2 * Copyright (c) 2004 Poul-Henning Kamp
3 * Copyright (c) 1994,1997 John S. Dyson
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * this file contains a new buffer I/O scheme implementing a coherent
30 * VM object and buffer cache scheme. Pains have been taken to make
31 * sure that the performance degradation associated with schemes such
32 * as this is not realized.
34 * Author: John S. Dyson
35 * Significant help during the development and debugging phases
36 * had been provided by David Greenman, also of the FreeBSD core team.
38 * see man buf(9) for more info.
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
44 #include <sys/param.h>
45 #include <sys/systm.h>
49 #include <sys/devicestat.h>
50 #include <sys/eventhandler.h>
52 #include <sys/limits.h>
54 #include <sys/malloc.h>
55 #include <sys/mount.h>
56 #include <sys/mutex.h>
57 #include <sys/kernel.h>
58 #include <sys/kthread.h>
60 #include <sys/resourcevar.h>
61 #include <sys/sysctl.h>
62 #include <sys/vmmeter.h>
63 #include <sys/vnode.h>
64 #include <geom/geom.h>
66 #include <vm/vm_param.h>
67 #include <vm/vm_kern.h>
68 #include <vm/vm_pageout.h>
69 #include <vm/vm_page.h>
70 #include <vm/vm_object.h>
71 #include <vm/vm_extern.h>
72 #include <vm/vm_map.h>
73 #include "opt_compat.h"
74 #include "opt_directio.h"
77 static MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
79 struct bio_ops bioops; /* I/O operation notification */
81 struct buf_ops buf_ops_bio = {
82 .bop_name = "buf_ops_bio",
83 .bop_write = bufwrite,
84 .bop_strategy = bufstrategy,
86 .bop_bdflush = bufbdflush,
90 * XXX buf is global because kern_shutdown.c and ffs_checkoverlap has
91 * carnal knowledge of buffers. This knowledge should be moved to vfs_bio.c.
93 struct buf *buf; /* buffer header pool */
95 static struct proc *bufdaemonproc;
97 static int inmem(struct vnode *vp, daddr_t blkno);
98 static void vm_hold_free_pages(struct buf *bp, int newbsize);
99 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
101 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m);
102 static void vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off,
104 static void vfs_drain_busy_pages(struct buf *bp);
105 static void vfs_clean_pages_dirty_buf(struct buf *bp);
106 static void vfs_setdirty_locked_object(struct buf *bp);
107 static void vfs_vmio_release(struct buf *bp);
108 static int vfs_bio_clcheck(struct vnode *vp, int size,
109 daddr_t lblkno, daddr_t blkno);
110 static int buf_do_flush(struct vnode *vp);
111 static int flushbufqueues(struct vnode *, int, int);
112 static void buf_daemon(void);
113 static void bremfreel(struct buf *bp);
114 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
115 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
116 static int sysctl_bufspace(SYSCTL_HANDLER_ARGS);
119 int vmiodirenable = TRUE;
120 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
121 "Use the VM system for directory writes");
122 long runningbufspace;
123 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
124 "Amount of presently outstanding async buffer io");
125 static long bufspace;
126 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
127 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
128 SYSCTL_PROC(_vfs, OID_AUTO, bufspace, CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RD,
129 &bufspace, 0, sysctl_bufspace, "L", "Virtual memory used for buffers");
131 SYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
132 "Virtual memory used for buffers");
134 static long maxbufspace;
135 SYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
136 "Maximum allowed value of bufspace (including buf_daemon)");
137 static long bufmallocspace;
138 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
139 "Amount of malloced memory for buffers");
140 static long maxbufmallocspace;
141 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace, 0,
142 "Maximum amount of malloced memory for buffers");
143 static long lobufspace;
144 SYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
145 "Minimum amount of buffers we want to have");
147 SYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
148 "Maximum allowed value of bufspace (excluding buf_daemon)");
149 static int bufreusecnt;
150 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW, &bufreusecnt, 0,
151 "Number of times we have reused a buffer");
152 static int buffreekvacnt;
153 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
154 "Number of times we have freed the KVA space from some buffer");
155 static int bufdefragcnt;
156 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
157 "Number of times we have had to repeat buffer allocation to defragment");
158 static long lorunningspace;
159 SYSCTL_LONG(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
160 "Minimum preferred space used for in-progress I/O");
161 static long hirunningspace;
162 SYSCTL_LONG(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
163 "Maximum amount of space to use for in-progress I/O");
164 int dirtybufferflushes;
165 SYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
166 0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
168 SYSCTL_INT(_vfs, OID_AUTO, bdwriteskip, CTLFLAG_RW, &bdwriteskip,
169 0, "Number of buffers supplied to bdwrite with snapshot deadlock risk");
170 int altbufferflushes;
171 SYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes,
172 0, "Number of fsync flushes to limit dirty buffers");
173 static int recursiveflushes;
174 SYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes,
175 0, "Number of flushes skipped due to being recursive");
176 static int numdirtybuffers;
177 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
178 "Number of buffers that are dirty (has unwritten changes) at the moment");
179 static int lodirtybuffers;
180 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
181 "How many buffers we want to have free before bufdaemon can sleep");
182 static int hidirtybuffers;
183 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
184 "When the number of dirty buffers is considered severe");
186 SYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh,
187 0, "Number of bdwrite to bawrite conversions to clear dirty buffers");
188 static int numfreebuffers;
189 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
190 "Number of free buffers");
191 static int lofreebuffers;
192 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
194 static int hifreebuffers;
195 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
196 "XXX Complicatedly unused");
197 static int getnewbufcalls;
198 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
199 "Number of calls to getnewbuf");
200 static int getnewbufrestarts;
201 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
202 "Number of times getnewbuf has had to restart a buffer aquisition");
203 static int flushbufqtarget = 100;
204 SYSCTL_INT(_vfs, OID_AUTO, flushbufqtarget, CTLFLAG_RW, &flushbufqtarget, 0,
205 "Amount of work to do in flushbufqueues when helping bufdaemon");
206 static long notbufdflashes;
207 SYSCTL_LONG(_vfs, OID_AUTO, notbufdflashes, CTLFLAG_RD, ¬bufdflashes, 0,
208 "Number of dirty buffer flushes done by the bufdaemon helpers");
209 static long barrierwrites;
210 SYSCTL_LONG(_vfs, OID_AUTO, barrierwrites, CTLFLAG_RW, &barrierwrites, 0,
211 "Number of barrier writes");
214 * Wakeup point for bufdaemon, as well as indicator of whether it is already
215 * active. Set to 1 when the bufdaemon is already "on" the queue, 0 when it
218 static int bd_request;
221 * This lock synchronizes access to bd_request.
223 static struct mtx bdlock;
226 * bogus page -- for I/O to/from partially complete buffers
227 * this is a temporary solution to the problem, but it is not
228 * really that bad. it would be better to split the buffer
229 * for input in the case of buffers partially already in memory,
230 * but the code is intricate enough already.
232 vm_page_t bogus_page;
235 * Synchronization (sleep/wakeup) variable for active buffer space requests.
236 * Set when wait starts, cleared prior to wakeup().
237 * Used in runningbufwakeup() and waitrunningbufspace().
239 static int runningbufreq;
242 * This lock protects the runningbufreq and synchronizes runningbufwakeup and
243 * waitrunningbufspace().
245 static struct mtx rbreqlock;
248 * Synchronization (sleep/wakeup) variable for buffer requests.
249 * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
251 * Used in numdirtywakeup(), bufspacewakeup(), bufcountwakeup(), bwillwrite(),
252 * getnewbuf(), and getblk().
254 static int needsbuffer;
257 * Lock that protects needsbuffer and the sleeps/wakeups surrounding it.
259 static struct mtx nblock;
262 * Definitions for the buffer free lists.
264 #define BUFFER_QUEUES 6 /* number of free buffer queues */
266 #define QUEUE_NONE 0 /* on no queue */
267 #define QUEUE_CLEAN 1 /* non-B_DELWRI buffers */
268 #define QUEUE_DIRTY 2 /* B_DELWRI buffers */
269 #define QUEUE_DIRTY_GIANT 3 /* B_DELWRI buffers that need giant */
270 #define QUEUE_EMPTYKVA 4 /* empty buffer headers w/KVA assignment */
271 #define QUEUE_EMPTY 5 /* empty buffer headers */
272 #define QUEUE_SENTINEL 1024 /* not an queue index, but mark for sentinel */
274 /* Queues for free buffers with various properties */
275 static TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
277 /* Lock for the bufqueues */
278 static struct mtx bqlock;
281 * Single global constant for BUF_WMESG, to avoid getting multiple references.
282 * buf_wmesg is referred from macros.
284 const char *buf_wmesg = BUF_WMESG;
286 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
287 #define VFS_BIO_NEED_DIRTYFLUSH 0x02 /* waiting for dirty buffer flush */
288 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
289 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
291 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
292 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
294 sysctl_bufspace(SYSCTL_HANDLER_ARGS)
299 if (sizeof(int) == sizeof(long) || req->oldlen >= sizeof(long))
300 return (sysctl_handle_long(oidp, arg1, arg2, req));
301 lvalue = *(long *)arg1;
302 if (lvalue > INT_MAX)
303 /* On overflow, still write out a long to trigger ENOMEM. */
304 return (sysctl_handle_long(oidp, &lvalue, 0, req));
306 return (sysctl_handle_int(oidp, &ivalue, 0, req));
311 extern void ffs_rawread_setup(void);
312 #endif /* DIRECTIO */
316 * If someone is blocked due to there being too many dirty buffers,
317 * and numdirtybuffers is now reasonable, wake them up.
321 numdirtywakeup(int level)
324 if (numdirtybuffers <= level) {
326 if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
327 needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
328 wakeup(&needsbuffer);
337 * Called when buffer space is potentially available for recovery.
338 * getnewbuf() will block on this flag when it is unable to free
339 * sufficient buffer space. Buffer space becomes recoverable when
340 * bp's get placed back in the queues.
348 * If someone is waiting for BUF space, wake them up. Even
349 * though we haven't freed the kva space yet, the waiting
350 * process will be able to now.
353 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
354 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
355 wakeup(&needsbuffer);
361 * runningbufwakeup() - in-progress I/O accounting.
365 runningbufwakeup(struct buf *bp)
368 if (bp->b_runningbufspace) {
369 atomic_subtract_long(&runningbufspace, bp->b_runningbufspace);
370 bp->b_runningbufspace = 0;
371 mtx_lock(&rbreqlock);
372 if (runningbufreq && runningbufspace <= lorunningspace) {
374 wakeup(&runningbufreq);
376 mtx_unlock(&rbreqlock);
383 * Called when a buffer has been added to one of the free queues to
384 * account for the buffer and to wakeup anyone waiting for free buffers.
385 * This typically occurs when large amounts of metadata are being handled
386 * by the buffer cache ( else buffer space runs out first, usually ).
390 bufcountwakeup(struct buf *bp)
394 KASSERT((bp->b_vflags & BV_INFREECNT) == 0,
395 ("buf %p already counted as free", bp));
396 if (bp->b_bufobj != NULL)
397 mtx_assert(BO_MTX(bp->b_bufobj), MA_OWNED);
398 bp->b_vflags |= BV_INFREECNT;
399 old = atomic_fetchadd_int(&numfreebuffers, 1);
400 KASSERT(old >= 0 && old < nbuf,
401 ("numfreebuffers climbed to %d", old + 1));
404 needsbuffer &= ~VFS_BIO_NEED_ANY;
405 if (numfreebuffers >= hifreebuffers)
406 needsbuffer &= ~VFS_BIO_NEED_FREE;
407 wakeup(&needsbuffer);
413 * waitrunningbufspace()
415 * runningbufspace is a measure of the amount of I/O currently
416 * running. This routine is used in async-write situations to
417 * prevent creating huge backups of pending writes to a device.
418 * Only asynchronous writes are governed by this function.
420 * Reads will adjust runningbufspace, but will not block based on it.
421 * The read load has a side effect of reducing the allowed write load.
423 * This does NOT turn an async write into a sync write. It waits
424 * for earlier writes to complete and generally returns before the
425 * caller's write has reached the device.
428 waitrunningbufspace(void)
431 mtx_lock(&rbreqlock);
432 while (runningbufspace > hirunningspace) {
434 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
436 mtx_unlock(&rbreqlock);
441 * vfs_buf_test_cache:
443 * Called when a buffer is extended. This function clears the B_CACHE
444 * bit if the newly extended portion of the buffer does not contain
449 vfs_buf_test_cache(struct buf *bp,
450 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
454 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
455 if (bp->b_flags & B_CACHE) {
456 int base = (foff + off) & PAGE_MASK;
457 if (vm_page_is_valid(m, base, size) == 0)
458 bp->b_flags &= ~B_CACHE;
462 /* Wake up the buffer daemon if necessary */
465 bd_wakeup(int dirtybuflevel)
469 if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
477 * bd_speedup - speedup the buffer cache flushing code
489 * Calculating buffer cache scaling values and reserve space for buffer
490 * headers. This is called during low level kernel initialization and
491 * may be called more then once. We CANNOT write to the memory area
492 * being reserved at this time.
495 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
501 * physmem_est is in pages. Convert it to kilobytes (assumes
502 * PAGE_SIZE is >= 1K)
504 physmem_est = physmem_est * (PAGE_SIZE / 1024);
507 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
508 * For the first 64MB of ram nominally allocate sufficient buffers to
509 * cover 1/4 of our ram. Beyond the first 64MB allocate additional
510 * buffers to cover 1/10 of our ram over 64MB. When auto-sizing
511 * the buffer cache we limit the eventual kva reservation to
514 * factor represents the 1/4 x ram conversion.
517 int factor = 4 * BKVASIZE / 1024;
520 if (physmem_est > 4096)
521 nbuf += min((physmem_est - 4096) / factor,
523 if (physmem_est > 65536)
524 nbuf += (physmem_est - 65536) * 2 / (factor * 5);
526 if (maxbcache && nbuf > maxbcache / BKVASIZE)
527 nbuf = maxbcache / BKVASIZE;
532 /* XXX Avoid unsigned long overflows later on with maxbufspace. */
533 maxbuf = (LONG_MAX / 3) / BKVASIZE;
536 printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
542 * swbufs are used as temporary holders for I/O, such as paging I/O.
543 * We have no less then 16 and no more then 256.
545 nswbuf = max(min(nbuf/4, 256), 16);
547 if (nswbuf < NSWBUF_MIN)
555 * Reserve space for the buffer cache buffers
558 v = (caddr_t)(swbuf + nswbuf);
560 v = (caddr_t)(buf + nbuf);
565 /* Initialize the buffer subsystem. Called before use of any buffers. */
572 mtx_init(&bqlock, "buf queue lock", NULL, MTX_DEF);
573 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
574 mtx_init(&nblock, "needsbuffer lock", NULL, MTX_DEF);
575 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
577 /* next, make a null set of free lists */
578 for (i = 0; i < BUFFER_QUEUES; i++)
579 TAILQ_INIT(&bufqueues[i]);
581 /* finally, initialize each buffer header and stick on empty q */
582 for (i = 0; i < nbuf; i++) {
584 bzero(bp, sizeof *bp);
585 bp->b_flags = B_INVAL; /* we're just an empty header */
586 bp->b_rcred = NOCRED;
587 bp->b_wcred = NOCRED;
588 bp->b_qindex = QUEUE_EMPTY;
589 bp->b_vflags = BV_INFREECNT; /* buf is counted as free */
591 LIST_INIT(&bp->b_dep);
593 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
597 * maxbufspace is the absolute maximum amount of buffer space we are
598 * allowed to reserve in KVM and in real terms. The absolute maximum
599 * is nominally used by buf_daemon. hibufspace is the nominal maximum
600 * used by most other processes. The differential is required to
601 * ensure that buf_daemon is able to run when other processes might
602 * be blocked waiting for buffer space.
604 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
605 * this may result in KVM fragmentation which is not handled optimally
608 maxbufspace = (long)nbuf * BKVASIZE;
609 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
610 lobufspace = hibufspace - MAXBSIZE;
612 lorunningspace = 512 * 1024;
613 hirunningspace = 1024 * 1024;
616 * Limit the amount of malloc memory since it is wired permanently into
617 * the kernel space. Even though this is accounted for in the buffer
618 * allocation, we don't want the malloced region to grow uncontrolled.
619 * The malloc scheme improves memory utilization significantly on average
620 * (small) directories.
622 maxbufmallocspace = hibufspace / 20;
625 * Reduce the chance of a deadlock occuring by limiting the number
626 * of delayed-write dirty buffers we allow to stack up.
628 hidirtybuffers = nbuf / 4 + 20;
629 dirtybufthresh = hidirtybuffers * 9 / 10;
632 * To support extreme low-memory systems, make sure hidirtybuffers cannot
633 * eat up all available buffer space. This occurs when our minimum cannot
634 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
635 * BKVASIZE'd (8K) buffers.
637 while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
638 hidirtybuffers >>= 1;
640 lodirtybuffers = hidirtybuffers / 2;
643 * Try to keep the number of free buffers in the specified range,
644 * and give special processes (e.g. like buf_daemon) access to an
647 lofreebuffers = nbuf / 18 + 5;
648 hifreebuffers = 2 * lofreebuffers;
649 numfreebuffers = nbuf;
651 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
652 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
656 * bfreekva() - free the kva allocation for a buffer.
658 * Since this call frees up buffer space, we call bufspacewakeup().
661 bfreekva(struct buf *bp)
665 atomic_add_int(&buffreekvacnt, 1);
666 atomic_subtract_long(&bufspace, bp->b_kvasize);
667 vm_map_remove(buffer_map, (vm_offset_t) bp->b_kvabase,
668 (vm_offset_t) bp->b_kvabase + bp->b_kvasize);
677 * Mark the buffer for removal from the appropriate free list in brelse.
681 bremfree(struct buf *bp)
685 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
686 KASSERT((bp->b_flags & B_REMFREE) == 0,
687 ("bremfree: buffer %p already marked for delayed removal.", bp));
688 KASSERT(bp->b_qindex != QUEUE_NONE,
689 ("bremfree: buffer %p not on a queue.", bp));
692 bp->b_flags |= B_REMFREE;
693 /* Fixup numfreebuffers count. */
694 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
695 KASSERT((bp->b_vflags & BV_INFREECNT) != 0,
696 ("buf %p not counted in numfreebuffers", bp));
697 if (bp->b_bufobj != NULL)
698 mtx_assert(BO_MTX(bp->b_bufobj), MA_OWNED);
699 bp->b_vflags &= ~BV_INFREECNT;
700 old = atomic_fetchadd_int(&numfreebuffers, -1);
701 KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
708 * Force an immediate removal from a free list. Used only in nfs when
709 * it abuses the b_freelist pointer.
712 bremfreef(struct buf *bp)
722 * Removes a buffer from the free list, must be called with the
726 bremfreel(struct buf *bp)
730 CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
731 bp, bp->b_vp, bp->b_flags);
732 KASSERT(bp->b_qindex != QUEUE_NONE,
733 ("bremfreel: buffer %p not on a queue.", bp));
735 mtx_assert(&bqlock, MA_OWNED);
737 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
738 bp->b_qindex = QUEUE_NONE;
740 * If this was a delayed bremfree() we only need to remove the buffer
741 * from the queue and return the stats are already done.
743 if (bp->b_flags & B_REMFREE) {
744 bp->b_flags &= ~B_REMFREE;
748 * Fixup numfreebuffers count. If the buffer is invalid or not
749 * delayed-write, the buffer was free and we must decrement
752 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
753 KASSERT((bp->b_vflags & BV_INFREECNT) != 0,
754 ("buf %p not counted in numfreebuffers", bp));
755 if (bp->b_bufobj != NULL)
756 mtx_assert(BO_MTX(bp->b_bufobj), MA_OWNED);
757 bp->b_vflags &= ~BV_INFREECNT;
758 old = atomic_fetchadd_int(&numfreebuffers, -1);
759 KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
765 * Get a buffer with the specified data. Look in the cache first. We
766 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
767 * is set, the buffer is valid and we do not have to do anything ( see
768 * getblk() ). This is really just a special case of breadn().
771 bread(struct vnode * vp, daddr_t blkno, int size, struct ucred * cred,
775 return (breadn(vp, blkno, size, 0, 0, 0, cred, bpp));
779 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must
780 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
781 * the buffer is valid and we do not have to do anything.
784 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
785 int cnt, struct ucred * cred)
790 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
791 if (inmem(vp, *rablkno))
793 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
795 if ((rabp->b_flags & B_CACHE) == 0) {
796 if (!TD_IS_IDLETHREAD(curthread))
797 curthread->td_ru.ru_inblock++;
798 rabp->b_flags |= B_ASYNC;
799 rabp->b_flags &= ~B_INVAL;
800 rabp->b_ioflags &= ~BIO_ERROR;
801 rabp->b_iocmd = BIO_READ;
802 if (rabp->b_rcred == NOCRED && cred != NOCRED)
803 rabp->b_rcred = crhold(cred);
804 vfs_busy_pages(rabp, 0);
806 rabp->b_iooffset = dbtob(rabp->b_blkno);
815 * Operates like bread, but also starts asynchronous I/O on
819 breadn(struct vnode * vp, daddr_t blkno, int size,
820 daddr_t * rablkno, int *rabsize,
821 int cnt, struct ucred * cred, struct buf **bpp)
824 int rv = 0, readwait = 0;
826 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
827 *bpp = bp = getblk(vp, blkno, size, 0, 0, 0);
829 /* if not found in cache, do some I/O */
830 if ((bp->b_flags & B_CACHE) == 0) {
831 if (!TD_IS_IDLETHREAD(curthread))
832 curthread->td_ru.ru_inblock++;
833 bp->b_iocmd = BIO_READ;
834 bp->b_flags &= ~B_INVAL;
835 bp->b_ioflags &= ~BIO_ERROR;
836 if (bp->b_rcred == NOCRED && cred != NOCRED)
837 bp->b_rcred = crhold(cred);
838 vfs_busy_pages(bp, 0);
839 bp->b_iooffset = dbtob(bp->b_blkno);
844 breada(vp, rablkno, rabsize, cnt, cred);
853 * Write, release buffer on completion. (Done by iodone
854 * if async). Do not bother writing anything if the buffer
857 * Note that we set B_CACHE here, indicating that buffer is
858 * fully valid and thus cacheable. This is true even of NFS
859 * now so we set it generally. This could be set either here
860 * or in biodone() since the I/O is synchronous. We put it
864 bufwrite(struct buf *bp)
870 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
871 if (bp->b_flags & B_INVAL) {
876 if (bp->b_flags & B_BARRIER)
879 oldflags = bp->b_flags;
883 if (bp->b_pin_count > 0)
886 KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
887 ("FFS background buffer should not get here %p", bp));
891 vp_md = vp->v_vflag & VV_MD;
896 * Mark the buffer clean. Increment the bufobj write count
897 * before bundirty() call, to prevent other thread from seeing
898 * empty dirty list and zero counter for writes in progress,
899 * falsely indicating that the bufobj is clean.
901 bufobj_wref(bp->b_bufobj);
904 bp->b_flags &= ~B_DONE;
905 bp->b_ioflags &= ~BIO_ERROR;
906 bp->b_flags |= B_CACHE;
907 bp->b_iocmd = BIO_WRITE;
909 vfs_busy_pages(bp, 1);
912 * Normal bwrites pipeline writes
914 bp->b_runningbufspace = bp->b_bufsize;
915 atomic_add_long(&runningbufspace, bp->b_runningbufspace);
917 if (!TD_IS_IDLETHREAD(curthread))
918 curthread->td_ru.ru_oublock++;
919 if (oldflags & B_ASYNC)
921 bp->b_iooffset = dbtob(bp->b_blkno);
924 if ((oldflags & B_ASYNC) == 0) {
925 int rtval = bufwait(bp);
930 * don't allow the async write to saturate the I/O
931 * system. We will not deadlock here because
932 * we are blocking waiting for I/O that is already in-progress
933 * to complete. We do not block here if it is the update
934 * or syncer daemon trying to clean up as that can lead
937 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
938 waitrunningbufspace();
945 bufbdflush(struct bufobj *bo, struct buf *bp)
949 if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
950 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
952 } else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
955 * Try to find a buffer to flush.
957 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
958 if ((nbp->b_vflags & BV_BKGRDINPROG) ||
960 LK_EXCLUSIVE | LK_NOWAIT, NULL))
963 panic("bdwrite: found ourselves");
965 /* Don't countdeps with the bo lock held. */
966 if (buf_countdeps(nbp, 0)) {
971 if (nbp->b_flags & B_CLUSTEROK) {
977 dirtybufferflushes++;
986 * Delayed write. (Buffer is marked dirty). Do not bother writing
987 * anything if the buffer is marked invalid.
989 * Note that since the buffer must be completely valid, we can safely
990 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
991 * biodone() in order to prevent getblk from writing the buffer
995 bdwrite(struct buf *bp)
997 struct thread *td = curthread;
1001 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1002 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1003 KASSERT((bp->b_flags & B_BARRIER) == 0,
1004 ("Barrier request in delayed write %p", bp));
1005 BUF_ASSERT_HELD(bp);
1007 if (bp->b_flags & B_INVAL) {
1013 * If we have too many dirty buffers, don't create any more.
1014 * If we are wildly over our limit, then force a complete
1015 * cleanup. Otherwise, just keep the situation from getting
1016 * out of control. Note that we have to avoid a recursive
1017 * disaster and not try to clean up after our own cleanup!
1021 if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
1022 td->td_pflags |= TDP_INBDFLUSH;
1024 td->td_pflags &= ~TDP_INBDFLUSH;
1030 * Set B_CACHE, indicating that the buffer is fully valid. This is
1031 * true even of NFS now.
1033 bp->b_flags |= B_CACHE;
1036 * This bmap keeps the system from needing to do the bmap later,
1037 * perhaps when the system is attempting to do a sync. Since it
1038 * is likely that the indirect block -- or whatever other datastructure
1039 * that the filesystem needs is still in memory now, it is a good
1040 * thing to do this. Note also, that if the pageout daemon is
1041 * requesting a sync -- there might not be enough memory to do
1042 * the bmap then... So, this is important to do.
1044 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
1045 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
1049 * Set the *dirty* buffer range based upon the VM system dirty
1052 * Mark the buffer pages as clean. We need to do this here to
1053 * satisfy the vnode_pager and the pageout daemon, so that it
1054 * thinks that the pages have been "cleaned". Note that since
1055 * the pages are in a delayed write buffer -- the VFS layer
1056 * "will" see that the pages get written out on the next sync,
1057 * or perhaps the cluster will be completed.
1059 vfs_clean_pages_dirty_buf(bp);
1063 * Wakeup the buffer flushing daemon if we have a lot of dirty
1064 * buffers (midpoint between our recovery point and our stall
1067 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1070 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1071 * due to the softdep code.
1078 * Turn buffer into delayed write request. We must clear BIO_READ and
1079 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
1080 * itself to properly update it in the dirty/clean lists. We mark it
1081 * B_DONE to ensure that any asynchronization of the buffer properly
1082 * clears B_DONE ( else a panic will occur later ).
1084 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1085 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
1086 * should only be called if the buffer is known-good.
1088 * Since the buffer is not on a queue, we do not update the numfreebuffers
1091 * The buffer must be on QUEUE_NONE.
1094 bdirty(struct buf *bp)
1097 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
1098 bp, bp->b_vp, bp->b_flags);
1099 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1100 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1101 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1102 BUF_ASSERT_HELD(bp);
1103 bp->b_flags &= ~(B_RELBUF);
1104 bp->b_iocmd = BIO_WRITE;
1106 if ((bp->b_flags & B_DELWRI) == 0) {
1107 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
1109 atomic_add_int(&numdirtybuffers, 1);
1110 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1117 * Clear B_DELWRI for buffer.
1119 * Since the buffer is not on a queue, we do not update the numfreebuffers
1122 * The buffer must be on QUEUE_NONE.
1126 bundirty(struct buf *bp)
1129 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1130 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1131 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1132 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1133 BUF_ASSERT_HELD(bp);
1135 if (bp->b_flags & B_DELWRI) {
1136 bp->b_flags &= ~B_DELWRI;
1138 atomic_subtract_int(&numdirtybuffers, 1);
1139 numdirtywakeup(lodirtybuffers);
1142 * Since it is now being written, we can clear its deferred write flag.
1144 bp->b_flags &= ~B_DEFERRED;
1150 * Asynchronous write. Start output on a buffer, but do not wait for
1151 * it to complete. The buffer is released when the output completes.
1153 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1154 * B_INVAL buffers. Not us.
1157 bawrite(struct buf *bp)
1160 bp->b_flags |= B_ASYNC;
1167 * Asynchronous barrier write. Start output on a buffer, but do not
1168 * wait for it to complete. Place a write barrier after this write so
1169 * that this buffer and all buffers written before it are committed to
1170 * the disk before any buffers written after this write are committed
1171 * to the disk. The buffer is released when the output completes.
1174 babarrierwrite(struct buf *bp)
1177 bp->b_flags |= B_ASYNC | B_BARRIER;
1184 * Synchronous barrier write. Start output on a buffer and wait for
1185 * it to complete. Place a write barrier after this write so that
1186 * this buffer and all buffers written before it are committed to
1187 * the disk before any buffers written after this write are committed
1188 * to the disk. The buffer is released when the output completes.
1191 bbarrierwrite(struct buf *bp)
1194 bp->b_flags |= B_BARRIER;
1195 return (bwrite(bp));
1201 * Called prior to the locking of any vnodes when we are expecting to
1202 * write. We do not want to starve the buffer cache with too many
1203 * dirty buffers so we block here. By blocking prior to the locking
1204 * of any vnodes we attempt to avoid the situation where a locked vnode
1205 * prevents the various system daemons from flushing related buffers.
1212 if (numdirtybuffers >= hidirtybuffers) {
1214 while (numdirtybuffers >= hidirtybuffers) {
1216 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
1217 msleep(&needsbuffer, &nblock,
1218 (PRIBIO + 4), "flswai", 0);
1220 mtx_unlock(&nblock);
1225 * Return true if we have too many dirty buffers.
1228 buf_dirty_count_severe(void)
1231 return(numdirtybuffers >= hidirtybuffers);
1234 static __noinline int
1235 buf_vm_page_count_severe(void)
1238 KFAIL_POINT_CODE(DEBUG_FP, buf_pressure, return 1);
1240 return vm_page_count_severe();
1246 * Release a busy buffer and, if requested, free its resources. The
1247 * buffer will be stashed in the appropriate bufqueue[] allowing it
1248 * to be accessed later as a cache entity or reused for other purposes.
1251 brelse(struct buf *bp)
1253 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
1254 bp, bp->b_vp, bp->b_flags);
1255 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1256 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1258 if (bp->b_flags & B_MANAGED) {
1263 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
1264 bp->b_error == EIO && !(bp->b_flags & B_INVAL)) {
1266 * Failed write, redirty. Must clear BIO_ERROR to prevent
1267 * pages from being scrapped. If the error is anything
1268 * other than an I/O error (EIO), assume that retrying
1271 bp->b_ioflags &= ~BIO_ERROR;
1273 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1274 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
1276 * Either a failed I/O or we were asked to free or not
1279 bp->b_flags |= B_INVAL;
1280 if (!LIST_EMPTY(&bp->b_dep))
1282 if (bp->b_flags & B_DELWRI) {
1283 atomic_subtract_int(&numdirtybuffers, 1);
1284 numdirtywakeup(lodirtybuffers);
1286 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1287 if ((bp->b_flags & B_VMIO) == 0) {
1296 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1297 * is called with B_DELWRI set, the underlying pages may wind up
1298 * getting freed causing a previous write (bdwrite()) to get 'lost'
1299 * because pages associated with a B_DELWRI bp are marked clean.
1301 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1302 * if B_DELWRI is set.
1304 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1305 * on pages to return pages to the VM page queues.
1307 if (bp->b_flags & B_DELWRI)
1308 bp->b_flags &= ~B_RELBUF;
1309 else if (buf_vm_page_count_severe()) {
1311 * The locking of the BO_LOCK is not necessary since
1312 * BKGRDINPROG cannot be set while we hold the buf
1313 * lock, it can only be cleared if it is already
1317 if (!(bp->b_vflags & BV_BKGRDINPROG))
1318 bp->b_flags |= B_RELBUF;
1320 bp->b_flags |= B_RELBUF;
1324 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1325 * constituted, not even NFS buffers now. Two flags effect this. If
1326 * B_INVAL, the struct buf is invalidated but the VM object is kept
1327 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1329 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1330 * invalidated. BIO_ERROR cannot be set for a failed write unless the
1331 * buffer is also B_INVAL because it hits the re-dirtying code above.
1333 * Normally we can do this whether a buffer is B_DELWRI or not. If
1334 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1335 * the commit state and we cannot afford to lose the buffer. If the
1336 * buffer has a background write in progress, we need to keep it
1337 * around to prevent it from being reconstituted and starting a second
1340 if ((bp->b_flags & B_VMIO)
1341 && !(bp->b_vp->v_mount != NULL &&
1342 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1343 !vn_isdisk(bp->b_vp, NULL) &&
1344 (bp->b_flags & B_DELWRI))
1353 obj = bp->b_bufobj->bo_object;
1356 * Get the base offset and length of the buffer. Note that
1357 * in the VMIO case if the buffer block size is not
1358 * page-aligned then b_data pointer may not be page-aligned.
1359 * But our b_pages[] array *IS* page aligned.
1361 * block sizes less then DEV_BSIZE (usually 512) are not
1362 * supported due to the page granularity bits (m->valid,
1363 * m->dirty, etc...).
1365 * See man buf(9) for more information
1367 resid = bp->b_bufsize;
1368 foff = bp->b_offset;
1369 VM_OBJECT_LOCK(obj);
1370 for (i = 0; i < bp->b_npages; i++) {
1376 * If we hit a bogus page, fixup *all* the bogus pages
1379 if (m == bogus_page) {
1380 poff = OFF_TO_IDX(bp->b_offset);
1383 for (j = i; j < bp->b_npages; j++) {
1385 mtmp = bp->b_pages[j];
1386 if (mtmp == bogus_page) {
1387 mtmp = vm_page_lookup(obj, poff + j);
1389 panic("brelse: page missing\n");
1391 bp->b_pages[j] = mtmp;
1395 if ((bp->b_flags & B_INVAL) == 0) {
1397 trunc_page((vm_offset_t)bp->b_data),
1398 bp->b_pages, bp->b_npages);
1402 if ((bp->b_flags & B_NOCACHE) ||
1403 (bp->b_ioflags & BIO_ERROR &&
1404 bp->b_iocmd == BIO_READ)) {
1405 int poffset = foff & PAGE_MASK;
1406 int presid = resid > (PAGE_SIZE - poffset) ?
1407 (PAGE_SIZE - poffset) : resid;
1409 KASSERT(presid >= 0, ("brelse: extra page"));
1410 vm_page_lock_queues();
1411 vm_page_set_invalid(m, poffset, presid);
1412 vm_page_unlock_queues();
1414 printf("avoided corruption bug in bogus_page/brelse code\n");
1416 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1417 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1419 VM_OBJECT_UNLOCK(obj);
1420 if (bp->b_flags & (B_INVAL | B_RELBUF))
1421 vfs_vmio_release(bp);
1423 } else if (bp->b_flags & B_VMIO) {
1425 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1426 vfs_vmio_release(bp);
1429 } else if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0) {
1430 if (bp->b_bufsize != 0)
1432 if (bp->b_vp != NULL)
1436 if (BUF_LOCKRECURSED(bp)) {
1437 /* do not release to free list */
1444 /* Handle delayed bremfree() processing. */
1445 if (bp->b_flags & B_REMFREE) {
1455 if (bp->b_qindex != QUEUE_NONE)
1456 panic("brelse: free buffer onto another queue???");
1459 * If the buffer has junk contents signal it and eventually
1460 * clean up B_DELWRI and diassociate the vnode so that gbincore()
1463 if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
1464 (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
1465 bp->b_flags |= B_INVAL;
1466 if (bp->b_flags & B_INVAL) {
1467 if (bp->b_flags & B_DELWRI)
1473 /* buffers with no memory */
1474 if (bp->b_bufsize == 0) {
1475 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1476 if (bp->b_vflags & BV_BKGRDINPROG)
1477 panic("losing buffer 1");
1478 if (bp->b_kvasize) {
1479 bp->b_qindex = QUEUE_EMPTYKVA;
1481 bp->b_qindex = QUEUE_EMPTY;
1483 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1484 /* buffers with junk contents */
1485 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1486 (bp->b_ioflags & BIO_ERROR)) {
1487 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1488 if (bp->b_vflags & BV_BKGRDINPROG)
1489 panic("losing buffer 2");
1490 bp->b_qindex = QUEUE_CLEAN;
1491 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1492 /* remaining buffers */
1494 if ((bp->b_flags & (B_DELWRI|B_NEEDSGIANT)) ==
1495 (B_DELWRI|B_NEEDSGIANT))
1496 bp->b_qindex = QUEUE_DIRTY_GIANT;
1497 else if (bp->b_flags & B_DELWRI)
1498 bp->b_qindex = QUEUE_DIRTY;
1500 bp->b_qindex = QUEUE_CLEAN;
1501 if (bp->b_flags & B_AGE)
1502 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1504 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1506 mtx_unlock(&bqlock);
1509 * Fixup numfreebuffers count. The bp is on an appropriate queue
1510 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1511 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1512 * if B_INVAL is set ).
1515 if (!(bp->b_flags & B_DELWRI)) {
1527 * Something we can maybe free or reuse
1529 if (bp->b_bufsize || bp->b_kvasize)
1532 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1533 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1534 panic("brelse: not dirty");
1540 * Release a buffer back to the appropriate queue but do not try to free
1541 * it. The buffer is expected to be used again soon.
1543 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1544 * biodone() to requeue an async I/O on completion. It is also used when
1545 * known good buffers need to be requeued but we think we may need the data
1548 * XXX we should be able to leave the B_RELBUF hint set on completion.
1551 bqrelse(struct buf *bp)
1555 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1556 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1557 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1559 if (BUF_LOCKRECURSED(bp)) {
1560 /* do not release to free list */
1566 if (bp->b_flags & B_MANAGED) {
1567 if (bp->b_flags & B_REMFREE) {
1574 mtx_unlock(&bqlock);
1576 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1582 /* Handle delayed bremfree() processing. */
1583 if (bp->b_flags & B_REMFREE) {
1590 if (bp->b_qindex != QUEUE_NONE)
1591 panic("bqrelse: free buffer onto another queue???");
1592 /* buffers with stale but valid contents */
1593 if (bp->b_flags & B_DELWRI) {
1594 if (bp->b_flags & B_NEEDSGIANT)
1595 bp->b_qindex = QUEUE_DIRTY_GIANT;
1597 bp->b_qindex = QUEUE_DIRTY;
1598 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1601 * The locking of the BO_LOCK for checking of the
1602 * BV_BKGRDINPROG is not necessary since the
1603 * BV_BKGRDINPROG cannot be set while we hold the buf
1604 * lock, it can only be cleared if it is already
1607 if (!buf_vm_page_count_severe() || (bp->b_vflags & BV_BKGRDINPROG)) {
1608 bp->b_qindex = QUEUE_CLEAN;
1609 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp,
1613 * We are too low on memory, we have to try to free
1614 * the buffer (most importantly: the wired pages
1615 * making up its backing store) *now*.
1617 mtx_unlock(&bqlock);
1622 mtx_unlock(&bqlock);
1624 if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI)) {
1633 * Something we can maybe free or reuse.
1635 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1638 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1639 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1640 panic("bqrelse: not dirty");
1645 /* Give pages used by the bp back to the VM system (where possible) */
1647 vfs_vmio_release(struct buf *bp)
1652 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
1653 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
1654 vm_page_lock_queues();
1655 for (i = 0; i < bp->b_npages; i++) {
1657 bp->b_pages[i] = NULL;
1659 * In order to keep page LRU ordering consistent, put
1660 * everything on the inactive queue.
1662 vm_page_unwire(m, 0);
1664 * We don't mess with busy pages, it is
1665 * the responsibility of the process that
1666 * busied the pages to deal with them.
1668 if ((m->oflags & VPO_BUSY) || (m->busy != 0))
1671 if (m->wire_count == 0) {
1673 * Might as well free the page if we can and it has
1674 * no valid data. We also free the page if the
1675 * buffer was used for direct I/O
1677 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1678 m->hold_count == 0) {
1680 } else if (bp->b_flags & B_DIRECT) {
1681 vm_page_try_to_free(m);
1682 } else if (buf_vm_page_count_severe()) {
1683 vm_page_try_to_cache(m);
1687 vm_page_unlock_queues();
1688 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
1690 if (bp->b_bufsize) {
1695 bp->b_flags &= ~B_VMIO;
1701 * Check to see if a block at a particular lbn is available for a clustered
1705 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1712 /* If the buf isn't in core skip it */
1713 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1716 /* If the buf is busy we don't want to wait for it */
1717 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1720 /* Only cluster with valid clusterable delayed write buffers */
1721 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1722 (B_DELWRI | B_CLUSTEROK))
1725 if (bpa->b_bufsize != size)
1729 * Check to see if it is in the expected place on disk and that the
1730 * block has been mapped.
1732 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1742 * Implement clustered async writes for clearing out B_DELWRI buffers.
1743 * This is much better then the old way of writing only one buffer at
1744 * a time. Note that we may not be presented with the buffers in the
1745 * correct order, so we search for the cluster in both directions.
1748 vfs_bio_awrite(struct buf *bp)
1753 daddr_t lblkno = bp->b_lblkno;
1754 struct vnode *vp = bp->b_vp;
1762 * right now we support clustered writing only to regular files. If
1763 * we find a clusterable block we could be in the middle of a cluster
1764 * rather then at the beginning.
1766 if ((vp->v_type == VREG) &&
1767 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1768 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1770 size = vp->v_mount->mnt_stat.f_iosize;
1771 maxcl = MAXPHYS / size;
1774 for (i = 1; i < maxcl; i++)
1775 if (vfs_bio_clcheck(vp, size, lblkno + i,
1776 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1779 for (j = 1; i + j <= maxcl && j <= lblkno; j++)
1780 if (vfs_bio_clcheck(vp, size, lblkno - j,
1781 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
1787 * this is a possible cluster write
1791 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1796 bp->b_flags |= B_ASYNC;
1798 * default (old) behavior, writing out only one block
1800 * XXX returns b_bufsize instead of b_bcount for nwritten?
1802 nwritten = bp->b_bufsize;
1811 * Find and initialize a new buffer header, freeing up existing buffers
1812 * in the bufqueues as necessary. The new buffer is returned locked.
1814 * Important: B_INVAL is not set. If the caller wishes to throw the
1815 * buffer away, the caller must set B_INVAL prior to calling brelse().
1818 * We have insufficient buffer headers
1819 * We have insufficient buffer space
1820 * buffer_map is too fragmented ( space reservation fails )
1821 * If we have to flush dirty buffers ( but we try to avoid this )
1823 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1824 * Instead we ask the buf daemon to do it for us. We attempt to
1825 * avoid piecemeal wakeups of the pageout daemon.
1829 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int size, int maxsize,
1837 static int flushingbufs;
1841 * We can't afford to block since we might be holding a vnode lock,
1842 * which may prevent system daemons from running. We deal with
1843 * low-memory situations by proactively returning memory and running
1844 * async I/O rather then sync I/O.
1846 atomic_add_int(&getnewbufcalls, 1);
1847 atomic_subtract_int(&getnewbufrestarts, 1);
1849 atomic_add_int(&getnewbufrestarts, 1);
1852 * Setup for scan. If we do not have enough free buffers,
1853 * we setup a degenerate case that immediately fails. Note
1854 * that if we are specially marked process, we are allowed to
1855 * dip into our reserves.
1857 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1859 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1860 * However, there are a number of cases (defragging, reusing, ...)
1861 * where we cannot backup.
1864 nqindex = QUEUE_EMPTYKVA;
1865 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1869 * If no EMPTYKVA buffers and we are either
1870 * defragging or reusing, locate a CLEAN buffer
1871 * to free or reuse. If bufspace useage is low
1872 * skip this step so we can allocate a new buffer.
1874 if (defrag || bufspace >= lobufspace) {
1875 nqindex = QUEUE_CLEAN;
1876 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1880 * If we could not find or were not allowed to reuse a
1881 * CLEAN buffer, check to see if it is ok to use an EMPTY
1882 * buffer. We can only use an EMPTY buffer if allocating
1883 * its KVA would not otherwise run us out of buffer space.
1885 if (nbp == NULL && defrag == 0 &&
1886 bufspace + maxsize < hibufspace) {
1887 nqindex = QUEUE_EMPTY;
1888 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1893 * Run scan, possibly freeing data and/or kva mappings on the fly
1897 while ((bp = nbp) != NULL) {
1898 int qindex = nqindex;
1901 * Calculate next bp ( we can only use it if we do not block
1902 * or do other fancy things ).
1904 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1907 nqindex = QUEUE_EMPTYKVA;
1908 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1911 case QUEUE_EMPTYKVA:
1912 nqindex = QUEUE_CLEAN;
1913 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1924 * If we are defragging then we need a buffer with
1925 * b_kvasize != 0. XXX this situation should no longer
1926 * occur, if defrag is non-zero the buffer's b_kvasize
1927 * should also be non-zero at this point. XXX
1929 if (defrag && bp->b_kvasize == 0) {
1930 printf("Warning: defrag empty buffer %p\n", bp);
1935 * Start freeing the bp. This is somewhat involved. nbp
1936 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1938 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1941 BO_LOCK(bp->b_bufobj);
1942 if (bp->b_vflags & BV_BKGRDINPROG) {
1943 BO_UNLOCK(bp->b_bufobj);
1947 BO_UNLOCK(bp->b_bufobj);
1950 "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
1951 "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
1952 bp->b_kvasize, bp->b_bufsize, qindex);
1957 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1960 * Note: we no longer distinguish between VMIO and non-VMIO
1964 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1966 if (bp->b_bufobj != NULL)
1967 BO_LOCK(bp->b_bufobj);
1969 if (bp->b_bufobj != NULL)
1970 BO_UNLOCK(bp->b_bufobj);
1971 mtx_unlock(&bqlock);
1973 if (qindex == QUEUE_CLEAN) {
1974 if (bp->b_flags & B_VMIO) {
1975 bp->b_flags &= ~B_ASYNC;
1976 vfs_vmio_release(bp);
1983 * NOTE: nbp is now entirely invalid. We can only restart
1984 * the scan from this point on.
1986 * Get the rest of the buffer freed up. b_kva* is still
1987 * valid after this operation.
1990 if (bp->b_rcred != NOCRED) {
1991 crfree(bp->b_rcred);
1992 bp->b_rcred = NOCRED;
1994 if (bp->b_wcred != NOCRED) {
1995 crfree(bp->b_wcred);
1996 bp->b_wcred = NOCRED;
1998 if (!LIST_EMPTY(&bp->b_dep))
2000 if (bp->b_vflags & BV_BKGRDINPROG)
2001 panic("losing buffer 3");
2002 KASSERT(bp->b_vp == NULL,
2003 ("bp: %p still has vnode %p. qindex: %d",
2004 bp, bp->b_vp, qindex));
2005 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
2006 ("bp: %p still on a buffer list. xflags %X",
2015 KASSERT((bp->b_vflags & BV_INFREECNT) == 0,
2016 ("buf %p still counted as free?", bp));
2019 bp->b_blkno = bp->b_lblkno = 0;
2020 bp->b_offset = NOOFFSET;
2026 bp->b_dirtyoff = bp->b_dirtyend = 0;
2027 bp->b_bufobj = NULL;
2028 bp->b_pin_count = 0;
2029 bp->b_fsprivate1 = NULL;
2030 bp->b_fsprivate2 = NULL;
2031 bp->b_fsprivate3 = NULL;
2033 LIST_INIT(&bp->b_dep);
2036 * If we are defragging then free the buffer.
2039 bp->b_flags |= B_INVAL;
2047 * Notify any waiters for the buffer lock about
2048 * identity change by freeing the buffer.
2050 if (qindex == QUEUE_CLEAN && BUF_LOCKWAITERS(bp)) {
2051 bp->b_flags |= B_INVAL;
2058 * If we are overcomitted then recover the buffer and its
2059 * KVM space. This occurs in rare situations when multiple
2060 * processes are blocked in getnewbuf() or allocbuf().
2062 if (bufspace >= hibufspace)
2064 if (flushingbufs && bp->b_kvasize != 0) {
2065 bp->b_flags |= B_INVAL;
2070 if (bufspace < lobufspace)
2076 * If we exhausted our list, sleep as appropriate. We may have to
2077 * wakeup various daemons and write out some dirty buffers.
2079 * Generally we are sleeping due to insufficient buffer space.
2083 int flags, norunbuf;
2088 flags = VFS_BIO_NEED_BUFSPACE;
2090 } else if (bufspace >= hibufspace) {
2092 flags = VFS_BIO_NEED_BUFSPACE;
2095 flags = VFS_BIO_NEED_ANY;
2098 needsbuffer |= flags;
2099 mtx_unlock(&nblock);
2100 mtx_unlock(&bqlock);
2102 bd_speedup(); /* heeeelp */
2103 if (gbflags & GB_NOWAIT_BD)
2107 while (needsbuffer & flags) {
2108 if (vp != NULL && (td->td_pflags & TDP_BUFNEED) == 0) {
2109 mtx_unlock(&nblock);
2111 * getblk() is called with a vnode
2112 * locked, and some majority of the
2113 * dirty buffers may as well belong to
2114 * the vnode. Flushing the buffers
2115 * there would make a progress that
2116 * cannot be achieved by the
2117 * buf_daemon, that cannot lock the
2120 norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
2121 (td->td_pflags & TDP_NORUNNINGBUF);
2122 /* play bufdaemon */
2123 td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
2124 fl = buf_do_flush(vp);
2125 td->td_pflags &= norunbuf;
2129 if ((needsbuffer & flags) == 0)
2132 if (msleep(&needsbuffer, &nblock,
2133 (PRIBIO + 4) | slpflag, waitmsg, slptimeo)) {
2134 mtx_unlock(&nblock);
2138 mtx_unlock(&nblock);
2141 * We finally have a valid bp. We aren't quite out of the
2142 * woods, we still have to reserve kva space. In order
2143 * to keep fragmentation sane we only allocate kva in
2146 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2148 if (maxsize != bp->b_kvasize) {
2149 vm_offset_t addr = 0;
2153 vm_map_lock(buffer_map);
2154 if (vm_map_findspace(buffer_map,
2155 vm_map_min(buffer_map), maxsize, &addr)) {
2157 * Uh oh. Buffer map is to fragmented. We
2158 * must defragment the map.
2160 atomic_add_int(&bufdefragcnt, 1);
2161 vm_map_unlock(buffer_map);
2163 bp->b_flags |= B_INVAL;
2168 vm_map_insert(buffer_map, NULL, 0,
2169 addr, addr + maxsize,
2170 VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
2172 bp->b_kvabase = (caddr_t) addr;
2173 bp->b_kvasize = maxsize;
2174 atomic_add_long(&bufspace, bp->b_kvasize);
2175 atomic_add_int(&bufreusecnt, 1);
2177 vm_map_unlock(buffer_map);
2179 bp->b_saveaddr = bp->b_kvabase;
2180 bp->b_data = bp->b_saveaddr;
2188 * buffer flushing daemon. Buffers are normally flushed by the
2189 * update daemon but if it cannot keep up this process starts to
2190 * take the load in an attempt to prevent getnewbuf() from blocking.
2193 static struct kproc_desc buf_kp = {
2198 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
2201 buf_do_flush(struct vnode *vp)
2205 flushed = flushbufqueues(vp, QUEUE_DIRTY, 0);
2206 /* The list empty check here is slightly racy */
2207 if (!TAILQ_EMPTY(&bufqueues[QUEUE_DIRTY_GIANT])) {
2209 flushed += flushbufqueues(vp, QUEUE_DIRTY_GIANT, 0);
2214 * Could not find any buffers without rollback
2215 * dependencies, so just write the first one
2216 * in the hopes of eventually making progress.
2218 flushbufqueues(vp, QUEUE_DIRTY, 1);
2220 &bufqueues[QUEUE_DIRTY_GIANT])) {
2222 flushbufqueues(vp, QUEUE_DIRTY_GIANT, 1);
2234 * This process needs to be suspended prior to shutdown sync.
2236 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2240 * This process is allowed to take the buffer cache to the limit
2242 curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
2246 mtx_unlock(&bdlock);
2248 kproc_suspend_check(bufdaemonproc);
2251 * Do the flush. Limit the amount of in-transit I/O we
2252 * allow to build up, otherwise we would completely saturate
2253 * the I/O system. Wakeup any waiting processes before we
2254 * normally would so they can run in parallel with our drain.
2256 while (numdirtybuffers > lodirtybuffers) {
2257 if (buf_do_flush(NULL) == 0)
2263 * Only clear bd_request if we have reached our low water
2264 * mark. The buf_daemon normally waits 1 second and
2265 * then incrementally flushes any dirty buffers that have
2266 * built up, within reason.
2268 * If we were unable to hit our low water mark and couldn't
2269 * find any flushable buffers, we sleep half a second.
2270 * Otherwise we loop immediately.
2273 if (numdirtybuffers <= lodirtybuffers) {
2275 * We reached our low water mark, reset the
2276 * request and sleep until we are needed again.
2277 * The sleep is just so the suspend code works.
2280 msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2283 * We couldn't find any flushable dirty buffers but
2284 * still have too many dirty buffers, we
2285 * have to sleep and try again. (rare)
2287 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2295 * Try to flush a buffer in the dirty queue. We must be careful to
2296 * free up B_INVAL buffers instead of write them, which NFS is
2297 * particularly sensitive to.
2299 static int flushwithdeps = 0;
2300 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2301 0, "Number of buffers flushed with dependecies that require rollbacks");
2304 flushbufqueues(struct vnode *lvp, int queue, int flushdeps)
2306 struct buf *sentinel;
2315 target = numdirtybuffers - lodirtybuffers;
2316 if (flushdeps && target > 2)
2319 target = flushbufqtarget;
2322 sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
2323 sentinel->b_qindex = QUEUE_SENTINEL;
2325 TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
2326 while (flushed != target) {
2327 bp = TAILQ_NEXT(sentinel, b_freelist);
2329 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2330 TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
2335 * Skip sentinels inserted by other invocations of the
2336 * flushbufqueues(), taking care to not reorder them.
2338 if (bp->b_qindex == QUEUE_SENTINEL)
2341 * Only flush the buffers that belong to the
2342 * vnode locked by the curthread.
2344 if (lvp != NULL && bp->b_vp != lvp)
2346 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2348 if (bp->b_pin_count > 0) {
2352 BO_LOCK(bp->b_bufobj);
2353 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2354 (bp->b_flags & B_DELWRI) == 0) {
2355 BO_UNLOCK(bp->b_bufobj);
2359 BO_UNLOCK(bp->b_bufobj);
2360 if (bp->b_flags & B_INVAL) {
2362 mtx_unlock(&bqlock);
2365 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2370 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
2371 if (flushdeps == 0) {
2379 * We must hold the lock on a vnode before writing
2380 * one of its buffers. Otherwise we may confuse, or
2381 * in the case of a snapshot vnode, deadlock the
2384 * The lock order here is the reverse of the normal
2385 * of vnode followed by buf lock. This is ok because
2386 * the NOWAIT will prevent deadlock.
2389 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2393 if (vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT | LK_CANRECURSE) == 0) {
2394 mtx_unlock(&bqlock);
2395 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2396 bp, bp->b_vp, bp->b_flags);
2397 if (curproc == bufdaemonproc)
2404 vn_finished_write(mp);
2406 flushwithdeps += hasdeps;
2410 * Sleeping on runningbufspace while holding
2411 * vnode lock leads to deadlock.
2413 if (curproc == bufdaemonproc)
2414 waitrunningbufspace();
2415 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2419 vn_finished_write(mp);
2422 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2423 mtx_unlock(&bqlock);
2424 free(sentinel, M_TEMP);
2429 * Check to see if a block is currently memory resident.
2432 incore(struct bufobj *bo, daddr_t blkno)
2437 bp = gbincore(bo, blkno);
2443 * Returns true if no I/O is needed to access the
2444 * associated VM object. This is like incore except
2445 * it also hunts around in the VM system for the data.
2449 inmem(struct vnode * vp, daddr_t blkno)
2452 vm_offset_t toff, tinc, size;
2456 ASSERT_VOP_LOCKED(vp, "inmem");
2458 if (incore(&vp->v_bufobj, blkno))
2460 if (vp->v_mount == NULL)
2467 if (size > vp->v_mount->mnt_stat.f_iosize)
2468 size = vp->v_mount->mnt_stat.f_iosize;
2469 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2471 VM_OBJECT_LOCK(obj);
2472 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2473 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2477 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2478 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2479 if (vm_page_is_valid(m,
2480 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2483 VM_OBJECT_UNLOCK(obj);
2487 VM_OBJECT_UNLOCK(obj);
2492 * Set the dirty range for a buffer based on the status of the dirty
2493 * bits in the pages comprising the buffer. The range is limited
2494 * to the size of the buffer.
2496 * Tell the VM system that the pages associated with this buffer
2497 * are clean. This is used for delayed writes where the data is
2498 * going to go to disk eventually without additional VM intevention.
2500 * Note that while we only really need to clean through to b_bcount, we
2501 * just go ahead and clean through to b_bufsize.
2504 vfs_clean_pages_dirty_buf(struct buf *bp)
2506 vm_ooffset_t foff, noff, eoff;
2510 if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
2513 foff = bp->b_offset;
2514 KASSERT(bp->b_offset != NOOFFSET,
2515 ("vfs_clean_pages_dirty_buf: no buffer offset"));
2517 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
2518 vfs_drain_busy_pages(bp);
2519 vfs_setdirty_locked_object(bp);
2520 vm_page_lock_queues();
2521 for (i = 0; i < bp->b_npages; i++) {
2522 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2524 if (eoff > bp->b_offset + bp->b_bufsize)
2525 eoff = bp->b_offset + bp->b_bufsize;
2527 vfs_page_set_validclean(bp, foff, m);
2528 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
2531 vm_page_unlock_queues();
2532 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
2536 vfs_setdirty_locked_object(struct buf *bp)
2541 object = bp->b_bufobj->bo_object;
2542 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2545 * We qualify the scan for modified pages on whether the
2546 * object has been flushed yet.
2548 if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2549 vm_offset_t boffset;
2550 vm_offset_t eoffset;
2552 vm_page_lock_queues();
2554 * test the pages to see if they have been modified directly
2555 * by users through the VM system.
2557 for (i = 0; i < bp->b_npages; i++)
2558 vm_page_test_dirty(bp->b_pages[i]);
2561 * Calculate the encompassing dirty range, boffset and eoffset,
2562 * (eoffset - boffset) bytes.
2565 for (i = 0; i < bp->b_npages; i++) {
2566 if (bp->b_pages[i]->dirty)
2569 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2571 for (i = bp->b_npages - 1; i >= 0; --i) {
2572 if (bp->b_pages[i]->dirty) {
2576 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2578 vm_page_unlock_queues();
2580 * Fit it to the buffer.
2583 if (eoffset > bp->b_bcount)
2584 eoffset = bp->b_bcount;
2587 * If we have a good dirty range, merge with the existing
2591 if (boffset < eoffset) {
2592 if (bp->b_dirtyoff > boffset)
2593 bp->b_dirtyoff = boffset;
2594 if (bp->b_dirtyend < eoffset)
2595 bp->b_dirtyend = eoffset;
2603 * Get a block given a specified block and offset into a file/device.
2604 * The buffers B_DONE bit will be cleared on return, making it almost
2605 * ready for an I/O initiation. B_INVAL may or may not be set on
2606 * return. The caller should clear B_INVAL prior to initiating a
2609 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2610 * an existing buffer.
2612 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2613 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2614 * and then cleared based on the backing VM. If the previous buffer is
2615 * non-0-sized but invalid, B_CACHE will be cleared.
2617 * If getblk() must create a new buffer, the new buffer is returned with
2618 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2619 * case it is returned with B_INVAL clear and B_CACHE set based on the
2622 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
2623 * B_CACHE bit is clear.
2625 * What this means, basically, is that the caller should use B_CACHE to
2626 * determine whether the buffer is fully valid or not and should clear
2627 * B_INVAL prior to issuing a read. If the caller intends to validate
2628 * the buffer by loading its data area with something, the caller needs
2629 * to clear B_INVAL. If the caller does this without issuing an I/O,
2630 * the caller should set B_CACHE ( as an optimization ), else the caller
2631 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2632 * a write attempt or if it was a successfull read. If the caller
2633 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
2634 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2637 getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo,
2644 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
2645 ASSERT_VOP_LOCKED(vp, "getblk");
2646 if (size > MAXBSIZE)
2647 panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2652 * Block if we are low on buffers. Certain processes are allowed
2653 * to completely exhaust the buffer cache.
2655 * If this check ever becomes a bottleneck it may be better to
2656 * move it into the else, when gbincore() fails. At the moment
2657 * it isn't a problem.
2659 * XXX remove if 0 sections (clean this up after its proven)
2661 if (numfreebuffers == 0) {
2662 if (TD_IS_IDLETHREAD(curthread))
2665 needsbuffer |= VFS_BIO_NEED_ANY;
2666 mtx_unlock(&nblock);
2670 bp = gbincore(bo, blkno);
2674 * Buffer is in-core. If the buffer is not busy, it must
2677 lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
2679 if (flags & GB_LOCK_NOWAIT)
2680 lockflags |= LK_NOWAIT;
2682 error = BUF_TIMELOCK(bp, lockflags,
2683 BO_MTX(bo), "getblk", slpflag, slptimeo);
2686 * If we slept and got the lock we have to restart in case
2687 * the buffer changed identities.
2689 if (error == ENOLCK)
2691 /* We timed out or were interrupted. */
2696 * The buffer is locked. B_CACHE is cleared if the buffer is
2697 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
2698 * and for a VMIO buffer B_CACHE is adjusted according to the
2701 if (bp->b_flags & B_INVAL)
2702 bp->b_flags &= ~B_CACHE;
2703 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2704 bp->b_flags |= B_CACHE;
2710 * check for size inconsistancies for non-VMIO case.
2713 if (bp->b_bcount != size) {
2714 if ((bp->b_flags & B_VMIO) == 0 ||
2715 (size > bp->b_kvasize)) {
2716 if (bp->b_flags & B_DELWRI) {
2718 * If buffer is pinned and caller does
2719 * not want sleep waiting for it to be
2720 * unpinned, bail out
2722 if (bp->b_pin_count > 0) {
2723 if (flags & GB_LOCK_NOWAIT) {
2730 bp->b_flags |= B_NOCACHE;
2733 if (LIST_EMPTY(&bp->b_dep)) {
2734 bp->b_flags |= B_RELBUF;
2737 bp->b_flags |= B_NOCACHE;
2746 * If the size is inconsistant in the VMIO case, we can resize
2747 * the buffer. This might lead to B_CACHE getting set or
2748 * cleared. If the size has not changed, B_CACHE remains
2749 * unchanged from its previous state.
2752 if (bp->b_bcount != size)
2755 KASSERT(bp->b_offset != NOOFFSET,
2756 ("getblk: no buffer offset"));
2759 * A buffer with B_DELWRI set and B_CACHE clear must
2760 * be committed before we can return the buffer in
2761 * order to prevent the caller from issuing a read
2762 * ( due to B_CACHE not being set ) and overwriting
2765 * Most callers, including NFS and FFS, need this to
2766 * operate properly either because they assume they
2767 * can issue a read if B_CACHE is not set, or because
2768 * ( for example ) an uncached B_DELWRI might loop due
2769 * to softupdates re-dirtying the buffer. In the latter
2770 * case, B_CACHE is set after the first write completes,
2771 * preventing further loops.
2772 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2773 * above while extending the buffer, we cannot allow the
2774 * buffer to remain with B_CACHE set after the write
2775 * completes or it will represent a corrupt state. To
2776 * deal with this we set B_NOCACHE to scrap the buffer
2779 * We might be able to do something fancy, like setting
2780 * B_CACHE in bwrite() except if B_DELWRI is already set,
2781 * so the below call doesn't set B_CACHE, but that gets real
2782 * confusing. This is much easier.
2785 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2786 bp->b_flags |= B_NOCACHE;
2790 bp->b_flags &= ~B_DONE;
2792 int bsize, maxsize, vmio;
2796 * Buffer is not in-core, create new buffer. The buffer
2797 * returned by getnewbuf() is locked. Note that the returned
2798 * buffer is also considered valid (not marked B_INVAL).
2802 * If the user does not want us to create the buffer, bail out
2805 if (flags & GB_NOCREAT)
2807 bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
2808 offset = blkno * bsize;
2809 vmio = vp->v_object != NULL;
2810 maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2811 maxsize = imax(maxsize, bsize);
2813 bp = getnewbuf(vp, slpflag, slptimeo, size, maxsize, flags);
2815 if (slpflag || slptimeo)
2821 * This code is used to make sure that a buffer is not
2822 * created while the getnewbuf routine is blocked.
2823 * This can be a problem whether the vnode is locked or not.
2824 * If the buffer is created out from under us, we have to
2825 * throw away the one we just created.
2827 * Note: this must occur before we associate the buffer
2828 * with the vp especially considering limitations in
2829 * the splay tree implementation when dealing with duplicate
2833 if (gbincore(bo, blkno)) {
2835 bp->b_flags |= B_INVAL;
2841 * Insert the buffer into the hash, so that it can
2842 * be found by incore.
2844 bp->b_blkno = bp->b_lblkno = blkno;
2845 bp->b_offset = offset;
2850 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
2851 * buffer size starts out as 0, B_CACHE will be set by
2852 * allocbuf() for the VMIO case prior to it testing the
2853 * backing store for validity.
2857 bp->b_flags |= B_VMIO;
2858 #if defined(VFS_BIO_DEBUG)
2859 if (vn_canvmio(vp) != TRUE)
2860 printf("getblk: VMIO on vnode type %d\n",
2863 KASSERT(vp->v_object == bp->b_bufobj->bo_object,
2864 ("ARGH! different b_bufobj->bo_object %p %p %p\n",
2865 bp, vp->v_object, bp->b_bufobj->bo_object));
2867 bp->b_flags &= ~B_VMIO;
2868 KASSERT(bp->b_bufobj->bo_object == NULL,
2869 ("ARGH! has b_bufobj->bo_object %p %p\n",
2870 bp, bp->b_bufobj->bo_object));
2874 bp->b_flags &= ~B_DONE;
2876 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
2877 BUF_ASSERT_HELD(bp);
2878 KASSERT(bp->b_bufobj == bo,
2879 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2884 * Get an empty, disassociated buffer of given size. The buffer is initially
2888 geteblk(int size, int flags)
2893 maxsize = (size + BKVAMASK) & ~BKVAMASK;
2894 while ((bp = getnewbuf(NULL, 0, 0, size, maxsize, flags)) == NULL) {
2895 if ((flags & GB_NOWAIT_BD) &&
2896 (curthread->td_pflags & TDP_BUFNEED) != 0)
2900 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2901 BUF_ASSERT_HELD(bp);
2907 * This code constitutes the buffer memory from either anonymous system
2908 * memory (in the case of non-VMIO operations) or from an associated
2909 * VM object (in the case of VMIO operations). This code is able to
2910 * resize a buffer up or down.
2912 * Note that this code is tricky, and has many complications to resolve
2913 * deadlock or inconsistant data situations. Tread lightly!!!
2914 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2915 * the caller. Calling this code willy nilly can result in the loss of data.
2917 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2918 * B_CACHE for the non-VMIO case.
2922 allocbuf(struct buf *bp, int size)
2924 int newbsize, mbsize;
2927 BUF_ASSERT_HELD(bp);
2929 if (bp->b_kvasize < size)
2930 panic("allocbuf: buffer too small");
2932 if ((bp->b_flags & B_VMIO) == 0) {
2936 * Just get anonymous memory from the kernel. Don't
2937 * mess with B_CACHE.
2939 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2940 if (bp->b_flags & B_MALLOC)
2943 newbsize = round_page(size);
2945 if (newbsize < bp->b_bufsize) {
2947 * malloced buffers are not shrunk
2949 if (bp->b_flags & B_MALLOC) {
2951 bp->b_bcount = size;
2953 free(bp->b_data, M_BIOBUF);
2954 if (bp->b_bufsize) {
2955 atomic_subtract_long(
2961 bp->b_saveaddr = bp->b_kvabase;
2962 bp->b_data = bp->b_saveaddr;
2964 bp->b_flags &= ~B_MALLOC;
2968 vm_hold_free_pages(bp, newbsize);
2969 } else if (newbsize > bp->b_bufsize) {
2971 * We only use malloced memory on the first allocation.
2972 * and revert to page-allocated memory when the buffer
2976 * There is a potential smp race here that could lead
2977 * to bufmallocspace slightly passing the max. It
2978 * is probably extremely rare and not worth worrying
2981 if ( (bufmallocspace < maxbufmallocspace) &&
2982 (bp->b_bufsize == 0) &&
2983 (mbsize <= PAGE_SIZE/2)) {
2985 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2986 bp->b_bufsize = mbsize;
2987 bp->b_bcount = size;
2988 bp->b_flags |= B_MALLOC;
2989 atomic_add_long(&bufmallocspace, mbsize);
2995 * If the buffer is growing on its other-than-first allocation,
2996 * then we revert to the page-allocation scheme.
2998 if (bp->b_flags & B_MALLOC) {
2999 origbuf = bp->b_data;
3000 origbufsize = bp->b_bufsize;
3001 bp->b_data = bp->b_kvabase;
3002 if (bp->b_bufsize) {
3003 atomic_subtract_long(&bufmallocspace,
3008 bp->b_flags &= ~B_MALLOC;
3009 newbsize = round_page(newbsize);
3013 (vm_offset_t) bp->b_data + bp->b_bufsize,
3014 (vm_offset_t) bp->b_data + newbsize);
3016 bcopy(origbuf, bp->b_data, origbufsize);
3017 free(origbuf, M_BIOBUF);
3023 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3024 desiredpages = (size == 0) ? 0 :
3025 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
3027 if (bp->b_flags & B_MALLOC)
3028 panic("allocbuf: VMIO buffer can't be malloced");
3030 * Set B_CACHE initially if buffer is 0 length or will become
3033 if (size == 0 || bp->b_bufsize == 0)
3034 bp->b_flags |= B_CACHE;
3036 if (newbsize < bp->b_bufsize) {
3038 * DEV_BSIZE aligned new buffer size is less then the
3039 * DEV_BSIZE aligned existing buffer size. Figure out
3040 * if we have to remove any pages.
3042 if (desiredpages < bp->b_npages) {
3045 pmap_qremove((vm_offset_t)trunc_page(
3046 (vm_offset_t)bp->b_data) +
3047 (desiredpages << PAGE_SHIFT),
3048 (bp->b_npages - desiredpages));
3049 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3050 vm_page_lock_queues();
3051 for (i = desiredpages; i < bp->b_npages; i++) {
3053 * the page is not freed here -- it
3054 * is the responsibility of
3055 * vnode_pager_setsize
3058 KASSERT(m != bogus_page,
3059 ("allocbuf: bogus page found"));
3060 while (vm_page_sleep_if_busy(m, TRUE, "biodep"))
3061 vm_page_lock_queues();
3063 bp->b_pages[i] = NULL;
3064 vm_page_unwire(m, 0);
3066 vm_page_unlock_queues();
3067 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3068 bp->b_npages = desiredpages;
3070 } else if (size > bp->b_bcount) {
3072 * We are growing the buffer, possibly in a
3073 * byte-granular fashion.
3080 * Step 1, bring in the VM pages from the object,
3081 * allocating them if necessary. We must clear
3082 * B_CACHE if these pages are not valid for the
3083 * range covered by the buffer.
3086 obj = bp->b_bufobj->bo_object;
3088 VM_OBJECT_LOCK(obj);
3089 while (bp->b_npages < desiredpages) {
3093 pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
3094 if ((m = vm_page_lookup(obj, pi)) == NULL) {
3096 * note: must allocate system pages
3097 * since blocking here could intefere
3098 * with paging I/O, no matter which
3101 m = vm_page_alloc(obj, pi,
3102 VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM |
3105 atomic_add_int(&vm_pageout_deficit,
3106 desiredpages - bp->b_npages);
3107 VM_OBJECT_UNLOCK(obj);
3109 VM_OBJECT_LOCK(obj);
3112 bp->b_flags &= ~B_CACHE;
3113 bp->b_pages[bp->b_npages] = m;
3120 * We found a page. If we have to sleep on it,
3121 * retry because it might have gotten freed out
3124 * We can only test VPO_BUSY here. Blocking on
3125 * m->busy might lead to a deadlock:
3127 * vm_fault->getpages->cluster_read->allocbuf
3130 if (vm_page_sleep_if_busy(m, FALSE, "pgtblk"))
3134 * We have a good page.
3136 vm_page_lock_queues();
3138 vm_page_unlock_queues();
3139 bp->b_pages[bp->b_npages] = m;
3144 * Step 2. We've loaded the pages into the buffer,
3145 * we have to figure out if we can still have B_CACHE
3146 * set. Note that B_CACHE is set according to the
3147 * byte-granular range ( bcount and size ), new the
3148 * aligned range ( newbsize ).
3150 * The VM test is against m->valid, which is DEV_BSIZE
3151 * aligned. Needless to say, the validity of the data
3152 * needs to also be DEV_BSIZE aligned. Note that this
3153 * fails with NFS if the server or some other client
3154 * extends the file's EOF. If our buffer is resized,
3155 * B_CACHE may remain set! XXX
3158 toff = bp->b_bcount;
3159 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
3161 while ((bp->b_flags & B_CACHE) && toff < size) {
3164 if (tinc > (size - toff))
3167 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
3180 VM_OBJECT_UNLOCK(obj);
3183 * Step 3, fixup the KVM pmap. Remember that
3184 * bp->b_data is relative to bp->b_offset, but
3185 * bp->b_offset may be offset into the first page.
3188 bp->b_data = (caddr_t)
3189 trunc_page((vm_offset_t)bp->b_data);
3191 (vm_offset_t)bp->b_data,
3196 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
3197 (vm_offset_t)(bp->b_offset & PAGE_MASK));
3200 if (newbsize < bp->b_bufsize)
3202 bp->b_bufsize = newbsize; /* actual buffer allocation */
3203 bp->b_bcount = size; /* requested buffer size */
3208 biodone(struct bio *bp)
3211 void (*done)(struct bio *);
3213 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3215 bp->bio_flags |= BIO_DONE;
3216 done = bp->bio_done;
3225 * Wait for a BIO to finish.
3227 * XXX: resort to a timeout for now. The optimal locking (if any) for this
3228 * case is not yet clear.
3231 biowait(struct bio *bp, const char *wchan)
3235 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3237 while ((bp->bio_flags & BIO_DONE) == 0)
3238 msleep(bp, mtxp, PRIBIO, wchan, hz / 10);
3240 if (bp->bio_error != 0)
3241 return (bp->bio_error);
3242 if (!(bp->bio_flags & BIO_ERROR))
3248 biofinish(struct bio *bp, struct devstat *stat, int error)
3252 bp->bio_error = error;
3253 bp->bio_flags |= BIO_ERROR;
3256 devstat_end_transaction_bio(stat, bp);
3263 * Wait for buffer I/O completion, returning error status. The buffer
3264 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR
3265 * error and cleared.
3268 bufwait(struct buf *bp)
3270 if (bp->b_iocmd == BIO_READ)
3271 bwait(bp, PRIBIO, "biord");
3273 bwait(bp, PRIBIO, "biowr");
3274 if (bp->b_flags & B_EINTR) {
3275 bp->b_flags &= ~B_EINTR;
3278 if (bp->b_ioflags & BIO_ERROR) {
3279 return (bp->b_error ? bp->b_error : EIO);
3286 * Call back function from struct bio back up to struct buf.
3289 bufdonebio(struct bio *bip)
3293 bp = bip->bio_caller2;
3294 bp->b_resid = bp->b_bcount - bip->bio_completed;
3295 bp->b_resid = bip->bio_resid; /* XXX: remove */
3296 bp->b_ioflags = bip->bio_flags;
3297 bp->b_error = bip->bio_error;
3299 bp->b_ioflags |= BIO_ERROR;
3305 dev_strategy(struct cdev *dev, struct buf *bp)
3311 if ((!bp->b_iocmd) || (bp->b_iocmd & (bp->b_iocmd - 1)))
3312 panic("b_iocmd botch");
3317 /* Try again later */
3318 tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3320 bip->bio_cmd = bp->b_iocmd;
3321 bip->bio_offset = bp->b_iooffset;
3322 bip->bio_length = bp->b_bcount;
3323 bip->bio_bcount = bp->b_bcount; /* XXX: remove */
3324 bip->bio_data = bp->b_data;
3325 bip->bio_done = bufdonebio;
3326 bip->bio_caller2 = bp;
3328 KASSERT(dev->si_refcount > 0,
3329 ("dev_strategy on un-referenced struct cdev *(%s)",
3331 csw = dev_refthread(dev, &ref);
3334 bp->b_error = ENXIO;
3335 bp->b_ioflags = BIO_ERROR;
3339 (*csw->d_strategy)(bip);
3340 dev_relthread(dev, ref);
3346 * Finish I/O on a buffer, optionally calling a completion function.
3347 * This is usually called from an interrupt so process blocking is
3350 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3351 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3352 * assuming B_INVAL is clear.
3354 * For the VMIO case, we set B_CACHE if the op was a read and no
3355 * read error occured, or if the op was a write. B_CACHE is never
3356 * set if the buffer is invalid or otherwise uncacheable.
3358 * biodone does not mess with B_INVAL, allowing the I/O routine or the
3359 * initiator to leave B_INVAL set to brelse the buffer out of existance
3360 * in the biodone routine.
3363 bufdone(struct buf *bp)
3365 struct bufobj *dropobj;
3366 void (*biodone)(struct buf *);
3368 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3371 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3372 BUF_ASSERT_HELD(bp);
3374 runningbufwakeup(bp);
3375 if (bp->b_iocmd == BIO_WRITE)
3376 dropobj = bp->b_bufobj;
3377 /* call optional completion function if requested */
3378 if (bp->b_iodone != NULL) {
3379 biodone = bp->b_iodone;
3380 bp->b_iodone = NULL;
3383 bufobj_wdrop(dropobj);
3390 bufobj_wdrop(dropobj);
3394 bufdone_finish(struct buf *bp)
3396 BUF_ASSERT_HELD(bp);
3398 if (!LIST_EMPTY(&bp->b_dep))
3401 if (bp->b_flags & B_VMIO) {
3407 struct vnode *vp = bp->b_vp;
3409 obj = bp->b_bufobj->bo_object;
3411 #if defined(VFS_BIO_DEBUG)
3412 mp_fixme("usecount and vflag accessed without locks.");
3413 if (vp->v_usecount == 0) {
3414 panic("biodone: zero vnode ref count");
3417 KASSERT(vp->v_object != NULL,
3418 ("biodone: vnode %p has no vm_object", vp));
3421 foff = bp->b_offset;
3422 KASSERT(bp->b_offset != NOOFFSET,
3423 ("biodone: no buffer offset"));
3425 VM_OBJECT_LOCK(obj);
3426 #if defined(VFS_BIO_DEBUG)
3427 if (obj->paging_in_progress < bp->b_npages) {
3428 printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
3429 obj->paging_in_progress, bp->b_npages);
3434 * Set B_CACHE if the op was a normal read and no error
3435 * occured. B_CACHE is set for writes in the b*write()
3438 iosize = bp->b_bcount - bp->b_resid;
3439 if (bp->b_iocmd == BIO_READ &&
3440 !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3441 !(bp->b_ioflags & BIO_ERROR)) {
3442 bp->b_flags |= B_CACHE;
3445 for (i = 0; i < bp->b_npages; i++) {
3449 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3454 * cleanup bogus pages, restoring the originals
3457 if (m == bogus_page) {
3458 bogus = bogusflag = 1;
3459 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3461 panic("biodone: page disappeared!");
3464 #if defined(VFS_BIO_DEBUG)
3465 if (OFF_TO_IDX(foff) != m->pindex) {
3467 "biodone: foff(%jd)/m->pindex(%ju) mismatch\n",
3468 (intmax_t)foff, (uintmax_t)m->pindex);
3473 * In the write case, the valid and clean bits are
3474 * already changed correctly ( see bdwrite() ), so we
3475 * only need to do this here in the read case.
3477 if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3478 KASSERT((m->dirty & vm_page_bits(foff &
3479 PAGE_MASK, resid)) == 0, ("bufdone_finish:"
3480 " page %p has unexpected dirty bits", m));
3481 vfs_page_set_valid(bp, foff, m);
3485 * when debugging new filesystems or buffer I/O methods, this
3486 * is the most common error that pops up. if you see this, you
3487 * have not set the page busy flag correctly!!!
3490 printf("biodone: page busy < 0, "
3491 "pindex: %d, foff: 0x(%x,%x), "
3492 "resid: %d, index: %d\n",
3493 (int) m->pindex, (int)(foff >> 32),
3494 (int) foff & 0xffffffff, resid, i);
3495 if (!vn_isdisk(vp, NULL))
3496 printf(" iosize: %jd, lblkno: %jd, flags: 0x%x, npages: %d\n",
3497 (intmax_t)bp->b_vp->v_mount->mnt_stat.f_iosize,
3498 (intmax_t) bp->b_lblkno,
3499 bp->b_flags, bp->b_npages);
3501 printf(" VDEV, lblkno: %jd, flags: 0x%x, npages: %d\n",
3502 (intmax_t) bp->b_lblkno,
3503 bp->b_flags, bp->b_npages);
3504 printf(" valid: 0x%lx, dirty: 0x%lx, wired: %d\n",
3505 (u_long)m->valid, (u_long)m->dirty,
3507 panic("biodone: page busy < 0\n");
3509 vm_page_io_finish(m);
3510 vm_object_pip_subtract(obj, 1);
3511 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3514 vm_object_pip_wakeupn(obj, 0);
3515 VM_OBJECT_UNLOCK(obj);
3517 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3518 bp->b_pages, bp->b_npages);
3522 * For asynchronous completions, release the buffer now. The brelse
3523 * will do a wakeup there if necessary - so no need to do a wakeup
3524 * here in the async case. The sync case always needs to do a wakeup.
3527 if (bp->b_flags & B_ASYNC) {
3528 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3537 * This routine is called in lieu of iodone in the case of
3538 * incomplete I/O. This keeps the busy status for pages
3542 vfs_unbusy_pages(struct buf *bp)
3548 runningbufwakeup(bp);
3549 if (!(bp->b_flags & B_VMIO))
3552 obj = bp->b_bufobj->bo_object;
3553 VM_OBJECT_LOCK(obj);
3554 for (i = 0; i < bp->b_npages; i++) {
3556 if (m == bogus_page) {
3557 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3559 panic("vfs_unbusy_pages: page missing\n");
3561 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3562 bp->b_pages, bp->b_npages);
3564 vm_object_pip_subtract(obj, 1);
3565 vm_page_io_finish(m);
3567 vm_object_pip_wakeupn(obj, 0);
3568 VM_OBJECT_UNLOCK(obj);
3572 * vfs_page_set_valid:
3574 * Set the valid bits in a page based on the supplied offset. The
3575 * range is restricted to the buffer's size.
3577 * This routine is typically called after a read completes.
3580 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3585 * Compute the end offset, eoff, such that [off, eoff) does not span a
3586 * page boundary and eoff is not greater than the end of the buffer.
3587 * The end of the buffer, in this case, is our file EOF, not the
3588 * allocation size of the buffer.
3590 eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
3591 if (eoff > bp->b_offset + bp->b_bcount)
3592 eoff = bp->b_offset + bp->b_bcount;
3595 * Set valid range. This is typically the entire buffer and thus the
3599 vm_page_set_valid(m, off & PAGE_MASK, eoff - off);
3603 * vfs_page_set_validclean:
3605 * Set the valid bits and clear the dirty bits in a page based on the
3606 * supplied offset. The range is restricted to the buffer's size.
3609 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3611 vm_ooffset_t soff, eoff;
3613 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
3615 * Start and end offsets in buffer. eoff - soff may not cross a
3616 * page boundry or cross the end of the buffer. The end of the
3617 * buffer, in this case, is our file EOF, not the allocation size
3621 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3622 if (eoff > bp->b_offset + bp->b_bcount)
3623 eoff = bp->b_offset + bp->b_bcount;
3626 * Set valid range. This is typically the entire buffer and thus the
3630 vm_page_set_validclean(
3632 (vm_offset_t) (soff & PAGE_MASK),
3633 (vm_offset_t) (eoff - soff)
3639 * Ensure that all buffer pages are not busied by VPO_BUSY flag. If
3640 * any page is busy, drain the flag.
3643 vfs_drain_busy_pages(struct buf *bp)
3648 VM_OBJECT_LOCK_ASSERT(bp->b_bufobj->bo_object, MA_OWNED);
3650 for (i = 0; i < bp->b_npages; i++) {
3652 if ((m->oflags & VPO_BUSY) != 0) {
3653 for (; last_busied < i; last_busied++)
3654 vm_page_busy(bp->b_pages[last_busied]);
3655 while ((m->oflags & VPO_BUSY) != 0)
3656 vm_page_sleep(m, "vbpage");
3659 for (i = 0; i < last_busied; i++)
3660 vm_page_wakeup(bp->b_pages[i]);
3664 * This routine is called before a device strategy routine.
3665 * It is used to tell the VM system that paging I/O is in
3666 * progress, and treat the pages associated with the buffer
3667 * almost as being VPO_BUSY. Also the object paging_in_progress
3668 * flag is handled to make sure that the object doesn't become
3671 * Since I/O has not been initiated yet, certain buffer flags
3672 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
3673 * and should be ignored.
3676 vfs_busy_pages(struct buf *bp, int clear_modify)
3683 if (!(bp->b_flags & B_VMIO))
3686 obj = bp->b_bufobj->bo_object;
3687 foff = bp->b_offset;
3688 KASSERT(bp->b_offset != NOOFFSET,
3689 ("vfs_busy_pages: no buffer offset"));
3690 VM_OBJECT_LOCK(obj);
3691 vfs_drain_busy_pages(bp);
3692 if (bp->b_bufsize != 0)
3693 vfs_setdirty_locked_object(bp);
3696 vm_page_lock_queues();
3697 for (i = 0; i < bp->b_npages; i++) {
3700 if ((bp->b_flags & B_CLUSTER) == 0) {
3701 vm_object_pip_add(obj, 1);
3702 vm_page_io_start(m);
3705 * When readying a buffer for a read ( i.e
3706 * clear_modify == 0 ), it is important to do
3707 * bogus_page replacement for valid pages in
3708 * partially instantiated buffers. Partially
3709 * instantiated buffers can, in turn, occur when
3710 * reconstituting a buffer from its VM backing store
3711 * base. We only have to do this if B_CACHE is
3712 * clear ( which causes the I/O to occur in the
3713 * first place ). The replacement prevents the read
3714 * I/O from overwriting potentially dirty VM-backed
3715 * pages. XXX bogus page replacement is, uh, bogus.
3716 * It may not work properly with small-block devices.
3717 * We need to find a better way.
3720 pmap_remove_write(m);
3721 vfs_page_set_validclean(bp, foff, m);
3722 } else if (m->valid == VM_PAGE_BITS_ALL &&
3723 (bp->b_flags & B_CACHE) == 0) {
3724 bp->b_pages[i] = bogus_page;
3727 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3730 vm_page_unlock_queues();
3731 VM_OBJECT_UNLOCK(obj);
3733 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3734 bp->b_pages, bp->b_npages);
3738 * vfs_bio_set_valid:
3740 * Set the range within the buffer to valid. The range is
3741 * relative to the beginning of the buffer, b_offset. Note that
3742 * b_offset itself may be offset from the beginning of the first
3746 vfs_bio_set_valid(struct buf *bp, int base, int size)
3751 if (!(bp->b_flags & B_VMIO))
3755 * Fixup base to be relative to beginning of first page.
3756 * Set initial n to be the maximum number of bytes in the
3757 * first page that can be validated.
3759 base += (bp->b_offset & PAGE_MASK);
3760 n = PAGE_SIZE - (base & PAGE_MASK);
3762 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3763 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3767 vm_page_set_valid(m, base & PAGE_MASK, n);
3772 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3778 * If the specified buffer is a non-VMIO buffer, clear the entire
3779 * buffer. If the specified buffer is a VMIO buffer, clear and
3780 * validate only the previously invalid portions of the buffer.
3781 * This routine essentially fakes an I/O, so we need to clear
3782 * BIO_ERROR and B_INVAL.
3784 * Note that while we only theoretically need to clear through b_bcount,
3785 * we go ahead and clear through b_bufsize.
3788 vfs_bio_clrbuf(struct buf *bp)
3793 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
3797 bp->b_flags &= ~B_INVAL;
3798 bp->b_ioflags &= ~BIO_ERROR;
3799 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3800 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3801 (bp->b_offset & PAGE_MASK) == 0) {
3802 if (bp->b_pages[0] == bogus_page)
3804 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3805 VM_OBJECT_LOCK_ASSERT(bp->b_pages[0]->object, MA_OWNED);
3806 if ((bp->b_pages[0]->valid & mask) == mask)
3808 if ((bp->b_pages[0]->valid & mask) == 0) {
3809 bzero(bp->b_data, bp->b_bufsize);
3810 bp->b_pages[0]->valid |= mask;
3814 ea = sa = bp->b_data;
3815 for(i = 0; i < bp->b_npages; i++, sa = ea) {
3816 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3817 ea = (caddr_t)(vm_offset_t)ulmin(
3818 (u_long)(vm_offset_t)ea,
3819 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3820 if (bp->b_pages[i] == bogus_page)
3822 j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3823 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3824 VM_OBJECT_LOCK_ASSERT(bp->b_pages[i]->object, MA_OWNED);
3825 if ((bp->b_pages[i]->valid & mask) == mask)
3827 if ((bp->b_pages[i]->valid & mask) == 0)
3830 for (; sa < ea; sa += DEV_BSIZE, j++) {
3831 if ((bp->b_pages[i]->valid & (1 << j)) == 0)
3832 bzero(sa, DEV_BSIZE);
3835 bp->b_pages[i]->valid |= mask;
3838 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3843 * vm_hold_load_pages and vm_hold_free_pages get pages into
3844 * a buffers address space. The pages are anonymous and are
3845 * not associated with a file object.
3848 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3854 to = round_page(to);
3855 from = round_page(from);
3856 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3858 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3861 * note: must allocate system pages since blocking here
3862 * could interfere with paging I/O, no matter which
3865 p = vm_page_alloc(NULL, pg >> PAGE_SHIFT, VM_ALLOC_NOOBJ |
3866 VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
3868 atomic_add_int(&vm_pageout_deficit,
3869 (to - pg) >> PAGE_SHIFT);
3873 pmap_qenter(pg, &p, 1);
3874 bp->b_pages[index] = p;
3876 bp->b_npages = index;
3879 /* Return pages associated with this buf to the vm system */
3881 vm_hold_free_pages(struct buf *bp, int newbsize)
3885 int index, newnpages;
3887 from = round_page((vm_offset_t)bp->b_data + newbsize);
3888 newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3889 if (bp->b_npages > newnpages)
3890 pmap_qremove(from, bp->b_npages - newnpages);
3891 for (index = newnpages; index < bp->b_npages; index++) {
3892 p = bp->b_pages[index];
3893 bp->b_pages[index] = NULL;
3895 printf("vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
3896 (intmax_t)bp->b_blkno, (intmax_t)bp->b_lblkno);
3899 atomic_subtract_int(&cnt.v_wire_count, 1);
3901 bp->b_npages = newnpages;
3905 * Map an IO request into kernel virtual address space.
3907 * All requests are (re)mapped into kernel VA space.
3908 * Notice that we use b_bufsize for the size of the buffer
3909 * to be mapped. b_bcount might be modified by the driver.
3911 * Note that even if the caller determines that the address space should
3912 * be valid, a race or a smaller-file mapped into a larger space may
3913 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
3914 * check the return value.
3917 vmapbuf(struct buf *bp)
3923 struct pmap *pmap = &curproc->p_vmspace->vm_pmap;
3925 if (bp->b_bufsize < 0)
3927 prot = VM_PROT_READ;
3928 if (bp->b_iocmd == BIO_READ)
3929 prot |= VM_PROT_WRITE; /* Less backwards than it looks */
3930 for (addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data), pidx = 0;
3931 addr < bp->b_data + bp->b_bufsize;
3932 addr += PAGE_SIZE, pidx++) {
3934 * Do the vm_fault if needed; do the copy-on-write thing
3935 * when reading stuff off device into memory.
3937 * NOTE! Must use pmap_extract() because addr may be in
3938 * the userland address space, and kextract is only guarenteed
3939 * to work for the kernland address space (see: sparc64 port).
3942 if (vm_fault_quick(addr >= bp->b_data ? addr : bp->b_data,
3944 vm_page_lock_queues();
3945 for (i = 0; i < pidx; ++i) {
3946 vm_page_unhold(bp->b_pages[i]);
3947 bp->b_pages[i] = NULL;
3949 vm_page_unlock_queues();
3952 m = pmap_extract_and_hold(pmap, (vm_offset_t)addr, prot);
3955 bp->b_pages[pidx] = m;
3957 if (pidx > btoc(MAXPHYS))
3958 panic("vmapbuf: mapped more than MAXPHYS");
3959 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
3961 kva = bp->b_saveaddr;
3962 bp->b_npages = pidx;
3963 bp->b_saveaddr = bp->b_data;
3964 bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3969 * Free the io map PTEs associated with this IO operation.
3970 * We also invalidate the TLB entries and restore the original b_addr.
3973 vunmapbuf(struct buf *bp)
3978 npages = bp->b_npages;
3979 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
3980 vm_page_lock_queues();
3981 for (pidx = 0; pidx < npages; pidx++)
3982 vm_page_unhold(bp->b_pages[pidx]);
3983 vm_page_unlock_queues();
3985 bp->b_data = bp->b_saveaddr;
3989 bdone(struct buf *bp)
3993 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3995 bp->b_flags |= B_DONE;
4001 bwait(struct buf *bp, u_char pri, const char *wchan)
4005 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4007 while ((bp->b_flags & B_DONE) == 0)
4008 msleep(bp, mtxp, pri, wchan, 0);
4013 bufsync(struct bufobj *bo, int waitfor)
4016 return (VOP_FSYNC(bo->__bo_vnode, waitfor, curthread));
4020 bufstrategy(struct bufobj *bo, struct buf *bp)
4026 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
4027 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
4028 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
4029 i = VOP_STRATEGY(vp, bp);
4030 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
4034 bufobj_wrefl(struct bufobj *bo)
4037 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4038 ASSERT_BO_LOCKED(bo);
4043 bufobj_wref(struct bufobj *bo)
4046 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4053 bufobj_wdrop(struct bufobj *bo)
4056 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
4058 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
4059 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
4060 bo->bo_flag &= ~BO_WWAIT;
4061 wakeup(&bo->bo_numoutput);
4067 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
4071 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
4072 ASSERT_BO_LOCKED(bo);
4074 while (bo->bo_numoutput) {
4075 bo->bo_flag |= BO_WWAIT;
4076 error = msleep(&bo->bo_numoutput, BO_MTX(bo),
4077 slpflag | (PRIBIO + 1), "bo_wwait", timeo);
4085 bpin(struct buf *bp)
4089 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4096 bunpin(struct buf *bp)
4100 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4102 if (--bp->b_pin_count == 0)
4108 bunpin_wait(struct buf *bp)
4112 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4114 while (bp->b_pin_count > 0)
4115 msleep(bp, mtxp, PRIBIO, "bwunpin", 0);
4119 #include "opt_ddb.h"
4121 #include <ddb/ddb.h>
4123 /* DDB command to show buffer data */
4124 DB_SHOW_COMMAND(buffer, db_show_buffer)
4127 struct buf *bp = (struct buf *)addr;
4130 db_printf("usage: show buffer <addr>\n");
4134 db_printf("buf at %p\n", bp);
4135 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
4137 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4138 "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_dep = %p\n",
4139 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4140 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4141 bp->b_dep.lh_first);
4144 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4145 for (i = 0; i < bp->b_npages; i++) {
4148 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4149 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4150 if ((i + 1) < bp->b_npages)
4156 BUF_LOCKPRINTINFO(bp);
4159 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
4164 for (i = 0; i < nbuf; i++) {
4166 if (BUF_ISLOCKED(bp)) {
4167 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4173 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
4179 db_printf("usage: show vnodebufs <addr>\n");
4182 vp = (struct vnode *)addr;
4183 db_printf("Clean buffers:\n");
4184 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
4185 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4188 db_printf("Dirty buffers:\n");
4189 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
4190 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4195 DB_COMMAND(countfreebufs, db_coundfreebufs)
4198 int i, used = 0, nfree = 0;
4201 db_printf("usage: countfreebufs\n");
4205 for (i = 0; i < nbuf; i++) {
4207 if ((bp->b_vflags & BV_INFREECNT) != 0)
4213 db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
4215 db_printf("numfreebuffers is %d\n", numfreebuffers);