xref: /linux/Documentation/driver-api/cxl/allocation/dax.rst (revision 746680ec6696585e30db3e18c93a63df9cbec39c)
1.. SPDX-License-Identifier: GPL-2.0
2
3===========
4DAX Devices
5===========
6CXL capacity exposed as a DAX device can be accessed directly via mmap.
7Users may wish to use this interface mechanism to write their own userland
8CXL allocator, or to managed shared or persistent memory regions across multiple
9hosts.
10
11If the capacity is shared across hosts or persistent, appropriate flushing
12mechanisms must be employed unless the region supports Snoop Back-Invalidate.
13
14Note that mappings must be aligned (size and base) to the dax device's base
15alignment, which is typically 2MB - but maybe be configured larger.
16
17::
18
19  #include <stdio.h>
20  #include <stdlib.h>
21  #include <stdint.h>
22  #include <sys/mman.h>
23  #include <fcntl.h>
24  #include <unistd.h>
25
26  #define DEVICE_PATH "/dev/dax0.0" // Replace DAX device path
27  #define DEVICE_SIZE (4ULL * 1024 * 1024 * 1024) // 4GB
28
29  int main() {
30      int fd;
31      void* mapped_addr;
32
33      /* Open the DAX device */
34      fd = open(DEVICE_PATH, O_RDWR);
35      if (fd < 0) {
36          perror("open");
37          return -1;
38      }
39
40      /* Map the device into memory */
41      mapped_addr = mmap(NULL, DEVICE_SIZE, PROT_READ | PROT_WRITE,
42                         MAP_SHARED, fd, 0);
43      if (mapped_addr == MAP_FAILED) {
44          perror("mmap");
45          close(fd);
46          return -1;
47      }
48
49      printf("Mapped address: %p\n", mapped_addr);
50
51      /* You can now access the device through the mapped address */
52      uint64_t* ptr = (uint64_t*)mapped_addr;
53      *ptr = 0x1234567890abcdef; // Write a value to the device
54      printf("Value at address %p: 0x%016llx\n", ptr, *ptr);
55
56      /* Clean up */
57      munmap(mapped_addr, DEVICE_SIZE);
58      close(fd);
59      return 0;
60  }
61