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