/[zanavi_public1]/navit/navit/support/glib/gslice.c
ZANavi

Contents of /navit/navit/support/glib/gslice.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2 - (show annotations) (download)
Fri Oct 28 21:19:04 2011 UTC (12 years, 5 months ago) by zoff99
File MIME type: text/plain
File size: 52750 byte(s)
import files
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 #if defined HAVE_POSIX_MEMALIGN && defined POSIX_MEMALIGN_WITH_COMPLIANT_ALLOCS
24 # define HAVE_COMPLIANT_POSIX_MEMALIGN 1
25 #endif
26
27 #ifdef HAVE_COMPLIANT_POSIX_MEMALIGN
28 #define _XOPEN_SOURCE 600 /* posix_memalign() */
29 #endif
30 #include <stdlib.h> /* posix_memalign() */
31 #include <string.h>
32 #include <errno.h>
33 #include "gmem.h" /* gslice.h */
34 #include "gthreadprivate.h"
35 #include "glib.h"
36 #include "galias.h"
37 #ifdef HAVE_UNISTD_H
38 #include <unistd.h> /* sysconf() */
39 #endif
40 #ifdef G_OS_WIN32
41 #include <windows.h>
42 #include <process.h>
43 #endif
44
45 #include <stdio.h> /* fputs/fprintf */
46
47
48 /* the GSlice allocator is split up into 4 layers, roughly modelled after the slab
49 * allocator and magazine extensions as outlined in:
50 * + [Bonwick94] Jeff Bonwick, The slab allocator: An object-caching kernel
51 * memory allocator. USENIX 1994, http://citeseer.ist.psu.edu/bonwick94slab.html
52 * + [Bonwick01] Bonwick and Jonathan Adams, Magazines and vmem: Extending the
53 * slab allocator to many cpu's and arbitrary resources.
54 * USENIX 2001, http://citeseer.ist.psu.edu/bonwick01magazines.html
55 * the layers are:
56 * - the thread magazines. for each (aligned) chunk size, a magazine (a list)
57 * of recently freed and soon to be allocated chunks is maintained per thread.
58 * this way, most alloc/free requests can be quickly satisfied from per-thread
59 * free lists which only require one g_private_get() call to retrive the
60 * thread handle.
61 * - the magazine cache. allocating and freeing chunks to/from threads only
62 * occours at magazine sizes from a global depot of magazines. the depot
63 * maintaines a 15 second working set of allocated magazines, so full
64 * magazines are not allocated and released too often.
65 * the chunk size dependent magazine sizes automatically adapt (within limits,
66 * see [3]) to lock contention to properly scale performance across a variety
67 * of SMP systems.
68 * - the slab allocator. this allocator allocates slabs (blocks of memory) close
69 * to the system page size or multiples thereof which have to be page aligned.
70 * the blocks are divided into smaller chunks which are used to satisfy
71 * allocations from the upper layers. the space provided by the reminder of
72 * the chunk size division is used for cache colorization (random distribution
73 * of chunk addresses) to improve processor cache utilization. multiple slabs
74 * with the same chunk size are kept in a partially sorted ring to allow O(1)
75 * freeing and allocation of chunks (as long as the allocation of an entirely
76 * new slab can be avoided).
77 * - the page allocator. on most modern systems, posix_memalign(3) or
78 * memalign(3) should be available, so this is used to allocate blocks with
79 * system page size based alignments and sizes or multiples thereof.
80 * if no memalign variant is provided, valloc() is used instead and
81 * block sizes are limited to the system page size (no multiples thereof).
82 * as a fallback, on system without even valloc(), a malloc(3)-based page
83 * allocator with alloc-only behaviour is used.
84 *
85 * NOTES:
86 * [1] some systems memalign(3) implementations may rely on boundary tagging for
87 * the handed out memory chunks. to avoid excessive page-wise fragmentation,
88 * we reserve 2 * sizeof (void*) per block size for the systems memalign(3),
89 * specified in NATIVE_MALLOC_PADDING.
90 * [2] using the slab allocator alone already provides for a fast and efficient
91 * allocator, it doesn't properly scale beyond single-threaded uses though.
92 * also, the slab allocator implements eager free(3)-ing, i.e. does not
93 * provide any form of caching or working set maintenance. so if used alone,
94 * it's vulnerable to trashing for sequences of balanced (alloc, free) pairs
95 * at certain thresholds.
96 * [3] magazine sizes are bound by an implementation specific minimum size and
97 * a chunk size specific maximum to limit magazine storage sizes to roughly
98 * 16KB.
99 * [4] allocating ca. 8 chunks per block/page keeps a good balance between
100 * external and internal fragmentation (<= 12.5%). [Bonwick94]
101 */
102
103 /* --- macros and constants --- */
104 #define LARGEALIGNMENT (256)
105 #define P2ALIGNMENT (2 * sizeof (gsize)) /* fits 2 pointers (assumed to be 2 * GLIB_SIZEOF_SIZE_T below) */
106 #define ALIGN(size, base) ((base) * (gsize) (((size) + (base) - 1) / (base)))
107 #define NATIVE_MALLOC_PADDING 0 /* per-page padding left for native malloc(3) see [1] */
108 #define SLAB_INFO_SIZE P2ALIGN (sizeof (SlabInfo) + NATIVE_MALLOC_PADDING)
109 #define MAX_MAGAZINE_SIZE (256) /* see [3] and allocator_get_magazine_threshold() for this */
110 #define MIN_MAGAZINE_SIZE (4)
111 #define MAX_STAMP_COUNTER (7) /* distributes the load of gettimeofday() */
112 #define MAX_SLAB_CHUNK_SIZE(al) (((al)->max_page_size - SLAB_INFO_SIZE) / 8) /* we want at last 8 chunks per page, see [4] */
113 #define MAX_SLAB_INDEX(al) (SLAB_INDEX (al, MAX_SLAB_CHUNK_SIZE (al)) + 1)
114 #define SLAB_INDEX(al, asize) ((asize) / P2ALIGNMENT - 1) /* asize must be P2ALIGNMENT aligned */
115 #define SLAB_CHUNK_SIZE(al, ix) (((ix) + 1) * P2ALIGNMENT)
116 #define SLAB_BPAGE_SIZE(al,csz) (8 * (csz) + SLAB_INFO_SIZE)
117
118 /* optimized version of ALIGN (size, P2ALIGNMENT) */
119 #if GLIB_SIZEOF_SIZE_T * 2 == 8 /* P2ALIGNMENT */
120 #define P2ALIGN(size) (((size) + 0x7) & ~(gsize) 0x7)
121 #elif GLIB_SIZEOF_SIZE_T * 2 == 16 /* P2ALIGNMENT */
122 #define P2ALIGN(size) (((size) + 0xf) & ~(gsize) 0xf)
123 #else
124 #define P2ALIGN(size) ALIGN (size, P2ALIGNMENT)
125 #endif
126
127 /* special helpers to avoid gmessage.c dependency */
128 static void mem_error (const char *format, ...) G_GNUC_PRINTF (1,2);
129 #define mem_assert(cond) do { if (G_LIKELY (cond)) ; else mem_error ("assertion failed: %s", #cond); } while (0)
130
131 /* --- structures --- */
132 typedef struct _ChunkLink ChunkLink;
133 typedef struct _SlabInfo SlabInfo;
134 typedef struct _CachedMagazine CachedMagazine;
135 struct _ChunkLink {
136 ChunkLink *next;
137 ChunkLink *data;
138 };
139 struct _SlabInfo {
140 ChunkLink *chunks;
141 guint n_allocated;
142 SlabInfo *next, *prev;
143 };
144 typedef struct {
145 ChunkLink *chunks;
146 gsize count; /* approximative chunks list length */
147 } Magazine;
148 typedef struct {
149 Magazine *magazine1; /* array of MAX_SLAB_INDEX (allocator) */
150 Magazine *magazine2; /* array of MAX_SLAB_INDEX (allocator) */
151 } ThreadMemory;
152 typedef struct {
153 gboolean always_malloc;
154 gboolean bypass_magazines;
155 gboolean debug_blocks;
156 gsize working_set_msecs;
157 guint color_increment;
158 } SliceConfig;
159 typedef struct {
160 /* const after initialization */
161 gsize min_page_size, max_page_size;
162 SliceConfig config;
163 gsize max_slab_chunk_size_for_magazine_cache;
164 /* magazine cache */
165 GMutex *magazine_mutex;
166 ChunkLink **magazines; /* array of MAX_SLAB_INDEX (allocator) */
167 guint *contention_counters; /* array of MAX_SLAB_INDEX (allocator) */
168 gint mutex_counter;
169 guint stamp_counter;
170 guint last_stamp;
171 /* slab allocator */
172 GMutex *slab_mutex;
173 SlabInfo **slab_stack; /* array of MAX_SLAB_INDEX (allocator) */
174 guint color_accu;
175 } Allocator;
176
177 /* --- g-slice prototypes --- */
178 static gpointer slab_allocator_alloc_chunk (gsize chunk_size);
179 static void slab_allocator_free_chunk (gsize chunk_size,
180 gpointer mem);
181 static void private_thread_memory_cleanup (gpointer data);
182 static gpointer allocator_memalign (gsize alignment,
183 gsize memsize);
184 static void allocator_memfree (gsize memsize,
185 gpointer mem);
186 static inline void magazine_cache_update_stamp (void);
187 static inline gsize allocator_get_magazine_threshold (Allocator *allocator,
188 guint ix);
189
190 /* --- g-slice memory checker --- */
191 static void smc_notify_alloc (void *pointer,
192 size_t size);
193 static int smc_notify_free (void *pointer,
194 size_t size);
195
196 /* --- variables --- */
197 static GPrivate *private_thread_memory = NULL;
198 static gsize sys_page_size = 0;
199 static gsize sys_valignment = ((32*1024*1024));
200 static guint8 *virtual_mem = 0;
201 static Allocator allocator[1] = { { 0, }, };
202 static SliceConfig slice_config = {
203 FALSE, /* always_malloc */
204 FALSE, /* bypass_magazines */
205 FALSE, /* debug_blocks */
206 15 * 1000, /* working_set_msecs */
207 1, /* color increment, alt: 0x7fffffff */
208 };
209 static GMutex *smc_tree_mutex = NULL; /* mutex for G_SLICE=debug-blocks */
210
211 /* --- auxillary funcitons --- */
212 void
213 g_slice_set_config (GSliceConfig ckey,
214 gint64 value)
215 {
216 g_return_if_fail (sys_page_size == 0);
217 switch (ckey)
218 {
219 case G_SLICE_CONFIG_ALWAYS_MALLOC:
220 slice_config.always_malloc = value != 0;
221 break;
222 case G_SLICE_CONFIG_BYPASS_MAGAZINES:
223 slice_config.bypass_magazines = value != 0;
224 break;
225 case G_SLICE_CONFIG_WORKING_SET_MSECS:
226 slice_config.working_set_msecs = value;
227 break;
228 case G_SLICE_CONFIG_COLOR_INCREMENT:
229 slice_config.color_increment = value;
230 default: ;
231 }
232 }
233
234 gint64
235 g_slice_get_config (GSliceConfig ckey)
236 {
237 switch (ckey)
238 {
239 case G_SLICE_CONFIG_ALWAYS_MALLOC:
240 return slice_config.always_malloc;
241 case G_SLICE_CONFIG_BYPASS_MAGAZINES:
242 return slice_config.bypass_magazines;
243 case G_SLICE_CONFIG_WORKING_SET_MSECS:
244 return slice_config.working_set_msecs;
245 case G_SLICE_CONFIG_CHUNK_SIZES:
246 return MAX_SLAB_INDEX (allocator);
247 case G_SLICE_CONFIG_COLOR_INCREMENT:
248 return slice_config.color_increment;
249 default:
250 return 0;
251 }
252 }
253
254 gint64*
255 g_slice_get_config_state (GSliceConfig ckey,
256 gint64 address,
257 guint *n_values)
258 {
259 guint i = 0;
260 g_return_val_if_fail (n_values != NULL, NULL);
261 *n_values = 0;
262 switch (ckey)
263 {
264 gint64 array[64];
265 case G_SLICE_CONFIG_CONTENTION_COUNTER:
266 array[i++] = SLAB_CHUNK_SIZE (allocator, address);
267 array[i++] = allocator->contention_counters[address];
268 array[i++] = allocator_get_magazine_threshold (allocator, address);
269 *n_values = i;
270 return g_memdup (array, sizeof (array[0]) * *n_values);
271 default:
272 return NULL;
273 }
274 }
275
276 static void
277 slice_config_init (SliceConfig *config)
278 {
279 /* don't use g_malloc/g_message here */
280 #if NOT_NEEDED_FOR_NAVIT
281 gchar buffer[1024];
282 const gchar *val = _g_getenv_nomalloc ("G_SLICE", buffer);
283 const GDebugKey keys[] = {
284 { "always-malloc", 1 << 0 },
285 { "debug-blocks", 1 << 1 },
286 };
287 gint flags = !val ? 0 : g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
288 #endif
289 *config = slice_config;
290 #if NOT_NEEDED_FOR_NAVIT
291 if (flags & (1 << 0)) /* always-malloc */
292 config->always_malloc = TRUE;
293 if (flags & (1 << 1)) /* debug-blocks */
294 config->debug_blocks = TRUE;
295 #endif
296 }
297
298 static void
299 g_slice_init_nomessage (void)
300 {
301 /* we may not use g_error() or friends here */
302 mem_assert (sys_page_size == 0);
303 mem_assert (MIN_MAGAZINE_SIZE >= 4);
304
305 #ifdef G_OS_WIN32
306 {
307 SYSTEM_INFO system_info;
308 GetSystemInfo (&system_info);
309 sys_page_size = system_info.dwPageSize;
310 virtual_mem = VirtualAlloc (NULL, sys_valignment, MEM_RESERVE, PAGE_NOACCESS);
311 // sys_valignment = system_info.dwAllocationGranularity;
312 //sys_valignment = 2*1024*1024 + sys_page_size;
313 printf("SPAGE_SIZE: %d, SVALIGN:%d\n", sys_page_size, sys_valignment);
314 }
315 #else
316 sys_page_size = sysconf (_SC_PAGESIZE); /* = sysconf (_SC_PAGE_SIZE); = getpagesize(); */
317 sys_valignment = sys_page_size;
318 #endif
319 mem_assert (sys_page_size >= 2 * LARGEALIGNMENT);
320 mem_assert ((sys_page_size & (sys_page_size - 1)) == 0);
321 slice_config_init (&allocator->config);
322 allocator->min_page_size = sys_page_size;
323 #if HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN
324 /* allow allocation of pages up to 8KB (with 8KB alignment).
325 * this is useful because many medium to large sized structures
326 * fit less than 8 times (see [4]) into 4KB pages.
327 * we allow very small page sizes here, to reduce wastage in
328 * threads if only small allocations are required (this does
329 * bear the risk of incresing allocation times and fragmentation
330 * though).
331 */
332 allocator->min_page_size = MAX (allocator->min_page_size, 4096);
333 allocator->max_page_size = MAX (allocator->min_page_size, 8192);
334 allocator->min_page_size = MIN (allocator->min_page_size, 128);
335 #else
336 /* we can only align to system page size */
337 allocator->max_page_size = sys_page_size;
338 #endif
339 allocator->magazine_mutex = NULL; /* _g_slice_thread_init_nomessage() */
340 allocator->magazines = g_new0 (ChunkLink*, MAX_SLAB_INDEX (allocator));
341 allocator->contention_counters = g_new0 (guint, MAX_SLAB_INDEX (allocator));
342 allocator->mutex_counter = 0;
343 allocator->stamp_counter = MAX_STAMP_COUNTER; /* force initial update */
344 allocator->last_stamp = 0;
345 allocator->slab_mutex = NULL; /* _g_slice_thread_init_nomessage() */
346 allocator->slab_stack = g_new0 (SlabInfo*, MAX_SLAB_INDEX (allocator));
347 allocator->color_accu = 0;
348 magazine_cache_update_stamp();
349 /* values cached for performance reasons */
350 allocator->max_slab_chunk_size_for_magazine_cache = MAX_SLAB_CHUNK_SIZE (allocator);
351 if (allocator->config.always_malloc || allocator->config.bypass_magazines)
352 allocator->max_slab_chunk_size_for_magazine_cache = 0; /* non-optimized cases */
353 /* at this point, g_mem_gc_friendly() should be initialized, this
354 * should have been accomplished by the above g_malloc/g_new calls
355 */
356 }
357
358 static inline guint
359 allocator_categorize (gsize aligned_chunk_size)
360 {
361 /* speed up the likely path */
362 if (G_LIKELY (aligned_chunk_size && aligned_chunk_size <= allocator->max_slab_chunk_size_for_magazine_cache))
363 return 1; /* use magazine cache */
364
365 /* the above will fail (max_slab_chunk_size_for_magazine_cache == 0) if the
366 * allocator is still uninitialized, or if we are not configured to use the
367 * magazine cache.
368 */
369 if (!sys_page_size)
370 g_slice_init_nomessage ();
371 if (!allocator->config.always_malloc &&
372 aligned_chunk_size &&
373 aligned_chunk_size <= MAX_SLAB_CHUNK_SIZE (allocator))
374 {
375 if (allocator->config.bypass_magazines)
376 return 2; /* use slab allocator, see [2] */
377 return 1; /* use magazine cache */
378 }
379 return 0; /* use malloc() */
380 }
381
382 void
383 _g_slice_thread_init_nomessage (void)
384 {
385 /* we may not use g_error() or friends here */
386 if (!sys_page_size)
387 g_slice_init_nomessage();
388 else
389 {
390 /* g_slice_init_nomessage() has been called already, probably due
391 * to a g_slice_alloc1() before g_thread_init().
392 */
393 }
394 private_thread_memory = g_private_new (private_thread_memory_cleanup);
395 allocator->magazine_mutex = g_mutex_new();
396 allocator->slab_mutex = g_mutex_new();
397 if (allocator->config.debug_blocks)
398 smc_tree_mutex = g_mutex_new();
399 }
400
401 static inline void
402 g_mutex_lock_a (GMutex *mutex,
403 guint *contention_counter)
404 {
405 gboolean contention = FALSE;
406 if (!g_mutex_trylock (mutex))
407 {
408 g_mutex_lock (mutex);
409 contention = TRUE;
410 }
411 if (contention)
412 {
413 allocator->mutex_counter++;
414 if (allocator->mutex_counter >= 1) /* quickly adapt to contention */
415 {
416 allocator->mutex_counter = 0;
417 *contention_counter = MIN (*contention_counter + 1, MAX_MAGAZINE_SIZE);
418 }
419 }
420 else /* !contention */
421 {
422 allocator->mutex_counter--;
423 if (allocator->mutex_counter < -11) /* moderately recover magazine sizes */
424 {
425 allocator->mutex_counter = 0;
426 *contention_counter = MAX (*contention_counter, 1) - 1;
427 }
428 }
429 }
430
431 static inline ThreadMemory*
432 thread_memory_from_self (void)
433 {
434 ThreadMemory *tmem = g_private_get (private_thread_memory);
435 if (G_UNLIKELY (!tmem))
436 {
437 static ThreadMemory *single_thread_memory = NULL; /* remember single-thread info for multi-threaded case */
438 if (single_thread_memory && g_thread_supported ())
439 {
440 g_mutex_lock (allocator->slab_mutex);
441 if (single_thread_memory)
442 {
443 /* GSlice has been used before g_thread_init(), and now
444 * we are running threaded. to cope with it, use the saved
445 * thread memory structure from when we weren't threaded.
446 */
447 tmem = single_thread_memory;
448 single_thread_memory = NULL; /* slab_mutex protected when multi-threaded */
449 }
450 g_mutex_unlock (allocator->slab_mutex);
451 }
452 if (!tmem)
453 {
454 const guint n_magazines = MAX_SLAB_INDEX (allocator);
455 tmem = g_malloc0 (sizeof (ThreadMemory) + sizeof (Magazine) * 2 * n_magazines);
456 tmem->magazine1 = (Magazine*) (tmem + 1);
457 tmem->magazine2 = &tmem->magazine1[n_magazines];
458 }
459 /* g_private_get/g_private_set works in the single-threaded xor the multi-
460 * threaded case. but not *across* g_thread_init(), after multi-thread
461 * initialization it returns NULL for previously set single-thread data.
462 */
463 g_private_set (private_thread_memory, tmem);
464 /* save single-thread thread memory structure, in case we need to
465 * pick it up again after multi-thread initialization happened.
466 */
467 if (!single_thread_memory && !g_thread_supported ())
468 single_thread_memory = tmem; /* no slab_mutex created yet */
469 }
470 return tmem;
471 }
472
473 static inline ChunkLink*
474 magazine_chain_pop_head (ChunkLink **magazine_chunks)
475 {
476 /* magazine chains are linked via ChunkLink->next.
477 * each ChunkLink->data of the toplevel chain may point to a subchain,
478 * linked via ChunkLink->next. ChunkLink->data of the subchains just
479 * contains uninitialized junk.
480 */
481 ChunkLink *chunk = (*magazine_chunks)->data;
482 if (G_UNLIKELY (chunk))
483 {
484 /* allocating from freed list */
485 (*magazine_chunks)->data = chunk->next;
486 }
487 else
488 {
489 chunk = *magazine_chunks;
490 *magazine_chunks = chunk->next;
491 }
492 return chunk;
493 }
494
495 #if 0 /* useful for debugging */
496 static guint
497 magazine_count (ChunkLink *head)
498 {
499 guint count = 0;
500 if (!head)
501 return 0;
502 while (head)
503 {
504 ChunkLink *child = head->data;
505 count += 1;
506 for (child = head->data; child; child = child->next)
507 count += 1;
508 head = head->next;
509 }
510 return count;
511 }
512 #endif
513
514 static inline gsize
515 allocator_get_magazine_threshold (Allocator *allocator,
516 guint ix)
517 {
518 /* the magazine size calculated here has a lower bound of MIN_MAGAZINE_SIZE,
519 * which is required by the implementation. also, for moderately sized chunks
520 * (say >= 64 bytes), magazine sizes shouldn't be much smaller then the number
521 * of chunks available per page/2 to avoid excessive traffic in the magazine
522 * cache for small to medium sized structures.
523 * the upper bound of the magazine size is effectively provided by
524 * MAX_MAGAZINE_SIZE. for larger chunks, this number is scaled down so that
525 * the content of a single magazine doesn't exceed ca. 16KB.
526 */
527 gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
528 guint threshold = MAX (MIN_MAGAZINE_SIZE, allocator->max_page_size / MAX (5 * chunk_size, 5 * 32));
529 guint contention_counter = allocator->contention_counters[ix];
530 if (G_UNLIKELY (contention_counter)) /* single CPU bias */
531 {
532 /* adapt contention counter thresholds to chunk sizes */
533 contention_counter = contention_counter * 64 / chunk_size;
534 threshold = MAX (threshold, contention_counter);
535 }
536 return threshold;
537 }
538
539 /* --- magazine cache --- */
540 static inline void
541 magazine_cache_update_stamp (void)
542 {
543 if (allocator->stamp_counter >= MAX_STAMP_COUNTER)
544 {
545 GTimeVal tv;
546 g_get_current_time (&tv);
547 allocator->last_stamp = tv.tv_sec * 1000 + tv.tv_usec / 1000; /* milli seconds */
548 allocator->stamp_counter = 0;
549 }
550 else
551 allocator->stamp_counter++;
552 }
553
554 static inline ChunkLink*
555 magazine_chain_prepare_fields (ChunkLink *magazine_chunks)
556 {
557 ChunkLink *chunk1;
558 ChunkLink *chunk2;
559 ChunkLink *chunk3;
560 ChunkLink *chunk4;
561 /* checked upon initialization: mem_assert (MIN_MAGAZINE_SIZE >= 4); */
562 /* ensure a magazine with at least 4 unused data pointers */
563 chunk1 = magazine_chain_pop_head (&magazine_chunks);
564 chunk2 = magazine_chain_pop_head (&magazine_chunks);
565 chunk3 = magazine_chain_pop_head (&magazine_chunks);
566 chunk4 = magazine_chain_pop_head (&magazine_chunks);
567 chunk4->next = magazine_chunks;
568 chunk3->next = chunk4;
569 chunk2->next = chunk3;
570 chunk1->next = chunk2;
571 return chunk1;
572 }
573
574 /* access the first 3 fields of a specially prepared magazine chain */
575 #define magazine_chain_prev(mc) ((mc)->data)
576 #define magazine_chain_stamp(mc) ((mc)->next->data)
577 #define magazine_chain_uint_stamp(mc) GPOINTER_TO_UINT ((mc)->next->data)
578 #define magazine_chain_next(mc) ((mc)->next->next->data)
579 #define magazine_chain_count(mc) ((mc)->next->next->next->data)
580
581 static void
582 magazine_cache_trim (Allocator *allocator,
583 guint ix,
584 guint stamp)
585 {
586 /* g_mutex_lock (allocator->mutex); done by caller */
587 /* trim magazine cache from tail */
588 ChunkLink *current = magazine_chain_prev (allocator->magazines[ix]);
589 ChunkLink *trash = NULL;
590 while (ABS (stamp - magazine_chain_uint_stamp (current)) >= allocator->config.working_set_msecs)
591 {
592 /* unlink */
593 ChunkLink *prev = magazine_chain_prev (current);
594 ChunkLink *next = magazine_chain_next (current);
595 magazine_chain_next (prev) = next;
596 magazine_chain_prev (next) = prev;
597 /* clear special fields, put on trash stack */
598 magazine_chain_next (current) = NULL;
599 magazine_chain_count (current) = NULL;
600 magazine_chain_stamp (current) = NULL;
601 magazine_chain_prev (current) = trash;
602 trash = current;
603 /* fixup list head if required */
604 if (current == allocator->magazines[ix])
605 {
606 allocator->magazines[ix] = NULL;
607 break;
608 }
609 current = prev;
610 }
611 g_mutex_unlock (allocator->magazine_mutex);
612 /* free trash */
613 if (trash)
614 {
615 const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
616 g_mutex_lock (allocator->slab_mutex);
617 while (trash)
618 {
619 current = trash;
620 trash = magazine_chain_prev (current);
621 magazine_chain_prev (current) = NULL; /* clear special field */
622 while (current)
623 {
624 ChunkLink *chunk = magazine_chain_pop_head (&current);
625 slab_allocator_free_chunk (chunk_size, chunk);
626 }
627 }
628 g_mutex_unlock (allocator->slab_mutex);
629 }
630 }
631
632 static void
633 magazine_cache_push_magazine (guint ix,
634 ChunkLink *magazine_chunks,
635 gsize count) /* must be >= MIN_MAGAZINE_SIZE */
636 {
637 ChunkLink *current = magazine_chain_prepare_fields (magazine_chunks);
638 ChunkLink *next, *prev;
639 g_mutex_lock (allocator->magazine_mutex);
640 /* add magazine at head */
641 next = allocator->magazines[ix];
642 if (next)
643 prev = magazine_chain_prev (next);
644 else
645 next = prev = current;
646 magazine_chain_next (prev) = current;
647 magazine_chain_prev (next) = current;
648 magazine_chain_prev (current) = prev;
649 magazine_chain_next (current) = next;
650 magazine_chain_count (current) = (gpointer) count;
651 /* stamp magazine */
652 magazine_cache_update_stamp();
653 magazine_chain_stamp (current) = GUINT_TO_POINTER (allocator->last_stamp);
654 allocator->magazines[ix] = current;
655 /* free old magazines beyond a certain threshold */
656 magazine_cache_trim (allocator, ix, allocator->last_stamp);
657 /* g_mutex_unlock (allocator->mutex); was done by magazine_cache_trim() */
658 }
659
660 static ChunkLink*
661 magazine_cache_pop_magazine (guint ix,
662 gsize *countp)
663 {
664 g_mutex_lock_a (allocator->magazine_mutex, &allocator->contention_counters[ix]);
665 if (!allocator->magazines[ix])
666 {
667 guint magazine_threshold = allocator_get_magazine_threshold (allocator, ix);
668 gsize i, chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
669 ChunkLink *chunk, *head;
670 g_mutex_unlock (allocator->magazine_mutex);
671 g_mutex_lock (allocator->slab_mutex);
672 head = slab_allocator_alloc_chunk (chunk_size);
673 head->data = NULL;
674 chunk = head;
675 for (i = 1; i < magazine_threshold; i++)
676 {
677 chunk->next = slab_allocator_alloc_chunk (chunk_size);
678 chunk = chunk->next;
679 chunk->data = NULL;
680 }
681 chunk->next = NULL;
682 g_mutex_unlock (allocator->slab_mutex);
683 *countp = i;
684 return head;
685 }
686 else
687 {
688 ChunkLink *current = allocator->magazines[ix];
689 ChunkLink *prev = magazine_chain_prev (current);
690 ChunkLink *next = magazine_chain_next (current);
691 /* unlink */
692 magazine_chain_next (prev) = next;
693 magazine_chain_prev (next) = prev;
694 allocator->magazines[ix] = next == current ? NULL : next;
695 g_mutex_unlock (allocator->magazine_mutex);
696 /* clear special fields and hand out */
697 *countp = (gsize) magazine_chain_count (current);
698 magazine_chain_prev (current) = NULL;
699 magazine_chain_next (current) = NULL;
700 magazine_chain_count (current) = NULL;
701 magazine_chain_stamp (current) = NULL;
702 return current;
703 }
704 }
705
706 /* --- thread magazines --- */
707 static void
708 private_thread_memory_cleanup (gpointer data)
709 {
710 ThreadMemory *tmem = data;
711 const guint n_magazines = MAX_SLAB_INDEX (allocator);
712 guint ix;
713 for (ix = 0; ix < n_magazines; ix++)
714 {
715 Magazine *mags[2];
716 guint j;
717 mags[0] = &tmem->magazine1[ix];
718 mags[1] = &tmem->magazine2[ix];
719 for (j = 0; j < 2; j++)
720 {
721 Magazine *mag = mags[j];
722 if (mag->count >= MIN_MAGAZINE_SIZE)
723 magazine_cache_push_magazine (ix, mag->chunks, mag->count);
724 else
725 {
726 const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
727 g_mutex_lock (allocator->slab_mutex);
728 while (mag->chunks)
729 {
730 ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
731 slab_allocator_free_chunk (chunk_size, chunk);
732 }
733 g_mutex_unlock (allocator->slab_mutex);
734 }
735 }
736 }
737 g_free (tmem);
738 }
739
740 static void
741 thread_memory_magazine1_reload (ThreadMemory *tmem,
742 guint ix)
743 {
744 Magazine *mag = &tmem->magazine1[ix];
745 mem_assert (mag->chunks == NULL); /* ensure that we may reset mag->count */
746 mag->count = 0;
747 mag->chunks = magazine_cache_pop_magazine (ix, &mag->count);
748 }
749
750 static void
751 thread_memory_magazine2_unload (ThreadMemory *tmem,
752 guint ix)
753 {
754 Magazine *mag = &tmem->magazine2[ix];
755 magazine_cache_push_magazine (ix, mag->chunks, mag->count);
756 mag->chunks = NULL;
757 mag->count = 0;
758 }
759
760 static inline void
761 thread_memory_swap_magazines (ThreadMemory *tmem,
762 guint ix)
763 {
764 Magazine xmag = tmem->magazine1[ix];
765 tmem->magazine1[ix] = tmem->magazine2[ix];
766 tmem->magazine2[ix] = xmag;
767 }
768
769 static inline gboolean
770 thread_memory_magazine1_is_empty (ThreadMemory *tmem,
771 guint ix)
772 {
773 return tmem->magazine1[ix].chunks == NULL;
774 }
775
776 static inline gboolean
777 thread_memory_magazine2_is_full (ThreadMemory *tmem,
778 guint ix)
779 {
780 return tmem->magazine2[ix].count >= allocator_get_magazine_threshold (allocator, ix);
781 }
782
783 static inline gpointer
784 thread_memory_magazine1_alloc (ThreadMemory *tmem,
785 guint ix)
786 {
787 Magazine *mag = &tmem->magazine1[ix];
788 ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
789 if (G_LIKELY (mag->count > 0))
790 mag->count--;
791 return chunk;
792 }
793
794 static inline void
795 thread_memory_magazine2_free (ThreadMemory *tmem,
796 guint ix,
797 gpointer mem)
798 {
799 Magazine *mag = &tmem->magazine2[ix];
800 ChunkLink *chunk = mem;
801 chunk->data = NULL;
802 chunk->next = mag->chunks;
803 mag->chunks = chunk;
804 mag->count++;
805 }
806
807 /* --- API functions --- */
808 gpointer
809 g_slice_alloc (gsize mem_size)
810 {
811 gsize chunk_size;
812 gpointer mem;
813 guint acat;
814 chunk_size = P2ALIGN (mem_size);
815 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 if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
821 {
822 thread_memory_swap_magazines (tmem, ix);
823 if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
824 thread_memory_magazine1_reload (tmem, ix);
825 }
826 mem = thread_memory_magazine1_alloc (tmem, ix);
827 }
828 else if (acat == 2) /* allocate through slab allocator */
829 {
830 g_mutex_lock (allocator->slab_mutex);
831 mem = slab_allocator_alloc_chunk (chunk_size);
832 g_mutex_unlock (allocator->slab_mutex);
833 }
834 else /* delegate to system malloc */
835 mem = g_malloc (mem_size);
836 if (G_UNLIKELY (allocator->config.debug_blocks))
837 smc_notify_alloc (mem, mem_size);
838 return mem;
839 }
840
841 gpointer
842 g_slice_alloc0 (gsize mem_size)
843 {
844 gpointer mem = g_slice_alloc (mem_size);
845 if (mem)
846 memset (mem, 0, mem_size);
847 return mem;
848 }
849
850 gpointer
851 g_slice_copy (gsize mem_size,
852 gconstpointer mem_block)
853 {
854 gpointer mem = g_slice_alloc (mem_size);
855 if (mem)
856 memcpy (mem, mem_block, mem_size);
857 return mem;
858 }
859
860 void
861 g_slice_free1 (gsize mem_size,
862 gpointer mem_block)
863 {
864 gsize chunk_size = P2ALIGN (mem_size);
865 guint acat = allocator_categorize (chunk_size);
866 if (G_UNLIKELY (!mem_block))
867 return;
868 if (G_UNLIKELY (allocator->config.debug_blocks) &&
869 !smc_notify_free (mem_block, mem_size))
870 abort();
871 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
872 {
873 ThreadMemory *tmem = thread_memory_from_self();
874 guint ix = SLAB_INDEX (allocator, chunk_size);
875 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
876 {
877 thread_memory_swap_magazines (tmem, ix);
878 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
879 thread_memory_magazine2_unload (tmem, ix);
880 }
881 if (G_UNLIKELY (g_mem_gc_friendly))
882 memset (mem_block, 0, chunk_size);
883 thread_memory_magazine2_free (tmem, ix, mem_block);
884 }
885 else if (acat == 2) /* allocate through slab allocator */
886 {
887 if (G_UNLIKELY (g_mem_gc_friendly))
888 memset (mem_block, 0, chunk_size);
889 g_mutex_lock (allocator->slab_mutex);
890 slab_allocator_free_chunk (chunk_size, mem_block);
891 g_mutex_unlock (allocator->slab_mutex);
892 }
893 else /* delegate to system malloc */
894 {
895 if (G_UNLIKELY (g_mem_gc_friendly))
896 memset (mem_block, 0, mem_size);
897 g_free (mem_block);
898 }
899 }
900
901 void
902 g_slice_free_chain_with_offset (gsize mem_size,
903 gpointer mem_chain,
904 gsize next_offset)
905 {
906 gpointer slice = mem_chain;
907 /* while the thread magazines and the magazine cache are implemented so that
908 * they can easily be extended to allow for free lists containing more free
909 * lists for the first level nodes, which would allow O(1) freeing in this
910 * function, the benefit of such an extension is questionable, because:
911 * - the magazine size counts will become mere lower bounds which confuses
912 * the code adapting to lock contention;
913 * - freeing a single node to the thread magazines is very fast, so this
914 * O(list_length) operation is multiplied by a fairly small factor;
915 * - memory usage histograms on larger applications seem to indicate that
916 * the amount of released multi node lists is negligible in comparison
917 * to single node releases.
918 * - the major performance bottle neck, namely g_private_get() or
919 * g_mutex_lock()/g_mutex_unlock() has already been moved out of the
920 * inner loop for freeing chained slices.
921 */
922 gsize chunk_size = P2ALIGN (mem_size);
923 guint acat = allocator_categorize (chunk_size);
924 if (G_LIKELY (acat == 1)) /* allocate through magazine layer */
925 {
926 ThreadMemory *tmem = thread_memory_from_self();
927 guint ix = SLAB_INDEX (allocator, chunk_size);
928 while (slice)
929 {
930 guint8 *current = slice;
931 slice = *(gpointer*) (current + next_offset);
932 if (G_UNLIKELY (allocator->config.debug_blocks) &&
933 !smc_notify_free (current, mem_size))
934 abort();
935 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
936 {
937 thread_memory_swap_magazines (tmem, ix);
938 if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
939 thread_memory_magazine2_unload (tmem, ix);
940 }
941 if (G_UNLIKELY (g_mem_gc_friendly))
942 memset (current, 0, chunk_size);
943 thread_memory_magazine2_free (tmem, ix, current);
944 }
945 }
946 else if (acat == 2) /* allocate through slab allocator */
947 {
948 g_mutex_lock (allocator->slab_mutex);
949 while (slice)
950 {
951 guint8 *current = slice;
952 slice = *(gpointer*) (current + next_offset);
953 if (G_UNLIKELY (allocator->config.debug_blocks) &&
954 !smc_notify_free (current, mem_size))
955 abort();
956 if (G_UNLIKELY (g_mem_gc_friendly))
957 memset (current, 0, chunk_size);
958 slab_allocator_free_chunk (chunk_size, current);
959 }
960 g_mutex_unlock (allocator->slab_mutex);
961 }
962 else /* delegate to system malloc */
963 while (slice)
964 {
965 guint8 *current = slice;
966 slice = *(gpointer*) (current + next_offset);
967 if (G_UNLIKELY (allocator->config.debug_blocks) &&
968 !smc_notify_free (current, mem_size))
969 abort();
970 if (G_UNLIKELY (g_mem_gc_friendly))
971 memset (current, 0, mem_size);
972 g_free (current);
973 }
974 }
975
976 /* --- single page allocator --- */
977 static void
978 allocator_slab_stack_push (Allocator *allocator,
979 guint ix,
980 SlabInfo *sinfo)
981 {
982 /* insert slab at slab ring head */
983 if (!allocator->slab_stack[ix])
984 {
985 sinfo->next = sinfo;
986 sinfo->prev = sinfo;
987 }
988 else
989 {
990 SlabInfo *next = allocator->slab_stack[ix], *prev = next->prev;
991 next->prev = sinfo;
992 prev->next = sinfo;
993 sinfo->next = next;
994 sinfo->prev = prev;
995 }
996 allocator->slab_stack[ix] = sinfo;
997 }
998
999 static gsize
1000 allocator_aligned_page_size (Allocator *allocator,
1001 gsize n_bytes)
1002 {
1003 gsize val = 1 << g_bit_storage (n_bytes - 1);
1004 val = MAX (val, allocator->min_page_size);
1005 return val;
1006 }
1007
1008 static void
1009 allocator_add_slab (Allocator *allocator,
1010 guint ix,
1011 gsize chunk_size)
1012 {
1013 ChunkLink *chunk;
1014 SlabInfo *sinfo;
1015 gsize addr, padding, n_chunks, color = 0;
1016 gsize page_size = allocator_aligned_page_size (allocator, SLAB_BPAGE_SIZE (allocator, chunk_size));
1017 /* allocate 1 page for the chunks and the slab */
1018 gpointer aligned_memory = allocator_memalign (page_size, page_size - NATIVE_MALLOC_PADDING);
1019 guint8 *mem = aligned_memory;
1020 guint i;
1021 if (!mem)
1022 {
1023 const gchar *syserr = "unknown error";
1024 #if HAVE_STRERROR
1025 syserr = strerror (errno);
1026 #endif
1027 mem_error ("failed to allocate %u bytes (alignment: %u): %s\n",
1028 (guint) (page_size - NATIVE_MALLOC_PADDING), (guint) page_size, syserr);
1029 }
1030 /* mask page adress */
1031 addr = ((gsize) mem / page_size) * page_size;
1032 /* assert alignment */
1033 mem_assert (aligned_memory == (gpointer) addr);
1034 /* basic slab info setup */
1035 sinfo = (SlabInfo*) (mem + page_size - SLAB_INFO_SIZE);
1036 sinfo->n_allocated = 0;
1037 sinfo->chunks = NULL;
1038 /* figure cache colorization */
1039 n_chunks = ((guint8*) sinfo - mem) / chunk_size;
1040 padding = ((guint8*) sinfo - mem) - n_chunks * chunk_size;
1041 if (padding)
1042 {
1043 color = (allocator->color_accu * P2ALIGNMENT) % padding;
1044 allocator->color_accu += allocator->config.color_increment;
1045 }
1046 /* add chunks to free list */
1047 chunk = (ChunkLink*) (mem + color);
1048 sinfo->chunks = chunk;
1049 for (i = 0; i < n_chunks - 1; i++)
1050 {
1051 chunk->next = (ChunkLink*) ((guint8*) chunk + chunk_size);
1052 chunk = chunk->next;
1053 }
1054 chunk->next = NULL; /* last chunk */
1055 /* add slab to slab ring */
1056 allocator_slab_stack_push (allocator, ix, sinfo);
1057 }
1058
1059 static gpointer
1060 slab_allocator_alloc_chunk (gsize chunk_size)
1061 {
1062 ChunkLink *chunk;
1063 guint ix = SLAB_INDEX (allocator, chunk_size);
1064 /* ensure non-empty slab */
1065 if (!allocator->slab_stack[ix] || !allocator->slab_stack[ix]->chunks)
1066 allocator_add_slab (allocator, ix, chunk_size);
1067 /* allocate chunk */
1068 chunk = allocator->slab_stack[ix]->chunks;
1069 allocator->slab_stack[ix]->chunks = chunk->next;
1070 allocator->slab_stack[ix]->n_allocated++;
1071 /* rotate empty slabs */
1072 if (!allocator->slab_stack[ix]->chunks)
1073 allocator->slab_stack[ix] = allocator->slab_stack[ix]->next;
1074 return chunk;
1075 }
1076
1077 static void
1078 slab_allocator_free_chunk (gsize chunk_size,
1079 gpointer mem)
1080 {
1081 ChunkLink *chunk;
1082 gboolean was_empty;
1083 guint ix = SLAB_INDEX (allocator, chunk_size);
1084 gsize page_size = allocator_aligned_page_size (allocator, SLAB_BPAGE_SIZE (allocator, chunk_size));
1085 gsize addr = ((gsize) mem / page_size) * page_size;
1086 /* mask page adress */
1087 guint8 *page = (guint8*) addr;
1088 SlabInfo *sinfo = (SlabInfo*) (page + page_size - SLAB_INFO_SIZE);
1089 /* assert valid chunk count */
1090 mem_assert (sinfo->n_allocated > 0);
1091 /* add chunk to free list */
1092 was_empty = sinfo->chunks == NULL;
1093 chunk = (ChunkLink*) mem;
1094 chunk->next = sinfo->chunks;
1095 sinfo->chunks = chunk;
1096 sinfo->n_allocated--;
1097 /* keep slab ring partially sorted, empty slabs at end */
1098 if (was_empty)
1099 {
1100 /* unlink slab */
1101 SlabInfo *next = sinfo->next, *prev = sinfo->prev;
1102 next->prev = prev;
1103 prev->next = next;
1104 if (allocator->slab_stack[ix] == sinfo)
1105 allocator->slab_stack[ix] = next == sinfo ? NULL : next;
1106 /* insert slab at head */
1107 allocator_slab_stack_push (allocator, ix, sinfo);
1108 }
1109 /* eagerly free complete unused slabs */
1110 if (!sinfo->n_allocated)
1111 {
1112 /* unlink slab */
1113 SlabInfo *next = sinfo->next, *prev = sinfo->prev;
1114 next->prev = prev;
1115 prev->next = next;
1116 if (allocator->slab_stack[ix] == sinfo)
1117 allocator->slab_stack[ix] = next == sinfo ? NULL : next;
1118 /* free slab */
1119 allocator_memfree (page_size, page);
1120 }
1121 }
1122
1123 /* --- memalign implementation --- */
1124 #ifdef HAVE_MALLOC_H
1125 #include <malloc.h> /* memalign() */
1126 #endif
1127
1128 /* from config.h:
1129 * define HAVE_POSIX_MEMALIGN 1 // if free(posix_memalign(3)) works, <stdlib.h>
1130 * define HAVE_COMPLIANT_POSIX_MEMALIGN 1 // if free(posix_memalign(3)) works for sizes != 2^n, <stdlib.h>
1131 * define HAVE_MEMALIGN 1 // if free(memalign(3)) works, <malloc.h>
1132 * define HAVE_VALLOC 1 // if free(valloc(3)) works, <stdlib.h> or <malloc.h>
1133 * if none is provided, we implement malloc(3)-based alloc-only page alignment
1134 */
1135
1136 #if !(HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC)
1137 static GTrashStack *compat_valloc_trash = NULL;
1138 #endif
1139
1140 static gpointer
1141 allocator_memalign (gsize alignment,
1142 gsize memsize)
1143 {
1144 gpointer aligned_memory = NULL;
1145 gint err = ENOMEM;
1146 #if HAVE_COMPLIANT_POSIX_MEMALIGN
1147 err = posix_memalign (&aligned_memory, alignment, memsize);
1148 #elif HAVE_MEMALIGN
1149 errno = 0;
1150 aligned_memory = memalign (alignment, memsize);
1151 err = errno;
1152 #elif HAVE_VALLOC
1153 errno = 0;
1154 aligned_memory = valloc (memsize);
1155 err = errno;
1156 #else
1157 /* simplistic non-freeing page allocator */
1158 mem_assert (alignment == sys_page_size);
1159 mem_assert (memsize <= sys_page_size);
1160 if (!compat_valloc_trash)
1161 #ifdef G_OS_WIN32
1162 {
1163 aligned_memory = VirtualAlloc (virtual_mem, sys_page_size, MEM_COMMIT, PAGE_READWRITE);
1164 virtual_mem += sys_page_size;
1165 }
1166 else
1167 #else
1168 {
1169
1170 const guint n_pages = 16;
1171 guint8 *mem = malloc (n_pages * sys_page_size);
1172 err = errno;
1173 if (mem)
1174 {
1175 gint i = n_pages;
1176 guint8 *amem = (guint8*) ALIGN ((gsize) mem, sys_page_size);
1177 if (amem != mem)
1178 i--; /* mem wasn't page aligned */
1179 while (--i >= 0)
1180 g_trash_stack_push (&compat_valloc_trash, amem + i * sys_page_size);
1181 }
1182 }
1183 #endif
1184 aligned_memory = g_trash_stack_pop (&compat_valloc_trash);
1185 #endif
1186 if (!aligned_memory)
1187 errno = err;
1188 return aligned_memory;
1189 }
1190
1191 static void
1192 allocator_memfree (gsize memsize,
1193 gpointer mem)
1194 {
1195 #if HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC
1196 free (mem);
1197 #else
1198 mem_assert (memsize <= sys_page_size);
1199 g_trash_stack_push (&compat_valloc_trash, mem);
1200 #endif
1201 }
1202
1203 static void
1204 mem_error (const char *format,
1205 ...)
1206 {
1207 const char *pname;
1208 va_list args;
1209 /* at least, put out "MEMORY-ERROR", in case we segfault during the rest of the function */
1210 fputs ("\n***MEMORY-ERROR***: ", stderr);
1211 pname = g_get_prgname();
1212 fprintf (stderr, "%s: GSlice: ", pname ? pname : "");
1213 va_start (args, format);
1214 vfprintf (stderr, format, args);
1215 va_end (args);
1216 fputs ("\n", stderr);
1217 abort();
1218 _exit (1);
1219 }
1220
1221 /* --- g-slice memory checker tree --- */
1222 typedef size_t SmcKType; /* key type */
1223 typedef size_t SmcVType; /* value type */
1224 typedef struct {
1225 SmcKType key;
1226 SmcVType value;
1227 } SmcEntry;
1228 static void smc_tree_insert (SmcKType key,
1229 SmcVType value);
1230 static gboolean smc_tree_lookup (SmcKType key,
1231 SmcVType *value_p);
1232 static gboolean smc_tree_remove (SmcKType key);
1233
1234
1235 /* --- g-slice memory checker implementation --- */
1236 static void
1237 smc_notify_alloc (void *pointer,
1238 size_t size)
1239 {
1240 size_t adress = (size_t) pointer;
1241 if (pointer)
1242 smc_tree_insert (adress, size);
1243 }
1244
1245 #if 0
1246 static void
1247 smc_notify_ignore (void *pointer)
1248 {
1249 size_t adress = (size_t) pointer;
1250 if (pointer)
1251 smc_tree_remove (adress);
1252 }
1253 #endif
1254
1255 static int
1256 smc_notify_free (void *pointer,
1257 size_t size)
1258 {
1259 size_t adress = (size_t) pointer;
1260 SmcVType real_size;
1261 gboolean found_one;
1262
1263 if (!pointer)
1264 return 1; /* ignore */
1265 found_one = smc_tree_lookup (adress, &real_size);
1266 if (!found_one)
1267 {
1268 fprintf (stderr, "GSlice: MemChecker: attempt to release non-allocated block: %p size=%" G_GSIZE_FORMAT "\n", pointer, size);
1269 return 0;
1270 }
1271 if (real_size != size && (real_size || size))
1272 {
1273 fprintf (stderr, "GSlice: MemChecker: attempt to release block with invalid size: %p size=%" G_GSIZE_FORMAT " invalid-size=%" G_GSIZE_FORMAT "\n", pointer, real_size, size);
1274 return 0;
1275 }
1276 if (!smc_tree_remove (adress))
1277 {
1278 fprintf (stderr, "GSlice: MemChecker: attempt to release non-allocated block: %p size=%" G_GSIZE_FORMAT "\n", pointer, size);
1279 return 0;
1280 }
1281 return 1; /* all fine */
1282 }
1283
1284 /* --- g-slice memory checker tree implementation --- */
1285 #define SMC_TRUNK_COUNT (4093 /* 16381 */) /* prime, to distribute trunk collisions (big, allocated just once) */
1286 #define SMC_BRANCH_COUNT (511) /* prime, to distribute branch collisions */
1287 #define SMC_TRUNK_EXTENT (SMC_BRANCH_COUNT * 2039) /* key adress space per trunk, should distribute uniformly across BRANCH_COUNT */
1288 #define SMC_TRUNK_HASH(k) ((k / SMC_TRUNK_EXTENT) % SMC_TRUNK_COUNT) /* generate new trunk hash per megabyte (roughly) */
1289 #define SMC_BRANCH_HASH(k) (k % SMC_BRANCH_COUNT)
1290
1291 typedef struct {
1292 SmcEntry *entries;
1293 unsigned int n_entries;
1294 } SmcBranch;
1295
1296 static SmcBranch **smc_tree_root = NULL;
1297
1298 static void
1299 smc_tree_abort (int errval)
1300 {
1301 const char *syserr = "unknown error";
1302 #if HAVE_STRERROR
1303 syserr = strerror (errval);
1304 #endif
1305 mem_error ("MemChecker: failure in debugging tree: %s", syserr);
1306 }
1307
1308 static inline SmcEntry*
1309 smc_tree_branch_grow_L (SmcBranch *branch,
1310 unsigned int index)
1311 {
1312 unsigned int old_size = branch->n_entries * sizeof (branch->entries[0]);
1313 unsigned int new_size = old_size + sizeof (branch->entries[0]);
1314 SmcEntry *entry;
1315 mem_assert (index <= branch->n_entries);
1316 branch->entries = (SmcEntry*) realloc (branch->entries, new_size);
1317 if (!branch->entries)
1318 smc_tree_abort (errno);
1319 entry = branch->entries + index;
1320 g_memmove (entry + 1, entry, (branch->n_entries - index) * sizeof (entry[0]));
1321 branch->n_entries += 1;
1322 return entry;
1323 }
1324
1325 static inline SmcEntry*
1326 smc_tree_branch_lookup_nearest_L (SmcBranch *branch,
1327 SmcKType key)
1328 {
1329 unsigned int n_nodes = branch->n_entries, offs = 0;
1330 SmcEntry *check = branch->entries;
1331 int cmp = 0;
1332 while (offs < n_nodes)
1333 {
1334 unsigned int i = (offs + n_nodes) >> 1;
1335 check = branch->entries + i;
1336 cmp = key < check->key ? -1 : key != check->key;
1337 if (cmp == 0)
1338 return check; /* return exact match */
1339 else if (cmp < 0)
1340 n_nodes = i;
1341 else /* (cmp > 0) */
1342 offs = i + 1;
1343 }
1344 /* check points at last mismatch, cmp > 0 indicates greater key */
1345 return cmp > 0 ? check + 1 : check; /* return insertion position for inexact match */
1346 }
1347
1348 static void
1349 smc_tree_insert (SmcKType key,
1350 SmcVType value)
1351 {
1352 unsigned int ix0, ix1;
1353 SmcEntry *entry;
1354
1355 g_mutex_lock (smc_tree_mutex);
1356 ix0 = SMC_TRUNK_HASH (key);
1357 ix1 = SMC_BRANCH_HASH (key);
1358 if (!smc_tree_root)
1359 {
1360 smc_tree_root = calloc (SMC_TRUNK_COUNT, sizeof (smc_tree_root[0]));
1361 if (!smc_tree_root)
1362 smc_tree_abort (errno);
1363 }
1364 if (!smc_tree_root[ix0])
1365 {
1366 smc_tree_root[ix0] = calloc (SMC_BRANCH_COUNT, sizeof (smc_tree_root[0][0]));
1367 if (!smc_tree_root[ix0])
1368 smc_tree_abort (errno);
1369 }
1370 entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
1371 if (!entry || /* need create */
1372 entry >= smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries || /* need append */
1373 entry->key != key) /* need insert */
1374 entry = smc_tree_branch_grow_L (&smc_tree_root[ix0][ix1], entry - smc_tree_root[ix0][ix1].entries);
1375 entry->key = key;
1376 entry->value = value;
1377 g_mutex_unlock (smc_tree_mutex);
1378 }
1379
1380 static gboolean
1381 smc_tree_lookup (SmcKType key,
1382 SmcVType *value_p)
1383 {
1384 SmcEntry *entry = NULL;
1385 unsigned int ix0 = SMC_TRUNK_HASH (key), ix1 = SMC_BRANCH_HASH (key);
1386 gboolean found_one = FALSE;
1387 *value_p = 0;
1388 g_mutex_lock (smc_tree_mutex);
1389 if (smc_tree_root && smc_tree_root[ix0])
1390 {
1391 entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
1392 if (entry &&
1393 entry < smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries &&
1394 entry->key == key)
1395 {
1396 found_one = TRUE;
1397 *value_p = entry->value;
1398 }
1399 }
1400 g_mutex_unlock (smc_tree_mutex);
1401 return found_one;
1402 }
1403
1404 static gboolean
1405 smc_tree_remove (SmcKType key)
1406 {
1407 unsigned int ix0 = SMC_TRUNK_HASH (key), ix1 = SMC_BRANCH_HASH (key);
1408 gboolean found_one = FALSE;
1409 g_mutex_lock (smc_tree_mutex);
1410 if (smc_tree_root && smc_tree_root[ix0])
1411 {
1412 SmcEntry *entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
1413 if (entry &&
1414 entry < smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries &&
1415 entry->key == key)
1416 {
1417 unsigned int i = entry - smc_tree_root[ix0][ix1].entries;
1418 smc_tree_root[ix0][ix1].n_entries -= 1;
1419 g_memmove (entry, entry + 1, (smc_tree_root[ix0][ix1].n_entries - i) * sizeof (entry[0]));
1420 if (!smc_tree_root[ix0][ix1].n_entries)
1421 {
1422 /* avoid useless pressure on the memory system */
1423 free (smc_tree_root[ix0][ix1].entries);
1424 smc_tree_root[ix0][ix1].entries = NULL;
1425 }
1426 found_one = TRUE;
1427 }
1428 }
1429 g_mutex_unlock (smc_tree_mutex);
1430 return found_one;
1431 }
1432
1433 #ifdef G_ENABLE_DEBUG
1434 void
1435 g_slice_debug_tree_statistics (void)
1436 {
1437 g_mutex_lock (smc_tree_mutex);
1438 if (smc_tree_root)
1439 {
1440 unsigned int i, j, t = 0, o = 0, b = 0, su = 0, ex = 0, en = 4294967295u;
1441 double tf, bf;
1442 for (i = 0; i < SMC_TRUNK_COUNT; i++)
1443 if (smc_tree_root[i])
1444 {
1445 t++;
1446 for (j = 0; j < SMC_BRANCH_COUNT; j++)
1447 if (smc_tree_root[i][j].n_entries)
1448 {
1449 b++;
1450 su += smc_tree_root[i][j].n_entries;
1451 en = MIN (en, smc_tree_root[i][j].n_entries);
1452 ex = MAX (ex, smc_tree_root[i][j].n_entries);
1453 }
1454 else if (smc_tree_root[i][j].entries)
1455 o++; /* formerly used, now empty */
1456 }
1457 en = b ? en : 0;
1458 tf = MAX (t, 1.0); /* max(1) to be a valid divisor */
1459 bf = MAX (b, 1.0); /* max(1) to be a valid divisor */
1460 fprintf (stderr, "GSlice: MemChecker: %u trunks, %u branches, %u old branches\n", t, b, o);
1461 fprintf (stderr, "GSlice: MemChecker: %f branches per trunk, %.2f%% utilization\n",
1462 b / tf,
1463 100.0 - (SMC_BRANCH_COUNT - b / tf) / (0.01 * SMC_BRANCH_COUNT));
1464 fprintf (stderr, "GSlice: MemChecker: %f entries per branch, %u minimum, %u maximum\n",
1465 su / bf, en, ex);
1466 }
1467 else
1468 fprintf (stderr, "GSlice: MemChecker: root=NULL\n");
1469 g_mutex_unlock (smc_tree_mutex);
1470
1471 /* sample statistics (beast + GSLice + 24h scripted core & GUI activity):
1472 * PID %CPU %MEM VSZ RSS COMMAND
1473 * 8887 30.3 45.8 456068 414856 beast-0.7.1 empty.bse
1474 * $ cat /proc/8887/statm # total-program-size resident-set-size shared-pages text/code data/stack library dirty-pages
1475 * 114017 103714 2354 344 0 108676 0
1476 * $ cat /proc/8887/status
1477 * Name: beast-0.7.1
1478 * VmSize: 456068 kB
1479 * VmLck: 0 kB
1480 * VmRSS: 414856 kB
1481 * VmData: 434620 kB
1482 * VmStk: 84 kB
1483 * VmExe: 1376 kB
1484 * VmLib: 13036 kB
1485 * VmPTE: 456 kB
1486 * Threads: 3
1487 * (gdb) print g_slice_debug_tree_statistics ()
1488 * GSlice: MemChecker: 422 trunks, 213068 branches, 0 old branches
1489 * GSlice: MemChecker: 504.900474 branches per trunk, 98.81% utilization
1490 * GSlice: MemChecker: 4.965039 entries per branch, 1 minimum, 37 maximum
1491 */
1492 }
1493 #endif /* G_ENABLE_DEBUG */
1494
1495 #define __G_SLICE_C__
1496 #include "galiasdef.c"

   
Visit the ZANavi Wiki