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