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