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