1 /*
2 * Copyright (C) 2025 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "dma_swap.h"
17 #include <fcntl.h>
18 #include <unistd.h>
19 #include <sys/ioctl.h>
20 #include <sys/mman.h>
21 #include "avcodec_errors.h"
22 #include "avcodec_log.h"
23
24 namespace OHOS {
25 namespace MediaAVCodec {
26 namespace Codec {
27 namespace {
28 constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, LOG_DOMAIN_FRAMEWORK, "CODEC_UTILS"};
29 #define DMA_DEVICE_FILE "/dev/dma_reclaim"
30 #define DMA_BUF_RECLAIM_IOC_MAGIC 'd'
31 #define DMA_BUF_RECLAIM_FD _IOWR(DMA_BUF_RECLAIM_IOC_MAGIC, 0x07, int)
32 #define DMA_BUF_RESUME_FD _IOWR(DMA_BUF_RECLAIM_IOC_MAGIC, 0x08, int)
33 } // namespace
34
DmaSwaper()35 DmaSwaper::DmaSwaper()
36 {
37 CHECK_AND_RETURN_LOG(reclaimDriverFd_ <= 0, "Already initialized!");
38 reclaimDriverFd_ = open(DMA_DEVICE_FILE, O_RDWR | O_CLOEXEC | O_NONBLOCK);
39 CHECK_AND_RETURN_LOG(reclaimDriverFd_ > 0, "Fail to open device!");
40 }
41
~DmaSwaper()42 DmaSwaper::~DmaSwaper()
43 {
44 CHECK_AND_RETURN_LOG(reclaimDriverFd_ > 0, "Invalid fd!");
45 close(reclaimDriverFd_);
46 reclaimDriverFd_ = -1;
47 }
48
SwapOutDma(pid_t pid,int32_t bufFd)49 int32_t DmaSwaper::SwapOutDma(pid_t pid, int32_t bufFd)
50 {
51 CHECK_AND_RETURN_RET_LOG(reclaimDriverFd_ > 0, AVCS_ERR_UNKNOWN, "reclaimDriverFd_ <= 0!");
52 CHECK_AND_RETURN_RET_LOG(pid > 0, AVCS_ERR_UNKNOWN, "pid <= 0!");
53 CHECK_AND_RETURN_RET_LOG(bufFd > 0, AVCS_ERR_UNKNOWN, "bufFd <= 0!");
54 DmaBufIoctlSwPara param {
55 .pid = pid,
56 .ino = 0,
57 .fd = bufFd
58 };
59 AVCODEC_LOGI("SwapOutDma do ioctl!");
60 return ioctl(reclaimDriverFd_, DMA_BUF_RECLAIM_FD, ¶m);
61 }
62
SwapInDma(pid_t pid,int32_t bufFd)63 int32_t DmaSwaper::SwapInDma(pid_t pid, int32_t bufFd)
64 {
65 CHECK_AND_RETURN_RET_LOG(reclaimDriverFd_ > 0, AVCS_ERR_UNKNOWN, "reclaimDriverFd_ <= 0!");
66 CHECK_AND_RETURN_RET_LOG(pid > 0, AVCS_ERR_UNKNOWN, "pid <= 0!");
67 CHECK_AND_RETURN_RET_LOG(bufFd > 0, AVCS_ERR_UNKNOWN, "bufFd <= 0!");
68 DmaBufIoctlSwPara param {
69 .pid = pid,
70 .ino = 0,
71 .fd = bufFd
72 };
73 AVCODEC_LOGI("SwapInDma do ioctl!");
74 return ioctl(reclaimDriverFd_, DMA_BUF_RESUME_FD, ¶m);
75 }
76
GetInstance()77 DmaSwaper &DmaSwaper::GetInstance()
78 {
79 static DmaSwaper swaper;
80 return swaper;
81 }
82 } // namespace Codec
83 } // namespace MediaAVCodec
84 } // namespace OHOS