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
65
66
67
68
69
70
71
72
73
74
75
76
77
|
// examples/utils.c
#include <stddef.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include "utils.h"
struct cmmm__sv
mmap_whole (int fd)
{
struct cmmm__sv sv;
struct stat st;
int ret = fstat (fd, &st);
UNUSED (ret);
ASSERT_MSG (ret != -1, "fstat: %s", strerror (errno));
ASSERT (S_ISREG (st.st_mode));
posix_fadvise (fd, 0, st.st_size, POSIX_FADV_SEQUENTIAL |
POSIX_FADV_WILLNEED |
POSIX_FADV_NOREUSE);
sv.begin = mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE |
MAP_POPULATE |
MAP_NONBLOCK, fd, 0);
ASSERT_MSG (sv.begin != MAP_FAILED, "mmap: %s", strerror (errno));
posix_madvise ((void *) sv.begin, st.st_size, MADV_HUGEPAGE | MADV_WILLNEED);
sv.end = sv.begin + st.st_size;
return sv;
}
struct cmmm__sv
read_until_eof (ARENA arena, int fd)
{
struct arena__checkpoint checkpoint = arena__checkpoint (arena);
size_t reserve = 4096;
size_t read_total = 0;
for (;;) {
arena__reserve (arena, reserve, 1);
ssize_t bytes_read = read (fd,
arena__next_free (arena, 1),
arena__room (arena, 1));
if (bytes_read < 0) {
DEBUG ("fstat: %s", strerror (errno));
arena__rollback_to (arena, checkpoint);
return (struct cmmm__sv) {0};
}
if (bytes_read == 0)
break;
read_total += bytes_read;
arena__allocate_fast (arena, bytes_read, 1);
reserve *= 2;
}
if (arena->tail->free == checkpoint.free)
return (struct cmmm__sv) {0};
char *ptr = arena__coalesce_from_fast (arena, checkpoint, read_total);
return (struct cmmm__sv) {
.begin = ptr,
.end = ptr + read_total,
};
}
// examples/utils.c ends here
|