2003-04-27 Havoc Pennington <hp@pobox.com>
[platform/upstream/dbus.git] / dbus / dbus-mempool.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-mempool.h Memory pools
3  * 
4  * Copyright (C) 2002, 2003  Red Hat, Inc.
5  *
6  * Licensed under the Academic Free License version 1.2
7  * 
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.
12  *
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.
17  * 
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
21  *
22  */
23
24 #include "dbus-mempool.h"
25 #include "dbus-internals.h"
26
27 /**
28  * @defgroup DBusMemPool memory pools
29  * @ingroup  DBusInternals
30  * @brief DBusMemPool object
31  *
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
36  * secondary.
37  */
38
39 /**
40  * @defgroup DBusMemPoolInternals Memory pool implementation details
41  * @ingroup  DBusInternals
42  * @brief DBusMemPool implementation details
43  *
44  * The guts of DBusMemPool.
45  *
46  * @{
47  */
48
49 /**
50  * typedef so DBusFreedElement struct can refer to itself.
51  */
52 typedef struct DBusFreedElement DBusFreedElement;
53
54 /**
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.
58  */
59 struct DBusFreedElement
60 {
61   DBusFreedElement *next; /**< next element of the free list */
62 };
63
64 /**
65  * The dummy size of the variable-length "elements"
66  * field in DBusMemBlock
67  */
68 #define ELEMENT_PADDING 4
69
70 /**
71  * Typedef for DBusMemBlock so the struct can recursively
72  * point to itself.
73  */
74 typedef struct DBusMemBlock DBusMemBlock;
75
76 /**
77  * DBusMemBlock object represents a single malloc()-returned
78  * block that gets chunked up into objects in the memory pool.
79  */
80 struct DBusMemBlock
81 {
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.
85                         */
86
87   /* this is a long so that "elements" is aligned */
88   long used_so_far;     /**< bytes of this block already allocated as elements. */
89   
90   unsigned char elements[ELEMENT_PADDING]; /**< the block data, actually allocated to required size */
91 };
92
93 /**
94  * Internals fields of DBusMemPool
95  */
96 struct DBusMemPool
97 {
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 */
101
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 */
105 };
106
107 /** @} */
108
109 /**
110  * @addtogroup DBusMemPool
111  *
112  * @{
113  */
114
115 /**
116  * @typedef DBusMemPool
117  *
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.
122  */
123
124 /**
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.
130  *
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
134  */
135 DBusMemPool*
136 _dbus_mem_pool_new (int element_size,
137                     dbus_bool_t zero_elements)
138 {
139   DBusMemPool *pool;
140
141   pool = dbus_new0 (DBusMemPool, 1);
142   if (pool == NULL)
143     return NULL;
144
145   /* Make the element size at least 8 bytes. */
146   if (element_size < 8)
147     element_size = 8;
148   
149   /* these assertions are equivalent but the first is more clear
150    * to programmers that see it fail.
151    */
152   _dbus_assert (element_size >= (int) sizeof (void*));
153   _dbus_assert (element_size >= (int) sizeof (DBusFreedElement));
154
155   /* align the element size to a pointer boundary so we won't get bus
156    * errors under other architectures.  
157    */
158   pool->element_size = _DBUS_ALIGN_VALUE (element_size, sizeof (void *));
159
160   pool->zero_elements = zero_elements != FALSE;
161
162   pool->allocated_elements = 0;
163   
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;
170
171   _dbus_assert ((pool->block_size %
172                  pool->element_size) == 0);
173   
174   return pool;
175 }
176
177 /**
178  * Frees a memory pool (and all elements allocated from it).
179  *
180  * @param pool the memory pool.
181  */
182 void
183 _dbus_mem_pool_free (DBusMemPool *pool)
184 {
185   DBusMemBlock *block;
186
187   block = pool->blocks;
188   while (block != NULL)
189     {
190       DBusMemBlock *next = block->next;
191
192       dbus_free (block);
193
194       block = next;
195     }
196
197   dbus_free (pool);
198 }
199
200 /**
201  * Allocates an object from the memory pool.
202  * The object must be freed with _dbus_mem_pool_dealloc().
203  *
204  * @param pool the memory pool
205  * @returns the allocated object or #NULL if no memory.
206  */
207 void*
208 _dbus_mem_pool_alloc (DBusMemPool *pool)
209 {
210   if (_dbus_disable_mem_pools ())
211     {
212       DBusMemBlock *block;
213       int alloc_size;
214       
215       /* This is obviously really silly, but it's
216        * debug-mode-only code that is compiled out
217        * when tests are disabled (_dbus_disable_mem_pools()
218        * is a constant expression FALSE so this block
219        * should vanish)
220        */
221       
222       alloc_size = sizeof (DBusMemBlock) - ELEMENT_PADDING +
223         pool->element_size;
224       
225       if (pool->zero_elements)
226         block = dbus_malloc0 (alloc_size);
227       else
228         block = dbus_malloc (alloc_size);
229
230       if (block != NULL)
231         {
232           block->next = pool->blocks;
233           pool->blocks = block;
234           pool->allocated_elements += 1;
235
236           return (void*) &block->elements[0];
237         }
238       else
239         return NULL;
240     }
241   else
242     {
243       if (_dbus_decrement_fail_alloc_counter ())
244         {
245           _dbus_verbose (" FAILING mempool alloc\n");
246           return NULL;
247         }
248       else if (pool->free_elements)
249         {
250           DBusFreedElement *element = pool->free_elements;
251
252           pool->free_elements = pool->free_elements->next;
253
254           if (pool->zero_elements)
255             memset (element, '\0', pool->element_size);
256
257           pool->allocated_elements += 1;
258           
259           return element;
260         }
261       else
262         {
263           void *element;
264       
265           if (pool->blocks == NULL ||
266               pool->blocks->used_so_far == pool->block_size)
267             {
268               /* Need a new block */
269               DBusMemBlock *block;
270               int alloc_size;
271 #ifdef DBUS_BUILD_TESTS
272               int saved_counter;
273 #endif
274           
275               if (pool->block_size <= _DBUS_INT_MAX / 4) /* avoid overflow */
276                 {
277                   /* use a larger block size for our next block */
278                   pool->block_size *= 2;
279                   _dbus_assert ((pool->block_size %
280                                  pool->element_size) == 0);
281                 }
282
283               alloc_size = sizeof (DBusMemBlock) - ELEMENT_PADDING + pool->block_size;
284
285 #ifdef DBUS_BUILD_TESTS
286               /* We save/restore the counter, so that memory pools won't
287                * cause a given function to have different number of
288                * allocations on different invocations. i.e.  when testing
289                * we want consistent alloc patterns. So we skip our
290                * malloc here for purposes of failed alloc simulation.
291                */
292               saved_counter = _dbus_get_fail_alloc_counter ();
293               _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
294 #endif
295           
296               if (pool->zero_elements)
297                 block = dbus_malloc0 (alloc_size);
298               else
299                 block = dbus_malloc (alloc_size);
300
301 #ifdef DBUS_BUILD_TESTS
302               _dbus_set_fail_alloc_counter (saved_counter);
303               _dbus_assert (saved_counter == _dbus_get_fail_alloc_counter ());
304 #endif
305           
306               if (block == NULL)
307                 return NULL;
308
309               block->used_so_far = 0;
310               block->next = pool->blocks;
311               pool->blocks = block;          
312             }
313       
314           element = &pool->blocks->elements[pool->blocks->used_so_far];
315           
316           pool->blocks->used_so_far += pool->element_size;
317
318           pool->allocated_elements += 1;
319           
320           return element;
321         }
322     }
323 }
324
325 /**
326  * Deallocates an object previously created with
327  * _dbus_mem_pool_alloc(). The previous object
328  * must have come from this same pool.
329  * @param pool the memory pool
330  * @param element the element earlier allocated.
331  * @returns #TRUE if there are no remaining allocated elements
332  */
333 dbus_bool_t
334 _dbus_mem_pool_dealloc (DBusMemPool *pool,
335                         void        *element)
336 {
337   if (_dbus_disable_mem_pools ())
338     {
339       DBusMemBlock *block;
340       DBusMemBlock *prev;
341
342       /* mmm, fast. ;-) debug-only code, so doesn't matter. */
343       
344       prev = NULL;
345       block = pool->blocks;
346
347       while (block != NULL)
348         {
349           if (block->elements == (unsigned char*) element)
350             {
351               if (prev)
352                 prev->next = block->next;
353               else
354                 pool->blocks = block->next;
355               
356               dbus_free (block);
357
358               _dbus_assert (pool->allocated_elements > 0);
359               pool->allocated_elements -= 1;
360               
361               if (pool->allocated_elements == 0)
362                 _dbus_assert (pool->blocks == NULL);
363               
364               return pool->blocks == NULL;
365             }
366           prev = block;
367           block = block->next;
368         }
369       
370       _dbus_assert_not_reached ("freed nonexistent block");
371       return FALSE;
372     }
373   else
374     {
375       DBusFreedElement *freed;
376       
377       freed = element;
378       freed->next = pool->free_elements;
379       pool->free_elements = freed;
380       
381       _dbus_assert (pool->allocated_elements > 0);
382       pool->allocated_elements -= 1;
383       
384       return pool->allocated_elements == 0;
385     }
386 }
387
388 /** @} */
389
390 #ifdef DBUS_BUILD_TESTS
391 #include "dbus-test.h"
392 #include <stdio.h>
393 #include <time.h>
394
395 static void
396 time_for_size (int size)
397 {
398   int i;
399   int j;
400   clock_t start;
401   clock_t end;
402 #define FREE_ARRAY_SIZE 512
403 #define N_ITERATIONS FREE_ARRAY_SIZE * 512
404   void *to_free[FREE_ARRAY_SIZE];
405   DBusMemPool *pool;
406
407   _dbus_verbose ("Timings for size %d\n", size);
408   
409   _dbus_verbose (" malloc\n");
410   
411   start = clock ();
412   
413   i = 0;
414   j = 0;
415   while (i < N_ITERATIONS)
416     {
417       to_free[j] = dbus_malloc (size);
418       _dbus_assert (to_free[j] != NULL); /* in a real app of course this is wrong */
419
420       ++j;
421
422       if (j == FREE_ARRAY_SIZE)
423         {
424           j = 0;
425           while (j < FREE_ARRAY_SIZE)
426             {
427               dbus_free (to_free[j]);
428               ++j;
429             }
430
431           j = 0;
432         }
433       
434       ++i;
435     }
436
437   end = clock ();
438
439   _dbus_verbose ("  created/destroyed %d elements in %g seconds\n",
440                  N_ITERATIONS, (end - start) / (double) CLOCKS_PER_SEC);
441
442
443
444   _dbus_verbose (" mempools\n");
445   
446   start = clock ();
447
448   pool = _dbus_mem_pool_new (size, FALSE);
449   
450   i = 0;
451   j = 0;
452   while (i < N_ITERATIONS)
453     {
454       to_free[j] = _dbus_mem_pool_alloc (pool); 
455       _dbus_assert (to_free[j] != NULL);  /* in a real app of course this is wrong */
456
457       ++j;
458
459       if (j == FREE_ARRAY_SIZE)
460         {
461           j = 0;
462           while (j < FREE_ARRAY_SIZE)
463             {
464               _dbus_mem_pool_dealloc (pool, to_free[j]);
465               ++j;
466             }
467
468           j = 0;
469         }
470       
471       ++i;
472     }
473
474   _dbus_mem_pool_free (pool);
475   
476   end = clock ();
477
478   _dbus_verbose ("  created/destroyed %d elements in %g seconds\n",
479                  N_ITERATIONS, (end - start) / (double) CLOCKS_PER_SEC);
480
481   _dbus_verbose (" zeroed malloc\n");
482     
483   start = clock ();
484   
485   i = 0;
486   j = 0;
487   while (i < N_ITERATIONS)
488     {
489       to_free[j] = dbus_malloc0 (size);
490       _dbus_assert (to_free[j] != NULL); /* in a real app of course this is wrong */
491
492       ++j;
493
494       if (j == FREE_ARRAY_SIZE)
495         {
496           j = 0;
497           while (j < FREE_ARRAY_SIZE)
498             {
499               dbus_free (to_free[j]);
500               ++j;
501             }
502
503           j = 0;
504         }
505       
506       ++i;
507     }
508
509   end = clock ();
510
511   _dbus_verbose ("  created/destroyed %d elements in %g seconds\n",
512                  N_ITERATIONS, (end - start) / (double) CLOCKS_PER_SEC);
513   
514   _dbus_verbose (" zeroed mempools\n");
515   
516   start = clock ();
517
518   pool = _dbus_mem_pool_new (size, TRUE);
519   
520   i = 0;
521   j = 0;
522   while (i < N_ITERATIONS)
523     {
524       to_free[j] = _dbus_mem_pool_alloc (pool); 
525       _dbus_assert (to_free[j] != NULL);  /* in a real app of course this is wrong */
526
527       ++j;
528
529       if (j == FREE_ARRAY_SIZE)
530         {
531           j = 0;
532           while (j < FREE_ARRAY_SIZE)
533             {
534               _dbus_mem_pool_dealloc (pool, to_free[j]);
535               ++j;
536             }
537
538           j = 0;
539         }
540       
541       ++i;
542     }
543
544   _dbus_mem_pool_free (pool);
545   
546   end = clock ();
547
548   _dbus_verbose ("  created/destroyed %d elements in %g seconds\n",
549                  N_ITERATIONS, (end - start) / (double) CLOCKS_PER_SEC);
550 }
551
552 /**
553  * @ingroup DBusMemPoolInternals
554  * Unit test for DBusMemPool
555  * @returns #TRUE on success.
556  */
557 dbus_bool_t
558 _dbus_mem_pool_test (void)
559 {
560   int i;
561   int element_sizes[] = { 4, 8, 16, 50, 124 };
562   
563   i = 0;
564   while (i < _DBUS_N_ELEMENTS (element_sizes))
565     {
566       time_for_size (element_sizes[i]);
567       ++i;
568     }
569   
570   return TRUE;
571 }
572
573 #endif /* DBUS_BUILD_TESTS */