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