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