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