vfs_bio.c revision 120769
1/*
2 * Copyright (c) 1994,1997 John S. Dyson
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice immediately at the beginning of the file, without modification,
10 *    this list of conditions, and the following disclaimer.
11 * 2. Absolutely no warranty of function or purpose is made by the author
12 *		John S. Dyson.
13 */
14
15/*
16 * this file contains a new buffer I/O scheme implementing a coherent
17 * VM object and buffer cache scheme.  Pains have been taken to make
18 * sure that the performance degradation associated with schemes such
19 * as this is not realized.
20 *
21 * Author:  John S. Dyson
22 * Significant help during the development and debugging phases
23 * had been provided by David Greenman, also of the FreeBSD core team.
24 *
25 * see man buf(9) for more info.
26 */
27
28#include <sys/cdefs.h>
29__FBSDID("$FreeBSD: head/sys/kern/vfs_bio.c 120769 2003-10-04 22:47:20Z alc $");
30
31#include <sys/param.h>
32#include <sys/systm.h>
33#include <sys/bio.h>
34#include <sys/buf.h>
35#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 buf *bp;
2139	int hasdeps;
2140
2141	mtx_lock(&bqlock);
2142	TAILQ_FOREACH(bp, &bufqueues[QUEUE_DIRTY], b_freelist) {
2143		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2144			continue;
2145		KASSERT((bp->b_flags & B_DELWRI),
2146		    ("unexpected clean buffer %p", bp));
2147		VI_LOCK(bp->b_vp);
2148		if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
2149			VI_UNLOCK(bp->b_vp);
2150			BUF_UNLOCK(bp);
2151			continue;
2152		}
2153		VI_UNLOCK(bp->b_vp);
2154		if (bp->b_flags & B_INVAL) {
2155			bremfreel(bp);
2156			mtx_unlock(&bqlock);
2157			brelse(bp);
2158			return (1);
2159		}
2160
2161		if (LIST_FIRST(&bp->b_dep) != NULL && buf_countdeps(bp, 0)) {
2162			if (flushdeps == 0) {
2163				BUF_UNLOCK(bp);
2164				continue;
2165			}
2166			hasdeps = 1;
2167		} else
2168			hasdeps = 0;
2169		/*
2170		 * We must hold the lock on a vnode before writing
2171		 * one of its buffers. Otherwise we may confuse, or
2172		 * in the case of a snapshot vnode, deadlock the
2173		 * system.
2174		 *
2175		 * The lock order here is the reverse of the normal
2176		 * of vnode followed by buf lock.  This is ok because
2177		 * the NOWAIT will prevent deadlock.
2178		 */
2179		if ((vp = bp->b_vp) == NULL ||
2180		    vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT, td) == 0) {
2181			mtx_unlock(&bqlock);
2182			vfs_bio_awrite(bp);
2183			if (vp != NULL)
2184				VOP_UNLOCK(vp, 0, td);
2185			flushwithdeps += hasdeps;
2186			return (1);
2187		}
2188		BUF_UNLOCK(bp);
2189	}
2190	mtx_unlock(&bqlock);
2191	return (0);
2192}
2193
2194/*
2195 * Check to see if a block is currently memory resident.
2196 */
2197struct buf *
2198incore(struct vnode * vp, daddr_t blkno)
2199{
2200	struct buf *bp;
2201
2202	int s = splbio();
2203	VI_LOCK(vp);
2204	bp = gbincore(vp, blkno);
2205	VI_UNLOCK(vp);
2206	splx(s);
2207	return (bp);
2208}
2209
2210/*
2211 * Returns true if no I/O is needed to access the
2212 * associated VM object.  This is like incore except
2213 * it also hunts around in the VM system for the data.
2214 */
2215
2216int
2217inmem(struct vnode * vp, daddr_t blkno)
2218{
2219	vm_object_t obj;
2220	vm_offset_t toff, tinc, size;
2221	vm_page_t m;
2222	vm_ooffset_t off;
2223
2224	GIANT_REQUIRED;
2225	ASSERT_VOP_LOCKED(vp, "inmem");
2226
2227	if (incore(vp, blkno))
2228		return 1;
2229	if (vp->v_mount == NULL)
2230		return 0;
2231	if (VOP_GETVOBJECT(vp, &obj) != 0 || (vp->v_vflag & VV_OBJBUF) == 0)
2232		return 0;
2233
2234	size = PAGE_SIZE;
2235	if (size > vp->v_mount->mnt_stat.f_iosize)
2236		size = vp->v_mount->mnt_stat.f_iosize;
2237	off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2238
2239	VM_OBJECT_LOCK(obj);
2240	for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2241		m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2242		if (!m)
2243			goto notinmem;
2244		tinc = size;
2245		if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2246			tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2247		if (vm_page_is_valid(m,
2248		    (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2249			goto notinmem;
2250	}
2251	VM_OBJECT_UNLOCK(obj);
2252	return 1;
2253
2254notinmem:
2255	VM_OBJECT_UNLOCK(obj);
2256	return (0);
2257}
2258
2259/*
2260 *	vfs_setdirty:
2261 *
2262 *	Sets the dirty range for a buffer based on the status of the dirty
2263 *	bits in the pages comprising the buffer.
2264 *
2265 *	The range is limited to the size of the buffer.
2266 *
2267 *	This routine is primarily used by NFS, but is generalized for the
2268 *	B_VMIO case.
2269 */
2270static void
2271vfs_setdirty(struct buf *bp)
2272{
2273	int i;
2274	vm_object_t object;
2275
2276	GIANT_REQUIRED;
2277	/*
2278	 * Degenerate case - empty buffer
2279	 */
2280
2281	if (bp->b_bufsize == 0)
2282		return;
2283
2284	/*
2285	 * We qualify the scan for modified pages on whether the
2286	 * object has been flushed yet.  The OBJ_WRITEABLE flag
2287	 * is not cleared simply by protecting pages off.
2288	 */
2289
2290	if ((bp->b_flags & B_VMIO) == 0)
2291		return;
2292
2293	object = bp->b_pages[0]->object;
2294	VM_OBJECT_LOCK(object);
2295	if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
2296		printf("Warning: object %p writeable but not mightbedirty\n", object);
2297	if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
2298		printf("Warning: object %p mightbedirty but not writeable\n", object);
2299
2300	if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2301		vm_offset_t boffset;
2302		vm_offset_t eoffset;
2303
2304		vm_page_lock_queues();
2305		/*
2306		 * test the pages to see if they have been modified directly
2307		 * by users through the VM system.
2308		 */
2309		for (i = 0; i < bp->b_npages; i++) {
2310			vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
2311			vm_page_test_dirty(bp->b_pages[i]);
2312		}
2313
2314		/*
2315		 * Calculate the encompassing dirty range, boffset and eoffset,
2316		 * (eoffset - boffset) bytes.
2317		 */
2318
2319		for (i = 0; i < bp->b_npages; i++) {
2320			if (bp->b_pages[i]->dirty)
2321				break;
2322		}
2323		boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2324
2325		for (i = bp->b_npages - 1; i >= 0; --i) {
2326			if (bp->b_pages[i]->dirty) {
2327				break;
2328			}
2329		}
2330		eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2331
2332		vm_page_unlock_queues();
2333		/*
2334		 * Fit it to the buffer.
2335		 */
2336
2337		if (eoffset > bp->b_bcount)
2338			eoffset = bp->b_bcount;
2339
2340		/*
2341		 * If we have a good dirty range, merge with the existing
2342		 * dirty range.
2343		 */
2344
2345		if (boffset < eoffset) {
2346			if (bp->b_dirtyoff > boffset)
2347				bp->b_dirtyoff = boffset;
2348			if (bp->b_dirtyend < eoffset)
2349				bp->b_dirtyend = eoffset;
2350		}
2351	}
2352	VM_OBJECT_UNLOCK(object);
2353}
2354
2355/*
2356 *	getblk:
2357 *
2358 *	Get a block given a specified block and offset into a file/device.
2359 *	The buffers B_DONE bit will be cleared on return, making it almost
2360 * 	ready for an I/O initiation.  B_INVAL may or may not be set on
2361 *	return.  The caller should clear B_INVAL prior to initiating a
2362 *	READ.
2363 *
2364 *	For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2365 *	an existing buffer.
2366 *
2367 *	For a VMIO buffer, B_CACHE is modified according to the backing VM.
2368 *	If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2369 *	and then cleared based on the backing VM.  If the previous buffer is
2370 *	non-0-sized but invalid, B_CACHE will be cleared.
2371 *
2372 *	If getblk() must create a new buffer, the new buffer is returned with
2373 *	both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2374 *	case it is returned with B_INVAL clear and B_CACHE set based on the
2375 *	backing VM.
2376 *
2377 *	getblk() also forces a BUF_WRITE() for any B_DELWRI buffer whos
2378 *	B_CACHE bit is clear.
2379 *
2380 *	What this means, basically, is that the caller should use B_CACHE to
2381 *	determine whether the buffer is fully valid or not and should clear
2382 *	B_INVAL prior to issuing a read.  If the caller intends to validate
2383 *	the buffer by loading its data area with something, the caller needs
2384 *	to clear B_INVAL.  If the caller does this without issuing an I/O,
2385 *	the caller should set B_CACHE ( as an optimization ), else the caller
2386 *	should issue the I/O and biodone() will set B_CACHE if the I/O was
2387 *	a write attempt or if it was a successfull read.  If the caller
2388 *	intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
2389 *	prior to issuing the READ.  biodone() will *not* clear B_INVAL.
2390 */
2391struct buf *
2392getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo,
2393    int flags)
2394{
2395	struct buf *bp;
2396	int s;
2397	int error;
2398	ASSERT_VOP_LOCKED(vp, "getblk");
2399
2400	if (size > MAXBSIZE)
2401		panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2402
2403	s = splbio();
2404loop:
2405	/*
2406	 * Block if we are low on buffers.   Certain processes are allowed
2407	 * to completely exhaust the buffer cache.
2408         *
2409         * If this check ever becomes a bottleneck it may be better to
2410         * move it into the else, when gbincore() fails.  At the moment
2411         * it isn't a problem.
2412	 *
2413	 * XXX remove if 0 sections (clean this up after its proven)
2414         */
2415	if (numfreebuffers == 0) {
2416		if (curthread == PCPU_GET(idlethread))
2417			return NULL;
2418		mtx_lock(&nblock);
2419		needsbuffer |= VFS_BIO_NEED_ANY;
2420		mtx_unlock(&nblock);
2421	}
2422
2423	VI_LOCK(vp);
2424	if ((bp = gbincore(vp, blkno))) {
2425		int lockflags;
2426		/*
2427		 * Buffer is in-core.  If the buffer is not busy, it must
2428		 * be on a queue.
2429		 */
2430		lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
2431
2432		if (flags & GB_LOCK_NOWAIT)
2433			lockflags |= LK_NOWAIT;
2434
2435		error = BUF_TIMELOCK(bp, lockflags,
2436		    VI_MTX(vp), "getblk", slpflag, slptimeo);
2437
2438		/*
2439		 * If we slept and got the lock we have to restart in case
2440		 * the buffer changed identities.
2441		 */
2442		if (error == ENOLCK)
2443			goto loop;
2444		/* We timed out or were interrupted. */
2445		else if (error)
2446			return (NULL);
2447
2448		/*
2449		 * The buffer is locked.  B_CACHE is cleared if the buffer is
2450		 * invalid.  Otherwise, for a non-VMIO buffer, B_CACHE is set
2451		 * and for a VMIO buffer B_CACHE is adjusted according to the
2452		 * backing VM cache.
2453		 */
2454		if (bp->b_flags & B_INVAL)
2455			bp->b_flags &= ~B_CACHE;
2456		else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2457			bp->b_flags |= B_CACHE;
2458		bremfree(bp);
2459
2460		/*
2461		 * check for size inconsistancies for non-VMIO case.
2462		 */
2463
2464		if (bp->b_bcount != size) {
2465			if ((bp->b_flags & B_VMIO) == 0 ||
2466			    (size > bp->b_kvasize)) {
2467				if (bp->b_flags & B_DELWRI) {
2468					bp->b_flags |= B_NOCACHE;
2469					BUF_WRITE(bp);
2470				} else {
2471					if ((bp->b_flags & B_VMIO) &&
2472					   (LIST_FIRST(&bp->b_dep) == NULL)) {
2473						bp->b_flags |= B_RELBUF;
2474						brelse(bp);
2475					} else {
2476						bp->b_flags |= B_NOCACHE;
2477						BUF_WRITE(bp);
2478					}
2479				}
2480				goto loop;
2481			}
2482		}
2483
2484		/*
2485		 * If the size is inconsistant in the VMIO case, we can resize
2486		 * the buffer.  This might lead to B_CACHE getting set or
2487		 * cleared.  If the size has not changed, B_CACHE remains
2488		 * unchanged from its previous state.
2489		 */
2490
2491		if (bp->b_bcount != size)
2492			allocbuf(bp, size);
2493
2494		KASSERT(bp->b_offset != NOOFFSET,
2495		    ("getblk: no buffer offset"));
2496
2497		/*
2498		 * A buffer with B_DELWRI set and B_CACHE clear must
2499		 * be committed before we can return the buffer in
2500		 * order to prevent the caller from issuing a read
2501		 * ( due to B_CACHE not being set ) and overwriting
2502		 * it.
2503		 *
2504		 * Most callers, including NFS and FFS, need this to
2505		 * operate properly either because they assume they
2506		 * can issue a read if B_CACHE is not set, or because
2507		 * ( for example ) an uncached B_DELWRI might loop due
2508		 * to softupdates re-dirtying the buffer.  In the latter
2509		 * case, B_CACHE is set after the first write completes,
2510		 * preventing further loops.
2511		 * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
2512		 * above while extending the buffer, we cannot allow the
2513		 * buffer to remain with B_CACHE set after the write
2514		 * completes or it will represent a corrupt state.  To
2515		 * deal with this we set B_NOCACHE to scrap the buffer
2516		 * after the write.
2517		 *
2518		 * We might be able to do something fancy, like setting
2519		 * B_CACHE in bwrite() except if B_DELWRI is already set,
2520		 * so the below call doesn't set B_CACHE, but that gets real
2521		 * confusing.  This is much easier.
2522		 */
2523
2524		if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2525			bp->b_flags |= B_NOCACHE;
2526			BUF_WRITE(bp);
2527			goto loop;
2528		}
2529
2530		splx(s);
2531		bp->b_flags &= ~B_DONE;
2532	} else {
2533		int bsize, maxsize, vmio;
2534		off_t offset;
2535
2536		/*
2537		 * Buffer is not in-core, create new buffer.  The buffer
2538		 * returned by getnewbuf() is locked.  Note that the returned
2539		 * buffer is also considered valid (not marked B_INVAL).
2540		 */
2541		VI_UNLOCK(vp);
2542		/*
2543		 * If the user does not want us to create the buffer, bail out
2544		 * here.
2545		 */
2546		if (flags & GB_NOCREAT) {
2547			splx(s);
2548			return NULL;
2549		}
2550		if (vn_isdisk(vp, NULL))
2551			bsize = DEV_BSIZE;
2552		else if (vp->v_mountedhere)
2553			bsize = vp->v_mountedhere->mnt_stat.f_iosize;
2554		else if (vp->v_mount)
2555			bsize = vp->v_mount->mnt_stat.f_iosize;
2556		else
2557			bsize = size;
2558
2559		offset = blkno * bsize;
2560		vmio = (VOP_GETVOBJECT(vp, NULL) == 0) &&
2561		    (vp->v_vflag & VV_OBJBUF);
2562		maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2563		maxsize = imax(maxsize, bsize);
2564
2565		if ((bp = getnewbuf(slpflag, slptimeo, size, maxsize)) == NULL) {
2566			if (slpflag || slptimeo) {
2567				splx(s);
2568				return NULL;
2569			}
2570			goto loop;
2571		}
2572
2573		/*
2574		 * This code is used to make sure that a buffer is not
2575		 * created while the getnewbuf routine is blocked.
2576		 * This can be a problem whether the vnode is locked or not.
2577		 * If the buffer is created out from under us, we have to
2578		 * throw away the one we just created.  There is now window
2579		 * race because we are safely running at splbio() from the
2580		 * point of the duplicate buffer creation through to here,
2581		 * and we've locked the buffer.
2582		 *
2583		 * Note: this must occur before we associate the buffer
2584		 * with the vp especially considering limitations in
2585		 * the splay tree implementation when dealing with duplicate
2586		 * lblkno's.
2587		 */
2588		VI_LOCK(vp);
2589		if (gbincore(vp, blkno)) {
2590			VI_UNLOCK(vp);
2591			bp->b_flags |= B_INVAL;
2592			brelse(bp);
2593			goto loop;
2594		}
2595
2596		/*
2597		 * Insert the buffer into the hash, so that it can
2598		 * be found by incore.
2599		 */
2600		bp->b_blkno = bp->b_lblkno = blkno;
2601		bp->b_offset = offset;
2602
2603		bgetvp(vp, bp);
2604		VI_UNLOCK(vp);
2605
2606		/*
2607		 * set B_VMIO bit.  allocbuf() the buffer bigger.  Since the
2608		 * buffer size starts out as 0, B_CACHE will be set by
2609		 * allocbuf() for the VMIO case prior to it testing the
2610		 * backing store for validity.
2611		 */
2612
2613		if (vmio) {
2614			bp->b_flags |= B_VMIO;
2615#if defined(VFS_BIO_DEBUG)
2616			if (vp->v_type != VREG)
2617				printf("getblk: vmioing file type %d???\n", vp->v_type);
2618#endif
2619			VOP_GETVOBJECT(vp, &bp->b_object);
2620		} else {
2621			bp->b_flags &= ~B_VMIO;
2622			bp->b_object = NULL;
2623		}
2624
2625		allocbuf(bp, size);
2626
2627		splx(s);
2628		bp->b_flags &= ~B_DONE;
2629	}
2630	KASSERT(BUF_REFCNT(bp) == 1, ("getblk: bp %p not locked",bp));
2631	return (bp);
2632}
2633
2634/*
2635 * Get an empty, disassociated buffer of given size.  The buffer is initially
2636 * set to B_INVAL.
2637 */
2638struct buf *
2639geteblk(int size)
2640{
2641	struct buf *bp;
2642	int s;
2643	int maxsize;
2644
2645	maxsize = (size + BKVAMASK) & ~BKVAMASK;
2646
2647	s = splbio();
2648	while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2649		continue;
2650	splx(s);
2651	allocbuf(bp, size);
2652	bp->b_flags |= B_INVAL;	/* b_dep cleared by getnewbuf() */
2653	KASSERT(BUF_REFCNT(bp) == 1, ("geteblk: bp %p not locked",bp));
2654	return (bp);
2655}
2656
2657
2658/*
2659 * This code constitutes the buffer memory from either anonymous system
2660 * memory (in the case of non-VMIO operations) or from an associated
2661 * VM object (in the case of VMIO operations).  This code is able to
2662 * resize a buffer up or down.
2663 *
2664 * Note that this code is tricky, and has many complications to resolve
2665 * deadlock or inconsistant data situations.  Tread lightly!!!
2666 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2667 * the caller.  Calling this code willy nilly can result in the loss of data.
2668 *
2669 * allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
2670 * B_CACHE for the non-VMIO case.
2671 */
2672
2673int
2674allocbuf(struct buf *bp, int size)
2675{
2676	int newbsize, mbsize;
2677	int i;
2678
2679	GIANT_REQUIRED;
2680
2681	if (BUF_REFCNT(bp) == 0)
2682		panic("allocbuf: buffer not busy");
2683
2684	if (bp->b_kvasize < size)
2685		panic("allocbuf: buffer too small");
2686
2687	if ((bp->b_flags & B_VMIO) == 0) {
2688		caddr_t origbuf;
2689		int origbufsize;
2690		/*
2691		 * Just get anonymous memory from the kernel.  Don't
2692		 * mess with B_CACHE.
2693		 */
2694		mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2695		if (bp->b_flags & B_MALLOC)
2696			newbsize = mbsize;
2697		else
2698			newbsize = round_page(size);
2699
2700		if (newbsize < bp->b_bufsize) {
2701			/*
2702			 * malloced buffers are not shrunk
2703			 */
2704			if (bp->b_flags & B_MALLOC) {
2705				if (newbsize) {
2706					bp->b_bcount = size;
2707				} else {
2708					free(bp->b_data, M_BIOBUF);
2709					if (bp->b_bufsize) {
2710						atomic_subtract_int(
2711						    &bufmallocspace,
2712						    bp->b_bufsize);
2713						bufspacewakeup();
2714						bp->b_bufsize = 0;
2715					}
2716					bp->b_saveaddr = bp->b_kvabase;
2717					bp->b_data = bp->b_saveaddr;
2718					bp->b_bcount = 0;
2719					bp->b_flags &= ~B_MALLOC;
2720				}
2721				return 1;
2722			}
2723			vm_hold_free_pages(
2724			    bp,
2725			    (vm_offset_t) bp->b_data + newbsize,
2726			    (vm_offset_t) bp->b_data + bp->b_bufsize);
2727		} else if (newbsize > bp->b_bufsize) {
2728			/*
2729			 * We only use malloced memory on the first allocation.
2730			 * and revert to page-allocated memory when the buffer
2731			 * grows.
2732			 */
2733			/*
2734			 * There is a potential smp race here that could lead
2735			 * to bufmallocspace slightly passing the max.  It
2736			 * is probably extremely rare and not worth worrying
2737			 * over.
2738			 */
2739			if ( (bufmallocspace < maxbufmallocspace) &&
2740				(bp->b_bufsize == 0) &&
2741				(mbsize <= PAGE_SIZE/2)) {
2742
2743				bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2744				bp->b_bufsize = mbsize;
2745				bp->b_bcount = size;
2746				bp->b_flags |= B_MALLOC;
2747				atomic_add_int(&bufmallocspace, mbsize);
2748				return 1;
2749			}
2750			origbuf = NULL;
2751			origbufsize = 0;
2752			/*
2753			 * If the buffer is growing on its other-than-first allocation,
2754			 * then we revert to the page-allocation scheme.
2755			 */
2756			if (bp->b_flags & B_MALLOC) {
2757				origbuf = bp->b_data;
2758				origbufsize = bp->b_bufsize;
2759				bp->b_data = bp->b_kvabase;
2760				if (bp->b_bufsize) {
2761					atomic_subtract_int(&bufmallocspace,
2762					    bp->b_bufsize);
2763					bufspacewakeup();
2764					bp->b_bufsize = 0;
2765				}
2766				bp->b_flags &= ~B_MALLOC;
2767				newbsize = round_page(newbsize);
2768			}
2769			vm_hold_load_pages(
2770			    bp,
2771			    (vm_offset_t) bp->b_data + bp->b_bufsize,
2772			    (vm_offset_t) bp->b_data + newbsize);
2773			if (origbuf) {
2774				bcopy(origbuf, bp->b_data, origbufsize);
2775				free(origbuf, M_BIOBUF);
2776			}
2777		}
2778	} else {
2779		int desiredpages;
2780
2781		newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2782		desiredpages = (size == 0) ? 0 :
2783			num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2784
2785		if (bp->b_flags & B_MALLOC)
2786			panic("allocbuf: VMIO buffer can't be malloced");
2787		/*
2788		 * Set B_CACHE initially if buffer is 0 length or will become
2789		 * 0-length.
2790		 */
2791		if (size == 0 || bp->b_bufsize == 0)
2792			bp->b_flags |= B_CACHE;
2793
2794		if (newbsize < bp->b_bufsize) {
2795			/*
2796			 * DEV_BSIZE aligned new buffer size is less then the
2797			 * DEV_BSIZE aligned existing buffer size.  Figure out
2798			 * if we have to remove any pages.
2799			 */
2800			if (desiredpages < bp->b_npages) {
2801				vm_page_t m;
2802
2803				vm_page_lock_queues();
2804				for (i = desiredpages; i < bp->b_npages; i++) {
2805					/*
2806					 * the page is not freed here -- it
2807					 * is the responsibility of
2808					 * vnode_pager_setsize
2809					 */
2810					m = bp->b_pages[i];
2811					KASSERT(m != bogus_page,
2812					    ("allocbuf: bogus page found"));
2813					while (vm_page_sleep_if_busy(m, TRUE, "biodep"))
2814						vm_page_lock_queues();
2815
2816					bp->b_pages[i] = NULL;
2817					vm_page_unwire(m, 0);
2818				}
2819				vm_page_unlock_queues();
2820				pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2821				    (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
2822				bp->b_npages = desiredpages;
2823			}
2824		} else if (size > bp->b_bcount) {
2825			/*
2826			 * We are growing the buffer, possibly in a
2827			 * byte-granular fashion.
2828			 */
2829			struct vnode *vp;
2830			vm_object_t obj;
2831			vm_offset_t toff;
2832			vm_offset_t tinc;
2833
2834			/*
2835			 * Step 1, bring in the VM pages from the object,
2836			 * allocating them if necessary.  We must clear
2837			 * B_CACHE if these pages are not valid for the
2838			 * range covered by the buffer.
2839			 */
2840
2841			vp = bp->b_vp;
2842			obj = bp->b_object;
2843
2844			VM_OBJECT_LOCK(obj);
2845			while (bp->b_npages < desiredpages) {
2846				vm_page_t m;
2847				vm_pindex_t pi;
2848
2849				pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
2850				if ((m = vm_page_lookup(obj, pi)) == NULL) {
2851					/*
2852					 * note: must allocate system pages
2853					 * since blocking here could intefere
2854					 * with paging I/O, no matter which
2855					 * process we are.
2856					 */
2857					m = vm_page_alloc(obj, pi,
2858					    VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
2859					if (m == NULL) {
2860						atomic_add_int(&vm_pageout_deficit,
2861						    desiredpages - bp->b_npages);
2862						VM_OBJECT_UNLOCK(obj);
2863						VM_WAIT;
2864						VM_OBJECT_LOCK(obj);
2865					} else {
2866						vm_page_lock_queues();
2867						vm_page_wakeup(m);
2868						vm_page_unlock_queues();
2869						bp->b_flags &= ~B_CACHE;
2870						bp->b_pages[bp->b_npages] = m;
2871						++bp->b_npages;
2872					}
2873					continue;
2874				}
2875
2876				/*
2877				 * We found a page.  If we have to sleep on it,
2878				 * retry because it might have gotten freed out
2879				 * from under us.
2880				 *
2881				 * We can only test PG_BUSY here.  Blocking on
2882				 * m->busy might lead to a deadlock:
2883				 *
2884				 *  vm_fault->getpages->cluster_read->allocbuf
2885				 *
2886				 */
2887				vm_page_lock_queues();
2888				if (vm_page_sleep_if_busy(m, FALSE, "pgtblk"))
2889					continue;
2890
2891				/*
2892				 * We have a good page.  Should we wakeup the
2893				 * page daemon?
2894				 */
2895				if ((curproc != pageproc) &&
2896				    ((m->queue - m->pc) == PQ_CACHE) &&
2897				    ((cnt.v_free_count + cnt.v_cache_count) <
2898					(cnt.v_free_min + cnt.v_cache_min))) {
2899					pagedaemon_wakeup();
2900				}
2901				vm_page_flag_clear(m, PG_ZERO);
2902				vm_page_wire(m);
2903				vm_page_unlock_queues();
2904				bp->b_pages[bp->b_npages] = m;
2905				++bp->b_npages;
2906			}
2907
2908			/*
2909			 * Step 2.  We've loaded the pages into the buffer,
2910			 * we have to figure out if we can still have B_CACHE
2911			 * set.  Note that B_CACHE is set according to the
2912			 * byte-granular range ( bcount and size ), new the
2913			 * aligned range ( newbsize ).
2914			 *
2915			 * The VM test is against m->valid, which is DEV_BSIZE
2916			 * aligned.  Needless to say, the validity of the data
2917			 * needs to also be DEV_BSIZE aligned.  Note that this
2918			 * fails with NFS if the server or some other client
2919			 * extends the file's EOF.  If our buffer is resized,
2920			 * B_CACHE may remain set! XXX
2921			 */
2922
2923			toff = bp->b_bcount;
2924			tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2925
2926			while ((bp->b_flags & B_CACHE) && toff < size) {
2927				vm_pindex_t pi;
2928
2929				if (tinc > (size - toff))
2930					tinc = size - toff;
2931
2932				pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2933				    PAGE_SHIFT;
2934
2935				vfs_buf_test_cache(
2936				    bp,
2937				    bp->b_offset,
2938				    toff,
2939				    tinc,
2940				    bp->b_pages[pi]
2941				);
2942				toff += tinc;
2943				tinc = PAGE_SIZE;
2944			}
2945			VM_OBJECT_UNLOCK(obj);
2946
2947			/*
2948			 * Step 3, fixup the KVM pmap.  Remember that
2949			 * bp->b_data is relative to bp->b_offset, but
2950			 * bp->b_offset may be offset into the first page.
2951			 */
2952
2953			bp->b_data = (caddr_t)
2954			    trunc_page((vm_offset_t)bp->b_data);
2955			pmap_qenter(
2956			    (vm_offset_t)bp->b_data,
2957			    bp->b_pages,
2958			    bp->b_npages
2959			);
2960
2961			bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2962			    (vm_offset_t)(bp->b_offset & PAGE_MASK));
2963		}
2964	}
2965	if (newbsize < bp->b_bufsize)
2966		bufspacewakeup();
2967	bp->b_bufsize = newbsize;	/* actual buffer allocation	*/
2968	bp->b_bcount = size;		/* requested buffer size	*/
2969	return 1;
2970}
2971
2972void
2973biodone(struct bio *bp)
2974{
2975	mtx_lock(&bdonelock);
2976	bp->bio_flags |= BIO_DONE;
2977	if (bp->bio_done == NULL)
2978		wakeup(bp);
2979	mtx_unlock(&bdonelock);
2980	if (bp->bio_done != NULL)
2981		bp->bio_done(bp);
2982}
2983
2984/*
2985 * Wait for a BIO to finish.
2986 *
2987 * XXX: resort to a timeout for now.  The optimal locking (if any) for this
2988 * case is not yet clear.
2989 */
2990int
2991biowait(struct bio *bp, const char *wchan)
2992{
2993
2994	mtx_lock(&bdonelock);
2995	while ((bp->bio_flags & BIO_DONE) == 0)
2996		msleep(bp, &bdonelock, PRIBIO, wchan, hz / 10);
2997	mtx_unlock(&bdonelock);
2998	if (bp->bio_error != 0)
2999		return (bp->bio_error);
3000	if (!(bp->bio_flags & BIO_ERROR))
3001		return (0);
3002	return (EIO);
3003}
3004
3005void
3006biofinish(struct bio *bp, struct devstat *stat, int error)
3007{
3008
3009	if (error) {
3010		bp->bio_error = error;
3011		bp->bio_flags |= BIO_ERROR;
3012	}
3013	if (stat != NULL)
3014		devstat_end_transaction_bio(stat, bp);
3015	biodone(bp);
3016}
3017
3018/*
3019 *	bufwait:
3020 *
3021 *	Wait for buffer I/O completion, returning error status.  The buffer
3022 *	is left locked and B_DONE on return.  B_EINTR is converted into an EINTR
3023 *	error and cleared.
3024 */
3025int
3026bufwait(register struct buf * bp)
3027{
3028	int s;
3029
3030	s = splbio();
3031	if (bp->b_iocmd == BIO_READ)
3032		bwait(bp, PRIBIO, "biord");
3033	else
3034		bwait(bp, PRIBIO, "biowr");
3035	splx(s);
3036	if (bp->b_flags & B_EINTR) {
3037		bp->b_flags &= ~B_EINTR;
3038		return (EINTR);
3039	}
3040	if (bp->b_ioflags & BIO_ERROR) {
3041		return (bp->b_error ? bp->b_error : EIO);
3042	} else {
3043		return (0);
3044	}
3045}
3046
3047 /*
3048  * Call back function from struct bio back up to struct buf.
3049  * The corresponding initialization lives in sys/conf.h:DEV_STRATEGY().
3050  */
3051void
3052bufdonebio(struct bio *bp)
3053{
3054
3055	/* Device drivers may or may not hold giant, hold it here. */
3056	mtx_lock(&Giant);
3057	bufdone(bp->bio_caller2);
3058	mtx_unlock(&Giant);
3059}
3060
3061/*
3062 *	bufdone:
3063 *
3064 *	Finish I/O on a buffer, optionally calling a completion function.
3065 *	This is usually called from an interrupt so process blocking is
3066 *	not allowed.
3067 *
3068 *	biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3069 *	In a non-VMIO bp, B_CACHE will be set on the next getblk()
3070 *	assuming B_INVAL is clear.
3071 *
3072 *	For the VMIO case, we set B_CACHE if the op was a read and no
3073 *	read error occured, or if the op was a write.  B_CACHE is never
3074 *	set if the buffer is invalid or otherwise uncacheable.
3075 *
3076 *	biodone does not mess with B_INVAL, allowing the I/O routine or the
3077 *	initiator to leave B_INVAL set to brelse the buffer out of existance
3078 *	in the biodone routine.
3079 */
3080void
3081bufdone(struct buf *bp)
3082{
3083	int s;
3084	void    (*biodone)(struct buf *);
3085
3086	GIANT_REQUIRED;
3087
3088	s = splbio();
3089
3090	KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp, BUF_REFCNT(bp)));
3091	KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3092
3093	bp->b_flags |= B_DONE;
3094	runningbufwakeup(bp);
3095
3096	if (bp->b_iocmd == BIO_DELETE) {
3097		brelse(bp);
3098		splx(s);
3099		return;
3100	}
3101
3102	if (bp->b_iocmd == BIO_WRITE) {
3103		vwakeup(bp);
3104	}
3105
3106	/* call optional completion function if requested */
3107	if (bp->b_iodone != NULL) {
3108		biodone = bp->b_iodone;
3109		bp->b_iodone = NULL;
3110		(*biodone) (bp);
3111		splx(s);
3112		return;
3113	}
3114	if (LIST_FIRST(&bp->b_dep) != NULL)
3115		buf_complete(bp);
3116
3117	if (bp->b_flags & B_VMIO) {
3118		int i;
3119		vm_ooffset_t foff;
3120		vm_page_t m;
3121		vm_object_t obj;
3122		int iosize;
3123		struct vnode *vp = bp->b_vp;
3124
3125		obj = bp->b_object;
3126
3127#if defined(VFS_BIO_DEBUG)
3128		mp_fixme("usecount and vflag accessed without locks.");
3129		if (vp->v_usecount == 0) {
3130			panic("biodone: zero vnode ref count");
3131		}
3132
3133		if ((vp->v_vflag & VV_OBJBUF) == 0) {
3134			panic("biodone: vnode is not setup for merged cache");
3135		}
3136#endif
3137
3138		foff = bp->b_offset;
3139		KASSERT(bp->b_offset != NOOFFSET,
3140		    ("biodone: no buffer offset"));
3141
3142		if (obj != NULL)
3143			VM_OBJECT_LOCK(obj);
3144#if defined(VFS_BIO_DEBUG)
3145		if (obj->paging_in_progress < bp->b_npages) {
3146			printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
3147			    obj->paging_in_progress, bp->b_npages);
3148		}
3149#endif
3150
3151		/*
3152		 * Set B_CACHE if the op was a normal read and no error
3153		 * occured.  B_CACHE is set for writes in the b*write()
3154		 * routines.
3155		 */
3156		iosize = bp->b_bcount - bp->b_resid;
3157		if (bp->b_iocmd == BIO_READ &&
3158		    !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3159		    !(bp->b_ioflags & BIO_ERROR)) {
3160			bp->b_flags |= B_CACHE;
3161		}
3162		vm_page_lock_queues();
3163		for (i = 0; i < bp->b_npages; i++) {
3164			int bogusflag = 0;
3165			int resid;
3166
3167			resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3168			if (resid > iosize)
3169				resid = iosize;
3170
3171			/*
3172			 * cleanup bogus pages, restoring the originals
3173			 */
3174			m = bp->b_pages[i];
3175			if (m == bogus_page) {
3176				bogusflag = 1;
3177				m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3178				if (m == NULL)
3179					panic("biodone: page disappeared!");
3180				bp->b_pages[i] = m;
3181				pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
3182			}
3183#if defined(VFS_BIO_DEBUG)
3184			if (OFF_TO_IDX(foff) != m->pindex) {
3185				printf(
3186"biodone: foff(%jd)/m->pindex(%ju) mismatch\n",
3187				    (intmax_t)foff, (uintmax_t)m->pindex);
3188			}
3189#endif
3190
3191			/*
3192			 * In the write case, the valid and clean bits are
3193			 * already changed correctly ( see bdwrite() ), so we
3194			 * only need to do this here in the read case.
3195			 */
3196			if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3197				vfs_page_set_valid(bp, foff, i, m);
3198			}
3199			vm_page_flag_clear(m, PG_ZERO);
3200
3201			/*
3202			 * when debugging new filesystems or buffer I/O methods, this
3203			 * is the most common error that pops up.  if you see this, you
3204			 * have not set the page busy flag correctly!!!
3205			 */
3206			if (m->busy == 0) {
3207				printf("biodone: page busy < 0, "
3208				    "pindex: %d, foff: 0x(%x,%x), "
3209				    "resid: %d, index: %d\n",
3210				    (int) m->pindex, (int)(foff >> 32),
3211						(int) foff & 0xffffffff, resid, i);
3212				if (!vn_isdisk(vp, NULL))
3213					printf(" iosize: %ld, lblkno: %jd, flags: 0x%x, npages: %d\n",
3214					    bp->b_vp->v_mount->mnt_stat.f_iosize,
3215					    (intmax_t) bp->b_lblkno,
3216					    bp->b_flags, bp->b_npages);
3217				else
3218					printf(" VDEV, lblkno: %jd, flags: 0x%x, npages: %d\n",
3219					    (intmax_t) bp->b_lblkno,
3220					    bp->b_flags, bp->b_npages);
3221				printf(" valid: 0x%lx, dirty: 0x%lx, wired: %d\n",
3222				    (u_long)m->valid, (u_long)m->dirty,
3223				    m->wire_count);
3224				panic("biodone: page busy < 0\n");
3225			}
3226			vm_page_io_finish(m);
3227			vm_object_pip_subtract(obj, 1);
3228			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3229			iosize -= resid;
3230		}
3231		vm_page_unlock_queues();
3232		if (obj != NULL) {
3233			vm_object_pip_wakeupn(obj, 0);
3234			VM_OBJECT_UNLOCK(obj);
3235		}
3236	}
3237
3238	/*
3239	 * For asynchronous completions, release the buffer now. The brelse
3240	 * will do a wakeup there if necessary - so no need to do a wakeup
3241	 * here in the async case. The sync case always needs to do a wakeup.
3242	 */
3243
3244	if (bp->b_flags & B_ASYNC) {
3245		if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3246			brelse(bp);
3247		else
3248			bqrelse(bp);
3249	} else {
3250		bdone(bp);
3251	}
3252	splx(s);
3253}
3254
3255/*
3256 * This routine is called in lieu of iodone in the case of
3257 * incomplete I/O.  This keeps the busy status for pages
3258 * consistant.
3259 */
3260void
3261vfs_unbusy_pages(struct buf * bp)
3262{
3263	int i;
3264
3265	GIANT_REQUIRED;
3266
3267	runningbufwakeup(bp);
3268	if (bp->b_flags & B_VMIO) {
3269		vm_object_t obj;
3270
3271		obj = bp->b_object;
3272		VM_OBJECT_LOCK(obj);
3273		vm_page_lock_queues();
3274		for (i = 0; i < bp->b_npages; i++) {
3275			vm_page_t m = bp->b_pages[i];
3276
3277			if (m == bogus_page) {
3278				m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3279				if (!m) {
3280					panic("vfs_unbusy_pages: page missing\n");
3281				}
3282				bp->b_pages[i] = m;
3283				pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
3284			}
3285			vm_object_pip_subtract(obj, 1);
3286			vm_page_flag_clear(m, PG_ZERO);
3287			vm_page_io_finish(m);
3288		}
3289		vm_page_unlock_queues();
3290		vm_object_pip_wakeupn(obj, 0);
3291		VM_OBJECT_UNLOCK(obj);
3292	}
3293}
3294
3295/*
3296 * vfs_page_set_valid:
3297 *
3298 *	Set the valid bits in a page based on the supplied offset.   The
3299 *	range is restricted to the buffer's size.
3300 *
3301 *	This routine is typically called after a read completes.
3302 */
3303static void
3304vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3305{
3306	vm_ooffset_t soff, eoff;
3307
3308	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
3309	/*
3310	 * Start and end offsets in buffer.  eoff - soff may not cross a
3311	 * page boundry or cross the end of the buffer.  The end of the
3312	 * buffer, in this case, is our file EOF, not the allocation size
3313	 * of the buffer.
3314	 */
3315	soff = off;
3316	eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3317	if (eoff > bp->b_offset + bp->b_bcount)
3318		eoff = bp->b_offset + bp->b_bcount;
3319
3320	/*
3321	 * Set valid range.  This is typically the entire buffer and thus the
3322	 * entire page.
3323	 */
3324	if (eoff > soff) {
3325		vm_page_set_validclean(
3326		    m,
3327		   (vm_offset_t) (soff & PAGE_MASK),
3328		   (vm_offset_t) (eoff - soff)
3329		);
3330	}
3331}
3332
3333/*
3334 * This routine is called before a device strategy routine.
3335 * It is used to tell the VM system that paging I/O is in
3336 * progress, and treat the pages associated with the buffer
3337 * almost as being PG_BUSY.  Also the object paging_in_progress
3338 * flag is handled to make sure that the object doesn't become
3339 * inconsistant.
3340 *
3341 * Since I/O has not been initiated yet, certain buffer flags
3342 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
3343 * and should be ignored.
3344 */
3345void
3346vfs_busy_pages(struct buf * bp, int clear_modify)
3347{
3348	int i, bogus;
3349
3350	if (bp->b_flags & B_VMIO) {
3351		vm_object_t obj;
3352		vm_ooffset_t foff;
3353
3354		obj = bp->b_object;
3355		foff = bp->b_offset;
3356		KASSERT(bp->b_offset != NOOFFSET,
3357		    ("vfs_busy_pages: no buffer offset"));
3358		vfs_setdirty(bp);
3359		if (obj != NULL)
3360			VM_OBJECT_LOCK(obj);
3361retry:
3362		vm_page_lock_queues();
3363		for (i = 0; i < bp->b_npages; i++) {
3364			vm_page_t m = bp->b_pages[i];
3365
3366			if (vm_page_sleep_if_busy(m, FALSE, "vbpage"))
3367				goto retry;
3368		}
3369		bogus = 0;
3370		for (i = 0; i < bp->b_npages; i++) {
3371			vm_page_t m = bp->b_pages[i];
3372
3373			vm_page_flag_clear(m, PG_ZERO);
3374			if ((bp->b_flags & B_CLUSTER) == 0) {
3375				vm_object_pip_add(obj, 1);
3376				vm_page_io_start(m);
3377			}
3378			/*
3379			 * When readying a buffer for a read ( i.e
3380			 * clear_modify == 0 ), it is important to do
3381			 * bogus_page replacement for valid pages in
3382			 * partially instantiated buffers.  Partially
3383			 * instantiated buffers can, in turn, occur when
3384			 * reconstituting a buffer from its VM backing store
3385			 * base.  We only have to do this if B_CACHE is
3386			 * clear ( which causes the I/O to occur in the
3387			 * first place ).  The replacement prevents the read
3388			 * I/O from overwriting potentially dirty VM-backed
3389			 * pages.  XXX bogus page replacement is, uh, bogus.
3390			 * It may not work properly with small-block devices.
3391			 * We need to find a better way.
3392			 */
3393			pmap_remove_all(m);
3394			if (clear_modify)
3395				vfs_page_set_valid(bp, foff, i, m);
3396			else if (m->valid == VM_PAGE_BITS_ALL &&
3397				(bp->b_flags & B_CACHE) == 0) {
3398				bp->b_pages[i] = bogus_page;
3399				bogus++;
3400			}
3401			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3402		}
3403		vm_page_unlock_queues();
3404		if (obj != NULL)
3405			VM_OBJECT_UNLOCK(obj);
3406		if (bogus)
3407			pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
3408	}
3409}
3410
3411/*
3412 * Tell the VM system that the pages associated with this buffer
3413 * are clean.  This is used for delayed writes where the data is
3414 * going to go to disk eventually without additional VM intevention.
3415 *
3416 * Note that while we only really need to clean through to b_bcount, we
3417 * just go ahead and clean through to b_bufsize.
3418 */
3419static void
3420vfs_clean_pages(struct buf * bp)
3421{
3422	int i;
3423
3424	GIANT_REQUIRED;
3425
3426	if (bp->b_flags & B_VMIO) {
3427		vm_ooffset_t foff;
3428
3429		foff = bp->b_offset;
3430		KASSERT(bp->b_offset != NOOFFSET,
3431		    ("vfs_clean_pages: no buffer offset"));
3432		vm_page_lock_queues();
3433		for (i = 0; i < bp->b_npages; i++) {
3434			vm_page_t m = bp->b_pages[i];
3435			vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3436			vm_ooffset_t eoff = noff;
3437
3438			if (eoff > bp->b_offset + bp->b_bufsize)
3439				eoff = bp->b_offset + bp->b_bufsize;
3440			vfs_page_set_valid(bp, foff, i, m);
3441			/* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3442			foff = noff;
3443		}
3444		vm_page_unlock_queues();
3445	}
3446}
3447
3448/*
3449 *	vfs_bio_set_validclean:
3450 *
3451 *	Set the range within the buffer to valid and clean.  The range is
3452 *	relative to the beginning of the buffer, b_offset.  Note that b_offset
3453 *	itself may be offset from the beginning of the first page.
3454 *
3455 */
3456
3457void
3458vfs_bio_set_validclean(struct buf *bp, int base, int size)
3459{
3460	if (bp->b_flags & B_VMIO) {
3461		int i;
3462		int n;
3463
3464		/*
3465		 * Fixup base to be relative to beginning of first page.
3466		 * Set initial n to be the maximum number of bytes in the
3467		 * first page that can be validated.
3468		 */
3469
3470		base += (bp->b_offset & PAGE_MASK);
3471		n = PAGE_SIZE - (base & PAGE_MASK);
3472
3473		vm_page_lock_queues();
3474		for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3475			vm_page_t m = bp->b_pages[i];
3476
3477			if (n > size)
3478				n = size;
3479
3480			vm_page_set_validclean(m, base & PAGE_MASK, n);
3481			base += n;
3482			size -= n;
3483			n = PAGE_SIZE;
3484		}
3485		vm_page_unlock_queues();
3486	}
3487}
3488
3489/*
3490 *	vfs_bio_clrbuf:
3491 *
3492 *	clear a buffer.  This routine essentially fakes an I/O, so we need
3493 *	to clear BIO_ERROR and B_INVAL.
3494 *
3495 *	Note that while we only theoretically need to clear through b_bcount,
3496 *	we go ahead and clear through b_bufsize.
3497 */
3498
3499void
3500vfs_bio_clrbuf(struct buf *bp)
3501{
3502	int i, mask = 0;
3503	caddr_t sa, ea;
3504
3505	GIANT_REQUIRED;
3506
3507	if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3508		bp->b_flags &= ~B_INVAL;
3509		bp->b_ioflags &= ~BIO_ERROR;
3510		if( (bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3511		    (bp->b_offset & PAGE_MASK) == 0) {
3512			mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3513			if ((bp->b_pages[0]->valid & mask) == mask) {
3514				bp->b_resid = 0;
3515				return;
3516			}
3517			if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
3518			    ((bp->b_pages[0]->valid & mask) == 0)) {
3519				bzero(bp->b_data, bp->b_bufsize);
3520				bp->b_pages[0]->valid |= mask;
3521				bp->b_resid = 0;
3522				return;
3523			}
3524		}
3525		ea = sa = bp->b_data;
3526		for(i=0;i<bp->b_npages;i++,sa=ea) {
3527			int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3528			ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3529			ea = (caddr_t)(vm_offset_t)ulmin(
3530			    (u_long)(vm_offset_t)ea,
3531			    (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3532			mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3533			if ((bp->b_pages[i]->valid & mask) == mask)
3534				continue;
3535			if ((bp->b_pages[i]->valid & mask) == 0) {
3536				if ((bp->b_pages[i]->flags & PG_ZERO) == 0) {
3537					bzero(sa, ea - sa);
3538				}
3539			} else {
3540				for (; sa < ea; sa += DEV_BSIZE, j++) {
3541					if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
3542						(bp->b_pages[i]->valid & (1<<j)) == 0)
3543						bzero(sa, DEV_BSIZE);
3544				}
3545			}
3546			bp->b_pages[i]->valid |= mask;
3547			vm_page_lock_queues();
3548			vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
3549			vm_page_unlock_queues();
3550		}
3551		bp->b_resid = 0;
3552	} else {
3553		clrbuf(bp);
3554	}
3555}
3556
3557/*
3558 * vm_hold_load_pages and vm_hold_free_pages get pages into
3559 * a buffers address space.  The pages are anonymous and are
3560 * not associated with a file object.
3561 */
3562static void
3563vm_hold_load_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3564{
3565	vm_offset_t pg;
3566	vm_page_t p;
3567	int index;
3568
3569	GIANT_REQUIRED;
3570
3571	to = round_page(to);
3572	from = round_page(from);
3573	index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3574
3575	VM_OBJECT_LOCK(kernel_object);
3576	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3577tryagain:
3578		/*
3579		 * note: must allocate system pages since blocking here
3580		 * could intefere with paging I/O, no matter which
3581		 * process we are.
3582		 */
3583		p = vm_page_alloc(kernel_object,
3584			((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3585		    VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
3586		if (!p) {
3587			atomic_add_int(&vm_pageout_deficit,
3588			    (to - pg) >> PAGE_SHIFT);
3589			VM_OBJECT_UNLOCK(kernel_object);
3590			VM_WAIT;
3591			VM_OBJECT_LOCK(kernel_object);
3592			goto tryagain;
3593		}
3594		p->valid = VM_PAGE_BITS_ALL;
3595		pmap_qenter(pg, &p, 1);
3596		bp->b_pages[index] = p;
3597		vm_page_lock_queues();
3598		vm_page_wakeup(p);
3599		vm_page_unlock_queues();
3600	}
3601	VM_OBJECT_UNLOCK(kernel_object);
3602	bp->b_npages = index;
3603}
3604
3605/* Return pages associated with this buf to the vm system */
3606static void
3607vm_hold_free_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3608{
3609	vm_offset_t pg;
3610	vm_page_t p;
3611	int index, newnpages;
3612
3613	GIANT_REQUIRED;
3614
3615	from = round_page(from);
3616	to = round_page(to);
3617	newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3618
3619	VM_OBJECT_LOCK(kernel_object);
3620	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3621		p = bp->b_pages[index];
3622		if (p && (index < bp->b_npages)) {
3623			if (p->busy) {
3624				printf(
3625			    "vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
3626				    (intmax_t)bp->b_blkno,
3627				    (intmax_t)bp->b_lblkno);
3628			}
3629			bp->b_pages[index] = NULL;
3630			pmap_qremove(pg, 1);
3631			vm_page_lock_queues();
3632			vm_page_busy(p);
3633			vm_page_unwire(p, 0);
3634			vm_page_free(p);
3635			vm_page_unlock_queues();
3636		}
3637	}
3638	VM_OBJECT_UNLOCK(kernel_object);
3639	bp->b_npages = newnpages;
3640}
3641
3642/*
3643 * Map an IO request into kernel virtual address space.
3644 *
3645 * All requests are (re)mapped into kernel VA space.
3646 * Notice that we use b_bufsize for the size of the buffer
3647 * to be mapped.  b_bcount might be modified by the driver.
3648 *
3649 * Note that even if the caller determines that the address space should
3650 * be valid, a race or a smaller-file mapped into a larger space may
3651 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
3652 * check the return value.
3653 */
3654int
3655vmapbuf(struct buf *bp)
3656{
3657	caddr_t addr, kva;
3658	vm_prot_t prot;
3659	int pidx, i;
3660	struct vm_page *m;
3661	struct pmap *pmap = &curproc->p_vmspace->vm_pmap;
3662
3663	GIANT_REQUIRED;
3664
3665	if ((bp->b_flags & B_PHYS) == 0)
3666		panic("vmapbuf");
3667	if (bp->b_bufsize < 0)
3668		return (-1);
3669	prot = (bp->b_iocmd == BIO_READ) ? VM_PROT_READ | VM_PROT_WRITE :
3670	    VM_PROT_READ;
3671	for (addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data), pidx = 0;
3672	     addr < bp->b_data + bp->b_bufsize;
3673	     addr += PAGE_SIZE, pidx++) {
3674		/*
3675		 * Do the vm_fault if needed; do the copy-on-write thing
3676		 * when reading stuff off device into memory.
3677		 *
3678		 * NOTE! Must use pmap_extract() because addr may be in
3679		 * the userland address space, and kextract is only guarenteed
3680		 * to work for the kernland address space (see: sparc64 port).
3681		 */
3682retry:
3683		if (vm_fault_quick(addr >= bp->b_data ? addr : bp->b_data,
3684		    prot) < 0) {
3685			vm_page_lock_queues();
3686			for (i = 0; i < pidx; ++i) {
3687				vm_page_unhold(bp->b_pages[i]);
3688				bp->b_pages[i] = NULL;
3689			}
3690			vm_page_unlock_queues();
3691			return(-1);
3692		}
3693		m = pmap_extract_and_hold(pmap, (vm_offset_t)addr, prot);
3694		if (m == NULL)
3695			goto retry;
3696		bp->b_pages[pidx] = m;
3697	}
3698	if (pidx > btoc(MAXPHYS))
3699		panic("vmapbuf: mapped more than MAXPHYS");
3700	pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
3701
3702	kva = bp->b_saveaddr;
3703	bp->b_npages = pidx;
3704	bp->b_saveaddr = bp->b_data;
3705	bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3706	return(0);
3707}
3708
3709/*
3710 * Free the io map PTEs associated with this IO operation.
3711 * We also invalidate the TLB entries and restore the original b_addr.
3712 */
3713void
3714vunmapbuf(struct buf *bp)
3715{
3716	int pidx;
3717	int npages;
3718
3719	GIANT_REQUIRED;
3720
3721	if ((bp->b_flags & B_PHYS) == 0)
3722		panic("vunmapbuf");
3723
3724	npages = bp->b_npages;
3725	pmap_qremove(trunc_page((vm_offset_t)bp->b_data),
3726		     npages);
3727	vm_page_lock_queues();
3728	for (pidx = 0; pidx < npages; pidx++)
3729		vm_page_unhold(bp->b_pages[pidx]);
3730	vm_page_unlock_queues();
3731
3732	bp->b_data = bp->b_saveaddr;
3733}
3734
3735void
3736bdone(struct buf *bp)
3737{
3738	mtx_lock(&bdonelock);
3739	bp->b_flags |= B_DONE;
3740	wakeup(bp);
3741	mtx_unlock(&bdonelock);
3742}
3743
3744void
3745bwait(struct buf *bp, u_char pri, const char *wchan)
3746{
3747	mtx_lock(&bdonelock);
3748	while ((bp->b_flags & B_DONE) == 0)
3749		msleep(bp, &bdonelock, pri, wchan, 0);
3750	mtx_unlock(&bdonelock);
3751}
3752
3753#include "opt_ddb.h"
3754#ifdef DDB
3755#include <ddb/ddb.h>
3756
3757/* DDB command to show buffer data */
3758DB_SHOW_COMMAND(buffer, db_show_buffer)
3759{
3760	/* get args */
3761	struct buf *bp = (struct buf *)addr;
3762
3763	if (!have_addr) {
3764		db_printf("usage: show buffer <addr>\n");
3765		return;
3766	}
3767
3768	db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3769	db_printf(
3770	    "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
3771	    "b_dev = (%d,%d), b_data = %p, b_blkno = %jd, b_pblkno = %jd\n",
3772	    bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3773	    major(bp->b_dev), minor(bp->b_dev), bp->b_data,
3774	    (intmax_t)bp->b_blkno, (intmax_t)bp->b_pblkno);
3775	if (bp->b_npages) {
3776		int i;
3777		db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
3778		for (i = 0; i < bp->b_npages; i++) {
3779			vm_page_t m;
3780			m = bp->b_pages[i];
3781			db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3782			    (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3783			if ((i + 1) < bp->b_npages)
3784				db_printf(",");
3785		}
3786		db_printf("\n");
3787	}
3788}
3789#endif /* DDB */
3790