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