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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
|
//
// = Meta Allocator =
//
// Read the full documentation of the allocation strategy to understand what's
// going on here at a high level: Chapter 0, Appendix A
//
// 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 that many (but not all) of the conversions to byte
// based addresses are effectively free thanks to instructions like LEA or the
// ARM barrel shifter. Using size class sized units would only require a few
// more shift instructions here and there, but seems unnecessary.
//
// Downsizing units to one byte would shave off an instruction here and there,
// and decrease vmem to 32 GiB (2 per slab), but that may be too restrictive.
//
// 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: [14]u32,
// extra_idx_array: [16]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.
//
// == Vacancy-lists ==
//
// For each size class, there's a global vacancy-list, whose entries store
// information about large contiguous segments of memory that are below the
// watermark yet completely vacant and need not be backed by physical memory.
//
// Currently, the only purpose of this is recording the region of memory a
// thread had reserved by bumping the global watermark, when that thread is
// terminated. We only do this if the remaining reserved memory spans over
// multiple pages of memory, since in that case it would need faulting in if
// given out to application code. The free-list represents slots that were
// already given out and then freed, meaning they were probably faulted in
// already when the application wrote data into them.
//
// In the future, we may also implement a method of finding contiguous slots
// within the free-list that together span across pages, informing the kernel
// about the fact that it's not needed right now, and recording it within the
// vacancy-list.
//
// == 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");
/// The units of memory in which slabs are addressed.
const Unit = u64;
/// Integer that can hold a slab/unit index, plus one overflow bit.
const UnitIdx = u32;
/// Length of each slab, as in Unit count.
const SLAB_LEN: UnitIdx = 1 << 31;
/// A slab of memory.
const Slab = [SLAB_LEN]Unit;
/// A pointer to a slot of allocated memory; N units depending on size class.
const SlotPtr = [*]Unit;
/// Size classes.
const SIZES: [16]usize = .{
// Important: Ensure the smallest size class is inherently immune to false
// sharing, and no smaller than: 64 + @sizeOf(UnitIdx) * ( FSC_MAX / 2 ).
// That's exactly 128 bytes assuming FSC_MAX = 32 (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 to 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 {
// Can't handle size that isn't power of two or below smallest size class.
if (@popCount(size) != 1) @panic("Only powers of two supported.");
if (size < SIZES[0]) @panic("Can't alloc below smallest size.");
return @ctz(size >> @ctz(SIZES[0]));
}
/// Pointer to start of all slabs as a contiguous array.
var slabs: *[SIZES.len]Slab = undefined;
/// Linked-list head pointer with ABA counter.
const ListHead = packed struct(u64) {
// Putting aba first leads to slightly better codegen.
aba: UnitIdx,
idx: UnitIdx,
};
/// 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: ListHead = .{ .aba = 0, .idx = SLAB_LEN },
/// Head of shared vacancy-list for the size class; index value SLAB_LEN
/// used to mean NULL, since it's an invalid slab index.
vacancy_list: ListHead = .{ .aba = 0, .idx = SLAB_LEN },
/// Global slab watermark: Start address of unused vmem, as 8-byte index.
watermark: UnitIdx = 0,
};
/// Global shared metadata per slab / size class.
var slab_infos: [SIZES.len]SlabInfo = @splat(.{});
/// Maximum number of slots reserved by a thread when bumping a slab watermark.
/// Halved after every two size classes, so make sure it's >= 128.
const RESERVE_MAX: UnitIdx = 512; // Results in 4 for the two largest classes.
/// Maximum number of free slot cache entries before half of them are flushed.
/// Halved after every four size classes, so make sure it's >= 8.
const FSC_MAX: UnitIdx = 32; // Results in 4 for the two largest classes.
/// Given a size class index 0 to 15, returns the number of slots that a thread
/// should reserve every time it needs to bump the global watermark. Starts at
/// RESERVE_MAX and is halved after every two size classes.
inline fn reserveCountForSizeClassIndex(sci: u8) UnitIdx {
return RESERVE_MAX >> @intCast(sci / 2);
}
/// Given a size class index 0 to 15, returns the maximum number of entries in
/// the free slot cache of a thread before half of them are flushed. Starts at
/// FSC_MAX and is halved after every four size classes.
inline fn maxFscCountForSizeClassIndex(sci: u8) UnitIdx {
return FSC_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.
fsc: [FSC_MAX]UnitIdx align(std.atomic.cache_line) = @splat(0),
/// Current count of entries in free slot cache.
fsc_count: UnitIdx = 0,
/// Start point of memory reserved for this thread.
wm_lo: UnitIdx = 0,
/// End point of memory reserved for this thread.
wm_hi: UnitIdx = 0,
};
/// Thread-local metadata per slab / size class.
threadlocal var tl_slab_infos: [SIZES.len]TlSlabInfo = @splat(.{});
/// Wrapper around the platform's mmap() or equivalent. The 'commit' argument
/// indicates whether read/write access should already be enabled. If false,
/// one must later use mcommit() to enable part or all of it.
fn mmap(size: usize, commit: bool) [*]align(4096) u8 {
// TODO: MS Windows
const ret = std.c.mmap(
null,
size,
.{ .READ = commit, .WRITE = commit },
.{ .TYPE = .PRIVATE, .ANONYMOUS = true },
-1,
0,
);
if (ret == std.c.MAP_FAILED) {
// TODO: Report reason.
@panic("Failed to map memory.");
}
return @ptrCast(@alignCast(ret));
}
/// Signal to the platform that we now require slab[0..idx] to be accessible.
fn mcommit(slab: *Slab, idx: UnitIdx) void {
// TODO: MS Windows
const ptr: *align(4096) anyopaque = @ptrCast(@alignCast(slab));
const len: usize = idx * @sizeOf(Unit);
const ret = std.c.mprotect(
ptr,
len,
.{ .READ = true, .WRITE = true },
);
if (ret == -1) {
// TODO: Report reason.
@panic("Failed to commit memory.");
}
}
/// Signal to the platform that slab[idx..len] can be discarded, so it doesn't
/// need physical backing memory until we write to it again. This does *not*
/// undo mcommit(), so there is no need to call it again.
fn mdiscard(ptr: [*]const u8, len: usize) void {
// TODO: MS Windows
const ret = std.c.madvise(
ptr,
len,
std.c.MADV.DONTNEED,
);
// Practically can't happen.
std.debug.assert(ret != -1);
}
/// Must call this once to initialize the slabs.
export fn init() void {
slabs = @ptrCast(mmap(SIZES.len * SLAB_LEN * @sizeOf(Unit), false));
}
/// 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 {
const sci = getSizeClassIndex(size);
if (sci < SIZES.len) {
@branchHint(.likely);
return @ptrCast(alloc_size_class(sci, size));
} else {
return mmap(size, true);
}
}
/// Free memory of a specific size that was returned by alloc().
export fn free(size: usize, ptr: [*]u8) void {
const sci = getSizeClassIndex(size);
if (sci < SIZES.len) {
@branchHint(.likely);
free_size_class(sci, @ptrCast(@alignCast(ptr)));
} else {
const ret = std.c.munmap(@ptrCast(@alignCast(ptr)), size);
// Practically can't happen.
std.debug.assert(ret != -1);
}
}
/// Free memory that was returned by alloc(), calculating the size class from
/// the pointer address, which is only possible if it lies within one of the
/// managed slabs. If this pointer came from a call to alloc() with a size
/// greater than the largest size class, this function will panic.
export fn free_auto(ptr: [*]u8) void {
const paddr = @intFromPtr(ptr);
const saddr = @intFromPtr(slabs);
if (paddr < saddr) {
@panic("Invalid pointer passed to free_auto().");
}
const uaddr = paddr - saddr;
const uidx = uaddr / @sizeOf(Unit);
const sci = uidx / SLAB_LEN;
if (sci >= SIZES.len) {
@panic("Invalid pointer passed to free_auto().");
}
free_size_class(@intCast(sci), @ptrCast(@alignCast(ptr)));
}
fn alloc_size_class(sci: u8, size: usize) SlotPtr {
std.debug.assert(sci < SIZES.len);
const tl = &tl_slab_infos[sci];
const slab: *Slab = &slabs[sci];
// Reuse from thread-local free cache.
if (tl.fsc_count > 0) {
tl.fsc_count -= 1;
const idx = tl.fsc[tl.fsc_count];
return slab[idx..].ptr;
}
// The length of a slot in Units.
const slot_len: UnitIdx = @intCast(size / @sizeOf(Unit));
// Use part of the reserved memory for this thread.
if (tl.wm_lo < tl.wm_hi) {
const idx = tl.wm_lo;
tl.wm_lo += slot_len;
return slab[idx..].ptr;
}
const info = &slab_infos[sci];
// Try to transfer a chunk from the global free-list.
if (alloc_from_fl(slab, info, tl)) |p| return p;
// Check the vacancy-list.
if (alloc_from_vl(slab, info, tl, slot_len)) |p| return p;
const res_n = reserveCountForSizeClassIndex(sci);
return alloc_fresh(size, slab, info, tl, slot_len, res_n);
}
fn alloc_from_fl(
slab: *Slab,
info: *SlabInfo,
tl: *TlSlabInfo,
) ?SlotPtr {
var ptr: SlotPtr = undefined;
var arr: [*]UnitIdx = undefined;
var fl_head = @atomicLoad(ListHead, &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..].ptr;
arr = @ptrCast(@alignCast(ptr));
// Load this atomically since it's still globally accessible memory;
// unordered is fine since we discard it if the cmpxchg below fails.
const next_head = @atomicLoad(UnitIdx, &arr[0], .unordered);
fl_head = @cmpxchgWeak(
ListHead,
&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.fsc_count = arr[1];
// We can safely copy more than needed since we set fsc_count.
const half_max = FSC_MAX / 2;
@memcpy(tl.fsc[0..half_max], arr[16 .. 16 + half_max]);
return ptr;
}
fn alloc_from_vl(
slab: *Slab,
info: *SlabInfo,
tl: *TlSlabInfo,
slot_len: UnitIdx,
) ?SlotPtr {
// This is largely analogous to alloc_from_fl().
var idx: UnitIdx = undefined;
var ptr: SlotPtr = undefined;
var arr: [*]UnitIdx = undefined;
var vl_head = @atomicLoad(ListHead, &info.vacancy_list, .acquire);
while (true) : (std.atomic.spinLoopHint()) {
if (vl_head.idx >= SLAB_LEN) return null;
idx = vl_head.idx;
ptr = slab[idx..].ptr;
arr = @ptrCast(@alignCast(ptr));
const next_head = @atomicLoad(UnitIdx, &arr[0], .unordered);
vl_head = @cmpxchgWeak(
ListHead,
&info.vacancy_list,
vl_head,
.{ .aba = vl_head.aba +% 1, .idx = next_head },
.release,
.acquire,
) orelse break;
}
tl.wm_lo = idx + slot_len;
tl.wm_hi = arr[1];
return ptr;
}
fn alloc_fresh(
size: usize,
slab: *Slab,
info: *SlabInfo,
tl: *TlSlabInfo,
slot_len: UnitIdx,
res_n: UnitIdx,
) SlotPtr {
// 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 * slot_len;
const old_wm = @atomicRmw(UnitIdx, &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
// slot_len, res_n, and slab length are all powers of two.
if (old_wm >= SLAB_LEN) {
std.debug.panic("Exhausted slab for size class: {}", .{size});
}
mcommit(slab, new_wm);
tl.wm_hi = new_wm;
tl.wm_lo = old_wm + slot_len;
return slab[old_wm..].ptr;
}
fn free_size_class(sci: u8, ptr: SlotPtr) void {
std.debug.assert(sci < SIZES.len);
const tl = &tl_slab_infos[sci];
const slab: *Slab = &slabs[sci];
const idx: UnitIdx = @intCast(ptr - slab);
const fsc_lim = maxFscCountForSizeClassIndex(sci);
// Still some space in the local free slot cache?
if (tl.fsc_count != fsc_lim) {
tl.fsc[tl.fsc_count] = idx;
tl.fsc_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, fsc_lim / 2);
}
fn free_into_fl(
info: *SlabInfo,
tl: *TlSlabInfo,
ptr: SlotPtr,
idx: UnitIdx,
n: UnitIdx,
) void {
// Note: n = 0 is valid and must work.
std.debug.assert(n <= FSC_MAX / 2);
const arr: [*]UnitIdx = @ptrCast(@alignCast(ptr));
const split = tl.fsc_count - n;
tl.fsc_count = split;
// 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] = n;
// Safe to copy more than needed.
const max = FSC_MAX / 2;
@memcpy(arr[16 .. 16 + max], tl.fsc[split .. split + max]);
// Now atomically announce the new free-list head to global visibility.
var fl_head = @atomicLoad(ListHead, &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(
ListHead,
&info.free_list,
fl_head,
.{ .aba = fl_head.aba +% 1, .idx = idx },
.release,
.acquire,
) orelse break;
}
}
/// For every size class: Flushes the calling thread's free slot cache into the
/// global free-list, and remaining reserved memory into the vacancy-list; some
/// may be turned into slots in the free-list instead if the reserved memory is
/// not worth creating a vacancy-list entry for. A thread that intends to exit
/// must call this function before doing so, or else memory may be leaked.
export fn flush_thread_reserves() void {
var sci: u8 = 0;
var slot_len: UnitIdx = SIZES[0] / @sizeOf(Unit);
while (sci < SIZES.len) : ({
sci += 1;
slot_len *= 2;
}) {
const info = &slab_infos[sci];
const tl = &tl_slab_infos[sci];
const slab: *Slab = &slabs[sci];
// Given our chunked WM bumps and smallest size class, hi - lo > 4 KiB
// implies that there's at least one entire untouched page, as well as
// at least one >=256-byte slot before it, which can hold the metadata
// of the vacancy-list entry without faulting in an empty page.
if (tl.wm_hi - tl.wm_lo > 4096 / @sizeOf(Unit)) {
flush_to_vl(info, tl, slab);
}
const fsc_lim = maxFscCountForSizeClassIndex(sci);
const flush_max = fsc_lim / 2;
flush_to_fl(info, tl, slab, slot_len, fsc_lim, flush_max);
}
}
fn flush_to_vl(info: *SlabInfo, tl: *TlSlabInfo, slab: *Slab) void {
const idx = tl.wm_lo;
const ptr = slab[idx..].ptr;
const arr: [*]UnitIdx = @ptrCast(@alignCast(ptr));
arr[1] = tl.wm_hi;
var vl_head = @atomicLoad(ListHead, &info.vacancy_list, .acquire);
while (true) : (std.atomic.spinLoopHint()) {
arr[0] = vl_head.idx;
vl_head = @cmpxchgWeak(
ListHead,
&info.vacancy_list,
vl_head,
.{ .aba = vl_head.aba +% 1, .idx = idx },
.release,
.acquire,
) orelse break;
}
tl.wm_lo = tl.wm_hi;
}
fn flush_to_fl(
info: *SlabInfo,
tl: *TlSlabInfo,
slab: *Slab,
slot_len: UnitIdx,
fsc_lim: UnitIdx,
flush_max: UnitIdx,
) void {
// We could first flush the current fsc and then move on to splitting
// reserved memory, but this could result in an "undersized" chunk from
// the current fsc and then a second undersized chunk when we reach the
// end of reserved memory. A simple improvement is to do it this way
// around instead:
// Add remaining reserved memory to fsc in a loop, flushing every time
// we hit the fsc limit.
while (tl.wm_lo < tl.wm_hi) : (tl.wm_lo += slot_len) {
const idx = tl.wm_lo;
const ptr = slab[idx..].ptr;
if (tl.fsc_count == fsc_lim) {
free_into_fl(info, tl, ptr, idx, flush_max);
} else {
tl.fsc[tl.fsc_count] = idx;
tl.fsc_count += 1;
}
}
// Now flush the rest, in two iterations if necessary.
while (tl.fsc_count != 0) {
tl.fsc_count -= 1;
const idx = tl.fsc[tl.fsc_count];
const ptr = slab[idx..].ptr;
free_into_fl(info, tl, ptr, idx, @min(flush_max, tl.fsc_count));
}
}
|