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