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