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