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