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