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_vflags & BV_INFREECNT) == 0,
422 ("buf %p already counted as free", bp));
423 if (bp->b_bufobj != NULL)
424 mtx_assert(BO_MTX(bp->b_bufobj), MA_OWNED);
425 bp->b_vflags |= BV_INFREECNT;
426 old = atomic_fetchadd_int(&numfreebuffers, 1);
427 KASSERT(old >= 0 && old < nbuf,
428 ("numfreebuffers climbed to %d", old + 1));
431 needsbuffer &= ~VFS_BIO_NEED_ANY;
432 if (numfreebuffers >= hifreebuffers)
433 needsbuffer &= ~VFS_BIO_NEED_FREE;
434 wakeup(&needsbuffer);
440 * waitrunningbufspace()
442 * runningbufspace is a measure of the amount of I/O currently
443 * running. This routine is used in async-write situations to
444 * prevent creating huge backups of pending writes to a device.
445 * Only asynchronous writes are governed by this function.
447 * Reads will adjust runningbufspace, but will not block based on it.
448 * The read load has a side effect of reducing the allowed write load.
450 * This does NOT turn an async write into a sync write. It waits
451 * for earlier writes to complete and generally returns before the
452 * caller's write has reached the device.
455 waitrunningbufspace(void)
458 mtx_lock(&rbreqlock);
459 while (runningbufspace > hirunningspace) {
461 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
463 mtx_unlock(&rbreqlock);
468 * vfs_buf_test_cache:
470 * Called when a buffer is extended. This function clears the B_CACHE
471 * bit if the newly extended portion of the buffer does not contain
476 vfs_buf_test_cache(struct buf *bp,
477 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
481 VM_OBJECT_ASSERT_WLOCKED(m->object);
482 if (bp->b_flags & B_CACHE) {
483 int base = (foff + off) & PAGE_MASK;
484 if (vm_page_is_valid(m, base, size) == 0)
485 bp->b_flags &= ~B_CACHE;
489 /* Wake up the buffer daemon if necessary */
492 bd_wakeup(int dirtybuflevel)
496 if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
504 * bd_speedup - speedup the buffer cache flushing code
514 if (bd_speedupreq == 0 || bd_request == 0)
524 * Calculating buffer cache scaling values and reserve space for buffer
525 * headers. This is called during low level kernel initialization and
526 * may be called more then once. We CANNOT write to the memory area
527 * being reserved at this time.
530 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
533 long maxbuf, maxbuf_sz, buf_sz, biotmap_sz;
536 * physmem_est is in pages. Convert it to kilobytes (assumes
537 * PAGE_SIZE is >= 1K)
539 physmem_est = physmem_est * (PAGE_SIZE / 1024);
542 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
543 * For the first 64MB of ram nominally allocate sufficient buffers to
544 * cover 1/4 of our ram. Beyond the first 64MB allocate additional
545 * buffers to cover 1/10 of our ram over 64MB. When auto-sizing
546 * the buffer cache we limit the eventual kva reservation to
549 * factor represents the 1/4 x ram conversion.
552 int factor = 4 * BKVASIZE / 1024;
555 if (physmem_est > 4096)
556 nbuf += min((physmem_est - 4096) / factor,
558 if (physmem_est > 65536)
559 nbuf += (physmem_est - 65536) * 2 / (factor * 5);
561 if (maxbcache && nbuf > maxbcache / BKVASIZE)
562 nbuf = maxbcache / BKVASIZE;
567 /* XXX Avoid unsigned long overflows later on with maxbufspace. */
568 maxbuf = (LONG_MAX / 3) / BKVASIZE;
571 printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
577 * Ideal allocation size for the transient bio submap if 10%
578 * of the maximal space buffer map. This roughly corresponds
579 * to the amount of the buffer mapped for typical UFS load.
581 * Clip the buffer map to reserve space for the transient
582 * BIOs, if its extent is bigger than 90% of the maximum
583 * buffer map extent on the platform.
585 * The fall-back to the maxbuf in case of maxbcache unset,
586 * allows to not trim the buffer KVA for the architectures
587 * with ample KVA space.
589 if (bio_transient_maxcnt == 0 && unmapped_buf_allowed) {
590 maxbuf_sz = maxbcache != 0 ? maxbcache : maxbuf * BKVASIZE;
591 buf_sz = (long)nbuf * BKVASIZE;
592 if (buf_sz < maxbuf_sz / 10 * 9) {
594 * There is more KVA than memory. Do not
595 * adjust buffer map size, and assign the rest
596 * of maxbuf to transient map.
598 biotmap_sz = maxbuf_sz - buf_sz;
601 * Buffer map spans all KVA we could afford on
602 * this platform. Give 10% of the buffer map
603 * to the transient bio map.
605 biotmap_sz = buf_sz / 10;
606 buf_sz -= biotmap_sz;
608 if (biotmap_sz / INT_MAX > MAXPHYS)
609 bio_transient_maxcnt = INT_MAX;
611 bio_transient_maxcnt = biotmap_sz / MAXPHYS;
613 * Artifically limit to 1024 simultaneous in-flight I/Os
614 * using the transient mapping.
616 if (bio_transient_maxcnt > 1024)
617 bio_transient_maxcnt = 1024;
619 nbuf = buf_sz / BKVASIZE;
623 * swbufs are used as temporary holders for I/O, such as paging I/O.
624 * We have no less then 16 and no more then 256.
626 nswbuf = max(min(nbuf/4, 256), 16);
628 if (nswbuf < NSWBUF_MIN)
636 * Reserve space for the buffer cache buffers
639 v = (caddr_t)(swbuf + nswbuf);
641 v = (caddr_t)(buf + nbuf);
646 /* Initialize the buffer subsystem. Called before use of any buffers. */
653 mtx_init(&bqlock, "buf queue lock", NULL, MTX_DEF);
654 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
655 mtx_init(&nblock, "needsbuffer lock", NULL, MTX_DEF);
656 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
658 /* next, make a null set of free lists */
659 for (i = 0; i < BUFFER_QUEUES; i++)
660 TAILQ_INIT(&bufqueues[i]);
662 /* finally, initialize each buffer header and stick on empty q */
663 for (i = 0; i < nbuf; i++) {
665 bzero(bp, sizeof *bp);
666 bp->b_flags = B_INVAL; /* we're just an empty header */
667 bp->b_rcred = NOCRED;
668 bp->b_wcred = NOCRED;
669 bp->b_qindex = QUEUE_EMPTY;
670 bp->b_vflags = BV_INFREECNT; /* buf is counted as free */
672 LIST_INIT(&bp->b_dep);
674 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
676 bq_len[QUEUE_EMPTY]++;
681 * maxbufspace is the absolute maximum amount of buffer space we are
682 * allowed to reserve in KVM and in real terms. The absolute maximum
683 * is nominally used by buf_daemon. hibufspace is the nominal maximum
684 * used by most other processes. The differential is required to
685 * ensure that buf_daemon is able to run when other processes might
686 * be blocked waiting for buffer space.
688 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
689 * this may result in KVM fragmentation which is not handled optimally
692 maxbufspace = (long)nbuf * BKVASIZE;
693 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
694 lobufspace = hibufspace - MAXBSIZE;
697 * Note: The 16 MiB upper limit for hirunningspace was chosen
698 * arbitrarily and may need further tuning. It corresponds to
699 * 128 outstanding write IO requests (if IO size is 128 KiB),
700 * which fits with many RAID controllers' tagged queuing limits.
701 * The lower 1 MiB limit is the historical upper limit for
704 hirunningspace = lmax(lmin(roundup(hibufspace / 64, MAXBSIZE),
705 16 * 1024 * 1024), 1024 * 1024);
706 lorunningspace = roundup((hirunningspace * 2) / 3, MAXBSIZE);
709 * Limit the amount of malloc memory since it is wired permanently into
710 * the kernel space. Even though this is accounted for in the buffer
711 * allocation, we don't want the malloced region to grow uncontrolled.
712 * The malloc scheme improves memory utilization significantly on average
713 * (small) directories.
715 maxbufmallocspace = hibufspace / 20;
718 * Reduce the chance of a deadlock occuring by limiting the number
719 * of delayed-write dirty buffers we allow to stack up.
721 hidirtybuffers = nbuf / 4 + 20;
722 dirtybufthresh = hidirtybuffers * 9 / 10;
725 * To support extreme low-memory systems, make sure hidirtybuffers cannot
726 * eat up all available buffer space. This occurs when our minimum cannot
727 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
728 * BKVASIZE'd buffers.
730 while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
731 hidirtybuffers >>= 1;
733 lodirtybuffers = hidirtybuffers / 2;
736 * Try to keep the number of free buffers in the specified range,
737 * and give special processes (e.g. like buf_daemon) access to an
740 lofreebuffers = nbuf / 18 + 5;
741 hifreebuffers = 2 * lofreebuffers;
742 numfreebuffers = nbuf;
744 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
745 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
746 unmapped_buf = (caddr_t)kmem_alloc_nofault(kernel_map, MAXPHYS);
751 vfs_buf_check_mapped(struct buf *bp)
754 KASSERT((bp->b_flags & B_UNMAPPED) == 0,
755 ("mapped buf %p %x", bp, bp->b_flags));
756 KASSERT(bp->b_kvabase != unmapped_buf,
757 ("mapped buf: b_kvabase was not updated %p", bp));
758 KASSERT(bp->b_data != unmapped_buf,
759 ("mapped buf: b_data was not updated %p", bp));
763 vfs_buf_check_unmapped(struct buf *bp)
766 KASSERT((bp->b_flags & B_UNMAPPED) == B_UNMAPPED,
767 ("unmapped buf %p %x", bp, bp->b_flags));
768 KASSERT(bp->b_kvabase == unmapped_buf,
769 ("unmapped buf: corrupted b_kvabase %p", bp));
770 KASSERT(bp->b_data == unmapped_buf,
771 ("unmapped buf: corrupted b_data %p", bp));
774 #define BUF_CHECK_MAPPED(bp) vfs_buf_check_mapped(bp)
775 #define BUF_CHECK_UNMAPPED(bp) vfs_buf_check_unmapped(bp)
777 #define BUF_CHECK_MAPPED(bp) do {} while (0)
778 #define BUF_CHECK_UNMAPPED(bp) do {} while (0)
782 bpmap_qenter(struct buf *bp)
785 BUF_CHECK_MAPPED(bp);
788 * bp->b_data is relative to bp->b_offset, but
789 * bp->b_offset may be offset into the first page.
791 bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
792 pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
793 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
794 (vm_offset_t)(bp->b_offset & PAGE_MASK));
798 * bfreekva() - free the kva allocation for a buffer.
800 * Since this call frees up buffer space, we call bufspacewakeup().
803 bfreekva(struct buf *bp)
806 if (bp->b_kvasize == 0)
809 atomic_add_int(&buffreekvacnt, 1);
810 atomic_subtract_long(&bufspace, bp->b_kvasize);
811 if ((bp->b_flags & B_UNMAPPED) == 0) {
812 BUF_CHECK_MAPPED(bp);
813 vm_map_remove(buffer_map, (vm_offset_t)bp->b_kvabase,
814 (vm_offset_t)bp->b_kvabase + bp->b_kvasize);
816 BUF_CHECK_UNMAPPED(bp);
817 if ((bp->b_flags & B_KVAALLOC) != 0) {
818 vm_map_remove(buffer_map, (vm_offset_t)bp->b_kvaalloc,
819 (vm_offset_t)bp->b_kvaalloc + bp->b_kvasize);
821 atomic_subtract_long(&unmapped_bufspace, bp->b_kvasize);
822 bp->b_flags &= ~(B_UNMAPPED | B_KVAALLOC);
831 * Mark the buffer for removal from the appropriate free list in brelse.
835 bremfree(struct buf *bp)
839 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
840 KASSERT((bp->b_flags & B_REMFREE) == 0,
841 ("bremfree: buffer %p already marked for delayed removal.", bp));
842 KASSERT(bp->b_qindex != QUEUE_NONE,
843 ("bremfree: buffer %p not on a queue.", bp));
846 bp->b_flags |= B_REMFREE;
847 /* Fixup numfreebuffers count. */
848 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
849 KASSERT((bp->b_vflags & BV_INFREECNT) != 0,
850 ("buf %p not counted in numfreebuffers", bp));
851 if (bp->b_bufobj != NULL)
852 mtx_assert(BO_MTX(bp->b_bufobj), MA_OWNED);
853 bp->b_vflags &= ~BV_INFREECNT;
854 old = atomic_fetchadd_int(&numfreebuffers, -1);
855 KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
862 * Force an immediate removal from a free list. Used only in nfs when
863 * it abuses the b_freelist pointer.
866 bremfreef(struct buf *bp)
876 * Removes a buffer from the free list, must be called with the
880 bremfreel(struct buf *bp)
884 CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
885 bp, bp->b_vp, bp->b_flags);
886 KASSERT(bp->b_qindex != QUEUE_NONE,
887 ("bremfreel: buffer %p not on a queue.", bp));
889 mtx_assert(&bqlock, MA_OWNED);
891 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
893 KASSERT(bq_len[bp->b_qindex] >= 1, ("queue %d underflow",
895 bq_len[bp->b_qindex]--;
897 bp->b_qindex = QUEUE_NONE;
899 * If this was a delayed bremfree() we only need to remove the buffer
900 * from the queue and return the stats are already done.
902 if (bp->b_flags & B_REMFREE) {
903 bp->b_flags &= ~B_REMFREE;
907 * Fixup numfreebuffers count. If the buffer is invalid or not
908 * delayed-write, the buffer was free and we must decrement
911 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
912 KASSERT((bp->b_vflags & BV_INFREECNT) != 0,
913 ("buf %p not counted in numfreebuffers", bp));
914 if (bp->b_bufobj != NULL)
915 mtx_assert(BO_MTX(bp->b_bufobj), MA_OWNED);
916 bp->b_vflags &= ~BV_INFREECNT;
917 old = atomic_fetchadd_int(&numfreebuffers, -1);
918 KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
923 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must
924 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
925 * the buffer is valid and we do not have to do anything.
928 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
929 int cnt, struct ucred * cred)
934 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
935 if (inmem(vp, *rablkno))
937 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
939 if ((rabp->b_flags & B_CACHE) == 0) {
940 if (!TD_IS_IDLETHREAD(curthread))
941 curthread->td_ru.ru_inblock++;
942 rabp->b_flags |= B_ASYNC;
943 rabp->b_flags &= ~B_INVAL;
944 rabp->b_ioflags &= ~BIO_ERROR;
945 rabp->b_iocmd = BIO_READ;
946 if (rabp->b_rcred == NOCRED && cred != NOCRED)
947 rabp->b_rcred = crhold(cred);
948 vfs_busy_pages(rabp, 0);
950 rabp->b_iooffset = dbtob(rabp->b_blkno);
959 * Entry point for bread() and breadn() via #defines in sys/buf.h.
961 * Get a buffer with the specified data. Look in the cache first. We
962 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
963 * is set, the buffer is valid and we do not have to do anything, see
964 * getblk(). Also starts asynchronous I/O on read-ahead blocks.
967 breadn_flags(struct vnode *vp, daddr_t blkno, int size, daddr_t *rablkno,
968 int *rabsize, int cnt, struct ucred *cred, int flags, struct buf **bpp)
971 int rv = 0, readwait = 0;
973 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
975 * Can only return NULL if GB_LOCK_NOWAIT flag is specified.
977 *bpp = bp = getblk(vp, blkno, size, 0, 0, flags);
981 /* if not found in cache, do some I/O */
982 if ((bp->b_flags & B_CACHE) == 0) {
983 if (!TD_IS_IDLETHREAD(curthread))
984 curthread->td_ru.ru_inblock++;
985 bp->b_iocmd = BIO_READ;
986 bp->b_flags &= ~B_INVAL;
987 bp->b_ioflags &= ~BIO_ERROR;
988 if (bp->b_rcred == NOCRED && cred != NOCRED)
989 bp->b_rcred = crhold(cred);
990 vfs_busy_pages(bp, 0);
991 bp->b_iooffset = dbtob(bp->b_blkno);
996 breada(vp, rablkno, rabsize, cnt, cred);
1005 * Write, release buffer on completion. (Done by iodone
1006 * if async). Do not bother writing anything if the buffer
1009 * Note that we set B_CACHE here, indicating that buffer is
1010 * fully valid and thus cacheable. This is true even of NFS
1011 * now so we set it generally. This could be set either here
1012 * or in biodone() since the I/O is synchronous. We put it
1016 bufwrite(struct buf *bp)
1022 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1023 if (bp->b_flags & B_INVAL) {
1028 if (bp->b_flags & B_BARRIER)
1031 oldflags = bp->b_flags;
1033 BUF_ASSERT_HELD(bp);
1035 if (bp->b_pin_count > 0)
1038 KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
1039 ("FFS background buffer should not get here %p", bp));
1043 vp_md = vp->v_vflag & VV_MD;
1048 * Mark the buffer clean. Increment the bufobj write count
1049 * before bundirty() call, to prevent other thread from seeing
1050 * empty dirty list and zero counter for writes in progress,
1051 * falsely indicating that the bufobj is clean.
1053 bufobj_wref(bp->b_bufobj);
1056 bp->b_flags &= ~B_DONE;
1057 bp->b_ioflags &= ~BIO_ERROR;
1058 bp->b_flags |= B_CACHE;
1059 bp->b_iocmd = BIO_WRITE;
1061 vfs_busy_pages(bp, 1);
1064 * Normal bwrites pipeline writes
1066 bp->b_runningbufspace = bp->b_bufsize;
1067 atomic_add_long(&runningbufspace, bp->b_runningbufspace);
1069 if (!TD_IS_IDLETHREAD(curthread))
1070 curthread->td_ru.ru_oublock++;
1071 if (oldflags & B_ASYNC)
1073 bp->b_iooffset = dbtob(bp->b_blkno);
1076 if ((oldflags & B_ASYNC) == 0) {
1077 int rtval = bufwait(bp);
1082 * don't allow the async write to saturate the I/O
1083 * system. We will not deadlock here because
1084 * we are blocking waiting for I/O that is already in-progress
1085 * to complete. We do not block here if it is the update
1086 * or syncer daemon trying to clean up as that can lead
1089 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
1090 waitrunningbufspace();
1097 bufbdflush(struct bufobj *bo, struct buf *bp)
1101 if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
1102 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
1104 } else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
1107 * Try to find a buffer to flush.
1109 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
1110 if ((nbp->b_vflags & BV_BKGRDINPROG) ||
1112 LK_EXCLUSIVE | LK_NOWAIT, NULL))
1115 panic("bdwrite: found ourselves");
1117 /* Don't countdeps with the bo lock held. */
1118 if (buf_countdeps(nbp, 0)) {
1123 if (nbp->b_flags & B_CLUSTEROK) {
1124 vfs_bio_awrite(nbp);
1129 dirtybufferflushes++;
1138 * Delayed write. (Buffer is marked dirty). Do not bother writing
1139 * anything if the buffer is marked invalid.
1141 * Note that since the buffer must be completely valid, we can safely
1142 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
1143 * biodone() in order to prevent getblk from writing the buffer
1144 * out synchronously.
1147 bdwrite(struct buf *bp)
1149 struct thread *td = curthread;
1153 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1154 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1155 KASSERT((bp->b_flags & B_BARRIER) == 0,
1156 ("Barrier request in delayed write %p", bp));
1157 BUF_ASSERT_HELD(bp);
1159 if (bp->b_flags & B_INVAL) {
1165 * If we have too many dirty buffers, don't create any more.
1166 * If we are wildly over our limit, then force a complete
1167 * cleanup. Otherwise, just keep the situation from getting
1168 * out of control. Note that we have to avoid a recursive
1169 * disaster and not try to clean up after our own cleanup!
1173 if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
1174 td->td_pflags |= TDP_INBDFLUSH;
1176 td->td_pflags &= ~TDP_INBDFLUSH;
1182 * Set B_CACHE, indicating that the buffer is fully valid. This is
1183 * true even of NFS now.
1185 bp->b_flags |= B_CACHE;
1188 * This bmap keeps the system from needing to do the bmap later,
1189 * perhaps when the system is attempting to do a sync. Since it
1190 * is likely that the indirect block -- or whatever other datastructure
1191 * that the filesystem needs is still in memory now, it is a good
1192 * thing to do this. Note also, that if the pageout daemon is
1193 * requesting a sync -- there might not be enough memory to do
1194 * the bmap then... So, this is important to do.
1196 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
1197 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
1201 * Set the *dirty* buffer range based upon the VM system dirty
1204 * Mark the buffer pages as clean. We need to do this here to
1205 * satisfy the vnode_pager and the pageout daemon, so that it
1206 * thinks that the pages have been "cleaned". Note that since
1207 * the pages are in a delayed write buffer -- the VFS layer
1208 * "will" see that the pages get written out on the next sync,
1209 * or perhaps the cluster will be completed.
1211 vfs_clean_pages_dirty_buf(bp);
1215 * Wakeup the buffer flushing daemon if we have a lot of dirty
1216 * buffers (midpoint between our recovery point and our stall
1219 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1222 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1223 * due to the softdep code.
1230 * Turn buffer into delayed write request. We must clear BIO_READ and
1231 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
1232 * itself to properly update it in the dirty/clean lists. We mark it
1233 * B_DONE to ensure that any asynchronization of the buffer properly
1234 * clears B_DONE ( else a panic will occur later ).
1236 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1237 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
1238 * should only be called if the buffer is known-good.
1240 * Since the buffer is not on a queue, we do not update the numfreebuffers
1243 * The buffer must be on QUEUE_NONE.
1246 bdirty(struct buf *bp)
1249 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
1250 bp, bp->b_vp, bp->b_flags);
1251 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1252 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1253 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1254 BUF_ASSERT_HELD(bp);
1255 bp->b_flags &= ~(B_RELBUF);
1256 bp->b_iocmd = BIO_WRITE;
1258 if ((bp->b_flags & B_DELWRI) == 0) {
1259 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
1261 atomic_add_int(&numdirtybuffers, 1);
1262 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1269 * Clear B_DELWRI for buffer.
1271 * Since the buffer is not on a queue, we do not update the numfreebuffers
1274 * The buffer must be on QUEUE_NONE.
1278 bundirty(struct buf *bp)
1281 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1282 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1283 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1284 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1285 BUF_ASSERT_HELD(bp);
1287 if (bp->b_flags & B_DELWRI) {
1288 bp->b_flags &= ~B_DELWRI;
1290 atomic_subtract_int(&numdirtybuffers, 1);
1291 numdirtywakeup(lodirtybuffers);
1294 * Since it is now being written, we can clear its deferred write flag.
1296 bp->b_flags &= ~B_DEFERRED;
1302 * Asynchronous write. Start output on a buffer, but do not wait for
1303 * it to complete. The buffer is released when the output completes.
1305 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1306 * B_INVAL buffers. Not us.
1309 bawrite(struct buf *bp)
1312 bp->b_flags |= B_ASYNC;
1319 * Asynchronous barrier write. Start output on a buffer, but do not
1320 * wait for it to complete. Place a write barrier after this write so
1321 * that this buffer and all buffers written before it are committed to
1322 * the disk before any buffers written after this write are committed
1323 * to the disk. The buffer is released when the output completes.
1326 babarrierwrite(struct buf *bp)
1329 bp->b_flags |= B_ASYNC | B_BARRIER;
1336 * Synchronous barrier write. Start output on a buffer and wait for
1337 * it to complete. Place a write barrier after this write so that
1338 * this buffer and all buffers written before it are committed to
1339 * the disk before any buffers written after this write are committed
1340 * to the disk. The buffer is released when the output completes.
1343 bbarrierwrite(struct buf *bp)
1346 bp->b_flags |= B_BARRIER;
1347 return (bwrite(bp));
1353 * Called prior to the locking of any vnodes when we are expecting to
1354 * write. We do not want to starve the buffer cache with too many
1355 * dirty buffers so we block here. By blocking prior to the locking
1356 * of any vnodes we attempt to avoid the situation where a locked vnode
1357 * prevents the various system daemons from flushing related buffers.
1364 if (numdirtybuffers >= hidirtybuffers) {
1366 while (numdirtybuffers >= hidirtybuffers) {
1368 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
1369 msleep(&needsbuffer, &nblock,
1370 (PRIBIO + 4), "flswai", 0);
1372 mtx_unlock(&nblock);
1377 * Return true if we have too many dirty buffers.
1380 buf_dirty_count_severe(void)
1383 return(numdirtybuffers >= hidirtybuffers);
1386 static __noinline int
1387 buf_vm_page_count_severe(void)
1390 KFAIL_POINT_CODE(DEBUG_FP, buf_pressure, return 1);
1392 return vm_page_count_severe();
1398 * Release a busy buffer and, if requested, free its resources. The
1399 * buffer will be stashed in the appropriate bufqueue[] allowing it
1400 * to be accessed later as a cache entity or reused for other purposes.
1403 brelse(struct buf *bp)
1405 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
1406 bp, bp->b_vp, bp->b_flags);
1407 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1408 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1410 if (BUF_LOCKRECURSED(bp)) {
1412 * Do not process, in particular, do not handle the
1413 * B_INVAL/B_RELBUF and do not release to free list.
1419 if (bp->b_flags & B_MANAGED) {
1424 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
1425 bp->b_error == EIO && !(bp->b_flags & B_INVAL)) {
1427 * Failed write, redirty. Must clear BIO_ERROR to prevent
1428 * pages from being scrapped. If the error is anything
1429 * other than an I/O error (EIO), assume that retrying
1432 bp->b_ioflags &= ~BIO_ERROR;
1434 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1435 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
1437 * Either a failed I/O or we were asked to free or not
1440 bp->b_flags |= B_INVAL;
1441 if (!LIST_EMPTY(&bp->b_dep))
1443 if (bp->b_flags & B_DELWRI) {
1444 atomic_subtract_int(&numdirtybuffers, 1);
1445 numdirtywakeup(lodirtybuffers);
1447 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1448 if ((bp->b_flags & B_VMIO) == 0) {
1457 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1458 * is called with B_DELWRI set, the underlying pages may wind up
1459 * getting freed causing a previous write (bdwrite()) to get 'lost'
1460 * because pages associated with a B_DELWRI bp are marked clean.
1462 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1463 * if B_DELWRI is set.
1465 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1466 * on pages to return pages to the VM page queues.
1468 if (bp->b_flags & B_DELWRI)
1469 bp->b_flags &= ~B_RELBUF;
1470 else if (buf_vm_page_count_severe()) {
1472 * The locking of the BO_LOCK is not necessary since
1473 * BKGRDINPROG cannot be set while we hold the buf
1474 * lock, it can only be cleared if it is already
1478 if (!(bp->b_vflags & BV_BKGRDINPROG))
1479 bp->b_flags |= B_RELBUF;
1481 bp->b_flags |= B_RELBUF;
1485 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1486 * constituted, not even NFS buffers now. Two flags effect this. If
1487 * B_INVAL, the struct buf is invalidated but the VM object is kept
1488 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1490 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1491 * invalidated. BIO_ERROR cannot be set for a failed write unless the
1492 * buffer is also B_INVAL because it hits the re-dirtying code above.
1494 * Normally we can do this whether a buffer is B_DELWRI or not. If
1495 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1496 * the commit state and we cannot afford to lose the buffer. If the
1497 * buffer has a background write in progress, we need to keep it
1498 * around to prevent it from being reconstituted and starting a second
1501 if ((bp->b_flags & B_VMIO)
1502 && !(bp->b_vp->v_mount != NULL &&
1503 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1504 !vn_isdisk(bp->b_vp, NULL) &&
1505 (bp->b_flags & B_DELWRI))
1514 obj = bp->b_bufobj->bo_object;
1517 * Get the base offset and length of the buffer. Note that
1518 * in the VMIO case if the buffer block size is not
1519 * page-aligned then b_data pointer may not be page-aligned.
1520 * But our b_pages[] array *IS* page aligned.
1522 * block sizes less then DEV_BSIZE (usually 512) are not
1523 * supported due to the page granularity bits (m->valid,
1524 * m->dirty, etc...).
1526 * See man buf(9) for more information
1528 resid = bp->b_bufsize;
1529 foff = bp->b_offset;
1530 VM_OBJECT_WLOCK(obj);
1531 for (i = 0; i < bp->b_npages; i++) {
1537 * If we hit a bogus page, fixup *all* the bogus pages
1540 if (m == bogus_page) {
1541 poff = OFF_TO_IDX(bp->b_offset);
1544 for (j = i; j < bp->b_npages; j++) {
1546 mtmp = bp->b_pages[j];
1547 if (mtmp == bogus_page) {
1548 mtmp = vm_page_lookup(obj, poff + j);
1550 panic("brelse: page missing\n");
1552 bp->b_pages[j] = mtmp;
1556 if ((bp->b_flags & (B_INVAL | B_UNMAPPED)) == 0) {
1557 BUF_CHECK_MAPPED(bp);
1559 trunc_page((vm_offset_t)bp->b_data),
1560 bp->b_pages, bp->b_npages);
1564 if ((bp->b_flags & B_NOCACHE) ||
1565 (bp->b_ioflags & BIO_ERROR &&
1566 bp->b_iocmd == BIO_READ)) {
1567 int poffset = foff & PAGE_MASK;
1568 int presid = resid > (PAGE_SIZE - poffset) ?
1569 (PAGE_SIZE - poffset) : resid;
1571 KASSERT(presid >= 0, ("brelse: extra page"));
1572 vm_page_set_invalid(m, poffset, presid);
1574 printf("avoided corruption bug in bogus_page/brelse code\n");
1576 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1577 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1579 VM_OBJECT_WUNLOCK(obj);
1580 if (bp->b_flags & (B_INVAL | B_RELBUF))
1581 vfs_vmio_release(bp);
1583 } else if (bp->b_flags & B_VMIO) {
1585 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1586 vfs_vmio_release(bp);
1589 } else if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0) {
1590 if (bp->b_bufsize != 0)
1592 if (bp->b_vp != NULL)
1598 /* Handle delayed bremfree() processing. */
1599 if (bp->b_flags & B_REMFREE) {
1609 if (bp->b_qindex != QUEUE_NONE)
1610 panic("brelse: free buffer onto another queue???");
1613 * If the buffer has junk contents signal it and eventually
1614 * clean up B_DELWRI and diassociate the vnode so that gbincore()
1617 if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
1618 (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
1619 bp->b_flags |= B_INVAL;
1620 if (bp->b_flags & B_INVAL) {
1621 if (bp->b_flags & B_DELWRI)
1627 /* buffers with no memory */
1628 if (bp->b_bufsize == 0) {
1629 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1630 if (bp->b_vflags & BV_BKGRDINPROG)
1631 panic("losing buffer 1");
1632 if (bp->b_kvasize) {
1633 bp->b_qindex = QUEUE_EMPTYKVA;
1635 bp->b_qindex = QUEUE_EMPTY;
1637 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1638 /* buffers with junk contents */
1639 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1640 (bp->b_ioflags & BIO_ERROR)) {
1641 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1642 if (bp->b_vflags & BV_BKGRDINPROG)
1643 panic("losing buffer 2");
1644 bp->b_qindex = QUEUE_CLEAN;
1645 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1646 /* remaining buffers */
1648 if (bp->b_flags & B_DELWRI)
1649 bp->b_qindex = QUEUE_DIRTY;
1651 bp->b_qindex = QUEUE_CLEAN;
1652 if (bp->b_flags & B_AGE) {
1653 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp,
1656 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp,
1661 bq_len[bp->b_qindex]++;
1663 mtx_unlock(&bqlock);
1666 * Fixup numfreebuffers count. The bp is on an appropriate queue
1667 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1668 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1669 * if B_INVAL is set ).
1672 if (!(bp->b_flags & B_DELWRI)) {
1684 * Something we can maybe free or reuse
1686 if (bp->b_bufsize || bp->b_kvasize)
1689 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1690 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1691 panic("brelse: not dirty");
1697 * Release a buffer back to the appropriate queue but do not try to free
1698 * it. The buffer is expected to be used again soon.
1700 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1701 * biodone() to requeue an async I/O on completion. It is also used when
1702 * known good buffers need to be requeued but we think we may need the data
1705 * XXX we should be able to leave the B_RELBUF hint set on completion.
1708 bqrelse(struct buf *bp)
1712 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1713 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1714 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1716 if (BUF_LOCKRECURSED(bp)) {
1717 /* do not release to free list */
1723 if (bp->b_flags & B_MANAGED) {
1724 if (bp->b_flags & B_REMFREE) {
1731 mtx_unlock(&bqlock);
1733 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1739 /* Handle delayed bremfree() processing. */
1740 if (bp->b_flags & B_REMFREE) {
1747 if (bp->b_qindex != QUEUE_NONE)
1748 panic("bqrelse: free buffer onto another queue???");
1749 /* buffers with stale but valid contents */
1750 if (bp->b_flags & B_DELWRI) {
1751 bp->b_qindex = QUEUE_DIRTY;
1752 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1754 bq_len[bp->b_qindex]++;
1758 * The locking of the BO_LOCK for checking of the
1759 * BV_BKGRDINPROG is not necessary since the
1760 * BV_BKGRDINPROG cannot be set while we hold the buf
1761 * lock, it can only be cleared if it is already
1764 if (!buf_vm_page_count_severe() || (bp->b_vflags & BV_BKGRDINPROG)) {
1765 bp->b_qindex = QUEUE_CLEAN;
1766 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp,
1769 bq_len[QUEUE_CLEAN]++;
1773 * We are too low on memory, we have to try to free
1774 * the buffer (most importantly: the wired pages
1775 * making up its backing store) *now*.
1777 mtx_unlock(&bqlock);
1782 mtx_unlock(&bqlock);
1784 if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI)) {
1793 * Something we can maybe free or reuse.
1795 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1798 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1799 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1800 panic("bqrelse: not dirty");
1805 /* Give pages used by the bp back to the VM system (where possible) */
1807 vfs_vmio_release(struct buf *bp)
1812 if ((bp->b_flags & B_UNMAPPED) == 0) {
1813 BUF_CHECK_MAPPED(bp);
1814 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
1816 BUF_CHECK_UNMAPPED(bp);
1817 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
1818 for (i = 0; i < bp->b_npages; i++) {
1820 bp->b_pages[i] = NULL;
1822 * In order to keep page LRU ordering consistent, put
1823 * everything on the inactive queue.
1826 vm_page_unwire(m, 0);
1828 * We don't mess with busy pages, it is
1829 * the responsibility of the process that
1830 * busied the pages to deal with them.
1832 if ((m->oflags & VPO_BUSY) == 0 && m->busy == 0 &&
1833 m->wire_count == 0) {
1835 * Might as well free the page if we can and it has
1836 * no valid data. We also free the page if the
1837 * buffer was used for direct I/O
1839 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid) {
1841 } else if (bp->b_flags & B_DIRECT) {
1842 vm_page_try_to_free(m);
1843 } else if (buf_vm_page_count_severe()) {
1844 vm_page_try_to_cache(m);
1849 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
1851 if (bp->b_bufsize) {
1856 bp->b_flags &= ~B_VMIO;
1862 * Check to see if a block at a particular lbn is available for a clustered
1866 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1873 /* If the buf isn't in core skip it */
1874 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1877 /* If the buf is busy we don't want to wait for it */
1878 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1881 /* Only cluster with valid clusterable delayed write buffers */
1882 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1883 (B_DELWRI | B_CLUSTEROK))
1886 if (bpa->b_bufsize != size)
1890 * Check to see if it is in the expected place on disk and that the
1891 * block has been mapped.
1893 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1903 * Implement clustered async writes for clearing out B_DELWRI buffers.
1904 * This is much better then the old way of writing only one buffer at
1905 * a time. Note that we may not be presented with the buffers in the
1906 * correct order, so we search for the cluster in both directions.
1909 vfs_bio_awrite(struct buf *bp)
1914 daddr_t lblkno = bp->b_lblkno;
1915 struct vnode *vp = bp->b_vp;
1923 gbflags = (bp->b_flags & B_UNMAPPED) != 0 ? GB_UNMAPPED : 0;
1925 * right now we support clustered writing only to regular files. If
1926 * we find a clusterable block we could be in the middle of a cluster
1927 * rather then at the beginning.
1929 if ((vp->v_type == VREG) &&
1930 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1931 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1933 size = vp->v_mount->mnt_stat.f_iosize;
1934 maxcl = MAXPHYS / size;
1937 for (i = 1; i < maxcl; i++)
1938 if (vfs_bio_clcheck(vp, size, lblkno + i,
1939 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1942 for (j = 1; i + j <= maxcl && j <= lblkno; j++)
1943 if (vfs_bio_clcheck(vp, size, lblkno - j,
1944 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
1950 * this is a possible cluster write
1954 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl,
1960 bp->b_flags |= B_ASYNC;
1962 * default (old) behavior, writing out only one block
1964 * XXX returns b_bufsize instead of b_bcount for nwritten?
1966 nwritten = bp->b_bufsize;
1973 setbufkva(struct buf *bp, vm_offset_t addr, int maxsize, int gbflags)
1976 KASSERT((bp->b_flags & (B_UNMAPPED | B_KVAALLOC)) == 0 &&
1977 bp->b_kvasize == 0, ("call bfreekva(%p)", bp));
1978 if ((gbflags & GB_UNMAPPED) == 0) {
1979 bp->b_kvabase = (caddr_t)addr;
1980 } else if ((gbflags & GB_KVAALLOC) != 0) {
1981 KASSERT((gbflags & GB_UNMAPPED) != 0,
1982 ("GB_KVAALLOC without GB_UNMAPPED"));
1983 bp->b_kvaalloc = (caddr_t)addr;
1984 bp->b_flags |= B_UNMAPPED | B_KVAALLOC;
1985 atomic_add_long(&unmapped_bufspace, bp->b_kvasize);
1987 bp->b_kvasize = maxsize;
1991 * Allocate the buffer KVA and set b_kvasize. Also set b_kvabase if
1995 allocbufkva(struct buf *bp, int maxsize, int gbflags)
2003 vm_map_lock(buffer_map);
2004 if (vm_map_findspace(buffer_map, vm_map_min(buffer_map), maxsize,
2006 vm_map_unlock(buffer_map);
2008 * Buffer map is too fragmented. Request the caller
2009 * to defragment the map.
2011 atomic_add_int(&bufdefragcnt, 1);
2014 rv = vm_map_insert(buffer_map, NULL, 0, addr, addr + maxsize,
2015 VM_PROT_RW, VM_PROT_RW, MAP_NOFAULT);
2016 KASSERT(rv == KERN_SUCCESS, ("vm_map_insert(buffer_map) rv %d", rv));
2017 vm_map_unlock(buffer_map);
2018 setbufkva(bp, addr, maxsize, gbflags);
2019 atomic_add_long(&bufspace, bp->b_kvasize);
2024 * Ask the bufdaemon for help, or act as bufdaemon itself, when a
2025 * locked vnode is supplied.
2028 getnewbuf_bufd_help(struct vnode *vp, int gbflags, int slpflag, int slptimeo,
2033 int fl, flags, norunbuf;
2035 mtx_assert(&bqlock, MA_OWNED);
2038 flags = VFS_BIO_NEED_BUFSPACE;
2040 } else if (bufspace >= hibufspace) {
2042 flags = VFS_BIO_NEED_BUFSPACE;
2045 flags = VFS_BIO_NEED_ANY;
2048 needsbuffer |= flags;
2049 mtx_unlock(&nblock);
2050 mtx_unlock(&bqlock);
2052 bd_speedup(); /* heeeelp */
2053 if ((gbflags & GB_NOWAIT_BD) != 0)
2058 while (needsbuffer & flags) {
2059 if (vp != NULL && (td->td_pflags & TDP_BUFNEED) == 0) {
2060 mtx_unlock(&nblock);
2062 * getblk() is called with a vnode locked, and
2063 * some majority of the dirty buffers may as
2064 * well belong to the vnode. Flushing the
2065 * buffers there would make a progress that
2066 * cannot be achieved by the buf_daemon, that
2067 * cannot lock the vnode.
2069 norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
2070 (td->td_pflags & TDP_NORUNNINGBUF);
2071 /* play bufdaemon */
2072 td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
2073 fl = buf_do_flush(vp);
2074 td->td_pflags &= norunbuf;
2078 if ((needsbuffer & flags) == 0)
2081 if (msleep(&needsbuffer, &nblock, (PRIBIO + 4) | slpflag,
2085 mtx_unlock(&nblock);
2089 getnewbuf_reuse_bp(struct buf *bp, int qindex)
2092 CTR6(KTR_BUF, "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
2093 "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
2094 bp->b_kvasize, bp->b_bufsize, qindex);
2095 mtx_assert(&bqlock, MA_NOTOWNED);
2098 * Note: we no longer distinguish between VMIO and non-VMIO
2101 KASSERT((bp->b_flags & B_DELWRI) == 0,
2102 ("delwri buffer %p found in queue %d", bp, qindex));
2104 if (qindex == QUEUE_CLEAN) {
2105 if (bp->b_flags & B_VMIO) {
2106 bp->b_flags &= ~B_ASYNC;
2107 vfs_vmio_release(bp);
2109 if (bp->b_vp != NULL)
2114 * Get the rest of the buffer freed up. b_kva* is still valid
2115 * after this operation.
2118 if (bp->b_rcred != NOCRED) {
2119 crfree(bp->b_rcred);
2120 bp->b_rcred = NOCRED;
2122 if (bp->b_wcred != NOCRED) {
2123 crfree(bp->b_wcred);
2124 bp->b_wcred = NOCRED;
2126 if (!LIST_EMPTY(&bp->b_dep))
2128 if (bp->b_vflags & BV_BKGRDINPROG)
2129 panic("losing buffer 3");
2130 KASSERT(bp->b_vp == NULL, ("bp: %p still has vnode %p. qindex: %d",
2131 bp, bp->b_vp, qindex));
2132 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
2133 ("bp: %p still on a buffer list. xflags %X", bp, bp->b_xflags));
2138 bp->b_flags &= B_UNMAPPED | B_KVAALLOC;
2141 KASSERT((bp->b_vflags & BV_INFREECNT) == 0,
2142 ("buf %p still counted as free?", bp));
2145 bp->b_blkno = bp->b_lblkno = 0;
2146 bp->b_offset = NOOFFSET;
2152 bp->b_dirtyoff = bp->b_dirtyend = 0;
2153 bp->b_bufobj = NULL;
2154 bp->b_pin_count = 0;
2155 bp->b_fsprivate1 = NULL;
2156 bp->b_fsprivate2 = NULL;
2157 bp->b_fsprivate3 = NULL;
2159 LIST_INIT(&bp->b_dep);
2162 static int flushingbufs;
2165 getnewbuf_scan(int maxsize, int defrag, int unmapped, int metadata)
2167 struct buf *bp, *nbp;
2168 int nqindex, qindex, pass;
2170 KASSERT(!unmapped || !defrag, ("both unmapped and defrag"));
2174 atomic_add_int(&getnewbufrestarts, 1);
2177 * Setup for scan. If we do not have enough free buffers,
2178 * we setup a degenerate case that immediately fails. Note
2179 * that if we are specially marked process, we are allowed to
2180 * dip into our reserves.
2182 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
2183 * for the allocation of the mapped buffer. For unmapped, the
2184 * easiest is to start with EMPTY outright.
2186 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
2187 * However, there are a number of cases (defragging, reusing, ...)
2188 * where we cannot backup.
2192 if (!defrag && unmapped) {
2193 nqindex = QUEUE_EMPTY;
2194 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
2197 nqindex = QUEUE_EMPTYKVA;
2198 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
2202 * If no EMPTYKVA buffers and we are either defragging or
2203 * reusing, locate a CLEAN buffer to free or reuse. If
2204 * bufspace useage is low skip this step so we can allocate a
2207 if (nbp == NULL && (defrag || bufspace >= lobufspace)) {
2208 nqindex = QUEUE_CLEAN;
2209 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2213 * If we could not find or were not allowed to reuse a CLEAN
2214 * buffer, check to see if it is ok to use an EMPTY buffer.
2215 * We can only use an EMPTY buffer if allocating its KVA would
2216 * not otherwise run us out of buffer space. No KVA is needed
2217 * for the unmapped allocation.
2219 if (nbp == NULL && defrag == 0 && (bufspace + maxsize < hibufspace ||
2221 nqindex = QUEUE_EMPTY;
2222 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
2226 * All available buffers might be clean, retry ignoring the
2227 * lobufspace as the last resort.
2229 if (nbp == NULL && !TAILQ_EMPTY(&bufqueues[QUEUE_CLEAN])) {
2230 nqindex = QUEUE_CLEAN;
2231 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2235 * Run scan, possibly freeing data and/or kva mappings on the fly
2238 while ((bp = nbp) != NULL) {
2242 * Calculate next bp (we can only use it if we do not
2243 * block or do other fancy things).
2245 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
2248 nqindex = QUEUE_EMPTYKVA;
2249 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
2253 case QUEUE_EMPTYKVA:
2254 nqindex = QUEUE_CLEAN;
2255 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2260 if (metadata && pass == 1) {
2262 nqindex = QUEUE_EMPTY;
2264 &bufqueues[QUEUE_EMPTY]);
2273 * If we are defragging then we need a buffer with
2274 * b_kvasize != 0. XXX this situation should no longer
2275 * occur, if defrag is non-zero the buffer's b_kvasize
2276 * should also be non-zero at this point. XXX
2278 if (defrag && bp->b_kvasize == 0) {
2279 printf("Warning: defrag empty buffer %p\n", bp);
2284 * Start freeing the bp. This is somewhat involved. nbp
2285 * remains valid only for QUEUE_EMPTY[KVA] bp's.
2287 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2290 BO_LOCK(bp->b_bufobj);
2291 if (bp->b_vflags & BV_BKGRDINPROG) {
2292 BO_UNLOCK(bp->b_bufobj);
2296 BO_UNLOCK(bp->b_bufobj);
2299 KASSERT(bp->b_qindex == qindex,
2300 ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
2302 if (bp->b_bufobj != NULL)
2303 BO_LOCK(bp->b_bufobj);
2305 if (bp->b_bufobj != NULL)
2306 BO_UNLOCK(bp->b_bufobj);
2307 mtx_unlock(&bqlock);
2309 * NOTE: nbp is now entirely invalid. We can only restart
2310 * the scan from this point on.
2313 getnewbuf_reuse_bp(bp, qindex);
2314 mtx_assert(&bqlock, MA_NOTOWNED);
2317 * If we are defragging then free the buffer.
2320 bp->b_flags |= B_INVAL;
2328 * Notify any waiters for the buffer lock about
2329 * identity change by freeing the buffer.
2331 if (qindex == QUEUE_CLEAN && BUF_LOCKWAITERS(bp)) {
2332 bp->b_flags |= B_INVAL;
2342 * If we are overcomitted then recover the buffer and its
2343 * KVM space. This occurs in rare situations when multiple
2344 * processes are blocked in getnewbuf() or allocbuf().
2346 if (bufspace >= hibufspace)
2348 if (flushingbufs && bp->b_kvasize != 0) {
2349 bp->b_flags |= B_INVAL;
2354 if (bufspace < lobufspace)
2364 * Find and initialize a new buffer header, freeing up existing buffers
2365 * in the bufqueues as necessary. The new buffer is returned locked.
2367 * Important: B_INVAL is not set. If the caller wishes to throw the
2368 * buffer away, the caller must set B_INVAL prior to calling brelse().
2371 * We have insufficient buffer headers
2372 * We have insufficient buffer space
2373 * buffer_map is too fragmented ( space reservation fails )
2374 * If we have to flush dirty buffers ( but we try to avoid this )
2376 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
2377 * Instead we ask the buf daemon to do it for us. We attempt to
2378 * avoid piecemeal wakeups of the pageout daemon.
2381 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int size, int maxsize,
2385 int defrag, metadata;
2387 KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
2388 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
2389 if (!unmapped_buf_allowed)
2390 gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC);
2393 if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 ||
2399 * We can't afford to block since we might be holding a vnode lock,
2400 * which may prevent system daemons from running. We deal with
2401 * low-memory situations by proactively returning memory and running
2402 * async I/O rather then sync I/O.
2404 atomic_add_int(&getnewbufcalls, 1);
2405 atomic_subtract_int(&getnewbufrestarts, 1);
2407 bp = getnewbuf_scan(maxsize, defrag, (gbflags & (GB_UNMAPPED |
2408 GB_KVAALLOC)) == GB_UNMAPPED, metadata);
2413 * If we exhausted our list, sleep as appropriate. We may have to
2414 * wakeup various daemons and write out some dirty buffers.
2416 * Generally we are sleeping due to insufficient buffer space.
2419 mtx_assert(&bqlock, MA_OWNED);
2420 getnewbuf_bufd_help(vp, gbflags, slpflag, slptimeo, defrag);
2421 mtx_assert(&bqlock, MA_NOTOWNED);
2422 } else if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == GB_UNMAPPED) {
2423 mtx_assert(&bqlock, MA_NOTOWNED);
2426 bp->b_flags |= B_UNMAPPED;
2427 bp->b_kvabase = bp->b_data = unmapped_buf;
2428 bp->b_kvasize = maxsize;
2429 atomic_add_long(&bufspace, bp->b_kvasize);
2430 atomic_add_long(&unmapped_bufspace, bp->b_kvasize);
2431 atomic_add_int(&bufreusecnt, 1);
2433 mtx_assert(&bqlock, MA_NOTOWNED);
2436 * We finally have a valid bp. We aren't quite out of the
2437 * woods, we still have to reserve kva space. In order
2438 * to keep fragmentation sane we only allocate kva in
2441 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2443 if (maxsize != bp->b_kvasize || (bp->b_flags & (B_UNMAPPED |
2444 B_KVAALLOC)) == B_UNMAPPED) {
2445 if (allocbufkva(bp, maxsize, gbflags)) {
2447 bp->b_flags |= B_INVAL;
2451 atomic_add_int(&bufreusecnt, 1);
2452 } else if ((bp->b_flags & B_KVAALLOC) != 0 &&
2453 (gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == 0) {
2455 * If the reused buffer has KVA allocated,
2456 * reassign b_kvaalloc to b_kvabase.
2458 bp->b_kvabase = bp->b_kvaalloc;
2459 bp->b_flags &= ~B_KVAALLOC;
2460 atomic_subtract_long(&unmapped_bufspace,
2462 atomic_add_int(&bufreusecnt, 1);
2463 } else if ((bp->b_flags & (B_UNMAPPED | B_KVAALLOC)) == 0 &&
2464 (gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == (GB_UNMAPPED |
2467 * The case of reused buffer already have KVA
2468 * mapped, but the request is for unmapped
2469 * buffer with KVA allocated.
2471 bp->b_kvaalloc = bp->b_kvabase;
2472 bp->b_data = bp->b_kvabase = unmapped_buf;
2473 bp->b_flags |= B_UNMAPPED | B_KVAALLOC;
2474 atomic_add_long(&unmapped_bufspace,
2476 atomic_add_int(&bufreusecnt, 1);
2478 if ((gbflags & GB_UNMAPPED) == 0) {
2479 bp->b_saveaddr = bp->b_kvabase;
2480 bp->b_data = bp->b_saveaddr;
2481 bp->b_flags &= ~B_UNMAPPED;
2482 BUF_CHECK_MAPPED(bp);
2491 * buffer flushing daemon. Buffers are normally flushed by the
2492 * update daemon but if it cannot keep up this process starts to
2493 * take the load in an attempt to prevent getnewbuf() from blocking.
2496 static struct kproc_desc buf_kp = {
2501 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
2504 buf_do_flush(struct vnode *vp)
2508 flushed = flushbufqueues(vp, QUEUE_DIRTY, 0);
2511 * Could not find any buffers without rollback
2512 * dependencies, so just write the first one
2513 * in the hopes of eventually making progress.
2515 flushbufqueues(vp, QUEUE_DIRTY, 1);
2526 * This process needs to be suspended prior to shutdown sync.
2528 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2532 * This process is allowed to take the buffer cache to the limit
2534 curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
2538 mtx_unlock(&bdlock);
2540 kproc_suspend_check(bufdaemonproc);
2541 lodirtysave = lodirtybuffers;
2542 if (bd_speedupreq) {
2543 lodirtybuffers = numdirtybuffers / 2;
2547 * Do the flush. Limit the amount of in-transit I/O we
2548 * allow to build up, otherwise we would completely saturate
2549 * the I/O system. Wakeup any waiting processes before we
2550 * normally would so they can run in parallel with our drain.
2552 while (numdirtybuffers > lodirtybuffers) {
2553 if (buf_do_flush(NULL) == 0)
2555 kern_yield(PRI_USER);
2557 lodirtybuffers = lodirtysave;
2560 * Only clear bd_request if we have reached our low water
2561 * mark. The buf_daemon normally waits 1 second and
2562 * then incrementally flushes any dirty buffers that have
2563 * built up, within reason.
2565 * If we were unable to hit our low water mark and couldn't
2566 * find any flushable buffers, we sleep half a second.
2567 * Otherwise we loop immediately.
2570 if (numdirtybuffers <= lodirtybuffers) {
2572 * We reached our low water mark, reset the
2573 * request and sleep until we are needed again.
2574 * The sleep is just so the suspend code works.
2577 msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2580 * We couldn't find any flushable dirty buffers but
2581 * still have too many dirty buffers, we
2582 * have to sleep and try again. (rare)
2584 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2592 * Try to flush a buffer in the dirty queue. We must be careful to
2593 * free up B_INVAL buffers instead of write them, which NFS is
2594 * particularly sensitive to.
2596 static int flushwithdeps = 0;
2597 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2598 0, "Number of buffers flushed with dependecies that require rollbacks");
2601 flushbufqueues(struct vnode *lvp, int queue, int flushdeps)
2603 struct buf *sentinel;
2612 target = numdirtybuffers - lodirtybuffers;
2613 if (flushdeps && target > 2)
2616 target = flushbufqtarget;
2619 sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
2620 sentinel->b_qindex = QUEUE_SENTINEL;
2622 TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
2623 while (flushed != target) {
2624 bp = TAILQ_NEXT(sentinel, b_freelist);
2626 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2627 TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
2632 * Skip sentinels inserted by other invocations of the
2633 * flushbufqueues(), taking care to not reorder them.
2635 if (bp->b_qindex == QUEUE_SENTINEL)
2638 * Only flush the buffers that belong to the
2639 * vnode locked by the curthread.
2641 if (lvp != NULL && bp->b_vp != lvp)
2643 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2645 if (bp->b_pin_count > 0) {
2649 BO_LOCK(bp->b_bufobj);
2650 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2651 (bp->b_flags & B_DELWRI) == 0) {
2652 BO_UNLOCK(bp->b_bufobj);
2656 BO_UNLOCK(bp->b_bufobj);
2657 if (bp->b_flags & B_INVAL) {
2659 mtx_unlock(&bqlock);
2662 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2667 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
2668 if (flushdeps == 0) {
2676 * We must hold the lock on a vnode before writing
2677 * one of its buffers. Otherwise we may confuse, or
2678 * in the case of a snapshot vnode, deadlock the
2681 * The lock order here is the reverse of the normal
2682 * of vnode followed by buf lock. This is ok because
2683 * the NOWAIT will prevent deadlock.
2686 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2690 if (vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT | LK_CANRECURSE) == 0) {
2691 mtx_unlock(&bqlock);
2692 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2693 bp, bp->b_vp, bp->b_flags);
2694 if (curproc == bufdaemonproc)
2701 vn_finished_write(mp);
2703 flushwithdeps += hasdeps;
2707 * Sleeping on runningbufspace while holding
2708 * vnode lock leads to deadlock.
2710 if (curproc == bufdaemonproc)
2711 waitrunningbufspace();
2712 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2716 vn_finished_write(mp);
2719 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2720 mtx_unlock(&bqlock);
2721 free(sentinel, M_TEMP);
2726 * Check to see if a block is currently memory resident.
2729 incore(struct bufobj *bo, daddr_t blkno)
2734 bp = gbincore(bo, blkno);
2740 * Returns true if no I/O is needed to access the
2741 * associated VM object. This is like incore except
2742 * it also hunts around in the VM system for the data.
2746 inmem(struct vnode * vp, daddr_t blkno)
2749 vm_offset_t toff, tinc, size;
2753 ASSERT_VOP_LOCKED(vp, "inmem");
2755 if (incore(&vp->v_bufobj, blkno))
2757 if (vp->v_mount == NULL)
2764 if (size > vp->v_mount->mnt_stat.f_iosize)
2765 size = vp->v_mount->mnt_stat.f_iosize;
2766 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2768 VM_OBJECT_WLOCK(obj);
2769 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2770 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2774 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2775 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2776 if (vm_page_is_valid(m,
2777 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2780 VM_OBJECT_WUNLOCK(obj);
2784 VM_OBJECT_WUNLOCK(obj);
2789 * Set the dirty range for a buffer based on the status of the dirty
2790 * bits in the pages comprising the buffer. The range is limited
2791 * to the size of the buffer.
2793 * Tell the VM system that the pages associated with this buffer
2794 * are clean. This is used for delayed writes where the data is
2795 * going to go to disk eventually without additional VM intevention.
2797 * Note that while we only really need to clean through to b_bcount, we
2798 * just go ahead and clean through to b_bufsize.
2801 vfs_clean_pages_dirty_buf(struct buf *bp)
2803 vm_ooffset_t foff, noff, eoff;
2807 if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
2810 foff = bp->b_offset;
2811 KASSERT(bp->b_offset != NOOFFSET,
2812 ("vfs_clean_pages_dirty_buf: no buffer offset"));
2814 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
2815 vfs_drain_busy_pages(bp);
2816 vfs_setdirty_locked_object(bp);
2817 for (i = 0; i < bp->b_npages; i++) {
2818 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2820 if (eoff > bp->b_offset + bp->b_bufsize)
2821 eoff = bp->b_offset + bp->b_bufsize;
2823 vfs_page_set_validclean(bp, foff, m);
2824 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
2827 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
2831 vfs_setdirty_locked_object(struct buf *bp)
2836 object = bp->b_bufobj->bo_object;
2837 VM_OBJECT_ASSERT_WLOCKED(object);
2840 * We qualify the scan for modified pages on whether the
2841 * object has been flushed yet.
2843 if ((object->flags & OBJ_MIGHTBEDIRTY) != 0) {
2844 vm_offset_t boffset;
2845 vm_offset_t eoffset;
2848 * test the pages to see if they have been modified directly
2849 * by users through the VM system.
2851 for (i = 0; i < bp->b_npages; i++)
2852 vm_page_test_dirty(bp->b_pages[i]);
2855 * Calculate the encompassing dirty range, boffset and eoffset,
2856 * (eoffset - boffset) bytes.
2859 for (i = 0; i < bp->b_npages; i++) {
2860 if (bp->b_pages[i]->dirty)
2863 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2865 for (i = bp->b_npages - 1; i >= 0; --i) {
2866 if (bp->b_pages[i]->dirty) {
2870 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2873 * Fit it to the buffer.
2876 if (eoffset > bp->b_bcount)
2877 eoffset = bp->b_bcount;
2880 * If we have a good dirty range, merge with the existing
2884 if (boffset < eoffset) {
2885 if (bp->b_dirtyoff > boffset)
2886 bp->b_dirtyoff = boffset;
2887 if (bp->b_dirtyend < eoffset)
2888 bp->b_dirtyend = eoffset;
2894 * Allocate the KVA mapping for an existing buffer. It handles the
2895 * cases of both B_UNMAPPED buffer, and buffer with the preallocated
2896 * KVA which is not mapped (B_KVAALLOC).
2899 bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags)
2901 struct buf *scratch_bp;
2902 int bsize, maxsize, need_mapping, need_kva;
2905 need_mapping = (bp->b_flags & B_UNMAPPED) != 0 &&
2906 (gbflags & GB_UNMAPPED) == 0;
2907 need_kva = (bp->b_flags & (B_KVAALLOC | B_UNMAPPED)) == B_UNMAPPED &&
2908 (gbflags & GB_KVAALLOC) != 0;
2909 if (!need_mapping && !need_kva)
2912 BUF_CHECK_UNMAPPED(bp);
2914 if (need_mapping && (bp->b_flags & B_KVAALLOC) != 0) {
2916 * Buffer is not mapped, but the KVA was already
2917 * reserved at the time of the instantiation. Use the
2920 bp->b_flags &= ~B_KVAALLOC;
2921 KASSERT(bp->b_kvaalloc != 0, ("kvaalloc == 0"));
2922 bp->b_kvabase = bp->b_kvaalloc;
2923 atomic_subtract_long(&unmapped_bufspace, bp->b_kvasize);
2928 * Calculate the amount of the address space we would reserve
2929 * if the buffer was mapped.
2931 bsize = vn_isdisk(bp->b_vp, NULL) ? DEV_BSIZE : bp->b_bufobj->bo_bsize;
2932 offset = blkno * bsize;
2933 maxsize = size + (offset & PAGE_MASK);
2934 maxsize = imax(maxsize, bsize);
2937 if (allocbufkva(bp, maxsize, gbflags)) {
2939 * Request defragmentation. getnewbuf() returns us the
2940 * allocated space by the scratch buffer KVA.
2942 scratch_bp = getnewbuf(bp->b_vp, 0, 0, size, maxsize, gbflags |
2943 (GB_UNMAPPED | GB_KVAALLOC));
2944 if (scratch_bp == NULL) {
2945 if ((gbflags & GB_NOWAIT_BD) != 0) {
2947 * XXXKIB: defragmentation cannot
2948 * succeed, not sure what else to do.
2950 panic("GB_NOWAIT_BD and B_UNMAPPED %p", bp);
2952 atomic_add_int(&mappingrestarts, 1);
2955 KASSERT((scratch_bp->b_flags & B_KVAALLOC) != 0,
2956 ("scratch bp !B_KVAALLOC %p", scratch_bp));
2957 setbufkva(bp, (vm_offset_t)scratch_bp->b_kvaalloc,
2958 scratch_bp->b_kvasize, gbflags);
2960 /* Get rid of the scratch buffer. */
2961 scratch_bp->b_kvasize = 0;
2962 scratch_bp->b_flags |= B_INVAL;
2963 scratch_bp->b_flags &= ~(B_UNMAPPED | B_KVAALLOC);
2970 bp->b_saveaddr = bp->b_kvabase;
2971 bp->b_data = bp->b_saveaddr; /* b_offset is handled by bpmap_qenter */
2972 bp->b_flags &= ~B_UNMAPPED;
2973 BUF_CHECK_MAPPED(bp);
2980 * Get a block given a specified block and offset into a file/device.
2981 * The buffers B_DONE bit will be cleared on return, making it almost
2982 * ready for an I/O initiation. B_INVAL may or may not be set on
2983 * return. The caller should clear B_INVAL prior to initiating a
2986 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2987 * an existing buffer.
2989 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2990 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2991 * and then cleared based on the backing VM. If the previous buffer is
2992 * non-0-sized but invalid, B_CACHE will be cleared.
2994 * If getblk() must create a new buffer, the new buffer is returned with
2995 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2996 * case it is returned with B_INVAL clear and B_CACHE set based on the
2999 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
3000 * B_CACHE bit is clear.
3002 * What this means, basically, is that the caller should use B_CACHE to
3003 * determine whether the buffer is fully valid or not and should clear
3004 * B_INVAL prior to issuing a read. If the caller intends to validate
3005 * the buffer by loading its data area with something, the caller needs
3006 * to clear B_INVAL. If the caller does this without issuing an I/O,
3007 * the caller should set B_CACHE ( as an optimization ), else the caller
3008 * should issue the I/O and biodone() will set B_CACHE if the I/O was
3009 * a write attempt or if it was a successfull read. If the caller
3010 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
3011 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
3014 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo,
3019 int bsize, error, maxsize, vmio;
3022 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
3023 KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3024 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3025 ASSERT_VOP_LOCKED(vp, "getblk");
3026 if (size > MAXBSIZE)
3027 panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
3028 if (!unmapped_buf_allowed)
3029 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3034 * Block if we are low on buffers. Certain processes are allowed
3035 * to completely exhaust the buffer cache.
3037 * If this check ever becomes a bottleneck it may be better to
3038 * move it into the else, when gbincore() fails. At the moment
3039 * it isn't a problem.
3041 if (numfreebuffers == 0) {
3042 if (TD_IS_IDLETHREAD(curthread))
3045 needsbuffer |= VFS_BIO_NEED_ANY;
3046 mtx_unlock(&nblock);
3050 bp = gbincore(bo, blkno);
3054 * Buffer is in-core. If the buffer is not busy nor managed,
3055 * it must be on a queue.
3057 lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
3059 if (flags & GB_LOCK_NOWAIT)
3060 lockflags |= LK_NOWAIT;
3062 error = BUF_TIMELOCK(bp, lockflags,
3063 BO_MTX(bo), "getblk", slpflag, slptimeo);
3066 * If we slept and got the lock we have to restart in case
3067 * the buffer changed identities.
3069 if (error == ENOLCK)
3071 /* We timed out or were interrupted. */
3074 /* If recursed, assume caller knows the rules. */
3075 else if (BUF_LOCKRECURSED(bp))
3079 * The buffer is locked. B_CACHE is cleared if the buffer is
3080 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
3081 * and for a VMIO buffer B_CACHE is adjusted according to the
3084 if (bp->b_flags & B_INVAL)
3085 bp->b_flags &= ~B_CACHE;
3086 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
3087 bp->b_flags |= B_CACHE;
3088 if (bp->b_flags & B_MANAGED)
3089 MPASS(bp->b_qindex == QUEUE_NONE);
3097 * check for size inconsistencies for non-VMIO case.
3099 if (bp->b_bcount != size) {
3100 if ((bp->b_flags & B_VMIO) == 0 ||
3101 (size > bp->b_kvasize)) {
3102 if (bp->b_flags & B_DELWRI) {
3104 * If buffer is pinned and caller does
3105 * not want sleep waiting for it to be
3106 * unpinned, bail out
3108 if (bp->b_pin_count > 0) {
3109 if (flags & GB_LOCK_NOWAIT) {
3116 bp->b_flags |= B_NOCACHE;
3119 if (LIST_EMPTY(&bp->b_dep)) {
3120 bp->b_flags |= B_RELBUF;
3123 bp->b_flags |= B_NOCACHE;
3132 * Handle the case of unmapped buffer which should
3133 * become mapped, or the buffer for which KVA
3134 * reservation is requested.
3136 bp_unmapped_get_kva(bp, blkno, size, flags);
3139 * If the size is inconsistant in the VMIO case, we can resize
3140 * the buffer. This might lead to B_CACHE getting set or
3141 * cleared. If the size has not changed, B_CACHE remains
3142 * unchanged from its previous state.
3144 if (bp->b_bcount != size)
3147 KASSERT(bp->b_offset != NOOFFSET,
3148 ("getblk: no buffer offset"));
3151 * A buffer with B_DELWRI set and B_CACHE clear must
3152 * be committed before we can return the buffer in
3153 * order to prevent the caller from issuing a read
3154 * ( due to B_CACHE not being set ) and overwriting
3157 * Most callers, including NFS and FFS, need this to
3158 * operate properly either because they assume they
3159 * can issue a read if B_CACHE is not set, or because
3160 * ( for example ) an uncached B_DELWRI might loop due
3161 * to softupdates re-dirtying the buffer. In the latter
3162 * case, B_CACHE is set after the first write completes,
3163 * preventing further loops.
3164 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
3165 * above while extending the buffer, we cannot allow the
3166 * buffer to remain with B_CACHE set after the write
3167 * completes or it will represent a corrupt state. To
3168 * deal with this we set B_NOCACHE to scrap the buffer
3171 * We might be able to do something fancy, like setting
3172 * B_CACHE in bwrite() except if B_DELWRI is already set,
3173 * so the below call doesn't set B_CACHE, but that gets real
3174 * confusing. This is much easier.
3177 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
3178 bp->b_flags |= B_NOCACHE;
3182 bp->b_flags &= ~B_DONE;
3185 * Buffer is not in-core, create new buffer. The buffer
3186 * returned by getnewbuf() is locked. Note that the returned
3187 * buffer is also considered valid (not marked B_INVAL).
3191 * If the user does not want us to create the buffer, bail out
3194 if (flags & GB_NOCREAT)
3196 bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
3197 offset = blkno * bsize;
3198 vmio = vp->v_object != NULL;
3200 maxsize = size + (offset & PAGE_MASK);
3203 /* Do not allow non-VMIO notmapped buffers. */
3204 flags &= ~GB_UNMAPPED;
3206 maxsize = imax(maxsize, bsize);
3208 bp = getnewbuf(vp, slpflag, slptimeo, size, maxsize, flags);
3210 if (slpflag || slptimeo)
3216 * This code is used to make sure that a buffer is not
3217 * created while the getnewbuf routine is blocked.
3218 * This can be a problem whether the vnode is locked or not.
3219 * If the buffer is created out from under us, we have to
3220 * throw away the one we just created.
3222 * Note: this must occur before we associate the buffer
3223 * with the vp especially considering limitations in
3224 * the splay tree implementation when dealing with duplicate
3228 if (gbincore(bo, blkno)) {
3230 bp->b_flags |= B_INVAL;
3236 * Insert the buffer into the hash, so that it can
3237 * be found by incore.
3239 bp->b_blkno = bp->b_lblkno = blkno;
3240 bp->b_offset = offset;
3245 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
3246 * buffer size starts out as 0, B_CACHE will be set by
3247 * allocbuf() for the VMIO case prior to it testing the
3248 * backing store for validity.
3252 bp->b_flags |= B_VMIO;
3253 KASSERT(vp->v_object == bp->b_bufobj->bo_object,
3254 ("ARGH! different b_bufobj->bo_object %p %p %p\n",
3255 bp, vp->v_object, bp->b_bufobj->bo_object));
3257 bp->b_flags &= ~B_VMIO;
3258 KASSERT(bp->b_bufobj->bo_object == NULL,
3259 ("ARGH! has b_bufobj->bo_object %p %p\n",
3260 bp, bp->b_bufobj->bo_object));
3261 BUF_CHECK_MAPPED(bp);
3265 bp->b_flags &= ~B_DONE;
3267 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
3268 BUF_ASSERT_HELD(bp);
3270 KASSERT(bp->b_bufobj == bo,
3271 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3276 * Get an empty, disassociated buffer of given size. The buffer is initially
3280 geteblk(int size, int flags)
3285 maxsize = (size + BKVAMASK) & ~BKVAMASK;
3286 while ((bp = getnewbuf(NULL, 0, 0, size, maxsize, flags)) == NULL) {
3287 if ((flags & GB_NOWAIT_BD) &&
3288 (curthread->td_pflags & TDP_BUFNEED) != 0)
3292 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
3293 BUF_ASSERT_HELD(bp);
3299 * This code constitutes the buffer memory from either anonymous system
3300 * memory (in the case of non-VMIO operations) or from an associated
3301 * VM object (in the case of VMIO operations). This code is able to
3302 * resize a buffer up or down.
3304 * Note that this code is tricky, and has many complications to resolve
3305 * deadlock or inconsistant data situations. Tread lightly!!!
3306 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3307 * the caller. Calling this code willy nilly can result in the loss of data.
3309 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
3310 * B_CACHE for the non-VMIO case.
3314 allocbuf(struct buf *bp, int size)
3316 int newbsize, mbsize;
3319 BUF_ASSERT_HELD(bp);
3321 if (bp->b_kvasize < size)
3322 panic("allocbuf: buffer too small");
3324 if ((bp->b_flags & B_VMIO) == 0) {
3328 * Just get anonymous memory from the kernel. Don't
3329 * mess with B_CACHE.
3331 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3332 if (bp->b_flags & B_MALLOC)
3335 newbsize = round_page(size);
3337 if (newbsize < bp->b_bufsize) {
3339 * malloced buffers are not shrunk
3341 if (bp->b_flags & B_MALLOC) {
3343 bp->b_bcount = size;
3345 free(bp->b_data, M_BIOBUF);
3346 if (bp->b_bufsize) {
3347 atomic_subtract_long(
3353 bp->b_saveaddr = bp->b_kvabase;
3354 bp->b_data = bp->b_saveaddr;
3356 bp->b_flags &= ~B_MALLOC;
3360 vm_hold_free_pages(bp, newbsize);
3361 } else if (newbsize > bp->b_bufsize) {
3363 * We only use malloced memory on the first allocation.
3364 * and revert to page-allocated memory when the buffer
3368 * There is a potential smp race here that could lead
3369 * to bufmallocspace slightly passing the max. It
3370 * is probably extremely rare and not worth worrying
3373 if ( (bufmallocspace < maxbufmallocspace) &&
3374 (bp->b_bufsize == 0) &&
3375 (mbsize <= PAGE_SIZE/2)) {
3377 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
3378 bp->b_bufsize = mbsize;
3379 bp->b_bcount = size;
3380 bp->b_flags |= B_MALLOC;
3381 atomic_add_long(&bufmallocspace, mbsize);
3387 * If the buffer is growing on its other-than-first allocation,
3388 * then we revert to the page-allocation scheme.
3390 if (bp->b_flags & B_MALLOC) {
3391 origbuf = bp->b_data;
3392 origbufsize = bp->b_bufsize;
3393 bp->b_data = bp->b_kvabase;
3394 if (bp->b_bufsize) {
3395 atomic_subtract_long(&bufmallocspace,
3400 bp->b_flags &= ~B_MALLOC;
3401 newbsize = round_page(newbsize);
3405 (vm_offset_t) bp->b_data + bp->b_bufsize,
3406 (vm_offset_t) bp->b_data + newbsize);
3408 bcopy(origbuf, bp->b_data, origbufsize);
3409 free(origbuf, M_BIOBUF);
3415 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3416 desiredpages = (size == 0) ? 0 :
3417 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
3419 if (bp->b_flags & B_MALLOC)
3420 panic("allocbuf: VMIO buffer can't be malloced");
3422 * Set B_CACHE initially if buffer is 0 length or will become
3425 if (size == 0 || bp->b_bufsize == 0)
3426 bp->b_flags |= B_CACHE;
3428 if (newbsize < bp->b_bufsize) {
3430 * DEV_BSIZE aligned new buffer size is less then the
3431 * DEV_BSIZE aligned existing buffer size. Figure out
3432 * if we have to remove any pages.
3434 if (desiredpages < bp->b_npages) {
3437 if ((bp->b_flags & B_UNMAPPED) == 0) {
3438 BUF_CHECK_MAPPED(bp);
3439 pmap_qremove((vm_offset_t)trunc_page(
3440 (vm_offset_t)bp->b_data) +
3441 (desiredpages << PAGE_SHIFT),
3442 (bp->b_npages - desiredpages));
3444 BUF_CHECK_UNMAPPED(bp);
3445 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
3446 for (i = desiredpages; i < bp->b_npages; i++) {
3448 * the page is not freed here -- it
3449 * is the responsibility of
3450 * vnode_pager_setsize
3453 KASSERT(m != bogus_page,
3454 ("allocbuf: bogus page found"));
3455 while (vm_page_sleep_if_busy(m, TRUE,
3459 bp->b_pages[i] = NULL;
3461 vm_page_unwire(m, 0);
3464 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
3465 bp->b_npages = desiredpages;
3467 } else if (size > bp->b_bcount) {
3469 * We are growing the buffer, possibly in a
3470 * byte-granular fashion.
3477 * Step 1, bring in the VM pages from the object,
3478 * allocating them if necessary. We must clear
3479 * B_CACHE if these pages are not valid for the
3480 * range covered by the buffer.
3483 obj = bp->b_bufobj->bo_object;
3485 VM_OBJECT_WLOCK(obj);
3486 while (bp->b_npages < desiredpages) {
3490 * We must allocate system pages since blocking
3491 * here could interfere with paging I/O, no
3492 * matter which process we are.
3494 * We can only test VPO_BUSY here. Blocking on
3495 * m->busy might lead to a deadlock:
3496 * vm_fault->getpages->cluster_read->allocbuf
3497 * Thus, we specify VM_ALLOC_IGN_SBUSY.
3499 m = vm_page_grab(obj, OFF_TO_IDX(bp->b_offset) +
3500 bp->b_npages, VM_ALLOC_NOBUSY |
3501 VM_ALLOC_SYSTEM | VM_ALLOC_WIRED |
3502 VM_ALLOC_RETRY | VM_ALLOC_IGN_SBUSY |
3503 VM_ALLOC_COUNT(desiredpages - bp->b_npages));
3505 bp->b_flags &= ~B_CACHE;
3506 bp->b_pages[bp->b_npages] = m;
3511 * Step 2. We've loaded the pages into the buffer,
3512 * we have to figure out if we can still have B_CACHE
3513 * set. Note that B_CACHE is set according to the
3514 * byte-granular range ( bcount and size ), new the
3515 * aligned range ( newbsize ).
3517 * The VM test is against m->valid, which is DEV_BSIZE
3518 * aligned. Needless to say, the validity of the data
3519 * needs to also be DEV_BSIZE aligned. Note that this
3520 * fails with NFS if the server or some other client
3521 * extends the file's EOF. If our buffer is resized,
3522 * B_CACHE may remain set! XXX
3525 toff = bp->b_bcount;
3526 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
3528 while ((bp->b_flags & B_CACHE) && toff < size) {
3531 if (tinc > (size - toff))
3534 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
3547 VM_OBJECT_WUNLOCK(obj);
3550 * Step 3, fixup the KVM pmap.
3552 if ((bp->b_flags & B_UNMAPPED) == 0)
3555 BUF_CHECK_UNMAPPED(bp);
3558 if (newbsize < bp->b_bufsize)
3560 bp->b_bufsize = newbsize; /* actual buffer allocation */
3561 bp->b_bcount = size; /* requested buffer size */
3565 extern int inflight_transient_maps;
3568 biodone(struct bio *bp)
3571 void (*done)(struct bio *);
3572 vm_offset_t start, end;
3575 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3577 bp->bio_flags |= BIO_DONE;
3578 if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) {
3579 start = trunc_page((vm_offset_t)bp->bio_data);
3580 end = round_page((vm_offset_t)bp->bio_data + bp->bio_length);
3586 done = bp->bio_done;
3593 pmap_qremove(start, OFF_TO_IDX(end - start));
3594 vm_map_remove(bio_transient_map, start, end);
3595 atomic_add_int(&inflight_transient_maps, -1);
3600 * Wait for a BIO to finish.
3602 * XXX: resort to a timeout for now. The optimal locking (if any) for this
3603 * case is not yet clear.
3606 biowait(struct bio *bp, const char *wchan)
3610 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3612 while ((bp->bio_flags & BIO_DONE) == 0)
3613 msleep(bp, mtxp, PRIBIO, wchan, hz / 10);
3615 if (bp->bio_error != 0)
3616 return (bp->bio_error);
3617 if (!(bp->bio_flags & BIO_ERROR))
3623 biofinish(struct bio *bp, struct devstat *stat, int error)
3627 bp->bio_error = error;
3628 bp->bio_flags |= BIO_ERROR;
3631 devstat_end_transaction_bio(stat, bp);
3638 * Wait for buffer I/O completion, returning error status. The buffer
3639 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR
3640 * error and cleared.
3643 bufwait(struct buf *bp)
3645 if (bp->b_iocmd == BIO_READ)
3646 bwait(bp, PRIBIO, "biord");
3648 bwait(bp, PRIBIO, "biowr");
3649 if (bp->b_flags & B_EINTR) {
3650 bp->b_flags &= ~B_EINTR;
3653 if (bp->b_ioflags & BIO_ERROR) {
3654 return (bp->b_error ? bp->b_error : EIO);
3661 * Call back function from struct bio back up to struct buf.
3664 bufdonebio(struct bio *bip)
3668 bp = bip->bio_caller2;
3669 bp->b_resid = bp->b_bcount - bip->bio_completed;
3670 bp->b_resid = bip->bio_resid; /* XXX: remove */
3671 bp->b_ioflags = bip->bio_flags;
3672 bp->b_error = bip->bio_error;
3674 bp->b_ioflags |= BIO_ERROR;
3680 dev_strategy(struct cdev *dev, struct buf *bp)
3686 if ((!bp->b_iocmd) || (bp->b_iocmd & (bp->b_iocmd - 1)))
3687 panic("b_iocmd botch");
3692 /* Try again later */
3693 tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3695 bip->bio_cmd = bp->b_iocmd;
3696 bip->bio_offset = bp->b_iooffset;
3697 bip->bio_length = bp->b_bcount;
3698 bip->bio_bcount = bp->b_bcount; /* XXX: remove */
3700 bip->bio_done = bufdonebio;
3701 bip->bio_caller2 = bp;
3703 KASSERT(dev->si_refcount > 0,
3704 ("dev_strategy on un-referenced struct cdev *(%s)",
3706 csw = dev_refthread(dev, &ref);
3709 bp->b_error = ENXIO;
3710 bp->b_ioflags = BIO_ERROR;
3714 (*csw->d_strategy)(bip);
3715 dev_relthread(dev, ref);
3721 * Finish I/O on a buffer, optionally calling a completion function.
3722 * This is usually called from an interrupt so process blocking is
3725 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3726 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3727 * assuming B_INVAL is clear.
3729 * For the VMIO case, we set B_CACHE if the op was a read and no
3730 * read error occured, or if the op was a write. B_CACHE is never
3731 * set if the buffer is invalid or otherwise uncacheable.
3733 * biodone does not mess with B_INVAL, allowing the I/O routine or the
3734 * initiator to leave B_INVAL set to brelse the buffer out of existance
3735 * in the biodone routine.
3738 bufdone(struct buf *bp)
3740 struct bufobj *dropobj;
3741 void (*biodone)(struct buf *);
3743 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3746 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3747 BUF_ASSERT_HELD(bp);
3749 runningbufwakeup(bp);
3750 if (bp->b_iocmd == BIO_WRITE)
3751 dropobj = bp->b_bufobj;
3752 /* call optional completion function if requested */
3753 if (bp->b_iodone != NULL) {
3754 biodone = bp->b_iodone;
3755 bp->b_iodone = NULL;
3758 bufobj_wdrop(dropobj);
3765 bufobj_wdrop(dropobj);
3769 bufdone_finish(struct buf *bp)
3771 BUF_ASSERT_HELD(bp);
3773 if (!LIST_EMPTY(&bp->b_dep))
3776 if (bp->b_flags & B_VMIO) {
3781 int bogus, i, iosize;
3783 obj = bp->b_bufobj->bo_object;
3784 KASSERT(obj->paging_in_progress >= bp->b_npages,
3785 ("biodone_finish: paging in progress(%d) < b_npages(%d)",
3786 obj->paging_in_progress, bp->b_npages));
3789 KASSERT(vp->v_holdcnt > 0,
3790 ("biodone_finish: vnode %p has zero hold count", vp));
3791 KASSERT(vp->v_object != NULL,
3792 ("biodone_finish: vnode %p has no vm_object", vp));
3794 foff = bp->b_offset;
3795 KASSERT(bp->b_offset != NOOFFSET,
3796 ("biodone_finish: bp %p has no buffer offset", bp));
3799 * Set B_CACHE if the op was a normal read and no error
3800 * occured. B_CACHE is set for writes in the b*write()
3803 iosize = bp->b_bcount - bp->b_resid;
3804 if (bp->b_iocmd == BIO_READ &&
3805 !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3806 !(bp->b_ioflags & BIO_ERROR)) {
3807 bp->b_flags |= B_CACHE;
3810 VM_OBJECT_WLOCK(obj);
3811 for (i = 0; i < bp->b_npages; i++) {
3815 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3820 * cleanup bogus pages, restoring the originals
3823 if (m == bogus_page) {
3824 bogus = bogusflag = 1;
3825 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3827 panic("biodone: page disappeared!");
3830 KASSERT(OFF_TO_IDX(foff) == m->pindex,
3831 ("biodone_finish: foff(%jd)/pindex(%ju) mismatch",
3832 (intmax_t)foff, (uintmax_t)m->pindex));
3835 * In the write case, the valid and clean bits are
3836 * already changed correctly ( see bdwrite() ), so we
3837 * only need to do this here in the read case.
3839 if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3840 KASSERT((m->dirty & vm_page_bits(foff &
3841 PAGE_MASK, resid)) == 0, ("bufdone_finish:"
3842 " page %p has unexpected dirty bits", m));
3843 vfs_page_set_valid(bp, foff, m);
3846 vm_page_io_finish(m);
3847 vm_object_pip_subtract(obj, 1);
3848 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3851 vm_object_pip_wakeupn(obj, 0);
3852 VM_OBJECT_WUNLOCK(obj);
3853 if (bogus && (bp->b_flags & B_UNMAPPED) == 0) {
3854 BUF_CHECK_MAPPED(bp);
3855 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3856 bp->b_pages, bp->b_npages);
3861 * For asynchronous completions, release the buffer now. The brelse
3862 * will do a wakeup there if necessary - so no need to do a wakeup
3863 * here in the async case. The sync case always needs to do a wakeup.
3866 if (bp->b_flags & B_ASYNC) {
3867 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3876 * This routine is called in lieu of iodone in the case of
3877 * incomplete I/O. This keeps the busy status for pages
3881 vfs_unbusy_pages(struct buf *bp)
3887 runningbufwakeup(bp);
3888 if (!(bp->b_flags & B_VMIO))
3891 obj = bp->b_bufobj->bo_object;
3892 VM_OBJECT_WLOCK(obj);
3893 for (i = 0; i < bp->b_npages; i++) {
3895 if (m == bogus_page) {
3896 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3898 panic("vfs_unbusy_pages: page missing\n");
3900 if ((bp->b_flags & B_UNMAPPED) == 0) {
3901 BUF_CHECK_MAPPED(bp);
3902 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3903 bp->b_pages, bp->b_npages);
3905 BUF_CHECK_UNMAPPED(bp);
3907 vm_object_pip_subtract(obj, 1);
3908 vm_page_io_finish(m);
3910 vm_object_pip_wakeupn(obj, 0);
3911 VM_OBJECT_WUNLOCK(obj);
3915 * vfs_page_set_valid:
3917 * Set the valid bits in a page based on the supplied offset. The
3918 * range is restricted to the buffer's size.
3920 * This routine is typically called after a read completes.
3923 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3928 * Compute the end offset, eoff, such that [off, eoff) does not span a
3929 * page boundary and eoff is not greater than the end of the buffer.
3930 * The end of the buffer, in this case, is our file EOF, not the
3931 * allocation size of the buffer.
3933 eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
3934 if (eoff > bp->b_offset + bp->b_bcount)
3935 eoff = bp->b_offset + bp->b_bcount;
3938 * Set valid range. This is typically the entire buffer and thus the
3942 vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off);
3946 * vfs_page_set_validclean:
3948 * Set the valid bits and clear the dirty bits in a page based on the
3949 * supplied offset. The range is restricted to the buffer's size.
3952 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3954 vm_ooffset_t soff, eoff;
3957 * Start and end offsets in buffer. eoff - soff may not cross a
3958 * page boundry or cross the end of the buffer. The end of the
3959 * buffer, in this case, is our file EOF, not the allocation size
3963 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3964 if (eoff > bp->b_offset + bp->b_bcount)
3965 eoff = bp->b_offset + bp->b_bcount;
3968 * Set valid range. This is typically the entire buffer and thus the
3972 vm_page_set_validclean(
3974 (vm_offset_t) (soff & PAGE_MASK),
3975 (vm_offset_t) (eoff - soff)
3981 * Ensure that all buffer pages are not busied by VPO_BUSY flag. If
3982 * any page is busy, drain the flag.
3985 vfs_drain_busy_pages(struct buf *bp)
3990 VM_OBJECT_ASSERT_WLOCKED(bp->b_bufobj->bo_object);
3992 for (i = 0; i < bp->b_npages; i++) {
3994 if ((m->oflags & VPO_BUSY) != 0) {
3995 for (; last_busied < i; last_busied++)
3996 vm_page_busy(bp->b_pages[last_busied]);
3997 while ((m->oflags & VPO_BUSY) != 0)
3998 vm_page_sleep(m, "vbpage");
4001 for (i = 0; i < last_busied; i++)
4002 vm_page_wakeup(bp->b_pages[i]);
4006 * This routine is called before a device strategy routine.
4007 * It is used to tell the VM system that paging I/O is in
4008 * progress, and treat the pages associated with the buffer
4009 * almost as being VPO_BUSY. Also the object paging_in_progress
4010 * flag is handled to make sure that the object doesn't become
4013 * Since I/O has not been initiated yet, certain buffer flags
4014 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
4015 * and should be ignored.
4018 vfs_busy_pages(struct buf *bp, int clear_modify)
4025 if (!(bp->b_flags & B_VMIO))
4028 obj = bp->b_bufobj->bo_object;
4029 foff = bp->b_offset;
4030 KASSERT(bp->b_offset != NOOFFSET,
4031 ("vfs_busy_pages: no buffer offset"));
4032 VM_OBJECT_WLOCK(obj);
4033 vfs_drain_busy_pages(bp);
4034 if (bp->b_bufsize != 0)
4035 vfs_setdirty_locked_object(bp);
4037 for (i = 0; i < bp->b_npages; i++) {
4040 if ((bp->b_flags & B_CLUSTER) == 0) {
4041 vm_object_pip_add(obj, 1);
4042 vm_page_io_start(m);
4045 * When readying a buffer for a read ( i.e
4046 * clear_modify == 0 ), it is important to do
4047 * bogus_page replacement for valid pages in
4048 * partially instantiated buffers. Partially
4049 * instantiated buffers can, in turn, occur when
4050 * reconstituting a buffer from its VM backing store
4051 * base. We only have to do this if B_CACHE is
4052 * clear ( which causes the I/O to occur in the
4053 * first place ). The replacement prevents the read
4054 * I/O from overwriting potentially dirty VM-backed
4055 * pages. XXX bogus page replacement is, uh, bogus.
4056 * It may not work properly with small-block devices.
4057 * We need to find a better way.
4060 pmap_remove_write(m);
4061 vfs_page_set_validclean(bp, foff, m);
4062 } else if (m->valid == VM_PAGE_BITS_ALL &&
4063 (bp->b_flags & B_CACHE) == 0) {
4064 bp->b_pages[i] = bogus_page;
4067 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4069 VM_OBJECT_WUNLOCK(obj);
4070 if (bogus && (bp->b_flags & B_UNMAPPED) == 0) {
4071 BUF_CHECK_MAPPED(bp);
4072 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4073 bp->b_pages, bp->b_npages);
4078 * vfs_bio_set_valid:
4080 * Set the range within the buffer to valid. The range is
4081 * relative to the beginning of the buffer, b_offset. Note that
4082 * b_offset itself may be offset from the beginning of the first
4086 vfs_bio_set_valid(struct buf *bp, int base, int size)
4091 if (!(bp->b_flags & B_VMIO))
4095 * Fixup base to be relative to beginning of first page.
4096 * Set initial n to be the maximum number of bytes in the
4097 * first page that can be validated.
4099 base += (bp->b_offset & PAGE_MASK);
4100 n = PAGE_SIZE - (base & PAGE_MASK);
4102 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4103 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4107 vm_page_set_valid_range(m, base & PAGE_MASK, n);
4112 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4118 * If the specified buffer is a non-VMIO buffer, clear the entire
4119 * buffer. If the specified buffer is a VMIO buffer, clear and
4120 * validate only the previously invalid portions of the buffer.
4121 * This routine essentially fakes an I/O, so we need to clear
4122 * BIO_ERROR and B_INVAL.
4124 * Note that while we only theoretically need to clear through b_bcount,
4125 * we go ahead and clear through b_bufsize.
4128 vfs_bio_clrbuf(struct buf *bp)
4130 int i, j, mask, sa, ea, slide;
4132 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
4136 bp->b_flags &= ~B_INVAL;
4137 bp->b_ioflags &= ~BIO_ERROR;
4138 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4139 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4140 (bp->b_offset & PAGE_MASK) == 0) {
4141 if (bp->b_pages[0] == bogus_page)
4143 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4144 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[0]->object);
4145 if ((bp->b_pages[0]->valid & mask) == mask)
4147 if ((bp->b_pages[0]->valid & mask) == 0) {
4148 pmap_zero_page_area(bp->b_pages[0], 0, bp->b_bufsize);
4149 bp->b_pages[0]->valid |= mask;
4153 sa = bp->b_offset & PAGE_MASK;
4155 for (i = 0; i < bp->b_npages; i++, sa = 0) {
4156 slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize);
4157 ea = slide & PAGE_MASK;
4160 if (bp->b_pages[i] == bogus_page)
4163 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4164 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[i]->object);
4165 if ((bp->b_pages[i]->valid & mask) == mask)
4167 if ((bp->b_pages[i]->valid & mask) == 0)
4168 pmap_zero_page_area(bp->b_pages[i], sa, ea - sa);
4170 for (; sa < ea; sa += DEV_BSIZE, j++) {
4171 if ((bp->b_pages[i]->valid & (1 << j)) == 0) {
4172 pmap_zero_page_area(bp->b_pages[i],
4177 bp->b_pages[i]->valid |= mask;
4180 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4185 vfs_bio_bzero_buf(struct buf *bp, int base, int size)
4190 if ((bp->b_flags & B_UNMAPPED) == 0) {
4191 BUF_CHECK_MAPPED(bp);
4192 bzero(bp->b_data + base, size);
4194 BUF_CHECK_UNMAPPED(bp);
4195 n = PAGE_SIZE - (base & PAGE_MASK);
4196 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4197 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4201 pmap_zero_page_area(m, base & PAGE_MASK, n);
4206 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4211 * vm_hold_load_pages and vm_hold_free_pages get pages into
4212 * a buffers address space. The pages are anonymous and are
4213 * not associated with a file object.
4216 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4222 BUF_CHECK_MAPPED(bp);
4224 to = round_page(to);
4225 from = round_page(from);
4226 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4228 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4231 * note: must allocate system pages since blocking here
4232 * could interfere with paging I/O, no matter which
4235 p = vm_page_alloc(NULL, 0, VM_ALLOC_SYSTEM | VM_ALLOC_NOOBJ |
4236 VM_ALLOC_WIRED | VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT));
4241 pmap_qenter(pg, &p, 1);
4242 bp->b_pages[index] = p;
4244 bp->b_npages = index;
4247 /* Return pages associated with this buf to the vm system */
4249 vm_hold_free_pages(struct buf *bp, int newbsize)
4253 int index, newnpages;
4255 BUF_CHECK_MAPPED(bp);
4257 from = round_page((vm_offset_t)bp->b_data + newbsize);
4258 newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4259 if (bp->b_npages > newnpages)
4260 pmap_qremove(from, bp->b_npages - newnpages);
4261 for (index = newnpages; index < bp->b_npages; index++) {
4262 p = bp->b_pages[index];
4263 bp->b_pages[index] = NULL;
4265 printf("vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
4266 (intmax_t)bp->b_blkno, (intmax_t)bp->b_lblkno);
4269 atomic_subtract_int(&cnt.v_wire_count, 1);
4271 bp->b_npages = newnpages;
4275 * Map an IO request into kernel virtual address space.
4277 * All requests are (re)mapped into kernel VA space.
4278 * Notice that we use b_bufsize for the size of the buffer
4279 * to be mapped. b_bcount might be modified by the driver.
4281 * Note that even if the caller determines that the address space should
4282 * be valid, a race or a smaller-file mapped into a larger space may
4283 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
4284 * check the return value.
4287 vmapbuf(struct buf *bp, int mapbuf)
4293 if (bp->b_bufsize < 0)
4295 prot = VM_PROT_READ;
4296 if (bp->b_iocmd == BIO_READ)
4297 prot |= VM_PROT_WRITE; /* Less backwards than it looks */
4298 if ((pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
4299 (vm_offset_t)bp->b_data, bp->b_bufsize, prot, bp->b_pages,
4300 btoc(MAXPHYS))) < 0)
4302 bp->b_npages = pidx;
4303 if (mapbuf || !unmapped_buf_allowed) {
4304 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
4305 kva = bp->b_saveaddr;
4306 bp->b_saveaddr = bp->b_data;
4307 bp->b_data = kva + (((vm_offset_t)bp->b_data) & PAGE_MASK);
4308 bp->b_flags &= ~B_UNMAPPED;
4310 bp->b_flags |= B_UNMAPPED;
4311 bp->b_offset = ((vm_offset_t)bp->b_data) & PAGE_MASK;
4312 bp->b_saveaddr = bp->b_data;
4313 bp->b_data = unmapped_buf;
4319 * Free the io map PTEs associated with this IO operation.
4320 * We also invalidate the TLB entries and restore the original b_addr.
4323 vunmapbuf(struct buf *bp)
4327 npages = bp->b_npages;
4328 if (bp->b_flags & B_UNMAPPED)
4329 bp->b_flags &= ~B_UNMAPPED;
4331 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4332 vm_page_unhold_pages(bp->b_pages, npages);
4334 bp->b_data = bp->b_saveaddr;
4338 bdone(struct buf *bp)
4342 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4344 bp->b_flags |= B_DONE;
4350 bwait(struct buf *bp, u_char pri, const char *wchan)
4354 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4356 while ((bp->b_flags & B_DONE) == 0)
4357 msleep(bp, mtxp, pri, wchan, 0);
4362 bufsync(struct bufobj *bo, int waitfor)
4365 return (VOP_FSYNC(bo->__bo_vnode, waitfor, curthread));
4369 bufstrategy(struct bufobj *bo, struct buf *bp)
4375 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
4376 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
4377 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
4378 i = VOP_STRATEGY(vp, bp);
4379 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
4383 bufobj_wrefl(struct bufobj *bo)
4386 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4387 ASSERT_BO_LOCKED(bo);
4392 bufobj_wref(struct bufobj *bo)
4395 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4402 bufobj_wdrop(struct bufobj *bo)
4405 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
4407 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
4408 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
4409 bo->bo_flag &= ~BO_WWAIT;
4410 wakeup(&bo->bo_numoutput);
4416 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
4420 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
4421 ASSERT_BO_LOCKED(bo);
4423 while (bo->bo_numoutput) {
4424 bo->bo_flag |= BO_WWAIT;
4425 error = msleep(&bo->bo_numoutput, BO_MTX(bo),
4426 slpflag | (PRIBIO + 1), "bo_wwait", timeo);
4434 bpin(struct buf *bp)
4438 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4445 bunpin(struct buf *bp)
4449 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4451 if (--bp->b_pin_count == 0)
4457 bunpin_wait(struct buf *bp)
4461 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4463 while (bp->b_pin_count > 0)
4464 msleep(bp, mtxp, PRIBIO, "bwunpin", 0);
4469 * Set bio_data or bio_ma for struct bio from the struct buf.
4472 bdata2bio(struct buf *bp, struct bio *bip)
4475 if ((bp->b_flags & B_UNMAPPED) != 0) {
4476 KASSERT(unmapped_buf_allowed, ("unmapped"));
4477 bip->bio_ma = bp->b_pages;
4478 bip->bio_ma_n = bp->b_npages;
4479 bip->bio_data = unmapped_buf;
4480 bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
4481 bip->bio_flags |= BIO_UNMAPPED;
4482 KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) /
4483 PAGE_SIZE == bp->b_npages,
4484 ("Buffer %p too short: %d %d %d", bp, bip->bio_ma_offset,
4485 bip->bio_length, bip->bio_ma_n));
4487 bip->bio_data = bp->b_data;
4492 #include "opt_ddb.h"
4494 #include <ddb/ddb.h>
4496 /* DDB command to show buffer data */
4497 DB_SHOW_COMMAND(buffer, db_show_buffer)
4500 struct buf *bp = (struct buf *)addr;
4503 db_printf("usage: show buffer <addr>\n");
4507 db_printf("buf at %p\n", bp);
4508 db_printf("b_flags = 0x%b, b_xflags=0x%b, b_vflags=0x%b\n",
4509 (u_int)bp->b_flags, PRINT_BUF_FLAGS, (u_int)bp->b_xflags,
4510 PRINT_BUF_XFLAGS, (u_int)bp->b_vflags, PRINT_BUF_VFLAGS);
4512 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4513 "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_lblkno = %jd, "
4515 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4516 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4517 (intmax_t)bp->b_lblkno, bp->b_dep.lh_first);
4520 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4521 for (i = 0; i < bp->b_npages; i++) {
4524 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4525 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4526 if ((i + 1) < bp->b_npages)
4532 BUF_LOCKPRINTINFO(bp);
4535 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
4540 for (i = 0; i < nbuf; i++) {
4542 if (BUF_ISLOCKED(bp)) {
4543 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4549 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
4555 db_printf("usage: show vnodebufs <addr>\n");
4558 vp = (struct vnode *)addr;
4559 db_printf("Clean buffers:\n");
4560 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
4561 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4564 db_printf("Dirty buffers:\n");
4565 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
4566 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4571 DB_COMMAND(countfreebufs, db_coundfreebufs)
4574 int i, used = 0, nfree = 0;
4577 db_printf("usage: countfreebufs\n");
4581 for (i = 0; i < nbuf; i++) {
4583 if ((bp->b_vflags & BV_INFREECNT) != 0)
4589 db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
4591 db_printf("numfreebuffers is %d\n", numfreebuffers);