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