vfs_bio.c revision 137168
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 137168 2004-11-03 20:17:31Z alc $");
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				pmap_remove_all(m);
1599				vm_page_free(m);
1600			} else if (bp->b_flags & B_DIRECT) {
1601				vm_page_try_to_free(m);
1602			} else if (vm_page_count_severe()) {
1603				vm_page_try_to_cache(m);
1604			}
1605		}
1606	}
1607	vm_page_unlock_queues();
1608	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
1609	pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
1610
1611	if (bp->b_bufsize) {
1612		bufspacewakeup();
1613		bp->b_bufsize = 0;
1614	}
1615	bp->b_npages = 0;
1616	bp->b_flags &= ~B_VMIO;
1617	if (bp->b_vp)
1618		brelvp(bp);
1619}
1620
1621/*
1622 * Check to see if a block at a particular lbn is available for a clustered
1623 * write.
1624 */
1625static int
1626vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1627{
1628	struct buf *bpa;
1629	int match;
1630
1631	match = 0;
1632
1633	/* If the buf isn't in core skip it */
1634	if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1635		return (0);
1636
1637	/* If the buf is busy we don't want to wait for it */
1638	if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1639		return (0);
1640
1641	/* Only cluster with valid clusterable delayed write buffers */
1642	if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1643	    (B_DELWRI | B_CLUSTEROK))
1644		goto done;
1645
1646	if (bpa->b_bufsize != size)
1647		goto done;
1648
1649	/*
1650	 * Check to see if it is in the expected place on disk and that the
1651	 * block has been mapped.
1652	 */
1653	if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1654		match = 1;
1655done:
1656	BUF_UNLOCK(bpa);
1657	return (match);
1658}
1659
1660/*
1661 *	vfs_bio_awrite:
1662 *
1663 *	Implement clustered async writes for clearing out B_DELWRI buffers.
1664 *	This is much better then the old way of writing only one buffer at
1665 *	a time.  Note that we may not be presented with the buffers in the
1666 *	correct order, so we search for the cluster in both directions.
1667 */
1668int
1669vfs_bio_awrite(struct buf *bp)
1670{
1671	int i;
1672	int j;
1673	daddr_t lblkno = bp->b_lblkno;
1674	struct vnode *vp = bp->b_vp;
1675	int s;
1676	int ncl;
1677	int nwritten;
1678	int size;
1679	int maxcl;
1680
1681	s = splbio();
1682	/*
1683	 * right now we support clustered writing only to regular files.  If
1684	 * we find a clusterable block we could be in the middle of a cluster
1685	 * rather then at the beginning.
1686	 */
1687	if ((vp->v_type == VREG) &&
1688	    (vp->v_mount != 0) && /* Only on nodes that have the size info */
1689	    (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1690
1691		size = vp->v_mount->mnt_stat.f_iosize;
1692		maxcl = MAXPHYS / size;
1693
1694		VI_LOCK(vp);
1695		for (i = 1; i < maxcl; i++)
1696			if (vfs_bio_clcheck(vp, size, lblkno + i,
1697			    bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1698				break;
1699
1700		for (j = 1; i + j <= maxcl && j <= lblkno; j++)
1701			if (vfs_bio_clcheck(vp, size, lblkno - j,
1702			    bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
1703				break;
1704
1705		VI_UNLOCK(vp);
1706		--j;
1707		ncl = i + j;
1708		/*
1709		 * this is a possible cluster write
1710		 */
1711		if (ncl != 1) {
1712			BUF_UNLOCK(bp);
1713			nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1714			splx(s);
1715			return nwritten;
1716		}
1717	}
1718
1719	bremfree(bp);
1720	bp->b_flags |= B_ASYNC;
1721
1722	splx(s);
1723	/*
1724	 * default (old) behavior, writing out only one block
1725	 *
1726	 * XXX returns b_bufsize instead of b_bcount for nwritten?
1727	 */
1728	nwritten = bp->b_bufsize;
1729	(void) bwrite(bp);
1730
1731	return nwritten;
1732}
1733
1734/*
1735 *	getnewbuf:
1736 *
1737 *	Find and initialize a new buffer header, freeing up existing buffers
1738 *	in the bufqueues as necessary.  The new buffer is returned locked.
1739 *
1740 *	Important:  B_INVAL is not set.  If the caller wishes to throw the
1741 *	buffer away, the caller must set B_INVAL prior to calling brelse().
1742 *
1743 *	We block if:
1744 *		We have insufficient buffer headers
1745 *		We have insufficient buffer space
1746 *		buffer_map is too fragmented ( space reservation fails )
1747 *		If we have to flush dirty buffers ( but we try to avoid this )
1748 *
1749 *	To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1750 *	Instead we ask the buf daemon to do it for us.  We attempt to
1751 *	avoid piecemeal wakeups of the pageout daemon.
1752 */
1753
1754static struct buf *
1755getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1756{
1757	struct buf *bp;
1758	struct buf *nbp;
1759	int defrag = 0;
1760	int nqindex;
1761	static int flushingbufs;
1762
1763	GIANT_REQUIRED;
1764
1765	/*
1766	 * We can't afford to block since we might be holding a vnode lock,
1767	 * which may prevent system daemons from running.  We deal with
1768	 * low-memory situations by proactively returning memory and running
1769	 * async I/O rather then sync I/O.
1770	 */
1771
1772	atomic_add_int(&getnewbufcalls, 1);
1773	atomic_subtract_int(&getnewbufrestarts, 1);
1774restart:
1775	atomic_add_int(&getnewbufrestarts, 1);
1776
1777	/*
1778	 * Setup for scan.  If we do not have enough free buffers,
1779	 * we setup a degenerate case that immediately fails.  Note
1780	 * that if we are specially marked process, we are allowed to
1781	 * dip into our reserves.
1782	 *
1783	 * The scanning sequence is nominally:  EMPTY->EMPTYKVA->CLEAN
1784	 *
1785	 * We start with EMPTYKVA.  If the list is empty we backup to EMPTY.
1786	 * However, there are a number of cases (defragging, reusing, ...)
1787	 * where we cannot backup.
1788	 */
1789	mtx_lock(&bqlock);
1790	nqindex = QUEUE_EMPTYKVA;
1791	nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1792
1793	if (nbp == NULL) {
1794		/*
1795		 * If no EMPTYKVA buffers and we are either
1796		 * defragging or reusing, locate a CLEAN buffer
1797		 * to free or reuse.  If bufspace useage is low
1798		 * skip this step so we can allocate a new buffer.
1799		 */
1800		if (defrag || bufspace >= lobufspace) {
1801			nqindex = QUEUE_CLEAN;
1802			nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1803		}
1804
1805		/*
1806		 * If we could not find or were not allowed to reuse a
1807		 * CLEAN buffer, check to see if it is ok to use an EMPTY
1808		 * buffer.  We can only use an EMPTY buffer if allocating
1809		 * its KVA would not otherwise run us out of buffer space.
1810		 */
1811		if (nbp == NULL && defrag == 0 &&
1812		    bufspace + maxsize < hibufspace) {
1813			nqindex = QUEUE_EMPTY;
1814			nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1815		}
1816	}
1817
1818	/*
1819	 * Run scan, possibly freeing data and/or kva mappings on the fly
1820	 * depending.
1821	 */
1822
1823	while ((bp = nbp) != NULL) {
1824		int qindex = nqindex;
1825
1826		/*
1827		 * Calculate next bp ( we can only use it if we do not block
1828		 * or do other fancy things ).
1829		 */
1830		if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1831			switch(qindex) {
1832			case QUEUE_EMPTY:
1833				nqindex = QUEUE_EMPTYKVA;
1834				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1835					break;
1836				/* FALLTHROUGH */
1837			case QUEUE_EMPTYKVA:
1838				nqindex = QUEUE_CLEAN;
1839				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1840					break;
1841				/* FALLTHROUGH */
1842			case QUEUE_CLEAN:
1843				/*
1844				 * nbp is NULL.
1845				 */
1846				break;
1847			}
1848		}
1849		if (bp->b_vp) {
1850			BO_LOCK(bp->b_bufobj);
1851			if (bp->b_vflags & BV_BKGRDINPROG) {
1852				BO_UNLOCK(bp->b_bufobj);
1853				continue;
1854			}
1855			BO_UNLOCK(bp->b_bufobj);
1856		}
1857
1858		/*
1859		 * Sanity Checks
1860		 */
1861		KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1862
1863		/*
1864		 * Note: we no longer distinguish between VMIO and non-VMIO
1865		 * buffers.
1866		 */
1867
1868		KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1869
1870		/*
1871		 * If we are defragging then we need a buffer with
1872		 * b_kvasize != 0.  XXX this situation should no longer
1873		 * occur, if defrag is non-zero the buffer's b_kvasize
1874		 * should also be non-zero at this point.  XXX
1875		 */
1876		if (defrag && bp->b_kvasize == 0) {
1877			printf("Warning: defrag empty buffer %p\n", bp);
1878			continue;
1879		}
1880
1881		/*
1882		 * Start freeing the bp.  This is somewhat involved.  nbp
1883		 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1884		 */
1885
1886		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1887			panic("getnewbuf: locked buf");
1888		bremfreel(bp);
1889		mtx_unlock(&bqlock);
1890
1891		if (qindex == QUEUE_CLEAN) {
1892			if (bp->b_flags & B_VMIO) {
1893				bp->b_flags &= ~B_ASYNC;
1894				vfs_vmio_release(bp);
1895			}
1896			if (bp->b_vp)
1897				brelvp(bp);
1898		}
1899
1900		/*
1901		 * NOTE:  nbp is now entirely invalid.  We can only restart
1902		 * the scan from this point on.
1903		 *
1904		 * Get the rest of the buffer freed up.  b_kva* is still
1905		 * valid after this operation.
1906		 */
1907
1908		if (bp->b_rcred != NOCRED) {
1909			crfree(bp->b_rcred);
1910			bp->b_rcred = NOCRED;
1911		}
1912		if (bp->b_wcred != NOCRED) {
1913			crfree(bp->b_wcred);
1914			bp->b_wcred = NOCRED;
1915		}
1916		if (LIST_FIRST(&bp->b_dep) != NULL)
1917			buf_deallocate(bp);
1918		if (bp->b_vflags & BV_BKGRDINPROG)
1919			panic("losing buffer 3");
1920
1921		if (bp->b_bufsize)
1922			allocbuf(bp, 0);
1923
1924		bp->b_flags = 0;
1925		bp->b_ioflags = 0;
1926		bp->b_xflags = 0;
1927		bp->b_vflags = 0;
1928		bp->b_dev = NULL;
1929		bp->b_vp = NULL;
1930		bp->b_blkno = bp->b_lblkno = 0;
1931		bp->b_offset = NOOFFSET;
1932		bp->b_iodone = 0;
1933		bp->b_error = 0;
1934		bp->b_resid = 0;
1935		bp->b_bcount = 0;
1936		bp->b_npages = 0;
1937		bp->b_dirtyoff = bp->b_dirtyend = 0;
1938		bp->b_magic = B_MAGIC_BIO;
1939		bp->b_bufobj = NULL;
1940
1941		LIST_INIT(&bp->b_dep);
1942
1943		/*
1944		 * If we are defragging then free the buffer.
1945		 */
1946		if (defrag) {
1947			bp->b_flags |= B_INVAL;
1948			bfreekva(bp);
1949			brelse(bp);
1950			defrag = 0;
1951			goto restart;
1952		}
1953
1954		/*
1955		 * If we are overcomitted then recover the buffer and its
1956		 * KVM space.  This occurs in rare situations when multiple
1957		 * processes are blocked in getnewbuf() or allocbuf().
1958		 */
1959		if (bufspace >= hibufspace)
1960			flushingbufs = 1;
1961		if (flushingbufs && bp->b_kvasize != 0) {
1962			bp->b_flags |= B_INVAL;
1963			bfreekva(bp);
1964			brelse(bp);
1965			goto restart;
1966		}
1967		if (bufspace < lobufspace)
1968			flushingbufs = 0;
1969		break;
1970	}
1971
1972	/*
1973	 * If we exhausted our list, sleep as appropriate.  We may have to
1974	 * wakeup various daemons and write out some dirty buffers.
1975	 *
1976	 * Generally we are sleeping due to insufficient buffer space.
1977	 */
1978
1979	if (bp == NULL) {
1980		int flags;
1981		char *waitmsg;
1982
1983		mtx_unlock(&bqlock);
1984		if (defrag) {
1985			flags = VFS_BIO_NEED_BUFSPACE;
1986			waitmsg = "nbufkv";
1987		} else if (bufspace >= hibufspace) {
1988			waitmsg = "nbufbs";
1989			flags = VFS_BIO_NEED_BUFSPACE;
1990		} else {
1991			waitmsg = "newbuf";
1992			flags = VFS_BIO_NEED_ANY;
1993		}
1994
1995		bd_speedup();	/* heeeelp */
1996
1997		mtx_lock(&nblock);
1998		needsbuffer |= flags;
1999		while (needsbuffer & flags) {
2000			if (msleep(&needsbuffer, &nblock,
2001			    (PRIBIO + 4) | slpflag, waitmsg, slptimeo)) {
2002				mtx_unlock(&nblock);
2003				return (NULL);
2004			}
2005		}
2006		mtx_unlock(&nblock);
2007	} else {
2008		/*
2009		 * We finally have a valid bp.  We aren't quite out of the
2010		 * woods, we still have to reserve kva space.  In order
2011		 * to keep fragmentation sane we only allocate kva in
2012		 * BKVASIZE chunks.
2013		 */
2014		maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2015
2016		if (maxsize != bp->b_kvasize) {
2017			vm_offset_t addr = 0;
2018
2019			bfreekva(bp);
2020
2021			if (vm_map_findspace(buffer_map,
2022				vm_map_min(buffer_map), maxsize, &addr)) {
2023				/*
2024				 * Uh oh.  Buffer map is to fragmented.  We
2025				 * must defragment the map.
2026				 */
2027				atomic_add_int(&bufdefragcnt, 1);
2028				defrag = 1;
2029				bp->b_flags |= B_INVAL;
2030				brelse(bp);
2031				goto restart;
2032			}
2033			if (addr) {
2034				vm_map_insert(buffer_map, NULL, 0,
2035					addr, addr + maxsize,
2036					VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
2037
2038				bp->b_kvabase = (caddr_t) addr;
2039				bp->b_kvasize = maxsize;
2040				atomic_add_int(&bufspace, bp->b_kvasize);
2041				atomic_add_int(&bufreusecnt, 1);
2042			}
2043		}
2044		bp->b_saveaddr = bp->b_kvabase;
2045		bp->b_data = bp->b_saveaddr;
2046	}
2047	return(bp);
2048}
2049
2050/*
2051 *	buf_daemon:
2052 *
2053 *	buffer flushing daemon.  Buffers are normally flushed by the
2054 *	update daemon but if it cannot keep up this process starts to
2055 *	take the load in an attempt to prevent getnewbuf() from blocking.
2056 */
2057
2058static struct kproc_desc buf_kp = {
2059	"bufdaemon",
2060	buf_daemon,
2061	&bufdaemonproc
2062};
2063SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
2064
2065static void
2066buf_daemon()
2067{
2068	int s;
2069
2070	mtx_lock(&Giant);
2071
2072	/*
2073	 * This process needs to be suspended prior to shutdown sync.
2074	 */
2075	EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2076	    SHUTDOWN_PRI_LAST);
2077
2078	/*
2079	 * This process is allowed to take the buffer cache to the limit
2080	 */
2081	s = splbio();
2082	mtx_lock(&bdlock);
2083
2084	for (;;) {
2085		bd_request = 0;
2086		mtx_unlock(&bdlock);
2087
2088		kthread_suspend_check(bufdaemonproc);
2089
2090		/*
2091		 * Do the flush.  Limit the amount of in-transit I/O we
2092		 * allow to build up, otherwise we would completely saturate
2093		 * the I/O system.  Wakeup any waiting processes before we
2094		 * normally would so they can run in parallel with our drain.
2095		 */
2096		while (numdirtybuffers > lodirtybuffers) {
2097			if (flushbufqueues(0) == 0) {
2098				/*
2099				 * Could not find any buffers without rollback
2100				 * dependencies, so just write the first one
2101				 * in the hopes of eventually making progress.
2102				 */
2103				flushbufqueues(1);
2104				break;
2105			}
2106			waitrunningbufspace();
2107			numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2108		}
2109
2110		/*
2111		 * Only clear bd_request if we have reached our low water
2112		 * mark.  The buf_daemon normally waits 1 second and
2113		 * then incrementally flushes any dirty buffers that have
2114		 * built up, within reason.
2115		 *
2116		 * If we were unable to hit our low water mark and couldn't
2117		 * find any flushable buffers, we sleep half a second.
2118		 * Otherwise we loop immediately.
2119		 */
2120		mtx_lock(&bdlock);
2121		if (numdirtybuffers <= lodirtybuffers) {
2122			/*
2123			 * We reached our low water mark, reset the
2124			 * request and sleep until we are needed again.
2125			 * The sleep is just so the suspend code works.
2126			 */
2127			bd_request = 0;
2128			msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2129		} else {
2130			/*
2131			 * We couldn't find any flushable dirty buffers but
2132			 * still have too many dirty buffers, we
2133			 * have to sleep and try again.  (rare)
2134			 */
2135			msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2136		}
2137	}
2138}
2139
2140/*
2141 *	flushbufqueues:
2142 *
2143 *	Try to flush a buffer in the dirty queue.  We must be careful to
2144 *	free up B_INVAL buffers instead of write them, which NFS is
2145 *	particularly sensitive to.
2146 */
2147int flushwithdeps = 0;
2148SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2149    0, "Number of buffers flushed with dependecies that require rollbacks");
2150
2151static int
2152flushbufqueues(int flushdeps)
2153{
2154	struct thread *td = curthread;
2155	struct vnode *vp;
2156	struct mount *mp;
2157	struct buf *bp;
2158	int hasdeps;
2159
2160	mtx_lock(&bqlock);
2161	TAILQ_FOREACH(bp, &bufqueues[QUEUE_DIRTY], b_freelist) {
2162		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2163			continue;
2164		KASSERT((bp->b_flags & B_DELWRI),
2165		    ("unexpected clean buffer %p", bp));
2166		BO_LOCK(bp->b_bufobj);
2167		if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
2168			BO_UNLOCK(bp->b_bufobj);
2169			BUF_UNLOCK(bp);
2170			continue;
2171		}
2172		BO_UNLOCK(bp->b_bufobj);
2173		if (bp->b_flags & B_INVAL) {
2174			bremfreel(bp);
2175			mtx_unlock(&bqlock);
2176			brelse(bp);
2177			return (1);
2178		}
2179
2180		if (LIST_FIRST(&bp->b_dep) != NULL && buf_countdeps(bp, 0)) {
2181			if (flushdeps == 0) {
2182				BUF_UNLOCK(bp);
2183				continue;
2184			}
2185			hasdeps = 1;
2186		} else
2187			hasdeps = 0;
2188		/*
2189		 * We must hold the lock on a vnode before writing
2190		 * one of its buffers. Otherwise we may confuse, or
2191		 * in the case of a snapshot vnode, deadlock the
2192		 * system.
2193		 *
2194		 * The lock order here is the reverse of the normal
2195		 * of vnode followed by buf lock.  This is ok because
2196		 * the NOWAIT will prevent deadlock.
2197		 */
2198		vp = bp->b_vp;
2199		if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2200			BUF_UNLOCK(bp);
2201			continue;
2202		}
2203		if (vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT, td) == 0) {
2204			mtx_unlock(&bqlock);
2205			vfs_bio_awrite(bp);
2206			vn_finished_write(mp);
2207			VOP_UNLOCK(vp, 0, td);
2208			flushwithdeps += hasdeps;
2209			return (1);
2210		}
2211		vn_finished_write(mp);
2212		BUF_UNLOCK(bp);
2213	}
2214	mtx_unlock(&bqlock);
2215	return (0);
2216}
2217
2218/*
2219 * Check to see if a block is currently memory resident.
2220 */
2221struct buf *
2222incore(struct bufobj *bo, daddr_t blkno)
2223{
2224	struct buf *bp;
2225
2226	int s = splbio();
2227	BO_LOCK(bo);
2228	bp = gbincore(bo, blkno);
2229	BO_UNLOCK(bo);
2230	splx(s);
2231	return (bp);
2232}
2233
2234/*
2235 * Returns true if no I/O is needed to access the
2236 * associated VM object.  This is like incore except
2237 * it also hunts around in the VM system for the data.
2238 */
2239
2240static int
2241inmem(struct vnode * vp, daddr_t blkno)
2242{
2243	vm_object_t obj;
2244	vm_offset_t toff, tinc, size;
2245	vm_page_t m;
2246	vm_ooffset_t off;
2247
2248	GIANT_REQUIRED;
2249	ASSERT_VOP_LOCKED(vp, "inmem");
2250
2251	if (incore(&vp->v_bufobj, blkno))
2252		return 1;
2253	if (vp->v_mount == NULL)
2254		return 0;
2255	if (VOP_GETVOBJECT(vp, &obj) != 0 || (vp->v_vflag & VV_OBJBUF) == 0)
2256		return 0;
2257
2258	size = PAGE_SIZE;
2259	if (size > vp->v_mount->mnt_stat.f_iosize)
2260		size = vp->v_mount->mnt_stat.f_iosize;
2261	off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2262
2263	VM_OBJECT_LOCK(obj);
2264	for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2265		m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2266		if (!m)
2267			goto notinmem;
2268		tinc = size;
2269		if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2270			tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2271		if (vm_page_is_valid(m,
2272		    (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2273			goto notinmem;
2274	}
2275	VM_OBJECT_UNLOCK(obj);
2276	return 1;
2277
2278notinmem:
2279	VM_OBJECT_UNLOCK(obj);
2280	return (0);
2281}
2282
2283/*
2284 *	vfs_setdirty:
2285 *
2286 *	Sets the dirty range for a buffer based on the status of the dirty
2287 *	bits in the pages comprising the buffer.
2288 *
2289 *	The range is limited to the size of the buffer.
2290 *
2291 *	This routine is primarily used by NFS, but is generalized for the
2292 *	B_VMIO case.
2293 */
2294static void
2295vfs_setdirty(struct buf *bp)
2296{
2297	int i;
2298	vm_object_t object;
2299
2300	GIANT_REQUIRED;
2301	/*
2302	 * Degenerate case - empty buffer
2303	 */
2304
2305	if (bp->b_bufsize == 0)
2306		return;
2307
2308	/*
2309	 * We qualify the scan for modified pages on whether the
2310	 * object has been flushed yet.  The OBJ_WRITEABLE flag
2311	 * is not cleared simply by protecting pages off.
2312	 */
2313
2314	if ((bp->b_flags & B_VMIO) == 0)
2315		return;
2316
2317	object = bp->b_pages[0]->object;
2318	VM_OBJECT_LOCK(object);
2319	if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
2320		printf("Warning: object %p writeable but not mightbedirty\n", object);
2321	if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
2322		printf("Warning: object %p mightbedirty but not writeable\n", object);
2323
2324	if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2325		vm_offset_t boffset;
2326		vm_offset_t eoffset;
2327
2328		vm_page_lock_queues();
2329		/*
2330		 * test the pages to see if they have been modified directly
2331		 * by users through the VM system.
2332		 */
2333		for (i = 0; i < bp->b_npages; i++)
2334			vm_page_test_dirty(bp->b_pages[i]);
2335
2336		/*
2337		 * Calculate the encompassing dirty range, boffset and eoffset,
2338		 * (eoffset - boffset) bytes.
2339		 */
2340
2341		for (i = 0; i < bp->b_npages; i++) {
2342			if (bp->b_pages[i]->dirty)
2343				break;
2344		}
2345		boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2346
2347		for (i = bp->b_npages - 1; i >= 0; --i) {
2348			if (bp->b_pages[i]->dirty) {
2349				break;
2350			}
2351		}
2352		eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2353
2354		vm_page_unlock_queues();
2355		/*
2356		 * Fit it to the buffer.
2357		 */
2358
2359		if (eoffset > bp->b_bcount)
2360			eoffset = bp->b_bcount;
2361
2362		/*
2363		 * If we have a good dirty range, merge with the existing
2364		 * dirty range.
2365		 */
2366
2367		if (boffset < eoffset) {
2368			if (bp->b_dirtyoff > boffset)
2369				bp->b_dirtyoff = boffset;
2370			if (bp->b_dirtyend < eoffset)
2371				bp->b_dirtyend = eoffset;
2372		}
2373	}
2374	VM_OBJECT_UNLOCK(object);
2375}
2376
2377/*
2378 *	getblk:
2379 *
2380 *	Get a block given a specified block and offset into a file/device.
2381 *	The buffers B_DONE bit will be cleared on return, making it almost
2382 * 	ready for an I/O initiation.  B_INVAL may or may not be set on
2383 *	return.  The caller should clear B_INVAL prior to initiating a
2384 *	READ.
2385 *
2386 *	For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2387 *	an existing buffer.
2388 *
2389 *	For a VMIO buffer, B_CACHE is modified according to the backing VM.
2390 *	If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2391 *	and then cleared based on the backing VM.  If the previous buffer is
2392 *	non-0-sized but invalid, B_CACHE will be cleared.
2393 *
2394 *	If getblk() must create a new buffer, the new buffer is returned with
2395 *	both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2396 *	case it is returned with B_INVAL clear and B_CACHE set based on the
2397 *	backing VM.
2398 *
2399 *	getblk() also forces a bwrite() for any B_DELWRI buffer whos
2400 *	B_CACHE bit is clear.
2401 *
2402 *	What this means, basically, is that the caller should use B_CACHE to
2403 *	determine whether the buffer is fully valid or not and should clear
2404 *	B_INVAL prior to issuing a read.  If the caller intends to validate
2405 *	the buffer by loading its data area with something, the caller needs
2406 *	to clear B_INVAL.  If the caller does this without issuing an I/O,
2407 *	the caller should set B_CACHE ( as an optimization ), else the caller
2408 *	should issue the I/O and biodone() will set B_CACHE if the I/O was
2409 *	a write attempt or if it was a successfull read.  If the caller
2410 *	intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
2411 *	prior to issuing the READ.  biodone() will *not* clear B_INVAL.
2412 */
2413struct buf *
2414getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo,
2415    int flags)
2416{
2417	struct buf *bp;
2418	struct bufobj *bo;
2419	int s;
2420	int error;
2421	ASSERT_VOP_LOCKED(vp, "getblk");
2422	struct vm_object *vmo;
2423
2424	if (size > MAXBSIZE)
2425		panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2426
2427	bo = &vp->v_bufobj;
2428	s = splbio();
2429loop:
2430	/*
2431	 * Block if we are low on buffers.   Certain processes are allowed
2432	 * to completely exhaust the buffer cache.
2433         *
2434         * If this check ever becomes a bottleneck it may be better to
2435         * move it into the else, when gbincore() fails.  At the moment
2436         * it isn't a problem.
2437	 *
2438	 * XXX remove if 0 sections (clean this up after its proven)
2439         */
2440	if (numfreebuffers == 0) {
2441		if (curthread == PCPU_GET(idlethread))
2442			return NULL;
2443		mtx_lock(&nblock);
2444		needsbuffer |= VFS_BIO_NEED_ANY;
2445		mtx_unlock(&nblock);
2446	}
2447
2448	VI_LOCK(vp);
2449	bp = gbincore(bo, blkno);
2450	if (bp != NULL) {
2451		int lockflags;
2452		/*
2453		 * Buffer is in-core.  If the buffer is not busy, it must
2454		 * be on a queue.
2455		 */
2456		lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
2457
2458		if (flags & GB_LOCK_NOWAIT)
2459			lockflags |= LK_NOWAIT;
2460
2461		error = BUF_TIMELOCK(bp, lockflags,
2462		    VI_MTX(vp), "getblk", slpflag, slptimeo);
2463
2464		/*
2465		 * If we slept and got the lock we have to restart in case
2466		 * the buffer changed identities.
2467		 */
2468		if (error == ENOLCK)
2469			goto loop;
2470		/* We timed out or were interrupted. */
2471		else if (error)
2472			return (NULL);
2473
2474		/*
2475		 * The buffer is locked.  B_CACHE is cleared if the buffer is
2476		 * invalid.  Otherwise, for a non-VMIO buffer, B_CACHE is set
2477		 * and for a VMIO buffer B_CACHE is adjusted according to the
2478		 * backing VM cache.
2479		 */
2480		if (bp->b_flags & B_INVAL)
2481			bp->b_flags &= ~B_CACHE;
2482		else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2483			bp->b_flags |= B_CACHE;
2484		bremfree(bp);
2485
2486		/*
2487		 * check for size inconsistancies for non-VMIO case.
2488		 */
2489
2490		if (bp->b_bcount != size) {
2491			if ((bp->b_flags & B_VMIO) == 0 ||
2492			    (size > bp->b_kvasize)) {
2493				if (bp->b_flags & B_DELWRI) {
2494					bp->b_flags |= B_NOCACHE;
2495					bwrite(bp);
2496				} else {
2497					if ((bp->b_flags & B_VMIO) &&
2498					   (LIST_FIRST(&bp->b_dep) == NULL)) {
2499						bp->b_flags |= B_RELBUF;
2500						brelse(bp);
2501					} else {
2502						bp->b_flags |= B_NOCACHE;
2503						bwrite(bp);
2504					}
2505				}
2506				goto loop;
2507			}
2508		}
2509
2510		/*
2511		 * If the size is inconsistant in the VMIO case, we can resize
2512		 * the buffer.  This might lead to B_CACHE getting set or
2513		 * cleared.  If the size has not changed, B_CACHE remains
2514		 * unchanged from its previous state.
2515		 */
2516
2517		if (bp->b_bcount != size)
2518			allocbuf(bp, size);
2519
2520		KASSERT(bp->b_offset != NOOFFSET,
2521		    ("getblk: no buffer offset"));
2522
2523		/*
2524		 * A buffer with B_DELWRI set and B_CACHE clear must
2525		 * be committed before we can return the buffer in
2526		 * order to prevent the caller from issuing a read
2527		 * ( due to B_CACHE not being set ) and overwriting
2528		 * it.
2529		 *
2530		 * Most callers, including NFS and FFS, need this to
2531		 * operate properly either because they assume they
2532		 * can issue a read if B_CACHE is not set, or because
2533		 * ( for example ) an uncached B_DELWRI might loop due
2534		 * to softupdates re-dirtying the buffer.  In the latter
2535		 * case, B_CACHE is set after the first write completes,
2536		 * preventing further loops.
2537		 * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
2538		 * above while extending the buffer, we cannot allow the
2539		 * buffer to remain with B_CACHE set after the write
2540		 * completes or it will represent a corrupt state.  To
2541		 * deal with this we set B_NOCACHE to scrap the buffer
2542		 * after the write.
2543		 *
2544		 * We might be able to do something fancy, like setting
2545		 * B_CACHE in bwrite() except if B_DELWRI is already set,
2546		 * so the below call doesn't set B_CACHE, but that gets real
2547		 * confusing.  This is much easier.
2548		 */
2549
2550		if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2551			bp->b_flags |= B_NOCACHE;
2552			bwrite(bp);
2553			goto loop;
2554		}
2555
2556		splx(s);
2557		bp->b_flags &= ~B_DONE;
2558	} else {
2559		int bsize, maxsize, vmio;
2560		off_t offset;
2561
2562		/*
2563		 * Buffer is not in-core, create new buffer.  The buffer
2564		 * returned by getnewbuf() is locked.  Note that the returned
2565		 * buffer is also considered valid (not marked B_INVAL).
2566		 */
2567		VI_UNLOCK(vp);
2568		/*
2569		 * If the user does not want us to create the buffer, bail out
2570		 * here.
2571		 */
2572		if (flags & GB_NOCREAT) {
2573			splx(s);
2574			return NULL;
2575		}
2576
2577		bsize = bo->bo_bsize;
2578		offset = blkno * bsize;
2579		vmio = (VOP_GETVOBJECT(vp, NULL) == 0) &&
2580		    (vp->v_vflag & VV_OBJBUF);
2581		maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2582		maxsize = imax(maxsize, bsize);
2583
2584		bp = getnewbuf(slpflag, slptimeo, size, maxsize);
2585		if (bp == NULL) {
2586			if (slpflag || slptimeo) {
2587				splx(s);
2588				return NULL;
2589			}
2590			goto loop;
2591		}
2592
2593		/*
2594		 * This code is used to make sure that a buffer is not
2595		 * created while the getnewbuf routine is blocked.
2596		 * This can be a problem whether the vnode is locked or not.
2597		 * If the buffer is created out from under us, we have to
2598		 * throw away the one we just created.  There is now window
2599		 * race because we are safely running at splbio() from the
2600		 * point of the duplicate buffer creation through to here,
2601		 * and we've locked the buffer.
2602		 *
2603		 * Note: this must occur before we associate the buffer
2604		 * with the vp especially considering limitations in
2605		 * the splay tree implementation when dealing with duplicate
2606		 * lblkno's.
2607		 */
2608		BO_LOCK(bo);
2609		if (gbincore(bo, blkno)) {
2610			BO_UNLOCK(bo);
2611			bp->b_flags |= B_INVAL;
2612			brelse(bp);
2613			goto loop;
2614		}
2615
2616		/*
2617		 * Insert the buffer into the hash, so that it can
2618		 * be found by incore.
2619		 */
2620		bp->b_blkno = bp->b_lblkno = blkno;
2621		bp->b_offset = offset;
2622
2623		bgetvp(vp, bp);
2624		BO_UNLOCK(bo);
2625
2626		/*
2627		 * set B_VMIO bit.  allocbuf() the buffer bigger.  Since the
2628		 * buffer size starts out as 0, B_CACHE will be set by
2629		 * allocbuf() for the VMIO case prior to it testing the
2630		 * backing store for validity.
2631		 */
2632
2633		if (vmio) {
2634			bp->b_flags |= B_VMIO;
2635#if defined(VFS_BIO_DEBUG)
2636			if (vn_canvmio(vp) != TRUE)
2637				printf("getblk: VMIO on vnode type %d\n",
2638					vp->v_type);
2639#endif
2640			VOP_GETVOBJECT(vp, &vmo);
2641			KASSERT(vmo == bp->b_object,
2642			    ("ARGH! different b_object %p %p %p\n", bp, vmo, bp->b_object));
2643		} else {
2644			bp->b_flags &= ~B_VMIO;
2645			KASSERT(bp->b_object == NULL,
2646			    ("ARGH! has b_object %p %p\n", bp, bp->b_object));
2647		}
2648
2649		allocbuf(bp, size);
2650
2651		splx(s);
2652		bp->b_flags &= ~B_DONE;
2653	}
2654	KASSERT(BUF_REFCNT(bp) == 1, ("getblk: bp %p not locked",bp));
2655	KASSERT(bp->b_bufobj == bo,
2656	    ("wrong b_bufobj %p should be %p", bp->b_bufobj, bo));
2657	return (bp);
2658}
2659
2660/*
2661 * Get an empty, disassociated buffer of given size.  The buffer is initially
2662 * set to B_INVAL.
2663 */
2664struct buf *
2665geteblk(int size)
2666{
2667	struct buf *bp;
2668	int s;
2669	int maxsize;
2670
2671	maxsize = (size + BKVAMASK) & ~BKVAMASK;
2672
2673	s = splbio();
2674	while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2675		continue;
2676	splx(s);
2677	allocbuf(bp, size);
2678	bp->b_flags |= B_INVAL;	/* b_dep cleared by getnewbuf() */
2679	KASSERT(BUF_REFCNT(bp) == 1, ("geteblk: bp %p not locked",bp));
2680	return (bp);
2681}
2682
2683
2684/*
2685 * This code constitutes the buffer memory from either anonymous system
2686 * memory (in the case of non-VMIO operations) or from an associated
2687 * VM object (in the case of VMIO operations).  This code is able to
2688 * resize a buffer up or down.
2689 *
2690 * Note that this code is tricky, and has many complications to resolve
2691 * deadlock or inconsistant data situations.  Tread lightly!!!
2692 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2693 * the caller.  Calling this code willy nilly can result in the loss of data.
2694 *
2695 * allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
2696 * B_CACHE for the non-VMIO case.
2697 */
2698
2699int
2700allocbuf(struct buf *bp, int size)
2701{
2702	int newbsize, mbsize;
2703	int i;
2704
2705	GIANT_REQUIRED;
2706
2707	if (BUF_REFCNT(bp) == 0)
2708		panic("allocbuf: buffer not busy");
2709
2710	if (bp->b_kvasize < size)
2711		panic("allocbuf: buffer too small");
2712
2713	if ((bp->b_flags & B_VMIO) == 0) {
2714		caddr_t origbuf;
2715		int origbufsize;
2716		/*
2717		 * Just get anonymous memory from the kernel.  Don't
2718		 * mess with B_CACHE.
2719		 */
2720		mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2721		if (bp->b_flags & B_MALLOC)
2722			newbsize = mbsize;
2723		else
2724			newbsize = round_page(size);
2725
2726		if (newbsize < bp->b_bufsize) {
2727			/*
2728			 * malloced buffers are not shrunk
2729			 */
2730			if (bp->b_flags & B_MALLOC) {
2731				if (newbsize) {
2732					bp->b_bcount = size;
2733				} else {
2734					free(bp->b_data, M_BIOBUF);
2735					if (bp->b_bufsize) {
2736						atomic_subtract_int(
2737						    &bufmallocspace,
2738						    bp->b_bufsize);
2739						bufspacewakeup();
2740						bp->b_bufsize = 0;
2741					}
2742					bp->b_saveaddr = bp->b_kvabase;
2743					bp->b_data = bp->b_saveaddr;
2744					bp->b_bcount = 0;
2745					bp->b_flags &= ~B_MALLOC;
2746				}
2747				return 1;
2748			}
2749			vm_hold_free_pages(
2750			    bp,
2751			    (vm_offset_t) bp->b_data + newbsize,
2752			    (vm_offset_t) bp->b_data + bp->b_bufsize);
2753		} else if (newbsize > bp->b_bufsize) {
2754			/*
2755			 * We only use malloced memory on the first allocation.
2756			 * and revert to page-allocated memory when the buffer
2757			 * grows.
2758			 */
2759			/*
2760			 * There is a potential smp race here that could lead
2761			 * to bufmallocspace slightly passing the max.  It
2762			 * is probably extremely rare and not worth worrying
2763			 * over.
2764			 */
2765			if ( (bufmallocspace < maxbufmallocspace) &&
2766				(bp->b_bufsize == 0) &&
2767				(mbsize <= PAGE_SIZE/2)) {
2768
2769				bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2770				bp->b_bufsize = mbsize;
2771				bp->b_bcount = size;
2772				bp->b_flags |= B_MALLOC;
2773				atomic_add_int(&bufmallocspace, mbsize);
2774				return 1;
2775			}
2776			origbuf = NULL;
2777			origbufsize = 0;
2778			/*
2779			 * If the buffer is growing on its other-than-first allocation,
2780			 * then we revert to the page-allocation scheme.
2781			 */
2782			if (bp->b_flags & B_MALLOC) {
2783				origbuf = bp->b_data;
2784				origbufsize = bp->b_bufsize;
2785				bp->b_data = bp->b_kvabase;
2786				if (bp->b_bufsize) {
2787					atomic_subtract_int(&bufmallocspace,
2788					    bp->b_bufsize);
2789					bufspacewakeup();
2790					bp->b_bufsize = 0;
2791				}
2792				bp->b_flags &= ~B_MALLOC;
2793				newbsize = round_page(newbsize);
2794			}
2795			vm_hold_load_pages(
2796			    bp,
2797			    (vm_offset_t) bp->b_data + bp->b_bufsize,
2798			    (vm_offset_t) bp->b_data + newbsize);
2799			if (origbuf) {
2800				bcopy(origbuf, bp->b_data, origbufsize);
2801				free(origbuf, M_BIOBUF);
2802			}
2803		}
2804	} else {
2805		int desiredpages;
2806
2807		newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2808		desiredpages = (size == 0) ? 0 :
2809			num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2810
2811		if (bp->b_flags & B_MALLOC)
2812			panic("allocbuf: VMIO buffer can't be malloced");
2813		/*
2814		 * Set B_CACHE initially if buffer is 0 length or will become
2815		 * 0-length.
2816		 */
2817		if (size == 0 || bp->b_bufsize == 0)
2818			bp->b_flags |= B_CACHE;
2819
2820		if (newbsize < bp->b_bufsize) {
2821			/*
2822			 * DEV_BSIZE aligned new buffer size is less then the
2823			 * DEV_BSIZE aligned existing buffer size.  Figure out
2824			 * if we have to remove any pages.
2825			 */
2826			if (desiredpages < bp->b_npages) {
2827				vm_page_t m;
2828
2829				VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
2830				vm_page_lock_queues();
2831				for (i = desiredpages; i < bp->b_npages; i++) {
2832					/*
2833					 * the page is not freed here -- it
2834					 * is the responsibility of
2835					 * vnode_pager_setsize
2836					 */
2837					m = bp->b_pages[i];
2838					KASSERT(m != bogus_page,
2839					    ("allocbuf: bogus page found"));
2840					while (vm_page_sleep_if_busy(m, TRUE, "biodep"))
2841						vm_page_lock_queues();
2842
2843					bp->b_pages[i] = NULL;
2844					vm_page_unwire(m, 0);
2845				}
2846				vm_page_unlock_queues();
2847				VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
2848				pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2849				    (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
2850				bp->b_npages = desiredpages;
2851			}
2852		} else if (size > bp->b_bcount) {
2853			/*
2854			 * We are growing the buffer, possibly in a
2855			 * byte-granular fashion.
2856			 */
2857			struct vnode *vp;
2858			vm_object_t obj;
2859			vm_offset_t toff;
2860			vm_offset_t tinc;
2861
2862			/*
2863			 * Step 1, bring in the VM pages from the object,
2864			 * allocating them if necessary.  We must clear
2865			 * B_CACHE if these pages are not valid for the
2866			 * range covered by the buffer.
2867			 */
2868
2869			vp = bp->b_vp;
2870			obj = bp->b_object;
2871
2872			VM_OBJECT_LOCK(obj);
2873			while (bp->b_npages < desiredpages) {
2874				vm_page_t m;
2875				vm_pindex_t pi;
2876
2877				pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
2878				if ((m = vm_page_lookup(obj, pi)) == NULL) {
2879					/*
2880					 * note: must allocate system pages
2881					 * since blocking here could intefere
2882					 * with paging I/O, no matter which
2883					 * process we are.
2884					 */
2885					m = vm_page_alloc(obj, pi,
2886					    VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM |
2887					    VM_ALLOC_WIRED);
2888					if (m == NULL) {
2889						atomic_add_int(&vm_pageout_deficit,
2890						    desiredpages - bp->b_npages);
2891						VM_OBJECT_UNLOCK(obj);
2892						VM_WAIT;
2893						VM_OBJECT_LOCK(obj);
2894					} else {
2895						bp->b_flags &= ~B_CACHE;
2896						bp->b_pages[bp->b_npages] = m;
2897						++bp->b_npages;
2898					}
2899					continue;
2900				}
2901
2902				/*
2903				 * We found a page.  If we have to sleep on it,
2904				 * retry because it might have gotten freed out
2905				 * from under us.
2906				 *
2907				 * We can only test PG_BUSY here.  Blocking on
2908				 * m->busy might lead to a deadlock:
2909				 *
2910				 *  vm_fault->getpages->cluster_read->allocbuf
2911				 *
2912				 */
2913				vm_page_lock_queues();
2914				if (vm_page_sleep_if_busy(m, FALSE, "pgtblk"))
2915					continue;
2916
2917				/*
2918				 * We have a good page.  Should we wakeup the
2919				 * page daemon?
2920				 */
2921				if ((curproc != pageproc) &&
2922				    ((m->queue - m->pc) == PQ_CACHE) &&
2923				    ((cnt.v_free_count + cnt.v_cache_count) <
2924					(cnt.v_free_min + cnt.v_cache_min))) {
2925					pagedaemon_wakeup();
2926				}
2927				vm_page_wire(m);
2928				vm_page_unlock_queues();
2929				bp->b_pages[bp->b_npages] = m;
2930				++bp->b_npages;
2931			}
2932
2933			/*
2934			 * Step 2.  We've loaded the pages into the buffer,
2935			 * we have to figure out if we can still have B_CACHE
2936			 * set.  Note that B_CACHE is set according to the
2937			 * byte-granular range ( bcount and size ), new the
2938			 * aligned range ( newbsize ).
2939			 *
2940			 * The VM test is against m->valid, which is DEV_BSIZE
2941			 * aligned.  Needless to say, the validity of the data
2942			 * needs to also be DEV_BSIZE aligned.  Note that this
2943			 * fails with NFS if the server or some other client
2944			 * extends the file's EOF.  If our buffer is resized,
2945			 * B_CACHE may remain set! XXX
2946			 */
2947
2948			toff = bp->b_bcount;
2949			tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2950
2951			while ((bp->b_flags & B_CACHE) && toff < size) {
2952				vm_pindex_t pi;
2953
2954				if (tinc > (size - toff))
2955					tinc = size - toff;
2956
2957				pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2958				    PAGE_SHIFT;
2959
2960				vfs_buf_test_cache(
2961				    bp,
2962				    bp->b_offset,
2963				    toff,
2964				    tinc,
2965				    bp->b_pages[pi]
2966				);
2967				toff += tinc;
2968				tinc = PAGE_SIZE;
2969			}
2970			VM_OBJECT_UNLOCK(obj);
2971
2972			/*
2973			 * Step 3, fixup the KVM pmap.  Remember that
2974			 * bp->b_data is relative to bp->b_offset, but
2975			 * bp->b_offset may be offset into the first page.
2976			 */
2977
2978			bp->b_data = (caddr_t)
2979			    trunc_page((vm_offset_t)bp->b_data);
2980			pmap_qenter(
2981			    (vm_offset_t)bp->b_data,
2982			    bp->b_pages,
2983			    bp->b_npages
2984			);
2985
2986			bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2987			    (vm_offset_t)(bp->b_offset & PAGE_MASK));
2988		}
2989	}
2990	if (newbsize < bp->b_bufsize)
2991		bufspacewakeup();
2992	bp->b_bufsize = newbsize;	/* actual buffer allocation	*/
2993	bp->b_bcount = size;		/* requested buffer size	*/
2994	return 1;
2995}
2996
2997void
2998biodone(struct bio *bp)
2999{
3000
3001	mtx_lock(&bdonelock);
3002	bp->bio_flags |= BIO_DONE;
3003	if (bp->bio_done == NULL)
3004		wakeup(bp);
3005	mtx_unlock(&bdonelock);
3006	if (bp->bio_done != NULL)
3007		bp->bio_done(bp);
3008}
3009
3010/*
3011 * Wait for a BIO to finish.
3012 *
3013 * XXX: resort to a timeout for now.  The optimal locking (if any) for this
3014 * case is not yet clear.
3015 */
3016int
3017biowait(struct bio *bp, const char *wchan)
3018{
3019
3020	mtx_lock(&bdonelock);
3021	while ((bp->bio_flags & BIO_DONE) == 0)
3022		msleep(bp, &bdonelock, PRIBIO, wchan, hz / 10);
3023	mtx_unlock(&bdonelock);
3024	if (bp->bio_error != 0)
3025		return (bp->bio_error);
3026	if (!(bp->bio_flags & BIO_ERROR))
3027		return (0);
3028	return (EIO);
3029}
3030
3031void
3032biofinish(struct bio *bp, struct devstat *stat, int error)
3033{
3034
3035	if (error) {
3036		bp->bio_error = error;
3037		bp->bio_flags |= BIO_ERROR;
3038	}
3039	if (stat != NULL)
3040		devstat_end_transaction_bio(stat, bp);
3041	biodone(bp);
3042}
3043
3044/*
3045 *	bufwait:
3046 *
3047 *	Wait for buffer I/O completion, returning error status.  The buffer
3048 *	is left locked and B_DONE on return.  B_EINTR is converted into an EINTR
3049 *	error and cleared.
3050 */
3051int
3052bufwait(struct buf *bp)
3053{
3054	int s;
3055
3056	s = splbio();
3057	if (bp->b_iocmd == BIO_READ)
3058		bwait(bp, PRIBIO, "biord");
3059	else
3060		bwait(bp, PRIBIO, "biowr");
3061	splx(s);
3062	if (bp->b_flags & B_EINTR) {
3063		bp->b_flags &= ~B_EINTR;
3064		return (EINTR);
3065	}
3066	if (bp->b_ioflags & BIO_ERROR) {
3067		return (bp->b_error ? bp->b_error : EIO);
3068	} else {
3069		return (0);
3070	}
3071}
3072
3073 /*
3074  * Call back function from struct bio back up to struct buf.
3075  */
3076static void
3077bufdonebio(struct bio *bip)
3078{
3079	struct buf *bp;
3080
3081	/* Device drivers may or may not hold giant, hold it here. */
3082	mtx_lock(&Giant);
3083	bp = bip->bio_caller2;
3084	bp->b_resid = bp->b_bcount - bip->bio_completed;
3085	bp->b_resid = bip->bio_resid;	/* XXX: remove */
3086	bp->b_ioflags = bip->bio_flags;
3087	bp->b_error = bip->bio_error;
3088	if (bp->b_error)
3089		bp->b_ioflags |= BIO_ERROR;
3090	bufdone(bp);
3091	mtx_unlock(&Giant);
3092	g_destroy_bio(bip);
3093}
3094
3095void
3096dev_strategy(struct cdev *dev, struct buf *bp)
3097{
3098	struct cdevsw *csw;
3099	struct bio *bip;
3100
3101	if ((!bp->b_iocmd) || (bp->b_iocmd & (bp->b_iocmd - 1)))
3102		panic("b_iocmd botch");
3103	for (;;) {
3104		bip = g_new_bio();
3105		if (bip != NULL)
3106			break;
3107		/* Try again later */
3108		tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3109	}
3110	bip->bio_cmd = bp->b_iocmd;
3111	bip->bio_offset = bp->b_iooffset;
3112	bip->bio_length = bp->b_bcount;
3113	bip->bio_bcount = bp->b_bcount;	/* XXX: remove */
3114	bip->bio_data = bp->b_data;
3115	bip->bio_done = bufdonebio;
3116	bip->bio_caller2 = bp;
3117	bip->bio_dev = dev;
3118
3119	KASSERT(dev->si_refcount > 0,
3120	    ("dev_strategy on un-referenced struct cdev *(%s)",
3121	    devtoname(dev)));
3122	csw = dev_refthread(dev);
3123	if (csw == NULL) {
3124		bp->b_error = ENXIO;
3125		bp->b_ioflags = BIO_ERROR;
3126		mtx_lock(&Giant);	/* XXX: too defensive ? */
3127		bufdone(bp);
3128		mtx_unlock(&Giant);	/* XXX: too defensive ? */
3129		return;
3130	}
3131	(*csw->d_strategy)(bip);
3132	dev_relthread(dev);
3133}
3134
3135/*
3136 *	bufdone:
3137 *
3138 *	Finish I/O on a buffer, optionally calling a completion function.
3139 *	This is usually called from an interrupt so process blocking is
3140 *	not allowed.
3141 *
3142 *	biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3143 *	In a non-VMIO bp, B_CACHE will be set on the next getblk()
3144 *	assuming B_INVAL is clear.
3145 *
3146 *	For the VMIO case, we set B_CACHE if the op was a read and no
3147 *	read error occured, or if the op was a write.  B_CACHE is never
3148 *	set if the buffer is invalid or otherwise uncacheable.
3149 *
3150 *	biodone does not mess with B_INVAL, allowing the I/O routine or the
3151 *	initiator to leave B_INVAL set to brelse the buffer out of existance
3152 *	in the biodone routine.
3153 */
3154void
3155bufdone(struct buf *bp)
3156{
3157	int s;
3158	void    (*biodone)(struct buf *);
3159
3160
3161	s = splbio();
3162
3163	KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp, BUF_REFCNT(bp)));
3164	KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3165
3166	bp->b_flags |= B_DONE;
3167	runningbufwakeup(bp);
3168
3169	if (bp->b_iocmd == BIO_WRITE && bp->b_bufobj != NULL)
3170		bufobj_wdrop(bp->b_bufobj);
3171
3172	/* call optional completion function if requested */
3173	if (bp->b_iodone != NULL) {
3174		biodone = bp->b_iodone;
3175		bp->b_iodone = NULL;
3176		(*biodone) (bp);
3177		splx(s);
3178		return;
3179	}
3180	if (LIST_FIRST(&bp->b_dep) != NULL)
3181		buf_complete(bp);
3182
3183	if (bp->b_flags & B_VMIO) {
3184		int i;
3185		vm_ooffset_t foff;
3186		vm_page_t m;
3187		vm_object_t obj;
3188		int iosize;
3189		struct vnode *vp = bp->b_vp;
3190
3191		obj = bp->b_object;
3192
3193#if defined(VFS_BIO_DEBUG)
3194		mp_fixme("usecount and vflag accessed without locks.");
3195		if (vp->v_usecount == 0) {
3196			panic("biodone: zero vnode ref count");
3197		}
3198
3199		if ((vp->v_vflag & VV_OBJBUF) == 0) {
3200			panic("biodone: vnode is not setup for merged cache");
3201		}
3202#endif
3203
3204		foff = bp->b_offset;
3205		KASSERT(bp->b_offset != NOOFFSET,
3206		    ("biodone: no buffer offset"));
3207
3208		VM_OBJECT_LOCK(obj);
3209#if defined(VFS_BIO_DEBUG)
3210		if (obj->paging_in_progress < bp->b_npages) {
3211			printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
3212			    obj->paging_in_progress, bp->b_npages);
3213		}
3214#endif
3215
3216		/*
3217		 * Set B_CACHE if the op was a normal read and no error
3218		 * occured.  B_CACHE is set for writes in the b*write()
3219		 * routines.
3220		 */
3221		iosize = bp->b_bcount - bp->b_resid;
3222		if (bp->b_iocmd == BIO_READ &&
3223		    !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3224		    !(bp->b_ioflags & BIO_ERROR)) {
3225			bp->b_flags |= B_CACHE;
3226		}
3227		vm_page_lock_queues();
3228		for (i = 0; i < bp->b_npages; i++) {
3229			int bogusflag = 0;
3230			int resid;
3231
3232			resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3233			if (resid > iosize)
3234				resid = iosize;
3235
3236			/*
3237			 * cleanup bogus pages, restoring the originals
3238			 */
3239			m = bp->b_pages[i];
3240			if (m == bogus_page) {
3241				bogusflag = 1;
3242				m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3243				if (m == NULL)
3244					panic("biodone: page disappeared!");
3245				bp->b_pages[i] = m;
3246				pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
3247			}
3248#if defined(VFS_BIO_DEBUG)
3249			if (OFF_TO_IDX(foff) != m->pindex) {
3250				printf(
3251"biodone: foff(%jd)/m->pindex(%ju) mismatch\n",
3252				    (intmax_t)foff, (uintmax_t)m->pindex);
3253			}
3254#endif
3255
3256			/*
3257			 * In the write case, the valid and clean bits are
3258			 * already changed correctly ( see bdwrite() ), so we
3259			 * only need to do this here in the read case.
3260			 */
3261			if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3262				vfs_page_set_valid(bp, foff, i, m);
3263			}
3264
3265			/*
3266			 * when debugging new filesystems or buffer I/O methods, this
3267			 * is the most common error that pops up.  if you see this, you
3268			 * have not set the page busy flag correctly!!!
3269			 */
3270			if (m->busy == 0) {
3271				printf("biodone: page busy < 0, "
3272				    "pindex: %d, foff: 0x(%x,%x), "
3273				    "resid: %d, index: %d\n",
3274				    (int) m->pindex, (int)(foff >> 32),
3275						(int) foff & 0xffffffff, resid, i);
3276				if (!vn_isdisk(vp, NULL))
3277					printf(" iosize: %jd, lblkno: %jd, flags: 0x%x, npages: %d\n",
3278					    (intmax_t)bp->b_vp->v_mount->mnt_stat.f_iosize,
3279					    (intmax_t) bp->b_lblkno,
3280					    bp->b_flags, bp->b_npages);
3281				else
3282					printf(" VDEV, lblkno: %jd, flags: 0x%x, npages: %d\n",
3283					    (intmax_t) bp->b_lblkno,
3284					    bp->b_flags, bp->b_npages);
3285				printf(" valid: 0x%lx, dirty: 0x%lx, wired: %d\n",
3286				    (u_long)m->valid, (u_long)m->dirty,
3287				    m->wire_count);
3288				panic("biodone: page busy < 0\n");
3289			}
3290			vm_page_io_finish(m);
3291			vm_object_pip_subtract(obj, 1);
3292			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3293			iosize -= resid;
3294		}
3295		vm_page_unlock_queues();
3296		vm_object_pip_wakeupn(obj, 0);
3297		VM_OBJECT_UNLOCK(obj);
3298	}
3299
3300	/*
3301	 * For asynchronous completions, release the buffer now. The brelse
3302	 * will do a wakeup there if necessary - so no need to do a wakeup
3303	 * here in the async case. The sync case always needs to do a wakeup.
3304	 */
3305
3306	if (bp->b_flags & B_ASYNC) {
3307		if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3308			brelse(bp);
3309		else
3310			bqrelse(bp);
3311	} else {
3312		bdone(bp);
3313	}
3314	splx(s);
3315}
3316
3317/*
3318 * This routine is called in lieu of iodone in the case of
3319 * incomplete I/O.  This keeps the busy status for pages
3320 * consistant.
3321 */
3322void
3323vfs_unbusy_pages(struct buf *bp)
3324{
3325	int i;
3326	vm_object_t obj;
3327	vm_page_t m;
3328
3329	runningbufwakeup(bp);
3330	if (!(bp->b_flags & B_VMIO))
3331		return;
3332
3333	obj = bp->b_object;
3334	VM_OBJECT_LOCK(obj);
3335	vm_page_lock_queues();
3336	for (i = 0; i < bp->b_npages; i++) {
3337		m = bp->b_pages[i];
3338		if (m == bogus_page) {
3339			m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3340			if (!m)
3341				panic("vfs_unbusy_pages: page missing\n");
3342			bp->b_pages[i] = m;
3343			pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3344			    bp->b_pages, bp->b_npages);
3345		}
3346		vm_object_pip_subtract(obj, 1);
3347		vm_page_io_finish(m);
3348	}
3349	vm_page_unlock_queues();
3350	vm_object_pip_wakeupn(obj, 0);
3351	VM_OBJECT_UNLOCK(obj);
3352}
3353
3354/*
3355 * vfs_page_set_valid:
3356 *
3357 *	Set the valid bits in a page based on the supplied offset.   The
3358 *	range is restricted to the buffer's size.
3359 *
3360 *	This routine is typically called after a read completes.
3361 */
3362static void
3363vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3364{
3365	vm_ooffset_t soff, eoff;
3366
3367	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
3368	/*
3369	 * Start and end offsets in buffer.  eoff - soff may not cross a
3370	 * page boundry or cross the end of the buffer.  The end of the
3371	 * buffer, in this case, is our file EOF, not the allocation size
3372	 * of the buffer.
3373	 */
3374	soff = off;
3375	eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3376	if (eoff > bp->b_offset + bp->b_bcount)
3377		eoff = bp->b_offset + bp->b_bcount;
3378
3379	/*
3380	 * Set valid range.  This is typically the entire buffer and thus the
3381	 * entire page.
3382	 */
3383	if (eoff > soff) {
3384		vm_page_set_validclean(
3385		    m,
3386		   (vm_offset_t) (soff & PAGE_MASK),
3387		   (vm_offset_t) (eoff - soff)
3388		);
3389	}
3390}
3391
3392/*
3393 * This routine is called before a device strategy routine.
3394 * It is used to tell the VM system that paging I/O is in
3395 * progress, and treat the pages associated with the buffer
3396 * almost as being PG_BUSY.  Also the object paging_in_progress
3397 * flag is handled to make sure that the object doesn't become
3398 * inconsistant.
3399 *
3400 * Since I/O has not been initiated yet, certain buffer flags
3401 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
3402 * and should be ignored.
3403 */
3404void
3405vfs_busy_pages(struct buf *bp, int clear_modify)
3406{
3407	int i, bogus;
3408	vm_object_t obj;
3409	vm_ooffset_t foff;
3410	vm_page_t m;
3411
3412	if (!(bp->b_flags & B_VMIO))
3413		return;
3414
3415	obj = bp->b_object;
3416	foff = bp->b_offset;
3417	KASSERT(bp->b_offset != NOOFFSET,
3418	    ("vfs_busy_pages: no buffer offset"));
3419	vfs_setdirty(bp);
3420	VM_OBJECT_LOCK(obj);
3421retry:
3422	vm_page_lock_queues();
3423	for (i = 0; i < bp->b_npages; i++) {
3424		m = bp->b_pages[i];
3425
3426		if (vm_page_sleep_if_busy(m, FALSE, "vbpage"))
3427			goto retry;
3428	}
3429	bogus = 0;
3430	for (i = 0; i < bp->b_npages; i++) {
3431		m = bp->b_pages[i];
3432
3433		if ((bp->b_flags & B_CLUSTER) == 0) {
3434			vm_object_pip_add(obj, 1);
3435			vm_page_io_start(m);
3436		}
3437		/*
3438		 * When readying a buffer for a read ( i.e
3439		 * clear_modify == 0 ), it is important to do
3440		 * bogus_page replacement for valid pages in
3441		 * partially instantiated buffers.  Partially
3442		 * instantiated buffers can, in turn, occur when
3443		 * reconstituting a buffer from its VM backing store
3444		 * base.  We only have to do this if B_CACHE is
3445		 * clear ( which causes the I/O to occur in the
3446		 * first place ).  The replacement prevents the read
3447		 * I/O from overwriting potentially dirty VM-backed
3448		 * pages.  XXX bogus page replacement is, uh, bogus.
3449		 * It may not work properly with small-block devices.
3450		 * We need to find a better way.
3451		 */
3452		pmap_remove_all(m);
3453		if (clear_modify)
3454			vfs_page_set_valid(bp, foff, i, m);
3455		else if (m->valid == VM_PAGE_BITS_ALL &&
3456			(bp->b_flags & B_CACHE) == 0) {
3457			bp->b_pages[i] = bogus_page;
3458			bogus++;
3459		}
3460		foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3461	}
3462	vm_page_unlock_queues();
3463	VM_OBJECT_UNLOCK(obj);
3464	if (bogus)
3465		pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3466		    bp->b_pages, bp->b_npages);
3467}
3468
3469/*
3470 * Tell the VM system that the pages associated with this buffer
3471 * are clean.  This is used for delayed writes where the data is
3472 * going to go to disk eventually without additional VM intevention.
3473 *
3474 * Note that while we only really need to clean through to b_bcount, we
3475 * just go ahead and clean through to b_bufsize.
3476 */
3477static void
3478vfs_clean_pages(struct buf *bp)
3479{
3480	int i;
3481	vm_ooffset_t foff, noff, eoff;
3482	vm_page_t m;
3483
3484	if (!(bp->b_flags & B_VMIO))
3485		return;
3486
3487	foff = bp->b_offset;
3488	KASSERT(bp->b_offset != NOOFFSET,
3489	    ("vfs_clean_pages: no buffer offset"));
3490	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3491	vm_page_lock_queues();
3492	for (i = 0; i < bp->b_npages; i++) {
3493		m = bp->b_pages[i];
3494		noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3495		eoff = noff;
3496
3497		if (eoff > bp->b_offset + bp->b_bufsize)
3498			eoff = bp->b_offset + bp->b_bufsize;
3499		vfs_page_set_valid(bp, foff, i, m);
3500		/* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3501		foff = noff;
3502	}
3503	vm_page_unlock_queues();
3504	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3505}
3506
3507/*
3508 *	vfs_bio_set_validclean:
3509 *
3510 *	Set the range within the buffer to valid and clean.  The range is
3511 *	relative to the beginning of the buffer, b_offset.  Note that b_offset
3512 *	itself may be offset from the beginning of the first page.
3513 *
3514 */
3515
3516void
3517vfs_bio_set_validclean(struct buf *bp, int base, int size)
3518{
3519	int i, n;
3520	vm_page_t m;
3521
3522	if (!(bp->b_flags & B_VMIO))
3523		return;
3524
3525	/*
3526	 * Fixup base to be relative to beginning of first page.
3527	 * Set initial n to be the maximum number of bytes in the
3528	 * first page that can be validated.
3529	 */
3530
3531	base += (bp->b_offset & PAGE_MASK);
3532	n = PAGE_SIZE - (base & PAGE_MASK);
3533
3534	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3535	vm_page_lock_queues();
3536	for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3537		m = bp->b_pages[i];
3538
3539		if (n > size)
3540			n = size;
3541
3542		vm_page_set_validclean(m, base & PAGE_MASK, n);
3543		base += n;
3544		size -= n;
3545		n = PAGE_SIZE;
3546	}
3547	vm_page_unlock_queues();
3548	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3549}
3550
3551/*
3552 *	vfs_bio_clrbuf:
3553 *
3554 *	clear a buffer.  This routine essentially fakes an I/O, so we need
3555 *	to clear BIO_ERROR and B_INVAL.
3556 *
3557 *	Note that while we only theoretically need to clear through b_bcount,
3558 *	we go ahead and clear through b_bufsize.
3559 */
3560
3561void
3562vfs_bio_clrbuf(struct buf *bp)
3563{
3564	int i, j, mask = 0;
3565	caddr_t sa, ea;
3566
3567	GIANT_REQUIRED;
3568
3569	if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
3570		clrbuf(bp);
3571		return;
3572	}
3573	bp->b_flags &= ~B_INVAL;
3574	bp->b_ioflags &= ~BIO_ERROR;
3575	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3576	if( (bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3577	    (bp->b_offset & PAGE_MASK) == 0) {
3578		if (bp->b_pages[0] == bogus_page)
3579			goto unlock;
3580		mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3581		VM_OBJECT_LOCK_ASSERT(bp->b_pages[0]->object, MA_OWNED);
3582		if ((bp->b_pages[0]->valid & mask) == mask)
3583			goto unlock;
3584		if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
3585		    ((bp->b_pages[0]->valid & mask) == 0)) {
3586			bzero(bp->b_data, bp->b_bufsize);
3587			bp->b_pages[0]->valid |= mask;
3588			goto unlock;
3589		}
3590	}
3591	ea = sa = bp->b_data;
3592	for(i = 0; i < bp->b_npages; i++, sa = ea) {
3593		ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3594		ea = (caddr_t)(vm_offset_t)ulmin(
3595		    (u_long)(vm_offset_t)ea,
3596		    (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3597		if (bp->b_pages[i] == bogus_page)
3598			continue;
3599		j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3600		mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3601		VM_OBJECT_LOCK_ASSERT(bp->b_pages[i]->object, MA_OWNED);
3602		if ((bp->b_pages[i]->valid & mask) == mask)
3603			continue;
3604		if ((bp->b_pages[i]->valid & mask) == 0) {
3605			if ((bp->b_pages[i]->flags & PG_ZERO) == 0)
3606				bzero(sa, ea - sa);
3607		} else {
3608			for (; sa < ea; sa += DEV_BSIZE, j++) {
3609				if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
3610					(bp->b_pages[i]->valid & (1<<j)) == 0)
3611					bzero(sa, DEV_BSIZE);
3612			}
3613		}
3614		bp->b_pages[i]->valid |= mask;
3615	}
3616unlock:
3617	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3618	bp->b_resid = 0;
3619}
3620
3621/*
3622 * vm_hold_load_pages and vm_hold_free_pages get pages into
3623 * a buffers address space.  The pages are anonymous and are
3624 * not associated with a file object.
3625 */
3626static void
3627vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3628{
3629	vm_offset_t pg;
3630	vm_page_t p;
3631	int index;
3632
3633	to = round_page(to);
3634	from = round_page(from);
3635	index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3636
3637	VM_OBJECT_LOCK(kernel_object);
3638	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3639tryagain:
3640		/*
3641		 * note: must allocate system pages since blocking here
3642		 * could intefere with paging I/O, no matter which
3643		 * process we are.
3644		 */
3645		p = vm_page_alloc(kernel_object,
3646			((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3647		    VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
3648		if (!p) {
3649			atomic_add_int(&vm_pageout_deficit,
3650			    (to - pg) >> PAGE_SHIFT);
3651			VM_OBJECT_UNLOCK(kernel_object);
3652			VM_WAIT;
3653			VM_OBJECT_LOCK(kernel_object);
3654			goto tryagain;
3655		}
3656		p->valid = VM_PAGE_BITS_ALL;
3657		pmap_qenter(pg, &p, 1);
3658		bp->b_pages[index] = p;
3659	}
3660	VM_OBJECT_UNLOCK(kernel_object);
3661	bp->b_npages = index;
3662}
3663
3664/* Return pages associated with this buf to the vm system */
3665static void
3666vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3667{
3668	vm_offset_t pg;
3669	vm_page_t p;
3670	int index, newnpages;
3671
3672	from = round_page(from);
3673	to = round_page(to);
3674	newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3675
3676	VM_OBJECT_LOCK(kernel_object);
3677	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3678		p = bp->b_pages[index];
3679		if (p && (index < bp->b_npages)) {
3680			if (p->busy) {
3681				printf(
3682			    "vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
3683				    (intmax_t)bp->b_blkno,
3684				    (intmax_t)bp->b_lblkno);
3685			}
3686			bp->b_pages[index] = NULL;
3687			pmap_qremove(pg, 1);
3688			vm_page_lock_queues();
3689			vm_page_unwire(p, 0);
3690			vm_page_free(p);
3691			vm_page_unlock_queues();
3692		}
3693	}
3694	VM_OBJECT_UNLOCK(kernel_object);
3695	bp->b_npages = newnpages;
3696}
3697
3698/*
3699 * Map an IO request into kernel virtual address space.
3700 *
3701 * All requests are (re)mapped into kernel VA space.
3702 * Notice that we use b_bufsize for the size of the buffer
3703 * to be mapped.  b_bcount might be modified by the driver.
3704 *
3705 * Note that even if the caller determines that the address space should
3706 * be valid, a race or a smaller-file mapped into a larger space may
3707 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
3708 * check the return value.
3709 */
3710int
3711vmapbuf(struct buf *bp)
3712{
3713	caddr_t addr, kva;
3714	vm_prot_t prot;
3715	int pidx, i;
3716	struct vm_page *m;
3717	struct pmap *pmap = &curproc->p_vmspace->vm_pmap;
3718
3719	if (bp->b_bufsize < 0)
3720		return (-1);
3721	prot = VM_PROT_READ;
3722	if (bp->b_iocmd == BIO_READ)
3723		prot |= VM_PROT_WRITE;	/* Less backwards than it looks */
3724	for (addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data), pidx = 0;
3725	     addr < bp->b_data + bp->b_bufsize;
3726	     addr += PAGE_SIZE, pidx++) {
3727		/*
3728		 * Do the vm_fault if needed; do the copy-on-write thing
3729		 * when reading stuff off device into memory.
3730		 *
3731		 * NOTE! Must use pmap_extract() because addr may be in
3732		 * the userland address space, and kextract is only guarenteed
3733		 * to work for the kernland address space (see: sparc64 port).
3734		 */
3735retry:
3736		if (vm_fault_quick(addr >= bp->b_data ? addr : bp->b_data,
3737		    prot) < 0) {
3738			vm_page_lock_queues();
3739			for (i = 0; i < pidx; ++i) {
3740				vm_page_unhold(bp->b_pages[i]);
3741				bp->b_pages[i] = NULL;
3742			}
3743			vm_page_unlock_queues();
3744			return(-1);
3745		}
3746		m = pmap_extract_and_hold(pmap, (vm_offset_t)addr, prot);
3747		if (m == NULL)
3748			goto retry;
3749		bp->b_pages[pidx] = m;
3750	}
3751	if (pidx > btoc(MAXPHYS))
3752		panic("vmapbuf: mapped more than MAXPHYS");
3753	pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
3754
3755	kva = bp->b_saveaddr;
3756	bp->b_npages = pidx;
3757	bp->b_saveaddr = bp->b_data;
3758	bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3759	return(0);
3760}
3761
3762/*
3763 * Free the io map PTEs associated with this IO operation.
3764 * We also invalidate the TLB entries and restore the original b_addr.
3765 */
3766void
3767vunmapbuf(struct buf *bp)
3768{
3769	int pidx;
3770	int npages;
3771
3772	npages = bp->b_npages;
3773	pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
3774	vm_page_lock_queues();
3775	for (pidx = 0; pidx < npages; pidx++)
3776		vm_page_unhold(bp->b_pages[pidx]);
3777	vm_page_unlock_queues();
3778
3779	bp->b_data = bp->b_saveaddr;
3780}
3781
3782void
3783bdone(struct buf *bp)
3784{
3785
3786	mtx_lock(&bdonelock);
3787	bp->b_flags |= B_DONE;
3788	wakeup(bp);
3789	mtx_unlock(&bdonelock);
3790}
3791
3792void
3793bwait(struct buf *bp, u_char pri, const char *wchan)
3794{
3795
3796	mtx_lock(&bdonelock);
3797	while ((bp->b_flags & B_DONE) == 0)
3798		msleep(bp, &bdonelock, pri, wchan, 0);
3799	mtx_unlock(&bdonelock);
3800}
3801
3802void
3803bufstrategy(struct bufobj *bo, struct buf *bp)
3804{
3805	int i = 0;
3806	struct vnode *vp;
3807
3808	vp = bp->b_vp;
3809	KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
3810	KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
3811	    ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
3812	i = VOP_STRATEGY(vp, bp);
3813	KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
3814}
3815
3816void
3817bufobj_wref(struct bufobj *bo)
3818{
3819
3820	KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
3821	BO_LOCK(bo);
3822	bo->bo_numoutput++;
3823	BO_UNLOCK(bo);
3824}
3825
3826void
3827bufobj_wdrop(struct bufobj *bo)
3828{
3829
3830	KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
3831	BO_LOCK(bo);
3832	KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
3833	if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
3834		bo->bo_flag &= ~BO_WWAIT;
3835		wakeup(&bo->bo_numoutput);
3836	}
3837	BO_UNLOCK(bo);
3838}
3839
3840int
3841bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
3842{
3843	int error;
3844
3845	KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
3846	ASSERT_BO_LOCKED(bo);
3847	error = 0;
3848	while (bo->bo_numoutput) {
3849		bo->bo_flag |= BO_WWAIT;
3850		error = msleep(&bo->bo_numoutput, BO_MTX(bo),
3851		    slpflag | (PRIBIO + 1), "bo_wwait", timeo);
3852		if (error)
3853			break;
3854	}
3855	return (error);
3856}
3857
3858#include "opt_ddb.h"
3859#ifdef DDB
3860#include <ddb/ddb.h>
3861
3862/* DDB command to show buffer data */
3863DB_SHOW_COMMAND(buffer, db_show_buffer)
3864{
3865	/* get args */
3866	struct buf *bp = (struct buf *)addr;
3867
3868	if (!have_addr) {
3869		db_printf("usage: show buffer <addr>\n");
3870		return;
3871	}
3872
3873	db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3874	db_printf(
3875	    "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
3876	    "b_dev = (%d,%d), b_data = %p, b_blkno = %jd\n",
3877	    bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3878	    major(bp->b_dev), minor(bp->b_dev), bp->b_data,
3879	    (intmax_t)bp->b_blkno);
3880	if (bp->b_npages) {
3881		int i;
3882		db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
3883		for (i = 0; i < bp->b_npages; i++) {
3884			vm_page_t m;
3885			m = bp->b_pages[i];
3886			db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3887			    (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3888			if ((i + 1) < bp->b_npages)
3889				db_printf(",");
3890		}
3891		db_printf("\n");
3892	}
3893}
3894#endif /* DDB */
3895