2 * UCW Library -- Fast Allocator for Fixed-Size Elements
4 * (c) 2007 Martin Mares <mj@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
11 * This allocator is optimized for intensive allocation and freeing of small
12 * blocks of identical sizes. System memory is allocated by multiples of the
13 * page size and it is returned back only when the whole eltpool is deleted.
15 * In the future, we can add returning of memory to the system and also cache
16 * coloring like in the SLAB allocator used in the Linux kernel.
22 #include "ucw/eltpool.h"
25 ep_new(uns elt_size, uns elts_per_chunk)
27 struct eltpool *pool = xmalloc_zero(sizeof(*pool));
28 pool->elt_size = ALIGN_TO(MAX(elt_size, sizeof(struct eltpool_free)), CPU_STRUCT_ALIGN);
29 pool->chunk_size = CPU_PAGE_SIZE;
30 while (pool->elt_size * elts_per_chunk + sizeof(struct eltpool_chunk) > pool->chunk_size)
31 pool->chunk_size *= 2;
32 pool->elts_per_chunk = (pool->chunk_size - sizeof(struct eltpool_chunk)) / pool->elt_size;
33 DBG("ep_new(): got elt_size=%d, epc=%d; used chunk_size=%d, epc=%d", elt_size, elts_per_chunk, pool->chunk_size, pool->elts_per_chunk);
38 ep_delete(struct eltpool *pool)
40 struct eltpool_chunk *ch;
41 while (ch = pool->first_chunk)
43 pool->first_chunk = ch->next;
44 page_free(ch, pool->chunk_size);
50 ep_alloc_slow(struct eltpool *pool)
52 struct eltpool_chunk *ch = page_alloc(pool->chunk_size);
53 void *p = (void *)(ch+1);
54 for (uns i=1; i<pool->elts_per_chunk; i++)
56 struct eltpool_free *f = p;
57 f->next = pool->first_free;
61 ch->next = pool->first_chunk;
62 pool->first_chunk = ch;
68 ep_total_size(struct eltpool *pool)
70 return (u64)pool->num_chunks * pool->chunk_size + sizeof(*pool);
76 #include "ucw/clists.h"
85 struct eltpool *ep = ep_new(sizeof(struct argh), 64);
88 for (uns i=0; i<65536; i++)
90 struct argh *a = ep_alloc(ep);
92 clist_add_tail(&l, &a->n);
94 clist_add_head(&l, &a->n);