]> mj.ucw.cz Git - libucw.git/blob - ucw/mempool.h
ad24a3983fc1580ee0f8f8a0b5ef3d6a6e660f7f
[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
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
47 #endif
48
49 /***
50  * [[defs]]
51  * Definitions
52  * -----------
53  ***/
54
55 /**
56  * Memory pool state (see @mp_push(), ...).
57  * You should use this one as an opaque handle only, the insides are internal.
58  **/
59 struct mempool_state {
60   uns free[2];
61   void *last[2];
62   struct mempool_state *next;
63 };
64
65 /**
66  * Memory pool.
67  * You should use this one as an opaque handle only, the insides are internal.
68  **/
69 struct mempool {
70   struct ucw_allocator allocator;
71   struct mempool_state state;
72   void *unused, *last_big;
73   uns chunk_size, threshold, idx;
74   u64 total_size;
75 };
76
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 */
81 };
82
83 /***
84  * [[basic]]
85  * Basic manipulation
86  * ------------------
87  ***/
88
89 /**
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.
94  *
95  * Memory pools can be treated as <<trans:respools,resources>>, see <<trans:res_mempool()>>.
96  **/
97 void mp_init(struct mempool *pool, uns chunk_size);
98
99 /**
100  * Allocate and initialize a new memory pool.
101  * See @mp_init() for @chunk_size limitations.
102  *
103  * The new mempool structure is allocated on the new mempool.
104  *
105  * Memory pools can be treated as <<trans:respools,resources>>, see <<trans:res_mempool()>>.
106  **/
107 struct mempool *mp_new(uns chunk_size);
108
109 /**
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.
113  **/
114 void mp_delete(struct mempool *pool);
115
116 /**
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().
121  **/
122 void mp_flush(struct mempool *pool);
123
124 /**
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.
129  **/
130 void mp_stats(struct mempool *pool, struct mempool_stats *stats);
131
132 /**
133  * Return how many bytes were allocated by the pool, including unused parts
134  * of chunks. This function runs in constant time.
135  **/
136 u64 mp_total_size(struct mempool *pool);
137
138
139 /***
140  * [[alloc]]
141  * Allocation routines
142  * -------------------
143  ***/
144
145 /* For internal use only, do not call directly */
146 void *mp_alloc_internal(struct mempool *pool, uns size) LIKE_MALLOC;
147
148 /**
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.
153  *
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.
157  **/
158 void *mp_alloc(struct mempool *pool, uns size);
159
160 /**
161  * The same as @mp_alloc(), but the result may be unaligned.
162  **/
163 void *mp_alloc_noalign(struct mempool *pool, uns size);
164
165 /**
166  * The same as @mp_alloc(), but fills the newly allocated memory with zeroes.
167  **/
168 void *mp_alloc_zero(struct mempool *pool, uns size);
169
170 /**
171  * Inlined version of @mp_alloc().
172  **/
173 static inline void *mp_alloc_fast(struct mempool *pool, uns size)
174 {
175   uns avail = pool->state.free[0] & ~(CPU_STRUCT_ALIGN - 1);
176   if (size <= avail)
177     {
178       pool->state.free[0] = avail - size;
179       return (byte *)pool->state.last[0] - avail;
180     }
181   else
182     return mp_alloc_internal(pool, size);
183 }
184
185 /**
186  * Inlined version of @mp_alloc_noalign().
187  **/
188 static inline void *mp_alloc_fast_noalign(struct mempool *pool, uns size)
189 {
190   if (size <= pool->state.free[0])
191     {
192       void *ptr = (byte *)pool->state.last[0] - pool->state.free[0];
193       pool->state.free[0] -= size;
194       return ptr;
195     }
196   else
197     return mp_alloc_internal(pool, size);
198 }
199
200 /**
201  * Return a generic allocator representing the given mempool.
202  **/
203 static inline struct ucw_allocator *mp_get_allocator(struct mempool *mp)
204 {
205   return &mp->allocator;
206 }
207
208 /***
209  * [[gbuf]]
210  * Growing buffers
211  * ---------------
212  *
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.
216  *
217  * Similar functionality is provided by <<growbuf:,growing buffes>> module.
218  ***/
219
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);
224
225 static inline uns mp_idx(struct mempool *pool, void *ptr)
226 {
227   return ptr == pool->last_big;
228 }
229
230 /**
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.
235  *
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.
239  *
240  * Keep in mind that you can't make any other pool allocations
241  * before you "close" the growing buffer with @mp_end().
242  */
243 void *mp_start(struct mempool *pool, uns size);
244 void *mp_start_noalign(struct mempool *pool, uns size);
245
246 /**
247  * Inlined version of @mp_start().
248  **/
249 static inline void *mp_start_fast(struct mempool *pool, uns size)
250 {
251   uns avail = pool->state.free[0] & ~(CPU_STRUCT_ALIGN - 1);
252   if (size <= avail)
253     {
254       pool->idx = 0;
255       pool->state.free[0] = avail;
256       return (byte *)pool->state.last[0] - avail;
257     }
258   else
259     return mp_start_internal(pool, size);
260 }
261
262 /**
263  * Inlined version of @mp_start_noalign().
264  **/
265 static inline void *mp_start_fast_noalign(struct mempool *pool, uns size)
266 {
267   if (size <= pool->state.free[0])
268     {
269       pool->idx = 0;
270       return (byte *)pool->state.last[0] - pool->state.free[0];
271     }
272   else
273     return mp_start_internal(pool, size);
274 }
275
276 /**
277  * Return start pointer of the growing buffer allocated by latest @mp_start() or a similar function.
278  **/
279 static inline void *mp_ptr(struct mempool *pool)
280 {
281   return (byte *)pool->state.last[pool->idx] - pool->state.free[pool->idx];
282 }
283
284 /**
285  * Return the number of bytes available for extending the growing buffer.
286  * (Before a reallocation will be needed).
287  **/
288 static inline uns mp_avail(struct mempool *pool)
289 {
290   return pool->state.free[pool->idx];
291 }
292
293 /**
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)
300 {
301   return (size <= mp_avail(pool)) ? mp_ptr(pool) : mp_grow_internal(pool, size);
302 }
303
304 /**
305  * Grow the buffer by at least one byte -- equivalent to <<mp_grow(),`mp_grow`>>`(@pool, @mp_avail(pool) + 1)`.
306  **/
307 static inline void *mp_expand(struct mempool *pool)
308 {
309   return mp_grow_internal(pool, mp_avail(pool) + 1);
310 }
311
312 /**
313  * Ensure that there is at least @size bytes free after @p,
314  * if not, reallocate and adjust @p.
315  **/
316 static inline void *mp_spread(struct mempool *pool, void *p, uns size)
317 {
318   return (((uns)((byte *)pool->state.last[pool->idx] - (byte *)p) >= size) ? p : mp_spread_internal(pool, p, size));
319 }
320
321 /**
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.
325  **/
326 static inline void *mp_end(struct mempool *pool, void *end)
327 {
328   void *p = mp_ptr(pool);
329   pool->state.free[pool->idx] = (byte *)pool->state.last[pool->idx] - (byte *)end;
330   return p;
331 }
332
333 /**
334  * Return size in bytes of the last allocated memory block (with @mp_alloc() or @mp_end()).
335  **/
336 static inline uns mp_size(struct mempool *pool, void *ptr)
337 {
338   uns idx = mp_idx(pool, ptr);
339   return ((byte *)pool->state.last[idx] - (byte *)ptr) - pool->state.free[idx];
340 }
341
342 /**
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.
346  **/
347 uns mp_open(struct mempool *pool, void *ptr);
348
349 /**
350  * Inlined version of @mp_open().
351  **/
352 static inline uns mp_open_fast(struct mempool *pool, void *ptr)
353 {
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;
357   return size;
358 }
359
360 /**
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
363  * block is closed.
364  **/
365 void *mp_realloc(struct mempool *pool, void *ptr, uns size);
366
367 /**
368  * The same as @mp_realloc(), but fills the additional bytes (if any) with zeroes.
369  **/
370 void *mp_realloc_zero(struct mempool *pool, void *ptr, uns size);
371
372 /**
373  * Inlined version of @mp_realloc().
374  **/
375 static inline void *mp_realloc_fast(struct mempool *pool, void *ptr, uns size)
376 {
377   mp_open_fast(pool, ptr);
378   ptr = mp_grow(pool, size);
379   mp_end(pool, (byte *)ptr + size);
380   return ptr;
381 }
382
383 /***
384  * [[store]]
385  * Storing and restoring state
386  * ---------------------------
387  *
388  * Mempools can remember history of what was allocated and return back
389  * in time.
390  ***/
391
392 /**
393  * Save the current state of a memory pool.
394  * Do not call this function with an opened growing buffer.
395  **/
396 static inline void mp_save(struct mempool *pool, struct mempool_state *state)
397 {
398   *state = pool->state;
399   pool->state.next = state;
400 }
401
402 /**
403  * Save the current state to a newly allocated mempool_state structure.
404  * Do not call this function with an opened growing buffer.
405  **/
406 struct mempool_state *mp_push(struct mempool *pool);
407
408 /**
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.
412  **/
413 void mp_restore(struct mempool *pool, struct mempool_state *state);
414
415 /**
416  * Inlined version of @mp_restore().
417  **/
418 static inline void mp_restore_fast(struct mempool *pool, struct mempool_state *state)
419 {
420   if (pool->state.last[0] != state->last[0] || pool->state.last[1] != state->last[1])
421     mp_restore(pool, state);
422   else
423     {
424       pool->state = *state;
425       pool->last_big = &pool->last_big;
426     }
427 }
428
429 /**
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.
432  **/
433 void mp_pop(struct mempool *pool);
434
435
436 /***
437  * [[string]]
438  * String operations
439  * -----------------
440  ***/
441
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. **/
444 /**
445  * Concatenates all passed strings. The last parameter must be NULL.
446  * This will concatenate two strings:
447  *
448  *   char *message = mp_multicat(pool, "hello ", "world", NULL);
449  **/
450 char *mp_multicat(struct mempool *, ...) LIKE_MALLOC SENTINEL_CHECK;
451 /**
452  * Concatenates two strings and stores result on @mp.
453  */
454 static inline char *LIKE_MALLOC mp_strcat(struct mempool *mp, const char *x, const char *y)
455 {
456   return mp_multicat(mp, x, y, NULL);
457 }
458 /**
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.
462  **/
463 char *mp_strjoin(struct mempool *p, char **a, uns n, uns sep) LIKE_MALLOC;
464 /**
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.
467  **/
468 char *mp_str_from_mem(struct mempool *p, const void *mem, uns len) LIKE_MALLOC;
469
470
471 /***
472  * [[format]]
473  * Formatted output
474  * ---------------
475  ***/
476
477 /**
478  * printf() into a in-memory string, allocated on the memory pool.
479  **/
480 char *mp_printf(struct mempool *mp, const char *fmt, ...) FORMAT_CHECK(printf,2,3) LIKE_MALLOC;
481 /**
482  * Like @mp_printf(), but uses `va_list` for parameters.
483  **/
484 char *mp_vprintf(struct mempool *mp, const char *fmt, va_list args) LIKE_MALLOC;
485 /**
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.
489  *
490  * Returns pointer to the beginning of the string (the pointer may have
491  * changed due to reallocation).
492  **/
493 char *mp_printf_append(struct mempool *mp, char *ptr, const char *fmt, ...) FORMAT_CHECK(printf,3,4);
494 /**
495  * Like @mp_printf_append(), but uses `va_list` for parameters.
496  **/
497 char *mp_vprintf_append(struct mempool *mp, char *ptr, const char *fmt, va_list args);
498
499 #endif