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