1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-mempool.h Memory pools
4 * Copyright (C) 2002, 2003 Red Hat, Inc.
6 * Licensed under the Academic Free License version 2.1
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include "dbus-mempool.h"
26 #include "dbus-internals.h"
27 #include "dbus-valgrind-internal.h"
30 * @defgroup DBusMemPool memory pools
31 * @ingroup DBusInternals
32 * @brief DBusMemPool object
34 * Types and functions related to DBusMemPool. A memory pool is used
35 * to decrease memory fragmentation/overhead and increase speed for
36 * blocks of small uniformly-sized objects. The main point is to avoid
37 * the overhead of a malloc block for each small object, speed is
42 * @defgroup DBusMemPoolInternals Memory pool implementation details
43 * @ingroup DBusInternals
44 * @brief DBusMemPool implementation details
46 * The guts of DBusMemPool.
52 * typedef so DBusFreedElement struct can refer to itself.
54 typedef struct DBusFreedElement DBusFreedElement;
57 * struct representing an element on the free list.
58 * We just cast freed elements to this so we can
59 * make a list out of them.
61 struct DBusFreedElement
63 DBusFreedElement *next; /**< next element of the free list */
67 * The dummy size of the variable-length "elements"
68 * field in DBusMemBlock
70 #define ELEMENT_PADDING 4
73 * Typedef for DBusMemBlock so the struct can recursively
76 typedef struct DBusMemBlock DBusMemBlock;
79 * DBusMemBlock object represents a single malloc()-returned
80 * block that gets chunked up into objects in the memory pool.
84 DBusMemBlock *next; /**< next block in the list, which is already used up;
85 * only saved so we can free all the blocks
86 * when we free the mem pool.
89 /* this is a long so that "elements" is aligned */
90 long used_so_far; /**< bytes of this block already allocated as elements. */
92 unsigned char elements[ELEMENT_PADDING]; /**< the block data, actually allocated to required size */
96 * Internals fields of DBusMemPool
100 int element_size; /**< size of a single object in the pool */
101 int block_size; /**< size of most recently allocated block */
102 unsigned int zero_elements : 1; /**< whether to zero-init allocated elements */
104 DBusFreedElement *free_elements; /**< a free list of elements to recycle */
105 DBusMemBlock *blocks; /**< blocks of memory from malloc() */
106 int allocated_elements; /**< Count of outstanding allocated elements */
112 * @addtogroup DBusMemPool
118 * @typedef DBusMemPool
120 * Opaque object representing a memory pool. Memory pools allow
121 * avoiding per-malloc-block memory overhead when allocating a lot of
122 * small objects that are all the same size. They are slightly
123 * faster than calling malloc() also.
127 * Creates a new memory pool, or returns #NULL on failure. Objects in
128 * the pool must be at least sizeof(void*) bytes each, due to the way
129 * memory pools work. To avoid creating 64 bit problems, this means at
130 * least 8 bytes on all platforms, unless you are 4 bytes on 32-bit
131 * and 8 bytes on 64-bit.
133 * @param element_size size of an element allocated from the pool.
134 * @param zero_elements whether to zero-initialize elements
135 * @returns the new pool or #NULL
138 _dbus_mem_pool_new (int element_size,
139 dbus_bool_t zero_elements)
143 pool = dbus_new0 (DBusMemPool, 1);
147 /* Make the element size at least 8 bytes. */
148 if (element_size < 8)
151 /* these assertions are equivalent but the first is more clear
152 * to programmers that see it fail.
154 _dbus_assert (element_size >= (int) sizeof (void*));
155 _dbus_assert (element_size >= (int) sizeof (DBusFreedElement));
157 /* align the element size to a pointer boundary so we won't get bus
158 * errors under other architectures.
160 pool->element_size = _DBUS_ALIGN_VALUE (element_size, sizeof (void *));
162 pool->zero_elements = zero_elements != FALSE;
164 pool->allocated_elements = 0;
166 /* pick a size for the first block; it increases
167 * for each block we need to allocate. This is
168 * actually half the initial block size
169 * since _dbus_mem_pool_alloc() unconditionally
170 * doubles it prior to creating a new block. */
171 pool->block_size = pool->element_size * 8;
173 _dbus_assert ((pool->block_size %
174 pool->element_size) == 0);
176 VALGRIND_CREATE_MEMPOOL (pool, 0, zero_elements);
182 * Frees a memory pool (and all elements allocated from it).
184 * @param pool the memory pool.
187 _dbus_mem_pool_free (DBusMemPool *pool)
191 VALGRIND_DESTROY_MEMPOOL (pool);
193 block = pool->blocks;
194 while (block != NULL)
196 DBusMemBlock *next = block->next;
207 * Allocates an object from the memory pool.
208 * The object must be freed with _dbus_mem_pool_dealloc().
210 * @param pool the memory pool
211 * @returns the allocated object or #NULL if no memory.
214 _dbus_mem_pool_alloc (DBusMemPool *pool)
216 #ifdef DBUS_BUILD_TESTS
217 if (_dbus_disable_mem_pools ())
222 /* This is obviously really silly, but it's
223 * debug-mode-only code that is compiled out
224 * when tests are disabled (_dbus_disable_mem_pools()
225 * is a constant expression FALSE so this block
229 alloc_size = sizeof (DBusMemBlock) - ELEMENT_PADDING +
232 if (pool->zero_elements)
233 block = dbus_malloc0 (alloc_size);
235 block = dbus_malloc (alloc_size);
239 block->next = pool->blocks;
240 pool->blocks = block;
241 pool->allocated_elements += 1;
243 VALGRIND_MEMPOOL_ALLOC (pool, (void *) &block->elements[0],
245 return (void*) &block->elements[0];
253 if (_dbus_decrement_fail_alloc_counter ())
255 _dbus_verbose (" FAILING mempool alloc\n");
258 else if (pool->free_elements)
260 DBusFreedElement *element = pool->free_elements;
262 pool->free_elements = pool->free_elements->next;
264 VALGRIND_MEMPOOL_ALLOC (pool, element, pool->element_size);
266 if (pool->zero_elements)
267 memset (element, '\0', pool->element_size);
269 pool->allocated_elements += 1;
277 if (pool->blocks == NULL ||
278 pool->blocks->used_so_far == pool->block_size)
280 /* Need a new block */
283 #ifdef DBUS_BUILD_TESTS
287 if (pool->block_size <= _DBUS_INT_MAX / 4) /* avoid overflow */
289 /* use a larger block size for our next block */
290 pool->block_size *= 2;
291 _dbus_assert ((pool->block_size %
292 pool->element_size) == 0);
295 alloc_size = sizeof (DBusMemBlock) - ELEMENT_PADDING + pool->block_size;
297 #ifdef DBUS_BUILD_TESTS
298 /* We save/restore the counter, so that memory pools won't
299 * cause a given function to have different number of
300 * allocations on different invocations. i.e. when testing
301 * we want consistent alloc patterns. So we skip our
302 * malloc here for purposes of failed alloc simulation.
304 saved_counter = _dbus_get_fail_alloc_counter ();
305 _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
308 if (pool->zero_elements)
309 block = dbus_malloc0 (alloc_size);
311 block = dbus_malloc (alloc_size);
313 #ifdef DBUS_BUILD_TESTS
314 _dbus_set_fail_alloc_counter (saved_counter);
315 _dbus_assert (saved_counter == _dbus_get_fail_alloc_counter ());
321 block->used_so_far = 0;
322 block->next = pool->blocks;
323 pool->blocks = block;
326 element = &pool->blocks->elements[pool->blocks->used_so_far];
328 pool->blocks->used_so_far += pool->element_size;
330 pool->allocated_elements += 1;
332 VALGRIND_MEMPOOL_ALLOC (pool, element, pool->element_size);
339 * Deallocates an object previously created with
340 * _dbus_mem_pool_alloc(). The previous object
341 * must have come from this same pool.
342 * @param pool the memory pool
343 * @param element the element earlier allocated.
344 * @returns #TRUE if there are no remaining allocated elements
347 _dbus_mem_pool_dealloc (DBusMemPool *pool,
350 VALGRIND_MEMPOOL_FREE (pool, element);
352 #ifdef DBUS_BUILD_TESTS
353 if (_dbus_disable_mem_pools ())
358 /* mmm, fast. ;-) debug-only code, so doesn't matter. */
361 block = pool->blocks;
363 while (block != NULL)
365 if (block->elements == (unsigned char*) element)
368 prev->next = block->next;
370 pool->blocks = block->next;
374 _dbus_assert (pool->allocated_elements > 0);
375 pool->allocated_elements -= 1;
377 if (pool->allocated_elements == 0)
378 _dbus_assert (pool->blocks == NULL);
380 return pool->blocks == NULL;
386 _dbus_assert_not_reached ("freed nonexistent block");
392 DBusFreedElement *freed;
395 /* used for internal mempool administration */
396 VALGRIND_MAKE_MEM_UNDEFINED (freed, sizeof (freed));
398 freed->next = pool->free_elements;
399 pool->free_elements = freed;
401 _dbus_assert (pool->allocated_elements > 0);
402 pool->allocated_elements -= 1;
404 return pool->allocated_elements == 0;
408 #ifdef DBUS_ENABLE_STATS
410 _dbus_mem_pool_get_stats (DBusMemPool *pool,
411 dbus_uint32_t *in_use_p,
412 dbus_uint32_t *in_free_list_p,
413 dbus_uint32_t *allocated_p)
416 DBusFreedElement *freed;
417 dbus_uint32_t in_use = 0;
418 dbus_uint32_t in_free_list = 0;
419 dbus_uint32_t allocated = 0;
423 in_use = pool->element_size * pool->allocated_elements;
425 for (freed = pool->free_elements; freed != NULL; freed = freed->next)
427 in_free_list += pool->element_size;
430 for (block = pool->blocks; block != NULL; block = block->next)
432 if (block == pool->blocks)
433 allocated += pool->block_size;
435 allocated += block->used_so_far;
439 if (in_use_p != NULL)
442 if (in_free_list_p != NULL)
443 *in_free_list_p = in_free_list;
445 if (allocated_p != NULL)
446 *allocated_p = allocated;
448 #endif /* DBUS_ENABLE_STATS */
452 #ifdef DBUS_BUILD_TESTS
453 #include "dbus-test.h"
458 time_for_size (int size)
464 #define FREE_ARRAY_SIZE 512
465 #define N_ITERATIONS FREE_ARRAY_SIZE * 512
466 void *to_free[FREE_ARRAY_SIZE];
469 _dbus_verbose ("Timings for size %d\n", size);
471 _dbus_verbose (" malloc\n");
477 while (i < N_ITERATIONS)
479 to_free[j] = dbus_malloc (size);
480 _dbus_assert (to_free[j] != NULL); /* in a real app of course this is wrong */
484 if (j == FREE_ARRAY_SIZE)
487 while (j < FREE_ARRAY_SIZE)
489 dbus_free (to_free[j]);
501 _dbus_verbose (" created/destroyed %d elements in %g seconds\n",
502 N_ITERATIONS, (end - start) / (double) CLOCKS_PER_SEC);
506 _dbus_verbose (" mempools\n");
510 pool = _dbus_mem_pool_new (size, FALSE);
514 while (i < N_ITERATIONS)
516 to_free[j] = _dbus_mem_pool_alloc (pool);
517 _dbus_assert (to_free[j] != NULL); /* in a real app of course this is wrong */
521 if (j == FREE_ARRAY_SIZE)
524 while (j < FREE_ARRAY_SIZE)
526 _dbus_mem_pool_dealloc (pool, to_free[j]);
536 _dbus_mem_pool_free (pool);
540 _dbus_verbose (" created/destroyed %d elements in %g seconds\n",
541 N_ITERATIONS, (end - start) / (double) CLOCKS_PER_SEC);
543 _dbus_verbose (" zeroed malloc\n");
549 while (i < N_ITERATIONS)
551 to_free[j] = dbus_malloc0 (size);
552 _dbus_assert (to_free[j] != NULL); /* in a real app of course this is wrong */
556 if (j == FREE_ARRAY_SIZE)
559 while (j < FREE_ARRAY_SIZE)
561 dbus_free (to_free[j]);
573 _dbus_verbose (" created/destroyed %d elements in %g seconds\n",
574 N_ITERATIONS, (end - start) / (double) CLOCKS_PER_SEC);
576 _dbus_verbose (" zeroed mempools\n");
580 pool = _dbus_mem_pool_new (size, TRUE);
584 while (i < N_ITERATIONS)
586 to_free[j] = _dbus_mem_pool_alloc (pool);
587 _dbus_assert (to_free[j] != NULL); /* in a real app of course this is wrong */
591 if (j == FREE_ARRAY_SIZE)
594 while (j < FREE_ARRAY_SIZE)
596 _dbus_mem_pool_dealloc (pool, to_free[j]);
606 _dbus_mem_pool_free (pool);
610 _dbus_verbose (" created/destroyed %d elements in %g seconds\n",
611 N_ITERATIONS, (end - start) / (double) CLOCKS_PER_SEC);
615 * @ingroup DBusMemPoolInternals
616 * Unit test for DBusMemPool
617 * @returns #TRUE on success.
620 _dbus_mem_pool_test (void)
623 int element_sizes[] = { 4, 8, 16, 50, 124 };
626 while (i < _DBUS_N_ELEMENTS (element_sizes))
628 time_for_size (element_sizes[i]);
635 #endif /* DBUS_BUILD_TESTS */