vfs_bio.c revision 31380
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.134 1997/11/07 08:53:04 phk 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 <vm/vm_map.h>
55#include <sys/buf.h>
56#include <sys/mount.h>
57#include <sys/malloc.h>
58#include <sys/resourcevar.h>
59
60static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
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_buf_set_valid(struct buf *bp, vm_ooffset_t foff,
80			      vm_offset_t off, vm_offset_t size,
81			      vm_page_t m);
82static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
83			       int pageno, vm_page_t m);
84static void vfs_clean_pages(struct buf * bp);
85static void vfs_setdirty(struct buf *bp);
86static void vfs_vmio_release(struct buf *bp);
87static void flushdirtybuffers(int slpflag, int slptimeo);
88
89int needsbuffer;
90
91/*
92 * Internal update daemon, process 3
93 *	The variable vfs_update_wakeup allows for internal syncs.
94 */
95int vfs_update_wakeup;
96
97
98/*
99 * buffers base kva
100 */
101
102/*
103 * bogus page -- for I/O to/from partially complete buffers
104 * this is a temporary solution to the problem, but it is not
105 * really that bad.  it would be better to split the buffer
106 * for input in the case of buffers partially already in memory,
107 * but the code is intricate enough already.
108 */
109vm_page_t bogus_page;
110static vm_offset_t bogus_offset;
111
112static int bufspace, maxbufspace, vmiospace, maxvmiobufspace,
113	bufmallocspace, maxbufmallocspace;
114int numdirtybuffers, lodirtybuffers, hidirtybuffers;
115static int numfreebuffers, lofreebuffers, hifreebuffers;
116
117SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD,
118	&numdirtybuffers, 0, "");
119SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW,
120	&lodirtybuffers, 0, "");
121SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW,
122	&hidirtybuffers, 0, "");
123SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD,
124	&numfreebuffers, 0, "");
125SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW,
126	&lofreebuffers, 0, "");
127SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW,
128	&hifreebuffers, 0, "");
129SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RW,
130	&maxbufspace, 0, "");
131SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD,
132	&bufspace, 0, "");
133SYSCTL_INT(_vfs, OID_AUTO, maxvmiobufspace, CTLFLAG_RW,
134	&maxvmiobufspace, 0, "");
135SYSCTL_INT(_vfs, OID_AUTO, vmiospace, CTLFLAG_RD,
136	&vmiospace, 0, "");
137SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW,
138	&maxbufmallocspace, 0, "");
139SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD,
140	&bufmallocspace, 0, "");
141
142static LIST_HEAD(bufhashhdr, buf) bufhashtbl[BUFHSZ], invalhash;
143static TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES];
144
145extern int vm_swap_size;
146
147#define BUF_MAXUSE 24
148
149#define VFS_BIO_NEED_ANY 1
150#define VFS_BIO_NEED_LOWLIMIT 2
151#define VFS_BIO_NEED_FREE 4
152
153/*
154 * Initialize buffer headers and related structures.
155 */
156void
157bufinit()
158{
159	struct buf *bp;
160	int i;
161
162	TAILQ_INIT(&bswlist);
163	LIST_INIT(&invalhash);
164
165	/* first, make a null hash table */
166	for (i = 0; i < BUFHSZ; i++)
167		LIST_INIT(&bufhashtbl[i]);
168
169	/* next, make a null set of free lists */
170	for (i = 0; i < BUFFER_QUEUES; i++)
171		TAILQ_INIT(&bufqueues[i]);
172
173	/* finally, initialize each buffer header and stick on empty q */
174	for (i = 0; i < nbuf; i++) {
175		bp = &buf[i];
176		bzero(bp, sizeof *bp);
177		bp->b_flags = B_INVAL;	/* we're just an empty header */
178		bp->b_dev = NODEV;
179		bp->b_rcred = NOCRED;
180		bp->b_wcred = NOCRED;
181		bp->b_qindex = QUEUE_EMPTY;
182		bp->b_vnbufs.le_next = NOLIST;
183		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
184		LIST_INSERT_HEAD(&invalhash, bp, b_hash);
185	}
186/*
187 * maxbufspace is currently calculated to support all filesystem blocks
188 * to be 8K.  If you happen to use a 16K filesystem, the size of the buffer
189 * cache is still the same as it would be for 8K filesystems.  This
190 * keeps the size of the buffer cache "in check" for big block filesystems.
191 */
192	maxbufspace = (nbuf + 8) * DFLTBSIZE;
193/*
194 * reserve 1/3 of the buffers for metadata (VDIR) which might not be VMIO'ed
195 */
196	maxvmiobufspace = 2 * maxbufspace / 3;
197/*
198 * Limit the amount of malloc memory since it is wired permanently into
199 * the kernel space.  Even though this is accounted for in the buffer
200 * allocation, we don't want the malloced region to grow uncontrolled.
201 * The malloc scheme improves memory utilization significantly on average
202 * (small) directories.
203 */
204	maxbufmallocspace = maxbufspace / 20;
205
206/*
207 * Remove the probability of deadlock conditions by limiting the
208 * number of dirty buffers.
209 */
210	hidirtybuffers = nbuf / 6 + 20;
211	lodirtybuffers = nbuf / 12 + 10;
212	numdirtybuffers = 0;
213	lofreebuffers = nbuf / 18 + 5;
214	hifreebuffers = 2 * lofreebuffers;
215	numfreebuffers = nbuf;
216
217	bogus_offset = kmem_alloc_pageable(kernel_map, PAGE_SIZE);
218	bogus_page = vm_page_alloc(kernel_object,
219			((bogus_offset - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
220			VM_ALLOC_NORMAL);
221
222}
223
224/*
225 * Free the kva allocation for a buffer
226 * Must be called only at splbio or higher,
227 *  as this is the only locking for buffer_map.
228 */
229static void
230bfreekva(struct buf * bp)
231{
232	if (bp->b_kvasize == 0)
233		return;
234
235	vm_map_delete(buffer_map,
236		(vm_offset_t) bp->b_kvabase,
237		(vm_offset_t) bp->b_kvabase + bp->b_kvasize);
238
239	bp->b_kvasize = 0;
240
241}
242
243/*
244 * remove the buffer from the appropriate free list
245 */
246void
247bremfree(struct buf * bp)
248{
249	int s = splbio();
250
251	if (bp->b_qindex != QUEUE_NONE) {
252		TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
253		bp->b_qindex = QUEUE_NONE;
254	} else {
255#if !defined(MAX_PERF)
256		panic("bremfree: removing a buffer when not on a queue");
257#endif
258	}
259	if ((bp->b_flags & B_INVAL) ||
260		(bp->b_flags & (B_DELWRI|B_LOCKED)) == 0)
261		--numfreebuffers;
262	splx(s);
263}
264
265/*
266 * Get a buffer with the specified data.  Look in the cache first.
267 */
268int
269bread(struct vnode * vp, daddr_t blkno, int size, struct ucred * cred,
270    struct buf ** bpp)
271{
272	struct buf *bp;
273
274	bp = getblk(vp, blkno, size, 0, 0);
275	*bpp = bp;
276
277	/* if not found in cache, do some I/O */
278	if ((bp->b_flags & B_CACHE) == 0) {
279		if (curproc != NULL)
280			curproc->p_stats->p_ru.ru_inblock++;
281		bp->b_flags |= B_READ;
282		bp->b_flags &= ~(B_DONE | B_ERROR | B_INVAL);
283		if (bp->b_rcred == NOCRED) {
284			if (cred != NOCRED)
285				crhold(cred);
286			bp->b_rcred = cred;
287		}
288		vfs_busy_pages(bp, 0);
289		VOP_STRATEGY(bp);
290		return (biowait(bp));
291	}
292	return (0);
293}
294
295/*
296 * Operates like bread, but also starts asynchronous I/O on
297 * read-ahead blocks.
298 */
299int
300breadn(struct vnode * vp, daddr_t blkno, int size,
301    daddr_t * rablkno, int *rabsize,
302    int cnt, struct ucred * cred, struct buf ** bpp)
303{
304	struct buf *bp, *rabp;
305	int i;
306	int rv = 0, readwait = 0;
307
308	*bpp = bp = getblk(vp, blkno, size, 0, 0);
309
310	/* if not found in cache, do some I/O */
311	if ((bp->b_flags & B_CACHE) == 0) {
312		if (curproc != NULL)
313			curproc->p_stats->p_ru.ru_inblock++;
314		bp->b_flags |= B_READ;
315		bp->b_flags &= ~(B_DONE | B_ERROR | B_INVAL);
316		if (bp->b_rcred == NOCRED) {
317			if (cred != NOCRED)
318				crhold(cred);
319			bp->b_rcred = cred;
320		}
321		vfs_busy_pages(bp, 0);
322		VOP_STRATEGY(bp);
323		++readwait;
324	}
325	for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
326		if (inmem(vp, *rablkno))
327			continue;
328		rabp = getblk(vp, *rablkno, *rabsize, 0, 0);
329
330		if ((rabp->b_flags & B_CACHE) == 0) {
331			if (curproc != NULL)
332				curproc->p_stats->p_ru.ru_inblock++;
333			rabp->b_flags |= B_READ | B_ASYNC;
334			rabp->b_flags &= ~(B_DONE | B_ERROR | B_INVAL);
335			if (rabp->b_rcred == NOCRED) {
336				if (cred != NOCRED)
337					crhold(cred);
338				rabp->b_rcred = cred;
339			}
340			vfs_busy_pages(rabp, 0);
341			VOP_STRATEGY(rabp);
342		} else {
343			brelse(rabp);
344		}
345	}
346
347	if (readwait) {
348		rv = biowait(bp);
349	}
350	return (rv);
351}
352
353/*
354 * Write, release buffer on completion.  (Done by iodone
355 * if async.)
356 */
357int
358bwrite(struct buf * bp)
359{
360	int oldflags = bp->b_flags;
361
362	if (bp->b_flags & B_INVAL) {
363		brelse(bp);
364		return (0);
365	}
366#if !defined(MAX_PERF)
367	if (!(bp->b_flags & B_BUSY))
368		panic("bwrite: buffer is not busy???");
369#endif
370
371	bp->b_flags &= ~(B_READ | B_DONE | B_ERROR | B_DELWRI);
372	bp->b_flags |= B_WRITEINPROG;
373
374	if ((oldflags & B_DELWRI) == B_DELWRI) {
375		--numdirtybuffers;
376		reassignbuf(bp, bp->b_vp);
377	}
378
379	bp->b_vp->v_numoutput++;
380	vfs_busy_pages(bp, 1);
381	if (curproc != NULL)
382		curproc->p_stats->p_ru.ru_oublock++;
383	VOP_STRATEGY(bp);
384
385	if ((oldflags & B_ASYNC) == 0) {
386		int rtval = biowait(bp);
387
388		if (oldflags & B_DELWRI) {
389			reassignbuf(bp, bp->b_vp);
390		}
391		brelse(bp);
392		return (rtval);
393	}
394	return (0);
395}
396
397void
398vfs_bio_need_satisfy(void) {
399	++numfreebuffers;
400	if (!needsbuffer)
401		return;
402	if (numdirtybuffers < lodirtybuffers) {
403		needsbuffer &= ~(VFS_BIO_NEED_ANY | VFS_BIO_NEED_LOWLIMIT);
404	} else {
405		needsbuffer &= ~VFS_BIO_NEED_ANY;
406	}
407	if (numfreebuffers >= hifreebuffers) {
408		needsbuffer &= ~VFS_BIO_NEED_FREE;
409	}
410	wakeup(&needsbuffer);
411}
412
413/*
414 * Delayed write. (Buffer is marked dirty).
415 */
416void
417bdwrite(struct buf * bp)
418{
419
420#if !defined(MAX_PERF)
421	if ((bp->b_flags & B_BUSY) == 0) {
422		panic("bdwrite: buffer is not busy");
423	}
424#endif
425
426	if (bp->b_flags & B_INVAL) {
427		brelse(bp);
428		return;
429	}
430	if (bp->b_flags & B_TAPE) {
431		bawrite(bp);
432		return;
433	}
434	bp->b_flags &= ~(B_READ|B_RELBUF);
435	if ((bp->b_flags & B_DELWRI) == 0) {
436		bp->b_flags |= B_DONE | B_DELWRI;
437		reassignbuf(bp, bp->b_vp);
438		++numdirtybuffers;
439	}
440
441	/*
442	 * This bmap keeps the system from needing to do the bmap later,
443	 * perhaps when the system is attempting to do a sync.  Since it
444	 * is likely that the indirect block -- or whatever other datastructure
445	 * that the filesystem needs is still in memory now, it is a good
446	 * thing to do this.  Note also, that if the pageout daemon is
447	 * requesting a sync -- there might not be enough memory to do
448	 * the bmap then...  So, this is important to do.
449	 */
450	if (bp->b_lblkno == bp->b_blkno) {
451		VOP_BMAP(bp->b_vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
452	}
453
454	/*
455	 * Set the *dirty* buffer range based upon the VM system dirty pages.
456	 */
457	vfs_setdirty(bp);
458
459	/*
460	 * We need to do this here to satisfy the vnode_pager and the
461	 * pageout daemon, so that it thinks that the pages have been
462	 * "cleaned".  Note that since the pages are in a delayed write
463	 * buffer -- the VFS layer "will" see that the pages get written
464	 * out on the next sync, or perhaps the cluster will be completed.
465	 */
466	vfs_clean_pages(bp);
467	bqrelse(bp);
468
469	if (numdirtybuffers >= hidirtybuffers)
470		flushdirtybuffers(0, 0);
471
472	return;
473}
474
475/*
476 * Asynchronous write.
477 * Start output on a buffer, but do not wait for it to complete.
478 * The buffer is released when the output completes.
479 */
480void
481bawrite(struct buf * bp)
482{
483	bp->b_flags |= B_ASYNC;
484	(void) VOP_BWRITE(bp);
485}
486
487/*
488 * Ordered write.
489 * Start output on a buffer, but only wait for it to complete if the
490 * output device cannot guarantee ordering in some other way.  Devices
491 * that can perform asynchronous ordered writes will set the B_ASYNC
492 * flag in their strategy routine.
493 * The buffer is released when the output completes.
494 */
495int
496bowrite(struct buf * bp)
497{
498	/*
499	 * XXX Add in B_ASYNC once the SCSI
500	 *     layer can deal with ordered
501	 *     writes properly.
502	 */
503	bp->b_flags |= B_ORDERED;
504	return (VOP_BWRITE(bp));
505}
506
507/*
508 * Release a buffer.
509 */
510void
511brelse(struct buf * bp)
512{
513	int s;
514
515	if (bp->b_flags & B_CLUSTER) {
516		relpbuf(bp);
517		return;
518	}
519	/* anyone need a "free" block? */
520	s = splbio();
521
522	/* anyone need this block? */
523	if (bp->b_flags & B_WANTED) {
524		bp->b_flags &= ~(B_WANTED | B_AGE);
525		wakeup(bp);
526	}
527
528	if (bp->b_flags & B_LOCKED)
529		bp->b_flags &= ~B_ERROR;
530
531	if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR)) ||
532	    (bp->b_bufsize <= 0)) {
533		bp->b_flags |= B_INVAL;
534		if (bp->b_flags & B_DELWRI)
535			--numdirtybuffers;
536		bp->b_flags &= ~(B_DELWRI | B_CACHE);
537		if (((bp->b_flags & B_VMIO) == 0) && bp->b_vp) {
538			if (bp->b_bufsize)
539				allocbuf(bp, 0);
540			brelvp(bp);
541		}
542	}
543
544	/*
545	 * VMIO buffer rundown.  It is not very necessary to keep a VMIO buffer
546	 * constituted, so the B_INVAL flag is used to *invalidate* the buffer,
547	 * but the VM object is kept around.  The B_NOCACHE flag is used to
548	 * invalidate the pages in the VM object.
549	 *
550	 * If the buffer is a partially filled NFS buffer, keep it
551	 * since invalidating it now will lose informatio.  The valid
552	 * flags in the vm_pages have only DEV_BSIZE resolution but
553	 * the b_validoff, b_validend fields have byte resolution.
554	 * This can avoid unnecessary re-reads of the buffer.
555	 * XXX this seems to cause performance problems.
556	 */
557	if ((bp->b_flags & B_VMIO)
558	    && !(bp->b_vp->v_tag == VT_NFS &&
559		 bp->b_vp->v_type != VBLK &&
560		 (bp->b_flags & B_DELWRI) != 0)
561#ifdef notdef
562	    && (bp->b_vp->v_tag != VT_NFS
563		|| bp->b_vp->v_type == VBLK
564		|| (bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR))
565		|| bp->b_validend == 0
566		|| (bp->b_validoff == 0
567		    && bp->b_validend == bp->b_bufsize))
568#endif
569	    ) {
570		vm_ooffset_t foff;
571		vm_object_t obj;
572		int i, resid;
573		vm_page_t m;
574		struct vnode *vp;
575		int iototal = bp->b_bufsize;
576
577		vp = bp->b_vp;
578
579#if !defined(MAX_PERF)
580		if (!vp)
581			panic("brelse: missing vp");
582#endif
583
584		if (bp->b_npages) {
585			vm_pindex_t poff;
586			obj = (vm_object_t) vp->v_object;
587			if (vp->v_type == VBLK)
588				foff = ((vm_ooffset_t) bp->b_lblkno) << DEV_BSHIFT;
589			else
590				foff = (vm_ooffset_t) vp->v_mount->mnt_stat.f_iosize * bp->b_lblkno;
591			poff = OFF_TO_IDX(foff);
592			for (i = 0; i < bp->b_npages; i++) {
593				m = bp->b_pages[i];
594				if (m == bogus_page) {
595					m = vm_page_lookup(obj, poff + i);
596#if !defined(MAX_PERF)
597					if (!m) {
598						panic("brelse: page missing\n");
599					}
600#endif
601					bp->b_pages[i] = m;
602					pmap_qenter(trunc_page(bp->b_data),
603						bp->b_pages, bp->b_npages);
604				}
605				resid = IDX_TO_OFF(m->pindex+1) - foff;
606				if (resid > iototal)
607					resid = iototal;
608				if (resid > 0) {
609					/*
610					 * Don't invalidate the page if the local machine has already
611					 * modified it.  This is the lesser of two evils, and should
612					 * be fixed.
613					 */
614					if (bp->b_flags & (B_NOCACHE | B_ERROR)) {
615						vm_page_test_dirty(m);
616						if (m->dirty == 0) {
617							vm_page_set_invalid(m, (vm_offset_t) foff, resid);
618							if (m->valid == 0)
619								vm_page_protect(m, VM_PROT_NONE);
620						}
621					}
622					if (resid >= PAGE_SIZE) {
623						if ((m->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL) {
624							bp->b_flags |= B_INVAL;
625						}
626					} else {
627						if (!vm_page_is_valid(m,
628							(((vm_offset_t) bp->b_data) & PAGE_MASK), resid)) {
629							bp->b_flags |= B_INVAL;
630						}
631					}
632				}
633				foff += resid;
634				iototal -= resid;
635			}
636		}
637		if (bp->b_flags & (B_INVAL | B_RELBUF))
638			vfs_vmio_release(bp);
639	}
640#if !defined(MAX_PERF)
641	if (bp->b_qindex != QUEUE_NONE)
642		panic("brelse: free buffer onto another queue???");
643#endif
644
645	/* enqueue */
646	/* buffers with no memory */
647	if (bp->b_bufsize == 0) {
648		bp->b_flags |= B_INVAL;
649		bp->b_qindex = QUEUE_EMPTY;
650		TAILQ_INSERT_HEAD(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
651		LIST_REMOVE(bp, b_hash);
652		LIST_INSERT_HEAD(&invalhash, bp, b_hash);
653		bp->b_dev = NODEV;
654
655	/* buffers with junk contents */
656	} else if (bp->b_flags & (B_ERROR | B_INVAL | B_NOCACHE | B_RELBUF)) {
657		bp->b_flags |= B_INVAL;
658		bp->b_qindex = QUEUE_AGE;
659		TAILQ_INSERT_HEAD(&bufqueues[QUEUE_AGE], bp, b_freelist);
660		LIST_REMOVE(bp, b_hash);
661		LIST_INSERT_HEAD(&invalhash, bp, b_hash);
662		bp->b_dev = NODEV;
663
664	/* buffers that are locked */
665	} else if (bp->b_flags & B_LOCKED) {
666		bp->b_qindex = QUEUE_LOCKED;
667		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
668
669	/* buffers with stale but valid contents */
670	} else if (bp->b_flags & B_AGE) {
671		bp->b_qindex = QUEUE_AGE;
672		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_AGE], bp, b_freelist);
673
674	/* buffers with valid and quite potentially reuseable contents */
675	} else {
676		bp->b_qindex = QUEUE_LRU;
677		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LRU], bp, b_freelist);
678	}
679
680	if ((bp->b_flags & B_INVAL) ||
681		(bp->b_flags & (B_LOCKED|B_DELWRI)) == 0) {
682		if (bp->b_flags & B_DELWRI) {
683			--numdirtybuffers;
684			bp->b_flags &= ~B_DELWRI;
685		}
686		vfs_bio_need_satisfy();
687	}
688
689	/* unlock */
690	bp->b_flags &= ~(B_ORDERED | B_WANTED | B_BUSY |
691				B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
692	splx(s);
693}
694
695/*
696 * Release a buffer.
697 */
698void
699bqrelse(struct buf * bp)
700{
701	int s;
702
703	s = splbio();
704
705	/* anyone need this block? */
706	if (bp->b_flags & B_WANTED) {
707		bp->b_flags &= ~(B_WANTED | B_AGE);
708		wakeup(bp);
709	}
710
711#if !defined(MAX_PERF)
712	if (bp->b_qindex != QUEUE_NONE)
713		panic("bqrelse: free buffer onto another queue???");
714#endif
715
716	if (bp->b_flags & B_LOCKED) {
717		bp->b_flags &= ~B_ERROR;
718		bp->b_qindex = QUEUE_LOCKED;
719		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
720		/* buffers with stale but valid contents */
721	} else {
722		bp->b_qindex = QUEUE_LRU;
723		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LRU], bp, b_freelist);
724	}
725
726	if ((bp->b_flags & (B_LOCKED|B_DELWRI)) == 0) {
727		vfs_bio_need_satisfy();
728	}
729
730	/* unlock */
731	bp->b_flags &= ~(B_ORDERED | B_WANTED | B_BUSY |
732		B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
733	splx(s);
734}
735
736static void
737vfs_vmio_release(bp)
738	struct buf *bp;
739{
740	int i;
741	vm_page_t m;
742
743	for (i = 0; i < bp->b_npages; i++) {
744		m = bp->b_pages[i];
745		bp->b_pages[i] = NULL;
746		vm_page_unwire(m);
747		/*
748		 * We don't mess with busy pages, it is
749		 * the responsibility of the process that
750		 * busied the pages to deal with them.
751		 */
752		if ((m->flags & PG_BUSY) || (m->busy != 0))
753			continue;
754
755		if (m->wire_count == 0) {
756
757			if (m->flags & PG_WANTED) {
758				m->flags &= ~PG_WANTED;
759				wakeup(m);
760			}
761
762			/*
763			 * If this is an async free -- we cannot place
764			 * pages onto the cache queue.  If it is an
765			 * async free, then we don't modify any queues.
766			 * This is probably in error (for perf reasons),
767			 * and we will eventually need to build
768			 * a more complete infrastructure to support I/O
769			 * rundown.
770			 */
771			if ((bp->b_flags & B_ASYNC) == 0) {
772
773			/*
774			 * In the case of sync buffer frees, we can do pretty much
775			 * anything to any of the memory queues.  Specifically,
776			 * the cache queue is okay to be modified.
777			 */
778				if (m->valid) {
779					if(m->dirty == 0)
780						vm_page_test_dirty(m);
781					/*
782					 * this keeps pressure off of the process memory
783					 */
784					if (m->dirty == 0 && m->hold_count == 0)
785						vm_page_cache(m);
786					else
787						vm_page_deactivate(m);
788				} else if (m->hold_count == 0) {
789					vm_page_protect(m, VM_PROT_NONE);
790					vm_page_free(m);
791				}
792			} else {
793				/*
794				 * If async, then at least we clear the
795				 * act_count.
796				 */
797				m->act_count = 0;
798			}
799		}
800	}
801	bufspace -= bp->b_bufsize;
802	vmiospace -= bp->b_bufsize;
803	pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
804	bp->b_npages = 0;
805	bp->b_bufsize = 0;
806	bp->b_flags &= ~B_VMIO;
807	if (bp->b_vp)
808		brelvp(bp);
809}
810
811/*
812 * Check to see if a block is currently memory resident.
813 */
814struct buf *
815gbincore(struct vnode * vp, daddr_t blkno)
816{
817	struct buf *bp;
818	struct bufhashhdr *bh;
819
820	bh = BUFHASH(vp, blkno);
821	bp = bh->lh_first;
822
823	/* Search hash chain */
824	while (bp != NULL) {
825		/* hit */
826		if (bp->b_vp == vp && bp->b_lblkno == blkno &&
827		    (bp->b_flags & B_INVAL) == 0) {
828			break;
829		}
830		bp = bp->b_hash.le_next;
831	}
832	return (bp);
833}
834
835/*
836 * this routine implements clustered async writes for
837 * clearing out B_DELWRI buffers...  This is much better
838 * than the old way of writing only one buffer at a time.
839 */
840int
841vfs_bio_awrite(struct buf * bp)
842{
843	int i;
844	daddr_t lblkno = bp->b_lblkno;
845	struct vnode *vp = bp->b_vp;
846	int s;
847	int ncl;
848	struct buf *bpa;
849	int nwritten;
850
851	s = splbio();
852	/*
853	 * right now we support clustered writing only to regular files
854	 */
855	if ((vp->v_type == VREG) &&
856	    (vp->v_mount != 0) && /* Only on nodes that have the size info */
857	    (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
858		int size;
859		int maxcl;
860
861		size = vp->v_mount->mnt_stat.f_iosize;
862		maxcl = MAXPHYS / size;
863
864		for (i = 1; i < maxcl; i++) {
865			if ((bpa = gbincore(vp, lblkno + i)) &&
866			    ((bpa->b_flags & (B_BUSY | B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
867			    (B_DELWRI | B_CLUSTEROK)) &&
868			    (bpa->b_bufsize == size)) {
869				if ((bpa->b_blkno == bpa->b_lblkno) ||
870				    (bpa->b_blkno != bp->b_blkno + ((i * size) >> DEV_BSHIFT)))
871					break;
872			} else {
873				break;
874			}
875		}
876		ncl = i;
877		/*
878		 * this is a possible cluster write
879		 */
880		if (ncl != 1) {
881			nwritten = cluster_wbuild(vp, size, lblkno, ncl);
882			splx(s);
883			return nwritten;
884		}
885	}
886	bremfree(bp);
887	splx(s);
888	/*
889	 * default (old) behavior, writing out only one block
890	 */
891	bp->b_flags |= B_BUSY | B_ASYNC;
892	nwritten = bp->b_bufsize;
893	(void) VOP_BWRITE(bp);
894	return nwritten;
895}
896
897
898/*
899 * Find a buffer header which is available for use.
900 */
901static struct buf *
902getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int size, int maxsize)
903{
904	struct buf *bp;
905	int nbyteswritten = 0;
906	vm_offset_t addr;
907	static int writerecursion = 0;
908
909start:
910	if (bufspace >= maxbufspace)
911		goto trytofreespace;
912
913	/* can we constitute a new buffer? */
914	if ((bp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]))) {
915#if !defined(MAX_PERF)
916		if (bp->b_qindex != QUEUE_EMPTY)
917			panic("getnewbuf: inconsistent EMPTY queue, qindex=%d",
918			    bp->b_qindex);
919#endif
920		bp->b_flags |= B_BUSY;
921		bremfree(bp);
922		goto fillbuf;
923	}
924trytofreespace:
925	/*
926	 * We keep the file I/O from hogging metadata I/O
927	 * This is desirable because file data is cached in the
928	 * VM/Buffer cache even if a buffer is freed.
929	 */
930	if ((bp = TAILQ_FIRST(&bufqueues[QUEUE_AGE]))) {
931#if !defined(MAX_PERF)
932		if (bp->b_qindex != QUEUE_AGE)
933			panic("getnewbuf: inconsistent AGE queue, qindex=%d",
934			    bp->b_qindex);
935#endif
936	} else if ((bp = TAILQ_FIRST(&bufqueues[QUEUE_LRU]))) {
937#if !defined(MAX_PERF)
938		if (bp->b_qindex != QUEUE_LRU)
939			panic("getnewbuf: inconsistent LRU queue, qindex=%d",
940			    bp->b_qindex);
941#endif
942	}
943	if (!bp) {
944		/* wait for a free buffer of any kind */
945		needsbuffer |= VFS_BIO_NEED_ANY;
946		do
947			tsleep(&needsbuffer, (PRIBIO + 1) | slpflag, "newbuf",
948			    slptimeo);
949		while (needsbuffer & VFS_BIO_NEED_ANY);
950		return (0);
951	}
952
953#if defined(DIAGNOSTIC)
954	if (bp->b_flags & B_BUSY) {
955		panic("getnewbuf: busy buffer on free list\n");
956	}
957#endif
958
959	/*
960	 * We are fairly aggressive about freeing VMIO buffers, but since
961	 * the buffering is intact without buffer headers, there is not
962	 * much loss.  We gain by maintaining non-VMIOed metadata in buffers.
963	 */
964	if ((bp->b_qindex == QUEUE_LRU) && (bp->b_usecount > 0)) {
965		if ((bp->b_flags & B_VMIO) == 0 ||
966			(vmiospace < maxvmiobufspace)) {
967			--bp->b_usecount;
968			TAILQ_REMOVE(&bufqueues[QUEUE_LRU], bp, b_freelist);
969			if (TAILQ_FIRST(&bufqueues[QUEUE_LRU]) != NULL) {
970				TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LRU], bp, b_freelist);
971				goto start;
972			}
973			TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LRU], bp, b_freelist);
974		}
975	}
976
977
978	/* if we are a delayed write, convert to an async write */
979	if ((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) {
980
981		if (writerecursion > 0) {
982			bp = TAILQ_FIRST(&bufqueues[QUEUE_AGE]);
983			while (bp) {
984				if ((bp->b_flags & B_DELWRI) == 0)
985					break;
986				bp = TAILQ_NEXT(bp, b_freelist);
987			}
988			if (bp == NULL) {
989				bp = TAILQ_FIRST(&bufqueues[QUEUE_LRU]);
990				while (bp) {
991					if ((bp->b_flags & B_DELWRI) == 0)
992						break;
993					bp = TAILQ_NEXT(bp, b_freelist);
994				}
995			}
996			if (bp == NULL)
997				panic("getnewbuf: cannot get buffer, infinite recursion failure");
998		} else {
999			++writerecursion;
1000			nbyteswritten += vfs_bio_awrite(bp);
1001			--writerecursion;
1002			if (!slpflag && !slptimeo) {
1003				return (0);
1004			}
1005			goto start;
1006		}
1007	}
1008
1009	if (bp->b_flags & B_WANTED) {
1010		bp->b_flags &= ~B_WANTED;
1011		wakeup(bp);
1012	}
1013	bremfree(bp);
1014	bp->b_flags |= B_BUSY;
1015
1016	if (bp->b_flags & B_VMIO) {
1017		bp->b_flags &= ~B_ASYNC;
1018		vfs_vmio_release(bp);
1019	}
1020
1021	if (bp->b_vp)
1022		brelvp(bp);
1023
1024fillbuf:
1025	/* we are not free, nor do we contain interesting data */
1026	if (bp->b_rcred != NOCRED) {
1027		crfree(bp->b_rcred);
1028		bp->b_rcred = NOCRED;
1029	}
1030	if (bp->b_wcred != NOCRED) {
1031		crfree(bp->b_wcred);
1032		bp->b_wcred = NOCRED;
1033	}
1034
1035	LIST_REMOVE(bp, b_hash);
1036	LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1037	if (bp->b_bufsize) {
1038		allocbuf(bp, 0);
1039	}
1040	bp->b_flags = B_BUSY;
1041	bp->b_dev = NODEV;
1042	bp->b_vp = NULL;
1043	bp->b_blkno = bp->b_lblkno = 0;
1044	bp->b_iodone = 0;
1045	bp->b_error = 0;
1046	bp->b_resid = 0;
1047	bp->b_bcount = 0;
1048	bp->b_npages = 0;
1049	bp->b_dirtyoff = bp->b_dirtyend = 0;
1050	bp->b_validoff = bp->b_validend = 0;
1051	bp->b_usecount = 4;
1052
1053	maxsize = (maxsize + PAGE_MASK) & ~PAGE_MASK;
1054
1055	/*
1056	 * we assume that buffer_map is not at address 0
1057	 */
1058	addr = 0;
1059	if (maxsize != bp->b_kvasize) {
1060		bfreekva(bp);
1061
1062		/*
1063		 * See if we have buffer kva space
1064		 */
1065		if (vm_map_findspace(buffer_map,
1066			vm_map_min(buffer_map), maxsize, &addr)) {
1067			bp->b_flags |= B_INVAL;
1068			brelse(bp);
1069			goto trytofreespace;
1070		}
1071	}
1072
1073	/*
1074	 * See if we are below are allocated minimum
1075	 */
1076	if (bufspace >= (maxbufspace + nbyteswritten)) {
1077		bp->b_flags |= B_INVAL;
1078		brelse(bp);
1079		goto trytofreespace;
1080	}
1081
1082	/*
1083	 * create a map entry for the buffer -- in essence
1084	 * reserving the kva space.
1085	 */
1086	if (addr) {
1087		vm_map_insert(buffer_map, NULL, 0,
1088			addr, addr + maxsize,
1089			VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
1090
1091		bp->b_kvabase = (caddr_t) addr;
1092		bp->b_kvasize = maxsize;
1093	}
1094	bp->b_data = bp->b_kvabase;
1095
1096	return (bp);
1097}
1098
1099static void
1100waitfreebuffers(int slpflag, int slptimeo) {
1101	while (numfreebuffers < hifreebuffers) {
1102		flushdirtybuffers(slpflag, slptimeo);
1103		if (numfreebuffers < hifreebuffers)
1104			break;
1105		needsbuffer |= VFS_BIO_NEED_FREE;
1106		if (tsleep(&needsbuffer, PRIBIO|slpflag, "biofre", slptimeo))
1107			break;
1108	}
1109}
1110
1111static void
1112flushdirtybuffers(int slpflag, int slptimeo) {
1113	int s;
1114	static pid_t flushing = 0;
1115
1116	s = splbio();
1117
1118	if (flushing) {
1119		if (flushing == curproc->p_pid) {
1120			splx(s);
1121			return;
1122		}
1123		while (flushing) {
1124			if (tsleep(&flushing, PRIBIO|slpflag, "biofls", slptimeo)) {
1125				splx(s);
1126				return;
1127			}
1128		}
1129	}
1130	flushing = curproc->p_pid;
1131
1132	while (numdirtybuffers > lodirtybuffers) {
1133		struct buf *bp;
1134		needsbuffer |= VFS_BIO_NEED_LOWLIMIT;
1135		bp = TAILQ_FIRST(&bufqueues[QUEUE_AGE]);
1136		if (bp == NULL)
1137			bp = TAILQ_FIRST(&bufqueues[QUEUE_LRU]);
1138
1139		while (bp && ((bp->b_flags & B_DELWRI) == 0)) {
1140			bp = TAILQ_NEXT(bp, b_freelist);
1141		}
1142
1143		if (bp) {
1144			splx(s);
1145			vfs_bio_awrite(bp);
1146			s = splbio();
1147			continue;
1148		}
1149		break;
1150	}
1151
1152	flushing = 0;
1153	wakeup(&flushing);
1154	splx(s);
1155}
1156
1157/*
1158 * Check to see if a block is currently memory resident.
1159 */
1160struct buf *
1161incore(struct vnode * vp, daddr_t blkno)
1162{
1163	struct buf *bp;
1164
1165	int s = splbio();
1166	bp = gbincore(vp, blkno);
1167	splx(s);
1168	return (bp);
1169}
1170
1171/*
1172 * Returns true if no I/O is needed to access the
1173 * associated VM object.  This is like incore except
1174 * it also hunts around in the VM system for the data.
1175 */
1176
1177int
1178inmem(struct vnode * vp, daddr_t blkno)
1179{
1180	vm_object_t obj;
1181	vm_offset_t toff, tinc;
1182	vm_page_t m;
1183	vm_ooffset_t off;
1184
1185	if (incore(vp, blkno))
1186		return 1;
1187	if (vp->v_mount == NULL)
1188		return 0;
1189	if ((vp->v_object == NULL) || (vp->v_flag & VVMIO) == 0)
1190		return 0;
1191
1192	obj = vp->v_object;
1193	tinc = PAGE_SIZE;
1194	if (tinc > vp->v_mount->mnt_stat.f_iosize)
1195		tinc = vp->v_mount->mnt_stat.f_iosize;
1196	off = blkno * vp->v_mount->mnt_stat.f_iosize;
1197
1198	for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
1199
1200		m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
1201		if (!m)
1202			return 0;
1203		if (vm_page_is_valid(m, (vm_offset_t) (toff + off), tinc) == 0)
1204			return 0;
1205	}
1206	return 1;
1207}
1208
1209/*
1210 * now we set the dirty range for the buffer --
1211 * for NFS -- if the file is mapped and pages have
1212 * been written to, let it know.  We want the
1213 * entire range of the buffer to be marked dirty if
1214 * any of the pages have been written to for consistancy
1215 * with the b_validoff, b_validend set in the nfs write
1216 * code, and used by the nfs read code.
1217 */
1218static void
1219vfs_setdirty(struct buf *bp) {
1220	int i;
1221	vm_object_t object;
1222	vm_offset_t boffset, offset;
1223	/*
1224	 * We qualify the scan for modified pages on whether the
1225	 * object has been flushed yet.  The OBJ_WRITEABLE flag
1226	 * is not cleared simply by protecting pages off.
1227	 */
1228	if ((bp->b_flags & B_VMIO) &&
1229		((object = bp->b_pages[0]->object)->flags & (OBJ_WRITEABLE|OBJ_CLEANING))) {
1230		/*
1231		 * test the pages to see if they have been modified directly
1232		 * by users through the VM system.
1233		 */
1234		for (i = 0; i < bp->b_npages; i++)
1235			vm_page_test_dirty(bp->b_pages[i]);
1236
1237		/*
1238		 * scan forwards for the first page modified
1239		 */
1240		for (i = 0; i < bp->b_npages; i++) {
1241			if (bp->b_pages[i]->dirty) {
1242				break;
1243			}
1244		}
1245		boffset = (i << PAGE_SHIFT);
1246		if (boffset < bp->b_dirtyoff) {
1247			bp->b_dirtyoff = boffset;
1248		}
1249
1250		/*
1251		 * scan backwards for the last page modified
1252		 */
1253		for (i = bp->b_npages - 1; i >= 0; --i) {
1254			if (bp->b_pages[i]->dirty) {
1255				break;
1256			}
1257		}
1258		boffset = (i + 1);
1259		offset = boffset + bp->b_pages[0]->pindex;
1260		if (offset >= object->size)
1261			boffset = object->size - bp->b_pages[0]->pindex;
1262		if (bp->b_dirtyend < (boffset << PAGE_SHIFT))
1263			bp->b_dirtyend = (boffset << PAGE_SHIFT);
1264	}
1265}
1266
1267/*
1268 * Get a block given a specified block and offset into a file/device.
1269 */
1270struct buf *
1271getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo)
1272{
1273	struct buf *bp;
1274	int s;
1275	struct bufhashhdr *bh;
1276	int maxsize;
1277
1278	if (vp->v_mount) {
1279		maxsize = vp->v_mount->mnt_stat.f_iosize;
1280		/*
1281		 * This happens on mount points.
1282		 */
1283		if (maxsize < size)
1284			maxsize = size;
1285	} else {
1286		maxsize = size;
1287	}
1288
1289#if !defined(MAX_PERF)
1290	if (size > MAXBSIZE)
1291		panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
1292#endif
1293
1294	s = splbio();
1295loop:
1296	if (numfreebuffers < lofreebuffers) {
1297		waitfreebuffers(slpflag, slptimeo);
1298	}
1299
1300	if ((bp = gbincore(vp, blkno))) {
1301		if (bp->b_flags & B_BUSY) {
1302			bp->b_flags |= B_WANTED;
1303			if (bp->b_usecount < BUF_MAXUSE)
1304				++bp->b_usecount;
1305			if (!tsleep(bp,
1306				(PRIBIO + 1) | slpflag, "getblk", slptimeo))
1307				goto loop;
1308
1309			splx(s);
1310			return (struct buf *) NULL;
1311		}
1312		bp->b_flags |= B_BUSY | B_CACHE;
1313		bremfree(bp);
1314
1315		/*
1316		 * check for size inconsistancies (note that they shouldn't
1317		 * happen but do when filesystems don't handle the size changes
1318		 * correctly.) We are conservative on metadata and don't just
1319		 * extend the buffer but write and re-constitute it.
1320		 */
1321
1322		if (bp->b_bcount != size) {
1323			if ((bp->b_flags & B_VMIO) && (size <= bp->b_kvasize)) {
1324				allocbuf(bp, size);
1325			} else {
1326				bp->b_flags |= B_NOCACHE;
1327				VOP_BWRITE(bp);
1328				goto loop;
1329			}
1330		}
1331
1332		if (bp->b_usecount < BUF_MAXUSE)
1333			++bp->b_usecount;
1334		splx(s);
1335		return (bp);
1336	} else {
1337		vm_object_t obj;
1338
1339		if ((bp = getnewbuf(vp, slpflag, slptimeo, size, maxsize)) == 0) {
1340			if (slpflag || slptimeo) {
1341				splx(s);
1342				return NULL;
1343			}
1344			goto loop;
1345		}
1346
1347		/*
1348		 * This code is used to make sure that a buffer is not
1349		 * created while the getnewbuf routine is blocked.
1350		 * Normally the vnode is locked so this isn't a problem.
1351		 * VBLK type I/O requests, however, don't lock the vnode.
1352		 */
1353		if (!VOP_ISLOCKED(vp) && gbincore(vp, blkno)) {
1354			bp->b_flags |= B_INVAL;
1355			brelse(bp);
1356			goto loop;
1357		}
1358
1359		/*
1360		 * Insert the buffer into the hash, so that it can
1361		 * be found by incore.
1362		 */
1363		bp->b_blkno = bp->b_lblkno = blkno;
1364		bgetvp(vp, bp);
1365		LIST_REMOVE(bp, b_hash);
1366		bh = BUFHASH(vp, blkno);
1367		LIST_INSERT_HEAD(bh, bp, b_hash);
1368
1369		if ((obj = vp->v_object) && (vp->v_flag & VVMIO)) {
1370			bp->b_flags |= (B_VMIO | B_CACHE);
1371#if defined(VFS_BIO_DEBUG)
1372			if (vp->v_type != VREG && vp->v_type != VBLK)
1373				printf("getblk: vmioing file type %d???\n", vp->v_type);
1374#endif
1375		} else {
1376			bp->b_flags &= ~B_VMIO;
1377		}
1378		splx(s);
1379
1380		allocbuf(bp, size);
1381#ifdef	PC98
1382		/*
1383		 * 1024byte/sector support
1384		 */
1385#define B_XXX2 0x8000000
1386		if (vp->v_flag & 0x10000) bp->b_flags |= B_XXX2;
1387#endif
1388		return (bp);
1389	}
1390}
1391
1392/*
1393 * Get an empty, disassociated buffer of given size.
1394 */
1395struct buf *
1396geteblk(int size)
1397{
1398	struct buf *bp;
1399	int s;
1400
1401	s = splbio();
1402	while ((bp = getnewbuf(0, 0, 0, size, MAXBSIZE)) == 0);
1403	splx(s);
1404	allocbuf(bp, size);
1405	bp->b_flags |= B_INVAL;
1406	return (bp);
1407}
1408
1409
1410/*
1411 * This code constitutes the buffer memory from either anonymous system
1412 * memory (in the case of non-VMIO operations) or from an associated
1413 * VM object (in the case of VMIO operations).
1414 *
1415 * Note that this code is tricky, and has many complications to resolve
1416 * deadlock or inconsistant data situations.  Tread lightly!!!
1417 *
1418 * Modify the length of a buffer's underlying buffer storage without
1419 * destroying information (unless, of course the buffer is shrinking).
1420 */
1421int
1422allocbuf(struct buf * bp, int size)
1423{
1424
1425	int s;
1426	int newbsize, mbsize;
1427	int i;
1428
1429#if !defined(MAX_PERF)
1430	if (!(bp->b_flags & B_BUSY))
1431		panic("allocbuf: buffer not busy");
1432
1433	if (bp->b_kvasize < size)
1434		panic("allocbuf: buffer too small");
1435#endif
1436
1437	if ((bp->b_flags & B_VMIO) == 0) {
1438		caddr_t origbuf;
1439		int origbufsize;
1440		/*
1441		 * Just get anonymous memory from the kernel
1442		 */
1443		mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
1444#if !defined(NO_B_MALLOC)
1445		if (bp->b_flags & B_MALLOC)
1446			newbsize = mbsize;
1447		else
1448#endif
1449			newbsize = round_page(size);
1450
1451		if (newbsize < bp->b_bufsize) {
1452#if !defined(NO_B_MALLOC)
1453			/*
1454			 * malloced buffers are not shrunk
1455			 */
1456			if (bp->b_flags & B_MALLOC) {
1457				if (newbsize) {
1458					bp->b_bcount = size;
1459				} else {
1460					free(bp->b_data, M_BIOBUF);
1461					bufspace -= bp->b_bufsize;
1462					bufmallocspace -= bp->b_bufsize;
1463					bp->b_data = bp->b_kvabase;
1464					bp->b_bufsize = 0;
1465					bp->b_bcount = 0;
1466					bp->b_flags &= ~B_MALLOC;
1467				}
1468				return 1;
1469			}
1470#endif
1471			vm_hold_free_pages(
1472			    bp,
1473			    (vm_offset_t) bp->b_data + newbsize,
1474			    (vm_offset_t) bp->b_data + bp->b_bufsize);
1475		} else if (newbsize > bp->b_bufsize) {
1476#if !defined(NO_B_MALLOC)
1477			/*
1478			 * We only use malloced memory on the first allocation.
1479			 * and revert to page-allocated memory when the buffer grows.
1480			 */
1481			if ( (bufmallocspace < maxbufmallocspace) &&
1482				(bp->b_bufsize == 0) &&
1483				(mbsize <= PAGE_SIZE/2)) {
1484
1485				bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
1486				bp->b_bufsize = mbsize;
1487				bp->b_bcount = size;
1488				bp->b_flags |= B_MALLOC;
1489				bufspace += mbsize;
1490				bufmallocspace += mbsize;
1491				return 1;
1492			}
1493#endif
1494			origbuf = NULL;
1495			origbufsize = 0;
1496#if !defined(NO_B_MALLOC)
1497			/*
1498			 * If the buffer is growing on it's other-than-first allocation,
1499			 * then we revert to the page-allocation scheme.
1500			 */
1501			if (bp->b_flags & B_MALLOC) {
1502				origbuf = bp->b_data;
1503				origbufsize = bp->b_bufsize;
1504				bp->b_data = bp->b_kvabase;
1505				bufspace -= bp->b_bufsize;
1506				bufmallocspace -= bp->b_bufsize;
1507				bp->b_bufsize = 0;
1508				bp->b_flags &= ~B_MALLOC;
1509				newbsize = round_page(newbsize);
1510			}
1511#endif
1512			vm_hold_load_pages(
1513			    bp,
1514			    (vm_offset_t) bp->b_data + bp->b_bufsize,
1515			    (vm_offset_t) bp->b_data + newbsize);
1516#if !defined(NO_B_MALLOC)
1517			if (origbuf) {
1518				bcopy(origbuf, bp->b_data, origbufsize);
1519				free(origbuf, M_BIOBUF);
1520			}
1521#endif
1522		}
1523	} else {
1524		vm_page_t m;
1525		int desiredpages;
1526
1527		newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
1528		desiredpages = (round_page(newbsize) >> PAGE_SHIFT);
1529
1530#if !defined(NO_B_MALLOC)
1531		if (bp->b_flags & B_MALLOC)
1532			panic("allocbuf: VMIO buffer can't be malloced");
1533#endif
1534
1535		if (newbsize < bp->b_bufsize) {
1536			if (desiredpages < bp->b_npages) {
1537				for (i = desiredpages; i < bp->b_npages; i++) {
1538					/*
1539					 * the page is not freed here -- it
1540					 * is the responsibility of vnode_pager_setsize
1541					 */
1542					m = bp->b_pages[i];
1543#if defined(DIAGNOSTIC)
1544					if (m == bogus_page)
1545						panic("allocbuf: bogus page found");
1546#endif
1547					s = splvm();
1548					while ((m->flags & PG_BUSY) || (m->busy != 0)) {
1549						m->flags |= PG_WANTED;
1550						tsleep(m, PVM, "biodep", 0);
1551					}
1552					splx(s);
1553
1554					bp->b_pages[i] = NULL;
1555					vm_page_unwire(m);
1556				}
1557				pmap_qremove((vm_offset_t) trunc_page(bp->b_data) +
1558				    (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
1559				bp->b_npages = desiredpages;
1560			}
1561		} else if (newbsize > bp->b_bufsize) {
1562			vm_object_t obj;
1563			vm_offset_t tinc, toff;
1564			vm_ooffset_t off;
1565			vm_pindex_t objoff;
1566			int pageindex, curbpnpages;
1567			struct vnode *vp;
1568			int bsize;
1569
1570			vp = bp->b_vp;
1571
1572			if (vp->v_type == VBLK)
1573				bsize = DEV_BSIZE;
1574			else
1575				bsize = vp->v_mount->mnt_stat.f_iosize;
1576
1577			if (bp->b_npages < desiredpages) {
1578				obj = vp->v_object;
1579				tinc = PAGE_SIZE;
1580				if (tinc > bsize)
1581					tinc = bsize;
1582				off = (vm_ooffset_t) bp->b_lblkno * bsize;
1583				curbpnpages = bp->b_npages;
1584		doretry:
1585				bp->b_flags |= B_CACHE;
1586				bp->b_validoff = bp->b_validend = 0;
1587				for (toff = 0; toff < newbsize; toff += tinc) {
1588					int bytesinpage;
1589
1590					pageindex = toff >> PAGE_SHIFT;
1591					objoff = OFF_TO_IDX(off + toff);
1592					if (pageindex < curbpnpages) {
1593
1594						m = bp->b_pages[pageindex];
1595#ifdef VFS_BIO_DIAG
1596						if (m->pindex != objoff)
1597							panic("allocbuf: page changed offset??!!!?");
1598#endif
1599						bytesinpage = tinc;
1600						if (tinc > (newbsize - toff))
1601							bytesinpage = newbsize - toff;
1602						if (bp->b_flags & B_CACHE)
1603							vfs_buf_set_valid(bp, off, toff, bytesinpage, m);
1604						continue;
1605					}
1606					m = vm_page_lookup(obj, objoff);
1607					if (!m) {
1608						m = vm_page_alloc(obj, objoff, VM_ALLOC_NORMAL);
1609						if (!m) {
1610							VM_WAIT;
1611							goto doretry;
1612						}
1613						/*
1614						 * Normally it is unwise to clear PG_BUSY without
1615						 * PAGE_WAKEUP -- but it is okay here, as there is
1616						 * no chance for blocking between here and vm_page_alloc
1617						 */
1618						m->flags &= ~PG_BUSY;
1619						vm_page_wire(m);
1620						bp->b_flags &= ~B_CACHE;
1621					} else if (m->flags & PG_BUSY) {
1622						s = splvm();
1623						if (m->flags & PG_BUSY) {
1624							m->flags |= PG_WANTED;
1625							tsleep(m, PVM, "pgtblk", 0);
1626						}
1627						splx(s);
1628						goto doretry;
1629					} else {
1630						if ((curproc != pageproc) &&
1631							((m->queue - m->pc) == PQ_CACHE) &&
1632						    ((cnt.v_free_count + cnt.v_cache_count) <
1633								(cnt.v_free_min + cnt.v_cache_min))) {
1634							pagedaemon_wakeup();
1635						}
1636						bytesinpage = tinc;
1637						if (tinc > (newbsize - toff))
1638							bytesinpage = newbsize - toff;
1639						if (bp->b_flags & B_CACHE)
1640							vfs_buf_set_valid(bp, off, toff, bytesinpage, m);
1641						vm_page_wire(m);
1642					}
1643					bp->b_pages[pageindex] = m;
1644					curbpnpages = pageindex + 1;
1645				}
1646				if (vp->v_tag == VT_NFS &&
1647				    vp->v_type != VBLK) {
1648					if (bp->b_dirtyend > 0) {
1649						bp->b_validoff = min(bp->b_validoff, bp->b_dirtyoff);
1650						bp->b_validend = max(bp->b_validend, bp->b_dirtyend);
1651					}
1652					if (bp->b_validend == 0)
1653						bp->b_flags &= ~B_CACHE;
1654				}
1655				bp->b_data = (caddr_t) trunc_page(bp->b_data);
1656				bp->b_npages = curbpnpages;
1657				pmap_qenter((vm_offset_t) bp->b_data,
1658					bp->b_pages, bp->b_npages);
1659				((vm_offset_t) bp->b_data) |= off & PAGE_MASK;
1660			}
1661		}
1662	}
1663	if (bp->b_flags & B_VMIO)
1664		vmiospace += (newbsize - bp->b_bufsize);
1665	bufspace += (newbsize - bp->b_bufsize);
1666	bp->b_bufsize = newbsize;
1667	bp->b_bcount = size;
1668	return 1;
1669}
1670
1671/*
1672 * Wait for buffer I/O completion, returning error status.
1673 */
1674int
1675biowait(register struct buf * bp)
1676{
1677	int s;
1678
1679	s = splbio();
1680	while ((bp->b_flags & B_DONE) == 0)
1681#if defined(NO_SCHEDULE_MODS)
1682		tsleep(bp, PRIBIO, "biowait", 0);
1683#else
1684		tsleep(bp, curproc->p_usrpri, "biowait", 0);
1685#endif
1686	splx(s);
1687	if (bp->b_flags & B_EINTR) {
1688		bp->b_flags &= ~B_EINTR;
1689		return (EINTR);
1690	}
1691	if (bp->b_flags & B_ERROR) {
1692		return (bp->b_error ? bp->b_error : EIO);
1693	} else {
1694		return (0);
1695	}
1696}
1697
1698/*
1699 * Finish I/O on a buffer, calling an optional function.
1700 * This is usually called from interrupt level, so process blocking
1701 * is not *a good idea*.
1702 */
1703void
1704biodone(register struct buf * bp)
1705{
1706	int s;
1707
1708	s = splbio();
1709
1710#if !defined(MAX_PERF)
1711	if (!(bp->b_flags & B_BUSY))
1712		panic("biodone: buffer not busy");
1713#endif
1714
1715	if (bp->b_flags & B_DONE) {
1716		splx(s);
1717#if !defined(MAX_PERF)
1718		printf("biodone: buffer already done\n");
1719#endif
1720		return;
1721	}
1722	bp->b_flags |= B_DONE;
1723
1724	if ((bp->b_flags & B_READ) == 0) {
1725		vwakeup(bp);
1726	}
1727#ifdef BOUNCE_BUFFERS
1728	if (bp->b_flags & B_BOUNCE)
1729		vm_bounce_free(bp);
1730#endif
1731
1732	/* call optional completion function if requested */
1733	if (bp->b_flags & B_CALL) {
1734		bp->b_flags &= ~B_CALL;
1735		(*bp->b_iodone) (bp);
1736		splx(s);
1737		return;
1738	}
1739	if (bp->b_flags & B_VMIO) {
1740		int i, resid;
1741		vm_ooffset_t foff;
1742		vm_page_t m;
1743		vm_object_t obj;
1744		int iosize;
1745		struct vnode *vp = bp->b_vp;
1746
1747		obj = vp->v_object;
1748
1749#if defined(VFS_BIO_DEBUG)
1750		if (vp->v_usecount == 0) {
1751			panic("biodone: zero vnode ref count");
1752		}
1753
1754		if (vp->v_object == NULL) {
1755			panic("biodone: missing VM object");
1756		}
1757
1758		if ((vp->v_flag & VVMIO) == 0) {
1759			panic("biodone: vnode is not setup for merged cache");
1760		}
1761#endif
1762
1763		if (vp->v_type == VBLK)
1764			foff = (vm_ooffset_t) DEV_BSIZE * bp->b_lblkno;
1765		else
1766			foff = (vm_ooffset_t) vp->v_mount->mnt_stat.f_iosize * bp->b_lblkno;
1767#if !defined(MAX_PERF)
1768		if (!obj) {
1769			panic("biodone: no object");
1770		}
1771#endif
1772#if defined(VFS_BIO_DEBUG)
1773		if (obj->paging_in_progress < bp->b_npages) {
1774			printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
1775			    obj->paging_in_progress, bp->b_npages);
1776		}
1777#endif
1778		iosize = bp->b_bufsize;
1779		for (i = 0; i < bp->b_npages; i++) {
1780			int bogusflag = 0;
1781			m = bp->b_pages[i];
1782			if (m == bogus_page) {
1783				bogusflag = 1;
1784				m = vm_page_lookup(obj, OFF_TO_IDX(foff));
1785				if (!m) {
1786#if defined(VFS_BIO_DEBUG)
1787					printf("biodone: page disappeared\n");
1788#endif
1789					--obj->paging_in_progress;
1790					continue;
1791				}
1792				bp->b_pages[i] = m;
1793				pmap_qenter(trunc_page(bp->b_data), bp->b_pages, bp->b_npages);
1794			}
1795#if defined(VFS_BIO_DEBUG)
1796			if (OFF_TO_IDX(foff) != m->pindex) {
1797				printf("biodone: foff(%d)/m->pindex(%d) mismatch\n", foff, m->pindex);
1798			}
1799#endif
1800			resid = IDX_TO_OFF(m->pindex + 1) - foff;
1801			if (resid > iosize)
1802				resid = iosize;
1803			/*
1804			 * In the write case, the valid and clean bits are
1805			 * already changed correctly, so we only need to do this
1806			 * here in the read case.
1807			 */
1808			if ((bp->b_flags & B_READ) && !bogusflag && resid > 0) {
1809				vfs_page_set_valid(bp, foff, i, m);
1810			}
1811
1812			/*
1813			 * when debugging new filesystems or buffer I/O methods, this
1814			 * is the most common error that pops up.  if you see this, you
1815			 * have not set the page busy flag correctly!!!
1816			 */
1817			if (m->busy == 0) {
1818#if !defined(MAX_PERF)
1819				printf("biodone: page busy < 0, "
1820				    "pindex: %d, foff: 0x(%x,%x), "
1821				    "resid: %d, index: %d\n",
1822				    (int) m->pindex, (int)(foff >> 32),
1823						(int) foff & 0xffffffff, resid, i);
1824#endif
1825				if (vp->v_type != VBLK)
1826#if !defined(MAX_PERF)
1827					printf(" iosize: %ld, lblkno: %d, flags: 0x%lx, npages: %d\n",
1828					    bp->b_vp->v_mount->mnt_stat.f_iosize,
1829					    (int) bp->b_lblkno,
1830					    bp->b_flags, bp->b_npages);
1831				else
1832					printf(" VDEV, lblkno: %d, flags: 0x%lx, npages: %d\n",
1833					    (int) bp->b_lblkno,
1834					    bp->b_flags, bp->b_npages);
1835				printf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
1836				    m->valid, m->dirty, m->wire_count);
1837#endif
1838				panic("biodone: page busy < 0\n");
1839			}
1840			--m->busy;
1841			if ((m->busy == 0) && (m->flags & PG_WANTED)) {
1842				m->flags &= ~PG_WANTED;
1843				wakeup(m);
1844			}
1845			--obj->paging_in_progress;
1846			foff += resid;
1847			iosize -= resid;
1848		}
1849		if (obj && obj->paging_in_progress == 0 &&
1850		    (obj->flags & OBJ_PIPWNT)) {
1851			obj->flags &= ~OBJ_PIPWNT;
1852			wakeup(obj);
1853		}
1854	}
1855	/*
1856	 * For asynchronous completions, release the buffer now. The brelse
1857	 * checks for B_WANTED and will do the wakeup there if necessary - so
1858	 * no need to do a wakeup here in the async case.
1859	 */
1860
1861	if (bp->b_flags & B_ASYNC) {
1862		if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
1863			brelse(bp);
1864		else
1865			bqrelse(bp);
1866	} else {
1867		bp->b_flags &= ~B_WANTED;
1868		wakeup(bp);
1869	}
1870	splx(s);
1871}
1872
1873int
1874count_lock_queue()
1875{
1876	int count;
1877	struct buf *bp;
1878
1879	count = 0;
1880	for (bp = TAILQ_FIRST(&bufqueues[QUEUE_LOCKED]);
1881	    bp != NULL;
1882	    bp = TAILQ_NEXT(bp, b_freelist))
1883		count++;
1884	return (count);
1885}
1886
1887int vfs_update_interval = 30;
1888
1889static void
1890vfs_update()
1891{
1892	while (1) {
1893		tsleep(&vfs_update_wakeup, PUSER, "update",
1894		    hz * vfs_update_interval);
1895		vfs_update_wakeup = 0;
1896		sync(curproc, NULL);
1897	}
1898}
1899
1900static int
1901sysctl_kern_updateinterval SYSCTL_HANDLER_ARGS
1902{
1903	int error = sysctl_handle_int(oidp,
1904		oidp->oid_arg1, oidp->oid_arg2, req);
1905	if (!error)
1906		wakeup(&vfs_update_wakeup);
1907	return error;
1908}
1909
1910SYSCTL_PROC(_kern, KERN_UPDATEINTERVAL, update, CTLTYPE_INT|CTLFLAG_RW,
1911	&vfs_update_interval, 0, sysctl_kern_updateinterval, "I", "");
1912
1913
1914/*
1915 * This routine is called in lieu of iodone in the case of
1916 * incomplete I/O.  This keeps the busy status for pages
1917 * consistant.
1918 */
1919void
1920vfs_unbusy_pages(struct buf * bp)
1921{
1922	int i;
1923
1924	if (bp->b_flags & B_VMIO) {
1925		struct vnode *vp = bp->b_vp;
1926		vm_object_t obj = vp->v_object;
1927		vm_ooffset_t foff;
1928
1929		foff = (vm_ooffset_t) vp->v_mount->mnt_stat.f_iosize * bp->b_lblkno;
1930
1931		for (i = 0; i < bp->b_npages; i++) {
1932			vm_page_t m = bp->b_pages[i];
1933
1934			if (m == bogus_page) {
1935				m = vm_page_lookup(obj, OFF_TO_IDX(foff) + i);
1936#if !defined(MAX_PERF)
1937				if (!m) {
1938					panic("vfs_unbusy_pages: page missing\n");
1939				}
1940#endif
1941				bp->b_pages[i] = m;
1942				pmap_qenter(trunc_page(bp->b_data), bp->b_pages, bp->b_npages);
1943			}
1944			--obj->paging_in_progress;
1945			--m->busy;
1946			if ((m->busy == 0) && (m->flags & PG_WANTED)) {
1947				m->flags &= ~PG_WANTED;
1948				wakeup(m);
1949			}
1950		}
1951		if (obj->paging_in_progress == 0 &&
1952		    (obj->flags & OBJ_PIPWNT)) {
1953			obj->flags &= ~OBJ_PIPWNT;
1954			wakeup(obj);
1955		}
1956	}
1957}
1958
1959/*
1960 * Set NFS' b_validoff and b_validend fields from the valid bits
1961 * of a page.  If the consumer is not NFS, and the page is not
1962 * valid for the entire range, clear the B_CACHE flag to force
1963 * the consumer to re-read the page.
1964 */
1965static void
1966vfs_buf_set_valid(struct buf *bp,
1967		  vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
1968		  vm_page_t m)
1969{
1970	if (bp->b_vp->v_tag == VT_NFS && bp->b_vp->v_type != VBLK) {
1971		vm_offset_t svalid, evalid;
1972		int validbits = m->valid;
1973
1974		/*
1975		 * This only bothers with the first valid range in the
1976		 * page.
1977		 */
1978		svalid = off;
1979		while (validbits && !(validbits & 1)) {
1980			svalid += DEV_BSIZE;
1981			validbits >>= 1;
1982		}
1983		evalid = svalid;
1984		while (validbits & 1) {
1985			evalid += DEV_BSIZE;
1986			validbits >>= 1;
1987		}
1988		/*
1989		 * Make sure this range is contiguous with the range
1990		 * built up from previous pages.  If not, then we will
1991		 * just use the range from the previous pages.
1992		 */
1993		if (svalid == bp->b_validend) {
1994			bp->b_validoff = min(bp->b_validoff, svalid);
1995			bp->b_validend = max(bp->b_validend, evalid);
1996		}
1997	} else if (!vm_page_is_valid(m,
1998				     (vm_offset_t) ((foff + off) & PAGE_MASK),
1999				     size)) {
2000		bp->b_flags &= ~B_CACHE;
2001	}
2002}
2003
2004/*
2005 * Set the valid bits in a page, taking care of the b_validoff,
2006 * b_validend fields which NFS uses to optimise small reads.  Off is
2007 * the offset within the file and pageno is the page index within the buf.
2008 */
2009static void
2010vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
2011{
2012	struct vnode *vp = bp->b_vp;
2013	vm_ooffset_t soff, eoff;
2014
2015	soff = off;
2016	eoff = off + min(PAGE_SIZE, bp->b_bufsize);
2017	vm_page_set_invalid(m,
2018			    (vm_offset_t) (soff & PAGE_MASK),
2019			    (vm_offset_t) (eoff - soff));
2020	if (vp->v_tag == VT_NFS && vp->v_type != VBLK) {
2021		vm_ooffset_t sv, ev;
2022		off = off - pageno * PAGE_SIZE;
2023		sv = off + ((bp->b_validoff + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1));
2024		ev = off + (bp->b_validend & ~(DEV_BSIZE - 1));
2025		soff = max(sv, soff);
2026		eoff = min(ev, eoff);
2027	}
2028	if (eoff > soff)
2029		vm_page_set_validclean(m,
2030				       (vm_offset_t) (soff & PAGE_MASK),
2031				       (vm_offset_t) (eoff - soff));
2032}
2033
2034/*
2035 * This routine is called before a device strategy routine.
2036 * It is used to tell the VM system that paging I/O is in
2037 * progress, and treat the pages associated with the buffer
2038 * almost as being PG_BUSY.  Also the object paging_in_progress
2039 * flag is handled to make sure that the object doesn't become
2040 * inconsistant.
2041 */
2042void
2043vfs_busy_pages(struct buf * bp, int clear_modify)
2044{
2045	int i;
2046
2047	if (bp->b_flags & B_VMIO) {
2048		struct vnode *vp = bp->b_vp;
2049		vm_object_t obj = vp->v_object;
2050		vm_ooffset_t foff;
2051
2052		if (vp->v_type == VBLK)
2053			foff = (vm_ooffset_t) DEV_BSIZE * bp->b_lblkno;
2054		else
2055			foff = (vm_ooffset_t) vp->v_mount->mnt_stat.f_iosize * bp->b_lblkno;
2056		vfs_setdirty(bp);
2057		for (i = 0; i < bp->b_npages; i++, foff += PAGE_SIZE) {
2058			vm_page_t m = bp->b_pages[i];
2059
2060			if ((bp->b_flags & B_CLUSTER) == 0) {
2061				obj->paging_in_progress++;
2062				m->busy++;
2063			}
2064			vm_page_protect(m, VM_PROT_NONE);
2065			if (clear_modify)
2066				vfs_page_set_valid(bp, foff, i, m);
2067			else if (bp->b_bcount >= PAGE_SIZE) {
2068				if (m->valid && (bp->b_flags & B_CACHE) == 0) {
2069					bp->b_pages[i] = bogus_page;
2070					pmap_qenter(trunc_page(bp->b_data), bp->b_pages, bp->b_npages);
2071				}
2072			}
2073		}
2074	}
2075}
2076
2077/*
2078 * Tell the VM system that the pages associated with this buffer
2079 * are clean.  This is used for delayed writes where the data is
2080 * going to go to disk eventually without additional VM intevention.
2081 */
2082void
2083vfs_clean_pages(struct buf * bp)
2084{
2085	int i;
2086
2087	if (bp->b_flags & B_VMIO) {
2088		struct vnode *vp = bp->b_vp;
2089		vm_ooffset_t foff;
2090
2091		if (vp->v_type == VBLK)
2092			foff = (vm_ooffset_t) DEV_BSIZE * bp->b_lblkno;
2093		else
2094			foff = (vm_ooffset_t) vp->v_mount->mnt_stat.f_iosize * bp->b_lblkno;
2095		for (i = 0; i < bp->b_npages; i++, foff += PAGE_SIZE) {
2096			vm_page_t m = bp->b_pages[i];
2097
2098			vfs_page_set_valid(bp, foff, i, m);
2099		}
2100	}
2101}
2102
2103void
2104vfs_bio_clrbuf(struct buf *bp) {
2105	int i;
2106	if( bp->b_flags & B_VMIO) {
2107		if( (bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE)) {
2108			int mask;
2109			mask = 0;
2110			for(i=0;i<bp->b_bufsize;i+=DEV_BSIZE)
2111				mask |= (1 << (i/DEV_BSIZE));
2112			if( bp->b_pages[0]->valid != mask) {
2113				bzero(bp->b_data, bp->b_bufsize);
2114			}
2115			bp->b_pages[0]->valid = mask;
2116			bp->b_resid = 0;
2117			return;
2118		}
2119		for(i=0;i<bp->b_npages;i++) {
2120			if( bp->b_pages[i]->valid == VM_PAGE_BITS_ALL)
2121				continue;
2122			if( bp->b_pages[i]->valid == 0) {
2123				if ((bp->b_pages[i]->flags & PG_ZERO) == 0) {
2124					bzero(bp->b_data + (i << PAGE_SHIFT), PAGE_SIZE);
2125				}
2126			} else {
2127				int j;
2128				for(j=0;j<PAGE_SIZE/DEV_BSIZE;j++) {
2129					if( (bp->b_pages[i]->valid & (1<<j)) == 0)
2130						bzero(bp->b_data + (i << PAGE_SHIFT) + j * DEV_BSIZE, DEV_BSIZE);
2131				}
2132			}
2133			/* bp->b_pages[i]->valid = VM_PAGE_BITS_ALL; */
2134		}
2135		bp->b_resid = 0;
2136	} else {
2137		clrbuf(bp);
2138	}
2139}
2140
2141/*
2142 * vm_hold_load_pages and vm_hold_unload pages get pages into
2143 * a buffers address space.  The pages are anonymous and are
2144 * not associated with a file object.
2145 */
2146void
2147vm_hold_load_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
2148{
2149	vm_offset_t pg;
2150	vm_page_t p;
2151	int index;
2152
2153	to = round_page(to);
2154	from = round_page(from);
2155	index = (from - trunc_page(bp->b_data)) >> PAGE_SHIFT;
2156
2157	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
2158
2159tryagain:
2160
2161		p = vm_page_alloc(kernel_object,
2162			((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
2163		    VM_ALLOC_NORMAL);
2164		if (!p) {
2165			VM_WAIT;
2166			goto tryagain;
2167		}
2168		vm_page_wire(p);
2169		pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
2170		bp->b_pages[index] = p;
2171		PAGE_WAKEUP(p);
2172	}
2173	bp->b_npages = index;
2174}
2175
2176void
2177vm_hold_free_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
2178{
2179	vm_offset_t pg;
2180	vm_page_t p;
2181	int index, newnpages;
2182
2183	from = round_page(from);
2184	to = round_page(to);
2185	newnpages = index = (from - trunc_page(bp->b_data)) >> PAGE_SHIFT;
2186
2187	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
2188		p = bp->b_pages[index];
2189		if (p && (index < bp->b_npages)) {
2190#if !defined(MAX_PERF)
2191			if (p->busy) {
2192				printf("vm_hold_free_pages: blkno: %d, lblkno: %d\n",
2193					bp->b_blkno, bp->b_lblkno);
2194			}
2195#endif
2196			bp->b_pages[index] = NULL;
2197			pmap_kremove(pg);
2198			vm_page_unwire(p);
2199			vm_page_free(p);
2200		}
2201	}
2202	bp->b_npages = newnpages;
2203}
2204
2205
2206#include "opt_ddb.h"
2207#ifdef DDB
2208#include <ddb/ddb.h>
2209
2210DB_SHOW_COMMAND(buffer, db_show_buffer)
2211{
2212	/* get args */
2213	struct buf *bp = (struct buf *)addr;
2214
2215	if (!have_addr) {
2216		db_printf("usage: show buffer <addr>\n");
2217		return;
2218	}
2219
2220	db_printf("b_proc = %p,\nb_flags = 0x%b\n", (void *)bp->b_proc,
2221		  bp->b_flags, "\20\40bounce\37cluster\36vmio\35ram\34ordered"
2222		  "\33paging\32xxx\31writeinprog\30wanted\27relbuf\26tape"
2223		  "\25read\24raw\23phys\22clusterok\21malloc\20nocache"
2224		  "\17locked\16inval\15gathered\14error\13eintr\12done\11dirty"
2225		  "\10delwri\7call\6cache\5busy\4bad\3async\2needcommit\1age");
2226	db_printf("b_error = %d, b_bufsize = %ld, b_bcount = %ld, "
2227		  "b_resid = %ld\nb_dev = 0x%x, b_un.b_addr = %p, "
2228		  "b_blkno = %d, b_pblkno = %d\n",
2229		  bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
2230		  bp->b_dev, bp->b_un.b_addr, bp->b_blkno, bp->b_pblkno);
2231	if (bp->b_npages) {
2232		int i;
2233		db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
2234		for (i = 0; i < bp->b_npages; i++) {
2235			vm_page_t m;
2236			m = bp->b_pages[i];
2237			db_printf("(0x%x, 0x%x, 0x%x)", m->object, m->pindex,
2238				VM_PAGE_TO_PHYS(m));
2239			if ((i + 1) < bp->b_npages)
2240				db_printf(",");
2241		}
2242		db_printf("\n");
2243	}
2244}
2245#endif /* DDB */
2246