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