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