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