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