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