1 /*	$OpenBSD: subr_pool.c,v 1.45 2004/07/29 09:18:17 mickey 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  * 3. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *	This product includes software developed by the NetBSD
23  *	Foundation, Inc. and its contributors.
24  * 4. Neither the name of The NetBSD Foundation nor the names of its
25  *    contributors may be used to endorse or promote products derived
26  *    from this software without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
29  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
30  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
31  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
32  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
34  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
35  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
36  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38  * POSSIBILITY OF SUCH DAMAGE.
39  */
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/proc.h>
44 #include <sys/errno.h>
45 #include <sys/kernel.h>
46 #include <sys/malloc.h>
47 #include <sys/lock.h>
48 #include <sys/pool.h>
49 #include <sys/syslog.h>
50 #include <sys/sysctl.h>
51 
52 #include <uvm/uvm.h>
53 
54 /*
55  * XXX - for now.
56  */
57 #define SIMPLELOCK_INITIALIZER { SLOCK_UNLOCKED }
58 #ifdef LOCKDEBUG
59 #define simple_lock_freecheck(a, s) do { /* nothing */ } while (0)
60 #define simple_lock_only_held(lkp, str) do { /* nothing */ } while (0)
61 #endif
62 
63 /*
64  * Pool resource management utility.
65  *
66  * Memory is allocated in pages which are split into pieces according to
67  * the pool item size. Each page is kept on one of three lists in the
68  * pool structure: `pr_emptypages', `pr_fullpages' and `pr_partpages',
69  * for empty, full and partially-full pages respectively. The individual
70  * pool items are on a linked list headed by `ph_itemlist' in each page
71  * header. The memory for building the page list is either taken from
72  * the allocated pages themselves (for small pool items) or taken from
73  * an internal pool of page headers (`phpool').
74  */
75 
76 /* List of all pools */
77 TAILQ_HEAD(,pool) pool_head = TAILQ_HEAD_INITIALIZER(pool_head);
78 
79 /* Private pool for page header structures */
80 static struct pool phpool;
81 
82 /* # of seconds to retain page after last use */
83 int pool_inactive_time = 10;
84 
85 /* Next candidate for drainage (see pool_drain()) */
86 static struct pool	*drainpp;
87 
88 /* This spin lock protects both pool_head and drainpp. */
89 struct simplelock pool_head_slock = SIMPLELOCK_INITIALIZER;
90 
91 struct pool_item_header {
92 	/* Page headers */
93 	LIST_ENTRY(pool_item_header)
94 				ph_pagelist;	/* pool page list */
95 	TAILQ_HEAD(,pool_item)	ph_itemlist;	/* chunk list for this page */
96 	SPLAY_ENTRY(pool_item_header)
97 				ph_node;	/* Off-page page headers */
98 	int			ph_nmissing;	/* # of chunks in use */
99 	caddr_t			ph_page;	/* this page's address */
100 	struct timeval		ph_time;	/* last referenced */
101 };
102 
103 struct pool_item {
104 #ifdef DIAGNOSTIC
105 	int pi_magic;
106 #endif
107 #define	PI_MAGIC 0xdeafbeef
108 	/* Other entries use only this list entry */
109 	TAILQ_ENTRY(pool_item)	pi_list;
110 };
111 
112 #define	POOL_NEEDS_CATCHUP(pp)						\
113 	((pp)->pr_nitems < (pp)->pr_minitems)
114 
115 /*
116  * Every pool get a unique serial number assigned to it. If this counter
117  * wraps, we're screwed, but we shouldn't create so many pools anyway.
118  */
119 unsigned int pool_serial;
120 
121 /*
122  * Pool cache management.
123  *
124  * Pool caches provide a way for constructed objects to be cached by the
125  * pool subsystem.  This can lead to performance improvements by avoiding
126  * needless object construction/destruction; it is deferred until absolutely
127  * necessary.
128  *
129  * Caches are grouped into cache groups.  Each cache group references
130  * up to 16 constructed objects.  When a cache allocates an object
131  * from the pool, it calls the object's constructor and places it into
132  * a cache group.  When a cache group frees an object back to the pool,
133  * it first calls the object's destructor.  This allows the object to
134  * persist in constructed form while freed to the cache.
135  *
136  * Multiple caches may exist for each pool.  This allows a single
137  * object type to have multiple constructed forms.  The pool references
138  * each cache, so that when a pool is drained by the pagedaemon, it can
139  * drain each individual cache as well.  Each time a cache is drained,
140  * the most idle cache group is freed to the pool in its entirety.
141  *
142  * Pool caches are layed on top of pools.  By layering them, we can avoid
143  * the complexity of cache management for pools which would not benefit
144  * from it.
145  */
146 
147 /* The cache group pool. */
148 static struct pool pcgpool;
149 
150 /* The pool cache group. */
151 #define	PCG_NOBJECTS		16
152 struct pool_cache_group {
153 	TAILQ_ENTRY(pool_cache_group)
154 		pcg_list;	/* link in the pool cache's group list */
155 	u_int	pcg_avail;	/* # available objects */
156 				/* pointers to the objects */
157 	void	*pcg_objects[PCG_NOBJECTS];
158 };
159 
160 void	pool_cache_reclaim(struct pool_cache *);
161 void	pool_cache_do_invalidate(struct pool_cache *, int,
162     void (*)(struct pool *, void *));
163 
164 int	pool_catchup(struct pool *);
165 void	pool_prime_page(struct pool *, caddr_t, struct pool_item_header *);
166 void	pool_update_curpage(struct pool *);
167 void	pool_do_put(struct pool *, void *);
168 void	pr_rmpage(struct pool *, struct pool_item_header *,
169     struct pool_pagelist *);
170 int	pool_chk_page(struct pool *, const char *, struct pool_item_header *);
171 
172 void	*pool_allocator_alloc(struct pool *, int);
173 void	pool_allocator_free(struct pool *, void *);
174 
175 #ifdef DDB
176 void pool_print_pagelist(struct pool_pagelist *, int (*)(const char *, ...));
177 void pool_print1(struct pool *, const char *, int (*)(const char *, ...));
178 #endif
179 
180 
181 /*
182  * Pool log entry. An array of these is allocated in pool_init().
183  */
184 struct pool_log {
185 	const char	*pl_file;
186 	long		pl_line;
187 	int		pl_action;
188 #define	PRLOG_GET	1
189 #define	PRLOG_PUT	2
190 	void		*pl_addr;
191 };
192 
193 /* Number of entries in pool log buffers */
194 #ifndef POOL_LOGSIZE
195 #define	POOL_LOGSIZE	10
196 #endif
197 
198 int pool_logsize = POOL_LOGSIZE;
199 
200 #ifdef POOL_DIAGNOSTIC
201 static __inline void
pr_log(struct pool * pp,void * v,int action,const char * file,long line)202 pr_log(struct pool *pp, void *v, int action, const char *file, long line)
203 {
204 	int n = pp->pr_curlogentry;
205 	struct pool_log *pl;
206 
207 	if ((pp->pr_roflags & PR_LOGGING) == 0)
208 		return;
209 
210 	/*
211 	 * Fill in the current entry. Wrap around and overwrite
212 	 * the oldest entry if necessary.
213 	 */
214 	pl = &pp->pr_log[n];
215 	pl->pl_file = file;
216 	pl->pl_line = line;
217 	pl->pl_action = action;
218 	pl->pl_addr = v;
219 	if (++n >= pp->pr_logsize)
220 		n = 0;
221 	pp->pr_curlogentry = n;
222 }
223 
224 static void
pr_printlog(struct pool * pp,struct pool_item * pi,int (* pr)(const char *,...))225 pr_printlog(struct pool *pp, struct pool_item *pi,
226     int (*pr)(const char *, ...))
227 {
228 	int i = pp->pr_logsize;
229 	int n = pp->pr_curlogentry;
230 
231 	if ((pp->pr_roflags & PR_LOGGING) == 0)
232 		return;
233 
234 	/*
235 	 * Print all entries in this pool's log.
236 	 */
237 	while (i-- > 0) {
238 		struct pool_log *pl = &pp->pr_log[n];
239 		if (pl->pl_action != 0) {
240 			if (pi == NULL || pi == pl->pl_addr) {
241 				(*pr)("\tlog entry %d:\n", i);
242 				(*pr)("\t\taction = %s, addr = %p\n",
243 				    pl->pl_action == PRLOG_GET ? "get" : "put",
244 				    pl->pl_addr);
245 				(*pr)("\t\tfile: %s at line %lu\n",
246 				    pl->pl_file, pl->pl_line);
247 			}
248 		}
249 		if (++n >= pp->pr_logsize)
250 			n = 0;
251 	}
252 }
253 
254 static __inline void
pr_enter(struct pool * pp,const char * file,long line)255 pr_enter(struct pool *pp, const char *file, long line)
256 {
257 
258 	if (__predict_false(pp->pr_entered_file != NULL)) {
259 		printf("pool %s: reentrancy at file %s line %ld\n",
260 		    pp->pr_wchan, file, line);
261 		printf("         previous entry at file %s line %ld\n",
262 		    pp->pr_entered_file, pp->pr_entered_line);
263 		panic("pr_enter");
264 	}
265 
266 	pp->pr_entered_file = file;
267 	pp->pr_entered_line = line;
268 }
269 
270 static __inline void
pr_leave(struct pool * pp)271 pr_leave(struct pool *pp)
272 {
273 
274 	if (__predict_false(pp->pr_entered_file == NULL)) {
275 		printf("pool %s not entered?\n", pp->pr_wchan);
276 		panic("pr_leave");
277 	}
278 
279 	pp->pr_entered_file = NULL;
280 	pp->pr_entered_line = 0;
281 }
282 
283 static __inline void
pr_enter_check(struct pool * pp,int (* pr)(const char *,...))284 pr_enter_check(struct pool *pp, int (*pr)(const char *, ...))
285 {
286 
287 	if (pp->pr_entered_file != NULL)
288 		(*pr)("\n\tcurrently entered from file %s line %ld\n",
289 		    pp->pr_entered_file, pp->pr_entered_line);
290 }
291 #else
292 #define	pr_log(pp, v, action, file, line)
293 #define	pr_printlog(pp, pi, pr)
294 #define	pr_enter(pp, file, line)
295 #define	pr_leave(pp)
296 #define	pr_enter_check(pp, pr)
297 #endif /* POOL_DIAGNOSTIC */
298 
299 static __inline int
phtree_compare(struct pool_item_header * a,struct pool_item_header * b)300 phtree_compare(struct pool_item_header *a, struct pool_item_header *b)
301 {
302 	if (a->ph_page < b->ph_page)
303 		return (-1);
304 	else if (a->ph_page > b->ph_page)
305 		return (1);
306 	else
307 		return (0);
308 }
309 
310 SPLAY_PROTOTYPE(phtree, pool_item_header, ph_node, phtree_compare);
311 SPLAY_GENERATE(phtree, pool_item_header, ph_node, phtree_compare);
312 
313 /*
314  * Return the pool page header based on page address.
315  */
316 static __inline struct pool_item_header *
pr_find_pagehead(struct pool * pp,caddr_t page)317 pr_find_pagehead(struct pool *pp, caddr_t page)
318 {
319 	struct pool_item_header *ph, tmp;
320 
321 	if ((pp->pr_roflags & PR_PHINPAGE) != 0)
322 		return ((struct pool_item_header *)(page + pp->pr_phoffset));
323 
324 	tmp.ph_page = page;
325 	ph = SPLAY_FIND(phtree, &pp->pr_phtree, &tmp);
326 	return ph;
327 }
328 
329 /*
330  * Remove a page from the pool.
331  */
332 void
pr_rmpage(struct pool * pp,struct pool_item_header * ph,struct pool_pagelist * pq)333 pr_rmpage(struct pool *pp, struct pool_item_header *ph,
334      struct pool_pagelist *pq)
335 {
336 	int s;
337 
338 	/*
339 	 * If the page was idle, decrement the idle page count.
340 	 */
341 	if (ph->ph_nmissing == 0) {
342 #ifdef DIAGNOSTIC
343 		if (pp->pr_nidle == 0)
344 			panic("pr_rmpage: nidle inconsistent");
345 		if (pp->pr_nitems < pp->pr_itemsperpage)
346 			panic("pr_rmpage: nitems inconsistent");
347 #endif
348 		pp->pr_nidle--;
349 	}
350 
351 	pp->pr_nitems -= pp->pr_itemsperpage;
352 
353 	/*
354 	 * Unlink a page from the pool and release it (or queue it for release).
355 	 */
356 	LIST_REMOVE(ph, ph_pagelist);
357 	if (pq) {
358 		LIST_INSERT_HEAD(pq, ph, ph_pagelist);
359 	} else {
360 		pool_allocator_free(pp, ph->ph_page);
361 		if ((pp->pr_roflags & PR_PHINPAGE) == 0) {
362 			SPLAY_REMOVE(phtree, &pp->pr_phtree, ph);
363 			s = splhigh();
364 			pool_put(&phpool, ph);
365 			splx(s);
366 		}
367 	}
368 	pp->pr_npages--;
369 	pp->pr_npagefree++;
370 
371 	pool_update_curpage(pp);
372 }
373 
374 /*
375  * Initialize the given pool resource structure.
376  *
377  * We export this routine to allow other kernel parts to declare
378  * static pools that must be initialized before malloc() is available.
379  */
380 void
pool_init(struct pool * pp,size_t size,u_int align,u_int ioff,int flags,const char * wchan,struct pool_allocator * palloc)381 pool_init(struct pool *pp, size_t size, u_int align, u_int ioff, int flags,
382     const char *wchan, struct pool_allocator *palloc)
383 {
384 	int off, slack;
385 
386 #ifdef POOL_DIAGNOSTIC
387 	/*
388 	 * Always log if POOL_DIAGNOSTIC is defined.
389 	 */
390 	if (pool_logsize != 0)
391 		flags |= PR_LOGGING;
392 #endif
393 
394 #ifdef MALLOC_DEBUG
395 	if ((flags & PR_DEBUG) && (ioff != 0 || align != 0))
396 		flags &= ~PR_DEBUG;
397 #endif
398 	/*
399 	 * Check arguments and construct default values.
400 	 */
401 	if (palloc == NULL)
402 		palloc = &pool_allocator_nointr;
403 	if ((palloc->pa_flags & PA_INITIALIZED) == 0) {
404 		if (palloc->pa_pagesz == 0)
405 			palloc->pa_pagesz = PAGE_SIZE;
406 
407 		TAILQ_INIT(&palloc->pa_list);
408 
409 		simple_lock_init(&palloc->pa_slock);
410 		palloc->pa_pagemask = ~(palloc->pa_pagesz - 1);
411 		palloc->pa_pageshift = ffs(palloc->pa_pagesz) - 1;
412 		palloc->pa_flags |= PA_INITIALIZED;
413 	}
414 
415 	if (align == 0)
416 		align = ALIGN(1);
417 
418 	if (size < sizeof(struct pool_item))
419 		size = sizeof(struct pool_item);
420 
421 	size = roundup(size, align);
422 #ifdef DIAGNOSTIC
423 	if (size > palloc->pa_pagesz)
424 		panic("pool_init: pool item size (%lu) too large",
425 		      (u_long)size);
426 #endif
427 
428 	/*
429 	 * Initialize the pool structure.
430 	 */
431 	LIST_INIT(&pp->pr_emptypages);
432 	LIST_INIT(&pp->pr_fullpages);
433 	LIST_INIT(&pp->pr_partpages);
434 	TAILQ_INIT(&pp->pr_cachelist);
435 	pp->pr_curpage = NULL;
436 	pp->pr_npages = 0;
437 	pp->pr_minitems = 0;
438 	pp->pr_minpages = 0;
439 	pp->pr_maxpages = 8;
440 	pp->pr_roflags = flags;
441 	pp->pr_flags = 0;
442 	pp->pr_size = size;
443 	pp->pr_align = align;
444 	pp->pr_wchan = wchan;
445 	pp->pr_alloc = palloc;
446 	pp->pr_nitems = 0;
447 	pp->pr_nout = 0;
448 	pp->pr_hardlimit = UINT_MAX;
449 	pp->pr_hardlimit_warning = NULL;
450 	pp->pr_hardlimit_ratecap.tv_sec = 0;
451 	pp->pr_hardlimit_ratecap.tv_usec = 0;
452 	pp->pr_hardlimit_warning_last.tv_sec = 0;
453 	pp->pr_hardlimit_warning_last.tv_usec = 0;
454 	pp->pr_drain_hook = NULL;
455 	pp->pr_drain_hook_arg = NULL;
456 	pp->pr_serial = ++pool_serial;
457 	if (pool_serial == 0)
458 		panic("pool_init: too much uptime");
459 
460 	/*
461 	 * Decide whether to put the page header off page to avoid
462 	 * wasting too large a part of the page. Off-page page headers
463 	 * go on a hash table, so we can match a returned item
464 	 * with its header based on the page address.
465 	 * We use 1/16 of the page size as the threshold (XXX: tune)
466 	 */
467 	if (pp->pr_size < palloc->pa_pagesz/16) {
468 		/* Use the end of the page for the page header */
469 		pp->pr_roflags |= PR_PHINPAGE;
470 		pp->pr_phoffset = off = palloc->pa_pagesz -
471 		    ALIGN(sizeof(struct pool_item_header));
472 	} else {
473 		/* The page header will be taken from our page header pool */
474 		pp->pr_phoffset = 0;
475 		off = palloc->pa_pagesz;
476 		SPLAY_INIT(&pp->pr_phtree);
477 	}
478 
479 	/*
480 	 * Alignment is to take place at `ioff' within the item. This means
481 	 * we must reserve up to `align - 1' bytes on the page to allow
482 	 * appropriate positioning of each item.
483 	 *
484 	 * Silently enforce `0 <= ioff < align'.
485 	 */
486 	pp->pr_itemoffset = ioff = ioff % align;
487 	pp->pr_itemsperpage = (off - ((align - ioff) % align)) / pp->pr_size;
488 	KASSERT(pp->pr_itemsperpage != 0);
489 
490 	/*
491 	 * Use the slack between the chunks and the page header
492 	 * for "cache coloring".
493 	 */
494 	slack = off - pp->pr_itemsperpage * pp->pr_size;
495 	pp->pr_maxcolor = (slack / align) * align;
496 	pp->pr_curcolor = 0;
497 
498 	pp->pr_nget = 0;
499 	pp->pr_nfail = 0;
500 	pp->pr_nput = 0;
501 	pp->pr_npagealloc = 0;
502 	pp->pr_npagefree = 0;
503 	pp->pr_hiwat = 0;
504 	pp->pr_nidle = 0;
505 
506 #ifdef POOL_DIAGNOSTIC
507 	if (flags & PR_LOGGING) {
508 		if (kmem_map == NULL ||
509 		    (pp->pr_log = malloc(pool_logsize * sizeof(struct pool_log),
510 		     M_TEMP, M_NOWAIT)) == NULL)
511 			pp->pr_roflags &= ~PR_LOGGING;
512 		pp->pr_curlogentry = 0;
513 		pp->pr_logsize = pool_logsize;
514 	}
515 #endif
516 
517 	pp->pr_entered_file = NULL;
518 	pp->pr_entered_line = 0;
519 
520 	simple_lock_init(&pp->pr_slock);
521 
522 	/*
523 	 * Initialize private page header pool and cache magazine pool if we
524 	 * haven't done so yet.
525 	 * XXX LOCKING.
526 	 */
527 	if (phpool.pr_size == 0) {
528 		pool_init(&phpool, sizeof(struct pool_item_header), 0, 0,
529 		    0, "phpool", NULL);
530 		pool_init(&pcgpool, sizeof(struct pool_cache_group), 0, 0,
531 		    0, "pcgpool", NULL);
532 	}
533 
534 	/* Insert this into the list of all pools. */
535 	simple_lock(&pool_head_slock);
536 	TAILQ_INSERT_TAIL(&pool_head, pp, pr_poollist);
537 	simple_unlock(&pool_head_slock);
538 
539 	/* Insert into the list of pools using this allocator. */
540 	simple_lock(&palloc->pa_slock);
541 	TAILQ_INSERT_TAIL(&palloc->pa_list, pp, pr_alloc_list);
542 	simple_unlock(&palloc->pa_slock);
543 }
544 
545 /*
546  * De-commision a pool resource.
547  */
548 void
pool_destroy(struct pool * pp)549 pool_destroy(struct pool *pp)
550 {
551 	struct pool_item_header *ph;
552 	struct pool_cache *pc;
553 
554 	/* Locking order: pool_allocator -> pool */
555 	simple_lock(&pp->pr_alloc->pa_slock);
556 	TAILQ_REMOVE(&pp->pr_alloc->pa_list, pp, pr_alloc_list);
557 	simple_unlock(&pp->pr_alloc->pa_slock);
558 
559 	/* Destroy all caches for this pool. */
560 	while ((pc = TAILQ_FIRST(&pp->pr_cachelist)) != NULL)
561 		pool_cache_destroy(pc);
562 
563 #ifdef DIAGNOSTIC
564 	if (pp->pr_nout != 0) {
565 		pr_printlog(pp, NULL, printf);
566 		panic("pool_destroy: pool busy: still out: %u",
567 		    pp->pr_nout);
568 	}
569 #endif
570 
571 	/* Remove all pages */
572 	while ((ph = LIST_FIRST(&pp->pr_emptypages)) != NULL)
573 		pr_rmpage(pp, ph, NULL);
574 	KASSERT(LIST_EMPTY(&pp->pr_fullpages));
575 	KASSERT(LIST_EMPTY(&pp->pr_partpages));
576 
577 	/* Remove from global pool list */
578 	simple_lock(&pool_head_slock);
579 	TAILQ_REMOVE(&pool_head, pp, pr_poollist);
580 	if (drainpp == pp) {
581 		drainpp = NULL;
582 	}
583 	simple_unlock(&pool_head_slock);
584 
585 #ifdef POOL_DIAGNOSTIC
586 	if ((pp->pr_roflags & PR_LOGGING) != 0)
587 		free(pp->pr_log, M_TEMP);
588 #endif
589 }
590 
591 void
pool_set_drain_hook(struct pool * pp,void (* fn)(void *,int),void * arg)592 pool_set_drain_hook(struct pool *pp, void (*fn)(void *, int), void *arg)
593 {
594 	/* XXX no locking -- must be used just after pool_init() */
595 #ifdef DIAGNOSTIC
596 	if (pp->pr_drain_hook != NULL)
597 		panic("pool_set_drain_hook(%s): already set", pp->pr_wchan);
598 #endif
599 	pp->pr_drain_hook = fn;
600 	pp->pr_drain_hook_arg = arg;
601 }
602 
603 static struct pool_item_header *
pool_alloc_item_header(struct pool * pp,caddr_t storage,int flags)604 pool_alloc_item_header(struct pool *pp, caddr_t storage, int flags)
605 {
606 	struct pool_item_header *ph;
607 	int s;
608 
609 	LOCK_ASSERT(simple_lock_held(&pp->pr_slock) == 0);
610 
611 	if ((pp->pr_roflags & PR_PHINPAGE) != 0)
612 		ph = (struct pool_item_header *) (storage + pp->pr_phoffset);
613 	else {
614 		s = splhigh();
615 		ph = pool_get(&phpool, flags);
616 		splx(s);
617 	}
618 
619 	return (ph);
620 }
621 
622 /*
623  * Grab an item from the pool; must be called at appropriate spl level
624  */
625 void *
626 #ifdef POOL_DIAGNOSTIC
_pool_get(struct pool * pp,int flags,const char * file,long line)627 _pool_get(struct pool *pp, int flags, const char *file, long line)
628 #else
629 pool_get(struct pool *pp, int flags)
630 #endif
631 {
632 	struct pool_item *pi;
633 	struct pool_item_header *ph;
634 	void *v;
635 
636 #ifdef DIAGNOSTIC
637 	if ((flags & PR_WAITOK) != 0)
638 		splassert(IPL_NONE);
639 	if (__predict_false(curproc == NULL && /* doing_shutdown == 0 && XXX*/
640 			    (flags & PR_WAITOK) != 0))
641 		panic("pool_get: %s:must have NOWAIT", pp->pr_wchan);
642 
643 #ifdef LOCKDEBUG
644 	if (flags & PR_WAITOK)
645 		simple_lock_only_held(NULL, "pool_get(PR_WAITOK)");
646 #endif
647 #endif /* DIAGNOSTIC */
648 
649 #ifdef MALLOC_DEBUG
650 	if (pp->pr_roflags & PR_DEBUG) {
651 		void *addr;
652 
653 		addr = NULL;
654 		debug_malloc(pp->pr_size, M_DEBUG,
655 		    (flags & PR_WAITOK) ? M_WAITOK : M_NOWAIT, &addr);
656 		return (addr);
657 	}
658 #endif
659 
660 	simple_lock(&pp->pr_slock);
661 	pr_enter(pp, file, line);
662 
663  startover:
664 	/*
665 	 * Check to see if we've reached the hard limit.  If we have,
666 	 * and we can wait, then wait until an item has been returned to
667 	 * the pool.
668 	 */
669 #ifdef DIAGNOSTIC
670 	if (__predict_false(pp->pr_nout > pp->pr_hardlimit)) {
671 		pr_leave(pp);
672 		simple_unlock(&pp->pr_slock);
673 		panic("pool_get: %s: crossed hard limit", pp->pr_wchan);
674 	}
675 #endif
676 	if (__predict_false(pp->pr_nout == pp->pr_hardlimit)) {
677 		if (pp->pr_drain_hook != NULL) {
678 			/*
679 			 * Since the drain hook is going to free things
680 			 * back to the pool, unlock, call hook, re-lock
681 			 * and check hardlimit condition again.
682 			 */
683 			pr_leave(pp);
684 			simple_unlock(&pp->pr_slock);
685 			(*pp->pr_drain_hook)(pp->pr_drain_hook_arg, flags);
686 			simple_lock(&pp->pr_slock);
687 			pr_enter(pp, file, line);
688 			if (pp->pr_nout < pp->pr_hardlimit)
689 				goto startover;
690 		}
691 
692 		if ((flags & PR_WAITOK) && !(flags & PR_LIMITFAIL)) {
693 			/*
694 			 * XXX: A warning isn't logged in this case.  Should
695 			 * it be?
696 			 */
697 			pp->pr_flags |= PR_WANTED;
698 			pr_leave(pp);
699 			ltsleep(pp, PSWP, pp->pr_wchan, 0, &pp->pr_slock);
700 			pr_enter(pp, file, line);
701 			goto startover;
702 		}
703 
704 		/*
705 		 * Log a message that the hard limit has been hit.
706 		 */
707 		if (pp->pr_hardlimit_warning != NULL &&
708 		    ratecheck(&pp->pr_hardlimit_warning_last,
709 			      &pp->pr_hardlimit_ratecap))
710 			log(LOG_ERR, "%s\n", pp->pr_hardlimit_warning);
711 
712 		pp->pr_nfail++;
713 
714 		pr_leave(pp);
715 		simple_unlock(&pp->pr_slock);
716 		return (NULL);
717 	}
718 
719 	/*
720 	 * The convention we use is that if `curpage' is not NULL, then
721 	 * it points at a non-empty bucket. In particular, `curpage'
722 	 * never points at a page header which has PR_PHINPAGE set and
723 	 * has no items in its bucket.
724 	 */
725 	if ((ph = pp->pr_curpage) == NULL) {
726 #ifdef DIAGNOSTIC
727 		if (pp->pr_nitems != 0) {
728 			simple_unlock(&pp->pr_slock);
729 			printf("pool_get: %s: curpage NULL, nitems %u\n",
730 			    pp->pr_wchan, pp->pr_nitems);
731 			panic("pool_get: nitems inconsistent");
732 		}
733 #endif
734 
735 		/*
736 		 * Call the back-end page allocator for more memory.
737 		 * Release the pool lock, as the back-end page allocator
738 		 * may block.
739 		 */
740 		pr_leave(pp);
741 		simple_unlock(&pp->pr_slock);
742 		v = pool_allocator_alloc(pp, flags);
743 		if (__predict_true(v != NULL))
744 			ph = pool_alloc_item_header(pp, v, flags);
745 		simple_lock(&pp->pr_slock);
746 		pr_enter(pp, file, line);
747 
748 		if (__predict_false(v == NULL || ph == NULL)) {
749 			if (v != NULL)
750 				pool_allocator_free(pp, v);
751 
752 			/*
753 			 * We were unable to allocate a page or item
754 			 * header, but we released the lock during
755 			 * allocation, so perhaps items were freed
756 			 * back to the pool.  Check for this case.
757 			 */
758 			if (pp->pr_curpage != NULL)
759 				goto startover;
760 
761 			if ((flags & PR_WAITOK) == 0) {
762 				pp->pr_nfail++;
763 				pr_leave(pp);
764 				simple_unlock(&pp->pr_slock);
765 				return (NULL);
766 			}
767 
768 			/*
769 			 * Wait for items to be returned to this pool.
770 			 *
771 			 * XXX: maybe we should wake up once a second and
772 			 * try again?
773 			 */
774 			pp->pr_flags |= PR_WANTED;
775 			/* PA_WANTED is already set on the allocator. */
776 			pr_leave(pp);
777 			ltsleep(pp, PSWP, pp->pr_wchan, 0, &pp->pr_slock);
778 			pr_enter(pp, file, line);
779 			goto startover;
780 		}
781 
782 		/* We have more memory; add it to the pool */
783 		pool_prime_page(pp, v, ph);
784 		pp->pr_npagealloc++;
785 
786 		/* Start the allocation process over. */
787 		goto startover;
788 	}
789 	if (__predict_false((v = pi = TAILQ_FIRST(&ph->ph_itemlist)) == NULL)) {
790 		pr_leave(pp);
791 		simple_unlock(&pp->pr_slock);
792 		panic("pool_get: %s: page empty", pp->pr_wchan);
793 	}
794 #ifdef DIAGNOSTIC
795 	if (__predict_false(pp->pr_nitems == 0)) {
796 		pr_leave(pp);
797 		simple_unlock(&pp->pr_slock);
798 		printf("pool_get: %s: items on itemlist, nitems %u\n",
799 		    pp->pr_wchan, pp->pr_nitems);
800 		panic("pool_get: nitems inconsistent");
801 	}
802 #endif
803 
804 #ifdef POOL_DIAGNOSTIC
805 	pr_log(pp, v, PRLOG_GET, file, line);
806 #endif
807 
808 #ifdef DIAGNOSTIC
809 	if (__predict_false(pi->pi_magic != PI_MAGIC)) {
810 		pr_printlog(pp, pi, printf);
811 		panic("pool_get(%s): free list modified: magic=%x; page %p;"
812 		       " item addr %p",
813 			pp->pr_wchan, pi->pi_magic, ph->ph_page, pi);
814 	}
815 #endif
816 
817 	/*
818 	 * Remove from item list.
819 	 */
820 	TAILQ_REMOVE(&ph->ph_itemlist, pi, pi_list);
821 	pp->pr_nitems--;
822 	pp->pr_nout++;
823 	if (ph->ph_nmissing == 0) {
824 #ifdef DIAGNOSTIC
825 		if (__predict_false(pp->pr_nidle == 0))
826 			panic("pool_get: nidle inconsistent");
827 #endif
828 		pp->pr_nidle--;
829 
830 		/*
831 		 * This page was previously empty.  Move it to the list of
832 		 * partially-full pages.  This page is already curpage.
833 		 */
834 		LIST_REMOVE(ph, ph_pagelist);
835 		LIST_INSERT_HEAD(&pp->pr_partpages, ph, ph_pagelist);
836 	}
837 	ph->ph_nmissing++;
838 	if (TAILQ_EMPTY(&ph->ph_itemlist)) {
839 #ifdef DIAGNOSTIC
840 		if (__predict_false(ph->ph_nmissing != pp->pr_itemsperpage)) {
841 			pr_leave(pp);
842 			simple_unlock(&pp->pr_slock);
843 			panic("pool_get: %s: nmissing inconsistent",
844 			    pp->pr_wchan);
845 		}
846 #endif
847 		/*
848 		 * This page is now full.  Move it to the full list
849 		 * and select a new current page.
850 		 */
851 		LIST_REMOVE(ph, ph_pagelist);
852 		LIST_INSERT_HEAD(&pp->pr_fullpages, ph, ph_pagelist);
853 		pool_update_curpage(pp);
854 	}
855 
856 	pp->pr_nget++;
857 
858 	/*
859 	 * If we have a low water mark and we are now below that low
860 	 * water mark, add more items to the pool.
861 	 */
862 	if (POOL_NEEDS_CATCHUP(pp) && pool_catchup(pp) != 0) {
863 		/*
864 		 * XXX: Should we log a warning?  Should we set up a timeout
865 		 * to try again in a second or so?  The latter could break
866 		 * a caller's assumptions about interrupt protection, etc.
867 		 */
868 	}
869 
870 	pr_leave(pp);
871 	simple_unlock(&pp->pr_slock);
872 	return (v);
873 }
874 
875 /*
876  * Internal version of pool_put().  Pool is already locked/entered.
877  */
878 void
pool_do_put(struct pool * pp,void * v)879 pool_do_put(struct pool *pp, void *v)
880 {
881 	struct pool_item *pi = v;
882 	struct pool_item_header *ph;
883 	caddr_t page;
884 	int s;
885 
886 #ifdef MALLOC_DEBUG
887 	if (pp->pr_roflags & PR_DEBUG) {
888 		debug_free(v, M_DEBUG);
889 		return;
890 	}
891 #endif
892 
893 	LOCK_ASSERT(simple_lock_held(&pp->pr_slock));
894 
895 	page = (caddr_t)((vaddr_t)v & pp->pr_alloc->pa_pagemask);
896 
897 #ifdef DIAGNOSTIC
898 	if (__predict_false(pp->pr_nout == 0)) {
899 		printf("pool %s: putting with none out\n",
900 		    pp->pr_wchan);
901 		panic("pool_put");
902 	}
903 #endif
904 
905 	if (__predict_false((ph = pr_find_pagehead(pp, page)) == NULL)) {
906 		pr_printlog(pp, NULL, printf);
907 		panic("pool_put: %s: page header missing", pp->pr_wchan);
908 	}
909 
910 #ifdef LOCKDEBUG
911 	/*
912 	 * Check if we're freeing a locked simple lock.
913 	 */
914 	simple_lock_freecheck((caddr_t)pi, ((caddr_t)pi) + pp->pr_size);
915 #endif
916 
917 	/*
918 	 * Return to item list.
919 	 */
920 #ifdef DIAGNOSTIC
921 	pi->pi_magic = PI_MAGIC;
922 #endif
923 #ifdef DEBUG
924 	{
925 		int i, *ip = v;
926 
927 		for (i = 0; i < pp->pr_size / sizeof(int); i++) {
928 			*ip++ = PI_MAGIC;
929 		}
930 	}
931 #endif
932 
933 	TAILQ_INSERT_HEAD(&ph->ph_itemlist, pi, pi_list);
934 	ph->ph_nmissing--;
935 	pp->pr_nput++;
936 	pp->pr_nitems++;
937 	pp->pr_nout--;
938 
939 	/* Cancel "pool empty" condition if it exists */
940 	if (pp->pr_curpage == NULL)
941 		pp->pr_curpage = ph;
942 
943 	if (pp->pr_flags & PR_WANTED) {
944 		pp->pr_flags &= ~PR_WANTED;
945 		if (ph->ph_nmissing == 0)
946 			pp->pr_nidle++;
947 		wakeup((caddr_t)pp);
948 		return;
949 	}
950 
951 	/*
952 	 * If this page is now empty, do one of two things:
953 	 *
954 	 *	(1) If we have more pages than the page high water mark,
955 	 *	    free the page back to the system.
956 	 *
957 	 *	(2) Otherwise, move the page to the empty page list.
958 	 *
959 	 * Either way, select a new current page (so we use a partially-full
960 	 * page if one is available).
961 	 */
962 	if (ph->ph_nmissing == 0) {
963 		pp->pr_nidle++;
964 		if (pp->pr_nidle > pp->pr_maxpages ||
965 		    (pp->pr_alloc->pa_flags & PA_WANT) != 0) {
966 			pr_rmpage(pp, ph, NULL);
967 		} else {
968 			LIST_REMOVE(ph, ph_pagelist);
969 			LIST_INSERT_HEAD(&pp->pr_emptypages, ph, ph_pagelist);
970 
971 			/*
972 			 * Update the timestamp on the page.  A page must
973 			 * be idle for some period of time before it can
974 			 * be reclaimed by the pagedaemon.  This minimizes
975 			 * ping-pong'ing for memory.
976 			 */
977 			s = splclock();
978 			ph->ph_time = mono_time;
979 			splx(s);
980 		}
981 		pool_update_curpage(pp);
982 	}
983 
984 	/*
985 	 * If the page was previously completely full, move it to the
986 	 * partially-full list and make it the current page.  The next
987 	 * allocation will get the item from this page, instead of
988 	 * further fragmenting the pool.
989 	 */
990 	else if (ph->ph_nmissing == (pp->pr_itemsperpage - 1)) {
991 		LIST_REMOVE(ph, ph_pagelist);
992 		LIST_INSERT_HEAD(&pp->pr_partpages, ph, ph_pagelist);
993 		pp->pr_curpage = ph;
994 	}
995 }
996 
997 /*
998  * Return resource to the pool; must be called at appropriate spl level
999  */
1000 #ifdef POOL_DIAGNOSTIC
1001 void
_pool_put(struct pool * pp,void * v,const char * file,long line)1002 _pool_put(struct pool *pp, void *v, const char *file, long line)
1003 {
1004 
1005 	simple_lock(&pp->pr_slock);
1006 	pr_enter(pp, file, line);
1007 
1008 	pr_log(pp, v, PRLOG_PUT, file, line);
1009 
1010 	pool_do_put(pp, v);
1011 
1012 	pr_leave(pp);
1013 	simple_unlock(&pp->pr_slock);
1014 }
1015 #undef pool_put
1016 #endif /* POOL_DIAGNOSTIC */
1017 
1018 void
pool_put(struct pool * pp,void * v)1019 pool_put(struct pool *pp, void *v)
1020 {
1021 
1022 	simple_lock(&pp->pr_slock);
1023 
1024 	pool_do_put(pp, v);
1025 
1026 	simple_unlock(&pp->pr_slock);
1027 }
1028 
1029 #ifdef POOL_DIAGNOSTIC
1030 #define		pool_put(h, v)	_pool_put((h), (v), __FILE__, __LINE__)
1031 #endif
1032 
1033 /*
1034  * Add N items to the pool.
1035  */
1036 int
pool_prime(struct pool * pp,int n)1037 pool_prime(struct pool *pp, int n)
1038 {
1039 	struct pool_item_header *ph;
1040 	caddr_t cp;
1041 	int newpages;
1042 
1043 	simple_lock(&pp->pr_slock);
1044 
1045 	newpages = roundup(n, pp->pr_itemsperpage) / pp->pr_itemsperpage;
1046 
1047 	while (newpages-- > 0) {
1048 		simple_unlock(&pp->pr_slock);
1049 		cp = pool_allocator_alloc(pp, PR_NOWAIT);
1050 		if (__predict_true(cp != NULL))
1051 			ph = pool_alloc_item_header(pp, cp, PR_NOWAIT);
1052 		simple_lock(&pp->pr_slock);
1053 
1054 		if (__predict_false(cp == NULL || ph == NULL)) {
1055 			if (cp != NULL)
1056 				pool_allocator_free(pp, cp);
1057 			break;
1058 		}
1059 
1060 		pool_prime_page(pp, cp, ph);
1061 		pp->pr_npagealloc++;
1062 		pp->pr_minpages++;
1063 	}
1064 
1065 	if (pp->pr_minpages >= pp->pr_maxpages)
1066 		pp->pr_maxpages = pp->pr_minpages + 1;	/* XXX */
1067 
1068 	simple_unlock(&pp->pr_slock);
1069 	return (0);
1070 }
1071 
1072 /*
1073  * Add a page worth of items to the pool.
1074  *
1075  * Note, we must be called with the pool descriptor LOCKED.
1076  */
1077 void
pool_prime_page(struct pool * pp,caddr_t storage,struct pool_item_header * ph)1078 pool_prime_page(struct pool *pp, caddr_t storage, struct pool_item_header *ph)
1079 {
1080 	struct pool_item *pi;
1081 	caddr_t cp = storage;
1082 	unsigned int align = pp->pr_align;
1083 	unsigned int ioff = pp->pr_itemoffset;
1084 	int n;
1085 
1086 #ifdef DIAGNOSTIC
1087 	if (((u_long)cp & (pp->pr_alloc->pa_pagesz - 1)) != 0)
1088 		panic("pool_prime_page: %s: unaligned page", pp->pr_wchan);
1089 #endif
1090 
1091 	/*
1092 	 * Insert page header.
1093 	 */
1094 	LIST_INSERT_HEAD(&pp->pr_emptypages, ph, ph_pagelist);
1095 	TAILQ_INIT(&ph->ph_itemlist);
1096 	ph->ph_page = storage;
1097 	ph->ph_nmissing = 0;
1098 	memset(&ph->ph_time, 0, sizeof(ph->ph_time));
1099 	if ((pp->pr_roflags & PR_PHINPAGE) == 0)
1100 		SPLAY_INSERT(phtree, &pp->pr_phtree, ph);
1101 
1102 	pp->pr_nidle++;
1103 
1104 	/*
1105 	 * Color this page.
1106 	 */
1107 	cp = (caddr_t)(cp + pp->pr_curcolor);
1108 	if ((pp->pr_curcolor += align) > pp->pr_maxcolor)
1109 		pp->pr_curcolor = 0;
1110 
1111 	/*
1112 	 * Adjust storage to apply aligment to `pr_itemoffset' in each item.
1113 	 */
1114 	if (ioff != 0)
1115 		cp = (caddr_t)(cp + (align - ioff));
1116 
1117 	/*
1118 	 * Insert remaining chunks on the bucket list.
1119 	 */
1120 	n = pp->pr_itemsperpage;
1121 	pp->pr_nitems += n;
1122 
1123 	while (n--) {
1124 		pi = (struct pool_item *)cp;
1125 
1126 		KASSERT(((((vaddr_t)pi) + ioff) & (align - 1)) == 0);
1127 
1128 		/* Insert on page list */
1129 		TAILQ_INSERT_TAIL(&ph->ph_itemlist, pi, pi_list);
1130 #ifdef DIAGNOSTIC
1131 		pi->pi_magic = PI_MAGIC;
1132 #endif
1133 		cp = (caddr_t)(cp + pp->pr_size);
1134 	}
1135 
1136 	/*
1137 	 * If the pool was depleted, point at the new page.
1138 	 */
1139 	if (pp->pr_curpage == NULL)
1140 		pp->pr_curpage = ph;
1141 
1142 	if (++pp->pr_npages > pp->pr_hiwat)
1143 		pp->pr_hiwat = pp->pr_npages;
1144 }
1145 
1146 /*
1147  * Used by pool_get() when nitems drops below the low water mark.  This
1148  * is used to catch up pr_nitems with the low water mark.
1149  *
1150  * Note 1, we never wait for memory here, we let the caller decide what to do.
1151  *
1152  * Note 2, we must be called with the pool already locked, and we return
1153  * with it locked.
1154  */
1155 int
pool_catchup(struct pool * pp)1156 pool_catchup(struct pool *pp)
1157 {
1158 	struct pool_item_header *ph;
1159 	caddr_t cp;
1160 	int error = 0;
1161 
1162 	while (POOL_NEEDS_CATCHUP(pp)) {
1163 		/*
1164 		 * Call the page back-end allocator for more memory.
1165 		 *
1166 		 * XXX: We never wait, so should we bother unlocking
1167 		 * the pool descriptor?
1168 		 */
1169 		simple_unlock(&pp->pr_slock);
1170 		cp = pool_allocator_alloc(pp, PR_NOWAIT);
1171 		if (__predict_true(cp != NULL))
1172 			ph = pool_alloc_item_header(pp, cp, PR_NOWAIT);
1173 		simple_lock(&pp->pr_slock);
1174 		if (__predict_false(cp == NULL || ph == NULL)) {
1175 			if (cp != NULL)
1176 				pool_allocator_free(pp, cp);
1177 			error = ENOMEM;
1178 			break;
1179 		}
1180 		pool_prime_page(pp, cp, ph);
1181 		pp->pr_npagealloc++;
1182 	}
1183 
1184 	return (error);
1185 }
1186 
1187 void
pool_update_curpage(struct pool * pp)1188 pool_update_curpage(struct pool *pp)
1189 {
1190 
1191 	pp->pr_curpage = LIST_FIRST(&pp->pr_partpages);
1192 	if (pp->pr_curpage == NULL) {
1193 		pp->pr_curpage = LIST_FIRST(&pp->pr_emptypages);
1194 	}
1195 }
1196 
1197 void
pool_setlowat(struct pool * pp,int n)1198 pool_setlowat(struct pool *pp, int n)
1199 {
1200 
1201 	simple_lock(&pp->pr_slock);
1202 
1203 	pp->pr_minitems = n;
1204 	pp->pr_minpages = (n == 0)
1205 		? 0
1206 		: roundup(n, pp->pr_itemsperpage) / pp->pr_itemsperpage;
1207 
1208 	/* Make sure we're caught up with the newly-set low water mark. */
1209 	if (POOL_NEEDS_CATCHUP(pp) && pool_catchup(pp) != 0) {
1210 		/*
1211 		 * XXX: Should we log a warning?  Should we set up a timeout
1212 		 * to try again in a second or so?  The latter could break
1213 		 * a caller's assumptions about interrupt protection, etc.
1214 		 */
1215 	}
1216 
1217 	simple_unlock(&pp->pr_slock);
1218 }
1219 
1220 void
pool_sethiwat(struct pool * pp,int n)1221 pool_sethiwat(struct pool *pp, int n)
1222 {
1223 
1224 	simple_lock(&pp->pr_slock);
1225 
1226 	pp->pr_maxpages = (n == 0)
1227 		? 0
1228 		: roundup(n, pp->pr_itemsperpage) / pp->pr_itemsperpage;
1229 
1230 	simple_unlock(&pp->pr_slock);
1231 }
1232 
1233 int
pool_sethardlimit(struct pool * pp,unsigned n,const char * warnmess,int ratecap)1234 pool_sethardlimit(struct pool *pp, unsigned n, const char *warnmess, int ratecap)
1235 {
1236 	int error = 0;
1237 
1238 	simple_lock(&pp->pr_slock);
1239 
1240 	if (n < pp->pr_nout) {
1241 		error = EINVAL;
1242 		goto done;
1243 	}
1244 
1245 	pp->pr_hardlimit = n;
1246 	pp->pr_hardlimit_warning = warnmess;
1247 	pp->pr_hardlimit_ratecap.tv_sec = ratecap;
1248 	pp->pr_hardlimit_warning_last.tv_sec = 0;
1249 	pp->pr_hardlimit_warning_last.tv_usec = 0;
1250 
1251 	/*
1252 	 * In-line version of pool_sethiwat(), because we don't want to
1253 	 * release the lock.
1254 	 */
1255 	pp->pr_maxpages = (n == 0 || n == UINT_MAX)
1256 		? n
1257 		: roundup(n, pp->pr_itemsperpage) / pp->pr_itemsperpage;
1258 
1259  done:
1260 	simple_unlock(&pp->pr_slock);
1261 
1262 	return (error);
1263 }
1264 
1265 /*
1266  * Release all complete pages that have not been used recently.
1267  *
1268  * Returns non-zero if any pages have been reclaimed.
1269  */
1270 int
1271 #ifdef POOL_DIAGNOSTIC
_pool_reclaim(struct pool * pp,const char * file,long line)1272 _pool_reclaim(struct pool *pp, const char *file, long line)
1273 #else
1274 pool_reclaim(struct pool *pp)
1275 #endif
1276 {
1277 	struct pool_item_header *ph, *phnext;
1278 	struct pool_cache *pc;
1279 	struct timeval curtime;
1280 	struct pool_pagelist pq;
1281 	struct timeval diff;
1282 	int s;
1283 
1284 	if (pp->pr_drain_hook != NULL) {
1285 		/*
1286 		 * The drain hook must be called with the pool unlocked.
1287 		 */
1288 		(*pp->pr_drain_hook)(pp->pr_drain_hook_arg, PR_NOWAIT);
1289 	}
1290 
1291 	if (simple_lock_try(&pp->pr_slock) == 0)
1292 		return (0);
1293 	pr_enter(pp, file, line);
1294 
1295 	LIST_INIT(&pq);
1296 
1297 	/*
1298 	 * Reclaim items from the pool's caches.
1299 	 */
1300 	TAILQ_FOREACH(pc, &pp->pr_cachelist, pc_poollist)
1301 		pool_cache_reclaim(pc);
1302 
1303 	s = splclock();
1304 	curtime = mono_time;
1305 	splx(s);
1306 
1307 	for (ph = LIST_FIRST(&pp->pr_emptypages); ph != NULL; ph = phnext) {
1308 		phnext = LIST_NEXT(ph, ph_pagelist);
1309 
1310 		/* Check our minimum page claim */
1311 		if (pp->pr_npages <= pp->pr_minpages)
1312 			break;
1313 
1314 		KASSERT(ph->ph_nmissing == 0);
1315 		timersub(&curtime, &ph->ph_time, &diff);
1316 		if (diff.tv_sec < pool_inactive_time)
1317 			continue;
1318 
1319 		/*
1320 		 * If freeing this page would put us below
1321 		 * the low water mark, stop now.
1322 		 */
1323 		if ((pp->pr_nitems - pp->pr_itemsperpage) <
1324 		    pp->pr_minitems)
1325 			break;
1326 
1327 		pr_rmpage(pp, ph, &pq);
1328 	}
1329 
1330 	pr_leave(pp);
1331 	simple_unlock(&pp->pr_slock);
1332 	if (LIST_EMPTY(&pq))
1333 		return (0);
1334 	while ((ph = LIST_FIRST(&pq)) != NULL) {
1335 		LIST_REMOVE(ph, ph_pagelist);
1336 		pool_allocator_free(pp, ph->ph_page);
1337 		if (pp->pr_roflags & PR_PHINPAGE) {
1338 			continue;
1339 		}
1340 		SPLAY_REMOVE(phtree, &pp->pr_phtree, ph);
1341 		s = splhigh();
1342 		pool_put(&phpool, ph);
1343 		splx(s);
1344 	}
1345 
1346 	return (1);
1347 }
1348 
1349 
1350 /*
1351  * Drain pools, one at a time.
1352  *
1353  * Note, we must never be called from an interrupt context.
1354  */
1355 void
pool_drain(void * arg)1356 pool_drain(void *arg)
1357 {
1358 	struct pool *pp;
1359 	int s;
1360 
1361 	pp = NULL;
1362 	s = splvm();
1363 	simple_lock(&pool_head_slock);
1364 	if (drainpp == NULL) {
1365 		drainpp = TAILQ_FIRST(&pool_head);
1366 	}
1367 	if (drainpp) {
1368 		pp = drainpp;
1369 		drainpp = TAILQ_NEXT(pp, pr_poollist);
1370 	}
1371 	simple_unlock(&pool_head_slock);
1372 	pool_reclaim(pp);
1373 	splx(s);
1374 }
1375 
1376 #ifdef DDB
1377 /*
1378  * Diagnostic helpers.
1379  */
1380 void
pool_printit(struct pool * pp,const char * modif,int (* pr)(const char *,...))1381 pool_printit(struct pool *pp, const char *modif, int (*pr)(const char *, ...))
1382 {
1383 	int s;
1384 
1385 	s = splvm();
1386 	if (simple_lock_try(&pp->pr_slock) == 0) {
1387 		pr("pool %s is locked; try again later\n",
1388 		    pp->pr_wchan);
1389 		splx(s);
1390 		return;
1391 	}
1392 	pool_print1(pp, modif, pr);
1393 	simple_unlock(&pp->pr_slock);
1394 	splx(s);
1395 }
1396 
1397 void
pool_print_pagelist(struct pool_pagelist * pl,int (* pr)(const char *,...))1398 pool_print_pagelist(struct pool_pagelist *pl, int (*pr)(const char *, ...))
1399 {
1400 	struct pool_item_header *ph;
1401 #ifdef DIAGNOSTIC
1402 	struct pool_item *pi;
1403 #endif
1404 
1405 	LIST_FOREACH(ph, pl, ph_pagelist) {
1406 		(*pr)("\t\tpage %p, nmissing %d, time %lld,%lu\n",
1407 		    ph->ph_page, ph->ph_nmissing,
1408 		    (int64_t)ph->ph_time.tv_sec,
1409 		    (u_long)ph->ph_time.tv_usec);
1410 #ifdef DIAGNOSTIC
1411 		TAILQ_FOREACH(pi, &ph->ph_itemlist, pi_list) {
1412 			if (pi->pi_magic != PI_MAGIC) {
1413 				(*pr)("\t\t\titem %p, magic 0x%x\n",
1414 				    pi, pi->pi_magic);
1415 			}
1416 		}
1417 #endif
1418 	}
1419 }
1420 
1421 void
pool_print1(struct pool * pp,const char * modif,int (* pr)(const char *,...))1422 pool_print1(struct pool *pp, const char *modif, int (*pr)(const char *, ...))
1423 {
1424 	struct pool_item_header *ph;
1425 	struct pool_cache *pc;
1426 	struct pool_cache_group *pcg;
1427 	int i, print_log = 0, print_pagelist = 0, print_cache = 0;
1428 	char c;
1429 
1430 	while ((c = *modif++) != '\0') {
1431 		if (c == 'l')
1432 			print_log = 1;
1433 		if (c == 'p')
1434 			print_pagelist = 1;
1435 		if (c == 'c')
1436 			print_cache = 1;
1437 		modif++;
1438 	}
1439 
1440 	(*pr)("POOL %s: size %u, align %u, ioff %u, roflags 0x%08x\n",
1441 	    pp->pr_wchan, pp->pr_size, pp->pr_align, pp->pr_itemoffset,
1442 	    pp->pr_roflags);
1443 	(*pr)("\talloc %p\n", pp->pr_alloc);
1444 	(*pr)("\tminitems %u, minpages %u, maxpages %u, npages %u\n",
1445 	    pp->pr_minitems, pp->pr_minpages, pp->pr_maxpages, pp->pr_npages);
1446 	(*pr)("\titemsperpage %u, nitems %u, nout %u, hardlimit %u\n",
1447 	    pp->pr_itemsperpage, pp->pr_nitems, pp->pr_nout, pp->pr_hardlimit);
1448 
1449 	(*pr)("\n\tnget %lu, nfail %lu, nput %lu\n",
1450 	    pp->pr_nget, pp->pr_nfail, pp->pr_nput);
1451 	(*pr)("\tnpagealloc %lu, npagefree %lu, hiwat %u, nidle %lu\n",
1452 	    pp->pr_npagealloc, pp->pr_npagefree, pp->pr_hiwat, pp->pr_nidle);
1453 
1454 	if (print_pagelist == 0)
1455 		goto skip_pagelist;
1456 
1457 	if ((ph = LIST_FIRST(&pp->pr_emptypages)) != NULL)
1458 		(*pr)("\n\tempty page list:\n");
1459 	pool_print_pagelist(&pp->pr_emptypages, pr);
1460 	if ((ph = LIST_FIRST(&pp->pr_fullpages)) != NULL)
1461 		(*pr)("\n\tfull page list:\n");
1462 	pool_print_pagelist(&pp->pr_fullpages, pr);
1463 	if ((ph = LIST_FIRST(&pp->pr_partpages)) != NULL)
1464 		(*pr)("\n\tpartial-page list:\n");
1465 	pool_print_pagelist(&pp->pr_partpages, pr);
1466 
1467 	if (pp->pr_curpage == NULL)
1468 		(*pr)("\tno current page\n");
1469 	else
1470 		(*pr)("\tcurpage %p\n", pp->pr_curpage->ph_page);
1471 
1472 skip_pagelist:
1473 	if (print_log == 0)
1474 		goto skip_log;
1475 
1476 	(*pr)("\n");
1477 	if ((pp->pr_roflags & PR_LOGGING) == 0)
1478 		(*pr)("\tno log\n");
1479 	else
1480 		pr_printlog(pp, NULL, pr);
1481 
1482 skip_log:
1483 	if (print_cache == 0)
1484 		goto skip_cache;
1485 
1486 	TAILQ_FOREACH(pc, &pp->pr_cachelist, pc_poollist) {
1487 		(*pr)("\tcache %p: allocfrom %p freeto %p\n", pc,
1488 		    pc->pc_allocfrom, pc->pc_freeto);
1489 		(*pr)("\t    hits %lu misses %lu ngroups %lu nitems %lu\n",
1490 		    pc->pc_hits, pc->pc_misses, pc->pc_ngroups, pc->pc_nitems);
1491 		TAILQ_FOREACH(pcg, &pc->pc_grouplist, pcg_list) {
1492 			(*pr)("\t\tgroup %p: avail %d\n", pcg, pcg->pcg_avail);
1493 			for (i = 0; i < PCG_NOBJECTS; i++)
1494 				(*pr)("\t\t\t%p\n", pcg->pcg_objects[i]);
1495 		}
1496 	}
1497 
1498 skip_cache:
1499 	pr_enter_check(pp, pr);
1500 }
1501 
1502 int
pool_chk_page(struct pool * pp,const char * label,struct pool_item_header * ph)1503 pool_chk_page(struct pool *pp, const char *label, struct pool_item_header *ph)
1504 {
1505 	struct pool_item *pi;
1506 	caddr_t page;
1507 	int n;
1508 
1509 	page = (caddr_t)((u_long)ph & pp->pr_alloc->pa_pagemask);
1510 	if (page != ph->ph_page &&
1511 	    (pp->pr_roflags & PR_PHINPAGE) != 0) {
1512 		if (label != NULL)
1513 			printf("%s: ", label);
1514 		printf("pool(%p:%s): page inconsistency: page %p;"
1515 		       " at page head addr %p (p %p)\n", pp,
1516 			pp->pr_wchan, ph->ph_page,
1517 			ph, page);
1518 		return 1;
1519 	}
1520 
1521 	for (pi = TAILQ_FIRST(&ph->ph_itemlist), n = 0;
1522 	     pi != NULL;
1523 	     pi = TAILQ_NEXT(pi,pi_list), n++) {
1524 
1525 #ifdef DIAGNOSTIC
1526 		if (pi->pi_magic != PI_MAGIC) {
1527 			if (label != NULL)
1528 				printf("%s: ", label);
1529 			printf("pool(%s): free list modified: magic=%x;"
1530 			       " page %p; item ordinal %d;"
1531 			       " addr %p (p %p)\n",
1532 				pp->pr_wchan, pi->pi_magic, ph->ph_page,
1533 				n, pi, page);
1534 			panic("pool");
1535 		}
1536 #endif
1537 		page =
1538 		    (caddr_t)((u_long)pi & pp->pr_alloc->pa_pagemask);
1539 		if (page == ph->ph_page)
1540 			continue;
1541 
1542 		if (label != NULL)
1543 			printf("%s: ", label);
1544 		printf("pool(%p:%s): page inconsistency: page %p;"
1545 		       " item ordinal %d; addr %p (p %p)\n", pp,
1546 			pp->pr_wchan, ph->ph_page,
1547 			n, pi, page);
1548 		return 1;
1549 	}
1550 	return 0;
1551 }
1552 
1553 int
pool_chk(struct pool * pp,const char * label)1554 pool_chk(struct pool *pp, const char *label)
1555 {
1556 	struct pool_item_header *ph;
1557 	int r = 0;
1558 
1559 	simple_lock(&pp->pr_slock);
1560 	LIST_FOREACH(ph, &pp->pr_emptypages, ph_pagelist) {
1561 		r = pool_chk_page(pp, label, ph);
1562 		if (r) {
1563 			goto out;
1564 		}
1565 	}
1566 	LIST_FOREACH(ph, &pp->pr_fullpages, ph_pagelist) {
1567 		r = pool_chk_page(pp, label, ph);
1568 		if (r) {
1569 			goto out;
1570 		}
1571 	}
1572 	LIST_FOREACH(ph, &pp->pr_partpages, ph_pagelist) {
1573 		r = pool_chk_page(pp, label, ph);
1574 		if (r) {
1575 			goto out;
1576 		}
1577 	}
1578 
1579 out:
1580 	simple_unlock(&pp->pr_slock);
1581 	return (r);
1582 }
1583 #endif
1584 
1585 /*
1586  * pool_cache_init:
1587  *
1588  *	Initialize a pool cache.
1589  *
1590  *	NOTE: If the pool must be protected from interrupts, we expect
1591  *	to be called at the appropriate interrupt priority level.
1592  */
1593 void
pool_cache_init(struct pool_cache * pc,struct pool * pp,int (* ctor)(void *,void *,int),void (* dtor)(void *,void *),void * arg)1594 pool_cache_init(struct pool_cache *pc, struct pool *pp,
1595     int (*ctor)(void *, void *, int),
1596     void (*dtor)(void *, void *),
1597     void *arg)
1598 {
1599 
1600 	TAILQ_INIT(&pc->pc_grouplist);
1601 	simple_lock_init(&pc->pc_slock);
1602 
1603 	pc->pc_allocfrom = NULL;
1604 	pc->pc_freeto = NULL;
1605 	pc->pc_pool = pp;
1606 
1607 	pc->pc_ctor = ctor;
1608 	pc->pc_dtor = dtor;
1609 	pc->pc_arg  = arg;
1610 
1611 	pc->pc_hits   = 0;
1612 	pc->pc_misses = 0;
1613 
1614 	pc->pc_ngroups = 0;
1615 
1616 	pc->pc_nitems = 0;
1617 
1618 	simple_lock(&pp->pr_slock);
1619 	TAILQ_INSERT_TAIL(&pp->pr_cachelist, pc, pc_poollist);
1620 	simple_unlock(&pp->pr_slock);
1621 }
1622 
1623 /*
1624  * pool_cache_destroy:
1625  *
1626  *	Destroy a pool cache.
1627  */
1628 void
pool_cache_destroy(struct pool_cache * pc)1629 pool_cache_destroy(struct pool_cache *pc)
1630 {
1631 	struct pool *pp = pc->pc_pool;
1632 
1633 	/* First, invalidate the entire cache. */
1634 	pool_cache_invalidate(pc);
1635 
1636 	/* ...and remove it from the pool's cache list. */
1637 	simple_lock(&pp->pr_slock);
1638 	TAILQ_REMOVE(&pp->pr_cachelist, pc, pc_poollist);
1639 	simple_unlock(&pp->pr_slock);
1640 }
1641 
1642 static __inline void *
pcg_get(struct pool_cache_group * pcg)1643 pcg_get(struct pool_cache_group *pcg)
1644 {
1645 	void *object;
1646 	u_int idx;
1647 
1648 	KASSERT(pcg->pcg_avail <= PCG_NOBJECTS);
1649 	KASSERT(pcg->pcg_avail != 0);
1650 	idx = --pcg->pcg_avail;
1651 
1652 	KASSERT(pcg->pcg_objects[idx] != NULL);
1653 	object = pcg->pcg_objects[idx];
1654 	pcg->pcg_objects[idx] = NULL;
1655 
1656 	return (object);
1657 }
1658 
1659 static __inline void
pcg_put(struct pool_cache_group * pcg,void * object)1660 pcg_put(struct pool_cache_group *pcg, void *object)
1661 {
1662 	u_int idx;
1663 
1664 	KASSERT(pcg->pcg_avail < PCG_NOBJECTS);
1665 	idx = pcg->pcg_avail++;
1666 
1667 	KASSERT(pcg->pcg_objects[idx] == NULL);
1668 	pcg->pcg_objects[idx] = object;
1669 }
1670 
1671 /*
1672  * pool_cache_get:
1673  *
1674  *	Get an object from a pool cache.
1675  */
1676 void *
pool_cache_get(struct pool_cache * pc,int flags)1677 pool_cache_get(struct pool_cache *pc, int flags)
1678 {
1679 	struct pool_cache_group *pcg;
1680 	void *object;
1681 
1682 #ifdef LOCKDEBUG
1683 	if (flags & PR_WAITOK)
1684 		simple_lock_only_held(NULL, "pool_cache_get(PR_WAITOK)");
1685 #endif
1686 
1687 	simple_lock(&pc->pc_slock);
1688 
1689 	if ((pcg = pc->pc_allocfrom) == NULL) {
1690 		TAILQ_FOREACH(pcg, &pc->pc_grouplist, pcg_list) {
1691 			if (pcg->pcg_avail != 0) {
1692 				pc->pc_allocfrom = pcg;
1693 				goto have_group;
1694 			}
1695 		}
1696 
1697 		/*
1698 		 * No groups with any available objects.  Allocate
1699 		 * a new object, construct it, and return it to
1700 		 * the caller.  We will allocate a group, if necessary,
1701 		 * when the object is freed back to the cache.
1702 		 */
1703 		pc->pc_misses++;
1704 		simple_unlock(&pc->pc_slock);
1705 		object = pool_get(pc->pc_pool, flags);
1706 		if (object != NULL && pc->pc_ctor != NULL) {
1707 			if ((*pc->pc_ctor)(pc->pc_arg, object, flags) != 0) {
1708 				pool_put(pc->pc_pool, object);
1709 				return (NULL);
1710 			}
1711 		}
1712 		return (object);
1713 	}
1714 
1715  have_group:
1716 	pc->pc_hits++;
1717 	pc->pc_nitems--;
1718 	object = pcg_get(pcg);
1719 
1720 	if (pcg->pcg_avail == 0)
1721 		pc->pc_allocfrom = NULL;
1722 
1723 	simple_unlock(&pc->pc_slock);
1724 
1725 	return (object);
1726 }
1727 
1728 /*
1729  * pool_cache_put:
1730  *
1731  *	Put an object back to the pool cache.
1732  */
1733 void
pool_cache_put(struct pool_cache * pc,void * object)1734 pool_cache_put(struct pool_cache *pc, void *object)
1735 {
1736 	struct pool_cache_group *pcg;
1737 	int s;
1738 
1739 	simple_lock(&pc->pc_slock);
1740 
1741 	if ((pcg = pc->pc_freeto) == NULL) {
1742 		TAILQ_FOREACH(pcg, &pc->pc_grouplist, pcg_list) {
1743 			if (pcg->pcg_avail != PCG_NOBJECTS) {
1744 				pc->pc_freeto = pcg;
1745 				goto have_group;
1746 			}
1747 		}
1748 
1749 		/*
1750 		 * No empty groups to free the object to.  Attempt to
1751 		 * allocate one.
1752 		 */
1753 		simple_unlock(&pc->pc_slock);
1754 		s = splvm();
1755 		pcg = pool_get(&pcgpool, PR_NOWAIT);
1756 		splx(s);
1757 		if (pcg != NULL) {
1758 			memset(pcg, 0, sizeof(*pcg));
1759 			simple_lock(&pc->pc_slock);
1760 			pc->pc_ngroups++;
1761 			TAILQ_INSERT_TAIL(&pc->pc_grouplist, pcg, pcg_list);
1762 			if (pc->pc_freeto == NULL)
1763 				pc->pc_freeto = pcg;
1764 			goto have_group;
1765 		}
1766 
1767 		/*
1768 		 * Unable to allocate a cache group; destruct the object
1769 		 * and free it back to the pool.
1770 		 */
1771 		pool_cache_destruct_object(pc, object);
1772 		return;
1773 	}
1774 
1775  have_group:
1776 	pc->pc_nitems++;
1777 	pcg_put(pcg, object);
1778 
1779 	if (pcg->pcg_avail == PCG_NOBJECTS)
1780 		pc->pc_freeto = NULL;
1781 
1782 	simple_unlock(&pc->pc_slock);
1783 }
1784 
1785 /*
1786  * pool_cache_destruct_object:
1787  *
1788  *	Force destruction of an object and its release back into
1789  *	the pool.
1790  */
1791 void
pool_cache_destruct_object(struct pool_cache * pc,void * object)1792 pool_cache_destruct_object(struct pool_cache *pc, void *object)
1793 {
1794 
1795 	if (pc->pc_dtor != NULL)
1796 		(*pc->pc_dtor)(pc->pc_arg, object);
1797 	pool_put(pc->pc_pool, object);
1798 }
1799 
1800 /*
1801  * pool_cache_do_invalidate:
1802  *
1803  *	This internal function implements pool_cache_invalidate() and
1804  *	pool_cache_reclaim().
1805  */
1806 void
pool_cache_do_invalidate(struct pool_cache * pc,int free_groups,void (* putit)(struct pool *,void *))1807 pool_cache_do_invalidate(struct pool_cache *pc, int free_groups,
1808     void (*putit)(struct pool *, void *))
1809 {
1810 	struct pool_cache_group *pcg, *npcg;
1811 	void *object;
1812 	int s;
1813 
1814 	for (pcg = TAILQ_FIRST(&pc->pc_grouplist); pcg != NULL;
1815 	     pcg = npcg) {
1816 		npcg = TAILQ_NEXT(pcg, pcg_list);
1817 		while (pcg->pcg_avail != 0) {
1818 			pc->pc_nitems--;
1819 			object = pcg_get(pcg);
1820 			if (pcg->pcg_avail == 0 && pc->pc_allocfrom == pcg)
1821 				pc->pc_allocfrom = NULL;
1822 			if (pc->pc_dtor != NULL)
1823 				(*pc->pc_dtor)(pc->pc_arg, object);
1824 			(*putit)(pc->pc_pool, object);
1825 		}
1826 		if (free_groups) {
1827 			pc->pc_ngroups--;
1828 			TAILQ_REMOVE(&pc->pc_grouplist, pcg, pcg_list);
1829 			if (pc->pc_freeto == pcg)
1830 				pc->pc_freeto = NULL;
1831 			s = splvm();
1832 			pool_put(&pcgpool, pcg);
1833 			splx(s);
1834 		}
1835 	}
1836 }
1837 
1838 /*
1839  * pool_cache_invalidate:
1840  *
1841  *	Invalidate a pool cache (destruct and release all of the
1842  *	cached objects).
1843  */
1844 void
pool_cache_invalidate(struct pool_cache * pc)1845 pool_cache_invalidate(struct pool_cache *pc)
1846 {
1847 
1848 	simple_lock(&pc->pc_slock);
1849 	pool_cache_do_invalidate(pc, 0, pool_put);
1850 	simple_unlock(&pc->pc_slock);
1851 }
1852 
1853 /*
1854  * pool_cache_reclaim:
1855  *
1856  *	Reclaim a pool cache for pool_reclaim().
1857  */
1858 void
pool_cache_reclaim(struct pool_cache * pc)1859 pool_cache_reclaim(struct pool_cache *pc)
1860 {
1861 
1862 	simple_lock(&pc->pc_slock);
1863 	pool_cache_do_invalidate(pc, 1, pool_do_put);
1864 	simple_unlock(&pc->pc_slock);
1865 }
1866 
1867 /*
1868  * We have three different sysctls.
1869  * kern.pool.npools - the number of pools.
1870  * kern.pool.pool.<pool#> - the pool struct for the pool#.
1871  * kern.pool.name.<pool#> - the name for pool#.[6~
1872  */
1873 int
sysctl_dopool(int * name,u_int namelen,char * where,size_t * sizep)1874 sysctl_dopool(int *name, u_int namelen, char *where, size_t *sizep)
1875 {
1876 	struct pool *pp, *foundpool = NULL;
1877 	size_t buflen = where != NULL ? *sizep : 0;
1878 	int npools = 0, s;
1879 	unsigned int lookfor;
1880 	size_t len;
1881 
1882 	switch (*name) {
1883 	case KERN_POOL_NPOOLS:
1884 		if (namelen != 1 || buflen != sizeof(int))
1885 			return (EINVAL);
1886 		lookfor = 0;
1887 		break;
1888 	case KERN_POOL_NAME:
1889 		if (namelen != 2 || buflen < 1)
1890 			return (EINVAL);
1891 		lookfor = name[1];
1892 		break;
1893 	case KERN_POOL_POOL:
1894 		if (namelen != 2 || buflen != sizeof(struct pool))
1895 			return (EINVAL);
1896 		lookfor = name[1];
1897 		break;
1898 	default:
1899 		return (EINVAL);
1900 	}
1901 
1902 	s = splvm();
1903 	simple_lock(&pool_head_slock);
1904 
1905 	TAILQ_FOREACH(pp, &pool_head, pr_poollist) {
1906 		npools++;
1907 		if (lookfor == pp->pr_serial) {
1908 			foundpool = pp;
1909 			break;
1910 		}
1911 	}
1912 
1913 	simple_unlock(&pool_head_slock);
1914 	splx(s);
1915 
1916 	if (lookfor != 0 && foundpool == NULL)
1917 		return (ENOENT);
1918 
1919 	switch (*name) {
1920 	case KERN_POOL_NPOOLS:
1921 		return copyout(&npools, where, buflen);
1922 	case KERN_POOL_NAME:
1923 		len = strlen(foundpool->pr_wchan) + 1;
1924 		if (*sizep < len)
1925 			return (ENOMEM);
1926 		*sizep = len;
1927 		return copyout(foundpool->pr_wchan, where, len);
1928 	case KERN_POOL_POOL:
1929 		return copyout(foundpool, where, buflen);
1930 	}
1931 	/* NOTREACHED */
1932 	return (0); /* XXX - Stupid gcc */
1933 }
1934 
1935 /*
1936  * Pool backend allocators.
1937  *
1938  * Each pool has a backend allocator that handles allocation, deallocation
1939  * and any additional draining that might be needed.
1940  */
1941 void	*pool_page_alloc_kmem(struct pool *, int);
1942 void	pool_page_free_kmem(struct pool *, void *);
1943 void	*pool_page_alloc_oldnointr(struct pool *, int);
1944 void	pool_page_free_oldnointr(struct pool *, void *);
1945 void	*pool_page_alloc(struct pool *, int);
1946 void	pool_page_free(struct pool *, void *);
1947 
1948 /* old default allocator, interrupt safe */
1949 struct pool_allocator pool_allocator_kmem = {
1950 	pool_page_alloc_kmem, pool_page_free_kmem, 0,
1951 };
1952 /* previous nointr.  handles large allocations safely */
1953 struct pool_allocator pool_allocator_oldnointr = {
1954 	pool_page_alloc_oldnointr, pool_page_free_oldnointr, 0,
1955 };
1956 /* safe for interrupts, name preserved for compat
1957  * this is the default allocator */
1958 struct pool_allocator pool_allocator_nointr = {
1959 	pool_page_alloc, pool_page_free, 0,
1960 };
1961 
1962 /*
1963  * XXX - we have at least three different resources for the same allocation
1964  *  and each resource can be depleted. First we have the ready elements in
1965  *  the pool. Then we have the resource (typically a vm_map) for this
1966  *  allocator, then we have physical memory. Waiting for any of these can
1967  *  be unnecessary when any other is freed, but the kernel doesn't support
1968  *  sleeping on multiple addresses, so we have to fake. The caller sleeps on
1969  *  the pool (so that we can be awakened when an item is returned to the pool),
1970  *  but we set PA_WANT on the allocator. When a page is returned to
1971  *  the allocator and PA_WANT is set pool_allocator_free will wakeup all
1972  *  sleeping pools belonging to this allocator. (XXX - thundering herd).
1973  *  We also wake up the allocator in case someone without a pool (malloc)
1974  *  is sleeping waiting for this allocator.
1975  */
1976 
1977 void *
pool_allocator_alloc(struct pool * org,int flags)1978 pool_allocator_alloc(struct pool *org, int flags)
1979 {
1980 	struct pool_allocator *pa = org->pr_alloc;
1981 	int freed;
1982 	void *res;
1983 	int s;
1984 
1985 	do {
1986 		if ((res = (*pa->pa_alloc)(org, flags)) != NULL)
1987 			return (res);
1988 		if ((flags & PR_WAITOK) == 0) {
1989 			/*
1990 			 * We only run the drain hook here if PR_NOWAIT.
1991 			 * In other cases the hook will be run in
1992 			 * pool_reclaim.
1993 			 */
1994 			if (org->pr_drain_hook != NULL) {
1995 				(*org->pr_drain_hook)(org->pr_drain_hook_arg,
1996 				    flags);
1997 				if ((res = (*pa->pa_alloc)(org, flags)) != NULL)
1998 					return (res);
1999 			}
2000 			break;
2001 		}
2002 		s = splvm();
2003 		simple_lock(&pa->pa_slock);
2004 		freed = pool_allocator_drain(pa, org, 1);
2005 		simple_unlock(&pa->pa_slock);
2006 		splx(s);
2007 	} while (freed);
2008 	return (NULL);
2009 }
2010 
2011 void
pool_allocator_free(struct pool * pp,void * v)2012 pool_allocator_free(struct pool *pp, void *v)
2013 {
2014 	struct pool_allocator *pa = pp->pr_alloc;
2015 	int s;
2016 
2017 	(*pa->pa_free)(pp, v);
2018 
2019 	s = splvm();
2020 	simple_lock(&pa->pa_slock);
2021 	if ((pa->pa_flags & PA_WANT) == 0) {
2022 		simple_unlock(&pa->pa_slock);
2023 		splx(s);
2024 		return;
2025 	}
2026 
2027 	TAILQ_FOREACH(pp, &pa->pa_list, pr_alloc_list) {
2028 		simple_lock(&pp->pr_slock);
2029 		if ((pp->pr_flags & PR_WANTED) != 0) {
2030 			pp->pr_flags &= ~PR_WANTED;
2031 			wakeup(pp);
2032 		}
2033 		simple_unlock(&pp->pr_slock);
2034 	}
2035 	pa->pa_flags &= ~PA_WANT;
2036 	simple_unlock(&pa->pa_slock);
2037 	splx(s);
2038 }
2039 
2040 /*
2041  * Drain all pools, except 'org', that use this allocator.
2042  *
2043  * Must be called at appropriate spl level and with the allocator locked.
2044  *
2045  * We do this to reclaim va space. pa_alloc is responsible
2046  * for waiting for physical memory.
2047  * XXX - we risk looping forever if start if someone calls
2048  *  pool_destroy on 'start'. But there is no other way to
2049  *  have potentially sleeping pool_reclaim, non-sleeping
2050  *  locks on pool_allocator and some stirring of drained
2051  *  pools in the allocator.
2052  * XXX - maybe we should use pool_head_slock for locking
2053  *  the allocators?
2054  */
2055 int
pool_allocator_drain(struct pool_allocator * pa,struct pool * org,int need)2056 pool_allocator_drain(struct pool_allocator *pa, struct pool *org, int need)
2057 {
2058 	struct pool *pp, *start;
2059 	int freed;
2060 
2061 	freed = 0;
2062 
2063 	pp = start = TAILQ_FIRST(&pa->pa_list);
2064 	do {
2065 		TAILQ_REMOVE(&pa->pa_list, pp, pr_alloc_list);
2066 		TAILQ_INSERT_TAIL(&pa->pa_list, pp, pr_alloc_list);
2067 		if (pp == org)
2068 			continue;
2069 		simple_unlock(&pa->pa_list);
2070 		freed = pool_reclaim(pp)
2071 		simple_lock(&pa->pa_list);
2072 	} while ((pp = TAILQ_FIRST(&pa->pa_list)) != start && (freed < need));
2073 
2074 	if (!freed) {
2075 		/*
2076 		 * We set PA_WANT here, the caller will most likely
2077 		 * sleep waiting for pages (if not, this won't hurt
2078 		 * that much) and there is no way to set this in the
2079 		 * caller without violating locking order.
2080 		 */
2081 		pa->pa_flags |= PA_WANT;
2082 	}
2083 
2084 	return (freed);
2085 }
2086 
2087 void *
pool_page_alloc(struct pool * pp,int flags)2088 pool_page_alloc(struct pool *pp, int flags)
2089 {
2090 	boolean_t waitok = (flags & PR_WAITOK) ? TRUE : FALSE;
2091 
2092 	return (uvm_km_getpage(waitok));
2093 }
2094 
2095 void
pool_page_free(struct pool * pp,void * v)2096 pool_page_free(struct pool *pp, void *v)
2097 {
2098 
2099 	uvm_km_putpage(v);
2100 }
2101 
2102 void *
pool_page_alloc_kmem(struct pool * pp,int flags)2103 pool_page_alloc_kmem(struct pool *pp, int flags)
2104 {
2105 	boolean_t waitok = (flags & PR_WAITOK) ? TRUE : FALSE;
2106 
2107 	return ((void *)uvm_km_alloc_poolpage1(kmem_map, uvmexp.kmem_object,
2108 	    waitok));
2109 }
2110 
2111 void
pool_page_free_kmem(struct pool * pp,void * v)2112 pool_page_free_kmem(struct pool *pp, void *v)
2113 {
2114 
2115 	uvm_km_free_poolpage1(kmem_map, (vaddr_t)v);
2116 }
2117 
2118 void *
pool_page_alloc_oldnointr(struct pool * pp,int flags)2119 pool_page_alloc_oldnointr(struct pool *pp, int flags)
2120 {
2121 	boolean_t waitok = (flags & PR_WAITOK) ? TRUE : FALSE;
2122 
2123 	splassert(IPL_NONE);
2124 
2125 	return ((void *)uvm_km_alloc_poolpage1(kernel_map, uvm.kernel_object,
2126 	    waitok));
2127 }
2128 
2129 void
pool_page_free_oldnointr(struct pool * pp,void * v)2130 pool_page_free_oldnointr(struct pool *pp, void *v)
2131 {
2132 	splassert(IPL_NONE);
2133 
2134 	uvm_km_free_poolpage1(kernel_map, (vaddr_t)v);
2135 }
2136