[BACK]Return to jemalloc.c CVS log [TXT][DIR] Up to [cvs.NetBSD.org] / src / lib / libc / stdlib

Annotation of src/lib/libc/stdlib/jemalloc.c, Revision 1.3

1.3     ! he          1: /*     $NetBSD: jemalloc.c,v 1.2 2007/10/05 23:42:23 ad Exp $  */
1.2       ad          2:
1.1       ad          3: /*-
                      4:  * Copyright (C) 2006,2007 Jason Evans <jasone@FreeBSD.org>.
                      5:  * All rights reserved.
                      6:  *
                      7:  * Redistribution and use in source and binary forms, with or without
                      8:  * modification, are permitted provided that the following conditions
                      9:  * are met:
                     10:  * 1. Redistributions of source code must retain the above copyright
                     11:  *    notice(s), this list of conditions and the following disclaimer as
                     12:  *    the first lines of this file unmodified other than the possible
                     13:  *    addition of one or more copyright notices.
                     14:  * 2. Redistributions in binary form must reproduce the above copyright
                     15:  *    notice(s), this list of conditions and the following disclaimer in
                     16:  *    the documentation and/or other materials provided with the
                     17:  *    distribution.
                     18:  *
                     19:  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
                     20:  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
                     21:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
                     22:  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE
                     23:  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
                     24:  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
                     25:  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
                     26:  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
                     27:  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
                     28:  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
                     29:  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                     30:  *
                     31:  *******************************************************************************
                     32:  *
                     33:  * This allocator implementation is designed to provide scalable performance
                     34:  * for multi-threaded programs on multi-processor systems.  The following
                     35:  * features are included for this purpose:
                     36:  *
                     37:  *   + Multiple arenas are used if there are multiple CPUs, which reduces lock
                     38:  *     contention and cache sloshing.
                     39:  *
                     40:  *   + Cache line sharing between arenas is avoided for internal data
                     41:  *     structures.
                     42:  *
                     43:  *   + Memory is managed in chunks and runs (chunks can be split into runs),
                     44:  *     rather than as individual pages.  This provides a constant-time
                     45:  *     mechanism for associating allocations with particular arenas.
                     46:  *
                     47:  * Allocation requests are rounded up to the nearest size class, and no record
                     48:  * of the original request size is maintained.  Allocations are broken into
                     49:  * categories according to size class.  Assuming runtime defaults, 4 kB pages
                     50:  * and a 16 byte quantum, the size classes in each category are as follows:
                     51:  *
                     52:  *   |=====================================|
                     53:  *   | Category | Subcategory    |    Size |
                     54:  *   |=====================================|
                     55:  *   | Small    | Tiny           |       2 |
                     56:  *   |          |                |       4 |
                     57:  *   |          |                |       8 |
                     58:  *   |          |----------------+---------|
                     59:  *   |          | Quantum-spaced |      16 |
                     60:  *   |          |                |      32 |
                     61:  *   |          |                |      48 |
                     62:  *   |          |                |     ... |
                     63:  *   |          |                |     480 |
                     64:  *   |          |                |     496 |
                     65:  *   |          |                |     512 |
                     66:  *   |          |----------------+---------|
                     67:  *   |          | Sub-page       |    1 kB |
                     68:  *   |          |                |    2 kB |
                     69:  *   |=====================================|
                     70:  *   | Large                     |    4 kB |
                     71:  *   |                           |    8 kB |
                     72:  *   |                           |   12 kB |
                     73:  *   |                           |     ... |
                     74:  *   |                           | 1012 kB |
                     75:  *   |                           | 1016 kB |
                     76:  *   |                           | 1020 kB |
                     77:  *   |=====================================|
                     78:  *   | Huge                      |    1 MB |
                     79:  *   |                           |    2 MB |
                     80:  *   |                           |    3 MB |
                     81:  *   |                           |     ... |
                     82:  *   |=====================================|
                     83:  *
                     84:  * A different mechanism is used for each category:
                     85:  *
                     86:  *   Small : Each size class is segregated into its own set of runs.  Each run
                     87:  *           maintains a bitmap of which regions are free/allocated.
                     88:  *
                     89:  *   Large : Each allocation is backed by a dedicated run.  Metadata are stored
                     90:  *           in the associated arena chunk header maps.
                     91:  *
                     92:  *   Huge : Each allocation is backed by a dedicated contiguous set of chunks.
                     93:  *          Metadata are stored in a separate red-black tree.
                     94:  *
                     95:  *******************************************************************************
                     96:  */
                     97:
1.2       ad         98: /* LINTLIBRARY */
                     99:
                    100: #ifdef __NetBSD__
                    101: #  define xutrace(a, b)                utrace("malloc", (a), (b))
                    102: #  define __DECONST(x, y)      ((x)__UNCONST(y))
                    103: #  define NO_TLS
                    104: #else
                    105: #  define xutrace(a, b)                utrace((a), (b))
                    106: #endif /* __NetBSD__ */
                    107:
1.1       ad        108: /*
                    109:  * MALLOC_PRODUCTION disables assertions and statistics gathering.  It also
                    110:  * defaults the A and J runtime options to off.  These settings are appropriate
                    111:  * for production systems.
                    112:  */
1.2       ad        113: #define MALLOC_PRODUCTION
1.1       ad        114:
                    115: #ifndef MALLOC_PRODUCTION
                    116: #  define MALLOC_DEBUG
                    117: #endif
                    118:
                    119: #include <sys/cdefs.h>
1.2       ad        120: /* __FBSDID("$FreeBSD: src/lib/libc/stdlib/malloc.c,v 1.147 2007/06/15 22:00:16 jasone Exp $"); */
1.3     ! he        121: __RCSID("$NetBSD: jemalloc.c,v 1.2 2007/10/05 23:42:23 ad Exp $");
1.1       ad        122:
1.2       ad        123: #ifdef __FreeBSD__
1.1       ad        124: #include "libc_private.h"
                    125: #ifdef MALLOC_DEBUG
                    126: #  define _LOCK_DEBUG
                    127: #endif
                    128: #include "spinlock.h"
1.2       ad        129: #endif
1.1       ad        130: #include "namespace.h"
                    131: #include <sys/mman.h>
                    132: #include <sys/param.h>
1.2       ad        133: #ifdef __FreeBSD__
1.1       ad        134: #include <sys/stddef.h>
1.2       ad        135: #endif
1.1       ad        136: #include <sys/time.h>
                    137: #include <sys/types.h>
                    138: #include <sys/sysctl.h>
                    139: #include <sys/tree.h>
                    140: #include <sys/uio.h>
                    141: #include <sys/ktrace.h> /* Must come after several other sys/ includes. */
                    142:
1.2       ad        143: #ifdef __FreeBSD__
1.1       ad        144: #include <machine/atomic.h>
                    145: #include <machine/cpufunc.h>
1.2       ad        146: #endif
1.1       ad        147: #include <machine/vmparam.h>
                    148:
                    149: #include <errno.h>
                    150: #include <limits.h>
                    151: #include <pthread.h>
                    152: #include <sched.h>
                    153: #include <stdarg.h>
                    154: #include <stdbool.h>
                    155: #include <stdio.h>
                    156: #include <stdint.h>
                    157: #include <stdlib.h>
                    158: #include <string.h>
                    159: #include <strings.h>
                    160: #include <unistd.h>
                    161:
1.2       ad        162: #ifdef __NetBSD__
                    163: #  include <reentrant.h>
                    164: void   _malloc_prefork(void);
                    165: void   _malloc_postfork(void);
                    166: ssize_t        _write(int, const void *, size_t);
                    167: const char     *_getprogname(void);
                    168: #endif
                    169:
                    170: #ifdef __FreeBSD__
1.1       ad        171: #include "un-namespace.h"
1.2       ad        172: #endif
1.1       ad        173:
                    174: /* MALLOC_STATS enables statistics calculation. */
                    175: #ifndef MALLOC_PRODUCTION
                    176: #  define MALLOC_STATS
                    177: #endif
                    178:
                    179: #ifdef MALLOC_DEBUG
                    180: #  ifdef NDEBUG
                    181: #    undef NDEBUG
                    182: #  endif
                    183: #else
                    184: #  ifndef NDEBUG
                    185: #    define NDEBUG
                    186: #  endif
                    187: #endif
                    188: #include <assert.h>
                    189:
                    190: #ifdef MALLOC_DEBUG
                    191:    /* Disable inlining to make debugging easier. */
                    192: #  define inline
                    193: #endif
                    194:
                    195: /* Size of stack-allocated buffer passed to strerror_r(). */
                    196: #define        STRERROR_BUF            64
                    197:
                    198: /* Minimum alignment of allocations is 2^QUANTUM_2POW_MIN bytes. */
                    199: #ifdef __i386__
                    200: #  define QUANTUM_2POW_MIN     4
                    201: #  define SIZEOF_PTR_2POW      2
                    202: #  define USE_BRK
                    203: #endif
                    204: #ifdef __ia64__
                    205: #  define QUANTUM_2POW_MIN     4
                    206: #  define SIZEOF_PTR_2POW      3
                    207: #endif
                    208: #ifdef __alpha__
                    209: #  define QUANTUM_2POW_MIN     4
                    210: #  define SIZEOF_PTR_2POW      3
                    211: #  define NO_TLS
                    212: #endif
                    213: #ifdef __sparc64__
                    214: #  define QUANTUM_2POW_MIN     4
                    215: #  define SIZEOF_PTR_2POW      3
                    216: #  define NO_TLS
                    217: #endif
                    218: #ifdef __amd64__
                    219: #  define QUANTUM_2POW_MIN     4
                    220: #  define SIZEOF_PTR_2POW      3
                    221: #endif
                    222: #ifdef __arm__
                    223: #  define QUANTUM_2POW_MIN     3
                    224: #  define SIZEOF_PTR_2POW      2
                    225: #  define USE_BRK
                    226: #  define NO_TLS
                    227: #endif
                    228: #ifdef __powerpc__
                    229: #  define QUANTUM_2POW_MIN     4
                    230: #  define SIZEOF_PTR_2POW      2
                    231: #  define USE_BRK
                    232: #endif
1.3     ! he        233: #if defined(__sparc__) && !defined(__sparc64__)
1.2       ad        234: #  define QUANTUM_2POW_MIN     4
                    235: #  define SIZEOF_PTR_2POW      2
                    236: #  define USE_BRK
                    237: #endif
                    238: #ifdef __vax__
                    239: #  define QUANTUM_2POW_MIN     4
                    240: #  define SIZEOF_PTR_2POW      2
                    241: #  define USE_BRK
                    242: #endif
                    243: #ifdef __sh__
                    244: #  define QUANTUM_2POW_MIN     4
                    245: #  define SIZEOF_PTR_2POW      2
                    246: #  define USE_BRK
                    247: #endif
                    248: #ifdef __m68k__
                    249: #  define QUANTUM_2POW_MIN     4
                    250: #  define SIZEOF_PTR_2POW      2
                    251: #  define USE_BRK
                    252: #endif
                    253: #ifdef __mips__
                    254: #  define QUANTUM_2POW_MIN     4
                    255: #  define SIZEOF_PTR_2POW      2
                    256: #  define USE_BRK
                    257: #endif
1.1       ad        258:
                    259: #define        SIZEOF_PTR              (1 << SIZEOF_PTR_2POW)
                    260:
                    261: /* sizeof(int) == (1 << SIZEOF_INT_2POW). */
                    262: #ifndef SIZEOF_INT_2POW
                    263: #  define SIZEOF_INT_2POW      2
                    264: #endif
                    265:
                    266: /* We can't use TLS in non-PIC programs, since TLS relies on loader magic. */
                    267: #if (!defined(PIC) && !defined(NO_TLS))
                    268: #  define NO_TLS
                    269: #endif
                    270:
                    271: /*
                    272:  * Size and alignment of memory chunks that are allocated by the OS's virtual
                    273:  * memory system.
                    274:  */
                    275: #define        CHUNK_2POW_DEFAULT      20
                    276:
                    277: /*
                    278:  * Maximum size of L1 cache line.  This is used to avoid cache line aliasing,
                    279:  * so over-estimates are okay (up to a point), but under-estimates will
                    280:  * negatively affect performance.
                    281:  */
                    282: #define        CACHELINE_2POW          6
                    283: #define        CACHELINE               ((size_t)(1 << CACHELINE_2POW))
                    284:
                    285: /* Smallest size class to support. */
                    286: #define        TINY_MIN_2POW           1
                    287:
                    288: /*
                    289:  * Maximum size class that is a multiple of the quantum, but not (necessarily)
                    290:  * a power of 2.  Above this size, allocations are rounded up to the nearest
                    291:  * power of 2.
                    292:  */
                    293: #define        SMALL_MAX_2POW_DEFAULT  9
                    294: #define        SMALL_MAX_DEFAULT       (1 << SMALL_MAX_2POW_DEFAULT)
                    295:
                    296: /*
                    297:  * Maximum desired run header overhead.  Runs are sized as small as possible
                    298:  * such that this setting is still honored, without violating other constraints.
                    299:  * The goal is to make runs as small as possible without exceeding a per run
                    300:  * external fragmentation threshold.
                    301:  *
                    302:  * Note that it is possible to set this low enough that it cannot be honored
                    303:  * for some/all object sizes, since there is one bit of header overhead per
                    304:  * object (plus a constant).  In such cases, this constraint is relaxed.
                    305:  *
                    306:  * RUN_MAX_OVRHD_RELAX specifies the maximum number of bits per region of
                    307:  * overhead for which RUN_MAX_OVRHD is relaxed.
                    308:  */
                    309: #define RUN_MAX_OVRHD          0.015
                    310: #define RUN_MAX_OVRHD_RELAX    1.5
                    311:
                    312: /* Put a cap on small object run size.  This overrides RUN_MAX_OVRHD. */
                    313: #define RUN_MAX_SMALL_2POW     15
                    314: #define RUN_MAX_SMALL          (1 << RUN_MAX_SMALL_2POW)
                    315:
                    316: /******************************************************************************/
                    317:
1.2       ad        318: #ifdef __FreeBSD__
1.1       ad        319: /*
                    320:  * Mutexes based on spinlocks.  We can't use normal pthread mutexes, because
                    321:  * they require malloc()ed memory.
                    322:  */
                    323: typedef struct {
                    324:        spinlock_t      lock;
                    325: } malloc_mutex_t;
                    326:
                    327: /* Set to true once the allocator has been initialized. */
                    328: static bool malloc_initialized = false;
                    329:
                    330: /* Used to avoid initialization races. */
                    331: static malloc_mutex_t init_lock = {_SPINLOCK_INITIALIZER};
1.2       ad        332: #else
                    333: #define        malloc_mutex_t  mutex_t
                    334:
                    335: /* Set to true once the allocator has been initialized. */
                    336: static bool malloc_initialized = false;
                    337:
                    338: /* Used to avoid initialization races. */
                    339: static mutex_t init_lock = MUTEX_INITIALIZER;
                    340: #endif
1.1       ad        341:
                    342: /******************************************************************************/
                    343: /*
                    344:  * Statistics data structures.
                    345:  */
                    346:
                    347: #ifdef MALLOC_STATS
                    348:
                    349: typedef struct malloc_bin_stats_s malloc_bin_stats_t;
                    350: struct malloc_bin_stats_s {
                    351:        /*
                    352:         * Number of allocation requests that corresponded to the size of this
                    353:         * bin.
                    354:         */
                    355:        uint64_t        nrequests;
                    356:
                    357:        /* Total number of runs created for this bin's size class. */
                    358:        uint64_t        nruns;
                    359:
                    360:        /*
                    361:         * Total number of runs reused by extracting them from the runs tree for
                    362:         * this bin's size class.
                    363:         */
                    364:        uint64_t        reruns;
                    365:
                    366:        /* High-water mark for this bin. */
                    367:        unsigned long   highruns;
                    368:
                    369:        /* Current number of runs in this bin. */
                    370:        unsigned long   curruns;
                    371: };
                    372:
                    373: typedef struct arena_stats_s arena_stats_t;
                    374: struct arena_stats_s {
                    375:        /* Number of bytes currently mapped. */
                    376:        size_t          mapped;
                    377:
                    378:        /* Per-size-category statistics. */
                    379:        size_t          allocated_small;
                    380:        uint64_t        nmalloc_small;
                    381:        uint64_t        ndalloc_small;
                    382:
                    383:        size_t          allocated_large;
                    384:        uint64_t        nmalloc_large;
                    385:        uint64_t        ndalloc_large;
                    386: };
                    387:
                    388: typedef struct chunk_stats_s chunk_stats_t;
                    389: struct chunk_stats_s {
                    390:        /* Number of chunks that were allocated. */
                    391:        uint64_t        nchunks;
                    392:
                    393:        /* High-water mark for number of chunks allocated. */
                    394:        unsigned long   highchunks;
                    395:
                    396:        /*
                    397:         * Current number of chunks allocated.  This value isn't maintained for
                    398:         * any other purpose, so keep track of it in order to be able to set
                    399:         * highchunks.
                    400:         */
                    401:        unsigned long   curchunks;
                    402: };
                    403:
                    404: #endif /* #ifdef MALLOC_STATS */
                    405:
                    406: /******************************************************************************/
                    407: /*
                    408:  * Chunk data structures.
                    409:  */
                    410:
                    411: /* Tree of chunks. */
                    412: typedef struct chunk_node_s chunk_node_t;
                    413: struct chunk_node_s {
                    414:        /* Linkage for the chunk tree. */
                    415:        RB_ENTRY(chunk_node_s) link;
                    416:
                    417:        /*
                    418:         * Pointer to the chunk that this tree node is responsible for.  In some
                    419:         * (but certainly not all) cases, this data structure is placed at the
                    420:         * beginning of the corresponding chunk, so this field may point to this
                    421:         * node.
                    422:         */
                    423:        void    *chunk;
                    424:
                    425:        /* Total chunk size. */
                    426:        size_t  size;
                    427: };
                    428: typedef struct chunk_tree_s chunk_tree_t;
                    429: RB_HEAD(chunk_tree_s, chunk_node_s);
                    430:
                    431: /******************************************************************************/
                    432: /*
                    433:  * Arena data structures.
                    434:  */
                    435:
                    436: typedef struct arena_s arena_t;
                    437: typedef struct arena_bin_s arena_bin_t;
                    438:
                    439: typedef struct arena_chunk_map_s arena_chunk_map_t;
                    440: struct arena_chunk_map_s {
                    441:        /* Number of pages in run. */
                    442:        uint32_t        npages;
                    443:        /*
                    444:         * Position within run.  For a free run, this is POS_FREE for the first
                    445:         * and last pages.  The POS_FREE special value makes it possible to
                    446:         * quickly coalesce free runs.
                    447:         *
                    448:         * This is the limiting factor for chunksize; there can be at most 2^31
                    449:         * pages in a run.
                    450:         */
                    451: #define POS_FREE ((uint32_t)0xffffffffU)
                    452:        uint32_t        pos;
                    453: };
                    454:
                    455: /* Arena chunk header. */
                    456: typedef struct arena_chunk_s arena_chunk_t;
                    457: struct arena_chunk_s {
                    458:        /* Arena that owns the chunk. */
                    459:        arena_t *arena;
                    460:
                    461:        /* Linkage for the arena's chunk tree. */
                    462:        RB_ENTRY(arena_chunk_s) link;
                    463:
                    464:        /*
                    465:         * Number of pages in use.  This is maintained in order to make
                    466:         * detection of empty chunks fast.
                    467:         */
                    468:        uint32_t pages_used;
                    469:
                    470:        /*
                    471:         * Every time a free run larger than this value is created/coalesced,
                    472:         * this value is increased.  The only way that the value decreases is if
                    473:         * arena_run_alloc() fails to find a free run as large as advertised by
                    474:         * this value.
                    475:         */
                    476:        uint32_t max_frun_npages;
                    477:
                    478:        /*
                    479:         * Every time a free run that starts at an earlier page than this value
                    480:         * is created/coalesced, this value is decreased.  It is reset in a
                    481:         * similar fashion to max_frun_npages.
                    482:         */
                    483:        uint32_t min_frun_ind;
                    484:
                    485:        /*
                    486:         * Map of pages within chunk that keeps track of free/large/small.  For
                    487:         * free runs, only the map entries for the first and last pages are
                    488:         * kept up to date, so that free runs can be quickly coalesced.
                    489:         */
                    490:        arena_chunk_map_t map[1]; /* Dynamically sized. */
                    491: };
                    492: typedef struct arena_chunk_tree_s arena_chunk_tree_t;
                    493: RB_HEAD(arena_chunk_tree_s, arena_chunk_s);
                    494:
                    495: typedef struct arena_run_s arena_run_t;
                    496: struct arena_run_s {
                    497:        /* Linkage for run trees. */
                    498:        RB_ENTRY(arena_run_s) link;
                    499:
                    500: #ifdef MALLOC_DEBUG
                    501:        uint32_t        magic;
                    502: #  define ARENA_RUN_MAGIC 0x384adf93
                    503: #endif
                    504:
                    505:        /* Bin this run is associated with. */
                    506:        arena_bin_t     *bin;
                    507:
                    508:        /* Index of first element that might have a free region. */
                    509:        unsigned        regs_minelm;
                    510:
                    511:        /* Number of free regions in run. */
                    512:        unsigned        nfree;
                    513:
                    514:        /* Bitmask of in-use regions (0: in use, 1: free). */
                    515:        unsigned        regs_mask[1]; /* Dynamically sized. */
                    516: };
                    517: typedef struct arena_run_tree_s arena_run_tree_t;
                    518: RB_HEAD(arena_run_tree_s, arena_run_s);
                    519:
                    520: struct arena_bin_s {
                    521:        /*
                    522:         * Current run being used to service allocations of this bin's size
                    523:         * class.
                    524:         */
                    525:        arena_run_t     *runcur;
                    526:
                    527:        /*
                    528:         * Tree of non-full runs.  This tree is used when looking for an
                    529:         * existing run when runcur is no longer usable.  We choose the
                    530:         * non-full run that is lowest in memory; this policy tends to keep
                    531:         * objects packed well, and it can also help reduce the number of
                    532:         * almost-empty chunks.
                    533:         */
                    534:        arena_run_tree_t runs;
                    535:
                    536:        /* Size of regions in a run for this bin's size class. */
                    537:        size_t          reg_size;
                    538:
                    539:        /* Total size of a run for this bin's size class. */
                    540:        size_t          run_size;
                    541:
                    542:        /* Total number of regions in a run for this bin's size class. */
                    543:        uint32_t        nregs;
                    544:
                    545:        /* Number of elements in a run's regs_mask for this bin's size class. */
                    546:        uint32_t        regs_mask_nelms;
                    547:
                    548:        /* Offset of first region in a run for this bin's size class. */
                    549:        uint32_t        reg0_offset;
                    550:
                    551: #ifdef MALLOC_STATS
                    552:        /* Bin statistics. */
                    553:        malloc_bin_stats_t stats;
                    554: #endif
                    555: };
                    556:
                    557: struct arena_s {
                    558: #ifdef MALLOC_DEBUG
                    559:        uint32_t                magic;
                    560: #  define ARENA_MAGIC 0x947d3d24
                    561: #endif
                    562:
                    563:        /* All operations on this arena require that mtx be locked. */
                    564:        malloc_mutex_t          mtx;
                    565:
                    566: #ifdef MALLOC_STATS
                    567:        arena_stats_t           stats;
                    568: #endif
                    569:
                    570:        /*
                    571:         * Tree of chunks this arena manages.
                    572:         */
                    573:        arena_chunk_tree_t      chunks;
                    574:
                    575:        /*
                    576:         * In order to avoid rapid chunk allocation/deallocation when an arena
                    577:         * oscillates right on the cusp of needing a new chunk, cache the most
                    578:         * recently freed chunk.  This caching is disabled by opt_hint.
                    579:         *
                    580:         * There is one spare chunk per arena, rather than one spare total, in
                    581:         * order to avoid interactions between multiple threads that could make
                    582:         * a single spare inadequate.
                    583:         */
                    584:        arena_chunk_t *spare;
                    585:
                    586:        /*
                    587:         * bins is used to store rings of free regions of the following sizes,
                    588:         * assuming a 16-byte quantum, 4kB pagesize, and default MALLOC_OPTIONS.
                    589:         *
                    590:         *   bins[i] | size |
                    591:         *   --------+------+
                    592:         *        0  |    2 |
                    593:         *        1  |    4 |
                    594:         *        2  |    8 |
                    595:         *   --------+------+
                    596:         *        3  |   16 |
                    597:         *        4  |   32 |
                    598:         *        5  |   48 |
                    599:         *        6  |   64 |
                    600:         *           :      :
                    601:         *           :      :
                    602:         *       33  |  496 |
                    603:         *       34  |  512 |
                    604:         *   --------+------+
                    605:         *       35  | 1024 |
                    606:         *       36  | 2048 |
                    607:         *   --------+------+
                    608:         */
                    609:        arena_bin_t             bins[1]; /* Dynamically sized. */
                    610: };
                    611:
                    612: /******************************************************************************/
                    613: /*
                    614:  * Data.
                    615:  */
                    616:
                    617: /* Number of CPUs. */
                    618: static unsigned                ncpus;
                    619:
                    620: /* VM page size. */
                    621: static size_t          pagesize;
                    622: static size_t          pagesize_mask;
                    623: static size_t          pagesize_2pow;
                    624:
                    625: /* Various bin-related settings. */
                    626: static size_t          bin_maxclass; /* Max size class for bins. */
                    627: static unsigned                ntbins; /* Number of (2^n)-spaced tiny bins. */
                    628: static unsigned                nqbins; /* Number of quantum-spaced bins. */
                    629: static unsigned                nsbins; /* Number of (2^n)-spaced sub-page bins. */
                    630: static size_t          small_min;
                    631: static size_t          small_max;
                    632:
                    633: /* Various quantum-related settings. */
                    634: static size_t          quantum;
                    635: static size_t          quantum_mask; /* (quantum - 1). */
                    636:
                    637: /* Various chunk-related settings. */
                    638: static size_t          chunksize;
                    639: static size_t          chunksize_mask; /* (chunksize - 1). */
                    640: static unsigned                chunk_npages;
                    641: static unsigned                arena_chunk_header_npages;
                    642: static size_t          arena_maxclass; /* Max size class for arenas. */
                    643:
                    644: /********/
                    645: /*
                    646:  * Chunks.
                    647:  */
                    648:
                    649: /* Protects chunk-related data structures. */
                    650: static malloc_mutex_t  chunks_mtx;
                    651:
                    652: /* Tree of chunks that are stand-alone huge allocations. */
                    653: static chunk_tree_t    huge;
                    654:
                    655: #ifdef USE_BRK
                    656: /*
                    657:  * Try to use brk for chunk-size allocations, due to address space constraints.
                    658:  */
                    659: /*
                    660:  * Protects sbrk() calls.  This must be separate from chunks_mtx, since
                    661:  * base_pages_alloc() also uses sbrk(), but cannot lock chunks_mtx (doing so
                    662:  * could cause recursive lock acquisition).
                    663:  */
                    664: static malloc_mutex_t  brk_mtx;
                    665: /* Result of first sbrk(0) call. */
                    666: static void            *brk_base;
                    667: /* Current end of brk, or ((void *)-1) if brk is exhausted. */
                    668: static void            *brk_prev;
                    669: /* Current upper limit on brk addresses. */
                    670: static void            *brk_max;
                    671: #endif
                    672:
                    673: #ifdef MALLOC_STATS
                    674: /* Huge allocation statistics. */
                    675: static uint64_t                huge_nmalloc;
                    676: static uint64_t                huge_ndalloc;
                    677: static size_t          huge_allocated;
                    678: #endif
                    679:
                    680: /*
                    681:  * Tree of chunks that were previously allocated.  This is used when allocating
                    682:  * chunks, in an attempt to re-use address space.
                    683:  */
                    684: static chunk_tree_t    old_chunks;
                    685:
                    686: /****************************/
                    687: /*
                    688:  * base (internal allocation).
                    689:  */
                    690:
                    691: /*
                    692:  * Current pages that are being used for internal memory allocations.  These
                    693:  * pages are carved up in cacheline-size quanta, so that there is no chance of
                    694:  * false cache line sharing.
                    695:  */
                    696: static void            *base_pages;
                    697: static void            *base_next_addr;
                    698: static void            *base_past_addr; /* Addr immediately past base_pages. */
                    699: static chunk_node_t    *base_chunk_nodes; /* LIFO cache of chunk nodes. */
                    700: static malloc_mutex_t  base_mtx;
                    701: #ifdef MALLOC_STATS
                    702: static size_t          base_mapped;
                    703: #endif
                    704:
                    705: /********/
                    706: /*
                    707:  * Arenas.
                    708:  */
                    709:
                    710: /*
                    711:  * Arenas that are used to service external requests.  Not all elements of the
                    712:  * arenas array are necessarily used; arenas are created lazily as needed.
                    713:  */
                    714: static arena_t         **arenas;
                    715: static unsigned                narenas;
                    716: static unsigned                next_arena;
                    717: static malloc_mutex_t  arenas_mtx; /* Protects arenas initialization. */
                    718:
                    719: #ifndef NO_TLS
                    720: /*
                    721:  * Map of pthread_self() --> arenas[???], used for selecting an arena to use
                    722:  * for allocations.
                    723:  */
                    724: static __thread arena_t        *arenas_map;
1.2       ad        725: #define        get_arenas_map()        (arenas_map)
                    726: #define        set_arenas_map(x)       (arenas_map = x)
                    727: #else
                    728: static thread_key_t arenas_map_key;
                    729: #define        get_arenas_map()        thr_getspecific(arenas_map_key)
                    730: #define        set_arenas_map(x)       thr_setspecific(arenas_map_key, x)
1.1       ad        731: #endif
                    732:
                    733: #ifdef MALLOC_STATS
                    734: /* Chunk statistics. */
                    735: static chunk_stats_t   stats_chunks;
                    736: #endif
                    737:
                    738: /*******************************/
                    739: /*
                    740:  * Runtime configuration options.
                    741:  */
                    742: const char     *_malloc_options;
                    743:
                    744: #ifndef MALLOC_PRODUCTION
                    745: static bool    opt_abort = true;
                    746: static bool    opt_junk = true;
                    747: #else
                    748: static bool    opt_abort = false;
                    749: static bool    opt_junk = false;
                    750: #endif
                    751: static bool    opt_hint = false;
                    752: static bool    opt_print_stats = false;
                    753: static size_t  opt_quantum_2pow = QUANTUM_2POW_MIN;
                    754: static size_t  opt_small_max_2pow = SMALL_MAX_2POW_DEFAULT;
                    755: static size_t  opt_chunk_2pow = CHUNK_2POW_DEFAULT;
                    756: static bool    opt_utrace = false;
                    757: static bool    opt_sysv = false;
                    758: static bool    opt_xmalloc = false;
                    759: static bool    opt_zero = false;
                    760: static int32_t opt_narenas_lshift = 0;
                    761:
                    762: typedef struct {
                    763:        void    *p;
                    764:        size_t  s;
                    765:        void    *r;
                    766: } malloc_utrace_t;
                    767:
                    768: #define        UTRACE(a, b, c)                                                 \
                    769:        if (opt_utrace) {                                               \
1.2       ad        770:                malloc_utrace_t ut;                                     \
                    771:                ut.p = a;                                               \
                    772:                ut.s = b;                                               \
                    773:                ut.r = c;                                               \
                    774:                xutrace(&ut, sizeof(ut));                               \
1.1       ad        775:        }
                    776:
                    777: /******************************************************************************/
                    778: /*
                    779:  * Begin function prototypes for non-inline static functions.
                    780:  */
                    781:
                    782: static void    wrtmessage(const char *p1, const char *p2, const char *p3,
                    783:                const char *p4);
                    784: #ifdef MALLOC_STATS
                    785: static void    malloc_printf(const char *format, ...);
                    786: #endif
                    787: static char    *umax2s(uintmax_t x, char *s);
                    788: static bool    base_pages_alloc(size_t minsize);
                    789: static void    *base_alloc(size_t size);
                    790: static chunk_node_t *base_chunk_node_alloc(void);
                    791: static void    base_chunk_node_dealloc(chunk_node_t *node);
                    792: #ifdef MALLOC_STATS
                    793: static void    stats_print(arena_t *arena);
                    794: #endif
                    795: static void    *pages_map(void *addr, size_t size);
                    796: static void    pages_unmap(void *addr, size_t size);
                    797: static void    *chunk_alloc(size_t size);
                    798: static void    chunk_dealloc(void *chunk, size_t size);
                    799: static arena_t *choose_arena_hard(void);
                    800: static void    arena_run_split(arena_t *arena, arena_run_t *run, size_t size);
                    801: static arena_chunk_t *arena_chunk_alloc(arena_t *arena);
                    802: static void    arena_chunk_dealloc(arena_t *arena, arena_chunk_t *chunk);
                    803: static arena_run_t *arena_run_alloc(arena_t *arena, size_t size);
                    804: static void    arena_run_dalloc(arena_t *arena, arena_run_t *run, size_t size);
                    805: static arena_run_t *arena_bin_nonfull_run_get(arena_t *arena, arena_bin_t *bin);
                    806: static void *arena_bin_malloc_hard(arena_t *arena, arena_bin_t *bin);
                    807: static size_t arena_bin_run_size_calc(arena_bin_t *bin, size_t min_run_size);
                    808: static void    *arena_malloc(arena_t *arena, size_t size);
                    809: static void    *arena_palloc(arena_t *arena, size_t alignment, size_t size,
                    810:     size_t alloc_size);
                    811: static size_t  arena_salloc(const void *ptr);
                    812: static void    *arena_ralloc(void *ptr, size_t size, size_t oldsize);
                    813: static void    arena_dalloc(arena_t *arena, arena_chunk_t *chunk, void *ptr);
                    814: static bool    arena_new(arena_t *arena);
                    815: static arena_t *arenas_extend(unsigned ind);
                    816: static void    *huge_malloc(size_t size);
                    817: static void    *huge_palloc(size_t alignment, size_t size);
                    818: static void    *huge_ralloc(void *ptr, size_t size, size_t oldsize);
                    819: static void    huge_dalloc(void *ptr);
                    820: static void    *imalloc(size_t size);
                    821: static void    *ipalloc(size_t alignment, size_t size);
                    822: static void    *icalloc(size_t size);
                    823: static size_t  isalloc(const void *ptr);
                    824: static void    *iralloc(void *ptr, size_t size);
                    825: static void    idalloc(void *ptr);
                    826: static void    malloc_print_stats(void);
                    827: static bool    malloc_init_hard(void);
                    828:
                    829: /*
                    830:  * End function prototypes.
                    831:  */
                    832: /******************************************************************************/
                    833: /*
                    834:  * Begin mutex.
                    835:  */
                    836:
1.2       ad        837: #ifdef __NetBSD__
                    838: #define        malloc_mutex_init(m)    mutex_init(m, NULL)
                    839: #define        malloc_mutex_lock(m)    mutex_lock(m)
                    840: #define        malloc_mutex_unlock(m)  mutex_unlock(m)
                    841: #else  /* __NetBSD__ */
                    842: static inline void
1.1       ad        843: malloc_mutex_init(malloc_mutex_t *a_mutex)
                    844: {
                    845:        static const spinlock_t lock = _SPINLOCK_INITIALIZER;
                    846:
                    847:        a_mutex->lock = lock;
                    848: }
                    849:
                    850: static inline void
                    851: malloc_mutex_lock(malloc_mutex_t *a_mutex)
                    852: {
                    853:
                    854:        if (__isthreaded)
                    855:                _SPINLOCK(&a_mutex->lock);
                    856: }
                    857:
                    858: static inline void
                    859: malloc_mutex_unlock(malloc_mutex_t *a_mutex)
                    860: {
                    861:
                    862:        if (__isthreaded)
                    863:                _SPINUNLOCK(&a_mutex->lock);
                    864: }
1.2       ad        865: #endif /* __NetBSD__ */
1.1       ad        866:
                    867: /*
                    868:  * End mutex.
                    869:  */
                    870: /******************************************************************************/
                    871: /*
                    872:  * Begin Utility functions/macros.
                    873:  */
                    874:
                    875: /* Return the chunk address for allocation address a. */
                    876: #define        CHUNK_ADDR2BASE(a)                                              \
                    877:        ((void *)((uintptr_t)(a) & ~chunksize_mask))
                    878:
                    879: /* Return the chunk offset of address a. */
                    880: #define        CHUNK_ADDR2OFFSET(a)                                            \
                    881:        ((size_t)((uintptr_t)(a) & chunksize_mask))
                    882:
                    883: /* Return the smallest chunk multiple that is >= s. */
                    884: #define        CHUNK_CEILING(s)                                                \
                    885:        (((s) + chunksize_mask) & ~chunksize_mask)
                    886:
                    887: /* Return the smallest cacheline multiple that is >= s. */
                    888: #define        CACHELINE_CEILING(s)                                            \
                    889:        (((s) + (CACHELINE - 1)) & ~(CACHELINE - 1))
                    890:
                    891: /* Return the smallest quantum multiple that is >= a. */
                    892: #define        QUANTUM_CEILING(a)                                              \
                    893:        (((a) + quantum_mask) & ~quantum_mask)
                    894:
                    895: /* Return the smallest pagesize multiple that is >= s. */
                    896: #define        PAGE_CEILING(s)                                                 \
                    897:        (((s) + pagesize_mask) & ~pagesize_mask)
                    898:
                    899: /* Compute the smallest power of 2 that is >= x. */
                    900: static inline size_t
                    901: pow2_ceil(size_t x)
                    902: {
                    903:
                    904:        x--;
                    905:        x |= x >> 1;
                    906:        x |= x >> 2;
                    907:        x |= x >> 4;
                    908:        x |= x >> 8;
                    909:        x |= x >> 16;
                    910: #if (SIZEOF_PTR == 8)
                    911:        x |= x >> 32;
                    912: #endif
                    913:        x++;
                    914:        return (x);
                    915: }
                    916:
                    917: static void
                    918: wrtmessage(const char *p1, const char *p2, const char *p3, const char *p4)
                    919: {
                    920:
                    921:        _write(STDERR_FILENO, p1, strlen(p1));
                    922:        _write(STDERR_FILENO, p2, strlen(p2));
                    923:        _write(STDERR_FILENO, p3, strlen(p3));
                    924:        _write(STDERR_FILENO, p4, strlen(p4));
                    925: }
                    926:
                    927: void   (*_malloc_message)(const char *p1, const char *p2, const char *p3,
                    928:            const char *p4) = wrtmessage;
                    929:
                    930: #ifdef MALLOC_STATS
                    931: /*
                    932:  * Print to stderr in such a way as to (hopefully) avoid memory allocation.
                    933:  */
                    934: static void
                    935: malloc_printf(const char *format, ...)
                    936: {
                    937:        char buf[4096];
                    938:        va_list ap;
                    939:
                    940:        va_start(ap, format);
                    941:        vsnprintf(buf, sizeof(buf), format, ap);
                    942:        va_end(ap);
                    943:        _malloc_message(buf, "", "", "");
                    944: }
                    945: #endif
                    946:
                    947: /*
                    948:  * We don't want to depend on vsnprintf() for production builds, since that can
                    949:  * cause unnecessary bloat for static binaries.  umax2s() provides minimal
                    950:  * integer printing functionality, so that malloc_printf() use can be limited to
                    951:  * MALLOC_STATS code.
                    952:  */
                    953: #define UMAX2S_BUFSIZE 21
                    954: static char *
                    955: umax2s(uintmax_t x, char *s)
                    956: {
                    957:        unsigned i;
                    958:
                    959:        /* Make sure UMAX2S_BUFSIZE is large enough. */
                    960:        assert(sizeof(uintmax_t) <= 8);
                    961:
                    962:        i = UMAX2S_BUFSIZE - 1;
                    963:        s[i] = '\0';
                    964:        do {
                    965:                i--;
1.2       ad        966:                s[i] = "0123456789"[(int)x % 10];
                    967:                x /= (uintmax_t)10LL;
1.1       ad        968:        } while (x > 0);
                    969:
                    970:        return (&s[i]);
                    971: }
                    972:
                    973: /******************************************************************************/
                    974:
                    975: static bool
                    976: base_pages_alloc(size_t minsize)
                    977: {
1.2       ad        978:        size_t csize = 0;
1.1       ad        979:
                    980: #ifdef USE_BRK
                    981:        /*
                    982:         * Do special brk allocation here, since base allocations don't need to
                    983:         * be chunk-aligned.
                    984:         */
                    985:        if (brk_prev != (void *)-1) {
                    986:                void *brk_cur;
                    987:                intptr_t incr;
                    988:
                    989:                if (minsize != 0)
                    990:                        csize = CHUNK_CEILING(minsize);
                    991:
                    992:                malloc_mutex_lock(&brk_mtx);
                    993:                do {
                    994:                        /* Get the current end of brk. */
                    995:                        brk_cur = sbrk(0);
                    996:
                    997:                        /*
                    998:                         * Calculate how much padding is necessary to
                    999:                         * chunk-align the end of brk.  Don't worry about
                   1000:                         * brk_cur not being chunk-aligned though.
                   1001:                         */
                   1002:                        incr = (intptr_t)chunksize
                   1003:                            - (intptr_t)CHUNK_ADDR2OFFSET(brk_cur);
                   1004:                        if (incr < minsize)
                   1005:                                incr += csize;
                   1006:
                   1007:                        brk_prev = sbrk(incr);
                   1008:                        if (brk_prev == brk_cur) {
                   1009:                                /* Success. */
                   1010:                                malloc_mutex_unlock(&brk_mtx);
                   1011:                                base_pages = brk_cur;
                   1012:                                base_next_addr = base_pages;
                   1013:                                base_past_addr = (void *)((uintptr_t)base_pages
                   1014:                                    + incr);
                   1015: #ifdef MALLOC_STATS
                   1016:                                base_mapped += incr;
                   1017: #endif
                   1018:                                return (false);
                   1019:                        }
                   1020:                } while (brk_prev != (void *)-1);
                   1021:                malloc_mutex_unlock(&brk_mtx);
                   1022:        }
                   1023:        if (minsize == 0) {
                   1024:                /*
                   1025:                 * Failure during initialization doesn't matter, so avoid
                   1026:                 * falling through to the mmap-based page mapping code.
                   1027:                 */
                   1028:                return (true);
                   1029:        }
                   1030: #endif
                   1031:        assert(minsize != 0);
                   1032:        csize = PAGE_CEILING(minsize);
                   1033:        base_pages = pages_map(NULL, csize);
                   1034:        if (base_pages == NULL)
                   1035:                return (true);
                   1036:        base_next_addr = base_pages;
                   1037:        base_past_addr = (void *)((uintptr_t)base_pages + csize);
                   1038: #ifdef MALLOC_STATS
                   1039:        base_mapped += csize;
                   1040: #endif
                   1041:        return (false);
                   1042: }
                   1043:
                   1044: static void *
                   1045: base_alloc(size_t size)
                   1046: {
                   1047:        void *ret;
                   1048:        size_t csize;
                   1049:
                   1050:        /* Round size up to nearest multiple of the cacheline size. */
                   1051:        csize = CACHELINE_CEILING(size);
                   1052:
                   1053:        malloc_mutex_lock(&base_mtx);
                   1054:
                   1055:        /* Make sure there's enough space for the allocation. */
                   1056:        if ((uintptr_t)base_next_addr + csize > (uintptr_t)base_past_addr) {
                   1057:                if (base_pages_alloc(csize)) {
                   1058:                        ret = NULL;
                   1059:                        goto RETURN;
                   1060:                }
                   1061:        }
                   1062:
                   1063:        /* Allocate. */
                   1064:        ret = base_next_addr;
                   1065:        base_next_addr = (void *)((uintptr_t)base_next_addr + csize);
                   1066:
                   1067: RETURN:
                   1068:        malloc_mutex_unlock(&base_mtx);
                   1069:        return (ret);
                   1070: }
                   1071:
                   1072: static chunk_node_t *
                   1073: base_chunk_node_alloc(void)
                   1074: {
                   1075:        chunk_node_t *ret;
                   1076:
                   1077:        malloc_mutex_lock(&base_mtx);
                   1078:        if (base_chunk_nodes != NULL) {
                   1079:                ret = base_chunk_nodes;
1.2       ad       1080:                /* LINTED */
1.1       ad       1081:                base_chunk_nodes = *(chunk_node_t **)ret;
                   1082:                malloc_mutex_unlock(&base_mtx);
                   1083:        } else {
                   1084:                malloc_mutex_unlock(&base_mtx);
                   1085:                ret = (chunk_node_t *)base_alloc(sizeof(chunk_node_t));
                   1086:        }
                   1087:
                   1088:        return (ret);
                   1089: }
                   1090:
                   1091: static void
                   1092: base_chunk_node_dealloc(chunk_node_t *node)
                   1093: {
                   1094:
                   1095:        malloc_mutex_lock(&base_mtx);
1.2       ad       1096:        /* LINTED */
1.1       ad       1097:        *(chunk_node_t **)node = base_chunk_nodes;
                   1098:        base_chunk_nodes = node;
                   1099:        malloc_mutex_unlock(&base_mtx);
                   1100: }
                   1101:
                   1102: /******************************************************************************/
                   1103:
                   1104: #ifdef MALLOC_STATS
                   1105: static void
                   1106: stats_print(arena_t *arena)
                   1107: {
                   1108:        unsigned i;
                   1109:        int gap_start;
                   1110:
                   1111:        malloc_printf(
                   1112:            "          allocated/mapped            nmalloc      ndalloc\n");
1.2       ad       1113:
                   1114:        malloc_printf("small: %12zu %-12s %12llu %12llu\n",
1.1       ad       1115:            arena->stats.allocated_small, "", arena->stats.nmalloc_small,
                   1116:            arena->stats.ndalloc_small);
1.2       ad       1117:        malloc_printf("large: %12zu %-12s %12llu %12llu\n",
1.1       ad       1118:            arena->stats.allocated_large, "", arena->stats.nmalloc_large,
                   1119:            arena->stats.ndalloc_large);
1.2       ad       1120:        malloc_printf("total: %12zu/%-12zu %12llu %12llu\n",
1.1       ad       1121:            arena->stats.allocated_small + arena->stats.allocated_large,
                   1122:            arena->stats.mapped,
                   1123:            arena->stats.nmalloc_small + arena->stats.nmalloc_large,
                   1124:            arena->stats.ndalloc_small + arena->stats.ndalloc_large);
                   1125:
                   1126:        malloc_printf("bins:     bin   size regs pgs  requests   newruns"
                   1127:            "    reruns maxruns curruns\n");
                   1128:        for (i = 0, gap_start = -1; i < ntbins + nqbins + nsbins; i++) {
                   1129:                if (arena->bins[i].stats.nrequests == 0) {
                   1130:                        if (gap_start == -1)
                   1131:                                gap_start = i;
                   1132:                } else {
                   1133:                        if (gap_start != -1) {
                   1134:                                if (i > gap_start + 1) {
                   1135:                                        /* Gap of more than one size class. */
                   1136:                                        malloc_printf("[%u..%u]\n",
                   1137:                                            gap_start, i - 1);
                   1138:                                } else {
                   1139:                                        /* Gap of one size class. */
                   1140:                                        malloc_printf("[%u]\n", gap_start);
                   1141:                                }
                   1142:                                gap_start = -1;
                   1143:                        }
                   1144:                        malloc_printf(
                   1145:                            "%13u %1s %4u %4u %3u %9llu %9llu"
                   1146:                            " %9llu %7lu %7lu\n",
                   1147:                            i,
                   1148:                            i < ntbins ? "T" : i < ntbins + nqbins ? "Q" : "S",
                   1149:                            arena->bins[i].reg_size,
                   1150:                            arena->bins[i].nregs,
                   1151:                            arena->bins[i].run_size >> pagesize_2pow,
                   1152:                            arena->bins[i].stats.nrequests,
                   1153:                            arena->bins[i].stats.nruns,
                   1154:                            arena->bins[i].stats.reruns,
                   1155:                            arena->bins[i].stats.highruns,
                   1156:                            arena->bins[i].stats.curruns);
                   1157:                }
                   1158:        }
                   1159:        if (gap_start != -1) {
                   1160:                if (i > gap_start + 1) {
                   1161:                        /* Gap of more than one size class. */
                   1162:                        malloc_printf("[%u..%u]\n", gap_start, i - 1);
                   1163:                } else {
                   1164:                        /* Gap of one size class. */
                   1165:                        malloc_printf("[%u]\n", gap_start);
                   1166:                }
                   1167:        }
                   1168: }
                   1169: #endif
                   1170:
                   1171: /*
                   1172:  * End Utility functions/macros.
                   1173:  */
                   1174: /******************************************************************************/
                   1175: /*
                   1176:  * Begin chunk management functions.
                   1177:  */
                   1178:
                   1179: static inline int
                   1180: chunk_comp(chunk_node_t *a, chunk_node_t *b)
                   1181: {
                   1182:
                   1183:        assert(a != NULL);
                   1184:        assert(b != NULL);
                   1185:
                   1186:        if ((uintptr_t)a->chunk < (uintptr_t)b->chunk)
                   1187:                return (-1);
                   1188:        else if (a->chunk == b->chunk)
                   1189:                return (0);
                   1190:        else
                   1191:                return (1);
                   1192: }
                   1193:
                   1194: /* Generate red-black tree code for chunks. */
1.2       ad       1195: #ifndef lint
1.1       ad       1196: RB_GENERATE_STATIC(chunk_tree_s, chunk_node_s, link, chunk_comp);
1.2       ad       1197: #endif
1.1       ad       1198:
                   1199: static void *
                   1200: pages_map(void *addr, size_t size)
                   1201: {
                   1202:        void *ret;
                   1203:
                   1204:        /*
                   1205:         * We don't use MAP_FIXED here, because it can cause the *replacement*
                   1206:         * of existing mappings, and we only want to create new mappings.
                   1207:         */
                   1208:        ret = mmap(addr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON,
                   1209:            -1, 0);
                   1210:        assert(ret != NULL);
                   1211:
                   1212:        if (ret == MAP_FAILED)
                   1213:                ret = NULL;
                   1214:        else if (addr != NULL && ret != addr) {
                   1215:                /*
                   1216:                 * We succeeded in mapping memory, but not in the right place.
                   1217:                 */
                   1218:                if (munmap(ret, size) == -1) {
                   1219:                        char buf[STRERROR_BUF];
                   1220:
                   1221:                        strerror_r(errno, buf, sizeof(buf));
                   1222:                        _malloc_message(_getprogname(),
                   1223:                            ": (malloc) Error in munmap(): ", buf, "\n");
                   1224:                        if (opt_abort)
                   1225:                                abort();
                   1226:                }
                   1227:                ret = NULL;
                   1228:        }
                   1229:
                   1230:        assert(ret == NULL || (addr == NULL && ret != addr)
                   1231:            || (addr != NULL && ret == addr));
                   1232:        return (ret);
                   1233: }
                   1234:
                   1235: static void
                   1236: pages_unmap(void *addr, size_t size)
                   1237: {
                   1238:
                   1239:        if (munmap(addr, size) == -1) {
                   1240:                char buf[STRERROR_BUF];
                   1241:
                   1242:                strerror_r(errno, buf, sizeof(buf));
                   1243:                _malloc_message(_getprogname(),
                   1244:                    ": (malloc) Error in munmap(): ", buf, "\n");
                   1245:                if (opt_abort)
                   1246:                        abort();
                   1247:        }
                   1248: }
                   1249:
                   1250: static void *
                   1251: chunk_alloc(size_t size)
                   1252: {
                   1253:        void *ret, *chunk;
                   1254:        chunk_node_t *tchunk, *delchunk;
                   1255:
                   1256:        assert(size != 0);
                   1257:        assert((size & chunksize_mask) == 0);
                   1258:
                   1259:        malloc_mutex_lock(&chunks_mtx);
                   1260:
                   1261:        if (size == chunksize) {
                   1262:                /*
                   1263:                 * Check for address ranges that were previously chunks and try
                   1264:                 * to use them.
                   1265:                 */
                   1266:
1.2       ad       1267:                /* LINTED */
1.1       ad       1268:                tchunk = RB_MIN(chunk_tree_s, &old_chunks);
                   1269:                while (tchunk != NULL) {
                   1270:                        /* Found an address range.  Try to recycle it. */
                   1271:
                   1272:                        chunk = tchunk->chunk;
                   1273:                        delchunk = tchunk;
1.2       ad       1274:                        /* LINTED */
1.1       ad       1275:                        tchunk = RB_NEXT(chunk_tree_s, &old_chunks, delchunk);
                   1276:
                   1277:                        /* Remove delchunk from the tree. */
1.2       ad       1278:                        /* LINTED */
1.1       ad       1279:                        RB_REMOVE(chunk_tree_s, &old_chunks, delchunk);
                   1280:                        base_chunk_node_dealloc(delchunk);
                   1281:
                   1282: #ifdef USE_BRK
                   1283:                        if ((uintptr_t)chunk >= (uintptr_t)brk_base
                   1284:                            && (uintptr_t)chunk < (uintptr_t)brk_max) {
                   1285:                                /* Re-use a previously freed brk chunk. */
                   1286:                                ret = chunk;
                   1287:                                goto RETURN;
                   1288:                        }
                   1289: #endif
                   1290:                        if ((ret = pages_map(chunk, size)) != NULL) {
                   1291:                                /* Success. */
                   1292:                                goto RETURN;
                   1293:                        }
                   1294:                }
                   1295:        }
                   1296:
                   1297:        /*
                   1298:         * Try to over-allocate, but allow the OS to place the allocation
                   1299:         * anywhere.  Beware of size_t wrap-around.
                   1300:         */
                   1301:        if (size + chunksize > size) {
                   1302:                if ((ret = pages_map(NULL, size + chunksize)) != NULL) {
                   1303:                        size_t offset = CHUNK_ADDR2OFFSET(ret);
                   1304:
                   1305:                        /*
                   1306:                         * Success.  Clean up unneeded leading/trailing space.
                   1307:                         */
                   1308:                        if (offset != 0) {
                   1309:                                /* Leading space. */
                   1310:                                pages_unmap(ret, chunksize - offset);
                   1311:
                   1312:                                ret = (void *)((uintptr_t)ret + (chunksize -
                   1313:                                    offset));
                   1314:
                   1315:                                /* Trailing space. */
                   1316:                                pages_unmap((void *)((uintptr_t)ret + size),
                   1317:                                    offset);
                   1318:                        } else {
                   1319:                                /* Trailing space only. */
                   1320:                                pages_unmap((void *)((uintptr_t)ret + size),
                   1321:                                    chunksize);
                   1322:                        }
                   1323:                        goto RETURN;
                   1324:                }
                   1325:        }
                   1326:
                   1327: #ifdef USE_BRK
                   1328:        /*
                   1329:         * Try to create allocations in brk, in order to make full use of
                   1330:         * limited address space.
                   1331:         */
                   1332:        if (brk_prev != (void *)-1) {
                   1333:                void *brk_cur;
                   1334:                intptr_t incr;
                   1335:
                   1336:                /*
                   1337:                 * The loop is necessary to recover from races with other
                   1338:                 * threads that are using brk for something other than malloc.
                   1339:                 */
                   1340:                malloc_mutex_lock(&brk_mtx);
                   1341:                do {
                   1342:                        /* Get the current end of brk. */
                   1343:                        brk_cur = sbrk(0);
                   1344:
                   1345:                        /*
                   1346:                         * Calculate how much padding is necessary to
                   1347:                         * chunk-align the end of brk.
                   1348:                         */
                   1349:                        incr = (intptr_t)size
                   1350:                            - (intptr_t)CHUNK_ADDR2OFFSET(brk_cur);
                   1351:                        if (incr == size) {
                   1352:                                ret = brk_cur;
                   1353:                        } else {
                   1354:                                ret = (void *)((intptr_t)brk_cur + incr);
                   1355:                                incr += size;
                   1356:                        }
                   1357:
                   1358:                        brk_prev = sbrk(incr);
                   1359:                        if (brk_prev == brk_cur) {
                   1360:                                /* Success. */
                   1361:                                malloc_mutex_unlock(&brk_mtx);
                   1362:                                brk_max = (void *)((intptr_t)ret + size);
                   1363:                                goto RETURN;
                   1364:                        }
                   1365:                } while (brk_prev != (void *)-1);
                   1366:                malloc_mutex_unlock(&brk_mtx);
                   1367:        }
                   1368: #endif
                   1369:
                   1370:        /* All strategies for allocation failed. */
                   1371:        ret = NULL;
                   1372: RETURN:
                   1373:        if (ret != NULL) {
                   1374:                chunk_node_t key;
                   1375:                /*
                   1376:                 * Clean out any entries in old_chunks that overlap with the
                   1377:                 * memory we just allocated.
                   1378:                 */
                   1379:                key.chunk = ret;
1.2       ad       1380:                /* LINTED */
1.1       ad       1381:                tchunk = RB_NFIND(chunk_tree_s, &old_chunks, &key);
                   1382:                while (tchunk != NULL
                   1383:                    && (uintptr_t)tchunk->chunk >= (uintptr_t)ret
                   1384:                    && (uintptr_t)tchunk->chunk < (uintptr_t)ret + size) {
                   1385:                        delchunk = tchunk;
1.2       ad       1386:                        /* LINTED */
1.1       ad       1387:                        tchunk = RB_NEXT(chunk_tree_s, &old_chunks, delchunk);
1.2       ad       1388:                        /* LINTED */
1.1       ad       1389:                        RB_REMOVE(chunk_tree_s, &old_chunks, delchunk);
                   1390:                        base_chunk_node_dealloc(delchunk);
                   1391:                }
                   1392:
                   1393:        }
                   1394: #ifdef MALLOC_STATS
                   1395:        if (ret != NULL) {
                   1396:                stats_chunks.nchunks += (size / chunksize);
                   1397:                stats_chunks.curchunks += (size / chunksize);
                   1398:        }
                   1399:        if (stats_chunks.curchunks > stats_chunks.highchunks)
                   1400:                stats_chunks.highchunks = stats_chunks.curchunks;
                   1401: #endif
                   1402:        malloc_mutex_unlock(&chunks_mtx);
                   1403:
                   1404:        assert(CHUNK_ADDR2BASE(ret) == ret);
                   1405:        return (ret);
                   1406: }
                   1407:
                   1408: static void
                   1409: chunk_dealloc(void *chunk, size_t size)
                   1410: {
                   1411:        chunk_node_t *node;
                   1412:
                   1413:        assert(chunk != NULL);
                   1414:        assert(CHUNK_ADDR2BASE(chunk) == chunk);
                   1415:        assert(size != 0);
                   1416:        assert((size & chunksize_mask) == 0);
                   1417:
                   1418:        malloc_mutex_lock(&chunks_mtx);
                   1419:
                   1420: #ifdef USE_BRK
                   1421:        if ((uintptr_t)chunk >= (uintptr_t)brk_base
                   1422:            && (uintptr_t)chunk < (uintptr_t)brk_max) {
                   1423:                void *brk_cur;
                   1424:
                   1425:                malloc_mutex_lock(&brk_mtx);
                   1426:                /* Get the current end of brk. */
                   1427:                brk_cur = sbrk(0);
                   1428:
                   1429:                /*
                   1430:                 * Try to shrink the data segment if this chunk is at the end
                   1431:                 * of the data segment.  The sbrk() call here is subject to a
                   1432:                 * race condition with threads that use brk(2) or sbrk(2)
                   1433:                 * directly, but the alternative would be to leak memory for
                   1434:                 * the sake of poorly designed multi-threaded programs.
                   1435:                 */
                   1436:                if (brk_cur == brk_max
                   1437:                    && (void *)((uintptr_t)chunk + size) == brk_max
                   1438:                    && sbrk(-(intptr_t)size) == brk_max) {
                   1439:                        malloc_mutex_unlock(&brk_mtx);
                   1440:                        if (brk_prev == brk_max) {
                   1441:                                /* Success. */
                   1442:                                brk_prev = (void *)((intptr_t)brk_max
                   1443:                                    - (intptr_t)size);
                   1444:                                brk_max = brk_prev;
                   1445:                        }
                   1446:                } else {
                   1447:                        size_t offset;
                   1448:
                   1449:                        malloc_mutex_unlock(&brk_mtx);
                   1450:                        madvise(chunk, size, MADV_FREE);
                   1451:
                   1452:                        /*
                   1453:                         * Iteratively create records of each chunk-sized
                   1454:                         * memory region that 'chunk' is comprised of, so that
                   1455:                         * the address range can be recycled if memory usage
                   1456:                         * increases later on.
                   1457:                         */
                   1458:                        for (offset = 0; offset < size; offset += chunksize) {
                   1459:                                node = base_chunk_node_alloc();
                   1460:                                if (node == NULL)
                   1461:                                        break;
                   1462:
                   1463:                                node->chunk = (void *)((uintptr_t)chunk
                   1464:                                    + (uintptr_t)offset);
                   1465:                                node->size = chunksize;
1.2       ad       1466:                                /* LINTED */
1.1       ad       1467:                                RB_INSERT(chunk_tree_s, &old_chunks, node);
                   1468:                        }
                   1469:                }
                   1470:        } else {
                   1471: #endif
                   1472:                pages_unmap(chunk, size);
                   1473:
                   1474:                /*
                   1475:                 * Make a record of the chunk's address, so that the address
                   1476:                 * range can be recycled if memory usage increases later on.
                   1477:                 * Don't bother to create entries if (size > chunksize), since
                   1478:                 * doing so could cause scalability issues for truly gargantuan
                   1479:                 * objects (many gigabytes or larger).
                   1480:                 */
                   1481:                if (size == chunksize) {
                   1482:                        node = base_chunk_node_alloc();
                   1483:                        if (node != NULL) {
                   1484:                                node->chunk = (void *)(uintptr_t)chunk;
                   1485:                                node->size = chunksize;
1.2       ad       1486:                                /* LINTED */
1.1       ad       1487:                                RB_INSERT(chunk_tree_s, &old_chunks, node);
                   1488:                        }
                   1489:                }
                   1490: #ifdef USE_BRK
                   1491:        }
                   1492: #endif
                   1493:
                   1494: #ifdef MALLOC_STATS
                   1495:        stats_chunks.curchunks -= (size / chunksize);
                   1496: #endif
                   1497:        malloc_mutex_unlock(&chunks_mtx);
                   1498: }
                   1499:
                   1500: /*
                   1501:  * End chunk management functions.
                   1502:  */
                   1503: /******************************************************************************/
                   1504: /*
                   1505:  * Begin arena.
                   1506:  */
                   1507:
                   1508: /*
                   1509:  * Choose an arena based on a per-thread value (fast-path code, calls slow-path
                   1510:  * code if necessary).
                   1511:  */
                   1512: static inline arena_t *
                   1513: choose_arena(void)
                   1514: {
                   1515:        arena_t *ret;
                   1516:
                   1517:        /*
                   1518:         * We can only use TLS if this is a PIC library, since for the static
                   1519:         * library version, libc's malloc is used by TLS allocation, which
                   1520:         * introduces a bootstrapping issue.
                   1521:         */
                   1522:        if (__isthreaded == false) {
                   1523:            /*
                   1524:             * Avoid the overhead of TLS for single-threaded operation.  If the
                   1525:             * app switches to threaded mode, the initial thread may end up
                   1526:             * being assigned to some other arena, but this one-time switch
                   1527:             * shouldn't cause significant issues.
                   1528:             */
                   1529:            return (arenas[0]);
                   1530:        }
                   1531:
1.2       ad       1532:        ret = get_arenas_map();
1.1       ad       1533:        if (ret == NULL)
                   1534:                ret = choose_arena_hard();
                   1535:
                   1536:        assert(ret != NULL);
                   1537:        return (ret);
                   1538: }
                   1539:
                   1540: /*
                   1541:  * Choose an arena based on a per-thread value (slow-path code only, called
                   1542:  * only by choose_arena()).
                   1543:  */
                   1544: static arena_t *
                   1545: choose_arena_hard(void)
                   1546: {
                   1547:        arena_t *ret;
                   1548:
                   1549:        assert(__isthreaded);
                   1550:
                   1551:        /* Assign one of the arenas to this thread, in a round-robin fashion. */
                   1552:        malloc_mutex_lock(&arenas_mtx);
                   1553:        ret = arenas[next_arena];
                   1554:        if (ret == NULL)
                   1555:                ret = arenas_extend(next_arena);
                   1556:        if (ret == NULL) {
                   1557:                /*
                   1558:                 * Make sure that this function never returns NULL, so that
                   1559:                 * choose_arena() doesn't have to check for a NULL return
                   1560:                 * value.
                   1561:                 */
                   1562:                ret = arenas[0];
                   1563:        }
                   1564:        next_arena = (next_arena + 1) % narenas;
                   1565:        malloc_mutex_unlock(&arenas_mtx);
1.2       ad       1566:        set_arenas_map(ret);
1.1       ad       1567:
                   1568:        return (ret);
                   1569: }
                   1570:
                   1571: static inline int
                   1572: arena_chunk_comp(arena_chunk_t *a, arena_chunk_t *b)
                   1573: {
                   1574:
                   1575:        assert(a != NULL);
                   1576:        assert(b != NULL);
                   1577:
                   1578:        if ((uintptr_t)a < (uintptr_t)b)
                   1579:                return (-1);
                   1580:        else if (a == b)
                   1581:                return (0);
                   1582:        else
                   1583:                return (1);
                   1584: }
                   1585:
                   1586: /* Generate red-black tree code for arena chunks. */
1.2       ad       1587: #ifndef lint
1.1       ad       1588: RB_GENERATE_STATIC(arena_chunk_tree_s, arena_chunk_s, link, arena_chunk_comp);
1.2       ad       1589: #endif
1.1       ad       1590:
                   1591: static inline int
                   1592: arena_run_comp(arena_run_t *a, arena_run_t *b)
                   1593: {
                   1594:
                   1595:        assert(a != NULL);
                   1596:        assert(b != NULL);
                   1597:
                   1598:        if ((uintptr_t)a < (uintptr_t)b)
                   1599:                return (-1);
                   1600:        else if (a == b)
                   1601:                return (0);
                   1602:        else
                   1603:                return (1);
                   1604: }
                   1605:
                   1606: /* Generate red-black tree code for arena runs. */
1.2       ad       1607: #ifndef lint
1.1       ad       1608: RB_GENERATE_STATIC(arena_run_tree_s, arena_run_s, link, arena_run_comp);
1.2       ad       1609: #endif
1.1       ad       1610:
                   1611: static inline void *
                   1612: arena_run_reg_alloc(arena_run_t *run, arena_bin_t *bin)
                   1613: {
                   1614:        void *ret;
                   1615:        unsigned i, mask, bit, regind;
                   1616:
                   1617:        assert(run->magic == ARENA_RUN_MAGIC);
                   1618:        assert(run->regs_minelm < bin->regs_mask_nelms);
                   1619:
                   1620:        /*
                   1621:         * Move the first check outside the loop, so that run->regs_minelm can
                   1622:         * be updated unconditionally, without the possibility of updating it
                   1623:         * multiple times.
                   1624:         */
                   1625:        i = run->regs_minelm;
                   1626:        mask = run->regs_mask[i];
                   1627:        if (mask != 0) {
                   1628:                /* Usable allocation found. */
                   1629:                bit = ffs((int)mask) - 1;
                   1630:
                   1631:                regind = ((i << (SIZEOF_INT_2POW + 3)) + bit);
                   1632:                ret = (void *)(((uintptr_t)run) + bin->reg0_offset
                   1633:                    + (bin->reg_size * regind));
                   1634:
                   1635:                /* Clear bit. */
                   1636:                mask ^= (1 << bit);
                   1637:                run->regs_mask[i] = mask;
                   1638:
                   1639:                return (ret);
                   1640:        }
                   1641:
                   1642:        for (i++; i < bin->regs_mask_nelms; i++) {
                   1643:                mask = run->regs_mask[i];
                   1644:                if (mask != 0) {
                   1645:                        /* Usable allocation found. */
                   1646:                        bit = ffs((int)mask) - 1;
                   1647:
                   1648:                        regind = ((i << (SIZEOF_INT_2POW + 3)) + bit);
                   1649:                        ret = (void *)(((uintptr_t)run) + bin->reg0_offset
                   1650:                            + (bin->reg_size * regind));
                   1651:
                   1652:                        /* Clear bit. */
                   1653:                        mask ^= (1 << bit);
                   1654:                        run->regs_mask[i] = mask;
                   1655:
                   1656:                        /*
                   1657:                         * Make a note that nothing before this element
                   1658:                         * contains a free region.
                   1659:                         */
                   1660:                        run->regs_minelm = i; /* Low payoff: + (mask == 0); */
                   1661:
                   1662:                        return (ret);
                   1663:                }
                   1664:        }
                   1665:        /* Not reached. */
                   1666:        assert(0);
                   1667:        return (NULL);
                   1668: }
                   1669:
                   1670: static inline void
                   1671: arena_run_reg_dalloc(arena_run_t *run, arena_bin_t *bin, void *ptr, size_t size)
                   1672: {
                   1673:        /*
                   1674:         * To divide by a number D that is not a power of two we multiply
                   1675:         * by (2^21 / D) and then right shift by 21 positions.
                   1676:         *
                   1677:         *   X / D
                   1678:         *
                   1679:         * becomes
                   1680:         *
                   1681:         *   (X * size_invs[(D >> QUANTUM_2POW_MIN) - 3]) >> SIZE_INV_SHIFT
                   1682:         */
                   1683: #define SIZE_INV_SHIFT 21
                   1684: #define SIZE_INV(s) (((1 << SIZE_INV_SHIFT) / (s << QUANTUM_2POW_MIN)) + 1)
                   1685:        static const unsigned size_invs[] = {
                   1686:            SIZE_INV(3),
                   1687:            SIZE_INV(4), SIZE_INV(5), SIZE_INV(6), SIZE_INV(7),
                   1688:            SIZE_INV(8), SIZE_INV(9), SIZE_INV(10), SIZE_INV(11),
                   1689:            SIZE_INV(12),SIZE_INV(13), SIZE_INV(14), SIZE_INV(15),
                   1690:            SIZE_INV(16),SIZE_INV(17), SIZE_INV(18), SIZE_INV(19),
                   1691:            SIZE_INV(20),SIZE_INV(21), SIZE_INV(22), SIZE_INV(23),
                   1692:            SIZE_INV(24),SIZE_INV(25), SIZE_INV(26), SIZE_INV(27),
                   1693:            SIZE_INV(28),SIZE_INV(29), SIZE_INV(30), SIZE_INV(31)
                   1694: #if (QUANTUM_2POW_MIN < 4)
                   1695:            ,
                   1696:            SIZE_INV(32), SIZE_INV(33), SIZE_INV(34), SIZE_INV(35),
                   1697:            SIZE_INV(36), SIZE_INV(37), SIZE_INV(38), SIZE_INV(39),
                   1698:            SIZE_INV(40), SIZE_INV(41), SIZE_INV(42), SIZE_INV(43),
                   1699:            SIZE_INV(44), SIZE_INV(45), SIZE_INV(46), SIZE_INV(47),
                   1700:            SIZE_INV(48), SIZE_INV(49), SIZE_INV(50), SIZE_INV(51),
                   1701:            SIZE_INV(52), SIZE_INV(53), SIZE_INV(54), SIZE_INV(55),
                   1702:            SIZE_INV(56), SIZE_INV(57), SIZE_INV(58), SIZE_INV(59),
                   1703:            SIZE_INV(60), SIZE_INV(61), SIZE_INV(62), SIZE_INV(63)
                   1704: #endif
                   1705:        };
                   1706:        unsigned diff, regind, elm, bit;
                   1707:
                   1708:        assert(run->magic == ARENA_RUN_MAGIC);
                   1709:        assert(((sizeof(size_invs)) / sizeof(unsigned)) + 3
                   1710:            >= (SMALL_MAX_DEFAULT >> QUANTUM_2POW_MIN));
                   1711:
                   1712:        /*
                   1713:         * Avoid doing division with a variable divisor if possible.  Using
                   1714:         * actual division here can reduce allocator throughput by over 20%!
                   1715:         */
                   1716:        diff = (unsigned)((uintptr_t)ptr - (uintptr_t)run - bin->reg0_offset);
                   1717:        if ((size & (size - 1)) == 0) {
                   1718:                /*
                   1719:                 * log2_table allows fast division of a power of two in the
                   1720:                 * [1..128] range.
                   1721:                 *
                   1722:                 * (x / divisor) becomes (x >> log2_table[divisor - 1]).
                   1723:                 */
                   1724:                static const unsigned char log2_table[] = {
                   1725:                    0, 1, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4,
                   1726:                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
                   1727:                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                   1728:                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6,
                   1729:                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                   1730:                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                   1731:                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                   1732:                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7
                   1733:                };
                   1734:
                   1735:                if (size <= 128)
                   1736:                        regind = (diff >> log2_table[size - 1]);
                   1737:                else if (size <= 32768)
                   1738:                        regind = diff >> (8 + log2_table[(size >> 8) - 1]);
                   1739:                else {
                   1740:                        /*
                   1741:                         * The page size is too large for us to use the lookup
                   1742:                         * table.  Use real division.
                   1743:                         */
                   1744:                        regind = diff / size;
                   1745:                }
                   1746:        } else if (size <= ((sizeof(size_invs) / sizeof(unsigned))
                   1747:            << QUANTUM_2POW_MIN) + 2) {
                   1748:                regind = size_invs[(size >> QUANTUM_2POW_MIN) - 3] * diff;
                   1749:                regind >>= SIZE_INV_SHIFT;
                   1750:        } else {
                   1751:                /*
                   1752:                 * size_invs isn't large enough to handle this size class, so
                   1753:                 * calculate regind using actual division.  This only happens
                   1754:                 * if the user increases small_max via the 'S' runtime
                   1755:                 * configuration option.
                   1756:                 */
                   1757:                regind = diff / size;
                   1758:        };
                   1759:        assert(diff == regind * size);
                   1760:        assert(regind < bin->nregs);
                   1761:
                   1762:        elm = regind >> (SIZEOF_INT_2POW + 3);
                   1763:        if (elm < run->regs_minelm)
                   1764:                run->regs_minelm = elm;
                   1765:        bit = regind - (elm << (SIZEOF_INT_2POW + 3));
                   1766:        assert((run->regs_mask[elm] & (1 << bit)) == 0);
                   1767:        run->regs_mask[elm] |= (1 << bit);
                   1768: #undef SIZE_INV
                   1769: #undef SIZE_INV_SHIFT
                   1770: }
                   1771:
                   1772: static void
                   1773: arena_run_split(arena_t *arena, arena_run_t *run, size_t size)
                   1774: {
                   1775:        arena_chunk_t *chunk;
                   1776:        unsigned run_ind, map_offset, total_pages, need_pages, rem_pages;
                   1777:        unsigned i;
                   1778:
                   1779:        chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(run);
                   1780:        run_ind = (unsigned)(((uintptr_t)run - (uintptr_t)chunk)
                   1781:            >> pagesize_2pow);
                   1782:        total_pages = chunk->map[run_ind].npages;
                   1783:        need_pages = (size >> pagesize_2pow);
                   1784:        assert(need_pages <= total_pages);
                   1785:        rem_pages = total_pages - need_pages;
                   1786:
                   1787:        /* Split enough pages from the front of run to fit allocation size. */
                   1788:        map_offset = run_ind;
                   1789:        for (i = 0; i < need_pages; i++) {
                   1790:                chunk->map[map_offset + i].npages = need_pages;
                   1791:                chunk->map[map_offset + i].pos = i;
                   1792:        }
                   1793:
                   1794:        /* Keep track of trailing unused pages for later use. */
                   1795:        if (rem_pages > 0) {
                   1796:                /* Update map for trailing pages. */
                   1797:                map_offset += need_pages;
                   1798:                chunk->map[map_offset].npages = rem_pages;
                   1799:                chunk->map[map_offset].pos = POS_FREE;
                   1800:                chunk->map[map_offset + rem_pages - 1].npages = rem_pages;
                   1801:                chunk->map[map_offset + rem_pages - 1].pos = POS_FREE;
                   1802:        }
                   1803:
                   1804:        chunk->pages_used += need_pages;
                   1805: }
                   1806:
                   1807: static arena_chunk_t *
                   1808: arena_chunk_alloc(arena_t *arena)
                   1809: {
                   1810:        arena_chunk_t *chunk;
                   1811:
                   1812:        if (arena->spare != NULL) {
                   1813:                chunk = arena->spare;
                   1814:                arena->spare = NULL;
                   1815:
1.2       ad       1816:                /* LINTED */
1.1       ad       1817:                RB_INSERT(arena_chunk_tree_s, &arena->chunks, chunk);
                   1818:        } else {
                   1819:                chunk = (arena_chunk_t *)chunk_alloc(chunksize);
                   1820:                if (chunk == NULL)
                   1821:                        return (NULL);
                   1822: #ifdef MALLOC_STATS
                   1823:                arena->stats.mapped += chunksize;
                   1824: #endif
                   1825:
                   1826:                chunk->arena = arena;
                   1827:
1.2       ad       1828:                /* LINTED */
1.1       ad       1829:                RB_INSERT(arena_chunk_tree_s, &arena->chunks, chunk);
                   1830:
                   1831:                /*
                   1832:                 * Claim that no pages are in use, since the header is merely
                   1833:                 * overhead.
                   1834:                 */
                   1835:                chunk->pages_used = 0;
                   1836:
                   1837:                chunk->max_frun_npages = chunk_npages -
                   1838:                    arena_chunk_header_npages;
                   1839:                chunk->min_frun_ind = arena_chunk_header_npages;
                   1840:
                   1841:                /*
                   1842:                 * Initialize enough of the map to support one maximal free run.
                   1843:                 */
                   1844:                chunk->map[arena_chunk_header_npages].npages = chunk_npages -
                   1845:                    arena_chunk_header_npages;
                   1846:                chunk->map[arena_chunk_header_npages].pos = POS_FREE;
                   1847:                chunk->map[chunk_npages - 1].npages = chunk_npages -
                   1848:                    arena_chunk_header_npages;
                   1849:                chunk->map[chunk_npages - 1].pos = POS_FREE;
                   1850:        }
                   1851:
                   1852:        return (chunk);
                   1853: }
                   1854:
                   1855: static void
                   1856: arena_chunk_dealloc(arena_t *arena, arena_chunk_t *chunk)
                   1857: {
                   1858:
                   1859:        /*
                   1860:         * Remove chunk from the chunk tree, regardless of whether this chunk
                   1861:         * will be cached, so that the arena does not use it.
                   1862:         */
1.2       ad       1863:        /* LINTED */
1.1       ad       1864:        RB_REMOVE(arena_chunk_tree_s, &chunk->arena->chunks, chunk);
                   1865:
                   1866:        if (opt_hint == false) {
                   1867:                if (arena->spare != NULL) {
                   1868:                        chunk_dealloc((void *)arena->spare, chunksize);
                   1869: #ifdef MALLOC_STATS
                   1870:                        arena->stats.mapped -= chunksize;
                   1871: #endif
                   1872:                }
                   1873:                arena->spare = chunk;
                   1874:        } else {
                   1875:                assert(arena->spare == NULL);
                   1876:                chunk_dealloc((void *)chunk, chunksize);
                   1877: #ifdef MALLOC_STATS
                   1878:                arena->stats.mapped -= chunksize;
                   1879: #endif
                   1880:        }
                   1881: }
                   1882:
                   1883: static arena_run_t *
                   1884: arena_run_alloc(arena_t *arena, size_t size)
                   1885: {
                   1886:        arena_chunk_t *chunk;
                   1887:        arena_run_t *run;
                   1888:        unsigned need_npages, limit_pages, compl_need_npages;
                   1889:
                   1890:        assert(size <= (chunksize - (arena_chunk_header_npages <<
                   1891:            pagesize_2pow)));
                   1892:        assert((size & pagesize_mask) == 0);
                   1893:
                   1894:        /*
                   1895:         * Search through arena's chunks in address order for a free run that is
                   1896:         * large enough.  Look for the first fit.
                   1897:         */
                   1898:        need_npages = (size >> pagesize_2pow);
                   1899:        limit_pages = chunk_npages - arena_chunk_header_npages;
                   1900:        compl_need_npages = limit_pages - need_npages;
1.2       ad       1901:        /* LINTED */
1.1       ad       1902:        RB_FOREACH(chunk, arena_chunk_tree_s, &arena->chunks) {
                   1903:                /*
                   1904:                 * Avoid searching this chunk if there are not enough
                   1905:                 * contiguous free pages for there to possibly be a large
                   1906:                 * enough free run.
                   1907:                 */
                   1908:                if (chunk->pages_used <= compl_need_npages &&
                   1909:                    need_npages <= chunk->max_frun_npages) {
                   1910:                        arena_chunk_map_t *mapelm;
                   1911:                        unsigned i;
                   1912:                        unsigned max_frun_npages = 0;
                   1913:                        unsigned min_frun_ind = chunk_npages;
                   1914:
                   1915:                        assert(chunk->min_frun_ind >=
                   1916:                            arena_chunk_header_npages);
                   1917:                        for (i = chunk->min_frun_ind; i < chunk_npages;) {
                   1918:                                mapelm = &chunk->map[i];
                   1919:                                if (mapelm->pos == POS_FREE) {
                   1920:                                        if (mapelm->npages >= need_npages) {
                   1921:                                                run = (arena_run_t *)
                   1922:                                                    ((uintptr_t)chunk + (i <<
                   1923:                                                    pagesize_2pow));
                   1924:                                                /* Update page map. */
                   1925:                                                arena_run_split(arena, run,
                   1926:                                                    size);
                   1927:                                                return (run);
                   1928:                                        }
                   1929:                                        if (mapelm->npages >
                   1930:                                            max_frun_npages) {
                   1931:                                                max_frun_npages =
                   1932:                                                    mapelm->npages;
                   1933:                                        }
                   1934:                                        if (i < min_frun_ind) {
                   1935:                                                min_frun_ind = i;
                   1936:                                                if (i < chunk->min_frun_ind)
                   1937:                                                        chunk->min_frun_ind = i;
                   1938:                                        }
                   1939:                                }
                   1940:                                i += mapelm->npages;
                   1941:                        }
                   1942:                        /*
                   1943:                         * Search failure.  Reset cached chunk->max_frun_npages.
                   1944:                         * chunk->min_frun_ind was already reset above (if
                   1945:                         * necessary).
                   1946:                         */
                   1947:                        chunk->max_frun_npages = max_frun_npages;
                   1948:                }
                   1949:        }
                   1950:
                   1951:        /*
                   1952:         * No usable runs.  Create a new chunk from which to allocate the run.
                   1953:         */
                   1954:        chunk = arena_chunk_alloc(arena);
                   1955:        if (chunk == NULL)
                   1956:                return (NULL);
                   1957:        run = (arena_run_t *)((uintptr_t)chunk + (arena_chunk_header_npages <<
                   1958:            pagesize_2pow));
                   1959:        /* Update page map. */
                   1960:        arena_run_split(arena, run, size);
                   1961:        return (run);
                   1962: }
                   1963:
                   1964: static void
                   1965: arena_run_dalloc(arena_t *arena, arena_run_t *run, size_t size)
                   1966: {
                   1967:        arena_chunk_t *chunk;
                   1968:        unsigned run_ind, run_pages;
                   1969:
                   1970:        chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(run);
                   1971:
                   1972:        run_ind = (unsigned)(((uintptr_t)run - (uintptr_t)chunk)
                   1973:            >> pagesize_2pow);
                   1974:        assert(run_ind >= arena_chunk_header_npages);
                   1975:        assert(run_ind < (chunksize >> pagesize_2pow));
                   1976:        run_pages = (size >> pagesize_2pow);
                   1977:        assert(run_pages == chunk->map[run_ind].npages);
                   1978:
                   1979:        /* Subtract pages from count of pages used in chunk. */
                   1980:        chunk->pages_used -= run_pages;
                   1981:
                   1982:        /* Mark run as deallocated. */
                   1983:        assert(chunk->map[run_ind].npages == run_pages);
                   1984:        chunk->map[run_ind].pos = POS_FREE;
                   1985:        assert(chunk->map[run_ind + run_pages - 1].npages == run_pages);
                   1986:        chunk->map[run_ind + run_pages - 1].pos = POS_FREE;
                   1987:
                   1988:        /*
                   1989:         * Tell the kernel that we don't need the data in this run, but only if
                   1990:         * requested via runtime configuration.
                   1991:         */
                   1992:        if (opt_hint)
                   1993:                madvise(run, size, MADV_FREE);
                   1994:
                   1995:        /* Try to coalesce with neighboring runs. */
                   1996:        if (run_ind > arena_chunk_header_npages &&
                   1997:            chunk->map[run_ind - 1].pos == POS_FREE) {
                   1998:                unsigned prev_npages;
                   1999:
                   2000:                /* Coalesce with previous run. */
                   2001:                prev_npages = chunk->map[run_ind - 1].npages;
                   2002:                run_ind -= prev_npages;
                   2003:                assert(chunk->map[run_ind].npages == prev_npages);
                   2004:                assert(chunk->map[run_ind].pos == POS_FREE);
                   2005:                run_pages += prev_npages;
                   2006:
                   2007:                chunk->map[run_ind].npages = run_pages;
                   2008:                assert(chunk->map[run_ind].pos == POS_FREE);
                   2009:                chunk->map[run_ind + run_pages - 1].npages = run_pages;
                   2010:                assert(chunk->map[run_ind + run_pages - 1].pos == POS_FREE);
                   2011:        }
                   2012:
                   2013:        if (run_ind + run_pages < chunk_npages &&
                   2014:            chunk->map[run_ind + run_pages].pos == POS_FREE) {
                   2015:                unsigned next_npages;
                   2016:
                   2017:                /* Coalesce with next run. */
                   2018:                next_npages = chunk->map[run_ind + run_pages].npages;
                   2019:                run_pages += next_npages;
                   2020:                assert(chunk->map[run_ind + run_pages - 1].npages ==
                   2021:                    next_npages);
                   2022:                assert(chunk->map[run_ind + run_pages - 1].pos == POS_FREE);
                   2023:
                   2024:                chunk->map[run_ind].npages = run_pages;
                   2025:                chunk->map[run_ind].pos = POS_FREE;
                   2026:                chunk->map[run_ind + run_pages - 1].npages = run_pages;
                   2027:                assert(chunk->map[run_ind + run_pages - 1].pos == POS_FREE);
                   2028:        }
                   2029:
                   2030:        if (chunk->map[run_ind].npages > chunk->max_frun_npages)
                   2031:                chunk->max_frun_npages = chunk->map[run_ind].npages;
                   2032:        if (run_ind < chunk->min_frun_ind)
                   2033:                chunk->min_frun_ind = run_ind;
                   2034:
                   2035:        /* Deallocate chunk if it is now completely unused. */
                   2036:        if (chunk->pages_used == 0)
                   2037:                arena_chunk_dealloc(arena, chunk);
                   2038: }
                   2039:
                   2040: static arena_run_t *
                   2041: arena_bin_nonfull_run_get(arena_t *arena, arena_bin_t *bin)
                   2042: {
                   2043:        arena_run_t *run;
                   2044:        unsigned i, remainder;
                   2045:
                   2046:        /* Look for a usable run. */
1.2       ad       2047:        /* LINTED */
1.1       ad       2048:        if ((run = RB_MIN(arena_run_tree_s, &bin->runs)) != NULL) {
                   2049:                /* run is guaranteed to have available space. */
1.2       ad       2050:                /* LINTED */
1.1       ad       2051:                RB_REMOVE(arena_run_tree_s, &bin->runs, run);
                   2052: #ifdef MALLOC_STATS
                   2053:                bin->stats.reruns++;
                   2054: #endif
                   2055:                return (run);
                   2056:        }
                   2057:        /* No existing runs have any space available. */
                   2058:
                   2059:        /* Allocate a new run. */
                   2060:        run = arena_run_alloc(arena, bin->run_size);
                   2061:        if (run == NULL)
                   2062:                return (NULL);
                   2063:
                   2064:        /* Initialize run internals. */
                   2065:        run->bin = bin;
                   2066:
                   2067:        for (i = 0; i < bin->regs_mask_nelms; i++)
                   2068:                run->regs_mask[i] = UINT_MAX;
                   2069:        remainder = bin->nregs & ((1 << (SIZEOF_INT_2POW + 3)) - 1);
                   2070:        if (remainder != 0) {
                   2071:                /* The last element has spare bits that need to be unset. */
                   2072:                run->regs_mask[i] = (UINT_MAX >> ((1 << (SIZEOF_INT_2POW + 3))
                   2073:                    - remainder));
                   2074:        }
                   2075:
                   2076:        run->regs_minelm = 0;
                   2077:
                   2078:        run->nfree = bin->nregs;
                   2079: #ifdef MALLOC_DEBUG
                   2080:        run->magic = ARENA_RUN_MAGIC;
                   2081: #endif
                   2082:
                   2083: #ifdef MALLOC_STATS
                   2084:        bin->stats.nruns++;
                   2085:        bin->stats.curruns++;
                   2086:        if (bin->stats.curruns > bin->stats.highruns)
                   2087:                bin->stats.highruns = bin->stats.curruns;
                   2088: #endif
                   2089:        return (run);
                   2090: }
                   2091:
                   2092: /* bin->runcur must have space available before this function is called. */
                   2093: static inline void *
                   2094: arena_bin_malloc_easy(arena_t *arena, arena_bin_t *bin, arena_run_t *run)
                   2095: {
                   2096:        void *ret;
                   2097:
                   2098:        assert(run->magic == ARENA_RUN_MAGIC);
                   2099:        assert(run->nfree > 0);
                   2100:
                   2101:        ret = arena_run_reg_alloc(run, bin);
                   2102:        assert(ret != NULL);
                   2103:        run->nfree--;
                   2104:
                   2105:        return (ret);
                   2106: }
                   2107:
                   2108: /* Re-fill bin->runcur, then call arena_bin_malloc_easy(). */
                   2109: static void *
                   2110: arena_bin_malloc_hard(arena_t *arena, arena_bin_t *bin)
                   2111: {
                   2112:
                   2113:        bin->runcur = arena_bin_nonfull_run_get(arena, bin);
                   2114:        if (bin->runcur == NULL)
                   2115:                return (NULL);
                   2116:        assert(bin->runcur->magic == ARENA_RUN_MAGIC);
                   2117:        assert(bin->runcur->nfree > 0);
                   2118:
                   2119:        return (arena_bin_malloc_easy(arena, bin, bin->runcur));
                   2120: }
                   2121:
                   2122: /*
                   2123:  * Calculate bin->run_size such that it meets the following constraints:
                   2124:  *
                   2125:  *   *) bin->run_size >= min_run_size
                   2126:  *   *) bin->run_size <= arena_maxclass
                   2127:  *   *) bin->run_size <= RUN_MAX_SMALL
                   2128:  *   *) run header overhead <= RUN_MAX_OVRHD (or header overhead relaxed).
                   2129:  *
                   2130:  * bin->nregs, bin->regs_mask_nelms, and bin->reg0_offset are
                   2131:  * also calculated here, since these settings are all interdependent.
                   2132:  */
                   2133: static size_t
                   2134: arena_bin_run_size_calc(arena_bin_t *bin, size_t min_run_size)
                   2135: {
                   2136:        size_t try_run_size, good_run_size;
                   2137:        unsigned good_nregs, good_mask_nelms, good_reg0_offset;
                   2138:        unsigned try_nregs, try_mask_nelms, try_reg0_offset;
                   2139:        float max_ovrhd = RUN_MAX_OVRHD;
                   2140:
                   2141:        assert(min_run_size >= pagesize);
                   2142:        assert(min_run_size <= arena_maxclass);
                   2143:        assert(min_run_size <= RUN_MAX_SMALL);
                   2144:
                   2145:        /*
                   2146:         * Calculate known-valid settings before entering the run_size
                   2147:         * expansion loop, so that the first part of the loop always copies
                   2148:         * valid settings.
                   2149:         *
                   2150:         * The do..while loop iteratively reduces the number of regions until
                   2151:         * the run header and the regions no longer overlap.  A closed formula
                   2152:         * would be quite messy, since there is an interdependency between the
                   2153:         * header's mask length and the number of regions.
                   2154:         */
                   2155:        try_run_size = min_run_size;
                   2156:        try_nregs = ((try_run_size - sizeof(arena_run_t)) / bin->reg_size)
                   2157:            + 1; /* Counter-act the first line of the loop. */
                   2158:        do {
                   2159:                try_nregs--;
                   2160:                try_mask_nelms = (try_nregs >> (SIZEOF_INT_2POW + 3)) +
                   2161:                    ((try_nregs & ((1 << (SIZEOF_INT_2POW + 3)) - 1)) ? 1 : 0);
                   2162:                try_reg0_offset = try_run_size - (try_nregs * bin->reg_size);
                   2163:        } while (sizeof(arena_run_t) + (sizeof(unsigned) * (try_mask_nelms - 1))
                   2164:            > try_reg0_offset);
                   2165:
                   2166:        /* run_size expansion loop. */
                   2167:        do {
                   2168:                /*
                   2169:                 * Copy valid settings before trying more aggressive settings.
                   2170:                 */
                   2171:                good_run_size = try_run_size;
                   2172:                good_nregs = try_nregs;
                   2173:                good_mask_nelms = try_mask_nelms;
                   2174:                good_reg0_offset = try_reg0_offset;
                   2175:
                   2176:                /* Try more aggressive settings. */
                   2177:                try_run_size += pagesize;
                   2178:                try_nregs = ((try_run_size - sizeof(arena_run_t)) /
                   2179:                    bin->reg_size) + 1; /* Counter-act try_nregs-- in loop. */
                   2180:                do {
                   2181:                        try_nregs--;
                   2182:                        try_mask_nelms = (try_nregs >> (SIZEOF_INT_2POW + 3)) +
                   2183:                            ((try_nregs & ((1 << (SIZEOF_INT_2POW + 3)) - 1)) ?
                   2184:                            1 : 0);
                   2185:                        try_reg0_offset = try_run_size - (try_nregs *
                   2186:                            bin->reg_size);
                   2187:                } while (sizeof(arena_run_t) + (sizeof(unsigned) *
                   2188:                    (try_mask_nelms - 1)) > try_reg0_offset);
                   2189:        } while (try_run_size <= arena_maxclass && try_run_size <= RUN_MAX_SMALL
                   2190:            && max_ovrhd > RUN_MAX_OVRHD_RELAX / ((float)(bin->reg_size << 3))
                   2191:            && ((float)(try_reg0_offset)) / ((float)(try_run_size)) >
                   2192:            max_ovrhd);
                   2193:
                   2194:        assert(sizeof(arena_run_t) + (sizeof(unsigned) * (good_mask_nelms - 1))
                   2195:            <= good_reg0_offset);
                   2196:        assert((good_mask_nelms << (SIZEOF_INT_2POW + 3)) >= good_nregs);
                   2197:
                   2198:        /* Copy final settings. */
                   2199:        bin->run_size = good_run_size;
                   2200:        bin->nregs = good_nregs;
                   2201:        bin->regs_mask_nelms = good_mask_nelms;
                   2202:        bin->reg0_offset = good_reg0_offset;
                   2203:
                   2204:        return (good_run_size);
                   2205: }
                   2206:
                   2207: static void *
                   2208: arena_malloc(arena_t *arena, size_t size)
                   2209: {
                   2210:        void *ret;
                   2211:
                   2212:        assert(arena != NULL);
                   2213:        assert(arena->magic == ARENA_MAGIC);
                   2214:        assert(size != 0);
                   2215:        assert(QUANTUM_CEILING(size) <= arena_maxclass);
                   2216:
                   2217:        if (size <= bin_maxclass) {
                   2218:                arena_bin_t *bin;
                   2219:                arena_run_t *run;
                   2220:
                   2221:                /* Small allocation. */
                   2222:
                   2223:                if (size < small_min) {
                   2224:                        /* Tiny. */
                   2225:                        size = pow2_ceil(size);
                   2226:                        bin = &arena->bins[ffs((int)(size >> (TINY_MIN_2POW +
                   2227:                            1)))];
                   2228: #if (!defined(NDEBUG) || defined(MALLOC_STATS))
                   2229:                        /*
                   2230:                         * Bin calculation is always correct, but we may need
                   2231:                         * to fix size for the purposes of assertions and/or
                   2232:                         * stats accuracy.
                   2233:                         */
                   2234:                        if (size < (1 << TINY_MIN_2POW))
                   2235:                                size = (1 << TINY_MIN_2POW);
                   2236: #endif
                   2237:                } else if (size <= small_max) {
                   2238:                        /* Quantum-spaced. */
                   2239:                        size = QUANTUM_CEILING(size);
                   2240:                        bin = &arena->bins[ntbins + (size >> opt_quantum_2pow)
                   2241:                            - 1];
                   2242:                } else {
                   2243:                        /* Sub-page. */
                   2244:                        size = pow2_ceil(size);
                   2245:                        bin = &arena->bins[ntbins + nqbins
                   2246:                            + (ffs((int)(size >> opt_small_max_2pow)) - 2)];
                   2247:                }
                   2248:                assert(size == bin->reg_size);
                   2249:
                   2250:                malloc_mutex_lock(&arena->mtx);
                   2251:                if ((run = bin->runcur) != NULL && run->nfree > 0)
                   2252:                        ret = arena_bin_malloc_easy(arena, bin, run);
                   2253:                else
                   2254:                        ret = arena_bin_malloc_hard(arena, bin);
                   2255:
                   2256:                if (ret == NULL) {
                   2257:                        malloc_mutex_unlock(&arena->mtx);
                   2258:                        return (NULL);
                   2259:                }
                   2260:
                   2261: #ifdef MALLOC_STATS
                   2262:                bin->stats.nrequests++;
                   2263:                arena->stats.nmalloc_small++;
                   2264:                arena->stats.allocated_small += size;
                   2265: #endif
                   2266:        } else {
                   2267:                /* Large allocation. */
                   2268:                size = PAGE_CEILING(size);
                   2269:                malloc_mutex_lock(&arena->mtx);
                   2270:                ret = (void *)arena_run_alloc(arena, size);
                   2271:                if (ret == NULL) {
                   2272:                        malloc_mutex_unlock(&arena->mtx);
                   2273:                        return (NULL);
                   2274:                }
                   2275: #ifdef MALLOC_STATS
                   2276:                arena->stats.nmalloc_large++;
                   2277:                arena->stats.allocated_large += size;
                   2278: #endif
                   2279:        }
                   2280:
                   2281:        malloc_mutex_unlock(&arena->mtx);
                   2282:
                   2283:        if (opt_junk)
                   2284:                memset(ret, 0xa5, size);
                   2285:        else if (opt_zero)
                   2286:                memset(ret, 0, size);
                   2287:        return (ret);
                   2288: }
                   2289:
                   2290: static inline void
                   2291: arena_palloc_trim(arena_t *arena, arena_chunk_t *chunk, unsigned pageind,
                   2292:     unsigned npages)
                   2293: {
                   2294:        unsigned i;
                   2295:
                   2296:        assert(npages > 0);
                   2297:
                   2298:        /*
                   2299:         * Modifiy the map such that arena_run_dalloc() sees the run as
                   2300:         * separately allocated.
                   2301:         */
                   2302:        for (i = 0; i < npages; i++) {
                   2303:                chunk->map[pageind + i].npages = npages;
                   2304:                chunk->map[pageind + i].pos = i;
                   2305:        }
                   2306:        arena_run_dalloc(arena, (arena_run_t *)((uintptr_t)chunk + (pageind <<
                   2307:            pagesize_2pow)), npages << pagesize_2pow);
                   2308: }
                   2309:
                   2310: /* Only handles large allocations that require more than page alignment. */
                   2311: static void *
                   2312: arena_palloc(arena_t *arena, size_t alignment, size_t size, size_t alloc_size)
                   2313: {
                   2314:        void *ret;
                   2315:        size_t offset;
                   2316:        arena_chunk_t *chunk;
                   2317:        unsigned pageind, i, npages;
                   2318:
                   2319:        assert((size & pagesize_mask) == 0);
                   2320:        assert((alignment & pagesize_mask) == 0);
                   2321:
                   2322:        npages = size >> pagesize_2pow;
                   2323:
                   2324:        malloc_mutex_lock(&arena->mtx);
                   2325:        ret = (void *)arena_run_alloc(arena, alloc_size);
                   2326:        if (ret == NULL) {
                   2327:                malloc_mutex_unlock(&arena->mtx);
                   2328:                return (NULL);
                   2329:        }
                   2330:
                   2331:        chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ret);
                   2332:
                   2333:        offset = (uintptr_t)ret & (alignment - 1);
                   2334:        assert((offset & pagesize_mask) == 0);
                   2335:        assert(offset < alloc_size);
                   2336:        if (offset == 0) {
                   2337:                pageind = (((uintptr_t)ret - (uintptr_t)chunk) >>
                   2338:                    pagesize_2pow);
                   2339:
                   2340:                /* Update the map for the run to be kept. */
                   2341:                for (i = 0; i < npages; i++) {
                   2342:                        chunk->map[pageind + i].npages = npages;
                   2343:                        assert(chunk->map[pageind + i].pos == i);
                   2344:                }
                   2345:
                   2346:                /* Trim trailing space. */
                   2347:                arena_palloc_trim(arena, chunk, pageind + npages,
                   2348:                    (alloc_size - size) >> pagesize_2pow);
                   2349:        } else {
                   2350:                size_t leadsize, trailsize;
                   2351:
                   2352:                leadsize = alignment - offset;
                   2353:                ret = (void *)((uintptr_t)ret + leadsize);
                   2354:                pageind = (((uintptr_t)ret - (uintptr_t)chunk) >>
                   2355:                    pagesize_2pow);
                   2356:
                   2357:                /* Update the map for the run to be kept. */
                   2358:                for (i = 0; i < npages; i++) {
                   2359:                        chunk->map[pageind + i].npages = npages;
                   2360:                        chunk->map[pageind + i].pos = i;
                   2361:                }
                   2362:
                   2363:                /* Trim leading space. */
                   2364:                arena_palloc_trim(arena, chunk, pageind - (leadsize >>
                   2365:                    pagesize_2pow), leadsize >> pagesize_2pow);
                   2366:
                   2367:                trailsize = alloc_size - leadsize - size;
                   2368:                if (trailsize != 0) {
                   2369:                        /* Trim trailing space. */
                   2370:                        assert(trailsize < alloc_size);
                   2371:                        arena_palloc_trim(arena, chunk, pageind + npages,
                   2372:                            trailsize >> pagesize_2pow);
                   2373:                }
                   2374:        }
                   2375:
                   2376: #ifdef MALLOC_STATS
                   2377:        arena->stats.nmalloc_large++;
                   2378:        arena->stats.allocated_large += size;
                   2379: #endif
                   2380:        malloc_mutex_unlock(&arena->mtx);
                   2381:
                   2382:        if (opt_junk)
                   2383:                memset(ret, 0xa5, size);
                   2384:        else if (opt_zero)
                   2385:                memset(ret, 0, size);
                   2386:        return (ret);
                   2387: }
                   2388:
                   2389: /* Return the size of the allocation pointed to by ptr. */
                   2390: static size_t
                   2391: arena_salloc(const void *ptr)
                   2392: {
                   2393:        size_t ret;
                   2394:        arena_chunk_t *chunk;
                   2395:        arena_chunk_map_t *mapelm;
                   2396:        unsigned pageind;
                   2397:
                   2398:        assert(ptr != NULL);
                   2399:        assert(CHUNK_ADDR2BASE(ptr) != ptr);
                   2400:
                   2401:        /*
                   2402:         * No arena data structures that we query here can change in a way that
                   2403:         * affects this function, so we don't need to lock.
                   2404:         */
                   2405:        chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
                   2406:        pageind = (((uintptr_t)ptr - (uintptr_t)chunk) >> pagesize_2pow);
                   2407:        mapelm = &chunk->map[pageind];
1.2       ad       2408:        if (mapelm->pos != 0 || ptr != (char *)((uintptr_t)chunk) + (pageind <<
1.1       ad       2409:            pagesize_2pow)) {
                   2410:                arena_run_t *run;
                   2411:
                   2412:                pageind -= mapelm->pos;
                   2413:
                   2414:                run = (arena_run_t *)((uintptr_t)chunk + (pageind <<
                   2415:                    pagesize_2pow));
                   2416:                assert(run->magic == ARENA_RUN_MAGIC);
                   2417:                ret = run->bin->reg_size;
                   2418:        } else
                   2419:                ret = mapelm->npages << pagesize_2pow;
                   2420:
                   2421:        return (ret);
                   2422: }
                   2423:
                   2424: static void *
                   2425: arena_ralloc(void *ptr, size_t size, size_t oldsize)
                   2426: {
                   2427:        void *ret;
                   2428:
                   2429:        /* Avoid moving the allocation if the size class would not change. */
                   2430:        if (size < small_min) {
                   2431:                if (oldsize < small_min &&
                   2432:                    ffs((int)(pow2_ceil(size) >> (TINY_MIN_2POW + 1)))
                   2433:                    == ffs((int)(pow2_ceil(oldsize) >> (TINY_MIN_2POW + 1))))
                   2434:                        goto IN_PLACE;
                   2435:        } else if (size <= small_max) {
                   2436:                if (oldsize >= small_min && oldsize <= small_max &&
                   2437:                    (QUANTUM_CEILING(size) >> opt_quantum_2pow)
                   2438:                    == (QUANTUM_CEILING(oldsize) >> opt_quantum_2pow))
                   2439:                        goto IN_PLACE;
                   2440:        } else {
                   2441:                /*
                   2442:                 * We make no attempt to resize runs here, though it would be
                   2443:                 * possible to do so.
                   2444:                 */
                   2445:                if (oldsize > small_max && PAGE_CEILING(size) == oldsize)
                   2446:                        goto IN_PLACE;
                   2447:        }
                   2448:
                   2449:        /*
                   2450:         * If we get here, then size and oldsize are different enough that we
                   2451:         * need to use a different size class.  In that case, fall back to
                   2452:         * allocating new space and copying.
                   2453:         */
                   2454:        ret = arena_malloc(choose_arena(), size);
                   2455:        if (ret == NULL)
                   2456:                return (NULL);
                   2457:
                   2458:        /* Junk/zero-filling were already done by arena_malloc(). */
                   2459:        if (size < oldsize)
                   2460:                memcpy(ret, ptr, size);
                   2461:        else
                   2462:                memcpy(ret, ptr, oldsize);
                   2463:        idalloc(ptr);
                   2464:        return (ret);
                   2465: IN_PLACE:
                   2466:        if (opt_junk && size < oldsize)
                   2467:                memset((void *)((uintptr_t)ptr + size), 0x5a, oldsize - size);
                   2468:        else if (opt_zero && size > oldsize)
                   2469:                memset((void *)((uintptr_t)ptr + oldsize), 0, size - oldsize);
                   2470:        return (ptr);
                   2471: }
                   2472:
                   2473: static void
                   2474: arena_dalloc(arena_t *arena, arena_chunk_t *chunk, void *ptr)
                   2475: {
                   2476:        unsigned pageind;
                   2477:        arena_chunk_map_t *mapelm;
                   2478:        size_t size;
                   2479:
                   2480:        assert(arena != NULL);
                   2481:        assert(arena->magic == ARENA_MAGIC);
                   2482:        assert(chunk->arena == arena);
                   2483:        assert(ptr != NULL);
                   2484:        assert(CHUNK_ADDR2BASE(ptr) != ptr);
                   2485:
                   2486:        pageind = (((uintptr_t)ptr - (uintptr_t)chunk) >> pagesize_2pow);
                   2487:        mapelm = &chunk->map[pageind];
1.2       ad       2488:        if (mapelm->pos != 0 || ptr != (char *)((uintptr_t)chunk) + (pageind <<
1.1       ad       2489:            pagesize_2pow)) {
                   2490:                arena_run_t *run;
                   2491:                arena_bin_t *bin;
                   2492:
                   2493:                /* Small allocation. */
                   2494:
                   2495:                pageind -= mapelm->pos;
                   2496:
                   2497:                run = (arena_run_t *)((uintptr_t)chunk + (pageind <<
                   2498:                    pagesize_2pow));
                   2499:                assert(run->magic == ARENA_RUN_MAGIC);
                   2500:                bin = run->bin;
                   2501:                size = bin->reg_size;
                   2502:
                   2503:                if (opt_junk)
                   2504:                        memset(ptr, 0x5a, size);
                   2505:
                   2506:                malloc_mutex_lock(&arena->mtx);
                   2507:                arena_run_reg_dalloc(run, bin, ptr, size);
                   2508:                run->nfree++;
                   2509:
                   2510:                if (run->nfree == bin->nregs) {
                   2511:                        /* Deallocate run. */
                   2512:                        if (run == bin->runcur)
                   2513:                                bin->runcur = NULL;
                   2514:                        else if (bin->nregs != 1) {
                   2515:                                /*
                   2516:                                 * This block's conditional is necessary because
                   2517:                                 * if the run only contains one region, then it
                   2518:                                 * never gets inserted into the non-full runs
                   2519:                                 * tree.
                   2520:                                 */
1.2       ad       2521:                                /* LINTED */
1.1       ad       2522:                                RB_REMOVE(arena_run_tree_s, &bin->runs, run);
                   2523:                        }
                   2524: #ifdef MALLOC_DEBUG
                   2525:                        run->magic = 0;
                   2526: #endif
                   2527:                        arena_run_dalloc(arena, run, bin->run_size);
                   2528: #ifdef MALLOC_STATS
                   2529:                        bin->stats.curruns--;
                   2530: #endif
                   2531:                } else if (run->nfree == 1 && run != bin->runcur) {
                   2532:                        /*
                   2533:                         * Make sure that bin->runcur always refers to the
                   2534:                         * lowest non-full run, if one exists.
                   2535:                         */
                   2536:                        if (bin->runcur == NULL)
                   2537:                                bin->runcur = run;
                   2538:                        else if ((uintptr_t)run < (uintptr_t)bin->runcur) {
                   2539:                                /* Switch runcur. */
                   2540:                                if (bin->runcur->nfree > 0) {
                   2541:                                        /* Insert runcur. */
1.2       ad       2542:                                        /* LINTED */
1.1       ad       2543:                                        RB_INSERT(arena_run_tree_s, &bin->runs,
                   2544:                                            bin->runcur);
                   2545:                                }
                   2546:                                bin->runcur = run;
1.2       ad       2547:                        } else {
                   2548:                                /* LINTED */
1.1       ad       2549:                                RB_INSERT(arena_run_tree_s, &bin->runs, run);
1.2       ad       2550:                        }
1.1       ad       2551:                }
                   2552: #ifdef MALLOC_STATS
                   2553:                arena->stats.allocated_small -= size;
                   2554:                arena->stats.ndalloc_small++;
                   2555: #endif
                   2556:        } else {
                   2557:                /* Large allocation. */
                   2558:
                   2559:                size = mapelm->npages << pagesize_2pow;
                   2560:                assert((((uintptr_t)ptr) & pagesize_mask) == 0);
                   2561:
                   2562:                if (opt_junk)
                   2563:                        memset(ptr, 0x5a, size);
                   2564:
                   2565:                malloc_mutex_lock(&arena->mtx);
                   2566:                arena_run_dalloc(arena, (arena_run_t *)ptr, size);
                   2567: #ifdef MALLOC_STATS
                   2568:                arena->stats.allocated_large -= size;
                   2569:                arena->stats.ndalloc_large++;
                   2570: #endif
                   2571:        }
                   2572:
                   2573:        malloc_mutex_unlock(&arena->mtx);
                   2574: }
                   2575:
                   2576: static bool
                   2577: arena_new(arena_t *arena)
                   2578: {
                   2579:        unsigned i;
                   2580:        arena_bin_t *bin;
1.2       ad       2581:        size_t prev_run_size;
1.1       ad       2582:
                   2583:        malloc_mutex_init(&arena->mtx);
                   2584:
                   2585: #ifdef MALLOC_STATS
                   2586:        memset(&arena->stats, 0, sizeof(arena_stats_t));
                   2587: #endif
                   2588:
                   2589:        /* Initialize chunks. */
                   2590:        RB_INIT(&arena->chunks);
                   2591:        arena->spare = NULL;
                   2592:
                   2593:        /* Initialize bins. */
                   2594:        prev_run_size = pagesize;
                   2595:
                   2596:        /* (2^n)-spaced tiny bins. */
                   2597:        for (i = 0; i < ntbins; i++) {
                   2598:                bin = &arena->bins[i];
                   2599:                bin->runcur = NULL;
                   2600:                RB_INIT(&bin->runs);
                   2601:
                   2602:                bin->reg_size = (1 << (TINY_MIN_2POW + i));
                   2603:                prev_run_size = arena_bin_run_size_calc(bin, prev_run_size);
                   2604:
                   2605: #ifdef MALLOC_STATS
                   2606:                memset(&bin->stats, 0, sizeof(malloc_bin_stats_t));
                   2607: #endif
                   2608:        }
                   2609:
                   2610:        /* Quantum-spaced bins. */
                   2611:        for (; i < ntbins + nqbins; i++) {
                   2612:                bin = &arena->bins[i];
                   2613:                bin->runcur = NULL;
                   2614:                RB_INIT(&bin->runs);
                   2615:
                   2616:                bin->reg_size = quantum * (i - ntbins + 1);
1.2       ad       2617: /*
1.1       ad       2618:                pow2_size = pow2_ceil(quantum * (i - ntbins + 1));
1.2       ad       2619: */
1.1       ad       2620:                prev_run_size = arena_bin_run_size_calc(bin, prev_run_size);
                   2621:
                   2622: #ifdef MALLOC_STATS
                   2623:                memset(&bin->stats, 0, sizeof(malloc_bin_stats_t));
                   2624: #endif
                   2625:        }
                   2626:
                   2627:        /* (2^n)-spaced sub-page bins. */
                   2628:        for (; i < ntbins + nqbins + nsbins; i++) {
                   2629:                bin = &arena->bins[i];
                   2630:                bin->runcur = NULL;
                   2631:                RB_INIT(&bin->runs);
                   2632:
                   2633:                bin->reg_size = (small_max << (i - (ntbins + nqbins) + 1));
                   2634:
                   2635:                prev_run_size = arena_bin_run_size_calc(bin, prev_run_size);
                   2636:
                   2637: #ifdef MALLOC_STATS
                   2638:                memset(&bin->stats, 0, sizeof(malloc_bin_stats_t));
                   2639: #endif
                   2640:        }
                   2641:
                   2642: #ifdef MALLOC_DEBUG
                   2643:        arena->magic = ARENA_MAGIC;
                   2644: #endif
                   2645:
                   2646:        return (false);
                   2647: }
                   2648:
                   2649: /* Create a new arena and insert it into the arenas array at index ind. */
                   2650: static arena_t *
                   2651: arenas_extend(unsigned ind)
                   2652: {
                   2653:        arena_t *ret;
                   2654:
                   2655:        /* Allocate enough space for trailing bins. */
                   2656:        ret = (arena_t *)base_alloc(sizeof(arena_t)
                   2657:            + (sizeof(arena_bin_t) * (ntbins + nqbins + nsbins - 1)));
                   2658:        if (ret != NULL && arena_new(ret) == false) {
                   2659:                arenas[ind] = ret;
                   2660:                return (ret);
                   2661:        }
                   2662:        /* Only reached if there is an OOM error. */
                   2663:
                   2664:        /*
                   2665:         * OOM here is quite inconvenient to propagate, since dealing with it
                   2666:         * would require a check for failure in the fast path.  Instead, punt
                   2667:         * by using arenas[0].  In practice, this is an extremely unlikely
                   2668:         * failure.
                   2669:         */
                   2670:        _malloc_message(_getprogname(),
                   2671:            ": (malloc) Error initializing arena\n", "", "");
                   2672:        if (opt_abort)
                   2673:                abort();
                   2674:
                   2675:        return (arenas[0]);
                   2676: }
                   2677:
                   2678: /*
                   2679:  * End arena.
                   2680:  */
                   2681: /******************************************************************************/
                   2682: /*
                   2683:  * Begin general internal functions.
                   2684:  */
                   2685:
                   2686: static void *
                   2687: huge_malloc(size_t size)
                   2688: {
                   2689:        void *ret;
                   2690:        size_t csize;
                   2691:        chunk_node_t *node;
                   2692:
                   2693:        /* Allocate one or more contiguous chunks for this request. */
                   2694:
                   2695:        csize = CHUNK_CEILING(size);
                   2696:        if (csize == 0) {
                   2697:                /* size is large enough to cause size_t wrap-around. */
                   2698:                return (NULL);
                   2699:        }
                   2700:
                   2701:        /* Allocate a chunk node with which to track the chunk. */
                   2702:        node = base_chunk_node_alloc();
                   2703:        if (node == NULL)
                   2704:                return (NULL);
                   2705:
                   2706:        ret = chunk_alloc(csize);
                   2707:        if (ret == NULL) {
                   2708:                base_chunk_node_dealloc(node);
                   2709:                return (NULL);
                   2710:        }
                   2711:
                   2712:        /* Insert node into huge. */
                   2713:        node->chunk = ret;
                   2714:        node->size = csize;
                   2715:
                   2716:        malloc_mutex_lock(&chunks_mtx);
                   2717:        RB_INSERT(chunk_tree_s, &huge, node);
                   2718: #ifdef MALLOC_STATS
                   2719:        huge_nmalloc++;
                   2720:        huge_allocated += csize;
                   2721: #endif
                   2722:        malloc_mutex_unlock(&chunks_mtx);
                   2723:
                   2724:        if (opt_junk)
                   2725:                memset(ret, 0xa5, csize);
                   2726:        else if (opt_zero)
                   2727:                memset(ret, 0, csize);
                   2728:
                   2729:        return (ret);
                   2730: }
                   2731:
                   2732: /* Only handles large allocations that require more than chunk alignment. */
                   2733: static void *
                   2734: huge_palloc(size_t alignment, size_t size)
                   2735: {
                   2736:        void *ret;
                   2737:        size_t alloc_size, chunk_size, offset;
                   2738:        chunk_node_t *node;
                   2739:
                   2740:        /*
                   2741:         * This allocation requires alignment that is even larger than chunk
                   2742:         * alignment.  This means that huge_malloc() isn't good enough.
                   2743:         *
                   2744:         * Allocate almost twice as many chunks as are demanded by the size or
                   2745:         * alignment, in order to assure the alignment can be achieved, then
                   2746:         * unmap leading and trailing chunks.
                   2747:         */
                   2748:        assert(alignment >= chunksize);
                   2749:
                   2750:        chunk_size = CHUNK_CEILING(size);
                   2751:
                   2752:        if (size >= alignment)
                   2753:                alloc_size = chunk_size + alignment - chunksize;
                   2754:        else
                   2755:                alloc_size = (alignment << 1) - chunksize;
                   2756:
                   2757:        /* Allocate a chunk node with which to track the chunk. */
                   2758:        node = base_chunk_node_alloc();
                   2759:        if (node == NULL)
                   2760:                return (NULL);
                   2761:
                   2762:        ret = chunk_alloc(alloc_size);
                   2763:        if (ret == NULL) {
                   2764:                base_chunk_node_dealloc(node);
                   2765:                return (NULL);
                   2766:        }
                   2767:
                   2768:        offset = (uintptr_t)ret & (alignment - 1);
                   2769:        assert((offset & chunksize_mask) == 0);
                   2770:        assert(offset < alloc_size);
                   2771:        if (offset == 0) {
                   2772:                /* Trim trailing space. */
                   2773:                chunk_dealloc((void *)((uintptr_t)ret + chunk_size), alloc_size
                   2774:                    - chunk_size);
                   2775:        } else {
                   2776:                size_t trailsize;
                   2777:
                   2778:                /* Trim leading space. */
                   2779:                chunk_dealloc(ret, alignment - offset);
                   2780:
                   2781:                ret = (void *)((uintptr_t)ret + (alignment - offset));
                   2782:
                   2783:                trailsize = alloc_size - (alignment - offset) - chunk_size;
                   2784:                if (trailsize != 0) {
                   2785:                    /* Trim trailing space. */
                   2786:                    assert(trailsize < alloc_size);
                   2787:                    chunk_dealloc((void *)((uintptr_t)ret + chunk_size),
                   2788:                        trailsize);
                   2789:                }
                   2790:        }
                   2791:
                   2792:        /* Insert node into huge. */
                   2793:        node->chunk = ret;
                   2794:        node->size = chunk_size;
                   2795:
                   2796:        malloc_mutex_lock(&chunks_mtx);
                   2797:        RB_INSERT(chunk_tree_s, &huge, node);
                   2798: #ifdef MALLOC_STATS
                   2799:        huge_nmalloc++;
                   2800:        huge_allocated += chunk_size;
                   2801: #endif
                   2802:        malloc_mutex_unlock(&chunks_mtx);
                   2803:
                   2804:        if (opt_junk)
                   2805:                memset(ret, 0xa5, chunk_size);
                   2806:        else if (opt_zero)
                   2807:                memset(ret, 0, chunk_size);
                   2808:
                   2809:        return (ret);
                   2810: }
                   2811:
                   2812: static void *
                   2813: huge_ralloc(void *ptr, size_t size, size_t oldsize)
                   2814: {
                   2815:        void *ret;
                   2816:
                   2817:        /* Avoid moving the allocation if the size class would not change. */
                   2818:        if (oldsize > arena_maxclass &&
                   2819:            CHUNK_CEILING(size) == CHUNK_CEILING(oldsize)) {
                   2820:                if (opt_junk && size < oldsize) {
                   2821:                        memset((void *)((uintptr_t)ptr + size), 0x5a, oldsize
                   2822:                            - size);
                   2823:                } else if (opt_zero && size > oldsize) {
                   2824:                        memset((void *)((uintptr_t)ptr + oldsize), 0, size
                   2825:                            - oldsize);
                   2826:                }
                   2827:                return (ptr);
                   2828:        }
                   2829:
                   2830:        /*
                   2831:         * If we get here, then size and oldsize are different enough that we
                   2832:         * need to use a different size class.  In that case, fall back to
                   2833:         * allocating new space and copying.
                   2834:         */
                   2835:        ret = huge_malloc(size);
                   2836:        if (ret == NULL)
                   2837:                return (NULL);
                   2838:
                   2839:        if (CHUNK_ADDR2BASE(ptr) == ptr) {
                   2840:                /* The old allocation is a chunk. */
                   2841:                if (size < oldsize)
                   2842:                        memcpy(ret, ptr, size);
                   2843:                else
                   2844:                        memcpy(ret, ptr, oldsize);
                   2845:        } else {
                   2846:                /* The old allocation is a region. */
                   2847:                assert(oldsize < size);
                   2848:                memcpy(ret, ptr, oldsize);
                   2849:        }
                   2850:        idalloc(ptr);
                   2851:        return (ret);
                   2852: }
                   2853:
                   2854: static void
                   2855: huge_dalloc(void *ptr)
                   2856: {
                   2857:        chunk_node_t key;
                   2858:        chunk_node_t *node;
                   2859:
                   2860:        malloc_mutex_lock(&chunks_mtx);
                   2861:
                   2862:        /* Extract from tree of huge allocations. */
                   2863:        key.chunk = ptr;
1.2       ad       2864:        /* LINTED */
1.1       ad       2865:        node = RB_FIND(chunk_tree_s, &huge, &key);
                   2866:        assert(node != NULL);
                   2867:        assert(node->chunk == ptr);
1.2       ad       2868:        /* LINTED */
1.1       ad       2869:        RB_REMOVE(chunk_tree_s, &huge, node);
                   2870:
                   2871: #ifdef MALLOC_STATS
                   2872:        huge_ndalloc++;
                   2873:        huge_allocated -= node->size;
                   2874: #endif
                   2875:
                   2876:        malloc_mutex_unlock(&chunks_mtx);
                   2877:
                   2878:        /* Unmap chunk. */
                   2879: #ifdef USE_BRK
                   2880:        if (opt_junk)
                   2881:                memset(node->chunk, 0x5a, node->size);
                   2882: #endif
                   2883:        chunk_dealloc(node->chunk, node->size);
                   2884:
                   2885:        base_chunk_node_dealloc(node);
                   2886: }
                   2887:
                   2888: static void *
                   2889: imalloc(size_t size)
                   2890: {
                   2891:        void *ret;
                   2892:
                   2893:        assert(size != 0);
                   2894:
                   2895:        if (size <= arena_maxclass)
                   2896:                ret = arena_malloc(choose_arena(), size);
                   2897:        else
                   2898:                ret = huge_malloc(size);
                   2899:
                   2900:        return (ret);
                   2901: }
                   2902:
                   2903: static void *
                   2904: ipalloc(size_t alignment, size_t size)
                   2905: {
                   2906:        void *ret;
                   2907:        size_t ceil_size;
                   2908:
                   2909:        /*
                   2910:         * Round size up to the nearest multiple of alignment.
                   2911:         *
                   2912:         * This done, we can take advantage of the fact that for each small
                   2913:         * size class, every object is aligned at the smallest power of two
                   2914:         * that is non-zero in the base two representation of the size.  For
                   2915:         * example:
                   2916:         *
                   2917:         *   Size |   Base 2 | Minimum alignment
                   2918:         *   -----+----------+------------------
                   2919:         *     96 |  1100000 |  32
                   2920:         *    144 | 10100000 |  32
                   2921:         *    192 | 11000000 |  64
                   2922:         *
                   2923:         * Depending on runtime settings, it is possible that arena_malloc()
                   2924:         * will further round up to a power of two, but that never causes
                   2925:         * correctness issues.
                   2926:         */
                   2927:        ceil_size = (size + (alignment - 1)) & (-alignment);
                   2928:        /*
                   2929:         * (ceil_size < size) protects against the combination of maximal
                   2930:         * alignment and size greater than maximal alignment.
                   2931:         */
                   2932:        if (ceil_size < size) {
                   2933:                /* size_t overflow. */
                   2934:                return (NULL);
                   2935:        }
                   2936:
                   2937:        if (ceil_size <= pagesize || (alignment <= pagesize
                   2938:            && ceil_size <= arena_maxclass))
                   2939:                ret = arena_malloc(choose_arena(), ceil_size);
                   2940:        else {
                   2941:                size_t run_size;
                   2942:
                   2943:                /*
                   2944:                 * We can't achieve sub-page alignment, so round up alignment
                   2945:                 * permanently; it makes later calculations simpler.
                   2946:                 */
                   2947:                alignment = PAGE_CEILING(alignment);
                   2948:                ceil_size = PAGE_CEILING(size);
                   2949:                /*
                   2950:                 * (ceil_size < size) protects against very large sizes within
                   2951:                 * pagesize of SIZE_T_MAX.
                   2952:                 *
                   2953:                 * (ceil_size + alignment < ceil_size) protects against the
                   2954:                 * combination of maximal alignment and ceil_size large enough
                   2955:                 * to cause overflow.  This is similar to the first overflow
                   2956:                 * check above, but it needs to be repeated due to the new
                   2957:                 * ceil_size value, which may now be *equal* to maximal
                   2958:                 * alignment, whereas before we only detected overflow if the
                   2959:                 * original size was *greater* than maximal alignment.
                   2960:                 */
                   2961:                if (ceil_size < size || ceil_size + alignment < ceil_size) {
                   2962:                        /* size_t overflow. */
                   2963:                        return (NULL);
                   2964:                }
                   2965:
                   2966:                /*
                   2967:                 * Calculate the size of the over-size run that arena_palloc()
                   2968:                 * would need to allocate in order to guarantee the alignment.
                   2969:                 */
                   2970:                if (ceil_size >= alignment)
                   2971:                        run_size = ceil_size + alignment - pagesize;
                   2972:                else {
                   2973:                        /*
                   2974:                         * It is possible that (alignment << 1) will cause
                   2975:                         * overflow, but it doesn't matter because we also
                   2976:                         * subtract pagesize, which in the case of overflow
                   2977:                         * leaves us with a very large run_size.  That causes
                   2978:                         * the first conditional below to fail, which means
                   2979:                         * that the bogus run_size value never gets used for
                   2980:                         * anything important.
                   2981:                         */
                   2982:                        run_size = (alignment << 1) - pagesize;
                   2983:                }
                   2984:
                   2985:                if (run_size <= arena_maxclass) {
                   2986:                        ret = arena_palloc(choose_arena(), alignment, ceil_size,
                   2987:                            run_size);
                   2988:                } else if (alignment <= chunksize)
                   2989:                        ret = huge_malloc(ceil_size);
                   2990:                else
                   2991:                        ret = huge_palloc(alignment, ceil_size);
                   2992:        }
                   2993:
                   2994:        assert(((uintptr_t)ret & (alignment - 1)) == 0);
                   2995:        return (ret);
                   2996: }
                   2997:
                   2998: static void *
                   2999: icalloc(size_t size)
                   3000: {
                   3001:        void *ret;
                   3002:
                   3003:        if (size <= arena_maxclass) {
                   3004:                ret = arena_malloc(choose_arena(), size);
                   3005:                if (ret == NULL)
                   3006:                        return (NULL);
                   3007:                memset(ret, 0, size);
                   3008:        } else {
                   3009:                /*
                   3010:                 * The virtual memory system provides zero-filled pages, so
                   3011:                 * there is no need to do so manually, unless opt_junk is
                   3012:                 * enabled, in which case huge_malloc() fills huge allocations
                   3013:                 * with junk.
                   3014:                 */
                   3015:                ret = huge_malloc(size);
                   3016:                if (ret == NULL)
                   3017:                        return (NULL);
                   3018:
                   3019:                if (opt_junk)
                   3020:                        memset(ret, 0, size);
                   3021: #ifdef USE_BRK
                   3022:                else if ((uintptr_t)ret >= (uintptr_t)brk_base
                   3023:                    && (uintptr_t)ret < (uintptr_t)brk_max) {
                   3024:                        /*
                   3025:                         * This may be a re-used brk chunk.  Therefore, zero
                   3026:                         * the memory.
                   3027:                         */
                   3028:                        memset(ret, 0, size);
                   3029:                }
                   3030: #endif
                   3031:        }
                   3032:
                   3033:        return (ret);
                   3034: }
                   3035:
                   3036: static size_t
                   3037: isalloc(const void *ptr)
                   3038: {
                   3039:        size_t ret;
                   3040:        arena_chunk_t *chunk;
                   3041:
                   3042:        assert(ptr != NULL);
                   3043:
                   3044:        chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
                   3045:        if (chunk != ptr) {
                   3046:                /* Region. */
                   3047:                assert(chunk->arena->magic == ARENA_MAGIC);
                   3048:
                   3049:                ret = arena_salloc(ptr);
                   3050:        } else {
                   3051:                chunk_node_t *node, key;
                   3052:
                   3053:                /* Chunk (huge allocation). */
                   3054:
                   3055:                malloc_mutex_lock(&chunks_mtx);
                   3056:
                   3057:                /* Extract from tree of huge allocations. */
                   3058:                key.chunk = __DECONST(void *, ptr);
1.2       ad       3059:                /* LINTED */
1.1       ad       3060:                node = RB_FIND(chunk_tree_s, &huge, &key);
                   3061:                assert(node != NULL);
                   3062:
                   3063:                ret = node->size;
                   3064:
                   3065:                malloc_mutex_unlock(&chunks_mtx);
                   3066:        }
                   3067:
                   3068:        return (ret);
                   3069: }
                   3070:
                   3071: static void *
                   3072: iralloc(void *ptr, size_t size)
                   3073: {
                   3074:        void *ret;
                   3075:        size_t oldsize;
                   3076:
                   3077:        assert(ptr != NULL);
                   3078:        assert(size != 0);
                   3079:
                   3080:        oldsize = isalloc(ptr);
                   3081:
                   3082:        if (size <= arena_maxclass)
                   3083:                ret = arena_ralloc(ptr, size, oldsize);
                   3084:        else
                   3085:                ret = huge_ralloc(ptr, size, oldsize);
                   3086:
                   3087:        return (ret);
                   3088: }
                   3089:
                   3090: static void
                   3091: idalloc(void *ptr)
                   3092: {
                   3093:        arena_chunk_t *chunk;
                   3094:
                   3095:        assert(ptr != NULL);
                   3096:
                   3097:        chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
                   3098:        if (chunk != ptr) {
                   3099:                /* Region. */
                   3100:                arena_dalloc(chunk->arena, chunk, ptr);
                   3101:        } else
                   3102:                huge_dalloc(ptr);
                   3103: }
                   3104:
                   3105: static void
                   3106: malloc_print_stats(void)
                   3107: {
                   3108:
                   3109:        if (opt_print_stats) {
                   3110:                char s[UMAX2S_BUFSIZE];
                   3111:                _malloc_message("___ Begin malloc statistics ___\n", "", "",
                   3112:                    "");
                   3113:                _malloc_message("Assertions ",
                   3114: #ifdef NDEBUG
                   3115:                    "disabled",
                   3116: #else
                   3117:                    "enabled",
                   3118: #endif
                   3119:                    "\n", "");
                   3120:                _malloc_message("Boolean MALLOC_OPTIONS: ",
                   3121:                    opt_abort ? "A" : "a",
                   3122:                    opt_junk ? "J" : "j",
                   3123:                    opt_hint ? "H" : "h");
                   3124:                _malloc_message(opt_utrace ? "PU" : "Pu",
                   3125:                    opt_sysv ? "V" : "v",
                   3126:                    opt_xmalloc ? "X" : "x",
                   3127:                    opt_zero ? "Z\n" : "z\n");
                   3128:
                   3129:                _malloc_message("CPUs: ", umax2s(ncpus, s), "\n", "");
                   3130:                _malloc_message("Max arenas: ", umax2s(narenas, s), "\n", "");
                   3131:                _malloc_message("Pointer size: ", umax2s(sizeof(void *), s),
                   3132:                    "\n", "");
                   3133:                _malloc_message("Quantum size: ", umax2s(quantum, s), "\n", "");
                   3134:                _malloc_message("Max small size: ", umax2s(small_max, s), "\n",
                   3135:                    "");
                   3136:
                   3137:                _malloc_message("Chunk size: ", umax2s(chunksize, s), "", "");
                   3138:                _malloc_message(" (2^", umax2s(opt_chunk_2pow, s), ")\n", "");
                   3139:
                   3140: #ifdef MALLOC_STATS
                   3141:                {
                   3142:                        size_t allocated, mapped;
                   3143:                        unsigned i;
                   3144:                        arena_t *arena;
                   3145:
                   3146:                        /* Calculate and print allocated/mapped stats. */
                   3147:
                   3148:                        /* arenas. */
                   3149:                        for (i = 0, allocated = 0; i < narenas; i++) {
                   3150:                                if (arenas[i] != NULL) {
                   3151:                                        malloc_mutex_lock(&arenas[i]->mtx);
                   3152:                                        allocated +=
                   3153:                                            arenas[i]->stats.allocated_small;
                   3154:                                        allocated +=
                   3155:                                            arenas[i]->stats.allocated_large;
                   3156:                                        malloc_mutex_unlock(&arenas[i]->mtx);
                   3157:                                }
                   3158:                        }
                   3159:
                   3160:                        /* huge/base. */
                   3161:                        malloc_mutex_lock(&chunks_mtx);
                   3162:                        allocated += huge_allocated;
                   3163:                        mapped = stats_chunks.curchunks * chunksize;
                   3164:                        malloc_mutex_unlock(&chunks_mtx);
                   3165:
                   3166:                        malloc_mutex_lock(&base_mtx);
                   3167:                        mapped += base_mapped;
                   3168:                        malloc_mutex_unlock(&base_mtx);
                   3169:
                   3170:                        malloc_printf("Allocated: %zu, mapped: %zu\n",
                   3171:                            allocated, mapped);
                   3172:
                   3173:                        /* Print chunk stats. */
                   3174:                        {
                   3175:                                chunk_stats_t chunks_stats;
                   3176:
                   3177:                                malloc_mutex_lock(&chunks_mtx);
                   3178:                                chunks_stats = stats_chunks;
                   3179:                                malloc_mutex_unlock(&chunks_mtx);
                   3180:
                   3181:                                malloc_printf("chunks: nchunks   "
                   3182:                                    "highchunks    curchunks\n");
                   3183:                                malloc_printf("  %13llu%13lu%13lu\n",
                   3184:                                    chunks_stats.nchunks,
                   3185:                                    chunks_stats.highchunks,
                   3186:                                    chunks_stats.curchunks);
                   3187:                        }
                   3188:
                   3189:                        /* Print chunk stats. */
                   3190:                        malloc_printf(
                   3191:                            "huge: nmalloc      ndalloc    allocated\n");
                   3192:                        malloc_printf(" %12llu %12llu %12zu\n",
                   3193:                            huge_nmalloc, huge_ndalloc, huge_allocated
                   3194:                            * chunksize);
                   3195:
                   3196:                        /* Print stats for each arena. */
                   3197:                        for (i = 0; i < narenas; i++) {
                   3198:                                arena = arenas[i];
                   3199:                                if (arena != NULL) {
                   3200:                                        malloc_printf(
1.2       ad       3201:                                            "\narenas[%u] @ %p\n", i, arena);
1.1       ad       3202:                                        malloc_mutex_lock(&arena->mtx);
                   3203:                                        stats_print(arena);
                   3204:                                        malloc_mutex_unlock(&arena->mtx);
                   3205:                                }
                   3206:                        }
                   3207:                }
                   3208: #endif /* #ifdef MALLOC_STATS */
                   3209:                _malloc_message("--- End malloc statistics ---\n", "", "", "");
                   3210:        }
                   3211: }
                   3212:
                   3213: /*
                   3214:  * FreeBSD's pthreads implementation calls malloc(3), so the malloc
                   3215:  * implementation has to take pains to avoid infinite recursion during
                   3216:  * initialization.
                   3217:  */
                   3218: static inline bool
                   3219: malloc_init(void)
                   3220: {
                   3221:
                   3222:        if (malloc_initialized == false)
                   3223:                return (malloc_init_hard());
                   3224:
                   3225:        return (false);
                   3226: }
                   3227:
                   3228: static bool
                   3229: malloc_init_hard(void)
                   3230: {
                   3231:        unsigned i, j;
                   3232:        int linklen;
                   3233:        char buf[PATH_MAX + 1];
1.2       ad       3234:        const char *opts = "";
1.1       ad       3235:
                   3236:        malloc_mutex_lock(&init_lock);
                   3237:        if (malloc_initialized) {
                   3238:                /*
                   3239:                 * Another thread initialized the allocator before this one
                   3240:                 * acquired init_lock.
                   3241:                 */
                   3242:                malloc_mutex_unlock(&init_lock);
                   3243:                return (false);
                   3244:        }
                   3245:
                   3246:        /* Get number of CPUs. */
                   3247:        {
                   3248:                int mib[2];
                   3249:                size_t len;
                   3250:
                   3251:                mib[0] = CTL_HW;
                   3252:                mib[1] = HW_NCPU;
                   3253:                len = sizeof(ncpus);
                   3254:                if (sysctl(mib, 2, &ncpus, &len, (void *) 0, 0) == -1) {
                   3255:                        /* Error. */
                   3256:                        ncpus = 1;
                   3257:                }
                   3258:        }
                   3259:
                   3260:        /* Get page size. */
                   3261:        {
                   3262:                long result;
                   3263:
                   3264:                result = sysconf(_SC_PAGESIZE);
                   3265:                assert(result != -1);
                   3266:                pagesize = (unsigned) result;
                   3267:
                   3268:                /*
                   3269:                 * We assume that pagesize is a power of 2 when calculating
                   3270:                 * pagesize_mask and pagesize_2pow.
                   3271:                 */
                   3272:                assert(((result - 1) & result) == 0);
                   3273:                pagesize_mask = result - 1;
                   3274:                pagesize_2pow = ffs((int)result) - 1;
                   3275:        }
                   3276:
                   3277:        for (i = 0; i < 3; i++) {
                   3278:                /* Get runtime configuration. */
                   3279:                switch (i) {
                   3280:                case 0:
                   3281:                        if ((linklen = readlink("/etc/malloc.conf", buf,
                   3282:                                                sizeof(buf) - 1)) != -1) {
                   3283:                                /*
                   3284:                                 * Use the contents of the "/etc/malloc.conf"
                   3285:                                 * symbolic link's name.
                   3286:                                 */
                   3287:                                buf[linklen] = '\0';
                   3288:                                opts = buf;
                   3289:                        } else {
                   3290:                                /* No configuration specified. */
                   3291:                                buf[0] = '\0';
                   3292:                                opts = buf;
                   3293:                        }
                   3294:                        break;
                   3295:                case 1:
                   3296:                        if (issetugid() == 0 && (opts =
                   3297:                            getenv("MALLOC_OPTIONS")) != NULL) {
                   3298:                                /*
                   3299:                                 * Do nothing; opts is already initialized to
                   3300:                                 * the value of the MALLOC_OPTIONS environment
                   3301:                                 * variable.
                   3302:                                 */
                   3303:                        } else {
                   3304:                                /* No configuration specified. */
                   3305:                                buf[0] = '\0';
                   3306:                                opts = buf;
                   3307:                        }
                   3308:                        break;
                   3309:                case 2:
                   3310:                        if (_malloc_options != NULL) {
                   3311:                            /*
                   3312:                             * Use options that were compiled into the program.
                   3313:                             */
                   3314:                            opts = _malloc_options;
                   3315:                        } else {
                   3316:                                /* No configuration specified. */
                   3317:                                buf[0] = '\0';
                   3318:                                opts = buf;
                   3319:                        }
                   3320:                        break;
                   3321:                default:
                   3322:                        /* NOTREACHED */
                   3323:                        assert(false);
                   3324:                }
                   3325:
                   3326:                for (j = 0; opts[j] != '\0'; j++) {
                   3327:                        switch (opts[j]) {
                   3328:                        case 'a':
                   3329:                                opt_abort = false;
                   3330:                                break;
                   3331:                        case 'A':
                   3332:                                opt_abort = true;
                   3333:                                break;
                   3334:                        case 'h':
                   3335:                                opt_hint = false;
                   3336:                                break;
                   3337:                        case 'H':
                   3338:                                opt_hint = true;
                   3339:                                break;
                   3340:                        case 'j':
                   3341:                                opt_junk = false;
                   3342:                                break;
                   3343:                        case 'J':
                   3344:                                opt_junk = true;
                   3345:                                break;
                   3346:                        case 'k':
                   3347:                                /*
                   3348:                                 * Chunks always require at least one header
                   3349:                                 * page, so chunks can never be smaller than
                   3350:                                 * two pages.
                   3351:                                 */
                   3352:                                if (opt_chunk_2pow > pagesize_2pow + 1)
                   3353:                                        opt_chunk_2pow--;
                   3354:                                break;
                   3355:                        case 'K':
                   3356:                                /*
                   3357:                                 * There must be fewer pages in a chunk than
                   3358:                                 * can be recorded by the pos field of
                   3359:                                 * arena_chunk_map_t, in order to make POS_FREE
                   3360:                                 * special.
                   3361:                                 */
                   3362:                                if (opt_chunk_2pow - pagesize_2pow
                   3363:                                    < (sizeof(uint32_t) << 3) - 1)
                   3364:                                        opt_chunk_2pow++;
                   3365:                                break;
                   3366:                        case 'n':
                   3367:                                opt_narenas_lshift--;
                   3368:                                break;
                   3369:                        case 'N':
                   3370:                                opt_narenas_lshift++;
                   3371:                                break;
                   3372:                        case 'p':
                   3373:                                opt_print_stats = false;
                   3374:                                break;
                   3375:                        case 'P':
                   3376:                                opt_print_stats = true;
                   3377:                                break;
                   3378:                        case 'q':
                   3379:                                if (opt_quantum_2pow > QUANTUM_2POW_MIN)
                   3380:                                        opt_quantum_2pow--;
                   3381:                                break;
                   3382:                        case 'Q':
                   3383:                                if (opt_quantum_2pow < pagesize_2pow - 1)
                   3384:                                        opt_quantum_2pow++;
                   3385:                                break;
                   3386:                        case 's':
                   3387:                                if (opt_small_max_2pow > QUANTUM_2POW_MIN)
                   3388:                                        opt_small_max_2pow--;
                   3389:                                break;
                   3390:                        case 'S':
                   3391:                                if (opt_small_max_2pow < pagesize_2pow - 1)
                   3392:                                        opt_small_max_2pow++;
                   3393:                                break;
                   3394:                        case 'u':
                   3395:                                opt_utrace = false;
                   3396:                                break;
                   3397:                        case 'U':
                   3398:                                opt_utrace = true;
                   3399:                                break;
                   3400:                        case 'v':
                   3401:                                opt_sysv = false;
                   3402:                                break;
                   3403:                        case 'V':
                   3404:                                opt_sysv = true;
                   3405:                                break;
                   3406:                        case 'x':
                   3407:                                opt_xmalloc = false;
                   3408:                                break;
                   3409:                        case 'X':
                   3410:                                opt_xmalloc = true;
                   3411:                                break;
                   3412:                        case 'z':
                   3413:                                opt_zero = false;
                   3414:                                break;
                   3415:                        case 'Z':
                   3416:                                opt_zero = true;
                   3417:                                break;
                   3418:                        default: {
                   3419:                                char cbuf[2];
                   3420:
                   3421:                                cbuf[0] = opts[j];
                   3422:                                cbuf[1] = '\0';
                   3423:                                _malloc_message(_getprogname(),
                   3424:                                    ": (malloc) Unsupported character in "
                   3425:                                    "malloc options: '", cbuf, "'\n");
                   3426:                        }
                   3427:                        }
                   3428:                }
                   3429:        }
                   3430:
                   3431:        /* Take care to call atexit() only once. */
                   3432:        if (opt_print_stats) {
                   3433:                /* Print statistics at exit. */
                   3434:                atexit(malloc_print_stats);
                   3435:        }
                   3436:
                   3437:        /* Set variables according to the value of opt_small_max_2pow. */
                   3438:        if (opt_small_max_2pow < opt_quantum_2pow)
                   3439:                opt_small_max_2pow = opt_quantum_2pow;
                   3440:        small_max = (1 << opt_small_max_2pow);
                   3441:
                   3442:        /* Set bin-related variables. */
                   3443:        bin_maxclass = (pagesize >> 1);
                   3444:        assert(opt_quantum_2pow >= TINY_MIN_2POW);
                   3445:        ntbins = opt_quantum_2pow - TINY_MIN_2POW;
                   3446:        assert(ntbins <= opt_quantum_2pow);
                   3447:        nqbins = (small_max >> opt_quantum_2pow);
                   3448:        nsbins = pagesize_2pow - opt_small_max_2pow - 1;
                   3449:
                   3450:        /* Set variables according to the value of opt_quantum_2pow. */
                   3451:        quantum = (1 << opt_quantum_2pow);
                   3452:        quantum_mask = quantum - 1;
                   3453:        if (ntbins > 0)
                   3454:                small_min = (quantum >> 1) + 1;
                   3455:        else
                   3456:                small_min = 1;
                   3457:        assert(small_min <= quantum);
                   3458:
                   3459:        /* Set variables according to the value of opt_chunk_2pow. */
                   3460:        chunksize = (1LU << opt_chunk_2pow);
                   3461:        chunksize_mask = chunksize - 1;
                   3462:        chunk_npages = (chunksize >> pagesize_2pow);
                   3463:        {
                   3464:                unsigned header_size;
                   3465:
                   3466:                header_size = sizeof(arena_chunk_t) + (sizeof(arena_chunk_map_t)
                   3467:                    * (chunk_npages - 1));
                   3468:                arena_chunk_header_npages = (header_size >> pagesize_2pow);
                   3469:                if ((header_size & pagesize_mask) != 0)
                   3470:                        arena_chunk_header_npages++;
                   3471:        }
                   3472:        arena_maxclass = chunksize - (arena_chunk_header_npages <<
                   3473:            pagesize_2pow);
                   3474:
                   3475:        UTRACE(0, 0, 0);
                   3476:
                   3477: #ifdef MALLOC_STATS
                   3478:        memset(&stats_chunks, 0, sizeof(chunk_stats_t));
                   3479: #endif
                   3480:
                   3481:        /* Various sanity checks that regard configuration. */
                   3482:        assert(quantum >= sizeof(void *));
                   3483:        assert(quantum <= pagesize);
                   3484:        assert(chunksize >= pagesize);
                   3485:        assert(quantum * 4 <= chunksize);
                   3486:
                   3487:        /* Initialize chunks data. */
                   3488:        malloc_mutex_init(&chunks_mtx);
                   3489:        RB_INIT(&huge);
                   3490: #ifdef USE_BRK
                   3491:        malloc_mutex_init(&brk_mtx);
                   3492:        brk_base = sbrk(0);
                   3493:        brk_prev = brk_base;
                   3494:        brk_max = brk_base;
                   3495: #endif
                   3496: #ifdef MALLOC_STATS
                   3497:        huge_nmalloc = 0;
                   3498:        huge_ndalloc = 0;
                   3499:        huge_allocated = 0;
                   3500: #endif
                   3501:        RB_INIT(&old_chunks);
                   3502:
                   3503:        /* Initialize base allocation data structures. */
                   3504: #ifdef MALLOC_STATS
                   3505:        base_mapped = 0;
                   3506: #endif
                   3507: #ifdef USE_BRK
                   3508:        /*
                   3509:         * Allocate a base chunk here, since it doesn't actually have to be
                   3510:         * chunk-aligned.  Doing this before allocating any other chunks allows
                   3511:         * the use of space that would otherwise be wasted.
                   3512:         */
                   3513:        base_pages_alloc(0);
                   3514: #endif
                   3515:        base_chunk_nodes = NULL;
                   3516:        malloc_mutex_init(&base_mtx);
                   3517:
                   3518:        if (ncpus > 1) {
                   3519:                /*
                   3520:                 * For SMP systems, create four times as many arenas as there
                   3521:                 * are CPUs by default.
                   3522:                 */
                   3523:                opt_narenas_lshift += 2;
                   3524:        }
                   3525:
1.2       ad       3526: #ifdef NO_TLS
                   3527:        /* Initialize arena key. */
                   3528:        (void)thr_keycreate(&arenas_map_key, NULL);
                   3529: #endif
                   3530:
1.1       ad       3531:        /* Determine how many arenas to use. */
                   3532:        narenas = ncpus;
                   3533:        if (opt_narenas_lshift > 0) {
                   3534:                if ((narenas << opt_narenas_lshift) > narenas)
                   3535:                        narenas <<= opt_narenas_lshift;
                   3536:                /*
                   3537:                 * Make sure not to exceed the limits of what base_malloc()
                   3538:                 * can handle.
                   3539:                 */
                   3540:                if (narenas * sizeof(arena_t *) > chunksize)
                   3541:                        narenas = chunksize / sizeof(arena_t *);
                   3542:        } else if (opt_narenas_lshift < 0) {
                   3543:                if ((narenas << opt_narenas_lshift) < narenas)
                   3544:                        narenas <<= opt_narenas_lshift;
                   3545:                /* Make sure there is at least one arena. */
                   3546:                if (narenas == 0)
                   3547:                        narenas = 1;
                   3548:        }
                   3549:
                   3550:        next_arena = 0;
                   3551:
                   3552:        /* Allocate and initialize arenas. */
                   3553:        arenas = (arena_t **)base_alloc(sizeof(arena_t *) * narenas);
                   3554:        if (arenas == NULL) {
                   3555:                malloc_mutex_unlock(&init_lock);
                   3556:                return (true);
                   3557:        }
                   3558:        /*
                   3559:         * Zero the array.  In practice, this should always be pre-zeroed,
                   3560:         * since it was just mmap()ed, but let's be sure.
                   3561:         */
                   3562:        memset(arenas, 0, sizeof(arena_t *) * narenas);
                   3563:
                   3564:        /*
                   3565:         * Initialize one arena here.  The rest are lazily created in
                   3566:         * arena_choose_hard().
                   3567:         */
                   3568:        arenas_extend(0);
                   3569:        if (arenas[0] == NULL) {
                   3570:                malloc_mutex_unlock(&init_lock);
                   3571:                return (true);
                   3572:        }
                   3573:
                   3574:        malloc_mutex_init(&arenas_mtx);
                   3575:
                   3576:        malloc_initialized = true;
                   3577:        malloc_mutex_unlock(&init_lock);
                   3578:        return (false);
                   3579: }
                   3580:
                   3581: /*
                   3582:  * End general internal functions.
                   3583:  */
                   3584: /******************************************************************************/
                   3585: /*
                   3586:  * Begin malloc(3)-compatible functions.
                   3587:  */
                   3588:
                   3589: void *
                   3590: malloc(size_t size)
                   3591: {
                   3592:        void *ret;
                   3593:
                   3594:        if (malloc_init()) {
                   3595:                ret = NULL;
                   3596:                goto RETURN;
                   3597:        }
                   3598:
                   3599:        if (size == 0) {
                   3600:                if (opt_sysv == false)
                   3601:                        size = 1;
                   3602:                else {
                   3603:                        ret = NULL;
                   3604:                        goto RETURN;
                   3605:                }
                   3606:        }
                   3607:
                   3608:        ret = imalloc(size);
                   3609:
                   3610: RETURN:
                   3611:        if (ret == NULL) {
                   3612:                if (opt_xmalloc) {
                   3613:                        _malloc_message(_getprogname(),
                   3614:                            ": (malloc) Error in malloc(): out of memory\n", "",
                   3615:                            "");
                   3616:                        abort();
                   3617:                }
                   3618:                errno = ENOMEM;
                   3619:        }
                   3620:
                   3621:        UTRACE(0, size, ret);
                   3622:        return (ret);
                   3623: }
                   3624:
1.2       ad       3625: /* XXXAD */
                   3626: int    posix_memalign(void **memptr, size_t alignment, size_t size);
                   3627:
1.1       ad       3628: int
                   3629: posix_memalign(void **memptr, size_t alignment, size_t size)
                   3630: {
                   3631:        int ret;
                   3632:        void *result;
                   3633:
                   3634:        if (malloc_init())
                   3635:                result = NULL;
                   3636:        else {
                   3637:                /* Make sure that alignment is a large enough power of 2. */
                   3638:                if (((alignment - 1) & alignment) != 0
                   3639:                    || alignment < sizeof(void *)) {
                   3640:                        if (opt_xmalloc) {
                   3641:                                _malloc_message(_getprogname(),
                   3642:                                    ": (malloc) Error in posix_memalign(): "
                   3643:                                    "invalid alignment\n", "", "");
                   3644:                                abort();
                   3645:                        }
                   3646:                        result = NULL;
                   3647:                        ret = EINVAL;
                   3648:                        goto RETURN;
                   3649:                }
                   3650:
                   3651:                result = ipalloc(alignment, size);
                   3652:        }
                   3653:
                   3654:        if (result == NULL) {
                   3655:                if (opt_xmalloc) {
                   3656:                        _malloc_message(_getprogname(),
                   3657:                        ": (malloc) Error in posix_memalign(): out of memory\n",
                   3658:                        "", "");
                   3659:                        abort();
                   3660:                }
                   3661:                ret = ENOMEM;
                   3662:                goto RETURN;
                   3663:        }
                   3664:
                   3665:        *memptr = result;
                   3666:        ret = 0;
                   3667:
                   3668: RETURN:
                   3669:        UTRACE(0, size, result);
                   3670:        return (ret);
                   3671: }
                   3672:
                   3673: void *
                   3674: calloc(size_t num, size_t size)
                   3675: {
                   3676:        void *ret;
                   3677:        size_t num_size;
                   3678:
                   3679:        if (malloc_init()) {
                   3680:                num_size = 0;
                   3681:                ret = NULL;
                   3682:                goto RETURN;
                   3683:        }
                   3684:
                   3685:        num_size = num * size;
                   3686:        if (num_size == 0) {
                   3687:                if ((opt_sysv == false) && ((num == 0) || (size == 0)))
                   3688:                        num_size = 1;
                   3689:                else {
                   3690:                        ret = NULL;
                   3691:                        goto RETURN;
                   3692:                }
                   3693:        /*
                   3694:         * Try to avoid division here.  We know that it isn't possible to
                   3695:         * overflow during multiplication if neither operand uses any of the
                   3696:         * most significant half of the bits in a size_t.
                   3697:         */
1.2       ad       3698:        } else if ((unsigned long long)((num | size) &
                   3699:           ((unsigned long long)SIZE_T_MAX << (sizeof(size_t) << 2))) &&
                   3700:           (num_size / size != num)) {
1.1       ad       3701:                /* size_t overflow. */
                   3702:                ret = NULL;
                   3703:                goto RETURN;
                   3704:        }
                   3705:
                   3706:        ret = icalloc(num_size);
                   3707:
                   3708: RETURN:
                   3709:        if (ret == NULL) {
                   3710:                if (opt_xmalloc) {
                   3711:                        _malloc_message(_getprogname(),
                   3712:                            ": (malloc) Error in calloc(): out of memory\n", "",
                   3713:                            "");
                   3714:                        abort();
                   3715:                }
                   3716:                errno = ENOMEM;
                   3717:        }
                   3718:
                   3719:        UTRACE(0, num_size, ret);
                   3720:        return (ret);
                   3721: }
                   3722:
                   3723: void *
                   3724: realloc(void *ptr, size_t size)
                   3725: {
                   3726:        void *ret;
                   3727:
                   3728:        if (size == 0) {
                   3729:                if (opt_sysv == false)
                   3730:                        size = 1;
                   3731:                else {
                   3732:                        if (ptr != NULL)
                   3733:                                idalloc(ptr);
                   3734:                        ret = NULL;
                   3735:                        goto RETURN;
                   3736:                }
                   3737:        }
                   3738:
                   3739:        if (ptr != NULL) {
                   3740:                assert(malloc_initialized);
                   3741:
                   3742:                ret = iralloc(ptr, size);
                   3743:
                   3744:                if (ret == NULL) {
                   3745:                        if (opt_xmalloc) {
                   3746:                                _malloc_message(_getprogname(),
                   3747:                                    ": (malloc) Error in realloc(): out of "
                   3748:                                    "memory\n", "", "");
                   3749:                                abort();
                   3750:                        }
                   3751:                        errno = ENOMEM;
                   3752:                }
                   3753:        } else {
                   3754:                if (malloc_init())
                   3755:                        ret = NULL;
                   3756:                else
                   3757:                        ret = imalloc(size);
                   3758:
                   3759:                if (ret == NULL) {
                   3760:                        if (opt_xmalloc) {
                   3761:                                _malloc_message(_getprogname(),
                   3762:                                    ": (malloc) Error in realloc(): out of "
                   3763:                                    "memory\n", "", "");
                   3764:                                abort();
                   3765:                        }
                   3766:                        errno = ENOMEM;
                   3767:                }
                   3768:        }
                   3769:
                   3770: RETURN:
                   3771:        UTRACE(ptr, size, ret);
                   3772:        return (ret);
                   3773: }
                   3774:
                   3775: void
                   3776: free(void *ptr)
                   3777: {
                   3778:
                   3779:        UTRACE(ptr, 0, 0);
                   3780:        if (ptr != NULL) {
                   3781:                assert(malloc_initialized);
                   3782:
                   3783:                idalloc(ptr);
                   3784:        }
                   3785: }
                   3786:
                   3787: /*
                   3788:  * End malloc(3)-compatible functions.
                   3789:  */
                   3790: /******************************************************************************/
                   3791: /*
                   3792:  * Begin non-standard functions.
                   3793:  */
1.2       ad       3794: #ifndef __NetBSD__
1.1       ad       3795: size_t
                   3796: malloc_usable_size(const void *ptr)
                   3797: {
                   3798:
                   3799:        assert(ptr != NULL);
                   3800:
                   3801:        return (isalloc(ptr));
                   3802: }
1.2       ad       3803: #endif
1.1       ad       3804:
                   3805: /*
                   3806:  * End non-standard functions.
                   3807:  */
                   3808: /******************************************************************************/
                   3809: /*
                   3810:  * Begin library-private functions, used by threading libraries for protection
                   3811:  * of malloc during fork().  These functions are only called if the program is
                   3812:  * running in threaded mode, so there is no need to check whether the program
                   3813:  * is threaded here.
                   3814:  */
                   3815:
                   3816: void
                   3817: _malloc_prefork(void)
                   3818: {
                   3819:        unsigned i;
                   3820:
                   3821:        /* Acquire all mutexes in a safe order. */
                   3822:
                   3823:        malloc_mutex_lock(&arenas_mtx);
                   3824:        for (i = 0; i < narenas; i++) {
                   3825:                if (arenas[i] != NULL)
                   3826:                        malloc_mutex_lock(&arenas[i]->mtx);
                   3827:        }
                   3828:        malloc_mutex_unlock(&arenas_mtx);
                   3829:
                   3830:        malloc_mutex_lock(&base_mtx);
                   3831:
                   3832:        malloc_mutex_lock(&chunks_mtx);
                   3833: }
                   3834:
                   3835: void
                   3836: _malloc_postfork(void)
                   3837: {
                   3838:        unsigned i;
                   3839:
                   3840:        /* Release all mutexes, now that fork() has completed. */
                   3841:
                   3842:        malloc_mutex_unlock(&chunks_mtx);
                   3843:
                   3844:        malloc_mutex_unlock(&base_mtx);
                   3845:
                   3846:        malloc_mutex_lock(&arenas_mtx);
                   3847:        for (i = 0; i < narenas; i++) {
                   3848:                if (arenas[i] != NULL)
                   3849:                        malloc_mutex_unlock(&arenas[i]->mtx);
                   3850:        }
                   3851:        malloc_mutex_unlock(&arenas_mtx);
                   3852: }
                   3853:
                   3854: /*
                   3855:  * End library-private functions.
                   3856:  */
                   3857: /******************************************************************************/

CVSweb <webmaster@jp.NetBSD.org>