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/rwlock.h>
66 #include <sys/sysctl.h>
67 #include <sys/vmmeter.h>
68 #include <sys/vnode.h>
69 #include <geom/geom.h>
71 #include <vm/vm_param.h>
72 #include <vm/vm_kern.h>
73 #include <vm/vm_pageout.h>
74 #include <vm/vm_page.h>
75 #include <vm/vm_object.h>
76 #include <vm/vm_extern.h>
77 #include <vm/vm_map.h>
78 #include "opt_compat.h"
79 #include "opt_directio.h"
82 static MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
84 struct bio_ops bioops; /* I/O operation notification */
86 struct buf_ops buf_ops_bio = {
87 .bop_name = "buf_ops_bio",
88 .bop_write = bufwrite,
89 .bop_strategy = bufstrategy,
91 .bop_bdflush = bufbdflush,
95 * XXX buf is global because kern_shutdown.c and ffs_checkoverlap has
96 * carnal knowledge of buffers. This knowledge should be moved to vfs_bio.c.
98 struct buf *buf; /* buffer header pool */
101 static struct proc *bufdaemonproc;
103 static int inmem(struct vnode *vp, daddr_t blkno);
104 static void vm_hold_free_pages(struct buf *bp, int newbsize);
105 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
107 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m);
108 static void vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off,
110 static void vfs_drain_busy_pages(struct buf *bp);
111 static void vfs_clean_pages_dirty_buf(struct buf *bp);
112 static void vfs_setdirty_locked_object(struct buf *bp);
113 static void vfs_vmio_release(struct buf *bp);
114 static int vfs_bio_clcheck(struct vnode *vp, int size,
115 daddr_t lblkno, daddr_t blkno);
116 static int buf_do_flush(struct vnode *vp);
117 static int flushbufqueues(struct vnode *, int, int);
118 static void buf_daemon(void);
119 static void bremfreel(struct buf *bp);
120 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
121 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
122 static int sysctl_bufspace(SYSCTL_HANDLER_ARGS);
125 int vmiodirenable = TRUE;
126 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
127 "Use the VM system for directory writes");
128 long runningbufspace;
129 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
130 "Amount of presently outstanding async buffer io");
131 static long bufspace;
132 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
133 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
134 SYSCTL_PROC(_vfs, OID_AUTO, bufspace, CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RD,
135 &bufspace, 0, sysctl_bufspace, "L", "Virtual memory used for buffers");
137 SYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
138 "Virtual memory used for buffers");
140 static long unmapped_bufspace;
141 SYSCTL_LONG(_vfs, OID_AUTO, unmapped_bufspace, CTLFLAG_RD,
142 &unmapped_bufspace, 0,
143 "Amount of unmapped buffers, inclusive in the bufspace");
144 static long maxbufspace;
145 SYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
146 "Maximum allowed value of bufspace (including buf_daemon)");
147 static long bufmallocspace;
148 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
149 "Amount of malloced memory for buffers");
150 static long maxbufmallocspace;
151 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace, 0,
152 "Maximum amount of malloced memory for buffers");
153 static long lobufspace;
154 SYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
155 "Minimum amount of buffers we want to have");
157 SYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
158 "Maximum allowed value of bufspace (excluding buf_daemon)");
159 static int bufreusecnt;
160 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW, &bufreusecnt, 0,
161 "Number of times we have reused a buffer");
162 static int buffreekvacnt;
163 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
164 "Number of times we have freed the KVA space from some buffer");
165 static int bufdefragcnt;
166 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
167 "Number of times we have had to repeat buffer allocation to defragment");
168 static long lorunningspace;
169 SYSCTL_LONG(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
170 "Minimum preferred space used for in-progress I/O");
171 static long hirunningspace;
172 SYSCTL_LONG(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
173 "Maximum amount of space to use for in-progress I/O");
174 int dirtybufferflushes;
175 SYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
176 0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
178 SYSCTL_INT(_vfs, OID_AUTO, bdwriteskip, CTLFLAG_RW, &bdwriteskip,
179 0, "Number of buffers supplied to bdwrite with snapshot deadlock risk");
180 int altbufferflushes;
181 SYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes,
182 0, "Number of fsync flushes to limit dirty buffers");
183 static int recursiveflushes;
184 SYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes,
185 0, "Number of flushes skipped due to being recursive");
186 static int numdirtybuffers;
187 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
188 "Number of buffers that are dirty (has unwritten changes) at the moment");
189 static int lodirtybuffers;
190 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
191 "How many buffers we want to have free before bufdaemon can sleep");
192 static int hidirtybuffers;
193 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
194 "When the number of dirty buffers is considered severe");
196 SYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh,
197 0, "Number of bdwrite to bawrite conversions to clear dirty buffers");
198 static int numfreebuffers;
199 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
200 "Number of free buffers");
201 static int lofreebuffers;
202 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
204 static int hifreebuffers;
205 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
206 "XXX Complicatedly unused");
207 static int getnewbufcalls;
208 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
209 "Number of calls to getnewbuf");
210 static int getnewbufrestarts;
211 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
212 "Number of times getnewbuf has had to restart a buffer aquisition");
213 static int mappingrestarts;
214 SYSCTL_INT(_vfs, OID_AUTO, mappingrestarts, CTLFLAG_RW, &mappingrestarts, 0,
215 "Number of times getblk has had to restart a buffer mapping for "
217 static int flushbufqtarget = 100;
218 SYSCTL_INT(_vfs, OID_AUTO, flushbufqtarget, CTLFLAG_RW, &flushbufqtarget, 0,
219 "Amount of work to do in flushbufqueues when helping bufdaemon");
220 static long notbufdflashes;
221 SYSCTL_LONG(_vfs, OID_AUTO, notbufdflashes, CTLFLAG_RD, ¬bufdflashes, 0,
222 "Number of dirty buffer flushes done by the bufdaemon helpers");
223 static long barrierwrites;
224 SYSCTL_LONG(_vfs, OID_AUTO, barrierwrites, CTLFLAG_RW, &barrierwrites, 0,
225 "Number of barrier writes");
226 SYSCTL_INT(_vfs, OID_AUTO, unmapped_buf_allowed, CTLFLAG_RD,
227 &unmapped_buf_allowed, 0,
228 "Permit the use of the unmapped i/o");
231 * Wakeup point for bufdaemon, as well as indicator of whether it is already
232 * active. Set to 1 when the bufdaemon is already "on" the queue, 0 when it
235 static int bd_request;
238 * Request for the buf daemon to write more buffers than is indicated by
239 * lodirtybuf. This may be necessary to push out excess dependencies or
240 * defragment the address space where a simple count of the number of dirty
241 * buffers is insufficient to characterize the demand for flushing them.
243 static int bd_speedupreq;
246 * This lock synchronizes access to bd_request.
248 static struct mtx bdlock;
251 * bogus page -- for I/O to/from partially complete buffers
252 * this is a temporary solution to the problem, but it is not
253 * really that bad. it would be better to split the buffer
254 * for input in the case of buffers partially already in memory,
255 * but the code is intricate enough already.
257 vm_page_t bogus_page;
260 * Synchronization (sleep/wakeup) variable for active buffer space requests.
261 * Set when wait starts, cleared prior to wakeup().
262 * Used in runningbufwakeup() and waitrunningbufspace().
264 static int runningbufreq;
267 * This lock protects the runningbufreq and synchronizes runningbufwakeup and
268 * waitrunningbufspace().
270 static struct mtx rbreqlock;
273 * Synchronization (sleep/wakeup) variable for buffer requests.
274 * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
276 * Used in numdirtywakeup(), bufspacewakeup(), bufcountwakeup(), bwillwrite(),
277 * getnewbuf(), and getblk().
279 static int needsbuffer;
282 * Lock that protects needsbuffer and the sleeps/wakeups surrounding it.
284 static struct mtx nblock;
287 * Definitions for the buffer free lists.
289 #define BUFFER_QUEUES 5 /* number of free buffer queues */
291 #define QUEUE_NONE 0 /* on no queue */
292 #define QUEUE_CLEAN 1 /* non-B_DELWRI buffers */
293 #define QUEUE_DIRTY 2 /* B_DELWRI buffers */
294 #define QUEUE_EMPTYKVA 3 /* empty buffer headers w/KVA assignment */
295 #define QUEUE_EMPTY 4 /* 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_flags & B_INFREECNT) == 0,
422 ("buf %p already counted as free", bp));
423 bp->b_flags |= B_INFREECNT;
424 old = atomic_fetchadd_int(&numfreebuffers, 1);
425 KASSERT(old >= 0 && old < nbuf,
426 ("numfreebuffers climbed to %d", old + 1));
429 needsbuffer &= ~VFS_BIO_NEED_ANY;
430 if (numfreebuffers >= hifreebuffers)
431 needsbuffer &= ~VFS_BIO_NEED_FREE;
432 wakeup(&needsbuffer);
438 * waitrunningbufspace()
440 * runningbufspace is a measure of the amount of I/O currently
441 * running. This routine is used in async-write situations to
442 * prevent creating huge backups of pending writes to a device.
443 * Only asynchronous writes are governed by this function.
445 * Reads will adjust runningbufspace, but will not block based on it.
446 * The read load has a side effect of reducing the allowed write load.
448 * This does NOT turn an async write into a sync write. It waits
449 * for earlier writes to complete and generally returns before the
450 * caller's write has reached the device.
453 waitrunningbufspace(void)
456 mtx_lock(&rbreqlock);
457 while (runningbufspace > hirunningspace) {
459 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
461 mtx_unlock(&rbreqlock);
466 * vfs_buf_test_cache:
468 * Called when a buffer is extended. This function clears the B_CACHE
469 * bit if the newly extended portion of the buffer does not contain
474 vfs_buf_test_cache(struct buf *bp,
475 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
479 VM_OBJECT_ASSERT_WLOCKED(m->object);
480 if (bp->b_flags & B_CACHE) {
481 int base = (foff + off) & PAGE_MASK;
482 if (vm_page_is_valid(m, base, size) == 0)
483 bp->b_flags &= ~B_CACHE;
487 /* Wake up the buffer daemon if necessary */
490 bd_wakeup(int dirtybuflevel)
494 if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
502 * bd_speedup - speedup the buffer cache flushing code
512 if (bd_speedupreq == 0 || bd_request == 0)
522 #define TRANSIENT_DENOM 5
524 #define TRANSIENT_DENOM 10
528 * Calculating buffer cache scaling values and reserve space for buffer
529 * headers. This is called during low level kernel initialization and
530 * may be called more then once. We CANNOT write to the memory area
531 * being reserved at this time.
534 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
537 long maxbuf, maxbuf_sz, buf_sz, biotmap_sz;
540 * physmem_est is in pages. Convert it to kilobytes (assumes
541 * PAGE_SIZE is >= 1K)
543 physmem_est = physmem_est * (PAGE_SIZE / 1024);
546 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
547 * For the first 64MB of ram nominally allocate sufficient buffers to
548 * cover 1/4 of our ram. Beyond the first 64MB allocate additional
549 * buffers to cover 1/10 of our ram over 64MB. When auto-sizing
550 * the buffer cache we limit the eventual kva reservation to
553 * factor represents the 1/4 x ram conversion.
556 int factor = 4 * BKVASIZE / 1024;
559 if (physmem_est > 4096)
560 nbuf += min((physmem_est - 4096) / factor,
562 if (physmem_est > 65536)
563 nbuf += (physmem_est - 65536) * 2 / (factor * 5);
565 if (maxbcache && nbuf > maxbcache / BKVASIZE)
566 nbuf = maxbcache / BKVASIZE;
571 /* XXX Avoid unsigned long overflows later on with maxbufspace. */
572 maxbuf = (LONG_MAX / 3) / BKVASIZE;
575 printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
581 * Ideal allocation size for the transient bio submap if 10%
582 * of the maximal space buffer map. This roughly corresponds
583 * to the amount of the buffer mapped for typical UFS load.
585 * Clip the buffer map to reserve space for the transient
586 * BIOs, if its extent is bigger than 90% (80% on i386) of the
587 * maximum buffer map extent on the platform.
589 * The fall-back to the maxbuf in case of maxbcache unset,
590 * allows to not trim the buffer KVA for the architectures
591 * with ample KVA space.
593 if (bio_transient_maxcnt == 0 && unmapped_buf_allowed) {
594 maxbuf_sz = maxbcache != 0 ? maxbcache : maxbuf * BKVASIZE;
595 buf_sz = (long)nbuf * BKVASIZE;
596 if (buf_sz < maxbuf_sz / TRANSIENT_DENOM *
597 (TRANSIENT_DENOM - 1)) {
599 * There is more KVA than memory. Do not
600 * adjust buffer map size, and assign the rest
601 * of maxbuf to transient map.
603 biotmap_sz = maxbuf_sz - buf_sz;
606 * Buffer map spans all KVA we could afford on
607 * this platform. Give 10% (20% on i386) of
608 * the buffer map to the transient bio map.
610 biotmap_sz = buf_sz / TRANSIENT_DENOM;
611 buf_sz -= biotmap_sz;
613 if (biotmap_sz / INT_MAX > MAXPHYS)
614 bio_transient_maxcnt = INT_MAX;
616 bio_transient_maxcnt = biotmap_sz / MAXPHYS;
618 * Artifically limit to 1024 simultaneous in-flight I/Os
619 * using the transient mapping.
621 if (bio_transient_maxcnt > 1024)
622 bio_transient_maxcnt = 1024;
624 nbuf = buf_sz / BKVASIZE;
628 * swbufs are used as temporary holders for I/O, such as paging I/O.
629 * We have no less then 16 and no more then 256.
631 nswbuf = max(min(nbuf/4, 256), 16);
633 if (nswbuf < NSWBUF_MIN)
641 * Reserve space for the buffer cache buffers
644 v = (caddr_t)(swbuf + nswbuf);
646 v = (caddr_t)(buf + nbuf);
651 /* Initialize the buffer subsystem. Called before use of any buffers. */
658 mtx_init(&bqlock, "buf queue lock", NULL, MTX_DEF);
659 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
660 mtx_init(&nblock, "needsbuffer lock", NULL, MTX_DEF);
661 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
663 /* next, make a null set of free lists */
664 for (i = 0; i < BUFFER_QUEUES; i++)
665 TAILQ_INIT(&bufqueues[i]);
667 /* finally, initialize each buffer header and stick on empty q */
668 for (i = 0; i < nbuf; i++) {
670 bzero(bp, sizeof *bp);
671 bp->b_flags = B_INVAL | B_INFREECNT;
672 bp->b_rcred = NOCRED;
673 bp->b_wcred = NOCRED;
674 bp->b_qindex = QUEUE_EMPTY;
676 LIST_INIT(&bp->b_dep);
678 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
680 bq_len[QUEUE_EMPTY]++;
685 * maxbufspace is the absolute maximum amount of buffer space we are
686 * allowed to reserve in KVM and in real terms. The absolute maximum
687 * is nominally used by buf_daemon. hibufspace is the nominal maximum
688 * used by most other processes. The differential is required to
689 * ensure that buf_daemon is able to run when other processes might
690 * be blocked waiting for buffer space.
692 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
693 * this may result in KVM fragmentation which is not handled optimally
696 maxbufspace = (long)nbuf * BKVASIZE;
697 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
698 lobufspace = hibufspace - MAXBSIZE;
701 * Note: The 16 MiB upper limit for hirunningspace was chosen
702 * arbitrarily and may need further tuning. It corresponds to
703 * 128 outstanding write IO requests (if IO size is 128 KiB),
704 * which fits with many RAID controllers' tagged queuing limits.
705 * The lower 1 MiB limit is the historical upper limit for
708 hirunningspace = lmax(lmin(roundup(hibufspace / 64, MAXBSIZE),
709 16 * 1024 * 1024), 1024 * 1024);
710 lorunningspace = roundup((hirunningspace * 2) / 3, MAXBSIZE);
713 * Limit the amount of malloc memory since it is wired permanently into
714 * the kernel space. Even though this is accounted for in the buffer
715 * allocation, we don't want the malloced region to grow uncontrolled.
716 * The malloc scheme improves memory utilization significantly on average
717 * (small) directories.
719 maxbufmallocspace = hibufspace / 20;
722 * Reduce the chance of a deadlock occuring by limiting the number
723 * of delayed-write dirty buffers we allow to stack up.
725 hidirtybuffers = nbuf / 4 + 20;
726 dirtybufthresh = hidirtybuffers * 9 / 10;
729 * To support extreme low-memory systems, make sure hidirtybuffers cannot
730 * eat up all available buffer space. This occurs when our minimum cannot
731 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
732 * BKVASIZE'd buffers.
734 while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
735 hidirtybuffers >>= 1;
737 lodirtybuffers = hidirtybuffers / 2;
740 * Try to keep the number of free buffers in the specified range,
741 * and give special processes (e.g. like buf_daemon) access to an
744 lofreebuffers = nbuf / 18 + 5;
745 hifreebuffers = 2 * lofreebuffers;
746 numfreebuffers = nbuf;
748 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
749 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
750 unmapped_buf = (caddr_t)kmem_alloc_nofault(kernel_map, MAXPHYS);
755 vfs_buf_check_mapped(struct buf *bp)
758 KASSERT((bp->b_flags & B_UNMAPPED) == 0,
759 ("mapped buf %p %x", bp, bp->b_flags));
760 KASSERT(bp->b_kvabase != unmapped_buf,
761 ("mapped buf: b_kvabase was not updated %p", bp));
762 KASSERT(bp->b_data != unmapped_buf,
763 ("mapped buf: b_data was not updated %p", bp));
767 vfs_buf_check_unmapped(struct buf *bp)
770 KASSERT((bp->b_flags & B_UNMAPPED) == B_UNMAPPED,
771 ("unmapped buf %p %x", bp, bp->b_flags));
772 KASSERT(bp->b_kvabase == unmapped_buf,
773 ("unmapped buf: corrupted b_kvabase %p", bp));
774 KASSERT(bp->b_data == unmapped_buf,
775 ("unmapped buf: corrupted b_data %p", bp));
778 #define BUF_CHECK_MAPPED(bp) vfs_buf_check_mapped(bp)
779 #define BUF_CHECK_UNMAPPED(bp) vfs_buf_check_unmapped(bp)
781 #define BUF_CHECK_MAPPED(bp) do {} while (0)
782 #define BUF_CHECK_UNMAPPED(bp) do {} while (0)
786 bpmap_qenter(struct buf *bp)
789 BUF_CHECK_MAPPED(bp);
792 * bp->b_data is relative to bp->b_offset, but
793 * bp->b_offset may be offset into the first page.
795 bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
796 pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
797 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
798 (vm_offset_t)(bp->b_offset & PAGE_MASK));
802 * bfreekva() - free the kva allocation for a buffer.
804 * Since this call frees up buffer space, we call bufspacewakeup().
807 bfreekva(struct buf *bp)
810 if (bp->b_kvasize == 0)
813 atomic_add_int(&buffreekvacnt, 1);
814 atomic_subtract_long(&bufspace, bp->b_kvasize);
815 if ((bp->b_flags & B_UNMAPPED) == 0) {
816 BUF_CHECK_MAPPED(bp);
817 vm_map_remove(buffer_map, (vm_offset_t)bp->b_kvabase,
818 (vm_offset_t)bp->b_kvabase + bp->b_kvasize);
820 BUF_CHECK_UNMAPPED(bp);
821 if ((bp->b_flags & B_KVAALLOC) != 0) {
822 vm_map_remove(buffer_map, (vm_offset_t)bp->b_kvaalloc,
823 (vm_offset_t)bp->b_kvaalloc + bp->b_kvasize);
825 atomic_subtract_long(&unmapped_bufspace, bp->b_kvasize);
826 bp->b_flags &= ~(B_UNMAPPED | B_KVAALLOC);
835 * Mark the buffer for removal from the appropriate free list in brelse.
839 bremfree(struct buf *bp)
843 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
844 KASSERT((bp->b_flags & B_REMFREE) == 0,
845 ("bremfree: buffer %p already marked for delayed removal.", bp));
846 KASSERT(bp->b_qindex != QUEUE_NONE,
847 ("bremfree: buffer %p not on a queue.", bp));
848 BUF_ASSERT_XLOCKED(bp);
850 bp->b_flags |= B_REMFREE;
851 /* Fixup numfreebuffers count. */
852 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
853 KASSERT((bp->b_flags & B_INFREECNT) != 0,
854 ("buf %p not counted in numfreebuffers", bp));
855 bp->b_flags &= ~B_INFREECNT;
856 old = atomic_fetchadd_int(&numfreebuffers, -1);
857 KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
864 * Force an immediate removal from a free list. Used only in nfs when
865 * it abuses the b_freelist pointer.
868 bremfreef(struct buf *bp)
878 * Removes a buffer from the free list, must be called with the
882 bremfreel(struct buf *bp)
886 CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
887 bp, bp->b_vp, bp->b_flags);
888 KASSERT(bp->b_qindex != QUEUE_NONE,
889 ("bremfreel: buffer %p not on a queue.", bp));
890 BUF_ASSERT_XLOCKED(bp);
891 mtx_assert(&bqlock, MA_OWNED);
893 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
895 KASSERT(bq_len[bp->b_qindex] >= 1, ("queue %d underflow",
897 bq_len[bp->b_qindex]--;
899 bp->b_qindex = QUEUE_NONE;
901 * If this was a delayed bremfree() we only need to remove the buffer
902 * from the queue and return the stats are already done.
904 if (bp->b_flags & B_REMFREE) {
905 bp->b_flags &= ~B_REMFREE;
909 * Fixup numfreebuffers count. If the buffer is invalid or not
910 * delayed-write, the buffer was free and we must decrement
913 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
914 KASSERT((bp->b_flags & B_INFREECNT) != 0,
915 ("buf %p not counted in numfreebuffers", bp));
916 bp->b_flags &= ~B_INFREECNT;
917 old = atomic_fetchadd_int(&numfreebuffers, -1);
918 KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
923 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must
924 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
925 * the buffer is valid and we do not have to do anything.
928 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
929 int cnt, struct ucred * cred)
934 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
935 if (inmem(vp, *rablkno))
937 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
939 if ((rabp->b_flags & B_CACHE) == 0) {
940 if (!TD_IS_IDLETHREAD(curthread))
941 curthread->td_ru.ru_inblock++;
942 rabp->b_flags |= B_ASYNC;
943 rabp->b_flags &= ~B_INVAL;
944 rabp->b_ioflags &= ~BIO_ERROR;
945 rabp->b_iocmd = BIO_READ;
946 if (rabp->b_rcred == NOCRED && cred != NOCRED)
947 rabp->b_rcred = crhold(cred);
948 vfs_busy_pages(rabp, 0);
950 rabp->b_iooffset = dbtob(rabp->b_blkno);
959 * Entry point for bread() and breadn() via #defines in sys/buf.h.
961 * Get a buffer with the specified data. Look in the cache first. We
962 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
963 * is set, the buffer is valid and we do not have to do anything, see
964 * getblk(). Also starts asynchronous I/O on read-ahead blocks.
967 breadn_flags(struct vnode *vp, daddr_t blkno, int size, daddr_t *rablkno,
968 int *rabsize, int cnt, struct ucred *cred, int flags, struct buf **bpp)
971 int rv = 0, readwait = 0;
973 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
975 * Can only return NULL if GB_LOCK_NOWAIT flag is specified.
977 *bpp = bp = getblk(vp, blkno, size, 0, 0, flags);
981 /* if not found in cache, do some I/O */
982 if ((bp->b_flags & B_CACHE) == 0) {
983 if (!TD_IS_IDLETHREAD(curthread))
984 curthread->td_ru.ru_inblock++;
985 bp->b_iocmd = BIO_READ;
986 bp->b_flags &= ~B_INVAL;
987 bp->b_ioflags &= ~BIO_ERROR;
988 if (bp->b_rcred == NOCRED && cred != NOCRED)
989 bp->b_rcred = crhold(cred);
990 vfs_busy_pages(bp, 0);
991 bp->b_iooffset = dbtob(bp->b_blkno);
996 breada(vp, rablkno, rabsize, cnt, cred);
1005 * Write, release buffer on completion. (Done by iodone
1006 * if async). Do not bother writing anything if the buffer
1009 * Note that we set B_CACHE here, indicating that buffer is
1010 * fully valid and thus cacheable. This is true even of NFS
1011 * now so we set it generally. This could be set either here
1012 * or in biodone() since the I/O is synchronous. We put it
1016 bufwrite(struct buf *bp)
1022 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1023 if (bp->b_flags & B_INVAL) {
1028 if (bp->b_flags & B_BARRIER)
1031 oldflags = bp->b_flags;
1033 BUF_ASSERT_HELD(bp);
1035 if (bp->b_pin_count > 0)
1038 KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
1039 ("FFS background buffer should not get here %p", bp));
1043 vp_md = vp->v_vflag & VV_MD;
1048 * Mark the buffer clean. Increment the bufobj write count
1049 * before bundirty() call, to prevent other thread from seeing
1050 * empty dirty list and zero counter for writes in progress,
1051 * falsely indicating that the bufobj is clean.
1053 bufobj_wref(bp->b_bufobj);
1056 bp->b_flags &= ~B_DONE;
1057 bp->b_ioflags &= ~BIO_ERROR;
1058 bp->b_flags |= B_CACHE;
1059 bp->b_iocmd = BIO_WRITE;
1061 vfs_busy_pages(bp, 1);
1064 * Normal bwrites pipeline writes
1066 bp->b_runningbufspace = bp->b_bufsize;
1067 atomic_add_long(&runningbufspace, bp->b_runningbufspace);
1069 if (!TD_IS_IDLETHREAD(curthread))
1070 curthread->td_ru.ru_oublock++;
1071 if (oldflags & B_ASYNC)
1073 bp->b_iooffset = dbtob(bp->b_blkno);
1076 if ((oldflags & B_ASYNC) == 0) {
1077 int rtval = bufwait(bp);
1082 * don't allow the async write to saturate the I/O
1083 * system. We will not deadlock here because
1084 * we are blocking waiting for I/O that is already in-progress
1085 * to complete. We do not block here if it is the update
1086 * or syncer daemon trying to clean up as that can lead
1089 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
1090 waitrunningbufspace();
1097 bufbdflush(struct bufobj *bo, struct buf *bp)
1101 if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
1102 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
1104 } else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
1107 * Try to find a buffer to flush.
1109 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
1110 if ((nbp->b_vflags & BV_BKGRDINPROG) ||
1112 LK_EXCLUSIVE | LK_NOWAIT, NULL))
1115 panic("bdwrite: found ourselves");
1117 /* Don't countdeps with the bo lock held. */
1118 if (buf_countdeps(nbp, 0)) {
1123 if (nbp->b_flags & B_CLUSTEROK) {
1124 vfs_bio_awrite(nbp);
1129 dirtybufferflushes++;
1138 * Delayed write. (Buffer is marked dirty). Do not bother writing
1139 * anything if the buffer is marked invalid.
1141 * Note that since the buffer must be completely valid, we can safely
1142 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
1143 * biodone() in order to prevent getblk from writing the buffer
1144 * out synchronously.
1147 bdwrite(struct buf *bp)
1149 struct thread *td = curthread;
1153 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1154 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1155 KASSERT((bp->b_flags & B_BARRIER) == 0,
1156 ("Barrier request in delayed write %p", bp));
1157 BUF_ASSERT_HELD(bp);
1159 if (bp->b_flags & B_INVAL) {
1165 * If we have too many dirty buffers, don't create any more.
1166 * If we are wildly over our limit, then force a complete
1167 * cleanup. Otherwise, just keep the situation from getting
1168 * out of control. Note that we have to avoid a recursive
1169 * disaster and not try to clean up after our own cleanup!
1173 if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
1174 td->td_pflags |= TDP_INBDFLUSH;
1176 td->td_pflags &= ~TDP_INBDFLUSH;
1182 * Set B_CACHE, indicating that the buffer is fully valid. This is
1183 * true even of NFS now.
1185 bp->b_flags |= B_CACHE;
1188 * This bmap keeps the system from needing to do the bmap later,
1189 * perhaps when the system is attempting to do a sync. Since it
1190 * is likely that the indirect block -- or whatever other datastructure
1191 * that the filesystem needs is still in memory now, it is a good
1192 * thing to do this. Note also, that if the pageout daemon is
1193 * requesting a sync -- there might not be enough memory to do
1194 * the bmap then... So, this is important to do.
1196 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
1197 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
1201 * Set the *dirty* buffer range based upon the VM system dirty
1204 * Mark the buffer pages as clean. We need to do this here to
1205 * satisfy the vnode_pager and the pageout daemon, so that it
1206 * thinks that the pages have been "cleaned". Note that since
1207 * the pages are in a delayed write buffer -- the VFS layer
1208 * "will" see that the pages get written out on the next sync,
1209 * or perhaps the cluster will be completed.
1211 vfs_clean_pages_dirty_buf(bp);
1215 * Wakeup the buffer flushing daemon if we have a lot of dirty
1216 * buffers (midpoint between our recovery point and our stall
1219 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1222 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1223 * due to the softdep code.
1230 * Turn buffer into delayed write request. We must clear BIO_READ and
1231 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
1232 * itself to properly update it in the dirty/clean lists. We mark it
1233 * B_DONE to ensure that any asynchronization of the buffer properly
1234 * clears B_DONE ( else a panic will occur later ).
1236 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1237 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
1238 * should only be called if the buffer is known-good.
1240 * Since the buffer is not on a queue, we do not update the numfreebuffers
1243 * The buffer must be on QUEUE_NONE.
1246 bdirty(struct buf *bp)
1249 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
1250 bp, bp->b_vp, bp->b_flags);
1251 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1252 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1253 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1254 BUF_ASSERT_HELD(bp);
1255 bp->b_flags &= ~(B_RELBUF);
1256 bp->b_iocmd = BIO_WRITE;
1258 if ((bp->b_flags & B_DELWRI) == 0) {
1259 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
1261 atomic_add_int(&numdirtybuffers, 1);
1262 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1269 * Clear B_DELWRI for buffer.
1271 * Since the buffer is not on a queue, we do not update the numfreebuffers
1274 * The buffer must be on QUEUE_NONE.
1278 bundirty(struct buf *bp)
1281 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1282 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1283 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1284 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1285 BUF_ASSERT_HELD(bp);
1287 if (bp->b_flags & B_DELWRI) {
1288 bp->b_flags &= ~B_DELWRI;
1290 atomic_subtract_int(&numdirtybuffers, 1);
1291 numdirtywakeup(lodirtybuffers);
1294 * Since it is now being written, we can clear its deferred write flag.
1296 bp->b_flags &= ~B_DEFERRED;
1302 * Asynchronous write. Start output on a buffer, but do not wait for
1303 * it to complete. The buffer is released when the output completes.
1305 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1306 * B_INVAL buffers. Not us.
1309 bawrite(struct buf *bp)
1312 bp->b_flags |= B_ASYNC;
1319 * Asynchronous barrier write. Start output on a buffer, but do not
1320 * wait for it to complete. Place a write barrier after this write so
1321 * that this buffer and all buffers written before it are committed to
1322 * the disk before any buffers written after this write are committed
1323 * to the disk. The buffer is released when the output completes.
1326 babarrierwrite(struct buf *bp)
1329 bp->b_flags |= B_ASYNC | B_BARRIER;
1336 * Synchronous barrier write. Start output on a buffer and wait for
1337 * it to complete. Place a write barrier after this write so that
1338 * this buffer and all buffers written before it are committed to
1339 * the disk before any buffers written after this write are committed
1340 * to the disk. The buffer is released when the output completes.
1343 bbarrierwrite(struct buf *bp)
1346 bp->b_flags |= B_BARRIER;
1347 return (bwrite(bp));
1353 * Called prior to the locking of any vnodes when we are expecting to
1354 * write. We do not want to starve the buffer cache with too many
1355 * dirty buffers so we block here. By blocking prior to the locking
1356 * of any vnodes we attempt to avoid the situation where a locked vnode
1357 * prevents the various system daemons from flushing related buffers.
1364 if (numdirtybuffers >= hidirtybuffers) {
1366 while (numdirtybuffers >= hidirtybuffers) {
1368 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
1369 msleep(&needsbuffer, &nblock,
1370 (PRIBIO + 4), "flswai", 0);
1372 mtx_unlock(&nblock);
1377 * Return true if we have too many dirty buffers.
1380 buf_dirty_count_severe(void)
1383 return(numdirtybuffers >= hidirtybuffers);
1386 static __noinline int
1387 buf_vm_page_count_severe(void)
1390 KFAIL_POINT_CODE(DEBUG_FP, buf_pressure, return 1);
1392 return vm_page_count_severe();
1398 * Release a busy buffer and, if requested, free its resources. The
1399 * buffer will be stashed in the appropriate bufqueue[] allowing it
1400 * to be accessed later as a cache entity or reused for other purposes.
1403 brelse(struct buf *bp)
1405 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
1406 bp, bp->b_vp, bp->b_flags);
1407 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1408 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1410 if (BUF_LOCKRECURSED(bp)) {
1412 * Do not process, in particular, do not handle the
1413 * B_INVAL/B_RELBUF and do not release to free list.
1419 if (bp->b_flags & B_MANAGED) {
1424 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
1425 bp->b_error == EIO && !(bp->b_flags & B_INVAL)) {
1427 * Failed write, redirty. Must clear BIO_ERROR to prevent
1428 * pages from being scrapped. If the error is anything
1429 * other than an I/O error (EIO), assume that retrying
1432 bp->b_ioflags &= ~BIO_ERROR;
1434 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1435 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
1437 * Either a failed I/O or we were asked to free or not
1440 bp->b_flags |= B_INVAL;
1441 if (!LIST_EMPTY(&bp->b_dep))
1443 if (bp->b_flags & B_DELWRI) {
1444 atomic_subtract_int(&numdirtybuffers, 1);
1445 numdirtywakeup(lodirtybuffers);
1447 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1448 if ((bp->b_flags & B_VMIO) == 0) {
1457 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1458 * is called with B_DELWRI set, the underlying pages may wind up
1459 * getting freed causing a previous write (bdwrite()) to get 'lost'
1460 * because pages associated with a B_DELWRI bp are marked clean.
1462 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1463 * if B_DELWRI is set.
1465 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1466 * on pages to return pages to the VM page queues.
1468 if (bp->b_flags & B_DELWRI)
1469 bp->b_flags &= ~B_RELBUF;
1470 else if (buf_vm_page_count_severe()) {
1472 * BKGRDINPROG can only be set with the buf and bufobj
1473 * locks both held. We tolerate a race to clear it here.
1475 if (!(bp->b_vflags & BV_BKGRDINPROG))
1476 bp->b_flags |= B_RELBUF;
1480 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1481 * constituted, not even NFS buffers now. Two flags effect this. If
1482 * B_INVAL, the struct buf is invalidated but the VM object is kept
1483 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1485 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1486 * invalidated. BIO_ERROR cannot be set for a failed write unless the
1487 * buffer is also B_INVAL because it hits the re-dirtying code above.
1489 * Normally we can do this whether a buffer is B_DELWRI or not. If
1490 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1491 * the commit state and we cannot afford to lose the buffer. If the
1492 * buffer has a background write in progress, we need to keep it
1493 * around to prevent it from being reconstituted and starting a second
1496 if ((bp->b_flags & B_VMIO)
1497 && !(bp->b_vp->v_mount != NULL &&
1498 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1499 !vn_isdisk(bp->b_vp, NULL) &&
1500 (bp->b_flags & B_DELWRI))
1509 obj = bp->b_bufobj->bo_object;
1512 * Get the base offset and length of the buffer. Note that
1513 * in the VMIO case if the buffer block size is not
1514 * page-aligned then b_data pointer may not be page-aligned.
1515 * But our b_pages[] array *IS* page aligned.
1517 * block sizes less then DEV_BSIZE (usually 512) are not
1518 * supported due to the page granularity bits (m->valid,
1519 * m->dirty, etc...).
1521 * See man buf(9) for more information
1523 resid = bp->b_bufsize;
1524 foff = bp->b_offset;
1525 for (i = 0; i < bp->b_npages; i++) {
1531 * If we hit a bogus page, fixup *all* the bogus pages
1534 if (m == bogus_page) {
1535 poff = OFF_TO_IDX(bp->b_offset);
1538 VM_OBJECT_RLOCK(obj);
1539 for (j = i; j < bp->b_npages; j++) {
1541 mtmp = bp->b_pages[j];
1542 if (mtmp == bogus_page) {
1543 mtmp = vm_page_lookup(obj, poff + j);
1545 panic("brelse: page missing\n");
1547 bp->b_pages[j] = mtmp;
1550 VM_OBJECT_RUNLOCK(obj);
1552 if ((bp->b_flags & (B_INVAL | B_UNMAPPED)) == 0) {
1553 BUF_CHECK_MAPPED(bp);
1555 trunc_page((vm_offset_t)bp->b_data),
1556 bp->b_pages, bp->b_npages);
1560 if ((bp->b_flags & B_NOCACHE) ||
1561 (bp->b_ioflags & BIO_ERROR &&
1562 bp->b_iocmd == BIO_READ)) {
1563 int poffset = foff & PAGE_MASK;
1564 int presid = resid > (PAGE_SIZE - poffset) ?
1565 (PAGE_SIZE - poffset) : resid;
1567 KASSERT(presid >= 0, ("brelse: extra page"));
1568 VM_OBJECT_WLOCK(obj);
1569 vm_page_set_invalid(m, poffset, presid);
1570 VM_OBJECT_WUNLOCK(obj);
1572 printf("avoided corruption bug in bogus_page/brelse code\n");
1574 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1575 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1577 if (bp->b_flags & (B_INVAL | B_RELBUF))
1578 vfs_vmio_release(bp);
1580 } else if (bp->b_flags & B_VMIO) {
1582 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1583 vfs_vmio_release(bp);
1586 } else if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0) {
1587 if (bp->b_bufsize != 0)
1589 if (bp->b_vp != NULL)
1595 /* Handle delayed bremfree() processing. */
1596 if (bp->b_flags & B_REMFREE)
1599 if (bp->b_qindex != QUEUE_NONE)
1600 panic("brelse: free buffer onto another queue???");
1603 * If the buffer has junk contents signal it and eventually
1604 * clean up B_DELWRI and diassociate the vnode so that gbincore()
1607 if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
1608 (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
1609 bp->b_flags |= B_INVAL;
1610 if (bp->b_flags & B_INVAL) {
1611 if (bp->b_flags & B_DELWRI)
1617 /* buffers with no memory */
1618 if (bp->b_bufsize == 0) {
1619 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1620 if (bp->b_vflags & BV_BKGRDINPROG)
1621 panic("losing buffer 1");
1622 if (bp->b_kvasize) {
1623 bp->b_qindex = QUEUE_EMPTYKVA;
1625 bp->b_qindex = QUEUE_EMPTY;
1627 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1628 /* buffers with junk contents */
1629 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1630 (bp->b_ioflags & BIO_ERROR)) {
1631 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1632 if (bp->b_vflags & BV_BKGRDINPROG)
1633 panic("losing buffer 2");
1634 bp->b_qindex = QUEUE_CLEAN;
1635 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1636 /* remaining buffers */
1638 if (bp->b_flags & B_DELWRI)
1639 bp->b_qindex = QUEUE_DIRTY;
1641 bp->b_qindex = QUEUE_CLEAN;
1642 if (bp->b_flags & B_AGE) {
1643 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp,
1646 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp,
1651 bq_len[bp->b_qindex]++;
1653 mtx_unlock(&bqlock);
1656 * Fixup numfreebuffers count. The bp is on an appropriate queue
1657 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1658 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1659 * if B_INVAL is set ).
1662 if (!(bp->b_flags & B_DELWRI))
1666 * Something we can maybe free or reuse
1668 if (bp->b_bufsize || bp->b_kvasize)
1671 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1672 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1673 panic("brelse: not dirty");
1679 * Release a buffer back to the appropriate queue but do not try to free
1680 * it. The buffer is expected to be used again soon.
1682 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1683 * biodone() to requeue an async I/O on completion. It is also used when
1684 * known good buffers need to be requeued but we think we may need the data
1687 * XXX we should be able to leave the B_RELBUF hint set on completion.
1690 bqrelse(struct buf *bp)
1694 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1695 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1696 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1698 if (BUF_LOCKRECURSED(bp)) {
1699 /* do not release to free list */
1705 if (bp->b_flags & B_MANAGED) {
1706 if (bp->b_flags & B_REMFREE) {
1709 mtx_unlock(&bqlock);
1711 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1717 /* Handle delayed bremfree() processing. */
1718 if (bp->b_flags & B_REMFREE)
1721 if (bp->b_qindex != QUEUE_NONE)
1722 panic("bqrelse: free buffer onto another queue???");
1723 /* buffers with stale but valid contents */
1724 if (bp->b_flags & B_DELWRI) {
1725 bp->b_qindex = QUEUE_DIRTY;
1726 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1728 bq_len[bp->b_qindex]++;
1732 * BKGRDINPROG can only be set with the buf and bufobj
1733 * locks both held. We tolerate a race to clear it here.
1735 if (!buf_vm_page_count_severe() ||
1736 (bp->b_vflags & BV_BKGRDINPROG)) {
1737 bp->b_qindex = QUEUE_CLEAN;
1738 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp,
1741 bq_len[QUEUE_CLEAN]++;
1745 * We are too low on memory, we have to try to free
1746 * the buffer (most importantly: the wired pages
1747 * making up its backing store) *now*.
1749 mtx_unlock(&bqlock);
1754 mtx_unlock(&bqlock);
1756 if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))
1760 * Something we can maybe free or reuse.
1762 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1765 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1766 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1767 panic("bqrelse: not dirty");
1772 /* Give pages used by the bp back to the VM system (where possible) */
1774 vfs_vmio_release(struct buf *bp)
1779 if ((bp->b_flags & B_UNMAPPED) == 0) {
1780 BUF_CHECK_MAPPED(bp);
1781 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
1783 BUF_CHECK_UNMAPPED(bp);
1784 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
1785 for (i = 0; i < bp->b_npages; i++) {
1787 bp->b_pages[i] = NULL;
1789 * In order to keep page LRU ordering consistent, put
1790 * everything on the inactive queue.
1793 vm_page_unwire(m, 0);
1795 * We don't mess with busy pages, it is
1796 * the responsibility of the process that
1797 * busied the pages to deal with them.
1799 if ((m->oflags & VPO_BUSY) == 0 && m->busy == 0 &&
1800 m->wire_count == 0) {
1802 * Might as well free the page if we can and it has
1803 * no valid data. We also free the page if the
1804 * buffer was used for direct I/O
1806 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid) {
1808 } else if (bp->b_flags & B_DIRECT) {
1809 vm_page_try_to_free(m);
1810 } else if (buf_vm_page_count_severe()) {
1811 vm_page_try_to_cache(m);
1816 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
1818 if (bp->b_bufsize) {
1823 bp->b_flags &= ~B_VMIO;
1829 * Check to see if a block at a particular lbn is available for a clustered
1833 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1840 /* If the buf isn't in core skip it */
1841 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1844 /* If the buf is busy we don't want to wait for it */
1845 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1848 /* Only cluster with valid clusterable delayed write buffers */
1849 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1850 (B_DELWRI | B_CLUSTEROK))
1853 if (bpa->b_bufsize != size)
1857 * Check to see if it is in the expected place on disk and that the
1858 * block has been mapped.
1860 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1870 * Implement clustered async writes for clearing out B_DELWRI buffers.
1871 * This is much better then the old way of writing only one buffer at
1872 * a time. Note that we may not be presented with the buffers in the
1873 * correct order, so we search for the cluster in both directions.
1876 vfs_bio_awrite(struct buf *bp)
1881 daddr_t lblkno = bp->b_lblkno;
1882 struct vnode *vp = bp->b_vp;
1890 gbflags = (bp->b_flags & B_UNMAPPED) != 0 ? GB_UNMAPPED : 0;
1892 * right now we support clustered writing only to regular files. If
1893 * we find a clusterable block we could be in the middle of a cluster
1894 * rather then at the beginning.
1896 if ((vp->v_type == VREG) &&
1897 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1898 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1900 size = vp->v_mount->mnt_stat.f_iosize;
1901 maxcl = MAXPHYS / size;
1904 for (i = 1; i < maxcl; i++)
1905 if (vfs_bio_clcheck(vp, size, lblkno + i,
1906 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1909 for (j = 1; i + j <= maxcl && j <= lblkno; j++)
1910 if (vfs_bio_clcheck(vp, size, lblkno - j,
1911 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
1917 * this is a possible cluster write
1921 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl,
1927 bp->b_flags |= B_ASYNC;
1929 * default (old) behavior, writing out only one block
1931 * XXX returns b_bufsize instead of b_bcount for nwritten?
1933 nwritten = bp->b_bufsize;
1940 setbufkva(struct buf *bp, vm_offset_t addr, int maxsize, int gbflags)
1943 KASSERT((bp->b_flags & (B_UNMAPPED | B_KVAALLOC)) == 0 &&
1944 bp->b_kvasize == 0, ("call bfreekva(%p)", bp));
1945 if ((gbflags & GB_UNMAPPED) == 0) {
1946 bp->b_kvabase = (caddr_t)addr;
1947 } else if ((gbflags & GB_KVAALLOC) != 0) {
1948 KASSERT((gbflags & GB_UNMAPPED) != 0,
1949 ("GB_KVAALLOC without GB_UNMAPPED"));
1950 bp->b_kvaalloc = (caddr_t)addr;
1951 bp->b_flags |= B_UNMAPPED | B_KVAALLOC;
1952 atomic_add_long(&unmapped_bufspace, bp->b_kvasize);
1954 bp->b_kvasize = maxsize;
1958 * Allocate the buffer KVA and set b_kvasize. Also set b_kvabase if
1962 allocbufkva(struct buf *bp, int maxsize, int gbflags)
1970 vm_map_lock(buffer_map);
1971 if (vm_map_findspace(buffer_map, vm_map_min(buffer_map), maxsize,
1973 vm_map_unlock(buffer_map);
1975 * Buffer map is too fragmented. Request the caller
1976 * to defragment the map.
1978 atomic_add_int(&bufdefragcnt, 1);
1981 rv = vm_map_insert(buffer_map, NULL, 0, addr, addr + maxsize,
1982 VM_PROT_RW, VM_PROT_RW, MAP_NOFAULT);
1983 KASSERT(rv == KERN_SUCCESS, ("vm_map_insert(buffer_map) rv %d", rv));
1984 vm_map_unlock(buffer_map);
1985 setbufkva(bp, addr, maxsize, gbflags);
1986 atomic_add_long(&bufspace, bp->b_kvasize);
1991 * Ask the bufdaemon for help, or act as bufdaemon itself, when a
1992 * locked vnode is supplied.
1995 getnewbuf_bufd_help(struct vnode *vp, int gbflags, int slpflag, int slptimeo,
2000 int fl, flags, norunbuf;
2002 mtx_assert(&bqlock, MA_OWNED);
2005 flags = VFS_BIO_NEED_BUFSPACE;
2007 } else if (bufspace >= hibufspace) {
2009 flags = VFS_BIO_NEED_BUFSPACE;
2012 flags = VFS_BIO_NEED_ANY;
2015 needsbuffer |= flags;
2016 mtx_unlock(&nblock);
2017 mtx_unlock(&bqlock);
2019 bd_speedup(); /* heeeelp */
2020 if ((gbflags & GB_NOWAIT_BD) != 0)
2025 while (needsbuffer & flags) {
2026 if (vp != NULL && (td->td_pflags & TDP_BUFNEED) == 0) {
2027 mtx_unlock(&nblock);
2029 * getblk() is called with a vnode locked, and
2030 * some majority of the dirty buffers may as
2031 * well belong to the vnode. Flushing the
2032 * buffers there would make a progress that
2033 * cannot be achieved by the buf_daemon, that
2034 * cannot lock the vnode.
2036 norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
2037 (td->td_pflags & TDP_NORUNNINGBUF);
2038 /* play bufdaemon */
2039 td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
2040 fl = buf_do_flush(vp);
2041 td->td_pflags &= norunbuf;
2045 if ((needsbuffer & flags) == 0)
2048 if (msleep(&needsbuffer, &nblock, (PRIBIO + 4) | slpflag,
2052 mtx_unlock(&nblock);
2056 getnewbuf_reuse_bp(struct buf *bp, int qindex)
2059 CTR6(KTR_BUF, "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
2060 "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
2061 bp->b_kvasize, bp->b_bufsize, qindex);
2062 mtx_assert(&bqlock, MA_NOTOWNED);
2065 * Note: we no longer distinguish between VMIO and non-VMIO
2068 KASSERT((bp->b_flags & B_DELWRI) == 0,
2069 ("delwri buffer %p found in queue %d", bp, qindex));
2071 if (qindex == QUEUE_CLEAN) {
2072 if (bp->b_flags & B_VMIO) {
2073 bp->b_flags &= ~B_ASYNC;
2074 vfs_vmio_release(bp);
2076 if (bp->b_vp != NULL)
2081 * Get the rest of the buffer freed up. b_kva* is still valid
2082 * after this operation.
2085 if (bp->b_rcred != NOCRED) {
2086 crfree(bp->b_rcred);
2087 bp->b_rcred = NOCRED;
2089 if (bp->b_wcred != NOCRED) {
2090 crfree(bp->b_wcred);
2091 bp->b_wcred = NOCRED;
2093 if (!LIST_EMPTY(&bp->b_dep))
2095 if (bp->b_vflags & BV_BKGRDINPROG)
2096 panic("losing buffer 3");
2097 KASSERT(bp->b_vp == NULL, ("bp: %p still has vnode %p. qindex: %d",
2098 bp, bp->b_vp, qindex));
2099 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
2100 ("bp: %p still on a buffer list. xflags %X", bp, bp->b_xflags));
2105 bp->b_flags &= B_UNMAPPED | B_KVAALLOC;
2108 KASSERT((bp->b_flags & B_INFREECNT) == 0,
2109 ("buf %p still counted as free?", bp));
2112 bp->b_blkno = bp->b_lblkno = 0;
2113 bp->b_offset = NOOFFSET;
2119 bp->b_dirtyoff = bp->b_dirtyend = 0;
2120 bp->b_bufobj = NULL;
2121 bp->b_pin_count = 0;
2122 bp->b_fsprivate1 = NULL;
2123 bp->b_fsprivate2 = NULL;
2124 bp->b_fsprivate3 = NULL;
2126 LIST_INIT(&bp->b_dep);
2129 static int flushingbufs;
2132 getnewbuf_scan(int maxsize, int defrag, int unmapped, int metadata)
2134 struct buf *bp, *nbp;
2135 int nqindex, qindex, pass;
2137 KASSERT(!unmapped || !defrag, ("both unmapped and defrag"));
2141 atomic_add_int(&getnewbufrestarts, 1);
2144 * Setup for scan. If we do not have enough free buffers,
2145 * we setup a degenerate case that immediately fails. Note
2146 * that if we are specially marked process, we are allowed to
2147 * dip into our reserves.
2149 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
2150 * for the allocation of the mapped buffer. For unmapped, the
2151 * easiest is to start with EMPTY outright.
2153 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
2154 * However, there are a number of cases (defragging, reusing, ...)
2155 * where we cannot backup.
2159 if (!defrag && unmapped) {
2160 nqindex = QUEUE_EMPTY;
2161 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
2164 nqindex = QUEUE_EMPTYKVA;
2165 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
2169 * If no EMPTYKVA buffers and we are either defragging or
2170 * reusing, locate a CLEAN buffer to free or reuse. If
2171 * bufspace useage is low skip this step so we can allocate a
2174 if (nbp == NULL && (defrag || bufspace >= lobufspace)) {
2175 nqindex = QUEUE_CLEAN;
2176 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2180 * If we could not find or were not allowed to reuse a CLEAN
2181 * buffer, check to see if it is ok to use an EMPTY buffer.
2182 * We can only use an EMPTY buffer if allocating its KVA would
2183 * not otherwise run us out of buffer space. No KVA is needed
2184 * for the unmapped allocation.
2186 if (nbp == NULL && defrag == 0 && (bufspace + maxsize < hibufspace ||
2188 nqindex = QUEUE_EMPTY;
2189 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
2193 * All available buffers might be clean, retry ignoring the
2194 * lobufspace as the last resort.
2196 if (nbp == NULL && !TAILQ_EMPTY(&bufqueues[QUEUE_CLEAN])) {
2197 nqindex = QUEUE_CLEAN;
2198 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2202 * Run scan, possibly freeing data and/or kva mappings on the fly
2205 while ((bp = nbp) != NULL) {
2209 * Calculate next bp (we can only use it if we do not
2210 * block or do other fancy things).
2212 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
2215 nqindex = QUEUE_EMPTYKVA;
2216 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
2220 case QUEUE_EMPTYKVA:
2221 nqindex = QUEUE_CLEAN;
2222 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2227 if (metadata && pass == 1) {
2229 nqindex = QUEUE_EMPTY;
2231 &bufqueues[QUEUE_EMPTY]);
2240 * If we are defragging then we need a buffer with
2241 * b_kvasize != 0. XXX this situation should no longer
2242 * occur, if defrag is non-zero the buffer's b_kvasize
2243 * should also be non-zero at this point. XXX
2245 if (defrag && bp->b_kvasize == 0) {
2246 printf("Warning: defrag empty buffer %p\n", bp);
2251 * Start freeing the bp. This is somewhat involved. nbp
2252 * remains valid only for QUEUE_EMPTY[KVA] bp's.
2254 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2257 * BKGRDINPROG can only be set with the buf and bufobj
2258 * locks both held. We tolerate a race to clear it here.
2260 if (bp->b_vflags & BV_BKGRDINPROG) {
2265 KASSERT(bp->b_qindex == qindex,
2266 ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
2269 mtx_unlock(&bqlock);
2271 * NOTE: nbp is now entirely invalid. We can only restart
2272 * the scan from this point on.
2275 getnewbuf_reuse_bp(bp, qindex);
2276 mtx_assert(&bqlock, MA_NOTOWNED);
2279 * If we are defragging then free the buffer.
2282 bp->b_flags |= B_INVAL;
2290 * Notify any waiters for the buffer lock about
2291 * identity change by freeing the buffer.
2293 if (qindex == QUEUE_CLEAN && BUF_LOCKWAITERS(bp)) {
2294 bp->b_flags |= B_INVAL;
2304 * If we are overcomitted then recover the buffer and its
2305 * KVM space. This occurs in rare situations when multiple
2306 * processes are blocked in getnewbuf() or allocbuf().
2308 if (bufspace >= hibufspace)
2310 if (flushingbufs && bp->b_kvasize != 0) {
2311 bp->b_flags |= B_INVAL;
2316 if (bufspace < lobufspace)
2326 * Find and initialize a new buffer header, freeing up existing buffers
2327 * in the bufqueues as necessary. The new buffer is returned locked.
2329 * Important: B_INVAL is not set. If the caller wishes to throw the
2330 * buffer away, the caller must set B_INVAL prior to calling brelse().
2333 * We have insufficient buffer headers
2334 * We have insufficient buffer space
2335 * buffer_map is too fragmented ( space reservation fails )
2336 * If we have to flush dirty buffers ( but we try to avoid this )
2338 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
2339 * Instead we ask the buf daemon to do it for us. We attempt to
2340 * avoid piecemeal wakeups of the pageout daemon.
2343 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int size, int maxsize,
2347 int defrag, metadata;
2349 KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
2350 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
2351 if (!unmapped_buf_allowed)
2352 gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC);
2355 if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 ||
2361 * We can't afford to block since we might be holding a vnode lock,
2362 * which may prevent system daemons from running. We deal with
2363 * low-memory situations by proactively returning memory and running
2364 * async I/O rather then sync I/O.
2366 atomic_add_int(&getnewbufcalls, 1);
2367 atomic_subtract_int(&getnewbufrestarts, 1);
2369 bp = getnewbuf_scan(maxsize, defrag, (gbflags & (GB_UNMAPPED |
2370 GB_KVAALLOC)) == GB_UNMAPPED, metadata);
2375 * If we exhausted our list, sleep as appropriate. We may have to
2376 * wakeup various daemons and write out some dirty buffers.
2378 * Generally we are sleeping due to insufficient buffer space.
2381 mtx_assert(&bqlock, MA_OWNED);
2382 getnewbuf_bufd_help(vp, gbflags, slpflag, slptimeo, defrag);
2383 mtx_assert(&bqlock, MA_NOTOWNED);
2384 } else if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == GB_UNMAPPED) {
2385 mtx_assert(&bqlock, MA_NOTOWNED);
2388 bp->b_flags |= B_UNMAPPED;
2389 bp->b_kvabase = bp->b_data = unmapped_buf;
2390 bp->b_kvasize = maxsize;
2391 atomic_add_long(&bufspace, bp->b_kvasize);
2392 atomic_add_long(&unmapped_bufspace, bp->b_kvasize);
2393 atomic_add_int(&bufreusecnt, 1);
2395 mtx_assert(&bqlock, MA_NOTOWNED);
2398 * We finally have a valid bp. We aren't quite out of the
2399 * woods, we still have to reserve kva space. In order
2400 * to keep fragmentation sane we only allocate kva in
2403 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2405 if (maxsize != bp->b_kvasize || (bp->b_flags & (B_UNMAPPED |
2406 B_KVAALLOC)) == B_UNMAPPED) {
2407 if (allocbufkva(bp, maxsize, gbflags)) {
2409 bp->b_flags |= B_INVAL;
2413 atomic_add_int(&bufreusecnt, 1);
2414 } else if ((bp->b_flags & B_KVAALLOC) != 0 &&
2415 (gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == 0) {
2417 * If the reused buffer has KVA allocated,
2418 * reassign b_kvaalloc to b_kvabase.
2420 bp->b_kvabase = bp->b_kvaalloc;
2421 bp->b_flags &= ~B_KVAALLOC;
2422 atomic_subtract_long(&unmapped_bufspace,
2424 atomic_add_int(&bufreusecnt, 1);
2425 } else if ((bp->b_flags & (B_UNMAPPED | B_KVAALLOC)) == 0 &&
2426 (gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == (GB_UNMAPPED |
2429 * The case of reused buffer already have KVA
2430 * mapped, but the request is for unmapped
2431 * buffer with KVA allocated.
2433 bp->b_kvaalloc = bp->b_kvabase;
2434 bp->b_data = bp->b_kvabase = unmapped_buf;
2435 bp->b_flags |= B_UNMAPPED | B_KVAALLOC;
2436 atomic_add_long(&unmapped_bufspace,
2438 atomic_add_int(&bufreusecnt, 1);
2440 if ((gbflags & GB_UNMAPPED) == 0) {
2441 bp->b_saveaddr = bp->b_kvabase;
2442 bp->b_data = bp->b_saveaddr;
2443 bp->b_flags &= ~B_UNMAPPED;
2444 BUF_CHECK_MAPPED(bp);
2453 * buffer flushing daemon. Buffers are normally flushed by the
2454 * update daemon but if it cannot keep up this process starts to
2455 * take the load in an attempt to prevent getnewbuf() from blocking.
2458 static struct kproc_desc buf_kp = {
2463 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
2466 buf_do_flush(struct vnode *vp)
2470 flushed = flushbufqueues(vp, QUEUE_DIRTY, 0);
2473 * Could not find any buffers without rollback
2474 * dependencies, so just write the first one
2475 * in the hopes of eventually making progress.
2477 flushbufqueues(vp, QUEUE_DIRTY, 1);
2488 * This process needs to be suspended prior to shutdown sync.
2490 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2494 * This process is allowed to take the buffer cache to the limit
2496 curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
2500 mtx_unlock(&bdlock);
2502 kproc_suspend_check(bufdaemonproc);
2503 lodirtysave = lodirtybuffers;
2504 if (bd_speedupreq) {
2505 lodirtybuffers = numdirtybuffers / 2;
2509 * Do the flush. Limit the amount of in-transit I/O we
2510 * allow to build up, otherwise we would completely saturate
2511 * the I/O system. Wakeup any waiting processes before we
2512 * normally would so they can run in parallel with our drain.
2514 while (numdirtybuffers > lodirtybuffers) {
2515 if (buf_do_flush(NULL) == 0)
2517 kern_yield(PRI_USER);
2519 lodirtybuffers = lodirtysave;
2522 * Only clear bd_request if we have reached our low water
2523 * mark. The buf_daemon normally waits 1 second and
2524 * then incrementally flushes any dirty buffers that have
2525 * built up, within reason.
2527 * If we were unable to hit our low water mark and couldn't
2528 * find any flushable buffers, we sleep half a second.
2529 * Otherwise we loop immediately.
2532 if (numdirtybuffers <= lodirtybuffers) {
2534 * We reached our low water mark, reset the
2535 * request and sleep until we are needed again.
2536 * The sleep is just so the suspend code works.
2539 msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2542 * We couldn't find any flushable dirty buffers but
2543 * still have too many dirty buffers, we
2544 * have to sleep and try again. (rare)
2546 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2554 * Try to flush a buffer in the dirty queue. We must be careful to
2555 * free up B_INVAL buffers instead of write them, which NFS is
2556 * particularly sensitive to.
2558 static int flushwithdeps = 0;
2559 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2560 0, "Number of buffers flushed with dependecies that require rollbacks");
2563 flushbufqueues(struct vnode *lvp, int queue, int flushdeps)
2565 struct buf *sentinel;
2574 target = numdirtybuffers - lodirtybuffers;
2575 if (flushdeps && target > 2)
2578 target = flushbufqtarget;
2581 sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
2582 sentinel->b_qindex = QUEUE_SENTINEL;
2584 TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
2585 while (flushed != target) {
2586 bp = TAILQ_NEXT(sentinel, b_freelist);
2588 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2589 TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
2594 * Skip sentinels inserted by other invocations of the
2595 * flushbufqueues(), taking care to not reorder them.
2597 if (bp->b_qindex == QUEUE_SENTINEL)
2600 * Only flush the buffers that belong to the
2601 * vnode locked by the curthread.
2603 if (lvp != NULL && bp->b_vp != lvp)
2605 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2607 if (bp->b_pin_count > 0) {
2612 * BKGRDINPROG can only be set with the buf and bufobj
2613 * locks both held. We tolerate a race to clear it here.
2615 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2616 (bp->b_flags & B_DELWRI) == 0) {
2620 if (bp->b_flags & B_INVAL) {
2622 mtx_unlock(&bqlock);
2625 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2630 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
2631 if (flushdeps == 0) {
2639 * We must hold the lock on a vnode before writing
2640 * one of its buffers. Otherwise we may confuse, or
2641 * in the case of a snapshot vnode, deadlock the
2644 * The lock order here is the reverse of the normal
2645 * of vnode followed by buf lock. This is ok because
2646 * the NOWAIT will prevent deadlock.
2649 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2653 if (vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT | LK_CANRECURSE) == 0) {
2654 mtx_unlock(&bqlock);
2655 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2656 bp, bp->b_vp, bp->b_flags);
2657 if (curproc == bufdaemonproc)
2664 vn_finished_write(mp);
2666 flushwithdeps += hasdeps;
2670 * Sleeping on runningbufspace while holding
2671 * vnode lock leads to deadlock.
2673 if (curproc == bufdaemonproc)
2674 waitrunningbufspace();
2675 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2679 vn_finished_write(mp);
2682 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2683 mtx_unlock(&bqlock);
2684 free(sentinel, M_TEMP);
2689 * Check to see if a block is currently memory resident.
2692 incore(struct bufobj *bo, daddr_t blkno)
2697 bp = gbincore(bo, blkno);
2703 * Returns true if no I/O is needed to access the
2704 * associated VM object. This is like incore except
2705 * it also hunts around in the VM system for the data.
2709 inmem(struct vnode * vp, daddr_t blkno)
2712 vm_offset_t toff, tinc, size;
2716 ASSERT_VOP_LOCKED(vp, "inmem");
2718 if (incore(&vp->v_bufobj, blkno))
2720 if (vp->v_mount == NULL)
2727 if (size > vp->v_mount->mnt_stat.f_iosize)
2728 size = vp->v_mount->mnt_stat.f_iosize;
2729 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2731 VM_OBJECT_RLOCK(obj);
2732 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2733 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2737 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2738 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2739 if (vm_page_is_valid(m,
2740 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2743 VM_OBJECT_RUNLOCK(obj);
2747 VM_OBJECT_RUNLOCK(obj);
2752 * Set the dirty range for a buffer based on the status of the dirty
2753 * bits in the pages comprising the buffer. The range is limited
2754 * to the size of the buffer.
2756 * Tell the VM system that the pages associated with this buffer
2757 * are clean. This is used for delayed writes where the data is
2758 * going to go to disk eventually without additional VM intevention.
2760 * Note that while we only really need to clean through to b_bcount, we
2761 * just go ahead and clean through to b_bufsize.
2764 vfs_clean_pages_dirty_buf(struct buf *bp)
2766 vm_ooffset_t foff, noff, eoff;
2770 if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
2773 foff = bp->b_offset;
2774 KASSERT(bp->b_offset != NOOFFSET,
2775 ("vfs_clean_pages_dirty_buf: no buffer offset"));
2777 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
2778 vfs_drain_busy_pages(bp);
2779 vfs_setdirty_locked_object(bp);
2780 for (i = 0; i < bp->b_npages; i++) {
2781 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2783 if (eoff > bp->b_offset + bp->b_bufsize)
2784 eoff = bp->b_offset + bp->b_bufsize;
2786 vfs_page_set_validclean(bp, foff, m);
2787 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
2790 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
2794 vfs_setdirty_locked_object(struct buf *bp)
2799 object = bp->b_bufobj->bo_object;
2800 VM_OBJECT_ASSERT_WLOCKED(object);
2803 * We qualify the scan for modified pages on whether the
2804 * object has been flushed yet.
2806 if ((object->flags & OBJ_MIGHTBEDIRTY) != 0) {
2807 vm_offset_t boffset;
2808 vm_offset_t eoffset;
2811 * test the pages to see if they have been modified directly
2812 * by users through the VM system.
2814 for (i = 0; i < bp->b_npages; i++)
2815 vm_page_test_dirty(bp->b_pages[i]);
2818 * Calculate the encompassing dirty range, boffset and eoffset,
2819 * (eoffset - boffset) bytes.
2822 for (i = 0; i < bp->b_npages; i++) {
2823 if (bp->b_pages[i]->dirty)
2826 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2828 for (i = bp->b_npages - 1; i >= 0; --i) {
2829 if (bp->b_pages[i]->dirty) {
2833 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2836 * Fit it to the buffer.
2839 if (eoffset > bp->b_bcount)
2840 eoffset = bp->b_bcount;
2843 * If we have a good dirty range, merge with the existing
2847 if (boffset < eoffset) {
2848 if (bp->b_dirtyoff > boffset)
2849 bp->b_dirtyoff = boffset;
2850 if (bp->b_dirtyend < eoffset)
2851 bp->b_dirtyend = eoffset;
2857 * Allocate the KVA mapping for an existing buffer. It handles the
2858 * cases of both B_UNMAPPED buffer, and buffer with the preallocated
2859 * KVA which is not mapped (B_KVAALLOC).
2862 bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags)
2864 struct buf *scratch_bp;
2865 int bsize, maxsize, need_mapping, need_kva;
2868 need_mapping = (bp->b_flags & B_UNMAPPED) != 0 &&
2869 (gbflags & GB_UNMAPPED) == 0;
2870 need_kva = (bp->b_flags & (B_KVAALLOC | B_UNMAPPED)) == B_UNMAPPED &&
2871 (gbflags & GB_KVAALLOC) != 0;
2872 if (!need_mapping && !need_kva)
2875 BUF_CHECK_UNMAPPED(bp);
2877 if (need_mapping && (bp->b_flags & B_KVAALLOC) != 0) {
2879 * Buffer is not mapped, but the KVA was already
2880 * reserved at the time of the instantiation. Use the
2883 bp->b_flags &= ~B_KVAALLOC;
2884 KASSERT(bp->b_kvaalloc != 0, ("kvaalloc == 0"));
2885 bp->b_kvabase = bp->b_kvaalloc;
2886 atomic_subtract_long(&unmapped_bufspace, bp->b_kvasize);
2891 * Calculate the amount of the address space we would reserve
2892 * if the buffer was mapped.
2894 bsize = vn_isdisk(bp->b_vp, NULL) ? DEV_BSIZE : bp->b_bufobj->bo_bsize;
2895 offset = blkno * bsize;
2896 maxsize = size + (offset & PAGE_MASK);
2897 maxsize = imax(maxsize, bsize);
2900 if (allocbufkva(bp, maxsize, gbflags)) {
2902 * Request defragmentation. getnewbuf() returns us the
2903 * allocated space by the scratch buffer KVA.
2905 scratch_bp = getnewbuf(bp->b_vp, 0, 0, size, maxsize, gbflags |
2906 (GB_UNMAPPED | GB_KVAALLOC));
2907 if (scratch_bp == NULL) {
2908 if ((gbflags & GB_NOWAIT_BD) != 0) {
2910 * XXXKIB: defragmentation cannot
2911 * succeed, not sure what else to do.
2913 panic("GB_NOWAIT_BD and B_UNMAPPED %p", bp);
2915 atomic_add_int(&mappingrestarts, 1);
2918 KASSERT((scratch_bp->b_flags & B_KVAALLOC) != 0,
2919 ("scratch bp !B_KVAALLOC %p", scratch_bp));
2920 setbufkva(bp, (vm_offset_t)scratch_bp->b_kvaalloc,
2921 scratch_bp->b_kvasize, gbflags);
2923 /* Get rid of the scratch buffer. */
2924 scratch_bp->b_kvasize = 0;
2925 scratch_bp->b_flags |= B_INVAL;
2926 scratch_bp->b_flags &= ~(B_UNMAPPED | B_KVAALLOC);
2933 bp->b_saveaddr = bp->b_kvabase;
2934 bp->b_data = bp->b_saveaddr; /* b_offset is handled by bpmap_qenter */
2935 bp->b_flags &= ~B_UNMAPPED;
2936 BUF_CHECK_MAPPED(bp);
2943 * Get a block given a specified block and offset into a file/device.
2944 * The buffers B_DONE bit will be cleared on return, making it almost
2945 * ready for an I/O initiation. B_INVAL may or may not be set on
2946 * return. The caller should clear B_INVAL prior to initiating a
2949 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2950 * an existing buffer.
2952 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2953 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2954 * and then cleared based on the backing VM. If the previous buffer is
2955 * non-0-sized but invalid, B_CACHE will be cleared.
2957 * If getblk() must create a new buffer, the new buffer is returned with
2958 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2959 * case it is returned with B_INVAL clear and B_CACHE set based on the
2962 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
2963 * B_CACHE bit is clear.
2965 * What this means, basically, is that the caller should use B_CACHE to
2966 * determine whether the buffer is fully valid or not and should clear
2967 * B_INVAL prior to issuing a read. If the caller intends to validate
2968 * the buffer by loading its data area with something, the caller needs
2969 * to clear B_INVAL. If the caller does this without issuing an I/O,
2970 * the caller should set B_CACHE ( as an optimization ), else the caller
2971 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2972 * a write attempt or if it was a successfull read. If the caller
2973 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
2974 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2977 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo,
2982 int bsize, error, maxsize, vmio;
2985 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
2986 KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
2987 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
2988 ASSERT_VOP_LOCKED(vp, "getblk");
2989 if (size > MAXBSIZE)
2990 panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2991 if (!unmapped_buf_allowed)
2992 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
2997 * Block if we are low on buffers. Certain processes are allowed
2998 * to completely exhaust the buffer cache.
3000 * If this check ever becomes a bottleneck it may be better to
3001 * move it into the else, when gbincore() fails. At the moment
3002 * it isn't a problem.
3004 if (numfreebuffers == 0) {
3005 if (TD_IS_IDLETHREAD(curthread))
3008 needsbuffer |= VFS_BIO_NEED_ANY;
3009 mtx_unlock(&nblock);
3013 bp = gbincore(bo, blkno);
3017 * Buffer is in-core. If the buffer is not busy nor managed,
3018 * it must be on a queue.
3020 lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
3022 if (flags & GB_LOCK_NOWAIT)
3023 lockflags |= LK_NOWAIT;
3025 error = BUF_TIMELOCK(bp, lockflags,
3026 BO_LOCKPTR(bo), "getblk", slpflag, slptimeo);
3029 * If we slept and got the lock we have to restart in case
3030 * the buffer changed identities.
3032 if (error == ENOLCK)
3034 /* We timed out or were interrupted. */
3037 /* If recursed, assume caller knows the rules. */
3038 else if (BUF_LOCKRECURSED(bp))
3042 * The buffer is locked. B_CACHE is cleared if the buffer is
3043 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
3044 * and for a VMIO buffer B_CACHE is adjusted according to the
3047 if (bp->b_flags & B_INVAL)
3048 bp->b_flags &= ~B_CACHE;
3049 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
3050 bp->b_flags |= B_CACHE;
3051 if (bp->b_flags & B_MANAGED)
3052 MPASS(bp->b_qindex == QUEUE_NONE);
3057 * check for size inconsistencies for non-VMIO case.
3059 if (bp->b_bcount != size) {
3060 if ((bp->b_flags & B_VMIO) == 0 ||
3061 (size > bp->b_kvasize)) {
3062 if (bp->b_flags & B_DELWRI) {
3064 * If buffer is pinned and caller does
3065 * not want sleep waiting for it to be
3066 * unpinned, bail out
3068 if (bp->b_pin_count > 0) {
3069 if (flags & GB_LOCK_NOWAIT) {
3076 bp->b_flags |= B_NOCACHE;
3079 if (LIST_EMPTY(&bp->b_dep)) {
3080 bp->b_flags |= B_RELBUF;
3083 bp->b_flags |= B_NOCACHE;
3092 * Handle the case of unmapped buffer which should
3093 * become mapped, or the buffer for which KVA
3094 * reservation is requested.
3096 bp_unmapped_get_kva(bp, blkno, size, flags);
3099 * If the size is inconsistant in the VMIO case, we can resize
3100 * the buffer. This might lead to B_CACHE getting set or
3101 * cleared. If the size has not changed, B_CACHE remains
3102 * unchanged from its previous state.
3104 if (bp->b_bcount != size)
3107 KASSERT(bp->b_offset != NOOFFSET,
3108 ("getblk: no buffer offset"));
3111 * A buffer with B_DELWRI set and B_CACHE clear must
3112 * be committed before we can return the buffer in
3113 * order to prevent the caller from issuing a read
3114 * ( due to B_CACHE not being set ) and overwriting
3117 * Most callers, including NFS and FFS, need this to
3118 * operate properly either because they assume they
3119 * can issue a read if B_CACHE is not set, or because
3120 * ( for example ) an uncached B_DELWRI might loop due
3121 * to softupdates re-dirtying the buffer. In the latter
3122 * case, B_CACHE is set after the first write completes,
3123 * preventing further loops.
3124 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
3125 * above while extending the buffer, we cannot allow the
3126 * buffer to remain with B_CACHE set after the write
3127 * completes or it will represent a corrupt state. To
3128 * deal with this we set B_NOCACHE to scrap the buffer
3131 * We might be able to do something fancy, like setting
3132 * B_CACHE in bwrite() except if B_DELWRI is already set,
3133 * so the below call doesn't set B_CACHE, but that gets real
3134 * confusing. This is much easier.
3137 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
3138 bp->b_flags |= B_NOCACHE;
3142 bp->b_flags &= ~B_DONE;
3145 * Buffer is not in-core, create new buffer. The buffer
3146 * returned by getnewbuf() is locked. Note that the returned
3147 * buffer is also considered valid (not marked B_INVAL).
3151 * If the user does not want us to create the buffer, bail out
3154 if (flags & GB_NOCREAT)
3156 bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
3157 offset = blkno * bsize;
3158 vmio = vp->v_object != NULL;
3160 maxsize = size + (offset & PAGE_MASK);
3163 /* Do not allow non-VMIO notmapped buffers. */
3164 flags &= ~GB_UNMAPPED;
3166 maxsize = imax(maxsize, bsize);
3168 bp = getnewbuf(vp, slpflag, slptimeo, size, maxsize, flags);
3170 if (slpflag || slptimeo)
3176 * This code is used to make sure that a buffer is not
3177 * created while the getnewbuf routine is blocked.
3178 * This can be a problem whether the vnode is locked or not.
3179 * If the buffer is created out from under us, we have to
3180 * throw away the one we just created.
3182 * Note: this must occur before we associate the buffer
3183 * with the vp especially considering limitations in
3184 * the splay tree implementation when dealing with duplicate
3188 if (gbincore(bo, blkno)) {
3190 bp->b_flags |= B_INVAL;
3196 * Insert the buffer into the hash, so that it can
3197 * be found by incore.
3199 bp->b_blkno = bp->b_lblkno = blkno;
3200 bp->b_offset = offset;
3205 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
3206 * buffer size starts out as 0, B_CACHE will be set by
3207 * allocbuf() for the VMIO case prior to it testing the
3208 * backing store for validity.
3212 bp->b_flags |= B_VMIO;
3213 KASSERT(vp->v_object == bp->b_bufobj->bo_object,
3214 ("ARGH! different b_bufobj->bo_object %p %p %p\n",
3215 bp, vp->v_object, bp->b_bufobj->bo_object));
3217 bp->b_flags &= ~B_VMIO;
3218 KASSERT(bp->b_bufobj->bo_object == NULL,
3219 ("ARGH! has b_bufobj->bo_object %p %p\n",
3220 bp, bp->b_bufobj->bo_object));
3221 BUF_CHECK_MAPPED(bp);
3225 bp->b_flags &= ~B_DONE;
3227 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
3228 BUF_ASSERT_HELD(bp);
3230 KASSERT(bp->b_bufobj == bo,
3231 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3236 * Get an empty, disassociated buffer of given size. The buffer is initially
3240 geteblk(int size, int flags)
3245 maxsize = (size + BKVAMASK) & ~BKVAMASK;
3246 while ((bp = getnewbuf(NULL, 0, 0, size, maxsize, flags)) == NULL) {
3247 if ((flags & GB_NOWAIT_BD) &&
3248 (curthread->td_pflags & TDP_BUFNEED) != 0)
3252 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
3253 BUF_ASSERT_HELD(bp);
3259 * This code constitutes the buffer memory from either anonymous system
3260 * memory (in the case of non-VMIO operations) or from an associated
3261 * VM object (in the case of VMIO operations). This code is able to
3262 * resize a buffer up or down.
3264 * Note that this code is tricky, and has many complications to resolve
3265 * deadlock or inconsistant data situations. Tread lightly!!!
3266 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3267 * the caller. Calling this code willy nilly can result in the loss of data.
3269 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
3270 * B_CACHE for the non-VMIO case.
3274 allocbuf(struct buf *bp, int size)
3276 int newbsize, mbsize;
3279 BUF_ASSERT_HELD(bp);
3281 if (bp->b_kvasize < size)
3282 panic("allocbuf: buffer too small");
3284 if ((bp->b_flags & B_VMIO) == 0) {
3288 * Just get anonymous memory from the kernel. Don't
3289 * mess with B_CACHE.
3291 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3292 if (bp->b_flags & B_MALLOC)
3295 newbsize = round_page(size);
3297 if (newbsize < bp->b_bufsize) {
3299 * malloced buffers are not shrunk
3301 if (bp->b_flags & B_MALLOC) {
3303 bp->b_bcount = size;
3305 free(bp->b_data, M_BIOBUF);
3306 if (bp->b_bufsize) {
3307 atomic_subtract_long(
3313 bp->b_saveaddr = bp->b_kvabase;
3314 bp->b_data = bp->b_saveaddr;
3316 bp->b_flags &= ~B_MALLOC;
3320 vm_hold_free_pages(bp, newbsize);
3321 } else if (newbsize > bp->b_bufsize) {
3323 * We only use malloced memory on the first allocation.
3324 * and revert to page-allocated memory when the buffer
3328 * There is a potential smp race here that could lead
3329 * to bufmallocspace slightly passing the max. It
3330 * is probably extremely rare and not worth worrying
3333 if ( (bufmallocspace < maxbufmallocspace) &&
3334 (bp->b_bufsize == 0) &&
3335 (mbsize <= PAGE_SIZE/2)) {
3337 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
3338 bp->b_bufsize = mbsize;
3339 bp->b_bcount = size;
3340 bp->b_flags |= B_MALLOC;
3341 atomic_add_long(&bufmallocspace, mbsize);
3347 * If the buffer is growing on its other-than-first allocation,
3348 * then we revert to the page-allocation scheme.
3350 if (bp->b_flags & B_MALLOC) {
3351 origbuf = bp->b_data;
3352 origbufsize = bp->b_bufsize;
3353 bp->b_data = bp->b_kvabase;
3354 if (bp->b_bufsize) {
3355 atomic_subtract_long(&bufmallocspace,
3360 bp->b_flags &= ~B_MALLOC;
3361 newbsize = round_page(newbsize);
3365 (vm_offset_t) bp->b_data + bp->b_bufsize,
3366 (vm_offset_t) bp->b_data + newbsize);
3368 bcopy(origbuf, bp->b_data, origbufsize);
3369 free(origbuf, M_BIOBUF);
3375 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3376 desiredpages = (size == 0) ? 0 :
3377 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
3379 if (bp->b_flags & B_MALLOC)
3380 panic("allocbuf: VMIO buffer can't be malloced");
3382 * Set B_CACHE initially if buffer is 0 length or will become
3385 if (size == 0 || bp->b_bufsize == 0)
3386 bp->b_flags |= B_CACHE;
3388 if (newbsize < bp->b_bufsize) {
3390 * DEV_BSIZE aligned new buffer size is less then the
3391 * DEV_BSIZE aligned existing buffer size. Figure out
3392 * if we have to remove any pages.
3394 if (desiredpages < bp->b_npages) {
3397 if ((bp->b_flags & B_UNMAPPED) == 0) {
3398 BUF_CHECK_MAPPED(bp);
3399 pmap_qremove((vm_offset_t)trunc_page(
3400 (vm_offset_t)bp->b_data) +
3401 (desiredpages << PAGE_SHIFT),
3402 (bp->b_npages - desiredpages));
3404 BUF_CHECK_UNMAPPED(bp);
3405 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
3406 for (i = desiredpages; i < bp->b_npages; i++) {
3408 * the page is not freed here -- it
3409 * is the responsibility of
3410 * vnode_pager_setsize
3413 KASSERT(m != bogus_page,
3414 ("allocbuf: bogus page found"));
3415 while (vm_page_sleep_if_busy(m, TRUE,
3419 bp->b_pages[i] = NULL;
3421 vm_page_unwire(m, 0);
3424 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
3425 bp->b_npages = desiredpages;
3427 } else if (size > bp->b_bcount) {
3429 * We are growing the buffer, possibly in a
3430 * byte-granular fashion.
3437 * Step 1, bring in the VM pages from the object,
3438 * allocating them if necessary. We must clear
3439 * B_CACHE if these pages are not valid for the
3440 * range covered by the buffer.
3443 obj = bp->b_bufobj->bo_object;
3445 VM_OBJECT_WLOCK(obj);
3446 while (bp->b_npages < desiredpages) {
3450 * We must allocate system pages since blocking
3451 * here could interfere with paging I/O, no
3452 * matter which process we are.
3454 * We can only test VPO_BUSY here. Blocking on
3455 * m->busy might lead to a deadlock:
3456 * vm_fault->getpages->cluster_read->allocbuf
3457 * Thus, we specify VM_ALLOC_IGN_SBUSY.
3459 m = vm_page_grab(obj, OFF_TO_IDX(bp->b_offset) +
3460 bp->b_npages, VM_ALLOC_NOBUSY |
3461 VM_ALLOC_SYSTEM | VM_ALLOC_WIRED |
3462 VM_ALLOC_RETRY | VM_ALLOC_IGN_SBUSY |
3463 VM_ALLOC_COUNT(desiredpages - bp->b_npages));
3465 bp->b_flags &= ~B_CACHE;
3466 bp->b_pages[bp->b_npages] = m;
3471 * Step 2. We've loaded the pages into the buffer,
3472 * we have to figure out if we can still have B_CACHE
3473 * set. Note that B_CACHE is set according to the
3474 * byte-granular range ( bcount and size ), new the
3475 * aligned range ( newbsize ).
3477 * The VM test is against m->valid, which is DEV_BSIZE
3478 * aligned. Needless to say, the validity of the data
3479 * needs to also be DEV_BSIZE aligned. Note that this
3480 * fails with NFS if the server or some other client
3481 * extends the file's EOF. If our buffer is resized,
3482 * B_CACHE may remain set! XXX
3485 toff = bp->b_bcount;
3486 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
3488 while ((bp->b_flags & B_CACHE) && toff < size) {
3491 if (tinc > (size - toff))
3494 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
3507 VM_OBJECT_WUNLOCK(obj);
3510 * Step 3, fixup the KVM pmap.
3512 if ((bp->b_flags & B_UNMAPPED) == 0)
3515 BUF_CHECK_UNMAPPED(bp);
3518 if (newbsize < bp->b_bufsize)
3520 bp->b_bufsize = newbsize; /* actual buffer allocation */
3521 bp->b_bcount = size; /* requested buffer size */
3525 extern int inflight_transient_maps;
3528 biodone(struct bio *bp)
3531 void (*done)(struct bio *);
3532 vm_offset_t start, end;
3535 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3537 bp->bio_flags |= BIO_DONE;
3538 if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) {
3539 start = trunc_page((vm_offset_t)bp->bio_data);
3540 end = round_page((vm_offset_t)bp->bio_data + bp->bio_length);
3546 done = bp->bio_done;
3553 pmap_qremove(start, OFF_TO_IDX(end - start));
3554 vm_map_remove(bio_transient_map, start, end);
3555 atomic_add_int(&inflight_transient_maps, -1);
3560 * Wait for a BIO to finish.
3562 * XXX: resort to a timeout for now. The optimal locking (if any) for this
3563 * case is not yet clear.
3566 biowait(struct bio *bp, const char *wchan)
3570 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3572 while ((bp->bio_flags & BIO_DONE) == 0)
3573 msleep(bp, mtxp, PRIBIO, wchan, hz / 10);
3575 if (bp->bio_error != 0)
3576 return (bp->bio_error);
3577 if (!(bp->bio_flags & BIO_ERROR))
3583 biofinish(struct bio *bp, struct devstat *stat, int error)
3587 bp->bio_error = error;
3588 bp->bio_flags |= BIO_ERROR;
3591 devstat_end_transaction_bio(stat, bp);
3598 * Wait for buffer I/O completion, returning error status. The buffer
3599 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR
3600 * error and cleared.
3603 bufwait(struct buf *bp)
3605 if (bp->b_iocmd == BIO_READ)
3606 bwait(bp, PRIBIO, "biord");
3608 bwait(bp, PRIBIO, "biowr");
3609 if (bp->b_flags & B_EINTR) {
3610 bp->b_flags &= ~B_EINTR;
3613 if (bp->b_ioflags & BIO_ERROR) {
3614 return (bp->b_error ? bp->b_error : EIO);
3621 * Call back function from struct bio back up to struct buf.
3624 bufdonebio(struct bio *bip)
3628 bp = bip->bio_caller2;
3629 bp->b_resid = bp->b_bcount - bip->bio_completed;
3630 bp->b_resid = bip->bio_resid; /* XXX: remove */
3631 bp->b_ioflags = bip->bio_flags;
3632 bp->b_error = bip->bio_error;
3634 bp->b_ioflags |= BIO_ERROR;
3640 dev_strategy(struct cdev *dev, struct buf *bp)
3645 KASSERT(dev->si_refcount > 0,
3646 ("dev_strategy on un-referenced struct cdev *(%s) %p",
3647 devtoname(dev), dev));
3649 csw = dev_refthread(dev, &ref);
3650 dev_strategy_csw(dev, csw, bp);
3651 dev_relthread(dev, ref);
3655 dev_strategy_csw(struct cdev *dev, struct cdevsw *csw, struct buf *bp)
3659 KASSERT(bp->b_iocmd == BIO_READ || bp->b_iocmd == BIO_WRITE,
3661 KASSERT(((dev->si_flags & SI_ETERNAL) != 0 && csw != NULL) ||
3662 dev->si_threadcount > 0,
3663 ("dev_strategy_csw threadcount cdev *(%s) %p", devtoname(dev),
3666 bp->b_error = ENXIO;
3667 bp->b_ioflags = BIO_ERROR;
3675 /* Try again later */
3676 tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3678 bip->bio_cmd = bp->b_iocmd;
3679 bip->bio_offset = bp->b_iooffset;
3680 bip->bio_length = bp->b_bcount;
3681 bip->bio_bcount = bp->b_bcount; /* XXX: remove */
3683 bip->bio_done = bufdonebio;
3684 bip->bio_caller2 = bp;
3686 (*csw->d_strategy)(bip);
3692 * Finish I/O on a buffer, optionally calling a completion function.
3693 * This is usually called from an interrupt so process blocking is
3696 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3697 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3698 * assuming B_INVAL is clear.
3700 * For the VMIO case, we set B_CACHE if the op was a read and no
3701 * read error occured, or if the op was a write. B_CACHE is never
3702 * set if the buffer is invalid or otherwise uncacheable.
3704 * biodone does not mess with B_INVAL, allowing the I/O routine or the
3705 * initiator to leave B_INVAL set to brelse the buffer out of existance
3706 * in the biodone routine.
3709 bufdone(struct buf *bp)
3711 struct bufobj *dropobj;
3712 void (*biodone)(struct buf *);
3714 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3717 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3718 BUF_ASSERT_HELD(bp);
3720 runningbufwakeup(bp);
3721 if (bp->b_iocmd == BIO_WRITE)
3722 dropobj = bp->b_bufobj;
3723 /* call optional completion function if requested */
3724 if (bp->b_iodone != NULL) {
3725 biodone = bp->b_iodone;
3726 bp->b_iodone = NULL;
3729 bufobj_wdrop(dropobj);
3736 bufobj_wdrop(dropobj);
3740 bufdone_finish(struct buf *bp)
3742 BUF_ASSERT_HELD(bp);
3744 if (!LIST_EMPTY(&bp->b_dep))
3747 if (bp->b_flags & B_VMIO) {
3752 int bogus, i, iosize;
3754 obj = bp->b_bufobj->bo_object;
3755 KASSERT(obj->paging_in_progress >= bp->b_npages,
3756 ("biodone_finish: paging in progress(%d) < b_npages(%d)",
3757 obj->paging_in_progress, bp->b_npages));
3760 KASSERT(vp->v_holdcnt > 0,
3761 ("biodone_finish: vnode %p has zero hold count", vp));
3762 KASSERT(vp->v_object != NULL,
3763 ("biodone_finish: vnode %p has no vm_object", vp));
3765 foff = bp->b_offset;
3766 KASSERT(bp->b_offset != NOOFFSET,
3767 ("biodone_finish: bp %p has no buffer offset", bp));
3770 * Set B_CACHE if the op was a normal read and no error
3771 * occured. B_CACHE is set for writes in the b*write()
3774 iosize = bp->b_bcount - bp->b_resid;
3775 if (bp->b_iocmd == BIO_READ &&
3776 !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3777 !(bp->b_ioflags & BIO_ERROR)) {
3778 bp->b_flags |= B_CACHE;
3781 VM_OBJECT_WLOCK(obj);
3782 for (i = 0; i < bp->b_npages; i++) {
3786 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3791 * cleanup bogus pages, restoring the originals
3794 if (m == bogus_page) {
3795 bogus = bogusflag = 1;
3796 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3798 panic("biodone: page disappeared!");
3801 KASSERT(OFF_TO_IDX(foff) == m->pindex,
3802 ("biodone_finish: foff(%jd)/pindex(%ju) mismatch",
3803 (intmax_t)foff, (uintmax_t)m->pindex));
3806 * In the write case, the valid and clean bits are
3807 * already changed correctly ( see bdwrite() ), so we
3808 * only need to do this here in the read case.
3810 if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3811 KASSERT((m->dirty & vm_page_bits(foff &
3812 PAGE_MASK, resid)) == 0, ("bufdone_finish:"
3813 " page %p has unexpected dirty bits", m));
3814 vfs_page_set_valid(bp, foff, m);
3817 vm_page_io_finish(m);
3818 vm_object_pip_subtract(obj, 1);
3819 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3822 vm_object_pip_wakeupn(obj, 0);
3823 VM_OBJECT_WUNLOCK(obj);
3824 if (bogus && (bp->b_flags & B_UNMAPPED) == 0) {
3825 BUF_CHECK_MAPPED(bp);
3826 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3827 bp->b_pages, bp->b_npages);
3832 * For asynchronous completions, release the buffer now. The brelse
3833 * will do a wakeup there if necessary - so no need to do a wakeup
3834 * here in the async case. The sync case always needs to do a wakeup.
3837 if (bp->b_flags & B_ASYNC) {
3838 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3847 * This routine is called in lieu of iodone in the case of
3848 * incomplete I/O. This keeps the busy status for pages
3852 vfs_unbusy_pages(struct buf *bp)
3858 runningbufwakeup(bp);
3859 if (!(bp->b_flags & B_VMIO))
3862 obj = bp->b_bufobj->bo_object;
3863 VM_OBJECT_WLOCK(obj);
3864 for (i = 0; i < bp->b_npages; i++) {
3866 if (m == bogus_page) {
3867 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3869 panic("vfs_unbusy_pages: page missing\n");
3871 if ((bp->b_flags & B_UNMAPPED) == 0) {
3872 BUF_CHECK_MAPPED(bp);
3873 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3874 bp->b_pages, bp->b_npages);
3876 BUF_CHECK_UNMAPPED(bp);
3878 vm_object_pip_subtract(obj, 1);
3879 vm_page_io_finish(m);
3881 vm_object_pip_wakeupn(obj, 0);
3882 VM_OBJECT_WUNLOCK(obj);
3886 * vfs_page_set_valid:
3888 * Set the valid bits in a page based on the supplied offset. The
3889 * range is restricted to the buffer's size.
3891 * This routine is typically called after a read completes.
3894 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3899 * Compute the end offset, eoff, such that [off, eoff) does not span a
3900 * page boundary and eoff is not greater than the end of the buffer.
3901 * The end of the buffer, in this case, is our file EOF, not the
3902 * allocation size of the buffer.
3904 eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
3905 if (eoff > bp->b_offset + bp->b_bcount)
3906 eoff = bp->b_offset + bp->b_bcount;
3909 * Set valid range. This is typically the entire buffer and thus the
3913 vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off);
3917 * vfs_page_set_validclean:
3919 * Set the valid bits and clear the dirty bits in a page based on the
3920 * supplied offset. The range is restricted to the buffer's size.
3923 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3925 vm_ooffset_t soff, eoff;
3928 * Start and end offsets in buffer. eoff - soff may not cross a
3929 * page boundry or cross the end of the buffer. The end of the
3930 * buffer, in this case, is our file EOF, not the allocation size
3934 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3935 if (eoff > bp->b_offset + bp->b_bcount)
3936 eoff = bp->b_offset + bp->b_bcount;
3939 * Set valid range. This is typically the entire buffer and thus the
3943 vm_page_set_validclean(
3945 (vm_offset_t) (soff & PAGE_MASK),
3946 (vm_offset_t) (eoff - soff)
3952 * Ensure that all buffer pages are not busied by VPO_BUSY flag. If
3953 * any page is busy, drain the flag.
3956 vfs_drain_busy_pages(struct buf *bp)
3961 VM_OBJECT_ASSERT_WLOCKED(bp->b_bufobj->bo_object);
3963 for (i = 0; i < bp->b_npages; i++) {
3965 if ((m->oflags & VPO_BUSY) != 0) {
3966 for (; last_busied < i; last_busied++)
3967 vm_page_busy(bp->b_pages[last_busied]);
3968 while ((m->oflags & VPO_BUSY) != 0)
3969 vm_page_sleep(m, "vbpage");
3972 for (i = 0; i < last_busied; i++)
3973 vm_page_wakeup(bp->b_pages[i]);
3977 * This routine is called before a device strategy routine.
3978 * It is used to tell the VM system that paging I/O is in
3979 * progress, and treat the pages associated with the buffer
3980 * almost as being VPO_BUSY. Also the object paging_in_progress
3981 * flag is handled to make sure that the object doesn't become
3984 * Since I/O has not been initiated yet, certain buffer flags
3985 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
3986 * and should be ignored.
3989 vfs_busy_pages(struct buf *bp, int clear_modify)
3996 if (!(bp->b_flags & B_VMIO))
3999 obj = bp->b_bufobj->bo_object;
4000 foff = bp->b_offset;
4001 KASSERT(bp->b_offset != NOOFFSET,
4002 ("vfs_busy_pages: no buffer offset"));
4003 VM_OBJECT_WLOCK(obj);
4004 vfs_drain_busy_pages(bp);
4005 if (bp->b_bufsize != 0)
4006 vfs_setdirty_locked_object(bp);
4008 for (i = 0; i < bp->b_npages; i++) {
4011 if ((bp->b_flags & B_CLUSTER) == 0) {
4012 vm_object_pip_add(obj, 1);
4013 vm_page_io_start(m);
4016 * When readying a buffer for a read ( i.e
4017 * clear_modify == 0 ), it is important to do
4018 * bogus_page replacement for valid pages in
4019 * partially instantiated buffers. Partially
4020 * instantiated buffers can, in turn, occur when
4021 * reconstituting a buffer from its VM backing store
4022 * base. We only have to do this if B_CACHE is
4023 * clear ( which causes the I/O to occur in the
4024 * first place ). The replacement prevents the read
4025 * I/O from overwriting potentially dirty VM-backed
4026 * pages. XXX bogus page replacement is, uh, bogus.
4027 * It may not work properly with small-block devices.
4028 * We need to find a better way.
4031 pmap_remove_write(m);
4032 vfs_page_set_validclean(bp, foff, m);
4033 } else if (m->valid == VM_PAGE_BITS_ALL &&
4034 (bp->b_flags & B_CACHE) == 0) {
4035 bp->b_pages[i] = bogus_page;
4038 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4040 VM_OBJECT_WUNLOCK(obj);
4041 if (bogus && (bp->b_flags & B_UNMAPPED) == 0) {
4042 BUF_CHECK_MAPPED(bp);
4043 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4044 bp->b_pages, bp->b_npages);
4049 * vfs_bio_set_valid:
4051 * Set the range within the buffer to valid. The range is
4052 * relative to the beginning of the buffer, b_offset. Note that
4053 * b_offset itself may be offset from the beginning of the first
4057 vfs_bio_set_valid(struct buf *bp, int base, int size)
4062 if (!(bp->b_flags & B_VMIO))
4066 * Fixup base to be relative to beginning of first page.
4067 * Set initial n to be the maximum number of bytes in the
4068 * first page that can be validated.
4070 base += (bp->b_offset & PAGE_MASK);
4071 n = PAGE_SIZE - (base & PAGE_MASK);
4073 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4074 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4078 vm_page_set_valid_range(m, base & PAGE_MASK, n);
4083 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4089 * If the specified buffer is a non-VMIO buffer, clear the entire
4090 * buffer. If the specified buffer is a VMIO buffer, clear and
4091 * validate only the previously invalid portions of the buffer.
4092 * This routine essentially fakes an I/O, so we need to clear
4093 * BIO_ERROR and B_INVAL.
4095 * Note that while we only theoretically need to clear through b_bcount,
4096 * we go ahead and clear through b_bufsize.
4099 vfs_bio_clrbuf(struct buf *bp)
4101 int i, j, mask, sa, ea, slide;
4103 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
4107 bp->b_flags &= ~B_INVAL;
4108 bp->b_ioflags &= ~BIO_ERROR;
4109 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4110 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4111 (bp->b_offset & PAGE_MASK) == 0) {
4112 if (bp->b_pages[0] == bogus_page)
4114 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4115 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[0]->object);
4116 if ((bp->b_pages[0]->valid & mask) == mask)
4118 if ((bp->b_pages[0]->valid & mask) == 0) {
4119 pmap_zero_page_area(bp->b_pages[0], 0, bp->b_bufsize);
4120 bp->b_pages[0]->valid |= mask;
4124 sa = bp->b_offset & PAGE_MASK;
4126 for (i = 0; i < bp->b_npages; i++, sa = 0) {
4127 slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize);
4128 ea = slide & PAGE_MASK;
4131 if (bp->b_pages[i] == bogus_page)
4134 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4135 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[i]->object);
4136 if ((bp->b_pages[i]->valid & mask) == mask)
4138 if ((bp->b_pages[i]->valid & mask) == 0)
4139 pmap_zero_page_area(bp->b_pages[i], sa, ea - sa);
4141 for (; sa < ea; sa += DEV_BSIZE, j++) {
4142 if ((bp->b_pages[i]->valid & (1 << j)) == 0) {
4143 pmap_zero_page_area(bp->b_pages[i],
4148 bp->b_pages[i]->valid |= mask;
4151 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4156 vfs_bio_bzero_buf(struct buf *bp, int base, int size)
4161 if ((bp->b_flags & B_UNMAPPED) == 0) {
4162 BUF_CHECK_MAPPED(bp);
4163 bzero(bp->b_data + base, size);
4165 BUF_CHECK_UNMAPPED(bp);
4166 n = PAGE_SIZE - (base & PAGE_MASK);
4167 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4171 pmap_zero_page_area(m, base & PAGE_MASK, n);
4180 * vm_hold_load_pages and vm_hold_free_pages get pages into
4181 * a buffers address space. The pages are anonymous and are
4182 * not associated with a file object.
4185 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4191 BUF_CHECK_MAPPED(bp);
4193 to = round_page(to);
4194 from = round_page(from);
4195 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4197 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4200 * note: must allocate system pages since blocking here
4201 * could interfere with paging I/O, no matter which
4204 p = vm_page_alloc(NULL, 0, VM_ALLOC_SYSTEM | VM_ALLOC_NOOBJ |
4205 VM_ALLOC_WIRED | VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT));
4210 pmap_qenter(pg, &p, 1);
4211 bp->b_pages[index] = p;
4213 bp->b_npages = index;
4216 /* Return pages associated with this buf to the vm system */
4218 vm_hold_free_pages(struct buf *bp, int newbsize)
4222 int index, newnpages;
4224 BUF_CHECK_MAPPED(bp);
4226 from = round_page((vm_offset_t)bp->b_data + newbsize);
4227 newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4228 if (bp->b_npages > newnpages)
4229 pmap_qremove(from, bp->b_npages - newnpages);
4230 for (index = newnpages; index < bp->b_npages; index++) {
4231 p = bp->b_pages[index];
4232 bp->b_pages[index] = NULL;
4234 printf("vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
4235 (intmax_t)bp->b_blkno, (intmax_t)bp->b_lblkno);
4238 atomic_subtract_int(&cnt.v_wire_count, 1);
4240 bp->b_npages = newnpages;
4244 * Map an IO request into kernel virtual address space.
4246 * All requests are (re)mapped into kernel VA space.
4247 * Notice that we use b_bufsize for the size of the buffer
4248 * to be mapped. b_bcount might be modified by the driver.
4250 * Note that even if the caller determines that the address space should
4251 * be valid, a race or a smaller-file mapped into a larger space may
4252 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
4253 * check the return value.
4256 vmapbuf(struct buf *bp, int mapbuf)
4262 if (bp->b_bufsize < 0)
4264 prot = VM_PROT_READ;
4265 if (bp->b_iocmd == BIO_READ)
4266 prot |= VM_PROT_WRITE; /* Less backwards than it looks */
4267 if ((pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
4268 (vm_offset_t)bp->b_data, bp->b_bufsize, prot, bp->b_pages,
4269 btoc(MAXPHYS))) < 0)
4271 bp->b_npages = pidx;
4272 if (mapbuf || !unmapped_buf_allowed) {
4273 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
4274 kva = bp->b_saveaddr;
4275 bp->b_saveaddr = bp->b_data;
4276 bp->b_data = kva + (((vm_offset_t)bp->b_data) & PAGE_MASK);
4277 bp->b_flags &= ~B_UNMAPPED;
4279 bp->b_flags |= B_UNMAPPED;
4280 bp->b_offset = ((vm_offset_t)bp->b_data) & PAGE_MASK;
4281 bp->b_saveaddr = bp->b_data;
4282 bp->b_data = unmapped_buf;
4288 * Free the io map PTEs associated with this IO operation.
4289 * We also invalidate the TLB entries and restore the original b_addr.
4292 vunmapbuf(struct buf *bp)
4296 npages = bp->b_npages;
4297 if (bp->b_flags & B_UNMAPPED)
4298 bp->b_flags &= ~B_UNMAPPED;
4300 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4301 vm_page_unhold_pages(bp->b_pages, npages);
4303 bp->b_data = bp->b_saveaddr;
4307 bdone(struct buf *bp)
4311 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4313 bp->b_flags |= B_DONE;
4319 bwait(struct buf *bp, u_char pri, const char *wchan)
4323 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4325 while ((bp->b_flags & B_DONE) == 0)
4326 msleep(bp, mtxp, pri, wchan, 0);
4331 bufsync(struct bufobj *bo, int waitfor)
4334 return (VOP_FSYNC(bo->__bo_vnode, waitfor, curthread));
4338 bufstrategy(struct bufobj *bo, struct buf *bp)
4344 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
4345 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
4346 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
4347 i = VOP_STRATEGY(vp, bp);
4348 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
4352 bufobj_wrefl(struct bufobj *bo)
4355 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4356 ASSERT_BO_WLOCKED(bo);
4361 bufobj_wref(struct bufobj *bo)
4364 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4371 bufobj_wdrop(struct bufobj *bo)
4374 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
4376 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
4377 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
4378 bo->bo_flag &= ~BO_WWAIT;
4379 wakeup(&bo->bo_numoutput);
4385 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
4389 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
4390 ASSERT_BO_WLOCKED(bo);
4392 while (bo->bo_numoutput) {
4393 bo->bo_flag |= BO_WWAIT;
4394 error = msleep(&bo->bo_numoutput, BO_LOCKPTR(bo),
4395 slpflag | (PRIBIO + 1), "bo_wwait", timeo);
4403 bpin(struct buf *bp)
4407 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4414 bunpin(struct buf *bp)
4418 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4420 if (--bp->b_pin_count == 0)
4426 bunpin_wait(struct buf *bp)
4430 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4432 while (bp->b_pin_count > 0)
4433 msleep(bp, mtxp, PRIBIO, "bwunpin", 0);
4438 * Set bio_data or bio_ma for struct bio from the struct buf.
4441 bdata2bio(struct buf *bp, struct bio *bip)
4444 if ((bp->b_flags & B_UNMAPPED) != 0) {
4445 KASSERT(unmapped_buf_allowed, ("unmapped"));
4446 bip->bio_ma = bp->b_pages;
4447 bip->bio_ma_n = bp->b_npages;
4448 bip->bio_data = unmapped_buf;
4449 bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
4450 bip->bio_flags |= BIO_UNMAPPED;
4451 KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) /
4452 PAGE_SIZE == bp->b_npages,
4453 ("Buffer %p too short: %d %d %d", bp, bip->bio_ma_offset,
4454 bip->bio_length, bip->bio_ma_n));
4456 bip->bio_data = bp->b_data;
4461 #include "opt_ddb.h"
4463 #include <ddb/ddb.h>
4465 /* DDB command to show buffer data */
4466 DB_SHOW_COMMAND(buffer, db_show_buffer)
4469 struct buf *bp = (struct buf *)addr;
4472 db_printf("usage: show buffer <addr>\n");
4476 db_printf("buf at %p\n", bp);
4477 db_printf("b_flags = 0x%b, b_xflags=0x%b, b_vflags=0x%b\n",
4478 (u_int)bp->b_flags, PRINT_BUF_FLAGS, (u_int)bp->b_xflags,
4479 PRINT_BUF_XFLAGS, (u_int)bp->b_vflags, PRINT_BUF_VFLAGS);
4481 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4482 "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_lblkno = %jd, "
4484 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4485 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4486 (intmax_t)bp->b_lblkno, bp->b_dep.lh_first);
4489 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4490 for (i = 0; i < bp->b_npages; i++) {
4493 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4494 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4495 if ((i + 1) < bp->b_npages)
4501 BUF_LOCKPRINTINFO(bp);
4504 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
4509 for (i = 0; i < nbuf; i++) {
4511 if (BUF_ISLOCKED(bp)) {
4512 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4518 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
4524 db_printf("usage: show vnodebufs <addr>\n");
4527 vp = (struct vnode *)addr;
4528 db_printf("Clean buffers:\n");
4529 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
4530 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4533 db_printf("Dirty buffers:\n");
4534 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
4535 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4540 DB_COMMAND(countfreebufs, db_coundfreebufs)
4543 int i, used = 0, nfree = 0;
4546 db_printf("usage: countfreebufs\n");
4550 for (i = 0; i < nbuf; i++) {
4552 if ((bp->b_flags & B_INFREECNT) != 0)
4558 db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
4560 db_printf("numfreebuffers is %d\n", numfreebuffers);