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/malloc.h>
53 #include <sys/mount.h>
54 #include <sys/mutex.h>
55 #include <sys/kernel.h>
56 #include <sys/kthread.h>
58 #include <sys/resourcevar.h>
59 #include <sys/sysctl.h>
60 #include <sys/vmmeter.h>
61 #include <sys/vnode.h>
62 #include <geom/geom.h>
64 #include <vm/vm_param.h>
65 #include <vm/vm_kern.h>
66 #include <vm/vm_pageout.h>
67 #include <vm/vm_page.h>
68 #include <vm/vm_object.h>
69 #include <vm/vm_extern.h>
70 #include <vm/vm_map.h>
71 #include "opt_directio.h"
74 static MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
76 struct bio_ops bioops; /* I/O operation notification */
78 struct buf_ops buf_ops_bio = {
79 .bop_name = "buf_ops_bio",
80 .bop_write = bufwrite,
81 .bop_strategy = bufstrategy,
86 * XXX buf is global because kern_shutdown.c and ffs_checkoverlap has
87 * carnal knowledge of buffers. This knowledge should be moved to vfs_bio.c.
89 struct buf *buf; /* buffer header pool */
91 static struct proc *bufdaemonproc;
93 static int inmem(struct vnode *vp, daddr_t blkno);
94 static void vm_hold_free_pages(struct buf *bp, vm_offset_t from,
96 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
98 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
99 int pageno, vm_page_t m);
100 static void vfs_clean_pages(struct buf *bp);
101 static void vfs_setdirty(struct buf *bp);
102 static void vfs_vmio_release(struct buf *bp);
103 static int vfs_bio_clcheck(struct vnode *vp, int size,
104 daddr_t lblkno, daddr_t blkno);
105 static int flushbufqueues(int flushdeps);
106 static void buf_daemon(void);
107 static void bremfreel(struct buf *bp);
109 int vmiodirenable = TRUE;
110 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
111 "Use the VM system for directory writes");
113 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
114 "Amount of presently outstanding async buffer io");
116 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
117 "KVA memory used for bufs");
118 static int maxbufspace;
119 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
120 "Maximum allowed value of bufspace (including buf_daemon)");
121 static int bufmallocspace;
122 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
123 "Amount of malloced memory for buffers");
124 static int maxbufmallocspace;
125 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace, 0,
126 "Maximum amount of malloced memory for buffers");
127 static int lobufspace;
128 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
129 "Minimum amount of buffers we want to have");
131 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
132 "Maximum allowed value of bufspace (excluding buf_daemon)");
133 static int bufreusecnt;
134 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW, &bufreusecnt, 0,
135 "Number of times we have reused a buffer");
136 static int buffreekvacnt;
137 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
138 "Number of times we have freed the KVA space from some buffer");
139 static int bufdefragcnt;
140 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
141 "Number of times we have had to repeat buffer allocation to defragment");
142 static int lorunningspace;
143 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
144 "Minimum preferred space used for in-progress I/O");
145 static int hirunningspace;
146 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
147 "Maximum amount of space to use for in-progress I/O");
148 static int dirtybufferflushes;
149 SYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
150 0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
151 static int altbufferflushes;
152 SYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes,
153 0, "Number of fsync flushes to limit dirty buffers");
154 static int recursiveflushes;
155 SYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes,
156 0, "Number of flushes skipped due to being recursive");
157 static int numdirtybuffers;
158 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
159 "Number of buffers that are dirty (has unwritten changes) at the moment");
160 static int lodirtybuffers;
161 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
162 "How many buffers we want to have free before bufdaemon can sleep");
163 static int hidirtybuffers;
164 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
165 "When the number of dirty buffers is considered severe");
166 static int dirtybufthresh;
167 SYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh,
168 0, "Number of bdwrite to bawrite conversions to clear dirty buffers");
169 static int numfreebuffers;
170 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
171 "Number of free buffers");
172 static int lofreebuffers;
173 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
175 static int hifreebuffers;
176 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
177 "XXX Complicatedly unused");
178 static int getnewbufcalls;
179 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
180 "Number of calls to getnewbuf");
181 static int getnewbufrestarts;
182 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
183 "Number of times getnewbuf has had to restart a buffer aquisition");
186 * Wakeup point for bufdaemon, as well as indicator of whether it is already
187 * active. Set to 1 when the bufdaemon is already "on" the queue, 0 when it
190 static int bd_request;
193 * This lock synchronizes access to bd_request.
195 static struct mtx bdlock;
198 * bogus page -- for I/O to/from partially complete buffers
199 * this is a temporary solution to the problem, but it is not
200 * really that bad. it would be better to split the buffer
201 * for input in the case of buffers partially already in memory,
202 * but the code is intricate enough already.
204 vm_page_t bogus_page;
207 * Synchronization (sleep/wakeup) variable for active buffer space requests.
208 * Set when wait starts, cleared prior to wakeup().
209 * Used in runningbufwakeup() and waitrunningbufspace().
211 static int runningbufreq;
214 * This lock protects the runningbufreq and synchronizes runningbufwakeup and
215 * waitrunningbufspace().
217 static struct mtx rbreqlock;
220 * Synchronization (sleep/wakeup) variable for buffer requests.
221 * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
223 * Used in numdirtywakeup(), bufspacewakeup(), bufcountwakeup(), bwillwrite(),
224 * getnewbuf(), and getblk().
226 static int needsbuffer;
229 * Lock that protects needsbuffer and the sleeps/wakeups surrounding it.
231 static struct mtx nblock;
234 * Lock that protects against bwait()/bdone()/B_DONE races.
237 static struct mtx bdonelock;
240 * Lock that protects against bwait()/bdone()/B_DONE races.
242 static struct mtx bpinlock;
245 * Definitions for the buffer free lists.
247 #define BUFFER_QUEUES 5 /* number of free buffer queues */
249 #define QUEUE_NONE 0 /* on no queue */
250 #define QUEUE_CLEAN 1 /* non-B_DELWRI buffers */
251 #define QUEUE_DIRTY 2 /* B_DELWRI buffers */
252 #define QUEUE_EMPTYKVA 3 /* empty buffer headers w/KVA assignment */
253 #define QUEUE_EMPTY 4 /* empty buffer headers */
255 /* Queues for free buffers with various properties */
256 static TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
258 /* Lock for the bufqueues */
259 static struct mtx bqlock;
262 * Single global constant for BUF_WMESG, to avoid getting multiple references.
263 * buf_wmesg is referred from macros.
265 const char *buf_wmesg = BUF_WMESG;
267 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
268 #define VFS_BIO_NEED_DIRTYFLUSH 0x02 /* waiting for dirty buffer flush */
269 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
270 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
273 extern void ffs_rawread_setup(void);
274 #endif /* DIRECTIO */
278 * If someone is blocked due to there being too many dirty buffers,
279 * and numdirtybuffers is now reasonable, wake them up.
283 numdirtywakeup(int level)
286 if (numdirtybuffers <= level) {
288 if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
289 needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
290 wakeup(&needsbuffer);
299 * Called when buffer space is potentially available for recovery.
300 * getnewbuf() will block on this flag when it is unable to free
301 * sufficient buffer space. Buffer space becomes recoverable when
302 * bp's get placed back in the queues.
310 * If someone is waiting for BUF space, wake them up. Even
311 * though we haven't freed the kva space yet, the waiting
312 * process will be able to now.
315 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
316 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
317 wakeup(&needsbuffer);
323 * runningbufwakeup() - in-progress I/O accounting.
327 runningbufwakeup(struct buf *bp)
330 if (bp->b_runningbufspace) {
331 atomic_subtract_int(&runningbufspace, bp->b_runningbufspace);
332 bp->b_runningbufspace = 0;
333 mtx_lock(&rbreqlock);
334 if (runningbufreq && runningbufspace <= lorunningspace) {
336 wakeup(&runningbufreq);
338 mtx_unlock(&rbreqlock);
345 * Called when a buffer has been added to one of the free queues to
346 * account for the buffer and to wakeup anyone waiting for free buffers.
347 * This typically occurs when large amounts of metadata are being handled
348 * by the buffer cache ( else buffer space runs out first, usually ).
355 atomic_add_int(&numfreebuffers, 1);
358 needsbuffer &= ~VFS_BIO_NEED_ANY;
359 if (numfreebuffers >= hifreebuffers)
360 needsbuffer &= ~VFS_BIO_NEED_FREE;
361 wakeup(&needsbuffer);
367 * waitrunningbufspace()
369 * runningbufspace is a measure of the amount of I/O currently
370 * running. This routine is used in async-write situations to
371 * prevent creating huge backups of pending writes to a device.
372 * Only asynchronous writes are governed by this function.
374 * Reads will adjust runningbufspace, but will not block based on it.
375 * The read load has a side effect of reducing the allowed write load.
377 * This does NOT turn an async write into a sync write. It waits
378 * for earlier writes to complete and generally returns before the
379 * caller's write has reached the device.
382 waitrunningbufspace(void)
385 mtx_lock(&rbreqlock);
386 while (runningbufspace > hirunningspace) {
388 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
390 mtx_unlock(&rbreqlock);
395 * vfs_buf_test_cache:
397 * Called when a buffer is extended. This function clears the B_CACHE
398 * bit if the newly extended portion of the buffer does not contain
403 vfs_buf_test_cache(struct buf *bp,
404 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
408 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
409 if (bp->b_flags & B_CACHE) {
410 int base = (foff + off) & PAGE_MASK;
411 if (vm_page_is_valid(m, base, size) == 0)
412 bp->b_flags &= ~B_CACHE;
416 /* Wake up the buffer deamon if necessary */
419 bd_wakeup(int dirtybuflevel)
423 if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
431 * bd_speedup - speedup the buffer cache flushing code
443 * Calculating buffer cache scaling values and reserve space for buffer
444 * headers. This is called during low level kernel initialization and
445 * may be called more then once. We CANNOT write to the memory area
446 * being reserved at this time.
449 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
453 * physmem_est is in pages. Convert it to kilobytes (assumes
454 * PAGE_SIZE is >= 1K)
456 physmem_est = physmem_est * (PAGE_SIZE / 1024);
459 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
460 * For the first 64MB of ram nominally allocate sufficient buffers to
461 * cover 1/4 of our ram. Beyond the first 64MB allocate additional
462 * buffers to cover 1/20 of our ram over 64MB. When auto-sizing
463 * the buffer cache we limit the eventual kva reservation to
466 * factor represents the 1/4 x ram conversion.
469 int factor = 4 * BKVASIZE / 1024;
472 if (physmem_est > 4096)
473 nbuf += min((physmem_est - 4096) / factor,
475 if (physmem_est > 65536)
476 nbuf += (physmem_est - 65536) * 2 / (factor * 5);
478 if (maxbcache && nbuf > maxbcache / BKVASIZE)
479 nbuf = maxbcache / BKVASIZE;
484 * Do not allow the buffer_map to be more then 1/2 the size of the
487 if (nbuf > (kernel_map->max_offset - kernel_map->min_offset) /
489 nbuf = (kernel_map->max_offset - kernel_map->min_offset) /
491 printf("Warning: nbufs capped at %d\n", nbuf);
496 * swbufs are used as temporary holders for I/O, such as paging I/O.
497 * We have no less then 16 and no more then 256.
499 nswbuf = max(min(nbuf/4, 256), 16);
501 if (nswbuf < NSWBUF_MIN)
509 * Reserve space for the buffer cache buffers
512 v = (caddr_t)(swbuf + nswbuf);
514 v = (caddr_t)(buf + nbuf);
519 /* Initialize the buffer subsystem. Called before use of any buffers. */
526 mtx_init(&bqlock, "buf queue lock", NULL, MTX_DEF);
527 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
528 mtx_init(&nblock, "needsbuffer lock", NULL, MTX_DEF);
529 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
530 mtx_init(&bdonelock, "bdone lock", NULL, MTX_DEF);
531 mtx_init(&bpinlock, "bpin lock", NULL, MTX_DEF);
533 /* next, make a null set of free lists */
534 for (i = 0; i < BUFFER_QUEUES; i++)
535 TAILQ_INIT(&bufqueues[i]);
537 /* finally, initialize each buffer header and stick on empty q */
538 for (i = 0; i < nbuf; i++) {
540 bzero(bp, sizeof *bp);
541 bp->b_flags = B_INVAL; /* we're just an empty header */
542 bp->b_rcred = NOCRED;
543 bp->b_wcred = NOCRED;
544 bp->b_qindex = QUEUE_EMPTY;
547 LIST_INIT(&bp->b_dep);
549 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
553 * maxbufspace is the absolute maximum amount of buffer space we are
554 * allowed to reserve in KVM and in real terms. The absolute maximum
555 * is nominally used by buf_daemon. hibufspace is the nominal maximum
556 * used by most other processes. The differential is required to
557 * ensure that buf_daemon is able to run when other processes might
558 * be blocked waiting for buffer space.
560 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
561 * this may result in KVM fragmentation which is not handled optimally
564 maxbufspace = nbuf * BKVASIZE;
565 hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
566 lobufspace = hibufspace - MAXBSIZE;
568 lorunningspace = 512 * 1024;
569 hirunningspace = 1024 * 1024;
572 * Limit the amount of malloc memory since it is wired permanently into
573 * the kernel space. Even though this is accounted for in the buffer
574 * allocation, we don't want the malloced region to grow uncontrolled.
575 * The malloc scheme improves memory utilization significantly on average
576 * (small) directories.
578 maxbufmallocspace = hibufspace / 20;
581 * Reduce the chance of a deadlock occuring by limiting the number
582 * of delayed-write dirty buffers we allow to stack up.
584 hidirtybuffers = nbuf / 4 + 20;
585 dirtybufthresh = hidirtybuffers * 9 / 10;
588 * To support extreme low-memory systems, make sure hidirtybuffers cannot
589 * eat up all available buffer space. This occurs when our minimum cannot
590 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
591 * BKVASIZE'd (8K) buffers.
593 while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
594 hidirtybuffers >>= 1;
596 lodirtybuffers = hidirtybuffers / 2;
599 * Try to keep the number of free buffers in the specified range,
600 * and give special processes (e.g. like buf_daemon) access to an
603 lofreebuffers = nbuf / 18 + 5;
604 hifreebuffers = 2 * lofreebuffers;
605 numfreebuffers = nbuf;
608 * Maximum number of async ops initiated per buf_daemon loop. This is
609 * somewhat of a hack at the moment, we really need to limit ourselves
610 * based on the number of bytes of I/O in-transit that were initiated
614 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
615 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
619 * bfreekva() - free the kva allocation for a buffer.
621 * Since this call frees up buffer space, we call bufspacewakeup().
624 bfreekva(struct buf *bp)
628 atomic_add_int(&buffreekvacnt, 1);
629 atomic_subtract_int(&bufspace, bp->b_kvasize);
630 vm_map_lock(buffer_map);
631 vm_map_delete(buffer_map,
632 (vm_offset_t) bp->b_kvabase,
633 (vm_offset_t) bp->b_kvabase + bp->b_kvasize
635 vm_map_unlock(buffer_map);
644 * Mark the buffer for removal from the appropriate free list in brelse.
648 bremfree(struct buf *bp)
651 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
652 KASSERT(BUF_REFCNT(bp), ("bremfree: buf must be locked."));
653 KASSERT((bp->b_flags & B_REMFREE) == 0,
654 ("bremfree: buffer %p already marked for delayed removal.", bp));
655 KASSERT(bp->b_qindex != QUEUE_NONE,
656 ("bremfree: buffer %p not on a queue.", bp));
658 bp->b_flags |= B_REMFREE;
659 /* Fixup numfreebuffers count. */
660 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)
661 atomic_subtract_int(&numfreebuffers, 1);
667 * Force an immediate removal from a free list. Used only in nfs when
668 * it abuses the b_freelist pointer.
671 bremfreef(struct buf *bp)
681 * Removes a buffer from the free list, must be called with the
685 bremfreel(struct buf *bp)
687 CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
688 bp, bp->b_vp, bp->b_flags);
689 KASSERT(BUF_REFCNT(bp), ("bremfreel: buffer %p not locked.", bp));
690 KASSERT(bp->b_qindex != QUEUE_NONE,
691 ("bremfreel: buffer %p not on a queue.", bp));
692 mtx_assert(&bqlock, MA_OWNED);
694 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
695 bp->b_qindex = QUEUE_NONE;
697 * If this was a delayed bremfree() we only need to remove the buffer
698 * from the queue and return the stats are already done.
700 if (bp->b_flags & B_REMFREE) {
701 bp->b_flags &= ~B_REMFREE;
705 * Fixup numfreebuffers count. If the buffer is invalid or not
706 * delayed-write, the buffer was free and we must decrement
709 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)
710 atomic_subtract_int(&numfreebuffers, 1);
715 * Get a buffer with the specified data. Look in the cache first. We
716 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
717 * is set, the buffer is valid and we do not have to do anything ( see
718 * getblk() ). This is really just a special case of breadn().
721 bread(struct vnode * vp, daddr_t blkno, int size, struct ucred * cred,
725 return (breadn(vp, blkno, size, 0, 0, 0, cred, bpp));
729 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must
730 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
731 * the buffer is valid and we do not have to do anything.
734 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
735 int cnt, struct ucred * cred)
740 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
741 if (inmem(vp, *rablkno))
743 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
745 if ((rabp->b_flags & B_CACHE) == 0) {
746 if (curthread != PCPU_GET(idlethread))
747 curthread->td_proc->p_stats->p_ru.ru_inblock++;
748 rabp->b_flags |= B_ASYNC;
749 rabp->b_flags &= ~B_INVAL;
750 rabp->b_ioflags &= ~BIO_ERROR;
751 rabp->b_iocmd = BIO_READ;
752 if (rabp->b_rcred == NOCRED && cred != NOCRED)
753 rabp->b_rcred = crhold(cred);
754 vfs_busy_pages(rabp, 0);
756 rabp->b_iooffset = dbtob(rabp->b_blkno);
765 * Operates like bread, but also starts asynchronous I/O on
769 breadn(struct vnode * vp, daddr_t blkno, int size,
770 daddr_t * rablkno, int *rabsize,
771 int cnt, struct ucred * cred, struct buf **bpp)
774 int rv = 0, readwait = 0;
776 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
777 *bpp = bp = getblk(vp, blkno, size, 0, 0, 0);
779 /* if not found in cache, do some I/O */
780 if ((bp->b_flags & B_CACHE) == 0) {
781 if (curthread != PCPU_GET(idlethread))
782 curthread->td_proc->p_stats->p_ru.ru_inblock++;
783 bp->b_iocmd = BIO_READ;
784 bp->b_flags &= ~B_INVAL;
785 bp->b_ioflags &= ~BIO_ERROR;
786 if (bp->b_rcred == NOCRED && cred != NOCRED)
787 bp->b_rcred = crhold(cred);
788 vfs_busy_pages(bp, 0);
789 bp->b_iooffset = dbtob(bp->b_blkno);
794 breada(vp, rablkno, rabsize, cnt, cred);
803 * Write, release buffer on completion. (Done by iodone
804 * if async). Do not bother writing anything if the buffer
807 * Note that we set B_CACHE here, indicating that buffer is
808 * fully valid and thus cacheable. This is true even of NFS
809 * now so we set it generally. This could be set either here
810 * or in biodone() since the I/O is synchronous. We put it
814 bufwrite(struct buf *bp)
818 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
819 if (bp->b_flags & B_INVAL) {
824 oldflags = bp->b_flags;
826 if (BUF_REFCNT(bp) == 0)
827 panic("bufwrite: buffer is not busy???");
829 if (bp->b_pin_count > 0)
832 KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
833 ("FFS background buffer should not get here %p", bp));
835 /* Mark the buffer clean */
838 bp->b_flags &= ~B_DONE;
839 bp->b_ioflags &= ~BIO_ERROR;
840 bp->b_flags |= B_CACHE;
841 bp->b_iocmd = BIO_WRITE;
843 bufobj_wref(bp->b_bufobj);
844 vfs_busy_pages(bp, 1);
847 * Normal bwrites pipeline writes
849 bp->b_runningbufspace = bp->b_bufsize;
850 atomic_add_int(&runningbufspace, bp->b_runningbufspace);
852 if (curthread != PCPU_GET(idlethread))
853 curthread->td_proc->p_stats->p_ru.ru_oublock++;
854 if (oldflags & B_ASYNC)
856 bp->b_iooffset = dbtob(bp->b_blkno);
859 if ((oldflags & B_ASYNC) == 0) {
860 int rtval = bufwait(bp);
865 * don't allow the async write to saturate the I/O
866 * system. We will not deadlock here because
867 * we are blocking waiting for I/O that is already in-progress
868 * to complete. We do not block here if it is the update
869 * or syncer daemon trying to clean up as that can lead
872 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0)
873 waitrunningbufspace();
880 * Delayed write. (Buffer is marked dirty). Do not bother writing
881 * anything if the buffer is marked invalid.
883 * Note that since the buffer must be completely valid, we can safely
884 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
885 * biodone() in order to prevent getblk from writing the buffer
889 bdwrite(struct buf *bp)
891 struct thread *td = curthread;
896 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
897 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
898 KASSERT(BUF_REFCNT(bp) != 0, ("bdwrite: buffer is not busy"));
900 if (bp->b_flags & B_INVAL) {
906 * If we have too many dirty buffers, don't create any more.
907 * If we are wildly over our limit, then force a complete
908 * cleanup. Otherwise, just keep the situation from getting
909 * out of control. Note that we have to avoid a recursive
910 * disaster and not try to clean up after our own cleanup!
914 if ((td->td_pflags & TDP_COWINPROGRESS) == 0) {
916 if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
918 (void) VOP_FSYNC(vp, MNT_NOWAIT, td);
920 } else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
922 * Try to find a buffer to flush.
924 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
925 if ((nbp->b_vflags & BV_BKGRDINPROG) ||
927 LK_EXCLUSIVE | LK_NOWAIT, NULL))
930 panic("bdwrite: found ourselves");
932 /* Don't countdeps with the bo lock held. */
933 if (buf_countdeps(nbp, 0)) {
938 if (nbp->b_flags & B_CLUSTEROK) {
944 dirtybufferflushes++;
956 * Set B_CACHE, indicating that the buffer is fully valid. This is
957 * true even of NFS now.
959 bp->b_flags |= B_CACHE;
962 * This bmap keeps the system from needing to do the bmap later,
963 * perhaps when the system is attempting to do a sync. Since it
964 * is likely that the indirect block -- or whatever other datastructure
965 * that the filesystem needs is still in memory now, it is a good
966 * thing to do this. Note also, that if the pageout daemon is
967 * requesting a sync -- there might not be enough memory to do
968 * the bmap then... So, this is important to do.
970 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
971 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
975 * Set the *dirty* buffer range based upon the VM system dirty pages.
980 * We need to do this here to satisfy the vnode_pager and the
981 * pageout daemon, so that it thinks that the pages have been
982 * "cleaned". Note that since the pages are in a delayed write
983 * buffer -- the VFS layer "will" see that the pages get written
984 * out on the next sync, or perhaps the cluster will be completed.
990 * Wakeup the buffer flushing daemon if we have a lot of dirty
991 * buffers (midpoint between our recovery point and our stall
994 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
997 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
998 * due to the softdep code.
1005 * Turn buffer into delayed write request. We must clear BIO_READ and
1006 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
1007 * itself to properly update it in the dirty/clean lists. We mark it
1008 * B_DONE to ensure that any asynchronization of the buffer properly
1009 * clears B_DONE ( else a panic will occur later ).
1011 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1012 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
1013 * should only be called if the buffer is known-good.
1015 * Since the buffer is not on a queue, we do not update the numfreebuffers
1018 * The buffer must be on QUEUE_NONE.
1021 bdirty(struct buf *bp)
1024 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
1025 bp, bp->b_vp, bp->b_flags);
1026 KASSERT(BUF_REFCNT(bp) == 1, ("bdirty: bp %p not locked",bp));
1027 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1028 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1029 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1030 bp->b_flags &= ~(B_RELBUF);
1031 bp->b_iocmd = BIO_WRITE;
1033 if ((bp->b_flags & B_DELWRI) == 0) {
1034 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
1036 atomic_add_int(&numdirtybuffers, 1);
1037 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1044 * Clear B_DELWRI for buffer.
1046 * Since the buffer is not on a queue, we do not update the numfreebuffers
1049 * The buffer must be on QUEUE_NONE.
1053 bundirty(struct buf *bp)
1056 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1057 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1058 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1059 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1060 KASSERT(BUF_REFCNT(bp) == 1, ("bundirty: bp %p not locked",bp));
1062 if (bp->b_flags & B_DELWRI) {
1063 bp->b_flags &= ~B_DELWRI;
1065 atomic_subtract_int(&numdirtybuffers, 1);
1066 numdirtywakeup(lodirtybuffers);
1069 * Since it is now being written, we can clear its deferred write flag.
1071 bp->b_flags &= ~B_DEFERRED;
1077 * Asynchronous write. Start output on a buffer, but do not wait for
1078 * it to complete. The buffer is released when the output completes.
1080 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1081 * B_INVAL buffers. Not us.
1084 bawrite(struct buf *bp)
1087 bp->b_flags |= B_ASYNC;
1094 * Called prior to the locking of any vnodes when we are expecting to
1095 * write. We do not want to starve the buffer cache with too many
1096 * dirty buffers so we block here. By blocking prior to the locking
1097 * of any vnodes we attempt to avoid the situation where a locked vnode
1098 * prevents the various system daemons from flushing related buffers.
1105 if (numdirtybuffers >= hidirtybuffers) {
1107 while (numdirtybuffers >= hidirtybuffers) {
1109 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
1110 msleep(&needsbuffer, &nblock,
1111 (PRIBIO + 4), "flswai", 0);
1113 mtx_unlock(&nblock);
1118 * Return true if we have too many dirty buffers.
1121 buf_dirty_count_severe(void)
1124 return(numdirtybuffers >= hidirtybuffers);
1130 * Release a busy buffer and, if requested, free its resources. The
1131 * buffer will be stashed in the appropriate bufqueue[] allowing it
1132 * to be accessed later as a cache entity or reused for other purposes.
1135 brelse(struct buf *bp)
1137 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
1138 bp, bp->b_vp, bp->b_flags);
1139 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1140 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1142 if (bp->b_flags & B_MANAGED) {
1147 if (bp->b_iocmd == BIO_WRITE &&
1148 (bp->b_ioflags & BIO_ERROR) &&
1149 !(bp->b_flags & B_INVAL)) {
1151 * Failed write, redirty. Must clear BIO_ERROR to prevent
1152 * pages from being scrapped. If B_INVAL is set then
1153 * this case is not run and the next case is run to
1154 * destroy the buffer. B_INVAL can occur if the buffer
1155 * is outside the range supported by the underlying device.
1157 bp->b_ioflags &= ~BIO_ERROR;
1159 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1160 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
1162 * Either a failed I/O or we were asked to free or not
1165 bp->b_flags |= B_INVAL;
1166 if (LIST_FIRST(&bp->b_dep) != NULL)
1168 if (bp->b_flags & B_DELWRI) {
1169 atomic_subtract_int(&numdirtybuffers, 1);
1170 numdirtywakeup(lodirtybuffers);
1172 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1173 if ((bp->b_flags & B_VMIO) == 0) {
1182 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1183 * is called with B_DELWRI set, the underlying pages may wind up
1184 * getting freed causing a previous write (bdwrite()) to get 'lost'
1185 * because pages associated with a B_DELWRI bp are marked clean.
1187 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1188 * if B_DELWRI is set.
1190 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1191 * on pages to return pages to the VM page queues.
1193 if (bp->b_flags & B_DELWRI)
1194 bp->b_flags &= ~B_RELBUF;
1195 else if (vm_page_count_severe()) {
1197 * XXX This lock may not be necessary since BKGRDINPROG
1198 * cannot be set while we hold the buf lock, it can only be
1199 * cleared if it is already pending.
1202 BO_LOCK(bp->b_bufobj);
1203 if (!(bp->b_vflags & BV_BKGRDINPROG))
1204 bp->b_flags |= B_RELBUF;
1205 BO_UNLOCK(bp->b_bufobj);
1207 bp->b_flags |= B_RELBUF;
1211 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1212 * constituted, not even NFS buffers now. Two flags effect this. If
1213 * B_INVAL, the struct buf is invalidated but the VM object is kept
1214 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1216 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1217 * invalidated. BIO_ERROR cannot be set for a failed write unless the
1218 * buffer is also B_INVAL because it hits the re-dirtying code above.
1220 * Normally we can do this whether a buffer is B_DELWRI or not. If
1221 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1222 * the commit state and we cannot afford to lose the buffer. If the
1223 * buffer has a background write in progress, we need to keep it
1224 * around to prevent it from being reconstituted and starting a second
1227 if ((bp->b_flags & B_VMIO)
1228 && !(bp->b_vp->v_mount != NULL &&
1229 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1230 !vn_isdisk(bp->b_vp, NULL) &&
1231 (bp->b_flags & B_DELWRI))
1240 obj = bp->b_bufobj->bo_object;
1243 * Get the base offset and length of the buffer. Note that
1244 * in the VMIO case if the buffer block size is not
1245 * page-aligned then b_data pointer may not be page-aligned.
1246 * But our b_pages[] array *IS* page aligned.
1248 * block sizes less then DEV_BSIZE (usually 512) are not
1249 * supported due to the page granularity bits (m->valid,
1250 * m->dirty, etc...).
1252 * See man buf(9) for more information
1254 resid = bp->b_bufsize;
1255 foff = bp->b_offset;
1256 VM_OBJECT_LOCK(obj);
1257 for (i = 0; i < bp->b_npages; i++) {
1263 * If we hit a bogus page, fixup *all* the bogus pages
1266 if (m == bogus_page) {
1267 poff = OFF_TO_IDX(bp->b_offset);
1270 for (j = i; j < bp->b_npages; j++) {
1272 mtmp = bp->b_pages[j];
1273 if (mtmp == bogus_page) {
1274 mtmp = vm_page_lookup(obj, poff + j);
1276 panic("brelse: page missing\n");
1278 bp->b_pages[j] = mtmp;
1282 if ((bp->b_flags & B_INVAL) == 0) {
1284 trunc_page((vm_offset_t)bp->b_data),
1285 bp->b_pages, bp->b_npages);
1289 if ((bp->b_flags & B_NOCACHE) ||
1290 (bp->b_ioflags & BIO_ERROR)) {
1291 int poffset = foff & PAGE_MASK;
1292 int presid = resid > (PAGE_SIZE - poffset) ?
1293 (PAGE_SIZE - poffset) : resid;
1295 KASSERT(presid >= 0, ("brelse: extra page"));
1296 vm_page_lock_queues();
1297 vm_page_set_invalid(m, poffset, presid);
1298 vm_page_unlock_queues();
1300 printf("avoided corruption bug in bogus_page/brelse code\n");
1302 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1303 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1305 VM_OBJECT_UNLOCK(obj);
1306 if (bp->b_flags & (B_INVAL | B_RELBUF))
1307 vfs_vmio_release(bp);
1309 } else if (bp->b_flags & B_VMIO) {
1311 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1312 vfs_vmio_release(bp);
1315 } else if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0) {
1316 if (bp->b_bufsize != 0)
1318 if (bp->b_vp != NULL)
1322 if (BUF_REFCNT(bp) > 1) {
1323 /* do not release to free list */
1330 /* Handle delayed bremfree() processing. */
1331 if (bp->b_flags & B_REMFREE)
1333 if (bp->b_qindex != QUEUE_NONE)
1334 panic("brelse: free buffer onto another queue???");
1336 /* buffers with no memory */
1337 if (bp->b_bufsize == 0) {
1338 bp->b_flags |= B_INVAL;
1339 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1340 if (bp->b_vflags & BV_BKGRDINPROG)
1341 panic("losing buffer 1");
1342 if (bp->b_kvasize) {
1343 bp->b_qindex = QUEUE_EMPTYKVA;
1345 bp->b_qindex = QUEUE_EMPTY;
1347 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1348 /* buffers with junk contents */
1349 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1350 (bp->b_ioflags & BIO_ERROR)) {
1351 bp->b_flags |= B_INVAL;
1352 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1353 if (bp->b_vflags & BV_BKGRDINPROG)
1354 panic("losing buffer 2");
1355 bp->b_qindex = QUEUE_CLEAN;
1356 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1357 /* remaining buffers */
1359 if (bp->b_flags & B_DELWRI)
1360 bp->b_qindex = QUEUE_DIRTY;
1362 bp->b_qindex = QUEUE_CLEAN;
1363 if (bp->b_flags & B_AGE)
1364 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1366 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1368 mtx_unlock(&bqlock);
1371 * If B_INVAL and B_DELWRI is set, clear B_DELWRI. We have already
1372 * placed the buffer on the correct queue. We must also disassociate
1373 * the device and vnode for a B_INVAL buffer so gbincore() doesn't
1376 if (bp->b_flags & B_INVAL) {
1377 if (bp->b_flags & B_DELWRI)
1384 * Fixup numfreebuffers count. The bp is on an appropriate queue
1385 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1386 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1387 * if B_INVAL is set ).
1390 if (!(bp->b_flags & B_DELWRI))
1394 * Something we can maybe free or reuse
1396 if (bp->b_bufsize || bp->b_kvasize)
1399 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1400 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1401 panic("brelse: not dirty");
1407 * Release a buffer back to the appropriate queue but do not try to free
1408 * it. The buffer is expected to be used again soon.
1410 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1411 * biodone() to requeue an async I/O on completion. It is also used when
1412 * known good buffers need to be requeued but we think we may need the data
1415 * XXX we should be able to leave the B_RELBUF hint set on completion.
1418 bqrelse(struct buf *bp)
1420 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1421 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1422 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1424 if (BUF_REFCNT(bp) > 1) {
1425 /* do not release to free list */
1430 if (bp->b_flags & B_MANAGED) {
1431 if (bp->b_flags & B_REMFREE) {
1434 mtx_unlock(&bqlock);
1436 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1442 /* Handle delayed bremfree() processing. */
1443 if (bp->b_flags & B_REMFREE)
1445 if (bp->b_qindex != QUEUE_NONE)
1446 panic("bqrelse: free buffer onto another queue???");
1447 /* buffers with stale but valid contents */
1448 if (bp->b_flags & B_DELWRI) {
1449 bp->b_qindex = QUEUE_DIRTY;
1450 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1453 * XXX This lock may not be necessary since BKGRDINPROG
1454 * cannot be set while we hold the buf lock, it can only be
1455 * cleared if it is already pending.
1457 BO_LOCK(bp->b_bufobj);
1458 if (!vm_page_count_severe() || bp->b_vflags & BV_BKGRDINPROG) {
1459 BO_UNLOCK(bp->b_bufobj);
1460 bp->b_qindex = QUEUE_CLEAN;
1461 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp,
1465 * We are too low on memory, we have to try to free
1466 * the buffer (most importantly: the wired pages
1467 * making up its backing store) *now*.
1469 BO_UNLOCK(bp->b_bufobj);
1470 mtx_unlock(&bqlock);
1475 mtx_unlock(&bqlock);
1477 if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))
1481 * Something we can maybe free or reuse.
1483 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1486 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1487 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1488 panic("bqrelse: not dirty");
1493 /* Give pages used by the bp back to the VM system (where possible) */
1495 vfs_vmio_release(struct buf *bp)
1500 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
1501 vm_page_lock_queues();
1502 for (i = 0; i < bp->b_npages; i++) {
1504 bp->b_pages[i] = NULL;
1506 * In order to keep page LRU ordering consistent, put
1507 * everything on the inactive queue.
1509 vm_page_unwire(m, 0);
1511 * We don't mess with busy pages, it is
1512 * the responsibility of the process that
1513 * busied the pages to deal with them.
1515 if ((m->flags & PG_BUSY) || (m->busy != 0))
1518 if (m->wire_count == 0) {
1520 * Might as well free the page if we can and it has
1521 * no valid data. We also free the page if the
1522 * buffer was used for direct I/O
1524 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1525 m->hold_count == 0) {
1527 } else if (bp->b_flags & B_DIRECT) {
1528 vm_page_try_to_free(m);
1529 } else if (vm_page_count_severe()) {
1530 vm_page_try_to_cache(m);
1534 vm_page_unlock_queues();
1535 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
1536 pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
1538 if (bp->b_bufsize) {
1543 bp->b_flags &= ~B_VMIO;
1549 * Check to see if a block at a particular lbn is available for a clustered
1553 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1560 /* If the buf isn't in core skip it */
1561 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1564 /* If the buf is busy we don't want to wait for it */
1565 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1568 /* Only cluster with valid clusterable delayed write buffers */
1569 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1570 (B_DELWRI | B_CLUSTEROK))
1573 if (bpa->b_bufsize != size)
1577 * Check to see if it is in the expected place on disk and that the
1578 * block has been mapped.
1580 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1590 * Implement clustered async writes for clearing out B_DELWRI buffers.
1591 * This is much better then the old way of writing only one buffer at
1592 * a time. Note that we may not be presented with the buffers in the
1593 * correct order, so we search for the cluster in both directions.
1596 vfs_bio_awrite(struct buf *bp)
1600 daddr_t lblkno = bp->b_lblkno;
1601 struct vnode *vp = bp->b_vp;
1608 * right now we support clustered writing only to regular files. If
1609 * we find a clusterable block we could be in the middle of a cluster
1610 * rather then at the beginning.
1612 if ((vp->v_type == VREG) &&
1613 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1614 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1616 size = vp->v_mount->mnt_stat.f_iosize;
1617 maxcl = MAXPHYS / size;
1620 for (i = 1; i < maxcl; i++)
1621 if (vfs_bio_clcheck(vp, size, lblkno + i,
1622 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1625 for (j = 1; i + j <= maxcl && j <= lblkno; j++)
1626 if (vfs_bio_clcheck(vp, size, lblkno - j,
1627 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
1634 * this is a possible cluster write
1638 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1643 bp->b_flags |= B_ASYNC;
1645 * default (old) behavior, writing out only one block
1647 * XXX returns b_bufsize instead of b_bcount for nwritten?
1649 nwritten = bp->b_bufsize;
1658 * Find and initialize a new buffer header, freeing up existing buffers
1659 * in the bufqueues as necessary. The new buffer is returned locked.
1661 * Important: B_INVAL is not set. If the caller wishes to throw the
1662 * buffer away, the caller must set B_INVAL prior to calling brelse().
1665 * We have insufficient buffer headers
1666 * We have insufficient buffer space
1667 * buffer_map is too fragmented ( space reservation fails )
1668 * If we have to flush dirty buffers ( but we try to avoid this )
1670 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1671 * Instead we ask the buf daemon to do it for us. We attempt to
1672 * avoid piecemeal wakeups of the pageout daemon.
1676 getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1682 static int flushingbufs;
1685 * We can't afford to block since we might be holding a vnode lock,
1686 * which may prevent system daemons from running. We deal with
1687 * low-memory situations by proactively returning memory and running
1688 * async I/O rather then sync I/O.
1691 atomic_add_int(&getnewbufcalls, 1);
1692 atomic_subtract_int(&getnewbufrestarts, 1);
1694 atomic_add_int(&getnewbufrestarts, 1);
1697 * Setup for scan. If we do not have enough free buffers,
1698 * we setup a degenerate case that immediately fails. Note
1699 * that if we are specially marked process, we are allowed to
1700 * dip into our reserves.
1702 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1704 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1705 * However, there are a number of cases (defragging, reusing, ...)
1706 * where we cannot backup.
1709 nqindex = QUEUE_EMPTYKVA;
1710 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1714 * If no EMPTYKVA buffers and we are either
1715 * defragging or reusing, locate a CLEAN buffer
1716 * to free or reuse. If bufspace useage is low
1717 * skip this step so we can allocate a new buffer.
1719 if (defrag || bufspace >= lobufspace) {
1720 nqindex = QUEUE_CLEAN;
1721 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1725 * If we could not find or were not allowed to reuse a
1726 * CLEAN buffer, check to see if it is ok to use an EMPTY
1727 * buffer. We can only use an EMPTY buffer if allocating
1728 * its KVA would not otherwise run us out of buffer space.
1730 if (nbp == NULL && defrag == 0 &&
1731 bufspace + maxsize < hibufspace) {
1732 nqindex = QUEUE_EMPTY;
1733 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1738 * Run scan, possibly freeing data and/or kva mappings on the fly
1742 while ((bp = nbp) != NULL) {
1743 int qindex = nqindex;
1746 * Calculate next bp ( we can only use it if we do not block
1747 * or do other fancy things ).
1749 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1752 nqindex = QUEUE_EMPTYKVA;
1753 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1756 case QUEUE_EMPTYKVA:
1757 nqindex = QUEUE_CLEAN;
1758 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1769 * If we are defragging then we need a buffer with
1770 * b_kvasize != 0. XXX this situation should no longer
1771 * occur, if defrag is non-zero the buffer's b_kvasize
1772 * should also be non-zero at this point. XXX
1774 if (defrag && bp->b_kvasize == 0) {
1775 printf("Warning: defrag empty buffer %p\n", bp);
1780 * Start freeing the bp. This is somewhat involved. nbp
1781 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1783 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1786 BO_LOCK(bp->b_bufobj);
1787 if (bp->b_vflags & BV_BKGRDINPROG) {
1788 BO_UNLOCK(bp->b_bufobj);
1792 BO_UNLOCK(bp->b_bufobj);
1795 "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
1796 "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
1797 bp->b_kvasize, bp->b_bufsize, qindex);
1802 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1805 * Note: we no longer distinguish between VMIO and non-VMIO
1809 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1812 mtx_unlock(&bqlock);
1814 if (qindex == QUEUE_CLEAN) {
1815 if (bp->b_flags & B_VMIO) {
1816 bp->b_flags &= ~B_ASYNC;
1817 vfs_vmio_release(bp);
1824 * NOTE: nbp is now entirely invalid. We can only restart
1825 * the scan from this point on.
1827 * Get the rest of the buffer freed up. b_kva* is still
1828 * valid after this operation.
1831 if (bp->b_rcred != NOCRED) {
1832 crfree(bp->b_rcred);
1833 bp->b_rcred = NOCRED;
1835 if (bp->b_wcred != NOCRED) {
1836 crfree(bp->b_wcred);
1837 bp->b_wcred = NOCRED;
1839 if (LIST_FIRST(&bp->b_dep) != NULL)
1841 if (bp->b_vflags & BV_BKGRDINPROG)
1842 panic("losing buffer 3");
1843 KASSERT(bp->b_vp == NULL,
1844 ("bp: %p still has vnode %p. qindex: %d",
1845 bp, bp->b_vp, qindex));
1846 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
1847 ("bp: %p still on a buffer list. xflags %X",
1858 bp->b_blkno = bp->b_lblkno = 0;
1859 bp->b_offset = NOOFFSET;
1865 bp->b_dirtyoff = bp->b_dirtyend = 0;
1866 bp->b_bufobj = NULL;
1867 bp->b_pin_count = 0;
1868 bp->b_fsprivate1 = NULL;
1869 bp->b_fsprivate2 = NULL;
1870 bp->b_fsprivate3 = NULL;
1872 LIST_INIT(&bp->b_dep);
1875 * If we are defragging then free the buffer.
1878 bp->b_flags |= B_INVAL;
1886 * If we are overcomitted then recover the buffer and its
1887 * KVM space. This occurs in rare situations when multiple
1888 * processes are blocked in getnewbuf() or allocbuf().
1890 if (bufspace >= hibufspace)
1892 if (flushingbufs && bp->b_kvasize != 0) {
1893 bp->b_flags |= B_INVAL;
1898 if (bufspace < lobufspace)
1904 * If we exhausted our list, sleep as appropriate. We may have to
1905 * wakeup various daemons and write out some dirty buffers.
1907 * Generally we are sleeping due to insufficient buffer space.
1915 flags = VFS_BIO_NEED_BUFSPACE;
1917 } else if (bufspace >= hibufspace) {
1919 flags = VFS_BIO_NEED_BUFSPACE;
1922 flags = VFS_BIO_NEED_ANY;
1925 needsbuffer |= flags;
1926 mtx_unlock(&nblock);
1927 mtx_unlock(&bqlock);
1929 bd_speedup(); /* heeeelp */
1932 while (needsbuffer & flags) {
1933 if (msleep(&needsbuffer, &nblock,
1934 (PRIBIO + 4) | slpflag, waitmsg, slptimeo)) {
1935 mtx_unlock(&nblock);
1939 mtx_unlock(&nblock);
1942 * We finally have a valid bp. We aren't quite out of the
1943 * woods, we still have to reserve kva space. In order
1944 * to keep fragmentation sane we only allocate kva in
1947 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1949 if (maxsize != bp->b_kvasize) {
1950 vm_offset_t addr = 0;
1954 vm_map_lock(buffer_map);
1955 if (vm_map_findspace(buffer_map,
1956 vm_map_min(buffer_map), maxsize, &addr)) {
1958 * Uh oh. Buffer map is to fragmented. We
1959 * must defragment the map.
1961 atomic_add_int(&bufdefragcnt, 1);
1962 vm_map_unlock(buffer_map);
1964 bp->b_flags |= B_INVAL;
1969 vm_map_insert(buffer_map, NULL, 0,
1970 addr, addr + maxsize,
1971 VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
1973 bp->b_kvabase = (caddr_t) addr;
1974 bp->b_kvasize = maxsize;
1975 atomic_add_int(&bufspace, bp->b_kvasize);
1976 atomic_add_int(&bufreusecnt, 1);
1978 vm_map_unlock(buffer_map);
1980 bp->b_saveaddr = bp->b_kvabase;
1981 bp->b_data = bp->b_saveaddr;
1989 * buffer flushing daemon. Buffers are normally flushed by the
1990 * update daemon but if it cannot keep up this process starts to
1991 * take the load in an attempt to prevent getnewbuf() from blocking.
1994 static struct kproc_desc buf_kp = {
1999 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
2007 * This process needs to be suspended prior to shutdown sync.
2009 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2013 * This process is allowed to take the buffer cache to the limit
2015 curthread->td_pflags |= TDP_NORUNNINGBUF;
2019 mtx_unlock(&bdlock);
2021 kthread_suspend_check(bufdaemonproc);
2024 * Do the flush. Limit the amount of in-transit I/O we
2025 * allow to build up, otherwise we would completely saturate
2026 * the I/O system. Wakeup any waiting processes before we
2027 * normally would so they can run in parallel with our drain.
2029 while (numdirtybuffers > lodirtybuffers) {
2030 if (flushbufqueues(0) == 0) {
2032 * Could not find any buffers without rollback
2033 * dependencies, so just write the first one
2034 * in the hopes of eventually making progress.
2043 * Only clear bd_request if we have reached our low water
2044 * mark. The buf_daemon normally waits 1 second and
2045 * then incrementally flushes any dirty buffers that have
2046 * built up, within reason.
2048 * If we were unable to hit our low water mark and couldn't
2049 * find any flushable buffers, we sleep half a second.
2050 * Otherwise we loop immediately.
2053 if (numdirtybuffers <= lodirtybuffers) {
2055 * We reached our low water mark, reset the
2056 * request and sleep until we are needed again.
2057 * The sleep is just so the suspend code works.
2060 msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2063 * We couldn't find any flushable dirty buffers but
2064 * still have too many dirty buffers, we
2065 * have to sleep and try again. (rare)
2067 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2075 * Try to flush a buffer in the dirty queue. We must be careful to
2076 * free up B_INVAL buffers instead of write them, which NFS is
2077 * particularly sensitive to.
2079 static int flushwithdeps = 0;
2080 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2081 0, "Number of buffers flushed with dependecies that require rollbacks");
2084 flushbufqueues(int flushdeps)
2086 struct thread *td = curthread;
2087 struct buf sentinel;
2095 target = numdirtybuffers - lodirtybuffers;
2096 if (flushdeps && target > 2)
2101 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], &sentinel, b_freelist);
2102 while (flushed != target) {
2103 bp = TAILQ_FIRST(&bufqueues[QUEUE_DIRTY]);
2104 if (bp == &sentinel)
2106 TAILQ_REMOVE(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
2107 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
2109 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2111 if (bp->b_pin_count > 0) {
2115 BO_LOCK(bp->b_bufobj);
2116 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2117 (bp->b_flags & B_DELWRI) == 0) {
2118 BO_UNLOCK(bp->b_bufobj);
2122 BO_UNLOCK(bp->b_bufobj);
2123 if (bp->b_flags & B_INVAL) {
2125 mtx_unlock(&bqlock);
2128 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2133 if (LIST_FIRST(&bp->b_dep) != NULL && buf_countdeps(bp, 0)) {
2134 if (flushdeps == 0) {
2142 * We must hold the lock on a vnode before writing
2143 * one of its buffers. Otherwise we may confuse, or
2144 * in the case of a snapshot vnode, deadlock the
2147 * The lock order here is the reverse of the normal
2148 * of vnode followed by buf lock. This is ok because
2149 * the NOWAIT will prevent deadlock.
2152 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2156 if (vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT, td) == 0) {
2157 mtx_unlock(&bqlock);
2158 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2159 bp, bp->b_vp, bp->b_flags);
2161 vn_finished_write(mp);
2162 VOP_UNLOCK(vp, 0, td);
2163 flushwithdeps += hasdeps;
2165 waitrunningbufspace();
2166 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2170 vn_finished_write(mp);
2173 TAILQ_REMOVE(&bufqueues[QUEUE_DIRTY], &sentinel, b_freelist);
2174 mtx_unlock(&bqlock);
2179 * Check to see if a block is currently memory resident.
2182 incore(struct bufobj *bo, daddr_t blkno)
2187 bp = gbincore(bo, blkno);
2193 * Returns true if no I/O is needed to access the
2194 * associated VM object. This is like incore except
2195 * it also hunts around in the VM system for the data.
2199 inmem(struct vnode * vp, daddr_t blkno)
2202 vm_offset_t toff, tinc, size;
2206 ASSERT_VOP_LOCKED(vp, "inmem");
2208 if (incore(&vp->v_bufobj, blkno))
2210 if (vp->v_mount == NULL)
2217 if (size > vp->v_mount->mnt_stat.f_iosize)
2218 size = vp->v_mount->mnt_stat.f_iosize;
2219 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2221 VM_OBJECT_LOCK(obj);
2222 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2223 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2227 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2228 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2229 if (vm_page_is_valid(m,
2230 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2233 VM_OBJECT_UNLOCK(obj);
2237 VM_OBJECT_UNLOCK(obj);
2244 * Sets the dirty range for a buffer based on the status of the dirty
2245 * bits in the pages comprising the buffer.
2247 * The range is limited to the size of the buffer.
2249 * This routine is primarily used by NFS, but is generalized for the
2253 vfs_setdirty(struct buf *bp)
2259 * Degenerate case - empty buffer
2262 if (bp->b_bufsize == 0)
2266 * We qualify the scan for modified pages on whether the
2267 * object has been flushed yet. The OBJ_WRITEABLE flag
2268 * is not cleared simply by protecting pages off.
2271 if ((bp->b_flags & B_VMIO) == 0)
2274 object = bp->b_pages[0]->object;
2275 VM_OBJECT_LOCK(object);
2276 if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
2277 printf("Warning: object %p writeable but not mightbedirty\n", object);
2278 if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
2279 printf("Warning: object %p mightbedirty but not writeable\n", object);
2281 if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2282 vm_offset_t boffset;
2283 vm_offset_t eoffset;
2285 vm_page_lock_queues();
2287 * test the pages to see if they have been modified directly
2288 * by users through the VM system.
2290 for (i = 0; i < bp->b_npages; i++)
2291 vm_page_test_dirty(bp->b_pages[i]);
2294 * Calculate the encompassing dirty range, boffset and eoffset,
2295 * (eoffset - boffset) bytes.
2298 for (i = 0; i < bp->b_npages; i++) {
2299 if (bp->b_pages[i]->dirty)
2302 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2304 for (i = bp->b_npages - 1; i >= 0; --i) {
2305 if (bp->b_pages[i]->dirty) {
2309 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2311 vm_page_unlock_queues();
2313 * Fit it to the buffer.
2316 if (eoffset > bp->b_bcount)
2317 eoffset = bp->b_bcount;
2320 * If we have a good dirty range, merge with the existing
2324 if (boffset < eoffset) {
2325 if (bp->b_dirtyoff > boffset)
2326 bp->b_dirtyoff = boffset;
2327 if (bp->b_dirtyend < eoffset)
2328 bp->b_dirtyend = eoffset;
2331 VM_OBJECT_UNLOCK(object);
2337 * Get a block given a specified block and offset into a file/device.
2338 * The buffers B_DONE bit will be cleared on return, making it almost
2339 * ready for an I/O initiation. B_INVAL may or may not be set on
2340 * return. The caller should clear B_INVAL prior to initiating a
2343 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2344 * an existing buffer.
2346 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2347 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2348 * and then cleared based on the backing VM. If the previous buffer is
2349 * non-0-sized but invalid, B_CACHE will be cleared.
2351 * If getblk() must create a new buffer, the new buffer is returned with
2352 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2353 * case it is returned with B_INVAL clear and B_CACHE set based on the
2356 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
2357 * B_CACHE bit is clear.
2359 * What this means, basically, is that the caller should use B_CACHE to
2360 * determine whether the buffer is fully valid or not and should clear
2361 * B_INVAL prior to issuing a read. If the caller intends to validate
2362 * the buffer by loading its data area with something, the caller needs
2363 * to clear B_INVAL. If the caller does this without issuing an I/O,
2364 * the caller should set B_CACHE ( as an optimization ), else the caller
2365 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2366 * a write attempt or if it was a successfull read. If the caller
2367 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
2368 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2371 getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo,
2378 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
2379 ASSERT_VOP_LOCKED(vp, "getblk");
2380 if (size > MAXBSIZE)
2381 panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2386 * Block if we are low on buffers. Certain processes are allowed
2387 * to completely exhaust the buffer cache.
2389 * If this check ever becomes a bottleneck it may be better to
2390 * move it into the else, when gbincore() fails. At the moment
2391 * it isn't a problem.
2393 * XXX remove if 0 sections (clean this up after its proven)
2395 if (numfreebuffers == 0) {
2396 if (curthread == PCPU_GET(idlethread))
2399 needsbuffer |= VFS_BIO_NEED_ANY;
2400 mtx_unlock(&nblock);
2404 bp = gbincore(bo, blkno);
2408 * Buffer is in-core. If the buffer is not busy, it must
2411 lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
2413 if (flags & GB_LOCK_NOWAIT)
2414 lockflags |= LK_NOWAIT;
2416 error = BUF_TIMELOCK(bp, lockflags,
2417 VI_MTX(vp), "getblk", slpflag, slptimeo);
2420 * If we slept and got the lock we have to restart in case
2421 * the buffer changed identities.
2423 if (error == ENOLCK)
2425 /* We timed out or were interrupted. */
2430 * The buffer is locked. B_CACHE is cleared if the buffer is
2431 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
2432 * and for a VMIO buffer B_CACHE is adjusted according to the
2435 if (bp->b_flags & B_INVAL)
2436 bp->b_flags &= ~B_CACHE;
2437 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2438 bp->b_flags |= B_CACHE;
2442 * check for size inconsistancies for non-VMIO case.
2445 if (bp->b_bcount != size) {
2446 if ((bp->b_flags & B_VMIO) == 0 ||
2447 (size > bp->b_kvasize)) {
2448 if (bp->b_flags & B_DELWRI) {
2450 * If buffer is pinned and caller does
2451 * not want sleep waiting for it to be
2452 * unpinned, bail out
2454 if (bp->b_pin_count > 0) {
2455 if (flags & GB_LOCK_NOWAIT) {
2462 bp->b_flags |= B_NOCACHE;
2465 if (LIST_FIRST(&bp->b_dep) == NULL) {
2466 bp->b_flags |= B_RELBUF;
2469 bp->b_flags |= B_NOCACHE;
2478 * If the size is inconsistant in the VMIO case, we can resize
2479 * the buffer. This might lead to B_CACHE getting set or
2480 * cleared. If the size has not changed, B_CACHE remains
2481 * unchanged from its previous state.
2484 if (bp->b_bcount != size)
2487 KASSERT(bp->b_offset != NOOFFSET,
2488 ("getblk: no buffer offset"));
2491 * A buffer with B_DELWRI set and B_CACHE clear must
2492 * be committed before we can return the buffer in
2493 * order to prevent the caller from issuing a read
2494 * ( due to B_CACHE not being set ) and overwriting
2497 * Most callers, including NFS and FFS, need this to
2498 * operate properly either because they assume they
2499 * can issue a read if B_CACHE is not set, or because
2500 * ( for example ) an uncached B_DELWRI might loop due
2501 * to softupdates re-dirtying the buffer. In the latter
2502 * case, B_CACHE is set after the first write completes,
2503 * preventing further loops.
2504 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2505 * above while extending the buffer, we cannot allow the
2506 * buffer to remain with B_CACHE set after the write
2507 * completes or it will represent a corrupt state. To
2508 * deal with this we set B_NOCACHE to scrap the buffer
2511 * We might be able to do something fancy, like setting
2512 * B_CACHE in bwrite() except if B_DELWRI is already set,
2513 * so the below call doesn't set B_CACHE, but that gets real
2514 * confusing. This is much easier.
2517 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2518 bp->b_flags |= B_NOCACHE;
2522 bp->b_flags &= ~B_DONE;
2524 int bsize, maxsize, vmio;
2528 * Buffer is not in-core, create new buffer. The buffer
2529 * returned by getnewbuf() is locked. Note that the returned
2530 * buffer is also considered valid (not marked B_INVAL).
2534 * If the user does not want us to create the buffer, bail out
2537 if (flags & GB_NOCREAT)
2539 bsize = bo->bo_bsize;
2540 offset = blkno * bsize;
2541 vmio = vp->v_object != NULL;
2542 maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2543 maxsize = imax(maxsize, bsize);
2545 bp = getnewbuf(slpflag, slptimeo, size, maxsize);
2547 if (slpflag || slptimeo)
2553 * This code is used to make sure that a buffer is not
2554 * created while the getnewbuf routine is blocked.
2555 * This can be a problem whether the vnode is locked or not.
2556 * If the buffer is created out from under us, we have to
2557 * throw away the one we just created.
2559 * Note: this must occur before we associate the buffer
2560 * with the vp especially considering limitations in
2561 * the splay tree implementation when dealing with duplicate
2565 if (gbincore(bo, blkno)) {
2567 bp->b_flags |= B_INVAL;
2573 * Insert the buffer into the hash, so that it can
2574 * be found by incore.
2576 bp->b_blkno = bp->b_lblkno = blkno;
2577 bp->b_offset = offset;
2583 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
2584 * buffer size starts out as 0, B_CACHE will be set by
2585 * allocbuf() for the VMIO case prior to it testing the
2586 * backing store for validity.
2590 bp->b_flags |= B_VMIO;
2591 #if defined(VFS_BIO_DEBUG)
2592 if (vn_canvmio(vp) != TRUE)
2593 printf("getblk: VMIO on vnode type %d\n",
2596 KASSERT(vp->v_object == bp->b_bufobj->bo_object,
2597 ("ARGH! different b_bufobj->bo_object %p %p %p\n",
2598 bp, vp->v_object, bp->b_bufobj->bo_object));
2600 bp->b_flags &= ~B_VMIO;
2601 KASSERT(bp->b_bufobj->bo_object == NULL,
2602 ("ARGH! has b_bufobj->bo_object %p %p\n",
2603 bp, bp->b_bufobj->bo_object));
2607 bp->b_flags &= ~B_DONE;
2609 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
2610 KASSERT(BUF_REFCNT(bp) == 1, ("getblk: bp %p not locked",bp));
2611 KASSERT(bp->b_bufobj == bo,
2612 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2617 * Get an empty, disassociated buffer of given size. The buffer is initially
2626 maxsize = (size + BKVAMASK) & ~BKVAMASK;
2627 while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2630 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2631 KASSERT(BUF_REFCNT(bp) == 1, ("geteblk: bp %p not locked",bp));
2637 * This code constitutes the buffer memory from either anonymous system
2638 * memory (in the case of non-VMIO operations) or from an associated
2639 * VM object (in the case of VMIO operations). This code is able to
2640 * resize a buffer up or down.
2642 * Note that this code is tricky, and has many complications to resolve
2643 * deadlock or inconsistant data situations. Tread lightly!!!
2644 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2645 * the caller. Calling this code willy nilly can result in the loss of data.
2647 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2648 * B_CACHE for the non-VMIO case.
2652 allocbuf(struct buf *bp, int size)
2654 int newbsize, mbsize;
2657 if (BUF_REFCNT(bp) == 0)
2658 panic("allocbuf: buffer not busy");
2660 if (bp->b_kvasize < size)
2661 panic("allocbuf: buffer too small");
2663 if ((bp->b_flags & B_VMIO) == 0) {
2667 * Just get anonymous memory from the kernel. Don't
2668 * mess with B_CACHE.
2670 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2671 if (bp->b_flags & B_MALLOC)
2674 newbsize = round_page(size);
2676 if (newbsize < bp->b_bufsize) {
2678 * malloced buffers are not shrunk
2680 if (bp->b_flags & B_MALLOC) {
2682 bp->b_bcount = size;
2684 free(bp->b_data, M_BIOBUF);
2685 if (bp->b_bufsize) {
2686 atomic_subtract_int(
2692 bp->b_saveaddr = bp->b_kvabase;
2693 bp->b_data = bp->b_saveaddr;
2695 bp->b_flags &= ~B_MALLOC;
2701 (vm_offset_t) bp->b_data + newbsize,
2702 (vm_offset_t) bp->b_data + bp->b_bufsize);
2703 } else if (newbsize > bp->b_bufsize) {
2705 * We only use malloced memory on the first allocation.
2706 * and revert to page-allocated memory when the buffer
2710 * There is a potential smp race here that could lead
2711 * to bufmallocspace slightly passing the max. It
2712 * is probably extremely rare and not worth worrying
2715 if ( (bufmallocspace < maxbufmallocspace) &&
2716 (bp->b_bufsize == 0) &&
2717 (mbsize <= PAGE_SIZE/2)) {
2719 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2720 bp->b_bufsize = mbsize;
2721 bp->b_bcount = size;
2722 bp->b_flags |= B_MALLOC;
2723 atomic_add_int(&bufmallocspace, mbsize);
2729 * If the buffer is growing on its other-than-first allocation,
2730 * then we revert to the page-allocation scheme.
2732 if (bp->b_flags & B_MALLOC) {
2733 origbuf = bp->b_data;
2734 origbufsize = bp->b_bufsize;
2735 bp->b_data = bp->b_kvabase;
2736 if (bp->b_bufsize) {
2737 atomic_subtract_int(&bufmallocspace,
2742 bp->b_flags &= ~B_MALLOC;
2743 newbsize = round_page(newbsize);
2747 (vm_offset_t) bp->b_data + bp->b_bufsize,
2748 (vm_offset_t) bp->b_data + newbsize);
2750 bcopy(origbuf, bp->b_data, origbufsize);
2751 free(origbuf, M_BIOBUF);
2757 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2758 desiredpages = (size == 0) ? 0 :
2759 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2761 if (bp->b_flags & B_MALLOC)
2762 panic("allocbuf: VMIO buffer can't be malloced");
2764 * Set B_CACHE initially if buffer is 0 length or will become
2767 if (size == 0 || bp->b_bufsize == 0)
2768 bp->b_flags |= B_CACHE;
2770 if (newbsize < bp->b_bufsize) {
2772 * DEV_BSIZE aligned new buffer size is less then the
2773 * DEV_BSIZE aligned existing buffer size. Figure out
2774 * if we have to remove any pages.
2776 if (desiredpages < bp->b_npages) {
2779 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
2780 vm_page_lock_queues();
2781 for (i = desiredpages; i < bp->b_npages; i++) {
2783 * the page is not freed here -- it
2784 * is the responsibility of
2785 * vnode_pager_setsize
2788 KASSERT(m != bogus_page,
2789 ("allocbuf: bogus page found"));
2790 while (vm_page_sleep_if_busy(m, TRUE, "biodep"))
2791 vm_page_lock_queues();
2793 bp->b_pages[i] = NULL;
2794 vm_page_unwire(m, 0);
2796 vm_page_unlock_queues();
2797 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
2798 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2799 (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
2800 bp->b_npages = desiredpages;
2802 } else if (size > bp->b_bcount) {
2804 * We are growing the buffer, possibly in a
2805 * byte-granular fashion.
2813 * Step 1, bring in the VM pages from the object,
2814 * allocating them if necessary. We must clear
2815 * B_CACHE if these pages are not valid for the
2816 * range covered by the buffer.
2820 obj = bp->b_bufobj->bo_object;
2822 VM_OBJECT_LOCK(obj);
2823 while (bp->b_npages < desiredpages) {
2827 pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
2828 if ((m = vm_page_lookup(obj, pi)) == NULL) {
2830 * note: must allocate system pages
2831 * since blocking here could intefere
2832 * with paging I/O, no matter which
2835 m = vm_page_alloc(obj, pi,
2836 VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM |
2839 atomic_add_int(&vm_pageout_deficit,
2840 desiredpages - bp->b_npages);
2841 VM_OBJECT_UNLOCK(obj);
2843 VM_OBJECT_LOCK(obj);
2845 bp->b_flags &= ~B_CACHE;
2846 bp->b_pages[bp->b_npages] = m;
2853 * We found a page. If we have to sleep on it,
2854 * retry because it might have gotten freed out
2857 * We can only test PG_BUSY here. Blocking on
2858 * m->busy might lead to a deadlock:
2860 * vm_fault->getpages->cluster_read->allocbuf
2863 vm_page_lock_queues();
2864 if (vm_page_sleep_if_busy(m, FALSE, "pgtblk"))
2868 * We have a good page. Should we wakeup the
2871 if ((curproc != pageproc) &&
2872 (VM_PAGE_INQUEUE1(m, PQ_CACHE)) &&
2873 ((cnt.v_free_count + cnt.v_cache_count) <
2874 (cnt.v_free_min + cnt.v_cache_min))) {
2875 pagedaemon_wakeup();
2878 vm_page_unlock_queues();
2879 bp->b_pages[bp->b_npages] = m;
2884 * Step 2. We've loaded the pages into the buffer,
2885 * we have to figure out if we can still have B_CACHE
2886 * set. Note that B_CACHE is set according to the
2887 * byte-granular range ( bcount and size ), new the
2888 * aligned range ( newbsize ).
2890 * The VM test is against m->valid, which is DEV_BSIZE
2891 * aligned. Needless to say, the validity of the data
2892 * needs to also be DEV_BSIZE aligned. Note that this
2893 * fails with NFS if the server or some other client
2894 * extends the file's EOF. If our buffer is resized,
2895 * B_CACHE may remain set! XXX
2898 toff = bp->b_bcount;
2899 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2901 while ((bp->b_flags & B_CACHE) && toff < size) {
2904 if (tinc > (size - toff))
2907 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2920 VM_OBJECT_UNLOCK(obj);
2923 * Step 3, fixup the KVM pmap. Remember that
2924 * bp->b_data is relative to bp->b_offset, but
2925 * bp->b_offset may be offset into the first page.
2928 bp->b_data = (caddr_t)
2929 trunc_page((vm_offset_t)bp->b_data);
2931 (vm_offset_t)bp->b_data,
2936 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2937 (vm_offset_t)(bp->b_offset & PAGE_MASK));
2940 if (newbsize < bp->b_bufsize)
2942 bp->b_bufsize = newbsize; /* actual buffer allocation */
2943 bp->b_bcount = size; /* requested buffer size */
2948 biodone(struct bio *bp)
2950 void (*done)(struct bio *);
2952 mtx_lock(&bdonelock);
2953 bp->bio_flags |= BIO_DONE;
2954 done = bp->bio_done;
2957 mtx_unlock(&bdonelock);
2963 * Wait for a BIO to finish.
2965 * XXX: resort to a timeout for now. The optimal locking (if any) for this
2966 * case is not yet clear.
2969 biowait(struct bio *bp, const char *wchan)
2972 mtx_lock(&bdonelock);
2973 while ((bp->bio_flags & BIO_DONE) == 0)
2974 msleep(bp, &bdonelock, PRIBIO, wchan, hz / 10);
2975 mtx_unlock(&bdonelock);
2976 if (bp->bio_error != 0)
2977 return (bp->bio_error);
2978 if (!(bp->bio_flags & BIO_ERROR))
2984 biofinish(struct bio *bp, struct devstat *stat, int error)
2988 bp->bio_error = error;
2989 bp->bio_flags |= BIO_ERROR;
2992 devstat_end_transaction_bio(stat, bp);
2999 * Wait for buffer I/O completion, returning error status. The buffer
3000 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR
3001 * error and cleared.
3004 bufwait(struct buf *bp)
3006 if (bp->b_iocmd == BIO_READ)
3007 bwait(bp, PRIBIO, "biord");
3009 bwait(bp, PRIBIO, "biowr");
3010 if (bp->b_flags & B_EINTR) {
3011 bp->b_flags &= ~B_EINTR;
3014 if (bp->b_ioflags & BIO_ERROR) {
3015 return (bp->b_error ? bp->b_error : EIO);
3022 * Call back function from struct bio back up to struct buf.
3025 bufdonebio(struct bio *bip)
3029 bp = bip->bio_caller2;
3030 bp->b_resid = bp->b_bcount - bip->bio_completed;
3031 bp->b_resid = bip->bio_resid; /* XXX: remove */
3032 bp->b_ioflags = bip->bio_flags;
3033 bp->b_error = bip->bio_error;
3035 bp->b_ioflags |= BIO_ERROR;
3041 dev_strategy(struct cdev *dev, struct buf *bp)
3046 if ((!bp->b_iocmd) || (bp->b_iocmd & (bp->b_iocmd - 1)))
3047 panic("b_iocmd botch");
3052 /* Try again later */
3053 tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3055 bip->bio_cmd = bp->b_iocmd;
3056 bip->bio_offset = bp->b_iooffset;
3057 bip->bio_length = bp->b_bcount;
3058 bip->bio_bcount = bp->b_bcount; /* XXX: remove */
3059 bip->bio_data = bp->b_data;
3060 bip->bio_done = bufdonebio;
3061 bip->bio_caller2 = bp;
3063 KASSERT(dev->si_refcount > 0,
3064 ("dev_strategy on un-referenced struct cdev *(%s)",
3066 csw = dev_refthread(dev);
3068 bp->b_error = ENXIO;
3069 bp->b_ioflags = BIO_ERROR;
3073 (*csw->d_strategy)(bip);
3080 * Finish I/O on a buffer, optionally calling a completion function.
3081 * This is usually called from an interrupt so process blocking is
3084 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3085 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3086 * assuming B_INVAL is clear.
3088 * For the VMIO case, we set B_CACHE if the op was a read and no
3089 * read error occured, or if the op was a write. B_CACHE is never
3090 * set if the buffer is invalid or otherwise uncacheable.
3092 * biodone does not mess with B_INVAL, allowing the I/O routine or the
3093 * initiator to leave B_INVAL set to brelse the buffer out of existance
3094 * in the biodone routine.
3097 bufdone(struct buf *bp)
3099 struct bufobj *dropobj;
3100 void (*biodone)(struct buf *);
3102 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3105 KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp,
3107 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3109 runningbufwakeup(bp);
3110 if (bp->b_iocmd == BIO_WRITE)
3111 dropobj = bp->b_bufobj;
3112 /* call optional completion function if requested */
3113 if (bp->b_iodone != NULL) {
3114 biodone = bp->b_iodone;
3115 bp->b_iodone = NULL;
3118 bufobj_wdrop(dropobj);
3125 bufobj_wdrop(dropobj);
3129 bufdone_finish(struct buf *bp)
3131 KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp,
3134 if (LIST_FIRST(&bp->b_dep) != NULL)
3137 if (bp->b_flags & B_VMIO) {
3143 struct vnode *vp = bp->b_vp;
3145 obj = bp->b_bufobj->bo_object;
3147 #if defined(VFS_BIO_DEBUG)
3148 mp_fixme("usecount and vflag accessed without locks.");
3149 if (vp->v_usecount == 0) {
3150 panic("biodone: zero vnode ref count");
3153 KASSERT(vp->v_object != NULL,
3154 ("biodone: vnode %p has no vm_object", vp));
3157 foff = bp->b_offset;
3158 KASSERT(bp->b_offset != NOOFFSET,
3159 ("biodone: no buffer offset"));
3161 VM_OBJECT_LOCK(obj);
3162 #if defined(VFS_BIO_DEBUG)
3163 if (obj->paging_in_progress < bp->b_npages) {
3164 printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
3165 obj->paging_in_progress, bp->b_npages);
3170 * Set B_CACHE if the op was a normal read and no error
3171 * occured. B_CACHE is set for writes in the b*write()
3174 iosize = bp->b_bcount - bp->b_resid;
3175 if (bp->b_iocmd == BIO_READ &&
3176 !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3177 !(bp->b_ioflags & BIO_ERROR)) {
3178 bp->b_flags |= B_CACHE;
3180 vm_page_lock_queues();
3181 for (i = 0; i < bp->b_npages; i++) {
3185 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3190 * cleanup bogus pages, restoring the originals
3193 if (m == bogus_page) {
3195 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3197 panic("biodone: page disappeared!");
3199 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3200 bp->b_pages, bp->b_npages);
3202 #if defined(VFS_BIO_DEBUG)
3203 if (OFF_TO_IDX(foff) != m->pindex) {
3205 "biodone: foff(%jd)/m->pindex(%ju) mismatch\n",
3206 (intmax_t)foff, (uintmax_t)m->pindex);
3211 * In the write case, the valid and clean bits are
3212 * already changed correctly ( see bdwrite() ), so we
3213 * only need to do this here in the read case.
3215 if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3216 vfs_page_set_valid(bp, foff, i, m);
3220 * when debugging new filesystems or buffer I/O methods, this
3221 * is the most common error that pops up. if you see this, you
3222 * have not set the page busy flag correctly!!!
3225 printf("biodone: page busy < 0, "
3226 "pindex: %d, foff: 0x(%x,%x), "
3227 "resid: %d, index: %d\n",
3228 (int) m->pindex, (int)(foff >> 32),
3229 (int) foff & 0xffffffff, resid, i);
3230 if (!vn_isdisk(vp, NULL))
3231 printf(" iosize: %jd, lblkno: %jd, flags: 0x%x, npages: %d\n",
3232 (intmax_t)bp->b_vp->v_mount->mnt_stat.f_iosize,
3233 (intmax_t) bp->b_lblkno,
3234 bp->b_flags, bp->b_npages);
3236 printf(" VDEV, lblkno: %jd, flags: 0x%x, npages: %d\n",
3237 (intmax_t) bp->b_lblkno,
3238 bp->b_flags, bp->b_npages);
3239 printf(" valid: 0x%lx, dirty: 0x%lx, wired: %d\n",
3240 (u_long)m->valid, (u_long)m->dirty,
3242 panic("biodone: page busy < 0\n");
3244 vm_page_io_finish(m);
3245 vm_object_pip_subtract(obj, 1);
3246 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3249 vm_page_unlock_queues();
3250 vm_object_pip_wakeupn(obj, 0);
3251 VM_OBJECT_UNLOCK(obj);
3255 * For asynchronous completions, release the buffer now. The brelse
3256 * will do a wakeup there if necessary - so no need to do a wakeup
3257 * here in the async case. The sync case always needs to do a wakeup.
3260 if (bp->b_flags & B_ASYNC) {
3261 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3270 * This routine is called in lieu of iodone in the case of
3271 * incomplete I/O. This keeps the busy status for pages
3275 vfs_unbusy_pages(struct buf *bp)
3281 runningbufwakeup(bp);
3282 if (!(bp->b_flags & B_VMIO))
3285 obj = bp->b_bufobj->bo_object;
3286 VM_OBJECT_LOCK(obj);
3287 vm_page_lock_queues();
3288 for (i = 0; i < bp->b_npages; i++) {
3290 if (m == bogus_page) {
3291 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3293 panic("vfs_unbusy_pages: page missing\n");
3295 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3296 bp->b_pages, bp->b_npages);
3298 vm_object_pip_subtract(obj, 1);
3299 vm_page_io_finish(m);
3301 vm_page_unlock_queues();
3302 vm_object_pip_wakeupn(obj, 0);
3303 VM_OBJECT_UNLOCK(obj);
3307 * vfs_page_set_valid:
3309 * Set the valid bits in a page based on the supplied offset. The
3310 * range is restricted to the buffer's size.
3312 * This routine is typically called after a read completes.
3315 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3317 vm_ooffset_t soff, eoff;
3319 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
3321 * Start and end offsets in buffer. eoff - soff may not cross a
3322 * page boundry or cross the end of the buffer. The end of the
3323 * buffer, in this case, is our file EOF, not the allocation size
3327 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3328 if (eoff > bp->b_offset + bp->b_bcount)
3329 eoff = bp->b_offset + bp->b_bcount;
3332 * Set valid range. This is typically the entire buffer and thus the
3336 vm_page_set_validclean(
3338 (vm_offset_t) (soff & PAGE_MASK),
3339 (vm_offset_t) (eoff - soff)
3345 * This routine is called before a device strategy routine.
3346 * It is used to tell the VM system that paging I/O is in
3347 * progress, and treat the pages associated with the buffer
3348 * almost as being PG_BUSY. Also the object paging_in_progress
3349 * flag is handled to make sure that the object doesn't become
3352 * Since I/O has not been initiated yet, certain buffer flags
3353 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
3354 * and should be ignored.
3357 vfs_busy_pages(struct buf *bp, int clear_modify)
3364 if (!(bp->b_flags & B_VMIO))
3367 obj = bp->b_bufobj->bo_object;
3368 foff = bp->b_offset;
3369 KASSERT(bp->b_offset != NOOFFSET,
3370 ("vfs_busy_pages: no buffer offset"));
3372 VM_OBJECT_LOCK(obj);
3374 vm_page_lock_queues();
3375 for (i = 0; i < bp->b_npages; i++) {
3378 if (vm_page_sleep_if_busy(m, FALSE, "vbpage"))
3382 for (i = 0; i < bp->b_npages; i++) {
3385 if ((bp->b_flags & B_CLUSTER) == 0) {
3386 vm_object_pip_add(obj, 1);
3387 vm_page_io_start(m);
3390 * When readying a buffer for a read ( i.e
3391 * clear_modify == 0 ), it is important to do
3392 * bogus_page replacement for valid pages in
3393 * partially instantiated buffers. Partially
3394 * instantiated buffers can, in turn, occur when
3395 * reconstituting a buffer from its VM backing store
3396 * base. We only have to do this if B_CACHE is
3397 * clear ( which causes the I/O to occur in the
3398 * first place ). The replacement prevents the read
3399 * I/O from overwriting potentially dirty VM-backed
3400 * pages. XXX bogus page replacement is, uh, bogus.
3401 * It may not work properly with small-block devices.
3402 * We need to find a better way.
3406 vfs_page_set_valid(bp, foff, i, m);
3407 else if (m->valid == VM_PAGE_BITS_ALL &&
3408 (bp->b_flags & B_CACHE) == 0) {
3409 bp->b_pages[i] = bogus_page;
3412 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3414 vm_page_unlock_queues();
3415 VM_OBJECT_UNLOCK(obj);
3417 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3418 bp->b_pages, bp->b_npages);
3422 * Tell the VM system that the pages associated with this buffer
3423 * are clean. This is used for delayed writes where the data is
3424 * going to go to disk eventually without additional VM intevention.
3426 * Note that while we only really need to clean through to b_bcount, we
3427 * just go ahead and clean through to b_bufsize.
3430 vfs_clean_pages(struct buf *bp)
3433 vm_ooffset_t foff, noff, eoff;
3436 if (!(bp->b_flags & B_VMIO))
3439 foff = bp->b_offset;
3440 KASSERT(bp->b_offset != NOOFFSET,
3441 ("vfs_clean_pages: no buffer offset"));
3442 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3443 vm_page_lock_queues();
3444 for (i = 0; i < bp->b_npages; i++) {
3446 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3449 if (eoff > bp->b_offset + bp->b_bufsize)
3450 eoff = bp->b_offset + bp->b_bufsize;
3451 vfs_page_set_valid(bp, foff, i, m);
3452 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3455 vm_page_unlock_queues();
3456 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3460 * vfs_bio_set_validclean:
3462 * Set the range within the buffer to valid and clean. The range is
3463 * relative to the beginning of the buffer, b_offset. Note that b_offset
3464 * itself may be offset from the beginning of the first page.
3469 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3474 if (!(bp->b_flags & B_VMIO))
3477 * Fixup base to be relative to beginning of first page.
3478 * Set initial n to be the maximum number of bytes in the
3479 * first page that can be validated.
3482 base += (bp->b_offset & PAGE_MASK);
3483 n = PAGE_SIZE - (base & PAGE_MASK);
3485 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3486 vm_page_lock_queues();
3487 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3491 vm_page_set_validclean(m, base & PAGE_MASK, n);
3496 vm_page_unlock_queues();
3497 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3503 * clear a buffer. This routine essentially fakes an I/O, so we need
3504 * to clear BIO_ERROR and B_INVAL.
3506 * Note that while we only theoretically need to clear through b_bcount,
3507 * we go ahead and clear through b_bufsize.
3511 vfs_bio_clrbuf(struct buf *bp)
3516 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
3521 bp->b_flags &= ~B_INVAL;
3522 bp->b_ioflags &= ~BIO_ERROR;
3523 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3524 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3525 (bp->b_offset & PAGE_MASK) == 0) {
3526 if (bp->b_pages[0] == bogus_page)
3528 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3529 VM_OBJECT_LOCK_ASSERT(bp->b_pages[0]->object, MA_OWNED);
3530 if ((bp->b_pages[0]->valid & mask) == mask)
3532 if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
3533 ((bp->b_pages[0]->valid & mask) == 0)) {
3534 bzero(bp->b_data, bp->b_bufsize);
3535 bp->b_pages[0]->valid |= mask;
3539 ea = sa = bp->b_data;
3540 for(i = 0; i < bp->b_npages; i++, sa = ea) {
3541 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3542 ea = (caddr_t)(vm_offset_t)ulmin(
3543 (u_long)(vm_offset_t)ea,
3544 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3545 if (bp->b_pages[i] == bogus_page)
3547 j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3548 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3549 VM_OBJECT_LOCK_ASSERT(bp->b_pages[i]->object, MA_OWNED);
3550 if ((bp->b_pages[i]->valid & mask) == mask)
3552 if ((bp->b_pages[i]->valid & mask) == 0) {
3553 if ((bp->b_pages[i]->flags & PG_ZERO) == 0)
3556 for (; sa < ea; sa += DEV_BSIZE, j++) {
3557 if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
3558 (bp->b_pages[i]->valid & (1 << j)) == 0)
3559 bzero(sa, DEV_BSIZE);
3562 bp->b_pages[i]->valid |= mask;
3565 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3570 * vm_hold_load_pages and vm_hold_free_pages get pages into
3571 * a buffers address space. The pages are anonymous and are
3572 * not associated with a file object.
3575 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3581 to = round_page(to);
3582 from = round_page(from);
3583 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3585 VM_OBJECT_LOCK(kernel_object);
3586 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3589 * note: must allocate system pages since blocking here
3590 * could intefere with paging I/O, no matter which
3593 p = vm_page_alloc(kernel_object,
3594 ((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3595 VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
3597 atomic_add_int(&vm_pageout_deficit,
3598 (to - pg) >> PAGE_SHIFT);
3599 VM_OBJECT_UNLOCK(kernel_object);
3601 VM_OBJECT_LOCK(kernel_object);
3604 p->valid = VM_PAGE_BITS_ALL;
3605 pmap_qenter(pg, &p, 1);
3606 bp->b_pages[index] = p;
3608 VM_OBJECT_UNLOCK(kernel_object);
3609 bp->b_npages = index;
3612 /* Return pages associated with this buf to the vm system */
3614 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3618 int index, newnpages;
3620 from = round_page(from);
3621 to = round_page(to);
3622 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3624 VM_OBJECT_LOCK(kernel_object);
3625 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3626 p = bp->b_pages[index];
3627 if (p && (index < bp->b_npages)) {
3630 "vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
3631 (intmax_t)bp->b_blkno,
3632 (intmax_t)bp->b_lblkno);
3634 bp->b_pages[index] = NULL;
3635 pmap_qremove(pg, 1);
3636 vm_page_lock_queues();
3637 vm_page_unwire(p, 0);
3639 vm_page_unlock_queues();
3642 VM_OBJECT_UNLOCK(kernel_object);
3643 bp->b_npages = newnpages;
3647 * Map an IO request into kernel virtual address space.
3649 * All requests are (re)mapped into kernel VA space.
3650 * Notice that we use b_bufsize for the size of the buffer
3651 * to be mapped. b_bcount might be modified by the driver.
3653 * Note that even if the caller determines that the address space should
3654 * be valid, a race or a smaller-file mapped into a larger space may
3655 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
3656 * check the return value.
3659 vmapbuf(struct buf *bp)
3665 struct pmap *pmap = &curproc->p_vmspace->vm_pmap;
3667 if (bp->b_bufsize < 0)
3669 prot = VM_PROT_READ;
3670 if (bp->b_iocmd == BIO_READ)
3671 prot |= VM_PROT_WRITE; /* Less backwards than it looks */
3672 for (addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data), pidx = 0;
3673 addr < bp->b_data + bp->b_bufsize;
3674 addr += PAGE_SIZE, pidx++) {
3676 * Do the vm_fault if needed; do the copy-on-write thing
3677 * when reading stuff off device into memory.
3679 * NOTE! Must use pmap_extract() because addr may be in
3680 * the userland address space, and kextract is only guarenteed
3681 * to work for the kernland address space (see: sparc64 port).
3684 if (vm_fault_quick(addr >= bp->b_data ? addr : bp->b_data,
3686 vm_page_lock_queues();
3687 for (i = 0; i < pidx; ++i) {
3688 vm_page_unhold(bp->b_pages[i]);
3689 bp->b_pages[i] = NULL;
3691 vm_page_unlock_queues();
3694 m = pmap_extract_and_hold(pmap, (vm_offset_t)addr, prot);
3697 bp->b_pages[pidx] = m;
3699 if (pidx > btoc(MAXPHYS))
3700 panic("vmapbuf: mapped more than MAXPHYS");
3701 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
3703 kva = bp->b_saveaddr;
3704 bp->b_npages = pidx;
3705 bp->b_saveaddr = bp->b_data;
3706 bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3711 * Free the io map PTEs associated with this IO operation.
3712 * We also invalidate the TLB entries and restore the original b_addr.
3715 vunmapbuf(struct buf *bp)
3720 npages = bp->b_npages;
3721 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
3722 vm_page_lock_queues();
3723 for (pidx = 0; pidx < npages; pidx++)
3724 vm_page_unhold(bp->b_pages[pidx]);
3725 vm_page_unlock_queues();
3727 bp->b_data = bp->b_saveaddr;
3731 bdone(struct buf *bp)
3734 mtx_lock(&bdonelock);
3735 bp->b_flags |= B_DONE;
3737 mtx_unlock(&bdonelock);
3741 bwait(struct buf *bp, u_char pri, const char *wchan)
3744 mtx_lock(&bdonelock);
3745 while ((bp->b_flags & B_DONE) == 0)
3746 msleep(bp, &bdonelock, pri, wchan, 0);
3747 mtx_unlock(&bdonelock);
3751 bufsync(struct bufobj *bo, int waitfor, struct thread *td)
3754 return (VOP_FSYNC(bo->__bo_vnode, waitfor, td));
3758 bufstrategy(struct bufobj *bo, struct buf *bp)
3764 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
3765 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
3766 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
3767 i = VOP_STRATEGY(vp, bp);
3768 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
3772 bufobj_wrefl(struct bufobj *bo)
3775 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
3776 ASSERT_BO_LOCKED(bo);
3781 bufobj_wref(struct bufobj *bo)
3784 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
3791 bufobj_wdrop(struct bufobj *bo)
3794 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
3796 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
3797 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
3798 bo->bo_flag &= ~BO_WWAIT;
3799 wakeup(&bo->bo_numoutput);
3805 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
3809 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
3810 ASSERT_BO_LOCKED(bo);
3812 while (bo->bo_numoutput) {
3813 bo->bo_flag |= BO_WWAIT;
3814 error = msleep(&bo->bo_numoutput, BO_MTX(bo),
3815 slpflag | (PRIBIO + 1), "bo_wwait", timeo);
3823 bpin(struct buf *bp)
3825 mtx_lock(&bpinlock);
3827 mtx_unlock(&bpinlock);
3831 bunpin(struct buf *bp)
3833 mtx_lock(&bpinlock);
3834 if (--bp->b_pin_count == 0)
3836 mtx_unlock(&bpinlock);
3840 bunpin_wait(struct buf *bp)
3842 mtx_lock(&bpinlock);
3843 while (bp->b_pin_count > 0)
3844 msleep(bp, &bpinlock, PRIBIO, "bwunpin", 0);
3845 mtx_unlock(&bpinlock);
3848 #include "opt_ddb.h"
3850 #include <ddb/ddb.h>
3852 /* DDB command to show buffer data */
3853 DB_SHOW_COMMAND(buffer, db_show_buffer)
3856 struct buf *bp = (struct buf *)addr;
3859 db_printf("usage: show buffer <addr>\n");
3863 db_printf("buf at %p\n", bp);
3864 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3866 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
3867 "b_bufobj = (%p), b_data = %p, b_blkno = %jd\n",
3868 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3869 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno);
3872 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
3873 for (i = 0; i < bp->b_npages; i++) {
3876 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3877 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3878 if ((i + 1) < bp->b_npages)
3883 lockmgr_printinfo(&bp->b_lock);
3886 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
3891 for (i = 0; i < nbuf; i++) {
3893 if (lockcount(&bp->b_lock)) {
3894 db_show_buffer((uintptr_t)bp, 1, 0, NULL);