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