gslice.c 58.9 KB
Newer Older
1 2 3 4 5 6
/* GLIB sliced memory - fast concurrent memory chunk allocator
 * Copyright (C) 2005 Tim Janik
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
7
 * version 2.1 of the License, or (at your option) any later version.
8 9 10 11 12 13 14
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
15
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
16 17
 */
/* MT safe */
Matthias Clasen's avatar
Matthias Clasen committed
18 19

#include "config.h"
20
#include "glibconfig.h"
Matthias Clasen's avatar
Matthias Clasen committed
21

22 23 24 25
#if     defined HAVE_POSIX_MEMALIGN && defined POSIX_MEMALIGN_WITH_COMPLIANT_ALLOCS
#  define HAVE_COMPLIANT_POSIX_MEMALIGN 1
#endif

Dan Winship's avatar
Dan Winship committed
26
#if defined(HAVE_COMPLIANT_POSIX_MEMALIGN) && !defined(_XOPEN_SOURCE)
27
#define _XOPEN_SOURCE 600       /* posix_memalign() */
28
#endif
29 30 31
#include <stdlib.h>             /* posix_memalign() */
#include <string.h>
#include <errno.h>
32

33
#ifdef G_OS_UNIX
34 35 36 37
#include <unistd.h>             /* sysconf() */
#endif
#ifdef G_OS_WIN32
#include <windows.h>
38
#include <process.h>
39
#endif
40

41 42
#include <stdio.h>              /* fputs/fprintf */

43 44
#include "gslice.h"

45
#include "gmain.h"
46
#include "gmem.h"               /* gslice.h */
47
#include "gstrfuncs.h"
48
#include "gutils.h"
49
#include "gtrashstack.h"
50 51 52
#include "gtestutils.h"
#include "gthread.h"
#include "glib_trace.h"
53

54 55
#include "valgrind.h"

56 57 58 59 60 61 62 63 64 65 66 67 68
/**
 * SECTION:memory_slices
 * @title: Memory Slices
 * @short_description: efficient way to allocate groups of equal-sized
 *     chunks of memory
 *
 * Memory slices provide a space-efficient and multi-processing scalable
 * way to allocate equal-sized pieces of memory, just like the original
 * #GMemChunks (from GLib 2.8), while avoiding their excessive
 * memory-waste, scalability and performance problems.
 *
 * To achieve these goals, the slice allocator uses a sophisticated,
 * layered design that has been inspired by Bonwick's slab allocator
69 70
 * ([Bonwick94](http://citeseer.ist.psu.edu/bonwick94slab.html)
 * Jeff Bonwick, The slab allocator: An object-caching kernel
71
 * memory allocator. USENIX 1994, and
72 73
 * [Bonwick01](http://citeseer.ist.psu.edu/bonwick01magazines.html)
 * Bonwick and Jonathan Adams, Magazines and vmem: Extending the
74 75
 * slab allocator to many cpu's and arbitrary resources. USENIX 2001)
 *
76 77 78 79 80 81 82 83 84 85 86 87 88 89
 * It uses posix_memalign() to optimize allocations of many equally-sized
 * chunks, and has per-thread free lists (the so-called magazine layer)
 * to quickly satisfy allocation requests of already known structure sizes.
 * This is accompanied by extra caching logic to keep freed memory around
 * for some time before returning it to the system. Memory that is unused
 * due to alignment constraints is used for cache colorization (random
 * distribution of chunk addresses) to improve CPU cache utilization. The
 * caching layer of the slice allocator adapts itself to high lock contention
 * to improve scalability.
 *
 * The slice allocator can allocate blocks as small as two pointers, and
 * unlike malloc(), it does not reserve extra space per block. For large block
 * sizes, g_slice_new() and g_slice_alloc() will automatically delegate to the
 * system malloc() implementation. For newly written code it is recommended
90
 * to use the new `g_slice` API instead of g_malloc() and
91 92 93
 * friends, as long as objects are not resized during their lifetime and the
 * object size used at allocation time is still available when freeing.
 *
94
 * Here is an example for using the slice allocator:
95
 * |[<!-- language="C" --> 
96 97 98
 * gchar *mem[10000];
 * gint i;
 *
Matthias Clasen's avatar
Matthias Clasen committed
99
 * // Allocate 10000 blocks.
100
 * for (i = 0; i < 10000; i++)
101 102 103
 *   {
 *     mem[i] = g_slice_alloc (50);
 *
Matthias Clasen's avatar
Matthias Clasen committed
104
 *     // Fill in the memory with some junk.
105
 *     for (j = 0; j < 50; j++)
106 107 108
 *       mem[i][j] = i * j;
 *   }
 *
Matthias Clasen's avatar
Matthias Clasen committed
109
 * // Now free all of the blocks.
110 111 112
 * for (i = 0; i < 10000; i++)
 *   g_slice_free1 (50, mem[i]);
 * ]|
113
 *
114 115
 * And here is an example for using the using the slice allocator
 * with data structures:
116
 * |[<!-- language="C" --> 
117 118
 * GRealArray *array;
 *
Matthias Clasen's avatar
Matthias Clasen committed
119
 * // Allocate one block, using the g_slice_new() macro.
120
 * array = g_slice_new (GRealArray);
121
 *
Matthias Clasen's avatar
Matthias Clasen committed
122
 * // We can now use array just like a normal pointer to a structure.
123 124 125 126 127 128 129
 * array->data            = NULL;
 * array->len             = 0;
 * array->alloc           = 0;
 * array->zero_terminated = (zero_terminated ? 1 : 0);
 * array->clear           = (clear ? 1 : 0);
 * array->elt_size        = elt_size;
 *
Matthias Clasen's avatar
Matthias Clasen committed
130
 * // We can free the block, so it can be reused.
131
 * g_slice_free (GRealArray, array);
132
 * ]|
133 134
 */

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
/* the GSlice allocator is split up into 4 layers, roughly modelled after the slab
 * allocator and magazine extensions as outlined in:
 * + [Bonwick94] Jeff Bonwick, The slab allocator: An object-caching kernel
 *   memory allocator. USENIX 1994, http://citeseer.ist.psu.edu/bonwick94slab.html
 * + [Bonwick01] Bonwick and Jonathan Adams, Magazines and vmem: Extending the
 *   slab allocator to many cpu's and arbitrary resources.
 *   USENIX 2001, http://citeseer.ist.psu.edu/bonwick01magazines.html
 * the layers are:
 * - the thread magazines. for each (aligned) chunk size, a magazine (a list)
 *   of recently freed and soon to be allocated chunks is maintained per thread.
 *   this way, most alloc/free requests can be quickly satisfied from per-thread
 *   free lists which only require one g_private_get() call to retrive the
 *   thread handle.
 * - the magazine cache. allocating and freeing chunks to/from threads only
 *   occours at magazine sizes from a global depot of magazines. the depot
 *   maintaines a 15 second working set of allocated magazines, so full
 *   magazines are not allocated and released too often.
 *   the chunk size dependent magazine sizes automatically adapt (within limits,
 *   see [3]) to lock contention to properly scale performance across a variety
 *   of SMP systems.
 * - the slab allocator. this allocator allocates slabs (blocks of memory) close
 *   to the system page size or multiples thereof which have to be page aligned.
 *   the blocks are divided into smaller chunks which are used to satisfy
 *   allocations from the upper layers. the space provided by the reminder of
 *   the chunk size division is used for cache colorization (random distribution
 *   of chunk addresses) to improve processor cache utilization. multiple slabs
 *   with the same chunk size are kept in a partially sorted ring to allow O(1)
 *   freeing and allocation of chunks (as long as the allocation of an entirely
 *   new slab can be avoided).
 * - the page allocator. on most modern systems, posix_memalign(3) or
 *   memalign(3) should be available, so this is used to allocate blocks with
 *   system page size based alignments and sizes or multiples thereof.
 *   if no memalign variant is provided, valloc() is used instead and
 *   block sizes are limited to the system page size (no multiples thereof).
 *   as a fallback, on system without even valloc(), a malloc(3)-based page
 *   allocator with alloc-only behaviour is used.
 *
 * NOTES:
 * [1] some systems memalign(3) implementations may rely on boundary tagging for
 *     the handed out memory chunks. to avoid excessive page-wise fragmentation,
 *     we reserve 2 * sizeof (void*) per block size for the systems memalign(3),
 *     specified in NATIVE_MALLOC_PADDING.
 * [2] using the slab allocator alone already provides for a fast and efficient
 *     allocator, it doesn't properly scale beyond single-threaded uses though.
 *     also, the slab allocator implements eager free(3)-ing, i.e. does not
 *     provide any form of caching or working set maintenance. so if used alone,
 *     it's vulnerable to trashing for sequences of balanced (alloc, free) pairs
 *     at certain thresholds.
 * [3] magazine sizes are bound by an implementation specific minimum size and
 *     a chunk size specific maximum to limit magazine storage sizes to roughly
 *     16KB.
 * [4] allocating ca. 8 chunks per block/page keeps a good balance between
187
 *     external and internal fragmentation (<= 12.5%). [Bonwick94]
188 189 190 191 192 193 194 195 196 197
 */

/* --- macros and constants --- */
#define LARGEALIGNMENT          (256)
#define P2ALIGNMENT             (2 * sizeof (gsize))                            /* fits 2 pointers (assumed to be 2 * GLIB_SIZEOF_SIZE_T below) */
#define ALIGN(size, base)       ((base) * (gsize) (((size) + (base) - 1) / (base)))
#define NATIVE_MALLOC_PADDING   P2ALIGNMENT                                     /* per-page padding left for native malloc(3) see [1] */
#define SLAB_INFO_SIZE          P2ALIGN (sizeof (SlabInfo) + NATIVE_MALLOC_PADDING)
#define MAX_MAGAZINE_SIZE       (256)                                           /* see [3] and allocator_get_magazine_threshold() for this */
#define MIN_MAGAZINE_SIZE       (4)
198
#define MAX_STAMP_COUNTER       (7)                                             /* distributes the load of gettimeofday() */
199 200 201 202
#define MAX_SLAB_CHUNK_SIZE(al) (((al)->max_page_size - SLAB_INFO_SIZE) / 8)    /* we want at last 8 chunks per page, see [4] */
#define MAX_SLAB_INDEX(al)      (SLAB_INDEX (al, MAX_SLAB_CHUNK_SIZE (al)) + 1)
#define SLAB_INDEX(al, asize)   ((asize) / P2ALIGNMENT - 1)                     /* asize must be P2ALIGNMENT aligned */
#define SLAB_CHUNK_SIZE(al, ix) (((ix) + 1) * P2ALIGNMENT)
203
#define SLAB_BPAGE_SIZE(al,csz) (8 * (csz) + SLAB_INFO_SIZE)
204 205 206 207 208 209 210 211 212 213

/* optimized version of ALIGN (size, P2ALIGNMENT) */
#if     GLIB_SIZEOF_SIZE_T * 2 == 8  /* P2ALIGNMENT */
#define P2ALIGN(size)   (((size) + 0x7) & ~(gsize) 0x7)
#elif   GLIB_SIZEOF_SIZE_T * 2 == 16 /* P2ALIGNMENT */
#define P2ALIGN(size)   (((size) + 0xf) & ~(gsize) 0xf)
#else
#define P2ALIGN(size)   ALIGN (size, P2ALIGNMENT)
#endif

214 215 216 217
/* special helpers to avoid gmessage.c dependency */
static void mem_error (const char *format, ...) G_GNUC_PRINTF (1,2);
#define mem_assert(cond)    do { if (G_LIKELY (cond)) ; else mem_error ("assertion failed: %s", #cond); } while (0)

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
/* --- structures --- */
typedef struct _ChunkLink      ChunkLink;
typedef struct _SlabInfo       SlabInfo;
typedef struct _CachedMagazine CachedMagazine;
struct _ChunkLink {
  ChunkLink *next;
  ChunkLink *data;
};
struct _SlabInfo {
  ChunkLink *chunks;
  guint n_allocated;
  SlabInfo *next, *prev;
};
typedef struct {
  ChunkLink *chunks;
  gsize      count;                     /* approximative chunks list length */
} Magazine;
typedef struct {
  Magazine   *magazine1;                /* array of MAX_SLAB_INDEX (allocator) */
  Magazine   *magazine2;                /* array of MAX_SLAB_INDEX (allocator) */
} ThreadMemory;
typedef struct {
  gboolean always_malloc;
  gboolean bypass_magazines;
242
  gboolean debug_blocks;
243
  gsize    working_set_msecs;
244
  guint    color_increment;
245 246 247 248 249
} SliceConfig;
typedef struct {
  /* const after initialization */
  gsize         min_page_size, max_page_size;
  SliceConfig   config;
250
  gsize         max_slab_chunk_size_for_magazine_cache;
251
  /* magazine cache */
252
  GMutex        magazine_mutex;
253 254 255 256 257 258
  ChunkLink   **magazines;                /* array of MAX_SLAB_INDEX (allocator) */
  guint        *contention_counters;      /* array of MAX_SLAB_INDEX (allocator) */
  gint          mutex_counter;
  guint         stamp_counter;
  guint         last_stamp;
  /* slab allocator */
259
  GMutex        slab_mutex;
260 261 262 263
  SlabInfo    **slab_stack;                /* array of MAX_SLAB_INDEX (allocator) */
  guint        color_accu;
} Allocator;

264
/* --- g-slice prototypes --- */
265 266
static gpointer     slab_allocator_alloc_chunk       (gsize      chunk_size);
static void         slab_allocator_free_chunk        (gsize      chunk_size,
267 268 269 270 271 272 273
                                                      gpointer   mem);
static void         private_thread_memory_cleanup    (gpointer   data);
static gpointer     allocator_memalign               (gsize      alignment,
                                                      gsize      memsize);
static void         allocator_memfree                (gsize      memsize,
                                                      gpointer   mem);
static inline void  magazine_cache_update_stamp      (void);
274
static inline gsize allocator_get_magazine_threshold (Allocator *allocator,
275 276
                                                      guint      ix);

277 278 279 280 281 282
/* --- g-slice memory checker --- */
static void     smc_notify_alloc  (void   *pointer,
                                   size_t  size);
static int      smc_notify_free   (void   *pointer,
                                   size_t  size);

283
/* --- variables --- */
284
static GPrivate    private_thread_memory = G_PRIVATE_INIT (private_thread_memory_cleanup);
285 286 287
static gsize       sys_page_size = 0;
static Allocator   allocator[1] = { { 0, }, };
static SliceConfig slice_config = {
288 289
  FALSE,        /* always_malloc */
  FALSE,        /* bypass_magazines */
290
  FALSE,        /* debug_blocks */
291
  15 * 1000,    /* working_set_msecs */
292
  1,            /* color increment, alt: 0x7fffffff */
293
};
294
static GMutex      smc_tree_mutex; /* mutex for G_SLICE=debug-blocks */
295

Matthias Clasen's avatar
Matthias Clasen committed
296
/* --- auxiliary funcitons --- */
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
void
g_slice_set_config (GSliceConfig ckey,
                    gint64       value)
{
  g_return_if_fail (sys_page_size == 0);
  switch (ckey)
    {
    case G_SLICE_CONFIG_ALWAYS_MALLOC:
      slice_config.always_malloc = value != 0;
      break;
    case G_SLICE_CONFIG_BYPASS_MAGAZINES:
      slice_config.bypass_magazines = value != 0;
      break;
    case G_SLICE_CONFIG_WORKING_SET_MSECS:
      slice_config.working_set_msecs = value;
      break;
313 314
    case G_SLICE_CONFIG_COLOR_INCREMENT:
      slice_config.color_increment = value;
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
    default: ;
    }
}

gint64
g_slice_get_config (GSliceConfig ckey)
{
  switch (ckey)
    {
    case G_SLICE_CONFIG_ALWAYS_MALLOC:
      return slice_config.always_malloc;
    case G_SLICE_CONFIG_BYPASS_MAGAZINES:
      return slice_config.bypass_magazines;
    case G_SLICE_CONFIG_WORKING_SET_MSECS:
      return slice_config.working_set_msecs;
    case G_SLICE_CONFIG_CHUNK_SIZES:
      return MAX_SLAB_INDEX (allocator);
332 333
    case G_SLICE_CONFIG_COLOR_INCREMENT:
      return slice_config.color_increment;
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
    default:
      return 0;
    }
}

gint64*
g_slice_get_config_state (GSliceConfig ckey,
                          gint64       address,
                          guint       *n_values)
{
  guint i = 0;
  g_return_val_if_fail (n_values != NULL, NULL);
  *n_values = 0;
  switch (ckey)
    {
      gint64 array[64];
    case G_SLICE_CONFIG_CONTENTION_COUNTER:
      array[i++] = SLAB_CHUNK_SIZE (allocator, address);
      array[i++] = allocator->contention_counters[address];
      array[i++] = allocator_get_magazine_threshold (allocator, address);
      *n_values = i;
      return g_memdup (array, sizeof (array[0]) * *n_values);
    default:
      return NULL;
    }
}

361 362 363
static void
slice_config_init (SliceConfig *config)
{
364 365
  const gchar *val;

366
  *config = slice_config;
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382

  val = getenv ("G_SLICE");
  if (val != NULL)
    {
      gint flags;
      const GDebugKey keys[] = {
        { "always-malloc", 1 << 0 },
        { "debug-blocks",  1 << 1 },
      };

      flags = g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
      if (flags & (1 << 0))
        config->always_malloc = TRUE;
      if (flags & (1 << 1))
        config->debug_blocks = TRUE;
    }
383 384 385 386 387 388 389 390 391 392 393
  else
    {
      /* G_SLICE was not specified, so check if valgrind is running and
       * disable ourselves if it is.
       *
       * This way it's possible to force gslice to be enabled under
       * valgrind just by setting G_SLICE to the empty string.
       */
      if (RUNNING_ON_VALGRIND)
        config->always_malloc = TRUE;
    }
394 395
}

396 397
static void
g_slice_init_nomessage (void)
398 399
{
  /* we may not use g_error() or friends here */
400 401
  mem_assert (sys_page_size == 0);
  mem_assert (MIN_MAGAZINE_SIZE >= 4);
402

403
#ifdef G_OS_WIN32
404 405 406 407 408
  {
    SYSTEM_INFO system_info;
    GetSystemInfo (&system_info);
    sys_page_size = system_info.dwPageSize;
  }
409
#else
410
  sys_page_size = sysconf (_SC_PAGESIZE); /* = sysconf (_SC_PAGE_SIZE); = getpagesize(); */
411
#endif
412 413
  mem_assert (sys_page_size >= 2 * LARGEALIGNMENT);
  mem_assert ((sys_page_size & (sys_page_size - 1)) == 0);
414
  slice_config_init (&allocator->config);
415
  allocator->min_page_size = sys_page_size;
416
#if HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN
417 418 419
  /* allow allocation of pages up to 8KB (with 8KB alignment).
   * this is useful because many medium to large sized structures
   * fit less than 8 times (see [4]) into 4KB pages.
420 421
   * we allow very small page sizes here, to reduce wastage in
   * threads if only small allocations are required (this does
422
   * bear the risk of increasing allocation times and fragmentation
423
   * though).
424 425 426
   */
  allocator->min_page_size = MAX (allocator->min_page_size, 4096);
  allocator->max_page_size = MAX (allocator->min_page_size, 8192);
427
  allocator->min_page_size = MIN (allocator->min_page_size, 128);
428 429 430 431
#else
  /* we can only align to system page size */
  allocator->max_page_size = sys_page_size;
#endif
432 433 434 435 436 437 438 439 440 441 442 443 444
  if (allocator->config.always_malloc)
    {
      allocator->contention_counters = NULL;
      allocator->magazines = NULL;
      allocator->slab_stack = NULL;
    }
  else
    {
      allocator->contention_counters = g_new0 (guint, MAX_SLAB_INDEX (allocator));
      allocator->magazines = g_new0 (ChunkLink*, MAX_SLAB_INDEX (allocator));
      allocator->slab_stack = g_new0 (SlabInfo*, MAX_SLAB_INDEX (allocator));
    }

445 446 447 448 449 450 451 452 453 454 455 456
  allocator->mutex_counter = 0;
  allocator->stamp_counter = MAX_STAMP_COUNTER; /* force initial update */
  allocator->last_stamp = 0;
  allocator->color_accu = 0;
  magazine_cache_update_stamp();
  /* values cached for performance reasons */
  allocator->max_slab_chunk_size_for_magazine_cache = MAX_SLAB_CHUNK_SIZE (allocator);
  if (allocator->config.always_malloc || allocator->config.bypass_magazines)
    allocator->max_slab_chunk_size_for_magazine_cache = 0;      /* non-optimized cases */
}

static inline guint
457
allocator_categorize (gsize aligned_chunk_size)
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
{
  /* speed up the likely path */
  if (G_LIKELY (aligned_chunk_size && aligned_chunk_size <= allocator->max_slab_chunk_size_for_magazine_cache))
    return 1;           /* use magazine cache */

  if (!allocator->config.always_malloc &&
      aligned_chunk_size &&
      aligned_chunk_size <= MAX_SLAB_CHUNK_SIZE (allocator))
    {
      if (allocator->config.bypass_magazines)
        return 2;       /* use slab allocator, see [2] */
      return 1;         /* use magazine cache */
    }
  return 0;             /* use malloc() */
}

static inline void
g_mutex_lock_a (GMutex *mutex,
476
                guint  *contention_counter)
477 478 479 480 481 482 483 484 485 486 487 488 489
{
  gboolean contention = FALSE;
  if (!g_mutex_trylock (mutex))
    {
      g_mutex_lock (mutex);
      contention = TRUE;
    }
  if (contention)
    {
      allocator->mutex_counter++;
      if (allocator->mutex_counter >= 1)        /* quickly adapt to contention */
        {
          allocator->mutex_counter = 0;
490
          *contention_counter = MIN (*contention_counter + 1, MAX_MAGAZINE_SIZE);
491 492 493 494 495 496 497 498
        }
    }
  else /* !contention */
    {
      allocator->mutex_counter--;
      if (allocator->mutex_counter < -11)       /* moderately recover magazine sizes */
        {
          allocator->mutex_counter = 0;
499
          *contention_counter = MAX (*contention_counter, 1) - 1;
500 501 502 503 504 505 506
        }
    }
}

static inline ThreadMemory*
thread_memory_from_self (void)
{
507
  ThreadMemory *tmem = g_private_get (&private_thread_memory);
508 509
  if (G_UNLIKELY (!tmem))
    {
510 511 512 513 514 515 516 517 518
      static GMutex init_mutex;
      guint n_magazines;

      g_mutex_lock (&init_mutex);
      if G_UNLIKELY (sys_page_size == 0)
        g_slice_init_nomessage ();
      g_mutex_unlock (&init_mutex);

      n_magazines = MAX_SLAB_INDEX (allocator);
519 520 521
      tmem = g_malloc0 (sizeof (ThreadMemory) + sizeof (Magazine) * 2 * n_magazines);
      tmem->magazine1 = (Magazine*) (tmem + 1);
      tmem->magazine2 = &tmem->magazine1[n_magazines];
522
      g_private_set (&private_thread_memory, tmem);
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
    }
  return tmem;
}

static inline ChunkLink*
magazine_chain_pop_head (ChunkLink **magazine_chunks)
{
  /* magazine chains are linked via ChunkLink->next.
   * each ChunkLink->data of the toplevel chain may point to a subchain,
   * linked via ChunkLink->next. ChunkLink->data of the subchains just
   * contains uninitialized junk.
   */
  ChunkLink *chunk = (*magazine_chunks)->data;
  if (G_UNLIKELY (chunk))
    {
      /* allocating from freed list */
      (*magazine_chunks)->data = chunk->next;
    }
  else
    {
      chunk = *magazine_chunks;
      *magazine_chunks = chunk->next;
    }
  return chunk;
}

549
#if 0 /* useful for debugging */
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
static guint
magazine_count (ChunkLink *head)
{
  guint count = 0;
  if (!head)
    return 0;
  while (head)
    {
      ChunkLink *child = head->data;
      count += 1;
      for (child = head->data; child; child = child->next)
        count += 1;
      head = head->next;
    }
  return count;
}
566
#endif
567

568
static inline gsize
569 570 571 572 573 574
allocator_get_magazine_threshold (Allocator *allocator,
                                  guint      ix)
{
  /* the magazine size calculated here has a lower bound of MIN_MAGAZINE_SIZE,
   * which is required by the implementation. also, for moderately sized chunks
   * (say >= 64 bytes), magazine sizes shouldn't be much smaller then the number
575
   * of chunks available per page/2 to avoid excessive traffic in the magazine
576 577 578 579 580
   * cache for small to medium sized structures.
   * the upper bound of the magazine size is effectively provided by
   * MAX_MAGAZINE_SIZE. for larger chunks, this number is scaled down so that
   * the content of a single magazine doesn't exceed ca. 16KB.
   */
581
  gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
582
  guint threshold = MAX (MIN_MAGAZINE_SIZE, allocator->max_page_size / MAX (5 * chunk_size, 5 * 32));
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
  guint contention_counter = allocator->contention_counters[ix];
  if (G_UNLIKELY (contention_counter))  /* single CPU bias */
    {
      /* adapt contention counter thresholds to chunk sizes */
      contention_counter = contention_counter * 64 / chunk_size;
      threshold = MAX (threshold, contention_counter);
    }
  return threshold;
}

/* --- magazine cache --- */
static inline void
magazine_cache_update_stamp (void)
{
  if (allocator->stamp_counter >= MAX_STAMP_COUNTER)
    {
      GTimeVal tv;
      g_get_current_time (&tv);
      allocator->last_stamp = tv.tv_sec * 1000 + tv.tv_usec / 1000; /* milli seconds */
      allocator->stamp_counter = 0;
    }
  else
    allocator->stamp_counter++;
}

static inline ChunkLink*
magazine_chain_prepare_fields (ChunkLink *magazine_chunks)
{
611 612 613 614
  ChunkLink *chunk1;
  ChunkLink *chunk2;
  ChunkLink *chunk3;
  ChunkLink *chunk4;
615
  /* checked upon initialization: mem_assert (MIN_MAGAZINE_SIZE >= 4); */
616
  /* ensure a magazine with at least 4 unused data pointers */
617 618 619 620
  chunk1 = magazine_chain_pop_head (&magazine_chunks);
  chunk2 = magazine_chain_pop_head (&magazine_chunks);
  chunk3 = magazine_chain_pop_head (&magazine_chunks);
  chunk4 = magazine_chain_pop_head (&magazine_chunks);
621 622 623 624 625 626 627 628 629 630
  chunk4->next = magazine_chunks;
  chunk3->next = chunk4;
  chunk2->next = chunk3;
  chunk1->next = chunk2;
  return chunk1;
}

/* access the first 3 fields of a specially prepared magazine chain */
#define magazine_chain_prev(mc)         ((mc)->data)
#define magazine_chain_stamp(mc)        ((mc)->next->data)
Tim Janik's avatar
Tim Janik committed
631
#define magazine_chain_uint_stamp(mc)   GPOINTER_TO_UINT ((mc)->next->data)
632 633 634 635 636 637 638 639 640 641 642 643
#define magazine_chain_next(mc)         ((mc)->next->next->data)
#define magazine_chain_count(mc)        ((mc)->next->next->next->data)

static void
magazine_cache_trim (Allocator *allocator,
                     guint      ix,
                     guint      stamp)
{
  /* g_mutex_lock (allocator->mutex); done by caller */
  /* trim magazine cache from tail */
  ChunkLink *current = magazine_chain_prev (allocator->magazines[ix]);
  ChunkLink *trash = NULL;
644
  while (ABS (stamp - magazine_chain_uint_stamp (current)) >= allocator->config.working_set_msecs)
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
    {
      /* unlink */
      ChunkLink *prev = magazine_chain_prev (current);
      ChunkLink *next = magazine_chain_next (current);
      magazine_chain_next (prev) = next;
      magazine_chain_prev (next) = prev;
      /* clear special fields, put on trash stack */
      magazine_chain_next (current) = NULL;
      magazine_chain_count (current) = NULL;
      magazine_chain_stamp (current) = NULL;
      magazine_chain_prev (current) = trash;
      trash = current;
      /* fixup list head if required */
      if (current == allocator->magazines[ix])
        {
          allocator->magazines[ix] = NULL;
          break;
        }
      current = prev;
    }
665
  g_mutex_unlock (&allocator->magazine_mutex);
666 667 668
  /* free trash */
  if (trash)
    {
669
      const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
670
      g_mutex_lock (&allocator->slab_mutex);
671 672 673 674 675 676 677 678 679 680 681
      while (trash)
        {
          current = trash;
          trash = magazine_chain_prev (current);
          magazine_chain_prev (current) = NULL; /* clear special field */
          while (current)
            {
              ChunkLink *chunk = magazine_chain_pop_head (&current);
              slab_allocator_free_chunk (chunk_size, chunk);
            }
        }
682
      g_mutex_unlock (&allocator->slab_mutex);
683 684 685 686 687 688 689 690 691 692
    }
}

static void
magazine_cache_push_magazine (guint      ix,
                              ChunkLink *magazine_chunks,
                              gsize      count) /* must be >= MIN_MAGAZINE_SIZE */
{
  ChunkLink *current = magazine_chain_prepare_fields (magazine_chunks);
  ChunkLink *next, *prev;
693
  g_mutex_lock (&allocator->magazine_mutex);
694 695 696 697 698 699 700 701 702 703 704 705 706
  /* add magazine at head */
  next = allocator->magazines[ix];
  if (next)
    prev = magazine_chain_prev (next);
  else
    next = prev = current;
  magazine_chain_next (prev) = current;
  magazine_chain_prev (next) = current;
  magazine_chain_prev (current) = prev;
  magazine_chain_next (current) = next;
  magazine_chain_count (current) = (gpointer) count;
  /* stamp magazine */
  magazine_cache_update_stamp();
Tim Janik's avatar
Tim Janik committed
707
  magazine_chain_stamp (current) = GUINT_TO_POINTER (allocator->last_stamp);
708 709 710 711 712 713 714 715 716 717
  allocator->magazines[ix] = current;
  /* free old magazines beyond a certain threshold */
  magazine_cache_trim (allocator, ix, allocator->last_stamp);
  /* g_mutex_unlock (allocator->mutex); was done by magazine_cache_trim() */
}

static ChunkLink*
magazine_cache_pop_magazine (guint  ix,
                             gsize *countp)
{
718
  g_mutex_lock_a (&allocator->magazine_mutex, &allocator->contention_counters[ix]);
719 720 721 722
  if (!allocator->magazines[ix])
    {
      guint magazine_threshold = allocator_get_magazine_threshold (allocator, ix);
      gsize i, chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
723
      ChunkLink *chunk, *head;
724 725
      g_mutex_unlock (&allocator->magazine_mutex);
      g_mutex_lock (&allocator->slab_mutex);
726 727 728 729
      head = slab_allocator_alloc_chunk (chunk_size);
      head->data = NULL;
      chunk = head;
      for (i = 1; i < magazine_threshold; i++)
730
        {
731 732
          chunk->next = slab_allocator_alloc_chunk (chunk_size);
          chunk = chunk->next;
733 734
          chunk->data = NULL;
        }
735
      chunk->next = NULL;
736
      g_mutex_unlock (&allocator->slab_mutex);
737
      *countp = i;
738
      return head;
739 740 741 742 743 744 745 746 747 748
    }
  else
    {
      ChunkLink *current = allocator->magazines[ix];
      ChunkLink *prev = magazine_chain_prev (current);
      ChunkLink *next = magazine_chain_next (current);
      /* unlink */
      magazine_chain_next (prev) = next;
      magazine_chain_prev (next) = prev;
      allocator->magazines[ix] = next == current ? NULL : next;
749
      g_mutex_unlock (&allocator->magazine_mutex);
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
      /* clear special fields and hand out */
      *countp = (gsize) magazine_chain_count (current);
      magazine_chain_prev (current) = NULL;
      magazine_chain_next (current) = NULL;
      magazine_chain_count (current) = NULL;
      magazine_chain_stamp (current) = NULL;
      return current;
    }
}

/* --- thread magazines --- */
static void
private_thread_memory_cleanup (gpointer data)
{
  ThreadMemory *tmem = data;
  const guint n_magazines = MAX_SLAB_INDEX (allocator);
  guint ix;
  for (ix = 0; ix < n_magazines; ix++)
    {
      Magazine *mags[2];
      guint j;
      mags[0] = &tmem->magazine1[ix];
      mags[1] = &tmem->magazine2[ix];
      for (j = 0; j < 2; j++)
        {
          Magazine *mag = mags[j];
          if (mag->count >= MIN_MAGAZINE_SIZE)
            magazine_cache_push_magazine (ix, mag->chunks, mag->count);
          else
            {
780
              const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
781
              g_mutex_lock (&allocator->slab_mutex);
782 783 784 785 786
              while (mag->chunks)
                {
                  ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
                  slab_allocator_free_chunk (chunk_size, chunk);
                }
787
              g_mutex_unlock (&allocator->slab_mutex);
788 789 790 791 792 793 794 795 796 797 798
            }
        }
    }
  g_free (tmem);
}

static void
thread_memory_magazine1_reload (ThreadMemory *tmem,
                                guint         ix)
{
  Magazine *mag = &tmem->magazine1[ix];
799
  mem_assert (mag->chunks == NULL); /* ensure that we may reset mag->count */
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
  mag->count = 0;
  mag->chunks = magazine_cache_pop_magazine (ix, &mag->count);
}

static void
thread_memory_magazine2_unload (ThreadMemory *tmem,
                                guint         ix)
{
  Magazine *mag = &tmem->magazine2[ix];
  magazine_cache_push_magazine (ix, mag->chunks, mag->count);
  mag->chunks = NULL;
  mag->count = 0;
}

static inline void
thread_memory_swap_magazines (ThreadMemory *tmem,
                              guint         ix)
{
  Magazine xmag = tmem->magazine1[ix];
  tmem->magazine1[ix] = tmem->magazine2[ix];
  tmem->magazine2[ix] = xmag;
}

static inline gboolean
thread_memory_magazine1_is_empty (ThreadMemory *tmem,
                                  guint         ix)
{
  return tmem->magazine1[ix].chunks == NULL;
}

static inline gboolean
thread_memory_magazine2_is_full (ThreadMemory *tmem,
                                 guint         ix)
{
  return tmem->magazine2[ix].count >= allocator_get_magazine_threshold (allocator, ix);
}

static inline gpointer
thread_memory_magazine1_alloc (ThreadMemory *tmem,
                               guint         ix)
{
  Magazine *mag = &tmem->magazine1[ix];
  ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
  if (G_LIKELY (mag->count > 0))
    mag->count--;
  return chunk;
}

static inline void
thread_memory_magazine2_free (ThreadMemory *tmem,
                              guint         ix,
                              gpointer      mem)
{
  Magazine *mag = &tmem->magazine2[ix];
  ChunkLink *chunk = mem;
  chunk->data = NULL;
  chunk->next = mag->chunks;
  mag->chunks = chunk;
  mag->count++;
}

/* --- API functions --- */
862 863 864 865 866 867 868 869

/**
 * g_slice_new:
 * @type: the type to allocate, typically a structure name
 *
 * A convenience macro to allocate a block of memory from the
 * slice allocator.
 *
870 871 872
 * It calls g_slice_alloc() with `sizeof (@type)` and casts the
 * returned pointer to a pointer of the given type, avoiding a type
 * cast in the source code. Note that the underlying slice allocation
873
 * mechanism can be changed with the [`G_SLICE=always-malloc`][G_SLICE]
874 875
 * environment variable.
 *
876 877 878 879 880
 * This can never return %NULL as the minimum allocation size from
 * `sizeof (@type)` is 1 byte.
 *
 * Returns: (not nullable): a pointer to the allocated block, cast to a pointer
 *    to @type
881 882 883 884 885 886 887 888 889 890 891
 *
 * Since: 2.10
 */

/**
 * g_slice_new0:
 * @type: the type to allocate, typically a structure name
 *
 * A convenience macro to allocate a block of memory from the
 * slice allocator and set the memory to 0.
 *
892
 * It calls g_slice_alloc0() with `sizeof (@type)`
893 894 895
 * and casts the returned pointer to a pointer of the given type,
 * avoiding a type cast in the source code.
 * Note that the underlying slice allocation mechanism can
896
 * be changed with the [`G_SLICE=always-malloc`][G_SLICE]
897 898
 * environment variable.
 *
899 900 901 902 903 904
 * This can never return %NULL as the minimum allocation size from
 * `sizeof (@type)` is 1 byte.
 *
 * Returns: (not nullable): a pointer to the allocated block, cast to a pointer
 *    to @type
 *
905 906 907 908 909 910
 * Since: 2.10
 */

/**
 * g_slice_dup:
 * @type: the type to duplicate, typically a structure name
911
 * @mem: (not nullable): the memory to copy into the allocated block
912 913 914 915
 *
 * A convenience macro to duplicate a block of memory using
 * the slice allocator.
 *
916
 * It calls g_slice_copy() with `sizeof (@type)`
917 918 919
 * and casts the returned pointer to a pointer of the given type,
 * avoiding a type cast in the source code.
 * Note that the underlying slice allocation mechanism can
920
 * be changed with the [`G_SLICE=always-malloc`][G_SLICE]
921 922
 * environment variable.
 *
923 924 925 926
 * This can never return %NULL.
 *
 * Returns: (not nullable): a pointer to the allocated block, cast to a pointer
 *    to @type
927 928 929 930 931 932 933 934 935 936 937 938
 *
 * Since: 2.14
 */

/**
 * g_slice_free:
 * @type: the type of the block to free, typically a structure name
 * @mem: a pointer to the block to free
 *
 * A convenience macro to free a block of memory that has
 * been allocated from the slice allocator.
 *
939
 * It calls g_slice_free1() using `sizeof (type)`
940 941
 * as the block size.
 * Note that the exact release behaviour can be changed with the
942 943
 * [`G_DEBUG=gc-friendly`][G_DEBUG] environment variable, also see
 * [`G_SLICE`][G_SLICE] for related debugging options.
944
 *
945 946
 * If @mem is %NULL, this macro does nothing.
 *
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
 * Since: 2.10
 */

/**
 * g_slice_free_chain:
 * @type: the type of the @mem_chain blocks
 * @mem_chain: a pointer to the first block of the chain
 * @next: the field name of the next pointer in @type
 *
 * Frees a linked list of memory blocks of structure type @type.
 * The memory blocks must be equal-sized, allocated via
 * g_slice_alloc() or g_slice_alloc0() and linked together by
 * a @next pointer (similar to #GSList). The name of the
 * @next field in @type is passed as third argument.
 * Note that the exact release behaviour can be changed with the
962 963
 * [`G_DEBUG=gc-friendly`][G_DEBUG] environment variable, also see
 * [`G_SLICE`][G_SLICE] for related debugging options.
964
 *
965 966
 * If @mem_chain is %NULL, this function does nothing.
 *
967 968 969 970 971 972 973 974
 * Since: 2.10
 */

/**
 * g_slice_alloc:
 * @block_size: the number of bytes to allocate
 *
 * Allocates a block of memory from the slice allocator.
975
 * The block address handed out can be expected to be aligned
976
 * to at least 1 * sizeof (void*),
977 978 979 980
 * though in general slices are 2 * sizeof (void*) bytes aligned,
 * if a malloc() fallback implementation is used instead,
 * the alignment may be reduced in a libc dependent fashion.
 * Note that the underlying slice allocation mechanism can
981
 * be changed with the [`G_SLICE=always-malloc`][G_SLICE]
982 983
 * environment variable.
 *
984 985
 * Returns: a pointer to the allocated memory block, which will be %NULL if and
 *    only if @mem_size is 0
986 987 988
 *
 * Since: 2.10
 */
989 990 991
gpointer
g_slice_alloc (gsize mem_size)
{
992
  ThreadMemory *tmem;
993 994 995
  gsize chunk_size;
  gpointer mem;
  guint acat;
996 997 998 999 1000 1001 1002 1003 1004

  /* This gets the private structure for this thread.  If the private
   * structure does not yet exist, it is created.
   *
   * This has a side effect of causing GSlice to be initialised, so it
   * must come first.
   */
  tmem = thread_memory_from_self ();

1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
  chunk_size = P2ALIGN (mem_size);
  acat = allocator_categorize (chunk_size);
  if (G_LIKELY (acat == 1))     /* allocate through magazine layer */
    {
      guint ix = SLAB_INDEX (allocator, chunk_size);
      if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
        {
          thread_memory_swap_magazines (tmem, ix);
          if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
            thread_memory_magazine1_reload (tmem, ix);
        }
      mem = thread_memory_magazine1_alloc (tmem, ix);
    }
  else if (acat == 2)           /* allocate through slab allocator */
    {
1020
      g_mutex_lock (&allocator->slab_mutex);
1021
      mem = slab_allocator_alloc_chunk (chunk_size);
1022
      g_mutex_unlock (&allocator->slab_mutex);
1023 1024 1025
    }
  else                          /* delegate to system malloc */
    mem = g_malloc (mem_size);
1026 1027
  if (G_UNLIKELY (allocator->config.debug_blocks))
    smc_notify_alloc (mem, mem_size);
1028 1029 1030

  TRACE (GLIB_SLICE_ALLOC((void*)mem, mem_size));

1031 1032 1033
  return mem;
}

1034 1035 1036 1037 1038 1039
/**
 * g_slice_alloc0:
 * @block_size: the number of bytes to allocate
 *
 * Allocates a block of memory via g_slice_alloc() and initializes
 * the returned memory to 0. Note that the underlying slice allocation
1040
 * mechanism can be changed with the [`G_SLICE=always-malloc`][G_SLICE]
1041 1042
 * environment variable.
 *
1043 1044
 * Returns: a pointer to the allocated block, which will be %NULL if and only
 *    if @mem_size is 0
1045 1046 1047
 *
 * Since: 2.10
 */
1048
gpointer
1049
g_slice_alloc0 (gsize mem_size)
1050 1051 1052 1053 1054 1055 1056
{
  gpointer mem = g_slice_alloc (mem_size);
  if (mem)
    memset (mem, 0, mem_size);
  return mem;
}

1057 1058 1059 1060 1061 1062 1063 1064
/**
 * g_slice_copy:
 * @block_size: the number of bytes to allocate
 * @mem_block: the memory to copy
 *
 * Allocates a block of memory from the slice allocator
 * and copies @block_size bytes into it from @mem_block.
 *
1065 1066 1067 1068
 * @mem_block must be non-%NULL if @block_size is non-zero.
 *
 * Returns: a pointer to the allocated memory block, which will be %NULL if and
 *    only if @mem_size is 0
1069 1070 1071
 *
 * Since: 2.14
 */
1072
gpointer
1073 1074
g_slice_copy (gsize         mem_size,
              gconstpointer mem_block)
1075 1076 1077 1078 1079 1080 1081
{
  gpointer mem = g_slice_alloc (mem_size);
  if (mem)
    memcpy (mem, mem_block, mem_size);
  return mem;
}

1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
/**
 * g_slice_free1:
 * @block_size: the size of the block
 * @mem_block: a pointer to the block to free
 *
 * Frees a block of memory.
 *
 * The memory must have been allocated via g_slice_alloc() or
 * g_slice_alloc0() and the @block_size has to match the size
 * specified upon allocation. Note that the exact release behaviour
1092 1093
 * can be changed with the [`G_DEBUG=gc-friendly`][G_DEBUG] environment
 * variable, also see [`G_SLICE`][G_SLICE] for related debugging options.
1094
 *
1095 1096
 * If @mem_block is %NULL, this function does nothing.
 *
1097 1098
 * Since: 2.10
 */
1099
void
1100
g_slice_free1 (gsize    mem_size,
1101 1102
               gpointer mem_block)
{
1103
  gsize chunk_size = P2ALIGN (mem_size);
1104 1105
  guint acat = allocator_categorize (chunk_size);
  if (G_UNLIKELY (!mem_block))
1106
    return;
1107 1108 1109
  if (G_UNLIKELY (allocator->config.debug_blocks) &&
      !smc_notify_free (mem_block, mem_size))
    abort();
1110
  if (G_LIKELY (acat == 1))             /* allocate through magazine layer */
1111 1112 1113 1114 1115 1116 1117 1118 1119
    {
      ThreadMemory *tmem = thread_memory_from_self();
      guint ix = SLAB_INDEX (allocator, chunk_size);
      if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
        {
          thread_memory_swap_magazines (tmem, ix);
          if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
            thread_memory_magazine2_unload (tmem, ix);
        }
1120 1121
      if (G_UNLIKELY (g_mem_gc_friendly))
        memset (mem_block, 0, chunk_size);
1122 1123 1124 1125
      thread_memory_magazine2_free (tmem, ix, mem_block);
    }
  else if (acat == 2)                   /* allocate through slab allocator */
    {
1126 1127
      if (G_UNLIKELY (g_mem_gc_friendly))
        memset (mem_block, 0, chunk_size);
1128
      g_mutex_lock (&allocator->slab_mutex);
1129
      slab_allocator_free_chunk (chunk_size, mem_block);
1130
      g_mutex_unlock (&allocator->slab_mutex);
1131
    }
1132
  else                                  /* delegate to system malloc */
1133 1134 1135 1136 1137
    {
      if (G_UNLIKELY (g_mem_gc_friendly))
        memset (mem_block, 0, mem_size);
      g_free (mem_block);
    }
1138
  TRACE (GLIB_SLICE_FREE((void*)mem_block, mem_size));
1139 1140
}

1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
/**
 * g_slice_free_chain_with_offset:
 * @block_size: the size of the blocks
 * @mem_chain:  a pointer to the first block of the chain
 * @next_offset: the offset of the @next field in the blocks
 *
 * Frees a linked list of memory blocks of structure type @type.
 *
 * The memory blocks must be equal-sized, allocated via
 * g_slice_alloc() or g_slice_alloc0() and linked together by a
 * @next pointer (similar to #GSList). The offset of the @next
 * field in each block is passed as third argument.
 * Note that the exact release behaviour can be changed with the
1154 1155
 * [`G_DEBUG=gc-friendly`][G_DEBUG] environment variable, also see
 * [`G_SLICE`][G_SLICE] for related debugging options.
1156
 *
1157 1158
 * If @mem_chain is %NULL, this function does nothing.
 *
1159 1160
 * Since: 2.10
 */
1161
void
1162 1163 1164
g_slice_free_chain_with_offset (gsize    mem_size,
                                gpointer mem_chain,
                                gsize    next_offset)
1165
{
1166
  gpointer slice = mem_chain;
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
  /* while the thread magazines and the magazine cache are implemented so that
   * they can easily be extended to allow for free lists containing more free
   * lists for the first level nodes, which would allow O(1) freeing in this
   * function, the benefit of such an extension is questionable, because:
   * - the magazine size counts will become mere lower bounds which confuses
   *   the code adapting to lock contention;
   * - freeing a single node to the thread magazines is very fast, so this
   *   O(list_length) operation is multiplied by a fairly small factor;
   * - memory usage histograms on larger applications seem to indicate that
   *   the amount of released multi node lists is negligible in comparison
   *   to single node releases.
1178 1179 1180
   * - the major performance bottle neck, namely g_private_get() or
   *   g_mutex_lock()/g_mutex_unlock() has already been moved out of the
   *   inner loop for freeing chained slices.
1181
   */
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
  gsize chunk_size = P2ALIGN (mem_size);
  guint acat = allocator_categorize (chunk_size);
  if (G_LIKELY (acat == 1))             /* allocate through magazine layer */
    {
      ThreadMemory *tmem = thread_memory_from_self();
      guint ix = SLAB_INDEX (allocator, chunk_size);
      while (slice)
        {
          guint8 *current = slice;
          slice = *(gpointer*) (current + next_offset);
1192 1193 1194
          if (G_UNLIKELY (allocator->config.debug_blocks) &&
              !smc_notify_free (current, mem_size))
            abort();
1195 1196 1197 1198 1199 1200
          if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
            {
              thread_memory_swap_magazines (tmem, ix);
              if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
                thread_memory_magazine2_unload (tmem, ix);
            }
1201 1202
          if (G_UNLIKELY (g_mem_gc_friendly))
            memset (current, 0, chunk_size);
1203 1204 1205 1206 1207
          thread_memory_magazine2_free (tmem, ix, current);
        }
    }
  else if (acat == 2)                   /* allocate through slab allocator */
    {
1208
      g_mutex_lock (&allocator->slab_mutex);
1209 1210 1211 1212
      while (slice)
        {
          guint8 *current = slice;
          slice = *(gpointer*) (current + next_offset);
1213 1214 1215
          if (G_UNLIKELY (allocator->config.debug_blocks) &&
              !smc_notify_free (current, mem_size))
            abort();
1216 1217
          if (G_UNLIKELY (g_mem_gc_friendly))
            memset (current, 0, chunk_size);
1218 1219
          slab_allocator_free_chunk (chunk_size, current);
        }
1220
      g_mutex_unlock (&allocator->slab_mutex);
1221 1222 1223 1224 1225 1226
    }
  else                                  /* delegate to system malloc */
    while (slice)
      {
        guint8 *current = slice;
        slice = *(gpointer*) (current + next_offset);
1227 1228 1229
        if (G_UNLIKELY (allocator->config.debug_blocks) &&
            !smc_notify_free (current, mem_size))
          abort();
1230 1231
        if (G_UNLIKELY (g_mem_gc_friendly))
          memset (current, 0, mem_size);
1232 1233
        g_free (current);
      }
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
}

/* --- single page allocator --- */
static void
allocator_slab_stack_push (Allocator *allocator,
                           guint      ix,
                           SlabInfo  *sinfo)
{
  /* insert slab at slab ring head */
  if (!allocator->slab_stack[ix])
    {
      sinfo->next = sinfo;
      sinfo->prev = sinfo;
    }
  else
    {
      SlabInfo *next = allocator->slab_stack[ix], *prev = next->prev;
      next->prev = sinfo;
      prev->next = sinfo;
      sinfo->next = next;
      sinfo->prev = prev;
    }
  allocator->slab_stack[ix] = sinfo;
}

1259 1260 1261 1262 1263 1264 1265 1266 1267
static gsize
allocator_aligned_page_size (Allocator *allocator,
                             gsize      n_bytes)
{
  gsize val = 1 << g_bit_storage (n_bytes - 1);
  val = MAX (val, allocator->min_page_size);
  return val;
}

1268 1269 1270
static void
allocator_add_slab (Allocator *allocator,
                    guint      ix,
1271
                    gsize      chunk_size)
1272
{
1273
  ChunkLink *chunk;
1274
  SlabInfo *sinfo;
1275
  gsize addr, padding, n_chunks, color = 0;
1276
  gsize page_size;
1277
  int errsv;
1278 1279 1280 1281 1282
  gpointer aligned_memory;
  guint8 *mem;
  guint i;

  page_size = allocator_aligned_page_size (allocator, SLAB_BPAGE_SIZE (allocator, chunk_size));
1283
  /* allocate 1 page for the chunks and the slab */
1284
  aligned_memory = allocator_memalign (page_size, page_size - NATIVE_MALLOC_PADDING);
1285
  errsv = errno;
1286 1287
  mem = aligned_memory;

1288
  if (!mem)
1289
    {
1290
      const gchar *syserr = strerror (errsv);
1291 1292 1293
      mem_error ("failed to allocate %u bytes (alignment: %u): %s\n",
                 (guint) (page_size - NATIVE_MALLOC_PADDING), (guint) page_size, syserr);
    }
Matthias Clasen's avatar
Matthias Clasen committed
1294
  /* mask page address */
1295
  addr = ((gsize) mem / page_size) * page_size;
1296
  /* assert alignment */
1297
  mem_assert (aligned_memory == (gpointer) addr);
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
  /* basic slab info setup */
  sinfo = (SlabInfo*) (mem + page_size - SLAB_INFO_SIZE);
  sinfo->n_allocated = 0;
  sinfo->chunks = NULL;
  /* figure cache colorization */
  n_chunks = ((guint8*) sinfo - mem) / chunk_size;
  padding = ((guint8*) sinfo - mem) - n_chunks * chunk_size;
  if (padding)
    {
      color = (allocator->color_accu * P2ALIGNMENT) % padding;
1308
      allocator->color_accu += allocator->config.color_increment;
1309 1310
    }
  /* add chunks to free list */
1311
  chunk = (ChunkLink*) (mem + color);
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
  sinfo->chunks = chunk;
  for (i = 0; i < n_chunks - 1; i++)
    {
      chunk->next = (ChunkLink*) ((guint8*) chunk + chunk_size);
      chunk = chunk->next;
    }
  chunk->next = NULL;   /* last chunk */
  /* add slab to slab ring */
  allocator_slab_stack_push (allocator, ix, sinfo);
}

static gpointer
1324
slab_allocator_alloc_chunk (gsize chunk_size)
1325
{
1326
  ChunkLink *chunk;
1327 1328 1329 1330 1331
  guint ix = SLAB_INDEX (allocator, chunk_size);
  /* ensure non-empty slab */
  if (!allocator->slab_stack[ix] || !allocator->slab_stack[ix]->chunks)
    allocator_add_slab (allocator, ix, chunk_size);
  /* allocate chunk */
1332
  chunk = allocator->slab_stack[ix]->chunks;
1333 1334 1335 1336 1337 1338 1339 1340 1341
  allocator->slab_stack[ix]->chunks = chunk->next;
  allocator->slab_stack[ix]->n_allocated++;
  /* rotate empty slabs */
  if (!allocator->slab_stack[ix]->chunks)
    allocator->slab_stack[ix] = allocator->slab_stack[ix]->next;
  return chunk;
}

static void
1342
slab_allocator_free_chunk (gsize    chunk_size,
1343 1344
                           gpointer mem)
{
1345 1346
  ChunkLink *chunk;
  gboolean was_empty;
1347
  guint ix = SLAB_INDEX (allocator, chunk_size);
1348
  gsize page_size = allocator_aligned_page_size (allocator, SLAB_BPAGE_SIZE (allocator, chunk_size));
1349
  gsize addr = ((gsize) mem / page_size) * page_size;
Matthias Clasen's avatar
Matthias Clasen committed
1350
  /* mask page address */
1351 1352 1353
  guint8 *page = (guint8*) addr;
  SlabInfo *sinfo = (SlabInfo*) (page + page_size - SLAB_INFO_SIZE);
  /* assert valid chunk count */
1354
  mem_assert (sinfo->n_allocated > 0);
1355
  /* add chunk to free list */
1356 1357
  was_empty = sinfo->chunks == NULL;
  chunk = (ChunkLink*) mem;
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
  chunk->next = sinfo->chunks;
  sinfo->chunks = chunk;
  sinfo->n_allocated--;
  /* keep slab ring partially sorted, empty slabs at end */
  if (was_empty)
    {
      /* unlink slab */
      SlabInfo *next = sinfo->next, *prev = sinfo->prev;
      next->prev = prev;
      prev->next = next;
      if (allocator->slab_stack[ix] == sinfo)
        allocator->slab_stack[ix] = next == sinfo ? NULL : next;
      /* insert slab at head */
      allocator_slab_stack_push (allocator, ix, sinfo);
    }
  /* eagerly free complete unused slabs */
  if (!sinfo->n_allocated)
    {
      /* unlink slab */
      SlabInfo *next = sinfo->next, *prev = sinfo->prev;
      next->prev = prev;
      prev->next = next;
      if (allocator->slab_stack[ix] == sinfo)
        allocator->slab_stack[ix] = next == sinfo ? NULL : next;
      /* free slab */
      allocator_memfree (page_size, page);
    }
}

/* --- memalign implementation --- */
1388
#ifdef HAVE_MALLOC_H
1389
#include <malloc.h>             /* memalign() */
1390
#endif
1391 1392

/* from config.h:
1393 1394 1395 1396
 * define HAVE_POSIX_MEMALIGN           1 // if free(posix_memalign(3)) works, <stdlib.h>
 * define HAVE_COMPLIANT_POSIX_MEMALIGN 1 // if free(posix_memalign(3)) works for sizes != 2^n, <stdlib.h>
 * define HAVE_MEMALIGN                 1 // if free(memalign(3)) works, <malloc.h>
 * define HAVE_VALLOC                   1 // if free(valloc(3)) works, <stdlib.h> or <malloc.h>
1397 1398 1399
 * if none is provided, we implement malloc(3)-based alloc-only page alignment
 */

1400
#if !(HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC)
1401 1402 1403 1404 1405 1406 1407 1408 1409
static GTrashStack *compat_valloc_trash = NULL;
#endif

static gpointer
allocator_memalign (gsize alignment,
                    gsize memsize)
{
  gpointer aligned_memory = NULL;
  gint err = ENOMEM;
1410
#if     HAVE_COMPLIANT_POSIX_MEMALIGN
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
  err = posix_memalign (&aligned_memory, alignment, memsize);
#elif   HAVE_MEMALIGN
  errno = 0;
  aligned_memory = memalign (alignment, memsize);
  err = errno;
#elif   HAVE_VALLOC
  errno = 0;
  aligned_memory = valloc (memsize);
  err = errno;
#else
  /* simplistic non-freeing page allocator */
1422 1423
  mem_assert (alignment == sys_page_size);
  mem_assert (memsize <= sys_page_size);
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
  if (!compat_valloc_trash)
    {
      const guint n_pages = 16;
      guint8 *mem = malloc (n_pages * sys_page_size);
      err = errno;
      if (mem)
        {
          gint i = n_pages;
          guint8 *amem = (guint8*) ALIGN ((gsize) mem, sys_page_size);
          if (amem != mem)
            i--;        /* mem wasn't page aligned */
          while (--i >= 0)
            g_trash_stack_push (&compat_valloc_trash, amem + i * sys_page_size);
        }
    }
  aligned_memory = g_trash_stack_pop (&compat_valloc_trash);
#endif
  if (!aligned_memory)
    errno = err;
  return aligned_memory;
}

static void
allocator_memfree (gsize    memsize,
                   gpointer mem)
{
1450
#if     HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC
1451 1452
  free (mem);
#else
1453
  mem_assert (memsize <= sys_page_size);
1454 1455 1456 1457
  g_trash_stack_push (&compat_valloc_trash, mem);
#endif
}

1458 1459 1460 1461 1462 1463 1464 1465 1466
static void
mem_error (const char *format,
           ...)
{
  const char *pname;
  va_list args;
  /* at least, put out "MEMORY-ERROR", in case we segfault during the rest of the function */
  fputs ("\n***MEMORY-ERROR***: ", stderr);
  pname = g_get_prgname();
1467
  fprintf (stderr, "%s[%ld]: GSlice: ", pname ? pname : "", (long)getpid());
1468 1469 1470 1471
  va_start (args, format);
  vfprintf (stderr, format, args);
  va_end (args);
  fputs ("\n", stderr);
1472
  abort();
1473 1474 1475
  _exit (1);
}

1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
/* --- g-slice memory checker tree --- */
typedef size_t SmcKType;                /* key type */
typedef size_t SmcVType;                /* value type */
typedef struct {
  SmcKType key;
  SmcVType value;
} SmcEntry;
static void             smc_tree_insert      (SmcKType  key,
                                              SmcVType  value);
static gboolean         smc_tree_lookup      (SmcKType  key,
                                              SmcVType *value_p);
static gboolean         smc_tree_remove      (SmcKType  key);


/* --- g-slice memory checker implementation --- */
static void
smc_notify_alloc (void   *pointer,
                  size_t  size)
{
1495
  size_t address = (size_t) pointer;
1496
  if (pointer)
1497
    smc_tree_insert (address, size);
1498 1499 1500 1501 1502 1503
}

#if 0
static void
smc_notify_ignore (void *pointer)
{
1504
  size_t address = (size_t) pointer;
1505
  if (pointer)
1506
    smc_tree_remove (address);
1507 1508 1509 1510 1511 1512 1513
}
#endif

static int
smc_notify_free (void   *pointer,
                 size_t  size)
{
1514
  size_t address = (size_t) pointer;
1515 1516 1517
  SmcVType real_size;
  gboolean found_one;

1518 1519
  if (!pointer)
    return 1; /* ignore */
1520
  found_one = smc_tree_lookup (address, &real_size);
1521 1522
  if (!found_one)
    {
1523
      fprintf (stderr, "GSlice: MemChecker: attempt to release non-allocated block: %p size=%" G_GSIZE_FORMAT "\n", pointer, size);
1524 1525 1526 1527
      return 0;
    }
  if (real_size != size && (real_size || size))
    {
1528
      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);
1529 1530
      return 0;
    }
1531
  if (!smc_tree_remove (address))
1532
    {
1533
      fprintf (stderr, "GSlice: MemChecker: attempt to release non-allocated block: %p size=%" G_GSIZE_FORMAT "\n", pointer, size);
1534 1535 1536 1537 1538 1539 1540 1541
      return 0;
    }
  return 1; /* all fine */
}

/* --- g-slice memory checker tree implementation --- */
#define SMC_TRUNK_COUNT     (4093 /* 16381 */)          /* prime, to distribute trunk collisions (big, allocated just once) */
#define SMC_BRANCH_COUNT    (511)                       /* prime, to distribute branch collisions */
1542
#define SMC_TRUNK_EXTENT    (SMC_BRANCH_COUNT * 2039)   /* key address space per trunk, should distribute uniformly across BRANCH_COUNT */
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
#define SMC_TRUNK_HASH(k)   ((k / SMC_TRUNK_EXTENT) % SMC_TRUNK_COUNT)  /* generate new trunk hash per megabyte (roughly) */
#define SMC_BRANCH_HASH(k)  (k % SMC_BRANCH_COUNT)

typedef struct {
  SmcEntry    *entries;
  unsigned int n_entries;
} SmcBranch;

static SmcBranch     **smc_tree_root = NULL;

static void
smc_tree_abort (int errval)
{
Dan Winship's avatar
Dan Winship committed
1556
  const char *syserr = strerror (errval);
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
  mem_error ("MemChecker: failure in debugging tree: %s", syserr);
}

static inline SmcEntry*
smc_tree_branch_grow_L (SmcBranch   *branch,
                        unsigned int index)
{
  unsigned int old_size = branch->n_entries * sizeof (branch->entries[0]);
  unsigned int new_size = old_size + sizeof (branch->entries[0]);
  SmcEntry *entry;
  mem_assert (index <= branch->n_entries);
  branch->entries = (SmcEntry*) realloc (branch->entries, new_size);
  if (!branch->entries)
    smc_tree_abort (errno);
  entry = branch->entries + index;
Dan Winship's avatar
Dan Winship committed
1572
  memmove (entry + 1, entry, (branch->n_entries - index) * sizeof (entry[0]));
1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
  branch->n_entries += 1;
  return entry;
}

static inline SmcEntry*
smc_tree_branch_lookup_nearest_L (SmcBranch *branch,
                                  SmcKType   key)
{
  unsigned int n_nodes = branch->n_entries, offs = 0;
  SmcEntry *check = branch->entries;
  int cmp = 0;
  while (offs < n_nodes)
    {
      unsigned int i = (offs + n_nodes) >> 1;
      check = branch->entries + i;
      cmp = key < check->key ? -1 : key != check->key;
      if (cmp == 0)
        return check;                   /* return exact match */
      else if (cmp < 0)
        n_nodes = i;
      else /* (cmp > 0) */
        offs = i + 1;
    }
  /* check points at last mismatch, cmp > 0 indicates greater key */
  return cmp > 0 ? check + 1 : check;   /* return insertion position for inexact match */
}

static void
smc_tree_insert (SmcKType key,
                 SmcVType value)
{
1604 1605 1606
  unsigned int ix0, ix1;
  SmcEntry *entry;

1607
  g_mutex_lock (&smc_tree_mutex);
1608 1609
  ix0 = SMC_TRUNK_HASH (key);
  ix1 = SMC_BRANCH_HASH (key);
1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621
  if (!smc_tree_root)
    {
      smc_tree_root = calloc (SMC_TRUNK_COUNT, sizeof (smc_tree_root[0]));
      if (!smc_tree_root)
        smc_tree_abort (errno);
    }
  if (!smc_tree_root[ix0])
    {
      smc_tree_root[ix0] = calloc (SMC_BRANCH_COUNT, sizeof (smc_tree_root[0][0]));
      if (!smc_tree_root[ix0])
        smc_tree_abort (errno);
    }
1622
  entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
1623 1624 1625 1626 1627 1628
  if (!entry ||                                                                         /* need create */
      entry >= smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries ||   /* need append */
      entry->key != key)                                                                /* need insert */
    entry = smc_tree_branch_grow_L (&smc_tree_root[ix0][ix1], entry - smc_tree_root[ix0][ix1].entries);
  entry->key = key;
  entry->value = value;
1629
  g_mutex_unlock (&smc_tree_mutex);
1630 1631 1632 1633 1634 1635
}

static gboolean
smc_tree_lookup (SmcKType  key,
                 SmcVType *value_p)
{
1636
  SmcEntry *entry = NULL;
1637 1638 1639
  unsigned int ix0 = SMC_TRUNK_HASH (key), ix1 = SMC_BRANCH_HASH (key);
  gboolean found_one = FALSE;
  *value_p = 0;
1640
  g_mutex_lock (&smc_tree_mutex);
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
  if (smc_tree_root && smc_tree_root[ix0])
    {
      entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
      if (entry &&
          entry < smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries &&
          entry->key == key)
        {
          found_one = TRUE;
          *value_p = entry->value;
        }
    }
1652
  g_mutex_unlock (&smc_tree_mutex);
1653 1654 1655 1656 1657 1658 1659 1660
  return found_one;
}

static gboolean
smc_tree_remove (SmcKType key)
{
  unsigned int ix0 = SMC_TRUNK_HASH (key), ix1 = SMC_BRANCH_HASH (key);
  gboolean found_one = FALSE;
1661
  g_mutex_lock (&smc_tree_mutex);
1662 1663 1664 1665 1666 1667 1668 1669 1670
  if (smc_tree_root && smc_tree_root[ix0])
    {
      SmcEntry *entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
      if (entry &&
          entry < smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries &&
          entry->key == key)
        {
          unsigned int i = entry - smc_tree_root[ix0][ix1].entries;
          smc_tree_root[ix0][ix1].n_entries -= 1;
Dan Winship's avatar
Dan Winship committed
1671
          memmove (entry, entry + 1, (smc_tree_root[ix0][ix1].n_entries - i) * sizeof (entry[0]));
1672 1673 1674 1675 1676 1677 1678 1679 1680
          if (!smc_tree_root[ix0][ix1].n_entries)
            {
              /* avoid useless pressure on the memory system */
              free (smc_tree_root[ix0][ix1].entries);
              smc_tree_root[ix0][ix1].entries = NULL;
            }
          found_one = TRUE;
        }
    }
1681
  g_mutex_unlock (&smc_tree_mutex);
1682 1683 1684
  return found_one;
}

1685
#ifdef G_ENABLE_DEBUG
1686 1687 1688
void
g_slice_debug_tree_statistics (void)
{
1689
  g_mutex_lock (&smc_tree_mutex);
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
  if (smc_tree_root)
    {
      unsigned int i, j, t = 0, o = 0, b = 0, su = 0, ex = 0, en = 4294967295u;
      double tf, bf;
      for (i = 0; i < SMC_TRUNK_COUNT; i++)
        if (smc_tree_root[i])
          {
            t++;
            for (j = 0; j < SMC_BRANCH_COUNT; j++)
              if (smc_tree_root[i][j].n_entries)
                {
                  b++;
                  su += smc_tree_root[i][j].n_entries;
                  en = MIN (en, smc_tree_root[i][j].n_entries);
                  ex = MAX (ex, smc_tree_root[