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