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