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