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