]> mj.ucw.cz Git - libucw.git/blob - ucw/mempool.c
Mempool: Implemented statistics about allocated bytes from memory pool to application.
[libucw.git] / ucw / mempool.c
1 /*
2  *      UCW Library -- Memory Pools (One-Time Allocation)
3  *
4  *      (c) 1997--2014 Martin Mares <mj@ucw.cz>
5  *      (c) 2007--2014 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 #undef LOCAL_DEBUG
12
13 #include <ucw/lib.h>
14 #include <ucw/alloc.h>
15 #include <ucw/mempool.h>
16
17 #include <string.h>
18
19 #define MP_CHUNK_TAIL ALIGN_TO(sizeof(struct mempool_chunk), CPU_STRUCT_ALIGN)
20 #define MP_SIZE_MAX (~0U - MP_CHUNK_TAIL - CPU_PAGE_SIZE)
21
22 struct mempool_chunk {
23 #ifdef CONFIG_DEBUG
24   struct mempool *pool;         // Can be useful when analysing coredump for memory leaks
25 #endif
26   struct mempool_chunk *next;
27   uns size;
28 };
29
30 static uns
31 mp_align_size(uns size)
32 {
33 #ifdef CONFIG_UCW_POOL_IS_MMAP
34   return ALIGN_TO(size + MP_CHUNK_TAIL, CPU_PAGE_SIZE) - MP_CHUNK_TAIL;
35 #else
36   return ALIGN_TO(size, CPU_STRUCT_ALIGN);
37 #endif
38 }
39
40 static void *mp_allocator_alloc(struct ucw_allocator *a, size_t size)
41 {
42   struct mempool *mp = (struct mempool *) a;
43   return mp_alloc_fast(mp, size);
44 }
45
46 static void *mp_allocator_realloc(struct ucw_allocator *a, void *ptr, size_t old_size, size_t new_size)
47 {
48   if (new_size <= old_size)
49     return ptr;
50
51   /*
52    *  In the future, we might want to do something like mp_realloc(),
53    *  but we have to check that it is indeed the last block in the pool.
54    */
55   struct mempool *mp = (struct mempool *) a;
56   void *new = mp_alloc_fast(mp, new_size);
57   memcpy(new, ptr, old_size);
58   return new;
59 }
60
61 static void mp_allocator_free(struct ucw_allocator *a UNUSED, void *ptr UNUSED)
62 {
63   // Does nothing
64 }
65
66 void
67 mp_init(struct mempool *pool, uns chunk_size)
68 {
69   chunk_size = mp_align_size(MAX(sizeof(struct mempool), chunk_size));
70   *pool = (struct mempool) {
71     .allocator = {
72       .alloc = mp_allocator_alloc,
73       .realloc = mp_allocator_realloc,
74       .free = mp_allocator_free,
75     },
76     .chunk_size = chunk_size,
77     .threshold = chunk_size >> 1,
78     .last_big = &pool->last_big
79   };
80 }
81
82 static void *
83 mp_new_big_chunk(struct mempool *pool, uns size)
84 {
85   struct mempool_chunk *chunk;
86   chunk = xmalloc(size + MP_CHUNK_TAIL) + size;
87   chunk->size = size;
88   if (pool)
89     pool->total_size += size + MP_CHUNK_TAIL;
90   return chunk;
91 }
92
93 static void
94 mp_free_big_chunk(struct mempool *pool, struct mempool_chunk *chunk)
95 {
96   pool->total_size -= chunk->size + MP_CHUNK_TAIL;
97   xfree((void *)chunk - chunk->size);
98 }
99
100 static void *
101 mp_new_chunk(struct mempool *pool, uns size)
102 {
103 #ifdef CONFIG_UCW_POOL_IS_MMAP
104   struct mempool_chunk *chunk;
105   chunk = page_alloc(size + MP_CHUNK_TAIL) + size;
106   chunk->size = size;
107   if (pool)
108     pool->total_size += size + MP_CHUNK_TAIL;
109   return chunk;
110 #else
111   return mp_new_big_chunk(pool, size);
112 #endif
113 }
114
115 static void
116 mp_free_chunk(struct mempool *pool, struct mempool_chunk *chunk)
117 {
118 #ifdef CONFIG_UCW_POOL_IS_MMAP
119   pool->total_size -= chunk->size + MP_CHUNK_TAIL;
120   page_free((void *)chunk - chunk->size, chunk->size + MP_CHUNK_TAIL);
121 #else
122   mp_free_big_chunk(pool, chunk);
123 #endif
124 }
125
126 struct mempool *
127 mp_new(uns chunk_size)
128 {
129   chunk_size = mp_align_size(MAX(sizeof(struct mempool), chunk_size));
130   struct mempool_chunk *chunk = mp_new_chunk(NULL, chunk_size);
131   struct mempool *pool = (void *)chunk - chunk_size;
132   DBG("Creating mempool %p with %u bytes long chunks", pool, chunk_size);
133   chunk->next = NULL;
134 #ifdef CONFIG_DEBUG
135   chunk->pool = pool;
136 #endif
137   *pool = (struct mempool) {
138     .allocator = {
139       .alloc = mp_allocator_alloc,
140       .realloc = mp_allocator_realloc,
141       .free = mp_allocator_free,
142     },
143     .state = { .free = { chunk_size - sizeof(*pool) }, .last = { chunk } },
144     .chunk_size = chunk_size,
145     .threshold = chunk_size >> 1,
146     .last_big = &pool->last_big,
147     .total_size = chunk->size + MP_CHUNK_TAIL,
148   };
149   return pool;
150 }
151
152 static void
153 mp_free_chain(struct mempool *pool, struct mempool_chunk *chunk)
154 {
155   while (chunk)
156     {
157       struct mempool_chunk *next = chunk->next;
158       mp_free_chunk(pool, chunk);
159       chunk = next;
160     }
161 }
162
163 static void
164 mp_free_big_chain(struct mempool *pool, struct mempool_chunk *chunk)
165 {
166   while (chunk)
167     {
168       struct mempool_chunk *next = chunk->next;
169       mp_free_big_chunk(pool, chunk);
170       chunk = next;
171     }
172 }
173
174 void
175 mp_delete(struct mempool *pool)
176 {
177   DBG("Deleting mempool %p", pool);
178   mp_free_big_chain(pool, pool->state.last[1]);
179   mp_free_chain(pool, pool->unused);
180   mp_free_chain(pool, pool->state.last[0]); // can contain the mempool structure
181 }
182
183 void
184 mp_flush(struct mempool *pool)
185 {
186   mp_free_big_chain(pool, pool->state.last[1]);
187   struct mempool_chunk *chunk, *next;
188   for (chunk = pool->state.last[0]; chunk && (void *)chunk - chunk->size != pool; chunk = next)
189     {
190       next = chunk->next;
191       chunk->next = pool->unused;
192       pool->unused = chunk;
193     }
194   pool->state.last[0] = chunk;
195   pool->state.free[0] = chunk ? chunk->size - sizeof(*pool) : 0;
196   pool->state.last[1] = NULL;
197   pool->state.free[1] = 0;
198   pool->state.next = NULL;
199   pool->last_big = &pool->last_big;
200 }
201
202 static void
203 mp_stats_chain(struct mempool_chunk *chunk, struct mempool_stats *stats, uns idx)
204 {
205   while (chunk)
206     {
207       stats->chain_size[idx] += chunk->size + MP_CHUNK_TAIL;
208       stats->chain_count[idx]++;
209       chunk = chunk->next;
210     }
211   stats->total_size += stats->chain_size[idx];
212 }
213
214 void
215 mp_stats(struct mempool *pool, struct mempool_stats *stats)
216 {
217   bzero(stats, sizeof(*stats));
218   mp_stats_chain(pool->state.last[0], stats, 0);
219   mp_stats_chain(pool->state.last[1], stats, 1);
220   mp_stats_chain(pool->unused, stats, 2);
221   ASSERT(stats->total_size == pool->total_size);
222   stats->used_size = stats->chain_size[0] + stats->chain_size[1]
223     - MP_CHUNK_TAIL * (stats->chain_count[0] + stats->chain_count[1])
224     - pool->state.free[0] - pool->state.free[1];
225 }
226
227 u64
228 mp_total_size(struct mempool *pool)
229 {
230   return pool->total_size;
231 }
232
233 void *
234 mp_alloc_internal(struct mempool *pool, uns size)
235 {
236   struct mempool_chunk *chunk;
237   if (size <= pool->threshold)
238     {
239       pool->idx = 0;
240       if (pool->unused)
241         {
242           chunk = pool->unused;
243           pool->unused = chunk->next;
244         }
245       else
246         {
247           chunk = mp_new_chunk(pool, pool->chunk_size);
248 #ifdef CONFIG_DEBUG
249           chunk->pool = pool;
250 #endif
251         }
252       chunk->next = pool->state.last[0];
253       pool->state.last[0] = chunk;
254       pool->state.free[0] = pool->chunk_size - size;
255       return (void *)chunk - pool->chunk_size;
256     }
257   else if (likely(size <= MP_SIZE_MAX))
258     {
259       pool->idx = 1;
260       uns aligned = ALIGN_TO(size, CPU_STRUCT_ALIGN);
261       chunk = mp_new_big_chunk(pool, aligned);
262       chunk->next = pool->state.last[1];
263 #ifdef CONFIG_DEBUG
264       chunk->pool = pool;
265 #endif
266       pool->state.last[1] = chunk;
267       pool->state.free[1] = aligned - size;
268       return pool->last_big = (void *)chunk - aligned;
269     }
270   else
271     die("Cannot allocate %u bytes from a mempool", size);
272 }
273
274 void *
275 mp_alloc(struct mempool *pool, uns size)
276 {
277   return mp_alloc_fast(pool, size);
278 }
279
280 void *
281 mp_alloc_noalign(struct mempool *pool, uns size)
282 {
283   return mp_alloc_fast_noalign(pool, size);
284 }
285
286 void *
287 mp_alloc_zero(struct mempool *pool, uns size)
288 {
289   void *ptr = mp_alloc_fast(pool, size);
290   bzero(ptr, size);
291   return ptr;
292 }
293
294 void *
295 mp_start_internal(struct mempool *pool, uns size)
296 {
297   void *ptr = mp_alloc_internal(pool, size);
298   pool->state.free[pool->idx] += size;
299   return ptr;
300 }
301
302 void *
303 mp_start(struct mempool *pool, uns size)
304 {
305   return mp_start_fast(pool, size);
306 }
307
308 void *
309 mp_start_noalign(struct mempool *pool, uns size)
310 {
311   return mp_start_fast_noalign(pool, size);
312 }
313
314 void *
315 mp_grow_internal(struct mempool *pool, uns size)
316 {
317   if (unlikely(size > MP_SIZE_MAX))
318     die("Cannot allocate %u bytes of memory", size);
319   uns avail = mp_avail(pool);
320   void *ptr = mp_ptr(pool);
321   if (pool->idx)
322     {
323       uns amortized = likely(avail <= MP_SIZE_MAX / 2) ? avail * 2 : MP_SIZE_MAX;
324       amortized = MAX(amortized, size);
325       amortized = ALIGN_TO(amortized, CPU_STRUCT_ALIGN);
326       struct mempool_chunk *chunk = pool->state.last[1], *next = chunk->next;
327       pool->total_size = pool->total_size - chunk->size + amortized;
328       ptr = xrealloc(ptr, amortized + MP_CHUNK_TAIL);
329       chunk = ptr + amortized;
330       chunk->next = next;
331       chunk->size = amortized;
332       pool->state.last[1] = chunk;
333       pool->state.free[1] = amortized;
334       pool->last_big = ptr;
335       return ptr;
336     }
337   else
338     {
339       void *p = mp_start_internal(pool, size);
340       memcpy(p, ptr, avail);
341       return p;
342     }
343 }
344
345 uns
346 mp_open(struct mempool *pool, void *ptr)
347 {
348   return mp_open_fast(pool, ptr);
349 }
350
351 void *
352 mp_realloc(struct mempool *pool, void *ptr, uns size)
353 {
354   return mp_realloc_fast(pool, ptr, size);
355 }
356
357 void *
358 mp_realloc_zero(struct mempool *pool, void *ptr, uns size)
359 {
360   uns old_size = mp_open_fast(pool, ptr);
361   ptr = mp_grow(pool, size);
362   if (size > old_size)
363     bzero(ptr + old_size, size - old_size);
364   mp_end(pool, ptr + size);
365   return ptr;
366 }
367
368 void *
369 mp_spread_internal(struct mempool *pool, void *p, uns size)
370 {
371   void *old = mp_ptr(pool);
372   void *new = mp_grow_internal(pool, p-old+size);
373   return p-old+new;
374 }
375
376 void
377 mp_restore(struct mempool *pool, struct mempool_state *state)
378 {
379   struct mempool_chunk *chunk, *next;
380   struct mempool_state s = *state;
381   for (chunk = pool->state.last[0]; chunk != s.last[0]; chunk = next)
382     {
383       next = chunk->next;
384       chunk->next = pool->unused;
385       pool->unused = chunk;
386     }
387   for (chunk = pool->state.last[1]; chunk != s.last[1]; chunk = next)
388     {
389       next = chunk->next;
390       mp_free_big_chunk(pool, chunk);
391     }
392   pool->state = s;
393   pool->last_big = &pool->last_big;
394 }
395
396 struct mempool_state *
397 mp_push(struct mempool *pool)
398 {
399   struct mempool_state state = pool->state;
400   struct mempool_state *p = mp_alloc_fast(pool, sizeof(*p));
401   *p = state;
402   pool->state.next = p;
403   return p;
404 }
405
406 void
407 mp_pop(struct mempool *pool)
408 {
409   ASSERT(pool->state.next);
410   mp_restore(pool, pool->state.next);
411 }
412
413 #ifdef TEST
414
415 #include <ucw/getopt.h>
416 #include <stdio.h>
417 #include <stdlib.h>
418 #include <time.h>
419
420 static void
421 fill(byte *ptr, uns len, uns magic)
422 {
423   while (len--)
424     *ptr++ = (magic++ & 255);
425 }
426
427 static void
428 check(byte *ptr, uns len, uns magic, uns align)
429 {
430   ASSERT(!((uintptr_t)ptr & (align - 1)));
431   while (len--)
432     if (*ptr++ != (magic++ & 255))
433       ASSERT(0);
434 }
435
436 int main(int argc, char **argv)
437 {
438   srand(time(NULL));
439   log_init(argv[0]);
440   cf_def_file = NULL;
441   if (cf_getopt(argc, argv, CF_SHORT_OPTS, CF_NO_LONG_OPTS, NULL) >= 0 || argc != optind)
442     die("Invalid usage");
443
444   uns max = 1000, n = 0, m = 0, can_realloc = 0;
445   void *ptr[max];
446   struct mempool_state *state[max];
447   uns len[max], num[max], align[max];
448   struct mempool *mp = mp_new(128), mp_static;
449
450   for (uns i = 0; i < 5000; i++)
451     {
452       for (uns j = 0; j < n; j++)
453         check(ptr[j], len[j], j, align[j]);
454 #if 0
455       DBG("free_small=%u free_big=%u idx=%u chunk_size=%u last_big=%p", mp->state.free[0], mp->state.free[1], mp->idx, mp->chunk_size, mp->last_big);
456       for (struct mempool_chunk *ch = mp->state.last[0]; ch; ch = ch->next)
457         DBG("small %p %p %p %d", (byte *)ch - ch->size, ch, ch + 1, ch->size);
458       for (struct mempool_chunk *ch = mp->state.last[1]; ch; ch = ch->next)
459         DBG("big %p %p %p %d", (byte *)ch - ch->size, ch, ch + 1, ch->size);
460 #endif
461       int r = random_max(100);
462       if ((r -= 1) < 0)
463         {
464           DBG("flush");
465           mp_flush(mp);
466           n = m = 0;
467         }
468       else if ((r -= 1) < 0)
469         {
470           DBG("delete & new");
471           mp_delete(mp);
472           if (random_max(2))
473             mp = mp_new(random_max(0x1000) + 1);
474           else
475             mp = &mp_static, mp_init(mp, random_max(512) + 1);
476           n = m = 0;
477         }
478       else if (n < max && (r -= 30) < 0)
479         {
480           len[n] = random_max(0x2000);
481           DBG("alloc(%u)", len[n]);
482           align[n] = random_max(2) ? CPU_STRUCT_ALIGN : 1;
483           ptr[n] = (align[n] == 1) ? mp_alloc_fast_noalign(mp, len[n]) : mp_alloc_fast(mp, len[n]);
484           DBG(" -> (%p)", ptr[n]);
485           fill(ptr[n], len[n], n);
486           n++;
487           can_realloc = 1;
488         }
489       else if (n < max && (r -= 20) < 0)
490         {
491           len[n] = random_max(0x2000);
492           DBG("start(%u)", len[n]);
493           align[n] = random_max(2) ? CPU_STRUCT_ALIGN : 1;
494           ptr[n] = (align[n] == 1) ? mp_start_fast_noalign(mp, len[n]) : mp_start_fast(mp, len[n]);
495           DBG(" -> (%p)", ptr[n]);
496           fill(ptr[n], len[n], n);
497           n++;
498           can_realloc = 1;
499           goto grow;
500         }
501       else if (can_realloc && n && (r -= 10) < 0)
502         {
503           if (mp_open(mp, ptr[n - 1]) != len[n - 1])
504             ASSERT(0);
505 grow:
506           {
507             uns k = n - 1;
508             for (uns i = random_max(4); i--; )
509               {
510                 uns l = len[k];
511                 len[k] = random_max(0x2000);
512                 DBG("grow(%u)", len[k]);
513                 ptr[k] = mp_grow(mp, len[k]);
514                 DBG(" -> (%p)", ptr[k]);
515                 check(ptr[k], MIN(l, len[k]), k, align[k]);
516                 fill(ptr[k], len[k], k);
517               }
518             mp_end(mp, ptr[k] + len[k]);
519           }
520         }
521       else if (can_realloc && n && (r -= 20) < 0)
522         {
523           uns i = n - 1, l = len[i];
524           DBG("realloc(%p, %u)", ptr[i], len[i]);
525           ptr[i] = mp_realloc(mp, ptr[i], len[i] = random_max(0x2000));
526           DBG(" -> (%p, %u)", ptr[i], len[i]);
527           check(ptr[i],  MIN(len[i], l), i, align[i]);
528           fill(ptr[i], len[i], i);
529         }
530       else if (m < max && (r -= 5) < 0)
531         {
532           DBG("push(%u)", m);
533           num[m] = n;
534           state[m++] = mp_push(mp);
535           can_realloc = 0;
536         }
537       else if (m && (r -= 2) < 0)
538         {
539           m--;
540           DBG("pop(%u)", m);
541           mp_pop(mp);
542           n = num[m];
543           can_realloc = 0;
544         }
545       else if (m && (r -= 1) < 0)
546         {
547           uns i = random_max(m);
548           DBG("restore(%u)", i);
549           mp_restore(mp, state[i]);
550           n = num[m = i];
551           can_realloc = 0;
552         }
553       else if (can_realloc && n && (r -= 5) < 0)
554         ASSERT(mp_size(mp, ptr[n - 1]) == len[n - 1]);
555       else
556         {
557           struct mempool_stats stats;
558           mp_stats(mp, &stats);
559         }
560     }
561
562   mp_delete(mp);
563   return 0;
564 }
565
566 #endif