2 * Copyright (c) 2004 Poul-Henning Kamp
3 * Copyright (c) 1994,1997 John S. Dyson
4 * Copyright (c) 2013 The FreeBSD Foundation
7 * Portions of this software were developed by Konstantin Belousov
8 * under sponsorship from the FreeBSD Foundation.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * this file contains a new buffer I/O scheme implementing a coherent
34 * VM object and buffer cache scheme. Pains have been taken to make
35 * sure that the performance degradation associated with schemes such
36 * as this is not realized.
38 * Author: John S. Dyson
39 * Significant help during the development and debugging phases
40 * had been provided by David Greenman, also of the FreeBSD core team.
42 * see man buf(9) for more info.
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
48 #include <sys/param.h>
49 #include <sys/systm.h>
53 #include <sys/devicestat.h>
54 #include <sys/eventhandler.h>
56 #include <sys/limits.h>
58 #include <sys/malloc.h>
59 #include <sys/mount.h>
60 #include <sys/mutex.h>
61 #include <sys/kernel.h>
62 #include <sys/kthread.h>
64 #include <sys/resourcevar.h>
65 #include <sys/sysctl.h>
66 #include <sys/vmmeter.h>
67 #include <sys/vnode.h>
68 #include <geom/geom.h>
70 #include <vm/vm_param.h>
71 #include <vm/vm_kern.h>
72 #include <vm/vm_pageout.h>
73 #include <vm/vm_page.h>
74 #include <vm/vm_object.h>
75 #include <vm/vm_extern.h>
76 #include <vm/vm_map.h>
77 #include "opt_compat.h"
78 #include "opt_directio.h"
81 static MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
83 struct bio_ops bioops; /* I/O operation notification */
85 struct buf_ops buf_ops_bio = {
86 .bop_name = "buf_ops_bio",
87 .bop_write = bufwrite,
88 .bop_strategy = bufstrategy,
90 .bop_bdflush = bufbdflush,
94 * XXX buf is global because kern_shutdown.c and ffs_checkoverlap has
95 * carnal knowledge of buffers. This knowledge should be moved to vfs_bio.c.
97 struct buf *buf; /* buffer header pool */
100 static struct proc *bufdaemonproc;
102 static int inmem(struct vnode *vp, daddr_t blkno);
103 static void vm_hold_free_pages(struct buf *bp, int newbsize);
104 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
106 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m);
107 static void vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off,
109 static void vfs_drain_busy_pages(struct buf *bp);
110 static void vfs_clean_pages_dirty_buf(struct buf *bp);
111 static void vfs_setdirty_locked_object(struct buf *bp);
112 static void vfs_vmio_release(struct buf *bp);
113 static int vfs_bio_clcheck(struct vnode *vp, int size,
114 daddr_t lblkno, daddr_t blkno);
115 static int buf_do_flush(struct vnode *vp);
116 static int flushbufqueues(struct vnode *, int, int);
117 static void buf_daemon(void);
118 static void bremfreel(struct buf *bp);
119 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
120 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
121 static int sysctl_bufspace(SYSCTL_HANDLER_ARGS);
124 int vmiodirenable = TRUE;
125 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
126 "Use the VM system for directory writes");
127 long runningbufspace;
128 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
129 "Amount of presently outstanding async buffer io");
130 static long bufspace;
131 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
132 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
133 SYSCTL_PROC(_vfs, OID_AUTO, bufspace, CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RD,
134 &bufspace, 0, sysctl_bufspace, "L", "Virtual memory used for buffers");
136 SYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
137 "Virtual memory used for buffers");
139 static long unmapped_bufspace;
140 SYSCTL_LONG(_vfs, OID_AUTO, unmapped_bufspace, CTLFLAG_RD,
141 &unmapped_bufspace, 0,
142 "Amount of unmapped buffers, inclusive in the bufspace");
143 static long maxbufspace;
144 SYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
145 "Maximum allowed value of bufspace (including buf_daemon)");
146 static long bufmallocspace;
147 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
148 "Amount of malloced memory for buffers");
149 static long maxbufmallocspace;
150 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace, 0,
151 "Maximum amount of malloced memory for buffers");
152 static long lobufspace;
153 SYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
154 "Minimum amount of buffers we want to have");
156 SYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
157 "Maximum allowed value of bufspace (excluding buf_daemon)");
158 static int bufreusecnt;
159 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW, &bufreusecnt, 0,
160 "Number of times we have reused a buffer");
161 static int buffreekvacnt;
162 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
163 "Number of times we have freed the KVA space from some buffer");
164 static int bufdefragcnt;
165 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
166 "Number of times we have had to repeat buffer allocation to defragment");
167 static long lorunningspace;
168 SYSCTL_LONG(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
169 "Minimum preferred space used for in-progress I/O");
170 static long hirunningspace;
171 SYSCTL_LONG(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
172 "Maximum amount of space to use for in-progress I/O");
173 int dirtybufferflushes;
174 SYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
175 0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
177 SYSCTL_INT(_vfs, OID_AUTO, bdwriteskip, CTLFLAG_RW, &bdwriteskip,
178 0, "Number of buffers supplied to bdwrite with snapshot deadlock risk");
179 int altbufferflushes;
180 SYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes,
181 0, "Number of fsync flushes to limit dirty buffers");
182 static int recursiveflushes;
183 SYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes,
184 0, "Number of flushes skipped due to being recursive");
185 static int numdirtybuffers;
186 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
187 "Number of buffers that are dirty (has unwritten changes) at the moment");
188 static int lodirtybuffers;
189 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
190 "How many buffers we want to have free before bufdaemon can sleep");
191 static int hidirtybuffers;
192 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
193 "When the number of dirty buffers is considered severe");
195 SYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh,
196 0, "Number of bdwrite to bawrite conversions to clear dirty buffers");
197 static int numfreebuffers;
198 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
199 "Number of free buffers");
200 static int lofreebuffers;
201 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
203 static int hifreebuffers;
204 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
205 "XXX Complicatedly unused");
206 static int getnewbufcalls;
207 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
208 "Number of calls to getnewbuf");
209 static int getnewbufrestarts;
210 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
211 "Number of times getnewbuf has had to restart a buffer aquisition");
212 static int mappingrestarts;
213 SYSCTL_INT(_vfs, OID_AUTO, mappingrestarts, CTLFLAG_RW, &mappingrestarts, 0,
214 "Number of times getblk has had to restart a buffer mapping for "
216 static int flushbufqtarget = 100;
217 SYSCTL_INT(_vfs, OID_AUTO, flushbufqtarget, CTLFLAG_RW, &flushbufqtarget, 0,
218 "Amount of work to do in flushbufqueues when helping bufdaemon");
219 static long notbufdflashes;
220 SYSCTL_LONG(_vfs, OID_AUTO, notbufdflashes, CTLFLAG_RD, ¬bufdflashes, 0,
221 "Number of dirty buffer flushes done by the bufdaemon helpers");
222 static long barrierwrites;
223 SYSCTL_LONG(_vfs, OID_AUTO, barrierwrites, CTLFLAG_RW, &barrierwrites, 0,
224 "Number of barrier writes");
225 SYSCTL_INT(_vfs, OID_AUTO, unmapped_buf_allowed, CTLFLAG_RD,
226 &unmapped_buf_allowed, 0,
227 "Permit the use of the unmapped i/o");
230 * Wakeup point for bufdaemon, as well as indicator of whether it is already
231 * active. Set to 1 when the bufdaemon is already "on" the queue, 0 when it
234 static int bd_request;
237 * Request for the buf daemon to write more buffers than is indicated by
238 * lodirtybuf. This may be necessary to push out excess dependencies or
239 * defragment the address space where a simple count of the number of dirty
240 * buffers is insufficient to characterize the demand for flushing them.
242 static int bd_speedupreq;
245 * This lock synchronizes access to bd_request.
247 static struct mtx bdlock;
250 * bogus page -- for I/O to/from partially complete buffers
251 * this is a temporary solution to the problem, but it is not
252 * really that bad. it would be better to split the buffer
253 * for input in the case of buffers partially already in memory,
254 * but the code is intricate enough already.
256 vm_page_t bogus_page;
259 * Synchronization (sleep/wakeup) variable for active buffer space requests.
260 * Set when wait starts, cleared prior to wakeup().
261 * Used in runningbufwakeup() and waitrunningbufspace().
263 static int runningbufreq;
266 * This lock protects the runningbufreq and synchronizes runningbufwakeup and
267 * waitrunningbufspace().
269 static struct mtx rbreqlock;
272 * Synchronization (sleep/wakeup) variable for buffer requests.
273 * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
275 * Used in numdirtywakeup(), bufspacewakeup(), bufcountwakeup(), bwillwrite(),
276 * getnewbuf(), and getblk().
278 static int needsbuffer;
281 * Lock that protects needsbuffer and the sleeps/wakeups surrounding it.
283 static struct mtx nblock;
286 * Definitions for the buffer free lists.
288 #define BUFFER_QUEUES 6 /* number of free buffer queues */
290 #define QUEUE_NONE 0 /* on no queue */
291 #define QUEUE_CLEAN 1 /* non-B_DELWRI buffers */
292 #define QUEUE_DIRTY 2 /* B_DELWRI buffers */
293 #define QUEUE_DIRTY_GIANT 3 /* B_DELWRI buffers that need giant */
294 #define QUEUE_EMPTYKVA 4 /* empty buffer headers w/KVA assignment */
295 #define QUEUE_EMPTY 5 /* empty buffer headers */
296 #define QUEUE_SENTINEL 1024 /* not an queue index, but mark for sentinel */
298 /* Queues for free buffers with various properties */
299 static TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
301 static int bq_len[BUFFER_QUEUES];
304 /* Lock for the bufqueues */
305 static struct mtx bqlock;
308 * Single global constant for BUF_WMESG, to avoid getting multiple references.
309 * buf_wmesg is referred from macros.
311 const char *buf_wmesg = BUF_WMESG;
313 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
314 #define VFS_BIO_NEED_DIRTYFLUSH 0x02 /* waiting for dirty buffer flush */
315 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
316 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
318 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
319 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
321 sysctl_bufspace(SYSCTL_HANDLER_ARGS)
326 if (sizeof(int) == sizeof(long) || req->oldlen >= sizeof(long))
327 return (sysctl_handle_long(oidp, arg1, arg2, req));
328 lvalue = *(long *)arg1;
329 if (lvalue > INT_MAX)
330 /* On overflow, still write out a long to trigger ENOMEM. */
331 return (sysctl_handle_long(oidp, &lvalue, 0, req));
333 return (sysctl_handle_int(oidp, &ivalue, 0, req));
338 extern void ffs_rawread_setup(void);
339 #endif /* DIRECTIO */
343 * If someone is blocked due to there being too many dirty buffers,
344 * and numdirtybuffers is now reasonable, wake them up.
348 numdirtywakeup(int level)
351 if (numdirtybuffers <= level) {
353 if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
354 needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
355 wakeup(&needsbuffer);
364 * Called when buffer space is potentially available for recovery.
365 * getnewbuf() will block on this flag when it is unable to free
366 * sufficient buffer space. Buffer space becomes recoverable when
367 * bp's get placed back in the queues.
375 * If someone is waiting for BUF space, wake them up. Even
376 * though we haven't freed the kva space yet, the waiting
377 * process will be able to now.
380 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
381 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
382 wakeup(&needsbuffer);
388 * runningbufwakeup() - in-progress I/O accounting.
392 runningbufwakeup(struct buf *bp)
395 if (bp->b_runningbufspace) {
396 atomic_subtract_long(&runningbufspace, bp->b_runningbufspace);
397 bp->b_runningbufspace = 0;
398 mtx_lock(&rbreqlock);
399 if (runningbufreq && runningbufspace <= lorunningspace) {
401 wakeup(&runningbufreq);
403 mtx_unlock(&rbreqlock);
410 * Called when a buffer has been added to one of the free queues to
411 * account for the buffer and to wakeup anyone waiting for free buffers.
412 * This typically occurs when large amounts of metadata are being handled
413 * by the buffer cache ( else buffer space runs out first, usually ).
417 bufcountwakeup(struct buf *bp)
421 KASSERT((bp->b_vflags & BV_INFREECNT) == 0,
422 ("buf %p already counted as free", bp));
423 if (bp->b_bufobj != NULL)
424 mtx_assert(BO_MTX(bp->b_bufobj), MA_OWNED);
425 bp->b_vflags |= BV_INFREECNT;
426 old = atomic_fetchadd_int(&numfreebuffers, 1);
427 KASSERT(old >= 0 && old < nbuf,
428 ("numfreebuffers climbed to %d", old + 1));
431 needsbuffer &= ~VFS_BIO_NEED_ANY;
432 if (numfreebuffers >= hifreebuffers)
433 needsbuffer &= ~VFS_BIO_NEED_FREE;
434 wakeup(&needsbuffer);
440 * waitrunningbufspace()
442 * runningbufspace is a measure of the amount of I/O currently
443 * running. This routine is used in async-write situations to
444 * prevent creating huge backups of pending writes to a device.
445 * Only asynchronous writes are governed by this function.
447 * Reads will adjust runningbufspace, but will not block based on it.
448 * The read load has a side effect of reducing the allowed write load.
450 * This does NOT turn an async write into a sync write. It waits
451 * for earlier writes to complete and generally returns before the
452 * caller's write has reached the device.
455 waitrunningbufspace(void)
458 mtx_lock(&rbreqlock);
459 while (runningbufspace > hirunningspace) {
461 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
463 mtx_unlock(&rbreqlock);
468 * vfs_buf_test_cache:
470 * Called when a buffer is extended. This function clears the B_CACHE
471 * bit if the newly extended portion of the buffer does not contain
476 vfs_buf_test_cache(struct buf *bp,
477 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
481 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
482 if (bp->b_flags & B_CACHE) {
483 int base = (foff + off) & PAGE_MASK;
484 if (vm_page_is_valid(m, base, size) == 0)
485 bp->b_flags &= ~B_CACHE;
489 /* Wake up the buffer daemon if necessary */
492 bd_wakeup(int dirtybuflevel)
496 if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
504 * bd_speedup - speedup the buffer cache flushing code
514 if (bd_speedupreq == 0 || bd_request == 0)
524 #define TRANSIENT_DENOM 5
526 #define TRANSIENT_DENOM 10
530 * Calculating buffer cache scaling values and reserve space for buffer
531 * headers. This is called during low level kernel initialization and
532 * may be called more then once. We CANNOT write to the memory area
533 * being reserved at this time.
536 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
539 long maxbuf, maxbuf_sz, buf_sz, biotmap_sz;
542 * physmem_est is in pages. Convert it to kilobytes (assumes
543 * PAGE_SIZE is >= 1K)
545 physmem_est = physmem_est * (PAGE_SIZE / 1024);
548 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
549 * For the first 64MB of ram nominally allocate sufficient buffers to
550 * cover 1/4 of our ram. Beyond the first 64MB allocate additional
551 * buffers to cover 1/10 of our ram over 64MB. When auto-sizing
552 * the buffer cache we limit the eventual kva reservation to
555 * factor represents the 1/4 x ram conversion.
558 int factor = 4 * BKVASIZE / 1024;
561 if (physmem_est > 4096)
562 nbuf += min((physmem_est - 4096) / factor,
564 if (physmem_est > 65536)
565 nbuf += min((physmem_est - 65536) * 2 / (factor * 5),
566 32 * 1024 * 1024 / (factor * 5));
568 if (maxbcache && nbuf > maxbcache / BKVASIZE)
569 nbuf = maxbcache / BKVASIZE;
574 /* XXX Avoid unsigned long overflows later on with maxbufspace. */
575 maxbuf = (LONG_MAX / 3) / BKVASIZE;
578 printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
584 * Ideal allocation size for the transient bio submap if 10%
585 * of the maximal space buffer map. This roughly corresponds
586 * to the amount of the buffer mapped for typical UFS load.
588 * Clip the buffer map to reserve space for the transient
589 * BIOs, if its extent is bigger than 90% (80% on i386) of the
590 * maximum buffer map extent on the platform.
592 * The fall-back to the maxbuf in case of maxbcache unset,
593 * allows to not trim the buffer KVA for the architectures
594 * with ample KVA space.
596 if (bio_transient_maxcnt == 0) {
597 maxbuf_sz = maxbcache != 0 ? maxbcache : maxbuf * BKVASIZE;
598 buf_sz = (long)nbuf * BKVASIZE;
599 if (buf_sz < maxbuf_sz / TRANSIENT_DENOM *
600 (TRANSIENT_DENOM - 1)) {
602 * There is more KVA than memory. Do not
603 * adjust buffer map size, and assign the rest
604 * of maxbuf to transient map.
606 biotmap_sz = maxbuf_sz - buf_sz;
609 * Buffer map spans all KVA we could afford on
610 * this platform. Give 10% (20% on i386) of
611 * the buffer map to the transient bio map.
613 biotmap_sz = buf_sz / TRANSIENT_DENOM;
614 buf_sz -= biotmap_sz;
616 if (biotmap_sz / INT_MAX > MAXPHYS)
617 bio_transient_maxcnt = INT_MAX;
619 bio_transient_maxcnt = biotmap_sz / MAXPHYS;
621 * Artifically limit to 1024 simultaneous in-flight I/Os
622 * using the transient mapping.
624 if (bio_transient_maxcnt > 1024)
625 bio_transient_maxcnt = 1024;
627 nbuf = buf_sz / BKVASIZE;
631 * swbufs are used as temporary holders for I/O, such as paging I/O.
632 * We have no less then 16 and no more then 256.
634 nswbuf = max(min(nbuf/4, 256), 16);
636 if (nswbuf < NSWBUF_MIN)
644 * Reserve space for the buffer cache buffers
647 v = (caddr_t)(swbuf + nswbuf);
649 v = (caddr_t)(buf + nbuf);
654 /* Initialize the buffer subsystem. Called before use of any buffers. */
661 mtx_init(&bqlock, "buf queue lock", NULL, MTX_DEF);
662 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
663 mtx_init(&nblock, "needsbuffer lock", NULL, MTX_DEF);
664 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
666 /* next, make a null set of free lists */
667 for (i = 0; i < BUFFER_QUEUES; i++)
668 TAILQ_INIT(&bufqueues[i]);
670 /* finally, initialize each buffer header and stick on empty q */
671 for (i = 0; i < nbuf; i++) {
673 bzero(bp, sizeof *bp);
674 bp->b_flags = B_INVAL; /* we're just an empty header */
675 bp->b_rcred = NOCRED;
676 bp->b_wcred = NOCRED;
677 bp->b_qindex = QUEUE_EMPTY;
678 bp->b_vflags = BV_INFREECNT; /* buf is counted as free */
680 LIST_INIT(&bp->b_dep);
682 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
684 bq_len[QUEUE_EMPTY]++;
689 * maxbufspace is the absolute maximum amount of buffer space we are
690 * allowed to reserve in KVM and in real terms. The absolute maximum
691 * is nominally used by buf_daemon. hibufspace is the nominal maximum
692 * used by most other processes. The differential is required to
693 * ensure that buf_daemon is able to run when other processes might
694 * be blocked waiting for buffer space.
696 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
697 * this may result in KVM fragmentation which is not handled optimally
700 maxbufspace = (long)nbuf * BKVASIZE;
701 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
702 lobufspace = hibufspace - MAXBSIZE;
705 * Note: The 16 MiB upper limit for hirunningspace was chosen
706 * arbitrarily and may need further tuning. It corresponds to
707 * 128 outstanding write IO requests (if IO size is 128 KiB),
708 * which fits with many RAID controllers' tagged queuing limits.
709 * The lower 1 MiB limit is the historical upper limit for
712 hirunningspace = lmax(lmin(roundup(hibufspace / 64, MAXBSIZE),
713 16 * 1024 * 1024), 1024 * 1024);
714 lorunningspace = roundup((hirunningspace * 2) / 3, MAXBSIZE);
717 * Limit the amount of malloc memory since it is wired permanently into
718 * the kernel space. Even though this is accounted for in the buffer
719 * allocation, we don't want the malloced region to grow uncontrolled.
720 * The malloc scheme improves memory utilization significantly on average
721 * (small) directories.
723 maxbufmallocspace = hibufspace / 20;
726 * Reduce the chance of a deadlock occuring by limiting the number
727 * of delayed-write dirty buffers we allow to stack up.
729 hidirtybuffers = nbuf / 4 + 20;
730 dirtybufthresh = hidirtybuffers * 9 / 10;
733 * To support extreme low-memory systems, make sure hidirtybuffers cannot
734 * eat up all available buffer space. This occurs when our minimum cannot
735 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
736 * BKVASIZE'd buffers.
738 while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
739 hidirtybuffers >>= 1;
741 lodirtybuffers = hidirtybuffers / 2;
744 * Try to keep the number of free buffers in the specified range,
745 * and give special processes (e.g. like buf_daemon) access to an
748 lofreebuffers = nbuf / 18 + 5;
749 hifreebuffers = 2 * lofreebuffers;
750 numfreebuffers = nbuf;
752 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
753 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
754 unmapped_buf = (caddr_t)kmem_alloc_nofault(kernel_map, MAXPHYS);
759 vfs_buf_check_mapped(struct buf *bp)
762 KASSERT((bp->b_flags & B_UNMAPPED) == 0,
763 ("mapped buf %p %x", bp, bp->b_flags));
764 KASSERT(bp->b_kvabase != unmapped_buf,
765 ("mapped buf: b_kvabase was not updated %p", bp));
766 KASSERT(bp->b_data != unmapped_buf,
767 ("mapped buf: b_data was not updated %p", bp));
771 vfs_buf_check_unmapped(struct buf *bp)
774 KASSERT((bp->b_flags & B_UNMAPPED) == B_UNMAPPED,
775 ("unmapped buf %p %x", bp, bp->b_flags));
776 KASSERT(bp->b_kvabase == unmapped_buf,
777 ("unmapped buf: corrupted b_kvabase %p", bp));
778 KASSERT(bp->b_data == unmapped_buf,
779 ("unmapped buf: corrupted b_data %p", bp));
782 #define BUF_CHECK_MAPPED(bp) vfs_buf_check_mapped(bp)
783 #define BUF_CHECK_UNMAPPED(bp) vfs_buf_check_unmapped(bp)
785 #define BUF_CHECK_MAPPED(bp) do {} while (0)
786 #define BUF_CHECK_UNMAPPED(bp) do {} while (0)
790 bpmap_qenter(struct buf *bp)
793 BUF_CHECK_MAPPED(bp);
796 * bp->b_data is relative to bp->b_offset, but
797 * bp->b_offset may be offset into the first page.
799 bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
800 pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
801 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
802 (vm_offset_t)(bp->b_offset & PAGE_MASK));
806 * bfreekva() - free the kva allocation for a buffer.
808 * Since this call frees up buffer space, we call bufspacewakeup().
811 bfreekva(struct buf *bp)
814 if (bp->b_kvasize == 0)
817 atomic_add_int(&buffreekvacnt, 1);
818 atomic_subtract_long(&bufspace, bp->b_kvasize);
819 if ((bp->b_flags & B_UNMAPPED) == 0) {
820 BUF_CHECK_MAPPED(bp);
821 vm_map_remove(buffer_map, (vm_offset_t)bp->b_kvabase,
822 (vm_offset_t)bp->b_kvabase + bp->b_kvasize);
824 BUF_CHECK_UNMAPPED(bp);
825 if ((bp->b_flags & B_KVAALLOC) != 0) {
826 vm_map_remove(buffer_map, (vm_offset_t)bp->b_kvaalloc,
827 (vm_offset_t)bp->b_kvaalloc + bp->b_kvasize);
829 atomic_subtract_long(&unmapped_bufspace, bp->b_kvasize);
830 bp->b_flags &= ~(B_UNMAPPED | B_KVAALLOC);
839 * Mark the buffer for removal from the appropriate free list in brelse.
843 bremfree(struct buf *bp)
847 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
848 KASSERT((bp->b_flags & B_REMFREE) == 0,
849 ("bremfree: buffer %p already marked for delayed removal.", bp));
850 KASSERT(bp->b_qindex != QUEUE_NONE,
851 ("bremfree: buffer %p not on a queue.", bp));
854 bp->b_flags |= B_REMFREE;
855 /* Fixup numfreebuffers count. */
856 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
857 KASSERT((bp->b_vflags & BV_INFREECNT) != 0,
858 ("buf %p not counted in numfreebuffers", bp));
859 if (bp->b_bufobj != NULL)
860 mtx_assert(BO_MTX(bp->b_bufobj), MA_OWNED);
861 bp->b_vflags &= ~BV_INFREECNT;
862 old = atomic_fetchadd_int(&numfreebuffers, -1);
863 KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
870 * Force an immediate removal from a free list. Used only in nfs when
871 * it abuses the b_freelist pointer.
874 bremfreef(struct buf *bp)
884 * Removes a buffer from the free list, must be called with the
888 bremfreel(struct buf *bp)
892 CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
893 bp, bp->b_vp, bp->b_flags);
894 KASSERT(bp->b_qindex != QUEUE_NONE,
895 ("bremfreel: buffer %p not on a queue.", bp));
897 mtx_assert(&bqlock, MA_OWNED);
899 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
901 KASSERT(bq_len[bp->b_qindex] >= 1, ("queue %d underflow",
903 bq_len[bp->b_qindex]--;
905 bp->b_qindex = QUEUE_NONE;
907 * If this was a delayed bremfree() we only need to remove the buffer
908 * from the queue and return the stats are already done.
910 if (bp->b_flags & B_REMFREE) {
911 bp->b_flags &= ~B_REMFREE;
915 * Fixup numfreebuffers count. If the buffer is invalid or not
916 * delayed-write, the buffer was free and we must decrement
919 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
920 KASSERT((bp->b_vflags & BV_INFREECNT) != 0,
921 ("buf %p not counted in numfreebuffers", bp));
922 if (bp->b_bufobj != NULL)
923 mtx_assert(BO_MTX(bp->b_bufobj), MA_OWNED);
924 bp->b_vflags &= ~BV_INFREECNT;
925 old = atomic_fetchadd_int(&numfreebuffers, -1);
926 KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
931 * Get a buffer with the specified data.
934 bread(struct vnode * vp, daddr_t blkno, int size, struct ucred * cred,
938 return (breadn_flags(vp, blkno, size, 0, 0, 0, cred, 0, bpp));
942 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must
943 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
944 * the buffer is valid and we do not have to do anything.
947 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
948 int cnt, struct ucred * cred)
953 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
954 if (inmem(vp, *rablkno))
956 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
958 if ((rabp->b_flags & B_CACHE) == 0) {
959 if (!TD_IS_IDLETHREAD(curthread))
960 curthread->td_ru.ru_inblock++;
961 rabp->b_flags |= B_ASYNC;
962 rabp->b_flags &= ~B_INVAL;
963 rabp->b_ioflags &= ~BIO_ERROR;
964 rabp->b_iocmd = BIO_READ;
965 if (rabp->b_rcred == NOCRED && cred != NOCRED)
966 rabp->b_rcred = crhold(cred);
967 vfs_busy_pages(rabp, 0);
969 rabp->b_iooffset = dbtob(rabp->b_blkno);
978 * Operates like bread, but with getblk flags.
981 bread_gb(struct vnode * vp, daddr_t blkno, int cnt, struct ucred * cred,
982 int gbflags, struct buf **bpp)
985 return (breadn_flags(vp, blkno, cnt, NULL, NULL, 0,
986 cred, gbflags, bpp));
990 * Operates like bread, but also starts asynchronous I/O on
994 breadn(struct vnode * vp, daddr_t blkno, int size,
995 daddr_t * rablkno, int *rabsize,
996 int cnt, struct ucred * cred, struct buf **bpp)
999 return (breadn_flags(vp, blkno, size, rablkno, rabsize, cnt,
1004 * Entry point for bread() and breadn().
1006 * Get a buffer with the specified data. Look in the cache first. We
1007 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
1008 * is set, the buffer is valid and we do not have to do anything, see
1009 * getblk(). Also starts asynchronous I/O on read-ahead blocks.
1012 breadn_flags(struct vnode *vp, daddr_t blkno, int size, daddr_t *rablkno,
1013 int *rabsize, int cnt, struct ucred *cred, int flags, struct buf **bpp)
1016 int rv = 0, readwait = 0;
1018 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
1020 * Can only return NULL if GB_LOCK_NOWAIT flag is specified.
1022 *bpp = bp = getblk(vp, blkno, size, 0, 0, flags);
1026 /* if not found in cache, do some I/O */
1027 if ((bp->b_flags & B_CACHE) == 0) {
1028 if (!TD_IS_IDLETHREAD(curthread))
1029 curthread->td_ru.ru_inblock++;
1030 bp->b_iocmd = BIO_READ;
1031 bp->b_flags &= ~B_INVAL;
1032 bp->b_ioflags &= ~BIO_ERROR;
1033 if (bp->b_rcred == NOCRED && cred != NOCRED)
1034 bp->b_rcred = crhold(cred);
1035 vfs_busy_pages(bp, 0);
1036 bp->b_iooffset = dbtob(bp->b_blkno);
1041 breada(vp, rablkno, rabsize, cnt, cred);
1050 * Write, release buffer on completion. (Done by iodone
1051 * if async). Do not bother writing anything if the buffer
1054 * Note that we set B_CACHE here, indicating that buffer is
1055 * fully valid and thus cacheable. This is true even of NFS
1056 * now so we set it generally. This could be set either here
1057 * or in biodone() since the I/O is synchronous. We put it
1061 bufwrite(struct buf *bp)
1067 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1068 if (bp->b_flags & B_INVAL) {
1073 if (bp->b_flags & B_BARRIER)
1076 oldflags = bp->b_flags;
1078 BUF_ASSERT_HELD(bp);
1080 if (bp->b_pin_count > 0)
1083 KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
1084 ("FFS background buffer should not get here %p", bp));
1088 vp_md = vp->v_vflag & VV_MD;
1093 * Mark the buffer clean. Increment the bufobj write count
1094 * before bundirty() call, to prevent other thread from seeing
1095 * empty dirty list and zero counter for writes in progress,
1096 * falsely indicating that the bufobj is clean.
1098 bufobj_wref(bp->b_bufobj);
1101 bp->b_flags &= ~B_DONE;
1102 bp->b_ioflags &= ~BIO_ERROR;
1103 bp->b_flags |= B_CACHE;
1104 bp->b_iocmd = BIO_WRITE;
1106 vfs_busy_pages(bp, 1);
1109 * Normal bwrites pipeline writes
1111 bp->b_runningbufspace = bp->b_bufsize;
1112 atomic_add_long(&runningbufspace, bp->b_runningbufspace);
1114 if (!TD_IS_IDLETHREAD(curthread))
1115 curthread->td_ru.ru_oublock++;
1116 if (oldflags & B_ASYNC)
1118 bp->b_iooffset = dbtob(bp->b_blkno);
1121 if ((oldflags & B_ASYNC) == 0) {
1122 int rtval = bufwait(bp);
1127 * don't allow the async write to saturate the I/O
1128 * system. We will not deadlock here because
1129 * we are blocking waiting for I/O that is already in-progress
1130 * to complete. We do not block here if it is the update
1131 * or syncer daemon trying to clean up as that can lead
1134 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
1135 waitrunningbufspace();
1142 bufbdflush(struct bufobj *bo, struct buf *bp)
1146 if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
1147 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
1149 } else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
1152 * Try to find a buffer to flush.
1154 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
1155 if ((nbp->b_vflags & BV_BKGRDINPROG) ||
1157 LK_EXCLUSIVE | LK_NOWAIT, NULL))
1160 panic("bdwrite: found ourselves");
1162 /* Don't countdeps with the bo lock held. */
1163 if (buf_countdeps(nbp, 0)) {
1168 if (nbp->b_flags & B_CLUSTEROK) {
1169 vfs_bio_awrite(nbp);
1174 dirtybufferflushes++;
1183 * Delayed write. (Buffer is marked dirty). Do not bother writing
1184 * anything if the buffer is marked invalid.
1186 * Note that since the buffer must be completely valid, we can safely
1187 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
1188 * biodone() in order to prevent getblk from writing the buffer
1189 * out synchronously.
1192 bdwrite(struct buf *bp)
1194 struct thread *td = curthread;
1198 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1199 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1200 KASSERT((bp->b_flags & B_BARRIER) == 0,
1201 ("Barrier request in delayed write %p", bp));
1202 BUF_ASSERT_HELD(bp);
1204 if (bp->b_flags & B_INVAL) {
1210 * If we have too many dirty buffers, don't create any more.
1211 * If we are wildly over our limit, then force a complete
1212 * cleanup. Otherwise, just keep the situation from getting
1213 * out of control. Note that we have to avoid a recursive
1214 * disaster and not try to clean up after our own cleanup!
1218 if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
1219 td->td_pflags |= TDP_INBDFLUSH;
1221 td->td_pflags &= ~TDP_INBDFLUSH;
1227 * Set B_CACHE, indicating that the buffer is fully valid. This is
1228 * true even of NFS now.
1230 bp->b_flags |= B_CACHE;
1233 * This bmap keeps the system from needing to do the bmap later,
1234 * perhaps when the system is attempting to do a sync. Since it
1235 * is likely that the indirect block -- or whatever other datastructure
1236 * that the filesystem needs is still in memory now, it is a good
1237 * thing to do this. Note also, that if the pageout daemon is
1238 * requesting a sync -- there might not be enough memory to do
1239 * the bmap then... So, this is important to do.
1241 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
1242 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
1246 * Set the *dirty* buffer range based upon the VM system dirty
1249 * Mark the buffer pages as clean. We need to do this here to
1250 * satisfy the vnode_pager and the pageout daemon, so that it
1251 * thinks that the pages have been "cleaned". Note that since
1252 * the pages are in a delayed write buffer -- the VFS layer
1253 * "will" see that the pages get written out on the next sync,
1254 * or perhaps the cluster will be completed.
1256 vfs_clean_pages_dirty_buf(bp);
1260 * Wakeup the buffer flushing daemon if we have a lot of dirty
1261 * buffers (midpoint between our recovery point and our stall
1264 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1267 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1268 * due to the softdep code.
1275 * Turn buffer into delayed write request. We must clear BIO_READ and
1276 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
1277 * itself to properly update it in the dirty/clean lists. We mark it
1278 * B_DONE to ensure that any asynchronization of the buffer properly
1279 * clears B_DONE ( else a panic will occur later ).
1281 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1282 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
1283 * should only be called if the buffer is known-good.
1285 * Since the buffer is not on a queue, we do not update the numfreebuffers
1288 * The buffer must be on QUEUE_NONE.
1291 bdirty(struct buf *bp)
1294 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
1295 bp, bp->b_vp, bp->b_flags);
1296 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1297 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1298 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1299 BUF_ASSERT_HELD(bp);
1300 bp->b_flags &= ~(B_RELBUF);
1301 bp->b_iocmd = BIO_WRITE;
1303 if ((bp->b_flags & B_DELWRI) == 0) {
1304 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
1306 atomic_add_int(&numdirtybuffers, 1);
1307 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1314 * Clear B_DELWRI for buffer.
1316 * Since the buffer is not on a queue, we do not update the numfreebuffers
1319 * The buffer must be on QUEUE_NONE.
1323 bundirty(struct buf *bp)
1326 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1327 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1328 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1329 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1330 BUF_ASSERT_HELD(bp);
1332 if (bp->b_flags & B_DELWRI) {
1333 bp->b_flags &= ~B_DELWRI;
1335 atomic_subtract_int(&numdirtybuffers, 1);
1336 numdirtywakeup(lodirtybuffers);
1339 * Since it is now being written, we can clear its deferred write flag.
1341 bp->b_flags &= ~B_DEFERRED;
1347 * Asynchronous write. Start output on a buffer, but do not wait for
1348 * it to complete. The buffer is released when the output completes.
1350 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1351 * B_INVAL buffers. Not us.
1354 bawrite(struct buf *bp)
1357 bp->b_flags |= B_ASYNC;
1364 * Asynchronous barrier write. Start output on a buffer, but do not
1365 * wait for it to complete. Place a write barrier after this write so
1366 * that this buffer and all buffers written before it are committed to
1367 * the disk before any buffers written after this write are committed
1368 * to the disk. The buffer is released when the output completes.
1371 babarrierwrite(struct buf *bp)
1374 bp->b_flags |= B_ASYNC | B_BARRIER;
1381 * Synchronous barrier write. Start output on a buffer and wait for
1382 * it to complete. Place a write barrier after this write so that
1383 * this buffer and all buffers written before it are committed to
1384 * the disk before any buffers written after this write are committed
1385 * to the disk. The buffer is released when the output completes.
1388 bbarrierwrite(struct buf *bp)
1391 bp->b_flags |= B_BARRIER;
1392 return (bwrite(bp));
1398 * Called prior to the locking of any vnodes when we are expecting to
1399 * write. We do not want to starve the buffer cache with too many
1400 * dirty buffers so we block here. By blocking prior to the locking
1401 * of any vnodes we attempt to avoid the situation where a locked vnode
1402 * prevents the various system daemons from flushing related buffers.
1409 if (numdirtybuffers >= hidirtybuffers) {
1411 while (numdirtybuffers >= hidirtybuffers) {
1413 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
1414 msleep(&needsbuffer, &nblock,
1415 (PRIBIO + 4), "flswai", 0);
1417 mtx_unlock(&nblock);
1422 * Return true if we have too many dirty buffers.
1425 buf_dirty_count_severe(void)
1428 return(numdirtybuffers >= hidirtybuffers);
1431 static __noinline int
1432 buf_vm_page_count_severe(void)
1435 KFAIL_POINT_CODE(DEBUG_FP, buf_pressure, return 1);
1437 return vm_page_count_severe();
1443 * Release a busy buffer and, if requested, free its resources. The
1444 * buffer will be stashed in the appropriate bufqueue[] allowing it
1445 * to be accessed later as a cache entity or reused for other purposes.
1448 brelse(struct buf *bp)
1450 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
1451 bp, bp->b_vp, bp->b_flags);
1452 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1453 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1455 if (BUF_LOCKRECURSED(bp)) {
1457 * Do not process, in particular, do not handle the
1458 * B_INVAL/B_RELBUF and do not release to free list.
1464 if (bp->b_flags & B_MANAGED) {
1469 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
1470 bp->b_error == EIO && !(bp->b_flags & B_INVAL)) {
1472 * Failed write, redirty. Must clear BIO_ERROR to prevent
1473 * pages from being scrapped. If the error is anything
1474 * other than an I/O error (EIO), assume that retrying
1477 bp->b_ioflags &= ~BIO_ERROR;
1479 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1480 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
1482 * Either a failed I/O or we were asked to free or not
1485 bp->b_flags |= B_INVAL;
1486 if (!LIST_EMPTY(&bp->b_dep))
1488 if (bp->b_flags & B_DELWRI) {
1489 atomic_subtract_int(&numdirtybuffers, 1);
1490 numdirtywakeup(lodirtybuffers);
1492 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1493 if ((bp->b_flags & B_VMIO) == 0) {
1502 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1503 * is called with B_DELWRI set, the underlying pages may wind up
1504 * getting freed causing a previous write (bdwrite()) to get 'lost'
1505 * because pages associated with a B_DELWRI bp are marked clean.
1507 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1508 * if B_DELWRI is set.
1510 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1511 * on pages to return pages to the VM page queues.
1513 if (bp->b_flags & B_DELWRI)
1514 bp->b_flags &= ~B_RELBUF;
1515 else if (buf_vm_page_count_severe()) {
1517 * The locking of the BO_LOCK is not necessary since
1518 * BKGRDINPROG cannot be set while we hold the buf
1519 * lock, it can only be cleared if it is already
1523 if (!(bp->b_vflags & BV_BKGRDINPROG))
1524 bp->b_flags |= B_RELBUF;
1526 bp->b_flags |= B_RELBUF;
1530 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1531 * constituted, not even NFS buffers now. Two flags effect this. If
1532 * B_INVAL, the struct buf is invalidated but the VM object is kept
1533 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1535 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1536 * invalidated. BIO_ERROR cannot be set for a failed write unless the
1537 * buffer is also B_INVAL because it hits the re-dirtying code above.
1539 * Normally we can do this whether a buffer is B_DELWRI or not. If
1540 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1541 * the commit state and we cannot afford to lose the buffer. If the
1542 * buffer has a background write in progress, we need to keep it
1543 * around to prevent it from being reconstituted and starting a second
1546 if ((bp->b_flags & B_VMIO)
1547 && !(bp->b_vp->v_mount != NULL &&
1548 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1549 !vn_isdisk(bp->b_vp, NULL) &&
1550 (bp->b_flags & B_DELWRI))
1559 obj = bp->b_bufobj->bo_object;
1562 * Get the base offset and length of the buffer. Note that
1563 * in the VMIO case if the buffer block size is not
1564 * page-aligned then b_data pointer may not be page-aligned.
1565 * But our b_pages[] array *IS* page aligned.
1567 * block sizes less then DEV_BSIZE (usually 512) are not
1568 * supported due to the page granularity bits (m->valid,
1569 * m->dirty, etc...).
1571 * See man buf(9) for more information
1573 resid = bp->b_bufsize;
1574 foff = bp->b_offset;
1575 VM_OBJECT_LOCK(obj);
1576 for (i = 0; i < bp->b_npages; i++) {
1582 * If we hit a bogus page, fixup *all* the bogus pages
1585 if (m == bogus_page) {
1586 poff = OFF_TO_IDX(bp->b_offset);
1589 for (j = i; j < bp->b_npages; j++) {
1591 mtmp = bp->b_pages[j];
1592 if (mtmp == bogus_page) {
1593 mtmp = vm_page_lookup(obj, poff + j);
1595 panic("brelse: page missing\n");
1597 bp->b_pages[j] = mtmp;
1601 if ((bp->b_flags & (B_INVAL | B_UNMAPPED)) == 0) {
1602 BUF_CHECK_MAPPED(bp);
1604 trunc_page((vm_offset_t)bp->b_data),
1605 bp->b_pages, bp->b_npages);
1609 if ((bp->b_flags & B_NOCACHE) ||
1610 (bp->b_ioflags & BIO_ERROR &&
1611 bp->b_iocmd == BIO_READ)) {
1612 int poffset = foff & PAGE_MASK;
1613 int presid = resid > (PAGE_SIZE - poffset) ?
1614 (PAGE_SIZE - poffset) : resid;
1616 KASSERT(presid >= 0, ("brelse: extra page"));
1617 if (pmap_page_wired_mappings(m) == 0)
1618 vm_page_set_invalid(m, poffset, presid);
1620 printf("avoided corruption bug in bogus_page/brelse code\n");
1622 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1623 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1625 VM_OBJECT_UNLOCK(obj);
1626 if (bp->b_flags & (B_INVAL | B_RELBUF))
1627 vfs_vmio_release(bp);
1629 } else if (bp->b_flags & B_VMIO) {
1631 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1632 vfs_vmio_release(bp);
1635 } else if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0) {
1636 if (bp->b_bufsize != 0)
1638 if (bp->b_vp != NULL)
1644 /* Handle delayed bremfree() processing. */
1645 if (bp->b_flags & B_REMFREE) {
1655 if (bp->b_qindex != QUEUE_NONE)
1656 panic("brelse: free buffer onto another queue???");
1659 * If the buffer has junk contents signal it and eventually
1660 * clean up B_DELWRI and diassociate the vnode so that gbincore()
1663 if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
1664 (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
1665 bp->b_flags |= B_INVAL;
1666 if (bp->b_flags & B_INVAL) {
1667 if (bp->b_flags & B_DELWRI)
1673 /* buffers with no memory */
1674 if (bp->b_bufsize == 0) {
1675 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1676 if (bp->b_vflags & BV_BKGRDINPROG)
1677 panic("losing buffer 1");
1678 if (bp->b_kvasize) {
1679 bp->b_qindex = QUEUE_EMPTYKVA;
1681 bp->b_qindex = QUEUE_EMPTY;
1683 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1684 /* buffers with junk contents */
1685 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1686 (bp->b_ioflags & BIO_ERROR)) {
1687 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1688 if (bp->b_vflags & BV_BKGRDINPROG)
1689 panic("losing buffer 2");
1690 bp->b_qindex = QUEUE_CLEAN;
1691 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1692 /* remaining buffers */
1694 if ((bp->b_flags & (B_DELWRI|B_NEEDSGIANT)) ==
1695 (B_DELWRI|B_NEEDSGIANT))
1696 bp->b_qindex = QUEUE_DIRTY_GIANT;
1697 else if (bp->b_flags & B_DELWRI)
1698 bp->b_qindex = QUEUE_DIRTY;
1700 bp->b_qindex = QUEUE_CLEAN;
1701 if (bp->b_flags & B_AGE) {
1702 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp,
1705 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp,
1710 bq_len[bp->b_qindex]++;
1712 mtx_unlock(&bqlock);
1715 * Fixup numfreebuffers count. The bp is on an appropriate queue
1716 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1717 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1718 * if B_INVAL is set ).
1721 if (!(bp->b_flags & B_DELWRI)) {
1733 * Something we can maybe free or reuse
1735 if (bp->b_bufsize || bp->b_kvasize)
1738 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1739 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1740 panic("brelse: not dirty");
1746 * Release a buffer back to the appropriate queue but do not try to free
1747 * it. The buffer is expected to be used again soon.
1749 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1750 * biodone() to requeue an async I/O on completion. It is also used when
1751 * known good buffers need to be requeued but we think we may need the data
1754 * XXX we should be able to leave the B_RELBUF hint set on completion.
1757 bqrelse(struct buf *bp)
1761 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1762 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1763 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1765 if (BUF_LOCKRECURSED(bp)) {
1766 /* do not release to free list */
1772 if (bp->b_flags & B_MANAGED) {
1773 if (bp->b_flags & B_REMFREE) {
1780 mtx_unlock(&bqlock);
1782 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1788 /* Handle delayed bremfree() processing. */
1789 if (bp->b_flags & B_REMFREE) {
1796 if (bp->b_qindex != QUEUE_NONE)
1797 panic("bqrelse: free buffer onto another queue???");
1798 /* buffers with stale but valid contents */
1799 if (bp->b_flags & B_DELWRI) {
1800 if (bp->b_flags & B_NEEDSGIANT)
1801 bp->b_qindex = QUEUE_DIRTY_GIANT;
1803 bp->b_qindex = QUEUE_DIRTY;
1804 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1806 bq_len[bp->b_qindex]++;
1810 * The locking of the BO_LOCK for checking of the
1811 * BV_BKGRDINPROG is not necessary since the
1812 * BV_BKGRDINPROG cannot be set while we hold the buf
1813 * lock, it can only be cleared if it is already
1816 if (!buf_vm_page_count_severe() || (bp->b_vflags & BV_BKGRDINPROG)) {
1817 bp->b_qindex = QUEUE_CLEAN;
1818 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp,
1821 bq_len[QUEUE_CLEAN]++;
1825 * We are too low on memory, we have to try to free
1826 * the buffer (most importantly: the wired pages
1827 * making up its backing store) *now*.
1829 mtx_unlock(&bqlock);
1834 mtx_unlock(&bqlock);
1836 if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI)) {
1845 * Something we can maybe free or reuse.
1847 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1850 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1851 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1852 panic("bqrelse: not dirty");
1857 /* Give pages used by the bp back to the VM system (where possible) */
1859 vfs_vmio_release(struct buf *bp)
1864 if ((bp->b_flags & B_UNMAPPED) == 0) {
1865 BUF_CHECK_MAPPED(bp);
1866 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
1868 BUF_CHECK_UNMAPPED(bp);
1869 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
1870 for (i = 0; i < bp->b_npages; i++) {
1872 bp->b_pages[i] = NULL;
1874 * In order to keep page LRU ordering consistent, put
1875 * everything on the inactive queue.
1878 vm_page_unwire(m, 0);
1880 * We don't mess with busy pages, it is
1881 * the responsibility of the process that
1882 * busied the pages to deal with them.
1884 if ((m->oflags & VPO_BUSY) == 0 && m->busy == 0 &&
1885 m->wire_count == 0) {
1887 * Might as well free the page if we can and it has
1888 * no valid data. We also free the page if the
1889 * buffer was used for direct I/O
1891 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid) {
1893 } else if (bp->b_flags & B_DIRECT) {
1894 vm_page_try_to_free(m);
1895 } else if (buf_vm_page_count_severe()) {
1896 vm_page_try_to_cache(m);
1901 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
1903 if (bp->b_bufsize) {
1908 bp->b_flags &= ~B_VMIO;
1914 * Check to see if a block at a particular lbn is available for a clustered
1918 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1925 /* If the buf isn't in core skip it */
1926 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1929 /* If the buf is busy we don't want to wait for it */
1930 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1933 /* Only cluster with valid clusterable delayed write buffers */
1934 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1935 (B_DELWRI | B_CLUSTEROK))
1938 if (bpa->b_bufsize != size)
1942 * Check to see if it is in the expected place on disk and that the
1943 * block has been mapped.
1945 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1955 * Implement clustered async writes for clearing out B_DELWRI buffers.
1956 * This is much better then the old way of writing only one buffer at
1957 * a time. Note that we may not be presented with the buffers in the
1958 * correct order, so we search for the cluster in both directions.
1961 vfs_bio_awrite(struct buf *bp)
1966 daddr_t lblkno = bp->b_lblkno;
1967 struct vnode *vp = bp->b_vp;
1975 gbflags = (bp->b_flags & B_UNMAPPED) != 0 ? GB_UNMAPPED : 0;
1977 * right now we support clustered writing only to regular files. If
1978 * we find a clusterable block we could be in the middle of a cluster
1979 * rather then at the beginning.
1981 if ((vp->v_type == VREG) &&
1982 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1983 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1985 size = vp->v_mount->mnt_stat.f_iosize;
1986 maxcl = MAXPHYS / size;
1989 for (i = 1; i < maxcl; i++)
1990 if (vfs_bio_clcheck(vp, size, lblkno + i,
1991 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1994 for (j = 1; i + j <= maxcl && j <= lblkno; j++)
1995 if (vfs_bio_clcheck(vp, size, lblkno - j,
1996 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
2002 * this is a possible cluster write
2006 nwritten = cluster_wbuild_gb(vp, size, lblkno - j,
2012 bp->b_flags |= B_ASYNC;
2014 * default (old) behavior, writing out only one block
2016 * XXX returns b_bufsize instead of b_bcount for nwritten?
2018 nwritten = bp->b_bufsize;
2025 setbufkva(struct buf *bp, vm_offset_t addr, int maxsize, int gbflags)
2028 KASSERT((bp->b_flags & (B_UNMAPPED | B_KVAALLOC)) == 0 &&
2029 bp->b_kvasize == 0, ("call bfreekva(%p)", bp));
2030 if ((gbflags & GB_UNMAPPED) == 0) {
2031 bp->b_kvabase = (caddr_t)addr;
2032 } else if ((gbflags & GB_KVAALLOC) != 0) {
2033 KASSERT((gbflags & GB_UNMAPPED) != 0,
2034 ("GB_KVAALLOC without GB_UNMAPPED"));
2035 bp->b_kvaalloc = (caddr_t)addr;
2036 bp->b_flags |= B_UNMAPPED | B_KVAALLOC;
2037 atomic_add_long(&unmapped_bufspace, bp->b_kvasize);
2039 bp->b_kvasize = maxsize;
2043 * Allocate the buffer KVA and set b_kvasize. Also set b_kvabase if
2047 allocbufkva(struct buf *bp, int maxsize, int gbflags)
2055 vm_map_lock(buffer_map);
2056 if (vm_map_findspace(buffer_map, vm_map_min(buffer_map), maxsize,
2058 vm_map_unlock(buffer_map);
2060 * Buffer map is too fragmented. Request the caller
2061 * to defragment the map.
2063 atomic_add_int(&bufdefragcnt, 1);
2066 rv = vm_map_insert(buffer_map, NULL, 0, addr, addr + maxsize,
2067 VM_PROT_RW, VM_PROT_RW, MAP_NOFAULT);
2068 KASSERT(rv == KERN_SUCCESS, ("vm_map_insert(buffer_map) rv %d", rv));
2069 vm_map_unlock(buffer_map);
2070 setbufkva(bp, addr, maxsize, gbflags);
2071 atomic_add_long(&bufspace, bp->b_kvasize);
2076 * Ask the bufdaemon for help, or act as bufdaemon itself, when a
2077 * locked vnode is supplied.
2080 getnewbuf_bufd_help(struct vnode *vp, int gbflags, int slpflag, int slptimeo,
2085 int fl, flags, norunbuf;
2087 mtx_assert(&bqlock, MA_OWNED);
2090 flags = VFS_BIO_NEED_BUFSPACE;
2092 } else if (bufspace >= hibufspace) {
2094 flags = VFS_BIO_NEED_BUFSPACE;
2097 flags = VFS_BIO_NEED_ANY;
2100 needsbuffer |= flags;
2101 mtx_unlock(&nblock);
2102 mtx_unlock(&bqlock);
2104 bd_speedup(); /* heeeelp */
2105 if ((gbflags & GB_NOWAIT_BD) != 0)
2110 while (needsbuffer & flags) {
2111 if (vp != NULL && vp->v_type != VCHR &&
2112 (td->td_pflags & TDP_BUFNEED) == 0) {
2113 mtx_unlock(&nblock);
2115 * getblk() is called with a vnode locked, and
2116 * some majority of the dirty buffers may as
2117 * well belong to the vnode. Flushing the
2118 * buffers there would make a progress that
2119 * cannot be achieved by the buf_daemon, that
2120 * cannot lock the vnode.
2122 norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
2123 (td->td_pflags & TDP_NORUNNINGBUF);
2124 /* play bufdaemon */
2125 td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
2126 fl = buf_do_flush(vp);
2127 td->td_pflags &= norunbuf;
2131 if ((needsbuffer & flags) == 0)
2134 if (msleep(&needsbuffer, &nblock, (PRIBIO + 4) | slpflag,
2138 mtx_unlock(&nblock);
2142 getnewbuf_reuse_bp(struct buf *bp, int qindex)
2145 CTR6(KTR_BUF, "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
2146 "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
2147 bp->b_kvasize, bp->b_bufsize, qindex);
2148 mtx_assert(&bqlock, MA_NOTOWNED);
2151 * Note: we no longer distinguish between VMIO and non-VMIO
2154 KASSERT((bp->b_flags & B_DELWRI) == 0,
2155 ("delwri buffer %p found in queue %d", bp, qindex));
2157 if (qindex == QUEUE_CLEAN) {
2158 if (bp->b_flags & B_VMIO) {
2159 bp->b_flags &= ~B_ASYNC;
2160 vfs_vmio_release(bp);
2162 if (bp->b_vp != NULL)
2167 * Get the rest of the buffer freed up. b_kva* is still valid
2168 * after this operation.
2171 if (bp->b_rcred != NOCRED) {
2172 crfree(bp->b_rcred);
2173 bp->b_rcred = NOCRED;
2175 if (bp->b_wcred != NOCRED) {
2176 crfree(bp->b_wcred);
2177 bp->b_wcred = NOCRED;
2179 if (!LIST_EMPTY(&bp->b_dep))
2181 if (bp->b_vflags & BV_BKGRDINPROG)
2182 panic("losing buffer 3");
2183 KASSERT(bp->b_vp == NULL, ("bp: %p still has vnode %p. qindex: %d",
2184 bp, bp->b_vp, qindex));
2185 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
2186 ("bp: %p still on a buffer list. xflags %X", bp, bp->b_xflags));
2191 bp->b_flags &= B_UNMAPPED | B_KVAALLOC;
2194 KASSERT((bp->b_vflags & BV_INFREECNT) == 0,
2195 ("buf %p still counted as free?", bp));
2198 bp->b_blkno = bp->b_lblkno = 0;
2199 bp->b_offset = NOOFFSET;
2205 bp->b_dirtyoff = bp->b_dirtyend = 0;
2206 bp->b_bufobj = NULL;
2207 bp->b_pin_count = 0;
2208 bp->b_fsprivate1 = NULL;
2209 bp->b_fsprivate2 = NULL;
2210 bp->b_fsprivate3 = NULL;
2212 LIST_INIT(&bp->b_dep);
2215 static int flushingbufs;
2218 getnewbuf_scan(int maxsize, int defrag, int unmapped, int metadata)
2220 struct buf *bp, *nbp;
2221 int nqindex, qindex, pass;
2223 KASSERT(!unmapped || !defrag, ("both unmapped and defrag"));
2227 atomic_add_int(&getnewbufrestarts, 1);
2230 * Setup for scan. If we do not have enough free buffers,
2231 * we setup a degenerate case that immediately fails. Note
2232 * that if we are specially marked process, we are allowed to
2233 * dip into our reserves.
2235 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
2236 * for the allocation of the mapped buffer. For unmapped, the
2237 * easiest is to start with EMPTY outright.
2239 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
2240 * However, there are a number of cases (defragging, reusing, ...)
2241 * where we cannot backup.
2245 if (!defrag && unmapped) {
2246 nqindex = QUEUE_EMPTY;
2247 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
2250 nqindex = QUEUE_EMPTYKVA;
2251 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
2255 * If no EMPTYKVA buffers and we are either defragging or
2256 * reusing, locate a CLEAN buffer to free or reuse. If
2257 * bufspace useage is low skip this step so we can allocate a
2260 if (nbp == NULL && (defrag || bufspace >= lobufspace)) {
2261 nqindex = QUEUE_CLEAN;
2262 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2266 * If we could not find or were not allowed to reuse a CLEAN
2267 * buffer, check to see if it is ok to use an EMPTY buffer.
2268 * We can only use an EMPTY buffer if allocating its KVA would
2269 * not otherwise run us out of buffer space. No KVA is needed
2270 * for the unmapped allocation.
2272 if (nbp == NULL && defrag == 0 && (bufspace + maxsize < hibufspace ||
2274 nqindex = QUEUE_EMPTY;
2275 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
2279 * All available buffers might be clean, retry ignoring the
2280 * lobufspace as the last resort.
2282 if (nbp == NULL && !TAILQ_EMPTY(&bufqueues[QUEUE_CLEAN])) {
2283 nqindex = QUEUE_CLEAN;
2284 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2288 * Run scan, possibly freeing data and/or kva mappings on the fly
2291 while ((bp = nbp) != NULL) {
2295 * Calculate next bp (we can only use it if we do not
2296 * block or do other fancy things).
2298 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
2301 nqindex = QUEUE_EMPTYKVA;
2302 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
2306 case QUEUE_EMPTYKVA:
2307 nqindex = QUEUE_CLEAN;
2308 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2313 if (metadata && pass == 1) {
2315 nqindex = QUEUE_EMPTY;
2317 &bufqueues[QUEUE_EMPTY]);
2326 * If we are defragging then we need a buffer with
2327 * b_kvasize != 0. XXX this situation should no longer
2328 * occur, if defrag is non-zero the buffer's b_kvasize
2329 * should also be non-zero at this point. XXX
2331 if (defrag && bp->b_kvasize == 0) {
2332 printf("Warning: defrag empty buffer %p\n", bp);
2337 * Start freeing the bp. This is somewhat involved. nbp
2338 * remains valid only for QUEUE_EMPTY[KVA] bp's.
2340 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2343 BO_LOCK(bp->b_bufobj);
2344 if (bp->b_vflags & BV_BKGRDINPROG) {
2345 BO_UNLOCK(bp->b_bufobj);
2349 BO_UNLOCK(bp->b_bufobj);
2352 KASSERT(bp->b_qindex == qindex,
2353 ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
2355 if (bp->b_bufobj != NULL)
2356 BO_LOCK(bp->b_bufobj);
2358 if (bp->b_bufobj != NULL)
2359 BO_UNLOCK(bp->b_bufobj);
2360 mtx_unlock(&bqlock);
2362 * NOTE: nbp is now entirely invalid. We can only restart
2363 * the scan from this point on.
2366 getnewbuf_reuse_bp(bp, qindex);
2367 mtx_assert(&bqlock, MA_NOTOWNED);
2370 * If we are defragging then free the buffer.
2373 bp->b_flags |= B_INVAL;
2381 * Notify any waiters for the buffer lock about
2382 * identity change by freeing the buffer.
2384 if (qindex == QUEUE_CLEAN && BUF_LOCKWAITERS(bp)) {
2385 bp->b_flags |= B_INVAL;
2395 * If we are overcomitted then recover the buffer and its
2396 * KVM space. This occurs in rare situations when multiple
2397 * processes are blocked in getnewbuf() or allocbuf().
2399 if (bufspace >= hibufspace)
2401 if (flushingbufs && bp->b_kvasize != 0) {
2402 bp->b_flags |= B_INVAL;
2407 if (bufspace < lobufspace)
2417 * Find and initialize a new buffer header, freeing up existing buffers
2418 * in the bufqueues as necessary. The new buffer is returned locked.
2420 * Important: B_INVAL is not set. If the caller wishes to throw the
2421 * buffer away, the caller must set B_INVAL prior to calling brelse().
2424 * We have insufficient buffer headers
2425 * We have insufficient buffer space
2426 * buffer_map is too fragmented ( space reservation fails )
2427 * If we have to flush dirty buffers ( but we try to avoid this )
2429 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
2430 * Instead we ask the buf daemon to do it for us. We attempt to
2431 * avoid piecemeal wakeups of the pageout daemon.
2434 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int size, int maxsize,
2438 int defrag, metadata;
2440 KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
2441 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
2442 if (!unmapped_buf_allowed)
2443 gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC);
2446 if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 ||
2452 * We can't afford to block since we might be holding a vnode lock,
2453 * which may prevent system daemons from running. We deal with
2454 * low-memory situations by proactively returning memory and running
2455 * async I/O rather then sync I/O.
2457 atomic_add_int(&getnewbufcalls, 1);
2458 atomic_subtract_int(&getnewbufrestarts, 1);
2460 bp = getnewbuf_scan(maxsize, defrag, (gbflags & (GB_UNMAPPED |
2461 GB_KVAALLOC)) == GB_UNMAPPED, metadata);
2466 * If we exhausted our list, sleep as appropriate. We may have to
2467 * wakeup various daemons and write out some dirty buffers.
2469 * Generally we are sleeping due to insufficient buffer space.
2472 mtx_assert(&bqlock, MA_OWNED);
2473 getnewbuf_bufd_help(vp, gbflags, slpflag, slptimeo, defrag);
2474 mtx_assert(&bqlock, MA_NOTOWNED);
2475 } else if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == GB_UNMAPPED) {
2476 mtx_assert(&bqlock, MA_NOTOWNED);
2479 bp->b_flags |= B_UNMAPPED;
2480 bp->b_kvabase = bp->b_data = unmapped_buf;
2481 bp->b_kvasize = maxsize;
2482 atomic_add_long(&bufspace, bp->b_kvasize);
2483 atomic_add_long(&unmapped_bufspace, bp->b_kvasize);
2484 atomic_add_int(&bufreusecnt, 1);
2486 mtx_assert(&bqlock, MA_NOTOWNED);
2489 * We finally have a valid bp. We aren't quite out of the
2490 * woods, we still have to reserve kva space. In order
2491 * to keep fragmentation sane we only allocate kva in
2494 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2496 if (maxsize != bp->b_kvasize || (bp->b_flags & (B_UNMAPPED |
2497 B_KVAALLOC)) == B_UNMAPPED) {
2498 if (allocbufkva(bp, maxsize, gbflags)) {
2500 bp->b_flags |= B_INVAL;
2504 atomic_add_int(&bufreusecnt, 1);
2505 } else if ((bp->b_flags & B_KVAALLOC) != 0 &&
2506 (gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == 0) {
2508 * If the reused buffer has KVA allocated,
2509 * reassign b_kvaalloc to b_kvabase.
2511 bp->b_kvabase = bp->b_kvaalloc;
2512 bp->b_flags &= ~B_KVAALLOC;
2513 atomic_subtract_long(&unmapped_bufspace,
2515 atomic_add_int(&bufreusecnt, 1);
2516 } else if ((bp->b_flags & (B_UNMAPPED | B_KVAALLOC)) == 0 &&
2517 (gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == (GB_UNMAPPED |
2520 * The case of reused buffer already have KVA
2521 * mapped, but the request is for unmapped
2522 * buffer with KVA allocated.
2524 bp->b_kvaalloc = bp->b_kvabase;
2525 bp->b_data = bp->b_kvabase = unmapped_buf;
2526 bp->b_flags |= B_UNMAPPED | B_KVAALLOC;
2527 atomic_add_long(&unmapped_bufspace,
2529 atomic_add_int(&bufreusecnt, 1);
2531 if ((gbflags & GB_UNMAPPED) == 0) {
2532 bp->b_saveaddr = bp->b_kvabase;
2533 bp->b_data = bp->b_saveaddr;
2534 bp->b_flags &= ~B_UNMAPPED;
2535 BUF_CHECK_MAPPED(bp);
2544 * buffer flushing daemon. Buffers are normally flushed by the
2545 * update daemon but if it cannot keep up this process starts to
2546 * take the load in an attempt to prevent getnewbuf() from blocking.
2549 static struct kproc_desc buf_kp = {
2554 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
2557 buf_do_flush(struct vnode *vp)
2561 flushed = flushbufqueues(vp, QUEUE_DIRTY, 0);
2562 /* The list empty check here is slightly racy */
2563 if (!TAILQ_EMPTY(&bufqueues[QUEUE_DIRTY_GIANT])) {
2565 flushed += flushbufqueues(vp, QUEUE_DIRTY_GIANT, 0);
2570 * Could not find any buffers without rollback
2571 * dependencies, so just write the first one
2572 * in the hopes of eventually making progress.
2574 flushbufqueues(vp, QUEUE_DIRTY, 1);
2576 &bufqueues[QUEUE_DIRTY_GIANT])) {
2578 flushbufqueues(vp, QUEUE_DIRTY_GIANT, 1);
2591 * This process needs to be suspended prior to shutdown sync.
2593 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2597 * This process is allowed to take the buffer cache to the limit
2599 curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
2603 mtx_unlock(&bdlock);
2605 kproc_suspend_check(bufdaemonproc);
2606 lodirtysave = lodirtybuffers;
2607 if (bd_speedupreq) {
2608 lodirtybuffers = numdirtybuffers / 2;
2612 * Do the flush. Limit the amount of in-transit I/O we
2613 * allow to build up, otherwise we would completely saturate
2614 * the I/O system. Wakeup any waiting processes before we
2615 * normally would so they can run in parallel with our drain.
2617 while (numdirtybuffers > lodirtybuffers) {
2618 if (buf_do_flush(NULL) == 0)
2620 kern_yield(PRI_UNCHANGED);
2622 lodirtybuffers = lodirtysave;
2625 * Only clear bd_request if we have reached our low water
2626 * mark. The buf_daemon normally waits 1 second and
2627 * then incrementally flushes any dirty buffers that have
2628 * built up, within reason.
2630 * If we were unable to hit our low water mark and couldn't
2631 * find any flushable buffers, we sleep half a second.
2632 * Otherwise we loop immediately.
2635 if (numdirtybuffers <= lodirtybuffers) {
2637 * We reached our low water mark, reset the
2638 * request and sleep until we are needed again.
2639 * The sleep is just so the suspend code works.
2642 msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2645 * We couldn't find any flushable dirty buffers but
2646 * still have too many dirty buffers, we
2647 * have to sleep and try again. (rare)
2649 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2657 * Try to flush a buffer in the dirty queue. We must be careful to
2658 * free up B_INVAL buffers instead of write them, which NFS is
2659 * particularly sensitive to.
2661 static int flushwithdeps = 0;
2662 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2663 0, "Number of buffers flushed with dependecies that require rollbacks");
2666 flushbufqueues(struct vnode *lvp, int queue, int flushdeps)
2668 struct buf *sentinel;
2679 target = numdirtybuffers - lodirtybuffers;
2680 if (flushdeps && target > 2)
2683 target = flushbufqtarget;
2686 sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
2687 sentinel->b_qindex = QUEUE_SENTINEL;
2689 TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
2690 while (flushed != target) {
2691 bp = TAILQ_NEXT(sentinel, b_freelist);
2693 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2694 TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
2699 * Skip sentinels inserted by other invocations of the
2700 * flushbufqueues(), taking care to not reorder them.
2702 if (bp->b_qindex == QUEUE_SENTINEL)
2705 * Only flush the buffers that belong to the
2706 * vnode locked by the curthread.
2708 if (lvp != NULL && bp->b_vp != lvp)
2710 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2712 if (bp->b_pin_count > 0) {
2716 BO_LOCK(bp->b_bufobj);
2717 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2718 (bp->b_flags & B_DELWRI) == 0) {
2719 BO_UNLOCK(bp->b_bufobj);
2723 BO_UNLOCK(bp->b_bufobj);
2724 if (bp->b_flags & B_INVAL) {
2726 mtx_unlock(&bqlock);
2729 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2734 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
2735 if (flushdeps == 0) {
2743 * We must hold the lock on a vnode before writing
2744 * one of its buffers. Otherwise we may confuse, or
2745 * in the case of a snapshot vnode, deadlock the
2748 * The lock order here is the reverse of the normal
2749 * of vnode followed by buf lock. This is ok because
2750 * the NOWAIT will prevent deadlock.
2753 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2759 error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
2761 ASSERT_VOP_LOCKED(vp, "getbuf");
2763 error = VOP_ISLOCKED(vp) == LK_EXCLUSIVE ? 0 :
2764 vn_lock(vp, LK_TRYUPGRADE);
2767 mtx_unlock(&bqlock);
2768 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2769 bp, bp->b_vp, bp->b_flags);
2770 if (curproc == bufdaemonproc)
2777 vn_finished_write(mp);
2780 flushwithdeps += hasdeps;
2784 * Sleeping on runningbufspace while holding
2785 * vnode lock leads to deadlock.
2787 if (curproc == bufdaemonproc)
2788 waitrunningbufspace();
2789 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2793 vn_finished_write(mp);
2796 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2797 mtx_unlock(&bqlock);
2798 free(sentinel, M_TEMP);
2803 * Check to see if a block is currently memory resident.
2806 incore(struct bufobj *bo, daddr_t blkno)
2811 bp = gbincore(bo, blkno);
2817 * Returns true if no I/O is needed to access the
2818 * associated VM object. This is like incore except
2819 * it also hunts around in the VM system for the data.
2823 inmem(struct vnode * vp, daddr_t blkno)
2826 vm_offset_t toff, tinc, size;
2830 ASSERT_VOP_LOCKED(vp, "inmem");
2832 if (incore(&vp->v_bufobj, blkno))
2834 if (vp->v_mount == NULL)
2841 if (size > vp->v_mount->mnt_stat.f_iosize)
2842 size = vp->v_mount->mnt_stat.f_iosize;
2843 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2845 VM_OBJECT_LOCK(obj);
2846 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2847 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2851 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2852 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2853 if (vm_page_is_valid(m,
2854 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2857 VM_OBJECT_UNLOCK(obj);
2861 VM_OBJECT_UNLOCK(obj);
2866 * Set the dirty range for a buffer based on the status of the dirty
2867 * bits in the pages comprising the buffer. The range is limited
2868 * to the size of the buffer.
2870 * Tell the VM system that the pages associated with this buffer
2871 * are clean. This is used for delayed writes where the data is
2872 * going to go to disk eventually without additional VM intevention.
2874 * Note that while we only really need to clean through to b_bcount, we
2875 * just go ahead and clean through to b_bufsize.
2878 vfs_clean_pages_dirty_buf(struct buf *bp)
2880 vm_ooffset_t foff, noff, eoff;
2884 if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
2887 foff = bp->b_offset;
2888 KASSERT(bp->b_offset != NOOFFSET,
2889 ("vfs_clean_pages_dirty_buf: no buffer offset"));
2891 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
2892 vfs_drain_busy_pages(bp);
2893 vfs_setdirty_locked_object(bp);
2894 for (i = 0; i < bp->b_npages; i++) {
2895 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2897 if (eoff > bp->b_offset + bp->b_bufsize)
2898 eoff = bp->b_offset + bp->b_bufsize;
2900 vfs_page_set_validclean(bp, foff, m);
2901 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
2904 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
2908 vfs_setdirty_locked_object(struct buf *bp)
2913 object = bp->b_bufobj->bo_object;
2914 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2917 * We qualify the scan for modified pages on whether the
2918 * object has been flushed yet.
2920 if ((object->flags & OBJ_MIGHTBEDIRTY) != 0) {
2921 vm_offset_t boffset;
2922 vm_offset_t eoffset;
2925 * test the pages to see if they have been modified directly
2926 * by users through the VM system.
2928 for (i = 0; i < bp->b_npages; i++)
2929 vm_page_test_dirty(bp->b_pages[i]);
2932 * Calculate the encompassing dirty range, boffset and eoffset,
2933 * (eoffset - boffset) bytes.
2936 for (i = 0; i < bp->b_npages; i++) {
2937 if (bp->b_pages[i]->dirty)
2940 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2942 for (i = bp->b_npages - 1; i >= 0; --i) {
2943 if (bp->b_pages[i]->dirty) {
2947 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2950 * Fit it to the buffer.
2953 if (eoffset > bp->b_bcount)
2954 eoffset = bp->b_bcount;
2957 * If we have a good dirty range, merge with the existing
2961 if (boffset < eoffset) {
2962 if (bp->b_dirtyoff > boffset)
2963 bp->b_dirtyoff = boffset;
2964 if (bp->b_dirtyend < eoffset)
2965 bp->b_dirtyend = eoffset;
2971 * Allocate the KVA mapping for an existing buffer. It handles the
2972 * cases of both B_UNMAPPED buffer, and buffer with the preallocated
2973 * KVA which is not mapped (B_KVAALLOC).
2976 bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags)
2978 struct buf *scratch_bp;
2979 int bsize, maxsize, need_mapping, need_kva;
2982 need_mapping = (bp->b_flags & B_UNMAPPED) != 0 &&
2983 (gbflags & GB_UNMAPPED) == 0;
2984 need_kva = (bp->b_flags & (B_KVAALLOC | B_UNMAPPED)) == B_UNMAPPED &&
2985 (gbflags & GB_KVAALLOC) != 0;
2986 if (!need_mapping && !need_kva)
2989 BUF_CHECK_UNMAPPED(bp);
2991 if (need_mapping && (bp->b_flags & B_KVAALLOC) != 0) {
2993 * Buffer is not mapped, but the KVA was already
2994 * reserved at the time of the instantiation. Use the
2997 bp->b_flags &= ~B_KVAALLOC;
2998 KASSERT(bp->b_kvaalloc != 0, ("kvaalloc == 0"));
2999 bp->b_kvabase = bp->b_kvaalloc;
3000 atomic_subtract_long(&unmapped_bufspace, bp->b_kvasize);
3005 * Calculate the amount of the address space we would reserve
3006 * if the buffer was mapped.
3008 bsize = vn_isdisk(bp->b_vp, NULL) ? DEV_BSIZE : bp->b_bufobj->bo_bsize;
3009 offset = blkno * bsize;
3010 maxsize = size + (offset & PAGE_MASK);
3011 maxsize = imax(maxsize, bsize);
3014 if (allocbufkva(bp, maxsize, gbflags)) {
3016 * Request defragmentation. getnewbuf() returns us the
3017 * allocated space by the scratch buffer KVA.
3019 scratch_bp = getnewbuf(bp->b_vp, 0, 0, size, maxsize, gbflags |
3020 (GB_UNMAPPED | GB_KVAALLOC));
3021 if (scratch_bp == NULL) {
3022 if ((gbflags & GB_NOWAIT_BD) != 0) {
3024 * XXXKIB: defragmentation cannot
3025 * succeed, not sure what else to do.
3027 panic("GB_NOWAIT_BD and B_UNMAPPED %p", bp);
3029 atomic_add_int(&mappingrestarts, 1);
3032 KASSERT((scratch_bp->b_flags & B_KVAALLOC) != 0,
3033 ("scratch bp !B_KVAALLOC %p", scratch_bp));
3034 setbufkva(bp, (vm_offset_t)scratch_bp->b_kvaalloc,
3035 scratch_bp->b_kvasize, gbflags);
3037 /* Get rid of the scratch buffer. */
3038 scratch_bp->b_kvasize = 0;
3039 scratch_bp->b_flags |= B_INVAL;
3040 scratch_bp->b_flags &= ~(B_UNMAPPED | B_KVAALLOC);
3047 bp->b_saveaddr = bp->b_kvabase;
3048 bp->b_data = bp->b_saveaddr; /* b_offset is handled by bpmap_qenter */
3049 bp->b_flags &= ~B_UNMAPPED;
3050 BUF_CHECK_MAPPED(bp);
3057 * Get a block given a specified block and offset into a file/device.
3058 * The buffers B_DONE bit will be cleared on return, making it almost
3059 * ready for an I/O initiation. B_INVAL may or may not be set on
3060 * return. The caller should clear B_INVAL prior to initiating a
3063 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
3064 * an existing buffer.
3066 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
3067 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
3068 * and then cleared based on the backing VM. If the previous buffer is
3069 * non-0-sized but invalid, B_CACHE will be cleared.
3071 * If getblk() must create a new buffer, the new buffer is returned with
3072 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
3073 * case it is returned with B_INVAL clear and B_CACHE set based on the
3076 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
3077 * B_CACHE bit is clear.
3079 * What this means, basically, is that the caller should use B_CACHE to
3080 * determine whether the buffer is fully valid or not and should clear
3081 * B_INVAL prior to issuing a read. If the caller intends to validate
3082 * the buffer by loading its data area with something, the caller needs
3083 * to clear B_INVAL. If the caller does this without issuing an I/O,
3084 * the caller should set B_CACHE ( as an optimization ), else the caller
3085 * should issue the I/O and biodone() will set B_CACHE if the I/O was
3086 * a write attempt or if it was a successfull read. If the caller
3087 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
3088 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
3091 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo,
3096 int bsize, error, maxsize, vmio;
3099 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
3100 KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3101 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3102 ASSERT_VOP_LOCKED(vp, "getblk");
3103 if (size > MAXBSIZE)
3104 panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
3105 if (!unmapped_buf_allowed)
3106 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3111 * Block if we are low on buffers. Certain processes are allowed
3112 * to completely exhaust the buffer cache.
3114 * If this check ever becomes a bottleneck it may be better to
3115 * move it into the else, when gbincore() fails. At the moment
3116 * it isn't a problem.
3118 if (numfreebuffers == 0) {
3119 if (TD_IS_IDLETHREAD(curthread))
3122 needsbuffer |= VFS_BIO_NEED_ANY;
3123 mtx_unlock(&nblock);
3127 bp = gbincore(bo, blkno);
3131 * Buffer is in-core. If the buffer is not busy, it must
3134 lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
3136 if (flags & GB_LOCK_NOWAIT)
3137 lockflags |= LK_NOWAIT;
3139 error = BUF_TIMELOCK(bp, lockflags,
3140 BO_MTX(bo), "getblk", slpflag, slptimeo);
3143 * If we slept and got the lock we have to restart in case
3144 * the buffer changed identities.
3146 if (error == ENOLCK)
3148 /* We timed out or were interrupted. */
3151 /* If recursed, assume caller knows the rules. */
3152 else if (BUF_LOCKRECURSED(bp))
3156 * The buffer is locked. B_CACHE is cleared if the buffer is
3157 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
3158 * and for a VMIO buffer B_CACHE is adjusted according to the
3161 if (bp->b_flags & B_INVAL)
3162 bp->b_flags &= ~B_CACHE;
3163 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
3164 bp->b_flags |= B_CACHE;
3170 * check for size inconsistencies for non-VMIO case.
3172 if (bp->b_bcount != size) {
3173 if ((bp->b_flags & B_VMIO) == 0 ||
3174 (size > bp->b_kvasize)) {
3175 if (bp->b_flags & B_DELWRI) {
3177 * If buffer is pinned and caller does
3178 * not want sleep waiting for it to be
3179 * unpinned, bail out
3181 if (bp->b_pin_count > 0) {
3182 if (flags & GB_LOCK_NOWAIT) {
3189 bp->b_flags |= B_NOCACHE;
3192 if (LIST_EMPTY(&bp->b_dep)) {
3193 bp->b_flags |= B_RELBUF;
3196 bp->b_flags |= B_NOCACHE;
3205 * Handle the case of unmapped buffer which should
3206 * become mapped, or the buffer for which KVA
3207 * reservation is requested.
3209 bp_unmapped_get_kva(bp, blkno, size, flags);
3212 * If the size is inconsistant in the VMIO case, we can resize
3213 * the buffer. This might lead to B_CACHE getting set or
3214 * cleared. If the size has not changed, B_CACHE remains
3215 * unchanged from its previous state.
3217 if (bp->b_bcount != size)
3220 KASSERT(bp->b_offset != NOOFFSET,
3221 ("getblk: no buffer offset"));
3224 * A buffer with B_DELWRI set and B_CACHE clear must
3225 * be committed before we can return the buffer in
3226 * order to prevent the caller from issuing a read
3227 * ( due to B_CACHE not being set ) and overwriting
3230 * Most callers, including NFS and FFS, need this to
3231 * operate properly either because they assume they
3232 * can issue a read if B_CACHE is not set, or because
3233 * ( for example ) an uncached B_DELWRI might loop due
3234 * to softupdates re-dirtying the buffer. In the latter
3235 * case, B_CACHE is set after the first write completes,
3236 * preventing further loops.
3237 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
3238 * above while extending the buffer, we cannot allow the
3239 * buffer to remain with B_CACHE set after the write
3240 * completes or it will represent a corrupt state. To
3241 * deal with this we set B_NOCACHE to scrap the buffer
3244 * We might be able to do something fancy, like setting
3245 * B_CACHE in bwrite() except if B_DELWRI is already set,
3246 * so the below call doesn't set B_CACHE, but that gets real
3247 * confusing. This is much easier.
3250 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
3251 bp->b_flags |= B_NOCACHE;
3255 bp->b_flags &= ~B_DONE;
3258 * Buffer is not in-core, create new buffer. The buffer
3259 * returned by getnewbuf() is locked. Note that the returned
3260 * buffer is also considered valid (not marked B_INVAL).
3264 * If the user does not want us to create the buffer, bail out
3267 if (flags & GB_NOCREAT)
3269 bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
3270 offset = blkno * bsize;
3271 vmio = vp->v_object != NULL;
3273 maxsize = size + (offset & PAGE_MASK);
3276 /* Do not allow non-VMIO notmapped buffers. */
3277 flags &= ~GB_UNMAPPED;
3279 maxsize = imax(maxsize, bsize);
3281 bp = getnewbuf(vp, slpflag, slptimeo, size, maxsize, flags);
3283 if (slpflag || slptimeo)
3289 * This code is used to make sure that a buffer is not
3290 * created while the getnewbuf routine is blocked.
3291 * This can be a problem whether the vnode is locked or not.
3292 * If the buffer is created out from under us, we have to
3293 * throw away the one we just created.
3295 * Note: this must occur before we associate the buffer
3296 * with the vp especially considering limitations in
3297 * the splay tree implementation when dealing with duplicate
3301 if (gbincore(bo, blkno)) {
3303 bp->b_flags |= B_INVAL;
3309 * Insert the buffer into the hash, so that it can
3310 * be found by incore.
3312 bp->b_blkno = bp->b_lblkno = blkno;
3313 bp->b_offset = offset;
3318 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
3319 * buffer size starts out as 0, B_CACHE will be set by
3320 * allocbuf() for the VMIO case prior to it testing the
3321 * backing store for validity.
3325 bp->b_flags |= B_VMIO;
3326 KASSERT(vp->v_object == bp->b_bufobj->bo_object,
3327 ("ARGH! different b_bufobj->bo_object %p %p %p\n",
3328 bp, vp->v_object, bp->b_bufobj->bo_object));
3330 bp->b_flags &= ~B_VMIO;
3331 KASSERT(bp->b_bufobj->bo_object == NULL,
3332 ("ARGH! has b_bufobj->bo_object %p %p\n",
3333 bp, bp->b_bufobj->bo_object));
3334 BUF_CHECK_MAPPED(bp);
3338 bp->b_flags &= ~B_DONE;
3340 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
3341 BUF_ASSERT_HELD(bp);
3343 KASSERT(bp->b_bufobj == bo,
3344 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3349 * Get an empty, disassociated buffer of given size. The buffer is initially
3353 geteblk(int size, int flags)
3358 maxsize = (size + BKVAMASK) & ~BKVAMASK;
3359 while ((bp = getnewbuf(NULL, 0, 0, size, maxsize, flags)) == NULL) {
3360 if ((flags & GB_NOWAIT_BD) &&
3361 (curthread->td_pflags & TDP_BUFNEED) != 0)
3365 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
3366 BUF_ASSERT_HELD(bp);
3372 * This code constitutes the buffer memory from either anonymous system
3373 * memory (in the case of non-VMIO operations) or from an associated
3374 * VM object (in the case of VMIO operations). This code is able to
3375 * resize a buffer up or down.
3377 * Note that this code is tricky, and has many complications to resolve
3378 * deadlock or inconsistant data situations. Tread lightly!!!
3379 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3380 * the caller. Calling this code willy nilly can result in the loss of data.
3382 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
3383 * B_CACHE for the non-VMIO case.
3387 allocbuf(struct buf *bp, int size)
3389 int newbsize, mbsize;
3392 BUF_ASSERT_HELD(bp);
3394 if (bp->b_kvasize < size)
3395 panic("allocbuf: buffer too small");
3397 if ((bp->b_flags & B_VMIO) == 0) {
3401 * Just get anonymous memory from the kernel. Don't
3402 * mess with B_CACHE.
3404 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3405 if (bp->b_flags & B_MALLOC)
3408 newbsize = round_page(size);
3410 if (newbsize < bp->b_bufsize) {
3412 * malloced buffers are not shrunk
3414 if (bp->b_flags & B_MALLOC) {
3416 bp->b_bcount = size;
3418 free(bp->b_data, M_BIOBUF);
3419 if (bp->b_bufsize) {
3420 atomic_subtract_long(
3426 bp->b_saveaddr = bp->b_kvabase;
3427 bp->b_data = bp->b_saveaddr;
3429 bp->b_flags &= ~B_MALLOC;
3433 vm_hold_free_pages(bp, newbsize);
3434 } else if (newbsize > bp->b_bufsize) {
3436 * We only use malloced memory on the first allocation.
3437 * and revert to page-allocated memory when the buffer
3441 * There is a potential smp race here that could lead
3442 * to bufmallocspace slightly passing the max. It
3443 * is probably extremely rare and not worth worrying
3446 if ( (bufmallocspace < maxbufmallocspace) &&
3447 (bp->b_bufsize == 0) &&
3448 (mbsize <= PAGE_SIZE/2)) {
3450 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
3451 bp->b_bufsize = mbsize;
3452 bp->b_bcount = size;
3453 bp->b_flags |= B_MALLOC;
3454 atomic_add_long(&bufmallocspace, mbsize);
3460 * If the buffer is growing on its other-than-first allocation,
3461 * then we revert to the page-allocation scheme.
3463 if (bp->b_flags & B_MALLOC) {
3464 origbuf = bp->b_data;
3465 origbufsize = bp->b_bufsize;
3466 bp->b_data = bp->b_kvabase;
3467 if (bp->b_bufsize) {
3468 atomic_subtract_long(&bufmallocspace,
3473 bp->b_flags &= ~B_MALLOC;
3474 newbsize = round_page(newbsize);
3478 (vm_offset_t) bp->b_data + bp->b_bufsize,
3479 (vm_offset_t) bp->b_data + newbsize);
3481 bcopy(origbuf, bp->b_data, origbufsize);
3482 free(origbuf, M_BIOBUF);
3488 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3489 desiredpages = (size == 0) ? 0 :
3490 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
3492 if (bp->b_flags & B_MALLOC)
3493 panic("allocbuf: VMIO buffer can't be malloced");
3495 * Set B_CACHE initially if buffer is 0 length or will become
3498 if (size == 0 || bp->b_bufsize == 0)
3499 bp->b_flags |= B_CACHE;
3501 if (newbsize < bp->b_bufsize) {
3503 * DEV_BSIZE aligned new buffer size is less then the
3504 * DEV_BSIZE aligned existing buffer size. Figure out
3505 * if we have to remove any pages.
3507 if (desiredpages < bp->b_npages) {
3510 if ((bp->b_flags & B_UNMAPPED) == 0) {
3511 BUF_CHECK_MAPPED(bp);
3512 pmap_qremove((vm_offset_t)trunc_page(
3513 (vm_offset_t)bp->b_data) +
3514 (desiredpages << PAGE_SHIFT),
3515 (bp->b_npages - desiredpages));
3517 BUF_CHECK_UNMAPPED(bp);
3518 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3519 for (i = desiredpages; i < bp->b_npages; i++) {
3521 * the page is not freed here -- it
3522 * is the responsibility of
3523 * vnode_pager_setsize
3526 KASSERT(m != bogus_page,
3527 ("allocbuf: bogus page found"));
3528 while (vm_page_sleep_if_busy(m, TRUE,
3532 bp->b_pages[i] = NULL;
3534 vm_page_unwire(m, 0);
3537 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3538 bp->b_npages = desiredpages;
3540 } else if (size > bp->b_bcount) {
3542 * We are growing the buffer, possibly in a
3543 * byte-granular fashion.
3550 * Step 1, bring in the VM pages from the object,
3551 * allocating them if necessary. We must clear
3552 * B_CACHE if these pages are not valid for the
3553 * range covered by the buffer.
3556 obj = bp->b_bufobj->bo_object;
3558 VM_OBJECT_LOCK(obj);
3559 while (bp->b_npages < desiredpages) {
3563 * We must allocate system pages since blocking
3564 * here could interfere with paging I/O, no
3565 * matter which process we are.
3567 * We can only test VPO_BUSY here. Blocking on
3568 * m->busy might lead to a deadlock:
3569 * vm_fault->getpages->cluster_read->allocbuf
3570 * Thus, we specify VM_ALLOC_IGN_SBUSY.
3572 m = vm_page_grab(obj, OFF_TO_IDX(bp->b_offset) +
3573 bp->b_npages, VM_ALLOC_NOBUSY |
3574 VM_ALLOC_SYSTEM | VM_ALLOC_WIRED |
3575 VM_ALLOC_RETRY | VM_ALLOC_IGN_SBUSY |
3576 VM_ALLOC_COUNT(desiredpages - bp->b_npages));
3578 bp->b_flags &= ~B_CACHE;
3579 bp->b_pages[bp->b_npages] = m;
3584 * Step 2. We've loaded the pages into the buffer,
3585 * we have to figure out if we can still have B_CACHE
3586 * set. Note that B_CACHE is set according to the
3587 * byte-granular range ( bcount and size ), new the
3588 * aligned range ( newbsize ).
3590 * The VM test is against m->valid, which is DEV_BSIZE
3591 * aligned. Needless to say, the validity of the data
3592 * needs to also be DEV_BSIZE aligned. Note that this
3593 * fails with NFS if the server or some other client
3594 * extends the file's EOF. If our buffer is resized,
3595 * B_CACHE may remain set! XXX
3598 toff = bp->b_bcount;
3599 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
3601 while ((bp->b_flags & B_CACHE) && toff < size) {
3604 if (tinc > (size - toff))
3607 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
3620 VM_OBJECT_UNLOCK(obj);
3623 * Step 3, fixup the KVM pmap.
3625 if ((bp->b_flags & B_UNMAPPED) == 0)
3628 BUF_CHECK_UNMAPPED(bp);
3631 if (newbsize < bp->b_bufsize)
3633 bp->b_bufsize = newbsize; /* actual buffer allocation */
3634 bp->b_bcount = size; /* requested buffer size */
3638 extern int inflight_transient_maps;
3641 biodone(struct bio *bp)
3644 void (*done)(struct bio *);
3645 vm_offset_t start, end;
3648 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3650 bp->bio_flags |= BIO_DONE;
3651 if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) {
3652 start = trunc_page((vm_offset_t)bp->bio_data);
3653 end = round_page((vm_offset_t)bp->bio_data + bp->bio_length);
3659 done = bp->bio_done;
3666 pmap_qremove(start, OFF_TO_IDX(end - start));
3667 vm_map_remove(bio_transient_map, start, end);
3668 atomic_add_int(&inflight_transient_maps, -1);
3673 * Wait for a BIO to finish.
3675 * XXX: resort to a timeout for now. The optimal locking (if any) for this
3676 * case is not yet clear.
3679 biowait(struct bio *bp, const char *wchan)
3683 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3685 while ((bp->bio_flags & BIO_DONE) == 0)
3686 msleep(bp, mtxp, PRIBIO, wchan, hz / 10);
3688 if (bp->bio_error != 0)
3689 return (bp->bio_error);
3690 if (!(bp->bio_flags & BIO_ERROR))
3696 biofinish(struct bio *bp, struct devstat *stat, int error)
3700 bp->bio_error = error;
3701 bp->bio_flags |= BIO_ERROR;
3704 devstat_end_transaction_bio(stat, bp);
3711 * Wait for buffer I/O completion, returning error status. The buffer
3712 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR
3713 * error and cleared.
3716 bufwait(struct buf *bp)
3718 if (bp->b_iocmd == BIO_READ)
3719 bwait(bp, PRIBIO, "biord");
3721 bwait(bp, PRIBIO, "biowr");
3722 if (bp->b_flags & B_EINTR) {
3723 bp->b_flags &= ~B_EINTR;
3726 if (bp->b_ioflags & BIO_ERROR) {
3727 return (bp->b_error ? bp->b_error : EIO);
3734 * Call back function from struct bio back up to struct buf.
3737 bufdonebio(struct bio *bip)
3741 bp = bip->bio_caller2;
3742 bp->b_resid = bp->b_bcount - bip->bio_completed;
3743 bp->b_resid = bip->bio_resid; /* XXX: remove */
3744 bp->b_ioflags = bip->bio_flags;
3745 bp->b_error = bip->bio_error;
3747 bp->b_ioflags |= BIO_ERROR;
3753 dev_strategy(struct cdev *dev, struct buf *bp)
3758 KASSERT(dev->si_refcount > 0,
3759 ("dev_strategy on un-referenced struct cdev *(%s) %p",
3760 devtoname(dev), dev));
3762 csw = dev_refthread(dev, &ref);
3763 dev_strategy_csw(dev, csw, bp);
3764 dev_relthread(dev, ref);
3768 dev_strategy_csw(struct cdev *dev, struct cdevsw *csw, struct buf *bp)
3772 KASSERT(bp->b_iocmd == BIO_READ || bp->b_iocmd == BIO_WRITE,
3774 KASSERT(((dev->si_flags & SI_ETERNAL) != 0 && csw != NULL) ||
3775 dev->si_threadcount > 0,
3776 ("dev_strategy_csw threadcount cdev *(%s) %p", devtoname(dev),
3779 bp->b_error = ENXIO;
3780 bp->b_ioflags = BIO_ERROR;
3788 /* Try again later */
3789 tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3791 bip->bio_cmd = bp->b_iocmd;
3792 bip->bio_offset = bp->b_iooffset;
3793 bip->bio_length = bp->b_bcount;
3794 bip->bio_bcount = bp->b_bcount; /* XXX: remove */
3796 bip->bio_done = bufdonebio;
3797 bip->bio_caller2 = bp;
3799 (*csw->d_strategy)(bip);
3805 * Finish I/O on a buffer, optionally calling a completion function.
3806 * This is usually called from an interrupt so process blocking is
3809 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3810 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3811 * assuming B_INVAL is clear.
3813 * For the VMIO case, we set B_CACHE if the op was a read and no
3814 * read error occured, or if the op was a write. B_CACHE is never
3815 * set if the buffer is invalid or otherwise uncacheable.
3817 * biodone does not mess with B_INVAL, allowing the I/O routine or the
3818 * initiator to leave B_INVAL set to brelse the buffer out of existance
3819 * in the biodone routine.
3822 bufdone(struct buf *bp)
3824 struct bufobj *dropobj;
3825 void (*biodone)(struct buf *);
3827 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3830 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3831 BUF_ASSERT_HELD(bp);
3833 runningbufwakeup(bp);
3834 if (bp->b_iocmd == BIO_WRITE)
3835 dropobj = bp->b_bufobj;
3836 /* call optional completion function if requested */
3837 if (bp->b_iodone != NULL) {
3838 biodone = bp->b_iodone;
3839 bp->b_iodone = NULL;
3842 bufobj_wdrop(dropobj);
3849 bufobj_wdrop(dropobj);
3853 bufdone_finish(struct buf *bp)
3855 BUF_ASSERT_HELD(bp);
3857 if (!LIST_EMPTY(&bp->b_dep))
3860 if (bp->b_flags & B_VMIO) {
3865 int bogus, i, iosize;
3867 obj = bp->b_bufobj->bo_object;
3868 KASSERT(obj->paging_in_progress >= bp->b_npages,
3869 ("biodone_finish: paging in progress(%d) < b_npages(%d)",
3870 obj->paging_in_progress, bp->b_npages));
3873 KASSERT(vp->v_holdcnt > 0,
3874 ("biodone_finish: vnode %p has zero hold count", vp));
3875 KASSERT(vp->v_object != NULL,
3876 ("biodone_finish: vnode %p has no vm_object", vp));
3878 foff = bp->b_offset;
3879 KASSERT(bp->b_offset != NOOFFSET,
3880 ("biodone_finish: bp %p has no buffer offset", bp));
3883 * Set B_CACHE if the op was a normal read and no error
3884 * occured. B_CACHE is set for writes in the b*write()
3887 iosize = bp->b_bcount - bp->b_resid;
3888 if (bp->b_iocmd == BIO_READ &&
3889 !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3890 !(bp->b_ioflags & BIO_ERROR)) {
3891 bp->b_flags |= B_CACHE;
3894 VM_OBJECT_LOCK(obj);
3895 for (i = 0; i < bp->b_npages; i++) {
3899 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3904 * cleanup bogus pages, restoring the originals
3907 if (m == bogus_page) {
3908 bogus = bogusflag = 1;
3909 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3911 panic("biodone: page disappeared!");
3914 KASSERT(OFF_TO_IDX(foff) == m->pindex,
3915 ("biodone_finish: foff(%jd)/pindex(%ju) mismatch",
3916 (intmax_t)foff, (uintmax_t)m->pindex));
3919 * In the write case, the valid and clean bits are
3920 * already changed correctly ( see bdwrite() ), so we
3921 * only need to do this here in the read case.
3923 if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3924 KASSERT((m->dirty & vm_page_bits(foff &
3925 PAGE_MASK, resid)) == 0, ("bufdone_finish:"
3926 " page %p has unexpected dirty bits", m));
3927 vfs_page_set_valid(bp, foff, m);
3930 vm_page_io_finish(m);
3931 vm_object_pip_subtract(obj, 1);
3932 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3935 vm_object_pip_wakeupn(obj, 0);
3936 VM_OBJECT_UNLOCK(obj);
3937 if (bogus && (bp->b_flags & B_UNMAPPED) == 0) {
3938 BUF_CHECK_MAPPED(bp);
3939 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3940 bp->b_pages, bp->b_npages);
3945 * For asynchronous completions, release the buffer now. The brelse
3946 * will do a wakeup there if necessary - so no need to do a wakeup
3947 * here in the async case. The sync case always needs to do a wakeup.
3950 if (bp->b_flags & B_ASYNC) {
3951 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3960 * This routine is called in lieu of iodone in the case of
3961 * incomplete I/O. This keeps the busy status for pages
3965 vfs_unbusy_pages(struct buf *bp)
3971 runningbufwakeup(bp);
3972 if (!(bp->b_flags & B_VMIO))
3975 obj = bp->b_bufobj->bo_object;
3976 VM_OBJECT_LOCK(obj);
3977 for (i = 0; i < bp->b_npages; i++) {
3979 if (m == bogus_page) {
3980 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3982 panic("vfs_unbusy_pages: page missing\n");
3984 if ((bp->b_flags & B_UNMAPPED) == 0) {
3985 BUF_CHECK_MAPPED(bp);
3986 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3987 bp->b_pages, bp->b_npages);
3989 BUF_CHECK_UNMAPPED(bp);
3991 vm_object_pip_subtract(obj, 1);
3992 vm_page_io_finish(m);
3994 vm_object_pip_wakeupn(obj, 0);
3995 VM_OBJECT_UNLOCK(obj);
3999 * vfs_page_set_valid:
4001 * Set the valid bits in a page based on the supplied offset. The
4002 * range is restricted to the buffer's size.
4004 * This routine is typically called after a read completes.
4007 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4012 * Compute the end offset, eoff, such that [off, eoff) does not span a
4013 * page boundary and eoff is not greater than the end of the buffer.
4014 * The end of the buffer, in this case, is our file EOF, not the
4015 * allocation size of the buffer.
4017 eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
4018 if (eoff > bp->b_offset + bp->b_bcount)
4019 eoff = bp->b_offset + bp->b_bcount;
4022 * Set valid range. This is typically the entire buffer and thus the
4026 vm_page_set_valid(m, off & PAGE_MASK, eoff - off);
4030 * vfs_page_set_validclean:
4032 * Set the valid bits and clear the dirty bits in a page based on the
4033 * supplied offset. The range is restricted to the buffer's size.
4036 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4038 vm_ooffset_t soff, eoff;
4041 * Start and end offsets in buffer. eoff - soff may not cross a
4042 * page boundry or cross the end of the buffer. The end of the
4043 * buffer, in this case, is our file EOF, not the allocation size
4047 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4048 if (eoff > bp->b_offset + bp->b_bcount)
4049 eoff = bp->b_offset + bp->b_bcount;
4052 * Set valid range. This is typically the entire buffer and thus the
4056 vm_page_set_validclean(
4058 (vm_offset_t) (soff & PAGE_MASK),
4059 (vm_offset_t) (eoff - soff)
4065 * Ensure that all buffer pages are not busied by VPO_BUSY flag. If
4066 * any page is busy, drain the flag.
4069 vfs_drain_busy_pages(struct buf *bp)
4074 VM_OBJECT_LOCK_ASSERT(bp->b_bufobj->bo_object, MA_OWNED);
4076 for (i = 0; i < bp->b_npages; i++) {
4078 if ((m->oflags & VPO_BUSY) != 0) {
4079 for (; last_busied < i; last_busied++)
4080 vm_page_busy(bp->b_pages[last_busied]);
4081 while ((m->oflags & VPO_BUSY) != 0)
4082 vm_page_sleep(m, "vbpage");
4085 for (i = 0; i < last_busied; i++)
4086 vm_page_wakeup(bp->b_pages[i]);
4090 * This routine is called before a device strategy routine.
4091 * It is used to tell the VM system that paging I/O is in
4092 * progress, and treat the pages associated with the buffer
4093 * almost as being VPO_BUSY. Also the object paging_in_progress
4094 * flag is handled to make sure that the object doesn't become
4097 * Since I/O has not been initiated yet, certain buffer flags
4098 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
4099 * and should be ignored.
4102 vfs_busy_pages(struct buf *bp, int clear_modify)
4109 if (!(bp->b_flags & B_VMIO))
4112 obj = bp->b_bufobj->bo_object;
4113 foff = bp->b_offset;
4114 KASSERT(bp->b_offset != NOOFFSET,
4115 ("vfs_busy_pages: no buffer offset"));
4116 VM_OBJECT_LOCK(obj);
4117 vfs_drain_busy_pages(bp);
4118 if (bp->b_bufsize != 0)
4119 vfs_setdirty_locked_object(bp);
4121 for (i = 0; i < bp->b_npages; i++) {
4124 if ((bp->b_flags & B_CLUSTER) == 0) {
4125 vm_object_pip_add(obj, 1);
4126 vm_page_io_start(m);
4129 * When readying a buffer for a read ( i.e
4130 * clear_modify == 0 ), it is important to do
4131 * bogus_page replacement for valid pages in
4132 * partially instantiated buffers. Partially
4133 * instantiated buffers can, in turn, occur when
4134 * reconstituting a buffer from its VM backing store
4135 * base. We only have to do this if B_CACHE is
4136 * clear ( which causes the I/O to occur in the
4137 * first place ). The replacement prevents the read
4138 * I/O from overwriting potentially dirty VM-backed
4139 * pages. XXX bogus page replacement is, uh, bogus.
4140 * It may not work properly with small-block devices.
4141 * We need to find a better way.
4144 pmap_remove_write(m);
4145 vfs_page_set_validclean(bp, foff, m);
4146 } else if (m->valid == VM_PAGE_BITS_ALL &&
4147 (bp->b_flags & B_CACHE) == 0) {
4148 bp->b_pages[i] = bogus_page;
4151 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4153 VM_OBJECT_UNLOCK(obj);
4154 if (bogus && (bp->b_flags & B_UNMAPPED) == 0) {
4155 BUF_CHECK_MAPPED(bp);
4156 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4157 bp->b_pages, bp->b_npages);
4162 * vfs_bio_set_valid:
4164 * Set the range within the buffer to valid. The range is
4165 * relative to the beginning of the buffer, b_offset. Note that
4166 * b_offset itself may be offset from the beginning of the first
4170 vfs_bio_set_valid(struct buf *bp, int base, int size)
4175 if (!(bp->b_flags & B_VMIO))
4179 * Fixup base to be relative to beginning of first page.
4180 * Set initial n to be the maximum number of bytes in the
4181 * first page that can be validated.
4183 base += (bp->b_offset & PAGE_MASK);
4184 n = PAGE_SIZE - (base & PAGE_MASK);
4186 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
4187 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4191 vm_page_set_valid(m, base & PAGE_MASK, n);
4196 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
4202 * If the specified buffer is a non-VMIO buffer, clear the entire
4203 * buffer. If the specified buffer is a VMIO buffer, clear and
4204 * validate only the previously invalid portions of the buffer.
4205 * This routine essentially fakes an I/O, so we need to clear
4206 * BIO_ERROR and B_INVAL.
4208 * Note that while we only theoretically need to clear through b_bcount,
4209 * we go ahead and clear through b_bufsize.
4212 vfs_bio_clrbuf(struct buf *bp)
4214 int i, j, mask, sa, ea, slide;
4216 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
4220 bp->b_flags &= ~B_INVAL;
4221 bp->b_ioflags &= ~BIO_ERROR;
4222 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
4223 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4224 (bp->b_offset & PAGE_MASK) == 0) {
4225 if (bp->b_pages[0] == bogus_page)
4227 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4228 VM_OBJECT_LOCK_ASSERT(bp->b_pages[0]->object, MA_OWNED);
4229 if ((bp->b_pages[0]->valid & mask) == mask)
4231 if ((bp->b_pages[0]->valid & mask) == 0) {
4232 pmap_zero_page_area(bp->b_pages[0], 0, bp->b_bufsize);
4233 bp->b_pages[0]->valid |= mask;
4237 sa = bp->b_offset & PAGE_MASK;
4239 for (i = 0; i < bp->b_npages; i++, sa = 0) {
4240 slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize);
4241 ea = slide & PAGE_MASK;
4244 if (bp->b_pages[i] == bogus_page)
4247 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4248 VM_OBJECT_LOCK_ASSERT(bp->b_pages[i]->object, MA_OWNED);
4249 if ((bp->b_pages[i]->valid & mask) == mask)
4251 if ((bp->b_pages[i]->valid & mask) == 0)
4252 pmap_zero_page_area(bp->b_pages[i], sa, ea - sa);
4254 for (; sa < ea; sa += DEV_BSIZE, j++) {
4255 if ((bp->b_pages[i]->valid & (1 << j)) == 0) {
4256 pmap_zero_page_area(bp->b_pages[i],
4261 bp->b_pages[i]->valid |= mask;
4264 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
4269 vfs_bio_bzero_buf(struct buf *bp, int base, int size)
4274 if ((bp->b_flags & B_UNMAPPED) == 0) {
4275 BUF_CHECK_MAPPED(bp);
4276 bzero(bp->b_data + base, size);
4278 BUF_CHECK_UNMAPPED(bp);
4279 n = PAGE_SIZE - (base & PAGE_MASK);
4280 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
4281 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4285 pmap_zero_page_area(m, base & PAGE_MASK, n);
4290 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
4295 * vm_hold_load_pages and vm_hold_free_pages get pages into
4296 * a buffers address space. The pages are anonymous and are
4297 * not associated with a file object.
4300 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4306 BUF_CHECK_MAPPED(bp);
4308 to = round_page(to);
4309 from = round_page(from);
4310 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4312 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4315 * note: must allocate system pages since blocking here
4316 * could interfere with paging I/O, no matter which
4319 p = vm_page_alloc(NULL, 0, VM_ALLOC_SYSTEM | VM_ALLOC_NOOBJ |
4320 VM_ALLOC_WIRED | VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT));
4325 pmap_qenter(pg, &p, 1);
4326 bp->b_pages[index] = p;
4328 bp->b_npages = index;
4331 /* Return pages associated with this buf to the vm system */
4333 vm_hold_free_pages(struct buf *bp, int newbsize)
4337 int index, newnpages;
4339 BUF_CHECK_MAPPED(bp);
4341 from = round_page((vm_offset_t)bp->b_data + newbsize);
4342 newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4343 if (bp->b_npages > newnpages)
4344 pmap_qremove(from, bp->b_npages - newnpages);
4345 for (index = newnpages; index < bp->b_npages; index++) {
4346 p = bp->b_pages[index];
4347 bp->b_pages[index] = NULL;
4349 printf("vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
4350 (intmax_t)bp->b_blkno, (intmax_t)bp->b_lblkno);
4353 atomic_subtract_int(&cnt.v_wire_count, 1);
4355 bp->b_npages = newnpages;
4359 * Map an IO request into kernel virtual address space.
4361 * All requests are (re)mapped into kernel VA space.
4362 * Notice that we use b_bufsize for the size of the buffer
4363 * to be mapped. b_bcount might be modified by the driver.
4365 * Note that even if the caller determines that the address space should
4366 * be valid, a race or a smaller-file mapped into a larger space may
4367 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
4368 * check the return value.
4371 vmapbuf(struct buf *bp, int mapbuf)
4377 if (bp->b_bufsize < 0)
4379 prot = VM_PROT_READ;
4380 if (bp->b_iocmd == BIO_READ)
4381 prot |= VM_PROT_WRITE; /* Less backwards than it looks */
4382 if ((pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
4383 (vm_offset_t)bp->b_data, bp->b_bufsize, prot, bp->b_pages,
4384 btoc(MAXPHYS))) < 0)
4386 bp->b_npages = pidx;
4387 if (mapbuf || !unmapped_buf_allowed) {
4388 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
4389 kva = bp->b_saveaddr;
4390 bp->b_saveaddr = bp->b_data;
4391 bp->b_data = kva + (((vm_offset_t)bp->b_data) & PAGE_MASK);
4392 bp->b_flags &= ~B_UNMAPPED;
4394 bp->b_flags |= B_UNMAPPED;
4395 bp->b_offset = ((vm_offset_t)bp->b_data) & PAGE_MASK;
4396 bp->b_saveaddr = bp->b_data;
4397 bp->b_data = unmapped_buf;
4403 * Free the io map PTEs associated with this IO operation.
4404 * We also invalidate the TLB entries and restore the original b_addr.
4407 vunmapbuf(struct buf *bp)
4411 npages = bp->b_npages;
4412 if (bp->b_flags & B_UNMAPPED)
4413 bp->b_flags &= ~B_UNMAPPED;
4415 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4416 vm_page_unhold_pages(bp->b_pages, npages);
4418 bp->b_data = bp->b_saveaddr;
4422 bdone(struct buf *bp)
4426 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4428 bp->b_flags |= B_DONE;
4434 bwait(struct buf *bp, u_char pri, const char *wchan)
4438 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4440 while ((bp->b_flags & B_DONE) == 0)
4441 msleep(bp, mtxp, pri, wchan, 0);
4446 bufsync(struct bufobj *bo, int waitfor)
4449 return (VOP_FSYNC(bo->__bo_vnode, waitfor, curthread));
4453 bufstrategy(struct bufobj *bo, struct buf *bp)
4459 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
4460 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
4461 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
4462 i = VOP_STRATEGY(vp, bp);
4463 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
4467 bufobj_wrefl(struct bufobj *bo)
4470 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4471 ASSERT_BO_LOCKED(bo);
4476 bufobj_wref(struct bufobj *bo)
4479 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4486 bufobj_wdrop(struct bufobj *bo)
4489 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
4491 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
4492 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
4493 bo->bo_flag &= ~BO_WWAIT;
4494 wakeup(&bo->bo_numoutput);
4500 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
4504 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
4505 ASSERT_BO_LOCKED(bo);
4507 while (bo->bo_numoutput) {
4508 bo->bo_flag |= BO_WWAIT;
4509 error = msleep(&bo->bo_numoutput, BO_MTX(bo),
4510 slpflag | (PRIBIO + 1), "bo_wwait", timeo);
4518 bpin(struct buf *bp)
4522 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4529 bunpin(struct buf *bp)
4533 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4535 if (--bp->b_pin_count == 0)
4541 bunpin_wait(struct buf *bp)
4545 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4547 while (bp->b_pin_count > 0)
4548 msleep(bp, mtxp, PRIBIO, "bwunpin", 0);
4553 * Set bio_data or bio_ma for struct bio from the struct buf.
4556 bdata2bio(struct buf *bp, struct bio *bip)
4559 if ((bp->b_flags & B_UNMAPPED) != 0) {
4560 KASSERT(unmapped_buf_allowed, ("unmapped"));
4561 bip->bio_ma = bp->b_pages;
4562 bip->bio_ma_n = bp->b_npages;
4563 bip->bio_data = unmapped_buf;
4564 bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
4565 bip->bio_flags |= BIO_UNMAPPED;
4566 KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) /
4567 PAGE_SIZE == bp->b_npages,
4568 ("Buffer %p too short: %d %jd %d", bp, bip->bio_ma_offset,
4569 (uintmax_t)bip->bio_length, bip->bio_ma_n));
4571 bip->bio_data = bp->b_data;
4576 #include "opt_ddb.h"
4578 #include <ddb/ddb.h>
4580 /* DDB command to show buffer data */
4581 DB_SHOW_COMMAND(buffer, db_show_buffer)
4584 struct buf *bp = (struct buf *)addr;
4587 db_printf("usage: show buffer <addr>\n");
4591 db_printf("buf at %p\n", bp);
4592 db_printf("b_flags = 0x%b, b_xflags=0x%b, b_vflags=0x%b\n",
4593 (u_int)bp->b_flags, PRINT_BUF_FLAGS, (u_int)bp->b_xflags,
4594 PRINT_BUF_XFLAGS, (u_int)bp->b_vflags, PRINT_BUF_VFLAGS);
4596 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4597 "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_lblkno = %jd, "
4599 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4600 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4601 (intmax_t)bp->b_lblkno, bp->b_dep.lh_first);
4604 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4605 for (i = 0; i < bp->b_npages; i++) {
4608 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4609 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4610 if ((i + 1) < bp->b_npages)
4616 BUF_LOCKPRINTINFO(bp);
4619 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
4624 for (i = 0; i < nbuf; i++) {
4626 if (BUF_ISLOCKED(bp)) {
4627 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4633 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
4639 db_printf("usage: show vnodebufs <addr>\n");
4642 vp = (struct vnode *)addr;
4643 db_printf("Clean buffers:\n");
4644 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
4645 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4648 db_printf("Dirty buffers:\n");
4649 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
4650 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4655 DB_COMMAND(countfreebufs, db_coundfreebufs)
4658 int i, used = 0, nfree = 0;
4661 db_printf("usage: countfreebufs\n");
4665 for (i = 0; i < nbuf; i++) {
4667 if ((bp->b_vflags & BV_INFREECNT) != 0)
4673 db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
4675 db_printf("numfreebuffers is %d\n", numfreebuffers);