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