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