]> mj.ucw.cz Git - libucw.git/blob - ucw/mempool.h
Macros: CLAMP now accepts arbitrary types, not only ints
[libucw.git] / ucw / mempool.h
1 /*
2  *      UCW Library -- Memory Pools
3  *
4  *      (c) 1997--2014 Martin Mares <mj@ucw.cz>
5  *      (c) 2007 Pavel Charvat <pchar@ucw.cz>
6  *
7  *      This software may be freely distributed and used according to the terms
8  *      of the GNU Lesser General Public License.
9  */
10
11 #ifndef _UCW_POOLS_H
12 #define _UCW_POOLS_H
13
14 #include <ucw/alloc.h>
15 #include <string.h>
16
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
49 #endif
50
51 /***
52  * [[defs]]
53  * Definitions
54  * -----------
55  ***/
56
57 /**
58  * Memory pool state (see @mp_push(), ...).
59  * You should use this one as an opaque handle only, the insides are internal.
60  **/
61 struct mempool_state {
62   size_t free[2];
63   void *last[2];
64   struct mempool_state *next;
65 };
66
67 /**
68  * Memory pool.
69  * You should use this one as an opaque handle only, the insides are internal.
70  **/
71 struct mempool {
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;
76   uint idx;
77   u64 total_size;
78 };
79
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 */
85 };
86
87 /***
88  * [[basic]]
89  * Basic manipulation
90  * ------------------
91  ***/
92
93 /**
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.
98  *
99  * Memory pools can be treated as <<trans:respools,resources>>, see <<trans:res_mempool()>>.
100  **/
101 void mp_init(struct mempool *pool, size_t chunk_size);
102
103 /**
104  * Allocate and initialize a new memory pool.
105  * See @mp_init() for @chunk_size limitations.
106  *
107  * The new mempool structure is allocated on the new mempool.
108  *
109  * Memory pools can be treated as <<trans:respools,resources>>, see <<trans:res_mempool()>>.
110  **/
111 struct mempool *mp_new(size_t chunk_size);
112
113 /**
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.
117  **/
118 void mp_delete(struct mempool *pool);
119
120 /**
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().
125  **/
126 void mp_flush(struct mempool *pool);
127
128 /**
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.
133  **/
134 void mp_stats(struct mempool *pool, struct mempool_stats *stats);
135
136 /**
137  * Return how many bytes were allocated by the pool, including unused parts
138  * of chunks. This function runs in constant time.
139  **/
140 u64 mp_total_size(struct mempool *pool);
141
142 /**
143  * Release unused chunks of memory reserved for further allocation
144  * requests, but stop if mp_total_size() would drop below @min_total_size.
145  **/
146 void mp_shrink(struct mempool *pool, u64 min_total_size);
147
148 /***
149  * [[alloc]]
150  * Allocation routines
151  * -------------------
152  ***/
153
154 /* For internal use only, do not call directly */
155 void *mp_alloc_internal(struct mempool *pool, size_t size) LIKE_MALLOC;
156
157 /**
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.
162  *
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.
166  **/
167 void *mp_alloc(struct mempool *pool, size_t size);
168
169 /**
170  * The same as @mp_alloc(), but the result may be unaligned.
171  **/
172 void *mp_alloc_noalign(struct mempool *pool, size_t size);
173
174 /**
175  * The same as @mp_alloc(), but fills the newly allocated memory with zeroes.
176  **/
177 void *mp_alloc_zero(struct mempool *pool, size_t size);
178
179 /**
180  * Inlined version of @mp_alloc().
181  **/
182 static inline void *mp_alloc_fast(struct mempool *pool, size_t size)
183 {
184   size_t avail = pool->state.free[0] & ~(size_t)(CPU_STRUCT_ALIGN - 1);
185   if (size <= avail)
186     {
187       pool->state.free[0] = avail - size;
188       return (byte *)pool->state.last[0] - avail;
189     }
190   else
191     return mp_alloc_internal(pool, size);
192 }
193
194 /**
195  * Inlined version of @mp_alloc_noalign().
196  **/
197 static inline void *mp_alloc_fast_noalign(struct mempool *pool, size_t size)
198 {
199   if (size <= pool->state.free[0])
200     {
201       void *ptr = (byte *)pool->state.last[0] - pool->state.free[0];
202       pool->state.free[0] -= size;
203       return ptr;
204     }
205   else
206     return mp_alloc_internal(pool, size);
207 }
208
209 /**
210  * Return a generic allocator representing the given mempool.
211  **/
212 static inline struct ucw_allocator *mp_get_allocator(struct mempool *mp)
213 {
214   return &mp->allocator;
215 }
216
217 /***
218  * [[gbuf]]
219  * Growing buffers
220  * ---------------
221  *
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.
225  *
226  * Similar functionality is provided by <<growbuf:,growing buffes>> module.
227  ***/
228
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);
233
234 static inline uint mp_idx(struct mempool *pool, void *ptr)
235 {
236   return ptr == pool->last_big;
237 }
238
239 /**
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.
244  *
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.
248  *
249  * Keep in mind that you can't make any other pool allocations
250  * before you "close" the growing buffer with @mp_end().
251  */
252 void *mp_start(struct mempool *pool, size_t size);
253 void *mp_start_noalign(struct mempool *pool, size_t size);
254
255 /**
256  * Inlined version of @mp_start().
257  **/
258 static inline void *mp_start_fast(struct mempool *pool, size_t size)
259 {
260   size_t avail = pool->state.free[0] & ~(size_t)(CPU_STRUCT_ALIGN - 1);
261   if (size <= avail)
262     {
263       pool->idx = 0;
264       pool->state.free[0] = avail;
265       return (byte *)pool->state.last[0] - avail;
266     }
267   else
268     return mp_start_internal(pool, size);
269 }
270
271 /**
272  * Inlined version of @mp_start_noalign().
273  **/
274 static inline void *mp_start_fast_noalign(struct mempool *pool, size_t size)
275 {
276   if (size <= pool->state.free[0])
277     {
278       pool->idx = 0;
279       return (byte *)pool->state.last[0] - pool->state.free[0];
280     }
281   else
282     return mp_start_internal(pool, size);
283 }
284
285 /**
286  * Return start pointer of the growing buffer allocated by latest @mp_start() or a similar function.
287  **/
288 static inline void *mp_ptr(struct mempool *pool)
289 {
290   return (byte *)pool->state.last[pool->idx] - pool->state.free[pool->idx];
291 }
292
293 /**
294  * Return the number of bytes available for extending the growing buffer.
295  * (Before a reallocation will be needed).
296  **/
297 static inline size_t mp_avail(struct mempool *pool)
298 {
299   return pool->state.free[pool->idx];
300 }
301
302 /**
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)
309 {
310   return (size <= mp_avail(pool)) ? mp_ptr(pool) : mp_grow_internal(pool, size);
311 }
312
313 /**
314  * Grow the buffer by at least one byte -- equivalent to <<mp_grow(),`mp_grow`>>`(@pool, @mp_avail(pool) + 1)`.
315  **/
316 static inline void *mp_expand(struct mempool *pool)
317 {
318   return mp_grow_internal(pool, mp_avail(pool) + 1);
319 }
320
321 /**
322  * Ensure that there is at least @size bytes free after @p,
323  * if not, reallocate and adjust @p.
324  **/
325 static inline void *mp_spread(struct mempool *pool, void *p, size_t size)
326 {
327   return (((size_t)((byte *)pool->state.last[pool->idx] - (byte *)p) >= size) ? p : mp_spread_internal(pool, p, size));
328 }
329
330 /**
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.
334  **/
335 static inline char *mp_append_char(struct mempool *pool, char *p, uint c)
336 {
337   p = mp_spread(pool, p, 1);
338   *p++ = c;
339   return p;
340 }
341
342 /**
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.
346  **/
347 static inline void *mp_append_block(struct mempool *pool, void *p, const void *block, size_t size)
348 {
349   char *q = mp_spread(pool, p, size);
350   memcpy(q, block, size);
351   return q + size;
352 }
353
354 /**
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.
358  **/
359 static inline void *mp_append_string(struct mempool *pool, void *p, const char *str)
360 {
361   return mp_append_block(pool, p, str, strlen(str));
362 }
363
364 /**
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.
368  **/
369 static inline void *mp_end(struct mempool *pool, void *end)
370 {
371   void *p = mp_ptr(pool);
372   pool->state.free[pool->idx] = (byte *)pool->state.last[pool->idx] - (byte *)end;
373   return p;
374 }
375
376 /**
377  * Close the growing buffer as a string. That is, append a zero byte and call mp_end().
378  **/
379 static inline char *mp_end_string(struct mempool *pool, void *end)
380 {
381   end = mp_append_char(pool, end, 0);
382   return mp_end(pool, end);
383 }
384
385 /**
386  * Return size in bytes of the last allocated memory block (with @mp_alloc() or @mp_end()).
387  **/
388 static inline size_t mp_size(struct mempool *pool, void *ptr)
389 {
390   uint idx = mp_idx(pool, ptr);
391   return ((byte *)pool->state.last[idx] - (byte *)ptr) - pool->state.free[idx];
392 }
393
394 /**
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.
398  **/
399 size_t mp_open(struct mempool *pool, void *ptr);
400
401 /**
402  * Inlined version of @mp_open().
403  **/
404 static inline size_t mp_open_fast(struct mempool *pool, void *ptr)
405 {
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;
409   return size;
410 }
411
412 /**
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
415  * block is closed.
416  **/
417 void *mp_realloc(struct mempool *pool, void *ptr, size_t size);
418
419 /**
420  * The same as @mp_realloc(), but fills the additional bytes (if any) with zeroes.
421  **/
422 void *mp_realloc_zero(struct mempool *pool, void *ptr, size_t size);
423
424 /**
425  * Inlined version of @mp_realloc().
426  **/
427 static inline void *mp_realloc_fast(struct mempool *pool, void *ptr, size_t size)
428 {
429   mp_open_fast(pool, ptr);
430   ptr = mp_grow(pool, size);
431   mp_end(pool, (byte *)ptr + size);
432   return ptr;
433 }
434
435 /***
436  * [[store]]
437  * Storing and restoring state
438  * ---------------------------
439  *
440  * Mempools can remember history of what was allocated and return back
441  * in time.
442  ***/
443
444 /**
445  * Save the current state of a memory pool.
446  * Do not call this function with an opened growing buffer.
447  **/
448 static inline void mp_save(struct mempool *pool, struct mempool_state *state)
449 {
450   *state = pool->state;
451   pool->state.next = state;
452 }
453
454 /**
455  * Save the current state to a newly allocated mempool_state structure.
456  * Do not call this function with an opened growing buffer.
457  **/
458 struct mempool_state *mp_push(struct mempool *pool);
459
460 /**
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.
464  **/
465 void mp_restore(struct mempool *pool, struct mempool_state *state);
466
467 /**
468  * Inlined version of @mp_restore().
469  **/
470 static inline void mp_restore_fast(struct mempool *pool, struct mempool_state *state)
471 {
472   if (pool->state.last[0] != state->last[0] || pool->state.last[1] != state->last[1])
473     mp_restore(pool, state);
474   else
475     {
476       pool->state = *state;
477       pool->last_big = &pool->last_big;
478     }
479 }
480
481 /**
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.
484  **/
485 void mp_pop(struct mempool *pool);
486
487
488 /***
489  * [[string]]
490  * String operations
491  * -----------------
492  ***/
493
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. **/
496 /**
497  * Concatenates all passed strings. The last parameter must be NULL.
498  * This will concatenate two strings:
499  *
500  *   char *message = mp_multicat(pool, "hello ", "world", NULL);
501  **/
502 char *mp_multicat(struct mempool *, ...) LIKE_MALLOC SENTINEL_CHECK;
503 /**
504  * Concatenates two strings and stores result on @mp.
505  */
506 static inline char *LIKE_MALLOC mp_strcat(struct mempool *mp, const char *x, const char *y)
507 {
508   return mp_multicat(mp, x, y, NULL);
509 }
510 /**
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.
514  **/
515 char *mp_strjoin(struct mempool *p, char **a, uint n, uint sep) LIKE_MALLOC;
516 /**
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.
519  **/
520 char *mp_str_from_mem(struct mempool *p, const void *mem, size_t len) LIKE_MALLOC;
521
522
523 /***
524  * [[format]]
525  * Formatted output
526  * ---------------
527  ***/
528
529 /**
530  * printf() into a in-memory string, allocated on the memory pool.
531  **/
532 char *mp_printf(struct mempool *mp, const char *fmt, ...) FORMAT_CHECK(printf,2,3) LIKE_MALLOC;
533 /**
534  * Like @mp_printf(), but uses `va_list` for parameters.
535  **/
536 char *mp_vprintf(struct mempool *mp, const char *fmt, va_list args) LIKE_MALLOC;
537 /**
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.
541  *
542  * Returns pointer to the beginning of the string (the pointer may have
543  * changed due to reallocation).
544  *
545  * Alternatively, this function may be called mp_printf_append() for compatibility with
546  * previous releases of LibUCW.
547  **/
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
550 /**
551  * Like @mp_append_printf(), but uses `va_list` for parameters.
552  *
553  * Alternatively, this function may be called mp_vprintf_append() for compatibility with
554  * previous releases of LibUCW.
555  **/
556 char *mp_append_vprintf(struct mempool *mp, char *ptr, const char *fmt, va_list args);
557 #define mp_vprintf_append mp_append_vprintf
558
559 #endif