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>
16 #ifdef CONFIG_UCW_CLEAN_ABI
17 #define mp_alloc ucw_mp_alloc
18 #define mp_alloc_internal ucw_mp_alloc_internal
19 #define mp_alloc_noalign ucw_mp_alloc_noalign
20 #define mp_alloc_zero ucw_mp_alloc_zero
21 #define mp_delete ucw_mp_delete
22 #define mp_flush ucw_mp_flush
23 #define mp_grow_internal ucw_mp_grow_internal
24 #define mp_init ucw_mp_init
25 #define mp_memdup ucw_mp_memdup
26 #define mp_multicat ucw_mp_multicat
27 #define mp_new ucw_mp_new
28 #define mp_open ucw_mp_open
29 #define mp_pop ucw_mp_pop
30 #define mp_printf ucw_mp_printf
31 #define mp_printf_append ucw_mp_printf_append
32 #define mp_push ucw_mp_push
33 #define mp_realloc ucw_mp_realloc
34 #define mp_realloc_zero ucw_mp_realloc_zero
35 #define mp_restore ucw_mp_restore
36 #define mp_spread_internal ucw_mp_spread_internal
37 #define mp_start ucw_mp_start
38 #define mp_start_internal ucw_mp_start_internal
39 #define mp_start_noalign ucw_mp_start_noalign
40 #define mp_stats ucw_mp_stats
41 #define mp_str_from_mem ucw_mp_str_from_mem
42 #define mp_strdup ucw_mp_strdup
43 #define mp_strjoin ucw_mp_strjoin
44 #define mp_total_size ucw_mp_total_size
45 #define mp_vprintf ucw_mp_vprintf
46 #define mp_vprintf_append ucw_mp_vprintf_append
56 * Memory pool state (see @mp_push(), ...).
57 * You should use this one as an opaque handle only, the insides are internal.
59 struct mempool_state {
62 struct mempool_state *next;
67 * You should use this one as an opaque handle only, the insides are internal.
70 struct ucw_allocator allocator;
71 struct mempool_state state;
72 void *unused, *last_big;
73 uns chunk_size, threshold, idx;
77 struct mempool_stats { /** Mempool statistics. See @mp_stats(). **/
78 u64 total_size; /* Real allocated size in bytes */
79 uns chain_count[3]; /* Number of allocated chunks in small/big/unused chains */
80 uns chain_size[3]; /* Size of allocated chunks in small/big/unused chains */
90 * Initialize a given mempool structure.
91 * @chunk_size must be in the interval `[1, UINT_MAX / 2]`.
92 * It will allocate memory by this large chunks and take
93 * memory to satisfy requests from them.
95 * Memory pools can be treated as <<trans:respools,resources>>, see <<trans:res_mempool()>>.
97 void mp_init(struct mempool *pool, uns chunk_size);
100 * Allocate and initialize a new memory pool.
101 * See @mp_init() for @chunk_size limitations.
103 * The new mempool structure is allocated on the new mempool.
105 * Memory pools can be treated as <<trans:respools,resources>>, see <<trans:res_mempool()>>.
107 struct mempool *mp_new(uns chunk_size);
110 * Cleanup mempool initialized by mp_init or mp_new.
111 * Frees all the memory allocated by this mempool and,
112 * if created by @mp_new(), the @pool itself.
114 void mp_delete(struct mempool *pool);
117 * Frees all data on a memory pool, but leaves it working.
118 * It can keep some of the chunks allocated to serve
119 * further allocation requests. Leaves the @pool alive,
120 * even if it was created with @mp_new().
122 void mp_flush(struct mempool *pool);
125 * Compute some statistics for debug purposes.
126 * See the definition of the <<struct_mempool_stats,mempool_stats structure>>.
127 * This function scans the chunk list, so it can be slow. If you are interested
128 * in total memory consumption only, mp_total_size() is faster.
130 void mp_stats(struct mempool *pool, struct mempool_stats *stats);
133 * Return how many bytes were allocated by the pool, including unused parts
134 * of chunks. This function runs in constant time.
136 u64 mp_total_size(struct mempool *pool);
141 * Allocation routines
142 * -------------------
145 /* For internal use only, do not call directly */
146 void *mp_alloc_internal(struct mempool *pool, uns size) LIKE_MALLOC;
149 * The function allocates new @size bytes on a given memory pool.
150 * If the @size is zero, the resulting pointer is undefined,
151 * but it may be safely reallocated or used as the parameter
152 * to other functions below.
154 * The resulting pointer is always aligned to a multiple of
155 * `CPU_STRUCT_ALIGN` bytes and this condition remains true also
156 * after future reallocations.
158 void *mp_alloc(struct mempool *pool, uns size);
161 * The same as @mp_alloc(), but the result may be unaligned.
163 void *mp_alloc_noalign(struct mempool *pool, uns size);
166 * The same as @mp_alloc(), but fills the newly allocated memory with zeroes.
168 void *mp_alloc_zero(struct mempool *pool, uns size);
171 * Inlined version of @mp_alloc().
173 static inline void *mp_alloc_fast(struct mempool *pool, uns size)
175 uns avail = pool->state.free[0] & ~(CPU_STRUCT_ALIGN - 1);
178 pool->state.free[0] = avail - size;
179 return (byte *)pool->state.last[0] - avail;
182 return mp_alloc_internal(pool, size);
186 * Inlined version of @mp_alloc_noalign().
188 static inline void *mp_alloc_fast_noalign(struct mempool *pool, uns size)
190 if (size <= pool->state.free[0])
192 void *ptr = (byte *)pool->state.last[0] - pool->state.free[0];
193 pool->state.free[0] -= size;
197 return mp_alloc_internal(pool, size);
201 * Return a generic allocator representing the given mempool.
203 static inline struct ucw_allocator *mp_get_allocator(struct mempool *mp)
205 return &mp->allocator;
213 * You do not need to know, how a buffer will need to be large,
214 * you can grow it incrementally to needed size. You can grow only
215 * one buffer at a time on a given mempool.
217 * Similar functionality is provided by <<growbuf:,growing buffes>> module.
220 /* For internal use only, do not call directly */
221 void *mp_start_internal(struct mempool *pool, uns size) LIKE_MALLOC;
222 void *mp_grow_internal(struct mempool *pool, uns size);
223 void *mp_spread_internal(struct mempool *pool, void *p, uns size);
225 static inline uns mp_idx(struct mempool *pool, void *ptr)
227 return ptr == pool->last_big;
231 * Open a new growing buffer (at least @size bytes long).
232 * If the @size is zero, the resulting pointer is undefined,
233 * but it may be safely reallocated or used as the parameter
234 * to other functions below.
236 * The resulting pointer is always aligned to a multiple of
237 * `CPU_STRUCT_ALIGN` bytes and this condition remains true also
238 * after future reallocations. There is an unaligned version as well.
240 * Keep in mind that you can't make any other pool allocations
241 * before you "close" the growing buffer with @mp_end().
243 void *mp_start(struct mempool *pool, uns size);
244 void *mp_start_noalign(struct mempool *pool, uns size);
247 * Inlined version of @mp_start().
249 static inline void *mp_start_fast(struct mempool *pool, uns size)
251 uns avail = pool->state.free[0] & ~(CPU_STRUCT_ALIGN - 1);
255 pool->state.free[0] = avail;
256 return (byte *)pool->state.last[0] - avail;
259 return mp_start_internal(pool, size);
263 * Inlined version of @mp_start_noalign().
265 static inline void *mp_start_fast_noalign(struct mempool *pool, uns size)
267 if (size <= pool->state.free[0])
270 return (byte *)pool->state.last[0] - pool->state.free[0];
273 return mp_start_internal(pool, size);
277 * Return start pointer of the growing buffer allocated by latest @mp_start() or a similar function.
279 static inline void *mp_ptr(struct mempool *pool)
281 return (byte *)pool->state.last[pool->idx] - pool->state.free[pool->idx];
285 * Return the number of bytes available for extending the growing buffer.
286 * (Before a reallocation will be needed).
288 static inline uns mp_avail(struct mempool *pool)
290 return pool->state.free[pool->idx];
294 * Grow the buffer allocated by @mp_start() to be at least @size bytes long
295 * (@size may be less than @mp_avail(), even zero). Reallocated buffer may
296 * change its starting position. The content will be unchanged to the minimum
297 * of the old and new sizes; newly allocated memory will be uninitialized.
298 * Multiple calls to mp_grow() have amortized linear cost wrt. the maximum value of @size. */
299 static inline void *mp_grow(struct mempool *pool, uns size)
301 return (size <= mp_avail(pool)) ? mp_ptr(pool) : mp_grow_internal(pool, size);
305 * Grow the buffer by at least one byte -- equivalent to <<mp_grow(),`mp_grow`>>`(@pool, @mp_avail(pool) + 1)`.
307 static inline void *mp_expand(struct mempool *pool)
309 return mp_grow_internal(pool, mp_avail(pool) + 1);
313 * Ensure that there is at least @size bytes free after @p,
314 * if not, reallocate and adjust @p.
316 static inline void *mp_spread(struct mempool *pool, void *p, uns size)
318 return (((uns)((byte *)pool->state.last[pool->idx] - (byte *)p) >= size) ? p : mp_spread_internal(pool, p, size));
322 * Close the growing buffer. The @end must point just behind the data, you want to keep
323 * allocated (so it can be in the interval `[@mp_ptr(@pool), @mp_ptr(@pool) + @mp_avail(@pool)]`).
324 * Returns a pointer to the beginning of the just closed block.
326 static inline void *mp_end(struct mempool *pool, void *end)
328 void *p = mp_ptr(pool);
329 pool->state.free[pool->idx] = (byte *)pool->state.last[pool->idx] - (byte *)end;
334 * Return size in bytes of the last allocated memory block (with @mp_alloc() or @mp_end()).
336 static inline uns mp_size(struct mempool *pool, void *ptr)
338 uns idx = mp_idx(pool, ptr);
339 return ((byte *)pool->state.last[idx] - (byte *)ptr) - pool->state.free[idx];
343 * Open the last memory block (allocated with @mp_alloc() or @mp_end())
344 * for growing and return its size in bytes. The contents and the start pointer
345 * remain unchanged. Do not forget to call @mp_end() to close it.
347 uns mp_open(struct mempool *pool, void *ptr);
350 * Inlined version of @mp_open().
352 static inline uns mp_open_fast(struct mempool *pool, void *ptr)
354 pool->idx = mp_idx(pool, ptr);
355 uns size = ((byte *)pool->state.last[pool->idx] - (byte *)ptr) - pool->state.free[pool->idx];
356 pool->state.free[pool->idx] += size;
361 * Reallocate the last memory block (allocated with @mp_alloc() or @mp_end())
362 * to the new @size. Behavior is similar to @mp_grow(), but the resulting
365 void *mp_realloc(struct mempool *pool, void *ptr, uns size);
368 * The same as @mp_realloc(), but fills the additional bytes (if any) with zeroes.
370 void *mp_realloc_zero(struct mempool *pool, void *ptr, uns size);
373 * Inlined version of @mp_realloc().
375 static inline void *mp_realloc_fast(struct mempool *pool, void *ptr, uns size)
377 mp_open_fast(pool, ptr);
378 ptr = mp_grow(pool, size);
379 mp_end(pool, (byte *)ptr + size);
385 * Storing and restoring state
386 * ---------------------------
388 * Mempools can remember history of what was allocated and return back
393 * Save the current state of a memory pool.
394 * Do not call this function with an opened growing buffer.
396 static inline void mp_save(struct mempool *pool, struct mempool_state *state)
398 *state = pool->state;
399 pool->state.next = state;
403 * Save the current state to a newly allocated mempool_state structure.
404 * Do not call this function with an opened growing buffer.
406 struct mempool_state *mp_push(struct mempool *pool);
409 * Restore the state saved by @mp_save() or @mp_push() and free all
410 * data allocated after that point (including the state structure itself).
411 * You can't reallocate the last memory block from the saved state.
413 void mp_restore(struct mempool *pool, struct mempool_state *state);
416 * Inlined version of @mp_restore().
418 static inline void mp_restore_fast(struct mempool *pool, struct mempool_state *state)
420 if (pool->state.last[0] != state->last[0] || pool->state.last[1] != state->last[1])
421 mp_restore(pool, state);
424 pool->state = *state;
425 pool->last_big = &pool->last_big;
430 * Restore the state saved by the last call to @mp_push().
431 * @mp_pop() and @mp_push() works as a stack so you can push more states safely.
433 void mp_pop(struct mempool *pool);
442 char *mp_strdup(struct mempool *, const char *) LIKE_MALLOC; /** Makes a copy of a string on a mempool. Returns NULL for NULL string. **/
443 void *mp_memdup(struct mempool *, const void *, uns) LIKE_MALLOC; /** Makes a copy of a memory block on a mempool. **/
445 * Concatenates all passed strings. The last parameter must be NULL.
446 * This will concatenate two strings:
448 * char *message = mp_multicat(pool, "hello ", "world", NULL);
450 char *mp_multicat(struct mempool *, ...) LIKE_MALLOC SENTINEL_CHECK;
452 * Concatenates two strings and stores result on @mp.
454 static inline char *LIKE_MALLOC mp_strcat(struct mempool *mp, const char *x, const char *y)
456 return mp_multicat(mp, x, y, NULL);
459 * Join strings and place @sep between each two neighboring.
460 * @p is the mempool to provide memory, @a is array of strings and @n
461 * tells how many there is of them.
463 char *mp_strjoin(struct mempool *p, char **a, uns n, uns sep) LIKE_MALLOC;
465 * Convert memory block to a string. Makes a copy of the given memory block
466 * in the mempool @p, adding an extra terminating zero byte at the end.
468 char *mp_str_from_mem(struct mempool *p, const void *mem, uns len) LIKE_MALLOC;
478 * printf() into a in-memory string, allocated on the memory pool.
480 char *mp_printf(struct mempool *mp, const char *fmt, ...) FORMAT_CHECK(printf,2,3) LIKE_MALLOC;
482 * Like @mp_printf(), but uses `va_list` for parameters.
484 char *mp_vprintf(struct mempool *mp, const char *fmt, va_list args) LIKE_MALLOC;
486 * Like @mp_printf(), but it appends the data at the end of string
487 * pointed to by @ptr. The string is @mp_open()ed, so you have to
488 * provide something that can be.
490 * Returns pointer to the beginning of the string (the pointer may have
491 * changed due to reallocation).
493 char *mp_printf_append(struct mempool *mp, char *ptr, const char *fmt, ...) FORMAT_CHECK(printf,3,4);
495 * Like @mp_printf_append(), but uses `va_list` for parameters.
497 char *mp_vprintf_append(struct mempool *mp, char *ptr, const char *fmt, va_list args);