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