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