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() */
25 #include "gmem.h" /* gslice.h */
26 #include "gthreadinit.h"
30 #include <unistd.h> /* sysconf() */
36 /* the GSlice allocator is split up into 4 layers, roughly modelled after the slab
37 * allocator and magazine extensions as outlined in:
38 * + [Bonwick94] Jeff Bonwick, The slab allocator: An object-caching kernel
39 * memory allocator. USENIX 1994, http://citeseer.ist.psu.edu/bonwick94slab.html
40 * + [Bonwick01] Bonwick and Jonathan Adams, Magazines and vmem: Extending the
41 * slab allocator to many cpu's and arbitrary resources.
42 * USENIX 2001, http://citeseer.ist.psu.edu/bonwick01magazines.html
44 * - the thread magazines. for each (aligned) chunk size, a magazine (a list)
45 * of recently freed and soon to be allocated chunks is maintained per thread.
46 * this way, most alloc/free requests can be quickly satisfied from per-thread
47 * free lists which only require one g_private_get() call to retrive the
49 * - the magazine cache. allocating and freeing chunks to/from threads only
50 * occours at magazine sizes from a global depot of magazines. the depot
51 * maintaines a 15 second working set of allocated magazines, so full
52 * magazines are not allocated and released too often.
53 * the chunk size dependent magazine sizes automatically adapt (within limits,
54 * see [3]) to lock contention to properly scale performance across a variety
56 * - the slab allocator. this allocator allocates slabs (blocks of memory) close
57 * to the system page size or multiples thereof which have to be page aligned.
58 * the blocks are divided into smaller chunks which are used to satisfy
59 * allocations from the upper layers. the space provided by the reminder of
60 * the chunk size division is used for cache colorization (random distribution
61 * of chunk addresses) to improve processor cache utilization. multiple slabs
62 * with the same chunk size are kept in a partially sorted ring to allow O(1)
63 * freeing and allocation of chunks (as long as the allocation of an entirely
64 * new slab can be avoided).
65 * - the page allocator. on most modern systems, posix_memalign(3) or
66 * memalign(3) should be available, so this is used to allocate blocks with
67 * system page size based alignments and sizes or multiples thereof.
68 * if no memalign variant is provided, valloc() is used instead and
69 * block sizes are limited to the system page size (no multiples thereof).
70 * as a fallback, on system without even valloc(), a malloc(3)-based page
71 * allocator with alloc-only behaviour is used.
74 * [1] some systems memalign(3) implementations may rely on boundary tagging for
75 * the handed out memory chunks. to avoid excessive page-wise fragmentation,
76 * we reserve 2 * sizeof (void*) per block size for the systems memalign(3),
77 * specified in NATIVE_MALLOC_PADDING.
78 * [2] using the slab allocator alone already provides for a fast and efficient
79 * allocator, it doesn't properly scale beyond single-threaded uses though.
80 * also, the slab allocator implements eager free(3)-ing, i.e. does not
81 * provide any form of caching or working set maintenance. so if used alone,
82 * it's vulnerable to trashing for sequences of balanced (alloc, free) pairs
83 * at certain thresholds.
84 * [3] magazine sizes are bound by an implementation specific minimum size and
85 * a chunk size specific maximum to limit magazine storage sizes to roughly
87 * [4] allocating ca. 8 chunks per block/page keeps a good balance between
88 * external and internal fragmentation (<= 12.5%). [Bonwick94]
91 /* --- macros and constants --- */
92 #define LARGEALIGNMENT (256)
93 #define P2ALIGNMENT (2 * sizeof (gsize)) /* fits 2 pointers (assumed to be 2 * GLIB_SIZEOF_SIZE_T below) */
94 #define ALIGN(size, base) ((base) * (gsize) (((size) + (base) - 1) / (base)))
95 #define NATIVE_MALLOC_PADDING P2ALIGNMENT /* per-page padding left for native malloc(3) see [1] */
96 #define SLAB_INFO_SIZE P2ALIGN (sizeof (SlabInfo) + NATIVE_MALLOC_PADDING)
97 #define MAX_MAGAZINE_SIZE (256) /* see [3] and allocator_get_magazine_threshold() for this */
98 #define MIN_MAGAZINE_SIZE (4)
99 #define MAX_STAMP_COUNTER (7) /* distributes the load of gettimeofday() */
100 #define MAX_SLAB_CHUNK_SIZE(al) (((al)->max_page_size - SLAB_INFO_SIZE) / 8) /* we want at last 8 chunks per page, see [4] */
101 #define MAX_SLAB_INDEX(al) (SLAB_INDEX (al, MAX_SLAB_CHUNK_SIZE (al)) + 1)
102 #define SLAB_INDEX(al, asize) ((asize) / P2ALIGNMENT - 1) /* asize must be P2ALIGNMENT aligned */
103 #define SLAB_CHUNK_SIZE(al, ix) (((ix) + 1) * P2ALIGNMENT)
104 #define SLAB_BPAGE_SIZE(al,csz) (8 * (csz) + SLAB_INFO_SIZE)
106 /* optimized version of ALIGN (size, P2ALIGNMENT) */
107 #if GLIB_SIZEOF_SIZE_T * 2 == 8 /* P2ALIGNMENT */
108 #define P2ALIGN(size) (((size) + 0x7) & ~(gsize) 0x7)
109 #elif GLIB_SIZEOF_SIZE_T * 2 == 16 /* P2ALIGNMENT */
110 #define P2ALIGN(size) (((size) + 0xf) & ~(gsize) 0xf)
112 #define P2ALIGN(size) ALIGN (size, P2ALIGNMENT)
115 /* special helpers to avoid gmessage.c dependency */
116 static void mem_error (const char *format, ...) G_GNUC_PRINTF (1,2);
117 #define mem_assert(cond) do { if (G_LIKELY (cond)) ; else mem_error ("assertion failed: %s", #cond); } while (0)
119 /* --- structures --- */
120 typedef struct _ChunkLink ChunkLink;
121 typedef struct _SlabInfo SlabInfo;
122 typedef struct _CachedMagazine CachedMagazine;
130 SlabInfo *next, *prev;
134 gsize count; /* approximative chunks list length */
137 Magazine *magazine1; /* array of MAX_SLAB_INDEX (allocator) */
138 Magazine *magazine2; /* array of MAX_SLAB_INDEX (allocator) */
141 gboolean always_malloc;
142 gboolean bypass_magazines;
143 gsize working_set_msecs;
144 guint color_increment;
147 /* const after initialization */
148 gsize min_page_size, max_page_size;
150 gsize max_slab_chunk_size_for_magazine_cache;
152 GMutex *magazine_mutex;
153 ChunkLink **magazines; /* array of MAX_SLAB_INDEX (allocator) */
154 guint *contention_counters; /* array of MAX_SLAB_INDEX (allocator) */
160 SlabInfo **slab_stack; /* array of MAX_SLAB_INDEX (allocator) */
164 /* --- prototypes --- */
165 static gpointer slab_allocator_alloc_chunk (gsize chunk_size);
166 static void slab_allocator_free_chunk (gsize chunk_size,
168 static void private_thread_memory_cleanup (gpointer data);
169 static gpointer allocator_memalign (gsize alignment,
171 static void allocator_memfree (gsize memsize,
173 static inline void magazine_cache_update_stamp (void);
174 static inline gsize allocator_get_magazine_threshold (Allocator *allocator,
177 /* --- variables --- */
178 static GPrivate *private_thread_memory = NULL;
179 static gsize sys_page_size = 0;
180 static Allocator allocator[1] = { { 0, }, };
181 static SliceConfig slice_config = {
182 FALSE, /* always_malloc */
183 FALSE, /* bypass_magazines */
184 15 * 1000, /* working_set_msecs */
185 1, /* color increment, alt: 0x7fffffff */
188 /* --- auxillary funcitons --- */
190 g_slice_set_config (GSliceConfig ckey,
193 g_return_if_fail (sys_page_size == 0);
196 case G_SLICE_CONFIG_ALWAYS_MALLOC:
197 slice_config.always_malloc = value != 0;
199 case G_SLICE_CONFIG_BYPASS_MAGAZINES:
200 slice_config.bypass_magazines = value != 0;
202 case G_SLICE_CONFIG_WORKING_SET_MSECS:
203 slice_config.working_set_msecs = value;
205 case G_SLICE_CONFIG_COLOR_INCREMENT:
206 slice_config.color_increment = value;
212 g_slice_get_config (GSliceConfig ckey)
216 case G_SLICE_CONFIG_ALWAYS_MALLOC:
217 return slice_config.always_malloc;
218 case G_SLICE_CONFIG_BYPASS_MAGAZINES:
219 return slice_config.bypass_magazines;
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);
224 case G_SLICE_CONFIG_COLOR_INCREMENT:
225 return slice_config.color_increment;
232 g_slice_get_config_state (GSliceConfig ckey,
237 g_return_val_if_fail (n_values != NULL, NULL);
242 case G_SLICE_CONFIG_CONTENTION_COUNTER:
243 array[i++] = SLAB_CHUNK_SIZE (allocator, address);
244 array[i++] = allocator->contention_counters[address];
245 array[i++] = allocator_get_magazine_threshold (allocator, address);
247 return g_memdup (array, sizeof (array[0]) * *n_values);
254 g_slice_init_nomessage (void)
256 /* we may not use g_error() or friends here */
257 mem_assert (sys_page_size == 0);
258 mem_assert (MIN_MAGAZINE_SIZE >= 4);
262 SYSTEM_INFO system_info;
263 GetSystemInfo (&system_info);
264 sys_page_size = system_info.dwPageSize;
267 sys_page_size = sysconf (_SC_PAGESIZE); /* = sysconf (_SC_PAGE_SIZE); = getpagesize(); */
269 mem_assert (sys_page_size >= 2 * LARGEALIGNMENT);
270 mem_assert ((sys_page_size & (sys_page_size - 1)) == 0);
271 allocator->config = slice_config;
272 allocator->min_page_size = sys_page_size;
273 #if HAVE_POSIX_MEMALIGN || HAVE_MEMALIGN
274 /* allow allocation of pages up to 8KB (with 8KB alignment).
275 * this is useful because many medium to large sized structures
276 * fit less than 8 times (see [4]) into 4KB pages.
277 * we allow very small page sizes here, to reduce wastage in
278 * threads if only small allocations are required (this does
279 * bear the risk of incresing allocation times and fragmentation
282 allocator->min_page_size = MAX (allocator->min_page_size, 4096);
283 allocator->max_page_size = MAX (allocator->min_page_size, 8192);
284 allocator->min_page_size = MIN (allocator->min_page_size, 128);
286 /* we can only align to system page size */
287 allocator->max_page_size = sys_page_size;
289 allocator->magazine_mutex = NULL; /* _g_slice_thread_init_nomessage() */
290 allocator->magazines = g_new0 (ChunkLink*, MAX_SLAB_INDEX (allocator));
291 allocator->contention_counters = g_new0 (guint, MAX_SLAB_INDEX (allocator));
292 allocator->mutex_counter = 0;
293 allocator->stamp_counter = MAX_STAMP_COUNTER; /* force initial update */
294 allocator->last_stamp = 0;
295 allocator->slab_mutex = NULL; /* _g_slice_thread_init_nomessage() */
296 allocator->slab_stack = g_new0 (SlabInfo*, MAX_SLAB_INDEX (allocator));
297 allocator->color_accu = 0;
298 magazine_cache_update_stamp();
299 /* values cached for performance reasons */
300 allocator->max_slab_chunk_size_for_magazine_cache = MAX_SLAB_CHUNK_SIZE (allocator);
301 if (allocator->config.always_malloc || allocator->config.bypass_magazines)
302 allocator->max_slab_chunk_size_for_magazine_cache = 0; /* non-optimized cases */
306 allocator_categorize (gsize aligned_chunk_size)
308 /* speed up the likely path */
309 if (G_LIKELY (aligned_chunk_size && aligned_chunk_size <= allocator->max_slab_chunk_size_for_magazine_cache))
310 return 1; /* use magazine cache */
312 /* the above will fail (max_slab_chunk_size_for_magazine_cache == 0) if the
313 * allocator is still uninitialized, or if we are not configured to use the
317 g_slice_init_nomessage ();
318 if (!allocator->config.always_malloc &&
319 aligned_chunk_size &&
320 aligned_chunk_size <= MAX_SLAB_CHUNK_SIZE (allocator))
322 if (allocator->config.bypass_magazines)
323 return 2; /* use slab allocator, see [2] */
324 return 1; /* use magazine cache */
326 return 0; /* use malloc() */
330 _g_slice_thread_init_nomessage (void)
332 /* we may not use g_error() or friends here */
334 g_slice_init_nomessage();
335 private_thread_memory = g_private_new (private_thread_memory_cleanup);
336 allocator->magazine_mutex = g_mutex_new();
337 allocator->slab_mutex = g_mutex_new();
341 g_mutex_lock_a (GMutex *mutex,
342 guint *contention_counter)
344 gboolean contention = FALSE;
345 if (!g_mutex_trylock (mutex))
347 g_mutex_lock (mutex);
352 allocator->mutex_counter++;
353 if (allocator->mutex_counter >= 1) /* quickly adapt to contention */
355 allocator->mutex_counter = 0;
356 *contention_counter = MIN (*contention_counter + 1, MAX_MAGAZINE_SIZE);
359 else /* !contention */
361 allocator->mutex_counter--;
362 if (allocator->mutex_counter < -11) /* moderately recover magazine sizes */
364 allocator->mutex_counter = 0;
365 *contention_counter = MAX (*contention_counter, 1) - 1;
370 static inline ThreadMemory*
371 thread_memory_from_self (void)
373 ThreadMemory *tmem = g_private_get (private_thread_memory);
374 if (G_UNLIKELY (!tmem))
376 const guint n_magazines = MAX_SLAB_INDEX (allocator);
377 tmem = g_malloc0 (sizeof (ThreadMemory) + sizeof (Magazine) * 2 * n_magazines);
378 tmem->magazine1 = (Magazine*) (tmem + 1);
379 tmem->magazine2 = &tmem->magazine1[n_magazines];
380 g_private_set (private_thread_memory, tmem);
385 static inline ChunkLink*
386 magazine_chain_pop_head (ChunkLink **magazine_chunks)
388 /* magazine chains are linked via ChunkLink->next.
389 * each ChunkLink->data of the toplevel chain may point to a subchain,
390 * linked via ChunkLink->next. ChunkLink->data of the subchains just
391 * contains uninitialized junk.
393 ChunkLink *chunk = (*magazine_chunks)->data;
394 if (G_UNLIKELY (chunk))
396 /* allocating from freed list */
397 (*magazine_chunks)->data = chunk->next;
401 chunk = *magazine_chunks;
402 *magazine_chunks = chunk->next;
407 #if 0 /* useful for debugging */
409 magazine_count (ChunkLink *head)
416 ChunkLink *child = head->data;
418 for (child = head->data; child; child = child->next)
427 allocator_get_magazine_threshold (Allocator *allocator,
430 /* the magazine size calculated here has a lower bound of MIN_MAGAZINE_SIZE,
431 * which is required by the implementation. also, for moderately sized chunks
432 * (say >= 64 bytes), magazine sizes shouldn't be much smaller then the number
433 * of chunks available per page/2 to avoid excessive traffic in the magazine
434 * cache for small to medium sized structures.
435 * the upper bound of the magazine size is effectively provided by
436 * MAX_MAGAZINE_SIZE. for larger chunks, this number is scaled down so that
437 * the content of a single magazine doesn't exceed ca. 16KB.
439 gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
440 guint threshold = MAX (MIN_MAGAZINE_SIZE, allocator->max_page_size / MAX (5 * chunk_size, 5 * 32));
441 guint contention_counter = allocator->contention_counters[ix];
442 if (G_UNLIKELY (contention_counter)) /* single CPU bias */
444 /* adapt contention counter thresholds to chunk sizes */
445 contention_counter = contention_counter * 64 / chunk_size;
446 threshold = MAX (threshold, contention_counter);
451 /* --- magazine cache --- */
453 magazine_cache_update_stamp (void)
455 if (allocator->stamp_counter >= MAX_STAMP_COUNTER)
458 g_get_current_time (&tv);
459 allocator->last_stamp = tv.tv_sec * 1000 + tv.tv_usec / 1000; /* milli seconds */
460 allocator->stamp_counter = 0;
463 allocator->stamp_counter++;
466 static inline ChunkLink*
467 magazine_chain_prepare_fields (ChunkLink *magazine_chunks)
473 /* checked upon initialization: mem_assert (MIN_MAGAZINE_SIZE >= 4); */
474 /* ensure a magazine with at least 4 unused data pointers */
475 chunk1 = magazine_chain_pop_head (&magazine_chunks);
476 chunk2 = magazine_chain_pop_head (&magazine_chunks);
477 chunk3 = magazine_chain_pop_head (&magazine_chunks);
478 chunk4 = magazine_chain_pop_head (&magazine_chunks);
479 chunk4->next = magazine_chunks;
480 chunk3->next = chunk4;
481 chunk2->next = chunk3;
482 chunk1->next = chunk2;
486 /* access the first 3 fields of a specially prepared magazine chain */
487 #define magazine_chain_prev(mc) ((mc)->data)
488 #define magazine_chain_stamp(mc) ((mc)->next->data)
489 #define magazine_chain_uint_stamp(mc) GPOINTER_TO_UINT ((mc)->next->data)
490 #define magazine_chain_next(mc) ((mc)->next->next->data)
491 #define magazine_chain_count(mc) ((mc)->next->next->next->data)
494 magazine_cache_trim (Allocator *allocator,
498 /* g_mutex_lock (allocator->mutex); done by caller */
499 /* trim magazine cache from tail */
500 ChunkLink *current = magazine_chain_prev (allocator->magazines[ix]);
501 ChunkLink *trash = NULL;
502 while (ABS (stamp - magazine_chain_uint_stamp (current)) >= allocator->config.working_set_msecs)
505 ChunkLink *prev = magazine_chain_prev (current);
506 ChunkLink *next = magazine_chain_next (current);
507 magazine_chain_next (prev) = next;
508 magazine_chain_prev (next) = prev;
509 /* clear special fields, put on trash stack */
510 magazine_chain_next (current) = NULL;
511 magazine_chain_count (current) = NULL;
512 magazine_chain_stamp (current) = NULL;
513 magazine_chain_prev (current) = trash;
515 /* fixup list head if required */
516 if (current == allocator->magazines[ix])
518 allocator->magazines[ix] = NULL;
523 g_mutex_unlock (allocator->magazine_mutex);
527 const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
528 g_mutex_lock (allocator->slab_mutex);
532 trash = magazine_chain_prev (current);
533 magazine_chain_prev (current) = NULL; /* clear special field */
536 ChunkLink *chunk = magazine_chain_pop_head (¤t);
537 slab_allocator_free_chunk (chunk_size, chunk);
540 g_mutex_unlock (allocator->slab_mutex);
545 magazine_cache_push_magazine (guint ix,
546 ChunkLink *magazine_chunks,
547 gsize count) /* must be >= MIN_MAGAZINE_SIZE */
549 ChunkLink *current = magazine_chain_prepare_fields (magazine_chunks);
550 ChunkLink *next, *prev;
551 g_mutex_lock (allocator->magazine_mutex);
552 /* add magazine at head */
553 next = allocator->magazines[ix];
555 prev = magazine_chain_prev (next);
557 next = prev = current;
558 magazine_chain_next (prev) = current;
559 magazine_chain_prev (next) = current;
560 magazine_chain_prev (current) = prev;
561 magazine_chain_next (current) = next;
562 magazine_chain_count (current) = (gpointer) count;
564 magazine_cache_update_stamp();
565 magazine_chain_stamp (current) = GUINT_TO_POINTER (allocator->last_stamp);
566 allocator->magazines[ix] = current;
567 /* free old magazines beyond a certain threshold */
568 magazine_cache_trim (allocator, ix, allocator->last_stamp);
569 /* g_mutex_unlock (allocator->mutex); was done by magazine_cache_trim() */
573 magazine_cache_pop_magazine (guint ix,
576 g_mutex_lock_a (allocator->magazine_mutex, &allocator->contention_counters[ix]);
577 if (!allocator->magazines[ix])
579 guint magazine_threshold = allocator_get_magazine_threshold (allocator, ix);
580 gsize i, chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
581 ChunkLink *current = NULL;
582 g_mutex_unlock (allocator->magazine_mutex);
583 g_mutex_lock (allocator->slab_mutex);
584 for (i = 0; i < magazine_threshold; i++)
586 ChunkLink *chunk = slab_allocator_alloc_chunk (chunk_size);
588 chunk->next = current;
591 g_mutex_unlock (allocator->slab_mutex);
597 ChunkLink *current = allocator->magazines[ix];
598 ChunkLink *prev = magazine_chain_prev (current);
599 ChunkLink *next = magazine_chain_next (current);
601 magazine_chain_next (prev) = next;
602 magazine_chain_prev (next) = prev;
603 allocator->magazines[ix] = next == current ? NULL : next;
604 g_mutex_unlock (allocator->magazine_mutex);
605 /* clear special fields and hand out */
606 *countp = (gsize) magazine_chain_count (current);
607 magazine_chain_prev (current) = NULL;
608 magazine_chain_next (current) = NULL;
609 magazine_chain_count (current) = NULL;
610 magazine_chain_stamp (current) = NULL;
615 /* --- thread magazines --- */
617 private_thread_memory_cleanup (gpointer data)
619 ThreadMemory *tmem = data;
620 const guint n_magazines = MAX_SLAB_INDEX (allocator);
622 for (ix = 0; ix < n_magazines; ix++)
626 mags[0] = &tmem->magazine1[ix];
627 mags[1] = &tmem->magazine2[ix];
628 for (j = 0; j < 2; j++)
630 Magazine *mag = mags[j];
631 if (mag->count >= MIN_MAGAZINE_SIZE)
632 magazine_cache_push_magazine (ix, mag->chunks, mag->count);
635 const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
636 g_mutex_lock (allocator->slab_mutex);
639 ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
640 slab_allocator_free_chunk (chunk_size, chunk);
642 g_mutex_unlock (allocator->slab_mutex);
650 thread_memory_magazine1_reload (ThreadMemory *tmem,
653 Magazine *mag = &tmem->magazine1[ix];
654 mem_assert (mag->chunks == NULL); /* ensure that we may reset mag->count */
656 mag->chunks = magazine_cache_pop_magazine (ix, &mag->count);
660 thread_memory_magazine2_unload (ThreadMemory *tmem,
663 Magazine *mag = &tmem->magazine2[ix];
664 magazine_cache_push_magazine (ix, mag->chunks, mag->count);
670 thread_memory_swap_magazines (ThreadMemory *tmem,
673 Magazine xmag = tmem->magazine1[ix];
674 tmem->magazine1[ix] = tmem->magazine2[ix];
675 tmem->magazine2[ix] = xmag;
678 static inline gboolean
679 thread_memory_magazine1_is_empty (ThreadMemory *tmem,
682 return tmem->magazine1[ix].chunks == NULL;
685 static inline gboolean
686 thread_memory_magazine2_is_full (ThreadMemory *tmem,
689 return tmem->magazine2[ix].count >= allocator_get_magazine_threshold (allocator, ix);
692 static inline gpointer
693 thread_memory_magazine1_alloc (ThreadMemory *tmem,
696 Magazine *mag = &tmem->magazine1[ix];
697 ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
698 if (G_LIKELY (mag->count > 0))
704 thread_memory_magazine2_free (ThreadMemory *tmem,
708 Magazine *mag = &tmem->magazine2[ix];
709 ChunkLink *chunk = mem;
711 chunk->next = mag->chunks;
716 /* --- API functions --- */
718 g_slice_alloc (gsize mem_size)
723 chunk_size = P2ALIGN (mem_size);
724 acat = allocator_categorize (chunk_size);
725 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
727 ThreadMemory *tmem = thread_memory_from_self();
728 guint ix = SLAB_INDEX (allocator, chunk_size);
729 if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
731 thread_memory_swap_magazines (tmem, ix);
732 if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
733 thread_memory_magazine1_reload (tmem, ix);
735 mem = thread_memory_magazine1_alloc (tmem, ix);
737 else if (acat == 2) /* allocate through slab allocator */
739 g_mutex_lock (allocator->slab_mutex);
740 mem = slab_allocator_alloc_chunk (chunk_size);
741 g_mutex_unlock (allocator->slab_mutex);
743 else /* delegate to system malloc */
744 mem = g_malloc (mem_size);
749 g_slice_alloc0 (gsize mem_size)
751 gpointer mem = g_slice_alloc (mem_size);
753 memset (mem, 0, mem_size);
758 g_slice_free1 (gsize mem_size,
761 gsize chunk_size = P2ALIGN (mem_size);
762 guint acat = allocator_categorize (chunk_size);
763 if (G_UNLIKELY (!mem_block))
765 else if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
767 ThreadMemory *tmem = thread_memory_from_self();
768 guint ix = SLAB_INDEX (allocator, chunk_size);
769 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
771 thread_memory_swap_magazines (tmem, ix);
772 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
773 thread_memory_magazine2_unload (tmem, ix);
775 thread_memory_magazine2_free (tmem, ix, mem_block);
777 else if (acat == 2) /* allocate through slab allocator */
779 g_mutex_lock (allocator->slab_mutex);
780 slab_allocator_free_chunk (chunk_size, mem_block);
781 g_mutex_unlock (allocator->slab_mutex);
783 else /* delegate to system malloc */
788 g_slice_free_chain_with_offset (gsize mem_size,
792 gpointer slice = mem_chain;
793 /* while the thread magazines and the magazine cache are implemented so that
794 * they can easily be extended to allow for free lists containing more free
795 * lists for the first level nodes, which would allow O(1) freeing in this
796 * function, the benefit of such an extension is questionable, because:
797 * - the magazine size counts will become mere lower bounds which confuses
798 * the code adapting to lock contention;
799 * - freeing a single node to the thread magazines is very fast, so this
800 * O(list_length) operation is multiplied by a fairly small factor;
801 * - memory usage histograms on larger applications seem to indicate that
802 * the amount of released multi node lists is negligible in comparison
803 * to single node releases.
804 * - the major performance bottle neck, namely g_private_get() or
805 * g_mutex_lock()/g_mutex_unlock() has already been moved out of the
806 * inner loop for freeing chained slices.
808 gsize chunk_size = P2ALIGN (mem_size);
809 guint acat = allocator_categorize (chunk_size);
810 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
812 ThreadMemory *tmem = thread_memory_from_self();
813 guint ix = SLAB_INDEX (allocator, chunk_size);
816 guint8 *current = slice;
817 slice = *(gpointer*) (current + next_offset);
818 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
820 thread_memory_swap_magazines (tmem, ix);
821 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
822 thread_memory_magazine2_unload (tmem, ix);
824 thread_memory_magazine2_free (tmem, ix, current);
827 else if (acat == 2) /* allocate through slab allocator */
829 g_mutex_lock (allocator->slab_mutex);
832 guint8 *current = slice;
833 slice = *(gpointer*) (current + next_offset);
834 slab_allocator_free_chunk (chunk_size, current);
836 g_mutex_unlock (allocator->slab_mutex);
838 else /* delegate to system malloc */
841 guint8 *current = slice;
842 slice = *(gpointer*) (current + next_offset);
847 /* --- single page allocator --- */
849 allocator_slab_stack_push (Allocator *allocator,
853 /* insert slab at slab ring head */
854 if (!allocator->slab_stack[ix])
861 SlabInfo *next = allocator->slab_stack[ix], *prev = next->prev;
867 allocator->slab_stack[ix] = sinfo;
871 allocator_aligned_page_size (Allocator *allocator,
874 gsize val = 1 << g_bit_storage (n_bytes - 1);
875 val = MAX (val, allocator->min_page_size);
880 allocator_add_slab (Allocator *allocator,
886 gsize addr, padding, n_chunks, color = 0;
887 gsize page_size = allocator_aligned_page_size (allocator, SLAB_BPAGE_SIZE (allocator, chunk_size));
888 /* allocate 1 page for the chunks and the slab */
889 gpointer aligned_memory = allocator_memalign (page_size, page_size - NATIVE_MALLOC_PADDING);
890 guint8 *mem = aligned_memory;
894 const gchar *syserr = "unknown error";
896 syserr = strerror (errno);
898 mem_error ("failed to allocate %u bytes (alignment: %u): %s\n",
899 (guint) (page_size - NATIVE_MALLOC_PADDING), (guint) page_size, syserr);
901 /* mask page adress */
902 addr = ((gsize) mem / page_size) * page_size;
903 /* assert alignment */
904 mem_assert (aligned_memory == (gpointer) addr);
905 /* basic slab info setup */
906 sinfo = (SlabInfo*) (mem + page_size - SLAB_INFO_SIZE);
907 sinfo->n_allocated = 0;
908 sinfo->chunks = NULL;
909 /* figure cache colorization */
910 n_chunks = ((guint8*) sinfo - mem) / chunk_size;
911 padding = ((guint8*) sinfo - mem) - n_chunks * chunk_size;
914 color = (allocator->color_accu * P2ALIGNMENT) % padding;
915 allocator->color_accu += allocator->config.color_increment;
917 /* add chunks to free list */
918 chunk = (ChunkLink*) (mem + color);
919 sinfo->chunks = chunk;
920 for (i = 0; i < n_chunks - 1; i++)
922 chunk->next = (ChunkLink*) ((guint8*) chunk + chunk_size);
925 chunk->next = NULL; /* last chunk */
926 /* add slab to slab ring */
927 allocator_slab_stack_push (allocator, ix, sinfo);
931 slab_allocator_alloc_chunk (gsize chunk_size)
934 guint ix = SLAB_INDEX (allocator, chunk_size);
935 /* ensure non-empty slab */
936 if (!allocator->slab_stack[ix] || !allocator->slab_stack[ix]->chunks)
937 allocator_add_slab (allocator, ix, chunk_size);
939 chunk = allocator->slab_stack[ix]->chunks;
940 allocator->slab_stack[ix]->chunks = chunk->next;
941 allocator->slab_stack[ix]->n_allocated++;
942 /* rotate empty slabs */
943 if (!allocator->slab_stack[ix]->chunks)
944 allocator->slab_stack[ix] = allocator->slab_stack[ix]->next;
949 slab_allocator_free_chunk (gsize chunk_size,
954 guint ix = SLAB_INDEX (allocator, chunk_size);
955 gsize page_size = allocator_aligned_page_size (allocator, SLAB_BPAGE_SIZE (allocator, chunk_size));
956 gsize addr = ((gsize) mem / page_size) * page_size;
957 /* mask page adress */
958 guint8 *page = (guint8*) addr;
959 SlabInfo *sinfo = (SlabInfo*) (page + page_size - SLAB_INFO_SIZE);
960 /* assert valid chunk count */
961 mem_assert (sinfo->n_allocated > 0);
962 /* add chunk to free list */
963 was_empty = sinfo->chunks == NULL;
964 chunk = (ChunkLink*) mem;
965 chunk->next = sinfo->chunks;
966 sinfo->chunks = chunk;
967 sinfo->n_allocated--;
968 /* keep slab ring partially sorted, empty slabs at end */
972 SlabInfo *next = sinfo->next, *prev = sinfo->prev;
975 if (allocator->slab_stack[ix] == sinfo)
976 allocator->slab_stack[ix] = next == sinfo ? NULL : next;
977 /* insert slab at head */
978 allocator_slab_stack_push (allocator, ix, sinfo);
980 /* eagerly free complete unused slabs */
981 if (!sinfo->n_allocated)
984 SlabInfo *next = sinfo->next, *prev = sinfo->prev;
987 if (allocator->slab_stack[ix] == sinfo)
988 allocator->slab_stack[ix] = next == sinfo ? NULL : next;
990 allocator_memfree (page_size, page);
994 /* --- memalign implementation --- */
995 #include <malloc.h> /* memalign() */
998 * define HAVE_POSIX_MEMALIGN 1 // if free(posix_memalign(3)) works, <stdlib.h>
999 * define HAVE_MEMALIGN 1 // if free(memalign(3)) works, <malloc.h>
1000 * define HAVE_VALLOC 1 // if free(valloc(3)) works, <stdlib.h> or <malloc.h>
1001 * if none is provided, we implement malloc(3)-based alloc-only page alignment
1004 #if !(HAVE_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC)
1005 static GTrashStack *compat_valloc_trash = NULL;
1009 allocator_memalign (gsize alignment,
1012 gpointer aligned_memory = NULL;
1014 #if HAVE_POSIX_MEMALIGN
1015 err = posix_memalign (&aligned_memory, alignment, memsize);
1018 aligned_memory = memalign (alignment, memsize);
1022 aligned_memory = valloc (memsize);
1025 /* simplistic non-freeing page allocator */
1026 mem_assert (alignment == sys_page_size);
1027 mem_assert (memsize <= sys_page_size);
1028 if (!compat_valloc_trash)
1030 const guint n_pages = 16;
1031 guint8 *mem = malloc (n_pages * sys_page_size);
1036 guint8 *amem = (guint8*) ALIGN ((gsize) mem, sys_page_size);
1038 i--; /* mem wasn't page aligned */
1040 g_trash_stack_push (&compat_valloc_trash, amem + i * sys_page_size);
1043 aligned_memory = g_trash_stack_pop (&compat_valloc_trash);
1045 if (!aligned_memory)
1047 return aligned_memory;
1051 allocator_memfree (gsize memsize,
1054 #if HAVE_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC
1057 mem_assert (memsize <= sys_page_size);
1058 g_trash_stack_push (&compat_valloc_trash, mem);
1065 mem_error (const char *format,
1070 /* at least, put out "MEMORY-ERROR", in case we segfault during the rest of the function */
1071 fputs ("\n***MEMORY-ERROR***: ", stderr);
1072 pname = g_get_prgname();
1073 fprintf (stderr, "%s[%u]: GSlice: ", pname ? pname : "", getpid());
1074 va_start (args, format);
1075 vfprintf (stderr, format, args);
1077 fputs ("\n", stderr);
1081 #define __G_SLICE_C__
1082 #include "galiasdef.c"