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