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