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