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"
59 * SECTION:memory_slices
60 * @title: Memory Slices
61 * @short_description: efficient way to allocate groups of equal-sized
64 * Memory slices provide a space-efficient and multi-processing scalable
65 * way to allocate equal-sized pieces of memory, just like the original
66 * #GMemChunks (from GLib 2.8), while avoiding their excessive
67 * memory-waste, scalability and performance problems.
69 * To achieve these goals, the slice allocator uses a sophisticated,
70 * layered design that has been inspired by Bonwick's slab allocator
72 * <ulink url="http://citeseer.ist.psu.edu/bonwick94slab.html">[Bonwick94]</ulink> Jeff Bonwick, The slab allocator: An object-caching kernel
73 * memory allocator. USENIX 1994, and
74 * <ulink url="http://citeseer.ist.psu.edu/bonwick01magazines.html">[Bonwick01]</ulink> Bonwick and Jonathan Adams, Magazines and vmem: Extending the
75 * slab allocator to many cpu's and arbitrary resources. USENIX 2001
77 * It uses posix_memalign() to optimize allocations of many equally-sized
78 * chunks, and has per-thread free lists (the so-called magazine layer)
79 * to quickly satisfy allocation requests of already known structure sizes.
80 * This is accompanied by extra caching logic to keep freed memory around
81 * for some time before returning it to the system. Memory that is unused
82 * due to alignment constraints is used for cache colorization (random
83 * distribution of chunk addresses) to improve CPU cache utilization. The
84 * caching layer of the slice allocator adapts itself to high lock contention
85 * to improve scalability.
87 * The slice allocator can allocate blocks as small as two pointers, and
88 * unlike malloc(), it does not reserve extra space per block. For large block
89 * sizes, g_slice_new() and g_slice_alloc() will automatically delegate to the
90 * system malloc() implementation. For newly written code it is recommended
91 * to use the new <literal>g_slice</literal> API instead of g_malloc() and
92 * friends, as long as objects are not resized during their lifetime and the
93 * object size used at allocation time is still available when freeing.
96 * <title>Using the slice allocator</title>
101 * /* Allocate 10000 blocks. */
102 * for (i = 0; i < 10000; i++)
104 * mem[i] = g_slice_alloc (50);
106 * /* Fill in the memory with some junk. */
107 * for (j = 0; j < 50; j++)
111 * /* Now free all of the blocks. */
112 * for (i = 0; i < 10000; i++)
114 * g_slice_free1 (50, mem[i]);
116 * </programlisting></example>
119 * <title>Using the slice allocator with data structures</title>
123 * /* Allocate one block, using the g_slice_new() macro. */
124 * array = g_slice_new (GRealArray);
126 * /* We can now use array just like a normal pointer to a structure. */
127 * array->data = NULL;
130 * array->zero_terminated = (zero_terminated ? 1 : 0);
131 * array->clear = (clear ? 1 : 0);
132 * array->elt_size = elt_size;
134 * /* We can free the block, so it can be reused. */
135 * g_slice_free (GRealArray, array);
136 * </programlisting></example>
139 /* the GSlice allocator is split up into 4 layers, roughly modelled after the slab
140 * allocator and magazine extensions as outlined in:
141 * + [Bonwick94] Jeff Bonwick, The slab allocator: An object-caching kernel
142 * memory allocator. USENIX 1994, http://citeseer.ist.psu.edu/bonwick94slab.html
143 * + [Bonwick01] Bonwick and Jonathan Adams, Magazines and vmem: Extending the
144 * slab allocator to many cpu's and arbitrary resources.
145 * USENIX 2001, http://citeseer.ist.psu.edu/bonwick01magazines.html
147 * - the thread magazines. for each (aligned) chunk size, a magazine (a list)
148 * of recently freed and soon to be allocated chunks is maintained per thread.
149 * this way, most alloc/free requests can be quickly satisfied from per-thread
150 * free lists which only require one g_private_get() call to retrive the
152 * - the magazine cache. allocating and freeing chunks to/from threads only
153 * occours at magazine sizes from a global depot of magazines. the depot
154 * maintaines a 15 second working set of allocated magazines, so full
155 * magazines are not allocated and released too often.
156 * the chunk size dependent magazine sizes automatically adapt (within limits,
157 * see [3]) to lock contention to properly scale performance across a variety
159 * - the slab allocator. this allocator allocates slabs (blocks of memory) close
160 * to the system page size or multiples thereof which have to be page aligned.
161 * the blocks are divided into smaller chunks which are used to satisfy
162 * allocations from the upper layers. the space provided by the reminder of
163 * the chunk size division is used for cache colorization (random distribution
164 * of chunk addresses) to improve processor cache utilization. multiple slabs
165 * with the same chunk size are kept in a partially sorted ring to allow O(1)
166 * freeing and allocation of chunks (as long as the allocation of an entirely
167 * new slab can be avoided).
168 * - the page allocator. on most modern systems, posix_memalign(3) or
169 * memalign(3) should be available, so this is used to allocate blocks with
170 * system page size based alignments and sizes or multiples thereof.
171 * if no memalign variant is provided, valloc() is used instead and
172 * block sizes are limited to the system page size (no multiples thereof).
173 * as a fallback, on system without even valloc(), a malloc(3)-based page
174 * allocator with alloc-only behaviour is used.
177 * [1] some systems memalign(3) implementations may rely on boundary tagging for
178 * the handed out memory chunks. to avoid excessive page-wise fragmentation,
179 * we reserve 2 * sizeof (void*) per block size for the systems memalign(3),
180 * specified in NATIVE_MALLOC_PADDING.
181 * [2] using the slab allocator alone already provides for a fast and efficient
182 * allocator, it doesn't properly scale beyond single-threaded uses though.
183 * also, the slab allocator implements eager free(3)-ing, i.e. does not
184 * provide any form of caching or working set maintenance. so if used alone,
185 * it's vulnerable to trashing for sequences of balanced (alloc, free) pairs
186 * at certain thresholds.
187 * [3] magazine sizes are bound by an implementation specific minimum size and
188 * a chunk size specific maximum to limit magazine storage sizes to roughly
190 * [4] allocating ca. 8 chunks per block/page keeps a good balance between
191 * external and internal fragmentation (<= 12.5%). [Bonwick94]
194 /* --- macros and constants --- */
195 #define LARGEALIGNMENT (256)
196 #define P2ALIGNMENT (2 * sizeof (gsize)) /* fits 2 pointers (assumed to be 2 * GLIB_SIZEOF_SIZE_T below) */
197 #define ALIGN(size, base) ((base) * (gsize) (((size) + (base) - 1) / (base)))
198 #define NATIVE_MALLOC_PADDING P2ALIGNMENT /* per-page padding left for native malloc(3) see [1] */
199 #define SLAB_INFO_SIZE P2ALIGN (sizeof (SlabInfo) + NATIVE_MALLOC_PADDING)
200 #define MAX_MAGAZINE_SIZE (256) /* see [3] and allocator_get_magazine_threshold() for this */
201 #define MIN_MAGAZINE_SIZE (4)
202 #define MAX_STAMP_COUNTER (7) /* distributes the load of gettimeofday() */
203 #define MAX_SLAB_CHUNK_SIZE(al) (((al)->max_page_size - SLAB_INFO_SIZE) / 8) /* we want at last 8 chunks per page, see [4] */
204 #define MAX_SLAB_INDEX(al) (SLAB_INDEX (al, MAX_SLAB_CHUNK_SIZE (al)) + 1)
205 #define SLAB_INDEX(al, asize) ((asize) / P2ALIGNMENT - 1) /* asize must be P2ALIGNMENT aligned */
206 #define SLAB_CHUNK_SIZE(al, ix) (((ix) + 1) * P2ALIGNMENT)
207 #define SLAB_BPAGE_SIZE(al,csz) (8 * (csz) + SLAB_INFO_SIZE)
209 /* optimized version of ALIGN (size, P2ALIGNMENT) */
210 #if GLIB_SIZEOF_SIZE_T * 2 == 8 /* P2ALIGNMENT */
211 #define P2ALIGN(size) (((size) + 0x7) & ~(gsize) 0x7)
212 #elif GLIB_SIZEOF_SIZE_T * 2 == 16 /* P2ALIGNMENT */
213 #define P2ALIGN(size) (((size) + 0xf) & ~(gsize) 0xf)
215 #define P2ALIGN(size) ALIGN (size, P2ALIGNMENT)
218 /* special helpers to avoid gmessage.c dependency */
219 static void mem_error (const char *format, ...) G_GNUC_PRINTF (1,2);
220 #define mem_assert(cond) do { if (G_LIKELY (cond)) ; else mem_error ("assertion failed: %s", #cond); } while (0)
222 /* --- structures --- */
223 typedef struct _ChunkLink ChunkLink;
224 typedef struct _SlabInfo SlabInfo;
225 typedef struct _CachedMagazine CachedMagazine;
233 SlabInfo *next, *prev;
237 gsize count; /* approximative chunks list length */
240 Magazine *magazine1; /* array of MAX_SLAB_INDEX (allocator) */
241 Magazine *magazine2; /* array of MAX_SLAB_INDEX (allocator) */
244 gboolean always_malloc;
245 gboolean bypass_magazines;
246 gboolean debug_blocks;
247 gsize working_set_msecs;
248 guint color_increment;
251 /* const after initialization */
252 gsize min_page_size, max_page_size;
254 gsize max_slab_chunk_size_for_magazine_cache;
256 GMutex magazine_mutex;
257 ChunkLink **magazines; /* array of MAX_SLAB_INDEX (allocator) */
258 guint *contention_counters; /* array of MAX_SLAB_INDEX (allocator) */
264 SlabInfo **slab_stack; /* array of MAX_SLAB_INDEX (allocator) */
268 /* --- g-slice prototypes --- */
269 static gpointer slab_allocator_alloc_chunk (gsize chunk_size);
270 static void slab_allocator_free_chunk (gsize chunk_size,
272 static void private_thread_memory_cleanup (gpointer data);
273 static gpointer allocator_memalign (gsize alignment,
275 static void allocator_memfree (gsize memsize,
277 static inline void magazine_cache_update_stamp (void);
278 static inline gsize allocator_get_magazine_threshold (Allocator *allocator,
281 /* --- g-slice memory checker --- */
282 static void smc_notify_alloc (void *pointer,
284 static int smc_notify_free (void *pointer,
287 /* --- variables --- */
288 static GPrivate private_thread_memory = G_PRIVATE_INIT (private_thread_memory_cleanup);
289 static gsize sys_page_size = 0;
290 static Allocator allocator[1] = { { 0, }, };
291 static SliceConfig slice_config = {
292 FALSE, /* always_malloc */
293 FALSE, /* bypass_magazines */
294 FALSE, /* debug_blocks */
295 15 * 1000, /* working_set_msecs */
296 1, /* color increment, alt: 0x7fffffff */
298 static GMutex smc_tree_mutex; /* mutex for G_SLICE=debug-blocks */
300 /* --- auxiliary funcitons --- */
302 g_slice_set_config (GSliceConfig ckey,
305 g_return_if_fail (sys_page_size == 0);
308 case G_SLICE_CONFIG_ALWAYS_MALLOC:
309 slice_config.always_malloc = value != 0;
311 case G_SLICE_CONFIG_BYPASS_MAGAZINES:
312 slice_config.bypass_magazines = value != 0;
314 case G_SLICE_CONFIG_WORKING_SET_MSECS:
315 slice_config.working_set_msecs = value;
317 case G_SLICE_CONFIG_COLOR_INCREMENT:
318 slice_config.color_increment = value;
324 g_slice_get_config (GSliceConfig ckey)
328 case G_SLICE_CONFIG_ALWAYS_MALLOC:
329 return slice_config.always_malloc;
330 case G_SLICE_CONFIG_BYPASS_MAGAZINES:
331 return slice_config.bypass_magazines;
332 case G_SLICE_CONFIG_WORKING_SET_MSECS:
333 return slice_config.working_set_msecs;
334 case G_SLICE_CONFIG_CHUNK_SIZES:
335 return MAX_SLAB_INDEX (allocator);
336 case G_SLICE_CONFIG_COLOR_INCREMENT:
337 return slice_config.color_increment;
344 g_slice_get_config_state (GSliceConfig ckey,
349 g_return_val_if_fail (n_values != NULL, NULL);
354 case G_SLICE_CONFIG_CONTENTION_COUNTER:
355 array[i++] = SLAB_CHUNK_SIZE (allocator, address);
356 array[i++] = allocator->contention_counters[address];
357 array[i++] = allocator_get_magazine_threshold (allocator, address);
359 return g_memdup (array, sizeof (array[0]) * *n_values);
366 slice_config_init (SliceConfig *config)
370 *config = slice_config;
372 val = getenv ("G_SLICE");
376 const GDebugKey keys[] = {
377 { "always-malloc", 1 << 0 },
378 { "debug-blocks", 1 << 1 },
381 flags = g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
382 if (flags & (1 << 0))
383 config->always_malloc = TRUE;
384 if (flags & (1 << 1))
385 config->debug_blocks = TRUE;
389 /* G_SLICE was not specified, so check if valgrind is running and
390 * disable ourselves if it is.
392 * This way it's possible to force gslice to be enabled under
393 * valgrind just by setting G_SLICE to the empty string.
395 if (RUNNING_ON_VALGRIND)
396 config->always_malloc = TRUE;
401 g_slice_init_nomessage (void)
403 /* we may not use g_error() or friends here */
404 mem_assert (sys_page_size == 0);
405 mem_assert (MIN_MAGAZINE_SIZE >= 4);
409 SYSTEM_INFO system_info;
410 GetSystemInfo (&system_info);
411 sys_page_size = system_info.dwPageSize;
414 sys_page_size = sysconf (_SC_PAGESIZE); /* = sysconf (_SC_PAGE_SIZE); = getpagesize(); */
416 mem_assert (sys_page_size >= 2 * LARGEALIGNMENT);
417 mem_assert ((sys_page_size & (sys_page_size - 1)) == 0);
418 slice_config_init (&allocator->config);
419 allocator->min_page_size = sys_page_size;
420 #if HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN
421 /* allow allocation of pages up to 8KB (with 8KB alignment).
422 * this is useful because many medium to large sized structures
423 * fit less than 8 times (see [4]) into 4KB pages.
424 * we allow very small page sizes here, to reduce wastage in
425 * threads if only small allocations are required (this does
426 * bear the risk of increasing allocation times and fragmentation
429 allocator->min_page_size = MAX (allocator->min_page_size, 4096);
430 allocator->max_page_size = MAX (allocator->min_page_size, 8192);
431 allocator->min_page_size = MIN (allocator->min_page_size, 128);
433 /* we can only align to system page size */
434 allocator->max_page_size = sys_page_size;
436 if (allocator->config.always_malloc)
438 allocator->contention_counters = NULL;
439 allocator->magazines = NULL;
440 allocator->slab_stack = NULL;
444 allocator->contention_counters = g_new0 (guint, MAX_SLAB_INDEX (allocator));
445 allocator->magazines = g_new0 (ChunkLink*, MAX_SLAB_INDEX (allocator));
446 allocator->slab_stack = g_new0 (SlabInfo*, MAX_SLAB_INDEX (allocator));
449 g_mutex_init (&allocator->magazine_mutex);
450 allocator->mutex_counter = 0;
451 allocator->stamp_counter = MAX_STAMP_COUNTER; /* force initial update */
452 allocator->last_stamp = 0;
453 g_mutex_init (&allocator->slab_mutex);
454 allocator->color_accu = 0;
455 magazine_cache_update_stamp();
456 /* values cached for performance reasons */
457 allocator->max_slab_chunk_size_for_magazine_cache = MAX_SLAB_CHUNK_SIZE (allocator);
458 if (allocator->config.always_malloc || allocator->config.bypass_magazines)
459 allocator->max_slab_chunk_size_for_magazine_cache = 0; /* non-optimized cases */
463 allocator_categorize (gsize aligned_chunk_size)
465 /* speed up the likely path */
466 if (G_LIKELY (aligned_chunk_size && aligned_chunk_size <= allocator->max_slab_chunk_size_for_magazine_cache))
467 return 1; /* use magazine cache */
469 if (!allocator->config.always_malloc &&
470 aligned_chunk_size &&
471 aligned_chunk_size <= MAX_SLAB_CHUNK_SIZE (allocator))
473 if (allocator->config.bypass_magazines)
474 return 2; /* use slab allocator, see [2] */
475 return 1; /* use magazine cache */
477 return 0; /* use malloc() */
481 g_mutex_lock_a (GMutex *mutex,
482 guint *contention_counter)
484 gboolean contention = FALSE;
485 if (!g_mutex_trylock (mutex))
487 g_mutex_lock (mutex);
492 allocator->mutex_counter++;
493 if (allocator->mutex_counter >= 1) /* quickly adapt to contention */
495 allocator->mutex_counter = 0;
496 *contention_counter = MIN (*contention_counter + 1, MAX_MAGAZINE_SIZE);
499 else /* !contention */
501 allocator->mutex_counter--;
502 if (allocator->mutex_counter < -11) /* moderately recover magazine sizes */
504 allocator->mutex_counter = 0;
505 *contention_counter = MAX (*contention_counter, 1) - 1;
510 static inline ThreadMemory*
511 thread_memory_from_self (void)
513 ThreadMemory *tmem = g_private_get (&private_thread_memory);
514 if (G_UNLIKELY (!tmem))
516 static GMutex init_mutex;
519 g_mutex_lock (&init_mutex);
520 if G_UNLIKELY (sys_page_size == 0)
521 g_slice_init_nomessage ();
522 g_mutex_unlock (&init_mutex);
524 n_magazines = MAX_SLAB_INDEX (allocator);
525 tmem = g_malloc0 (sizeof (ThreadMemory) + sizeof (Magazine) * 2 * n_magazines);
526 tmem->magazine1 = (Magazine*) (tmem + 1);
527 tmem->magazine2 = &tmem->magazine1[n_magazines];
528 g_private_set (&private_thread_memory, tmem);
533 static inline ChunkLink*
534 magazine_chain_pop_head (ChunkLink **magazine_chunks)
536 /* magazine chains are linked via ChunkLink->next.
537 * each ChunkLink->data of the toplevel chain may point to a subchain,
538 * linked via ChunkLink->next. ChunkLink->data of the subchains just
539 * contains uninitialized junk.
541 ChunkLink *chunk = (*magazine_chunks)->data;
542 if (G_UNLIKELY (chunk))
544 /* allocating from freed list */
545 (*magazine_chunks)->data = chunk->next;
549 chunk = *magazine_chunks;
550 *magazine_chunks = chunk->next;
555 #if 0 /* useful for debugging */
557 magazine_count (ChunkLink *head)
564 ChunkLink *child = head->data;
566 for (child = head->data; child; child = child->next)
575 allocator_get_magazine_threshold (Allocator *allocator,
578 /* the magazine size calculated here has a lower bound of MIN_MAGAZINE_SIZE,
579 * which is required by the implementation. also, for moderately sized chunks
580 * (say >= 64 bytes), magazine sizes shouldn't be much smaller then the number
581 * of chunks available per page/2 to avoid excessive traffic in the magazine
582 * cache for small to medium sized structures.
583 * the upper bound of the magazine size is effectively provided by
584 * MAX_MAGAZINE_SIZE. for larger chunks, this number is scaled down so that
585 * the content of a single magazine doesn't exceed ca. 16KB.
587 gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
588 guint threshold = MAX (MIN_MAGAZINE_SIZE, allocator->max_page_size / MAX (5 * chunk_size, 5 * 32));
589 guint contention_counter = allocator->contention_counters[ix];
590 if (G_UNLIKELY (contention_counter)) /* single CPU bias */
592 /* adapt contention counter thresholds to chunk sizes */
593 contention_counter = contention_counter * 64 / chunk_size;
594 threshold = MAX (threshold, contention_counter);
599 /* --- magazine cache --- */
601 magazine_cache_update_stamp (void)
603 if (allocator->stamp_counter >= MAX_STAMP_COUNTER)
606 g_get_current_time (&tv);
607 allocator->last_stamp = tv.tv_sec * 1000 + tv.tv_usec / 1000; /* milli seconds */
608 allocator->stamp_counter = 0;
611 allocator->stamp_counter++;
614 static inline ChunkLink*
615 magazine_chain_prepare_fields (ChunkLink *magazine_chunks)
621 /* checked upon initialization: mem_assert (MIN_MAGAZINE_SIZE >= 4); */
622 /* ensure a magazine with at least 4 unused data pointers */
623 chunk1 = magazine_chain_pop_head (&magazine_chunks);
624 chunk2 = magazine_chain_pop_head (&magazine_chunks);
625 chunk3 = magazine_chain_pop_head (&magazine_chunks);
626 chunk4 = magazine_chain_pop_head (&magazine_chunks);
627 chunk4->next = magazine_chunks;
628 chunk3->next = chunk4;
629 chunk2->next = chunk3;
630 chunk1->next = chunk2;
634 /* access the first 3 fields of a specially prepared magazine chain */
635 #define magazine_chain_prev(mc) ((mc)->data)
636 #define magazine_chain_stamp(mc) ((mc)->next->data)
637 #define magazine_chain_uint_stamp(mc) GPOINTER_TO_UINT ((mc)->next->data)
638 #define magazine_chain_next(mc) ((mc)->next->next->data)
639 #define magazine_chain_count(mc) ((mc)->next->next->next->data)
642 magazine_cache_trim (Allocator *allocator,
646 /* g_mutex_lock (allocator->mutex); done by caller */
647 /* trim magazine cache from tail */
648 ChunkLink *current = magazine_chain_prev (allocator->magazines[ix]);
649 ChunkLink *trash = NULL;
650 while (ABS (stamp - magazine_chain_uint_stamp (current)) >= allocator->config.working_set_msecs)
653 ChunkLink *prev = magazine_chain_prev (current);
654 ChunkLink *next = magazine_chain_next (current);
655 magazine_chain_next (prev) = next;
656 magazine_chain_prev (next) = prev;
657 /* clear special fields, put on trash stack */
658 magazine_chain_next (current) = NULL;
659 magazine_chain_count (current) = NULL;
660 magazine_chain_stamp (current) = NULL;
661 magazine_chain_prev (current) = trash;
663 /* fixup list head if required */
664 if (current == allocator->magazines[ix])
666 allocator->magazines[ix] = NULL;
671 g_mutex_unlock (&allocator->magazine_mutex);
675 const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
676 g_mutex_lock (&allocator->slab_mutex);
680 trash = magazine_chain_prev (current);
681 magazine_chain_prev (current) = NULL; /* clear special field */
684 ChunkLink *chunk = magazine_chain_pop_head (¤t);
685 slab_allocator_free_chunk (chunk_size, chunk);
688 g_mutex_unlock (&allocator->slab_mutex);
693 magazine_cache_push_magazine (guint ix,
694 ChunkLink *magazine_chunks,
695 gsize count) /* must be >= MIN_MAGAZINE_SIZE */
697 ChunkLink *current = magazine_chain_prepare_fields (magazine_chunks);
698 ChunkLink *next, *prev;
699 g_mutex_lock (&allocator->magazine_mutex);
700 /* add magazine at head */
701 next = allocator->magazines[ix];
703 prev = magazine_chain_prev (next);
705 next = prev = current;
706 magazine_chain_next (prev) = current;
707 magazine_chain_prev (next) = current;
708 magazine_chain_prev (current) = prev;
709 magazine_chain_next (current) = next;
710 magazine_chain_count (current) = (gpointer) count;
712 magazine_cache_update_stamp();
713 magazine_chain_stamp (current) = GUINT_TO_POINTER (allocator->last_stamp);
714 allocator->magazines[ix] = current;
715 /* free old magazines beyond a certain threshold */
716 magazine_cache_trim (allocator, ix, allocator->last_stamp);
717 /* g_mutex_unlock (allocator->mutex); was done by magazine_cache_trim() */
721 magazine_cache_pop_magazine (guint ix,
724 g_mutex_lock_a (&allocator->magazine_mutex, &allocator->contention_counters[ix]);
725 if (!allocator->magazines[ix])
727 guint magazine_threshold = allocator_get_magazine_threshold (allocator, ix);
728 gsize i, chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
729 ChunkLink *chunk, *head;
730 g_mutex_unlock (&allocator->magazine_mutex);
731 g_mutex_lock (&allocator->slab_mutex);
732 head = slab_allocator_alloc_chunk (chunk_size);
735 for (i = 1; i < magazine_threshold; i++)
737 chunk->next = slab_allocator_alloc_chunk (chunk_size);
742 g_mutex_unlock (&allocator->slab_mutex);
748 ChunkLink *current = allocator->magazines[ix];
749 ChunkLink *prev = magazine_chain_prev (current);
750 ChunkLink *next = magazine_chain_next (current);
752 magazine_chain_next (prev) = next;
753 magazine_chain_prev (next) = prev;
754 allocator->magazines[ix] = next == current ? NULL : next;
755 g_mutex_unlock (&allocator->magazine_mutex);
756 /* clear special fields and hand out */
757 *countp = (gsize) magazine_chain_count (current);
758 magazine_chain_prev (current) = NULL;
759 magazine_chain_next (current) = NULL;
760 magazine_chain_count (current) = NULL;
761 magazine_chain_stamp (current) = NULL;
766 /* --- thread magazines --- */
768 private_thread_memory_cleanup (gpointer data)
770 ThreadMemory *tmem = data;
771 const guint n_magazines = MAX_SLAB_INDEX (allocator);
773 for (ix = 0; ix < n_magazines; ix++)
777 mags[0] = &tmem->magazine1[ix];
778 mags[1] = &tmem->magazine2[ix];
779 for (j = 0; j < 2; j++)
781 Magazine *mag = mags[j];
782 if (mag->count >= MIN_MAGAZINE_SIZE)
783 magazine_cache_push_magazine (ix, mag->chunks, mag->count);
786 const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
787 g_mutex_lock (&allocator->slab_mutex);
790 ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
791 slab_allocator_free_chunk (chunk_size, chunk);
793 g_mutex_unlock (&allocator->slab_mutex);
801 thread_memory_magazine1_reload (ThreadMemory *tmem,
804 Magazine *mag = &tmem->magazine1[ix];
805 mem_assert (mag->chunks == NULL); /* ensure that we may reset mag->count */
807 mag->chunks = magazine_cache_pop_magazine (ix, &mag->count);
811 thread_memory_magazine2_unload (ThreadMemory *tmem,
814 Magazine *mag = &tmem->magazine2[ix];
815 magazine_cache_push_magazine (ix, mag->chunks, mag->count);
821 thread_memory_swap_magazines (ThreadMemory *tmem,
824 Magazine xmag = tmem->magazine1[ix];
825 tmem->magazine1[ix] = tmem->magazine2[ix];
826 tmem->magazine2[ix] = xmag;
829 static inline gboolean
830 thread_memory_magazine1_is_empty (ThreadMemory *tmem,
833 return tmem->magazine1[ix].chunks == NULL;
836 static inline gboolean
837 thread_memory_magazine2_is_full (ThreadMemory *tmem,
840 return tmem->magazine2[ix].count >= allocator_get_magazine_threshold (allocator, ix);
843 static inline gpointer
844 thread_memory_magazine1_alloc (ThreadMemory *tmem,
847 Magazine *mag = &tmem->magazine1[ix];
848 ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
849 if (G_LIKELY (mag->count > 0))
855 thread_memory_magazine2_free (ThreadMemory *tmem,
859 Magazine *mag = &tmem->magazine2[ix];
860 ChunkLink *chunk = mem;
862 chunk->next = mag->chunks;
867 /* --- API functions --- */
871 * @type: the type to allocate, typically a structure name
873 * A convenience macro to allocate a block of memory from the
876 * It calls g_slice_alloc() with <literal>sizeof (@type)</literal>
877 * and casts the returned pointer to a pointer of the given type,
878 * avoiding a type cast in the source code.
879 * Note that the underlying slice allocation mechanism can
880 * be changed with the <link linkend="G_SLICE">G_SLICE=always-malloc</link>
881 * environment variable.
883 * Returns: a pointer to the allocated block, cast to a pointer to @type
890 * @type: the type to allocate, typically a structure name
892 * A convenience macro to allocate a block of memory from the
893 * slice allocator and set the memory to 0.
895 * It calls g_slice_alloc0() with <literal>sizeof (@type)</literal>
896 * and casts the returned pointer to a pointer of the given type,
897 * avoiding a type cast in the source code.
898 * Note that the underlying slice allocation mechanism can
899 * be changed with the <link linkend="G_SLICE">G_SLICE=always-malloc</link>
900 * environment variable.
907 * @type: the type to duplicate, typically a structure name
908 * @mem: the memory to copy into the allocated block
910 * A convenience macro to duplicate a block of memory using
911 * the slice allocator.
913 * It calls g_slice_copy() with <literal>sizeof (@type)</literal>
914 * and casts the returned pointer to a pointer of the given type,
915 * avoiding a type cast in the source code.
916 * Note that the underlying slice allocation mechanism can
917 * be changed with the <link linkend="G_SLICE">G_SLICE=always-malloc</link>
918 * environment variable.
920 * Returns: a pointer to the allocated block, cast to a pointer to @type
927 * @type: the type of the block to free, typically a structure name
928 * @mem: a pointer to the block to free
930 * A convenience macro to free a block of memory that has
931 * been allocated from the slice allocator.
933 * It calls g_slice_free1() using <literal>sizeof (type)</literal>
935 * Note that the exact release behaviour can be changed with the
936 * <link linkend="G_DEBUG">G_DEBUG=gc-friendly</link> environment
937 * variable, also see <link linkend="G_SLICE">G_SLICE</link> for
938 * related debugging options.
944 * g_slice_free_chain:
945 * @type: the type of the @mem_chain blocks
946 * @mem_chain: a pointer to the first block of the chain
947 * @next: the field name of the next pointer in @type
949 * Frees a linked list of memory blocks of structure type @type.
950 * The memory blocks must be equal-sized, allocated via
951 * g_slice_alloc() or g_slice_alloc0() and linked together by
952 * a @next pointer (similar to #GSList). The name of the
953 * @next field in @type is passed as third argument.
954 * Note that the exact release behaviour can be changed with the
955 * <link linkend="G_DEBUG">G_DEBUG=gc-friendly</link> environment
956 * variable, also see <link linkend="G_SLICE">G_SLICE</link> for
957 * related debugging options.
964 * @block_size: the number of bytes to allocate
966 * Allocates a block of memory from the slice allocator.
967 * The block adress handed out can be expected to be aligned
968 * to at least <literal>1 * sizeof (void*)</literal>,
969 * though in general slices are 2 * sizeof (void*) bytes aligned,
970 * if a malloc() fallback implementation is used instead,
971 * the alignment may be reduced in a libc dependent fashion.
972 * Note that the underlying slice allocation mechanism can
973 * be changed with the <link linkend="G_SLICE">G_SLICE=always-malloc</link>
974 * environment variable.
976 * Returns: a pointer to the allocated memory block
981 g_slice_alloc (gsize mem_size)
988 /* This gets the private structure for this thread. If the private
989 * structure does not yet exist, it is created.
991 * This has a side effect of causing GSlice to be initialised, so it
994 tmem = thread_memory_from_self ();
996 chunk_size = P2ALIGN (mem_size);
997 acat = allocator_categorize (chunk_size);
998 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
1000 guint ix = SLAB_INDEX (allocator, chunk_size);
1001 if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
1003 thread_memory_swap_magazines (tmem, ix);
1004 if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
1005 thread_memory_magazine1_reload (tmem, ix);
1007 mem = thread_memory_magazine1_alloc (tmem, ix);
1009 else if (acat == 2) /* allocate through slab allocator */
1011 g_mutex_lock (&allocator->slab_mutex);
1012 mem = slab_allocator_alloc_chunk (chunk_size);
1013 g_mutex_unlock (&allocator->slab_mutex);
1015 else /* delegate to system malloc */
1016 mem = g_malloc (mem_size);
1017 if (G_UNLIKELY (allocator->config.debug_blocks))
1018 smc_notify_alloc (mem, mem_size);
1020 TRACE (GLIB_SLICE_ALLOC((void*)mem, mem_size));
1027 * @block_size: the number of bytes to allocate
1029 * Allocates a block of memory via g_slice_alloc() and initializes
1030 * the returned memory to 0. Note that the underlying slice allocation
1031 * mechanism can be changed with the
1032 * <link linkend="G_SLICE">G_SLICE=always-malloc</link>
1033 * environment variable.
1035 * Returns: a pointer to the allocated block
1040 g_slice_alloc0 (gsize mem_size)
1042 gpointer mem = g_slice_alloc (mem_size);
1044 memset (mem, 0, mem_size);
1050 * @block_size: the number of bytes to allocate
1051 * @mem_block: the memory to copy
1053 * Allocates a block of memory from the slice allocator
1054 * and copies @block_size bytes into it from @mem_block.
1056 * Returns: a pointer to the allocated memory block
1061 g_slice_copy (gsize mem_size,
1062 gconstpointer mem_block)
1064 gpointer mem = g_slice_alloc (mem_size);
1066 memcpy (mem, mem_block, mem_size);
1072 * @block_size: the size of the block
1073 * @mem_block: a pointer to the block to free
1075 * Frees a block of memory.
1077 * The memory must have been allocated via g_slice_alloc() or
1078 * g_slice_alloc0() and the @block_size has to match the size
1079 * specified upon allocation. Note that the exact release behaviour
1080 * can be changed with the
1081 * <link linkend="G_DEBUG">G_DEBUG=gc-friendly</link> environment
1082 * variable, also see <link linkend="G_SLICE">G_SLICE</link> for
1083 * related debugging options.
1088 g_slice_free1 (gsize mem_size,
1091 gsize chunk_size = P2ALIGN (mem_size);
1092 guint acat = allocator_categorize (chunk_size);
1093 if (G_UNLIKELY (!mem_block))
1095 if (G_UNLIKELY (allocator->config.debug_blocks) &&
1096 !smc_notify_free (mem_block, mem_size))
1098 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
1100 ThreadMemory *tmem = thread_memory_from_self();
1101 guint ix = SLAB_INDEX (allocator, chunk_size);
1102 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
1104 thread_memory_swap_magazines (tmem, ix);
1105 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
1106 thread_memory_magazine2_unload (tmem, ix);
1108 if (G_UNLIKELY (g_mem_gc_friendly))
1109 memset (mem_block, 0, chunk_size);
1110 thread_memory_magazine2_free (tmem, ix, mem_block);
1112 else if (acat == 2) /* allocate through slab allocator */
1114 if (G_UNLIKELY (g_mem_gc_friendly))
1115 memset (mem_block, 0, chunk_size);
1116 g_mutex_lock (&allocator->slab_mutex);
1117 slab_allocator_free_chunk (chunk_size, mem_block);
1118 g_mutex_unlock (&allocator->slab_mutex);
1120 else /* delegate to system malloc */
1122 if (G_UNLIKELY (g_mem_gc_friendly))
1123 memset (mem_block, 0, mem_size);
1126 TRACE (GLIB_SLICE_FREE((void*)mem_block, mem_size));
1130 * g_slice_free_chain_with_offset:
1131 * @block_size: the size of the blocks
1132 * @mem_chain: a pointer to the first block of the chain
1133 * @next_offset: the offset of the @next field in the blocks
1135 * Frees a linked list of memory blocks of structure type @type.
1137 * The memory blocks must be equal-sized, allocated via
1138 * g_slice_alloc() or g_slice_alloc0() and linked together by a
1139 * @next pointer (similar to #GSList). The offset of the @next
1140 * field in each block is passed as third argument.
1141 * Note that the exact release behaviour can be changed with the
1142 * <link linkend="G_DEBUG">G_DEBUG=gc-friendly</link> environment
1143 * variable, also see <link linkend="G_SLICE">G_SLICE</link> for
1144 * related debugging options.
1149 g_slice_free_chain_with_offset (gsize mem_size,
1153 gpointer slice = mem_chain;
1154 /* while the thread magazines and the magazine cache are implemented so that
1155 * they can easily be extended to allow for free lists containing more free
1156 * lists for the first level nodes, which would allow O(1) freeing in this
1157 * function, the benefit of such an extension is questionable, because:
1158 * - the magazine size counts will become mere lower bounds which confuses
1159 * the code adapting to lock contention;
1160 * - freeing a single node to the thread magazines is very fast, so this
1161 * O(list_length) operation is multiplied by a fairly small factor;
1162 * - memory usage histograms on larger applications seem to indicate that
1163 * the amount of released multi node lists is negligible in comparison
1164 * to single node releases.
1165 * - the major performance bottle neck, namely g_private_get() or
1166 * g_mutex_lock()/g_mutex_unlock() has already been moved out of the
1167 * inner loop for freeing chained slices.
1169 gsize chunk_size = P2ALIGN (mem_size);
1170 guint acat = allocator_categorize (chunk_size);
1171 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
1173 ThreadMemory *tmem = thread_memory_from_self();
1174 guint ix = SLAB_INDEX (allocator, chunk_size);
1177 guint8 *current = slice;
1178 slice = *(gpointer*) (current + next_offset);
1179 if (G_UNLIKELY (allocator->config.debug_blocks) &&
1180 !smc_notify_free (current, mem_size))
1182 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
1184 thread_memory_swap_magazines (tmem, ix);
1185 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
1186 thread_memory_magazine2_unload (tmem, ix);
1188 if (G_UNLIKELY (g_mem_gc_friendly))
1189 memset (current, 0, chunk_size);
1190 thread_memory_magazine2_free (tmem, ix, current);
1193 else if (acat == 2) /* allocate through slab allocator */
1195 g_mutex_lock (&allocator->slab_mutex);
1198 guint8 *current = slice;
1199 slice = *(gpointer*) (current + next_offset);
1200 if (G_UNLIKELY (allocator->config.debug_blocks) &&
1201 !smc_notify_free (current, mem_size))
1203 if (G_UNLIKELY (g_mem_gc_friendly))
1204 memset (current, 0, chunk_size);
1205 slab_allocator_free_chunk (chunk_size, current);
1207 g_mutex_unlock (&allocator->slab_mutex);
1209 else /* delegate to system malloc */
1212 guint8 *current = slice;
1213 slice = *(gpointer*) (current + next_offset);
1214 if (G_UNLIKELY (allocator->config.debug_blocks) &&
1215 !smc_notify_free (current, mem_size))
1217 if (G_UNLIKELY (g_mem_gc_friendly))
1218 memset (current, 0, mem_size);
1223 /* --- single page allocator --- */
1225 allocator_slab_stack_push (Allocator *allocator,
1229 /* insert slab at slab ring head */
1230 if (!allocator->slab_stack[ix])
1232 sinfo->next = sinfo;
1233 sinfo->prev = sinfo;
1237 SlabInfo *next = allocator->slab_stack[ix], *prev = next->prev;
1243 allocator->slab_stack[ix] = sinfo;
1247 allocator_aligned_page_size (Allocator *allocator,
1250 gsize val = 1 << g_bit_storage (n_bytes - 1);
1251 val = MAX (val, allocator->min_page_size);
1256 allocator_add_slab (Allocator *allocator,
1262 gsize addr, padding, n_chunks, color = 0;
1263 gsize page_size = allocator_aligned_page_size (allocator, SLAB_BPAGE_SIZE (allocator, chunk_size));
1264 /* allocate 1 page for the chunks and the slab */
1265 gpointer aligned_memory = allocator_memalign (page_size, page_size - NATIVE_MALLOC_PADDING);
1266 guint8 *mem = aligned_memory;
1270 const gchar *syserr = "unknown error";
1272 syserr = strerror (errno);
1274 mem_error ("failed to allocate %u bytes (alignment: %u): %s\n",
1275 (guint) (page_size - NATIVE_MALLOC_PADDING), (guint) page_size, syserr);
1277 /* mask page address */
1278 addr = ((gsize) mem / page_size) * page_size;
1279 /* assert alignment */
1280 mem_assert (aligned_memory == (gpointer) addr);
1281 /* basic slab info setup */
1282 sinfo = (SlabInfo*) (mem + page_size - SLAB_INFO_SIZE);
1283 sinfo->n_allocated = 0;
1284 sinfo->chunks = NULL;
1285 /* figure cache colorization */
1286 n_chunks = ((guint8*) sinfo - mem) / chunk_size;
1287 padding = ((guint8*) sinfo - mem) - n_chunks * chunk_size;
1290 color = (allocator->color_accu * P2ALIGNMENT) % padding;
1291 allocator->color_accu += allocator->config.color_increment;
1293 /* add chunks to free list */
1294 chunk = (ChunkLink*) (mem + color);
1295 sinfo->chunks = chunk;
1296 for (i = 0; i < n_chunks - 1; i++)
1298 chunk->next = (ChunkLink*) ((guint8*) chunk + chunk_size);
1299 chunk = chunk->next;
1301 chunk->next = NULL; /* last chunk */
1302 /* add slab to slab ring */
1303 allocator_slab_stack_push (allocator, ix, sinfo);
1307 slab_allocator_alloc_chunk (gsize chunk_size)
1310 guint ix = SLAB_INDEX (allocator, chunk_size);
1311 /* ensure non-empty slab */
1312 if (!allocator->slab_stack[ix] || !allocator->slab_stack[ix]->chunks)
1313 allocator_add_slab (allocator, ix, chunk_size);
1314 /* allocate chunk */
1315 chunk = allocator->slab_stack[ix]->chunks;
1316 allocator->slab_stack[ix]->chunks = chunk->next;
1317 allocator->slab_stack[ix]->n_allocated++;
1318 /* rotate empty slabs */
1319 if (!allocator->slab_stack[ix]->chunks)
1320 allocator->slab_stack[ix] = allocator->slab_stack[ix]->next;
1325 slab_allocator_free_chunk (gsize chunk_size,
1330 guint ix = SLAB_INDEX (allocator, chunk_size);
1331 gsize page_size = allocator_aligned_page_size (allocator, SLAB_BPAGE_SIZE (allocator, chunk_size));
1332 gsize addr = ((gsize) mem / page_size) * page_size;
1333 /* mask page address */
1334 guint8 *page = (guint8*) addr;
1335 SlabInfo *sinfo = (SlabInfo*) (page + page_size - SLAB_INFO_SIZE);
1336 /* assert valid chunk count */
1337 mem_assert (sinfo->n_allocated > 0);
1338 /* add chunk to free list */
1339 was_empty = sinfo->chunks == NULL;
1340 chunk = (ChunkLink*) mem;
1341 chunk->next = sinfo->chunks;
1342 sinfo->chunks = chunk;
1343 sinfo->n_allocated--;
1344 /* keep slab ring partially sorted, empty slabs at end */
1348 SlabInfo *next = sinfo->next, *prev = sinfo->prev;
1351 if (allocator->slab_stack[ix] == sinfo)
1352 allocator->slab_stack[ix] = next == sinfo ? NULL : next;
1353 /* insert slab at head */
1354 allocator_slab_stack_push (allocator, ix, sinfo);
1356 /* eagerly free complete unused slabs */
1357 if (!sinfo->n_allocated)
1360 SlabInfo *next = sinfo->next, *prev = sinfo->prev;
1363 if (allocator->slab_stack[ix] == sinfo)
1364 allocator->slab_stack[ix] = next == sinfo ? NULL : next;
1366 allocator_memfree (page_size, page);
1370 /* --- memalign implementation --- */
1371 #ifdef HAVE_MALLOC_H
1372 #include <malloc.h> /* memalign() */
1376 * define HAVE_POSIX_MEMALIGN 1 // if free(posix_memalign(3)) works, <stdlib.h>
1377 * define HAVE_COMPLIANT_POSIX_MEMALIGN 1 // if free(posix_memalign(3)) works for sizes != 2^n, <stdlib.h>
1378 * define HAVE_MEMALIGN 1 // if free(memalign(3)) works, <malloc.h>
1379 * define HAVE_VALLOC 1 // if free(valloc(3)) works, <stdlib.h> or <malloc.h>
1380 * if none is provided, we implement malloc(3)-based alloc-only page alignment
1383 #if !(HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC)
1384 static GTrashStack *compat_valloc_trash = NULL;
1388 allocator_memalign (gsize alignment,
1391 gpointer aligned_memory = NULL;
1393 #if HAVE_COMPLIANT_POSIX_MEMALIGN
1394 err = posix_memalign (&aligned_memory, alignment, memsize);
1397 aligned_memory = memalign (alignment, memsize);
1401 aligned_memory = valloc (memsize);
1404 /* simplistic non-freeing page allocator */
1405 mem_assert (alignment == sys_page_size);
1406 mem_assert (memsize <= sys_page_size);
1407 if (!compat_valloc_trash)
1409 const guint n_pages = 16;
1410 guint8 *mem = malloc (n_pages * sys_page_size);
1415 guint8 *amem = (guint8*) ALIGN ((gsize) mem, sys_page_size);
1417 i--; /* mem wasn't page aligned */
1419 g_trash_stack_push (&compat_valloc_trash, amem + i * sys_page_size);
1422 aligned_memory = g_trash_stack_pop (&compat_valloc_trash);
1424 if (!aligned_memory)
1426 return aligned_memory;
1430 allocator_memfree (gsize memsize,
1433 #if HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC
1436 mem_assert (memsize <= sys_page_size);
1437 g_trash_stack_push (&compat_valloc_trash, mem);
1442 mem_error (const char *format,
1447 /* at least, put out "MEMORY-ERROR", in case we segfault during the rest of the function */
1448 fputs ("\n***MEMORY-ERROR***: ", stderr);
1449 pname = g_get_prgname();
1450 fprintf (stderr, "%s[%ld]: GSlice: ", pname ? pname : "", (long)getpid());
1451 va_start (args, format);
1452 vfprintf (stderr, format, args);
1454 fputs ("\n", stderr);
1459 /* --- g-slice memory checker tree --- */
1460 typedef size_t SmcKType; /* key type */
1461 typedef size_t SmcVType; /* value type */
1466 static void smc_tree_insert (SmcKType key,
1468 static gboolean smc_tree_lookup (SmcKType key,
1470 static gboolean smc_tree_remove (SmcKType key);
1473 /* --- g-slice memory checker implementation --- */
1475 smc_notify_alloc (void *pointer,
1478 size_t adress = (size_t) pointer;
1480 smc_tree_insert (adress, size);
1485 smc_notify_ignore (void *pointer)
1487 size_t adress = (size_t) pointer;
1489 smc_tree_remove (adress);
1494 smc_notify_free (void *pointer,
1497 size_t adress = (size_t) pointer;
1502 return 1; /* ignore */
1503 found_one = smc_tree_lookup (adress, &real_size);
1506 fprintf (stderr, "GSlice: MemChecker: attempt to release non-allocated block: %p size=%" G_GSIZE_FORMAT "\n", pointer, size);
1509 if (real_size != size && (real_size || size))
1511 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);
1514 if (!smc_tree_remove (adress))
1516 fprintf (stderr, "GSlice: MemChecker: attempt to release non-allocated block: %p size=%" G_GSIZE_FORMAT "\n", pointer, size);
1519 return 1; /* all fine */
1522 /* --- g-slice memory checker tree implementation --- */
1523 #define SMC_TRUNK_COUNT (4093 /* 16381 */) /* prime, to distribute trunk collisions (big, allocated just once) */
1524 #define SMC_BRANCH_COUNT (511) /* prime, to distribute branch collisions */
1525 #define SMC_TRUNK_EXTENT (SMC_BRANCH_COUNT * 2039) /* key address space per trunk, should distribute uniformly across BRANCH_COUNT */
1526 #define SMC_TRUNK_HASH(k) ((k / SMC_TRUNK_EXTENT) % SMC_TRUNK_COUNT) /* generate new trunk hash per megabyte (roughly) */
1527 #define SMC_BRANCH_HASH(k) (k % SMC_BRANCH_COUNT)
1531 unsigned int n_entries;
1534 static SmcBranch **smc_tree_root = NULL;
1537 smc_tree_abort (int errval)
1539 const char *syserr = "unknown error";
1541 syserr = strerror (errval);
1543 mem_error ("MemChecker: failure in debugging tree: %s", syserr);
1546 static inline SmcEntry*
1547 smc_tree_branch_grow_L (SmcBranch *branch,
1550 unsigned int old_size = branch->n_entries * sizeof (branch->entries[0]);
1551 unsigned int new_size = old_size + sizeof (branch->entries[0]);
1553 mem_assert (index <= branch->n_entries);
1554 branch->entries = (SmcEntry*) realloc (branch->entries, new_size);
1555 if (!branch->entries)
1556 smc_tree_abort (errno);
1557 entry = branch->entries + index;
1558 g_memmove (entry + 1, entry, (branch->n_entries - index) * sizeof (entry[0]));
1559 branch->n_entries += 1;
1563 static inline SmcEntry*
1564 smc_tree_branch_lookup_nearest_L (SmcBranch *branch,
1567 unsigned int n_nodes = branch->n_entries, offs = 0;
1568 SmcEntry *check = branch->entries;
1570 while (offs < n_nodes)
1572 unsigned int i = (offs + n_nodes) >> 1;
1573 check = branch->entries + i;
1574 cmp = key < check->key ? -1 : key != check->key;
1576 return check; /* return exact match */
1579 else /* (cmp > 0) */
1582 /* check points at last mismatch, cmp > 0 indicates greater key */
1583 return cmp > 0 ? check + 1 : check; /* return insertion position for inexact match */
1587 smc_tree_insert (SmcKType key,
1590 unsigned int ix0, ix1;
1593 g_mutex_lock (&smc_tree_mutex);
1594 ix0 = SMC_TRUNK_HASH (key);
1595 ix1 = SMC_BRANCH_HASH (key);
1598 smc_tree_root = calloc (SMC_TRUNK_COUNT, sizeof (smc_tree_root[0]));
1600 smc_tree_abort (errno);
1602 if (!smc_tree_root[ix0])
1604 smc_tree_root[ix0] = calloc (SMC_BRANCH_COUNT, sizeof (smc_tree_root[0][0]));
1605 if (!smc_tree_root[ix0])
1606 smc_tree_abort (errno);
1608 entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
1609 if (!entry || /* need create */
1610 entry >= smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries || /* need append */
1611 entry->key != key) /* need insert */
1612 entry = smc_tree_branch_grow_L (&smc_tree_root[ix0][ix1], entry - smc_tree_root[ix0][ix1].entries);
1614 entry->value = value;
1615 g_mutex_unlock (&smc_tree_mutex);
1619 smc_tree_lookup (SmcKType key,
1622 SmcEntry *entry = NULL;
1623 unsigned int ix0 = SMC_TRUNK_HASH (key), ix1 = SMC_BRANCH_HASH (key);
1624 gboolean found_one = FALSE;
1626 g_mutex_lock (&smc_tree_mutex);
1627 if (smc_tree_root && smc_tree_root[ix0])
1629 entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
1631 entry < smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries &&
1635 *value_p = entry->value;
1638 g_mutex_unlock (&smc_tree_mutex);
1643 smc_tree_remove (SmcKType key)
1645 unsigned int ix0 = SMC_TRUNK_HASH (key), ix1 = SMC_BRANCH_HASH (key);
1646 gboolean found_one = FALSE;
1647 g_mutex_lock (&smc_tree_mutex);
1648 if (smc_tree_root && smc_tree_root[ix0])
1650 SmcEntry *entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
1652 entry < smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries &&
1655 unsigned int i = entry - smc_tree_root[ix0][ix1].entries;
1656 smc_tree_root[ix0][ix1].n_entries -= 1;
1657 g_memmove (entry, entry + 1, (smc_tree_root[ix0][ix1].n_entries - i) * sizeof (entry[0]));
1658 if (!smc_tree_root[ix0][ix1].n_entries)
1660 /* avoid useless pressure on the memory system */
1661 free (smc_tree_root[ix0][ix1].entries);
1662 smc_tree_root[ix0][ix1].entries = NULL;
1667 g_mutex_unlock (&smc_tree_mutex);
1671 #ifdef G_ENABLE_DEBUG
1673 g_slice_debug_tree_statistics (void)
1675 g_mutex_lock (&smc_tree_mutex);
1678 unsigned int i, j, t = 0, o = 0, b = 0, su = 0, ex = 0, en = 4294967295u;
1680 for (i = 0; i < SMC_TRUNK_COUNT; i++)
1681 if (smc_tree_root[i])
1684 for (j = 0; j < SMC_BRANCH_COUNT; j++)
1685 if (smc_tree_root[i][j].n_entries)
1688 su += smc_tree_root[i][j].n_entries;
1689 en = MIN (en, smc_tree_root[i][j].n_entries);
1690 ex = MAX (ex, smc_tree_root[i][j].n_entries);
1692 else if (smc_tree_root[i][j].entries)
1693 o++; /* formerly used, now empty */
1696 tf = MAX (t, 1.0); /* max(1) to be a valid divisor */
1697 bf = MAX (b, 1.0); /* max(1) to be a valid divisor */
1698 fprintf (stderr, "GSlice: MemChecker: %u trunks, %u branches, %u old branches\n", t, b, o);
1699 fprintf (stderr, "GSlice: MemChecker: %f branches per trunk, %.2f%% utilization\n",
1701 100.0 - (SMC_BRANCH_COUNT - b / tf) / (0.01 * SMC_BRANCH_COUNT));
1702 fprintf (stderr, "GSlice: MemChecker: %f entries per branch, %u minimum, %u maximum\n",
1706 fprintf (stderr, "GSlice: MemChecker: root=NULL\n");
1707 g_mutex_unlock (&smc_tree_mutex);
1709 /* sample statistics (beast + GSLice + 24h scripted core & GUI activity):
1710 * PID %CPU %MEM VSZ RSS COMMAND
1711 * 8887 30.3 45.8 456068 414856 beast-0.7.1 empty.bse
1712 * $ cat /proc/8887/statm # total-program-size resident-set-size shared-pages text/code data/stack library dirty-pages
1713 * 114017 103714 2354 344 0 108676 0
1714 * $ cat /proc/8887/status
1725 * (gdb) print g_slice_debug_tree_statistics ()
1726 * GSlice: MemChecker: 422 trunks, 213068 branches, 0 old branches
1727 * GSlice: MemChecker: 504.900474 branches per trunk, 98.81% utilization
1728 * GSlice: MemChecker: 4.965039 entries per branch, 1 minimum, 37 maximum
1731 #endif /* G_ENABLE_DEBUG */