#! @file memory.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains how an executable acquires memory from the kernel and gives it back: #! the blocks `raw_allocate` takes, and those the runtime keeps for itself. #! #! Memory comes from the kernel in chunks, carved into blocks of classes of #! sizes from 16 to 2048 bytes, which are reused once disposed. Larger blocks #! are mapped on their own, and some given back are kept to be reused, as #! `map_large` says. Chunks are opened one after another in a region of #! address space reserved at once, so whether memory lies in a chunk is a #! comparison. What is acquired is zeroed where it is asked to be: memory fresh #! from the kernel already is, and a block reused is cleared for as many bytes #! as were asked for. import system::windows; module runtime when backend == native; val chunk_size := 1048576u; val region_size := 68719476736u; # 64 GiB of address space, which takes no memory until opened. val largest := 2048u; val classes := 19u; var chunk: *mut u8; # Where the next block is carved. var chunk_left: u64; # The bytes open after it. var free_lists: *mut *mut u8; # The region chunks are opened in: where it begins, where its open chunks end, # and where it ends. A region that fills is followed by another, and where each # before it begins and its chunks end are kept, in memory of their own. var region_low: u64; var region_high: u64; var region_end: u64; var old_regions: *mut u64; var old_count: u64; var old_capacity: u64; def word(at: *u8): u64 { return (at as *u64)[0]; } def set_word(at: *mut u8, value: u64): void { (at as *mut u64)[0] = value; } module runtime when backend == native && os == linux; def map(size: u64): *mut u8 { val address := syscall(call_mmap, 0, size, 3, 0x22, 0xFFFFFFFFFFFFFFFF, 0); if address < 0 { trap(31); } return address as *mut u8; } def unmap(address: *mut u8, size: u64): void { syscall(call_munmap, address as u64, size, 0, 0, 0, 0); } module runtime when backend == native; def pages(size: u64): u64 { return (size + 4095) / 4096 * 4096; } # Classes step by 16 bytes up to 256, then double up to 2048. def class_of(size: u64): u64 { if size <= 256 { return size == 0 ? 0 : (size + 15) / 16 - 1; } if size <= 512 { return 16; } return size <= 1024 ? 17 : 18; } def class_size(class: u64): u64 { return class < 16 ? (class + 1) * 16 : 512u << (class - 16); } # The class of each size up to `largest`, by `(size + 15) / 16`, and the size of # each class, worked out while compiling. Classes begin and end at multiples of 16 # bytes, so the sizes that round up to the same multiple share a class. const class_by_size: u8[129] = make_class_by_size(); const size_of_class: u64[19] = make_size_of_class(); const def make_class_by_size(): u8[129] { var made: u8[129]; for each in 0..129 { made[each] = class_of((each * 16) as u64) as u8; } return made; } const def make_size_of_class(): u64[19] { var made: u64[19]; for each in 0..19 { made[each] = class_size(each as u64); } return made; } # The shift that leaves the bits of a hash a set of the capacity is indexed by, # which is a power of 2. def shift_for(capacity: u64): u64 { var shift := 64u; var rest := capacity; while rest > 1 { rest = rest >> 1; shift--; } return shift; } # Where a probe for the address begins in a set indexed by the bits `shift` leaves: # the top bits of the address times the golden ratio, which spreads addresses that # differ in any bits across the set. It is one expression, so it is inlined. def hash(address: u64, shift: u64): u64 { return (address * 0x9E3779B97F4A7C15) >> shift; } # Carves every size up to 16 bytes, so each block is aligned for any value. def carve(wanted: u64): *mut u8 { val size := (wanted + 15) / 16 * 16; if chunk_left < size { open_chunk(); } val block := chunk; chunk = chunk + size; chunk_left = chunk_left - size; return block; } module runtime when backend == native && os == linux; # Opens the chunk after the last, which what is left of the last runs on into, # or the first of a new region where this one is full. def open_chunk(): void { if region_high + chunk_size > region_end { reserve(); chunk = region_high as *mut u8; chunk_left = 0; } if syscall(call_mprotect, region_high, chunk_size, 3, 0, 0, 0) < 0 { trap(error_out_of_memory); } region_high = region_high + chunk_size; chunk_left = chunk_left + chunk_size; } # Reserves a region without access, so it takes no memory until chunks are opened # in it: as large as the system allows, down to a chunk. The region before it is # kept, for `in_chunk`. def reserve(): void { if region_low != 0 { keep_region(); } var size := region_size; while size >= chunk_size { val address := syscall(call_mmap, 0, size, 0, 0x4022, 0xFFFFFFFFFFFFFFFF, 0); if address >= 0 { region_low = address as u64; region_high = address as u64; region_end = address as u64 + size; return; } size = size / 2; } trap(error_out_of_memory); } module runtime when backend == native; def keep_region(): void { if old_count == old_capacity { val capacity := old_capacity == 0 ? 256u : old_capacity * 2; val grown := map(pages(capacity * 16)) as *mut u64; for i in 0..old_count * 2 { grown[i] = old_regions[i]; } if old_regions != null { unmap(old_regions as *mut u8, pages(old_capacity * 16)); } old_regions = grown; old_capacity = capacity; } old_regions[2 * old_count] = region_low; old_regions[2 * old_count + 1] = region_high; old_count++; } # Zeroes the words that hold the first `size` bytes of memory aligned to 8 bytes, # which may run past `size` to the end of its word. Every block is a whole number # of words, so that is still within it. `memset` does so sixteen bytes at a time # where vectors are held in registers. def clear(at: *mut u8, size: u64): void { memset(at, 0, (size + 7) & ~7u); } # Copies bytes that may overlap, as `memmove` does, which `memcpy` does, sixteen # bytes at a time where vectors are held in registers. def copy_bytes(dst: *mut u8, src: *u8, size: u64): void { memcpy(dst, src, size); } def compare_bytes(a: *u8, b: *u8, size: u64): i64 { return 0 if size == 0; return memcmp(a, b, size); } #! The bytes acquired for memory of the size, rounded to its class or to pages. #! @param size The number of bytes asked for. #! @returns The bytes that many takes: the size of its class, or whole pages for #! a large block. def acquired(size: u64): u64 { return size > largest ? pages(size) : size_of_class[class_by_size[(size + 15) >> 4]]; } #! Acquires zeroed memory of at least the size. #! @param size The number of bytes asked for. #! @returns The first byte of the memory, a block of its class or pages of their #! own. def acquire(size: u64): *mut u8 { if size > largest { return map_large(pages(size), true); } return take(class_by_size[(size + 15) >> 4], size); } #! Takes memory of a class: a block disposed of, which holds what it held but #! for the bytes asked to be cleared, or one carved fresh, which the kernel #! zeroed. #! @param class The class. #! @param cleared How many of its first bytes a block reused is cleared for. #! @returns The first byte of the memory. def take(class: u64, cleared: u64): *mut u8 { if free_lists == null { free_lists = carve(classes * 8) as *mut *mut u8; } val found := free_lists[class]; if found != null { free_lists[class] = (found as *mut *mut u8)[0]; if cleared != 0 { clear(found, cleared); } return found; } return carve(size_of_class[class]); } #! Disposes of memory acquired with the size. #! @param at The first byte of the memory, or `null`, which does nothing. #! @param size The number of bytes it was acquired with. def dispose(at: *mut u8, size: u64): void { if at == null { return; } if size > largest { unmap_large(at, pages(size)); return; } val class: u64 = class_by_size[(size + 15) >> 4]; (at as *mut *mut u8)[0] = free_lists[class]; free_lists[class] = at; } # Large memory given back is kept to be handed out again, rather than unmapped, # as mapping memory and touching its pages for the first time costs far more # than clearing it: up to `kept_most` pieces, of `kept_bytes_most` bytes in # all, each of `kept_largest` bytes at most, past which clearing it, which is # done holding the lock, costs more than it saves. Each is kept by where it is # and how many bytes it is, and handed out for as many bytes alone. val kept_most := 64u; val kept_bytes_most := 33554432u; val kept_largest := 1048576u; var kept_at: u64[64]; var kept_size: u64[64]; var kept_count: u64; var kept_bytes: u64; #! Maps memory of a number of bytes, which the kernel zeroed, or hands out #! memory of as many that was kept. #! @param size The number of bytes, a whole number of pages. #! @param cleared Whether memory kept is cleared, as memory mapped is zeroed. #! @returns The first byte of the memory. def map_large(size: u64, cleared: bool): *mut u8 { for i in 0..kept_count { if kept_size[i] == size { val at := kept_at[i] as *mut u8; kept_count--; kept_at[i] = kept_at[kept_count]; kept_size[i] = kept_size[kept_count]; kept_bytes = kept_bytes - size; if cleared { clear(at, size); } return at; } } return map(size); } #! Gives back memory `map_large` gave, keeping it where there is room. #! @param at The first byte of the memory. #! @param size The number of bytes it was given with. def unmap_large(at: *mut u8, size: u64): void { if size <= kept_largest && kept_count < kept_most && kept_bytes + size <= kept_bytes_most { kept_at[kept_count] = at as u64; kept_size[kept_count] = size; kept_count++; kept_bytes = kept_bytes + size; return; } unmap(at, size); } # Whether memory lies within a chunk: the newest region's open chunks, or those of # a region before it. def in_chunk(at: *mut u8): bool { val address := at as u64; if address - region_low < region_high - region_low { return true; } for i in 0..old_count { val low := old_regions[2 * i]; if address - low < old_regions[2 * i + 1] - low { return true; } } return false; } # Blocks the program allocates and releases itself, each a header of its size and # mark followed by its data. A live block's mark is made from its header's # address, and releasing it takes the mark away, so a pointer never allocated or # already released is recognized. A small block is carved from a chunk, so its # header is safe to read wherever the pointer is within one; a large block is # mapped on its own, and found in a set of the large blocks. Every block's data # starts a multiple of 16 bytes into its memory, so it is aligned to 16 bytes as # the memory is, which is wider than any type needs. # # The set is probed linearly. A block released leaves a tombstone where it was, # unless nothing was ever placed past it, and a block allocated takes the first # tombstone or empty slot it meets. struct block { var size: u64; #! The bytes of its data, all of the memory after the header. var mark: u64; #! Made from its address while it is live, and 0 once released. } val block_header := 16u; # The size and mark before every block's data. val tombstone := 1u; var block_set: *mut *mut block; # Of the large blocks. var block_capacity: u64; var block_used: u64; # Slots holding blocks or tombstones. var block_shift: u64; # What `hash` shifts by for the set. var large_count: u64; # Large blocks that are live. # What a live block's mark is its address mixed with. val live_key := 0x6E69616C70657669u; # The slot holding the block, or the empty slot that ends its probe where the set # does not hold it. def block_slot(found: *mut block): u64 { val mask := block_capacity - 1; var i := hash(found as u64, block_shift); while block_set[i] != null && block_set[i] != found { i = (i + 1) & mask; } return i; } # The slot a block the set does not hold goes in: the first tombstone or empty # slot of its probe. def open_slot(made: *mut block): u64 { val mask := block_capacity - 1; var i := hash(made as u64, block_shift); while block_set[i] != null && block_set[i] != tombstone as *mut block { i = (i + 1) & mask; } return i; } # Makes room for one more large block, building the set again at a quarter full # from the blocks it holds once blocks and tombstones fill half of it. def block_room(): void { if block_capacity > 0 && (block_used + 1) * 2 <= block_capacity { return; } var capacity := 64u; while capacity < (large_count + 1) * 4 { capacity = capacity * 2; } val before := block_set; val had := block_capacity; block_set = acquire(capacity * 8) as *mut *mut block; block_capacity = capacity; block_shift = shift_for(capacity); block_used = large_count; for i in 0..had { val each := before[i]; if each != null && each != tombstone as *mut block { block_set[block_slot(each)] = each; } } dispose(before as *mut u8, had * 8); } # Takes the block at the slot out of the set. Where the slot after it is empty, no # probe goes on past it, so it and the tombstones before it are emptied instead. def unset(slot: u64): void { val mask := block_capacity - 1; if block_set[(slot + 1) & mask] != null { block_set[slot] = tombstone as *mut block; return; } var i := slot; block_set[i] = null; block_used--; i = (i + mask) & mask; while block_set[i] == tombstone as *mut block { block_set[i] = null; block_used--; i = (i + mask) & mask; } } # Puts a large block in the set. def remember_large(made: *mut block): void { block_room(); val slot := open_slot(made); if block_set[slot] == null { block_used++; } block_set[slot] = made; large_count++; } # The live block whose data begins at `data`, stopping the program where there is # none: a pointer never allocated, already released, or within a block. def block_of(data: *mut u8): *mut block { if (data as u64) % 16 != 0 || (data as u64) < block_header { trap(error_invalid_release); } val found := (data - block_header) as *mut block; if !in_chunk(found as *mut u8) { if block_capacity == 0 || block_set[block_slot(found)] != found { trap(error_invalid_release); } } if ((*found).mark ^ (found as u64)) != live_key { trap(error_invalid_release); } return found; } # Releases the block. def unblock(found: *mut block): void { if block_header + (*found).size > largest { unset(block_slot(found)); large_count--; } (*found).mark = 0; dispose(found as *mut u8, block_header + (*found).size); } #! Allocates a zeroed block for `core::raw_allocate_zeroed`, as the machine does. #! @param size The number of bytes asked for. #! @returns The first byte of the block, after its header. #! @remarks A size no block can hold stops the program with `out of memory`. def allocate_zeroed(size: u64): *mut u8 { if threaded { val cached := cached_allocate(size, true); if cached != null { return cached; } } hold(); val made := allocate_held(size, true); let_go(); return made; } #! Allocates a block for `core::raw_allocate`, which is not cleared. #! @param size The number of bytes asked for. #! @returns The first byte of the block, after its header. #! @remarks A size no block can hold stops the program with `out of memory`. def allocate(size: u64): *mut u8 { if threaded { val cached := cached_allocate(size, false); if cached != null { return cached; } } hold(); val made := allocate_held(size, false); let_go(); return made; } # Each thread's own free blocks of each class, once the program has threads, # which it takes and gives back without the lock: as many as `cache_most` of a # class, past which half go back to the lists every thread shares, and as many # as `cache_batch` taken from those at once where it has none. A thread's # blocks go back to the lists as it ends. struct block_cache { var heads: u64[19]; # The first block of each class, whose first word holds the next's address. var counts: u64[19]; # How many blocks each class has. } val cache_most := 64u; val cache_batch := 16u; # The running thread's cache, made where it has none. def own_cache(): *mut block_cache { val me := current(); var held := (*me).cache; if held == null { hold(); held = acquire(size_of::()) as *mut block_cache; let_go(); (*me).cache = held; } return held; } # Allocates a small block from the running thread's cache, taking a batch of the # class from the lists every thread shares, under the lock, where it has none, # or gives null for a large block, which `allocate_held` maps. def cached_allocate(size: u64, cleared: bool): *mut u8 { if size > largest - block_header { return null; } val class: u64 = class_by_size[(block_header + size + 15) >> 4]; val held := own_cache(); if held[0].counts[class] == 0 { hold(); for _ in 0..cache_batch { val each := take(class, 0); set_word(each, held[0].heads[class]); held[0].heads[class] = each as u64; } held[0].counts[class] = cache_batch; let_go(); } val made := held[0].heads[class] as *mut block; held[0].heads[class] = word(made as *u8); held[0].counts[class] -= 1; val total: u64 = size_of_class[class]; if cleared { clear(made as *mut u8, total); } (*made).size = total - block_header; (*made).mark = (made as u64) ^ live_key; return (made as *mut u8) + block_header; } # Gives a live block of the newest region's chunks back to the running thread's # cache, handing half of its class back to the lists every thread shares, under # the lock, past `cache_most`. Gives false for any other pointer, which # `release_held` looks at under the lock. The region's bounds are read without # the lock, the end first: another thread opening a chunk only moves the end # past blocks the bounds read do not hold, and one reserving a region sets its # start before its end. def cached_release(data: *mut u8): bool { val address := data as u64; if address % 16 != 0 || address < block_header { return false; } val found := (data - block_header) as *mut block; val high := region_high; val low := region_low; if high < low || found as u64 - low >= high - low { return false; } if ((*found).mark ^ (found as u64)) != live_key { return false; } val class: u64 = class_by_size[(block_header + (*found).size + 15) >> 4]; val held := own_cache(); (*found).mark = 0; set_word(found as *mut u8, held[0].heads[class]); held[0].heads[class] = found as u64; held[0].counts[class] += 1; if held[0].counts[class] > cache_most { hold(); while held[0].counts[class] > cache_most / 2 { val each := held[0].heads[class] as *mut u8; held[0].heads[class] = word(each); held[0].counts[class] -= 1; (each as *mut *mut u8)[0] = free_lists[class]; free_lists[class] = each; } let_go(); } return true; } # Gives a thread's cached blocks, and its cache, back to the lists every thread # shares, as it ends, holding the lock. def flush_cache(me: *mut state): void { val held := (*me).cache; if held == null { return; } for class in 0..classes { while held[0].counts[class] != 0 { val each := held[0].heads[class] as *mut u8; held[0].heads[class] = word(each); held[0].counts[class] -= 1; (each as *mut *mut u8)[0] = free_lists[class]; free_lists[class] = each; } } dispose(held as *mut u8, size_of::()); (*me).cache = null; } # `allocate_zeroed` and `allocate`, holding the lock around the runtime's memory. def allocate_held(size: u64, cleared: bool): *mut u8 { if size > 0xFFFFFFFFFFFFFFFF - block_header - 4095 { trap(error_out_of_memory); } val wanted := block_header + size; var total: u64 = 0; var made: *mut block = null; if wanted > largest { total = pages(wanted); made = map_large(total, cleared) as *mut block; } else { val class: u64 = class_by_size[(wanted + 15) >> 4]; total = size_of_class[class]; made = take(class, cleared ? total : 0) as *mut block; } (*made).size = total - block_header; (*made).mark = (made as u64) ^ live_key; if total > largest { remember_large(made); } return (made as *mut u8) + block_header; } #! Releases a block for `core::raw_release`, stopping the program where the #! pointer is not that of a live block. #! @param data The first byte of the block, or `null`, which does nothing. def release(data: *mut u8): void { if data == null { return; } if threaded && cached_release(data) { return; } hold(); release_held(data); let_go(); } # `release`, holding the lock around the runtime's memory. def release_held(data: *mut u8): void { if data == null { return; } unblock(block_of(data)); } #! Moves a block to one of another size for `core::raw_resize`. A block whose #! memory is already of the size keeps its place, and a large block grown larger #! is remapped where it is, or moved by the kernel, rather than copied. #! @param data The first byte of the block, or `null` to allocate one. #! @param size The number of bytes the new block holds. #! @returns The first byte of the new block, which holds what the old one did, #! as far as it reaches, and may hold anything past that. def resize(data: *mut u8, size: u64): *mut u8 { if threaded { hold(); } val made := resize_held(data, size); if threaded { let_go(); } return made; } module runtime when backend == native && os == linux; # `resize`, holding the lock around the runtime's memory. def resize_held(data: *mut u8, size: u64): *mut u8 { if data == null { return allocate_held(size, false); } val found := block_of(data); val most: u64 = 0xFFFFFFFFFFFFFFFF - block_header - 4095; if size > most { trap(error_out_of_memory); } val total := acquired(block_header + size); val before := block_header + (*found).size; if total == before { return data; } if total > largest && before > largest && total > before { val moved := syscall(call_mremap, found as u64, before, total, 1, 0, 0); if moved < 0 { trap(error_out_of_memory); } # The block keeps its place among the blocks, under its new address. unset(block_slot(found)); large_count--; val made := moved as u64 as *mut block; (*made).size = total - block_header; (*made).mark = (made as u64) ^ live_key; remember_large(made); return (made as *mut u8) + block_header; } val grown := allocate_held(size, false); copy_bytes(grown, data, (*found).size < size ? (*found).size : size); unblock(found); return grown; } module runtime when backend == native && os == windows; # Windows maps memory in parts of 64 KiB, which takes no more memory than a page # where less is used, and gives back only all of what it mapped at once, as every # call of `unmap` does. def map(size: u64): *mut u8 { val address := VirtualAlloc(0, size, 0x3000, 0x04); if address == 0 { trap(31); } return address as *mut u8; } def unmap(address: *mut u8, size: u64): void { VirtualFree(address as u64, 0, 0x8000); } # Opens the chunk after the last, committing it, or the first of a new region # where this one is full. Windows counts what is committed against the memory it # has, so a chunk it cannot commit is the program running out of memory. def open_chunk(): void { if region_high + chunk_size > region_end { reserve(); chunk = region_high as *mut u8; chunk_left = 0; } if VirtualAlloc(region_high, chunk_size, 0x1000, 0x04) == 0 { trap(error_out_of_memory); } region_high = region_high + chunk_size; chunk_left = chunk_left + chunk_size; } # Reserves a region without access, as on Linux, down to a chunk. def reserve(): void { if region_low != 0 { keep_region(); } var size := region_size; while size >= chunk_size { val address := VirtualAlloc(0, size, 0x2000, 0x01); if address != 0 { region_low = address; region_high = address; region_end = address + size; return; } size = size / 2; } trap(error_out_of_memory); } # `resize`, holding the lock around the runtime's memory. Windows cannot move # what it mapped elsewhere, so a large block grows as a small one does, copied. def resize_held(data: *mut u8, size: u64): *mut u8 { if data == null { return allocate_held(size, false); } val found := block_of(data); val most: u64 = 0xFFFFFFFFFFFFFFFF - block_header - 4095; if size > most { trap(error_out_of_memory); } val total := acquired(block_header + size); val before := block_header + (*found).size; if total == before { return data; } val grown := allocate_held(size, false); copy_bytes(grown, data, (*found).size < size ? (*found).size : size); unblock(found); return grown; }