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_spread_internal ucw_mp_spread_internal
39 #define mp_start ucw_mp_start
40 #define mp_start_internal ucw_mp_start_internal
41 #define mp_start_noalign ucw_mp_start_noalign
42 #define mp_stats ucw_mp_stats
43 #define mp_str_from_mem ucw_mp_str_from_mem
44 #define mp_strdup ucw_mp_strdup
45 #define mp_strjoin ucw_mp_strjoin
46 #define mp_total_size ucw_mp_total_size
47 #define mp_vprintf ucw_mp_vprintf
57 * Memory pool state (see @mp_push(), ...).
58 * You should use this one as an opaque handle only, the insides are internal.
60 struct mempool_state {
63 struct mempool_state *next;
68 * You should use this one as an opaque handle only, the insides are internal.
71 struct ucw_allocator allocator;
72 struct mempool_state state;
73 void *unused, *last_big;
74 size_t chunk_size, threshold;
79 struct mempool_stats { /** Mempool statistics. See @mp_stats(). **/
80 u64 total_size; /* Real allocated size in bytes */
81 u64 used_size; /* Estimated size allocated from mempool to application */
82 uns chain_count[3]; /* Number of allocated chunks in small/big/unused chains */
83 u64 chain_size[3]; /* Size of allocated chunks in small/big/unused chains */
93 * Initialize a given mempool structure.
94 * @chunk_size must be in the interval `[1, SIZE_MAX / 2]`.
95 * It will allocate memory by this large chunks and take
96 * memory to satisfy requests from them.
98 * Memory pools can be treated as <<trans:respools,resources>>, see <<trans:res_mempool()>>.
100 void mp_init(struct mempool *pool, size_t chunk_size);
103 * Allocate and initialize a new memory pool.
104 * See @mp_init() for @chunk_size limitations.
106 * The new mempool structure is allocated on the new mempool.
108 * Memory pools can be treated as <<trans:respools,resources>>, see <<trans:res_mempool()>>.
110 struct mempool *mp_new(size_t chunk_size);
113 * Cleanup mempool initialized by mp_init or mp_new.
114 * Frees all the memory allocated by this mempool and,
115 * if created by @mp_new(), the @pool itself.
117 void mp_delete(struct mempool *pool);
120 * Frees all data on a memory pool, but leaves it working.
121 * It can keep some of the chunks allocated to serve
122 * further allocation requests. Leaves the @pool alive,
123 * even if it was created with @mp_new().
125 void mp_flush(struct mempool *pool);
128 * Compute some statistics for debug purposes.
129 * See the definition of the <<struct_mempool_stats,mempool_stats structure>>.
130 * This function scans the chunk list, so it can be slow. If you are interested
131 * in total memory consumption only, mp_total_size() is faster.
133 void mp_stats(struct mempool *pool, struct mempool_stats *stats);
136 * Return how many bytes were allocated by the pool, including unused parts
137 * of chunks. This function runs in constant time.
139 u64 mp_total_size(struct mempool *pool);
142 * Release unused chunks of memory reserved for further allocation
143 * requests, but stop if mp_total_size() would drop below @min_total_size.
145 void mp_shrink(struct mempool *pool, u64 min_total_size);
149 * Allocation routines
150 * -------------------
153 /* For internal use only, do not call directly */
154 void *mp_alloc_internal(struct mempool *pool, size_t size) LIKE_MALLOC;
157 * The function allocates new @size bytes on a given memory pool.
158 * If the @size is zero, the resulting pointer is undefined,
159 * but it may be safely reallocated or used as the parameter
160 * to other functions below.
162 * The resulting pointer is always aligned to a multiple of
163 * `CPU_STRUCT_ALIGN` bytes and this condition remains true also
164 * after future reallocations.
166 void *mp_alloc(struct mempool *pool, size_t size);
169 * The same as @mp_alloc(), but the result may be unaligned.
171 void *mp_alloc_noalign(struct mempool *pool, size_t size);
174 * The same as @mp_alloc(), but fills the newly allocated memory with zeroes.
176 void *mp_alloc_zero(struct mempool *pool, size_t size);
179 * Inlined version of @mp_alloc().
181 static inline void *mp_alloc_fast(struct mempool *pool, size_t size)
183 size_t avail = pool->state.free[0] & ~(size_t)(CPU_STRUCT_ALIGN - 1);
186 pool->state.free[0] = avail - size;
187 return (byte *)pool->state.last[0] - avail;
190 return mp_alloc_internal(pool, size);
194 * Inlined version of @mp_alloc_noalign().
196 static inline void *mp_alloc_fast_noalign(struct mempool *pool, size_t size)
198 if (size <= pool->state.free[0])
200 void *ptr = (byte *)pool->state.last[0] - pool->state.free[0];
201 pool->state.free[0] -= size;
205 return mp_alloc_internal(pool, size);
209 * Return a generic allocator representing the given mempool.
211 static inline struct ucw_allocator *mp_get_allocator(struct mempool *mp)
213 return &mp->allocator;
221 * You do not need to know, how a buffer will need to be large,
222 * you can grow it incrementally to needed size. You can grow only
223 * one buffer at a time on a given mempool.
225 * Similar functionality is provided by <<growbuf:,growing buffes>> module.
228 /* For internal use only, do not call directly */
229 void *mp_start_internal(struct mempool *pool, size_t size) LIKE_MALLOC;
230 void *mp_grow_internal(struct mempool *pool, size_t size);
231 void *mp_spread_internal(struct mempool *pool, void *p, size_t size);
233 static inline uns mp_idx(struct mempool *pool, void *ptr)
235 return ptr == pool->last_big;
239 * Open a new growing buffer (at least @size bytes long).
240 * If the @size is zero, the resulting pointer is undefined,
241 * but it may be safely reallocated or used as the parameter
242 * to other functions below.
244 * The resulting pointer is always aligned to a multiple of
245 * `CPU_STRUCT_ALIGN` bytes and this condition remains true also
246 * after future reallocations. There is an unaligned version as well.
248 * Keep in mind that you can't make any other pool allocations
249 * before you "close" the growing buffer with @mp_end().
251 void *mp_start(struct mempool *pool, size_t size);
252 void *mp_start_noalign(struct mempool *pool, size_t size);
255 * Inlined version of @mp_start().
257 static inline void *mp_start_fast(struct mempool *pool, size_t size)
259 size_t avail = pool->state.free[0] & ~(size_t)(CPU_STRUCT_ALIGN - 1);
263 pool->state.free[0] = avail;
264 return (byte *)pool->state.last[0] - avail;
267 return mp_start_internal(pool, size);
271 * Inlined version of @mp_start_noalign().
273 static inline void *mp_start_fast_noalign(struct mempool *pool, size_t size)
275 if (size <= pool->state.free[0])
278 return (byte *)pool->state.last[0] - pool->state.free[0];
281 return mp_start_internal(pool, size);
285 * Return start pointer of the growing buffer allocated by latest @mp_start() or a similar function.
287 static inline void *mp_ptr(struct mempool *pool)
289 return (byte *)pool->state.last[pool->idx] - pool->state.free[pool->idx];
293 * Return the number of bytes available for extending the growing buffer.
294 * (Before a reallocation will be needed).
296 static inline size_t mp_avail(struct mempool *pool)
298 return pool->state.free[pool->idx];
302 * Grow the buffer allocated by @mp_start() to be at least @size bytes long
303 * (@size may be less than @mp_avail(), even zero). Reallocated buffer may
304 * change its starting position. The content will be unchanged to the minimum
305 * of the old and new sizes; newly allocated memory will be uninitialized.
306 * Multiple calls to mp_grow() have amortized linear cost wrt. the maximum value of @size. */
307 static inline void *mp_grow(struct mempool *pool, size_t size)
309 return (size <= mp_avail(pool)) ? mp_ptr(pool) : mp_grow_internal(pool, size);
313 * Grow the buffer by at least one byte -- equivalent to <<mp_grow(),`mp_grow`>>`(@pool, @mp_avail(pool) + 1)`.
315 static inline void *mp_expand(struct mempool *pool)
317 return mp_grow_internal(pool, mp_avail(pool) + 1);
321 * Ensure that there is at least @size bytes free after @p,
322 * if not, reallocate and adjust @p.
324 static inline void *mp_spread(struct mempool *pool, void *p, size_t size)
326 return (((size_t)((byte *)pool->state.last[pool->idx] - (byte *)p) >= size) ? p : mp_spread_internal(pool, p, size));
330 * Append a character to the growing buffer. Called with @p pointing after
331 * the last byte in the buffer, returns a pointer after the last byte
332 * of the new (possibly reallocated) buffer.
334 static inline char *mp_append_char(struct mempool *pool, char *p, uns c)
336 p = mp_spread(pool, p, 1);
342 * Append a memory block to the growing buffer. Called with @p pointing after
343 * the last byte in the buffer, returns a pointer after the last byte
344 * of the new (possibly reallocated) buffer.
346 static inline void *mp_append_block(struct mempool *pool, void *p, const void *block, size_t size)
348 char *q = mp_spread(pool, p, size);
349 memcpy(q, block, size);
354 * Append a string to the growing buffer. Called with @p pointing after
355 * the last byte in the buffer, returns a pointer after the last byte
356 * of the new (possibly reallocated) buffer.
358 static inline void *mp_append_string(struct mempool *pool, void *p, const char *str)
360 return mp_append_block(pool, p, str, strlen(str));
364 * Close the growing buffer. The @end must point just behind the data, you want to keep
365 * allocated (so it can be in the interval `[@mp_ptr(@pool), @mp_ptr(@pool) + @mp_avail(@pool)]`).
366 * Returns a pointer to the beginning of the just closed block.
368 static inline void *mp_end(struct mempool *pool, void *end)
370 void *p = mp_ptr(pool);
371 pool->state.free[pool->idx] = (byte *)pool->state.last[pool->idx] - (byte *)end;
376 * Close the growing buffer as a string. That is, append a zero byte and call mp_end().
378 static inline char *mp_end_string(struct mempool *pool, void *end)
380 end = mp_append_char(pool, end, 0);
381 return mp_end(pool, end);
385 * Return size in bytes of the last allocated memory block (with @mp_alloc() or @mp_end()).
387 static inline size_t mp_size(struct mempool *pool, void *ptr)
389 uns idx = mp_idx(pool, ptr);
390 return ((byte *)pool->state.last[idx] - (byte *)ptr) - pool->state.free[idx];
394 * Open the last memory block (allocated with @mp_alloc() or @mp_end())
395 * for growing and return its size in bytes. The contents and the start pointer
396 * remain unchanged. Do not forget to call @mp_end() to close it.
398 size_t mp_open(struct mempool *pool, void *ptr);
401 * Inlined version of @mp_open().
403 static inline size_t mp_open_fast(struct mempool *pool, void *ptr)
405 pool->idx = mp_idx(pool, ptr);
406 size_t size = ((byte *)pool->state.last[pool->idx] - (byte *)ptr) - pool->state.free[pool->idx];
407 pool->state.free[pool->idx] += size;
412 * Reallocate the last memory block (allocated with @mp_alloc() or @mp_end())
413 * to the new @size. Behavior is similar to @mp_grow(), but the resulting
416 void *mp_realloc(struct mempool *pool, void *ptr, size_t size);
419 * The same as @mp_realloc(), but fills the additional bytes (if any) with zeroes.
421 void *mp_realloc_zero(struct mempool *pool, void *ptr, size_t size);
424 * Inlined version of @mp_realloc().
426 static inline void *mp_realloc_fast(struct mempool *pool, void *ptr, size_t size)
428 mp_open_fast(pool, ptr);
429 ptr = mp_grow(pool, size);
430 mp_end(pool, (byte *)ptr + size);
436 * Storing and restoring state
437 * ---------------------------
439 * Mempools can remember history of what was allocated and return back
444 * Save the current state of a memory pool.
445 * Do not call this function with an opened growing buffer.
447 static inline void mp_save(struct mempool *pool, struct mempool_state *state)
449 *state = pool->state;
450 pool->state.next = state;
454 * Save the current state to a newly allocated mempool_state structure.
455 * Do not call this function with an opened growing buffer.
457 struct mempool_state *mp_push(struct mempool *pool);
460 * Restore the state saved by @mp_save() or @mp_push() and free all
461 * data allocated after that point (including the state structure itself).
462 * You can't reallocate the last memory block from the saved state.
464 void mp_restore(struct mempool *pool, struct mempool_state *state);
467 * Inlined version of @mp_restore().
469 static inline void mp_restore_fast(struct mempool *pool, struct mempool_state *state)
471 if (pool->state.last[0] != state->last[0] || pool->state.last[1] != state->last[1])
472 mp_restore(pool, state);
475 pool->state = *state;
476 pool->last_big = &pool->last_big;
481 * Restore the state saved by the last call to @mp_push().
482 * @mp_pop() and @mp_push() works as a stack so you can push more states safely.
484 void mp_pop(struct mempool *pool);
493 char *mp_strdup(struct mempool *, const char *) LIKE_MALLOC; /** Makes a copy of a string on a mempool. Returns NULL for NULL string. **/
494 void *mp_memdup(struct mempool *, const void *, size_t) LIKE_MALLOC; /** Makes a copy of a memory block on a mempool. **/
496 * Concatenates all passed strings. The last parameter must be NULL.
497 * This will concatenate two strings:
499 * char *message = mp_multicat(pool, "hello ", "world", NULL);
501 char *mp_multicat(struct mempool *, ...) LIKE_MALLOC SENTINEL_CHECK;
503 * Concatenates two strings and stores result on @mp.
505 static inline char *LIKE_MALLOC mp_strcat(struct mempool *mp, const char *x, const char *y)
507 return mp_multicat(mp, x, y, NULL);
510 * Join strings and place @sep between each two neighboring.
511 * @p is the mempool to provide memory, @a is array of strings and @n
512 * tells how many there is of them.
514 char *mp_strjoin(struct mempool *p, char **a, uns n, uns sep) LIKE_MALLOC;
516 * Convert memory block to a string. Makes a copy of the given memory block
517 * in the mempool @p, adding an extra terminating zero byte at the end.
519 char *mp_str_from_mem(struct mempool *p, const void *mem, size_t len) LIKE_MALLOC;
529 * printf() into a in-memory string, allocated on the memory pool.
531 char *mp_printf(struct mempool *mp, const char *fmt, ...) FORMAT_CHECK(printf,2,3) LIKE_MALLOC;
533 * Like @mp_printf(), but uses `va_list` for parameters.
535 char *mp_vprintf(struct mempool *mp, const char *fmt, va_list args) LIKE_MALLOC;
537 * Like @mp_printf(), but it appends the data at the end of string
538 * pointed to by @ptr. The string is @mp_open()ed, so you have to
539 * provide something that can be.
541 * Returns pointer to the beginning of the string (the pointer may have
542 * changed due to reallocation).
544 * Alternatively, this function may be called mp_printf_append() for compatibility with
545 * previous releases of LibUCW.
547 char *mp_append_printf(struct mempool *mp, char *ptr, const char *fmt, ...) FORMAT_CHECK(printf,3,4);
548 #define mp_printf_append mp_append_printf
550 * Like @mp_append_printf(), but uses `va_list` for parameters.
552 * Alternatively, this function may be called mp_vprintf_append() for compatibility with
553 * previous releases of LibUCW.
555 char *mp_append_vprintf(struct mempool *mp, char *ptr, const char *fmt, va_list args);
556 #define mp_vprintf_append mp_append_vprintf