Signal waiting threads, problem noticed by Christian Kellner.
[glib.git] / glib / gslice.c
blob46dd70b709eb294772f467e425d89937967ab197
1 /* GLIB sliced memory - fast concurrent memory chunk allocator
2 * Copyright (C) 2005 Tim Janik
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
19 /* MT safe */
21 #include "config.h"
23 #ifdef HAVE_POSIX_MEMALIGN
24 #define _XOPEN_SOURCE 600 /* posix_memalign() */
25 #endif
26 #include <stdlib.h> /* posix_memalign() */
27 #include <string.h>
28 #include <errno.h>
29 #include "gmem.h" /* gslice.h */
30 #include "gthreadinit.h"
31 #include "galias.h"
32 #include "glib.h"
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h> /* sysconf() */
35 #endif
36 #ifdef G_OS_WIN32
37 #include <windows.h>
38 #include <process.h>
39 #endif
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
48 * the layers are:
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
53 * thread handle.
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
60 * of SMP systems.
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.
78 * NOTES:
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
91 * 16KB.
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)
116 #else
117 #define P2ALIGN(size) ALIGN (size, P2ALIGNMENT)
118 #endif
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;
128 struct _ChunkLink {
129 ChunkLink *next;
130 ChunkLink *data;
132 struct _SlabInfo {
133 ChunkLink *chunks;
134 guint n_allocated;
135 SlabInfo *next, *prev;
137 typedef struct {
138 ChunkLink *chunks;
139 gsize count; /* approximative chunks list length */
140 } Magazine;
141 typedef struct {
142 Magazine *magazine1; /* array of MAX_SLAB_INDEX (allocator) */
143 Magazine *magazine2; /* array of MAX_SLAB_INDEX (allocator) */
144 } ThreadMemory;
145 typedef struct {
146 gboolean always_malloc;
147 gboolean bypass_magazines;
148 gsize working_set_msecs;
149 guint color_increment;
150 } SliceConfig;
151 typedef struct {
152 /* const after initialization */
153 gsize min_page_size, max_page_size;
154 SliceConfig config;
155 gsize max_slab_chunk_size_for_magazine_cache;
156 /* 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) */
160 gint mutex_counter;
161 guint stamp_counter;
162 guint last_stamp;
163 /* slab allocator */
164 GMutex *slab_mutex;
165 SlabInfo **slab_stack; /* array of MAX_SLAB_INDEX (allocator) */
166 guint color_accu;
167 } Allocator;
169 /* --- prototypes --- */
170 static gpointer slab_allocator_alloc_chunk (gsize chunk_size);
171 static void slab_allocator_free_chunk (gsize chunk_size,
172 gpointer mem);
173 static void private_thread_memory_cleanup (gpointer data);
174 static gpointer allocator_memalign (gsize alignment,
175 gsize memsize);
176 static void allocator_memfree (gsize memsize,
177 gpointer mem);
178 static inline void magazine_cache_update_stamp (void);
179 static inline gsize allocator_get_magazine_threshold (Allocator *allocator,
180 guint ix);
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 --- */
194 void
195 g_slice_set_config (GSliceConfig ckey,
196 gint64 value)
198 g_return_if_fail (sys_page_size == 0);
199 switch (ckey)
201 case G_SLICE_CONFIG_ALWAYS_MALLOC:
202 slice_config.always_malloc = value != 0;
203 break;
204 case G_SLICE_CONFIG_BYPASS_MAGAZINES:
205 slice_config.bypass_magazines = value != 0;
206 break;
207 case G_SLICE_CONFIG_WORKING_SET_MSECS:
208 slice_config.working_set_msecs = value;
209 break;
210 case G_SLICE_CONFIG_COLOR_INCREMENT:
211 slice_config.color_increment = value;
212 default: ;
216 gint64
217 g_slice_get_config (GSliceConfig ckey)
219 switch (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;
231 default:
232 return 0;
236 gint64*
237 g_slice_get_config_state (GSliceConfig ckey,
238 gint64 address,
239 guint *n_values)
241 guint i = 0;
242 g_return_val_if_fail (n_values != NULL, NULL);
243 *n_values = 0;
244 switch (ckey)
246 gint64 array[64];
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);
251 *n_values = i;
252 return g_memdup (array, sizeof (array[0]) * *n_values);
253 default:
254 return NULL;
258 static void
259 g_slice_init_nomessage (void)
261 /* we may not use g_error() or friends here */
262 mem_assert (sys_page_size == 0);
263 mem_assert (MIN_MAGAZINE_SIZE >= 4);
265 #ifdef G_OS_WIN32
267 SYSTEM_INFO system_info;
268 GetSystemInfo (&system_info);
269 sys_page_size = system_info.dwPageSize;
271 #else
272 sys_page_size = sysconf (_SC_PAGESIZE); /* = sysconf (_SC_PAGE_SIZE); = getpagesize(); */
273 #endif
274 mem_assert (sys_page_size >= 2 * LARGEALIGNMENT);
275 mem_assert ((sys_page_size & (sys_page_size - 1)) == 0);
276 allocator->config = slice_config;
277 allocator->min_page_size = sys_page_size;
278 #if HAVE_POSIX_MEMALIGN || HAVE_MEMALIGN
279 /* allow allocation of pages up to 8KB (with 8KB alignment).
280 * this is useful because many medium to large sized structures
281 * fit less than 8 times (see [4]) into 4KB pages.
282 * we allow very small page sizes here, to reduce wastage in
283 * threads if only small allocations are required (this does
284 * bear the risk of incresing allocation times and fragmentation
285 * though).
287 allocator->min_page_size = MAX (allocator->min_page_size, 4096);
288 allocator->max_page_size = MAX (allocator->min_page_size, 8192);
289 allocator->min_page_size = MIN (allocator->min_page_size, 128);
290 #else
291 /* we can only align to system page size */
292 allocator->max_page_size = sys_page_size;
293 #endif
294 allocator->magazine_mutex = NULL; /* _g_slice_thread_init_nomessage() */
295 allocator->magazines = g_new0 (ChunkLink*, MAX_SLAB_INDEX (allocator));
296 allocator->contention_counters = g_new0 (guint, MAX_SLAB_INDEX (allocator));
297 allocator->mutex_counter = 0;
298 allocator->stamp_counter = MAX_STAMP_COUNTER; /* force initial update */
299 allocator->last_stamp = 0;
300 allocator->slab_mutex = NULL; /* _g_slice_thread_init_nomessage() */
301 allocator->slab_stack = g_new0 (SlabInfo*, MAX_SLAB_INDEX (allocator));
302 allocator->color_accu = 0;
303 magazine_cache_update_stamp();
304 /* values cached for performance reasons */
305 allocator->max_slab_chunk_size_for_magazine_cache = MAX_SLAB_CHUNK_SIZE (allocator);
306 if (allocator->config.always_malloc || allocator->config.bypass_magazines)
307 allocator->max_slab_chunk_size_for_magazine_cache = 0; /* non-optimized cases */
310 static inline guint
311 allocator_categorize (gsize aligned_chunk_size)
313 /* speed up the likely path */
314 if (G_LIKELY (aligned_chunk_size && aligned_chunk_size <= allocator->max_slab_chunk_size_for_magazine_cache))
315 return 1; /* use magazine cache */
317 /* the above will fail (max_slab_chunk_size_for_magazine_cache == 0) if the
318 * allocator is still uninitialized, or if we are not configured to use the
319 * magazine cache.
321 if (!sys_page_size)
322 g_slice_init_nomessage ();
323 if (!allocator->config.always_malloc &&
324 aligned_chunk_size &&
325 aligned_chunk_size <= MAX_SLAB_CHUNK_SIZE (allocator))
327 if (allocator->config.bypass_magazines)
328 return 2; /* use slab allocator, see [2] */
329 return 1; /* use magazine cache */
331 return 0; /* use malloc() */
334 void
335 _g_slice_thread_init_nomessage (void)
337 /* we may not use g_error() or friends here */
338 if (!sys_page_size)
339 g_slice_init_nomessage();
340 private_thread_memory = g_private_new (private_thread_memory_cleanup);
341 allocator->magazine_mutex = g_mutex_new();
342 allocator->slab_mutex = g_mutex_new();
345 static inline void
346 g_mutex_lock_a (GMutex *mutex,
347 guint *contention_counter)
349 gboolean contention = FALSE;
350 if (!g_mutex_trylock (mutex))
352 g_mutex_lock (mutex);
353 contention = TRUE;
355 if (contention)
357 allocator->mutex_counter++;
358 if (allocator->mutex_counter >= 1) /* quickly adapt to contention */
360 allocator->mutex_counter = 0;
361 *contention_counter = MIN (*contention_counter + 1, MAX_MAGAZINE_SIZE);
364 else /* !contention */
366 allocator->mutex_counter--;
367 if (allocator->mutex_counter < -11) /* moderately recover magazine sizes */
369 allocator->mutex_counter = 0;
370 *contention_counter = MAX (*contention_counter, 1) - 1;
375 static inline ThreadMemory*
376 thread_memory_from_self (void)
378 ThreadMemory *tmem = g_private_get (private_thread_memory);
379 if (G_UNLIKELY (!tmem))
381 const guint n_magazines = MAX_SLAB_INDEX (allocator);
382 tmem = g_malloc0 (sizeof (ThreadMemory) + sizeof (Magazine) * 2 * n_magazines);
383 tmem->magazine1 = (Magazine*) (tmem + 1);
384 tmem->magazine2 = &tmem->magazine1[n_magazines];
385 g_private_set (private_thread_memory, tmem);
387 return tmem;
390 static inline ChunkLink*
391 magazine_chain_pop_head (ChunkLink **magazine_chunks)
393 /* magazine chains are linked via ChunkLink->next.
394 * each ChunkLink->data of the toplevel chain may point to a subchain,
395 * linked via ChunkLink->next. ChunkLink->data of the subchains just
396 * contains uninitialized junk.
398 ChunkLink *chunk = (*magazine_chunks)->data;
399 if (G_UNLIKELY (chunk))
401 /* allocating from freed list */
402 (*magazine_chunks)->data = chunk->next;
404 else
406 chunk = *magazine_chunks;
407 *magazine_chunks = chunk->next;
409 return chunk;
412 #if 0 /* useful for debugging */
413 static guint
414 magazine_count (ChunkLink *head)
416 guint count = 0;
417 if (!head)
418 return 0;
419 while (head)
421 ChunkLink *child = head->data;
422 count += 1;
423 for (child = head->data; child; child = child->next)
424 count += 1;
425 head = head->next;
427 return count;
429 #endif
431 static inline gsize
432 allocator_get_magazine_threshold (Allocator *allocator,
433 guint ix)
435 /* the magazine size calculated here has a lower bound of MIN_MAGAZINE_SIZE,
436 * which is required by the implementation. also, for moderately sized chunks
437 * (say >= 64 bytes), magazine sizes shouldn't be much smaller then the number
438 * of chunks available per page/2 to avoid excessive traffic in the magazine
439 * cache for small to medium sized structures.
440 * the upper bound of the magazine size is effectively provided by
441 * MAX_MAGAZINE_SIZE. for larger chunks, this number is scaled down so that
442 * the content of a single magazine doesn't exceed ca. 16KB.
444 gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
445 guint threshold = MAX (MIN_MAGAZINE_SIZE, allocator->max_page_size / MAX (5 * chunk_size, 5 * 32));
446 guint contention_counter = allocator->contention_counters[ix];
447 if (G_UNLIKELY (contention_counter)) /* single CPU bias */
449 /* adapt contention counter thresholds to chunk sizes */
450 contention_counter = contention_counter * 64 / chunk_size;
451 threshold = MAX (threshold, contention_counter);
453 return threshold;
456 /* --- magazine cache --- */
457 static inline void
458 magazine_cache_update_stamp (void)
460 if (allocator->stamp_counter >= MAX_STAMP_COUNTER)
462 GTimeVal tv;
463 g_get_current_time (&tv);
464 allocator->last_stamp = tv.tv_sec * 1000 + tv.tv_usec / 1000; /* milli seconds */
465 allocator->stamp_counter = 0;
467 else
468 allocator->stamp_counter++;
471 static inline ChunkLink*
472 magazine_chain_prepare_fields (ChunkLink *magazine_chunks)
474 ChunkLink *chunk1;
475 ChunkLink *chunk2;
476 ChunkLink *chunk3;
477 ChunkLink *chunk4;
478 /* checked upon initialization: mem_assert (MIN_MAGAZINE_SIZE >= 4); */
479 /* ensure a magazine with at least 4 unused data pointers */
480 chunk1 = magazine_chain_pop_head (&magazine_chunks);
481 chunk2 = magazine_chain_pop_head (&magazine_chunks);
482 chunk3 = magazine_chain_pop_head (&magazine_chunks);
483 chunk4 = magazine_chain_pop_head (&magazine_chunks);
484 chunk4->next = magazine_chunks;
485 chunk3->next = chunk4;
486 chunk2->next = chunk3;
487 chunk1->next = chunk2;
488 return chunk1;
491 /* access the first 3 fields of a specially prepared magazine chain */
492 #define magazine_chain_prev(mc) ((mc)->data)
493 #define magazine_chain_stamp(mc) ((mc)->next->data)
494 #define magazine_chain_uint_stamp(mc) GPOINTER_TO_UINT ((mc)->next->data)
495 #define magazine_chain_next(mc) ((mc)->next->next->data)
496 #define magazine_chain_count(mc) ((mc)->next->next->next->data)
498 static void
499 magazine_cache_trim (Allocator *allocator,
500 guint ix,
501 guint stamp)
503 /* g_mutex_lock (allocator->mutex); done by caller */
504 /* trim magazine cache from tail */
505 ChunkLink *current = magazine_chain_prev (allocator->magazines[ix]);
506 ChunkLink *trash = NULL;
507 while (ABS (stamp - magazine_chain_uint_stamp (current)) >= allocator->config.working_set_msecs)
509 /* unlink */
510 ChunkLink *prev = magazine_chain_prev (current);
511 ChunkLink *next = magazine_chain_next (current);
512 magazine_chain_next (prev) = next;
513 magazine_chain_prev (next) = prev;
514 /* clear special fields, put on trash stack */
515 magazine_chain_next (current) = NULL;
516 magazine_chain_count (current) = NULL;
517 magazine_chain_stamp (current) = NULL;
518 magazine_chain_prev (current) = trash;
519 trash = current;
520 /* fixup list head if required */
521 if (current == allocator->magazines[ix])
523 allocator->magazines[ix] = NULL;
524 break;
526 current = prev;
528 g_mutex_unlock (allocator->magazine_mutex);
529 /* free trash */
530 if (trash)
532 const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
533 g_mutex_lock (allocator->slab_mutex);
534 while (trash)
536 current = trash;
537 trash = magazine_chain_prev (current);
538 magazine_chain_prev (current) = NULL; /* clear special field */
539 while (current)
541 ChunkLink *chunk = magazine_chain_pop_head (&current);
542 slab_allocator_free_chunk (chunk_size, chunk);
545 g_mutex_unlock (allocator->slab_mutex);
549 static void
550 magazine_cache_push_magazine (guint ix,
551 ChunkLink *magazine_chunks,
552 gsize count) /* must be >= MIN_MAGAZINE_SIZE */
554 ChunkLink *current = magazine_chain_prepare_fields (magazine_chunks);
555 ChunkLink *next, *prev;
556 g_mutex_lock (allocator->magazine_mutex);
557 /* add magazine at head */
558 next = allocator->magazines[ix];
559 if (next)
560 prev = magazine_chain_prev (next);
561 else
562 next = prev = current;
563 magazine_chain_next (prev) = current;
564 magazine_chain_prev (next) = current;
565 magazine_chain_prev (current) = prev;
566 magazine_chain_next (current) = next;
567 magazine_chain_count (current) = (gpointer) count;
568 /* stamp magazine */
569 magazine_cache_update_stamp();
570 magazine_chain_stamp (current) = GUINT_TO_POINTER (allocator->last_stamp);
571 allocator->magazines[ix] = current;
572 /* free old magazines beyond a certain threshold */
573 magazine_cache_trim (allocator, ix, allocator->last_stamp);
574 /* g_mutex_unlock (allocator->mutex); was done by magazine_cache_trim() */
577 static ChunkLink*
578 magazine_cache_pop_magazine (guint ix,
579 gsize *countp)
581 g_mutex_lock_a (allocator->magazine_mutex, &allocator->contention_counters[ix]);
582 if (!allocator->magazines[ix])
584 guint magazine_threshold = allocator_get_magazine_threshold (allocator, ix);
585 gsize i, chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
586 ChunkLink *chunk, *head;
587 g_mutex_unlock (allocator->magazine_mutex);
588 g_mutex_lock (allocator->slab_mutex);
589 head = slab_allocator_alloc_chunk (chunk_size);
590 head->data = NULL;
591 chunk = head;
592 for (i = 1; i < magazine_threshold; i++)
594 chunk->next = slab_allocator_alloc_chunk (chunk_size);
595 chunk = chunk->next;
596 chunk->data = NULL;
598 chunk->next = NULL;
599 g_mutex_unlock (allocator->slab_mutex);
600 *countp = i;
601 return head;
603 else
605 ChunkLink *current = allocator->magazines[ix];
606 ChunkLink *prev = magazine_chain_prev (current);
607 ChunkLink *next = magazine_chain_next (current);
608 /* unlink */
609 magazine_chain_next (prev) = next;
610 magazine_chain_prev (next) = prev;
611 allocator->magazines[ix] = next == current ? NULL : next;
612 g_mutex_unlock (allocator->magazine_mutex);
613 /* clear special fields and hand out */
614 *countp = (gsize) magazine_chain_count (current);
615 magazine_chain_prev (current) = NULL;
616 magazine_chain_next (current) = NULL;
617 magazine_chain_count (current) = NULL;
618 magazine_chain_stamp (current) = NULL;
619 return current;
623 /* --- thread magazines --- */
624 static void
625 private_thread_memory_cleanup (gpointer data)
627 ThreadMemory *tmem = data;
628 const guint n_magazines = MAX_SLAB_INDEX (allocator);
629 guint ix;
630 for (ix = 0; ix < n_magazines; ix++)
632 Magazine *mags[2];
633 guint j;
634 mags[0] = &tmem->magazine1[ix];
635 mags[1] = &tmem->magazine2[ix];
636 for (j = 0; j < 2; j++)
638 Magazine *mag = mags[j];
639 if (mag->count >= MIN_MAGAZINE_SIZE)
640 magazine_cache_push_magazine (ix, mag->chunks, mag->count);
641 else
643 const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
644 g_mutex_lock (allocator->slab_mutex);
645 while (mag->chunks)
647 ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
648 slab_allocator_free_chunk (chunk_size, chunk);
650 g_mutex_unlock (allocator->slab_mutex);
654 g_free (tmem);
657 static void
658 thread_memory_magazine1_reload (ThreadMemory *tmem,
659 guint ix)
661 Magazine *mag = &tmem->magazine1[ix];
662 mem_assert (mag->chunks == NULL); /* ensure that we may reset mag->count */
663 mag->count = 0;
664 mag->chunks = magazine_cache_pop_magazine (ix, &mag->count);
667 static void
668 thread_memory_magazine2_unload (ThreadMemory *tmem,
669 guint ix)
671 Magazine *mag = &tmem->magazine2[ix];
672 magazine_cache_push_magazine (ix, mag->chunks, mag->count);
673 mag->chunks = NULL;
674 mag->count = 0;
677 static inline void
678 thread_memory_swap_magazines (ThreadMemory *tmem,
679 guint ix)
681 Magazine xmag = tmem->magazine1[ix];
682 tmem->magazine1[ix] = tmem->magazine2[ix];
683 tmem->magazine2[ix] = xmag;
686 static inline gboolean
687 thread_memory_magazine1_is_empty (ThreadMemory *tmem,
688 guint ix)
690 return tmem->magazine1[ix].chunks == NULL;
693 static inline gboolean
694 thread_memory_magazine2_is_full (ThreadMemory *tmem,
695 guint ix)
697 return tmem->magazine2[ix].count >= allocator_get_magazine_threshold (allocator, ix);
700 static inline gpointer
701 thread_memory_magazine1_alloc (ThreadMemory *tmem,
702 guint ix)
704 Magazine *mag = &tmem->magazine1[ix];
705 ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
706 if (G_LIKELY (mag->count > 0))
707 mag->count--;
708 return chunk;
711 static inline void
712 thread_memory_magazine2_free (ThreadMemory *tmem,
713 guint ix,
714 gpointer mem)
716 Magazine *mag = &tmem->magazine2[ix];
717 ChunkLink *chunk = mem;
718 chunk->data = NULL;
719 chunk->next = mag->chunks;
720 mag->chunks = chunk;
721 mag->count++;
724 /* --- API functions --- */
725 gpointer
726 g_slice_alloc (gsize mem_size)
728 gsize chunk_size;
729 gpointer mem;
730 guint acat;
731 chunk_size = P2ALIGN (mem_size);
732 acat = allocator_categorize (chunk_size);
733 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
735 ThreadMemory *tmem = thread_memory_from_self();
736 guint ix = SLAB_INDEX (allocator, chunk_size);
737 if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
739 thread_memory_swap_magazines (tmem, ix);
740 if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
741 thread_memory_magazine1_reload (tmem, ix);
743 mem = thread_memory_magazine1_alloc (tmem, ix);
745 else if (acat == 2) /* allocate through slab allocator */
747 g_mutex_lock (allocator->slab_mutex);
748 mem = slab_allocator_alloc_chunk (chunk_size);
749 g_mutex_unlock (allocator->slab_mutex);
751 else /* delegate to system malloc */
752 mem = g_malloc (mem_size);
753 return mem;
756 gpointer
757 g_slice_alloc0 (gsize mem_size)
759 gpointer mem = g_slice_alloc (mem_size);
760 if (mem)
761 memset (mem, 0, mem_size);
762 return mem;
765 void
766 g_slice_free1 (gsize mem_size,
767 gpointer mem_block)
769 gsize chunk_size = P2ALIGN (mem_size);
770 guint acat = allocator_categorize (chunk_size);
771 if (G_UNLIKELY (!mem_block))
772 /* pass */;
773 else if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
775 ThreadMemory *tmem = thread_memory_from_self();
776 guint ix = SLAB_INDEX (allocator, chunk_size);
777 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
779 thread_memory_swap_magazines (tmem, ix);
780 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
781 thread_memory_magazine2_unload (tmem, ix);
783 thread_memory_magazine2_free (tmem, ix, mem_block);
785 else if (acat == 2) /* allocate through slab allocator */
787 g_mutex_lock (allocator->slab_mutex);
788 slab_allocator_free_chunk (chunk_size, mem_block);
789 g_mutex_unlock (allocator->slab_mutex);
791 else /* delegate to system malloc */
792 g_free (mem_block);
795 void
796 g_slice_free_chain_with_offset (gsize mem_size,
797 gpointer mem_chain,
798 gsize next_offset)
800 gpointer slice = mem_chain;
801 /* while the thread magazines and the magazine cache are implemented so that
802 * they can easily be extended to allow for free lists containing more free
803 * lists for the first level nodes, which would allow O(1) freeing in this
804 * function, the benefit of such an extension is questionable, because:
805 * - the magazine size counts will become mere lower bounds which confuses
806 * the code adapting to lock contention;
807 * - freeing a single node to the thread magazines is very fast, so this
808 * O(list_length) operation is multiplied by a fairly small factor;
809 * - memory usage histograms on larger applications seem to indicate that
810 * the amount of released multi node lists is negligible in comparison
811 * to single node releases.
812 * - the major performance bottle neck, namely g_private_get() or
813 * g_mutex_lock()/g_mutex_unlock() has already been moved out of the
814 * inner loop for freeing chained slices.
816 gsize chunk_size = P2ALIGN (mem_size);
817 guint acat = allocator_categorize (chunk_size);
818 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
820 ThreadMemory *tmem = thread_memory_from_self();
821 guint ix = SLAB_INDEX (allocator, chunk_size);
822 while (slice)
824 guint8 *current = slice;
825 slice = *(gpointer*) (current + next_offset);
826 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
828 thread_memory_swap_magazines (tmem, ix);
829 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
830 thread_memory_magazine2_unload (tmem, ix);
832 thread_memory_magazine2_free (tmem, ix, current);
835 else if (acat == 2) /* allocate through slab allocator */
837 g_mutex_lock (allocator->slab_mutex);
838 while (slice)
840 guint8 *current = slice;
841 slice = *(gpointer*) (current + next_offset);
842 slab_allocator_free_chunk (chunk_size, current);
844 g_mutex_unlock (allocator->slab_mutex);
846 else /* delegate to system malloc */
847 while (slice)
849 guint8 *current = slice;
850 slice = *(gpointer*) (current + next_offset);
851 g_free (current);
855 /* --- single page allocator --- */
856 static void
857 allocator_slab_stack_push (Allocator *allocator,
858 guint ix,
859 SlabInfo *sinfo)
861 /* insert slab at slab ring head */
862 if (!allocator->slab_stack[ix])
864 sinfo->next = sinfo;
865 sinfo->prev = sinfo;
867 else
869 SlabInfo *next = allocator->slab_stack[ix], *prev = next->prev;
870 next->prev = sinfo;
871 prev->next = sinfo;
872 sinfo->next = next;
873 sinfo->prev = prev;
875 allocator->slab_stack[ix] = sinfo;
878 static gsize
879 allocator_aligned_page_size (Allocator *allocator,
880 gsize n_bytes)
882 gsize val = 1 << g_bit_storage (n_bytes - 1);
883 val = MAX (val, allocator->min_page_size);
884 return val;
887 static void
888 allocator_add_slab (Allocator *allocator,
889 guint ix,
890 gsize chunk_size)
892 ChunkLink *chunk;
893 SlabInfo *sinfo;
894 gsize addr, padding, n_chunks, color = 0;
895 gsize page_size = allocator_aligned_page_size (allocator, SLAB_BPAGE_SIZE (allocator, chunk_size));
896 /* allocate 1 page for the chunks and the slab */
897 gpointer aligned_memory = allocator_memalign (page_size, page_size - NATIVE_MALLOC_PADDING);
898 guint8 *mem = aligned_memory;
899 guint i;
900 if (!mem)
902 const gchar *syserr = "unknown error";
903 #if HAVE_STRERROR
904 syserr = strerror (errno);
905 #endif
906 mem_error ("failed to allocate %u bytes (alignment: %u): %s\n",
907 (guint) (page_size - NATIVE_MALLOC_PADDING), (guint) page_size, syserr);
909 /* mask page adress */
910 addr = ((gsize) mem / page_size) * page_size;
911 /* assert alignment */
912 mem_assert (aligned_memory == (gpointer) addr);
913 /* basic slab info setup */
914 sinfo = (SlabInfo*) (mem + page_size - SLAB_INFO_SIZE);
915 sinfo->n_allocated = 0;
916 sinfo->chunks = NULL;
917 /* figure cache colorization */
918 n_chunks = ((guint8*) sinfo - mem) / chunk_size;
919 padding = ((guint8*) sinfo - mem) - n_chunks * chunk_size;
920 if (padding)
922 color = (allocator->color_accu * P2ALIGNMENT) % padding;
923 allocator->color_accu += allocator->config.color_increment;
925 /* add chunks to free list */
926 chunk = (ChunkLink*) (mem + color);
927 sinfo->chunks = chunk;
928 for (i = 0; i < n_chunks - 1; i++)
930 chunk->next = (ChunkLink*) ((guint8*) chunk + chunk_size);
931 chunk = chunk->next;
933 chunk->next = NULL; /* last chunk */
934 /* add slab to slab ring */
935 allocator_slab_stack_push (allocator, ix, sinfo);
938 static gpointer
939 slab_allocator_alloc_chunk (gsize chunk_size)
941 ChunkLink *chunk;
942 guint ix = SLAB_INDEX (allocator, chunk_size);
943 /* ensure non-empty slab */
944 if (!allocator->slab_stack[ix] || !allocator->slab_stack[ix]->chunks)
945 allocator_add_slab (allocator, ix, chunk_size);
946 /* allocate chunk */
947 chunk = allocator->slab_stack[ix]->chunks;
948 allocator->slab_stack[ix]->chunks = chunk->next;
949 allocator->slab_stack[ix]->n_allocated++;
950 /* rotate empty slabs */
951 if (!allocator->slab_stack[ix]->chunks)
952 allocator->slab_stack[ix] = allocator->slab_stack[ix]->next;
953 return chunk;
956 static void
957 slab_allocator_free_chunk (gsize chunk_size,
958 gpointer mem)
960 ChunkLink *chunk;
961 gboolean was_empty;
962 guint ix = SLAB_INDEX (allocator, chunk_size);
963 gsize page_size = allocator_aligned_page_size (allocator, SLAB_BPAGE_SIZE (allocator, chunk_size));
964 gsize addr = ((gsize) mem / page_size) * page_size;
965 /* mask page adress */
966 guint8 *page = (guint8*) addr;
967 SlabInfo *sinfo = (SlabInfo*) (page + page_size - SLAB_INFO_SIZE);
968 /* assert valid chunk count */
969 mem_assert (sinfo->n_allocated > 0);
970 /* add chunk to free list */
971 was_empty = sinfo->chunks == NULL;
972 chunk = (ChunkLink*) mem;
973 chunk->next = sinfo->chunks;
974 sinfo->chunks = chunk;
975 sinfo->n_allocated--;
976 /* keep slab ring partially sorted, empty slabs at end */
977 if (was_empty)
979 /* unlink slab */
980 SlabInfo *next = sinfo->next, *prev = sinfo->prev;
981 next->prev = prev;
982 prev->next = next;
983 if (allocator->slab_stack[ix] == sinfo)
984 allocator->slab_stack[ix] = next == sinfo ? NULL : next;
985 /* insert slab at head */
986 allocator_slab_stack_push (allocator, ix, sinfo);
988 /* eagerly free complete unused slabs */
989 if (!sinfo->n_allocated)
991 /* unlink slab */
992 SlabInfo *next = sinfo->next, *prev = sinfo->prev;
993 next->prev = prev;
994 prev->next = next;
995 if (allocator->slab_stack[ix] == sinfo)
996 allocator->slab_stack[ix] = next == sinfo ? NULL : next;
997 /* free slab */
998 allocator_memfree (page_size, page);
1002 /* --- memalign implementation --- */
1003 #ifdef HAVE_MALLOC_H
1004 #include <malloc.h> /* memalign() */
1005 #endif
1007 /* from config.h:
1008 * define HAVE_POSIX_MEMALIGN 1 // if free(posix_memalign(3)) works, <stdlib.h>
1009 * define HAVE_MEMALIGN 1 // if free(memalign(3)) works, <malloc.h>
1010 * define HAVE_VALLOC 1 // if free(valloc(3)) works, <stdlib.h> or <malloc.h>
1011 * if none is provided, we implement malloc(3)-based alloc-only page alignment
1014 #if !(HAVE_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC)
1015 static GTrashStack *compat_valloc_trash = NULL;
1016 #endif
1018 static gpointer
1019 allocator_memalign (gsize alignment,
1020 gsize memsize)
1022 gpointer aligned_memory = NULL;
1023 gint err = ENOMEM;
1024 #if HAVE_POSIX_MEMALIGN
1025 err = posix_memalign (&aligned_memory, alignment, memsize);
1026 #elif HAVE_MEMALIGN
1027 errno = 0;
1028 aligned_memory = memalign (alignment, memsize);
1029 err = errno;
1030 #elif HAVE_VALLOC
1031 errno = 0;
1032 aligned_memory = valloc (memsize);
1033 err = errno;
1034 #else
1035 /* simplistic non-freeing page allocator */
1036 mem_assert (alignment == sys_page_size);
1037 mem_assert (memsize <= sys_page_size);
1038 if (!compat_valloc_trash)
1040 const guint n_pages = 16;
1041 guint8 *mem = malloc (n_pages * sys_page_size);
1042 err = errno;
1043 if (mem)
1045 gint i = n_pages;
1046 guint8 *amem = (guint8*) ALIGN ((gsize) mem, sys_page_size);
1047 if (amem != mem)
1048 i--; /* mem wasn't page aligned */
1049 while (--i >= 0)
1050 g_trash_stack_push (&compat_valloc_trash, amem + i * sys_page_size);
1053 aligned_memory = g_trash_stack_pop (&compat_valloc_trash);
1054 #endif
1055 if (!aligned_memory)
1056 errno = err;
1057 return aligned_memory;
1060 static void
1061 allocator_memfree (gsize memsize,
1062 gpointer mem)
1064 #if HAVE_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC
1065 free (mem);
1066 #else
1067 mem_assert (memsize <= sys_page_size);
1068 g_trash_stack_push (&compat_valloc_trash, mem);
1069 #endif
1072 #include <stdio.h>
1074 static void
1075 mem_error (const char *format,
1076 ...)
1078 const char *pname;
1079 va_list args;
1080 /* at least, put out "MEMORY-ERROR", in case we segfault during the rest of the function */
1081 fputs ("\n***MEMORY-ERROR***: ", stderr);
1082 pname = g_get_prgname();
1083 fprintf (stderr, "%s[%u]: GSlice: ", pname ? pname : "", getpid());
1084 va_start (args, format);
1085 vfprintf (stderr, format, args);
1086 va_end (args);
1087 fputs ("\n", stderr);
1088 _exit (1);
1091 #define __G_SLICE_C__
1092 #include "galiasdef.c"