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 += min((physmem_est - 65536) * 2 / (factor * 5),
564 32 * 1024 * 1024 / (factor * 5));
566 if (maxbcache && nbuf > maxbcache / BKVASIZE)
567 nbuf = maxbcache / BKVASIZE;
572 /* XXX Avoid unsigned long overflows later on with maxbufspace. */
573 maxbuf = (LONG_MAX / 3) / BKVASIZE;
576 printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
582 * Ideal allocation size for the transient bio submap if 10%
583 * of the maximal space buffer map. This roughly corresponds
584 * to the amount of the buffer mapped for typical UFS load.
586 * Clip the buffer map to reserve space for the transient
587 * BIOs, if its extent is bigger than 90% (80% on i386) of the
588 * maximum buffer map extent on the platform.
590 * The fall-back to the maxbuf in case of maxbcache unset,
591 * allows to not trim the buffer KVA for the architectures
592 * with ample KVA space.
594 if (bio_transient_maxcnt == 0 && unmapped_buf_allowed) {
595 maxbuf_sz = maxbcache != 0 ? maxbcache : maxbuf * BKVASIZE;
596 buf_sz = (long)nbuf * BKVASIZE;
597 if (buf_sz < maxbuf_sz / TRANSIENT_DENOM *
598 (TRANSIENT_DENOM - 1)) {
600 * There is more KVA than memory. Do not
601 * adjust buffer map size, and assign the rest
602 * of maxbuf to transient map.
604 biotmap_sz = maxbuf_sz - buf_sz;
607 * Buffer map spans all KVA we could afford on
608 * this platform. Give 10% (20% on i386) of
609 * the buffer map to the transient bio map.
611 biotmap_sz = buf_sz / TRANSIENT_DENOM;
612 buf_sz -= biotmap_sz;
614 if (biotmap_sz / INT_MAX > MAXPHYS)
615 bio_transient_maxcnt = INT_MAX;
617 bio_transient_maxcnt = biotmap_sz / MAXPHYS;
619 * Artifically limit to 1024 simultaneous in-flight I/Os
620 * using the transient mapping.
622 if (bio_transient_maxcnt > 1024)
623 bio_transient_maxcnt = 1024;
625 nbuf = buf_sz / BKVASIZE;
629 * swbufs are used as temporary holders for I/O, such as paging I/O.
630 * We have no less then 16 and no more then 256.
632 nswbuf = max(min(nbuf/4, 256), 16);
634 if (nswbuf < NSWBUF_MIN)
642 * Reserve space for the buffer cache buffers
645 v = (caddr_t)(swbuf + nswbuf);
647 v = (caddr_t)(buf + nbuf);
652 /* Initialize the buffer subsystem. Called before use of any buffers. */
659 mtx_init(&bqlock, "buf queue lock", NULL, MTX_DEF);
660 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
661 mtx_init(&nblock, "needsbuffer lock", NULL, MTX_DEF);
662 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
664 /* next, make a null set of free lists */
665 for (i = 0; i < BUFFER_QUEUES; i++)
666 TAILQ_INIT(&bufqueues[i]);
668 /* finally, initialize each buffer header and stick on empty q */
669 for (i = 0; i < nbuf; i++) {
671 bzero(bp, sizeof *bp);
672 bp->b_flags = B_INVAL | B_INFREECNT;
673 bp->b_rcred = NOCRED;
674 bp->b_wcred = NOCRED;
675 bp->b_qindex = QUEUE_EMPTY;
677 LIST_INIT(&bp->b_dep);
679 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
681 bq_len[QUEUE_EMPTY]++;
686 * maxbufspace is the absolute maximum amount of buffer space we are
687 * allowed to reserve in KVM and in real terms. The absolute maximum
688 * is nominally used by buf_daemon. hibufspace is the nominal maximum
689 * used by most other processes. The differential is required to
690 * ensure that buf_daemon is able to run when other processes might
691 * be blocked waiting for buffer space.
693 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
694 * this may result in KVM fragmentation which is not handled optimally
697 maxbufspace = (long)nbuf * BKVASIZE;
698 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
699 lobufspace = hibufspace - MAXBSIZE;
702 * Note: The 16 MiB upper limit for hirunningspace was chosen
703 * arbitrarily and may need further tuning. It corresponds to
704 * 128 outstanding write IO requests (if IO size is 128 KiB),
705 * which fits with many RAID controllers' tagged queuing limits.
706 * The lower 1 MiB limit is the historical upper limit for
709 hirunningspace = lmax(lmin(roundup(hibufspace / 64, MAXBSIZE),
710 16 * 1024 * 1024), 1024 * 1024);
711 lorunningspace = roundup((hirunningspace * 2) / 3, MAXBSIZE);
714 * Limit the amount of malloc memory since it is wired permanently into
715 * the kernel space. Even though this is accounted for in the buffer
716 * allocation, we don't want the malloced region to grow uncontrolled.
717 * The malloc scheme improves memory utilization significantly on average
718 * (small) directories.
720 maxbufmallocspace = hibufspace / 20;
723 * Reduce the chance of a deadlock occuring by limiting the number
724 * of delayed-write dirty buffers we allow to stack up.
726 hidirtybuffers = nbuf / 4 + 20;
727 dirtybufthresh = hidirtybuffers * 9 / 10;
730 * To support extreme low-memory systems, make sure hidirtybuffers cannot
731 * eat up all available buffer space. This occurs when our minimum cannot
732 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
733 * BKVASIZE'd buffers.
735 while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
736 hidirtybuffers >>= 1;
738 lodirtybuffers = hidirtybuffers / 2;
741 * Try to keep the number of free buffers in the specified range,
742 * and give special processes (e.g. like buf_daemon) access to an
745 lofreebuffers = nbuf / 18 + 5;
746 hifreebuffers = 2 * lofreebuffers;
747 numfreebuffers = nbuf;
749 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
750 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
751 unmapped_buf = (caddr_t)kmem_alloc_nofault(kernel_map, MAXPHYS);
756 vfs_buf_check_mapped(struct buf *bp)
759 KASSERT((bp->b_flags & B_UNMAPPED) == 0,
760 ("mapped buf %p %x", bp, bp->b_flags));
761 KASSERT(bp->b_kvabase != unmapped_buf,
762 ("mapped buf: b_kvabase was not updated %p", bp));
763 KASSERT(bp->b_data != unmapped_buf,
764 ("mapped buf: b_data was not updated %p", bp));
768 vfs_buf_check_unmapped(struct buf *bp)
771 KASSERT((bp->b_flags & B_UNMAPPED) == B_UNMAPPED,
772 ("unmapped buf %p %x", bp, bp->b_flags));
773 KASSERT(bp->b_kvabase == unmapped_buf,
774 ("unmapped buf: corrupted b_kvabase %p", bp));
775 KASSERT(bp->b_data == unmapped_buf,
776 ("unmapped buf: corrupted b_data %p", bp));
779 #define BUF_CHECK_MAPPED(bp) vfs_buf_check_mapped(bp)
780 #define BUF_CHECK_UNMAPPED(bp) vfs_buf_check_unmapped(bp)
782 #define BUF_CHECK_MAPPED(bp) do {} while (0)
783 #define BUF_CHECK_UNMAPPED(bp) do {} while (0)
787 bpmap_qenter(struct buf *bp)
790 BUF_CHECK_MAPPED(bp);
793 * bp->b_data is relative to bp->b_offset, but
794 * bp->b_offset may be offset into the first page.
796 bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
797 pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
798 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
799 (vm_offset_t)(bp->b_offset & PAGE_MASK));
803 * bfreekva() - free the kva allocation for a buffer.
805 * Since this call frees up buffer space, we call bufspacewakeup().
808 bfreekva(struct buf *bp)
811 if (bp->b_kvasize == 0)
814 atomic_add_int(&buffreekvacnt, 1);
815 atomic_subtract_long(&bufspace, bp->b_kvasize);
816 if ((bp->b_flags & B_UNMAPPED) == 0) {
817 BUF_CHECK_MAPPED(bp);
818 vm_map_remove(buffer_map, (vm_offset_t)bp->b_kvabase,
819 (vm_offset_t)bp->b_kvabase + bp->b_kvasize);
821 BUF_CHECK_UNMAPPED(bp);
822 if ((bp->b_flags & B_KVAALLOC) != 0) {
823 vm_map_remove(buffer_map, (vm_offset_t)bp->b_kvaalloc,
824 (vm_offset_t)bp->b_kvaalloc + bp->b_kvasize);
826 atomic_subtract_long(&unmapped_bufspace, bp->b_kvasize);
827 bp->b_flags &= ~(B_UNMAPPED | B_KVAALLOC);
836 * Mark the buffer for removal from the appropriate free list in brelse.
840 bremfree(struct buf *bp)
844 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
845 KASSERT((bp->b_flags & B_REMFREE) == 0,
846 ("bremfree: buffer %p already marked for delayed removal.", bp));
847 KASSERT(bp->b_qindex != QUEUE_NONE,
848 ("bremfree: buffer %p not on a queue.", bp));
849 BUF_ASSERT_XLOCKED(bp);
851 bp->b_flags |= B_REMFREE;
852 /* Fixup numfreebuffers count. */
853 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
854 KASSERT((bp->b_flags & B_INFREECNT) != 0,
855 ("buf %p not counted in numfreebuffers", bp));
856 bp->b_flags &= ~B_INFREECNT;
857 old = atomic_fetchadd_int(&numfreebuffers, -1);
858 KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
865 * Force an immediate removal from a free list. Used only in nfs when
866 * it abuses the b_freelist pointer.
869 bremfreef(struct buf *bp)
879 * Removes a buffer from the free list, must be called with the
883 bremfreel(struct buf *bp)
887 CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
888 bp, bp->b_vp, bp->b_flags);
889 KASSERT(bp->b_qindex != QUEUE_NONE,
890 ("bremfreel: buffer %p not on a queue.", bp));
891 BUF_ASSERT_XLOCKED(bp);
892 mtx_assert(&bqlock, MA_OWNED);
894 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
896 KASSERT(bq_len[bp->b_qindex] >= 1, ("queue %d underflow",
898 bq_len[bp->b_qindex]--;
900 bp->b_qindex = QUEUE_NONE;
902 * If this was a delayed bremfree() we only need to remove the buffer
903 * from the queue and return the stats are already done.
905 if (bp->b_flags & B_REMFREE) {
906 bp->b_flags &= ~B_REMFREE;
910 * Fixup numfreebuffers count. If the buffer is invalid or not
911 * delayed-write, the buffer was free and we must decrement
914 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
915 KASSERT((bp->b_flags & B_INFREECNT) != 0,
916 ("buf %p not counted in numfreebuffers", bp));
917 bp->b_flags &= ~B_INFREECNT;
918 old = atomic_fetchadd_int(&numfreebuffers, -1);
919 KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
924 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must
925 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
926 * the buffer is valid and we do not have to do anything.
929 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
930 int cnt, struct ucred * cred)
935 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
936 if (inmem(vp, *rablkno))
938 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
940 if ((rabp->b_flags & B_CACHE) == 0) {
941 if (!TD_IS_IDLETHREAD(curthread))
942 curthread->td_ru.ru_inblock++;
943 rabp->b_flags |= B_ASYNC;
944 rabp->b_flags &= ~B_INVAL;
945 rabp->b_ioflags &= ~BIO_ERROR;
946 rabp->b_iocmd = BIO_READ;
947 if (rabp->b_rcred == NOCRED && cred != NOCRED)
948 rabp->b_rcred = crhold(cred);
949 vfs_busy_pages(rabp, 0);
951 rabp->b_iooffset = dbtob(rabp->b_blkno);
960 * Entry point for bread() and breadn() via #defines in sys/buf.h.
962 * Get a buffer with the specified data. Look in the cache first. We
963 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
964 * is set, the buffer is valid and we do not have to do anything, see
965 * getblk(). Also starts asynchronous I/O on read-ahead blocks.
968 breadn_flags(struct vnode *vp, daddr_t blkno, int size, daddr_t *rablkno,
969 int *rabsize, int cnt, struct ucred *cred, int flags, struct buf **bpp)
972 int rv = 0, readwait = 0;
974 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
976 * Can only return NULL if GB_LOCK_NOWAIT flag is specified.
978 *bpp = bp = getblk(vp, blkno, size, 0, 0, flags);
982 /* if not found in cache, do some I/O */
983 if ((bp->b_flags & B_CACHE) == 0) {
984 if (!TD_IS_IDLETHREAD(curthread))
985 curthread->td_ru.ru_inblock++;
986 bp->b_iocmd = BIO_READ;
987 bp->b_flags &= ~B_INVAL;
988 bp->b_ioflags &= ~BIO_ERROR;
989 if (bp->b_rcred == NOCRED && cred != NOCRED)
990 bp->b_rcred = crhold(cred);
991 vfs_busy_pages(bp, 0);
992 bp->b_iooffset = dbtob(bp->b_blkno);
997 breada(vp, rablkno, rabsize, cnt, cred);
1006 * Write, release buffer on completion. (Done by iodone
1007 * if async). Do not bother writing anything if the buffer
1010 * Note that we set B_CACHE here, indicating that buffer is
1011 * fully valid and thus cacheable. This is true even of NFS
1012 * now so we set it generally. This could be set either here
1013 * or in biodone() since the I/O is synchronous. We put it
1017 bufwrite(struct buf *bp)
1023 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1024 if (bp->b_flags & B_INVAL) {
1029 if (bp->b_flags & B_BARRIER)
1032 oldflags = bp->b_flags;
1034 BUF_ASSERT_HELD(bp);
1036 if (bp->b_pin_count > 0)
1039 KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
1040 ("FFS background buffer should not get here %p", bp));
1044 vp_md = vp->v_vflag & VV_MD;
1049 * Mark the buffer clean. Increment the bufobj write count
1050 * before bundirty() call, to prevent other thread from seeing
1051 * empty dirty list and zero counter for writes in progress,
1052 * falsely indicating that the bufobj is clean.
1054 bufobj_wref(bp->b_bufobj);
1057 bp->b_flags &= ~B_DONE;
1058 bp->b_ioflags &= ~BIO_ERROR;
1059 bp->b_flags |= B_CACHE;
1060 bp->b_iocmd = BIO_WRITE;
1062 vfs_busy_pages(bp, 1);
1065 * Normal bwrites pipeline writes
1067 bp->b_runningbufspace = bp->b_bufsize;
1068 atomic_add_long(&runningbufspace, bp->b_runningbufspace);
1070 if (!TD_IS_IDLETHREAD(curthread))
1071 curthread->td_ru.ru_oublock++;
1072 if (oldflags & B_ASYNC)
1074 bp->b_iooffset = dbtob(bp->b_blkno);
1077 if ((oldflags & B_ASYNC) == 0) {
1078 int rtval = bufwait(bp);
1083 * don't allow the async write to saturate the I/O
1084 * system. We will not deadlock here because
1085 * we are blocking waiting for I/O that is already in-progress
1086 * to complete. We do not block here if it is the update
1087 * or syncer daemon trying to clean up as that can lead
1090 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
1091 waitrunningbufspace();
1098 bufbdflush(struct bufobj *bo, struct buf *bp)
1102 if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
1103 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
1105 } else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
1108 * Try to find a buffer to flush.
1110 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
1111 if ((nbp->b_vflags & BV_BKGRDINPROG) ||
1113 LK_EXCLUSIVE | LK_NOWAIT, NULL))
1116 panic("bdwrite: found ourselves");
1118 /* Don't countdeps with the bo lock held. */
1119 if (buf_countdeps(nbp, 0)) {
1124 if (nbp->b_flags & B_CLUSTEROK) {
1125 vfs_bio_awrite(nbp);
1130 dirtybufferflushes++;
1139 * Delayed write. (Buffer is marked dirty). Do not bother writing
1140 * anything if the buffer is marked invalid.
1142 * Note that since the buffer must be completely valid, we can safely
1143 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
1144 * biodone() in order to prevent getblk from writing the buffer
1145 * out synchronously.
1148 bdwrite(struct buf *bp)
1150 struct thread *td = curthread;
1154 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1155 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1156 KASSERT((bp->b_flags & B_BARRIER) == 0,
1157 ("Barrier request in delayed write %p", bp));
1158 BUF_ASSERT_HELD(bp);
1160 if (bp->b_flags & B_INVAL) {
1166 * If we have too many dirty buffers, don't create any more.
1167 * If we are wildly over our limit, then force a complete
1168 * cleanup. Otherwise, just keep the situation from getting
1169 * out of control. Note that we have to avoid a recursive
1170 * disaster and not try to clean up after our own cleanup!
1174 if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
1175 td->td_pflags |= TDP_INBDFLUSH;
1177 td->td_pflags &= ~TDP_INBDFLUSH;
1183 * Set B_CACHE, indicating that the buffer is fully valid. This is
1184 * true even of NFS now.
1186 bp->b_flags |= B_CACHE;
1189 * This bmap keeps the system from needing to do the bmap later,
1190 * perhaps when the system is attempting to do a sync. Since it
1191 * is likely that the indirect block -- or whatever other datastructure
1192 * that the filesystem needs is still in memory now, it is a good
1193 * thing to do this. Note also, that if the pageout daemon is
1194 * requesting a sync -- there might not be enough memory to do
1195 * the bmap then... So, this is important to do.
1197 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
1198 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
1202 * Set the *dirty* buffer range based upon the VM system dirty
1205 * Mark the buffer pages as clean. We need to do this here to
1206 * satisfy the vnode_pager and the pageout daemon, so that it
1207 * thinks that the pages have been "cleaned". Note that since
1208 * the pages are in a delayed write buffer -- the VFS layer
1209 * "will" see that the pages get written out on the next sync,
1210 * or perhaps the cluster will be completed.
1212 vfs_clean_pages_dirty_buf(bp);
1216 * Wakeup the buffer flushing daemon if we have a lot of dirty
1217 * buffers (midpoint between our recovery point and our stall
1220 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1223 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1224 * due to the softdep code.
1231 * Turn buffer into delayed write request. We must clear BIO_READ and
1232 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
1233 * itself to properly update it in the dirty/clean lists. We mark it
1234 * B_DONE to ensure that any asynchronization of the buffer properly
1235 * clears B_DONE ( else a panic will occur later ).
1237 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1238 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
1239 * should only be called if the buffer is known-good.
1241 * Since the buffer is not on a queue, we do not update the numfreebuffers
1244 * The buffer must be on QUEUE_NONE.
1247 bdirty(struct buf *bp)
1250 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
1251 bp, bp->b_vp, bp->b_flags);
1252 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1253 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1254 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1255 BUF_ASSERT_HELD(bp);
1256 bp->b_flags &= ~(B_RELBUF);
1257 bp->b_iocmd = BIO_WRITE;
1259 if ((bp->b_flags & B_DELWRI) == 0) {
1260 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
1262 atomic_add_int(&numdirtybuffers, 1);
1263 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1270 * Clear B_DELWRI for buffer.
1272 * Since the buffer is not on a queue, we do not update the numfreebuffers
1275 * The buffer must be on QUEUE_NONE.
1279 bundirty(struct buf *bp)
1282 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1283 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1284 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1285 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1286 BUF_ASSERT_HELD(bp);
1288 if (bp->b_flags & B_DELWRI) {
1289 bp->b_flags &= ~B_DELWRI;
1291 atomic_subtract_int(&numdirtybuffers, 1);
1292 numdirtywakeup(lodirtybuffers);
1295 * Since it is now being written, we can clear its deferred write flag.
1297 bp->b_flags &= ~B_DEFERRED;
1303 * Asynchronous write. Start output on a buffer, but do not wait for
1304 * it to complete. The buffer is released when the output completes.
1306 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1307 * B_INVAL buffers. Not us.
1310 bawrite(struct buf *bp)
1313 bp->b_flags |= B_ASYNC;
1320 * Asynchronous barrier write. Start output on a buffer, but do not
1321 * wait for it to complete. Place a write barrier after this write so
1322 * that this buffer and all buffers written before it are committed to
1323 * the disk before any buffers written after this write are committed
1324 * to the disk. The buffer is released when the output completes.
1327 babarrierwrite(struct buf *bp)
1330 bp->b_flags |= B_ASYNC | B_BARRIER;
1337 * Synchronous barrier write. Start output on a buffer and wait for
1338 * it to complete. Place a write barrier after this write so that
1339 * this buffer and all buffers written before it are committed to
1340 * the disk before any buffers written after this write are committed
1341 * to the disk. The buffer is released when the output completes.
1344 bbarrierwrite(struct buf *bp)
1347 bp->b_flags |= B_BARRIER;
1348 return (bwrite(bp));
1354 * Called prior to the locking of any vnodes when we are expecting to
1355 * write. We do not want to starve the buffer cache with too many
1356 * dirty buffers so we block here. By blocking prior to the locking
1357 * of any vnodes we attempt to avoid the situation where a locked vnode
1358 * prevents the various system daemons from flushing related buffers.
1365 if (numdirtybuffers >= hidirtybuffers) {
1367 while (numdirtybuffers >= hidirtybuffers) {
1369 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
1370 msleep(&needsbuffer, &nblock,
1371 (PRIBIO + 4), "flswai", 0);
1373 mtx_unlock(&nblock);
1378 * Return true if we have too many dirty buffers.
1381 buf_dirty_count_severe(void)
1384 return(numdirtybuffers >= hidirtybuffers);
1387 static __noinline int
1388 buf_vm_page_count_severe(void)
1391 KFAIL_POINT_CODE(DEBUG_FP, buf_pressure, return 1);
1393 return vm_page_count_severe();
1399 * Release a busy buffer and, if requested, free its resources. The
1400 * buffer will be stashed in the appropriate bufqueue[] allowing it
1401 * to be accessed later as a cache entity or reused for other purposes.
1404 brelse(struct buf *bp)
1406 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
1407 bp, bp->b_vp, bp->b_flags);
1408 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1409 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1411 if (BUF_LOCKRECURSED(bp)) {
1413 * Do not process, in particular, do not handle the
1414 * B_INVAL/B_RELBUF and do not release to free list.
1420 if (bp->b_flags & B_MANAGED) {
1425 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
1426 bp->b_error == EIO && !(bp->b_flags & B_INVAL)) {
1428 * Failed write, redirty. Must clear BIO_ERROR to prevent
1429 * pages from being scrapped. If the error is anything
1430 * other than an I/O error (EIO), assume that retrying
1433 bp->b_ioflags &= ~BIO_ERROR;
1435 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1436 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
1438 * Either a failed I/O or we were asked to free or not
1441 bp->b_flags |= B_INVAL;
1442 if (!LIST_EMPTY(&bp->b_dep))
1444 if (bp->b_flags & B_DELWRI) {
1445 atomic_subtract_int(&numdirtybuffers, 1);
1446 numdirtywakeup(lodirtybuffers);
1448 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1449 if ((bp->b_flags & B_VMIO) == 0) {
1458 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1459 * is called with B_DELWRI set, the underlying pages may wind up
1460 * getting freed causing a previous write (bdwrite()) to get 'lost'
1461 * because pages associated with a B_DELWRI bp are marked clean.
1463 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1464 * if B_DELWRI is set.
1466 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1467 * on pages to return pages to the VM page queues.
1469 if (bp->b_flags & B_DELWRI)
1470 bp->b_flags &= ~B_RELBUF;
1471 else if (buf_vm_page_count_severe()) {
1473 * BKGRDINPROG can only be set with the buf and bufobj
1474 * locks both held. We tolerate a race to clear it here.
1476 if (!(bp->b_vflags & BV_BKGRDINPROG))
1477 bp->b_flags |= B_RELBUF;
1481 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1482 * constituted, not even NFS buffers now. Two flags effect this. If
1483 * B_INVAL, the struct buf is invalidated but the VM object is kept
1484 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1486 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1487 * invalidated. BIO_ERROR cannot be set for a failed write unless the
1488 * buffer is also B_INVAL because it hits the re-dirtying code above.
1490 * Normally we can do this whether a buffer is B_DELWRI or not. If
1491 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1492 * the commit state and we cannot afford to lose the buffer. If the
1493 * buffer has a background write in progress, we need to keep it
1494 * around to prevent it from being reconstituted and starting a second
1497 if ((bp->b_flags & B_VMIO)
1498 && !(bp->b_vp->v_mount != NULL &&
1499 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1500 !vn_isdisk(bp->b_vp, NULL) &&
1501 (bp->b_flags & B_DELWRI))
1510 obj = bp->b_bufobj->bo_object;
1513 * Get the base offset and length of the buffer. Note that
1514 * in the VMIO case if the buffer block size is not
1515 * page-aligned then b_data pointer may not be page-aligned.
1516 * But our b_pages[] array *IS* page aligned.
1518 * block sizes less then DEV_BSIZE (usually 512) are not
1519 * supported due to the page granularity bits (m->valid,
1520 * m->dirty, etc...).
1522 * See man buf(9) for more information
1524 resid = bp->b_bufsize;
1525 foff = bp->b_offset;
1526 for (i = 0; i < bp->b_npages; i++) {
1532 * If we hit a bogus page, fixup *all* the bogus pages
1535 if (m == bogus_page) {
1536 poff = OFF_TO_IDX(bp->b_offset);
1539 VM_OBJECT_RLOCK(obj);
1540 for (j = i; j < bp->b_npages; j++) {
1542 mtmp = bp->b_pages[j];
1543 if (mtmp == bogus_page) {
1544 mtmp = vm_page_lookup(obj, poff + j);
1546 panic("brelse: page missing\n");
1548 bp->b_pages[j] = mtmp;
1551 VM_OBJECT_RUNLOCK(obj);
1553 if ((bp->b_flags & (B_INVAL | B_UNMAPPED)) == 0) {
1554 BUF_CHECK_MAPPED(bp);
1556 trunc_page((vm_offset_t)bp->b_data),
1557 bp->b_pages, bp->b_npages);
1561 if ((bp->b_flags & B_NOCACHE) ||
1562 (bp->b_ioflags & BIO_ERROR &&
1563 bp->b_iocmd == BIO_READ)) {
1564 int poffset = foff & PAGE_MASK;
1565 int presid = resid > (PAGE_SIZE - poffset) ?
1566 (PAGE_SIZE - poffset) : resid;
1568 KASSERT(presid >= 0, ("brelse: extra page"));
1569 VM_OBJECT_WLOCK(obj);
1570 vm_page_set_invalid(m, poffset, presid);
1571 VM_OBJECT_WUNLOCK(obj);
1573 printf("avoided corruption bug in bogus_page/brelse code\n");
1575 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1576 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1578 if (bp->b_flags & (B_INVAL | B_RELBUF))
1579 vfs_vmio_release(bp);
1581 } else if (bp->b_flags & B_VMIO) {
1583 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1584 vfs_vmio_release(bp);
1587 } else if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0) {
1588 if (bp->b_bufsize != 0)
1590 if (bp->b_vp != NULL)
1596 /* Handle delayed bremfree() processing. */
1597 if (bp->b_flags & B_REMFREE)
1600 if (bp->b_qindex != QUEUE_NONE)
1601 panic("brelse: free buffer onto another queue???");
1604 * If the buffer has junk contents signal it and eventually
1605 * clean up B_DELWRI and diassociate the vnode so that gbincore()
1608 if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
1609 (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
1610 bp->b_flags |= B_INVAL;
1611 if (bp->b_flags & B_INVAL) {
1612 if (bp->b_flags & B_DELWRI)
1618 /* buffers with no memory */
1619 if (bp->b_bufsize == 0) {
1620 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1621 if (bp->b_vflags & BV_BKGRDINPROG)
1622 panic("losing buffer 1");
1623 if (bp->b_kvasize) {
1624 bp->b_qindex = QUEUE_EMPTYKVA;
1626 bp->b_qindex = QUEUE_EMPTY;
1628 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1629 /* buffers with junk contents */
1630 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1631 (bp->b_ioflags & BIO_ERROR)) {
1632 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1633 if (bp->b_vflags & BV_BKGRDINPROG)
1634 panic("losing buffer 2");
1635 bp->b_qindex = QUEUE_CLEAN;
1636 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1637 /* remaining buffers */
1639 if (bp->b_flags & B_DELWRI)
1640 bp->b_qindex = QUEUE_DIRTY;
1642 bp->b_qindex = QUEUE_CLEAN;
1643 if (bp->b_flags & B_AGE) {
1644 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp,
1647 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp,
1652 bq_len[bp->b_qindex]++;
1654 mtx_unlock(&bqlock);
1657 * Fixup numfreebuffers count. The bp is on an appropriate queue
1658 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1659 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1660 * if B_INVAL is set ).
1663 if (!(bp->b_flags & B_DELWRI))
1667 * Something we can maybe free or reuse
1669 if (bp->b_bufsize || bp->b_kvasize)
1672 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1673 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1674 panic("brelse: not dirty");
1680 * Release a buffer back to the appropriate queue but do not try to free
1681 * it. The buffer is expected to be used again soon.
1683 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1684 * biodone() to requeue an async I/O on completion. It is also used when
1685 * known good buffers need to be requeued but we think we may need the data
1688 * XXX we should be able to leave the B_RELBUF hint set on completion.
1691 bqrelse(struct buf *bp)
1695 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1696 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1697 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1699 if (BUF_LOCKRECURSED(bp)) {
1700 /* do not release to free list */
1706 if (bp->b_flags & B_MANAGED) {
1707 if (bp->b_flags & B_REMFREE) {
1710 mtx_unlock(&bqlock);
1712 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1718 /* Handle delayed bremfree() processing. */
1719 if (bp->b_flags & B_REMFREE)
1722 if (bp->b_qindex != QUEUE_NONE)
1723 panic("bqrelse: free buffer onto another queue???");
1724 /* buffers with stale but valid contents */
1725 if (bp->b_flags & B_DELWRI) {
1726 bp->b_qindex = QUEUE_DIRTY;
1727 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1729 bq_len[bp->b_qindex]++;
1733 * BKGRDINPROG can only be set with the buf and bufobj
1734 * locks both held. We tolerate a race to clear it here.
1736 if (!buf_vm_page_count_severe() ||
1737 (bp->b_vflags & BV_BKGRDINPROG)) {
1738 bp->b_qindex = QUEUE_CLEAN;
1739 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp,
1742 bq_len[QUEUE_CLEAN]++;
1746 * We are too low on memory, we have to try to free
1747 * the buffer (most importantly: the wired pages
1748 * making up its backing store) *now*.
1750 mtx_unlock(&bqlock);
1755 mtx_unlock(&bqlock);
1757 if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))
1761 * Something we can maybe free or reuse.
1763 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1766 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1767 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1768 panic("bqrelse: not dirty");
1773 /* Give pages used by the bp back to the VM system (where possible) */
1775 vfs_vmio_release(struct buf *bp)
1780 if ((bp->b_flags & B_UNMAPPED) == 0) {
1781 BUF_CHECK_MAPPED(bp);
1782 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
1784 BUF_CHECK_UNMAPPED(bp);
1785 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
1786 for (i = 0; i < bp->b_npages; i++) {
1788 bp->b_pages[i] = NULL;
1790 * In order to keep page LRU ordering consistent, put
1791 * everything on the inactive queue.
1794 vm_page_unwire(m, 0);
1796 * We don't mess with busy pages, it is
1797 * the responsibility of the process that
1798 * busied the pages to deal with them.
1800 if ((m->oflags & VPO_BUSY) == 0 && m->busy == 0 &&
1801 m->wire_count == 0) {
1803 * Might as well free the page if we can and it has
1804 * no valid data. We also free the page if the
1805 * buffer was used for direct I/O
1807 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid) {
1809 } else if (bp->b_flags & B_DIRECT) {
1810 vm_page_try_to_free(m);
1811 } else if (buf_vm_page_count_severe()) {
1812 vm_page_try_to_cache(m);
1817 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
1819 if (bp->b_bufsize) {
1824 bp->b_flags &= ~B_VMIO;
1830 * Check to see if a block at a particular lbn is available for a clustered
1834 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1841 /* If the buf isn't in core skip it */
1842 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1845 /* If the buf is busy we don't want to wait for it */
1846 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1849 /* Only cluster with valid clusterable delayed write buffers */
1850 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1851 (B_DELWRI | B_CLUSTEROK))
1854 if (bpa->b_bufsize != size)
1858 * Check to see if it is in the expected place on disk and that the
1859 * block has been mapped.
1861 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1871 * Implement clustered async writes for clearing out B_DELWRI buffers.
1872 * This is much better then the old way of writing only one buffer at
1873 * a time. Note that we may not be presented with the buffers in the
1874 * correct order, so we search for the cluster in both directions.
1877 vfs_bio_awrite(struct buf *bp)
1882 daddr_t lblkno = bp->b_lblkno;
1883 struct vnode *vp = bp->b_vp;
1891 gbflags = (bp->b_flags & B_UNMAPPED) != 0 ? GB_UNMAPPED : 0;
1893 * right now we support clustered writing only to regular files. If
1894 * we find a clusterable block we could be in the middle of a cluster
1895 * rather then at the beginning.
1897 if ((vp->v_type == VREG) &&
1898 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1899 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1901 size = vp->v_mount->mnt_stat.f_iosize;
1902 maxcl = MAXPHYS / size;
1905 for (i = 1; i < maxcl; i++)
1906 if (vfs_bio_clcheck(vp, size, lblkno + i,
1907 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1910 for (j = 1; i + j <= maxcl && j <= lblkno; j++)
1911 if (vfs_bio_clcheck(vp, size, lblkno - j,
1912 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
1918 * this is a possible cluster write
1922 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl,
1928 bp->b_flags |= B_ASYNC;
1930 * default (old) behavior, writing out only one block
1932 * XXX returns b_bufsize instead of b_bcount for nwritten?
1934 nwritten = bp->b_bufsize;
1941 setbufkva(struct buf *bp, vm_offset_t addr, int maxsize, int gbflags)
1944 KASSERT((bp->b_flags & (B_UNMAPPED | B_KVAALLOC)) == 0 &&
1945 bp->b_kvasize == 0, ("call bfreekva(%p)", bp));
1946 if ((gbflags & GB_UNMAPPED) == 0) {
1947 bp->b_kvabase = (caddr_t)addr;
1948 } else if ((gbflags & GB_KVAALLOC) != 0) {
1949 KASSERT((gbflags & GB_UNMAPPED) != 0,
1950 ("GB_KVAALLOC without GB_UNMAPPED"));
1951 bp->b_kvaalloc = (caddr_t)addr;
1952 bp->b_flags |= B_UNMAPPED | B_KVAALLOC;
1953 atomic_add_long(&unmapped_bufspace, bp->b_kvasize);
1955 bp->b_kvasize = maxsize;
1959 * Allocate the buffer KVA and set b_kvasize. Also set b_kvabase if
1963 allocbufkva(struct buf *bp, int maxsize, int gbflags)
1971 vm_map_lock(buffer_map);
1972 if (vm_map_findspace(buffer_map, vm_map_min(buffer_map), maxsize,
1974 vm_map_unlock(buffer_map);
1976 * Buffer map is too fragmented. Request the caller
1977 * to defragment the map.
1979 atomic_add_int(&bufdefragcnt, 1);
1982 rv = vm_map_insert(buffer_map, NULL, 0, addr, addr + maxsize,
1983 VM_PROT_RW, VM_PROT_RW, MAP_NOFAULT);
1984 KASSERT(rv == KERN_SUCCESS, ("vm_map_insert(buffer_map) rv %d", rv));
1985 vm_map_unlock(buffer_map);
1986 setbufkva(bp, addr, maxsize, gbflags);
1987 atomic_add_long(&bufspace, bp->b_kvasize);
1992 * Ask the bufdaemon for help, or act as bufdaemon itself, when a
1993 * locked vnode is supplied.
1996 getnewbuf_bufd_help(struct vnode *vp, int gbflags, int slpflag, int slptimeo,
2001 int fl, flags, norunbuf;
2003 mtx_assert(&bqlock, MA_OWNED);
2006 flags = VFS_BIO_NEED_BUFSPACE;
2008 } else if (bufspace >= hibufspace) {
2010 flags = VFS_BIO_NEED_BUFSPACE;
2013 flags = VFS_BIO_NEED_ANY;
2016 needsbuffer |= flags;
2017 mtx_unlock(&nblock);
2018 mtx_unlock(&bqlock);
2020 bd_speedup(); /* heeeelp */
2021 if ((gbflags & GB_NOWAIT_BD) != 0)
2026 while (needsbuffer & flags) {
2027 if (vp != NULL && (td->td_pflags & TDP_BUFNEED) == 0) {
2028 mtx_unlock(&nblock);
2030 * getblk() is called with a vnode locked, and
2031 * some majority of the dirty buffers may as
2032 * well belong to the vnode. Flushing the
2033 * buffers there would make a progress that
2034 * cannot be achieved by the buf_daemon, that
2035 * cannot lock the vnode.
2037 norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
2038 (td->td_pflags & TDP_NORUNNINGBUF);
2039 /* play bufdaemon */
2040 td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
2041 fl = buf_do_flush(vp);
2042 td->td_pflags &= norunbuf;
2046 if ((needsbuffer & flags) == 0)
2049 if (msleep(&needsbuffer, &nblock, (PRIBIO + 4) | slpflag,
2053 mtx_unlock(&nblock);
2057 getnewbuf_reuse_bp(struct buf *bp, int qindex)
2060 CTR6(KTR_BUF, "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
2061 "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
2062 bp->b_kvasize, bp->b_bufsize, qindex);
2063 mtx_assert(&bqlock, MA_NOTOWNED);
2066 * Note: we no longer distinguish between VMIO and non-VMIO
2069 KASSERT((bp->b_flags & B_DELWRI) == 0,
2070 ("delwri buffer %p found in queue %d", bp, qindex));
2072 if (qindex == QUEUE_CLEAN) {
2073 if (bp->b_flags & B_VMIO) {
2074 bp->b_flags &= ~B_ASYNC;
2075 vfs_vmio_release(bp);
2077 if (bp->b_vp != NULL)
2082 * Get the rest of the buffer freed up. b_kva* is still valid
2083 * after this operation.
2086 if (bp->b_rcred != NOCRED) {
2087 crfree(bp->b_rcred);
2088 bp->b_rcred = NOCRED;
2090 if (bp->b_wcred != NOCRED) {
2091 crfree(bp->b_wcred);
2092 bp->b_wcred = NOCRED;
2094 if (!LIST_EMPTY(&bp->b_dep))
2096 if (bp->b_vflags & BV_BKGRDINPROG)
2097 panic("losing buffer 3");
2098 KASSERT(bp->b_vp == NULL, ("bp: %p still has vnode %p. qindex: %d",
2099 bp, bp->b_vp, qindex));
2100 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
2101 ("bp: %p still on a buffer list. xflags %X", bp, bp->b_xflags));
2106 bp->b_flags &= B_UNMAPPED | B_KVAALLOC;
2109 KASSERT((bp->b_flags & B_INFREECNT) == 0,
2110 ("buf %p still counted as free?", bp));
2113 bp->b_blkno = bp->b_lblkno = 0;
2114 bp->b_offset = NOOFFSET;
2120 bp->b_dirtyoff = bp->b_dirtyend = 0;
2121 bp->b_bufobj = NULL;
2122 bp->b_pin_count = 0;
2123 bp->b_fsprivate1 = NULL;
2124 bp->b_fsprivate2 = NULL;
2125 bp->b_fsprivate3 = NULL;
2127 LIST_INIT(&bp->b_dep);
2130 static int flushingbufs;
2133 getnewbuf_scan(int maxsize, int defrag, int unmapped, int metadata)
2135 struct buf *bp, *nbp;
2136 int nqindex, qindex, pass;
2138 KASSERT(!unmapped || !defrag, ("both unmapped and defrag"));
2142 atomic_add_int(&getnewbufrestarts, 1);
2145 * Setup for scan. If we do not have enough free buffers,
2146 * we setup a degenerate case that immediately fails. Note
2147 * that if we are specially marked process, we are allowed to
2148 * dip into our reserves.
2150 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
2151 * for the allocation of the mapped buffer. For unmapped, the
2152 * easiest is to start with EMPTY outright.
2154 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
2155 * However, there are a number of cases (defragging, reusing, ...)
2156 * where we cannot backup.
2160 if (!defrag && unmapped) {
2161 nqindex = QUEUE_EMPTY;
2162 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
2165 nqindex = QUEUE_EMPTYKVA;
2166 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
2170 * If no EMPTYKVA buffers and we are either defragging or
2171 * reusing, locate a CLEAN buffer to free or reuse. If
2172 * bufspace useage is low skip this step so we can allocate a
2175 if (nbp == NULL && (defrag || bufspace >= lobufspace)) {
2176 nqindex = QUEUE_CLEAN;
2177 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2181 * If we could not find or were not allowed to reuse a CLEAN
2182 * buffer, check to see if it is ok to use an EMPTY buffer.
2183 * We can only use an EMPTY buffer if allocating its KVA would
2184 * not otherwise run us out of buffer space. No KVA is needed
2185 * for the unmapped allocation.
2187 if (nbp == NULL && defrag == 0 && (bufspace + maxsize < hibufspace ||
2189 nqindex = QUEUE_EMPTY;
2190 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
2194 * All available buffers might be clean, retry ignoring the
2195 * lobufspace as the last resort.
2197 if (nbp == NULL && !TAILQ_EMPTY(&bufqueues[QUEUE_CLEAN])) {
2198 nqindex = QUEUE_CLEAN;
2199 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2203 * Run scan, possibly freeing data and/or kva mappings on the fly
2206 while ((bp = nbp) != NULL) {
2210 * Calculate next bp (we can only use it if we do not
2211 * block or do other fancy things).
2213 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
2216 nqindex = QUEUE_EMPTYKVA;
2217 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
2221 case QUEUE_EMPTYKVA:
2222 nqindex = QUEUE_CLEAN;
2223 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2228 if (metadata && pass == 1) {
2230 nqindex = QUEUE_EMPTY;
2232 &bufqueues[QUEUE_EMPTY]);
2241 * If we are defragging then we need a buffer with
2242 * b_kvasize != 0. XXX this situation should no longer
2243 * occur, if defrag is non-zero the buffer's b_kvasize
2244 * should also be non-zero at this point. XXX
2246 if (defrag && bp->b_kvasize == 0) {
2247 printf("Warning: defrag empty buffer %p\n", bp);
2252 * Start freeing the bp. This is somewhat involved. nbp
2253 * remains valid only for QUEUE_EMPTY[KVA] bp's.
2255 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2258 * BKGRDINPROG can only be set with the buf and bufobj
2259 * locks both held. We tolerate a race to clear it here.
2261 if (bp->b_vflags & BV_BKGRDINPROG) {
2266 KASSERT(bp->b_qindex == qindex,
2267 ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
2270 mtx_unlock(&bqlock);
2272 * NOTE: nbp is now entirely invalid. We can only restart
2273 * the scan from this point on.
2276 getnewbuf_reuse_bp(bp, qindex);
2277 mtx_assert(&bqlock, MA_NOTOWNED);
2280 * If we are defragging then free the buffer.
2283 bp->b_flags |= B_INVAL;
2291 * Notify any waiters for the buffer lock about
2292 * identity change by freeing the buffer.
2294 if (qindex == QUEUE_CLEAN && BUF_LOCKWAITERS(bp)) {
2295 bp->b_flags |= B_INVAL;
2305 * If we are overcomitted then recover the buffer and its
2306 * KVM space. This occurs in rare situations when multiple
2307 * processes are blocked in getnewbuf() or allocbuf().
2309 if (bufspace >= hibufspace)
2311 if (flushingbufs && bp->b_kvasize != 0) {
2312 bp->b_flags |= B_INVAL;
2317 if (bufspace < lobufspace)
2327 * Find and initialize a new buffer header, freeing up existing buffers
2328 * in the bufqueues as necessary. The new buffer is returned locked.
2330 * Important: B_INVAL is not set. If the caller wishes to throw the
2331 * buffer away, the caller must set B_INVAL prior to calling brelse().
2334 * We have insufficient buffer headers
2335 * We have insufficient buffer space
2336 * buffer_map is too fragmented ( space reservation fails )
2337 * If we have to flush dirty buffers ( but we try to avoid this )
2339 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
2340 * Instead we ask the buf daemon to do it for us. We attempt to
2341 * avoid piecemeal wakeups of the pageout daemon.
2344 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int size, int maxsize,
2348 int defrag, metadata;
2350 KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
2351 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
2352 if (!unmapped_buf_allowed)
2353 gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC);
2356 if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 ||
2362 * We can't afford to block since we might be holding a vnode lock,
2363 * which may prevent system daemons from running. We deal with
2364 * low-memory situations by proactively returning memory and running
2365 * async I/O rather then sync I/O.
2367 atomic_add_int(&getnewbufcalls, 1);
2368 atomic_subtract_int(&getnewbufrestarts, 1);
2370 bp = getnewbuf_scan(maxsize, defrag, (gbflags & (GB_UNMAPPED |
2371 GB_KVAALLOC)) == GB_UNMAPPED, metadata);
2376 * If we exhausted our list, sleep as appropriate. We may have to
2377 * wakeup various daemons and write out some dirty buffers.
2379 * Generally we are sleeping due to insufficient buffer space.
2382 mtx_assert(&bqlock, MA_OWNED);
2383 getnewbuf_bufd_help(vp, gbflags, slpflag, slptimeo, defrag);
2384 mtx_assert(&bqlock, MA_NOTOWNED);
2385 } else if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == GB_UNMAPPED) {
2386 mtx_assert(&bqlock, MA_NOTOWNED);
2389 bp->b_flags |= B_UNMAPPED;
2390 bp->b_kvabase = bp->b_data = unmapped_buf;
2391 bp->b_kvasize = maxsize;
2392 atomic_add_long(&bufspace, bp->b_kvasize);
2393 atomic_add_long(&unmapped_bufspace, bp->b_kvasize);
2394 atomic_add_int(&bufreusecnt, 1);
2396 mtx_assert(&bqlock, MA_NOTOWNED);
2399 * We finally have a valid bp. We aren't quite out of the
2400 * woods, we still have to reserve kva space. In order
2401 * to keep fragmentation sane we only allocate kva in
2404 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2406 if (maxsize != bp->b_kvasize || (bp->b_flags & (B_UNMAPPED |
2407 B_KVAALLOC)) == B_UNMAPPED) {
2408 if (allocbufkva(bp, maxsize, gbflags)) {
2410 bp->b_flags |= B_INVAL;
2414 atomic_add_int(&bufreusecnt, 1);
2415 } else if ((bp->b_flags & B_KVAALLOC) != 0 &&
2416 (gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == 0) {
2418 * If the reused buffer has KVA allocated,
2419 * reassign b_kvaalloc to b_kvabase.
2421 bp->b_kvabase = bp->b_kvaalloc;
2422 bp->b_flags &= ~B_KVAALLOC;
2423 atomic_subtract_long(&unmapped_bufspace,
2425 atomic_add_int(&bufreusecnt, 1);
2426 } else if ((bp->b_flags & (B_UNMAPPED | B_KVAALLOC)) == 0 &&
2427 (gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == (GB_UNMAPPED |
2430 * The case of reused buffer already have KVA
2431 * mapped, but the request is for unmapped
2432 * buffer with KVA allocated.
2434 bp->b_kvaalloc = bp->b_kvabase;
2435 bp->b_data = bp->b_kvabase = unmapped_buf;
2436 bp->b_flags |= B_UNMAPPED | B_KVAALLOC;
2437 atomic_add_long(&unmapped_bufspace,
2439 atomic_add_int(&bufreusecnt, 1);
2441 if ((gbflags & GB_UNMAPPED) == 0) {
2442 bp->b_saveaddr = bp->b_kvabase;
2443 bp->b_data = bp->b_saveaddr;
2444 bp->b_flags &= ~B_UNMAPPED;
2445 BUF_CHECK_MAPPED(bp);
2454 * buffer flushing daemon. Buffers are normally flushed by the
2455 * update daemon but if it cannot keep up this process starts to
2456 * take the load in an attempt to prevent getnewbuf() from blocking.
2459 static struct kproc_desc buf_kp = {
2464 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
2467 buf_do_flush(struct vnode *vp)
2471 flushed = flushbufqueues(vp, QUEUE_DIRTY, 0);
2474 * Could not find any buffers without rollback
2475 * dependencies, so just write the first one
2476 * in the hopes of eventually making progress.
2478 flushbufqueues(vp, QUEUE_DIRTY, 1);
2489 * This process needs to be suspended prior to shutdown sync.
2491 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2495 * This process is allowed to take the buffer cache to the limit
2497 curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
2501 mtx_unlock(&bdlock);
2503 kproc_suspend_check(bufdaemonproc);
2504 lodirtysave = lodirtybuffers;
2505 if (bd_speedupreq) {
2506 lodirtybuffers = numdirtybuffers / 2;
2510 * Do the flush. Limit the amount of in-transit I/O we
2511 * allow to build up, otherwise we would completely saturate
2512 * the I/O system. Wakeup any waiting processes before we
2513 * normally would so they can run in parallel with our drain.
2515 while (numdirtybuffers > lodirtybuffers) {
2516 if (buf_do_flush(NULL) == 0)
2518 kern_yield(PRI_USER);
2520 lodirtybuffers = lodirtysave;
2523 * Only clear bd_request if we have reached our low water
2524 * mark. The buf_daemon normally waits 1 second and
2525 * then incrementally flushes any dirty buffers that have
2526 * built up, within reason.
2528 * If we were unable to hit our low water mark and couldn't
2529 * find any flushable buffers, we sleep half a second.
2530 * Otherwise we loop immediately.
2533 if (numdirtybuffers <= lodirtybuffers) {
2535 * We reached our low water mark, reset the
2536 * request and sleep until we are needed again.
2537 * The sleep is just so the suspend code works.
2540 msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2543 * We couldn't find any flushable dirty buffers but
2544 * still have too many dirty buffers, we
2545 * have to sleep and try again. (rare)
2547 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2555 * Try to flush a buffer in the dirty queue. We must be careful to
2556 * free up B_INVAL buffers instead of write them, which NFS is
2557 * particularly sensitive to.
2559 static int flushwithdeps = 0;
2560 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2561 0, "Number of buffers flushed with dependecies that require rollbacks");
2564 flushbufqueues(struct vnode *lvp, int queue, int flushdeps)
2566 struct buf *sentinel;
2575 target = numdirtybuffers - lodirtybuffers;
2576 if (flushdeps && target > 2)
2579 target = flushbufqtarget;
2582 sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
2583 sentinel->b_qindex = QUEUE_SENTINEL;
2585 TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
2586 while (flushed != target) {
2587 bp = TAILQ_NEXT(sentinel, b_freelist);
2589 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2590 TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
2595 * Skip sentinels inserted by other invocations of the
2596 * flushbufqueues(), taking care to not reorder them.
2598 if (bp->b_qindex == QUEUE_SENTINEL)
2601 * Only flush the buffers that belong to the
2602 * vnode locked by the curthread.
2604 if (lvp != NULL && bp->b_vp != lvp)
2606 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2608 if (bp->b_pin_count > 0) {
2613 * BKGRDINPROG can only be set with the buf and bufobj
2614 * locks both held. We tolerate a race to clear it here.
2616 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2617 (bp->b_flags & B_DELWRI) == 0) {
2621 if (bp->b_flags & B_INVAL) {
2623 mtx_unlock(&bqlock);
2626 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2631 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
2632 if (flushdeps == 0) {
2640 * We must hold the lock on a vnode before writing
2641 * one of its buffers. Otherwise we may confuse, or
2642 * in the case of a snapshot vnode, deadlock the
2645 * The lock order here is the reverse of the normal
2646 * of vnode followed by buf lock. This is ok because
2647 * the NOWAIT will prevent deadlock.
2650 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2654 if (vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT | LK_CANRECURSE) == 0) {
2655 mtx_unlock(&bqlock);
2656 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2657 bp, bp->b_vp, bp->b_flags);
2658 if (curproc == bufdaemonproc)
2665 vn_finished_write(mp);
2667 flushwithdeps += hasdeps;
2671 * Sleeping on runningbufspace while holding
2672 * vnode lock leads to deadlock.
2674 if (curproc == bufdaemonproc)
2675 waitrunningbufspace();
2676 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2680 vn_finished_write(mp);
2683 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2684 mtx_unlock(&bqlock);
2685 free(sentinel, M_TEMP);
2690 * Check to see if a block is currently memory resident.
2693 incore(struct bufobj *bo, daddr_t blkno)
2698 bp = gbincore(bo, blkno);
2704 * Returns true if no I/O is needed to access the
2705 * associated VM object. This is like incore except
2706 * it also hunts around in the VM system for the data.
2710 inmem(struct vnode * vp, daddr_t blkno)
2713 vm_offset_t toff, tinc, size;
2717 ASSERT_VOP_LOCKED(vp, "inmem");
2719 if (incore(&vp->v_bufobj, blkno))
2721 if (vp->v_mount == NULL)
2728 if (size > vp->v_mount->mnt_stat.f_iosize)
2729 size = vp->v_mount->mnt_stat.f_iosize;
2730 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2732 VM_OBJECT_RLOCK(obj);
2733 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2734 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2738 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2739 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2740 if (vm_page_is_valid(m,
2741 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2744 VM_OBJECT_RUNLOCK(obj);
2748 VM_OBJECT_RUNLOCK(obj);
2753 * Set the dirty range for a buffer based on the status of the dirty
2754 * bits in the pages comprising the buffer. The range is limited
2755 * to the size of the buffer.
2757 * Tell the VM system that the pages associated with this buffer
2758 * are clean. This is used for delayed writes where the data is
2759 * going to go to disk eventually without additional VM intevention.
2761 * Note that while we only really need to clean through to b_bcount, we
2762 * just go ahead and clean through to b_bufsize.
2765 vfs_clean_pages_dirty_buf(struct buf *bp)
2767 vm_ooffset_t foff, noff, eoff;
2771 if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
2774 foff = bp->b_offset;
2775 KASSERT(bp->b_offset != NOOFFSET,
2776 ("vfs_clean_pages_dirty_buf: no buffer offset"));
2778 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
2779 vfs_drain_busy_pages(bp);
2780 vfs_setdirty_locked_object(bp);
2781 for (i = 0; i < bp->b_npages; i++) {
2782 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2784 if (eoff > bp->b_offset + bp->b_bufsize)
2785 eoff = bp->b_offset + bp->b_bufsize;
2787 vfs_page_set_validclean(bp, foff, m);
2788 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
2791 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
2795 vfs_setdirty_locked_object(struct buf *bp)
2800 object = bp->b_bufobj->bo_object;
2801 VM_OBJECT_ASSERT_WLOCKED(object);
2804 * We qualify the scan for modified pages on whether the
2805 * object has been flushed yet.
2807 if ((object->flags & OBJ_MIGHTBEDIRTY) != 0) {
2808 vm_offset_t boffset;
2809 vm_offset_t eoffset;
2812 * test the pages to see if they have been modified directly
2813 * by users through the VM system.
2815 for (i = 0; i < bp->b_npages; i++)
2816 vm_page_test_dirty(bp->b_pages[i]);
2819 * Calculate the encompassing dirty range, boffset and eoffset,
2820 * (eoffset - boffset) bytes.
2823 for (i = 0; i < bp->b_npages; i++) {
2824 if (bp->b_pages[i]->dirty)
2827 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2829 for (i = bp->b_npages - 1; i >= 0; --i) {
2830 if (bp->b_pages[i]->dirty) {
2834 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2837 * Fit it to the buffer.
2840 if (eoffset > bp->b_bcount)
2841 eoffset = bp->b_bcount;
2844 * If we have a good dirty range, merge with the existing
2848 if (boffset < eoffset) {
2849 if (bp->b_dirtyoff > boffset)
2850 bp->b_dirtyoff = boffset;
2851 if (bp->b_dirtyend < eoffset)
2852 bp->b_dirtyend = eoffset;
2858 * Allocate the KVA mapping for an existing buffer. It handles the
2859 * cases of both B_UNMAPPED buffer, and buffer with the preallocated
2860 * KVA which is not mapped (B_KVAALLOC).
2863 bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags)
2865 struct buf *scratch_bp;
2866 int bsize, maxsize, need_mapping, need_kva;
2869 need_mapping = (bp->b_flags & B_UNMAPPED) != 0 &&
2870 (gbflags & GB_UNMAPPED) == 0;
2871 need_kva = (bp->b_flags & (B_KVAALLOC | B_UNMAPPED)) == B_UNMAPPED &&
2872 (gbflags & GB_KVAALLOC) != 0;
2873 if (!need_mapping && !need_kva)
2876 BUF_CHECK_UNMAPPED(bp);
2878 if (need_mapping && (bp->b_flags & B_KVAALLOC) != 0) {
2880 * Buffer is not mapped, but the KVA was already
2881 * reserved at the time of the instantiation. Use the
2884 bp->b_flags &= ~B_KVAALLOC;
2885 KASSERT(bp->b_kvaalloc != 0, ("kvaalloc == 0"));
2886 bp->b_kvabase = bp->b_kvaalloc;
2887 atomic_subtract_long(&unmapped_bufspace, bp->b_kvasize);
2892 * Calculate the amount of the address space we would reserve
2893 * if the buffer was mapped.
2895 bsize = vn_isdisk(bp->b_vp, NULL) ? DEV_BSIZE : bp->b_bufobj->bo_bsize;
2896 offset = blkno * bsize;
2897 maxsize = size + (offset & PAGE_MASK);
2898 maxsize = imax(maxsize, bsize);
2901 if (allocbufkva(bp, maxsize, gbflags)) {
2903 * Request defragmentation. getnewbuf() returns us the
2904 * allocated space by the scratch buffer KVA.
2906 scratch_bp = getnewbuf(bp->b_vp, 0, 0, size, maxsize, gbflags |
2907 (GB_UNMAPPED | GB_KVAALLOC));
2908 if (scratch_bp == NULL) {
2909 if ((gbflags & GB_NOWAIT_BD) != 0) {
2911 * XXXKIB: defragmentation cannot
2912 * succeed, not sure what else to do.
2914 panic("GB_NOWAIT_BD and B_UNMAPPED %p", bp);
2916 atomic_add_int(&mappingrestarts, 1);
2919 KASSERT((scratch_bp->b_flags & B_KVAALLOC) != 0,
2920 ("scratch bp !B_KVAALLOC %p", scratch_bp));
2921 setbufkva(bp, (vm_offset_t)scratch_bp->b_kvaalloc,
2922 scratch_bp->b_kvasize, gbflags);
2924 /* Get rid of the scratch buffer. */
2925 scratch_bp->b_kvasize = 0;
2926 scratch_bp->b_flags |= B_INVAL;
2927 scratch_bp->b_flags &= ~(B_UNMAPPED | B_KVAALLOC);
2934 bp->b_saveaddr = bp->b_kvabase;
2935 bp->b_data = bp->b_saveaddr; /* b_offset is handled by bpmap_qenter */
2936 bp->b_flags &= ~B_UNMAPPED;
2937 BUF_CHECK_MAPPED(bp);
2944 * Get a block given a specified block and offset into a file/device.
2945 * The buffers B_DONE bit will be cleared on return, making it almost
2946 * ready for an I/O initiation. B_INVAL may or may not be set on
2947 * return. The caller should clear B_INVAL prior to initiating a
2950 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2951 * an existing buffer.
2953 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2954 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2955 * and then cleared based on the backing VM. If the previous buffer is
2956 * non-0-sized but invalid, B_CACHE will be cleared.
2958 * If getblk() must create a new buffer, the new buffer is returned with
2959 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2960 * case it is returned with B_INVAL clear and B_CACHE set based on the
2963 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
2964 * B_CACHE bit is clear.
2966 * What this means, basically, is that the caller should use B_CACHE to
2967 * determine whether the buffer is fully valid or not and should clear
2968 * B_INVAL prior to issuing a read. If the caller intends to validate
2969 * the buffer by loading its data area with something, the caller needs
2970 * to clear B_INVAL. If the caller does this without issuing an I/O,
2971 * the caller should set B_CACHE ( as an optimization ), else the caller
2972 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2973 * a write attempt or if it was a successfull read. If the caller
2974 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
2975 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2978 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo,
2983 int bsize, error, maxsize, vmio;
2986 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
2987 KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
2988 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
2989 ASSERT_VOP_LOCKED(vp, "getblk");
2990 if (size > MAXBSIZE)
2991 panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2992 if (!unmapped_buf_allowed)
2993 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
2998 * Block if we are low on buffers. Certain processes are allowed
2999 * to completely exhaust the buffer cache.
3001 * If this check ever becomes a bottleneck it may be better to
3002 * move it into the else, when gbincore() fails. At the moment
3003 * it isn't a problem.
3005 if (numfreebuffers == 0) {
3006 if (TD_IS_IDLETHREAD(curthread))
3009 needsbuffer |= VFS_BIO_NEED_ANY;
3010 mtx_unlock(&nblock);
3014 bp = gbincore(bo, blkno);
3018 * Buffer is in-core. If the buffer is not busy nor managed,
3019 * it must be on a queue.
3021 lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
3023 if (flags & GB_LOCK_NOWAIT)
3024 lockflags |= LK_NOWAIT;
3026 error = BUF_TIMELOCK(bp, lockflags,
3027 BO_LOCKPTR(bo), "getblk", slpflag, slptimeo);
3030 * If we slept and got the lock we have to restart in case
3031 * the buffer changed identities.
3033 if (error == ENOLCK)
3035 /* We timed out or were interrupted. */
3038 /* If recursed, assume caller knows the rules. */
3039 else if (BUF_LOCKRECURSED(bp))
3043 * The buffer is locked. B_CACHE is cleared if the buffer is
3044 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
3045 * and for a VMIO buffer B_CACHE is adjusted according to the
3048 if (bp->b_flags & B_INVAL)
3049 bp->b_flags &= ~B_CACHE;
3050 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
3051 bp->b_flags |= B_CACHE;
3052 if (bp->b_flags & B_MANAGED)
3053 MPASS(bp->b_qindex == QUEUE_NONE);
3058 * check for size inconsistencies for non-VMIO case.
3060 if (bp->b_bcount != size) {
3061 if ((bp->b_flags & B_VMIO) == 0 ||
3062 (size > bp->b_kvasize)) {
3063 if (bp->b_flags & B_DELWRI) {
3065 * If buffer is pinned and caller does
3066 * not want sleep waiting for it to be
3067 * unpinned, bail out
3069 if (bp->b_pin_count > 0) {
3070 if (flags & GB_LOCK_NOWAIT) {
3077 bp->b_flags |= B_NOCACHE;
3080 if (LIST_EMPTY(&bp->b_dep)) {
3081 bp->b_flags |= B_RELBUF;
3084 bp->b_flags |= B_NOCACHE;
3093 * Handle the case of unmapped buffer which should
3094 * become mapped, or the buffer for which KVA
3095 * reservation is requested.
3097 bp_unmapped_get_kva(bp, blkno, size, flags);
3100 * If the size is inconsistant in the VMIO case, we can resize
3101 * the buffer. This might lead to B_CACHE getting set or
3102 * cleared. If the size has not changed, B_CACHE remains
3103 * unchanged from its previous state.
3105 if (bp->b_bcount != size)
3108 KASSERT(bp->b_offset != NOOFFSET,
3109 ("getblk: no buffer offset"));
3112 * A buffer with B_DELWRI set and B_CACHE clear must
3113 * be committed before we can return the buffer in
3114 * order to prevent the caller from issuing a read
3115 * ( due to B_CACHE not being set ) and overwriting
3118 * Most callers, including NFS and FFS, need this to
3119 * operate properly either because they assume they
3120 * can issue a read if B_CACHE is not set, or because
3121 * ( for example ) an uncached B_DELWRI might loop due
3122 * to softupdates re-dirtying the buffer. In the latter
3123 * case, B_CACHE is set after the first write completes,
3124 * preventing further loops.
3125 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
3126 * above while extending the buffer, we cannot allow the
3127 * buffer to remain with B_CACHE set after the write
3128 * completes or it will represent a corrupt state. To
3129 * deal with this we set B_NOCACHE to scrap the buffer
3132 * We might be able to do something fancy, like setting
3133 * B_CACHE in bwrite() except if B_DELWRI is already set,
3134 * so the below call doesn't set B_CACHE, but that gets real
3135 * confusing. This is much easier.
3138 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
3139 bp->b_flags |= B_NOCACHE;
3143 bp->b_flags &= ~B_DONE;
3146 * Buffer is not in-core, create new buffer. The buffer
3147 * returned by getnewbuf() is locked. Note that the returned
3148 * buffer is also considered valid (not marked B_INVAL).
3152 * If the user does not want us to create the buffer, bail out
3155 if (flags & GB_NOCREAT)
3157 bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
3158 offset = blkno * bsize;
3159 vmio = vp->v_object != NULL;
3161 maxsize = size + (offset & PAGE_MASK);
3164 /* Do not allow non-VMIO notmapped buffers. */
3165 flags &= ~GB_UNMAPPED;
3167 maxsize = imax(maxsize, bsize);
3169 bp = getnewbuf(vp, slpflag, slptimeo, size, maxsize, flags);
3171 if (slpflag || slptimeo)
3177 * This code is used to make sure that a buffer is not
3178 * created while the getnewbuf routine is blocked.
3179 * This can be a problem whether the vnode is locked or not.
3180 * If the buffer is created out from under us, we have to
3181 * throw away the one we just created.
3183 * Note: this must occur before we associate the buffer
3184 * with the vp especially considering limitations in
3185 * the splay tree implementation when dealing with duplicate
3189 if (gbincore(bo, blkno)) {
3191 bp->b_flags |= B_INVAL;
3197 * Insert the buffer into the hash, so that it can
3198 * be found by incore.
3200 bp->b_blkno = bp->b_lblkno = blkno;
3201 bp->b_offset = offset;
3206 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
3207 * buffer size starts out as 0, B_CACHE will be set by
3208 * allocbuf() for the VMIO case prior to it testing the
3209 * backing store for validity.
3213 bp->b_flags |= B_VMIO;
3214 KASSERT(vp->v_object == bp->b_bufobj->bo_object,
3215 ("ARGH! different b_bufobj->bo_object %p %p %p\n",
3216 bp, vp->v_object, bp->b_bufobj->bo_object));
3218 bp->b_flags &= ~B_VMIO;
3219 KASSERT(bp->b_bufobj->bo_object == NULL,
3220 ("ARGH! has b_bufobj->bo_object %p %p\n",
3221 bp, bp->b_bufobj->bo_object));
3222 BUF_CHECK_MAPPED(bp);
3226 bp->b_flags &= ~B_DONE;
3228 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
3229 BUF_ASSERT_HELD(bp);
3231 KASSERT(bp->b_bufobj == bo,
3232 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3237 * Get an empty, disassociated buffer of given size. The buffer is initially
3241 geteblk(int size, int flags)
3246 maxsize = (size + BKVAMASK) & ~BKVAMASK;
3247 while ((bp = getnewbuf(NULL, 0, 0, size, maxsize, flags)) == NULL) {
3248 if ((flags & GB_NOWAIT_BD) &&
3249 (curthread->td_pflags & TDP_BUFNEED) != 0)
3253 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
3254 BUF_ASSERT_HELD(bp);
3260 * This code constitutes the buffer memory from either anonymous system
3261 * memory (in the case of non-VMIO operations) or from an associated
3262 * VM object (in the case of VMIO operations). This code is able to
3263 * resize a buffer up or down.
3265 * Note that this code is tricky, and has many complications to resolve
3266 * deadlock or inconsistant data situations. Tread lightly!!!
3267 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3268 * the caller. Calling this code willy nilly can result in the loss of data.
3270 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
3271 * B_CACHE for the non-VMIO case.
3275 allocbuf(struct buf *bp, int size)
3277 int newbsize, mbsize;
3280 BUF_ASSERT_HELD(bp);
3282 if (bp->b_kvasize < size)
3283 panic("allocbuf: buffer too small");
3285 if ((bp->b_flags & B_VMIO) == 0) {
3289 * Just get anonymous memory from the kernel. Don't
3290 * mess with B_CACHE.
3292 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3293 if (bp->b_flags & B_MALLOC)
3296 newbsize = round_page(size);
3298 if (newbsize < bp->b_bufsize) {
3300 * malloced buffers are not shrunk
3302 if (bp->b_flags & B_MALLOC) {
3304 bp->b_bcount = size;
3306 free(bp->b_data, M_BIOBUF);
3307 if (bp->b_bufsize) {
3308 atomic_subtract_long(
3314 bp->b_saveaddr = bp->b_kvabase;
3315 bp->b_data = bp->b_saveaddr;
3317 bp->b_flags &= ~B_MALLOC;
3321 vm_hold_free_pages(bp, newbsize);
3322 } else if (newbsize > bp->b_bufsize) {
3324 * We only use malloced memory on the first allocation.
3325 * and revert to page-allocated memory when the buffer
3329 * There is a potential smp race here that could lead
3330 * to bufmallocspace slightly passing the max. It
3331 * is probably extremely rare and not worth worrying
3334 if ( (bufmallocspace < maxbufmallocspace) &&
3335 (bp->b_bufsize == 0) &&
3336 (mbsize <= PAGE_SIZE/2)) {
3338 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
3339 bp->b_bufsize = mbsize;
3340 bp->b_bcount = size;
3341 bp->b_flags |= B_MALLOC;
3342 atomic_add_long(&bufmallocspace, mbsize);
3348 * If the buffer is growing on its other-than-first allocation,
3349 * then we revert to the page-allocation scheme.
3351 if (bp->b_flags & B_MALLOC) {
3352 origbuf = bp->b_data;
3353 origbufsize = bp->b_bufsize;
3354 bp->b_data = bp->b_kvabase;
3355 if (bp->b_bufsize) {
3356 atomic_subtract_long(&bufmallocspace,
3361 bp->b_flags &= ~B_MALLOC;
3362 newbsize = round_page(newbsize);
3366 (vm_offset_t) bp->b_data + bp->b_bufsize,
3367 (vm_offset_t) bp->b_data + newbsize);
3369 bcopy(origbuf, bp->b_data, origbufsize);
3370 free(origbuf, M_BIOBUF);
3376 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3377 desiredpages = (size == 0) ? 0 :
3378 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
3380 if (bp->b_flags & B_MALLOC)
3381 panic("allocbuf: VMIO buffer can't be malloced");
3383 * Set B_CACHE initially if buffer is 0 length or will become
3386 if (size == 0 || bp->b_bufsize == 0)
3387 bp->b_flags |= B_CACHE;
3389 if (newbsize < bp->b_bufsize) {
3391 * DEV_BSIZE aligned new buffer size is less then the
3392 * DEV_BSIZE aligned existing buffer size. Figure out
3393 * if we have to remove any pages.
3395 if (desiredpages < bp->b_npages) {
3398 if ((bp->b_flags & B_UNMAPPED) == 0) {
3399 BUF_CHECK_MAPPED(bp);
3400 pmap_qremove((vm_offset_t)trunc_page(
3401 (vm_offset_t)bp->b_data) +
3402 (desiredpages << PAGE_SHIFT),
3403 (bp->b_npages - desiredpages));
3405 BUF_CHECK_UNMAPPED(bp);
3406 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
3407 for (i = desiredpages; i < bp->b_npages; i++) {
3409 * the page is not freed here -- it
3410 * is the responsibility of
3411 * vnode_pager_setsize
3414 KASSERT(m != bogus_page,
3415 ("allocbuf: bogus page found"));
3416 while (vm_page_sleep_if_busy(m, TRUE,
3420 bp->b_pages[i] = NULL;
3422 vm_page_unwire(m, 0);
3425 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
3426 bp->b_npages = desiredpages;
3428 } else if (size > bp->b_bcount) {
3430 * We are growing the buffer, possibly in a
3431 * byte-granular fashion.
3438 * Step 1, bring in the VM pages from the object,
3439 * allocating them if necessary. We must clear
3440 * B_CACHE if these pages are not valid for the
3441 * range covered by the buffer.
3444 obj = bp->b_bufobj->bo_object;
3446 VM_OBJECT_WLOCK(obj);
3447 while (bp->b_npages < desiredpages) {
3451 * We must allocate system pages since blocking
3452 * here could interfere with paging I/O, no
3453 * matter which process we are.
3455 * We can only test VPO_BUSY here. Blocking on
3456 * m->busy might lead to a deadlock:
3457 * vm_fault->getpages->cluster_read->allocbuf
3458 * Thus, we specify VM_ALLOC_IGN_SBUSY.
3460 m = vm_page_grab(obj, OFF_TO_IDX(bp->b_offset) +
3461 bp->b_npages, VM_ALLOC_NOBUSY |
3462 VM_ALLOC_SYSTEM | VM_ALLOC_WIRED |
3463 VM_ALLOC_RETRY | VM_ALLOC_IGN_SBUSY |
3464 VM_ALLOC_COUNT(desiredpages - bp->b_npages));
3466 bp->b_flags &= ~B_CACHE;
3467 bp->b_pages[bp->b_npages] = m;
3472 * Step 2. We've loaded the pages into the buffer,
3473 * we have to figure out if we can still have B_CACHE
3474 * set. Note that B_CACHE is set according to the
3475 * byte-granular range ( bcount and size ), new the
3476 * aligned range ( newbsize ).
3478 * The VM test is against m->valid, which is DEV_BSIZE
3479 * aligned. Needless to say, the validity of the data
3480 * needs to also be DEV_BSIZE aligned. Note that this
3481 * fails with NFS if the server or some other client
3482 * extends the file's EOF. If our buffer is resized,
3483 * B_CACHE may remain set! XXX
3486 toff = bp->b_bcount;
3487 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
3489 while ((bp->b_flags & B_CACHE) && toff < size) {
3492 if (tinc > (size - toff))
3495 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
3508 VM_OBJECT_WUNLOCK(obj);
3511 * Step 3, fixup the KVM pmap.
3513 if ((bp->b_flags & B_UNMAPPED) == 0)
3516 BUF_CHECK_UNMAPPED(bp);
3519 if (newbsize < bp->b_bufsize)
3521 bp->b_bufsize = newbsize; /* actual buffer allocation */
3522 bp->b_bcount = size; /* requested buffer size */
3526 extern int inflight_transient_maps;
3529 biodone(struct bio *bp)
3532 void (*done)(struct bio *);
3533 vm_offset_t start, end;
3536 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3538 bp->bio_flags |= BIO_DONE;
3539 if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) {
3540 start = trunc_page((vm_offset_t)bp->bio_data);
3541 end = round_page((vm_offset_t)bp->bio_data + bp->bio_length);
3547 done = bp->bio_done;
3554 pmap_qremove(start, OFF_TO_IDX(end - start));
3555 vm_map_remove(bio_transient_map, start, end);
3556 atomic_add_int(&inflight_transient_maps, -1);
3561 * Wait for a BIO to finish.
3563 * XXX: resort to a timeout for now. The optimal locking (if any) for this
3564 * case is not yet clear.
3567 biowait(struct bio *bp, const char *wchan)
3571 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3573 while ((bp->bio_flags & BIO_DONE) == 0)
3574 msleep(bp, mtxp, PRIBIO, wchan, hz / 10);
3576 if (bp->bio_error != 0)
3577 return (bp->bio_error);
3578 if (!(bp->bio_flags & BIO_ERROR))
3584 biofinish(struct bio *bp, struct devstat *stat, int error)
3588 bp->bio_error = error;
3589 bp->bio_flags |= BIO_ERROR;
3592 devstat_end_transaction_bio(stat, bp);
3599 * Wait for buffer I/O completion, returning error status. The buffer
3600 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR
3601 * error and cleared.
3604 bufwait(struct buf *bp)
3606 if (bp->b_iocmd == BIO_READ)
3607 bwait(bp, PRIBIO, "biord");
3609 bwait(bp, PRIBIO, "biowr");
3610 if (bp->b_flags & B_EINTR) {
3611 bp->b_flags &= ~B_EINTR;
3614 if (bp->b_ioflags & BIO_ERROR) {
3615 return (bp->b_error ? bp->b_error : EIO);
3622 * Call back function from struct bio back up to struct buf.
3625 bufdonebio(struct bio *bip)
3629 bp = bip->bio_caller2;
3630 bp->b_resid = bp->b_bcount - bip->bio_completed;
3631 bp->b_resid = bip->bio_resid; /* XXX: remove */
3632 bp->b_ioflags = bip->bio_flags;
3633 bp->b_error = bip->bio_error;
3635 bp->b_ioflags |= BIO_ERROR;
3641 dev_strategy(struct cdev *dev, struct buf *bp)
3646 KASSERT(dev->si_refcount > 0,
3647 ("dev_strategy on un-referenced struct cdev *(%s) %p",
3648 devtoname(dev), dev));
3650 csw = dev_refthread(dev, &ref);
3651 dev_strategy_csw(dev, csw, bp);
3652 dev_relthread(dev, ref);
3656 dev_strategy_csw(struct cdev *dev, struct cdevsw *csw, struct buf *bp)
3660 KASSERT(bp->b_iocmd == BIO_READ || bp->b_iocmd == BIO_WRITE,
3662 KASSERT(((dev->si_flags & SI_ETERNAL) != 0 && csw != NULL) ||
3663 dev->si_threadcount > 0,
3664 ("dev_strategy_csw threadcount cdev *(%s) %p", devtoname(dev),
3667 bp->b_error = ENXIO;
3668 bp->b_ioflags = BIO_ERROR;
3676 /* Try again later */
3677 tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3679 bip->bio_cmd = bp->b_iocmd;
3680 bip->bio_offset = bp->b_iooffset;
3681 bip->bio_length = bp->b_bcount;
3682 bip->bio_bcount = bp->b_bcount; /* XXX: remove */
3684 bip->bio_done = bufdonebio;
3685 bip->bio_caller2 = bp;
3687 (*csw->d_strategy)(bip);
3693 * Finish I/O on a buffer, optionally calling a completion function.
3694 * This is usually called from an interrupt so process blocking is
3697 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3698 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3699 * assuming B_INVAL is clear.
3701 * For the VMIO case, we set B_CACHE if the op was a read and no
3702 * read error occured, or if the op was a write. B_CACHE is never
3703 * set if the buffer is invalid or otherwise uncacheable.
3705 * biodone does not mess with B_INVAL, allowing the I/O routine or the
3706 * initiator to leave B_INVAL set to brelse the buffer out of existance
3707 * in the biodone routine.
3710 bufdone(struct buf *bp)
3712 struct bufobj *dropobj;
3713 void (*biodone)(struct buf *);
3715 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3718 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3719 BUF_ASSERT_HELD(bp);
3721 runningbufwakeup(bp);
3722 if (bp->b_iocmd == BIO_WRITE)
3723 dropobj = bp->b_bufobj;
3724 /* call optional completion function if requested */
3725 if (bp->b_iodone != NULL) {
3726 biodone = bp->b_iodone;
3727 bp->b_iodone = NULL;
3730 bufobj_wdrop(dropobj);
3737 bufobj_wdrop(dropobj);
3741 bufdone_finish(struct buf *bp)
3743 BUF_ASSERT_HELD(bp);
3745 if (!LIST_EMPTY(&bp->b_dep))
3748 if (bp->b_flags & B_VMIO) {
3753 int bogus, i, iosize;
3755 obj = bp->b_bufobj->bo_object;
3756 KASSERT(obj->paging_in_progress >= bp->b_npages,
3757 ("biodone_finish: paging in progress(%d) < b_npages(%d)",
3758 obj->paging_in_progress, bp->b_npages));
3761 KASSERT(vp->v_holdcnt > 0,
3762 ("biodone_finish: vnode %p has zero hold count", vp));
3763 KASSERT(vp->v_object != NULL,
3764 ("biodone_finish: vnode %p has no vm_object", vp));
3766 foff = bp->b_offset;
3767 KASSERT(bp->b_offset != NOOFFSET,
3768 ("biodone_finish: bp %p has no buffer offset", bp));
3771 * Set B_CACHE if the op was a normal read and no error
3772 * occured. B_CACHE is set for writes in the b*write()
3775 iosize = bp->b_bcount - bp->b_resid;
3776 if (bp->b_iocmd == BIO_READ &&
3777 !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3778 !(bp->b_ioflags & BIO_ERROR)) {
3779 bp->b_flags |= B_CACHE;
3782 VM_OBJECT_WLOCK(obj);
3783 for (i = 0; i < bp->b_npages; i++) {
3787 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3792 * cleanup bogus pages, restoring the originals
3795 if (m == bogus_page) {
3796 bogus = bogusflag = 1;
3797 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3799 panic("biodone: page disappeared!");
3802 KASSERT(OFF_TO_IDX(foff) == m->pindex,
3803 ("biodone_finish: foff(%jd)/pindex(%ju) mismatch",
3804 (intmax_t)foff, (uintmax_t)m->pindex));
3807 * In the write case, the valid and clean bits are
3808 * already changed correctly ( see bdwrite() ), so we
3809 * only need to do this here in the read case.
3811 if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3812 KASSERT((m->dirty & vm_page_bits(foff &
3813 PAGE_MASK, resid)) == 0, ("bufdone_finish:"
3814 " page %p has unexpected dirty bits", m));
3815 vfs_page_set_valid(bp, foff, m);
3818 vm_page_io_finish(m);
3819 vm_object_pip_subtract(obj, 1);
3820 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3823 vm_object_pip_wakeupn(obj, 0);
3824 VM_OBJECT_WUNLOCK(obj);
3825 if (bogus && (bp->b_flags & B_UNMAPPED) == 0) {
3826 BUF_CHECK_MAPPED(bp);
3827 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3828 bp->b_pages, bp->b_npages);
3833 * For asynchronous completions, release the buffer now. The brelse
3834 * will do a wakeup there if necessary - so no need to do a wakeup
3835 * here in the async case. The sync case always needs to do a wakeup.
3838 if (bp->b_flags & B_ASYNC) {
3839 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3848 * This routine is called in lieu of iodone in the case of
3849 * incomplete I/O. This keeps the busy status for pages
3853 vfs_unbusy_pages(struct buf *bp)
3859 runningbufwakeup(bp);
3860 if (!(bp->b_flags & B_VMIO))
3863 obj = bp->b_bufobj->bo_object;
3864 VM_OBJECT_WLOCK(obj);
3865 for (i = 0; i < bp->b_npages; i++) {
3867 if (m == bogus_page) {
3868 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3870 panic("vfs_unbusy_pages: page missing\n");
3872 if ((bp->b_flags & B_UNMAPPED) == 0) {
3873 BUF_CHECK_MAPPED(bp);
3874 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3875 bp->b_pages, bp->b_npages);
3877 BUF_CHECK_UNMAPPED(bp);
3879 vm_object_pip_subtract(obj, 1);
3880 vm_page_io_finish(m);
3882 vm_object_pip_wakeupn(obj, 0);
3883 VM_OBJECT_WUNLOCK(obj);
3887 * vfs_page_set_valid:
3889 * Set the valid bits in a page based on the supplied offset. The
3890 * range is restricted to the buffer's size.
3892 * This routine is typically called after a read completes.
3895 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3900 * Compute the end offset, eoff, such that [off, eoff) does not span a
3901 * page boundary and eoff is not greater than the end of the buffer.
3902 * The end of the buffer, in this case, is our file EOF, not the
3903 * allocation size of the buffer.
3905 eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
3906 if (eoff > bp->b_offset + bp->b_bcount)
3907 eoff = bp->b_offset + bp->b_bcount;
3910 * Set valid range. This is typically the entire buffer and thus the
3914 vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off);
3918 * vfs_page_set_validclean:
3920 * Set the valid bits and clear the dirty bits in a page based on the
3921 * supplied offset. The range is restricted to the buffer's size.
3924 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3926 vm_ooffset_t soff, eoff;
3929 * Start and end offsets in buffer. eoff - soff may not cross a
3930 * page boundry or cross the end of the buffer. The end of the
3931 * buffer, in this case, is our file EOF, not the allocation size
3935 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3936 if (eoff > bp->b_offset + bp->b_bcount)
3937 eoff = bp->b_offset + bp->b_bcount;
3940 * Set valid range. This is typically the entire buffer and thus the
3944 vm_page_set_validclean(
3946 (vm_offset_t) (soff & PAGE_MASK),
3947 (vm_offset_t) (eoff - soff)
3953 * Ensure that all buffer pages are not busied by VPO_BUSY flag. If
3954 * any page is busy, drain the flag.
3957 vfs_drain_busy_pages(struct buf *bp)
3962 VM_OBJECT_ASSERT_WLOCKED(bp->b_bufobj->bo_object);
3964 for (i = 0; i < bp->b_npages; i++) {
3966 if ((m->oflags & VPO_BUSY) != 0) {
3967 for (; last_busied < i; last_busied++)
3968 vm_page_busy(bp->b_pages[last_busied]);
3969 while ((m->oflags & VPO_BUSY) != 0)
3970 vm_page_sleep(m, "vbpage");
3973 for (i = 0; i < last_busied; i++)
3974 vm_page_wakeup(bp->b_pages[i]);
3978 * This routine is called before a device strategy routine.
3979 * It is used to tell the VM system that paging I/O is in
3980 * progress, and treat the pages associated with the buffer
3981 * almost as being VPO_BUSY. Also the object paging_in_progress
3982 * flag is handled to make sure that the object doesn't become
3985 * Since I/O has not been initiated yet, certain buffer flags
3986 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
3987 * and should be ignored.
3990 vfs_busy_pages(struct buf *bp, int clear_modify)
3997 if (!(bp->b_flags & B_VMIO))
4000 obj = bp->b_bufobj->bo_object;
4001 foff = bp->b_offset;
4002 KASSERT(bp->b_offset != NOOFFSET,
4003 ("vfs_busy_pages: no buffer offset"));
4004 VM_OBJECT_WLOCK(obj);
4005 vfs_drain_busy_pages(bp);
4006 if (bp->b_bufsize != 0)
4007 vfs_setdirty_locked_object(bp);
4009 for (i = 0; i < bp->b_npages; i++) {
4012 if ((bp->b_flags & B_CLUSTER) == 0) {
4013 vm_object_pip_add(obj, 1);
4014 vm_page_io_start(m);
4017 * When readying a buffer for a read ( i.e
4018 * clear_modify == 0 ), it is important to do
4019 * bogus_page replacement for valid pages in
4020 * partially instantiated buffers. Partially
4021 * instantiated buffers can, in turn, occur when
4022 * reconstituting a buffer from its VM backing store
4023 * base. We only have to do this if B_CACHE is
4024 * clear ( which causes the I/O to occur in the
4025 * first place ). The replacement prevents the read
4026 * I/O from overwriting potentially dirty VM-backed
4027 * pages. XXX bogus page replacement is, uh, bogus.
4028 * It may not work properly with small-block devices.
4029 * We need to find a better way.
4032 pmap_remove_write(m);
4033 vfs_page_set_validclean(bp, foff, m);
4034 } else if (m->valid == VM_PAGE_BITS_ALL &&
4035 (bp->b_flags & B_CACHE) == 0) {
4036 bp->b_pages[i] = bogus_page;
4039 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4041 VM_OBJECT_WUNLOCK(obj);
4042 if (bogus && (bp->b_flags & B_UNMAPPED) == 0) {
4043 BUF_CHECK_MAPPED(bp);
4044 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4045 bp->b_pages, bp->b_npages);
4050 * vfs_bio_set_valid:
4052 * Set the range within the buffer to valid. The range is
4053 * relative to the beginning of the buffer, b_offset. Note that
4054 * b_offset itself may be offset from the beginning of the first
4058 vfs_bio_set_valid(struct buf *bp, int base, int size)
4063 if (!(bp->b_flags & B_VMIO))
4067 * Fixup base to be relative to beginning of first page.
4068 * Set initial n to be the maximum number of bytes in the
4069 * first page that can be validated.
4071 base += (bp->b_offset & PAGE_MASK);
4072 n = PAGE_SIZE - (base & PAGE_MASK);
4074 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4075 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4079 vm_page_set_valid_range(m, base & PAGE_MASK, n);
4084 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4090 * If the specified buffer is a non-VMIO buffer, clear the entire
4091 * buffer. If the specified buffer is a VMIO buffer, clear and
4092 * validate only the previously invalid portions of the buffer.
4093 * This routine essentially fakes an I/O, so we need to clear
4094 * BIO_ERROR and B_INVAL.
4096 * Note that while we only theoretically need to clear through b_bcount,
4097 * we go ahead and clear through b_bufsize.
4100 vfs_bio_clrbuf(struct buf *bp)
4102 int i, j, mask, sa, ea, slide;
4104 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
4108 bp->b_flags &= ~B_INVAL;
4109 bp->b_ioflags &= ~BIO_ERROR;
4110 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4111 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4112 (bp->b_offset & PAGE_MASK) == 0) {
4113 if (bp->b_pages[0] == bogus_page)
4115 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4116 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[0]->object);
4117 if ((bp->b_pages[0]->valid & mask) == mask)
4119 if ((bp->b_pages[0]->valid & mask) == 0) {
4120 pmap_zero_page_area(bp->b_pages[0], 0, bp->b_bufsize);
4121 bp->b_pages[0]->valid |= mask;
4125 sa = bp->b_offset & PAGE_MASK;
4127 for (i = 0; i < bp->b_npages; i++, sa = 0) {
4128 slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize);
4129 ea = slide & PAGE_MASK;
4132 if (bp->b_pages[i] == bogus_page)
4135 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4136 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[i]->object);
4137 if ((bp->b_pages[i]->valid & mask) == mask)
4139 if ((bp->b_pages[i]->valid & mask) == 0)
4140 pmap_zero_page_area(bp->b_pages[i], sa, ea - sa);
4142 for (; sa < ea; sa += DEV_BSIZE, j++) {
4143 if ((bp->b_pages[i]->valid & (1 << j)) == 0) {
4144 pmap_zero_page_area(bp->b_pages[i],
4149 bp->b_pages[i]->valid |= mask;
4152 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4157 vfs_bio_bzero_buf(struct buf *bp, int base, int size)
4162 if ((bp->b_flags & B_UNMAPPED) == 0) {
4163 BUF_CHECK_MAPPED(bp);
4164 bzero(bp->b_data + base, size);
4166 BUF_CHECK_UNMAPPED(bp);
4167 n = PAGE_SIZE - (base & PAGE_MASK);
4168 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4172 pmap_zero_page_area(m, base & PAGE_MASK, n);
4181 * vm_hold_load_pages and vm_hold_free_pages get pages into
4182 * a buffers address space. The pages are anonymous and are
4183 * not associated with a file object.
4186 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4192 BUF_CHECK_MAPPED(bp);
4194 to = round_page(to);
4195 from = round_page(from);
4196 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4198 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4201 * note: must allocate system pages since blocking here
4202 * could interfere with paging I/O, no matter which
4205 p = vm_page_alloc(NULL, 0, VM_ALLOC_SYSTEM | VM_ALLOC_NOOBJ |
4206 VM_ALLOC_WIRED | VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT));
4211 pmap_qenter(pg, &p, 1);
4212 bp->b_pages[index] = p;
4214 bp->b_npages = index;
4217 /* Return pages associated with this buf to the vm system */
4219 vm_hold_free_pages(struct buf *bp, int newbsize)
4223 int index, newnpages;
4225 BUF_CHECK_MAPPED(bp);
4227 from = round_page((vm_offset_t)bp->b_data + newbsize);
4228 newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4229 if (bp->b_npages > newnpages)
4230 pmap_qremove(from, bp->b_npages - newnpages);
4231 for (index = newnpages; index < bp->b_npages; index++) {
4232 p = bp->b_pages[index];
4233 bp->b_pages[index] = NULL;
4235 printf("vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
4236 (intmax_t)bp->b_blkno, (intmax_t)bp->b_lblkno);
4239 atomic_subtract_int(&cnt.v_wire_count, 1);
4241 bp->b_npages = newnpages;
4245 * Map an IO request into kernel virtual address space.
4247 * All requests are (re)mapped into kernel VA space.
4248 * Notice that we use b_bufsize for the size of the buffer
4249 * to be mapped. b_bcount might be modified by the driver.
4251 * Note that even if the caller determines that the address space should
4252 * be valid, a race or a smaller-file mapped into a larger space may
4253 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
4254 * check the return value.
4257 vmapbuf(struct buf *bp, int mapbuf)
4263 if (bp->b_bufsize < 0)
4265 prot = VM_PROT_READ;
4266 if (bp->b_iocmd == BIO_READ)
4267 prot |= VM_PROT_WRITE; /* Less backwards than it looks */
4268 if ((pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
4269 (vm_offset_t)bp->b_data, bp->b_bufsize, prot, bp->b_pages,
4270 btoc(MAXPHYS))) < 0)
4272 bp->b_npages = pidx;
4273 if (mapbuf || !unmapped_buf_allowed) {
4274 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
4275 kva = bp->b_saveaddr;
4276 bp->b_saveaddr = bp->b_data;
4277 bp->b_data = kva + (((vm_offset_t)bp->b_data) & PAGE_MASK);
4278 bp->b_flags &= ~B_UNMAPPED;
4280 bp->b_flags |= B_UNMAPPED;
4281 bp->b_offset = ((vm_offset_t)bp->b_data) & PAGE_MASK;
4282 bp->b_saveaddr = bp->b_data;
4283 bp->b_data = unmapped_buf;
4289 * Free the io map PTEs associated with this IO operation.
4290 * We also invalidate the TLB entries and restore the original b_addr.
4293 vunmapbuf(struct buf *bp)
4297 npages = bp->b_npages;
4298 if (bp->b_flags & B_UNMAPPED)
4299 bp->b_flags &= ~B_UNMAPPED;
4301 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4302 vm_page_unhold_pages(bp->b_pages, npages);
4304 bp->b_data = bp->b_saveaddr;
4308 bdone(struct buf *bp)
4312 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4314 bp->b_flags |= B_DONE;
4320 bwait(struct buf *bp, u_char pri, const char *wchan)
4324 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4326 while ((bp->b_flags & B_DONE) == 0)
4327 msleep(bp, mtxp, pri, wchan, 0);
4332 bufsync(struct bufobj *bo, int waitfor)
4335 return (VOP_FSYNC(bo->__bo_vnode, waitfor, curthread));
4339 bufstrategy(struct bufobj *bo, struct buf *bp)
4345 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
4346 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
4347 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
4348 i = VOP_STRATEGY(vp, bp);
4349 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
4353 bufobj_wrefl(struct bufobj *bo)
4356 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4357 ASSERT_BO_WLOCKED(bo);
4362 bufobj_wref(struct bufobj *bo)
4365 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4372 bufobj_wdrop(struct bufobj *bo)
4375 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
4377 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
4378 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
4379 bo->bo_flag &= ~BO_WWAIT;
4380 wakeup(&bo->bo_numoutput);
4386 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
4390 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
4391 ASSERT_BO_WLOCKED(bo);
4393 while (bo->bo_numoutput) {
4394 bo->bo_flag |= BO_WWAIT;
4395 error = msleep(&bo->bo_numoutput, BO_LOCKPTR(bo),
4396 slpflag | (PRIBIO + 1), "bo_wwait", timeo);
4404 bpin(struct buf *bp)
4408 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4415 bunpin(struct buf *bp)
4419 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4421 if (--bp->b_pin_count == 0)
4427 bunpin_wait(struct buf *bp)
4431 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4433 while (bp->b_pin_count > 0)
4434 msleep(bp, mtxp, PRIBIO, "bwunpin", 0);
4439 * Set bio_data or bio_ma for struct bio from the struct buf.
4442 bdata2bio(struct buf *bp, struct bio *bip)
4445 if ((bp->b_flags & B_UNMAPPED) != 0) {
4446 KASSERT(unmapped_buf_allowed, ("unmapped"));
4447 bip->bio_ma = bp->b_pages;
4448 bip->bio_ma_n = bp->b_npages;
4449 bip->bio_data = unmapped_buf;
4450 bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
4451 bip->bio_flags |= BIO_UNMAPPED;
4452 KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) /
4453 PAGE_SIZE == bp->b_npages,
4454 ("Buffer %p too short: %d %d %d", bp, bip->bio_ma_offset,
4455 bip->bio_length, bip->bio_ma_n));
4457 bip->bio_data = bp->b_data;
4462 #include "opt_ddb.h"
4464 #include <ddb/ddb.h>
4466 /* DDB command to show buffer data */
4467 DB_SHOW_COMMAND(buffer, db_show_buffer)
4470 struct buf *bp = (struct buf *)addr;
4473 db_printf("usage: show buffer <addr>\n");
4477 db_printf("buf at %p\n", bp);
4478 db_printf("b_flags = 0x%b, b_xflags=0x%b, b_vflags=0x%b\n",
4479 (u_int)bp->b_flags, PRINT_BUF_FLAGS, (u_int)bp->b_xflags,
4480 PRINT_BUF_XFLAGS, (u_int)bp->b_vflags, PRINT_BUF_VFLAGS);
4482 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4483 "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_lblkno = %jd, "
4485 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4486 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4487 (intmax_t)bp->b_lblkno, bp->b_dep.lh_first);
4490 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4491 for (i = 0; i < bp->b_npages; i++) {
4494 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4495 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4496 if ((i + 1) < bp->b_npages)
4502 BUF_LOCKPRINTINFO(bp);
4505 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
4510 for (i = 0; i < nbuf; i++) {
4512 if (BUF_ISLOCKED(bp)) {
4513 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4519 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
4525 db_printf("usage: show vnodebufs <addr>\n");
4528 vp = (struct vnode *)addr;
4529 db_printf("Clean buffers:\n");
4530 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
4531 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4534 db_printf("Dirty buffers:\n");
4535 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
4536 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4541 DB_COMMAND(countfreebufs, db_coundfreebufs)
4544 int i, used = 0, nfree = 0;
4547 db_printf("usage: countfreebufs\n");
4551 for (i = 0; i < nbuf; i++) {
4553 if ((bp->b_flags & B_INFREECNT) != 0)
4559 db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
4561 db_printf("numfreebuffers is %d\n", numfreebuffers);