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