bonus-edge-proxy/src/rknn_test/DmaBuffer.h

53 lines
1.2 KiB
C
Raw Normal View History

2026-01-16 18:18:17 +08:00
#include <fcntl.h>
#include <linux/dma-heap.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <iostream>
#include <string>
class DmaBuffer {
public:
int fd;
void* vaddr; // 虚拟地址仅供调试或CPU必须介入时使用如画字
size_t size;
DmaBuffer(size_t size, const std::string& heap_name = "/dev/dma_heap/system") {
this->size = size;
this->vaddr = MAP_FAILED;
this->fd = -1;
int heap_fd = open(heap_name.c_str(), O_RDONLY | O_CLOEXEC);
if (heap_fd < 0) {
perror("Failed to open dma heap");
return;
}
struct dma_heap_allocation_data data = {0};
data.len = size;
data.fd_flags = O_RDWR | O_CLOEXEC;
if (ioctl(heap_fd, DMA_HEAP_IOCTL_ALLOC, &data) < 0) {
perror("dma heap alloc failed");
close(heap_fd);
return;
}
this->fd = data.fd;
close(heap_fd);
// 如果需要CPU访问例如写OSD文字则映射否则可以不映射
this->vaddr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, this->fd, 0);
if (this->vaddr == MAP_FAILED) {
perror("mmap failed");
}
}
~DmaBuffer() {
if (vaddr != MAP_FAILED)
munmap(vaddr, size);
if (fd >= 0)
close(fd);
}
};