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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
|
/*
* Copyright (C) 2025 dwlr <dweller@cabin.digital>
*
* BSD 3-Clause License (BSD-3-Clause)
* See LICENSE for details
*/
typedef struct
{
u8* base;
u8* cursor;
usize size;
} arena;
typedef struct
{
u8* base;
ssize pages;
} do_pagefault_args;
void* do_pagefault(void* arg)
{
ssize i = 0;
ssize p = mm_pagesize();
do_pagefault_args* args = (do_pagefault_args*)arg;
if(!args)
{
report(ERR, "do_pagefault() with NULL args!\n");
return NULL;
}
for(i = 0; i < args->pages; i++) args->base[p * i] = 0;
return NULL;
}
bool ar_create(usize size, bool prefault, arena* ar)
{
ssize p = mm_pagesize();
if(!ar) return false;
if(size <= 0) return false;
size += (size % p) ? (p - (size % p)) : 0;
ar->base = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
if(ar->base == MAP_FAILED) return false;
ar->size = size;
ar->cursor = ar->base;
if(prefault)
{
ssize i = 0;
ssize cpus = cpu_count();
pthread_t* t = NULL;
do_pagefault_args* args = NULL;
t = calloc(cpus, sizeof(t[0]));
if(!t) report(FATAL, "ar_create()/prefault/calloc(t) failed!\n");
else
{
args = calloc(cpus, sizeof(args[0]));
if(!args)
{
free(t);
report(FATAL, "ar_create()/prefault/calloc(args) failed!\n");
}
}
for(i = 1; i < cpus; i++)
{
args[i].base = ar->base + ((size / cpus) * i);
args[i].pages = ((size / p) / cpus);
pthread_create(&t[i], NULL, do_pagefault, &args[i]);
}
args[0].base = ar->base;
args[0].pages = ((size / p) / cpus);
do_pagefault(&args[0]);
for(i = 1; i < cpus; i++) pthread_join(t[i], NULL);
free(args);
free(t);
}
return true;
}
#define ar_push(ar, sz) ar_pusha((ar), (sz), sizeof(int), true)
void* ar_pusha(arena* ar, usize size, usize alignment, bool zero)
{
usize cur, ovfl;
if(!ar) return NULL;
else
{
cur = align((usize)ar->cursor, alignment);
ovfl = (cur + size);
if(ovfl < cur) return NULL;
if(ovfl <= (usize)(ar->base + ar->size))
{
ar->cursor = (u8*)ovfl;
if(zero) memset((u8*)cur, 0, size);
return (u8*)cur;
}
else
{
report(ERR, "arena(%P): overflow @ %P x %llu\n", ar, cur, size);
return NULL;
}
}
}
void ar_pop(arena* ar, usize size)
{
if(!ar) return;
else ar->cursor = min(ar->base, ar->cursor - size);
}
void ar_clear(arena* ar)
{
if(ar) ar->cursor = ar->base;
}
void ar_destroy(arena* ar)
{
if(!ar) return;
munmap(ar->base, ar->size);
ar->base = ar->cursor = NULL;
ar->size = 0;
}
|