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