vfs_bio.c revision 118354
1100966Siwasaki/*
2100966Siwasaki * Copyright (c) 1994,1997 John S. Dyson
3100966Siwasaki * All rights reserved.
4100966Siwasaki *
5100966Siwasaki * Redistribution and use in source and binary forms, with or without
6100966Siwasaki * modification, are permitted provided that the following conditions
7100966Siwasaki * are met:
8217365Sjkim * 1. Redistributions of source code must retain the above copyright
9306536Sjkim *    notice immediately at the beginning of the file, without modification,
10100966Siwasaki *    this list of conditions, and the following disclaimer.
11100966Siwasaki * 2. Absolutely no warranty of function or purpose is made by the author
12217365Sjkim *		John S. Dyson.
13217365Sjkim */
14217365Sjkim
15217365Sjkim/*
16217365Sjkim * this file contains a new buffer I/O scheme implementing a coherent
17217365Sjkim * VM object and buffer cache scheme.  Pains have been taken to make
18217365Sjkim * sure that the performance degradation associated with schemes such
19217365Sjkim * as this is not realized.
20217365Sjkim *
21217365Sjkim * Author:  John S. Dyson
22217365Sjkim * Significant help during the development and debugging phases
23217365Sjkim * had been provided by David Greenman, also of the FreeBSD core team.
24217365Sjkim *
25217365Sjkim * see man buf(9) for more info.
26100966Siwasaki */
27217365Sjkim
28217365Sjkim#include <sys/cdefs.h>
29217365Sjkim__FBSDID("$FreeBSD: head/sys/kern/vfs_bio.c 118354 2003-08-02 09:45:10Z phk $");
30100966Siwasaki
31217365Sjkim#include <sys/param.h>
32217365Sjkim#include <sys/systm.h>
33217365Sjkim#include <sys/bio.h>
34217365Sjkim#include <sys/buf.h>
35217365Sjkim#include <sys/devicestat.h>
36217365Sjkim#include <sys/eventhandler.h>
37217365Sjkim#include <sys/lock.h>
38217365Sjkim#include <sys/malloc.h>
39217365Sjkim#include <sys/mount.h>
40217365Sjkim#include <sys/mutex.h>
41217365Sjkim#include <sys/kernel.h>
42217365Sjkim#include <sys/kthread.h>
43217365Sjkim#include <sys/proc.h>
44100966Siwasaki#include <sys/resourcevar.h>
45281075Sdim#include <sys/sysctl.h>
46100966Siwasaki#include <sys/vmmeter.h>
47193341Sjkim#include <sys/vnode.h>
48193341Sjkim#include <vm/vm.h>
49193341Sjkim#include <vm/vm_param.h>
50193341Sjkim#include <vm/vm_kern.h>
51100966Siwasaki#include <vm/vm_pageout.h>
52100966Siwasaki#include <vm/vm_page.h>
53100966Siwasaki#include <vm/vm_object.h>
54100966Siwasaki#include <vm/vm_extern.h>
55100966Siwasaki#include <vm/vm_map.h>
56193267Sjkim#include "opt_directio.h"
57100966Siwasaki#include "opt_swap.h"
58193267Sjkim
59193267Sjkimstatic MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
60193267Sjkim
61193267Sjkimstruct	bio_ops bioops;		/* I/O operation notification */
62193267Sjkim
63100966Siwasakistruct	buf_ops buf_ops_bio = {
64100966Siwasaki	"buf_ops_bio",
65100966Siwasaki	bwrite
66100966Siwasaki};
67100966Siwasaki
68151937Sjkim/*
69151937Sjkim * XXX buf is global because kern_shutdown.c and ffs_checkoverlap has
70241973Sjkim * carnal knowledge of buffers.  This knowledge should be moved to vfs_bio.c.
71100966Siwasaki */
72151937Sjkimstruct buf *buf;		/* buffer header pool */
73241973Sjkim
74100966Siwasakistatic void vm_hold_free_pages(struct buf * bp, vm_offset_t from,
75100966Siwasaki		vm_offset_t to);
76100966Siwasakistatic void vm_hold_load_pages(struct buf * bp, vm_offset_t from,
77100966Siwasaki		vm_offset_t to);
78100966Siwasakistatic void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
79241973Sjkim			       int pageno, vm_page_t m);
80100966Siwasakistatic void vfs_clean_pages(struct buf * bp);
81100966Siwasakistatic void vfs_setdirty(struct buf *bp);
82100966Siwasakistatic void vfs_vmio_release(struct buf *bp);
83100966Siwasakistatic void vfs_backgroundwritedone(struct buf *bp);
84100966Siwasakistatic int vfs_bio_clcheck(struct vnode *vp, int size,
85100966Siwasaki		daddr_t lblkno, daddr_t blkno);
86100966Siwasakistatic int flushbufqueues(int flushdeps);
87100966Siwasakistatic void buf_daemon(void);
88100966Siwasakivoid bremfreel(struct buf * bp);
89100966Siwasaki
90100966Siwasakiint vmiodirenable = TRUE;
91100966SiwasakiSYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
92100966Siwasaki    "Use the VM system for directory writes");
93281075Sdimint runningbufspace;
94100966SiwasakiSYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
95100966Siwasaki    "Amount of presently outstanding async buffer io");
96167802Sjkimstatic int bufspace;
97100966SiwasakiSYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
98100966Siwasaki    "KVA memory used for bufs");
99100966Siwasakistatic int maxbufspace;
100100966SiwasakiSYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
101100966Siwasaki    "Maximum allowed value of bufspace (including buf_daemon)");
102100966Siwasakistatic int bufmallocspace;
103100966SiwasakiSYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
104100966Siwasaki    "Amount of malloced memory for buffers");
105100966Siwasakistatic int maxbufmallocspace;
106100966SiwasakiSYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace, 0,
107100966Siwasaki    "Maximum amount of malloced memory for buffers");
108281075Sdimstatic int lobufspace;
109100966SiwasakiSYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
110100966Siwasaki    "Minimum amount of buffers we want to have");
111100966Siwasakistatic int hibufspace;
112100966SiwasakiSYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
113281075Sdim    "Maximum allowed value of bufspace (excluding buf_daemon)");
114281075Sdimstatic int bufreusecnt;
115100966SiwasakiSYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW, &bufreusecnt, 0,
116100966Siwasaki    "Number of times we have reused a buffer");
117100966Siwasakistatic int buffreekvacnt;
118100966SiwasakiSYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
119100966Siwasaki    "Number of times we have freed the KVA space from some buffer");
120100966Siwasakistatic int bufdefragcnt;
121100966SiwasakiSYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
122100966Siwasaki    "Number of times we have had to repeat buffer allocation to defragment");
123100966Siwasakistatic int lorunningspace;
124100966SiwasakiSYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
125100966Siwasaki    "Minimum preferred space used for in-progress I/O");
126100966Siwasakistatic int hirunningspace;
127100966SiwasakiSYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
128100966Siwasaki    "Maximum amount of space to use for in-progress I/O");
129100966Siwasakistatic int dirtybufferflushes;
130100966SiwasakiSYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
131167802Sjkim    0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
132100966Siwasakistatic int altbufferflushes;
133100966SiwasakiSYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes,
134100966Siwasaki    0, "Number of fsync flushes to limit dirty buffers");
135100966Siwasakistatic int recursiveflushes;
136100966SiwasakiSYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes,
137100966Siwasaki    0, "Number of flushes skipped due to being recursive");
138100966Siwasakistatic int numdirtybuffers;
139100966SiwasakiSYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
140100966Siwasaki    "Number of buffers that are dirty (has unwritten changes) at the moment");
141100966Siwasakistatic int lodirtybuffers;
142100966SiwasakiSYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
143100966Siwasaki    "How many buffers we want to have free before bufdaemon can sleep");
144167802Sjkimstatic int hidirtybuffers;
145167802SjkimSYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
146100966Siwasaki    "When the number of dirty buffers is considered severe");
147100966Siwasakistatic int dirtybufthresh;
148100966SiwasakiSYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh,
149281075Sdim    0, "Number of bdwrite to bawrite conversions to clear dirty buffers");
150100966Siwasakistatic int numfreebuffers;
151281075SdimSYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
152281075Sdim    "Number of free buffers");
153281075Sdimstatic int lofreebuffers;
154281075SdimSYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
155281075Sdim   "XXX Unused");
156281075Sdimstatic int hifreebuffers;
157281075SdimSYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
158100966Siwasaki   "XXX Complicatedly unused");
159100966Siwasakistatic int getnewbufcalls;
160100966SiwasakiSYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
161100966Siwasaki   "Number of calls to getnewbuf");
162100966Siwasakistatic int getnewbufrestarts;
163100966SiwasakiSYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
164100966Siwasaki    "Number of times getnewbuf has had to restart a buffer aquisition");
165100966Siwasakistatic int dobkgrdwrite = 1;
166167802SjkimSYSCTL_INT(_debug, OID_AUTO, dobkgrdwrite, CTLFLAG_RW, &dobkgrdwrite, 0,
167100966Siwasaki    "Do background writes (honoring the BX_BKGRDWRITE flag)?");
168167802Sjkim
169100966Siwasaki/*
170100966Siwasaki * Wakeup point for bufdaemon, as well as indicator of whether it is already
171100966Siwasaki * active.  Set to 1 when the bufdaemon is already "on" the queue, 0 when it
172100966Siwasaki * is idling.
173100966Siwasaki */
174128212Snjlstatic int bd_request;
175128212Snjl
176241973Sjkim/*
177100966Siwasaki * This lock synchronizes access to bd_request.
178128212Snjl */
179241973Sjkimstatic struct mtx bdlock;
180100966Siwasaki
181100966Siwasaki/*
182100966Siwasaki * bogus page -- for I/O to/from partially complete buffers
183100966Siwasaki * this is a temporary solution to the problem, but it is not
184241973Sjkim * really that bad.  it would be better to split the buffer
185100966Siwasaki * for input in the case of buffers partially already in memory,
186100966Siwasaki * but the code is intricate enough already.
187100966Siwasaki */
188100966Siwasakivm_page_t bogus_page;
189100966Siwasaki
190100966Siwasaki/*
191100966Siwasaki * Synchronization (sleep/wakeup) variable for active buffer space requests.
192100966Siwasaki * Set when wait starts, cleared prior to wakeup().
193100966Siwasaki * Used in runningbufwakeup() and waitrunningbufspace().
194100966Siwasaki */
195100966Siwasakistatic int runningbufreq;
196100966Siwasaki
197167802Sjkim/*
198100966Siwasaki * This lock protects the runningbufreq and synchronizes runningbufwakeup and
199100966Siwasaki * waitrunningbufspace().
200100966Siwasaki */
201100966Siwasakistatic struct mtx rbreqlock;
202167802Sjkim
203100966Siwasaki/*
204100966Siwasaki * Synchronization (sleep/wakeup) variable for buffer requests.
205167802Sjkim * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
206129684Snjl * by and/or.
207167802Sjkim * Used in numdirtywakeup(), bufspacewakeup(), bufcountwakeup(), bwillwrite(),
208167802Sjkim * getnewbuf(), and getblk().
209167802Sjkim */
210167802Sjkimstatic int needsbuffer;
211167802Sjkim
212167802Sjkim/*
213167802Sjkim * Lock that protects needsbuffer and the sleeps/wakeups surrounding it.
214167802Sjkim */
215200553Sjkimstatic struct mtx nblock;
216167802Sjkim
217167802Sjkim/*
218167802Sjkim * Lock that protects against bwait()/bdone()/B_DONE races.
219167802Sjkim */
220167802Sjkim
221167802Sjkimstatic struct mtx bdonelock;
222100966Siwasaki
223249663Sjkim/*
224249663Sjkim * Definitions for the buffer free lists.
225249663Sjkim */
226249663Sjkim#define BUFFER_QUEUES	6	/* number of free buffer queues */
227249663Sjkim
228249663Sjkim#define QUEUE_NONE	0	/* on no queue */
229100966Siwasaki#define QUEUE_LOCKED	1	/* locked buffers */
230249663Sjkim#define QUEUE_CLEAN	2	/* non-B_DELWRI buffers */
231249663Sjkim#define QUEUE_DIRTY	3	/* B_DELWRI buffers */
232249663Sjkim#define QUEUE_EMPTYKVA	4	/* empty buffer headers w/KVA assignment */
233249663Sjkim#define QUEUE_EMPTY	5	/* empty buffer headers */
234249663Sjkim
235249663Sjkim/* Queues for free buffers with various properties */
236249663Sjkimstatic TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
237249663Sjkim
238249663Sjkim/* Lock for the bufqueues */
239249663Sjkimstatic struct mtx bqlock;
240249663Sjkim
241249663Sjkim/*
242249663Sjkim * Single global constant for BUF_WMESG, to avoid getting multiple references.
243249663Sjkim * buf_wmesg is referred from macros.
244249663Sjkim */
245249663Sjkimconst char *buf_wmesg = BUF_WMESG;
246249663Sjkim
247249663Sjkim#define VFS_BIO_NEED_ANY	0x01	/* any freeable buffer */
248249663Sjkim#define VFS_BIO_NEED_DIRTYFLUSH	0x02	/* waiting for dirty buffer flush */
249249663Sjkim#define VFS_BIO_NEED_FREE	0x04	/* wait for free bufs, hi hysteresis */
250249663Sjkim#define VFS_BIO_NEED_BUFSPACE	0x08	/* wait for buf space, lo hysteresis */
251249663Sjkim
252249663Sjkim#ifdef DIRECTIO
253249663Sjkimextern void ffs_rawread_setup(void);
254249663Sjkim#endif /* DIRECTIO */
255249663Sjkim/*
256249663Sjkim *	numdirtywakeup:
257249663Sjkim *
258249663Sjkim *	If someone is blocked due to there being too many dirty buffers,
259249663Sjkim *	and numdirtybuffers is now reasonable, wake them up.
260249663Sjkim */
261249663Sjkim
262249663Sjkimstatic __inline void
263249663Sjkimnumdirtywakeup(int level)
264249663Sjkim{
265100966Siwasaki	if (numdirtybuffers <= level) {
266100966Siwasaki		mtx_lock(&nblock);
267249663Sjkim		if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
268249663Sjkim			needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
269249663Sjkim			wakeup(&needsbuffer);
270249663Sjkim		}
271249663Sjkim		mtx_unlock(&nblock);
272249663Sjkim	}
273249663Sjkim}
274249663Sjkim
275249663Sjkim/*
276249663Sjkim *	bufspacewakeup:
277249663Sjkim *
278249663Sjkim *	Called when buffer space is potentially available for recovery.
279249663Sjkim *	getnewbuf() will block on this flag when it is unable to free
280100966Siwasaki *	sufficient buffer space.  Buffer space becomes recoverable when
281100966Siwasaki *	bp's get placed back in the queues.
282100966Siwasaki */
283100966Siwasaki
284167802Sjkimstatic __inline void
285249663Sjkimbufspacewakeup(void)
286167802Sjkim{
287100966Siwasaki	/*
288167802Sjkim	 * If someone is waiting for BUF space, wake them up.  Even
289167802Sjkim	 * though we haven't freed the kva space yet, the waiting
290100966Siwasaki	 * process will be able to now.
291100966Siwasaki	 */
292167802Sjkim	mtx_lock(&nblock);
293167802Sjkim	if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
294249663Sjkim		needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
295100966Siwasaki		wakeup(&needsbuffer);
296167802Sjkim	}
297249663Sjkim	mtx_unlock(&nblock);
298100966Siwasaki}
299100966Siwasaki
300167802Sjkim/*
301100966Siwasaki * runningbufwakeup() - in-progress I/O accounting.
302100966Siwasaki *
303249663Sjkim */
304249663Sjkimstatic __inline void
305100966Siwasakirunningbufwakeup(struct buf *bp)
306100966Siwasaki{
307249663Sjkim	if (bp->b_runningbufspace) {
308306536Sjkim		atomic_subtract_int(&runningbufspace, bp->b_runningbufspace);
309249663Sjkim		bp->b_runningbufspace = 0;
310100966Siwasaki		mtx_lock(&rbreqlock);
311249663Sjkim		if (runningbufreq && runningbufspace <= lorunningspace) {
312249663Sjkim			runningbufreq = 0;
313100966Siwasaki			wakeup(&runningbufreq);
314249663Sjkim		}
315100966Siwasaki		mtx_unlock(&rbreqlock);
316249663Sjkim	}
317167802Sjkim}
318249663Sjkim
319249663Sjkim/*
320249663Sjkim *	bufcountwakeup:
321249663Sjkim *
322249663Sjkim *	Called when a buffer has been added to one of the free queues to
323249663Sjkim *	account for the buffer and to wakeup anyone waiting for free buffers.
324249663Sjkim *	This typically occurs when large amounts of metadata are being handled
325249663Sjkim *	by the buffer cache ( else buffer space runs out first, usually ).
326249663Sjkim */
327249663Sjkim
328249663Sjkimstatic __inline void
329249663Sjkimbufcountwakeup(void)
330249663Sjkim{
331249663Sjkim	atomic_add_int(&numfreebuffers, 1);
332249663Sjkim	mtx_lock(&nblock);
333249663Sjkim	if (needsbuffer) {
334249663Sjkim		needsbuffer &= ~VFS_BIO_NEED_ANY;
335249663Sjkim		if (numfreebuffers >= hifreebuffers)
336249663Sjkim			needsbuffer &= ~VFS_BIO_NEED_FREE;
337249663Sjkim		wakeup(&needsbuffer);
338249663Sjkim	}
339249663Sjkim	mtx_unlock(&nblock);
340249663Sjkim}
341249663Sjkim
342249663Sjkim/*
343100966Siwasaki *	waitrunningbufspace()
344249663Sjkim *
345249663Sjkim *	runningbufspace is a measure of the amount of I/O currently
346100966Siwasaki *	running.  This routine is used in async-write situations to
347249663Sjkim *	prevent creating huge backups of pending writes to a device.
348100966Siwasaki *	Only asynchronous writes are governed by this function.
349249663Sjkim *
350249663Sjkim *	Reads will adjust runningbufspace, but will not block based on it.
351249663Sjkim *	The read load has a side effect of reducing the allowed write load.
352249663Sjkim *
353249663Sjkim *	This does NOT turn an async write into a sync write.  It waits
354249663Sjkim *	for earlier writes to complete and generally returns before the
355249663Sjkim *	caller's write has reached the device.
356249663Sjkim */
357249663Sjkimstatic __inline void
358249663Sjkimwaitrunningbufspace(void)
359249663Sjkim{
360249663Sjkim	mtx_lock(&rbreqlock);
361249663Sjkim	while (runningbufspace > hirunningspace) {
362249663Sjkim		++runningbufreq;
363249663Sjkim		msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
364249663Sjkim	}
365249663Sjkim	mtx_unlock(&rbreqlock);
366249663Sjkim}
367249663Sjkim
368249663Sjkim
369249663Sjkim/*
370249663Sjkim *	vfs_buf_test_cache:
371249663Sjkim *
372249663Sjkim *	Called when a buffer is extended.  This function clears the B_CACHE
373249663Sjkim *	bit if the newly extended portion of the buffer does not contain
374100966Siwasaki *	valid data.
375249663Sjkim */
376249663Sjkimstatic __inline__
377249663Sjkimvoid
378249663Sjkimvfs_buf_test_cache(struct buf *bp,
379249663Sjkim		  vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
380249663Sjkim		  vm_page_t m)
381249663Sjkim{
382100966Siwasaki	GIANT_REQUIRED;
383249663Sjkim
384249663Sjkim	if (bp->b_flags & B_CACHE) {
385249663Sjkim		int base = (foff + off) & PAGE_MASK;
386100966Siwasaki		if (vm_page_is_valid(m, base, size) == 0)
387249663Sjkim			bp->b_flags &= ~B_CACHE;
388100966Siwasaki	}
389167802Sjkim}
390249663Sjkim
391100966Siwasaki/* Wake up the buffer deamon if necessary */
392249663Sjkimstatic __inline__
393249663Sjkimvoid
394249663Sjkimbd_wakeup(int dirtybuflevel)
395249663Sjkim{
396249663Sjkim	mtx_lock(&bdlock);
397100966Siwasaki	if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
398100966Siwasaki		bd_request = 1;
399100966Siwasaki		wakeup(&bd_request);
400100966Siwasaki	}
401306536Sjkim	mtx_unlock(&bdlock);
402100966Siwasaki}
403306536Sjkim
404306536Sjkim/*
405100966Siwasaki * bd_speedup - speedup the buffer cache flushing code
406306536Sjkim */
407306536Sjkim
408306536Sjkimstatic __inline__
409306536Sjkimvoid
410306536Sjkimbd_speedup(void)
411193267Sjkim{
412306536Sjkim	bd_wakeup(1);
413306536Sjkim}
414306536Sjkim
415306536Sjkim/*
416306536Sjkim * Calculating buffer cache scaling values and reserve space for buffer
417306536Sjkim * headers.  This is called during low level kernel initialization and
418306536Sjkim * may be called more then once.  We CANNOT write to the memory area
419306536Sjkim * being reserved at this time.
420306536Sjkim */
421306536Sjkimcaddr_t
422306536Sjkimkern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
423306536Sjkim{
424306536Sjkim	/*
425306536Sjkim	 * physmem_est is in pages.  Convert it to kilobytes (assumes
426306536Sjkim	 * PAGE_SIZE is >= 1K)
427193267Sjkim	 */
428306536Sjkim	physmem_est = physmem_est * (PAGE_SIZE / 1024);
429306536Sjkim
430306536Sjkim	/*
431306536Sjkim	 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
432167802Sjkim	 * For the first 64MB of ram nominally allocate sufficient buffers to
433306536Sjkim	 * cover 1/4 of our ram.  Beyond the first 64MB allocate additional
434100966Siwasaki	 * buffers to cover 1/20 of our ram over 64MB.  When auto-sizing
435306536Sjkim	 * the buffer cache we limit the eventual kva reservation to
436167802Sjkim	 * maxbcache bytes.
437306536Sjkim	 *
438306536Sjkim	 * factor represents the 1/4 x ram conversion.
439306536Sjkim	 */
440306536Sjkim	if (nbuf == 0) {
441306536Sjkim		int factor = 4 * BKVASIZE / 1024;
442306536Sjkim
443306536Sjkim		nbuf = 50;
444306536Sjkim		if (physmem_est > 4096)
445306536Sjkim			nbuf += min((physmem_est - 4096) / factor,
446306536Sjkim			    65536 / factor);
447306536Sjkim		if (physmem_est > 65536)
448306536Sjkim			nbuf += (physmem_est - 65536) * 2 / (factor * 5);
449306536Sjkim
450306536Sjkim		if (maxbcache && nbuf > maxbcache / BKVASIZE)
451306536Sjkim			nbuf = maxbcache / BKVASIZE;
452306536Sjkim	}
453306536Sjkim
454306536Sjkim#if 0
455306536Sjkim	/*
456306536Sjkim	 * Do not allow the buffer_map to be more then 1/2 the size of the
457100966Siwasaki	 * kernel_map.
458306536Sjkim	 */
459306536Sjkim	if (nbuf > (kernel_map->max_offset - kernel_map->min_offset) /
460306536Sjkim	    (BKVASIZE * 2)) {
461306536Sjkim		nbuf = (kernel_map->max_offset - kernel_map->min_offset) /
462306536Sjkim		    (BKVASIZE * 2);
463306536Sjkim		printf("Warning: nbufs capped at %d\n", nbuf);
464306536Sjkim	}
465100966Siwasaki#endif
466100966Siwasaki
467306536Sjkim	/*
468306536Sjkim	 * swbufs are used as temporary holders for I/O, such as paging I/O.
469167802Sjkim	 * We have no less then 16 and no more then 256.
470100966Siwasaki	 */
471129684Snjl	nswbuf = max(min(nbuf/4, 256), 16);
472167802Sjkim#ifdef NSWBUF_MIN
473167802Sjkim	if (nswbuf < NSWBUF_MIN)
474100966Siwasaki		nswbuf = NSWBUF_MIN;
475167802Sjkim#endif
476167802Sjkim#ifdef DIRECTIO
477167802Sjkim	ffs_rawread_setup();
478167802Sjkim#endif
479167802Sjkim
480167802Sjkim	/*
481100966Siwasaki	 * Reserve space for the buffer cache buffers
482100966Siwasaki	 */
483167802Sjkim	swbuf = (void *)v;
484167802Sjkim	v = (caddr_t)(swbuf + nswbuf);
485167802Sjkim	buf = (void *)v;
486167802Sjkim	v = (caddr_t)(buf + nbuf);
487167802Sjkim
488167802Sjkim	return(v);
489100966Siwasaki}
490100966Siwasaki
491100966Siwasaki/* Initialize the buffer subsystem.  Called before use of any buffers. */
492167802Sjkimvoid
493100966Siwasakibufinit(void)
494100966Siwasaki{
495167802Sjkim	struct buf *bp;
496100966Siwasaki	int i;
497100966Siwasaki
498100966Siwasaki	GIANT_REQUIRED;
499167802Sjkim
500100966Siwasaki	mtx_init(&bqlock, "buf queue lock", NULL, MTX_DEF);
501167802Sjkim	mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
502100966Siwasaki	mtx_init(&nblock, "needsbuffer lock", NULL, MTX_DEF);
503100966Siwasaki	mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
504193267Sjkim	mtx_init(&bdonelock, "bdone lock", NULL, MTX_DEF);
505193267Sjkim
506193267Sjkim	/* next, make a null set of free lists */
507193267Sjkim	for (i = 0; i < BUFFER_QUEUES; i++)
508193267Sjkim		TAILQ_INIT(&bufqueues[i]);
509193267Sjkim
510193267Sjkim	/* finally, initialize each buffer header and stick on empty q */
511193267Sjkim	for (i = 0; i < nbuf; i++) {
512193267Sjkim		bp = &buf[i];
513193267Sjkim		bzero(bp, sizeof *bp);
514193267Sjkim		bp->b_flags = B_INVAL;	/* we're just an empty header */
515193267Sjkim		bp->b_dev = NODEV;
516193267Sjkim		bp->b_rcred = NOCRED;
517193267Sjkim		bp->b_wcred = NOCRED;
518193267Sjkim		bp->b_qindex = QUEUE_EMPTY;
519193267Sjkim		bp->b_vflags = 0;
520193267Sjkim		bp->b_xflags = 0;
521193267Sjkim		LIST_INIT(&bp->b_dep);
522193267Sjkim		BUF_LOCKINIT(bp);
523193267Sjkim		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
524193267Sjkim	}
525193267Sjkim
526193267Sjkim	/*
527193267Sjkim	 * maxbufspace is the absolute maximum amount of buffer space we are
528193267Sjkim	 * allowed to reserve in KVM and in real terms.  The absolute maximum
529193267Sjkim	 * is nominally used by buf_daemon.  hibufspace is the nominal maximum
530193267Sjkim	 * used by most other processes.  The differential is required to
531193267Sjkim	 * ensure that buf_daemon is able to run when other processes might
532193267Sjkim	 * be blocked waiting for buffer space.
533193267Sjkim	 *
534193267Sjkim	 * maxbufspace is based on BKVASIZE.  Allocating buffers larger then
535193267Sjkim	 * this may result in KVM fragmentation which is not handled optimally
536193267Sjkim	 * by the system.
537193267Sjkim	 */
538193267Sjkim	maxbufspace = nbuf * BKVASIZE;
539193267Sjkim	hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
540193267Sjkim	lobufspace = hibufspace - MAXBSIZE;
541193267Sjkim
542193267Sjkim	lorunningspace = 512 * 1024;
543193267Sjkim	hirunningspace = 1024 * 1024;
544193267Sjkim
545193267Sjkim/*
546193267Sjkim * Limit the amount of malloc memory since it is wired permanently into
547193267Sjkim * the kernel space.  Even though this is accounted for in the buffer
548193267Sjkim * allocation, we don't want the malloced region to grow uncontrolled.
549193267Sjkim * The malloc scheme improves memory utilization significantly on average
550193267Sjkim * (small) directories.
551193267Sjkim */
552193267Sjkim	maxbufmallocspace = hibufspace / 20;
553193267Sjkim
554193267Sjkim/*
555193267Sjkim * Reduce the chance of a deadlock occuring by limiting the number
556193267Sjkim * of delayed-write dirty buffers we allow to stack up.
557193267Sjkim */
558193267Sjkim	hidirtybuffers = nbuf / 4 + 20;
559193267Sjkim	dirtybufthresh = hidirtybuffers * 9 / 10;
560193267Sjkim	numdirtybuffers = 0;
561193267Sjkim/*
562250838Sjkim * To support extreme low-memory systems, make sure hidirtybuffers cannot
563193267Sjkim * eat up all available buffer space.  This occurs when our minimum cannot
564193267Sjkim * be met.  We try to size hidirtybuffers to 3/4 our buffer space assuming
565193267Sjkim * BKVASIZE'd (8K) buffers.
566193267Sjkim */
567193267Sjkim	while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
568193267Sjkim		hidirtybuffers >>= 1;
569193267Sjkim	}
570193267Sjkim	lodirtybuffers = hidirtybuffers / 2;
571193267Sjkim
572193267Sjkim/*
573193267Sjkim * Try to keep the number of free buffers in the specified range,
574193267Sjkim * and give special processes (e.g. like buf_daemon) access to an
575193267Sjkim * emergency reserve.
576193267Sjkim */
577193267Sjkim	lofreebuffers = nbuf / 18 + 5;
578193267Sjkim	hifreebuffers = 2 * lofreebuffers;
579193267Sjkim	numfreebuffers = nbuf;
580193267Sjkim
581100966Siwasaki/*
582100966Siwasaki * Maximum number of async ops initiated per buf_daemon loop.  This is
583100966Siwasaki * somewhat of a hack at the moment, we really need to limit ourselves
584100966Siwasaki * based on the number of bytes of I/O in-transit that were initiated
585100966Siwasaki * from buf_daemon.
586253690Sjkim */
587199337Sjkim
588253690Sjkim	bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
589199337Sjkim	    VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
590199337Sjkim}
591100966Siwasaki
592100966Siwasaki/*
593100966Siwasaki * bfreekva() - free the kva allocation for a buffer.
594100966Siwasaki *
595100966Siwasaki *	Must be called at splbio() or higher as this is the only locking for
596100966Siwasaki *	buffer_map.
597100966Siwasaki *
598100966Siwasaki *	Since this call frees up buffer space, we call bufspacewakeup().
599199337Sjkim */
600199337Sjkimstatic void
601100966Siwasakibfreekva(struct buf * bp)
602100966Siwasaki{
603100966Siwasaki	GIANT_REQUIRED;
604100966Siwasaki
605100966Siwasaki	if (bp->b_kvasize) {
606199337Sjkim		atomic_add_int(&buffreekvacnt, 1);
607199337Sjkim		atomic_subtract_int(&bufspace, bp->b_kvasize);
608199337Sjkim		vm_map_delete(buffer_map,
609100966Siwasaki		    (vm_offset_t) bp->b_kvabase,
610100966Siwasaki		    (vm_offset_t) bp->b_kvabase + bp->b_kvasize
611100966Siwasaki		);
612100966Siwasaki		bp->b_kvasize = 0;
613100966Siwasaki		bufspacewakeup();
614100966Siwasaki	}
615100966Siwasaki}
616100966Siwasaki
617253690Sjkim/*
618253690Sjkim *	bremfree:
619100966Siwasaki *
620100966Siwasaki *	Remove the buffer from the appropriate free list.
621100966Siwasaki */
622100966Siwasakivoid
623100966Siwasakibremfree(struct buf * bp)
624100966Siwasaki{
625167802Sjkim	mtx_lock(&bqlock);
626100966Siwasaki	bremfreel(bp);
627100966Siwasaki	mtx_unlock(&bqlock);
628100966Siwasaki}
629100966Siwasaki
630167802Sjkimvoid
631167802Sjkimbremfreel(struct buf * bp)
632253690Sjkim{
633100966Siwasaki	int s = splbio();
634100966Siwasaki	int old_qindex = bp->b_qindex;
635100966Siwasaki
636100966Siwasaki	GIANT_REQUIRED;
637100966Siwasaki
638193267Sjkim	if (bp->b_qindex != QUEUE_NONE) {
639193267Sjkim		KASSERT(BUF_REFCNT(bp) == 1, ("bremfree: bp %p not locked",bp));
640193267Sjkim		TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
641193267Sjkim		bp->b_qindex = QUEUE_NONE;
642193267Sjkim	} else {
643193267Sjkim		if (BUF_REFCNT(bp) <= 1)
644193267Sjkim			panic("bremfree: removing a buffer not on a queue");
645193267Sjkim	}
646193267Sjkim
647100966Siwasaki	/*
648193267Sjkim	 * Fixup numfreebuffers count.  If the buffer is invalid or not
649193267Sjkim	 * delayed-write, and it was on the EMPTY, LRU, or AGE queues,
650193267Sjkim	 * the buffer was free and we must decrement numfreebuffers.
651241973Sjkim	 */
652193267Sjkim	if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
653193267Sjkim		switch(old_qindex) {
654193267Sjkim		case QUEUE_DIRTY:
655193267Sjkim		case QUEUE_CLEAN:
656193267Sjkim		case QUEUE_EMPTY:
657193267Sjkim		case QUEUE_EMPTYKVA:
658193267Sjkim			atomic_subtract_int(&numfreebuffers, 1);
659193267Sjkim			break;
660100966Siwasaki		default:
661100966Siwasaki			break;
662100966Siwasaki		}
663193267Sjkim	}
664100966Siwasaki	splx(s);
665100966Siwasaki}
666254745Sjkim
667254745Sjkim
668254745Sjkim/*
669254745Sjkim * Get a buffer with the specified data.  Look in the cache first.  We
670254745Sjkim * must clear BIO_ERROR and B_INVAL prior to initiating I/O.  If B_CACHE
671254745Sjkim * is set, the buffer is valid and we do not have to do anything ( see
672254745Sjkim * getblk() ).  This is really just a special case of breadn().
673254745Sjkim */
674151937Sjkimint
675306536Sjkimbread(struct vnode * vp, daddr_t blkno, int size, struct ucred * cred,
676306536Sjkim    struct buf ** bpp)
677100966Siwasaki{
678254745Sjkim
679100966Siwasaki	return (breadn(vp, blkno, size, 0, 0, 0, cred, bpp));
680193267Sjkim}
681193267Sjkim
682193267Sjkim/*
683100966Siwasaki * Operates like bread, but also starts asynchronous I/O on
684100966Siwasaki * read-ahead blocks.  We must clear BIO_ERROR and B_INVAL prior
685100966Siwasaki * to initiating I/O . If B_CACHE is set, the buffer is valid
686167802Sjkim * and we do not have to do anything.
687100966Siwasaki */
688167802Sjkimint
689100966Siwasakibreadn(struct vnode * vp, daddr_t blkno, int size,
690100966Siwasaki    daddr_t * rablkno, int *rabsize,
691100966Siwasaki    int cnt, struct ucred * cred, struct buf ** bpp)
692100966Siwasaki{
693100966Siwasaki	struct buf *bp, *rabp;
694100966Siwasaki	int i;
695100966Siwasaki	int rv = 0, readwait = 0;
696100966Siwasaki
697100966Siwasaki	*bpp = bp = getblk(vp, blkno, size, 0, 0, 0);
698100966Siwasaki
699100966Siwasaki	/* if not found in cache, do some I/O */
700100966Siwasaki	if ((bp->b_flags & B_CACHE) == 0) {
701100966Siwasaki		if (curthread != PCPU_GET(idlethread))
702100966Siwasaki			curthread->td_proc->p_stats->p_ru.ru_inblock++;
703100966Siwasaki		bp->b_iocmd = BIO_READ;
704100966Siwasaki		bp->b_flags &= ~B_INVAL;
705100966Siwasaki		bp->b_ioflags &= ~BIO_ERROR;
706100966Siwasaki		if (bp->b_rcred == NOCRED && cred != NOCRED)
707100966Siwasaki			bp->b_rcred = crhold(cred);
708100966Siwasaki		vfs_busy_pages(bp, 0);
709100966Siwasaki		if (vp->v_type == VCHR)
710117521Snjl			VOP_SPECSTRATEGY(vp, bp);
711100966Siwasaki		else
712100966Siwasaki			VOP_STRATEGY(vp, bp);
713100966Siwasaki		++readwait;
714241973Sjkim	}
715241973Sjkim
716193267Sjkim	for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
717193267Sjkim		if (inmem(vp, *rablkno))
718197104Sjkim			continue;
719100966Siwasaki		rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
720100966Siwasaki
721100966Siwasaki		if ((rabp->b_flags & B_CACHE) == 0) {
722100966Siwasaki			if (curthread != PCPU_GET(idlethread))
723100966Siwasaki				curthread->td_proc->p_stats->p_ru.ru_inblock++;
724100966Siwasaki			rabp->b_flags |= B_ASYNC;
725100966Siwasaki			rabp->b_flags &= ~B_INVAL;
726100966Siwasaki			rabp->b_ioflags &= ~BIO_ERROR;
727200553Sjkim			rabp->b_iocmd = BIO_READ;
728100966Siwasaki			if (rabp->b_rcred == NOCRED && cred != NOCRED)
729100966Siwasaki				rabp->b_rcred = crhold(cred);
730100966Siwasaki			vfs_busy_pages(rabp, 0);
731100966Siwasaki			BUF_KERNPROC(rabp);
732100966Siwasaki			if (vp->v_type == VCHR)
733100966Siwasaki				VOP_SPECSTRATEGY(vp, rabp);
734100966Siwasaki			else
735100966Siwasaki				VOP_STRATEGY(vp, rabp);
736100966Siwasaki		} else {
737100966Siwasaki			brelse(rabp);
738100966Siwasaki		}
739202771Sjkim	}
740202771Sjkim
741202771Sjkim	if (readwait) {
742202771Sjkim		rv = bufwait(bp);
743202771Sjkim	}
744202771Sjkim	return (rv);
745202771Sjkim}
746202771Sjkim
747202771Sjkim/*
748202771Sjkim * Write, release buffer on completion.  (Done by iodone
749202771Sjkim * if async).  Do not bother writing anything if the buffer
750202771Sjkim * is invalid.
751202771Sjkim *
752202771Sjkim * Note that we set B_CACHE here, indicating that buffer is
753100966Siwasaki * fully valid and thus cacheable.  This is true even of NFS
754100966Siwasaki * now so we set it generally.  This could be set either here
755100966Siwasaki * or in biodone() since the I/O is synchronous.  We put it
756100966Siwasaki * here.
757100966Siwasaki */
758100966Siwasaki
759100966Siwasakiint
760100966Siwasakibwrite(struct buf * bp)
761100966Siwasaki{
762100966Siwasaki	int oldflags, s;
763100966Siwasaki	struct buf *newbp;
764100966Siwasaki
765306536Sjkim	if (bp->b_flags & B_INVAL) {
766197104Sjkim		brelse(bp);
767197104Sjkim		return (0);
768197104Sjkim	}
769100966Siwasaki
770193267Sjkim	oldflags = bp->b_flags;
771193267Sjkim
772193267Sjkim	if (BUF_REFCNT(bp) == 0)
773193267Sjkim		panic("bwrite: buffer is not busy???");
774100966Siwasaki	s = splbio();
775100966Siwasaki	/*
776100966Siwasaki	 * If a background write is already in progress, delay
777100966Siwasaki	 * writing this block if it is asynchronous. Otherwise
778100966Siwasaki	 * wait for the background write to complete.
779100966Siwasaki	 */
780100966Siwasaki	if (bp->b_xflags & BX_BKGRDINPROG) {
781100966Siwasaki		if (bp->b_flags & B_ASYNC) {
782100966Siwasaki			splx(s);
783100966Siwasaki			bdwrite(bp);
784117521Snjl			return (0);
785100966Siwasaki		}
786193267Sjkim		bp->b_xflags |= BX_BKGRDWAIT;
787117521Snjl		tsleep(&bp->b_xflags, PRIBIO, "bwrbg", 0);
788100966Siwasaki		if (bp->b_xflags & BX_BKGRDINPROG)
789306536Sjkim			panic("bwrite: still writing");
790117521Snjl	}
791193267Sjkim
792193267Sjkim	/* Mark the buffer clean */
793193267Sjkim	bundirty(bp);
794193267Sjkim
795117521Snjl	/*
796100966Siwasaki	 * If this buffer is marked for background writing and we
797193267Sjkim	 * do not have to wait for it, make a copy and write the
798167802Sjkim	 * copy so as to leave this buffer ready for further use.
799193267Sjkim	 *
800193267Sjkim	 * This optimization eats a lot of memory.  If we have a page
801193267Sjkim	 * or buffer shortfall we can't do it.
802193267Sjkim	 */
803100966Siwasaki	if (dobkgrdwrite && (bp->b_xflags & BX_BKGRDWRITE) &&
804100966Siwasaki	    (bp->b_flags & B_ASYNC) &&
805100966Siwasaki	    !vm_page_count_severe() &&
806202771Sjkim	    !buf_dirty_count_severe()) {
807202771Sjkim		if (bp->b_iodone != NULL) {
808202771Sjkim			printf("bp->b_iodone = %p\n", bp->b_iodone);
809202771Sjkim			panic("bwrite: need chained iodone");
810202771Sjkim		}
811202771Sjkim
812202771Sjkim		/* get a new block */
813202771Sjkim		newbp = geteblk(bp->b_bufsize);
814202771Sjkim
815202771Sjkim		/*
816202771Sjkim		 * set it to be identical to the old block.  We have to
817202771Sjkim		 * set b_lblkno and BKGRDMARKER before calling bgetvp()
818202771Sjkim		 * to avoid confusing the splay tree and gbincore().
819202771Sjkim		 */
820202771Sjkim		memcpy(newbp->b_data, bp->b_data, bp->b_bufsize);
821202771Sjkim		newbp->b_lblkno = bp->b_lblkno;
822202771Sjkim		newbp->b_xflags |= BX_BKGRDMARKER;
823202771Sjkim		/* XXX The BX_ flags need to be protected as well */
824202771Sjkim		VI_LOCK(bp->b_vp);
825193267Sjkim		bgetvp(bp->b_vp, newbp);
826193267Sjkim		VI_UNLOCK(bp->b_vp);
827306536Sjkim		newbp->b_blkno = bp->b_blkno;
828306536Sjkim		newbp->b_offset = bp->b_offset;
829100966Siwasaki		newbp->b_iodone = vfs_backgroundwritedone;
830100966Siwasaki		newbp->b_flags |= B_ASYNC;
831100966Siwasaki		newbp->b_flags &= ~B_INVAL;
832100966Siwasaki
833100966Siwasaki		/* move over the dependencies */
834100966Siwasaki		if (LIST_FIRST(&bp->b_dep) != NULL)
835100966Siwasaki			buf_movedeps(bp, newbp);
836100966Siwasaki
837100966Siwasaki		/*
838100966Siwasaki		 * Initiate write on the copy, release the original to
839100966Siwasaki		 * the B_LOCKED queue so that it cannot go away until
840100966Siwasaki		 * the background write completes. If not locked it could go
841100966Siwasaki		 * away and then be reconstituted while it was being written.
842100966Siwasaki		 * If the reconstituted buffer were written, we could end up
843100966Siwasaki		 * with two background copies being written at the same time.
844100966Siwasaki		 */
845100966Siwasaki		bp->b_xflags |= BX_BKGRDINPROG;
846100966Siwasaki		bp->b_flags |= B_LOCKED;
847100966Siwasaki		bqrelse(bp);
848117521Snjl		bp = newbp;
849241973Sjkim	}
850100966Siwasaki
851100966Siwasaki	bp->b_flags &= ~B_DONE;
852100966Siwasaki	bp->b_ioflags &= ~BIO_ERROR;
853100966Siwasaki	bp->b_flags |= B_WRITEINPROG | B_CACHE;
854193267Sjkim	bp->b_iocmd = BIO_WRITE;
855100966Siwasaki
856100966Siwasaki	VI_LOCK(bp->b_vp);
857100966Siwasaki	bp->b_vp->v_numoutput++;
858100966Siwasaki	VI_UNLOCK(bp->b_vp);
859100966Siwasaki	vfs_busy_pages(bp, 1);
860114237Snjl
861100966Siwasaki	/*
862100966Siwasaki	 * Normal bwrites pipeline writes
863100966Siwasaki	 */
864100966Siwasaki	bp->b_runningbufspace = bp->b_bufsize;
865100966Siwasaki	atomic_add_int(&runningbufspace, bp->b_runningbufspace);
866100966Siwasaki
867100966Siwasaki	if (curthread != PCPU_GET(idlethread))
868100966Siwasaki		curthread->td_proc->p_stats->p_ru.ru_oublock++;
869167802Sjkim	splx(s);
870100966Siwasaki	if (oldflags & B_ASYNC)
871100966Siwasaki		BUF_KERNPROC(bp);
872100966Siwasaki	if (bp->b_vp->v_type == VCHR)
873100966Siwasaki		VOP_SPECSTRATEGY(bp->b_vp, bp);
874100966Siwasaki	else
875100966Siwasaki		VOP_STRATEGY(bp->b_vp, bp);
876100966Siwasaki
877100966Siwasaki	if ((oldflags & B_ASYNC) == 0) {
878100966Siwasaki		int rtval = bufwait(bp);
879100966Siwasaki		brelse(bp);
880100966Siwasaki		return (rtval);
881100966Siwasaki	} else {
882100966Siwasaki		/*
883306536Sjkim		 * don't allow the async write to saturate the I/O
884306536Sjkim		 * system.  We will not deadlock here because
885100966Siwasaki		 * we are blocking waiting for I/O that is already in-progress
886100966Siwasaki		 * to complete.
887100966Siwasaki		 */
888100966Siwasaki		waitrunningbufspace();
889100966Siwasaki	}
890100966Siwasaki
891100966Siwasaki	return (0);
892100966Siwasaki}
893100966Siwasaki
894100966Siwasaki/*
895100966Siwasaki * Complete a background write started from bwrite.
896100966Siwasaki */
897100966Siwasakistatic void
898100966Siwasakivfs_backgroundwritedone(bp)
899167802Sjkim	struct buf *bp;
900306536Sjkim{
901306536Sjkim	struct buf *origbp;
902100966Siwasaki
903100966Siwasaki	/*
904100966Siwasaki	 * Find the original buffer that we are writing.
905100966Siwasaki	 */
906100966Siwasaki	VI_LOCK(bp->b_vp);
907167802Sjkim	if ((origbp = gbincore(bp->b_vp, bp->b_lblkno)) == NULL)
908100966Siwasaki		panic("backgroundwritedone: lost buffer");
909167802Sjkim	VI_UNLOCK(bp->b_vp);
910100966Siwasaki	/*
911100966Siwasaki	 * Process dependencies then return any unfinished ones.
912100966Siwasaki	 */
913100966Siwasaki	if (LIST_FIRST(&bp->b_dep) != NULL)
914114237Snjl		buf_complete(bp);
915107325Siwasaki	if (LIST_FIRST(&bp->b_dep) != NULL)
916107325Siwasaki		buf_movedeps(bp, origbp);
917100966Siwasaki
918100966Siwasaki	/* XXX Find out if origbp can disappear or get inconsistent */
919100966Siwasaki	/*
920107325Siwasaki	 * Clear the BX_BKGRDINPROG flag in the original buffer
921100966Siwasaki	 * and awaken it if it is waiting for the write to complete.
922100966Siwasaki	 * If BX_BKGRDINPROG is not set in the original buffer it must
923100966Siwasaki	 * have been released and re-instantiated - which is not legal.
924100966Siwasaki	 */
925100966Siwasaki	KASSERT((origbp->b_xflags & BX_BKGRDINPROG),
926100966Siwasaki	    ("backgroundwritedone: lost buffer2"));
927100966Siwasaki	origbp->b_xflags &= ~BX_BKGRDINPROG;
928100966Siwasaki	if (origbp->b_xflags & BX_BKGRDWAIT) {
929100966Siwasaki		origbp->b_xflags &= ~BX_BKGRDWAIT;
930100966Siwasaki		wakeup(&origbp->b_xflags);
931100966Siwasaki	}
932100966Siwasaki	/*
933100966Siwasaki	 * Clear the B_LOCKED flag and remove it from the locked
934100966Siwasaki	 * queue if it currently resides there.
935100966Siwasaki	 */
936100966Siwasaki	origbp->b_flags &= ~B_LOCKED;
937100966Siwasaki	if (BUF_LOCK(origbp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0) {
938100966Siwasaki		bremfree(origbp);
939100966Siwasaki		bqrelse(origbp);
940100966Siwasaki	}
941100966Siwasaki	/*
942100966Siwasaki	 * This buffer is marked B_NOCACHE, so when it is released
943100966Siwasaki	 * by biodone, it will be tossed. We mark it with BIO_READ
944100966Siwasaki	 * to avoid biodone doing a second vwakeup.
945100966Siwasaki	 */
946100966Siwasaki	bp->b_flags |= B_NOCACHE;
947100966Siwasaki	bp->b_iocmd = BIO_READ;
948100966Siwasaki	bp->b_flags &= ~(B_CACHE | B_DONE);
949100966Siwasaki	bp->b_iodone = 0;
950100966Siwasaki	bufdone(bp);
951200553Sjkim}
952100966Siwasaki
953100966Siwasaki/*
954100966Siwasaki * Delayed write. (Buffer is marked dirty).  Do not bother writing
955100966Siwasaki * anything if the buffer is marked invalid.
956100966Siwasaki *
957100966Siwasaki * Note that since the buffer must be completely valid, we can safely
958100966Siwasaki * set B_CACHE.  In fact, we have to set B_CACHE here rather then in
959100966Siwasaki * biodone() in order to prevent getblk from writing the buffer
960100966Siwasaki * out synchronously.
961100966Siwasaki */
962100966Siwasakivoid
963100966Siwasakibdwrite(struct buf * bp)
964100966Siwasaki{
965167802Sjkim	struct thread *td = curthread;
966100966Siwasaki	struct vnode *vp;
967167802Sjkim	struct buf *nbp;
968100966Siwasaki
969100966Siwasaki	GIANT_REQUIRED;
970100966Siwasaki
971100966Siwasaki	if (BUF_REFCNT(bp) == 0)
972107325Siwasaki		panic("bdwrite: buffer is not busy");
973107325Siwasaki
974100966Siwasaki	if (bp->b_flags & B_INVAL) {
975100966Siwasaki		brelse(bp);
976100966Siwasaki		return;
977107325Siwasaki	}
978100966Siwasaki
979100966Siwasaki	/*
980100966Siwasaki	 * If we have too many dirty buffers, don't create any more.
981100966Siwasaki	 * If we are wildly over our limit, then force a complete
982100966Siwasaki	 * cleanup. Otherwise, just keep the situation from getting
983100966Siwasaki	 * out of control. Note that we have to avoid a recursive
984100966Siwasaki	 * disaster and not try to clean up after our own cleanup!
985100966Siwasaki	 */
986100966Siwasaki	vp = bp->b_vp;
987100966Siwasaki	VI_LOCK(vp);
988100966Siwasaki	if (td->td_proc->p_flag & P_COWINPROGRESS) {
989100966Siwasaki		recursiveflushes++;
990100966Siwasaki	} else if (vp != NULL && vp->v_dirtybufcnt > dirtybufthresh + 10) {
991100966Siwasaki		VI_UNLOCK(vp);
992100966Siwasaki		(void) VOP_FSYNC(vp, td->td_ucred, MNT_NOWAIT, td);
993100966Siwasaki		VI_LOCK(vp);
994100966Siwasaki		altbufferflushes++;
995100966Siwasaki	} else if (vp != NULL && vp->v_dirtybufcnt > dirtybufthresh) {
996100966Siwasaki		/*
997100966Siwasaki		 * Try to find a buffer to flush.
998100966Siwasaki		 */
999100966Siwasaki		TAILQ_FOREACH(nbp, &vp->v_dirtyblkhd, b_vnbufs) {
1000100966Siwasaki			if ((nbp->b_xflags & BX_BKGRDINPROG) ||
1001100966Siwasaki			    buf_countdeps(nbp, 0) ||
1002100966Siwasaki			    BUF_LOCK(nbp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
1003100966Siwasaki				continue;
1004100966Siwasaki			if (bp == nbp)
1005100966Siwasaki				panic("bdwrite: found ourselves");
1006200553Sjkim			VI_UNLOCK(vp);
1007100966Siwasaki			if (nbp->b_flags & B_CLUSTEROK) {
1008100966Siwasaki				vfs_bio_awrite(nbp);
1009100966Siwasaki			} else {
1010100966Siwasaki				bremfree(nbp);
1011100966Siwasaki				bawrite(nbp);
1012100966Siwasaki			}
1013100966Siwasaki			VI_LOCK(vp);
1014100966Siwasaki			dirtybufferflushes++;
1015100966Siwasaki			break;
1016100966Siwasaki		}
1017100966Siwasaki	}
1018100966Siwasaki	VI_UNLOCK(vp);
1019100966Siwasaki
1020167802Sjkim	bdirty(bp);
1021100966Siwasaki	/*
1022167802Sjkim	 * Set B_CACHE, indicating that the buffer is fully valid.  This is
1023100966Siwasaki	 * true even of NFS now.
1024100966Siwasaki	 */
1025100966Siwasaki	bp->b_flags |= B_CACHE;
1026100966Siwasaki
1027107325Siwasaki	/*
1028107325Siwasaki	 * This bmap keeps the system from needing to do the bmap later,
1029107325Siwasaki	 * perhaps when the system is attempting to do a sync.  Since it
1030100966Siwasaki	 * is likely that the indirect block -- or whatever other datastructure
1031100966Siwasaki	 * that the filesystem needs is still in memory now, it is a good
1032100966Siwasaki	 * thing to do this.  Note also, that if the pageout daemon is
1033107325Siwasaki	 * requesting a sync -- there might not be enough memory to do
1034100966Siwasaki	 * the bmap then...  So, this is important to do.
1035100966Siwasaki	 */
1036100966Siwasaki	if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
1037100966Siwasaki		VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
1038100966Siwasaki	}
1039100966Siwasaki
1040100966Siwasaki	/*
1041100966Siwasaki	 * Set the *dirty* buffer range based upon the VM system dirty pages.
1042100966Siwasaki	 */
1043100966Siwasaki	vfs_setdirty(bp);
1044100966Siwasaki
1045100966Siwasaki	/*
1046100966Siwasaki	 * We need to do this here to satisfy the vnode_pager and the
1047100966Siwasaki	 * pageout daemon, so that it thinks that the pages have been
1048100966Siwasaki	 * "cleaned".  Note that since the pages are in a delayed write
1049100966Siwasaki	 * buffer -- the VFS layer "will" see that the pages get written
1050100966Siwasaki	 * out on the next sync, or perhaps the cluster will be completed.
1051100966Siwasaki	 */
1052100966Siwasaki	vfs_clean_pages(bp);
1053100966Siwasaki	bqrelse(bp);
1054100966Siwasaki
1055100966Siwasaki	/*
1056100966Siwasaki	 * Wakeup the buffer flushing daemon if we have a lot of dirty
1057100966Siwasaki	 * buffers (midpoint between our recovery point and our stall
1058100966Siwasaki	 * point).
1059100966Siwasaki	 */
1060100966Siwasaki	bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1061100966Siwasaki
1062100966Siwasaki	/*
1063100966Siwasaki	 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1064200553Sjkim	 * due to the softdep code.
1065100966Siwasaki	 */
1066100966Siwasaki}
1067100966Siwasaki
1068100966Siwasaki/*
1069100966Siwasaki *	bdirty:
1070100966Siwasaki *
1071100966Siwasaki *	Turn buffer into delayed write request.  We must clear BIO_READ and
1072100966Siwasaki *	B_RELBUF, and we must set B_DELWRI.  We reassign the buffer to
1073100966Siwasaki *	itself to properly update it in the dirty/clean lists.  We mark it
1074100966Siwasaki *	B_DONE to ensure that any asynchronization of the buffer properly
1075100966Siwasaki *	clears B_DONE ( else a panic will occur later ).
1076100966Siwasaki *
1077100966Siwasaki *	bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1078167802Sjkim *	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
3033	/* Device drivers may or may not hold giant, hold it here. */
3034	mtx_lock(&Giant);
3035	bufdone(bp->bio_caller2);
3036	mtx_unlock(&Giant);
3037}
3038
3039/*
3040 *	bufdone:
3041 *
3042 *	Finish I/O on a buffer, optionally calling a completion function.
3043 *	This is usually called from an interrupt so process blocking is
3044 *	not allowed.
3045 *
3046 *	biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3047 *	In a non-VMIO bp, B_CACHE will be set on the next getblk()
3048 *	assuming B_INVAL is clear.
3049 *
3050 *	For the VMIO case, we set B_CACHE if the op was a read and no
3051 *	read error occured, or if the op was a write.  B_CACHE is never
3052 *	set if the buffer is invalid or otherwise uncacheable.
3053 *
3054 *	biodone does not mess with B_INVAL, allowing the I/O routine or the
3055 *	initiator to leave B_INVAL set to brelse the buffer out of existance
3056 *	in the biodone routine.
3057 */
3058void
3059bufdone(struct buf *bp)
3060{
3061	int s;
3062	void    (*biodone)(struct buf *);
3063
3064	GIANT_REQUIRED;
3065
3066	s = splbio();
3067
3068	KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp, BUF_REFCNT(bp)));
3069	KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3070
3071	bp->b_flags |= B_DONE;
3072	runningbufwakeup(bp);
3073
3074	if (bp->b_iocmd == BIO_DELETE) {
3075		brelse(bp);
3076		splx(s);
3077		return;
3078	}
3079
3080	if (bp->b_iocmd == BIO_WRITE) {
3081		vwakeup(bp);
3082	}
3083
3084	/* call optional completion function if requested */
3085	if (bp->b_iodone != NULL) {
3086		biodone = bp->b_iodone;
3087		bp->b_iodone = NULL;
3088		(*biodone) (bp);
3089		splx(s);
3090		return;
3091	}
3092	if (LIST_FIRST(&bp->b_dep) != NULL)
3093		buf_complete(bp);
3094
3095	if (bp->b_flags & B_VMIO) {
3096		int i;
3097		vm_ooffset_t foff;
3098		vm_page_t m;
3099		vm_object_t obj;
3100		int iosize;
3101		struct vnode *vp = bp->b_vp;
3102
3103		obj = bp->b_object;
3104
3105#if defined(VFS_BIO_DEBUG)
3106		mp_fixme("usecount and vflag accessed without locks.");
3107		if (vp->v_usecount == 0) {
3108			panic("biodone: zero vnode ref count");
3109		}
3110
3111		if ((vp->v_vflag & VV_OBJBUF) == 0) {
3112			panic("biodone: vnode is not setup for merged cache");
3113		}
3114#endif
3115
3116		foff = bp->b_offset;
3117		KASSERT(bp->b_offset != NOOFFSET,
3118		    ("biodone: no buffer offset"));
3119
3120		if (obj != NULL)
3121			VM_OBJECT_LOCK(obj);
3122#if defined(VFS_BIO_DEBUG)
3123		if (obj->paging_in_progress < bp->b_npages) {
3124			printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
3125			    obj->paging_in_progress, bp->b_npages);
3126		}
3127#endif
3128
3129		/*
3130		 * Set B_CACHE if the op was a normal read and no error
3131		 * occured.  B_CACHE is set for writes in the b*write()
3132		 * routines.
3133		 */
3134		iosize = bp->b_bcount - bp->b_resid;
3135		if (bp->b_iocmd == BIO_READ &&
3136		    !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3137		    !(bp->b_ioflags & BIO_ERROR)) {
3138			bp->b_flags |= B_CACHE;
3139		}
3140		vm_page_lock_queues();
3141		for (i = 0; i < bp->b_npages; i++) {
3142			int bogusflag = 0;
3143			int resid;
3144
3145			resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3146			if (resid > iosize)
3147				resid = iosize;
3148
3149			/*
3150			 * cleanup bogus pages, restoring the originals
3151			 */
3152			m = bp->b_pages[i];
3153			if (m == bogus_page) {
3154				bogusflag = 1;
3155				m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3156				if (m == NULL)
3157					panic("biodone: page disappeared!");
3158				bp->b_pages[i] = m;
3159				pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
3160			}
3161#if defined(VFS_BIO_DEBUG)
3162			if (OFF_TO_IDX(foff) != m->pindex) {
3163				printf(
3164"biodone: foff(%jd)/m->pindex(%ju) mismatch\n",
3165				    (intmax_t)foff, (uintmax_t)m->pindex);
3166			}
3167#endif
3168
3169			/*
3170			 * In the write case, the valid and clean bits are
3171			 * already changed correctly ( see bdwrite() ), so we
3172			 * only need to do this here in the read case.
3173			 */
3174			if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3175				vfs_page_set_valid(bp, foff, i, m);
3176			}
3177			vm_page_flag_clear(m, PG_ZERO);
3178
3179			/*
3180			 * when debugging new filesystems or buffer I/O methods, this
3181			 * is the most common error that pops up.  if you see this, you
3182			 * have not set the page busy flag correctly!!!
3183			 */
3184			if (m->busy == 0) {
3185				printf("biodone: page busy < 0, "
3186				    "pindex: %d, foff: 0x(%x,%x), "
3187				    "resid: %d, index: %d\n",
3188				    (int) m->pindex, (int)(foff >> 32),
3189						(int) foff & 0xffffffff, resid, i);
3190				if (!vn_isdisk(vp, NULL))
3191					printf(" iosize: %ld, lblkno: %jd, flags: 0x%x, npages: %d\n",
3192					    bp->b_vp->v_mount->mnt_stat.f_iosize,
3193					    (intmax_t) bp->b_lblkno,
3194					    bp->b_flags, bp->b_npages);
3195				else
3196					printf(" VDEV, lblkno: %jd, flags: 0x%x, npages: %d\n",
3197					    (intmax_t) bp->b_lblkno,
3198					    bp->b_flags, bp->b_npages);
3199				printf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
3200				    m->valid, m->dirty, m->wire_count);
3201				panic("biodone: page busy < 0\n");
3202			}
3203			vm_page_io_finish(m);
3204			vm_object_pip_subtract(obj, 1);
3205			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3206			iosize -= resid;
3207		}
3208		vm_page_unlock_queues();
3209		if (obj != NULL) {
3210			vm_object_pip_wakeupn(obj, 0);
3211			VM_OBJECT_UNLOCK(obj);
3212		}
3213	}
3214
3215	/*
3216	 * For asynchronous completions, release the buffer now. The brelse
3217	 * will do a wakeup there if necessary - so no need to do a wakeup
3218	 * here in the async case. The sync case always needs to do a wakeup.
3219	 */
3220
3221	if (bp->b_flags & B_ASYNC) {
3222		if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3223			brelse(bp);
3224		else
3225			bqrelse(bp);
3226	} else {
3227		bdone(bp);
3228	}
3229	splx(s);
3230}
3231
3232/*
3233 * This routine is called in lieu of iodone in the case of
3234 * incomplete I/O.  This keeps the busy status for pages
3235 * consistant.
3236 */
3237void
3238vfs_unbusy_pages(struct buf * bp)
3239{
3240	int i;
3241
3242	GIANT_REQUIRED;
3243
3244	runningbufwakeup(bp);
3245	if (bp->b_flags & B_VMIO) {
3246		vm_object_t obj;
3247
3248		obj = bp->b_object;
3249		VM_OBJECT_LOCK(obj);
3250		vm_page_lock_queues();
3251		for (i = 0; i < bp->b_npages; i++) {
3252			vm_page_t m = bp->b_pages[i];
3253
3254			if (m == bogus_page) {
3255				m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3256				if (!m) {
3257					panic("vfs_unbusy_pages: page missing\n");
3258				}
3259				bp->b_pages[i] = m;
3260				pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
3261			}
3262			vm_object_pip_subtract(obj, 1);
3263			vm_page_flag_clear(m, PG_ZERO);
3264			vm_page_io_finish(m);
3265		}
3266		vm_page_unlock_queues();
3267		vm_object_pip_wakeupn(obj, 0);
3268		VM_OBJECT_UNLOCK(obj);
3269	}
3270}
3271
3272/*
3273 * vfs_page_set_valid:
3274 *
3275 *	Set the valid bits in a page based on the supplied offset.   The
3276 *	range is restricted to the buffer's size.
3277 *
3278 *	This routine is typically called after a read completes.
3279 */
3280static void
3281vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3282{
3283	vm_ooffset_t soff, eoff;
3284
3285	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
3286	/*
3287	 * Start and end offsets in buffer.  eoff - soff may not cross a
3288	 * page boundry or cross the end of the buffer.  The end of the
3289	 * buffer, in this case, is our file EOF, not the allocation size
3290	 * of the buffer.
3291	 */
3292	soff = off;
3293	eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3294	if (eoff > bp->b_offset + bp->b_bcount)
3295		eoff = bp->b_offset + bp->b_bcount;
3296
3297	/*
3298	 * Set valid range.  This is typically the entire buffer and thus the
3299	 * entire page.
3300	 */
3301	if (eoff > soff) {
3302		vm_page_set_validclean(
3303		    m,
3304		   (vm_offset_t) (soff & PAGE_MASK),
3305		   (vm_offset_t) (eoff - soff)
3306		);
3307	}
3308}
3309
3310/*
3311 * This routine is called before a device strategy routine.
3312 * It is used to tell the VM system that paging I/O is in
3313 * progress, and treat the pages associated with the buffer
3314 * almost as being PG_BUSY.  Also the object paging_in_progress
3315 * flag is handled to make sure that the object doesn't become
3316 * inconsistant.
3317 *
3318 * Since I/O has not been initiated yet, certain buffer flags
3319 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
3320 * and should be ignored.
3321 */
3322void
3323vfs_busy_pages(struct buf * bp, int clear_modify)
3324{
3325	int i, bogus;
3326
3327	if (bp->b_flags & B_VMIO) {
3328		vm_object_t obj;
3329		vm_ooffset_t foff;
3330
3331		obj = bp->b_object;
3332		foff = bp->b_offset;
3333		KASSERT(bp->b_offset != NOOFFSET,
3334		    ("vfs_busy_pages: no buffer offset"));
3335		vfs_setdirty(bp);
3336		if (obj != NULL)
3337			VM_OBJECT_LOCK(obj);
3338retry:
3339		vm_page_lock_queues();
3340		for (i = 0; i < bp->b_npages; i++) {
3341			vm_page_t m = bp->b_pages[i];
3342
3343			if (vm_page_sleep_if_busy(m, FALSE, "vbpage"))
3344				goto retry;
3345		}
3346		bogus = 0;
3347		for (i = 0; i < bp->b_npages; i++) {
3348			vm_page_t m = bp->b_pages[i];
3349
3350			vm_page_flag_clear(m, PG_ZERO);
3351			if ((bp->b_flags & B_CLUSTER) == 0) {
3352				vm_object_pip_add(obj, 1);
3353				vm_page_io_start(m);
3354			}
3355			/*
3356			 * When readying a buffer for a read ( i.e
3357			 * clear_modify == 0 ), it is important to do
3358			 * bogus_page replacement for valid pages in
3359			 * partially instantiated buffers.  Partially
3360			 * instantiated buffers can, in turn, occur when
3361			 * reconstituting a buffer from its VM backing store
3362			 * base.  We only have to do this if B_CACHE is
3363			 * clear ( which causes the I/O to occur in the
3364			 * first place ).  The replacement prevents the read
3365			 * I/O from overwriting potentially dirty VM-backed
3366			 * pages.  XXX bogus page replacement is, uh, bogus.
3367			 * It may not work properly with small-block devices.
3368			 * We need to find a better way.
3369			 */
3370			pmap_remove_all(m);
3371			if (clear_modify)
3372				vfs_page_set_valid(bp, foff, i, m);
3373			else if (m->valid == VM_PAGE_BITS_ALL &&
3374				(bp->b_flags & B_CACHE) == 0) {
3375				bp->b_pages[i] = bogus_page;
3376				bogus++;
3377			}
3378			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3379		}
3380		vm_page_unlock_queues();
3381		if (obj != NULL)
3382			VM_OBJECT_UNLOCK(obj);
3383		if (bogus)
3384			pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
3385	}
3386}
3387
3388/*
3389 * Tell the VM system that the pages associated with this buffer
3390 * are clean.  This is used for delayed writes where the data is
3391 * going to go to disk eventually without additional VM intevention.
3392 *
3393 * Note that while we only really need to clean through to b_bcount, we
3394 * just go ahead and clean through to b_bufsize.
3395 */
3396static void
3397vfs_clean_pages(struct buf * bp)
3398{
3399	int i;
3400
3401	GIANT_REQUIRED;
3402
3403	if (bp->b_flags & B_VMIO) {
3404		vm_ooffset_t foff;
3405
3406		foff = bp->b_offset;
3407		KASSERT(bp->b_offset != NOOFFSET,
3408		    ("vfs_clean_pages: no buffer offset"));
3409		vm_page_lock_queues();
3410		for (i = 0; i < bp->b_npages; i++) {
3411			vm_page_t m = bp->b_pages[i];
3412			vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3413			vm_ooffset_t eoff = noff;
3414
3415			if (eoff > bp->b_offset + bp->b_bufsize)
3416				eoff = bp->b_offset + bp->b_bufsize;
3417			vfs_page_set_valid(bp, foff, i, m);
3418			/* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3419			foff = noff;
3420		}
3421		vm_page_unlock_queues();
3422	}
3423}
3424
3425/*
3426 *	vfs_bio_set_validclean:
3427 *
3428 *	Set the range within the buffer to valid and clean.  The range is
3429 *	relative to the beginning of the buffer, b_offset.  Note that b_offset
3430 *	itself may be offset from the beginning of the first page.
3431 *
3432 */
3433
3434void
3435vfs_bio_set_validclean(struct buf *bp, int base, int size)
3436{
3437	if (bp->b_flags & B_VMIO) {
3438		int i;
3439		int n;
3440
3441		/*
3442		 * Fixup base to be relative to beginning of first page.
3443		 * Set initial n to be the maximum number of bytes in the
3444		 * first page that can be validated.
3445		 */
3446
3447		base += (bp->b_offset & PAGE_MASK);
3448		n = PAGE_SIZE - (base & PAGE_MASK);
3449
3450		vm_page_lock_queues();
3451		for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3452			vm_page_t m = bp->b_pages[i];
3453
3454			if (n > size)
3455				n = size;
3456
3457			vm_page_set_validclean(m, base & PAGE_MASK, n);
3458			base += n;
3459			size -= n;
3460			n = PAGE_SIZE;
3461		}
3462		vm_page_unlock_queues();
3463	}
3464}
3465
3466/*
3467 *	vfs_bio_clrbuf:
3468 *
3469 *	clear a buffer.  This routine essentially fakes an I/O, so we need
3470 *	to clear BIO_ERROR and B_INVAL.
3471 *
3472 *	Note that while we only theoretically need to clear through b_bcount,
3473 *	we go ahead and clear through b_bufsize.
3474 */
3475
3476void
3477vfs_bio_clrbuf(struct buf *bp)
3478{
3479	int i, mask = 0;
3480	caddr_t sa, ea;
3481
3482	GIANT_REQUIRED;
3483
3484	if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3485		bp->b_flags &= ~B_INVAL;
3486		bp->b_ioflags &= ~BIO_ERROR;
3487		if( (bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3488		    (bp->b_offset & PAGE_MASK) == 0) {
3489			mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3490			if ((bp->b_pages[0]->valid & mask) == mask) {
3491				bp->b_resid = 0;
3492				return;
3493			}
3494			if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
3495			    ((bp->b_pages[0]->valid & mask) == 0)) {
3496				bzero(bp->b_data, bp->b_bufsize);
3497				bp->b_pages[0]->valid |= mask;
3498				bp->b_resid = 0;
3499				return;
3500			}
3501		}
3502		ea = sa = bp->b_data;
3503		for(i=0;i<bp->b_npages;i++,sa=ea) {
3504			int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3505			ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3506			ea = (caddr_t)(vm_offset_t)ulmin(
3507			    (u_long)(vm_offset_t)ea,
3508			    (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3509			mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3510			if ((bp->b_pages[i]->valid & mask) == mask)
3511				continue;
3512			if ((bp->b_pages[i]->valid & mask) == 0) {
3513				if ((bp->b_pages[i]->flags & PG_ZERO) == 0) {
3514					bzero(sa, ea - sa);
3515				}
3516			} else {
3517				for (; sa < ea; sa += DEV_BSIZE, j++) {
3518					if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
3519						(bp->b_pages[i]->valid & (1<<j)) == 0)
3520						bzero(sa, DEV_BSIZE);
3521				}
3522			}
3523			bp->b_pages[i]->valid |= mask;
3524			vm_page_lock_queues();
3525			vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
3526			vm_page_unlock_queues();
3527		}
3528		bp->b_resid = 0;
3529	} else {
3530		clrbuf(bp);
3531	}
3532}
3533
3534/*
3535 * vm_hold_load_pages and vm_hold_free_pages get pages into
3536 * a buffers address space.  The pages are anonymous and are
3537 * not associated with a file object.
3538 */
3539static void
3540vm_hold_load_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3541{
3542	vm_offset_t pg;
3543	vm_page_t p;
3544	int index;
3545
3546	GIANT_REQUIRED;
3547
3548	to = round_page(to);
3549	from = round_page(from);
3550	index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3551
3552	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3553tryagain:
3554		/*
3555		 * note: must allocate system pages since blocking here
3556		 * could intefere with paging I/O, no matter which
3557		 * process we are.
3558		 */
3559		VM_OBJECT_LOCK(kernel_object);
3560		p = vm_page_alloc(kernel_object,
3561			((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3562		    VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
3563		VM_OBJECT_UNLOCK(kernel_object);
3564		if (!p) {
3565			atomic_add_int(&vm_pageout_deficit,
3566			    (to - pg) >> PAGE_SHIFT);
3567			VM_WAIT;
3568			goto tryagain;
3569		}
3570		vm_page_lock_queues();
3571		p->valid = VM_PAGE_BITS_ALL;
3572		vm_page_unlock_queues();
3573		pmap_qenter(pg, &p, 1);
3574		bp->b_pages[index] = p;
3575		vm_page_lock_queues();
3576		vm_page_wakeup(p);
3577		vm_page_unlock_queues();
3578	}
3579	bp->b_npages = index;
3580}
3581
3582/* Return pages associated with this buf to the vm system */
3583static void
3584vm_hold_free_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3585{
3586	vm_offset_t pg;
3587	vm_page_t p;
3588	int index, newnpages;
3589
3590	GIANT_REQUIRED;
3591
3592	from = round_page(from);
3593	to = round_page(to);
3594	newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3595
3596	if (bp->b_object != NULL)
3597		VM_OBJECT_LOCK(bp->b_object);
3598	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3599		p = bp->b_pages[index];
3600		if (p && (index < bp->b_npages)) {
3601			if (p->busy) {
3602				printf(
3603			    "vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
3604				    (intmax_t)bp->b_blkno,
3605				    (intmax_t)bp->b_lblkno);
3606			}
3607			bp->b_pages[index] = NULL;
3608			pmap_qremove(pg, 1);
3609			vm_page_lock_queues();
3610			vm_page_busy(p);
3611			vm_page_unwire(p, 0);
3612			vm_page_free(p);
3613			vm_page_unlock_queues();
3614		}
3615	}
3616	if (bp->b_object != NULL)
3617		VM_OBJECT_UNLOCK(bp->b_object);
3618	bp->b_npages = newnpages;
3619}
3620
3621/*
3622 * Map an IO request into kernel virtual address space.
3623 *
3624 * All requests are (re)mapped into kernel VA space.
3625 * Notice that we use b_bufsize for the size of the buffer
3626 * to be mapped.  b_bcount might be modified by the driver.
3627 *
3628 * Note that even if the caller determines that the address space should
3629 * be valid, a race or a smaller-file mapped into a larger space may
3630 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
3631 * check the return value.
3632 */
3633int
3634vmapbuf(struct buf *bp)
3635{
3636	caddr_t addr, kva;
3637	vm_paddr_t pa;
3638	int pidx, i;
3639	struct vm_page *m;
3640	struct pmap *pmap = &curproc->p_vmspace->vm_pmap;
3641
3642	GIANT_REQUIRED;
3643
3644	if ((bp->b_flags & B_PHYS) == 0)
3645		panic("vmapbuf");
3646	if (bp->b_bufsize < 0)
3647		return (-1);
3648	for (addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data), pidx = 0;
3649	     addr < bp->b_data + bp->b_bufsize;
3650	     addr += PAGE_SIZE, pidx++) {
3651		/*
3652		 * Do the vm_fault if needed; do the copy-on-write thing
3653		 * when reading stuff off device into memory.
3654		 *
3655		 * NOTE! Must use pmap_extract() because addr may be in
3656		 * the userland address space, and kextract is only guarenteed
3657		 * to work for the kernland address space (see: sparc64 port).
3658		 */
3659retry:
3660		i = vm_fault_quick((addr >= bp->b_data) ? addr : bp->b_data,
3661			(bp->b_iocmd == BIO_READ) ?
3662			(VM_PROT_READ|VM_PROT_WRITE) : VM_PROT_READ);
3663		if (i < 0) {
3664			vm_page_lock_queues();
3665			for (i = 0; i < pidx; ++i) {
3666				vm_page_unhold(bp->b_pages[i]);
3667				bp->b_pages[i] = NULL;
3668			}
3669			vm_page_unlock_queues();
3670			return(-1);
3671		}
3672		pa = pmap_extract(pmap, (vm_offset_t)addr);
3673		if (pa == 0) {
3674			printf("vmapbuf: warning, race against user address during I/O");
3675			goto retry;
3676		}
3677		m = PHYS_TO_VM_PAGE(pa);
3678		vm_page_lock_queues();
3679		vm_page_hold(m);
3680		vm_page_unlock_queues();
3681		bp->b_pages[pidx] = m;
3682	}
3683	if (pidx > btoc(MAXPHYS))
3684		panic("vmapbuf: mapped more than MAXPHYS");
3685	pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
3686
3687	kva = bp->b_saveaddr;
3688	bp->b_npages = pidx;
3689	bp->b_saveaddr = bp->b_data;
3690	bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3691	return(0);
3692}
3693
3694/*
3695 * Free the io map PTEs associated with this IO operation.
3696 * We also invalidate the TLB entries and restore the original b_addr.
3697 */
3698void
3699vunmapbuf(struct buf *bp)
3700{
3701	int pidx;
3702	int npages;
3703
3704	GIANT_REQUIRED;
3705
3706	if ((bp->b_flags & B_PHYS) == 0)
3707		panic("vunmapbuf");
3708
3709	npages = bp->b_npages;
3710	pmap_qremove(trunc_page((vm_offset_t)bp->b_data),
3711		     npages);
3712	vm_page_lock_queues();
3713	for (pidx = 0; pidx < npages; pidx++)
3714		vm_page_unhold(bp->b_pages[pidx]);
3715	vm_page_unlock_queues();
3716
3717	bp->b_data = bp->b_saveaddr;
3718}
3719
3720void
3721bdone(struct buf *bp)
3722{
3723	mtx_lock(&bdonelock);
3724	bp->b_flags |= B_DONE;
3725	wakeup(bp);
3726	mtx_unlock(&bdonelock);
3727}
3728
3729void
3730bwait(struct buf *bp, u_char pri, const char *wchan)
3731{
3732	mtx_lock(&bdonelock);
3733	while ((bp->b_flags & B_DONE) == 0)
3734		msleep(bp, &bdonelock, pri, wchan, 0);
3735	mtx_unlock(&bdonelock);
3736}
3737
3738#include "opt_ddb.h"
3739#ifdef DDB
3740#include <ddb/ddb.h>
3741
3742/* DDB command to show buffer data */
3743DB_SHOW_COMMAND(buffer, db_show_buffer)
3744{
3745	/* get args */
3746	struct buf *bp = (struct buf *)addr;
3747
3748	if (!have_addr) {
3749		db_printf("usage: show buffer <addr>\n");
3750		return;
3751	}
3752
3753	db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3754	db_printf(
3755	    "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
3756	    "b_dev = (%d,%d), b_data = %p, b_blkno = %jd, b_pblkno = %jd\n",
3757	    bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3758	    major(bp->b_dev), minor(bp->b_dev), bp->b_data,
3759	    (intmax_t)bp->b_blkno, (intmax_t)bp->b_pblkno);
3760	if (bp->b_npages) {
3761		int i;
3762		db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
3763		for (i = 0; i < bp->b_npages; i++) {
3764			vm_page_t m;
3765			m = bp->b_pages[i];
3766			db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3767			    (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3768			if ((i + 1) < bp->b_npages)
3769				db_printf(",");
3770		}
3771		db_printf("\n");
3772	}
3773}
3774#endif /* DDB */
3775