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