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