summaryrefslogtreecommitdiffstats
path: root/dbus/dbus-mempool.c
blob: 05e3749be8f6ce918266d55f3881bd1edb2d908b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
/* -*- mode: C; c-file-style: "gnu" -*- */
/* dbus-mempool.h Memory pools
 * 
 * Copyright (C) 2002  Red Hat, Inc.
 *
 * Licensed under the Academic Free License version 1.2
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

#include "dbus-mempool.h"

/**
 * @defgroup DBusMemPool memory pools
 * @ingroup  DBusInternals
 * @brief DBusMemPool object
 *
 * Types and functions related to DBusMemPool.  A memory pool is used
 * to decrease memory fragmentation/overhead and increase speed for
 * blocks of small uniformly-sized objects. The main point is to avoid
 * the overhead of a malloc block for each small object, speed is
 * secondary.
 */

/**
 * @defgroup DBusMemPoolInternals Memory pool implementation details
 * @ingroup  DBusInternals
 * @brief DBusMemPool implementation details
 *
 * The guts of DBusMemPool.
 *
 * @{
 */

/**
 * typedef so DBusFreedElement struct can refer to itself.
 */
typedef struct DBusFreedElement DBusFreedElement;

/**
 * struct representing an element on the free list.
 * We just cast freed elements to this so we can
 * make a list out of them.
 */
struct DBusFreedElement
{
  DBusFreedElement *next; /**< next element of the free list */
};

/**
 * The dummy size of the variable-length "elements"
 * field in DBusMemBlock
 */
#define ELEMENT_PADDING 4

/**
 * Typedef for DBusMemBlock so the struct can recursively
 * point to itself.
 */
typedef struct DBusMemBlock DBusMemBlock;

/**
 * DBusMemBlock object represents a single malloc()-returned
 * block that gets chunked up into objects in the memory pool.
 */
struct DBusMemBlock
{
  DBusMemBlock *next;  /**< next block in the list, which is already used up;
                        *   only saved so we can free all the blocks
                        *   when we free the mem pool.
                        */

  int used_so_far;     /**< bytes of this block already allocated as elements. */
  
  unsigned char elements[ELEMENT_PADDING]; /**< the block data, actually allocated to required size */
};

/**
 * Internals fields of DBusMemPool
 */
struct DBusMemPool
{
  int element_size;                /**< size of a single object in the pool */
  int block_size;                  /**< size of most recently allocated block */
  unsigned int zero_elements : 1;  /**< whether to zero-init allocated elements */

  DBusFreedElement *free_elements; /**< a free list of elements to recycle */
  DBusMemBlock *blocks;            /**< blocks of memory from malloc() */
};

/** @} */

/**
 * @addtogroup DBusMemPool
 *
 * @{
 */

/**
 * @typedef DBusMemPool
 *
 * Opaque object representing a memory pool. Memory pools allow
 * avoiding per-malloc-block memory overhead when allocating a lot of
 * small objects that are all the same size. They are slightly
 * faster than calling malloc() also.
 */

/**
 * Creates a new memory pool, or returns #NULL on failure.  Objects in
 * the pool must be at least sizeof(void*) bytes each, due to the way
 * memory pools work. To avoid creating 64 bit problems, this means at
 * least 8 bytes on all platforms, unless you are 4 bytes on 32-bit
 * and 8 bytes on 64-bit.
 *
 * @param element_size size of an element allocated from the pool.
 * @param zero_elements whether to zero-initialize elements
 * @returns the new pool or #NULL
 */
DBusMemPool*
_dbus_mem_pool_new (int element_size,
                    dbus_bool_t zero_elements)
{
  DBusMemPool *pool;

  pool = dbus_new0 (DBusMemPool, 1);
  if (pool == NULL)
    return NULL;

  /* these assertions are equivalent but the first is more clear
   * to programmers that see it fail.
   */
  _dbus_assert (element_size >= (int) sizeof (void*));
  _dbus_assert (element_size >= (int) sizeof (DBusFreedElement));
  
  pool->element_size = element_size;
  pool->zero_elements = zero_elements != FALSE;

  /* pick a size for the first block; it increases
   * for each block we need to allocate. This is
   * actually half the initial block size
   * since _dbus_mem_pool_alloc() unconditionally
   * doubles it prior to creating a new block.
   */
  pool->block_size = element_size * 8;

  _dbus_assert ((pool->block_size %
                 pool->element_size) == 0);
  
  return pool;
}

/**
 * Frees a memory pool (and all elements allocated from it).
 *
 * @param pool the memory pool.
 */
void
_dbus_mem_pool_free (DBusMemPool *pool)
{
  DBusMemBlock *block;

  block = pool->blocks;
  while (block != NULL)
    {
      DBusMemBlock *next = block->next;

      dbus_free (block);

      block = next;
    }

  dbus_free (pool);
}

/**
 * Allocates an object from the memory pool.
 * The object must be freed with _dbus_mem_pool_dealloc().
 *
 * @param pool the memory pool
 * @returns the allocated object or #NULL if no memory.
 */
void*
_dbus_mem_pool_alloc (DBusMemPool *pool)
{
  if (pool->free_elements)
    {
      DBusFreedElement *element = pool->free_elements;

      pool->free_elements = pool->free_elements->next;

      if (pool->zero_elements)
        memset (element, '\0', pool->element_size);
      
      return element;
    }
  else
    {
      void *element;
      
      if (pool->blocks == NULL ||
          pool->blocks->used_so_far == pool->block_size)
        {
          /* Need a new block */
          DBusMemBlock *block;
          int alloc_size;

          if (pool->block_size <= _DBUS_INT_MAX / 4) /* avoid overflow */
            {
              /* use a larger block size for our next block */
              pool->block_size *= 2;
              _dbus_assert ((pool->block_size %
                             pool->element_size) == 0);
            }

          alloc_size = sizeof (DBusMemBlock) - ELEMENT_PADDING + pool->block_size;
          
          if (pool->zero_elements)
            block = dbus_malloc0 (alloc_size);
          else
            block = dbus_malloc (alloc_size);

          if (block == NULL)
            return NULL;

          block->used_so_far = 0;
          block->next = pool->blocks;
          pool->blocks = block;
        }
      
      element = &pool->blocks->elements[pool->blocks->used_so_far];

      pool->blocks->used_so_far += pool->element_size;

      return element;
    }
}

/**
 * Deallocates an object previously created with
 * _dbus_mem_pool_alloc(). The previous object
 * must have come from this same pool.
 * @param pool the memory pool
 * @param element the element earlier allocated.
 */
void
_dbus_mem_pool_dealloc (DBusMemPool *pool,
                        void        *element)
{
  DBusFreedElement *freed;

  freed = element;
  freed->next = pool->free_elements;
  pool->free_elements = freed;
}

/** @} */

#ifdef DBUS_BUILD_TESTS
#include "dbus-test.h"
#include <stdio.h>
#include <time.h>

static void
time_for_size (int size)
{
  int i;
  int j;
  clock_t start;
  clock_t end;
#define FREE_ARRAY_SIZE 512
#define N_ITERATIONS FREE_ARRAY_SIZE * 512
  void *to_free[FREE_ARRAY_SIZE];
  DBusMemPool *pool;

  _dbus_verbose ("Timings for size %d\n", size);
  
  _dbus_verbose (" malloc\n");
  
  start = clock ();
  
  i = 0;
  j = 0;
  while (i < N_ITERATIONS)
    {
      to_free[j] = dbus_malloc (size);
      _dbus_assert (to_free[j] != NULL); /* in a real app of course this is wrong */

      ++j;

      if (j == FREE_ARRAY_SIZE)
        {
          j = 0;
          while (j < FREE_ARRAY_SIZE)
            {
              dbus_free (to_free[j]);
              ++j;
            }

          j = 0;
        }
      
      ++i;
    }

  end = clock ();

  _dbus_verbose ("  created/destroyed %d elements in %g seconds\n",
                 N_ITERATIONS, (end - start) / (double) CLOCKS_PER_SEC);



  _dbus_verbose (" mempools\n");
  
  start = clock ();

  pool = _dbus_mem_pool_new (size, FALSE);
  
  i = 0;
  j = 0;
  while (i < N_ITERATIONS)
    {
      to_free[j] = _dbus_mem_pool_alloc (pool); 
      _dbus_assert (to_free[j] != NULL);  /* in a real app of course this is wrong */

      ++j;

      if (j == FREE_ARRAY_SIZE)
        {
          j = 0;
          while (j < FREE_ARRAY_SIZE)
            {
              _dbus_mem_pool_dealloc (pool, to_free[j]);
              ++j;
            }

          j = 0;
        }
      
      ++i;
    }

  _dbus_mem_pool_free (pool);
  
  end = clock ();

  _dbus_verbose ("  created/destroyed %d elements in %g seconds\n",
                 N_ITERATIONS, (end - start) / (double) CLOCKS_PER_SEC);

  _dbus_verbose (" zeroed malloc\n");
    
  start = clock ();
  
  i = 0;
  j = 0;
  while (i < N_ITERATIONS)
    {
      to_free[j] = dbus_malloc0 (size);
      _dbus_assert (to_free[j] != NULL); /* in a real app of course this is wrong */

      ++j;

      if (j == FREE_ARRAY_SIZE)
        {
          j = 0;
          while (j < FREE_ARRAY_SIZE)
            {
              dbus_free (to_free[j]);
              ++j;
            }

          j = 0;
        }
      
      ++i;
    }

  end = clock ();

  _dbus_verbose ("  created/destroyed %d elements in %g seconds\n",
                 N_ITERATIONS, (end - start) / (double) CLOCKS_PER_SEC);
  
  _dbus_verbose (" zeroed mempools\n");
  
  start = clock ();

  pool = _dbus_mem_pool_new (size, TRUE);
  
  i = 0;
  j = 0;
  while (i < N_ITERATIONS)
    {
      to_free[j] = _dbus_mem_pool_alloc (pool); 
      _dbus_assert (to_free[j] != NULL);  /* in a real app of course this is wrong */

      ++j;

      if (j == FREE_ARRAY_SIZE)
        {
          j = 0;
          while (j < FREE_ARRAY_SIZE)
            {
              _dbus_mem_pool_dealloc (pool, to_free[j]);
              ++j;
            }

          j = 0;
        }
      
      ++i;
    }

  _dbus_mem_pool_free (pool);
  
  end = clock ();

  _dbus_verbose ("  created/destroyed %d elements in %g seconds\n",
                 N_ITERATIONS, (end - start) / (double) CLOCKS_PER_SEC);
}

/**
 * @ingroup DBusMemPoolInternals
 * Unit test for DBusMemPool
 * @returns #TRUE on success.
 */
dbus_bool_t
_dbus_mem_pool_test (void)
{
  int i;
  int element_sizes[] = { 4, 8, 16, 50, 124 };
  
  i = 0;
  while (i < _DBUS_N_ELEMENTS (element_sizes))
    {
      time_for_size (element_sizes[i]);
      ++i;
    }
  
  return TRUE;
}

#endif /* DBUS_BUILD_TESTS */