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