Home | History | Annotate | Line # | Download | only in kern
subr_pool.c revision 1.259
      1 /*	$NetBSD: subr_pool.c,v 1.259 2019/09/23 05:39:59 skrll Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1997, 1999, 2000, 2002, 2007, 2008, 2010, 2014, 2015, 2018
      5  *     The NetBSD Foundation, Inc.
      6  * All rights reserved.
      7  *
      8  * This code is derived from software contributed to The NetBSD Foundation
      9  * by Paul Kranenburg; by Jason R. Thorpe of the Numerical Aerospace
     10  * Simulation Facility, NASA Ames Research Center; by Andrew Doran, and by
     11  * Maxime Villard.
     12  *
     13  * Redistribution and use in source and binary forms, with or without
     14  * modification, are permitted provided that the following conditions
     15  * are met:
     16  * 1. Redistributions of source code must retain the above copyright
     17  *    notice, this list of conditions and the following disclaimer.
     18  * 2. Redistributions in binary form must reproduce the above copyright
     19  *    notice, this list of conditions and the following disclaimer in the
     20  *    documentation and/or other materials provided with the distribution.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     24  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     25  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     26  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     32  * POSSIBILITY OF SUCH DAMAGE.
     33  */
     34 
     35 #include <sys/cdefs.h>
     36 __KERNEL_RCSID(0, "$NetBSD: subr_pool.c,v 1.259 2019/09/23 05:39:59 skrll Exp $");
     37 
     38 #ifdef _KERNEL_OPT
     39 #include "opt_ddb.h"
     40 #include "opt_lockdebug.h"
     41 #include "opt_pool.h"
     42 #include "opt_kleak.h"
     43 #endif
     44 
     45 #include <sys/param.h>
     46 #include <sys/systm.h>
     47 #include <sys/sysctl.h>
     48 #include <sys/bitops.h>
     49 #include <sys/proc.h>
     50 #include <sys/errno.h>
     51 #include <sys/kernel.h>
     52 #include <sys/vmem.h>
     53 #include <sys/pool.h>
     54 #include <sys/syslog.h>
     55 #include <sys/debug.h>
     56 #include <sys/lockdebug.h>
     57 #include <sys/xcall.h>
     58 #include <sys/cpu.h>
     59 #include <sys/atomic.h>
     60 #include <sys/asan.h>
     61 
     62 #include <uvm/uvm_extern.h>
     63 
     64 /*
     65  * Pool resource management utility.
     66  *
     67  * Memory is allocated in pages which are split into pieces according to
     68  * the pool item size. Each page is kept on one of three lists in the
     69  * pool structure: `pr_emptypages', `pr_fullpages' and `pr_partpages',
     70  * for empty, full and partially-full pages respectively. The individual
     71  * pool items are on a linked list headed by `ph_itemlist' in each page
     72  * header. The memory for building the page list is either taken from
     73  * the allocated pages themselves (for small pool items) or taken from
     74  * an internal pool of page headers (`phpool').
     75  */
     76 
     77 /* List of all pools. Non static as needed by 'vmstat -m' */
     78 TAILQ_HEAD(, pool) pool_head = TAILQ_HEAD_INITIALIZER(pool_head);
     79 
     80 /* Private pool for page header structures */
     81 #define	PHPOOL_MAX	8
     82 static struct pool phpool[PHPOOL_MAX];
     83 #define	PHPOOL_FREELIST_NELEM(idx) \
     84 	(((idx) == 0) ? BITMAP_MIN_SIZE : BITMAP_SIZE * (1 << (idx)))
     85 
     86 #if defined(DIAGNOSTIC) || defined(KASAN)
     87 #define POOL_REDZONE
     88 #endif
     89 
     90 #ifdef POOL_REDZONE
     91 # ifdef KASAN
     92 #  define POOL_REDZONE_SIZE 8
     93 # else
     94 #  define POOL_REDZONE_SIZE 2
     95 # endif
     96 static void pool_redzone_init(struct pool *, size_t);
     97 static void pool_redzone_fill(struct pool *, void *);
     98 static void pool_redzone_check(struct pool *, void *);
     99 static void pool_cache_redzone_check(pool_cache_t, void *);
    100 #else
    101 # define pool_redzone_init(pp, sz)		__nothing
    102 # define pool_redzone_fill(pp, ptr)		__nothing
    103 # define pool_redzone_check(pp, ptr)		__nothing
    104 # define pool_cache_redzone_check(pc, ptr)	__nothing
    105 #endif
    106 
    107 #ifdef KLEAK
    108 static void pool_kleak_fill(struct pool *, void *);
    109 static void pool_cache_kleak_fill(pool_cache_t, void *);
    110 #else
    111 #define pool_kleak_fill(pp, ptr)	__nothing
    112 #define pool_cache_kleak_fill(pc, ptr)	__nothing
    113 #endif
    114 
    115 #ifdef POOL_QUARANTINE
    116 static void pool_quarantine_init(struct pool *);
    117 static void pool_quarantine_flush(struct pool *);
    118 static bool pool_put_quarantine(struct pool *, void *,
    119     struct pool_pagelist *);
    120 static bool pool_cache_put_quarantine(pool_cache_t, void *, paddr_t);
    121 #else
    122 #define pool_quarantine_init(a)			__nothing
    123 #define pool_quarantine_flush(a)		__nothing
    124 #define pool_put_quarantine(a, b, c)		false
    125 #define pool_cache_put_quarantine(a, b, c)	false
    126 #endif
    127 
    128 #define pc_has_ctor(pc) \
    129 	(pc->pc_ctor != (int (*)(void *, void *, int))nullop)
    130 #define pc_has_dtor(pc) \
    131 	(pc->pc_dtor != (void (*)(void *, void *))nullop)
    132 
    133 /*
    134  * Pool backend allocators.
    135  *
    136  * Each pool has a backend allocator that handles allocation, deallocation,
    137  * and any additional draining that might be needed.
    138  *
    139  * We provide two standard allocators:
    140  *
    141  *	pool_allocator_kmem - the default when no allocator is specified
    142  *
    143  *	pool_allocator_nointr - used for pools that will not be accessed
    144  *	in interrupt context.
    145  */
    146 void *pool_page_alloc(struct pool *, int);
    147 void pool_page_free(struct pool *, void *);
    148 
    149 static void *pool_page_alloc_meta(struct pool *, int);
    150 static void pool_page_free_meta(struct pool *, void *);
    151 
    152 struct pool_allocator pool_allocator_kmem = {
    153 	.pa_alloc = pool_page_alloc,
    154 	.pa_free = pool_page_free,
    155 	.pa_pagesz = 0
    156 };
    157 
    158 struct pool_allocator pool_allocator_nointr = {
    159 	.pa_alloc = pool_page_alloc,
    160 	.pa_free = pool_page_free,
    161 	.pa_pagesz = 0
    162 };
    163 
    164 struct pool_allocator pool_allocator_meta = {
    165 	.pa_alloc = pool_page_alloc_meta,
    166 	.pa_free = pool_page_free_meta,
    167 	.pa_pagesz = 0
    168 };
    169 
    170 #define POOL_ALLOCATOR_BIG_BASE 13
    171 static struct pool_allocator pool_allocator_big[] = {
    172 	{
    173 		.pa_alloc = pool_page_alloc,
    174 		.pa_free = pool_page_free,
    175 		.pa_pagesz = 1 << (POOL_ALLOCATOR_BIG_BASE + 0),
    176 	},
    177 	{
    178 		.pa_alloc = pool_page_alloc,
    179 		.pa_free = pool_page_free,
    180 		.pa_pagesz = 1 << (POOL_ALLOCATOR_BIG_BASE + 1),
    181 	},
    182 	{
    183 		.pa_alloc = pool_page_alloc,
    184 		.pa_free = pool_page_free,
    185 		.pa_pagesz = 1 << (POOL_ALLOCATOR_BIG_BASE + 2),
    186 	},
    187 	{
    188 		.pa_alloc = pool_page_alloc,
    189 		.pa_free = pool_page_free,
    190 		.pa_pagesz = 1 << (POOL_ALLOCATOR_BIG_BASE + 3),
    191 	},
    192 	{
    193 		.pa_alloc = pool_page_alloc,
    194 		.pa_free = pool_page_free,
    195 		.pa_pagesz = 1 << (POOL_ALLOCATOR_BIG_BASE + 4),
    196 	},
    197 	{
    198 		.pa_alloc = pool_page_alloc,
    199 		.pa_free = pool_page_free,
    200 		.pa_pagesz = 1 << (POOL_ALLOCATOR_BIG_BASE + 5),
    201 	},
    202 	{
    203 		.pa_alloc = pool_page_alloc,
    204 		.pa_free = pool_page_free,
    205 		.pa_pagesz = 1 << (POOL_ALLOCATOR_BIG_BASE + 6),
    206 	},
    207 	{
    208 		.pa_alloc = pool_page_alloc,
    209 		.pa_free = pool_page_free,
    210 		.pa_pagesz = 1 << (POOL_ALLOCATOR_BIG_BASE + 7),
    211 	}
    212 };
    213 
    214 static int pool_bigidx(size_t);
    215 
    216 /* # of seconds to retain page after last use */
    217 int pool_inactive_time = 10;
    218 
    219 /* Next candidate for drainage (see pool_drain()) */
    220 static struct pool *drainpp;
    221 
    222 /* This lock protects both pool_head and drainpp. */
    223 static kmutex_t pool_head_lock;
    224 static kcondvar_t pool_busy;
    225 
    226 /* This lock protects initialization of a potentially shared pool allocator */
    227 static kmutex_t pool_allocator_lock;
    228 
    229 static unsigned int poolid_counter = 0;
    230 
    231 typedef uint32_t pool_item_bitmap_t;
    232 #define	BITMAP_SIZE	(CHAR_BIT * sizeof(pool_item_bitmap_t))
    233 #define	BITMAP_MASK	(BITMAP_SIZE - 1)
    234 #define	BITMAP_MIN_SIZE	(CHAR_BIT * sizeof(((struct pool_item_header *)NULL)->ph_u2))
    235 
    236 struct pool_item_header {
    237 	/* Page headers */
    238 	LIST_ENTRY(pool_item_header)
    239 				ph_pagelist;	/* pool page list */
    240 	union {
    241 		/* !PR_PHINPAGE */
    242 		struct {
    243 			SPLAY_ENTRY(pool_item_header)
    244 				phu_node;	/* off-page page headers */
    245 		} phu_offpage;
    246 		/* PR_PHINPAGE */
    247 		struct {
    248 			unsigned int phu_poolid;
    249 		} phu_onpage;
    250 	} ph_u1;
    251 	void *			ph_page;	/* this page's address */
    252 	uint32_t		ph_time;	/* last referenced */
    253 	uint16_t		ph_nmissing;	/* # of chunks in use */
    254 	uint16_t		ph_off;		/* start offset in page */
    255 	union {
    256 		/* !PR_USEBMAP */
    257 		struct {
    258 			LIST_HEAD(, pool_item)
    259 				phu_itemlist;	/* chunk list for this page */
    260 		} phu_normal;
    261 		/* PR_USEBMAP */
    262 		struct {
    263 			pool_item_bitmap_t phu_bitmap[1];
    264 		} phu_notouch;
    265 	} ph_u2;
    266 };
    267 #define ph_node		ph_u1.phu_offpage.phu_node
    268 #define ph_poolid	ph_u1.phu_onpage.phu_poolid
    269 #define ph_itemlist	ph_u2.phu_normal.phu_itemlist
    270 #define ph_bitmap	ph_u2.phu_notouch.phu_bitmap
    271 
    272 #define PHSIZE	ALIGN(sizeof(struct pool_item_header))
    273 
    274 CTASSERT(offsetof(struct pool_item_header, ph_u2) +
    275     BITMAP_MIN_SIZE / CHAR_BIT == sizeof(struct pool_item_header));
    276 
    277 #if defined(DIAGNOSTIC) && !defined(KASAN)
    278 #define POOL_CHECK_MAGIC
    279 #endif
    280 
    281 struct pool_item {
    282 #ifdef POOL_CHECK_MAGIC
    283 	u_int pi_magic;
    284 #endif
    285 #define	PI_MAGIC 0xdeaddeadU
    286 	/* Other entries use only this list entry */
    287 	LIST_ENTRY(pool_item)	pi_list;
    288 };
    289 
    290 #define	POOL_NEEDS_CATCHUP(pp)						\
    291 	((pp)->pr_nitems < (pp)->pr_minitems)
    292 #define	POOL_OBJ_TO_PAGE(pp, v)						\
    293 	(void *)((uintptr_t)v & pp->pr_alloc->pa_pagemask)
    294 
    295 /*
    296  * Pool cache management.
    297  *
    298  * Pool caches provide a way for constructed objects to be cached by the
    299  * pool subsystem.  This can lead to performance improvements by avoiding
    300  * needless object construction/destruction; it is deferred until absolutely
    301  * necessary.
    302  *
    303  * Caches are grouped into cache groups.  Each cache group references up
    304  * to PCG_NUMOBJECTS constructed objects.  When a cache allocates an
    305  * object from the pool, it calls the object's constructor and places it
    306  * into a cache group.  When a cache group frees an object back to the
    307  * pool, it first calls the object's destructor.  This allows the object
    308  * to persist in constructed form while freed to the cache.
    309  *
    310  * The pool references each cache, so that when a pool is drained by the
    311  * pagedaemon, it can drain each individual cache as well.  Each time a
    312  * cache is drained, the most idle cache group is freed to the pool in
    313  * its entirety.
    314  *
    315  * Pool caches are layed on top of pools.  By layering them, we can avoid
    316  * the complexity of cache management for pools which would not benefit
    317  * from it.
    318  */
    319 
    320 static struct pool pcg_normal_pool;
    321 static struct pool pcg_large_pool;
    322 static struct pool cache_pool;
    323 static struct pool cache_cpu_pool;
    324 
    325 /* List of all caches. */
    326 TAILQ_HEAD(,pool_cache) pool_cache_head =
    327     TAILQ_HEAD_INITIALIZER(pool_cache_head);
    328 
    329 int pool_cache_disable;		/* global disable for caching */
    330 static const pcg_t pcg_dummy;	/* zero sized: always empty, yet always full */
    331 
    332 static bool	pool_cache_put_slow(pool_cache_cpu_t *, int,
    333 				    void *);
    334 static bool	pool_cache_get_slow(pool_cache_cpu_t *, int,
    335 				    void **, paddr_t *, int);
    336 static void	pool_cache_cpu_init1(struct cpu_info *, pool_cache_t);
    337 static void	pool_cache_invalidate_groups(pool_cache_t, pcg_t *);
    338 static void	pool_cache_invalidate_cpu(pool_cache_t, u_int);
    339 static void	pool_cache_transfer(pool_cache_t);
    340 
    341 static int	pool_catchup(struct pool *);
    342 static void	pool_prime_page(struct pool *, void *,
    343 		    struct pool_item_header *);
    344 static void	pool_update_curpage(struct pool *);
    345 
    346 static int	pool_grow(struct pool *, int);
    347 static void	*pool_allocator_alloc(struct pool *, int);
    348 static void	pool_allocator_free(struct pool *, void *);
    349 
    350 static void pool_print_pagelist(struct pool *, struct pool_pagelist *,
    351 	void (*)(const char *, ...) __printflike(1, 2));
    352 static void pool_print1(struct pool *, const char *,
    353 	void (*)(const char *, ...) __printflike(1, 2));
    354 
    355 static int pool_chk_page(struct pool *, const char *,
    356 			 struct pool_item_header *);
    357 
    358 /* -------------------------------------------------------------------------- */
    359 
    360 static inline unsigned int
    361 pr_item_bitmap_index(const struct pool *pp, const struct pool_item_header *ph,
    362     const void *v)
    363 {
    364 	const char *cp = v;
    365 	unsigned int idx;
    366 
    367 	KASSERT(pp->pr_roflags & PR_USEBMAP);
    368 	idx = (cp - (char *)ph->ph_page - ph->ph_off) / pp->pr_size;
    369 
    370 	if (__predict_false(idx >= pp->pr_itemsperpage)) {
    371 		panic("%s: [%s] %u >= %u", __func__, pp->pr_wchan, idx,
    372 		    pp->pr_itemsperpage);
    373 	}
    374 
    375 	return idx;
    376 }
    377 
    378 static inline void
    379 pr_item_bitmap_put(const struct pool *pp, struct pool_item_header *ph,
    380     void *obj)
    381 {
    382 	unsigned int idx = pr_item_bitmap_index(pp, ph, obj);
    383 	pool_item_bitmap_t *bitmap = ph->ph_bitmap + (idx / BITMAP_SIZE);
    384 	pool_item_bitmap_t mask = 1U << (idx & BITMAP_MASK);
    385 
    386 	if (__predict_false((*bitmap & mask) != 0)) {
    387 		panic("%s: [%s] %p already freed", __func__, pp->pr_wchan, obj);
    388 	}
    389 
    390 	*bitmap |= mask;
    391 }
    392 
    393 static inline void *
    394 pr_item_bitmap_get(const struct pool *pp, struct pool_item_header *ph)
    395 {
    396 	pool_item_bitmap_t *bitmap = ph->ph_bitmap;
    397 	unsigned int idx;
    398 	int i;
    399 
    400 	for (i = 0; ; i++) {
    401 		int bit;
    402 
    403 		KASSERT((i * BITMAP_SIZE) < pp->pr_itemsperpage);
    404 		bit = ffs32(bitmap[i]);
    405 		if (bit) {
    406 			pool_item_bitmap_t mask;
    407 
    408 			bit--;
    409 			idx = (i * BITMAP_SIZE) + bit;
    410 			mask = 1U << bit;
    411 			KASSERT((bitmap[i] & mask) != 0);
    412 			bitmap[i] &= ~mask;
    413 			break;
    414 		}
    415 	}
    416 	KASSERT(idx < pp->pr_itemsperpage);
    417 	return (char *)ph->ph_page + ph->ph_off + idx * pp->pr_size;
    418 }
    419 
    420 static inline void
    421 pr_item_bitmap_init(const struct pool *pp, struct pool_item_header *ph)
    422 {
    423 	pool_item_bitmap_t *bitmap = ph->ph_bitmap;
    424 	const int n = howmany(pp->pr_itemsperpage, BITMAP_SIZE);
    425 	int i;
    426 
    427 	for (i = 0; i < n; i++) {
    428 		bitmap[i] = (pool_item_bitmap_t)-1;
    429 	}
    430 }
    431 
    432 /* -------------------------------------------------------------------------- */
    433 
    434 static inline void
    435 pr_item_linkedlist_put(const struct pool *pp, struct pool_item_header *ph,
    436     void *obj)
    437 {
    438 	struct pool_item *pi = obj;
    439 
    440 #ifdef POOL_CHECK_MAGIC
    441 	pi->pi_magic = PI_MAGIC;
    442 #endif
    443 
    444 	if (pp->pr_redzone) {
    445 		/*
    446 		 * Mark the pool_item as valid. The rest is already
    447 		 * invalid.
    448 		 */
    449 		kasan_mark(pi, sizeof(*pi), sizeof(*pi), 0);
    450 	}
    451 
    452 	LIST_INSERT_HEAD(&ph->ph_itemlist, pi, pi_list);
    453 }
    454 
    455 static inline void *
    456 pr_item_linkedlist_get(struct pool *pp, struct pool_item_header *ph)
    457 {
    458 	struct pool_item *pi;
    459 	void *v;
    460 
    461 	v = pi = LIST_FIRST(&ph->ph_itemlist);
    462 	if (__predict_false(v == NULL)) {
    463 		mutex_exit(&pp->pr_lock);
    464 		panic("%s: [%s] page empty", __func__, pp->pr_wchan);
    465 	}
    466 	KASSERTMSG((pp->pr_nitems > 0),
    467 	    "%s: [%s] nitems %u inconsistent on itemlist",
    468 	    __func__, pp->pr_wchan, pp->pr_nitems);
    469 #ifdef POOL_CHECK_MAGIC
    470 	KASSERTMSG((pi->pi_magic == PI_MAGIC),
    471 	    "%s: [%s] free list modified: "
    472 	    "magic=%x; page %p; item addr %p", __func__,
    473 	    pp->pr_wchan, pi->pi_magic, ph->ph_page, pi);
    474 #endif
    475 
    476 	/*
    477 	 * Remove from item list.
    478 	 */
    479 	LIST_REMOVE(pi, pi_list);
    480 
    481 	return v;
    482 }
    483 
    484 /* -------------------------------------------------------------------------- */
    485 
    486 static inline void
    487 pr_phinpage_check(struct pool *pp, struct pool_item_header *ph, void *page,
    488     void *object)
    489 {
    490 	if (__predict_false((void *)ph->ph_page != page)) {
    491 		panic("%s: [%s] item %p not part of pool", __func__,
    492 		    pp->pr_wchan, object);
    493 	}
    494 	if (__predict_false((char *)object < (char *)page + ph->ph_off)) {
    495 		panic("%s: [%s] item %p below item space", __func__,
    496 		    pp->pr_wchan, object);
    497 	}
    498 	if (__predict_false(ph->ph_poolid != pp->pr_poolid)) {
    499 		panic("%s: [%s] item %p poolid %u != %u", __func__,
    500 		    pp->pr_wchan, object, ph->ph_poolid, pp->pr_poolid);
    501 	}
    502 }
    503 
    504 static inline void
    505 pc_phinpage_check(pool_cache_t pc, void *object)
    506 {
    507 	struct pool_item_header *ph;
    508 	struct pool *pp;
    509 	void *page;
    510 
    511 	pp = &pc->pc_pool;
    512 	page = POOL_OBJ_TO_PAGE(pp, object);
    513 	ph = (struct pool_item_header *)page;
    514 
    515 	pr_phinpage_check(pp, ph, page, object);
    516 }
    517 
    518 /* -------------------------------------------------------------------------- */
    519 
    520 static inline int
    521 phtree_compare(struct pool_item_header *a, struct pool_item_header *b)
    522 {
    523 
    524 	/*
    525 	 * We consider pool_item_header with smaller ph_page bigger. This
    526 	 * unnatural ordering is for the benefit of pr_find_pagehead.
    527 	 */
    528 	if (a->ph_page < b->ph_page)
    529 		return 1;
    530 	else if (a->ph_page > b->ph_page)
    531 		return -1;
    532 	else
    533 		return 0;
    534 }
    535 
    536 SPLAY_PROTOTYPE(phtree, pool_item_header, ph_node, phtree_compare);
    537 SPLAY_GENERATE(phtree, pool_item_header, ph_node, phtree_compare);
    538 
    539 static inline struct pool_item_header *
    540 pr_find_pagehead_noalign(struct pool *pp, void *v)
    541 {
    542 	struct pool_item_header *ph, tmp;
    543 
    544 	tmp.ph_page = (void *)(uintptr_t)v;
    545 	ph = SPLAY_FIND(phtree, &pp->pr_phtree, &tmp);
    546 	if (ph == NULL) {
    547 		ph = SPLAY_ROOT(&pp->pr_phtree);
    548 		if (ph != NULL && phtree_compare(&tmp, ph) >= 0) {
    549 			ph = SPLAY_NEXT(phtree, &pp->pr_phtree, ph);
    550 		}
    551 		KASSERT(ph == NULL || phtree_compare(&tmp, ph) < 0);
    552 	}
    553 
    554 	return ph;
    555 }
    556 
    557 /*
    558  * Return the pool page header based on item address.
    559  */
    560 static inline struct pool_item_header *
    561 pr_find_pagehead(struct pool *pp, void *v)
    562 {
    563 	struct pool_item_header *ph, tmp;
    564 
    565 	if ((pp->pr_roflags & PR_NOALIGN) != 0) {
    566 		ph = pr_find_pagehead_noalign(pp, v);
    567 	} else {
    568 		void *page = POOL_OBJ_TO_PAGE(pp, v);
    569 		if ((pp->pr_roflags & PR_PHINPAGE) != 0) {
    570 			ph = (struct pool_item_header *)page;
    571 			pr_phinpage_check(pp, ph, page, v);
    572 		} else {
    573 			tmp.ph_page = page;
    574 			ph = SPLAY_FIND(phtree, &pp->pr_phtree, &tmp);
    575 		}
    576 	}
    577 
    578 	KASSERT(ph == NULL || ((pp->pr_roflags & PR_PHINPAGE) != 0) ||
    579 	    ((char *)ph->ph_page <= (char *)v &&
    580 	    (char *)v < (char *)ph->ph_page + pp->pr_alloc->pa_pagesz));
    581 	return ph;
    582 }
    583 
    584 static void
    585 pr_pagelist_free(struct pool *pp, struct pool_pagelist *pq)
    586 {
    587 	struct pool_item_header *ph;
    588 
    589 	while ((ph = LIST_FIRST(pq)) != NULL) {
    590 		LIST_REMOVE(ph, ph_pagelist);
    591 		pool_allocator_free(pp, ph->ph_page);
    592 		if ((pp->pr_roflags & PR_PHINPAGE) == 0)
    593 			pool_put(pp->pr_phpool, ph);
    594 	}
    595 }
    596 
    597 /*
    598  * Remove a page from the pool.
    599  */
    600 static inline void
    601 pr_rmpage(struct pool *pp, struct pool_item_header *ph,
    602      struct pool_pagelist *pq)
    603 {
    604 
    605 	KASSERT(mutex_owned(&pp->pr_lock));
    606 
    607 	/*
    608 	 * If the page was idle, decrement the idle page count.
    609 	 */
    610 	if (ph->ph_nmissing == 0) {
    611 		KASSERT(pp->pr_nidle != 0);
    612 		KASSERTMSG((pp->pr_nitems >= pp->pr_itemsperpage),
    613 		    "%s: [%s] nitems=%u < itemsperpage=%u", __func__,
    614 		    pp->pr_wchan, pp->pr_nitems, pp->pr_itemsperpage);
    615 		pp->pr_nidle--;
    616 	}
    617 
    618 	pp->pr_nitems -= pp->pr_itemsperpage;
    619 
    620 	/*
    621 	 * Unlink the page from the pool and queue it for release.
    622 	 */
    623 	LIST_REMOVE(ph, ph_pagelist);
    624 	if (pp->pr_roflags & PR_PHINPAGE) {
    625 		if (__predict_false(ph->ph_poolid != pp->pr_poolid)) {
    626 			panic("%s: [%s] ph %p poolid %u != %u",
    627 			    __func__, pp->pr_wchan, ph, ph->ph_poolid,
    628 			    pp->pr_poolid);
    629 		}
    630 	} else {
    631 		SPLAY_REMOVE(phtree, &pp->pr_phtree, ph);
    632 	}
    633 	LIST_INSERT_HEAD(pq, ph, ph_pagelist);
    634 
    635 	pp->pr_npages--;
    636 	pp->pr_npagefree++;
    637 
    638 	pool_update_curpage(pp);
    639 }
    640 
    641 /*
    642  * Initialize all the pools listed in the "pools" link set.
    643  */
    644 void
    645 pool_subsystem_init(void)
    646 {
    647 	size_t size;
    648 	int idx;
    649 
    650 	mutex_init(&pool_head_lock, MUTEX_DEFAULT, IPL_NONE);
    651 	mutex_init(&pool_allocator_lock, MUTEX_DEFAULT, IPL_NONE);
    652 	cv_init(&pool_busy, "poolbusy");
    653 
    654 	/*
    655 	 * Initialize private page header pool and cache magazine pool if we
    656 	 * haven't done so yet.
    657 	 */
    658 	for (idx = 0; idx < PHPOOL_MAX; idx++) {
    659 		static char phpool_names[PHPOOL_MAX][6+1+6+1];
    660 		int nelem;
    661 		size_t sz;
    662 
    663 		nelem = PHPOOL_FREELIST_NELEM(idx);
    664 		KASSERT(nelem != 0);
    665 		snprintf(phpool_names[idx], sizeof(phpool_names[idx]),
    666 		    "phpool-%d", nelem);
    667 		sz = offsetof(struct pool_item_header,
    668 		    ph_bitmap[howmany(nelem, BITMAP_SIZE)]);
    669 		pool_init(&phpool[idx], sz, 0, 0, 0,
    670 		    phpool_names[idx], &pool_allocator_meta, IPL_VM);
    671 	}
    672 
    673 	size = sizeof(pcg_t) +
    674 	    (PCG_NOBJECTS_NORMAL - 1) * sizeof(pcgpair_t);
    675 	pool_init(&pcg_normal_pool, size, coherency_unit, 0, 0,
    676 	    "pcgnormal", &pool_allocator_meta, IPL_VM);
    677 
    678 	size = sizeof(pcg_t) +
    679 	    (PCG_NOBJECTS_LARGE - 1) * sizeof(pcgpair_t);
    680 	pool_init(&pcg_large_pool, size, coherency_unit, 0, 0,
    681 	    "pcglarge", &pool_allocator_meta, IPL_VM);
    682 
    683 	pool_init(&cache_pool, sizeof(struct pool_cache), coherency_unit,
    684 	    0, 0, "pcache", &pool_allocator_meta, IPL_NONE);
    685 
    686 	pool_init(&cache_cpu_pool, sizeof(pool_cache_cpu_t), coherency_unit,
    687 	    0, 0, "pcachecpu", &pool_allocator_meta, IPL_NONE);
    688 }
    689 
    690 static inline bool
    691 pool_init_is_phinpage(const struct pool *pp)
    692 {
    693 	size_t pagesize;
    694 
    695 	if (pp->pr_roflags & PR_PHINPAGE) {
    696 		return true;
    697 	}
    698 	if (pp->pr_roflags & (PR_NOTOUCH | PR_NOALIGN)) {
    699 		return false;
    700 	}
    701 
    702 	pagesize = pp->pr_alloc->pa_pagesz;
    703 
    704 	/*
    705 	 * Threshold: the item size is below 1/16 of a page size, and below
    706 	 * 8 times the page header size. The latter ensures we go off-page
    707 	 * if the page header would make us waste a rather big item.
    708 	 */
    709 	if (pp->pr_size < MIN(pagesize / 16, PHSIZE * 8)) {
    710 		return true;
    711 	}
    712 
    713 	/* Put the header into the page if it doesn't waste any items. */
    714 	if (pagesize / pp->pr_size == (pagesize - PHSIZE) / pp->pr_size) {
    715 		return true;
    716 	}
    717 
    718 	return false;
    719 }
    720 
    721 static inline bool
    722 pool_init_is_usebmap(const struct pool *pp)
    723 {
    724 	size_t bmapsize;
    725 
    726 	if (pp->pr_roflags & PR_NOTOUCH) {
    727 		return true;
    728 	}
    729 
    730 	/*
    731 	 * If we're off-page, go with a bitmap.
    732 	 */
    733 	if (!(pp->pr_roflags & PR_PHINPAGE)) {
    734 		return true;
    735 	}
    736 
    737 	/*
    738 	 * If we're on-page, and the page header can already contain a bitmap
    739 	 * big enough to cover all the items of the page, go with a bitmap.
    740 	 */
    741 	bmapsize = roundup(PHSIZE, pp->pr_align) -
    742 	    offsetof(struct pool_item_header, ph_bitmap[0]);
    743 	KASSERT(bmapsize % sizeof(pool_item_bitmap_t) == 0);
    744 	if (pp->pr_itemsperpage <= bmapsize * CHAR_BIT) {
    745 		return true;
    746 	}
    747 
    748 	return false;
    749 }
    750 
    751 /*
    752  * Initialize the given pool resource structure.
    753  *
    754  * We export this routine to allow other kernel parts to declare
    755  * static pools that must be initialized before kmem(9) is available.
    756  */
    757 void
    758 pool_init(struct pool *pp, size_t size, u_int align, u_int ioff, int flags,
    759     const char *wchan, struct pool_allocator *palloc, int ipl)
    760 {
    761 	struct pool *pp1;
    762 	size_t prsize;
    763 	int itemspace, slack;
    764 
    765 	/* XXX ioff will be removed. */
    766 	KASSERT(ioff == 0);
    767 
    768 #ifdef DEBUG
    769 	if (__predict_true(!cold))
    770 		mutex_enter(&pool_head_lock);
    771 	/*
    772 	 * Check that the pool hasn't already been initialised and
    773 	 * added to the list of all pools.
    774 	 */
    775 	TAILQ_FOREACH(pp1, &pool_head, pr_poollist) {
    776 		if (pp == pp1)
    777 			panic("%s: [%s] already initialised", __func__,
    778 			    wchan);
    779 	}
    780 	if (__predict_true(!cold))
    781 		mutex_exit(&pool_head_lock);
    782 #endif
    783 
    784 	if (palloc == NULL)
    785 		palloc = &pool_allocator_kmem;
    786 
    787 	if (!cold)
    788 		mutex_enter(&pool_allocator_lock);
    789 	if (palloc->pa_refcnt++ == 0) {
    790 		if (palloc->pa_pagesz == 0)
    791 			palloc->pa_pagesz = PAGE_SIZE;
    792 
    793 		TAILQ_INIT(&palloc->pa_list);
    794 
    795 		mutex_init(&palloc->pa_lock, MUTEX_DEFAULT, IPL_VM);
    796 		palloc->pa_pagemask = ~(palloc->pa_pagesz - 1);
    797 		palloc->pa_pageshift = ffs(palloc->pa_pagesz) - 1;
    798 	}
    799 	if (!cold)
    800 		mutex_exit(&pool_allocator_lock);
    801 
    802 	if (align == 0)
    803 		align = ALIGN(1);
    804 
    805 	prsize = size;
    806 	if ((flags & PR_NOTOUCH) == 0 && prsize < sizeof(struct pool_item))
    807 		prsize = sizeof(struct pool_item);
    808 
    809 	prsize = roundup(prsize, align);
    810 	KASSERTMSG((prsize <= palloc->pa_pagesz),
    811 	    "%s: [%s] pool item size (%zu) larger than page size (%u)",
    812 	    __func__, wchan, prsize, palloc->pa_pagesz);
    813 
    814 	/*
    815 	 * Initialize the pool structure.
    816 	 */
    817 	LIST_INIT(&pp->pr_emptypages);
    818 	LIST_INIT(&pp->pr_fullpages);
    819 	LIST_INIT(&pp->pr_partpages);
    820 	pp->pr_cache = NULL;
    821 	pp->pr_curpage = NULL;
    822 	pp->pr_npages = 0;
    823 	pp->pr_minitems = 0;
    824 	pp->pr_minpages = 0;
    825 	pp->pr_maxpages = UINT_MAX;
    826 	pp->pr_roflags = flags;
    827 	pp->pr_flags = 0;
    828 	pp->pr_size = prsize;
    829 	pp->pr_reqsize = size;
    830 	pp->pr_align = align;
    831 	pp->pr_wchan = wchan;
    832 	pp->pr_alloc = palloc;
    833 	pp->pr_poolid = atomic_inc_uint_nv(&poolid_counter);
    834 	pp->pr_nitems = 0;
    835 	pp->pr_nout = 0;
    836 	pp->pr_hardlimit = UINT_MAX;
    837 	pp->pr_hardlimit_warning = NULL;
    838 	pp->pr_hardlimit_ratecap.tv_sec = 0;
    839 	pp->pr_hardlimit_ratecap.tv_usec = 0;
    840 	pp->pr_hardlimit_warning_last.tv_sec = 0;
    841 	pp->pr_hardlimit_warning_last.tv_usec = 0;
    842 	pp->pr_drain_hook = NULL;
    843 	pp->pr_drain_hook_arg = NULL;
    844 	pp->pr_freecheck = NULL;
    845 	pp->pr_redzone = false;
    846 	pool_redzone_init(pp, size);
    847 	pool_quarantine_init(pp);
    848 
    849 	/*
    850 	 * Decide whether to put the page header off-page to avoid wasting too
    851 	 * large a part of the page or too big an item. Off-page page headers
    852 	 * go on a hash table, so we can match a returned item with its header
    853 	 * based on the page address.
    854 	 */
    855 	if (pool_init_is_phinpage(pp)) {
    856 		/* Use the beginning of the page for the page header */
    857 		itemspace = palloc->pa_pagesz - roundup(PHSIZE, align);
    858 		pp->pr_itemoffset = roundup(PHSIZE, align);
    859 		pp->pr_roflags |= PR_PHINPAGE;
    860 	} else {
    861 		/* The page header will be taken from our page header pool */
    862 		itemspace = palloc->pa_pagesz;
    863 		pp->pr_itemoffset = 0;
    864 		SPLAY_INIT(&pp->pr_phtree);
    865 	}
    866 
    867 	pp->pr_itemsperpage = itemspace / pp->pr_size;
    868 	KASSERT(pp->pr_itemsperpage != 0);
    869 
    870 	/*
    871 	 * Decide whether to use a bitmap or a linked list to manage freed
    872 	 * items.
    873 	 */
    874 	if (pool_init_is_usebmap(pp)) {
    875 		pp->pr_roflags |= PR_USEBMAP;
    876 	}
    877 
    878 	/*
    879 	 * If we're off-page, then we're using a bitmap; choose the appropriate
    880 	 * pool to allocate page headers, whose size varies depending on the
    881 	 * bitmap. If we're on-page, nothing to do.
    882 	 */
    883 	if (!(pp->pr_roflags & PR_PHINPAGE)) {
    884 		int idx;
    885 
    886 		KASSERT(pp->pr_roflags & PR_USEBMAP);
    887 
    888 		for (idx = 0; pp->pr_itemsperpage > PHPOOL_FREELIST_NELEM(idx);
    889 		    idx++) {
    890 			/* nothing */
    891 		}
    892 		if (idx >= PHPOOL_MAX) {
    893 			/*
    894 			 * if you see this panic, consider to tweak
    895 			 * PHPOOL_MAX and PHPOOL_FREELIST_NELEM.
    896 			 */
    897 			panic("%s: [%s] too large itemsperpage(%d) for "
    898 			    "PR_USEBMAP", __func__,
    899 			    pp->pr_wchan, pp->pr_itemsperpage);
    900 		}
    901 		pp->pr_phpool = &phpool[idx];
    902 	} else {
    903 		pp->pr_phpool = NULL;
    904 	}
    905 
    906 	/*
    907 	 * Use the slack between the chunks and the page header
    908 	 * for "cache coloring".
    909 	 */
    910 	slack = itemspace - pp->pr_itemsperpage * pp->pr_size;
    911 	pp->pr_maxcolor = rounddown(slack, align);
    912 	pp->pr_curcolor = 0;
    913 
    914 	pp->pr_nget = 0;
    915 	pp->pr_nfail = 0;
    916 	pp->pr_nput = 0;
    917 	pp->pr_npagealloc = 0;
    918 	pp->pr_npagefree = 0;
    919 	pp->pr_hiwat = 0;
    920 	pp->pr_nidle = 0;
    921 	pp->pr_refcnt = 0;
    922 
    923 	mutex_init(&pp->pr_lock, MUTEX_DEFAULT, ipl);
    924 	cv_init(&pp->pr_cv, wchan);
    925 	pp->pr_ipl = ipl;
    926 
    927 	/* Insert into the list of all pools. */
    928 	if (!cold)
    929 		mutex_enter(&pool_head_lock);
    930 	TAILQ_FOREACH(pp1, &pool_head, pr_poollist) {
    931 		if (strcmp(pp1->pr_wchan, pp->pr_wchan) > 0)
    932 			break;
    933 	}
    934 	if (pp1 == NULL)
    935 		TAILQ_INSERT_TAIL(&pool_head, pp, pr_poollist);
    936 	else
    937 		TAILQ_INSERT_BEFORE(pp1, pp, pr_poollist);
    938 	if (!cold)
    939 		mutex_exit(&pool_head_lock);
    940 
    941 	/* Insert this into the list of pools using this allocator. */
    942 	if (!cold)
    943 		mutex_enter(&palloc->pa_lock);
    944 	TAILQ_INSERT_TAIL(&palloc->pa_list, pp, pr_alloc_list);
    945 	if (!cold)
    946 		mutex_exit(&palloc->pa_lock);
    947 }
    948 
    949 /*
    950  * De-commision a pool resource.
    951  */
    952 void
    953 pool_destroy(struct pool *pp)
    954 {
    955 	struct pool_pagelist pq;
    956 	struct pool_item_header *ph;
    957 
    958 	pool_quarantine_flush(pp);
    959 
    960 	/* Remove from global pool list */
    961 	mutex_enter(&pool_head_lock);
    962 	while (pp->pr_refcnt != 0)
    963 		cv_wait(&pool_busy, &pool_head_lock);
    964 	TAILQ_REMOVE(&pool_head, pp, pr_poollist);
    965 	if (drainpp == pp)
    966 		drainpp = NULL;
    967 	mutex_exit(&pool_head_lock);
    968 
    969 	/* Remove this pool from its allocator's list of pools. */
    970 	mutex_enter(&pp->pr_alloc->pa_lock);
    971 	TAILQ_REMOVE(&pp->pr_alloc->pa_list, pp, pr_alloc_list);
    972 	mutex_exit(&pp->pr_alloc->pa_lock);
    973 
    974 	mutex_enter(&pool_allocator_lock);
    975 	if (--pp->pr_alloc->pa_refcnt == 0)
    976 		mutex_destroy(&pp->pr_alloc->pa_lock);
    977 	mutex_exit(&pool_allocator_lock);
    978 
    979 	mutex_enter(&pp->pr_lock);
    980 
    981 	KASSERT(pp->pr_cache == NULL);
    982 	KASSERTMSG((pp->pr_nout == 0),
    983 	    "%s: [%s] pool busy: still out: %u", __func__, pp->pr_wchan,
    984 	    pp->pr_nout);
    985 	KASSERT(LIST_EMPTY(&pp->pr_fullpages));
    986 	KASSERT(LIST_EMPTY(&pp->pr_partpages));
    987 
    988 	/* Remove all pages */
    989 	LIST_INIT(&pq);
    990 	while ((ph = LIST_FIRST(&pp->pr_emptypages)) != NULL)
    991 		pr_rmpage(pp, ph, &pq);
    992 
    993 	mutex_exit(&pp->pr_lock);
    994 
    995 	pr_pagelist_free(pp, &pq);
    996 	cv_destroy(&pp->pr_cv);
    997 	mutex_destroy(&pp->pr_lock);
    998 }
    999 
   1000 void
   1001 pool_set_drain_hook(struct pool *pp, void (*fn)(void *, int), void *arg)
   1002 {
   1003 
   1004 	/* XXX no locking -- must be used just after pool_init() */
   1005 	KASSERTMSG((pp->pr_drain_hook == NULL),
   1006 	    "%s: [%s] already set", __func__, pp->pr_wchan);
   1007 	pp->pr_drain_hook = fn;
   1008 	pp->pr_drain_hook_arg = arg;
   1009 }
   1010 
   1011 static struct pool_item_header *
   1012 pool_alloc_item_header(struct pool *pp, void *storage, int flags)
   1013 {
   1014 	struct pool_item_header *ph;
   1015 
   1016 	if ((pp->pr_roflags & PR_PHINPAGE) != 0)
   1017 		ph = storage;
   1018 	else
   1019 		ph = pool_get(pp->pr_phpool, flags);
   1020 
   1021 	return ph;
   1022 }
   1023 
   1024 /*
   1025  * Grab an item from the pool.
   1026  */
   1027 void *
   1028 pool_get(struct pool *pp, int flags)
   1029 {
   1030 	struct pool_item_header *ph;
   1031 	void *v;
   1032 
   1033 	KASSERT(!(flags & PR_NOWAIT) != !(flags & PR_WAITOK));
   1034 	KASSERTMSG((pp->pr_itemsperpage != 0),
   1035 	    "%s: [%s] pr_itemsperpage is zero, "
   1036 	    "pool not initialized?", __func__, pp->pr_wchan);
   1037 	KASSERTMSG((!(cpu_intr_p() || cpu_softintr_p())
   1038 		|| pp->pr_ipl != IPL_NONE || cold || panicstr != NULL),
   1039 	    "%s: [%s] is IPL_NONE, but called from interrupt context",
   1040 	    __func__, pp->pr_wchan);
   1041 	if (flags & PR_WAITOK) {
   1042 		ASSERT_SLEEPABLE();
   1043 	}
   1044 
   1045 	mutex_enter(&pp->pr_lock);
   1046  startover:
   1047 	/*
   1048 	 * Check to see if we've reached the hard limit.  If we have,
   1049 	 * and we can wait, then wait until an item has been returned to
   1050 	 * the pool.
   1051 	 */
   1052 	KASSERTMSG((pp->pr_nout <= pp->pr_hardlimit),
   1053 	    "%s: %s: crossed hard limit", __func__, pp->pr_wchan);
   1054 	if (__predict_false(pp->pr_nout == pp->pr_hardlimit)) {
   1055 		if (pp->pr_drain_hook != NULL) {
   1056 			/*
   1057 			 * Since the drain hook is going to free things
   1058 			 * back to the pool, unlock, call the hook, re-lock,
   1059 			 * and check the hardlimit condition again.
   1060 			 */
   1061 			mutex_exit(&pp->pr_lock);
   1062 			(*pp->pr_drain_hook)(pp->pr_drain_hook_arg, flags);
   1063 			mutex_enter(&pp->pr_lock);
   1064 			if (pp->pr_nout < pp->pr_hardlimit)
   1065 				goto startover;
   1066 		}
   1067 
   1068 		if ((flags & PR_WAITOK) && !(flags & PR_LIMITFAIL)) {
   1069 			/*
   1070 			 * XXX: A warning isn't logged in this case.  Should
   1071 			 * it be?
   1072 			 */
   1073 			pp->pr_flags |= PR_WANTED;
   1074 			do {
   1075 				cv_wait(&pp->pr_cv, &pp->pr_lock);
   1076 			} while (pp->pr_flags & PR_WANTED);
   1077 			goto startover;
   1078 		}
   1079 
   1080 		/*
   1081 		 * Log a message that the hard limit has been hit.
   1082 		 */
   1083 		if (pp->pr_hardlimit_warning != NULL &&
   1084 		    ratecheck(&pp->pr_hardlimit_warning_last,
   1085 			      &pp->pr_hardlimit_ratecap))
   1086 			log(LOG_ERR, "%s\n", pp->pr_hardlimit_warning);
   1087 
   1088 		pp->pr_nfail++;
   1089 
   1090 		mutex_exit(&pp->pr_lock);
   1091 		KASSERT((flags & (PR_NOWAIT|PR_LIMITFAIL)) != 0);
   1092 		return NULL;
   1093 	}
   1094 
   1095 	/*
   1096 	 * The convention we use is that if `curpage' is not NULL, then
   1097 	 * it points at a non-empty bucket. In particular, `curpage'
   1098 	 * never points at a page header which has PR_PHINPAGE set and
   1099 	 * has no items in its bucket.
   1100 	 */
   1101 	if ((ph = pp->pr_curpage) == NULL) {
   1102 		int error;
   1103 
   1104 		KASSERTMSG((pp->pr_nitems == 0),
   1105 		    "%s: [%s] curpage NULL, inconsistent nitems %u",
   1106 		    __func__, pp->pr_wchan, pp->pr_nitems);
   1107 
   1108 		/*
   1109 		 * Call the back-end page allocator for more memory.
   1110 		 * Release the pool lock, as the back-end page allocator
   1111 		 * may block.
   1112 		 */
   1113 		error = pool_grow(pp, flags);
   1114 		if (error != 0) {
   1115 			/*
   1116 			 * pool_grow aborts when another thread
   1117 			 * is allocating a new page. Retry if it
   1118 			 * waited for it.
   1119 			 */
   1120 			if (error == ERESTART)
   1121 				goto startover;
   1122 
   1123 			/*
   1124 			 * We were unable to allocate a page or item
   1125 			 * header, but we released the lock during
   1126 			 * allocation, so perhaps items were freed
   1127 			 * back to the pool.  Check for this case.
   1128 			 */
   1129 			if (pp->pr_curpage != NULL)
   1130 				goto startover;
   1131 
   1132 			pp->pr_nfail++;
   1133 			mutex_exit(&pp->pr_lock);
   1134 			KASSERT((flags & (PR_WAITOK|PR_NOWAIT)) == PR_NOWAIT);
   1135 			return NULL;
   1136 		}
   1137 
   1138 		/* Start the allocation process over. */
   1139 		goto startover;
   1140 	}
   1141 	if (pp->pr_roflags & PR_USEBMAP) {
   1142 		KASSERTMSG((ph->ph_nmissing < pp->pr_itemsperpage),
   1143 		    "%s: [%s] pool page empty", __func__, pp->pr_wchan);
   1144 		v = pr_item_bitmap_get(pp, ph);
   1145 	} else {
   1146 		v = pr_item_linkedlist_get(pp, ph);
   1147 	}
   1148 	pp->pr_nitems--;
   1149 	pp->pr_nout++;
   1150 	if (ph->ph_nmissing == 0) {
   1151 		KASSERT(pp->pr_nidle > 0);
   1152 		pp->pr_nidle--;
   1153 
   1154 		/*
   1155 		 * This page was previously empty.  Move it to the list of
   1156 		 * partially-full pages.  This page is already curpage.
   1157 		 */
   1158 		LIST_REMOVE(ph, ph_pagelist);
   1159 		LIST_INSERT_HEAD(&pp->pr_partpages, ph, ph_pagelist);
   1160 	}
   1161 	ph->ph_nmissing++;
   1162 	if (ph->ph_nmissing == pp->pr_itemsperpage) {
   1163 		KASSERTMSG(((pp->pr_roflags & PR_USEBMAP) ||
   1164 			LIST_EMPTY(&ph->ph_itemlist)),
   1165 		    "%s: [%s] nmissing (%u) inconsistent", __func__,
   1166 			pp->pr_wchan, ph->ph_nmissing);
   1167 		/*
   1168 		 * This page is now full.  Move it to the full list
   1169 		 * and select a new current page.
   1170 		 */
   1171 		LIST_REMOVE(ph, ph_pagelist);
   1172 		LIST_INSERT_HEAD(&pp->pr_fullpages, ph, ph_pagelist);
   1173 		pool_update_curpage(pp);
   1174 	}
   1175 
   1176 	pp->pr_nget++;
   1177 
   1178 	/*
   1179 	 * If we have a low water mark and we are now below that low
   1180 	 * water mark, add more items to the pool.
   1181 	 */
   1182 	if (POOL_NEEDS_CATCHUP(pp) && pool_catchup(pp) != 0) {
   1183 		/*
   1184 		 * XXX: Should we log a warning?  Should we set up a timeout
   1185 		 * to try again in a second or so?  The latter could break
   1186 		 * a caller's assumptions about interrupt protection, etc.
   1187 		 */
   1188 	}
   1189 
   1190 	mutex_exit(&pp->pr_lock);
   1191 	KASSERT((((vaddr_t)v) & (pp->pr_align - 1)) == 0);
   1192 	FREECHECK_OUT(&pp->pr_freecheck, v);
   1193 	pool_redzone_fill(pp, v);
   1194 	if (flags & PR_ZERO)
   1195 		memset(v, 0, pp->pr_reqsize);
   1196 	else
   1197 		pool_kleak_fill(pp, v);
   1198 	return v;
   1199 }
   1200 
   1201 /*
   1202  * Internal version of pool_put().  Pool is already locked/entered.
   1203  */
   1204 static void
   1205 pool_do_put(struct pool *pp, void *v, struct pool_pagelist *pq)
   1206 {
   1207 	struct pool_item_header *ph;
   1208 
   1209 	KASSERT(mutex_owned(&pp->pr_lock));
   1210 	pool_redzone_check(pp, v);
   1211 	FREECHECK_IN(&pp->pr_freecheck, v);
   1212 	LOCKDEBUG_MEM_CHECK(v, pp->pr_size);
   1213 
   1214 	KASSERTMSG((pp->pr_nout > 0),
   1215 	    "%s: [%s] putting with none out", __func__, pp->pr_wchan);
   1216 
   1217 	if (__predict_false((ph = pr_find_pagehead(pp, v)) == NULL)) {
   1218 		panic("%s: [%s] page header missing", __func__,  pp->pr_wchan);
   1219 	}
   1220 
   1221 	/*
   1222 	 * Return to item list.
   1223 	 */
   1224 	if (pp->pr_roflags & PR_USEBMAP) {
   1225 		pr_item_bitmap_put(pp, ph, v);
   1226 	} else {
   1227 		pr_item_linkedlist_put(pp, ph, v);
   1228 	}
   1229 	KDASSERT(ph->ph_nmissing != 0);
   1230 	ph->ph_nmissing--;
   1231 	pp->pr_nput++;
   1232 	pp->pr_nitems++;
   1233 	pp->pr_nout--;
   1234 
   1235 	/* Cancel "pool empty" condition if it exists */
   1236 	if (pp->pr_curpage == NULL)
   1237 		pp->pr_curpage = ph;
   1238 
   1239 	if (pp->pr_flags & PR_WANTED) {
   1240 		pp->pr_flags &= ~PR_WANTED;
   1241 		cv_broadcast(&pp->pr_cv);
   1242 	}
   1243 
   1244 	/*
   1245 	 * If this page is now empty, do one of two things:
   1246 	 *
   1247 	 *	(1) If we have more pages than the page high water mark,
   1248 	 *	    free the page back to the system.  ONLY CONSIDER
   1249 	 *	    FREEING BACK A PAGE IF WE HAVE MORE THAN OUR MINIMUM PAGE
   1250 	 *	    CLAIM.
   1251 	 *
   1252 	 *	(2) Otherwise, move the page to the empty page list.
   1253 	 *
   1254 	 * Either way, select a new current page (so we use a partially-full
   1255 	 * page if one is available).
   1256 	 */
   1257 	if (ph->ph_nmissing == 0) {
   1258 		pp->pr_nidle++;
   1259 		if (pp->pr_npages > pp->pr_minpages &&
   1260 		    pp->pr_npages > pp->pr_maxpages) {
   1261 			pr_rmpage(pp, ph, pq);
   1262 		} else {
   1263 			LIST_REMOVE(ph, ph_pagelist);
   1264 			LIST_INSERT_HEAD(&pp->pr_emptypages, ph, ph_pagelist);
   1265 
   1266 			/*
   1267 			 * Update the timestamp on the page.  A page must
   1268 			 * be idle for some period of time before it can
   1269 			 * be reclaimed by the pagedaemon.  This minimizes
   1270 			 * ping-pong'ing for memory.
   1271 			 *
   1272 			 * note for 64-bit time_t: truncating to 32-bit is not
   1273 			 * a problem for our usage.
   1274 			 */
   1275 			ph->ph_time = time_uptime;
   1276 		}
   1277 		pool_update_curpage(pp);
   1278 	}
   1279 
   1280 	/*
   1281 	 * If the page was previously completely full, move it to the
   1282 	 * partially-full list and make it the current page.  The next
   1283 	 * allocation will get the item from this page, instead of
   1284 	 * further fragmenting the pool.
   1285 	 */
   1286 	else if (ph->ph_nmissing == (pp->pr_itemsperpage - 1)) {
   1287 		LIST_REMOVE(ph, ph_pagelist);
   1288 		LIST_INSERT_HEAD(&pp->pr_partpages, ph, ph_pagelist);
   1289 		pp->pr_curpage = ph;
   1290 	}
   1291 }
   1292 
   1293 void
   1294 pool_put(struct pool *pp, void *v)
   1295 {
   1296 	struct pool_pagelist pq;
   1297 
   1298 	LIST_INIT(&pq);
   1299 
   1300 	mutex_enter(&pp->pr_lock);
   1301 	if (!pool_put_quarantine(pp, v, &pq)) {
   1302 		pool_do_put(pp, v, &pq);
   1303 	}
   1304 	mutex_exit(&pp->pr_lock);
   1305 
   1306 	pr_pagelist_free(pp, &pq);
   1307 }
   1308 
   1309 /*
   1310  * pool_grow: grow a pool by a page.
   1311  *
   1312  * => called with pool locked.
   1313  * => unlock and relock the pool.
   1314  * => return with pool locked.
   1315  */
   1316 
   1317 static int
   1318 pool_grow(struct pool *pp, int flags)
   1319 {
   1320 	struct pool_item_header *ph;
   1321 	char *storage;
   1322 
   1323 	/*
   1324 	 * If there's a pool_grow in progress, wait for it to complete
   1325 	 * and try again from the top.
   1326 	 */
   1327 	if (pp->pr_flags & PR_GROWING) {
   1328 		if (flags & PR_WAITOK) {
   1329 			do {
   1330 				cv_wait(&pp->pr_cv, &pp->pr_lock);
   1331 			} while (pp->pr_flags & PR_GROWING);
   1332 			return ERESTART;
   1333 		} else {
   1334 			if (pp->pr_flags & PR_GROWINGNOWAIT) {
   1335 				/*
   1336 				 * This needs an unlock/relock dance so
   1337 				 * that the other caller has a chance to
   1338 				 * run and actually do the thing.  Note
   1339 				 * that this is effectively a busy-wait.
   1340 				 */
   1341 				mutex_exit(&pp->pr_lock);
   1342 				mutex_enter(&pp->pr_lock);
   1343 				return ERESTART;
   1344 			}
   1345 			return EWOULDBLOCK;
   1346 		}
   1347 	}
   1348 	pp->pr_flags |= PR_GROWING;
   1349 	if (flags & PR_WAITOK)
   1350 		mutex_exit(&pp->pr_lock);
   1351 	else
   1352 		pp->pr_flags |= PR_GROWINGNOWAIT;
   1353 
   1354 	storage = pool_allocator_alloc(pp, flags);
   1355 	if (__predict_false(storage == NULL))
   1356 		goto out;
   1357 
   1358 	ph = pool_alloc_item_header(pp, storage, flags);
   1359 	if (__predict_false(ph == NULL)) {
   1360 		pool_allocator_free(pp, storage);
   1361 		goto out;
   1362 	}
   1363 
   1364 	if (flags & PR_WAITOK)
   1365 		mutex_enter(&pp->pr_lock);
   1366 	pool_prime_page(pp, storage, ph);
   1367 	pp->pr_npagealloc++;
   1368 	KASSERT(pp->pr_flags & PR_GROWING);
   1369 	pp->pr_flags &= ~(PR_GROWING|PR_GROWINGNOWAIT);
   1370 	/*
   1371 	 * If anyone was waiting for pool_grow, notify them that we
   1372 	 * may have just done it.
   1373 	 */
   1374 	cv_broadcast(&pp->pr_cv);
   1375 	return 0;
   1376 out:
   1377 	if (flags & PR_WAITOK)
   1378 		mutex_enter(&pp->pr_lock);
   1379 	KASSERT(pp->pr_flags & PR_GROWING);
   1380 	pp->pr_flags &= ~(PR_GROWING|PR_GROWINGNOWAIT);
   1381 	return ENOMEM;
   1382 }
   1383 
   1384 /*
   1385  * Add N items to the pool.
   1386  */
   1387 int
   1388 pool_prime(struct pool *pp, int n)
   1389 {
   1390 	int newpages;
   1391 	int error = 0;
   1392 
   1393 	mutex_enter(&pp->pr_lock);
   1394 
   1395 	newpages = roundup(n, pp->pr_itemsperpage) / pp->pr_itemsperpage;
   1396 
   1397 	while (newpages > 0) {
   1398 		error = pool_grow(pp, PR_NOWAIT);
   1399 		if (error) {
   1400 			if (error == ERESTART)
   1401 				continue;
   1402 			break;
   1403 		}
   1404 		pp->pr_minpages++;
   1405 		newpages--;
   1406 	}
   1407 
   1408 	if (pp->pr_minpages >= pp->pr_maxpages)
   1409 		pp->pr_maxpages = pp->pr_minpages + 1;	/* XXX */
   1410 
   1411 	mutex_exit(&pp->pr_lock);
   1412 	return error;
   1413 }
   1414 
   1415 /*
   1416  * Add a page worth of items to the pool.
   1417  *
   1418  * Note, we must be called with the pool descriptor LOCKED.
   1419  */
   1420 static void
   1421 pool_prime_page(struct pool *pp, void *storage, struct pool_item_header *ph)
   1422 {
   1423 	const unsigned int align = pp->pr_align;
   1424 	struct pool_item *pi;
   1425 	void *cp = storage;
   1426 	int n;
   1427 
   1428 	KASSERT(mutex_owned(&pp->pr_lock));
   1429 	KASSERTMSG(((pp->pr_roflags & PR_NOALIGN) ||
   1430 		(((uintptr_t)cp & (pp->pr_alloc->pa_pagesz - 1)) == 0)),
   1431 	    "%s: [%s] unaligned page: %p", __func__, pp->pr_wchan, cp);
   1432 
   1433 	/*
   1434 	 * Insert page header.
   1435 	 */
   1436 	LIST_INSERT_HEAD(&pp->pr_emptypages, ph, ph_pagelist);
   1437 	LIST_INIT(&ph->ph_itemlist);
   1438 	ph->ph_page = storage;
   1439 	ph->ph_nmissing = 0;
   1440 	ph->ph_time = time_uptime;
   1441 	if (pp->pr_roflags & PR_PHINPAGE)
   1442 		ph->ph_poolid = pp->pr_poolid;
   1443 	else
   1444 		SPLAY_INSERT(phtree, &pp->pr_phtree, ph);
   1445 
   1446 	pp->pr_nidle++;
   1447 
   1448 	/*
   1449 	 * The item space starts after the on-page header, if any.
   1450 	 */
   1451 	ph->ph_off = pp->pr_itemoffset;
   1452 
   1453 	/*
   1454 	 * Color this page.
   1455 	 */
   1456 	ph->ph_off += pp->pr_curcolor;
   1457 	cp = (char *)cp + ph->ph_off;
   1458 	if ((pp->pr_curcolor += align) > pp->pr_maxcolor)
   1459 		pp->pr_curcolor = 0;
   1460 
   1461 	KASSERT((((vaddr_t)cp) & (align - 1)) == 0);
   1462 
   1463 	/*
   1464 	 * Insert remaining chunks on the bucket list.
   1465 	 */
   1466 	n = pp->pr_itemsperpage;
   1467 	pp->pr_nitems += n;
   1468 
   1469 	if (pp->pr_roflags & PR_USEBMAP) {
   1470 		pr_item_bitmap_init(pp, ph);
   1471 	} else {
   1472 		while (n--) {
   1473 			pi = (struct pool_item *)cp;
   1474 
   1475 			KASSERT((((vaddr_t)pi) & (align - 1)) == 0);
   1476 
   1477 			/* Insert on page list */
   1478 			LIST_INSERT_HEAD(&ph->ph_itemlist, pi, pi_list);
   1479 #ifdef POOL_CHECK_MAGIC
   1480 			pi->pi_magic = PI_MAGIC;
   1481 #endif
   1482 			cp = (char *)cp + pp->pr_size;
   1483 
   1484 			KASSERT((((vaddr_t)cp) & (align - 1)) == 0);
   1485 		}
   1486 	}
   1487 
   1488 	/*
   1489 	 * If the pool was depleted, point at the new page.
   1490 	 */
   1491 	if (pp->pr_curpage == NULL)
   1492 		pp->pr_curpage = ph;
   1493 
   1494 	if (++pp->pr_npages > pp->pr_hiwat)
   1495 		pp->pr_hiwat = pp->pr_npages;
   1496 }
   1497 
   1498 /*
   1499  * Used by pool_get() when nitems drops below the low water mark.  This
   1500  * is used to catch up pr_nitems with the low water mark.
   1501  *
   1502  * Note 1, we never wait for memory here, we let the caller decide what to do.
   1503  *
   1504  * Note 2, we must be called with the pool already locked, and we return
   1505  * with it locked.
   1506  */
   1507 static int
   1508 pool_catchup(struct pool *pp)
   1509 {
   1510 	int error = 0;
   1511 
   1512 	while (POOL_NEEDS_CATCHUP(pp)) {
   1513 		error = pool_grow(pp, PR_NOWAIT);
   1514 		if (error) {
   1515 			if (error == ERESTART)
   1516 				continue;
   1517 			break;
   1518 		}
   1519 	}
   1520 	return error;
   1521 }
   1522 
   1523 static void
   1524 pool_update_curpage(struct pool *pp)
   1525 {
   1526 
   1527 	pp->pr_curpage = LIST_FIRST(&pp->pr_partpages);
   1528 	if (pp->pr_curpage == NULL) {
   1529 		pp->pr_curpage = LIST_FIRST(&pp->pr_emptypages);
   1530 	}
   1531 	KASSERT((pp->pr_curpage == NULL && pp->pr_nitems == 0) ||
   1532 	    (pp->pr_curpage != NULL && pp->pr_nitems > 0));
   1533 }
   1534 
   1535 void
   1536 pool_setlowat(struct pool *pp, int n)
   1537 {
   1538 
   1539 	mutex_enter(&pp->pr_lock);
   1540 
   1541 	pp->pr_minitems = n;
   1542 	pp->pr_minpages = (n == 0)
   1543 		? 0
   1544 		: roundup(n, pp->pr_itemsperpage) / pp->pr_itemsperpage;
   1545 
   1546 	/* Make sure we're caught up with the newly-set low water mark. */
   1547 	if (POOL_NEEDS_CATCHUP(pp) && pool_catchup(pp) != 0) {
   1548 		/*
   1549 		 * XXX: Should we log a warning?  Should we set up a timeout
   1550 		 * to try again in a second or so?  The latter could break
   1551 		 * a caller's assumptions about interrupt protection, etc.
   1552 		 */
   1553 	}
   1554 
   1555 	mutex_exit(&pp->pr_lock);
   1556 }
   1557 
   1558 void
   1559 pool_sethiwat(struct pool *pp, int n)
   1560 {
   1561 
   1562 	mutex_enter(&pp->pr_lock);
   1563 
   1564 	pp->pr_maxpages = (n == 0)
   1565 		? 0
   1566 		: roundup(n, pp->pr_itemsperpage) / pp->pr_itemsperpage;
   1567 
   1568 	mutex_exit(&pp->pr_lock);
   1569 }
   1570 
   1571 void
   1572 pool_sethardlimit(struct pool *pp, int n, const char *warnmess, int ratecap)
   1573 {
   1574 
   1575 	mutex_enter(&pp->pr_lock);
   1576 
   1577 	pp->pr_hardlimit = n;
   1578 	pp->pr_hardlimit_warning = warnmess;
   1579 	pp->pr_hardlimit_ratecap.tv_sec = ratecap;
   1580 	pp->pr_hardlimit_warning_last.tv_sec = 0;
   1581 	pp->pr_hardlimit_warning_last.tv_usec = 0;
   1582 
   1583 	/*
   1584 	 * In-line version of pool_sethiwat(), because we don't want to
   1585 	 * release the lock.
   1586 	 */
   1587 	pp->pr_maxpages = (n == 0)
   1588 		? 0
   1589 		: roundup(n, pp->pr_itemsperpage) / pp->pr_itemsperpage;
   1590 
   1591 	mutex_exit(&pp->pr_lock);
   1592 }
   1593 
   1594 /*
   1595  * Release all complete pages that have not been used recently.
   1596  *
   1597  * Must not be called from interrupt context.
   1598  */
   1599 int
   1600 pool_reclaim(struct pool *pp)
   1601 {
   1602 	struct pool_item_header *ph, *phnext;
   1603 	struct pool_pagelist pq;
   1604 	uint32_t curtime;
   1605 	bool klock;
   1606 	int rv;
   1607 
   1608 	KASSERT(!cpu_intr_p() && !cpu_softintr_p());
   1609 
   1610 	if (pp->pr_drain_hook != NULL) {
   1611 		/*
   1612 		 * The drain hook must be called with the pool unlocked.
   1613 		 */
   1614 		(*pp->pr_drain_hook)(pp->pr_drain_hook_arg, PR_NOWAIT);
   1615 	}
   1616 
   1617 	/*
   1618 	 * XXXSMP Because we do not want to cause non-MPSAFE code
   1619 	 * to block.
   1620 	 */
   1621 	if (pp->pr_ipl == IPL_SOFTNET || pp->pr_ipl == IPL_SOFTCLOCK ||
   1622 	    pp->pr_ipl == IPL_SOFTSERIAL) {
   1623 		KERNEL_LOCK(1, NULL);
   1624 		klock = true;
   1625 	} else
   1626 		klock = false;
   1627 
   1628 	/* Reclaim items from the pool's cache (if any). */
   1629 	if (pp->pr_cache != NULL)
   1630 		pool_cache_invalidate(pp->pr_cache);
   1631 
   1632 	if (mutex_tryenter(&pp->pr_lock) == 0) {
   1633 		if (klock) {
   1634 			KERNEL_UNLOCK_ONE(NULL);
   1635 		}
   1636 		return 0;
   1637 	}
   1638 
   1639 	LIST_INIT(&pq);
   1640 
   1641 	curtime = time_uptime;
   1642 
   1643 	for (ph = LIST_FIRST(&pp->pr_emptypages); ph != NULL; ph = phnext) {
   1644 		phnext = LIST_NEXT(ph, ph_pagelist);
   1645 
   1646 		/* Check our minimum page claim */
   1647 		if (pp->pr_npages <= pp->pr_minpages)
   1648 			break;
   1649 
   1650 		KASSERT(ph->ph_nmissing == 0);
   1651 		if (curtime - ph->ph_time < pool_inactive_time)
   1652 			continue;
   1653 
   1654 		/*
   1655 		 * If freeing this page would put us below
   1656 		 * the low water mark, stop now.
   1657 		 */
   1658 		if ((pp->pr_nitems - pp->pr_itemsperpage) <
   1659 		    pp->pr_minitems)
   1660 			break;
   1661 
   1662 		pr_rmpage(pp, ph, &pq);
   1663 	}
   1664 
   1665 	mutex_exit(&pp->pr_lock);
   1666 
   1667 	if (LIST_EMPTY(&pq))
   1668 		rv = 0;
   1669 	else {
   1670 		pr_pagelist_free(pp, &pq);
   1671 		rv = 1;
   1672 	}
   1673 
   1674 	if (klock) {
   1675 		KERNEL_UNLOCK_ONE(NULL);
   1676 	}
   1677 
   1678 	return rv;
   1679 }
   1680 
   1681 /*
   1682  * Drain pools, one at a time. The drained pool is returned within ppp.
   1683  *
   1684  * Note, must never be called from interrupt context.
   1685  */
   1686 bool
   1687 pool_drain(struct pool **ppp)
   1688 {
   1689 	bool reclaimed;
   1690 	struct pool *pp;
   1691 
   1692 	KASSERT(!TAILQ_EMPTY(&pool_head));
   1693 
   1694 	pp = NULL;
   1695 
   1696 	/* Find next pool to drain, and add a reference. */
   1697 	mutex_enter(&pool_head_lock);
   1698 	do {
   1699 		if (drainpp == NULL) {
   1700 			drainpp = TAILQ_FIRST(&pool_head);
   1701 		}
   1702 		if (drainpp != NULL) {
   1703 			pp = drainpp;
   1704 			drainpp = TAILQ_NEXT(pp, pr_poollist);
   1705 		}
   1706 		/*
   1707 		 * Skip completely idle pools.  We depend on at least
   1708 		 * one pool in the system being active.
   1709 		 */
   1710 	} while (pp == NULL || pp->pr_npages == 0);
   1711 	pp->pr_refcnt++;
   1712 	mutex_exit(&pool_head_lock);
   1713 
   1714 	/* Drain the cache (if any) and pool.. */
   1715 	reclaimed = pool_reclaim(pp);
   1716 
   1717 	/* Finally, unlock the pool. */
   1718 	mutex_enter(&pool_head_lock);
   1719 	pp->pr_refcnt--;
   1720 	cv_broadcast(&pool_busy);
   1721 	mutex_exit(&pool_head_lock);
   1722 
   1723 	if (ppp != NULL)
   1724 		*ppp = pp;
   1725 
   1726 	return reclaimed;
   1727 }
   1728 
   1729 /*
   1730  * Calculate the total number of pages consumed by pools.
   1731  */
   1732 int
   1733 pool_totalpages(void)
   1734 {
   1735 
   1736 	mutex_enter(&pool_head_lock);
   1737 	int pages = pool_totalpages_locked();
   1738 	mutex_exit(&pool_head_lock);
   1739 
   1740 	return pages;
   1741 }
   1742 
   1743 int
   1744 pool_totalpages_locked(void)
   1745 {
   1746 	struct pool *pp;
   1747 	uint64_t total = 0;
   1748 
   1749 	TAILQ_FOREACH(pp, &pool_head, pr_poollist) {
   1750 		uint64_t bytes = pp->pr_npages * pp->pr_alloc->pa_pagesz;
   1751 
   1752 		if ((pp->pr_roflags & PR_RECURSIVE) != 0)
   1753 			bytes -= (pp->pr_nout * pp->pr_size);
   1754 		total += bytes;
   1755 	}
   1756 
   1757 	return atop(total);
   1758 }
   1759 
   1760 /*
   1761  * Diagnostic helpers.
   1762  */
   1763 
   1764 void
   1765 pool_printall(const char *modif, void (*pr)(const char *, ...))
   1766 {
   1767 	struct pool *pp;
   1768 
   1769 	TAILQ_FOREACH(pp, &pool_head, pr_poollist) {
   1770 		pool_printit(pp, modif, pr);
   1771 	}
   1772 }
   1773 
   1774 void
   1775 pool_printit(struct pool *pp, const char *modif, void (*pr)(const char *, ...))
   1776 {
   1777 
   1778 	if (pp == NULL) {
   1779 		(*pr)("Must specify a pool to print.\n");
   1780 		return;
   1781 	}
   1782 
   1783 	pool_print1(pp, modif, pr);
   1784 }
   1785 
   1786 static void
   1787 pool_print_pagelist(struct pool *pp, struct pool_pagelist *pl,
   1788     void (*pr)(const char *, ...))
   1789 {
   1790 	struct pool_item_header *ph;
   1791 
   1792 	LIST_FOREACH(ph, pl, ph_pagelist) {
   1793 		(*pr)("\t\tpage %p, nmissing %d, time %" PRIu32 "\n",
   1794 		    ph->ph_page, ph->ph_nmissing, ph->ph_time);
   1795 #ifdef POOL_CHECK_MAGIC
   1796 		struct pool_item *pi;
   1797 		if (!(pp->pr_roflags & PR_USEBMAP)) {
   1798 			LIST_FOREACH(pi, &ph->ph_itemlist, pi_list) {
   1799 				if (pi->pi_magic != PI_MAGIC) {
   1800 					(*pr)("\t\t\titem %p, magic 0x%x\n",
   1801 					    pi, pi->pi_magic);
   1802 				}
   1803 			}
   1804 		}
   1805 #endif
   1806 	}
   1807 }
   1808 
   1809 static void
   1810 pool_print1(struct pool *pp, const char *modif, void (*pr)(const char *, ...))
   1811 {
   1812 	struct pool_item_header *ph;
   1813 	pool_cache_t pc;
   1814 	pcg_t *pcg;
   1815 	pool_cache_cpu_t *cc;
   1816 	uint64_t cpuhit, cpumiss;
   1817 	int i, print_log = 0, print_pagelist = 0, print_cache = 0;
   1818 	char c;
   1819 
   1820 	while ((c = *modif++) != '\0') {
   1821 		if (c == 'l')
   1822 			print_log = 1;
   1823 		if (c == 'p')
   1824 			print_pagelist = 1;
   1825 		if (c == 'c')
   1826 			print_cache = 1;
   1827 	}
   1828 
   1829 	if ((pc = pp->pr_cache) != NULL) {
   1830 		(*pr)("POOL CACHE");
   1831 	} else {
   1832 		(*pr)("POOL");
   1833 	}
   1834 
   1835 	(*pr)(" %s: size %u, align %u, ioff %u, roflags 0x%08x\n",
   1836 	    pp->pr_wchan, pp->pr_size, pp->pr_align, pp->pr_itemoffset,
   1837 	    pp->pr_roflags);
   1838 	(*pr)("\talloc %p\n", pp->pr_alloc);
   1839 	(*pr)("\tminitems %u, minpages %u, maxpages %u, npages %u\n",
   1840 	    pp->pr_minitems, pp->pr_minpages, pp->pr_maxpages, pp->pr_npages);
   1841 	(*pr)("\titemsperpage %u, nitems %u, nout %u, hardlimit %u\n",
   1842 	    pp->pr_itemsperpage, pp->pr_nitems, pp->pr_nout, pp->pr_hardlimit);
   1843 
   1844 	(*pr)("\tnget %lu, nfail %lu, nput %lu\n",
   1845 	    pp->pr_nget, pp->pr_nfail, pp->pr_nput);
   1846 	(*pr)("\tnpagealloc %lu, npagefree %lu, hiwat %u, nidle %lu\n",
   1847 	    pp->pr_npagealloc, pp->pr_npagefree, pp->pr_hiwat, pp->pr_nidle);
   1848 
   1849 	if (print_pagelist == 0)
   1850 		goto skip_pagelist;
   1851 
   1852 	if ((ph = LIST_FIRST(&pp->pr_emptypages)) != NULL)
   1853 		(*pr)("\n\tempty page list:\n");
   1854 	pool_print_pagelist(pp, &pp->pr_emptypages, pr);
   1855 	if ((ph = LIST_FIRST(&pp->pr_fullpages)) != NULL)
   1856 		(*pr)("\n\tfull page list:\n");
   1857 	pool_print_pagelist(pp, &pp->pr_fullpages, pr);
   1858 	if ((ph = LIST_FIRST(&pp->pr_partpages)) != NULL)
   1859 		(*pr)("\n\tpartial-page list:\n");
   1860 	pool_print_pagelist(pp, &pp->pr_partpages, pr);
   1861 
   1862 	if (pp->pr_curpage == NULL)
   1863 		(*pr)("\tno current page\n");
   1864 	else
   1865 		(*pr)("\tcurpage %p\n", pp->pr_curpage->ph_page);
   1866 
   1867  skip_pagelist:
   1868 	if (print_log == 0)
   1869 		goto skip_log;
   1870 
   1871 	(*pr)("\n");
   1872 
   1873  skip_log:
   1874 
   1875 #define PR_GROUPLIST(pcg)						\
   1876 	(*pr)("\t\tgroup %p: avail %d\n", pcg, pcg->pcg_avail);		\
   1877 	for (i = 0; i < pcg->pcg_size; i++) {				\
   1878 		if (pcg->pcg_objects[i].pcgo_pa !=			\
   1879 		    POOL_PADDR_INVALID) {				\
   1880 			(*pr)("\t\t\t%p, 0x%llx\n",			\
   1881 			    pcg->pcg_objects[i].pcgo_va,		\
   1882 			    (unsigned long long)			\
   1883 			    pcg->pcg_objects[i].pcgo_pa);		\
   1884 		} else {						\
   1885 			(*pr)("\t\t\t%p\n",				\
   1886 			    pcg->pcg_objects[i].pcgo_va);		\
   1887 		}							\
   1888 	}
   1889 
   1890 	if (pc != NULL) {
   1891 		cpuhit = 0;
   1892 		cpumiss = 0;
   1893 		for (i = 0; i < __arraycount(pc->pc_cpus); i++) {
   1894 			if ((cc = pc->pc_cpus[i]) == NULL)
   1895 				continue;
   1896 			cpuhit += cc->cc_hits;
   1897 			cpumiss += cc->cc_misses;
   1898 		}
   1899 		(*pr)("\tcpu layer hits %llu misses %llu\n", cpuhit, cpumiss);
   1900 		(*pr)("\tcache layer hits %llu misses %llu\n",
   1901 		    pc->pc_hits, pc->pc_misses);
   1902 		(*pr)("\tcache layer entry uncontended %llu contended %llu\n",
   1903 		    pc->pc_hits + pc->pc_misses - pc->pc_contended,
   1904 		    pc->pc_contended);
   1905 		(*pr)("\tcache layer empty groups %u full groups %u\n",
   1906 		    pc->pc_nempty, pc->pc_nfull);
   1907 		if (print_cache) {
   1908 			(*pr)("\tfull cache groups:\n");
   1909 			for (pcg = pc->pc_fullgroups; pcg != NULL;
   1910 			    pcg = pcg->pcg_next) {
   1911 				PR_GROUPLIST(pcg);
   1912 			}
   1913 			(*pr)("\tempty cache groups:\n");
   1914 			for (pcg = pc->pc_emptygroups; pcg != NULL;
   1915 			    pcg = pcg->pcg_next) {
   1916 				PR_GROUPLIST(pcg);
   1917 			}
   1918 		}
   1919 	}
   1920 #undef PR_GROUPLIST
   1921 }
   1922 
   1923 static int
   1924 pool_chk_page(struct pool *pp, const char *label, struct pool_item_header *ph)
   1925 {
   1926 	struct pool_item *pi;
   1927 	void *page;
   1928 	int n;
   1929 
   1930 	if ((pp->pr_roflags & PR_NOALIGN) == 0) {
   1931 		page = POOL_OBJ_TO_PAGE(pp, ph);
   1932 		if (page != ph->ph_page &&
   1933 		    (pp->pr_roflags & PR_PHINPAGE) != 0) {
   1934 			if (label != NULL)
   1935 				printf("%s: ", label);
   1936 			printf("pool(%p:%s): page inconsistency: page %p;"
   1937 			       " at page head addr %p (p %p)\n", pp,
   1938 				pp->pr_wchan, ph->ph_page,
   1939 				ph, page);
   1940 			return 1;
   1941 		}
   1942 	}
   1943 
   1944 	if ((pp->pr_roflags & PR_USEBMAP) != 0)
   1945 		return 0;
   1946 
   1947 	for (pi = LIST_FIRST(&ph->ph_itemlist), n = 0;
   1948 	     pi != NULL;
   1949 	     pi = LIST_NEXT(pi,pi_list), n++) {
   1950 
   1951 #ifdef POOL_CHECK_MAGIC
   1952 		if (pi->pi_magic != PI_MAGIC) {
   1953 			if (label != NULL)
   1954 				printf("%s: ", label);
   1955 			printf("pool(%s): free list modified: magic=%x;"
   1956 			       " page %p; item ordinal %d; addr %p\n",
   1957 				pp->pr_wchan, pi->pi_magic, ph->ph_page,
   1958 				n, pi);
   1959 			panic("pool");
   1960 		}
   1961 #endif
   1962 		if ((pp->pr_roflags & PR_NOALIGN) != 0) {
   1963 			continue;
   1964 		}
   1965 		page = POOL_OBJ_TO_PAGE(pp, pi);
   1966 		if (page == ph->ph_page)
   1967 			continue;
   1968 
   1969 		if (label != NULL)
   1970 			printf("%s: ", label);
   1971 		printf("pool(%p:%s): page inconsistency: page %p;"
   1972 		       " item ordinal %d; addr %p (p %p)\n", pp,
   1973 			pp->pr_wchan, ph->ph_page,
   1974 			n, pi, page);
   1975 		return 1;
   1976 	}
   1977 	return 0;
   1978 }
   1979 
   1980 
   1981 int
   1982 pool_chk(struct pool *pp, const char *label)
   1983 {
   1984 	struct pool_item_header *ph;
   1985 	int r = 0;
   1986 
   1987 	mutex_enter(&pp->pr_lock);
   1988 	LIST_FOREACH(ph, &pp->pr_emptypages, ph_pagelist) {
   1989 		r = pool_chk_page(pp, label, ph);
   1990 		if (r) {
   1991 			goto out;
   1992 		}
   1993 	}
   1994 	LIST_FOREACH(ph, &pp->pr_fullpages, ph_pagelist) {
   1995 		r = pool_chk_page(pp, label, ph);
   1996 		if (r) {
   1997 			goto out;
   1998 		}
   1999 	}
   2000 	LIST_FOREACH(ph, &pp->pr_partpages, ph_pagelist) {
   2001 		r = pool_chk_page(pp, label, ph);
   2002 		if (r) {
   2003 			goto out;
   2004 		}
   2005 	}
   2006 
   2007 out:
   2008 	mutex_exit(&pp->pr_lock);
   2009 	return r;
   2010 }
   2011 
   2012 /*
   2013  * pool_cache_init:
   2014  *
   2015  *	Initialize a pool cache.
   2016  */
   2017 pool_cache_t
   2018 pool_cache_init(size_t size, u_int align, u_int align_offset, u_int flags,
   2019     const char *wchan, struct pool_allocator *palloc, int ipl,
   2020     int (*ctor)(void *, void *, int), void (*dtor)(void *, void *), void *arg)
   2021 {
   2022 	pool_cache_t pc;
   2023 
   2024 	pc = pool_get(&cache_pool, PR_WAITOK);
   2025 	if (pc == NULL)
   2026 		return NULL;
   2027 
   2028 	pool_cache_bootstrap(pc, size, align, align_offset, flags, wchan,
   2029 	   palloc, ipl, ctor, dtor, arg);
   2030 
   2031 	return pc;
   2032 }
   2033 
   2034 /*
   2035  * pool_cache_bootstrap:
   2036  *
   2037  *	Kernel-private version of pool_cache_init().  The caller
   2038  *	provides initial storage.
   2039  */
   2040 void
   2041 pool_cache_bootstrap(pool_cache_t pc, size_t size, u_int align,
   2042     u_int align_offset, u_int flags, const char *wchan,
   2043     struct pool_allocator *palloc, int ipl,
   2044     int (*ctor)(void *, void *, int), void (*dtor)(void *, void *),
   2045     void *arg)
   2046 {
   2047 	CPU_INFO_ITERATOR cii;
   2048 	pool_cache_t pc1;
   2049 	struct cpu_info *ci;
   2050 	struct pool *pp;
   2051 
   2052 	pp = &pc->pc_pool;
   2053 	if (palloc == NULL && ipl == IPL_NONE) {
   2054 		if (size > PAGE_SIZE) {
   2055 			int bigidx = pool_bigidx(size);
   2056 
   2057 			palloc = &pool_allocator_big[bigidx];
   2058 			flags |= PR_NOALIGN;
   2059 		} else
   2060 			palloc = &pool_allocator_nointr;
   2061 	}
   2062 	pool_init(pp, size, align, align_offset, flags, wchan, palloc, ipl);
   2063 	mutex_init(&pc->pc_lock, MUTEX_DEFAULT, ipl);
   2064 
   2065 	if (ctor == NULL) {
   2066 		ctor = (int (*)(void *, void *, int))nullop;
   2067 	}
   2068 	if (dtor == NULL) {
   2069 		dtor = (void (*)(void *, void *))nullop;
   2070 	}
   2071 
   2072 	pc->pc_emptygroups = NULL;
   2073 	pc->pc_fullgroups = NULL;
   2074 	pc->pc_partgroups = NULL;
   2075 	pc->pc_ctor = ctor;
   2076 	pc->pc_dtor = dtor;
   2077 	pc->pc_arg  = arg;
   2078 	pc->pc_hits  = 0;
   2079 	pc->pc_misses = 0;
   2080 	pc->pc_nempty = 0;
   2081 	pc->pc_npart = 0;
   2082 	pc->pc_nfull = 0;
   2083 	pc->pc_contended = 0;
   2084 	pc->pc_refcnt = 0;
   2085 	pc->pc_freecheck = NULL;
   2086 
   2087 	if ((flags & PR_LARGECACHE) != 0) {
   2088 		pc->pc_pcgsize = PCG_NOBJECTS_LARGE;
   2089 		pc->pc_pcgpool = &pcg_large_pool;
   2090 	} else {
   2091 		pc->pc_pcgsize = PCG_NOBJECTS_NORMAL;
   2092 		pc->pc_pcgpool = &pcg_normal_pool;
   2093 	}
   2094 
   2095 	/* Allocate per-CPU caches. */
   2096 	memset(pc->pc_cpus, 0, sizeof(pc->pc_cpus));
   2097 	pc->pc_ncpu = 0;
   2098 	if (ncpu < 2) {
   2099 		/* XXX For sparc: boot CPU is not attached yet. */
   2100 		pool_cache_cpu_init1(curcpu(), pc);
   2101 	} else {
   2102 		for (CPU_INFO_FOREACH(cii, ci)) {
   2103 			pool_cache_cpu_init1(ci, pc);
   2104 		}
   2105 	}
   2106 
   2107 	/* Add to list of all pools. */
   2108 	if (__predict_true(!cold))
   2109 		mutex_enter(&pool_head_lock);
   2110 	TAILQ_FOREACH(pc1, &pool_cache_head, pc_cachelist) {
   2111 		if (strcmp(pc1->pc_pool.pr_wchan, pc->pc_pool.pr_wchan) > 0)
   2112 			break;
   2113 	}
   2114 	if (pc1 == NULL)
   2115 		TAILQ_INSERT_TAIL(&pool_cache_head, pc, pc_cachelist);
   2116 	else
   2117 		TAILQ_INSERT_BEFORE(pc1, pc, pc_cachelist);
   2118 	if (__predict_true(!cold))
   2119 		mutex_exit(&pool_head_lock);
   2120 
   2121 	membar_sync();
   2122 	pp->pr_cache = pc;
   2123 }
   2124 
   2125 /*
   2126  * pool_cache_destroy:
   2127  *
   2128  *	Destroy a pool cache.
   2129  */
   2130 void
   2131 pool_cache_destroy(pool_cache_t pc)
   2132 {
   2133 
   2134 	pool_cache_bootstrap_destroy(pc);
   2135 	pool_put(&cache_pool, pc);
   2136 }
   2137 
   2138 /*
   2139  * pool_cache_bootstrap_destroy:
   2140  *
   2141  *	Destroy a pool cache.
   2142  */
   2143 void
   2144 pool_cache_bootstrap_destroy(pool_cache_t pc)
   2145 {
   2146 	struct pool *pp = &pc->pc_pool;
   2147 	u_int i;
   2148 
   2149 	/* Remove it from the global list. */
   2150 	mutex_enter(&pool_head_lock);
   2151 	while (pc->pc_refcnt != 0)
   2152 		cv_wait(&pool_busy, &pool_head_lock);
   2153 	TAILQ_REMOVE(&pool_cache_head, pc, pc_cachelist);
   2154 	mutex_exit(&pool_head_lock);
   2155 
   2156 	/* First, invalidate the entire cache. */
   2157 	pool_cache_invalidate(pc);
   2158 
   2159 	/* Disassociate it from the pool. */
   2160 	mutex_enter(&pp->pr_lock);
   2161 	pp->pr_cache = NULL;
   2162 	mutex_exit(&pp->pr_lock);
   2163 
   2164 	/* Destroy per-CPU data */
   2165 	for (i = 0; i < __arraycount(pc->pc_cpus); i++)
   2166 		pool_cache_invalidate_cpu(pc, i);
   2167 
   2168 	/* Finally, destroy it. */
   2169 	mutex_destroy(&pc->pc_lock);
   2170 	pool_destroy(pp);
   2171 }
   2172 
   2173 /*
   2174  * pool_cache_cpu_init1:
   2175  *
   2176  *	Called for each pool_cache whenever a new CPU is attached.
   2177  */
   2178 static void
   2179 pool_cache_cpu_init1(struct cpu_info *ci, pool_cache_t pc)
   2180 {
   2181 	pool_cache_cpu_t *cc;
   2182 	int index;
   2183 
   2184 	index = ci->ci_index;
   2185 
   2186 	KASSERT(index < __arraycount(pc->pc_cpus));
   2187 
   2188 	if ((cc = pc->pc_cpus[index]) != NULL) {
   2189 		KASSERT(cc->cc_cpuindex == index);
   2190 		return;
   2191 	}
   2192 
   2193 	/*
   2194 	 * The first CPU is 'free'.  This needs to be the case for
   2195 	 * bootstrap - we may not be able to allocate yet.
   2196 	 */
   2197 	if (pc->pc_ncpu == 0) {
   2198 		cc = &pc->pc_cpu0;
   2199 		pc->pc_ncpu = 1;
   2200 	} else {
   2201 		mutex_enter(&pc->pc_lock);
   2202 		pc->pc_ncpu++;
   2203 		mutex_exit(&pc->pc_lock);
   2204 		cc = pool_get(&cache_cpu_pool, PR_WAITOK);
   2205 	}
   2206 
   2207 	cc->cc_ipl = pc->pc_pool.pr_ipl;
   2208 	cc->cc_iplcookie = makeiplcookie(cc->cc_ipl);
   2209 	cc->cc_cache = pc;
   2210 	cc->cc_cpuindex = index;
   2211 	cc->cc_hits = 0;
   2212 	cc->cc_misses = 0;
   2213 	cc->cc_current = __UNCONST(&pcg_dummy);
   2214 	cc->cc_previous = __UNCONST(&pcg_dummy);
   2215 
   2216 	pc->pc_cpus[index] = cc;
   2217 }
   2218 
   2219 /*
   2220  * pool_cache_cpu_init:
   2221  *
   2222  *	Called whenever a new CPU is attached.
   2223  */
   2224 void
   2225 pool_cache_cpu_init(struct cpu_info *ci)
   2226 {
   2227 	pool_cache_t pc;
   2228 
   2229 	mutex_enter(&pool_head_lock);
   2230 	TAILQ_FOREACH(pc, &pool_cache_head, pc_cachelist) {
   2231 		pc->pc_refcnt++;
   2232 		mutex_exit(&pool_head_lock);
   2233 
   2234 		pool_cache_cpu_init1(ci, pc);
   2235 
   2236 		mutex_enter(&pool_head_lock);
   2237 		pc->pc_refcnt--;
   2238 		cv_broadcast(&pool_busy);
   2239 	}
   2240 	mutex_exit(&pool_head_lock);
   2241 }
   2242 
   2243 /*
   2244  * pool_cache_reclaim:
   2245  *
   2246  *	Reclaim memory from a pool cache.
   2247  */
   2248 bool
   2249 pool_cache_reclaim(pool_cache_t pc)
   2250 {
   2251 
   2252 	return pool_reclaim(&pc->pc_pool);
   2253 }
   2254 
   2255 static void
   2256 pool_cache_destruct_object1(pool_cache_t pc, void *object)
   2257 {
   2258 	(*pc->pc_dtor)(pc->pc_arg, object);
   2259 	pool_put(&pc->pc_pool, object);
   2260 }
   2261 
   2262 /*
   2263  * pool_cache_destruct_object:
   2264  *
   2265  *	Force destruction of an object and its release back into
   2266  *	the pool.
   2267  */
   2268 void
   2269 pool_cache_destruct_object(pool_cache_t pc, void *object)
   2270 {
   2271 
   2272 	FREECHECK_IN(&pc->pc_freecheck, object);
   2273 
   2274 	pool_cache_destruct_object1(pc, object);
   2275 }
   2276 
   2277 /*
   2278  * pool_cache_invalidate_groups:
   2279  *
   2280  *	Invalidate a chain of groups and destruct all objects.
   2281  */
   2282 static void
   2283 pool_cache_invalidate_groups(pool_cache_t pc, pcg_t *pcg)
   2284 {
   2285 	void *object;
   2286 	pcg_t *next;
   2287 	int i;
   2288 
   2289 	for (; pcg != NULL; pcg = next) {
   2290 		next = pcg->pcg_next;
   2291 
   2292 		for (i = 0; i < pcg->pcg_avail; i++) {
   2293 			object = pcg->pcg_objects[i].pcgo_va;
   2294 			pool_cache_destruct_object1(pc, object);
   2295 		}
   2296 
   2297 		if (pcg->pcg_size == PCG_NOBJECTS_LARGE) {
   2298 			pool_put(&pcg_large_pool, pcg);
   2299 		} else {
   2300 			KASSERT(pcg->pcg_size == PCG_NOBJECTS_NORMAL);
   2301 			pool_put(&pcg_normal_pool, pcg);
   2302 		}
   2303 	}
   2304 }
   2305 
   2306 /*
   2307  * pool_cache_invalidate:
   2308  *
   2309  *	Invalidate a pool cache (destruct and release all of the
   2310  *	cached objects).  Does not reclaim objects from the pool.
   2311  *
   2312  *	Note: For pool caches that provide constructed objects, there
   2313  *	is an assumption that another level of synchronization is occurring
   2314  *	between the input to the constructor and the cache invalidation.
   2315  *
   2316  *	Invalidation is a costly process and should not be called from
   2317  *	interrupt context.
   2318  */
   2319 void
   2320 pool_cache_invalidate(pool_cache_t pc)
   2321 {
   2322 	uint64_t where;
   2323 	pcg_t *full, *empty, *part;
   2324 
   2325 	KASSERT(!cpu_intr_p() && !cpu_softintr_p());
   2326 
   2327 	if (ncpu < 2 || !mp_online) {
   2328 		/*
   2329 		 * We might be called early enough in the boot process
   2330 		 * for the CPU data structures to not be fully initialized.
   2331 		 * In this case, transfer the content of the local CPU's
   2332 		 * cache back into global cache as only this CPU is currently
   2333 		 * running.
   2334 		 */
   2335 		pool_cache_transfer(pc);
   2336 	} else {
   2337 		/*
   2338 		 * Signal all CPUs that they must transfer their local
   2339 		 * cache back to the global pool then wait for the xcall to
   2340 		 * complete.
   2341 		 */
   2342 		where = xc_broadcast(0, (xcfunc_t)pool_cache_transfer,
   2343 		    pc, NULL);
   2344 		xc_wait(where);
   2345 	}
   2346 
   2347 	/* Empty pool caches, then invalidate objects */
   2348 	mutex_enter(&pc->pc_lock);
   2349 	full = pc->pc_fullgroups;
   2350 	empty = pc->pc_emptygroups;
   2351 	part = pc->pc_partgroups;
   2352 	pc->pc_fullgroups = NULL;
   2353 	pc->pc_emptygroups = NULL;
   2354 	pc->pc_partgroups = NULL;
   2355 	pc->pc_nfull = 0;
   2356 	pc->pc_nempty = 0;
   2357 	pc->pc_npart = 0;
   2358 	mutex_exit(&pc->pc_lock);
   2359 
   2360 	pool_cache_invalidate_groups(pc, full);
   2361 	pool_cache_invalidate_groups(pc, empty);
   2362 	pool_cache_invalidate_groups(pc, part);
   2363 }
   2364 
   2365 /*
   2366  * pool_cache_invalidate_cpu:
   2367  *
   2368  *	Invalidate all CPU-bound cached objects in pool cache, the CPU being
   2369  *	identified by its associated index.
   2370  *	It is caller's responsibility to ensure that no operation is
   2371  *	taking place on this pool cache while doing this invalidation.
   2372  *	WARNING: as no inter-CPU locking is enforced, trying to invalidate
   2373  *	pool cached objects from a CPU different from the one currently running
   2374  *	may result in an undefined behaviour.
   2375  */
   2376 static void
   2377 pool_cache_invalidate_cpu(pool_cache_t pc, u_int index)
   2378 {
   2379 	pool_cache_cpu_t *cc;
   2380 	pcg_t *pcg;
   2381 
   2382 	if ((cc = pc->pc_cpus[index]) == NULL)
   2383 		return;
   2384 
   2385 	if ((pcg = cc->cc_current) != &pcg_dummy) {
   2386 		pcg->pcg_next = NULL;
   2387 		pool_cache_invalidate_groups(pc, pcg);
   2388 	}
   2389 	if ((pcg = cc->cc_previous) != &pcg_dummy) {
   2390 		pcg->pcg_next = NULL;
   2391 		pool_cache_invalidate_groups(pc, pcg);
   2392 	}
   2393 	if (cc != &pc->pc_cpu0)
   2394 		pool_put(&cache_cpu_pool, cc);
   2395 
   2396 }
   2397 
   2398 void
   2399 pool_cache_set_drain_hook(pool_cache_t pc, void (*fn)(void *, int), void *arg)
   2400 {
   2401 
   2402 	pool_set_drain_hook(&pc->pc_pool, fn, arg);
   2403 }
   2404 
   2405 void
   2406 pool_cache_setlowat(pool_cache_t pc, int n)
   2407 {
   2408 
   2409 	pool_setlowat(&pc->pc_pool, n);
   2410 }
   2411 
   2412 void
   2413 pool_cache_sethiwat(pool_cache_t pc, int n)
   2414 {
   2415 
   2416 	pool_sethiwat(&pc->pc_pool, n);
   2417 }
   2418 
   2419 void
   2420 pool_cache_sethardlimit(pool_cache_t pc, int n, const char *warnmess, int ratecap)
   2421 {
   2422 
   2423 	pool_sethardlimit(&pc->pc_pool, n, warnmess, ratecap);
   2424 }
   2425 
   2426 static bool __noinline
   2427 pool_cache_get_slow(pool_cache_cpu_t *cc, int s, void **objectp,
   2428 		    paddr_t *pap, int flags)
   2429 {
   2430 	pcg_t *pcg, *cur;
   2431 	uint64_t ncsw;
   2432 	pool_cache_t pc;
   2433 	void *object;
   2434 
   2435 	KASSERT(cc->cc_current->pcg_avail == 0);
   2436 	KASSERT(cc->cc_previous->pcg_avail == 0);
   2437 
   2438 	pc = cc->cc_cache;
   2439 	cc->cc_misses++;
   2440 
   2441 	/*
   2442 	 * Nothing was available locally.  Try and grab a group
   2443 	 * from the cache.
   2444 	 */
   2445 	if (__predict_false(!mutex_tryenter(&pc->pc_lock))) {
   2446 		ncsw = curlwp->l_ncsw;
   2447 		mutex_enter(&pc->pc_lock);
   2448 		pc->pc_contended++;
   2449 
   2450 		/*
   2451 		 * If we context switched while locking, then
   2452 		 * our view of the per-CPU data is invalid:
   2453 		 * retry.
   2454 		 */
   2455 		if (curlwp->l_ncsw != ncsw) {
   2456 			mutex_exit(&pc->pc_lock);
   2457 			return true;
   2458 		}
   2459 	}
   2460 
   2461 	if (__predict_true((pcg = pc->pc_fullgroups) != NULL)) {
   2462 		/*
   2463 		 * If there's a full group, release our empty
   2464 		 * group back to the cache.  Install the full
   2465 		 * group as cc_current and return.
   2466 		 */
   2467 		if (__predict_true((cur = cc->cc_current) != &pcg_dummy)) {
   2468 			KASSERT(cur->pcg_avail == 0);
   2469 			cur->pcg_next = pc->pc_emptygroups;
   2470 			pc->pc_emptygroups = cur;
   2471 			pc->pc_nempty++;
   2472 		}
   2473 		KASSERT(pcg->pcg_avail == pcg->pcg_size);
   2474 		cc->cc_current = pcg;
   2475 		pc->pc_fullgroups = pcg->pcg_next;
   2476 		pc->pc_hits++;
   2477 		pc->pc_nfull--;
   2478 		mutex_exit(&pc->pc_lock);
   2479 		return true;
   2480 	}
   2481 
   2482 	/*
   2483 	 * Nothing available locally or in cache.  Take the slow
   2484 	 * path: fetch a new object from the pool and construct
   2485 	 * it.
   2486 	 */
   2487 	pc->pc_misses++;
   2488 	mutex_exit(&pc->pc_lock);
   2489 	splx(s);
   2490 
   2491 	object = pool_get(&pc->pc_pool, flags);
   2492 	*objectp = object;
   2493 	if (__predict_false(object == NULL)) {
   2494 		KASSERT((flags & (PR_WAITOK|PR_NOWAIT)) == PR_NOWAIT);
   2495 		return false;
   2496 	}
   2497 
   2498 	if (__predict_false((*pc->pc_ctor)(pc->pc_arg, object, flags) != 0)) {
   2499 		pool_put(&pc->pc_pool, object);
   2500 		*objectp = NULL;
   2501 		return false;
   2502 	}
   2503 
   2504 	KASSERT((((vaddr_t)object) & (pc->pc_pool.pr_align - 1)) == 0);
   2505 
   2506 	if (pap != NULL) {
   2507 #ifdef POOL_VTOPHYS
   2508 		*pap = POOL_VTOPHYS(object);
   2509 #else
   2510 		*pap = POOL_PADDR_INVALID;
   2511 #endif
   2512 	}
   2513 
   2514 	FREECHECK_OUT(&pc->pc_freecheck, object);
   2515 	pool_cache_kleak_fill(pc, object);
   2516 	return false;
   2517 }
   2518 
   2519 /*
   2520  * pool_cache_get{,_paddr}:
   2521  *
   2522  *	Get an object from a pool cache (optionally returning
   2523  *	the physical address of the object).
   2524  */
   2525 void *
   2526 pool_cache_get_paddr(pool_cache_t pc, int flags, paddr_t *pap)
   2527 {
   2528 	pool_cache_cpu_t *cc;
   2529 	pcg_t *pcg;
   2530 	void *object;
   2531 	int s;
   2532 
   2533 	KASSERT(!(flags & PR_NOWAIT) != !(flags & PR_WAITOK));
   2534 	KASSERTMSG((!cpu_intr_p() && !cpu_softintr_p()) ||
   2535 	    (pc->pc_pool.pr_ipl != IPL_NONE || cold || panicstr != NULL),
   2536 	    "%s: [%s] is IPL_NONE, but called from interrupt context",
   2537 	    __func__, pc->pc_pool.pr_wchan);
   2538 
   2539 	if (flags & PR_WAITOK) {
   2540 		ASSERT_SLEEPABLE();
   2541 	}
   2542 
   2543 	/* Lock out interrupts and disable preemption. */
   2544 	s = splvm();
   2545 	while (/* CONSTCOND */ true) {
   2546 		/* Try and allocate an object from the current group. */
   2547 		cc = pc->pc_cpus[curcpu()->ci_index];
   2548 		KASSERT(cc->cc_cache == pc);
   2549 	 	pcg = cc->cc_current;
   2550 		if (__predict_true(pcg->pcg_avail > 0)) {
   2551 			object = pcg->pcg_objects[--pcg->pcg_avail].pcgo_va;
   2552 			if (__predict_false(pap != NULL))
   2553 				*pap = pcg->pcg_objects[pcg->pcg_avail].pcgo_pa;
   2554 #if defined(DIAGNOSTIC)
   2555 			pcg->pcg_objects[pcg->pcg_avail].pcgo_va = NULL;
   2556 			KASSERT(pcg->pcg_avail < pcg->pcg_size);
   2557 			KASSERT(object != NULL);
   2558 #endif
   2559 			cc->cc_hits++;
   2560 			splx(s);
   2561 			FREECHECK_OUT(&pc->pc_freecheck, object);
   2562 			pool_redzone_fill(&pc->pc_pool, object);
   2563 			pool_cache_kleak_fill(pc, object);
   2564 			return object;
   2565 		}
   2566 
   2567 		/*
   2568 		 * That failed.  If the previous group isn't empty, swap
   2569 		 * it with the current group and allocate from there.
   2570 		 */
   2571 		pcg = cc->cc_previous;
   2572 		if (__predict_true(pcg->pcg_avail > 0)) {
   2573 			cc->cc_previous = cc->cc_current;
   2574 			cc->cc_current = pcg;
   2575 			continue;
   2576 		}
   2577 
   2578 		/*
   2579 		 * Can't allocate from either group: try the slow path.
   2580 		 * If get_slow() allocated an object for us, or if
   2581 		 * no more objects are available, it will return false.
   2582 		 * Otherwise, we need to retry.
   2583 		 */
   2584 		if (!pool_cache_get_slow(cc, s, &object, pap, flags))
   2585 			break;
   2586 	}
   2587 
   2588 	/*
   2589 	 * We would like to KASSERT(object || (flags & PR_NOWAIT)), but
   2590 	 * pool_cache_get can fail even in the PR_WAITOK case, if the
   2591 	 * constructor fails.
   2592 	 */
   2593 	return object;
   2594 }
   2595 
   2596 static bool __noinline
   2597 pool_cache_put_slow(pool_cache_cpu_t *cc, int s, void *object)
   2598 {
   2599 	struct lwp *l = curlwp;
   2600 	pcg_t *pcg, *cur;
   2601 	uint64_t ncsw;
   2602 	pool_cache_t pc;
   2603 
   2604 	KASSERT(cc->cc_current->pcg_avail == cc->cc_current->pcg_size);
   2605 	KASSERT(cc->cc_previous->pcg_avail == cc->cc_previous->pcg_size);
   2606 
   2607 	pc = cc->cc_cache;
   2608 	pcg = NULL;
   2609 	cc->cc_misses++;
   2610 	ncsw = l->l_ncsw;
   2611 
   2612 	/*
   2613 	 * If there are no empty groups in the cache then allocate one
   2614 	 * while still unlocked.
   2615 	 */
   2616 	if (__predict_false(pc->pc_emptygroups == NULL)) {
   2617 		if (__predict_true(!pool_cache_disable)) {
   2618 			pcg = pool_get(pc->pc_pcgpool, PR_NOWAIT);
   2619 		}
   2620 		/*
   2621 		 * If pool_get() blocked, then our view of
   2622 		 * the per-CPU data is invalid: retry.
   2623 		 */
   2624 		if (__predict_false(l->l_ncsw != ncsw)) {
   2625 			if (pcg != NULL) {
   2626 				pool_put(pc->pc_pcgpool, pcg);
   2627 			}
   2628 			return true;
   2629 		}
   2630 		if (__predict_true(pcg != NULL)) {
   2631 			pcg->pcg_avail = 0;
   2632 			pcg->pcg_size = pc->pc_pcgsize;
   2633 		}
   2634 	}
   2635 
   2636 	/* Lock the cache. */
   2637 	if (__predict_false(!mutex_tryenter(&pc->pc_lock))) {
   2638 		mutex_enter(&pc->pc_lock);
   2639 		pc->pc_contended++;
   2640 
   2641 		/*
   2642 		 * If we context switched while locking, then our view of
   2643 		 * the per-CPU data is invalid: retry.
   2644 		 */
   2645 		if (__predict_false(l->l_ncsw != ncsw)) {
   2646 			mutex_exit(&pc->pc_lock);
   2647 			if (pcg != NULL) {
   2648 				pool_put(pc->pc_pcgpool, pcg);
   2649 			}
   2650 			return true;
   2651 		}
   2652 	}
   2653 
   2654 	/* If there are no empty groups in the cache then allocate one. */
   2655 	if (pcg == NULL && pc->pc_emptygroups != NULL) {
   2656 		pcg = pc->pc_emptygroups;
   2657 		pc->pc_emptygroups = pcg->pcg_next;
   2658 		pc->pc_nempty--;
   2659 	}
   2660 
   2661 	/*
   2662 	 * If there's a empty group, release our full group back
   2663 	 * to the cache.  Install the empty group to the local CPU
   2664 	 * and return.
   2665 	 */
   2666 	if (pcg != NULL) {
   2667 		KASSERT(pcg->pcg_avail == 0);
   2668 		if (__predict_false(cc->cc_previous == &pcg_dummy)) {
   2669 			cc->cc_previous = pcg;
   2670 		} else {
   2671 			cur = cc->cc_current;
   2672 			if (__predict_true(cur != &pcg_dummy)) {
   2673 				KASSERT(cur->pcg_avail == cur->pcg_size);
   2674 				cur->pcg_next = pc->pc_fullgroups;
   2675 				pc->pc_fullgroups = cur;
   2676 				pc->pc_nfull++;
   2677 			}
   2678 			cc->cc_current = pcg;
   2679 		}
   2680 		pc->pc_hits++;
   2681 		mutex_exit(&pc->pc_lock);
   2682 		return true;
   2683 	}
   2684 
   2685 	/*
   2686 	 * Nothing available locally or in cache, and we didn't
   2687 	 * allocate an empty group.  Take the slow path and destroy
   2688 	 * the object here and now.
   2689 	 */
   2690 	pc->pc_misses++;
   2691 	mutex_exit(&pc->pc_lock);
   2692 	splx(s);
   2693 	pool_cache_destruct_object(pc, object);
   2694 
   2695 	return false;
   2696 }
   2697 
   2698 /*
   2699  * pool_cache_put{,_paddr}:
   2700  *
   2701  *	Put an object back to the pool cache (optionally caching the
   2702  *	physical address of the object).
   2703  */
   2704 void
   2705 pool_cache_put_paddr(pool_cache_t pc, void *object, paddr_t pa)
   2706 {
   2707 	pool_cache_cpu_t *cc;
   2708 	pcg_t *pcg;
   2709 	int s;
   2710 
   2711 	KASSERT(object != NULL);
   2712 	pool_cache_redzone_check(pc, object);
   2713 	FREECHECK_IN(&pc->pc_freecheck, object);
   2714 
   2715 	if (pc->pc_pool.pr_roflags & PR_PHINPAGE) {
   2716 		pc_phinpage_check(pc, object);
   2717 	}
   2718 
   2719 	if (pool_cache_put_quarantine(pc, object, pa)) {
   2720 		return;
   2721 	}
   2722 
   2723 	/* Lock out interrupts and disable preemption. */
   2724 	s = splvm();
   2725 	while (/* CONSTCOND */ true) {
   2726 		/* If the current group isn't full, release it there. */
   2727 		cc = pc->pc_cpus[curcpu()->ci_index];
   2728 		KASSERT(cc->cc_cache == pc);
   2729 	 	pcg = cc->cc_current;
   2730 		if (__predict_true(pcg->pcg_avail < pcg->pcg_size)) {
   2731 			pcg->pcg_objects[pcg->pcg_avail].pcgo_va = object;
   2732 			pcg->pcg_objects[pcg->pcg_avail].pcgo_pa = pa;
   2733 			pcg->pcg_avail++;
   2734 			cc->cc_hits++;
   2735 			splx(s);
   2736 			return;
   2737 		}
   2738 
   2739 		/*
   2740 		 * That failed.  If the previous group isn't full, swap
   2741 		 * it with the current group and try again.
   2742 		 */
   2743 		pcg = cc->cc_previous;
   2744 		if (__predict_true(pcg->pcg_avail < pcg->pcg_size)) {
   2745 			cc->cc_previous = cc->cc_current;
   2746 			cc->cc_current = pcg;
   2747 			continue;
   2748 		}
   2749 
   2750 		/*
   2751 		 * Can't free to either group: try the slow path.
   2752 		 * If put_slow() releases the object for us, it
   2753 		 * will return false.  Otherwise we need to retry.
   2754 		 */
   2755 		if (!pool_cache_put_slow(cc, s, object))
   2756 			break;
   2757 	}
   2758 }
   2759 
   2760 /*
   2761  * pool_cache_transfer:
   2762  *
   2763  *	Transfer objects from the per-CPU cache to the global cache.
   2764  *	Run within a cross-call thread.
   2765  */
   2766 static void
   2767 pool_cache_transfer(pool_cache_t pc)
   2768 {
   2769 	pool_cache_cpu_t *cc;
   2770 	pcg_t *prev, *cur, **list;
   2771 	int s;
   2772 
   2773 	s = splvm();
   2774 	mutex_enter(&pc->pc_lock);
   2775 	cc = pc->pc_cpus[curcpu()->ci_index];
   2776 	cur = cc->cc_current;
   2777 	cc->cc_current = __UNCONST(&pcg_dummy);
   2778 	prev = cc->cc_previous;
   2779 	cc->cc_previous = __UNCONST(&pcg_dummy);
   2780 	if (cur != &pcg_dummy) {
   2781 		if (cur->pcg_avail == cur->pcg_size) {
   2782 			list = &pc->pc_fullgroups;
   2783 			pc->pc_nfull++;
   2784 		} else if (cur->pcg_avail == 0) {
   2785 			list = &pc->pc_emptygroups;
   2786 			pc->pc_nempty++;
   2787 		} else {
   2788 			list = &pc->pc_partgroups;
   2789 			pc->pc_npart++;
   2790 		}
   2791 		cur->pcg_next = *list;
   2792 		*list = cur;
   2793 	}
   2794 	if (prev != &pcg_dummy) {
   2795 		if (prev->pcg_avail == prev->pcg_size) {
   2796 			list = &pc->pc_fullgroups;
   2797 			pc->pc_nfull++;
   2798 		} else if (prev->pcg_avail == 0) {
   2799 			list = &pc->pc_emptygroups;
   2800 			pc->pc_nempty++;
   2801 		} else {
   2802 			list = &pc->pc_partgroups;
   2803 			pc->pc_npart++;
   2804 		}
   2805 		prev->pcg_next = *list;
   2806 		*list = prev;
   2807 	}
   2808 	mutex_exit(&pc->pc_lock);
   2809 	splx(s);
   2810 }
   2811 
   2812 static int
   2813 pool_bigidx(size_t size)
   2814 {
   2815 	int i;
   2816 
   2817 	for (i = 0; i < __arraycount(pool_allocator_big); i++) {
   2818 		if (1 << (i + POOL_ALLOCATOR_BIG_BASE) >= size)
   2819 			return i;
   2820 	}
   2821 	panic("pool item size %zu too large, use a custom allocator", size);
   2822 }
   2823 
   2824 static void *
   2825 pool_allocator_alloc(struct pool *pp, int flags)
   2826 {
   2827 	struct pool_allocator *pa = pp->pr_alloc;
   2828 	void *res;
   2829 
   2830 	res = (*pa->pa_alloc)(pp, flags);
   2831 	if (res == NULL && (flags & PR_WAITOK) == 0) {
   2832 		/*
   2833 		 * We only run the drain hook here if PR_NOWAIT.
   2834 		 * In other cases, the hook will be run in
   2835 		 * pool_reclaim().
   2836 		 */
   2837 		if (pp->pr_drain_hook != NULL) {
   2838 			(*pp->pr_drain_hook)(pp->pr_drain_hook_arg, flags);
   2839 			res = (*pa->pa_alloc)(pp, flags);
   2840 		}
   2841 	}
   2842 	return res;
   2843 }
   2844 
   2845 static void
   2846 pool_allocator_free(struct pool *pp, void *v)
   2847 {
   2848 	struct pool_allocator *pa = pp->pr_alloc;
   2849 
   2850 	if (pp->pr_redzone) {
   2851 		kasan_mark(v, pa->pa_pagesz, pa->pa_pagesz, 0);
   2852 	}
   2853 	(*pa->pa_free)(pp, v);
   2854 }
   2855 
   2856 void *
   2857 pool_page_alloc(struct pool *pp, int flags)
   2858 {
   2859 	const vm_flag_t vflags = (flags & PR_WAITOK) ? VM_SLEEP: VM_NOSLEEP;
   2860 	vmem_addr_t va;
   2861 	int ret;
   2862 
   2863 	ret = uvm_km_kmem_alloc(kmem_va_arena, pp->pr_alloc->pa_pagesz,
   2864 	    vflags | VM_INSTANTFIT, &va);
   2865 
   2866 	return ret ? NULL : (void *)va;
   2867 }
   2868 
   2869 void
   2870 pool_page_free(struct pool *pp, void *v)
   2871 {
   2872 
   2873 	uvm_km_kmem_free(kmem_va_arena, (vaddr_t)v, pp->pr_alloc->pa_pagesz);
   2874 }
   2875 
   2876 static void *
   2877 pool_page_alloc_meta(struct pool *pp, int flags)
   2878 {
   2879 	const vm_flag_t vflags = (flags & PR_WAITOK) ? VM_SLEEP: VM_NOSLEEP;
   2880 	vmem_addr_t va;
   2881 	int ret;
   2882 
   2883 	ret = vmem_alloc(kmem_meta_arena, pp->pr_alloc->pa_pagesz,
   2884 	    vflags | VM_INSTANTFIT, &va);
   2885 
   2886 	return ret ? NULL : (void *)va;
   2887 }
   2888 
   2889 static void
   2890 pool_page_free_meta(struct pool *pp, void *v)
   2891 {
   2892 
   2893 	vmem_free(kmem_meta_arena, (vmem_addr_t)v, pp->pr_alloc->pa_pagesz);
   2894 }
   2895 
   2896 #ifdef KLEAK
   2897 static void
   2898 pool_kleak_fill(struct pool *pp, void *p)
   2899 {
   2900 	if (__predict_false(pp->pr_roflags & PR_NOTOUCH)) {
   2901 		return;
   2902 	}
   2903 	kleak_fill_area(p, pp->pr_size);
   2904 }
   2905 
   2906 static void
   2907 pool_cache_kleak_fill(pool_cache_t pc, void *p)
   2908 {
   2909 	if (__predict_false(pc_has_ctor(pc) || pc_has_dtor(pc))) {
   2910 		return;
   2911 	}
   2912 	pool_kleak_fill(&pc->pc_pool, p);
   2913 }
   2914 #endif
   2915 
   2916 #ifdef POOL_QUARANTINE
   2917 static void
   2918 pool_quarantine_init(struct pool *pp)
   2919 {
   2920 	pp->pr_quar.rotor = 0;
   2921 	memset(&pp->pr_quar, 0, sizeof(pp->pr_quar));
   2922 }
   2923 
   2924 static void
   2925 pool_quarantine_flush(struct pool *pp)
   2926 {
   2927 	pool_quar_t *quar = &pp->pr_quar;
   2928 	struct pool_pagelist pq;
   2929 	size_t i;
   2930 
   2931 	LIST_INIT(&pq);
   2932 
   2933 	mutex_enter(&pp->pr_lock);
   2934 	for (i = 0; i < POOL_QUARANTINE_DEPTH; i++) {
   2935 		if (quar->list[i] == 0)
   2936 			continue;
   2937 		pool_do_put(pp, (void *)quar->list[i], &pq);
   2938 	}
   2939 	mutex_exit(&pp->pr_lock);
   2940 
   2941 	pr_pagelist_free(pp, &pq);
   2942 }
   2943 
   2944 static bool
   2945 pool_put_quarantine(struct pool *pp, void *v, struct pool_pagelist *pq)
   2946 {
   2947 	pool_quar_t *quar = &pp->pr_quar;
   2948 	uintptr_t old;
   2949 
   2950 	if (pp->pr_roflags & PR_NOTOUCH) {
   2951 		return false;
   2952 	}
   2953 
   2954 	pool_redzone_check(pp, v);
   2955 
   2956 	old = quar->list[quar->rotor];
   2957 	quar->list[quar->rotor] = (uintptr_t)v;
   2958 	quar->rotor = (quar->rotor + 1) % POOL_QUARANTINE_DEPTH;
   2959 	if (old != 0) {
   2960 		pool_do_put(pp, (void *)old, pq);
   2961 	}
   2962 
   2963 	return true;
   2964 }
   2965 
   2966 static bool
   2967 pool_cache_put_quarantine(pool_cache_t pc, void *p, paddr_t pa)
   2968 {
   2969 	pool_cache_destruct_object(pc, p);
   2970 	return true;
   2971 }
   2972 #endif
   2973 
   2974 #ifdef POOL_REDZONE
   2975 #if defined(_LP64)
   2976 # define PRIME 0x9e37fffffffc0000UL
   2977 #else /* defined(_LP64) */
   2978 # define PRIME 0x9e3779b1
   2979 #endif /* defined(_LP64) */
   2980 #define STATIC_BYTE	0xFE
   2981 CTASSERT(POOL_REDZONE_SIZE > 1);
   2982 
   2983 #ifndef KASAN
   2984 static inline uint8_t
   2985 pool_pattern_generate(const void *p)
   2986 {
   2987 	return (uint8_t)(((uintptr_t)p) * PRIME
   2988 	   >> ((sizeof(uintptr_t) - sizeof(uint8_t))) * CHAR_BIT);
   2989 }
   2990 #endif
   2991 
   2992 static void
   2993 pool_redzone_init(struct pool *pp, size_t requested_size)
   2994 {
   2995 	size_t redzsz;
   2996 	size_t nsz;
   2997 
   2998 #ifdef KASAN
   2999 	redzsz = requested_size;
   3000 	kasan_add_redzone(&redzsz);
   3001 	redzsz -= requested_size;
   3002 #else
   3003 	redzsz = POOL_REDZONE_SIZE;
   3004 #endif
   3005 
   3006 	if (pp->pr_roflags & PR_NOTOUCH) {
   3007 		pp->pr_redzone = false;
   3008 		return;
   3009 	}
   3010 
   3011 	/*
   3012 	 * We may have extended the requested size earlier; check if
   3013 	 * there's naturally space in the padding for a red zone.
   3014 	 */
   3015 	if (pp->pr_size - requested_size >= redzsz) {
   3016 		pp->pr_reqsize_with_redzone = requested_size + redzsz;
   3017 		pp->pr_redzone = true;
   3018 		return;
   3019 	}
   3020 
   3021 	/*
   3022 	 * No space in the natural padding; check if we can extend a
   3023 	 * bit the size of the pool.
   3024 	 */
   3025 	nsz = roundup(pp->pr_size + redzsz, pp->pr_align);
   3026 	if (nsz <= pp->pr_alloc->pa_pagesz) {
   3027 		/* Ok, we can */
   3028 		pp->pr_size = nsz;
   3029 		pp->pr_reqsize_with_redzone = requested_size + redzsz;
   3030 		pp->pr_redzone = true;
   3031 	} else {
   3032 		/* No space for a red zone... snif :'( */
   3033 		pp->pr_redzone = false;
   3034 		printf("pool redzone disabled for '%s'\n", pp->pr_wchan);
   3035 	}
   3036 }
   3037 
   3038 static void
   3039 pool_redzone_fill(struct pool *pp, void *p)
   3040 {
   3041 	if (!pp->pr_redzone)
   3042 		return;
   3043 #ifdef KASAN
   3044 	kasan_mark(p, pp->pr_reqsize, pp->pr_reqsize_with_redzone,
   3045 	    KASAN_POOL_REDZONE);
   3046 #else
   3047 	uint8_t *cp, pat;
   3048 	const uint8_t *ep;
   3049 
   3050 	cp = (uint8_t *)p + pp->pr_reqsize;
   3051 	ep = cp + POOL_REDZONE_SIZE;
   3052 
   3053 	/*
   3054 	 * We really don't want the first byte of the red zone to be '\0';
   3055 	 * an off-by-one in a string may not be properly detected.
   3056 	 */
   3057 	pat = pool_pattern_generate(cp);
   3058 	*cp = (pat == '\0') ? STATIC_BYTE: pat;
   3059 	cp++;
   3060 
   3061 	while (cp < ep) {
   3062 		*cp = pool_pattern_generate(cp);
   3063 		cp++;
   3064 	}
   3065 #endif
   3066 }
   3067 
   3068 static void
   3069 pool_redzone_check(struct pool *pp, void *p)
   3070 {
   3071 	if (!pp->pr_redzone)
   3072 		return;
   3073 #ifdef KASAN
   3074 	kasan_mark(p, 0, pp->pr_reqsize_with_redzone, KASAN_POOL_FREED);
   3075 #else
   3076 	uint8_t *cp, pat, expected;
   3077 	const uint8_t *ep;
   3078 
   3079 	cp = (uint8_t *)p + pp->pr_reqsize;
   3080 	ep = cp + POOL_REDZONE_SIZE;
   3081 
   3082 	pat = pool_pattern_generate(cp);
   3083 	expected = (pat == '\0') ? STATIC_BYTE: pat;
   3084 	if (__predict_false(expected != *cp)) {
   3085 		printf("%s: %p: 0x%02x != 0x%02x\n",
   3086 		   __func__, cp, *cp, expected);
   3087 	}
   3088 	cp++;
   3089 
   3090 	while (cp < ep) {
   3091 		expected = pool_pattern_generate(cp);
   3092 		if (__predict_false(*cp != expected)) {
   3093 			printf("%s: %p: 0x%02x != 0x%02x\n",
   3094 			   __func__, cp, *cp, expected);
   3095 		}
   3096 		cp++;
   3097 	}
   3098 #endif
   3099 }
   3100 
   3101 static void
   3102 pool_cache_redzone_check(pool_cache_t pc, void *p)
   3103 {
   3104 #ifdef KASAN
   3105 	/* If there is a ctor/dtor, leave the data as valid. */
   3106 	if (__predict_false(pc_has_ctor(pc) || pc_has_dtor(pc))) {
   3107 		return;
   3108 	}
   3109 #endif
   3110 	pool_redzone_check(&pc->pc_pool, p);
   3111 }
   3112 
   3113 #endif /* POOL_REDZONE */
   3114 
   3115 #if defined(DDB)
   3116 static bool
   3117 pool_in_page(struct pool *pp, struct pool_item_header *ph, uintptr_t addr)
   3118 {
   3119 
   3120 	return (uintptr_t)ph->ph_page <= addr &&
   3121 	    addr < (uintptr_t)ph->ph_page + pp->pr_alloc->pa_pagesz;
   3122 }
   3123 
   3124 static bool
   3125 pool_in_item(struct pool *pp, void *item, uintptr_t addr)
   3126 {
   3127 
   3128 	return (uintptr_t)item <= addr && addr < (uintptr_t)item + pp->pr_size;
   3129 }
   3130 
   3131 static bool
   3132 pool_in_cg(struct pool *pp, struct pool_cache_group *pcg, uintptr_t addr)
   3133 {
   3134 	int i;
   3135 
   3136 	if (pcg == NULL) {
   3137 		return false;
   3138 	}
   3139 	for (i = 0; i < pcg->pcg_avail; i++) {
   3140 		if (pool_in_item(pp, pcg->pcg_objects[i].pcgo_va, addr)) {
   3141 			return true;
   3142 		}
   3143 	}
   3144 	return false;
   3145 }
   3146 
   3147 static bool
   3148 pool_allocated(struct pool *pp, struct pool_item_header *ph, uintptr_t addr)
   3149 {
   3150 
   3151 	if ((pp->pr_roflags & PR_USEBMAP) != 0) {
   3152 		unsigned int idx = pr_item_bitmap_index(pp, ph, (void *)addr);
   3153 		pool_item_bitmap_t *bitmap =
   3154 		    ph->ph_bitmap + (idx / BITMAP_SIZE);
   3155 		pool_item_bitmap_t mask = 1 << (idx & BITMAP_MASK);
   3156 
   3157 		return (*bitmap & mask) == 0;
   3158 	} else {
   3159 		struct pool_item *pi;
   3160 
   3161 		LIST_FOREACH(pi, &ph->ph_itemlist, pi_list) {
   3162 			if (pool_in_item(pp, pi, addr)) {
   3163 				return false;
   3164 			}
   3165 		}
   3166 		return true;
   3167 	}
   3168 }
   3169 
   3170 void
   3171 pool_whatis(uintptr_t addr, void (*pr)(const char *, ...))
   3172 {
   3173 	struct pool *pp;
   3174 
   3175 	TAILQ_FOREACH(pp, &pool_head, pr_poollist) {
   3176 		struct pool_item_header *ph;
   3177 		uintptr_t item;
   3178 		bool allocated = true;
   3179 		bool incache = false;
   3180 		bool incpucache = false;
   3181 		char cpucachestr[32];
   3182 
   3183 		if ((pp->pr_roflags & PR_PHINPAGE) != 0) {
   3184 			LIST_FOREACH(ph, &pp->pr_fullpages, ph_pagelist) {
   3185 				if (pool_in_page(pp, ph, addr)) {
   3186 					goto found;
   3187 				}
   3188 			}
   3189 			LIST_FOREACH(ph, &pp->pr_partpages, ph_pagelist) {
   3190 				if (pool_in_page(pp, ph, addr)) {
   3191 					allocated =
   3192 					    pool_allocated(pp, ph, addr);
   3193 					goto found;
   3194 				}
   3195 			}
   3196 			LIST_FOREACH(ph, &pp->pr_emptypages, ph_pagelist) {
   3197 				if (pool_in_page(pp, ph, addr)) {
   3198 					allocated = false;
   3199 					goto found;
   3200 				}
   3201 			}
   3202 			continue;
   3203 		} else {
   3204 			ph = pr_find_pagehead_noalign(pp, (void *)addr);
   3205 			if (ph == NULL || !pool_in_page(pp, ph, addr)) {
   3206 				continue;
   3207 			}
   3208 			allocated = pool_allocated(pp, ph, addr);
   3209 		}
   3210 found:
   3211 		if (allocated && pp->pr_cache) {
   3212 			pool_cache_t pc = pp->pr_cache;
   3213 			struct pool_cache_group *pcg;
   3214 			int i;
   3215 
   3216 			for (pcg = pc->pc_fullgroups; pcg != NULL;
   3217 			    pcg = pcg->pcg_next) {
   3218 				if (pool_in_cg(pp, pcg, addr)) {
   3219 					incache = true;
   3220 					goto print;
   3221 				}
   3222 			}
   3223 			for (i = 0; i < __arraycount(pc->pc_cpus); i++) {
   3224 				pool_cache_cpu_t *cc;
   3225 
   3226 				if ((cc = pc->pc_cpus[i]) == NULL) {
   3227 					continue;
   3228 				}
   3229 				if (pool_in_cg(pp, cc->cc_current, addr) ||
   3230 				    pool_in_cg(pp, cc->cc_previous, addr)) {
   3231 					struct cpu_info *ci =
   3232 					    cpu_lookup(i);
   3233 
   3234 					incpucache = true;
   3235 					snprintf(cpucachestr,
   3236 					    sizeof(cpucachestr),
   3237 					    "cached by CPU %u",
   3238 					    ci->ci_index);
   3239 					goto print;
   3240 				}
   3241 			}
   3242 		}
   3243 print:
   3244 		item = (uintptr_t)ph->ph_page + ph->ph_off;
   3245 		item = item + rounddown(addr - item, pp->pr_size);
   3246 		(*pr)("%p is %p+%zu in POOL '%s' (%s)\n",
   3247 		    (void *)addr, item, (size_t)(addr - item),
   3248 		    pp->pr_wchan,
   3249 		    incpucache ? cpucachestr :
   3250 		    incache ? "cached" : allocated ? "allocated" : "free");
   3251 	}
   3252 }
   3253 #endif /* defined(DDB) */
   3254 
   3255 static int
   3256 pool_sysctl(SYSCTLFN_ARGS)
   3257 {
   3258 	struct pool_sysctl data;
   3259 	struct pool *pp;
   3260 	struct pool_cache *pc;
   3261 	pool_cache_cpu_t *cc;
   3262 	int error;
   3263 	size_t i, written;
   3264 
   3265 	if (oldp == NULL) {
   3266 		*oldlenp = 0;
   3267 		TAILQ_FOREACH(pp, &pool_head, pr_poollist)
   3268 			*oldlenp += sizeof(data);
   3269 		return 0;
   3270 	}
   3271 
   3272 	memset(&data, 0, sizeof(data));
   3273 	error = 0;
   3274 	written = 0;
   3275 	TAILQ_FOREACH(pp, &pool_head, pr_poollist) {
   3276 		if (written + sizeof(data) > *oldlenp)
   3277 			break;
   3278 		strlcpy(data.pr_wchan, pp->pr_wchan, sizeof(data.pr_wchan));
   3279 		data.pr_pagesize = pp->pr_alloc->pa_pagesz;
   3280 		data.pr_flags = pp->pr_roflags | pp->pr_flags;
   3281 #define COPY(field) data.field = pp->field
   3282 		COPY(pr_size);
   3283 
   3284 		COPY(pr_itemsperpage);
   3285 		COPY(pr_nitems);
   3286 		COPY(pr_nout);
   3287 		COPY(pr_hardlimit);
   3288 		COPY(pr_npages);
   3289 		COPY(pr_minpages);
   3290 		COPY(pr_maxpages);
   3291 
   3292 		COPY(pr_nget);
   3293 		COPY(pr_nfail);
   3294 		COPY(pr_nput);
   3295 		COPY(pr_npagealloc);
   3296 		COPY(pr_npagefree);
   3297 		COPY(pr_hiwat);
   3298 		COPY(pr_nidle);
   3299 #undef COPY
   3300 
   3301 		data.pr_cache_nmiss_pcpu = 0;
   3302 		data.pr_cache_nhit_pcpu = 0;
   3303 		if (pp->pr_cache) {
   3304 			pc = pp->pr_cache;
   3305 			data.pr_cache_meta_size = pc->pc_pcgsize;
   3306 			data.pr_cache_nfull = pc->pc_nfull;
   3307 			data.pr_cache_npartial = pc->pc_npart;
   3308 			data.pr_cache_nempty = pc->pc_nempty;
   3309 			data.pr_cache_ncontended = pc->pc_contended;
   3310 			data.pr_cache_nmiss_global = pc->pc_misses;
   3311 			data.pr_cache_nhit_global = pc->pc_hits;
   3312 			for (i = 0; i < pc->pc_ncpu; ++i) {
   3313 				cc = pc->pc_cpus[i];
   3314 				if (cc == NULL)
   3315 					continue;
   3316 				data.pr_cache_nmiss_pcpu += cc->cc_misses;
   3317 				data.pr_cache_nhit_pcpu += cc->cc_hits;
   3318 			}
   3319 		} else {
   3320 			data.pr_cache_meta_size = 0;
   3321 			data.pr_cache_nfull = 0;
   3322 			data.pr_cache_npartial = 0;
   3323 			data.pr_cache_nempty = 0;
   3324 			data.pr_cache_ncontended = 0;
   3325 			data.pr_cache_nmiss_global = 0;
   3326 			data.pr_cache_nhit_global = 0;
   3327 		}
   3328 
   3329 		error = sysctl_copyout(l, &data, oldp, sizeof(data));
   3330 		if (error)
   3331 			break;
   3332 		written += sizeof(data);
   3333 		oldp = (char *)oldp + sizeof(data);
   3334 	}
   3335 
   3336 	*oldlenp = written;
   3337 	return error;
   3338 }
   3339 
   3340 SYSCTL_SETUP(sysctl_pool_setup, "sysctl kern.pool setup")
   3341 {
   3342 	const struct sysctlnode *rnode = NULL;
   3343 
   3344 	sysctl_createv(clog, 0, NULL, &rnode,
   3345 		       CTLFLAG_PERMANENT,
   3346 		       CTLTYPE_STRUCT, "pool",
   3347 		       SYSCTL_DESCR("Get pool statistics"),
   3348 		       pool_sysctl, 0, NULL, 0,
   3349 		       CTL_KERN, CTL_CREATE, CTL_EOL);
   3350 }
   3351