-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphysical.c
More file actions
47 lines (42 loc) · 1.28 KB
/
physical.c
File metadata and controls
47 lines (42 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include "physical.h"
// Open /dev/mem to give access to physical addresses
int open_physical(int fd) {
if (fd == -1) {
// check if already open
if ((fd = open("/dev/mem", (O_RDWR | O_SYNC))) == -1) {
printf("ERROR: could not open \"/dev/mem\"...\n");
return -1;
}
}
return fd;
}
// Close /dev/mem to give access to physical addresses
void close_physical(int fd) {
close(fd);
}
// Establish a virtual address mapping for the physical addresses
// starting at base and extending by span bytes
void * map_physical(int fd, unsigned int base, unsigned int span) {
void * virtual_base;
// Get a mapping from physical addresses to virtual addresses
virtual_base = mmap(NULL, span, (PROT_READ | PROT_WRITE), MAP_SHARED, fd, base);
if (virtual_base == MAP_FAILED) {
printf("ERROR: mmap() failed...\n");
close(fd);
return NULL;
}
return virtual_base;
}
// Close the previously-opened virtual address mapping
int unmap_physical(void * virtual_base, unsigned int span) {
if (munmap (virtual_base, span) != 0) {
printf("ERROR: munmap() failed...\n");
return -1;
}
return 0;
}