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