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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include "dbus-mempool.h"
25 #include "dbus-internals.h"
28 * @defgroup DBusMemPool memory pools
29 * @ingroup DBusInternals
30 * @brief DBusMemPool object
32 * Types and functions related to DBusMemPool. A memory pool is used
33 * to decrease memory fragmentation/overhead and increase speed for
34 * blocks of small uniformly-sized objects. The main point is to avoid
35 * the overhead of a malloc block for each small object, speed is
40 * @defgroup DBusMemPoolInternals Memory pool implementation details
41 * @ingroup DBusInternals
42 * @brief DBusMemPool implementation details
44 * The guts of DBusMemPool.
50 * typedef so DBusFreedElement struct can refer to itself.
52 typedef struct DBusFreedElement DBusFreedElement;
55 * struct representing an element on the free list.
56 * We just cast freed elements to this so we can
57 * make a list out of them.
59 struct DBusFreedElement
61 DBusFreedElement *next; /**< next element of the free list */
65 * The dummy size of the variable-length "elements"
66 * field in DBusMemBlock
68 #define ELEMENT_PADDING 4
71 * Typedef for DBusMemBlock so the struct can recursively
74 typedef struct DBusMemBlock DBusMemBlock;
77 * DBusMemBlock object represents a single malloc()-returned
78 * block that gets chunked up into objects in the memory pool.
82 DBusMemBlock *next; /**< next block in the list, which is already used up;
83 * only saved so we can free all the blocks
84 * when we free the mem pool.
87 /* this is a long so that "elements" is aligned */
88 long used_so_far; /**< bytes of this block already allocated as elements. */
90 unsigned char elements[ELEMENT_PADDING]; /**< the block data, actually allocated to required size */
94 * Internals fields of DBusMemPool
98 int element_size; /**< size of a single object in the pool */
99 int block_size; /**< size of most recently allocated block */
100 unsigned int zero_elements : 1; /**< whether to zero-init allocated elements */
102 DBusFreedElement *free_elements; /**< a free list of elements to recycle */
103 DBusMemBlock *blocks; /**< blocks of memory from malloc() */
104 int allocated_elements; /**< Count of outstanding allocated elements */
110 * @addtogroup DBusMemPool
116 * @typedef DBusMemPool
118 * Opaque object representing a memory pool. Memory pools allow
119 * avoiding per-malloc-block memory overhead when allocating a lot of
120 * small objects that are all the same size. They are slightly
121 * faster than calling malloc() also.
125 * Creates a new memory pool, or returns #NULL on failure. Objects in
126 * the pool must be at least sizeof(void*) bytes each, due to the way
127 * memory pools work. To avoid creating 64 bit problems, this means at
128 * least 8 bytes on all platforms, unless you are 4 bytes on 32-bit
129 * and 8 bytes on 64-bit.
131 * @param element_size size of an element allocated from the pool.
132 * @param zero_elements whether to zero-initialize elements
133 * @returns the new pool or #NULL
136 _dbus_mem_pool_new (int element_size,
137 dbus_bool_t zero_elements)
141 pool = dbus_new0 (DBusMemPool, 1);
145 /* Make the element size at least 8 bytes. */
146 if (element_size < 8)
149 /* these assertions are equivalent but the first is more clear
150 * to programmers that see it fail.
152 _dbus_assert (element_size >= (int) sizeof (void*));
153 _dbus_assert (element_size >= (int) sizeof (DBusFreedElement));
155 /* align the element size to a pointer boundary so we won't get bus
156 * errors under other architectures.
158 pool->element_size = _DBUS_ALIGN_VALUE (element_size, sizeof (void *));
160 pool->zero_elements = zero_elements != FALSE;
162 pool->allocated_elements = 0;
164 /* pick a size for the first block; it increases
165 * for each block we need to allocate. This is
166 * actually half the initial block size
167 * since _dbus_mem_pool_alloc() unconditionally
168 * doubles it prior to creating a new block. */
169 pool->block_size = pool->element_size * 8;
171 _dbus_assert ((pool->block_size %
172 pool->element_size) == 0);
178 * Frees a memory pool (and all elements allocated from it).
180 * @param pool the memory pool.
183 _dbus_mem_pool_free (DBusMemPool *pool)
187 block = pool->blocks;
188 while (block != NULL)
190 DBusMemBlock *next = block->next;
201 * Allocates an object from the memory pool.
202 * The object must be freed with _dbus_mem_pool_dealloc().
204 * @param pool the memory pool
205 * @returns the allocated object or #NULL if no memory.
208 _dbus_mem_pool_alloc (DBusMemPool *pool)
210 #ifdef DBUS_BUILD_TESTS
211 if (_dbus_disable_mem_pools ())
216 /* This is obviously really silly, but it's
217 * debug-mode-only code that is compiled out
218 * when tests are disabled (_dbus_disable_mem_pools()
219 * is a constant expression FALSE so this block
223 alloc_size = sizeof (DBusMemBlock) - ELEMENT_PADDING +
226 if (pool->zero_elements)
227 block = dbus_malloc0 (alloc_size);
229 block = dbus_malloc (alloc_size);
233 block->next = pool->blocks;
234 pool->blocks = block;
235 pool->allocated_elements += 1;
237 return (void*) &block->elements[0];
245 if (_dbus_decrement_fail_alloc_counter ())
247 _dbus_verbose (" FAILING mempool alloc\n");
250 else if (pool->free_elements)
252 DBusFreedElement *element = pool->free_elements;
254 pool->free_elements = pool->free_elements->next;
256 if (pool->zero_elements)
257 memset (element, '\0', pool->element_size);
259 pool->allocated_elements += 1;
267 if (pool->blocks == NULL ||
268 pool->blocks->used_so_far == pool->block_size)
270 /* Need a new block */
273 #ifdef DBUS_BUILD_TESTS
277 if (pool->block_size <= _DBUS_INT_MAX / 4) /* avoid overflow */
279 /* use a larger block size for our next block */
280 pool->block_size *= 2;
281 _dbus_assert ((pool->block_size %
282 pool->element_size) == 0);
285 alloc_size = sizeof (DBusMemBlock) - ELEMENT_PADDING + pool->block_size;
287 #ifdef DBUS_BUILD_TESTS
288 /* We save/restore the counter, so that memory pools won't
289 * cause a given function to have different number of
290 * allocations on different invocations. i.e. when testing
291 * we want consistent alloc patterns. So we skip our
292 * malloc here for purposes of failed alloc simulation.
294 saved_counter = _dbus_get_fail_alloc_counter ();
295 _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
298 if (pool->zero_elements)
299 block = dbus_malloc0 (alloc_size);
301 block = dbus_malloc (alloc_size);
303 #ifdef DBUS_BUILD_TESTS
304 _dbus_set_fail_alloc_counter (saved_counter);
305 _dbus_assert (saved_counter == _dbus_get_fail_alloc_counter ());
311 block->used_so_far = 0;
312 block->next = pool->blocks;
313 pool->blocks = block;
316 element = &pool->blocks->elements[pool->blocks->used_so_far];
318 pool->blocks->used_so_far += pool->element_size;
320 pool->allocated_elements += 1;
328 * Deallocates an object previously created with
329 * _dbus_mem_pool_alloc(). The previous object
330 * must have come from this same pool.
331 * @param pool the memory pool
332 * @param element the element earlier allocated.
333 * @returns #TRUE if there are no remaining allocated elements
336 _dbus_mem_pool_dealloc (DBusMemPool *pool,
339 #ifdef DBUS_BUILD_TESTS
340 if (_dbus_disable_mem_pools ())
345 /* mmm, fast. ;-) debug-only code, so doesn't matter. */
348 block = pool->blocks;
350 while (block != NULL)
352 if (block->elements == (unsigned char*) element)
355 prev->next = block->next;
357 pool->blocks = block->next;
361 _dbus_assert (pool->allocated_elements > 0);
362 pool->allocated_elements -= 1;
364 if (pool->allocated_elements == 0)
365 _dbus_assert (pool->blocks == NULL);
367 return pool->blocks == NULL;
373 _dbus_assert_not_reached ("freed nonexistent block");
379 DBusFreedElement *freed;
382 freed->next = pool->free_elements;
383 pool->free_elements = freed;
385 _dbus_assert (pool->allocated_elements > 0);
386 pool->allocated_elements -= 1;
388 return pool->allocated_elements == 0;
394 #ifdef DBUS_BUILD_TESTS
395 #include "dbus-test.h"
400 time_for_size (int size)
406 #define FREE_ARRAY_SIZE 512
407 #define N_ITERATIONS FREE_ARRAY_SIZE * 512
408 void *to_free[FREE_ARRAY_SIZE];
411 _dbus_verbose ("Timings for size %d\n", size);
413 _dbus_verbose (" malloc\n");
419 while (i < N_ITERATIONS)
421 to_free[j] = dbus_malloc (size);
422 _dbus_assert (to_free[j] != NULL); /* in a real app of course this is wrong */
426 if (j == FREE_ARRAY_SIZE)
429 while (j < FREE_ARRAY_SIZE)
431 dbus_free (to_free[j]);
443 _dbus_verbose (" created/destroyed %d elements in %g seconds\n",
444 N_ITERATIONS, (end - start) / (double) CLOCKS_PER_SEC);
448 _dbus_verbose (" mempools\n");
452 pool = _dbus_mem_pool_new (size, FALSE);
456 while (i < N_ITERATIONS)
458 to_free[j] = _dbus_mem_pool_alloc (pool);
459 _dbus_assert (to_free[j] != NULL); /* in a real app of course this is wrong */
463 if (j == FREE_ARRAY_SIZE)
466 while (j < FREE_ARRAY_SIZE)
468 _dbus_mem_pool_dealloc (pool, to_free[j]);
478 _dbus_mem_pool_free (pool);
482 _dbus_verbose (" created/destroyed %d elements in %g seconds\n",
483 N_ITERATIONS, (end - start) / (double) CLOCKS_PER_SEC);
485 _dbus_verbose (" zeroed malloc\n");
491 while (i < N_ITERATIONS)
493 to_free[j] = dbus_malloc0 (size);
494 _dbus_assert (to_free[j] != NULL); /* in a real app of course this is wrong */
498 if (j == FREE_ARRAY_SIZE)
501 while (j < FREE_ARRAY_SIZE)
503 dbus_free (to_free[j]);
515 _dbus_verbose (" created/destroyed %d elements in %g seconds\n",
516 N_ITERATIONS, (end - start) / (double) CLOCKS_PER_SEC);
518 _dbus_verbose (" zeroed mempools\n");
522 pool = _dbus_mem_pool_new (size, TRUE);
526 while (i < N_ITERATIONS)
528 to_free[j] = _dbus_mem_pool_alloc (pool);
529 _dbus_assert (to_free[j] != NULL); /* in a real app of course this is wrong */
533 if (j == FREE_ARRAY_SIZE)
536 while (j < FREE_ARRAY_SIZE)
538 _dbus_mem_pool_dealloc (pool, to_free[j]);
548 _dbus_mem_pool_free (pool);
552 _dbus_verbose (" created/destroyed %d elements in %g seconds\n",
553 N_ITERATIONS, (end - start) / (double) CLOCKS_PER_SEC);
557 * @ingroup DBusMemPoolInternals
558 * Unit test for DBusMemPool
559 * @returns #TRUE on success.
562 _dbus_mem_pool_test (void)
565 int element_sizes[] = { 4, 8, 16, 50, 124 };
568 while (i < _DBUS_N_ELEMENTS (element_sizes))
570 time_for_size (element_sizes[i]);
577 #endif /* DBUS_BUILD_TESTS */