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