DAX 裝置¶
作為 DAX 裝置公開的 CXL 容量可以直接透過 mmap 訪問。 使用者可能希望使用此介面機制來編寫自己的使用者空間 CXL 分配器,或者管理跨多個主機的共享或持久記憶體區域。
如果容量在主機之間共享或持久,則必須採用適當的重新整理機制,除非該區域支援窺探後失效。
請注意,對映必須與 dax 裝置的基本對齊方式對齊(大小和基址),這通常為 2MB,但可以配置得更大。
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#define DEVICE_PATH "/dev/dax0.0" // Replace DAX device path
#define DEVICE_SIZE (4ULL * 1024 * 1024 * 1024) // 4GB
int main() {
int fd;
void* mapped_addr;
/* Open the DAX device */
fd = open(DEVICE_PATH, O_RDWR);
if (fd < 0) {
perror("open");
return -1;
}
/* Map the device into memory */
mapped_addr = mmap(NULL, DEVICE_SIZE, PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0);
if (mapped_addr == MAP_FAILED) {
perror("mmap");
close(fd);
return -1;
}
printf("Mapped address: %p\n", mapped_addr);
/* You can now access the device through the mapped address */
uint64_t* ptr = (uint64_t*)mapped_addr;
*ptr = 0x1234567890abcdef; // Write a value to the device
printf("Value at address %p: 0x%016llx\n", ptr, *ptr);
/* Clean up */
munmap(mapped_addr, DEVICE_SIZE);
close(fd);
return 0;
}