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