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