1 /* GLIB sliced memory - fast concurrent memory chunk allocator
2 * Copyright (C) 2005 Tim Janik
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.
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.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
20 #include "glibconfig.h"
22 #if defined HAVE_POSIX_MEMALIGN && defined POSIX_MEMALIGN_WITH_COMPLIANT_ALLOCS
23 # define HAVE_COMPLIANT_POSIX_MEMALIGN 1
26 #if defined(HAVE_COMPLIANT_POSIX_MEMALIGN) && !defined(_XOPEN_SOURCE)
27 #define _XOPEN_SOURCE 600 /* posix_memalign() */
29 #include <stdlib.h> /* posix_memalign() */
34 #include <unistd.h> /* sysconf() */
41 #include <stdio.h> /* fputs/fprintf */
46 #include "gmem.h" /* gslice.h */
47 #include "gstrfuncs.h"
49 #include "gtrashstack.h"
50 #include "gtestutils.h"
52 #include "glib_trace.h"
57 * SECTION:memory_slices
58 * @title: Memory Slices
59 * @short_description: efficient way to allocate groups of equal-sized
62 * Memory slices provide a space-efficient and multi-processing scalable
63 * way to allocate equal-sized pieces of memory, just like the original
64 * #GMemChunks (from GLib 2.8), while avoiding their excessive
65 * memory-waste, scalability and performance problems.
67 * To achieve these goals, the slice allocator uses a sophisticated,
68 * layered design that has been inspired by Bonwick's slab allocator
69 * (<ulink url="http://citeseer.ist.psu.edu/bonwick94slab.html">[Bonwick94]</ulink> Jeff Bonwick, The slab allocator: An object-caching kernel
70 * memory allocator. USENIX 1994, and
71 * <ulink url="http://citeseer.ist.psu.edu/bonwick01magazines.html">[Bonwick01]</ulink> Bonwick and Jonathan Adams, Magazines and vmem: Extending the
72 * slab allocator to many cpu's and arbitrary resources. USENIX 2001)
74 * It uses posix_memalign() to optimize allocations of many equally-sized
75 * chunks, and has per-thread free lists (the so-called magazine layer)
76 * to quickly satisfy allocation requests of already known structure sizes.
77 * This is accompanied by extra caching logic to keep freed memory around
78 * for some time before returning it to the system. Memory that is unused
79 * due to alignment constraints is used for cache colorization (random
80 * distribution of chunk addresses) to improve CPU cache utilization. The
81 * caching layer of the slice allocator adapts itself to high lock contention
82 * to improve scalability.
84 * The slice allocator can allocate blocks as small as two pointers, and
85 * unlike malloc(), it does not reserve extra space per block. For large block
86 * sizes, g_slice_new() and g_slice_alloc() will automatically delegate to the
87 * system malloc() implementation. For newly written code it is recommended
88 * to use the new <literal>g_slice</literal> API instead of g_malloc() and
89 * friends, as long as objects are not resized during their lifetime and the
90 * object size used at allocation time is still available when freeing.
92 * Here is an example for using the slice allocator:
97 * /* Allocate 10000 blocks. */
98 * for (i = 0; i < 10000; i++)
100 * mem[i] = g_slice_alloc (50);
102 * /* Fill in the memory with some junk. */
103 * for (j = 0; j < 50; j++)
107 * /* Now free all of the blocks. */
108 * for (i = 0; i < 10000; i++)
109 * g_slice_free1 (50, mem[i]);
112 * And here is an example for using the using the slice allocator
113 * with data structures:
117 * /* Allocate one block, using the g_slice_new() macro. */
118 * array = g_slice_new (GRealArray);
120 * /* We can now use array just like a normal pointer to a structure. */
121 * array->data = NULL;
124 * array->zero_terminated = (zero_terminated ? 1 : 0);
125 * array->clear = (clear ? 1 : 0);
126 * array->elt_size = elt_size;
128 * /* We can free the block, so it can be reused. */
129 * g_slice_free (GRealArray, array);
133 /* the GSlice allocator is split up into 4 layers, roughly modelled after the slab
134 * allocator and magazine extensions as outlined in:
135 * + [Bonwick94] Jeff Bonwick, The slab allocator: An object-caching kernel
136 * memory allocator. USENIX 1994, http://citeseer.ist.psu.edu/bonwick94slab.html
137 * + [Bonwick01] Bonwick and Jonathan Adams, Magazines and vmem: Extending the
138 * slab allocator to many cpu's and arbitrary resources.
139 * USENIX 2001, http://citeseer.ist.psu.edu/bonwick01magazines.html
141 * - the thread magazines. for each (aligned) chunk size, a magazine (a list)
142 * of recently freed and soon to be allocated chunks is maintained per thread.
143 * this way, most alloc/free requests can be quickly satisfied from per-thread
144 * free lists which only require one g_private_get() call to retrive the
146 * - the magazine cache. allocating and freeing chunks to/from threads only
147 * occours at magazine sizes from a global depot of magazines. the depot
148 * maintaines a 15 second working set of allocated magazines, so full
149 * magazines are not allocated and released too often.
150 * the chunk size dependent magazine sizes automatically adapt (within limits,
151 * see [3]) to lock contention to properly scale performance across a variety
153 * - the slab allocator. this allocator allocates slabs (blocks of memory) close
154 * to the system page size or multiples thereof which have to be page aligned.
155 * the blocks are divided into smaller chunks which are used to satisfy
156 * allocations from the upper layers. the space provided by the reminder of
157 * the chunk size division is used for cache colorization (random distribution
158 * of chunk addresses) to improve processor cache utilization. multiple slabs
159 * with the same chunk size are kept in a partially sorted ring to allow O(1)
160 * freeing and allocation of chunks (as long as the allocation of an entirely
161 * new slab can be avoided).
162 * - the page allocator. on most modern systems, posix_memalign(3) or
163 * memalign(3) should be available, so this is used to allocate blocks with
164 * system page size based alignments and sizes or multiples thereof.
165 * if no memalign variant is provided, valloc() is used instead and
166 * block sizes are limited to the system page size (no multiples thereof).
167 * as a fallback, on system without even valloc(), a malloc(3)-based page
168 * allocator with alloc-only behaviour is used.
171 * [1] some systems memalign(3) implementations may rely on boundary tagging for
172 * the handed out memory chunks. to avoid excessive page-wise fragmentation,
173 * we reserve 2 * sizeof (void*) per block size for the systems memalign(3),
174 * specified in NATIVE_MALLOC_PADDING.
175 * [2] using the slab allocator alone already provides for a fast and efficient
176 * allocator, it doesn't properly scale beyond single-threaded uses though.
177 * also, the slab allocator implements eager free(3)-ing, i.e. does not
178 * provide any form of caching or working set maintenance. so if used alone,
179 * it's vulnerable to trashing for sequences of balanced (alloc, free) pairs
180 * at certain thresholds.
181 * [3] magazine sizes are bound by an implementation specific minimum size and
182 * a chunk size specific maximum to limit magazine storage sizes to roughly
184 * [4] allocating ca. 8 chunks per block/page keeps a good balance between
185 * external and internal fragmentation (<= 12.5%). [Bonwick94]
188 /* --- macros and constants --- */
189 #define LARGEALIGNMENT (256)
190 #define P2ALIGNMENT (2 * sizeof (gsize)) /* fits 2 pointers (assumed to be 2 * GLIB_SIZEOF_SIZE_T below) */
191 #define ALIGN(size, base) ((base) * (gsize) (((size) + (base) - 1) / (base)))
192 #define NATIVE_MALLOC_PADDING P2ALIGNMENT /* per-page padding left for native malloc(3) see [1] */
193 #define SLAB_INFO_SIZE P2ALIGN (sizeof (SlabInfo) + NATIVE_MALLOC_PADDING)
194 #define MAX_MAGAZINE_SIZE (256) /* see [3] and allocator_get_magazine_threshold() for this */
195 #define MIN_MAGAZINE_SIZE (4)
196 #define MAX_STAMP_COUNTER (7) /* distributes the load of gettimeofday() */
197 #define MAX_SLAB_CHUNK_SIZE(al) (((al)->max_page_size - SLAB_INFO_SIZE) / 8) /* we want at last 8 chunks per page, see [4] */
198 #define MAX_SLAB_INDEX(al) (SLAB_INDEX (al, MAX_SLAB_CHUNK_SIZE (al)) + 1)
199 #define SLAB_INDEX(al, asize) ((asize) / P2ALIGNMENT - 1) /* asize must be P2ALIGNMENT aligned */
200 #define SLAB_CHUNK_SIZE(al, ix) (((ix) + 1) * P2ALIGNMENT)
201 #define SLAB_BPAGE_SIZE(al,csz) (8 * (csz) + SLAB_INFO_SIZE)
203 /* optimized version of ALIGN (size, P2ALIGNMENT) */
204 #if GLIB_SIZEOF_SIZE_T * 2 == 8 /* P2ALIGNMENT */
205 #define P2ALIGN(size) (((size) + 0x7) & ~(gsize) 0x7)
206 #elif GLIB_SIZEOF_SIZE_T * 2 == 16 /* P2ALIGNMENT */
207 #define P2ALIGN(size) (((size) + 0xf) & ~(gsize) 0xf)
209 #define P2ALIGN(size) ALIGN (size, P2ALIGNMENT)
212 /* special helpers to avoid gmessage.c dependency */
213 static void mem_error (const char *format, ...) G_GNUC_PRINTF (1,2);
214 #define mem_assert(cond) do { if (G_LIKELY (cond)) ; else mem_error ("assertion failed: %s", #cond); } while (0)
216 /* --- structures --- */
217 typedef struct _ChunkLink ChunkLink;
218 typedef struct _SlabInfo SlabInfo;
219 typedef struct _CachedMagazine CachedMagazine;
227 SlabInfo *next, *prev;
231 gsize count; /* approximative chunks list length */
234 Magazine *magazine1; /* array of MAX_SLAB_INDEX (allocator) */
235 Magazine *magazine2; /* array of MAX_SLAB_INDEX (allocator) */
238 gboolean always_malloc;
239 gboolean bypass_magazines;
240 gboolean debug_blocks;
241 gsize working_set_msecs;
242 guint color_increment;
245 /* const after initialization */
246 gsize min_page_size, max_page_size;
248 gsize max_slab_chunk_size_for_magazine_cache;
250 GMutex magazine_mutex;
251 ChunkLink **magazines; /* array of MAX_SLAB_INDEX (allocator) */
252 guint *contention_counters; /* array of MAX_SLAB_INDEX (allocator) */
258 SlabInfo **slab_stack; /* array of MAX_SLAB_INDEX (allocator) */
262 /* --- g-slice prototypes --- */
263 static gpointer slab_allocator_alloc_chunk (gsize chunk_size);
264 static void slab_allocator_free_chunk (gsize chunk_size,
266 static void private_thread_memory_cleanup (gpointer data);
267 static gpointer allocator_memalign (gsize alignment,
269 static void allocator_memfree (gsize memsize,
271 static inline void magazine_cache_update_stamp (void);
272 static inline gsize allocator_get_magazine_threshold (Allocator *allocator,
275 /* --- g-slice memory checker --- */
276 static void smc_notify_alloc (void *pointer,
278 static int smc_notify_free (void *pointer,
281 /* --- variables --- */
282 static GPrivate private_thread_memory = G_PRIVATE_INIT (private_thread_memory_cleanup);
283 static gsize sys_page_size = 0;
284 static Allocator allocator[1] = { { 0, }, };
285 static SliceConfig slice_config = {
286 FALSE, /* always_malloc */
287 FALSE, /* bypass_magazines */
288 FALSE, /* debug_blocks */
289 15 * 1000, /* working_set_msecs */
290 1, /* color increment, alt: 0x7fffffff */
292 static GMutex smc_tree_mutex; /* mutex for G_SLICE=debug-blocks */
294 /* --- auxiliary funcitons --- */
296 g_slice_set_config (GSliceConfig ckey,
299 g_return_if_fail (sys_page_size == 0);
302 case G_SLICE_CONFIG_ALWAYS_MALLOC:
303 slice_config.always_malloc = value != 0;
305 case G_SLICE_CONFIG_BYPASS_MAGAZINES:
306 slice_config.bypass_magazines = value != 0;
308 case G_SLICE_CONFIG_WORKING_SET_MSECS:
309 slice_config.working_set_msecs = value;
311 case G_SLICE_CONFIG_COLOR_INCREMENT:
312 slice_config.color_increment = value;
318 g_slice_get_config (GSliceConfig ckey)
322 case G_SLICE_CONFIG_ALWAYS_MALLOC:
323 return slice_config.always_malloc;
324 case G_SLICE_CONFIG_BYPASS_MAGAZINES:
325 return slice_config.bypass_magazines;
326 case G_SLICE_CONFIG_WORKING_SET_MSECS:
327 return slice_config.working_set_msecs;
328 case G_SLICE_CONFIG_CHUNK_SIZES:
329 return MAX_SLAB_INDEX (allocator);
330 case G_SLICE_CONFIG_COLOR_INCREMENT:
331 return slice_config.color_increment;
338 g_slice_get_config_state (GSliceConfig ckey,
343 g_return_val_if_fail (n_values != NULL, NULL);
348 case G_SLICE_CONFIG_CONTENTION_COUNTER:
349 array[i++] = SLAB_CHUNK_SIZE (allocator, address);
350 array[i++] = allocator->contention_counters[address];
351 array[i++] = allocator_get_magazine_threshold (allocator, address);
353 return g_memdup (array, sizeof (array[0]) * *n_values);
360 slice_config_init (SliceConfig *config)
364 *config = slice_config;
366 val = getenv ("G_SLICE");
370 const GDebugKey keys[] = {
371 { "always-malloc", 1 << 0 },
372 { "debug-blocks", 1 << 1 },
375 flags = g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
376 if (flags & (1 << 0))
377 config->always_malloc = TRUE;
378 if (flags & (1 << 1))
379 config->debug_blocks = TRUE;
383 /* G_SLICE was not specified, so check if valgrind is running and
384 * disable ourselves if it is.
386 * This way it's possible to force gslice to be enabled under
387 * valgrind just by setting G_SLICE to the empty string.
389 if (RUNNING_ON_VALGRIND)
390 config->always_malloc = TRUE;
395 g_slice_init_nomessage (void)
397 /* we may not use g_error() or friends here */
398 mem_assert (sys_page_size == 0);
399 mem_assert (MIN_MAGAZINE_SIZE >= 4);
403 SYSTEM_INFO system_info;
404 GetSystemInfo (&system_info);
405 sys_page_size = system_info.dwPageSize;
408 sys_page_size = sysconf (_SC_PAGESIZE); /* = sysconf (_SC_PAGE_SIZE); = getpagesize(); */
410 mem_assert (sys_page_size >= 2 * LARGEALIGNMENT);
411 mem_assert ((sys_page_size & (sys_page_size - 1)) == 0);
412 slice_config_init (&allocator->config);
413 allocator->min_page_size = sys_page_size;
414 #if HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN
415 /* allow allocation of pages up to 8KB (with 8KB alignment).
416 * this is useful because many medium to large sized structures
417 * fit less than 8 times (see [4]) into 4KB pages.
418 * we allow very small page sizes here, to reduce wastage in
419 * threads if only small allocations are required (this does
420 * bear the risk of increasing allocation times and fragmentation
423 allocator->min_page_size = MAX (allocator->min_page_size, 4096);
424 allocator->max_page_size = MAX (allocator->min_page_size, 8192);
425 allocator->min_page_size = MIN (allocator->min_page_size, 128);
427 /* we can only align to system page size */
428 allocator->max_page_size = sys_page_size;
430 if (allocator->config.always_malloc)
432 allocator->contention_counters = NULL;
433 allocator->magazines = NULL;
434 allocator->slab_stack = NULL;
438 allocator->contention_counters = g_new0 (guint, MAX_SLAB_INDEX (allocator));
439 allocator->magazines = g_new0 (ChunkLink*, MAX_SLAB_INDEX (allocator));
440 allocator->slab_stack = g_new0 (SlabInfo*, MAX_SLAB_INDEX (allocator));
443 allocator->mutex_counter = 0;
444 allocator->stamp_counter = MAX_STAMP_COUNTER; /* force initial update */
445 allocator->last_stamp = 0;
446 allocator->color_accu = 0;
447 magazine_cache_update_stamp();
448 /* values cached for performance reasons */
449 allocator->max_slab_chunk_size_for_magazine_cache = MAX_SLAB_CHUNK_SIZE (allocator);
450 if (allocator->config.always_malloc || allocator->config.bypass_magazines)
451 allocator->max_slab_chunk_size_for_magazine_cache = 0; /* non-optimized cases */
455 allocator_categorize (gsize aligned_chunk_size)
457 /* speed up the likely path */
458 if (G_LIKELY (aligned_chunk_size && aligned_chunk_size <= allocator->max_slab_chunk_size_for_magazine_cache))
459 return 1; /* use magazine cache */
461 if (!allocator->config.always_malloc &&
462 aligned_chunk_size &&
463 aligned_chunk_size <= MAX_SLAB_CHUNK_SIZE (allocator))
465 if (allocator->config.bypass_magazines)
466 return 2; /* use slab allocator, see [2] */
467 return 1; /* use magazine cache */
469 return 0; /* use malloc() */
473 g_mutex_lock_a (GMutex *mutex,
474 guint *contention_counter)
476 gboolean contention = FALSE;
477 if (!g_mutex_trylock (mutex))
479 g_mutex_lock (mutex);
484 allocator->mutex_counter++;
485 if (allocator->mutex_counter >= 1) /* quickly adapt to contention */
487 allocator->mutex_counter = 0;
488 *contention_counter = MIN (*contention_counter + 1, MAX_MAGAZINE_SIZE);
491 else /* !contention */
493 allocator->mutex_counter--;
494 if (allocator->mutex_counter < -11) /* moderately recover magazine sizes */
496 allocator->mutex_counter = 0;
497 *contention_counter = MAX (*contention_counter, 1) - 1;
502 static inline ThreadMemory*
503 thread_memory_from_self (void)
505 ThreadMemory *tmem = g_private_get (&private_thread_memory);
506 if (G_UNLIKELY (!tmem))
508 static GMutex init_mutex;
511 g_mutex_lock (&init_mutex);
512 if G_UNLIKELY (sys_page_size == 0)
513 g_slice_init_nomessage ();
514 g_mutex_unlock (&init_mutex);
516 n_magazines = MAX_SLAB_INDEX (allocator);
517 tmem = g_malloc0 (sizeof (ThreadMemory) + sizeof (Magazine) * 2 * n_magazines);
518 tmem->magazine1 = (Magazine*) (tmem + 1);
519 tmem->magazine2 = &tmem->magazine1[n_magazines];
520 g_private_set (&private_thread_memory, tmem);
525 static inline ChunkLink*
526 magazine_chain_pop_head (ChunkLink **magazine_chunks)
528 /* magazine chains are linked via ChunkLink->next.
529 * each ChunkLink->data of the toplevel chain may point to a subchain,
530 * linked via ChunkLink->next. ChunkLink->data of the subchains just
531 * contains uninitialized junk.
533 ChunkLink *chunk = (*magazine_chunks)->data;
534 if (G_UNLIKELY (chunk))
536 /* allocating from freed list */
537 (*magazine_chunks)->data = chunk->next;
541 chunk = *magazine_chunks;
542 *magazine_chunks = chunk->next;
547 #if 0 /* useful for debugging */
549 magazine_count (ChunkLink *head)
556 ChunkLink *child = head->data;
558 for (child = head->data; child; child = child->next)
567 allocator_get_magazine_threshold (Allocator *allocator,
570 /* the magazine size calculated here has a lower bound of MIN_MAGAZINE_SIZE,
571 * which is required by the implementation. also, for moderately sized chunks
572 * (say >= 64 bytes), magazine sizes shouldn't be much smaller then the number
573 * of chunks available per page/2 to avoid excessive traffic in the magazine
574 * cache for small to medium sized structures.
575 * the upper bound of the magazine size is effectively provided by
576 * MAX_MAGAZINE_SIZE. for larger chunks, this number is scaled down so that
577 * the content of a single magazine doesn't exceed ca. 16KB.
579 gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
580 guint threshold = MAX (MIN_MAGAZINE_SIZE, allocator->max_page_size / MAX (5 * chunk_size, 5 * 32));
581 guint contention_counter = allocator->contention_counters[ix];
582 if (G_UNLIKELY (contention_counter)) /* single CPU bias */
584 /* adapt contention counter thresholds to chunk sizes */
585 contention_counter = contention_counter * 64 / chunk_size;
586 threshold = MAX (threshold, contention_counter);
591 /* --- magazine cache --- */
593 magazine_cache_update_stamp (void)
595 if (allocator->stamp_counter >= MAX_STAMP_COUNTER)
598 g_get_current_time (&tv);
599 allocator->last_stamp = tv.tv_sec * 1000 + tv.tv_usec / 1000; /* milli seconds */
600 allocator->stamp_counter = 0;
603 allocator->stamp_counter++;
606 static inline ChunkLink*
607 magazine_chain_prepare_fields (ChunkLink *magazine_chunks)
613 /* checked upon initialization: mem_assert (MIN_MAGAZINE_SIZE >= 4); */
614 /* ensure a magazine with at least 4 unused data pointers */
615 chunk1 = magazine_chain_pop_head (&magazine_chunks);
616 chunk2 = magazine_chain_pop_head (&magazine_chunks);
617 chunk3 = magazine_chain_pop_head (&magazine_chunks);
618 chunk4 = magazine_chain_pop_head (&magazine_chunks);
619 chunk4->next = magazine_chunks;
620 chunk3->next = chunk4;
621 chunk2->next = chunk3;
622 chunk1->next = chunk2;
626 /* access the first 3 fields of a specially prepared magazine chain */
627 #define magazine_chain_prev(mc) ((mc)->data)
628 #define magazine_chain_stamp(mc) ((mc)->next->data)
629 #define magazine_chain_uint_stamp(mc) GPOINTER_TO_UINT ((mc)->next->data)
630 #define magazine_chain_next(mc) ((mc)->next->next->data)
631 #define magazine_chain_count(mc) ((mc)->next->next->next->data)
634 magazine_cache_trim (Allocator *allocator,
638 /* g_mutex_lock (allocator->mutex); done by caller */
639 /* trim magazine cache from tail */
640 ChunkLink *current = magazine_chain_prev (allocator->magazines[ix]);
641 ChunkLink *trash = NULL;
642 while (ABS (stamp - magazine_chain_uint_stamp (current)) >= allocator->config.working_set_msecs)
645 ChunkLink *prev = magazine_chain_prev (current);
646 ChunkLink *next = magazine_chain_next (current);
647 magazine_chain_next (prev) = next;
648 magazine_chain_prev (next) = prev;
649 /* clear special fields, put on trash stack */
650 magazine_chain_next (current) = NULL;
651 magazine_chain_count (current) = NULL;
652 magazine_chain_stamp (current) = NULL;
653 magazine_chain_prev (current) = trash;
655 /* fixup list head if required */
656 if (current == allocator->magazines[ix])
658 allocator->magazines[ix] = NULL;
663 g_mutex_unlock (&allocator->magazine_mutex);
667 const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
668 g_mutex_lock (&allocator->slab_mutex);
672 trash = magazine_chain_prev (current);
673 magazine_chain_prev (current) = NULL; /* clear special field */
676 ChunkLink *chunk = magazine_chain_pop_head (¤t);
677 slab_allocator_free_chunk (chunk_size, chunk);
680 g_mutex_unlock (&allocator->slab_mutex);
685 magazine_cache_push_magazine (guint ix,
686 ChunkLink *magazine_chunks,
687 gsize count) /* must be >= MIN_MAGAZINE_SIZE */
689 ChunkLink *current = magazine_chain_prepare_fields (magazine_chunks);
690 ChunkLink *next, *prev;
691 g_mutex_lock (&allocator->magazine_mutex);
692 /* add magazine at head */
693 next = allocator->magazines[ix];
695 prev = magazine_chain_prev (next);
697 next = prev = current;
698 magazine_chain_next (prev) = current;
699 magazine_chain_prev (next) = current;
700 magazine_chain_prev (current) = prev;
701 magazine_chain_next (current) = next;
702 magazine_chain_count (current) = (gpointer) count;
704 magazine_cache_update_stamp();
705 magazine_chain_stamp (current) = GUINT_TO_POINTER (allocator->last_stamp);
706 allocator->magazines[ix] = current;
707 /* free old magazines beyond a certain threshold */
708 magazine_cache_trim (allocator, ix, allocator->last_stamp);
709 /* g_mutex_unlock (allocator->mutex); was done by magazine_cache_trim() */
713 magazine_cache_pop_magazine (guint ix,
716 g_mutex_lock_a (&allocator->magazine_mutex, &allocator->contention_counters[ix]);
717 if (!allocator->magazines[ix])
719 guint magazine_threshold = allocator_get_magazine_threshold (allocator, ix);
720 gsize i, chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
721 ChunkLink *chunk, *head;
722 g_mutex_unlock (&allocator->magazine_mutex);
723 g_mutex_lock (&allocator->slab_mutex);
724 head = slab_allocator_alloc_chunk (chunk_size);
727 for (i = 1; i < magazine_threshold; i++)
729 chunk->next = slab_allocator_alloc_chunk (chunk_size);
734 g_mutex_unlock (&allocator->slab_mutex);
740 ChunkLink *current = allocator->magazines[ix];
741 ChunkLink *prev = magazine_chain_prev (current);
742 ChunkLink *next = magazine_chain_next (current);
744 magazine_chain_next (prev) = next;
745 magazine_chain_prev (next) = prev;
746 allocator->magazines[ix] = next == current ? NULL : next;
747 g_mutex_unlock (&allocator->magazine_mutex);
748 /* clear special fields and hand out */
749 *countp = (gsize) magazine_chain_count (current);
750 magazine_chain_prev (current) = NULL;
751 magazine_chain_next (current) = NULL;
752 magazine_chain_count (current) = NULL;
753 magazine_chain_stamp (current) = NULL;
758 /* --- thread magazines --- */
760 private_thread_memory_cleanup (gpointer data)
762 ThreadMemory *tmem = data;
763 const guint n_magazines = MAX_SLAB_INDEX (allocator);
765 for (ix = 0; ix < n_magazines; ix++)
769 mags[0] = &tmem->magazine1[ix];
770 mags[1] = &tmem->magazine2[ix];
771 for (j = 0; j < 2; j++)
773 Magazine *mag = mags[j];
774 if (mag->count >= MIN_MAGAZINE_SIZE)
775 magazine_cache_push_magazine (ix, mag->chunks, mag->count);
778 const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
779 g_mutex_lock (&allocator->slab_mutex);
782 ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
783 slab_allocator_free_chunk (chunk_size, chunk);
785 g_mutex_unlock (&allocator->slab_mutex);
793 thread_memory_magazine1_reload (ThreadMemory *tmem,
796 Magazine *mag = &tmem->magazine1[ix];
797 mem_assert (mag->chunks == NULL); /* ensure that we may reset mag->count */
799 mag->chunks = magazine_cache_pop_magazine (ix, &mag->count);
803 thread_memory_magazine2_unload (ThreadMemory *tmem,
806 Magazine *mag = &tmem->magazine2[ix];
807 magazine_cache_push_magazine (ix, mag->chunks, mag->count);
813 thread_memory_swap_magazines (ThreadMemory *tmem,
816 Magazine xmag = tmem->magazine1[ix];
817 tmem->magazine1[ix] = tmem->magazine2[ix];
818 tmem->magazine2[ix] = xmag;
821 static inline gboolean
822 thread_memory_magazine1_is_empty (ThreadMemory *tmem,
825 return tmem->magazine1[ix].chunks == NULL;
828 static inline gboolean
829 thread_memory_magazine2_is_full (ThreadMemory *tmem,
832 return tmem->magazine2[ix].count >= allocator_get_magazine_threshold (allocator, ix);
835 static inline gpointer
836 thread_memory_magazine1_alloc (ThreadMemory *tmem,
839 Magazine *mag = &tmem->magazine1[ix];
840 ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
841 if (G_LIKELY (mag->count > 0))
847 thread_memory_magazine2_free (ThreadMemory *tmem,
851 Magazine *mag = &tmem->magazine2[ix];
852 ChunkLink *chunk = mem;
854 chunk->next = mag->chunks;
859 /* --- API functions --- */
863 * @type: the type to allocate, typically a structure name
865 * A convenience macro to allocate a block of memory from the
868 * It calls g_slice_alloc() with <literal>sizeof (@type)</literal>
869 * and casts the returned pointer to a pointer of the given type,
870 * avoiding a type cast in the source code.
871 * Note that the underlying slice allocation mechanism can
872 * be changed with the <link linkend="G_SLICE">G_SLICE=always-malloc</link>
873 * environment variable.
875 * Returns: a pointer to the allocated block, cast to a pointer to @type
882 * @type: the type to allocate, typically a structure name
884 * A convenience macro to allocate a block of memory from the
885 * slice allocator and set the memory to 0.
887 * It calls g_slice_alloc0() with <literal>sizeof (@type)</literal>
888 * and casts the returned pointer to a pointer of the given type,
889 * avoiding a type cast in the source code.
890 * Note that the underlying slice allocation mechanism can
891 * be changed with the <link linkend="G_SLICE">G_SLICE=always-malloc</link>
892 * environment variable.
899 * @type: the type to duplicate, typically a structure name
900 * @mem: the memory to copy into the allocated block
902 * A convenience macro to duplicate a block of memory using
903 * the slice allocator.
905 * It calls g_slice_copy() with <literal>sizeof (@type)</literal>
906 * and casts the returned pointer to a pointer of the given type,
907 * avoiding a type cast in the source code.
908 * Note that the underlying slice allocation mechanism can
909 * be changed with the <link linkend="G_SLICE">G_SLICE=always-malloc</link>
910 * environment variable.
912 * Returns: a pointer to the allocated block, cast to a pointer to @type
919 * @type: the type of the block to free, typically a structure name
920 * @mem: a pointer to the block to free
922 * A convenience macro to free a block of memory that has
923 * been allocated from the slice allocator.
925 * It calls g_slice_free1() using <literal>sizeof (type)</literal>
927 * Note that the exact release behaviour can be changed with the
928 * <link linkend="G_DEBUG">G_DEBUG=gc-friendly</link> environment
929 * variable, also see <link linkend="G_SLICE">G_SLICE</link> for
930 * related debugging options.
936 * g_slice_free_chain:
937 * @type: the type of the @mem_chain blocks
938 * @mem_chain: a pointer to the first block of the chain
939 * @next: the field name of the next pointer in @type
941 * Frees a linked list of memory blocks of structure type @type.
942 * The memory blocks must be equal-sized, allocated via
943 * g_slice_alloc() or g_slice_alloc0() and linked together by
944 * a @next pointer (similar to #GSList). The name of the
945 * @next field in @type is passed as third argument.
946 * Note that the exact release behaviour can be changed with the
947 * <link linkend="G_DEBUG">G_DEBUG=gc-friendly</link> environment
948 * variable, also see <link linkend="G_SLICE">G_SLICE</link> for
949 * related debugging options.
956 * @block_size: the number of bytes to allocate
958 * Allocates a block of memory from the slice allocator.
959 * The block adress handed out can be expected to be aligned
960 * to at least <literal>1 * sizeof (void*)</literal>,
961 * though in general slices are 2 * sizeof (void*) bytes aligned,
962 * if a malloc() fallback implementation is used instead,
963 * the alignment may be reduced in a libc dependent fashion.
964 * Note that the underlying slice allocation mechanism can
965 * be changed with the <link linkend="G_SLICE">G_SLICE=always-malloc</link>
966 * environment variable.
968 * Returns: a pointer to the allocated memory block
973 g_slice_alloc (gsize mem_size)
980 /* This gets the private structure for this thread. If the private
981 * structure does not yet exist, it is created.
983 * This has a side effect of causing GSlice to be initialised, so it
986 tmem = thread_memory_from_self ();
988 chunk_size = P2ALIGN (mem_size);
989 acat = allocator_categorize (chunk_size);
990 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
992 guint ix = SLAB_INDEX (allocator, chunk_size);
993 if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
995 thread_memory_swap_magazines (tmem, ix);
996 if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
997 thread_memory_magazine1_reload (tmem, ix);
999 mem = thread_memory_magazine1_alloc (tmem, ix);
1001 else if (acat == 2) /* allocate through slab allocator */
1003 g_mutex_lock (&allocator->slab_mutex);
1004 mem = slab_allocator_alloc_chunk (chunk_size);
1005 g_mutex_unlock (&allocator->slab_mutex);
1007 else /* delegate to system malloc */
1008 mem = g_malloc (mem_size);
1009 if (G_UNLIKELY (allocator->config.debug_blocks))
1010 smc_notify_alloc (mem, mem_size);
1012 TRACE (GLIB_SLICE_ALLOC((void*)mem, mem_size));
1019 * @block_size: the number of bytes to allocate
1021 * Allocates a block of memory via g_slice_alloc() and initializes
1022 * the returned memory to 0. Note that the underlying slice allocation
1023 * mechanism can be changed with the
1024 * <link linkend="G_SLICE">G_SLICE=always-malloc</link>
1025 * environment variable.
1027 * Returns: a pointer to the allocated block
1032 g_slice_alloc0 (gsize mem_size)
1034 gpointer mem = g_slice_alloc (mem_size);
1036 memset (mem, 0, mem_size);
1042 * @block_size: the number of bytes to allocate
1043 * @mem_block: the memory to copy
1045 * Allocates a block of memory from the slice allocator
1046 * and copies @block_size bytes into it from @mem_block.
1048 * Returns: a pointer to the allocated memory block
1053 g_slice_copy (gsize mem_size,
1054 gconstpointer mem_block)
1056 gpointer mem = g_slice_alloc (mem_size);
1058 memcpy (mem, mem_block, mem_size);
1064 * @block_size: the size of the block
1065 * @mem_block: a pointer to the block to free
1067 * Frees a block of memory.
1069 * The memory must have been allocated via g_slice_alloc() or
1070 * g_slice_alloc0() and the @block_size has to match the size
1071 * specified upon allocation. Note that the exact release behaviour
1072 * can be changed with the
1073 * <link linkend="G_DEBUG">G_DEBUG=gc-friendly</link> environment
1074 * variable, also see <link linkend="G_SLICE">G_SLICE</link> for
1075 * related debugging options.
1080 g_slice_free1 (gsize mem_size,
1083 gsize chunk_size = P2ALIGN (mem_size);
1084 guint acat = allocator_categorize (chunk_size);
1085 if (G_UNLIKELY (!mem_block))
1087 if (G_UNLIKELY (allocator->config.debug_blocks) &&
1088 !smc_notify_free (mem_block, mem_size))
1090 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
1092 ThreadMemory *tmem = thread_memory_from_self();
1093 guint ix = SLAB_INDEX (allocator, chunk_size);
1094 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
1096 thread_memory_swap_magazines (tmem, ix);
1097 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
1098 thread_memory_magazine2_unload (tmem, ix);
1100 if (G_UNLIKELY (g_mem_gc_friendly))
1101 memset (mem_block, 0, chunk_size);
1102 thread_memory_magazine2_free (tmem, ix, mem_block);
1104 else if (acat == 2) /* allocate through slab allocator */
1106 if (G_UNLIKELY (g_mem_gc_friendly))
1107 memset (mem_block, 0, chunk_size);
1108 g_mutex_lock (&allocator->slab_mutex);
1109 slab_allocator_free_chunk (chunk_size, mem_block);
1110 g_mutex_unlock (&allocator->slab_mutex);
1112 else /* delegate to system malloc */
1114 if (G_UNLIKELY (g_mem_gc_friendly))
1115 memset (mem_block, 0, mem_size);
1118 TRACE (GLIB_SLICE_FREE((void*)mem_block, mem_size));
1122 * g_slice_free_chain_with_offset:
1123 * @block_size: the size of the blocks
1124 * @mem_chain: a pointer to the first block of the chain
1125 * @next_offset: the offset of the @next field in the blocks
1127 * Frees a linked list of memory blocks of structure type @type.
1129 * The memory blocks must be equal-sized, allocated via
1130 * g_slice_alloc() or g_slice_alloc0() and linked together by a
1131 * @next pointer (similar to #GSList). The offset of the @next
1132 * field in each block is passed as third argument.
1133 * Note that the exact release behaviour can be changed with the
1134 * <link linkend="G_DEBUG">G_DEBUG=gc-friendly</link> environment
1135 * variable, also see <link linkend="G_SLICE">G_SLICE</link> for
1136 * related debugging options.
1141 g_slice_free_chain_with_offset (gsize mem_size,
1145 gpointer slice = mem_chain;
1146 /* while the thread magazines and the magazine cache are implemented so that
1147 * they can easily be extended to allow for free lists containing more free
1148 * lists for the first level nodes, which would allow O(1) freeing in this
1149 * function, the benefit of such an extension is questionable, because:
1150 * - the magazine size counts will become mere lower bounds which confuses
1151 * the code adapting to lock contention;
1152 * - freeing a single node to the thread magazines is very fast, so this
1153 * O(list_length) operation is multiplied by a fairly small factor;
1154 * - memory usage histograms on larger applications seem to indicate that
1155 * the amount of released multi node lists is negligible in comparison
1156 * to single node releases.
1157 * - the major performance bottle neck, namely g_private_get() or
1158 * g_mutex_lock()/g_mutex_unlock() has already been moved out of the
1159 * inner loop for freeing chained slices.
1161 gsize chunk_size = P2ALIGN (mem_size);
1162 guint acat = allocator_categorize (chunk_size);
1163 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
1165 ThreadMemory *tmem = thread_memory_from_self();
1166 guint ix = SLAB_INDEX (allocator, chunk_size);
1169 guint8 *current = slice;
1170 slice = *(gpointer*) (current + next_offset);
1171 if (G_UNLIKELY (allocator->config.debug_blocks) &&
1172 !smc_notify_free (current, mem_size))
1174 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
1176 thread_memory_swap_magazines (tmem, ix);
1177 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
1178 thread_memory_magazine2_unload (tmem, ix);
1180 if (G_UNLIKELY (g_mem_gc_friendly))
1181 memset (current, 0, chunk_size);
1182 thread_memory_magazine2_free (tmem, ix, current);
1185 else if (acat == 2) /* allocate through slab allocator */
1187 g_mutex_lock (&allocator->slab_mutex);
1190 guint8 *current = slice;
1191 slice = *(gpointer*) (current + next_offset);
1192 if (G_UNLIKELY (allocator->config.debug_blocks) &&
1193 !smc_notify_free (current, mem_size))
1195 if (G_UNLIKELY (g_mem_gc_friendly))
1196 memset (current, 0, chunk_size);
1197 slab_allocator_free_chunk (chunk_size, current);
1199 g_mutex_unlock (&allocator->slab_mutex);
1201 else /* delegate to system malloc */
1204 guint8 *current = slice;
1205 slice = *(gpointer*) (current + next_offset);
1206 if (G_UNLIKELY (allocator->config.debug_blocks) &&
1207 !smc_notify_free (current, mem_size))
1209 if (G_UNLIKELY (g_mem_gc_friendly))
1210 memset (current, 0, mem_size);
1215 /* --- single page allocator --- */
1217 allocator_slab_stack_push (Allocator *allocator,
1221 /* insert slab at slab ring head */
1222 if (!allocator->slab_stack[ix])
1224 sinfo->next = sinfo;
1225 sinfo->prev = sinfo;
1229 SlabInfo *next = allocator->slab_stack[ix], *prev = next->prev;
1235 allocator->slab_stack[ix] = sinfo;
1239 allocator_aligned_page_size (Allocator *allocator,
1242 gsize val = 1 << g_bit_storage (n_bytes - 1);
1243 val = MAX (val, allocator->min_page_size);
1248 allocator_add_slab (Allocator *allocator,
1254 gsize addr, padding, n_chunks, color = 0;
1255 gsize page_size = allocator_aligned_page_size (allocator, SLAB_BPAGE_SIZE (allocator, chunk_size));
1256 /* allocate 1 page for the chunks and the slab */
1257 gpointer aligned_memory = allocator_memalign (page_size, page_size - NATIVE_MALLOC_PADDING);
1258 guint8 *mem = aligned_memory;
1262 const gchar *syserr = strerror (errno);
1263 mem_error ("failed to allocate %u bytes (alignment: %u): %s\n",
1264 (guint) (page_size - NATIVE_MALLOC_PADDING), (guint) page_size, syserr);
1266 /* mask page address */
1267 addr = ((gsize) mem / page_size) * page_size;
1268 /* assert alignment */
1269 mem_assert (aligned_memory == (gpointer) addr);
1270 /* basic slab info setup */
1271 sinfo = (SlabInfo*) (mem + page_size - SLAB_INFO_SIZE);
1272 sinfo->n_allocated = 0;
1273 sinfo->chunks = NULL;
1274 /* figure cache colorization */
1275 n_chunks = ((guint8*) sinfo - mem) / chunk_size;
1276 padding = ((guint8*) sinfo - mem) - n_chunks * chunk_size;
1279 color = (allocator->color_accu * P2ALIGNMENT) % padding;
1280 allocator->color_accu += allocator->config.color_increment;
1282 /* add chunks to free list */
1283 chunk = (ChunkLink*) (mem + color);
1284 sinfo->chunks = chunk;
1285 for (i = 0; i < n_chunks - 1; i++)
1287 chunk->next = (ChunkLink*) ((guint8*) chunk + chunk_size);
1288 chunk = chunk->next;
1290 chunk->next = NULL; /* last chunk */
1291 /* add slab to slab ring */
1292 allocator_slab_stack_push (allocator, ix, sinfo);
1296 slab_allocator_alloc_chunk (gsize chunk_size)
1299 guint ix = SLAB_INDEX (allocator, chunk_size);
1300 /* ensure non-empty slab */
1301 if (!allocator->slab_stack[ix] || !allocator->slab_stack[ix]->chunks)
1302 allocator_add_slab (allocator, ix, chunk_size);
1303 /* allocate chunk */
1304 chunk = allocator->slab_stack[ix]->chunks;
1305 allocator->slab_stack[ix]->chunks = chunk->next;
1306 allocator->slab_stack[ix]->n_allocated++;
1307 /* rotate empty slabs */
1308 if (!allocator->slab_stack[ix]->chunks)
1309 allocator->slab_stack[ix] = allocator->slab_stack[ix]->next;
1314 slab_allocator_free_chunk (gsize chunk_size,
1319 guint ix = SLAB_INDEX (allocator, chunk_size);
1320 gsize page_size = allocator_aligned_page_size (allocator, SLAB_BPAGE_SIZE (allocator, chunk_size));
1321 gsize addr = ((gsize) mem / page_size) * page_size;
1322 /* mask page address */
1323 guint8 *page = (guint8*) addr;
1324 SlabInfo *sinfo = (SlabInfo*) (page + page_size - SLAB_INFO_SIZE);
1325 /* assert valid chunk count */
1326 mem_assert (sinfo->n_allocated > 0);
1327 /* add chunk to free list */
1328 was_empty = sinfo->chunks == NULL;
1329 chunk = (ChunkLink*) mem;
1330 chunk->next = sinfo->chunks;
1331 sinfo->chunks = chunk;
1332 sinfo->n_allocated--;
1333 /* keep slab ring partially sorted, empty slabs at end */
1337 SlabInfo *next = sinfo->next, *prev = sinfo->prev;
1340 if (allocator->slab_stack[ix] == sinfo)
1341 allocator->slab_stack[ix] = next == sinfo ? NULL : next;
1342 /* insert slab at head */
1343 allocator_slab_stack_push (allocator, ix, sinfo);
1345 /* eagerly free complete unused slabs */
1346 if (!sinfo->n_allocated)
1349 SlabInfo *next = sinfo->next, *prev = sinfo->prev;
1352 if (allocator->slab_stack[ix] == sinfo)
1353 allocator->slab_stack[ix] = next == sinfo ? NULL : next;
1355 allocator_memfree (page_size, page);
1359 /* --- memalign implementation --- */
1360 #ifdef HAVE_MALLOC_H
1361 #include <malloc.h> /* memalign() */
1365 * define HAVE_POSIX_MEMALIGN 1 // if free(posix_memalign(3)) works, <stdlib.h>
1366 * define HAVE_COMPLIANT_POSIX_MEMALIGN 1 // if free(posix_memalign(3)) works for sizes != 2^n, <stdlib.h>
1367 * define HAVE_MEMALIGN 1 // if free(memalign(3)) works, <malloc.h>
1368 * define HAVE_VALLOC 1 // if free(valloc(3)) works, <stdlib.h> or <malloc.h>
1369 * if none is provided, we implement malloc(3)-based alloc-only page alignment
1372 #if !(HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC)
1373 static GTrashStack *compat_valloc_trash = NULL;
1377 allocator_memalign (gsize alignment,
1380 gpointer aligned_memory = NULL;
1382 #if HAVE_COMPLIANT_POSIX_MEMALIGN
1383 err = posix_memalign (&aligned_memory, alignment, memsize);
1386 aligned_memory = memalign (alignment, memsize);
1390 aligned_memory = valloc (memsize);
1393 /* simplistic non-freeing page allocator */
1394 mem_assert (alignment == sys_page_size);
1395 mem_assert (memsize <= sys_page_size);
1396 if (!compat_valloc_trash)
1398 const guint n_pages = 16;
1399 guint8 *mem = malloc (n_pages * sys_page_size);
1404 guint8 *amem = (guint8*) ALIGN ((gsize) mem, sys_page_size);
1406 i--; /* mem wasn't page aligned */
1408 g_trash_stack_push (&compat_valloc_trash, amem + i * sys_page_size);
1411 aligned_memory = g_trash_stack_pop (&compat_valloc_trash);
1413 if (!aligned_memory)
1415 return aligned_memory;
1419 allocator_memfree (gsize memsize,
1422 #if HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC
1425 mem_assert (memsize <= sys_page_size);
1426 g_trash_stack_push (&compat_valloc_trash, mem);
1431 mem_error (const char *format,
1436 /* at least, put out "MEMORY-ERROR", in case we segfault during the rest of the function */
1437 fputs ("\n***MEMORY-ERROR***: ", stderr);
1438 pname = g_get_prgname();
1439 fprintf (stderr, "%s[%ld]: GSlice: ", pname ? pname : "", (long)getpid());
1440 va_start (args, format);
1441 vfprintf (stderr, format, args);
1443 fputs ("\n", stderr);
1448 /* --- g-slice memory checker tree --- */
1449 typedef size_t SmcKType; /* key type */
1450 typedef size_t SmcVType; /* value type */
1455 static void smc_tree_insert (SmcKType key,
1457 static gboolean smc_tree_lookup (SmcKType key,
1459 static gboolean smc_tree_remove (SmcKType key);
1462 /* --- g-slice memory checker implementation --- */
1464 smc_notify_alloc (void *pointer,
1467 size_t adress = (size_t) pointer;
1469 smc_tree_insert (adress, size);
1474 smc_notify_ignore (void *pointer)
1476 size_t adress = (size_t) pointer;
1478 smc_tree_remove (adress);
1483 smc_notify_free (void *pointer,
1486 size_t adress = (size_t) pointer;
1491 return 1; /* ignore */
1492 found_one = smc_tree_lookup (adress, &real_size);
1495 fprintf (stderr, "GSlice: MemChecker: attempt to release non-allocated block: %p size=%" G_GSIZE_FORMAT "\n", pointer, size);
1498 if (real_size != size && (real_size || size))
1500 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);
1503 if (!smc_tree_remove (adress))
1505 fprintf (stderr, "GSlice: MemChecker: attempt to release non-allocated block: %p size=%" G_GSIZE_FORMAT "\n", pointer, size);
1508 return 1; /* all fine */
1511 /* --- g-slice memory checker tree implementation --- */
1512 #define SMC_TRUNK_COUNT (4093 /* 16381 */) /* prime, to distribute trunk collisions (big, allocated just once) */
1513 #define SMC_BRANCH_COUNT (511) /* prime, to distribute branch collisions */
1514 #define SMC_TRUNK_EXTENT (SMC_BRANCH_COUNT * 2039) /* key address space per trunk, should distribute uniformly across BRANCH_COUNT */
1515 #define SMC_TRUNK_HASH(k) ((k / SMC_TRUNK_EXTENT) % SMC_TRUNK_COUNT) /* generate new trunk hash per megabyte (roughly) */
1516 #define SMC_BRANCH_HASH(k) (k % SMC_BRANCH_COUNT)
1520 unsigned int n_entries;
1523 static SmcBranch **smc_tree_root = NULL;
1526 smc_tree_abort (int errval)
1528 const char *syserr = strerror (errval);
1529 mem_error ("MemChecker: failure in debugging tree: %s", syserr);
1532 static inline SmcEntry*
1533 smc_tree_branch_grow_L (SmcBranch *branch,
1536 unsigned int old_size = branch->n_entries * sizeof (branch->entries[0]);
1537 unsigned int new_size = old_size + sizeof (branch->entries[0]);
1539 mem_assert (index <= branch->n_entries);
1540 branch->entries = (SmcEntry*) realloc (branch->entries, new_size);
1541 if (!branch->entries)
1542 smc_tree_abort (errno);
1543 entry = branch->entries + index;
1544 memmove (entry + 1, entry, (branch->n_entries - index) * sizeof (entry[0]));
1545 branch->n_entries += 1;
1549 static inline SmcEntry*
1550 smc_tree_branch_lookup_nearest_L (SmcBranch *branch,
1553 unsigned int n_nodes = branch->n_entries, offs = 0;
1554 SmcEntry *check = branch->entries;
1556 while (offs < n_nodes)
1558 unsigned int i = (offs + n_nodes) >> 1;
1559 check = branch->entries + i;
1560 cmp = key < check->key ? -1 : key != check->key;
1562 return check; /* return exact match */
1565 else /* (cmp > 0) */
1568 /* check points at last mismatch, cmp > 0 indicates greater key */
1569 return cmp > 0 ? check + 1 : check; /* return insertion position for inexact match */
1573 smc_tree_insert (SmcKType key,
1576 unsigned int ix0, ix1;
1579 g_mutex_lock (&smc_tree_mutex);
1580 ix0 = SMC_TRUNK_HASH (key);
1581 ix1 = SMC_BRANCH_HASH (key);
1584 smc_tree_root = calloc (SMC_TRUNK_COUNT, sizeof (smc_tree_root[0]));
1586 smc_tree_abort (errno);
1588 if (!smc_tree_root[ix0])
1590 smc_tree_root[ix0] = calloc (SMC_BRANCH_COUNT, sizeof (smc_tree_root[0][0]));
1591 if (!smc_tree_root[ix0])
1592 smc_tree_abort (errno);
1594 entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
1595 if (!entry || /* need create */
1596 entry >= smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries || /* need append */
1597 entry->key != key) /* need insert */
1598 entry = smc_tree_branch_grow_L (&smc_tree_root[ix0][ix1], entry - smc_tree_root[ix0][ix1].entries);
1600 entry->value = value;
1601 g_mutex_unlock (&smc_tree_mutex);
1605 smc_tree_lookup (SmcKType key,
1608 SmcEntry *entry = NULL;
1609 unsigned int ix0 = SMC_TRUNK_HASH (key), ix1 = SMC_BRANCH_HASH (key);
1610 gboolean found_one = FALSE;
1612 g_mutex_lock (&smc_tree_mutex);
1613 if (smc_tree_root && smc_tree_root[ix0])
1615 entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
1617 entry < smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries &&
1621 *value_p = entry->value;
1624 g_mutex_unlock (&smc_tree_mutex);
1629 smc_tree_remove (SmcKType key)
1631 unsigned int ix0 = SMC_TRUNK_HASH (key), ix1 = SMC_BRANCH_HASH (key);
1632 gboolean found_one = FALSE;
1633 g_mutex_lock (&smc_tree_mutex);
1634 if (smc_tree_root && smc_tree_root[ix0])
1636 SmcEntry *entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
1638 entry < smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries &&
1641 unsigned int i = entry - smc_tree_root[ix0][ix1].entries;
1642 smc_tree_root[ix0][ix1].n_entries -= 1;
1643 memmove (entry, entry + 1, (smc_tree_root[ix0][ix1].n_entries - i) * sizeof (entry[0]));
1644 if (!smc_tree_root[ix0][ix1].n_entries)
1646 /* avoid useless pressure on the memory system */
1647 free (smc_tree_root[ix0][ix1].entries);
1648 smc_tree_root[ix0][ix1].entries = NULL;
1653 g_mutex_unlock (&smc_tree_mutex);
1657 #ifdef G_ENABLE_DEBUG
1659 g_slice_debug_tree_statistics (void)
1661 g_mutex_lock (&smc_tree_mutex);
1664 unsigned int i, j, t = 0, o = 0, b = 0, su = 0, ex = 0, en = 4294967295u;
1666 for (i = 0; i < SMC_TRUNK_COUNT; i++)
1667 if (smc_tree_root[i])
1670 for (j = 0; j < SMC_BRANCH_COUNT; j++)
1671 if (smc_tree_root[i][j].n_entries)
1674 su += smc_tree_root[i][j].n_entries;
1675 en = MIN (en, smc_tree_root[i][j].n_entries);
1676 ex = MAX (ex, smc_tree_root[i][j].n_entries);
1678 else if (smc_tree_root[i][j].entries)
1679 o++; /* formerly used, now empty */
1682 tf = MAX (t, 1.0); /* max(1) to be a valid divisor */
1683 bf = MAX (b, 1.0); /* max(1) to be a valid divisor */
1684 fprintf (stderr, "GSlice: MemChecker: %u trunks, %u branches, %u old branches\n", t, b, o);
1685 fprintf (stderr, "GSlice: MemChecker: %f branches per trunk, %.2f%% utilization\n",
1687 100.0 - (SMC_BRANCH_COUNT - b / tf) / (0.01 * SMC_BRANCH_COUNT));
1688 fprintf (stderr, "GSlice: MemChecker: %f entries per branch, %u minimum, %u maximum\n",
1692 fprintf (stderr, "GSlice: MemChecker: root=NULL\n");
1693 g_mutex_unlock (&smc_tree_mutex);
1695 /* sample statistics (beast + GSLice + 24h scripted core & GUI activity):
1696 * PID %CPU %MEM VSZ RSS COMMAND
1697 * 8887 30.3 45.8 456068 414856 beast-0.7.1 empty.bse
1698 * $ cat /proc/8887/statm # total-program-size resident-set-size shared-pages text/code data/stack library dirty-pages
1699 * 114017 103714 2354 344 0 108676 0
1700 * $ cat /proc/8887/status
1711 * (gdb) print g_slice_debug_tree_statistics ()
1712 * GSlice: MemChecker: 422 trunks, 213068 branches, 0 old branches
1713 * GSlice: MemChecker: 504.900474 branches per trunk, 98.81% utilization
1714 * GSlice: MemChecker: 4.965039 entries per branch, 1 minimum, 37 maximum
1717 #endif /* G_ENABLE_DEBUG */