Home | History | Annotate | Line # | Download | only in kern
subr_pool.c revision 1.74.2.2
      1 /*	$NetBSD: subr_pool.c,v 1.74.2.2 2002/03/12 15:54:04 thorpej Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1997, 1999, 2000, 2002 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.
     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.74.2.2 2002/03/12 15:54:04 thorpej Exp $");
     42 
     43 #include "opt_pool.h"
     44 #include "opt_poollog.h"
     45 #include "opt_lockdebug.h"
     46 
     47 #include <sys/param.h>
     48 #include <sys/systm.h>
     49 #include <sys/proc.h>
     50 #include <sys/errno.h>
     51 #include <sys/kernel.h>
     52 #include <sys/malloc.h>
     53 #include <sys/lock.h>
     54 #include <sys/pool.h>
     55 #include <sys/syslog.h>
     56 
     57 #include <uvm/uvm.h>
     58 
     59 /*
     60  * Pool resource management utility.
     61  *
     62  * Memory is allocated in pages which are split into pieces according
     63  * to the pool item size. Each page is kept on a list headed by `pr_pagelist'
     64  * in the pool structure and the individual pool items are on a linked list
     65  * headed by `ph_itemlist' in each page header. The memory for building
     66  * the page list is either taken from the allocated pages themselves (for
     67  * small pool items) or taken from an internal pool of page headers (`phpool').
     68  */
     69 
     70 /* List of all pools */
     71 TAILQ_HEAD(,pool) pool_head = TAILQ_HEAD_INITIALIZER(pool_head);
     72 
     73 /* Private pool for page header structures */
     74 static struct pool phpool;
     75 
     76 #ifdef POOL_SUBPAGE
     77 /* Pool of subpages for use by normal pools. */
     78 static struct pool psppool;
     79 #endif
     80 
     81 /* # of seconds to retain page after last use */
     82 int pool_inactive_time = 10;
     83 
     84 /* Next candidate for drainage (see pool_drain()) */
     85 static struct pool	*drainpp;
     86 
     87 /* This spin lock protects both pool_head and drainpp. */
     88 struct simplelock pool_head_slock = SIMPLELOCK_INITIALIZER;
     89 
     90 struct pool_item_header {
     91 	/* Page headers */
     92 	TAILQ_ENTRY(pool_item_header)
     93 				ph_pagelist;	/* pool page list */
     94 	TAILQ_HEAD(,pool_item)	ph_itemlist;	/* chunk list for this page */
     95 	LIST_ENTRY(pool_item_header)
     96 				ph_hashlist;	/* Off-page page headers */
     97 	int			ph_nmissing;	/* # of chunks in use */
     98 	caddr_t			ph_page;	/* this page's address */
     99 	struct timeval		ph_time;	/* last referenced */
    100 };
    101 TAILQ_HEAD(pool_pagelist,pool_item_header);
    102 
    103 struct pool_item {
    104 #ifdef DIAGNOSTIC
    105 	int pi_magic;
    106 #endif
    107 #define	PI_MAGIC 0xdeadbeef
    108 	/* Other entries use only this list entry */
    109 	TAILQ_ENTRY(pool_item)	pi_list;
    110 };
    111 
    112 #define	PR_HASH_INDEX(pp,addr) \
    113 	(((u_long)(addr) >> (pp)->pr_alloc->pa_pageshift) & \
    114 	 (PR_HASHTABSIZE - 1))
    115 
    116 #define	POOL_NEEDS_CATCHUP(pp)						\
    117 	((pp)->pr_nitems < (pp)->pr_minitems)
    118 
    119 /*
    120  * Pool cache management.
    121  *
    122  * Pool caches provide a way for constructed objects to be cached by the
    123  * pool subsystem.  This can lead to performance improvements by avoiding
    124  * needless object construction/destruction; it is deferred until absolutely
    125  * necessary.
    126  *
    127  * Caches are grouped into cache groups.  Each cache group references
    128  * up to 16 constructed objects.  When a cache allocates an object
    129  * from the pool, it calls the object's constructor and places it into
    130  * a cache group.  When a cache group frees an object back to the pool,
    131  * it first calls the object's destructor.  This allows the object to
    132  * persist in constructed form while freed to the cache.
    133  *
    134  * Multiple caches may exist for each pool.  This allows a single
    135  * object type to have multiple constructed forms.  The pool references
    136  * each cache, so that when a pool is drained by the pagedaemon, it can
    137  * drain each individual cache as well.  Each time a cache is drained,
    138  * the most idle cache group is freed to the pool in its entirety.
    139  *
    140  * Pool caches are layed on top of pools.  By layering them, we can avoid
    141  * the complexity of cache management for pools which would not benefit
    142  * from it.
    143  */
    144 
    145 /* The cache group pool. */
    146 static struct pool pcgpool;
    147 
    148 /* The pool cache group. */
    149 #define	PCG_NOBJECTS		16
    150 struct pool_cache_group {
    151 	TAILQ_ENTRY(pool_cache_group)
    152 		pcg_list;	/* link in the pool cache's group list */
    153 	u_int	pcg_avail;	/* # available objects */
    154 				/* pointers to the objects */
    155 	void	*pcg_objects[PCG_NOBJECTS];
    156 };
    157 
    158 static void	pool_cache_reclaim(struct pool_cache *);
    159 
    160 static int	pool_catchup(struct pool *);
    161 static void	pool_prime_page(struct pool *, caddr_t,
    162 		    struct pool_item_header *);
    163 
    164 void		*pool_allocator_alloc(struct pool *, int);
    165 void		pool_allocator_free(struct pool *, void *);
    166 
    167 static void pool_print1(struct pool *, const char *,
    168 	void (*)(const char *, ...));
    169 
    170 /*
    171  * Pool log entry. An array of these is allocated in pool_init().
    172  */
    173 struct pool_log {
    174 	const char	*pl_file;
    175 	long		pl_line;
    176 	int		pl_action;
    177 #define	PRLOG_GET	1
    178 #define	PRLOG_PUT	2
    179 	void		*pl_addr;
    180 };
    181 
    182 /* Number of entries in pool log buffers */
    183 #ifndef POOL_LOGSIZE
    184 #define	POOL_LOGSIZE	10
    185 #endif
    186 
    187 int pool_logsize = POOL_LOGSIZE;
    188 
    189 #ifdef POOL_DIAGNOSTIC
    190 static __inline void
    191 pr_log(struct pool *pp, void *v, int action, const char *file, long line)
    192 {
    193 	int n = pp->pr_curlogentry;
    194 	struct pool_log *pl;
    195 
    196 	if ((pp->pr_roflags & PR_LOGGING) == 0)
    197 		return;
    198 
    199 	/*
    200 	 * Fill in the current entry. Wrap around and overwrite
    201 	 * the oldest entry if necessary.
    202 	 */
    203 	pl = &pp->pr_log[n];
    204 	pl->pl_file = file;
    205 	pl->pl_line = line;
    206 	pl->pl_action = action;
    207 	pl->pl_addr = v;
    208 	if (++n >= pp->pr_logsize)
    209 		n = 0;
    210 	pp->pr_curlogentry = n;
    211 }
    212 
    213 static void
    214 pr_printlog(struct pool *pp, struct pool_item *pi,
    215     void (*pr)(const char *, ...))
    216 {
    217 	int i = pp->pr_logsize;
    218 	int n = pp->pr_curlogentry;
    219 
    220 	if ((pp->pr_roflags & PR_LOGGING) == 0)
    221 		return;
    222 
    223 	/*
    224 	 * Print all entries in this pool's log.
    225 	 */
    226 	while (i-- > 0) {
    227 		struct pool_log *pl = &pp->pr_log[n];
    228 		if (pl->pl_action != 0) {
    229 			if (pi == NULL || pi == pl->pl_addr) {
    230 				(*pr)("\tlog entry %d:\n", i);
    231 				(*pr)("\t\taction = %s, addr = %p\n",
    232 				    pl->pl_action == PRLOG_GET ? "get" : "put",
    233 				    pl->pl_addr);
    234 				(*pr)("\t\tfile: %s at line %lu\n",
    235 				    pl->pl_file, pl->pl_line);
    236 			}
    237 		}
    238 		if (++n >= pp->pr_logsize)
    239 			n = 0;
    240 	}
    241 }
    242 
    243 static __inline void
    244 pr_enter(struct pool *pp, const char *file, long line)
    245 {
    246 
    247 	if (__predict_false(pp->pr_entered_file != NULL)) {
    248 		printf("pool %s: reentrancy at file %s line %ld\n",
    249 		    pp->pr_wchan, file, line);
    250 		printf("         previous entry at file %s line %ld\n",
    251 		    pp->pr_entered_file, pp->pr_entered_line);
    252 		panic("pr_enter");
    253 	}
    254 
    255 	pp->pr_entered_file = file;
    256 	pp->pr_entered_line = line;
    257 }
    258 
    259 static __inline void
    260 pr_leave(struct pool *pp)
    261 {
    262 
    263 	if (__predict_false(pp->pr_entered_file == NULL)) {
    264 		printf("pool %s not entered?\n", pp->pr_wchan);
    265 		panic("pr_leave");
    266 	}
    267 
    268 	pp->pr_entered_file = NULL;
    269 	pp->pr_entered_line = 0;
    270 }
    271 
    272 static __inline void
    273 pr_enter_check(struct pool *pp, void (*pr)(const char *, ...))
    274 {
    275 
    276 	if (pp->pr_entered_file != NULL)
    277 		(*pr)("\n\tcurrently entered from file %s line %ld\n",
    278 		    pp->pr_entered_file, pp->pr_entered_line);
    279 }
    280 #else
    281 #define	pr_log(pp, v, action, file, line)
    282 #define	pr_printlog(pp, pi, pr)
    283 #define	pr_enter(pp, file, line)
    284 #define	pr_leave(pp)
    285 #define	pr_enter_check(pp, pr)
    286 #endif /* POOL_DIAGNOSTIC */
    287 
    288 /*
    289  * Return the pool page header based on page address.
    290  */
    291 static __inline struct pool_item_header *
    292 pr_find_pagehead(struct pool *pp, caddr_t page)
    293 {
    294 	struct pool_item_header *ph;
    295 
    296 	if ((pp->pr_roflags & PR_PHINPAGE) != 0)
    297 		return ((struct pool_item_header *)(page + pp->pr_phoffset));
    298 
    299 	for (ph = LIST_FIRST(&pp->pr_hashtab[PR_HASH_INDEX(pp, page)]);
    300 	     ph != NULL;
    301 	     ph = LIST_NEXT(ph, ph_hashlist)) {
    302 		if (ph->ph_page == page)
    303 			return (ph);
    304 	}
    305 	return (NULL);
    306 }
    307 
    308 /*
    309  * Remove a page from the pool.
    310  */
    311 static __inline void
    312 pr_rmpage(struct pool *pp, struct pool_item_header *ph,
    313      struct pool_pagelist *pq)
    314 {
    315 	int s;
    316 
    317 	/*
    318 	 * If the page was idle, decrement the idle page count.
    319 	 */
    320 	if (ph->ph_nmissing == 0) {
    321 #ifdef DIAGNOSTIC
    322 		if (pp->pr_nidle == 0)
    323 			panic("pr_rmpage: nidle inconsistent");
    324 		if (pp->pr_nitems < pp->pr_itemsperpage)
    325 			panic("pr_rmpage: nitems inconsistent");
    326 #endif
    327 		pp->pr_nidle--;
    328 	}
    329 
    330 	pp->pr_nitems -= pp->pr_itemsperpage;
    331 
    332 	/*
    333 	 * Unlink a page from the pool and release it (or queue it for release).
    334 	 */
    335 	TAILQ_REMOVE(&pp->pr_pagelist, ph, ph_pagelist);
    336 	if (pq) {
    337 		TAILQ_INSERT_HEAD(pq, ph, ph_pagelist);
    338 	} else {
    339 		pool_allocator_free(pp, ph->ph_page);
    340 		if ((pp->pr_roflags & PR_PHINPAGE) == 0) {
    341 			LIST_REMOVE(ph, ph_hashlist);
    342 			s = splhigh();
    343 			pool_put(&phpool, ph);
    344 			splx(s);
    345 		}
    346 	}
    347 	pp->pr_npages--;
    348 	pp->pr_npagefree++;
    349 
    350 	if (pp->pr_curpage == ph) {
    351 		/*
    352 		 * Find a new non-empty page header, if any.
    353 		 * Start search from the page head, to increase the
    354 		 * chance for "high water" pages to be freed.
    355 		 */
    356 		TAILQ_FOREACH(ph, &pp->pr_pagelist, ph_pagelist)
    357 			if (TAILQ_FIRST(&ph->ph_itemlist) != NULL)
    358 				break;
    359 
    360 		pp->pr_curpage = ph;
    361 	}
    362 }
    363 
    364 /*
    365  * Initialize the given pool resource structure.
    366  *
    367  * We export this routine to allow other kernel parts to declare
    368  * static pools that must be initialized before malloc() is available.
    369  */
    370 void
    371 pool_init(struct pool *pp, size_t size, u_int align, u_int ioff, int flags,
    372     const char *wchan, struct pool_allocator *palloc)
    373 {
    374 	int off, slack, i;
    375 
    376 #ifdef POOL_DIAGNOSTIC
    377 	/*
    378 	 * Always log if POOL_DIAGNOSTIC is defined.
    379 	 */
    380 	if (pool_logsize != 0)
    381 		flags |= PR_LOGGING;
    382 #endif
    383 
    384 #ifdef POOL_SUBPAGE
    385 	/*
    386 	 * XXX We don't provide a real `nointr' back-end
    387 	 * yet; all sub-pages come from a kmem back-end.
    388 	 * maybe some day...
    389 	 */
    390 	if (palloc == NULL) {
    391 		extern struct pool_allocator pool_allocator_kmem_subpage;
    392 		palloc = &pool_allocator_kmem_subpage;
    393 	}
    394 	/*
    395 	 * We'll assume any user-specified back-end allocator
    396 	 * will deal with sub-pages, or simply don't care.
    397 	 */
    398 #else
    399 	if (palloc == NULL)
    400 		palloc = &pool_allocator_kmem;
    401 #endif /* POOL_SUBPAGE */
    402 	if ((palloc->pa_flags & PA_INITIALIZED) == 0) {
    403 		if (palloc->pa_pagesz == 0) {
    404 #ifdef POOL_SUBPAGE
    405 			if (palloc == &pool_allocator_kmem)
    406 				palloc->pa_pagesz = PAGE_SIZE;
    407 			else
    408 				palloc->pa_pagesz = POOL_SUBPAGE;
    409 #else
    410 			palloc->pa_pagesz = PAGE_SIZE;
    411 #endif /* POOL_SUBPAGE */
    412 		}
    413 
    414 		TAILQ_INIT(&palloc->pa_list);
    415 
    416 		simple_lock_init(&palloc->pa_slock);
    417 		palloc->pa_pagemask = ~(palloc->pa_pagesz - 1);
    418 		palloc->pa_pageshift = ffs(palloc->pa_pagesz) - 1;
    419 		palloc->pa_flags |= PA_INITIALIZED;
    420 	}
    421 
    422 	if (align == 0)
    423 		align = ALIGN(1);
    424 
    425 	if (size < sizeof(struct pool_item))
    426 		size = sizeof(struct pool_item);
    427 
    428 	size = roundup(size, align);
    429 #ifdef DIAGNOSTIC
    430 	if (size > palloc->pa_pagesz)
    431 		panic("pool_init: pool item size (%lu) too large",
    432 		      (u_long)size);
    433 #endif
    434 
    435 	/*
    436 	 * Initialize the pool structure.
    437 	 */
    438 	TAILQ_INIT(&pp->pr_pagelist);
    439 	TAILQ_INIT(&pp->pr_cachelist);
    440 	pp->pr_curpage = NULL;
    441 	pp->pr_npages = 0;
    442 	pp->pr_minitems = 0;
    443 	pp->pr_minpages = 0;
    444 	pp->pr_maxpages = UINT_MAX;
    445 	pp->pr_roflags = flags;
    446 	pp->pr_flags = 0;
    447 	pp->pr_size = size;
    448 	pp->pr_align = align;
    449 	pp->pr_wchan = wchan;
    450 	pp->pr_alloc = palloc;
    451 	pp->pr_nitems = 0;
    452 	pp->pr_nout = 0;
    453 	pp->pr_hardlimit = UINT_MAX;
    454 	pp->pr_hardlimit_warning = NULL;
    455 	pp->pr_hardlimit_ratecap.tv_sec = 0;
    456 	pp->pr_hardlimit_ratecap.tv_usec = 0;
    457 	pp->pr_hardlimit_warning_last.tv_sec = 0;
    458 	pp->pr_hardlimit_warning_last.tv_usec = 0;
    459 	pp->pr_drain_hook = NULL;
    460 	pp->pr_drain_hook_arg = NULL;
    461 
    462 	/*
    463 	 * Decide whether to put the page header off page to avoid
    464 	 * wasting too large a part of the page. Off-page page headers
    465 	 * go on a hash table, so we can match a returned item
    466 	 * with its header based on the page address.
    467 	 * We use 1/16 of the page size as the threshold (XXX: tune)
    468 	 */
    469 	if (pp->pr_size < palloc->pa_pagesz/16) {
    470 		/* Use the end of the page for the page header */
    471 		pp->pr_roflags |= PR_PHINPAGE;
    472 		pp->pr_phoffset = off = palloc->pa_pagesz -
    473 		    ALIGN(sizeof(struct pool_item_header));
    474 	} else {
    475 		/* The page header will be taken from our page header pool */
    476 		pp->pr_phoffset = 0;
    477 		off = palloc->pa_pagesz;
    478 		for (i = 0; i < PR_HASHTABSIZE; i++) {
    479 			LIST_INIT(&pp->pr_hashtab[i]);
    480 		}
    481 	}
    482 
    483 	/*
    484 	 * Alignment is to take place at `ioff' within the item. This means
    485 	 * we must reserve up to `align - 1' bytes on the page to allow
    486 	 * appropriate positioning of each item.
    487 	 *
    488 	 * Silently enforce `0 <= ioff < align'.
    489 	 */
    490 	pp->pr_itemoffset = ioff = ioff % align;
    491 	pp->pr_itemsperpage = (off - ((align - ioff) % align)) / pp->pr_size;
    492 	KASSERT(pp->pr_itemsperpage != 0);
    493 
    494 	/*
    495 	 * Use the slack between the chunks and the page header
    496 	 * for "cache coloring".
    497 	 */
    498 	slack = off - pp->pr_itemsperpage * pp->pr_size;
    499 	pp->pr_maxcolor = (slack / align) * align;
    500 	pp->pr_curcolor = 0;
    501 
    502 	pp->pr_nget = 0;
    503 	pp->pr_nfail = 0;
    504 	pp->pr_nput = 0;
    505 	pp->pr_npagealloc = 0;
    506 	pp->pr_npagefree = 0;
    507 	pp->pr_hiwat = 0;
    508 	pp->pr_nidle = 0;
    509 
    510 #ifdef POOL_DIAGNOSTIC
    511 	if (flags & PR_LOGGING) {
    512 		if (kmem_map == NULL ||
    513 		    (pp->pr_log = malloc(pool_logsize * sizeof(struct pool_log),
    514 		     M_TEMP, M_NOWAIT)) == NULL)
    515 			pp->pr_roflags &= ~PR_LOGGING;
    516 		pp->pr_curlogentry = 0;
    517 		pp->pr_logsize = pool_logsize;
    518 	}
    519 #endif
    520 
    521 	pp->pr_entered_file = NULL;
    522 	pp->pr_entered_line = 0;
    523 
    524 	simple_lock_init(&pp->pr_slock);
    525 
    526 	/*
    527 	 * Initialize private page header pool and cache magazine pool if we
    528 	 * haven't done so yet.
    529 	 * XXX LOCKING.
    530 	 */
    531 	if (phpool.pr_size == 0) {
    532 #ifdef POOL_SUBPAGE
    533 		pool_init(&phpool, sizeof(struct pool_item_header), 0, 0, 0,
    534 		    "phpool", &pool_allocator_kmem);
    535 		pool_init(&psppool, POOL_SUBPAGE, POOL_SUBPAGE, 0,
    536 		    PR_RECURSIVE, "psppool", &pool_allocator_kmem);
    537 #else
    538 		pool_init(&phpool, sizeof(struct pool_item_header), 0, 0,
    539 		    0, "phpool", NULL);
    540 #endif
    541 		pool_init(&pcgpool, sizeof(struct pool_cache_group), 0, 0,
    542 		    0, "pcgpool", NULL);
    543 	}
    544 
    545 	/* Insert into the list of all pools. */
    546 	simple_lock(&pool_head_slock);
    547 	TAILQ_INSERT_TAIL(&pool_head, pp, pr_poollist);
    548 	simple_unlock(&pool_head_slock);
    549 
    550 	/* Insert this into the list of pools using this allocator. */
    551 	simple_lock(&palloc->pa_slock);
    552 	TAILQ_INSERT_TAIL(&palloc->pa_list, pp, pr_alloc_list);
    553 	simple_unlock(&palloc->pa_slock);
    554 }
    555 
    556 /*
    557  * De-commision a pool resource.
    558  */
    559 void
    560 pool_destroy(struct pool *pp)
    561 {
    562 	struct pool_item_header *ph;
    563 	struct pool_cache *pc;
    564 
    565 	/* Locking order: pool_allocator -> pool */
    566 	simple_lock(&pp->pr_alloc->pa_slock);
    567 	TAILQ_REMOVE(&pp->pr_alloc->pa_list, pp, pr_alloc_list);
    568 	simple_unlock(&pp->pr_alloc->pa_slock);
    569 
    570 	/* Destroy all caches for this pool. */
    571 	while ((pc = TAILQ_FIRST(&pp->pr_cachelist)) != NULL)
    572 		pool_cache_destroy(pc);
    573 
    574 #ifdef DIAGNOSTIC
    575 	if (pp->pr_nout != 0) {
    576 		pr_printlog(pp, NULL, printf);
    577 		panic("pool_destroy: pool busy: still out: %u\n",
    578 		    pp->pr_nout);
    579 	}
    580 #endif
    581 
    582 	/* Remove all pages */
    583 	while ((ph = TAILQ_FIRST(&pp->pr_pagelist)) != NULL)
    584 		pr_rmpage(pp, ph, NULL);
    585 
    586 	/* Remove from global pool list */
    587 	simple_lock(&pool_head_slock);
    588 	TAILQ_REMOVE(&pool_head, pp, pr_poollist);
    589 	if (drainpp == pp) {
    590 		drainpp = NULL;
    591 	}
    592 	simple_unlock(&pool_head_slock);
    593 
    594 #ifdef POOL_DIAGNOSTIC
    595 	if ((pp->pr_roflags & PR_LOGGING) != 0)
    596 		free(pp->pr_log, M_TEMP);
    597 #endif
    598 }
    599 
    600 void
    601 pool_set_drain_hook(struct pool *pp, void (*fn)(void *, int), void *arg)
    602 {
    603 
    604 	/* XXX no locking -- must be used just after pool_init() */
    605 #ifdef DIAGNOSTIC
    606 	if (pp->pr_drain_hook != NULL)
    607 		panic("pool_set_drain_hook(%s): already set", pp->pr_wchan);
    608 #endif
    609 	pp->pr_drain_hook = fn;
    610 	pp->pr_drain_hook_arg = arg;
    611 }
    612 
    613 static __inline struct pool_item_header *
    614 pool_alloc_item_header(struct pool *pp, caddr_t storage, int flags)
    615 {
    616 	struct pool_item_header *ph;
    617 	int s;
    618 
    619 	LOCK_ASSERT(simple_lock_held(&pp->pr_slock) == 0);
    620 
    621 	if ((pp->pr_roflags & PR_PHINPAGE) != 0)
    622 		ph = (struct pool_item_header *) (storage + pp->pr_phoffset);
    623 	else {
    624 		s = splhigh();
    625 		ph = pool_get(&phpool, flags);
    626 		splx(s);
    627 	}
    628 
    629 	return (ph);
    630 }
    631 
    632 /*
    633  * Grab an item from the pool; must be called at appropriate spl level
    634  */
    635 void *
    636 #ifdef POOL_DIAGNOSTIC
    637 _pool_get(struct pool *pp, int flags, const char *file, long line)
    638 #else
    639 pool_get(struct pool *pp, int flags)
    640 #endif
    641 {
    642 	struct pool_item *pi;
    643 	struct pool_item_header *ph;
    644 	void *v;
    645 
    646 #ifdef DIAGNOSTIC
    647 	if (__predict_false(curproc == NULL && doing_shutdown == 0 &&
    648 			    (flags & PR_WAITOK) != 0))
    649 		panic("pool_get: must have NOWAIT");
    650 
    651 #ifdef LOCKDEBUG
    652 	if (flags & PR_WAITOK)
    653 		simple_lock_only_held(NULL, "pool_get(PR_WAITOK)");
    654 #endif
    655 #endif /* DIAGNOSTIC */
    656 
    657 	simple_lock(&pp->pr_slock);
    658 	pr_enter(pp, file, line);
    659 
    660  startover:
    661 	/*
    662 	 * Check to see if we've reached the hard limit.  If we have,
    663 	 * and we can wait, then wait until an item has been returned to
    664 	 * the pool.
    665 	 */
    666 #ifdef DIAGNOSTIC
    667 	if (__predict_false(pp->pr_nout > pp->pr_hardlimit)) {
    668 		pr_leave(pp);
    669 		simple_unlock(&pp->pr_slock);
    670 		panic("pool_get: %s: crossed hard limit", pp->pr_wchan);
    671 	}
    672 #endif
    673 	if (__predict_false(pp->pr_nout == pp->pr_hardlimit)) {
    674 		if (pp->pr_drain_hook != NULL) {
    675 			/*
    676 			 * Since the drain hook is going to free things
    677 			 * back to the pool, unlock, call the hook, re-lock,
    678 			 * and check the hardlimit condition again.
    679 			 */
    680 			pr_leave(pp);
    681 			simple_unlock(&pp->pr_slock);
    682 			(*pp->pr_drain_hook)(pp->pr_drain_hook_arg, flags);
    683 			simple_lock(&pp->pr_slock);
    684 			pr_enter(pp, file, line);
    685 			if (pp->pr_nout < pp->pr_hardlimit)
    686 				goto startover;
    687 		}
    688 
    689 		if ((flags & PR_WAITOK) && !(flags & PR_LIMITFAIL)) {
    690 			/*
    691 			 * XXX: A warning isn't logged in this case.  Should
    692 			 * it be?
    693 			 */
    694 			pp->pr_flags |= PR_WANTED;
    695 			pr_leave(pp);
    696 			ltsleep(pp, PSWP, pp->pr_wchan, 0, &pp->pr_slock);
    697 			pr_enter(pp, file, line);
    698 			goto startover;
    699 		}
    700 
    701 		/*
    702 		 * Log a message that the hard limit has been hit.
    703 		 */
    704 		if (pp->pr_hardlimit_warning != NULL &&
    705 		    ratecheck(&pp->pr_hardlimit_warning_last,
    706 			      &pp->pr_hardlimit_ratecap))
    707 			log(LOG_ERR, "%s\n", pp->pr_hardlimit_warning);
    708 
    709 		pp->pr_nfail++;
    710 
    711 		pr_leave(pp);
    712 		simple_unlock(&pp->pr_slock);
    713 		return (NULL);
    714 	}
    715 
    716 	/*
    717 	 * The convention we use is that if `curpage' is not NULL, then
    718 	 * it points at a non-empty bucket. In particular, `curpage'
    719 	 * never points at a page header which has PR_PHINPAGE set and
    720 	 * has no items in its bucket.
    721 	 */
    722 	if ((ph = pp->pr_curpage) == NULL) {
    723 #ifdef DIAGNOSTIC
    724 		if (pp->pr_nitems != 0) {
    725 			simple_unlock(&pp->pr_slock);
    726 			printf("pool_get: %s: curpage NULL, nitems %u\n",
    727 			    pp->pr_wchan, pp->pr_nitems);
    728 			panic("pool_get: nitems inconsistent\n");
    729 		}
    730 #endif
    731 
    732 		/*
    733 		 * Call the back-end page allocator for more memory.
    734 		 * Release the pool lock, as the back-end page allocator
    735 		 * may block.
    736 		 */
    737 		pr_leave(pp);
    738 		simple_unlock(&pp->pr_slock);
    739 		v = pool_allocator_alloc(pp, flags);
    740 		if (__predict_true(v != NULL))
    741 			ph = pool_alloc_item_header(pp, v, flags);
    742 		simple_lock(&pp->pr_slock);
    743 		pr_enter(pp, file, line);
    744 
    745 		if (__predict_false(v == NULL || ph == NULL)) {
    746 			if (v != NULL)
    747 				pool_allocator_free(pp, v);
    748 
    749 			/*
    750 			 * We were unable to allocate a page or item
    751 			 * header, but we released the lock during
    752 			 * allocation, so perhaps items were freed
    753 			 * back to the pool.  Check for this case.
    754 			 */
    755 			if (pp->pr_curpage != NULL)
    756 				goto startover;
    757 
    758 			if ((flags & PR_WAITOK) == 0) {
    759 				pp->pr_nfail++;
    760 				pr_leave(pp);
    761 				simple_unlock(&pp->pr_slock);
    762 				return (NULL);
    763 			}
    764 
    765 			/*
    766 			 * Wait for items to be returned to this pool.
    767 			 *
    768 			 * XXX: maybe we should wake up once a second and
    769 			 * try again?
    770 			 */
    771 			pp->pr_flags |= PR_WANTED;
    772 			/* PA_WANTED is already set on the allocator. */
    773 			pr_leave(pp);
    774 			ltsleep(pp, PSWP, pp->pr_wchan, 0, &pp->pr_slock);
    775 			pr_enter(pp, file, line);
    776 			goto startover;
    777 		}
    778 
    779 		/* We have more memory; add it to the pool */
    780 		pool_prime_page(pp, v, ph);
    781 		pp->pr_npagealloc++;
    782 
    783 		/* Start the allocation process over. */
    784 		goto startover;
    785 	}
    786 
    787 	if (__predict_false((v = pi = TAILQ_FIRST(&ph->ph_itemlist)) == NULL)) {
    788 		pr_leave(pp);
    789 		simple_unlock(&pp->pr_slock);
    790 		panic("pool_get: %s: page empty", pp->pr_wchan);
    791 	}
    792 #ifdef DIAGNOSTIC
    793 	if (__predict_false(pp->pr_nitems == 0)) {
    794 		pr_leave(pp);
    795 		simple_unlock(&pp->pr_slock);
    796 		printf("pool_get: %s: items on itemlist, nitems %u\n",
    797 		    pp->pr_wchan, pp->pr_nitems);
    798 		panic("pool_get: nitems inconsistent\n");
    799 	}
    800 #endif
    801 
    802 #ifdef POOL_DIAGNOSTIC
    803 	pr_log(pp, v, PRLOG_GET, file, line);
    804 #endif
    805 
    806 #ifdef DIAGNOSTIC
    807 	if (__predict_false(pi->pi_magic != PI_MAGIC)) {
    808 		pr_printlog(pp, pi, printf);
    809 		panic("pool_get(%s): free list modified: magic=%x; page %p;"
    810 		       " item addr %p\n",
    811 			pp->pr_wchan, pi->pi_magic, ph->ph_page, pi);
    812 	}
    813 #endif
    814 
    815 	/*
    816 	 * Remove from item list.
    817 	 */
    818 	TAILQ_REMOVE(&ph->ph_itemlist, pi, pi_list);
    819 	pp->pr_nitems--;
    820 	pp->pr_nout++;
    821 	if (ph->ph_nmissing == 0) {
    822 #ifdef DIAGNOSTIC
    823 		if (__predict_false(pp->pr_nidle == 0))
    824 			panic("pool_get: nidle inconsistent");
    825 #endif
    826 		pp->pr_nidle--;
    827 	}
    828 	ph->ph_nmissing++;
    829 	if (TAILQ_FIRST(&ph->ph_itemlist) == NULL) {
    830 #ifdef DIAGNOSTIC
    831 		if (__predict_false(ph->ph_nmissing != pp->pr_itemsperpage)) {
    832 			pr_leave(pp);
    833 			simple_unlock(&pp->pr_slock);
    834 			panic("pool_get: %s: nmissing inconsistent",
    835 			    pp->pr_wchan);
    836 		}
    837 #endif
    838 		/*
    839 		 * Find a new non-empty page header, if any.
    840 		 * Start search from the page head, to increase
    841 		 * the chance for "high water" pages to be freed.
    842 		 *
    843 		 * Migrate empty pages to the end of the list.  This
    844 		 * will speed the update of curpage as pages become
    845 		 * idle.  Empty pages intermingled with idle pages
    846 		 * is no big deal.  As soon as a page becomes un-empty,
    847 		 * it will move back to the head of the list.
    848 		 */
    849 		TAILQ_REMOVE(&pp->pr_pagelist, ph, ph_pagelist);
    850 		TAILQ_INSERT_TAIL(&pp->pr_pagelist, ph, ph_pagelist);
    851 		TAILQ_FOREACH(ph, &pp->pr_pagelist, ph_pagelist)
    852 			if (TAILQ_FIRST(&ph->ph_itemlist) != NULL)
    853 				break;
    854 
    855 		pp->pr_curpage = ph;
    856 	}
    857 
    858 	pp->pr_nget++;
    859 
    860 	/*
    861 	 * If we have a low water mark and we are now below that low
    862 	 * water mark, add more items to the pool.
    863 	 */
    864 	if (POOL_NEEDS_CATCHUP(pp) && pool_catchup(pp) != 0) {
    865 		/*
    866 		 * XXX: Should we log a warning?  Should we set up a timeout
    867 		 * to try again in a second or so?  The latter could break
    868 		 * a caller's assumptions about interrupt protection, etc.
    869 		 */
    870 	}
    871 
    872 	pr_leave(pp);
    873 	simple_unlock(&pp->pr_slock);
    874 	KASSERT((((vaddr_t)v + pp->pr_itemoffset) & (pp->pr_align - 1)) == 0);
    875 	return (v);
    876 }
    877 
    878 /*
    879  * Internal version of pool_put().  Pool is already locked/entered.
    880  */
    881 static void
    882 pool_do_put(struct pool *pp, void *v)
    883 {
    884 	struct pool_item *pi = v;
    885 	struct pool_item_header *ph;
    886 	caddr_t page;
    887 	int s;
    888 
    889 	LOCK_ASSERT(simple_lock_held(&pp->pr_slock));
    890 
    891 	page = (caddr_t)((u_long)v & pp->pr_alloc->pa_pagemask);
    892 
    893 #ifdef DIAGNOSTIC
    894 	if (__predict_false(pp->pr_nout == 0)) {
    895 		printf("pool %s: putting with none out\n",
    896 		    pp->pr_wchan);
    897 		panic("pool_put");
    898 	}
    899 #endif
    900 
    901 	if (__predict_false((ph = pr_find_pagehead(pp, page)) == NULL)) {
    902 		pr_printlog(pp, NULL, printf);
    903 		panic("pool_put: %s: page header missing", pp->pr_wchan);
    904 	}
    905 
    906 #ifdef LOCKDEBUG
    907 	/*
    908 	 * Check if we're freeing a locked simple lock.
    909 	 */
    910 	simple_lock_freecheck((caddr_t)pi, ((caddr_t)pi) + pp->pr_size);
    911 #endif
    912 
    913 	/*
    914 	 * Return to item list.
    915 	 */
    916 #ifdef DIAGNOSTIC
    917 	pi->pi_magic = PI_MAGIC;
    918 #endif
    919 #ifdef DEBUG
    920 	{
    921 		int i, *ip = v;
    922 
    923 		for (i = 0; i < pp->pr_size / sizeof(int); i++) {
    924 			*ip++ = PI_MAGIC;
    925 		}
    926 	}
    927 #endif
    928 
    929 	TAILQ_INSERT_HEAD(&ph->ph_itemlist, pi, pi_list);
    930 	ph->ph_nmissing--;
    931 	pp->pr_nput++;
    932 	pp->pr_nitems++;
    933 	pp->pr_nout--;
    934 
    935 	/* Cancel "pool empty" condition if it exists */
    936 	if (pp->pr_curpage == NULL)
    937 		pp->pr_curpage = ph;
    938 
    939 	if (pp->pr_flags & PR_WANTED) {
    940 		pp->pr_flags &= ~PR_WANTED;
    941 		if (ph->ph_nmissing == 0)
    942 			pp->pr_nidle++;
    943 		wakeup((caddr_t)pp);
    944 		return;
    945 	}
    946 
    947 	/*
    948 	 * If this page is now complete, do one of two things:
    949 	 *
    950 	 *	(1) If we have more pages than the page high water
    951 	 *	    mark, free the page back to the system.
    952 	 *
    953 	 *	(2) Move it to the end of the page list, so that
    954 	 *	    we minimize our chances of fragmenting the
    955 	 *	    pool.  Idle pages migrate to the end (along with
    956 	 *	    completely empty pages, so that we find un-empty
    957 	 *	    pages more quickly when we update curpage) of the
    958 	 *	    list so they can be more easily swept up by
    959 	 *	    the pagedaemon when pages are scarce.
    960 	 */
    961 	if (ph->ph_nmissing == 0) {
    962 		pp->pr_nidle++;
    963 		if (pp->pr_npages > pp->pr_maxpages ||
    964 		    (pp->pr_alloc->pa_flags & PA_WANT) != 0) {
    965 			pr_rmpage(pp, ph, NULL);
    966 		} else {
    967 			TAILQ_REMOVE(&pp->pr_pagelist, ph, ph_pagelist);
    968 			TAILQ_INSERT_TAIL(&pp->pr_pagelist, ph, ph_pagelist);
    969 
    970 			/*
    971 			 * Update the timestamp on the page.  A page must
    972 			 * be idle for some period of time before it can
    973 			 * be reclaimed by the pagedaemon.  This minimizes
    974 			 * ping-pong'ing for memory.
    975 			 */
    976 			s = splclock();
    977 			ph->ph_time = mono_time;
    978 			splx(s);
    979 
    980 			/*
    981 			 * Update the current page pointer.  Just look for
    982 			 * the first page with any free items.
    983 			 *
    984 			 * XXX: Maybe we want an option to look for the
    985 			 * page with the fewest available items, to minimize
    986 			 * fragmentation?
    987 			 */
    988 			TAILQ_FOREACH(ph, &pp->pr_pagelist, ph_pagelist)
    989 				if (TAILQ_FIRST(&ph->ph_itemlist) != NULL)
    990 					break;
    991 
    992 			pp->pr_curpage = ph;
    993 		}
    994 	}
    995 	/*
    996 	 * If the page has just become un-empty, move it to the head of
    997 	 * the list, and make it the current page.  The next allocation
    998 	 * will get the item from this page, instead of further fragmenting
    999 	 * the pool.
   1000 	 */
   1001 	else if (ph->ph_nmissing == (pp->pr_itemsperpage - 1)) {
   1002 		TAILQ_REMOVE(&pp->pr_pagelist, ph, ph_pagelist);
   1003 		TAILQ_INSERT_HEAD(&pp->pr_pagelist, ph, ph_pagelist);
   1004 		pp->pr_curpage = ph;
   1005 	}
   1006 }
   1007 
   1008 /*
   1009  * Return resource to the pool; must be called at appropriate spl level
   1010  */
   1011 #ifdef POOL_DIAGNOSTIC
   1012 void
   1013 _pool_put(struct pool *pp, void *v, const char *file, long line)
   1014 {
   1015 
   1016 	simple_lock(&pp->pr_slock);
   1017 	pr_enter(pp, file, line);
   1018 
   1019 	pr_log(pp, v, PRLOG_PUT, file, line);
   1020 
   1021 	pool_do_put(pp, v);
   1022 
   1023 	pr_leave(pp);
   1024 	simple_unlock(&pp->pr_slock);
   1025 }
   1026 #undef pool_put
   1027 #endif /* POOL_DIAGNOSTIC */
   1028 
   1029 void
   1030 pool_put(struct pool *pp, void *v)
   1031 {
   1032 
   1033 	simple_lock(&pp->pr_slock);
   1034 
   1035 	pool_do_put(pp, v);
   1036 
   1037 	simple_unlock(&pp->pr_slock);
   1038 }
   1039 
   1040 #ifdef POOL_DIAGNOSTIC
   1041 #define		pool_put(h, v)	_pool_put((h), (v), __FILE__, __LINE__)
   1042 #endif
   1043 
   1044 /*
   1045  * Add N items to the pool.
   1046  */
   1047 int
   1048 pool_prime(struct pool *pp, int n)
   1049 {
   1050 	struct pool_item_header *ph;
   1051 	caddr_t cp;
   1052 	int newpages, error = 0;
   1053 
   1054 	simple_lock(&pp->pr_slock);
   1055 
   1056 	newpages = roundup(n, pp->pr_itemsperpage) / pp->pr_itemsperpage;
   1057 
   1058 	while (newpages-- > 0) {
   1059 		simple_unlock(&pp->pr_slock);
   1060 		cp = pool_allocator_alloc(pp, PR_NOWAIT);
   1061 		if (__predict_true(cp != NULL))
   1062 			ph = pool_alloc_item_header(pp, cp, PR_NOWAIT);
   1063 		simple_lock(&pp->pr_slock);
   1064 
   1065 		if (__predict_false(cp == NULL || ph == NULL)) {
   1066 			error = ENOMEM;
   1067 			if (cp != NULL)
   1068 				pool_allocator_free(pp, cp);
   1069 			break;
   1070 		}
   1071 
   1072 		pool_prime_page(pp, cp, ph);
   1073 		pp->pr_npagealloc++;
   1074 		pp->pr_minpages++;
   1075 	}
   1076 
   1077 	if (pp->pr_minpages >= pp->pr_maxpages)
   1078 		pp->pr_maxpages = pp->pr_minpages + 1;	/* XXX */
   1079 
   1080 	simple_unlock(&pp->pr_slock);
   1081 	return (0);
   1082 }
   1083 
   1084 /*
   1085  * Add a page worth of items to the pool.
   1086  *
   1087  * Note, we must be called with the pool descriptor LOCKED.
   1088  */
   1089 static void
   1090 pool_prime_page(struct pool *pp, caddr_t storage, struct pool_item_header *ph)
   1091 {
   1092 	struct pool_item *pi;
   1093 	caddr_t cp = storage;
   1094 	const unsigned int align = pp->pr_align;
   1095 	const unsigned int ioff = pp->pr_itemoffset;
   1096 	int n;
   1097 
   1098 #ifdef DIAGNOSTIC
   1099 	if (((u_long)cp & (pp->pr_alloc->pa_pagesz - 1)) != 0)
   1100 		panic("pool_prime_page: %s: unaligned page", pp->pr_wchan);
   1101 #endif
   1102 
   1103 	if ((pp->pr_roflags & PR_PHINPAGE) == 0)
   1104 		LIST_INSERT_HEAD(&pp->pr_hashtab[PR_HASH_INDEX(pp, cp)],
   1105 		    ph, ph_hashlist);
   1106 
   1107 	/*
   1108 	 * Insert page header.
   1109 	 */
   1110 	TAILQ_INSERT_HEAD(&pp->pr_pagelist, ph, ph_pagelist);
   1111 	TAILQ_INIT(&ph->ph_itemlist);
   1112 	ph->ph_page = storage;
   1113 	ph->ph_nmissing = 0;
   1114 	memset(&ph->ph_time, 0, sizeof(ph->ph_time));
   1115 
   1116 	pp->pr_nidle++;
   1117 
   1118 	/*
   1119 	 * Color this page.
   1120 	 */
   1121 	cp = (caddr_t)(cp + pp->pr_curcolor);
   1122 	if ((pp->pr_curcolor += align) > pp->pr_maxcolor)
   1123 		pp->pr_curcolor = 0;
   1124 
   1125 	/*
   1126 	 * Adjust storage to apply aligment to `pr_itemoffset' in each item.
   1127 	 */
   1128 	if (ioff != 0)
   1129 		cp = (caddr_t)(cp + (align - ioff));
   1130 
   1131 	KASSERT((((vaddr_t)cp + ioff) & (align - 1)) == 0);
   1132 
   1133 	/*
   1134 	 * Insert remaining chunks on the bucket list.
   1135 	 */
   1136 	n = pp->pr_itemsperpage;
   1137 	pp->pr_nitems += n;
   1138 
   1139 	while (n--) {
   1140 		pi = (struct pool_item *)cp;
   1141 
   1142 		/* Insert on page list */
   1143 		TAILQ_INSERT_TAIL(&ph->ph_itemlist, pi, pi_list);
   1144 #ifdef DIAGNOSTIC
   1145 		pi->pi_magic = PI_MAGIC;
   1146 #endif
   1147 		cp = (caddr_t)(cp + pp->pr_size);
   1148 
   1149 		KASSERT((((vaddr_t)cp + ioff) & (align - 1)) == 0);
   1150 	}
   1151 
   1152 	/*
   1153 	 * If the pool was depleted, point at the new page.
   1154 	 */
   1155 	if (pp->pr_curpage == NULL)
   1156 		pp->pr_curpage = ph;
   1157 
   1158 	if (++pp->pr_npages > pp->pr_hiwat)
   1159 		pp->pr_hiwat = pp->pr_npages;
   1160 }
   1161 
   1162 /*
   1163  * Used by pool_get() when nitems drops below the low water mark.  This
   1164  * is used to catch up nitmes with the low water mark.
   1165  *
   1166  * Note 1, we never wait for memory here, we let the caller decide what to do.
   1167  *
   1168  * Note 2, we must be called with the pool already locked, and we return
   1169  * with it locked.
   1170  */
   1171 static int
   1172 pool_catchup(struct pool *pp)
   1173 {
   1174 	struct pool_item_header *ph;
   1175 	caddr_t cp;
   1176 	int error = 0;
   1177 
   1178 	while (POOL_NEEDS_CATCHUP(pp)) {
   1179 		/*
   1180 		 * Call the page back-end allocator for more memory.
   1181 		 *
   1182 		 * XXX: We never wait, so should we bother unlocking
   1183 		 * the pool descriptor?
   1184 		 */
   1185 		simple_unlock(&pp->pr_slock);
   1186 		cp = pool_allocator_alloc(pp, PR_NOWAIT);
   1187 		if (__predict_true(cp != NULL))
   1188 			ph = pool_alloc_item_header(pp, cp, PR_NOWAIT);
   1189 		simple_lock(&pp->pr_slock);
   1190 		if (__predict_false(cp == NULL || ph == NULL)) {
   1191 			if (cp != NULL)
   1192 				pool_allocator_free(pp, cp);
   1193 			error = ENOMEM;
   1194 			break;
   1195 		}
   1196 		pool_prime_page(pp, cp, ph);
   1197 		pp->pr_npagealloc++;
   1198 	}
   1199 
   1200 	return (error);
   1201 }
   1202 
   1203 void
   1204 pool_setlowat(struct pool *pp, int n)
   1205 {
   1206 	int error;
   1207 
   1208 	simple_lock(&pp->pr_slock);
   1209 
   1210 	pp->pr_minitems = n;
   1211 	pp->pr_minpages = (n == 0)
   1212 		? 0
   1213 		: roundup(n, pp->pr_itemsperpage) / pp->pr_itemsperpage;
   1214 
   1215 	/* Make sure we're caught up with the newly-set low water mark. */
   1216 	if (POOL_NEEDS_CATCHUP(pp) && (error = pool_catchup(pp) != 0)) {
   1217 		/*
   1218 		 * XXX: Should we log a warning?  Should we set up a timeout
   1219 		 * to try again in a second or so?  The latter could break
   1220 		 * a caller's assumptions about interrupt protection, etc.
   1221 		 */
   1222 	}
   1223 
   1224 	simple_unlock(&pp->pr_slock);
   1225 }
   1226 
   1227 void
   1228 pool_sethiwat(struct pool *pp, int n)
   1229 {
   1230 
   1231 	simple_lock(&pp->pr_slock);
   1232 
   1233 	pp->pr_maxpages = (n == 0)
   1234 		? 0
   1235 		: roundup(n, pp->pr_itemsperpage) / pp->pr_itemsperpage;
   1236 
   1237 	simple_unlock(&pp->pr_slock);
   1238 }
   1239 
   1240 void
   1241 pool_sethardlimit(struct pool *pp, int n, const char *warnmess, int ratecap)
   1242 {
   1243 
   1244 	simple_lock(&pp->pr_slock);
   1245 
   1246 	pp->pr_hardlimit = n;
   1247 	pp->pr_hardlimit_warning = warnmess;
   1248 	pp->pr_hardlimit_ratecap.tv_sec = ratecap;
   1249 	pp->pr_hardlimit_warning_last.tv_sec = 0;
   1250 	pp->pr_hardlimit_warning_last.tv_usec = 0;
   1251 
   1252 	/*
   1253 	 * In-line version of pool_sethiwat(), because we don't want to
   1254 	 * release the lock.
   1255 	 */
   1256 	pp->pr_maxpages = (n == 0)
   1257 		? 0
   1258 		: roundup(n, pp->pr_itemsperpage) / pp->pr_itemsperpage;
   1259 
   1260 	simple_unlock(&pp->pr_slock);
   1261 }
   1262 
   1263 /*
   1264  * Release all complete pages that have not been used recently.
   1265  */
   1266 int
   1267 #ifdef POOL_DIAGNOSTIC
   1268 _pool_reclaim(struct pool *pp, const char *file, long line)
   1269 #else
   1270 pool_reclaim(struct pool *pp)
   1271 #endif
   1272 {
   1273 	struct pool_item_header *ph, *phnext;
   1274 	struct pool_cache *pc;
   1275 	struct timeval curtime;
   1276 	struct pool_pagelist pq;
   1277 	int s;
   1278 
   1279 	if (pp->pr_drain_hook != NULL) {
   1280 		/*
   1281 		 * The drain hook must be called with the pool unlocked.
   1282 		 */
   1283 		(*pp->pr_drain_hook)(pp->pr_drain_hook_arg, PR_NOWAIT);
   1284 	}
   1285 
   1286 	if (simple_lock_try(&pp->pr_slock) == 0)
   1287 		return (0);
   1288 	pr_enter(pp, file, line);
   1289 
   1290 	TAILQ_INIT(&pq);
   1291 
   1292 	/*
   1293 	 * Reclaim items from the pool's caches.
   1294 	 */
   1295 	TAILQ_FOREACH(pc, &pp->pr_cachelist, pc_poollist)
   1296 		pool_cache_reclaim(pc);
   1297 
   1298 	s = splclock();
   1299 	curtime = mono_time;
   1300 	splx(s);
   1301 
   1302 	for (ph = TAILQ_FIRST(&pp->pr_pagelist); ph != NULL; ph = phnext) {
   1303 		phnext = TAILQ_NEXT(ph, ph_pagelist);
   1304 
   1305 		/* Check our minimum page claim */
   1306 		if (pp->pr_npages <= pp->pr_minpages)
   1307 			break;
   1308 
   1309 		if (ph->ph_nmissing == 0) {
   1310 			struct timeval diff;
   1311 			timersub(&curtime, &ph->ph_time, &diff);
   1312 			if (diff.tv_sec < pool_inactive_time)
   1313 				continue;
   1314 
   1315 			/*
   1316 			 * If freeing this page would put us below
   1317 			 * the low water mark, stop now.
   1318 			 */
   1319 			if ((pp->pr_nitems - pp->pr_itemsperpage) <
   1320 			    pp->pr_minitems)
   1321 				break;
   1322 
   1323 			pr_rmpage(pp, ph, &pq);
   1324 		}
   1325 	}
   1326 
   1327 	pr_leave(pp);
   1328 	simple_unlock(&pp->pr_slock);
   1329 	if (TAILQ_EMPTY(&pq))
   1330 		return (0);
   1331 
   1332 	while ((ph = TAILQ_FIRST(&pq)) != NULL) {
   1333 		TAILQ_REMOVE(&pq, ph, ph_pagelist);
   1334 		pool_allocator_free(pp, ph->ph_page);
   1335 		if (pp->pr_roflags & PR_PHINPAGE) {
   1336 			continue;
   1337 		}
   1338 		LIST_REMOVE(ph, ph_hashlist);
   1339 		s = splhigh();
   1340 		pool_put(&phpool, ph);
   1341 		splx(s);
   1342 	}
   1343 
   1344 	return (1);
   1345 }
   1346 
   1347 /*
   1348  * Drain pools, one at a time.
   1349  *
   1350  * Note, we must never be called from an interrupt context.
   1351  */
   1352 void
   1353 pool_drain(void *arg)
   1354 {
   1355 	struct pool *pp;
   1356 	int s;
   1357 
   1358 	pp = NULL;
   1359 	s = splvm();
   1360 	simple_lock(&pool_head_slock);
   1361 	if (drainpp == NULL) {
   1362 		drainpp = TAILQ_FIRST(&pool_head);
   1363 	}
   1364 	if (drainpp) {
   1365 		pp = drainpp;
   1366 		drainpp = TAILQ_NEXT(pp, pr_poollist);
   1367 	}
   1368 	simple_unlock(&pool_head_slock);
   1369 	pool_reclaim(pp);
   1370 	splx(s);
   1371 }
   1372 
   1373 /*
   1374  * Diagnostic helpers.
   1375  */
   1376 void
   1377 pool_print(struct pool *pp, const char *modif)
   1378 {
   1379 	int s;
   1380 
   1381 	s = splvm();
   1382 	if (simple_lock_try(&pp->pr_slock) == 0) {
   1383 		printf("pool %s is locked; try again later\n",
   1384 		    pp->pr_wchan);
   1385 		splx(s);
   1386 		return;
   1387 	}
   1388 	pool_print1(pp, modif, printf);
   1389 	simple_unlock(&pp->pr_slock);
   1390 	splx(s);
   1391 }
   1392 
   1393 void
   1394 pool_printit(struct pool *pp, const char *modif, void (*pr)(const char *, ...))
   1395 {
   1396 	int didlock = 0;
   1397 
   1398 	if (pp == NULL) {
   1399 		(*pr)("Must specify a pool to print.\n");
   1400 		return;
   1401 	}
   1402 
   1403 	/*
   1404 	 * Called from DDB; interrupts should be blocked, and all
   1405 	 * other processors should be paused.  We can skip locking
   1406 	 * the pool in this case.
   1407 	 *
   1408 	 * We do a simple_lock_try() just to print the lock
   1409 	 * status, however.
   1410 	 */
   1411 
   1412 	if (simple_lock_try(&pp->pr_slock) == 0)
   1413 		(*pr)("WARNING: pool %s is locked\n", pp->pr_wchan);
   1414 	else
   1415 		didlock = 1;
   1416 
   1417 	pool_print1(pp, modif, pr);
   1418 
   1419 	if (didlock)
   1420 		simple_unlock(&pp->pr_slock);
   1421 }
   1422 
   1423 static void
   1424 pool_print1(struct pool *pp, const char *modif, void (*pr)(const char *, ...))
   1425 {
   1426 	struct pool_item_header *ph;
   1427 	struct pool_cache *pc;
   1428 	struct pool_cache_group *pcg;
   1429 #ifdef DIAGNOSTIC
   1430 	struct pool_item *pi;
   1431 #endif
   1432 	int i, print_log = 0, print_pagelist = 0, print_cache = 0;
   1433 	char c;
   1434 
   1435 	while ((c = *modif++) != '\0') {
   1436 		if (c == 'l')
   1437 			print_log = 1;
   1438 		if (c == 'p')
   1439 			print_pagelist = 1;
   1440 		if (c == 'c')
   1441 			print_cache = 1;
   1442 		modif++;
   1443 	}
   1444 
   1445 	(*pr)("POOL %s: size %u, align %u, ioff %u, roflags 0x%08x\n",
   1446 	    pp->pr_wchan, pp->pr_size, pp->pr_align, pp->pr_itemoffset,
   1447 	    pp->pr_roflags);
   1448 	(*pr)("\talloc %p\n", pp->pr_alloc);
   1449 	(*pr)("\tminitems %u, minpages %u, maxpages %u, npages %u\n",
   1450 	    pp->pr_minitems, pp->pr_minpages, pp->pr_maxpages, pp->pr_npages);
   1451 	(*pr)("\titemsperpage %u, nitems %u, nout %u, hardlimit %u\n",
   1452 	    pp->pr_itemsperpage, pp->pr_nitems, pp->pr_nout, pp->pr_hardlimit);
   1453 
   1454 	(*pr)("\n\tnget %lu, nfail %lu, nput %lu\n",
   1455 	    pp->pr_nget, pp->pr_nfail, pp->pr_nput);
   1456 	(*pr)("\tnpagealloc %lu, npagefree %lu, hiwat %u, nidle %lu\n",
   1457 	    pp->pr_npagealloc, pp->pr_npagefree, pp->pr_hiwat, pp->pr_nidle);
   1458 
   1459 	if (print_pagelist == 0)
   1460 		goto skip_pagelist;
   1461 
   1462 	if ((ph = TAILQ_FIRST(&pp->pr_pagelist)) != NULL)
   1463 		(*pr)("\n\tpage list:\n");
   1464 	for (; ph != NULL; ph = TAILQ_NEXT(ph, ph_pagelist)) {
   1465 		(*pr)("\t\tpage %p, nmissing %d, time %lu,%lu\n",
   1466 		    ph->ph_page, ph->ph_nmissing,
   1467 		    (u_long)ph->ph_time.tv_sec,
   1468 		    (u_long)ph->ph_time.tv_usec);
   1469 #ifdef DIAGNOSTIC
   1470 		TAILQ_FOREACH(pi, &ph->ph_itemlist, pi_list) {
   1471 			if (pi->pi_magic != PI_MAGIC) {
   1472 				(*pr)("\t\t\titem %p, magic 0x%x\n",
   1473 				    pi, pi->pi_magic);
   1474 			}
   1475 		}
   1476 #endif
   1477 	}
   1478 	if (pp->pr_curpage == NULL)
   1479 		(*pr)("\tno current page\n");
   1480 	else
   1481 		(*pr)("\tcurpage %p\n", pp->pr_curpage->ph_page);
   1482 
   1483  skip_pagelist:
   1484 
   1485 	if (print_log == 0)
   1486 		goto skip_log;
   1487 
   1488 	(*pr)("\n");
   1489 	if ((pp->pr_roflags & PR_LOGGING) == 0)
   1490 		(*pr)("\tno log\n");
   1491 	else
   1492 		pr_printlog(pp, NULL, pr);
   1493 
   1494  skip_log:
   1495 
   1496 	if (print_cache == 0)
   1497 		goto skip_cache;
   1498 
   1499 	TAILQ_FOREACH(pc, &pp->pr_cachelist, pc_poollist) {
   1500 		(*pr)("\tcache %p: allocfrom %p freeto %p\n", pc,
   1501 		    pc->pc_allocfrom, pc->pc_freeto);
   1502 		(*pr)("\t    hits %lu misses %lu ngroups %lu nitems %lu\n",
   1503 		    pc->pc_hits, pc->pc_misses, pc->pc_ngroups, pc->pc_nitems);
   1504 		TAILQ_FOREACH(pcg, &pc->pc_grouplist, pcg_list) {
   1505 			(*pr)("\t\tgroup %p: avail %d\n", pcg, pcg->pcg_avail);
   1506 			for (i = 0; i < PCG_NOBJECTS; i++)
   1507 				(*pr)("\t\t\t%p\n", pcg->pcg_objects[i]);
   1508 		}
   1509 	}
   1510 
   1511  skip_cache:
   1512 
   1513 	pr_enter_check(pp, pr);
   1514 }
   1515 
   1516 int
   1517 pool_chk(struct pool *pp, const char *label)
   1518 {
   1519 	struct pool_item_header *ph;
   1520 	int r = 0;
   1521 
   1522 	simple_lock(&pp->pr_slock);
   1523 
   1524 	TAILQ_FOREACH(ph, &pp->pr_pagelist, ph_pagelist) {
   1525 		struct pool_item *pi;
   1526 		int n;
   1527 		caddr_t page;
   1528 
   1529 		page = (caddr_t)((u_long)ph & pp->pr_alloc->pa_pagemask);
   1530 		if (page != ph->ph_page &&
   1531 		    (pp->pr_roflags & PR_PHINPAGE) != 0) {
   1532 			if (label != NULL)
   1533 				printf("%s: ", label);
   1534 			printf("pool(%p:%s): page inconsistency: page %p;"
   1535 			       " at page head addr %p (p %p)\n", pp,
   1536 				pp->pr_wchan, ph->ph_page,
   1537 				ph, page);
   1538 			r++;
   1539 			goto out;
   1540 		}
   1541 
   1542 		for (pi = TAILQ_FIRST(&ph->ph_itemlist), n = 0;
   1543 		     pi != NULL;
   1544 		     pi = TAILQ_NEXT(pi,pi_list), n++) {
   1545 
   1546 #ifdef DIAGNOSTIC
   1547 			if (pi->pi_magic != PI_MAGIC) {
   1548 				if (label != NULL)
   1549 					printf("%s: ", label);
   1550 				printf("pool(%s): free list modified: magic=%x;"
   1551 				       " page %p; item ordinal %d;"
   1552 				       " addr %p (p %p)\n",
   1553 					pp->pr_wchan, pi->pi_magic, ph->ph_page,
   1554 					n, pi, page);
   1555 				panic("pool");
   1556 			}
   1557 #endif
   1558 			page =
   1559 			    (caddr_t)((u_long)pi & pp->pr_alloc->pa_pagemask);
   1560 			if (page == ph->ph_page)
   1561 				continue;
   1562 
   1563 			if (label != NULL)
   1564 				printf("%s: ", label);
   1565 			printf("pool(%p:%s): page inconsistency: page %p;"
   1566 			       " item ordinal %d; addr %p (p %p)\n", pp,
   1567 				pp->pr_wchan, ph->ph_page,
   1568 				n, pi, page);
   1569 			r++;
   1570 			goto out;
   1571 		}
   1572 	}
   1573 out:
   1574 	simple_unlock(&pp->pr_slock);
   1575 	return (r);
   1576 }
   1577 
   1578 /*
   1579  * pool_cache_init:
   1580  *
   1581  *	Initialize a pool cache.
   1582  *
   1583  *	NOTE: If the pool must be protected from interrupts, we expect
   1584  *	to be called at the appropriate interrupt priority level.
   1585  */
   1586 void
   1587 pool_cache_init(struct pool_cache *pc, struct pool *pp,
   1588     int (*ctor)(void *, void *, int),
   1589     void (*dtor)(void *, void *),
   1590     void *arg)
   1591 {
   1592 
   1593 	TAILQ_INIT(&pc->pc_grouplist);
   1594 	simple_lock_init(&pc->pc_slock);
   1595 
   1596 	pc->pc_allocfrom = NULL;
   1597 	pc->pc_freeto = NULL;
   1598 	pc->pc_pool = pp;
   1599 
   1600 	pc->pc_ctor = ctor;
   1601 	pc->pc_dtor = dtor;
   1602 	pc->pc_arg  = arg;
   1603 
   1604 	pc->pc_hits   = 0;
   1605 	pc->pc_misses = 0;
   1606 
   1607 	pc->pc_ngroups = 0;
   1608 
   1609 	pc->pc_nitems = 0;
   1610 
   1611 	simple_lock(&pp->pr_slock);
   1612 	TAILQ_INSERT_TAIL(&pp->pr_cachelist, pc, pc_poollist);
   1613 	simple_unlock(&pp->pr_slock);
   1614 }
   1615 
   1616 /*
   1617  * pool_cache_destroy:
   1618  *
   1619  *	Destroy a pool cache.
   1620  */
   1621 void
   1622 pool_cache_destroy(struct pool_cache *pc)
   1623 {
   1624 	struct pool *pp = pc->pc_pool;
   1625 
   1626 	/* First, invalidate the entire cache. */
   1627 	pool_cache_invalidate(pc);
   1628 
   1629 	/* ...and remove it from the pool's cache list. */
   1630 	simple_lock(&pp->pr_slock);
   1631 	TAILQ_REMOVE(&pp->pr_cachelist, pc, pc_poollist);
   1632 	simple_unlock(&pp->pr_slock);
   1633 }
   1634 
   1635 static __inline void *
   1636 pcg_get(struct pool_cache_group *pcg)
   1637 {
   1638 	void *object;
   1639 	u_int idx;
   1640 
   1641 	KASSERT(pcg->pcg_avail <= PCG_NOBJECTS);
   1642 	KASSERT(pcg->pcg_avail != 0);
   1643 	idx = --pcg->pcg_avail;
   1644 
   1645 	KASSERT(pcg->pcg_objects[idx] != NULL);
   1646 	object = pcg->pcg_objects[idx];
   1647 	pcg->pcg_objects[idx] = NULL;
   1648 
   1649 	return (object);
   1650 }
   1651 
   1652 static __inline void
   1653 pcg_put(struct pool_cache_group *pcg, void *object)
   1654 {
   1655 	u_int idx;
   1656 
   1657 	KASSERT(pcg->pcg_avail < PCG_NOBJECTS);
   1658 	idx = pcg->pcg_avail++;
   1659 
   1660 	KASSERT(pcg->pcg_objects[idx] == NULL);
   1661 	pcg->pcg_objects[idx] = object;
   1662 }
   1663 
   1664 /*
   1665  * pool_cache_get:
   1666  *
   1667  *	Get an object from a pool cache.
   1668  */
   1669 void *
   1670 pool_cache_get(struct pool_cache *pc, int flags)
   1671 {
   1672 	struct pool_cache_group *pcg;
   1673 	void *object;
   1674 
   1675 #ifdef LOCKDEBUG
   1676 	if (flags & PR_WAITOK)
   1677 		simple_lock_only_held(NULL, "pool_cache_get(PR_WAITOK)");
   1678 #endif
   1679 
   1680 	simple_lock(&pc->pc_slock);
   1681 
   1682 	if ((pcg = pc->pc_allocfrom) == NULL) {
   1683 		TAILQ_FOREACH(pcg, &pc->pc_grouplist, pcg_list) {
   1684 			if (pcg->pcg_avail != 0) {
   1685 				pc->pc_allocfrom = pcg;
   1686 				goto have_group;
   1687 			}
   1688 		}
   1689 
   1690 		/*
   1691 		 * No groups with any available objects.  Allocate
   1692 		 * a new object, construct it, and return it to
   1693 		 * the caller.  We will allocate a group, if necessary,
   1694 		 * when the object is freed back to the cache.
   1695 		 */
   1696 		pc->pc_misses++;
   1697 		simple_unlock(&pc->pc_slock);
   1698 		object = pool_get(pc->pc_pool, flags);
   1699 		if (object != NULL && pc->pc_ctor != NULL) {
   1700 			if ((*pc->pc_ctor)(pc->pc_arg, object, flags) != 0) {
   1701 				pool_put(pc->pc_pool, object);
   1702 				return (NULL);
   1703 			}
   1704 		}
   1705 		KASSERT((((vaddr_t)object + pc->pc_pool->pr_itemoffset) &
   1706 		    (pc->pc_pool->pr_align - 1)) == 0);
   1707 		return (object);
   1708 	}
   1709 
   1710  have_group:
   1711 	pc->pc_hits++;
   1712 	pc->pc_nitems--;
   1713 	object = pcg_get(pcg);
   1714 
   1715 	if (pcg->pcg_avail == 0)
   1716 		pc->pc_allocfrom = NULL;
   1717 
   1718 	simple_unlock(&pc->pc_slock);
   1719 
   1720 	KASSERT((((vaddr_t)object + pc->pc_pool->pr_itemoffset) &
   1721 	    (pc->pc_pool->pr_align - 1)) == 0);
   1722 	return (object);
   1723 }
   1724 
   1725 /*
   1726  * pool_cache_put:
   1727  *
   1728  *	Put an object back to the pool cache.
   1729  */
   1730 void
   1731 pool_cache_put(struct pool_cache *pc, void *object)
   1732 {
   1733 	struct pool_cache_group *pcg;
   1734 	int s;
   1735 
   1736 	simple_lock(&pc->pc_slock);
   1737 
   1738 	if ((pcg = pc->pc_freeto) == NULL) {
   1739 		TAILQ_FOREACH(pcg, &pc->pc_grouplist, pcg_list) {
   1740 			if (pcg->pcg_avail != PCG_NOBJECTS) {
   1741 				pc->pc_freeto = pcg;
   1742 				goto have_group;
   1743 			}
   1744 		}
   1745 
   1746 		/*
   1747 		 * No empty groups to free the object to.  Attempt to
   1748 		 * allocate one.
   1749 		 */
   1750 		simple_unlock(&pc->pc_slock);
   1751 		s = splvm();
   1752 		pcg = pool_get(&pcgpool, PR_NOWAIT);
   1753 		splx(s);
   1754 		if (pcg != NULL) {
   1755 			memset(pcg, 0, sizeof(*pcg));
   1756 			simple_lock(&pc->pc_slock);
   1757 			pc->pc_ngroups++;
   1758 			TAILQ_INSERT_TAIL(&pc->pc_grouplist, pcg, pcg_list);
   1759 			if (pc->pc_freeto == NULL)
   1760 				pc->pc_freeto = pcg;
   1761 			goto have_group;
   1762 		}
   1763 
   1764 		/*
   1765 		 * Unable to allocate a cache group; destruct the object
   1766 		 * and free it back to the pool.
   1767 		 */
   1768 		pool_cache_destruct_object(pc, object);
   1769 		return;
   1770 	}
   1771 
   1772  have_group:
   1773 	pc->pc_nitems++;
   1774 	pcg_put(pcg, object);
   1775 
   1776 	if (pcg->pcg_avail == PCG_NOBJECTS)
   1777 		pc->pc_freeto = NULL;
   1778 
   1779 	simple_unlock(&pc->pc_slock);
   1780 }
   1781 
   1782 /*
   1783  * pool_cache_destruct_object:
   1784  *
   1785  *	Force destruction of an object and its release back into
   1786  *	the pool.
   1787  */
   1788 void
   1789 pool_cache_destruct_object(struct pool_cache *pc, void *object)
   1790 {
   1791 
   1792 	if (pc->pc_dtor != NULL)
   1793 		(*pc->pc_dtor)(pc->pc_arg, object);
   1794 	pool_put(pc->pc_pool, object);
   1795 }
   1796 
   1797 /*
   1798  * pool_cache_do_invalidate:
   1799  *
   1800  *	This internal function implements pool_cache_invalidate() and
   1801  *	pool_cache_reclaim().
   1802  */
   1803 static void
   1804 pool_cache_do_invalidate(struct pool_cache *pc, int free_groups,
   1805     void (*putit)(struct pool *, void *))
   1806 {
   1807 	struct pool_cache_group *pcg, *npcg;
   1808 	void *object;
   1809 	int s;
   1810 
   1811 	for (pcg = TAILQ_FIRST(&pc->pc_grouplist); pcg != NULL;
   1812 	     pcg = npcg) {
   1813 		npcg = TAILQ_NEXT(pcg, pcg_list);
   1814 		while (pcg->pcg_avail != 0) {
   1815 			pc->pc_nitems--;
   1816 			object = pcg_get(pcg);
   1817 			if (pcg->pcg_avail == 0 && pc->pc_allocfrom == pcg)
   1818 				pc->pc_allocfrom = NULL;
   1819 			if (pc->pc_dtor != NULL)
   1820 				(*pc->pc_dtor)(pc->pc_arg, object);
   1821 			(*putit)(pc->pc_pool, object);
   1822 		}
   1823 		if (free_groups) {
   1824 			pc->pc_ngroups--;
   1825 			TAILQ_REMOVE(&pc->pc_grouplist, pcg, pcg_list);
   1826 			if (pc->pc_freeto == pcg)
   1827 				pc->pc_freeto = NULL;
   1828 			s = splvm();
   1829 			pool_put(&pcgpool, pcg);
   1830 			splx(s);
   1831 		}
   1832 	}
   1833 }
   1834 
   1835 /*
   1836  * pool_cache_invalidate:
   1837  *
   1838  *	Invalidate a pool cache (destruct and release all of the
   1839  *	cached objects).
   1840  */
   1841 void
   1842 pool_cache_invalidate(struct pool_cache *pc)
   1843 {
   1844 
   1845 	simple_lock(&pc->pc_slock);
   1846 	pool_cache_do_invalidate(pc, 0, pool_put);
   1847 	simple_unlock(&pc->pc_slock);
   1848 }
   1849 
   1850 /*
   1851  * pool_cache_reclaim:
   1852  *
   1853  *	Reclaim a pool cache for pool_reclaim().
   1854  */
   1855 static void
   1856 pool_cache_reclaim(struct pool_cache *pc)
   1857 {
   1858 
   1859 	simple_lock(&pc->pc_slock);
   1860 	pool_cache_do_invalidate(pc, 1, pool_do_put);
   1861 	simple_unlock(&pc->pc_slock);
   1862 }
   1863 
   1864 /*
   1865  * Pool backend allocators.
   1866  *
   1867  * Each pool has a backend allocator that handles allocation, deallocation,
   1868  * and any additional draining that might be needed.
   1869  *
   1870  * We provide two standard allocators:
   1871  *
   1872  *	pool_allocator_kmem - the default when no allocator is specified
   1873  *
   1874  *	pool_allocator_nointr - used for pools that will not be accessed
   1875  *	in interrupt context.
   1876  */
   1877 void	*pool_page_alloc(struct pool *, int);
   1878 void	pool_page_free(struct pool *, void *);
   1879 
   1880 struct pool_allocator pool_allocator_kmem = {
   1881 	pool_page_alloc, pool_page_free, 0,
   1882 };
   1883 
   1884 void	*pool_page_alloc_nointr(struct pool *, int);
   1885 void	pool_page_free_nointr(struct pool *, void *);
   1886 
   1887 struct pool_allocator pool_allocator_nointr = {
   1888 	pool_page_alloc_nointr, pool_page_free_nointr, 0,
   1889 };
   1890 
   1891 #ifdef POOL_SUBPAGE
   1892 void	*pool_subpage_alloc(struct pool *, int);
   1893 void	pool_subpage_free(struct pool *, void *);
   1894 
   1895 struct pool_allocator pool_allocator_kmem_subpage = {
   1896 	pool_subpage_alloc, pool_subpage_free, 0,
   1897 };
   1898 #endif /* POOL_SUBPAGE */
   1899 
   1900 /*
   1901  * We have at least three different resources for the same allocation and
   1902  * each resource can be depleted.  First, we have the ready elements in the
   1903  * pool.  Then we have the resource (typically a vm_map) for this allocator.
   1904  * Finally, we have physical memory.  Waiting for any of these can be
   1905  * unnecessary when any other is freed, but the kernel doesn't support
   1906  * sleeping on multiple wait channels, so we have to employ another strategy.
   1907  *
   1908  * The caller sleeps on the pool (so that it can be awakened when an item
   1909  * is returned to the pool), but we set PA_WANT on the allocator.  When a
   1910  * page is returned to the allocator and PA_WANT is set, pool_allocator_free
   1911  * will wake up all sleeping pools belonging to this allocator.
   1912  *
   1913  * XXX Thundering herd.
   1914  */
   1915 void *
   1916 pool_allocator_alloc(struct pool *org, int flags)
   1917 {
   1918 	struct pool_allocator *pa = org->pr_alloc;
   1919 	struct pool *pp, *start;
   1920 	int s, freed;
   1921 	void *res;
   1922 
   1923 	do {
   1924 		if ((res = (*pa->pa_alloc)(org, flags)) != NULL)
   1925 			return (res);
   1926 		if ((flags & PR_WAITOK) == 0) {
   1927 			/*
   1928 			 * We only run the drain hookhere if PR_NOWAIT.
   1929 			 * In other cases, the hook will be run in
   1930 			 * pool_reclaim().
   1931 			 */
   1932 			if (org->pr_drain_hook != NULL) {
   1933 				(*org->pr_drain_hook)(org->pr_drain_hook_arg,
   1934 				    flags);
   1935 				if ((res = (*pa->pa_alloc)(org, flags)) != NULL)
   1936 					return (res);
   1937 			}
   1938 			break;
   1939 		}
   1940 
   1941 		/*
   1942 		 * Drain all pools, except "org", that use this
   1943 		 * allocator.  We do this to reclaim VA space.
   1944 		 * pa_alloc is responsible for waiting for
   1945 		 * physical memory.
   1946 		 *
   1947 		 * XXX We risk looping forever if start if someone
   1948 		 * calls pool_destroy on "start".  But there is no
   1949 		 * other way to have potentially sleeping pool_reclaim,
   1950 		 * non-sleeping locks on pool_allocator, and some
   1951 		 * stirring of drained pools in the allocator.
   1952 		 *
   1953 		 * XXX Maybe we should use pool_head_slock for locking
   1954 		 * the allocators?
   1955 		 */
   1956 		freed = 0;
   1957 
   1958 		s = splvm();
   1959 		simple_lock(&pa->pa_slock);
   1960 		pp = start = TAILQ_FIRST(&pa->pa_list);
   1961 		do {
   1962 			TAILQ_REMOVE(&pa->pa_list, pp, pr_alloc_list);
   1963 			TAILQ_INSERT_TAIL(&pa->pa_list, pp, pr_alloc_list);
   1964 			if (pp == org)
   1965 				continue;
   1966 			simple_unlock(&pa->pa_slock);
   1967 			freed = pool_reclaim(pp);
   1968 			simple_lock(&pa->pa_slock);
   1969 		} while ((pp = TAILQ_FIRST(&pa->pa_list)) != start &&
   1970 			 freed == 0);
   1971 
   1972 		if (freed == 0) {
   1973 			/*
   1974 			 * We set PA_WANT here, the caller will most likely
   1975 			 * sleep waiting for pages (if not, this won't hurt
   1976 			 * that much), and there is no way to set this in
   1977 			 * the caller without violating locking order.
   1978 			 */
   1979 			pa->pa_flags |= PA_WANT;
   1980 		}
   1981 		simple_unlock(&pa->pa_slock);
   1982 		splx(s);
   1983 	} while (freed);
   1984 	return (NULL);
   1985 }
   1986 
   1987 void
   1988 pool_allocator_free(struct pool *pp, void *v)
   1989 {
   1990 	struct pool_allocator *pa = pp->pr_alloc;
   1991 	int s;
   1992 
   1993 	(*pa->pa_free)(pp, v);
   1994 
   1995 	s = splvm();
   1996 	simple_lock(&pa->pa_slock);
   1997 	if ((pa->pa_flags & PA_WANT) == 0) {
   1998 		simple_unlock(&pa->pa_slock);
   1999 		splx(s);
   2000 		return;
   2001 	}
   2002 
   2003 	TAILQ_FOREACH(pp, &pa->pa_list, pr_alloc_list) {
   2004 		simple_lock(&pp->pr_slock);
   2005 		if ((pp->pr_flags & PR_WANTED) != 0) {
   2006 			pp->pr_flags &= ~PR_WANTED;
   2007 			wakeup(pp);
   2008 		}
   2009 		simple_unlock(&pp->pr_slock);
   2010 	}
   2011 	pa->pa_flags &= ~PA_WANT;
   2012 	simple_unlock(&pa->pa_slock);
   2013 	splx(s);
   2014 }
   2015 
   2016 void *
   2017 pool_page_alloc(struct pool *pp, int flags)
   2018 {
   2019 	boolean_t waitok = (flags & PR_WAITOK) ? TRUE : FALSE;
   2020 
   2021 	return ((void *) uvm_km_alloc_poolpage(waitok));
   2022 }
   2023 
   2024 void
   2025 pool_page_free(struct pool *pp, void *v)
   2026 {
   2027 
   2028 	uvm_km_free_poolpage((vaddr_t) v);
   2029 }
   2030 
   2031 #ifdef POOL_SUBPAGE
   2032 /* Sub-page allocator, for machines with large hardware pages. */
   2033 void *
   2034 pool_subpage_alloc(struct pool *pp, int flags)
   2035 {
   2036 
   2037 	return (pool_get(&psppool, flags));
   2038 }
   2039 
   2040 void
   2041 pool_subpage_free(struct pool *pp, void *v)
   2042 {
   2043 
   2044 	pool_put(&psppool, v);
   2045 }
   2046 
   2047 /* We don't provide a real nointr allocator.  Maybe later. */
   2048 void *
   2049 pool_page_alloc_nointr(struct pool *pp, int flags)
   2050 {
   2051 
   2052 	return (pool_subpage_alloc(pp, flags));
   2053 }
   2054 
   2055 void
   2056 pool_page_free_nointr(struct pool *pp, void *v)
   2057 {
   2058 
   2059 	pool_subpage_free(pp, v);
   2060 }
   2061 #else
   2062 void *
   2063 pool_page_alloc_nointr(struct pool *pp, int flags)
   2064 {
   2065 	boolean_t waitok = (flags & PR_WAITOK) ? TRUE : FALSE;
   2066 
   2067 	return ((void *) uvm_km_alloc_poolpage1(kernel_map,
   2068 	    uvm.kernel_object, waitok));
   2069 }
   2070 
   2071 void
   2072 pool_page_free_nointr(struct pool *pp, void *v)
   2073 {
   2074 
   2075 	uvm_km_free_poolpage1(kernel_map, (vaddr_t) v);
   2076 }
   2077 #endif /* POOL_SUBPAGE */
   2078