xref: /netbsd-src/sys/kern/vfs_bio.c (revision 6a493d6bc668897c91594964a732d38505b70cbb)
1 /*	$NetBSD: vfs_bio.c,v 1.248 2013/10/25 20:36:08 martin Exp $	*/
2 
3 /*-
4  * Copyright (c) 2007, 2008, 2009 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Andrew Doran, and by Wasabi Systems, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*-
33  * Copyright (c) 1982, 1986, 1989, 1993
34  *	The Regents of the University of California.  All rights reserved.
35  * (c) UNIX System Laboratories, Inc.
36  * All or some portions of this file are derived from material licensed
37  * to the University of California by American Telephone and Telegraph
38  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
39  * the permission of UNIX System Laboratories, Inc.
40  *
41  * Redistribution and use in source and binary forms, with or without
42  * modification, are permitted provided that the following conditions
43  * are met:
44  * 1. Redistributions of source code must retain the above copyright
45  *    notice, this list of conditions and the following disclaimer.
46  * 2. Redistributions in binary form must reproduce the above copyright
47  *    notice, this list of conditions and the following disclaimer in the
48  *    documentation and/or other materials provided with the distribution.
49  * 3. Neither the name of the University nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63  * SUCH DAMAGE.
64  *
65  *	@(#)vfs_bio.c	8.6 (Berkeley) 1/11/94
66  */
67 
68 /*-
69  * Copyright (c) 1994 Christopher G. Demetriou
70  *
71  * Redistribution and use in source and binary forms, with or without
72  * modification, are permitted provided that the following conditions
73  * are met:
74  * 1. Redistributions of source code must retain the above copyright
75  *    notice, this list of conditions and the following disclaimer.
76  * 2. Redistributions in binary form must reproduce the above copyright
77  *    notice, this list of conditions and the following disclaimer in the
78  *    documentation and/or other materials provided with the distribution.
79  * 3. All advertising materials mentioning features or use of this software
80  *    must display the following acknowledgement:
81  *	This product includes software developed by the University of
82  *	California, Berkeley and its contributors.
83  * 4. Neither the name of the University nor the names of its contributors
84  *    may be used to endorse or promote products derived from this software
85  *    without specific prior written permission.
86  *
87  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
88  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
89  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
90  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
91  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
92  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
93  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
94  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
95  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
96  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
97  * SUCH DAMAGE.
98  *
99  *	@(#)vfs_bio.c	8.6 (Berkeley) 1/11/94
100  */
101 
102 /*
103  * The buffer cache subsystem.
104  *
105  * Some references:
106  *	Bach: The Design of the UNIX Operating System (Prentice Hall, 1986)
107  *	Leffler, et al.: The Design and Implementation of the 4.3BSD
108  *		UNIX Operating System (Addison Welley, 1989)
109  *
110  * Locking
111  *
112  * There are three locks:
113  * - bufcache_lock: protects global buffer cache state.
114  * - BC_BUSY: a long term per-buffer lock.
115  * - buf_t::b_objlock: lock on completion (biowait vs biodone).
116  *
117  * For buffers associated with vnodes (a most common case) b_objlock points
118  * to the vnode_t::v_interlock.  Otherwise, it points to generic buffer_lock.
119  *
120  * Lock order:
121  *	bufcache_lock ->
122  *		buf_t::b_objlock
123  */
124 
125 #include <sys/cdefs.h>
126 __KERNEL_RCSID(0, "$NetBSD: vfs_bio.c,v 1.248 2013/10/25 20:36:08 martin Exp $");
127 
128 #include "opt_bufcache.h"
129 
130 #include <sys/param.h>
131 #include <sys/systm.h>
132 #include <sys/kernel.h>
133 #include <sys/proc.h>
134 #include <sys/buf.h>
135 #include <sys/vnode.h>
136 #include <sys/mount.h>
137 #include <sys/resourcevar.h>
138 #include <sys/sysctl.h>
139 #include <sys/conf.h>
140 #include <sys/kauth.h>
141 #include <sys/fstrans.h>
142 #include <sys/intr.h>
143 #include <sys/cpu.h>
144 #include <sys/wapbl.h>
145 #include <sys/bitops.h>
146 
147 #include <uvm/uvm.h>	/* extern struct uvm uvm */
148 
149 #include <miscfs/specfs/specdev.h>
150 
151 #ifndef	BUFPAGES
152 # define BUFPAGES 0
153 #endif
154 
155 #ifdef BUFCACHE
156 # if (BUFCACHE < 5) || (BUFCACHE > 95)
157 #  error BUFCACHE is not between 5 and 95
158 # endif
159 #else
160 # define BUFCACHE 15
161 #endif
162 
163 u_int	nbuf;			/* desired number of buffer headers */
164 u_int	bufpages = BUFPAGES;	/* optional hardwired count */
165 u_int	bufcache = BUFCACHE;	/* max % of RAM to use for buffer cache */
166 
167 /* Function prototypes */
168 struct bqueue;
169 
170 static void buf_setwm(void);
171 static int buf_trim(void);
172 static void *bufpool_page_alloc(struct pool *, int);
173 static void bufpool_page_free(struct pool *, void *);
174 static buf_t *bio_doread(struct vnode *, daddr_t, int,
175     kauth_cred_t, int);
176 static buf_t *getnewbuf(int, int, int);
177 static int buf_lotsfree(void);
178 static int buf_canrelease(void);
179 static u_long buf_mempoolidx(u_long);
180 static u_long buf_roundsize(u_long);
181 static void *buf_alloc(size_t);
182 static void buf_mrelease(void *, size_t);
183 static void binsheadfree(buf_t *, struct bqueue *);
184 static void binstailfree(buf_t *, struct bqueue *);
185 #ifdef DEBUG
186 static int checkfreelist(buf_t *, struct bqueue *, int);
187 #endif
188 static void biointr(void *);
189 static void biodone2(buf_t *);
190 static void bref(buf_t *);
191 static void brele(buf_t *);
192 static void sysctl_kern_buf_setup(void);
193 static void sysctl_vm_buf_setup(void);
194 
195 /*
196  * Definitions for the buffer hash lists.
197  */
198 #define	BUFHASH(dvp, lbn)	\
199 	(&bufhashtbl[(((long)(dvp) >> 8) + (int)(lbn)) & bufhash])
200 LIST_HEAD(bufhashhdr, buf) *bufhashtbl, invalhash;
201 u_long	bufhash;
202 struct bqueue bufqueues[BQUEUES];
203 
204 static kcondvar_t needbuffer_cv;
205 
206 /*
207  * Buffer queue lock.
208  */
209 kmutex_t bufcache_lock;
210 kmutex_t buffer_lock;
211 
212 /* Software ISR for completed transfers. */
213 static void *biodone_sih;
214 
215 /* Buffer pool for I/O buffers. */
216 static pool_cache_t buf_cache;
217 static pool_cache_t bufio_cache;
218 
219 #define MEMPOOL_INDEX_OFFSET (ilog2(DEV_BSIZE))	/* smallest pool is 512 bytes */
220 #define NMEMPOOLS (ilog2(MAXBSIZE) - MEMPOOL_INDEX_OFFSET + 1)
221 __CTASSERT((1 << (NMEMPOOLS + MEMPOOL_INDEX_OFFSET - 1)) == MAXBSIZE);
222 
223 /* Buffer memory pools */
224 static struct pool bmempools[NMEMPOOLS];
225 
226 static struct vm_map *buf_map;
227 
228 /*
229  * Buffer memory pool allocator.
230  */
231 static void *
232 bufpool_page_alloc(struct pool *pp, int flags)
233 {
234 
235 	return (void *)uvm_km_alloc(buf_map,
236 	    MAXBSIZE, MAXBSIZE,
237 	    ((flags & PR_WAITOK) ? 0 : UVM_KMF_NOWAIT|UVM_KMF_TRYLOCK)
238 	    | UVM_KMF_WIRED);
239 }
240 
241 static void
242 bufpool_page_free(struct pool *pp, void *v)
243 {
244 
245 	uvm_km_free(buf_map, (vaddr_t)v, MAXBSIZE, UVM_KMF_WIRED);
246 }
247 
248 static struct pool_allocator bufmempool_allocator = {
249 	.pa_alloc = bufpool_page_alloc,
250 	.pa_free = bufpool_page_free,
251 	.pa_pagesz = MAXBSIZE,
252 };
253 
254 /* Buffer memory management variables */
255 u_long bufmem_valimit;
256 u_long bufmem_hiwater;
257 u_long bufmem_lowater;
258 u_long bufmem;
259 
260 /*
261  * MD code can call this to set a hard limit on the amount
262  * of virtual memory used by the buffer cache.
263  */
264 int
265 buf_setvalimit(vsize_t sz)
266 {
267 
268 	/* We need to accommodate at least NMEMPOOLS of MAXBSIZE each */
269 	if (sz < NMEMPOOLS * MAXBSIZE)
270 		return EINVAL;
271 
272 	bufmem_valimit = sz;
273 	return 0;
274 }
275 
276 static void
277 buf_setwm(void)
278 {
279 
280 	bufmem_hiwater = buf_memcalc();
281 	/* lowater is approx. 2% of memory (with bufcache = 15) */
282 #define	BUFMEM_WMSHIFT	3
283 #define	BUFMEM_HIWMMIN	(64 * 1024 << BUFMEM_WMSHIFT)
284 	if (bufmem_hiwater < BUFMEM_HIWMMIN)
285 		/* Ensure a reasonable minimum value */
286 		bufmem_hiwater = BUFMEM_HIWMMIN;
287 	bufmem_lowater = bufmem_hiwater >> BUFMEM_WMSHIFT;
288 }
289 
290 #ifdef DEBUG
291 int debug_verify_freelist = 0;
292 static int
293 checkfreelist(buf_t *bp, struct bqueue *dp, int ison)
294 {
295 	buf_t *b;
296 
297 	if (!debug_verify_freelist)
298 		return 1;
299 
300 	TAILQ_FOREACH(b, &dp->bq_queue, b_freelist) {
301 		if (b == bp)
302 			return ison ? 1 : 0;
303 	}
304 
305 	return ison ? 0 : 1;
306 }
307 #endif
308 
309 /*
310  * Insq/Remq for the buffer hash lists.
311  * Call with buffer queue locked.
312  */
313 static void
314 binsheadfree(buf_t *bp, struct bqueue *dp)
315 {
316 
317 	KASSERT(mutex_owned(&bufcache_lock));
318 	KASSERT(bp->b_freelistindex == -1);
319 	TAILQ_INSERT_HEAD(&dp->bq_queue, bp, b_freelist);
320 	dp->bq_bytes += bp->b_bufsize;
321 	bp->b_freelistindex = dp - bufqueues;
322 }
323 
324 static void
325 binstailfree(buf_t *bp, struct bqueue *dp)
326 {
327 
328 	KASSERT(mutex_owned(&bufcache_lock));
329 	KASSERT(bp->b_freelistindex == -1);
330 	TAILQ_INSERT_TAIL(&dp->bq_queue, bp, b_freelist);
331 	dp->bq_bytes += bp->b_bufsize;
332 	bp->b_freelistindex = dp - bufqueues;
333 }
334 
335 void
336 bremfree(buf_t *bp)
337 {
338 	struct bqueue *dp;
339 	int bqidx = bp->b_freelistindex;
340 
341 	KASSERT(mutex_owned(&bufcache_lock));
342 
343 	KASSERT(bqidx != -1);
344 	dp = &bufqueues[bqidx];
345 	KDASSERT(checkfreelist(bp, dp, 1));
346 	KASSERT(dp->bq_bytes >= bp->b_bufsize);
347 	TAILQ_REMOVE(&dp->bq_queue, bp, b_freelist);
348 	dp->bq_bytes -= bp->b_bufsize;
349 
350 	/* For the sysctl helper. */
351 	if (bp == dp->bq_marker)
352 		dp->bq_marker = NULL;
353 
354 #if defined(DIAGNOSTIC)
355 	bp->b_freelistindex = -1;
356 #endif /* defined(DIAGNOSTIC) */
357 }
358 
359 /*
360  * Add a reference to an buffer structure that came from buf_cache.
361  */
362 static inline void
363 bref(buf_t *bp)
364 {
365 
366 	KASSERT(mutex_owned(&bufcache_lock));
367 	KASSERT(bp->b_refcnt > 0);
368 
369 	bp->b_refcnt++;
370 }
371 
372 /*
373  * Free an unused buffer structure that came from buf_cache.
374  */
375 static inline void
376 brele(buf_t *bp)
377 {
378 
379 	KASSERT(mutex_owned(&bufcache_lock));
380 	KASSERT(bp->b_refcnt > 0);
381 
382 	if (bp->b_refcnt-- == 1) {
383 		buf_destroy(bp);
384 #ifdef DEBUG
385 		memset((char *)bp, 0, sizeof(*bp));
386 #endif
387 		pool_cache_put(buf_cache, bp);
388 	}
389 }
390 
391 /*
392  * note that for some ports this is used by pmap bootstrap code to
393  * determine kva size.
394  */
395 u_long
396 buf_memcalc(void)
397 {
398 	u_long n;
399 	vsize_t mapsz = 0;
400 
401 	/*
402 	 * Determine the upper bound of memory to use for buffers.
403 	 *
404 	 *	- If bufpages is specified, use that as the number
405 	 *	  pages.
406 	 *
407 	 *	- Otherwise, use bufcache as the percentage of
408 	 *	  physical memory.
409 	 */
410 	if (bufpages != 0) {
411 		n = bufpages;
412 	} else {
413 		if (bufcache < 5) {
414 			printf("forcing bufcache %d -> 5", bufcache);
415 			bufcache = 5;
416 		}
417 		if (bufcache > 95) {
418 			printf("forcing bufcache %d -> 95", bufcache);
419 			bufcache = 95;
420 		}
421 		if (buf_map != NULL)
422 			mapsz = vm_map_max(buf_map) - vm_map_min(buf_map);
423 		n = calc_cache_size(mapsz, bufcache,
424 		    (buf_map != kernel_map) ? 100 : BUFCACHE_VA_MAXPCT)
425 		    / PAGE_SIZE;
426 	}
427 
428 	n <<= PAGE_SHIFT;
429 	if (bufmem_valimit != 0 && n > bufmem_valimit)
430 		n = bufmem_valimit;
431 
432 	return (n);
433 }
434 
435 /*
436  * Initialize buffers and hash links for buffers.
437  */
438 void
439 bufinit(void)
440 {
441 	struct bqueue *dp;
442 	int use_std;
443 	u_int i;
444 
445 	mutex_init(&bufcache_lock, MUTEX_DEFAULT, IPL_NONE);
446 	mutex_init(&buffer_lock, MUTEX_DEFAULT, IPL_NONE);
447 	cv_init(&needbuffer_cv, "needbuf");
448 
449 	if (bufmem_valimit != 0) {
450 		vaddr_t minaddr = 0, maxaddr;
451 		buf_map = uvm_km_suballoc(kernel_map, &minaddr, &maxaddr,
452 					  bufmem_valimit, 0, false, 0);
453 		if (buf_map == NULL)
454 			panic("bufinit: cannot allocate submap");
455 	} else
456 		buf_map = kernel_map;
457 
458 	/*
459 	 * Initialize buffer cache memory parameters.
460 	 */
461 	bufmem = 0;
462 	buf_setwm();
463 
464 	/* On "small" machines use small pool page sizes where possible */
465 	use_std = (physmem < atop(16*1024*1024));
466 
467 	/*
468 	 * Also use them on systems that can map the pool pages using
469 	 * a direct-mapped segment.
470 	 */
471 #ifdef PMAP_MAP_POOLPAGE
472 	use_std = 1;
473 #endif
474 
475 	buf_cache = pool_cache_init(sizeof(buf_t), 0, 0, 0,
476 	    "bufpl", NULL, IPL_SOFTBIO, NULL, NULL, NULL);
477 	bufio_cache = pool_cache_init(sizeof(buf_t), 0, 0, 0,
478 	    "biopl", NULL, IPL_BIO, NULL, NULL, NULL);
479 
480 	for (i = 0; i < NMEMPOOLS; i++) {
481 		struct pool_allocator *pa;
482 		struct pool *pp = &bmempools[i];
483 		u_int size = 1 << (i + MEMPOOL_INDEX_OFFSET);
484 		char *name = kmem_alloc(8, KM_SLEEP); /* XXX: never freed */
485 		if (__predict_false(size >= 1048576))
486 			(void)snprintf(name, 8, "buf%um", size / 1048576);
487 		else if (__predict_true(size >= 1024))
488 			(void)snprintf(name, 8, "buf%uk", size / 1024);
489 		else
490 			(void)snprintf(name, 8, "buf%ub", size);
491 		pa = (size <= PAGE_SIZE && use_std)
492 			? &pool_allocator_nointr
493 			: &bufmempool_allocator;
494 		pool_init(pp, size, 0, 0, 0, name, pa, IPL_NONE);
495 		pool_setlowat(pp, 1);
496 		pool_sethiwat(pp, 1);
497 	}
498 
499 	/* Initialize the buffer queues */
500 	for (dp = bufqueues; dp < &bufqueues[BQUEUES]; dp++) {
501 		TAILQ_INIT(&dp->bq_queue);
502 		dp->bq_bytes = 0;
503 	}
504 
505 	/*
506 	 * Estimate hash table size based on the amount of memory we
507 	 * intend to use for the buffer cache. The average buffer
508 	 * size is dependent on our clients (i.e. filesystems).
509 	 *
510 	 * For now, use an empirical 3K per buffer.
511 	 */
512 	nbuf = (bufmem_hiwater / 1024) / 3;
513 	bufhashtbl = hashinit(nbuf, HASH_LIST, true, &bufhash);
514 
515 	sysctl_kern_buf_setup();
516 	sysctl_vm_buf_setup();
517 }
518 
519 void
520 bufinit2(void)
521 {
522 
523 	biodone_sih = softint_establish(SOFTINT_BIO | SOFTINT_MPSAFE, biointr,
524 	    NULL);
525 	if (biodone_sih == NULL)
526 		panic("bufinit2: can't establish soft interrupt");
527 }
528 
529 static int
530 buf_lotsfree(void)
531 {
532 	int try, thresh;
533 
534 	/* Always allocate if less than the low water mark. */
535 	if (bufmem < bufmem_lowater)
536 		return 1;
537 
538 	/* Never allocate if greater than the high water mark. */
539 	if (bufmem > bufmem_hiwater)
540 		return 0;
541 
542 	/* If there's anything on the AGE list, it should be eaten. */
543 	if (TAILQ_FIRST(&bufqueues[BQ_AGE].bq_queue) != NULL)
544 		return 0;
545 
546 	/*
547 	 * The probabily of getting a new allocation is inversely
548 	 * proportional to the current size of the cache, using
549 	 * a granularity of 16 steps.
550 	 */
551 	try = random() & 0x0000000fL;
552 
553 	/* Don't use "16 * bufmem" here to avoid a 32-bit overflow. */
554 	thresh = (bufmem - bufmem_lowater) /
555 	    ((bufmem_hiwater - bufmem_lowater) / 16);
556 
557 	if (try >= thresh)
558 		return 1;
559 
560 	/* Otherwise don't allocate. */
561 	return 0;
562 }
563 
564 /*
565  * Return estimate of bytes we think need to be
566  * released to help resolve low memory conditions.
567  *
568  * => called with bufcache_lock held.
569  */
570 static int
571 buf_canrelease(void)
572 {
573 	int pagedemand, ninvalid = 0;
574 
575 	KASSERT(mutex_owned(&bufcache_lock));
576 
577 	if (bufmem < bufmem_lowater)
578 		return 0;
579 
580 	if (bufmem > bufmem_hiwater)
581 		return bufmem - bufmem_hiwater;
582 
583 	ninvalid += bufqueues[BQ_AGE].bq_bytes;
584 
585 	pagedemand = uvmexp.freetarg - uvmexp.free;
586 	if (pagedemand < 0)
587 		return ninvalid;
588 	return MAX(ninvalid, MIN(2 * MAXBSIZE,
589 	    MIN((bufmem - bufmem_lowater) / 16, pagedemand * PAGE_SIZE)));
590 }
591 
592 /*
593  * Buffer memory allocation helper functions
594  */
595 static u_long
596 buf_mempoolidx(u_long size)
597 {
598 	u_int n = 0;
599 
600 	size -= 1;
601 	size >>= MEMPOOL_INDEX_OFFSET;
602 	while (size) {
603 		size >>= 1;
604 		n += 1;
605 	}
606 	if (n >= NMEMPOOLS)
607 		panic("buf mem pool index %d", n);
608 	return n;
609 }
610 
611 static u_long
612 buf_roundsize(u_long size)
613 {
614 	/* Round up to nearest power of 2 */
615 	return (1 << (buf_mempoolidx(size) + MEMPOOL_INDEX_OFFSET));
616 }
617 
618 static void *
619 buf_alloc(size_t size)
620 {
621 	u_int n = buf_mempoolidx(size);
622 	void *addr;
623 
624 	while (1) {
625 		addr = pool_get(&bmempools[n], PR_NOWAIT);
626 		if (addr != NULL)
627 			break;
628 
629 		/* No memory, see if we can free some. If so, try again */
630 		mutex_enter(&bufcache_lock);
631 		if (buf_drain(1) > 0) {
632 			mutex_exit(&bufcache_lock);
633 			continue;
634 		}
635 
636 		if (curlwp == uvm.pagedaemon_lwp) {
637 			mutex_exit(&bufcache_lock);
638 			return NULL;
639 		}
640 
641 		/* Wait for buffers to arrive on the LRU queue */
642 		cv_timedwait(&needbuffer_cv, &bufcache_lock, hz / 4);
643 		mutex_exit(&bufcache_lock);
644 	}
645 
646 	return addr;
647 }
648 
649 static void
650 buf_mrelease(void *addr, size_t size)
651 {
652 
653 	pool_put(&bmempools[buf_mempoolidx(size)], addr);
654 }
655 
656 /*
657  * bread()/breadn() helper.
658  */
659 static buf_t *
660 bio_doread(struct vnode *vp, daddr_t blkno, int size, kauth_cred_t cred,
661     int async)
662 {
663 	buf_t *bp;
664 	struct mount *mp;
665 
666 	bp = getblk(vp, blkno, size, 0, 0);
667 
668 	/*
669 	 * getblk() may return NULL if we are the pagedaemon.
670 	 */
671 	if (bp == NULL) {
672 		KASSERT(curlwp == uvm.pagedaemon_lwp);
673 		return NULL;
674 	}
675 
676 	/*
677 	 * If buffer does not have data valid, start a read.
678 	 * Note that if buffer is BC_INVAL, getblk() won't return it.
679 	 * Therefore, it's valid if its I/O has completed or been delayed.
680 	 */
681 	if (!ISSET(bp->b_oflags, (BO_DONE | BO_DELWRI))) {
682 		/* Start I/O for the buffer. */
683 		SET(bp->b_flags, B_READ | async);
684 		if (async)
685 			BIO_SETPRIO(bp, BPRIO_TIMELIMITED);
686 		else
687 			BIO_SETPRIO(bp, BPRIO_TIMECRITICAL);
688 		VOP_STRATEGY(vp, bp);
689 
690 		/* Pay for the read. */
691 		curlwp->l_ru.ru_inblock++;
692 	} else if (async)
693 		brelse(bp, 0);
694 
695 	if (vp->v_type == VBLK)
696 		mp = spec_node_getmountedfs(vp);
697 	else
698 		mp = vp->v_mount;
699 
700 	/*
701 	 * Collect statistics on synchronous and asynchronous reads.
702 	 * Reads from block devices are charged to their associated
703 	 * filesystem (if any).
704 	 */
705 	if (mp != NULL) {
706 		if (async == 0)
707 			mp->mnt_stat.f_syncreads++;
708 		else
709 			mp->mnt_stat.f_asyncreads++;
710 	}
711 
712 	return (bp);
713 }
714 
715 /*
716  * Read a disk block.
717  * This algorithm described in Bach (p.54).
718  */
719 int
720 bread(struct vnode *vp, daddr_t blkno, int size, kauth_cred_t cred,
721     int flags, buf_t **bpp)
722 {
723 	buf_t *bp;
724 	int error;
725 
726 	/* Get buffer for block. */
727 	bp = *bpp = bio_doread(vp, blkno, size, cred, 0);
728 	if (bp == NULL)
729 		return ENOMEM;
730 
731 	/* Wait for the read to complete, and return result. */
732 	error = biowait(bp);
733 	if (error == 0 && (flags & B_MODIFY) != 0)
734 		error = fscow_run(bp, true);
735 	if (error) {
736 		brelse(bp, 0);
737 		*bpp = NULL;
738 	}
739 
740 	return error;
741 }
742 
743 /*
744  * Read-ahead multiple disk blocks. The first is sync, the rest async.
745  * Trivial modification to the breada algorithm presented in Bach (p.55).
746  */
747 int
748 breadn(struct vnode *vp, daddr_t blkno, int size, daddr_t *rablks,
749     int *rasizes, int nrablks, kauth_cred_t cred, int flags, buf_t **bpp)
750 {
751 	buf_t *bp;
752 	int error, i;
753 
754 	bp = *bpp = bio_doread(vp, blkno, size, cred, 0);
755 	if (bp == NULL)
756 		return ENOMEM;
757 
758 	/*
759 	 * For each of the read-ahead blocks, start a read, if necessary.
760 	 */
761 	mutex_enter(&bufcache_lock);
762 	for (i = 0; i < nrablks; i++) {
763 		/* If it's in the cache, just go on to next one. */
764 		if (incore(vp, rablks[i]))
765 			continue;
766 
767 		/* Get a buffer for the read-ahead block */
768 		mutex_exit(&bufcache_lock);
769 		(void) bio_doread(vp, rablks[i], rasizes[i], cred, B_ASYNC);
770 		mutex_enter(&bufcache_lock);
771 	}
772 	mutex_exit(&bufcache_lock);
773 
774 	/* Otherwise, we had to start a read for it; wait until it's valid. */
775 	error = biowait(bp);
776 	if (error == 0 && (flags & B_MODIFY) != 0)
777 		error = fscow_run(bp, true);
778 	if (error) {
779 		brelse(bp, 0);
780 		*bpp = NULL;
781 	}
782 
783 	return error;
784 }
785 
786 /*
787  * Block write.  Described in Bach (p.56)
788  */
789 int
790 bwrite(buf_t *bp)
791 {
792 	int rv, sync, wasdelayed;
793 	struct vnode *vp;
794 	struct mount *mp;
795 
796 	KASSERT(ISSET(bp->b_cflags, BC_BUSY));
797 	KASSERT(!cv_has_waiters(&bp->b_done));
798 
799 	vp = bp->b_vp;
800 	if (vp != NULL) {
801 		KASSERT(bp->b_objlock == vp->v_interlock);
802 		if (vp->v_type == VBLK)
803 			mp = spec_node_getmountedfs(vp);
804 		else
805 			mp = vp->v_mount;
806 	} else {
807 		mp = NULL;
808 	}
809 
810 	if (mp && mp->mnt_wapbl) {
811 		if (bp->b_iodone != mp->mnt_wapbl_op->wo_wapbl_biodone) {
812 			bdwrite(bp);
813 			return 0;
814 		}
815 	}
816 
817 	/*
818 	 * Remember buffer type, to switch on it later.  If the write was
819 	 * synchronous, but the file system was mounted with MNT_ASYNC,
820 	 * convert it to a delayed write.
821 	 * XXX note that this relies on delayed tape writes being converted
822 	 * to async, not sync writes (which is safe, but ugly).
823 	 */
824 	sync = !ISSET(bp->b_flags, B_ASYNC);
825 	if (sync && mp != NULL && ISSET(mp->mnt_flag, MNT_ASYNC)) {
826 		bdwrite(bp);
827 		return (0);
828 	}
829 
830 	/*
831 	 * Collect statistics on synchronous and asynchronous writes.
832 	 * Writes to block devices are charged to their associated
833 	 * filesystem (if any).
834 	 */
835 	if (mp != NULL) {
836 		if (sync)
837 			mp->mnt_stat.f_syncwrites++;
838 		else
839 			mp->mnt_stat.f_asyncwrites++;
840 	}
841 
842 	/*
843 	 * Pay for the I/O operation and make sure the buf is on the correct
844 	 * vnode queue.
845 	 */
846 	bp->b_error = 0;
847 	wasdelayed = ISSET(bp->b_oflags, BO_DELWRI);
848 	CLR(bp->b_flags, B_READ);
849 	if (wasdelayed) {
850 		mutex_enter(&bufcache_lock);
851 		mutex_enter(bp->b_objlock);
852 		CLR(bp->b_oflags, BO_DONE | BO_DELWRI);
853 		reassignbuf(bp, bp->b_vp);
854 		mutex_exit(&bufcache_lock);
855 	} else {
856 		curlwp->l_ru.ru_oublock++;
857 		mutex_enter(bp->b_objlock);
858 		CLR(bp->b_oflags, BO_DONE | BO_DELWRI);
859 	}
860 	if (vp != NULL)
861 		vp->v_numoutput++;
862 	mutex_exit(bp->b_objlock);
863 
864 	/* Initiate disk write. */
865 	if (sync)
866 		BIO_SETPRIO(bp, BPRIO_TIMECRITICAL);
867 	else
868 		BIO_SETPRIO(bp, BPRIO_TIMELIMITED);
869 
870 	VOP_STRATEGY(vp, bp);
871 
872 	if (sync) {
873 		/* If I/O was synchronous, wait for it to complete. */
874 		rv = biowait(bp);
875 
876 		/* Release the buffer. */
877 		brelse(bp, 0);
878 
879 		return (rv);
880 	} else {
881 		return (0);
882 	}
883 }
884 
885 int
886 vn_bwrite(void *v)
887 {
888 	struct vop_bwrite_args *ap = v;
889 
890 	return (bwrite(ap->a_bp));
891 }
892 
893 /*
894  * Delayed write.
895  *
896  * The buffer is marked dirty, but is not queued for I/O.
897  * This routine should be used when the buffer is expected
898  * to be modified again soon, typically a small write that
899  * partially fills a buffer.
900  *
901  * NB: magnetic tapes cannot be delayed; they must be
902  * written in the order that the writes are requested.
903  *
904  * Described in Leffler, et al. (pp. 208-213).
905  */
906 void
907 bdwrite(buf_t *bp)
908 {
909 
910 	KASSERT(bp->b_vp == NULL || bp->b_vp->v_tag != VT_UFS ||
911 	    bp->b_vp->v_type == VBLK || ISSET(bp->b_flags, B_COWDONE));
912 	KASSERT(ISSET(bp->b_cflags, BC_BUSY));
913 	KASSERT(!cv_has_waiters(&bp->b_done));
914 
915 	/* If this is a tape block, write the block now. */
916 	if (bdev_type(bp->b_dev) == D_TAPE) {
917 		bawrite(bp);
918 		return;
919 	}
920 
921 	if (wapbl_vphaswapbl(bp->b_vp)) {
922 		struct mount *mp = wapbl_vptomp(bp->b_vp);
923 
924 		if (bp->b_iodone != mp->mnt_wapbl_op->wo_wapbl_biodone) {
925 			WAPBL_ADD_BUF(mp, bp);
926 		}
927 	}
928 
929 	/*
930 	 * If the block hasn't been seen before:
931 	 *	(1) Mark it as having been seen,
932 	 *	(2) Charge for the write,
933 	 *	(3) Make sure it's on its vnode's correct block list.
934 	 */
935 	KASSERT(bp->b_vp == NULL || bp->b_objlock == bp->b_vp->v_interlock);
936 
937 	if (!ISSET(bp->b_oflags, BO_DELWRI)) {
938 		mutex_enter(&bufcache_lock);
939 		mutex_enter(bp->b_objlock);
940 		SET(bp->b_oflags, BO_DELWRI);
941 		curlwp->l_ru.ru_oublock++;
942 		reassignbuf(bp, bp->b_vp);
943 		mutex_exit(&bufcache_lock);
944 	} else {
945 		mutex_enter(bp->b_objlock);
946 	}
947 	/* Otherwise, the "write" is done, so mark and release the buffer. */
948 	CLR(bp->b_oflags, BO_DONE);
949 	mutex_exit(bp->b_objlock);
950 
951 	brelse(bp, 0);
952 }
953 
954 /*
955  * Asynchronous block write; just an asynchronous bwrite().
956  */
957 void
958 bawrite(buf_t *bp)
959 {
960 
961 	KASSERT(ISSET(bp->b_cflags, BC_BUSY));
962 	KASSERT(bp->b_vp != NULL);
963 
964 	SET(bp->b_flags, B_ASYNC);
965 	VOP_BWRITE(bp->b_vp, bp);
966 }
967 
968 /*
969  * Release a buffer on to the free lists.
970  * Described in Bach (p. 46).
971  */
972 void
973 brelsel(buf_t *bp, int set)
974 {
975 	struct bqueue *bufq;
976 	struct vnode *vp;
977 
978 	KASSERT(bp != NULL);
979 	KASSERT(mutex_owned(&bufcache_lock));
980 	KASSERT(!cv_has_waiters(&bp->b_done));
981 	KASSERT(bp->b_refcnt > 0);
982 
983 	SET(bp->b_cflags, set);
984 
985 	KASSERT(ISSET(bp->b_cflags, BC_BUSY));
986 	KASSERT(bp->b_iodone == NULL);
987 
988 	/* Wake up any processes waiting for any buffer to become free. */
989 	cv_signal(&needbuffer_cv);
990 
991 	/* Wake up any proceeses waiting for _this_ buffer to become */
992 	if (ISSET(bp->b_cflags, BC_WANTED))
993 		CLR(bp->b_cflags, BC_WANTED|BC_AGE);
994 
995 	/* If it's clean clear the copy-on-write flag. */
996 	if (ISSET(bp->b_flags, B_COWDONE)) {
997 		mutex_enter(bp->b_objlock);
998 		if (!ISSET(bp->b_oflags, BO_DELWRI))
999 			CLR(bp->b_flags, B_COWDONE);
1000 		mutex_exit(bp->b_objlock);
1001 	}
1002 
1003 	/*
1004 	 * Determine which queue the buffer should be on, then put it there.
1005 	 */
1006 
1007 	/* If it's locked, don't report an error; try again later. */
1008 	if (ISSET(bp->b_flags, B_LOCKED))
1009 		bp->b_error = 0;
1010 
1011 	/* If it's not cacheable, or an error, mark it invalid. */
1012 	if (ISSET(bp->b_cflags, BC_NOCACHE) || bp->b_error != 0)
1013 		SET(bp->b_cflags, BC_INVAL);
1014 
1015 	if (ISSET(bp->b_cflags, BC_VFLUSH)) {
1016 		/*
1017 		 * This is a delayed write buffer that was just flushed to
1018 		 * disk.  It is still on the LRU queue.  If it's become
1019 		 * invalid, then we need to move it to a different queue;
1020 		 * otherwise leave it in its current position.
1021 		 */
1022 		CLR(bp->b_cflags, BC_VFLUSH);
1023 		if (!ISSET(bp->b_cflags, BC_INVAL|BC_AGE) &&
1024 		    !ISSET(bp->b_flags, B_LOCKED) && bp->b_error == 0) {
1025 			KDASSERT(checkfreelist(bp, &bufqueues[BQ_LRU], 1));
1026 			goto already_queued;
1027 		} else {
1028 			bremfree(bp);
1029 		}
1030 	}
1031 
1032 	KDASSERT(checkfreelist(bp, &bufqueues[BQ_AGE], 0));
1033 	KDASSERT(checkfreelist(bp, &bufqueues[BQ_LRU], 0));
1034 	KDASSERT(checkfreelist(bp, &bufqueues[BQ_LOCKED], 0));
1035 
1036 	if ((bp->b_bufsize <= 0) || ISSET(bp->b_cflags, BC_INVAL)) {
1037 		/*
1038 		 * If it's invalid or empty, dissociate it from its vnode
1039 		 * and put on the head of the appropriate queue.
1040 		 */
1041 		if (ISSET(bp->b_flags, B_LOCKED)) {
1042 			if (wapbl_vphaswapbl(vp = bp->b_vp)) {
1043 				struct mount *mp = wapbl_vptomp(vp);
1044 
1045 				KASSERT(bp->b_iodone
1046 				    != mp->mnt_wapbl_op->wo_wapbl_biodone);
1047 				WAPBL_REMOVE_BUF(mp, bp);
1048 			}
1049 		}
1050 
1051 		mutex_enter(bp->b_objlock);
1052 		CLR(bp->b_oflags, BO_DONE|BO_DELWRI);
1053 		if ((vp = bp->b_vp) != NULL) {
1054 			KASSERT(bp->b_objlock == vp->v_interlock);
1055 			reassignbuf(bp, bp->b_vp);
1056 			brelvp(bp);
1057 			mutex_exit(vp->v_interlock);
1058 		} else {
1059 			KASSERT(bp->b_objlock == &buffer_lock);
1060 			mutex_exit(bp->b_objlock);
1061 		}
1062 
1063 		if (bp->b_bufsize <= 0)
1064 			/* no data */
1065 			goto already_queued;
1066 		else
1067 			/* invalid data */
1068 			bufq = &bufqueues[BQ_AGE];
1069 		binsheadfree(bp, bufq);
1070 	} else  {
1071 		/*
1072 		 * It has valid data.  Put it on the end of the appropriate
1073 		 * queue, so that it'll stick around for as long as possible.
1074 		 * If buf is AGE, but has dependencies, must put it on last
1075 		 * bufqueue to be scanned, ie LRU. This protects against the
1076 		 * livelock where BQ_AGE only has buffers with dependencies,
1077 		 * and we thus never get to the dependent buffers in BQ_LRU.
1078 		 */
1079 		if (ISSET(bp->b_flags, B_LOCKED)) {
1080 			/* locked in core */
1081 			bufq = &bufqueues[BQ_LOCKED];
1082 		} else if (!ISSET(bp->b_cflags, BC_AGE)) {
1083 			/* valid data */
1084 			bufq = &bufqueues[BQ_LRU];
1085 		} else {
1086 			/* stale but valid data */
1087 			bufq = &bufqueues[BQ_AGE];
1088 		}
1089 		binstailfree(bp, bufq);
1090 	}
1091 already_queued:
1092 	/* Unlock the buffer. */
1093 	CLR(bp->b_cflags, BC_AGE|BC_BUSY|BC_NOCACHE);
1094 	CLR(bp->b_flags, B_ASYNC);
1095 	cv_broadcast(&bp->b_busy);
1096 
1097 	if (bp->b_bufsize <= 0)
1098 		brele(bp);
1099 }
1100 
1101 void
1102 brelse(buf_t *bp, int set)
1103 {
1104 
1105 	mutex_enter(&bufcache_lock);
1106 	brelsel(bp, set);
1107 	mutex_exit(&bufcache_lock);
1108 }
1109 
1110 /*
1111  * Determine if a block is in the cache.
1112  * Just look on what would be its hash chain.  If it's there, return
1113  * a pointer to it, unless it's marked invalid.  If it's marked invalid,
1114  * we normally don't return the buffer, unless the caller explicitly
1115  * wants us to.
1116  */
1117 buf_t *
1118 incore(struct vnode *vp, daddr_t blkno)
1119 {
1120 	buf_t *bp;
1121 
1122 	KASSERT(mutex_owned(&bufcache_lock));
1123 
1124 	/* Search hash chain */
1125 	LIST_FOREACH(bp, BUFHASH(vp, blkno), b_hash) {
1126 		if (bp->b_lblkno == blkno && bp->b_vp == vp &&
1127 		    !ISSET(bp->b_cflags, BC_INVAL)) {
1128 		    	KASSERT(bp->b_objlock == vp->v_interlock);
1129 		    	return (bp);
1130 		}
1131 	}
1132 
1133 	return (NULL);
1134 }
1135 
1136 /*
1137  * Get a block of requested size that is associated with
1138  * a given vnode and block offset. If it is found in the
1139  * block cache, mark it as having been found, make it busy
1140  * and return it. Otherwise, return an empty block of the
1141  * correct size. It is up to the caller to insure that the
1142  * cached blocks be of the correct size.
1143  */
1144 buf_t *
1145 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo)
1146 {
1147 	int err, preserve;
1148 	buf_t *bp;
1149 
1150 	mutex_enter(&bufcache_lock);
1151  loop:
1152 	bp = incore(vp, blkno);
1153 	if (bp != NULL) {
1154 		err = bbusy(bp, ((slpflag & PCATCH) != 0), slptimeo, NULL);
1155 		if (err != 0) {
1156 			if (err == EPASSTHROUGH)
1157 				goto loop;
1158 			mutex_exit(&bufcache_lock);
1159 			return (NULL);
1160 		}
1161 		KASSERT(!cv_has_waiters(&bp->b_done));
1162 #ifdef DIAGNOSTIC
1163 		if (ISSET(bp->b_oflags, BO_DONE|BO_DELWRI) &&
1164 		    bp->b_bcount < size && vp->v_type != VBLK)
1165 			panic("getblk: block size invariant failed");
1166 #endif
1167 		bremfree(bp);
1168 		preserve = 1;
1169 	} else {
1170 		if ((bp = getnewbuf(slpflag, slptimeo, 0)) == NULL)
1171 			goto loop;
1172 
1173 		if (incore(vp, blkno) != NULL) {
1174 			/* The block has come into memory in the meantime. */
1175 			brelsel(bp, 0);
1176 			goto loop;
1177 		}
1178 
1179 		LIST_INSERT_HEAD(BUFHASH(vp, blkno), bp, b_hash);
1180 		bp->b_blkno = bp->b_lblkno = bp->b_rawblkno = blkno;
1181 		mutex_enter(vp->v_interlock);
1182 		bgetvp(vp, bp);
1183 		mutex_exit(vp->v_interlock);
1184 		preserve = 0;
1185 	}
1186 	mutex_exit(&bufcache_lock);
1187 
1188 	/*
1189 	 * LFS can't track total size of B_LOCKED buffer (locked_queue_bytes)
1190 	 * if we re-size buffers here.
1191 	 */
1192 	if (ISSET(bp->b_flags, B_LOCKED)) {
1193 		KASSERT(bp->b_bufsize >= size);
1194 	} else {
1195 		if (allocbuf(bp, size, preserve)) {
1196 			mutex_enter(&bufcache_lock);
1197 			LIST_REMOVE(bp, b_hash);
1198 			mutex_exit(&bufcache_lock);
1199 			brelse(bp, BC_INVAL);
1200 			return NULL;
1201 		}
1202 	}
1203 	BIO_SETPRIO(bp, BPRIO_DEFAULT);
1204 	return (bp);
1205 }
1206 
1207 /*
1208  * Get an empty, disassociated buffer of given size.
1209  */
1210 buf_t *
1211 geteblk(int size)
1212 {
1213 	buf_t *bp;
1214 	int error __diagused;
1215 
1216 	mutex_enter(&bufcache_lock);
1217 	while ((bp = getnewbuf(0, 0, 0)) == NULL)
1218 		;
1219 
1220 	SET(bp->b_cflags, BC_INVAL);
1221 	LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1222 	mutex_exit(&bufcache_lock);
1223 	BIO_SETPRIO(bp, BPRIO_DEFAULT);
1224 	error = allocbuf(bp, size, 0);
1225 	KASSERT(error == 0);
1226 	return (bp);
1227 }
1228 
1229 /*
1230  * Expand or contract the actual memory allocated to a buffer.
1231  *
1232  * If the buffer shrinks, data is lost, so it's up to the
1233  * caller to have written it out *first*; this routine will not
1234  * start a write.  If the buffer grows, it's the callers
1235  * responsibility to fill out the buffer's additional contents.
1236  */
1237 int
1238 allocbuf(buf_t *bp, int size, int preserve)
1239 {
1240 	void *addr;
1241 	vsize_t oldsize, desired_size;
1242 	int oldcount;
1243 	int delta;
1244 
1245 	desired_size = buf_roundsize(size);
1246 	if (desired_size > MAXBSIZE)
1247 		printf("allocbuf: buffer larger than MAXBSIZE requested");
1248 
1249 	oldcount = bp->b_bcount;
1250 
1251 	bp->b_bcount = size;
1252 
1253 	oldsize = bp->b_bufsize;
1254 	if (oldsize == desired_size) {
1255 		/*
1256 		 * Do not short cut the WAPBL resize, as the buffer length
1257 		 * could still have changed and this would corrupt the
1258 		 * tracking of the transaction length.
1259 		 */
1260 		goto out;
1261 	}
1262 
1263 	/*
1264 	 * If we want a buffer of a different size, re-allocate the
1265 	 * buffer's memory; copy old content only if needed.
1266 	 */
1267 	addr = buf_alloc(desired_size);
1268 	if (addr == NULL)
1269 		return ENOMEM;
1270 	if (preserve)
1271 		memcpy(addr, bp->b_data, MIN(oldsize,desired_size));
1272 	if (bp->b_data != NULL)
1273 		buf_mrelease(bp->b_data, oldsize);
1274 	bp->b_data = addr;
1275 	bp->b_bufsize = desired_size;
1276 
1277 	/*
1278 	 * Update overall buffer memory counter (protected by bufcache_lock)
1279 	 */
1280 	delta = (long)desired_size - (long)oldsize;
1281 
1282 	mutex_enter(&bufcache_lock);
1283 	if ((bufmem += delta) > bufmem_hiwater) {
1284 		/*
1285 		 * Need to trim overall memory usage.
1286 		 */
1287 		while (buf_canrelease()) {
1288 			if (curcpu()->ci_schedstate.spc_flags &
1289 			    SPCF_SHOULDYIELD) {
1290 				mutex_exit(&bufcache_lock);
1291 				preempt();
1292 				mutex_enter(&bufcache_lock);
1293 			}
1294 			if (buf_trim() == 0)
1295 				break;
1296 		}
1297 	}
1298 	mutex_exit(&bufcache_lock);
1299 
1300  out:
1301 	if (wapbl_vphaswapbl(bp->b_vp))
1302 		WAPBL_RESIZE_BUF(wapbl_vptomp(bp->b_vp), bp, oldsize, oldcount);
1303 
1304 	return 0;
1305 }
1306 
1307 /*
1308  * Find a buffer which is available for use.
1309  * Select something from a free list.
1310  * Preference is to AGE list, then LRU list.
1311  *
1312  * Called with the buffer queues locked.
1313  * Return buffer locked.
1314  */
1315 buf_t *
1316 getnewbuf(int slpflag, int slptimeo, int from_bufq)
1317 {
1318 	buf_t *bp;
1319 	struct vnode *vp;
1320 
1321  start:
1322 	KASSERT(mutex_owned(&bufcache_lock));
1323 
1324 	/*
1325 	 * Get a new buffer from the pool.
1326 	 */
1327 	if (!from_bufq && buf_lotsfree()) {
1328 		mutex_exit(&bufcache_lock);
1329 		bp = pool_cache_get(buf_cache, PR_NOWAIT);
1330 		if (bp != NULL) {
1331 			memset((char *)bp, 0, sizeof(*bp));
1332 			buf_init(bp);
1333 			SET(bp->b_cflags, BC_BUSY);	/* mark buffer busy */
1334 			mutex_enter(&bufcache_lock);
1335 #if defined(DIAGNOSTIC)
1336 			bp->b_freelistindex = -1;
1337 #endif /* defined(DIAGNOSTIC) */
1338 			return (bp);
1339 		}
1340 		mutex_enter(&bufcache_lock);
1341 	}
1342 
1343 	KASSERT(mutex_owned(&bufcache_lock));
1344 	if ((bp = TAILQ_FIRST(&bufqueues[BQ_AGE].bq_queue)) != NULL ||
1345 	    (bp = TAILQ_FIRST(&bufqueues[BQ_LRU].bq_queue)) != NULL) {
1346 	    	KASSERT(!ISSET(bp->b_cflags, BC_BUSY) || ISSET(bp->b_cflags, BC_VFLUSH));
1347 		bremfree(bp);
1348 
1349 		/* Buffer is no longer on free lists. */
1350 		SET(bp->b_cflags, BC_BUSY);
1351 	} else {
1352 		/*
1353 		 * XXX: !from_bufq should be removed.
1354 		 */
1355 		if (!from_bufq || curlwp != uvm.pagedaemon_lwp) {
1356 			/* wait for a free buffer of any kind */
1357 			if ((slpflag & PCATCH) != 0)
1358 				(void)cv_timedwait_sig(&needbuffer_cv,
1359 				    &bufcache_lock, slptimeo);
1360 			else
1361 				(void)cv_timedwait(&needbuffer_cv,
1362 				    &bufcache_lock, slptimeo);
1363 		}
1364 		return (NULL);
1365 	}
1366 
1367 #ifdef DIAGNOSTIC
1368 	if (bp->b_bufsize <= 0)
1369 		panic("buffer %p: on queue but empty", bp);
1370 #endif
1371 
1372 	if (ISSET(bp->b_cflags, BC_VFLUSH)) {
1373 		/*
1374 		 * This is a delayed write buffer being flushed to disk.  Make
1375 		 * sure it gets aged out of the queue when it's finished, and
1376 		 * leave it off the LRU queue.
1377 		 */
1378 		CLR(bp->b_cflags, BC_VFLUSH);
1379 		SET(bp->b_cflags, BC_AGE);
1380 		goto start;
1381 	}
1382 
1383 	KASSERT(ISSET(bp->b_cflags, BC_BUSY));
1384 	KASSERT(bp->b_refcnt > 0);
1385     	KASSERT(!cv_has_waiters(&bp->b_done));
1386 
1387 	/*
1388 	 * If buffer was a delayed write, start it and return NULL
1389 	 * (since we might sleep while starting the write).
1390 	 */
1391 	if (ISSET(bp->b_oflags, BO_DELWRI)) {
1392 		/*
1393 		 * This buffer has gone through the LRU, so make sure it gets
1394 		 * reused ASAP.
1395 		 */
1396 		SET(bp->b_cflags, BC_AGE);
1397 		mutex_exit(&bufcache_lock);
1398 		bawrite(bp);
1399 		mutex_enter(&bufcache_lock);
1400 		return (NULL);
1401 	}
1402 
1403 	vp = bp->b_vp;
1404 
1405 	/* clear out various other fields */
1406 	bp->b_cflags = BC_BUSY;
1407 	bp->b_oflags = 0;
1408 	bp->b_flags = 0;
1409 	bp->b_dev = NODEV;
1410 	bp->b_blkno = 0;
1411 	bp->b_lblkno = 0;
1412 	bp->b_rawblkno = 0;
1413 	bp->b_iodone = 0;
1414 	bp->b_error = 0;
1415 	bp->b_resid = 0;
1416 	bp->b_bcount = 0;
1417 
1418 	LIST_REMOVE(bp, b_hash);
1419 
1420 	/* Disassociate us from our vnode, if we had one... */
1421 	if (vp != NULL) {
1422 		mutex_enter(vp->v_interlock);
1423 		brelvp(bp);
1424 		mutex_exit(vp->v_interlock);
1425 	}
1426 
1427 	return (bp);
1428 }
1429 
1430 /*
1431  * Attempt to free an aged buffer off the queues.
1432  * Called with queue lock held.
1433  * Returns the amount of buffer memory freed.
1434  */
1435 static int
1436 buf_trim(void)
1437 {
1438 	buf_t *bp;
1439 	long size;
1440 
1441 	KASSERT(mutex_owned(&bufcache_lock));
1442 
1443 	/* Instruct getnewbuf() to get buffers off the queues */
1444 	if ((bp = getnewbuf(PCATCH, 1, 1)) == NULL)
1445 		return 0;
1446 
1447 	KASSERT((bp->b_cflags & BC_WANTED) == 0);
1448 	size = bp->b_bufsize;
1449 	bufmem -= size;
1450 	if (size > 0) {
1451 		buf_mrelease(bp->b_data, size);
1452 		bp->b_bcount = bp->b_bufsize = 0;
1453 	}
1454 	/* brelse() will return the buffer to the global buffer pool */
1455 	brelsel(bp, 0);
1456 	return size;
1457 }
1458 
1459 int
1460 buf_drain(int n)
1461 {
1462 	int size = 0, sz;
1463 
1464 	KASSERT(mutex_owned(&bufcache_lock));
1465 
1466 	while (size < n && bufmem > bufmem_lowater) {
1467 		sz = buf_trim();
1468 		if (sz <= 0)
1469 			break;
1470 		size += sz;
1471 	}
1472 
1473 	return size;
1474 }
1475 
1476 /*
1477  * Wait for operations on the buffer to complete.
1478  * When they do, extract and return the I/O's error value.
1479  */
1480 int
1481 biowait(buf_t *bp)
1482 {
1483 
1484 	KASSERT(ISSET(bp->b_cflags, BC_BUSY));
1485 	KASSERT(bp->b_refcnt > 0);
1486 
1487 	mutex_enter(bp->b_objlock);
1488 	while (!ISSET(bp->b_oflags, BO_DONE | BO_DELWRI))
1489 		cv_wait(&bp->b_done, bp->b_objlock);
1490 	mutex_exit(bp->b_objlock);
1491 
1492 	return bp->b_error;
1493 }
1494 
1495 /*
1496  * Mark I/O complete on a buffer.
1497  *
1498  * If a callback has been requested, e.g. the pageout
1499  * daemon, do so. Otherwise, awaken waiting processes.
1500  *
1501  * [ Leffler, et al., says on p.247:
1502  *	"This routine wakes up the blocked process, frees the buffer
1503  *	for an asynchronous write, or, for a request by the pagedaemon
1504  *	process, invokes a procedure specified in the buffer structure" ]
1505  *
1506  * In real life, the pagedaemon (or other system processes) wants
1507  * to do async stuff to, and doesn't want the buffer brelse()'d.
1508  * (for swap pager, that puts swap buffers on the free lists (!!!),
1509  * for the vn device, that puts allocated buffers on the free lists!)
1510  */
1511 void
1512 biodone(buf_t *bp)
1513 {
1514 	int s;
1515 
1516 	KASSERT(!ISSET(bp->b_oflags, BO_DONE));
1517 
1518 	if (cpu_intr_p()) {
1519 		/* From interrupt mode: defer to a soft interrupt. */
1520 		s = splvm();
1521 		TAILQ_INSERT_TAIL(&curcpu()->ci_data.cpu_biodone, bp, b_actq);
1522 		softint_schedule(biodone_sih);
1523 		splx(s);
1524 	} else {
1525 		/* Process now - the buffer may be freed soon. */
1526 		biodone2(bp);
1527 	}
1528 }
1529 
1530 static void
1531 biodone2(buf_t *bp)
1532 {
1533 	void (*callout)(buf_t *);
1534 
1535 	mutex_enter(bp->b_objlock);
1536 	/* Note that the transfer is done. */
1537 	if (ISSET(bp->b_oflags, BO_DONE))
1538 		panic("biodone2 already");
1539 	CLR(bp->b_flags, B_COWDONE);
1540 	SET(bp->b_oflags, BO_DONE);
1541 	BIO_SETPRIO(bp, BPRIO_DEFAULT);
1542 
1543 	/* Wake up waiting writers. */
1544 	if (!ISSET(bp->b_flags, B_READ))
1545 		vwakeup(bp);
1546 
1547 	if ((callout = bp->b_iodone) != NULL) {
1548 		/* Note callout done, then call out. */
1549 		KASSERT(!cv_has_waiters(&bp->b_done));
1550 		KERNEL_LOCK(1, NULL);		/* XXXSMP */
1551 		bp->b_iodone = NULL;
1552 		mutex_exit(bp->b_objlock);
1553 		(*callout)(bp);
1554 		KERNEL_UNLOCK_ONE(NULL);	/* XXXSMP */
1555 	} else if (ISSET(bp->b_flags, B_ASYNC)) {
1556 		/* If async, release. */
1557 		KASSERT(!cv_has_waiters(&bp->b_done));
1558 		mutex_exit(bp->b_objlock);
1559 		brelse(bp, 0);
1560 	} else {
1561 		/* Otherwise just wake up waiters in biowait(). */
1562 		cv_broadcast(&bp->b_done);
1563 		mutex_exit(bp->b_objlock);
1564 	}
1565 }
1566 
1567 static void
1568 biointr(void *cookie)
1569 {
1570 	struct cpu_info *ci;
1571 	buf_t *bp;
1572 	int s;
1573 
1574 	ci = curcpu();
1575 
1576 	while (!TAILQ_EMPTY(&ci->ci_data.cpu_biodone)) {
1577 		KASSERT(curcpu() == ci);
1578 
1579 		s = splvm();
1580 		bp = TAILQ_FIRST(&ci->ci_data.cpu_biodone);
1581 		TAILQ_REMOVE(&ci->ci_data.cpu_biodone, bp, b_actq);
1582 		splx(s);
1583 
1584 		biodone2(bp);
1585 	}
1586 }
1587 
1588 /*
1589  * Wait for all buffers to complete I/O
1590  * Return the number of "stuck" buffers.
1591  */
1592 int
1593 buf_syncwait(void)
1594 {
1595 	buf_t *bp;
1596 	int iter, nbusy, nbusy_prev = 0, ihash;
1597 
1598 	for (iter = 0; iter < 20;) {
1599 		mutex_enter(&bufcache_lock);
1600 		nbusy = 0;
1601 		for (ihash = 0; ihash < bufhash+1; ihash++) {
1602 		    LIST_FOREACH(bp, &bufhashtbl[ihash], b_hash) {
1603 			if ((bp->b_cflags & (BC_BUSY|BC_INVAL)) == BC_BUSY)
1604 				nbusy += ((bp->b_flags & B_READ) == 0);
1605 		    }
1606 		}
1607 		mutex_exit(&bufcache_lock);
1608 
1609 		if (nbusy == 0)
1610 			break;
1611 		if (nbusy_prev == 0)
1612 			nbusy_prev = nbusy;
1613 		printf("%d ", nbusy);
1614 		kpause("bflush", false, MAX(1, hz / 25 * iter), NULL);
1615 		if (nbusy >= nbusy_prev) /* we didn't flush anything */
1616 			iter++;
1617 		else
1618 			nbusy_prev = nbusy;
1619 	}
1620 
1621 	if (nbusy) {
1622 #if defined(DEBUG) || defined(DEBUG_HALT_BUSY)
1623 		printf("giving up\nPrinting vnodes for busy buffers\n");
1624 		for (ihash = 0; ihash < bufhash+1; ihash++) {
1625 		    LIST_FOREACH(bp, &bufhashtbl[ihash], b_hash) {
1626 			if ((bp->b_cflags & (BC_BUSY|BC_INVAL)) == BC_BUSY &&
1627 			    (bp->b_flags & B_READ) == 0)
1628 				vprint(NULL, bp->b_vp);
1629 		    }
1630 		}
1631 #endif
1632 	}
1633 
1634 	return nbusy;
1635 }
1636 
1637 static void
1638 sysctl_fillbuf(buf_t *i, struct buf_sysctl *o)
1639 {
1640 
1641 	o->b_flags = i->b_flags | i->b_cflags | i->b_oflags;
1642 	o->b_error = i->b_error;
1643 	o->b_prio = i->b_prio;
1644 	o->b_dev = i->b_dev;
1645 	o->b_bufsize = i->b_bufsize;
1646 	o->b_bcount = i->b_bcount;
1647 	o->b_resid = i->b_resid;
1648 	o->b_addr = PTRTOUINT64(i->b_data);
1649 	o->b_blkno = i->b_blkno;
1650 	o->b_rawblkno = i->b_rawblkno;
1651 	o->b_iodone = PTRTOUINT64(i->b_iodone);
1652 	o->b_proc = PTRTOUINT64(i->b_proc);
1653 	o->b_vp = PTRTOUINT64(i->b_vp);
1654 	o->b_saveaddr = PTRTOUINT64(i->b_saveaddr);
1655 	o->b_lblkno = i->b_lblkno;
1656 }
1657 
1658 #define KERN_BUFSLOP 20
1659 static int
1660 sysctl_dobuf(SYSCTLFN_ARGS)
1661 {
1662 	buf_t *bp;
1663 	struct buf_sysctl bs;
1664 	struct bqueue *bq;
1665 	char *dp;
1666 	u_int i, op, arg;
1667 	size_t len, needed, elem_size, out_size;
1668 	int error, elem_count, retries;
1669 
1670 	if (namelen == 1 && name[0] == CTL_QUERY)
1671 		return (sysctl_query(SYSCTLFN_CALL(rnode)));
1672 
1673 	if (namelen != 4)
1674 		return (EINVAL);
1675 
1676 	retries = 100;
1677  retry:
1678 	dp = oldp;
1679 	len = (oldp != NULL) ? *oldlenp : 0;
1680 	op = name[0];
1681 	arg = name[1];
1682 	elem_size = name[2];
1683 	elem_count = name[3];
1684 	out_size = MIN(sizeof(bs), elem_size);
1685 
1686 	/*
1687 	 * at the moment, these are just "placeholders" to make the
1688 	 * API for retrieving kern.buf data more extensible in the
1689 	 * future.
1690 	 *
1691 	 * XXX kern.buf currently has "netbsd32" issues.  hopefully
1692 	 * these will be resolved at a later point.
1693 	 */
1694 	if (op != KERN_BUF_ALL || arg != KERN_BUF_ALL ||
1695 	    elem_size < 1 || elem_count < 0)
1696 		return (EINVAL);
1697 
1698 	error = 0;
1699 	needed = 0;
1700 	sysctl_unlock();
1701 	mutex_enter(&bufcache_lock);
1702 	for (i = 0; i < BQUEUES; i++) {
1703 		bq = &bufqueues[i];
1704 		TAILQ_FOREACH(bp, &bq->bq_queue, b_freelist) {
1705 			bq->bq_marker = bp;
1706 			if (len >= elem_size && elem_count > 0) {
1707 				sysctl_fillbuf(bp, &bs);
1708 				mutex_exit(&bufcache_lock);
1709 				error = copyout(&bs, dp, out_size);
1710 				mutex_enter(&bufcache_lock);
1711 				if (error)
1712 					break;
1713 				if (bq->bq_marker != bp) {
1714 					/*
1715 					 * This sysctl node is only for
1716 					 * statistics.  Retry; if the
1717 					 * queue keeps changing, then
1718 					 * bail out.
1719 					 */
1720 					if (retries-- == 0) {
1721 						error = EAGAIN;
1722 						break;
1723 					}
1724 					mutex_exit(&bufcache_lock);
1725 					sysctl_relock();
1726 					goto retry;
1727 				}
1728 				dp += elem_size;
1729 				len -= elem_size;
1730 			}
1731 			needed += elem_size;
1732 			if (elem_count > 0 && elem_count != INT_MAX)
1733 				elem_count--;
1734 		}
1735 		if (error != 0)
1736 			break;
1737 	}
1738 	mutex_exit(&bufcache_lock);
1739 	sysctl_relock();
1740 
1741 	*oldlenp = needed;
1742 	if (oldp == NULL)
1743 		*oldlenp += KERN_BUFSLOP * sizeof(buf_t);
1744 
1745 	return (error);
1746 }
1747 
1748 static int
1749 sysctl_bufvm_update(SYSCTLFN_ARGS)
1750 {
1751 	int error, rv;
1752 	struct sysctlnode node;
1753 	unsigned int temp_bufcache;
1754 	unsigned long temp_water;
1755 
1756 	/* Take a copy of the supplied node and its data */
1757 	node = *rnode;
1758 	if (node.sysctl_data == &bufcache) {
1759 	    node.sysctl_data = &temp_bufcache;
1760 	    temp_bufcache = *(unsigned int *)rnode->sysctl_data;
1761 	} else {
1762 	    node.sysctl_data = &temp_water;
1763 	    temp_water = *(unsigned long *)rnode->sysctl_data;
1764 	}
1765 
1766 	/* Update the copy */
1767 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
1768 	if (error || newp == NULL)
1769 		return (error);
1770 
1771 	if (rnode->sysctl_data == &bufcache) {
1772 		if (temp_bufcache > 100)
1773 			return (EINVAL);
1774 		bufcache = temp_bufcache;
1775 		buf_setwm();
1776 	} else if (rnode->sysctl_data == &bufmem_lowater) {
1777 		if (bufmem_hiwater - temp_water < 16)
1778 			return (EINVAL);
1779 		bufmem_lowater = temp_water;
1780 	} else if (rnode->sysctl_data == &bufmem_hiwater) {
1781 		if (temp_water - bufmem_lowater < 16)
1782 			return (EINVAL);
1783 		bufmem_hiwater = temp_water;
1784 	} else
1785 		return (EINVAL);
1786 
1787 	/* Drain until below new high water mark */
1788 	sysctl_unlock();
1789 	mutex_enter(&bufcache_lock);
1790 	while (bufmem > bufmem_hiwater) {
1791 		rv = buf_drain((bufmem - bufmem_hiwater) / (2 * 1024));
1792 		if (rv <= 0)
1793 			break;
1794 	}
1795 	mutex_exit(&bufcache_lock);
1796 	sysctl_relock();
1797 
1798 	return 0;
1799 }
1800 
1801 static struct sysctllog *vfsbio_sysctllog;
1802 
1803 static void
1804 sysctl_kern_buf_setup(void)
1805 {
1806 
1807 	sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
1808 		       CTLFLAG_PERMANENT,
1809 		       CTLTYPE_NODE, "kern", NULL,
1810 		       NULL, 0, NULL, 0,
1811 		       CTL_KERN, CTL_EOL);
1812 	sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
1813 		       CTLFLAG_PERMANENT,
1814 		       CTLTYPE_NODE, "buf",
1815 		       SYSCTL_DESCR("Kernel buffer cache information"),
1816 		       sysctl_dobuf, 0, NULL, 0,
1817 		       CTL_KERN, KERN_BUF, CTL_EOL);
1818 }
1819 
1820 static void
1821 sysctl_vm_buf_setup(void)
1822 {
1823 
1824 	sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
1825 		       CTLFLAG_PERMANENT,
1826 		       CTLTYPE_NODE, "vm", NULL,
1827 		       NULL, 0, NULL, 0,
1828 		       CTL_VM, CTL_EOL);
1829 	sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
1830 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1831 		       CTLTYPE_INT, "bufcache",
1832 		       SYSCTL_DESCR("Percentage of physical memory to use for "
1833 				    "buffer cache"),
1834 		       sysctl_bufvm_update, 0, &bufcache, 0,
1835 		       CTL_VM, CTL_CREATE, CTL_EOL);
1836 	sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
1837 		       CTLFLAG_PERMANENT|CTLFLAG_READONLY,
1838 		       CTLTYPE_LONG, "bufmem",
1839 		       SYSCTL_DESCR("Amount of kernel memory used by buffer "
1840 				    "cache"),
1841 		       NULL, 0, &bufmem, 0,
1842 		       CTL_VM, CTL_CREATE, CTL_EOL);
1843 	sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
1844 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1845 		       CTLTYPE_LONG, "bufmem_lowater",
1846 		       SYSCTL_DESCR("Minimum amount of kernel memory to "
1847 				    "reserve for buffer cache"),
1848 		       sysctl_bufvm_update, 0, &bufmem_lowater, 0,
1849 		       CTL_VM, CTL_CREATE, CTL_EOL);
1850 	sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
1851 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1852 		       CTLTYPE_LONG, "bufmem_hiwater",
1853 		       SYSCTL_DESCR("Maximum amount of kernel memory to use "
1854 				    "for buffer cache"),
1855 		       sysctl_bufvm_update, 0, &bufmem_hiwater, 0,
1856 		       CTL_VM, CTL_CREATE, CTL_EOL);
1857 }
1858 
1859 #ifdef DEBUG
1860 /*
1861  * Print out statistics on the current allocation of the buffer pool.
1862  * Can be enabled to print out on every ``sync'' by setting "syncprt"
1863  * in vfs_syscalls.c using sysctl.
1864  */
1865 void
1866 vfs_bufstats(void)
1867 {
1868 	int i, j, count;
1869 	buf_t *bp;
1870 	struct bqueue *dp;
1871 	int counts[(MAXBSIZE / PAGE_SIZE) + 1];
1872 	static const char *bname[BQUEUES] = { "LOCKED", "LRU", "AGE" };
1873 
1874 	for (dp = bufqueues, i = 0; dp < &bufqueues[BQUEUES]; dp++, i++) {
1875 		count = 0;
1876 		for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
1877 			counts[j] = 0;
1878 		TAILQ_FOREACH(bp, &dp->bq_queue, b_freelist) {
1879 			counts[bp->b_bufsize/PAGE_SIZE]++;
1880 			count++;
1881 		}
1882 		printf("%s: total-%d", bname[i], count);
1883 		for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
1884 			if (counts[j] != 0)
1885 				printf(", %d-%d", j * PAGE_SIZE, counts[j]);
1886 		printf("\n");
1887 	}
1888 }
1889 #endif /* DEBUG */
1890 
1891 /* ------------------------------ */
1892 
1893 buf_t *
1894 getiobuf(struct vnode *vp, bool waitok)
1895 {
1896 	buf_t *bp;
1897 
1898 	bp = pool_cache_get(bufio_cache, (waitok ? PR_WAITOK : PR_NOWAIT));
1899 	if (bp == NULL)
1900 		return bp;
1901 
1902 	buf_init(bp);
1903 
1904 	if ((bp->b_vp = vp) == NULL)
1905 		bp->b_objlock = &buffer_lock;
1906 	else
1907 		bp->b_objlock = vp->v_interlock;
1908 
1909 	return bp;
1910 }
1911 
1912 void
1913 putiobuf(buf_t *bp)
1914 {
1915 
1916 	buf_destroy(bp);
1917 	pool_cache_put(bufio_cache, bp);
1918 }
1919 
1920 /*
1921  * nestiobuf_iodone: b_iodone callback for nested buffers.
1922  */
1923 
1924 void
1925 nestiobuf_iodone(buf_t *bp)
1926 {
1927 	buf_t *mbp = bp->b_private;
1928 	int error;
1929 	int donebytes;
1930 
1931 	KASSERT(bp->b_bcount <= bp->b_bufsize);
1932 	KASSERT(mbp != bp);
1933 
1934 	error = bp->b_error;
1935 	if (bp->b_error == 0 &&
1936 	    (bp->b_bcount < bp->b_bufsize || bp->b_resid > 0)) {
1937 		/*
1938 		 * Not all got transfered, raise an error. We have no way to
1939 		 * propagate these conditions to mbp.
1940 		 */
1941 		error = EIO;
1942 	}
1943 
1944 	donebytes = bp->b_bufsize;
1945 
1946 	putiobuf(bp);
1947 	nestiobuf_done(mbp, donebytes, error);
1948 }
1949 
1950 /*
1951  * nestiobuf_setup: setup a "nested" buffer.
1952  *
1953  * => 'mbp' is a "master" buffer which is being divided into sub pieces.
1954  * => 'bp' should be a buffer allocated by getiobuf.
1955  * => 'offset' is a byte offset in the master buffer.
1956  * => 'size' is a size in bytes of this nested buffer.
1957  */
1958 
1959 void
1960 nestiobuf_setup(buf_t *mbp, buf_t *bp, int offset, size_t size)
1961 {
1962 	const int b_read = mbp->b_flags & B_READ;
1963 	struct vnode *vp = mbp->b_vp;
1964 
1965 	KASSERT(mbp->b_bcount >= offset + size);
1966 	bp->b_vp = vp;
1967 	bp->b_dev = mbp->b_dev;
1968 	bp->b_objlock = mbp->b_objlock;
1969 	bp->b_cflags = BC_BUSY;
1970 	bp->b_flags = B_ASYNC | b_read;
1971 	bp->b_iodone = nestiobuf_iodone;
1972 	bp->b_data = (char *)mbp->b_data + offset;
1973 	bp->b_resid = bp->b_bcount = size;
1974 	bp->b_bufsize = bp->b_bcount;
1975 	bp->b_private = mbp;
1976 	BIO_COPYPRIO(bp, mbp);
1977 	if (!b_read && vp != NULL) {
1978 		mutex_enter(vp->v_interlock);
1979 		vp->v_numoutput++;
1980 		mutex_exit(vp->v_interlock);
1981 	}
1982 }
1983 
1984 /*
1985  * nestiobuf_done: propagate completion to the master buffer.
1986  *
1987  * => 'donebytes' specifies how many bytes in the 'mbp' is completed.
1988  * => 'error' is an errno(2) that 'donebytes' has been completed with.
1989  */
1990 
1991 void
1992 nestiobuf_done(buf_t *mbp, int donebytes, int error)
1993 {
1994 
1995 	if (donebytes == 0) {
1996 		return;
1997 	}
1998 	mutex_enter(mbp->b_objlock);
1999 	KASSERT(mbp->b_resid >= donebytes);
2000 	mbp->b_resid -= donebytes;
2001 	if (error)
2002 		mbp->b_error = error;
2003 	if (mbp->b_resid == 0) {
2004 		if (mbp->b_error)
2005 			mbp->b_resid = mbp->b_bcount;
2006 		mutex_exit(mbp->b_objlock);
2007 		biodone(mbp);
2008 	} else
2009 		mutex_exit(mbp->b_objlock);
2010 }
2011 
2012 void
2013 buf_init(buf_t *bp)
2014 {
2015 
2016 	cv_init(&bp->b_busy, "biolock");
2017 	cv_init(&bp->b_done, "biowait");
2018 	bp->b_dev = NODEV;
2019 	bp->b_error = 0;
2020 	bp->b_flags = 0;
2021 	bp->b_cflags = 0;
2022 	bp->b_oflags = 0;
2023 	bp->b_objlock = &buffer_lock;
2024 	bp->b_iodone = NULL;
2025 	bp->b_refcnt = 1;
2026 	bp->b_dev = NODEV;
2027 	bp->b_vnbufs.le_next = NOLIST;
2028 	BIO_SETPRIO(bp, BPRIO_DEFAULT);
2029 }
2030 
2031 void
2032 buf_destroy(buf_t *bp)
2033 {
2034 
2035 	cv_destroy(&bp->b_done);
2036 	cv_destroy(&bp->b_busy);
2037 }
2038 
2039 int
2040 bbusy(buf_t *bp, bool intr, int timo, kmutex_t *interlock)
2041 {
2042 	int error;
2043 
2044 	KASSERT(mutex_owned(&bufcache_lock));
2045 
2046 	if ((bp->b_cflags & BC_BUSY) != 0) {
2047 		if (curlwp == uvm.pagedaemon_lwp)
2048 			return EDEADLK;
2049 		bp->b_cflags |= BC_WANTED;
2050 		bref(bp);
2051 		if (interlock != NULL)
2052 			mutex_exit(interlock);
2053 		if (intr) {
2054 			error = cv_timedwait_sig(&bp->b_busy, &bufcache_lock,
2055 			    timo);
2056 		} else {
2057 			error = cv_timedwait(&bp->b_busy, &bufcache_lock,
2058 			    timo);
2059 		}
2060 		brele(bp);
2061 		if (interlock != NULL)
2062 			mutex_enter(interlock);
2063 		if (error != 0)
2064 			return error;
2065 		return EPASSTHROUGH;
2066 	}
2067 	bp->b_cflags |= BC_BUSY;
2068 
2069 	return 0;
2070 }
2071