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