summaryrefslogtreecommitdiff
path: root/lib/std/bytealloc.myr
blob: 4cd2b6732743a595a0b641ab2e06cad35898d9cf (plain)
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
use sys

use "die"
use "extremum"
use "memops"
use "syswrap"
use "threadhooks"
use "types"
use "units"
use "result"
use "slfill"
use "backtrace"

pkg std =
	const startalloctrace	: (f : byte[:] -> void)
	const endalloctrace	: (-> void)

	const bytealloc		: (sz:size -> byte#)
	const zbytealloc	: (sz:size -> byte#)
	const bytefree		: (m:byte#, sz:size -> void)

	/* null pointers. only used internally. */
	pkglocal const Zslicep	= (0 : byte#)
	pkglocal const Align	= 16	/* minimum allocation alignment */

	pkglocal const align	: (m : std.size, align : std.size -> std.size)
	pkglocal const allocsz	: (sz : std.size -> std.size)

;;

const Zslab	= (0 : slab#)
const Zchunk	= (0 : chunk#)
const Slabsz 	= 512*KiB
const Cachemax	= 4
const Bktmax	= 128*KiB	/* a balance between wasted space and falling back to mmap */
const Pagesz	= 4*KiB

var buckets	: bucket[32] /* excessive */
var trace	: bool
var tracefd	: std.fd
var bigcache	: cacheelt[32]

type bucket = struct
	sz	: size	/* aligned size */
	nper	: size	/* max number of elements per slab */
	slabs	: slab#	/* partially filled or free slabs */
	cache	: slab# /* cache of empty slabs, to prevent thrashing */
	ncache	: size  /* size of cache */
;;

type slab = struct
	head	: byte#	/* head of virtual addresses, so we don't leak address space */
	next	: slab#	/* the next slab on the chain */
	prev	: slab#	/* the prev slab on the chain */
	freehd	: chunk#	/* the nodes we're allocating */
	nfree	: size	/* the number of free nodes */
	magic	: size	/* ensure we didn't index into the void */
;;

/* NB: must be smaller than sizeof(slab) */
type chunk = struct
	next	: chunk#	/* the next chunk in the free list */
;;

type cacheelt = struct
	sz	: std.size
	p	: byte#
;;

const __init__ = {
	for var i = 0; i < buckets.len && (Align << i) <= Bktmax; i++
		bktinit(&buckets[i], Align << i)
	;;
}

const startalloctrace = {path
	match openmode(path, Owrite | Ocreat, 0o644)
	| `Ok fd:	tracefd = fd
	| `Err e:	-> void
	;;
	trace = true
}

const endalloctrace = {
	std.close(tracefd)
	trace = false
}

const zbytealloc = {sz
	var p

	p = bytealloc(sz)
	memfill(p, 0, sz)
	-> p
}

const tracealloc = {p, sz
	var stk	: void#[23]	/* [type, addr, sz, 10 stack slots] */

	slfill(stk[:], (0 : void#))
	stk[0] = (0 : void#)
	stk[1] = (p : void#)
	stk[2] = (sz : void#)
	backtrace(stk[3:])
	writealloctrace(stk[:])
}

const tracefree = {p, sz
	var stk	: void#[3]

	stk[0] = (1 : void#)
	stk[1] = (p : void#)
	stk[2] = (sz : void#)
	writealloctrace(stk[:])
}

const writealloctrace = {sl
	var len, p

	len = sl.len * sizeof(void#)
	p = (sl : byte#)
	write(tracefd, p[:len])
}

/* Allocates a blob that is 'sz' bytes long. Dies if the allocation fails */
const bytealloc = {sz
	var bkt, p

	if sz <= Bktmax
		bkt = &buckets[bktnum(sz)]
		lock(memlck)
		p = bktalloc(bkt)
		unlock(memlck)
	else
		p = bigalloc(sz)
	;;
	if trace
		lock(memlck)
		tracealloc(p, sz)
		unlock(memlck)
	;;
	-> p
}

/* frees a blob that is 'sz' bytes long. */
const bytefree = {p, sz
	var bkt

	if p == (0 : byte#)
		-> void
	;;
	if trace
		lock(memlck)
		tracefree(p, sz)
		unlock(memlck)
	;;
	memfill(p, 0xa8, sz)
	if (sz < Bktmax)
		bkt = &buckets[bktnum(sz)]
		lock(memlck)
		bktfree(bkt, p)
		unlock(memlck)
	else
		bigfree(p, sz)
	;;
}

const bigalloc = {sz
	var p

	p = Failmem
	/*
	 We need to round up to the page size so that unmapping
	 doesn't end up taking out the tail of another allocation.
	*/
	sz = align(sz, Pagesz)

	/* check our cache */
	lock(memlck)
	for var i = 0; i < bigcache.len; i++
		if sz < bigcache[i].sz
			/*
			While the allocator may never use a small chunk, we need
			to keep it together so when unmapping it in the free call,
			end up unmapping the whole thing. We can't return a larger
			size here than requested, because we don't track the size.

			Eviction takes care of freeing it.
			*/
			p = bigcache[i].p
			bigcache[i].sz -= sz
			bigcache[i].p = ((p : intptr) + (sz : intptr) : byte#)
			break
		;;
	;;
	unlock(memlck)
	if p != Failmem
		-> p
	;;

	/* ok, lets give up and get memory from the os */
	p = getmem(sz)
	if p != Failmem
		-> p
	;;
	die("could not get memory\n")
}

const bigfree = {p, sz
	var evictsz, evictp, evictidx
	var endp, endblk

	sz = align(sz, Pagesz)
	evictp = p
	evictidx = -1
	evictsz = sz
	endp = ((p : intptr) + (sz : intptr) : byte#)
	lock(memlck)
	for var i = 0; i < bigcache.len; i++
		endblk = ((bigcache[i].p : intptr) + (bigcache[i].sz : intptr) : byte#)
		/* merge in front of existing block */
		if bigcache[i].p == endp
			bigcache[i].sz += sz
			bigcache[i].p = p
			evictidx = -1
			evictsz = 0
			break
		/* merge in behind existing block */
		elif endblk == p
			bigcache[i].sz += sz
			evictidx = -1
			evictsz = 0
			break
		;;
		/* evict */
		if bigcache[i].sz < evictsz
			evictidx = i
			evictsz = bigcache[i].sz
			evictp = bigcache[i].p
		;;
	;;

	if evictidx != -1
		bigcache[evictidx].p = p
		bigcache[evictidx].sz = sz
	;;
	unlock(memlck)

	/*
	  Now that we've removed it, we can
	  free it. It's not in the cache, so
	  we don't need the lock held.
	 */
	if evictsz > 0
		freemem(evictp, evictsz)
	;;
}

/* Sets up a single empty bucket */
const bktinit = {b, sz
	b.sz = align(sz, Align)
	b.nper = (Slabsz - sizeof(slab))/b.sz
	b.slabs = Zslab
	b.cache = Zslab
	b.ncache = 0
}

/* Creates a slab for bucket 'bkt', and fills the chunk list */
const mkslab = {bkt
	var p, s
	var b, bnext
	var off /* offset of chunk head */

	if bkt.ncache > 0
		s = bkt.cache
		bkt.cache = s.next
		bkt.ncache--
		s.next = Zslab
		-> s
	;;

	/*
	tricky: we need power of two alignment, so we allocate double the
	needed size, chop off the unaligned ends, and waste the address
	space. Since the OS is "smart enough", this shouldn't actually
	cost us memory, and 64 bits of address space means that we're not
	going to have issues with running out of address space for a
	while. On a 32 bit system this would be a bad idea.
	*/
	p = getmem(Slabsz*2)
	if p == Failmem
		die("Unable to get memory")
	;;

	b = Zchunk
	s = (align((p : size), Slabsz) : slab#)
	s.head = p
	s.nfree = bkt.nper
	s.next = Zslab
	s.prev = Zslab
	s.magic = 0xfee1baff1ed
	/* skip past the slab header */
	off = align(sizeof(slab), Align)
	bnext = nextchunk((s : chunk#), off)
	s.freehd = bnext
	for var i = 0; i < bkt.nper; i++
		b = bnext
		bnext = nextchunk(b, bkt.sz)
		b.next = bnext
	;;
	b.next = Zchunk
	-> s
}

/* 
Allocates a node from bucket 'bkt', crashing if the
allocation cannot be satisfied. Will create a new slab
if there are no slabs on the freelist.
*/
const bktalloc = {bkt
	var s, c

	/* find a slab */
	s = bkt.slabs
	if s == Zslab
		s = mkslab(bkt)
		bkt.slabs = s
		if s == Zslab
			die("No memory left")
		;;
	;;

	/* grab the first chunk on the slab */
	c = s.freehd
	s.freehd = c.next
	s.nfree--
	if s.freehd == Zchunk
		bkt.slabs = s.next
		if s.next != Zslab
			s.next.prev = Zslab
		;;
	;;
	-> (c : byte#)
}

/*
Frees a chunk of memory 'm' into bucket 'bkt'.
Assumes that the memory already came from a slab
that was created for bucket 'bkt'. Will crash
if this is not the case.
*/
const bktfree = {bkt, m
	var s, c

	s = (mtrunc(m, Slabsz) : slab#)
	iassert(s.magic == 0xfee1baff1ed, "bad free")
	c = (m : chunk#)
	if s.nfree == 0
		if bkt.slabs != Zslab
			bkt.slabs.prev = s
		;;
		s.next = bkt.slabs
		s.prev = Zslab
		bkt.slabs = s
	elif s.nfree == bkt.nper - 1
		/* unlink the slab from the list */
		if s.next != Zslab
			s.next.prev = s.prev
		;;
		if s.prev != Zslab
			s.prev.next = s.next
		;;
		if bkt.slabs == s
			bkt.slabs = s.next
		;;
		/*
		HACK HACK HACK: if we can't unmap, keep an infinite cache per slab size.
		We should solve this better somehow.
		*/
		if bkt.ncache < Cachemax || !Canunmap
			s.next = bkt.cache
			s.prev = Zslab
			bkt.cache = s
			bkt.ncache++
		else
			/* we mapped 2*Slabsz so we could align it,
			 so we need to unmap the same */
			freemem(s.head, Slabsz*2)
		;;
		-> void
	;;
	s.nfree++
	c.next = s.freehd
	s.freehd = c
}

/*
Finds the correct bucket index to allocate from
for allocations of size 'sz'
*/
const bitpos : byte[32] = [
  0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,
  8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31
]
const bktnum = {sz
	var n, v

	v = (sz >> 3 : uint32)
	v |= v >> 1
	v |= v >> 2
	v |= v >> 4
	v |= v >> 8
	v |= v >> 16

	n = bitpos[((v * 0x07c4acdd) & 0xffff_ffffui) >> 27]
	-> (n : size)
}

/*
returns the actual size we allocated for a given
size request
*/
const allocsz = {sz
	var bktsz

	if sz <= Bktmax
		bktsz = Align
		for var i = 0; bktsz <= Bktmax; i++
			if bktsz >= sz
				-> bktsz
			;;
			bktsz *= 2
		;;
	else
		-> align(sz, Pagesz)
	;;
	die("Size does not match any buckets")
}

/*
aligns a size to a requested alignment.
'align' must be a power of two
*/
const align = {v, align
	-> (v + align - 1) & ~(align - 1)
}

/*
chunks are variable sizes, so we can't just
index to get to the next one
*/
const nextchunk = {b, sz : size
	-> ((b : intptr) + (sz : intptr) : chunk#)
}

/*
truncates a pointer to 'align'. 'align' must
be a power of two.
*/
const mtrunc = {m, align
	-> ((m : intptr) & ~((align : intptr) - 1) : byte#)
}