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