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> 
10  #include <sys/types.h> 
11  #include <sys/mman.h> 
12 
13  #define LEDBASE 0x10000000
14  #define MAP_SIZE 4096UL 
15  #define LED_BIT 1
16 
17  int main(int argc, char **argv) { 
18    int fd; 
19    void *map_base;
20    unsigned char *led_val;
21    off_t offset; 
22   
23     offset = LEDBASE; 
24 
25     if ((fd = open ("/dev/mem", O_RDWR | O_SYNC)) == -1) {
26       
27      printf ("/dev/mem not opened.\n");
28      return -1;
29    }
30 
31     map_base = mmap (0, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset); 
32     if (map_base == (void *) -1) {
33      close(fd);
34      printf ("/dev/mem mapping failed.\n");
35    }
36    led_val = map_base;
37    while(1)
38    {
39      printf ("LED is %s \n", (*led_val & 1) ? "On""Off");
40      fflush (stdout); 
41      sleep(1);
42      printf ("Changing LED Status\n");
43      fflush (stdout); 
44      *led_val ^= LED_BIT;
45      sleep(1);
46      
47    }
48 
49    if (munmap(map_base, MAP_SIZE) == -1) {
50      printf("unmap failed\n");
51    }
52    close (fd); 
53    return 0; 
54  }

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

 Vote 0

Similar topics related to this section

fcntl, fputs,fgets,fgetc,fputc, printf, scanf, ioctl, mmap, DOS low level IO access, DOS BIOS int86, sleep/delay, sound, nosound,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan