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