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