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