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