xref: /netbsd-src/sys/kern/vfs_bio.c (revision 9ddb6ab554e70fb9bbd90c3d96b812bc57755a14)
1 /*	$NetBSD: vfs_bio.c,v 1.236 2012/02/01 23:43:49 para 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.236 2012/02/01 23:43:49 para 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 
400 	/*
401 	 * Determine the upper bound of memory to use for buffers.
402 	 *
403 	 *	- If bufpages is specified, use that as the number
404 	 *	  pages.
405 	 *
406 	 *	- Otherwise, use bufcache as the percentage of
407 	 *	  physical memory.
408 	 */
409 	if (bufpages != 0) {
410 		n = bufpages;
411 	} else {
412 		if (bufcache < 5) {
413 			printf("forcing bufcache %d -> 5", bufcache);
414 			bufcache = 5;
415 		}
416 		if (bufcache > 95) {
417 			printf("forcing bufcache %d -> 95", bufcache);
418 			bufcache = 95;
419 		}
420 		n = calc_cache_size(buf_map, bufcache,
421 		    (buf_map != kernel_map) ? 100 : BUFCACHE_VA_MAXPCT)
422 		    / PAGE_SIZE;
423 	}
424 
425 	n <<= PAGE_SHIFT;
426 	if (bufmem_valimit != 0 && n > bufmem_valimit)
427 		n = bufmem_valimit;
428 
429 	return (n);
430 }
431 
432 /*
433  * Initialize buffers and hash links for buffers.
434  */
435 void
436 bufinit(void)
437 {
438 	struct bqueue *dp;
439 	int use_std;
440 	u_int i;
441 
442 	mutex_init(&bufcache_lock, MUTEX_DEFAULT, IPL_NONE);
443 	mutex_init(&buffer_lock, MUTEX_DEFAULT, IPL_NONE);
444 	cv_init(&needbuffer_cv, "needbuf");
445 
446 	if (bufmem_valimit != 0) {
447 		vaddr_t minaddr = 0, maxaddr;
448 		buf_map = uvm_km_suballoc(kernel_map, &minaddr, &maxaddr,
449 					  bufmem_valimit, 0, false, 0);
450 		if (buf_map == NULL)
451 			panic("bufinit: cannot allocate submap");
452 	} else
453 		buf_map = kernel_map;
454 
455 	/*
456 	 * Initialize buffer cache memory parameters.
457 	 */
458 	bufmem = 0;
459 	buf_setwm();
460 
461 	/* On "small" machines use small pool page sizes where possible */
462 	use_std = (physmem < atop(16*1024*1024));
463 
464 	/*
465 	 * Also use them on systems that can map the pool pages using
466 	 * a direct-mapped segment.
467 	 */
468 #ifdef PMAP_MAP_POOLPAGE
469 	use_std = 1;
470 #endif
471 
472 	buf_cache = pool_cache_init(sizeof(buf_t), 0, 0, 0,
473 	    "bufpl", NULL, IPL_SOFTBIO, NULL, NULL, NULL);
474 	bufio_cache = pool_cache_init(sizeof(buf_t), 0, 0, 0,
475 	    "biopl", NULL, IPL_BIO, NULL, NULL, NULL);
476 
477 	for (i = 0; i < NMEMPOOLS; i++) {
478 		struct pool_allocator *pa;
479 		struct pool *pp = &bmempools[i];
480 		u_int size = 1 << (i + MEMPOOL_INDEX_OFFSET);
481 		char *name = kmem_alloc(8, KM_SLEEP); /* XXX: never freed */
482 		if (__predict_false(size >= 1048576))
483 			(void)snprintf(name, 8, "buf%um", size / 1048576);
484 		else if (__predict_true(size >= 1024))
485 			(void)snprintf(name, 8, "buf%uk", size / 1024);
486 		else
487 			(void)snprintf(name, 8, "buf%ub", size);
488 		pa = (size <= PAGE_SIZE && use_std)
489 			? &pool_allocator_nointr
490 			: &bufmempool_allocator;
491 		pool_init(pp, size, 0, 0, 0, name, pa, IPL_NONE);
492 		pool_setlowat(pp, 1);
493 		pool_sethiwat(pp, 1);
494 	}
495 
496 	/* Initialize the buffer queues */
497 	for (dp = bufqueues; dp < &bufqueues[BQUEUES]; dp++) {
498 		TAILQ_INIT(&dp->bq_queue);
499 		dp->bq_bytes = 0;
500 	}
501 
502 	/*
503 	 * Estimate hash table size based on the amount of memory we
504 	 * intend to use for the buffer cache. The average buffer
505 	 * size is dependent on our clients (i.e. filesystems).
506 	 *
507 	 * For now, use an empirical 3K per buffer.
508 	 */
509 	nbuf = (bufmem_hiwater / 1024) / 3;
510 	bufhashtbl = hashinit(nbuf, HASH_LIST, true, &bufhash);
511 
512 	sysctl_kern_buf_setup();
513 	sysctl_vm_buf_setup();
514 }
515 
516 void
517 bufinit2(void)
518 {
519 
520 	biodone_sih = softint_establish(SOFTINT_BIO | SOFTINT_MPSAFE, biointr,
521 	    NULL);
522 	if (biodone_sih == NULL)
523 		panic("bufinit2: can't establish soft interrupt");
524 }
525 
526 static int
527 buf_lotsfree(void)
528 {
529 	int try, thresh;
530 
531 	/* Always allocate if less than the low water mark. */
532 	if (bufmem < bufmem_lowater)
533 		return 1;
534 
535 	/* Never allocate if greater than the high water mark. */
536 	if (bufmem > bufmem_hiwater)
537 		return 0;
538 
539 	/* If there's anything on the AGE list, it should be eaten. */
540 	if (TAILQ_FIRST(&bufqueues[BQ_AGE].bq_queue) != NULL)
541 		return 0;
542 
543 	/*
544 	 * The probabily of getting a new allocation is inversely
545 	 * proportional to the current size of the cache, using
546 	 * a granularity of 16 steps.
547 	 */
548 	try = random() & 0x0000000fL;
549 
550 	/* Don't use "16 * bufmem" here to avoid a 32-bit overflow. */
551 	thresh = (bufmem - bufmem_lowater) /
552 	    ((bufmem_hiwater - bufmem_lowater) / 16);
553 
554 	if (try >= thresh)
555 		return 1;
556 
557 	/* Otherwise don't allocate. */
558 	return 0;
559 }
560 
561 /*
562  * Return estimate of bytes we think need to be
563  * released to help resolve low memory conditions.
564  *
565  * => called with bufcache_lock held.
566  */
567 static int
568 buf_canrelease(void)
569 {
570 	int pagedemand, ninvalid = 0;
571 
572 	KASSERT(mutex_owned(&bufcache_lock));
573 
574 	if (bufmem < bufmem_lowater)
575 		return 0;
576 
577 	if (bufmem > bufmem_hiwater)
578 		return bufmem - bufmem_hiwater;
579 
580 	ninvalid += bufqueues[BQ_AGE].bq_bytes;
581 
582 	pagedemand = uvmexp.freetarg - uvmexp.free;
583 	if (pagedemand < 0)
584 		return ninvalid;
585 	return MAX(ninvalid, MIN(2 * MAXBSIZE,
586 	    MIN((bufmem - bufmem_lowater) / 16, pagedemand * PAGE_SIZE)));
587 }
588 
589 /*
590  * Buffer memory allocation helper functions
591  */
592 static u_long
593 buf_mempoolidx(u_long size)
594 {
595 	u_int n = 0;
596 
597 	size -= 1;
598 	size >>= MEMPOOL_INDEX_OFFSET;
599 	while (size) {
600 		size >>= 1;
601 		n += 1;
602 	}
603 	if (n >= NMEMPOOLS)
604 		panic("buf mem pool index %d", n);
605 	return n;
606 }
607 
608 static u_long
609 buf_roundsize(u_long size)
610 {
611 	/* Round up to nearest power of 2 */
612 	return (1 << (buf_mempoolidx(size) + MEMPOOL_INDEX_OFFSET));
613 }
614 
615 static void *
616 buf_alloc(size_t size)
617 {
618 	u_int n = buf_mempoolidx(size);
619 	void *addr;
620 
621 	while (1) {
622 		addr = pool_get(&bmempools[n], PR_NOWAIT);
623 		if (addr != NULL)
624 			break;
625 
626 		/* No memory, see if we can free some. If so, try again */
627 		mutex_enter(&bufcache_lock);
628 		if (buf_drain(1) > 0) {
629 			mutex_exit(&bufcache_lock);
630 			continue;
631 		}
632 
633 		if (curlwp == uvm.pagedaemon_lwp) {
634 			mutex_exit(&bufcache_lock);
635 			return NULL;
636 		}
637 
638 		/* Wait for buffers to arrive on the LRU queue */
639 		cv_timedwait(&needbuffer_cv, &bufcache_lock, hz / 4);
640 		mutex_exit(&bufcache_lock);
641 	}
642 
643 	return addr;
644 }
645 
646 static void
647 buf_mrelease(void *addr, size_t size)
648 {
649 
650 	pool_put(&bmempools[buf_mempoolidx(size)], addr);
651 }
652 
653 /*
654  * bread()/breadn() helper.
655  */
656 static buf_t *
657 bio_doread(struct vnode *vp, daddr_t blkno, int size, kauth_cred_t cred,
658     int async)
659 {
660 	buf_t *bp;
661 	struct mount *mp;
662 
663 	bp = getblk(vp, blkno, size, 0, 0);
664 
665 #ifdef DIAGNOSTIC
666 	if (bp == NULL) {
667 		panic("bio_doread: no such buf");
668 	}
669 #endif
670 
671 	/*
672 	 * If buffer does not have data valid, start a read.
673 	 * Note that if buffer is BC_INVAL, getblk() won't return it.
674 	 * Therefore, it's valid if its I/O has completed or been delayed.
675 	 */
676 	if (!ISSET(bp->b_oflags, (BO_DONE | BO_DELWRI))) {
677 		/* Start I/O for the buffer. */
678 		SET(bp->b_flags, B_READ | async);
679 		if (async)
680 			BIO_SETPRIO(bp, BPRIO_TIMELIMITED);
681 		else
682 			BIO_SETPRIO(bp, BPRIO_TIMECRITICAL);
683 		VOP_STRATEGY(vp, bp);
684 
685 		/* Pay for the read. */
686 		curlwp->l_ru.ru_inblock++;
687 	} else if (async)
688 		brelse(bp, 0);
689 
690 	if (vp->v_type == VBLK)
691 		mp = vp->v_specmountpoint;
692 	else
693 		mp = vp->v_mount;
694 
695 	/*
696 	 * Collect statistics on synchronous and asynchronous reads.
697 	 * Reads from block devices are charged to their associated
698 	 * filesystem (if any).
699 	 */
700 	if (mp != NULL) {
701 		if (async == 0)
702 			mp->mnt_stat.f_syncreads++;
703 		else
704 			mp->mnt_stat.f_asyncreads++;
705 	}
706 
707 	return (bp);
708 }
709 
710 /*
711  * Read a disk block.
712  * This algorithm described in Bach (p.54).
713  */
714 int
715 bread(struct vnode *vp, daddr_t blkno, int size, kauth_cred_t cred,
716     int flags, buf_t **bpp)
717 {
718 	buf_t *bp;
719 	int error;
720 
721 	/* Get buffer for block. */
722 	bp = *bpp = bio_doread(vp, blkno, size, cred, 0);
723 
724 	/* Wait for the read to complete, and return result. */
725 	error = biowait(bp);
726 	if (error == 0 && (flags & B_MODIFY) != 0)
727 		error = fscow_run(bp, true);
728 
729 	return error;
730 }
731 
732 /*
733  * Read-ahead multiple disk blocks. The first is sync, the rest async.
734  * Trivial modification to the breada algorithm presented in Bach (p.55).
735  */
736 int
737 breadn(struct vnode *vp, daddr_t blkno, int size, daddr_t *rablks,
738     int *rasizes, int nrablks, kauth_cred_t cred, int flags, buf_t **bpp)
739 {
740 	buf_t *bp;
741 	int error, i;
742 
743 	bp = *bpp = bio_doread(vp, blkno, size, cred, 0);
744 
745 	/*
746 	 * For each of the read-ahead blocks, start a read, if necessary.
747 	 */
748 	mutex_enter(&bufcache_lock);
749 	for (i = 0; i < nrablks; i++) {
750 		/* If it's in the cache, just go on to next one. */
751 		if (incore(vp, rablks[i]))
752 			continue;
753 
754 		/* Get a buffer for the read-ahead block */
755 		mutex_exit(&bufcache_lock);
756 		(void) bio_doread(vp, rablks[i], rasizes[i], cred, B_ASYNC);
757 		mutex_enter(&bufcache_lock);
758 	}
759 	mutex_exit(&bufcache_lock);
760 
761 	/* Otherwise, we had to start a read for it; wait until it's valid. */
762 	error = biowait(bp);
763 	if (error == 0 && (flags & B_MODIFY) != 0)
764 		error = fscow_run(bp, true);
765 	return error;
766 }
767 
768 /*
769  * Block write.  Described in Bach (p.56)
770  */
771 int
772 bwrite(buf_t *bp)
773 {
774 	int rv, sync, wasdelayed;
775 	struct vnode *vp;
776 	struct mount *mp;
777 
778 	KASSERT(ISSET(bp->b_cflags, BC_BUSY));
779 	KASSERT(!cv_has_waiters(&bp->b_done));
780 
781 	vp = bp->b_vp;
782 	if (vp != NULL) {
783 		KASSERT(bp->b_objlock == vp->v_interlock);
784 		if (vp->v_type == VBLK)
785 			mp = vp->v_specmountpoint;
786 		else
787 			mp = vp->v_mount;
788 	} else {
789 		mp = NULL;
790 	}
791 
792 	if (mp && mp->mnt_wapbl) {
793 		if (bp->b_iodone != mp->mnt_wapbl_op->wo_wapbl_biodone) {
794 			bdwrite(bp);
795 			return 0;
796 		}
797 	}
798 
799 	/*
800 	 * Remember buffer type, to switch on it later.  If the write was
801 	 * synchronous, but the file system was mounted with MNT_ASYNC,
802 	 * convert it to a delayed write.
803 	 * XXX note that this relies on delayed tape writes being converted
804 	 * to async, not sync writes (which is safe, but ugly).
805 	 */
806 	sync = !ISSET(bp->b_flags, B_ASYNC);
807 	if (sync && mp != NULL && ISSET(mp->mnt_flag, MNT_ASYNC)) {
808 		bdwrite(bp);
809 		return (0);
810 	}
811 
812 	/*
813 	 * Collect statistics on synchronous and asynchronous writes.
814 	 * Writes to block devices are charged to their associated
815 	 * filesystem (if any).
816 	 */
817 	if (mp != NULL) {
818 		if (sync)
819 			mp->mnt_stat.f_syncwrites++;
820 		else
821 			mp->mnt_stat.f_asyncwrites++;
822 	}
823 
824 	/*
825 	 * Pay for the I/O operation and make sure the buf is on the correct
826 	 * vnode queue.
827 	 */
828 	bp->b_error = 0;
829 	wasdelayed = ISSET(bp->b_oflags, BO_DELWRI);
830 	CLR(bp->b_flags, B_READ);
831 	if (wasdelayed) {
832 		mutex_enter(&bufcache_lock);
833 		mutex_enter(bp->b_objlock);
834 		CLR(bp->b_oflags, BO_DONE | BO_DELWRI);
835 		reassignbuf(bp, bp->b_vp);
836 		mutex_exit(&bufcache_lock);
837 	} else {
838 		curlwp->l_ru.ru_oublock++;
839 		mutex_enter(bp->b_objlock);
840 		CLR(bp->b_oflags, BO_DONE | BO_DELWRI);
841 	}
842 	if (vp != NULL)
843 		vp->v_numoutput++;
844 	mutex_exit(bp->b_objlock);
845 
846 	/* Initiate disk write. */
847 	if (sync)
848 		BIO_SETPRIO(bp, BPRIO_TIMECRITICAL);
849 	else
850 		BIO_SETPRIO(bp, BPRIO_TIMELIMITED);
851 
852 	VOP_STRATEGY(vp, bp);
853 
854 	if (sync) {
855 		/* If I/O was synchronous, wait for it to complete. */
856 		rv = biowait(bp);
857 
858 		/* Release the buffer. */
859 		brelse(bp, 0);
860 
861 		return (rv);
862 	} else {
863 		return (0);
864 	}
865 }
866 
867 int
868 vn_bwrite(void *v)
869 {
870 	struct vop_bwrite_args *ap = v;
871 
872 	return (bwrite(ap->a_bp));
873 }
874 
875 /*
876  * Delayed write.
877  *
878  * The buffer is marked dirty, but is not queued for I/O.
879  * This routine should be used when the buffer is expected
880  * to be modified again soon, typically a small write that
881  * partially fills a buffer.
882  *
883  * NB: magnetic tapes cannot be delayed; they must be
884  * written in the order that the writes are requested.
885  *
886  * Described in Leffler, et al. (pp. 208-213).
887  */
888 void
889 bdwrite(buf_t *bp)
890 {
891 
892 	KASSERT(bp->b_vp == NULL || bp->b_vp->v_tag != VT_UFS ||
893 	    bp->b_vp->v_type == VBLK || ISSET(bp->b_flags, B_COWDONE));
894 	KASSERT(ISSET(bp->b_cflags, BC_BUSY));
895 	KASSERT(!cv_has_waiters(&bp->b_done));
896 
897 	/* If this is a tape block, write the block now. */
898 	if (bdev_type(bp->b_dev) == D_TAPE) {
899 		bawrite(bp);
900 		return;
901 	}
902 
903 	if (wapbl_vphaswapbl(bp->b_vp)) {
904 		struct mount *mp = wapbl_vptomp(bp->b_vp);
905 
906 		if (bp->b_iodone != mp->mnt_wapbl_op->wo_wapbl_biodone) {
907 			WAPBL_ADD_BUF(mp, bp);
908 		}
909 	}
910 
911 	/*
912 	 * If the block hasn't been seen before:
913 	 *	(1) Mark it as having been seen,
914 	 *	(2) Charge for the write,
915 	 *	(3) Make sure it's on its vnode's correct block list.
916 	 */
917 	KASSERT(bp->b_vp == NULL || bp->b_objlock == bp->b_vp->v_interlock);
918 
919 	if (!ISSET(bp->b_oflags, BO_DELWRI)) {
920 		mutex_enter(&bufcache_lock);
921 		mutex_enter(bp->b_objlock);
922 		SET(bp->b_oflags, BO_DELWRI);
923 		curlwp->l_ru.ru_oublock++;
924 		reassignbuf(bp, bp->b_vp);
925 		mutex_exit(&bufcache_lock);
926 	} else {
927 		mutex_enter(bp->b_objlock);
928 	}
929 	/* Otherwise, the "write" is done, so mark and release the buffer. */
930 	CLR(bp->b_oflags, BO_DONE);
931 	mutex_exit(bp->b_objlock);
932 
933 	brelse(bp, 0);
934 }
935 
936 /*
937  * Asynchronous block write; just an asynchronous bwrite().
938  */
939 void
940 bawrite(buf_t *bp)
941 {
942 
943 	KASSERT(ISSET(bp->b_cflags, BC_BUSY));
944 	KASSERT(bp->b_vp != NULL);
945 
946 	SET(bp->b_flags, B_ASYNC);
947 	VOP_BWRITE(bp->b_vp, bp);
948 }
949 
950 /*
951  * Release a buffer on to the free lists.
952  * Described in Bach (p. 46).
953  */
954 void
955 brelsel(buf_t *bp, int set)
956 {
957 	struct bqueue *bufq;
958 	struct vnode *vp;
959 
960 	KASSERT(mutex_owned(&bufcache_lock));
961 	KASSERT(!cv_has_waiters(&bp->b_done));
962 	KASSERT(bp->b_refcnt > 0);
963 
964 	SET(bp->b_cflags, set);
965 
966 	KASSERT(ISSET(bp->b_cflags, BC_BUSY));
967 	KASSERT(bp->b_iodone == NULL);
968 
969 	/* Wake up any processes waiting for any buffer to become free. */
970 	cv_signal(&needbuffer_cv);
971 
972 	/* Wake up any proceeses waiting for _this_ buffer to become */
973 	if (ISSET(bp->b_cflags, BC_WANTED))
974 		CLR(bp->b_cflags, BC_WANTED|BC_AGE);
975 
976 	/* If it's clean clear the copy-on-write flag. */
977 	if (ISSET(bp->b_flags, B_COWDONE)) {
978 		mutex_enter(bp->b_objlock);
979 		if (!ISSET(bp->b_oflags, BO_DELWRI))
980 			CLR(bp->b_flags, B_COWDONE);
981 		mutex_exit(bp->b_objlock);
982 	}
983 
984 	/*
985 	 * Determine which queue the buffer should be on, then put it there.
986 	 */
987 
988 	/* If it's locked, don't report an error; try again later. */
989 	if (ISSET(bp->b_flags, B_LOCKED))
990 		bp->b_error = 0;
991 
992 	/* If it's not cacheable, or an error, mark it invalid. */
993 	if (ISSET(bp->b_cflags, BC_NOCACHE) || bp->b_error != 0)
994 		SET(bp->b_cflags, BC_INVAL);
995 
996 	if (ISSET(bp->b_cflags, BC_VFLUSH)) {
997 		/*
998 		 * This is a delayed write buffer that was just flushed to
999 		 * disk.  It is still on the LRU queue.  If it's become
1000 		 * invalid, then we need to move it to a different queue;
1001 		 * otherwise leave it in its current position.
1002 		 */
1003 		CLR(bp->b_cflags, BC_VFLUSH);
1004 		if (!ISSET(bp->b_cflags, BC_INVAL|BC_AGE) &&
1005 		    !ISSET(bp->b_flags, B_LOCKED) && bp->b_error == 0) {
1006 			KDASSERT(checkfreelist(bp, &bufqueues[BQ_LRU], 1));
1007 			goto already_queued;
1008 		} else {
1009 			bremfree(bp);
1010 		}
1011 	}
1012 
1013 	KDASSERT(checkfreelist(bp, &bufqueues[BQ_AGE], 0));
1014 	KDASSERT(checkfreelist(bp, &bufqueues[BQ_LRU], 0));
1015 	KDASSERT(checkfreelist(bp, &bufqueues[BQ_LOCKED], 0));
1016 
1017 	if ((bp->b_bufsize <= 0) || ISSET(bp->b_cflags, BC_INVAL)) {
1018 		/*
1019 		 * If it's invalid or empty, dissociate it from its vnode
1020 		 * and put on the head of the appropriate queue.
1021 		 */
1022 		if (ISSET(bp->b_flags, B_LOCKED)) {
1023 			if (wapbl_vphaswapbl(vp = bp->b_vp)) {
1024 				struct mount *mp = wapbl_vptomp(vp);
1025 
1026 				KASSERT(bp->b_iodone
1027 				    != mp->mnt_wapbl_op->wo_wapbl_biodone);
1028 				WAPBL_REMOVE_BUF(mp, bp);
1029 			}
1030 		}
1031 
1032 		mutex_enter(bp->b_objlock);
1033 		CLR(bp->b_oflags, BO_DONE|BO_DELWRI);
1034 		if ((vp = bp->b_vp) != NULL) {
1035 			KASSERT(bp->b_objlock == vp->v_interlock);
1036 			reassignbuf(bp, bp->b_vp);
1037 			brelvp(bp);
1038 			mutex_exit(vp->v_interlock);
1039 		} else {
1040 			KASSERT(bp->b_objlock == &buffer_lock);
1041 			mutex_exit(bp->b_objlock);
1042 		}
1043 
1044 		if (bp->b_bufsize <= 0)
1045 			/* no data */
1046 			goto already_queued;
1047 		else
1048 			/* invalid data */
1049 			bufq = &bufqueues[BQ_AGE];
1050 		binsheadfree(bp, bufq);
1051 	} else  {
1052 		/*
1053 		 * It has valid data.  Put it on the end of the appropriate
1054 		 * queue, so that it'll stick around for as long as possible.
1055 		 * If buf is AGE, but has dependencies, must put it on last
1056 		 * bufqueue to be scanned, ie LRU. This protects against the
1057 		 * livelock where BQ_AGE only has buffers with dependencies,
1058 		 * and we thus never get to the dependent buffers in BQ_LRU.
1059 		 */
1060 		if (ISSET(bp->b_flags, B_LOCKED)) {
1061 			/* locked in core */
1062 			bufq = &bufqueues[BQ_LOCKED];
1063 		} else if (!ISSET(bp->b_cflags, BC_AGE)) {
1064 			/* valid data */
1065 			bufq = &bufqueues[BQ_LRU];
1066 		} else {
1067 			/* stale but valid data */
1068 			bufq = &bufqueues[BQ_AGE];
1069 		}
1070 		binstailfree(bp, bufq);
1071 	}
1072 already_queued:
1073 	/* Unlock the buffer. */
1074 	CLR(bp->b_cflags, BC_AGE|BC_BUSY|BC_NOCACHE);
1075 	CLR(bp->b_flags, B_ASYNC);
1076 	cv_broadcast(&bp->b_busy);
1077 
1078 	if (bp->b_bufsize <= 0)
1079 		brele(bp);
1080 }
1081 
1082 void
1083 brelse(buf_t *bp, int set)
1084 {
1085 
1086 	mutex_enter(&bufcache_lock);
1087 	brelsel(bp, set);
1088 	mutex_exit(&bufcache_lock);
1089 }
1090 
1091 /*
1092  * Determine if a block is in the cache.
1093  * Just look on what would be its hash chain.  If it's there, return
1094  * a pointer to it, unless it's marked invalid.  If it's marked invalid,
1095  * we normally don't return the buffer, unless the caller explicitly
1096  * wants us to.
1097  */
1098 buf_t *
1099 incore(struct vnode *vp, daddr_t blkno)
1100 {
1101 	buf_t *bp;
1102 
1103 	KASSERT(mutex_owned(&bufcache_lock));
1104 
1105 	/* Search hash chain */
1106 	LIST_FOREACH(bp, BUFHASH(vp, blkno), b_hash) {
1107 		if (bp->b_lblkno == blkno && bp->b_vp == vp &&
1108 		    !ISSET(bp->b_cflags, BC_INVAL)) {
1109 		    	KASSERT(bp->b_objlock == vp->v_interlock);
1110 		    	return (bp);
1111 		}
1112 	}
1113 
1114 	return (NULL);
1115 }
1116 
1117 /*
1118  * Get a block of requested size that is associated with
1119  * a given vnode and block offset. If it is found in the
1120  * block cache, mark it as having been found, make it busy
1121  * and return it. Otherwise, return an empty block of the
1122  * correct size. It is up to the caller to insure that the
1123  * cached blocks be of the correct size.
1124  */
1125 buf_t *
1126 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo)
1127 {
1128 	int err, preserve;
1129 	buf_t *bp;
1130 
1131 	mutex_enter(&bufcache_lock);
1132  loop:
1133 	bp = incore(vp, blkno);
1134 	if (bp != NULL) {
1135 		err = bbusy(bp, ((slpflag & PCATCH) != 0), slptimeo, NULL);
1136 		if (err != 0) {
1137 			if (err == EPASSTHROUGH)
1138 				goto loop;
1139 			mutex_exit(&bufcache_lock);
1140 			return (NULL);
1141 		}
1142 		KASSERT(!cv_has_waiters(&bp->b_done));
1143 #ifdef DIAGNOSTIC
1144 		if (ISSET(bp->b_oflags, BO_DONE|BO_DELWRI) &&
1145 		    bp->b_bcount < size && vp->v_type != VBLK)
1146 			panic("getblk: block size invariant failed");
1147 #endif
1148 		bremfree(bp);
1149 		preserve = 1;
1150 	} else {
1151 		if ((bp = getnewbuf(slpflag, slptimeo, 0)) == NULL)
1152 			goto loop;
1153 
1154 		if (incore(vp, blkno) != NULL) {
1155 			/* The block has come into memory in the meantime. */
1156 			brelsel(bp, 0);
1157 			goto loop;
1158 		}
1159 
1160 		LIST_INSERT_HEAD(BUFHASH(vp, blkno), bp, b_hash);
1161 		bp->b_blkno = bp->b_lblkno = bp->b_rawblkno = blkno;
1162 		mutex_enter(vp->v_interlock);
1163 		bgetvp(vp, bp);
1164 		mutex_exit(vp->v_interlock);
1165 		preserve = 0;
1166 	}
1167 	mutex_exit(&bufcache_lock);
1168 
1169 	/*
1170 	 * LFS can't track total size of B_LOCKED buffer (locked_queue_bytes)
1171 	 * if we re-size buffers here.
1172 	 */
1173 	if (ISSET(bp->b_flags, B_LOCKED)) {
1174 		KASSERT(bp->b_bufsize >= size);
1175 	} else {
1176 		if (allocbuf(bp, size, preserve)) {
1177 			mutex_enter(&bufcache_lock);
1178 			LIST_REMOVE(bp, b_hash);
1179 			mutex_exit(&bufcache_lock);
1180 			brelse(bp, BC_INVAL);
1181 			return NULL;
1182 		}
1183 	}
1184 	BIO_SETPRIO(bp, BPRIO_DEFAULT);
1185 	return (bp);
1186 }
1187 
1188 /*
1189  * Get an empty, disassociated buffer of given size.
1190  */
1191 buf_t *
1192 geteblk(int size)
1193 {
1194 	buf_t *bp;
1195 	int error;
1196 
1197 	mutex_enter(&bufcache_lock);
1198 	while ((bp = getnewbuf(0, 0, 0)) == NULL)
1199 		;
1200 
1201 	SET(bp->b_cflags, BC_INVAL);
1202 	LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1203 	mutex_exit(&bufcache_lock);
1204 	BIO_SETPRIO(bp, BPRIO_DEFAULT);
1205 	error = allocbuf(bp, size, 0);
1206 	KASSERT(error == 0);
1207 	return (bp);
1208 }
1209 
1210 /*
1211  * Expand or contract the actual memory allocated to a buffer.
1212  *
1213  * If the buffer shrinks, data is lost, so it's up to the
1214  * caller to have written it out *first*; this routine will not
1215  * start a write.  If the buffer grows, it's the callers
1216  * responsibility to fill out the buffer's additional contents.
1217  */
1218 int
1219 allocbuf(buf_t *bp, int size, int preserve)
1220 {
1221 	void *addr;
1222 	vsize_t oldsize, desired_size;
1223 	int oldcount;
1224 	int delta;
1225 
1226 	desired_size = buf_roundsize(size);
1227 	if (desired_size > MAXBSIZE)
1228 		printf("allocbuf: buffer larger than MAXBSIZE requested");
1229 
1230 	oldcount = bp->b_bcount;
1231 
1232 	bp->b_bcount = size;
1233 
1234 	oldsize = bp->b_bufsize;
1235 	if (oldsize == desired_size) {
1236 		/*
1237 		 * Do not short cut the WAPBL resize, as the buffer length
1238 		 * could still have changed and this would corrupt the
1239 		 * tracking of the transaction length.
1240 		 */
1241 		goto out;
1242 	}
1243 
1244 	/*
1245 	 * If we want a buffer of a different size, re-allocate the
1246 	 * buffer's memory; copy old content only if needed.
1247 	 */
1248 	addr = buf_alloc(desired_size);
1249 	if (addr == NULL)
1250 		return ENOMEM;
1251 	if (preserve)
1252 		memcpy(addr, bp->b_data, MIN(oldsize,desired_size));
1253 	if (bp->b_data != NULL)
1254 		buf_mrelease(bp->b_data, oldsize);
1255 	bp->b_data = addr;
1256 	bp->b_bufsize = desired_size;
1257 
1258 	/*
1259 	 * Update overall buffer memory counter (protected by bufcache_lock)
1260 	 */
1261 	delta = (long)desired_size - (long)oldsize;
1262 
1263 	mutex_enter(&bufcache_lock);
1264 	if ((bufmem += delta) > bufmem_hiwater) {
1265 		/*
1266 		 * Need to trim overall memory usage.
1267 		 */
1268 		while (buf_canrelease()) {
1269 			if (curcpu()->ci_schedstate.spc_flags &
1270 			    SPCF_SHOULDYIELD) {
1271 				mutex_exit(&bufcache_lock);
1272 				preempt();
1273 				mutex_enter(&bufcache_lock);
1274 			}
1275 			if (buf_trim() == 0)
1276 				break;
1277 		}
1278 	}
1279 	mutex_exit(&bufcache_lock);
1280 
1281  out:
1282 	if (wapbl_vphaswapbl(bp->b_vp))
1283 		WAPBL_RESIZE_BUF(wapbl_vptomp(bp->b_vp), bp, oldsize, oldcount);
1284 
1285 	return 0;
1286 }
1287 
1288 /*
1289  * Find a buffer which is available for use.
1290  * Select something from a free list.
1291  * Preference is to AGE list, then LRU list.
1292  *
1293  * Called with the buffer queues locked.
1294  * Return buffer locked.
1295  */
1296 buf_t *
1297 getnewbuf(int slpflag, int slptimeo, int from_bufq)
1298 {
1299 	buf_t *bp;
1300 	struct vnode *vp;
1301 
1302  start:
1303 	KASSERT(mutex_owned(&bufcache_lock));
1304 
1305 	/*
1306 	 * Get a new buffer from the pool.
1307 	 */
1308 	if (!from_bufq && buf_lotsfree()) {
1309 		mutex_exit(&bufcache_lock);
1310 		bp = pool_cache_get(buf_cache, PR_NOWAIT);
1311 		if (bp != NULL) {
1312 			memset((char *)bp, 0, sizeof(*bp));
1313 			buf_init(bp);
1314 			SET(bp->b_cflags, BC_BUSY);	/* mark buffer busy */
1315 			mutex_enter(&bufcache_lock);
1316 #if defined(DIAGNOSTIC)
1317 			bp->b_freelistindex = -1;
1318 #endif /* defined(DIAGNOSTIC) */
1319 			return (bp);
1320 		}
1321 		mutex_enter(&bufcache_lock);
1322 	}
1323 
1324 	KASSERT(mutex_owned(&bufcache_lock));
1325 	if ((bp = TAILQ_FIRST(&bufqueues[BQ_AGE].bq_queue)) != NULL ||
1326 	    (bp = TAILQ_FIRST(&bufqueues[BQ_LRU].bq_queue)) != NULL) {
1327 	    	KASSERT(!ISSET(bp->b_cflags, BC_BUSY) || ISSET(bp->b_cflags, BC_VFLUSH));
1328 		bremfree(bp);
1329 
1330 		/* Buffer is no longer on free lists. */
1331 		SET(bp->b_cflags, BC_BUSY);
1332 	} else {
1333 		/*
1334 		 * XXX: !from_bufq should be removed.
1335 		 */
1336 		if (!from_bufq || curlwp != uvm.pagedaemon_lwp) {
1337 			/* wait for a free buffer of any kind */
1338 			if ((slpflag & PCATCH) != 0)
1339 				(void)cv_timedwait_sig(&needbuffer_cv,
1340 				    &bufcache_lock, slptimeo);
1341 			else
1342 				(void)cv_timedwait(&needbuffer_cv,
1343 				    &bufcache_lock, slptimeo);
1344 		}
1345 		return (NULL);
1346 	}
1347 
1348 #ifdef DIAGNOSTIC
1349 	if (bp->b_bufsize <= 0)
1350 		panic("buffer %p: on queue but empty", bp);
1351 #endif
1352 
1353 	if (ISSET(bp->b_cflags, BC_VFLUSH)) {
1354 		/*
1355 		 * This is a delayed write buffer being flushed to disk.  Make
1356 		 * sure it gets aged out of the queue when it's finished, and
1357 		 * leave it off the LRU queue.
1358 		 */
1359 		CLR(bp->b_cflags, BC_VFLUSH);
1360 		SET(bp->b_cflags, BC_AGE);
1361 		goto start;
1362 	}
1363 
1364 	KASSERT(ISSET(bp->b_cflags, BC_BUSY));
1365 	KASSERT(bp->b_refcnt > 0);
1366     	KASSERT(!cv_has_waiters(&bp->b_done));
1367 
1368 	/*
1369 	 * If buffer was a delayed write, start it and return NULL
1370 	 * (since we might sleep while starting the write).
1371 	 */
1372 	if (ISSET(bp->b_oflags, BO_DELWRI)) {
1373 		/*
1374 		 * This buffer has gone through the LRU, so make sure it gets
1375 		 * reused ASAP.
1376 		 */
1377 		SET(bp->b_cflags, BC_AGE);
1378 		mutex_exit(&bufcache_lock);
1379 		bawrite(bp);
1380 		mutex_enter(&bufcache_lock);
1381 		return (NULL);
1382 	}
1383 
1384 	vp = bp->b_vp;
1385 
1386 	/* clear out various other fields */
1387 	bp->b_cflags = BC_BUSY;
1388 	bp->b_oflags = 0;
1389 	bp->b_flags = 0;
1390 	bp->b_dev = NODEV;
1391 	bp->b_blkno = 0;
1392 	bp->b_lblkno = 0;
1393 	bp->b_rawblkno = 0;
1394 	bp->b_iodone = 0;
1395 	bp->b_error = 0;
1396 	bp->b_resid = 0;
1397 	bp->b_bcount = 0;
1398 
1399 	LIST_REMOVE(bp, b_hash);
1400 
1401 	/* Disassociate us from our vnode, if we had one... */
1402 	if (vp != NULL) {
1403 		mutex_enter(vp->v_interlock);
1404 		brelvp(bp);
1405 		mutex_exit(vp->v_interlock);
1406 	}
1407 
1408 	return (bp);
1409 }
1410 
1411 /*
1412  * Attempt to free an aged buffer off the queues.
1413  * Called with queue lock held.
1414  * Returns the amount of buffer memory freed.
1415  */
1416 static int
1417 buf_trim(void)
1418 {
1419 	buf_t *bp;
1420 	long size = 0;
1421 
1422 	KASSERT(mutex_owned(&bufcache_lock));
1423 
1424 	/* Instruct getnewbuf() to get buffers off the queues */
1425 	if ((bp = getnewbuf(PCATCH, 1, 1)) == NULL)
1426 		return 0;
1427 
1428 	KASSERT((bp->b_cflags & BC_WANTED) == 0);
1429 	size = bp->b_bufsize;
1430 	bufmem -= size;
1431 	if (size > 0) {
1432 		buf_mrelease(bp->b_data, size);
1433 		bp->b_bcount = bp->b_bufsize = 0;
1434 	}
1435 	/* brelse() will return the buffer to the global buffer pool */
1436 	brelsel(bp, 0);
1437 	return size;
1438 }
1439 
1440 int
1441 buf_drain(int n)
1442 {
1443 	int size = 0, sz;
1444 
1445 	KASSERT(mutex_owned(&bufcache_lock));
1446 
1447 	while (size < n && bufmem > bufmem_lowater) {
1448 		sz = buf_trim();
1449 		if (sz <= 0)
1450 			break;
1451 		size += sz;
1452 	}
1453 
1454 	return size;
1455 }
1456 
1457 /*
1458  * Wait for operations on the buffer to complete.
1459  * When they do, extract and return the I/O's error value.
1460  */
1461 int
1462 biowait(buf_t *bp)
1463 {
1464 
1465 	KASSERT(ISSET(bp->b_cflags, BC_BUSY));
1466 	KASSERT(bp->b_refcnt > 0);
1467 
1468 	mutex_enter(bp->b_objlock);
1469 	while (!ISSET(bp->b_oflags, BO_DONE | BO_DELWRI))
1470 		cv_wait(&bp->b_done, bp->b_objlock);
1471 	mutex_exit(bp->b_objlock);
1472 
1473 	return bp->b_error;
1474 }
1475 
1476 /*
1477  * Mark I/O complete on a buffer.
1478  *
1479  * If a callback has been requested, e.g. the pageout
1480  * daemon, do so. Otherwise, awaken waiting processes.
1481  *
1482  * [ Leffler, et al., says on p.247:
1483  *	"This routine wakes up the blocked process, frees the buffer
1484  *	for an asynchronous write, or, for a request by the pagedaemon
1485  *	process, invokes a procedure specified in the buffer structure" ]
1486  *
1487  * In real life, the pagedaemon (or other system processes) wants
1488  * to do async stuff to, and doesn't want the buffer brelse()'d.
1489  * (for swap pager, that puts swap buffers on the free lists (!!!),
1490  * for the vn device, that puts allocated buffers on the free lists!)
1491  */
1492 void
1493 biodone(buf_t *bp)
1494 {
1495 	int s;
1496 
1497 	KASSERT(!ISSET(bp->b_oflags, BO_DONE));
1498 
1499 	if (cpu_intr_p()) {
1500 		/* From interrupt mode: defer to a soft interrupt. */
1501 		s = splvm();
1502 		TAILQ_INSERT_TAIL(&curcpu()->ci_data.cpu_biodone, bp, b_actq);
1503 		softint_schedule(biodone_sih);
1504 		splx(s);
1505 	} else {
1506 		/* Process now - the buffer may be freed soon. */
1507 		biodone2(bp);
1508 	}
1509 }
1510 
1511 static void
1512 biodone2(buf_t *bp)
1513 {
1514 	void (*callout)(buf_t *);
1515 
1516 	mutex_enter(bp->b_objlock);
1517 	/* Note that the transfer is done. */
1518 	if (ISSET(bp->b_oflags, BO_DONE))
1519 		panic("biodone2 already");
1520 	CLR(bp->b_flags, B_COWDONE);
1521 	SET(bp->b_oflags, BO_DONE);
1522 	BIO_SETPRIO(bp, BPRIO_DEFAULT);
1523 
1524 	/* Wake up waiting writers. */
1525 	if (!ISSET(bp->b_flags, B_READ))
1526 		vwakeup(bp);
1527 
1528 	if ((callout = bp->b_iodone) != NULL) {
1529 		/* Note callout done, then call out. */
1530 		KASSERT(!cv_has_waiters(&bp->b_done));
1531 		KERNEL_LOCK(1, NULL);		/* XXXSMP */
1532 		bp->b_iodone = NULL;
1533 		mutex_exit(bp->b_objlock);
1534 		(*callout)(bp);
1535 		KERNEL_UNLOCK_ONE(NULL);	/* XXXSMP */
1536 	} else if (ISSET(bp->b_flags, B_ASYNC)) {
1537 		/* If async, release. */
1538 		KASSERT(!cv_has_waiters(&bp->b_done));
1539 		mutex_exit(bp->b_objlock);
1540 		brelse(bp, 0);
1541 	} else {
1542 		/* Otherwise just wake up waiters in biowait(). */
1543 		cv_broadcast(&bp->b_done);
1544 		mutex_exit(bp->b_objlock);
1545 	}
1546 }
1547 
1548 static void
1549 biointr(void *cookie)
1550 {
1551 	struct cpu_info *ci;
1552 	buf_t *bp;
1553 	int s;
1554 
1555 	ci = curcpu();
1556 
1557 	while (!TAILQ_EMPTY(&ci->ci_data.cpu_biodone)) {
1558 		KASSERT(curcpu() == ci);
1559 
1560 		s = splvm();
1561 		bp = TAILQ_FIRST(&ci->ci_data.cpu_biodone);
1562 		TAILQ_REMOVE(&ci->ci_data.cpu_biodone, bp, b_actq);
1563 		splx(s);
1564 
1565 		biodone2(bp);
1566 	}
1567 }
1568 
1569 /*
1570  * Wait for all buffers to complete I/O
1571  * Return the number of "stuck" buffers.
1572  */
1573 int
1574 buf_syncwait(void)
1575 {
1576 	buf_t *bp;
1577 	int iter, nbusy, nbusy_prev = 0, dcount, ihash;
1578 
1579 	dcount = 10000;
1580 	for (iter = 0; iter < 20;) {
1581 		mutex_enter(&bufcache_lock);
1582 		nbusy = 0;
1583 		for (ihash = 0; ihash < bufhash+1; ihash++) {
1584 		    LIST_FOREACH(bp, &bufhashtbl[ihash], b_hash) {
1585 			if ((bp->b_cflags & (BC_BUSY|BC_INVAL)) == BC_BUSY)
1586 				nbusy += ((bp->b_flags & B_READ) == 0);
1587 		    }
1588 		}
1589 		mutex_exit(&bufcache_lock);
1590 
1591 		if (nbusy == 0)
1592 			break;
1593 		if (nbusy_prev == 0)
1594 			nbusy_prev = nbusy;
1595 		printf("%d ", nbusy);
1596 		kpause("bflush", false, MAX(1, hz / 25 * iter), NULL);
1597 		if (nbusy >= nbusy_prev) /* we didn't flush anything */
1598 			iter++;
1599 		else
1600 			nbusy_prev = nbusy;
1601 	}
1602 
1603 	if (nbusy) {
1604 #if defined(DEBUG) || defined(DEBUG_HALT_BUSY)
1605 		printf("giving up\nPrinting vnodes for busy buffers\n");
1606 		for (ihash = 0; ihash < bufhash+1; ihash++) {
1607 		    LIST_FOREACH(bp, &bufhashtbl[ihash], b_hash) {
1608 			if ((bp->b_cflags & (BC_BUSY|BC_INVAL)) == BC_BUSY &&
1609 			    (bp->b_flags & B_READ) == 0)
1610 				vprint(NULL, bp->b_vp);
1611 		    }
1612 		}
1613 #endif
1614 	}
1615 
1616 	return nbusy;
1617 }
1618 
1619 static void
1620 sysctl_fillbuf(buf_t *i, struct buf_sysctl *o)
1621 {
1622 
1623 	o->b_flags = i->b_flags | i->b_cflags | i->b_oflags;
1624 	o->b_error = i->b_error;
1625 	o->b_prio = i->b_prio;
1626 	o->b_dev = i->b_dev;
1627 	o->b_bufsize = i->b_bufsize;
1628 	o->b_bcount = i->b_bcount;
1629 	o->b_resid = i->b_resid;
1630 	o->b_addr = PTRTOUINT64(i->b_data);
1631 	o->b_blkno = i->b_blkno;
1632 	o->b_rawblkno = i->b_rawblkno;
1633 	o->b_iodone = PTRTOUINT64(i->b_iodone);
1634 	o->b_proc = PTRTOUINT64(i->b_proc);
1635 	o->b_vp = PTRTOUINT64(i->b_vp);
1636 	o->b_saveaddr = PTRTOUINT64(i->b_saveaddr);
1637 	o->b_lblkno = i->b_lblkno;
1638 }
1639 
1640 #define KERN_BUFSLOP 20
1641 static int
1642 sysctl_dobuf(SYSCTLFN_ARGS)
1643 {
1644 	buf_t *bp;
1645 	struct buf_sysctl bs;
1646 	struct bqueue *bq;
1647 	char *dp;
1648 	u_int i, op, arg;
1649 	size_t len, needed, elem_size, out_size;
1650 	int error, elem_count, retries;
1651 
1652 	if (namelen == 1 && name[0] == CTL_QUERY)
1653 		return (sysctl_query(SYSCTLFN_CALL(rnode)));
1654 
1655 	if (namelen != 4)
1656 		return (EINVAL);
1657 
1658 	retries = 100;
1659  retry:
1660 	dp = oldp;
1661 	len = (oldp != NULL) ? *oldlenp : 0;
1662 	op = name[0];
1663 	arg = name[1];
1664 	elem_size = name[2];
1665 	elem_count = name[3];
1666 	out_size = MIN(sizeof(bs), elem_size);
1667 
1668 	/*
1669 	 * at the moment, these are just "placeholders" to make the
1670 	 * API for retrieving kern.buf data more extensible in the
1671 	 * future.
1672 	 *
1673 	 * XXX kern.buf currently has "netbsd32" issues.  hopefully
1674 	 * these will be resolved at a later point.
1675 	 */
1676 	if (op != KERN_BUF_ALL || arg != KERN_BUF_ALL ||
1677 	    elem_size < 1 || elem_count < 0)
1678 		return (EINVAL);
1679 
1680 	error = 0;
1681 	needed = 0;
1682 	sysctl_unlock();
1683 	mutex_enter(&bufcache_lock);
1684 	for (i = 0; i < BQUEUES; i++) {
1685 		bq = &bufqueues[i];
1686 		TAILQ_FOREACH(bp, &bq->bq_queue, b_freelist) {
1687 			bq->bq_marker = bp;
1688 			if (len >= elem_size && elem_count > 0) {
1689 				sysctl_fillbuf(bp, &bs);
1690 				mutex_exit(&bufcache_lock);
1691 				error = copyout(&bs, dp, out_size);
1692 				mutex_enter(&bufcache_lock);
1693 				if (error)
1694 					break;
1695 				if (bq->bq_marker != bp) {
1696 					/*
1697 					 * This sysctl node is only for
1698 					 * statistics.  Retry; if the
1699 					 * queue keeps changing, then
1700 					 * bail out.
1701 					 */
1702 					if (retries-- == 0) {
1703 						error = EAGAIN;
1704 						break;
1705 					}
1706 					mutex_exit(&bufcache_lock);
1707 					sysctl_relock();
1708 					goto retry;
1709 				}
1710 				dp += elem_size;
1711 				len -= elem_size;
1712 			}
1713 			needed += elem_size;
1714 			if (elem_count > 0 && elem_count != INT_MAX)
1715 				elem_count--;
1716 		}
1717 		if (error != 0)
1718 			break;
1719 	}
1720 	mutex_exit(&bufcache_lock);
1721 	sysctl_relock();
1722 
1723 	*oldlenp = needed;
1724 	if (oldp == NULL)
1725 		*oldlenp += KERN_BUFSLOP * sizeof(buf_t);
1726 
1727 	return (error);
1728 }
1729 
1730 static int
1731 sysctl_bufvm_update(SYSCTLFN_ARGS)
1732 {
1733 	int t, error, rv;
1734 	struct sysctlnode node;
1735 
1736 	node = *rnode;
1737 	node.sysctl_data = &t;
1738 	t = *(int *)rnode->sysctl_data;
1739 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
1740 	if (error || newp == NULL)
1741 		return (error);
1742 
1743 	if (t < 0)
1744 		return EINVAL;
1745 	if (rnode->sysctl_data == &bufcache) {
1746 		if (t > 100)
1747 			return (EINVAL);
1748 		bufcache = t;
1749 		buf_setwm();
1750 	} else if (rnode->sysctl_data == &bufmem_lowater) {
1751 		if (bufmem_hiwater - t < 16)
1752 			return (EINVAL);
1753 		bufmem_lowater = t;
1754 	} else if (rnode->sysctl_data == &bufmem_hiwater) {
1755 		if (t - bufmem_lowater < 16)
1756 			return (EINVAL);
1757 		bufmem_hiwater = t;
1758 	} else
1759 		return (EINVAL);
1760 
1761 	/* Drain until below new high water mark */
1762 	sysctl_unlock();
1763 	mutex_enter(&bufcache_lock);
1764 	while ((t = bufmem - bufmem_hiwater) >= 0) {
1765 		rv = buf_drain(t / (2 * 1024));
1766 		if (rv <= 0)
1767 			break;
1768 	}
1769 	mutex_exit(&bufcache_lock);
1770 	sysctl_relock();
1771 
1772 	return 0;
1773 }
1774 
1775 static struct sysctllog *vfsbio_sysctllog;
1776 
1777 static void
1778 sysctl_kern_buf_setup(void)
1779 {
1780 
1781 	sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
1782 		       CTLFLAG_PERMANENT,
1783 		       CTLTYPE_NODE, "kern", NULL,
1784 		       NULL, 0, NULL, 0,
1785 		       CTL_KERN, CTL_EOL);
1786 	sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
1787 		       CTLFLAG_PERMANENT,
1788 		       CTLTYPE_NODE, "buf",
1789 		       SYSCTL_DESCR("Kernel buffer cache information"),
1790 		       sysctl_dobuf, 0, NULL, 0,
1791 		       CTL_KERN, KERN_BUF, CTL_EOL);
1792 }
1793 
1794 static void
1795 sysctl_vm_buf_setup(void)
1796 {
1797 
1798 	sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
1799 		       CTLFLAG_PERMANENT,
1800 		       CTLTYPE_NODE, "vm", NULL,
1801 		       NULL, 0, NULL, 0,
1802 		       CTL_VM, CTL_EOL);
1803 	sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
1804 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1805 		       CTLTYPE_INT, "bufcache",
1806 		       SYSCTL_DESCR("Percentage of physical memory to use for "
1807 				    "buffer cache"),
1808 		       sysctl_bufvm_update, 0, &bufcache, 0,
1809 		       CTL_VM, CTL_CREATE, CTL_EOL);
1810 	sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
1811 		       CTLFLAG_PERMANENT|CTLFLAG_READONLY,
1812 		       CTLTYPE_INT, "bufmem",
1813 		       SYSCTL_DESCR("Amount of kernel memory used by buffer "
1814 				    "cache"),
1815 		       NULL, 0, &bufmem, 0,
1816 		       CTL_VM, CTL_CREATE, CTL_EOL);
1817 	sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
1818 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1819 		       CTLTYPE_INT, "bufmem_lowater",
1820 		       SYSCTL_DESCR("Minimum amount of kernel memory to "
1821 				    "reserve for buffer cache"),
1822 		       sysctl_bufvm_update, 0, &bufmem_lowater, 0,
1823 		       CTL_VM, CTL_CREATE, CTL_EOL);
1824 	sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
1825 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1826 		       CTLTYPE_INT, "bufmem_hiwater",
1827 		       SYSCTL_DESCR("Maximum amount of kernel memory to use "
1828 				    "for buffer cache"),
1829 		       sysctl_bufvm_update, 0, &bufmem_hiwater, 0,
1830 		       CTL_VM, CTL_CREATE, CTL_EOL);
1831 }
1832 
1833 #ifdef DEBUG
1834 /*
1835  * Print out statistics on the current allocation of the buffer pool.
1836  * Can be enabled to print out on every ``sync'' by setting "syncprt"
1837  * in vfs_syscalls.c using sysctl.
1838  */
1839 void
1840 vfs_bufstats(void)
1841 {
1842 	int i, j, count;
1843 	buf_t *bp;
1844 	struct bqueue *dp;
1845 	int counts[(MAXBSIZE / PAGE_SIZE) + 1];
1846 	static const char *bname[BQUEUES] = { "LOCKED", "LRU", "AGE" };
1847 
1848 	for (dp = bufqueues, i = 0; dp < &bufqueues[BQUEUES]; dp++, i++) {
1849 		count = 0;
1850 		for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
1851 			counts[j] = 0;
1852 		TAILQ_FOREACH(bp, &dp->bq_queue, b_freelist) {
1853 			counts[bp->b_bufsize/PAGE_SIZE]++;
1854 			count++;
1855 		}
1856 		printf("%s: total-%d", bname[i], count);
1857 		for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
1858 			if (counts[j] != 0)
1859 				printf(", %d-%d", j * PAGE_SIZE, counts[j]);
1860 		printf("\n");
1861 	}
1862 }
1863 #endif /* DEBUG */
1864 
1865 /* ------------------------------ */
1866 
1867 buf_t *
1868 getiobuf(struct vnode *vp, bool waitok)
1869 {
1870 	buf_t *bp;
1871 
1872 	bp = pool_cache_get(bufio_cache, (waitok ? PR_WAITOK : PR_NOWAIT));
1873 	if (bp == NULL)
1874 		return bp;
1875 
1876 	buf_init(bp);
1877 
1878 	if ((bp->b_vp = vp) == NULL)
1879 		bp->b_objlock = &buffer_lock;
1880 	else
1881 		bp->b_objlock = vp->v_interlock;
1882 
1883 	return bp;
1884 }
1885 
1886 void
1887 putiobuf(buf_t *bp)
1888 {
1889 
1890 	buf_destroy(bp);
1891 	pool_cache_put(bufio_cache, bp);
1892 }
1893 
1894 /*
1895  * nestiobuf_iodone: b_iodone callback for nested buffers.
1896  */
1897 
1898 void
1899 nestiobuf_iodone(buf_t *bp)
1900 {
1901 	buf_t *mbp = bp->b_private;
1902 	int error;
1903 	int donebytes;
1904 
1905 	KASSERT(bp->b_bcount <= bp->b_bufsize);
1906 	KASSERT(mbp != bp);
1907 
1908 	error = bp->b_error;
1909 	if (bp->b_error == 0 &&
1910 	    (bp->b_bcount < bp->b_bufsize || bp->b_resid > 0)) {
1911 		/*
1912 		 * Not all got transfered, raise an error. We have no way to
1913 		 * propagate these conditions to mbp.
1914 		 */
1915 		error = EIO;
1916 	}
1917 
1918 	donebytes = bp->b_bufsize;
1919 
1920 	putiobuf(bp);
1921 	nestiobuf_done(mbp, donebytes, error);
1922 }
1923 
1924 /*
1925  * nestiobuf_setup: setup a "nested" buffer.
1926  *
1927  * => 'mbp' is a "master" buffer which is being divided into sub pieces.
1928  * => 'bp' should be a buffer allocated by getiobuf.
1929  * => 'offset' is a byte offset in the master buffer.
1930  * => 'size' is a size in bytes of this nested buffer.
1931  */
1932 
1933 void
1934 nestiobuf_setup(buf_t *mbp, buf_t *bp, int offset, size_t size)
1935 {
1936 	const int b_read = mbp->b_flags & B_READ;
1937 	struct vnode *vp = mbp->b_vp;
1938 
1939 	KASSERT(mbp->b_bcount >= offset + size);
1940 	bp->b_vp = vp;
1941 	bp->b_dev = mbp->b_dev;
1942 	bp->b_objlock = mbp->b_objlock;
1943 	bp->b_cflags = BC_BUSY;
1944 	bp->b_flags = B_ASYNC | b_read;
1945 	bp->b_iodone = nestiobuf_iodone;
1946 	bp->b_data = (char *)mbp->b_data + offset;
1947 	bp->b_resid = bp->b_bcount = size;
1948 	bp->b_bufsize = bp->b_bcount;
1949 	bp->b_private = mbp;
1950 	BIO_COPYPRIO(bp, mbp);
1951 	if (!b_read && vp != NULL) {
1952 		mutex_enter(vp->v_interlock);
1953 		vp->v_numoutput++;
1954 		mutex_exit(vp->v_interlock);
1955 	}
1956 }
1957 
1958 /*
1959  * nestiobuf_done: propagate completion to the master buffer.
1960  *
1961  * => 'donebytes' specifies how many bytes in the 'mbp' is completed.
1962  * => 'error' is an errno(2) that 'donebytes' has been completed with.
1963  */
1964 
1965 void
1966 nestiobuf_done(buf_t *mbp, int donebytes, int error)
1967 {
1968 
1969 	if (donebytes == 0) {
1970 		return;
1971 	}
1972 	mutex_enter(mbp->b_objlock);
1973 	KASSERT(mbp->b_resid >= donebytes);
1974 	mbp->b_resid -= donebytes;
1975 	if (error)
1976 		mbp->b_error = error;
1977 	if (mbp->b_resid == 0) {
1978 		if (mbp->b_error)
1979 			mbp->b_resid = mbp->b_bcount;
1980 		mutex_exit(mbp->b_objlock);
1981 		biodone(mbp);
1982 	} else
1983 		mutex_exit(mbp->b_objlock);
1984 }
1985 
1986 void
1987 buf_init(buf_t *bp)
1988 {
1989 
1990 	cv_init(&bp->b_busy, "biolock");
1991 	cv_init(&bp->b_done, "biowait");
1992 	bp->b_dev = NODEV;
1993 	bp->b_error = 0;
1994 	bp->b_flags = 0;
1995 	bp->b_cflags = 0;
1996 	bp->b_oflags = 0;
1997 	bp->b_objlock = &buffer_lock;
1998 	bp->b_iodone = NULL;
1999 	bp->b_refcnt = 1;
2000 	bp->b_dev = NODEV;
2001 	bp->b_vnbufs.le_next = NOLIST;
2002 	BIO_SETPRIO(bp, BPRIO_DEFAULT);
2003 }
2004 
2005 void
2006 buf_destroy(buf_t *bp)
2007 {
2008 
2009 	cv_destroy(&bp->b_done);
2010 	cv_destroy(&bp->b_busy);
2011 }
2012 
2013 int
2014 bbusy(buf_t *bp, bool intr, int timo, kmutex_t *interlock)
2015 {
2016 	int error;
2017 
2018 	KASSERT(mutex_owned(&bufcache_lock));
2019 
2020 	if ((bp->b_cflags & BC_BUSY) != 0) {
2021 		if (curlwp == uvm.pagedaemon_lwp)
2022 			return EDEADLK;
2023 		bp->b_cflags |= BC_WANTED;
2024 		bref(bp);
2025 		if (interlock != NULL)
2026 			mutex_exit(interlock);
2027 		if (intr) {
2028 			error = cv_timedwait_sig(&bp->b_busy, &bufcache_lock,
2029 			    timo);
2030 		} else {
2031 			error = cv_timedwait(&bp->b_busy, &bufcache_lock,
2032 			    timo);
2033 		}
2034 		brele(bp);
2035 		if (interlock != NULL)
2036 			mutex_enter(interlock);
2037 		if (error != 0)
2038 			return error;
2039 		return EPASSTHROUGH;
2040 	}
2041 	bp->b_cflags |= BC_BUSY;
2042 
2043 	return 0;
2044 }
2045