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