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