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