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