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