2 * UCW Library -- Memory Pools
4 * (c) 1997--2015 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_utf8_32 ucw_mp_append_utf8_32
23 #define mp_delete ucw_mp_delete
24 #define mp_flush ucw_mp_flush
25 #define mp_grow_internal ucw_mp_grow_internal
26 #define mp_init ucw_mp_init
27 #define mp_memdup ucw_mp_memdup
28 #define mp_multicat ucw_mp_multicat
29 #define mp_new ucw_mp_new
30 #define mp_open ucw_mp_open
31 #define mp_pop ucw_mp_pop
32 #define mp_printf ucw_mp_printf
33 #define mp_printf_append ucw_mp_printf_append
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
49 #define mp_vprintf_append ucw_mp_vprintf_append
59 * Memory pool state (see @mp_push(), ...).
60 * You should use this one as an opaque handle only, the insides are internal.
62 struct mempool_state {
65 struct mempool_state *next;
70 * You should use this one as an opaque handle only, the insides are internal.
73 struct ucw_allocator allocator; // This must be the first element
74 struct mempool_state state;
75 void *unused, *last_big;
76 size_t chunk_size, threshold;
81 struct mempool_stats { /** Mempool statistics. See @mp_stats(). **/
82 u64 total_size; /* Real allocated size in bytes */
83 u64 used_size; /* Estimated size allocated from mempool to application */
84 uint chain_count[3]; /* Number of allocated chunks in small/big/unused chains */
85 u64 chain_size[3]; /* Size of allocated chunks in small/big/unused chains */
95 * Initialize a given mempool structure.
96 * @chunk_size must be in the interval `[1, SIZE_MAX / 2]`.
97 * It will allocate memory by this large chunks and take
98 * memory to satisfy requests from them.
100 * Memory pools can be treated as <<trans:respools,resources>>, see <<trans:res_mempool()>>.
102 void mp_init(struct mempool *pool, size_t chunk_size);
105 * Allocate and initialize a new memory pool.
106 * See @mp_init() for @chunk_size limitations.
108 * The new mempool structure is allocated on the new mempool.
110 * Memory pools can be treated as <<trans:respools,resources>>, see <<trans:res_mempool()>>.
112 struct mempool *mp_new(size_t chunk_size);
115 * Cleanup mempool initialized by mp_init or mp_new.
116 * Frees all the memory allocated by this mempool and,
117 * if created by @mp_new(), the @pool itself.
119 void mp_delete(struct mempool *pool);
122 * Frees all data on a memory pool, but leaves it working.
123 * It can keep some of the chunks allocated to serve
124 * further allocation requests. Leaves the @pool alive,
125 * even if it was created with @mp_new().
127 void mp_flush(struct mempool *pool);
130 * Compute some statistics for debug purposes.
131 * See the definition of the <<struct_mempool_stats,mempool_stats structure>>.
132 * This function scans the chunk list, so it can be slow. If you are interested
133 * in total memory consumption only, mp_total_size() is faster.
135 void mp_stats(struct mempool *pool, struct mempool_stats *stats);
138 * Return how many bytes were allocated by the pool, including unused parts
139 * of chunks. This function runs in constant time.
141 u64 mp_total_size(struct mempool *pool);
144 * Release unused chunks of memory reserved for further allocation
145 * requests, but stop if mp_total_size() would drop below @min_total_size.
147 void mp_shrink(struct mempool *pool, u64 min_total_size);
151 * Allocation routines
152 * -------------------
155 /* For internal use only, do not call directly */
156 void *mp_alloc_internal(struct mempool *pool, size_t size) LIKE_MALLOC;
159 * The function allocates new @size bytes on a given memory pool.
160 * If the @size is zero, the resulting pointer is undefined,
161 * but it may be safely reallocated or used as the parameter
162 * to other functions below.
164 * The resulting pointer is always aligned to a multiple of
165 * `CPU_STRUCT_ALIGN` bytes and this condition remains true also
166 * after future reallocations.
168 void *mp_alloc(struct mempool *pool, size_t size);
171 * The same as @mp_alloc(), but the result may be unaligned.
173 void *mp_alloc_noalign(struct mempool *pool, size_t size);
176 * The same as @mp_alloc(), but fills the newly allocated memory with zeroes.
178 void *mp_alloc_zero(struct mempool *pool, size_t size);
181 * Inlined version of @mp_alloc().
183 static inline void *mp_alloc_fast(struct mempool *pool, size_t size)
185 size_t avail = pool->state.free[0] & ~(size_t)(CPU_STRUCT_ALIGN - 1);
188 pool->state.free[0] = avail - size;
189 return (byte *)pool->state.last[0] - avail;
192 return mp_alloc_internal(pool, size);
196 * Inlined version of @mp_alloc_noalign().
198 static inline void *mp_alloc_fast_noalign(struct mempool *pool, size_t size)
200 if (size <= pool->state.free[0])
202 void *ptr = (byte *)pool->state.last[0] - pool->state.free[0];
203 pool->state.free[0] -= size;
207 return mp_alloc_internal(pool, size);
211 * Return a generic allocator representing the given mempool.
213 static inline struct ucw_allocator *mp_get_allocator(struct mempool *mp)
215 return &mp->allocator;
223 * You do not need to know, how a buffer will need to be large,
224 * you can grow it incrementally to needed size. You can grow only
225 * one buffer at a time on a given mempool.
227 * Similar functionality is provided by <<growbuf:,growing buffes>> module.
230 /* For internal use only, do not call directly */
231 void *mp_start_internal(struct mempool *pool, size_t size) LIKE_MALLOC;
232 void *mp_grow_internal(struct mempool *pool, size_t size);
233 void *mp_spread_internal(struct mempool *pool, void *p, size_t size);
235 static inline uint mp_idx(struct mempool *pool, void *ptr)
237 return ptr == pool->last_big;
241 * Open a new growing buffer (at least @size bytes long).
242 * If the @size is zero, the resulting pointer is undefined,
243 * but it may be safely reallocated or used as the parameter
244 * to other functions below.
246 * The resulting pointer is always aligned to a multiple of
247 * `CPU_STRUCT_ALIGN` bytes and this condition remains true also
248 * after future reallocations. There is an unaligned version as well.
250 * Keep in mind that you can't make any other pool allocations
251 * before you "close" the growing buffer with @mp_end().
253 void *mp_start(struct mempool *pool, size_t size);
254 void *mp_start_noalign(struct mempool *pool, size_t size);
257 * Inlined version of @mp_start().
259 static inline void *mp_start_fast(struct mempool *pool, size_t size)
261 size_t avail = pool->state.free[0] & ~(size_t)(CPU_STRUCT_ALIGN - 1);
265 pool->state.free[0] = avail;
266 return (byte *)pool->state.last[0] - avail;
269 return mp_start_internal(pool, size);
273 * Inlined version of @mp_start_noalign().
275 static inline void *mp_start_fast_noalign(struct mempool *pool, size_t size)
277 if (size <= pool->state.free[0])
280 return (byte *)pool->state.last[0] - pool->state.free[0];
283 return mp_start_internal(pool, size);
287 * Return start pointer of the growing buffer allocated by latest @mp_start() or a similar function.
289 static inline void *mp_ptr(struct mempool *pool)
291 return (byte *)pool->state.last[pool->idx] - pool->state.free[pool->idx];
295 * Return the number of bytes available for extending the growing buffer.
296 * (Before a reallocation will be needed).
298 static inline size_t mp_avail(struct mempool *pool)
300 return pool->state.free[pool->idx];
304 * Grow the buffer allocated by @mp_start() to be at least @size bytes long
305 * (@size may be less than @mp_avail(), even zero). Reallocated buffer may
306 * change its starting position. The content will be unchanged to the minimum
307 * of the old and new sizes; newly allocated memory will be uninitialized.
308 * Multiple calls to mp_grow() have amortized linear cost wrt. the maximum value of @size. */
309 static inline void *mp_grow(struct mempool *pool, size_t size)
311 return (size <= mp_avail(pool)) ? mp_ptr(pool) : mp_grow_internal(pool, size);
315 * Grow the buffer by at least one byte -- equivalent to <<mp_grow(),`mp_grow`>>`(@pool, @mp_avail(pool) + 1)`.
317 static inline void *mp_expand(struct mempool *pool)
319 return mp_grow_internal(pool, mp_avail(pool) + 1);
323 * Ensure that there is at least @size bytes free after @p,
324 * if not, reallocate and adjust @p.
326 static inline void *mp_spread(struct mempool *pool, void *p, size_t size)
328 return (((size_t)((byte *)pool->state.last[pool->idx] - (byte *)p) >= size) ? p : mp_spread_internal(pool, p, size));
332 * Append a character to the growing buffer. Called with @p pointing after
333 * the last byte in the buffer, returns a pointer after the last byte
334 * of the new (possibly reallocated) buffer.
336 static inline char *mp_append_char(struct mempool *pool, char *p, uint c)
338 p = mp_spread(pool, p, 1);
344 * Append a memory block to the growing buffer. Called with @p pointing after
345 * the last byte in the buffer, returns a pointer after the last byte
346 * of the new (possibly reallocated) buffer.
348 static inline void *mp_append_block(struct mempool *pool, void *p, const void *block, size_t size)
350 char *q = mp_spread(pool, p, size);
351 memcpy(q, block, size);
356 * Append a string to the growing buffer. Called with @p pointing after
357 * the last byte in the buffer, returns a pointer after the last byte
358 * of the new (possibly reallocated) buffer.
360 static inline void *mp_append_string(struct mempool *pool, void *p, const char *str)
362 return mp_append_block(pool, p, str, strlen(str));
366 * Append an UTF-8 character to the growing buffer. Called with @p pointing after
367 * the last byte in the buffer, returns a pointer after the last byte
368 * of the new (possibly reallocated) buffer.
370 void *mp_append_utf8_32(struct mempool *pool, void *p, uint c);
373 * Close the growing buffer. The @end must point just behind the data, you want to keep
374 * allocated (so it can be in the interval `[@mp_ptr(@pool), @mp_ptr(@pool) + @mp_avail(@pool)]`).
375 * Returns a pointer to the beginning of the just closed block.
377 static inline void *mp_end(struct mempool *pool, void *end)
379 void *p = mp_ptr(pool);
380 pool->state.free[pool->idx] = (byte *)pool->state.last[pool->idx] - (byte *)end;
385 * Close the growing buffer as a string. That is, append a zero byte and call mp_end().
387 static inline char *mp_end_string(struct mempool *pool, void *end)
389 end = mp_append_char(pool, end, 0);
390 return mp_end(pool, end);
394 * Return size in bytes of the last allocated memory block (with @mp_alloc() or @mp_end()).
396 static inline size_t mp_size(struct mempool *pool, void *ptr)
398 uint idx = mp_idx(pool, ptr);
399 return ((byte *)pool->state.last[idx] - (byte *)ptr) - pool->state.free[idx];
403 * Open the last memory block (allocated with @mp_alloc() or @mp_end())
404 * for growing and return its size in bytes. The contents and the start pointer
405 * remain unchanged. Do not forget to call @mp_end() to close it.
407 size_t mp_open(struct mempool *pool, void *ptr);
410 * Inlined version of @mp_open().
412 static inline size_t mp_open_fast(struct mempool *pool, void *ptr)
414 pool->idx = mp_idx(pool, ptr);
415 size_t size = ((byte *)pool->state.last[pool->idx] - (byte *)ptr) - pool->state.free[pool->idx];
416 pool->state.free[pool->idx] += size;
421 * Reallocate the last memory block (allocated with @mp_alloc() or @mp_end())
422 * to the new @size. Behavior is similar to @mp_grow(), but the resulting
425 void *mp_realloc(struct mempool *pool, void *ptr, size_t size);
428 * The same as @mp_realloc(), but fills the additional bytes (if any) with zeroes.
430 void *mp_realloc_zero(struct mempool *pool, void *ptr, size_t size);
433 * Inlined version of @mp_realloc().
435 static inline void *mp_realloc_fast(struct mempool *pool, void *ptr, size_t size)
437 mp_open_fast(pool, ptr);
438 ptr = mp_grow(pool, size);
439 mp_end(pool, (byte *)ptr + size);
445 * Storing and restoring state
446 * ---------------------------
448 * Mempools can remember history of what was allocated and return back
453 * Save the current state of a memory pool.
454 * Do not call this function with an opened growing buffer.
456 static inline void mp_save(struct mempool *pool, struct mempool_state *state)
458 *state = pool->state;
459 pool->state.next = state;
463 * Save the current state to a newly allocated mempool_state structure.
464 * Do not call this function with an opened growing buffer.
466 struct mempool_state *mp_push(struct mempool *pool);
469 * Restore the state saved by @mp_save() or @mp_push() and free all
470 * data allocated after that point (including the state structure itself).
471 * You can't reallocate the last memory block from the saved state.
473 void mp_restore(struct mempool *pool, struct mempool_state *state);
476 * Inlined version of @mp_restore().
478 static inline void mp_restore_fast(struct mempool *pool, struct mempool_state *state)
480 if (pool->state.last[0] != state->last[0] || pool->state.last[1] != state->last[1])
481 mp_restore(pool, state);
484 pool->state = *state;
485 pool->last_big = &pool->last_big;
490 * Restore the state saved by the last call to @mp_push().
491 * @mp_pop() and @mp_push() works as a stack so you can push more states safely.
493 void mp_pop(struct mempool *pool);
502 char *mp_strdup(struct mempool *, const char *) LIKE_MALLOC; /** Makes a copy of a string on a mempool. Returns NULL for NULL string. **/
503 void *mp_memdup(struct mempool *, const void *, size_t) LIKE_MALLOC; /** Makes a copy of a memory block on a mempool. **/
505 * Concatenates all passed strings. The last parameter must be NULL.
506 * This will concatenate two strings:
508 * char *message = mp_multicat(pool, "hello ", "world", NULL);
510 char *mp_multicat(struct mempool *, ...) LIKE_MALLOC SENTINEL_CHECK;
512 * Concatenates two strings and stores result on @mp.
514 static inline char *LIKE_MALLOC mp_strcat(struct mempool *mp, const char *x, const char *y)
516 return mp_multicat(mp, x, y, NULL);
519 * Join strings and place @sep between each two neighboring.
520 * @p is the mempool to provide memory, @a is array of strings and @n
521 * tells how many there is of them.
523 char *mp_strjoin(struct mempool *p, char **a, uint n, uint sep) LIKE_MALLOC;
525 * Convert memory block to a string. Makes a copy of the given memory block
526 * in the mempool @p, adding an extra terminating zero byte at the end.
528 char *mp_str_from_mem(struct mempool *p, const void *mem, size_t len) LIKE_MALLOC;
538 * printf() into a in-memory string, allocated on the memory pool.
540 char *mp_printf(struct mempool *mp, const char *fmt, ...) FORMAT_CHECK(printf,2,3) LIKE_MALLOC;
542 * Like @mp_printf(), but uses `va_list` for parameters.
544 char *mp_vprintf(struct mempool *mp, const char *fmt, va_list args) LIKE_MALLOC;
546 * Like @mp_printf(), but it appends the data at the end of string
547 * pointed to by @ptr. The string is @mp_open()ed, so you have to
548 * provide something that can be.
550 * Returns pointer to the beginning of the string (the pointer may have
551 * changed due to reallocation).
553 * In some versions of LibUCW, this function was called mp_append_printf(). However,
554 * this name turned out to be confusing -- unlike other appending functions, this one is
555 * not called on an opened growing buffer. The old name will be preserved for backward
556 * compatibility for the time being.
558 char *mp_printf_append(struct mempool *mp, char *ptr, const char *fmt, ...) FORMAT_CHECK(printf,3,4);
559 #define mp_append_printf mp_printf_append
561 * Like @mp_printf_append(), but uses `va_list` for parameters.
563 * In some versions of LibUCW, this function was called mp_append_vprintf(). However,
564 * this name turned out to be confusing -- unlike other appending functions, this one is
565 * not called on an opened growing buffer. The old name will be preserved for backward
566 * compatibility for the time being.
568 char *mp_vprintf_append(struct mempool *mp, char *ptr, const char *fmt, va_list args);
569 #define mp_append_vprintf mp_vprintf_append