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 #define TRANSIENT_DENOM 5
526 #define TRANSIENT_DENOM 10
530 * Calculating buffer cache scaling values and reserve space for buffer
531 * headers. This is called during low level kernel initialization and
532 * may be called more then once. We CANNOT write to the memory area
533 * being reserved at this time.
536 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
539 long maxbuf, maxbuf_sz, buf_sz, biotmap_sz;
542 * physmem_est is in pages. Convert it to kilobytes (assumes
543 * PAGE_SIZE is >= 1K)
545 physmem_est = physmem_est * (PAGE_SIZE / 1024);
548 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
549 * For the first 64MB of ram nominally allocate sufficient buffers to
550 * cover 1/4 of our ram. Beyond the first 64MB allocate additional
551 * buffers to cover 1/10 of our ram over 64MB. When auto-sizing
552 * the buffer cache we limit the eventual kva reservation to
555 * factor represents the 1/4 x ram conversion.
558 int factor = 4 * BKVASIZE / 1024;
561 if (physmem_est > 4096)
562 nbuf += min((physmem_est - 4096) / factor,
564 if (physmem_est > 65536)
565 nbuf += (physmem_est - 65536) * 2 / (factor * 5);
567 if (maxbcache && nbuf > maxbcache / BKVASIZE)
568 nbuf = maxbcache / BKVASIZE;
573 /* XXX Avoid unsigned long overflows later on with maxbufspace. */
574 maxbuf = (LONG_MAX / 3) / BKVASIZE;
577 printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
583 * Ideal allocation size for the transient bio submap if 10%
584 * of the maximal space buffer map. This roughly corresponds
585 * to the amount of the buffer mapped for typical UFS load.
587 * Clip the buffer map to reserve space for the transient
588 * BIOs, if its extent is bigger than 90% (80% on i386) of the
589 * maximum buffer map extent on the platform.
591 * The fall-back to the maxbuf in case of maxbcache unset,
592 * allows to not trim the buffer KVA for the architectures
593 * with ample KVA space.
595 if (bio_transient_maxcnt == 0 && unmapped_buf_allowed) {
596 maxbuf_sz = maxbcache != 0 ? maxbcache : maxbuf * BKVASIZE;
597 buf_sz = (long)nbuf * BKVASIZE;
598 if (buf_sz < maxbuf_sz / TRANSIENT_DENOM *
599 (TRANSIENT_DENOM - 1)) {
601 * There is more KVA than memory. Do not
602 * adjust buffer map size, and assign the rest
603 * of maxbuf to transient map.
605 biotmap_sz = maxbuf_sz - buf_sz;
608 * Buffer map spans all KVA we could afford on
609 * this platform. Give 10% (20% on i386) of
610 * the buffer map to the transient bio map.
612 biotmap_sz = buf_sz / TRANSIENT_DENOM;
613 buf_sz -= biotmap_sz;
615 if (biotmap_sz / INT_MAX > MAXPHYS)
616 bio_transient_maxcnt = INT_MAX;
618 bio_transient_maxcnt = biotmap_sz / MAXPHYS;
620 * Artifically limit to 1024 simultaneous in-flight I/Os
621 * using the transient mapping.
623 if (bio_transient_maxcnt > 1024)
624 bio_transient_maxcnt = 1024;
626 nbuf = buf_sz / BKVASIZE;
630 * swbufs are used as temporary holders for I/O, such as paging I/O.
631 * We have no less then 16 and no more then 256.
633 nswbuf = max(min(nbuf/4, 256), 16);
635 if (nswbuf < NSWBUF_MIN)
643 * Reserve space for the buffer cache buffers
646 v = (caddr_t)(swbuf + nswbuf);
648 v = (caddr_t)(buf + nbuf);
653 /* Initialize the buffer subsystem. Called before use of any buffers. */
660 mtx_init(&bqlock, "buf queue lock", NULL, MTX_DEF);
661 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
662 mtx_init(&nblock, "needsbuffer lock", NULL, MTX_DEF);
663 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
665 /* next, make a null set of free lists */
666 for (i = 0; i < BUFFER_QUEUES; i++)
667 TAILQ_INIT(&bufqueues[i]);
669 /* finally, initialize each buffer header and stick on empty q */
670 for (i = 0; i < nbuf; i++) {
672 bzero(bp, sizeof *bp);
673 bp->b_flags = B_INVAL; /* we're just an empty header */
674 bp->b_rcred = NOCRED;
675 bp->b_wcred = NOCRED;
676 bp->b_qindex = QUEUE_EMPTY;
677 bp->b_vflags = BV_INFREECNT; /* buf is counted as free */
679 LIST_INIT(&bp->b_dep);
681 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
683 bq_len[QUEUE_EMPTY]++;
688 * maxbufspace is the absolute maximum amount of buffer space we are
689 * allowed to reserve in KVM and in real terms. The absolute maximum
690 * is nominally used by buf_daemon. hibufspace is the nominal maximum
691 * used by most other processes. The differential is required to
692 * ensure that buf_daemon is able to run when other processes might
693 * be blocked waiting for buffer space.
695 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
696 * this may result in KVM fragmentation which is not handled optimally
699 maxbufspace = (long)nbuf * BKVASIZE;
700 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
701 lobufspace = hibufspace - MAXBSIZE;
704 * Note: The 16 MiB upper limit for hirunningspace was chosen
705 * arbitrarily and may need further tuning. It corresponds to
706 * 128 outstanding write IO requests (if IO size is 128 KiB),
707 * which fits with many RAID controllers' tagged queuing limits.
708 * The lower 1 MiB limit is the historical upper limit for
711 hirunningspace = lmax(lmin(roundup(hibufspace / 64, MAXBSIZE),
712 16 * 1024 * 1024), 1024 * 1024);
713 lorunningspace = roundup((hirunningspace * 2) / 3, MAXBSIZE);
716 * Limit the amount of malloc memory since it is wired permanently into
717 * the kernel space. Even though this is accounted for in the buffer
718 * allocation, we don't want the malloced region to grow uncontrolled.
719 * The malloc scheme improves memory utilization significantly on average
720 * (small) directories.
722 maxbufmallocspace = hibufspace / 20;
725 * Reduce the chance of a deadlock occuring by limiting the number
726 * of delayed-write dirty buffers we allow to stack up.
728 hidirtybuffers = nbuf / 4 + 20;
729 dirtybufthresh = hidirtybuffers * 9 / 10;
732 * To support extreme low-memory systems, make sure hidirtybuffers cannot
733 * eat up all available buffer space. This occurs when our minimum cannot
734 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
735 * BKVASIZE'd buffers.
737 while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
738 hidirtybuffers >>= 1;
740 lodirtybuffers = hidirtybuffers / 2;
743 * Try to keep the number of free buffers in the specified range,
744 * and give special processes (e.g. like buf_daemon) access to an
747 lofreebuffers = nbuf / 18 + 5;
748 hifreebuffers = 2 * lofreebuffers;
749 numfreebuffers = nbuf;
751 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
752 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
753 unmapped_buf = (caddr_t)kmem_alloc_nofault(kernel_map, MAXPHYS);
758 vfs_buf_check_mapped(struct buf *bp)
761 KASSERT((bp->b_flags & B_UNMAPPED) == 0,
762 ("mapped buf %p %x", bp, bp->b_flags));
763 KASSERT(bp->b_kvabase != unmapped_buf,
764 ("mapped buf: b_kvabase was not updated %p", bp));
765 KASSERT(bp->b_data != unmapped_buf,
766 ("mapped buf: b_data was not updated %p", bp));
770 vfs_buf_check_unmapped(struct buf *bp)
773 KASSERT((bp->b_flags & B_UNMAPPED) == B_UNMAPPED,
774 ("unmapped buf %p %x", bp, bp->b_flags));
775 KASSERT(bp->b_kvabase == unmapped_buf,
776 ("unmapped buf: corrupted b_kvabase %p", bp));
777 KASSERT(bp->b_data == unmapped_buf,
778 ("unmapped buf: corrupted b_data %p", bp));
781 #define BUF_CHECK_MAPPED(bp) vfs_buf_check_mapped(bp)
782 #define BUF_CHECK_UNMAPPED(bp) vfs_buf_check_unmapped(bp)
784 #define BUF_CHECK_MAPPED(bp) do {} while (0)
785 #define BUF_CHECK_UNMAPPED(bp) do {} while (0)
789 bpmap_qenter(struct buf *bp)
792 BUF_CHECK_MAPPED(bp);
795 * bp->b_data is relative to bp->b_offset, but
796 * bp->b_offset may be offset into the first page.
798 bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
799 pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
800 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
801 (vm_offset_t)(bp->b_offset & PAGE_MASK));
805 * bfreekva() - free the kva allocation for a buffer.
807 * Since this call frees up buffer space, we call bufspacewakeup().
810 bfreekva(struct buf *bp)
813 if (bp->b_kvasize == 0)
816 atomic_add_int(&buffreekvacnt, 1);
817 atomic_subtract_long(&bufspace, bp->b_kvasize);
818 if ((bp->b_flags & B_UNMAPPED) == 0) {
819 BUF_CHECK_MAPPED(bp);
820 vm_map_remove(buffer_map, (vm_offset_t)bp->b_kvabase,
821 (vm_offset_t)bp->b_kvabase + bp->b_kvasize);
823 BUF_CHECK_UNMAPPED(bp);
824 if ((bp->b_flags & B_KVAALLOC) != 0) {
825 vm_map_remove(buffer_map, (vm_offset_t)bp->b_kvaalloc,
826 (vm_offset_t)bp->b_kvaalloc + bp->b_kvasize);
828 atomic_subtract_long(&unmapped_bufspace, bp->b_kvasize);
829 bp->b_flags &= ~(B_UNMAPPED | B_KVAALLOC);
838 * Mark the buffer for removal from the appropriate free list in brelse.
842 bremfree(struct buf *bp)
846 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
847 KASSERT((bp->b_flags & B_REMFREE) == 0,
848 ("bremfree: buffer %p already marked for delayed removal.", bp));
849 KASSERT(bp->b_qindex != QUEUE_NONE,
850 ("bremfree: buffer %p not on a queue.", bp));
853 bp->b_flags |= B_REMFREE;
854 /* Fixup numfreebuffers count. */
855 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
856 KASSERT((bp->b_vflags & BV_INFREECNT) != 0,
857 ("buf %p not counted in numfreebuffers", bp));
858 if (bp->b_bufobj != NULL)
859 mtx_assert(BO_MTX(bp->b_bufobj), MA_OWNED);
860 bp->b_vflags &= ~BV_INFREECNT;
861 old = atomic_fetchadd_int(&numfreebuffers, -1);
862 KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
869 * Force an immediate removal from a free list. Used only in nfs when
870 * it abuses the b_freelist pointer.
873 bremfreef(struct buf *bp)
883 * Removes a buffer from the free list, must be called with the
887 bremfreel(struct buf *bp)
891 CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
892 bp, bp->b_vp, bp->b_flags);
893 KASSERT(bp->b_qindex != QUEUE_NONE,
894 ("bremfreel: buffer %p not on a queue.", bp));
896 mtx_assert(&bqlock, MA_OWNED);
898 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
900 KASSERT(bq_len[bp->b_qindex] >= 1, ("queue %d underflow",
902 bq_len[bp->b_qindex]--;
904 bp->b_qindex = QUEUE_NONE;
906 * If this was a delayed bremfree() we only need to remove the buffer
907 * from the queue and return the stats are already done.
909 if (bp->b_flags & B_REMFREE) {
910 bp->b_flags &= ~B_REMFREE;
914 * Fixup numfreebuffers count. If the buffer is invalid or not
915 * delayed-write, the buffer was free and we must decrement
918 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
919 KASSERT((bp->b_vflags & BV_INFREECNT) != 0,
920 ("buf %p not counted in numfreebuffers", bp));
921 if (bp->b_bufobj != NULL)
922 mtx_assert(BO_MTX(bp->b_bufobj), MA_OWNED);
923 bp->b_vflags &= ~BV_INFREECNT;
924 old = atomic_fetchadd_int(&numfreebuffers, -1);
925 KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
930 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must
931 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
932 * the buffer is valid and we do not have to do anything.
935 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
936 int cnt, struct ucred * cred)
941 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
942 if (inmem(vp, *rablkno))
944 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
946 if ((rabp->b_flags & B_CACHE) == 0) {
947 if (!TD_IS_IDLETHREAD(curthread))
948 curthread->td_ru.ru_inblock++;
949 rabp->b_flags |= B_ASYNC;
950 rabp->b_flags &= ~B_INVAL;
951 rabp->b_ioflags &= ~BIO_ERROR;
952 rabp->b_iocmd = BIO_READ;
953 if (rabp->b_rcred == NOCRED && cred != NOCRED)
954 rabp->b_rcred = crhold(cred);
955 vfs_busy_pages(rabp, 0);
957 rabp->b_iooffset = dbtob(rabp->b_blkno);
966 * Entry point for bread() and breadn() via #defines in sys/buf.h.
968 * Get a buffer with the specified data. Look in the cache first. We
969 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
970 * is set, the buffer is valid and we do not have to do anything, see
971 * getblk(). Also starts asynchronous I/O on read-ahead blocks.
974 breadn_flags(struct vnode *vp, daddr_t blkno, int size, daddr_t *rablkno,
975 int *rabsize, int cnt, struct ucred *cred, int flags, struct buf **bpp)
978 int rv = 0, readwait = 0;
980 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
982 * Can only return NULL if GB_LOCK_NOWAIT flag is specified.
984 *bpp = bp = getblk(vp, blkno, size, 0, 0, flags);
988 /* if not found in cache, do some I/O */
989 if ((bp->b_flags & B_CACHE) == 0) {
990 if (!TD_IS_IDLETHREAD(curthread))
991 curthread->td_ru.ru_inblock++;
992 bp->b_iocmd = BIO_READ;
993 bp->b_flags &= ~B_INVAL;
994 bp->b_ioflags &= ~BIO_ERROR;
995 if (bp->b_rcred == NOCRED && cred != NOCRED)
996 bp->b_rcred = crhold(cred);
997 vfs_busy_pages(bp, 0);
998 bp->b_iooffset = dbtob(bp->b_blkno);
1003 breada(vp, rablkno, rabsize, cnt, cred);
1012 * Write, release buffer on completion. (Done by iodone
1013 * if async). Do not bother writing anything if the buffer
1016 * Note that we set B_CACHE here, indicating that buffer is
1017 * fully valid and thus cacheable. This is true even of NFS
1018 * now so we set it generally. This could be set either here
1019 * or in biodone() since the I/O is synchronous. We put it
1023 bufwrite(struct buf *bp)
1029 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1030 if (bp->b_flags & B_INVAL) {
1035 if (bp->b_flags & B_BARRIER)
1038 oldflags = bp->b_flags;
1040 BUF_ASSERT_HELD(bp);
1042 if (bp->b_pin_count > 0)
1045 KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
1046 ("FFS background buffer should not get here %p", bp));
1050 vp_md = vp->v_vflag & VV_MD;
1055 * Mark the buffer clean. Increment the bufobj write count
1056 * before bundirty() call, to prevent other thread from seeing
1057 * empty dirty list and zero counter for writes in progress,
1058 * falsely indicating that the bufobj is clean.
1060 bufobj_wref(bp->b_bufobj);
1063 bp->b_flags &= ~B_DONE;
1064 bp->b_ioflags &= ~BIO_ERROR;
1065 bp->b_flags |= B_CACHE;
1066 bp->b_iocmd = BIO_WRITE;
1068 vfs_busy_pages(bp, 1);
1071 * Normal bwrites pipeline writes
1073 bp->b_runningbufspace = bp->b_bufsize;
1074 atomic_add_long(&runningbufspace, bp->b_runningbufspace);
1076 if (!TD_IS_IDLETHREAD(curthread))
1077 curthread->td_ru.ru_oublock++;
1078 if (oldflags & B_ASYNC)
1080 bp->b_iooffset = dbtob(bp->b_blkno);
1083 if ((oldflags & B_ASYNC) == 0) {
1084 int rtval = bufwait(bp);
1089 * don't allow the async write to saturate the I/O
1090 * system. We will not deadlock here because
1091 * we are blocking waiting for I/O that is already in-progress
1092 * to complete. We do not block here if it is the update
1093 * or syncer daemon trying to clean up as that can lead
1096 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
1097 waitrunningbufspace();
1104 bufbdflush(struct bufobj *bo, struct buf *bp)
1108 if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
1109 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
1111 } else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
1114 * Try to find a buffer to flush.
1116 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
1117 if ((nbp->b_vflags & BV_BKGRDINPROG) ||
1119 LK_EXCLUSIVE | LK_NOWAIT, NULL))
1122 panic("bdwrite: found ourselves");
1124 /* Don't countdeps with the bo lock held. */
1125 if (buf_countdeps(nbp, 0)) {
1130 if (nbp->b_flags & B_CLUSTEROK) {
1131 vfs_bio_awrite(nbp);
1136 dirtybufferflushes++;
1145 * Delayed write. (Buffer is marked dirty). Do not bother writing
1146 * anything if the buffer is marked invalid.
1148 * Note that since the buffer must be completely valid, we can safely
1149 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
1150 * biodone() in order to prevent getblk from writing the buffer
1151 * out synchronously.
1154 bdwrite(struct buf *bp)
1156 struct thread *td = curthread;
1160 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1161 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1162 KASSERT((bp->b_flags & B_BARRIER) == 0,
1163 ("Barrier request in delayed write %p", bp));
1164 BUF_ASSERT_HELD(bp);
1166 if (bp->b_flags & B_INVAL) {
1172 * If we have too many dirty buffers, don't create any more.
1173 * If we are wildly over our limit, then force a complete
1174 * cleanup. Otherwise, just keep the situation from getting
1175 * out of control. Note that we have to avoid a recursive
1176 * disaster and not try to clean up after our own cleanup!
1180 if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
1181 td->td_pflags |= TDP_INBDFLUSH;
1183 td->td_pflags &= ~TDP_INBDFLUSH;
1189 * Set B_CACHE, indicating that the buffer is fully valid. This is
1190 * true even of NFS now.
1192 bp->b_flags |= B_CACHE;
1195 * This bmap keeps the system from needing to do the bmap later,
1196 * perhaps when the system is attempting to do a sync. Since it
1197 * is likely that the indirect block -- or whatever other datastructure
1198 * that the filesystem needs is still in memory now, it is a good
1199 * thing to do this. Note also, that if the pageout daemon is
1200 * requesting a sync -- there might not be enough memory to do
1201 * the bmap then... So, this is important to do.
1203 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
1204 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
1208 * Set the *dirty* buffer range based upon the VM system dirty
1211 * Mark the buffer pages as clean. We need to do this here to
1212 * satisfy the vnode_pager and the pageout daemon, so that it
1213 * thinks that the pages have been "cleaned". Note that since
1214 * the pages are in a delayed write buffer -- the VFS layer
1215 * "will" see that the pages get written out on the next sync,
1216 * or perhaps the cluster will be completed.
1218 vfs_clean_pages_dirty_buf(bp);
1222 * Wakeup the buffer flushing daemon if we have a lot of dirty
1223 * buffers (midpoint between our recovery point and our stall
1226 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1229 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1230 * due to the softdep code.
1237 * Turn buffer into delayed write request. We must clear BIO_READ and
1238 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
1239 * itself to properly update it in the dirty/clean lists. We mark it
1240 * B_DONE to ensure that any asynchronization of the buffer properly
1241 * clears B_DONE ( else a panic will occur later ).
1243 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1244 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
1245 * should only be called if the buffer is known-good.
1247 * Since the buffer is not on a queue, we do not update the numfreebuffers
1250 * The buffer must be on QUEUE_NONE.
1253 bdirty(struct buf *bp)
1256 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
1257 bp, bp->b_vp, bp->b_flags);
1258 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1259 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1260 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1261 BUF_ASSERT_HELD(bp);
1262 bp->b_flags &= ~(B_RELBUF);
1263 bp->b_iocmd = BIO_WRITE;
1265 if ((bp->b_flags & B_DELWRI) == 0) {
1266 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
1268 atomic_add_int(&numdirtybuffers, 1);
1269 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1276 * Clear B_DELWRI for buffer.
1278 * Since the buffer is not on a queue, we do not update the numfreebuffers
1281 * The buffer must be on QUEUE_NONE.
1285 bundirty(struct buf *bp)
1288 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1289 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1290 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1291 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1292 BUF_ASSERT_HELD(bp);
1294 if (bp->b_flags & B_DELWRI) {
1295 bp->b_flags &= ~B_DELWRI;
1297 atomic_subtract_int(&numdirtybuffers, 1);
1298 numdirtywakeup(lodirtybuffers);
1301 * Since it is now being written, we can clear its deferred write flag.
1303 bp->b_flags &= ~B_DEFERRED;
1309 * Asynchronous write. Start output on a buffer, but do not wait for
1310 * it to complete. The buffer is released when the output completes.
1312 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1313 * B_INVAL buffers. Not us.
1316 bawrite(struct buf *bp)
1319 bp->b_flags |= B_ASYNC;
1326 * Asynchronous barrier write. Start output on a buffer, but do not
1327 * wait for it to complete. Place a write barrier after this write so
1328 * that this buffer and all buffers written before it are committed to
1329 * the disk before any buffers written after this write are committed
1330 * to the disk. The buffer is released when the output completes.
1333 babarrierwrite(struct buf *bp)
1336 bp->b_flags |= B_ASYNC | B_BARRIER;
1343 * Synchronous barrier write. Start output on a buffer and wait for
1344 * it to complete. Place a write barrier after this write so that
1345 * this buffer and all buffers written before it are committed to
1346 * the disk before any buffers written after this write are committed
1347 * to the disk. The buffer is released when the output completes.
1350 bbarrierwrite(struct buf *bp)
1353 bp->b_flags |= B_BARRIER;
1354 return (bwrite(bp));
1360 * Called prior to the locking of any vnodes when we are expecting to
1361 * write. We do not want to starve the buffer cache with too many
1362 * dirty buffers so we block here. By blocking prior to the locking
1363 * of any vnodes we attempt to avoid the situation where a locked vnode
1364 * prevents the various system daemons from flushing related buffers.
1371 if (numdirtybuffers >= hidirtybuffers) {
1373 while (numdirtybuffers >= hidirtybuffers) {
1375 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
1376 msleep(&needsbuffer, &nblock,
1377 (PRIBIO + 4), "flswai", 0);
1379 mtx_unlock(&nblock);
1384 * Return true if we have too many dirty buffers.
1387 buf_dirty_count_severe(void)
1390 return(numdirtybuffers >= hidirtybuffers);
1393 static __noinline int
1394 buf_vm_page_count_severe(void)
1397 KFAIL_POINT_CODE(DEBUG_FP, buf_pressure, return 1);
1399 return vm_page_count_severe();
1405 * Release a busy buffer and, if requested, free its resources. The
1406 * buffer will be stashed in the appropriate bufqueue[] allowing it
1407 * to be accessed later as a cache entity or reused for other purposes.
1410 brelse(struct buf *bp)
1412 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
1413 bp, bp->b_vp, bp->b_flags);
1414 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1415 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1417 if (BUF_LOCKRECURSED(bp)) {
1419 * Do not process, in particular, do not handle the
1420 * B_INVAL/B_RELBUF and do not release to free list.
1426 if (bp->b_flags & B_MANAGED) {
1431 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
1432 bp->b_error == EIO && !(bp->b_flags & B_INVAL)) {
1434 * Failed write, redirty. Must clear BIO_ERROR to prevent
1435 * pages from being scrapped. If the error is anything
1436 * other than an I/O error (EIO), assume that retrying
1439 bp->b_ioflags &= ~BIO_ERROR;
1441 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1442 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
1444 * Either a failed I/O or we were asked to free or not
1447 bp->b_flags |= B_INVAL;
1448 if (!LIST_EMPTY(&bp->b_dep))
1450 if (bp->b_flags & B_DELWRI) {
1451 atomic_subtract_int(&numdirtybuffers, 1);
1452 numdirtywakeup(lodirtybuffers);
1454 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1455 if ((bp->b_flags & B_VMIO) == 0) {
1464 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1465 * is called with B_DELWRI set, the underlying pages may wind up
1466 * getting freed causing a previous write (bdwrite()) to get 'lost'
1467 * because pages associated with a B_DELWRI bp are marked clean.
1469 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1470 * if B_DELWRI is set.
1472 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1473 * on pages to return pages to the VM page queues.
1475 if (bp->b_flags & B_DELWRI)
1476 bp->b_flags &= ~B_RELBUF;
1477 else if (buf_vm_page_count_severe()) {
1479 * The locking of the BO_LOCK is not necessary since
1480 * BKGRDINPROG cannot be set while we hold the buf
1481 * lock, it can only be cleared if it is already
1485 if (!(bp->b_vflags & BV_BKGRDINPROG))
1486 bp->b_flags |= B_RELBUF;
1488 bp->b_flags |= B_RELBUF;
1492 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1493 * constituted, not even NFS buffers now. Two flags effect this. If
1494 * B_INVAL, the struct buf is invalidated but the VM object is kept
1495 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1497 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1498 * invalidated. BIO_ERROR cannot be set for a failed write unless the
1499 * buffer is also B_INVAL because it hits the re-dirtying code above.
1501 * Normally we can do this whether a buffer is B_DELWRI or not. If
1502 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1503 * the commit state and we cannot afford to lose the buffer. If the
1504 * buffer has a background write in progress, we need to keep it
1505 * around to prevent it from being reconstituted and starting a second
1508 if ((bp->b_flags & B_VMIO)
1509 && !(bp->b_vp->v_mount != NULL &&
1510 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1511 !vn_isdisk(bp->b_vp, NULL) &&
1512 (bp->b_flags & B_DELWRI))
1521 obj = bp->b_bufobj->bo_object;
1524 * Get the base offset and length of the buffer. Note that
1525 * in the VMIO case if the buffer block size is not
1526 * page-aligned then b_data pointer may not be page-aligned.
1527 * But our b_pages[] array *IS* page aligned.
1529 * block sizes less then DEV_BSIZE (usually 512) are not
1530 * supported due to the page granularity bits (m->valid,
1531 * m->dirty, etc...).
1533 * See man buf(9) for more information
1535 resid = bp->b_bufsize;
1536 foff = bp->b_offset;
1537 VM_OBJECT_WLOCK(obj);
1538 for (i = 0; i < bp->b_npages; i++) {
1544 * If we hit a bogus page, fixup *all* the bogus pages
1547 if (m == bogus_page) {
1548 poff = OFF_TO_IDX(bp->b_offset);
1551 for (j = i; j < bp->b_npages; j++) {
1553 mtmp = bp->b_pages[j];
1554 if (mtmp == bogus_page) {
1555 mtmp = vm_page_lookup(obj, poff + j);
1557 panic("brelse: page missing\n");
1559 bp->b_pages[j] = mtmp;
1563 if ((bp->b_flags & (B_INVAL | B_UNMAPPED)) == 0) {
1564 BUF_CHECK_MAPPED(bp);
1566 trunc_page((vm_offset_t)bp->b_data),
1567 bp->b_pages, bp->b_npages);
1571 if ((bp->b_flags & B_NOCACHE) ||
1572 (bp->b_ioflags & BIO_ERROR &&
1573 bp->b_iocmd == BIO_READ)) {
1574 int poffset = foff & PAGE_MASK;
1575 int presid = resid > (PAGE_SIZE - poffset) ?
1576 (PAGE_SIZE - poffset) : resid;
1578 KASSERT(presid >= 0, ("brelse: extra page"));
1579 vm_page_set_invalid(m, poffset, presid);
1581 printf("avoided corruption bug in bogus_page/brelse code\n");
1583 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1584 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1586 VM_OBJECT_WUNLOCK(obj);
1587 if (bp->b_flags & (B_INVAL | B_RELBUF))
1588 vfs_vmio_release(bp);
1590 } else if (bp->b_flags & B_VMIO) {
1592 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1593 vfs_vmio_release(bp);
1596 } else if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0) {
1597 if (bp->b_bufsize != 0)
1599 if (bp->b_vp != NULL)
1605 /* Handle delayed bremfree() processing. */
1606 if (bp->b_flags & B_REMFREE) {
1616 if (bp->b_qindex != QUEUE_NONE)
1617 panic("brelse: free buffer onto another queue???");
1620 * If the buffer has junk contents signal it and eventually
1621 * clean up B_DELWRI and diassociate the vnode so that gbincore()
1624 if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
1625 (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
1626 bp->b_flags |= B_INVAL;
1627 if (bp->b_flags & B_INVAL) {
1628 if (bp->b_flags & B_DELWRI)
1634 /* buffers with no memory */
1635 if (bp->b_bufsize == 0) {
1636 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1637 if (bp->b_vflags & BV_BKGRDINPROG)
1638 panic("losing buffer 1");
1639 if (bp->b_kvasize) {
1640 bp->b_qindex = QUEUE_EMPTYKVA;
1642 bp->b_qindex = QUEUE_EMPTY;
1644 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1645 /* buffers with junk contents */
1646 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1647 (bp->b_ioflags & BIO_ERROR)) {
1648 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1649 if (bp->b_vflags & BV_BKGRDINPROG)
1650 panic("losing buffer 2");
1651 bp->b_qindex = QUEUE_CLEAN;
1652 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1653 /* remaining buffers */
1655 if (bp->b_flags & B_DELWRI)
1656 bp->b_qindex = QUEUE_DIRTY;
1658 bp->b_qindex = QUEUE_CLEAN;
1659 if (bp->b_flags & B_AGE) {
1660 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp,
1663 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp,
1668 bq_len[bp->b_qindex]++;
1670 mtx_unlock(&bqlock);
1673 * Fixup numfreebuffers count. The bp is on an appropriate queue
1674 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1675 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1676 * if B_INVAL is set ).
1679 if (!(bp->b_flags & B_DELWRI)) {
1691 * Something we can maybe free or reuse
1693 if (bp->b_bufsize || bp->b_kvasize)
1696 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1697 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1698 panic("brelse: not dirty");
1704 * Release a buffer back to the appropriate queue but do not try to free
1705 * it. The buffer is expected to be used again soon.
1707 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1708 * biodone() to requeue an async I/O on completion. It is also used when
1709 * known good buffers need to be requeued but we think we may need the data
1712 * XXX we should be able to leave the B_RELBUF hint set on completion.
1715 bqrelse(struct buf *bp)
1719 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1720 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1721 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1723 if (BUF_LOCKRECURSED(bp)) {
1724 /* do not release to free list */
1730 if (bp->b_flags & B_MANAGED) {
1731 if (bp->b_flags & B_REMFREE) {
1738 mtx_unlock(&bqlock);
1740 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1746 /* Handle delayed bremfree() processing. */
1747 if (bp->b_flags & B_REMFREE) {
1754 if (bp->b_qindex != QUEUE_NONE)
1755 panic("bqrelse: free buffer onto another queue???");
1756 /* buffers with stale but valid contents */
1757 if (bp->b_flags & B_DELWRI) {
1758 bp->b_qindex = QUEUE_DIRTY;
1759 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1761 bq_len[bp->b_qindex]++;
1765 * The locking of the BO_LOCK for checking of the
1766 * BV_BKGRDINPROG is not necessary since the
1767 * BV_BKGRDINPROG cannot be set while we hold the buf
1768 * lock, it can only be cleared if it is already
1771 if (!buf_vm_page_count_severe() || (bp->b_vflags & BV_BKGRDINPROG)) {
1772 bp->b_qindex = QUEUE_CLEAN;
1773 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp,
1776 bq_len[QUEUE_CLEAN]++;
1780 * We are too low on memory, we have to try to free
1781 * the buffer (most importantly: the wired pages
1782 * making up its backing store) *now*.
1784 mtx_unlock(&bqlock);
1789 mtx_unlock(&bqlock);
1791 if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI)) {
1800 * Something we can maybe free or reuse.
1802 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1805 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1806 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1807 panic("bqrelse: not dirty");
1812 /* Give pages used by the bp back to the VM system (where possible) */
1814 vfs_vmio_release(struct buf *bp)
1819 if ((bp->b_flags & B_UNMAPPED) == 0) {
1820 BUF_CHECK_MAPPED(bp);
1821 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
1823 BUF_CHECK_UNMAPPED(bp);
1824 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
1825 for (i = 0; i < bp->b_npages; i++) {
1827 bp->b_pages[i] = NULL;
1829 * In order to keep page LRU ordering consistent, put
1830 * everything on the inactive queue.
1833 vm_page_unwire(m, 0);
1835 * We don't mess with busy pages, it is
1836 * the responsibility of the process that
1837 * busied the pages to deal with them.
1839 if ((m->oflags & VPO_BUSY) == 0 && m->busy == 0 &&
1840 m->wire_count == 0) {
1842 * Might as well free the page if we can and it has
1843 * no valid data. We also free the page if the
1844 * buffer was used for direct I/O
1846 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid) {
1848 } else if (bp->b_flags & B_DIRECT) {
1849 vm_page_try_to_free(m);
1850 } else if (buf_vm_page_count_severe()) {
1851 vm_page_try_to_cache(m);
1856 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
1858 if (bp->b_bufsize) {
1863 bp->b_flags &= ~B_VMIO;
1869 * Check to see if a block at a particular lbn is available for a clustered
1873 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1880 /* If the buf isn't in core skip it */
1881 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1884 /* If the buf is busy we don't want to wait for it */
1885 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1888 /* Only cluster with valid clusterable delayed write buffers */
1889 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1890 (B_DELWRI | B_CLUSTEROK))
1893 if (bpa->b_bufsize != size)
1897 * Check to see if it is in the expected place on disk and that the
1898 * block has been mapped.
1900 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1910 * Implement clustered async writes for clearing out B_DELWRI buffers.
1911 * This is much better then the old way of writing only one buffer at
1912 * a time. Note that we may not be presented with the buffers in the
1913 * correct order, so we search for the cluster in both directions.
1916 vfs_bio_awrite(struct buf *bp)
1921 daddr_t lblkno = bp->b_lblkno;
1922 struct vnode *vp = bp->b_vp;
1930 gbflags = (bp->b_flags & B_UNMAPPED) != 0 ? GB_UNMAPPED : 0;
1932 * right now we support clustered writing only to regular files. If
1933 * we find a clusterable block we could be in the middle of a cluster
1934 * rather then at the beginning.
1936 if ((vp->v_type == VREG) &&
1937 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1938 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1940 size = vp->v_mount->mnt_stat.f_iosize;
1941 maxcl = MAXPHYS / size;
1944 for (i = 1; i < maxcl; i++)
1945 if (vfs_bio_clcheck(vp, size, lblkno + i,
1946 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1949 for (j = 1; i + j <= maxcl && j <= lblkno; j++)
1950 if (vfs_bio_clcheck(vp, size, lblkno - j,
1951 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
1957 * this is a possible cluster write
1961 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl,
1967 bp->b_flags |= B_ASYNC;
1969 * default (old) behavior, writing out only one block
1971 * XXX returns b_bufsize instead of b_bcount for nwritten?
1973 nwritten = bp->b_bufsize;
1980 setbufkva(struct buf *bp, vm_offset_t addr, int maxsize, int gbflags)
1983 KASSERT((bp->b_flags & (B_UNMAPPED | B_KVAALLOC)) == 0 &&
1984 bp->b_kvasize == 0, ("call bfreekva(%p)", bp));
1985 if ((gbflags & GB_UNMAPPED) == 0) {
1986 bp->b_kvabase = (caddr_t)addr;
1987 } else if ((gbflags & GB_KVAALLOC) != 0) {
1988 KASSERT((gbflags & GB_UNMAPPED) != 0,
1989 ("GB_KVAALLOC without GB_UNMAPPED"));
1990 bp->b_kvaalloc = (caddr_t)addr;
1991 bp->b_flags |= B_UNMAPPED | B_KVAALLOC;
1992 atomic_add_long(&unmapped_bufspace, bp->b_kvasize);
1994 bp->b_kvasize = maxsize;
1998 * Allocate the buffer KVA and set b_kvasize. Also set b_kvabase if
2002 allocbufkva(struct buf *bp, int maxsize, int gbflags)
2010 vm_map_lock(buffer_map);
2011 if (vm_map_findspace(buffer_map, vm_map_min(buffer_map), maxsize,
2013 vm_map_unlock(buffer_map);
2015 * Buffer map is too fragmented. Request the caller
2016 * to defragment the map.
2018 atomic_add_int(&bufdefragcnt, 1);
2021 rv = vm_map_insert(buffer_map, NULL, 0, addr, addr + maxsize,
2022 VM_PROT_RW, VM_PROT_RW, MAP_NOFAULT);
2023 KASSERT(rv == KERN_SUCCESS, ("vm_map_insert(buffer_map) rv %d", rv));
2024 vm_map_unlock(buffer_map);
2025 setbufkva(bp, addr, maxsize, gbflags);
2026 atomic_add_long(&bufspace, bp->b_kvasize);
2031 * Ask the bufdaemon for help, or act as bufdaemon itself, when a
2032 * locked vnode is supplied.
2035 getnewbuf_bufd_help(struct vnode *vp, int gbflags, int slpflag, int slptimeo,
2040 int fl, flags, norunbuf;
2042 mtx_assert(&bqlock, MA_OWNED);
2045 flags = VFS_BIO_NEED_BUFSPACE;
2047 } else if (bufspace >= hibufspace) {
2049 flags = VFS_BIO_NEED_BUFSPACE;
2052 flags = VFS_BIO_NEED_ANY;
2055 needsbuffer |= flags;
2056 mtx_unlock(&nblock);
2057 mtx_unlock(&bqlock);
2059 bd_speedup(); /* heeeelp */
2060 if ((gbflags & GB_NOWAIT_BD) != 0)
2065 while (needsbuffer & flags) {
2066 if (vp != NULL && (td->td_pflags & TDP_BUFNEED) == 0) {
2067 mtx_unlock(&nblock);
2069 * getblk() is called with a vnode locked, and
2070 * some majority of the dirty buffers may as
2071 * well belong to the vnode. Flushing the
2072 * buffers there would make a progress that
2073 * cannot be achieved by the buf_daemon, that
2074 * cannot lock the vnode.
2076 norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
2077 (td->td_pflags & TDP_NORUNNINGBUF);
2078 /* play bufdaemon */
2079 td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
2080 fl = buf_do_flush(vp);
2081 td->td_pflags &= norunbuf;
2085 if ((needsbuffer & flags) == 0)
2088 if (msleep(&needsbuffer, &nblock, (PRIBIO + 4) | slpflag,
2092 mtx_unlock(&nblock);
2096 getnewbuf_reuse_bp(struct buf *bp, int qindex)
2099 CTR6(KTR_BUF, "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
2100 "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
2101 bp->b_kvasize, bp->b_bufsize, qindex);
2102 mtx_assert(&bqlock, MA_NOTOWNED);
2105 * Note: we no longer distinguish between VMIO and non-VMIO
2108 KASSERT((bp->b_flags & B_DELWRI) == 0,
2109 ("delwri buffer %p found in queue %d", bp, qindex));
2111 if (qindex == QUEUE_CLEAN) {
2112 if (bp->b_flags & B_VMIO) {
2113 bp->b_flags &= ~B_ASYNC;
2114 vfs_vmio_release(bp);
2116 if (bp->b_vp != NULL)
2121 * Get the rest of the buffer freed up. b_kva* is still valid
2122 * after this operation.
2125 if (bp->b_rcred != NOCRED) {
2126 crfree(bp->b_rcred);
2127 bp->b_rcred = NOCRED;
2129 if (bp->b_wcred != NOCRED) {
2130 crfree(bp->b_wcred);
2131 bp->b_wcred = NOCRED;
2133 if (!LIST_EMPTY(&bp->b_dep))
2135 if (bp->b_vflags & BV_BKGRDINPROG)
2136 panic("losing buffer 3");
2137 KASSERT(bp->b_vp == NULL, ("bp: %p still has vnode %p. qindex: %d",
2138 bp, bp->b_vp, qindex));
2139 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
2140 ("bp: %p still on a buffer list. xflags %X", bp, bp->b_xflags));
2145 bp->b_flags &= B_UNMAPPED | B_KVAALLOC;
2148 KASSERT((bp->b_vflags & BV_INFREECNT) == 0,
2149 ("buf %p still counted as free?", bp));
2152 bp->b_blkno = bp->b_lblkno = 0;
2153 bp->b_offset = NOOFFSET;
2159 bp->b_dirtyoff = bp->b_dirtyend = 0;
2160 bp->b_bufobj = NULL;
2161 bp->b_pin_count = 0;
2162 bp->b_fsprivate1 = NULL;
2163 bp->b_fsprivate2 = NULL;
2164 bp->b_fsprivate3 = NULL;
2166 LIST_INIT(&bp->b_dep);
2169 static int flushingbufs;
2172 getnewbuf_scan(int maxsize, int defrag, int unmapped, int metadata)
2174 struct buf *bp, *nbp;
2175 int nqindex, qindex, pass;
2177 KASSERT(!unmapped || !defrag, ("both unmapped and defrag"));
2181 atomic_add_int(&getnewbufrestarts, 1);
2184 * Setup for scan. If we do not have enough free buffers,
2185 * we setup a degenerate case that immediately fails. Note
2186 * that if we are specially marked process, we are allowed to
2187 * dip into our reserves.
2189 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
2190 * for the allocation of the mapped buffer. For unmapped, the
2191 * easiest is to start with EMPTY outright.
2193 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
2194 * However, there are a number of cases (defragging, reusing, ...)
2195 * where we cannot backup.
2199 if (!defrag && unmapped) {
2200 nqindex = QUEUE_EMPTY;
2201 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
2204 nqindex = QUEUE_EMPTYKVA;
2205 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
2209 * If no EMPTYKVA buffers and we are either defragging or
2210 * reusing, locate a CLEAN buffer to free or reuse. If
2211 * bufspace useage is low skip this step so we can allocate a
2214 if (nbp == NULL && (defrag || bufspace >= lobufspace)) {
2215 nqindex = QUEUE_CLEAN;
2216 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2220 * If we could not find or were not allowed to reuse a CLEAN
2221 * buffer, check to see if it is ok to use an EMPTY buffer.
2222 * We can only use an EMPTY buffer if allocating its KVA would
2223 * not otherwise run us out of buffer space. No KVA is needed
2224 * for the unmapped allocation.
2226 if (nbp == NULL && defrag == 0 && (bufspace + maxsize < hibufspace ||
2228 nqindex = QUEUE_EMPTY;
2229 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
2233 * All available buffers might be clean, retry ignoring the
2234 * lobufspace as the last resort.
2236 if (nbp == NULL && !TAILQ_EMPTY(&bufqueues[QUEUE_CLEAN])) {
2237 nqindex = QUEUE_CLEAN;
2238 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2242 * Run scan, possibly freeing data and/or kva mappings on the fly
2245 while ((bp = nbp) != NULL) {
2249 * Calculate next bp (we can only use it if we do not
2250 * block or do other fancy things).
2252 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
2255 nqindex = QUEUE_EMPTYKVA;
2256 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
2260 case QUEUE_EMPTYKVA:
2261 nqindex = QUEUE_CLEAN;
2262 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2267 if (metadata && pass == 1) {
2269 nqindex = QUEUE_EMPTY;
2271 &bufqueues[QUEUE_EMPTY]);
2280 * If we are defragging then we need a buffer with
2281 * b_kvasize != 0. XXX this situation should no longer
2282 * occur, if defrag is non-zero the buffer's b_kvasize
2283 * should also be non-zero at this point. XXX
2285 if (defrag && bp->b_kvasize == 0) {
2286 printf("Warning: defrag empty buffer %p\n", bp);
2291 * Start freeing the bp. This is somewhat involved. nbp
2292 * remains valid only for QUEUE_EMPTY[KVA] bp's.
2294 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2297 BO_LOCK(bp->b_bufobj);
2298 if (bp->b_vflags & BV_BKGRDINPROG) {
2299 BO_UNLOCK(bp->b_bufobj);
2303 BO_UNLOCK(bp->b_bufobj);
2306 KASSERT(bp->b_qindex == qindex,
2307 ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
2309 if (bp->b_bufobj != NULL)
2310 BO_LOCK(bp->b_bufobj);
2312 if (bp->b_bufobj != NULL)
2313 BO_UNLOCK(bp->b_bufobj);
2314 mtx_unlock(&bqlock);
2316 * NOTE: nbp is now entirely invalid. We can only restart
2317 * the scan from this point on.
2320 getnewbuf_reuse_bp(bp, qindex);
2321 mtx_assert(&bqlock, MA_NOTOWNED);
2324 * If we are defragging then free the buffer.
2327 bp->b_flags |= B_INVAL;
2335 * Notify any waiters for the buffer lock about
2336 * identity change by freeing the buffer.
2338 if (qindex == QUEUE_CLEAN && BUF_LOCKWAITERS(bp)) {
2339 bp->b_flags |= B_INVAL;
2349 * If we are overcomitted then recover the buffer and its
2350 * KVM space. This occurs in rare situations when multiple
2351 * processes are blocked in getnewbuf() or allocbuf().
2353 if (bufspace >= hibufspace)
2355 if (flushingbufs && bp->b_kvasize != 0) {
2356 bp->b_flags |= B_INVAL;
2361 if (bufspace < lobufspace)
2371 * Find and initialize a new buffer header, freeing up existing buffers
2372 * in the bufqueues as necessary. The new buffer is returned locked.
2374 * Important: B_INVAL is not set. If the caller wishes to throw the
2375 * buffer away, the caller must set B_INVAL prior to calling brelse().
2378 * We have insufficient buffer headers
2379 * We have insufficient buffer space
2380 * buffer_map is too fragmented ( space reservation fails )
2381 * If we have to flush dirty buffers ( but we try to avoid this )
2383 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
2384 * Instead we ask the buf daemon to do it for us. We attempt to
2385 * avoid piecemeal wakeups of the pageout daemon.
2388 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int size, int maxsize,
2392 int defrag, metadata;
2394 KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
2395 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
2396 if (!unmapped_buf_allowed)
2397 gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC);
2400 if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 ||
2406 * We can't afford to block since we might be holding a vnode lock,
2407 * which may prevent system daemons from running. We deal with
2408 * low-memory situations by proactively returning memory and running
2409 * async I/O rather then sync I/O.
2411 atomic_add_int(&getnewbufcalls, 1);
2412 atomic_subtract_int(&getnewbufrestarts, 1);
2414 bp = getnewbuf_scan(maxsize, defrag, (gbflags & (GB_UNMAPPED |
2415 GB_KVAALLOC)) == GB_UNMAPPED, metadata);
2420 * If we exhausted our list, sleep as appropriate. We may have to
2421 * wakeup various daemons and write out some dirty buffers.
2423 * Generally we are sleeping due to insufficient buffer space.
2426 mtx_assert(&bqlock, MA_OWNED);
2427 getnewbuf_bufd_help(vp, gbflags, slpflag, slptimeo, defrag);
2428 mtx_assert(&bqlock, MA_NOTOWNED);
2429 } else if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == GB_UNMAPPED) {
2430 mtx_assert(&bqlock, MA_NOTOWNED);
2433 bp->b_flags |= B_UNMAPPED;
2434 bp->b_kvabase = bp->b_data = unmapped_buf;
2435 bp->b_kvasize = maxsize;
2436 atomic_add_long(&bufspace, bp->b_kvasize);
2437 atomic_add_long(&unmapped_bufspace, bp->b_kvasize);
2438 atomic_add_int(&bufreusecnt, 1);
2440 mtx_assert(&bqlock, MA_NOTOWNED);
2443 * We finally have a valid bp. We aren't quite out of the
2444 * woods, we still have to reserve kva space. In order
2445 * to keep fragmentation sane we only allocate kva in
2448 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2450 if (maxsize != bp->b_kvasize || (bp->b_flags & (B_UNMAPPED |
2451 B_KVAALLOC)) == B_UNMAPPED) {
2452 if (allocbufkva(bp, maxsize, gbflags)) {
2454 bp->b_flags |= B_INVAL;
2458 atomic_add_int(&bufreusecnt, 1);
2459 } else if ((bp->b_flags & B_KVAALLOC) != 0 &&
2460 (gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == 0) {
2462 * If the reused buffer has KVA allocated,
2463 * reassign b_kvaalloc to b_kvabase.
2465 bp->b_kvabase = bp->b_kvaalloc;
2466 bp->b_flags &= ~B_KVAALLOC;
2467 atomic_subtract_long(&unmapped_bufspace,
2469 atomic_add_int(&bufreusecnt, 1);
2470 } else if ((bp->b_flags & (B_UNMAPPED | B_KVAALLOC)) == 0 &&
2471 (gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == (GB_UNMAPPED |
2474 * The case of reused buffer already have KVA
2475 * mapped, but the request is for unmapped
2476 * buffer with KVA allocated.
2478 bp->b_kvaalloc = bp->b_kvabase;
2479 bp->b_data = bp->b_kvabase = unmapped_buf;
2480 bp->b_flags |= B_UNMAPPED | B_KVAALLOC;
2481 atomic_add_long(&unmapped_bufspace,
2483 atomic_add_int(&bufreusecnt, 1);
2485 if ((gbflags & GB_UNMAPPED) == 0) {
2486 bp->b_saveaddr = bp->b_kvabase;
2487 bp->b_data = bp->b_saveaddr;
2488 bp->b_flags &= ~B_UNMAPPED;
2489 BUF_CHECK_MAPPED(bp);
2498 * buffer flushing daemon. Buffers are normally flushed by the
2499 * update daemon but if it cannot keep up this process starts to
2500 * take the load in an attempt to prevent getnewbuf() from blocking.
2503 static struct kproc_desc buf_kp = {
2508 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
2511 buf_do_flush(struct vnode *vp)
2515 flushed = flushbufqueues(vp, QUEUE_DIRTY, 0);
2518 * Could not find any buffers without rollback
2519 * dependencies, so just write the first one
2520 * in the hopes of eventually making progress.
2522 flushbufqueues(vp, QUEUE_DIRTY, 1);
2533 * This process needs to be suspended prior to shutdown sync.
2535 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2539 * This process is allowed to take the buffer cache to the limit
2541 curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
2545 mtx_unlock(&bdlock);
2547 kproc_suspend_check(bufdaemonproc);
2548 lodirtysave = lodirtybuffers;
2549 if (bd_speedupreq) {
2550 lodirtybuffers = numdirtybuffers / 2;
2554 * Do the flush. Limit the amount of in-transit I/O we
2555 * allow to build up, otherwise we would completely saturate
2556 * the I/O system. Wakeup any waiting processes before we
2557 * normally would so they can run in parallel with our drain.
2559 while (numdirtybuffers > lodirtybuffers) {
2560 if (buf_do_flush(NULL) == 0)
2562 kern_yield(PRI_USER);
2564 lodirtybuffers = lodirtysave;
2567 * Only clear bd_request if we have reached our low water
2568 * mark. The buf_daemon normally waits 1 second and
2569 * then incrementally flushes any dirty buffers that have
2570 * built up, within reason.
2572 * If we were unable to hit our low water mark and couldn't
2573 * find any flushable buffers, we sleep half a second.
2574 * Otherwise we loop immediately.
2577 if (numdirtybuffers <= lodirtybuffers) {
2579 * We reached our low water mark, reset the
2580 * request and sleep until we are needed again.
2581 * The sleep is just so the suspend code works.
2584 msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2587 * We couldn't find any flushable dirty buffers but
2588 * still have too many dirty buffers, we
2589 * have to sleep and try again. (rare)
2591 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2599 * Try to flush a buffer in the dirty queue. We must be careful to
2600 * free up B_INVAL buffers instead of write them, which NFS is
2601 * particularly sensitive to.
2603 static int flushwithdeps = 0;
2604 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2605 0, "Number of buffers flushed with dependecies that require rollbacks");
2608 flushbufqueues(struct vnode *lvp, int queue, int flushdeps)
2610 struct buf *sentinel;
2619 target = numdirtybuffers - lodirtybuffers;
2620 if (flushdeps && target > 2)
2623 target = flushbufqtarget;
2626 sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
2627 sentinel->b_qindex = QUEUE_SENTINEL;
2629 TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
2630 while (flushed != target) {
2631 bp = TAILQ_NEXT(sentinel, b_freelist);
2633 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2634 TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
2639 * Skip sentinels inserted by other invocations of the
2640 * flushbufqueues(), taking care to not reorder them.
2642 if (bp->b_qindex == QUEUE_SENTINEL)
2645 * Only flush the buffers that belong to the
2646 * vnode locked by the curthread.
2648 if (lvp != NULL && bp->b_vp != lvp)
2650 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2652 if (bp->b_pin_count > 0) {
2656 BO_LOCK(bp->b_bufobj);
2657 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2658 (bp->b_flags & B_DELWRI) == 0) {
2659 BO_UNLOCK(bp->b_bufobj);
2663 BO_UNLOCK(bp->b_bufobj);
2664 if (bp->b_flags & B_INVAL) {
2666 mtx_unlock(&bqlock);
2669 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2674 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
2675 if (flushdeps == 0) {
2683 * We must hold the lock on a vnode before writing
2684 * one of its buffers. Otherwise we may confuse, or
2685 * in the case of a snapshot vnode, deadlock the
2688 * The lock order here is the reverse of the normal
2689 * of vnode followed by buf lock. This is ok because
2690 * the NOWAIT will prevent deadlock.
2693 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2697 if (vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT | LK_CANRECURSE) == 0) {
2698 mtx_unlock(&bqlock);
2699 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2700 bp, bp->b_vp, bp->b_flags);
2701 if (curproc == bufdaemonproc)
2708 vn_finished_write(mp);
2710 flushwithdeps += hasdeps;
2714 * Sleeping on runningbufspace while holding
2715 * vnode lock leads to deadlock.
2717 if (curproc == bufdaemonproc)
2718 waitrunningbufspace();
2719 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2723 vn_finished_write(mp);
2726 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2727 mtx_unlock(&bqlock);
2728 free(sentinel, M_TEMP);
2733 * Check to see if a block is currently memory resident.
2736 incore(struct bufobj *bo, daddr_t blkno)
2741 bp = gbincore(bo, blkno);
2747 * Returns true if no I/O is needed to access the
2748 * associated VM object. This is like incore except
2749 * it also hunts around in the VM system for the data.
2753 inmem(struct vnode * vp, daddr_t blkno)
2756 vm_offset_t toff, tinc, size;
2760 ASSERT_VOP_LOCKED(vp, "inmem");
2762 if (incore(&vp->v_bufobj, blkno))
2764 if (vp->v_mount == NULL)
2771 if (size > vp->v_mount->mnt_stat.f_iosize)
2772 size = vp->v_mount->mnt_stat.f_iosize;
2773 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2775 VM_OBJECT_WLOCK(obj);
2776 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2777 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2781 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2782 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2783 if (vm_page_is_valid(m,
2784 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2787 VM_OBJECT_WUNLOCK(obj);
2791 VM_OBJECT_WUNLOCK(obj);
2796 * Set the dirty range for a buffer based on the status of the dirty
2797 * bits in the pages comprising the buffer. The range is limited
2798 * to the size of the buffer.
2800 * Tell the VM system that the pages associated with this buffer
2801 * are clean. This is used for delayed writes where the data is
2802 * going to go to disk eventually without additional VM intevention.
2804 * Note that while we only really need to clean through to b_bcount, we
2805 * just go ahead and clean through to b_bufsize.
2808 vfs_clean_pages_dirty_buf(struct buf *bp)
2810 vm_ooffset_t foff, noff, eoff;
2814 if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
2817 foff = bp->b_offset;
2818 KASSERT(bp->b_offset != NOOFFSET,
2819 ("vfs_clean_pages_dirty_buf: no buffer offset"));
2821 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
2822 vfs_drain_busy_pages(bp);
2823 vfs_setdirty_locked_object(bp);
2824 for (i = 0; i < bp->b_npages; i++) {
2825 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2827 if (eoff > bp->b_offset + bp->b_bufsize)
2828 eoff = bp->b_offset + bp->b_bufsize;
2830 vfs_page_set_validclean(bp, foff, m);
2831 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
2834 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
2838 vfs_setdirty_locked_object(struct buf *bp)
2843 object = bp->b_bufobj->bo_object;
2844 VM_OBJECT_ASSERT_WLOCKED(object);
2847 * We qualify the scan for modified pages on whether the
2848 * object has been flushed yet.
2850 if ((object->flags & OBJ_MIGHTBEDIRTY) != 0) {
2851 vm_offset_t boffset;
2852 vm_offset_t eoffset;
2855 * test the pages to see if they have been modified directly
2856 * by users through the VM system.
2858 for (i = 0; i < bp->b_npages; i++)
2859 vm_page_test_dirty(bp->b_pages[i]);
2862 * Calculate the encompassing dirty range, boffset and eoffset,
2863 * (eoffset - boffset) bytes.
2866 for (i = 0; i < bp->b_npages; i++) {
2867 if (bp->b_pages[i]->dirty)
2870 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2872 for (i = bp->b_npages - 1; i >= 0; --i) {
2873 if (bp->b_pages[i]->dirty) {
2877 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2880 * Fit it to the buffer.
2883 if (eoffset > bp->b_bcount)
2884 eoffset = bp->b_bcount;
2887 * If we have a good dirty range, merge with the existing
2891 if (boffset < eoffset) {
2892 if (bp->b_dirtyoff > boffset)
2893 bp->b_dirtyoff = boffset;
2894 if (bp->b_dirtyend < eoffset)
2895 bp->b_dirtyend = eoffset;
2901 * Allocate the KVA mapping for an existing buffer. It handles the
2902 * cases of both B_UNMAPPED buffer, and buffer with the preallocated
2903 * KVA which is not mapped (B_KVAALLOC).
2906 bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags)
2908 struct buf *scratch_bp;
2909 int bsize, maxsize, need_mapping, need_kva;
2912 need_mapping = (bp->b_flags & B_UNMAPPED) != 0 &&
2913 (gbflags & GB_UNMAPPED) == 0;
2914 need_kva = (bp->b_flags & (B_KVAALLOC | B_UNMAPPED)) == B_UNMAPPED &&
2915 (gbflags & GB_KVAALLOC) != 0;
2916 if (!need_mapping && !need_kva)
2919 BUF_CHECK_UNMAPPED(bp);
2921 if (need_mapping && (bp->b_flags & B_KVAALLOC) != 0) {
2923 * Buffer is not mapped, but the KVA was already
2924 * reserved at the time of the instantiation. Use the
2927 bp->b_flags &= ~B_KVAALLOC;
2928 KASSERT(bp->b_kvaalloc != 0, ("kvaalloc == 0"));
2929 bp->b_kvabase = bp->b_kvaalloc;
2930 atomic_subtract_long(&unmapped_bufspace, bp->b_kvasize);
2935 * Calculate the amount of the address space we would reserve
2936 * if the buffer was mapped.
2938 bsize = vn_isdisk(bp->b_vp, NULL) ? DEV_BSIZE : bp->b_bufobj->bo_bsize;
2939 offset = blkno * bsize;
2940 maxsize = size + (offset & PAGE_MASK);
2941 maxsize = imax(maxsize, bsize);
2944 if (allocbufkva(bp, maxsize, gbflags)) {
2946 * Request defragmentation. getnewbuf() returns us the
2947 * allocated space by the scratch buffer KVA.
2949 scratch_bp = getnewbuf(bp->b_vp, 0, 0, size, maxsize, gbflags |
2950 (GB_UNMAPPED | GB_KVAALLOC));
2951 if (scratch_bp == NULL) {
2952 if ((gbflags & GB_NOWAIT_BD) != 0) {
2954 * XXXKIB: defragmentation cannot
2955 * succeed, not sure what else to do.
2957 panic("GB_NOWAIT_BD and B_UNMAPPED %p", bp);
2959 atomic_add_int(&mappingrestarts, 1);
2962 KASSERT((scratch_bp->b_flags & B_KVAALLOC) != 0,
2963 ("scratch bp !B_KVAALLOC %p", scratch_bp));
2964 setbufkva(bp, (vm_offset_t)scratch_bp->b_kvaalloc,
2965 scratch_bp->b_kvasize, gbflags);
2967 /* Get rid of the scratch buffer. */
2968 scratch_bp->b_kvasize = 0;
2969 scratch_bp->b_flags |= B_INVAL;
2970 scratch_bp->b_flags &= ~(B_UNMAPPED | B_KVAALLOC);
2977 bp->b_saveaddr = bp->b_kvabase;
2978 bp->b_data = bp->b_saveaddr; /* b_offset is handled by bpmap_qenter */
2979 bp->b_flags &= ~B_UNMAPPED;
2980 BUF_CHECK_MAPPED(bp);
2987 * Get a block given a specified block and offset into a file/device.
2988 * The buffers B_DONE bit will be cleared on return, making it almost
2989 * ready for an I/O initiation. B_INVAL may or may not be set on
2990 * return. The caller should clear B_INVAL prior to initiating a
2993 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2994 * an existing buffer.
2996 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2997 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2998 * and then cleared based on the backing VM. If the previous buffer is
2999 * non-0-sized but invalid, B_CACHE will be cleared.
3001 * If getblk() must create a new buffer, the new buffer is returned with
3002 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
3003 * case it is returned with B_INVAL clear and B_CACHE set based on the
3006 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
3007 * B_CACHE bit is clear.
3009 * What this means, basically, is that the caller should use B_CACHE to
3010 * determine whether the buffer is fully valid or not and should clear
3011 * B_INVAL prior to issuing a read. If the caller intends to validate
3012 * the buffer by loading its data area with something, the caller needs
3013 * to clear B_INVAL. If the caller does this without issuing an I/O,
3014 * the caller should set B_CACHE ( as an optimization ), else the caller
3015 * should issue the I/O and biodone() will set B_CACHE if the I/O was
3016 * a write attempt or if it was a successfull read. If the caller
3017 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
3018 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
3021 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo,
3026 int bsize, error, maxsize, vmio;
3029 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
3030 KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3031 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3032 ASSERT_VOP_LOCKED(vp, "getblk");
3033 if (size > MAXBSIZE)
3034 panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
3035 if (!unmapped_buf_allowed)
3036 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3041 * Block if we are low on buffers. Certain processes are allowed
3042 * to completely exhaust the buffer cache.
3044 * If this check ever becomes a bottleneck it may be better to
3045 * move it into the else, when gbincore() fails. At the moment
3046 * it isn't a problem.
3048 if (numfreebuffers == 0) {
3049 if (TD_IS_IDLETHREAD(curthread))
3052 needsbuffer |= VFS_BIO_NEED_ANY;
3053 mtx_unlock(&nblock);
3057 bp = gbincore(bo, blkno);
3061 * Buffer is in-core. If the buffer is not busy nor managed,
3062 * it must be on a queue.
3064 lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
3066 if (flags & GB_LOCK_NOWAIT)
3067 lockflags |= LK_NOWAIT;
3069 error = BUF_TIMELOCK(bp, lockflags,
3070 BO_MTX(bo), "getblk", slpflag, slptimeo);
3073 * If we slept and got the lock we have to restart in case
3074 * the buffer changed identities.
3076 if (error == ENOLCK)
3078 /* We timed out or were interrupted. */
3081 /* If recursed, assume caller knows the rules. */
3082 else if (BUF_LOCKRECURSED(bp))
3086 * The buffer is locked. B_CACHE is cleared if the buffer is
3087 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
3088 * and for a VMIO buffer B_CACHE is adjusted according to the
3091 if (bp->b_flags & B_INVAL)
3092 bp->b_flags &= ~B_CACHE;
3093 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
3094 bp->b_flags |= B_CACHE;
3095 if (bp->b_flags & B_MANAGED)
3096 MPASS(bp->b_qindex == QUEUE_NONE);
3104 * check for size inconsistencies for non-VMIO case.
3106 if (bp->b_bcount != size) {
3107 if ((bp->b_flags & B_VMIO) == 0 ||
3108 (size > bp->b_kvasize)) {
3109 if (bp->b_flags & B_DELWRI) {
3111 * If buffer is pinned and caller does
3112 * not want sleep waiting for it to be
3113 * unpinned, bail out
3115 if (bp->b_pin_count > 0) {
3116 if (flags & GB_LOCK_NOWAIT) {
3123 bp->b_flags |= B_NOCACHE;
3126 if (LIST_EMPTY(&bp->b_dep)) {
3127 bp->b_flags |= B_RELBUF;
3130 bp->b_flags |= B_NOCACHE;
3139 * Handle the case of unmapped buffer which should
3140 * become mapped, or the buffer for which KVA
3141 * reservation is requested.
3143 bp_unmapped_get_kva(bp, blkno, size, flags);
3146 * If the size is inconsistant in the VMIO case, we can resize
3147 * the buffer. This might lead to B_CACHE getting set or
3148 * cleared. If the size has not changed, B_CACHE remains
3149 * unchanged from its previous state.
3151 if (bp->b_bcount != size)
3154 KASSERT(bp->b_offset != NOOFFSET,
3155 ("getblk: no buffer offset"));
3158 * A buffer with B_DELWRI set and B_CACHE clear must
3159 * be committed before we can return the buffer in
3160 * order to prevent the caller from issuing a read
3161 * ( due to B_CACHE not being set ) and overwriting
3164 * Most callers, including NFS and FFS, need this to
3165 * operate properly either because they assume they
3166 * can issue a read if B_CACHE is not set, or because
3167 * ( for example ) an uncached B_DELWRI might loop due
3168 * to softupdates re-dirtying the buffer. In the latter
3169 * case, B_CACHE is set after the first write completes,
3170 * preventing further loops.
3171 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
3172 * above while extending the buffer, we cannot allow the
3173 * buffer to remain with B_CACHE set after the write
3174 * completes or it will represent a corrupt state. To
3175 * deal with this we set B_NOCACHE to scrap the buffer
3178 * We might be able to do something fancy, like setting
3179 * B_CACHE in bwrite() except if B_DELWRI is already set,
3180 * so the below call doesn't set B_CACHE, but that gets real
3181 * confusing. This is much easier.
3184 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
3185 bp->b_flags |= B_NOCACHE;
3189 bp->b_flags &= ~B_DONE;
3192 * Buffer is not in-core, create new buffer. The buffer
3193 * returned by getnewbuf() is locked. Note that the returned
3194 * buffer is also considered valid (not marked B_INVAL).
3198 * If the user does not want us to create the buffer, bail out
3201 if (flags & GB_NOCREAT)
3203 bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
3204 offset = blkno * bsize;
3205 vmio = vp->v_object != NULL;
3207 maxsize = size + (offset & PAGE_MASK);
3210 /* Do not allow non-VMIO notmapped buffers. */
3211 flags &= ~GB_UNMAPPED;
3213 maxsize = imax(maxsize, bsize);
3215 bp = getnewbuf(vp, slpflag, slptimeo, size, maxsize, flags);
3217 if (slpflag || slptimeo)
3223 * This code is used to make sure that a buffer is not
3224 * created while the getnewbuf routine is blocked.
3225 * This can be a problem whether the vnode is locked or not.
3226 * If the buffer is created out from under us, we have to
3227 * throw away the one we just created.
3229 * Note: this must occur before we associate the buffer
3230 * with the vp especially considering limitations in
3231 * the splay tree implementation when dealing with duplicate
3235 if (gbincore(bo, blkno)) {
3237 bp->b_flags |= B_INVAL;
3243 * Insert the buffer into the hash, so that it can
3244 * be found by incore.
3246 bp->b_blkno = bp->b_lblkno = blkno;
3247 bp->b_offset = offset;
3252 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
3253 * buffer size starts out as 0, B_CACHE will be set by
3254 * allocbuf() for the VMIO case prior to it testing the
3255 * backing store for validity.
3259 bp->b_flags |= B_VMIO;
3260 KASSERT(vp->v_object == bp->b_bufobj->bo_object,
3261 ("ARGH! different b_bufobj->bo_object %p %p %p\n",
3262 bp, vp->v_object, bp->b_bufobj->bo_object));
3264 bp->b_flags &= ~B_VMIO;
3265 KASSERT(bp->b_bufobj->bo_object == NULL,
3266 ("ARGH! has b_bufobj->bo_object %p %p\n",
3267 bp, bp->b_bufobj->bo_object));
3268 BUF_CHECK_MAPPED(bp);
3272 bp->b_flags &= ~B_DONE;
3274 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
3275 BUF_ASSERT_HELD(bp);
3277 KASSERT(bp->b_bufobj == bo,
3278 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3283 * Get an empty, disassociated buffer of given size. The buffer is initially
3287 geteblk(int size, int flags)
3292 maxsize = (size + BKVAMASK) & ~BKVAMASK;
3293 while ((bp = getnewbuf(NULL, 0, 0, size, maxsize, flags)) == NULL) {
3294 if ((flags & GB_NOWAIT_BD) &&
3295 (curthread->td_pflags & TDP_BUFNEED) != 0)
3299 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
3300 BUF_ASSERT_HELD(bp);
3306 * This code constitutes the buffer memory from either anonymous system
3307 * memory (in the case of non-VMIO operations) or from an associated
3308 * VM object (in the case of VMIO operations). This code is able to
3309 * resize a buffer up or down.
3311 * Note that this code is tricky, and has many complications to resolve
3312 * deadlock or inconsistant data situations. Tread lightly!!!
3313 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3314 * the caller. Calling this code willy nilly can result in the loss of data.
3316 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
3317 * B_CACHE for the non-VMIO case.
3321 allocbuf(struct buf *bp, int size)
3323 int newbsize, mbsize;
3326 BUF_ASSERT_HELD(bp);
3328 if (bp->b_kvasize < size)
3329 panic("allocbuf: buffer too small");
3331 if ((bp->b_flags & B_VMIO) == 0) {
3335 * Just get anonymous memory from the kernel. Don't
3336 * mess with B_CACHE.
3338 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3339 if (bp->b_flags & B_MALLOC)
3342 newbsize = round_page(size);
3344 if (newbsize < bp->b_bufsize) {
3346 * malloced buffers are not shrunk
3348 if (bp->b_flags & B_MALLOC) {
3350 bp->b_bcount = size;
3352 free(bp->b_data, M_BIOBUF);
3353 if (bp->b_bufsize) {
3354 atomic_subtract_long(
3360 bp->b_saveaddr = bp->b_kvabase;
3361 bp->b_data = bp->b_saveaddr;
3363 bp->b_flags &= ~B_MALLOC;
3367 vm_hold_free_pages(bp, newbsize);
3368 } else if (newbsize > bp->b_bufsize) {
3370 * We only use malloced memory on the first allocation.
3371 * and revert to page-allocated memory when the buffer
3375 * There is a potential smp race here that could lead
3376 * to bufmallocspace slightly passing the max. It
3377 * is probably extremely rare and not worth worrying
3380 if ( (bufmallocspace < maxbufmallocspace) &&
3381 (bp->b_bufsize == 0) &&
3382 (mbsize <= PAGE_SIZE/2)) {
3384 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
3385 bp->b_bufsize = mbsize;
3386 bp->b_bcount = size;
3387 bp->b_flags |= B_MALLOC;
3388 atomic_add_long(&bufmallocspace, mbsize);
3394 * If the buffer is growing on its other-than-first allocation,
3395 * then we revert to the page-allocation scheme.
3397 if (bp->b_flags & B_MALLOC) {
3398 origbuf = bp->b_data;
3399 origbufsize = bp->b_bufsize;
3400 bp->b_data = bp->b_kvabase;
3401 if (bp->b_bufsize) {
3402 atomic_subtract_long(&bufmallocspace,
3407 bp->b_flags &= ~B_MALLOC;
3408 newbsize = round_page(newbsize);
3412 (vm_offset_t) bp->b_data + bp->b_bufsize,
3413 (vm_offset_t) bp->b_data + newbsize);
3415 bcopy(origbuf, bp->b_data, origbufsize);
3416 free(origbuf, M_BIOBUF);
3422 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3423 desiredpages = (size == 0) ? 0 :
3424 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
3426 if (bp->b_flags & B_MALLOC)
3427 panic("allocbuf: VMIO buffer can't be malloced");
3429 * Set B_CACHE initially if buffer is 0 length or will become
3432 if (size == 0 || bp->b_bufsize == 0)
3433 bp->b_flags |= B_CACHE;
3435 if (newbsize < bp->b_bufsize) {
3437 * DEV_BSIZE aligned new buffer size is less then the
3438 * DEV_BSIZE aligned existing buffer size. Figure out
3439 * if we have to remove any pages.
3441 if (desiredpages < bp->b_npages) {
3444 if ((bp->b_flags & B_UNMAPPED) == 0) {
3445 BUF_CHECK_MAPPED(bp);
3446 pmap_qremove((vm_offset_t)trunc_page(
3447 (vm_offset_t)bp->b_data) +
3448 (desiredpages << PAGE_SHIFT),
3449 (bp->b_npages - desiredpages));
3451 BUF_CHECK_UNMAPPED(bp);
3452 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
3453 for (i = desiredpages; i < bp->b_npages; i++) {
3455 * the page is not freed here -- it
3456 * is the responsibility of
3457 * vnode_pager_setsize
3460 KASSERT(m != bogus_page,
3461 ("allocbuf: bogus page found"));
3462 while (vm_page_sleep_if_busy(m, TRUE,
3466 bp->b_pages[i] = NULL;
3468 vm_page_unwire(m, 0);
3471 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
3472 bp->b_npages = desiredpages;
3474 } else if (size > bp->b_bcount) {
3476 * We are growing the buffer, possibly in a
3477 * byte-granular fashion.
3484 * Step 1, bring in the VM pages from the object,
3485 * allocating them if necessary. We must clear
3486 * B_CACHE if these pages are not valid for the
3487 * range covered by the buffer.
3490 obj = bp->b_bufobj->bo_object;
3492 VM_OBJECT_WLOCK(obj);
3493 while (bp->b_npages < desiredpages) {
3497 * We must allocate system pages since blocking
3498 * here could interfere with paging I/O, no
3499 * matter which process we are.
3501 * We can only test VPO_BUSY here. Blocking on
3502 * m->busy might lead to a deadlock:
3503 * vm_fault->getpages->cluster_read->allocbuf
3504 * Thus, we specify VM_ALLOC_IGN_SBUSY.
3506 m = vm_page_grab(obj, OFF_TO_IDX(bp->b_offset) +
3507 bp->b_npages, VM_ALLOC_NOBUSY |
3508 VM_ALLOC_SYSTEM | VM_ALLOC_WIRED |
3509 VM_ALLOC_RETRY | VM_ALLOC_IGN_SBUSY |
3510 VM_ALLOC_COUNT(desiredpages - bp->b_npages));
3512 bp->b_flags &= ~B_CACHE;
3513 bp->b_pages[bp->b_npages] = m;
3518 * Step 2. We've loaded the pages into the buffer,
3519 * we have to figure out if we can still have B_CACHE
3520 * set. Note that B_CACHE is set according to the
3521 * byte-granular range ( bcount and size ), new the
3522 * aligned range ( newbsize ).
3524 * The VM test is against m->valid, which is DEV_BSIZE
3525 * aligned. Needless to say, the validity of the data
3526 * needs to also be DEV_BSIZE aligned. Note that this
3527 * fails with NFS if the server or some other client
3528 * extends the file's EOF. If our buffer is resized,
3529 * B_CACHE may remain set! XXX
3532 toff = bp->b_bcount;
3533 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
3535 while ((bp->b_flags & B_CACHE) && toff < size) {
3538 if (tinc > (size - toff))
3541 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
3554 VM_OBJECT_WUNLOCK(obj);
3557 * Step 3, fixup the KVM pmap.
3559 if ((bp->b_flags & B_UNMAPPED) == 0)
3562 BUF_CHECK_UNMAPPED(bp);
3565 if (newbsize < bp->b_bufsize)
3567 bp->b_bufsize = newbsize; /* actual buffer allocation */
3568 bp->b_bcount = size; /* requested buffer size */
3572 extern int inflight_transient_maps;
3575 biodone(struct bio *bp)
3578 void (*done)(struct bio *);
3579 vm_offset_t start, end;
3582 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3584 bp->bio_flags |= BIO_DONE;
3585 if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) {
3586 start = trunc_page((vm_offset_t)bp->bio_data);
3587 end = round_page((vm_offset_t)bp->bio_data + bp->bio_length);
3593 done = bp->bio_done;
3600 pmap_qremove(start, OFF_TO_IDX(end - start));
3601 vm_map_remove(bio_transient_map, start, end);
3602 atomic_add_int(&inflight_transient_maps, -1);
3607 * Wait for a BIO to finish.
3609 * XXX: resort to a timeout for now. The optimal locking (if any) for this
3610 * case is not yet clear.
3613 biowait(struct bio *bp, const char *wchan)
3617 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3619 while ((bp->bio_flags & BIO_DONE) == 0)
3620 msleep(bp, mtxp, PRIBIO, wchan, hz / 10);
3622 if (bp->bio_error != 0)
3623 return (bp->bio_error);
3624 if (!(bp->bio_flags & BIO_ERROR))
3630 biofinish(struct bio *bp, struct devstat *stat, int error)
3634 bp->bio_error = error;
3635 bp->bio_flags |= BIO_ERROR;
3638 devstat_end_transaction_bio(stat, bp);
3645 * Wait for buffer I/O completion, returning error status. The buffer
3646 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR
3647 * error and cleared.
3650 bufwait(struct buf *bp)
3652 if (bp->b_iocmd == BIO_READ)
3653 bwait(bp, PRIBIO, "biord");
3655 bwait(bp, PRIBIO, "biowr");
3656 if (bp->b_flags & B_EINTR) {
3657 bp->b_flags &= ~B_EINTR;
3660 if (bp->b_ioflags & BIO_ERROR) {
3661 return (bp->b_error ? bp->b_error : EIO);
3668 * Call back function from struct bio back up to struct buf.
3671 bufdonebio(struct bio *bip)
3675 bp = bip->bio_caller2;
3676 bp->b_resid = bp->b_bcount - bip->bio_completed;
3677 bp->b_resid = bip->bio_resid; /* XXX: remove */
3678 bp->b_ioflags = bip->bio_flags;
3679 bp->b_error = bip->bio_error;
3681 bp->b_ioflags |= BIO_ERROR;
3687 dev_strategy(struct cdev *dev, struct buf *bp)
3692 KASSERT(dev->si_refcount > 0,
3693 ("dev_strategy on un-referenced struct cdev *(%s) %p",
3694 devtoname(dev), dev));
3696 csw = dev_refthread(dev, &ref);
3697 dev_strategy_csw(dev, csw, bp);
3698 dev_relthread(dev, ref);
3702 dev_strategy_csw(struct cdev *dev, struct cdevsw *csw, struct buf *bp)
3706 KASSERT(bp->b_iocmd == BIO_READ || bp->b_iocmd == BIO_WRITE,
3708 KASSERT(((dev->si_flags & SI_ETERNAL) != 0 && csw != NULL) ||
3709 dev->si_threadcount > 0,
3710 ("dev_strategy_csw threadcount cdev *(%s) %p", devtoname(dev),
3713 bp->b_error = ENXIO;
3714 bp->b_ioflags = BIO_ERROR;
3722 /* Try again later */
3723 tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3725 bip->bio_cmd = bp->b_iocmd;
3726 bip->bio_offset = bp->b_iooffset;
3727 bip->bio_length = bp->b_bcount;
3728 bip->bio_bcount = bp->b_bcount; /* XXX: remove */
3730 bip->bio_done = bufdonebio;
3731 bip->bio_caller2 = bp;
3733 (*csw->d_strategy)(bip);
3739 * Finish I/O on a buffer, optionally calling a completion function.
3740 * This is usually called from an interrupt so process blocking is
3743 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3744 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3745 * assuming B_INVAL is clear.
3747 * For the VMIO case, we set B_CACHE if the op was a read and no
3748 * read error occured, or if the op was a write. B_CACHE is never
3749 * set if the buffer is invalid or otherwise uncacheable.
3751 * biodone does not mess with B_INVAL, allowing the I/O routine or the
3752 * initiator to leave B_INVAL set to brelse the buffer out of existance
3753 * in the biodone routine.
3756 bufdone(struct buf *bp)
3758 struct bufobj *dropobj;
3759 void (*biodone)(struct buf *);
3761 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3764 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3765 BUF_ASSERT_HELD(bp);
3767 runningbufwakeup(bp);
3768 if (bp->b_iocmd == BIO_WRITE)
3769 dropobj = bp->b_bufobj;
3770 /* call optional completion function if requested */
3771 if (bp->b_iodone != NULL) {
3772 biodone = bp->b_iodone;
3773 bp->b_iodone = NULL;
3776 bufobj_wdrop(dropobj);
3783 bufobj_wdrop(dropobj);
3787 bufdone_finish(struct buf *bp)
3789 BUF_ASSERT_HELD(bp);
3791 if (!LIST_EMPTY(&bp->b_dep))
3794 if (bp->b_flags & B_VMIO) {
3799 int bogus, i, iosize;
3801 obj = bp->b_bufobj->bo_object;
3802 KASSERT(obj->paging_in_progress >= bp->b_npages,
3803 ("biodone_finish: paging in progress(%d) < b_npages(%d)",
3804 obj->paging_in_progress, bp->b_npages));
3807 KASSERT(vp->v_holdcnt > 0,
3808 ("biodone_finish: vnode %p has zero hold count", vp));
3809 KASSERT(vp->v_object != NULL,
3810 ("biodone_finish: vnode %p has no vm_object", vp));
3812 foff = bp->b_offset;
3813 KASSERT(bp->b_offset != NOOFFSET,
3814 ("biodone_finish: bp %p has no buffer offset", bp));
3817 * Set B_CACHE if the op was a normal read and no error
3818 * occured. B_CACHE is set for writes in the b*write()
3821 iosize = bp->b_bcount - bp->b_resid;
3822 if (bp->b_iocmd == BIO_READ &&
3823 !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3824 !(bp->b_ioflags & BIO_ERROR)) {
3825 bp->b_flags |= B_CACHE;
3828 VM_OBJECT_WLOCK(obj);
3829 for (i = 0; i < bp->b_npages; i++) {
3833 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3838 * cleanup bogus pages, restoring the originals
3841 if (m == bogus_page) {
3842 bogus = bogusflag = 1;
3843 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3845 panic("biodone: page disappeared!");
3848 KASSERT(OFF_TO_IDX(foff) == m->pindex,
3849 ("biodone_finish: foff(%jd)/pindex(%ju) mismatch",
3850 (intmax_t)foff, (uintmax_t)m->pindex));
3853 * In the write case, the valid and clean bits are
3854 * already changed correctly ( see bdwrite() ), so we
3855 * only need to do this here in the read case.
3857 if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3858 KASSERT((m->dirty & vm_page_bits(foff &
3859 PAGE_MASK, resid)) == 0, ("bufdone_finish:"
3860 " page %p has unexpected dirty bits", m));
3861 vfs_page_set_valid(bp, foff, m);
3864 vm_page_io_finish(m);
3865 vm_object_pip_subtract(obj, 1);
3866 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3869 vm_object_pip_wakeupn(obj, 0);
3870 VM_OBJECT_WUNLOCK(obj);
3871 if (bogus && (bp->b_flags & B_UNMAPPED) == 0) {
3872 BUF_CHECK_MAPPED(bp);
3873 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3874 bp->b_pages, bp->b_npages);
3879 * For asynchronous completions, release the buffer now. The brelse
3880 * will do a wakeup there if necessary - so no need to do a wakeup
3881 * here in the async case. The sync case always needs to do a wakeup.
3884 if (bp->b_flags & B_ASYNC) {
3885 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3894 * This routine is called in lieu of iodone in the case of
3895 * incomplete I/O. This keeps the busy status for pages
3899 vfs_unbusy_pages(struct buf *bp)
3905 runningbufwakeup(bp);
3906 if (!(bp->b_flags & B_VMIO))
3909 obj = bp->b_bufobj->bo_object;
3910 VM_OBJECT_WLOCK(obj);
3911 for (i = 0; i < bp->b_npages; i++) {
3913 if (m == bogus_page) {
3914 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3916 panic("vfs_unbusy_pages: page missing\n");
3918 if ((bp->b_flags & B_UNMAPPED) == 0) {
3919 BUF_CHECK_MAPPED(bp);
3920 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3921 bp->b_pages, bp->b_npages);
3923 BUF_CHECK_UNMAPPED(bp);
3925 vm_object_pip_subtract(obj, 1);
3926 vm_page_io_finish(m);
3928 vm_object_pip_wakeupn(obj, 0);
3929 VM_OBJECT_WUNLOCK(obj);
3933 * vfs_page_set_valid:
3935 * Set the valid bits in a page based on the supplied offset. The
3936 * range is restricted to the buffer's size.
3938 * This routine is typically called after a read completes.
3941 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3946 * Compute the end offset, eoff, such that [off, eoff) does not span a
3947 * page boundary and eoff is not greater than the end of the buffer.
3948 * The end of the buffer, in this case, is our file EOF, not the
3949 * allocation size of the buffer.
3951 eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
3952 if (eoff > bp->b_offset + bp->b_bcount)
3953 eoff = bp->b_offset + bp->b_bcount;
3956 * Set valid range. This is typically the entire buffer and thus the
3960 vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off);
3964 * vfs_page_set_validclean:
3966 * Set the valid bits and clear the dirty bits in a page based on the
3967 * supplied offset. The range is restricted to the buffer's size.
3970 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3972 vm_ooffset_t soff, eoff;
3975 * Start and end offsets in buffer. eoff - soff may not cross a
3976 * page boundry or cross the end of the buffer. The end of the
3977 * buffer, in this case, is our file EOF, not the allocation size
3981 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3982 if (eoff > bp->b_offset + bp->b_bcount)
3983 eoff = bp->b_offset + bp->b_bcount;
3986 * Set valid range. This is typically the entire buffer and thus the
3990 vm_page_set_validclean(
3992 (vm_offset_t) (soff & PAGE_MASK),
3993 (vm_offset_t) (eoff - soff)
3999 * Ensure that all buffer pages are not busied by VPO_BUSY flag. If
4000 * any page is busy, drain the flag.
4003 vfs_drain_busy_pages(struct buf *bp)
4008 VM_OBJECT_ASSERT_WLOCKED(bp->b_bufobj->bo_object);
4010 for (i = 0; i < bp->b_npages; i++) {
4012 if ((m->oflags & VPO_BUSY) != 0) {
4013 for (; last_busied < i; last_busied++)
4014 vm_page_busy(bp->b_pages[last_busied]);
4015 while ((m->oflags & VPO_BUSY) != 0)
4016 vm_page_sleep(m, "vbpage");
4019 for (i = 0; i < last_busied; i++)
4020 vm_page_wakeup(bp->b_pages[i]);
4024 * This routine is called before a device strategy routine.
4025 * It is used to tell the VM system that paging I/O is in
4026 * progress, and treat the pages associated with the buffer
4027 * almost as being VPO_BUSY. Also the object paging_in_progress
4028 * flag is handled to make sure that the object doesn't become
4031 * Since I/O has not been initiated yet, certain buffer flags
4032 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
4033 * and should be ignored.
4036 vfs_busy_pages(struct buf *bp, int clear_modify)
4043 if (!(bp->b_flags & B_VMIO))
4046 obj = bp->b_bufobj->bo_object;
4047 foff = bp->b_offset;
4048 KASSERT(bp->b_offset != NOOFFSET,
4049 ("vfs_busy_pages: no buffer offset"));
4050 VM_OBJECT_WLOCK(obj);
4051 vfs_drain_busy_pages(bp);
4052 if (bp->b_bufsize != 0)
4053 vfs_setdirty_locked_object(bp);
4055 for (i = 0; i < bp->b_npages; i++) {
4058 if ((bp->b_flags & B_CLUSTER) == 0) {
4059 vm_object_pip_add(obj, 1);
4060 vm_page_io_start(m);
4063 * When readying a buffer for a read ( i.e
4064 * clear_modify == 0 ), it is important to do
4065 * bogus_page replacement for valid pages in
4066 * partially instantiated buffers. Partially
4067 * instantiated buffers can, in turn, occur when
4068 * reconstituting a buffer from its VM backing store
4069 * base. We only have to do this if B_CACHE is
4070 * clear ( which causes the I/O to occur in the
4071 * first place ). The replacement prevents the read
4072 * I/O from overwriting potentially dirty VM-backed
4073 * pages. XXX bogus page replacement is, uh, bogus.
4074 * It may not work properly with small-block devices.
4075 * We need to find a better way.
4078 pmap_remove_write(m);
4079 vfs_page_set_validclean(bp, foff, m);
4080 } else if (m->valid == VM_PAGE_BITS_ALL &&
4081 (bp->b_flags & B_CACHE) == 0) {
4082 bp->b_pages[i] = bogus_page;
4085 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4087 VM_OBJECT_WUNLOCK(obj);
4088 if (bogus && (bp->b_flags & B_UNMAPPED) == 0) {
4089 BUF_CHECK_MAPPED(bp);
4090 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4091 bp->b_pages, bp->b_npages);
4096 * vfs_bio_set_valid:
4098 * Set the range within the buffer to valid. The range is
4099 * relative to the beginning of the buffer, b_offset. Note that
4100 * b_offset itself may be offset from the beginning of the first
4104 vfs_bio_set_valid(struct buf *bp, int base, int size)
4109 if (!(bp->b_flags & B_VMIO))
4113 * Fixup base to be relative to beginning of first page.
4114 * Set initial n to be the maximum number of bytes in the
4115 * first page that can be validated.
4117 base += (bp->b_offset & PAGE_MASK);
4118 n = PAGE_SIZE - (base & PAGE_MASK);
4120 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4121 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4125 vm_page_set_valid_range(m, base & PAGE_MASK, n);
4130 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4136 * If the specified buffer is a non-VMIO buffer, clear the entire
4137 * buffer. If the specified buffer is a VMIO buffer, clear and
4138 * validate only the previously invalid portions of the buffer.
4139 * This routine essentially fakes an I/O, so we need to clear
4140 * BIO_ERROR and B_INVAL.
4142 * Note that while we only theoretically need to clear through b_bcount,
4143 * we go ahead and clear through b_bufsize.
4146 vfs_bio_clrbuf(struct buf *bp)
4148 int i, j, mask, sa, ea, slide;
4150 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
4154 bp->b_flags &= ~B_INVAL;
4155 bp->b_ioflags &= ~BIO_ERROR;
4156 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4157 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4158 (bp->b_offset & PAGE_MASK) == 0) {
4159 if (bp->b_pages[0] == bogus_page)
4161 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4162 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[0]->object);
4163 if ((bp->b_pages[0]->valid & mask) == mask)
4165 if ((bp->b_pages[0]->valid & mask) == 0) {
4166 pmap_zero_page_area(bp->b_pages[0], 0, bp->b_bufsize);
4167 bp->b_pages[0]->valid |= mask;
4171 sa = bp->b_offset & PAGE_MASK;
4173 for (i = 0; i < bp->b_npages; i++, sa = 0) {
4174 slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize);
4175 ea = slide & PAGE_MASK;
4178 if (bp->b_pages[i] == bogus_page)
4181 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4182 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[i]->object);
4183 if ((bp->b_pages[i]->valid & mask) == mask)
4185 if ((bp->b_pages[i]->valid & mask) == 0)
4186 pmap_zero_page_area(bp->b_pages[i], sa, ea - sa);
4188 for (; sa < ea; sa += DEV_BSIZE, j++) {
4189 if ((bp->b_pages[i]->valid & (1 << j)) == 0) {
4190 pmap_zero_page_area(bp->b_pages[i],
4195 bp->b_pages[i]->valid |= mask;
4198 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4203 vfs_bio_bzero_buf(struct buf *bp, int base, int size)
4208 if ((bp->b_flags & B_UNMAPPED) == 0) {
4209 BUF_CHECK_MAPPED(bp);
4210 bzero(bp->b_data + base, size);
4212 BUF_CHECK_UNMAPPED(bp);
4213 n = PAGE_SIZE - (base & PAGE_MASK);
4214 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4215 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4219 pmap_zero_page_area(m, base & PAGE_MASK, n);
4224 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4229 * vm_hold_load_pages and vm_hold_free_pages get pages into
4230 * a buffers address space. The pages are anonymous and are
4231 * not associated with a file object.
4234 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4240 BUF_CHECK_MAPPED(bp);
4242 to = round_page(to);
4243 from = round_page(from);
4244 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4246 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4249 * note: must allocate system pages since blocking here
4250 * could interfere with paging I/O, no matter which
4253 p = vm_page_alloc(NULL, 0, VM_ALLOC_SYSTEM | VM_ALLOC_NOOBJ |
4254 VM_ALLOC_WIRED | VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT));
4259 pmap_qenter(pg, &p, 1);
4260 bp->b_pages[index] = p;
4262 bp->b_npages = index;
4265 /* Return pages associated with this buf to the vm system */
4267 vm_hold_free_pages(struct buf *bp, int newbsize)
4271 int index, newnpages;
4273 BUF_CHECK_MAPPED(bp);
4275 from = round_page((vm_offset_t)bp->b_data + newbsize);
4276 newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4277 if (bp->b_npages > newnpages)
4278 pmap_qremove(from, bp->b_npages - newnpages);
4279 for (index = newnpages; index < bp->b_npages; index++) {
4280 p = bp->b_pages[index];
4281 bp->b_pages[index] = NULL;
4283 printf("vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
4284 (intmax_t)bp->b_blkno, (intmax_t)bp->b_lblkno);
4287 atomic_subtract_int(&cnt.v_wire_count, 1);
4289 bp->b_npages = newnpages;
4293 * Map an IO request into kernel virtual address space.
4295 * All requests are (re)mapped into kernel VA space.
4296 * Notice that we use b_bufsize for the size of the buffer
4297 * to be mapped. b_bcount might be modified by the driver.
4299 * Note that even if the caller determines that the address space should
4300 * be valid, a race or a smaller-file mapped into a larger space may
4301 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
4302 * check the return value.
4305 vmapbuf(struct buf *bp, int mapbuf)
4311 if (bp->b_bufsize < 0)
4313 prot = VM_PROT_READ;
4314 if (bp->b_iocmd == BIO_READ)
4315 prot |= VM_PROT_WRITE; /* Less backwards than it looks */
4316 if ((pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
4317 (vm_offset_t)bp->b_data, bp->b_bufsize, prot, bp->b_pages,
4318 btoc(MAXPHYS))) < 0)
4320 bp->b_npages = pidx;
4321 if (mapbuf || !unmapped_buf_allowed) {
4322 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
4323 kva = bp->b_saveaddr;
4324 bp->b_saveaddr = bp->b_data;
4325 bp->b_data = kva + (((vm_offset_t)bp->b_data) & PAGE_MASK);
4326 bp->b_flags &= ~B_UNMAPPED;
4328 bp->b_flags |= B_UNMAPPED;
4329 bp->b_offset = ((vm_offset_t)bp->b_data) & PAGE_MASK;
4330 bp->b_saveaddr = bp->b_data;
4331 bp->b_data = unmapped_buf;
4337 * Free the io map PTEs associated with this IO operation.
4338 * We also invalidate the TLB entries and restore the original b_addr.
4341 vunmapbuf(struct buf *bp)
4345 npages = bp->b_npages;
4346 if (bp->b_flags & B_UNMAPPED)
4347 bp->b_flags &= ~B_UNMAPPED;
4349 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4350 vm_page_unhold_pages(bp->b_pages, npages);
4352 bp->b_data = bp->b_saveaddr;
4356 bdone(struct buf *bp)
4360 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4362 bp->b_flags |= B_DONE;
4368 bwait(struct buf *bp, u_char pri, const char *wchan)
4372 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4374 while ((bp->b_flags & B_DONE) == 0)
4375 msleep(bp, mtxp, pri, wchan, 0);
4380 bufsync(struct bufobj *bo, int waitfor)
4383 return (VOP_FSYNC(bo->__bo_vnode, waitfor, curthread));
4387 bufstrategy(struct bufobj *bo, struct buf *bp)
4393 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
4394 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
4395 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
4396 i = VOP_STRATEGY(vp, bp);
4397 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
4401 bufobj_wrefl(struct bufobj *bo)
4404 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4405 ASSERT_BO_LOCKED(bo);
4410 bufobj_wref(struct bufobj *bo)
4413 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4420 bufobj_wdrop(struct bufobj *bo)
4423 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
4425 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
4426 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
4427 bo->bo_flag &= ~BO_WWAIT;
4428 wakeup(&bo->bo_numoutput);
4434 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
4438 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
4439 ASSERT_BO_LOCKED(bo);
4441 while (bo->bo_numoutput) {
4442 bo->bo_flag |= BO_WWAIT;
4443 error = msleep(&bo->bo_numoutput, BO_MTX(bo),
4444 slpflag | (PRIBIO + 1), "bo_wwait", timeo);
4452 bpin(struct buf *bp)
4456 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4463 bunpin(struct buf *bp)
4467 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4469 if (--bp->b_pin_count == 0)
4475 bunpin_wait(struct buf *bp)
4479 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4481 while (bp->b_pin_count > 0)
4482 msleep(bp, mtxp, PRIBIO, "bwunpin", 0);
4487 * Set bio_data or bio_ma for struct bio from the struct buf.
4490 bdata2bio(struct buf *bp, struct bio *bip)
4493 if ((bp->b_flags & B_UNMAPPED) != 0) {
4494 KASSERT(unmapped_buf_allowed, ("unmapped"));
4495 bip->bio_ma = bp->b_pages;
4496 bip->bio_ma_n = bp->b_npages;
4497 bip->bio_data = unmapped_buf;
4498 bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
4499 bip->bio_flags |= BIO_UNMAPPED;
4500 KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) /
4501 PAGE_SIZE == bp->b_npages,
4502 ("Buffer %p too short: %d %d %d", bp, bip->bio_ma_offset,
4503 bip->bio_length, bip->bio_ma_n));
4505 bip->bio_data = bp->b_data;
4510 #include "opt_ddb.h"
4512 #include <ddb/ddb.h>
4514 /* DDB command to show buffer data */
4515 DB_SHOW_COMMAND(buffer, db_show_buffer)
4518 struct buf *bp = (struct buf *)addr;
4521 db_printf("usage: show buffer <addr>\n");
4525 db_printf("buf at %p\n", bp);
4526 db_printf("b_flags = 0x%b, b_xflags=0x%b, b_vflags=0x%b\n",
4527 (u_int)bp->b_flags, PRINT_BUF_FLAGS, (u_int)bp->b_xflags,
4528 PRINT_BUF_XFLAGS, (u_int)bp->b_vflags, PRINT_BUF_VFLAGS);
4530 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4531 "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_lblkno = %jd, "
4533 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4534 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4535 (intmax_t)bp->b_lblkno, bp->b_dep.lh_first);
4538 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4539 for (i = 0; i < bp->b_npages; i++) {
4542 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4543 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4544 if ((i + 1) < bp->b_npages)
4550 BUF_LOCKPRINTINFO(bp);
4553 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
4558 for (i = 0; i < nbuf; i++) {
4560 if (BUF_ISLOCKED(bp)) {
4561 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4567 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
4573 db_printf("usage: show vnodebufs <addr>\n");
4576 vp = (struct vnode *)addr;
4577 db_printf("Clean buffers:\n");
4578 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
4579 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4582 db_printf("Dirty buffers:\n");
4583 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
4584 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4589 DB_COMMAND(countfreebufs, db_coundfreebufs)
4592 int i, used = 0, nfree = 0;
4595 db_printf("usage: countfreebufs\n");
4599 for (i = 0; i < nbuf; i++) {
4601 if ((bp->b_vflags & BV_INFREECNT) != 0)
4607 db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
4609 db_printf("numfreebuffers is %d\n", numfreebuffers);