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