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