|
ADS
Algorithms and Data Structures
|
The headers of include/ADS/memory realize, beyond the book, the dynamic storage allocation of section 2.5 of the first volume of Knuth and the allocators of today that descend from it: the boundary tags and the buddy system on a simulated memory, the arenas and the pools of objects of one type, the size classes for one thread and for many, the huge pages, and a heap of cells with a garbage collector. This page collects what the headers take for granted: the vocabulary of blocks, free lists and fragmentation (see Definitions and notation), the allocators and the cost of their operations (see The allocators and their costs), and, for each family, the invariant on which it rests and the argument behind its cost and its waste (from Boundary tags to Garbage collection). The pseudocode of each operation is instead on the page of its header, in the comment of its function, together with the algorithm of Knuth, or the paper, that it follows.
An allocator manages a memory of \( N \) words (or bytes) and serves two operations: allocate( n ) gives a block of at least \( n \) contiguous words that no other block overlaps, and free() (or deallocate()) takes a block back; the blocks not given are free, and an allocator keeps them on one or more free lists, which the free blocks themselves hold, a word of a free block pointing to the next one (the list AVAIL of Knuth). A block may carry a header, words of its own that the allocator reads, e.g., its size; a sized deallocation, as that of std::allocator, gives the size back with the block, so that the block needs no header.
The memory that an allocator holds and does not give for use is its fragmentation. It is internal when a block is larger than its request (the rounding to a class, to a power of 2, the header), and external when free memory exists in pieces too small for a request, so that a request fails, or takes new memory, although the free words would be enough. Merging adjacent free blocks (coalescing) fights the external fragmentation, and giving each request a block of one of a few sizes, a size class, removes it within a class at the price of an internal one; the allocators of the area are points between the two.
| Symbol | Meaning |
|---|---|
| \( N \) | the words of a simulated memory, \( 2^m \) for the buddy system |
| \( n \), \( b \), \( a \) | the words or bytes of a request, and its alignment |
| \( s( p ) \) | the words of the block at the address \( p \), kept in its tags |
| \( F \), \( F_k \), \( F_c \) | a free list, that of the blocks of \( 2^k \) words, that of the class \( c \) |
| \( g \) | the step of the size classes of the pools, 8 bytes |
| page, segment | the \( 2^{16} \) bytes of the slots of one class, and the \( 2^{21} \) bytes from which the pages are cut |
| Allocator | Blocks | Allocate | Free | Waste |
|---|---|---|---|---|
| BoundaryTagAllocator | any size | \( O( f ) \) for \( f \) free blocks | \( O( 1 ) \), merging both neighbors | 2 words of tags, external fragmentation |
| BuddyAllocator | powers of 2 | \( O( m ) \) splits | \( O( m ) \) merges | less than half of each block |
| Arena | objects of one type | \( O( 1 ) \), a pointer bump | only all at once | part of the last block |
| ObjectPool | objects of one type | \( O( 1 ) \), but for a new block | \( O( 1 ) \) | at most the largest size held, plus a block |
| SizeClassAllocator | 41 classes up to 32768 bytes | \( O( 1 ) \) | \( O( 1 ) \), sized | below 20% past 128 bytes |
| PoolResource, PageHeap | classes of 8 bytes up to \( M \) | \( O( 1 ) \) amortized | \( O( 1 ) \) | below \( \max( a , g ) \) bytes per slot |
| ConcurrentPoolResource | as above, any thread | \( O( 1 ) \) amortized | \( O( 1 ) \), a compare-and-swap per batch of at most 32 frees of other threads | as above, and 31 slots per class and thread in transit |
| HugePageAllocator | any, aligned to 2 MB from 2 MB | that of the system | that of the system, or kept from 8 MB | address space up to a huge page |
| CellHeap | cells of two fields | \( O( 1 ) \), a collection when none is free | by the collector | none |
The general allocators of section 2.5 serve any size and pay for it with a search of the free list and with the external fragmentation; the pools serve one size, or a few, and pay with the internal fragmentation and with memory that a class keeps when another needs it. The second kind is the one of the allocators of today, which add the locality: the blocks made one after another are next to each other, and a block just freed, still in the cache, is the next one given.
BoundaryTagAllocator keeps the free blocks on a doubly linked list and writes the size of each block, and whether it is free, in a tag at both of its ends (Algorithm 2.5C of Knuth).
Lemma 1 (the boundary tags). After each operation the blocks tile the memory and
\[ \text{no two free blocks are adjacent.} \tag{1} \]
A freed block reads the tag just below it, which is the upper tag of the block below, and the tag just above it, the lower tag of the block above: two reads tell whether its neighbors are free and how large they are, and since the list is doubly linked each free neighbor leaves the list in \( O( 1 ) \), and merges; hence (1) is kept by every free in \( O( 1 ) \) time. An allocation splits a block only if the rest has room for the tags and the two links, and gives the upper part, so that the lower part keeps its place on the list and only its tags change. The search for a block is the cost of the method: the first fit stops at the first block large enough, the best fit reads the whole list, and the next fit starts where the last search stopped, so that the small pieces left by the splits do not gather at the head of the list. Knuth reports, as the fifty-percent rule, that in equilibrium the free blocks are about half as many as the blocks in use, whatever the fit.
BuddyAllocator (Knowlton; Algorithms 2.5R and 2.5S of Knuth) gives blocks of \( 2^k \) words only, each at an address multiple of its size.
Lemma 2 (the buddies). The block of \( 2^k \) words at the address \( a \), \( k < m \), was split from the block of \( 2^{k+1} \) words at \( a \wedge \neg 2^k \), and its buddy, the other half, is at
\[ a \oplus 2^k . \tag{2} \]
By induction on the splits: a block of \( 2^{k+1} \) words at an address multiple of \( 2^{k+1} \) has the bit \( k \) of its address 0, and its halves are at \( a \) and \( a + 2^k \), which differ in that bit only, and are multiples of \( 2^k \). A request of \( n \) words takes \( k = \lceil \log_2 n \rceil \), and splits the least free block not smaller, by halves, each upper half joining its free list; a freed block finds its buddy by (2) and, if it is free and whole, merges with it and goes on upwards. Both take at most \( m \) steps, each a search of an ordered set of the free blocks of one size in the code, i.e., \( O( m \log N ) \) time; a block is less than twice its request, so that the internal waste is less than half of the block, and no two free buddies are ever both on the lists.
An arena (Hanson) gives the objects of one type from blocks, by a pointer bump, and frees them all at once with the arena; an object costs no header and no search, the objects made one after another are next to each other, and their addresses never change, which the parents of the nodes of a search rely on; its iterators read a block through the vector of the blocks, not through the array of that vector, which an append may move, so that they too stay valid while the arena lives. A pool (ObjectPool) adds the free of one object: its slot goes at the head of a free list, the list AVAIL of section 2.2.3 of Knuth, and the next allocation takes it again, still in the cache. Its blocks double from 1 slot up to \( n \), so that a pool that has held at most \( k \) objects at once has at most \( 2 k + n \) slots, and the allocations of blocks are \( O( \log k ) \) while the blocks double. A pool that adopts the blocks of another one (adopt()) keeps them whatever it holds, and its limit becomes the larger of the two, whether it had blocks or not.
A size class serves all the requests between two sizes with blocks of the larger one. SizeClassAllocator has the class of 8 bytes, the multiples of 16 up to 128, and four classes for each power of 2 above,
\[ s = 2^e + j \, 2^{e - 2} , \quad j = 1 , \ldots , 4 , \quad 7 \le e \le 14 . \tag{3} \]
A request between two consecutive sizes of (3) wastes less than \( 2^{e - 2} \) bytes of a block of at least \( 5 \cdot 2^{e - 2} \), i.e., less than 20% of it; the class is found from the position of the leading bit of \( n - 1 \) and two more bits below it, with no table and no loop. Each class has its free list and a page whose rest is cut a block at a time, so that both operations take \( O( 1 ) \) time (the scheme of TLSF and of the allocators of today, by size classes rather than by fits).
PoolResource keeps the classes of 8 bytes up to \( M \) on the pages of PageHeap, with one free list per page instead of one per class (the sharding of mimalloc): a class allocates from its current page, the pop of the list of the page or the bump of its pointer, and moves to another page with free slots only when the current one is exhausted. A slot finds its page by masking the low 16 bits of its address, so that a free is a push on the list of that page. After frees in a scrambled order, a single free list gives the slots back in that order, scattered over all the memory, while the lists by page give them back a page at a time, so that the nodes of a container built again are close to each other. ConcurrentPoolResource gives each thread such a heap of its own, and a slot freed by a thread other than its owner goes back to the owner in a batch of up to 32, pushed whole on a stack of returns by one compare-and-swap, which the owner takes whole by an exchange (see the theory of concurrency for the argument that excludes the ABA problem); the frees of one thread to another thus cost one atomic operation per batch (snmalloc).
A search restarted many times (an incremental search that gives up the repair of its solution) drops all its nodes at each restart. Freeing them one by one costs a free per node, and giving the blocks back to the allocator costs their faults again in the next run; clear() of Arena and of ObjectPool ends instead an epoch, the time from the construction or from the last clear(), and keeps the blocks. The arena goes back to the first place of its first block, and moves to the next block kept when the block in use is full, appending a block only past the last one; the pool empties its free list, takes the slots of its last block, and then those of the blocks before it, one block at a time, from a pointer \( R \) to the first block not yet used again, taking a new block only when \( R \) is nil. Hence an epoch takes a block from the allocator only when every place of the blocks kept has been given in it, and the memory of a sequence of epochs is that of the largest one (for the pool, the bound \( 2 k + n \) above with \( k \) the most objects alive at once in any epoch). The call writes a few words, i.e., \( O( 1 ) \) time, but for the destructors of the objects of an arena when they are not trivial; the allocation path is the same as without epochs, since the test of a block kept sits where a block was allocated.
Nothing survives an epoch: the objects are destroyed or dropped, and the free slots forgotten. A pointer of an old epoch is stale, and using it is a violation of the contract, since its place may hold an object of the new epoch. fresh( p ) tells, in time linear in the blocks, whether \( p \) is a place given in the current epoch, which a stale pointer is only once its place is given again; the frees of the pool check it at the level of the audits, and under the sanitizer of addresses the places of an epoch are forbidden at its end and allowed again one at a time as they are given. Each structure belongs to one thread, which alone calls make(), free() and clear(); another thread may read the objects, and gives back to the owner an object that it drops, by a message, but each of its accesses must happen before the clear() of the owner (e.g., through a barrier), and then every write of the owner in the next epochs follows it in the order of happens-before, so that no data race can occur.
A structure whose nodes are reached in no useful order, e.g., the trees of a heap or the buckets of a hash table, misses the translation lookaside buffer (TLB) at nearly each step when its memory spans more pages than the TLB has entries: with \( E \) entries a TLB covers \( 4 E \) KB of pages of 4 KB, and \( 2 E \) MB of huge pages of 2 MB, 512 times more. HugePageAllocator aligns the blocks of at least 2 MB to 2 MB and rounds them up to whole huge pages, which the kernel backs by the transparent huge pages (Navarro et al.) where its policy gives them to every large region, at the price of at most one huge page of address space per block, which is never touched; the blocks of 8 MB or more given back are kept by their thread, up to 64 MB, for the next request of the same size, so that a structure that grows and shrinks through the same sizes pays the faults of its pages once.
The containers that manage their memory take an allocator A with the rules of the allocator-aware containers of the standard ([container.reqmts]), written once in AllocatorAware.h: A is rebound to what the container allocates, a copy is made on the allocator that select_on_container_copy_construction() gives, and an assignment or a swap takes the allocator of the other container only when the corresponding trait propagate_on_container_copy_assignment, propagate_on_container_move_assignment or propagate_on_container_swap is true. A move assignment between unequal allocators that do not propagate moves the items one by one, in \( O( n ) \) time, since the memory of the source must go back to the allocator that gave it; it is the only operation that costs more than with std::allocator, whose instances are all equal. The default allocator of each container is the one it used before (std::allocator, or the HugePageAllocator of its ObjectPool); it is empty, held as an empty base or member, and the paths of a stateful allocator are discarded at compile time, so that the code and the layout are unchanged. ArenaResource [see Arena.h] is the arena of Hanson for the bytes of any type, a resource of PoolAllocator, so that the containers take their memory from a few blocks freed all at once. The join trees take only a stateless allocator, since their algorithms build and free nodes with no tree at hand, also from many threads.
In CellHeap the cells have two fields, each nil, an atom or the address of a cell, and the cells not reachable from the roots are garbage, which collect() finds by marking the reachable cells and sweeping the others onto the free list; a root is a cell in use (addRoot() refuses a free one, whose marking would walk the free list). A marking by a visit in depth needs a stack as deep as the longest path of cells, which a collector, run when the memory is exhausted, cannot allocate.
Lemma 3 (Deutsch, Schorr and Waite). During the marking by pointer reversal (Algorithm 2.3.5E of Knuth), with \( c \) the current cell and \( p \) the previous one, the field of \( p \) that the visit followed holds the previous cell of \( p \), a bit of \( p \) telling which field it is, so that
\[ p , \; \mathrm{back}( p ) , \; \mathrm{back}( \mathrm{back}( p ) ) , \ldots \tag{4} \]
is the path of the visit from \( c \) back to the root, in reverse.
Going down a field, the visit stores \( p \) in that field of \( c \) and moves on; going back up, it reads the field of \( p \) that the bit names, restores in it the cell it comes from, and moves to \( p \). By (4) the path needs no stack, one bit per cell besides the mark, and every field is restored when the visit leaves its cell; each cell reached is entered once and left at most twice, and the marking costs time linear in the cells reached. The sweep reads every cell, and a collection costs \( O( n ) \) on a heap of \( n \) cells; a cons() costs \( O( 1 ) \) amortized over the cells freed by the collection that precedes it, when they are a constant fraction of the heap.