xref: /openbsd-src/sys/kern/subr_pool.c (revision 43003dfe3ad45d1698bed8a37f2b0f5b14f20d4f)
1 /*	$OpenBSD: subr_pool.c,v 1.90 2009/09/05 16:06:57 thib Exp $	*/
2 /*	$NetBSD: subr_pool.c,v 1.61 2001/09/26 07:14:56 chs Exp $	*/
3 
4 /*-
5  * Copyright (c) 1997, 1999, 2000 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.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
23  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
25  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/proc.h>
37 #include <sys/errno.h>
38 #include <sys/kernel.h>
39 #include <sys/malloc.h>
40 #include <sys/pool.h>
41 #include <sys/syslog.h>
42 #include <sys/sysctl.h>
43 
44 #include <uvm/uvm.h>
45 
46 
47 /*
48  * Pool resource management utility.
49  *
50  * Memory is allocated in pages which are split into pieces according to
51  * the pool item size. Each page is kept on one of three lists in the
52  * pool structure: `pr_emptypages', `pr_fullpages' and `pr_partpages',
53  * for empty, full and partially-full pages respectively. The individual
54  * pool items are on a linked list headed by `ph_itemlist' in each page
55  * header. The memory for building the page list is either taken from
56  * the allocated pages themselves (for small pool items) or taken from
57  * an internal pool of page headers (`phpool').
58  */
59 
60 /* List of all pools */
61 TAILQ_HEAD(,pool) pool_head = TAILQ_HEAD_INITIALIZER(pool_head);
62 
63 /* Private pool for page header structures */
64 struct pool phpool;
65 
66 struct pool_item_header {
67 	/* Page headers */
68 	LIST_ENTRY(pool_item_header)
69 				ph_pagelist;	/* pool page list */
70 	TAILQ_HEAD(,pool_item)	ph_itemlist;	/* chunk list for this page */
71 	RB_ENTRY(pool_item_header)
72 				ph_node;	/* Off-page page headers */
73 	int			ph_nmissing;	/* # of chunks in use */
74 	caddr_t			ph_page;	/* this page's address */
75 	caddr_t			ph_colored;	/* page's colored address */
76 	int			ph_pagesize;
77 };
78 
79 struct pool_item {
80 #ifdef DIAGNOSTIC
81 	u_int32_t pi_magic;
82 #endif
83 	/* Other entries use only this list entry */
84 	TAILQ_ENTRY(pool_item)	pi_list;
85 };
86 
87 #ifdef DEADBEEF1
88 #define	PI_MAGIC DEADBEEF1
89 #else
90 #define	PI_MAGIC 0xdeafbeef
91 #endif
92 
93 #define	POOL_NEEDS_CATCHUP(pp)						\
94 	((pp)->pr_nitems < (pp)->pr_minitems)
95 
96 /*
97  * Every pool gets a unique serial number assigned to it. If this counter
98  * wraps, we're screwed, but we shouldn't create so many pools anyway.
99  */
100 unsigned int pool_serial;
101 
102 int	 pool_catchup(struct pool *);
103 void	 pool_prime_page(struct pool *, caddr_t, struct pool_item_header *);
104 void	 pool_update_curpage(struct pool *);
105 void	*pool_do_get(struct pool *, int);
106 void	 pool_do_put(struct pool *, void *);
107 void	 pr_rmpage(struct pool *, struct pool_item_header *,
108 	    struct pool_pagelist *);
109 int	pool_chk_page(struct pool *, const char *, struct pool_item_header *);
110 struct pool_item_header *pool_alloc_item_header(struct pool *, caddr_t , int);
111 
112 void	*pool_allocator_alloc(struct pool *, int, int *);
113 void	 pool_allocator_free(struct pool *, void *);
114 
115 /*
116  * XXX - quick hack. For pools with large items we want to use a special
117  *       allocator. For now, instead of having the allocator figure out
118  *       the allocation size from the pool (which can be done trivially
119  *       with round_page(pr_itemsperpage * pr_size)) which would require
120  *	 lots of changes everywhere, we just create allocators for each
121  *	 size. We limit those to 128 pages.
122  */
123 #define POOL_LARGE_MAXPAGES 128
124 struct pool_allocator pool_allocator_large[POOL_LARGE_MAXPAGES];
125 struct pool_allocator pool_allocator_large_ni[POOL_LARGE_MAXPAGES];
126 void	*pool_large_alloc(struct pool *, int, int *);
127 void	pool_large_free(struct pool *, void *);
128 void	*pool_large_alloc_ni(struct pool *, int, int *);
129 void	pool_large_free_ni(struct pool *, void *);
130 
131 
132 #ifdef DDB
133 void	 pool_print_pagelist(struct pool_pagelist *,
134 	    int (*)(const char *, ...));
135 void	 pool_print1(struct pool *, const char *, int (*)(const char *, ...));
136 #endif
137 
138 #define pool_sleep(pl) msleep(pl, &pl->pr_mtx, PSWP, pl->pr_wchan, 0)
139 
140 static __inline int
141 phtree_compare(struct pool_item_header *a, struct pool_item_header *b)
142 {
143 	long diff = (vaddr_t)a->ph_page - (vaddr_t)b->ph_page;
144 	if (diff < 0)
145 		return -(-diff >= a->ph_pagesize);
146 	else if (diff > 0)
147 		return (diff >= b->ph_pagesize);
148 	else
149 		return (0);
150 }
151 
152 RB_PROTOTYPE(phtree, pool_item_header, ph_node, phtree_compare);
153 RB_GENERATE(phtree, pool_item_header, ph_node, phtree_compare);
154 
155 /*
156  * Return the pool page header based on page address.
157  */
158 static __inline struct pool_item_header *
159 pr_find_pagehead(struct pool *pp, void *v)
160 {
161 	struct pool_item_header *ph, tmp;
162 
163 	if ((pp->pr_roflags & PR_PHINPAGE) != 0) {
164 		caddr_t page;
165 
166 		page = (caddr_t)((vaddr_t)v & pp->pr_alloc->pa_pagemask);
167 
168 		return ((struct pool_item_header *)(page + pp->pr_phoffset));
169 	}
170 
171 	/*
172 	 * The trick we're using in the tree compare function is to compare
173 	 * two elements equal when they overlap. We want to return the
174 	 * page header that belongs to the element just before this address.
175 	 * We don't want this element to compare equal to the next element,
176 	 * so the compare function takes the pagesize from the lower element.
177 	 * If this header is the lower, its pagesize is zero, so it can't
178 	 * overlap with the next header. But if the header we're looking for
179 	 * is lower, we'll use its pagesize and it will overlap and return
180 	 * equal.
181 	 */
182 	tmp.ph_page = v;
183 	tmp.ph_pagesize = 0;
184 	ph = RB_FIND(phtree, &pp->pr_phtree, &tmp);
185 
186 	if (ph) {
187 		KASSERT(ph->ph_page <= (caddr_t)v);
188 		KASSERT(ph->ph_page + ph->ph_pagesize > (caddr_t)v);
189 	}
190 	return ph;
191 }
192 
193 /*
194  * Remove a page from the pool.
195  */
196 void
197 pr_rmpage(struct pool *pp, struct pool_item_header *ph,
198     struct pool_pagelist *pq)
199 {
200 
201 	/*
202 	 * If the page was idle, decrement the idle page count.
203 	 */
204 	if (ph->ph_nmissing == 0) {
205 #ifdef DIAGNOSTIC
206 		if (pp->pr_nidle == 0)
207 			panic("pr_rmpage: nidle inconsistent");
208 		if (pp->pr_nitems < pp->pr_itemsperpage)
209 			panic("pr_rmpage: nitems inconsistent");
210 #endif
211 		pp->pr_nidle--;
212 	}
213 
214 	pp->pr_nitems -= pp->pr_itemsperpage;
215 
216 	/*
217 	 * Unlink a page from the pool and release it (or queue it for release).
218 	 */
219 	LIST_REMOVE(ph, ph_pagelist);
220 	if ((pp->pr_roflags & PR_PHINPAGE) == 0)
221 		RB_REMOVE(phtree, &pp->pr_phtree, ph);
222 	if (pq) {
223 		LIST_INSERT_HEAD(pq, ph, ph_pagelist);
224 	} else {
225 		pool_allocator_free(pp, ph->ph_page);
226 		if ((pp->pr_roflags & PR_PHINPAGE) == 0)
227 			pool_put(&phpool, ph);
228 	}
229 	pp->pr_npages--;
230 	pp->pr_npagefree++;
231 
232 	pool_update_curpage(pp);
233 }
234 
235 /*
236  * Initialize the given pool resource structure.
237  *
238  * We export this routine to allow other kernel parts to declare
239  * static pools that must be initialized before malloc() is available.
240  */
241 void
242 pool_init(struct pool *pp, size_t size, u_int align, u_int ioff, int flags,
243     const char *wchan, struct pool_allocator *palloc)
244 {
245 	int off, slack;
246 
247 #ifdef MALLOC_DEBUG
248 	if ((flags & PR_DEBUG) && (ioff != 0 || align != 0))
249 		flags &= ~PR_DEBUG;
250 #endif
251 	/*
252 	 * Check arguments and construct default values.
253 	 */
254 	if (palloc == NULL) {
255 		if (size > PAGE_SIZE) {
256 			int psize;
257 
258 			/*
259 			 * XXX - should take align into account as well.
260 			 */
261 			if (size == round_page(size))
262 				psize = size / PAGE_SIZE;
263 			else
264 				psize = PAGE_SIZE / roundup(size % PAGE_SIZE,
265 				    1024);
266 			if (psize > POOL_LARGE_MAXPAGES)
267 				psize = POOL_LARGE_MAXPAGES;
268 			if (flags & PR_WAITOK)
269 				palloc = &pool_allocator_large_ni[psize-1];
270 			else
271 				palloc = &pool_allocator_large[psize-1];
272 			if (palloc->pa_pagesz == 0) {
273 				palloc->pa_pagesz = psize * PAGE_SIZE;
274 				if (flags & PR_WAITOK) {
275 					palloc->pa_alloc = pool_large_alloc_ni;
276 					palloc->pa_free = pool_large_free_ni;
277 				} else {
278 					palloc->pa_alloc = pool_large_alloc;
279 					palloc->pa_free = pool_large_free;
280 				}
281 			}
282 		} else {
283 			palloc = &pool_allocator_nointr;
284 		}
285 	}
286 	if (palloc->pa_pagesz == 0) {
287 		palloc->pa_pagesz = PAGE_SIZE;
288 	}
289 	if (palloc->pa_pagemask == 0) {
290 		palloc->pa_pagemask = ~(palloc->pa_pagesz - 1);
291 		palloc->pa_pageshift = ffs(palloc->pa_pagesz) - 1;
292 	}
293 
294 	if (align == 0)
295 		align = ALIGN(1);
296 
297 	if (size < sizeof(struct pool_item))
298 		size = sizeof(struct pool_item);
299 
300 	size = roundup(size, align);
301 #ifdef DIAGNOSTIC
302 	if (size > palloc->pa_pagesz)
303 		panic("pool_init: pool item size (%lu) too large",
304 		    (u_long)size);
305 #endif
306 
307 	/*
308 	 * Initialize the pool structure.
309 	 */
310 	LIST_INIT(&pp->pr_emptypages);
311 	LIST_INIT(&pp->pr_fullpages);
312 	LIST_INIT(&pp->pr_partpages);
313 	pp->pr_curpage = NULL;
314 	pp->pr_npages = 0;
315 	pp->pr_minitems = 0;
316 	pp->pr_minpages = 0;
317 	pp->pr_maxpages = 8;
318 	pp->pr_roflags = flags;
319 	pp->pr_flags = 0;
320 	pp->pr_size = size;
321 	pp->pr_align = align;
322 	pp->pr_wchan = wchan;
323 	pp->pr_alloc = palloc;
324 	pp->pr_nitems = 0;
325 	pp->pr_nout = 0;
326 	pp->pr_hardlimit = UINT_MAX;
327 	pp->pr_hardlimit_warning = NULL;
328 	pp->pr_hardlimit_ratecap.tv_sec = 0;
329 	pp->pr_hardlimit_ratecap.tv_usec = 0;
330 	pp->pr_hardlimit_warning_last.tv_sec = 0;
331 	pp->pr_hardlimit_warning_last.tv_usec = 0;
332 	pp->pr_serial = ++pool_serial;
333 	if (pool_serial == 0)
334 		panic("pool_init: too much uptime");
335 
336         /* constructor, destructor, and arg */
337 	pp->pr_ctor = NULL;
338 	pp->pr_dtor = NULL;
339 	pp->pr_arg = NULL;
340 
341 	/*
342 	 * Decide whether to put the page header off page to avoid
343 	 * wasting too large a part of the page. Off-page page headers
344 	 * go into an RB tree, so we can match a returned item with
345 	 * its header based on the page address.
346 	 * We use 1/16 of the page size as the threshold (XXX: tune)
347 	 */
348 	if (pp->pr_size < palloc->pa_pagesz/16 && pp->pr_size < PAGE_SIZE) {
349 		/* Use the end of the page for the page header */
350 		pp->pr_roflags |= PR_PHINPAGE;
351 		pp->pr_phoffset = off = palloc->pa_pagesz -
352 		    ALIGN(sizeof(struct pool_item_header));
353 	} else {
354 		/* The page header will be taken from our page header pool */
355 		pp->pr_phoffset = 0;
356 		off = palloc->pa_pagesz;
357 		RB_INIT(&pp->pr_phtree);
358 	}
359 
360 	/*
361 	 * Alignment is to take place at `ioff' within the item. This means
362 	 * we must reserve up to `align - 1' bytes on the page to allow
363 	 * appropriate positioning of each item.
364 	 *
365 	 * Silently enforce `0 <= ioff < align'.
366 	 */
367 	pp->pr_itemoffset = ioff = ioff % align;
368 	pp->pr_itemsperpage = (off - ((align - ioff) % align)) / pp->pr_size;
369 	KASSERT(pp->pr_itemsperpage != 0);
370 
371 	/*
372 	 * Use the slack between the chunks and the page header
373 	 * for "cache coloring".
374 	 */
375 	slack = off - pp->pr_itemsperpage * pp->pr_size;
376 	pp->pr_maxcolor = (slack / align) * align;
377 	pp->pr_curcolor = 0;
378 
379 	pp->pr_nget = 0;
380 	pp->pr_nfail = 0;
381 	pp->pr_nput = 0;
382 	pp->pr_npagealloc = 0;
383 	pp->pr_npagefree = 0;
384 	pp->pr_hiwat = 0;
385 	pp->pr_nidle = 0;
386 
387 	pp->pr_ipl = -1;
388 	mtx_init(&pp->pr_mtx, IPL_NONE);
389 
390 	if (phpool.pr_size == 0) {
391 		pool_init(&phpool, sizeof(struct pool_item_header), 0, 0,
392 		    0, "phpool", NULL);
393 		pool_setipl(&phpool, IPL_HIGH);
394 	}
395 
396 	/* Insert this into the list of all pools. */
397 	TAILQ_INSERT_HEAD(&pool_head, pp, pr_poollist);
398 }
399 
400 void
401 pool_setipl(struct pool *pp, int ipl)
402 {
403 	pp->pr_ipl = ipl;
404 	mtx_init(&pp->pr_mtx, ipl);
405 }
406 
407 /*
408  * Decommission a pool resource.
409  */
410 void
411 pool_destroy(struct pool *pp)
412 {
413 	struct pool_item_header *ph;
414 
415 #ifdef DIAGNOSTIC
416 	if (pp->pr_nout != 0)
417 		panic("pool_destroy: pool busy: still out: %u", pp->pr_nout);
418 #endif
419 
420 	/* Remove all pages */
421 	while ((ph = LIST_FIRST(&pp->pr_emptypages)) != NULL)
422 		pr_rmpage(pp, ph, NULL);
423 	KASSERT(LIST_EMPTY(&pp->pr_fullpages));
424 	KASSERT(LIST_EMPTY(&pp->pr_partpages));
425 
426 	/* Remove from global pool list */
427 	TAILQ_REMOVE(&pool_head, pp, pr_poollist);
428 }
429 
430 struct pool_item_header *
431 pool_alloc_item_header(struct pool *pp, caddr_t storage, int flags)
432 {
433 	struct pool_item_header *ph;
434 
435 	if ((pp->pr_roflags & PR_PHINPAGE) != 0)
436 		ph = (struct pool_item_header *)(storage + pp->pr_phoffset);
437 	else {
438 		ph = pool_get(&phpool, flags);
439 	}
440 
441 	return (ph);
442 }
443 
444 /*
445  * Grab an item from the pool; must be called at appropriate spl level
446  */
447 void *
448 pool_get(struct pool *pp, int flags)
449 {
450 	void *v;
451 
452 #ifdef DIAGNOSTIC
453 	if ((flags & PR_WAITOK) != 0)
454 		splassert(IPL_NONE);
455 #endif /* DIAGNOSTIC */
456 
457 	mtx_enter(&pp->pr_mtx);
458 	v = pool_do_get(pp, flags);
459 	mtx_leave(&pp->pr_mtx);
460 	if (v == NULL)
461 		return (v);
462 
463 	if (pp->pr_ctor) {
464 		if (flags & PR_ZERO)
465 			panic("pool_get: PR_ZERO when ctor set");
466 		if (pp->pr_ctor(pp->pr_arg, v, flags)) {
467 			mtx_enter(&pp->pr_mtx);
468 			pool_do_put(pp, v);
469 			mtx_leave(&pp->pr_mtx);
470 			v = NULL;
471 		}
472 	} else {
473 		if (flags & PR_ZERO)
474 			memset(v, 0, pp->pr_size);
475 	}
476 	if (v != NULL)
477 		pp->pr_nget++;
478 	return (v);
479 }
480 
481 void *
482 pool_do_get(struct pool *pp, int flags)
483 {
484 	struct pool_item *pi;
485 	struct pool_item_header *ph;
486 	void *v;
487 	int slowdown = 0;
488 #if defined(DIAGNOSTIC) && defined(POOL_DEBUG)
489 	int i, *ip;
490 #endif
491 
492 #ifdef MALLOC_DEBUG
493 	if (pp->pr_roflags & PR_DEBUG) {
494 		void *addr;
495 
496 		addr = NULL;
497 		debug_malloc(pp->pr_size, M_DEBUG,
498 		    (flags & PR_WAITOK) ? M_WAITOK : M_NOWAIT, &addr);
499 		return (addr);
500 	}
501 #endif
502 
503 startover:
504 	/*
505 	 * Check to see if we've reached the hard limit.  If we have,
506 	 * and we can wait, then wait until an item has been returned to
507 	 * the pool.
508 	 */
509 #ifdef DIAGNOSTIC
510 	if (__predict_false(pp->pr_nout > pp->pr_hardlimit))
511 		panic("pool_do_get: %s: crossed hard limit", pp->pr_wchan);
512 #endif
513 	if (__predict_false(pp->pr_nout == pp->pr_hardlimit)) {
514 		if ((flags & PR_WAITOK) && !(flags & PR_LIMITFAIL)) {
515 			/*
516 			 * XXX: A warning isn't logged in this case.  Should
517 			 * it be?
518 			 */
519 			pp->pr_flags |= PR_WANTED;
520 			pool_sleep(pp);
521 			goto startover;
522 		}
523 
524 		/*
525 		 * Log a message that the hard limit has been hit.
526 		 */
527 		if (pp->pr_hardlimit_warning != NULL &&
528 		    ratecheck(&pp->pr_hardlimit_warning_last,
529 		    &pp->pr_hardlimit_ratecap))
530 			log(LOG_ERR, "%s\n", pp->pr_hardlimit_warning);
531 
532 		pp->pr_nfail++;
533 		return (NULL);
534 	}
535 
536 	/*
537 	 * The convention we use is that if `curpage' is not NULL, then
538 	 * it points at a non-empty bucket. In particular, `curpage'
539 	 * never points at a page header which has PR_PHINPAGE set and
540 	 * has no items in its bucket.
541 	 */
542 	if ((ph = pp->pr_curpage) == NULL) {
543 #ifdef DIAGNOSTIC
544 		if (pp->pr_nitems != 0) {
545 			printf("pool_do_get: %s: curpage NULL, nitems %u\n",
546 			    pp->pr_wchan, pp->pr_nitems);
547 			panic("pool_do_get: nitems inconsistent");
548 		}
549 #endif
550 
551 		/*
552 		 * Call the back-end page allocator for more memory.
553 		 */
554 		v = pool_allocator_alloc(pp, flags, &slowdown);
555 		if (__predict_true(v != NULL))
556 			ph = pool_alloc_item_header(pp, v, flags);
557 
558 		if (__predict_false(v == NULL || ph == NULL)) {
559 			if (v != NULL)
560 				pool_allocator_free(pp, v);
561 
562 			if ((flags & PR_WAITOK) == 0) {
563 				pp->pr_nfail++;
564 				return (NULL);
565 			}
566 
567 			/*
568 			 * Wait for items to be returned to this pool.
569 			 *
570 			 * XXX: maybe we should wake up once a second and
571 			 * try again?
572 			 */
573 			pp->pr_flags |= PR_WANTED;
574 			pool_sleep(pp);
575 			goto startover;
576 		}
577 
578 		/* We have more memory; add it to the pool */
579 		pool_prime_page(pp, v, ph);
580 		pp->pr_npagealloc++;
581 
582 		if (slowdown && (flags & PR_WAITOK)) {
583 			mtx_leave(&pp->pr_mtx);
584 			yield();
585 			mtx_enter(&pp->pr_mtx);
586 		}
587 
588 		/* Start the allocation process over. */
589 		goto startover;
590 	}
591 	if (__predict_false((v = pi = TAILQ_FIRST(&ph->ph_itemlist)) == NULL)) {
592 		panic("pool_do_get: %s: page empty", pp->pr_wchan);
593 	}
594 #ifdef DIAGNOSTIC
595 	if (__predict_false(pp->pr_nitems == 0)) {
596 		printf("pool_do_get: %s: items on itemlist, nitems %u\n",
597 		    pp->pr_wchan, pp->pr_nitems);
598 		panic("pool_do_get: nitems inconsistent");
599 	}
600 #endif
601 
602 #ifdef DIAGNOSTIC
603 	if (__predict_false(pi->pi_magic != PI_MAGIC))
604 		panic("pool_do_get(%s): free list modified: "
605 		    "page %p; item addr %p; offset 0x%x=0x%x",
606 		    pp->pr_wchan, ph->ph_page, pi, 0, pi->pi_magic);
607 #ifdef POOL_DEBUG
608 	for (ip = (int *)pi, i = sizeof(*pi) / sizeof(int);
609 	    i < pp->pr_size / sizeof(int); i++) {
610 		if (ip[i] != PI_MAGIC) {
611 			panic("pool_do_get(%s): free list modified: "
612 			    "page %p; item addr %p; offset 0x%x=0x%x",
613 			    pp->pr_wchan, ph->ph_page, pi,
614 			    i * sizeof(int), ip[i]);
615 		}
616 	}
617 #endif /* POOL_DEBUG */
618 #endif /* DIAGNOSTIC */
619 
620 	/*
621 	 * Remove from item list.
622 	 */
623 	TAILQ_REMOVE(&ph->ph_itemlist, pi, pi_list);
624 	pp->pr_nitems--;
625 	pp->pr_nout++;
626 	if (ph->ph_nmissing == 0) {
627 #ifdef DIAGNOSTIC
628 		if (__predict_false(pp->pr_nidle == 0))
629 			panic("pool_do_get: nidle inconsistent");
630 #endif
631 		pp->pr_nidle--;
632 
633 		/*
634 		 * This page was previously empty.  Move it to the list of
635 		 * partially-full pages.  This page is already curpage.
636 		 */
637 		LIST_REMOVE(ph, ph_pagelist);
638 		LIST_INSERT_HEAD(&pp->pr_partpages, ph, ph_pagelist);
639 	}
640 	ph->ph_nmissing++;
641 	if (TAILQ_EMPTY(&ph->ph_itemlist)) {
642 #ifdef DIAGNOSTIC
643 		if (__predict_false(ph->ph_nmissing != pp->pr_itemsperpage)) {
644 			panic("pool_do_get: %s: nmissing inconsistent",
645 			    pp->pr_wchan);
646 		}
647 #endif
648 		/*
649 		 * This page is now full.  Move it to the full list
650 		 * and select a new current page.
651 		 */
652 		LIST_REMOVE(ph, ph_pagelist);
653 		LIST_INSERT_HEAD(&pp->pr_fullpages, ph, ph_pagelist);
654 		pool_update_curpage(pp);
655 	}
656 
657 	/*
658 	 * If we have a low water mark and we are now below that low
659 	 * water mark, add more items to the pool.
660 	 */
661 	if (POOL_NEEDS_CATCHUP(pp) && pool_catchup(pp) != 0) {
662 		/*
663 		 * XXX: Should we log a warning?  Should we set up a timeout
664 		 * to try again in a second or so?  The latter could break
665 		 * a caller's assumptions about interrupt protection, etc.
666 		 */
667 	}
668 	return (v);
669 }
670 
671 /*
672  * Return resource to the pool; must be called at appropriate spl level
673  */
674 void
675 pool_put(struct pool *pp, void *v)
676 {
677 	if (pp->pr_dtor)
678 		pp->pr_dtor(pp->pr_arg, v);
679 	mtx_enter(&pp->pr_mtx);
680 	pool_do_put(pp, v);
681 	mtx_leave(&pp->pr_mtx);
682 	pp->pr_nput++;
683 }
684 
685 /*
686  * Internal version of pool_put().
687  */
688 void
689 pool_do_put(struct pool *pp, void *v)
690 {
691 	struct pool_item *pi = v;
692 	struct pool_item_header *ph;
693 #if defined(DIAGNOSTIC) && defined(POOL_DEBUG)
694 	int i, *ip;
695 #endif
696 
697 	if (v == NULL)
698 		panic("pool_put of NULL");
699 
700 #ifdef MALLOC_DEBUG
701 	if (pp->pr_roflags & PR_DEBUG) {
702 		debug_free(v, M_DEBUG);
703 		return;
704 	}
705 #endif
706 
707 #ifdef DIAGNOSTIC
708 	if (pp->pr_ipl != -1)
709 		splassert(pp->pr_ipl);
710 
711 	if (__predict_false(pp->pr_nout == 0)) {
712 		printf("pool %s: putting with none out\n",
713 		    pp->pr_wchan);
714 		panic("pool_do_put");
715 	}
716 #endif
717 
718 	if (__predict_false((ph = pr_find_pagehead(pp, v)) == NULL)) {
719 		panic("pool_do_put: %s: page header missing", pp->pr_wchan);
720 	}
721 
722 	/*
723 	 * Return to item list.
724 	 */
725 #ifdef DIAGNOSTIC
726 	pi->pi_magic = PI_MAGIC;
727 #ifdef POOL_DEBUG
728 	for (ip = (int *)pi, i = sizeof(*pi)/sizeof(int);
729 	    i < pp->pr_size / sizeof(int); i++)
730 		ip[i] = PI_MAGIC;
731 #endif /* POOL_DEBUG */
732 #endif /* DIAGNOSTIC */
733 
734 	TAILQ_INSERT_HEAD(&ph->ph_itemlist, pi, pi_list);
735 	ph->ph_nmissing--;
736 	pp->pr_nitems++;
737 	pp->pr_nout--;
738 
739 	/* Cancel "pool empty" condition if it exists */
740 	if (pp->pr_curpage == NULL)
741 		pp->pr_curpage = ph;
742 
743 	if (pp->pr_flags & PR_WANTED) {
744 		pp->pr_flags &= ~PR_WANTED;
745 		if (ph->ph_nmissing == 0)
746 			pp->pr_nidle++;
747 		wakeup(pp);
748 		return;
749 	}
750 
751 	/*
752 	 * If this page is now empty, do one of two things:
753 	 *
754 	 *	(1) If we have more pages than the page high water mark,
755 	 *	    free the page back to the system.
756 	 *
757 	 *	(2) Otherwise, move the page to the empty page list.
758 	 *
759 	 * Either way, select a new current page (so we use a partially-full
760 	 * page if one is available).
761 	 */
762 	if (ph->ph_nmissing == 0) {
763 		pp->pr_nidle++;
764 		if (pp->pr_nidle > pp->pr_maxpages) {
765 			pr_rmpage(pp, ph, NULL);
766 		} else {
767 			LIST_REMOVE(ph, ph_pagelist);
768 			LIST_INSERT_HEAD(&pp->pr_emptypages, ph, ph_pagelist);
769 		}
770 		pool_update_curpage(pp);
771 	}
772 
773 	/*
774 	 * If the page was previously completely full, move it to the
775 	 * partially-full list and make it the current page.  The next
776 	 * allocation will get the item from this page, instead of
777 	 * further fragmenting the pool.
778 	 */
779 	else if (ph->ph_nmissing == (pp->pr_itemsperpage - 1)) {
780 		LIST_REMOVE(ph, ph_pagelist);
781 		LIST_INSERT_HEAD(&pp->pr_partpages, ph, ph_pagelist);
782 		pp->pr_curpage = ph;
783 	}
784 }
785 
786 /*
787  * Add N items to the pool.
788  */
789 int
790 pool_prime(struct pool *pp, int n)
791 {
792 	struct pool_item_header *ph;
793 	caddr_t cp;
794 	int newpages;
795 	int slowdown;
796 
797 	mtx_enter(&pp->pr_mtx);
798 	newpages = roundup(n, pp->pr_itemsperpage) / pp->pr_itemsperpage;
799 
800 	while (newpages-- > 0) {
801 		cp = pool_allocator_alloc(pp, PR_NOWAIT, &slowdown);
802 		if (__predict_true(cp != NULL))
803 			ph = pool_alloc_item_header(pp, cp, PR_NOWAIT);
804 		if (__predict_false(cp == NULL || ph == NULL)) {
805 			if (cp != NULL)
806 				pool_allocator_free(pp, cp);
807 			break;
808 		}
809 
810 		pool_prime_page(pp, cp, ph);
811 		pp->pr_npagealloc++;
812 		pp->pr_minpages++;
813 	}
814 
815 	if (pp->pr_minpages >= pp->pr_maxpages)
816 		pp->pr_maxpages = pp->pr_minpages + 1;	/* XXX */
817 
818 	mtx_leave(&pp->pr_mtx);
819 	return (0);
820 }
821 
822 /*
823  * Add a page worth of items to the pool.
824  *
825  * Note, we must be called with the pool descriptor LOCKED.
826  */
827 void
828 pool_prime_page(struct pool *pp, caddr_t storage, struct pool_item_header *ph)
829 {
830 	struct pool_item *pi;
831 	caddr_t cp = storage;
832 	unsigned int align = pp->pr_align;
833 	unsigned int ioff = pp->pr_itemoffset;
834 	int n;
835 #if defined(DIAGNOSTIC) && defined(POOL_DEBUG)
836 	int i, *ip;
837 #endif
838 
839 	/*
840 	 * Insert page header.
841 	 */
842 	LIST_INSERT_HEAD(&pp->pr_emptypages, ph, ph_pagelist);
843 	TAILQ_INIT(&ph->ph_itemlist);
844 	ph->ph_page = storage;
845 	ph->ph_pagesize = pp->pr_alloc->pa_pagesz;
846 	ph->ph_nmissing = 0;
847 	if ((pp->pr_roflags & PR_PHINPAGE) == 0)
848 		RB_INSERT(phtree, &pp->pr_phtree, ph);
849 
850 	pp->pr_nidle++;
851 
852 	/*
853 	 * Color this page.
854 	 */
855 	cp = (caddr_t)(cp + pp->pr_curcolor);
856 	if ((pp->pr_curcolor += align) > pp->pr_maxcolor)
857 		pp->pr_curcolor = 0;
858 
859 	/*
860 	 * Adjust storage to apply aligment to `pr_itemoffset' in each item.
861 	 */
862 	if (ioff != 0)
863 		cp = (caddr_t)(cp + (align - ioff));
864 	ph->ph_colored = cp;
865 
866 	/*
867 	 * Insert remaining chunks on the bucket list.
868 	 */
869 	n = pp->pr_itemsperpage;
870 	pp->pr_nitems += n;
871 
872 	while (n--) {
873 		pi = (struct pool_item *)cp;
874 
875 		KASSERT(((((vaddr_t)pi) + ioff) & (align - 1)) == 0);
876 
877 		/* Insert on page list */
878 		TAILQ_INSERT_TAIL(&ph->ph_itemlist, pi, pi_list);
879 
880 #ifdef DIAGNOSTIC
881 		pi->pi_magic = PI_MAGIC;
882 #ifdef POOL_DEBUG
883 		for (ip = (int *)pi, i = sizeof(*pi)/sizeof(int);
884 		    i < pp->pr_size / sizeof(int); i++)
885 			ip[i] = PI_MAGIC;
886 #endif /* POOL_DEBUG */
887 #endif /* DIAGNOSTIC */
888 		cp = (caddr_t)(cp + pp->pr_size);
889 	}
890 
891 	/*
892 	 * If the pool was depleted, point at the new page.
893 	 */
894 	if (pp->pr_curpage == NULL)
895 		pp->pr_curpage = ph;
896 
897 	if (++pp->pr_npages > pp->pr_hiwat)
898 		pp->pr_hiwat = pp->pr_npages;
899 }
900 
901 /*
902  * Used by pool_get() when nitems drops below the low water mark.  This
903  * is used to catch up pr_nitems with the low water mark.
904  *
905  * Note we never wait for memory here, we let the caller decide what to do.
906  */
907 int
908 pool_catchup(struct pool *pp)
909 {
910 	struct pool_item_header *ph;
911 	caddr_t cp;
912 	int error = 0;
913 	int slowdown;
914 
915 	while (POOL_NEEDS_CATCHUP(pp)) {
916 		/*
917 		 * Call the page back-end allocator for more memory.
918 		 */
919 		cp = pool_allocator_alloc(pp, PR_NOWAIT, &slowdown);
920 		if (__predict_true(cp != NULL))
921 			ph = pool_alloc_item_header(pp, cp, PR_NOWAIT);
922 		if (__predict_false(cp == NULL || ph == NULL)) {
923 			if (cp != NULL)
924 				pool_allocator_free(pp, cp);
925 			error = ENOMEM;
926 			break;
927 		}
928 		pool_prime_page(pp, cp, ph);
929 		pp->pr_npagealloc++;
930 	}
931 
932 	return (error);
933 }
934 
935 void
936 pool_update_curpage(struct pool *pp)
937 {
938 
939 	pp->pr_curpage = LIST_FIRST(&pp->pr_partpages);
940 	if (pp->pr_curpage == NULL) {
941 		pp->pr_curpage = LIST_FIRST(&pp->pr_emptypages);
942 	}
943 }
944 
945 void
946 pool_setlowat(struct pool *pp, int n)
947 {
948 
949 	pp->pr_minitems = n;
950 	pp->pr_minpages = (n == 0)
951 		? 0
952 		: roundup(n, pp->pr_itemsperpage) / pp->pr_itemsperpage;
953 
954 	mtx_enter(&pp->pr_mtx);
955 	/* Make sure we're caught up with the newly-set low water mark. */
956 	if (POOL_NEEDS_CATCHUP(pp) && pool_catchup(pp) != 0) {
957 		/*
958 		 * XXX: Should we log a warning?  Should we set up a timeout
959 		 * to try again in a second or so?  The latter could break
960 		 * a caller's assumptions about interrupt protection, etc.
961 		 */
962 	}
963 	mtx_leave(&pp->pr_mtx);
964 }
965 
966 void
967 pool_sethiwat(struct pool *pp, int n)
968 {
969 
970 	pp->pr_maxpages = (n == 0)
971 		? 0
972 		: roundup(n, pp->pr_itemsperpage) / pp->pr_itemsperpage;
973 }
974 
975 int
976 pool_sethardlimit(struct pool *pp, u_int n, const char *warnmsg, int ratecap)
977 {
978 	int error = 0;
979 
980 	if (n < pp->pr_nout) {
981 		error = EINVAL;
982 		goto done;
983 	}
984 
985 	pp->pr_hardlimit = n;
986 	pp->pr_hardlimit_warning = warnmsg;
987 	pp->pr_hardlimit_ratecap.tv_sec = ratecap;
988 	pp->pr_hardlimit_warning_last.tv_sec = 0;
989 	pp->pr_hardlimit_warning_last.tv_usec = 0;
990 
991 	/*
992 	 * In-line version of pool_sethiwat().
993 	 */
994 	pp->pr_maxpages = (n == 0 || n == UINT_MAX)
995 		? n
996 		: roundup(n, pp->pr_itemsperpage) / pp->pr_itemsperpage;
997 
998 done:
999 	return (error);
1000 }
1001 
1002 void
1003 pool_set_ctordtor(struct pool *pp, int (*ctor)(void *, void *, int),
1004     void (*dtor)(void *, void *), void *arg)
1005 {
1006 	pp->pr_ctor = ctor;
1007 	pp->pr_dtor = dtor;
1008 	pp->pr_arg = arg;
1009 }
1010 /*
1011  * Release all complete pages that have not been used recently.
1012  *
1013  * Returns non-zero if any pages have been reclaimed.
1014  */
1015 int
1016 pool_reclaim(struct pool *pp)
1017 {
1018 	struct pool_item_header *ph, *phnext;
1019 	struct pool_pagelist pq;
1020 
1021 	LIST_INIT(&pq);
1022 
1023 	mtx_enter(&pp->pr_mtx);
1024 	for (ph = LIST_FIRST(&pp->pr_emptypages); ph != NULL; ph = phnext) {
1025 		phnext = LIST_NEXT(ph, ph_pagelist);
1026 
1027 		/* Check our minimum page claim */
1028 		if (pp->pr_npages <= pp->pr_minpages)
1029 			break;
1030 
1031 		KASSERT(ph->ph_nmissing == 0);
1032 
1033 		/*
1034 		 * If freeing this page would put us below
1035 		 * the low water mark, stop now.
1036 		 */
1037 		if ((pp->pr_nitems - pp->pr_itemsperpage) <
1038 		    pp->pr_minitems)
1039 			break;
1040 
1041 		pr_rmpage(pp, ph, &pq);
1042 	}
1043 	mtx_leave(&pp->pr_mtx);
1044 
1045 	if (LIST_EMPTY(&pq))
1046 		return (0);
1047 	while ((ph = LIST_FIRST(&pq)) != NULL) {
1048 		LIST_REMOVE(ph, ph_pagelist);
1049 		pool_allocator_free(pp, ph->ph_page);
1050 		if (pp->pr_roflags & PR_PHINPAGE)
1051 			continue;
1052 		pool_put(&phpool, ph);
1053 	}
1054 
1055 	return (1);
1056 }
1057 
1058 #ifdef DDB
1059 #include <machine/db_machdep.h>
1060 #include <ddb/db_interface.h>
1061 #include <ddb/db_output.h>
1062 
1063 /*
1064  * Diagnostic helpers.
1065  */
1066 void
1067 pool_printit(struct pool *pp, const char *modif, int (*pr)(const char *, ...))
1068 {
1069 	pool_print1(pp, modif, pr);
1070 }
1071 
1072 void
1073 pool_print_pagelist(struct pool_pagelist *pl, int (*pr)(const char *, ...))
1074 {
1075 	struct pool_item_header *ph;
1076 #ifdef DIAGNOSTIC
1077 	struct pool_item *pi;
1078 #endif
1079 
1080 	LIST_FOREACH(ph, pl, ph_pagelist) {
1081 		(*pr)("\t\tpage %p, nmissing %d\n",
1082 		    ph->ph_page, ph->ph_nmissing);
1083 #ifdef DIAGNOSTIC
1084 		TAILQ_FOREACH(pi, &ph->ph_itemlist, pi_list) {
1085 			if (pi->pi_magic != PI_MAGIC) {
1086 				(*pr)("\t\t\titem %p, magic 0x%x\n",
1087 				    pi, pi->pi_magic);
1088 			}
1089 		}
1090 #endif
1091 	}
1092 }
1093 
1094 void
1095 pool_print1(struct pool *pp, const char *modif, int (*pr)(const char *, ...))
1096 {
1097 	struct pool_item_header *ph;
1098 	int print_pagelist = 0;
1099 	char c;
1100 
1101 	while ((c = *modif++) != '\0') {
1102 		if (c == 'p')
1103 			print_pagelist = 1;
1104 		modif++;
1105 	}
1106 
1107 	(*pr)("POOL %s: size %u, align %u, ioff %u, roflags 0x%08x\n",
1108 	    pp->pr_wchan, pp->pr_size, pp->pr_align, pp->pr_itemoffset,
1109 	    pp->pr_roflags);
1110 	(*pr)("\talloc %p\n", pp->pr_alloc);
1111 	(*pr)("\tminitems %u, minpages %u, maxpages %u, npages %u\n",
1112 	    pp->pr_minitems, pp->pr_minpages, pp->pr_maxpages, pp->pr_npages);
1113 	(*pr)("\titemsperpage %u, nitems %u, nout %u, hardlimit %u\n",
1114 	    pp->pr_itemsperpage, pp->pr_nitems, pp->pr_nout, pp->pr_hardlimit);
1115 
1116 	(*pr)("\n\tnget %lu, nfail %lu, nput %lu\n",
1117 	    pp->pr_nget, pp->pr_nfail, pp->pr_nput);
1118 	(*pr)("\tnpagealloc %lu, npagefree %lu, hiwat %u, nidle %lu\n",
1119 	    pp->pr_npagealloc, pp->pr_npagefree, pp->pr_hiwat, pp->pr_nidle);
1120 
1121 	if (print_pagelist == 0)
1122 		return;
1123 
1124 	if ((ph = LIST_FIRST(&pp->pr_emptypages)) != NULL)
1125 		(*pr)("\n\tempty page list:\n");
1126 	pool_print_pagelist(&pp->pr_emptypages, pr);
1127 	if ((ph = LIST_FIRST(&pp->pr_fullpages)) != NULL)
1128 		(*pr)("\n\tfull page list:\n");
1129 	pool_print_pagelist(&pp->pr_fullpages, pr);
1130 	if ((ph = LIST_FIRST(&pp->pr_partpages)) != NULL)
1131 		(*pr)("\n\tpartial-page list:\n");
1132 	pool_print_pagelist(&pp->pr_partpages, pr);
1133 
1134 	if (pp->pr_curpage == NULL)
1135 		(*pr)("\tno current page\n");
1136 	else
1137 		(*pr)("\tcurpage %p\n", pp->pr_curpage->ph_page);
1138 }
1139 
1140 void
1141 db_show_all_pools(db_expr_t expr, int haddr, db_expr_t count, char *modif)
1142 {
1143 	struct pool *pp;
1144 	char maxp[16];
1145 	int ovflw;
1146 	char mode;
1147 
1148 	mode = modif[0];
1149 	if (mode != '\0' && mode != 'a') {
1150 		db_printf("usage: show all pools [/a]\n");
1151 		return;
1152 	}
1153 
1154 	if (mode == '\0')
1155 		db_printf("%-10s%4s%9s%5s%9s%6s%6s%6s%6s%6s%6s%5s\n",
1156 		    "Name",
1157 		    "Size",
1158 		    "Requests",
1159 		    "Fail",
1160 		    "Releases",
1161 		    "Pgreq",
1162 		    "Pgrel",
1163 		    "Npage",
1164 		    "Hiwat",
1165 		    "Minpg",
1166 		    "Maxpg",
1167 		    "Idle");
1168 	else
1169 		db_printf("%-10s %18s %18s\n",
1170 		    "Name", "Address", "Allocator");
1171 
1172 	TAILQ_FOREACH(pp, &pool_head, pr_poollist) {
1173 		if (mode == 'a') {
1174 			db_printf("%-10s %18p %18p\n", pp->pr_wchan, pp,
1175 			    pp->pr_alloc);
1176 			continue;
1177 		}
1178 
1179 		if (!pp->pr_nget)
1180 			continue;
1181 
1182 		if (pp->pr_maxpages == UINT_MAX)
1183 			snprintf(maxp, sizeof maxp, "inf");
1184 		else
1185 			snprintf(maxp, sizeof maxp, "%u", pp->pr_maxpages);
1186 
1187 #define PRWORD(ovflw, fmt, width, fixed, val) do {	\
1188 	(ovflw) += db_printf((fmt),			\
1189 	    (width) - (fixed) - (ovflw) > 0 ?		\
1190 	    (width) - (fixed) - (ovflw) : 0,		\
1191 	    (val)) - (width);				\
1192 	if ((ovflw) < 0)				\
1193 		(ovflw) = 0;				\
1194 } while (/* CONSTCOND */0)
1195 
1196 		ovflw = 0;
1197 		PRWORD(ovflw, "%-*s", 10, 0, pp->pr_wchan);
1198 		PRWORD(ovflw, " %*u", 4, 1, pp->pr_size);
1199 		PRWORD(ovflw, " %*lu", 9, 1, pp->pr_nget);
1200 		PRWORD(ovflw, " %*lu", 5, 1, pp->pr_nfail);
1201 		PRWORD(ovflw, " %*lu", 9, 1, pp->pr_nput);
1202 		PRWORD(ovflw, " %*lu", 6, 1, pp->pr_npagealloc);
1203 		PRWORD(ovflw, " %*lu", 6, 1, pp->pr_npagefree);
1204 		PRWORD(ovflw, " %*d", 6, 1, pp->pr_npages);
1205 		PRWORD(ovflw, " %*d", 6, 1, pp->pr_hiwat);
1206 		PRWORD(ovflw, " %*d", 6, 1, pp->pr_minpages);
1207 		PRWORD(ovflw, " %*s", 6, 1, maxp);
1208 		PRWORD(ovflw, " %*lu\n", 5, 1, pp->pr_nidle);
1209 
1210 		pool_chk(pp, pp->pr_wchan);
1211 	}
1212 }
1213 
1214 int
1215 pool_chk_page(struct pool *pp, const char *label, struct pool_item_header *ph)
1216 {
1217 	struct pool_item *pi;
1218 	caddr_t page;
1219 	int n;
1220 #if defined(DIAGNOSTIC) && defined(POOL_DEBUG)
1221 	int i, *ip;
1222 #endif
1223 
1224 	page = (caddr_t)((u_long)ph & pp->pr_alloc->pa_pagemask);
1225 	if (page != ph->ph_page &&
1226 	    (pp->pr_roflags & PR_PHINPAGE) != 0) {
1227 		if (label != NULL)
1228 			printf("%s: ", label);
1229 		printf("pool(%p:%s): page inconsistency: page %p; "
1230 		    "at page head addr %p (p %p)\n",
1231 		    pp, pp->pr_wchan, ph->ph_page, ph, page);
1232 		return 1;
1233 	}
1234 
1235 	for (pi = TAILQ_FIRST(&ph->ph_itemlist), n = 0;
1236 	     pi != NULL;
1237 	     pi = TAILQ_NEXT(pi,pi_list), n++) {
1238 
1239 #ifdef DIAGNOSTIC
1240 		if (pi->pi_magic != PI_MAGIC) {
1241 			if (label != NULL)
1242 				printf("%s: ", label);
1243 			printf("pool(%s): free list modified: "
1244 			    "page %p; item ordinal %d; addr %p "
1245 			    "(p %p); offset 0x%x=0x%x\n",
1246 			    pp->pr_wchan, ph->ph_page, n, pi, page,
1247 			    0, pi->pi_magic);
1248 		}
1249 #ifdef POOL_DEBUG
1250 		for (ip = (int *)pi, i = sizeof(*pi) / sizeof(int);
1251 		    i < pp->pr_size / sizeof(int); i++) {
1252 			if (ip[i] != PI_MAGIC) {
1253 				printf("pool(%s): free list modified: "
1254 				    "page %p; item ordinal %d; addr %p "
1255 				    "(p %p); offset 0x%x=0x%x\n",
1256 				    pp->pr_wchan, ph->ph_page, n, pi,
1257 				    page, i * sizeof(int), ip[i]);
1258 			}
1259 		}
1260 
1261 #endif /* POOL_DEBUG */
1262 #endif /* DIAGNOSTIC */
1263 		page =
1264 		    (caddr_t)((u_long)pi & pp->pr_alloc->pa_pagemask);
1265 		if (page == ph->ph_page)
1266 			continue;
1267 
1268 		if (label != NULL)
1269 			printf("%s: ", label);
1270 		printf("pool(%p:%s): page inconsistency: page %p;"
1271 		    " item ordinal %d; addr %p (p %p)\n", pp,
1272 		    pp->pr_wchan, ph->ph_page, n, pi, page);
1273 		return 1;
1274 	}
1275 	return 0;
1276 }
1277 
1278 int
1279 pool_chk(struct pool *pp, const char *label)
1280 {
1281 	struct pool_item_header *ph;
1282 	int r = 0;
1283 
1284 	LIST_FOREACH(ph, &pp->pr_emptypages, ph_pagelist)
1285 		r += pool_chk_page(pp, label, ph);
1286 	LIST_FOREACH(ph, &pp->pr_fullpages, ph_pagelist)
1287 		r += pool_chk_page(pp, label, ph);
1288 	LIST_FOREACH(ph, &pp->pr_partpages, ph_pagelist)
1289 		r += pool_chk_page(pp, label, ph);
1290 
1291 	return (r);
1292 }
1293 
1294 void
1295 pool_walk(struct pool *pp, int full, int (*pr)(const char *, ...),
1296     void (*func)(void *, int, int (*)(const char *, ...)))
1297 {
1298 	struct pool_item_header *ph;
1299 	struct pool_item *pi;
1300 	caddr_t cp;
1301 	int n;
1302 
1303 	LIST_FOREACH(ph, &pp->pr_fullpages, ph_pagelist) {
1304 		cp = ph->ph_colored;
1305 		n = ph->ph_nmissing;
1306 
1307 		while (n--) {
1308 			func(cp, full, pr);
1309 			cp += pp->pr_size;
1310 		}
1311 	}
1312 
1313 	LIST_FOREACH(ph, &pp->pr_partpages, ph_pagelist) {
1314 		cp = ph->ph_colored;
1315 		n = ph->ph_nmissing;
1316 
1317 		do {
1318 			TAILQ_FOREACH(pi, &ph->ph_itemlist, pi_list) {
1319 				if (cp == (caddr_t)pi)
1320 					break;
1321 			}
1322 			if (cp != (caddr_t)pi) {
1323 				func(cp, full, pr);
1324 				n--;
1325 			}
1326 
1327 			cp += pp->pr_size;
1328 		} while (n > 0);
1329 	}
1330 }
1331 #endif
1332 
1333 /*
1334  * We have three different sysctls.
1335  * kern.pool.npools - the number of pools.
1336  * kern.pool.pool.<pool#> - the pool struct for the pool#.
1337  * kern.pool.name.<pool#> - the name for pool#.
1338  */
1339 int
1340 sysctl_dopool(int *name, u_int namelen, char *where, size_t *sizep)
1341 {
1342 	struct pool *pp, *foundpool = NULL;
1343 	size_t buflen = where != NULL ? *sizep : 0;
1344 	int npools = 0, s;
1345 	unsigned int lookfor;
1346 	size_t len;
1347 
1348 	switch (*name) {
1349 	case KERN_POOL_NPOOLS:
1350 		if (namelen != 1 || buflen != sizeof(int))
1351 			return (EINVAL);
1352 		lookfor = 0;
1353 		break;
1354 	case KERN_POOL_NAME:
1355 		if (namelen != 2 || buflen < 1)
1356 			return (EINVAL);
1357 		lookfor = name[1];
1358 		break;
1359 	case KERN_POOL_POOL:
1360 		if (namelen != 2 || buflen != sizeof(struct pool))
1361 			return (EINVAL);
1362 		lookfor = name[1];
1363 		break;
1364 	default:
1365 		return (EINVAL);
1366 	}
1367 
1368 	s = splvm();
1369 
1370 	TAILQ_FOREACH(pp, &pool_head, pr_poollist) {
1371 		npools++;
1372 		if (lookfor == pp->pr_serial) {
1373 			foundpool = pp;
1374 			break;
1375 		}
1376 	}
1377 
1378 	splx(s);
1379 
1380 	if (*name != KERN_POOL_NPOOLS && foundpool == NULL)
1381 		return (ENOENT);
1382 
1383 	switch (*name) {
1384 	case KERN_POOL_NPOOLS:
1385 		return copyout(&npools, where, buflen);
1386 	case KERN_POOL_NAME:
1387 		len = strlen(foundpool->pr_wchan) + 1;
1388 		if (*sizep < len)
1389 			return (ENOMEM);
1390 		*sizep = len;
1391 		return copyout(foundpool->pr_wchan, where, len);
1392 	case KERN_POOL_POOL:
1393 		return copyout(foundpool, where, buflen);
1394 	}
1395 	/* NOTREACHED */
1396 	return (0); /* XXX - Stupid gcc */
1397 }
1398 
1399 /*
1400  * Pool backend allocators.
1401  *
1402  * Each pool has a backend allocator that handles allocation, deallocation
1403  */
1404 void	*pool_page_alloc(struct pool *, int, int *);
1405 void	pool_page_free(struct pool *, void *);
1406 
1407 /*
1408  * safe for interrupts, name preserved for compat this is the default
1409  * allocator
1410  */
1411 struct pool_allocator pool_allocator_nointr = {
1412 	pool_page_alloc, pool_page_free, 0,
1413 };
1414 
1415 /*
1416  * XXX - we have at least three different resources for the same allocation
1417  *  and each resource can be depleted. First we have the ready elements in
1418  *  the pool. Then we have the resource (typically a vm_map) for this
1419  *  allocator, then we have physical memory. Waiting for any of these can
1420  *  be unnecessary when any other is freed, but the kernel doesn't support
1421  *  sleeping on multiple addresses, so we have to fake. The caller sleeps on
1422  *  the pool (so that we can be awakened when an item is returned to the pool),
1423  *  but we set PA_WANT on the allocator. When a page is returned to
1424  *  the allocator and PA_WANT is set pool_allocator_free will wakeup all
1425  *  sleeping pools belonging to this allocator. (XXX - thundering herd).
1426  *  We also wake up the allocator in case someone without a pool (malloc)
1427  *  is sleeping waiting for this allocator.
1428  */
1429 
1430 void *
1431 pool_allocator_alloc(struct pool *pp, int flags, int *slowdown)
1432 {
1433 	boolean_t waitok = (flags & PR_WAITOK) ? TRUE : FALSE;
1434 	void *v;
1435 
1436 	if (waitok)
1437 		mtx_leave(&pp->pr_mtx);
1438 	v = pp->pr_alloc->pa_alloc(pp, flags, slowdown);
1439 	if (waitok)
1440 		mtx_enter(&pp->pr_mtx);
1441 
1442 	return (v);
1443 }
1444 
1445 void
1446 pool_allocator_free(struct pool *pp, void *v)
1447 {
1448 	struct pool_allocator *pa = pp->pr_alloc;
1449 
1450 	(*pa->pa_free)(pp, v);
1451 }
1452 
1453 void *
1454 pool_page_alloc(struct pool *pp, int flags, int *slowdown)
1455 {
1456 	boolean_t waitok = (flags & PR_WAITOK) ? TRUE : FALSE;
1457 
1458 	return (uvm_km_getpage(waitok, slowdown));
1459 }
1460 
1461 void
1462 pool_page_free(struct pool *pp, void *v)
1463 {
1464 
1465 	uvm_km_putpage(v);
1466 }
1467 
1468 void *
1469 pool_large_alloc(struct pool *pp, int flags, int *slowdown)
1470 {
1471 	int kfl = (flags & PR_WAITOK) ? 0 : UVM_KMF_NOWAIT;
1472 	vaddr_t va;
1473 	int s;
1474 
1475 	s = splvm();
1476 	va = uvm_km_kmemalloc(kmem_map, NULL, pp->pr_alloc->pa_pagesz, kfl);
1477 	splx(s);
1478 
1479 	return ((void *)va);
1480 }
1481 
1482 void
1483 pool_large_free(struct pool *pp, void *v)
1484 {
1485 	int s;
1486 
1487 	s = splvm();
1488 	uvm_km_free(kmem_map, (vaddr_t)v, pp->pr_alloc->pa_pagesz);
1489 	splx(s);
1490 }
1491 
1492 void *
1493 pool_large_alloc_ni(struct pool *pp, int flags, int *slowdown)
1494 {
1495 	int kfl = (flags & PR_WAITOK) ? 0 : UVM_KMF_NOWAIT;
1496 
1497 	return ((void *)uvm_km_kmemalloc(kernel_map, uvm.kernel_object,
1498 	    pp->pr_alloc->pa_pagesz, kfl));
1499 }
1500 
1501 void
1502 pool_large_free_ni(struct pool *pp, void *v)
1503 {
1504 	uvm_km_free(kernel_map, (vaddr_t)v, pp->pr_alloc->pa_pagesz);
1505 }
1506