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