MMAP and MUNMAP

Mmap() is a system call to map a file content in application address space. This are needed if we want to read or write file content directly from memory instead of file read/write.

Source Code

Mapping file content using mmap and reading content by dereferencing pointer is very common example. We are doing something different here. We are mapping MMIO memory using /dev/mem device. Linux has memory device to map system and MMIO memory address space. Once address range is mapped to user space then we can alter MMIO register with simple pointer operations. This mechanism is very common for accessing in embedded system for accessing GPIO and MMIO registers directly from user mode. We have used a ARM9 board and figured out GPIO pin which can be set to high or low. We connected a LED with 1K resistor to ground. We are toggling MMIO register bit and LED will blink as we are altering the bits.

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <string.h> 
#include <errno.h> 
#include <signal.h> 
#include <fcntl.h> 
#include <ctype.h> 
#include <termios.h> 
#include <sys/types.h> 
#include <sys/mman.h> 

#define LEDBASE 0x10000000
#define MAP_SIZE 4096UL 
#define LED_BIT 1

int main(int argc, char **argv) { 
  int fd; 
  void *map_base;
  unsigned char *led_val;
  off_t offset; 
 
   offset = LEDBASE; 

   if ((fd = open ("/dev/mem", O_RDWR | O_SYNC)) == -1) {
     
    printf ("/dev/mem not opened.\n");
    return -1;
  }

   map_base = mmap (0, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset); 
   if (map_base == (void *) -1) {
    close(fd);
    printf ("/dev/mem mapping failed.\n");
  }
  led_val = map_base;
  while(1)
  {
    printf ("LED is %s \n", (*led_val & 1) ? "On""Off");
    fflush (stdout); 
    sleep(1);
    printf ("Changing LED Status\n");
    fflush (stdout); 
    *led_val ^= LED_BIT;
    sleep(1);
    
  }

  if (munmap(map_base, MAP_SIZE) == -1) {
    printf("unmap failed\n");
  }
  close (fd); 
  return 0; 
}

About our authors: Team EQA

You have viewed 1 page out of 252. Your C learning is 0.00% complete. Login to check your learning progress.

#