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