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