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