Blame glib/gslice.c

Packit ae235b
/* GLIB sliced memory - fast concurrent memory chunk allocator
Packit ae235b
 * Copyright (C) 2005 Tim Janik
Packit ae235b
 *
Packit ae235b
 * This library is free software; you can redistribute it and/or
Packit ae235b
 * modify it under the terms of the GNU Lesser General Public
Packit ae235b
 * License as published by the Free Software Foundation; either
Packit ae235b
 * version 2.1 of the License, or (at your option) any later version.
Packit ae235b
 *
Packit ae235b
 * This library is distributed in the hope that it will be useful,
Packit ae235b
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Packit ae235b
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Packit ae235b
 * Lesser General Public License for more details.
Packit ae235b
 *
Packit ae235b
 * You should have received a copy of the GNU Lesser General Public
Packit ae235b
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
Packit ae235b
 */
Packit ae235b
/* MT safe */
Packit ae235b
Packit ae235b
#include "config.h"
Packit ae235b
#include "glibconfig.h"
Packit ae235b
Packit ae235b
#if     defined HAVE_POSIX_MEMALIGN && defined POSIX_MEMALIGN_WITH_COMPLIANT_ALLOCS
Packit ae235b
#  define HAVE_COMPLIANT_POSIX_MEMALIGN 1
Packit ae235b
#endif
Packit ae235b
Packit ae235b
#if defined(HAVE_COMPLIANT_POSIX_MEMALIGN) && !defined(_XOPEN_SOURCE)
Packit ae235b
#define _XOPEN_SOURCE 600       /* posix_memalign() */
Packit ae235b
#endif
Packit ae235b
#include <stdlib.h>             /* posix_memalign() */
Packit ae235b
#include <string.h>
Packit ae235b
#include <errno.h>
Packit ae235b
Packit ae235b
#ifdef G_OS_UNIX
Packit ae235b
#include <unistd.h>             /* sysconf() */
Packit ae235b
#endif
Packit ae235b
#ifdef G_OS_WIN32
Packit ae235b
#include <windows.h>
Packit ae235b
#include <process.h>
Packit ae235b
#endif
Packit ae235b
Packit ae235b
#include <stdio.h>              /* fputs/fprintf */
Packit ae235b
Packit ae235b
#include "gslice.h"
Packit ae235b
Packit ae235b
#include "gmain.h"
Packit ae235b
#include "gmem.h"               /* gslice.h */
Packit ae235b
#include "gstrfuncs.h"
Packit ae235b
#include "gutils.h"
Packit ae235b
#include "gtrashstack.h"
Packit ae235b
#include "gtestutils.h"
Packit ae235b
#include "gthread.h"
Packit ae235b
#include "glib_trace.h"
Packit ae235b
Packit ae235b
#include "valgrind.h"
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * SECTION:memory_slices
Packit ae235b
 * @title: Memory Slices
Packit ae235b
 * @short_description: efficient way to allocate groups of equal-sized
Packit ae235b
 *     chunks of memory
Packit ae235b
 *
Packit ae235b
 * Memory slices provide a space-efficient and multi-processing scalable
Packit ae235b
 * way to allocate equal-sized pieces of memory, just like the original
Packit ae235b
 * #GMemChunks (from GLib 2.8), while avoiding their excessive
Packit ae235b
 * memory-waste, scalability and performance problems.
Packit ae235b
 *
Packit ae235b
 * To achieve these goals, the slice allocator uses a sophisticated,
Packit ae235b
 * layered design that has been inspired by Bonwick's slab allocator
Packit ae235b
 * ([Bonwick94](http://citeseer.ist.psu.edu/bonwick94slab.html)
Packit ae235b
 * Jeff Bonwick, The slab allocator: An object-caching kernel
Packit ae235b
 * memory allocator. USENIX 1994, and
Packit ae235b
 * [Bonwick01](http://citeseer.ist.psu.edu/bonwick01magazines.html)
Packit ae235b
 * Bonwick and Jonathan Adams, Magazines and vmem: Extending the
Packit ae235b
 * slab allocator to many cpu's and arbitrary resources. USENIX 2001)
Packit ae235b
 *
Packit ae235b
 * It uses posix_memalign() to optimize allocations of many equally-sized
Packit ae235b
 * chunks, and has per-thread free lists (the so-called magazine layer)
Packit ae235b
 * to quickly satisfy allocation requests of already known structure sizes.
Packit ae235b
 * This is accompanied by extra caching logic to keep freed memory around
Packit ae235b
 * for some time before returning it to the system. Memory that is unused
Packit ae235b
 * due to alignment constraints is used for cache colorization (random
Packit ae235b
 * distribution of chunk addresses) to improve CPU cache utilization. The
Packit ae235b
 * caching layer of the slice allocator adapts itself to high lock contention
Packit ae235b
 * to improve scalability.
Packit ae235b
 *
Packit ae235b
 * The slice allocator can allocate blocks as small as two pointers, and
Packit ae235b
 * unlike malloc(), it does not reserve extra space per block. For large block
Packit ae235b
 * sizes, g_slice_new() and g_slice_alloc() will automatically delegate to the
Packit ae235b
 * system malloc() implementation. For newly written code it is recommended
Packit ae235b
 * to use the new `g_slice` API instead of g_malloc() and
Packit ae235b
 * friends, as long as objects are not resized during their lifetime and the
Packit ae235b
 * object size used at allocation time is still available when freeing.
Packit ae235b
 *
Packit ae235b
 * Here is an example for using the slice allocator:
Packit ae235b
 * |[ 
Packit ae235b
 * gchar *mem[10000];
Packit ae235b
 * gint i;
Packit ae235b
 *
Packit ae235b
 * // Allocate 10000 blocks.
Packit ae235b
 * for (i = 0; i < 10000; i++)
Packit ae235b
 *   {
Packit ae235b
 *     mem[i] = g_slice_alloc (50);
Packit ae235b
 *
Packit ae235b
 *     // Fill in the memory with some junk.
Packit ae235b
 *     for (j = 0; j < 50; j++)
Packit ae235b
 *       mem[i][j] = i * j;
Packit ae235b
 *   }
Packit ae235b
 *
Packit ae235b
 * // Now free all of the blocks.
Packit ae235b
 * for (i = 0; i < 10000; i++)
Packit ae235b
 *   g_slice_free1 (50, mem[i]);
Packit ae235b
 * ]|
Packit ae235b
 *
Packit ae235b
 * And here is an example for using the using the slice allocator
Packit ae235b
 * with data structures:
Packit ae235b
 * |[ 
Packit ae235b
 * GRealArray *array;
Packit ae235b
 *
Packit ae235b
 * // Allocate one block, using the g_slice_new() macro.
Packit ae235b
 * array = g_slice_new (GRealArray);
Packit ae235b
 *
Packit ae235b
 * // We can now use array just like a normal pointer to a structure.
Packit ae235b
 * array->data            = NULL;
Packit ae235b
 * array->len             = 0;
Packit ae235b
 * array->alloc           = 0;
Packit ae235b
 * array->zero_terminated = (zero_terminated ? 1 : 0);
Packit ae235b
 * array->clear           = (clear ? 1 : 0);
Packit ae235b
 * array->elt_size        = elt_size;
Packit ae235b
 *
Packit ae235b
 * // We can free the block, so it can be reused.
Packit ae235b
 * g_slice_free (GRealArray, array);
Packit ae235b
 * ]|
Packit ae235b
 */
Packit ae235b
Packit ae235b
/* the GSlice allocator is split up into 4 layers, roughly modelled after the slab
Packit ae235b
 * allocator and magazine extensions as outlined in:
Packit ae235b
 * + [Bonwick94] Jeff Bonwick, The slab allocator: An object-caching kernel
Packit ae235b
 *   memory allocator. USENIX 1994, http://citeseer.ist.psu.edu/bonwick94slab.html
Packit ae235b
 * + [Bonwick01] Bonwick and Jonathan Adams, Magazines and vmem: Extending the
Packit ae235b
 *   slab allocator to many cpu's and arbitrary resources.
Packit ae235b
 *   USENIX 2001, http://citeseer.ist.psu.edu/bonwick01magazines.html
Packit ae235b
 * the layers are:
Packit ae235b
 * - the thread magazines. for each (aligned) chunk size, a magazine (a list)
Packit ae235b
 *   of recently freed and soon to be allocated chunks is maintained per thread.
Packit ae235b
 *   this way, most alloc/free requests can be quickly satisfied from per-thread
Packit ae235b
 *   free lists which only require one g_private_get() call to retrive the
Packit ae235b
 *   thread handle.
Packit ae235b
 * - the magazine cache. allocating and freeing chunks to/from threads only
Packit ae235b
 *   occours at magazine sizes from a global depot of magazines. the depot
Packit ae235b
 *   maintaines a 15 second working set of allocated magazines, so full
Packit ae235b
 *   magazines are not allocated and released too often.
Packit ae235b
 *   the chunk size dependent magazine sizes automatically adapt (within limits,
Packit ae235b
 *   see [3]) to lock contention to properly scale performance across a variety
Packit ae235b
 *   of SMP systems.
Packit ae235b
 * - the slab allocator. this allocator allocates slabs (blocks of memory) close
Packit ae235b
 *   to the system page size or multiples thereof which have to be page aligned.
Packit ae235b
 *   the blocks are divided into smaller chunks which are used to satisfy
Packit ae235b
 *   allocations from the upper layers. the space provided by the reminder of
Packit ae235b
 *   the chunk size division is used for cache colorization (random distribution
Packit ae235b
 *   of chunk addresses) to improve processor cache utilization. multiple slabs
Packit ae235b
 *   with the same chunk size are kept in a partially sorted ring to allow O(1)
Packit ae235b
 *   freeing and allocation of chunks (as long as the allocation of an entirely
Packit ae235b
 *   new slab can be avoided).
Packit ae235b
 * - the page allocator. on most modern systems, posix_memalign(3) or
Packit ae235b
 *   memalign(3) should be available, so this is used to allocate blocks with
Packit ae235b
 *   system page size based alignments and sizes or multiples thereof.
Packit ae235b
 *   if no memalign variant is provided, valloc() is used instead and
Packit ae235b
 *   block sizes are limited to the system page size (no multiples thereof).
Packit ae235b
 *   as a fallback, on system without even valloc(), a malloc(3)-based page
Packit ae235b
 *   allocator with alloc-only behaviour is used.
Packit ae235b
 *
Packit ae235b
 * NOTES:
Packit ae235b
 * [1] some systems memalign(3) implementations may rely on boundary tagging for
Packit ae235b
 *     the handed out memory chunks. to avoid excessive page-wise fragmentation,
Packit ae235b
 *     we reserve 2 * sizeof (void*) per block size for the systems memalign(3),
Packit ae235b
 *     specified in NATIVE_MALLOC_PADDING.
Packit ae235b
 * [2] using the slab allocator alone already provides for a fast and efficient
Packit ae235b
 *     allocator, it doesn't properly scale beyond single-threaded uses though.
Packit ae235b
 *     also, the slab allocator implements eager free(3)-ing, i.e. does not
Packit ae235b
 *     provide any form of caching or working set maintenance. so if used alone,
Packit ae235b
 *     it's vulnerable to trashing for sequences of balanced (alloc, free) pairs
Packit ae235b
 *     at certain thresholds.
Packit ae235b
 * [3] magazine sizes are bound by an implementation specific minimum size and
Packit ae235b
 *     a chunk size specific maximum to limit magazine storage sizes to roughly
Packit ae235b
 *     16KB.
Packit ae235b
 * [4] allocating ca. 8 chunks per block/page keeps a good balance between
Packit ae235b
 *     external and internal fragmentation (<= 12.5%). [Bonwick94]
Packit ae235b
 */
Packit ae235b
Packit ae235b
/* --- macros and constants --- */
Packit ae235b
#define LARGEALIGNMENT          (256)
Packit ae235b
#define P2ALIGNMENT             (2 * sizeof (gsize))                            /* fits 2 pointers (assumed to be 2 * GLIB_SIZEOF_SIZE_T below) */
Packit ae235b
#define ALIGN(size, base)       ((base) * (gsize) (((size) + (base) - 1) / (base)))
Packit ae235b
#define NATIVE_MALLOC_PADDING   P2ALIGNMENT                                     /* per-page padding left for native malloc(3) see [1] */
Packit ae235b
#define SLAB_INFO_SIZE          P2ALIGN (sizeof (SlabInfo) + NATIVE_MALLOC_PADDING)
Packit ae235b
#define MAX_MAGAZINE_SIZE       (256)                                           /* see [3] and allocator_get_magazine_threshold() for this */
Packit ae235b
#define MIN_MAGAZINE_SIZE       (4)
Packit ae235b
#define MAX_STAMP_COUNTER       (7)                                             /* distributes the load of gettimeofday() */
Packit ae235b
#define MAX_SLAB_CHUNK_SIZE(al) (((al)->max_page_size - SLAB_INFO_SIZE) / 8)    /* we want at last 8 chunks per page, see [4] */
Packit ae235b
#define MAX_SLAB_INDEX(al)      (SLAB_INDEX (al, MAX_SLAB_CHUNK_SIZE (al)) + 1)
Packit ae235b
#define SLAB_INDEX(al, asize)   ((asize) / P2ALIGNMENT - 1)                     /* asize must be P2ALIGNMENT aligned */
Packit ae235b
#define SLAB_CHUNK_SIZE(al, ix) (((ix) + 1) * P2ALIGNMENT)
Packit ae235b
#define SLAB_BPAGE_SIZE(al,csz) (8 * (csz) + SLAB_INFO_SIZE)
Packit ae235b
Packit ae235b
/* optimized version of ALIGN (size, P2ALIGNMENT) */
Packit ae235b
#if     GLIB_SIZEOF_SIZE_T * 2 == 8  /* P2ALIGNMENT */
Packit ae235b
#define P2ALIGN(size)   (((size) + 0x7) & ~(gsize) 0x7)
Packit ae235b
#elif   GLIB_SIZEOF_SIZE_T * 2 == 16 /* P2ALIGNMENT */
Packit ae235b
#define P2ALIGN(size)   (((size) + 0xf) & ~(gsize) 0xf)
Packit ae235b
#else
Packit ae235b
#define P2ALIGN(size)   ALIGN (size, P2ALIGNMENT)
Packit ae235b
#endif
Packit ae235b
Packit ae235b
/* special helpers to avoid gmessage.c dependency */
Packit ae235b
static void mem_error (const char *format, ...) G_GNUC_PRINTF (1,2);
Packit ae235b
#define mem_assert(cond)    do { if (G_LIKELY (cond)) ; else mem_error ("assertion failed: %s", #cond); } while (0)
Packit ae235b
Packit ae235b
/* --- structures --- */
Packit ae235b
typedef struct _ChunkLink      ChunkLink;
Packit ae235b
typedef struct _SlabInfo       SlabInfo;
Packit ae235b
typedef struct _CachedMagazine CachedMagazine;
Packit ae235b
struct _ChunkLink {
Packit ae235b
  ChunkLink *next;
Packit ae235b
  ChunkLink *data;
Packit ae235b
};
Packit ae235b
struct _SlabInfo {
Packit ae235b
  ChunkLink *chunks;
Packit ae235b
  guint n_allocated;
Packit ae235b
  SlabInfo *next, *prev;
Packit ae235b
};
Packit ae235b
typedef struct {
Packit ae235b
  ChunkLink *chunks;
Packit ae235b
  gsize      count;                     /* approximative chunks list length */
Packit ae235b
} Magazine;
Packit ae235b
typedef struct {
Packit ae235b
  Magazine   *magazine1;                /* array of MAX_SLAB_INDEX (allocator) */
Packit ae235b
  Magazine   *magazine2;                /* array of MAX_SLAB_INDEX (allocator) */
Packit ae235b
} ThreadMemory;
Packit ae235b
typedef struct {
Packit ae235b
  gboolean always_malloc;
Packit ae235b
  gboolean bypass_magazines;
Packit ae235b
  gboolean debug_blocks;
Packit ae235b
  gsize    working_set_msecs;
Packit ae235b
  guint    color_increment;
Packit ae235b
} SliceConfig;
Packit ae235b
typedef struct {
Packit ae235b
  /* const after initialization */
Packit ae235b
  gsize         min_page_size, max_page_size;
Packit ae235b
  SliceConfig   config;
Packit ae235b
  gsize         max_slab_chunk_size_for_magazine_cache;
Packit ae235b
  /* magazine cache */
Packit ae235b
  GMutex        magazine_mutex;
Packit ae235b
  ChunkLink   **magazines;                /* array of MAX_SLAB_INDEX (allocator) */
Packit ae235b
  guint        *contention_counters;      /* array of MAX_SLAB_INDEX (allocator) */
Packit ae235b
  gint          mutex_counter;
Packit ae235b
  guint         stamp_counter;
Packit ae235b
  guint         last_stamp;
Packit ae235b
  /* slab allocator */
Packit ae235b
  GMutex        slab_mutex;
Packit ae235b
  SlabInfo    **slab_stack;                /* array of MAX_SLAB_INDEX (allocator) */
Packit ae235b
  guint        color_accu;
Packit ae235b
} Allocator;
Packit ae235b
Packit ae235b
/* --- g-slice prototypes --- */
Packit ae235b
static gpointer     slab_allocator_alloc_chunk       (gsize      chunk_size);
Packit ae235b
static void         slab_allocator_free_chunk        (gsize      chunk_size,
Packit ae235b
                                                      gpointer   mem);
Packit ae235b
static void         private_thread_memory_cleanup    (gpointer   data);
Packit ae235b
static gpointer     allocator_memalign               (gsize      alignment,
Packit ae235b
                                                      gsize      memsize);
Packit ae235b
static void         allocator_memfree                (gsize      memsize,
Packit ae235b
                                                      gpointer   mem);
Packit ae235b
static inline void  magazine_cache_update_stamp      (void);
Packit ae235b
static inline gsize allocator_get_magazine_threshold (Allocator *allocator,
Packit ae235b
                                                      guint      ix);
Packit ae235b
Packit ae235b
/* --- g-slice memory checker --- */
Packit ae235b
static void     smc_notify_alloc  (void   *pointer,
Packit ae235b
                                   size_t  size);
Packit ae235b
static int      smc_notify_free   (void   *pointer,
Packit ae235b
                                   size_t  size);
Packit ae235b
Packit ae235b
/* --- variables --- */
Packit ae235b
static GPrivate    private_thread_memory = G_PRIVATE_INIT (private_thread_memory_cleanup);
Packit ae235b
static gsize       sys_page_size = 0;
Packit ae235b
static Allocator   allocator[1] = { { 0, }, };
Packit ae235b
static SliceConfig slice_config = {
Packit ae235b
  FALSE,        /* always_malloc */
Packit ae235b
  FALSE,        /* bypass_magazines */
Packit ae235b
  FALSE,        /* debug_blocks */
Packit ae235b
  15 * 1000,    /* working_set_msecs */
Packit ae235b
  1,            /* color increment, alt: 0x7fffffff */
Packit ae235b
};
Packit ae235b
static GMutex      smc_tree_mutex; /* mutex for G_SLICE=debug-blocks */
Packit ae235b
Packit ae235b
/* --- auxiliary funcitons --- */
Packit ae235b
void
Packit ae235b
g_slice_set_config (GSliceConfig ckey,
Packit ae235b
                    gint64       value)
Packit ae235b
{
Packit ae235b
  g_return_if_fail (sys_page_size == 0);
Packit ae235b
  switch (ckey)
Packit ae235b
    {
Packit ae235b
    case G_SLICE_CONFIG_ALWAYS_MALLOC:
Packit ae235b
      slice_config.always_malloc = value != 0;
Packit ae235b
      break;
Packit ae235b
    case G_SLICE_CONFIG_BYPASS_MAGAZINES:
Packit ae235b
      slice_config.bypass_magazines = value != 0;
Packit ae235b
      break;
Packit ae235b
    case G_SLICE_CONFIG_WORKING_SET_MSECS:
Packit ae235b
      slice_config.working_set_msecs = value;
Packit ae235b
      break;
Packit ae235b
    case G_SLICE_CONFIG_COLOR_INCREMENT:
Packit ae235b
      slice_config.color_increment = value;
Packit ae235b
    default: ;
Packit ae235b
    }
Packit ae235b
}
Packit ae235b
Packit ae235b
gint64
Packit ae235b
g_slice_get_config (GSliceConfig ckey)
Packit ae235b
{
Packit ae235b
  switch (ckey)
Packit ae235b
    {
Packit ae235b
    case G_SLICE_CONFIG_ALWAYS_MALLOC:
Packit ae235b
      return slice_config.always_malloc;
Packit ae235b
    case G_SLICE_CONFIG_BYPASS_MAGAZINES:
Packit ae235b
      return slice_config.bypass_magazines;
Packit ae235b
    case G_SLICE_CONFIG_WORKING_SET_MSECS:
Packit ae235b
      return slice_config.working_set_msecs;
Packit ae235b
    case G_SLICE_CONFIG_CHUNK_SIZES:
Packit ae235b
      return MAX_SLAB_INDEX (allocator);
Packit ae235b
    case G_SLICE_CONFIG_COLOR_INCREMENT:
Packit ae235b
      return slice_config.color_increment;
Packit ae235b
    default:
Packit ae235b
      return 0;
Packit ae235b
    }
Packit ae235b
}
Packit ae235b
Packit ae235b
gint64*
Packit ae235b
g_slice_get_config_state (GSliceConfig ckey,
Packit ae235b
                          gint64       address,
Packit ae235b
                          guint       *n_values)
Packit ae235b
{
Packit ae235b
  guint i = 0;
Packit ae235b
  g_return_val_if_fail (n_values != NULL, NULL);
Packit ae235b
  *n_values = 0;
Packit ae235b
  switch (ckey)
Packit ae235b
    {
Packit ae235b
      gint64 array[64];
Packit ae235b
    case G_SLICE_CONFIG_CONTENTION_COUNTER:
Packit ae235b
      array[i++] = SLAB_CHUNK_SIZE (allocator, address);
Packit ae235b
      array[i++] = allocator->contention_counters[address];
Packit ae235b
      array[i++] = allocator_get_magazine_threshold (allocator, address);
Packit ae235b
      *n_values = i;
Packit ae235b
      return g_memdup (array, sizeof (array[0]) * *n_values);
Packit ae235b
    default:
Packit ae235b
      return NULL;
Packit ae235b
    }
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
slice_config_init (SliceConfig *config)
Packit ae235b
{
Packit ae235b
  const gchar *val;
Packit ae235b
Packit ae235b
  *config = slice_config;
Packit ae235b
Packit ae235b
  val = getenv ("G_SLICE");
Packit ae235b
  if (val != NULL)
Packit ae235b
    {
Packit ae235b
      gint flags;
Packit ae235b
      const GDebugKey keys[] = {
Packit ae235b
        { "always-malloc", 1 << 0 },
Packit ae235b
        { "debug-blocks",  1 << 1 },
Packit ae235b
      };
Packit ae235b
Packit ae235b
      flags = g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
Packit ae235b
      if (flags & (1 << 0))
Packit ae235b
        config->always_malloc = TRUE;
Packit ae235b
      if (flags & (1 << 1))
Packit ae235b
        config->debug_blocks = TRUE;
Packit ae235b
    }
Packit ae235b
  else
Packit ae235b
    {
Packit ae235b
      /* G_SLICE was not specified, so check if valgrind is running and
Packit ae235b
       * disable ourselves if it is.
Packit ae235b
       *
Packit ae235b
       * This way it's possible to force gslice to be enabled under
Packit ae235b
       * valgrind just by setting G_SLICE to the empty string.
Packit ae235b
       */
Packit ae235b
      if (RUNNING_ON_VALGRIND)
Packit ae235b
        config->always_malloc = TRUE;
Packit ae235b
    }
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
g_slice_init_nomessage (void)
Packit ae235b
{
Packit ae235b
  /* we may not use g_error() or friends here */
Packit ae235b
  mem_assert (sys_page_size == 0);
Packit ae235b
  mem_assert (MIN_MAGAZINE_SIZE >= 4);
Packit ae235b
Packit ae235b
#ifdef G_OS_WIN32
Packit ae235b
  {
Packit ae235b
    SYSTEM_INFO system_info;
Packit ae235b
    GetSystemInfo (&system_info);
Packit ae235b
    sys_page_size = system_info.dwPageSize;
Packit ae235b
  }
Packit ae235b
#else
Packit ae235b
  sys_page_size = sysconf (_SC_PAGESIZE); /* = sysconf (_SC_PAGE_SIZE); = getpagesize(); */
Packit ae235b
#endif
Packit ae235b
  mem_assert (sys_page_size >= 2 * LARGEALIGNMENT);
Packit ae235b
  mem_assert ((sys_page_size & (sys_page_size - 1)) == 0);
Packit ae235b
  slice_config_init (&allocator->config);
Packit ae235b
  allocator->min_page_size = sys_page_size;
Packit ae235b
#if HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN
Packit ae235b
  /* allow allocation of pages up to 8KB (with 8KB alignment).
Packit ae235b
   * this is useful because many medium to large sized structures
Packit ae235b
   * fit less than 8 times (see [4]) into 4KB pages.
Packit ae235b
   * we allow very small page sizes here, to reduce wastage in
Packit ae235b
   * threads if only small allocations are required (this does
Packit ae235b
   * bear the risk of increasing allocation times and fragmentation
Packit ae235b
   * though).
Packit ae235b
   */
Packit ae235b
  allocator->min_page_size = MAX (allocator->min_page_size, 4096);
Packit ae235b
  allocator->max_page_size = MAX (allocator->min_page_size, 8192);
Packit ae235b
  allocator->min_page_size = MIN (allocator->min_page_size, 128);
Packit ae235b
#else
Packit ae235b
  /* we can only align to system page size */
Packit ae235b
  allocator->max_page_size = sys_page_size;
Packit ae235b
#endif
Packit ae235b
  if (allocator->config.always_malloc)
Packit ae235b
    {
Packit ae235b
      allocator->contention_counters = NULL;
Packit ae235b
      allocator->magazines = NULL;
Packit ae235b
      allocator->slab_stack = NULL;
Packit ae235b
    }
Packit ae235b
  else
Packit ae235b
    {
Packit ae235b
      allocator->contention_counters = g_new0 (guint, MAX_SLAB_INDEX (allocator));
Packit ae235b
      allocator->magazines = g_new0 (ChunkLink*, MAX_SLAB_INDEX (allocator));
Packit ae235b
      allocator->slab_stack = g_new0 (SlabInfo*, MAX_SLAB_INDEX (allocator));
Packit ae235b
    }
Packit ae235b
Packit ae235b
  allocator->mutex_counter = 0;
Packit ae235b
  allocator->stamp_counter = MAX_STAMP_COUNTER; /* force initial update */
Packit ae235b
  allocator->last_stamp = 0;
Packit ae235b
  allocator->color_accu = 0;
Packit ae235b
  magazine_cache_update_stamp();
Packit ae235b
  /* values cached for performance reasons */
Packit ae235b
  allocator->max_slab_chunk_size_for_magazine_cache = MAX_SLAB_CHUNK_SIZE (allocator);
Packit ae235b
  if (allocator->config.always_malloc || allocator->config.bypass_magazines)
Packit ae235b
    allocator->max_slab_chunk_size_for_magazine_cache = 0;      /* non-optimized cases */
Packit ae235b
}
Packit ae235b
Packit ae235b
static inline guint
Packit ae235b
allocator_categorize (gsize aligned_chunk_size)
Packit ae235b
{
Packit ae235b
  /* speed up the likely path */
Packit ae235b
  if (G_LIKELY (aligned_chunk_size && aligned_chunk_size <= allocator->max_slab_chunk_size_for_magazine_cache))
Packit ae235b
    return 1;           /* use magazine cache */
Packit ae235b
Packit ae235b
  if (!allocator->config.always_malloc &&
Packit ae235b
      aligned_chunk_size &&
Packit ae235b
      aligned_chunk_size <= MAX_SLAB_CHUNK_SIZE (allocator))
Packit ae235b
    {
Packit ae235b
      if (allocator->config.bypass_magazines)
Packit ae235b
        return 2;       /* use slab allocator, see [2] */
Packit ae235b
      return 1;         /* use magazine cache */
Packit ae235b
    }
Packit ae235b
  return 0;             /* use malloc() */
Packit ae235b
}
Packit ae235b
Packit ae235b
static inline void
Packit ae235b
g_mutex_lock_a (GMutex *mutex,
Packit ae235b
                guint  *contention_counter)
Packit ae235b
{
Packit ae235b
  gboolean contention = FALSE;
Packit ae235b
  if (!g_mutex_trylock (mutex))
Packit ae235b
    {
Packit ae235b
      g_mutex_lock (mutex);
Packit ae235b
      contention = TRUE;
Packit ae235b
    }
Packit ae235b
  if (contention)
Packit ae235b
    {
Packit ae235b
      allocator->mutex_counter++;
Packit ae235b
      if (allocator->mutex_counter >= 1)        /* quickly adapt to contention */
Packit ae235b
        {
Packit ae235b
          allocator->mutex_counter = 0;
Packit ae235b
          *contention_counter = MIN (*contention_counter + 1, MAX_MAGAZINE_SIZE);
Packit ae235b
        }
Packit ae235b
    }
Packit ae235b
  else /* !contention */
Packit ae235b
    {
Packit ae235b
      allocator->mutex_counter--;
Packit ae235b
      if (allocator->mutex_counter < -11)       /* moderately recover magazine sizes */
Packit ae235b
        {
Packit ae235b
          allocator->mutex_counter = 0;
Packit ae235b
          *contention_counter = MAX (*contention_counter, 1) - 1;
Packit ae235b
        }
Packit ae235b
    }
Packit ae235b
}
Packit ae235b
Packit ae235b
static inline ThreadMemory*
Packit ae235b
thread_memory_from_self (void)
Packit ae235b
{
Packit ae235b
  ThreadMemory *tmem = g_private_get (&private_thread_memory);
Packit ae235b
  if (G_UNLIKELY (!tmem))
Packit ae235b
    {
Packit ae235b
      static GMutex init_mutex;
Packit ae235b
      guint n_magazines;
Packit ae235b
Packit ae235b
      g_mutex_lock (&init_mutex);
Packit ae235b
      if G_UNLIKELY (sys_page_size == 0)
Packit ae235b
        g_slice_init_nomessage ();
Packit ae235b
      g_mutex_unlock (&init_mutex);
Packit ae235b
Packit ae235b
      n_magazines = MAX_SLAB_INDEX (allocator);
Packit ae235b
      tmem = g_malloc0 (sizeof (ThreadMemory) + sizeof (Magazine) * 2 * n_magazines);
Packit ae235b
      tmem->magazine1 = (Magazine*) (tmem + 1);
Packit ae235b
      tmem->magazine2 = &tmem->magazine1[n_magazines];
Packit ae235b
      g_private_set (&private_thread_memory, tmem);
Packit ae235b
    }
Packit ae235b
  return tmem;
Packit ae235b
}
Packit ae235b
Packit ae235b
static inline ChunkLink*
Packit ae235b
magazine_chain_pop_head (ChunkLink **magazine_chunks)
Packit ae235b
{
Packit ae235b
  /* magazine chains are linked via ChunkLink->next.
Packit ae235b
   * each ChunkLink->data of the toplevel chain may point to a subchain,
Packit ae235b
   * linked via ChunkLink->next. ChunkLink->data of the subchains just
Packit ae235b
   * contains uninitialized junk.
Packit ae235b
   */
Packit ae235b
  ChunkLink *chunk = (*magazine_chunks)->data;
Packit ae235b
  if (G_UNLIKELY (chunk))
Packit ae235b
    {
Packit ae235b
      /* allocating from freed list */
Packit ae235b
      (*magazine_chunks)->data = chunk->next;
Packit ae235b
    }
Packit ae235b
  else
Packit ae235b
    {
Packit ae235b
      chunk = *magazine_chunks;
Packit ae235b
      *magazine_chunks = chunk->next;
Packit ae235b
    }
Packit ae235b
  return chunk;
Packit ae235b
}
Packit ae235b
Packit ae235b
#if 0 /* useful for debugging */
Packit ae235b
static guint
Packit ae235b
magazine_count (ChunkLink *head)
Packit ae235b
{
Packit ae235b
  guint count = 0;
Packit ae235b
  if (!head)
Packit ae235b
    return 0;
Packit ae235b
  while (head)
Packit ae235b
    {
Packit ae235b
      ChunkLink *child = head->data;
Packit ae235b
      count += 1;
Packit ae235b
      for (child = head->data; child; child = child->next)
Packit ae235b
        count += 1;
Packit ae235b
      head = head->next;
Packit ae235b
    }
Packit ae235b
  return count;
Packit ae235b
}
Packit ae235b
#endif
Packit ae235b
Packit ae235b
static inline gsize
Packit ae235b
allocator_get_magazine_threshold (Allocator *allocator,
Packit ae235b
                                  guint      ix)
Packit ae235b
{
Packit ae235b
  /* the magazine size calculated here has a lower bound of MIN_MAGAZINE_SIZE,
Packit ae235b
   * which is required by the implementation. also, for moderately sized chunks
Packit ae235b
   * (say >= 64 bytes), magazine sizes shouldn't be much smaller then the number
Packit ae235b
   * of chunks available per page/2 to avoid excessive traffic in the magazine
Packit ae235b
   * cache for small to medium sized structures.
Packit ae235b
   * the upper bound of the magazine size is effectively provided by
Packit ae235b
   * MAX_MAGAZINE_SIZE. for larger chunks, this number is scaled down so that
Packit ae235b
   * the content of a single magazine doesn't exceed ca. 16KB.
Packit ae235b
   */
Packit ae235b
  gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
Packit ae235b
  guint threshold = MAX (MIN_MAGAZINE_SIZE, allocator->max_page_size / MAX (5 * chunk_size, 5 * 32));
Packit ae235b
  guint contention_counter = allocator->contention_counters[ix];
Packit ae235b
  if (G_UNLIKELY (contention_counter))  /* single CPU bias */
Packit ae235b
    {
Packit ae235b
      /* adapt contention counter thresholds to chunk sizes */
Packit ae235b
      contention_counter = contention_counter * 64 / chunk_size;
Packit ae235b
      threshold = MAX (threshold, contention_counter);
Packit ae235b
    }
Packit ae235b
  return threshold;
Packit ae235b
}
Packit ae235b
Packit ae235b
/* --- magazine cache --- */
Packit ae235b
static inline void
Packit ae235b
magazine_cache_update_stamp (void)
Packit ae235b
{
Packit ae235b
  if (allocator->stamp_counter >= MAX_STAMP_COUNTER)
Packit ae235b
    {
Packit ae235b
      GTimeVal tv;
Packit ae235b
      g_get_current_time (&tv;;
Packit ae235b
      allocator->last_stamp = tv.tv_sec * 1000 + tv.tv_usec / 1000; /* milli seconds */
Packit ae235b
      allocator->stamp_counter = 0;
Packit ae235b
    }
Packit ae235b
  else
Packit ae235b
    allocator->stamp_counter++;
Packit ae235b
}
Packit ae235b
Packit ae235b
static inline ChunkLink*
Packit ae235b
magazine_chain_prepare_fields (ChunkLink *magazine_chunks)
Packit ae235b
{
Packit ae235b
  ChunkLink *chunk1;
Packit ae235b
  ChunkLink *chunk2;
Packit ae235b
  ChunkLink *chunk3;
Packit ae235b
  ChunkLink *chunk4;
Packit ae235b
  /* checked upon initialization: mem_assert (MIN_MAGAZINE_SIZE >= 4); */
Packit ae235b
  /* ensure a magazine with at least 4 unused data pointers */
Packit ae235b
  chunk1 = magazine_chain_pop_head (&magazine_chunks);
Packit ae235b
  chunk2 = magazine_chain_pop_head (&magazine_chunks);
Packit ae235b
  chunk3 = magazine_chain_pop_head (&magazine_chunks);
Packit ae235b
  chunk4 = magazine_chain_pop_head (&magazine_chunks);
Packit ae235b
  chunk4->next = magazine_chunks;
Packit ae235b
  chunk3->next = chunk4;
Packit ae235b
  chunk2->next = chunk3;
Packit ae235b
  chunk1->next = chunk2;
Packit ae235b
  return chunk1;
Packit ae235b
}
Packit ae235b
Packit ae235b
/* access the first 3 fields of a specially prepared magazine chain */
Packit ae235b
#define magazine_chain_prev(mc)         ((mc)->data)
Packit ae235b
#define magazine_chain_stamp(mc)        ((mc)->next->data)
Packit ae235b
#define magazine_chain_uint_stamp(mc)   GPOINTER_TO_UINT ((mc)->next->data)
Packit ae235b
#define magazine_chain_next(mc)         ((mc)->next->next->data)
Packit ae235b
#define magazine_chain_count(mc)        ((mc)->next->next->next->data)
Packit ae235b
Packit ae235b
static void
Packit ae235b
magazine_cache_trim (Allocator *allocator,
Packit ae235b
                     guint      ix,
Packit ae235b
                     guint      stamp)
Packit ae235b
{
Packit ae235b
  /* g_mutex_lock (allocator->mutex); done by caller */
Packit ae235b
  /* trim magazine cache from tail */
Packit ae235b
  ChunkLink *current = magazine_chain_prev (allocator->magazines[ix]);
Packit ae235b
  ChunkLink *trash = NULL;
Packit ae235b
  while (ABS (stamp - magazine_chain_uint_stamp (current)) >= allocator->config.working_set_msecs)
Packit ae235b
    {
Packit ae235b
      /* unlink */
Packit ae235b
      ChunkLink *prev = magazine_chain_prev (current);
Packit ae235b
      ChunkLink *next = magazine_chain_next (current);
Packit ae235b
      magazine_chain_next (prev) = next;
Packit ae235b
      magazine_chain_prev (next) = prev;
Packit ae235b
      /* clear special fields, put on trash stack */
Packit ae235b
      magazine_chain_next (current) = NULL;
Packit ae235b
      magazine_chain_count (current) = NULL;
Packit ae235b
      magazine_chain_stamp (current) = NULL;
Packit ae235b
      magazine_chain_prev (current) = trash;
Packit ae235b
      trash = current;
Packit ae235b
      /* fixup list head if required */
Packit ae235b
      if (current == allocator->magazines[ix])
Packit ae235b
        {
Packit ae235b
          allocator->magazines[ix] = NULL;
Packit ae235b
          break;
Packit ae235b
        }
Packit ae235b
      current = prev;
Packit ae235b
    }
Packit ae235b
  g_mutex_unlock (&allocator->magazine_mutex);
Packit ae235b
  /* free trash */
Packit ae235b
  if (trash)
Packit ae235b
    {
Packit ae235b
      const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
Packit ae235b
      g_mutex_lock (&allocator->slab_mutex);
Packit ae235b
      while (trash)
Packit ae235b
        {
Packit ae235b
          current = trash;
Packit ae235b
          trash = magazine_chain_prev (current);
Packit ae235b
          magazine_chain_prev (current) = NULL; /* clear special field */
Packit ae235b
          while (current)
Packit ae235b
            {
Packit ae235b
              ChunkLink *chunk = magazine_chain_pop_head (¤t;;
Packit ae235b
              slab_allocator_free_chunk (chunk_size, chunk);
Packit ae235b
            }
Packit ae235b
        }
Packit ae235b
      g_mutex_unlock (&allocator->slab_mutex);
Packit ae235b
    }
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
magazine_cache_push_magazine (guint      ix,
Packit ae235b
                              ChunkLink *magazine_chunks,
Packit ae235b
                              gsize      count) /* must be >= MIN_MAGAZINE_SIZE */
Packit ae235b
{
Packit ae235b
  ChunkLink *current = magazine_chain_prepare_fields (magazine_chunks);
Packit ae235b
  ChunkLink *next, *prev;
Packit ae235b
  g_mutex_lock (&allocator->magazine_mutex);
Packit ae235b
  /* add magazine at head */
Packit ae235b
  next = allocator->magazines[ix];
Packit ae235b
  if (next)
Packit ae235b
    prev = magazine_chain_prev (next);
Packit ae235b
  else
Packit ae235b
    next = prev = current;
Packit ae235b
  magazine_chain_next (prev) = current;
Packit ae235b
  magazine_chain_prev (next) = current;
Packit ae235b
  magazine_chain_prev (current) = prev;
Packit ae235b
  magazine_chain_next (current) = next;
Packit ae235b
  magazine_chain_count (current) = (gpointer) count;
Packit ae235b
  /* stamp magazine */
Packit ae235b
  magazine_cache_update_stamp();
Packit ae235b
  magazine_chain_stamp (current) = GUINT_TO_POINTER (allocator->last_stamp);
Packit ae235b
  allocator->magazines[ix] = current;
Packit ae235b
  /* free old magazines beyond a certain threshold */
Packit ae235b
  magazine_cache_trim (allocator, ix, allocator->last_stamp);
Packit ae235b
  /* g_mutex_unlock (allocator->mutex); was done by magazine_cache_trim() */
Packit ae235b
}
Packit ae235b
Packit ae235b
static ChunkLink*
Packit ae235b
magazine_cache_pop_magazine (guint  ix,
Packit ae235b
                             gsize *countp)
Packit ae235b
{
Packit ae235b
  g_mutex_lock_a (&allocator->magazine_mutex, &allocator->contention_counters[ix]);
Packit ae235b
  if (!allocator->magazines[ix])
Packit ae235b
    {
Packit ae235b
      guint magazine_threshold = allocator_get_magazine_threshold (allocator, ix);
Packit ae235b
      gsize i, chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
Packit ae235b
      ChunkLink *chunk, *head;
Packit ae235b
      g_mutex_unlock (&allocator->magazine_mutex);
Packit ae235b
      g_mutex_lock (&allocator->slab_mutex);
Packit ae235b
      head = slab_allocator_alloc_chunk (chunk_size);
Packit ae235b
      head->data = NULL;
Packit ae235b
      chunk = head;
Packit ae235b
      for (i = 1; i < magazine_threshold; i++)
Packit ae235b
        {
Packit ae235b
          chunk->next = slab_allocator_alloc_chunk (chunk_size);
Packit ae235b
          chunk = chunk->next;
Packit ae235b
          chunk->data = NULL;
Packit ae235b
        }
Packit ae235b
      chunk->next = NULL;
Packit ae235b
      g_mutex_unlock (&allocator->slab_mutex);
Packit ae235b
      *countp = i;
Packit ae235b
      return head;
Packit ae235b
    }
Packit ae235b
  else
Packit ae235b
    {
Packit ae235b
      ChunkLink *current = allocator->magazines[ix];
Packit ae235b
      ChunkLink *prev = magazine_chain_prev (current);
Packit ae235b
      ChunkLink *next = magazine_chain_next (current);
Packit ae235b
      /* unlink */
Packit ae235b
      magazine_chain_next (prev) = next;
Packit ae235b
      magazine_chain_prev (next) = prev;
Packit ae235b
      allocator->magazines[ix] = next == current ? NULL : next;
Packit ae235b
      g_mutex_unlock (&allocator->magazine_mutex);
Packit ae235b
      /* clear special fields and hand out */
Packit ae235b
      *countp = (gsize) magazine_chain_count (current);
Packit ae235b
      magazine_chain_prev (current) = NULL;
Packit ae235b
      magazine_chain_next (current) = NULL;
Packit ae235b
      magazine_chain_count (current) = NULL;
Packit ae235b
      magazine_chain_stamp (current) = NULL;
Packit ae235b
      return current;
Packit ae235b
    }
Packit ae235b
}
Packit ae235b
Packit ae235b
/* --- thread magazines --- */
Packit ae235b
static void
Packit ae235b
private_thread_memory_cleanup (gpointer data)
Packit ae235b
{
Packit ae235b
  ThreadMemory *tmem = data;
Packit ae235b
  const guint n_magazines = MAX_SLAB_INDEX (allocator);
Packit ae235b
  guint ix;
Packit ae235b
  for (ix = 0; ix < n_magazines; ix++)
Packit ae235b
    {
Packit ae235b
      Magazine *mags[2];
Packit ae235b
      guint j;
Packit ae235b
      mags[0] = &tmem->magazine1[ix];
Packit ae235b
      mags[1] = &tmem->magazine2[ix];
Packit ae235b
      for (j = 0; j < 2; j++)
Packit ae235b
        {
Packit ae235b
          Magazine *mag = mags[j];
Packit ae235b
          if (mag->count >= MIN_MAGAZINE_SIZE)
Packit ae235b
            magazine_cache_push_magazine (ix, mag->chunks, mag->count);
Packit ae235b
          else
Packit ae235b
            {
Packit ae235b
              const gsize chunk_size = SLAB_CHUNK_SIZE (allocator, ix);
Packit ae235b
              g_mutex_lock (&allocator->slab_mutex);
Packit ae235b
              while (mag->chunks)
Packit ae235b
                {
Packit ae235b
                  ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
Packit ae235b
                  slab_allocator_free_chunk (chunk_size, chunk);
Packit ae235b
                }
Packit ae235b
              g_mutex_unlock (&allocator->slab_mutex);
Packit ae235b
            }
Packit ae235b
        }
Packit ae235b
    }
Packit ae235b
  g_free (tmem);
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
thread_memory_magazine1_reload (ThreadMemory *tmem,
Packit ae235b
                                guint         ix)
Packit ae235b
{
Packit ae235b
  Magazine *mag = &tmem->magazine1[ix];
Packit ae235b
  mem_assert (mag->chunks == NULL); /* ensure that we may reset mag->count */
Packit ae235b
  mag->count = 0;
Packit ae235b
  mag->chunks = magazine_cache_pop_magazine (ix, &mag->count);
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
thread_memory_magazine2_unload (ThreadMemory *tmem,
Packit ae235b
                                guint         ix)
Packit ae235b
{
Packit ae235b
  Magazine *mag = &tmem->magazine2[ix];
Packit ae235b
  magazine_cache_push_magazine (ix, mag->chunks, mag->count);
Packit ae235b
  mag->chunks = NULL;
Packit ae235b
  mag->count = 0;
Packit ae235b
}
Packit ae235b
Packit ae235b
static inline void
Packit ae235b
thread_memory_swap_magazines (ThreadMemory *tmem,
Packit ae235b
                              guint         ix)
Packit ae235b
{
Packit ae235b
  Magazine xmag = tmem->magazine1[ix];
Packit ae235b
  tmem->magazine1[ix] = tmem->magazine2[ix];
Packit ae235b
  tmem->magazine2[ix] = xmag;
Packit ae235b
}
Packit ae235b
Packit ae235b
static inline gboolean
Packit ae235b
thread_memory_magazine1_is_empty (ThreadMemory *tmem,
Packit ae235b
                                  guint         ix)
Packit ae235b
{
Packit ae235b
  return tmem->magazine1[ix].chunks == NULL;
Packit ae235b
}
Packit ae235b
Packit ae235b
static inline gboolean
Packit ae235b
thread_memory_magazine2_is_full (ThreadMemory *tmem,
Packit ae235b
                                 guint         ix)
Packit ae235b
{
Packit ae235b
  return tmem->magazine2[ix].count >= allocator_get_magazine_threshold (allocator, ix);
Packit ae235b
}
Packit ae235b
Packit ae235b
static inline gpointer
Packit ae235b
thread_memory_magazine1_alloc (ThreadMemory *tmem,
Packit ae235b
                               guint         ix)
Packit ae235b
{
Packit ae235b
  Magazine *mag = &tmem->magazine1[ix];
Packit ae235b
  ChunkLink *chunk = magazine_chain_pop_head (&mag->chunks);
Packit ae235b
  if (G_LIKELY (mag->count > 0))
Packit ae235b
    mag->count--;
Packit ae235b
  return chunk;
Packit ae235b
}
Packit ae235b
Packit ae235b
static inline void
Packit ae235b
thread_memory_magazine2_free (ThreadMemory *tmem,
Packit ae235b
                              guint         ix,
Packit ae235b
                              gpointer      mem)
Packit ae235b
{
Packit ae235b
  Magazine *mag = &tmem->magazine2[ix];
Packit ae235b
  ChunkLink *chunk = mem;
Packit ae235b
  chunk->data = NULL;
Packit ae235b
  chunk->next = mag->chunks;
Packit ae235b
  mag->chunks = chunk;
Packit ae235b
  mag->count++;
Packit ae235b
}
Packit ae235b
Packit ae235b
/* --- API functions --- */
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_slice_new:
Packit ae235b
 * @type: the type to allocate, typically a structure name
Packit ae235b
 *
Packit ae235b
 * A convenience macro to allocate a block of memory from the
Packit ae235b
 * slice allocator.
Packit ae235b
 *
Packit ae235b
 * It calls g_slice_alloc() with `sizeof (@type)` and casts the
Packit ae235b
 * returned pointer to a pointer of the given type, avoiding a type
Packit ae235b
 * cast in the source code. Note that the underlying slice allocation
Packit ae235b
 * mechanism can be changed with the [`G_SLICE=always-malloc`][G_SLICE]
Packit ae235b
 * environment variable.
Packit ae235b
 *
Packit ae235b
 * This can never return %NULL as the minimum allocation size from
Packit ae235b
 * `sizeof (@type)` is 1 byte.
Packit ae235b
 *
Packit ae235b
 * Returns: (not nullable): a pointer to the allocated block, cast to a pointer
Packit ae235b
 *    to @type
Packit ae235b
 *
Packit ae235b
 * Since: 2.10
Packit ae235b
 */
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_slice_new0:
Packit ae235b
 * @type: the type to allocate, typically a structure name
Packit ae235b
 *
Packit ae235b
 * A convenience macro to allocate a block of memory from the
Packit ae235b
 * slice allocator and set the memory to 0.
Packit ae235b
 *
Packit ae235b
 * It calls g_slice_alloc0() with `sizeof (@type)`
Packit ae235b
 * and casts the returned pointer to a pointer of the given type,
Packit ae235b
 * avoiding a type cast in the source code.
Packit ae235b
 * Note that the underlying slice allocation mechanism can
Packit ae235b
 * be changed with the [`G_SLICE=always-malloc`][G_SLICE]
Packit ae235b
 * environment variable.
Packit ae235b
 *
Packit ae235b
 * This can never return %NULL as the minimum allocation size from
Packit ae235b
 * `sizeof (@type)` is 1 byte.
Packit ae235b
 *
Packit ae235b
 * Returns: (not nullable): a pointer to the allocated block, cast to a pointer
Packit ae235b
 *    to @type
Packit ae235b
 *
Packit ae235b
 * Since: 2.10
Packit ae235b
 */
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_slice_dup:
Packit ae235b
 * @type: the type to duplicate, typically a structure name
Packit ae235b
 * @mem: (not nullable): the memory to copy into the allocated block
Packit ae235b
 *
Packit ae235b
 * A convenience macro to duplicate a block of memory using
Packit ae235b
 * the slice allocator.
Packit ae235b
 *
Packit ae235b
 * It calls g_slice_copy() with `sizeof (@type)`
Packit ae235b
 * and casts the returned pointer to a pointer of the given type,
Packit ae235b
 * avoiding a type cast in the source code.
Packit ae235b
 * Note that the underlying slice allocation mechanism can
Packit ae235b
 * be changed with the [`G_SLICE=always-malloc`][G_SLICE]
Packit ae235b
 * environment variable.
Packit ae235b
 *
Packit ae235b
 * This can never return %NULL.
Packit ae235b
 *
Packit ae235b
 * Returns: (not nullable): a pointer to the allocated block, cast to a pointer
Packit ae235b
 *    to @type
Packit ae235b
 *
Packit ae235b
 * Since: 2.14
Packit ae235b
 */
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_slice_free:
Packit ae235b
 * @type: the type of the block to free, typically a structure name
Packit ae235b
 * @mem: a pointer to the block to free
Packit ae235b
 *
Packit ae235b
 * A convenience macro to free a block of memory that has
Packit ae235b
 * been allocated from the slice allocator.
Packit ae235b
 *
Packit ae235b
 * It calls g_slice_free1() using `sizeof (type)`
Packit ae235b
 * as the block size.
Packit ae235b
 * Note that the exact release behaviour can be changed with the
Packit ae235b
 * [`G_DEBUG=gc-friendly`][G_DEBUG] environment variable, also see
Packit ae235b
 * [`G_SLICE`][G_SLICE] for related debugging options.
Packit ae235b
 *
Packit ae235b
 * If @mem is %NULL, this macro does nothing.
Packit ae235b
 *
Packit ae235b
 * Since: 2.10
Packit ae235b
 */
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_slice_free_chain:
Packit ae235b
 * @type: the type of the @mem_chain blocks
Packit ae235b
 * @mem_chain: a pointer to the first block of the chain
Packit ae235b
 * @next: the field name of the next pointer in @type
Packit ae235b
 *
Packit ae235b
 * Frees a linked list of memory blocks of structure type @type.
Packit ae235b
 * The memory blocks must be equal-sized, allocated via
Packit ae235b
 * g_slice_alloc() or g_slice_alloc0() and linked together by
Packit ae235b
 * a @next pointer (similar to #GSList). The name of the
Packit ae235b
 * @next field in @type is passed as third argument.
Packit ae235b
 * Note that the exact release behaviour can be changed with the
Packit ae235b
 * [`G_DEBUG=gc-friendly`][G_DEBUG] environment variable, also see
Packit ae235b
 * [`G_SLICE`][G_SLICE] for related debugging options.
Packit ae235b
 *
Packit ae235b
 * If @mem_chain is %NULL, this function does nothing.
Packit ae235b
 *
Packit ae235b
 * Since: 2.10
Packit ae235b
 */
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_slice_alloc:
Packit ae235b
 * @block_size: the number of bytes to allocate
Packit ae235b
 *
Packit ae235b
 * Allocates a block of memory from the slice allocator.
Packit ae235b
 * The block address handed out can be expected to be aligned
Packit ae235b
 * to at least 1 * sizeof (void*),
Packit ae235b
 * though in general slices are 2 * sizeof (void*) bytes aligned,
Packit ae235b
 * if a malloc() fallback implementation is used instead,
Packit ae235b
 * the alignment may be reduced in a libc dependent fashion.
Packit ae235b
 * Note that the underlying slice allocation mechanism can
Packit ae235b
 * be changed with the [`G_SLICE=always-malloc`][G_SLICE]
Packit ae235b
 * environment variable.
Packit ae235b
 *
Packit ae235b
 * Returns: a pointer to the allocated memory block, which will be %NULL if and
Packit ae235b
 *    only if @mem_size is 0
Packit ae235b
 *
Packit ae235b
 * Since: 2.10
Packit ae235b
 */
Packit ae235b
gpointer
Packit ae235b
g_slice_alloc (gsize mem_size)
Packit ae235b
{
Packit ae235b
  ThreadMemory *tmem;
Packit ae235b
  gsize chunk_size;
Packit ae235b
  gpointer mem;
Packit ae235b
  guint acat;
Packit ae235b
Packit ae235b
  /* This gets the private structure for this thread.  If the private
Packit ae235b
   * structure does not yet exist, it is created.
Packit ae235b
   *
Packit ae235b
   * This has a side effect of causing GSlice to be initialised, so it
Packit ae235b
   * must come first.
Packit ae235b
   */
Packit ae235b
  tmem = thread_memory_from_self ();
Packit ae235b
Packit ae235b
  chunk_size = P2ALIGN (mem_size);
Packit ae235b
  acat = allocator_categorize (chunk_size);
Packit ae235b
  if (G_LIKELY (acat == 1))     /* allocate through magazine layer */
Packit ae235b
    {
Packit ae235b
      guint ix = SLAB_INDEX (allocator, chunk_size);
Packit ae235b
      if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
Packit ae235b
        {
Packit ae235b
          thread_memory_swap_magazines (tmem, ix);
Packit ae235b
          if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
Packit ae235b
            thread_memory_magazine1_reload (tmem, ix);
Packit ae235b
        }
Packit ae235b
      mem = thread_memory_magazine1_alloc (tmem, ix);
Packit ae235b
    }
Packit ae235b
  else if (acat == 2)           /* allocate through slab allocator */
Packit ae235b
    {
Packit ae235b
      g_mutex_lock (&allocator->slab_mutex);
Packit ae235b
      mem = slab_allocator_alloc_chunk (chunk_size);
Packit ae235b
      g_mutex_unlock (&allocator->slab_mutex);
Packit ae235b
    }
Packit ae235b
  else                          /* delegate to system malloc */
Packit ae235b
    mem = g_malloc (mem_size);
Packit ae235b
  if (G_UNLIKELY (allocator->config.debug_blocks))
Packit ae235b
    smc_notify_alloc (mem, mem_size);
Packit ae235b
Packit ae235b
  TRACE (GLIB_SLICE_ALLOC((void*)mem, mem_size));
Packit ae235b
Packit ae235b
  return mem;
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_slice_alloc0:
Packit ae235b
 * @block_size: the number of bytes to allocate
Packit ae235b
 *
Packit ae235b
 * Allocates a block of memory via g_slice_alloc() and initializes
Packit ae235b
 * the returned memory to 0. Note that the underlying slice allocation
Packit ae235b
 * mechanism can be changed with the [`G_SLICE=always-malloc`][G_SLICE]
Packit ae235b
 * environment variable.
Packit ae235b
 *
Packit ae235b
 * Returns: a pointer to the allocated block, which will be %NULL if and only
Packit ae235b
 *    if @mem_size is 0
Packit ae235b
 *
Packit ae235b
 * Since: 2.10
Packit ae235b
 */
Packit ae235b
gpointer
Packit ae235b
g_slice_alloc0 (gsize mem_size)
Packit ae235b
{
Packit ae235b
  gpointer mem = g_slice_alloc (mem_size);
Packit ae235b
  if (mem)
Packit ae235b
    memset (mem, 0, mem_size);
Packit ae235b
  return mem;
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_slice_copy:
Packit ae235b
 * @block_size: the number of bytes to allocate
Packit ae235b
 * @mem_block: the memory to copy
Packit ae235b
 *
Packit ae235b
 * Allocates a block of memory from the slice allocator
Packit ae235b
 * and copies @block_size bytes into it from @mem_block.
Packit ae235b
 *
Packit ae235b
 * @mem_block must be non-%NULL if @block_size is non-zero.
Packit ae235b
 *
Packit ae235b
 * Returns: a pointer to the allocated memory block, which will be %NULL if and
Packit ae235b
 *    only if @mem_size is 0
Packit ae235b
 *
Packit ae235b
 * Since: 2.14
Packit ae235b
 */
Packit ae235b
gpointer
Packit ae235b
g_slice_copy (gsize         mem_size,
Packit ae235b
              gconstpointer mem_block)
Packit ae235b
{
Packit ae235b
  gpointer mem = g_slice_alloc (mem_size);
Packit ae235b
  if (mem)
Packit ae235b
    memcpy (mem, mem_block, mem_size);
Packit ae235b
  return mem;
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_slice_free1:
Packit ae235b
 * @block_size: the size of the block
Packit ae235b
 * @mem_block: a pointer to the block to free
Packit ae235b
 *
Packit ae235b
 * Frees a block of memory.
Packit ae235b
 *
Packit ae235b
 * The memory must have been allocated via g_slice_alloc() or
Packit ae235b
 * g_slice_alloc0() and the @block_size has to match the size
Packit ae235b
 * specified upon allocation. Note that the exact release behaviour
Packit ae235b
 * can be changed with the [`G_DEBUG=gc-friendly`][G_DEBUG] environment
Packit ae235b
 * variable, also see [`G_SLICE`][G_SLICE] for related debugging options.
Packit ae235b
 *
Packit ae235b
 * If @mem_block is %NULL, this function does nothing.
Packit ae235b
 *
Packit ae235b
 * Since: 2.10
Packit ae235b
 */
Packit ae235b
void
Packit ae235b
g_slice_free1 (gsize    mem_size,
Packit ae235b
               gpointer mem_block)
Packit ae235b
{
Packit ae235b
  gsize chunk_size = P2ALIGN (mem_size);
Packit ae235b
  guint acat = allocator_categorize (chunk_size);
Packit ae235b
  if (G_UNLIKELY (!mem_block))
Packit ae235b
    return;
Packit ae235b
  if (G_UNLIKELY (allocator->config.debug_blocks) &&
Packit ae235b
      !smc_notify_free (mem_block, mem_size))
Packit ae235b
    abort();
Packit ae235b
  if (G_LIKELY (acat == 1))             /* allocate through magazine layer */
Packit ae235b
    {
Packit ae235b
      ThreadMemory *tmem = thread_memory_from_self();
Packit ae235b
      guint ix = SLAB_INDEX (allocator, chunk_size);
Packit ae235b
      if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
Packit ae235b
        {
Packit ae235b
          thread_memory_swap_magazines (tmem, ix);
Packit ae235b
          if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
Packit ae235b
            thread_memory_magazine2_unload (tmem, ix);
Packit ae235b
        }
Packit ae235b
      if (G_UNLIKELY (g_mem_gc_friendly))
Packit ae235b
        memset (mem_block, 0, chunk_size);
Packit ae235b
      thread_memory_magazine2_free (tmem, ix, mem_block);
Packit ae235b
    }
Packit ae235b
  else if (acat == 2)                   /* allocate through slab allocator */
Packit ae235b
    {
Packit ae235b
      if (G_UNLIKELY (g_mem_gc_friendly))
Packit ae235b
        memset (mem_block, 0, chunk_size);
Packit ae235b
      g_mutex_lock (&allocator->slab_mutex);
Packit ae235b
      slab_allocator_free_chunk (chunk_size, mem_block);
Packit ae235b
      g_mutex_unlock (&allocator->slab_mutex);
Packit ae235b
    }
Packit ae235b
  else                                  /* delegate to system malloc */
Packit ae235b
    {
Packit ae235b
      if (G_UNLIKELY (g_mem_gc_friendly))
Packit ae235b
        memset (mem_block, 0, mem_size);
Packit ae235b
      g_free (mem_block);
Packit ae235b
    }
Packit ae235b
  TRACE (GLIB_SLICE_FREE((void*)mem_block, mem_size));
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_slice_free_chain_with_offset:
Packit ae235b
 * @block_size: the size of the blocks
Packit ae235b
 * @mem_chain:  a pointer to the first block of the chain
Packit ae235b
 * @next_offset: the offset of the @next field in the blocks
Packit ae235b
 *
Packit ae235b
 * Frees a linked list of memory blocks of structure type @type.
Packit ae235b
 *
Packit ae235b
 * The memory blocks must be equal-sized, allocated via
Packit ae235b
 * g_slice_alloc() or g_slice_alloc0() and linked together by a
Packit ae235b
 * @next pointer (similar to #GSList). The offset of the @next
Packit ae235b
 * field in each block is passed as third argument.
Packit ae235b
 * Note that the exact release behaviour can be changed with the
Packit ae235b
 * [`G_DEBUG=gc-friendly`][G_DEBUG] environment variable, also see
Packit ae235b
 * [`G_SLICE`][G_SLICE] for related debugging options.
Packit ae235b
 *
Packit ae235b
 * If @mem_chain is %NULL, this function does nothing.
Packit ae235b
 *
Packit ae235b
 * Since: 2.10
Packit ae235b
 */
Packit ae235b
void
Packit ae235b
g_slice_free_chain_with_offset (gsize    mem_size,
Packit ae235b
                                gpointer mem_chain,
Packit ae235b
                                gsize    next_offset)
Packit ae235b
{
Packit ae235b
  gpointer slice = mem_chain;
Packit ae235b
  /* while the thread magazines and the magazine cache are implemented so that
Packit ae235b
   * they can easily be extended to allow for free lists containing more free
Packit ae235b
   * lists for the first level nodes, which would allow O(1) freeing in this
Packit ae235b
   * function, the benefit of such an extension is questionable, because:
Packit ae235b
   * - the magazine size counts will become mere lower bounds which confuses
Packit ae235b
   *   the code adapting to lock contention;
Packit ae235b
   * - freeing a single node to the thread magazines is very fast, so this
Packit ae235b
   *   O(list_length) operation is multiplied by a fairly small factor;
Packit ae235b
   * - memory usage histograms on larger applications seem to indicate that
Packit ae235b
   *   the amount of released multi node lists is negligible in comparison
Packit ae235b
   *   to single node releases.
Packit ae235b
   * - the major performance bottle neck, namely g_private_get() or
Packit ae235b
   *   g_mutex_lock()/g_mutex_unlock() has already been moved out of the
Packit ae235b
   *   inner loop for freeing chained slices.
Packit ae235b
   */
Packit ae235b
  gsize chunk_size = P2ALIGN (mem_size);
Packit ae235b
  guint acat = allocator_categorize (chunk_size);
Packit ae235b
  if (G_LIKELY (acat == 1))             /* allocate through magazine layer */
Packit ae235b
    {
Packit ae235b
      ThreadMemory *tmem = thread_memory_from_self();
Packit ae235b
      guint ix = SLAB_INDEX (allocator, chunk_size);
Packit ae235b
      while (slice)
Packit ae235b
        {
Packit ae235b
          guint8 *current = slice;
Packit ae235b
          slice = *(gpointer*) (current + next_offset);
Packit ae235b
          if (G_UNLIKELY (allocator->config.debug_blocks) &&
Packit ae235b
              !smc_notify_free (current, mem_size))
Packit ae235b
            abort();
Packit ae235b
          if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
Packit ae235b
            {
Packit ae235b
              thread_memory_swap_magazines (tmem, ix);
Packit ae235b
              if (G_UNLIKELY (thread_memory_magazine2_is_full (tmem, ix)))
Packit ae235b
                thread_memory_magazine2_unload (tmem, ix);
Packit ae235b
            }
Packit ae235b
          if (G_UNLIKELY (g_mem_gc_friendly))
Packit ae235b
            memset (current, 0, chunk_size);
Packit ae235b
          thread_memory_magazine2_free (tmem, ix, current);
Packit ae235b
        }
Packit ae235b
    }
Packit ae235b
  else if (acat == 2)                   /* allocate through slab allocator */
Packit ae235b
    {
Packit ae235b
      g_mutex_lock (&allocator->slab_mutex);
Packit ae235b
      while (slice)
Packit ae235b
        {
Packit ae235b
          guint8 *current = slice;
Packit ae235b
          slice = *(gpointer*) (current + next_offset);
Packit ae235b
          if (G_UNLIKELY (allocator->config.debug_blocks) &&
Packit ae235b
              !smc_notify_free (current, mem_size))
Packit ae235b
            abort();
Packit ae235b
          if (G_UNLIKELY (g_mem_gc_friendly))
Packit ae235b
            memset (current, 0, chunk_size);
Packit ae235b
          slab_allocator_free_chunk (chunk_size, current);
Packit ae235b
        }
Packit ae235b
      g_mutex_unlock (&allocator->slab_mutex);
Packit ae235b
    }
Packit ae235b
  else                                  /* delegate to system malloc */
Packit ae235b
    while (slice)
Packit ae235b
      {
Packit ae235b
        guint8 *current = slice;
Packit ae235b
        slice = *(gpointer*) (current + next_offset);
Packit ae235b
        if (G_UNLIKELY (allocator->config.debug_blocks) &&
Packit ae235b
            !smc_notify_free (current, mem_size))
Packit ae235b
          abort();
Packit ae235b
        if (G_UNLIKELY (g_mem_gc_friendly))
Packit ae235b
          memset (current, 0, mem_size);
Packit ae235b
        g_free (current);
Packit ae235b
      }
Packit ae235b
}
Packit ae235b
Packit ae235b
/* --- single page allocator --- */
Packit ae235b
static void
Packit ae235b
allocator_slab_stack_push (Allocator *allocator,
Packit ae235b
                           guint      ix,
Packit ae235b
                           SlabInfo  *sinfo)
Packit ae235b
{
Packit ae235b
  /* insert slab at slab ring head */
Packit ae235b
  if (!allocator->slab_stack[ix])
Packit ae235b
    {
Packit ae235b
      sinfo->next = sinfo;
Packit ae235b
      sinfo->prev = sinfo;
Packit ae235b
    }
Packit ae235b
  else
Packit ae235b
    {
Packit ae235b
      SlabInfo *next = allocator->slab_stack[ix], *prev = next->prev;
Packit ae235b
      next->prev = sinfo;
Packit ae235b
      prev->next = sinfo;
Packit ae235b
      sinfo->next = next;
Packit ae235b
      sinfo->prev = prev;
Packit ae235b
    }
Packit ae235b
  allocator->slab_stack[ix] = sinfo;
Packit ae235b
}
Packit ae235b
Packit ae235b
static gsize
Packit ae235b
allocator_aligned_page_size (Allocator *allocator,
Packit ae235b
                             gsize      n_bytes)
Packit ae235b
{
Packit ae235b
  gsize val = 1 << g_bit_storage (n_bytes - 1);
Packit ae235b
  val = MAX (val, allocator->min_page_size);
Packit ae235b
  return val;
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
allocator_add_slab (Allocator *allocator,
Packit ae235b
                    guint      ix,
Packit ae235b
                    gsize      chunk_size)
Packit ae235b
{
Packit ae235b
  ChunkLink *chunk;
Packit ae235b
  SlabInfo *sinfo;
Packit ae235b
  gsize addr, padding, n_chunks, color = 0;
Packit ae235b
  gsize page_size;
Packit ae235b
  int errsv;
Packit ae235b
  gpointer aligned_memory;
Packit ae235b
  guint8 *mem;
Packit ae235b
  guint i;
Packit ae235b
Packit ae235b
  page_size = allocator_aligned_page_size (allocator, SLAB_BPAGE_SIZE (allocator, chunk_size));
Packit ae235b
  /* allocate 1 page for the chunks and the slab */
Packit ae235b
  aligned_memory = allocator_memalign (page_size, page_size - NATIVE_MALLOC_PADDING);
Packit ae235b
  errsv = errno;
Packit ae235b
  mem = aligned_memory;
Packit ae235b
Packit ae235b
  if (!mem)
Packit ae235b
    {
Packit ae235b
      const gchar *syserr = strerror (errsv);
Packit ae235b
      mem_error ("failed to allocate %u bytes (alignment: %u): %s\n",
Packit ae235b
                 (guint) (page_size - NATIVE_MALLOC_PADDING), (guint) page_size, syserr);
Packit ae235b
    }
Packit ae235b
  /* mask page address */
Packit ae235b
  addr = ((gsize) mem / page_size) * page_size;
Packit ae235b
  /* assert alignment */
Packit ae235b
  mem_assert (aligned_memory == (gpointer) addr);
Packit ae235b
  /* basic slab info setup */
Packit ae235b
  sinfo = (SlabInfo*) (mem + page_size - SLAB_INFO_SIZE);
Packit ae235b
  sinfo->n_allocated = 0;
Packit ae235b
  sinfo->chunks = NULL;
Packit ae235b
  /* figure cache colorization */
Packit ae235b
  n_chunks = ((guint8*) sinfo - mem) / chunk_size;
Packit ae235b
  padding = ((guint8*) sinfo - mem) - n_chunks * chunk_size;
Packit ae235b
  if (padding)
Packit ae235b
    {
Packit ae235b
      color = (allocator->color_accu * P2ALIGNMENT) % padding;
Packit ae235b
      allocator->color_accu += allocator->config.color_increment;
Packit ae235b
    }
Packit ae235b
  /* add chunks to free list */
Packit ae235b
  chunk = (ChunkLink*) (mem + color);
Packit ae235b
  sinfo->chunks = chunk;
Packit ae235b
  for (i = 0; i < n_chunks - 1; i++)
Packit ae235b
    {
Packit ae235b
      chunk->next = (ChunkLink*) ((guint8*) chunk + chunk_size);
Packit ae235b
      chunk = chunk->next;
Packit ae235b
    }
Packit ae235b
  chunk->next = NULL;   /* last chunk */
Packit ae235b
  /* add slab to slab ring */
Packit ae235b
  allocator_slab_stack_push (allocator, ix, sinfo);
Packit ae235b
}
Packit ae235b
Packit ae235b
static gpointer
Packit ae235b
slab_allocator_alloc_chunk (gsize chunk_size)
Packit ae235b
{
Packit ae235b
  ChunkLink *chunk;
Packit ae235b
  guint ix = SLAB_INDEX (allocator, chunk_size);
Packit ae235b
  /* ensure non-empty slab */
Packit ae235b
  if (!allocator->slab_stack[ix] || !allocator->slab_stack[ix]->chunks)
Packit ae235b
    allocator_add_slab (allocator, ix, chunk_size);
Packit ae235b
  /* allocate chunk */
Packit ae235b
  chunk = allocator->slab_stack[ix]->chunks;
Packit ae235b
  allocator->slab_stack[ix]->chunks = chunk->next;
Packit ae235b
  allocator->slab_stack[ix]->n_allocated++;
Packit ae235b
  /* rotate empty slabs */
Packit ae235b
  if (!allocator->slab_stack[ix]->chunks)
Packit ae235b
    allocator->slab_stack[ix] = allocator->slab_stack[ix]->next;
Packit ae235b
  return chunk;
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
slab_allocator_free_chunk (gsize    chunk_size,
Packit ae235b
                           gpointer mem)
Packit ae235b
{
Packit ae235b
  ChunkLink *chunk;
Packit ae235b
  gboolean was_empty;
Packit ae235b
  guint ix = SLAB_INDEX (allocator, chunk_size);
Packit ae235b
  gsize page_size = allocator_aligned_page_size (allocator, SLAB_BPAGE_SIZE (allocator, chunk_size));
Packit ae235b
  gsize addr = ((gsize) mem / page_size) * page_size;
Packit ae235b
  /* mask page address */
Packit ae235b
  guint8 *page = (guint8*) addr;
Packit ae235b
  SlabInfo *sinfo = (SlabInfo*) (page + page_size - SLAB_INFO_SIZE);
Packit ae235b
  /* assert valid chunk count */
Packit ae235b
  mem_assert (sinfo->n_allocated > 0);
Packit ae235b
  /* add chunk to free list */
Packit ae235b
  was_empty = sinfo->chunks == NULL;
Packit ae235b
  chunk = (ChunkLink*) mem;
Packit ae235b
  chunk->next = sinfo->chunks;
Packit ae235b
  sinfo->chunks = chunk;
Packit ae235b
  sinfo->n_allocated--;
Packit ae235b
  /* keep slab ring partially sorted, empty slabs at end */
Packit ae235b
  if (was_empty)
Packit ae235b
    {
Packit ae235b
      /* unlink slab */
Packit ae235b
      SlabInfo *next = sinfo->next, *prev = sinfo->prev;
Packit ae235b
      next->prev = prev;
Packit ae235b
      prev->next = next;
Packit ae235b
      if (allocator->slab_stack[ix] == sinfo)
Packit ae235b
        allocator->slab_stack[ix] = next == sinfo ? NULL : next;
Packit ae235b
      /* insert slab at head */
Packit ae235b
      allocator_slab_stack_push (allocator, ix, sinfo);
Packit ae235b
    }
Packit ae235b
  /* eagerly free complete unused slabs */
Packit ae235b
  if (!sinfo->n_allocated)
Packit ae235b
    {
Packit ae235b
      /* unlink slab */
Packit ae235b
      SlabInfo *next = sinfo->next, *prev = sinfo->prev;
Packit ae235b
      next->prev = prev;
Packit ae235b
      prev->next = next;
Packit ae235b
      if (allocator->slab_stack[ix] == sinfo)
Packit ae235b
        allocator->slab_stack[ix] = next == sinfo ? NULL : next;
Packit ae235b
      /* free slab */
Packit ae235b
      allocator_memfree (page_size, page);
Packit ae235b
    }
Packit ae235b
}
Packit ae235b
Packit ae235b
/* --- memalign implementation --- */
Packit ae235b
#ifdef HAVE_MALLOC_H
Packit ae235b
#include <malloc.h>             /* memalign() */
Packit ae235b
#endif
Packit ae235b
Packit ae235b
/* from config.h:
Packit ae235b
 * define HAVE_POSIX_MEMALIGN           1 // if free(posix_memalign(3)) works, <stdlib.h>
Packit ae235b
 * define HAVE_COMPLIANT_POSIX_MEMALIGN 1 // if free(posix_memalign(3)) works for sizes != 2^n, <stdlib.h>
Packit ae235b
 * define HAVE_MEMALIGN                 1 // if free(memalign(3)) works, <malloc.h>
Packit ae235b
 * define HAVE_VALLOC                   1 // if free(valloc(3)) works, <stdlib.h> or <malloc.h>
Packit ae235b
 * if none is provided, we implement malloc(3)-based alloc-only page alignment
Packit ae235b
 */
Packit ae235b
Packit ae235b
#if !(HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC)
Packit ae235b
static GTrashStack *compat_valloc_trash = NULL;
Packit ae235b
#endif
Packit ae235b
Packit ae235b
static gpointer
Packit ae235b
allocator_memalign (gsize alignment,
Packit ae235b
                    gsize memsize)
Packit ae235b
{
Packit ae235b
  gpointer aligned_memory = NULL;
Packit ae235b
  gint err = ENOMEM;
Packit ae235b
#if     HAVE_COMPLIANT_POSIX_MEMALIGN
Packit ae235b
  err = posix_memalign (&aligned_memory, alignment, memsize);
Packit ae235b
#elif   HAVE_MEMALIGN
Packit ae235b
  errno = 0;
Packit ae235b
  aligned_memory = memalign (alignment, memsize);
Packit ae235b
  err = errno;
Packit ae235b
#elif   HAVE_VALLOC
Packit ae235b
  errno = 0;
Packit ae235b
  aligned_memory = valloc (memsize);
Packit ae235b
  err = errno;
Packit ae235b
#else
Packit ae235b
  /* simplistic non-freeing page allocator */
Packit ae235b
  mem_assert (alignment == sys_page_size);
Packit ae235b
  mem_assert (memsize <= sys_page_size);
Packit ae235b
  if (!compat_valloc_trash)
Packit ae235b
    {
Packit ae235b
      const guint n_pages = 16;
Packit ae235b
      guint8 *mem = malloc (n_pages * sys_page_size);
Packit ae235b
      err = errno;
Packit ae235b
      if (mem)
Packit ae235b
        {
Packit ae235b
          gint i = n_pages;
Packit ae235b
          guint8 *amem = (guint8*) ALIGN ((gsize) mem, sys_page_size);
Packit ae235b
          if (amem != mem)
Packit ae235b
            i--;        /* mem wasn't page aligned */
Packit ae235b
          while (--i >= 0)
Packit ae235b
            g_trash_stack_push (&compat_valloc_trash, amem + i * sys_page_size);
Packit ae235b
        }
Packit ae235b
    }
Packit ae235b
  aligned_memory = g_trash_stack_pop (&compat_valloc_trash);
Packit ae235b
#endif
Packit ae235b
  if (!aligned_memory)
Packit ae235b
    errno = err;
Packit ae235b
  return aligned_memory;
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
allocator_memfree (gsize    memsize,
Packit ae235b
                   gpointer mem)
Packit ae235b
{
Packit ae235b
#if     HAVE_COMPLIANT_POSIX_MEMALIGN || HAVE_MEMALIGN || HAVE_VALLOC
Packit ae235b
  free (mem);
Packit ae235b
#else
Packit ae235b
  mem_assert (memsize <= sys_page_size);
Packit ae235b
  g_trash_stack_push (&compat_valloc_trash, mem);
Packit ae235b
#endif
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
mem_error (const char *format,
Packit ae235b
           ...)
Packit ae235b
{
Packit ae235b
  const char *pname;
Packit ae235b
  va_list args;
Packit ae235b
  /* at least, put out "MEMORY-ERROR", in case we segfault during the rest of the function */
Packit ae235b
  fputs ("\n***MEMORY-ERROR***: ", stderr);
Packit ae235b
  pname = g_get_prgname();
Packit ae235b
  fprintf (stderr, "%s[%ld]: GSlice: ", pname ? pname : "", (long)getpid());
Packit ae235b
  va_start (args, format);
Packit ae235b
  vfprintf (stderr, format, args);
Packit ae235b
  va_end (args);
Packit ae235b
  fputs ("\n", stderr);
Packit ae235b
  abort();
Packit ae235b
  _exit (1);
Packit ae235b
}
Packit ae235b
Packit ae235b
/* --- g-slice memory checker tree --- */
Packit ae235b
typedef size_t SmcKType;                /* key type */
Packit ae235b
typedef size_t SmcVType;                /* value type */
Packit ae235b
typedef struct {
Packit ae235b
  SmcKType key;
Packit ae235b
  SmcVType value;
Packit ae235b
} SmcEntry;
Packit ae235b
static void             smc_tree_insert      (SmcKType  key,
Packit ae235b
                                              SmcVType  value);
Packit ae235b
static gboolean         smc_tree_lookup      (SmcKType  key,
Packit ae235b
                                              SmcVType *value_p);
Packit ae235b
static gboolean         smc_tree_remove      (SmcKType  key);
Packit ae235b
Packit ae235b
Packit ae235b
/* --- g-slice memory checker implementation --- */
Packit ae235b
static void
Packit ae235b
smc_notify_alloc (void   *pointer,
Packit ae235b
                  size_t  size)
Packit ae235b
{
Packit ae235b
  size_t address = (size_t) pointer;
Packit ae235b
  if (pointer)
Packit ae235b
    smc_tree_insert (address, size);
Packit ae235b
}
Packit ae235b
Packit ae235b
#if 0
Packit ae235b
static void
Packit ae235b
smc_notify_ignore (void *pointer)
Packit ae235b
{
Packit ae235b
  size_t address = (size_t) pointer;
Packit ae235b
  if (pointer)
Packit ae235b
    smc_tree_remove (address);
Packit ae235b
}
Packit ae235b
#endif
Packit ae235b
Packit ae235b
static int
Packit ae235b
smc_notify_free (void   *pointer,
Packit ae235b
                 size_t  size)
Packit ae235b
{
Packit ae235b
  size_t address = (size_t) pointer;
Packit ae235b
  SmcVType real_size;
Packit ae235b
  gboolean found_one;
Packit ae235b
Packit ae235b
  if (!pointer)
Packit ae235b
    return 1; /* ignore */
Packit ae235b
  found_one = smc_tree_lookup (address, &real_size);
Packit ae235b
  if (!found_one)
Packit ae235b
    {
Packit ae235b
      fprintf (stderr, "GSlice: MemChecker: attempt to release non-allocated block: %p size=%" G_GSIZE_FORMAT "\n", pointer, size);
Packit ae235b
      return 0;
Packit ae235b
    }
Packit ae235b
  if (real_size != size && (real_size || size))
Packit ae235b
    {
Packit ae235b
      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);
Packit ae235b
      return 0;
Packit ae235b
    }
Packit ae235b
  if (!smc_tree_remove (address))
Packit ae235b
    {
Packit ae235b
      fprintf (stderr, "GSlice: MemChecker: attempt to release non-allocated block: %p size=%" G_GSIZE_FORMAT "\n", pointer, size);
Packit ae235b
      return 0;
Packit ae235b
    }
Packit ae235b
  return 1; /* all fine */
Packit ae235b
}
Packit ae235b
Packit ae235b
/* --- g-slice memory checker tree implementation --- */
Packit ae235b
#define SMC_TRUNK_COUNT     (4093 /* 16381 */)          /* prime, to distribute trunk collisions (big, allocated just once) */
Packit ae235b
#define SMC_BRANCH_COUNT    (511)                       /* prime, to distribute branch collisions */
Packit ae235b
#define SMC_TRUNK_EXTENT    (SMC_BRANCH_COUNT * 2039)   /* key address space per trunk, should distribute uniformly across BRANCH_COUNT */
Packit ae235b
#define SMC_TRUNK_HASH(k)   ((k / SMC_TRUNK_EXTENT) % SMC_TRUNK_COUNT)  /* generate new trunk hash per megabyte (roughly) */
Packit ae235b
#define SMC_BRANCH_HASH(k)  (k % SMC_BRANCH_COUNT)
Packit ae235b
Packit ae235b
typedef struct {
Packit ae235b
  SmcEntry    *entries;
Packit ae235b
  unsigned int n_entries;
Packit ae235b
} SmcBranch;
Packit ae235b
Packit ae235b
static SmcBranch     **smc_tree_root = NULL;
Packit ae235b
Packit ae235b
static void
Packit ae235b
smc_tree_abort (int errval)
Packit ae235b
{
Packit ae235b
  const char *syserr = strerror (errval);
Packit ae235b
  mem_error ("MemChecker: failure in debugging tree: %s", syserr);
Packit ae235b
}
Packit ae235b
Packit ae235b
static inline SmcEntry*
Packit ae235b
smc_tree_branch_grow_L (SmcBranch   *branch,
Packit ae235b
                        unsigned int index)
Packit ae235b
{
Packit ae235b
  unsigned int old_size = branch->n_entries * sizeof (branch->entries[0]);
Packit ae235b
  unsigned int new_size = old_size + sizeof (branch->entries[0]);
Packit ae235b
  SmcEntry *entry;
Packit ae235b
  mem_assert (index <= branch->n_entries);
Packit ae235b
  branch->entries = (SmcEntry*) realloc (branch->entries, new_size);
Packit ae235b
  if (!branch->entries)
Packit ae235b
    smc_tree_abort (errno);
Packit ae235b
  entry = branch->entries + index;
Packit ae235b
  memmove (entry + 1, entry, (branch->n_entries - index) * sizeof (entry[0]));
Packit ae235b
  branch->n_entries += 1;
Packit ae235b
  return entry;
Packit ae235b
}
Packit ae235b
Packit ae235b
static inline SmcEntry*
Packit ae235b
smc_tree_branch_lookup_nearest_L (SmcBranch *branch,
Packit ae235b
                                  SmcKType   key)
Packit ae235b
{
Packit ae235b
  unsigned int n_nodes = branch->n_entries, offs = 0;
Packit ae235b
  SmcEntry *check = branch->entries;
Packit ae235b
  int cmp = 0;
Packit ae235b
  while (offs < n_nodes)
Packit ae235b
    {
Packit ae235b
      unsigned int i = (offs + n_nodes) >> 1;
Packit ae235b
      check = branch->entries + i;
Packit ae235b
      cmp = key < check->key ? -1 : key != check->key;
Packit ae235b
      if (cmp == 0)
Packit ae235b
        return check;                   /* return exact match */
Packit ae235b
      else if (cmp < 0)
Packit ae235b
        n_nodes = i;
Packit ae235b
      else /* (cmp > 0) */
Packit ae235b
        offs = i + 1;
Packit ae235b
    }
Packit ae235b
  /* check points at last mismatch, cmp > 0 indicates greater key */
Packit ae235b
  return cmp > 0 ? check + 1 : check;   /* return insertion position for inexact match */
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
smc_tree_insert (SmcKType key,
Packit ae235b
                 SmcVType value)
Packit ae235b
{
Packit ae235b
  unsigned int ix0, ix1;
Packit ae235b
  SmcEntry *entry;
Packit ae235b
Packit ae235b
  g_mutex_lock (&smc_tree_mutex);
Packit ae235b
  ix0 = SMC_TRUNK_HASH (key);
Packit ae235b
  ix1 = SMC_BRANCH_HASH (key);
Packit ae235b
  if (!smc_tree_root)
Packit ae235b
    {
Packit ae235b
      smc_tree_root = calloc (SMC_TRUNK_COUNT, sizeof (smc_tree_root[0]));
Packit ae235b
      if (!smc_tree_root)
Packit ae235b
        smc_tree_abort (errno);
Packit ae235b
    }
Packit ae235b
  if (!smc_tree_root[ix0])
Packit ae235b
    {
Packit ae235b
      smc_tree_root[ix0] = calloc (SMC_BRANCH_COUNT, sizeof (smc_tree_root[0][0]));
Packit ae235b
      if (!smc_tree_root[ix0])
Packit ae235b
        smc_tree_abort (errno);
Packit ae235b
    }
Packit ae235b
  entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
Packit ae235b
  if (!entry ||                                                                         /* need create */
Packit ae235b
      entry >= smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries ||   /* need append */
Packit ae235b
      entry->key != key)                                                                /* need insert */
Packit ae235b
    entry = smc_tree_branch_grow_L (&smc_tree_root[ix0][ix1], entry - smc_tree_root[ix0][ix1].entries);
Packit ae235b
  entry->key = key;
Packit ae235b
  entry->value = value;
Packit ae235b
  g_mutex_unlock (&smc_tree_mutex);
Packit ae235b
}
Packit ae235b
Packit ae235b
static gboolean
Packit ae235b
smc_tree_lookup (SmcKType  key,
Packit ae235b
                 SmcVType *value_p)
Packit ae235b
{
Packit ae235b
  SmcEntry *entry = NULL;
Packit ae235b
  unsigned int ix0 = SMC_TRUNK_HASH (key), ix1 = SMC_BRANCH_HASH (key);
Packit ae235b
  gboolean found_one = FALSE;
Packit ae235b
  *value_p = 0;
Packit ae235b
  g_mutex_lock (&smc_tree_mutex);
Packit ae235b
  if (smc_tree_root && smc_tree_root[ix0])
Packit ae235b
    {
Packit ae235b
      entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
Packit ae235b
      if (entry &&
Packit ae235b
          entry < smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries &&
Packit ae235b
          entry->key == key)
Packit ae235b
        {
Packit ae235b
          found_one = TRUE;
Packit ae235b
          *value_p = entry->value;
Packit ae235b
        }
Packit ae235b
    }
Packit ae235b
  g_mutex_unlock (&smc_tree_mutex);
Packit ae235b
  return found_one;
Packit ae235b
}
Packit ae235b
Packit ae235b
static gboolean
Packit ae235b
smc_tree_remove (SmcKType key)
Packit ae235b
{
Packit ae235b
  unsigned int ix0 = SMC_TRUNK_HASH (key), ix1 = SMC_BRANCH_HASH (key);
Packit ae235b
  gboolean found_one = FALSE;
Packit ae235b
  g_mutex_lock (&smc_tree_mutex);
Packit ae235b
  if (smc_tree_root && smc_tree_root[ix0])
Packit ae235b
    {
Packit ae235b
      SmcEntry *entry = smc_tree_branch_lookup_nearest_L (&smc_tree_root[ix0][ix1], key);
Packit ae235b
      if (entry &&
Packit ae235b
          entry < smc_tree_root[ix0][ix1].entries + smc_tree_root[ix0][ix1].n_entries &&
Packit ae235b
          entry->key == key)
Packit ae235b
        {
Packit ae235b
          unsigned int i = entry - smc_tree_root[ix0][ix1].entries;
Packit ae235b
          smc_tree_root[ix0][ix1].n_entries -= 1;
Packit ae235b
          memmove (entry, entry + 1, (smc_tree_root[ix0][ix1].n_entries - i) * sizeof (entry[0]));
Packit ae235b
          if (!smc_tree_root[ix0][ix1].n_entries)
Packit ae235b
            {
Packit ae235b
              /* avoid useless pressure on the memory system */
Packit ae235b
              free (smc_tree_root[ix0][ix1].entries);
Packit ae235b
              smc_tree_root[ix0][ix1].entries = NULL;
Packit ae235b
            }
Packit ae235b
          found_one = TRUE;
Packit ae235b
        }
Packit ae235b
    }
Packit ae235b
  g_mutex_unlock (&smc_tree_mutex);
Packit ae235b
  return found_one;
Packit ae235b
}
Packit ae235b
Packit ae235b
#ifdef G_ENABLE_DEBUG
Packit ae235b
void
Packit ae235b
g_slice_debug_tree_statistics (void)
Packit ae235b
{
Packit ae235b
  g_mutex_lock (&smc_tree_mutex);
Packit ae235b
  if (smc_tree_root)
Packit ae235b
    {
Packit ae235b
      unsigned int i, j, t = 0, o = 0, b = 0, su = 0, ex = 0, en = 4294967295u;
Packit ae235b
      double tf, bf;
Packit ae235b
      for (i = 0; i < SMC_TRUNK_COUNT; i++)
Packit ae235b
        if (smc_tree_root[i])
Packit ae235b
          {
Packit ae235b
            t++;
Packit ae235b
            for (j = 0; j < SMC_BRANCH_COUNT; j++)
Packit ae235b
              if (smc_tree_root[i][j].n_entries)
Packit ae235b
                {
Packit ae235b
                  b++;
Packit ae235b
                  su += smc_tree_root[i][j].n_entries;
Packit ae235b
                  en = MIN (en, smc_tree_root[i][j].n_entries);
Packit ae235b
                  ex = MAX (ex, smc_tree_root[i][j].n_entries);
Packit ae235b
                }
Packit ae235b
              else if (smc_tree_root[i][j].entries)
Packit ae235b
                o++; /* formerly used, now empty */
Packit ae235b
          }
Packit ae235b
      en = b ? en : 0;
Packit ae235b
      tf = MAX (t, 1.0); /* max(1) to be a valid divisor */
Packit ae235b
      bf = MAX (b, 1.0); /* max(1) to be a valid divisor */
Packit ae235b
      fprintf (stderr, "GSlice: MemChecker: %u trunks, %u branches, %u old branches\n", t, b, o);
Packit ae235b
      fprintf (stderr, "GSlice: MemChecker: %f branches per trunk, %.2f%% utilization\n",
Packit ae235b
               b / tf,
Packit ae235b
               100.0 - (SMC_BRANCH_COUNT - b / tf) / (0.01 * SMC_BRANCH_COUNT));
Packit ae235b
      fprintf (stderr, "GSlice: MemChecker: %f entries per branch, %u minimum, %u maximum\n",
Packit ae235b
               su / bf, en, ex);
Packit ae235b
    }
Packit ae235b
  else
Packit ae235b
    fprintf (stderr, "GSlice: MemChecker: root=NULL\n");
Packit ae235b
  g_mutex_unlock (&smc_tree_mutex);
Packit ae235b
  
Packit ae235b
  /* sample statistics (beast + GSLice + 24h scripted core & GUI activity):
Packit ae235b
   *  PID %CPU %MEM   VSZ  RSS      COMMAND
Packit ae235b
   * 8887 30.3 45.8 456068 414856   beast-0.7.1 empty.bse
Packit ae235b
   * $ cat /proc/8887/statm # total-program-size resident-set-size shared-pages text/code data/stack library dirty-pages
Packit ae235b
   * 114017 103714 2354 344 0 108676 0
Packit ae235b
   * $ cat /proc/8887/status 
Packit ae235b
   * Name:   beast-0.7.1
Packit ae235b
   * VmSize:   456068 kB
Packit ae235b
   * VmLck:         0 kB
Packit ae235b
   * VmRSS:    414856 kB
Packit ae235b
   * VmData:   434620 kB
Packit ae235b
   * VmStk:        84 kB
Packit ae235b
   * VmExe:      1376 kB
Packit ae235b
   * VmLib:     13036 kB
Packit ae235b
   * VmPTE:       456 kB
Packit ae235b
   * Threads:        3
Packit ae235b
   * (gdb) print g_slice_debug_tree_statistics ()
Packit ae235b
   * GSlice: MemChecker: 422 trunks, 213068 branches, 0 old branches
Packit ae235b
   * GSlice: MemChecker: 504.900474 branches per trunk, 98.81% utilization
Packit ae235b
   * GSlice: MemChecker: 4.965039 entries per branch, 1 minimum, 37 maximum
Packit ae235b
   */
Packit ae235b
}
Packit ae235b
#endif /* G_ENABLE_DEBUG */