new slice allocator implementation.
[platform/upstream/glib.git] / glib / gslice.c
1 /* GLIB sliced memory - fast concurrent memory chunk allocator
2  * Copyright (C) 2005 Tim Janik
3  *
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.
8  *
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.
13  *
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.
18  */
19 /* MT safe */
20 #define _XOPEN_SOURCE 600       /* posix_memalign() */
21 #include <stdlib.h>             /* posix_memalign() */
22 #include <unistd.h>             /* sysconf() */
23 #include <assert.h>             /* assert() for nomessage phase */
24 #include <string.h>
25 #include <errno.h>
26 #include "config.h"
27 #include "gmem.h"               /* gslice.h */
28 #include "gthreadinit.h"
29 #include "galias.h"
30 #include "glib.h"
31
32 /* the GSlice allocator is split up into 4 layers, roughly modelled after the slab
33  * allocator and magazine extensions as outlined in:
34  * + [Bonwick94] Jeff Bonwick, The slab allocator: An object-caching kernel
35  *   memory allocator. USENIX 1994, http://citeseer.ist.psu.edu/bonwick94slab.html
36  * + [Bonwick01] Bonwick and Jonathan Adams, Magazines and vmem: Extending the
37  *   slab allocator to many cpu's and arbitrary resources.
38  *   USENIX 2001, http://citeseer.ist.psu.edu/bonwick01magazines.html
39  * the layers are:
40  * - the thread magazines. for each (aligned) chunk size, a magazine (a list)
41  *   of recently freed and soon to be allocated chunks is maintained per thread.
42  *   this way, most alloc/free requests can be quickly satisfied from per-thread
43  *   free lists which only require one g_private_get() call to retrive the
44  *   thread handle.
45  * - the magazine cache. allocating and freeing chunks to/from threads only
46  *   occours at magazine sizes from a global depot of magazines. the depot
47  *   maintaines a 15 second working set of allocated magazines, so full
48  *   magazines are not allocated and released too often.
49  *   the chunk size dependent magazine sizes automatically adapt (within limits,
50  *   see [3]) to lock contention to properly scale performance across a variety
51  *   of SMP systems.
52  * - the slab allocator. this allocator allocates slabs (blocks of memory) close
53  *   to the system page size or multiples thereof which have to be page aligned.
54  *   the blocks are divided into smaller chunks which are used to satisfy
55  *   allocations from the upper layers. the space provided by the reminder of
56  *   the chunk size division is used for cache colorization (random distribution
57  *   of chunk addresses) to improve processor cache utilization. multiple slabs
58  *   with the same chunk size are kept in a partially sorted ring to allow O(1)
59  *   freeing and allocation of chunks (as long as the allocation of an entirely
60  *   new slab can be avoided).
61  * - the page allocator. on most modern systems, posix_memalign(3) or
62  *   memalign(3) should be available, so this is used to allocate blocks with
63  *   system page size based alignments and sizes or multiples thereof.
64  *   if no memalign variant is provided, valloc() is used instead and
65  *   block sizes are limited to the system page size (no multiples thereof).
66  *   as a fallback, on system without even valloc(), a malloc(3)-based page
67  *   allocator with alloc-only behaviour is used.
68  *
69  * NOTES:
70  * [1] some systems memalign(3) implementations may rely on boundary tagging for
71  *     the handed out memory chunks. to avoid excessive page-wise fragmentation,
72  *     we reserve 2 * sizeof (void*) per block size for the systems memalign(3),
73  *     specified in NATIVE_MALLOC_PADDING.
74  * [2] using the slab allocator alone already provides for a fast and efficient
75  *     allocator, it doesn't properly scale beyond single-threaded uses though.
76  *     also, the slab allocator implements eager free(3)-ing, i.e. does not
77  *     provide any form of caching or working set maintenance. so if used alone,
78  *     it's vulnerable to trashing for sequences of balanced (alloc, free) pairs
79  *     at certain thresholds.
80  * [3] magazine sizes are bound by an implementation specific minimum size and
81  *     a chunk size specific maximum to limit magazine storage sizes to roughly
82  *     16KB.
83  * [4] allocating ca. 8 chunks per block/page keeps a good balance between
84  *     external and internal fragmentation (<= 12.5%) [Bonwick94]
85  */
86
87 /* --- macros and constants --- */
88 #define LARGEALIGNMENT          (256)
89 #define P2ALIGNMENT             (2 * sizeof (gsize))                            /* fits 2 pointers (assumed to be 2 * GLIB_SIZEOF_SIZE_T below) */
90 #define ALIGN(size, base)       ((base) * (gsize) (((size) + (base) - 1) / (base)))
91 #define NATIVE_MALLOC_PADDING   P2ALIGNMENT                                     /* per-page padding left for native malloc(3) see [1] */
92 #define SLAB_INFO_SIZE          P2ALIGN (sizeof (SlabInfo) + NATIVE_MALLOC_PADDING)
93 #define MAX_MAGAZINE_SIZE       (256)                                           /* see [3] and allocator_get_magazine_threshold() for this */
94 #define MIN_MAGAZINE_SIZE       (4)
95 #define MAX_STAMP_COUNTER       (13)                                            /* distributes the load of gettimeofday() */
96 #define MAX_SLAB_CHUNK_SIZE(al) (((al)->max_page_size - SLAB_INFO_SIZE) / 8)    /* we want at last 8 chunks per page, see [4] */
97 #define MAX_SLAB_INDEX(al)      (SLAB_INDEX (al, MAX_SLAB_CHUNK_SIZE (al)) + 1)
98 #define SLAB_INDEX(al, asize)   ((asize) / P2ALIGNMENT - 1)                     /* asize must be P2ALIGNMENT aligned */
99 #define SLAB_CHUNK_SIZE(al, ix) (((ix) + 1) * P2ALIGNMENT)
100 #define SLAB_PAGE_SIZE(al,csz)  (ALIGN (8 * (csz) + SLAB_INFO_SIZE, (al)->min_page_size))
101
102 /* optimized version of ALIGN (size, P2ALIGNMENT) */
103 #if     GLIB_SIZEOF_SIZE_T * 2 == 8  /* P2ALIGNMENT */
104 #define P2ALIGN(size)   (((size) + 0x7) & ~(gsize) 0x7)
105 #elif   GLIB_SIZEOF_SIZE_T * 2 == 16 /* P2ALIGNMENT */
106 #define P2ALIGN(size)   (((size) + 0xf) & ~(gsize) 0xf)
107 #else
108 #define P2ALIGN(size)   ALIGN (size, P2ALIGNMENT)
109 #endif
110
111 /* --- structures --- */
112 typedef struct _ChunkLink      ChunkLink;
113 typedef struct _SlabInfo       SlabInfo;
114 typedef struct _CachedMagazine CachedMagazine;
115 struct _ChunkLink {
116   ChunkLink *next;
117   ChunkLink *data;
118 };
119 struct _SlabInfo {
120   ChunkLink *chunks;
121   guint n_allocated;
122   SlabInfo *next, *prev;
123 };
124 typedef struct {
125   ChunkLink *chunks;
126   gsize      count;                     /* approximative chunks list length */
127 } Magazine;
128 typedef struct {
129   Magazine   *magazine1;                /* array of MAX_SLAB_INDEX (allocator) */
130   Magazine   *magazine2;                /* array of MAX_SLAB_INDEX (allocator) */
131 } ThreadMemory;
132 typedef struct {
133   gboolean always_malloc;
134   gboolean bypass_magazines;
135   gboolean always_free;
136   gsize    working_set_msecs;
137 } SliceConfig;
138 typedef struct {
139   /* const after initialization */
140   gsize         min_page_size, max_page_size;
141   SliceConfig   config;
142   guint         max_slab_chunk_size_for_magazine_cache;
143   /* magazine cache */
144   GMutex       *magazine_mutex;
145   ChunkLink   **magazines;                /* array of MAX_SLAB_INDEX (allocator) */
146   guint        *contention_counters;      /* array of MAX_SLAB_INDEX (allocator) */
147   gint          mutex_counter;
148   guint         stamp_counter;
149   guint         last_stamp;
150   /* slab allocator */
151   GMutex       *slab_mutex;
152   SlabInfo    **slab_stack;                /* array of MAX_SLAB_INDEX (allocator) */
153   guint        color_accu;
154 } Allocator;
155
156 /* --- prototypes --- */
157 static gpointer     slab_allocator_alloc_chunk       (guint      chunk_size);
158 static void         slab_allocator_free_chunk        (guint      chunk_size,
159                                                       gpointer   mem);
160 static void         private_thread_memory_cleanup    (gpointer   data);
161 static gpointer     allocator_memalign               (gsize      alignment,
162                                                       gsize      memsize);
163 static void         allocator_memfree                (gsize      memsize,
164                                                       gpointer   mem);
165 static inline void  magazine_cache_update_stamp      (void);
166 static inline guint allocator_get_magazine_threshold (Allocator *allocator,
167                                                       guint      ix);
168
169 /* --- variables --- */
170 static GPrivate        *private_thread_memory = NULL;
171 static gsize            sys_page_size = 0;
172 static Allocator        allocator[1] = { { 0, }, };
173 static SliceConfig      slice_config = {
174   FALSE,        /* always_malloc */
175   FALSE,        /* bypass_magazines */
176   FALSE,        /* always_free */
177   15 * 1000,    /* working_set_msecs */
178 };
179
180 /* --- auxillary funcitons --- */
181 void
182 g_slice_set_config (GSliceConfig ckey,
183                     gint64       value)
184 {
185   g_return_if_fail (sys_page_size == 0);
186   switch (ckey)
187     {
188     case G_SLICE_CONFIG_ALWAYS_MALLOC:
189       slice_config.always_malloc = value != 0;
190       break;
191     case G_SLICE_CONFIG_BYPASS_MAGAZINES:
192       slice_config.bypass_magazines = value != 0;
193       break;
194     case G_SLICE_CONFIG_ALWAYS_FREE:
195       slice_config.always_free = value != 0;
196       break;
197     case G_SLICE_CONFIG_WORKING_SET_MSECS:
198       slice_config.working_set_msecs = value;
199       break;
200     default: ;
201     }
202 }
203
204 gint64
205 g_slice_get_config (GSliceConfig ckey)
206 {
207   switch (ckey)
208     {
209     case G_SLICE_CONFIG_ALWAYS_MALLOC:
210       return slice_config.always_malloc;
211     case G_SLICE_CONFIG_BYPASS_MAGAZINES:
212       return slice_config.bypass_magazines;
213     case G_SLICE_CONFIG_ALWAYS_FREE:
214       return slice_config.always_free;
215     case G_SLICE_CONFIG_WORKING_SET_MSECS:
216       return slice_config.working_set_msecs;
217     case G_SLICE_CONFIG_CHUNK_SIZES:
218       return MAX_SLAB_INDEX (allocator);
219     default:
220       return 0;
221     }
222 }
223
224 gint64*
225 g_slice_get_config_state (GSliceConfig ckey,
226                           gint64       address,
227                           guint       *n_values)
228 {
229   guint i = 0;
230   g_return_val_if_fail (n_values != NULL, NULL);
231   *n_values = 0;
232   switch (ckey)
233     {
234       gint64 array[64];
235     case G_SLICE_CONFIG_CONTENTION_COUNTER:
236       array[i++] = SLAB_CHUNK_SIZE (allocator, address);
237       array[i++] = allocator->contention_counters[address];
238       array[i++] = allocator_get_magazine_threshold (allocator, address);
239       *n_values = i;
240       return g_memdup (array, sizeof (array[0]) * *n_values);
241     default:
242       return NULL;
243     }
244 }
245
246 static void
247 g_slice_init_nomessage (void)
248 {
249   /* we may not use g_error() or friends here */
250   assert (sys_page_size == 0);
251
252   sys_page_size = sysconf (_SC_PAGESIZE); /* = sysconf (_SC_PAGE_SIZE); = getpagesize(); */
253   assert (sys_page_size >= 2 * LARGEALIGNMENT);
254   allocator->config = slice_config;
255   allocator->min_page_size = sys_page_size;
256 #if HAVE_POSIX_MEMALIGN || HAVE_MEMALIGN
257   /* allow allocation of pages up to 8KB (with 8KB alignment).
258    * this is useful because many medium to large sized structures
259    * fit less than 8 times (see [4]) into 4KB pages.
260    */
261   allocator->min_page_size = MAX (allocator->min_page_size, 4096);
262   allocator->max_page_size = MAX (allocator->min_page_size, 8192);
263 #else
264   /* we can only align to system page size */
265   allocator->max_page_size = sys_page_size;
266 #endif
267   allocator->magazine_mutex = NULL;     /* _g_slice_thread_init_nomessage() */
268   allocator->magazines = g_new0 (ChunkLink*, MAX_SLAB_INDEX (allocator));
269   allocator->contention_counters = g_new0 (guint, MAX_SLAB_INDEX (allocator));
270   allocator->mutex_counter = 0;
271   allocator->stamp_counter = MAX_STAMP_COUNTER; /* force initial update */
272   allocator->last_stamp = 0;
273   allocator->slab_mutex = NULL;         /* _g_slice_thread_init_nomessage() */
274   allocator->slab_stack = g_new0 (SlabInfo*, MAX_SLAB_INDEX (allocator));
275   allocator->color_accu = 0;
276   magazine_cache_update_stamp();
277   /* values cached for performance reasons */
278   allocator->max_slab_chunk_size_for_magazine_cache = MAX_SLAB_CHUNK_SIZE (allocator);
279   if (allocator->config.always_malloc || allocator->config.bypass_magazines)
280     allocator->max_slab_chunk_size_for_magazine_cache = 0;      /* non-optimized cases */
281 }
282
283 static inline guint
284 allocator_categorize (guint aligned_chunk_size)
285 {
286   /* speed up the likely path */
287   if (G_LIKELY (aligned_chunk_size && aligned_chunk_size <= allocator->max_slab_chunk_size_for_magazine_cache))
288     return 1;           /* use magazine cache */
289
290   /* the above will fail (max_slab_chunk_size_for_magazine_cache == 0) if the
291    * allocator is still uninitialized, or if we are not configured to use the
292    * magazine cache.
293    */
294   if (!sys_page_size)
295     g_slice_init_nomessage ();
296   if (!allocator->config.always_malloc &&
297       aligned_chunk_size &&
298       aligned_chunk_size <= MAX_SLAB_CHUNK_SIZE (allocator))
299     {
300       if (allocator->config.bypass_magazines)
301         return 2;       /* use slab allocator, see [2] */
302       return 1;         /* use magazine cache */
303     }
304   return 0;             /* use malloc() */
305 }
306
307 void
308 _g_slice_thread_init_nomessage (void)
309 {
310   /* we may not use g_error() or friends here */
311   if (!sys_page_size)
312     g_slice_init_nomessage();
313   private_thread_memory = g_private_new (private_thread_memory_cleanup);
314   allocator->magazine_mutex = g_mutex_new();
315   allocator->slab_mutex = g_mutex_new();
316 }
317
318 static inline void
319 g_mutex_lock_a (GMutex *mutex,
320                 guint  *threshold)
321 {
322   gboolean contention = FALSE;
323   if (!g_mutex_trylock (mutex))
324     {
325       g_mutex_lock (mutex);
326       contention = TRUE;
327     }
328   if (contention)
329     {
330       allocator->mutex_counter++;
331       if (allocator->mutex_counter >= 1)        /* quickly adapt to contention */
332         {
333           allocator->mutex_counter = 0;
334           *threshold = MIN (*threshold + 1, MAX_MAGAZINE_SIZE);
335         }
336     }
337   else /* !contention */
338     {
339       allocator->mutex_counter--;
340       if (allocator->mutex_counter < -11)       /* moderately recover magazine sizes */
341         {
342           allocator->mutex_counter = 0;
343           *threshold = MAX (*threshold, 1) - 1;
344         }
345     }
346 }
347
348 static inline ThreadMemory*
349 thread_memory_from_self (void)
350 {
351   ThreadMemory *tmem = g_private_get (private_thread_memory);
352   if (G_UNLIKELY (!tmem))
353     {
354       const guint n_magazines = MAX_SLAB_INDEX (allocator);
355       tmem = g_malloc0 (sizeof (ThreadMemory) + sizeof (Magazine) * 2 * n_magazines);
356       tmem->magazine1 = (Magazine*) (tmem + 1);
357       tmem->magazine2 = &tmem->magazine1[n_magazines];
358       g_private_set (private_thread_memory, tmem);
359     }
360   return tmem;
361 }
362
363 static inline ChunkLink*
364 magazine_chain_pop_head (ChunkLink **magazine_chunks)
365 {
366   /* magazine chains are linked via ChunkLink->next.
367    * each ChunkLink->data of the toplevel chain may point to a subchain,
368    * linked via ChunkLink->next. ChunkLink->data of the subchains just
369    * contains uninitialized junk.
370    */
371   ChunkLink *chunk = (*magazine_chunks)->data;
372   if (G_UNLIKELY (chunk))
373     {
374       /* allocating from freed list */
375       (*magazine_chunks)->data = chunk->next;
376     }
377   else
378     {
379       chunk = *magazine_chunks;
380       *magazine_chunks = chunk->next;
381     }
382   return chunk;
383 }
384
385 static guint
386 magazine_count (ChunkLink *head)
387 {
388   guint count = 0;
389   if (!head)
390     return 0;
391   while (head)
392     {
393       ChunkLink *child = head->data;
394       count += 1;
395       for (child = head->data; child; child = child->next)
396         count += 1;
397       head = head->next;
398     }
399   return count;
400 }
401
402 static inline guint
403 allocator_get_magazine_threshold (Allocator *allocator,
404                                   guint      ix)
405 {
406   /* the magazine size calculated here has a lower bound of MIN_MAGAZINE_SIZE,
407    * which is required by the implementation. also, for moderately sized chunks
408    * (say >= 64 bytes), magazine sizes shouldn't be much smaller then the number
409    * of chunks available per page to avoid excessive traffic in the magazine
410    * cache for small to medium sized structures.
411    * the upper bound of the magazine size is effectively provided by
412    * MAX_MAGAZINE_SIZE. for larger chunks, this number is scaled down so that
413    * the content of a single magazine doesn't exceed ca. 16KB.
414    */
415   guint chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
416   guint threshold = MAX (MIN_MAGAZINE_SIZE, sys_page_size / MAX (chunk_size, 64));
417   guint contention_counter = allocator->contention_counters[ix];
418   if (G_UNLIKELY (contention_counter))  /* single CPU bias */
419     {
420       /* adapt contention counter thresholds to chunk sizes */
421       contention_counter = contention_counter * 64 / chunk_size;
422       threshold = MAX (threshold, contention_counter);
423     }
424   return threshold;
425 }
426
427 /* --- magazine cache --- */
428 static inline void
429 magazine_cache_update_stamp (void)
430 {
431   if (allocator->stamp_counter >= MAX_STAMP_COUNTER)
432     {
433       GTimeVal tv;
434       g_get_current_time (&tv);
435       allocator->last_stamp = tv.tv_sec * 1000 + tv.tv_usec / 1000; /* milli seconds */
436       allocator->stamp_counter = 0;
437     }
438   else
439     allocator->stamp_counter++;
440 }
441
442 static inline ChunkLink*
443 magazine_chain_prepare_fields (ChunkLink *magazine_chunks)
444 {
445   g_assert (MIN_MAGAZINE_SIZE >= 4);
446   /* ensure a magazine with at least 4 unused data pointers */
447   ChunkLink *chunk1 = magazine_chain_pop_head (&magazine_chunks);
448   ChunkLink *chunk2 = magazine_chain_pop_head (&magazine_chunks);
449   ChunkLink *chunk3 = magazine_chain_pop_head (&magazine_chunks);
450   ChunkLink *chunk4 = magazine_chain_pop_head (&magazine_chunks);
451   chunk4->next = magazine_chunks;
452   chunk3->next = chunk4;
453   chunk2->next = chunk3;
454   chunk1->next = chunk2;
455   return chunk1;
456 }
457
458 /* access the first 3 fields of a specially prepared magazine chain */
459 #define magazine_chain_prev(mc)         ((mc)->data)
460 #define magazine_chain_stamp(mc)        ((mc)->next->data)
461 #define magazine_chain_next(mc)         ((mc)->next->next->data)
462 #define magazine_chain_count(mc)        ((mc)->next->next->next->data)
463
464 static void
465 magazine_cache_trim (Allocator *allocator,
466                      guint      ix,
467                      guint      stamp)
468 {
469   /* g_mutex_lock (allocator->mutex); done by caller */
470   /* trim magazine cache from tail */
471   ChunkLink *current = magazine_chain_prev (allocator->magazines[ix]);
472   ChunkLink *trash = NULL;
473   while (allocator->config.always_free ||
474          ABS (stamp - (guint) magazine_chain_stamp (current)) > allocator->config.working_set_msecs)
475     {
476       /* unlink */
477       ChunkLink *prev = magazine_chain_prev (current);
478       ChunkLink *next = magazine_chain_next (current);
479       magazine_chain_next (prev) = next;
480       magazine_chain_prev (next) = prev;
481       /* clear special fields, put on trash stack */
482       magazine_chain_next (current) = NULL;
483       magazine_chain_count (current) = NULL;
484       magazine_chain_stamp (current) = NULL;
485       magazine_chain_prev (current) = trash;
486       trash = current;
487       /* fixup list head if required */
488       if (current == allocator->magazines[ix])
489         {
490           allocator->magazines[ix] = NULL;
491           break;
492         }
493       current = prev;
494     }
495   g_mutex_unlock (allocator->magazine_mutex);
496   /* free trash */
497   if (trash)
498     {
499       const guint chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
500       g_mutex_lock (allocator->slab_mutex);
501       while (trash)
502         {
503           current = trash;
504           trash = magazine_chain_prev (current);
505           magazine_chain_prev (current) = NULL; /* clear special field */
506           while (current)
507             {
508               ChunkLink *chunk = magazine_chain_pop_head (&current);
509               slab_allocator_free_chunk (chunk_size, chunk);
510             }
511         }
512       g_mutex_unlock (allocator->slab_mutex);
513     }
514 }
515
516 static void
517 magazine_cache_push_magazine (guint      ix,
518                               ChunkLink *magazine_chunks,
519                               gsize      count) /* must be >= MIN_MAGAZINE_SIZE */
520 {
521   ChunkLink *current = magazine_chain_prepare_fields (magazine_chunks);
522   ChunkLink *next, *prev;
523   g_mutex_lock (allocator->magazine_mutex);
524   /* add magazine at head */
525   next = allocator->magazines[ix];
526   if (next)
527     prev = magazine_chain_prev (next);
528   else
529     next = prev = current;
530   magazine_chain_next (prev) = current;
531   magazine_chain_prev (next) = current;
532   magazine_chain_prev (current) = prev;
533   magazine_chain_next (current) = next;
534   magazine_chain_count (current) = (gpointer) count;
535   /* stamp magazine */
536   magazine_cache_update_stamp();
537   magazine_chain_stamp (current) = (gpointer) allocator->last_stamp;
538   allocator->magazines[ix] = current;
539   /* free old magazines beyond a certain threshold */
540   magazine_cache_trim (allocator, ix, allocator->last_stamp);
541   /* g_mutex_unlock (allocator->mutex); was done by magazine_cache_trim() */
542 }
543
544 static ChunkLink*
545 magazine_cache_pop_magazine (guint  ix,
546                              gsize *countp)
547 {
548   g_mutex_lock_a (allocator->magazine_mutex, &allocator->contention_counters[ix]);
549   if (!allocator->magazines[ix])
550     {
551       guint magazine_threshold = allocator_get_magazine_threshold (allocator, ix);
552       gsize i, chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
553       ChunkLink *current = NULL;
554       g_mutex_unlock (allocator->magazine_mutex);
555       g_mutex_lock (allocator->slab_mutex);
556       for (i = 0; i < magazine_threshold; i++)
557         {
558           ChunkLink *chunk = slab_allocator_alloc_chunk (chunk_size);
559           chunk->data = NULL;
560           chunk->next = current;
561           current = chunk;
562         }
563       g_mutex_unlock (allocator->slab_mutex);
564       *countp = i;
565       return current;
566     }
567   else
568     {
569       ChunkLink *current = allocator->magazines[ix];
570       ChunkLink *prev = magazine_chain_prev (current);
571       ChunkLink *next = magazine_chain_next (current);
572       /* unlink */
573       magazine_chain_next (prev) = next;
574       magazine_chain_prev (next) = prev;
575       allocator->magazines[ix] = next == current ? NULL : next;
576       g_mutex_unlock (allocator->magazine_mutex);
577       /* clear special fields and hand out */
578       *countp = (gsize) magazine_chain_count (current);
579       magazine_chain_prev (current) = NULL;
580       magazine_chain_next (current) = NULL;
581       magazine_chain_count (current) = NULL;
582       magazine_chain_stamp (current) = NULL;
583       return current;
584     }
585 }
586
587 /* --- thread magazines --- */
588 static void
589 private_thread_memory_cleanup (gpointer data)
590 {
591   ThreadMemory *tmem = data;
592   const guint n_magazines = MAX_SLAB_INDEX (allocator);
593   guint ix;
594   for (ix = 0; ix < n_magazines; ix++)
595     {
596       Magazine *mags[2];
597       guint j;
598       mags[0] = &tmem->magazine1[ix];
599       mags[1] = &tmem->magazine2[ix];
600       for (j = 0; j < 2; j++)
601         {
602           Magazine *mag = mags[j];
603           if (mag->count >= MIN_MAGAZINE_SIZE)
604             magazine_cache_push_magazine (ix, mag->chunks, mag->count);
605           else
606             {
607               const guint chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
608               g_mutex_lock (allocator->slab_mutex);
609               while (mag->chunks)
610                 {
611                   ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
612                   slab_allocator_free_chunk (chunk_size, chunk);
613                 }
614               g_mutex_unlock (allocator->slab_mutex);
615             }
616         }
617     }
618   g_free (tmem);
619 }
620
621 static void
622 thread_memory_magazine1_reload (ThreadMemory *tmem,
623                                 guint         ix)
624 {
625   Magazine *mag = &tmem->magazine1[ix];
626   g_assert (mag->chunks == NULL); /* ensure that we may reset mag->count */
627   mag->count = 0;
628   mag->chunks = magazine_cache_pop_magazine (ix, &mag->count);
629 }
630
631 static void
632 thread_memory_magazine2_unload (ThreadMemory *tmem,
633                                 guint         ix)
634 {
635   Magazine *mag = &tmem->magazine2[ix];
636   magazine_cache_push_magazine (ix, mag->chunks, mag->count);
637   mag->chunks = NULL;
638   mag->count = 0;
639 }
640
641 static inline void
642 thread_memory_swap_magazines (ThreadMemory *tmem,
643                               guint         ix)
644 {
645   Magazine xmag = tmem->magazine1[ix];
646   tmem->magazine1[ix] = tmem->magazine2[ix];
647   tmem->magazine2[ix] = xmag;
648 }
649
650 static inline gboolean
651 thread_memory_magazine1_is_empty (ThreadMemory *tmem,
652                                   guint         ix)
653 {
654   return tmem->magazine1[ix].chunks == NULL;
655 }
656
657 static inline gboolean
658 thread_memory_magazine2_is_full (ThreadMemory *tmem,
659                                  guint         ix)
660 {
661   return tmem->magazine2[ix].count >= allocator_get_magazine_threshold (allocator, ix);
662 }
663
664 static inline gpointer
665 thread_memory_magazine1_alloc (ThreadMemory *tmem,
666                                guint         ix)
667 {
668   Magazine *mag = &tmem->magazine1[ix];
669   ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
670   if (G_LIKELY (mag->count > 0))
671     mag->count--;
672   return chunk;
673 }
674
675 static inline void
676 thread_memory_magazine2_free (ThreadMemory *tmem,
677                               guint         ix,
678                               gpointer      mem)
679 {
680   Magazine *mag = &tmem->magazine2[ix];
681   ChunkLink *chunk = mem;
682   chunk->data = NULL;
683   chunk->next = mag->chunks;
684   mag->chunks = chunk;
685   mag->count++;
686 }
687
688 /* --- API functions --- */
689 gpointer
690 g_slice_alloc (gsize mem_size)
691 {
692   gsize chunk_size;
693   gpointer mem;
694   guint acat;
695   chunk_size = P2ALIGN (mem_size);
696   acat = allocator_categorize (chunk_size);
697   if (G_LIKELY (acat == 1))     /* allocate through magazine layer */
698     {
699       ThreadMemory *tmem = thread_memory_from_self();
700       guint ix = SLAB_INDEX (allocator, chunk_size);
701       if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
702         {
703           thread_memory_swap_magazines (tmem, ix);
704           if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
705             thread_memory_magazine1_reload (tmem, ix);
706         }
707       mem = thread_memory_magazine1_alloc (tmem, ix);
708     }
709   else if (acat == 2)           /* allocate through slab allocator */
710     {
711       g_mutex_lock (allocator->slab_mutex);
712       mem = slab_allocator_alloc_chunk (chunk_size);
713       g_mutex_unlock (allocator->slab_mutex);
714     }
715   else                          /* delegate to system malloc */
716     mem = g_malloc (mem_size);
717   return mem;
718 }
719
720 gpointer
721 g_slice_alloc0 (guint mem_size)
722 {
723   gpointer mem = g_slice_alloc (mem_size);
724   if (mem)
725     memset (mem, 0, mem_size);
726   return mem;
727 }
728
729 void
730 g_slice_free1 (guint    mem_size,
731                gpointer mem_block)
732 {
733   guint chunk_size = P2ALIGN (mem_size);
734   guint acat = allocator_categorize (chunk_size);
735   if (G_UNLIKELY (!mem_block))
736     /* pass */;
737   else if (G_LIKELY (acat == 1))        /* allocate through magazine layer */
738     {
739       ThreadMemory *tmem = thread_memory_from_self();
740       guint ix = SLAB_INDEX (allocator, chunk_size);
741       if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
742         {
743           thread_memory_swap_magazines (tmem, ix);
744           if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
745             thread_memory_magazine2_unload (tmem, ix);
746         }
747       thread_memory_magazine2_free (tmem, ix, mem_block);
748     }
749   else if (acat == 2)                   /* allocate through slab allocator */
750     {
751       g_mutex_lock (allocator->slab_mutex);
752       slab_allocator_free_chunk (chunk_size, mem_block);
753       g_mutex_unlock (allocator->slab_mutex);
754     }
755   else                          /* delegate to system malloc */
756     g_free (mem_block);
757 }
758
759 void
760 g_slice_free_chain (guint    mem_size,
761                     gpointer mem_chain,
762                     guint    next_offset)
763 {
764   GSList *slice = mem_chain;
765   g_return_if_fail (next_offset == G_STRUCT_OFFSET (GSList, next));
766   g_return_if_fail (mem_size >= sizeof (GSList));
767   while (slice)
768     {
769       GSList *current = slice;
770       slice = slice->next;
771       g_slice_free1 (mem_size, current);
772     }
773   /* while the thread magazines and the magazine cache are implemented so that
774    * they can easily be extended to allow for free lists containing more free
775    * lists for the first level nodes, which would allow O(1) freeing in this
776    * function, the benefit of such an extension is questionable, because:
777    * - the magazine size counts will become mere lower bounds which confuses
778    *   the code adapting to lock contention;
779    * - freeing a single node to the thread magazines is very fast, so this
780    *   O(list_length) operation is multiplied by a fairly small factor;
781    * - memory usage histograms on larger applications seem to indicate that
782    *   the amount of released multi node lists is negligible in comparison
783    *   to single node releases.
784    */
785 }
786
787 /* --- single page allocator --- */
788 static void
789 allocator_slab_stack_push (Allocator *allocator,
790                            guint      ix,
791                            SlabInfo  *sinfo)
792 {
793   /* insert slab at slab ring head */
794   if (!allocator->slab_stack[ix])
795     {
796       sinfo->next = sinfo;
797       sinfo->prev = sinfo;
798     }
799   else
800     {
801       SlabInfo *next = allocator->slab_stack[ix], *prev = next->prev;
802       next->prev = sinfo;
803       prev->next = sinfo;
804       sinfo->next = next;
805       sinfo->prev = prev;
806     }
807   allocator->slab_stack[ix] = sinfo;
808 }
809
810 static void
811 allocator_add_slab (Allocator *allocator,
812                     guint      ix,
813                     guint      chunk_size)
814 {
815   SlabInfo *sinfo;
816   gsize padding, n_chunks, color = 0;
817   gsize page_size = SLAB_PAGE_SIZE (allocator, chunk_size);
818   /* allocate 1 page for the chunks and the slab */
819   gpointer aligned_memory = allocator_memalign (page_size, page_size - NATIVE_MALLOC_PADDING);
820   guint8 *mem = aligned_memory;
821   if (!mem)
822     g_error ("%s: failed to allocate %lu bytes: %s", "GSlicedMemory", (gulong) (page_size - NATIVE_MALLOC_PADDING), g_strerror (errno));
823   /* mask page adress */
824   gsize addr = ((gsize) mem / page_size) * page_size;
825   /* assert alignment */
826   g_assert (aligned_memory == (gpointer) addr);
827   /* basic slab info setup */
828   sinfo = (SlabInfo*) (mem + page_size - SLAB_INFO_SIZE);
829   sinfo->n_allocated = 0;
830   sinfo->chunks = NULL;
831   /* figure cache colorization */
832   n_chunks = ((guint8*) sinfo - mem) / chunk_size;
833   padding = ((guint8*) sinfo - mem) - n_chunks * chunk_size;
834   if (padding)
835     {
836       color = (allocator->color_accu * P2ALIGNMENT) % padding;
837       allocator->color_accu += 1;       /* alternatively: + 0x7fffffff */
838     }
839   /* add chunks to free list */
840   ChunkLink *chunk = (ChunkLink*) (mem + color);
841   guint i;
842   sinfo->chunks = chunk;
843   for (i = 0; i < n_chunks - 1; i++)
844     {
845       chunk->next = (ChunkLink*) ((guint8*) chunk + chunk_size);
846       chunk = chunk->next;
847     }
848   chunk->next = NULL;   /* last chunk */
849   /* add slab to slab ring */
850   allocator_slab_stack_push (allocator, ix, sinfo);
851 }
852
853 static gpointer
854 slab_allocator_alloc_chunk (guint chunk_size)
855 {
856   guint ix = SLAB_INDEX (allocator, chunk_size);
857   /* ensure non-empty slab */
858   if (!allocator->slab_stack[ix] || !allocator->slab_stack[ix]->chunks)
859     allocator_add_slab (allocator, ix, chunk_size);
860   /* allocate chunk */
861   ChunkLink *chunk = allocator->slab_stack[ix]->chunks;
862   allocator->slab_stack[ix]->chunks = chunk->next;
863   allocator->slab_stack[ix]->n_allocated++;
864   /* rotate empty slabs */
865   if (!allocator->slab_stack[ix]->chunks)
866     allocator->slab_stack[ix] = allocator->slab_stack[ix]->next;
867   return chunk;
868 }
869
870 static void
871 slab_allocator_free_chunk (guint    chunk_size,
872                            gpointer mem)
873 {
874   guint ix = SLAB_INDEX (allocator, chunk_size);
875   gsize page_size = SLAB_PAGE_SIZE (allocator, chunk_size);
876   gsize addr = ((gsize) mem / page_size) * page_size;
877   /* mask page adress */
878   guint8 *page = (guint8*) addr;
879   SlabInfo *sinfo = (SlabInfo*) (page + page_size - SLAB_INFO_SIZE);
880   /* assert valid chunk count */
881   g_assert (sinfo->n_allocated > 0);
882   /* add chunk to free list */
883   gboolean was_empty = sinfo->chunks == NULL;
884   ChunkLink *chunk = (ChunkLink*) mem;
885   chunk->next = sinfo->chunks;
886   sinfo->chunks = chunk;
887   sinfo->n_allocated--;
888   /* keep slab ring partially sorted, empty slabs at end */
889   if (was_empty)
890     {
891       /* unlink slab */
892       SlabInfo *next = sinfo->next, *prev = sinfo->prev;
893       next->prev = prev;
894       prev->next = next;
895       if (allocator->slab_stack[ix] == sinfo)
896         allocator->slab_stack[ix] = next == sinfo ? NULL : next;
897       /* insert slab at head */
898       allocator_slab_stack_push (allocator, ix, sinfo);
899     }
900   /* eagerly free complete unused slabs */
901   if (!sinfo->n_allocated)
902     {
903       /* unlink slab */
904       SlabInfo *next = sinfo->next, *prev = sinfo->prev;
905       next->prev = prev;
906       prev->next = next;
907       if (allocator->slab_stack[ix] == sinfo)
908         allocator->slab_stack[ix] = next == sinfo ? NULL : next;
909       /* free slab */
910       allocator_memfree (page_size, page);
911     }
912 }
913
914 /* --- memalign implementation --- */
915 #include <malloc.h>             /* memalign() */
916
917 /* from config.h:
918  * define HAVE_POSIX_MEMALIGN     1     // if free(posix_memalign(3)) works, <stdlib.h>
919  * define HAVE_MEMALIGN           1     // if free(memalign(3)) works, <malloc.h>
920  * define HAVE_VALLOC             1     // if free(valloc(3)) works, <stdlib.h> or <malloc.h>
921  * if none is provided, we implement malloc(3)-based alloc-only page alignment
922  */
923
924 #if !(HAVE_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC)
925 static GTrashStack *compat_valloc_trash = NULL;
926 #endif
927
928 static gpointer
929 allocator_memalign (gsize alignment,
930                     gsize memsize)
931 {
932   gpointer aligned_memory = NULL;
933   gint err = ENOMEM;
934 #if     HAVE_POSIX_MEMALIGN
935   err = posix_memalign (&aligned_memory, alignment, memsize);
936 #elif   HAVE_MEMALIGN
937   errno = 0;
938   aligned_memory = memalign (alignment, memsize);
939   err = errno;
940 #elif   HAVE_VALLOC
941   errno = 0;
942   aligned_memory = valloc (memsize);
943   err = errno;
944 #else
945   /* simplistic non-freeing page allocator */
946   g_assert (alignment == sys_page_size);
947   g_assert (memsize <= sys_page_size);
948   if (!compat_valloc_trash)
949     {
950       const guint n_pages = 16;
951       guint8 *mem = malloc (n_pages * sys_page_size);
952       err = errno;
953       if (mem)
954         {
955           gint i = n_pages;
956           guint8 *amem = (guint8*) ALIGN ((gsize) mem, sys_page_size);
957           if (amem != mem)
958             i--;        /* mem wasn't page aligned */
959           while (--i >= 0)
960             g_trash_stack_push (&compat_valloc_trash, amem + i * sys_page_size);
961         }
962     }
963   aligned_memory = g_trash_stack_pop (&compat_valloc_trash);
964 #endif
965   if (!aligned_memory)
966     errno = err;
967   return aligned_memory;
968 }
969
970 static void
971 allocator_memfree (gsize    memsize,
972                    gpointer mem)
973 {
974 #if     HAVE_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC
975   free (mem);
976 #else
977   g_assert (memsize <= sys_page_size);
978   g_trash_stack_push (&compat_valloc_trash, mem);
979 #endif
980 }
981
982 #define __G_SLICE_C__
983 #include "galiasdef.c"