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"
29 * @defgroup DBusMemPool memory pools
30 * @ingroup DBusInternals
31 * @brief DBusMemPool object
33 * Types and functions related to DBusMemPool. A memory pool is used
34 * to decrease memory fragmentation/overhead and increase speed for
35 * blocks of small uniformly-sized objects. The main point is to avoid
36 * the overhead of a malloc block for each small object, speed is
41 * @defgroup DBusMemPoolInternals Memory pool implementation details
42 * @ingroup DBusInternals
43 * @brief DBusMemPool implementation details
45 * The guts of DBusMemPool.
51 * typedef so DBusFreedElement struct can refer to itself.
53 typedef struct DBusFreedElement DBusFreedElement;
56 * struct representing an element on the free list.
57 * We just cast freed elements to this so we can
58 * make a list out of them.
60 struct DBusFreedElement
62 DBusFreedElement *next; /**< next element of the free list */
66 * The dummy size of the variable-length "elements"
67 * field in DBusMemBlock
69 #define ELEMENT_PADDING 4
72 * Typedef for DBusMemBlock so the struct can recursively
75 typedef struct DBusMemBlock DBusMemBlock;
78 * DBusMemBlock object represents a single malloc()-returned
79 * block that gets chunked up into objects in the memory pool.
83 DBusMemBlock *next; /**< next block in the list, which is already used up;
84 * only saved so we can free all the blocks
85 * when we free the mem pool.
88 /* this is a long so that "elements" is aligned */
89 long used_so_far; /**< bytes of this block already allocated as elements. */
91 unsigned char elements[ELEMENT_PADDING]; /**< the block data, actually allocated to required size */
95 * Internals fields of DBusMemPool
99 int element_size; /**< size of a single object in the pool */
100 int block_size; /**< size of most recently allocated block */
101 unsigned int zero_elements : 1; /**< whether to zero-init allocated elements */
103 DBusFreedElement *free_elements; /**< a free list of elements to recycle */
104 DBusMemBlock *blocks; /**< blocks of memory from malloc() */
105 int allocated_elements; /**< Count of outstanding allocated elements */
111 * @addtogroup DBusMemPool
117 * @typedef DBusMemPool
119 * Opaque object representing a memory pool. Memory pools allow
120 * avoiding per-malloc-block memory overhead when allocating a lot of
121 * small objects that are all the same size. They are slightly
122 * faster than calling malloc() also.
126 * Creates a new memory pool, or returns #NULL on failure. Objects in
127 * the pool must be at least sizeof(void*) bytes each, due to the way
128 * memory pools work. To avoid creating 64 bit problems, this means at
129 * least 8 bytes on all platforms, unless you are 4 bytes on 32-bit
130 * and 8 bytes on 64-bit.
132 * @param element_size size of an element allocated from the pool.
133 * @param zero_elements whether to zero-initialize elements
134 * @returns the new pool or #NULL
137 _dbus_mem_pool_new (int element_size,
138 dbus_bool_t zero_elements)
142 pool = dbus_new0 (DBusMemPool, 1);
146 /* Make the element size at least 8 bytes. */
147 if (element_size < 8)
150 /* these assertions are equivalent but the first is more clear
151 * to programmers that see it fail.
153 _dbus_assert (element_size >= (int) sizeof (void*));
154 _dbus_assert (element_size >= (int) sizeof (DBusFreedElement));
156 /* align the element size to a pointer boundary so we won't get bus
157 * errors under other architectures.
159 pool->element_size = _DBUS_ALIGN_VALUE (element_size, sizeof (void *));
161 pool->zero_elements = zero_elements != FALSE;
163 pool->allocated_elements = 0;
165 /* pick a size for the first block; it increases
166 * for each block we need to allocate. This is
167 * actually half the initial block size
168 * since _dbus_mem_pool_alloc() unconditionally
169 * doubles it prior to creating a new block. */
170 pool->block_size = pool->element_size * 8;
172 _dbus_assert ((pool->block_size %
173 pool->element_size) == 0);
179 * Frees a memory pool (and all elements allocated from it).
181 * @param pool the memory pool.
184 _dbus_mem_pool_free (DBusMemPool *pool)
188 block = pool->blocks;
189 while (block != NULL)
191 DBusMemBlock *next = block->next;
202 * Allocates an object from the memory pool.
203 * The object must be freed with _dbus_mem_pool_dealloc().
205 * @param pool the memory pool
206 * @returns the allocated object or #NULL if no memory.
209 _dbus_mem_pool_alloc (DBusMemPool *pool)
211 #ifdef DBUS_BUILD_TESTS
212 if (_dbus_disable_mem_pools ())
217 /* This is obviously really silly, but it's
218 * debug-mode-only code that is compiled out
219 * when tests are disabled (_dbus_disable_mem_pools()
220 * is a constant expression FALSE so this block
224 alloc_size = sizeof (DBusMemBlock) - ELEMENT_PADDING +
227 if (pool->zero_elements)
228 block = dbus_malloc0 (alloc_size);
230 block = dbus_malloc (alloc_size);
234 block->next = pool->blocks;
235 pool->blocks = block;
236 pool->allocated_elements += 1;
238 return (void*) &block->elements[0];
246 if (_dbus_decrement_fail_alloc_counter ())
248 _dbus_verbose (" FAILING mempool alloc\n");
251 else if (pool->free_elements)
253 DBusFreedElement *element = pool->free_elements;
255 pool->free_elements = pool->free_elements->next;
257 if (pool->zero_elements)
258 memset (element, '\0', pool->element_size);
260 pool->allocated_elements += 1;
268 if (pool->blocks == NULL ||
269 pool->blocks->used_so_far == pool->block_size)
271 /* Need a new block */
274 #ifdef DBUS_BUILD_TESTS
278 if (pool->block_size <= _DBUS_INT_MAX / 4) /* avoid overflow */
280 /* use a larger block size for our next block */
281 pool->block_size *= 2;
282 _dbus_assert ((pool->block_size %
283 pool->element_size) == 0);
286 alloc_size = sizeof (DBusMemBlock) - ELEMENT_PADDING + pool->block_size;
288 #ifdef DBUS_BUILD_TESTS
289 /* We save/restore the counter, so that memory pools won't
290 * cause a given function to have different number of
291 * allocations on different invocations. i.e. when testing
292 * we want consistent alloc patterns. So we skip our
293 * malloc here for purposes of failed alloc simulation.
295 saved_counter = _dbus_get_fail_alloc_counter ();
296 _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
299 if (pool->zero_elements)
300 block = dbus_malloc0 (alloc_size);
302 block = dbus_malloc (alloc_size);
304 #ifdef DBUS_BUILD_TESTS
305 _dbus_set_fail_alloc_counter (saved_counter);
306 _dbus_assert (saved_counter == _dbus_get_fail_alloc_counter ());
312 block->used_so_far = 0;
313 block->next = pool->blocks;
314 pool->blocks = block;
317 element = &pool->blocks->elements[pool->blocks->used_so_far];
319 pool->blocks->used_so_far += pool->element_size;
321 pool->allocated_elements += 1;
329 * Deallocates an object previously created with
330 * _dbus_mem_pool_alloc(). The previous object
331 * must have come from this same pool.
332 * @param pool the memory pool
333 * @param element the element earlier allocated.
334 * @returns #TRUE if there are no remaining allocated elements
337 _dbus_mem_pool_dealloc (DBusMemPool *pool,
340 #ifdef DBUS_BUILD_TESTS
341 if (_dbus_disable_mem_pools ())
346 /* mmm, fast. ;-) debug-only code, so doesn't matter. */
349 block = pool->blocks;
351 while (block != NULL)
353 if (block->elements == (unsigned char*) element)
356 prev->next = block->next;
358 pool->blocks = block->next;
362 _dbus_assert (pool->allocated_elements > 0);
363 pool->allocated_elements -= 1;
365 if (pool->allocated_elements == 0)
366 _dbus_assert (pool->blocks == NULL);
368 return pool->blocks == NULL;
374 _dbus_assert_not_reached ("freed nonexistent block");
380 DBusFreedElement *freed;
383 freed->next = pool->free_elements;
384 pool->free_elements = freed;
386 _dbus_assert (pool->allocated_elements > 0);
387 pool->allocated_elements -= 1;
389 return pool->allocated_elements == 0;
393 #ifdef DBUS_ENABLE_STATS
395 _dbus_mem_pool_get_stats (DBusMemPool *pool,
396 dbus_uint32_t *in_use_p,
397 dbus_uint32_t *in_free_list_p,
398 dbus_uint32_t *allocated_p)
401 DBusFreedElement *freed;
402 dbus_uint32_t in_use = 0;
403 dbus_uint32_t in_free_list = 0;
404 dbus_uint32_t allocated = 0;
408 in_use = pool->element_size * pool->allocated_elements;
410 for (freed = pool->free_elements; freed != NULL; freed = freed->next)
412 in_free_list += pool->element_size;
415 for (block = pool->blocks; block != NULL; block = block->next)
417 if (block == pool->blocks)
418 allocated += pool->block_size;
420 allocated += block->used_so_far;
424 if (in_use_p != NULL)
427 if (in_free_list_p != NULL)
428 *in_free_list_p = in_free_list;
430 if (allocated_p != NULL)
431 *allocated_p = allocated;
433 #endif /* DBUS_ENABLE_STATS */
437 #ifdef DBUS_BUILD_TESTS
438 #include "dbus-test.h"
443 time_for_size (int size)
449 #define FREE_ARRAY_SIZE 512
450 #define N_ITERATIONS FREE_ARRAY_SIZE * 512
451 void *to_free[FREE_ARRAY_SIZE];
454 _dbus_verbose ("Timings for size %d\n", size);
456 _dbus_verbose (" malloc\n");
462 while (i < N_ITERATIONS)
464 to_free[j] = dbus_malloc (size);
465 _dbus_assert (to_free[j] != NULL); /* in a real app of course this is wrong */
469 if (j == FREE_ARRAY_SIZE)
472 while (j < FREE_ARRAY_SIZE)
474 dbus_free (to_free[j]);
486 _dbus_verbose (" created/destroyed %d elements in %g seconds\n",
487 N_ITERATIONS, (end - start) / (double) CLOCKS_PER_SEC);
491 _dbus_verbose (" mempools\n");
495 pool = _dbus_mem_pool_new (size, FALSE);
499 while (i < N_ITERATIONS)
501 to_free[j] = _dbus_mem_pool_alloc (pool);
502 _dbus_assert (to_free[j] != NULL); /* in a real app of course this is wrong */
506 if (j == FREE_ARRAY_SIZE)
509 while (j < FREE_ARRAY_SIZE)
511 _dbus_mem_pool_dealloc (pool, to_free[j]);
521 _dbus_mem_pool_free (pool);
525 _dbus_verbose (" created/destroyed %d elements in %g seconds\n",
526 N_ITERATIONS, (end - start) / (double) CLOCKS_PER_SEC);
528 _dbus_verbose (" zeroed malloc\n");
534 while (i < N_ITERATIONS)
536 to_free[j] = dbus_malloc0 (size);
537 _dbus_assert (to_free[j] != NULL); /* in a real app of course this is wrong */
541 if (j == FREE_ARRAY_SIZE)
544 while (j < FREE_ARRAY_SIZE)
546 dbus_free (to_free[j]);
558 _dbus_verbose (" created/destroyed %d elements in %g seconds\n",
559 N_ITERATIONS, (end - start) / (double) CLOCKS_PER_SEC);
561 _dbus_verbose (" zeroed mempools\n");
565 pool = _dbus_mem_pool_new (size, TRUE);
569 while (i < N_ITERATIONS)
571 to_free[j] = _dbus_mem_pool_alloc (pool);
572 _dbus_assert (to_free[j] != NULL); /* in a real app of course this is wrong */
576 if (j == FREE_ARRAY_SIZE)
579 while (j < FREE_ARRAY_SIZE)
581 _dbus_mem_pool_dealloc (pool, to_free[j]);
591 _dbus_mem_pool_free (pool);
595 _dbus_verbose (" created/destroyed %d elements in %g seconds\n",
596 N_ITERATIONS, (end - start) / (double) CLOCKS_PER_SEC);
600 * @ingroup DBusMemPoolInternals
601 * Unit test for DBusMemPool
602 * @returns #TRUE on success.
605 _dbus_mem_pool_test (void)
608 int element_sizes[] = { 4, 8, 16, 50, 124 };
611 while (i < _DBUS_N_ELEMENTS (element_sizes))
613 time_for_size (element_sizes[i]);
620 #endif /* DBUS_BUILD_TESTS */