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.
20 #define _XOPEN_SOURCE 600 /* posix_memalign() */
21 #include <stdlib.h> /* posix_memalign() */
22 #include <assert.h> /* assert() for nomessage phase */
26 #include "gmem.h" /* gslice.h */
27 #include "gthreadinit.h"
31 #include <unistd.h> /* sysconf() */
37 /* the GSlice allocator is split up into 4 layers, roughly modelled after the slab
38 * allocator and magazine extensions as outlined in:
39 * + [Bonwick94] Jeff Bonwick, The slab allocator: An object-caching kernel
40 * memory allocator. USENIX 1994, http://citeseer.ist.psu.edu/bonwick94slab.html
41 * + [Bonwick01] Bonwick and Jonathan Adams, Magazines and vmem: Extending the
42 * slab allocator to many cpu's and arbitrary resources.
43 * USENIX 2001, http://citeseer.ist.psu.edu/bonwick01magazines.html
45 * - the thread magazines. for each (aligned) chunk size, a magazine (a list)
46 * of recently freed and soon to be allocated chunks is maintained per thread.
47 * this way, most alloc/free requests can be quickly satisfied from per-thread
48 * free lists which only require one g_private_get() call to retrive the
50 * - the magazine cache. allocating and freeing chunks to/from threads only
51 * occours at magazine sizes from a global depot of magazines. the depot
52 * maintaines a 15 second working set of allocated magazines, so full
53 * magazines are not allocated and released too often.
54 * the chunk size dependent magazine sizes automatically adapt (within limits,
55 * see [3]) to lock contention to properly scale performance across a variety
57 * - the slab allocator. this allocator allocates slabs (blocks of memory) close
58 * to the system page size or multiples thereof which have to be page aligned.
59 * the blocks are divided into smaller chunks which are used to satisfy
60 * allocations from the upper layers. the space provided by the reminder of
61 * the chunk size division is used for cache colorization (random distribution
62 * of chunk addresses) to improve processor cache utilization. multiple slabs
63 * with the same chunk size are kept in a partially sorted ring to allow O(1)
64 * freeing and allocation of chunks (as long as the allocation of an entirely
65 * new slab can be avoided).
66 * - the page allocator. on most modern systems, posix_memalign(3) or
67 * memalign(3) should be available, so this is used to allocate blocks with
68 * system page size based alignments and sizes or multiples thereof.
69 * if no memalign variant is provided, valloc() is used instead and
70 * block sizes are limited to the system page size (no multiples thereof).
71 * as a fallback, on system without even valloc(), a malloc(3)-based page
72 * allocator with alloc-only behaviour is used.
75 * [1] some systems memalign(3) implementations may rely on boundary tagging for
76 * the handed out memory chunks. to avoid excessive page-wise fragmentation,
77 * we reserve 2 * sizeof (void*) per block size for the systems memalign(3),
78 * specified in NATIVE_MALLOC_PADDING.
79 * [2] using the slab allocator alone already provides for a fast and efficient
80 * allocator, it doesn't properly scale beyond single-threaded uses though.
81 * also, the slab allocator implements eager free(3)-ing, i.e. does not
82 * provide any form of caching or working set maintenance. so if used alone,
83 * it's vulnerable to trashing for sequences of balanced (alloc, free) pairs
84 * at certain thresholds.
85 * [3] magazine sizes are bound by an implementation specific minimum size and
86 * a chunk size specific maximum to limit magazine storage sizes to roughly
88 * [4] allocating ca. 8 chunks per block/page keeps a good balance between
89 * external and internal fragmentation (<= 12.5%) [Bonwick94]
92 /* --- macros and constants --- */
93 #define LARGEALIGNMENT (256)
94 #define P2ALIGNMENT (2 * sizeof (gsize)) /* fits 2 pointers (assumed to be 2 * GLIB_SIZEOF_SIZE_T below) */
95 #define ALIGN(size, base) ((base) * (gsize) (((size) + (base) - 1) / (base)))
96 #define NATIVE_MALLOC_PADDING P2ALIGNMENT /* per-page padding left for native malloc(3) see [1] */
97 #define SLAB_INFO_SIZE P2ALIGN (sizeof (SlabInfo) + NATIVE_MALLOC_PADDING)
98 #define MAX_MAGAZINE_SIZE (256) /* see [3] and allocator_get_magazine_threshold() for this */
99 #define MIN_MAGAZINE_SIZE (4)
100 #define MAX_STAMP_COUNTER (7) /* distributes the load of gettimeofday() */
101 #define MAX_SLAB_CHUNK_SIZE(al) (((al)->max_page_size - SLAB_INFO_SIZE) / 8) /* we want at last 8 chunks per page, see [4] */
102 #define MAX_SLAB_INDEX(al) (SLAB_INDEX (al, MAX_SLAB_CHUNK_SIZE (al)) + 1)
103 #define SLAB_INDEX(al, asize) ((asize) / P2ALIGNMENT - 1) /* asize must be P2ALIGNMENT aligned */
104 #define SLAB_CHUNK_SIZE(al, ix) (((ix) + 1) * P2ALIGNMENT)
105 #define SLAB_PAGE_SIZE(al,csz) (ALIGN (8 * (csz) + SLAB_INFO_SIZE, (al)->min_page_size))
107 /* optimized version of ALIGN (size, P2ALIGNMENT) */
108 #if GLIB_SIZEOF_SIZE_T * 2 == 8 /* P2ALIGNMENT */
109 #define P2ALIGN(size) (((size) + 0x7) & ~(gsize) 0x7)
110 #elif GLIB_SIZEOF_SIZE_T * 2 == 16 /* P2ALIGNMENT */
111 #define P2ALIGN(size) (((size) + 0xf) & ~(gsize) 0xf)
113 #define P2ALIGN(size) ALIGN (size, P2ALIGNMENT)
116 /* --- structures --- */
117 typedef struct _ChunkLink ChunkLink;
118 typedef struct _SlabInfo SlabInfo;
119 typedef struct _CachedMagazine CachedMagazine;
127 SlabInfo *next, *prev;
131 gsize count; /* approximative chunks list length */
134 Magazine *magazine1; /* array of MAX_SLAB_INDEX (allocator) */
135 Magazine *magazine2; /* array of MAX_SLAB_INDEX (allocator) */
138 gboolean always_malloc;
139 gboolean bypass_magazines;
140 gboolean always_free;
141 gsize working_set_msecs;
144 /* const after initialization */
145 gsize min_page_size, max_page_size;
147 guint max_slab_chunk_size_for_magazine_cache;
149 GMutex *magazine_mutex;
150 ChunkLink **magazines; /* array of MAX_SLAB_INDEX (allocator) */
151 guint *contention_counters; /* array of MAX_SLAB_INDEX (allocator) */
157 SlabInfo **slab_stack; /* array of MAX_SLAB_INDEX (allocator) */
161 /* --- prototypes --- */
162 static gpointer slab_allocator_alloc_chunk (gsize chunk_size);
163 static void slab_allocator_free_chunk (gsize chunk_size,
165 static void private_thread_memory_cleanup (gpointer data);
166 static gpointer allocator_memalign (gsize alignment,
168 static void allocator_memfree (gsize memsize,
170 static inline void magazine_cache_update_stamp (void);
171 static inline gsize allocator_get_magazine_threshold (Allocator *allocator,
174 /* --- variables --- */
175 static GPrivate *private_thread_memory = NULL;
176 static gsize sys_page_size = 0;
177 static Allocator allocator[1] = { { 0, }, };
178 static SliceConfig slice_config = {
179 FALSE, /* always_malloc */
180 FALSE, /* bypass_magazines */
181 FALSE, /* always_free */
182 15 * 1000, /* working_set_msecs */
185 /* --- auxillary funcitons --- */
187 g_slice_set_config (GSliceConfig ckey,
190 g_return_if_fail (sys_page_size == 0);
193 case G_SLICE_CONFIG_ALWAYS_MALLOC:
194 slice_config.always_malloc = value != 0;
196 case G_SLICE_CONFIG_BYPASS_MAGAZINES:
197 slice_config.bypass_magazines = value != 0;
199 case G_SLICE_CONFIG_ALWAYS_FREE:
200 slice_config.always_free = value != 0;
202 case G_SLICE_CONFIG_WORKING_SET_MSECS:
203 slice_config.working_set_msecs = value;
210 g_slice_get_config (GSliceConfig ckey)
214 case G_SLICE_CONFIG_ALWAYS_MALLOC:
215 return slice_config.always_malloc;
216 case G_SLICE_CONFIG_BYPASS_MAGAZINES:
217 return slice_config.bypass_magazines;
218 case G_SLICE_CONFIG_ALWAYS_FREE:
219 return slice_config.always_free;
220 case G_SLICE_CONFIG_WORKING_SET_MSECS:
221 return slice_config.working_set_msecs;
222 case G_SLICE_CONFIG_CHUNK_SIZES:
223 return MAX_SLAB_INDEX (allocator);
230 g_slice_get_config_state (GSliceConfig ckey,
235 g_return_val_if_fail (n_values != NULL, NULL);
240 case G_SLICE_CONFIG_CONTENTION_COUNTER:
241 array[i++] = SLAB_CHUNK_SIZE (allocator, address);
242 array[i++] = allocator->contention_counters[address];
243 array[i++] = allocator_get_magazine_threshold (allocator, address);
245 return g_memdup (array, sizeof (array[0]) * *n_values);
252 g_slice_init_nomessage (void)
255 SYSTEM_INFO system_info;
257 /* we may not use g_error() or friends here */
258 assert (sys_page_size == 0);
261 GetSystemInfo (&system_info);
262 sys_page_size = system_info.dwPageSize;
264 sys_page_size = sysconf (_SC_PAGESIZE); /* = sysconf (_SC_PAGE_SIZE); = getpagesize(); */
266 assert (sys_page_size >= 2 * LARGEALIGNMENT);
267 allocator->config = slice_config;
268 allocator->min_page_size = sys_page_size;
269 #if HAVE_POSIX_MEMALIGN || HAVE_MEMALIGN
270 /* allow allocation of pages up to 8KB (with 8KB alignment).
271 * this is useful because many medium to large sized structures
272 * fit less than 8 times (see [4]) into 4KB pages.
274 allocator->min_page_size = MAX (allocator->min_page_size, 4096);
275 allocator->max_page_size = MAX (allocator->min_page_size, 8192);
277 /* we can only align to system page size */
278 allocator->max_page_size = sys_page_size;
280 allocator->magazine_mutex = NULL; /* _g_slice_thread_init_nomessage() */
281 allocator->magazines = g_new0 (ChunkLink*, MAX_SLAB_INDEX (allocator));
282 allocator->contention_counters = g_new0 (guint, MAX_SLAB_INDEX (allocator));
283 allocator->mutex_counter = 0;
284 allocator->stamp_counter = MAX_STAMP_COUNTER; /* force initial update */
285 allocator->last_stamp = 0;
286 allocator->slab_mutex = NULL; /* _g_slice_thread_init_nomessage() */
287 allocator->slab_stack = g_new0 (SlabInfo*, MAX_SLAB_INDEX (allocator));
288 allocator->color_accu = 0;
289 magazine_cache_update_stamp();
290 /* values cached for performance reasons */
291 allocator->max_slab_chunk_size_for_magazine_cache = MAX_SLAB_CHUNK_SIZE (allocator);
292 if (allocator->config.always_malloc || allocator->config.bypass_magazines)
293 allocator->max_slab_chunk_size_for_magazine_cache = 0; /* non-optimized cases */
297 allocator_categorize (gsize aligned_chunk_size)
299 /* speed up the likely path */
300 if (G_LIKELY (aligned_chunk_size && aligned_chunk_size <= allocator->max_slab_chunk_size_for_magazine_cache))
301 return 1; /* use magazine cache */
303 /* the above will fail (max_slab_chunk_size_for_magazine_cache == 0) if the
304 * allocator is still uninitialized, or if we are not configured to use the
308 g_slice_init_nomessage ();
309 if (!allocator->config.always_malloc &&
310 aligned_chunk_size &&
311 aligned_chunk_size <= MAX_SLAB_CHUNK_SIZE (allocator))
313 if (allocator->config.bypass_magazines)
314 return 2; /* use slab allocator, see [2] */
315 return 1; /* use magazine cache */
317 return 0; /* use malloc() */
321 _g_slice_thread_init_nomessage (void)
323 /* we may not use g_error() or friends here */
325 g_slice_init_nomessage();
326 private_thread_memory = g_private_new (private_thread_memory_cleanup);
327 allocator->magazine_mutex = g_mutex_new();
328 allocator->slab_mutex = g_mutex_new();
332 g_mutex_lock_a (GMutex *mutex,
333 guint *contention_counter)
335 gboolean contention = FALSE;
336 if (!g_mutex_trylock (mutex))
338 g_mutex_lock (mutex);
343 allocator->mutex_counter++;
344 if (allocator->mutex_counter >= 1) /* quickly adapt to contention */
346 allocator->mutex_counter = 0;
347 *contention_counter = MIN (*contention_counter + 1, MAX_MAGAZINE_SIZE);
350 else /* !contention */
352 allocator->mutex_counter--;
353 if (allocator->mutex_counter < -11) /* moderately recover magazine sizes */
355 allocator->mutex_counter = 0;
356 *contention_counter = MAX (*contention_counter, 1) - 1;
361 static inline ThreadMemory*
362 thread_memory_from_self (void)
364 ThreadMemory *tmem = g_private_get (private_thread_memory);
365 if (G_UNLIKELY (!tmem))
367 const guint n_magazines = MAX_SLAB_INDEX (allocator);
368 tmem = g_malloc0 (sizeof (ThreadMemory) + sizeof (Magazine) * 2 * n_magazines);
369 tmem->magazine1 = (Magazine*) (tmem + 1);
370 tmem->magazine2 = &tmem->magazine1[n_magazines];
371 g_private_set (private_thread_memory, tmem);
376 static inline ChunkLink*
377 magazine_chain_pop_head (ChunkLink **magazine_chunks)
379 /* magazine chains are linked via ChunkLink->next.
380 * each ChunkLink->data of the toplevel chain may point to a subchain,
381 * linked via ChunkLink->next. ChunkLink->data of the subchains just
382 * contains uninitialized junk.
384 ChunkLink *chunk = (*magazine_chunks)->data;
385 if (G_UNLIKELY (chunk))
387 /* allocating from freed list */
388 (*magazine_chunks)->data = chunk->next;
392 chunk = *magazine_chunks;
393 *magazine_chunks = chunk->next;
398 #if 0 /* useful for debugging */
400 magazine_count (ChunkLink *head)
407 ChunkLink *child = head->data;
409 for (child = head->data; child; child = child->next)
418 allocator_get_magazine_threshold (Allocator *allocator,
421 /* the magazine size calculated here has a lower bound of MIN_MAGAZINE_SIZE,
422 * which is required by the implementation. also, for moderately sized chunks
423 * (say >= 64 bytes), magazine sizes shouldn't be much smaller then the number
424 * of chunks available per page/2 to avoid excessive traffic in the magazine
425 * cache for small to medium sized structures.
426 * the upper bound of the magazine size is effectively provided by
427 * MAX_MAGAZINE_SIZE. for larger chunks, this number is scaled down so that
428 * the content of a single magazine doesn't exceed ca. 16KB.
430 gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
431 guint threshold = MAX (MIN_MAGAZINE_SIZE, allocator->max_page_size / MAX (5 * chunk_size, 5 * 32));
432 guint contention_counter = allocator->contention_counters[ix];
433 if (G_UNLIKELY (contention_counter)) /* single CPU bias */
435 /* adapt contention counter thresholds to chunk sizes */
436 contention_counter = contention_counter * 64 / chunk_size;
437 threshold = MAX (threshold, contention_counter);
442 /* --- magazine cache --- */
444 magazine_cache_update_stamp (void)
446 if (allocator->stamp_counter >= MAX_STAMP_COUNTER)
449 g_get_current_time (&tv);
450 allocator->last_stamp = tv.tv_sec * 1000 + tv.tv_usec / 1000; /* milli seconds */
451 allocator->stamp_counter = 0;
454 allocator->stamp_counter++;
457 static inline ChunkLink*
458 magazine_chain_prepare_fields (ChunkLink *magazine_chunks)
464 g_assert (MIN_MAGAZINE_SIZE >= 4);
465 /* ensure a magazine with at least 4 unused data pointers */
466 chunk1 = magazine_chain_pop_head (&magazine_chunks);
467 chunk2 = magazine_chain_pop_head (&magazine_chunks);
468 chunk3 = magazine_chain_pop_head (&magazine_chunks);
469 chunk4 = magazine_chain_pop_head (&magazine_chunks);
470 chunk4->next = magazine_chunks;
471 chunk3->next = chunk4;
472 chunk2->next = chunk3;
473 chunk1->next = chunk2;
477 /* access the first 3 fields of a specially prepared magazine chain */
478 #define magazine_chain_prev(mc) ((mc)->data)
479 #define magazine_chain_stamp(mc) ((mc)->next->data)
480 #define magazine_chain_uint_stamp(mc) GPOINTER_TO_UINT ((mc)->next->data)
481 #define magazine_chain_next(mc) ((mc)->next->next->data)
482 #define magazine_chain_count(mc) ((mc)->next->next->next->data)
485 magazine_cache_trim (Allocator *allocator,
489 /* g_mutex_lock (allocator->mutex); done by caller */
490 /* trim magazine cache from tail */
491 ChunkLink *current = magazine_chain_prev (allocator->magazines[ix]);
492 ChunkLink *trash = NULL;
493 while (allocator->config.always_free ||
494 ABS (stamp - magazine_chain_uint_stamp (current)) > allocator->config.working_set_msecs)
497 ChunkLink *prev = magazine_chain_prev (current);
498 ChunkLink *next = magazine_chain_next (current);
499 magazine_chain_next (prev) = next;
500 magazine_chain_prev (next) = prev;
501 /* clear special fields, put on trash stack */
502 magazine_chain_next (current) = NULL;
503 magazine_chain_count (current) = NULL;
504 magazine_chain_stamp (current) = NULL;
505 magazine_chain_prev (current) = trash;
507 /* fixup list head if required */
508 if (current == allocator->magazines[ix])
510 allocator->magazines[ix] = NULL;
515 g_mutex_unlock (allocator->magazine_mutex);
519 const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
520 g_mutex_lock (allocator->slab_mutex);
524 trash = magazine_chain_prev (current);
525 magazine_chain_prev (current) = NULL; /* clear special field */
528 ChunkLink *chunk = magazine_chain_pop_head (¤t);
529 slab_allocator_free_chunk (chunk_size, chunk);
532 g_mutex_unlock (allocator->slab_mutex);
537 magazine_cache_push_magazine (guint ix,
538 ChunkLink *magazine_chunks,
539 gsize count) /* must be >= MIN_MAGAZINE_SIZE */
541 ChunkLink *current = magazine_chain_prepare_fields (magazine_chunks);
542 ChunkLink *next, *prev;
543 g_mutex_lock (allocator->magazine_mutex);
544 /* add magazine at head */
545 next = allocator->magazines[ix];
547 prev = magazine_chain_prev (next);
549 next = prev = current;
550 magazine_chain_next (prev) = current;
551 magazine_chain_prev (next) = current;
552 magazine_chain_prev (current) = prev;
553 magazine_chain_next (current) = next;
554 magazine_chain_count (current) = (gpointer) count;
556 magazine_cache_update_stamp();
557 magazine_chain_stamp (current) = GUINT_TO_POINTER (allocator->last_stamp);
558 allocator->magazines[ix] = current;
559 /* free old magazines beyond a certain threshold */
560 magazine_cache_trim (allocator, ix, allocator->last_stamp);
561 /* g_mutex_unlock (allocator->mutex); was done by magazine_cache_trim() */
565 magazine_cache_pop_magazine (guint ix,
568 g_mutex_lock_a (allocator->magazine_mutex, &allocator->contention_counters[ix]);
569 if (!allocator->magazines[ix])
571 guint magazine_threshold = allocator_get_magazine_threshold (allocator, ix);
572 gsize i, chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
573 ChunkLink *current = NULL;
574 g_mutex_unlock (allocator->magazine_mutex);
575 g_mutex_lock (allocator->slab_mutex);
576 for (i = 0; i < magazine_threshold; i++)
578 ChunkLink *chunk = slab_allocator_alloc_chunk (chunk_size);
580 chunk->next = current;
583 g_mutex_unlock (allocator->slab_mutex);
589 ChunkLink *current = allocator->magazines[ix];
590 ChunkLink *prev = magazine_chain_prev (current);
591 ChunkLink *next = magazine_chain_next (current);
593 magazine_chain_next (prev) = next;
594 magazine_chain_prev (next) = prev;
595 allocator->magazines[ix] = next == current ? NULL : next;
596 g_mutex_unlock (allocator->magazine_mutex);
597 /* clear special fields and hand out */
598 *countp = (gsize) magazine_chain_count (current);
599 magazine_chain_prev (current) = NULL;
600 magazine_chain_next (current) = NULL;
601 magazine_chain_count (current) = NULL;
602 magazine_chain_stamp (current) = NULL;
607 /* --- thread magazines --- */
609 private_thread_memory_cleanup (gpointer data)
611 ThreadMemory *tmem = data;
612 const guint n_magazines = MAX_SLAB_INDEX (allocator);
614 for (ix = 0; ix < n_magazines; ix++)
618 mags[0] = &tmem->magazine1[ix];
619 mags[1] = &tmem->magazine2[ix];
620 for (j = 0; j < 2; j++)
622 Magazine *mag = mags[j];
623 if (mag->count >= MIN_MAGAZINE_SIZE)
624 magazine_cache_push_magazine (ix, mag->chunks, mag->count);
627 const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
628 g_mutex_lock (allocator->slab_mutex);
631 ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
632 slab_allocator_free_chunk (chunk_size, chunk);
634 g_mutex_unlock (allocator->slab_mutex);
642 thread_memory_magazine1_reload (ThreadMemory *tmem,
645 Magazine *mag = &tmem->magazine1[ix];
646 g_assert (mag->chunks == NULL); /* ensure that we may reset mag->count */
648 mag->chunks = magazine_cache_pop_magazine (ix, &mag->count);
652 thread_memory_magazine2_unload (ThreadMemory *tmem,
655 Magazine *mag = &tmem->magazine2[ix];
656 magazine_cache_push_magazine (ix, mag->chunks, mag->count);
662 thread_memory_swap_magazines (ThreadMemory *tmem,
665 Magazine xmag = tmem->magazine1[ix];
666 tmem->magazine1[ix] = tmem->magazine2[ix];
667 tmem->magazine2[ix] = xmag;
670 static inline gboolean
671 thread_memory_magazine1_is_empty (ThreadMemory *tmem,
674 return tmem->magazine1[ix].chunks == NULL;
677 static inline gboolean
678 thread_memory_magazine2_is_full (ThreadMemory *tmem,
681 return tmem->magazine2[ix].count >= allocator_get_magazine_threshold (allocator, ix);
684 static inline gpointer
685 thread_memory_magazine1_alloc (ThreadMemory *tmem,
688 Magazine *mag = &tmem->magazine1[ix];
689 ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
690 if (G_LIKELY (mag->count > 0))
696 thread_memory_magazine2_free (ThreadMemory *tmem,
700 Magazine *mag = &tmem->magazine2[ix];
701 ChunkLink *chunk = mem;
703 chunk->next = mag->chunks;
708 /* --- API functions --- */
710 g_slice_alloc (gsize mem_size)
715 chunk_size = P2ALIGN (mem_size);
716 acat = allocator_categorize (chunk_size);
717 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
719 ThreadMemory *tmem = thread_memory_from_self();
720 guint ix = SLAB_INDEX (allocator, chunk_size);
721 if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
723 thread_memory_swap_magazines (tmem, ix);
724 if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
725 thread_memory_magazine1_reload (tmem, ix);
727 mem = thread_memory_magazine1_alloc (tmem, ix);
729 else if (acat == 2) /* allocate through slab allocator */
731 g_mutex_lock (allocator->slab_mutex);
732 mem = slab_allocator_alloc_chunk (chunk_size);
733 g_mutex_unlock (allocator->slab_mutex);
735 else /* delegate to system malloc */
736 mem = g_malloc (mem_size);
741 g_slice_alloc0 (gsize mem_size)
743 gpointer mem = g_slice_alloc (mem_size);
745 memset (mem, 0, mem_size);
750 g_slice_free1 (gsize mem_size,
753 gsize chunk_size = P2ALIGN (mem_size);
754 guint acat = allocator_categorize (chunk_size);
755 if (G_UNLIKELY (!mem_block))
757 else if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
759 ThreadMemory *tmem = thread_memory_from_self();
760 guint ix = SLAB_INDEX (allocator, chunk_size);
761 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
763 thread_memory_swap_magazines (tmem, ix);
764 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
765 thread_memory_magazine2_unload (tmem, ix);
767 thread_memory_magazine2_free (tmem, ix, mem_block);
769 else if (acat == 2) /* allocate through slab allocator */
771 g_mutex_lock (allocator->slab_mutex);
772 slab_allocator_free_chunk (chunk_size, mem_block);
773 g_mutex_unlock (allocator->slab_mutex);
775 else /* delegate to system malloc */
780 g_slice_free_chain_with_offset (gsize mem_size,
784 gpointer slice = mem_chain;
785 /* while the thread magazines and the magazine cache are implemented so that
786 * they can easily be extended to allow for free lists containing more free
787 * lists for the first level nodes, which would allow O(1) freeing in this
788 * function, the benefit of such an extension is questionable, because:
789 * - the magazine size counts will become mere lower bounds which confuses
790 * the code adapting to lock contention;
791 * - freeing a single node to the thread magazines is very fast, so this
792 * O(list_length) operation is multiplied by a fairly small factor;
793 * - memory usage histograms on larger applications seem to indicate that
794 * the amount of released multi node lists is negligible in comparison
795 * to single node releases.
796 * - the major performance bottle neck, namely g_private_get() or
797 * g_mutex_lock()/g_mutex_unlock() has already been moved out of the
798 * inner loop for freeing chained slices.
800 gsize chunk_size = P2ALIGN (mem_size);
801 guint acat = allocator_categorize (chunk_size);
802 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
804 ThreadMemory *tmem = thread_memory_from_self();
805 guint ix = SLAB_INDEX (allocator, chunk_size);
808 guint8 *current = slice;
809 slice = *(gpointer*) (current + next_offset);
810 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
812 thread_memory_swap_magazines (tmem, ix);
813 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
814 thread_memory_magazine2_unload (tmem, ix);
816 thread_memory_magazine2_free (tmem, ix, current);
819 else if (acat == 2) /* allocate through slab allocator */
821 g_mutex_lock (allocator->slab_mutex);
824 guint8 *current = slice;
825 slice = *(gpointer*) (current + next_offset);
826 slab_allocator_free_chunk (chunk_size, current);
828 g_mutex_unlock (allocator->slab_mutex);
830 else /* delegate to system malloc */
833 guint8 *current = slice;
834 slice = *(gpointer*) (current + next_offset);
839 /* --- single page allocator --- */
841 allocator_slab_stack_push (Allocator *allocator,
845 /* insert slab at slab ring head */
846 if (!allocator->slab_stack[ix])
853 SlabInfo *next = allocator->slab_stack[ix], *prev = next->prev;
859 allocator->slab_stack[ix] = sinfo;
863 allocator_add_slab (Allocator *allocator,
869 gsize addr, padding, n_chunks, color = 0;
870 gsize page_size = SLAB_PAGE_SIZE (allocator, chunk_size);
871 /* allocate 1 page for the chunks and the slab */
872 gpointer aligned_memory = allocator_memalign (page_size, page_size - NATIVE_MALLOC_PADDING);
873 guint8 *mem = aligned_memory;
876 g_error ("%s: failed to allocate %lu bytes: %s", "GSlicedMemory", (gulong) (page_size - NATIVE_MALLOC_PADDING), g_strerror (errno));
877 /* mask page adress */
878 addr = ((gsize) mem / page_size) * page_size;
879 /* assert alignment */
880 g_assert (aligned_memory == (gpointer) addr);
881 /* basic slab info setup */
882 sinfo = (SlabInfo*) (mem + page_size - SLAB_INFO_SIZE);
883 sinfo->n_allocated = 0;
884 sinfo->chunks = NULL;
885 /* figure cache colorization */
886 n_chunks = ((guint8*) sinfo - mem) / chunk_size;
887 padding = ((guint8*) sinfo - mem) - n_chunks * chunk_size;
890 color = (allocator->color_accu * P2ALIGNMENT) % padding;
891 allocator->color_accu += 1; /* alternatively: + 0x7fffffff */
893 /* add chunks to free list */
894 chunk = (ChunkLink*) (mem + color);
895 sinfo->chunks = chunk;
896 for (i = 0; i < n_chunks - 1; i++)
898 chunk->next = (ChunkLink*) ((guint8*) chunk + chunk_size);
901 chunk->next = NULL; /* last chunk */
902 /* add slab to slab ring */
903 allocator_slab_stack_push (allocator, ix, sinfo);
907 slab_allocator_alloc_chunk (gsize chunk_size)
910 guint ix = SLAB_INDEX (allocator, chunk_size);
911 /* ensure non-empty slab */
912 if (!allocator->slab_stack[ix] || !allocator->slab_stack[ix]->chunks)
913 allocator_add_slab (allocator, ix, chunk_size);
915 chunk = allocator->slab_stack[ix]->chunks;
916 allocator->slab_stack[ix]->chunks = chunk->next;
917 allocator->slab_stack[ix]->n_allocated++;
918 /* rotate empty slabs */
919 if (!allocator->slab_stack[ix]->chunks)
920 allocator->slab_stack[ix] = allocator->slab_stack[ix]->next;
925 slab_allocator_free_chunk (gsize chunk_size,
930 guint ix = SLAB_INDEX (allocator, chunk_size);
931 gsize page_size = SLAB_PAGE_SIZE (allocator, chunk_size);
932 gsize addr = ((gsize) mem / page_size) * page_size;
933 /* mask page adress */
934 guint8 *page = (guint8*) addr;
935 SlabInfo *sinfo = (SlabInfo*) (page + page_size - SLAB_INFO_SIZE);
936 /* assert valid chunk count */
937 g_assert (sinfo->n_allocated > 0);
938 /* add chunk to free list */
939 was_empty = sinfo->chunks == NULL;
940 chunk = (ChunkLink*) mem;
941 chunk->next = sinfo->chunks;
942 sinfo->chunks = chunk;
943 sinfo->n_allocated--;
944 /* keep slab ring partially sorted, empty slabs at end */
948 SlabInfo *next = sinfo->next, *prev = sinfo->prev;
951 if (allocator->slab_stack[ix] == sinfo)
952 allocator->slab_stack[ix] = next == sinfo ? NULL : next;
953 /* insert slab at head */
954 allocator_slab_stack_push (allocator, ix, sinfo);
956 /* eagerly free complete unused slabs */
957 if (!sinfo->n_allocated)
960 SlabInfo *next = sinfo->next, *prev = sinfo->prev;
963 if (allocator->slab_stack[ix] == sinfo)
964 allocator->slab_stack[ix] = next == sinfo ? NULL : next;
966 allocator_memfree (page_size, page);
970 /* --- memalign implementation --- */
971 #include <malloc.h> /* memalign() */
974 * define HAVE_POSIX_MEMALIGN 1 // if free(posix_memalign(3)) works, <stdlib.h>
975 * define HAVE_MEMALIGN 1 // if free(memalign(3)) works, <malloc.h>
976 * define HAVE_VALLOC 1 // if free(valloc(3)) works, <stdlib.h> or <malloc.h>
977 * if none is provided, we implement malloc(3)-based alloc-only page alignment
980 #if !(HAVE_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC)
981 static GTrashStack *compat_valloc_trash = NULL;
985 allocator_memalign (gsize alignment,
988 gpointer aligned_memory = NULL;
990 #if HAVE_POSIX_MEMALIGN
991 err = posix_memalign (&aligned_memory, alignment, memsize);
994 aligned_memory = memalign (alignment, memsize);
998 aligned_memory = valloc (memsize);
1001 /* simplistic non-freeing page allocator */
1002 g_assert (alignment == sys_page_size);
1003 g_assert (memsize <= sys_page_size);
1004 if (!compat_valloc_trash)
1006 const guint n_pages = 16;
1007 guint8 *mem = malloc (n_pages * sys_page_size);
1012 guint8 *amem = (guint8*) ALIGN ((gsize) mem, sys_page_size);
1014 i--; /* mem wasn't page aligned */
1016 g_trash_stack_push (&compat_valloc_trash, amem + i * sys_page_size);
1019 aligned_memory = g_trash_stack_pop (&compat_valloc_trash);
1021 if (!aligned_memory)
1023 return aligned_memory;
1027 allocator_memfree (gsize memsize,
1030 #if HAVE_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC
1033 g_assert (memsize <= sys_page_size);
1034 g_trash_stack_push (&compat_valloc_trash, mem);
1038 #define __G_SLICE_C__
1039 #include "galiasdef.c"