Advertisement
milanmetal

[Linux C] Map reserved memory block

Mar 21st, 2018
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.01 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <fcntl.h>
  4. #include <stdint.h>
  5. #include <sys/mman.h>
  6. // Mapping to reserved DDR3 mmeory: 196MB / 0xC400000
  7. #define HW_REGS_BASE ( 196*1024*1024 )
  8.  
  9. // mapping address range 1MB
  10. #define HW_REGS_SPAN ( 0x100000 )
  11. #define HW_REGS_MASK ( HW_REGS_SPAN - 1 )
  12.  
  13. void HexDump( unsigned char * buffer, int bytes)
  14. {
  15.   int i;
  16.   for(i=0; i<bytes; i++)
  17.   {
  18.     if(i%16 == 0)
  19.     printf("\n [%04X] " , i);
  20.     printf("%02X " , buffer[i]);
  21.   }
  22.   printf( "\n");
  23. }
  24.  
  25. int main() {
  26.  
  27.   void *virtual_base;
  28.   int fd;
  29.  
  30.   // Broj bajta koje zelim da mapiram na fizicki adresni prostor i broj
  31.   // njih koje cu posle ispisati
  32.   int bytes_to_map  = 4;
  33.   int bytes_to_dump = 4;
  34.  
  35.   // map the address space for the LED registers into user space so we can interact with them.
  36.   // we'll actually map in the entire CSR span of the HPS since we want to access various registers within that span
  37.   if( ( fd = open( "/dev/mem", ( O_RDWR | O_SYNC ) ) ) == -1 ) {
  38.     printf( "ERROR: could not open \"/ dev/mem \"...\n" );
  39.     return(1);
  40.   }
  41.  
  42.   printf( "mapping DDR3 offset from 0x%X, range = 0x%X. \r\n" , HW_REGS_BASE, HW_REGS_SPAN);
  43.   //virtual_base = mmap( NULL, HW_REGS_SPAN, ( PROT_READ | PROT_WRITE ), MAP_SHARED, fd, HW_REGS_BASE );
  44.   virtual_base = mmap( NULL, bytes_to_map, ( PROT_READ | PROT_WRITE ), MAP_SHARED, fd, HW_REGS_BASE );
  45.  
  46.   if( virtual_base == MAP_FAILED ) {
  47.     printf( "ERROR: mmap() failed...\n" );
  48.     close( fd );
  49.     return(1);
  50.   }
  51.  
  52.   //HexDump(virtual_base, 0x40);
  53.   // Okej ovde mu kazem ispisi mi 8 bajta od ovih gore 16 koje si mapirao
  54.   // pocev od HW_REGS_BASE
  55.   HexDump(virtual_base, bytes_to_dump);
  56.  
  57.   // clean up our memory mapping and exit
  58.   // if( munmap( virtual_base, HW_REGS_SPAN ) != 0 ) {
  59.  
  60.   // Ovde unmap odradim kako bi virtuelne adrese vratio kernelu na raspolaganje.
  61.   if( munmap( virtual_base, bytes_to_map ) != 0 ) {
  62.     printf( "ERROR: munmap() failed...\n" );
  63.     close( fd );
  64.     return(1);
  65.   }
  66.   close( fd );
  67.   return(0);
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement