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