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