]> mj.ucw.cz Git - libucw.git/blob - ucw/mempool.h
Merge branch 'dev-uint'
[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_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
48 #endif
49
50 /***
51  * [[defs]]
52  * Definitions
53  * -----------
54  ***/
55
56 /**
57  * Memory pool state (see @mp_push(), ...).
58  * You should use this one as an opaque handle only, the insides are internal.
59  **/
60 struct mempool_state {
61   uint free[2];
62   void *last[2];
63   struct mempool_state *next;
64 };
65
66 /**
67  * Memory pool.
68  * You should use this one as an opaque handle only, the insides are internal.
69  **/
70 struct mempool {
71   struct ucw_allocator allocator;
72   struct mempool_state state;
73   void *unused, *last_big;
74   uint chunk_size, threshold, idx;
75   u64 total_size;
76 };
77
78 struct mempool_stats {                  /** Mempool statistics. See @mp_stats(). **/
79   u64 total_size;                       /* Real allocated size in bytes */
80   u64 used_size;                        /* Estimated size allocated from mempool to application */
81   uint chain_count[3];                  /* Number of allocated chunks in small/big/unused chains */
82   u64 chain_size[3];                    /* Size of allocated chunks in small/big/unused chains */
83 };
84
85 /***
86  * [[basic]]
87  * Basic manipulation
88  * ------------------
89  ***/
90
91 /**
92  * Initialize a given mempool structure.
93  * @chunk_size must be in the interval `[1, UINT_MAX / 2]`.
94  * It will allocate memory by this large chunks and take
95  * memory to satisfy requests from them.
96  *
97  * Memory pools can be treated as <<trans:respools,resources>>, see <<trans:res_mempool()>>.
98  **/
99 void mp_init(struct mempool *pool, uint chunk_size);
100
101 /**
102  * Allocate and initialize a new memory pool.
103  * See @mp_init() for @chunk_size limitations.
104  *
105  * The new mempool structure is allocated on the new mempool.
106  *
107  * Memory pools can be treated as <<trans:respools,resources>>, see <<trans:res_mempool()>>.
108  **/
109 struct mempool *mp_new(uint chunk_size);
110
111 /**
112  * Cleanup mempool initialized by mp_init or mp_new.
113  * Frees all the memory allocated by this mempool and,
114  * if created by @mp_new(), the @pool itself.
115  **/
116 void mp_delete(struct mempool *pool);
117
118 /**
119  * Frees all data on a memory pool, but leaves it working.
120  * It can keep some of the chunks allocated to serve
121  * further allocation requests. Leaves the @pool alive,
122  * even if it was created with @mp_new().
123  **/
124 void mp_flush(struct mempool *pool);
125
126 /**
127  * Compute some statistics for debug purposes.
128  * See the definition of the <<struct_mempool_stats,mempool_stats structure>>.
129  * This function scans the chunk list, so it can be slow. If you are interested
130  * in total memory consumption only, mp_total_size() is faster.
131  **/
132 void mp_stats(struct mempool *pool, struct mempool_stats *stats);
133
134 /**
135  * Return how many bytes were allocated by the pool, including unused parts
136  * of chunks. This function runs in constant time.
137  **/
138 u64 mp_total_size(struct mempool *pool);
139
140 /**
141  * Release unused chunks of memory reserved for further allocation
142  * requests, but stop if mp_total_size() would drop below @min_total_size.
143  **/
144 void mp_shrink(struct mempool *pool, u64 min_total_size);
145
146 /***
147  * [[alloc]]
148  * Allocation routines
149  * -------------------
150  ***/
151
152 /* For internal use only, do not call directly */
153 void *mp_alloc_internal(struct mempool *pool, uint size) LIKE_MALLOC;
154
155 /**
156  * The function allocates new @size bytes on a given memory pool.
157  * If the @size is zero, the resulting pointer is undefined,
158  * but it may be safely reallocated or used as the parameter
159  * to other functions below.
160  *
161  * The resulting pointer is always aligned to a multiple of
162  * `CPU_STRUCT_ALIGN` bytes and this condition remains true also
163  * after future reallocations.
164  **/
165 void *mp_alloc(struct mempool *pool, uint size);
166
167 /**
168  * The same as @mp_alloc(), but the result may be unaligned.
169  **/
170 void *mp_alloc_noalign(struct mempool *pool, uint size);
171
172 /**
173  * The same as @mp_alloc(), but fills the newly allocated memory with zeroes.
174  **/
175 void *mp_alloc_zero(struct mempool *pool, uint size);
176
177 /**
178  * Inlined version of @mp_alloc().
179  **/
180 static inline void *mp_alloc_fast(struct mempool *pool, uint size)
181 {
182   uint avail = pool->state.free[0] & ~(CPU_STRUCT_ALIGN - 1);
183   if (size <= avail)
184     {
185       pool->state.free[0] = avail - size;
186       return (byte *)pool->state.last[0] - avail;
187     }
188   else
189     return mp_alloc_internal(pool, size);
190 }
191
192 /**
193  * Inlined version of @mp_alloc_noalign().
194  **/
195 static inline void *mp_alloc_fast_noalign(struct mempool *pool, uint size)
196 {
197   if (size <= pool->state.free[0])
198     {
199       void *ptr = (byte *)pool->state.last[0] - pool->state.free[0];
200       pool->state.free[0] -= size;
201       return ptr;
202     }
203   else
204     return mp_alloc_internal(pool, size);
205 }
206
207 /**
208  * Return a generic allocator representing the given mempool.
209  **/
210 static inline struct ucw_allocator *mp_get_allocator(struct mempool *mp)
211 {
212   return &mp->allocator;
213 }
214
215 /***
216  * [[gbuf]]
217  * Growing buffers
218  * ---------------
219  *
220  * You do not need to know, how a buffer will need to be large,
221  * you can grow it incrementally to needed size. You can grow only
222  * one buffer at a time on a given mempool.
223  *
224  * Similar functionality is provided by <<growbuf:,growing buffes>> module.
225  ***/
226
227 /* For internal use only, do not call directly */
228 void *mp_start_internal(struct mempool *pool, uint size) LIKE_MALLOC;
229 void *mp_grow_internal(struct mempool *pool, uint size);
230 void *mp_spread_internal(struct mempool *pool, void *p, uint size);
231
232 static inline uint mp_idx(struct mempool *pool, void *ptr)
233 {
234   return ptr == pool->last_big;
235 }
236
237 /**
238  * Open a new growing buffer (at least @size bytes long).
239  * If the @size is zero, the resulting pointer is undefined,
240  * but it may be safely reallocated or used as the parameter
241  * to other functions below.
242  *
243  * The resulting pointer is always aligned to a multiple of
244  * `CPU_STRUCT_ALIGN` bytes and this condition remains true also
245  * after future reallocations. There is an unaligned version as well.
246  *
247  * Keep in mind that you can't make any other pool allocations
248  * before you "close" the growing buffer with @mp_end().
249  */
250 void *mp_start(struct mempool *pool, uint size);
251 void *mp_start_noalign(struct mempool *pool, uint size);
252
253 /**
254  * Inlined version of @mp_start().
255  **/
256 static inline void *mp_start_fast(struct mempool *pool, uint size)
257 {
258   uint avail = pool->state.free[0] & ~(CPU_STRUCT_ALIGN - 1);
259   if (size <= avail)
260     {
261       pool->idx = 0;
262       pool->state.free[0] = avail;
263       return (byte *)pool->state.last[0] - avail;
264     }
265   else
266     return mp_start_internal(pool, size);
267 }
268
269 /**
270  * Inlined version of @mp_start_noalign().
271  **/
272 static inline void *mp_start_fast_noalign(struct mempool *pool, uint size)
273 {
274   if (size <= pool->state.free[0])
275     {
276       pool->idx = 0;
277       return (byte *)pool->state.last[0] - pool->state.free[0];
278     }
279   else
280     return mp_start_internal(pool, size);
281 }
282
283 /**
284  * Return start pointer of the growing buffer allocated by latest @mp_start() or a similar function.
285  **/
286 static inline void *mp_ptr(struct mempool *pool)
287 {
288   return (byte *)pool->state.last[pool->idx] - pool->state.free[pool->idx];
289 }
290
291 /**
292  * Return the number of bytes available for extending the growing buffer.
293  * (Before a reallocation will be needed).
294  **/
295 static inline uint mp_avail(struct mempool *pool)
296 {
297   return pool->state.free[pool->idx];
298 }
299
300 /**
301  * Grow the buffer allocated by @mp_start() to be at least @size bytes long
302  * (@size may be less than @mp_avail(), even zero). Reallocated buffer may
303  * change its starting position. The content will be unchanged to the minimum
304  * of the old and new sizes; newly allocated memory will be uninitialized.
305  * Multiple calls to mp_grow() have amortized linear cost wrt. the maximum value of @size. */
306 static inline void *mp_grow(struct mempool *pool, uint size)
307 {
308   return (size <= mp_avail(pool)) ? mp_ptr(pool) : mp_grow_internal(pool, size);
309 }
310
311 /**
312  * Grow the buffer by at least one byte -- equivalent to <<mp_grow(),`mp_grow`>>`(@pool, @mp_avail(pool) + 1)`.
313  **/
314 static inline void *mp_expand(struct mempool *pool)
315 {
316   return mp_grow_internal(pool, mp_avail(pool) + 1);
317 }
318
319 /**
320  * Ensure that there is at least @size bytes free after @p,
321  * if not, reallocate and adjust @p.
322  **/
323 static inline void *mp_spread(struct mempool *pool, void *p, uint size)
324 {
325   return (((uint)((byte *)pool->state.last[pool->idx] - (byte *)p) >= size) ? p : mp_spread_internal(pool, p, size));
326 }
327
328 /**
329  * Append a character to the growing buffer. Called with @p pointing after
330  * the last byte in the buffer, returns a pointer after the last byte
331  * of the new (possibly reallocated) buffer.
332  **/
333 static inline char *mp_append_char(struct mempool *pool, char *p, uint c)
334 {
335   p = mp_spread(pool, p, 1);
336   *p++ = c;
337   return p;
338 }
339
340 /**
341  * Append a memory block to the growing buffer. Called with @p pointing after
342  * the last byte in the buffer, returns a pointer after the last byte
343  * of the new (possibly reallocated) buffer.
344  **/
345 static inline void *mp_append_block(struct mempool *pool, void *p, const void *block, uint size)
346 {
347   char *q = mp_spread(pool, p, size);
348   memcpy(q, block, size);
349   return q + size;
350 }
351
352 /**
353  * Append a string to the growing buffer. Called with @p pointing after
354  * the last byte in the buffer, returns a pointer after the last byte
355  * of the new (possibly reallocated) buffer.
356  **/
357 static inline void *mp_append_string(struct mempool *pool, void *p, const char *str)
358 {
359   return mp_append_block(pool, p, str, strlen(str));
360 }
361
362 /**
363  * Close the growing buffer. The @end must point just behind the data, you want to keep
364  * allocated (so it can be in the interval `[@mp_ptr(@pool), @mp_ptr(@pool) + @mp_avail(@pool)]`).
365  * Returns a pointer to the beginning of the just closed block.
366  **/
367 static inline void *mp_end(struct mempool *pool, void *end)
368 {
369   void *p = mp_ptr(pool);
370   pool->state.free[pool->idx] = (byte *)pool->state.last[pool->idx] - (byte *)end;
371   return p;
372 }
373
374 /**
375  * Close the growing buffer as a string. That is, append a zero byte and call mp_end().
376  **/
377 static inline char *mp_end_string(struct mempool *pool, void *end)
378 {
379   end = mp_append_char(pool, end, 0);
380   return mp_end(pool, end);
381 }
382
383 /**
384  * Return size in bytes of the last allocated memory block (with @mp_alloc() or @mp_end()).
385  **/
386 static inline uint mp_size(struct mempool *pool, void *ptr)
387 {
388   uint idx = mp_idx(pool, ptr);
389   return ((byte *)pool->state.last[idx] - (byte *)ptr) - pool->state.free[idx];
390 }
391
392 /**
393  * Open the last memory block (allocated with @mp_alloc() or @mp_end())
394  * for growing and return its size in bytes. The contents and the start pointer
395  * remain unchanged. Do not forget to call @mp_end() to close it.
396  **/
397 uint mp_open(struct mempool *pool, void *ptr);
398
399 /**
400  * Inlined version of @mp_open().
401  **/
402 static inline uint mp_open_fast(struct mempool *pool, void *ptr)
403 {
404   pool->idx = mp_idx(pool, ptr);
405   uint size = ((byte *)pool->state.last[pool->idx] - (byte *)ptr) - pool->state.free[pool->idx];
406   pool->state.free[pool->idx] += size;
407   return size;
408 }
409
410 /**
411  * Reallocate the last memory block (allocated with @mp_alloc() or @mp_end())
412  * to the new @size. Behavior is similar to @mp_grow(), but the resulting
413  * block is closed.
414  **/
415 void *mp_realloc(struct mempool *pool, void *ptr, uint size);
416
417 /**
418  * The same as @mp_realloc(), but fills the additional bytes (if any) with zeroes.
419  **/
420 void *mp_realloc_zero(struct mempool *pool, void *ptr, uint size);
421
422 /**
423  * Inlined version of @mp_realloc().
424  **/
425 static inline void *mp_realloc_fast(struct mempool *pool, void *ptr, uint size)
426 {
427   mp_open_fast(pool, ptr);
428   ptr = mp_grow(pool, size);
429   mp_end(pool, (byte *)ptr + size);
430   return ptr;
431 }
432
433 /***
434  * [[store]]
435  * Storing and restoring state
436  * ---------------------------
437  *
438  * Mempools can remember history of what was allocated and return back
439  * in time.
440  ***/
441
442 /**
443  * Save the current state of a memory pool.
444  * Do not call this function with an opened growing buffer.
445  **/
446 static inline void mp_save(struct mempool *pool, struct mempool_state *state)
447 {
448   *state = pool->state;
449   pool->state.next = state;
450 }
451
452 /**
453  * Save the current state to a newly allocated mempool_state structure.
454  * Do not call this function with an opened growing buffer.
455  **/
456 struct mempool_state *mp_push(struct mempool *pool);
457
458 /**
459  * Restore the state saved by @mp_save() or @mp_push() and free all
460  * data allocated after that point (including the state structure itself).
461  * You can't reallocate the last memory block from the saved state.
462  **/
463 void mp_restore(struct mempool *pool, struct mempool_state *state);
464
465 /**
466  * Inlined version of @mp_restore().
467  **/
468 static inline void mp_restore_fast(struct mempool *pool, struct mempool_state *state)
469 {
470   if (pool->state.last[0] != state->last[0] || pool->state.last[1] != state->last[1])
471     mp_restore(pool, state);
472   else
473     {
474       pool->state = *state;
475       pool->last_big = &pool->last_big;
476     }
477 }
478
479 /**
480  * Restore the state saved by the last call to @mp_push().
481  * @mp_pop() and @mp_push() works as a stack so you can push more states safely.
482  **/
483 void mp_pop(struct mempool *pool);
484
485
486 /***
487  * [[string]]
488  * String operations
489  * -----------------
490  ***/
491
492 char *mp_strdup(struct mempool *, const char *) LIKE_MALLOC;            /** Makes a copy of a string on a mempool. Returns NULL for NULL string. **/
493 void *mp_memdup(struct mempool *, const void *, uint) LIKE_MALLOC;      /** Makes a copy of a memory block on a mempool. **/
494 /**
495  * Concatenates all passed strings. The last parameter must be NULL.
496  * This will concatenate two strings:
497  *
498  *   char *message = mp_multicat(pool, "hello ", "world", NULL);
499  **/
500 char *mp_multicat(struct mempool *, ...) LIKE_MALLOC SENTINEL_CHECK;
501 /**
502  * Concatenates two strings and stores result on @mp.
503  */
504 static inline char *LIKE_MALLOC mp_strcat(struct mempool *mp, const char *x, const char *y)
505 {
506   return mp_multicat(mp, x, y, NULL);
507 }
508 /**
509  * Join strings and place @sep between each two neighboring.
510  * @p is the mempool to provide memory, @a is array of strings and @n
511  * tells how many there is of them.
512  **/
513 char *mp_strjoin(struct mempool *p, char **a, uint n, uint sep) LIKE_MALLOC;
514 /**
515  * Convert memory block to a string. Makes a copy of the given memory block
516  * in the mempool @p, adding an extra terminating zero byte at the end.
517  **/
518 char *mp_str_from_mem(struct mempool *p, const void *mem, uint len) LIKE_MALLOC;
519
520
521 /***
522  * [[format]]
523  * Formatted output
524  * ---------------
525  ***/
526
527 /**
528  * printf() into a in-memory string, allocated on the memory pool.
529  **/
530 char *mp_printf(struct mempool *mp, const char *fmt, ...) FORMAT_CHECK(printf,2,3) LIKE_MALLOC;
531 /**
532  * Like @mp_printf(), but uses `va_list` for parameters.
533  **/
534 char *mp_vprintf(struct mempool *mp, const char *fmt, va_list args) LIKE_MALLOC;
535 /**
536  * Like @mp_printf(), but it appends the data at the end of string
537  * pointed to by @ptr. The string is @mp_open()ed, so you have to
538  * provide something that can be.
539  *
540  * Returns pointer to the beginning of the string (the pointer may have
541  * changed due to reallocation).
542  *
543  * Alternatively, this function may be called mp_printf_append() for compatibility with
544  * previous releases of LibUCW.
545  **/
546 char *mp_append_printf(struct mempool *mp, char *ptr, const char *fmt, ...) FORMAT_CHECK(printf,3,4);
547 #define mp_printf_append mp_append_printf
548 /**
549  * Like @mp_append_printf(), but uses `va_list` for parameters.
550  *
551  * Alternatively, this function may be called mp_vprintf_append() for compatibility with
552  * previous releases of LibUCW.
553  **/
554 char *mp_append_vprintf(struct mempool *mp, char *ptr, const char *fmt, va_list args);
555 #define mp_vprintf_append mp_append_vprintf
556
557 #endif