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