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