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