Home | History | Annotate | Line # | Download | only in kern
subr_pool.c revision 1.44
      1 /*	$NetBSD: subr_pool.c,v 1.44 2000/12/07 19:30:31 thorpej 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 void	pool_prime_page(struct pool *, caddr_t);
    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 		pp->pr_npagealloc++;
    718 		pool_prime_page(pp, v);
    719 
    720 		/* Start the allocation process over. */
    721 		goto startover;
    722 	}
    723 
    724 	if (__predict_false((v = pi = TAILQ_FIRST(&ph->ph_itemlist)) == NULL)) {
    725 		pr_leave(pp);
    726 		simple_unlock(&pp->pr_slock);
    727 		panic("pool_get: %s: page empty", pp->pr_wchan);
    728 	}
    729 #ifdef DIAGNOSTIC
    730 	if (__predict_false(pp->pr_nitems == 0)) {
    731 		pr_leave(pp);
    732 		simple_unlock(&pp->pr_slock);
    733 		printf("pool_get: %s: items on itemlist, nitems %u\n",
    734 		    pp->pr_wchan, pp->pr_nitems);
    735 		panic("pool_get: nitems inconsistent\n");
    736 	}
    737 #endif
    738 	pr_log(pp, v, PRLOG_GET, file, line);
    739 
    740 #ifdef DIAGNOSTIC
    741 	if (__predict_false(pi->pi_magic != PI_MAGIC)) {
    742 		pr_printlog(pp, pi, printf);
    743 		panic("pool_get(%s): free list modified: magic=%x; page %p;"
    744 		       " item addr %p\n",
    745 			pp->pr_wchan, pi->pi_magic, ph->ph_page, pi);
    746 	}
    747 #endif
    748 
    749 	/*
    750 	 * Remove from item list.
    751 	 */
    752 	TAILQ_REMOVE(&ph->ph_itemlist, pi, pi_list);
    753 	pp->pr_nitems--;
    754 	pp->pr_nout++;
    755 	if (ph->ph_nmissing == 0) {
    756 #ifdef DIAGNOSTIC
    757 		if (__predict_false(pp->pr_nidle == 0))
    758 			panic("pool_get: nidle inconsistent");
    759 #endif
    760 		pp->pr_nidle--;
    761 	}
    762 	ph->ph_nmissing++;
    763 	if (TAILQ_FIRST(&ph->ph_itemlist) == NULL) {
    764 #ifdef DIAGNOSTIC
    765 		if (__predict_false(ph->ph_nmissing != pp->pr_itemsperpage)) {
    766 			pr_leave(pp);
    767 			simple_unlock(&pp->pr_slock);
    768 			panic("pool_get: %s: nmissing inconsistent",
    769 			    pp->pr_wchan);
    770 		}
    771 #endif
    772 		/*
    773 		 * Find a new non-empty page header, if any.
    774 		 * Start search from the page head, to increase
    775 		 * the chance for "high water" pages to be freed.
    776 		 *
    777 		 * Migrate empty pages to the end of the list.  This
    778 		 * will speed the update of curpage as pages become
    779 		 * idle.  Empty pages intermingled with idle pages
    780 		 * is no big deal.  As soon as a page becomes un-empty,
    781 		 * it will move back to the head of the list.
    782 		 */
    783 		TAILQ_REMOVE(&pp->pr_pagelist, ph, ph_pagelist);
    784 		TAILQ_INSERT_TAIL(&pp->pr_pagelist, ph, ph_pagelist);
    785 		for (ph = TAILQ_FIRST(&pp->pr_pagelist); ph != NULL;
    786 		     ph = TAILQ_NEXT(ph, ph_pagelist))
    787 			if (TAILQ_FIRST(&ph->ph_itemlist) != NULL)
    788 				break;
    789 
    790 		pp->pr_curpage = ph;
    791 	}
    792 
    793 	pp->pr_nget++;
    794 
    795 	/*
    796 	 * If we have a low water mark and we are now below that low
    797 	 * water mark, add more items to the pool.
    798 	 */
    799 	if (pp->pr_nitems < pp->pr_minitems && pool_catchup(pp) != 0) {
    800 		/*
    801 		 * XXX: Should we log a warning?  Should we set up a timeout
    802 		 * to try again in a second or so?  The latter could break
    803 		 * a caller's assumptions about interrupt protection, etc.
    804 		 */
    805 	}
    806 
    807 	pr_leave(pp);
    808 	simple_unlock(&pp->pr_slock);
    809 	return (v);
    810 }
    811 
    812 /*
    813  * Internal version of pool_put().  Pool is already locked/entered.
    814  */
    815 static void
    816 pool_do_put(struct pool *pp, void *v, const char *file, long line)
    817 {
    818 	struct pool_item *pi = v;
    819 	struct pool_item_header *ph;
    820 	caddr_t page;
    821 	int s;
    822 
    823 	page = (caddr_t)((u_long)v & pp->pr_pagemask);
    824 
    825 #ifdef DIAGNOSTIC
    826 	if (__predict_false(pp->pr_nout == 0)) {
    827 		printf("pool %s: putting with none out\n",
    828 		    pp->pr_wchan);
    829 		panic("pool_put");
    830 	}
    831 #endif
    832 
    833 	pr_log(pp, v, PRLOG_PUT, file, line);
    834 
    835 	if (__predict_false((ph = pr_find_pagehead(pp, page)) == NULL)) {
    836 		pr_printlog(pp, NULL, printf);
    837 		panic("pool_put: %s: page header missing", pp->pr_wchan);
    838 	}
    839 
    840 #ifdef LOCKDEBUG
    841 	/*
    842 	 * Check if we're freeing a locked simple lock.
    843 	 */
    844 	simple_lock_freecheck((caddr_t)pi, ((caddr_t)pi) + pp->pr_size);
    845 #endif
    846 
    847 	/*
    848 	 * Return to item list.
    849 	 */
    850 #ifdef DIAGNOSTIC
    851 	pi->pi_magic = PI_MAGIC;
    852 #endif
    853 #ifdef DEBUG
    854 	{
    855 		int i, *ip = v;
    856 
    857 		for (i = 0; i < pp->pr_size / sizeof(int); i++) {
    858 			*ip++ = PI_MAGIC;
    859 		}
    860 	}
    861 #endif
    862 
    863 	TAILQ_INSERT_HEAD(&ph->ph_itemlist, pi, pi_list);
    864 	ph->ph_nmissing--;
    865 	pp->pr_nput++;
    866 	pp->pr_nitems++;
    867 	pp->pr_nout--;
    868 
    869 	/* Cancel "pool empty" condition if it exists */
    870 	if (pp->pr_curpage == NULL)
    871 		pp->pr_curpage = ph;
    872 
    873 	if (pp->pr_flags & PR_WANTED) {
    874 		pp->pr_flags &= ~PR_WANTED;
    875 		if (ph->ph_nmissing == 0)
    876 			pp->pr_nidle++;
    877 		wakeup((caddr_t)pp);
    878 		return;
    879 	}
    880 
    881 	/*
    882 	 * If this page is now complete, do one of two things:
    883 	 *
    884 	 *	(1) If we have more pages than the page high water
    885 	 *	    mark, free the page back to the system.
    886 	 *
    887 	 *	(2) Move it to the end of the page list, so that
    888 	 *	    we minimize our chances of fragmenting the
    889 	 *	    pool.  Idle pages migrate to the end (along with
    890 	 *	    completely empty pages, so that we find un-empty
    891 	 *	    pages more quickly when we update curpage) of the
    892 	 *	    list so they can be more easily swept up by
    893 	 *	    the pagedaemon when pages are scarce.
    894 	 */
    895 	if (ph->ph_nmissing == 0) {
    896 		pp->pr_nidle++;
    897 		if (pp->pr_npages > pp->pr_maxpages) {
    898 			pr_rmpage(pp, ph);
    899 		} else {
    900 			TAILQ_REMOVE(&pp->pr_pagelist, ph, ph_pagelist);
    901 			TAILQ_INSERT_TAIL(&pp->pr_pagelist, ph, ph_pagelist);
    902 
    903 			/*
    904 			 * Update the timestamp on the page.  A page must
    905 			 * be idle for some period of time before it can
    906 			 * be reclaimed by the pagedaemon.  This minimizes
    907 			 * ping-pong'ing for memory.
    908 			 */
    909 			s = splclock();
    910 			ph->ph_time = mono_time;
    911 			splx(s);
    912 
    913 			/*
    914 			 * Update the current page pointer.  Just look for
    915 			 * the first page with any free items.
    916 			 *
    917 			 * XXX: Maybe we want an option to look for the
    918 			 * page with the fewest available items, to minimize
    919 			 * fragmentation?
    920 			 */
    921 			for (ph = TAILQ_FIRST(&pp->pr_pagelist); ph != NULL;
    922 			     ph = TAILQ_NEXT(ph, ph_pagelist))
    923 				if (TAILQ_FIRST(&ph->ph_itemlist) != NULL)
    924 					break;
    925 
    926 			pp->pr_curpage = ph;
    927 		}
    928 	}
    929 	/*
    930 	 * If the page has just become un-empty, move it to the head of
    931 	 * the list, and make it the current page.  The next allocation
    932 	 * will get the item from this page, instead of further fragmenting
    933 	 * the pool.
    934 	 */
    935 	else if (ph->ph_nmissing == (pp->pr_itemsperpage - 1)) {
    936 		TAILQ_REMOVE(&pp->pr_pagelist, ph, ph_pagelist);
    937 		TAILQ_INSERT_HEAD(&pp->pr_pagelist, ph, ph_pagelist);
    938 		pp->pr_curpage = ph;
    939 	}
    940 }
    941 
    942 /*
    943  * Return resource to the pool; must be called at appropriate spl level
    944  */
    945 void
    946 _pool_put(struct pool *pp, void *v, const char *file, long line)
    947 {
    948 
    949 	simple_lock(&pp->pr_slock);
    950 	pr_enter(pp, file, line);
    951 
    952 	pool_do_put(pp, v, file, line);
    953 
    954 	pr_leave(pp);
    955 	simple_unlock(&pp->pr_slock);
    956 }
    957 
    958 /*
    959  * Add N items to the pool.
    960  */
    961 int
    962 pool_prime(struct pool *pp, int n, caddr_t storage)
    963 {
    964 	caddr_t cp;
    965 	int newnitems, newpages;
    966 
    967 #ifdef DIAGNOSTIC
    968 	if (__predict_false(storage && !(pp->pr_roflags & PR_STATIC)))
    969 		panic("pool_prime: static");
    970 	/* !storage && static caught below */
    971 #endif
    972 
    973 	simple_lock(&pp->pr_slock);
    974 
    975 	newnitems = pp->pr_minitems + n;
    976 	newpages =
    977 		roundup(newnitems, pp->pr_itemsperpage) / pp->pr_itemsperpage
    978 		- pp->pr_minpages;
    979 
    980 	while (newpages-- > 0) {
    981 		if (pp->pr_roflags & PR_STATIC) {
    982 			cp = storage;
    983 			storage += pp->pr_pagesz;
    984 		} else {
    985 			simple_unlock(&pp->pr_slock);
    986 			cp = (*pp->pr_alloc)(pp->pr_pagesz, 0, pp->pr_mtype);
    987 			simple_lock(&pp->pr_slock);
    988 		}
    989 
    990 		if (cp == NULL) {
    991 			simple_unlock(&pp->pr_slock);
    992 			return (ENOMEM);
    993 		}
    994 
    995 		pp->pr_npagealloc++;
    996 		pool_prime_page(pp, cp);
    997 		pp->pr_minpages++;
    998 	}
    999 
   1000 	pp->pr_minitems = newnitems;
   1001 
   1002 	if (pp->pr_minpages >= pp->pr_maxpages)
   1003 		pp->pr_maxpages = pp->pr_minpages + 1;	/* XXX */
   1004 
   1005 	simple_unlock(&pp->pr_slock);
   1006 	return (0);
   1007 }
   1008 
   1009 /*
   1010  * Add a page worth of items to the pool.
   1011  *
   1012  * Note, we must be called with the pool descriptor LOCKED.
   1013  */
   1014 static void
   1015 pool_prime_page(struct pool *pp, caddr_t storage)
   1016 {
   1017 	struct pool_item *pi;
   1018 	struct pool_item_header *ph;
   1019 	caddr_t cp = storage;
   1020 	unsigned int align = pp->pr_align;
   1021 	unsigned int ioff = pp->pr_itemoffset;
   1022 	int s, n;
   1023 
   1024 	if (((u_long)cp & (pp->pr_pagesz - 1)) != 0)
   1025 		panic("pool_prime_page: %s: unaligned page", pp->pr_wchan);
   1026 
   1027 	if ((pp->pr_roflags & PR_PHINPAGE) != 0) {
   1028 		ph = (struct pool_item_header *)(cp + pp->pr_phoffset);
   1029 	} else {
   1030 		s = splhigh();
   1031 		ph = pool_get(&phpool, PR_URGENT);
   1032 		splx(s);
   1033 		LIST_INSERT_HEAD(&pp->pr_hashtab[PR_HASH_INDEX(pp, cp)],
   1034 				 ph, ph_hashlist);
   1035 	}
   1036 
   1037 	/*
   1038 	 * Insert page header.
   1039 	 */
   1040 	TAILQ_INSERT_HEAD(&pp->pr_pagelist, ph, ph_pagelist);
   1041 	TAILQ_INIT(&ph->ph_itemlist);
   1042 	ph->ph_page = storage;
   1043 	ph->ph_nmissing = 0;
   1044 	memset(&ph->ph_time, 0, sizeof(ph->ph_time));
   1045 
   1046 	pp->pr_nidle++;
   1047 
   1048 	/*
   1049 	 * Color this page.
   1050 	 */
   1051 	cp = (caddr_t)(cp + pp->pr_curcolor);
   1052 	if ((pp->pr_curcolor += align) > pp->pr_maxcolor)
   1053 		pp->pr_curcolor = 0;
   1054 
   1055 	/*
   1056 	 * Adjust storage to apply aligment to `pr_itemoffset' in each item.
   1057 	 */
   1058 	if (ioff != 0)
   1059 		cp = (caddr_t)(cp + (align - ioff));
   1060 
   1061 	/*
   1062 	 * Insert remaining chunks on the bucket list.
   1063 	 */
   1064 	n = pp->pr_itemsperpage;
   1065 	pp->pr_nitems += n;
   1066 
   1067 	while (n--) {
   1068 		pi = (struct pool_item *)cp;
   1069 
   1070 		/* Insert on page list */
   1071 		TAILQ_INSERT_TAIL(&ph->ph_itemlist, pi, pi_list);
   1072 #ifdef DIAGNOSTIC
   1073 		pi->pi_magic = PI_MAGIC;
   1074 #endif
   1075 		cp = (caddr_t)(cp + pp->pr_size);
   1076 	}
   1077 
   1078 	/*
   1079 	 * If the pool was depleted, point at the new page.
   1080 	 */
   1081 	if (pp->pr_curpage == NULL)
   1082 		pp->pr_curpage = ph;
   1083 
   1084 	if (++pp->pr_npages > pp->pr_hiwat)
   1085 		pp->pr_hiwat = pp->pr_npages;
   1086 }
   1087 
   1088 /*
   1089  * Like pool_prime(), except this is used by pool_get() when nitems
   1090  * drops below the low water mark.  This is used to catch up nitmes
   1091  * with the low water mark.
   1092  *
   1093  * Note 1, we never wait for memory here, we let the caller decide what to do.
   1094  *
   1095  * Note 2, this doesn't work with static pools.
   1096  *
   1097  * Note 3, we must be called with the pool already locked, and we return
   1098  * with it locked.
   1099  */
   1100 static int
   1101 pool_catchup(struct pool *pp)
   1102 {
   1103 	caddr_t cp;
   1104 	int error = 0;
   1105 
   1106 	if (pp->pr_roflags & PR_STATIC) {
   1107 		/*
   1108 		 * We dropped below the low water mark, and this is not a
   1109 		 * good thing.  Log a warning.
   1110 		 *
   1111 		 * XXX: rate-limit this?
   1112 		 */
   1113 		printf("WARNING: static pool `%s' dropped below low water "
   1114 		    "mark\n", pp->pr_wchan);
   1115 		return (0);
   1116 	}
   1117 
   1118 	while (pp->pr_nitems < pp->pr_minitems) {
   1119 		/*
   1120 		 * Call the page back-end allocator for more memory.
   1121 		 *
   1122 		 * XXX: We never wait, so should we bother unlocking
   1123 		 * the pool descriptor?
   1124 		 */
   1125 		simple_unlock(&pp->pr_slock);
   1126 		cp = (*pp->pr_alloc)(pp->pr_pagesz, 0, pp->pr_mtype);
   1127 		simple_lock(&pp->pr_slock);
   1128 		if (__predict_false(cp == NULL)) {
   1129 			error = ENOMEM;
   1130 			break;
   1131 		}
   1132 		pp->pr_npagealloc++;
   1133 		pool_prime_page(pp, cp);
   1134 	}
   1135 
   1136 	return (error);
   1137 }
   1138 
   1139 void
   1140 pool_setlowat(struct pool *pp, int n)
   1141 {
   1142 	int error;
   1143 
   1144 	simple_lock(&pp->pr_slock);
   1145 
   1146 	pp->pr_minitems = n;
   1147 	pp->pr_minpages = (n == 0)
   1148 		? 0
   1149 		: roundup(n, pp->pr_itemsperpage) / pp->pr_itemsperpage;
   1150 
   1151 	/* Make sure we're caught up with the newly-set low water mark. */
   1152 	if ((pp->pr_nitems < pp->pr_minitems) &&
   1153 	    (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 _pool_reclaim(struct pool *pp, const char *file, long line)
   1244 {
   1245 	struct pool_item_header *ph, *phnext;
   1246 	struct pool_cache *pc;
   1247 	struct timeval curtime;
   1248 	int s;
   1249 
   1250 	if (pp->pr_roflags & PR_STATIC)
   1251 		return;
   1252 
   1253 	if (simple_lock_try(&pp->pr_slock) == 0)
   1254 		return;
   1255 	pr_enter(pp, file, line);
   1256 
   1257 	/*
   1258 	 * Reclaim items from the pool's caches.
   1259 	 */
   1260 	for (pc = TAILQ_FIRST(&pp->pr_cachelist); pc != NULL;
   1261 	     pc = TAILQ_NEXT(pc, pc_poollist))
   1262 		pool_cache_reclaim(pc);
   1263 
   1264 	s = splclock();
   1265 	curtime = mono_time;
   1266 	splx(s);
   1267 
   1268 	for (ph = TAILQ_FIRST(&pp->pr_pagelist); ph != NULL; ph = phnext) {
   1269 		phnext = TAILQ_NEXT(ph, ph_pagelist);
   1270 
   1271 		/* Check our minimum page claim */
   1272 		if (pp->pr_npages <= pp->pr_minpages)
   1273 			break;
   1274 
   1275 		if (ph->ph_nmissing == 0) {
   1276 			struct timeval diff;
   1277 			timersub(&curtime, &ph->ph_time, &diff);
   1278 			if (diff.tv_sec < pool_inactive_time)
   1279 				continue;
   1280 
   1281 			/*
   1282 			 * If freeing this page would put us below
   1283 			 * the low water mark, stop now.
   1284 			 */
   1285 			if ((pp->pr_nitems - pp->pr_itemsperpage) <
   1286 			    pp->pr_minitems)
   1287 				break;
   1288 
   1289 			pr_rmpage(pp, ph);
   1290 		}
   1291 	}
   1292 
   1293 	pr_leave(pp);
   1294 	simple_unlock(&pp->pr_slock);
   1295 }
   1296 
   1297 
   1298 /*
   1299  * Drain pools, one at a time.
   1300  *
   1301  * Note, we must never be called from an interrupt context.
   1302  */
   1303 void
   1304 pool_drain(void *arg)
   1305 {
   1306 	struct pool *pp;
   1307 	int s;
   1308 
   1309 	s = splimp();
   1310 	simple_lock(&pool_head_slock);
   1311 
   1312 	if (drainpp == NULL && (drainpp = TAILQ_FIRST(&pool_head)) == NULL)
   1313 		goto out;
   1314 
   1315 	pp = drainpp;
   1316 	drainpp = TAILQ_NEXT(pp, pr_poollist);
   1317 
   1318 	pool_reclaim(pp);
   1319 
   1320  out:
   1321 	simple_unlock(&pool_head_slock);
   1322 	splx(s);
   1323 }
   1324 
   1325 
   1326 /*
   1327  * Diagnostic helpers.
   1328  */
   1329 void
   1330 pool_print(struct pool *pp, const char *modif)
   1331 {
   1332 	int s;
   1333 
   1334 	s = splimp();
   1335 	if (simple_lock_try(&pp->pr_slock) == 0) {
   1336 		printf("pool %s is locked; try again later\n",
   1337 		    pp->pr_wchan);
   1338 		splx(s);
   1339 		return;
   1340 	}
   1341 	pool_print1(pp, modif, printf);
   1342 	simple_unlock(&pp->pr_slock);
   1343 	splx(s);
   1344 }
   1345 
   1346 void
   1347 pool_printit(struct pool *pp, const char *modif, void (*pr)(const char *, ...))
   1348 {
   1349 	int didlock = 0;
   1350 
   1351 	if (pp == NULL) {
   1352 		(*pr)("Must specify a pool to print.\n");
   1353 		return;
   1354 	}
   1355 
   1356 	/*
   1357 	 * Called from DDB; interrupts should be blocked, and all
   1358 	 * other processors should be paused.  We can skip locking
   1359 	 * the pool in this case.
   1360 	 *
   1361 	 * We do a simple_lock_try() just to print the lock
   1362 	 * status, however.
   1363 	 */
   1364 
   1365 	if (simple_lock_try(&pp->pr_slock) == 0)
   1366 		(*pr)("WARNING: pool %s is locked\n", pp->pr_wchan);
   1367 	else
   1368 		didlock = 1;
   1369 
   1370 	pool_print1(pp, modif, pr);
   1371 
   1372 	if (didlock)
   1373 		simple_unlock(&pp->pr_slock);
   1374 }
   1375 
   1376 static void
   1377 pool_print1(struct pool *pp, const char *modif, void (*pr)(const char *, ...))
   1378 {
   1379 	struct pool_item_header *ph;
   1380 	struct pool_cache *pc;
   1381 	struct pool_cache_group *pcg;
   1382 #ifdef DIAGNOSTIC
   1383 	struct pool_item *pi;
   1384 #endif
   1385 	int i, print_log = 0, print_pagelist = 0, print_cache = 0;
   1386 	char c;
   1387 
   1388 	while ((c = *modif++) != '\0') {
   1389 		if (c == 'l')
   1390 			print_log = 1;
   1391 		if (c == 'p')
   1392 			print_pagelist = 1;
   1393 		if (c == 'c')
   1394 			print_cache = 1;
   1395 		modif++;
   1396 	}
   1397 
   1398 	(*pr)("POOL %s: size %u, align %u, ioff %u, roflags 0x%08x\n",
   1399 	    pp->pr_wchan, pp->pr_size, pp->pr_align, pp->pr_itemoffset,
   1400 	    pp->pr_roflags);
   1401 	(*pr)("\tpagesz %u, mtype %d\n", pp->pr_pagesz, pp->pr_mtype);
   1402 	(*pr)("\talloc %p, release %p\n", pp->pr_alloc, pp->pr_free);
   1403 	(*pr)("\tminitems %u, minpages %u, maxpages %u, npages %u\n",
   1404 	    pp->pr_minitems, pp->pr_minpages, pp->pr_maxpages, pp->pr_npages);
   1405 	(*pr)("\titemsperpage %u, nitems %u, nout %u, hardlimit %u\n",
   1406 	    pp->pr_itemsperpage, pp->pr_nitems, pp->pr_nout, pp->pr_hardlimit);
   1407 
   1408 	(*pr)("\n\tnget %lu, nfail %lu, nput %lu\n",
   1409 	    pp->pr_nget, pp->pr_nfail, pp->pr_nput);
   1410 	(*pr)("\tnpagealloc %lu, npagefree %lu, hiwat %u, nidle %lu\n",
   1411 	    pp->pr_npagealloc, pp->pr_npagefree, pp->pr_hiwat, pp->pr_nidle);
   1412 
   1413 	if (print_pagelist == 0)
   1414 		goto skip_pagelist;
   1415 
   1416 	if ((ph = TAILQ_FIRST(&pp->pr_pagelist)) != NULL)
   1417 		(*pr)("\n\tpage list:\n");
   1418 	for (; ph != NULL; ph = TAILQ_NEXT(ph, ph_pagelist)) {
   1419 		(*pr)("\t\tpage %p, nmissing %d, time %lu,%lu\n",
   1420 		    ph->ph_page, ph->ph_nmissing,
   1421 		    (u_long)ph->ph_time.tv_sec,
   1422 		    (u_long)ph->ph_time.tv_usec);
   1423 #ifdef DIAGNOSTIC
   1424 		for (pi = TAILQ_FIRST(&ph->ph_itemlist); pi != NULL;
   1425 		     pi = TAILQ_NEXT(pi, pi_list)) {
   1426 			if (pi->pi_magic != PI_MAGIC) {
   1427 				(*pr)("\t\t\titem %p, magic 0x%x\n",
   1428 				    pi, pi->pi_magic);
   1429 			}
   1430 		}
   1431 #endif
   1432 	}
   1433 	if (pp->pr_curpage == NULL)
   1434 		(*pr)("\tno current page\n");
   1435 	else
   1436 		(*pr)("\tcurpage %p\n", pp->pr_curpage->ph_page);
   1437 
   1438  skip_pagelist:
   1439 
   1440 	if (print_log == 0)
   1441 		goto skip_log;
   1442 
   1443 	(*pr)("\n");
   1444 	if ((pp->pr_roflags & PR_LOGGING) == 0)
   1445 		(*pr)("\tno log\n");
   1446 	else
   1447 		pr_printlog(pp, NULL, pr);
   1448 
   1449  skip_log:
   1450 
   1451 	if (print_cache == 0)
   1452 		goto skip_cache;
   1453 
   1454 	for (pc = TAILQ_FIRST(&pp->pr_cachelist); pc != NULL;
   1455 	     pc = TAILQ_NEXT(pc, pc_poollist)) {
   1456 		(*pr)("\tcache %p: allocfrom %p freeto %p\n", pc,
   1457 		    pc->pc_allocfrom, pc->pc_freeto);
   1458 		for (pcg = TAILQ_FIRST(&pc->pc_grouplist); pcg != NULL;
   1459 		     pcg = TAILQ_NEXT(pcg, pcg_list)) {
   1460 			(*pr)("\t\tgroup %p: avail %d\n", pcg, pcg->pcg_avail);
   1461 			for (i = 0; i < PCG_NOBJECTS; i++)
   1462 				(*pr)("\t\t\t%p\n", pcg->pcg_objects[i]);
   1463 		}
   1464 	}
   1465 
   1466  skip_cache:
   1467 
   1468 	pr_enter_check(pp, pr);
   1469 }
   1470 
   1471 int
   1472 pool_chk(struct pool *pp, const char *label)
   1473 {
   1474 	struct pool_item_header *ph;
   1475 	int r = 0;
   1476 
   1477 	simple_lock(&pp->pr_slock);
   1478 
   1479 	for (ph = TAILQ_FIRST(&pp->pr_pagelist); ph != NULL;
   1480 	     ph = TAILQ_NEXT(ph, ph_pagelist)) {
   1481 
   1482 		struct pool_item *pi;
   1483 		int n;
   1484 		caddr_t page;
   1485 
   1486 		page = (caddr_t)((u_long)ph & pp->pr_pagemask);
   1487 		if (page != ph->ph_page &&
   1488 		    (pp->pr_roflags & PR_PHINPAGE) != 0) {
   1489 			if (label != NULL)
   1490 				printf("%s: ", label);
   1491 			printf("pool(%p:%s): page inconsistency: page %p;"
   1492 			       " at page head addr %p (p %p)\n", pp,
   1493 				pp->pr_wchan, ph->ph_page,
   1494 				ph, page);
   1495 			r++;
   1496 			goto out;
   1497 		}
   1498 
   1499 		for (pi = TAILQ_FIRST(&ph->ph_itemlist), n = 0;
   1500 		     pi != NULL;
   1501 		     pi = TAILQ_NEXT(pi,pi_list), n++) {
   1502 
   1503 #ifdef DIAGNOSTIC
   1504 			if (pi->pi_magic != PI_MAGIC) {
   1505 				if (label != NULL)
   1506 					printf("%s: ", label);
   1507 				printf("pool(%s): free list modified: magic=%x;"
   1508 				       " page %p; item ordinal %d;"
   1509 				       " addr %p (p %p)\n",
   1510 					pp->pr_wchan, pi->pi_magic, ph->ph_page,
   1511 					n, pi, page);
   1512 				panic("pool");
   1513 			}
   1514 #endif
   1515 			page = (caddr_t)((u_long)pi & pp->pr_pagemask);
   1516 			if (page == ph->ph_page)
   1517 				continue;
   1518 
   1519 			if (label != NULL)
   1520 				printf("%s: ", label);
   1521 			printf("pool(%p:%s): page inconsistency: page %p;"
   1522 			       " item ordinal %d; addr %p (p %p)\n", pp,
   1523 				pp->pr_wchan, ph->ph_page,
   1524 				n, pi, page);
   1525 			r++;
   1526 			goto out;
   1527 		}
   1528 	}
   1529 out:
   1530 	simple_unlock(&pp->pr_slock);
   1531 	return (r);
   1532 }
   1533 
   1534 /*
   1535  * pool_cache_init:
   1536  *
   1537  *	Initialize a pool cache.
   1538  *
   1539  *	NOTE: If the pool must be protected from interrupts, we expect
   1540  *	to be called at the appropriate interrupt priority level.
   1541  */
   1542 void
   1543 pool_cache_init(struct pool_cache *pc, struct pool *pp,
   1544     int (*ctor)(void *, void *, int),
   1545     void (*dtor)(void *, void *),
   1546     void *arg)
   1547 {
   1548 
   1549 	TAILQ_INIT(&pc->pc_grouplist);
   1550 	simple_lock_init(&pc->pc_slock);
   1551 
   1552 	pc->pc_allocfrom = NULL;
   1553 	pc->pc_freeto = NULL;
   1554 	pc->pc_pool = pp;
   1555 
   1556 	pc->pc_ctor = ctor;
   1557 	pc->pc_dtor = dtor;
   1558 	pc->pc_arg  = arg;
   1559 
   1560 	simple_lock(&pp->pr_slock);
   1561 	TAILQ_INSERT_TAIL(&pp->pr_cachelist, pc, pc_poollist);
   1562 	simple_unlock(&pp->pr_slock);
   1563 }
   1564 
   1565 /*
   1566  * pool_cache_destroy:
   1567  *
   1568  *	Destroy a pool cache.
   1569  */
   1570 void
   1571 pool_cache_destroy(struct pool_cache *pc)
   1572 {
   1573 	struct pool *pp = pc->pc_pool;
   1574 
   1575 	/* First, invalidate the entire cache. */
   1576 	pool_cache_invalidate(pc);
   1577 
   1578 	/* ...and remove it from the pool's cache list. */
   1579 	simple_lock(&pp->pr_slock);
   1580 	TAILQ_REMOVE(&pp->pr_cachelist, pc, pc_poollist);
   1581 	simple_unlock(&pp->pr_slock);
   1582 }
   1583 
   1584 static __inline void *
   1585 pcg_get(struct pool_cache_group *pcg)
   1586 {
   1587 	void *object;
   1588 	u_int idx;
   1589 
   1590 	KASSERT(pcg->pcg_avail <= PCG_NOBJECTS);
   1591 	idx = --pcg->pcg_avail;
   1592 
   1593 	KASSERT(pcg->pcg_objects[idx] != NULL);
   1594 	object = pcg->pcg_objects[idx];
   1595 	pcg->pcg_objects[idx] = NULL;
   1596 
   1597 	return (object);
   1598 }
   1599 
   1600 static __inline void
   1601 pcg_put(struct pool_cache_group *pcg, void *object)
   1602 {
   1603 	u_int idx;
   1604 
   1605 	KASSERT(pcg->pcg_avail < PCG_NOBJECTS);
   1606 	idx = pcg->pcg_avail++;
   1607 
   1608 	KASSERT(pcg->pcg_objects[idx] == NULL);
   1609 	pcg->pcg_objects[idx] = object;
   1610 }
   1611 
   1612 /*
   1613  * pool_cache_get:
   1614  *
   1615  *	Get an object from a pool cache.
   1616  */
   1617 void *
   1618 pool_cache_get(struct pool_cache *pc, int flags)
   1619 {
   1620 	struct pool_cache_group *pcg;
   1621 	void *object;
   1622 
   1623 	simple_lock(&pc->pc_slock);
   1624 
   1625 	if ((pcg = pc->pc_allocfrom) == NULL) {
   1626 		for (pcg = TAILQ_FIRST(&pc->pc_grouplist); pcg != NULL;
   1627 		     pcg = TAILQ_NEXT(pcg, pcg_list)) {
   1628 			if (pcg->pcg_avail != 0) {
   1629 				pc->pc_allocfrom = pcg;
   1630 				goto have_group;
   1631 			}
   1632 		}
   1633 
   1634 		/*
   1635 		 * No groups with any available objects.  Allocate
   1636 		 * a new object, construct it, and return it to
   1637 		 * the caller.  We will allocate a group, if necessary,
   1638 		 * when the object is freed back to the cache.
   1639 		 */
   1640 		simple_unlock(&pc->pc_slock);
   1641 		object = pool_get(pc->pc_pool, flags);
   1642 		if (object != NULL && pc->pc_ctor != NULL) {
   1643 			if ((*pc->pc_ctor)(pc->pc_arg, object, flags) != 0) {
   1644 				pool_put(pc->pc_pool, object);
   1645 				return (NULL);
   1646 			}
   1647 		}
   1648 		return (object);
   1649 	}
   1650 
   1651  have_group:
   1652 	object = pcg_get(pcg);
   1653 
   1654 	if (pcg->pcg_avail == 0)
   1655 		pc->pc_allocfrom = NULL;
   1656 
   1657 	simple_unlock(&pc->pc_slock);
   1658 
   1659 	return (object);
   1660 }
   1661 
   1662 /*
   1663  * pool_cache_put:
   1664  *
   1665  *	Put an object back to the pool cache.
   1666  */
   1667 void
   1668 pool_cache_put(struct pool_cache *pc, void *object)
   1669 {
   1670 	struct pool_cache_group *pcg;
   1671 
   1672 	simple_lock(&pc->pc_slock);
   1673 
   1674 	if ((pcg = pc->pc_freeto) == NULL) {
   1675 		for (pcg = TAILQ_FIRST(&pc->pc_grouplist); pcg != NULL;
   1676 		     pcg = TAILQ_NEXT(pcg, pcg_list)) {
   1677 			if (pcg->pcg_avail != PCG_NOBJECTS) {
   1678 				pc->pc_freeto = pcg;
   1679 				goto have_group;
   1680 			}
   1681 		}
   1682 
   1683 		/*
   1684 		 * No empty groups to free the object to.  Attempt to
   1685 		 * allocate one.  We don't unlock the cache here, since
   1686 		 * we never block.
   1687 		 */
   1688 		pcg = pool_get(&pcgpool, PR_NOWAIT);
   1689 		if (pcg != NULL) {
   1690 			memset(pcg, 0, sizeof(*pcg));
   1691 			TAILQ_INSERT_TAIL(&pc->pc_grouplist, pcg, pcg_list);
   1692 			pc->pc_freeto = pcg;
   1693 			goto have_group;
   1694 		}
   1695 
   1696 		simple_unlock(&pc->pc_slock);
   1697 
   1698 		/*
   1699 		 * Unable to allocate a cache group; destruct the object
   1700 		 * and free it back to the pool.
   1701 		 */
   1702 		if (pc->pc_dtor != NULL)
   1703 			(*pc->pc_dtor)(pc->pc_arg, object);
   1704 		pool_put(pc->pc_pool, object);
   1705 		return;
   1706 	}
   1707 
   1708  have_group:
   1709 	pcg_put(pcg, object);
   1710 
   1711 	if (pcg->pcg_avail == PCG_NOBJECTS)
   1712 		pc->pc_freeto = NULL;
   1713 
   1714 	simple_unlock(&pc->pc_slock);
   1715 }
   1716 
   1717 /*
   1718  * pool_cache_do_invalidate:
   1719  *
   1720  *	This internal function implements pool_cache_invalidate() and
   1721  *	pool_cache_reclaim().
   1722  */
   1723 static void
   1724 pool_cache_do_invalidate(struct pool_cache *pc, int free_groups,
   1725     void (*putit)(struct pool *, void *, const char *, long))
   1726 {
   1727 	struct pool_cache_group *pcg, *npcg;
   1728 	void *object;
   1729 
   1730 	for (pcg = TAILQ_FIRST(&pc->pc_grouplist); pcg != NULL;
   1731 	     pcg = npcg) {
   1732 		npcg = TAILQ_NEXT(pcg, pcg_list);
   1733 		while (pcg->pcg_avail != 0) {
   1734 			object = pcg_get(pcg);
   1735 			if (pc->pc_dtor != NULL)
   1736 				(*pc->pc_dtor)(pc->pc_arg, object);
   1737 			(*putit)(pc->pc_pool, object, __FILE__, __LINE__);
   1738 		}
   1739 		if (free_groups) {
   1740 			TAILQ_REMOVE(&pc->pc_grouplist, pcg, pcg_list);
   1741 			pool_put(&pcgpool, pcg);
   1742 		}
   1743 	}
   1744 }
   1745 
   1746 /*
   1747  * pool_cache_invalidate:
   1748  *
   1749  *	Invalidate a pool cache (destruct and release all of the
   1750  *	cached objects).
   1751  */
   1752 void
   1753 pool_cache_invalidate(struct pool_cache *pc)
   1754 {
   1755 
   1756 	simple_lock(&pc->pc_slock);
   1757 	pool_cache_do_invalidate(pc, 0, _pool_put);
   1758 	simple_unlock(&pc->pc_slock);
   1759 }
   1760 
   1761 /*
   1762  * pool_cache_reclaim:
   1763  *
   1764  *	Reclaim a pool cache for pool_reclaim().
   1765  */
   1766 static void
   1767 pool_cache_reclaim(struct pool_cache *pc)
   1768 {
   1769 
   1770 	/*
   1771 	 * We're locking in the opposite order (pool already
   1772 	 * locked in pool_reclaim()), so use a try-lock instead.
   1773 	 */
   1774 
   1775 	if (simple_lock_try(&pc->pc_slock) == 0)
   1776 		return;
   1777 	pool_cache_do_invalidate(pc, 1, pool_do_put);
   1778 	simple_unlock(&pc->pc_slock);
   1779 }
   1780