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