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