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