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