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