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