1 /* GLIB sliced memory - fast concurrent memory chunk allocator
2 * Copyright (C) 2005 Tim Janik
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
23 #ifdef HAVE_POSIX_MEMALIGN
24 #define _XOPEN_SOURCE 600 /* posix_memalign() */
26 #include <stdlib.h> /* posix_memalign() */
29 #include "gmem.h" /* gslice.h */
30 #include "gthreadinit.h"
34 #include <unistd.h> /* sysconf() */
41 /* the GSlice allocator is split up into 4 layers, roughly modelled after the slab
42 * allocator and magazine extensions as outlined in:
43 * + [Bonwick94] Jeff Bonwick, The slab allocator: An object-caching kernel
44 * memory allocator. USENIX 1994, http://citeseer.ist.psu.edu/bonwick94slab.html
45 * + [Bonwick01] Bonwick and Jonathan Adams, Magazines and vmem: Extending the
46 * slab allocator to many cpu's and arbitrary resources.
47 * USENIX 2001, http://citeseer.ist.psu.edu/bonwick01magazines.html
49 * - the thread magazines. for each (aligned) chunk size, a magazine (a list)
50 * of recently freed and soon to be allocated chunks is maintained per thread.
51 * this way, most alloc/free requests can be quickly satisfied from per-thread
52 * free lists which only require one g_private_get() call to retrive the
54 * - the magazine cache. allocating and freeing chunks to/from threads only
55 * occours at magazine sizes from a global depot of magazines. the depot
56 * maintaines a 15 second working set of allocated magazines, so full
57 * magazines are not allocated and released too often.
58 * the chunk size dependent magazine sizes automatically adapt (within limits,
59 * see [3]) to lock contention to properly scale performance across a variety
61 * - the slab allocator. this allocator allocates slabs (blocks of memory) close
62 * to the system page size or multiples thereof which have to be page aligned.
63 * the blocks are divided into smaller chunks which are used to satisfy
64 * allocations from the upper layers. the space provided by the reminder of
65 * the chunk size division is used for cache colorization (random distribution
66 * of chunk addresses) to improve processor cache utilization. multiple slabs
67 * with the same chunk size are kept in a partially sorted ring to allow O(1)
68 * freeing and allocation of chunks (as long as the allocation of an entirely
69 * new slab can be avoided).
70 * - the page allocator. on most modern systems, posix_memalign(3) or
71 * memalign(3) should be available, so this is used to allocate blocks with
72 * system page size based alignments and sizes or multiples thereof.
73 * if no memalign variant is provided, valloc() is used instead and
74 * block sizes are limited to the system page size (no multiples thereof).
75 * as a fallback, on system without even valloc(), a malloc(3)-based page
76 * allocator with alloc-only behaviour is used.
79 * [1] some systems memalign(3) implementations may rely on boundary tagging for
80 * the handed out memory chunks. to avoid excessive page-wise fragmentation,
81 * we reserve 2 * sizeof (void*) per block size for the systems memalign(3),
82 * specified in NATIVE_MALLOC_PADDING.
83 * [2] using the slab allocator alone already provides for a fast and efficient
84 * allocator, it doesn't properly scale beyond single-threaded uses though.
85 * also, the slab allocator implements eager free(3)-ing, i.e. does not
86 * provide any form of caching or working set maintenance. so if used alone,
87 * it's vulnerable to trashing for sequences of balanced (alloc, free) pairs
88 * at certain thresholds.
89 * [3] magazine sizes are bound by an implementation specific minimum size and
90 * a chunk size specific maximum to limit magazine storage sizes to roughly
92 * [4] allocating ca. 8 chunks per block/page keeps a good balance between
93 * external and internal fragmentation (<= 12.5%). [Bonwick94]
96 /* --- macros and constants --- */
97 #define LARGEALIGNMENT (256)
98 #define P2ALIGNMENT (2 * sizeof (gsize)) /* fits 2 pointers (assumed to be 2 * GLIB_SIZEOF_SIZE_T below) */
99 #define ALIGN(size, base) ((base) * (gsize) (((size) + (base) - 1) / (base)))
100 #define NATIVE_MALLOC_PADDING P2ALIGNMENT /* per-page padding left for native malloc(3) see [1] */
101 #define SLAB_INFO_SIZE P2ALIGN (sizeof (SlabInfo) + NATIVE_MALLOC_PADDING)
102 #define MAX_MAGAZINE_SIZE (256) /* see [3] and allocator_get_magazine_threshold() for this */
103 #define MIN_MAGAZINE_SIZE (4)
104 #define MAX_STAMP_COUNTER (7) /* distributes the load of gettimeofday() */
105 #define MAX_SLAB_CHUNK_SIZE(al) (((al)->max_page_size - SLAB_INFO_SIZE) / 8) /* we want at last 8 chunks per page, see [4] */
106 #define MAX_SLAB_INDEX(al) (SLAB_INDEX (al, MAX_SLAB_CHUNK_SIZE (al)) + 1)
107 #define SLAB_INDEX(al, asize) ((asize) / P2ALIGNMENT - 1) /* asize must be P2ALIGNMENT aligned */
108 #define SLAB_CHUNK_SIZE(al, ix) (((ix) + 1) * P2ALIGNMENT)
109 #define SLAB_BPAGE_SIZE(al,csz) (8 * (csz) + SLAB_INFO_SIZE)
111 /* optimized version of ALIGN (size, P2ALIGNMENT) */
112 #if GLIB_SIZEOF_SIZE_T * 2 == 8 /* P2ALIGNMENT */
113 #define P2ALIGN(size) (((size) + 0x7) & ~(gsize) 0x7)
114 #elif GLIB_SIZEOF_SIZE_T * 2 == 16 /* P2ALIGNMENT */
115 #define P2ALIGN(size) (((size) + 0xf) & ~(gsize) 0xf)
117 #define P2ALIGN(size) ALIGN (size, P2ALIGNMENT)
120 /* special helpers to avoid gmessage.c dependency */
121 static void mem_error (const char *format, ...) G_GNUC_PRINTF (1,2);
122 #define mem_assert(cond) do { if (G_LIKELY (cond)) ; else mem_error ("assertion failed: %s", #cond); } while (0)
124 /* --- structures --- */
125 typedef struct _ChunkLink ChunkLink;
126 typedef struct _SlabInfo SlabInfo;
127 typedef struct _CachedMagazine CachedMagazine;
135 SlabInfo *next, *prev;
139 gsize count; /* approximative chunks list length */
142 Magazine *magazine1; /* array of MAX_SLAB_INDEX (allocator) */
143 Magazine *magazine2; /* array of MAX_SLAB_INDEX (allocator) */
146 gboolean always_malloc;
147 gboolean bypass_magazines;
148 gsize working_set_msecs;
149 guint color_increment;
152 /* const after initialization */
153 gsize min_page_size, max_page_size;
155 gsize max_slab_chunk_size_for_magazine_cache;
157 GMutex *magazine_mutex;
158 ChunkLink **magazines; /* array of MAX_SLAB_INDEX (allocator) */
159 guint *contention_counters; /* array of MAX_SLAB_INDEX (allocator) */
165 SlabInfo **slab_stack; /* array of MAX_SLAB_INDEX (allocator) */
169 /* --- prototypes --- */
170 static gpointer slab_allocator_alloc_chunk (gsize chunk_size);
171 static void slab_allocator_free_chunk (gsize chunk_size,
173 static void private_thread_memory_cleanup (gpointer data);
174 static gpointer allocator_memalign (gsize alignment,
176 static void allocator_memfree (gsize memsize,
178 static inline void magazine_cache_update_stamp (void);
179 static inline gsize allocator_get_magazine_threshold (Allocator *allocator,
182 /* --- variables --- */
183 static GPrivate *private_thread_memory = NULL;
184 static gsize sys_page_size = 0;
185 static Allocator allocator[1] = { { 0, }, };
186 static SliceConfig slice_config = {
187 FALSE, /* always_malloc */
188 FALSE, /* bypass_magazines */
189 15 * 1000, /* working_set_msecs */
190 1, /* color increment, alt: 0x7fffffff */
193 /* --- auxillary funcitons --- */
195 g_slice_set_config (GSliceConfig ckey,
198 g_return_if_fail (sys_page_size == 0);
201 case G_SLICE_CONFIG_ALWAYS_MALLOC:
202 slice_config.always_malloc = value != 0;
204 case G_SLICE_CONFIG_BYPASS_MAGAZINES:
205 slice_config.bypass_magazines = value != 0;
207 case G_SLICE_CONFIG_WORKING_SET_MSECS:
208 slice_config.working_set_msecs = value;
210 case G_SLICE_CONFIG_COLOR_INCREMENT:
211 slice_config.color_increment = value;
217 g_slice_get_config (GSliceConfig ckey)
221 case G_SLICE_CONFIG_ALWAYS_MALLOC:
222 return slice_config.always_malloc;
223 case G_SLICE_CONFIG_BYPASS_MAGAZINES:
224 return slice_config.bypass_magazines;
225 case G_SLICE_CONFIG_WORKING_SET_MSECS:
226 return slice_config.working_set_msecs;
227 case G_SLICE_CONFIG_CHUNK_SIZES:
228 return MAX_SLAB_INDEX (allocator);
229 case G_SLICE_CONFIG_COLOR_INCREMENT:
230 return slice_config.color_increment;
237 g_slice_get_config_state (GSliceConfig ckey,
242 g_return_val_if_fail (n_values != NULL, NULL);
247 case G_SLICE_CONFIG_CONTENTION_COUNTER:
248 array[i++] = SLAB_CHUNK_SIZE (allocator, address);
249 array[i++] = allocator->contention_counters[address];
250 array[i++] = allocator_get_magazine_threshold (allocator, address);
252 return g_memdup (array, sizeof (array[0]) * *n_values);
259 slice_config_init (SliceConfig *config)
261 /* don't use g_malloc/g_message here */
263 const gchar *val = _g_getenv_nomalloc ("G_SLICE", buffer);
264 static const GDebugKey keys[] = {
265 { "always-malloc", 1 << 0 },
267 gint flags = !val ? 0 : g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
268 *config = slice_config;
269 if (flags & (1 << 0)) /* always-malloc */
271 config->always_malloc = TRUE;
276 g_slice_init_nomessage (void)
278 /* we may not use g_error() or friends here */
279 mem_assert (sys_page_size == 0);
280 mem_assert (MIN_MAGAZINE_SIZE >= 4);
284 SYSTEM_INFO system_info;
285 GetSystemInfo (&system_info);
286 sys_page_size = system_info.dwPageSize;
289 sys_page_size = sysconf (_SC_PAGESIZE); /* = sysconf (_SC_PAGE_SIZE); = getpagesize(); */
291 mem_assert (sys_page_size >= 2 * LARGEALIGNMENT);
292 mem_assert ((sys_page_size & (sys_page_size - 1)) == 0);
293 slice_config_init (&allocator->config);
294 allocator->min_page_size = sys_page_size;
295 #if HAVE_POSIX_MEMALIGN || HAVE_MEMALIGN
296 /* allow allocation of pages up to 8KB (with 8KB alignment).
297 * this is useful because many medium to large sized structures
298 * fit less than 8 times (see [4]) into 4KB pages.
299 * we allow very small page sizes here, to reduce wastage in
300 * threads if only small allocations are required (this does
301 * bear the risk of incresing allocation times and fragmentation
304 allocator->min_page_size = MAX (allocator->min_page_size, 4096);
305 allocator->max_page_size = MAX (allocator->min_page_size, 8192);
306 allocator->min_page_size = MIN (allocator->min_page_size, 128);
308 /* we can only align to system page size */
309 allocator->max_page_size = sys_page_size;
311 allocator->magazine_mutex = NULL; /* _g_slice_thread_init_nomessage() */
312 allocator->magazines = g_new0 (ChunkLink*, MAX_SLAB_INDEX (allocator));
313 allocator->contention_counters = g_new0 (guint, MAX_SLAB_INDEX (allocator));
314 allocator->mutex_counter = 0;
315 allocator->stamp_counter = MAX_STAMP_COUNTER; /* force initial update */
316 allocator->last_stamp = 0;
317 allocator->slab_mutex = NULL; /* _g_slice_thread_init_nomessage() */
318 allocator->slab_stack = g_new0 (SlabInfo*, MAX_SLAB_INDEX (allocator));
319 allocator->color_accu = 0;
320 magazine_cache_update_stamp();
321 /* values cached for performance reasons */
322 allocator->max_slab_chunk_size_for_magazine_cache = MAX_SLAB_CHUNK_SIZE (allocator);
323 if (allocator->config.always_malloc || allocator->config.bypass_magazines)
324 allocator->max_slab_chunk_size_for_magazine_cache = 0; /* non-optimized cases */
328 allocator_categorize (gsize aligned_chunk_size)
330 /* speed up the likely path */
331 if (G_LIKELY (aligned_chunk_size && aligned_chunk_size <= allocator->max_slab_chunk_size_for_magazine_cache))
332 return 1; /* use magazine cache */
334 /* the above will fail (max_slab_chunk_size_for_magazine_cache == 0) if the
335 * allocator is still uninitialized, or if we are not configured to use the
339 g_slice_init_nomessage ();
340 if (!allocator->config.always_malloc &&
341 aligned_chunk_size &&
342 aligned_chunk_size <= MAX_SLAB_CHUNK_SIZE (allocator))
344 if (allocator->config.bypass_magazines)
345 return 2; /* use slab allocator, see [2] */
346 return 1; /* use magazine cache */
348 return 0; /* use malloc() */
352 _g_slice_thread_init_nomessage (void)
354 /* we may not use g_error() or friends here */
356 g_slice_init_nomessage();
357 private_thread_memory = g_private_new (private_thread_memory_cleanup);
358 allocator->magazine_mutex = g_mutex_new();
359 allocator->slab_mutex = g_mutex_new();
363 g_mutex_lock_a (GMutex *mutex,
364 guint *contention_counter)
366 gboolean contention = FALSE;
367 if (!g_mutex_trylock (mutex))
369 g_mutex_lock (mutex);
374 allocator->mutex_counter++;
375 if (allocator->mutex_counter >= 1) /* quickly adapt to contention */
377 allocator->mutex_counter = 0;
378 *contention_counter = MIN (*contention_counter + 1, MAX_MAGAZINE_SIZE);
381 else /* !contention */
383 allocator->mutex_counter--;
384 if (allocator->mutex_counter < -11) /* moderately recover magazine sizes */
386 allocator->mutex_counter = 0;
387 *contention_counter = MAX (*contention_counter, 1) - 1;
392 static inline ThreadMemory*
393 thread_memory_from_self (void)
395 ThreadMemory *tmem = g_private_get (private_thread_memory);
396 if (G_UNLIKELY (!tmem))
398 const guint n_magazines = MAX_SLAB_INDEX (allocator);
399 tmem = g_malloc0 (sizeof (ThreadMemory) + sizeof (Magazine) * 2 * n_magazines);
400 tmem->magazine1 = (Magazine*) (tmem + 1);
401 tmem->magazine2 = &tmem->magazine1[n_magazines];
402 g_private_set (private_thread_memory, tmem);
407 static inline ChunkLink*
408 magazine_chain_pop_head (ChunkLink **magazine_chunks)
410 /* magazine chains are linked via ChunkLink->next.
411 * each ChunkLink->data of the toplevel chain may point to a subchain,
412 * linked via ChunkLink->next. ChunkLink->data of the subchains just
413 * contains uninitialized junk.
415 ChunkLink *chunk = (*magazine_chunks)->data;
416 if (G_UNLIKELY (chunk))
418 /* allocating from freed list */
419 (*magazine_chunks)->data = chunk->next;
423 chunk = *magazine_chunks;
424 *magazine_chunks = chunk->next;
429 #if 0 /* useful for debugging */
431 magazine_count (ChunkLink *head)
438 ChunkLink *child = head->data;
440 for (child = head->data; child; child = child->next)
449 allocator_get_magazine_threshold (Allocator *allocator,
452 /* the magazine size calculated here has a lower bound of MIN_MAGAZINE_SIZE,
453 * which is required by the implementation. also, for moderately sized chunks
454 * (say >= 64 bytes), magazine sizes shouldn't be much smaller then the number
455 * of chunks available per page/2 to avoid excessive traffic in the magazine
456 * cache for small to medium sized structures.
457 * the upper bound of the magazine size is effectively provided by
458 * MAX_MAGAZINE_SIZE. for larger chunks, this number is scaled down so that
459 * the content of a single magazine doesn't exceed ca. 16KB.
461 gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
462 guint threshold = MAX (MIN_MAGAZINE_SIZE, allocator->max_page_size / MAX (5 * chunk_size, 5 * 32));
463 guint contention_counter = allocator->contention_counters[ix];
464 if (G_UNLIKELY (contention_counter)) /* single CPU bias */
466 /* adapt contention counter thresholds to chunk sizes */
467 contention_counter = contention_counter * 64 / chunk_size;
468 threshold = MAX (threshold, contention_counter);
473 /* --- magazine cache --- */
475 magazine_cache_update_stamp (void)
477 if (allocator->stamp_counter >= MAX_STAMP_COUNTER)
480 g_get_current_time (&tv);
481 allocator->last_stamp = tv.tv_sec * 1000 + tv.tv_usec / 1000; /* milli seconds */
482 allocator->stamp_counter = 0;
485 allocator->stamp_counter++;
488 static inline ChunkLink*
489 magazine_chain_prepare_fields (ChunkLink *magazine_chunks)
495 /* checked upon initialization: mem_assert (MIN_MAGAZINE_SIZE >= 4); */
496 /* ensure a magazine with at least 4 unused data pointers */
497 chunk1 = magazine_chain_pop_head (&magazine_chunks);
498 chunk2 = magazine_chain_pop_head (&magazine_chunks);
499 chunk3 = magazine_chain_pop_head (&magazine_chunks);
500 chunk4 = magazine_chain_pop_head (&magazine_chunks);
501 chunk4->next = magazine_chunks;
502 chunk3->next = chunk4;
503 chunk2->next = chunk3;
504 chunk1->next = chunk2;
508 /* access the first 3 fields of a specially prepared magazine chain */
509 #define magazine_chain_prev(mc) ((mc)->data)
510 #define magazine_chain_stamp(mc) ((mc)->next->data)
511 #define magazine_chain_uint_stamp(mc) GPOINTER_TO_UINT ((mc)->next->data)
512 #define magazine_chain_next(mc) ((mc)->next->next->data)
513 #define magazine_chain_count(mc) ((mc)->next->next->next->data)
516 magazine_cache_trim (Allocator *allocator,
520 /* g_mutex_lock (allocator->mutex); done by caller */
521 /* trim magazine cache from tail */
522 ChunkLink *current = magazine_chain_prev (allocator->magazines[ix]);
523 ChunkLink *trash = NULL;
524 while (ABS (stamp - magazine_chain_uint_stamp (current)) >= allocator->config.working_set_msecs)
527 ChunkLink *prev = magazine_chain_prev (current);
528 ChunkLink *next = magazine_chain_next (current);
529 magazine_chain_next (prev) = next;
530 magazine_chain_prev (next) = prev;
531 /* clear special fields, put on trash stack */
532 magazine_chain_next (current) = NULL;
533 magazine_chain_count (current) = NULL;
534 magazine_chain_stamp (current) = NULL;
535 magazine_chain_prev (current) = trash;
537 /* fixup list head if required */
538 if (current == allocator->magazines[ix])
540 allocator->magazines[ix] = NULL;
545 g_mutex_unlock (allocator->magazine_mutex);
549 const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
550 g_mutex_lock (allocator->slab_mutex);
554 trash = magazine_chain_prev (current);
555 magazine_chain_prev (current) = NULL; /* clear special field */
558 ChunkLink *chunk = magazine_chain_pop_head (¤t);
559 slab_allocator_free_chunk (chunk_size, chunk);
562 g_mutex_unlock (allocator->slab_mutex);
567 magazine_cache_push_magazine (guint ix,
568 ChunkLink *magazine_chunks,
569 gsize count) /* must be >= MIN_MAGAZINE_SIZE */
571 ChunkLink *current = magazine_chain_prepare_fields (magazine_chunks);
572 ChunkLink *next, *prev;
573 g_mutex_lock (allocator->magazine_mutex);
574 /* add magazine at head */
575 next = allocator->magazines[ix];
577 prev = magazine_chain_prev (next);
579 next = prev = current;
580 magazine_chain_next (prev) = current;
581 magazine_chain_prev (next) = current;
582 magazine_chain_prev (current) = prev;
583 magazine_chain_next (current) = next;
584 magazine_chain_count (current) = (gpointer) count;
586 magazine_cache_update_stamp();
587 magazine_chain_stamp (current) = GUINT_TO_POINTER (allocator->last_stamp);
588 allocator->magazines[ix] = current;
589 /* free old magazines beyond a certain threshold */
590 magazine_cache_trim (allocator, ix, allocator->last_stamp);
591 /* g_mutex_unlock (allocator->mutex); was done by magazine_cache_trim() */
595 magazine_cache_pop_magazine (guint ix,
598 g_mutex_lock_a (allocator->magazine_mutex, &allocator->contention_counters[ix]);
599 if (!allocator->magazines[ix])
601 guint magazine_threshold = allocator_get_magazine_threshold (allocator, ix);
602 gsize i, chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
603 ChunkLink *chunk, *head;
604 g_mutex_unlock (allocator->magazine_mutex);
605 g_mutex_lock (allocator->slab_mutex);
606 head = slab_allocator_alloc_chunk (chunk_size);
609 for (i = 1; i < magazine_threshold; i++)
611 chunk->next = slab_allocator_alloc_chunk (chunk_size);
616 g_mutex_unlock (allocator->slab_mutex);
622 ChunkLink *current = allocator->magazines[ix];
623 ChunkLink *prev = magazine_chain_prev (current);
624 ChunkLink *next = magazine_chain_next (current);
626 magazine_chain_next (prev) = next;
627 magazine_chain_prev (next) = prev;
628 allocator->magazines[ix] = next == current ? NULL : next;
629 g_mutex_unlock (allocator->magazine_mutex);
630 /* clear special fields and hand out */
631 *countp = (gsize) magazine_chain_count (current);
632 magazine_chain_prev (current) = NULL;
633 magazine_chain_next (current) = NULL;
634 magazine_chain_count (current) = NULL;
635 magazine_chain_stamp (current) = NULL;
640 /* --- thread magazines --- */
642 private_thread_memory_cleanup (gpointer data)
644 ThreadMemory *tmem = data;
645 const guint n_magazines = MAX_SLAB_INDEX (allocator);
647 for (ix = 0; ix < n_magazines; ix++)
651 mags[0] = &tmem->magazine1[ix];
652 mags[1] = &tmem->magazine2[ix];
653 for (j = 0; j < 2; j++)
655 Magazine *mag = mags[j];
656 if (mag->count >= MIN_MAGAZINE_SIZE)
657 magazine_cache_push_magazine (ix, mag->chunks, mag->count);
660 const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
661 g_mutex_lock (allocator->slab_mutex);
664 ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
665 slab_allocator_free_chunk (chunk_size, chunk);
667 g_mutex_unlock (allocator->slab_mutex);
675 thread_memory_magazine1_reload (ThreadMemory *tmem,
678 Magazine *mag = &tmem->magazine1[ix];
679 mem_assert (mag->chunks == NULL); /* ensure that we may reset mag->count */
681 mag->chunks = magazine_cache_pop_magazine (ix, &mag->count);
685 thread_memory_magazine2_unload (ThreadMemory *tmem,
688 Magazine *mag = &tmem->magazine2[ix];
689 magazine_cache_push_magazine (ix, mag->chunks, mag->count);
695 thread_memory_swap_magazines (ThreadMemory *tmem,
698 Magazine xmag = tmem->magazine1[ix];
699 tmem->magazine1[ix] = tmem->magazine2[ix];
700 tmem->magazine2[ix] = xmag;
703 static inline gboolean
704 thread_memory_magazine1_is_empty (ThreadMemory *tmem,
707 return tmem->magazine1[ix].chunks == NULL;
710 static inline gboolean
711 thread_memory_magazine2_is_full (ThreadMemory *tmem,
714 return tmem->magazine2[ix].count >= allocator_get_magazine_threshold (allocator, ix);
717 static inline gpointer
718 thread_memory_magazine1_alloc (ThreadMemory *tmem,
721 Magazine *mag = &tmem->magazine1[ix];
722 ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
723 if (G_LIKELY (mag->count > 0))
729 thread_memory_magazine2_free (ThreadMemory *tmem,
733 Magazine *mag = &tmem->magazine2[ix];
734 ChunkLink *chunk = mem;
736 chunk->next = mag->chunks;
741 /* --- API functions --- */
743 g_slice_alloc (gsize mem_size)
748 chunk_size = P2ALIGN (mem_size);
749 acat = allocator_categorize (chunk_size);
750 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
752 ThreadMemory *tmem = thread_memory_from_self();
753 guint ix = SLAB_INDEX (allocator, chunk_size);
754 if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
756 thread_memory_swap_magazines (tmem, ix);
757 if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
758 thread_memory_magazine1_reload (tmem, ix);
760 mem = thread_memory_magazine1_alloc (tmem, ix);
762 else if (acat == 2) /* allocate through slab allocator */
764 g_mutex_lock (allocator->slab_mutex);
765 mem = slab_allocator_alloc_chunk (chunk_size);
766 g_mutex_unlock (allocator->slab_mutex);
768 else /* delegate to system malloc */
769 mem = g_malloc (mem_size);
774 g_slice_alloc0 (gsize mem_size)
776 gpointer mem = g_slice_alloc (mem_size);
778 memset (mem, 0, mem_size);
783 g_slice_free1 (gsize mem_size,
786 gsize chunk_size = P2ALIGN (mem_size);
787 guint acat = allocator_categorize (chunk_size);
788 if (G_UNLIKELY (!mem_block))
790 else if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
792 ThreadMemory *tmem = thread_memory_from_self();
793 guint ix = SLAB_INDEX (allocator, chunk_size);
794 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
796 thread_memory_swap_magazines (tmem, ix);
797 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
798 thread_memory_magazine2_unload (tmem, ix);
800 thread_memory_magazine2_free (tmem, ix, mem_block);
802 else if (acat == 2) /* allocate through slab allocator */
804 g_mutex_lock (allocator->slab_mutex);
805 slab_allocator_free_chunk (chunk_size, mem_block);
806 g_mutex_unlock (allocator->slab_mutex);
808 else /* delegate to system malloc */
813 g_slice_free_chain_with_offset (gsize mem_size,
817 gpointer slice = mem_chain;
818 /* while the thread magazines and the magazine cache are implemented so that
819 * they can easily be extended to allow for free lists containing more free
820 * lists for the first level nodes, which would allow O(1) freeing in this
821 * function, the benefit of such an extension is questionable, because:
822 * - the magazine size counts will become mere lower bounds which confuses
823 * the code adapting to lock contention;
824 * - freeing a single node to the thread magazines is very fast, so this
825 * O(list_length) operation is multiplied by a fairly small factor;
826 * - memory usage histograms on larger applications seem to indicate that
827 * the amount of released multi node lists is negligible in comparison
828 * to single node releases.
829 * - the major performance bottle neck, namely g_private_get() or
830 * g_mutex_lock()/g_mutex_unlock() has already been moved out of the
831 * inner loop for freeing chained slices.
833 gsize chunk_size = P2ALIGN (mem_size);
834 guint acat = allocator_categorize (chunk_size);
835 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
837 ThreadMemory *tmem = thread_memory_from_self();
838 guint ix = SLAB_INDEX (allocator, chunk_size);
841 guint8 *current = slice;
842 slice = *(gpointer*) (current + next_offset);
843 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
845 thread_memory_swap_magazines (tmem, ix);
846 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
847 thread_memory_magazine2_unload (tmem, ix);
849 thread_memory_magazine2_free (tmem, ix, current);
852 else if (acat == 2) /* allocate through slab allocator */
854 g_mutex_lock (allocator->slab_mutex);
857 guint8 *current = slice;
858 slice = *(gpointer*) (current + next_offset);
859 slab_allocator_free_chunk (chunk_size, current);
861 g_mutex_unlock (allocator->slab_mutex);
863 else /* delegate to system malloc */
866 guint8 *current = slice;
867 slice = *(gpointer*) (current + next_offset);
872 /* --- single page allocator --- */
874 allocator_slab_stack_push (Allocator *allocator,
878 /* insert slab at slab ring head */
879 if (!allocator->slab_stack[ix])
886 SlabInfo *next = allocator->slab_stack[ix], *prev = next->prev;
892 allocator->slab_stack[ix] = sinfo;
896 allocator_aligned_page_size (Allocator *allocator,
899 gsize val = 1 << g_bit_storage (n_bytes - 1);
900 val = MAX (val, allocator->min_page_size);
905 allocator_add_slab (Allocator *allocator,
911 gsize addr, padding, n_chunks, color = 0;
912 gsize page_size = allocator_aligned_page_size (allocator, SLAB_BPAGE_SIZE (allocator, chunk_size));
913 /* allocate 1 page for the chunks and the slab */
914 gpointer aligned_memory = allocator_memalign (page_size, page_size - NATIVE_MALLOC_PADDING);
915 guint8 *mem = aligned_memory;
919 const gchar *syserr = "unknown error";
921 syserr = strerror (errno);
923 mem_error ("failed to allocate %u bytes (alignment: %u): %s\n",
924 (guint) (page_size - NATIVE_MALLOC_PADDING), (guint) page_size, syserr);
926 /* mask page adress */
927 addr = ((gsize) mem / page_size) * page_size;
928 /* assert alignment */
929 mem_assert (aligned_memory == (gpointer) addr);
930 /* basic slab info setup */
931 sinfo = (SlabInfo*) (mem + page_size - SLAB_INFO_SIZE);
932 sinfo->n_allocated = 0;
933 sinfo->chunks = NULL;
934 /* figure cache colorization */
935 n_chunks = ((guint8*) sinfo - mem) / chunk_size;
936 padding = ((guint8*) sinfo - mem) - n_chunks * chunk_size;
939 color = (allocator->color_accu * P2ALIGNMENT) % padding;
940 allocator->color_accu += allocator->config.color_increment;
942 /* add chunks to free list */
943 chunk = (ChunkLink*) (mem + color);
944 sinfo->chunks = chunk;
945 for (i = 0; i < n_chunks - 1; i++)
947 chunk->next = (ChunkLink*) ((guint8*) chunk + chunk_size);
950 chunk->next = NULL; /* last chunk */
951 /* add slab to slab ring */
952 allocator_slab_stack_push (allocator, ix, sinfo);
956 slab_allocator_alloc_chunk (gsize chunk_size)
959 guint ix = SLAB_INDEX (allocator, chunk_size);
960 /* ensure non-empty slab */
961 if (!allocator->slab_stack[ix] || !allocator->slab_stack[ix]->chunks)
962 allocator_add_slab (allocator, ix, chunk_size);
964 chunk = allocator->slab_stack[ix]->chunks;
965 allocator->slab_stack[ix]->chunks = chunk->next;
966 allocator->slab_stack[ix]->n_allocated++;
967 /* rotate empty slabs */
968 if (!allocator->slab_stack[ix]->chunks)
969 allocator->slab_stack[ix] = allocator->slab_stack[ix]->next;
974 slab_allocator_free_chunk (gsize chunk_size,
979 guint ix = SLAB_INDEX (allocator, chunk_size);
980 gsize page_size = allocator_aligned_page_size (allocator, SLAB_BPAGE_SIZE (allocator, chunk_size));
981 gsize addr = ((gsize) mem / page_size) * page_size;
982 /* mask page adress */
983 guint8 *page = (guint8*) addr;
984 SlabInfo *sinfo = (SlabInfo*) (page + page_size - SLAB_INFO_SIZE);
985 /* assert valid chunk count */
986 mem_assert (sinfo->n_allocated > 0);
987 /* add chunk to free list */
988 was_empty = sinfo->chunks == NULL;
989 chunk = (ChunkLink*) mem;
990 chunk->next = sinfo->chunks;
991 sinfo->chunks = chunk;
992 sinfo->n_allocated--;
993 /* keep slab ring partially sorted, empty slabs at end */
997 SlabInfo *next = sinfo->next, *prev = sinfo->prev;
1000 if (allocator->slab_stack[ix] == sinfo)
1001 allocator->slab_stack[ix] = next == sinfo ? NULL : next;
1002 /* insert slab at head */
1003 allocator_slab_stack_push (allocator, ix, sinfo);
1005 /* eagerly free complete unused slabs */
1006 if (!sinfo->n_allocated)
1009 SlabInfo *next = sinfo->next, *prev = sinfo->prev;
1012 if (allocator->slab_stack[ix] == sinfo)
1013 allocator->slab_stack[ix] = next == sinfo ? NULL : next;
1015 allocator_memfree (page_size, page);
1019 /* --- memalign implementation --- */
1020 #ifdef HAVE_MALLOC_H
1021 #include <malloc.h> /* memalign() */
1025 * define HAVE_POSIX_MEMALIGN 1 // if free(posix_memalign(3)) works, <stdlib.h>
1026 * define HAVE_MEMALIGN 1 // if free(memalign(3)) works, <malloc.h>
1027 * define HAVE_VALLOC 1 // if free(valloc(3)) works, <stdlib.h> or <malloc.h>
1028 * if none is provided, we implement malloc(3)-based alloc-only page alignment
1031 #if !(HAVE_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC)
1032 static GTrashStack *compat_valloc_trash = NULL;
1036 allocator_memalign (gsize alignment,
1039 gpointer aligned_memory = NULL;
1041 #if HAVE_POSIX_MEMALIGN
1042 err = posix_memalign (&aligned_memory, alignment, memsize);
1045 aligned_memory = memalign (alignment, memsize);
1049 aligned_memory = valloc (memsize);
1052 /* simplistic non-freeing page allocator */
1053 mem_assert (alignment == sys_page_size);
1054 mem_assert (memsize <= sys_page_size);
1055 if (!compat_valloc_trash)
1057 const guint n_pages = 16;
1058 guint8 *mem = malloc (n_pages * sys_page_size);
1063 guint8 *amem = (guint8*) ALIGN ((gsize) mem, sys_page_size);
1065 i--; /* mem wasn't page aligned */
1067 g_trash_stack_push (&compat_valloc_trash, amem + i * sys_page_size);
1070 aligned_memory = g_trash_stack_pop (&compat_valloc_trash);
1072 if (!aligned_memory)
1074 return aligned_memory;
1078 allocator_memfree (gsize memsize,
1081 #if HAVE_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC
1084 mem_assert (memsize <= sys_page_size);
1085 g_trash_stack_push (&compat_valloc_trash, mem);
1092 mem_error (const char *format,
1097 /* at least, put out "MEMORY-ERROR", in case we segfault during the rest of the function */
1098 fputs ("\n***MEMORY-ERROR***: ", stderr);
1099 pname = g_get_prgname();
1100 fprintf (stderr, "%s[%u]: GSlice: ", pname ? pname : "", getpid());
1101 va_start (args, format);
1102 vfprintf (stderr, format, args);
1104 fputs ("\n", stderr);
1108 #define __G_SLICE_C__
1109 #include "galiasdef.c"