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.
23 #if defined HAVE_POSIX_MEMALIGN && defined POSIX_MEMALIGN_WITH_COMPLIANT_ALLOCS
24 # define HAVE_COMPLIANT_POSIX_MEMALIGN 1
27 #ifdef HAVE_COMPLIANT_POSIX_MEMALIGN
28 #define _XOPEN_SOURCE 600 /* posix_memalign() */
30 #include <stdlib.h> /* posix_memalign() */
33 #include "gmem.h" /* gslice.h */
34 #include "gthreadprivate.h"
38 #include <unistd.h> /* sysconf() */
45 /* the GSlice allocator is split up into 4 layers, roughly modelled after the slab
46 * allocator and magazine extensions as outlined in:
47 * + [Bonwick94] Jeff Bonwick, The slab allocator: An object-caching kernel
48 * memory allocator. USENIX 1994, http://citeseer.ist.psu.edu/bonwick94slab.html
49 * + [Bonwick01] Bonwick and Jonathan Adams, Magazines and vmem: Extending the
50 * slab allocator to many cpu's and arbitrary resources.
51 * USENIX 2001, http://citeseer.ist.psu.edu/bonwick01magazines.html
53 * - the thread magazines. for each (aligned) chunk size, a magazine (a list)
54 * of recently freed and soon to be allocated chunks is maintained per thread.
55 * this way, most alloc/free requests can be quickly satisfied from per-thread
56 * free lists which only require one g_private_get() call to retrive the
58 * - the magazine cache. allocating and freeing chunks to/from threads only
59 * occours at magazine sizes from a global depot of magazines. the depot
60 * maintaines a 15 second working set of allocated magazines, so full
61 * magazines are not allocated and released too often.
62 * the chunk size dependent magazine sizes automatically adapt (within limits,
63 * see [3]) to lock contention to properly scale performance across a variety
65 * - the slab allocator. this allocator allocates slabs (blocks of memory) close
66 * to the system page size or multiples thereof which have to be page aligned.
67 * the blocks are divided into smaller chunks which are used to satisfy
68 * allocations from the upper layers. the space provided by the reminder of
69 * the chunk size division is used for cache colorization (random distribution
70 * of chunk addresses) to improve processor cache utilization. multiple slabs
71 * with the same chunk size are kept in a partially sorted ring to allow O(1)
72 * freeing and allocation of chunks (as long as the allocation of an entirely
73 * new slab can be avoided).
74 * - the page allocator. on most modern systems, posix_memalign(3) or
75 * memalign(3) should be available, so this is used to allocate blocks with
76 * system page size based alignments and sizes or multiples thereof.
77 * if no memalign variant is provided, valloc() is used instead and
78 * block sizes are limited to the system page size (no multiples thereof).
79 * as a fallback, on system without even valloc(), a malloc(3)-based page
80 * allocator with alloc-only behaviour is used.
83 * [1] some systems memalign(3) implementations may rely on boundary tagging for
84 * the handed out memory chunks. to avoid excessive page-wise fragmentation,
85 * we reserve 2 * sizeof (void*) per block size for the systems memalign(3),
86 * specified in NATIVE_MALLOC_PADDING.
87 * [2] using the slab allocator alone already provides for a fast and efficient
88 * allocator, it doesn't properly scale beyond single-threaded uses though.
89 * also, the slab allocator implements eager free(3)-ing, i.e. does not
90 * provide any form of caching or working set maintenance. so if used alone,
91 * it's vulnerable to trashing for sequences of balanced (alloc, free) pairs
92 * at certain thresholds.
93 * [3] magazine sizes are bound by an implementation specific minimum size and
94 * a chunk size specific maximum to limit magazine storage sizes to roughly
96 * [4] allocating ca. 8 chunks per block/page keeps a good balance between
97 * external and internal fragmentation (<= 12.5%). [Bonwick94]
100 /* --- macros and constants --- */
101 #define LARGEALIGNMENT (256)
102 #define P2ALIGNMENT (2 * sizeof (gsize)) /* fits 2 pointers (assumed to be 2 * GLIB_SIZEOF_SIZE_T below) */
103 #define ALIGN(size, base) ((base) * (gsize) (((size) + (base) - 1) / (base)))
104 #define NATIVE_MALLOC_PADDING P2ALIGNMENT /* per-page padding left for native malloc(3) see [1] */
105 #define SLAB_INFO_SIZE P2ALIGN (sizeof (SlabInfo) + NATIVE_MALLOC_PADDING)
106 #define MAX_MAGAZINE_SIZE (256) /* see [3] and allocator_get_magazine_threshold() for this */
107 #define MIN_MAGAZINE_SIZE (4)
108 #define MAX_STAMP_COUNTER (7) /* distributes the load of gettimeofday() */
109 #define MAX_SLAB_CHUNK_SIZE(al) (((al)->max_page_size - SLAB_INFO_SIZE) / 8) /* we want at last 8 chunks per page, see [4] */
110 #define MAX_SLAB_INDEX(al) (SLAB_INDEX (al, MAX_SLAB_CHUNK_SIZE (al)) + 1)
111 #define SLAB_INDEX(al, asize) ((asize) / P2ALIGNMENT - 1) /* asize must be P2ALIGNMENT aligned */
112 #define SLAB_CHUNK_SIZE(al, ix) (((ix) + 1) * P2ALIGNMENT)
113 #define SLAB_BPAGE_SIZE(al,csz) (8 * (csz) + SLAB_INFO_SIZE)
115 /* optimized version of ALIGN (size, P2ALIGNMENT) */
116 #if GLIB_SIZEOF_SIZE_T * 2 == 8 /* P2ALIGNMENT */
117 #define P2ALIGN(size) (((size) + 0x7) & ~(gsize) 0x7)
118 #elif GLIB_SIZEOF_SIZE_T * 2 == 16 /* P2ALIGNMENT */
119 #define P2ALIGN(size) (((size) + 0xf) & ~(gsize) 0xf)
121 #define P2ALIGN(size) ALIGN (size, P2ALIGNMENT)
124 /* special helpers to avoid gmessage.c dependency */
125 static void mem_error (const char *format, ...) G_GNUC_PRINTF (1,2);
126 #define mem_assert(cond) do { if (G_LIKELY (cond)) ; else mem_error ("assertion failed: %s", #cond); } while (0)
128 /* --- structures --- */
129 typedef struct _ChunkLink ChunkLink;
130 typedef struct _SlabInfo SlabInfo;
131 typedef struct _CachedMagazine CachedMagazine;
139 SlabInfo *next, *prev;
143 gsize count; /* approximative chunks list length */
146 Magazine *magazine1; /* array of MAX_SLAB_INDEX (allocator) */
147 Magazine *magazine2; /* array of MAX_SLAB_INDEX (allocator) */
150 gboolean always_malloc;
151 gboolean bypass_magazines;
152 gboolean debug_blocks;
153 gsize working_set_msecs;
154 guint color_increment;
157 /* const after initialization */
158 gsize min_page_size, max_page_size;
160 gsize max_slab_chunk_size_for_magazine_cache;
162 GMutex *magazine_mutex;
163 ChunkLink **magazines; /* array of MAX_SLAB_INDEX (allocator) */
164 guint *contention_counters; /* array of MAX_SLAB_INDEX (allocator) */
170 SlabInfo **slab_stack; /* array of MAX_SLAB_INDEX (allocator) */
174 /* --- g-slice prototypes --- */
175 static gpointer slab_allocator_alloc_chunk (gsize chunk_size);
176 static void slab_allocator_free_chunk (gsize chunk_size,
178 static void private_thread_memory_cleanup (gpointer data);
179 static gpointer allocator_memalign (gsize alignment,
181 static void allocator_memfree (gsize memsize,
183 static inline void magazine_cache_update_stamp (void);
184 static inline gsize allocator_get_magazine_threshold (Allocator *allocator,
187 /* --- g-slice memory checker --- */
188 static void smc_notify_alloc (void *pointer,
190 static int smc_notify_free (void *pointer,
193 /* --- variables --- */
194 static GPrivate *private_thread_memory = NULL;
195 static gsize sys_page_size = 0;
196 static Allocator allocator[1] = { { 0, }, };
197 static SliceConfig slice_config = {
198 FALSE, /* always_malloc */
199 FALSE, /* bypass_magazines */
200 FALSE, /* debug_blocks */
201 15 * 1000, /* working_set_msecs */
202 1, /* color increment, alt: 0x7fffffff */
204 static GMutex *smc_tree_mutex = NULL; /* mutex for G_SLICE=debug-blocks */
206 /* --- auxillary funcitons --- */
208 g_slice_set_config (GSliceConfig ckey,
211 g_return_if_fail (sys_page_size == 0);
214 case G_SLICE_CONFIG_ALWAYS_MALLOC:
215 slice_config.always_malloc = value != 0;
217 case G_SLICE_CONFIG_BYPASS_MAGAZINES:
218 slice_config.bypass_magazines = value != 0;
220 case G_SLICE_CONFIG_WORKING_SET_MSECS:
221 slice_config.working_set_msecs = value;
223 case G_SLICE_CONFIG_COLOR_INCREMENT:
224 slice_config.color_increment = value;
230 g_slice_get_config (GSliceConfig ckey)
234 case G_SLICE_CONFIG_ALWAYS_MALLOC:
235 return slice_config.always_malloc;
236 case G_SLICE_CONFIG_BYPASS_MAGAZINES:
237 return slice_config.bypass_magazines;
238 case G_SLICE_CONFIG_WORKING_SET_MSECS:
239 return slice_config.working_set_msecs;
240 case G_SLICE_CONFIG_CHUNK_SIZES:
241 return MAX_SLAB_INDEX (allocator);
242 case G_SLICE_CONFIG_COLOR_INCREMENT:
243 return slice_config.color_increment;
250 g_slice_get_config_state (GSliceConfig ckey,
255 g_return_val_if_fail (n_values != NULL, NULL);
260 case G_SLICE_CONFIG_CONTENTION_COUNTER:
261 array[i++] = SLAB_CHUNK_SIZE (allocator, address);
262 array[i++] = allocator->contention_counters[address];
263 array[i++] = allocator_get_magazine_threshold (allocator, address);
265 return g_memdup (array, sizeof (array[0]) * *n_values);
272 slice_config_init (SliceConfig *config)
274 /* don't use g_malloc/g_message here */
276 const gchar *val = _g_getenv_nomalloc ("G_SLICE", buffer);
277 static const GDebugKey keys[] = {
278 { "always-malloc", 1 << 0 },
279 { "debug-blocks", 1 << 1 },
281 gint flags = !val ? 0 : g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
282 *config = slice_config;
283 if (flags & (1 << 0)) /* always-malloc */
284 config->always_malloc = TRUE;
285 if (flags & (1 << 1)) /* debug-blocks */
286 config->debug_blocks = TRUE;
290 g_slice_init_nomessage (void)
292 /* we may not use g_error() or friends here */
293 mem_assert (sys_page_size == 0);
294 mem_assert (MIN_MAGAZINE_SIZE >= 4);
298 SYSTEM_INFO system_info;
299 GetSystemInfo (&system_info);
300 sys_page_size = system_info.dwPageSize;
303 sys_page_size = sysconf (_SC_PAGESIZE); /* = sysconf (_SC_PAGE_SIZE); = getpagesize(); */
305 mem_assert (sys_page_size >= 2 * LARGEALIGNMENT);
306 mem_assert ((sys_page_size & (sys_page_size - 1)) == 0);
307 slice_config_init (&allocator->config);
308 allocator->min_page_size = sys_page_size;
309 #if HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN
310 /* allow allocation of pages up to 8KB (with 8KB alignment).
311 * this is useful because many medium to large sized structures
312 * fit less than 8 times (see [4]) into 4KB pages.
313 * we allow very small page sizes here, to reduce wastage in
314 * threads if only small allocations are required (this does
315 * bear the risk of incresing allocation times and fragmentation
318 allocator->min_page_size = MAX (allocator->min_page_size, 4096);
319 allocator->max_page_size = MAX (allocator->min_page_size, 8192);
320 allocator->min_page_size = MIN (allocator->min_page_size, 128);
322 /* we can only align to system page size */
323 allocator->max_page_size = sys_page_size;
325 allocator->magazine_mutex = NULL; /* _g_slice_thread_init_nomessage() */
326 allocator->magazines = g_new0 (ChunkLink*, MAX_SLAB_INDEX (allocator));
327 allocator->contention_counters = g_new0 (guint, MAX_SLAB_INDEX (allocator));
328 allocator->mutex_counter = 0;
329 allocator->stamp_counter = MAX_STAMP_COUNTER; /* force initial update */
330 allocator->last_stamp = 0;
331 allocator->slab_mutex = NULL; /* _g_slice_thread_init_nomessage() */
332 allocator->slab_stack = g_new0 (SlabInfo*, MAX_SLAB_INDEX (allocator));
333 allocator->color_accu = 0;
334 magazine_cache_update_stamp();
335 /* values cached for performance reasons */
336 allocator->max_slab_chunk_size_for_magazine_cache = MAX_SLAB_CHUNK_SIZE (allocator);
337 if (allocator->config.always_malloc || allocator->config.bypass_magazines)
338 allocator->max_slab_chunk_size_for_magazine_cache = 0; /* non-optimized cases */
339 /* at this point, g_mem_gc_friendly() should be initialized, this
340 * should have been accomplished by the above g_malloc/g_new calls
345 allocator_categorize (gsize aligned_chunk_size)
347 /* speed up the likely path */
348 if (G_LIKELY (aligned_chunk_size && aligned_chunk_size <= allocator->max_slab_chunk_size_for_magazine_cache))
349 return 1; /* use magazine cache */
351 /* the above will fail (max_slab_chunk_size_for_magazine_cache == 0) if the
352 * allocator is still uninitialized, or if we are not configured to use the
356 g_slice_init_nomessage ();
357 if (!allocator->config.always_malloc &&
358 aligned_chunk_size &&
359 aligned_chunk_size <= MAX_SLAB_CHUNK_SIZE (allocator))
361 if (allocator->config.bypass_magazines)
362 return 2; /* use slab allocator, see [2] */
363 return 1; /* use magazine cache */
365 return 0; /* use malloc() */
369 _g_slice_thread_init_nomessage (void)
371 /* we may not use g_error() or friends here */
373 mem_error ("g_thread_init() must be called before GSlice is used, memory corrupted...");
374 g_slice_init_nomessage();
375 private_thread_memory = g_private_new (private_thread_memory_cleanup);
376 allocator->magazine_mutex = g_mutex_new();
377 allocator->slab_mutex = g_mutex_new();
378 if (allocator->config.debug_blocks)
379 smc_tree_mutex = g_mutex_new();
383 g_mutex_lock_a (GMutex *mutex,
384 guint *contention_counter)
386 gboolean contention = FALSE;
387 if (!g_mutex_trylock (mutex))
389 g_mutex_lock (mutex);
394 allocator->mutex_counter++;
395 if (allocator->mutex_counter >= 1) /* quickly adapt to contention */
397 allocator->mutex_counter = 0;
398 *contention_counter = MIN (*contention_counter + 1, MAX_MAGAZINE_SIZE);
401 else /* !contention */
403 allocator->mutex_counter--;
404 if (allocator->mutex_counter < -11) /* moderately recover magazine sizes */
406 allocator->mutex_counter = 0;
407 *contention_counter = MAX (*contention_counter, 1) - 1;
412 static inline ThreadMemory*
413 thread_memory_from_self (void)
415 ThreadMemory *tmem = g_private_get (private_thread_memory);
416 if (G_UNLIKELY (!tmem))
418 const guint n_magazines = MAX_SLAB_INDEX (allocator);
419 tmem = g_malloc0 (sizeof (ThreadMemory) + sizeof (Magazine) * 2 * n_magazines);
420 tmem->magazine1 = (Magazine*) (tmem + 1);
421 tmem->magazine2 = &tmem->magazine1[n_magazines];
422 g_private_set (private_thread_memory, tmem);
427 static inline ChunkLink*
428 magazine_chain_pop_head (ChunkLink **magazine_chunks)
430 /* magazine chains are linked via ChunkLink->next.
431 * each ChunkLink->data of the toplevel chain may point to a subchain,
432 * linked via ChunkLink->next. ChunkLink->data of the subchains just
433 * contains uninitialized junk.
435 ChunkLink *chunk = (*magazine_chunks)->data;
436 if (G_UNLIKELY (chunk))
438 /* allocating from freed list */
439 (*magazine_chunks)->data = chunk->next;
443 chunk = *magazine_chunks;
444 *magazine_chunks = chunk->next;
449 #if 0 /* useful for debugging */
451 magazine_count (ChunkLink *head)
458 ChunkLink *child = head->data;
460 for (child = head->data; child; child = child->next)
469 allocator_get_magazine_threshold (Allocator *allocator,
472 /* the magazine size calculated here has a lower bound of MIN_MAGAZINE_SIZE,
473 * which is required by the implementation. also, for moderately sized chunks
474 * (say >= 64 bytes), magazine sizes shouldn't be much smaller then the number
475 * of chunks available per page/2 to avoid excessive traffic in the magazine
476 * cache for small to medium sized structures.
477 * the upper bound of the magazine size is effectively provided by
478 * MAX_MAGAZINE_SIZE. for larger chunks, this number is scaled down so that
479 * the content of a single magazine doesn't exceed ca. 16KB.
481 gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
482 guint threshold = MAX (MIN_MAGAZINE_SIZE, allocator->max_page_size / MAX (5 * chunk_size, 5 * 32));
483 guint contention_counter = allocator->contention_counters[ix];
484 if (G_UNLIKELY (contention_counter)) /* single CPU bias */
486 /* adapt contention counter thresholds to chunk sizes */
487 contention_counter = contention_counter * 64 / chunk_size;
488 threshold = MAX (threshold, contention_counter);
493 /* --- magazine cache --- */
495 magazine_cache_update_stamp (void)
497 if (allocator->stamp_counter >= MAX_STAMP_COUNTER)
500 g_get_current_time (&tv);
501 allocator->last_stamp = tv.tv_sec * 1000 + tv.tv_usec / 1000; /* milli seconds */
502 allocator->stamp_counter = 0;
505 allocator->stamp_counter++;
508 static inline ChunkLink*
509 magazine_chain_prepare_fields (ChunkLink *magazine_chunks)
515 /* checked upon initialization: mem_assert (MIN_MAGAZINE_SIZE >= 4); */
516 /* ensure a magazine with at least 4 unused data pointers */
517 chunk1 = magazine_chain_pop_head (&magazine_chunks);
518 chunk2 = magazine_chain_pop_head (&magazine_chunks);
519 chunk3 = magazine_chain_pop_head (&magazine_chunks);
520 chunk4 = magazine_chain_pop_head (&magazine_chunks);
521 chunk4->next = magazine_chunks;
522 chunk3->next = chunk4;
523 chunk2->next = chunk3;
524 chunk1->next = chunk2;
528 /* access the first 3 fields of a specially prepared magazine chain */
529 #define magazine_chain_prev(mc) ((mc)->data)
530 #define magazine_chain_stamp(mc) ((mc)->next->data)
531 #define magazine_chain_uint_stamp(mc) GPOINTER_TO_UINT ((mc)->next->data)
532 #define magazine_chain_next(mc) ((mc)->next->next->data)
533 #define magazine_chain_count(mc) ((mc)->next->next->next->data)
536 magazine_cache_trim (Allocator *allocator,
540 /* g_mutex_lock (allocator->mutex); done by caller */
541 /* trim magazine cache from tail */
542 ChunkLink *current = magazine_chain_prev (allocator->magazines[ix]);
543 ChunkLink *trash = NULL;
544 while (ABS (stamp - magazine_chain_uint_stamp (current)) >= allocator->config.working_set_msecs)
547 ChunkLink *prev = magazine_chain_prev (current);
548 ChunkLink *next = magazine_chain_next (current);
549 magazine_chain_next (prev) = next;
550 magazine_chain_prev (next) = prev;
551 /* clear special fields, put on trash stack */
552 magazine_chain_next (current) = NULL;
553 magazine_chain_count (current) = NULL;
554 magazine_chain_stamp (current) = NULL;
555 magazine_chain_prev (current) = trash;
557 /* fixup list head if required */
558 if (current == allocator->magazines[ix])
560 allocator->magazines[ix] = NULL;
565 g_mutex_unlock (allocator->magazine_mutex);
569 const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
570 g_mutex_lock (allocator->slab_mutex);
574 trash = magazine_chain_prev (current);
575 magazine_chain_prev (current) = NULL; /* clear special field */
578 ChunkLink *chunk = magazine_chain_pop_head (¤t);
579 slab_allocator_free_chunk (chunk_size, chunk);
582 g_mutex_unlock (allocator->slab_mutex);
587 magazine_cache_push_magazine (guint ix,
588 ChunkLink *magazine_chunks,
589 gsize count) /* must be >= MIN_MAGAZINE_SIZE */
591 ChunkLink *current = magazine_chain_prepare_fields (magazine_chunks);
592 ChunkLink *next, *prev;
593 g_mutex_lock (allocator->magazine_mutex);
594 /* add magazine at head */
595 next = allocator->magazines[ix];
597 prev = magazine_chain_prev (next);
599 next = prev = current;
600 magazine_chain_next (prev) = current;
601 magazine_chain_prev (next) = current;
602 magazine_chain_prev (current) = prev;
603 magazine_chain_next (current) = next;
604 magazine_chain_count (current) = (gpointer) count;
606 magazine_cache_update_stamp();
607 magazine_chain_stamp (current) = GUINT_TO_POINTER (allocator->last_stamp);
608 allocator->magazines[ix] = current;
609 /* free old magazines beyond a certain threshold */
610 magazine_cache_trim (allocator, ix, allocator->last_stamp);
611 /* g_mutex_unlock (allocator->mutex); was done by magazine_cache_trim() */
615 magazine_cache_pop_magazine (guint ix,
618 g_mutex_lock_a (allocator->magazine_mutex, &allocator->contention_counters[ix]);
619 if (!allocator->magazines[ix])
621 guint magazine_threshold = allocator_get_magazine_threshold (allocator, ix);
622 gsize i, chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
623 ChunkLink *chunk, *head;
624 g_mutex_unlock (allocator->magazine_mutex);
625 g_mutex_lock (allocator->slab_mutex);
626 head = slab_allocator_alloc_chunk (chunk_size);
629 for (i = 1; i < magazine_threshold; i++)
631 chunk->next = slab_allocator_alloc_chunk (chunk_size);
636 g_mutex_unlock (allocator->slab_mutex);
642 ChunkLink *current = allocator->magazines[ix];
643 ChunkLink *prev = magazine_chain_prev (current);
644 ChunkLink *next = magazine_chain_next (current);
646 magazine_chain_next (prev) = next;
647 magazine_chain_prev (next) = prev;
648 allocator->magazines[ix] = next == current ? NULL : next;
649 g_mutex_unlock (allocator->magazine_mutex);
650 /* clear special fields and hand out */
651 *countp = (gsize) magazine_chain_count (current);
652 magazine_chain_prev (current) = NULL;
653 magazine_chain_next (current) = NULL;
654 magazine_chain_count (current) = NULL;
655 magazine_chain_stamp (current) = NULL;
660 /* --- thread magazines --- */
662 private_thread_memory_cleanup (gpointer data)
664 ThreadMemory *tmem = data;
665 const guint n_magazines = MAX_SLAB_INDEX (allocator);
667 for (ix = 0; ix < n_magazines; ix++)
671 mags[0] = &tmem->magazine1[ix];
672 mags[1] = &tmem->magazine2[ix];
673 for (j = 0; j < 2; j++)
675 Magazine *mag = mags[j];
676 if (mag->count >= MIN_MAGAZINE_SIZE)
677 magazine_cache_push_magazine (ix, mag->chunks, mag->count);
680 const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
681 g_mutex_lock (allocator->slab_mutex);
684 ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
685 slab_allocator_free_chunk (chunk_size, chunk);
687 g_mutex_unlock (allocator->slab_mutex);
695 thread_memory_magazine1_reload (ThreadMemory *tmem,
698 Magazine *mag = &tmem->magazine1[ix];
699 mem_assert (mag->chunks == NULL); /* ensure that we may reset mag->count */
701 mag->chunks = magazine_cache_pop_magazine (ix, &mag->count);
705 thread_memory_magazine2_unload (ThreadMemory *tmem,
708 Magazine *mag = &tmem->magazine2[ix];
709 magazine_cache_push_magazine (ix, mag->chunks, mag->count);
715 thread_memory_swap_magazines (ThreadMemory *tmem,
718 Magazine xmag = tmem->magazine1[ix];
719 tmem->magazine1[ix] = tmem->magazine2[ix];
720 tmem->magazine2[ix] = xmag;
723 static inline gboolean
724 thread_memory_magazine1_is_empty (ThreadMemory *tmem,
727 return tmem->magazine1[ix].chunks == NULL;
730 static inline gboolean
731 thread_memory_magazine2_is_full (ThreadMemory *tmem,
734 return tmem->magazine2[ix].count >= allocator_get_magazine_threshold (allocator, ix);
737 static inline gpointer
738 thread_memory_magazine1_alloc (ThreadMemory *tmem,
741 Magazine *mag = &tmem->magazine1[ix];
742 ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
743 if (G_LIKELY (mag->count > 0))
749 thread_memory_magazine2_free (ThreadMemory *tmem,
753 Magazine *mag = &tmem->magazine2[ix];
754 ChunkLink *chunk = mem;
756 chunk->next = mag->chunks;
761 /* --- API functions --- */
763 g_slice_alloc (gsize mem_size)
768 chunk_size = P2ALIGN (mem_size);
769 acat = allocator_categorize (chunk_size);
770 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
772 ThreadMemory *tmem = thread_memory_from_self();
773 guint ix = SLAB_INDEX (allocator, chunk_size);
774 if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
776 thread_memory_swap_magazines (tmem, ix);
777 if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
778 thread_memory_magazine1_reload (tmem, ix);
780 mem = thread_memory_magazine1_alloc (tmem, ix);
782 else if (acat == 2) /* allocate through slab allocator */
784 g_mutex_lock (allocator->slab_mutex);
785 mem = slab_allocator_alloc_chunk (chunk_size);
786 g_mutex_unlock (allocator->slab_mutex);
788 else /* delegate to system malloc */
789 mem = g_malloc (mem_size);
790 if (G_UNLIKELY (allocator->config.debug_blocks))
791 smc_notify_alloc (mem, mem_size);
796 g_slice_alloc0 (gsize mem_size)
798 gpointer mem = g_slice_alloc (mem_size);
800 memset (mem, 0, mem_size);
805 g_slice_free1 (gsize mem_size,
808 gsize chunk_size = P2ALIGN (mem_size);
809 guint acat = allocator_categorize (chunk_size);
810 if (G_UNLIKELY (!mem_block))
812 if (G_UNLIKELY (allocator->config.debug_blocks) &&
813 !smc_notify_free (mem_block, mem_size))
815 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
817 ThreadMemory *tmem = thread_memory_from_self();
818 guint ix = SLAB_INDEX (allocator, chunk_size);
819 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
821 thread_memory_swap_magazines (tmem, ix);
822 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
823 thread_memory_magazine2_unload (tmem, ix);
825 if (G_UNLIKELY (g_mem_gc_friendly))
826 memset (mem_block, 0, chunk_size);
827 thread_memory_magazine2_free (tmem, ix, mem_block);
829 else if (acat == 2) /* allocate through slab allocator */
831 if (G_UNLIKELY (g_mem_gc_friendly))
832 memset (mem_block, 0, chunk_size);
833 g_mutex_lock (allocator->slab_mutex);
834 slab_allocator_free_chunk (chunk_size, mem_block);
835 g_mutex_unlock (allocator->slab_mutex);
837 else /* delegate to system malloc */
839 if (G_UNLIKELY (g_mem_gc_friendly))
840 memset (mem_block, 0, mem_size);
846 g_slice_free_chain_with_offset (gsize mem_size,
850 gpointer slice = mem_chain;
851 /* while the thread magazines and the magazine cache are implemented so that
852 * they can easily be extended to allow for free lists containing more free
853 * lists for the first level nodes, which would allow O(1) freeing in this
854 * function, the benefit of such an extension is questionable, because:
855 * - the magazine size counts will become mere lower bounds which confuses
856 * the code adapting to lock contention;
857 * - freeing a single node to the thread magazines is very fast, so this
858 * O(list_length) operation is multiplied by a fairly small factor;
859 * - memory usage histograms on larger applications seem to indicate that
860 * the amount of released multi node lists is negligible in comparison
861 * to single node releases.
862 * - the major performance bottle neck, namely g_private_get() or
863 * g_mutex_lock()/g_mutex_unlock() has already been moved out of the
864 * inner loop for freeing chained slices.
866 gsize chunk_size = P2ALIGN (mem_size);
867 guint acat = allocator_categorize (chunk_size);
868 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
870 ThreadMemory *tmem = thread_memory_from_self();
871 guint ix = SLAB_INDEX (allocator, chunk_size);
874 guint8 *current = slice;
875 slice = *(gpointer*) (current + next_offset);
876 if (G_UNLIKELY (allocator->config.debug_blocks) &&
877 !smc_notify_free (current, mem_size))
879 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
881 thread_memory_swap_magazines (tmem, ix);
882 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
883 thread_memory_magazine2_unload (tmem, ix);
885 if (G_UNLIKELY (g_mem_gc_friendly))
886 memset (current, 0, chunk_size);
887 thread_memory_magazine2_free (tmem, ix, current);
890 else if (acat == 2) /* allocate through slab allocator */
892 g_mutex_lock (allocator->slab_mutex);
895 guint8 *current = slice;
896 slice = *(gpointer*) (current + next_offset);
897 if (G_UNLIKELY (allocator->config.debug_blocks) &&
898 !smc_notify_free (current, mem_size))
900 if (G_UNLIKELY (g_mem_gc_friendly))
901 memset (current, 0, chunk_size);
902 slab_allocator_free_chunk (chunk_size, current);
904 g_mutex_unlock (allocator->slab_mutex);
906 else /* delegate to system malloc */
909 guint8 *current = slice;
910 slice = *(gpointer*) (current + next_offset);
911 if (G_UNLIKELY (allocator->config.debug_blocks) &&
912 !smc_notify_free (current, mem_size))
914 if (G_UNLIKELY (g_mem_gc_friendly))
915 memset (current, 0, mem_size);
920 /* --- single page allocator --- */
922 allocator_slab_stack_push (Allocator *allocator,
926 /* insert slab at slab ring head */
927 if (!allocator->slab_stack[ix])
934 SlabInfo *next = allocator->slab_stack[ix], *prev = next->prev;
940 allocator->slab_stack[ix] = sinfo;
944 allocator_aligned_page_size (Allocator *allocator,
947 gsize val = 1 << g_bit_storage (n_bytes - 1);
948 val = MAX (val, allocator->min_page_size);
953 allocator_add_slab (Allocator *allocator,
959 gsize addr, padding, n_chunks, color = 0;
960 gsize page_size = allocator_aligned_page_size (allocator, SLAB_BPAGE_SIZE (allocator, chunk_size));
961 /* allocate 1 page for the chunks and the slab */
962 gpointer aligned_memory = allocator_memalign (page_size, page_size - NATIVE_MALLOC_PADDING);
963 guint8 *mem = aligned_memory;
967 const gchar *syserr = "unknown error";
969 syserr = strerror (errno);
971 mem_error ("failed to allocate %u bytes (alignment: %u): %s\n",
972 (guint) (page_size - NATIVE_MALLOC_PADDING), (guint) page_size, syserr);
974 /* mask page adress */
975 addr = ((gsize) mem / page_size) * page_size;
976 /* assert alignment */
977 mem_assert (aligned_memory == (gpointer) addr);
978 /* basic slab info setup */
979 sinfo = (SlabInfo*) (mem + page_size - SLAB_INFO_SIZE);
980 sinfo->n_allocated = 0;
981 sinfo->chunks = NULL;
982 /* figure cache colorization */
983 n_chunks = ((guint8*) sinfo - mem) / chunk_size;
984 padding = ((guint8*) sinfo - mem) - n_chunks * chunk_size;
987 color = (allocator->color_accu * P2ALIGNMENT) % padding;
988 allocator->color_accu += allocator->config.color_increment;
990 /* add chunks to free list */
991 chunk = (ChunkLink*) (mem + color);
992 sinfo->chunks = chunk;
993 for (i = 0; i < n_chunks - 1; i++)
995 chunk->next = (ChunkLink*) ((guint8*) chunk + chunk_size);
998 chunk->next = NULL; /* last chunk */
999 /* add slab to slab ring */
1000 allocator_slab_stack_push (allocator, ix, sinfo);
1004 slab_allocator_alloc_chunk (gsize chunk_size)
1007 guint ix = SLAB_INDEX (allocator, chunk_size);
1008 /* ensure non-empty slab */
1009 if (!allocator->slab_stack[ix] || !allocator->slab_stack[ix]->chunks)
1010 allocator_add_slab (allocator, ix, chunk_size);
1011 /* allocate chunk */
1012 chunk = allocator->slab_stack[ix]->chunks;
1013 allocator->slab_stack[ix]->chunks = chunk->next;
1014 allocator->slab_stack[ix]->n_allocated++;
1015 /* rotate empty slabs */
1016 if (!allocator->slab_stack[ix]->chunks)
1017 allocator->slab_stack[ix] = allocator->slab_stack[ix]->next;
1022 slab_allocator_free_chunk (gsize chunk_size,
1027 guint ix = SLAB_INDEX (allocator, chunk_size);
1028 gsize page_size = allocator_aligned_page_size (allocator, SLAB_BPAGE_SIZE (allocator, chunk_size));
1029 gsize addr = ((gsize) mem / page_size) * page_size;
1030 /* mask page adress */
1031 guint8 *page = (guint8*) addr;
1032 SlabInfo *sinfo = (SlabInfo*) (page + page_size - SLAB_INFO_SIZE);
1033 /* assert valid chunk count */
1034 mem_assert (sinfo->n_allocated > 0);
1035 /* add chunk to free list */
1036 was_empty = sinfo->chunks == NULL;
1037 chunk = (ChunkLink*) mem;
1038 chunk->next = sinfo->chunks;
1039 sinfo->chunks = chunk;
1040 sinfo->n_allocated--;
1041 /* keep slab ring partially sorted, empty slabs at end */
1045 SlabInfo *next = sinfo->next, *prev = sinfo->prev;
1048 if (allocator->slab_stack[ix] == sinfo)
1049 allocator->slab_stack[ix] = next == sinfo ? NULL : next;
1050 /* insert slab at head */
1051 allocator_slab_stack_push (allocator, ix, sinfo);
1053 /* eagerly free complete unused slabs */
1054 if (!sinfo->n_allocated)
1057 SlabInfo *next = sinfo->next, *prev = sinfo->prev;
1060 if (allocator->slab_stack[ix] == sinfo)
1061 allocator->slab_stack[ix] = next == sinfo ? NULL : next;
1063 allocator_memfree (page_size, page);
1067 /* --- memalign implementation --- */
1068 #ifdef HAVE_MALLOC_H
1069 #include <malloc.h> /* memalign() */
1073 * define HAVE_POSIX_MEMALIGN 1 // if free(posix_memalign(3)) works, <stdlib.h>
1074 * define HAVE_COMPLIANT_POSIX_MEMALIGN 1 // if free(posix_memalign(3)) works for sizes != 2^n, <stdlib.h>
1075 * define HAVE_MEMALIGN 1 // if free(memalign(3)) works, <malloc.h>
1076 * define HAVE_VALLOC 1 // if free(valloc(3)) works, <stdlib.h> or <malloc.h>
1077 * if none is provided, we implement malloc(3)-based alloc-only page alignment
1080 #if !(HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC)
1081 static GTrashStack *compat_valloc_trash = NULL;
1085 allocator_memalign (gsize alignment,
1088 gpointer aligned_memory = NULL;
1090 #if HAVE_COMPLIANT_POSIX_MEMALIGN
1091 err = posix_memalign (&aligned_memory, alignment, memsize);
1094 aligned_memory = memalign (alignment, memsize);
1098 aligned_memory = valloc (memsize);
1101 /* simplistic non-freeing page allocator */
1102 mem_assert (alignment == sys_page_size);
1103 mem_assert (memsize <= sys_page_size);
1104 if (!compat_valloc_trash)
1106 const guint n_pages = 16;
1107 guint8 *mem = malloc (n_pages * sys_page_size);
1112 guint8 *amem = (guint8*) ALIGN ((gsize) mem, sys_page_size);
1114 i--; /* mem wasn't page aligned */
1116 g_trash_stack_push (&compat_valloc_trash, amem + i * sys_page_size);
1119 aligned_memory = g_trash_stack_pop (&compat_valloc_trash);
1121 if (!aligned_memory)
1123 return aligned_memory;
1127 allocator_memfree (gsize memsize,
1130 #if HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC
1133 mem_assert (memsize <= sys_page_size);
1134 g_trash_stack_push (&compat_valloc_trash, mem);
1141 mem_error (const char *format,
1146 /* at least, put out "MEMORY-ERROR", in case we segfault during the rest of the function */
1147 fputs ("\n***MEMORY-ERROR***: ", stderr);
1148 pname = g_get_prgname();
1149 fprintf (stderr, "%s[%u]: GSlice: ", pname ? pname : "", getpid());
1150 va_start (args, format);
1151 vfprintf (stderr, format, args);
1153 fputs ("\n", stderr);
1158 /* --- g-slice memory checker tree --- */
1159 typedef size_t SmcKType; /* key type */
1160 typedef size_t SmcVType; /* value type */
1165 static void smc_tree_insert (SmcKType key,
1167 static gboolean smc_tree_lookup (SmcKType key,
1169 static gboolean smc_tree_remove (SmcKType key);
1172 /* --- g-slice memory checker implementation --- */
1174 smc_notify_alloc (void *pointer,
1177 size_t adress = (size_t) pointer;
1179 smc_tree_insert (adress, size);
1184 smc_notify_ignore (void *pointer)
1186 size_t adress = (size_t) pointer;
1188 smc_tree_remove (adress);
1193 smc_notify_free (void *pointer,
1196 size_t adress = (size_t) pointer;
1198 return 1; /* ignore */
1200 gboolean found_one = smc_tree_lookup (adress, &real_size);
1203 fprintf (stderr, "GSlice: MemChecker: attempt to release non-allocated block: %p size=%zu\n", pointer, size);
1206 if (real_size != size && (real_size || size))
1208 fprintf (stderr, "GSlice: MemChecker: attempt to release block with invalid size: %p size=%zu invalid-size=%zu\n", pointer, real_size, size);
1211 if (!smc_tree_remove (adress))
1213 fprintf (stderr, "GSlice: MemChecker: attempt to release non-allocated block: %p size=%zu\n", pointer, size);
1216 return 1; /* all fine */
1219 /* --- g-slice memory checker tree implementation --- */
1220 #define SMC_TRUNK_COUNT (4093 /* 16381 */) /* prime, to distribute trunk collisions (big, allocated just once) */
1221 #define SMC_BRANCH_COUNT (511) /* prime, to distribute branch collisions */
1222 #define SMC_TRUNK_EXTENT (SMC_BRANCH_COUNT * 2039) /* key adress space per trunk, should distribute uniformly across BRANCH_COUNT */
1223 #define SMC_TRUNK_HASH(k) ((k / SMC_TRUNK_EXTENT) % SMC_TRUNK_COUNT) /* generate new trunk hash per megabyte (roughly) */
1224 #define SMC_BRANCH_HASH(k) (k % SMC_BRANCH_COUNT)
1228 unsigned int n_entries;
1231 static SmcBranch **smc_tree_root = NULL;
1234 smc_tree_abort (int errval)
1236 const char *syserr = "unknown error";
1238 syserr = strerror (errval);
1240 mem_error ("MemChecker: failure in debugging tree: %s", syserr);
1243 static inline SmcEntry*
1244 smc_tree_branch_grow_L (SmcBranch *branch,
1247 unsigned int old_size = branch->n_entries * sizeof (branch->entries[0]);
1248 unsigned int new_size = old_size + sizeof (branch->entries[0]);
1250 mem_assert (index <= branch->n_entries);
1251 branch->entries = (SmcEntry*) realloc (branch->entries, new_size);
1252 if (!branch->entries)
1253 smc_tree_abort (errno);
1254 entry = branch->entries + index;
1255 g_memmove (entry + 1, entry, (branch->n_entries - index) * sizeof (entry[0]));
1256 branch->n_entries += 1;
1260 static inline SmcEntry*
1261 smc_tree_branch_lookup_nearest_L (SmcBranch *branch,
1264 unsigned int n_nodes = branch->n_entries, offs = 0;
1265 SmcEntry *check = branch->entries;
1267 while (offs < n_nodes)
1269 unsigned int i = (offs + n_nodes) >> 1;
1270 check = branch->entries + i;
1271 cmp = key < check->key ? -1 : key != check->key;
1273 return check; /* return exact match */
1276 else /* (cmp > 0) */
1279 /* check points at last mismatch, cmp > 0 indicates greater key */
1280 return cmp > 0 ? check + 1 : check; /* return insertion position for inexact match */
1284 smc_tree_insert (SmcKType key,
1287 g_mutex_lock (smc_tree_mutex);
1288 unsigned int ix0 = SMC_TRUNK_HASH (key), ix1 = SMC_BRANCH_HASH (key);
1291 smc_tree_root = calloc (SMC_TRUNK_COUNT, sizeof (smc_tree_root[0]));
1293 smc_tree_abort (errno);
1295 if (!smc_tree_root[ix0])
1297 smc_tree_root[ix0] = calloc (SMC_BRANCH_COUNT, sizeof (smc_tree_root[0][0]));
1298 if (!smc_tree_root[ix0])
1299 smc_tree_abort (errno);
1301 SmcEntry *entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
1302 if (!entry || /* need create */
1303 entry >= smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries || /* need append */
1304 entry->key != key) /* need insert */
1305 entry = smc_tree_branch_grow_L (&smc_tree_root[ix0][ix1], entry - smc_tree_root[ix0][ix1].entries);
1307 entry->value = value;
1308 g_mutex_unlock (smc_tree_mutex);
1312 smc_tree_lookup (SmcKType key,
1315 unsigned int ix0 = SMC_TRUNK_HASH (key), ix1 = SMC_BRANCH_HASH (key);
1316 gboolean found_one = FALSE;
1318 g_mutex_lock (smc_tree_mutex);
1319 SmcEntry *entry = NULL;
1320 if (smc_tree_root && smc_tree_root[ix0])
1322 entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
1324 entry < smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries &&
1328 *value_p = entry->value;
1331 g_mutex_unlock (smc_tree_mutex);
1336 smc_tree_remove (SmcKType key)
1338 unsigned int ix0 = SMC_TRUNK_HASH (key), ix1 = SMC_BRANCH_HASH (key);
1339 gboolean found_one = FALSE;
1340 g_mutex_lock (smc_tree_mutex);
1341 if (smc_tree_root && smc_tree_root[ix0])
1343 SmcEntry *entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
1345 entry < smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries &&
1348 unsigned int i = entry - smc_tree_root[ix0][ix1].entries;
1349 smc_tree_root[ix0][ix1].n_entries -= 1;
1350 g_memmove (entry, entry + 1, (smc_tree_root[ix0][ix1].n_entries - i) * sizeof (entry[0]));
1351 if (!smc_tree_root[ix0][ix1].n_entries)
1353 /* avoid useless pressure on the memory system */
1354 free (smc_tree_root[ix0][ix1].entries);
1355 smc_tree_root[ix0][ix1].entries = NULL;
1360 g_mutex_unlock (smc_tree_mutex);
1364 #ifdef G_ENABLE_DEBUG
1366 g_slice_debug_tree_statistics (void)
1368 g_mutex_lock (smc_tree_mutex);
1371 unsigned int i, j, t = 0, o = 0, b = 0, su = 0, ex = 0, en = 4294967295u;
1373 for (i = 0; i < SMC_TRUNK_COUNT; i++)
1374 if (smc_tree_root[i])
1377 for (j = 0; j < SMC_BRANCH_COUNT; j++)
1378 if (smc_tree_root[i][j].n_entries)
1381 su += smc_tree_root[i][j].n_entries;
1382 en = MIN (en, smc_tree_root[i][j].n_entries);
1383 ex = MAX (ex, smc_tree_root[i][j].n_entries);
1385 else if (smc_tree_root[i][j].entries)
1386 o++; /* formerly used, now empty */
1389 tf = MAX (t, 1.0); // max(1) to be a valid divisor
1390 bf = MAX (b, 1.0); // max(1) to be a valid divisor
1391 fprintf (stderr, "GSlice: MemChecker: %u trunks, %u branches, %u old branches\n", t, b, o);
1392 fprintf (stderr, "GSlice: MemChecker: %f branches per trunk, %.2f%% utilization\n",
1394 100.0 - (SMC_BRANCH_COUNT - b / tf) / (0.01 * SMC_BRANCH_COUNT));
1395 fprintf (stderr, "GSlice: MemChecker: %f entries per branch, %u minimum, %u maximum\n",
1399 fprintf (stderr, "GSlice: MemChecker: root=NULL\n");
1400 g_mutex_unlock (smc_tree_mutex);
1402 /* sample statistics (beast + GSLice + 24h scripted core & GUI activity):
1403 * PID %CPU %MEM VSZ RSS COMMAND
1404 * 8887 30.3 45.8 456068 414856 beast-0.7.1 empty.bse
1405 * $ cat /proc/8887/statm # total-program-size resident-set-size shared-pages text/code data/stack library dirty-pages
1406 * 114017 103714 2354 344 0 108676 0
1407 * $ cat /proc/8887/status
1418 * (gdb) print g_slice_debug_tree_statistics ()
1419 * GSlice: MemChecker: 422 trunks, 213068 branches, 0 old branches
1420 * GSlice: MemChecker: 504.900474 branches per trunk, 98.81% utilization
1421 * GSlice: MemChecker: 4.965039 entries per branch, 1 minimum, 37 maximum
1424 #endif /* G_ENABLE_DEBUG */
1426 #define __G_SLICE_C__
1427 #include "galiasdef.c"