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, int);
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 6 /* 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_DIRTY_GIANT 3 /* B_DELWRI buffers that need giant */
253 #define QUEUE_EMPTYKVA 4 /* empty buffer headers w/KVA assignment */
254 #define QUEUE_EMPTY 5 /* empty buffer headers */
256 /* Queues for free buffers with various properties */
257 static TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
259 /* Lock for the bufqueues */
260 static struct mtx bqlock;
263 * Single global constant for BUF_WMESG, to avoid getting multiple references.
264 * buf_wmesg is referred from macros.
266 const char *buf_wmesg = BUF_WMESG;
268 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
269 #define VFS_BIO_NEED_DIRTYFLUSH 0x02 /* waiting for dirty buffer flush */
270 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
271 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
274 extern void ffs_rawread_setup(void);
275 #endif /* DIRECTIO */
279 * If someone is blocked due to there being too many dirty buffers,
280 * and numdirtybuffers is now reasonable, wake them up.
284 numdirtywakeup(int level)
287 if (numdirtybuffers <= level) {
289 if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
290 needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
291 wakeup(&needsbuffer);
300 * Called when buffer space is potentially available for recovery.
301 * getnewbuf() will block on this flag when it is unable to free
302 * sufficient buffer space. Buffer space becomes recoverable when
303 * bp's get placed back in the queues.
311 * If someone is waiting for BUF space, wake them up. Even
312 * though we haven't freed the kva space yet, the waiting
313 * process will be able to now.
316 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
317 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
318 wakeup(&needsbuffer);
324 * runningbufwakeup() - in-progress I/O accounting.
328 runningbufwakeup(struct buf *bp)
331 if (bp->b_runningbufspace) {
332 atomic_subtract_int(&runningbufspace, bp->b_runningbufspace);
333 bp->b_runningbufspace = 0;
334 mtx_lock(&rbreqlock);
335 if (runningbufreq && runningbufspace <= lorunningspace) {
337 wakeup(&runningbufreq);
339 mtx_unlock(&rbreqlock);
346 * Called when a buffer has been added to one of the free queues to
347 * account for the buffer and to wakeup anyone waiting for free buffers.
348 * This typically occurs when large amounts of metadata are being handled
349 * by the buffer cache ( else buffer space runs out first, usually ).
356 atomic_add_int(&numfreebuffers, 1);
359 needsbuffer &= ~VFS_BIO_NEED_ANY;
360 if (numfreebuffers >= hifreebuffers)
361 needsbuffer &= ~VFS_BIO_NEED_FREE;
362 wakeup(&needsbuffer);
368 * waitrunningbufspace()
370 * runningbufspace is a measure of the amount of I/O currently
371 * running. This routine is used in async-write situations to
372 * prevent creating huge backups of pending writes to a device.
373 * Only asynchronous writes are governed by this function.
375 * Reads will adjust runningbufspace, but will not block based on it.
376 * The read load has a side effect of reducing the allowed write load.
378 * This does NOT turn an async write into a sync write. It waits
379 * for earlier writes to complete and generally returns before the
380 * caller's write has reached the device.
383 waitrunningbufspace(void)
386 mtx_lock(&rbreqlock);
387 while (runningbufspace > hirunningspace) {
389 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
391 mtx_unlock(&rbreqlock);
396 * vfs_buf_test_cache:
398 * Called when a buffer is extended. This function clears the B_CACHE
399 * bit if the newly extended portion of the buffer does not contain
404 vfs_buf_test_cache(struct buf *bp,
405 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
409 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
410 if (bp->b_flags & B_CACHE) {
411 int base = (foff + off) & PAGE_MASK;
412 if (vm_page_is_valid(m, base, size) == 0)
413 bp->b_flags &= ~B_CACHE;
417 /* Wake up the buffer deamon if necessary */
420 bd_wakeup(int dirtybuflevel)
424 if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
432 * bd_speedup - speedup the buffer cache flushing code
444 * Calculating buffer cache scaling values and reserve space for buffer
445 * headers. This is called during low level kernel initialization and
446 * may be called more then once. We CANNOT write to the memory area
447 * being reserved at this time.
450 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
454 * physmem_est is in pages. Convert it to kilobytes (assumes
455 * PAGE_SIZE is >= 1K)
457 physmem_est = physmem_est * (PAGE_SIZE / 1024);
460 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
461 * For the first 64MB of ram nominally allocate sufficient buffers to
462 * cover 1/4 of our ram. Beyond the first 64MB allocate additional
463 * buffers to cover 1/20 of our ram over 64MB. When auto-sizing
464 * the buffer cache we limit the eventual kva reservation to
467 * factor represents the 1/4 x ram conversion.
470 int factor = 4 * BKVASIZE / 1024;
473 if (physmem_est > 4096)
474 nbuf += min((physmem_est - 4096) / factor,
476 if (physmem_est > 65536)
477 nbuf += (physmem_est - 65536) * 2 / (factor * 5);
479 if (maxbcache && nbuf > maxbcache / BKVASIZE)
480 nbuf = maxbcache / BKVASIZE;
485 * Do not allow the buffer_map to be more then 1/2 the size of the
488 if (nbuf > (kernel_map->max_offset - kernel_map->min_offset) /
490 nbuf = (kernel_map->max_offset - kernel_map->min_offset) /
492 printf("Warning: nbufs capped at %d\n", nbuf);
497 * swbufs are used as temporary holders for I/O, such as paging I/O.
498 * We have no less then 16 and no more then 256.
500 nswbuf = max(min(nbuf/4, 256), 16);
502 if (nswbuf < NSWBUF_MIN)
510 * Reserve space for the buffer cache buffers
513 v = (caddr_t)(swbuf + nswbuf);
515 v = (caddr_t)(buf + nbuf);
520 /* Initialize the buffer subsystem. Called before use of any buffers. */
527 mtx_init(&bqlock, "buf queue lock", NULL, MTX_DEF);
528 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
529 mtx_init(&nblock, "needsbuffer lock", NULL, MTX_DEF);
530 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
531 mtx_init(&bdonelock, "bdone lock", NULL, MTX_DEF);
532 mtx_init(&bpinlock, "bpin lock", NULL, MTX_DEF);
534 /* next, make a null set of free lists */
535 for (i = 0; i < BUFFER_QUEUES; i++)
536 TAILQ_INIT(&bufqueues[i]);
538 /* finally, initialize each buffer header and stick on empty q */
539 for (i = 0; i < nbuf; i++) {
541 bzero(bp, sizeof *bp);
542 bp->b_flags = B_INVAL; /* we're just an empty header */
543 bp->b_rcred = NOCRED;
544 bp->b_wcred = NOCRED;
545 bp->b_qindex = QUEUE_EMPTY;
548 LIST_INIT(&bp->b_dep);
550 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
554 * maxbufspace is the absolute maximum amount of buffer space we are
555 * allowed to reserve in KVM and in real terms. The absolute maximum
556 * is nominally used by buf_daemon. hibufspace is the nominal maximum
557 * used by most other processes. The differential is required to
558 * ensure that buf_daemon is able to run when other processes might
559 * be blocked waiting for buffer space.
561 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
562 * this may result in KVM fragmentation which is not handled optimally
565 maxbufspace = nbuf * BKVASIZE;
566 hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
567 lobufspace = hibufspace - MAXBSIZE;
569 lorunningspace = 512 * 1024;
570 hirunningspace = 1024 * 1024;
573 * Limit the amount of malloc memory since it is wired permanently into
574 * the kernel space. Even though this is accounted for in the buffer
575 * allocation, we don't want the malloced region to grow uncontrolled.
576 * The malloc scheme improves memory utilization significantly on average
577 * (small) directories.
579 maxbufmallocspace = hibufspace / 20;
582 * Reduce the chance of a deadlock occuring by limiting the number
583 * of delayed-write dirty buffers we allow to stack up.
585 hidirtybuffers = nbuf / 4 + 20;
586 dirtybufthresh = hidirtybuffers * 9 / 10;
589 * To support extreme low-memory systems, make sure hidirtybuffers cannot
590 * eat up all available buffer space. This occurs when our minimum cannot
591 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
592 * BKVASIZE'd (8K) buffers.
594 while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
595 hidirtybuffers >>= 1;
597 lodirtybuffers = hidirtybuffers / 2;
600 * Try to keep the number of free buffers in the specified range,
601 * and give special processes (e.g. like buf_daemon) access to an
604 lofreebuffers = nbuf / 18 + 5;
605 hifreebuffers = 2 * lofreebuffers;
606 numfreebuffers = nbuf;
609 * Maximum number of async ops initiated per buf_daemon loop. This is
610 * somewhat of a hack at the moment, we really need to limit ourselves
611 * based on the number of bytes of I/O in-transit that were initiated
615 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
616 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
620 * bfreekva() - free the kva allocation for a buffer.
622 * Since this call frees up buffer space, we call bufspacewakeup().
625 bfreekva(struct buf *bp)
629 atomic_add_int(&buffreekvacnt, 1);
630 atomic_subtract_int(&bufspace, bp->b_kvasize);
631 vm_map_lock(buffer_map);
632 vm_map_delete(buffer_map,
633 (vm_offset_t) bp->b_kvabase,
634 (vm_offset_t) bp->b_kvabase + bp->b_kvasize
636 vm_map_unlock(buffer_map);
645 * Mark the buffer for removal from the appropriate free list in brelse.
649 bremfree(struct buf *bp)
652 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
653 KASSERT(BUF_REFCNT(bp), ("bremfree: buf must be locked."));
654 KASSERT((bp->b_flags & B_REMFREE) == 0,
655 ("bremfree: buffer %p already marked for delayed removal.", bp));
656 KASSERT(bp->b_qindex != QUEUE_NONE,
657 ("bremfree: buffer %p not on a queue.", bp));
659 bp->b_flags |= B_REMFREE;
660 /* Fixup numfreebuffers count. */
661 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)
662 atomic_subtract_int(&numfreebuffers, 1);
668 * Force an immediate removal from a free list. Used only in nfs when
669 * it abuses the b_freelist pointer.
672 bremfreef(struct buf *bp)
682 * Removes a buffer from the free list, must be called with the
686 bremfreel(struct buf *bp)
688 CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
689 bp, bp->b_vp, bp->b_flags);
690 KASSERT(BUF_REFCNT(bp), ("bremfreel: buffer %p not locked.", bp));
691 KASSERT(bp->b_qindex != QUEUE_NONE,
692 ("bremfreel: buffer %p not on a queue.", bp));
693 mtx_assert(&bqlock, MA_OWNED);
695 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
696 bp->b_qindex = QUEUE_NONE;
698 * If this was a delayed bremfree() we only need to remove the buffer
699 * from the queue and return the stats are already done.
701 if (bp->b_flags & B_REMFREE) {
702 bp->b_flags &= ~B_REMFREE;
706 * Fixup numfreebuffers count. If the buffer is invalid or not
707 * delayed-write, the buffer was free and we must decrement
710 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)
711 atomic_subtract_int(&numfreebuffers, 1);
716 * Get a buffer with the specified data. Look in the cache first. We
717 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
718 * is set, the buffer is valid and we do not have to do anything ( see
719 * getblk() ). This is really just a special case of breadn().
722 bread(struct vnode * vp, daddr_t blkno, int size, struct ucred * cred,
726 return (breadn(vp, blkno, size, 0, 0, 0, cred, bpp));
730 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must
731 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
732 * the buffer is valid and we do not have to do anything.
735 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
736 int cnt, struct ucred * cred)
741 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
742 if (inmem(vp, *rablkno))
744 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
746 if ((rabp->b_flags & B_CACHE) == 0) {
747 if (curthread != PCPU_GET(idlethread))
748 curthread->td_proc->p_stats->p_ru.ru_inblock++;
749 rabp->b_flags |= B_ASYNC;
750 rabp->b_flags &= ~B_INVAL;
751 rabp->b_ioflags &= ~BIO_ERROR;
752 rabp->b_iocmd = BIO_READ;
753 if (rabp->b_rcred == NOCRED && cred != NOCRED)
754 rabp->b_rcred = crhold(cred);
755 vfs_busy_pages(rabp, 0);
757 rabp->b_iooffset = dbtob(rabp->b_blkno);
766 * Operates like bread, but also starts asynchronous I/O on
770 breadn(struct vnode * vp, daddr_t blkno, int size,
771 daddr_t * rablkno, int *rabsize,
772 int cnt, struct ucred * cred, struct buf **bpp)
775 int rv = 0, readwait = 0;
777 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
778 *bpp = bp = getblk(vp, blkno, size, 0, 0, 0);
780 /* if not found in cache, do some I/O */
781 if ((bp->b_flags & B_CACHE) == 0) {
782 if (curthread != PCPU_GET(idlethread))
783 curthread->td_proc->p_stats->p_ru.ru_inblock++;
784 bp->b_iocmd = BIO_READ;
785 bp->b_flags &= ~B_INVAL;
786 bp->b_ioflags &= ~BIO_ERROR;
787 if (bp->b_rcred == NOCRED && cred != NOCRED)
788 bp->b_rcred = crhold(cred);
789 vfs_busy_pages(bp, 0);
790 bp->b_iooffset = dbtob(bp->b_blkno);
795 breada(vp, rablkno, rabsize, cnt, cred);
804 * Write, release buffer on completion. (Done by iodone
805 * if async). Do not bother writing anything if the buffer
808 * Note that we set B_CACHE here, indicating that buffer is
809 * fully valid and thus cacheable. This is true even of NFS
810 * now so we set it generally. This could be set either here
811 * or in biodone() since the I/O is synchronous. We put it
815 bufwrite(struct buf *bp)
819 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
820 if (bp->b_flags & B_INVAL) {
825 oldflags = bp->b_flags;
827 if (BUF_REFCNT(bp) == 0)
828 panic("bufwrite: buffer is not busy???");
830 if (bp->b_pin_count > 0)
833 KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
834 ("FFS background buffer should not get here %p", bp));
836 /* Mark the buffer clean */
839 bp->b_flags &= ~B_DONE;
840 bp->b_ioflags &= ~BIO_ERROR;
841 bp->b_flags |= B_CACHE;
842 bp->b_iocmd = BIO_WRITE;
844 bufobj_wref(bp->b_bufobj);
845 vfs_busy_pages(bp, 1);
848 * Normal bwrites pipeline writes
850 bp->b_runningbufspace = bp->b_bufsize;
851 atomic_add_int(&runningbufspace, bp->b_runningbufspace);
853 if (curthread != PCPU_GET(idlethread))
854 curthread->td_proc->p_stats->p_ru.ru_oublock++;
855 if (oldflags & B_ASYNC)
857 bp->b_iooffset = dbtob(bp->b_blkno);
860 if ((oldflags & B_ASYNC) == 0) {
861 int rtval = bufwait(bp);
866 * don't allow the async write to saturate the I/O
867 * system. We will not deadlock here because
868 * we are blocking waiting for I/O that is already in-progress
869 * to complete. We do not block here if it is the update
870 * or syncer daemon trying to clean up as that can lead
873 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0)
874 waitrunningbufspace();
881 * Delayed write. (Buffer is marked dirty). Do not bother writing
882 * anything if the buffer is marked invalid.
884 * Note that since the buffer must be completely valid, we can safely
885 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
886 * biodone() in order to prevent getblk from writing the buffer
890 bdwrite(struct buf *bp)
892 struct thread *td = curthread;
897 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
898 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
899 KASSERT(BUF_REFCNT(bp) != 0, ("bdwrite: buffer is not busy"));
901 if (bp->b_flags & B_INVAL) {
907 * If we have too many dirty buffers, don't create any more.
908 * If we are wildly over our limit, then force a complete
909 * cleanup. Otherwise, just keep the situation from getting
910 * out of control. Note that we have to avoid a recursive
911 * disaster and not try to clean up after our own cleanup!
915 if ((td->td_pflags & TDP_COWINPROGRESS) == 0) {
917 if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
919 (void) VOP_FSYNC(vp, MNT_NOWAIT, td);
921 } else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
923 * Try to find a buffer to flush.
925 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
926 if ((nbp->b_vflags & BV_BKGRDINPROG) ||
928 LK_EXCLUSIVE | LK_NOWAIT, NULL))
931 panic("bdwrite: found ourselves");
933 /* Don't countdeps with the bo lock held. */
934 if (buf_countdeps(nbp, 0)) {
939 if (nbp->b_flags & B_CLUSTEROK) {
945 dirtybufferflushes++;
957 * Set B_CACHE, indicating that the buffer is fully valid. This is
958 * true even of NFS now.
960 bp->b_flags |= B_CACHE;
963 * This bmap keeps the system from needing to do the bmap later,
964 * perhaps when the system is attempting to do a sync. Since it
965 * is likely that the indirect block -- or whatever other datastructure
966 * that the filesystem needs is still in memory now, it is a good
967 * thing to do this. Note also, that if the pageout daemon is
968 * requesting a sync -- there might not be enough memory to do
969 * the bmap then... So, this is important to do.
971 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
972 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
976 * Set the *dirty* buffer range based upon the VM system dirty pages.
981 * We need to do this here to satisfy the vnode_pager and the
982 * pageout daemon, so that it thinks that the pages have been
983 * "cleaned". Note that since the pages are in a delayed write
984 * buffer -- the VFS layer "will" see that the pages get written
985 * out on the next sync, or perhaps the cluster will be completed.
991 * Wakeup the buffer flushing daemon if we have a lot of dirty
992 * buffers (midpoint between our recovery point and our stall
995 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
998 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
999 * due to the softdep code.
1006 * Turn buffer into delayed write request. We must clear BIO_READ and
1007 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
1008 * itself to properly update it in the dirty/clean lists. We mark it
1009 * B_DONE to ensure that any asynchronization of the buffer properly
1010 * clears B_DONE ( else a panic will occur later ).
1012 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1013 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
1014 * should only be called if the buffer is known-good.
1016 * Since the buffer is not on a queue, we do not update the numfreebuffers
1019 * The buffer must be on QUEUE_NONE.
1022 bdirty(struct buf *bp)
1025 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
1026 bp, bp->b_vp, bp->b_flags);
1027 KASSERT(BUF_REFCNT(bp) == 1, ("bdirty: bp %p not locked",bp));
1028 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1029 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1030 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1031 bp->b_flags &= ~(B_RELBUF);
1032 bp->b_iocmd = BIO_WRITE;
1034 if ((bp->b_flags & B_DELWRI) == 0) {
1035 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
1037 atomic_add_int(&numdirtybuffers, 1);
1038 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1045 * Clear B_DELWRI for buffer.
1047 * Since the buffer is not on a queue, we do not update the numfreebuffers
1050 * The buffer must be on QUEUE_NONE.
1054 bundirty(struct buf *bp)
1057 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1058 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1059 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1060 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1061 KASSERT(BUF_REFCNT(bp) == 1, ("bundirty: bp %p not locked",bp));
1063 if (bp->b_flags & B_DELWRI) {
1064 bp->b_flags &= ~B_DELWRI;
1066 atomic_subtract_int(&numdirtybuffers, 1);
1067 numdirtywakeup(lodirtybuffers);
1070 * Since it is now being written, we can clear its deferred write flag.
1072 bp->b_flags &= ~B_DEFERRED;
1078 * Asynchronous write. Start output on a buffer, but do not wait for
1079 * it to complete. The buffer is released when the output completes.
1081 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1082 * B_INVAL buffers. Not us.
1085 bawrite(struct buf *bp)
1088 bp->b_flags |= B_ASYNC;
1095 * Called prior to the locking of any vnodes when we are expecting to
1096 * write. We do not want to starve the buffer cache with too many
1097 * dirty buffers so we block here. By blocking prior to the locking
1098 * of any vnodes we attempt to avoid the situation where a locked vnode
1099 * prevents the various system daemons from flushing related buffers.
1106 if (numdirtybuffers >= hidirtybuffers) {
1108 while (numdirtybuffers >= hidirtybuffers) {
1110 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
1111 msleep(&needsbuffer, &nblock,
1112 (PRIBIO + 4), "flswai", 0);
1114 mtx_unlock(&nblock);
1119 * Return true if we have too many dirty buffers.
1122 buf_dirty_count_severe(void)
1125 return(numdirtybuffers >= hidirtybuffers);
1131 * Release a busy buffer and, if requested, free its resources. The
1132 * buffer will be stashed in the appropriate bufqueue[] allowing it
1133 * to be accessed later as a cache entity or reused for other purposes.
1136 brelse(struct buf *bp)
1138 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
1139 bp, bp->b_vp, bp->b_flags);
1140 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1141 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1143 if (bp->b_flags & B_MANAGED) {
1148 if (bp->b_iocmd == BIO_WRITE &&
1149 (bp->b_ioflags & BIO_ERROR) &&
1150 !(bp->b_flags & B_INVAL)) {
1152 * Failed write, redirty. Must clear BIO_ERROR to prevent
1153 * pages from being scrapped. If B_INVAL is set then
1154 * this case is not run and the next case is run to
1155 * destroy the buffer. B_INVAL can occur if the buffer
1156 * is outside the range supported by the underlying device.
1158 bp->b_ioflags &= ~BIO_ERROR;
1160 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1161 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
1163 * Either a failed I/O or we were asked to free or not
1166 bp->b_flags |= B_INVAL;
1167 if (LIST_FIRST(&bp->b_dep) != NULL)
1169 if (bp->b_flags & B_DELWRI) {
1170 atomic_subtract_int(&numdirtybuffers, 1);
1171 numdirtywakeup(lodirtybuffers);
1173 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1174 if ((bp->b_flags & B_VMIO) == 0) {
1183 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1184 * is called with B_DELWRI set, the underlying pages may wind up
1185 * getting freed causing a previous write (bdwrite()) to get 'lost'
1186 * because pages associated with a B_DELWRI bp are marked clean.
1188 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1189 * if B_DELWRI is set.
1191 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1192 * on pages to return pages to the VM page queues.
1194 if (bp->b_flags & B_DELWRI)
1195 bp->b_flags &= ~B_RELBUF;
1196 else if (vm_page_count_severe()) {
1198 * XXX This lock may not be necessary since BKGRDINPROG
1199 * cannot be set while we hold the buf lock, it can only be
1200 * cleared if it is already pending.
1203 BO_LOCK(bp->b_bufobj);
1204 if (!(bp->b_vflags & BV_BKGRDINPROG))
1205 bp->b_flags |= B_RELBUF;
1206 BO_UNLOCK(bp->b_bufobj);
1208 bp->b_flags |= B_RELBUF;
1212 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1213 * constituted, not even NFS buffers now. Two flags effect this. If
1214 * B_INVAL, the struct buf is invalidated but the VM object is kept
1215 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1217 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1218 * invalidated. BIO_ERROR cannot be set for a failed write unless the
1219 * buffer is also B_INVAL because it hits the re-dirtying code above.
1221 * Normally we can do this whether a buffer is B_DELWRI or not. If
1222 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1223 * the commit state and we cannot afford to lose the buffer. If the
1224 * buffer has a background write in progress, we need to keep it
1225 * around to prevent it from being reconstituted and starting a second
1228 if ((bp->b_flags & B_VMIO)
1229 && !(bp->b_vp->v_mount != NULL &&
1230 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1231 !vn_isdisk(bp->b_vp, NULL) &&
1232 (bp->b_flags & B_DELWRI))
1241 obj = bp->b_bufobj->bo_object;
1244 * Get the base offset and length of the buffer. Note that
1245 * in the VMIO case if the buffer block size is not
1246 * page-aligned then b_data pointer may not be page-aligned.
1247 * But our b_pages[] array *IS* page aligned.
1249 * block sizes less then DEV_BSIZE (usually 512) are not
1250 * supported due to the page granularity bits (m->valid,
1251 * m->dirty, etc...).
1253 * See man buf(9) for more information
1255 resid = bp->b_bufsize;
1256 foff = bp->b_offset;
1257 VM_OBJECT_LOCK(obj);
1258 for (i = 0; i < bp->b_npages; i++) {
1264 * If we hit a bogus page, fixup *all* the bogus pages
1267 if (m == bogus_page) {
1268 poff = OFF_TO_IDX(bp->b_offset);
1271 for (j = i; j < bp->b_npages; j++) {
1273 mtmp = bp->b_pages[j];
1274 if (mtmp == bogus_page) {
1275 mtmp = vm_page_lookup(obj, poff + j);
1277 panic("brelse: page missing\n");
1279 bp->b_pages[j] = mtmp;
1283 if ((bp->b_flags & B_INVAL) == 0) {
1285 trunc_page((vm_offset_t)bp->b_data),
1286 bp->b_pages, bp->b_npages);
1290 if ((bp->b_flags & B_NOCACHE) ||
1291 (bp->b_ioflags & BIO_ERROR)) {
1292 int poffset = foff & PAGE_MASK;
1293 int presid = resid > (PAGE_SIZE - poffset) ?
1294 (PAGE_SIZE - poffset) : resid;
1296 KASSERT(presid >= 0, ("brelse: extra page"));
1297 vm_page_lock_queues();
1298 vm_page_set_invalid(m, poffset, presid);
1299 vm_page_unlock_queues();
1301 printf("avoided corruption bug in bogus_page/brelse code\n");
1303 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1304 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1306 VM_OBJECT_UNLOCK(obj);
1307 if (bp->b_flags & (B_INVAL | B_RELBUF))
1308 vfs_vmio_release(bp);
1310 } else if (bp->b_flags & B_VMIO) {
1312 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1313 vfs_vmio_release(bp);
1316 } else if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0) {
1317 if (bp->b_bufsize != 0)
1319 if (bp->b_vp != NULL)
1323 if (BUF_REFCNT(bp) > 1) {
1324 /* do not release to free list */
1331 /* Handle delayed bremfree() processing. */
1332 if (bp->b_flags & B_REMFREE)
1334 if (bp->b_qindex != QUEUE_NONE)
1335 panic("brelse: free buffer onto another queue???");
1337 /* buffers with no memory */
1338 if (bp->b_bufsize == 0) {
1339 bp->b_flags |= B_INVAL;
1340 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1341 if (bp->b_vflags & BV_BKGRDINPROG)
1342 panic("losing buffer 1");
1343 if (bp->b_kvasize) {
1344 bp->b_qindex = QUEUE_EMPTYKVA;
1346 bp->b_qindex = QUEUE_EMPTY;
1348 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1349 /* buffers with junk contents */
1350 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1351 (bp->b_ioflags & BIO_ERROR)) {
1352 bp->b_flags |= B_INVAL;
1353 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1354 if (bp->b_vflags & BV_BKGRDINPROG)
1355 panic("losing buffer 2");
1356 bp->b_qindex = QUEUE_CLEAN;
1357 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1358 /* remaining buffers */
1360 if ((bp->b_flags & (B_DELWRI|B_NEEDSGIANT)) ==
1361 (B_DELWRI|B_NEEDSGIANT))
1362 bp->b_qindex = QUEUE_DIRTY_GIANT;
1363 if (bp->b_flags & B_DELWRI)
1364 bp->b_qindex = QUEUE_DIRTY;
1366 bp->b_qindex = QUEUE_CLEAN;
1367 if (bp->b_flags & B_AGE)
1368 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1370 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1372 mtx_unlock(&bqlock);
1375 * If B_INVAL and B_DELWRI is set, clear B_DELWRI. We have already
1376 * placed the buffer on the correct queue. We must also disassociate
1377 * the device and vnode for a B_INVAL buffer so gbincore() doesn't
1380 if (bp->b_flags & B_INVAL) {
1381 if (bp->b_flags & B_DELWRI)
1388 * Fixup numfreebuffers count. The bp is on an appropriate queue
1389 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1390 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1391 * if B_INVAL is set ).
1394 if (!(bp->b_flags & B_DELWRI))
1398 * Something we can maybe free or reuse
1400 if (bp->b_bufsize || bp->b_kvasize)
1403 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1404 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1405 panic("brelse: not dirty");
1411 * Release a buffer back to the appropriate queue but do not try to free
1412 * it. The buffer is expected to be used again soon.
1414 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1415 * biodone() to requeue an async I/O on completion. It is also used when
1416 * known good buffers need to be requeued but we think we may need the data
1419 * XXX we should be able to leave the B_RELBUF hint set on completion.
1422 bqrelse(struct buf *bp)
1424 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1425 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1426 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1428 if (BUF_REFCNT(bp) > 1) {
1429 /* do not release to free list */
1434 if (bp->b_flags & B_MANAGED) {
1435 if (bp->b_flags & B_REMFREE) {
1438 mtx_unlock(&bqlock);
1440 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1446 /* Handle delayed bremfree() processing. */
1447 if (bp->b_flags & B_REMFREE)
1449 if (bp->b_qindex != QUEUE_NONE)
1450 panic("bqrelse: free buffer onto another queue???");
1451 /* buffers with stale but valid contents */
1452 if (bp->b_flags & B_DELWRI) {
1453 if (bp->b_flags & B_NEEDSGIANT)
1454 bp->b_qindex = QUEUE_DIRTY_GIANT;
1456 bp->b_qindex = QUEUE_DIRTY;
1457 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1460 * XXX This lock may not be necessary since BKGRDINPROG
1461 * cannot be set while we hold the buf lock, it can only be
1462 * cleared if it is already pending.
1464 BO_LOCK(bp->b_bufobj);
1465 if (!vm_page_count_severe() || bp->b_vflags & BV_BKGRDINPROG) {
1466 BO_UNLOCK(bp->b_bufobj);
1467 bp->b_qindex = QUEUE_CLEAN;
1468 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp,
1472 * We are too low on memory, we have to try to free
1473 * the buffer (most importantly: the wired pages
1474 * making up its backing store) *now*.
1476 BO_UNLOCK(bp->b_bufobj);
1477 mtx_unlock(&bqlock);
1482 mtx_unlock(&bqlock);
1484 if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))
1488 * Something we can maybe free or reuse.
1490 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1493 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1494 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1495 panic("bqrelse: not dirty");
1500 /* Give pages used by the bp back to the VM system (where possible) */
1502 vfs_vmio_release(struct buf *bp)
1507 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
1508 vm_page_lock_queues();
1509 for (i = 0; i < bp->b_npages; i++) {
1511 bp->b_pages[i] = NULL;
1513 * In order to keep page LRU ordering consistent, put
1514 * everything on the inactive queue.
1516 vm_page_unwire(m, 0);
1518 * We don't mess with busy pages, it is
1519 * the responsibility of the process that
1520 * busied the pages to deal with them.
1522 if ((m->flags & PG_BUSY) || (m->busy != 0))
1525 if (m->wire_count == 0) {
1527 * Might as well free the page if we can and it has
1528 * no valid data. We also free the page if the
1529 * buffer was used for direct I/O
1531 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1532 m->hold_count == 0) {
1534 } else if (bp->b_flags & B_DIRECT) {
1535 vm_page_try_to_free(m);
1536 } else if (vm_page_count_severe()) {
1537 vm_page_try_to_cache(m);
1541 vm_page_unlock_queues();
1542 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
1543 pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
1545 if (bp->b_bufsize) {
1550 bp->b_flags &= ~B_VMIO;
1556 * Check to see if a block at a particular lbn is available for a clustered
1560 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1567 /* If the buf isn't in core skip it */
1568 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1571 /* If the buf is busy we don't want to wait for it */
1572 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1575 /* Only cluster with valid clusterable delayed write buffers */
1576 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1577 (B_DELWRI | B_CLUSTEROK))
1580 if (bpa->b_bufsize != size)
1584 * Check to see if it is in the expected place on disk and that the
1585 * block has been mapped.
1587 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1597 * Implement clustered async writes for clearing out B_DELWRI buffers.
1598 * This is much better then the old way of writing only one buffer at
1599 * a time. Note that we may not be presented with the buffers in the
1600 * correct order, so we search for the cluster in both directions.
1603 vfs_bio_awrite(struct buf *bp)
1607 daddr_t lblkno = bp->b_lblkno;
1608 struct vnode *vp = bp->b_vp;
1615 * right now we support clustered writing only to regular files. If
1616 * we find a clusterable block we could be in the middle of a cluster
1617 * rather then at the beginning.
1619 if ((vp->v_type == VREG) &&
1620 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1621 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1623 size = vp->v_mount->mnt_stat.f_iosize;
1624 maxcl = MAXPHYS / size;
1627 for (i = 1; i < maxcl; i++)
1628 if (vfs_bio_clcheck(vp, size, lblkno + i,
1629 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1632 for (j = 1; i + j <= maxcl && j <= lblkno; j++)
1633 if (vfs_bio_clcheck(vp, size, lblkno - j,
1634 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
1641 * this is a possible cluster write
1645 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1650 bp->b_flags |= B_ASYNC;
1652 * default (old) behavior, writing out only one block
1654 * XXX returns b_bufsize instead of b_bcount for nwritten?
1656 nwritten = bp->b_bufsize;
1665 * Find and initialize a new buffer header, freeing up existing buffers
1666 * in the bufqueues as necessary. The new buffer is returned locked.
1668 * Important: B_INVAL is not set. If the caller wishes to throw the
1669 * buffer away, the caller must set B_INVAL prior to calling brelse().
1672 * We have insufficient buffer headers
1673 * We have insufficient buffer space
1674 * buffer_map is too fragmented ( space reservation fails )
1675 * If we have to flush dirty buffers ( but we try to avoid this )
1677 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1678 * Instead we ask the buf daemon to do it for us. We attempt to
1679 * avoid piecemeal wakeups of the pageout daemon.
1683 getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1689 static int flushingbufs;
1692 * We can't afford to block since we might be holding a vnode lock,
1693 * which may prevent system daemons from running. We deal with
1694 * low-memory situations by proactively returning memory and running
1695 * async I/O rather then sync I/O.
1698 atomic_add_int(&getnewbufcalls, 1);
1699 atomic_subtract_int(&getnewbufrestarts, 1);
1701 atomic_add_int(&getnewbufrestarts, 1);
1704 * Setup for scan. If we do not have enough free buffers,
1705 * we setup a degenerate case that immediately fails. Note
1706 * that if we are specially marked process, we are allowed to
1707 * dip into our reserves.
1709 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1711 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1712 * However, there are a number of cases (defragging, reusing, ...)
1713 * where we cannot backup.
1716 nqindex = QUEUE_EMPTYKVA;
1717 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1721 * If no EMPTYKVA buffers and we are either
1722 * defragging or reusing, locate a CLEAN buffer
1723 * to free or reuse. If bufspace useage is low
1724 * skip this step so we can allocate a new buffer.
1726 if (defrag || bufspace >= lobufspace) {
1727 nqindex = QUEUE_CLEAN;
1728 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1732 * If we could not find or were not allowed to reuse a
1733 * CLEAN buffer, check to see if it is ok to use an EMPTY
1734 * buffer. We can only use an EMPTY buffer if allocating
1735 * its KVA would not otherwise run us out of buffer space.
1737 if (nbp == NULL && defrag == 0 &&
1738 bufspace + maxsize < hibufspace) {
1739 nqindex = QUEUE_EMPTY;
1740 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1745 * Run scan, possibly freeing data and/or kva mappings on the fly
1749 while ((bp = nbp) != NULL) {
1750 int qindex = nqindex;
1753 * Calculate next bp ( we can only use it if we do not block
1754 * or do other fancy things ).
1756 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1759 nqindex = QUEUE_EMPTYKVA;
1760 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1763 case QUEUE_EMPTYKVA:
1764 nqindex = QUEUE_CLEAN;
1765 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1776 * If we are defragging then we need a buffer with
1777 * b_kvasize != 0. XXX this situation should no longer
1778 * occur, if defrag is non-zero the buffer's b_kvasize
1779 * should also be non-zero at this point. XXX
1781 if (defrag && bp->b_kvasize == 0) {
1782 printf("Warning: defrag empty buffer %p\n", bp);
1787 * Start freeing the bp. This is somewhat involved. nbp
1788 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1790 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1793 BO_LOCK(bp->b_bufobj);
1794 if (bp->b_vflags & BV_BKGRDINPROG) {
1795 BO_UNLOCK(bp->b_bufobj);
1799 BO_UNLOCK(bp->b_bufobj);
1802 "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
1803 "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
1804 bp->b_kvasize, bp->b_bufsize, qindex);
1809 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1812 * Note: we no longer distinguish between VMIO and non-VMIO
1816 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1819 mtx_unlock(&bqlock);
1821 if (qindex == QUEUE_CLEAN) {
1822 if (bp->b_flags & B_VMIO) {
1823 bp->b_flags &= ~B_ASYNC;
1824 vfs_vmio_release(bp);
1831 * NOTE: nbp is now entirely invalid. We can only restart
1832 * the scan from this point on.
1834 * Get the rest of the buffer freed up. b_kva* is still
1835 * valid after this operation.
1838 if (bp->b_rcred != NOCRED) {
1839 crfree(bp->b_rcred);
1840 bp->b_rcred = NOCRED;
1842 if (bp->b_wcred != NOCRED) {
1843 crfree(bp->b_wcred);
1844 bp->b_wcred = NOCRED;
1846 if (LIST_FIRST(&bp->b_dep) != NULL)
1848 if (bp->b_vflags & BV_BKGRDINPROG)
1849 panic("losing buffer 3");
1850 KASSERT(bp->b_vp == NULL,
1851 ("bp: %p still has vnode %p. qindex: %d",
1852 bp, bp->b_vp, qindex));
1853 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
1854 ("bp: %p still on a buffer list. xflags %X",
1865 bp->b_blkno = bp->b_lblkno = 0;
1866 bp->b_offset = NOOFFSET;
1872 bp->b_dirtyoff = bp->b_dirtyend = 0;
1873 bp->b_bufobj = NULL;
1874 bp->b_pin_count = 0;
1875 bp->b_fsprivate1 = NULL;
1876 bp->b_fsprivate2 = NULL;
1877 bp->b_fsprivate3 = NULL;
1879 LIST_INIT(&bp->b_dep);
1882 * If we are defragging then free the buffer.
1885 bp->b_flags |= B_INVAL;
1893 * If we are overcomitted then recover the buffer and its
1894 * KVM space. This occurs in rare situations when multiple
1895 * processes are blocked in getnewbuf() or allocbuf().
1897 if (bufspace >= hibufspace)
1899 if (flushingbufs && bp->b_kvasize != 0) {
1900 bp->b_flags |= B_INVAL;
1905 if (bufspace < lobufspace)
1911 * If we exhausted our list, sleep as appropriate. We may have to
1912 * wakeup various daemons and write out some dirty buffers.
1914 * Generally we are sleeping due to insufficient buffer space.
1922 flags = VFS_BIO_NEED_BUFSPACE;
1924 } else if (bufspace >= hibufspace) {
1926 flags = VFS_BIO_NEED_BUFSPACE;
1929 flags = VFS_BIO_NEED_ANY;
1932 needsbuffer |= flags;
1933 mtx_unlock(&nblock);
1934 mtx_unlock(&bqlock);
1936 bd_speedup(); /* heeeelp */
1939 while (needsbuffer & flags) {
1940 if (msleep(&needsbuffer, &nblock,
1941 (PRIBIO + 4) | slpflag, waitmsg, slptimeo)) {
1942 mtx_unlock(&nblock);
1946 mtx_unlock(&nblock);
1949 * We finally have a valid bp. We aren't quite out of the
1950 * woods, we still have to reserve kva space. In order
1951 * to keep fragmentation sane we only allocate kva in
1954 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1956 if (maxsize != bp->b_kvasize) {
1957 vm_offset_t addr = 0;
1961 vm_map_lock(buffer_map);
1962 if (vm_map_findspace(buffer_map,
1963 vm_map_min(buffer_map), maxsize, &addr)) {
1965 * Uh oh. Buffer map is to fragmented. We
1966 * must defragment the map.
1968 atomic_add_int(&bufdefragcnt, 1);
1969 vm_map_unlock(buffer_map);
1971 bp->b_flags |= B_INVAL;
1976 vm_map_insert(buffer_map, NULL, 0,
1977 addr, addr + maxsize,
1978 VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
1980 bp->b_kvabase = (caddr_t) addr;
1981 bp->b_kvasize = maxsize;
1982 atomic_add_int(&bufspace, bp->b_kvasize);
1983 atomic_add_int(&bufreusecnt, 1);
1985 vm_map_unlock(buffer_map);
1987 bp->b_saveaddr = bp->b_kvabase;
1988 bp->b_data = bp->b_saveaddr;
1996 * buffer flushing daemon. Buffers are normally flushed by the
1997 * update daemon but if it cannot keep up this process starts to
1998 * take the load in an attempt to prevent getnewbuf() from blocking.
2001 static struct kproc_desc buf_kp = {
2006 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
2013 * This process needs to be suspended prior to shutdown sync.
2015 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2019 * This process is allowed to take the buffer cache to the limit
2021 curthread->td_pflags |= TDP_NORUNNINGBUF;
2025 mtx_unlock(&bdlock);
2027 kthread_suspend_check(bufdaemonproc);
2030 * Do the flush. Limit the amount of in-transit I/O we
2031 * allow to build up, otherwise we would completely saturate
2032 * the I/O system. Wakeup any waiting processes before we
2033 * normally would so they can run in parallel with our drain.
2035 while (numdirtybuffers > lodirtybuffers) {
2038 flushed = flushbufqueues(QUEUE_DIRTY, 0);
2039 /* The list empty check here is slightly racy */
2040 if (!TAILQ_EMPTY(&bufqueues[QUEUE_DIRTY_GIANT])) {
2042 flushed += flushbufqueues(QUEUE_DIRTY_GIANT, 0);
2047 * Could not find any buffers without rollback
2048 * dependencies, so just write the first one
2049 * in the hopes of eventually making progress.
2051 flushbufqueues(QUEUE_DIRTY, 1);
2053 &bufqueues[QUEUE_DIRTY_GIANT])) {
2055 flushbufqueues(QUEUE_DIRTY_GIANT, 1);
2064 * Only clear bd_request if we have reached our low water
2065 * mark. The buf_daemon normally waits 1 second and
2066 * then incrementally flushes any dirty buffers that have
2067 * built up, within reason.
2069 * If we were unable to hit our low water mark and couldn't
2070 * find any flushable buffers, we sleep half a second.
2071 * Otherwise we loop immediately.
2074 if (numdirtybuffers <= lodirtybuffers) {
2076 * We reached our low water mark, reset the
2077 * request and sleep until we are needed again.
2078 * The sleep is just so the suspend code works.
2081 msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2084 * We couldn't find any flushable dirty buffers but
2085 * still have too many dirty buffers, we
2086 * have to sleep and try again. (rare)
2088 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2096 * Try to flush a buffer in the dirty queue. We must be careful to
2097 * free up B_INVAL buffers instead of write them, which NFS is
2098 * particularly sensitive to.
2100 static int flushwithdeps = 0;
2101 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2102 0, "Number of buffers flushed with dependecies that require rollbacks");
2105 flushbufqueues(int queue, int flushdeps)
2107 struct thread *td = curthread;
2108 struct buf sentinel;
2116 target = numdirtybuffers - lodirtybuffers;
2117 if (flushdeps && target > 2)
2122 TAILQ_INSERT_TAIL(&bufqueues[queue], &sentinel, b_freelist);
2123 while (flushed != target) {
2124 bp = TAILQ_FIRST(&bufqueues[queue]);
2125 if (bp == &sentinel)
2127 TAILQ_REMOVE(&bufqueues[queue], bp, b_freelist);
2128 TAILQ_INSERT_TAIL(&bufqueues[queue], bp, b_freelist);
2130 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2132 if (bp->b_pin_count > 0) {
2136 BO_LOCK(bp->b_bufobj);
2137 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2138 (bp->b_flags & B_DELWRI) == 0) {
2139 BO_UNLOCK(bp->b_bufobj);
2143 BO_UNLOCK(bp->b_bufobj);
2144 if (bp->b_flags & B_INVAL) {
2146 mtx_unlock(&bqlock);
2149 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2154 if (LIST_FIRST(&bp->b_dep) != NULL && buf_countdeps(bp, 0)) {
2155 if (flushdeps == 0) {
2163 * We must hold the lock on a vnode before writing
2164 * one of its buffers. Otherwise we may confuse, or
2165 * in the case of a snapshot vnode, deadlock the
2168 * The lock order here is the reverse of the normal
2169 * of vnode followed by buf lock. This is ok because
2170 * the NOWAIT will prevent deadlock.
2173 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2177 if (vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT, td) == 0) {
2178 mtx_unlock(&bqlock);
2179 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2180 bp, bp->b_vp, bp->b_flags);
2182 vn_finished_write(mp);
2183 VOP_UNLOCK(vp, 0, td);
2184 flushwithdeps += hasdeps;
2186 waitrunningbufspace();
2187 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2191 vn_finished_write(mp);
2194 TAILQ_REMOVE(&bufqueues[queue], &sentinel, b_freelist);
2195 mtx_unlock(&bqlock);
2200 * Check to see if a block is currently memory resident.
2203 incore(struct bufobj *bo, daddr_t blkno)
2208 bp = gbincore(bo, blkno);
2214 * Returns true if no I/O is needed to access the
2215 * associated VM object. This is like incore except
2216 * it also hunts around in the VM system for the data.
2220 inmem(struct vnode * vp, daddr_t blkno)
2223 vm_offset_t toff, tinc, size;
2227 ASSERT_VOP_LOCKED(vp, "inmem");
2229 if (incore(&vp->v_bufobj, blkno))
2231 if (vp->v_mount == NULL)
2238 if (size > vp->v_mount->mnt_stat.f_iosize)
2239 size = vp->v_mount->mnt_stat.f_iosize;
2240 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2242 VM_OBJECT_LOCK(obj);
2243 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2244 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2248 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2249 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2250 if (vm_page_is_valid(m,
2251 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2254 VM_OBJECT_UNLOCK(obj);
2258 VM_OBJECT_UNLOCK(obj);
2265 * Sets the dirty range for a buffer based on the status of the dirty
2266 * bits in the pages comprising the buffer.
2268 * The range is limited to the size of the buffer.
2270 * This routine is primarily used by NFS, but is generalized for the
2274 vfs_setdirty(struct buf *bp)
2280 * Degenerate case - empty buffer
2283 if (bp->b_bufsize == 0)
2287 * We qualify the scan for modified pages on whether the
2288 * object has been flushed yet.
2291 if ((bp->b_flags & B_VMIO) == 0)
2294 object = bp->b_pages[0]->object;
2295 VM_OBJECT_LOCK(object);
2296 if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2297 vm_offset_t boffset;
2298 vm_offset_t eoffset;
2300 vm_page_lock_queues();
2302 * test the pages to see if they have been modified directly
2303 * by users through the VM system.
2305 for (i = 0; i < bp->b_npages; i++)
2306 vm_page_test_dirty(bp->b_pages[i]);
2309 * Calculate the encompassing dirty range, boffset and eoffset,
2310 * (eoffset - boffset) bytes.
2313 for (i = 0; i < bp->b_npages; i++) {
2314 if (bp->b_pages[i]->dirty)
2317 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2319 for (i = bp->b_npages - 1; i >= 0; --i) {
2320 if (bp->b_pages[i]->dirty) {
2324 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2326 vm_page_unlock_queues();
2328 * Fit it to the buffer.
2331 if (eoffset > bp->b_bcount)
2332 eoffset = bp->b_bcount;
2335 * If we have a good dirty range, merge with the existing
2339 if (boffset < eoffset) {
2340 if (bp->b_dirtyoff > boffset)
2341 bp->b_dirtyoff = boffset;
2342 if (bp->b_dirtyend < eoffset)
2343 bp->b_dirtyend = eoffset;
2346 VM_OBJECT_UNLOCK(object);
2352 * Get a block given a specified block and offset into a file/device.
2353 * The buffers B_DONE bit will be cleared on return, making it almost
2354 * ready for an I/O initiation. B_INVAL may or may not be set on
2355 * return. The caller should clear B_INVAL prior to initiating a
2358 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2359 * an existing buffer.
2361 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2362 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2363 * and then cleared based on the backing VM. If the previous buffer is
2364 * non-0-sized but invalid, B_CACHE will be cleared.
2366 * If getblk() must create a new buffer, the new buffer is returned with
2367 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2368 * case it is returned with B_INVAL clear and B_CACHE set based on the
2371 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
2372 * B_CACHE bit is clear.
2374 * What this means, basically, is that the caller should use B_CACHE to
2375 * determine whether the buffer is fully valid or not and should clear
2376 * B_INVAL prior to issuing a read. If the caller intends to validate
2377 * the buffer by loading its data area with something, the caller needs
2378 * to clear B_INVAL. If the caller does this without issuing an I/O,
2379 * the caller should set B_CACHE ( as an optimization ), else the caller
2380 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2381 * a write attempt or if it was a successfull read. If the caller
2382 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
2383 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2386 getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo,
2393 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
2394 ASSERT_VOP_LOCKED(vp, "getblk");
2395 if (size > MAXBSIZE)
2396 panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2401 * Block if we are low on buffers. Certain processes are allowed
2402 * to completely exhaust the buffer cache.
2404 * If this check ever becomes a bottleneck it may be better to
2405 * move it into the else, when gbincore() fails. At the moment
2406 * it isn't a problem.
2408 * XXX remove if 0 sections (clean this up after its proven)
2410 if (numfreebuffers == 0) {
2411 if (curthread == PCPU_GET(idlethread))
2414 needsbuffer |= VFS_BIO_NEED_ANY;
2415 mtx_unlock(&nblock);
2419 bp = gbincore(bo, blkno);
2423 * Buffer is in-core. If the buffer is not busy, it must
2426 lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
2428 if (flags & GB_LOCK_NOWAIT)
2429 lockflags |= LK_NOWAIT;
2431 error = BUF_TIMELOCK(bp, lockflags,
2432 VI_MTX(vp), "getblk", slpflag, slptimeo);
2435 * If we slept and got the lock we have to restart in case
2436 * the buffer changed identities.
2438 if (error == ENOLCK)
2440 /* We timed out or were interrupted. */
2445 * The buffer is locked. B_CACHE is cleared if the buffer is
2446 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
2447 * and for a VMIO buffer B_CACHE is adjusted according to the
2450 if (bp->b_flags & B_INVAL)
2451 bp->b_flags &= ~B_CACHE;
2452 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2453 bp->b_flags |= B_CACHE;
2457 * check for size inconsistancies for non-VMIO case.
2460 if (bp->b_bcount != size) {
2461 if ((bp->b_flags & B_VMIO) == 0 ||
2462 (size > bp->b_kvasize)) {
2463 if (bp->b_flags & B_DELWRI) {
2465 * If buffer is pinned and caller does
2466 * not want sleep waiting for it to be
2467 * unpinned, bail out
2469 if (bp->b_pin_count > 0) {
2470 if (flags & GB_LOCK_NOWAIT) {
2477 bp->b_flags |= B_NOCACHE;
2480 if (LIST_FIRST(&bp->b_dep) == NULL) {
2481 bp->b_flags |= B_RELBUF;
2484 bp->b_flags |= B_NOCACHE;
2493 * If the size is inconsistant in the VMIO case, we can resize
2494 * the buffer. This might lead to B_CACHE getting set or
2495 * cleared. If the size has not changed, B_CACHE remains
2496 * unchanged from its previous state.
2499 if (bp->b_bcount != size)
2502 KASSERT(bp->b_offset != NOOFFSET,
2503 ("getblk: no buffer offset"));
2506 * A buffer with B_DELWRI set and B_CACHE clear must
2507 * be committed before we can return the buffer in
2508 * order to prevent the caller from issuing a read
2509 * ( due to B_CACHE not being set ) and overwriting
2512 * Most callers, including NFS and FFS, need this to
2513 * operate properly either because they assume they
2514 * can issue a read if B_CACHE is not set, or because
2515 * ( for example ) an uncached B_DELWRI might loop due
2516 * to softupdates re-dirtying the buffer. In the latter
2517 * case, B_CACHE is set after the first write completes,
2518 * preventing further loops.
2519 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2520 * above while extending the buffer, we cannot allow the
2521 * buffer to remain with B_CACHE set after the write
2522 * completes or it will represent a corrupt state. To
2523 * deal with this we set B_NOCACHE to scrap the buffer
2526 * We might be able to do something fancy, like setting
2527 * B_CACHE in bwrite() except if B_DELWRI is already set,
2528 * so the below call doesn't set B_CACHE, but that gets real
2529 * confusing. This is much easier.
2532 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2533 bp->b_flags |= B_NOCACHE;
2537 bp->b_flags &= ~B_DONE;
2539 int bsize, maxsize, vmio;
2543 * Buffer is not in-core, create new buffer. The buffer
2544 * returned by getnewbuf() is locked. Note that the returned
2545 * buffer is also considered valid (not marked B_INVAL).
2549 * If the user does not want us to create the buffer, bail out
2552 if (flags & GB_NOCREAT)
2554 bsize = bo->bo_bsize;
2555 offset = blkno * bsize;
2556 vmio = vp->v_object != NULL;
2557 maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2558 maxsize = imax(maxsize, bsize);
2560 bp = getnewbuf(slpflag, slptimeo, size, maxsize);
2562 if (slpflag || slptimeo)
2568 * This code is used to make sure that a buffer is not
2569 * created while the getnewbuf routine is blocked.
2570 * This can be a problem whether the vnode is locked or not.
2571 * If the buffer is created out from under us, we have to
2572 * throw away the one we just created.
2574 * Note: this must occur before we associate the buffer
2575 * with the vp especially considering limitations in
2576 * the splay tree implementation when dealing with duplicate
2580 if (gbincore(bo, blkno)) {
2582 bp->b_flags |= B_INVAL;
2588 * Insert the buffer into the hash, so that it can
2589 * be found by incore.
2591 bp->b_blkno = bp->b_lblkno = blkno;
2592 bp->b_offset = offset;
2597 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
2598 * buffer size starts out as 0, B_CACHE will be set by
2599 * allocbuf() for the VMIO case prior to it testing the
2600 * backing store for validity.
2604 bp->b_flags |= B_VMIO;
2605 #if defined(VFS_BIO_DEBUG)
2606 if (vn_canvmio(vp) != TRUE)
2607 printf("getblk: VMIO on vnode type %d\n",
2610 KASSERT(vp->v_object == bp->b_bufobj->bo_object,
2611 ("ARGH! different b_bufobj->bo_object %p %p %p\n",
2612 bp, vp->v_object, bp->b_bufobj->bo_object));
2614 bp->b_flags &= ~B_VMIO;
2615 KASSERT(bp->b_bufobj->bo_object == NULL,
2616 ("ARGH! has b_bufobj->bo_object %p %p\n",
2617 bp, bp->b_bufobj->bo_object));
2621 bp->b_flags &= ~B_DONE;
2623 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
2624 KASSERT(BUF_REFCNT(bp) == 1, ("getblk: bp %p not locked",bp));
2625 KASSERT(bp->b_bufobj == bo,
2626 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2631 * Get an empty, disassociated buffer of given size. The buffer is initially
2640 maxsize = (size + BKVAMASK) & ~BKVAMASK;
2641 while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2644 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2645 KASSERT(BUF_REFCNT(bp) == 1, ("geteblk: bp %p not locked",bp));
2651 * This code constitutes the buffer memory from either anonymous system
2652 * memory (in the case of non-VMIO operations) or from an associated
2653 * VM object (in the case of VMIO operations). This code is able to
2654 * resize a buffer up or down.
2656 * Note that this code is tricky, and has many complications to resolve
2657 * deadlock or inconsistant data situations. Tread lightly!!!
2658 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2659 * the caller. Calling this code willy nilly can result in the loss of data.
2661 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2662 * B_CACHE for the non-VMIO case.
2666 allocbuf(struct buf *bp, int size)
2668 int newbsize, mbsize;
2671 if (BUF_REFCNT(bp) == 0)
2672 panic("allocbuf: buffer not busy");
2674 if (bp->b_kvasize < size)
2675 panic("allocbuf: buffer too small");
2677 if ((bp->b_flags & B_VMIO) == 0) {
2681 * Just get anonymous memory from the kernel. Don't
2682 * mess with B_CACHE.
2684 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2685 if (bp->b_flags & B_MALLOC)
2688 newbsize = round_page(size);
2690 if (newbsize < bp->b_bufsize) {
2692 * malloced buffers are not shrunk
2694 if (bp->b_flags & B_MALLOC) {
2696 bp->b_bcount = size;
2698 free(bp->b_data, M_BIOBUF);
2699 if (bp->b_bufsize) {
2700 atomic_subtract_int(
2706 bp->b_saveaddr = bp->b_kvabase;
2707 bp->b_data = bp->b_saveaddr;
2709 bp->b_flags &= ~B_MALLOC;
2715 (vm_offset_t) bp->b_data + newbsize,
2716 (vm_offset_t) bp->b_data + bp->b_bufsize);
2717 } else if (newbsize > bp->b_bufsize) {
2719 * We only use malloced memory on the first allocation.
2720 * and revert to page-allocated memory when the buffer
2724 * There is a potential smp race here that could lead
2725 * to bufmallocspace slightly passing the max. It
2726 * is probably extremely rare and not worth worrying
2729 if ( (bufmallocspace < maxbufmallocspace) &&
2730 (bp->b_bufsize == 0) &&
2731 (mbsize <= PAGE_SIZE/2)) {
2733 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2734 bp->b_bufsize = mbsize;
2735 bp->b_bcount = size;
2736 bp->b_flags |= B_MALLOC;
2737 atomic_add_int(&bufmallocspace, mbsize);
2743 * If the buffer is growing on its other-than-first allocation,
2744 * then we revert to the page-allocation scheme.
2746 if (bp->b_flags & B_MALLOC) {
2747 origbuf = bp->b_data;
2748 origbufsize = bp->b_bufsize;
2749 bp->b_data = bp->b_kvabase;
2750 if (bp->b_bufsize) {
2751 atomic_subtract_int(&bufmallocspace,
2756 bp->b_flags &= ~B_MALLOC;
2757 newbsize = round_page(newbsize);
2761 (vm_offset_t) bp->b_data + bp->b_bufsize,
2762 (vm_offset_t) bp->b_data + newbsize);
2764 bcopy(origbuf, bp->b_data, origbufsize);
2765 free(origbuf, M_BIOBUF);
2771 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2772 desiredpages = (size == 0) ? 0 :
2773 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2775 if (bp->b_flags & B_MALLOC)
2776 panic("allocbuf: VMIO buffer can't be malloced");
2778 * Set B_CACHE initially if buffer is 0 length or will become
2781 if (size == 0 || bp->b_bufsize == 0)
2782 bp->b_flags |= B_CACHE;
2784 if (newbsize < bp->b_bufsize) {
2786 * DEV_BSIZE aligned new buffer size is less then the
2787 * DEV_BSIZE aligned existing buffer size. Figure out
2788 * if we have to remove any pages.
2790 if (desiredpages < bp->b_npages) {
2793 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
2794 vm_page_lock_queues();
2795 for (i = desiredpages; i < bp->b_npages; i++) {
2797 * the page is not freed here -- it
2798 * is the responsibility of
2799 * vnode_pager_setsize
2802 KASSERT(m != bogus_page,
2803 ("allocbuf: bogus page found"));
2804 while (vm_page_sleep_if_busy(m, TRUE, "biodep"))
2805 vm_page_lock_queues();
2807 bp->b_pages[i] = NULL;
2808 vm_page_unwire(m, 0);
2810 vm_page_unlock_queues();
2811 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
2812 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2813 (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
2814 bp->b_npages = desiredpages;
2816 } else if (size > bp->b_bcount) {
2818 * We are growing the buffer, possibly in a
2819 * byte-granular fashion.
2827 * Step 1, bring in the VM pages from the object,
2828 * allocating them if necessary. We must clear
2829 * B_CACHE if these pages are not valid for the
2830 * range covered by the buffer.
2834 obj = bp->b_bufobj->bo_object;
2836 VM_OBJECT_LOCK(obj);
2837 while (bp->b_npages < desiredpages) {
2841 pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
2842 if ((m = vm_page_lookup(obj, pi)) == NULL) {
2844 * note: must allocate system pages
2845 * since blocking here could intefere
2846 * with paging I/O, no matter which
2849 m = vm_page_alloc(obj, pi,
2850 VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM |
2853 atomic_add_int(&vm_pageout_deficit,
2854 desiredpages - bp->b_npages);
2855 VM_OBJECT_UNLOCK(obj);
2857 VM_OBJECT_LOCK(obj);
2859 bp->b_flags &= ~B_CACHE;
2860 bp->b_pages[bp->b_npages] = m;
2867 * We found a page. If we have to sleep on it,
2868 * retry because it might have gotten freed out
2871 * We can only test PG_BUSY here. Blocking on
2872 * m->busy might lead to a deadlock:
2874 * vm_fault->getpages->cluster_read->allocbuf
2877 vm_page_lock_queues();
2878 if (vm_page_sleep_if_busy(m, FALSE, "pgtblk"))
2882 * We have a good page. Should we wakeup the
2885 if ((curproc != pageproc) &&
2886 (VM_PAGE_INQUEUE1(m, PQ_CACHE)) &&
2887 ((cnt.v_free_count + cnt.v_cache_count) <
2888 (cnt.v_free_min + cnt.v_cache_min))) {
2889 pagedaemon_wakeup();
2892 vm_page_unlock_queues();
2893 bp->b_pages[bp->b_npages] = m;
2898 * Step 2. We've loaded the pages into the buffer,
2899 * we have to figure out if we can still have B_CACHE
2900 * set. Note that B_CACHE is set according to the
2901 * byte-granular range ( bcount and size ), new the
2902 * aligned range ( newbsize ).
2904 * The VM test is against m->valid, which is DEV_BSIZE
2905 * aligned. Needless to say, the validity of the data
2906 * needs to also be DEV_BSIZE aligned. Note that this
2907 * fails with NFS if the server or some other client
2908 * extends the file's EOF. If our buffer is resized,
2909 * B_CACHE may remain set! XXX
2912 toff = bp->b_bcount;
2913 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2915 while ((bp->b_flags & B_CACHE) && toff < size) {
2918 if (tinc > (size - toff))
2921 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2934 VM_OBJECT_UNLOCK(obj);
2937 * Step 3, fixup the KVM pmap. Remember that
2938 * bp->b_data is relative to bp->b_offset, but
2939 * bp->b_offset may be offset into the first page.
2942 bp->b_data = (caddr_t)
2943 trunc_page((vm_offset_t)bp->b_data);
2945 (vm_offset_t)bp->b_data,
2950 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2951 (vm_offset_t)(bp->b_offset & PAGE_MASK));
2954 if (newbsize < bp->b_bufsize)
2956 bp->b_bufsize = newbsize; /* actual buffer allocation */
2957 bp->b_bcount = size; /* requested buffer size */
2962 biodone(struct bio *bp)
2964 void (*done)(struct bio *);
2966 mtx_lock(&bdonelock);
2967 bp->bio_flags |= BIO_DONE;
2968 done = bp->bio_done;
2971 mtx_unlock(&bdonelock);
2977 * Wait for a BIO to finish.
2979 * XXX: resort to a timeout for now. The optimal locking (if any) for this
2980 * case is not yet clear.
2983 biowait(struct bio *bp, const char *wchan)
2986 mtx_lock(&bdonelock);
2987 while ((bp->bio_flags & BIO_DONE) == 0)
2988 msleep(bp, &bdonelock, PRIBIO, wchan, hz / 10);
2989 mtx_unlock(&bdonelock);
2990 if (bp->bio_error != 0)
2991 return (bp->bio_error);
2992 if (!(bp->bio_flags & BIO_ERROR))
2998 biofinish(struct bio *bp, struct devstat *stat, int error)
3002 bp->bio_error = error;
3003 bp->bio_flags |= BIO_ERROR;
3006 devstat_end_transaction_bio(stat, bp);
3013 * Wait for buffer I/O completion, returning error status. The buffer
3014 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR
3015 * error and cleared.
3018 bufwait(struct buf *bp)
3020 if (bp->b_iocmd == BIO_READ)
3021 bwait(bp, PRIBIO, "biord");
3023 bwait(bp, PRIBIO, "biowr");
3024 if (bp->b_flags & B_EINTR) {
3025 bp->b_flags &= ~B_EINTR;
3028 if (bp->b_ioflags & BIO_ERROR) {
3029 return (bp->b_error ? bp->b_error : EIO);
3036 * Call back function from struct bio back up to struct buf.
3039 bufdonebio(struct bio *bip)
3043 bp = bip->bio_caller2;
3044 bp->b_resid = bp->b_bcount - bip->bio_completed;
3045 bp->b_resid = bip->bio_resid; /* XXX: remove */
3046 bp->b_ioflags = bip->bio_flags;
3047 bp->b_error = bip->bio_error;
3049 bp->b_ioflags |= BIO_ERROR;
3055 dev_strategy(struct cdev *dev, struct buf *bp)
3060 if ((!bp->b_iocmd) || (bp->b_iocmd & (bp->b_iocmd - 1)))
3061 panic("b_iocmd botch");
3066 /* Try again later */
3067 tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3069 bip->bio_cmd = bp->b_iocmd;
3070 bip->bio_offset = bp->b_iooffset;
3071 bip->bio_length = bp->b_bcount;
3072 bip->bio_bcount = bp->b_bcount; /* XXX: remove */
3073 bip->bio_data = bp->b_data;
3074 bip->bio_done = bufdonebio;
3075 bip->bio_caller2 = bp;
3077 KASSERT(dev->si_refcount > 0,
3078 ("dev_strategy on un-referenced struct cdev *(%s)",
3080 csw = dev_refthread(dev);
3083 bp->b_error = ENXIO;
3084 bp->b_ioflags = BIO_ERROR;
3088 (*csw->d_strategy)(bip);
3095 * Finish I/O on a buffer, optionally calling a completion function.
3096 * This is usually called from an interrupt so process blocking is
3099 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3100 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3101 * assuming B_INVAL is clear.
3103 * For the VMIO case, we set B_CACHE if the op was a read and no
3104 * read error occured, or if the op was a write. B_CACHE is never
3105 * set if the buffer is invalid or otherwise uncacheable.
3107 * biodone does not mess with B_INVAL, allowing the I/O routine or the
3108 * initiator to leave B_INVAL set to brelse the buffer out of existance
3109 * in the biodone routine.
3112 bufdone(struct buf *bp)
3114 struct bufobj *dropobj;
3115 void (*biodone)(struct buf *);
3117 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3120 KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp,
3122 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3124 runningbufwakeup(bp);
3125 if (bp->b_iocmd == BIO_WRITE)
3126 dropobj = bp->b_bufobj;
3127 /* call optional completion function if requested */
3128 if (bp->b_iodone != NULL) {
3129 biodone = bp->b_iodone;
3130 bp->b_iodone = NULL;
3133 bufobj_wdrop(dropobj);
3140 bufobj_wdrop(dropobj);
3144 bufdone_finish(struct buf *bp)
3146 KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp,
3149 if (LIST_FIRST(&bp->b_dep) != NULL)
3152 if (bp->b_flags & B_VMIO) {
3158 struct vnode *vp = bp->b_vp;
3160 obj = bp->b_bufobj->bo_object;
3162 #if defined(VFS_BIO_DEBUG)
3163 mp_fixme("usecount and vflag accessed without locks.");
3164 if (vp->v_usecount == 0) {
3165 panic("biodone: zero vnode ref count");
3168 KASSERT(vp->v_object != NULL,
3169 ("biodone: vnode %p has no vm_object", vp));
3172 foff = bp->b_offset;
3173 KASSERT(bp->b_offset != NOOFFSET,
3174 ("biodone: no buffer offset"));
3176 VM_OBJECT_LOCK(obj);
3177 #if defined(VFS_BIO_DEBUG)
3178 if (obj->paging_in_progress < bp->b_npages) {
3179 printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
3180 obj->paging_in_progress, bp->b_npages);
3185 * Set B_CACHE if the op was a normal read and no error
3186 * occured. B_CACHE is set for writes in the b*write()
3189 iosize = bp->b_bcount - bp->b_resid;
3190 if (bp->b_iocmd == BIO_READ &&
3191 !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3192 !(bp->b_ioflags & BIO_ERROR)) {
3193 bp->b_flags |= B_CACHE;
3195 vm_page_lock_queues();
3196 for (i = 0; i < bp->b_npages; i++) {
3200 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3205 * cleanup bogus pages, restoring the originals
3208 if (m == bogus_page) {
3210 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3212 panic("biodone: page disappeared!");
3214 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3215 bp->b_pages, bp->b_npages);
3217 #if defined(VFS_BIO_DEBUG)
3218 if (OFF_TO_IDX(foff) != m->pindex) {
3220 "biodone: foff(%jd)/m->pindex(%ju) mismatch\n",
3221 (intmax_t)foff, (uintmax_t)m->pindex);
3226 * In the write case, the valid and clean bits are
3227 * already changed correctly ( see bdwrite() ), so we
3228 * only need to do this here in the read case.
3230 if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3231 vfs_page_set_valid(bp, foff, i, m);
3235 * when debugging new filesystems or buffer I/O methods, this
3236 * is the most common error that pops up. if you see this, you
3237 * have not set the page busy flag correctly!!!
3240 printf("biodone: page busy < 0, "
3241 "pindex: %d, foff: 0x(%x,%x), "
3242 "resid: %d, index: %d\n",
3243 (int) m->pindex, (int)(foff >> 32),
3244 (int) foff & 0xffffffff, resid, i);
3245 if (!vn_isdisk(vp, NULL))
3246 printf(" iosize: %jd, lblkno: %jd, flags: 0x%x, npages: %d\n",
3247 (intmax_t)bp->b_vp->v_mount->mnt_stat.f_iosize,
3248 (intmax_t) bp->b_lblkno,
3249 bp->b_flags, bp->b_npages);
3251 printf(" VDEV, lblkno: %jd, flags: 0x%x, npages: %d\n",
3252 (intmax_t) bp->b_lblkno,
3253 bp->b_flags, bp->b_npages);
3254 printf(" valid: 0x%lx, dirty: 0x%lx, wired: %d\n",
3255 (u_long)m->valid, (u_long)m->dirty,
3257 panic("biodone: page busy < 0\n");
3259 vm_page_io_finish(m);
3260 vm_object_pip_subtract(obj, 1);
3261 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3264 vm_page_unlock_queues();
3265 vm_object_pip_wakeupn(obj, 0);
3266 VM_OBJECT_UNLOCK(obj);
3270 * For asynchronous completions, release the buffer now. The brelse
3271 * will do a wakeup there if necessary - so no need to do a wakeup
3272 * here in the async case. The sync case always needs to do a wakeup.
3275 if (bp->b_flags & B_ASYNC) {
3276 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3285 * This routine is called in lieu of iodone in the case of
3286 * incomplete I/O. This keeps the busy status for pages
3290 vfs_unbusy_pages(struct buf *bp)
3296 runningbufwakeup(bp);
3297 if (!(bp->b_flags & B_VMIO))
3300 obj = bp->b_bufobj->bo_object;
3301 VM_OBJECT_LOCK(obj);
3302 for (i = 0; i < bp->b_npages; i++) {
3304 if (m == bogus_page) {
3305 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3307 panic("vfs_unbusy_pages: page missing\n");
3309 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3310 bp->b_pages, bp->b_npages);
3312 vm_object_pip_subtract(obj, 1);
3313 vm_page_io_finish(m);
3315 vm_object_pip_wakeupn(obj, 0);
3316 VM_OBJECT_UNLOCK(obj);
3320 * vfs_page_set_valid:
3322 * Set the valid bits in a page based on the supplied offset. The
3323 * range is restricted to the buffer's size.
3325 * This routine is typically called after a read completes.
3328 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3330 vm_ooffset_t soff, eoff;
3332 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
3334 * Start and end offsets in buffer. eoff - soff may not cross a
3335 * page boundry or cross the end of the buffer. The end of the
3336 * buffer, in this case, is our file EOF, not the allocation size
3340 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3341 if (eoff > bp->b_offset + bp->b_bcount)
3342 eoff = bp->b_offset + bp->b_bcount;
3345 * Set valid range. This is typically the entire buffer and thus the
3349 vm_page_set_validclean(
3351 (vm_offset_t) (soff & PAGE_MASK),
3352 (vm_offset_t) (eoff - soff)
3358 * This routine is called before a device strategy routine.
3359 * It is used to tell the VM system that paging I/O is in
3360 * progress, and treat the pages associated with the buffer
3361 * almost as being PG_BUSY. Also the object paging_in_progress
3362 * flag is handled to make sure that the object doesn't become
3365 * Since I/O has not been initiated yet, certain buffer flags
3366 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
3367 * and should be ignored.
3370 vfs_busy_pages(struct buf *bp, int clear_modify)
3377 if (!(bp->b_flags & B_VMIO))
3380 obj = bp->b_bufobj->bo_object;
3381 foff = bp->b_offset;
3382 KASSERT(bp->b_offset != NOOFFSET,
3383 ("vfs_busy_pages: no buffer offset"));
3385 VM_OBJECT_LOCK(obj);
3387 for (i = 0; i < bp->b_npages; i++) {
3390 if (vm_page_sleep_if_busy(m, FALSE, "vbpage"))
3394 vm_page_lock_queues();
3395 for (i = 0; i < bp->b_npages; i++) {
3398 if ((bp->b_flags & B_CLUSTER) == 0) {
3399 vm_object_pip_add(obj, 1);
3400 vm_page_io_start(m);
3403 * When readying a buffer for a read ( i.e
3404 * clear_modify == 0 ), it is important to do
3405 * bogus_page replacement for valid pages in
3406 * partially instantiated buffers. Partially
3407 * instantiated buffers can, in turn, occur when
3408 * reconstituting a buffer from its VM backing store
3409 * base. We only have to do this if B_CACHE is
3410 * clear ( which causes the I/O to occur in the
3411 * first place ). The replacement prevents the read
3412 * I/O from overwriting potentially dirty VM-backed
3413 * pages. XXX bogus page replacement is, uh, bogus.
3414 * It may not work properly with small-block devices.
3415 * We need to find a better way.
3419 vfs_page_set_valid(bp, foff, i, m);
3420 else if (m->valid == VM_PAGE_BITS_ALL &&
3421 (bp->b_flags & B_CACHE) == 0) {
3422 bp->b_pages[i] = bogus_page;
3425 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3427 vm_page_unlock_queues();
3428 VM_OBJECT_UNLOCK(obj);
3430 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3431 bp->b_pages, bp->b_npages);
3435 * Tell the VM system that the pages associated with this buffer
3436 * are clean. This is used for delayed writes where the data is
3437 * going to go to disk eventually without additional VM intevention.
3439 * Note that while we only really need to clean through to b_bcount, we
3440 * just go ahead and clean through to b_bufsize.
3443 vfs_clean_pages(struct buf *bp)
3446 vm_ooffset_t foff, noff, eoff;
3449 if (!(bp->b_flags & B_VMIO))
3452 foff = bp->b_offset;
3453 KASSERT(bp->b_offset != NOOFFSET,
3454 ("vfs_clean_pages: no buffer offset"));
3455 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3456 vm_page_lock_queues();
3457 for (i = 0; i < bp->b_npages; i++) {
3459 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3462 if (eoff > bp->b_offset + bp->b_bufsize)
3463 eoff = bp->b_offset + bp->b_bufsize;
3464 vfs_page_set_valid(bp, foff, i, m);
3465 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3468 vm_page_unlock_queues();
3469 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3473 * vfs_bio_set_validclean:
3475 * Set the range within the buffer to valid and clean. The range is
3476 * relative to the beginning of the buffer, b_offset. Note that b_offset
3477 * itself may be offset from the beginning of the first page.
3482 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3487 if (!(bp->b_flags & B_VMIO))
3490 * Fixup base to be relative to beginning of first page.
3491 * Set initial n to be the maximum number of bytes in the
3492 * first page that can be validated.
3495 base += (bp->b_offset & PAGE_MASK);
3496 n = PAGE_SIZE - (base & PAGE_MASK);
3498 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3499 vm_page_lock_queues();
3500 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3504 vm_page_set_validclean(m, base & PAGE_MASK, n);
3509 vm_page_unlock_queues();
3510 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3516 * clear a buffer. This routine essentially fakes an I/O, so we need
3517 * to clear BIO_ERROR and B_INVAL.
3519 * Note that while we only theoretically need to clear through b_bcount,
3520 * we go ahead and clear through b_bufsize.
3524 vfs_bio_clrbuf(struct buf *bp)
3529 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
3534 bp->b_flags &= ~B_INVAL;
3535 bp->b_ioflags &= ~BIO_ERROR;
3536 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3537 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3538 (bp->b_offset & PAGE_MASK) == 0) {
3539 if (bp->b_pages[0] == bogus_page)
3541 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3542 VM_OBJECT_LOCK_ASSERT(bp->b_pages[0]->object, MA_OWNED);
3543 if ((bp->b_pages[0]->valid & mask) == mask)
3545 if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
3546 ((bp->b_pages[0]->valid & mask) == 0)) {
3547 bzero(bp->b_data, bp->b_bufsize);
3548 bp->b_pages[0]->valid |= mask;
3552 ea = sa = bp->b_data;
3553 for(i = 0; i < bp->b_npages; i++, sa = ea) {
3554 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3555 ea = (caddr_t)(vm_offset_t)ulmin(
3556 (u_long)(vm_offset_t)ea,
3557 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3558 if (bp->b_pages[i] == bogus_page)
3560 j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3561 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3562 VM_OBJECT_LOCK_ASSERT(bp->b_pages[i]->object, MA_OWNED);
3563 if ((bp->b_pages[i]->valid & mask) == mask)
3565 if ((bp->b_pages[i]->valid & mask) == 0) {
3566 if ((bp->b_pages[i]->flags & PG_ZERO) == 0)
3569 for (; sa < ea; sa += DEV_BSIZE, j++) {
3570 if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
3571 (bp->b_pages[i]->valid & (1 << j)) == 0)
3572 bzero(sa, DEV_BSIZE);
3575 bp->b_pages[i]->valid |= mask;
3578 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3583 * vm_hold_load_pages and vm_hold_free_pages get pages into
3584 * a buffers address space. The pages are anonymous and are
3585 * not associated with a file object.
3588 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3594 to = round_page(to);
3595 from = round_page(from);
3596 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3598 VM_OBJECT_LOCK(kernel_object);
3599 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3602 * note: must allocate system pages since blocking here
3603 * could intefere with paging I/O, no matter which
3606 p = vm_page_alloc(kernel_object,
3607 ((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3608 VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
3610 atomic_add_int(&vm_pageout_deficit,
3611 (to - pg) >> PAGE_SHIFT);
3612 VM_OBJECT_UNLOCK(kernel_object);
3614 VM_OBJECT_LOCK(kernel_object);
3617 p->valid = VM_PAGE_BITS_ALL;
3618 pmap_qenter(pg, &p, 1);
3619 bp->b_pages[index] = p;
3621 VM_OBJECT_UNLOCK(kernel_object);
3622 bp->b_npages = index;
3625 /* Return pages associated with this buf to the vm system */
3627 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3631 int index, newnpages;
3633 from = round_page(from);
3634 to = round_page(to);
3635 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3637 VM_OBJECT_LOCK(kernel_object);
3638 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3639 p = bp->b_pages[index];
3640 if (p && (index < bp->b_npages)) {
3643 "vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
3644 (intmax_t)bp->b_blkno,
3645 (intmax_t)bp->b_lblkno);
3647 bp->b_pages[index] = NULL;
3648 pmap_qremove(pg, 1);
3649 vm_page_lock_queues();
3650 vm_page_unwire(p, 0);
3652 vm_page_unlock_queues();
3655 VM_OBJECT_UNLOCK(kernel_object);
3656 bp->b_npages = newnpages;
3660 * Map an IO request into kernel virtual address space.
3662 * All requests are (re)mapped into kernel VA space.
3663 * Notice that we use b_bufsize for the size of the buffer
3664 * to be mapped. b_bcount might be modified by the driver.
3666 * Note that even if the caller determines that the address space should
3667 * be valid, a race or a smaller-file mapped into a larger space may
3668 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
3669 * check the return value.
3672 vmapbuf(struct buf *bp)
3678 struct pmap *pmap = &curproc->p_vmspace->vm_pmap;
3680 if (bp->b_bufsize < 0)
3682 prot = VM_PROT_READ;
3683 if (bp->b_iocmd == BIO_READ)
3684 prot |= VM_PROT_WRITE; /* Less backwards than it looks */
3685 for (addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data), pidx = 0;
3686 addr < bp->b_data + bp->b_bufsize;
3687 addr += PAGE_SIZE, pidx++) {
3689 * Do the vm_fault if needed; do the copy-on-write thing
3690 * when reading stuff off device into memory.
3692 * NOTE! Must use pmap_extract() because addr may be in
3693 * the userland address space, and kextract is only guarenteed
3694 * to work for the kernland address space (see: sparc64 port).
3697 if (vm_fault_quick(addr >= bp->b_data ? addr : bp->b_data,
3699 vm_page_lock_queues();
3700 for (i = 0; i < pidx; ++i) {
3701 vm_page_unhold(bp->b_pages[i]);
3702 bp->b_pages[i] = NULL;
3704 vm_page_unlock_queues();
3707 m = pmap_extract_and_hold(pmap, (vm_offset_t)addr, prot);
3710 bp->b_pages[pidx] = m;
3712 if (pidx > btoc(MAXPHYS))
3713 panic("vmapbuf: mapped more than MAXPHYS");
3714 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
3716 kva = bp->b_saveaddr;
3717 bp->b_npages = pidx;
3718 bp->b_saveaddr = bp->b_data;
3719 bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3724 * Free the io map PTEs associated with this IO operation.
3725 * We also invalidate the TLB entries and restore the original b_addr.
3728 vunmapbuf(struct buf *bp)
3733 npages = bp->b_npages;
3734 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
3735 vm_page_lock_queues();
3736 for (pidx = 0; pidx < npages; pidx++)
3737 vm_page_unhold(bp->b_pages[pidx]);
3738 vm_page_unlock_queues();
3740 bp->b_data = bp->b_saveaddr;
3744 bdone(struct buf *bp)
3747 mtx_lock(&bdonelock);
3748 bp->b_flags |= B_DONE;
3750 mtx_unlock(&bdonelock);
3754 bwait(struct buf *bp, u_char pri, const char *wchan)
3757 mtx_lock(&bdonelock);
3758 while ((bp->b_flags & B_DONE) == 0)
3759 msleep(bp, &bdonelock, pri, wchan, 0);
3760 mtx_unlock(&bdonelock);
3764 bufsync(struct bufobj *bo, int waitfor, struct thread *td)
3767 return (VOP_FSYNC(bo->__bo_vnode, waitfor, td));
3771 bufstrategy(struct bufobj *bo, struct buf *bp)
3777 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
3778 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
3779 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
3780 i = VOP_STRATEGY(vp, bp);
3781 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
3785 bufobj_wrefl(struct bufobj *bo)
3788 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
3789 ASSERT_BO_LOCKED(bo);
3794 bufobj_wref(struct bufobj *bo)
3797 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
3804 bufobj_wdrop(struct bufobj *bo)
3807 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
3809 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
3810 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
3811 bo->bo_flag &= ~BO_WWAIT;
3812 wakeup(&bo->bo_numoutput);
3818 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
3822 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
3823 ASSERT_BO_LOCKED(bo);
3825 while (bo->bo_numoutput) {
3826 bo->bo_flag |= BO_WWAIT;
3827 error = msleep(&bo->bo_numoutput, BO_MTX(bo),
3828 slpflag | (PRIBIO + 1), "bo_wwait", timeo);
3836 bpin(struct buf *bp)
3838 mtx_lock(&bpinlock);
3840 mtx_unlock(&bpinlock);
3844 bunpin(struct buf *bp)
3846 mtx_lock(&bpinlock);
3847 if (--bp->b_pin_count == 0)
3849 mtx_unlock(&bpinlock);
3853 bunpin_wait(struct buf *bp)
3855 mtx_lock(&bpinlock);
3856 while (bp->b_pin_count > 0)
3857 msleep(bp, &bpinlock, PRIBIO, "bwunpin", 0);
3858 mtx_unlock(&bpinlock);
3861 #include "opt_ddb.h"
3863 #include <ddb/ddb.h>
3865 /* DDB command to show buffer data */
3866 DB_SHOW_COMMAND(buffer, db_show_buffer)
3869 struct buf *bp = (struct buf *)addr;
3872 db_printf("usage: show buffer <addr>\n");
3876 db_printf("buf at %p\n", bp);
3877 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3879 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
3880 "b_bufobj = (%p), b_data = %p, b_blkno = %jd\n",
3881 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3882 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno);
3885 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
3886 for (i = 0; i < bp->b_npages; i++) {
3889 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3890 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3891 if ((i + 1) < bp->b_npages)
3896 lockmgr_printinfo(&bp->b_lock);
3899 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
3904 for (i = 0; i < nbuf; i++) {
3906 if (lockcount(&bp->b_lock)) {
3907 db_show_buffer((uintptr_t)bp, 1, 0, NULL);