Advertisement
zmatt

uio-mmap.h

May 27th, 2020
1,176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.30 KB | None | 0 0
  1. #pragma once
  2. #include <sys/mman.h>
  3. #include <errno.h>
  4.  
  5. //-------------- UIO memory mapping ------------------------------------------//
  6. //
  7. // All functions here return NULL (and set errno) on failure.
  8. //
  9. // UIO abuses the offset parameter of mmap() to specify the memory region index.
  10. //
  11. // NOTE: instead of hardcoding memory region indices you really ought to try to
  12. // look them up by name via sysfs, where you can also find the size and physical
  13. // address for each region.  This is left as an exercise for the reader.
  14.  
  15. // Map memory region of given size.
  16. //
  17. inline void *uio_mmap( int fd, int index, size_t size, bool readonly = false )
  18. {
  19.     static int const MAX_UIO_MAPS = 5;
  20.     static int const page_size = getpagesize();
  21.  
  22.     size += -size & ( page_size - 1 );  // round up to multiple of page size
  23.  
  24.     if( index < 0 || index >= MAX_UIO_MAPS || size == 0 ) {
  25.         errno = EINVAL;
  26.         return NULL;
  27.     }
  28.  
  29.     int prot = PROT_READ | ( readonly ? 0 : PROT_WRITE );
  30.     void *ptr = mmap( NULL, size, prot, MAP_SHARED, fd, index * page_size );
  31.     if( ptr == MAP_FAILED )
  32.         return NULL;
  33.  
  34.     assert( ptr != NULL );
  35.     return ptr;
  36. }
  37.  
  38. // Map memory region of given type T.
  39. //
  40. template< typename T >
  41. T *uio_mmap( int fd, int index, bool readonly = false )
  42. {
  43.     return (T *)uio_mmap( fd, index, sizeof(T), readonly );
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement