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