xref: /freebsd/sys/kern/vfs_bio.c (revision 7aa383846770374466b1dcb2cefd71bde9acf463)
1 /*-
2  * Copyright (c) 2004 Poul-Henning Kamp
3  * Copyright (c) 1994,1997 John S. Dyson
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 /*
29  * this file contains a new buffer I/O scheme implementing a coherent
30  * VM object and buffer cache scheme.  Pains have been taken to make
31  * sure that the performance degradation associated with schemes such
32  * as this is not realized.
33  *
34  * Author:  John S. Dyson
35  * Significant help during the development and debugging phases
36  * had been provided by David Greenman, also of the FreeBSD core team.
37  *
38  * see man buf(9) for more info.
39  */
40 
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/bio.h>
47 #include <sys/conf.h>
48 #include <sys/buf.h>
49 #include <sys/devicestat.h>
50 #include <sys/eventhandler.h>
51 #include <sys/fail.h>
52 #include <sys/limits.h>
53 #include <sys/lock.h>
54 #include <sys/malloc.h>
55 #include <sys/mount.h>
56 #include <sys/mutex.h>
57 #include <sys/kernel.h>
58 #include <sys/kthread.h>
59 #include <sys/proc.h>
60 #include <sys/resourcevar.h>
61 #include <sys/sysctl.h>
62 #include <sys/vmmeter.h>
63 #include <sys/vnode.h>
64 #include <geom/geom.h>
65 #include <vm/vm.h>
66 #include <vm/vm_param.h>
67 #include <vm/vm_kern.h>
68 #include <vm/vm_pageout.h>
69 #include <vm/vm_page.h>
70 #include <vm/vm_object.h>
71 #include <vm/vm_extern.h>
72 #include <vm/vm_map.h>
73 #include "opt_compat.h"
74 #include "opt_directio.h"
75 #include "opt_swap.h"
76 
77 static MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
78 
79 struct	bio_ops bioops;		/* I/O operation notification */
80 
81 struct	buf_ops buf_ops_bio = {
82 	.bop_name	=	"buf_ops_bio",
83 	.bop_write	=	bufwrite,
84 	.bop_strategy	=	bufstrategy,
85 	.bop_sync	=	bufsync,
86 	.bop_bdflush	=	bufbdflush,
87 };
88 
89 /*
90  * XXX buf is global because kern_shutdown.c and ffs_checkoverlap has
91  * carnal knowledge of buffers.  This knowledge should be moved to vfs_bio.c.
92  */
93 struct buf *buf;		/* buffer header pool */
94 
95 static struct proc *bufdaemonproc;
96 
97 static int inmem(struct vnode *vp, daddr_t blkno);
98 static void vm_hold_free_pages(struct buf *bp, int newbsize);
99 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
100 		vm_offset_t to);
101 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m);
102 static void vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off,
103 		vm_page_t m);
104 static void vfs_drain_busy_pages(struct buf *bp);
105 static void vfs_clean_pages_dirty_buf(struct buf *bp);
106 static void vfs_setdirty_locked_object(struct buf *bp);
107 static void vfs_vmio_release(struct buf *bp);
108 static int vfs_bio_clcheck(struct vnode *vp, int size,
109 		daddr_t lblkno, daddr_t blkno);
110 static int buf_do_flush(struct vnode *vp);
111 static int flushbufqueues(struct vnode *, int, int);
112 static void buf_daemon(void);
113 static void bremfreel(struct buf *bp);
114 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
115     defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
116 static int sysctl_bufspace(SYSCTL_HANDLER_ARGS);
117 #endif
118 
119 int vmiodirenable = TRUE;
120 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
121     "Use the VM system for directory writes");
122 long runningbufspace;
123 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
124     "Amount of presently outstanding async buffer io");
125 static long bufspace;
126 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
127     defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
128 SYSCTL_PROC(_vfs, OID_AUTO, bufspace, CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RD,
129     &bufspace, 0, sysctl_bufspace, "L", "Virtual memory used for buffers");
130 #else
131 SYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
132     "Virtual memory used for buffers");
133 #endif
134 static long maxbufspace;
135 SYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
136     "Maximum allowed value of bufspace (including buf_daemon)");
137 static long bufmallocspace;
138 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
139     "Amount of malloced memory for buffers");
140 static long maxbufmallocspace;
141 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace, 0,
142     "Maximum amount of malloced memory for buffers");
143 static long lobufspace;
144 SYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
145     "Minimum amount of buffers we want to have");
146 long hibufspace;
147 SYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
148     "Maximum allowed value of bufspace (excluding buf_daemon)");
149 static int bufreusecnt;
150 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW, &bufreusecnt, 0,
151     "Number of times we have reused a buffer");
152 static int buffreekvacnt;
153 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
154     "Number of times we have freed the KVA space from some buffer");
155 static int bufdefragcnt;
156 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
157     "Number of times we have had to repeat buffer allocation to defragment");
158 static long lorunningspace;
159 SYSCTL_LONG(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
160     "Minimum preferred space used for in-progress I/O");
161 static long hirunningspace;
162 SYSCTL_LONG(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
163     "Maximum amount of space to use for in-progress I/O");
164 int dirtybufferflushes;
165 SYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
166     0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
167 int bdwriteskip;
168 SYSCTL_INT(_vfs, OID_AUTO, bdwriteskip, CTLFLAG_RW, &bdwriteskip,
169     0, "Number of buffers supplied to bdwrite with snapshot deadlock risk");
170 int altbufferflushes;
171 SYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes,
172     0, "Number of fsync flushes to limit dirty buffers");
173 static int recursiveflushes;
174 SYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes,
175     0, "Number of flushes skipped due to being recursive");
176 static int numdirtybuffers;
177 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
178     "Number of buffers that are dirty (has unwritten changes) at the moment");
179 static int lodirtybuffers;
180 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
181     "How many buffers we want to have free before bufdaemon can sleep");
182 static int hidirtybuffers;
183 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
184     "When the number of dirty buffers is considered severe");
185 int dirtybufthresh;
186 SYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh,
187     0, "Number of bdwrite to bawrite conversions to clear dirty buffers");
188 static int numfreebuffers;
189 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
190     "Number of free buffers");
191 static int lofreebuffers;
192 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
193    "XXX Unused");
194 static int hifreebuffers;
195 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
196    "XXX Complicatedly unused");
197 static int getnewbufcalls;
198 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
199    "Number of calls to getnewbuf");
200 static int getnewbufrestarts;
201 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
202     "Number of times getnewbuf has had to restart a buffer aquisition");
203 static int flushbufqtarget = 100;
204 SYSCTL_INT(_vfs, OID_AUTO, flushbufqtarget, CTLFLAG_RW, &flushbufqtarget, 0,
205     "Amount of work to do in flushbufqueues when helping bufdaemon");
206 static long notbufdflashes;
207 SYSCTL_LONG(_vfs, OID_AUTO, notbufdflashes, CTLFLAG_RD, &notbufdflashes, 0,
208     "Number of dirty buffer flushes done by the bufdaemon helpers");
209 
210 /*
211  * Wakeup point for bufdaemon, as well as indicator of whether it is already
212  * active.  Set to 1 when the bufdaemon is already "on" the queue, 0 when it
213  * is idling.
214  */
215 static int bd_request;
216 
217 /*
218  * Request for the buf daemon to write more buffers than is indicated by
219  * lodirtybuf.  This may be necessary to push out excess dependencies or
220  * defragment the address space where a simple count of the number of dirty
221  * buffers is insufficient to characterize the demand for flushing them.
222  */
223 static int bd_speedupreq;
224 
225 /*
226  * This lock synchronizes access to bd_request.
227  */
228 static struct mtx bdlock;
229 
230 /*
231  * bogus page -- for I/O to/from partially complete buffers
232  * this is a temporary solution to the problem, but it is not
233  * really that bad.  it would be better to split the buffer
234  * for input in the case of buffers partially already in memory,
235  * but the code is intricate enough already.
236  */
237 vm_page_t bogus_page;
238 
239 /*
240  * Synchronization (sleep/wakeup) variable for active buffer space requests.
241  * Set when wait starts, cleared prior to wakeup().
242  * Used in runningbufwakeup() and waitrunningbufspace().
243  */
244 static int runningbufreq;
245 
246 /*
247  * This lock protects the runningbufreq and synchronizes runningbufwakeup and
248  * waitrunningbufspace().
249  */
250 static struct mtx rbreqlock;
251 
252 /*
253  * Synchronization (sleep/wakeup) variable for buffer requests.
254  * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
255  * by and/or.
256  * Used in numdirtywakeup(), bufspacewakeup(), bufcountwakeup(), bwillwrite(),
257  * getnewbuf(), and getblk().
258  */
259 static int needsbuffer;
260 
261 /*
262  * Lock that protects needsbuffer and the sleeps/wakeups surrounding it.
263  */
264 static struct mtx nblock;
265 
266 /*
267  * Definitions for the buffer free lists.
268  */
269 #define BUFFER_QUEUES	6	/* number of free buffer queues */
270 
271 #define QUEUE_NONE	0	/* on no queue */
272 #define QUEUE_CLEAN	1	/* non-B_DELWRI buffers */
273 #define QUEUE_DIRTY	2	/* B_DELWRI buffers */
274 #define QUEUE_DIRTY_GIANT 3	/* B_DELWRI buffers that need giant */
275 #define QUEUE_EMPTYKVA	4	/* empty buffer headers w/KVA assignment */
276 #define QUEUE_EMPTY	5	/* empty buffer headers */
277 #define QUEUE_SENTINEL	1024	/* not an queue index, but mark for sentinel */
278 
279 /* Queues for free buffers with various properties */
280 static TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
281 
282 /* Lock for the bufqueues */
283 static struct mtx bqlock;
284 
285 /*
286  * Single global constant for BUF_WMESG, to avoid getting multiple references.
287  * buf_wmesg is referred from macros.
288  */
289 const char *buf_wmesg = BUF_WMESG;
290 
291 #define VFS_BIO_NEED_ANY	0x01	/* any freeable buffer */
292 #define VFS_BIO_NEED_DIRTYFLUSH	0x02	/* waiting for dirty buffer flush */
293 #define VFS_BIO_NEED_FREE	0x04	/* wait for free bufs, hi hysteresis */
294 #define VFS_BIO_NEED_BUFSPACE	0x08	/* wait for buf space, lo hysteresis */
295 
296 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
297     defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
298 static int
299 sysctl_bufspace(SYSCTL_HANDLER_ARGS)
300 {
301 	long lvalue;
302 	int ivalue;
303 
304 	if (sizeof(int) == sizeof(long) || req->oldlen >= sizeof(long))
305 		return (sysctl_handle_long(oidp, arg1, arg2, req));
306 	lvalue = *(long *)arg1;
307 	if (lvalue > INT_MAX)
308 		/* On overflow, still write out a long to trigger ENOMEM. */
309 		return (sysctl_handle_long(oidp, &lvalue, 0, req));
310 	ivalue = lvalue;
311 	return (sysctl_handle_int(oidp, &ivalue, 0, req));
312 }
313 #endif
314 
315 #ifdef DIRECTIO
316 extern void ffs_rawread_setup(void);
317 #endif /* DIRECTIO */
318 /*
319  *	numdirtywakeup:
320  *
321  *	If someone is blocked due to there being too many dirty buffers,
322  *	and numdirtybuffers is now reasonable, wake them up.
323  */
324 
325 static __inline void
326 numdirtywakeup(int level)
327 {
328 
329 	if (numdirtybuffers <= level) {
330 		mtx_lock(&nblock);
331 		if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
332 			needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
333 			wakeup(&needsbuffer);
334 		}
335 		mtx_unlock(&nblock);
336 	}
337 }
338 
339 /*
340  *	bufspacewakeup:
341  *
342  *	Called when buffer space is potentially available for recovery.
343  *	getnewbuf() will block on this flag when it is unable to free
344  *	sufficient buffer space.  Buffer space becomes recoverable when
345  *	bp's get placed back in the queues.
346  */
347 
348 static __inline void
349 bufspacewakeup(void)
350 {
351 
352 	/*
353 	 * If someone is waiting for BUF space, wake them up.  Even
354 	 * though we haven't freed the kva space yet, the waiting
355 	 * process will be able to now.
356 	 */
357 	mtx_lock(&nblock);
358 	if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
359 		needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
360 		wakeup(&needsbuffer);
361 	}
362 	mtx_unlock(&nblock);
363 }
364 
365 /*
366  * runningbufwakeup() - in-progress I/O accounting.
367  *
368  */
369 void
370 runningbufwakeup(struct buf *bp)
371 {
372 
373 	if (bp->b_runningbufspace) {
374 		atomic_subtract_long(&runningbufspace, bp->b_runningbufspace);
375 		bp->b_runningbufspace = 0;
376 		mtx_lock(&rbreqlock);
377 		if (runningbufreq && runningbufspace <= lorunningspace) {
378 			runningbufreq = 0;
379 			wakeup(&runningbufreq);
380 		}
381 		mtx_unlock(&rbreqlock);
382 	}
383 }
384 
385 /*
386  *	bufcountwakeup:
387  *
388  *	Called when a buffer has been added to one of the free queues to
389  *	account for the buffer and to wakeup anyone waiting for free buffers.
390  *	This typically occurs when large amounts of metadata are being handled
391  *	by the buffer cache ( else buffer space runs out first, usually ).
392  */
393 
394 static __inline void
395 bufcountwakeup(struct buf *bp)
396 {
397 	int old;
398 
399 	KASSERT((bp->b_vflags & BV_INFREECNT) == 0,
400 	    ("buf %p already counted as free", bp));
401 	bp->b_vflags |= BV_INFREECNT;
402 	old = atomic_fetchadd_int(&numfreebuffers, 1);
403 	KASSERT(old >= 0 && old < nbuf,
404 	    ("numfreebuffers climbed to %d", old + 1));
405 	mtx_lock(&nblock);
406 	if (needsbuffer) {
407 		needsbuffer &= ~VFS_BIO_NEED_ANY;
408 		if (numfreebuffers >= hifreebuffers)
409 			needsbuffer &= ~VFS_BIO_NEED_FREE;
410 		wakeup(&needsbuffer);
411 	}
412 	mtx_unlock(&nblock);
413 }
414 
415 /*
416  *	waitrunningbufspace()
417  *
418  *	runningbufspace is a measure of the amount of I/O currently
419  *	running.  This routine is used in async-write situations to
420  *	prevent creating huge backups of pending writes to a device.
421  *	Only asynchronous writes are governed by this function.
422  *
423  *	Reads will adjust runningbufspace, but will not block based on it.
424  *	The read load has a side effect of reducing the allowed write load.
425  *
426  *	This does NOT turn an async write into a sync write.  It waits
427  *	for earlier writes to complete and generally returns before the
428  *	caller's write has reached the device.
429  */
430 void
431 waitrunningbufspace(void)
432 {
433 
434 	mtx_lock(&rbreqlock);
435 	while (runningbufspace > hirunningspace) {
436 		++runningbufreq;
437 		msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
438 	}
439 	mtx_unlock(&rbreqlock);
440 }
441 
442 
443 /*
444  *	vfs_buf_test_cache:
445  *
446  *	Called when a buffer is extended.  This function clears the B_CACHE
447  *	bit if the newly extended portion of the buffer does not contain
448  *	valid data.
449  */
450 static __inline
451 void
452 vfs_buf_test_cache(struct buf *bp,
453 		  vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
454 		  vm_page_t m)
455 {
456 
457 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
458 	if (bp->b_flags & B_CACHE) {
459 		int base = (foff + off) & PAGE_MASK;
460 		if (vm_page_is_valid(m, base, size) == 0)
461 			bp->b_flags &= ~B_CACHE;
462 	}
463 }
464 
465 /* Wake up the buffer daemon if necessary */
466 static __inline
467 void
468 bd_wakeup(int dirtybuflevel)
469 {
470 
471 	mtx_lock(&bdlock);
472 	if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
473 		bd_request = 1;
474 		wakeup(&bd_request);
475 	}
476 	mtx_unlock(&bdlock);
477 }
478 
479 /*
480  * bd_speedup - speedup the buffer cache flushing code
481  */
482 
483 void
484 bd_speedup(void)
485 {
486 	int needwake;
487 
488 	mtx_lock(&bdlock);
489 	needwake = 0;
490 	if (bd_speedupreq == 0 || bd_request == 0)
491 		needwake = 1;
492 	bd_speedupreq = 1;
493 	bd_request = 1;
494 	if (needwake)
495 		wakeup(&bd_request);
496 	mtx_unlock(&bdlock);
497 }
498 
499 /*
500  * Calculating buffer cache scaling values and reserve space for buffer
501  * headers.  This is called during low level kernel initialization and
502  * may be called more then once.  We CANNOT write to the memory area
503  * being reserved at this time.
504  */
505 caddr_t
506 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
507 {
508 	int tuned_nbuf;
509 	long maxbuf;
510 
511 	/*
512 	 * physmem_est is in pages.  Convert it to kilobytes (assumes
513 	 * PAGE_SIZE is >= 1K)
514 	 */
515 	physmem_est = physmem_est * (PAGE_SIZE / 1024);
516 
517 	/*
518 	 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
519 	 * For the first 64MB of ram nominally allocate sufficient buffers to
520 	 * cover 1/4 of our ram.  Beyond the first 64MB allocate additional
521 	 * buffers to cover 1/10 of our ram over 64MB.  When auto-sizing
522 	 * the buffer cache we limit the eventual kva reservation to
523 	 * maxbcache bytes.
524 	 *
525 	 * factor represents the 1/4 x ram conversion.
526 	 */
527 	if (nbuf == 0) {
528 		int factor = 4 * BKVASIZE / 1024;
529 
530 		nbuf = 50;
531 		if (physmem_est > 4096)
532 			nbuf += min((physmem_est - 4096) / factor,
533 			    65536 / factor);
534 		if (physmem_est > 65536)
535 			nbuf += (physmem_est - 65536) * 2 / (factor * 5);
536 
537 		if (maxbcache && nbuf > maxbcache / BKVASIZE)
538 			nbuf = maxbcache / BKVASIZE;
539 		tuned_nbuf = 1;
540 	} else
541 		tuned_nbuf = 0;
542 
543 	/* XXX Avoid unsigned long overflows later on with maxbufspace. */
544 	maxbuf = (LONG_MAX / 3) / BKVASIZE;
545 	if (nbuf > maxbuf) {
546 		if (!tuned_nbuf)
547 			printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
548 			    maxbuf);
549 		nbuf = maxbuf;
550 	}
551 
552 	/*
553 	 * swbufs are used as temporary holders for I/O, such as paging I/O.
554 	 * We have no less then 16 and no more then 256.
555 	 */
556 	nswbuf = max(min(nbuf/4, 256), 16);
557 #ifdef NSWBUF_MIN
558 	if (nswbuf < NSWBUF_MIN)
559 		nswbuf = NSWBUF_MIN;
560 #endif
561 #ifdef DIRECTIO
562 	ffs_rawread_setup();
563 #endif
564 
565 	/*
566 	 * Reserve space for the buffer cache buffers
567 	 */
568 	swbuf = (void *)v;
569 	v = (caddr_t)(swbuf + nswbuf);
570 	buf = (void *)v;
571 	v = (caddr_t)(buf + nbuf);
572 
573 	return(v);
574 }
575 
576 /* Initialize the buffer subsystem.  Called before use of any buffers. */
577 void
578 bufinit(void)
579 {
580 	struct buf *bp;
581 	int i;
582 
583 	mtx_init(&bqlock, "buf queue lock", NULL, MTX_DEF);
584 	mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
585 	mtx_init(&nblock, "needsbuffer lock", NULL, MTX_DEF);
586 	mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
587 
588 	/* next, make a null set of free lists */
589 	for (i = 0; i < BUFFER_QUEUES; i++)
590 		TAILQ_INIT(&bufqueues[i]);
591 
592 	/* finally, initialize each buffer header and stick on empty q */
593 	for (i = 0; i < nbuf; i++) {
594 		bp = &buf[i];
595 		bzero(bp, sizeof *bp);
596 		bp->b_flags = B_INVAL;	/* we're just an empty header */
597 		bp->b_rcred = NOCRED;
598 		bp->b_wcred = NOCRED;
599 		bp->b_qindex = QUEUE_EMPTY;
600 		bp->b_vflags = BV_INFREECNT;	/* buf is counted as free */
601 		bp->b_xflags = 0;
602 		LIST_INIT(&bp->b_dep);
603 		BUF_LOCKINIT(bp);
604 		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
605 	}
606 
607 	/*
608 	 * maxbufspace is the absolute maximum amount of buffer space we are
609 	 * allowed to reserve in KVM and in real terms.  The absolute maximum
610 	 * is nominally used by buf_daemon.  hibufspace is the nominal maximum
611 	 * used by most other processes.  The differential is required to
612 	 * ensure that buf_daemon is able to run when other processes might
613 	 * be blocked waiting for buffer space.
614 	 *
615 	 * maxbufspace is based on BKVASIZE.  Allocating buffers larger then
616 	 * this may result in KVM fragmentation which is not handled optimally
617 	 * by the system.
618 	 */
619 	maxbufspace = (long)nbuf * BKVASIZE;
620 	hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
621 	lobufspace = hibufspace - MAXBSIZE;
622 
623 	lorunningspace = 512 * 1024;
624 	hirunningspace = 1024 * 1024;
625 
626 /*
627  * Limit the amount of malloc memory since it is wired permanently into
628  * the kernel space.  Even though this is accounted for in the buffer
629  * allocation, we don't want the malloced region to grow uncontrolled.
630  * The malloc scheme improves memory utilization significantly on average
631  * (small) directories.
632  */
633 	maxbufmallocspace = hibufspace / 20;
634 
635 /*
636  * Reduce the chance of a deadlock occuring by limiting the number
637  * of delayed-write dirty buffers we allow to stack up.
638  */
639 	hidirtybuffers = nbuf / 4 + 20;
640 	dirtybufthresh = hidirtybuffers * 9 / 10;
641 	numdirtybuffers = 0;
642 /*
643  * To support extreme low-memory systems, make sure hidirtybuffers cannot
644  * eat up all available buffer space.  This occurs when our minimum cannot
645  * be met.  We try to size hidirtybuffers to 3/4 our buffer space assuming
646  * BKVASIZE'd (8K) buffers.
647  */
648 	while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
649 		hidirtybuffers >>= 1;
650 	}
651 	lodirtybuffers = hidirtybuffers / 2;
652 
653 /*
654  * Try to keep the number of free buffers in the specified range,
655  * and give special processes (e.g. like buf_daemon) access to an
656  * emergency reserve.
657  */
658 	lofreebuffers = nbuf / 18 + 5;
659 	hifreebuffers = 2 * lofreebuffers;
660 	numfreebuffers = nbuf;
661 
662 	bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
663 	    VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
664 }
665 
666 /*
667  * bfreekva() - free the kva allocation for a buffer.
668  *
669  *	Since this call frees up buffer space, we call bufspacewakeup().
670  */
671 static void
672 bfreekva(struct buf *bp)
673 {
674 
675 	if (bp->b_kvasize) {
676 		atomic_add_int(&buffreekvacnt, 1);
677 		atomic_subtract_long(&bufspace, bp->b_kvasize);
678 		vm_map_remove(buffer_map, (vm_offset_t) bp->b_kvabase,
679 		    (vm_offset_t) bp->b_kvabase + bp->b_kvasize);
680 		bp->b_kvasize = 0;
681 		bufspacewakeup();
682 	}
683 }
684 
685 /*
686  *	bremfree:
687  *
688  *	Mark the buffer for removal from the appropriate free list in brelse.
689  *
690  */
691 void
692 bremfree(struct buf *bp)
693 {
694 	int old;
695 
696 	CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
697 	KASSERT((bp->b_flags & B_REMFREE) == 0,
698 	    ("bremfree: buffer %p already marked for delayed removal.", bp));
699 	KASSERT(bp->b_qindex != QUEUE_NONE,
700 	    ("bremfree: buffer %p not on a queue.", bp));
701 	BUF_ASSERT_HELD(bp);
702 
703 	bp->b_flags |= B_REMFREE;
704 	/* Fixup numfreebuffers count.  */
705 	if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
706 		KASSERT((bp->b_vflags & BV_INFREECNT) != 0,
707 		    ("buf %p not counted in numfreebuffers", bp));
708 		bp->b_vflags &= ~BV_INFREECNT;
709 		old = atomic_fetchadd_int(&numfreebuffers, -1);
710 		KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
711 	}
712 }
713 
714 /*
715  *	bremfreef:
716  *
717  *	Force an immediate removal from a free list.  Used only in nfs when
718  *	it abuses the b_freelist pointer.
719  */
720 void
721 bremfreef(struct buf *bp)
722 {
723 	mtx_lock(&bqlock);
724 	bremfreel(bp);
725 	mtx_unlock(&bqlock);
726 }
727 
728 /*
729  *	bremfreel:
730  *
731  *	Removes a buffer from the free list, must be called with the
732  *	bqlock held.
733  */
734 static void
735 bremfreel(struct buf *bp)
736 {
737 	int old;
738 
739 	CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
740 	    bp, bp->b_vp, bp->b_flags);
741 	KASSERT(bp->b_qindex != QUEUE_NONE,
742 	    ("bremfreel: buffer %p not on a queue.", bp));
743 	BUF_ASSERT_HELD(bp);
744 	mtx_assert(&bqlock, MA_OWNED);
745 
746 	TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
747 	bp->b_qindex = QUEUE_NONE;
748 	/*
749 	 * If this was a delayed bremfree() we only need to remove the buffer
750 	 * from the queue and return the stats are already done.
751 	 */
752 	if (bp->b_flags & B_REMFREE) {
753 		bp->b_flags &= ~B_REMFREE;
754 		return;
755 	}
756 	/*
757 	 * Fixup numfreebuffers count.  If the buffer is invalid or not
758 	 * delayed-write, the buffer was free and we must decrement
759 	 * numfreebuffers.
760 	 */
761 	if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
762 		KASSERT((bp->b_vflags & BV_INFREECNT) != 0,
763 		    ("buf %p not counted in numfreebuffers", bp));
764 		bp->b_vflags &= ~BV_INFREECNT;
765 		old = atomic_fetchadd_int(&numfreebuffers, -1);
766 		KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
767 	}
768 }
769 
770 
771 /*
772  * Get a buffer with the specified data.  Look in the cache first.  We
773  * must clear BIO_ERROR and B_INVAL prior to initiating I/O.  If B_CACHE
774  * is set, the buffer is valid and we do not have to do anything ( see
775  * getblk() ).  This is really just a special case of breadn().
776  */
777 int
778 bread(struct vnode * vp, daddr_t blkno, int size, struct ucred * cred,
779     struct buf **bpp)
780 {
781 
782 	return (breadn(vp, blkno, size, 0, 0, 0, cred, bpp));
783 }
784 
785 /*
786  * Attempt to initiate asynchronous I/O on read-ahead blocks.  We must
787  * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
788  * the buffer is valid and we do not have to do anything.
789  */
790 void
791 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
792     int cnt, struct ucred * cred)
793 {
794 	struct buf *rabp;
795 	int i;
796 
797 	for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
798 		if (inmem(vp, *rablkno))
799 			continue;
800 		rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
801 
802 		if ((rabp->b_flags & B_CACHE) == 0) {
803 			if (!TD_IS_IDLETHREAD(curthread))
804 				curthread->td_ru.ru_inblock++;
805 			rabp->b_flags |= B_ASYNC;
806 			rabp->b_flags &= ~B_INVAL;
807 			rabp->b_ioflags &= ~BIO_ERROR;
808 			rabp->b_iocmd = BIO_READ;
809 			if (rabp->b_rcred == NOCRED && cred != NOCRED)
810 				rabp->b_rcred = crhold(cred);
811 			vfs_busy_pages(rabp, 0);
812 			BUF_KERNPROC(rabp);
813 			rabp->b_iooffset = dbtob(rabp->b_blkno);
814 			bstrategy(rabp);
815 		} else {
816 			brelse(rabp);
817 		}
818 	}
819 }
820 
821 /*
822  * Operates like bread, but also starts asynchronous I/O on
823  * read-ahead blocks.
824  */
825 int
826 breadn(struct vnode * vp, daddr_t blkno, int size,
827     daddr_t * rablkno, int *rabsize,
828     int cnt, struct ucred * cred, struct buf **bpp)
829 {
830 	struct buf *bp;
831 	int rv = 0, readwait = 0;
832 
833 	CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
834 	*bpp = bp = getblk(vp, blkno, size, 0, 0, 0);
835 
836 	/* if not found in cache, do some I/O */
837 	if ((bp->b_flags & B_CACHE) == 0) {
838 		if (!TD_IS_IDLETHREAD(curthread))
839 			curthread->td_ru.ru_inblock++;
840 		bp->b_iocmd = BIO_READ;
841 		bp->b_flags &= ~B_INVAL;
842 		bp->b_ioflags &= ~BIO_ERROR;
843 		if (bp->b_rcred == NOCRED && cred != NOCRED)
844 			bp->b_rcred = crhold(cred);
845 		vfs_busy_pages(bp, 0);
846 		bp->b_iooffset = dbtob(bp->b_blkno);
847 		bstrategy(bp);
848 		++readwait;
849 	}
850 
851 	breada(vp, rablkno, rabsize, cnt, cred);
852 
853 	if (readwait) {
854 		rv = bufwait(bp);
855 	}
856 	return (rv);
857 }
858 
859 /*
860  * Write, release buffer on completion.  (Done by iodone
861  * if async).  Do not bother writing anything if the buffer
862  * is invalid.
863  *
864  * Note that we set B_CACHE here, indicating that buffer is
865  * fully valid and thus cacheable.  This is true even of NFS
866  * now so we set it generally.  This could be set either here
867  * or in biodone() since the I/O is synchronous.  We put it
868  * here.
869  */
870 int
871 bufwrite(struct buf *bp)
872 {
873 	int oldflags;
874 	struct vnode *vp;
875 	int vp_md;
876 
877 	CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
878 	if (bp->b_flags & B_INVAL) {
879 		brelse(bp);
880 		return (0);
881 	}
882 
883 	oldflags = bp->b_flags;
884 
885 	BUF_ASSERT_HELD(bp);
886 
887 	if (bp->b_pin_count > 0)
888 		bunpin_wait(bp);
889 
890 	KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
891 	    ("FFS background buffer should not get here %p", bp));
892 
893 	vp = bp->b_vp;
894 	if (vp)
895 		vp_md = vp->v_vflag & VV_MD;
896 	else
897 		vp_md = 0;
898 
899 	/* Mark the buffer clean */
900 	bundirty(bp);
901 
902 	bp->b_flags &= ~B_DONE;
903 	bp->b_ioflags &= ~BIO_ERROR;
904 	bp->b_flags |= B_CACHE;
905 	bp->b_iocmd = BIO_WRITE;
906 
907 	bufobj_wref(bp->b_bufobj);
908 	vfs_busy_pages(bp, 1);
909 
910 	/*
911 	 * Normal bwrites pipeline writes
912 	 */
913 	bp->b_runningbufspace = bp->b_bufsize;
914 	atomic_add_long(&runningbufspace, bp->b_runningbufspace);
915 
916 	if (!TD_IS_IDLETHREAD(curthread))
917 		curthread->td_ru.ru_oublock++;
918 	if (oldflags & B_ASYNC)
919 		BUF_KERNPROC(bp);
920 	bp->b_iooffset = dbtob(bp->b_blkno);
921 	bstrategy(bp);
922 
923 	if ((oldflags & B_ASYNC) == 0) {
924 		int rtval = bufwait(bp);
925 		brelse(bp);
926 		return (rtval);
927 	} else {
928 		/*
929 		 * don't allow the async write to saturate the I/O
930 		 * system.  We will not deadlock here because
931 		 * we are blocking waiting for I/O that is already in-progress
932 		 * to complete. We do not block here if it is the update
933 		 * or syncer daemon trying to clean up as that can lead
934 		 * to deadlock.
935 		 */
936 		if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
937 			waitrunningbufspace();
938 	}
939 
940 	return (0);
941 }
942 
943 void
944 bufbdflush(struct bufobj *bo, struct buf *bp)
945 {
946 	struct buf *nbp;
947 
948 	if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
949 		(void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
950 		altbufferflushes++;
951 	} else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
952 		BO_LOCK(bo);
953 		/*
954 		 * Try to find a buffer to flush.
955 		 */
956 		TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
957 			if ((nbp->b_vflags & BV_BKGRDINPROG) ||
958 			    BUF_LOCK(nbp,
959 				     LK_EXCLUSIVE | LK_NOWAIT, NULL))
960 				continue;
961 			if (bp == nbp)
962 				panic("bdwrite: found ourselves");
963 			BO_UNLOCK(bo);
964 			/* Don't countdeps with the bo lock held. */
965 			if (buf_countdeps(nbp, 0)) {
966 				BO_LOCK(bo);
967 				BUF_UNLOCK(nbp);
968 				continue;
969 			}
970 			if (nbp->b_flags & B_CLUSTEROK) {
971 				vfs_bio_awrite(nbp);
972 			} else {
973 				bremfree(nbp);
974 				bawrite(nbp);
975 			}
976 			dirtybufferflushes++;
977 			break;
978 		}
979 		if (nbp == NULL)
980 			BO_UNLOCK(bo);
981 	}
982 }
983 
984 /*
985  * Delayed write. (Buffer is marked dirty).  Do not bother writing
986  * anything if the buffer is marked invalid.
987  *
988  * Note that since the buffer must be completely valid, we can safely
989  * set B_CACHE.  In fact, we have to set B_CACHE here rather then in
990  * biodone() in order to prevent getblk from writing the buffer
991  * out synchronously.
992  */
993 void
994 bdwrite(struct buf *bp)
995 {
996 	struct thread *td = curthread;
997 	struct vnode *vp;
998 	struct bufobj *bo;
999 
1000 	CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1001 	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1002 	BUF_ASSERT_HELD(bp);
1003 
1004 	if (bp->b_flags & B_INVAL) {
1005 		brelse(bp);
1006 		return;
1007 	}
1008 
1009 	/*
1010 	 * If we have too many dirty buffers, don't create any more.
1011 	 * If we are wildly over our limit, then force a complete
1012 	 * cleanup. Otherwise, just keep the situation from getting
1013 	 * out of control. Note that we have to avoid a recursive
1014 	 * disaster and not try to clean up after our own cleanup!
1015 	 */
1016 	vp = bp->b_vp;
1017 	bo = bp->b_bufobj;
1018 	if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
1019 		td->td_pflags |= TDP_INBDFLUSH;
1020 		BO_BDFLUSH(bo, bp);
1021 		td->td_pflags &= ~TDP_INBDFLUSH;
1022 	} else
1023 		recursiveflushes++;
1024 
1025 	bdirty(bp);
1026 	/*
1027 	 * Set B_CACHE, indicating that the buffer is fully valid.  This is
1028 	 * true even of NFS now.
1029 	 */
1030 	bp->b_flags |= B_CACHE;
1031 
1032 	/*
1033 	 * This bmap keeps the system from needing to do the bmap later,
1034 	 * perhaps when the system is attempting to do a sync.  Since it
1035 	 * is likely that the indirect block -- or whatever other datastructure
1036 	 * that the filesystem needs is still in memory now, it is a good
1037 	 * thing to do this.  Note also, that if the pageout daemon is
1038 	 * requesting a sync -- there might not be enough memory to do
1039 	 * the bmap then...  So, this is important to do.
1040 	 */
1041 	if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
1042 		VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
1043 	}
1044 
1045 	/*
1046 	 * Set the *dirty* buffer range based upon the VM system dirty
1047 	 * pages.
1048 	 *
1049 	 * Mark the buffer pages as clean.  We need to do this here to
1050 	 * satisfy the vnode_pager and the pageout daemon, so that it
1051 	 * thinks that the pages have been "cleaned".  Note that since
1052 	 * the pages are in a delayed write buffer -- the VFS layer
1053 	 * "will" see that the pages get written out on the next sync,
1054 	 * or perhaps the cluster will be completed.
1055 	 */
1056 	vfs_clean_pages_dirty_buf(bp);
1057 	bqrelse(bp);
1058 
1059 	/*
1060 	 * Wakeup the buffer flushing daemon if we have a lot of dirty
1061 	 * buffers (midpoint between our recovery point and our stall
1062 	 * point).
1063 	 */
1064 	bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1065 
1066 	/*
1067 	 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1068 	 * due to the softdep code.
1069 	 */
1070 }
1071 
1072 /*
1073  *	bdirty:
1074  *
1075  *	Turn buffer into delayed write request.  We must clear BIO_READ and
1076  *	B_RELBUF, and we must set B_DELWRI.  We reassign the buffer to
1077  *	itself to properly update it in the dirty/clean lists.  We mark it
1078  *	B_DONE to ensure that any asynchronization of the buffer properly
1079  *	clears B_DONE ( else a panic will occur later ).
1080  *
1081  *	bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1082  *	might have been set pre-getblk().  Unlike bwrite/bdwrite, bdirty()
1083  *	should only be called if the buffer is known-good.
1084  *
1085  *	Since the buffer is not on a queue, we do not update the numfreebuffers
1086  *	count.
1087  *
1088  *	The buffer must be on QUEUE_NONE.
1089  */
1090 void
1091 bdirty(struct buf *bp)
1092 {
1093 
1094 	CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
1095 	    bp, bp->b_vp, bp->b_flags);
1096 	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1097 	KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1098 	    ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1099 	BUF_ASSERT_HELD(bp);
1100 	bp->b_flags &= ~(B_RELBUF);
1101 	bp->b_iocmd = BIO_WRITE;
1102 
1103 	if ((bp->b_flags & B_DELWRI) == 0) {
1104 		bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
1105 		reassignbuf(bp);
1106 		atomic_add_int(&numdirtybuffers, 1);
1107 		bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1108 	}
1109 }
1110 
1111 /*
1112  *	bundirty:
1113  *
1114  *	Clear B_DELWRI for buffer.
1115  *
1116  *	Since the buffer is not on a queue, we do not update the numfreebuffers
1117  *	count.
1118  *
1119  *	The buffer must be on QUEUE_NONE.
1120  */
1121 
1122 void
1123 bundirty(struct buf *bp)
1124 {
1125 
1126 	CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1127 	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1128 	KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1129 	    ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1130 	BUF_ASSERT_HELD(bp);
1131 
1132 	if (bp->b_flags & B_DELWRI) {
1133 		bp->b_flags &= ~B_DELWRI;
1134 		reassignbuf(bp);
1135 		atomic_subtract_int(&numdirtybuffers, 1);
1136 		numdirtywakeup(lodirtybuffers);
1137 	}
1138 	/*
1139 	 * Since it is now being written, we can clear its deferred write flag.
1140 	 */
1141 	bp->b_flags &= ~B_DEFERRED;
1142 }
1143 
1144 /*
1145  *	bawrite:
1146  *
1147  *	Asynchronous write.  Start output on a buffer, but do not wait for
1148  *	it to complete.  The buffer is released when the output completes.
1149  *
1150  *	bwrite() ( or the VOP routine anyway ) is responsible for handling
1151  *	B_INVAL buffers.  Not us.
1152  */
1153 void
1154 bawrite(struct buf *bp)
1155 {
1156 
1157 	bp->b_flags |= B_ASYNC;
1158 	(void) bwrite(bp);
1159 }
1160 
1161 /*
1162  *	bwillwrite:
1163  *
1164  *	Called prior to the locking of any vnodes when we are expecting to
1165  *	write.  We do not want to starve the buffer cache with too many
1166  *	dirty buffers so we block here.  By blocking prior to the locking
1167  *	of any vnodes we attempt to avoid the situation where a locked vnode
1168  *	prevents the various system daemons from flushing related buffers.
1169  */
1170 
1171 void
1172 bwillwrite(void)
1173 {
1174 
1175 	if (numdirtybuffers >= hidirtybuffers) {
1176 		mtx_lock(&nblock);
1177 		while (numdirtybuffers >= hidirtybuffers) {
1178 			bd_wakeup(1);
1179 			needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
1180 			msleep(&needsbuffer, &nblock,
1181 			    (PRIBIO + 4), "flswai", 0);
1182 		}
1183 		mtx_unlock(&nblock);
1184 	}
1185 }
1186 
1187 /*
1188  * Return true if we have too many dirty buffers.
1189  */
1190 int
1191 buf_dirty_count_severe(void)
1192 {
1193 
1194 	return(numdirtybuffers >= hidirtybuffers);
1195 }
1196 
1197 static __noinline int
1198 buf_vm_page_count_severe(void)
1199 {
1200 
1201 	KFAIL_POINT_CODE(DEBUG_FP, buf_pressure, return 1);
1202 
1203 	return vm_page_count_severe();
1204 }
1205 
1206 /*
1207  *	brelse:
1208  *
1209  *	Release a busy buffer and, if requested, free its resources.  The
1210  *	buffer will be stashed in the appropriate bufqueue[] allowing it
1211  *	to be accessed later as a cache entity or reused for other purposes.
1212  */
1213 void
1214 brelse(struct buf *bp)
1215 {
1216 	CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
1217 	    bp, bp->b_vp, bp->b_flags);
1218 	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1219 	    ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1220 
1221 	if (bp->b_flags & B_MANAGED) {
1222 		bqrelse(bp);
1223 		return;
1224 	}
1225 
1226 	if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
1227 	    bp->b_error == EIO && !(bp->b_flags & B_INVAL)) {
1228 		/*
1229 		 * Failed write, redirty.  Must clear BIO_ERROR to prevent
1230 		 * pages from being scrapped.  If the error is anything
1231 		 * other than an I/O error (EIO), assume that retrying
1232 		 * is futile.
1233 		 */
1234 		bp->b_ioflags &= ~BIO_ERROR;
1235 		bdirty(bp);
1236 	} else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1237 	    (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
1238 		/*
1239 		 * Either a failed I/O or we were asked to free or not
1240 		 * cache the buffer.
1241 		 */
1242 		bp->b_flags |= B_INVAL;
1243 		if (!LIST_EMPTY(&bp->b_dep))
1244 			buf_deallocate(bp);
1245 		if (bp->b_flags & B_DELWRI) {
1246 			atomic_subtract_int(&numdirtybuffers, 1);
1247 			numdirtywakeup(lodirtybuffers);
1248 		}
1249 		bp->b_flags &= ~(B_DELWRI | B_CACHE);
1250 		if ((bp->b_flags & B_VMIO) == 0) {
1251 			if (bp->b_bufsize)
1252 				allocbuf(bp, 0);
1253 			if (bp->b_vp)
1254 				brelvp(bp);
1255 		}
1256 	}
1257 
1258 	/*
1259 	 * We must clear B_RELBUF if B_DELWRI is set.  If vfs_vmio_release()
1260 	 * is called with B_DELWRI set, the underlying pages may wind up
1261 	 * getting freed causing a previous write (bdwrite()) to get 'lost'
1262 	 * because pages associated with a B_DELWRI bp are marked clean.
1263 	 *
1264 	 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1265 	 * if B_DELWRI is set.
1266 	 *
1267 	 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1268 	 * on pages to return pages to the VM page queues.
1269 	 */
1270 	if (bp->b_flags & B_DELWRI)
1271 		bp->b_flags &= ~B_RELBUF;
1272 	else if (buf_vm_page_count_severe()) {
1273 		/*
1274 		 * The locking of the BO_LOCK is not necessary since
1275 		 * BKGRDINPROG cannot be set while we hold the buf
1276 		 * lock, it can only be cleared if it is already
1277 		 * pending.
1278 		 */
1279 		if (bp->b_vp) {
1280 			if (!(bp->b_vflags & BV_BKGRDINPROG))
1281 				bp->b_flags |= B_RELBUF;
1282 		} else
1283 			bp->b_flags |= B_RELBUF;
1284 	}
1285 
1286 	/*
1287 	 * VMIO buffer rundown.  It is not very necessary to keep a VMIO buffer
1288 	 * constituted, not even NFS buffers now.  Two flags effect this.  If
1289 	 * B_INVAL, the struct buf is invalidated but the VM object is kept
1290 	 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1291 	 *
1292 	 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1293 	 * invalidated.  BIO_ERROR cannot be set for a failed write unless the
1294 	 * buffer is also B_INVAL because it hits the re-dirtying code above.
1295 	 *
1296 	 * Normally we can do this whether a buffer is B_DELWRI or not.  If
1297 	 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1298 	 * the commit state and we cannot afford to lose the buffer. If the
1299 	 * buffer has a background write in progress, we need to keep it
1300 	 * around to prevent it from being reconstituted and starting a second
1301 	 * background write.
1302 	 */
1303 	if ((bp->b_flags & B_VMIO)
1304 	    && !(bp->b_vp->v_mount != NULL &&
1305 		 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1306 		 !vn_isdisk(bp->b_vp, NULL) &&
1307 		 (bp->b_flags & B_DELWRI))
1308 	    ) {
1309 
1310 		int i, j, resid;
1311 		vm_page_t m;
1312 		off_t foff;
1313 		vm_pindex_t poff;
1314 		vm_object_t obj;
1315 
1316 		obj = bp->b_bufobj->bo_object;
1317 
1318 		/*
1319 		 * Get the base offset and length of the buffer.  Note that
1320 		 * in the VMIO case if the buffer block size is not
1321 		 * page-aligned then b_data pointer may not be page-aligned.
1322 		 * But our b_pages[] array *IS* page aligned.
1323 		 *
1324 		 * block sizes less then DEV_BSIZE (usually 512) are not
1325 		 * supported due to the page granularity bits (m->valid,
1326 		 * m->dirty, etc...).
1327 		 *
1328 		 * See man buf(9) for more information
1329 		 */
1330 		resid = bp->b_bufsize;
1331 		foff = bp->b_offset;
1332 		VM_OBJECT_LOCK(obj);
1333 		for (i = 0; i < bp->b_npages; i++) {
1334 			int had_bogus = 0;
1335 
1336 			m = bp->b_pages[i];
1337 
1338 			/*
1339 			 * If we hit a bogus page, fixup *all* the bogus pages
1340 			 * now.
1341 			 */
1342 			if (m == bogus_page) {
1343 				poff = OFF_TO_IDX(bp->b_offset);
1344 				had_bogus = 1;
1345 
1346 				for (j = i; j < bp->b_npages; j++) {
1347 					vm_page_t mtmp;
1348 					mtmp = bp->b_pages[j];
1349 					if (mtmp == bogus_page) {
1350 						mtmp = vm_page_lookup(obj, poff + j);
1351 						if (!mtmp) {
1352 							panic("brelse: page missing\n");
1353 						}
1354 						bp->b_pages[j] = mtmp;
1355 					}
1356 				}
1357 
1358 				if ((bp->b_flags & B_INVAL) == 0) {
1359 					pmap_qenter(
1360 					    trunc_page((vm_offset_t)bp->b_data),
1361 					    bp->b_pages, bp->b_npages);
1362 				}
1363 				m = bp->b_pages[i];
1364 			}
1365 			if ((bp->b_flags & B_NOCACHE) ||
1366 			    (bp->b_ioflags & BIO_ERROR &&
1367 			     bp->b_iocmd == BIO_READ)) {
1368 				int poffset = foff & PAGE_MASK;
1369 				int presid = resid > (PAGE_SIZE - poffset) ?
1370 					(PAGE_SIZE - poffset) : resid;
1371 
1372 				KASSERT(presid >= 0, ("brelse: extra page"));
1373 				vm_page_set_invalid(m, poffset, presid);
1374 				if (had_bogus)
1375 					printf("avoided corruption bug in bogus_page/brelse code\n");
1376 			}
1377 			resid -= PAGE_SIZE - (foff & PAGE_MASK);
1378 			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1379 		}
1380 		VM_OBJECT_UNLOCK(obj);
1381 		if (bp->b_flags & (B_INVAL | B_RELBUF))
1382 			vfs_vmio_release(bp);
1383 
1384 	} else if (bp->b_flags & B_VMIO) {
1385 
1386 		if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1387 			vfs_vmio_release(bp);
1388 		}
1389 
1390 	} else if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0) {
1391 		if (bp->b_bufsize != 0)
1392 			allocbuf(bp, 0);
1393 		if (bp->b_vp != NULL)
1394 			brelvp(bp);
1395 	}
1396 
1397 	if (BUF_LOCKRECURSED(bp)) {
1398 		/* do not release to free list */
1399 		BUF_UNLOCK(bp);
1400 		return;
1401 	}
1402 
1403 	/* enqueue */
1404 	mtx_lock(&bqlock);
1405 	/* Handle delayed bremfree() processing. */
1406 	if (bp->b_flags & B_REMFREE)
1407 		bremfreel(bp);
1408 	if (bp->b_qindex != QUEUE_NONE)
1409 		panic("brelse: free buffer onto another queue???");
1410 
1411 	/*
1412 	 * If the buffer has junk contents signal it and eventually
1413 	 * clean up B_DELWRI and diassociate the vnode so that gbincore()
1414 	 * doesn't find it.
1415 	 */
1416 	if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
1417 	    (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
1418 		bp->b_flags |= B_INVAL;
1419 	if (bp->b_flags & B_INVAL) {
1420 		if (bp->b_flags & B_DELWRI)
1421 			bundirty(bp);
1422 		if (bp->b_vp)
1423 			brelvp(bp);
1424 	}
1425 
1426 	/* buffers with no memory */
1427 	if (bp->b_bufsize == 0) {
1428 		bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1429 		if (bp->b_vflags & BV_BKGRDINPROG)
1430 			panic("losing buffer 1");
1431 		if (bp->b_kvasize) {
1432 			bp->b_qindex = QUEUE_EMPTYKVA;
1433 		} else {
1434 			bp->b_qindex = QUEUE_EMPTY;
1435 		}
1436 		TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1437 	/* buffers with junk contents */
1438 	} else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1439 	    (bp->b_ioflags & BIO_ERROR)) {
1440 		bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1441 		if (bp->b_vflags & BV_BKGRDINPROG)
1442 			panic("losing buffer 2");
1443 		bp->b_qindex = QUEUE_CLEAN;
1444 		TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1445 	/* remaining buffers */
1446 	} else {
1447 		if ((bp->b_flags & (B_DELWRI|B_NEEDSGIANT)) ==
1448 		    (B_DELWRI|B_NEEDSGIANT))
1449 			bp->b_qindex = QUEUE_DIRTY_GIANT;
1450 		else if (bp->b_flags & B_DELWRI)
1451 			bp->b_qindex = QUEUE_DIRTY;
1452 		else
1453 			bp->b_qindex = QUEUE_CLEAN;
1454 		if (bp->b_flags & B_AGE)
1455 			TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1456 		else
1457 			TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1458 	}
1459 	mtx_unlock(&bqlock);
1460 
1461 	/*
1462 	 * Fixup numfreebuffers count.  The bp is on an appropriate queue
1463 	 * unless locked.  We then bump numfreebuffers if it is not B_DELWRI.
1464 	 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1465 	 * if B_INVAL is set ).
1466 	 */
1467 
1468 	if (!(bp->b_flags & B_DELWRI))
1469 		bufcountwakeup(bp);
1470 
1471 	/*
1472 	 * Something we can maybe free or reuse
1473 	 */
1474 	if (bp->b_bufsize || bp->b_kvasize)
1475 		bufspacewakeup();
1476 
1477 	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1478 	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1479 		panic("brelse: not dirty");
1480 	/* unlock */
1481 	BUF_UNLOCK(bp);
1482 }
1483 
1484 /*
1485  * Release a buffer back to the appropriate queue but do not try to free
1486  * it.  The buffer is expected to be used again soon.
1487  *
1488  * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1489  * biodone() to requeue an async I/O on completion.  It is also used when
1490  * known good buffers need to be requeued but we think we may need the data
1491  * again soon.
1492  *
1493  * XXX we should be able to leave the B_RELBUF hint set on completion.
1494  */
1495 void
1496 bqrelse(struct buf *bp)
1497 {
1498 	CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1499 	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1500 	    ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1501 
1502 	if (BUF_LOCKRECURSED(bp)) {
1503 		/* do not release to free list */
1504 		BUF_UNLOCK(bp);
1505 		return;
1506 	}
1507 
1508 	if (bp->b_flags & B_MANAGED) {
1509 		if (bp->b_flags & B_REMFREE) {
1510 			mtx_lock(&bqlock);
1511 			bremfreel(bp);
1512 			mtx_unlock(&bqlock);
1513 		}
1514 		bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1515 		BUF_UNLOCK(bp);
1516 		return;
1517 	}
1518 
1519 	mtx_lock(&bqlock);
1520 	/* Handle delayed bremfree() processing. */
1521 	if (bp->b_flags & B_REMFREE)
1522 		bremfreel(bp);
1523 	if (bp->b_qindex != QUEUE_NONE)
1524 		panic("bqrelse: free buffer onto another queue???");
1525 	/* buffers with stale but valid contents */
1526 	if (bp->b_flags & B_DELWRI) {
1527 		if (bp->b_flags & B_NEEDSGIANT)
1528 			bp->b_qindex = QUEUE_DIRTY_GIANT;
1529 		else
1530 			bp->b_qindex = QUEUE_DIRTY;
1531 		TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1532 	} else {
1533 		/*
1534 		 * The locking of the BO_LOCK for checking of the
1535 		 * BV_BKGRDINPROG is not necessary since the
1536 		 * BV_BKGRDINPROG cannot be set while we hold the buf
1537 		 * lock, it can only be cleared if it is already
1538 		 * pending.
1539 		 */
1540 		if (!buf_vm_page_count_severe() || (bp->b_vflags & BV_BKGRDINPROG)) {
1541 			bp->b_qindex = QUEUE_CLEAN;
1542 			TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp,
1543 			    b_freelist);
1544 		} else {
1545 			/*
1546 			 * We are too low on memory, we have to try to free
1547 			 * the buffer (most importantly: the wired pages
1548 			 * making up its backing store) *now*.
1549 			 */
1550 			mtx_unlock(&bqlock);
1551 			brelse(bp);
1552 			return;
1553 		}
1554 	}
1555 	mtx_unlock(&bqlock);
1556 
1557 	if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))
1558 		bufcountwakeup(bp);
1559 
1560 	/*
1561 	 * Something we can maybe free or reuse.
1562 	 */
1563 	if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1564 		bufspacewakeup();
1565 
1566 	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1567 	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1568 		panic("bqrelse: not dirty");
1569 	/* unlock */
1570 	BUF_UNLOCK(bp);
1571 }
1572 
1573 /* Give pages used by the bp back to the VM system (where possible) */
1574 static void
1575 vfs_vmio_release(struct buf *bp)
1576 {
1577 	int i;
1578 	vm_page_t m;
1579 
1580 	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
1581 	for (i = 0; i < bp->b_npages; i++) {
1582 		m = bp->b_pages[i];
1583 		bp->b_pages[i] = NULL;
1584 		/*
1585 		 * In order to keep page LRU ordering consistent, put
1586 		 * everything on the inactive queue.
1587 		 */
1588 		vm_page_lock(m);
1589 		vm_page_unwire(m, 0);
1590 		/*
1591 		 * We don't mess with busy pages, it is
1592 		 * the responsibility of the process that
1593 		 * busied the pages to deal with them.
1594 		 */
1595 		if ((m->oflags & VPO_BUSY) == 0 && m->busy == 0 &&
1596 		    m->wire_count == 0) {
1597 			/*
1598 			 * Might as well free the page if we can and it has
1599 			 * no valid data.  We also free the page if the
1600 			 * buffer was used for direct I/O
1601 			 */
1602 			if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1603 			    m->hold_count == 0) {
1604 				vm_page_free(m);
1605 			} else if (bp->b_flags & B_DIRECT) {
1606 				vm_page_try_to_free(m);
1607 			} else if (buf_vm_page_count_severe()) {
1608 				vm_page_try_to_cache(m);
1609 			}
1610 		}
1611 		vm_page_unlock(m);
1612 	}
1613 	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
1614 	pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
1615 
1616 	if (bp->b_bufsize) {
1617 		bufspacewakeup();
1618 		bp->b_bufsize = 0;
1619 	}
1620 	bp->b_npages = 0;
1621 	bp->b_flags &= ~B_VMIO;
1622 	if (bp->b_vp)
1623 		brelvp(bp);
1624 }
1625 
1626 /*
1627  * Check to see if a block at a particular lbn is available for a clustered
1628  * write.
1629  */
1630 static int
1631 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1632 {
1633 	struct buf *bpa;
1634 	int match;
1635 
1636 	match = 0;
1637 
1638 	/* If the buf isn't in core skip it */
1639 	if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1640 		return (0);
1641 
1642 	/* If the buf is busy we don't want to wait for it */
1643 	if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1644 		return (0);
1645 
1646 	/* Only cluster with valid clusterable delayed write buffers */
1647 	if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1648 	    (B_DELWRI | B_CLUSTEROK))
1649 		goto done;
1650 
1651 	if (bpa->b_bufsize != size)
1652 		goto done;
1653 
1654 	/*
1655 	 * Check to see if it is in the expected place on disk and that the
1656 	 * block has been mapped.
1657 	 */
1658 	if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1659 		match = 1;
1660 done:
1661 	BUF_UNLOCK(bpa);
1662 	return (match);
1663 }
1664 
1665 /*
1666  *	vfs_bio_awrite:
1667  *
1668  *	Implement clustered async writes for clearing out B_DELWRI buffers.
1669  *	This is much better then the old way of writing only one buffer at
1670  *	a time.  Note that we may not be presented with the buffers in the
1671  *	correct order, so we search for the cluster in both directions.
1672  */
1673 int
1674 vfs_bio_awrite(struct buf *bp)
1675 {
1676 	struct bufobj *bo;
1677 	int i;
1678 	int j;
1679 	daddr_t lblkno = bp->b_lblkno;
1680 	struct vnode *vp = bp->b_vp;
1681 	int ncl;
1682 	int nwritten;
1683 	int size;
1684 	int maxcl;
1685 
1686 	bo = &vp->v_bufobj;
1687 	/*
1688 	 * right now we support clustered writing only to regular files.  If
1689 	 * we find a clusterable block we could be in the middle of a cluster
1690 	 * rather then at the beginning.
1691 	 */
1692 	if ((vp->v_type == VREG) &&
1693 	    (vp->v_mount != 0) && /* Only on nodes that have the size info */
1694 	    (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1695 
1696 		size = vp->v_mount->mnt_stat.f_iosize;
1697 		maxcl = MAXPHYS / size;
1698 
1699 		BO_LOCK(bo);
1700 		for (i = 1; i < maxcl; i++)
1701 			if (vfs_bio_clcheck(vp, size, lblkno + i,
1702 			    bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1703 				break;
1704 
1705 		for (j = 1; i + j <= maxcl && j <= lblkno; j++)
1706 			if (vfs_bio_clcheck(vp, size, lblkno - j,
1707 			    bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
1708 				break;
1709 		BO_UNLOCK(bo);
1710 		--j;
1711 		ncl = i + j;
1712 		/*
1713 		 * this is a possible cluster write
1714 		 */
1715 		if (ncl != 1) {
1716 			BUF_UNLOCK(bp);
1717 			nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1718 			return nwritten;
1719 		}
1720 	}
1721 	bremfree(bp);
1722 	bp->b_flags |= B_ASYNC;
1723 	/*
1724 	 * default (old) behavior, writing out only one block
1725 	 *
1726 	 * XXX returns b_bufsize instead of b_bcount for nwritten?
1727 	 */
1728 	nwritten = bp->b_bufsize;
1729 	(void) bwrite(bp);
1730 
1731 	return nwritten;
1732 }
1733 
1734 /*
1735  *	getnewbuf:
1736  *
1737  *	Find and initialize a new buffer header, freeing up existing buffers
1738  *	in the bufqueues as necessary.  The new buffer is returned locked.
1739  *
1740  *	Important:  B_INVAL is not set.  If the caller wishes to throw the
1741  *	buffer away, the caller must set B_INVAL prior to calling brelse().
1742  *
1743  *	We block if:
1744  *		We have insufficient buffer headers
1745  *		We have insufficient buffer space
1746  *		buffer_map is too fragmented ( space reservation fails )
1747  *		If we have to flush dirty buffers ( but we try to avoid this )
1748  *
1749  *	To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1750  *	Instead we ask the buf daemon to do it for us.  We attempt to
1751  *	avoid piecemeal wakeups of the pageout daemon.
1752  */
1753 
1754 static struct buf *
1755 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int size, int maxsize,
1756     int gbflags)
1757 {
1758 	struct thread *td;
1759 	struct buf *bp;
1760 	struct buf *nbp;
1761 	int defrag = 0;
1762 	int nqindex;
1763 	static int flushingbufs;
1764 
1765 	td = curthread;
1766 	/*
1767 	 * We can't afford to block since we might be holding a vnode lock,
1768 	 * which may prevent system daemons from running.  We deal with
1769 	 * low-memory situations by proactively returning memory and running
1770 	 * async I/O rather then sync I/O.
1771 	 */
1772 	atomic_add_int(&getnewbufcalls, 1);
1773 	atomic_subtract_int(&getnewbufrestarts, 1);
1774 restart:
1775 	atomic_add_int(&getnewbufrestarts, 1);
1776 
1777 	/*
1778 	 * Setup for scan.  If we do not have enough free buffers,
1779 	 * we setup a degenerate case that immediately fails.  Note
1780 	 * that if we are specially marked process, we are allowed to
1781 	 * dip into our reserves.
1782 	 *
1783 	 * The scanning sequence is nominally:  EMPTY->EMPTYKVA->CLEAN
1784 	 *
1785 	 * We start with EMPTYKVA.  If the list is empty we backup to EMPTY.
1786 	 * However, there are a number of cases (defragging, reusing, ...)
1787 	 * where we cannot backup.
1788 	 */
1789 	mtx_lock(&bqlock);
1790 	nqindex = QUEUE_EMPTYKVA;
1791 	nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1792 
1793 	if (nbp == NULL) {
1794 		/*
1795 		 * If no EMPTYKVA buffers and we are either
1796 		 * defragging or reusing, locate a CLEAN buffer
1797 		 * to free or reuse.  If bufspace useage is low
1798 		 * skip this step so we can allocate a new buffer.
1799 		 */
1800 		if (defrag || bufspace >= lobufspace) {
1801 			nqindex = QUEUE_CLEAN;
1802 			nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1803 		}
1804 
1805 		/*
1806 		 * If we could not find or were not allowed to reuse a
1807 		 * CLEAN buffer, check to see if it is ok to use an EMPTY
1808 		 * buffer.  We can only use an EMPTY buffer if allocating
1809 		 * its KVA would not otherwise run us out of buffer space.
1810 		 */
1811 		if (nbp == NULL && defrag == 0 &&
1812 		    bufspace + maxsize < hibufspace) {
1813 			nqindex = QUEUE_EMPTY;
1814 			nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1815 		}
1816 	}
1817 
1818 	/*
1819 	 * Run scan, possibly freeing data and/or kva mappings on the fly
1820 	 * depending.
1821 	 */
1822 
1823 	while ((bp = nbp) != NULL) {
1824 		int qindex = nqindex;
1825 
1826 		/*
1827 		 * Calculate next bp ( we can only use it if we do not block
1828 		 * or do other fancy things ).
1829 		 */
1830 		if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1831 			switch(qindex) {
1832 			case QUEUE_EMPTY:
1833 				nqindex = QUEUE_EMPTYKVA;
1834 				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1835 					break;
1836 				/* FALLTHROUGH */
1837 			case QUEUE_EMPTYKVA:
1838 				nqindex = QUEUE_CLEAN;
1839 				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1840 					break;
1841 				/* FALLTHROUGH */
1842 			case QUEUE_CLEAN:
1843 				/*
1844 				 * nbp is NULL.
1845 				 */
1846 				break;
1847 			}
1848 		}
1849 		/*
1850 		 * If we are defragging then we need a buffer with
1851 		 * b_kvasize != 0.  XXX this situation should no longer
1852 		 * occur, if defrag is non-zero the buffer's b_kvasize
1853 		 * should also be non-zero at this point.  XXX
1854 		 */
1855 		if (defrag && bp->b_kvasize == 0) {
1856 			printf("Warning: defrag empty buffer %p\n", bp);
1857 			continue;
1858 		}
1859 
1860 		/*
1861 		 * Start freeing the bp.  This is somewhat involved.  nbp
1862 		 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1863 		 */
1864 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1865 			continue;
1866 		if (bp->b_vp) {
1867 			BO_LOCK(bp->b_bufobj);
1868 			if (bp->b_vflags & BV_BKGRDINPROG) {
1869 				BO_UNLOCK(bp->b_bufobj);
1870 				BUF_UNLOCK(bp);
1871 				continue;
1872 			}
1873 			BO_UNLOCK(bp->b_bufobj);
1874 		}
1875 		CTR6(KTR_BUF,
1876 		    "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
1877 		    "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
1878 		    bp->b_kvasize, bp->b_bufsize, qindex);
1879 
1880 		/*
1881 		 * Sanity Checks
1882 		 */
1883 		KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1884 
1885 		/*
1886 		 * Note: we no longer distinguish between VMIO and non-VMIO
1887 		 * buffers.
1888 		 */
1889 
1890 		KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1891 
1892 		bremfreel(bp);
1893 		mtx_unlock(&bqlock);
1894 
1895 		if (qindex == QUEUE_CLEAN) {
1896 			if (bp->b_flags & B_VMIO) {
1897 				bp->b_flags &= ~B_ASYNC;
1898 				vfs_vmio_release(bp);
1899 			}
1900 			if (bp->b_vp)
1901 				brelvp(bp);
1902 		}
1903 
1904 		/*
1905 		 * NOTE:  nbp is now entirely invalid.  We can only restart
1906 		 * the scan from this point on.
1907 		 *
1908 		 * Get the rest of the buffer freed up.  b_kva* is still
1909 		 * valid after this operation.
1910 		 */
1911 
1912 		if (bp->b_rcred != NOCRED) {
1913 			crfree(bp->b_rcred);
1914 			bp->b_rcred = NOCRED;
1915 		}
1916 		if (bp->b_wcred != NOCRED) {
1917 			crfree(bp->b_wcred);
1918 			bp->b_wcred = NOCRED;
1919 		}
1920 		if (!LIST_EMPTY(&bp->b_dep))
1921 			buf_deallocate(bp);
1922 		if (bp->b_vflags & BV_BKGRDINPROG)
1923 			panic("losing buffer 3");
1924 		KASSERT(bp->b_vp == NULL,
1925 		    ("bp: %p still has vnode %p.  qindex: %d",
1926 		    bp, bp->b_vp, qindex));
1927 		KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
1928 		   ("bp: %p still on a buffer list. xflags %X",
1929 		    bp, bp->b_xflags));
1930 
1931 		if (bp->b_bufsize)
1932 			allocbuf(bp, 0);
1933 
1934 		bp->b_flags = 0;
1935 		bp->b_ioflags = 0;
1936 		bp->b_xflags = 0;
1937 		KASSERT((bp->b_vflags & BV_INFREECNT) == 0,
1938 		    ("buf %p still counted as free?", bp));
1939 		bp->b_vflags = 0;
1940 		bp->b_vp = NULL;
1941 		bp->b_blkno = bp->b_lblkno = 0;
1942 		bp->b_offset = NOOFFSET;
1943 		bp->b_iodone = 0;
1944 		bp->b_error = 0;
1945 		bp->b_resid = 0;
1946 		bp->b_bcount = 0;
1947 		bp->b_npages = 0;
1948 		bp->b_dirtyoff = bp->b_dirtyend = 0;
1949 		bp->b_bufobj = NULL;
1950 		bp->b_pin_count = 0;
1951 		bp->b_fsprivate1 = NULL;
1952 		bp->b_fsprivate2 = NULL;
1953 		bp->b_fsprivate3 = NULL;
1954 
1955 		LIST_INIT(&bp->b_dep);
1956 
1957 		/*
1958 		 * If we are defragging then free the buffer.
1959 		 */
1960 		if (defrag) {
1961 			bp->b_flags |= B_INVAL;
1962 			bfreekva(bp);
1963 			brelse(bp);
1964 			defrag = 0;
1965 			goto restart;
1966 		}
1967 
1968 		/*
1969 		 * Notify any waiters for the buffer lock about
1970 		 * identity change by freeing the buffer.
1971 		 */
1972 		if (qindex == QUEUE_CLEAN && BUF_LOCKWAITERS(bp)) {
1973 			bp->b_flags |= B_INVAL;
1974 			bfreekva(bp);
1975 			brelse(bp);
1976 			goto restart;
1977 		}
1978 
1979 		/*
1980 		 * If we are overcomitted then recover the buffer and its
1981 		 * KVM space.  This occurs in rare situations when multiple
1982 		 * processes are blocked in getnewbuf() or allocbuf().
1983 		 */
1984 		if (bufspace >= hibufspace)
1985 			flushingbufs = 1;
1986 		if (flushingbufs && bp->b_kvasize != 0) {
1987 			bp->b_flags |= B_INVAL;
1988 			bfreekva(bp);
1989 			brelse(bp);
1990 			goto restart;
1991 		}
1992 		if (bufspace < lobufspace)
1993 			flushingbufs = 0;
1994 		break;
1995 	}
1996 
1997 	/*
1998 	 * If we exhausted our list, sleep as appropriate.  We may have to
1999 	 * wakeup various daemons and write out some dirty buffers.
2000 	 *
2001 	 * Generally we are sleeping due to insufficient buffer space.
2002 	 */
2003 
2004 	if (bp == NULL) {
2005 		int flags, norunbuf;
2006 		char *waitmsg;
2007 		int fl;
2008 
2009 		if (defrag) {
2010 			flags = VFS_BIO_NEED_BUFSPACE;
2011 			waitmsg = "nbufkv";
2012 		} else if (bufspace >= hibufspace) {
2013 			waitmsg = "nbufbs";
2014 			flags = VFS_BIO_NEED_BUFSPACE;
2015 		} else {
2016 			waitmsg = "newbuf";
2017 			flags = VFS_BIO_NEED_ANY;
2018 		}
2019 		mtx_lock(&nblock);
2020 		needsbuffer |= flags;
2021 		mtx_unlock(&nblock);
2022 		mtx_unlock(&bqlock);
2023 
2024 		bd_speedup();	/* heeeelp */
2025 		if (gbflags & GB_NOWAIT_BD)
2026 			return (NULL);
2027 
2028 		mtx_lock(&nblock);
2029 		while (needsbuffer & flags) {
2030 			if (vp != NULL && (td->td_pflags & TDP_BUFNEED) == 0) {
2031 				mtx_unlock(&nblock);
2032 				/*
2033 				 * getblk() is called with a vnode
2034 				 * locked, and some majority of the
2035 				 * dirty buffers may as well belong to
2036 				 * the vnode. Flushing the buffers
2037 				 * there would make a progress that
2038 				 * cannot be achieved by the
2039 				 * buf_daemon, that cannot lock the
2040 				 * vnode.
2041 				 */
2042 				norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
2043 				    (td->td_pflags & TDP_NORUNNINGBUF);
2044 				/* play bufdaemon */
2045 				td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
2046 				fl = buf_do_flush(vp);
2047 				td->td_pflags &= norunbuf;
2048 				mtx_lock(&nblock);
2049 				if (fl != 0)
2050 					continue;
2051 				if ((needsbuffer & flags) == 0)
2052 					break;
2053 			}
2054 			if (msleep(&needsbuffer, &nblock,
2055 			    (PRIBIO + 4) | slpflag, waitmsg, slptimeo)) {
2056 				mtx_unlock(&nblock);
2057 				return (NULL);
2058 			}
2059 		}
2060 		mtx_unlock(&nblock);
2061 	} else {
2062 		/*
2063 		 * We finally have a valid bp.  We aren't quite out of the
2064 		 * woods, we still have to reserve kva space.  In order
2065 		 * to keep fragmentation sane we only allocate kva in
2066 		 * BKVASIZE chunks.
2067 		 */
2068 		maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2069 
2070 		if (maxsize != bp->b_kvasize) {
2071 			vm_offset_t addr = 0;
2072 
2073 			bfreekva(bp);
2074 
2075 			vm_map_lock(buffer_map);
2076 			if (vm_map_findspace(buffer_map,
2077 				vm_map_min(buffer_map), maxsize, &addr)) {
2078 				/*
2079 				 * Uh oh.  Buffer map is to fragmented.  We
2080 				 * must defragment the map.
2081 				 */
2082 				atomic_add_int(&bufdefragcnt, 1);
2083 				vm_map_unlock(buffer_map);
2084 				defrag = 1;
2085 				bp->b_flags |= B_INVAL;
2086 				brelse(bp);
2087 				goto restart;
2088 			}
2089 			if (addr) {
2090 				vm_map_insert(buffer_map, NULL, 0,
2091 					addr, addr + maxsize,
2092 					VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
2093 
2094 				bp->b_kvabase = (caddr_t) addr;
2095 				bp->b_kvasize = maxsize;
2096 				atomic_add_long(&bufspace, bp->b_kvasize);
2097 				atomic_add_int(&bufreusecnt, 1);
2098 			}
2099 			vm_map_unlock(buffer_map);
2100 		}
2101 		bp->b_saveaddr = bp->b_kvabase;
2102 		bp->b_data = bp->b_saveaddr;
2103 	}
2104 	return(bp);
2105 }
2106 
2107 /*
2108  *	buf_daemon:
2109  *
2110  *	buffer flushing daemon.  Buffers are normally flushed by the
2111  *	update daemon but if it cannot keep up this process starts to
2112  *	take the load in an attempt to prevent getnewbuf() from blocking.
2113  */
2114 
2115 static struct kproc_desc buf_kp = {
2116 	"bufdaemon",
2117 	buf_daemon,
2118 	&bufdaemonproc
2119 };
2120 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
2121 
2122 static int
2123 buf_do_flush(struct vnode *vp)
2124 {
2125 	int flushed;
2126 
2127 	flushed = flushbufqueues(vp, QUEUE_DIRTY, 0);
2128 	/* The list empty check here is slightly racy */
2129 	if (!TAILQ_EMPTY(&bufqueues[QUEUE_DIRTY_GIANT])) {
2130 		mtx_lock(&Giant);
2131 		flushed += flushbufqueues(vp, QUEUE_DIRTY_GIANT, 0);
2132 		mtx_unlock(&Giant);
2133 	}
2134 	if (flushed == 0) {
2135 		/*
2136 		 * Could not find any buffers without rollback
2137 		 * dependencies, so just write the first one
2138 		 * in the hopes of eventually making progress.
2139 		 */
2140 		flushbufqueues(vp, QUEUE_DIRTY, 1);
2141 		if (!TAILQ_EMPTY(
2142 			    &bufqueues[QUEUE_DIRTY_GIANT])) {
2143 			mtx_lock(&Giant);
2144 			flushbufqueues(vp, QUEUE_DIRTY_GIANT, 1);
2145 			mtx_unlock(&Giant);
2146 		}
2147 	}
2148 	return (flushed);
2149 }
2150 
2151 static void
2152 buf_daemon()
2153 {
2154 	int lodirtysave;
2155 
2156 	/*
2157 	 * This process needs to be suspended prior to shutdown sync.
2158 	 */
2159 	EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2160 	    SHUTDOWN_PRI_LAST);
2161 
2162 	/*
2163 	 * This process is allowed to take the buffer cache to the limit
2164 	 */
2165 	curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
2166 	mtx_lock(&bdlock);
2167 	for (;;) {
2168 		bd_request = 0;
2169 		mtx_unlock(&bdlock);
2170 
2171 		kproc_suspend_check(bufdaemonproc);
2172 		lodirtysave = lodirtybuffers;
2173 		if (bd_speedupreq) {
2174 			lodirtybuffers = numdirtybuffers / 2;
2175 			bd_speedupreq = 0;
2176 		}
2177 		/*
2178 		 * Do the flush.  Limit the amount of in-transit I/O we
2179 		 * allow to build up, otherwise we would completely saturate
2180 		 * the I/O system.  Wakeup any waiting processes before we
2181 		 * normally would so they can run in parallel with our drain.
2182 		 */
2183 		while (numdirtybuffers > lodirtybuffers) {
2184 			if (buf_do_flush(NULL) == 0)
2185 				break;
2186 			uio_yield();
2187 		}
2188 		lodirtybuffers = lodirtysave;
2189 
2190 		/*
2191 		 * Only clear bd_request if we have reached our low water
2192 		 * mark.  The buf_daemon normally waits 1 second and
2193 		 * then incrementally flushes any dirty buffers that have
2194 		 * built up, within reason.
2195 		 *
2196 		 * If we were unable to hit our low water mark and couldn't
2197 		 * find any flushable buffers, we sleep half a second.
2198 		 * Otherwise we loop immediately.
2199 		 */
2200 		mtx_lock(&bdlock);
2201 		if (numdirtybuffers <= lodirtybuffers) {
2202 			/*
2203 			 * We reached our low water mark, reset the
2204 			 * request and sleep until we are needed again.
2205 			 * The sleep is just so the suspend code works.
2206 			 */
2207 			bd_request = 0;
2208 			msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2209 		} else {
2210 			/*
2211 			 * We couldn't find any flushable dirty buffers but
2212 			 * still have too many dirty buffers, we
2213 			 * have to sleep and try again.  (rare)
2214 			 */
2215 			msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2216 		}
2217 	}
2218 }
2219 
2220 /*
2221  *	flushbufqueues:
2222  *
2223  *	Try to flush a buffer in the dirty queue.  We must be careful to
2224  *	free up B_INVAL buffers instead of write them, which NFS is
2225  *	particularly sensitive to.
2226  */
2227 static int flushwithdeps = 0;
2228 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2229     0, "Number of buffers flushed with dependecies that require rollbacks");
2230 
2231 static int
2232 flushbufqueues(struct vnode *lvp, int queue, int flushdeps)
2233 {
2234 	struct buf *sentinel;
2235 	struct vnode *vp;
2236 	struct mount *mp;
2237 	struct buf *bp;
2238 	int hasdeps;
2239 	int flushed;
2240 	int target;
2241 
2242 	if (lvp == NULL) {
2243 		target = numdirtybuffers - lodirtybuffers;
2244 		if (flushdeps && target > 2)
2245 			target /= 2;
2246 	} else
2247 		target = flushbufqtarget;
2248 	flushed = 0;
2249 	bp = NULL;
2250 	sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
2251 	sentinel->b_qindex = QUEUE_SENTINEL;
2252 	mtx_lock(&bqlock);
2253 	TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
2254 	while (flushed != target) {
2255 		bp = TAILQ_NEXT(sentinel, b_freelist);
2256 		if (bp != NULL) {
2257 			TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2258 			TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
2259 			    b_freelist);
2260 		} else
2261 			break;
2262 		/*
2263 		 * Skip sentinels inserted by other invocations of the
2264 		 * flushbufqueues(), taking care to not reorder them.
2265 		 */
2266 		if (bp->b_qindex == QUEUE_SENTINEL)
2267 			continue;
2268 		/*
2269 		 * Only flush the buffers that belong to the
2270 		 * vnode locked by the curthread.
2271 		 */
2272 		if (lvp != NULL && bp->b_vp != lvp)
2273 			continue;
2274 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2275 			continue;
2276 		if (bp->b_pin_count > 0) {
2277 			BUF_UNLOCK(bp);
2278 			continue;
2279 		}
2280 		BO_LOCK(bp->b_bufobj);
2281 		if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2282 		    (bp->b_flags & B_DELWRI) == 0) {
2283 			BO_UNLOCK(bp->b_bufobj);
2284 			BUF_UNLOCK(bp);
2285 			continue;
2286 		}
2287 		BO_UNLOCK(bp->b_bufobj);
2288 		if (bp->b_flags & B_INVAL) {
2289 			bremfreel(bp);
2290 			mtx_unlock(&bqlock);
2291 			brelse(bp);
2292 			flushed++;
2293 			numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2294 			mtx_lock(&bqlock);
2295 			continue;
2296 		}
2297 
2298 		if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
2299 			if (flushdeps == 0) {
2300 				BUF_UNLOCK(bp);
2301 				continue;
2302 			}
2303 			hasdeps = 1;
2304 		} else
2305 			hasdeps = 0;
2306 		/*
2307 		 * We must hold the lock on a vnode before writing
2308 		 * one of its buffers. Otherwise we may confuse, or
2309 		 * in the case of a snapshot vnode, deadlock the
2310 		 * system.
2311 		 *
2312 		 * The lock order here is the reverse of the normal
2313 		 * of vnode followed by buf lock.  This is ok because
2314 		 * the NOWAIT will prevent deadlock.
2315 		 */
2316 		vp = bp->b_vp;
2317 		if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2318 			BUF_UNLOCK(bp);
2319 			continue;
2320 		}
2321 		if (vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT | LK_CANRECURSE) == 0) {
2322 			mtx_unlock(&bqlock);
2323 			CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2324 			    bp, bp->b_vp, bp->b_flags);
2325 			if (curproc == bufdaemonproc)
2326 				vfs_bio_awrite(bp);
2327 			else {
2328 				bremfree(bp);
2329 				bwrite(bp);
2330 				notbufdflashes++;
2331 			}
2332 			vn_finished_write(mp);
2333 			VOP_UNLOCK(vp, 0);
2334 			flushwithdeps += hasdeps;
2335 			flushed++;
2336 
2337 			/*
2338 			 * Sleeping on runningbufspace while holding
2339 			 * vnode lock leads to deadlock.
2340 			 */
2341 			if (curproc == bufdaemonproc)
2342 				waitrunningbufspace();
2343 			numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2344 			mtx_lock(&bqlock);
2345 			continue;
2346 		}
2347 		vn_finished_write(mp);
2348 		BUF_UNLOCK(bp);
2349 	}
2350 	TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2351 	mtx_unlock(&bqlock);
2352 	free(sentinel, M_TEMP);
2353 	return (flushed);
2354 }
2355 
2356 /*
2357  * Check to see if a block is currently memory resident.
2358  */
2359 struct buf *
2360 incore(struct bufobj *bo, daddr_t blkno)
2361 {
2362 	struct buf *bp;
2363 
2364 	BO_LOCK(bo);
2365 	bp = gbincore(bo, blkno);
2366 	BO_UNLOCK(bo);
2367 	return (bp);
2368 }
2369 
2370 /*
2371  * Returns true if no I/O is needed to access the
2372  * associated VM object.  This is like incore except
2373  * it also hunts around in the VM system for the data.
2374  */
2375 
2376 static int
2377 inmem(struct vnode * vp, daddr_t blkno)
2378 {
2379 	vm_object_t obj;
2380 	vm_offset_t toff, tinc, size;
2381 	vm_page_t m;
2382 	vm_ooffset_t off;
2383 
2384 	ASSERT_VOP_LOCKED(vp, "inmem");
2385 
2386 	if (incore(&vp->v_bufobj, blkno))
2387 		return 1;
2388 	if (vp->v_mount == NULL)
2389 		return 0;
2390 	obj = vp->v_object;
2391 	if (obj == NULL)
2392 		return (0);
2393 
2394 	size = PAGE_SIZE;
2395 	if (size > vp->v_mount->mnt_stat.f_iosize)
2396 		size = vp->v_mount->mnt_stat.f_iosize;
2397 	off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2398 
2399 	VM_OBJECT_LOCK(obj);
2400 	for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2401 		m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2402 		if (!m)
2403 			goto notinmem;
2404 		tinc = size;
2405 		if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2406 			tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2407 		if (vm_page_is_valid(m,
2408 		    (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2409 			goto notinmem;
2410 	}
2411 	VM_OBJECT_UNLOCK(obj);
2412 	return 1;
2413 
2414 notinmem:
2415 	VM_OBJECT_UNLOCK(obj);
2416 	return (0);
2417 }
2418 
2419 /*
2420  * Set the dirty range for a buffer based on the status of the dirty
2421  * bits in the pages comprising the buffer.  The range is limited
2422  * to the size of the buffer.
2423  *
2424  * Tell the VM system that the pages associated with this buffer
2425  * are clean.  This is used for delayed writes where the data is
2426  * going to go to disk eventually without additional VM intevention.
2427  *
2428  * Note that while we only really need to clean through to b_bcount, we
2429  * just go ahead and clean through to b_bufsize.
2430  */
2431 static void
2432 vfs_clean_pages_dirty_buf(struct buf *bp)
2433 {
2434 	vm_ooffset_t foff, noff, eoff;
2435 	vm_page_t m;
2436 	int i;
2437 
2438 	if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
2439 		return;
2440 
2441 	foff = bp->b_offset;
2442 	KASSERT(bp->b_offset != NOOFFSET,
2443 	    ("vfs_clean_pages_dirty_buf: no buffer offset"));
2444 
2445 	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
2446 	vfs_drain_busy_pages(bp);
2447 	vfs_setdirty_locked_object(bp);
2448 	for (i = 0; i < bp->b_npages; i++) {
2449 		noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2450 		eoff = noff;
2451 		if (eoff > bp->b_offset + bp->b_bufsize)
2452 			eoff = bp->b_offset + bp->b_bufsize;
2453 		m = bp->b_pages[i];
2454 		vfs_page_set_validclean(bp, foff, m);
2455 		/* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
2456 		foff = noff;
2457 	}
2458 	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
2459 }
2460 
2461 static void
2462 vfs_setdirty_locked_object(struct buf *bp)
2463 {
2464 	vm_object_t object;
2465 	int i;
2466 
2467 	object = bp->b_bufobj->bo_object;
2468 	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2469 
2470 	/*
2471 	 * We qualify the scan for modified pages on whether the
2472 	 * object has been flushed yet.
2473 	 */
2474 	if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2475 		vm_offset_t boffset;
2476 		vm_offset_t eoffset;
2477 
2478 		/*
2479 		 * test the pages to see if they have been modified directly
2480 		 * by users through the VM system.
2481 		 */
2482 		for (i = 0; i < bp->b_npages; i++)
2483 			vm_page_test_dirty(bp->b_pages[i]);
2484 
2485 		/*
2486 		 * Calculate the encompassing dirty range, boffset and eoffset,
2487 		 * (eoffset - boffset) bytes.
2488 		 */
2489 
2490 		for (i = 0; i < bp->b_npages; i++) {
2491 			if (bp->b_pages[i]->dirty)
2492 				break;
2493 		}
2494 		boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2495 
2496 		for (i = bp->b_npages - 1; i >= 0; --i) {
2497 			if (bp->b_pages[i]->dirty) {
2498 				break;
2499 			}
2500 		}
2501 		eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2502 
2503 		/*
2504 		 * Fit it to the buffer.
2505 		 */
2506 
2507 		if (eoffset > bp->b_bcount)
2508 			eoffset = bp->b_bcount;
2509 
2510 		/*
2511 		 * If we have a good dirty range, merge with the existing
2512 		 * dirty range.
2513 		 */
2514 
2515 		if (boffset < eoffset) {
2516 			if (bp->b_dirtyoff > boffset)
2517 				bp->b_dirtyoff = boffset;
2518 			if (bp->b_dirtyend < eoffset)
2519 				bp->b_dirtyend = eoffset;
2520 		}
2521 	}
2522 }
2523 
2524 /*
2525  *	getblk:
2526  *
2527  *	Get a block given a specified block and offset into a file/device.
2528  *	The buffers B_DONE bit will be cleared on return, making it almost
2529  * 	ready for an I/O initiation.  B_INVAL may or may not be set on
2530  *	return.  The caller should clear B_INVAL prior to initiating a
2531  *	READ.
2532  *
2533  *	For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2534  *	an existing buffer.
2535  *
2536  *	For a VMIO buffer, B_CACHE is modified according to the backing VM.
2537  *	If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2538  *	and then cleared based on the backing VM.  If the previous buffer is
2539  *	non-0-sized but invalid, B_CACHE will be cleared.
2540  *
2541  *	If getblk() must create a new buffer, the new buffer is returned with
2542  *	both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2543  *	case it is returned with B_INVAL clear and B_CACHE set based on the
2544  *	backing VM.
2545  *
2546  *	getblk() also forces a bwrite() for any B_DELWRI buffer whos
2547  *	B_CACHE bit is clear.
2548  *
2549  *	What this means, basically, is that the caller should use B_CACHE to
2550  *	determine whether the buffer is fully valid or not and should clear
2551  *	B_INVAL prior to issuing a read.  If the caller intends to validate
2552  *	the buffer by loading its data area with something, the caller needs
2553  *	to clear B_INVAL.  If the caller does this without issuing an I/O,
2554  *	the caller should set B_CACHE ( as an optimization ), else the caller
2555  *	should issue the I/O and biodone() will set B_CACHE if the I/O was
2556  *	a write attempt or if it was a successfull read.  If the caller
2557  *	intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
2558  *	prior to issuing the READ.  biodone() will *not* clear B_INVAL.
2559  */
2560 struct buf *
2561 getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo,
2562     int flags)
2563 {
2564 	struct buf *bp;
2565 	struct bufobj *bo;
2566 	int error;
2567 
2568 	CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
2569 	ASSERT_VOP_LOCKED(vp, "getblk");
2570 	if (size > MAXBSIZE)
2571 		panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2572 
2573 	bo = &vp->v_bufobj;
2574 loop:
2575 	/*
2576 	 * Block if we are low on buffers.   Certain processes are allowed
2577 	 * to completely exhaust the buffer cache.
2578          *
2579          * If this check ever becomes a bottleneck it may be better to
2580          * move it into the else, when gbincore() fails.  At the moment
2581          * it isn't a problem.
2582 	 *
2583 	 * XXX remove if 0 sections (clean this up after its proven)
2584          */
2585 	if (numfreebuffers == 0) {
2586 		if (TD_IS_IDLETHREAD(curthread))
2587 			return NULL;
2588 		mtx_lock(&nblock);
2589 		needsbuffer |= VFS_BIO_NEED_ANY;
2590 		mtx_unlock(&nblock);
2591 	}
2592 
2593 	BO_LOCK(bo);
2594 	bp = gbincore(bo, blkno);
2595 	if (bp != NULL) {
2596 		int lockflags;
2597 		/*
2598 		 * Buffer is in-core.  If the buffer is not busy, it must
2599 		 * be on a queue.
2600 		 */
2601 		lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
2602 
2603 		if (flags & GB_LOCK_NOWAIT)
2604 			lockflags |= LK_NOWAIT;
2605 
2606 		error = BUF_TIMELOCK(bp, lockflags,
2607 		    BO_MTX(bo), "getblk", slpflag, slptimeo);
2608 
2609 		/*
2610 		 * If we slept and got the lock we have to restart in case
2611 		 * the buffer changed identities.
2612 		 */
2613 		if (error == ENOLCK)
2614 			goto loop;
2615 		/* We timed out or were interrupted. */
2616 		else if (error)
2617 			return (NULL);
2618 
2619 		/*
2620 		 * The buffer is locked.  B_CACHE is cleared if the buffer is
2621 		 * invalid.  Otherwise, for a non-VMIO buffer, B_CACHE is set
2622 		 * and for a VMIO buffer B_CACHE is adjusted according to the
2623 		 * backing VM cache.
2624 		 */
2625 		if (bp->b_flags & B_INVAL)
2626 			bp->b_flags &= ~B_CACHE;
2627 		else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2628 			bp->b_flags |= B_CACHE;
2629 		bremfree(bp);
2630 
2631 		/*
2632 		 * check for size inconsistancies for non-VMIO case.
2633 		 */
2634 
2635 		if (bp->b_bcount != size) {
2636 			if ((bp->b_flags & B_VMIO) == 0 ||
2637 			    (size > bp->b_kvasize)) {
2638 				if (bp->b_flags & B_DELWRI) {
2639 					/*
2640 					 * If buffer is pinned and caller does
2641 					 * not want sleep  waiting for it to be
2642 					 * unpinned, bail out
2643 					 * */
2644 					if (bp->b_pin_count > 0) {
2645 						if (flags & GB_LOCK_NOWAIT) {
2646 							bqrelse(bp);
2647 							return (NULL);
2648 						} else {
2649 							bunpin_wait(bp);
2650 						}
2651 					}
2652 					bp->b_flags |= B_NOCACHE;
2653 					bwrite(bp);
2654 				} else {
2655 					if (LIST_EMPTY(&bp->b_dep)) {
2656 						bp->b_flags |= B_RELBUF;
2657 						brelse(bp);
2658 					} else {
2659 						bp->b_flags |= B_NOCACHE;
2660 						bwrite(bp);
2661 					}
2662 				}
2663 				goto loop;
2664 			}
2665 		}
2666 
2667 		/*
2668 		 * If the size is inconsistant in the VMIO case, we can resize
2669 		 * the buffer.  This might lead to B_CACHE getting set or
2670 		 * cleared.  If the size has not changed, B_CACHE remains
2671 		 * unchanged from its previous state.
2672 		 */
2673 
2674 		if (bp->b_bcount != size)
2675 			allocbuf(bp, size);
2676 
2677 		KASSERT(bp->b_offset != NOOFFSET,
2678 		    ("getblk: no buffer offset"));
2679 
2680 		/*
2681 		 * A buffer with B_DELWRI set and B_CACHE clear must
2682 		 * be committed before we can return the buffer in
2683 		 * order to prevent the caller from issuing a read
2684 		 * ( due to B_CACHE not being set ) and overwriting
2685 		 * it.
2686 		 *
2687 		 * Most callers, including NFS and FFS, need this to
2688 		 * operate properly either because they assume they
2689 		 * can issue a read if B_CACHE is not set, or because
2690 		 * ( for example ) an uncached B_DELWRI might loop due
2691 		 * to softupdates re-dirtying the buffer.  In the latter
2692 		 * case, B_CACHE is set after the first write completes,
2693 		 * preventing further loops.
2694 		 * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
2695 		 * above while extending the buffer, we cannot allow the
2696 		 * buffer to remain with B_CACHE set after the write
2697 		 * completes or it will represent a corrupt state.  To
2698 		 * deal with this we set B_NOCACHE to scrap the buffer
2699 		 * after the write.
2700 		 *
2701 		 * We might be able to do something fancy, like setting
2702 		 * B_CACHE in bwrite() except if B_DELWRI is already set,
2703 		 * so the below call doesn't set B_CACHE, but that gets real
2704 		 * confusing.  This is much easier.
2705 		 */
2706 
2707 		if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2708 			bp->b_flags |= B_NOCACHE;
2709 			bwrite(bp);
2710 			goto loop;
2711 		}
2712 		bp->b_flags &= ~B_DONE;
2713 	} else {
2714 		int bsize, maxsize, vmio;
2715 		off_t offset;
2716 
2717 		/*
2718 		 * Buffer is not in-core, create new buffer.  The buffer
2719 		 * returned by getnewbuf() is locked.  Note that the returned
2720 		 * buffer is also considered valid (not marked B_INVAL).
2721 		 */
2722 		BO_UNLOCK(bo);
2723 		/*
2724 		 * If the user does not want us to create the buffer, bail out
2725 		 * here.
2726 		 */
2727 		if (flags & GB_NOCREAT)
2728 			return NULL;
2729 		bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
2730 		offset = blkno * bsize;
2731 		vmio = vp->v_object != NULL;
2732 		maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2733 		maxsize = imax(maxsize, bsize);
2734 
2735 		bp = getnewbuf(vp, slpflag, slptimeo, size, maxsize, flags);
2736 		if (bp == NULL) {
2737 			if (slpflag || slptimeo)
2738 				return NULL;
2739 			goto loop;
2740 		}
2741 
2742 		/*
2743 		 * This code is used to make sure that a buffer is not
2744 		 * created while the getnewbuf routine is blocked.
2745 		 * This can be a problem whether the vnode is locked or not.
2746 		 * If the buffer is created out from under us, we have to
2747 		 * throw away the one we just created.
2748 		 *
2749 		 * Note: this must occur before we associate the buffer
2750 		 * with the vp especially considering limitations in
2751 		 * the splay tree implementation when dealing with duplicate
2752 		 * lblkno's.
2753 		 */
2754 		BO_LOCK(bo);
2755 		if (gbincore(bo, blkno)) {
2756 			BO_UNLOCK(bo);
2757 			bp->b_flags |= B_INVAL;
2758 			brelse(bp);
2759 			goto loop;
2760 		}
2761 
2762 		/*
2763 		 * Insert the buffer into the hash, so that it can
2764 		 * be found by incore.
2765 		 */
2766 		bp->b_blkno = bp->b_lblkno = blkno;
2767 		bp->b_offset = offset;
2768 		bgetvp(vp, bp);
2769 		BO_UNLOCK(bo);
2770 
2771 		/*
2772 		 * set B_VMIO bit.  allocbuf() the buffer bigger.  Since the
2773 		 * buffer size starts out as 0, B_CACHE will be set by
2774 		 * allocbuf() for the VMIO case prior to it testing the
2775 		 * backing store for validity.
2776 		 */
2777 
2778 		if (vmio) {
2779 			bp->b_flags |= B_VMIO;
2780 #if defined(VFS_BIO_DEBUG)
2781 			if (vn_canvmio(vp) != TRUE)
2782 				printf("getblk: VMIO on vnode type %d\n",
2783 					vp->v_type);
2784 #endif
2785 			KASSERT(vp->v_object == bp->b_bufobj->bo_object,
2786 			    ("ARGH! different b_bufobj->bo_object %p %p %p\n",
2787 			    bp, vp->v_object, bp->b_bufobj->bo_object));
2788 		} else {
2789 			bp->b_flags &= ~B_VMIO;
2790 			KASSERT(bp->b_bufobj->bo_object == NULL,
2791 			    ("ARGH! has b_bufobj->bo_object %p %p\n",
2792 			    bp, bp->b_bufobj->bo_object));
2793 		}
2794 
2795 		allocbuf(bp, size);
2796 		bp->b_flags &= ~B_DONE;
2797 	}
2798 	CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
2799 	BUF_ASSERT_HELD(bp);
2800 	KASSERT(bp->b_bufobj == bo,
2801 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2802 	return (bp);
2803 }
2804 
2805 /*
2806  * Get an empty, disassociated buffer of given size.  The buffer is initially
2807  * set to B_INVAL.
2808  */
2809 struct buf *
2810 geteblk(int size, int flags)
2811 {
2812 	struct buf *bp;
2813 	int maxsize;
2814 
2815 	maxsize = (size + BKVAMASK) & ~BKVAMASK;
2816 	while ((bp = getnewbuf(NULL, 0, 0, size, maxsize, flags)) == NULL) {
2817 		if ((flags & GB_NOWAIT_BD) &&
2818 		    (curthread->td_pflags & TDP_BUFNEED) != 0)
2819 			return (NULL);
2820 	}
2821 	allocbuf(bp, size);
2822 	bp->b_flags |= B_INVAL;	/* b_dep cleared by getnewbuf() */
2823 	BUF_ASSERT_HELD(bp);
2824 	return (bp);
2825 }
2826 
2827 
2828 /*
2829  * This code constitutes the buffer memory from either anonymous system
2830  * memory (in the case of non-VMIO operations) or from an associated
2831  * VM object (in the case of VMIO operations).  This code is able to
2832  * resize a buffer up or down.
2833  *
2834  * Note that this code is tricky, and has many complications to resolve
2835  * deadlock or inconsistant data situations.  Tread lightly!!!
2836  * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2837  * the caller.  Calling this code willy nilly can result in the loss of data.
2838  *
2839  * allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
2840  * B_CACHE for the non-VMIO case.
2841  */
2842 
2843 int
2844 allocbuf(struct buf *bp, int size)
2845 {
2846 	int newbsize, mbsize;
2847 	int i;
2848 
2849 	BUF_ASSERT_HELD(bp);
2850 
2851 	if (bp->b_kvasize < size)
2852 		panic("allocbuf: buffer too small");
2853 
2854 	if ((bp->b_flags & B_VMIO) == 0) {
2855 		caddr_t origbuf;
2856 		int origbufsize;
2857 		/*
2858 		 * Just get anonymous memory from the kernel.  Don't
2859 		 * mess with B_CACHE.
2860 		 */
2861 		mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2862 		if (bp->b_flags & B_MALLOC)
2863 			newbsize = mbsize;
2864 		else
2865 			newbsize = round_page(size);
2866 
2867 		if (newbsize < bp->b_bufsize) {
2868 			/*
2869 			 * malloced buffers are not shrunk
2870 			 */
2871 			if (bp->b_flags & B_MALLOC) {
2872 				if (newbsize) {
2873 					bp->b_bcount = size;
2874 				} else {
2875 					free(bp->b_data, M_BIOBUF);
2876 					if (bp->b_bufsize) {
2877 						atomic_subtract_long(
2878 						    &bufmallocspace,
2879 						    bp->b_bufsize);
2880 						bufspacewakeup();
2881 						bp->b_bufsize = 0;
2882 					}
2883 					bp->b_saveaddr = bp->b_kvabase;
2884 					bp->b_data = bp->b_saveaddr;
2885 					bp->b_bcount = 0;
2886 					bp->b_flags &= ~B_MALLOC;
2887 				}
2888 				return 1;
2889 			}
2890 			vm_hold_free_pages(bp, newbsize);
2891 		} else if (newbsize > bp->b_bufsize) {
2892 			/*
2893 			 * We only use malloced memory on the first allocation.
2894 			 * and revert to page-allocated memory when the buffer
2895 			 * grows.
2896 			 */
2897 			/*
2898 			 * There is a potential smp race here that could lead
2899 			 * to bufmallocspace slightly passing the max.  It
2900 			 * is probably extremely rare and not worth worrying
2901 			 * over.
2902 			 */
2903 			if ( (bufmallocspace < maxbufmallocspace) &&
2904 				(bp->b_bufsize == 0) &&
2905 				(mbsize <= PAGE_SIZE/2)) {
2906 
2907 				bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2908 				bp->b_bufsize = mbsize;
2909 				bp->b_bcount = size;
2910 				bp->b_flags |= B_MALLOC;
2911 				atomic_add_long(&bufmallocspace, mbsize);
2912 				return 1;
2913 			}
2914 			origbuf = NULL;
2915 			origbufsize = 0;
2916 			/*
2917 			 * If the buffer is growing on its other-than-first allocation,
2918 			 * then we revert to the page-allocation scheme.
2919 			 */
2920 			if (bp->b_flags & B_MALLOC) {
2921 				origbuf = bp->b_data;
2922 				origbufsize = bp->b_bufsize;
2923 				bp->b_data = bp->b_kvabase;
2924 				if (bp->b_bufsize) {
2925 					atomic_subtract_long(&bufmallocspace,
2926 					    bp->b_bufsize);
2927 					bufspacewakeup();
2928 					bp->b_bufsize = 0;
2929 				}
2930 				bp->b_flags &= ~B_MALLOC;
2931 				newbsize = round_page(newbsize);
2932 			}
2933 			vm_hold_load_pages(
2934 			    bp,
2935 			    (vm_offset_t) bp->b_data + bp->b_bufsize,
2936 			    (vm_offset_t) bp->b_data + newbsize);
2937 			if (origbuf) {
2938 				bcopy(origbuf, bp->b_data, origbufsize);
2939 				free(origbuf, M_BIOBUF);
2940 			}
2941 		}
2942 	} else {
2943 		int desiredpages;
2944 
2945 		newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2946 		desiredpages = (size == 0) ? 0 :
2947 			num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2948 
2949 		if (bp->b_flags & B_MALLOC)
2950 			panic("allocbuf: VMIO buffer can't be malloced");
2951 		/*
2952 		 * Set B_CACHE initially if buffer is 0 length or will become
2953 		 * 0-length.
2954 		 */
2955 		if (size == 0 || bp->b_bufsize == 0)
2956 			bp->b_flags |= B_CACHE;
2957 
2958 		if (newbsize < bp->b_bufsize) {
2959 			/*
2960 			 * DEV_BSIZE aligned new buffer size is less then the
2961 			 * DEV_BSIZE aligned existing buffer size.  Figure out
2962 			 * if we have to remove any pages.
2963 			 */
2964 			if (desiredpages < bp->b_npages) {
2965 				vm_page_t m;
2966 
2967 				VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
2968 				for (i = desiredpages; i < bp->b_npages; i++) {
2969 					/*
2970 					 * the page is not freed here -- it
2971 					 * is the responsibility of
2972 					 * vnode_pager_setsize
2973 					 */
2974 					m = bp->b_pages[i];
2975 					KASSERT(m != bogus_page,
2976 					    ("allocbuf: bogus page found"));
2977 					while (vm_page_sleep_if_busy(m, TRUE,
2978 					    "biodep"))
2979 						continue;
2980 
2981 					bp->b_pages[i] = NULL;
2982 					vm_page_lock(m);
2983 					vm_page_unwire(m, 0);
2984 					vm_page_unlock(m);
2985 				}
2986 				VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
2987 				pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2988 				    (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
2989 				bp->b_npages = desiredpages;
2990 			}
2991 		} else if (size > bp->b_bcount) {
2992 			/*
2993 			 * We are growing the buffer, possibly in a
2994 			 * byte-granular fashion.
2995 			 */
2996 			vm_object_t obj;
2997 			vm_offset_t toff;
2998 			vm_offset_t tinc;
2999 
3000 			/*
3001 			 * Step 1, bring in the VM pages from the object,
3002 			 * allocating them if necessary.  We must clear
3003 			 * B_CACHE if these pages are not valid for the
3004 			 * range covered by the buffer.
3005 			 */
3006 
3007 			obj = bp->b_bufobj->bo_object;
3008 
3009 			VM_OBJECT_LOCK(obj);
3010 			while (bp->b_npages < desiredpages) {
3011 				vm_page_t m;
3012 
3013 				/*
3014 				 * We must allocate system pages since blocking
3015 				 * here could intefere with paging I/O, no
3016 				 * matter which process we are.
3017 				 *
3018 				 * We can only test VPO_BUSY here.  Blocking on
3019 				 * m->busy might lead to a deadlock:
3020 				 *  vm_fault->getpages->cluster_read->allocbuf
3021 				 * Thus, we specify VM_ALLOC_IGN_SBUSY.
3022 				 */
3023 				m = vm_page_grab(obj, OFF_TO_IDX(bp->b_offset) +
3024 				    bp->b_npages, VM_ALLOC_NOBUSY |
3025 				    VM_ALLOC_SYSTEM | VM_ALLOC_WIRED |
3026 				    VM_ALLOC_RETRY | VM_ALLOC_IGN_SBUSY |
3027 				    VM_ALLOC_COUNT(desiredpages - bp->b_npages));
3028 				if (m->valid == 0)
3029 					bp->b_flags &= ~B_CACHE;
3030 				bp->b_pages[bp->b_npages] = m;
3031 				++bp->b_npages;
3032 			}
3033 
3034 			/*
3035 			 * Step 2.  We've loaded the pages into the buffer,
3036 			 * we have to figure out if we can still have B_CACHE
3037 			 * set.  Note that B_CACHE is set according to the
3038 			 * byte-granular range ( bcount and size ), new the
3039 			 * aligned range ( newbsize ).
3040 			 *
3041 			 * The VM test is against m->valid, which is DEV_BSIZE
3042 			 * aligned.  Needless to say, the validity of the data
3043 			 * needs to also be DEV_BSIZE aligned.  Note that this
3044 			 * fails with NFS if the server or some other client
3045 			 * extends the file's EOF.  If our buffer is resized,
3046 			 * B_CACHE may remain set! XXX
3047 			 */
3048 
3049 			toff = bp->b_bcount;
3050 			tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
3051 
3052 			while ((bp->b_flags & B_CACHE) && toff < size) {
3053 				vm_pindex_t pi;
3054 
3055 				if (tinc > (size - toff))
3056 					tinc = size - toff;
3057 
3058 				pi = ((bp->b_offset & PAGE_MASK) + toff) >>
3059 				    PAGE_SHIFT;
3060 
3061 				vfs_buf_test_cache(
3062 				    bp,
3063 				    bp->b_offset,
3064 				    toff,
3065 				    tinc,
3066 				    bp->b_pages[pi]
3067 				);
3068 				toff += tinc;
3069 				tinc = PAGE_SIZE;
3070 			}
3071 			VM_OBJECT_UNLOCK(obj);
3072 
3073 			/*
3074 			 * Step 3, fixup the KVM pmap.  Remember that
3075 			 * bp->b_data is relative to bp->b_offset, but
3076 			 * bp->b_offset may be offset into the first page.
3077 			 */
3078 
3079 			bp->b_data = (caddr_t)
3080 			    trunc_page((vm_offset_t)bp->b_data);
3081 			pmap_qenter(
3082 			    (vm_offset_t)bp->b_data,
3083 			    bp->b_pages,
3084 			    bp->b_npages
3085 			);
3086 
3087 			bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
3088 			    (vm_offset_t)(bp->b_offset & PAGE_MASK));
3089 		}
3090 	}
3091 	if (newbsize < bp->b_bufsize)
3092 		bufspacewakeup();
3093 	bp->b_bufsize = newbsize;	/* actual buffer allocation	*/
3094 	bp->b_bcount = size;		/* requested buffer size	*/
3095 	return 1;
3096 }
3097 
3098 void
3099 biodone(struct bio *bp)
3100 {
3101 	struct mtx *mtxp;
3102 	void (*done)(struct bio *);
3103 
3104 	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3105 	mtx_lock(mtxp);
3106 	bp->bio_flags |= BIO_DONE;
3107 	done = bp->bio_done;
3108 	if (done == NULL)
3109 		wakeup(bp);
3110 	mtx_unlock(mtxp);
3111 	if (done != NULL)
3112 		done(bp);
3113 }
3114 
3115 /*
3116  * Wait for a BIO to finish.
3117  *
3118  * XXX: resort to a timeout for now.  The optimal locking (if any) for this
3119  * case is not yet clear.
3120  */
3121 int
3122 biowait(struct bio *bp, const char *wchan)
3123 {
3124 	struct mtx *mtxp;
3125 
3126 	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3127 	mtx_lock(mtxp);
3128 	while ((bp->bio_flags & BIO_DONE) == 0)
3129 		msleep(bp, mtxp, PRIBIO, wchan, hz / 10);
3130 	mtx_unlock(mtxp);
3131 	if (bp->bio_error != 0)
3132 		return (bp->bio_error);
3133 	if (!(bp->bio_flags & BIO_ERROR))
3134 		return (0);
3135 	return (EIO);
3136 }
3137 
3138 void
3139 biofinish(struct bio *bp, struct devstat *stat, int error)
3140 {
3141 
3142 	if (error) {
3143 		bp->bio_error = error;
3144 		bp->bio_flags |= BIO_ERROR;
3145 	}
3146 	if (stat != NULL)
3147 		devstat_end_transaction_bio(stat, bp);
3148 	biodone(bp);
3149 }
3150 
3151 /*
3152  *	bufwait:
3153  *
3154  *	Wait for buffer I/O completion, returning error status.  The buffer
3155  *	is left locked and B_DONE on return.  B_EINTR is converted into an EINTR
3156  *	error and cleared.
3157  */
3158 int
3159 bufwait(struct buf *bp)
3160 {
3161 	if (bp->b_iocmd == BIO_READ)
3162 		bwait(bp, PRIBIO, "biord");
3163 	else
3164 		bwait(bp, PRIBIO, "biowr");
3165 	if (bp->b_flags & B_EINTR) {
3166 		bp->b_flags &= ~B_EINTR;
3167 		return (EINTR);
3168 	}
3169 	if (bp->b_ioflags & BIO_ERROR) {
3170 		return (bp->b_error ? bp->b_error : EIO);
3171 	} else {
3172 		return (0);
3173 	}
3174 }
3175 
3176  /*
3177   * Call back function from struct bio back up to struct buf.
3178   */
3179 static void
3180 bufdonebio(struct bio *bip)
3181 {
3182 	struct buf *bp;
3183 
3184 	bp = bip->bio_caller2;
3185 	bp->b_resid = bp->b_bcount - bip->bio_completed;
3186 	bp->b_resid = bip->bio_resid;	/* XXX: remove */
3187 	bp->b_ioflags = bip->bio_flags;
3188 	bp->b_error = bip->bio_error;
3189 	if (bp->b_error)
3190 		bp->b_ioflags |= BIO_ERROR;
3191 	bufdone(bp);
3192 	g_destroy_bio(bip);
3193 }
3194 
3195 void
3196 dev_strategy(struct cdev *dev, struct buf *bp)
3197 {
3198 	struct cdevsw *csw;
3199 	struct bio *bip;
3200 
3201 	if ((!bp->b_iocmd) || (bp->b_iocmd & (bp->b_iocmd - 1)))
3202 		panic("b_iocmd botch");
3203 	for (;;) {
3204 		bip = g_new_bio();
3205 		if (bip != NULL)
3206 			break;
3207 		/* Try again later */
3208 		tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3209 	}
3210 	bip->bio_cmd = bp->b_iocmd;
3211 	bip->bio_offset = bp->b_iooffset;
3212 	bip->bio_length = bp->b_bcount;
3213 	bip->bio_bcount = bp->b_bcount;	/* XXX: remove */
3214 	bip->bio_data = bp->b_data;
3215 	bip->bio_done = bufdonebio;
3216 	bip->bio_caller2 = bp;
3217 	bip->bio_dev = dev;
3218 	KASSERT(dev->si_refcount > 0,
3219 	    ("dev_strategy on un-referenced struct cdev *(%s)",
3220 	    devtoname(dev)));
3221 	csw = dev_refthread(dev);
3222 	if (csw == NULL) {
3223 		g_destroy_bio(bip);
3224 		bp->b_error = ENXIO;
3225 		bp->b_ioflags = BIO_ERROR;
3226 		bufdone(bp);
3227 		return;
3228 	}
3229 	(*csw->d_strategy)(bip);
3230 	dev_relthread(dev);
3231 }
3232 
3233 /*
3234  *	bufdone:
3235  *
3236  *	Finish I/O on a buffer, optionally calling a completion function.
3237  *	This is usually called from an interrupt so process blocking is
3238  *	not allowed.
3239  *
3240  *	biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3241  *	In a non-VMIO bp, B_CACHE will be set on the next getblk()
3242  *	assuming B_INVAL is clear.
3243  *
3244  *	For the VMIO case, we set B_CACHE if the op was a read and no
3245  *	read error occured, or if the op was a write.  B_CACHE is never
3246  *	set if the buffer is invalid or otherwise uncacheable.
3247  *
3248  *	biodone does not mess with B_INVAL, allowing the I/O routine or the
3249  *	initiator to leave B_INVAL set to brelse the buffer out of existance
3250  *	in the biodone routine.
3251  */
3252 void
3253 bufdone(struct buf *bp)
3254 {
3255 	struct bufobj *dropobj;
3256 	void    (*biodone)(struct buf *);
3257 
3258 	CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3259 	dropobj = NULL;
3260 
3261 	KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3262 	BUF_ASSERT_HELD(bp);
3263 
3264 	runningbufwakeup(bp);
3265 	if (bp->b_iocmd == BIO_WRITE)
3266 		dropobj = bp->b_bufobj;
3267 	/* call optional completion function if requested */
3268 	if (bp->b_iodone != NULL) {
3269 		biodone = bp->b_iodone;
3270 		bp->b_iodone = NULL;
3271 		(*biodone) (bp);
3272 		if (dropobj)
3273 			bufobj_wdrop(dropobj);
3274 		return;
3275 	}
3276 
3277 	bufdone_finish(bp);
3278 
3279 	if (dropobj)
3280 		bufobj_wdrop(dropobj);
3281 }
3282 
3283 void
3284 bufdone_finish(struct buf *bp)
3285 {
3286 	BUF_ASSERT_HELD(bp);
3287 
3288 	if (!LIST_EMPTY(&bp->b_dep))
3289 		buf_complete(bp);
3290 
3291 	if (bp->b_flags & B_VMIO) {
3292 		int i;
3293 		vm_ooffset_t foff;
3294 		vm_page_t m;
3295 		vm_object_t obj;
3296 		int bogus, iosize;
3297 		struct vnode *vp = bp->b_vp;
3298 
3299 		obj = bp->b_bufobj->bo_object;
3300 
3301 #if defined(VFS_BIO_DEBUG)
3302 		mp_fixme("usecount and vflag accessed without locks.");
3303 		if (vp->v_usecount == 0) {
3304 			panic("biodone: zero vnode ref count");
3305 		}
3306 
3307 		KASSERT(vp->v_object != NULL,
3308 			("biodone: vnode %p has no vm_object", vp));
3309 #endif
3310 
3311 		foff = bp->b_offset;
3312 		KASSERT(bp->b_offset != NOOFFSET,
3313 		    ("biodone: no buffer offset"));
3314 
3315 		VM_OBJECT_LOCK(obj);
3316 #if defined(VFS_BIO_DEBUG)
3317 		if (obj->paging_in_progress < bp->b_npages) {
3318 			printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
3319 			    obj->paging_in_progress, bp->b_npages);
3320 		}
3321 #endif
3322 
3323 		/*
3324 		 * Set B_CACHE if the op was a normal read and no error
3325 		 * occured.  B_CACHE is set for writes in the b*write()
3326 		 * routines.
3327 		 */
3328 		iosize = bp->b_bcount - bp->b_resid;
3329 		if (bp->b_iocmd == BIO_READ &&
3330 		    !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3331 		    !(bp->b_ioflags & BIO_ERROR)) {
3332 			bp->b_flags |= B_CACHE;
3333 		}
3334 		bogus = 0;
3335 		for (i = 0; i < bp->b_npages; i++) {
3336 			int bogusflag = 0;
3337 			int resid;
3338 
3339 			resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3340 			if (resid > iosize)
3341 				resid = iosize;
3342 
3343 			/*
3344 			 * cleanup bogus pages, restoring the originals
3345 			 */
3346 			m = bp->b_pages[i];
3347 			if (m == bogus_page) {
3348 				bogus = bogusflag = 1;
3349 				m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3350 				if (m == NULL)
3351 					panic("biodone: page disappeared!");
3352 				bp->b_pages[i] = m;
3353 			}
3354 #if defined(VFS_BIO_DEBUG)
3355 			if (OFF_TO_IDX(foff) != m->pindex) {
3356 				printf(
3357 "biodone: foff(%jd)/m->pindex(%ju) mismatch\n",
3358 				    (intmax_t)foff, (uintmax_t)m->pindex);
3359 			}
3360 #endif
3361 
3362 			/*
3363 			 * In the write case, the valid and clean bits are
3364 			 * already changed correctly ( see bdwrite() ), so we
3365 			 * only need to do this here in the read case.
3366 			 */
3367 			if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3368 				KASSERT((m->dirty & vm_page_bits(foff &
3369 				    PAGE_MASK, resid)) == 0, ("bufdone_finish:"
3370 				    " page %p has unexpected dirty bits", m));
3371 				vfs_page_set_valid(bp, foff, m);
3372 			}
3373 
3374 			/*
3375 			 * when debugging new filesystems or buffer I/O methods, this
3376 			 * is the most common error that pops up.  if you see this, you
3377 			 * have not set the page busy flag correctly!!!
3378 			 */
3379 			if (m->busy == 0) {
3380 				printf("biodone: page busy < 0, "
3381 				    "pindex: %d, foff: 0x(%x,%x), "
3382 				    "resid: %d, index: %d\n",
3383 				    (int) m->pindex, (int)(foff >> 32),
3384 						(int) foff & 0xffffffff, resid, i);
3385 				if (!vn_isdisk(vp, NULL))
3386 					printf(" iosize: %jd, lblkno: %jd, flags: 0x%x, npages: %d\n",
3387 					    (intmax_t)bp->b_vp->v_mount->mnt_stat.f_iosize,
3388 					    (intmax_t) bp->b_lblkno,
3389 					    bp->b_flags, bp->b_npages);
3390 				else
3391 					printf(" VDEV, lblkno: %jd, flags: 0x%x, npages: %d\n",
3392 					    (intmax_t) bp->b_lblkno,
3393 					    bp->b_flags, bp->b_npages);
3394 				printf(" valid: 0x%lx, dirty: 0x%lx, wired: %d\n",
3395 				    (u_long)m->valid, (u_long)m->dirty,
3396 				    m->wire_count);
3397 				panic("biodone: page busy < 0\n");
3398 			}
3399 			vm_page_io_finish(m);
3400 			vm_object_pip_subtract(obj, 1);
3401 			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3402 			iosize -= resid;
3403 		}
3404 		vm_object_pip_wakeupn(obj, 0);
3405 		VM_OBJECT_UNLOCK(obj);
3406 		if (bogus)
3407 			pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3408 			    bp->b_pages, bp->b_npages);
3409 	}
3410 
3411 	/*
3412 	 * For asynchronous completions, release the buffer now. The brelse
3413 	 * will do a wakeup there if necessary - so no need to do a wakeup
3414 	 * here in the async case. The sync case always needs to do a wakeup.
3415 	 */
3416 
3417 	if (bp->b_flags & B_ASYNC) {
3418 		if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3419 			brelse(bp);
3420 		else
3421 			bqrelse(bp);
3422 	} else
3423 		bdone(bp);
3424 }
3425 
3426 /*
3427  * This routine is called in lieu of iodone in the case of
3428  * incomplete I/O.  This keeps the busy status for pages
3429  * consistant.
3430  */
3431 void
3432 vfs_unbusy_pages(struct buf *bp)
3433 {
3434 	int i;
3435 	vm_object_t obj;
3436 	vm_page_t m;
3437 
3438 	runningbufwakeup(bp);
3439 	if (!(bp->b_flags & B_VMIO))
3440 		return;
3441 
3442 	obj = bp->b_bufobj->bo_object;
3443 	VM_OBJECT_LOCK(obj);
3444 	for (i = 0; i < bp->b_npages; i++) {
3445 		m = bp->b_pages[i];
3446 		if (m == bogus_page) {
3447 			m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3448 			if (!m)
3449 				panic("vfs_unbusy_pages: page missing\n");
3450 			bp->b_pages[i] = m;
3451 			pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3452 			    bp->b_pages, bp->b_npages);
3453 		}
3454 		vm_object_pip_subtract(obj, 1);
3455 		vm_page_io_finish(m);
3456 	}
3457 	vm_object_pip_wakeupn(obj, 0);
3458 	VM_OBJECT_UNLOCK(obj);
3459 }
3460 
3461 /*
3462  * vfs_page_set_valid:
3463  *
3464  *	Set the valid bits in a page based on the supplied offset.   The
3465  *	range is restricted to the buffer's size.
3466  *
3467  *	This routine is typically called after a read completes.
3468  */
3469 static void
3470 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3471 {
3472 	vm_ooffset_t eoff;
3473 
3474 	/*
3475 	 * Compute the end offset, eoff, such that [off, eoff) does not span a
3476 	 * page boundary and eoff is not greater than the end of the buffer.
3477 	 * The end of the buffer, in this case, is our file EOF, not the
3478 	 * allocation size of the buffer.
3479 	 */
3480 	eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
3481 	if (eoff > bp->b_offset + bp->b_bcount)
3482 		eoff = bp->b_offset + bp->b_bcount;
3483 
3484 	/*
3485 	 * Set valid range.  This is typically the entire buffer and thus the
3486 	 * entire page.
3487 	 */
3488 	if (eoff > off)
3489 		vm_page_set_valid(m, off & PAGE_MASK, eoff - off);
3490 }
3491 
3492 /*
3493  * vfs_page_set_validclean:
3494  *
3495  *	Set the valid bits and clear the dirty bits in a page based on the
3496  *	supplied offset.   The range is restricted to the buffer's size.
3497  */
3498 static void
3499 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3500 {
3501 	vm_ooffset_t soff, eoff;
3502 
3503 	/*
3504 	 * Start and end offsets in buffer.  eoff - soff may not cross a
3505 	 * page boundry or cross the end of the buffer.  The end of the
3506 	 * buffer, in this case, is our file EOF, not the allocation size
3507 	 * of the buffer.
3508 	 */
3509 	soff = off;
3510 	eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3511 	if (eoff > bp->b_offset + bp->b_bcount)
3512 		eoff = bp->b_offset + bp->b_bcount;
3513 
3514 	/*
3515 	 * Set valid range.  This is typically the entire buffer and thus the
3516 	 * entire page.
3517 	 */
3518 	if (eoff > soff) {
3519 		vm_page_set_validclean(
3520 		    m,
3521 		   (vm_offset_t) (soff & PAGE_MASK),
3522 		   (vm_offset_t) (eoff - soff)
3523 		);
3524 	}
3525 }
3526 
3527 /*
3528  * Ensure that all buffer pages are not busied by VPO_BUSY flag. If
3529  * any page is busy, drain the flag.
3530  */
3531 static void
3532 vfs_drain_busy_pages(struct buf *bp)
3533 {
3534 	vm_page_t m;
3535 	int i, last_busied;
3536 
3537 	VM_OBJECT_LOCK_ASSERT(bp->b_bufobj->bo_object, MA_OWNED);
3538 	last_busied = 0;
3539 	for (i = 0; i < bp->b_npages; i++) {
3540 		m = bp->b_pages[i];
3541 		if ((m->oflags & VPO_BUSY) != 0) {
3542 			for (; last_busied < i; last_busied++)
3543 				vm_page_busy(bp->b_pages[last_busied]);
3544 			while ((m->oflags & VPO_BUSY) != 0)
3545 				vm_page_sleep(m, "vbpage");
3546 		}
3547 	}
3548 	for (i = 0; i < last_busied; i++)
3549 		vm_page_wakeup(bp->b_pages[i]);
3550 }
3551 
3552 /*
3553  * This routine is called before a device strategy routine.
3554  * It is used to tell the VM system that paging I/O is in
3555  * progress, and treat the pages associated with the buffer
3556  * almost as being VPO_BUSY.  Also the object paging_in_progress
3557  * flag is handled to make sure that the object doesn't become
3558  * inconsistant.
3559  *
3560  * Since I/O has not been initiated yet, certain buffer flags
3561  * such as BIO_ERROR or B_INVAL may be in an inconsistant state
3562  * and should be ignored.
3563  */
3564 void
3565 vfs_busy_pages(struct buf *bp, int clear_modify)
3566 {
3567 	int i, bogus;
3568 	vm_object_t obj;
3569 	vm_ooffset_t foff;
3570 	vm_page_t m;
3571 
3572 	if (!(bp->b_flags & B_VMIO))
3573 		return;
3574 
3575 	obj = bp->b_bufobj->bo_object;
3576 	foff = bp->b_offset;
3577 	KASSERT(bp->b_offset != NOOFFSET,
3578 	    ("vfs_busy_pages: no buffer offset"));
3579 	VM_OBJECT_LOCK(obj);
3580 	vfs_drain_busy_pages(bp);
3581 	if (bp->b_bufsize != 0)
3582 		vfs_setdirty_locked_object(bp);
3583 	bogus = 0;
3584 	for (i = 0; i < bp->b_npages; i++) {
3585 		m = bp->b_pages[i];
3586 
3587 		if ((bp->b_flags & B_CLUSTER) == 0) {
3588 			vm_object_pip_add(obj, 1);
3589 			vm_page_io_start(m);
3590 		}
3591 		/*
3592 		 * When readying a buffer for a read ( i.e
3593 		 * clear_modify == 0 ), it is important to do
3594 		 * bogus_page replacement for valid pages in
3595 		 * partially instantiated buffers.  Partially
3596 		 * instantiated buffers can, in turn, occur when
3597 		 * reconstituting a buffer from its VM backing store
3598 		 * base.  We only have to do this if B_CACHE is
3599 		 * clear ( which causes the I/O to occur in the
3600 		 * first place ).  The replacement prevents the read
3601 		 * I/O from overwriting potentially dirty VM-backed
3602 		 * pages.  XXX bogus page replacement is, uh, bogus.
3603 		 * It may not work properly with small-block devices.
3604 		 * We need to find a better way.
3605 		 */
3606 		if (clear_modify) {
3607 			pmap_remove_write(m);
3608 			vfs_page_set_validclean(bp, foff, m);
3609 		} else if (m->valid == VM_PAGE_BITS_ALL &&
3610 		    (bp->b_flags & B_CACHE) == 0) {
3611 			bp->b_pages[i] = bogus_page;
3612 			bogus++;
3613 		}
3614 		foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3615 	}
3616 	VM_OBJECT_UNLOCK(obj);
3617 	if (bogus)
3618 		pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3619 		    bp->b_pages, bp->b_npages);
3620 }
3621 
3622 /*
3623  *	vfs_bio_set_valid:
3624  *
3625  *	Set the range within the buffer to valid.  The range is
3626  *	relative to the beginning of the buffer, b_offset.  Note that
3627  *	b_offset itself may be offset from the beginning of the first
3628  *	page.
3629  */
3630 void
3631 vfs_bio_set_valid(struct buf *bp, int base, int size)
3632 {
3633 	int i, n;
3634 	vm_page_t m;
3635 
3636 	if (!(bp->b_flags & B_VMIO))
3637 		return;
3638 
3639 	/*
3640 	 * Fixup base to be relative to beginning of first page.
3641 	 * Set initial n to be the maximum number of bytes in the
3642 	 * first page that can be validated.
3643 	 */
3644 	base += (bp->b_offset & PAGE_MASK);
3645 	n = PAGE_SIZE - (base & PAGE_MASK);
3646 
3647 	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3648 	for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3649 		m = bp->b_pages[i];
3650 		if (n > size)
3651 			n = size;
3652 		vm_page_set_valid(m, base & PAGE_MASK, n);
3653 		base += n;
3654 		size -= n;
3655 		n = PAGE_SIZE;
3656 	}
3657 	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3658 }
3659 
3660 /*
3661  *	vfs_bio_clrbuf:
3662  *
3663  *	If the specified buffer is a non-VMIO buffer, clear the entire
3664  *	buffer.  If the specified buffer is a VMIO buffer, clear and
3665  *	validate only the previously invalid portions of the buffer.
3666  *	This routine essentially fakes an I/O, so we need to clear
3667  *	BIO_ERROR and B_INVAL.
3668  *
3669  *	Note that while we only theoretically need to clear through b_bcount,
3670  *	we go ahead and clear through b_bufsize.
3671  */
3672 void
3673 vfs_bio_clrbuf(struct buf *bp)
3674 {
3675 	int i, j, mask;
3676 	caddr_t sa, ea;
3677 
3678 	if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
3679 		clrbuf(bp);
3680 		return;
3681 	}
3682 	bp->b_flags &= ~B_INVAL;
3683 	bp->b_ioflags &= ~BIO_ERROR;
3684 	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3685 	if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3686 	    (bp->b_offset & PAGE_MASK) == 0) {
3687 		if (bp->b_pages[0] == bogus_page)
3688 			goto unlock;
3689 		mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3690 		VM_OBJECT_LOCK_ASSERT(bp->b_pages[0]->object, MA_OWNED);
3691 		if ((bp->b_pages[0]->valid & mask) == mask)
3692 			goto unlock;
3693 		if ((bp->b_pages[0]->valid & mask) == 0) {
3694 			bzero(bp->b_data, bp->b_bufsize);
3695 			bp->b_pages[0]->valid |= mask;
3696 			goto unlock;
3697 		}
3698 	}
3699 	ea = sa = bp->b_data;
3700 	for(i = 0; i < bp->b_npages; i++, sa = ea) {
3701 		ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3702 		ea = (caddr_t)(vm_offset_t)ulmin(
3703 		    (u_long)(vm_offset_t)ea,
3704 		    (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3705 		if (bp->b_pages[i] == bogus_page)
3706 			continue;
3707 		j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3708 		mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3709 		VM_OBJECT_LOCK_ASSERT(bp->b_pages[i]->object, MA_OWNED);
3710 		if ((bp->b_pages[i]->valid & mask) == mask)
3711 			continue;
3712 		if ((bp->b_pages[i]->valid & mask) == 0)
3713 			bzero(sa, ea - sa);
3714 		else {
3715 			for (; sa < ea; sa += DEV_BSIZE, j++) {
3716 				if ((bp->b_pages[i]->valid & (1 << j)) == 0)
3717 					bzero(sa, DEV_BSIZE);
3718 			}
3719 		}
3720 		bp->b_pages[i]->valid |= mask;
3721 	}
3722 unlock:
3723 	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3724 	bp->b_resid = 0;
3725 }
3726 
3727 /*
3728  * vm_hold_load_pages and vm_hold_free_pages get pages into
3729  * a buffers address space.  The pages are anonymous and are
3730  * not associated with a file object.
3731  */
3732 static void
3733 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3734 {
3735 	vm_offset_t pg;
3736 	vm_page_t p;
3737 	int index;
3738 
3739 	to = round_page(to);
3740 	from = round_page(from);
3741 	index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3742 
3743 	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3744 tryagain:
3745 		/*
3746 		 * note: must allocate system pages since blocking here
3747 		 * could interfere with paging I/O, no matter which
3748 		 * process we are.
3749 		 */
3750 		p = vm_page_alloc(NULL, pg >> PAGE_SHIFT, VM_ALLOC_NOOBJ |
3751 		    VM_ALLOC_SYSTEM | VM_ALLOC_WIRED |
3752 		    VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT));
3753 		if (!p) {
3754 			VM_WAIT;
3755 			goto tryagain;
3756 		}
3757 		pmap_qenter(pg, &p, 1);
3758 		bp->b_pages[index] = p;
3759 	}
3760 	bp->b_npages = index;
3761 }
3762 
3763 /* Return pages associated with this buf to the vm system */
3764 static void
3765 vm_hold_free_pages(struct buf *bp, int newbsize)
3766 {
3767 	vm_offset_t from;
3768 	vm_page_t p;
3769 	int index, newnpages;
3770 
3771 	from = round_page((vm_offset_t)bp->b_data + newbsize);
3772 	newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3773 	if (bp->b_npages > newnpages)
3774 		pmap_qremove(from, bp->b_npages - newnpages);
3775 	for (index = newnpages; index < bp->b_npages; index++) {
3776 		p = bp->b_pages[index];
3777 		bp->b_pages[index] = NULL;
3778 		if (p->busy != 0)
3779 			printf("vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
3780 			    (intmax_t)bp->b_blkno, (intmax_t)bp->b_lblkno);
3781 		p->wire_count--;
3782 		vm_page_free(p);
3783 		atomic_subtract_int(&cnt.v_wire_count, 1);
3784 	}
3785 	bp->b_npages = newnpages;
3786 }
3787 
3788 /*
3789  * Map an IO request into kernel virtual address space.
3790  *
3791  * All requests are (re)mapped into kernel VA space.
3792  * Notice that we use b_bufsize for the size of the buffer
3793  * to be mapped.  b_bcount might be modified by the driver.
3794  *
3795  * Note that even if the caller determines that the address space should
3796  * be valid, a race or a smaller-file mapped into a larger space may
3797  * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
3798  * check the return value.
3799  */
3800 int
3801 vmapbuf(struct buf *bp)
3802 {
3803 	caddr_t addr, kva;
3804 	vm_prot_t prot;
3805 	int pidx, i;
3806 	struct vm_page *m;
3807 	struct pmap *pmap = &curproc->p_vmspace->vm_pmap;
3808 
3809 	if (bp->b_bufsize < 0)
3810 		return (-1);
3811 	prot = VM_PROT_READ;
3812 	if (bp->b_iocmd == BIO_READ)
3813 		prot |= VM_PROT_WRITE;	/* Less backwards than it looks */
3814 	for (addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data), pidx = 0;
3815 	     addr < bp->b_data + bp->b_bufsize;
3816 	     addr += PAGE_SIZE, pidx++) {
3817 		/*
3818 		 * Do the vm_fault if needed; do the copy-on-write thing
3819 		 * when reading stuff off device into memory.
3820 		 *
3821 		 * NOTE! Must use pmap_extract() because addr may be in
3822 		 * the userland address space, and kextract is only guarenteed
3823 		 * to work for the kernland address space (see: sparc64 port).
3824 		 */
3825 retry:
3826 		if (vm_fault_quick(addr >= bp->b_data ? addr : bp->b_data,
3827 		    prot) < 0) {
3828 			for (i = 0; i < pidx; ++i) {
3829 				vm_page_lock(bp->b_pages[i]);
3830 				vm_page_unhold(bp->b_pages[i]);
3831 				vm_page_unlock(bp->b_pages[i]);
3832 				bp->b_pages[i] = NULL;
3833 			}
3834 			return(-1);
3835 		}
3836 		m = pmap_extract_and_hold(pmap, (vm_offset_t)addr, prot);
3837 		if (m == NULL)
3838 			goto retry;
3839 		bp->b_pages[pidx] = m;
3840 	}
3841 	if (pidx > btoc(MAXPHYS))
3842 		panic("vmapbuf: mapped more than MAXPHYS");
3843 	pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
3844 
3845 	kva = bp->b_saveaddr;
3846 	bp->b_npages = pidx;
3847 	bp->b_saveaddr = bp->b_data;
3848 	bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3849 	return(0);
3850 }
3851 
3852 /*
3853  * Free the io map PTEs associated with this IO operation.
3854  * We also invalidate the TLB entries and restore the original b_addr.
3855  */
3856 void
3857 vunmapbuf(struct buf *bp)
3858 {
3859 	int pidx;
3860 	int npages;
3861 
3862 	npages = bp->b_npages;
3863 	pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
3864 	for (pidx = 0; pidx < npages; pidx++) {
3865 		vm_page_lock(bp->b_pages[pidx]);
3866 		vm_page_unhold(bp->b_pages[pidx]);
3867 		vm_page_unlock(bp->b_pages[pidx]);
3868 	}
3869 
3870 	bp->b_data = bp->b_saveaddr;
3871 }
3872 
3873 void
3874 bdone(struct buf *bp)
3875 {
3876 	struct mtx *mtxp;
3877 
3878 	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3879 	mtx_lock(mtxp);
3880 	bp->b_flags |= B_DONE;
3881 	wakeup(bp);
3882 	mtx_unlock(mtxp);
3883 }
3884 
3885 void
3886 bwait(struct buf *bp, u_char pri, const char *wchan)
3887 {
3888 	struct mtx *mtxp;
3889 
3890 	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3891 	mtx_lock(mtxp);
3892 	while ((bp->b_flags & B_DONE) == 0)
3893 		msleep(bp, mtxp, pri, wchan, 0);
3894 	mtx_unlock(mtxp);
3895 }
3896 
3897 int
3898 bufsync(struct bufobj *bo, int waitfor)
3899 {
3900 
3901 	return (VOP_FSYNC(bo->__bo_vnode, waitfor, curthread));
3902 }
3903 
3904 void
3905 bufstrategy(struct bufobj *bo, struct buf *bp)
3906 {
3907 	int i = 0;
3908 	struct vnode *vp;
3909 
3910 	vp = bp->b_vp;
3911 	KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
3912 	KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
3913 	    ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
3914 	i = VOP_STRATEGY(vp, bp);
3915 	KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
3916 }
3917 
3918 void
3919 bufobj_wrefl(struct bufobj *bo)
3920 {
3921 
3922 	KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
3923 	ASSERT_BO_LOCKED(bo);
3924 	bo->bo_numoutput++;
3925 }
3926 
3927 void
3928 bufobj_wref(struct bufobj *bo)
3929 {
3930 
3931 	KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
3932 	BO_LOCK(bo);
3933 	bo->bo_numoutput++;
3934 	BO_UNLOCK(bo);
3935 }
3936 
3937 void
3938 bufobj_wdrop(struct bufobj *bo)
3939 {
3940 
3941 	KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
3942 	BO_LOCK(bo);
3943 	KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
3944 	if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
3945 		bo->bo_flag &= ~BO_WWAIT;
3946 		wakeup(&bo->bo_numoutput);
3947 	}
3948 	BO_UNLOCK(bo);
3949 }
3950 
3951 int
3952 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
3953 {
3954 	int error;
3955 
3956 	KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
3957 	ASSERT_BO_LOCKED(bo);
3958 	error = 0;
3959 	while (bo->bo_numoutput) {
3960 		bo->bo_flag |= BO_WWAIT;
3961 		error = msleep(&bo->bo_numoutput, BO_MTX(bo),
3962 		    slpflag | (PRIBIO + 1), "bo_wwait", timeo);
3963 		if (error)
3964 			break;
3965 	}
3966 	return (error);
3967 }
3968 
3969 void
3970 bpin(struct buf *bp)
3971 {
3972 	struct mtx *mtxp;
3973 
3974 	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3975 	mtx_lock(mtxp);
3976 	bp->b_pin_count++;
3977 	mtx_unlock(mtxp);
3978 }
3979 
3980 void
3981 bunpin(struct buf *bp)
3982 {
3983 	struct mtx *mtxp;
3984 
3985 	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3986 	mtx_lock(mtxp);
3987 	if (--bp->b_pin_count == 0)
3988 		wakeup(bp);
3989 	mtx_unlock(mtxp);
3990 }
3991 
3992 void
3993 bunpin_wait(struct buf *bp)
3994 {
3995 	struct mtx *mtxp;
3996 
3997 	mtxp = mtx_pool_find(mtxpool_sleep, bp);
3998 	mtx_lock(mtxp);
3999 	while (bp->b_pin_count > 0)
4000 		msleep(bp, mtxp, PRIBIO, "bwunpin", 0);
4001 	mtx_unlock(mtxp);
4002 }
4003 
4004 #include "opt_ddb.h"
4005 #ifdef DDB
4006 #include <ddb/ddb.h>
4007 
4008 /* DDB command to show buffer data */
4009 DB_SHOW_COMMAND(buffer, db_show_buffer)
4010 {
4011 	/* get args */
4012 	struct buf *bp = (struct buf *)addr;
4013 
4014 	if (!have_addr) {
4015 		db_printf("usage: show buffer <addr>\n");
4016 		return;
4017 	}
4018 
4019 	db_printf("buf at %p\n", bp);
4020 	db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
4021 	db_printf(
4022 	    "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4023 	    "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_dep = %p\n",
4024 	    bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4025 	    bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4026 	    bp->b_dep.lh_first);
4027 	if (bp->b_npages) {
4028 		int i;
4029 		db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4030 		for (i = 0; i < bp->b_npages; i++) {
4031 			vm_page_t m;
4032 			m = bp->b_pages[i];
4033 			db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4034 			    (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4035 			if ((i + 1) < bp->b_npages)
4036 				db_printf(",");
4037 		}
4038 		db_printf("\n");
4039 	}
4040 	db_printf(" ");
4041 	lockmgr_printinfo(&bp->b_lock);
4042 }
4043 
4044 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
4045 {
4046 	struct buf *bp;
4047 	int i;
4048 
4049 	for (i = 0; i < nbuf; i++) {
4050 		bp = &buf[i];
4051 		if (BUF_ISLOCKED(bp)) {
4052 			db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4053 			db_printf("\n");
4054 		}
4055 	}
4056 }
4057 
4058 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
4059 {
4060 	struct vnode *vp;
4061 	struct buf *bp;
4062 
4063 	if (!have_addr) {
4064 		db_printf("usage: show vnodebufs <addr>\n");
4065 		return;
4066 	}
4067 	vp = (struct vnode *)addr;
4068 	db_printf("Clean buffers:\n");
4069 	TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
4070 		db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4071 		db_printf("\n");
4072 	}
4073 	db_printf("Dirty buffers:\n");
4074 	TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
4075 		db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4076 		db_printf("\n");
4077 	}
4078 }
4079 
4080 DB_COMMAND(countfreebufs, db_coundfreebufs)
4081 {
4082 	struct buf *bp;
4083 	int i, used = 0, nfree = 0;
4084 
4085 	if (have_addr) {
4086 		db_printf("usage: countfreebufs\n");
4087 		return;
4088 	}
4089 
4090 	for (i = 0; i < nbuf; i++) {
4091 		bp = &buf[i];
4092 		if ((bp->b_vflags & BV_INFREECNT) != 0)
4093 			nfree++;
4094 		else
4095 			used++;
4096 	}
4097 
4098 	db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
4099 	    nfree + used);
4100 	db_printf("numfreebuffers is %d\n", numfreebuffers);
4101 }
4102 #endif /* DDB */
4103