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