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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
|
//
// = Meta Allocator =
//
// Please read the full documentation of the allocation strategy to understand
// what's going on here at a high level: /doc/0/A-memory.html
//
// That said, a few quick implementation notes follow.
//
// == Slabs and their watermarks ==
//
// We use an i32 for slab watermarks so we can simply let it overflow on the
// last valid allocation; the next allocation attempt will then see that it's
// negative, and panic.
//
// It's actually stored as a u32 anyway, because Zig is annoying.
//
// The watermark is counted in 8-byte units. If you do the math, you'll notice
// that this means the slabs are limited to 16 GiB each (2^31 units because i32;
// 8 bytes each) for a 256 GiB total, since we have 16 size classes.
//
// Using 8-byte units means free conversion to byte-based addresses thanks to
// instructions like LEA or the ARM barrel shifter. Using size class sized
// units would require additional shift instructions and seems unnecessary.
//
// The global slab watermark of a size class is bumped in chunks, reserving a
// number of slots for the thread that performed the bump. This way, threads
// don't need to perform any atomic operations for most allocations.
//
// == Free-lists and free slot cache arrays ==
//
// For each size class there's a global free-list that uses the freed memory
// slots themselves as intrusive linked lists with an inline array, so we can
// directly store a chunk of indexes. Concretely, nodes of this linked list
// have the following format:
//
// {
// next_head_idx: u32,
// extra_idx_count: u32,
// pad_to_64_bytes: [7]u64,
// extra_idx_array: [32]u32,
// }
//
// So, it's not a typical free-list where each node simply points to the next
// entry; rather, each node is the first of a chunk of 1+N entries, where the
// indexes of the N extra entries are inlined into the head node.
//
// Each thread also has a small static thread-local array of indexes of most
// recently freed slots. This makes alloc/free extremely efficient in common
// cases. We fill/empty half of this array from/to the global free-list when
// it's empty/full; this is how the chunks in the global free-list are formed.
//
// == Monomorphization (or lack thereof) over size class values ==
//
// Given that we have a small-ish static number of size classes, we could make
// alloc and free generic and be monomorphized, having various per size class
// constants baked into each. However, this doesn't seem worth it, as these
// constants are efficiently calculated in a small handful of instructions.
// Further, we need a dynamic version anyway for when the size class is only
// known at run-time.
//
// The compiler may still decide to emit specialized versions of alloc/free
// based on statically known size class parameters, but we don't force it.
//
const std = @import("std");
/// Size classes.
const SIZES: [16]comptime_int = .{
// Important: Ensure the smallest size class is inherently immune to false
// sharing, and no smaller than: 64 + 4 * ( RESERVE_MAX / 2 ) many bytes.
// That's 192 bytes assuming RESERVE_MAX = 64 (see below).
256,
512,
1024,
1024 * 2,
1024 * 4,
1024 * 8,
1024 * 16,
1024 * 32,
1024 * 64,
1024 * 128,
1024 * 256,
1024 * 512,
1024 * 1024,
1024 * 1024 * 2,
1024 * 1024 * 4,
1024 * 1024 * 8,
};
/// Gets the index [0,15] of a size class, from the size value, returning a
/// value greater than 15 if the size is beyond the largest size class.
inline fn getSizeClassIndex(size: usize) u8 {
const min: u32 = SIZES[0];
return @ctz(size >> @ctz(min));
}
/// The length of each slab in 8-byte units.
const SLAB_LEN: u32 = 0x8000_0000;
/// Pointer to start of all 16 slabs as a contiguous vmem block.
var slabs: *[SIZES.len][SLAB_LEN]u64 = undefined;
/// Free-list head pointer with ABA counter.
const FlHead = packed struct(u64) {
// Putting aba first leads to slightly better codegen.
aba: u32,
idx: u32,
};
/// Global shared metadata per slab / size class.
const SlabInfo = struct {
/// Force cache line alignment to prevent false sharing.
_: void align(std.atomic.cache_line) = {},
/// Head of shared free-list for the size class; index value SLAB_LEN is
/// used to mean NULL, since it's an invalid slab index.
free_list: FlHead = .{ .aba = 0, .idx = SLAB_LEN },
/// Global slab watermark: Start address of unused vmem, as 8-byte index.
watermark: u32 = 0,
};
/// Global shared metadata per slab / size class.
var slab_infos: [SIZES.len]SlabInfo = @splat(.{});
/// Maximum number of slots reserved for a thread.
const RESERVE_MAX = 64;
/// Given a size class index 0 to 15, returns the number of slots that threads
/// should keep in reserve for that size class. This starts at RESERVE_MAX for
/// the smallest class, and is halved every four size classes. This number is
/// used both for deciding how much to bump the global watermark of a slab to
/// reserve memory for a thread, and to determine the maximum count of entries
/// stored in the thread's free slot cache for that size class.
inline fn reserveCountForSizeClassIndex(sci: u8) u32 {
return @as(u8, RESERVE_MAX) >> @intCast(sci / 4);
}
/// Thread-local metadata per slab / size class.
const TlSlabInfo = struct {
/// Free slot cache; align to cache line to prevent false sharing and for
/// possible SIMD related benefits.
fc: [RESERVE_MAX]u32 align(std.atomic.cache_line) = @splat(0),
/// Current count of entries in free slot cache.
fc_count: u32 = 0,
/// Start point of memory reserved for this thread.
wm_lo: u32 = 0,
/// End point of memory reserved for this thread.
wm_hi: u32 = 0,
};
/// Thread-local metadata per slab / size class.
threadlocal var tl_slab_infos: [SIZES.len]TlSlabInfo = @splat(.{});
/// Wrapper around std.posix.mmap().
fn mmap(size: usize) []align(4096) u8 {
return std.posix.mmap(
null,
size,
.{ .READ = true, .WRITE = true },
.{ .TYPE = .PRIVATE, .ANONYMOUS = true },
-1,
0,
) catch @panic("Syscall mmap() failed.");
}
/// Must call this once to initialize the slabs.
export fn init() void {
slabs = @ptrCast(mmap(SIZES.len * SLAB_LEN * 8));
}
/// Allocate a slot of the given size, which must be a power of two and greater
/// than or equal to the smallest size class. If it's greater than the largest
/// size class, this will fall back to an mmap() syscall.
export fn alloc(size: usize) [*]u8 {
// Can't allocate size that isn't power of two.
std.debug.assert(@popCount(size) == 1);
// Can't allocate below smallest size class.
std.debug.assert(size >= SIZES[0]);
const sci = getSizeClassIndex(size);
if (sci < SIZES.len) {
@branchHint(.likely);
const slot_ptr = alloc_size_class(sci, size);
return @ptrCast(slot_ptr);
} else {
return mmap(size).ptr;
}
}
/// Free memory that was returned by alloc().
export fn free(size: usize, ptr: [*]u8) void {
std.debug.assert(@popCount(size) == 1);
std.debug.assert(size >= SIZES[0]);
const sci = getSizeClassIndex(size);
if (sci < SIZES.len) {
@branchHint(.likely);
free_size_class(sci, @ptrCast(@alignCast(ptr)));
} else {
std.posix.munmap(@alignCast(ptr[0..size]));
}
}
fn alloc_size_class(sci: u8, size: usize) [*]u64 {
std.debug.assert(sci < SIZES.len);
const tl = &tl_slab_infos[sci];
const slab: [*]u64 = &slabs[sci];
// Reuse from thread-local free cache.
if (tl.fc_count > 0) {
tl.fc_count -= 1;
const idx = tl.fc[tl.fc_count];
return slab[idx..];
}
// The size in 8-byte slab/watermark units.
const wm_units: u32 = @intCast(size / 8);
// Use part of the reserved memory for this thread.
if (tl.wm_lo < tl.wm_hi) {
const idx = tl.wm_lo;
tl.wm_lo += wm_units;
return slab[idx..];
}
// Try to transfer a chunk from the global free-list.
const info = &slab_infos[sci];
if (alloc_from_fl(slab, info, tl)) |p| return p;
const res_n = reserveCountForSizeClassIndex(sci);
return alloc_fresh(size, slab, info, tl, wm_units, res_n);
}
fn alloc_from_fl(
slab: [*]u64,
info: *SlabInfo,
tl: *TlSlabInfo,
) ?[*]u64 {
var ptr: [*]u64 = undefined;
var arr: [*]u32 = undefined;
var fl_head = @atomicLoad(FlHead, &info.free_list, .acquire);
while (true) : (std.atomic.spinLoopHint()) {
// Checking for >= SLAB_LEN is optimal; it'll just test the sign bit.
if (fl_head.idx >= SLAB_LEN) return null;
ptr = slab[fl_head.idx..];
arr = @ptrCast(ptr);
// Load this atomically since it's still globally accessible memory;
// unordered is fine since we discard it if the following CAS fails.
const next_head = @atomicLoad(u32, &arr[0], .unordered);
fl_head = @cmpxchgWeak(
FlHead,
&info.free_list,
fl_head,
.{ .aba = fl_head.aba +% 1, .idx = next_head },
.release,
.acquire,
) orelse break;
}
// Now detached from global; no need for atomics anymore.
tl.fc_count = arr[1];
// We can safely copy more than needed since we set fc_count; this way it
// should compile neatly into SIMD instructions.
for (0..RESERVE_MAX / 2) |i| tl.fc[i] = arr[8 + i];
return ptr;
}
fn alloc_fresh(
size: usize,
slab: [*]u64,
info: *SlabInfo,
tl: *TlSlabInfo,
wm_units: u32,
res_n: u32,
) [*]u64 {
// Have to use fresh memory from the top of the slab; bump it by a chunk,
// atomically, to reserve memory for this thread.
const bump = res_n * wm_units;
const old_wm = @atomicRmw(u32, &info.watermark, .Add, bump, .monotonic);
const new_wm = old_wm + bump;
// Check only if the old WM was already overflown; chunk count is such that
// it's always safe to bump by a chunk if the old WM was still valid, since
// wm_units, res_n, and slab length are all powers of two.
if (old_wm >= SLAB_LEN) {
std.debug.panic("Exhausted slab for size class: {}", .{size});
}
tl.wm_hi = new_wm;
tl.wm_lo = old_wm + wm_units;
return slab[old_wm..];
}
fn free_size_class(sci: u8, ptr: [*]u64) void {
std.debug.assert(sci < SIZES.len);
const tl = &tl_slab_infos[sci];
const slab: [*]u64 = &slabs[sci];
const idx: u32 = @intCast(ptr - slab);
const res_n = reserveCountForSizeClassIndex(sci);
// Still some space in the local free slot cache.
if (tl.fc_count != res_n) {
tl.fc[tl.fc_count] = idx;
tl.fc_count += 1;
return;
}
// Local cache full; need to flush some to global free-list.
const info = &slab_infos[sci];
free_into_fl(info, tl, ptr, idx, res_n);
}
fn free_into_fl(
info: *SlabInfo,
tl: *TlSlabInfo,
ptr: [*]u64,
idx: u32,
res_n: u32,
) void {
const arr: [*]u32 = @ptrCast(ptr);
const half = res_n / 2;
// Intuitively, this belongs to the end, but it doesn't matter; the rest of
// this function is not allowed to fail anyway.
tl.fc_count = half;
// No need for atomic stores; we own this memory exclusively right now,
// unless another thread calls free() on the same slot which is a bug.
arr[1] = half;
// Safe to copy more than needed; should compile into SIMD.
for (0..RESERVE_MAX / 2) |i| arr[8 + i] = tl.fc[half + i];
// Now atomically announce the new free-list head to global visibility.
var fl_head = @atomicLoad(FlHead, &info.free_list, .acquire);
while (true) : (std.atomic.spinLoopHint()) {
// Still owned exclusively; no need for atomic store.
arr[0] = fl_head.idx;
fl_head = @cmpxchgWeak(
FlHead,
&info.free_list,
fl_head,
.{ .aba = fl_head.aba +% 1, .idx = idx },
.release,
.acquire,
) orelse break;
}
}
|