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