Merge branch 'macosx-ci' into 'master'
[glib.git] / glib / gslice.c
blob48e4c5a33b25e9488552337745204c191388d7a0
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.1 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
17 /* MT safe */
19 #include "config.h"
20 #include "glibconfig.h"
22 #if defined HAVE_POSIX_MEMALIGN && defined POSIX_MEMALIGN_WITH_COMPLIANT_ALLOCS
23 # define HAVE_COMPLIANT_POSIX_MEMALIGN 1
24 #endif
26 #if defined(HAVE_COMPLIANT_POSIX_MEMALIGN) && !defined(_XOPEN_SOURCE)
27 #define _XOPEN_SOURCE 600 /* posix_memalign() */
28 #endif
29 #include <stdlib.h> /* posix_memalign() */
30 #include <string.h>
31 #include <errno.h>
33 #ifdef G_OS_UNIX
34 #include <unistd.h> /* sysconf() */
35 #endif
36 #ifdef G_OS_WIN32
37 #include <windows.h>
38 #include <process.h>
39 #endif
41 #include <stdio.h> /* fputs */
43 #include "gslice.h"
45 #include "gmain.h"
46 #include "gmem.h" /* gslice.h */
47 #include "gstrfuncs.h"
48 #include "gutils.h"
49 #include "gtrashstack.h"
50 #include "gtestutils.h"
51 #include "gthread.h"
52 #include "glib_trace.h"
53 #include "gprintf.h"
55 #include "gvalgrind.h"
57 /**
58 * SECTION:memory_slices
59 * @title: Memory Slices
60 * @short_description: efficient way to allocate groups of equal-sized
61 * chunks of memory
63 * Memory slices provide a space-efficient and multi-processing scalable
64 * way to allocate equal-sized pieces of memory, just like the original
65 * #GMemChunks (from GLib 2.8), while avoiding their excessive
66 * memory-waste, scalability and performance problems.
68 * To achieve these goals, the slice allocator uses a sophisticated,
69 * layered design that has been inspired by Bonwick's slab allocator
70 * ([Bonwick94](http://citeseer.ist.psu.edu/bonwick94slab.html)
71 * Jeff Bonwick, The slab allocator: An object-caching kernel
72 * memory allocator. USENIX 1994, and
73 * [Bonwick01](http://citeseer.ist.psu.edu/bonwick01magazines.html)
74 * 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 `g_slice` 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.
95 * Here is an example for using the slice allocator:
96 * |[<!-- language="C" -->
97 * gchar *mem[10000];
98 * gint i;
100 * // Allocate 10000 blocks.
101 * for (i = 0; i < 10000; i++)
103 * mem[i] = g_slice_alloc (50);
105 * // Fill in the memory with some junk.
106 * for (j = 0; j < 50; j++)
107 * mem[i][j] = i * j;
110 * // Now free all of the blocks.
111 * for (i = 0; i < 10000; i++)
112 * g_slice_free1 (50, mem[i]);
113 * ]|
115 * And here is an example for using the using the slice allocator
116 * with data structures:
117 * |[<!-- language="C" -->
118 * GRealArray *array;
120 * // Allocate one block, using the g_slice_new() macro.
121 * array = g_slice_new (GRealArray);
123 * // We can now use array just like a normal pointer to a structure.
124 * array->data = NULL;
125 * array->len = 0;
126 * array->alloc = 0;
127 * array->zero_terminated = (zero_terminated ? 1 : 0);
128 * array->clear = (clear ? 1 : 0);
129 * array->elt_size = elt_size;
131 * // We can free the block, so it can be reused.
132 * g_slice_free (GRealArray, array);
133 * ]|
136 /* the GSlice allocator is split up into 4 layers, roughly modelled after the slab
137 * allocator and magazine extensions as outlined in:
138 * + [Bonwick94] Jeff Bonwick, The slab allocator: An object-caching kernel
139 * memory allocator. USENIX 1994, http://citeseer.ist.psu.edu/bonwick94slab.html
140 * + [Bonwick01] Bonwick and Jonathan Adams, Magazines and vmem: Extending the
141 * slab allocator to many cpu's and arbitrary resources.
142 * USENIX 2001, http://citeseer.ist.psu.edu/bonwick01magazines.html
143 * the layers are:
144 * - the thread magazines. for each (aligned) chunk size, a magazine (a list)
145 * of recently freed and soon to be allocated chunks is maintained per thread.
146 * this way, most alloc/free requests can be quickly satisfied from per-thread
147 * free lists which only require one g_private_get() call to retrive the
148 * thread handle.
149 * - the magazine cache. allocating and freeing chunks to/from threads only
150 * occours at magazine sizes from a global depot of magazines. the depot
151 * maintaines a 15 second working set of allocated magazines, so full
152 * magazines are not allocated and released too often.
153 * the chunk size dependent magazine sizes automatically adapt (within limits,
154 * see [3]) to lock contention to properly scale performance across a variety
155 * of SMP systems.
156 * - the slab allocator. this allocator allocates slabs (blocks of memory) close
157 * to the system page size or multiples thereof which have to be page aligned.
158 * the blocks are divided into smaller chunks which are used to satisfy
159 * allocations from the upper layers. the space provided by the reminder of
160 * the chunk size division is used for cache colorization (random distribution
161 * of chunk addresses) to improve processor cache utilization. multiple slabs
162 * with the same chunk size are kept in a partially sorted ring to allow O(1)
163 * freeing and allocation of chunks (as long as the allocation of an entirely
164 * new slab can be avoided).
165 * - the page allocator. on most modern systems, posix_memalign(3) or
166 * memalign(3) should be available, so this is used to allocate blocks with
167 * system page size based alignments and sizes or multiples thereof.
168 * if no memalign variant is provided, valloc() is used instead and
169 * block sizes are limited to the system page size (no multiples thereof).
170 * as a fallback, on system without even valloc(), a malloc(3)-based page
171 * allocator with alloc-only behaviour is used.
173 * NOTES:
174 * [1] some systems memalign(3) implementations may rely on boundary tagging for
175 * the handed out memory chunks. to avoid excessive page-wise fragmentation,
176 * we reserve 2 * sizeof (void*) per block size for the systems memalign(3),
177 * specified in NATIVE_MALLOC_PADDING.
178 * [2] using the slab allocator alone already provides for a fast and efficient
179 * allocator, it doesn't properly scale beyond single-threaded uses though.
180 * also, the slab allocator implements eager free(3)-ing, i.e. does not
181 * provide any form of caching or working set maintenance. so if used alone,
182 * it's vulnerable to trashing for sequences of balanced (alloc, free) pairs
183 * at certain thresholds.
184 * [3] magazine sizes are bound by an implementation specific minimum size and
185 * a chunk size specific maximum to limit magazine storage sizes to roughly
186 * 16KB.
187 * [4] allocating ca. 8 chunks per block/page keeps a good balance between
188 * external and internal fragmentation (<= 12.5%). [Bonwick94]
191 /* --- macros and constants --- */
192 #define LARGEALIGNMENT (256)
193 #define P2ALIGNMENT (2 * sizeof (gsize)) /* fits 2 pointers (assumed to be 2 * GLIB_SIZEOF_SIZE_T below) */
194 #define ALIGN(size, base) ((base) * (gsize) (((size) + (base) - 1) / (base)))
195 #define NATIVE_MALLOC_PADDING P2ALIGNMENT /* per-page padding left for native malloc(3) see [1] */
196 #define SLAB_INFO_SIZE P2ALIGN (sizeof (SlabInfo) + NATIVE_MALLOC_PADDING)
197 #define MAX_MAGAZINE_SIZE (256) /* see [3] and allocator_get_magazine_threshold() for this */
198 #define MIN_MAGAZINE_SIZE (4)
199 #define MAX_STAMP_COUNTER (7) /* distributes the load of gettimeofday() */
200 #define MAX_SLAB_CHUNK_SIZE(al) (((al)->max_page_size - SLAB_INFO_SIZE) / 8) /* we want at last 8 chunks per page, see [4] */
201 #define MAX_SLAB_INDEX(al) (SLAB_INDEX (al, MAX_SLAB_CHUNK_SIZE (al)) + 1)
202 #define SLAB_INDEX(al, asize) ((asize) / P2ALIGNMENT - 1) /* asize must be P2ALIGNMENT aligned */
203 #define SLAB_CHUNK_SIZE(al, ix) (((ix) + 1) * P2ALIGNMENT)
204 #define SLAB_BPAGE_SIZE(al,csz) (8 * (csz) + SLAB_INFO_SIZE)
206 /* optimized version of ALIGN (size, P2ALIGNMENT) */
207 #if GLIB_SIZEOF_SIZE_T * 2 == 8 /* P2ALIGNMENT */
208 #define P2ALIGN(size) (((size) + 0x7) & ~(gsize) 0x7)
209 #elif GLIB_SIZEOF_SIZE_T * 2 == 16 /* P2ALIGNMENT */
210 #define P2ALIGN(size) (((size) + 0xf) & ~(gsize) 0xf)
211 #else
212 #define P2ALIGN(size) ALIGN (size, P2ALIGNMENT)
213 #endif
215 /* special helpers to avoid gmessage.c dependency */
216 static void mem_error (const char *format, ...) G_GNUC_PRINTF (1,2);
217 #define mem_assert(cond) do { if (G_LIKELY (cond)) ; else mem_error ("assertion failed: %s", #cond); } while (0)
219 /* --- structures --- */
220 typedef struct _ChunkLink ChunkLink;
221 typedef struct _SlabInfo SlabInfo;
222 typedef struct _CachedMagazine CachedMagazine;
223 struct _ChunkLink {
224 ChunkLink *next;
225 ChunkLink *data;
227 struct _SlabInfo {
228 ChunkLink *chunks;
229 guint n_allocated;
230 SlabInfo *next, *prev;
232 typedef struct {
233 ChunkLink *chunks;
234 gsize count; /* approximative chunks list length */
235 } Magazine;
236 typedef struct {
237 Magazine *magazine1; /* array of MAX_SLAB_INDEX (allocator) */
238 Magazine *magazine2; /* array of MAX_SLAB_INDEX (allocator) */
239 } ThreadMemory;
240 typedef struct {
241 gboolean always_malloc;
242 gboolean bypass_magazines;
243 gboolean debug_blocks;
244 gsize working_set_msecs;
245 guint color_increment;
246 } SliceConfig;
247 typedef struct {
248 /* const after initialization */
249 gsize min_page_size, max_page_size;
250 SliceConfig config;
251 gsize max_slab_chunk_size_for_magazine_cache;
252 /* magazine cache */
253 GMutex magazine_mutex;
254 ChunkLink **magazines; /* array of MAX_SLAB_INDEX (allocator) */
255 guint *contention_counters; /* array of MAX_SLAB_INDEX (allocator) */
256 gint mutex_counter;
257 guint stamp_counter;
258 guint last_stamp;
259 /* slab allocator */
260 GMutex slab_mutex;
261 SlabInfo **slab_stack; /* array of MAX_SLAB_INDEX (allocator) */
262 guint color_accu;
263 } Allocator;
265 /* --- g-slice prototypes --- */
266 static gpointer slab_allocator_alloc_chunk (gsize chunk_size);
267 static void slab_allocator_free_chunk (gsize chunk_size,
268 gpointer mem);
269 static void private_thread_memory_cleanup (gpointer data);
270 static gpointer allocator_memalign (gsize alignment,
271 gsize memsize);
272 static void allocator_memfree (gsize memsize,
273 gpointer mem);
274 static inline void magazine_cache_update_stamp (void);
275 static inline gsize allocator_get_magazine_threshold (Allocator *allocator,
276 guint ix);
278 /* --- g-slice memory checker --- */
279 static void smc_notify_alloc (void *pointer,
280 size_t size);
281 static int smc_notify_free (void *pointer,
282 size_t size);
284 /* --- variables --- */
285 static GPrivate private_thread_memory = G_PRIVATE_INIT (private_thread_memory_cleanup);
286 static gsize sys_page_size = 0;
287 static Allocator allocator[1] = { { 0, }, };
288 static SliceConfig slice_config = {
289 FALSE, /* always_malloc */
290 FALSE, /* bypass_magazines */
291 FALSE, /* debug_blocks */
292 15 * 1000, /* working_set_msecs */
293 1, /* color increment, alt: 0x7fffffff */
295 static GMutex smc_tree_mutex; /* mutex for G_SLICE=debug-blocks */
297 /* --- auxiliary funcitons --- */
298 void
299 g_slice_set_config (GSliceConfig ckey,
300 gint64 value)
302 g_return_if_fail (sys_page_size == 0);
303 switch (ckey)
305 case G_SLICE_CONFIG_ALWAYS_MALLOC:
306 slice_config.always_malloc = value != 0;
307 break;
308 case G_SLICE_CONFIG_BYPASS_MAGAZINES:
309 slice_config.bypass_magazines = value != 0;
310 break;
311 case G_SLICE_CONFIG_WORKING_SET_MSECS:
312 slice_config.working_set_msecs = value;
313 break;
314 case G_SLICE_CONFIG_COLOR_INCREMENT:
315 slice_config.color_increment = value;
316 default: ;
320 gint64
321 g_slice_get_config (GSliceConfig ckey)
323 switch (ckey)
325 case G_SLICE_CONFIG_ALWAYS_MALLOC:
326 return slice_config.always_malloc;
327 case G_SLICE_CONFIG_BYPASS_MAGAZINES:
328 return slice_config.bypass_magazines;
329 case G_SLICE_CONFIG_WORKING_SET_MSECS:
330 return slice_config.working_set_msecs;
331 case G_SLICE_CONFIG_CHUNK_SIZES:
332 return MAX_SLAB_INDEX (allocator);
333 case G_SLICE_CONFIG_COLOR_INCREMENT:
334 return slice_config.color_increment;
335 default:
336 return 0;
340 gint64*
341 g_slice_get_config_state (GSliceConfig ckey,
342 gint64 address,
343 guint *n_values)
345 guint i = 0;
346 g_return_val_if_fail (n_values != NULL, NULL);
347 *n_values = 0;
348 switch (ckey)
350 gint64 array[64];
351 case G_SLICE_CONFIG_CONTENTION_COUNTER:
352 array[i++] = SLAB_CHUNK_SIZE (allocator, address);
353 array[i++] = allocator->contention_counters[address];
354 array[i++] = allocator_get_magazine_threshold (allocator, address);
355 *n_values = i;
356 return g_memdup (array, sizeof (array[0]) * *n_values);
357 default:
358 return NULL;
362 static void
363 slice_config_init (SliceConfig *config)
365 const gchar *val;
367 *config = slice_config;
369 val = getenv ("G_SLICE");
370 if (val != NULL)
372 gint flags;
373 const GDebugKey keys[] = {
374 { "always-malloc", 1 << 0 },
375 { "debug-blocks", 1 << 1 },
378 flags = g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
379 if (flags & (1 << 0))
380 config->always_malloc = TRUE;
381 if (flags & (1 << 1))
382 config->debug_blocks = TRUE;
384 else
386 /* G_SLICE was not specified, so check if valgrind is running and
387 * disable ourselves if it is.
389 * This way it's possible to force gslice to be enabled under
390 * valgrind just by setting G_SLICE to the empty string.
392 #ifdef ENABLE_VALGRIND
393 if (RUNNING_ON_VALGRIND)
394 config->always_malloc = TRUE;
395 #endif
399 static void
400 g_slice_init_nomessage (void)
402 /* we may not use g_error() or friends here */
403 mem_assert (sys_page_size == 0);
404 mem_assert (MIN_MAGAZINE_SIZE >= 4);
406 #ifdef G_OS_WIN32
408 SYSTEM_INFO system_info;
409 GetSystemInfo (&system_info);
410 sys_page_size = system_info.dwPageSize;
412 #else
413 sys_page_size = sysconf (_SC_PAGESIZE); /* = sysconf (_SC_PAGE_SIZE); = getpagesize(); */
414 #endif
415 mem_assert (sys_page_size >= 2 * LARGEALIGNMENT);
416 mem_assert ((sys_page_size & (sys_page_size - 1)) == 0);
417 slice_config_init (&allocator->config);
418 allocator->min_page_size = sys_page_size;
419 #if HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN
420 /* allow allocation of pages up to 8KB (with 8KB alignment).
421 * this is useful because many medium to large sized structures
422 * fit less than 8 times (see [4]) into 4KB pages.
423 * we allow very small page sizes here, to reduce wastage in
424 * threads if only small allocations are required (this does
425 * bear the risk of increasing allocation times and fragmentation
426 * though).
428 allocator->min_page_size = MAX (allocator->min_page_size, 4096);
429 allocator->max_page_size = MAX (allocator->min_page_size, 8192);
430 allocator->min_page_size = MIN (allocator->min_page_size, 128);
431 #else
432 /* we can only align to system page size */
433 allocator->max_page_size = sys_page_size;
434 #endif
435 if (allocator->config.always_malloc)
437 allocator->contention_counters = NULL;
438 allocator->magazines = NULL;
439 allocator->slab_stack = NULL;
441 else
443 allocator->contention_counters = g_new0 (guint, MAX_SLAB_INDEX (allocator));
444 allocator->magazines = g_new0 (ChunkLink*, MAX_SLAB_INDEX (allocator));
445 allocator->slab_stack = g_new0 (SlabInfo*, MAX_SLAB_INDEX (allocator));
448 allocator->mutex_counter = 0;
449 allocator->stamp_counter = MAX_STAMP_COUNTER; /* force initial update */
450 allocator->last_stamp = 0;
451 allocator->color_accu = 0;
452 magazine_cache_update_stamp();
453 /* values cached for performance reasons */
454 allocator->max_slab_chunk_size_for_magazine_cache = MAX_SLAB_CHUNK_SIZE (allocator);
455 if (allocator->config.always_malloc || allocator->config.bypass_magazines)
456 allocator->max_slab_chunk_size_for_magazine_cache = 0; /* non-optimized cases */
459 static inline guint
460 allocator_categorize (gsize aligned_chunk_size)
462 /* speed up the likely path */
463 if (G_LIKELY (aligned_chunk_size && aligned_chunk_size <= allocator->max_slab_chunk_size_for_magazine_cache))
464 return 1; /* use magazine cache */
466 if (!allocator->config.always_malloc &&
467 aligned_chunk_size &&
468 aligned_chunk_size <= MAX_SLAB_CHUNK_SIZE (allocator))
470 if (allocator->config.bypass_magazines)
471 return 2; /* use slab allocator, see [2] */
472 return 1; /* use magazine cache */
474 return 0; /* use malloc() */
477 static inline void
478 g_mutex_lock_a (GMutex *mutex,
479 guint *contention_counter)
481 gboolean contention = FALSE;
482 if (!g_mutex_trylock (mutex))
484 g_mutex_lock (mutex);
485 contention = TRUE;
487 if (contention)
489 allocator->mutex_counter++;
490 if (allocator->mutex_counter >= 1) /* quickly adapt to contention */
492 allocator->mutex_counter = 0;
493 *contention_counter = MIN (*contention_counter + 1, MAX_MAGAZINE_SIZE);
496 else /* !contention */
498 allocator->mutex_counter--;
499 if (allocator->mutex_counter < -11) /* moderately recover magazine sizes */
501 allocator->mutex_counter = 0;
502 *contention_counter = MAX (*contention_counter, 1) - 1;
507 static inline ThreadMemory*
508 thread_memory_from_self (void)
510 ThreadMemory *tmem = g_private_get (&private_thread_memory);
511 if (G_UNLIKELY (!tmem))
513 static GMutex init_mutex;
514 guint n_magazines;
516 g_mutex_lock (&init_mutex);
517 if G_UNLIKELY (sys_page_size == 0)
518 g_slice_init_nomessage ();
519 g_mutex_unlock (&init_mutex);
521 n_magazines = MAX_SLAB_INDEX (allocator);
522 tmem = g_malloc0 (sizeof (ThreadMemory) + sizeof (Magazine) * 2 * n_magazines);
523 tmem->magazine1 = (Magazine*) (tmem + 1);
524 tmem->magazine2 = &tmem->magazine1[n_magazines];
525 g_private_set (&private_thread_memory, tmem);
527 return tmem;
530 static inline ChunkLink*
531 magazine_chain_pop_head (ChunkLink **magazine_chunks)
533 /* magazine chains are linked via ChunkLink->next.
534 * each ChunkLink->data of the toplevel chain may point to a subchain,
535 * linked via ChunkLink->next. ChunkLink->data of the subchains just
536 * contains uninitialized junk.
538 ChunkLink *chunk = (*magazine_chunks)->data;
539 if (G_UNLIKELY (chunk))
541 /* allocating from freed list */
542 (*magazine_chunks)->data = chunk->next;
544 else
546 chunk = *magazine_chunks;
547 *magazine_chunks = chunk->next;
549 return chunk;
552 #if 0 /* useful for debugging */
553 static guint
554 magazine_count (ChunkLink *head)
556 guint count = 0;
557 if (!head)
558 return 0;
559 while (head)
561 ChunkLink *child = head->data;
562 count += 1;
563 for (child = head->data; child; child = child->next)
564 count += 1;
565 head = head->next;
567 return count;
569 #endif
571 static inline gsize
572 allocator_get_magazine_threshold (Allocator *allocator,
573 guint ix)
575 /* the magazine size calculated here has a lower bound of MIN_MAGAZINE_SIZE,
576 * which is required by the implementation. also, for moderately sized chunks
577 * (say >= 64 bytes), magazine sizes shouldn't be much smaller then the number
578 * of chunks available per page/2 to avoid excessive traffic in the magazine
579 * cache for small to medium sized structures.
580 * the upper bound of the magazine size is effectively provided by
581 * MAX_MAGAZINE_SIZE. for larger chunks, this number is scaled down so that
582 * the content of a single magazine doesn't exceed ca. 16KB.
584 gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
585 guint threshold = MAX (MIN_MAGAZINE_SIZE, allocator->max_page_size / MAX (5 * chunk_size, 5 * 32));
586 guint contention_counter = allocator->contention_counters[ix];
587 if (G_UNLIKELY (contention_counter)) /* single CPU bias */
589 /* adapt contention counter thresholds to chunk sizes */
590 contention_counter = contention_counter * 64 / chunk_size;
591 threshold = MAX (threshold, contention_counter);
593 return threshold;
596 /* --- magazine cache --- */
597 static inline void
598 magazine_cache_update_stamp (void)
600 if (allocator->stamp_counter >= MAX_STAMP_COUNTER)
602 GTimeVal tv;
603 g_get_current_time (&tv);
604 allocator->last_stamp = tv.tv_sec * 1000 + tv.tv_usec / 1000; /* milli seconds */
605 allocator->stamp_counter = 0;
607 else
608 allocator->stamp_counter++;
611 static inline ChunkLink*
612 magazine_chain_prepare_fields (ChunkLink *magazine_chunks)
614 ChunkLink *chunk1;
615 ChunkLink *chunk2;
616 ChunkLink *chunk3;
617 ChunkLink *chunk4;
618 /* checked upon initialization: mem_assert (MIN_MAGAZINE_SIZE >= 4); */
619 /* ensure a magazine with at least 4 unused data pointers */
620 chunk1 = magazine_chain_pop_head (&magazine_chunks);
621 chunk2 = magazine_chain_pop_head (&magazine_chunks);
622 chunk3 = magazine_chain_pop_head (&magazine_chunks);
623 chunk4 = magazine_chain_pop_head (&magazine_chunks);
624 chunk4->next = magazine_chunks;
625 chunk3->next = chunk4;
626 chunk2->next = chunk3;
627 chunk1->next = chunk2;
628 return chunk1;
631 /* access the first 3 fields of a specially prepared magazine chain */
632 #define magazine_chain_prev(mc) ((mc)->data)
633 #define magazine_chain_stamp(mc) ((mc)->next->data)
634 #define magazine_chain_uint_stamp(mc) GPOINTER_TO_UINT ((mc)->next->data)
635 #define magazine_chain_next(mc) ((mc)->next->next->data)
636 #define magazine_chain_count(mc) ((mc)->next->next->next->data)
638 static void
639 magazine_cache_trim (Allocator *allocator,
640 guint ix,
641 guint stamp)
643 /* g_mutex_lock (allocator->mutex); done by caller */
644 /* trim magazine cache from tail */
645 ChunkLink *current = magazine_chain_prev (allocator->magazines[ix]);
646 ChunkLink *trash = NULL;
647 while (ABS (stamp - magazine_chain_uint_stamp (current)) >= allocator->config.working_set_msecs)
649 /* unlink */
650 ChunkLink *prev = magazine_chain_prev (current);
651 ChunkLink *next = magazine_chain_next (current);
652 magazine_chain_next (prev) = next;
653 magazine_chain_prev (next) = prev;
654 /* clear special fields, put on trash stack */
655 magazine_chain_next (current) = NULL;
656 magazine_chain_count (current) = NULL;
657 magazine_chain_stamp (current) = NULL;
658 magazine_chain_prev (current) = trash;
659 trash = current;
660 /* fixup list head if required */
661 if (current == allocator->magazines[ix])
663 allocator->magazines[ix] = NULL;
664 break;
666 current = prev;
668 g_mutex_unlock (&allocator->magazine_mutex);
669 /* free trash */
670 if (trash)
672 const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
673 g_mutex_lock (&allocator->slab_mutex);
674 while (trash)
676 current = trash;
677 trash = magazine_chain_prev (current);
678 magazine_chain_prev (current) = NULL; /* clear special field */
679 while (current)
681 ChunkLink *chunk = magazine_chain_pop_head (&current);
682 slab_allocator_free_chunk (chunk_size, chunk);
685 g_mutex_unlock (&allocator->slab_mutex);
689 static void
690 magazine_cache_push_magazine (guint ix,
691 ChunkLink *magazine_chunks,
692 gsize count) /* must be >= MIN_MAGAZINE_SIZE */
694 ChunkLink *current = magazine_chain_prepare_fields (magazine_chunks);
695 ChunkLink *next, *prev;
696 g_mutex_lock (&allocator->magazine_mutex);
697 /* add magazine at head */
698 next = allocator->magazines[ix];
699 if (next)
700 prev = magazine_chain_prev (next);
701 else
702 next = prev = current;
703 magazine_chain_next (prev) = current;
704 magazine_chain_prev (next) = current;
705 magazine_chain_prev (current) = prev;
706 magazine_chain_next (current) = next;
707 magazine_chain_count (current) = (gpointer) count;
708 /* stamp magazine */
709 magazine_cache_update_stamp();
710 magazine_chain_stamp (current) = GUINT_TO_POINTER (allocator->last_stamp);
711 allocator->magazines[ix] = current;
712 /* free old magazines beyond a certain threshold */
713 magazine_cache_trim (allocator, ix, allocator->last_stamp);
714 /* g_mutex_unlock (allocator->mutex); was done by magazine_cache_trim() */
717 static ChunkLink*
718 magazine_cache_pop_magazine (guint ix,
719 gsize *countp)
721 g_mutex_lock_a (&allocator->magazine_mutex, &allocator->contention_counters[ix]);
722 if (!allocator->magazines[ix])
724 guint magazine_threshold = allocator_get_magazine_threshold (allocator, ix);
725 gsize i, chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
726 ChunkLink *chunk, *head;
727 g_mutex_unlock (&allocator->magazine_mutex);
728 g_mutex_lock (&allocator->slab_mutex);
729 head = slab_allocator_alloc_chunk (chunk_size);
730 head->data = NULL;
731 chunk = head;
732 for (i = 1; i < magazine_threshold; i++)
734 chunk->next = slab_allocator_alloc_chunk (chunk_size);
735 chunk = chunk->next;
736 chunk->data = NULL;
738 chunk->next = NULL;
739 g_mutex_unlock (&allocator->slab_mutex);
740 *countp = i;
741 return head;
743 else
745 ChunkLink *current = allocator->magazines[ix];
746 ChunkLink *prev = magazine_chain_prev (current);
747 ChunkLink *next = magazine_chain_next (current);
748 /* unlink */
749 magazine_chain_next (prev) = next;
750 magazine_chain_prev (next) = prev;
751 allocator->magazines[ix] = next == current ? NULL : next;
752 g_mutex_unlock (&allocator->magazine_mutex);
753 /* clear special fields and hand out */
754 *countp = (gsize) magazine_chain_count (current);
755 magazine_chain_prev (current) = NULL;
756 magazine_chain_next (current) = NULL;
757 magazine_chain_count (current) = NULL;
758 magazine_chain_stamp (current) = NULL;
759 return current;
763 /* --- thread magazines --- */
764 static void
765 private_thread_memory_cleanup (gpointer data)
767 ThreadMemory *tmem = data;
768 const guint n_magazines = MAX_SLAB_INDEX (allocator);
769 guint ix;
770 for (ix = 0; ix < n_magazines; ix++)
772 Magazine *mags[2];
773 guint j;
774 mags[0] = &tmem->magazine1[ix];
775 mags[1] = &tmem->magazine2[ix];
776 for (j = 0; j < 2; j++)
778 Magazine *mag = mags[j];
779 if (mag->count >= MIN_MAGAZINE_SIZE)
780 magazine_cache_push_magazine (ix, mag->chunks, mag->count);
781 else
783 const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
784 g_mutex_lock (&allocator->slab_mutex);
785 while (mag->chunks)
787 ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
788 slab_allocator_free_chunk (chunk_size, chunk);
790 g_mutex_unlock (&allocator->slab_mutex);
794 g_free (tmem);
797 static void
798 thread_memory_magazine1_reload (ThreadMemory *tmem,
799 guint ix)
801 Magazine *mag = &tmem->magazine1[ix];
802 mem_assert (mag->chunks == NULL); /* ensure that we may reset mag->count */
803 mag->count = 0;
804 mag->chunks = magazine_cache_pop_magazine (ix, &mag->count);
807 static void
808 thread_memory_magazine2_unload (ThreadMemory *tmem,
809 guint ix)
811 Magazine *mag = &tmem->magazine2[ix];
812 magazine_cache_push_magazine (ix, mag->chunks, mag->count);
813 mag->chunks = NULL;
814 mag->count = 0;
817 static inline void
818 thread_memory_swap_magazines (ThreadMemory *tmem,
819 guint ix)
821 Magazine xmag = tmem->magazine1[ix];
822 tmem->magazine1[ix] = tmem->magazine2[ix];
823 tmem->magazine2[ix] = xmag;
826 static inline gboolean
827 thread_memory_magazine1_is_empty (ThreadMemory *tmem,
828 guint ix)
830 return tmem->magazine1[ix].chunks == NULL;
833 static inline gboolean
834 thread_memory_magazine2_is_full (ThreadMemory *tmem,
835 guint ix)
837 return tmem->magazine2[ix].count >= allocator_get_magazine_threshold (allocator, ix);
840 static inline gpointer
841 thread_memory_magazine1_alloc (ThreadMemory *tmem,
842 guint ix)
844 Magazine *mag = &tmem->magazine1[ix];
845 ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
846 if (G_LIKELY (mag->count > 0))
847 mag->count--;
848 return chunk;
851 static inline void
852 thread_memory_magazine2_free (ThreadMemory *tmem,
853 guint ix,
854 gpointer mem)
856 Magazine *mag = &tmem->magazine2[ix];
857 ChunkLink *chunk = mem;
858 chunk->data = NULL;
859 chunk->next = mag->chunks;
860 mag->chunks = chunk;
861 mag->count++;
864 /* --- API functions --- */
867 * g_slice_new:
868 * @type: the type to allocate, typically a structure name
870 * A convenience macro to allocate a block of memory from the
871 * slice allocator.
873 * It calls g_slice_alloc() with `sizeof (@type)` and casts the
874 * returned pointer to a pointer of the given type, avoiding a type
875 * cast in the source code. Note that the underlying slice allocation
876 * mechanism can be changed with the [`G_SLICE=always-malloc`][G_SLICE]
877 * environment variable.
879 * This can never return %NULL as the minimum allocation size from
880 * `sizeof (@type)` is 1 byte.
882 * Returns: (not nullable): a pointer to the allocated block, cast to a pointer
883 * to @type
885 * Since: 2.10
889 * g_slice_new0:
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 `sizeof (@type)`
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 [`G_SLICE=always-malloc`][G_SLICE]
900 * environment variable.
902 * This can never return %NULL as the minimum allocation size from
903 * `sizeof (@type)` is 1 byte.
905 * Returns: (not nullable): a pointer to the allocated block, cast to a pointer
906 * to @type
908 * Since: 2.10
912 * g_slice_dup:
913 * @type: the type to duplicate, typically a structure name
914 * @mem: (not nullable): the memory to copy into the allocated block
916 * A convenience macro to duplicate a block of memory using
917 * the slice allocator.
919 * It calls g_slice_copy() with `sizeof (@type)`
920 * and casts the returned pointer to a pointer of the given type,
921 * avoiding a type cast in the source code.
922 * Note that the underlying slice allocation mechanism can
923 * be changed with the [`G_SLICE=always-malloc`][G_SLICE]
924 * environment variable.
926 * This can never return %NULL.
928 * Returns: (not nullable): a pointer to the allocated block, cast to a pointer
929 * to @type
931 * Since: 2.14
935 * g_slice_free:
936 * @type: the type of the block to free, typically a structure name
937 * @mem: a pointer to the block to free
939 * A convenience macro to free a block of memory that has
940 * been allocated from the slice allocator.
942 * It calls g_slice_free1() using `sizeof (type)`
943 * as the block size.
944 * Note that the exact release behaviour can be changed with the
945 * [`G_DEBUG=gc-friendly`][G_DEBUG] environment variable, also see
946 * [`G_SLICE`][G_SLICE] for related debugging options.
948 * If @mem is %NULL, this macro does nothing.
950 * Since: 2.10
954 * g_slice_free_chain:
955 * @type: the type of the @mem_chain blocks
956 * @mem_chain: a pointer to the first block of the chain
957 * @next: the field name of the next pointer in @type
959 * Frees a linked list of memory blocks of structure type @type.
960 * The memory blocks must be equal-sized, allocated via
961 * g_slice_alloc() or g_slice_alloc0() and linked together by
962 * a @next pointer (similar to #GSList). The name of the
963 * @next field in @type is passed as third argument.
964 * Note that the exact release behaviour can be changed with the
965 * [`G_DEBUG=gc-friendly`][G_DEBUG] environment variable, also see
966 * [`G_SLICE`][G_SLICE] for related debugging options.
968 * If @mem_chain is %NULL, this function does nothing.
970 * Since: 2.10
974 * g_slice_alloc:
975 * @block_size: the number of bytes to allocate
977 * Allocates a block of memory from the slice allocator.
978 * The block address handed out can be expected to be aligned
979 * to at least 1 * sizeof (void*),
980 * though in general slices are 2 * sizeof (void*) bytes aligned,
981 * if a malloc() fallback implementation is used instead,
982 * the alignment may be reduced in a libc dependent fashion.
983 * Note that the underlying slice allocation mechanism can
984 * be changed with the [`G_SLICE=always-malloc`][G_SLICE]
985 * environment variable.
987 * Returns: a pointer to the allocated memory block, which will be %NULL if and
988 * only if @mem_size is 0
990 * Since: 2.10
992 gpointer
993 g_slice_alloc (gsize mem_size)
995 ThreadMemory *tmem;
996 gsize chunk_size;
997 gpointer mem;
998 guint acat;
1000 /* This gets the private structure for this thread. If the private
1001 * structure does not yet exist, it is created.
1003 * This has a side effect of causing GSlice to be initialised, so it
1004 * must come first.
1006 tmem = thread_memory_from_self ();
1008 chunk_size = P2ALIGN (mem_size);
1009 acat = allocator_categorize (chunk_size);
1010 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
1012 guint ix = SLAB_INDEX (allocator, chunk_size);
1013 if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
1015 thread_memory_swap_magazines (tmem, ix);
1016 if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
1017 thread_memory_magazine1_reload (tmem, ix);
1019 mem = thread_memory_magazine1_alloc (tmem, ix);
1021 else if (acat == 2) /* allocate through slab allocator */
1023 g_mutex_lock (&allocator->slab_mutex);
1024 mem = slab_allocator_alloc_chunk (chunk_size);
1025 g_mutex_unlock (&allocator->slab_mutex);
1027 else /* delegate to system malloc */
1028 mem = g_malloc (mem_size);
1029 if (G_UNLIKELY (allocator->config.debug_blocks))
1030 smc_notify_alloc (mem, mem_size);
1032 TRACE (GLIB_SLICE_ALLOC((void*)mem, mem_size));
1034 return mem;
1038 * g_slice_alloc0:
1039 * @block_size: the number of bytes to allocate
1041 * Allocates a block of memory via g_slice_alloc() and initializes
1042 * the returned memory to 0. Note that the underlying slice allocation
1043 * mechanism can be changed with the [`G_SLICE=always-malloc`][G_SLICE]
1044 * environment variable.
1046 * Returns: a pointer to the allocated block, which will be %NULL if and only
1047 * if @mem_size is 0
1049 * Since: 2.10
1051 gpointer
1052 g_slice_alloc0 (gsize mem_size)
1054 gpointer mem = g_slice_alloc (mem_size);
1055 if (mem)
1056 memset (mem, 0, mem_size);
1057 return mem;
1061 * g_slice_copy:
1062 * @block_size: the number of bytes to allocate
1063 * @mem_block: the memory to copy
1065 * Allocates a block of memory from the slice allocator
1066 * and copies @block_size bytes into it from @mem_block.
1068 * @mem_block must be non-%NULL if @block_size is non-zero.
1070 * Returns: a pointer to the allocated memory block, which will be %NULL if and
1071 * only if @mem_size is 0
1073 * Since: 2.14
1075 gpointer
1076 g_slice_copy (gsize mem_size,
1077 gconstpointer mem_block)
1079 gpointer mem = g_slice_alloc (mem_size);
1080 if (mem)
1081 memcpy (mem, mem_block, mem_size);
1082 return mem;
1086 * g_slice_free1:
1087 * @block_size: the size of the block
1088 * @mem_block: a pointer to the block to free
1090 * Frees a block of memory.
1092 * The memory must have been allocated via g_slice_alloc() or
1093 * g_slice_alloc0() and the @block_size has to match the size
1094 * specified upon allocation. Note that the exact release behaviour
1095 * can be changed with the [`G_DEBUG=gc-friendly`][G_DEBUG] environment
1096 * variable, also see [`G_SLICE`][G_SLICE] for related debugging options.
1098 * If @mem_block is %NULL, this function does nothing.
1100 * Since: 2.10
1102 void
1103 g_slice_free1 (gsize mem_size,
1104 gpointer mem_block)
1106 gsize chunk_size = P2ALIGN (mem_size);
1107 guint acat = allocator_categorize (chunk_size);
1108 if (G_UNLIKELY (!mem_block))
1109 return;
1110 if (G_UNLIKELY (allocator->config.debug_blocks) &&
1111 !smc_notify_free (mem_block, mem_size))
1112 abort();
1113 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
1115 ThreadMemory *tmem = thread_memory_from_self();
1116 guint ix = SLAB_INDEX (allocator, chunk_size);
1117 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
1119 thread_memory_swap_magazines (tmem, ix);
1120 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
1121 thread_memory_magazine2_unload (tmem, ix);
1123 if (G_UNLIKELY (g_mem_gc_friendly))
1124 memset (mem_block, 0, chunk_size);
1125 thread_memory_magazine2_free (tmem, ix, mem_block);
1127 else if (acat == 2) /* allocate through slab allocator */
1129 if (G_UNLIKELY (g_mem_gc_friendly))
1130 memset (mem_block, 0, chunk_size);
1131 g_mutex_lock (&allocator->slab_mutex);
1132 slab_allocator_free_chunk (chunk_size, mem_block);
1133 g_mutex_unlock (&allocator->slab_mutex);
1135 else /* delegate to system malloc */
1137 if (G_UNLIKELY (g_mem_gc_friendly))
1138 memset (mem_block, 0, mem_size);
1139 g_free (mem_block);
1141 TRACE (GLIB_SLICE_FREE((void*)mem_block, mem_size));
1145 * g_slice_free_chain_with_offset:
1146 * @block_size: the size of the blocks
1147 * @mem_chain: a pointer to the first block of the chain
1148 * @next_offset: the offset of the @next field in the blocks
1150 * Frees a linked list of memory blocks of structure type @type.
1152 * The memory blocks must be equal-sized, allocated via
1153 * g_slice_alloc() or g_slice_alloc0() and linked together by a
1154 * @next pointer (similar to #GSList). The offset of the @next
1155 * field in each block is passed as third argument.
1156 * Note that the exact release behaviour can be changed with the
1157 * [`G_DEBUG=gc-friendly`][G_DEBUG] environment variable, also see
1158 * [`G_SLICE`][G_SLICE] for related debugging options.
1160 * If @mem_chain is %NULL, this function does nothing.
1162 * Since: 2.10
1164 void
1165 g_slice_free_chain_with_offset (gsize mem_size,
1166 gpointer mem_chain,
1167 gsize next_offset)
1169 gpointer slice = mem_chain;
1170 /* while the thread magazines and the magazine cache are implemented so that
1171 * they can easily be extended to allow for free lists containing more free
1172 * lists for the first level nodes, which would allow O(1) freeing in this
1173 * function, the benefit of such an extension is questionable, because:
1174 * - the magazine size counts will become mere lower bounds which confuses
1175 * the code adapting to lock contention;
1176 * - freeing a single node to the thread magazines is very fast, so this
1177 * O(list_length) operation is multiplied by a fairly small factor;
1178 * - memory usage histograms on larger applications seem to indicate that
1179 * the amount of released multi node lists is negligible in comparison
1180 * to single node releases.
1181 * - the major performance bottle neck, namely g_private_get() or
1182 * g_mutex_lock()/g_mutex_unlock() has already been moved out of the
1183 * inner loop for freeing chained slices.
1185 gsize chunk_size = P2ALIGN (mem_size);
1186 guint acat = allocator_categorize (chunk_size);
1187 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
1189 ThreadMemory *tmem = thread_memory_from_self();
1190 guint ix = SLAB_INDEX (allocator, chunk_size);
1191 while (slice)
1193 guint8 *current = slice;
1194 slice = *(gpointer*) (current + next_offset);
1195 if (G_UNLIKELY (allocator->config.debug_blocks) &&
1196 !smc_notify_free (current, mem_size))
1197 abort();
1198 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
1200 thread_memory_swap_magazines (tmem, ix);
1201 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
1202 thread_memory_magazine2_unload (tmem, ix);
1204 if (G_UNLIKELY (g_mem_gc_friendly))
1205 memset (current, 0, chunk_size);
1206 thread_memory_magazine2_free (tmem, ix, current);
1209 else if (acat == 2) /* allocate through slab allocator */
1211 g_mutex_lock (&allocator->slab_mutex);
1212 while (slice)
1214 guint8 *current = slice;
1215 slice = *(gpointer*) (current + next_offset);
1216 if (G_UNLIKELY (allocator->config.debug_blocks) &&
1217 !smc_notify_free (current, mem_size))
1218 abort();
1219 if (G_UNLIKELY (g_mem_gc_friendly))
1220 memset (current, 0, chunk_size);
1221 slab_allocator_free_chunk (chunk_size, current);
1223 g_mutex_unlock (&allocator->slab_mutex);
1225 else /* delegate to system malloc */
1226 while (slice)
1228 guint8 *current = slice;
1229 slice = *(gpointer*) (current + next_offset);
1230 if (G_UNLIKELY (allocator->config.debug_blocks) &&
1231 !smc_notify_free (current, mem_size))
1232 abort();
1233 if (G_UNLIKELY (g_mem_gc_friendly))
1234 memset (current, 0, mem_size);
1235 g_free (current);
1239 /* --- single page allocator --- */
1240 static void
1241 allocator_slab_stack_push (Allocator *allocator,
1242 guint ix,
1243 SlabInfo *sinfo)
1245 /* insert slab at slab ring head */
1246 if (!allocator->slab_stack[ix])
1248 sinfo->next = sinfo;
1249 sinfo->prev = sinfo;
1251 else
1253 SlabInfo *next = allocator->slab_stack[ix], *prev = next->prev;
1254 next->prev = sinfo;
1255 prev->next = sinfo;
1256 sinfo->next = next;
1257 sinfo->prev = prev;
1259 allocator->slab_stack[ix] = sinfo;
1262 static gsize
1263 allocator_aligned_page_size (Allocator *allocator,
1264 gsize n_bytes)
1266 gsize val = 1 << g_bit_storage (n_bytes - 1);
1267 val = MAX (val, allocator->min_page_size);
1268 return val;
1271 static void
1272 allocator_add_slab (Allocator *allocator,
1273 guint ix,
1274 gsize chunk_size)
1276 ChunkLink *chunk;
1277 SlabInfo *sinfo;
1278 gsize addr, padding, n_chunks, color = 0;
1279 gsize page_size;
1280 int errsv;
1281 gpointer aligned_memory;
1282 guint8 *mem;
1283 guint i;
1285 page_size = allocator_aligned_page_size (allocator, SLAB_BPAGE_SIZE (allocator, chunk_size));
1286 /* allocate 1 page for the chunks and the slab */
1287 aligned_memory = allocator_memalign (page_size, page_size - NATIVE_MALLOC_PADDING);
1288 errsv = errno;
1289 mem = aligned_memory;
1291 if (!mem)
1293 const gchar *syserr = strerror (errsv);
1294 mem_error ("failed to allocate %u bytes (alignment: %u): %s\n",
1295 (guint) (page_size - NATIVE_MALLOC_PADDING), (guint) page_size, syserr);
1297 /* mask page address */
1298 addr = ((gsize) mem / page_size) * page_size;
1299 /* assert alignment */
1300 mem_assert (aligned_memory == (gpointer) addr);
1301 /* basic slab info setup */
1302 sinfo = (SlabInfo*) (mem + page_size - SLAB_INFO_SIZE);
1303 sinfo->n_allocated = 0;
1304 sinfo->chunks = NULL;
1305 /* figure cache colorization */
1306 n_chunks = ((guint8*) sinfo - mem) / chunk_size;
1307 padding = ((guint8*) sinfo - mem) - n_chunks * chunk_size;
1308 if (padding)
1310 color = (allocator->color_accu * P2ALIGNMENT) % padding;
1311 allocator->color_accu += allocator->config.color_increment;
1313 /* add chunks to free list */
1314 chunk = (ChunkLink*) (mem + color);
1315 sinfo->chunks = chunk;
1316 for (i = 0; i < n_chunks - 1; i++)
1318 chunk->next = (ChunkLink*) ((guint8*) chunk + chunk_size);
1319 chunk = chunk->next;
1321 chunk->next = NULL; /* last chunk */
1322 /* add slab to slab ring */
1323 allocator_slab_stack_push (allocator, ix, sinfo);
1326 static gpointer
1327 slab_allocator_alloc_chunk (gsize chunk_size)
1329 ChunkLink *chunk;
1330 guint ix = SLAB_INDEX (allocator, chunk_size);
1331 /* ensure non-empty slab */
1332 if (!allocator->slab_stack[ix] || !allocator->slab_stack[ix]->chunks)
1333 allocator_add_slab (allocator, ix, chunk_size);
1334 /* allocate chunk */
1335 chunk = allocator->slab_stack[ix]->chunks;
1336 allocator->slab_stack[ix]->chunks = chunk->next;
1337 allocator->slab_stack[ix]->n_allocated++;
1338 /* rotate empty slabs */
1339 if (!allocator->slab_stack[ix]->chunks)
1340 allocator->slab_stack[ix] = allocator->slab_stack[ix]->next;
1341 return chunk;
1344 static void
1345 slab_allocator_free_chunk (gsize chunk_size,
1346 gpointer mem)
1348 ChunkLink *chunk;
1349 gboolean was_empty;
1350 guint ix = SLAB_INDEX (allocator, chunk_size);
1351 gsize page_size = allocator_aligned_page_size (allocator, SLAB_BPAGE_SIZE (allocator, chunk_size));
1352 gsize addr = ((gsize) mem / page_size) * page_size;
1353 /* mask page address */
1354 guint8 *page = (guint8*) addr;
1355 SlabInfo *sinfo = (SlabInfo*) (page + page_size - SLAB_INFO_SIZE);
1356 /* assert valid chunk count */
1357 mem_assert (sinfo->n_allocated > 0);
1358 /* add chunk to free list */
1359 was_empty = sinfo->chunks == NULL;
1360 chunk = (ChunkLink*) mem;
1361 chunk->next = sinfo->chunks;
1362 sinfo->chunks = chunk;
1363 sinfo->n_allocated--;
1364 /* keep slab ring partially sorted, empty slabs at end */
1365 if (was_empty)
1367 /* unlink slab */
1368 SlabInfo *next = sinfo->next, *prev = sinfo->prev;
1369 next->prev = prev;
1370 prev->next = next;
1371 if (allocator->slab_stack[ix] == sinfo)
1372 allocator->slab_stack[ix] = next == sinfo ? NULL : next;
1373 /* insert slab at head */
1374 allocator_slab_stack_push (allocator, ix, sinfo);
1376 /* eagerly free complete unused slabs */
1377 if (!sinfo->n_allocated)
1379 /* unlink slab */
1380 SlabInfo *next = sinfo->next, *prev = sinfo->prev;
1381 next->prev = prev;
1382 prev->next = next;
1383 if (allocator->slab_stack[ix] == sinfo)
1384 allocator->slab_stack[ix] = next == sinfo ? NULL : next;
1385 /* free slab */
1386 allocator_memfree (page_size, page);
1390 /* --- memalign implementation --- */
1391 #ifdef HAVE_MALLOC_H
1392 #include <malloc.h> /* memalign() */
1393 #endif
1395 /* from config.h:
1396 * define HAVE_POSIX_MEMALIGN 1 // if free(posix_memalign(3)) works, <stdlib.h>
1397 * define HAVE_COMPLIANT_POSIX_MEMALIGN 1 // if free(posix_memalign(3)) works for sizes != 2^n, <stdlib.h>
1398 * define HAVE_MEMALIGN 1 // if free(memalign(3)) works, <malloc.h>
1399 * define HAVE_VALLOC 1 // if free(valloc(3)) works, <stdlib.h> or <malloc.h>
1400 * if none is provided, we implement malloc(3)-based alloc-only page alignment
1403 #if !(HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC)
1404 static GTrashStack *compat_valloc_trash = NULL;
1405 #endif
1407 static gpointer
1408 allocator_memalign (gsize alignment,
1409 gsize memsize)
1411 gpointer aligned_memory = NULL;
1412 gint err = ENOMEM;
1413 #if HAVE_COMPLIANT_POSIX_MEMALIGN
1414 err = posix_memalign (&aligned_memory, alignment, memsize);
1415 #elif HAVE_MEMALIGN
1416 errno = 0;
1417 aligned_memory = memalign (alignment, memsize);
1418 err = errno;
1419 #elif HAVE_VALLOC
1420 errno = 0;
1421 aligned_memory = valloc (memsize);
1422 err = errno;
1423 #else
1424 /* simplistic non-freeing page allocator */
1425 mem_assert (alignment == sys_page_size);
1426 mem_assert (memsize <= sys_page_size);
1427 if (!compat_valloc_trash)
1429 const guint n_pages = 16;
1430 guint8 *mem = malloc (n_pages * sys_page_size);
1431 err = errno;
1432 if (mem)
1434 gint i = n_pages;
1435 guint8 *amem = (guint8*) ALIGN ((gsize) mem, sys_page_size);
1436 if (amem != mem)
1437 i--; /* mem wasn't page aligned */
1438 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
1439 while (--i >= 0)
1440 g_trash_stack_push (&compat_valloc_trash, amem + i * sys_page_size);
1441 G_GNUC_END_IGNORE_DEPRECATIONS
1444 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
1445 aligned_memory = g_trash_stack_pop (&compat_valloc_trash);
1446 G_GNUC_END_IGNORE_DEPRECATIONS
1447 #endif
1448 if (!aligned_memory)
1449 errno = err;
1450 return aligned_memory;
1453 static void
1454 allocator_memfree (gsize memsize,
1455 gpointer mem)
1457 #if HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC
1458 free (mem);
1459 #else
1460 mem_assert (memsize <= sys_page_size);
1461 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
1462 g_trash_stack_push (&compat_valloc_trash, mem);
1463 G_GNUC_END_IGNORE_DEPRECATIONS
1464 #endif
1467 static void
1468 mem_error (const char *format,
1469 ...)
1471 const char *pname;
1472 va_list args;
1473 /* at least, put out "MEMORY-ERROR", in case we segfault during the rest of the function */
1474 fputs ("\n***MEMORY-ERROR***: ", stderr);
1475 pname = g_get_prgname();
1476 g_fprintf (stderr, "%s[%ld]: GSlice: ", pname ? pname : "", (long)getpid());
1477 va_start (args, format);
1478 g_vfprintf (stderr, format, args);
1479 va_end (args);
1480 fputs ("\n", stderr);
1481 abort();
1482 _exit (1);
1485 /* --- g-slice memory checker tree --- */
1486 typedef size_t SmcKType; /* key type */
1487 typedef size_t SmcVType; /* value type */
1488 typedef struct {
1489 SmcKType key;
1490 SmcVType value;
1491 } SmcEntry;
1492 static void smc_tree_insert (SmcKType key,
1493 SmcVType value);
1494 static gboolean smc_tree_lookup (SmcKType key,
1495 SmcVType *value_p);
1496 static gboolean smc_tree_remove (SmcKType key);
1499 /* --- g-slice memory checker implementation --- */
1500 static void
1501 smc_notify_alloc (void *pointer,
1502 size_t size)
1504 size_t address = (size_t) pointer;
1505 if (pointer)
1506 smc_tree_insert (address, size);
1509 #if 0
1510 static void
1511 smc_notify_ignore (void *pointer)
1513 size_t address = (size_t) pointer;
1514 if (pointer)
1515 smc_tree_remove (address);
1517 #endif
1519 static int
1520 smc_notify_free (void *pointer,
1521 size_t size)
1523 size_t address = (size_t) pointer;
1524 SmcVType real_size;
1525 gboolean found_one;
1527 if (!pointer)
1528 return 1; /* ignore */
1529 found_one = smc_tree_lookup (address, &real_size);
1530 if (!found_one)
1532 g_fprintf (stderr, "GSlice: MemChecker: attempt to release non-allocated block: %p size=%" G_GSIZE_FORMAT "\n", pointer, size);
1533 return 0;
1535 if (real_size != size && (real_size || size))
1537 g_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);
1538 return 0;
1540 if (!smc_tree_remove (address))
1542 g_fprintf (stderr, "GSlice: MemChecker: attempt to release non-allocated block: %p size=%" G_GSIZE_FORMAT "\n", pointer, size);
1543 return 0;
1545 return 1; /* all fine */
1548 /* --- g-slice memory checker tree implementation --- */
1549 #define SMC_TRUNK_COUNT (4093 /* 16381 */) /* prime, to distribute trunk collisions (big, allocated just once) */
1550 #define SMC_BRANCH_COUNT (511) /* prime, to distribute branch collisions */
1551 #define SMC_TRUNK_EXTENT (SMC_BRANCH_COUNT * 2039) /* key address space per trunk, should distribute uniformly across BRANCH_COUNT */
1552 #define SMC_TRUNK_HASH(k) ((k / SMC_TRUNK_EXTENT) % SMC_TRUNK_COUNT) /* generate new trunk hash per megabyte (roughly) */
1553 #define SMC_BRANCH_HASH(k) (k % SMC_BRANCH_COUNT)
1555 typedef struct {
1556 SmcEntry *entries;
1557 unsigned int n_entries;
1558 } SmcBranch;
1560 static SmcBranch **smc_tree_root = NULL;
1562 static void
1563 smc_tree_abort (int errval)
1565 const char *syserr = strerror (errval);
1566 mem_error ("MemChecker: failure in debugging tree: %s", syserr);
1569 static inline SmcEntry*
1570 smc_tree_branch_grow_L (SmcBranch *branch,
1571 unsigned int index)
1573 unsigned int old_size = branch->n_entries * sizeof (branch->entries[0]);
1574 unsigned int new_size = old_size + sizeof (branch->entries[0]);
1575 SmcEntry *entry;
1576 mem_assert (index <= branch->n_entries);
1577 branch->entries = (SmcEntry*) realloc (branch->entries, new_size);
1578 if (!branch->entries)
1579 smc_tree_abort (errno);
1580 entry = branch->entries + index;
1581 memmove (entry + 1, entry, (branch->n_entries - index) * sizeof (entry[0]));
1582 branch->n_entries += 1;
1583 return entry;
1586 static inline SmcEntry*
1587 smc_tree_branch_lookup_nearest_L (SmcBranch *branch,
1588 SmcKType key)
1590 unsigned int n_nodes = branch->n_entries, offs = 0;
1591 SmcEntry *check = branch->entries;
1592 int cmp = 0;
1593 while (offs < n_nodes)
1595 unsigned int i = (offs + n_nodes) >> 1;
1596 check = branch->entries + i;
1597 cmp = key < check->key ? -1 : key != check->key;
1598 if (cmp == 0)
1599 return check; /* return exact match */
1600 else if (cmp < 0)
1601 n_nodes = i;
1602 else /* (cmp > 0) */
1603 offs = i + 1;
1605 /* check points at last mismatch, cmp > 0 indicates greater key */
1606 return cmp > 0 ? check + 1 : check; /* return insertion position for inexact match */
1609 static void
1610 smc_tree_insert (SmcKType key,
1611 SmcVType value)
1613 unsigned int ix0, ix1;
1614 SmcEntry *entry;
1616 g_mutex_lock (&smc_tree_mutex);
1617 ix0 = SMC_TRUNK_HASH (key);
1618 ix1 = SMC_BRANCH_HASH (key);
1619 if (!smc_tree_root)
1621 smc_tree_root = calloc (SMC_TRUNK_COUNT, sizeof (smc_tree_root[0]));
1622 if (!smc_tree_root)
1623 smc_tree_abort (errno);
1625 if (!smc_tree_root[ix0])
1627 smc_tree_root[ix0] = calloc (SMC_BRANCH_COUNT, sizeof (smc_tree_root[0][0]));
1628 if (!smc_tree_root[ix0])
1629 smc_tree_abort (errno);
1631 entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
1632 if (!entry || /* need create */
1633 entry >= smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries || /* need append */
1634 entry->key != key) /* need insert */
1635 entry = smc_tree_branch_grow_L (&smc_tree_root[ix0][ix1], entry - smc_tree_root[ix0][ix1].entries);
1636 entry->key = key;
1637 entry->value = value;
1638 g_mutex_unlock (&smc_tree_mutex);
1641 static gboolean
1642 smc_tree_lookup (SmcKType key,
1643 SmcVType *value_p)
1645 SmcEntry *entry = NULL;
1646 unsigned int ix0 = SMC_TRUNK_HASH (key), ix1 = SMC_BRANCH_HASH (key);
1647 gboolean found_one = FALSE;
1648 *value_p = 0;
1649 g_mutex_lock (&smc_tree_mutex);
1650 if (smc_tree_root && smc_tree_root[ix0])
1652 entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
1653 if (entry &&
1654 entry < smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries &&
1655 entry->key == key)
1657 found_one = TRUE;
1658 *value_p = entry->value;
1661 g_mutex_unlock (&smc_tree_mutex);
1662 return found_one;
1665 static gboolean
1666 smc_tree_remove (SmcKType key)
1668 unsigned int ix0 = SMC_TRUNK_HASH (key), ix1 = SMC_BRANCH_HASH (key);
1669 gboolean found_one = FALSE;
1670 g_mutex_lock (&smc_tree_mutex);
1671 if (smc_tree_root && smc_tree_root[ix0])
1673 SmcEntry *entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
1674 if (entry &&
1675 entry < smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries &&
1676 entry->key == key)
1678 unsigned int i = entry - smc_tree_root[ix0][ix1].entries;
1679 smc_tree_root[ix0][ix1].n_entries -= 1;
1680 memmove (entry, entry + 1, (smc_tree_root[ix0][ix1].n_entries - i) * sizeof (entry[0]));
1681 if (!smc_tree_root[ix0][ix1].n_entries)
1683 /* avoid useless pressure on the memory system */
1684 free (smc_tree_root[ix0][ix1].entries);
1685 smc_tree_root[ix0][ix1].entries = NULL;
1687 found_one = TRUE;
1690 g_mutex_unlock (&smc_tree_mutex);
1691 return found_one;
1694 #ifdef G_ENABLE_DEBUG
1695 void
1696 g_slice_debug_tree_statistics (void)
1698 g_mutex_lock (&smc_tree_mutex);
1699 if (smc_tree_root)
1701 unsigned int i, j, t = 0, o = 0, b = 0, su = 0, ex = 0, en = 4294967295u;
1702 double tf, bf;
1703 for (i = 0; i < SMC_TRUNK_COUNT; i++)
1704 if (smc_tree_root[i])
1706 t++;
1707 for (j = 0; j < SMC_BRANCH_COUNT; j++)
1708 if (smc_tree_root[i][j].n_entries)
1710 b++;
1711 su += smc_tree_root[i][j].n_entries;
1712 en = MIN (en, smc_tree_root[i][j].n_entries);
1713 ex = MAX (ex, smc_tree_root[i][j].n_entries);
1715 else if (smc_tree_root[i][j].entries)
1716 o++; /* formerly used, now empty */
1718 en = b ? en : 0;
1719 tf = MAX (t, 1.0); /* max(1) to be a valid divisor */
1720 bf = MAX (b, 1.0); /* max(1) to be a valid divisor */
1721 g_fprintf (stderr, "GSlice: MemChecker: %u trunks, %u branches, %u old branches\n", t, b, o);
1722 g_fprintf (stderr, "GSlice: MemChecker: %f branches per trunk, %.2f%% utilization\n",
1723 b / tf,
1724 100.0 - (SMC_BRANCH_COUNT - b / tf) / (0.01 * SMC_BRANCH_COUNT));
1725 g_fprintf (stderr, "GSlice: MemChecker: %f entries per branch, %u minimum, %u maximum\n",
1726 su / bf, en, ex);
1728 else
1729 g_fprintf (stderr, "GSlice: MemChecker: root=NULL\n");
1730 g_mutex_unlock (&smc_tree_mutex);
1732 /* sample statistics (beast + GSLice + 24h scripted core & GUI activity):
1733 * PID %CPU %MEM VSZ RSS COMMAND
1734 * 8887 30.3 45.8 456068 414856 beast-0.7.1 empty.bse
1735 * $ cat /proc/8887/statm # total-program-size resident-set-size shared-pages text/code data/stack library dirty-pages
1736 * 114017 103714 2354 344 0 108676 0
1737 * $ cat /proc/8887/status
1738 * Name: beast-0.7.1
1739 * VmSize: 456068 kB
1740 * VmLck: 0 kB
1741 * VmRSS: 414856 kB
1742 * VmData: 434620 kB
1743 * VmStk: 84 kB
1744 * VmExe: 1376 kB
1745 * VmLib: 13036 kB
1746 * VmPTE: 456 kB
1747 * Threads: 3
1748 * (gdb) print g_slice_debug_tree_statistics ()
1749 * GSlice: MemChecker: 422 trunks, 213068 branches, 0 old branches
1750 * GSlice: MemChecker: 504.900474 branches per trunk, 98.81% utilization
1751 * GSlice: MemChecker: 4.965039 entries per branch, 1 minimum, 37 maximum
1754 #endif /* G_ENABLE_DEBUG */