vfs_bio.c revision 18271
1/*
2 * Copyright (c) 1994 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. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 * 3. Absolutely no warranty of function or purpose is made by the author
15 *    John S. Dyson.
16 * 4. This work was done expressly for inclusion into FreeBSD.  Other use
17 *    is allowed if this notation is included.
18 * 5. Modifications may be freely made to this file if the above conditions
19 *    are met.
20 *
21 * $Id: vfs_bio.c,v 1.98 1996/09/08 20:44:20 dyson Exp $
22 */
23
24/*
25 * this file contains a new buffer I/O scheme implementing a coherent
26 * VM object and buffer cache scheme.  Pains have been taken to make
27 * sure that the performance degradation associated with schemes such
28 * as this is not realized.
29 *
30 * Author:  John S. Dyson
31 * Significant help during the development and debugging phases
32 * had been provided by David Greenman, also of the FreeBSD core team.
33 */
34
35#include "opt_bounce.h"
36
37#define VMIO
38#include <sys/param.h>
39#include <sys/systm.h>
40#include <sys/sysproto.h>
41#include <sys/kernel.h>
42#include <sys/sysctl.h>
43#include <sys/proc.h>
44#include <sys/vnode.h>
45#include <sys/vmmeter.h>
46#include <vm/vm.h>
47#include <vm/vm_param.h>
48#include <vm/vm_prot.h>
49#include <vm/vm_kern.h>
50#include <vm/vm_pageout.h>
51#include <vm/vm_page.h>
52#include <vm/vm_object.h>
53#include <vm/vm_extern.h>
54#include <sys/buf.h>
55#include <sys/mount.h>
56#include <sys/malloc.h>
57#include <sys/resourcevar.h>
58#include <sys/proc.h>
59
60#include <miscfs/specfs/specdev.h>
61
62static void vfs_update __P((void));
63static struct	proc *updateproc;
64static struct kproc_desc up_kp = {
65	"update",
66	vfs_update,
67	&updateproc
68};
69SYSINIT_KT(update, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp)
70
71struct buf *buf;		/* buffer header pool */
72struct swqueue bswlist;
73
74int count_lock_queue __P((void));
75static void vm_hold_free_pages(struct buf * bp, vm_offset_t from,
76		vm_offset_t to);
77static void vm_hold_load_pages(struct buf * bp, vm_offset_t from,
78		vm_offset_t to);
79static void vfs_clean_pages(struct buf * bp);
80static void vfs_setdirty(struct buf *bp);
81static void vfs_vmio_release(struct buf *bp);
82
83int needsbuffer;
84
85/*
86 * Internal update daemon, process 3
87 *	The variable vfs_update_wakeup allows for internal syncs.
88 */
89int vfs_update_wakeup;
90
91
92/*
93 * buffers base kva
94 */
95caddr_t buffers_kva;
96
97/*
98 * bogus page -- for I/O to/from partially complete buffers
99 * this is a temporary solution to the problem, but it is not
100 * really that bad.  it would be better to split the buffer
101 * for input in the case of buffers partially already in memory,
102 * but the code is intricate enough already.
103 */
104vm_page_t bogus_page;
105static vm_offset_t bogus_offset;
106
107static int bufspace, maxbufspace, vmiospace, maxvmiobufspace,
108	bufmallocspace, maxbufmallocspace;
109
110static struct bufhashhdr bufhashtbl[BUFHSZ], invalhash;
111static struct bqueues bufqueues[BUFFER_QUEUES];
112
113extern int vm_swap_size;
114
115#define BUF_MAXUSE 8
116/*
117#define NO_B_MALLOC
118*/
119
120/*
121 * Initialize buffer headers and related structures.
122 */
123void
124bufinit()
125{
126	struct buf *bp;
127	int i;
128
129	TAILQ_INIT(&bswlist);
130	LIST_INIT(&invalhash);
131
132	/* first, make a null hash table */
133	for (i = 0; i < BUFHSZ; i++)
134		LIST_INIT(&bufhashtbl[i]);
135
136	/* next, make a null set of free lists */
137	for (i = 0; i < BUFFER_QUEUES; i++)
138		TAILQ_INIT(&bufqueues[i]);
139
140	buffers_kva = (caddr_t) kmem_alloc_pageable(buffer_map, MAXBSIZE * nbuf);
141	/* finally, initialize each buffer header and stick on empty q */
142	for (i = 0; i < nbuf; i++) {
143		bp = &buf[i];
144		bzero(bp, sizeof *bp);
145		bp->b_flags = B_INVAL;	/* we're just an empty header */
146		bp->b_dev = NODEV;
147		bp->b_rcred = NOCRED;
148		bp->b_wcred = NOCRED;
149		bp->b_qindex = QUEUE_EMPTY;
150		bp->b_vnbufs.le_next = NOLIST;
151		bp->b_data = buffers_kva + i * MAXBSIZE;
152		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
153		LIST_INSERT_HEAD(&invalhash, bp, b_hash);
154	}
155/*
156 * maxbufspace is currently calculated to support all filesystem blocks
157 * to be 8K.  If you happen to use a 16K filesystem, the size of the buffer
158 * cache is still the same as it would be for 8K filesystems.  This
159 * keeps the size of the buffer cache "in check" for big block filesystems.
160 */
161	maxbufspace = 2 * (nbuf + 8) * PAGE_SIZE;
162/*
163 * reserve 1/3 of the buffers for metadata (VDIR) which might not be VMIO'ed
164 */
165	maxvmiobufspace = 2 * maxbufspace / 3;
166/*
167 * Limit the amount of malloc memory since it is wired permanently into
168 * the kernel space.  Even though this is accounted for in the buffer
169 * allocation, we don't want the malloced region to grow uncontrolled.
170 * The malloc scheme improves memory utilization significantly on average
171 * (small) directories.
172 */
173	maxbufmallocspace = maxbufspace / 20;
174
175	bogus_offset = kmem_alloc_pageable(kernel_map, PAGE_SIZE);
176	bogus_page = vm_page_alloc(kernel_object,
177			((bogus_offset - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
178			VM_ALLOC_NORMAL);
179
180}
181
182/*
183 * remove the buffer from the appropriate free list
184 */
185void
186bremfree(struct buf * bp)
187{
188	int s = splbio();
189
190	if (bp->b_qindex != QUEUE_NONE) {
191		TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
192		bp->b_qindex = QUEUE_NONE;
193	} else {
194		panic("bremfree: removing a buffer when not on a queue");
195	}
196	splx(s);
197}
198
199/*
200 * Get a buffer with the specified data.  Look in the cache first.
201 */
202int
203bread(struct vnode * vp, daddr_t blkno, int size, struct ucred * cred,
204    struct buf ** bpp)
205{
206	struct buf *bp;
207
208	bp = getblk(vp, blkno, size, 0, 0);
209	*bpp = bp;
210
211	/* if not found in cache, do some I/O */
212	if ((bp->b_flags & B_CACHE) == 0) {
213		if (curproc != NULL)
214			curproc->p_stats->p_ru.ru_inblock++;
215		bp->b_flags |= B_READ;
216		bp->b_flags &= ~(B_DONE | B_ERROR | B_INVAL);
217		if (bp->b_rcred == NOCRED) {
218			if (cred != NOCRED)
219				crhold(cred);
220			bp->b_rcred = cred;
221		}
222		vfs_busy_pages(bp, 0);
223		VOP_STRATEGY(bp);
224		return (biowait(bp));
225	}
226	return (0);
227}
228
229/*
230 * Operates like bread, but also starts asynchronous I/O on
231 * read-ahead blocks.
232 */
233int
234breadn(struct vnode * vp, daddr_t blkno, int size,
235    daddr_t * rablkno, int *rabsize,
236    int cnt, struct ucred * cred, struct buf ** bpp)
237{
238	struct buf *bp, *rabp;
239	int i;
240	int rv = 0, readwait = 0;
241
242	*bpp = bp = getblk(vp, blkno, size, 0, 0);
243
244	/* if not found in cache, do some I/O */
245	if ((bp->b_flags & B_CACHE) == 0) {
246		if (curproc != NULL)
247			curproc->p_stats->p_ru.ru_inblock++;
248		bp->b_flags |= B_READ;
249		bp->b_flags &= ~(B_DONE | B_ERROR | B_INVAL);
250		if (bp->b_rcred == NOCRED) {
251			if (cred != NOCRED)
252				crhold(cred);
253			bp->b_rcred = cred;
254		}
255		vfs_busy_pages(bp, 0);
256		VOP_STRATEGY(bp);
257		++readwait;
258	}
259	for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
260		if (inmem(vp, *rablkno))
261			continue;
262		rabp = getblk(vp, *rablkno, *rabsize, 0, 0);
263
264		if ((rabp->b_flags & B_CACHE) == 0) {
265			if (curproc != NULL)
266				curproc->p_stats->p_ru.ru_inblock++;
267			rabp->b_flags |= B_READ | B_ASYNC;
268			rabp->b_flags &= ~(B_DONE | B_ERROR | B_INVAL);
269			if (rabp->b_rcred == NOCRED) {
270				if (cred != NOCRED)
271					crhold(cred);
272				rabp->b_rcred = cred;
273			}
274			vfs_busy_pages(rabp, 0);
275			VOP_STRATEGY(rabp);
276		} else {
277			brelse(rabp);
278		}
279	}
280
281	if (readwait) {
282		rv = biowait(bp);
283	}
284	return (rv);
285}
286
287/*
288 * Write, release buffer on completion.  (Done by iodone
289 * if async.)
290 */
291int
292bwrite(struct buf * bp)
293{
294	int oldflags = bp->b_flags;
295
296	if (bp->b_flags & B_INVAL) {
297		brelse(bp);
298		return (0);
299	}
300	if (!(bp->b_flags & B_BUSY))
301		panic("bwrite: buffer is not busy???");
302
303	bp->b_flags &= ~(B_READ | B_DONE | B_ERROR | B_DELWRI);
304	bp->b_flags |= B_WRITEINPROG;
305
306	if ((oldflags & (B_ASYNC|B_DELWRI)) == (B_ASYNC|B_DELWRI)) {
307		reassignbuf(bp, bp->b_vp);
308	}
309
310	bp->b_vp->v_numoutput++;
311	vfs_busy_pages(bp, 1);
312	if (curproc != NULL)
313		curproc->p_stats->p_ru.ru_oublock++;
314	VOP_STRATEGY(bp);
315
316	/* if ((bp->b_flags & B_ASYNC) == 0) { */
317	if ((oldflags & B_ASYNC) == 0) {
318		int rtval = biowait(bp);
319
320		if (oldflags & B_DELWRI) {
321			reassignbuf(bp, bp->b_vp);
322		}
323		brelse(bp);
324		return (rtval);
325	}
326	return (0);
327}
328
329int
330vn_bwrite(ap)
331	struct vop_bwrite_args *ap;
332{
333	return (bwrite(ap->a_bp));
334}
335
336/*
337 * Delayed write. (Buffer is marked dirty).
338 */
339void
340bdwrite(struct buf * bp)
341{
342
343	if ((bp->b_flags & B_BUSY) == 0) {
344		panic("bdwrite: buffer is not busy");
345	}
346	if (bp->b_flags & B_INVAL) {
347		brelse(bp);
348		return;
349	}
350	if (bp->b_flags & B_TAPE) {
351		bawrite(bp);
352		return;
353	}
354	bp->b_flags &= ~(B_READ|B_RELBUF);
355	if ((bp->b_flags & B_DELWRI) == 0) {
356		bp->b_flags |= B_DONE | B_DELWRI;
357		reassignbuf(bp, bp->b_vp);
358	}
359
360	/*
361	 * This bmap keeps the system from needing to do the bmap later,
362	 * perhaps when the system is attempting to do a sync.  Since it
363	 * is likely that the indirect block -- or whatever other datastructure
364	 * that the filesystem needs is still in memory now, it is a good
365	 * thing to do this.  Note also, that if the pageout daemon is
366	 * requesting a sync -- there might not be enough memory to do
367	 * the bmap then...  So, this is important to do.
368	 */
369	if( bp->b_lblkno == bp->b_blkno) {
370		VOP_BMAP(bp->b_vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
371	}
372
373	/*
374	 * Set the *dirty* buffer range based upon the VM system dirty pages.
375	 */
376	vfs_setdirty(bp);
377
378	/*
379	 * We need to do this here to satisfy the vnode_pager and the
380	 * pageout daemon, so that it thinks that the pages have been
381	 * "cleaned".  Note that since the pages are in a delayed write
382	 * buffer -- the VFS layer "will" see that the pages get written
383	 * out on the next sync, or perhaps the cluster will be completed.
384	 */
385	vfs_clean_pages(bp);
386	bqrelse(bp);
387	return;
388}
389
390/*
391 * Asynchronous write.
392 * Start output on a buffer, but do not wait for it to complete.
393 * The buffer is released when the output completes.
394 */
395void
396bawrite(struct buf * bp)
397{
398	bp->b_flags |= B_ASYNC;
399	(void) VOP_BWRITE(bp);
400}
401
402/*
403 * Ordered write.
404 * Start output on a buffer, but only wait for it to complete if the
405 * output device cannot guarantee ordering in some other way.  Devices
406 * that can perform asynchronous ordered writes will set the B_ASYNC
407 * flag in their strategy routine.
408 * The buffer is released when the output completes.
409 */
410int
411bowrite(struct buf * bp)
412{
413	bp->b_flags |= B_ORDERED;
414	return (VOP_BWRITE(bp));
415}
416
417/*
418 * Release a buffer.
419 */
420void
421brelse(struct buf * bp)
422{
423	int s;
424
425	if (bp->b_flags & B_CLUSTER) {
426		relpbuf(bp);
427		return;
428	}
429	/* anyone need a "free" block? */
430	s = splbio();
431
432	/* anyone need this block? */
433	if (bp->b_flags & B_WANTED) {
434		bp->b_flags &= ~(B_WANTED | B_AGE);
435		wakeup(bp);
436	}
437
438	if (bp->b_flags & B_LOCKED)
439		bp->b_flags &= ~B_ERROR;
440
441	if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR)) ||
442	    (bp->b_bufsize <= 0)) {
443		bp->b_flags |= B_INVAL;
444		bp->b_flags &= ~(B_DELWRI | B_CACHE);
445		if (((bp->b_flags & B_VMIO) == 0) && bp->b_vp) {
446			if (bp->b_bufsize)
447				allocbuf(bp, 0);
448			brelvp(bp);
449		}
450	}
451
452	/*
453	 * VMIO buffer rundown.  It is not very necessary to keep a VMIO buffer
454	 * constituted, so the B_INVAL flag is used to *invalidate* the buffer,
455	 * but the VM object is kept around.  The B_NOCACHE flag is used to
456	 * invalidate the pages in the VM object.
457	 */
458	if (bp->b_flags & B_VMIO) {
459		vm_ooffset_t foff;
460		vm_object_t obj;
461		int i, resid;
462		vm_page_t m;
463		struct vnode *vp;
464		int iototal = bp->b_bufsize;
465
466		vp = bp->b_vp;
467		if (!vp)
468			panic("brelse: missing vp");
469
470		if (bp->b_npages) {
471			vm_pindex_t poff;
472			obj = (vm_object_t) vp->v_object;
473			if (vp->v_type == VBLK)
474				foff = ((vm_ooffset_t) bp->b_lblkno) << DEV_BSHIFT;
475			else
476				foff = (vm_ooffset_t) vp->v_mount->mnt_stat.f_iosize * bp->b_lblkno;
477			poff = OFF_TO_IDX(foff);
478			for (i = 0; i < bp->b_npages; i++) {
479				m = bp->b_pages[i];
480				if (m == bogus_page) {
481					m = vm_page_lookup(obj, poff + i);
482					if (!m) {
483						panic("brelse: page missing\n");
484					}
485					bp->b_pages[i] = m;
486					pmap_qenter(trunc_page(bp->b_data),
487						bp->b_pages, bp->b_npages);
488				}
489				resid = IDX_TO_OFF(m->pindex+1) - foff;
490				if (resid > iototal)
491					resid = iototal;
492				if (resid > 0) {
493					/*
494					 * Don't invalidate the page if the local machine has already
495					 * modified it.  This is the lesser of two evils, and should
496					 * be fixed.
497					 */
498					if (bp->b_flags & (B_NOCACHE | B_ERROR)) {
499						vm_page_test_dirty(m);
500						if (m->dirty == 0) {
501							vm_page_set_invalid(m, (vm_offset_t) foff, resid);
502							if (m->valid == 0)
503								vm_page_protect(m, VM_PROT_NONE);
504						}
505					}
506					if (resid >= PAGE_SIZE) {
507						if ((m->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL) {
508							bp->b_flags |= B_INVAL;
509						}
510					} else {
511						if (!vm_page_is_valid(m,
512							(((vm_offset_t) bp->b_data) & PAGE_MASK), resid)) {
513							bp->b_flags |= B_INVAL;
514						}
515					}
516				}
517				foff += resid;
518				iototal -= resid;
519			}
520		}
521		if (bp->b_flags & (B_INVAL | B_RELBUF))
522			vfs_vmio_release(bp);
523	}
524	if (bp->b_qindex != QUEUE_NONE)
525		panic("brelse: free buffer onto another queue???");
526
527	/* enqueue */
528	/* buffers with no memory */
529	if (bp->b_bufsize == 0) {
530		bp->b_qindex = QUEUE_EMPTY;
531		TAILQ_INSERT_HEAD(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
532		LIST_REMOVE(bp, b_hash);
533		LIST_INSERT_HEAD(&invalhash, bp, b_hash);
534		bp->b_dev = NODEV;
535		if (needsbuffer) {
536			wakeup(&needsbuffer);
537			needsbuffer=0;
538		}
539		/* buffers with junk contents */
540	} else if (bp->b_flags & (B_ERROR | B_INVAL | B_NOCACHE | B_RELBUF)) {
541		bp->b_qindex = QUEUE_AGE;
542		TAILQ_INSERT_HEAD(&bufqueues[QUEUE_AGE], bp, b_freelist);
543		LIST_REMOVE(bp, b_hash);
544		LIST_INSERT_HEAD(&invalhash, bp, b_hash);
545		bp->b_dev = NODEV;
546		if (needsbuffer) {
547			wakeup(&needsbuffer);
548			needsbuffer=0;
549		}
550		/* buffers that are locked */
551	} else if (bp->b_flags & B_LOCKED) {
552		bp->b_qindex = QUEUE_LOCKED;
553		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
554		/* buffers with stale but valid contents */
555	} else if (bp->b_flags & B_AGE) {
556		bp->b_qindex = QUEUE_AGE;
557		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_AGE], bp, b_freelist);
558		if (needsbuffer) {
559			wakeup(&needsbuffer);
560			needsbuffer=0;
561		}
562		/* buffers with valid and quite potentially reuseable contents */
563	} else {
564		bp->b_qindex = QUEUE_LRU;
565		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LRU], bp, b_freelist);
566		if (needsbuffer) {
567			wakeup(&needsbuffer);
568			needsbuffer=0;
569		}
570	}
571
572	/* unlock */
573	bp->b_flags &= ~(B_WANTED | B_BUSY | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
574	splx(s);
575}
576
577/*
578 * Release a buffer.
579 */
580void
581bqrelse(struct buf * bp)
582{
583	int s;
584
585	s = splbio();
586
587
588	/* anyone need this block? */
589	if (bp->b_flags & B_WANTED) {
590		bp->b_flags &= ~(B_WANTED | B_AGE);
591		wakeup(bp);
592	}
593
594	if (bp->b_qindex != QUEUE_NONE)
595		panic("bqrelse: free buffer onto another queue???");
596
597	if (bp->b_flags & B_LOCKED) {
598		bp->b_flags &= ~B_ERROR;
599		bp->b_qindex = QUEUE_LOCKED;
600		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
601		/* buffers with stale but valid contents */
602	} else {
603		bp->b_qindex = QUEUE_LRU;
604		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LRU], bp, b_freelist);
605		if (needsbuffer) {
606			wakeup(&needsbuffer);
607			needsbuffer=0;
608		}
609	}
610
611	/* unlock */
612	bp->b_flags &= ~(B_WANTED | B_BUSY | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
613	splx(s);
614}
615
616static void
617vfs_vmio_release(bp)
618	struct buf *bp;
619{
620	int i;
621	vm_page_t m;
622
623	for (i = 0; i < bp->b_npages; i++) {
624		m = bp->b_pages[i];
625		bp->b_pages[i] = NULL;
626		if (m->flags & PG_WANTED) {
627			m->flags &= ~PG_WANTED;
628			wakeup(m);
629		}
630		vm_page_unwire(m);
631		if (m->wire_count == 0 && (m->flags & PG_BUSY) == 0) {
632			if (m->valid) {
633				if(m->dirty == 0)
634					vm_page_test_dirty(m);
635				/*
636				 * this keeps pressure off of the process memory
637				 */
638				if ((vm_swap_size == 0) ||
639					(cnt.v_free_count < cnt.v_free_min)) {
640					if ((m->dirty == 0) &&
641						(m->hold_count == 0) &&
642						(m->flags & PG_BUSY) == 0 &&
643						(m->busy == 0))
644						vm_page_cache(m);
645					else
646						vm_page_deactivate(m);
647				}
648			} else if ((m->hold_count == 0) &&
649				((m->flags & PG_BUSY) == 0) &&
650				(m->busy == 0)) {
651				vm_page_protect(m, VM_PROT_NONE);
652				vm_page_free(m);
653			}
654		}
655	}
656	bufspace -= bp->b_bufsize;
657	vmiospace -= bp->b_bufsize;
658	pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
659	bp->b_npages = 0;
660	bp->b_bufsize = 0;
661	bp->b_flags &= ~B_VMIO;
662	if (bp->b_vp)
663		brelvp(bp);
664}
665
666/*
667 * Check to see if a block is currently memory resident.
668 */
669__inline struct buf *
670gbincore(struct vnode * vp, daddr_t blkno)
671{
672	struct buf *bp;
673	struct bufhashhdr *bh;
674
675	bh = BUFHASH(vp, blkno);
676	bp = bh->lh_first;
677
678	/* Search hash chain */
679	while (bp != NULL) {
680		/* hit */
681		if (bp->b_vp == vp && bp->b_lblkno == blkno &&
682		    (bp->b_flags & B_INVAL) == 0) {
683			break;
684		}
685		bp = bp->b_hash.le_next;
686	}
687	return (bp);
688}
689
690/*
691 * this routine implements clustered async writes for
692 * clearing out B_DELWRI buffers...  This is much better
693 * than the old way of writing only one buffer at a time.
694 */
695int
696vfs_bio_awrite(struct buf * bp)
697{
698	int i;
699	daddr_t lblkno = bp->b_lblkno;
700	struct vnode *vp = bp->b_vp;
701	int s;
702	int ncl;
703	struct buf *bpa;
704	int nwritten;
705
706	s = splbio();
707	/*
708	 * right now we support clustered writing only to regular files
709	 */
710	if ((vp->v_type == VREG) &&
711	    (vp->v_mount != 0) && /* Only on nodes that have the size info */
712	    (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
713		int size;
714		int maxcl;
715
716		size = vp->v_mount->mnt_stat.f_iosize;
717		maxcl = MAXPHYS / size;
718
719		for (i = 1; i < maxcl; i++) {
720			if ((bpa = gbincore(vp, lblkno + i)) &&
721			    ((bpa->b_flags & (B_BUSY | B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
722			    (B_DELWRI | B_CLUSTEROK)) &&
723			    (bpa->b_bufsize == size)) {
724				if ((bpa->b_blkno == bpa->b_lblkno) ||
725				    (bpa->b_blkno != bp->b_blkno + ((i * size) >> DEV_BSHIFT)))
726					break;
727			} else {
728				break;
729			}
730		}
731		ncl = i;
732		/*
733		 * this is a possible cluster write
734		 */
735		if (ncl != 1) {
736			nwritten = cluster_wbuild(vp, size, lblkno, ncl);
737			splx(s);
738			return nwritten;
739		}
740	}
741	bremfree(bp);
742	splx(s);
743	/*
744	 * default (old) behavior, writing out only one block
745	 */
746	bp->b_flags |= B_BUSY | B_ASYNC;
747	nwritten = bp->b_bufsize;
748	(void) VOP_BWRITE(bp);
749	return nwritten;
750}
751
752
753/*
754 * Find a buffer header which is available for use.
755 */
756static struct buf *
757getnewbuf(int slpflag, int slptimeo, int doingvmio)
758{
759	struct buf *bp;
760	int nbyteswritten = 0;
761
762start:
763	if (bufspace >= maxbufspace)
764		goto trytofreespace;
765
766	/* can we constitute a new buffer? */
767	if ((bp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]))) {
768		if (bp->b_qindex != QUEUE_EMPTY)
769			panic("getnewbuf: inconsistent EMPTY queue, qindex=%d",
770			    bp->b_qindex);
771		bp->b_flags |= B_BUSY;
772		bremfree(bp);
773		goto fillbuf;
774	}
775trytofreespace:
776	/*
777	 * We keep the file I/O from hogging metadata I/O
778	 * This is desirable because file data is cached in the
779	 * VM/Buffer cache even if a buffer is freed.
780	 */
781	if ((bp = TAILQ_FIRST(&bufqueues[QUEUE_AGE]))) {
782		if (bp->b_qindex != QUEUE_AGE)
783			panic("getnewbuf: inconsistent AGE queue, qindex=%d",
784			    bp->b_qindex);
785	} else if ((bp = TAILQ_FIRST(&bufqueues[QUEUE_LRU]))) {
786		if (bp->b_qindex != QUEUE_LRU)
787			panic("getnewbuf: inconsistent LRU queue, qindex=%d",
788			    bp->b_qindex);
789	}
790	if (!bp) {
791		/* wait for a free buffer of any kind */
792		needsbuffer = 1;
793		tsleep(&needsbuffer,
794			(PRIBIO + 1) | slpflag, "newbuf", slptimeo);
795		return (0);
796	}
797
798	/*
799	 * We are fairly aggressive about freeing VMIO buffers, but since
800	 * the buffering is intact without buffer headers, there is not
801	 * much loss.  We gain by maintaining non-VMIOed metadata in buffers.
802	 */
803	if ((bp->b_qindex == QUEUE_LRU) && (bp->b_usecount > 0)) {
804		if ((bp->b_flags & B_VMIO) == 0 ||
805			(vmiospace < maxvmiobufspace)) {
806			--bp->b_usecount;
807			TAILQ_REMOVE(&bufqueues[QUEUE_LRU], bp, b_freelist);
808			if (TAILQ_FIRST(&bufqueues[QUEUE_LRU]) != NULL) {
809				TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LRU], bp, b_freelist);
810				goto start;
811			}
812			TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LRU], bp, b_freelist);
813		}
814	}
815
816	/* if we are a delayed write, convert to an async write */
817	if ((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) {
818		nbyteswritten += vfs_bio_awrite(bp);
819		if (!slpflag && !slptimeo) {
820			return (0);
821		}
822		goto start;
823	}
824
825	if (bp->b_flags & B_WANTED) {
826		bp->b_flags &= ~B_WANTED;
827		wakeup(bp);
828	}
829	bremfree(bp);
830	bp->b_flags |= B_BUSY;
831
832	if (bp->b_flags & B_VMIO)
833		vfs_vmio_release(bp);
834
835	if (bp->b_vp)
836		brelvp(bp);
837
838fillbuf:
839	/* we are not free, nor do we contain interesting data */
840	if (bp->b_rcred != NOCRED) {
841		crfree(bp->b_rcred);
842		bp->b_rcred = NOCRED;
843	}
844	if (bp->b_wcred != NOCRED) {
845		crfree(bp->b_wcred);
846		bp->b_wcred = NOCRED;
847	}
848
849	LIST_REMOVE(bp, b_hash);
850	LIST_INSERT_HEAD(&invalhash, bp, b_hash);
851	if (bp->b_bufsize) {
852		allocbuf(bp, 0);
853	}
854	bp->b_flags = B_BUSY;
855	bp->b_dev = NODEV;
856	bp->b_vp = NULL;
857	bp->b_blkno = bp->b_lblkno = 0;
858	bp->b_iodone = 0;
859	bp->b_error = 0;
860	bp->b_resid = 0;
861	bp->b_bcount = 0;
862	bp->b_npages = 0;
863	bp->b_data = buffers_kva + (bp - buf) * MAXBSIZE;
864	bp->b_dirtyoff = bp->b_dirtyend = 0;
865	bp->b_validoff = bp->b_validend = 0;
866	bp->b_usecount = 4;
867	if (bufspace >= maxbufspace + nbyteswritten) {
868		bp->b_flags |= B_INVAL;
869		brelse(bp);
870		goto trytofreespace;
871	}
872	return (bp);
873}
874
875/*
876 * Check to see if a block is currently memory resident.
877 */
878struct buf *
879incore(struct vnode * vp, daddr_t blkno)
880{
881	struct buf *bp;
882
883	int s = splbio();
884	bp = gbincore(vp, blkno);
885	splx(s);
886	return (bp);
887}
888
889/*
890 * Returns true if no I/O is needed to access the
891 * associated VM object.  This is like incore except
892 * it also hunts around in the VM system for the data.
893 */
894
895int
896inmem(struct vnode * vp, daddr_t blkno)
897{
898	vm_object_t obj;
899	vm_offset_t toff, tinc;
900	vm_page_t m;
901	vm_ooffset_t off;
902
903	if (incore(vp, blkno))
904		return 1;
905	if (vp->v_mount == NULL)
906		return 0;
907	if ((vp->v_object == NULL) || (vp->v_flag & VVMIO) == 0)
908		return 0;
909
910	obj = vp->v_object;
911	tinc = PAGE_SIZE;
912	if (tinc > vp->v_mount->mnt_stat.f_iosize)
913		tinc = vp->v_mount->mnt_stat.f_iosize;
914	off = blkno * vp->v_mount->mnt_stat.f_iosize;
915
916	for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
917
918		m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
919		if (!m)
920			return 0;
921		if (vm_page_is_valid(m, (vm_offset_t) (toff + off), tinc) == 0)
922			return 0;
923	}
924	return 1;
925}
926
927/*
928 * now we set the dirty range for the buffer --
929 * for NFS -- if the file is mapped and pages have
930 * been written to, let it know.  We want the
931 * entire range of the buffer to be marked dirty if
932 * any of the pages have been written to for consistancy
933 * with the b_validoff, b_validend set in the nfs write
934 * code, and used by the nfs read code.
935 */
936static void
937vfs_setdirty(struct buf *bp) {
938	int i;
939	vm_object_t object;
940	vm_offset_t boffset, offset;
941	/*
942	 * We qualify the scan for modified pages on whether the
943	 * object has been flushed yet.  The OBJ_WRITEABLE flag
944	 * is not cleared simply by protecting pages off.
945	 */
946	if ((bp->b_flags & B_VMIO) &&
947		((object = bp->b_pages[0]->object)->flags & (OBJ_WRITEABLE|OBJ_CLEANING))) {
948		/*
949		 * test the pages to see if they have been modified directly
950		 * by users through the VM system.
951		 */
952		for (i = 0; i < bp->b_npages; i++)
953			vm_page_test_dirty(bp->b_pages[i]);
954
955		/*
956		 * scan forwards for the first page modified
957		 */
958		for (i = 0; i < bp->b_npages; i++) {
959			if (bp->b_pages[i]->dirty) {
960				break;
961			}
962		}
963		boffset = (i << PAGE_SHIFT);
964		if (boffset < bp->b_dirtyoff) {
965			bp->b_dirtyoff = boffset;
966		}
967
968		/*
969		 * scan backwards for the last page modified
970		 */
971		for (i = bp->b_npages - 1; i >= 0; --i) {
972			if (bp->b_pages[i]->dirty) {
973				break;
974			}
975		}
976		boffset = (i + 1);
977		offset = boffset + bp->b_pages[0]->pindex;
978		if (offset >= object->size)
979			boffset = object->size - bp->b_pages[0]->pindex;
980		if (bp->b_dirtyend < (boffset << PAGE_SHIFT))
981			bp->b_dirtyend = (boffset << PAGE_SHIFT);
982	}
983}
984
985/*
986 * Get a block given a specified block and offset into a file/device.
987 */
988struct buf *
989getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo)
990{
991	struct buf *bp;
992	int s;
993	struct bufhashhdr *bh;
994
995	s = splbio();
996loop:
997	if ((bp = gbincore(vp, blkno))) {
998		if (bp->b_flags & B_BUSY) {
999			bp->b_flags |= B_WANTED;
1000			if (bp->b_usecount < BUF_MAXUSE)
1001				++bp->b_usecount;
1002			if (!tsleep(bp,
1003				(PRIBIO + 1) | slpflag, "getblk", slptimeo))
1004				goto loop;
1005
1006			splx(s);
1007			return (struct buf *) NULL;
1008		}
1009		bp->b_flags |= B_BUSY | B_CACHE;
1010		bremfree(bp);
1011
1012		/*
1013		 * check for size inconsistancies (note that they shouldn't happen
1014		 * but do when filesystems don't handle the size changes correctly.)
1015		 * We are conservative on metadata and don't just extend the buffer
1016		 * but write and re-constitute it.
1017		 */
1018
1019		if (bp->b_bcount != size) {
1020			if (bp->b_flags & B_VMIO) {
1021				allocbuf(bp, size);
1022			} else {
1023				bp->b_flags |= B_NOCACHE;
1024				VOP_BWRITE(bp);
1025				goto loop;
1026			}
1027		}
1028
1029		if (bp->b_usecount < BUF_MAXUSE)
1030			++bp->b_usecount;
1031		splx(s);
1032		return (bp);
1033	} else {
1034		vm_object_t obj;
1035		int doingvmio;
1036
1037		if ((obj = vp->v_object) && (vp->v_flag & VVMIO)) {
1038			doingvmio = 1;
1039		} else {
1040			doingvmio = 0;
1041		}
1042		if ((bp = getnewbuf(slpflag, slptimeo, doingvmio)) == 0) {
1043			if (slpflag || slptimeo) {
1044				splx(s);
1045				return NULL;
1046			}
1047			goto loop;
1048		}
1049
1050		/*
1051		 * This code is used to make sure that a buffer is not
1052		 * created while the getnewbuf routine is blocked.
1053		 * Normally the vnode is locked so this isn't a problem.
1054		 * VBLK type I/O requests, however, don't lock the vnode.
1055		 */
1056		if (!VOP_ISLOCKED(vp) && gbincore(vp, blkno)) {
1057			bp->b_flags |= B_INVAL;
1058			brelse(bp);
1059			goto loop;
1060		}
1061
1062		/*
1063		 * Insert the buffer into the hash, so that it can
1064		 * be found by incore.
1065		 */
1066		bp->b_blkno = bp->b_lblkno = blkno;
1067		bgetvp(vp, bp);
1068		LIST_REMOVE(bp, b_hash);
1069		bh = BUFHASH(vp, blkno);
1070		LIST_INSERT_HEAD(bh, bp, b_hash);
1071
1072		if (doingvmio) {
1073			bp->b_flags |= (B_VMIO | B_CACHE);
1074#if defined(VFS_BIO_DEBUG)
1075			if (vp->v_type != VREG && vp->v_type != VBLK)
1076				printf("getblk: vmioing file type %d???\n", vp->v_type);
1077#endif
1078		} else {
1079			bp->b_flags &= ~B_VMIO;
1080		}
1081		splx(s);
1082
1083		allocbuf(bp, size);
1084#ifdef	PC98
1085		/*
1086		 * 1024byte/sector support
1087		 */
1088#define B_XXX2 0x8000000
1089		if (vp->v_flag & 0x10000) bp->b_flags |= B_XXX2;
1090#endif
1091		return (bp);
1092	}
1093}
1094
1095/*
1096 * Get an empty, disassociated buffer of given size.
1097 */
1098struct buf *
1099geteblk(int size)
1100{
1101	struct buf *bp;
1102	int s;
1103
1104	s = splbio();
1105	while ((bp = getnewbuf(0, 0, 0)) == 0);
1106	splx(s);
1107	allocbuf(bp, size);
1108	bp->b_flags |= B_INVAL;
1109	return (bp);
1110}
1111
1112
1113/*
1114 * This code constitutes the buffer memory from either anonymous system
1115 * memory (in the case of non-VMIO operations) or from an associated
1116 * VM object (in the case of VMIO operations).
1117 *
1118 * Note that this code is tricky, and has many complications to resolve
1119 * deadlock or inconsistant data situations.  Tread lightly!!!
1120 *
1121 * Modify the length of a buffer's underlying buffer storage without
1122 * destroying information (unless, of course the buffer is shrinking).
1123 */
1124int
1125allocbuf(struct buf * bp, int size)
1126{
1127
1128	int s;
1129	int newbsize, mbsize;
1130	int i;
1131
1132	if (!(bp->b_flags & B_BUSY))
1133		panic("allocbuf: buffer not busy");
1134
1135	if ((bp->b_flags & B_VMIO) == 0) {
1136		caddr_t origbuf;
1137		int origbufsize;
1138		/*
1139		 * Just get anonymous memory from the kernel
1140		 */
1141		mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
1142#if !defined(NO_B_MALLOC)
1143		if (bp->b_flags & B_MALLOC)
1144			newbsize = mbsize;
1145		else
1146#endif
1147			newbsize = round_page(size);
1148
1149		if (newbsize < bp->b_bufsize) {
1150#if !defined(NO_B_MALLOC)
1151			/*
1152			 * malloced buffers are not shrunk
1153			 */
1154			if (bp->b_flags & B_MALLOC) {
1155				if (newbsize) {
1156					bp->b_bcount = size;
1157				} else {
1158					free(bp->b_data, M_BIOBUF);
1159					bufspace -= bp->b_bufsize;
1160					bufmallocspace -= bp->b_bufsize;
1161					bp->b_data = (caddr_t) buffers_kva + (bp - buf) * MAXBSIZE;
1162					bp->b_bufsize = 0;
1163					bp->b_bcount = 0;
1164					bp->b_flags &= ~B_MALLOC;
1165				}
1166				return 1;
1167			}
1168#endif
1169			vm_hold_free_pages(
1170			    bp,
1171			    (vm_offset_t) bp->b_data + newbsize,
1172			    (vm_offset_t) bp->b_data + bp->b_bufsize);
1173		} else if (newbsize > bp->b_bufsize) {
1174#if !defined(NO_B_MALLOC)
1175			/*
1176			 * We only use malloced memory on the first allocation.
1177			 * and revert to page-allocated memory when the buffer grows.
1178			 */
1179			if ( (bufmallocspace < maxbufmallocspace) &&
1180				(bp->b_bufsize == 0) &&
1181				(mbsize <= PAGE_SIZE/2)) {
1182
1183				bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
1184				bp->b_bufsize = mbsize;
1185				bp->b_bcount = size;
1186				bp->b_flags |= B_MALLOC;
1187				bufspace += mbsize;
1188				bufmallocspace += mbsize;
1189				return 1;
1190			}
1191#endif
1192			origbuf = NULL;
1193			origbufsize = 0;
1194#if !defined(NO_B_MALLOC)
1195			/*
1196			 * If the buffer is growing on it's other-than-first allocation,
1197			 * then we revert to the page-allocation scheme.
1198			 */
1199			if (bp->b_flags & B_MALLOC) {
1200				origbuf = bp->b_data;
1201				origbufsize = bp->b_bufsize;
1202				bp->b_data = (caddr_t) buffers_kva + (bp - buf) * MAXBSIZE;
1203				bufspace -= bp->b_bufsize;
1204				bufmallocspace -= bp->b_bufsize;
1205				bp->b_bufsize = 0;
1206				bp->b_flags &= ~B_MALLOC;
1207				newbsize = round_page(newbsize);
1208			}
1209#endif
1210			vm_hold_load_pages(
1211			    bp,
1212			    (vm_offset_t) bp->b_data + bp->b_bufsize,
1213			    (vm_offset_t) bp->b_data + newbsize);
1214#if !defined(NO_B_MALLOC)
1215			if (origbuf) {
1216				bcopy(origbuf, bp->b_data, origbufsize);
1217				free(origbuf, M_BIOBUF);
1218			}
1219#endif
1220		}
1221	} else {
1222		vm_page_t m;
1223		int desiredpages;
1224
1225		newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
1226		desiredpages = (round_page(newbsize) >> PAGE_SHIFT);
1227
1228#if !defined(NO_B_MALLOC)
1229		if (bp->b_flags & B_MALLOC)
1230			panic("allocbuf: VMIO buffer can't be malloced");
1231#endif
1232
1233		if (newbsize < bp->b_bufsize) {
1234			if (desiredpages < bp->b_npages) {
1235				for (i = desiredpages; i < bp->b_npages; i++) {
1236					/*
1237					 * the page is not freed here -- it
1238					 * is the responsibility of vnode_pager_setsize
1239					 */
1240					m = bp->b_pages[i];
1241					s = splhigh();
1242					while ((m->flags & PG_BUSY) || (m->busy != 0)) {
1243						m->flags |= PG_WANTED;
1244						tsleep(m, PVM, "biodep", 0);
1245					}
1246					splx(s);
1247
1248					bp->b_pages[i] = NULL;
1249					vm_page_unwire(m);
1250				}
1251				pmap_qremove((vm_offset_t) trunc_page(bp->b_data) +
1252				    (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
1253				bp->b_npages = desiredpages;
1254			}
1255		} else if (newbsize > bp->b_bufsize) {
1256			vm_object_t obj;
1257			vm_offset_t tinc, toff;
1258			vm_ooffset_t off;
1259			vm_pindex_t objoff;
1260			int pageindex, curbpnpages;
1261			struct vnode *vp;
1262			int bsize;
1263
1264			vp = bp->b_vp;
1265
1266			if (vp->v_type == VBLK)
1267				bsize = DEV_BSIZE;
1268			else
1269				bsize = vp->v_mount->mnt_stat.f_iosize;
1270
1271			if (bp->b_npages < desiredpages) {
1272				obj = vp->v_object;
1273				tinc = PAGE_SIZE;
1274				if (tinc > bsize)
1275					tinc = bsize;
1276				off = (vm_ooffset_t) bp->b_lblkno * bsize;
1277		doretry:
1278				curbpnpages = bp->b_npages;
1279				bp->b_flags |= B_CACHE;
1280				for (toff = 0; toff < newbsize; toff += tinc) {
1281					int bytesinpage;
1282
1283					pageindex = toff >> PAGE_SHIFT;
1284					objoff = OFF_TO_IDX(off + toff);
1285					if (pageindex < curbpnpages) {
1286
1287						m = bp->b_pages[pageindex];
1288#ifdef VFS_BIO_DIAG
1289						if (m->pindex != objoff)
1290							panic("allocbuf: page changed offset??!!!?");
1291#endif
1292						bytesinpage = tinc;
1293						if (tinc > (newbsize - toff))
1294							bytesinpage = newbsize - toff;
1295						if ((bp->b_flags & B_CACHE) &&
1296							!vm_page_is_valid(m,
1297							(vm_offset_t) ((toff + off) & PAGE_MASK),
1298							bytesinpage)) {
1299							bp->b_flags &= ~B_CACHE;
1300						}
1301						continue;
1302					}
1303					m = vm_page_lookup(obj, objoff);
1304					if (!m) {
1305						m = vm_page_alloc(obj, objoff, VM_ALLOC_NORMAL);
1306						if (!m) {
1307							VM_WAIT;
1308							goto doretry;
1309						}
1310						/*
1311						 * Normally it is unwise to clear PG_BUSY without
1312						 * PAGE_WAKEUP -- but it is okay here, as there is
1313						 * no chance for blocking between here and vm_page_alloc
1314						 */
1315						m->flags &= ~PG_BUSY;
1316						vm_page_wire(m);
1317						bp->b_flags &= ~B_CACHE;
1318					} else if (m->flags & PG_BUSY) {
1319
1320						s = splhigh();
1321						m->flags |= PG_WANTED;
1322						tsleep(m, PVM, "pgtblk", 0);
1323						splx(s);
1324
1325						goto doretry;
1326					} else {
1327						if ((curproc != pageproc) &&
1328							((m->queue - m->pc) == PQ_CACHE) &&
1329						    ((cnt.v_free_count + cnt.v_cache_count) <
1330								(cnt.v_free_min + cnt.v_cache_min))) {
1331							pagedaemon_wakeup();
1332						}
1333						bytesinpage = tinc;
1334						if (tinc > (newbsize - toff))
1335							bytesinpage = newbsize - toff;
1336						if ((bp->b_flags & B_CACHE) &&
1337							!vm_page_is_valid(m,
1338							(vm_offset_t) ((toff + off) & PAGE_MASK),
1339							bytesinpage)) {
1340							bp->b_flags &= ~B_CACHE;
1341						}
1342						vm_page_wire(m);
1343					}
1344					bp->b_pages[pageindex] = m;
1345					curbpnpages = pageindex + 1;
1346				}
1347				bp->b_data = (caddr_t) trunc_page(bp->b_data);
1348				bp->b_npages = curbpnpages;
1349				pmap_qenter((vm_offset_t) bp->b_data,
1350					bp->b_pages, bp->b_npages);
1351				((vm_offset_t) bp->b_data) |= off & PAGE_MASK;
1352			}
1353		}
1354	}
1355	if (bp->b_flags & B_VMIO)
1356		vmiospace += bp->b_bufsize;
1357	bufspace += (newbsize - bp->b_bufsize);
1358	bp->b_bufsize = newbsize;
1359	bp->b_bcount = size;
1360	return 1;
1361}
1362
1363/*
1364 * Wait for buffer I/O completion, returning error status.
1365 */
1366int
1367biowait(register struct buf * bp)
1368{
1369	int s;
1370
1371	s = splbio();
1372	while ((bp->b_flags & B_DONE) == 0)
1373		tsleep(bp, PRIBIO, "biowait", 0);
1374	splx(s);
1375	if (bp->b_flags & B_EINTR) {
1376		bp->b_flags &= ~B_EINTR;
1377		return (EINTR);
1378	}
1379	if (bp->b_flags & B_ERROR) {
1380		return (bp->b_error ? bp->b_error : EIO);
1381	} else {
1382		return (0);
1383	}
1384}
1385
1386/*
1387 * Finish I/O on a buffer, calling an optional function.
1388 * This is usually called from interrupt level, so process blocking
1389 * is not *a good idea*.
1390 */
1391void
1392biodone(register struct buf * bp)
1393{
1394	int s;
1395
1396	s = splbio();
1397	if (!(bp->b_flags & B_BUSY))
1398		panic("biodone: buffer not busy");
1399
1400	if (bp->b_flags & B_DONE) {
1401		splx(s);
1402		printf("biodone: buffer already done\n");
1403		return;
1404	}
1405	bp->b_flags |= B_DONE;
1406
1407	if ((bp->b_flags & B_READ) == 0) {
1408		vwakeup(bp);
1409	}
1410#ifdef BOUNCE_BUFFERS
1411	if (bp->b_flags & B_BOUNCE)
1412		vm_bounce_free(bp);
1413#endif
1414
1415	/* call optional completion function if requested */
1416	if (bp->b_flags & B_CALL) {
1417		bp->b_flags &= ~B_CALL;
1418		(*bp->b_iodone) (bp);
1419		splx(s);
1420		return;
1421	}
1422	if (bp->b_flags & B_VMIO) {
1423		int i, resid;
1424		vm_ooffset_t foff;
1425		vm_page_t m;
1426		vm_object_t obj;
1427		int iosize;
1428		struct vnode *vp = bp->b_vp;
1429
1430		if (vp->v_type == VBLK)
1431			foff = (vm_ooffset_t) DEV_BSIZE * bp->b_lblkno;
1432		else
1433			foff = (vm_ooffset_t) vp->v_mount->mnt_stat.f_iosize * bp->b_lblkno;
1434		obj = vp->v_object;
1435		if (!obj) {
1436			panic("biodone: no object");
1437		}
1438#if defined(VFS_BIO_DEBUG)
1439		if (obj->paging_in_progress < bp->b_npages) {
1440			printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
1441			    obj->paging_in_progress, bp->b_npages);
1442		}
1443#endif
1444		iosize = bp->b_bufsize;
1445		for (i = 0; i < bp->b_npages; i++) {
1446			int bogusflag = 0;
1447			m = bp->b_pages[i];
1448			if (m == bogus_page) {
1449				bogusflag = 1;
1450				m = vm_page_lookup(obj, OFF_TO_IDX(foff));
1451				if (!m) {
1452#if defined(VFS_BIO_DEBUG)
1453					printf("biodone: page disappeared\n");
1454#endif
1455					--obj->paging_in_progress;
1456					continue;
1457				}
1458				bp->b_pages[i] = m;
1459				pmap_qenter(trunc_page(bp->b_data), bp->b_pages, bp->b_npages);
1460			}
1461#if defined(VFS_BIO_DEBUG)
1462			if (OFF_TO_IDX(foff) != m->pindex) {
1463				printf("biodone: foff(%d)/m->pindex(%d) mismatch\n", foff, m->pindex);
1464			}
1465#endif
1466			resid = IDX_TO_OFF(m->pindex + 1) - foff;
1467			if (resid > iosize)
1468				resid = iosize;
1469			/*
1470			 * In the write case, the valid and clean bits are
1471			 * already changed correctly, so we only need to do this
1472			 * here in the read case.
1473			 */
1474			if ((bp->b_flags & B_READ) && !bogusflag && resid > 0) {
1475				vm_page_set_validclean(m,
1476					(vm_offset_t) (foff & PAGE_MASK), resid);
1477			}
1478
1479			/*
1480			 * when debugging new filesystems or buffer I/O methods, this
1481			 * is the most common error that pops up.  if you see this, you
1482			 * have not set the page busy flag correctly!!!
1483			 */
1484			if (m->busy == 0) {
1485				printf("biodone: page busy < 0, "
1486				    "pindex: %d, foff: 0x(%x,%x), "
1487				    "resid: %d, index: %d\n",
1488				    (int) m->pindex, (int)(foff >> 32),
1489						(int) foff & 0xffffffff, resid, i);
1490				if (vp->v_type != VBLK)
1491					printf(" iosize: %ld, lblkno: %d, flags: 0x%lx, npages: %d\n",
1492					    bp->b_vp->v_mount->mnt_stat.f_iosize,
1493					    (int) bp->b_lblkno,
1494					    bp->b_flags, bp->b_npages);
1495				else
1496					printf(" VDEV, lblkno: %d, flags: 0x%lx, npages: %d\n",
1497					    (int) bp->b_lblkno,
1498					    bp->b_flags, bp->b_npages);
1499				printf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
1500				    m->valid, m->dirty, m->wire_count);
1501				panic("biodone: page busy < 0\n");
1502			}
1503			--m->busy;
1504			if ((m->busy == 0) && (m->flags & PG_WANTED)) {
1505				m->flags &= ~PG_WANTED;
1506				wakeup(m);
1507			}
1508			--obj->paging_in_progress;
1509			foff += resid;
1510			iosize -= resid;
1511		}
1512		if (obj && obj->paging_in_progress == 0 &&
1513		    (obj->flags & OBJ_PIPWNT)) {
1514			obj->flags &= ~OBJ_PIPWNT;
1515			wakeup(obj);
1516		}
1517	}
1518	/*
1519	 * For asynchronous completions, release the buffer now. The brelse
1520	 * checks for B_WANTED and will do the wakeup there if necessary - so
1521	 * no need to do a wakeup here in the async case.
1522	 */
1523
1524	if (bp->b_flags & B_ASYNC) {
1525		if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
1526			brelse(bp);
1527		else
1528			bqrelse(bp);
1529	} else {
1530		wakeup(bp);
1531	}
1532	splx(s);
1533}
1534
1535int
1536count_lock_queue()
1537{
1538	int count;
1539	struct buf *bp;
1540
1541	count = 0;
1542	for (bp = TAILQ_FIRST(&bufqueues[QUEUE_LOCKED]);
1543	    bp != NULL;
1544	    bp = TAILQ_NEXT(bp, b_freelist))
1545		count++;
1546	return (count);
1547}
1548
1549int vfs_update_interval = 30;
1550
1551static void
1552vfs_update()
1553{
1554	(void) spl0();		/* XXX redundant?  wrong place? */
1555	while (1) {
1556		tsleep(&vfs_update_wakeup, PUSER, "update",
1557		    hz * vfs_update_interval);
1558		vfs_update_wakeup = 0;
1559		sync(curproc, NULL, NULL);
1560	}
1561}
1562
1563static int
1564sysctl_kern_updateinterval SYSCTL_HANDLER_ARGS
1565{
1566	int error = sysctl_handle_int(oidp,
1567		oidp->oid_arg1, oidp->oid_arg2, req);
1568	if (!error)
1569		wakeup(&vfs_update_wakeup);
1570	return error;
1571}
1572
1573SYSCTL_PROC(_kern, KERN_UPDATEINTERVAL, update, CTLTYPE_INT|CTLFLAG_RW,
1574	&vfs_update_interval, 0, sysctl_kern_updateinterval, "I", "");
1575
1576
1577/*
1578 * This routine is called in lieu of iodone in the case of
1579 * incomplete I/O.  This keeps the busy status for pages
1580 * consistant.
1581 */
1582void
1583vfs_unbusy_pages(struct buf * bp)
1584{
1585	int i;
1586
1587	if (bp->b_flags & B_VMIO) {
1588		struct vnode *vp = bp->b_vp;
1589		vm_object_t obj = vp->v_object;
1590		vm_ooffset_t foff;
1591
1592		foff = (vm_ooffset_t) vp->v_mount->mnt_stat.f_iosize * bp->b_lblkno;
1593
1594		for (i = 0; i < bp->b_npages; i++) {
1595			vm_page_t m = bp->b_pages[i];
1596
1597			if (m == bogus_page) {
1598				m = vm_page_lookup(obj, OFF_TO_IDX(foff) + i);
1599				if (!m) {
1600					panic("vfs_unbusy_pages: page missing\n");
1601				}
1602				bp->b_pages[i] = m;
1603				pmap_qenter(trunc_page(bp->b_data), bp->b_pages, bp->b_npages);
1604			}
1605			--obj->paging_in_progress;
1606			--m->busy;
1607			if ((m->busy == 0) && (m->flags & PG_WANTED)) {
1608				m->flags &= ~PG_WANTED;
1609				wakeup(m);
1610			}
1611		}
1612		if (obj->paging_in_progress == 0 &&
1613		    (obj->flags & OBJ_PIPWNT)) {
1614			obj->flags &= ~OBJ_PIPWNT;
1615			wakeup(obj);
1616		}
1617	}
1618}
1619
1620/*
1621 * This routine is called before a device strategy routine.
1622 * It is used to tell the VM system that paging I/O is in
1623 * progress, and treat the pages associated with the buffer
1624 * almost as being PG_BUSY.  Also the object paging_in_progress
1625 * flag is handled to make sure that the object doesn't become
1626 * inconsistant.
1627 */
1628void
1629vfs_busy_pages(struct buf * bp, int clear_modify)
1630{
1631	int i;
1632
1633	if (bp->b_flags & B_VMIO) {
1634		vm_object_t obj = bp->b_vp->v_object;
1635		vm_ooffset_t foff;
1636		int iocount = bp->b_bufsize;
1637
1638		if (bp->b_vp->v_type == VBLK)
1639			foff = (vm_ooffset_t) DEV_BSIZE * bp->b_lblkno;
1640		else
1641			foff = (vm_ooffset_t) bp->b_vp->v_mount->mnt_stat.f_iosize * bp->b_lblkno;
1642		vfs_setdirty(bp);
1643		for (i = 0; i < bp->b_npages; i++) {
1644			vm_page_t m = bp->b_pages[i];
1645			int resid = IDX_TO_OFF(m->pindex + 1) - foff;
1646
1647			if (resid > iocount)
1648				resid = iocount;
1649			if ((bp->b_flags & B_CLUSTER) == 0) {
1650				obj->paging_in_progress++;
1651				m->busy++;
1652			}
1653			vm_page_protect(m, VM_PROT_NONE);
1654			if (clear_modify) {
1655				vm_page_set_validclean(m,
1656					(vm_offset_t) (foff & PAGE_MASK), resid);
1657			} else if (bp->b_bcount >= PAGE_SIZE) {
1658				if (m->valid && (bp->b_flags & B_CACHE) == 0) {
1659					bp->b_pages[i] = bogus_page;
1660					pmap_qenter(trunc_page(bp->b_data), bp->b_pages, bp->b_npages);
1661				}
1662			}
1663			foff += resid;
1664			iocount -= resid;
1665		}
1666	}
1667}
1668
1669/*
1670 * Tell the VM system that the pages associated with this buffer
1671 * are clean.  This is used for delayed writes where the data is
1672 * going to go to disk eventually without additional VM intevention.
1673 */
1674void
1675vfs_clean_pages(struct buf * bp)
1676{
1677	int i;
1678
1679	if (bp->b_flags & B_VMIO) {
1680		vm_ooffset_t foff;
1681		int iocount = bp->b_bufsize;
1682
1683		if (bp->b_vp->v_type == VBLK)
1684			foff = (vm_ooffset_t) DEV_BSIZE * bp->b_lblkno;
1685		else
1686			foff = (vm_ooffset_t) bp->b_vp->v_mount->mnt_stat.f_iosize * bp->b_lblkno;
1687
1688		for (i = 0; i < bp->b_npages; i++) {
1689			vm_page_t m = bp->b_pages[i];
1690			int resid = IDX_TO_OFF(m->pindex + 1) - foff;
1691
1692			if (resid > iocount)
1693				resid = iocount;
1694			if (resid > 0) {
1695				vm_page_set_validclean(m,
1696					((vm_offset_t) foff & PAGE_MASK), resid);
1697			}
1698			foff += resid;
1699			iocount -= resid;
1700		}
1701	}
1702}
1703
1704void
1705vfs_bio_clrbuf(struct buf *bp) {
1706	int i;
1707	if( bp->b_flags & B_VMIO) {
1708		if( (bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE)) {
1709			int mask;
1710			mask = 0;
1711			for(i=0;i<bp->b_bufsize;i+=DEV_BSIZE)
1712				mask |= (1 << (i/DEV_BSIZE));
1713			if( bp->b_pages[0]->valid != mask) {
1714				bzero(bp->b_data, bp->b_bufsize);
1715			}
1716			bp->b_pages[0]->valid = mask;
1717			bp->b_resid = 0;
1718			return;
1719		}
1720		for(i=0;i<bp->b_npages;i++) {
1721			if( bp->b_pages[i]->valid == VM_PAGE_BITS_ALL)
1722				continue;
1723			if( bp->b_pages[i]->valid == 0) {
1724				if ((bp->b_pages[i]->flags & PG_ZERO) == 0) {
1725					bzero(bp->b_data + (i << PAGE_SHIFT), PAGE_SIZE);
1726				}
1727			} else {
1728				int j;
1729				for(j=0;j<PAGE_SIZE/DEV_BSIZE;j++) {
1730					if( (bp->b_pages[i]->valid & (1<<j)) == 0)
1731						bzero(bp->b_data + (i << PAGE_SHIFT) + j * DEV_BSIZE, DEV_BSIZE);
1732				}
1733			}
1734			/* bp->b_pages[i]->valid = VM_PAGE_BITS_ALL; */
1735		}
1736		bp->b_resid = 0;
1737	} else {
1738		clrbuf(bp);
1739	}
1740}
1741
1742/*
1743 * vm_hold_load_pages and vm_hold_unload pages get pages into
1744 * a buffers address space.  The pages are anonymous and are
1745 * not associated with a file object.
1746 */
1747void
1748vm_hold_load_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
1749{
1750	vm_offset_t pg;
1751	vm_page_t p;
1752	int index;
1753
1754	to = round_page(to);
1755	from = round_page(from);
1756	index = (from - trunc_page(bp->b_data)) >> PAGE_SHIFT;
1757
1758	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
1759
1760tryagain:
1761
1762		p = vm_page_alloc(kernel_object, ((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
1763		    VM_ALLOC_NORMAL);
1764		if (!p) {
1765			VM_WAIT;
1766			goto tryagain;
1767		}
1768		vm_page_wire(p);
1769		pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
1770		bp->b_pages[index] = p;
1771		PAGE_WAKEUP(p);
1772	}
1773	bp->b_npages = to >> PAGE_SHIFT;
1774}
1775
1776void
1777vm_hold_free_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
1778{
1779	vm_offset_t pg;
1780	vm_page_t p;
1781	int index;
1782
1783	from = round_page(from);
1784	to = round_page(to);
1785	index = (from - trunc_page(bp->b_data)) >> PAGE_SHIFT;
1786
1787	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
1788		p = bp->b_pages[index];
1789		if (p && (index < bp->b_npages)) {
1790			if (p->busy) {
1791				printf("vm_hold_free_pages: blkno: %d, lblkno: %d\n",
1792					bp->b_blkno, bp->b_lblkno);
1793			}
1794			bp->b_pages[index] = NULL;
1795			pmap_kremove(pg);
1796			vm_page_unwire(p);
1797			vm_page_free(p);
1798		}
1799	}
1800	bp->b_npages = from >> PAGE_SHIFT;
1801}
1802