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