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