Set up test environment properly
[platform/upstream/glib.git] / glib / gslice.c
1 /* GLIB sliced memory - fast concurrent memory chunk allocator
2  * Copyright (C) 2005 Tim Janik
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19 /* MT safe */
20
21 #include "config.h"
22 #include "glibconfig.h"
23
24 #if     defined HAVE_POSIX_MEMALIGN && defined POSIX_MEMALIGN_WITH_COMPLIANT_ALLOCS
25 #  define HAVE_COMPLIANT_POSIX_MEMALIGN 1
26 #endif
27
28 #if defined(HAVE_COMPLIANT_POSIX_MEMALIGN) && !defined(_XOPEN_SOURCE)
29 #define _XOPEN_SOURCE 600       /* posix_memalign() */
30 #endif
31 #include <stdlib.h>             /* posix_memalign() */
32 #include <string.h>
33 #include <errno.h>
34
35 #ifdef HAVE_UNISTD_H
36 #include <unistd.h>             /* sysconf() */
37 #endif
38 #ifdef G_OS_WIN32
39 #include <windows.h>
40 #include <process.h>
41 #endif
42
43 #include <stdio.h>              /* fputs/fprintf */
44
45 #include "gslice.h"
46
47 #include "gmain.h"
48 #include "gmem.h"               /* gslice.h */
49 #include "gstrfuncs.h"
50 #include "gutils.h"
51 #include "gtrashstack.h"
52 #include "gtestutils.h"
53 #include "gthread.h"
54 #include "glib_trace.h"
55
56 #include "valgrind.h"
57
58 /**
59  * SECTION:memory_slices
60  * @title: Memory Slices
61  * @short_description: efficient way to allocate groups of equal-sized
62  *     chunks of memory
63  *
64  * Memory slices provide a space-efficient and multi-processing scalable
65  * way to allocate equal-sized pieces of memory, just like the original
66  * #GMemChunks (from GLib 2.8), while avoiding their excessive
67  * memory-waste, scalability and performance problems.
68  *
69  * To achieve these goals, the slice allocator uses a sophisticated,
70  * layered design that has been inspired by Bonwick's slab allocator
71  * <footnote><para>
72  * <ulink url="http://citeseer.ist.psu.edu/bonwick94slab.html">[Bonwick94]</ulink> Jeff Bonwick, The slab allocator: An object-caching kernel
73  * memory allocator. USENIX 1994, and
74  * <ulink url="http://citeseer.ist.psu.edu/bonwick01magazines.html">[Bonwick01]</ulink> Bonwick and Jonathan Adams, Magazines and vmem: Extending the
75  * slab allocator to many cpu's and arbitrary resources. USENIX 2001
76  * </para></footnote>.
77  * It uses posix_memalign() to optimize allocations of many equally-sized
78  * chunks, and has per-thread free lists (the so-called magazine layer)
79  * to quickly satisfy allocation requests of already known structure sizes.
80  * This is accompanied by extra caching logic to keep freed memory around
81  * for some time before returning it to the system. Memory that is unused
82  * due to alignment constraints is used for cache colorization (random
83  * distribution of chunk addresses) to improve CPU cache utilization. The
84  * caching layer of the slice allocator adapts itself to high lock contention
85  * to improve scalability.
86  *
87  * The slice allocator can allocate blocks as small as two pointers, and
88  * unlike malloc(), it does not reserve extra space per block. For large block
89  * sizes, g_slice_new() and g_slice_alloc() will automatically delegate to the
90  * system malloc() implementation. For newly written code it is recommended
91  * to use the new <literal>g_slice</literal> API instead of g_malloc() and
92  * friends, as long as objects are not resized during their lifetime and the
93  * object size used at allocation time is still available when freeing.
94  *
95  * <example>
96  * <title>Using the slice allocator</title>
97  * <programlisting>
98  * gchar *mem[10000];
99  * gint i;
100  *
101  * /&ast; Allocate 10000 blocks. &ast;/
102  * for (i = 0; i &lt; 10000; i++)
103  *   {
104  *     mem[i] = g_slice_alloc (50);
105  *
106  *     /&ast; Fill in the memory with some junk. &ast;/
107  *     for (j = 0; j &lt; 50; j++)
108  *       mem[i][j] = i * j;
109  *   }
110  *
111  * /&ast; Now free all of the blocks. &ast;/
112  * for (i = 0; i &lt; 10000; i++)
113  *   {
114  *     g_slice_free1 (50, mem[i]);
115  *   }
116  * </programlisting></example>
117  *
118  * <example>
119  * <title>Using the slice allocator with data structures</title>
120  * <programlisting>
121  * GRealArray *array;
122  *
123  * /&ast; Allocate one block, using the g_slice_new() macro. &ast;/
124  * array = g_slice_new (GRealArray);
125
126  * /&ast; We can now use array just like a normal pointer to a structure. &ast;/
127  * array->data            = NULL;
128  * array->len             = 0;
129  * array->alloc           = 0;
130  * array->zero_terminated = (zero_terminated ? 1 : 0);
131  * array->clear           = (clear ? 1 : 0);
132  * array->elt_size        = elt_size;
133  *
134  * /&ast; We can free the block, so it can be reused. &ast;/
135  * g_slice_free (GRealArray, array);
136  * </programlisting></example>
137  */
138
139 /* the GSlice allocator is split up into 4 layers, roughly modelled after the slab
140  * allocator and magazine extensions as outlined in:
141  * + [Bonwick94] Jeff Bonwick, The slab allocator: An object-caching kernel
142  *   memory allocator. USENIX 1994, http://citeseer.ist.psu.edu/bonwick94slab.html
143  * + [Bonwick01] Bonwick and Jonathan Adams, Magazines and vmem: Extending the
144  *   slab allocator to many cpu's and arbitrary resources.
145  *   USENIX 2001, http://citeseer.ist.psu.edu/bonwick01magazines.html
146  * the layers are:
147  * - the thread magazines. for each (aligned) chunk size, a magazine (a list)
148  *   of recently freed and soon to be allocated chunks is maintained per thread.
149  *   this way, most alloc/free requests can be quickly satisfied from per-thread
150  *   free lists which only require one g_private_get() call to retrive the
151  *   thread handle.
152  * - the magazine cache. allocating and freeing chunks to/from threads only
153  *   occours at magazine sizes from a global depot of magazines. the depot
154  *   maintaines a 15 second working set of allocated magazines, so full
155  *   magazines are not allocated and released too often.
156  *   the chunk size dependent magazine sizes automatically adapt (within limits,
157  *   see [3]) to lock contention to properly scale performance across a variety
158  *   of SMP systems.
159  * - the slab allocator. this allocator allocates slabs (blocks of memory) close
160  *   to the system page size or multiples thereof which have to be page aligned.
161  *   the blocks are divided into smaller chunks which are used to satisfy
162  *   allocations from the upper layers. the space provided by the reminder of
163  *   the chunk size division is used for cache colorization (random distribution
164  *   of chunk addresses) to improve processor cache utilization. multiple slabs
165  *   with the same chunk size are kept in a partially sorted ring to allow O(1)
166  *   freeing and allocation of chunks (as long as the allocation of an entirely
167  *   new slab can be avoided).
168  * - the page allocator. on most modern systems, posix_memalign(3) or
169  *   memalign(3) should be available, so this is used to allocate blocks with
170  *   system page size based alignments and sizes or multiples thereof.
171  *   if no memalign variant is provided, valloc() is used instead and
172  *   block sizes are limited to the system page size (no multiples thereof).
173  *   as a fallback, on system without even valloc(), a malloc(3)-based page
174  *   allocator with alloc-only behaviour is used.
175  *
176  * NOTES:
177  * [1] some systems memalign(3) implementations may rely on boundary tagging for
178  *     the handed out memory chunks. to avoid excessive page-wise fragmentation,
179  *     we reserve 2 * sizeof (void*) per block size for the systems memalign(3),
180  *     specified in NATIVE_MALLOC_PADDING.
181  * [2] using the slab allocator alone already provides for a fast and efficient
182  *     allocator, it doesn't properly scale beyond single-threaded uses though.
183  *     also, the slab allocator implements eager free(3)-ing, i.e. does not
184  *     provide any form of caching or working set maintenance. so if used alone,
185  *     it's vulnerable to trashing for sequences of balanced (alloc, free) pairs
186  *     at certain thresholds.
187  * [3] magazine sizes are bound by an implementation specific minimum size and
188  *     a chunk size specific maximum to limit magazine storage sizes to roughly
189  *     16KB.
190  * [4] allocating ca. 8 chunks per block/page keeps a good balance between
191  *     external and internal fragmentation (<= 12.5%). [Bonwick94]
192  */
193
194 /* --- macros and constants --- */
195 #define LARGEALIGNMENT          (256)
196 #define P2ALIGNMENT             (2 * sizeof (gsize))                            /* fits 2 pointers (assumed to be 2 * GLIB_SIZEOF_SIZE_T below) */
197 #define ALIGN(size, base)       ((base) * (gsize) (((size) + (base) - 1) / (base)))
198 #define NATIVE_MALLOC_PADDING   P2ALIGNMENT                                     /* per-page padding left for native malloc(3) see [1] */
199 #define SLAB_INFO_SIZE          P2ALIGN (sizeof (SlabInfo) + NATIVE_MALLOC_PADDING)
200 #define MAX_MAGAZINE_SIZE       (256)                                           /* see [3] and allocator_get_magazine_threshold() for this */
201 #define MIN_MAGAZINE_SIZE       (4)
202 #define MAX_STAMP_COUNTER       (7)                                             /* distributes the load of gettimeofday() */
203 #define MAX_SLAB_CHUNK_SIZE(al) (((al)->max_page_size - SLAB_INFO_SIZE) / 8)    /* we want at last 8 chunks per page, see [4] */
204 #define MAX_SLAB_INDEX(al)      (SLAB_INDEX (al, MAX_SLAB_CHUNK_SIZE (al)) + 1)
205 #define SLAB_INDEX(al, asize)   ((asize) / P2ALIGNMENT - 1)                     /* asize must be P2ALIGNMENT aligned */
206 #define SLAB_CHUNK_SIZE(al, ix) (((ix) + 1) * P2ALIGNMENT)
207 #define SLAB_BPAGE_SIZE(al,csz) (8 * (csz) + SLAB_INFO_SIZE)
208
209 /* optimized version of ALIGN (size, P2ALIGNMENT) */
210 #if     GLIB_SIZEOF_SIZE_T * 2 == 8  /* P2ALIGNMENT */
211 #define P2ALIGN(size)   (((size) + 0x7) & ~(gsize) 0x7)
212 #elif   GLIB_SIZEOF_SIZE_T * 2 == 16 /* P2ALIGNMENT */
213 #define P2ALIGN(size)   (((size) + 0xf) & ~(gsize) 0xf)
214 #else
215 #define P2ALIGN(size)   ALIGN (size, P2ALIGNMENT)
216 #endif
217
218 /* special helpers to avoid gmessage.c dependency */
219 static void mem_error (const char *format, ...) G_GNUC_PRINTF (1,2);
220 #define mem_assert(cond)    do { if (G_LIKELY (cond)) ; else mem_error ("assertion failed: %s", #cond); } while (0)
221
222 /* --- structures --- */
223 typedef struct _ChunkLink      ChunkLink;
224 typedef struct _SlabInfo       SlabInfo;
225 typedef struct _CachedMagazine CachedMagazine;
226 struct _ChunkLink {
227   ChunkLink *next;
228   ChunkLink *data;
229 };
230 struct _SlabInfo {
231   ChunkLink *chunks;
232   guint n_allocated;
233   SlabInfo *next, *prev;
234 };
235 typedef struct {
236   ChunkLink *chunks;
237   gsize      count;                     /* approximative chunks list length */
238 } Magazine;
239 typedef struct {
240   Magazine   *magazine1;                /* array of MAX_SLAB_INDEX (allocator) */
241   Magazine   *magazine2;                /* array of MAX_SLAB_INDEX (allocator) */
242 } ThreadMemory;
243 typedef struct {
244   gboolean always_malloc;
245   gboolean bypass_magazines;
246   gboolean debug_blocks;
247   gsize    working_set_msecs;
248   guint    color_increment;
249 } SliceConfig;
250 typedef struct {
251   /* const after initialization */
252   gsize         min_page_size, max_page_size;
253   SliceConfig   config;
254   gsize         max_slab_chunk_size_for_magazine_cache;
255   /* magazine cache */
256   GMutex        magazine_mutex;
257   ChunkLink   **magazines;                /* array of MAX_SLAB_INDEX (allocator) */
258   guint        *contention_counters;      /* array of MAX_SLAB_INDEX (allocator) */
259   gint          mutex_counter;
260   guint         stamp_counter;
261   guint         last_stamp;
262   /* slab allocator */
263   GMutex        slab_mutex;
264   SlabInfo    **slab_stack;                /* array of MAX_SLAB_INDEX (allocator) */
265   guint        color_accu;
266 } Allocator;
267
268 /* --- g-slice prototypes --- */
269 static gpointer     slab_allocator_alloc_chunk       (gsize      chunk_size);
270 static void         slab_allocator_free_chunk        (gsize      chunk_size,
271                                                       gpointer   mem);
272 static void         private_thread_memory_cleanup    (gpointer   data);
273 static gpointer     allocator_memalign               (gsize      alignment,
274                                                       gsize      memsize);
275 static void         allocator_memfree                (gsize      memsize,
276                                                       gpointer   mem);
277 static inline void  magazine_cache_update_stamp      (void);
278 static inline gsize allocator_get_magazine_threshold (Allocator *allocator,
279                                                       guint      ix);
280
281 /* --- g-slice memory checker --- */
282 static void     smc_notify_alloc  (void   *pointer,
283                                    size_t  size);
284 static int      smc_notify_free   (void   *pointer,
285                                    size_t  size);
286
287 /* --- variables --- */
288 static GPrivate    private_thread_memory = G_PRIVATE_INIT (private_thread_memory_cleanup);
289 static gsize       sys_page_size = 0;
290 static Allocator   allocator[1] = { { 0, }, };
291 static SliceConfig slice_config = {
292   FALSE,        /* always_malloc */
293   FALSE,        /* bypass_magazines */
294   FALSE,        /* debug_blocks */
295   15 * 1000,    /* working_set_msecs */
296   1,            /* color increment, alt: 0x7fffffff */
297 };
298 static GMutex      smc_tree_mutex; /* mutex for G_SLICE=debug-blocks */
299
300 /* --- auxiliary funcitons --- */
301 void
302 g_slice_set_config (GSliceConfig ckey,
303                     gint64       value)
304 {
305   g_return_if_fail (sys_page_size == 0);
306   switch (ckey)
307     {
308     case G_SLICE_CONFIG_ALWAYS_MALLOC:
309       slice_config.always_malloc = value != 0;
310       break;
311     case G_SLICE_CONFIG_BYPASS_MAGAZINES:
312       slice_config.bypass_magazines = value != 0;
313       break;
314     case G_SLICE_CONFIG_WORKING_SET_MSECS:
315       slice_config.working_set_msecs = value;
316       break;
317     case G_SLICE_CONFIG_COLOR_INCREMENT:
318       slice_config.color_increment = value;
319     default: ;
320     }
321 }
322
323 gint64
324 g_slice_get_config (GSliceConfig ckey)
325 {
326   switch (ckey)
327     {
328     case G_SLICE_CONFIG_ALWAYS_MALLOC:
329       return slice_config.always_malloc;
330     case G_SLICE_CONFIG_BYPASS_MAGAZINES:
331       return slice_config.bypass_magazines;
332     case G_SLICE_CONFIG_WORKING_SET_MSECS:
333       return slice_config.working_set_msecs;
334     case G_SLICE_CONFIG_CHUNK_SIZES:
335       return MAX_SLAB_INDEX (allocator);
336     case G_SLICE_CONFIG_COLOR_INCREMENT:
337       return slice_config.color_increment;
338     default:
339       return 0;
340     }
341 }
342
343 gint64*
344 g_slice_get_config_state (GSliceConfig ckey,
345                           gint64       address,
346                           guint       *n_values)
347 {
348   guint i = 0;
349   g_return_val_if_fail (n_values != NULL, NULL);
350   *n_values = 0;
351   switch (ckey)
352     {
353       gint64 array[64];
354     case G_SLICE_CONFIG_CONTENTION_COUNTER:
355       array[i++] = SLAB_CHUNK_SIZE (allocator, address);
356       array[i++] = allocator->contention_counters[address];
357       array[i++] = allocator_get_magazine_threshold (allocator, address);
358       *n_values = i;
359       return g_memdup (array, sizeof (array[0]) * *n_values);
360     default:
361       return NULL;
362     }
363 }
364
365 static void
366 slice_config_init (SliceConfig *config)
367 {
368   const gchar *val;
369
370   *config = slice_config;
371
372   val = getenv ("G_SLICE");
373   if (val != NULL)
374     {
375       gint flags;
376       const GDebugKey keys[] = {
377         { "always-malloc", 1 << 0 },
378         { "debug-blocks",  1 << 1 },
379       };
380
381       flags = g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
382       if (flags & (1 << 0))
383         config->always_malloc = TRUE;
384       if (flags & (1 << 1))
385         config->debug_blocks = TRUE;
386     }
387   else
388     {
389       /* G_SLICE was not specified, so check if valgrind is running and
390        * disable ourselves if it is.
391        *
392        * This way it's possible to force gslice to be enabled under
393        * valgrind just by setting G_SLICE to the empty string.
394        */
395       if (RUNNING_ON_VALGRIND)
396         config->always_malloc = TRUE;
397     }
398 }
399
400 static void
401 g_slice_init_nomessage (void)
402 {
403   /* we may not use g_error() or friends here */
404   mem_assert (sys_page_size == 0);
405   mem_assert (MIN_MAGAZINE_SIZE >= 4);
406
407 #ifdef G_OS_WIN32
408   {
409     SYSTEM_INFO system_info;
410     GetSystemInfo (&system_info);
411     sys_page_size = system_info.dwPageSize;
412   }
413 #else
414   sys_page_size = sysconf (_SC_PAGESIZE); /* = sysconf (_SC_PAGE_SIZE); = getpagesize(); */
415 #endif
416   mem_assert (sys_page_size >= 2 * LARGEALIGNMENT);
417   mem_assert ((sys_page_size & (sys_page_size - 1)) == 0);
418   slice_config_init (&allocator->config);
419   allocator->min_page_size = sys_page_size;
420 #if HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN
421   /* allow allocation of pages up to 8KB (with 8KB alignment).
422    * this is useful because many medium to large sized structures
423    * fit less than 8 times (see [4]) into 4KB pages.
424    * we allow very small page sizes here, to reduce wastage in
425    * threads if only small allocations are required (this does
426    * bear the risk of increasing allocation times and fragmentation
427    * though).
428    */
429   allocator->min_page_size = MAX (allocator->min_page_size, 4096);
430   allocator->max_page_size = MAX (allocator->min_page_size, 8192);
431   allocator->min_page_size = MIN (allocator->min_page_size, 128);
432 #else
433   /* we can only align to system page size */
434   allocator->max_page_size = sys_page_size;
435 #endif
436   if (allocator->config.always_malloc)
437     {
438       allocator->contention_counters = NULL;
439       allocator->magazines = NULL;
440       allocator->slab_stack = NULL;
441     }
442   else
443     {
444       allocator->contention_counters = g_new0 (guint, MAX_SLAB_INDEX (allocator));
445       allocator->magazines = g_new0 (ChunkLink*, MAX_SLAB_INDEX (allocator));
446       allocator->slab_stack = g_new0 (SlabInfo*, MAX_SLAB_INDEX (allocator));
447     }
448
449   g_mutex_init (&allocator->magazine_mutex);
450   allocator->mutex_counter = 0;
451   allocator->stamp_counter = MAX_STAMP_COUNTER; /* force initial update */
452   allocator->last_stamp = 0;
453   g_mutex_init (&allocator->slab_mutex);
454   allocator->color_accu = 0;
455   magazine_cache_update_stamp();
456   /* values cached for performance reasons */
457   allocator->max_slab_chunk_size_for_magazine_cache = MAX_SLAB_CHUNK_SIZE (allocator);
458   if (allocator->config.always_malloc || allocator->config.bypass_magazines)
459     allocator->max_slab_chunk_size_for_magazine_cache = 0;      /* non-optimized cases */
460 }
461
462 static inline guint
463 allocator_categorize (gsize aligned_chunk_size)
464 {
465   /* speed up the likely path */
466   if (G_LIKELY (aligned_chunk_size && aligned_chunk_size <= allocator->max_slab_chunk_size_for_magazine_cache))
467     return 1;           /* use magazine cache */
468
469   if (!allocator->config.always_malloc &&
470       aligned_chunk_size &&
471       aligned_chunk_size <= MAX_SLAB_CHUNK_SIZE (allocator))
472     {
473       if (allocator->config.bypass_magazines)
474         return 2;       /* use slab allocator, see [2] */
475       return 1;         /* use magazine cache */
476     }
477   return 0;             /* use malloc() */
478 }
479
480 static inline void
481 g_mutex_lock_a (GMutex *mutex,
482                 guint  *contention_counter)
483 {
484   gboolean contention = FALSE;
485   if (!g_mutex_trylock (mutex))
486     {
487       g_mutex_lock (mutex);
488       contention = TRUE;
489     }
490   if (contention)
491     {
492       allocator->mutex_counter++;
493       if (allocator->mutex_counter >= 1)        /* quickly adapt to contention */
494         {
495           allocator->mutex_counter = 0;
496           *contention_counter = MIN (*contention_counter + 1, MAX_MAGAZINE_SIZE);
497         }
498     }
499   else /* !contention */
500     {
501       allocator->mutex_counter--;
502       if (allocator->mutex_counter < -11)       /* moderately recover magazine sizes */
503         {
504           allocator->mutex_counter = 0;
505           *contention_counter = MAX (*contention_counter, 1) - 1;
506         }
507     }
508 }
509
510 static inline ThreadMemory*
511 thread_memory_from_self (void)
512 {
513   ThreadMemory *tmem = g_private_get (&private_thread_memory);
514   if (G_UNLIKELY (!tmem))
515     {
516       static GMutex init_mutex;
517       guint n_magazines;
518
519       g_mutex_lock (&init_mutex);
520       if G_UNLIKELY (sys_page_size == 0)
521         g_slice_init_nomessage ();
522       g_mutex_unlock (&init_mutex);
523
524       n_magazines = MAX_SLAB_INDEX (allocator);
525       tmem = g_malloc0 (sizeof (ThreadMemory) + sizeof (Magazine) * 2 * n_magazines);
526       tmem->magazine1 = (Magazine*) (tmem + 1);
527       tmem->magazine2 = &tmem->magazine1[n_magazines];
528       g_private_set (&private_thread_memory, tmem);
529     }
530   return tmem;
531 }
532
533 static inline ChunkLink*
534 magazine_chain_pop_head (ChunkLink **magazine_chunks)
535 {
536   /* magazine chains are linked via ChunkLink->next.
537    * each ChunkLink->data of the toplevel chain may point to a subchain,
538    * linked via ChunkLink->next. ChunkLink->data of the subchains just
539    * contains uninitialized junk.
540    */
541   ChunkLink *chunk = (*magazine_chunks)->data;
542   if (G_UNLIKELY (chunk))
543     {
544       /* allocating from freed list */
545       (*magazine_chunks)->data = chunk->next;
546     }
547   else
548     {
549       chunk = *magazine_chunks;
550       *magazine_chunks = chunk->next;
551     }
552   return chunk;
553 }
554
555 #if 0 /* useful for debugging */
556 static guint
557 magazine_count (ChunkLink *head)
558 {
559   guint count = 0;
560   if (!head)
561     return 0;
562   while (head)
563     {
564       ChunkLink *child = head->data;
565       count += 1;
566       for (child = head->data; child; child = child->next)
567         count += 1;
568       head = head->next;
569     }
570   return count;
571 }
572 #endif
573
574 static inline gsize
575 allocator_get_magazine_threshold (Allocator *allocator,
576                                   guint      ix)
577 {
578   /* the magazine size calculated here has a lower bound of MIN_MAGAZINE_SIZE,
579    * which is required by the implementation. also, for moderately sized chunks
580    * (say >= 64 bytes), magazine sizes shouldn't be much smaller then the number
581    * of chunks available per page/2 to avoid excessive traffic in the magazine
582    * cache for small to medium sized structures.
583    * the upper bound of the magazine size is effectively provided by
584    * MAX_MAGAZINE_SIZE. for larger chunks, this number is scaled down so that
585    * the content of a single magazine doesn't exceed ca. 16KB.
586    */
587   gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
588   guint threshold = MAX (MIN_MAGAZINE_SIZE, allocator->max_page_size / MAX (5 * chunk_size, 5 * 32));
589   guint contention_counter = allocator->contention_counters[ix];
590   if (G_UNLIKELY (contention_counter))  /* single CPU bias */
591     {
592       /* adapt contention counter thresholds to chunk sizes */
593       contention_counter = contention_counter * 64 / chunk_size;
594       threshold = MAX (threshold, contention_counter);
595     }
596   return threshold;
597 }
598
599 /* --- magazine cache --- */
600 static inline void
601 magazine_cache_update_stamp (void)
602 {
603   if (allocator->stamp_counter >= MAX_STAMP_COUNTER)
604     {
605       GTimeVal tv;
606       g_get_current_time (&tv);
607       allocator->last_stamp = tv.tv_sec * 1000 + tv.tv_usec / 1000; /* milli seconds */
608       allocator->stamp_counter = 0;
609     }
610   else
611     allocator->stamp_counter++;
612 }
613
614 static inline ChunkLink*
615 magazine_chain_prepare_fields (ChunkLink *magazine_chunks)
616 {
617   ChunkLink *chunk1;
618   ChunkLink *chunk2;
619   ChunkLink *chunk3;
620   ChunkLink *chunk4;
621   /* checked upon initialization: mem_assert (MIN_MAGAZINE_SIZE >= 4); */
622   /* ensure a magazine with at least 4 unused data pointers */
623   chunk1 = magazine_chain_pop_head (&magazine_chunks);
624   chunk2 = magazine_chain_pop_head (&magazine_chunks);
625   chunk3 = magazine_chain_pop_head (&magazine_chunks);
626   chunk4 = magazine_chain_pop_head (&magazine_chunks);
627   chunk4->next = magazine_chunks;
628   chunk3->next = chunk4;
629   chunk2->next = chunk3;
630   chunk1->next = chunk2;
631   return chunk1;
632 }
633
634 /* access the first 3 fields of a specially prepared magazine chain */
635 #define magazine_chain_prev(mc)         ((mc)->data)
636 #define magazine_chain_stamp(mc)        ((mc)->next->data)
637 #define magazine_chain_uint_stamp(mc)   GPOINTER_TO_UINT ((mc)->next->data)
638 #define magazine_chain_next(mc)         ((mc)->next->next->data)
639 #define magazine_chain_count(mc)        ((mc)->next->next->next->data)
640
641 static void
642 magazine_cache_trim (Allocator *allocator,
643                      guint      ix,
644                      guint      stamp)
645 {
646   /* g_mutex_lock (allocator->mutex); done by caller */
647   /* trim magazine cache from tail */
648   ChunkLink *current = magazine_chain_prev (allocator->magazines[ix]);
649   ChunkLink *trash = NULL;
650   while (ABS (stamp - magazine_chain_uint_stamp (current)) >= allocator->config.working_set_msecs)
651     {
652       /* unlink */
653       ChunkLink *prev = magazine_chain_prev (current);
654       ChunkLink *next = magazine_chain_next (current);
655       magazine_chain_next (prev) = next;
656       magazine_chain_prev (next) = prev;
657       /* clear special fields, put on trash stack */
658       magazine_chain_next (current) = NULL;
659       magazine_chain_count (current) = NULL;
660       magazine_chain_stamp (current) = NULL;
661       magazine_chain_prev (current) = trash;
662       trash = current;
663       /* fixup list head if required */
664       if (current == allocator->magazines[ix])
665         {
666           allocator->magazines[ix] = NULL;
667           break;
668         }
669       current = prev;
670     }
671   g_mutex_unlock (&allocator->magazine_mutex);
672   /* free trash */
673   if (trash)
674     {
675       const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
676       g_mutex_lock (&allocator->slab_mutex);
677       while (trash)
678         {
679           current = trash;
680           trash = magazine_chain_prev (current);
681           magazine_chain_prev (current) = NULL; /* clear special field */
682           while (current)
683             {
684               ChunkLink *chunk = magazine_chain_pop_head (&current);
685               slab_allocator_free_chunk (chunk_size, chunk);
686             }
687         }
688       g_mutex_unlock (&allocator->slab_mutex);
689     }
690 }
691
692 static void
693 magazine_cache_push_magazine (guint      ix,
694                               ChunkLink *magazine_chunks,
695                               gsize      count) /* must be >= MIN_MAGAZINE_SIZE */
696 {
697   ChunkLink *current = magazine_chain_prepare_fields (magazine_chunks);
698   ChunkLink *next, *prev;
699   g_mutex_lock (&allocator->magazine_mutex);
700   /* add magazine at head */
701   next = allocator->magazines[ix];
702   if (next)
703     prev = magazine_chain_prev (next);
704   else
705     next = prev = current;
706   magazine_chain_next (prev) = current;
707   magazine_chain_prev (next) = current;
708   magazine_chain_prev (current) = prev;
709   magazine_chain_next (current) = next;
710   magazine_chain_count (current) = (gpointer) count;
711   /* stamp magazine */
712   magazine_cache_update_stamp();
713   magazine_chain_stamp (current) = GUINT_TO_POINTER (allocator->last_stamp);
714   allocator->magazines[ix] = current;
715   /* free old magazines beyond a certain threshold */
716   magazine_cache_trim (allocator, ix, allocator->last_stamp);
717   /* g_mutex_unlock (allocator->mutex); was done by magazine_cache_trim() */
718 }
719
720 static ChunkLink*
721 magazine_cache_pop_magazine (guint  ix,
722                              gsize *countp)
723 {
724   g_mutex_lock_a (&allocator->magazine_mutex, &allocator->contention_counters[ix]);
725   if (!allocator->magazines[ix])
726     {
727       guint magazine_threshold = allocator_get_magazine_threshold (allocator, ix);
728       gsize i, chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
729       ChunkLink *chunk, *head;
730       g_mutex_unlock (&allocator->magazine_mutex);
731       g_mutex_lock (&allocator->slab_mutex);
732       head = slab_allocator_alloc_chunk (chunk_size);
733       head->data = NULL;
734       chunk = head;
735       for (i = 1; i < magazine_threshold; i++)
736         {
737           chunk->next = slab_allocator_alloc_chunk (chunk_size);
738           chunk = chunk->next;
739           chunk->data = NULL;
740         }
741       chunk->next = NULL;
742       g_mutex_unlock (&allocator->slab_mutex);
743       *countp = i;
744       return head;
745     }
746   else
747     {
748       ChunkLink *current = allocator->magazines[ix];
749       ChunkLink *prev = magazine_chain_prev (current);
750       ChunkLink *next = magazine_chain_next (current);
751       /* unlink */
752       magazine_chain_next (prev) = next;
753       magazine_chain_prev (next) = prev;
754       allocator->magazines[ix] = next == current ? NULL : next;
755       g_mutex_unlock (&allocator->magazine_mutex);
756       /* clear special fields and hand out */
757       *countp = (gsize) magazine_chain_count (current);
758       magazine_chain_prev (current) = NULL;
759       magazine_chain_next (current) = NULL;
760       magazine_chain_count (current) = NULL;
761       magazine_chain_stamp (current) = NULL;
762       return current;
763     }
764 }
765
766 /* --- thread magazines --- */
767 static void
768 private_thread_memory_cleanup (gpointer data)
769 {
770   ThreadMemory *tmem = data;
771   const guint n_magazines = MAX_SLAB_INDEX (allocator);
772   guint ix;
773   for (ix = 0; ix < n_magazines; ix++)
774     {
775       Magazine *mags[2];
776       guint j;
777       mags[0] = &tmem->magazine1[ix];
778       mags[1] = &tmem->magazine2[ix];
779       for (j = 0; j < 2; j++)
780         {
781           Magazine *mag = mags[j];
782           if (mag->count >= MIN_MAGAZINE_SIZE)
783             magazine_cache_push_magazine (ix, mag->chunks, mag->count);
784           else
785             {
786               const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
787               g_mutex_lock (&allocator->slab_mutex);
788               while (mag->chunks)
789                 {
790                   ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
791                   slab_allocator_free_chunk (chunk_size, chunk);
792                 }
793               g_mutex_unlock (&allocator->slab_mutex);
794             }
795         }
796     }
797   g_free (tmem);
798 }
799
800 static void
801 thread_memory_magazine1_reload (ThreadMemory *tmem,
802                                 guint         ix)
803 {
804   Magazine *mag = &tmem->magazine1[ix];
805   mem_assert (mag->chunks == NULL); /* ensure that we may reset mag->count */
806   mag->count = 0;
807   mag->chunks = magazine_cache_pop_magazine (ix, &mag->count);
808 }
809
810 static void
811 thread_memory_magazine2_unload (ThreadMemory *tmem,
812                                 guint         ix)
813 {
814   Magazine *mag = &tmem->magazine2[ix];
815   magazine_cache_push_magazine (ix, mag->chunks, mag->count);
816   mag->chunks = NULL;
817   mag->count = 0;
818 }
819
820 static inline void
821 thread_memory_swap_magazines (ThreadMemory *tmem,
822                               guint         ix)
823 {
824   Magazine xmag = tmem->magazine1[ix];
825   tmem->magazine1[ix] = tmem->magazine2[ix];
826   tmem->magazine2[ix] = xmag;
827 }
828
829 static inline gboolean
830 thread_memory_magazine1_is_empty (ThreadMemory *tmem,
831                                   guint         ix)
832 {
833   return tmem->magazine1[ix].chunks == NULL;
834 }
835
836 static inline gboolean
837 thread_memory_magazine2_is_full (ThreadMemory *tmem,
838                                  guint         ix)
839 {
840   return tmem->magazine2[ix].count >= allocator_get_magazine_threshold (allocator, ix);
841 }
842
843 static inline gpointer
844 thread_memory_magazine1_alloc (ThreadMemory *tmem,
845                                guint         ix)
846 {
847   Magazine *mag = &tmem->magazine1[ix];
848   ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
849   if (G_LIKELY (mag->count > 0))
850     mag->count--;
851   return chunk;
852 }
853
854 static inline void
855 thread_memory_magazine2_free (ThreadMemory *tmem,
856                               guint         ix,
857                               gpointer      mem)
858 {
859   Magazine *mag = &tmem->magazine2[ix];
860   ChunkLink *chunk = mem;
861   chunk->data = NULL;
862   chunk->next = mag->chunks;
863   mag->chunks = chunk;
864   mag->count++;
865 }
866
867 /* --- API functions --- */
868
869 /**
870  * g_slice_new:
871  * @type: the type to allocate, typically a structure name
872  *
873  * A convenience macro to allocate a block of memory from the
874  * slice allocator.
875  *
876  * It calls g_slice_alloc() with <literal>sizeof (@type)</literal>
877  * and casts the returned pointer to a pointer of the given type,
878  * avoiding a type cast in the source code.
879  * Note that the underlying slice allocation mechanism can
880  * be changed with the <link linkend="G_SLICE">G_SLICE=always-malloc</link>
881  * environment variable.
882  *
883  * Returns: a pointer to the allocated block, cast to a pointer to @type
884  *
885  * Since: 2.10
886  */
887
888 /**
889  * g_slice_new0:
890  * @type: the type to allocate, typically a structure name
891  *
892  * A convenience macro to allocate a block of memory from the
893  * slice allocator and set the memory to 0.
894  *
895  * It calls g_slice_alloc0() with <literal>sizeof (@type)</literal>
896  * and casts the returned pointer to a pointer of the given type,
897  * avoiding a type cast in the source code.
898  * Note that the underlying slice allocation mechanism can
899  * be changed with the <link linkend="G_SLICE">G_SLICE=always-malloc</link>
900  * environment variable.
901  *
902  * Since: 2.10
903  */
904
905 /**
906  * g_slice_dup:
907  * @type: the type to duplicate, typically a structure name
908  * @mem: the memory to copy into the allocated block
909  *
910  * A convenience macro to duplicate a block of memory using
911  * the slice allocator.
912  *
913  * It calls g_slice_copy() with <literal>sizeof (@type)</literal>
914  * and casts the returned pointer to a pointer of the given type,
915  * avoiding a type cast in the source code.
916  * Note that the underlying slice allocation mechanism can
917  * be changed with the <link linkend="G_SLICE">G_SLICE=always-malloc</link>
918  * environment variable.
919  *
920  * Returns: a pointer to the allocated block, cast to a pointer to @type
921  *
922  * Since: 2.14
923  */
924
925 /**
926  * g_slice_free:
927  * @type: the type of the block to free, typically a structure name
928  * @mem: a pointer to the block to free
929  *
930  * A convenience macro to free a block of memory that has
931  * been allocated from the slice allocator.
932  *
933  * It calls g_slice_free1() using <literal>sizeof (type)</literal>
934  * as the block size.
935  * Note that the exact release behaviour can be changed with the
936  * <link linkend="G_DEBUG">G_DEBUG=gc-friendly</link> environment
937  * variable, also see <link linkend="G_SLICE">G_SLICE</link> for
938  * related debugging options.
939  *
940  * Since: 2.10
941  */
942
943 /**
944  * g_slice_free_chain:
945  * @type: the type of the @mem_chain blocks
946  * @mem_chain: a pointer to the first block of the chain
947  * @next: the field name of the next pointer in @type
948  *
949  * Frees a linked list of memory blocks of structure type @type.
950  * The memory blocks must be equal-sized, allocated via
951  * g_slice_alloc() or g_slice_alloc0() and linked together by
952  * a @next pointer (similar to #GSList). The name of the
953  * @next field in @type is passed as third argument.
954  * Note that the exact release behaviour can be changed with the
955  * <link linkend="G_DEBUG">G_DEBUG=gc-friendly</link> environment
956  * variable, also see <link linkend="G_SLICE">G_SLICE</link> for
957  * related debugging options.
958  *
959  * Since: 2.10
960  */
961
962 /**
963  * g_slice_alloc:
964  * @block_size: the number of bytes to allocate
965  *
966  * Allocates a block of memory from the slice allocator.
967  * The block adress handed out can be expected to be aligned
968  * to at least <literal>1 * sizeof (void*)</literal>,
969  * though in general slices are 2 * sizeof (void*) bytes aligned,
970  * if a malloc() fallback implementation is used instead,
971  * the alignment may be reduced in a libc dependent fashion.
972  * Note that the underlying slice allocation mechanism can
973  * be changed with the <link linkend="G_SLICE">G_SLICE=always-malloc</link>
974  * environment variable.
975  *
976  * Returns: a pointer to the allocated memory block
977  *
978  * Since: 2.10
979  */
980 gpointer
981 g_slice_alloc (gsize mem_size)
982 {
983   ThreadMemory *tmem;
984   gsize chunk_size;
985   gpointer mem;
986   guint acat;
987
988   /* This gets the private structure for this thread.  If the private
989    * structure does not yet exist, it is created.
990    *
991    * This has a side effect of causing GSlice to be initialised, so it
992    * must come first.
993    */
994   tmem = thread_memory_from_self ();
995
996   chunk_size = P2ALIGN (mem_size);
997   acat = allocator_categorize (chunk_size);
998   if (G_LIKELY (acat == 1))     /* allocate through magazine layer */
999     {
1000       guint ix = SLAB_INDEX (allocator, chunk_size);
1001       if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
1002         {
1003           thread_memory_swap_magazines (tmem, ix);
1004           if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
1005             thread_memory_magazine1_reload (tmem, ix);
1006         }
1007       mem = thread_memory_magazine1_alloc (tmem, ix);
1008     }
1009   else if (acat == 2)           /* allocate through slab allocator */
1010     {
1011       g_mutex_lock (&allocator->slab_mutex);
1012       mem = slab_allocator_alloc_chunk (chunk_size);
1013       g_mutex_unlock (&allocator->slab_mutex);
1014     }
1015   else                          /* delegate to system malloc */
1016     mem = g_malloc (mem_size);
1017   if (G_UNLIKELY (allocator->config.debug_blocks))
1018     smc_notify_alloc (mem, mem_size);
1019
1020   TRACE (GLIB_SLICE_ALLOC((void*)mem, mem_size));
1021
1022   return mem;
1023 }
1024
1025 /**
1026  * g_slice_alloc0:
1027  * @block_size: the number of bytes to allocate
1028  *
1029  * Allocates a block of memory via g_slice_alloc() and initializes
1030  * the returned memory to 0. Note that the underlying slice allocation
1031  * mechanism can be changed with the
1032  * <link linkend="G_SLICE">G_SLICE=always-malloc</link>
1033  * environment variable.
1034  *
1035  * Returns: a pointer to the allocated block
1036  *
1037  * Since: 2.10
1038  */
1039 gpointer
1040 g_slice_alloc0 (gsize mem_size)
1041 {
1042   gpointer mem = g_slice_alloc (mem_size);
1043   if (mem)
1044     memset (mem, 0, mem_size);
1045   return mem;
1046 }
1047
1048 /**
1049  * g_slice_copy:
1050  * @block_size: the number of bytes to allocate
1051  * @mem_block: the memory to copy
1052  *
1053  * Allocates a block of memory from the slice allocator
1054  * and copies @block_size bytes into it from @mem_block.
1055  *
1056  * Returns: a pointer to the allocated memory block
1057  *
1058  * Since: 2.14
1059  */
1060 gpointer
1061 g_slice_copy (gsize         mem_size,
1062               gconstpointer mem_block)
1063 {
1064   gpointer mem = g_slice_alloc (mem_size);
1065   if (mem)
1066     memcpy (mem, mem_block, mem_size);
1067   return mem;
1068 }
1069
1070 /**
1071  * g_slice_free1:
1072  * @block_size: the size of the block
1073  * @mem_block: a pointer to the block to free
1074  *
1075  * Frees a block of memory.
1076  *
1077  * The memory must have been allocated via g_slice_alloc() or
1078  * g_slice_alloc0() and the @block_size has to match the size
1079  * specified upon allocation. Note that the exact release behaviour
1080  * can be changed with the
1081  * <link linkend="G_DEBUG">G_DEBUG=gc-friendly</link> environment
1082  * variable, also see <link linkend="G_SLICE">G_SLICE</link> for
1083  * related debugging options.
1084  *
1085  * Since: 2.10
1086  */
1087 void
1088 g_slice_free1 (gsize    mem_size,
1089                gpointer mem_block)
1090 {
1091   gsize chunk_size = P2ALIGN (mem_size);
1092   guint acat = allocator_categorize (chunk_size);
1093   if (G_UNLIKELY (!mem_block))
1094     return;
1095   if (G_UNLIKELY (allocator->config.debug_blocks) &&
1096       !smc_notify_free (mem_block, mem_size))
1097     abort();
1098   if (G_LIKELY (acat == 1))             /* allocate through magazine layer */
1099     {
1100       ThreadMemory *tmem = thread_memory_from_self();
1101       guint ix = SLAB_INDEX (allocator, chunk_size);
1102       if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
1103         {
1104           thread_memory_swap_magazines (tmem, ix);
1105           if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
1106             thread_memory_magazine2_unload (tmem, ix);
1107         }
1108       if (G_UNLIKELY (g_mem_gc_friendly))
1109         memset (mem_block, 0, chunk_size);
1110       thread_memory_magazine2_free (tmem, ix, mem_block);
1111     }
1112   else if (acat == 2)                   /* allocate through slab allocator */
1113     {
1114       if (G_UNLIKELY (g_mem_gc_friendly))
1115         memset (mem_block, 0, chunk_size);
1116       g_mutex_lock (&allocator->slab_mutex);
1117       slab_allocator_free_chunk (chunk_size, mem_block);
1118       g_mutex_unlock (&allocator->slab_mutex);
1119     }
1120   else                                  /* delegate to system malloc */
1121     {
1122       if (G_UNLIKELY (g_mem_gc_friendly))
1123         memset (mem_block, 0, mem_size);
1124       g_free (mem_block);
1125     }
1126   TRACE (GLIB_SLICE_FREE((void*)mem_block, mem_size));
1127 }
1128
1129 /**
1130  * g_slice_free_chain_with_offset:
1131  * @block_size: the size of the blocks
1132  * @mem_chain:  a pointer to the first block of the chain
1133  * @next_offset: the offset of the @next field in the blocks
1134  *
1135  * Frees a linked list of memory blocks of structure type @type.
1136  *
1137  * The memory blocks must be equal-sized, allocated via
1138  * g_slice_alloc() or g_slice_alloc0() and linked together by a
1139  * @next pointer (similar to #GSList). The offset of the @next
1140  * field in each block is passed as third argument.
1141  * Note that the exact release behaviour can be changed with the
1142  * <link linkend="G_DEBUG">G_DEBUG=gc-friendly</link> environment
1143  * variable, also see <link linkend="G_SLICE">G_SLICE</link> for
1144  * related debugging options.
1145  *
1146  * Since: 2.10
1147  */
1148 void
1149 g_slice_free_chain_with_offset (gsize    mem_size,
1150                                 gpointer mem_chain,
1151                                 gsize    next_offset)
1152 {
1153   gpointer slice = mem_chain;
1154   /* while the thread magazines and the magazine cache are implemented so that
1155    * they can easily be extended to allow for free lists containing more free
1156    * lists for the first level nodes, which would allow O(1) freeing in this
1157    * function, the benefit of such an extension is questionable, because:
1158    * - the magazine size counts will become mere lower bounds which confuses
1159    *   the code adapting to lock contention;
1160    * - freeing a single node to the thread magazines is very fast, so this
1161    *   O(list_length) operation is multiplied by a fairly small factor;
1162    * - memory usage histograms on larger applications seem to indicate that
1163    *   the amount of released multi node lists is negligible in comparison
1164    *   to single node releases.
1165    * - the major performance bottle neck, namely g_private_get() or
1166    *   g_mutex_lock()/g_mutex_unlock() has already been moved out of the
1167    *   inner loop for freeing chained slices.
1168    */
1169   gsize chunk_size = P2ALIGN (mem_size);
1170   guint acat = allocator_categorize (chunk_size);
1171   if (G_LIKELY (acat == 1))             /* allocate through magazine layer */
1172     {
1173       ThreadMemory *tmem = thread_memory_from_self();
1174       guint ix = SLAB_INDEX (allocator, chunk_size);
1175       while (slice)
1176         {
1177           guint8 *current = slice;
1178           slice = *(gpointer*) (current + next_offset);
1179           if (G_UNLIKELY (allocator->config.debug_blocks) &&
1180               !smc_notify_free (current, mem_size))
1181             abort();
1182           if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
1183             {
1184               thread_memory_swap_magazines (tmem, ix);
1185               if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
1186                 thread_memory_magazine2_unload (tmem, ix);
1187             }
1188           if (G_UNLIKELY (g_mem_gc_friendly))
1189             memset (current, 0, chunk_size);
1190           thread_memory_magazine2_free (tmem, ix, current);
1191         }
1192     }
1193   else if (acat == 2)                   /* allocate through slab allocator */
1194     {
1195       g_mutex_lock (&allocator->slab_mutex);
1196       while (slice)
1197         {
1198           guint8 *current = slice;
1199           slice = *(gpointer*) (current + next_offset);
1200           if (G_UNLIKELY (allocator->config.debug_blocks) &&
1201               !smc_notify_free (current, mem_size))
1202             abort();
1203           if (G_UNLIKELY (g_mem_gc_friendly))
1204             memset (current, 0, chunk_size);
1205           slab_allocator_free_chunk (chunk_size, current);
1206         }
1207       g_mutex_unlock (&allocator->slab_mutex);
1208     }
1209   else                                  /* delegate to system malloc */
1210     while (slice)
1211       {
1212         guint8 *current = slice;
1213         slice = *(gpointer*) (current + next_offset);
1214         if (G_UNLIKELY (allocator->config.debug_blocks) &&
1215             !smc_notify_free (current, mem_size))
1216           abort();
1217         if (G_UNLIKELY (g_mem_gc_friendly))
1218           memset (current, 0, mem_size);
1219         g_free (current);
1220       }
1221 }
1222
1223 /* --- single page allocator --- */
1224 static void
1225 allocator_slab_stack_push (Allocator *allocator,
1226                            guint      ix,
1227                            SlabInfo  *sinfo)
1228 {
1229   /* insert slab at slab ring head */
1230   if (!allocator->slab_stack[ix])
1231     {
1232       sinfo->next = sinfo;
1233       sinfo->prev = sinfo;
1234     }
1235   else
1236     {
1237       SlabInfo *next = allocator->slab_stack[ix], *prev = next->prev;
1238       next->prev = sinfo;
1239       prev->next = sinfo;
1240       sinfo->next = next;
1241       sinfo->prev = prev;
1242     }
1243   allocator->slab_stack[ix] = sinfo;
1244 }
1245
1246 static gsize
1247 allocator_aligned_page_size (Allocator *allocator,
1248                              gsize      n_bytes)
1249 {
1250   gsize val = 1 << g_bit_storage (n_bytes - 1);
1251   val = MAX (val, allocator->min_page_size);
1252   return val;
1253 }
1254
1255 static void
1256 allocator_add_slab (Allocator *allocator,
1257                     guint      ix,
1258                     gsize      chunk_size)
1259 {
1260   ChunkLink *chunk;
1261   SlabInfo *sinfo;
1262   gsize addr, padding, n_chunks, color = 0;
1263   gsize page_size = allocator_aligned_page_size (allocator, SLAB_BPAGE_SIZE (allocator, chunk_size));
1264   /* allocate 1 page for the chunks and the slab */
1265   gpointer aligned_memory = allocator_memalign (page_size, page_size - NATIVE_MALLOC_PADDING);
1266   guint8 *mem = aligned_memory;
1267   guint i;
1268   if (!mem)
1269     {
1270       const gchar *syserr = "unknown error";
1271 #if HAVE_STRERROR
1272       syserr = strerror (errno);
1273 #endif
1274       mem_error ("failed to allocate %u bytes (alignment: %u): %s\n",
1275                  (guint) (page_size - NATIVE_MALLOC_PADDING), (guint) page_size, syserr);
1276     }
1277   /* mask page address */
1278   addr = ((gsize) mem / page_size) * page_size;
1279   /* assert alignment */
1280   mem_assert (aligned_memory == (gpointer) addr);
1281   /* basic slab info setup */
1282   sinfo = (SlabInfo*) (mem + page_size - SLAB_INFO_SIZE);
1283   sinfo->n_allocated = 0;
1284   sinfo->chunks = NULL;
1285   /* figure cache colorization */
1286   n_chunks = ((guint8*) sinfo - mem) / chunk_size;
1287   padding = ((guint8*) sinfo - mem) - n_chunks * chunk_size;
1288   if (padding)
1289     {
1290       color = (allocator->color_accu * P2ALIGNMENT) % padding;
1291       allocator->color_accu += allocator->config.color_increment;
1292     }
1293   /* add chunks to free list */
1294   chunk = (ChunkLink*) (mem + color);
1295   sinfo->chunks = chunk;
1296   for (i = 0; i < n_chunks - 1; i++)
1297     {
1298       chunk->next = (ChunkLink*) ((guint8*) chunk + chunk_size);
1299       chunk = chunk->next;
1300     }
1301   chunk->next = NULL;   /* last chunk */
1302   /* add slab to slab ring */
1303   allocator_slab_stack_push (allocator, ix, sinfo);
1304 }
1305
1306 static gpointer
1307 slab_allocator_alloc_chunk (gsize chunk_size)
1308 {
1309   ChunkLink *chunk;
1310   guint ix = SLAB_INDEX (allocator, chunk_size);
1311   /* ensure non-empty slab */
1312   if (!allocator->slab_stack[ix] || !allocator->slab_stack[ix]->chunks)
1313     allocator_add_slab (allocator, ix, chunk_size);
1314   /* allocate chunk */
1315   chunk = allocator->slab_stack[ix]->chunks;
1316   allocator->slab_stack[ix]->chunks = chunk->next;
1317   allocator->slab_stack[ix]->n_allocated++;
1318   /* rotate empty slabs */
1319   if (!allocator->slab_stack[ix]->chunks)
1320     allocator->slab_stack[ix] = allocator->slab_stack[ix]->next;
1321   return chunk;
1322 }
1323
1324 static void
1325 slab_allocator_free_chunk (gsize    chunk_size,
1326                            gpointer mem)
1327 {
1328   ChunkLink *chunk;
1329   gboolean was_empty;
1330   guint ix = SLAB_INDEX (allocator, chunk_size);
1331   gsize page_size = allocator_aligned_page_size (allocator, SLAB_BPAGE_SIZE (allocator, chunk_size));
1332   gsize addr = ((gsize) mem / page_size) * page_size;
1333   /* mask page address */
1334   guint8 *page = (guint8*) addr;
1335   SlabInfo *sinfo = (SlabInfo*) (page + page_size - SLAB_INFO_SIZE);
1336   /* assert valid chunk count */
1337   mem_assert (sinfo->n_allocated > 0);
1338   /* add chunk to free list */
1339   was_empty = sinfo->chunks == NULL;
1340   chunk = (ChunkLink*) mem;
1341   chunk->next = sinfo->chunks;
1342   sinfo->chunks = chunk;
1343   sinfo->n_allocated--;
1344   /* keep slab ring partially sorted, empty slabs at end */
1345   if (was_empty)
1346     {
1347       /* unlink slab */
1348       SlabInfo *next = sinfo->next, *prev = sinfo->prev;
1349       next->prev = prev;
1350       prev->next = next;
1351       if (allocator->slab_stack[ix] == sinfo)
1352         allocator->slab_stack[ix] = next == sinfo ? NULL : next;
1353       /* insert slab at head */
1354       allocator_slab_stack_push (allocator, ix, sinfo);
1355     }
1356   /* eagerly free complete unused slabs */
1357   if (!sinfo->n_allocated)
1358     {
1359       /* unlink slab */
1360       SlabInfo *next = sinfo->next, *prev = sinfo->prev;
1361       next->prev = prev;
1362       prev->next = next;
1363       if (allocator->slab_stack[ix] == sinfo)
1364         allocator->slab_stack[ix] = next == sinfo ? NULL : next;
1365       /* free slab */
1366       allocator_memfree (page_size, page);
1367     }
1368 }
1369
1370 /* --- memalign implementation --- */
1371 #ifdef HAVE_MALLOC_H
1372 #include <malloc.h>             /* memalign() */
1373 #endif
1374
1375 /* from config.h:
1376  * define HAVE_POSIX_MEMALIGN           1 // if free(posix_memalign(3)) works, <stdlib.h>
1377  * define HAVE_COMPLIANT_POSIX_MEMALIGN 1 // if free(posix_memalign(3)) works for sizes != 2^n, <stdlib.h>
1378  * define HAVE_MEMALIGN                 1 // if free(memalign(3)) works, <malloc.h>
1379  * define HAVE_VALLOC                   1 // if free(valloc(3)) works, <stdlib.h> or <malloc.h>
1380  * if none is provided, we implement malloc(3)-based alloc-only page alignment
1381  */
1382
1383 #if !(HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC)
1384 static GTrashStack *compat_valloc_trash = NULL;
1385 #endif
1386
1387 static gpointer
1388 allocator_memalign (gsize alignment,
1389                     gsize memsize)
1390 {
1391   gpointer aligned_memory = NULL;
1392   gint err = ENOMEM;
1393 #if     HAVE_COMPLIANT_POSIX_MEMALIGN
1394   err = posix_memalign (&aligned_memory, alignment, memsize);
1395 #elif   HAVE_MEMALIGN
1396   errno = 0;
1397   aligned_memory = memalign (alignment, memsize);
1398   err = errno;
1399 #elif   HAVE_VALLOC
1400   errno = 0;
1401   aligned_memory = valloc (memsize);
1402   err = errno;
1403 #else
1404   /* simplistic non-freeing page allocator */
1405   mem_assert (alignment == sys_page_size);
1406   mem_assert (memsize <= sys_page_size);
1407   if (!compat_valloc_trash)
1408     {
1409       const guint n_pages = 16;
1410       guint8 *mem = malloc (n_pages * sys_page_size);
1411       err = errno;
1412       if (mem)
1413         {
1414           gint i = n_pages;
1415           guint8 *amem = (guint8*) ALIGN ((gsize) mem, sys_page_size);
1416           if (amem != mem)
1417             i--;        /* mem wasn't page aligned */
1418           while (--i >= 0)
1419             g_trash_stack_push (&compat_valloc_trash, amem + i * sys_page_size);
1420         }
1421     }
1422   aligned_memory = g_trash_stack_pop (&compat_valloc_trash);
1423 #endif
1424   if (!aligned_memory)
1425     errno = err;
1426   return aligned_memory;
1427 }
1428
1429 static void
1430 allocator_memfree (gsize    memsize,
1431                    gpointer mem)
1432 {
1433 #if     HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC
1434   free (mem);
1435 #else
1436   mem_assert (memsize <= sys_page_size);
1437   g_trash_stack_push (&compat_valloc_trash, mem);
1438 #endif
1439 }
1440
1441 static void
1442 mem_error (const char *format,
1443            ...)
1444 {
1445   const char *pname;
1446   va_list args;
1447   /* at least, put out "MEMORY-ERROR", in case we segfault during the rest of the function */
1448   fputs ("\n***MEMORY-ERROR***: ", stderr);
1449   pname = g_get_prgname();
1450   fprintf (stderr, "%s[%ld]: GSlice: ", pname ? pname : "", (long)getpid());
1451   va_start (args, format);
1452   vfprintf (stderr, format, args);
1453   va_end (args);
1454   fputs ("\n", stderr);
1455   abort();
1456   _exit (1);
1457 }
1458
1459 /* --- g-slice memory checker tree --- */
1460 typedef size_t SmcKType;                /* key type */
1461 typedef size_t SmcVType;                /* value type */
1462 typedef struct {
1463   SmcKType key;
1464   SmcVType value;
1465 } SmcEntry;
1466 static void             smc_tree_insert      (SmcKType  key,
1467                                               SmcVType  value);
1468 static gboolean         smc_tree_lookup      (SmcKType  key,
1469                                               SmcVType *value_p);
1470 static gboolean         smc_tree_remove      (SmcKType  key);
1471
1472
1473 /* --- g-slice memory checker implementation --- */
1474 static void
1475 smc_notify_alloc (void   *pointer,
1476                   size_t  size)
1477 {
1478   size_t adress = (size_t) pointer;
1479   if (pointer)
1480     smc_tree_insert (adress, size);
1481 }
1482
1483 #if 0
1484 static void
1485 smc_notify_ignore (void *pointer)
1486 {
1487   size_t adress = (size_t) pointer;
1488   if (pointer)
1489     smc_tree_remove (adress);
1490 }
1491 #endif
1492
1493 static int
1494 smc_notify_free (void   *pointer,
1495                  size_t  size)
1496 {
1497   size_t adress = (size_t) pointer;
1498   SmcVType real_size;
1499   gboolean found_one;
1500
1501   if (!pointer)
1502     return 1; /* ignore */
1503   found_one = smc_tree_lookup (adress, &real_size);
1504   if (!found_one)
1505     {
1506       fprintf (stderr, "GSlice: MemChecker: attempt to release non-allocated block: %p size=%" G_GSIZE_FORMAT "\n", pointer, size);
1507       return 0;
1508     }
1509   if (real_size != size && (real_size || size))
1510     {
1511       fprintf (stderr, "GSlice: MemChecker: attempt to release block with invalid size: %p size=%" G_GSIZE_FORMAT " invalid-size=%" G_GSIZE_FORMAT "\n", pointer, real_size, size);
1512       return 0;
1513     }
1514   if (!smc_tree_remove (adress))
1515     {
1516       fprintf (stderr, "GSlice: MemChecker: attempt to release non-allocated block: %p size=%" G_GSIZE_FORMAT "\n", pointer, size);
1517       return 0;
1518     }
1519   return 1; /* all fine */
1520 }
1521
1522 /* --- g-slice memory checker tree implementation --- */
1523 #define SMC_TRUNK_COUNT     (4093 /* 16381 */)          /* prime, to distribute trunk collisions (big, allocated just once) */
1524 #define SMC_BRANCH_COUNT    (511)                       /* prime, to distribute branch collisions */
1525 #define SMC_TRUNK_EXTENT    (SMC_BRANCH_COUNT * 2039)   /* key address space per trunk, should distribute uniformly across BRANCH_COUNT */
1526 #define SMC_TRUNK_HASH(k)   ((k / SMC_TRUNK_EXTENT) % SMC_TRUNK_COUNT)  /* generate new trunk hash per megabyte (roughly) */
1527 #define SMC_BRANCH_HASH(k)  (k % SMC_BRANCH_COUNT)
1528
1529 typedef struct {
1530   SmcEntry    *entries;
1531   unsigned int n_entries;
1532 } SmcBranch;
1533
1534 static SmcBranch     **smc_tree_root = NULL;
1535
1536 static void
1537 smc_tree_abort (int errval)
1538 {
1539   const char *syserr = "unknown error";
1540 #if HAVE_STRERROR
1541   syserr = strerror (errval);
1542 #endif
1543   mem_error ("MemChecker: failure in debugging tree: %s", syserr);
1544 }
1545
1546 static inline SmcEntry*
1547 smc_tree_branch_grow_L (SmcBranch   *branch,
1548                         unsigned int index)
1549 {
1550   unsigned int old_size = branch->n_entries * sizeof (branch->entries[0]);
1551   unsigned int new_size = old_size + sizeof (branch->entries[0]);
1552   SmcEntry *entry;
1553   mem_assert (index <= branch->n_entries);
1554   branch->entries = (SmcEntry*) realloc (branch->entries, new_size);
1555   if (!branch->entries)
1556     smc_tree_abort (errno);
1557   entry = branch->entries + index;
1558   g_memmove (entry + 1, entry, (branch->n_entries - index) * sizeof (entry[0]));
1559   branch->n_entries += 1;
1560   return entry;
1561 }
1562
1563 static inline SmcEntry*
1564 smc_tree_branch_lookup_nearest_L (SmcBranch *branch,
1565                                   SmcKType   key)
1566 {
1567   unsigned int n_nodes = branch->n_entries, offs = 0;
1568   SmcEntry *check = branch->entries;
1569   int cmp = 0;
1570   while (offs < n_nodes)
1571     {
1572       unsigned int i = (offs + n_nodes) >> 1;
1573       check = branch->entries + i;
1574       cmp = key < check->key ? -1 : key != check->key;
1575       if (cmp == 0)
1576         return check;                   /* return exact match */
1577       else if (cmp < 0)
1578         n_nodes = i;
1579       else /* (cmp > 0) */
1580         offs = i + 1;
1581     }
1582   /* check points at last mismatch, cmp > 0 indicates greater key */
1583   return cmp > 0 ? check + 1 : check;   /* return insertion position for inexact match */
1584 }
1585
1586 static void
1587 smc_tree_insert (SmcKType key,
1588                  SmcVType value)
1589 {
1590   unsigned int ix0, ix1;
1591   SmcEntry *entry;
1592
1593   g_mutex_lock (&smc_tree_mutex);
1594   ix0 = SMC_TRUNK_HASH (key);
1595   ix1 = SMC_BRANCH_HASH (key);
1596   if (!smc_tree_root)
1597     {
1598       smc_tree_root = calloc (SMC_TRUNK_COUNT, sizeof (smc_tree_root[0]));
1599       if (!smc_tree_root)
1600         smc_tree_abort (errno);
1601     }
1602   if (!smc_tree_root[ix0])
1603     {
1604       smc_tree_root[ix0] = calloc (SMC_BRANCH_COUNT, sizeof (smc_tree_root[0][0]));
1605       if (!smc_tree_root[ix0])
1606         smc_tree_abort (errno);
1607     }
1608   entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
1609   if (!entry ||                                                                         /* need create */
1610       entry >= smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries ||   /* need append */
1611       entry->key != key)                                                                /* need insert */
1612     entry = smc_tree_branch_grow_L (&smc_tree_root[ix0][ix1], entry - smc_tree_root[ix0][ix1].entries);
1613   entry->key = key;
1614   entry->value = value;
1615   g_mutex_unlock (&smc_tree_mutex);
1616 }
1617
1618 static gboolean
1619 smc_tree_lookup (SmcKType  key,
1620                  SmcVType *value_p)
1621 {
1622   SmcEntry *entry = NULL;
1623   unsigned int ix0 = SMC_TRUNK_HASH (key), ix1 = SMC_BRANCH_HASH (key);
1624   gboolean found_one = FALSE;
1625   *value_p = 0;
1626   g_mutex_lock (&smc_tree_mutex);
1627   if (smc_tree_root && smc_tree_root[ix0])
1628     {
1629       entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
1630       if (entry &&
1631           entry < smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries &&
1632           entry->key == key)
1633         {
1634           found_one = TRUE;
1635           *value_p = entry->value;
1636         }
1637     }
1638   g_mutex_unlock (&smc_tree_mutex);
1639   return found_one;
1640 }
1641
1642 static gboolean
1643 smc_tree_remove (SmcKType key)
1644 {
1645   unsigned int ix0 = SMC_TRUNK_HASH (key), ix1 = SMC_BRANCH_HASH (key);
1646   gboolean found_one = FALSE;
1647   g_mutex_lock (&smc_tree_mutex);
1648   if (smc_tree_root && smc_tree_root[ix0])
1649     {
1650       SmcEntry *entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
1651       if (entry &&
1652           entry < smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries &&
1653           entry->key == key)
1654         {
1655           unsigned int i = entry - smc_tree_root[ix0][ix1].entries;
1656           smc_tree_root[ix0][ix1].n_entries -= 1;
1657           g_memmove (entry, entry + 1, (smc_tree_root[ix0][ix1].n_entries - i) * sizeof (entry[0]));
1658           if (!smc_tree_root[ix0][ix1].n_entries)
1659             {
1660               /* avoid useless pressure on the memory system */
1661               free (smc_tree_root[ix0][ix1].entries);
1662               smc_tree_root[ix0][ix1].entries = NULL;
1663             }
1664           found_one = TRUE;
1665         }
1666     }
1667   g_mutex_unlock (&smc_tree_mutex);
1668   return found_one;
1669 }
1670
1671 #ifdef G_ENABLE_DEBUG
1672 void
1673 g_slice_debug_tree_statistics (void)
1674 {
1675   g_mutex_lock (&smc_tree_mutex);
1676   if (smc_tree_root)
1677     {
1678       unsigned int i, j, t = 0, o = 0, b = 0, su = 0, ex = 0, en = 4294967295u;
1679       double tf, bf;
1680       for (i = 0; i < SMC_TRUNK_COUNT; i++)
1681         if (smc_tree_root[i])
1682           {
1683             t++;
1684             for (j = 0; j < SMC_BRANCH_COUNT; j++)
1685               if (smc_tree_root[i][j].n_entries)
1686                 {
1687                   b++;
1688                   su += smc_tree_root[i][j].n_entries;
1689                   en = MIN (en, smc_tree_root[i][j].n_entries);
1690                   ex = MAX (ex, smc_tree_root[i][j].n_entries);
1691                 }
1692               else if (smc_tree_root[i][j].entries)
1693                 o++; /* formerly used, now empty */
1694           }
1695       en = b ? en : 0;
1696       tf = MAX (t, 1.0); /* max(1) to be a valid divisor */
1697       bf = MAX (b, 1.0); /* max(1) to be a valid divisor */
1698       fprintf (stderr, "GSlice: MemChecker: %u trunks, %u branches, %u old branches\n", t, b, o);
1699       fprintf (stderr, "GSlice: MemChecker: %f branches per trunk, %.2f%% utilization\n",
1700                b / tf,
1701                100.0 - (SMC_BRANCH_COUNT - b / tf) / (0.01 * SMC_BRANCH_COUNT));
1702       fprintf (stderr, "GSlice: MemChecker: %f entries per branch, %u minimum, %u maximum\n",
1703                su / bf, en, ex);
1704     }
1705   else
1706     fprintf (stderr, "GSlice: MemChecker: root=NULL\n");
1707   g_mutex_unlock (&smc_tree_mutex);
1708   
1709   /* sample statistics (beast + GSLice + 24h scripted core & GUI activity):
1710    *  PID %CPU %MEM   VSZ  RSS      COMMAND
1711    * 8887 30.3 45.8 456068 414856   beast-0.7.1 empty.bse
1712    * $ cat /proc/8887/statm # total-program-size resident-set-size shared-pages text/code data/stack library dirty-pages
1713    * 114017 103714 2354 344 0 108676 0
1714    * $ cat /proc/8887/status 
1715    * Name:   beast-0.7.1
1716    * VmSize:   456068 kB
1717    * VmLck:         0 kB
1718    * VmRSS:    414856 kB
1719    * VmData:   434620 kB
1720    * VmStk:        84 kB
1721    * VmExe:      1376 kB
1722    * VmLib:     13036 kB
1723    * VmPTE:       456 kB
1724    * Threads:        3
1725    * (gdb) print g_slice_debug_tree_statistics ()
1726    * GSlice: MemChecker: 422 trunks, 213068 branches, 0 old branches
1727    * GSlice: MemChecker: 504.900474 branches per trunk, 98.81% utilization
1728    * GSlice: MemChecker: 4.965039 entries per branch, 1 minimum, 37 maximum
1729    */
1730 }
1731 #endif /* G_ENABLE_DEBUG */