2 * UCW Library -- Memory Pools
4 * (c) 1997--2014 Martin Mares <mj@ucw.cz>
5 * (c) 2007 Pavel Charvat <pchar@ucw.cz>
7 * This software may be freely distributed and used according to the terms
8 * of the GNU Lesser General Public License.
14 #include <ucw/alloc.h>
17 #ifdef CONFIG_UCW_CLEAN_ABI
18 #define mp_alloc ucw_mp_alloc
19 #define mp_alloc_internal ucw_mp_alloc_internal
20 #define mp_alloc_noalign ucw_mp_alloc_noalign
21 #define mp_alloc_zero ucw_mp_alloc_zero
22 #define mp_append_printf ucw_mp_append_printf
23 #define mp_append_vprintf ucw_mp_append_vprintf
24 #define mp_delete ucw_mp_delete
25 #define mp_flush ucw_mp_flush
26 #define mp_grow_internal ucw_mp_grow_internal
27 #define mp_init ucw_mp_init
28 #define mp_memdup ucw_mp_memdup
29 #define mp_multicat ucw_mp_multicat
30 #define mp_new ucw_mp_new
31 #define mp_open ucw_mp_open
32 #define mp_pop ucw_mp_pop
33 #define mp_printf ucw_mp_printf
34 #define mp_push ucw_mp_push
35 #define mp_realloc ucw_mp_realloc
36 #define mp_realloc_zero ucw_mp_realloc_zero
37 #define mp_restore ucw_mp_restore
38 #define mp_shrink ucw_mp_shrink
39 #define mp_spread_internal ucw_mp_spread_internal
40 #define mp_start ucw_mp_start
41 #define mp_start_internal ucw_mp_start_internal
42 #define mp_start_noalign ucw_mp_start_noalign
43 #define mp_stats ucw_mp_stats
44 #define mp_str_from_mem ucw_mp_str_from_mem
45 #define mp_strdup ucw_mp_strdup
46 #define mp_strjoin ucw_mp_strjoin
47 #define mp_total_size ucw_mp_total_size
48 #define mp_vprintf ucw_mp_vprintf
58 * Memory pool state (see @mp_push(), ...).
59 * You should use this one as an opaque handle only, the insides are internal.
61 struct mempool_state {
64 struct mempool_state *next;
69 * You should use this one as an opaque handle only, the insides are internal.
72 struct ucw_allocator allocator; // This must be the first element
73 struct mempool_state state;
74 void *unused, *last_big;
75 size_t chunk_size, threshold;
80 struct mempool_stats { /** Mempool statistics. See @mp_stats(). **/
81 u64 total_size; /* Real allocated size in bytes */
82 u64 used_size; /* Estimated size allocated from mempool to application */
83 uint chain_count[3]; /* Number of allocated chunks in small/big/unused chains */
84 u64 chain_size[3]; /* Size of allocated chunks in small/big/unused chains */
94 * Initialize a given mempool structure.
95 * @chunk_size must be in the interval `[1, SIZE_MAX / 2]`.
96 * It will allocate memory by this large chunks and take
97 * memory to satisfy requests from them.
99 * Memory pools can be treated as <<trans:respools,resources>>, see <<trans:res_mempool()>>.
101 void mp_init(struct mempool *pool, size_t chunk_size);
104 * Allocate and initialize a new memory pool.
105 * See @mp_init() for @chunk_size limitations.
107 * The new mempool structure is allocated on the new mempool.
109 * Memory pools can be treated as <<trans:respools,resources>>, see <<trans:res_mempool()>>.
111 struct mempool *mp_new(size_t chunk_size);
114 * Cleanup mempool initialized by mp_init or mp_new.
115 * Frees all the memory allocated by this mempool and,
116 * if created by @mp_new(), the @pool itself.
118 void mp_delete(struct mempool *pool);
121 * Frees all data on a memory pool, but leaves it working.
122 * It can keep some of the chunks allocated to serve
123 * further allocation requests. Leaves the @pool alive,
124 * even if it was created with @mp_new().
126 void mp_flush(struct mempool *pool);
129 * Compute some statistics for debug purposes.
130 * See the definition of the <<struct_mempool_stats,mempool_stats structure>>.
131 * This function scans the chunk list, so it can be slow. If you are interested
132 * in total memory consumption only, mp_total_size() is faster.
134 void mp_stats(struct mempool *pool, struct mempool_stats *stats);
137 * Return how many bytes were allocated by the pool, including unused parts
138 * of chunks. This function runs in constant time.
140 u64 mp_total_size(struct mempool *pool);
143 * Release unused chunks of memory reserved for further allocation
144 * requests, but stop if mp_total_size() would drop below @min_total_size.
146 void mp_shrink(struct mempool *pool, u64 min_total_size);
150 * Allocation routines
151 * -------------------
154 /* For internal use only, do not call directly */
155 void *mp_alloc_internal(struct mempool *pool, size_t size) LIKE_MALLOC;
158 * The function allocates new @size bytes on a given memory pool.
159 * If the @size is zero, the resulting pointer is undefined,
160 * but it may be safely reallocated or used as the parameter
161 * to other functions below.
163 * The resulting pointer is always aligned to a multiple of
164 * `CPU_STRUCT_ALIGN` bytes and this condition remains true also
165 * after future reallocations.
167 void *mp_alloc(struct mempool *pool, size_t size);
170 * The same as @mp_alloc(), but the result may be unaligned.
172 void *mp_alloc_noalign(struct mempool *pool, size_t size);
175 * The same as @mp_alloc(), but fills the newly allocated memory with zeroes.
177 void *mp_alloc_zero(struct mempool *pool, size_t size);
180 * Inlined version of @mp_alloc().
182 static inline void *mp_alloc_fast(struct mempool *pool, size_t size)
184 size_t avail = pool->state.free[0] & ~(size_t)(CPU_STRUCT_ALIGN - 1);
187 pool->state.free[0] = avail - size;
188 return (byte *)pool->state.last[0] - avail;
191 return mp_alloc_internal(pool, size);
195 * Inlined version of @mp_alloc_noalign().
197 static inline void *mp_alloc_fast_noalign(struct mempool *pool, size_t size)
199 if (size <= pool->state.free[0])
201 void *ptr = (byte *)pool->state.last[0] - pool->state.free[0];
202 pool->state.free[0] -= size;
206 return mp_alloc_internal(pool, size);
210 * Return a generic allocator representing the given mempool.
212 static inline struct ucw_allocator *mp_get_allocator(struct mempool *mp)
214 return &mp->allocator;
222 * You do not need to know, how a buffer will need to be large,
223 * you can grow it incrementally to needed size. You can grow only
224 * one buffer at a time on a given mempool.
226 * Similar functionality is provided by <<growbuf:,growing buffes>> module.
229 /* For internal use only, do not call directly */
230 void *mp_start_internal(struct mempool *pool, size_t size) LIKE_MALLOC;
231 void *mp_grow_internal(struct mempool *pool, size_t size);
232 void *mp_spread_internal(struct mempool *pool, void *p, size_t size);
234 static inline uint mp_idx(struct mempool *pool, void *ptr)
236 return ptr == pool->last_big;
240 * Open a new growing buffer (at least @size bytes long).
241 * If the @size is zero, the resulting pointer is undefined,
242 * but it may be safely reallocated or used as the parameter
243 * to other functions below.
245 * The resulting pointer is always aligned to a multiple of
246 * `CPU_STRUCT_ALIGN` bytes and this condition remains true also
247 * after future reallocations. There is an unaligned version as well.
249 * Keep in mind that you can't make any other pool allocations
250 * before you "close" the growing buffer with @mp_end().
252 void *mp_start(struct mempool *pool, size_t size);
253 void *mp_start_noalign(struct mempool *pool, size_t size);
256 * Inlined version of @mp_start().
258 static inline void *mp_start_fast(struct mempool *pool, size_t size)
260 size_t avail = pool->state.free[0] & ~(size_t)(CPU_STRUCT_ALIGN - 1);
264 pool->state.free[0] = avail;
265 return (byte *)pool->state.last[0] - avail;
268 return mp_start_internal(pool, size);
272 * Inlined version of @mp_start_noalign().
274 static inline void *mp_start_fast_noalign(struct mempool *pool, size_t size)
276 if (size <= pool->state.free[0])
279 return (byte *)pool->state.last[0] - pool->state.free[0];
282 return mp_start_internal(pool, size);
286 * Return start pointer of the growing buffer allocated by latest @mp_start() or a similar function.
288 static inline void *mp_ptr(struct mempool *pool)
290 return (byte *)pool->state.last[pool->idx] - pool->state.free[pool->idx];
294 * Return the number of bytes available for extending the growing buffer.
295 * (Before a reallocation will be needed).
297 static inline size_t mp_avail(struct mempool *pool)
299 return pool->state.free[pool->idx];
303 * Grow the buffer allocated by @mp_start() to be at least @size bytes long
304 * (@size may be less than @mp_avail(), even zero). Reallocated buffer may
305 * change its starting position. The content will be unchanged to the minimum
306 * of the old and new sizes; newly allocated memory will be uninitialized.
307 * Multiple calls to mp_grow() have amortized linear cost wrt. the maximum value of @size. */
308 static inline void *mp_grow(struct mempool *pool, size_t size)
310 return (size <= mp_avail(pool)) ? mp_ptr(pool) : mp_grow_internal(pool, size);
314 * Grow the buffer by at least one byte -- equivalent to <<mp_grow(),`mp_grow`>>`(@pool, @mp_avail(pool) + 1)`.
316 static inline void *mp_expand(struct mempool *pool)
318 return mp_grow_internal(pool, mp_avail(pool) + 1);
322 * Ensure that there is at least @size bytes free after @p,
323 * if not, reallocate and adjust @p.
325 static inline void *mp_spread(struct mempool *pool, void *p, size_t size)
327 return (((size_t)((byte *)pool->state.last[pool->idx] - (byte *)p) >= size) ? p : mp_spread_internal(pool, p, size));
331 * Append a character to the growing buffer. Called with @p pointing after
332 * the last byte in the buffer, returns a pointer after the last byte
333 * of the new (possibly reallocated) buffer.
335 static inline char *mp_append_char(struct mempool *pool, char *p, uint c)
337 p = mp_spread(pool, p, 1);
343 * Append a memory block to the growing buffer. Called with @p pointing after
344 * the last byte in the buffer, returns a pointer after the last byte
345 * of the new (possibly reallocated) buffer.
347 static inline void *mp_append_block(struct mempool *pool, void *p, const void *block, size_t size)
349 char *q = mp_spread(pool, p, size);
350 memcpy(q, block, size);
355 * Append a string to the growing buffer. Called with @p pointing after
356 * the last byte in the buffer, returns a pointer after the last byte
357 * of the new (possibly reallocated) buffer.
359 static inline void *mp_append_string(struct mempool *pool, void *p, const char *str)
361 return mp_append_block(pool, p, str, strlen(str));
365 * Close the growing buffer. The @end must point just behind the data, you want to keep
366 * allocated (so it can be in the interval `[@mp_ptr(@pool), @mp_ptr(@pool) + @mp_avail(@pool)]`).
367 * Returns a pointer to the beginning of the just closed block.
369 static inline void *mp_end(struct mempool *pool, void *end)
371 void *p = mp_ptr(pool);
372 pool->state.free[pool->idx] = (byte *)pool->state.last[pool->idx] - (byte *)end;
377 * Close the growing buffer as a string. That is, append a zero byte and call mp_end().
379 static inline char *mp_end_string(struct mempool *pool, void *end)
381 end = mp_append_char(pool, end, 0);
382 return mp_end(pool, end);
386 * Return size in bytes of the last allocated memory block (with @mp_alloc() or @mp_end()).
388 static inline size_t mp_size(struct mempool *pool, void *ptr)
390 uint idx = mp_idx(pool, ptr);
391 return ((byte *)pool->state.last[idx] - (byte *)ptr) - pool->state.free[idx];
395 * Open the last memory block (allocated with @mp_alloc() or @mp_end())
396 * for growing and return its size in bytes. The contents and the start pointer
397 * remain unchanged. Do not forget to call @mp_end() to close it.
399 size_t mp_open(struct mempool *pool, void *ptr);
402 * Inlined version of @mp_open().
404 static inline size_t mp_open_fast(struct mempool *pool, void *ptr)
406 pool->idx = mp_idx(pool, ptr);
407 size_t size = ((byte *)pool->state.last[pool->idx] - (byte *)ptr) - pool->state.free[pool->idx];
408 pool->state.free[pool->idx] += size;
413 * Reallocate the last memory block (allocated with @mp_alloc() or @mp_end())
414 * to the new @size. Behavior is similar to @mp_grow(), but the resulting
417 void *mp_realloc(struct mempool *pool, void *ptr, size_t size);
420 * The same as @mp_realloc(), but fills the additional bytes (if any) with zeroes.
422 void *mp_realloc_zero(struct mempool *pool, void *ptr, size_t size);
425 * Inlined version of @mp_realloc().
427 static inline void *mp_realloc_fast(struct mempool *pool, void *ptr, size_t size)
429 mp_open_fast(pool, ptr);
430 ptr = mp_grow(pool, size);
431 mp_end(pool, (byte *)ptr + size);
437 * Storing and restoring state
438 * ---------------------------
440 * Mempools can remember history of what was allocated and return back
445 * Save the current state of a memory pool.
446 * Do not call this function with an opened growing buffer.
448 static inline void mp_save(struct mempool *pool, struct mempool_state *state)
450 *state = pool->state;
451 pool->state.next = state;
455 * Save the current state to a newly allocated mempool_state structure.
456 * Do not call this function with an opened growing buffer.
458 struct mempool_state *mp_push(struct mempool *pool);
461 * Restore the state saved by @mp_save() or @mp_push() and free all
462 * data allocated after that point (including the state structure itself).
463 * You can't reallocate the last memory block from the saved state.
465 void mp_restore(struct mempool *pool, struct mempool_state *state);
468 * Inlined version of @mp_restore().
470 static inline void mp_restore_fast(struct mempool *pool, struct mempool_state *state)
472 if (pool->state.last[0] != state->last[0] || pool->state.last[1] != state->last[1])
473 mp_restore(pool, state);
476 pool->state = *state;
477 pool->last_big = &pool->last_big;
482 * Restore the state saved by the last call to @mp_push().
483 * @mp_pop() and @mp_push() works as a stack so you can push more states safely.
485 void mp_pop(struct mempool *pool);
494 char *mp_strdup(struct mempool *, const char *) LIKE_MALLOC; /** Makes a copy of a string on a mempool. Returns NULL for NULL string. **/
495 void *mp_memdup(struct mempool *, const void *, size_t) LIKE_MALLOC; /** Makes a copy of a memory block on a mempool. **/
497 * Concatenates all passed strings. The last parameter must be NULL.
498 * This will concatenate two strings:
500 * char *message = mp_multicat(pool, "hello ", "world", NULL);
502 char *mp_multicat(struct mempool *, ...) LIKE_MALLOC SENTINEL_CHECK;
504 * Concatenates two strings and stores result on @mp.
506 static inline char *LIKE_MALLOC mp_strcat(struct mempool *mp, const char *x, const char *y)
508 return mp_multicat(mp, x, y, NULL);
511 * Join strings and place @sep between each two neighboring.
512 * @p is the mempool to provide memory, @a is array of strings and @n
513 * tells how many there is of them.
515 char *mp_strjoin(struct mempool *p, char **a, uint n, uint sep) LIKE_MALLOC;
517 * Convert memory block to a string. Makes a copy of the given memory block
518 * in the mempool @p, adding an extra terminating zero byte at the end.
520 char *mp_str_from_mem(struct mempool *p, const void *mem, size_t len) LIKE_MALLOC;
530 * printf() into a in-memory string, allocated on the memory pool.
532 char *mp_printf(struct mempool *mp, const char *fmt, ...) FORMAT_CHECK(printf,2,3) LIKE_MALLOC;
534 * Like @mp_printf(), but uses `va_list` for parameters.
536 char *mp_vprintf(struct mempool *mp, const char *fmt, va_list args) LIKE_MALLOC;
538 * Like @mp_printf(), but it appends the data at the end of string
539 * pointed to by @ptr. The string is @mp_open()ed, so you have to
540 * provide something that can be.
542 * Returns pointer to the beginning of the string (the pointer may have
543 * changed due to reallocation).
545 * Alternatively, this function may be called mp_printf_append() for compatibility with
546 * previous releases of LibUCW.
548 char *mp_append_printf(struct mempool *mp, char *ptr, const char *fmt, ...) FORMAT_CHECK(printf,3,4);
549 #define mp_printf_append mp_append_printf
551 * Like @mp_append_printf(), but uses `va_list` for parameters.
553 * Alternatively, this function may be called mp_vprintf_append() for compatibility with
554 * previous releases of LibUCW.
556 char *mp_append_vprintf(struct mempool *mp, char *ptr, const char *fmt, va_list args);
557 #define mp_vprintf_append mp_append_vprintf