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