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, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
22 #include "glibconfig.h"
24 #if defined HAVE_POSIX_MEMALIGN && defined POSIX_MEMALIGN_WITH_COMPLIANT_ALLOCS
25 # define HAVE_COMPLIANT_POSIX_MEMALIGN 1
28 #if defined(HAVE_COMPLIANT_POSIX_MEMALIGN) && !defined(_XOPEN_SOURCE)
29 #define _XOPEN_SOURCE 600 /* posix_memalign() */
31 #include <stdlib.h> /* posix_memalign() */
36 #include <unistd.h> /* sysconf() */
43 #include <stdio.h> /* fputs/fprintf */
48 #include "gmem.h" /* gslice.h */
49 #include "gstrfuncs.h"
51 #include "gtrashstack.h"
52 #include "gtestutils.h"
54 #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
70 * <ulink url="http://citeseer.ist.psu.edu/bonwick94slab.html">[Bonwick94]</ulink> Jeff Bonwick, The slab allocator: An object-caching kernel
71 * memory allocator. USENIX 1994, and
72 * <ulink url="http://citeseer.ist.psu.edu/bonwick01magazines.html">[Bonwick01]</ulink> Bonwick and Jonathan Adams, Magazines and vmem: Extending the
73 * slab allocator to many cpu's and arbitrary resources. USENIX 2001
75 * It uses posix_memalign() to optimize allocations of many equally-sized
76 * chunks, and has per-thread free lists (the so-called magazine layer)
77 * to quickly satisfy allocation requests of already known structure sizes.
78 * This is accompanied by extra caching logic to keep freed memory around
79 * for some time before returning it to the system. Memory that is unused
80 * due to alignment constraints is used for cache colorization (random
81 * distribution of chunk addresses) to improve CPU cache utilization. The
82 * caching layer of the slice allocator adapts itself to high lock contention
83 * to improve scalability.
85 * The slice allocator can allocate blocks as small as two pointers, and
86 * unlike malloc(), it does not reserve extra space per block. For large block
87 * sizes, g_slice_new() and g_slice_alloc() will automatically delegate to the
88 * system malloc() implementation. For newly written code it is recommended
89 * to use the new <literal>g_slice</literal> API instead of g_malloc() and
90 * friends, as long as objects are not resized during their lifetime and the
91 * object size used at allocation time is still available when freeing.
94 * <title>Using the slice allocator</title>
99 * /* Allocate 10000 blocks. */
100 * for (i = 0; i < 10000; i++)
102 * mem[i] = g_slice_alloc (50);
104 * /* Fill in the memory with some junk. */
105 * for (j = 0; j < 50; j++)
109 * /* Now free all of the blocks. */
110 * for (i = 0; i < 10000; i++)
112 * g_slice_free1 (50, mem[i]);
114 * </programlisting></example>
117 * <title>Using the slice allocator with data structures</title>
121 * /* Allocate one block, using the g_slice_new() macro. */
122 * array = g_slice_new (GRealArray);
124 * /* We can now use array just like a normal pointer to a structure. */
125 * array->data = NULL;
128 * array->zero_terminated = (zero_terminated ? 1 : 0);
129 * array->clear = (clear ? 1 : 0);
130 * array->elt_size = elt_size;
132 * /* We can free the block, so it can be reused. */
133 * g_slice_free (GRealArray, array);
134 * </programlisting></example>
137 /* the GSlice allocator is split up into 4 layers, roughly modelled after the slab
138 * allocator and magazine extensions as outlined in:
139 * + [Bonwick94] Jeff Bonwick, The slab allocator: An object-caching kernel
140 * memory allocator. USENIX 1994, http://citeseer.ist.psu.edu/bonwick94slab.html
141 * + [Bonwick01] Bonwick and Jonathan Adams, Magazines and vmem: Extending the
142 * slab allocator to many cpu's and arbitrary resources.
143 * USENIX 2001, http://citeseer.ist.psu.edu/bonwick01magazines.html
145 * - the thread magazines. for each (aligned) chunk size, a magazine (a list)
146 * of recently freed and soon to be allocated chunks is maintained per thread.
147 * this way, most alloc/free requests can be quickly satisfied from per-thread
148 * free lists which only require one g_private_get() call to retrive the
150 * - the magazine cache. allocating and freeing chunks to/from threads only
151 * occours at magazine sizes from a global depot of magazines. the depot
152 * maintaines a 15 second working set of allocated magazines, so full
153 * magazines are not allocated and released too often.
154 * the chunk size dependent magazine sizes automatically adapt (within limits,
155 * see [3]) to lock contention to properly scale performance across a variety
157 * - the slab allocator. this allocator allocates slabs (blocks of memory) close
158 * to the system page size or multiples thereof which have to be page aligned.
159 * the blocks are divided into smaller chunks which are used to satisfy
160 * allocations from the upper layers. the space provided by the reminder of
161 * the chunk size division is used for cache colorization (random distribution
162 * of chunk addresses) to improve processor cache utilization. multiple slabs
163 * with the same chunk size are kept in a partially sorted ring to allow O(1)
164 * freeing and allocation of chunks (as long as the allocation of an entirely
165 * new slab can be avoided).
166 * - the page allocator. on most modern systems, posix_memalign(3) or
167 * memalign(3) should be available, so this is used to allocate blocks with
168 * system page size based alignments and sizes or multiples thereof.
169 * if no memalign variant is provided, valloc() is used instead and
170 * block sizes are limited to the system page size (no multiples thereof).
171 * as a fallback, on system without even valloc(), a malloc(3)-based page
172 * allocator with alloc-only behaviour is used.
175 * [1] some systems memalign(3) implementations may rely on boundary tagging for
176 * the handed out memory chunks. to avoid excessive page-wise fragmentation,
177 * we reserve 2 * sizeof (void*) per block size for the systems memalign(3),
178 * specified in NATIVE_MALLOC_PADDING.
179 * [2] using the slab allocator alone already provides for a fast and efficient
180 * allocator, it doesn't properly scale beyond single-threaded uses though.
181 * also, the slab allocator implements eager free(3)-ing, i.e. does not
182 * provide any form of caching or working set maintenance. so if used alone,
183 * it's vulnerable to trashing for sequences of balanced (alloc, free) pairs
184 * at certain thresholds.
185 * [3] magazine sizes are bound by an implementation specific minimum size and
186 * a chunk size specific maximum to limit magazine storage sizes to roughly
188 * [4] allocating ca. 8 chunks per block/page keeps a good balance between
189 * external and internal fragmentation (<= 12.5%). [Bonwick94]
192 /* --- macros and constants --- */
193 #define LARGEALIGNMENT (256)
194 #define P2ALIGNMENT (2 * sizeof (gsize)) /* fits 2 pointers (assumed to be 2 * GLIB_SIZEOF_SIZE_T below) */
195 #define ALIGN(size, base) ((base) * (gsize) (((size) + (base) - 1) / (base)))
196 #define NATIVE_MALLOC_PADDING P2ALIGNMENT /* per-page padding left for native malloc(3) see [1] */
197 #define SLAB_INFO_SIZE P2ALIGN (sizeof (SlabInfo) + NATIVE_MALLOC_PADDING)
198 #define MAX_MAGAZINE_SIZE (256) /* see [3] and allocator_get_magazine_threshold() for this */
199 #define MIN_MAGAZINE_SIZE (4)
200 #define MAX_STAMP_COUNTER (7) /* distributes the load of gettimeofday() */
201 #define MAX_SLAB_CHUNK_SIZE(al) (((al)->max_page_size - SLAB_INFO_SIZE) / 8) /* we want at last 8 chunks per page, see [4] */
202 #define MAX_SLAB_INDEX(al) (SLAB_INDEX (al, MAX_SLAB_CHUNK_SIZE (al)) + 1)
203 #define SLAB_INDEX(al, asize) ((asize) / P2ALIGNMENT - 1) /* asize must be P2ALIGNMENT aligned */
204 #define SLAB_CHUNK_SIZE(al, ix) (((ix) + 1) * P2ALIGNMENT)
205 #define SLAB_BPAGE_SIZE(al,csz) (8 * (csz) + SLAB_INFO_SIZE)
207 /* optimized version of ALIGN (size, P2ALIGNMENT) */
208 #if GLIB_SIZEOF_SIZE_T * 2 == 8 /* P2ALIGNMENT */
209 #define P2ALIGN(size) (((size) + 0x7) & ~(gsize) 0x7)
210 #elif GLIB_SIZEOF_SIZE_T * 2 == 16 /* P2ALIGNMENT */
211 #define P2ALIGN(size) (((size) + 0xf) & ~(gsize) 0xf)
213 #define P2ALIGN(size) ALIGN (size, P2ALIGNMENT)
216 /* special helpers to avoid gmessage.c dependency */
217 static void mem_error (const char *format, ...) G_GNUC_PRINTF (1,2);
218 #define mem_assert(cond) do { if (G_LIKELY (cond)) ; else mem_error ("assertion failed: %s", #cond); } while (0)
220 /* --- structures --- */
221 typedef struct _ChunkLink ChunkLink;
222 typedef struct _SlabInfo SlabInfo;
223 typedef struct _CachedMagazine CachedMagazine;
231 SlabInfo *next, *prev;
235 gsize count; /* approximative chunks list length */
238 Magazine *magazine1; /* array of MAX_SLAB_INDEX (allocator) */
239 Magazine *magazine2; /* array of MAX_SLAB_INDEX (allocator) */
242 gboolean always_malloc;
243 gboolean bypass_magazines;
244 gboolean debug_blocks;
245 gsize working_set_msecs;
246 guint color_increment;
249 /* const after initialization */
250 gsize min_page_size, max_page_size;
252 gsize max_slab_chunk_size_for_magazine_cache;
254 GMutex magazine_mutex;
255 ChunkLink **magazines; /* array of MAX_SLAB_INDEX (allocator) */
256 guint *contention_counters; /* array of MAX_SLAB_INDEX (allocator) */
262 SlabInfo **slab_stack; /* array of MAX_SLAB_INDEX (allocator) */
266 /* --- g-slice prototypes --- */
267 static gpointer slab_allocator_alloc_chunk (gsize chunk_size);
268 static void slab_allocator_free_chunk (gsize chunk_size,
270 static void private_thread_memory_cleanup (gpointer data);
271 static gpointer allocator_memalign (gsize alignment,
273 static void allocator_memfree (gsize memsize,
275 static inline void magazine_cache_update_stamp (void);
276 static inline gsize allocator_get_magazine_threshold (Allocator *allocator,
279 /* --- g-slice memory checker --- */
280 static void smc_notify_alloc (void *pointer,
282 static int smc_notify_free (void *pointer,
285 /* --- variables --- */
286 static GPrivate private_thread_memory = G_PRIVATE_INIT (private_thread_memory_cleanup);
287 static gsize sys_page_size = 0;
288 static Allocator allocator[1] = { { 0, }, };
289 static SliceConfig slice_config = {
290 FALSE, /* always_malloc */
291 FALSE, /* bypass_magazines */
292 FALSE, /* debug_blocks */
293 15 * 1000, /* working_set_msecs */
294 1, /* color increment, alt: 0x7fffffff */
296 static GMutex smc_tree_mutex; /* mutex for G_SLICE=debug-blocks */
298 /* --- auxiliary funcitons --- */
300 g_slice_set_config (GSliceConfig ckey,
303 g_return_if_fail (sys_page_size == 0);
306 case G_SLICE_CONFIG_ALWAYS_MALLOC:
307 slice_config.always_malloc = value != 0;
309 case G_SLICE_CONFIG_BYPASS_MAGAZINES:
310 slice_config.bypass_magazines = value != 0;
312 case G_SLICE_CONFIG_WORKING_SET_MSECS:
313 slice_config.working_set_msecs = value;
315 case G_SLICE_CONFIG_COLOR_INCREMENT:
316 slice_config.color_increment = value;
322 g_slice_get_config (GSliceConfig ckey)
326 case G_SLICE_CONFIG_ALWAYS_MALLOC:
327 return slice_config.always_malloc;
328 case G_SLICE_CONFIG_BYPASS_MAGAZINES:
329 return slice_config.bypass_magazines;
330 case G_SLICE_CONFIG_WORKING_SET_MSECS:
331 return slice_config.working_set_msecs;
332 case G_SLICE_CONFIG_CHUNK_SIZES:
333 return MAX_SLAB_INDEX (allocator);
334 case G_SLICE_CONFIG_COLOR_INCREMENT:
335 return slice_config.color_increment;
342 g_slice_get_config_state (GSliceConfig ckey,
347 g_return_val_if_fail (n_values != NULL, NULL);
352 case G_SLICE_CONFIG_CONTENTION_COUNTER:
353 array[i++] = SLAB_CHUNK_SIZE (allocator, address);
354 array[i++] = allocator->contention_counters[address];
355 array[i++] = allocator_get_magazine_threshold (allocator, address);
357 return g_memdup (array, sizeof (array[0]) * *n_values);
364 slice_config_init (SliceConfig *config)
368 *config = slice_config;
370 val = getenv ("G_SLICE");
374 const GDebugKey keys[] = {
375 { "always-malloc", 1 << 0 },
376 { "debug-blocks", 1 << 1 },
379 flags = g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
380 if (flags & (1 << 0))
381 config->always_malloc = TRUE;
382 if (flags & (1 << 1))
383 config->debug_blocks = TRUE;
388 g_slice_init_nomessage (void)
390 /* we may not use g_error() or friends here */
391 mem_assert (sys_page_size == 0);
392 mem_assert (MIN_MAGAZINE_SIZE >= 4);
396 SYSTEM_INFO system_info;
397 GetSystemInfo (&system_info);
398 sys_page_size = system_info.dwPageSize;
401 sys_page_size = sysconf (_SC_PAGESIZE); /* = sysconf (_SC_PAGE_SIZE); = getpagesize(); */
403 mem_assert (sys_page_size >= 2 * LARGEALIGNMENT);
404 mem_assert ((sys_page_size & (sys_page_size - 1)) == 0);
405 slice_config_init (&allocator->config);
406 allocator->min_page_size = sys_page_size;
407 #if HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN
408 /* allow allocation of pages up to 8KB (with 8KB alignment).
409 * this is useful because many medium to large sized structures
410 * fit less than 8 times (see [4]) into 4KB pages.
411 * we allow very small page sizes here, to reduce wastage in
412 * threads if only small allocations are required (this does
413 * bear the risk of increasing allocation times and fragmentation
416 allocator->min_page_size = MAX (allocator->min_page_size, 4096);
417 allocator->max_page_size = MAX (allocator->min_page_size, 8192);
418 allocator->min_page_size = MIN (allocator->min_page_size, 128);
420 /* we can only align to system page size */
421 allocator->max_page_size = sys_page_size;
423 if (allocator->config.always_malloc)
425 allocator->contention_counters = NULL;
426 allocator->magazines = NULL;
427 allocator->slab_stack = NULL;
431 allocator->contention_counters = g_new0 (guint, MAX_SLAB_INDEX (allocator));
432 allocator->magazines = g_new0 (ChunkLink*, MAX_SLAB_INDEX (allocator));
433 allocator->slab_stack = g_new0 (SlabInfo*, MAX_SLAB_INDEX (allocator));
436 g_mutex_init (&allocator->magazine_mutex);
437 allocator->mutex_counter = 0;
438 allocator->stamp_counter = MAX_STAMP_COUNTER; /* force initial update */
439 allocator->last_stamp = 0;
440 g_mutex_init (&allocator->slab_mutex);
441 allocator->color_accu = 0;
442 magazine_cache_update_stamp();
443 /* values cached for performance reasons */
444 allocator->max_slab_chunk_size_for_magazine_cache = MAX_SLAB_CHUNK_SIZE (allocator);
445 if (allocator->config.always_malloc || allocator->config.bypass_magazines)
446 allocator->max_slab_chunk_size_for_magazine_cache = 0; /* non-optimized cases */
450 allocator_categorize (gsize aligned_chunk_size)
452 /* speed up the likely path */
453 if (G_LIKELY (aligned_chunk_size && aligned_chunk_size <= allocator->max_slab_chunk_size_for_magazine_cache))
454 return 1; /* use magazine cache */
456 if (!allocator->config.always_malloc &&
457 aligned_chunk_size &&
458 aligned_chunk_size <= MAX_SLAB_CHUNK_SIZE (allocator))
460 if (allocator->config.bypass_magazines)
461 return 2; /* use slab allocator, see [2] */
462 return 1; /* use magazine cache */
464 return 0; /* use malloc() */
468 g_mutex_lock_a (GMutex *mutex,
469 guint *contention_counter)
471 gboolean contention = FALSE;
472 if (!g_mutex_trylock (mutex))
474 g_mutex_lock (mutex);
479 allocator->mutex_counter++;
480 if (allocator->mutex_counter >= 1) /* quickly adapt to contention */
482 allocator->mutex_counter = 0;
483 *contention_counter = MIN (*contention_counter + 1, MAX_MAGAZINE_SIZE);
486 else /* !contention */
488 allocator->mutex_counter--;
489 if (allocator->mutex_counter < -11) /* moderately recover magazine sizes */
491 allocator->mutex_counter = 0;
492 *contention_counter = MAX (*contention_counter, 1) - 1;
497 static inline ThreadMemory*
498 thread_memory_from_self (void)
500 ThreadMemory *tmem = g_private_get (&private_thread_memory);
501 if (G_UNLIKELY (!tmem))
503 static GMutex init_mutex;
506 g_mutex_lock (&init_mutex);
507 if G_UNLIKELY (sys_page_size == 0)
508 g_slice_init_nomessage ();
509 g_mutex_unlock (&init_mutex);
511 n_magazines = MAX_SLAB_INDEX (allocator);
512 tmem = g_malloc0 (sizeof (ThreadMemory) + sizeof (Magazine) * 2 * n_magazines);
513 tmem->magazine1 = (Magazine*) (tmem + 1);
514 tmem->magazine2 = &tmem->magazine1[n_magazines];
515 g_private_set (&private_thread_memory, tmem);
520 static inline ChunkLink*
521 magazine_chain_pop_head (ChunkLink **magazine_chunks)
523 /* magazine chains are linked via ChunkLink->next.
524 * each ChunkLink->data of the toplevel chain may point to a subchain,
525 * linked via ChunkLink->next. ChunkLink->data of the subchains just
526 * contains uninitialized junk.
528 ChunkLink *chunk = (*magazine_chunks)->data;
529 if (G_UNLIKELY (chunk))
531 /* allocating from freed list */
532 (*magazine_chunks)->data = chunk->next;
536 chunk = *magazine_chunks;
537 *magazine_chunks = chunk->next;
542 #if 0 /* useful for debugging */
544 magazine_count (ChunkLink *head)
551 ChunkLink *child = head->data;
553 for (child = head->data; child; child = child->next)
562 allocator_get_magazine_threshold (Allocator *allocator,
565 /* the magazine size calculated here has a lower bound of MIN_MAGAZINE_SIZE,
566 * which is required by the implementation. also, for moderately sized chunks
567 * (say >= 64 bytes), magazine sizes shouldn't be much smaller then the number
568 * of chunks available per page/2 to avoid excessive traffic in the magazine
569 * cache for small to medium sized structures.
570 * the upper bound of the magazine size is effectively provided by
571 * MAX_MAGAZINE_SIZE. for larger chunks, this number is scaled down so that
572 * the content of a single magazine doesn't exceed ca. 16KB.
574 gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
575 guint threshold = MAX (MIN_MAGAZINE_SIZE, allocator->max_page_size / MAX (5 * chunk_size, 5 * 32));
576 guint contention_counter = allocator->contention_counters[ix];
577 if (G_UNLIKELY (contention_counter)) /* single CPU bias */
579 /* adapt contention counter thresholds to chunk sizes */
580 contention_counter = contention_counter * 64 / chunk_size;
581 threshold = MAX (threshold, contention_counter);
586 /* --- magazine cache --- */
588 magazine_cache_update_stamp (void)
590 if (allocator->stamp_counter >= MAX_STAMP_COUNTER)
593 g_get_current_time (&tv);
594 allocator->last_stamp = tv.tv_sec * 1000 + tv.tv_usec / 1000; /* milli seconds */
595 allocator->stamp_counter = 0;
598 allocator->stamp_counter++;
601 static inline ChunkLink*
602 magazine_chain_prepare_fields (ChunkLink *magazine_chunks)
608 /* checked upon initialization: mem_assert (MIN_MAGAZINE_SIZE >= 4); */
609 /* ensure a magazine with at least 4 unused data pointers */
610 chunk1 = magazine_chain_pop_head (&magazine_chunks);
611 chunk2 = magazine_chain_pop_head (&magazine_chunks);
612 chunk3 = magazine_chain_pop_head (&magazine_chunks);
613 chunk4 = magazine_chain_pop_head (&magazine_chunks);
614 chunk4->next = magazine_chunks;
615 chunk3->next = chunk4;
616 chunk2->next = chunk3;
617 chunk1->next = chunk2;
621 /* access the first 3 fields of a specially prepared magazine chain */
622 #define magazine_chain_prev(mc) ((mc)->data)
623 #define magazine_chain_stamp(mc) ((mc)->next->data)
624 #define magazine_chain_uint_stamp(mc) GPOINTER_TO_UINT ((mc)->next->data)
625 #define magazine_chain_next(mc) ((mc)->next->next->data)
626 #define magazine_chain_count(mc) ((mc)->next->next->next->data)
629 magazine_cache_trim (Allocator *allocator,
633 /* g_mutex_lock (allocator->mutex); done by caller */
634 /* trim magazine cache from tail */
635 ChunkLink *current = magazine_chain_prev (allocator->magazines[ix]);
636 ChunkLink *trash = NULL;
637 while (ABS (stamp - magazine_chain_uint_stamp (current)) >= allocator->config.working_set_msecs)
640 ChunkLink *prev = magazine_chain_prev (current);
641 ChunkLink *next = magazine_chain_next (current);
642 magazine_chain_next (prev) = next;
643 magazine_chain_prev (next) = prev;
644 /* clear special fields, put on trash stack */
645 magazine_chain_next (current) = NULL;
646 magazine_chain_count (current) = NULL;
647 magazine_chain_stamp (current) = NULL;
648 magazine_chain_prev (current) = trash;
650 /* fixup list head if required */
651 if (current == allocator->magazines[ix])
653 allocator->magazines[ix] = NULL;
658 g_mutex_unlock (&allocator->magazine_mutex);
662 const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
663 g_mutex_lock (&allocator->slab_mutex);
667 trash = magazine_chain_prev (current);
668 magazine_chain_prev (current) = NULL; /* clear special field */
671 ChunkLink *chunk = magazine_chain_pop_head (¤t);
672 slab_allocator_free_chunk (chunk_size, chunk);
675 g_mutex_unlock (&allocator->slab_mutex);
680 magazine_cache_push_magazine (guint ix,
681 ChunkLink *magazine_chunks,
682 gsize count) /* must be >= MIN_MAGAZINE_SIZE */
684 ChunkLink *current = magazine_chain_prepare_fields (magazine_chunks);
685 ChunkLink *next, *prev;
686 g_mutex_lock (&allocator->magazine_mutex);
687 /* add magazine at head */
688 next = allocator->magazines[ix];
690 prev = magazine_chain_prev (next);
692 next = prev = current;
693 magazine_chain_next (prev) = current;
694 magazine_chain_prev (next) = current;
695 magazine_chain_prev (current) = prev;
696 magazine_chain_next (current) = next;
697 magazine_chain_count (current) = (gpointer) count;
699 magazine_cache_update_stamp();
700 magazine_chain_stamp (current) = GUINT_TO_POINTER (allocator->last_stamp);
701 allocator->magazines[ix] = current;
702 /* free old magazines beyond a certain threshold */
703 magazine_cache_trim (allocator, ix, allocator->last_stamp);
704 /* g_mutex_unlock (allocator->mutex); was done by magazine_cache_trim() */
708 magazine_cache_pop_magazine (guint ix,
711 g_mutex_lock_a (&allocator->magazine_mutex, &allocator->contention_counters[ix]);
712 if (!allocator->magazines[ix])
714 guint magazine_threshold = allocator_get_magazine_threshold (allocator, ix);
715 gsize i, chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
716 ChunkLink *chunk, *head;
717 g_mutex_unlock (&allocator->magazine_mutex);
718 g_mutex_lock (&allocator->slab_mutex);
719 head = slab_allocator_alloc_chunk (chunk_size);
722 for (i = 1; i < magazine_threshold; i++)
724 chunk->next = slab_allocator_alloc_chunk (chunk_size);
729 g_mutex_unlock (&allocator->slab_mutex);
735 ChunkLink *current = allocator->magazines[ix];
736 ChunkLink *prev = magazine_chain_prev (current);
737 ChunkLink *next = magazine_chain_next (current);
739 magazine_chain_next (prev) = next;
740 magazine_chain_prev (next) = prev;
741 allocator->magazines[ix] = next == current ? NULL : next;
742 g_mutex_unlock (&allocator->magazine_mutex);
743 /* clear special fields and hand out */
744 *countp = (gsize) magazine_chain_count (current);
745 magazine_chain_prev (current) = NULL;
746 magazine_chain_next (current) = NULL;
747 magazine_chain_count (current) = NULL;
748 magazine_chain_stamp (current) = NULL;
753 /* --- thread magazines --- */
755 private_thread_memory_cleanup (gpointer data)
757 ThreadMemory *tmem = data;
758 const guint n_magazines = MAX_SLAB_INDEX (allocator);
760 for (ix = 0; ix < n_magazines; ix++)
764 mags[0] = &tmem->magazine1[ix];
765 mags[1] = &tmem->magazine2[ix];
766 for (j = 0; j < 2; j++)
768 Magazine *mag = mags[j];
769 if (mag->count >= MIN_MAGAZINE_SIZE)
770 magazine_cache_push_magazine (ix, mag->chunks, mag->count);
773 const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
774 g_mutex_lock (&allocator->slab_mutex);
777 ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
778 slab_allocator_free_chunk (chunk_size, chunk);
780 g_mutex_unlock (&allocator->slab_mutex);
788 thread_memory_magazine1_reload (ThreadMemory *tmem,
791 Magazine *mag = &tmem->magazine1[ix];
792 mem_assert (mag->chunks == NULL); /* ensure that we may reset mag->count */
794 mag->chunks = magazine_cache_pop_magazine (ix, &mag->count);
798 thread_memory_magazine2_unload (ThreadMemory *tmem,
801 Magazine *mag = &tmem->magazine2[ix];
802 magazine_cache_push_magazine (ix, mag->chunks, mag->count);
808 thread_memory_swap_magazines (ThreadMemory *tmem,
811 Magazine xmag = tmem->magazine1[ix];
812 tmem->magazine1[ix] = tmem->magazine2[ix];
813 tmem->magazine2[ix] = xmag;
816 static inline gboolean
817 thread_memory_magazine1_is_empty (ThreadMemory *tmem,
820 return tmem->magazine1[ix].chunks == NULL;
823 static inline gboolean
824 thread_memory_magazine2_is_full (ThreadMemory *tmem,
827 return tmem->magazine2[ix].count >= allocator_get_magazine_threshold (allocator, ix);
830 static inline gpointer
831 thread_memory_magazine1_alloc (ThreadMemory *tmem,
834 Magazine *mag = &tmem->magazine1[ix];
835 ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
836 if (G_LIKELY (mag->count > 0))
842 thread_memory_magazine2_free (ThreadMemory *tmem,
846 Magazine *mag = &tmem->magazine2[ix];
847 ChunkLink *chunk = mem;
849 chunk->next = mag->chunks;
854 /* --- API functions --- */
858 * @type: the type to allocate, typically a structure name
860 * A convenience macro to allocate a block of memory from the
863 * It calls g_slice_alloc() with <literal>sizeof (@type)</literal>
864 * and casts the returned pointer to a pointer of the given type,
865 * avoiding a type cast in the source code.
866 * Note that the underlying slice allocation mechanism can
867 * be changed with the <link linkend="G_SLICE">G_SLICE=always-malloc</link>
868 * environment variable.
870 * Returns: a pointer to the allocated block, cast to a pointer to @type
877 * @type: the type to allocate, typically a structure name
879 * A convenience macro to allocate a block of memory from the
880 * slice allocator and set the memory to 0.
882 * It calls g_slice_alloc0() with <literal>sizeof (@type)</literal>
883 * and casts the returned pointer to a pointer of the given type,
884 * avoiding a type cast in the source code.
885 * Note that the underlying slice allocation mechanism can
886 * be changed with the <link linkend="G_SLICE">G_SLICE=always-malloc</link>
887 * environment variable.
894 * @type: the type to duplicate, typically a structure name
895 * @mem: the memory to copy into the allocated block
897 * A convenience macro to duplicate a block of memory using
898 * the slice allocator.
900 * It calls g_slice_copy() with <literal>sizeof (@type)</literal>
901 * and casts the returned pointer to a pointer of the given type,
902 * avoiding a type cast in the source code.
903 * Note that the underlying slice allocation mechanism can
904 * be changed with the <link linkend="G_SLICE">G_SLICE=always-malloc</link>
905 * environment variable.
907 * Returns: a pointer to the allocated block, cast to a pointer to @type
914 * @type: the type of the block to free, typically a structure name
915 * @mem: a pointer to the block to free
917 * A convenience macro to free a block of memory that has
918 * been allocated from the slice allocator.
920 * It calls g_slice_free1() using <literal>sizeof (type)</literal>
922 * Note that the exact release behaviour can be changed with the
923 * <link linkend="G_DEBUG">G_DEBUG=gc-friendly</link> environment
924 * variable, also see <link linkend="G_SLICE">G_SLICE</link> for
925 * related debugging options.
931 * g_slice_free_chain:
932 * @type: the type of the @mem_chain blocks
933 * @mem_chain: a pointer to the first block of the chain
934 * @next: the field name of the next pointer in @type
936 * Frees a linked list of memory blocks of structure type @type.
937 * The memory blocks must be equal-sized, allocated via
938 * g_slice_alloc() or g_slice_alloc0() and linked together by
939 * a @next pointer (similar to #GSList). The name of the
940 * @next field in @type is passed as third argument.
941 * Note that the exact release behaviour can be changed with the
942 * <link linkend="G_DEBUG">G_DEBUG=gc-friendly</link> environment
943 * variable, also see <link linkend="G_SLICE">G_SLICE</link> for
944 * related debugging options.
951 * @block_size: the number of bytes to allocate
953 * Allocates a block of memory from the slice allocator.
954 * The block adress handed out can be expected to be aligned
955 * to at least <literal>1 * sizeof (void*)</literal>,
956 * though in general slices are 2 * sizeof (void*) bytes aligned,
957 * if a malloc() fallback implementation is used instead,
958 * the alignment may be reduced in a libc dependent fashion.
959 * Note that the underlying slice allocation mechanism can
960 * be changed with the <link linkend="G_SLICE">G_SLICE=always-malloc</link>
961 * environment variable.
963 * Returns: a pointer to the allocated memory block
968 g_slice_alloc (gsize mem_size)
975 /* This gets the private structure for this thread. If the private
976 * structure does not yet exist, it is created.
978 * This has a side effect of causing GSlice to be initialised, so it
981 tmem = thread_memory_from_self ();
983 chunk_size = P2ALIGN (mem_size);
984 acat = allocator_categorize (chunk_size);
985 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
987 guint ix = SLAB_INDEX (allocator, chunk_size);
988 if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
990 thread_memory_swap_magazines (tmem, ix);
991 if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
992 thread_memory_magazine1_reload (tmem, ix);
994 mem = thread_memory_magazine1_alloc (tmem, ix);
996 else if (acat == 2) /* allocate through slab allocator */
998 g_mutex_lock (&allocator->slab_mutex);
999 mem = slab_allocator_alloc_chunk (chunk_size);
1000 g_mutex_unlock (&allocator->slab_mutex);
1002 else /* delegate to system malloc */
1003 mem = g_malloc (mem_size);
1004 if (G_UNLIKELY (allocator->config.debug_blocks))
1005 smc_notify_alloc (mem, mem_size);
1007 TRACE (GLIB_SLICE_ALLOC((void*)mem, mem_size));
1014 * @block_size: the number of bytes to allocate
1016 * Allocates a block of memory via g_slice_alloc() and initializes
1017 * the returned memory to 0. Note that the underlying slice allocation
1018 * mechanism can be changed with the
1019 * <link linkend="G_SLICE">G_SLICE=always-malloc</link>
1020 * environment variable.
1022 * Returns: a pointer to the allocated block
1027 g_slice_alloc0 (gsize mem_size)
1029 gpointer mem = g_slice_alloc (mem_size);
1031 memset (mem, 0, mem_size);
1037 * @block_size: the number of bytes to allocate
1038 * @mem_block: the memory to copy
1040 * Allocates a block of memory from the slice allocator
1041 * and copies @block_size bytes into it from @mem_block.
1043 * Returns: a pointer to the allocated memory block
1048 g_slice_copy (gsize mem_size,
1049 gconstpointer mem_block)
1051 gpointer mem = g_slice_alloc (mem_size);
1053 memcpy (mem, mem_block, mem_size);
1059 * @block_size: the size of the block
1060 * @mem_block: a pointer to the block to free
1062 * Frees a block of memory.
1064 * The memory must have been allocated via g_slice_alloc() or
1065 * g_slice_alloc0() and the @block_size has to match the size
1066 * specified upon allocation. Note that the exact release behaviour
1067 * can be changed with the
1068 * <link linkend="G_DEBUG">G_DEBUG=gc-friendly</link> environment
1069 * variable, also see <link linkend="G_SLICE">G_SLICE</link> for
1070 * related debugging options.
1075 g_slice_free1 (gsize mem_size,
1078 gsize chunk_size = P2ALIGN (mem_size);
1079 guint acat = allocator_categorize (chunk_size);
1080 if (G_UNLIKELY (!mem_block))
1082 if (G_UNLIKELY (allocator->config.debug_blocks) &&
1083 !smc_notify_free (mem_block, mem_size))
1085 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
1087 ThreadMemory *tmem = thread_memory_from_self();
1088 guint ix = SLAB_INDEX (allocator, chunk_size);
1089 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
1091 thread_memory_swap_magazines (tmem, ix);
1092 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
1093 thread_memory_magazine2_unload (tmem, ix);
1095 if (G_UNLIKELY (g_mem_gc_friendly))
1096 memset (mem_block, 0, chunk_size);
1097 thread_memory_magazine2_free (tmem, ix, mem_block);
1099 else if (acat == 2) /* allocate through slab allocator */
1101 if (G_UNLIKELY (g_mem_gc_friendly))
1102 memset (mem_block, 0, chunk_size);
1103 g_mutex_lock (&allocator->slab_mutex);
1104 slab_allocator_free_chunk (chunk_size, mem_block);
1105 g_mutex_unlock (&allocator->slab_mutex);
1107 else /* delegate to system malloc */
1109 if (G_UNLIKELY (g_mem_gc_friendly))
1110 memset (mem_block, 0, mem_size);
1113 TRACE (GLIB_SLICE_FREE((void*)mem_block, mem_size));
1117 * g_slice_free_chain_with_offset:
1118 * @block_size: the size of the blocks
1119 * @mem_chain: a pointer to the first block of the chain
1120 * @next_offset: the offset of the @next field in the blocks
1122 * Frees a linked list of memory blocks of structure type @type.
1124 * The memory blocks must be equal-sized, allocated via
1125 * g_slice_alloc() or g_slice_alloc0() and linked together by a
1126 * @next pointer (similar to #GSList). The offset of the @next
1127 * field in each block is passed as third argument.
1128 * Note that the exact release behaviour can be changed with the
1129 * <link linkend="G_DEBUG">G_DEBUG=gc-friendly</link> environment
1130 * variable, also see <link linkend="G_SLICE">G_SLICE</link> for
1131 * related debugging options.
1136 g_slice_free_chain_with_offset (gsize mem_size,
1140 gpointer slice = mem_chain;
1141 /* while the thread magazines and the magazine cache are implemented so that
1142 * they can easily be extended to allow for free lists containing more free
1143 * lists for the first level nodes, which would allow O(1) freeing in this
1144 * function, the benefit of such an extension is questionable, because:
1145 * - the magazine size counts will become mere lower bounds which confuses
1146 * the code adapting to lock contention;
1147 * - freeing a single node to the thread magazines is very fast, so this
1148 * O(list_length) operation is multiplied by a fairly small factor;
1149 * - memory usage histograms on larger applications seem to indicate that
1150 * the amount of released multi node lists is negligible in comparison
1151 * to single node releases.
1152 * - the major performance bottle neck, namely g_private_get() or
1153 * g_mutex_lock()/g_mutex_unlock() has already been moved out of the
1154 * inner loop for freeing chained slices.
1156 gsize chunk_size = P2ALIGN (mem_size);
1157 guint acat = allocator_categorize (chunk_size);
1158 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
1160 ThreadMemory *tmem = thread_memory_from_self();
1161 guint ix = SLAB_INDEX (allocator, chunk_size);
1164 guint8 *current = slice;
1165 slice = *(gpointer*) (current + next_offset);
1166 if (G_UNLIKELY (allocator->config.debug_blocks) &&
1167 !smc_notify_free (current, mem_size))
1169 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
1171 thread_memory_swap_magazines (tmem, ix);
1172 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
1173 thread_memory_magazine2_unload (tmem, ix);
1175 if (G_UNLIKELY (g_mem_gc_friendly))
1176 memset (current, 0, chunk_size);
1177 thread_memory_magazine2_free (tmem, ix, current);
1180 else if (acat == 2) /* allocate through slab allocator */
1182 g_mutex_lock (&allocator->slab_mutex);
1185 guint8 *current = slice;
1186 slice = *(gpointer*) (current + next_offset);
1187 if (G_UNLIKELY (allocator->config.debug_blocks) &&
1188 !smc_notify_free (current, mem_size))
1190 if (G_UNLIKELY (g_mem_gc_friendly))
1191 memset (current, 0, chunk_size);
1192 slab_allocator_free_chunk (chunk_size, current);
1194 g_mutex_unlock (&allocator->slab_mutex);
1196 else /* delegate to system malloc */
1199 guint8 *current = slice;
1200 slice = *(gpointer*) (current + next_offset);
1201 if (G_UNLIKELY (allocator->config.debug_blocks) &&
1202 !smc_notify_free (current, mem_size))
1204 if (G_UNLIKELY (g_mem_gc_friendly))
1205 memset (current, 0, mem_size);
1210 /* --- single page allocator --- */
1212 allocator_slab_stack_push (Allocator *allocator,
1216 /* insert slab at slab ring head */
1217 if (!allocator->slab_stack[ix])
1219 sinfo->next = sinfo;
1220 sinfo->prev = sinfo;
1224 SlabInfo *next = allocator->slab_stack[ix], *prev = next->prev;
1230 allocator->slab_stack[ix] = sinfo;
1234 allocator_aligned_page_size (Allocator *allocator,
1237 gsize val = 1 << g_bit_storage (n_bytes - 1);
1238 val = MAX (val, allocator->min_page_size);
1243 allocator_add_slab (Allocator *allocator,
1249 gsize addr, padding, n_chunks, color = 0;
1250 gsize page_size = allocator_aligned_page_size (allocator, SLAB_BPAGE_SIZE (allocator, chunk_size));
1251 /* allocate 1 page for the chunks and the slab */
1252 gpointer aligned_memory = allocator_memalign (page_size, page_size - NATIVE_MALLOC_PADDING);
1253 guint8 *mem = aligned_memory;
1257 const gchar *syserr = "unknown error";
1259 syserr = strerror (errno);
1261 mem_error ("failed to allocate %u bytes (alignment: %u): %s\n",
1262 (guint) (page_size - NATIVE_MALLOC_PADDING), (guint) page_size, syserr);
1264 /* mask page address */
1265 addr = ((gsize) mem / page_size) * page_size;
1266 /* assert alignment */
1267 mem_assert (aligned_memory == (gpointer) addr);
1268 /* basic slab info setup */
1269 sinfo = (SlabInfo*) (mem + page_size - SLAB_INFO_SIZE);
1270 sinfo->n_allocated = 0;
1271 sinfo->chunks = NULL;
1272 /* figure cache colorization */
1273 n_chunks = ((guint8*) sinfo - mem) / chunk_size;
1274 padding = ((guint8*) sinfo - mem) - n_chunks * chunk_size;
1277 color = (allocator->color_accu * P2ALIGNMENT) % padding;
1278 allocator->color_accu += allocator->config.color_increment;
1280 /* add chunks to free list */
1281 chunk = (ChunkLink*) (mem + color);
1282 sinfo->chunks = chunk;
1283 for (i = 0; i < n_chunks - 1; i++)
1285 chunk->next = (ChunkLink*) ((guint8*) chunk + chunk_size);
1286 chunk = chunk->next;
1288 chunk->next = NULL; /* last chunk */
1289 /* add slab to slab ring */
1290 allocator_slab_stack_push (allocator, ix, sinfo);
1294 slab_allocator_alloc_chunk (gsize chunk_size)
1297 guint ix = SLAB_INDEX (allocator, chunk_size);
1298 /* ensure non-empty slab */
1299 if (!allocator->slab_stack[ix] || !allocator->slab_stack[ix]->chunks)
1300 allocator_add_slab (allocator, ix, chunk_size);
1301 /* allocate chunk */
1302 chunk = allocator->slab_stack[ix]->chunks;
1303 allocator->slab_stack[ix]->chunks = chunk->next;
1304 allocator->slab_stack[ix]->n_allocated++;
1305 /* rotate empty slabs */
1306 if (!allocator->slab_stack[ix]->chunks)
1307 allocator->slab_stack[ix] = allocator->slab_stack[ix]->next;
1312 slab_allocator_free_chunk (gsize chunk_size,
1317 guint ix = SLAB_INDEX (allocator, chunk_size);
1318 gsize page_size = allocator_aligned_page_size (allocator, SLAB_BPAGE_SIZE (allocator, chunk_size));
1319 gsize addr = ((gsize) mem / page_size) * page_size;
1320 /* mask page address */
1321 guint8 *page = (guint8*) addr;
1322 SlabInfo *sinfo = (SlabInfo*) (page + page_size - SLAB_INFO_SIZE);
1323 /* assert valid chunk count */
1324 mem_assert (sinfo->n_allocated > 0);
1325 /* add chunk to free list */
1326 was_empty = sinfo->chunks == NULL;
1327 chunk = (ChunkLink*) mem;
1328 chunk->next = sinfo->chunks;
1329 sinfo->chunks = chunk;
1330 sinfo->n_allocated--;
1331 /* keep slab ring partially sorted, empty slabs at end */
1335 SlabInfo *next = sinfo->next, *prev = sinfo->prev;
1338 if (allocator->slab_stack[ix] == sinfo)
1339 allocator->slab_stack[ix] = next == sinfo ? NULL : next;
1340 /* insert slab at head */
1341 allocator_slab_stack_push (allocator, ix, sinfo);
1343 /* eagerly free complete unused slabs */
1344 if (!sinfo->n_allocated)
1347 SlabInfo *next = sinfo->next, *prev = sinfo->prev;
1350 if (allocator->slab_stack[ix] == sinfo)
1351 allocator->slab_stack[ix] = next == sinfo ? NULL : next;
1353 allocator_memfree (page_size, page);
1357 /* --- memalign implementation --- */
1358 #ifdef HAVE_MALLOC_H
1359 #include <malloc.h> /* memalign() */
1363 * define HAVE_POSIX_MEMALIGN 1 // if free(posix_memalign(3)) works, <stdlib.h>
1364 * define HAVE_COMPLIANT_POSIX_MEMALIGN 1 // if free(posix_memalign(3)) works for sizes != 2^n, <stdlib.h>
1365 * define HAVE_MEMALIGN 1 // if free(memalign(3)) works, <malloc.h>
1366 * define HAVE_VALLOC 1 // if free(valloc(3)) works, <stdlib.h> or <malloc.h>
1367 * if none is provided, we implement malloc(3)-based alloc-only page alignment
1370 #if !(HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC)
1371 static GTrashStack *compat_valloc_trash = NULL;
1375 allocator_memalign (gsize alignment,
1378 gpointer aligned_memory = NULL;
1380 #if HAVE_COMPLIANT_POSIX_MEMALIGN
1381 err = posix_memalign (&aligned_memory, alignment, memsize);
1384 aligned_memory = memalign (alignment, memsize);
1388 aligned_memory = valloc (memsize);
1391 /* simplistic non-freeing page allocator */
1392 mem_assert (alignment == sys_page_size);
1393 mem_assert (memsize <= sys_page_size);
1394 if (!compat_valloc_trash)
1396 const guint n_pages = 16;
1397 guint8 *mem = malloc (n_pages * sys_page_size);
1402 guint8 *amem = (guint8*) ALIGN ((gsize) mem, sys_page_size);
1404 i--; /* mem wasn't page aligned */
1406 g_trash_stack_push (&compat_valloc_trash, amem + i * sys_page_size);
1409 aligned_memory = g_trash_stack_pop (&compat_valloc_trash);
1411 if (!aligned_memory)
1413 return aligned_memory;
1417 allocator_memfree (gsize memsize,
1420 #if HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC
1423 mem_assert (memsize <= sys_page_size);
1424 g_trash_stack_push (&compat_valloc_trash, mem);
1429 mem_error (const char *format,
1434 /* at least, put out "MEMORY-ERROR", in case we segfault during the rest of the function */
1435 fputs ("\n***MEMORY-ERROR***: ", stderr);
1436 pname = g_get_prgname();
1437 fprintf (stderr, "%s[%ld]: GSlice: ", pname ? pname : "", (long)getpid());
1438 va_start (args, format);
1439 vfprintf (stderr, format, args);
1441 fputs ("\n", stderr);
1446 /* --- g-slice memory checker tree --- */
1447 typedef size_t SmcKType; /* key type */
1448 typedef size_t SmcVType; /* value type */
1453 static void smc_tree_insert (SmcKType key,
1455 static gboolean smc_tree_lookup (SmcKType key,
1457 static gboolean smc_tree_remove (SmcKType key);
1460 /* --- g-slice memory checker implementation --- */
1462 smc_notify_alloc (void *pointer,
1465 size_t adress = (size_t) pointer;
1467 smc_tree_insert (adress, size);
1472 smc_notify_ignore (void *pointer)
1474 size_t adress = (size_t) pointer;
1476 smc_tree_remove (adress);
1481 smc_notify_free (void *pointer,
1484 size_t adress = (size_t) pointer;
1489 return 1; /* ignore */
1490 found_one = smc_tree_lookup (adress, &real_size);
1493 fprintf (stderr, "GSlice: MemChecker: attempt to release non-allocated block: %p size=%" G_GSIZE_FORMAT "\n", pointer, size);
1496 if (real_size != size && (real_size || size))
1498 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);
1501 if (!smc_tree_remove (adress))
1503 fprintf (stderr, "GSlice: MemChecker: attempt to release non-allocated block: %p size=%" G_GSIZE_FORMAT "\n", pointer, size);
1506 return 1; /* all fine */
1509 /* --- g-slice memory checker tree implementation --- */
1510 #define SMC_TRUNK_COUNT (4093 /* 16381 */) /* prime, to distribute trunk collisions (big, allocated just once) */
1511 #define SMC_BRANCH_COUNT (511) /* prime, to distribute branch collisions */
1512 #define SMC_TRUNK_EXTENT (SMC_BRANCH_COUNT * 2039) /* key address space per trunk, should distribute uniformly across BRANCH_COUNT */
1513 #define SMC_TRUNK_HASH(k) ((k / SMC_TRUNK_EXTENT) % SMC_TRUNK_COUNT) /* generate new trunk hash per megabyte (roughly) */
1514 #define SMC_BRANCH_HASH(k) (k % SMC_BRANCH_COUNT)
1518 unsigned int n_entries;
1521 static SmcBranch **smc_tree_root = NULL;
1524 smc_tree_abort (int errval)
1526 const char *syserr = "unknown error";
1528 syserr = strerror (errval);
1530 mem_error ("MemChecker: failure in debugging tree: %s", syserr);
1533 static inline SmcEntry*
1534 smc_tree_branch_grow_L (SmcBranch *branch,
1537 unsigned int old_size = branch->n_entries * sizeof (branch->entries[0]);
1538 unsigned int new_size = old_size + sizeof (branch->entries[0]);
1540 mem_assert (index <= branch->n_entries);
1541 branch->entries = (SmcEntry*) realloc (branch->entries, new_size);
1542 if (!branch->entries)
1543 smc_tree_abort (errno);
1544 entry = branch->entries + index;
1545 g_memmove (entry + 1, entry, (branch->n_entries - index) * sizeof (entry[0]));
1546 branch->n_entries += 1;
1550 static inline SmcEntry*
1551 smc_tree_branch_lookup_nearest_L (SmcBranch *branch,
1554 unsigned int n_nodes = branch->n_entries, offs = 0;
1555 SmcEntry *check = branch->entries;
1557 while (offs < n_nodes)
1559 unsigned int i = (offs + n_nodes) >> 1;
1560 check = branch->entries + i;
1561 cmp = key < check->key ? -1 : key != check->key;
1563 return check; /* return exact match */
1566 else /* (cmp > 0) */
1569 /* check points at last mismatch, cmp > 0 indicates greater key */
1570 return cmp > 0 ? check + 1 : check; /* return insertion position for inexact match */
1574 smc_tree_insert (SmcKType key,
1577 unsigned int ix0, ix1;
1580 g_mutex_lock (&smc_tree_mutex);
1581 ix0 = SMC_TRUNK_HASH (key);
1582 ix1 = SMC_BRANCH_HASH (key);
1585 smc_tree_root = calloc (SMC_TRUNK_COUNT, sizeof (smc_tree_root[0]));
1587 smc_tree_abort (errno);
1589 if (!smc_tree_root[ix0])
1591 smc_tree_root[ix0] = calloc (SMC_BRANCH_COUNT, sizeof (smc_tree_root[0][0]));
1592 if (!smc_tree_root[ix0])
1593 smc_tree_abort (errno);
1595 entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
1596 if (!entry || /* need create */
1597 entry >= smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries || /* need append */
1598 entry->key != key) /* need insert */
1599 entry = smc_tree_branch_grow_L (&smc_tree_root[ix0][ix1], entry - smc_tree_root[ix0][ix1].entries);
1601 entry->value = value;
1602 g_mutex_unlock (&smc_tree_mutex);
1606 smc_tree_lookup (SmcKType key,
1609 SmcEntry *entry = NULL;
1610 unsigned int ix0 = SMC_TRUNK_HASH (key), ix1 = SMC_BRANCH_HASH (key);
1611 gboolean found_one = FALSE;
1613 g_mutex_lock (&smc_tree_mutex);
1614 if (smc_tree_root && smc_tree_root[ix0])
1616 entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
1618 entry < smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries &&
1622 *value_p = entry->value;
1625 g_mutex_unlock (&smc_tree_mutex);
1630 smc_tree_remove (SmcKType key)
1632 unsigned int ix0 = SMC_TRUNK_HASH (key), ix1 = SMC_BRANCH_HASH (key);
1633 gboolean found_one = FALSE;
1634 g_mutex_lock (&smc_tree_mutex);
1635 if (smc_tree_root && smc_tree_root[ix0])
1637 SmcEntry *entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
1639 entry < smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries &&
1642 unsigned int i = entry - smc_tree_root[ix0][ix1].entries;
1643 smc_tree_root[ix0][ix1].n_entries -= 1;
1644 g_memmove (entry, entry + 1, (smc_tree_root[ix0][ix1].n_entries - i) * sizeof (entry[0]));
1645 if (!smc_tree_root[ix0][ix1].n_entries)
1647 /* avoid useless pressure on the memory system */
1648 free (smc_tree_root[ix0][ix1].entries);
1649 smc_tree_root[ix0][ix1].entries = NULL;
1654 g_mutex_unlock (&smc_tree_mutex);
1658 #ifdef G_ENABLE_DEBUG
1660 g_slice_debug_tree_statistics (void)
1662 g_mutex_lock (&smc_tree_mutex);
1665 unsigned int i, j, t = 0, o = 0, b = 0, su = 0, ex = 0, en = 4294967295u;
1667 for (i = 0; i < SMC_TRUNK_COUNT; i++)
1668 if (smc_tree_root[i])
1671 for (j = 0; j < SMC_BRANCH_COUNT; j++)
1672 if (smc_tree_root[i][j].n_entries)
1675 su += smc_tree_root[i][j].n_entries;
1676 en = MIN (en, smc_tree_root[i][j].n_entries);
1677 ex = MAX (ex, smc_tree_root[i][j].n_entries);
1679 else if (smc_tree_root[i][j].entries)
1680 o++; /* formerly used, now empty */
1683 tf = MAX (t, 1.0); /* max(1) to be a valid divisor */
1684 bf = MAX (b, 1.0); /* max(1) to be a valid divisor */
1685 fprintf (stderr, "GSlice: MemChecker: %u trunks, %u branches, %u old branches\n", t, b, o);
1686 fprintf (stderr, "GSlice: MemChecker: %f branches per trunk, %.2f%% utilization\n",
1688 100.0 - (SMC_BRANCH_COUNT - b / tf) / (0.01 * SMC_BRANCH_COUNT));
1689 fprintf (stderr, "GSlice: MemChecker: %f entries per branch, %u minimum, %u maximum\n",
1693 fprintf (stderr, "GSlice: MemChecker: root=NULL\n");
1694 g_mutex_unlock (&smc_tree_mutex);
1696 /* sample statistics (beast + GSLice + 24h scripted core & GUI activity):
1697 * PID %CPU %MEM VSZ RSS COMMAND
1698 * 8887 30.3 45.8 456068 414856 beast-0.7.1 empty.bse
1699 * $ cat /proc/8887/statm # total-program-size resident-set-size shared-pages text/code data/stack library dirty-pages
1700 * 114017 103714 2354 344 0 108676 0
1701 * $ cat /proc/8887/status
1712 * (gdb) print g_slice_debug_tree_statistics ()
1713 * GSlice: MemChecker: 422 trunks, 213068 branches, 0 old branches
1714 * GSlice: MemChecker: 504.900474 branches per trunk, 98.81% utilization
1715 * GSlice: MemChecker: 4.965039 entries per branch, 1 minimum, 37 maximum
1718 #endif /* G_ENABLE_DEBUG */