Landin library reference discuss source

hosted/heap/heap.ldn

1--  The hosted heap is separate from core/mem's freestanding allocator
2--  protocol and caller-backed providers.  It keeps size classes over
3--  memory it maps itself, written once for every hosted system: posix.ldn
4--  maps it through platform/posix and windows.ldn through Windows'
5--  `VirtualAlloc`.  It over-allocates so that every usize alignment is
6--  honoured, not only the powers of two posix_memalign and aligned_alloc
7--  admit.  Its classes are behind one lock once the program has started a
8--  thread (D502).
9
10import core/mem
11import hosted/thread/lock
12
13--  The state carries no information; it is opaque so that only `host` makes
14--  one.
15system_value: type = struct
16    reserved: u8
17end system_value
18
19--- The host heap as an allocator capability. The value is a handle that
20--- borrows nothing: the heap belongs to the process, and copies share it. It
21--- allocates and frees through size classes over memory it maps from the
22--- system. A resize grows a block in place when its slot or mapping holds the
23--- new extent or its mapping can grow where it is; otherwise it moves the
24--- mapping's pages with Linux's `mremap` or copies the block. On Windows a
25--- mapping reserves its address space in the system's 64 KiB units and grows
26--- in place into what its reservation holds beyond it. Available only on
27--- hosted targets. Threads share the heap: once the program has started a
28--- thread through hosted/thread, one lock guards its size classes, and a
29--- program that has started none never takes it. A block larger than the
30--- largest class is a mapping of its own and needs no lock. A C thread calling
31--- in under `--link=libc` is no thread of the program's, and two of them may
32--- not use it at once.
33---
34--- Every usize alignment is accepted. Zero and one mean no stricter than byte
35--- alignment. A zero-byte request still returns a distinct, non-null, freeable
36--- token on success. The provider reserves a header plus at most alignment - 1
37--- bytes and refuses an overflow or an extent above the host's PTRDIFF_MAX
38--- before asking the host for memory. Any other failure to obtain memory is
39--- reported through mem.out_of_memory, before the provider's own state
40--- changes.
41---
42--- Freeing trusts the two words this heap keeps before every block: it frees
43--- the extent they hold and does not read the `size` passed. So freeing a
44--- block this heap did not give, freeing one twice, or writing below a block's
45--- first byte is undefined, as it is with C's `free`; nothing here can tell
46--- such a block from one of its own. A block larger than the largest class is
47--- unmapped when it is freed, and a refusal to unmap, which the system gives
48--- only for an address or a length it never mapped, keeps the pages, costing
49--- their memory and nothing else.
50public heap: type = system_value
51
52word: usize = sizeof usize
53
54--  The largest extent either host takes: PTRDIFF_MAX.
55largest: usize = (0 -% 1) >> 1
56
57--  A header word, at a multiple of the word.
58store_word: (at: usize, value: usize) -> none =
59    cell: ptr mut usize = ptr(at)
60    cell.val = value
61end store_word
62
63load_word: (at: usize) -> (value: usize) =
64    cell: ptr usize = ptr(at)
65    value = cell.val
66end load_word
67
68--  The first address at or above `first` that is a multiple of `unit`.
69--  Every unit an allocation asks for in practice is a power of two,
70--  which a mask aligns; any other takes the division.
71align_up: (first: usize, unit: usize) -> (aligned: usize) =
72    low: usize = unit -% 1
73    aligned = if unit & low == 0 then (first + low) & (0 -% unit)
74              else align_any(first, unit) end if
75end align_up
76
77align_any: (first: usize, unit: usize) -> (aligned: usize) =
78    over: usize = first % unit
79    aligned = if over == 0 then first else first + (unit - over) end if
80end align_any
81
82--  Every block is preceded by two words: the start of the slot or mapping
83--  that holds it, and that slot's or mapping's extent.  A slot of a size
84--  class has the class's extent; anything larger than the largest class
85--  is a mapping of its own, unmapped when it is freed.
86header: usize = 2 * word
87
88--  Where a block's two words are: at the multiple of the word at or below
89--  a header before the block, so that they are aligned whatever the
90--  block's alignment.  A slot or mapping starts at a multiple of the word
91--  and its block is at least a header past that start, so the words never
92--  reach below it.
93header_at: (block: usize) -> (at: usize) =
94    at = (block - header) & (0 -% word)
95end header_at
96
97--  Eight classes, of 32 to 4096 bytes.  A class with no free slot maps a
98--  chunk and divides it into slots.  A freed slot goes back on its class's
99--  list, linked through its first word, and is reused before any new chunk
100--  is mapped; chunks are never unmapped.
101classes: usize = 8
102smallest_class: usize = 32
103largest_class: usize = 4096
104chunk: usize = 65536
105
106--  The first free slot of each class, or zero.  The lists are plain module
107--  storage, which `class_lock` serialises once a thread has started.
108mut free_slots: [8]usize
109
110--  The lock over every class's list and over mapping a class's chunk
111--  (D502).  A program that has started no thread skips it: the thread
112--  facility records the start before it makes the thread, and the
113--  creation orders everything this thread did to the lists before.
114mut class_lock: lock.lock = zeroed
115
116--  Take the classes' lock when `locked`, which the caller read from
117--  `lock.threads_started` itself, for `give_classes` to give it back
118--  alike: D339 copies one level, so the caller's copy of the read is a
119--  load and a branch only when the caller makes the call.
120take_classes: (locked: bool) -> none =
121    if locked then
122        lock.take(addr class_lock)
123    end if
124end take_classes
125
126give_classes: (locked: bool) -> none =
127    if locked then
128        lock.give(addr class_lock)
129    end if
130end give_classes
131
132--  The smallest class holding `extent` bytes, which is at most the largest
133--  class: its index and its size.
134class_of: (extent: usize) -> (index: usize, size: usize) =
135    index = 0
136    size = smallest_class
137    while size < extent do
138        index += 1
139        size = size * 2
140    end while
141end class_of
142
143--  A free slot of class `index` and `size`, taken off its list, or zero
144--  when none is free and no chunk could be mapped.
145take_slot: (index: usize, size: usize) -> (slot: usize) =
146    if free_slots[index] == 0 then
147        base: usize = map_pages(chunk)
148        if base == 0 then
149            slot = 0
150            return
151        end if
152        --  Link the chunk's slots in address order.
153        mut at: usize = base
154        while at < base + chunk do
155            link: ptr mut usize = ptr(at)
156            link.val = if at + size < base + chunk then at + size
157                       else usize(0) end if
158            at += size
159        end while
160        free_slots[index] = base
161    end if
162    slot = free_slots[index]
163    link: ptr usize = ptr(slot)
164    free_slots[index] = link.val
165end take_slot
166
167--  Slots and mappings start at multiples of the smallest class, so a unit
168--  that divides the header has the block a header past the start aligned
169--  already; any other unit may need up to unit - 1 bytes more.
170host_alloc: (size: usize, unit: usize) -> (block: usize) =
171    low: usize = unit -% 1
172    power: bool = unit & low == 0
173    slack: usize = if power and unit <= header then 0
174                   elsif not power and header % unit == 0 then 0
175                   else low end if
176    extent: usize = size + slack + header
177    mut origin: usize = 0
178    mut held: usize = 0
179    if extent <= largest_class then
180        (index, size: class_size) := class_of(extent)
181        locked: bool = lock.threads_started()
182        take_classes(locked)
183        origin = take_slot(index, class_size)
184        give_classes(locked)
185        held = class_size
186    else
187        page: usize = page_bytes()
188        held = align_up(extent, page)
189        origin = map_pages(held)
190    end if
191    if origin == 0 then
192        block = 0
193        return
194    end if
195    --  `size` copies no call, so the hot path keeps the mask itself.
196    block = if power then (origin + header + low) & (0 -% unit)
197            else align_any(origin + header, unit) end if
198    at: usize = header_at(block)
199    store_word(at, origin)
200    store_word(at + word, held)
201end host_alloc
202
203host_free: (block: usize) -> none =
204    at: usize = header_at(block)
205    origin: usize = load_word(at)
206    held: usize = load_word(at + word)
207    if held <= largest_class then
208        (index, size: _) := class_of(held)
209        locked: bool = lock.threads_started()
210        take_classes(locked)
211        link: ptr mut usize = ptr(origin)
212        link.val = free_slots[index]
213        free_slots[index] = origin
214        give_classes(locked)
215    else
216        --  A refusal means the header no longer holds a mapping of this
217        --  heap's, and free has no failure to report it by: the pages, if
218        --  any, stay mapped.
219        release_pages(origin, held)
220    end if
221end host_free
222
223--  The page rounding a mapping adds, beyond the header and alignment: a
224--  page is at most 64 KiB on every hosted system.
225rounding: usize = 65535
226
227--  The alignment of a request for `size` bytes as a unit of at least one,
228--  or zero when the request is refused before the host is asked: the host
229--  takes no extent above PTRDIFF_MAX, and no addition may wrap.
230unit_for: (size: usize, alignment: usize) -> (unit: usize) =
231    unit = if alignment > 1 then alignment else 1 end if
232    if unit - 1 > largest - header - rounding then
233        unit = 0
234        return
235    end if
236    padding: usize = unit - 1 + header + rounding
237    if size > largest - padding then
238        unit = 0
239    end if
240end unit_for
241
242system_alloc: (self: heap, size: usize, alignment: usize)
243              -> (block: ptr mut u8) ! mem.out_of_memory =
244    _ = self.reserved
245    unit: usize = unit_for(size, alignment)
246    fail mem.out_of_memory when unit == 0
247    address: usize = host_alloc(size, unit)
248    fail mem.out_of_memory when address == 0
249    block = ptr(address)
250end system_alloc
251
252system_free: (self: heap, block: ptr mut u8, size: usize) -> none =
253    _ = self.reserved
254    _ = size
255    host_free(usize(block))
256end system_free
257
258--  Where a block's slot or mapping is: the address of the block's two
259--  words, and the slot's or mapping's start and extent, which they hold.
260place: type = struct
261    at: usize
262    origin: usize
263    held: usize
264end place
265
266place_of: (block: usize) -> (where: place) =
267    at: usize = header_at(block)
268    where = (at: at, origin: load_word(at), held: load_word(at + word))
269end place_of
270
271--  Grow the mapping `where` describes where it is, to hold `ends` bytes
272--  from its start, or report that it is a slot or that the pages after
273--  it are taken.
274extend_mapping: (where: place, ends: usize) -> (grown: bool) =
275    grown = false
276    return when where.held <= largest_class
277    wanted: usize = align_up(ends, page_bytes())
278    return when not extend_pages(where.origin, where.held, wanted)
279    store_word(where.at + word, wanted)
280    grown = true
281end extend_mapping
282
283--  Make the mapping `where` describes, which holds the block at `block`,
284--  hold `ends` bytes from its start, in place or with its pages moved where
285--  the system can move them: the block's address afterwards, or zero.
286remap_mapping: (block: usize, where: place, ends: usize) -> (moved: usize) =
287    moved = 0
288    wanted: usize = align_up(ends, page_bytes())
289    origin: usize = remap_pages(where.origin, where.held, wanted)
290    return when origin == 0
291    moved = origin + (block - where.origin)
292    at: usize = header_at(moved)
293    store_word(at, origin)
294    store_word(at + word, wanted)
295end remap_mapping
296
297--  Give the pages of the mapping `where` describes past `ends` bytes from
298--  its start back, keeping it larger than the largest class so that it is
299--  still freed as a mapping.  A refusal keeps them, which costs memory and
300--  nothing else.
301trim_mapping: (where: place, ends: usize) -> none =
302    return when where.held <= largest_class
303    least: usize = if ends > largest_class then ends else largest_class + 1
304                   end if
305    kept: usize = align_up(least, page_bytes())
306    return when kept >= where.held
307    return when not return_tail(where.origin + kept, where.held - kept)
308    store_word(where.at + word, kept)
309end trim_mapping
310
311--  Whether the block at `block` can hold `size` bytes where it is: in its
312--  slot or mapping, or in its mapping grown in place.
313host_grow: (block: usize, size: usize) -> (grown: bool) =
314    where: place = place_of(block)
315    ends: usize = block - where.origin + size
316    grown = ends <= where.held or extend_mapping(where, ends)
317end host_grow
318
319--  The block at `block` made `new_size` bytes long with `unit`'s alignment
320--  without copying its bytes, or zero when that cannot be done: in its slot
321--  or mapping when that holds it, or its mapping grown or moved by the
322--  system.  The system puts a mapping at a page, so a moved one keeps the
323--  block's alignment only when a page has it too.
324host_resize: (block: usize, new_size: usize, unit: usize)
325             -> (resized: usize) =
326    resized = block
327    where: place = place_of(block)
328    ends: usize = block - where.origin + new_size
329    if ends <= where.held then
330        trim_mapping(where, ends)
331        return
332    end if
333    if where.held > largest_class then
334        if page_bytes() % unit == 0 then
335            resized = remap_mapping(block, where, ends)
336            return when resized <> 0
337        else
338            return when extend_mapping(where, ends)
339        end if
340    end if
341    resized = 0
342end host_resize
343
344system_grow: (self: heap, block: ptr mut u8,
345              old_size: usize, new_size: usize, alignment: usize)
346             -> (grown: bool) =
347    _ = self.reserved
348    grown = false
349    return when new_size <= old_size or unit_for(new_size, alignment) == 0
350    grown = host_grow(usize(block), new_size)
351end system_grow
352
353system_resize: (self: heap, block: ptr mut u8,
354                old_size: usize, new_size: usize, alignment: usize)
355               -> (moved: ptr mut u8) ! mem.out_of_memory =
356    _ = self.reserved
357    unit: usize = unit_for(new_size, alignment)
358    fail mem.out_of_memory when unit == 0
359    address: usize = host_resize(usize(block), new_size, unit)
360    if address <> 0 then
361        moved = ptr(address)
362        return
363    end if
364    moved = try mem.relocate(self, block, old_size, new_size, alignment)
365end system_resize
366
367heap is mem.allocator (alloc: system_alloc, grow: system_grow,
368                       resize: system_resize, free: system_free)
369
370--- Return a handle to the host heap. Making one does not allocate; callers
371--- retain and free each successful allocation explicitly.
372public new: () -> (handle: heap) =
373    handle = (reserved: 0)
374end new