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