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