-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.h
64 lines (51 loc) · 1.29 KB
/
map.h
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#pragma once
#ifndef MAP_H
#define MAP_H
#include <sys/mman.h>
#include <fcntl.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "cell.h"
/* Issue standard error message and terminate */
static inline void die(const char *restrict str) {
perror(str);
exit(EXIT_FAILURE);
}
static struct Cell *map_open(const char *restrict path, bool rw, bool seq) {
int fd;
/* Open map file */
if (rw)
fd = open(path, O_RDWR | O_CREAT, 0600);
else
fd = open(path, O_RDONLY);
if (fd < 0)
die("open");
if (rw) {
/* Lock the file */
if (lockf(fd, F_TLOCK, SIZE))
die("lockf");
/* Truncate map file to the correct size */
if (ftruncate(fd, SIZE))
die("ftruncate");
/* Allocate file space */
if (posix_fallocate(fd, 0, SIZE))
die("posix_fallocate");
}
else {
if (lseek(fd, 0, SEEK_END) != SIZE) {
fputs("Invalid file size!\n", stderr);
exit(EXIT_FAILURE);
}
}
/* Memory-map it */
struct Cell *map = mmap((void *) 0, SIZE, rw ? PROT_READ | PROT_WRITE : PROT_READ, MAP_SHARED, fd, 0);
if (map == MAP_FAILED)
die("mmap");
/* We will need the pages immediately */
if (posix_madvise(map, SIZE, seq ? POSIX_MADV_SEQUENTIAL | POSIX_MADV_WILLNEED : POSIX_MADV_RANDOM | POSIX_MADV_WILLNEED))
die("posix_madvise");
return map;
}
#endif