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