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