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