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