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