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