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