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