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