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