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