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