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