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