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