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