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