| 1 |
/* |
| 2 |
Allocators |
| 3 |
========== |
| 4 |
|
| 5 |
Using allocators defined here makes sense if there is a need to take a space for rather large amount of rather small objects. |
| 6 |
The basic idea is to take memory in reasonably large blocks and to distribute small chunks from those blocks. Once chunks are |
| 7 |
no longer needed, one can free them all at once, or free taken chunks individually. |
| 8 |
|
| 9 |
We define 3 types of allocators: |
| 10 |
|
| 11 |
1. HEAP - the simplest one, provides variable length memory chunks from larger blocks and frees them all on explicit |
| 12 |
request. There is no way to free individual objects, only the entire heap. The heap only grows, until freed. |
| 13 |
|
| 14 |
2. STOCK - provides variable length memory chunks from larger blocks, but allows to free individual objects as well as the |
| 15 |
entire stock. The stock grows and shrinks, by leaps and bounds, depending on parameters given during initialization. |
| 16 |
|
| 17 |
3. POOL - provides fixed size memory chunks from larger blocks. It allows to free individual chunks as well as the entire pool. |
| 18 |
In opposite to a stock, a pool also reuses a space reclaimed by freeing individual objects; before allocating a new block it |
| 19 |
firsts recycles freed chunks, if any. |
| 20 |
|
| 21 |
In general, memory chunks provided by allocators are never reallocated. Allocators do nothing with provided chunks until freed. |
| 22 |
|
| 23 |
Allocators are represented as small structures (several pointers and integers). We assume that such structures are either static |
| 24 |
variables, or members of larger structures. We don't bother to allocate a memory for them. Usage scheme is pretty similar for |
| 25 |
all: |
| 26 |
|
| 27 |
init() - just inititalize, don't allocate anything yet |
| 28 |
take() - take chunks |
| 29 |
take() |
| 30 |
take() |
| 31 |
... |
| 32 |
free() - free the all at once |
| 33 |
|
| 34 |
For stocks and pools there is a possibility to give back individual chunks: |
| 35 |
|
| 36 |
init() - like above |
| 37 |
take() - take chunks |
| 38 |
take() |
| 39 |
take() |
| 40 |
back() - give chunks back when no longer needed |
| 41 |
take() |
| 42 |
back() |
| 43 |
... |
| 44 |
free() - needed only if not all chunks have been given back |
| 45 |
|
| 46 |
All calls take a shell structure pointer as an argument. take() returns a void pointer, aligned according to used variant |
| 47 |
(8, 16, 32, 64). back() takes a void pointer as the second argument. It must be the pointer previously returned by take(). |
| 48 |
|
| 49 |
back() can be called in any order and can obviously be plotted with take(). By default, after back()-ing all taken chunks, the |
| 50 |
stock returns to its initial state (zero memory used). A special KEEP flag can be used during initialization to prevent |
| 51 |
freeing the last (sole) allocated block. If KEEP option is used, the allocator always keeps a single segment for further |
| 52 |
allocations. This is necessary only when there is a risk that just several take() calls will be immediatelly followed by the |
| 53 |
same number of back() calls. KEEP flag prevents allocating and freeing rather large blocks just to serve several chunks. And |
| 54 |
this is actually important only if there are no other blocks taken, that is, if there is only one, nearly empty block in use. |
| 55 |
In other cases KEEP flag doesn't matter, but allocators takes care to always have a block for fast allocs. |
| 56 |
|
| 57 |
There is also clear() operation that frees all but the recent block. One can use it to free all chunks taken so far, but to |
| 58 |
make the allocator ready for further allocs. If either KEEP flag is used or clear() is called, soner or later the user have to |
| 59 |
call free() explicitly, to remove all the remaining memory kept by the allocator. There is no KEEP flag for heaps, as heaps |
| 60 |
don't allow to free individual chunks. And so, the heap never needs to make a decision if the last sole block should be removed |
| 61 |
or not. The user makes the decision by calling clear() vs free() respectively. |
| 62 |
|
| 63 |
Pop |
| 64 |
=== |
| 65 |
|
| 66 |
A very last chunk taken can be quickly given back with |
| 67 |
|
| 68 |
pop(heap, taken, size) // for heap or stock |
| 69 |
pop(pool, taken) // for pool |
| 70 |
|
| 71 |
taken must be the chunk returned by the very last take(), size must be the size requested. If the chunk has been taken from |
| 72 |
the head block (more about blocks below), the block pointer returns to its previous position, as it was before the last take(). |
| 73 |
If the chunk has been taken from the sole block beneatch the head, the entire sole block (containing just that single chunk) |
| 74 |
is freed. The pop() operation is different than back(); the popped chunk doesn't cause freeing the head block when its refcount |
| 75 |
gets zero. So pop() operation breaks the concept of stock that frees all the memory once all taken chunks are given back. |
| 76 |
on the other hand, if for some reason the very last taken chunk is to be ignored, pop() is better, as it doesn't cause blocks |
| 77 |
scattering. The popped chunk pointer will probably be returned by the very next call to take(). In case of heap, pop() is |
| 78 |
the only way to discard the chunk, as there is no back() operation. |
| 79 |
|
| 80 |
Buffer interface |
| 81 |
================ |
| 82 |
|
| 83 |
When heap or stock is used by parsers, the caller oftenly doesn't know how many space will be needed for a data (this doesn't |
| 84 |
apply to pools, which returns constant size memory chunks). Here is an interface for the allocator-as-bufer case (same for |
| 85 |
heap and stock): |
| 86 |
|
| 87 |
some(heap, atleast, &space); |
| 88 |
... |
| 89 |
atleast <<= 1; |
| 90 |
more(heap, taken, written, atleast, &space); |
| 91 |
... |
| 92 |
done(heap, taken, written); |
| 93 |
|
| 94 |
some() operation provides a data pointer to at least a given bytes. The actual space provided for writing is set to the third |
| 95 |
argument. The caller may write space-bytes. If more space is needed, more() operation takes care to provide a chunk for a given |
| 96 |
amount of bytes and rewrites already written amount of bytes from a previous chunk to a new location. Same as with() some, the |
| 97 |
requests for atleast bytes, and the actual provided chunk size is given as space (space >= atleast). |
| 98 |
|
| 99 |
The function takes the pointer to the chunk previously taken; the one returned by some() or more(). This argument must not be NULL. |
| 100 |
If you don't want to copy a data, set written argument to zero. No matter if more() operation was used zero, one or multiple times, |
| 101 |
all the cycle must end with done(). Calls triple - some(), more() and done() - must not be interrupted by any other api calls. |
| 102 |
In particular, using take() or back() smells like a segfault. However, if there is a need discard the buffer being written |
| 103 |
(eg. input data error), instead of done() one may use |
| 104 |
|
| 105 |
giveup(heap, taken) |
| 106 |
|
| 107 |
If done() has already been called, pop() is the only option to discard the chunk |
| 108 |
|
| 109 |
pop(heap, taken, written) |
| 110 |
|
| 111 |
some() operation usually doesn't change the state of the heap, unless the heap head block is NULL, or atleast parameter is too |
| 112 |
large to fit the remaining block. more() usually changes the state, either by allocating a new head block, or by allocating |
| 113 |
a sole block just beneath the head (blocks and blocks tiling mechanism are described below). If a sole block has been taken for |
| 114 |
some large chunk subsequent calls to more() reallocate this sole block in place. It is assumed, that the size you request in subsequent |
| 115 |
calls generally grows. It is ok to request space-bytes, then call done() with written value less then requested. But the drawback |
| 116 |
is that if the chunk has already been allocated from a sole chunk, the space requested but not used is a waste. |
| 117 |
|
| 118 |
iof interface |
| 119 |
============= |
| 120 |
|
| 121 |
iof is an independent interface for buffers written/read byte-by-byte. When used together with allocators, it provides |
| 122 |
a convenient way to write byte data to the heap or stock, without a need for intermediate buffers. The buffer is setup with |
| 123 |
|
| 124 |
iof output, *O |
| 125 |
O = buffer_init(heap, &output); // doesn't allocate anything |
| 126 |
|
| 127 |
or |
| 128 |
|
| 129 |
output = BUFFER_INIT(heap); // doesn't allocate anything |
| 130 |
O = &output; |
| 131 |
|
| 132 |
iof keeps pointers to the beginning of the buffer, end of buffer, and current position. Once the position reaches the end, |
| 133 |
the iof internal handler updates the buffer providing more space to write. When used in conjunction with heap or stock, |
| 134 |
the space to write is the space provided by the heap or stock. To start the buffer session: |
| 135 |
|
| 136 |
O = buffer_some(heap, O, atleast) // ensure iof *O to have atleast bytes to be written |
| 137 |
|
| 138 |
Once you are done with writing some chunk |
| 139 |
|
| 140 |
buffer_done(heap, O) |
| 141 |
|
| 142 |
instead of buffer_done(), one may also use |
| 143 |
|
| 144 |
iof_flush(O) // calls buffer_done() and buffer_some() again |
| 145 |
|
| 146 |
which updates the underlying heap or stock, and makes the iof ready for a new chunk. iof itself does not allocate a memory, |
| 147 |
so it doesn't need finalizer. iof_close(output) does nothing. To drop the buffer use: |
| 148 |
|
| 149 |
buffer_giveup(heap, O) // restore the from before buffer_some() |
| 150 |
|
| 151 |
More often then not, we need to specify a minimal space for buffer each time, eg. for memcpy() or so. The actual space left |
| 152 |
can be checked with iof_left(O). The entire space of recent chunk is O->space (eq. O->end - O->buf). |
| 153 |
|
| 154 |
Identical interface for heap and stock. |
| 155 |
|
| 156 |
Blocks |
| 157 |
====== |
| 158 |
|
| 159 |
Each alloctor structure keeps a pointer to a head block, initially NULL. Most of new chunks are taken from the head. Once the |
| 160 |
space left in the head block is to small to provide a chunk of requested size, a new head is created and the previous one is |
| 161 |
linked to the head (blocks form a linked list). A stock block is named a ream, a heap block is named a pyre, a pool block is |
| 162 |
named pile (we need to distinguish structure names in code but in the description below they are all called blocks). Every |
| 163 |
block knows a number of chunks taken from that block (refcont). A stock also keeps a number of freed chunks [actually only |
| 164 |
for statistics; in most cases it doesn't need an extra space in struct ream, as thies structure member lays in the place |
| 165 |
f padding bytes.] |
| 166 |
|
| 167 |
We change the head block only if the new block is allocated, but we never change the head backward. Once some block became |
| 168 |
->prev, it will never became a head again. This ensures that the allocator have the head block that usually has a lot of space |
| 169 |
for new allocs. This needs a special care when removing a block that is not a head block. We check if the next block to the one |
| 170 |
being removed is the head. If it is, and if its refcount is zero (and no KEEP flag is used) the head is removed as well. |
| 171 |
|
| 172 |
The basis of pools is similar to stocks and heaps, but there are some significant differences. A pool servers memory chunks of |
| 173 |
equal size, specified during initialization. This also means that the pool knows the boundaries of individual chunks (stock and |
| 174 |
heap doesn't). A pool provides iterators over chunks in use (taken but not given back yet). A pool shell structure keeps |
| 175 |
a pointer to a head block and a tail block (both may point a different block, the same block or NULL). This is necessary only |
| 176 |
for iterators to let the user follow the chunks from the first or from the last taken. The extra cost of maintaining both |
| 177 |
->head and ->tail is neglectable. |
| 178 |
|
| 179 |
Refcounting |
| 180 |
=========== |
| 181 |
|
| 182 |
Heap refcounting: whenever a new chunk is taken, the block refcount is incremented. It is never decremented, but plays an |
| 183 |
important role in block tiling algorithm (below). No KEEP flag is used here. All the blocks are removed on free(), all but |
| 184 |
recent are removed on clear(). |
| 185 |
|
| 186 |
Stock refcounting: whenever a new chunk in taken from the block, the block refcount is incremented. Whenever the chunk is given |
| 187 |
back, the refcount is decremented. When the refcount gets zero, the block is removed and freed. To remove the block from the |
| 188 |
list (any block, not necessarily a head block), a stock needs 2-directional list; every block has ->next and ->prev links. The |
| 189 |
head block of the stock is freed only if this is the last (sole) block and no KEEP flag was used during initialization. |
| 190 |
Otherwise the block is just reset, becoming ready for further allocations - refcount gets zero, data space reset to an initial |
| 191 |
state. |
| 192 |
|
| 193 |
Pool refcounting: pretty much like with stocks, except that any chunk given back can be recycled on further take(). |
| 194 |
|
| 195 |
Ghosts |
| 196 |
====== |
| 197 |
|
| 198 |
Every allocated block starts with a private structure for next/prev links, data pointer, refcount. We call it a block ghost. |
| 199 |
Except from heap, individual chunks also need a ghost (chunk ghost) so that we are able to know from which block the chunk |
| 200 |
comes from once the chunk is given back by the user (heaps don't have back() operation so data chunks have no ghosts). We keep |
| 201 |
ghosts possibly small. Chunk ghosts are of size natural for alignment variant (1, 2, 4 or 8 bytes). Block ghosts are somewhat |
| 202 |
larger. Statistics show clearly that it is worthy to keep them as small as possible: |
| 203 |
- chunk ghosts keep offset to the block ghost, not a pointer to it (we use the pointer only if it makes no difference |
| 204 |
to the chunk size; 64-bit aligned variant on 64-bit machine, 32 and 64 variants on 32-bit machine) |
| 205 |
- block ghosts uses a data pointer (not an offset) so that we are able to record any requested chunk size (size_t) and to avoid |
| 206 |
long array indexing on every chunk request |
| 207 |
|
| 208 |
At some point we considered storing a sheel structure pointer in the block ghost, then back() operation wouldn't need an extra |
| 209 |
argument. But stats showed that the size of the block ghost is the most significant factor in memory usage efficiency, so eliminating |
| 210 |
this extra pointer pays off. Besides, this would make impossible to relocate the shell structure. We don't allocate a memory |
| 211 |
for the shell, so we shouldn't make assumptions of shell structure address. |
| 212 |
|
| 213 |
Tiling algorithm |
| 214 |
================ |
| 215 |
|
| 216 |
Tiling the block size refers to stocks and heaps that serves memory chunks of variable size. Both stock and heap performs best |
| 217 |
when the average size of requested chunks is a way smaller that the configured block size. But both also put no limitations on |
| 218 |
chunk sizes, so they need to cope with situation, where the requested size is quite large, eg. half of the block size or even |
| 219 |
more than the block size. Here is the algorithm used for blocks tiling: |
| 220 |
|
| 221 |
1. When the requested chunk size fills in the recent block, just serve it from that block. This is the best and hopefully the |
| 222 |
most common case. |
| 223 |
|
| 224 |
2. When the requested chunk size is larger that the space left in the recent block, the new block must be allocated. But there |
| 225 |
are two ways: |
| 226 |
|
| 227 |
a) either replace the head block with the new block so that the list of blocks is |
| 228 |
|
| 229 |
... <- prev <- head so far <- new head |
| 230 |
|
| 231 |
b) or insert the block just "below the head", keeping the head intact, |
| 232 |
|
| 233 |
... <- prev <- new single head <- head |
| 234 |
|
| 235 |
The first is the regular case. It is used when the space left in the head so far is small (can be neglected), and the requested |
| 236 |
size is relatively small (will fit the new block). If the space left in the head block is worthy to bother, or the requested |
| 237 |
chunk size is rather large, the new chunk is served from a single block, allocated just for that chunk. The block is of the |
| 238 |
size needed for that chunk. The block never becomes the head, no other chunks will be served from it (its refcount is |
| 239 |
permanently 1, until freed). |
| 240 |
|
| 241 |
Much depends on what is considered 'small, neglectable block space' and 'rather large chunk size'. The later is easier to |
| 242 |
imagine. When the requested size is larger than the block size used for a given allocator, then the size is definitelly |
| 243 |
considered large. When it is smaller than the block size, but still large enough to occupy most of the block size (grabbing |
| 244 |
quite some space for tiny chunks), it is also considered large. As the block size, what is considered 'large' can be spcified |
| 245 |
during initialization. A setup that works fine for me is (large = block_size / 2). |
| 246 |
|
| 247 |
Making a decision what is the left block space we can neglect is quite not obvious. At first approach we used a constant value, |
| 248 |
requested from the user during allocator initialization. But it is hard to select a good default. Now we compute this value |
| 249 |
from block params, by dividing a complete space occupied so far in the block by the number of chunks served from that block |
| 250 |
(the average size of chunks allocated from this block). We assume that the average chunk size (or smaller) is the space we can |
| 251 |
neglect. The logic behind is the following: if the space left in the block is larger than the average, it makes sense not to |
| 252 |
waste this space and keep it for further allocs. If the space left in the block is less than the average, there is only a little |
| 253 |
chance we will get a request for suitable size, so we sacrifice that space and we start allocating from a new block. |
| 254 |
|
| 255 |
Statistics showed a caveat in average == treshold approach. Suppose we have a block that has the average chunk size 16, there |
| 256 |
is 18 bytes left in the block (not neglectable), and the user request is 20 bytes. Allocating a single block for 20 bytes is |
| 257 |
bad, because the block ghost is 24 bytes (more internal than allocated memory). Allocating many of such blocks gives bad results; |
| 258 |
much more allocs than necessary, large waste. To avoid that, we help to neglect the remaining block space by checking if the |
| 259 |
space left is smaller than the block ghost size, which is an inevitable cost anyway. |
| 260 |
|
| 261 |
Stats below shows clearly that we should rather focus on "how to avoid producing sole-chunk blocks" instead of "how to feel the |
| 262 |
remaining space". |
| 263 |
|
| 264 |
Recycling |
| 265 |
========= |
| 266 |
|
| 267 |
Recycling applies only to pools. When a chunk is given back, it is inserted into a list of items for recycling. Every pool |
| 268 |
block keeps a head of that list. Once a chunk is given back, it is inserted as recycling head and the previous head is attached |
| 269 |
to a new head. Since every chunk is associated with a ghost, we use ghosts to store a link (pointer or offset) to another item |
| 270 |
for recycling. Note that the ghost always keeps either a link to the block it belongs to, or a link to another recyclable ghost |
| 271 |
of the same block. This is used by iteratos to distinguish the chunk currently in use from the chunk that has already been |
| 272 |
given back; if the link points the block, the chunk is in use. |
| 273 |
|
| 274 |
A pool block that has at least one recyclable chunk is called a squot. A pool shell structure keeps 2-directional list of |
| 275 |
squots. Once a pool block becomes a squot, it is inserted to that list. Once its all recyclable items has been used, it is |
| 276 |
removed from the squots list. In every moment, the pool has an access to a list of all squots, and therefore, to a list of all |
| 277 |
recyclable items. |
| 278 |
|
| 279 |
Whenever there is a request for a new chunk, at first it is served from the head block, as this is the easiest and the cheapest way. |
| 280 |
Once the recent block has no more place for new items, recycling list is used, starting from the head recyclable chunk of the head squot. |
| 281 |
In practise this is always the most recently reclaimed chunk ghost. During further allocs, a pool will first utilize all recyclables |
| 282 |
from all squots before allocating a new block. |
| 283 |
|
| 284 |
Stats |
| 285 |
===== |
| 286 |
|
| 287 |
Some numbers. The test made on a stock8, block size 255 bytes, 10000 allocations, random chunk sizes from 1 to 32 bytes |
| 288 |
(average 16). These are rather tight constraints because of 255 buffer limit. First approach: |
| 289 |
|
| 290 |
blocks: 903 - this is the actual number of malloc() calls |
| 291 |
singles: 214, 23.70% of all blocks |
| 292 |
waste: 20.16% - total memory that was allocated but not requested by the user |
| 293 |
block ghosts 10.04%, plus single block ghosts 3.12% |
| 294 |
chunk ghosts 4.55% |
| 295 |
neglected block tails 2.45% |
| 296 |
|
| 297 |
After adding a test for left space that helps in 'neglect remainig space or make sole chunk block' decision: |
| 298 |
|
| 299 |
blocks: 723 - a way better |
| 300 |
singles 0 |
| 301 |
waste: 19.04% - slightly better |
| 302 |
block ghosts 10.67% |
| 303 |
chunk ghosts 4.61% |
| 304 |
neglected block tails 3.76% |
| 305 |
|
| 306 |
The actual numbers vary depending on the buffer size, the average elements size and, of course, taken alignment variant. After |
| 307 |
some parameters tuning, on various tests we get 5-19% total waste for stocks, 3-14% total waste for heaps. But the basic scheme |
| 308 |
of statistics remains similar: we take relatively lots of space for blocks ghost (5-10% of total memory taken), some inevitable |
| 309 |
space for chunk ghosts (varies, 4-13% on various tests), and a little waste of neglected block tails (2-4%). Quite |
| 310 |
surprisingly, block ghosts are, in sum, oftenly more significant than individual chunk ghosts (for the test above over half of |
| 311 |
all the waste!). The number of block ghosts (equals the number of blocks) mostly depends on block size vs chunk size relation. |
| 312 |
But seemingly it is worthy to bother about the size of the block ghost and the number of blocks taken - the less the better. |
| 313 |
The waste of ghosts of individual objects (stock and pool) is inevitable, and depends only on the number/size of objects taken. |
| 314 |
We can't use smaller ghosts, we can't do better. Anyways, the least significant is the waste of neglected block tails. |
| 315 |
|
| 316 |
Pools stats are pretty similar, but more predictable because of known chunks size. A pool block ghost is somewhat larger |
| 317 |
structure because it keeps ->nextsquot / ->prevsquot pointers among ->next / ->prev. On the other hand, it doesn't need |
| 318 |
->unused counter, as for fixed-length chunks it can always be computed from the refcount and used data. Also somewhat larger |
| 319 |
block ghost structure is compensated by the fact that the are no tail block waste and there is no 'neglect or not' problem. |
| 320 |
|
| 321 |
Alignment |
| 322 |
========= |
| 323 |
|
| 324 |
Each allocator has 4 variants for 1, 2, 4, 8 bytes alignment respectively. Eg. stock32_take() always returns a pointer aligned |
| 325 |
to 4 bytes, heap64_take() returns a pointer aligned to 8 bytes. You can ask for any data length, but in practise you'll always |
| 326 |
obtain 1N, 2N, 4N or 8N. Alignment implies data padding unless the user requests for "aligned" sizes. In statistics the padding |
| 327 |
is not considered a waste. |
| 328 |
|
| 329 |
Zeroing |
| 330 |
======= |
| 331 |
|
| 332 |
All heap, stock and pool may return zeroed memory chunks, depending on initial flags: |
| 333 |
|
| 334 |
HEAP_ZERO |
| 335 |
STOCK_ZERO |
| 336 |
POOL_ZERO |
| 337 |
|
| 338 |
There are also take0() variants that simply return memset(take(), 0, size), regardless the flag. |
| 339 |
*/ |
| 340 |
|
| 341 |
#ifndef UTIL_MEM_ALLC_C |
| 342 |
#define UTIL_MEM_ALLC_C |
| 343 |
|
| 344 |
/* |
| 345 |
Common internals for allocators suite. A selection or all of the following defines (from api headers) should already be there: |
| 346 |
|
| 347 |
UTIL_MEM_HEAP_H // utilmemheap.h |
| 348 |
UTIL_MEM_STOCK_H // utilmemstock.h |
| 349 |
UTIL_MEM_POOL_H // utilmempool.h |
| 350 |
|
| 351 |
*/ |
| 352 |
|
| 353 |
#include <string.h> // memset() |
| 354 |
#include <stdio.h> // printf() |
| 355 |
|
| 356 |
#include "utilmem.h" |
| 357 |
|
| 358 |
//#if defined(DEBUG) && debug != 0 |
| 359 |
#if 1 |
| 360 |
# define ASSERT8(cond) ((void)((cond) || (printf("8bit allocator assertion, %s:%d: %s\n", __FILE__, __LINE__, #cond), 0))) |
| 361 |
# define ASSERT16(cond) ((void)((cond) || (printf("16bit allocator assertion, %s:%d: %s\n", __FILE__, __LINE__, #cond), 0))) |
| 362 |
# define ASSERT32(cond) ((void)((cond) || (printf("32bit allocator assertion, %s:%d: %s\n", __FILE__, __LINE__, #cond), 0))) |
| 363 |
# define ASSERT64(cond) ((void)((cond) || (printf("64bit allocator assertion, %s:%d: %s\n", __FILE__, __LINE__, #cond), 0))) |
| 364 |
#else |
| 365 |
# define ASSERT8(cond) (void)0 |
| 366 |
# define ASSERT16(cond) (void)0 |
| 367 |
# define ASSERT32(cond) (void)0 |
| 368 |
# define ASSERT64(cond) (void)0 |
| 369 |
#endif |
| 370 |
|
| 371 |
#if defined(UTIL_MEM_STOCK_H) || defined(UTIL_MEM_POOL_H) |
| 372 |
struct ghost8{ |
| 373 |
uint8_t offset; |
| 374 |
}; |
| 375 |
|
| 376 |
struct ghost16 { |
| 377 |
uint16_t offset; |
| 378 |
}; |
| 379 |
|
| 380 |
#ifdef BIT32 |
| 381 |
struct ghost32 { |
| 382 |
union { |
| 383 |
#ifdef UTIL_MEM_STOCK_H |
| 384 |
ream32 *ream; |
| 385 |
#endif |
| 386 |
#ifdef UTIL_MEM_POOL_H |
| 387 |
pile32 *pile; |
| 388 |
ghost32 *nextfree; |
| 389 |
#endif |
| 390 |
void *block; |
| 391 |
}; |
| 392 |
}; |
| 393 |
#else |
| 394 |
struct ghost32 { |
| 395 |
uint32_t offset; |
| 396 |
}; |
| 397 |
#endif |
| 398 |
|
| 399 |
struct ghost64 { |
| 400 |
union { |
| 401 |
#ifdef UTIL_MEM_STOCK_H |
| 402 |
ream64 *ream; |
| 403 |
#endif |
| 404 |
#ifdef UTIL_MEM_POOL_H |
| 405 |
pile64 *pile; |
| 406 |
ghost64 *nextfree; |
| 407 |
#endif |
| 408 |
void *block; |
| 409 |
}; |
| 410 |
#ifdef BIT32 |
| 411 |
uint8_t dummy[4]; // force 8 |
| 412 |
#endif |
| 413 |
}; |
| 414 |
#endif |
| 415 |
|
| 416 |
/* |
| 417 |
All offsets related macro horror is here. Block is 4/8-bytes aligned (32/64 pointer size), ream->data is adjusted to 1/2/4/8-bytes accordingly. |
| 418 |
Therefore all offsets we store and pointers we cast, should be properly aligned. In all cases, sizes and offsets refers to bytes. |
| 419 |
We need data ghosts only to access the block. For 8 and 16 we use 8/16 bit offsets to keep the ghost smaller. For 32 and 64 we either use offset, |
| 420 |
or a pointer to the ream. |
| 421 |
|
| 422 |
malloc() is obviously expected to return a pointer properly allowed for all standard c-types. For 64-bit we can safely expect at least 8-bytes aligned. |
| 423 |
(at least, because long double may need 16 bytes on gcc64, or 8 bytes on msvc64, or weird on some exotics). On 32 bit machines pointers are 4 bytes |
| 424 |
aligned, even long long is 4-bytes aligned. But double on 32bit machine is 8-bytes aligned on windows, 4 bytes aligned in linux (compiler option |
| 425 |
-malign-double makes it 8-bytes aligned). Anyways, we cannot expect that on 32bit machine the result of malloc is always 8-bytes aligned. |
| 426 |
This requires a very special treatment of 64-variant on 32bit machine: the first data ghost may need to be 4-bytes off. Should we ensure 4 bytes |
| 427 |
more from malloc just in case? Hmm padding will be there anyway, as we adjust ream->data size to bytes boundaries. |
| 428 |
|
| 429 |
In both 32/64bit environments, the ghost keeps a pointer to the block. On 32bit machine, the first chunk ghost address may need to be +4, |
| 430 |
as this is not ensured by malloc(). See struct ream64 {}. We have an extra test; the final ghost pointer will be properly aligned iff |
| 431 |
|
| 432 |
((block & 7 == 0) && (sizeof(block64) & 7 == 0)) || ((block & 7 == 4) && (sizeof(block64) & 7 == 4) |
| 433 |
|
| 434 |
or in short |
| 435 |
|
| 436 |
((block + 1) & 7) == 0 |
| 437 |
|
| 438 |
otherwise it needs 4 bytes offset. |
| 439 |
*/ |
| 440 |
|
| 441 |
#define pointer_tointeger(p) ((size_t)(p)) // & not allowed on pointer |
| 442 |
|
| 443 |
#define pointer_aligned32(p) ((pointer_tointeger(p) & 3) == 0) |
| 444 |
#define pointer_aligned64(p) ((pointer_tointeger(p) & 7) == 0) |
| 445 |
|
| 446 |
#define void_data(data) ((void *)(data)) |
| 447 |
#define byte_data(data) ((uint8_t *)(data)) |
| 448 |
|
| 449 |
/* top of the block ghost */ |
| 450 |
|
| 451 |
#define block_top(block) (byte_data(block + 1)) |
| 452 |
|
| 453 |
/* where the data begins */ |
| 454 |
|
| 455 |
#define block_edge8(block) block_top(block) |
| 456 |
#define block_edge16(block) block_top(block) |
| 457 |
#define block_edge32(block) block_top(block) |
| 458 |
|
| 459 |
#ifdef BIT32 |
| 460 |
# define ALIGN64ON32(block) (pointer_aligned64(block + 1) ? 0 : 4) |
| 461 |
# define block_edge64(block) (block_top(block) + ALIGN64ON32(block)) |
| 462 |
#else |
| 463 |
# define block_edge64(block) block_top(block) |
| 464 |
#endif |
| 465 |
|
| 466 |
#define block_left8(block, size) (size) |
| 467 |
#define block_left16(block, size) (size) |
| 468 |
#define block_left32(block, size) (size) |
| 469 |
#ifdef BIT32 |
| 470 |
# define block_left64(block, size) (size - ALIGN64ON32(block)) |
| 471 |
#else |
| 472 |
# define block_left64(block, size) (size) |
| 473 |
#endif |
| 474 |
|
| 475 |
/* consumed block space; it is important to use edge() macros that involves ALIGN64ON32() */ |
| 476 |
|
| 477 |
#define block_used8(block) (block->data - block_edge8(block)) |
| 478 |
#define block_used16(block) (block->data - block_edge16(block)) |
| 479 |
#define block_used32(block) (block->data - block_edge32(block)) |
| 480 |
#define block_used64(block) (block->data - block_edge64(block)) |
| 481 |
|
| 482 |
/* align requested size to keep ream->data / pyre->data always aligned. size is always size_t, no insane overflow checks */ |
| 483 |
|
| 484 |
#define align_size8(size) ((void)size) |
| 485 |
#define align_size16(size) (size = aligned_size16(size)) |
| 486 |
#define align_size32(size) (size = aligned_size32(size)) |
| 487 |
#define align_size64(size) (size = aligned_size64(size)) |
| 488 |
|
| 489 |
/* |
| 490 |
done() and pop() operations decrements block->left space by an aligned size; block->left -= alignedwritten. Lets have 8-bytes aligned |
| 491 |
variant block. If we tell the user there is 15 bytes left (block->left == 15) and the user taked 12. Aligned is 16, we cannot substract. |
| 492 |
We could eventually set block->left to 0, but then pop() operation would no be allowed. Hance, block->left must be aligned. The procedure |
| 493 |
is different than for size (size_t), we cannot cross 0xff/0xffff,... bondaries. |
| 494 |
*/ |
| 495 |
|
| 496 |
#define align_space8(space) ((void)space) |
| 497 |
#define align_space16(space) (space = aligned_space16(space)) |
| 498 |
#define align_space32(space) (space = aligned_space32(space)) |
| 499 |
#define align_space64(space) (space = aligned_space64(space)) |
| 500 |
|
| 501 |
/* handling ghost structure (stock and pool) */ |
| 502 |
|
| 503 |
#if defined(UTIL_MEM_STOCK_H) || defined(UTIL_MEM_POOL_H) |
| 504 |
|
| 505 |
/* ghost offset from block top; not from bottom because we must not exceed offset limit */ |
| 506 |
|
| 507 |
#define ghost_offset(block, ghost) (byte_data(ghost) - block_top(block)) |
| 508 |
|
| 509 |
/* ghost <-> data */ |
| 510 |
|
| 511 |
#define ghost_data(ghost) ((void *)(ghost + 1)) |
| 512 |
|
| 513 |
/* cast from data to ghost structure goes via (void *) to shut up warnigns, alignment ok */ |
| 514 |
|
| 515 |
#define data_ghost8(data) (((ghost8 *)void_data(data)) - 1) |
| 516 |
#define data_ghost16(data) (((ghost16 *)void_data(data)) - 1) |
| 517 |
#define data_ghost32(data) (((ghost32 *)void_data(data)) - 1) |
| 518 |
#define data_ghost64(data) (((ghost64 *)void_data(data)) - 1) |
| 519 |
|
| 520 |
/* ghost <-> block */ |
| 521 |
|
| 522 |
#define ghost_block8(ghost, block8) ((block8 *)void_data(byte_data(ghost) - ghost->offset - sizeof(block8))) |
| 523 |
#define ghost_block16(ghost, block16) ((block16 *)void_data(byte_data(ghost) - ghost->offset - sizeof(block16))) |
| 524 |
#ifdef BIT32 |
| 525 |
# define ghost_block32(ghost, block32) (ghost->block) |
| 526 |
#else |
| 527 |
# define ghost_block32(ghost, block32) ((block32 *)void_data(byte_data(ghost) - ghost->offset - sizeof(block32))) |
| 528 |
#endif |
| 529 |
#define ghost_block64(ghost, block64) (ghost->block) |
| 530 |
|
| 531 |
/* ghost init */ |
| 532 |
|
| 533 |
#define ghost_next8(block, ghost) ((ghost = block->dataghost), (ghost->offset = (uint8_t)ghost_offset(block, ghost))) |
| 534 |
#define ghost_next16(block, ghost) ((ghost = block->dataghost), (ghost->offset = (uint16_t)ghost_offset(block, ghost))) |
| 535 |
#ifdef BIT32 |
| 536 |
# define ghost_next32(bl0ck, ghost) ((ghost = bl0ck->dataghost), (ghost->block = bl0ck)) |
| 537 |
#else |
| 538 |
# define ghost_next32(block, ghost) ((ghost = block->dataghost), (ghost->offset = (uint32_t)ghost_offset(block, ghost))) |
| 539 |
#endif |
| 540 |
#define ghost_next64(bl0ck, ghost) ((ghost = bl0ck->dataghost), (ghost->block = bl0ck)) |
| 541 |
|
| 542 |
#endif |
| 543 |
|
| 544 |
/* average block chunk size */ |
| 545 |
|
| 546 |
#define average_block_chunk8(ream) (block_used8(ream) / ream->chunks) |
| 547 |
#define average_block_chunk16(ream) (block_used16(ream) / ream->chunks) |
| 548 |
#define average_block_chunk32(ream) (block_used32(ream) / ream->chunks) |
| 549 |
#define average_block_chunk64(ream) (block_used64(ream) / ream->chunks) |
| 550 |
|
| 551 |
/* |
| 552 |
neglect remaining block tail and start a new block or create a single block; a test for (block->chunks > 0) is a sanity; |
| 553 |
if block->chunks is zero (block has a full space left), we shouldn't get there, except when alloc->large is larger then alloc->space |
| 554 |
*/ |
| 555 |
|
| 556 |
#define take_new_block8(alloc, ghoststruct, block, size) \ |
| 557 |
((size < alloc->large) && (block->left <= sizeof(ghoststruct) || (block->chunks > 0 && block->left <= average_block_chunk8(block)))) |
| 558 |
#define take_new_block16(alloc, ghoststruct, block, size) \ |
| 559 |
((size < alloc->large) && (block->left <= sizeof(ghoststruct) || (block->chunks > 0 && block->left <= average_block_chunk16(block)))) |
| 560 |
#define take_new_block32(alloc, ghoststruct, block, size) \ |
| 561 |
((size < alloc->large) && (block->left <= sizeof(ghoststruct) || (block->chunks > 0 && block->left <= average_block_chunk32(block)))) |
| 562 |
#define take_new_block64(alloc, ghoststruct, block, size) \ |
| 563 |
((size < alloc->large) && (block->left <= sizeof(ghoststruct) || (block->chunks > 0 && block->left <= average_block_chunk64(block)))) |
| 564 |
|
| 565 |
/* empty */ |
| 566 |
|
| 567 |
#define head_block_empty(alloc, block) (((block = alloc->head) == NULL) || (block->chunks == 0 && block->prev == NULL)) |
| 568 |
|
| 569 |
#endif |