2 * Copyright (c) 1994,1997 John S. Dyson
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice immediately at the beginning of the file, without modification,
10 * this list of conditions, and the following disclaimer.
11 * 2. Absolutely no warranty of function or purpose is made by the author
14 * $FreeBSD: src/sys/kern/vfs_bio.c,v 1.242.2.20 2003/05/28 18:38:10 alc Exp $
18 * this file contains a new buffer I/O scheme implementing a coherent
19 * VM object and buffer cache scheme. Pains have been taken to make
20 * sure that the performance degradation associated with schemes such
21 * as this is not realized.
23 * Author: John S. Dyson
24 * Significant help during the development and debugging phases
25 * had been provided by David Greenman, also of the FreeBSD core team.
27 * see man buf(9) for more info. Note that man buf(9) doesn't reflect
28 * the actual buf/bio implementation in DragonFly.
31 #include <sys/param.h>
32 #include <sys/systm.h>
35 #include <sys/devicestat.h>
36 #include <sys/eventhandler.h>
38 #include <sys/malloc.h>
39 #include <sys/mount.h>
40 #include <sys/kernel.h>
41 #include <sys/kthread.h>
43 #include <sys/reboot.h>
44 #include <sys/resourcevar.h>
45 #include <sys/sysctl.h>
46 #include <sys/vmmeter.h>
47 #include <sys/vnode.h>
48 #include <sys/dsched.h>
50 #include <vm/vm_param.h>
51 #include <vm/vm_kern.h>
52 #include <vm/vm_pageout.h>
53 #include <vm/vm_page.h>
54 #include <vm/vm_object.h>
55 #include <vm/vm_extern.h>
56 #include <vm/vm_map.h>
57 #include <vm/vm_pager.h>
58 #include <vm/swap_pager.h>
61 #include <sys/thread2.h>
62 #include <sys/spinlock2.h>
63 #include <vm/vm_page2.h>
74 BQUEUE_NONE, /* not on any queue */
75 BQUEUE_LOCKED, /* locked buffers */
76 BQUEUE_CLEAN, /* non-B_DELWRI buffers */
77 BQUEUE_DIRTY, /* B_DELWRI buffers */
78 BQUEUE_DIRTY_HW, /* B_DELWRI buffers - heavy weight */
79 BQUEUE_EMPTY, /* empty buffer headers */
81 BUFFER_QUEUES /* number of buffer queues */
84 typedef enum bufq_type bufq_type_t;
86 #define BD_WAKE_SIZE 16384
87 #define BD_WAKE_MASK (BD_WAKE_SIZE - 1)
89 TAILQ_HEAD(bqueues, buf);
93 struct bqueues bufqueues[BUFFER_QUEUES];
96 struct bufpcpu bufpcpu[MAXCPU];
98 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
100 struct buf *buf; /* buffer header pool */
102 static void vfs_clean_pages(struct buf *bp);
103 static void vfs_clean_one_page(struct buf *bp, int pageno, vm_page_t m);
105 static void vfs_dirty_one_page(struct buf *bp, int pageno, vm_page_t m);
107 static void vfs_vmio_release(struct buf *bp);
108 static int flushbufqueues(struct buf *marker, bufq_type_t q);
109 static vm_page_t bio_page_alloc(struct buf *bp, vm_object_t obj,
110 vm_pindex_t pg, int deficit);
112 static void bd_signal(long totalspace);
113 static void buf_daemon(void);
114 static void buf_daemon_hw(void);
117 * bogus page -- for I/O to/from partially complete buffers
118 * this is a temporary solution to the problem, but it is not
119 * really that bad. it would be better to split the buffer
120 * for input in the case of buffers partially already in memory,
121 * but the code is intricate enough already.
123 vm_page_t bogus_page;
126 * These are all static, but make the ones we export globals so we do
127 * not need to use compiler magic.
129 long bufspace; /* atomic ops */
131 static long bufmallocspace; /* atomic ops */
132 long maxbufmallocspace, lobufspace, hibufspace;
133 static long lorunningspace;
134 static long hirunningspace;
135 static long dirtykvaspace; /* atomic */
136 long dirtybufspace; /* atomic (global for systat) */
137 static long dirtybufcount; /* atomic */
138 static long dirtybufspacehw; /* atomic */
139 static long dirtybufcounthw; /* atomic */
140 static long runningbufspace; /* atomic */
141 static long runningbufcount; /* atomic */
142 long lodirtybufspace;
143 long hidirtybufspace;
144 static int getnewbufcalls;
145 static int recoverbufcalls;
146 static int needsbuffer; /* atomic */
147 static int runningbufreq; /* atomic */
148 static int bd_request; /* atomic */
149 static int bd_request_hw; /* atomic */
150 static u_int bd_wake_ary[BD_WAKE_SIZE];
151 static u_int bd_wake_index;
152 static u_int vm_cycle_point = 40; /* 23-36 will migrate more act->inact */
153 static int debug_commit;
154 static int debug_bufbio;
155 static long bufcache_bw = 200 * 1024 * 1024;
157 static struct thread *bufdaemon_td;
158 static struct thread *bufdaemonhw_td;
159 static u_int lowmempgallocs;
160 static u_int lowmempgfails;
161 static u_int flushperqueue = 1024;
164 * Sysctls for operational control of the buffer cache.
166 SYSCTL_UINT(_vfs, OID_AUTO, flushperqueue, CTLFLAG_RW, &flushperqueue, 0,
167 "Number of buffers to flush from each per-cpu queue");
168 SYSCTL_LONG(_vfs, OID_AUTO, lodirtybufspace, CTLFLAG_RW, &lodirtybufspace, 0,
169 "Number of dirty buffers to flush before bufdaemon becomes inactive");
170 SYSCTL_LONG(_vfs, OID_AUTO, hidirtybufspace, CTLFLAG_RW, &hidirtybufspace, 0,
171 "High watermark used to trigger explicit flushing of dirty buffers");
172 SYSCTL_LONG(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
173 "Minimum amount of buffer space required for active I/O");
174 SYSCTL_LONG(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
175 "Maximum amount of buffer space to usable for active I/O");
176 SYSCTL_LONG(_vfs, OID_AUTO, bufcache_bw, CTLFLAG_RW, &bufcache_bw, 0,
177 "Buffer-cache -> VM page cache transfer bandwidth");
178 SYSCTL_UINT(_vfs, OID_AUTO, lowmempgallocs, CTLFLAG_RW, &lowmempgallocs, 0,
179 "Page allocations done during periods of very low free memory");
180 SYSCTL_UINT(_vfs, OID_AUTO, lowmempgfails, CTLFLAG_RW, &lowmempgfails, 0,
181 "Page allocations which failed during periods of very low free memory");
182 SYSCTL_UINT(_vfs, OID_AUTO, vm_cycle_point, CTLFLAG_RW, &vm_cycle_point, 0,
183 "Recycle pages to active or inactive queue transition pt 0-64");
185 * Sysctls determining current state of the buffer cache.
187 SYSCTL_LONG(_vfs, OID_AUTO, nbuf, CTLFLAG_RD, &nbuf, 0,
188 "Total number of buffers in buffer cache");
189 SYSCTL_LONG(_vfs, OID_AUTO, dirtykvaspace, CTLFLAG_RD, &dirtykvaspace, 0,
190 "KVA reserved by dirty buffers (all)");
191 SYSCTL_LONG(_vfs, OID_AUTO, dirtybufspace, CTLFLAG_RD, &dirtybufspace, 0,
192 "Pending bytes of dirty buffers (all)");
193 SYSCTL_LONG(_vfs, OID_AUTO, dirtybufspacehw, CTLFLAG_RD, &dirtybufspacehw, 0,
194 "Pending bytes of dirty buffers (heavy weight)");
195 SYSCTL_LONG(_vfs, OID_AUTO, dirtybufcount, CTLFLAG_RD, &dirtybufcount, 0,
196 "Pending number of dirty buffers");
197 SYSCTL_LONG(_vfs, OID_AUTO, dirtybufcounthw, CTLFLAG_RD, &dirtybufcounthw, 0,
198 "Pending number of dirty buffers (heavy weight)");
199 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
200 "I/O bytes currently in progress due to asynchronous writes");
201 SYSCTL_LONG(_vfs, OID_AUTO, runningbufcount, CTLFLAG_RD, &runningbufcount, 0,
202 "I/O buffers currently in progress due to asynchronous writes");
203 SYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
204 "Hard limit on maximum amount of memory usable for buffer space");
205 SYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
206 "Soft limit on maximum amount of memory usable for buffer space");
207 SYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
208 "Minimum amount of memory to reserve for system buffer space");
209 SYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
210 "Amount of memory available for buffers");
211 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RD, &maxbufmallocspace,
212 0, "Maximum amount of memory reserved for buffers using malloc");
213 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
214 "Amount of memory left for buffers using malloc-scheme");
215 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD, &getnewbufcalls, 0,
216 "New buffer header acquisition requests");
217 SYSCTL_INT(_vfs, OID_AUTO, recoverbufcalls, CTLFLAG_RD, &recoverbufcalls, 0,
218 "Recover VM space in an emergency");
219 SYSCTL_INT(_vfs, OID_AUTO, debug_commit, CTLFLAG_RW, &debug_commit, 0, "");
220 SYSCTL_INT(_vfs, OID_AUTO, debug_bufbio, CTLFLAG_RW, &debug_bufbio, 0, "");
221 SYSCTL_INT(_debug_sizeof, OID_AUTO, buf, CTLFLAG_RD, 0, sizeof(struct buf),
222 "sizeof(struct buf)");
224 char *buf_wmesg = BUF_WMESG;
226 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
227 #define VFS_BIO_NEED_UNUSED02 0x02
228 #define VFS_BIO_NEED_UNUSED04 0x04
229 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
232 * Called when buffer space is potentially available for recovery.
233 * getnewbuf() will block on this flag when it is unable to free
234 * sufficient buffer space. Buffer space becomes recoverable when
235 * bp's get placed back in the queues.
241 * If someone is waiting for BUF space, wake them up. Even
242 * though we haven't freed the kva space yet, the waiting
243 * process will be able to now.
246 int flags = needsbuffer;
248 if ((flags & VFS_BIO_NEED_BUFSPACE) == 0)
250 if (atomic_cmpset_int(&needsbuffer, flags,
251 flags & ~VFS_BIO_NEED_BUFSPACE)) {
252 wakeup(&needsbuffer);
262 * Accounting for I/O in progress.
266 runningbufwakeup(struct buf *bp)
271 if ((totalspace = bp->b_runningbufspace) != 0) {
272 atomic_add_long(&runningbufspace, -totalspace);
273 atomic_add_long(&runningbufcount, -1);
274 bp->b_runningbufspace = 0;
277 * see waitrunningbufspace() for limit test.
280 flags = runningbufreq;
284 if (atomic_cmpset_int(&runningbufreq, flags, 0)) {
285 wakeup(&runningbufreq);
290 bd_signal(totalspace);
297 * Called when a buffer has been added to one of the free queues to
298 * account for the buffer and to wakeup anyone waiting for free buffers.
299 * This typically occurs when large amounts of metadata are being handled
300 * by the buffer cache ( else buffer space runs out first, usually ).
311 if (atomic_cmpset_int(&needsbuffer, flags,
312 (flags & ~VFS_BIO_NEED_ANY))) {
313 wakeup(&needsbuffer);
321 * waitrunningbufspace()
323 * If runningbufspace exceeds 4/6 hirunningspace we block until
324 * runningbufspace drops to 3/6 hirunningspace. We also block if another
325 * thread blocked here in order to be fair, even if runningbufspace
326 * is now lower than the limit.
328 * The caller may be using this function to block in a tight loop, we
329 * must block while runningbufspace is greater than at least
330 * hirunningspace * 3 / 6.
333 waitrunningbufspace(void)
335 long limit = hirunningspace * 4 / 6;
338 while (runningbufspace > limit || runningbufreq) {
339 tsleep_interlock(&runningbufreq, 0);
340 flags = atomic_fetchadd_int(&runningbufreq, 1);
341 if (runningbufspace > limit || flags)
342 tsleep(&runningbufreq, PINTERLOCKED, "wdrn1", hz);
347 * buf_dirty_count_severe:
349 * Return true if we have too many dirty buffers.
352 buf_dirty_count_severe(void)
354 return (runningbufspace + dirtykvaspace >= hidirtybufspace ||
355 dirtybufcount >= nbuf / 2);
359 * Return true if the amount of running I/O is severe and BIOQ should
363 buf_runningbufspace_severe(void)
365 return (runningbufspace >= hirunningspace * 4 / 6);
369 * vfs_buf_test_cache:
371 * Called when a buffer is extended. This function clears the B_CACHE
372 * bit if the newly extended portion of the buffer does not contain
375 * NOTE! Dirty VM pages are not processed into dirty (B_DELWRI) buffer
376 * cache buffers. The VM pages remain dirty, as someone had mmap()'d
377 * them while a clean buffer was present.
381 vfs_buf_test_cache(struct buf *bp,
382 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
385 if (bp->b_flags & B_CACHE) {
386 int base = (foff + off) & PAGE_MASK;
387 if (vm_page_is_valid(m, base, size) == 0)
388 bp->b_flags &= ~B_CACHE;
395 * Spank the buf_daemon[_hw] if the total dirty buffer space exceeds the
402 if (dirtykvaspace < lodirtybufspace && dirtybufcount < nbuf / 2)
405 if (bd_request == 0 &&
406 (dirtykvaspace > lodirtybufspace / 2 ||
407 dirtybufcount - dirtybufcounthw >= nbuf / 2)) {
408 if (atomic_fetchadd_int(&bd_request, 1) == 0)
411 if (bd_request_hw == 0 &&
412 (dirtykvaspace > lodirtybufspace / 2 ||
413 dirtybufcounthw >= nbuf / 2)) {
414 if (atomic_fetchadd_int(&bd_request_hw, 1) == 0)
415 wakeup(&bd_request_hw);
422 * Get the buf_daemon heated up when the number of running and dirty
423 * buffers exceeds the mid-point.
425 * Return the total number of dirty bytes past the second mid point
426 * as a measure of how much excess dirty data there is in the system.
435 mid1 = lodirtybufspace + (hidirtybufspace - lodirtybufspace) / 2;
437 totalspace = runningbufspace + dirtykvaspace;
438 if (totalspace >= mid1 || dirtybufcount >= nbuf / 2) {
440 mid2 = mid1 + (hidirtybufspace - mid1) / 2;
441 if (totalspace >= mid2)
442 return(totalspace - mid2);
450 * Wait for the buffer cache to flush (totalspace) bytes worth of
451 * buffers, then return.
453 * Regardless this function blocks while the number of dirty buffers
454 * exceeds hidirtybufspace.
457 bd_wait(long totalspace)
464 if (curthread == bufdaemonhw_td || curthread == bufdaemon_td)
467 while (totalspace > 0) {
471 * Order is important. Suppliers adjust bd_wake_index after
472 * updating runningbufspace/dirtykvaspace. We want to fetch
473 * bd_wake_index before accessing. Any error should thus
476 i = atomic_fetchadd_int(&bd_wake_index, 0);
477 if (totalspace > runningbufspace + dirtykvaspace)
478 totalspace = runningbufspace + dirtykvaspace;
479 count = totalspace / MAXBSIZE;
480 if (count >= BD_WAKE_SIZE / 2)
481 count = BD_WAKE_SIZE / 2;
483 mi = i & BD_WAKE_MASK;
486 * This is not a strict interlock, so we play a bit loose
487 * with locking access to dirtybufspace*. We have to re-check
488 * bd_wake_index to ensure that it hasn't passed us.
490 tsleep_interlock(&bd_wake_ary[mi], 0);
491 atomic_add_int(&bd_wake_ary[mi], 1);
492 j = atomic_fetchadd_int(&bd_wake_index, 0);
493 if ((int)(i - j) >= 0)
494 tsleep(&bd_wake_ary[mi], PINTERLOCKED, "flstik", hz);
496 totalspace = runningbufspace + dirtykvaspace - hidirtybufspace;
503 * This function is called whenever runningbufspace or dirtykvaspace
504 * is reduced. Track threads waiting for run+dirty buffer I/O
508 bd_signal(long totalspace)
512 if (totalspace > 0) {
513 if (totalspace > MAXBSIZE * BD_WAKE_SIZE)
514 totalspace = MAXBSIZE * BD_WAKE_SIZE;
515 while (totalspace > 0) {
516 i = atomic_fetchadd_int(&bd_wake_index, 1);
518 if (atomic_readandclear_int(&bd_wake_ary[i]))
519 wakeup(&bd_wake_ary[i]);
520 totalspace -= MAXBSIZE;
526 * BIO tracking support routines.
528 * Release a ref on a bio_track. Wakeup requests are atomically released
529 * along with the last reference so bk_active will never wind up set to
534 bio_track_rel(struct bio_track *track)
542 active = track->bk_active;
543 if (active == 1 && atomic_cmpset_int(&track->bk_active, 1, 0))
547 * Full-on. Note that the wait flag is only atomically released on
548 * the 1->0 count transition.
550 * We check for a negative count transition using bit 30 since bit 31
551 * has a different meaning.
554 desired = (active & 0x7FFFFFFF) - 1;
556 desired |= active & 0x80000000;
557 if (atomic_cmpset_int(&track->bk_active, active, desired)) {
558 if (desired & 0x40000000)
559 panic("bio_track_rel: bad count: %p", track);
560 if (active & 0x80000000)
564 active = track->bk_active;
569 * Wait for the tracking count to reach 0.
571 * Use atomic ops such that the wait flag is only set atomically when
572 * bk_active is non-zero.
575 bio_track_wait(struct bio_track *track, int slp_flags, int slp_timo)
584 if (track->bk_active == 0)
588 * Full-on. Note that the wait flag may only be atomically set if
589 * the active count is non-zero.
591 * NOTE: We cannot optimize active == desired since a wakeup could
592 * clear active prior to our tsleep_interlock().
595 while ((active = track->bk_active) != 0) {
597 desired = active | 0x80000000;
598 tsleep_interlock(track, slp_flags);
599 if (atomic_cmpset_int(&track->bk_active, active, desired)) {
600 error = tsleep(track, slp_flags | PINTERLOCKED,
612 * Load time initialisation of the buffer cache, called from machine
613 * dependant initialization code.
617 bufinit(void *dummy __unused)
619 struct bufpcpu *pcpu;
621 vm_offset_t bogus_offset;
626 /* next, make a null set of free lists */
627 for (i = 0; i < ncpus; ++i) {
629 spin_init(&pcpu->spin, "bufinit");
630 for (j = 0; j < BUFFER_QUEUES; j++)
631 TAILQ_INIT(&pcpu->bufqueues[j]);
635 * Finally, initialize each buffer header and stick on empty q.
636 * Each buffer gets its own KVA reservation.
641 for (n = 0; n < nbuf; n++) {
643 bzero(bp, sizeof *bp);
644 bp->b_flags = B_INVAL; /* we're just an empty header */
645 bp->b_cmd = BUF_CMD_DONE;
646 bp->b_qindex = BQUEUE_EMPTY;
648 bp->b_kvabase = (void *)(vm_map_min(&buffer_map) +
650 bp->b_kvasize = MAXBSIZE;
652 xio_init(&bp->b_xio);
654 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
662 * maxbufspace is the absolute maximum amount of buffer space we are
663 * allowed to reserve in KVM and in real terms. The absolute maximum
664 * is nominally used by buf_daemon. hibufspace is the nominal maximum
665 * used by most other processes. The differential is required to
666 * ensure that buf_daemon is able to run when other processes might
667 * be blocked waiting for buffer space.
669 * Calculate hysteresis (lobufspace, hibufspace). Don't make it
670 * too large or we might lockup a cpu for too long a period of
671 * time in our tight loop.
673 maxbufspace = nbuf * NBUFCALCSIZE;
674 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
675 lobufspace = hibufspace * 7 / 8;
676 if (hibufspace - lobufspace > 64 * 1024 * 1024)
677 lobufspace = hibufspace - 64 * 1024 * 1024;
678 if (lobufspace > hibufspace - MAXBSIZE)
679 lobufspace = hibufspace - MAXBSIZE;
681 lorunningspace = 512 * 1024;
682 /* hirunningspace -- see below */
685 * Limit the amount of malloc memory since it is wired permanently
686 * into the kernel space. Even though this is accounted for in
687 * the buffer allocation, we don't want the malloced region to grow
688 * uncontrolled. The malloc scheme improves memory utilization
689 * significantly on average (small) directories.
691 maxbufmallocspace = hibufspace / 20;
694 * Reduce the chance of a deadlock occuring by limiting the number
695 * of delayed-write dirty buffers we allow to stack up.
697 * We don't want too much actually queued to the device at once
698 * (XXX this needs to be per-mount!), because the buffers will
699 * wind up locked for a very long period of time while the I/O
702 hidirtybufspace = hibufspace / 2; /* dirty + running */
703 hirunningspace = hibufspace / 16; /* locked & queued to device */
704 if (hirunningspace < 1024 * 1024)
705 hirunningspace = 1024 * 1024;
711 lodirtybufspace = hidirtybufspace / 2;
714 * Maximum number of async ops initiated per buf_daemon loop. This is
715 * somewhat of a hack at the moment, we really need to limit ourselves
716 * based on the number of bytes of I/O in-transit that were initiated
720 bogus_offset = kmem_alloc_pageable(&kernel_map, PAGE_SIZE,
722 vm_object_hold(&kernel_object);
723 bogus_page = vm_page_alloc(&kernel_object,
724 (bogus_offset >> PAGE_SHIFT),
726 vm_object_drop(&kernel_object);
727 vmstats.v_wire_count++;
731 SYSINIT(do_bufinit, SI_BOOT2_MACHDEP, SI_ORDER_FIRST, bufinit, NULL);
734 * Initialize the embedded bio structures, typically used by
735 * deprecated code which tries to allocate its own struct bufs.
738 initbufbio(struct buf *bp)
740 bp->b_bio1.bio_buf = bp;
741 bp->b_bio1.bio_prev = NULL;
742 bp->b_bio1.bio_offset = NOOFFSET;
743 bp->b_bio1.bio_next = &bp->b_bio2;
744 bp->b_bio1.bio_done = NULL;
745 bp->b_bio1.bio_flags = 0;
747 bp->b_bio2.bio_buf = bp;
748 bp->b_bio2.bio_prev = &bp->b_bio1;
749 bp->b_bio2.bio_offset = NOOFFSET;
750 bp->b_bio2.bio_next = NULL;
751 bp->b_bio2.bio_done = NULL;
752 bp->b_bio2.bio_flags = 0;
758 * Reinitialize the embedded bio structures as well as any additional
759 * translation cache layers.
762 reinitbufbio(struct buf *bp)
766 for (bio = &bp->b_bio1; bio; bio = bio->bio_next) {
767 bio->bio_done = NULL;
768 bio->bio_offset = NOOFFSET;
773 * Undo the effects of an initbufbio().
776 uninitbufbio(struct buf *bp)
783 * Push another BIO layer onto an existing BIO and return it. The new
784 * BIO layer may already exist, holding cached translation data.
787 push_bio(struct bio *bio)
791 if ((nbio = bio->bio_next) == NULL) {
792 int index = bio - &bio->bio_buf->b_bio_array[0];
793 if (index >= NBUF_BIO - 1) {
794 panic("push_bio: too many layers %d for bp %p",
795 index, bio->bio_buf);
797 nbio = &bio->bio_buf->b_bio_array[index + 1];
798 bio->bio_next = nbio;
799 nbio->bio_prev = bio;
800 nbio->bio_buf = bio->bio_buf;
801 nbio->bio_offset = NOOFFSET;
802 nbio->bio_done = NULL;
803 nbio->bio_next = NULL;
805 KKASSERT(nbio->bio_done == NULL);
810 * Pop a BIO translation layer, returning the previous layer. The
811 * must have been previously pushed.
814 pop_bio(struct bio *bio)
816 return(bio->bio_prev);
820 clearbiocache(struct bio *bio)
823 bio->bio_offset = NOOFFSET;
829 * Remove the buffer from the appropriate free list.
830 * (caller must be locked)
833 _bremfree(struct buf *bp)
835 struct bufpcpu *pcpu = &bufpcpu[bp->b_qcpu];
837 if (bp->b_qindex != BQUEUE_NONE) {
838 KASSERT(BUF_REFCNTNB(bp) == 1,
839 ("bremfree: bp %p not locked",bp));
840 TAILQ_REMOVE(&pcpu->bufqueues[bp->b_qindex], bp, b_freelist);
841 bp->b_qindex = BQUEUE_NONE;
843 if (BUF_REFCNTNB(bp) <= 1)
844 panic("bremfree: removing a buffer not on a queue");
849 * bremfree() - must be called with a locked buffer
852 bremfree(struct buf *bp)
854 struct bufpcpu *pcpu = &bufpcpu[bp->b_qcpu];
856 spin_lock(&pcpu->spin);
858 spin_unlock(&pcpu->spin);
862 * bremfree_locked - must be called with pcpu->spin locked
865 bremfree_locked(struct buf *bp)
871 * This version of bread issues any required I/O asyncnronously and
872 * makes a callback on completion.
874 * The callback must check whether BIO_DONE is set in the bio and issue
875 * the bpdone(bp, 0) if it isn't. The callback is responsible for clearing
876 * BIO_DONE and disposing of the I/O (bqrelse()ing it).
879 breadcb(struct vnode *vp, off_t loffset, int size, int bflags,
880 void (*func)(struct bio *), void *arg)
884 bp = getblk(vp, loffset, size, 0, 0);
886 /* if not found in cache, do some I/O */
887 if ((bp->b_flags & B_CACHE) == 0) {
888 bp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL | B_NOTMETA);
889 bp->b_flags |= bflags;
890 bp->b_cmd = BUF_CMD_READ;
891 bp->b_bio1.bio_done = func;
892 bp->b_bio1.bio_caller_info1.ptr = arg;
893 vfs_busy_pages(vp, bp);
895 vn_strategy(vp, &bp->b_bio1);
898 * Since we are issuing the callback synchronously it cannot
899 * race the BIO_DONE, so no need for atomic ops here.
901 /*bp->b_bio1.bio_done = func;*/
902 bp->b_bio1.bio_caller_info1.ptr = arg;
903 bp->b_bio1.bio_flags |= BIO_DONE;
911 * breadnx() - Terminal function for bread() and breadn().
913 * This function will start asynchronous I/O on read-ahead blocks as well
914 * as satisfy the primary request.
916 * We must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE is
917 * set, the buffer is valid and we do not have to do anything.
920 breadnx(struct vnode *vp, off_t loffset, int size, int bflags,
921 off_t *raoffset, int *rabsize,
922 int cnt, struct buf **bpp)
924 struct buf *bp, *rabp;
926 int rv = 0, readwait = 0;
927 int blkflags = (bflags & B_KVABIO) ? GETBLK_KVABIO : 0;
932 *bpp = bp = getblk(vp, loffset, size, blkflags, 0);
934 /* if not found in cache, do some I/O */
935 if ((bp->b_flags & B_CACHE) == 0) {
936 bp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL | B_NOTMETA);
937 bp->b_flags |= bflags;
938 bp->b_cmd = BUF_CMD_READ;
939 bp->b_bio1.bio_done = biodone_sync;
940 bp->b_bio1.bio_flags |= BIO_SYNC;
941 vfs_busy_pages(vp, bp);
942 vn_strategy(vp, &bp->b_bio1);
946 for (i = 0; i < cnt; i++, raoffset++, rabsize++) {
947 if (inmem(vp, *raoffset))
949 rabp = getblk(vp, *raoffset, *rabsize, GETBLK_KVABIO, 0);
951 if ((rabp->b_flags & B_CACHE) == 0) {
952 rabp->b_flags &= ~(B_ERROR | B_EINTR |
953 B_INVAL | B_NOTMETA);
954 rabp->b_flags |= (bflags & ~B_KVABIO);
955 rabp->b_cmd = BUF_CMD_READ;
956 vfs_busy_pages(vp, rabp);
958 vn_strategy(vp, &rabp->b_bio1);
964 rv = biowait(&bp->b_bio1, "biord");
971 * Synchronous write, waits for completion.
973 * Write, release buffer on completion. (Done by iodone
974 * if async). Do not bother writing anything if the buffer
977 * Note that we set B_CACHE here, indicating that buffer is
978 * fully valid and thus cacheable. This is true even of NFS
979 * now so we set it generally. This could be set either here
980 * or in biodone() since the I/O is synchronous. We put it
984 bwrite(struct buf *bp)
988 if (bp->b_flags & B_INVAL) {
992 if (BUF_REFCNTNB(bp) == 0)
993 panic("bwrite: buffer is not busy???");
996 * NOTE: We no longer mark the buffer clear prior to the vn_strategy()
997 * call because it will remove the buffer from the vnode's
998 * dirty buffer list prematurely and possibly cause filesystem
999 * checks to race buffer flushes. This is now handled in
1002 * bundirty(bp); REMOVED
1005 bp->b_flags &= ~(B_ERROR | B_EINTR);
1006 bp->b_flags |= B_CACHE;
1007 bp->b_cmd = BUF_CMD_WRITE;
1008 bp->b_bio1.bio_done = biodone_sync;
1009 bp->b_bio1.bio_flags |= BIO_SYNC;
1010 vfs_busy_pages(bp->b_vp, bp);
1013 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
1014 * valid for vnode-backed buffers.
1016 bsetrunningbufspace(bp, bp->b_bufsize);
1017 vn_strategy(bp->b_vp, &bp->b_bio1);
1018 error = biowait(&bp->b_bio1, "biows");
1027 * Asynchronous write. Start output on a buffer, but do not wait for
1028 * it to complete. The buffer is released when the output completes.
1030 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1031 * B_INVAL buffers. Not us.
1034 bawrite(struct buf *bp)
1036 if (bp->b_flags & B_INVAL) {
1040 if (BUF_REFCNTNB(bp) == 0)
1041 panic("bawrite: buffer is not busy???");
1044 * NOTE: We no longer mark the buffer clear prior to the vn_strategy()
1045 * call because it will remove the buffer from the vnode's
1046 * dirty buffer list prematurely and possibly cause filesystem
1047 * checks to race buffer flushes. This is now handled in
1050 * bundirty(bp); REMOVED
1052 bp->b_flags &= ~(B_ERROR | B_EINTR);
1053 bp->b_flags |= B_CACHE;
1054 bp->b_cmd = BUF_CMD_WRITE;
1055 KKASSERT(bp->b_bio1.bio_done == NULL);
1056 vfs_busy_pages(bp->b_vp, bp);
1059 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
1060 * valid for vnode-backed buffers.
1062 bsetrunningbufspace(bp, bp->b_bufsize);
1064 vn_strategy(bp->b_vp, &bp->b_bio1);
1070 * Delayed write. (Buffer is marked dirty). Do not bother writing
1071 * anything if the buffer is marked invalid.
1073 * Note that since the buffer must be completely valid, we can safely
1074 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
1075 * biodone() in order to prevent getblk from writing the buffer
1076 * out synchronously.
1079 bdwrite(struct buf *bp)
1081 if (BUF_REFCNTNB(bp) == 0)
1082 panic("bdwrite: buffer is not busy");
1084 if (bp->b_flags & B_INVAL) {
1090 dsched_buf_enter(bp); /* might stack */
1093 * Set B_CACHE, indicating that the buffer is fully valid. This is
1094 * true even of NFS now.
1096 bp->b_flags |= B_CACHE;
1099 * This bmap keeps the system from needing to do the bmap later,
1100 * perhaps when the system is attempting to do a sync. Since it
1101 * is likely that the indirect block -- or whatever other datastructure
1102 * that the filesystem needs is still in memory now, it is a good
1103 * thing to do this. Note also, that if the pageout daemon is
1104 * requesting a sync -- there might not be enough memory to do
1105 * the bmap then... So, this is important to do.
1107 if (bp->b_bio2.bio_offset == NOOFFSET) {
1108 VOP_BMAP(bp->b_vp, bp->b_loffset, &bp->b_bio2.bio_offset,
1109 NULL, NULL, BUF_CMD_WRITE);
1113 * Because the underlying pages may still be mapped and
1114 * writable trying to set the dirty buffer (b_dirtyoff/end)
1115 * range here will be inaccurate.
1117 * However, we must still clean the pages to satisfy the
1118 * vnode_pager and pageout daemon, so they think the pages
1119 * have been "cleaned". What has really occured is that
1120 * they've been earmarked for later writing by the buffer
1123 * So we get the b_dirtyoff/end update but will not actually
1124 * depend on it (NFS that is) until the pages are busied for
1127 vfs_clean_pages(bp);
1131 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1132 * due to the softdep code.
1137 * Fake write - return pages to VM system as dirty, leave the buffer clean.
1138 * This is used by tmpfs.
1140 * It is important for any VFS using this routine to NOT use it for
1141 * IO_SYNC or IO_ASYNC operations which occur when the system really
1142 * wants to flush VM pages to backing store.
1145 buwrite(struct buf *bp)
1151 * Only works for VMIO buffers. If the buffer is already
1152 * marked for delayed-write we can't avoid the bdwrite().
1154 if ((bp->b_flags & B_VMIO) == 0 || (bp->b_flags & B_DELWRI)) {
1160 * Mark as needing a commit.
1162 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1163 m = bp->b_xio.xio_pages[i];
1164 vm_page_need_commit(m);
1172 * Turn buffer into delayed write request by marking it B_DELWRI.
1173 * B_RELBUF and B_NOCACHE must be cleared.
1175 * We reassign the buffer to itself to properly update it in the
1176 * dirty/clean lists.
1178 * Must be called from a critical section.
1179 * The buffer must be on BQUEUE_NONE.
1182 bdirty(struct buf *bp)
1184 KASSERT(bp->b_qindex == BQUEUE_NONE,
1185 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1186 if (bp->b_flags & B_NOCACHE) {
1187 kprintf("bdirty: clearing B_NOCACHE on buf %p\n", bp);
1188 bp->b_flags &= ~B_NOCACHE;
1190 if (bp->b_flags & B_INVAL) {
1191 kprintf("bdirty: warning, dirtying invalid buffer %p\n", bp);
1193 bp->b_flags &= ~B_RELBUF;
1195 if ((bp->b_flags & B_DELWRI) == 0) {
1196 lwkt_gettoken(&bp->b_vp->v_token);
1197 bp->b_flags |= B_DELWRI;
1199 lwkt_reltoken(&bp->b_vp->v_token);
1201 atomic_add_long(&dirtybufcount, 1);
1202 atomic_add_long(&dirtykvaspace, bp->b_kvasize);
1203 atomic_add_long(&dirtybufspace, bp->b_bufsize);
1204 if (bp->b_flags & B_HEAVY) {
1205 atomic_add_long(&dirtybufcounthw, 1);
1206 atomic_add_long(&dirtybufspacehw, bp->b_bufsize);
1213 * Set B_HEAVY, indicating that this is a heavy-weight buffer that
1214 * needs to be flushed with a different buf_daemon thread to avoid
1215 * deadlocks. B_HEAVY also imposes restrictions in getnewbuf().
1218 bheavy(struct buf *bp)
1220 if ((bp->b_flags & B_HEAVY) == 0) {
1221 bp->b_flags |= B_HEAVY;
1222 if (bp->b_flags & B_DELWRI) {
1223 atomic_add_long(&dirtybufcounthw, 1);
1224 atomic_add_long(&dirtybufspacehw, bp->b_bufsize);
1232 * Clear B_DELWRI for buffer.
1234 * Must be called from a critical section.
1236 * The buffer is typically on BQUEUE_NONE but there is one case in
1237 * brelse() that calls this function after placing the buffer on
1238 * a different queue.
1241 bundirty(struct buf *bp)
1243 if (bp->b_flags & B_DELWRI) {
1244 lwkt_gettoken(&bp->b_vp->v_token);
1245 bp->b_flags &= ~B_DELWRI;
1247 lwkt_reltoken(&bp->b_vp->v_token);
1249 atomic_add_long(&dirtybufcount, -1);
1250 atomic_add_long(&dirtykvaspace, -bp->b_kvasize);
1251 atomic_add_long(&dirtybufspace, -bp->b_bufsize);
1252 if (bp->b_flags & B_HEAVY) {
1253 atomic_add_long(&dirtybufcounthw, -1);
1254 atomic_add_long(&dirtybufspacehw, -bp->b_bufsize);
1256 bd_signal(bp->b_bufsize);
1259 * Since it is now being written, we can clear its deferred write flag.
1261 bp->b_flags &= ~B_DEFERRED;
1265 * Set the b_runningbufspace field, used to track how much I/O is
1266 * in progress at any given moment.
1269 bsetrunningbufspace(struct buf *bp, int bytes)
1271 bp->b_runningbufspace = bytes;
1273 atomic_add_long(&runningbufspace, bytes);
1274 atomic_add_long(&runningbufcount, 1);
1281 * Release a busy buffer and, if requested, free its resources. The
1282 * buffer will be stashed in the appropriate bufqueue[] allowing it
1283 * to be accessed later as a cache entity or reused for other purposes.
1286 brelse(struct buf *bp)
1288 struct bufpcpu *pcpu;
1290 int saved_flags = bp->b_flags;
1293 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1294 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1297 * If B_NOCACHE is set we are being asked to destroy the buffer and
1298 * its backing store. Clear B_DELWRI.
1300 * B_NOCACHE is set in two cases: (1) when the caller really wants
1301 * to destroy the buffer and backing store and (2) when the caller
1302 * wants to destroy the buffer and backing store after a write
1305 if ((bp->b_flags & (B_NOCACHE|B_DELWRI)) == (B_NOCACHE|B_DELWRI)) {
1309 if ((bp->b_flags & (B_INVAL | B_DELWRI)) == B_DELWRI) {
1311 * A re-dirtied buffer is only subject to destruction
1312 * by B_INVAL. B_ERROR and B_NOCACHE are ignored.
1314 /* leave buffer intact */
1315 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR)) ||
1316 (bp->b_bufsize <= 0)) {
1318 * Either a failed read or we were asked to free or not
1319 * cache the buffer. This path is reached with B_DELWRI
1320 * set only if B_INVAL is already set. B_NOCACHE governs
1321 * backing store destruction.
1323 * NOTE: HAMMER will set B_LOCKED in buf_deallocate if the
1324 * buffer cannot be immediately freed.
1326 bp->b_flags |= B_INVAL;
1327 if (LIST_FIRST(&bp->b_dep) != NULL)
1329 if (bp->b_flags & B_DELWRI) {
1330 atomic_add_long(&dirtybufcount, -1);
1331 atomic_add_long(&dirtykvaspace, -bp->b_kvasize);
1332 atomic_add_long(&dirtybufspace, -bp->b_bufsize);
1333 if (bp->b_flags & B_HEAVY) {
1334 atomic_add_long(&dirtybufcounthw, -1);
1335 atomic_add_long(&dirtybufspacehw,
1338 bd_signal(bp->b_bufsize);
1340 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1344 * We must clear B_RELBUF if B_DELWRI or B_LOCKED is set,
1345 * or if b_refs is non-zero.
1347 * If vfs_vmio_release() is called with either bit set, the
1348 * underlying pages may wind up getting freed causing a previous
1349 * write (bdwrite()) to get 'lost' because pages associated with
1350 * a B_DELWRI bp are marked clean. Pages associated with a
1351 * B_LOCKED buffer may be mapped by the filesystem.
1353 * If we want to release the buffer ourselves (rather then the
1354 * originator asking us to release it), give the originator a
1355 * chance to countermand the release by setting B_LOCKED.
1357 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1358 * if B_DELWRI is set.
1360 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1361 * on pages to return pages to the VM page queues.
1363 if ((bp->b_flags & (B_DELWRI | B_LOCKED)) || bp->b_refs) {
1364 bp->b_flags &= ~B_RELBUF;
1365 } else if (vm_page_count_min(0)) {
1366 if (LIST_FIRST(&bp->b_dep) != NULL)
1367 buf_deallocate(bp); /* can set B_LOCKED */
1368 if (bp->b_flags & (B_DELWRI | B_LOCKED))
1369 bp->b_flags &= ~B_RELBUF;
1371 bp->b_flags |= B_RELBUF;
1375 * Make sure b_cmd is clear. It may have already been cleared by
1378 * At this point destroying the buffer is governed by the B_INVAL
1379 * or B_RELBUF flags.
1381 bp->b_cmd = BUF_CMD_DONE;
1382 dsched_buf_exit(bp);
1385 * VMIO buffer rundown. Make sure the VM page array is restored
1386 * after an I/O may have replaces some of the pages with bogus pages
1387 * in order to not destroy dirty pages in a fill-in read.
1389 * Note that due to the code above, if a buffer is marked B_DELWRI
1390 * then the B_RELBUF and B_NOCACHE bits will always be clear.
1391 * B_INVAL may still be set, however.
1393 * For clean buffers, B_INVAL or B_RELBUF will destroy the buffer
1394 * but not the backing store. B_NOCACHE will destroy the backing
1397 * Note that dirty NFS buffers contain byte-granular write ranges
1398 * and should not be destroyed w/ B_INVAL even if the backing store
1401 if (bp->b_flags & B_VMIO) {
1403 * Rundown for VMIO buffers which are not dirty NFS buffers.
1415 * Get the base offset and length of the buffer. Note that
1416 * in the VMIO case if the buffer block size is not
1417 * page-aligned then b_data pointer may not be page-aligned.
1418 * But our b_xio.xio_pages array *IS* page aligned.
1420 * block sizes less then DEV_BSIZE (usually 512) are not
1421 * supported due to the page granularity bits (m->valid,
1422 * m->dirty, etc...).
1424 * See man buf(9) for more information
1427 resid = bp->b_bufsize;
1428 foff = bp->b_loffset;
1430 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1431 m = bp->b_xio.xio_pages[i];
1434 * If we hit a bogus page, fixup *all* of them
1435 * now. Note that we left these pages wired
1436 * when we removed them so they had better exist,
1437 * and they cannot be ripped out from under us so
1438 * no critical section protection is necessary.
1440 if (m == bogus_page) {
1442 poff = OFF_TO_IDX(bp->b_loffset);
1444 vm_object_hold(obj);
1445 for (j = i; j < bp->b_xio.xio_npages; j++) {
1448 mtmp = bp->b_xio.xio_pages[j];
1449 if (mtmp == bogus_page) {
1450 if ((bp->b_flags & B_HASBOGUS) == 0)
1451 panic("brelse: bp %p corrupt bogus", bp);
1452 mtmp = vm_page_lookup(obj, poff + j);
1454 panic("brelse: bp %p page %d missing", bp, j);
1455 bp->b_xio.xio_pages[j] = mtmp;
1458 vm_object_drop(obj);
1460 if ((bp->b_flags & B_HASBOGUS) ||
1461 (bp->b_flags & B_INVAL) == 0) {
1462 pmap_qenter_noinval(
1463 trunc_page((vm_offset_t)bp->b_data),
1464 bp->b_xio.xio_pages,
1465 bp->b_xio.xio_npages);
1466 bp->b_flags &= ~B_HASBOGUS;
1467 bp->b_flags |= B_KVABIO;
1470 m = bp->b_xio.xio_pages[i];
1474 * Invalidate the backing store if B_NOCACHE is set
1475 * (e.g. used with vinvalbuf()). If this is NFS
1476 * we impose a requirement that the block size be
1477 * a multiple of PAGE_SIZE and create a temporary
1478 * hack to basically invalidate the whole page. The
1479 * problem is that NFS uses really odd buffer sizes
1480 * especially when tracking piecemeal writes and
1481 * it also vinvalbuf()'s a lot, which would result
1482 * in only partial page validation and invalidation
1483 * here. If the file page is mmap()'d, however,
1484 * all the valid bits get set so after we invalidate
1485 * here we would end up with weird m->valid values
1486 * like 0xfc. nfs_getpages() can't handle this so
1487 * we clear all the valid bits for the NFS case
1488 * instead of just some of them.
1490 * The real bug is the VM system having to set m->valid
1491 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1492 * itself is an artifact of the whole 512-byte
1493 * granular mess that exists to support odd block
1494 * sizes and UFS meta-data block sizes (e.g. 6144).
1495 * A complete rewrite is required.
1499 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1500 int poffset = foff & PAGE_MASK;
1503 presid = PAGE_SIZE - poffset;
1504 if (bp->b_vp->v_tag == VT_NFS &&
1505 bp->b_vp->v_type == VREG) {
1507 } else if (presid > resid) {
1510 KASSERT(presid >= 0, ("brelse: extra page"));
1511 vm_page_set_invalid(m, poffset, presid);
1514 * Also make sure any swap cache is removed
1515 * as it is now stale (HAMMER in particular
1516 * uses B_NOCACHE to deal with buffer
1519 swap_pager_unswapped(m);
1521 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1522 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1524 if (bp->b_flags & (B_INVAL | B_RELBUF))
1525 vfs_vmio_release(bp);
1528 * Rundown for non-VMIO buffers.
1530 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1533 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1539 if (bp->b_qindex != BQUEUE_NONE)
1540 panic("brelse: free buffer onto another queue???");
1541 if (BUF_REFCNTNB(bp) > 1) {
1542 /* Temporary panic to verify exclusive locking */
1543 /* This panic goes away when we allow shared refs */
1544 panic("brelse: multiple refs");
1550 * Figure out the correct queue to place the cleaned up buffer on.
1551 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1552 * disassociated from their vnode.
1554 * Return the buffer to its original pcpu area
1556 pcpu = &bufpcpu[bp->b_qcpu];
1557 spin_lock(&pcpu->spin);
1559 if (bp->b_flags & B_LOCKED) {
1561 * Buffers that are locked are placed in the locked queue
1562 * immediately, regardless of their state.
1564 bp->b_qindex = BQUEUE_LOCKED;
1565 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1567 } else if (bp->b_bufsize == 0) {
1569 * Buffers with no memory. Due to conditionals near the top
1570 * of brelse() such buffers should probably already be
1571 * marked B_INVAL and disassociated from their vnode.
1573 bp->b_flags |= B_INVAL;
1574 KASSERT(bp->b_vp == NULL,
1575 ("bp1 %p flags %08x/%08x vnode %p "
1576 "unexpectededly still associated!",
1577 bp, saved_flags, bp->b_flags, bp->b_vp));
1578 KKASSERT((bp->b_flags & B_HASHED) == 0);
1579 bp->b_qindex = BQUEUE_EMPTY;
1580 TAILQ_INSERT_HEAD(&pcpu->bufqueues[bp->b_qindex],
1582 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) {
1584 * Buffers with junk contents. Again these buffers had better
1585 * already be disassociated from their vnode.
1587 KASSERT(bp->b_vp == NULL,
1588 ("bp2 %p flags %08x/%08x vnode %p unexpectededly "
1589 "still associated!",
1590 bp, saved_flags, bp->b_flags, bp->b_vp));
1591 KKASSERT((bp->b_flags & B_HASHED) == 0);
1592 bp->b_flags |= B_INVAL;
1593 bp->b_qindex = BQUEUE_CLEAN;
1594 TAILQ_INSERT_HEAD(&pcpu->bufqueues[bp->b_qindex],
1598 * Remaining buffers. These buffers are still associated with
1601 switch(bp->b_flags & (B_DELWRI|B_HEAVY)) {
1603 bp->b_qindex = BQUEUE_DIRTY;
1604 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1607 case B_DELWRI | B_HEAVY:
1608 bp->b_qindex = BQUEUE_DIRTY_HW;
1609 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1614 * NOTE: Buffers are always placed at the end of the
1615 * queue. If B_AGE is not set the buffer will cycle
1616 * through the queue twice.
1618 bp->b_qindex = BQUEUE_CLEAN;
1619 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1624 spin_unlock(&pcpu->spin);
1627 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1628 * on the correct queue but we have not yet unlocked it.
1630 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1634 * The bp is on an appropriate queue unless locked. If it is not
1635 * locked or dirty we can wakeup threads waiting for buffer space.
1637 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1638 * if B_INVAL is set ).
1640 if ((bp->b_flags & (B_LOCKED|B_DELWRI)) == 0)
1644 * Something we can maybe free or reuse
1646 if (bp->b_bufsize || bp->b_kvasize)
1650 * Clean up temporary flags and unlock the buffer.
1652 bp->b_flags &= ~(B_NOCACHE | B_RELBUF | B_DIRECT);
1659 * Release a buffer back to the appropriate queue but do not try to free
1660 * it. The buffer is expected to be used again soon.
1662 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1663 * biodone() to requeue an async I/O on completion. It is also used when
1664 * known good buffers need to be requeued but we think we may need the data
1667 * XXX we should be able to leave the B_RELBUF hint set on completion.
1670 bqrelse(struct buf *bp)
1672 struct bufpcpu *pcpu;
1674 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1675 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1677 if (bp->b_qindex != BQUEUE_NONE)
1678 panic("bqrelse: free buffer onto another queue???");
1679 if (BUF_REFCNTNB(bp) > 1) {
1680 /* do not release to free list */
1681 panic("bqrelse: multiple refs");
1685 buf_act_advance(bp);
1687 pcpu = &bufpcpu[bp->b_qcpu];
1688 spin_lock(&pcpu->spin);
1690 if (bp->b_flags & B_LOCKED) {
1692 * Locked buffers are released to the locked queue. However,
1693 * if the buffer is dirty it will first go into the dirty
1694 * queue and later on after the I/O completes successfully it
1695 * will be released to the locked queue.
1697 bp->b_qindex = BQUEUE_LOCKED;
1698 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1700 } else if (bp->b_flags & B_DELWRI) {
1701 bp->b_qindex = (bp->b_flags & B_HEAVY) ?
1702 BQUEUE_DIRTY_HW : BQUEUE_DIRTY;
1703 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1705 } else if (vm_page_count_min(0)) {
1707 * We are too low on memory, we have to try to free the
1708 * buffer (most importantly: the wired pages making up its
1709 * backing store) *now*.
1711 spin_unlock(&pcpu->spin);
1715 bp->b_qindex = BQUEUE_CLEAN;
1716 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1719 spin_unlock(&pcpu->spin);
1722 * We have now placed the buffer on the proper queue, but have yet
1725 if ((bp->b_flags & B_LOCKED) == 0 &&
1726 ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)) {
1731 * Something we can maybe free or reuse.
1733 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1737 * Final cleanup and unlock. Clear bits that are only used while a
1738 * buffer is actively locked.
1740 bp->b_flags &= ~(B_NOCACHE | B_RELBUF);
1741 dsched_buf_exit(bp);
1746 * Hold a buffer, preventing it from being reused. This will prevent
1747 * normal B_RELBUF operations on the buffer but will not prevent B_INVAL
1748 * operations. If a B_INVAL operation occurs the buffer will remain held
1749 * but the underlying pages may get ripped out.
1751 * These functions are typically used in VOP_READ/VOP_WRITE functions
1752 * to hold a buffer during a copyin or copyout, preventing deadlocks
1753 * or recursive lock panics when read()/write() is used over mmap()'d
1756 * NOTE: bqhold() requires that the buffer be locked at the time of the
1757 * hold. bqdrop() has no requirements other than the buffer having
1758 * previously been held.
1761 bqhold(struct buf *bp)
1763 atomic_add_int(&bp->b_refs, 1);
1767 bqdrop(struct buf *bp)
1769 KKASSERT(bp->b_refs > 0);
1770 atomic_add_int(&bp->b_refs, -1);
1774 * Return backing pages held by the buffer 'bp' back to the VM system.
1775 * This routine is called when the bp is invalidated, released, or
1778 * The KVA mapping (b_data) for the underlying pages is removed by
1781 * WARNING! This routine is integral to the low memory critical path
1782 * when a buffer is B_RELBUF'd. If the system has a severe page
1783 * deficit we need to get the page(s) onto the PQ_FREE or PQ_CACHE
1784 * queues so they can be reused in the current pageout daemon
1788 vfs_vmio_release(struct buf *bp)
1793 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1794 m = bp->b_xio.xio_pages[i];
1795 bp->b_xio.xio_pages[i] = NULL;
1798 * We need to own the page in order to safely unwire it.
1800 vm_page_busy_wait(m, FALSE, "vmiopg");
1803 * The VFS is telling us this is not a meta-data buffer
1804 * even if it is backed by a block device.
1806 if (bp->b_flags & B_NOTMETA)
1807 vm_page_flag_set(m, PG_NOTMETA);
1810 * This is a very important bit of code. We try to track
1811 * VM page use whether the pages are wired into the buffer
1812 * cache or not. While wired into the buffer cache the
1813 * bp tracks the act_count.
1815 * We can choose to place unwired pages on the inactive
1816 * queue (0) or active queue (1). If we place too many
1817 * on the active queue the queue will cycle the act_count
1818 * on pages we'd like to keep, just from single-use pages
1819 * (such as when doing a tar-up or file scan).
1821 if (bp->b_act_count < vm_cycle_point)
1822 vm_page_unwire(m, 0);
1824 vm_page_unwire(m, 1);
1827 * If the wire_count has dropped to 0 we may need to take
1828 * further action before unbusying the page.
1830 * WARNING: vm_page_try_*() also checks PG_NEED_COMMIT for us.
1832 if (m->wire_count == 0) {
1833 if (bp->b_flags & B_DIRECT) {
1835 * Attempt to free the page if B_DIRECT is
1836 * set, the caller does not desire the page
1840 vm_page_try_to_free(m);
1841 } else if ((bp->b_flags & B_NOTMETA) ||
1842 vm_page_count_min(0)) {
1844 * Attempt to move the page to PQ_CACHE
1845 * if B_NOTMETA is set. This flag is set
1846 * by HAMMER to remove one of the two pages
1847 * present when double buffering is enabled.
1849 * Attempt to move the page to PQ_CACHE
1850 * If we have a severe page deficit. This
1851 * will cause buffer cache operations related
1852 * to pageouts to recycle the related pages
1853 * in order to avoid a low memory deadlock.
1855 m->act_count = bp->b_act_count;
1856 vm_page_try_to_cache(m);
1859 * Nominal case, leave the page on the
1860 * queue the original unwiring placed it on
1861 * (active or inactive).
1863 m->act_count = bp->b_act_count;
1872 * Zero out the pmap pte's for the mapping, but don't bother
1873 * invalidating the TLB. The range will be properly invalidating
1874 * when new pages are entered into the mapping.
1876 * This in particular reduces tmpfs tear-down overhead and reduces
1877 * buffer cache re-use overhead (one invalidation sequence instead
1878 * of two per re-use).
1880 pmap_qremove_noinval(trunc_page((vm_offset_t) bp->b_data),
1881 bp->b_xio.xio_npages);
1882 CPUMASK_ASSZERO(bp->b_cpumask);
1883 if (bp->b_bufsize) {
1884 atomic_add_long(&bufspace, -bp->b_bufsize);
1888 bp->b_xio.xio_npages = 0;
1889 bp->b_flags &= ~B_VMIO;
1890 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1896 * Find and initialize a new buffer header, freeing up existing buffers
1897 * in the bufqueues as necessary. The new buffer is returned locked.
1899 * Important: B_INVAL is not set. If the caller wishes to throw the
1900 * buffer away, the caller must set B_INVAL prior to calling brelse().
1903 * We have insufficient buffer headers
1904 * We have insufficient buffer space
1906 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1907 * Instead we ask the buf daemon to do it for us. We attempt to
1908 * avoid piecemeal wakeups of the pageout daemon.
1911 getnewbuf(int blkflags, int slptimeo, int size, int maxsize)
1913 struct bufpcpu *pcpu;
1918 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
1919 int maxloops = 200000;
1920 int restart_reason = 0;
1921 struct buf *restart_bp = NULL;
1922 static char flushingbufs[MAXCPU];
1926 * We can't afford to block since we might be holding a vnode lock,
1927 * which may prevent system daemons from running. We deal with
1928 * low-memory situations by proactively returning memory and running
1929 * async I/O rather then sync I/O.
1933 nqcpu = mycpu->gd_cpuid;
1934 flushingp = &flushingbufs[nqcpu];
1936 if (bufspace < lobufspace)
1939 if (debug_bufbio && --maxloops == 0)
1940 panic("getnewbuf, excessive loops on cpu %d restart %d (%p)",
1941 mycpu->gd_cpuid, restart_reason, restart_bp);
1944 * Setup for scan. If we do not have enough free buffers,
1945 * we setup a degenerate case that immediately fails. Note
1946 * that if we are specially marked process, we are allowed to
1947 * dip into our reserves.
1949 * The scanning sequence is nominally: EMPTY->CLEAN
1951 pcpu = &bufpcpu[nqcpu];
1952 spin_lock(&pcpu->spin);
1955 * Prime the scan for this cpu. Locate the first buffer to
1956 * check. If we are flushing buffers we must skip the
1959 nqindex = BQUEUE_EMPTY;
1960 nbp = TAILQ_FIRST(&pcpu->bufqueues[BQUEUE_EMPTY]);
1961 if (nbp == NULL || *flushingp) {
1962 nqindex = BQUEUE_CLEAN;
1963 nbp = TAILQ_FIRST(&pcpu->bufqueues[BQUEUE_CLEAN]);
1967 * Run scan, possibly freeing data and/or kva mappings on the fly,
1970 * WARNING! spin is held!
1972 while ((bp = nbp) != NULL) {
1973 int qindex = nqindex;
1975 nbp = TAILQ_NEXT(bp, b_freelist);
1978 * BQUEUE_CLEAN - B_AGE special case. If not set the bp
1979 * cycles through the queue twice before being selected.
1981 if (qindex == BQUEUE_CLEAN &&
1982 (bp->b_flags & B_AGE) == 0 && nbp) {
1983 bp->b_flags |= B_AGE;
1984 TAILQ_REMOVE(&pcpu->bufqueues[qindex],
1986 TAILQ_INSERT_TAIL(&pcpu->bufqueues[qindex],
1992 * Calculate next bp ( we can only use it if we do not block
1993 * or do other fancy things ).
1998 nqindex = BQUEUE_CLEAN;
1999 if ((nbp = TAILQ_FIRST(&pcpu->bufqueues[BQUEUE_CLEAN])))
2013 KASSERT(bp->b_qindex == qindex,
2014 ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
2017 * Note: we no longer distinguish between VMIO and non-VMIO
2020 KASSERT((bp->b_flags & B_DELWRI) == 0,
2021 ("delwri buffer %p found in queue %d", bp, qindex));
2024 * Do not try to reuse a buffer with a non-zero b_refs.
2025 * This is an unsynchronized test. A synchronized test
2026 * is also performed after we lock the buffer.
2032 * Start freeing the bp. This is somewhat involved. nbp
2033 * remains valid only for BQUEUE_EMPTY bp's. Buffers
2034 * on the clean list must be disassociated from their
2035 * current vnode. Buffers on the empty lists have
2036 * already been disassociated.
2038 * b_refs is checked after locking along with queue changes.
2039 * We must check here to deal with zero->nonzero transitions
2040 * made by the owner of the buffer lock, which is used by
2041 * VFS's to hold the buffer while issuing an unlocked
2042 * uiomove()s. We cannot invalidate the buffer's pages
2043 * for this case. Once we successfully lock a buffer the
2044 * only 0->1 transitions of b_refs will occur via findblk().
2046 * We must also check for queue changes after successful
2047 * locking as the current lock holder may dispose of the
2048 * buffer and change its queue.
2050 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
2051 spin_unlock(&pcpu->spin);
2052 tsleep(&bd_request, 0, "gnbxxx", (hz + 99) / 100);
2057 if (bp->b_qindex != qindex || bp->b_refs) {
2058 spin_unlock(&pcpu->spin);
2064 bremfree_locked(bp);
2065 spin_unlock(&pcpu->spin);
2068 * Dependancies must be handled before we disassociate the
2071 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
2072 * be immediately disassociated. HAMMER then becomes
2073 * responsible for releasing the buffer.
2075 * NOTE: spin is UNLOCKED now.
2077 if (LIST_FIRST(&bp->b_dep) != NULL) {
2079 if (bp->b_flags & B_LOCKED) {
2085 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2089 * CLEAN buffers have content or associations that must be
2090 * cleaned out if not repurposing.
2092 if (qindex == BQUEUE_CLEAN) {
2093 if (bp->b_flags & B_VMIO)
2094 vfs_vmio_release(bp);
2100 * NOTE: nbp is now entirely invalid. We can only restart
2101 * the scan from this point on.
2103 * Get the rest of the buffer freed up. b_kva* is still
2104 * valid after this operation.
2106 KASSERT(bp->b_vp == NULL,
2107 ("bp3 %p flags %08x vnode %p qindex %d "
2108 "unexpectededly still associated!",
2109 bp, bp->b_flags, bp->b_vp, qindex));
2110 KKASSERT((bp->b_flags & B_HASHED) == 0);
2115 if (bp->b_flags & (B_VNDIRTY | B_VNCLEAN | B_HASHED)) {
2116 kprintf("getnewbuf: caught bug vp queue "
2117 "%p/%08x qidx %d\n",
2118 bp, bp->b_flags, qindex);
2121 bp->b_flags = B_BNOCLIP;
2122 bp->b_cmd = BUF_CMD_DONE;
2127 bp->b_xio.xio_npages = 0;
2128 bp->b_dirtyoff = bp->b_dirtyend = 0;
2129 bp->b_act_count = ACT_INIT;
2131 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2133 if (blkflags & GETBLK_BHEAVY)
2134 bp->b_flags |= B_HEAVY;
2136 if (bufspace >= hibufspace)
2138 if (bufspace < lobufspace)
2141 bp->b_flags |= B_INVAL;
2149 * b_refs can transition to a non-zero value while we hold
2150 * the buffer locked due to a findblk(). Our brelvp() above
2151 * interlocked any future possible transitions due to
2154 * If we find b_refs to be non-zero we can destroy the
2155 * buffer's contents but we cannot yet reuse the buffer.
2158 bp->b_flags |= B_INVAL;
2167 * We found our buffer!
2173 * If we exhausted our list, iterate other cpus. If that fails,
2174 * sleep as appropriate. We may have to wakeup various daemons
2175 * and write out some dirty buffers.
2177 * Generally we are sleeping due to insufficient buffer space.
2179 * NOTE: spin is held if bp is NULL, else it is not held.
2185 spin_unlock(&pcpu->spin);
2187 nqcpu = (nqcpu + 1) % ncpus;
2188 if (nqcpu != mycpu->gd_cpuid) {
2194 if (bufspace >= hibufspace) {
2196 flags = VFS_BIO_NEED_BUFSPACE;
2199 flags = VFS_BIO_NEED_ANY;
2202 bd_speedup(); /* heeeelp */
2203 atomic_set_int(&needsbuffer, flags);
2204 while (needsbuffer & flags) {
2207 tsleep_interlock(&needsbuffer, 0);
2208 value = atomic_fetchadd_int(&needsbuffer, 0);
2209 if (value & flags) {
2210 if (tsleep(&needsbuffer, PINTERLOCKED|slpflags,
2211 waitmsg, slptimeo)) {
2218 * We finally have a valid bp. Reset b_data.
2220 * (spin is not held)
2222 bp->b_data = bp->b_kvabase;
2230 * Buffer flushing daemon. Buffers are normally flushed by the
2231 * update daemon but if it cannot keep up this process starts to
2232 * take the load in an attempt to prevent getnewbuf() from blocking.
2234 * Once a flush is initiated it does not stop until the number
2235 * of buffers falls below lodirtybuffers, but we will wake up anyone
2236 * waiting at the mid-point.
2238 static struct kproc_desc buf_kp = {
2243 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2244 kproc_start, &buf_kp);
2246 static struct kproc_desc bufhw_kp = {
2251 SYSINIT(bufdaemon_hw, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2252 kproc_start, &bufhw_kp);
2255 buf_daemon1(struct thread *td, int queue, int (*buf_limit_fn)(long),
2261 marker = kmalloc(sizeof(*marker), M_BIOBUF, M_WAITOK | M_ZERO);
2262 marker->b_flags |= B_MARKER;
2263 marker->b_qindex = BQUEUE_NONE;
2267 * This process needs to be suspended prior to shutdown sync.
2269 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2270 td, SHUTDOWN_PRI_LAST);
2271 curthread->td_flags |= TDF_SYSTHREAD;
2274 * This process is allowed to take the buffer cache to the limit
2277 kproc_suspend_loop();
2280 * Do the flush as long as the number of dirty buffers
2281 * (including those running) exceeds lodirtybufspace.
2283 * When flushing limit running I/O to hirunningspace
2284 * Do the flush. Limit the amount of in-transit I/O we
2285 * allow to build up, otherwise we would completely saturate
2286 * the I/O system. Wakeup any waiting processes before we
2287 * normally would so they can run in parallel with our drain.
2289 * Our aggregate normal+HW lo water mark is lodirtybufspace,
2290 * but because we split the operation into two threads we
2291 * have to cut it in half for each thread.
2293 waitrunningbufspace();
2294 limit = lodirtybufspace / 2;
2295 while (buf_limit_fn(limit)) {
2296 if (flushbufqueues(marker, queue) == 0)
2298 if (runningbufspace < hirunningspace)
2300 waitrunningbufspace();
2304 * We reached our low water mark, reset the
2305 * request and sleep until we are needed again.
2306 * The sleep is just so the suspend code works.
2308 tsleep_interlock(bd_req, 0);
2309 if (atomic_swap_int(bd_req, 0) == 0)
2310 tsleep(bd_req, PINTERLOCKED, "psleep", hz);
2313 /*kfree(marker, M_BIOBUF);*/
2317 buf_daemon_limit(long limit)
2319 return (runningbufspace + dirtykvaspace > limit ||
2320 dirtybufcount - dirtybufcounthw >= nbuf / 2);
2324 buf_daemon_hw_limit(long limit)
2326 return (runningbufspace + dirtykvaspace > limit ||
2327 dirtybufcounthw >= nbuf / 2);
2333 buf_daemon1(bufdaemon_td, BQUEUE_DIRTY, buf_daemon_limit,
2340 buf_daemon1(bufdaemonhw_td, BQUEUE_DIRTY_HW, buf_daemon_hw_limit,
2345 * Flush up to (flushperqueue) buffers in the dirty queue. Each cpu has a
2346 * localized version of the queue. Each call made to this function iterates
2347 * to another cpu. It is desireable to flush several buffers from the same
2348 * cpu's queue at once, as these are likely going to be linear.
2350 * We must be careful to free up B_INVAL buffers instead of write them, which
2351 * NFS is particularly sensitive to.
2353 * B_RELBUF may only be set by VFSs. We do set B_AGE to indicate that we
2354 * really want to try to get the buffer out and reuse it due to the write
2355 * load on the machine.
2357 * We must lock the buffer in order to check its validity before we can mess
2358 * with its contents. spin isn't enough.
2361 flushbufqueues(struct buf *marker, bufq_type_t q)
2363 struct bufpcpu *pcpu;
2366 u_int loops = flushperqueue;
2367 int lcpu = marker->b_qcpu;
2369 KKASSERT(marker->b_qindex == BQUEUE_NONE);
2370 KKASSERT(marker->b_flags & B_MARKER);
2374 * Spinlock needed to perform operations on the queue and may be
2375 * held through a non-blocking BUF_LOCK(), but cannot be held when
2376 * BUF_UNLOCK()ing or through any other major operation.
2378 pcpu = &bufpcpu[marker->b_qcpu];
2379 spin_lock(&pcpu->spin);
2380 marker->b_qindex = q;
2381 TAILQ_INSERT_HEAD(&pcpu->bufqueues[q], marker, b_freelist);
2384 while ((bp = TAILQ_NEXT(bp, b_freelist)) != NULL) {
2386 * NOTE: spinlock is always held at the top of the loop
2388 if (bp->b_flags & B_MARKER)
2390 if ((bp->b_flags & B_DELWRI) == 0) {
2391 kprintf("Unexpected clean buffer %p\n", bp);
2394 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT))
2396 KKASSERT(bp->b_qcpu == marker->b_qcpu && bp->b_qindex == q);
2399 * Once the buffer is locked we will have no choice but to
2400 * unlock the spinlock around a later BUF_UNLOCK and re-set
2401 * bp = marker when looping. Move the marker now to make
2404 TAILQ_REMOVE(&pcpu->bufqueues[q], marker, b_freelist);
2405 TAILQ_INSERT_AFTER(&pcpu->bufqueues[q], bp, marker, b_freelist);
2408 * Must recheck B_DELWRI after successfully locking
2411 if ((bp->b_flags & B_DELWRI) == 0) {
2412 spin_unlock(&pcpu->spin);
2414 spin_lock(&pcpu->spin);
2420 * Remove the buffer from its queue. We still own the
2426 * Disposing of an invalid buffer counts as a flush op
2428 if (bp->b_flags & B_INVAL) {
2429 spin_unlock(&pcpu->spin);
2435 * Release the spinlock for the more complex ops we
2436 * are now going to do.
2438 spin_unlock(&pcpu->spin);
2442 * This is a bit messy
2444 if (LIST_FIRST(&bp->b_dep) != NULL &&
2445 (bp->b_flags & B_DEFERRED) == 0 &&
2446 buf_countdeps(bp, 0)) {
2447 spin_lock(&pcpu->spin);
2448 TAILQ_INSERT_TAIL(&pcpu->bufqueues[q], bp, b_freelist);
2450 bp->b_flags |= B_DEFERRED;
2451 spin_unlock(&pcpu->spin);
2453 spin_lock(&pcpu->spin);
2459 * spinlock not held here.
2461 * If the buffer has a dependancy, buf_checkwrite() must
2462 * also return 0 for us to be able to initate the write.
2464 * If the buffer is flagged B_ERROR it may be requeued
2465 * over and over again, we try to avoid a live lock.
2467 if (LIST_FIRST(&bp->b_dep) != NULL && buf_checkwrite(bp)) {
2469 } else if (bp->b_flags & B_ERROR) {
2470 tsleep(bp, 0, "bioer", 1);
2471 bp->b_flags &= ~B_AGE;
2474 bp->b_flags |= B_AGE | B_KVABIO;
2477 /* bp invalid but needs to be NULL-tested if we break out */
2479 spin_lock(&pcpu->spin);
2485 /* bp is invalid here but can be NULL-tested to advance */
2487 TAILQ_REMOVE(&pcpu->bufqueues[q], marker, b_freelist);
2488 marker->b_qindex = BQUEUE_NONE;
2489 spin_unlock(&pcpu->spin);
2492 * Advance the marker to be fair.
2494 marker->b_qcpu = (marker->b_qcpu + 1) % ncpus;
2496 if (marker->b_qcpu != lcpu)
2506 * Returns true if no I/O is needed to access the associated VM object.
2507 * This is like findblk except it also hunts around in the VM system for
2510 * Note that we ignore vm_page_free() races from interrupts against our
2511 * lookup, since if the caller is not protected our return value will not
2512 * be any more valid then otherwise once we exit the critical section.
2515 inmem(struct vnode *vp, off_t loffset)
2518 vm_offset_t toff, tinc, size;
2522 if (findblk(vp, loffset, FINDBLK_TEST))
2524 if (vp->v_mount == NULL)
2526 if ((obj = vp->v_object) == NULL)
2530 if (size > vp->v_mount->mnt_stat.f_iosize)
2531 size = vp->v_mount->mnt_stat.f_iosize;
2533 vm_object_hold(obj);
2534 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2535 m = vm_page_lookup(obj, OFF_TO_IDX(loffset + toff));
2541 if (tinc > PAGE_SIZE - ((toff + loffset) & PAGE_MASK))
2542 tinc = PAGE_SIZE - ((toff + loffset) & PAGE_MASK);
2543 if (vm_page_is_valid(m,
2544 (vm_offset_t) ((toff + loffset) & PAGE_MASK), tinc) == 0) {
2549 vm_object_drop(obj);
2556 * Locate and return the specified buffer. Unless flagged otherwise,
2557 * a locked buffer will be returned if it exists or NULL if it does not.
2559 * findblk()'d buffers are still on the bufqueues and if you intend
2560 * to use your (locked NON-TEST) buffer you need to bremfree(bp)
2561 * and possibly do other stuff to it.
2563 * FINDBLK_TEST - Do not lock the buffer. The caller is responsible
2564 * for locking the buffer and ensuring that it remains
2565 * the desired buffer after locking.
2567 * FINDBLK_NBLOCK - Lock the buffer non-blocking. If we are unable
2568 * to acquire the lock we return NULL, even if the
2571 * FINDBLK_REF - Returns the buffer ref'd, which prevents normal
2572 * reuse by getnewbuf() but does not prevent
2573 * disassociation (B_INVAL). Used to avoid deadlocks
2574 * against random (vp,loffset)s due to reassignment.
2576 * FINDBLK_KVABIO - Only applicable when returning a locked buffer.
2577 * Indicates that the caller supports B_KVABIO.
2579 * (0) - Lock the buffer blocking.
2582 findblk(struct vnode *vp, off_t loffset, int flags)
2587 lkflags = LK_EXCLUSIVE;
2588 if (flags & FINDBLK_NBLOCK)
2589 lkflags |= LK_NOWAIT;
2593 * Lookup. Ref the buf while holding v_token to prevent
2594 * reuse (but does not prevent diassociation).
2596 lwkt_gettoken_shared(&vp->v_token);
2597 bp = buf_rb_hash_RB_LOOKUP(&vp->v_rbhash_tree, loffset);
2599 lwkt_reltoken(&vp->v_token);
2603 lwkt_reltoken(&vp->v_token);
2606 * If testing only break and return bp, do not lock.
2608 if (flags & FINDBLK_TEST)
2612 * Lock the buffer, return an error if the lock fails.
2613 * (only FINDBLK_NBLOCK can cause the lock to fail).
2615 if (BUF_LOCK(bp, lkflags)) {
2616 atomic_subtract_int(&bp->b_refs, 1);
2617 /* bp = NULL; not needed */
2622 * Revalidate the locked buf before allowing it to be
2625 * B_KVABIO is only set/cleared when locking. When
2626 * clearing B_KVABIO, we must ensure that the buffer
2627 * is synchronized to all cpus.
2629 if (bp->b_vp == vp && bp->b_loffset == loffset) {
2630 if (flags & FINDBLK_KVABIO)
2631 bp->b_flags |= B_KVABIO;
2636 atomic_subtract_int(&bp->b_refs, 1);
2643 if ((flags & FINDBLK_REF) == 0)
2644 atomic_subtract_int(&bp->b_refs, 1);
2651 * Similar to getblk() except only returns the buffer if it is
2652 * B_CACHE and requires no other manipulation. Otherwise NULL
2653 * is returned. NULL is also returned if GETBLK_NOWAIT is set
2654 * and the getblk() would block.
2656 * If B_RAM is set the buffer might be just fine, but we return
2657 * NULL anyway because we want the code to fall through to the
2658 * cluster read to issue more read-aheads. Otherwise read-ahead breaks.
2660 * If blksize is 0 the buffer cache buffer must already be fully
2663 * If blksize is non-zero getblk() will be used, allowing a buffer
2664 * to be reinstantiated from its VM backing store. The buffer must
2665 * still be fully cached after reinstantiation to be returned.
2668 getcacheblk(struct vnode *vp, off_t loffset, int blksize, int blkflags)
2673 if (blkflags & GETBLK_NOWAIT)
2674 fndflags |= FINDBLK_NBLOCK;
2675 if (blkflags & GETBLK_KVABIO)
2676 fndflags |= FINDBLK_KVABIO;
2679 bp = getblk(vp, loffset, blksize, blkflags, 0);
2681 if ((bp->b_flags & (B_INVAL | B_CACHE)) == B_CACHE) {
2682 bp->b_flags &= ~B_AGE;
2683 if (bp->b_flags & B_RAM) {
2693 bp = findblk(vp, loffset, fndflags);
2695 if ((bp->b_flags & (B_INVAL | B_CACHE | B_RAM)) ==
2697 bp->b_flags &= ~B_AGE;
2711 * Get a block given a specified block and offset into a file/device.
2712 * B_INVAL may or may not be set on return. The caller should clear
2713 * B_INVAL prior to initiating a READ.
2715 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2716 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2717 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2718 * without doing any of those things the system will likely believe
2719 * the buffer to be valid (especially if it is not B_VMIO), and the
2720 * next getblk() will return the buffer with B_CACHE set.
2722 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2723 * an existing buffer.
2725 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2726 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2727 * and then cleared based on the backing VM. If the previous buffer is
2728 * non-0-sized but invalid, B_CACHE will be cleared.
2730 * If getblk() must create a new buffer, the new buffer is returned with
2731 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2732 * case it is returned with B_INVAL clear and B_CACHE set based on the
2735 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
2736 * B_CACHE bit is clear.
2738 * What this means, basically, is that the caller should use B_CACHE to
2739 * determine whether the buffer is fully valid or not and should clear
2740 * B_INVAL prior to issuing a read. If the caller intends to validate
2741 * the buffer by loading its data area with something, the caller needs
2742 * to clear B_INVAL. If the caller does this without issuing an I/O,
2743 * the caller should set B_CACHE ( as an optimization ), else the caller
2744 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2745 * a write attempt or if it was a successfull read. If the caller
2746 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2747 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2751 * GETBLK_PCATCH - catch signal if blocked, can cause NULL return
2752 * GETBLK_BHEAVY - heavy-weight buffer cache buffer
2755 getblk(struct vnode *vp, off_t loffset, int size, int blkflags, int slptimeo)
2758 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
2762 if (size > MAXBSIZE)
2763 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2764 if (vp->v_object == NULL)
2765 panic("getblk: vnode %p has no object!", vp);
2768 * NOTE: findblk does not try to resolve KVABIO in REF-only mode.
2769 * we still have to handle that ourselves.
2772 if ((bp = findblk(vp, loffset, FINDBLK_REF | FINDBLK_TEST)) != NULL) {
2774 * The buffer was found in the cache, but we need to lock it.
2775 * We must acquire a ref on the bp to prevent reuse, but
2776 * this will not prevent disassociation (brelvp()) so we
2777 * must recheck (vp,loffset) after acquiring the lock.
2779 * Without the ref the buffer could potentially be reused
2780 * before we acquire the lock and create a deadlock
2781 * situation between the thread trying to reuse the buffer
2782 * and us due to the fact that we would wind up blocking
2783 * on a random (vp,loffset).
2785 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2786 if (blkflags & GETBLK_NOWAIT) {
2790 lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
2791 if (blkflags & GETBLK_PCATCH)
2792 lkflags |= LK_PCATCH;
2793 error = BUF_TIMELOCK(bp, lkflags, "getblk", slptimeo);
2796 if (error == ENOLCK)
2800 /* buffer may have changed on us */
2805 * Once the buffer has been locked, make sure we didn't race
2806 * a buffer recyclement. Buffers that are no longer hashed
2807 * will have b_vp == NULL, so this takes care of that check
2810 if (bp->b_vp != vp || bp->b_loffset != loffset) {
2812 kprintf("Warning buffer %p (vp %p loffset %lld) "
2814 bp, vp, (long long)loffset);
2821 * If SZMATCH any pre-existing buffer must be of the requested
2822 * size or NULL is returned. The caller absolutely does not
2823 * want getblk() to bwrite() the buffer on a size mismatch.
2825 if ((blkflags & GETBLK_SZMATCH) && size != bp->b_bcount) {
2831 * All vnode-based buffers must be backed by a VM object.
2833 * Set B_KVABIO for any incidental work, we will fix it
2836 KKASSERT(bp->b_flags & B_VMIO);
2837 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2838 bp->b_flags &= ~B_AGE;
2839 bp->b_flags |= B_KVABIO;
2842 * Make sure that B_INVAL buffers do not have a cached
2843 * block number translation.
2845 if ((bp->b_flags & B_INVAL) &&
2846 (bp->b_bio2.bio_offset != NOOFFSET)) {
2847 kprintf("Warning invalid buffer %p (vp %p loffset %lld)"
2848 " did not have cleared bio_offset cache\n",
2849 bp, vp, (long long)loffset);
2850 clearbiocache(&bp->b_bio2);
2854 * The buffer is locked. B_CACHE is cleared if the buffer is
2857 * After the bremfree(), disposals must use b[q]relse().
2859 if (bp->b_flags & B_INVAL)
2860 bp->b_flags &= ~B_CACHE;
2864 * Any size inconsistancy with a dirty buffer or a buffer
2865 * with a softupdates dependancy must be resolved. Resizing
2866 * the buffer in such circumstances can lead to problems.
2868 * Dirty or dependant buffers are written synchronously.
2869 * Other types of buffers are simply released and
2870 * reconstituted as they may be backed by valid, dirty VM
2871 * pages (but not marked B_DELWRI).
2873 * NFS NOTE: NFS buffers which straddle EOF are oddly-sized
2874 * and may be left over from a prior truncation (and thus
2875 * no longer represent the actual EOF point), so we
2876 * definitely do not want to B_NOCACHE the backing store.
2878 if (size != bp->b_bcount) {
2879 if (bp->b_flags & B_DELWRI) {
2880 bp->b_flags |= B_RELBUF;
2882 } else if (LIST_FIRST(&bp->b_dep)) {
2883 bp->b_flags |= B_RELBUF;
2886 bp->b_flags |= B_RELBUF;
2891 KKASSERT(size <= bp->b_kvasize);
2892 KASSERT(bp->b_loffset != NOOFFSET,
2893 ("getblk: no buffer offset"));
2896 * A buffer with B_DELWRI set and B_CACHE clear must
2897 * be committed before we can return the buffer in
2898 * order to prevent the caller from issuing a read
2899 * ( due to B_CACHE not being set ) and overwriting
2902 * Most callers, including NFS and FFS, need this to
2903 * operate properly either because they assume they
2904 * can issue a read if B_CACHE is not set, or because
2905 * ( for example ) an uncached B_DELWRI might loop due
2906 * to softupdates re-dirtying the buffer. In the latter
2907 * case, B_CACHE is set after the first write completes,
2908 * preventing further loops.
2910 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2911 * above while extending the buffer, we cannot allow the
2912 * buffer to remain with B_CACHE set after the write
2913 * completes or it will represent a corrupt state. To
2914 * deal with this we set B_NOCACHE to scrap the buffer
2917 * XXX Should this be B_RELBUF instead of B_NOCACHE?
2918 * I'm not even sure this state is still possible
2919 * now that getblk() writes out any dirty buffers
2922 * We might be able to do something fancy, like setting
2923 * B_CACHE in bwrite() except if B_DELWRI is already set,
2924 * so the below call doesn't set B_CACHE, but that gets real
2925 * confusing. This is much easier.
2927 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2928 kprintf("getblk: Warning, bp %p loff=%jx DELWRI set "
2929 "and CACHE clear, b_flags %08x\n",
2930 bp, (uintmax_t)bp->b_loffset, bp->b_flags);
2931 bp->b_flags |= B_NOCACHE;
2937 * Buffer is not in-core, create new buffer. The buffer
2938 * returned by getnewbuf() is locked. Note that the returned
2939 * buffer is also considered valid (not marked B_INVAL).
2941 * Calculating the offset for the I/O requires figuring out
2942 * the block size. We use DEV_BSIZE for VBLK or VCHR and
2943 * the mount's f_iosize otherwise. If the vnode does not
2944 * have an associated mount we assume that the passed size is
2947 * Note that vn_isdisk() cannot be used here since it may
2948 * return a failure for numerous reasons. Note that the
2949 * buffer size may be larger then the block size (the caller
2950 * will use block numbers with the proper multiple). Beware
2951 * of using any v_* fields which are part of unions. In
2952 * particular, in DragonFly the mount point overloading
2953 * mechanism uses the namecache only and the underlying
2954 * directory vnode is not a special case.
2958 if (vp->v_type == VBLK || vp->v_type == VCHR)
2960 else if (vp->v_mount)
2961 bsize = vp->v_mount->mnt_stat.f_iosize;
2965 maxsize = size + (loffset & PAGE_MASK);
2966 maxsize = imax(maxsize, bsize);
2968 bp = getnewbuf(blkflags, slptimeo, size, maxsize);
2970 if (slpflags || slptimeo)
2976 * Atomically insert the buffer into the hash, so that it can
2977 * be found by findblk().
2979 * If bgetvp() returns non-zero a collision occured, and the
2980 * bp will not be associated with the vnode.
2982 * Make sure the translation layer has been cleared.
2984 bp->b_loffset = loffset;
2985 bp->b_bio2.bio_offset = NOOFFSET;
2986 /* bp->b_bio2.bio_next = NULL; */
2988 if (bgetvp(vp, bp, size)) {
2989 bp->b_flags |= B_INVAL;
2995 * All vnode-based buffers must be backed by a VM object.
2997 * Set B_KVABIO for incidental work
2999 KKASSERT(vp->v_object != NULL);
3000 bp->b_flags |= B_VMIO | B_KVABIO;
3001 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
3007 * Do the nasty smp broadcast (if the buffer needs it) when KVABIO
3010 if (bp && (blkflags & GETBLK_KVABIO) == 0) {
3019 * Reacquire a buffer that was previously released to the locked queue,
3020 * or reacquire a buffer which is interlocked by having bioops->io_deallocate
3021 * set B_LOCKED (which handles the acquisition race).
3023 * To this end, either B_LOCKED must be set or the dependancy list must be
3027 regetblk(struct buf *bp)
3029 KKASSERT((bp->b_flags & B_LOCKED) || LIST_FIRST(&bp->b_dep) != NULL);
3030 BUF_LOCK(bp, LK_EXCLUSIVE | LK_RETRY);
3037 * This code constitutes the buffer memory from either anonymous system
3038 * memory (in the case of non-VMIO operations) or from an associated
3039 * VM object (in the case of VMIO operations). This code is able to
3040 * resize a buffer up or down.
3042 * Note that this code is tricky, and has many complications to resolve
3043 * deadlock or inconsistant data situations. Tread lightly!!!
3044 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3045 * the caller. Calling this code willy nilly can result in the loss of
3048 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
3049 * B_CACHE for the non-VMIO case.
3051 * This routine does not need to be called from a critical section but you
3052 * must own the buffer.
3055 allocbuf(struct buf *bp, int size)
3062 if (BUF_REFCNT(bp) == 0)
3063 panic("allocbuf: buffer not busy");
3065 if (bp->b_kvasize < size)
3066 panic("allocbuf: buffer too small");
3068 KKASSERT(bp->b_flags & B_VMIO);
3070 newbsize = roundup2(size, DEV_BSIZE);
3071 desiredpages = ((int)(bp->b_loffset & PAGE_MASK) +
3072 newbsize + PAGE_MASK) >> PAGE_SHIFT;
3073 KKASSERT(desiredpages <= XIO_INTERNAL_PAGES);
3076 * Set B_CACHE initially if buffer is 0 length or will become
3079 if (size == 0 || bp->b_bufsize == 0)
3080 bp->b_flags |= B_CACHE;
3082 if (newbsize < bp->b_bufsize) {
3084 * DEV_BSIZE aligned new buffer size is less then the
3085 * DEV_BSIZE aligned existing buffer size. Figure out
3086 * if we have to remove any pages.
3088 if (desiredpages < bp->b_xio.xio_npages) {
3089 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
3091 * the page is not freed here -- it
3092 * is the responsibility of
3093 * vnode_pager_setsize
3095 m = bp->b_xio.xio_pages[i];
3096 KASSERT(m != bogus_page,
3097 ("allocbuf: bogus page found"));
3098 vm_page_busy_wait(m, TRUE, "biodep");
3099 bp->b_xio.xio_pages[i] = NULL;
3100 vm_page_unwire(m, 0);
3103 pmap_qremove_noinval((vm_offset_t)
3104 trunc_page((vm_offset_t)bp->b_data) +
3105 (desiredpages << PAGE_SHIFT),
3106 (bp->b_xio.xio_npages - desiredpages));
3107 bp->b_xio.xio_npages = desiredpages;
3110 * Don't bother invalidating the pmap changes
3111 * (which wastes global SMP invalidation IPIs)
3112 * when setting the size to 0. This case occurs
3113 * when called via getnewbuf() during buffer
3116 if (desiredpages == 0) {
3117 CPUMASK_ASSZERO(bp->b_cpumask);
3122 } else if (size > bp->b_bcount) {
3124 * We are growing the buffer, possibly in a
3125 * byte-granular fashion.
3133 * Step 1, bring in the VM pages from the object,
3134 * allocating them if necessary. We must clear
3135 * B_CACHE if these pages are not valid for the
3136 * range covered by the buffer.
3141 vm_object_hold(obj);
3142 while (bp->b_xio.xio_npages < desiredpages) {
3147 pi = OFF_TO_IDX(bp->b_loffset) +
3148 bp->b_xio.xio_npages;
3151 * Blocking on m->busy_count might lead to a
3154 * vm_fault->getpages->cluster_read->allocbuf
3156 m = vm_page_lookup_busy_try(obj, pi, FALSE,
3159 vm_page_sleep_busy(m, FALSE, "pgtblk");
3164 * note: must allocate system pages
3165 * since blocking here could intefere
3166 * with paging I/O, no matter which
3169 m = bio_page_alloc(bp, obj, pi,
3171 bp->b_xio.xio_npages);
3175 bp->b_flags &= ~B_CACHE;
3176 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
3177 ++bp->b_xio.xio_npages;
3183 * We found a page and were able to busy it.
3187 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
3188 ++bp->b_xio.xio_npages;
3189 if (bp->b_act_count < m->act_count)
3190 bp->b_act_count = m->act_count;
3192 vm_object_drop(obj);
3195 * Step 2. We've loaded the pages into the buffer,
3196 * we have to figure out if we can still have B_CACHE
3197 * set. Note that B_CACHE is set according to the
3198 * byte-granular range ( bcount and size ), not the
3199 * aligned range ( newbsize ).
3201 * The VM test is against m->valid, which is DEV_BSIZE
3202 * aligned. Needless to say, the validity of the data
3203 * needs to also be DEV_BSIZE aligned. Note that this
3204 * fails with NFS if the server or some other client
3205 * extends the file's EOF. If our buffer is resized,
3206 * B_CACHE may remain set! XXX
3209 toff = bp->b_bcount;
3210 tinc = PAGE_SIZE - ((bp->b_loffset + toff) & PAGE_MASK);
3212 while ((bp->b_flags & B_CACHE) && toff < size) {
3215 if (tinc > (size - toff))
3218 pi = ((bp->b_loffset & PAGE_MASK) + toff) >>
3226 bp->b_xio.xio_pages[pi]
3233 * Step 3, fixup the KVM pmap. Remember that
3234 * bp->b_data is relative to bp->b_loffset, but
3235 * bp->b_loffset may be offset into the first page.
3237 bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
3238 pmap_qenter_noinval((vm_offset_t)bp->b_data,
3239 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3240 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
3241 (vm_offset_t)(bp->b_loffset & PAGE_MASK));
3244 atomic_add_long(&bufspace, newbsize - bp->b_bufsize);
3246 /* adjust space use on already-dirty buffer */
3247 if (bp->b_flags & B_DELWRI) {
3248 /* dirtykvaspace unchanged */
3249 atomic_add_long(&dirtybufspace, newbsize - bp->b_bufsize);
3250 if (bp->b_flags & B_HEAVY) {
3251 atomic_add_long(&dirtybufspacehw,
3252 newbsize - bp->b_bufsize);
3255 bp->b_bufsize = newbsize; /* actual buffer allocation */
3256 bp->b_bcount = size; /* requested buffer size */
3263 * Wait for buffer I/O completion, returning error status. B_EINTR
3264 * is converted into an EINTR error but not cleared (since a chain
3265 * of biowait() calls may occur).
3267 * On return bpdone() will have been called but the buffer will remain
3268 * locked and will not have been brelse()'d.
3270 * NOTE! If a timeout is specified and ETIMEDOUT occurs the I/O is
3271 * likely still in progress on return.
3273 * NOTE! This operation is on a BIO, not a BUF.
3275 * NOTE! BIO_DONE is cleared by vn_strategy()
3278 _biowait(struct bio *bio, const char *wmesg, int to)
3280 struct buf *bp = bio->bio_buf;
3285 KKASSERT(bio == &bp->b_bio1);
3287 flags = bio->bio_flags;
3288 if (flags & BIO_DONE)
3290 nflags = flags | BIO_WANT;
3291 tsleep_interlock(bio, 0);
3292 if (atomic_cmpset_int(&bio->bio_flags, flags, nflags)) {
3294 error = tsleep(bio, PINTERLOCKED, wmesg, to);
3295 else if (bp->b_cmd == BUF_CMD_READ)
3296 error = tsleep(bio, PINTERLOCKED, "biord", to);
3298 error = tsleep(bio, PINTERLOCKED, "biowr", to);
3300 kprintf("tsleep error biowait %d\n", error);
3309 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
3310 bio->bio_flags &= ~(BIO_DONE | BIO_SYNC);
3311 if (bp->b_flags & B_EINTR)
3313 if (bp->b_flags & B_ERROR)
3314 return (bp->b_error ? bp->b_error : EIO);
3319 biowait(struct bio *bio, const char *wmesg)
3321 return(_biowait(bio, wmesg, 0));
3325 biowait_timeout(struct bio *bio, const char *wmesg, int to)
3327 return(_biowait(bio, wmesg, to));
3331 * This associates a tracking count with an I/O. vn_strategy() and
3332 * dev_dstrategy() do this automatically but there are a few cases
3333 * where a vnode or device layer is bypassed when a block translation
3334 * is cached. In such cases bio_start_transaction() may be called on
3335 * the bypassed layers so the system gets an I/O in progress indication
3336 * for those higher layers.
3339 bio_start_transaction(struct bio *bio, struct bio_track *track)
3341 bio->bio_track = track;
3342 bio_track_ref(track);
3343 dsched_buf_enter(bio->bio_buf); /* might stack */
3347 * Initiate I/O on a vnode.
3349 * SWAPCACHE OPERATION:
3351 * Real buffer cache buffers have a non-NULL bp->b_vp. Unfortunately
3352 * devfs also uses b_vp for fake buffers so we also have to check
3353 * that B_PAGING is 0. In this case the passed 'vp' is probably the
3354 * underlying block device. The swap assignments are related to the
3355 * buffer cache buffer's b_vp, not the passed vp.
3357 * The passed vp == bp->b_vp only in the case where the strategy call
3358 * is made on the vp itself for its own buffers (a regular file or
3359 * block device vp). The filesystem usually then re-calls vn_strategy()
3360 * after translating the request to an underlying device.
3362 * Cluster buffers set B_CLUSTER and the passed vp is the vp of the
3363 * underlying buffer cache buffers.
3365 * We can only deal with page-aligned buffers at the moment, because
3366 * we can't tell what the real dirty state for pages straddling a buffer
3369 * In order to call swap_pager_strategy() we must provide the VM object
3370 * and base offset for the underlying buffer cache pages so it can find
3374 vn_strategy(struct vnode *vp, struct bio *bio)
3376 struct bio_track *track;
3377 struct buf *bp = bio->bio_buf;
3379 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3382 * Set when an I/O is issued on the bp. Cleared by consumers
3383 * (aka HAMMER), allowing the consumer to determine if I/O had
3384 * actually occurred.
3386 bp->b_flags |= B_IOISSUED;
3389 * Handle the swapcache intercept.
3391 * NOTE: The swapcache itself always supports KVABIO and will
3392 * do the right thing if its underlying devices do not.
3394 if (vn_cache_strategy(vp, bio))
3398 * If the vnode does not support KVABIO and the buffer is using
3399 * KVABIO, we must synchronize b_data to all cpus before dispatching.
3401 if ((vp->v_flag & VKVABIO) == 0 && (bp->b_flags & B_KVABIO))
3405 * Otherwise do the operation through the filesystem
3407 if (bp->b_cmd == BUF_CMD_READ)
3408 track = &vp->v_track_read;
3410 track = &vp->v_track_write;
3411 KKASSERT((bio->bio_flags & BIO_DONE) == 0);
3412 bio->bio_track = track;
3413 bio_track_ref(track);
3414 dsched_buf_enter(bp); /* might stack */
3415 vop_strategy(*vp->v_ops, vp, bio);
3419 * vn_cache_strategy()
3421 * NOTE: This function supports the KVABIO API wherein b_data might not
3422 * be synchronized to the current cpu.
3424 static void vn_cache_strategy_callback(struct bio *bio);
3427 vn_cache_strategy(struct vnode *vp, struct bio *bio)
3429 struct buf *bp = bio->bio_buf;
3436 * Stop using swapcache if paniced, dumping, or dumped
3438 if (panicstr || dumping)
3442 * Is this buffer cache buffer suitable for reading from
3445 if (vm_swapcache_read_enable == 0 ||
3446 bp->b_cmd != BUF_CMD_READ ||
3447 ((bp->b_flags & B_CLUSTER) == 0 &&
3448 (bp->b_vp == NULL || (bp->b_flags & B_PAGING))) ||
3449 ((int)bp->b_loffset & PAGE_MASK) != 0 ||
3450 (bp->b_bcount & PAGE_MASK) != 0) {
3455 * Figure out the original VM object (it will match the underlying
3456 * VM pages). Note that swap cached data uses page indices relative
3457 * to that object, not relative to bio->bio_offset.
3459 if (bp->b_flags & B_CLUSTER)
3460 object = vp->v_object;
3462 object = bp->b_vp->v_object;
3465 * In order to be able to use the swap cache all underlying VM
3466 * pages must be marked as such, and we can't have any bogus pages.
3468 for (i = 0; i < bp->b_xio.xio_npages; ++i) {
3469 m = bp->b_xio.xio_pages[i];
3470 if ((m->flags & PG_SWAPPED) == 0)
3472 if (m == bogus_page)
3477 * If we are good then issue the I/O using swap_pager_strategy().
3479 * We can only do this if the buffer actually supports object-backed
3480 * I/O. If it doesn't npages will be 0.
3482 if (i && i == bp->b_xio.xio_npages) {
3483 m = bp->b_xio.xio_pages[0];
3484 nbio = push_bio(bio);
3485 nbio->bio_done = vn_cache_strategy_callback;
3486 nbio->bio_offset = ptoa(m->pindex);
3487 KKASSERT(m->object == object);
3488 swap_pager_strategy(object, nbio);
3495 * This is a bit of a hack but since the vn_cache_strategy() function can
3496 * override a VFS's strategy function we must make sure that the bio, which
3497 * is probably bio2, doesn't leak an unexpected offset value back to the
3498 * filesystem. The filesystem (e.g. UFS) might otherwise assume that the
3499 * bio went through its own file strategy function and the the bio2 offset
3500 * is a cached disk offset when, in fact, it isn't.
3503 vn_cache_strategy_callback(struct bio *bio)
3505 bio->bio_offset = NOOFFSET;
3506 biodone(pop_bio(bio));
3512 * Finish I/O on a buffer after all BIOs have been processed.
3513 * Called when the bio chain is exhausted or by biowait. If called
3514 * by biowait, elseit is typically 0.
3516 * bpdone is also responsible for setting B_CACHE in a B_VMIO bp.
3517 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3518 * assuming B_INVAL is clear.
3520 * For the VMIO case, we set B_CACHE if the op was a read and no
3521 * read error occured, or if the op was a write. B_CACHE is never
3522 * set if the buffer is invalid or otherwise uncacheable.
3524 * bpdone does not mess with B_INVAL, allowing the I/O routine or the
3525 * initiator to leave B_INVAL set to brelse the buffer out of existance
3526 * in the biodone routine.
3528 * bpdone is responsible for calling bundirty() on the buffer after a
3529 * successful write. We previously did this prior to initiating the
3530 * write under the assumption that the buffer might be dirtied again
3531 * while the write was in progress, however doing it before-hand creates
3532 * a race condition prior to the call to vn_strategy() where the
3533 * filesystem may not be aware that a dirty buffer is present.
3534 * It should not be possible for the buffer or its underlying pages to
3535 * be redirtied prior to bpdone()'s unbusying of the underlying VM
3539 bpdone(struct buf *bp, int elseit)
3543 KASSERT(BUF_REFCNTNB(bp) > 0,
3544 ("bpdone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
3545 KASSERT(bp->b_cmd != BUF_CMD_DONE,
3546 ("bpdone: bp %p already done!", bp));
3549 * No more BIOs are left. All completion functions have been dealt
3550 * with, now we clean up the buffer.
3553 bp->b_cmd = BUF_CMD_DONE;
3556 * Only reads and writes are processed past this point.
3558 if (cmd != BUF_CMD_READ && cmd != BUF_CMD_WRITE) {
3559 if (cmd == BUF_CMD_FREEBLKS)
3560 bp->b_flags |= B_NOCACHE;
3567 * A failed write must re-dirty the buffer unless B_INVAL
3570 * A successful write must clear the dirty flag. This is done after
3571 * the write to ensure that the buffer remains on the vnode's dirty
3572 * list for filesystem interlocks / checks until the write is actually
3573 * complete. HAMMER2 is sensitive to this issue.
3575 * Only applicable to normal buffers (with VPs). vinum buffers may
3578 * Must be done prior to calling buf_complete() as the callback might
3579 * re-dirty the buffer.
3581 if (cmd == BUF_CMD_WRITE) {
3582 if ((bp->b_flags & (B_ERROR | B_INVAL)) == B_ERROR) {
3583 bp->b_flags &= ~B_NOCACHE;
3593 * Warning: softupdates may re-dirty the buffer, and HAMMER can do
3594 * a lot worse. XXX - move this above the clearing of b_cmd
3596 if (LIST_FIRST(&bp->b_dep) != NULL)
3599 if (bp->b_flags & B_VMIO) {
3605 struct vnode *vp = bp->b_vp;
3609 #if defined(VFS_BIO_DEBUG)
3610 if (vp->v_auxrefs == 0)
3611 panic("bpdone: zero vnode hold count");
3612 if ((vp->v_flag & VOBJBUF) == 0)
3613 panic("bpdone: vnode is not setup for merged cache");
3616 foff = bp->b_loffset;
3617 KASSERT(foff != NOOFFSET, ("bpdone: no buffer offset"));
3618 KASSERT(obj != NULL, ("bpdone: missing VM object"));
3620 #if defined(VFS_BIO_DEBUG)
3621 if (obj->paging_in_progress < bp->b_xio.xio_npages) {
3622 kprintf("bpdone: paging in progress(%d) < "
3623 "bp->b_xio.xio_npages(%d)\n",
3624 obj->paging_in_progress,
3625 bp->b_xio.xio_npages);
3630 * Set B_CACHE if the op was a normal read and no error
3631 * occured. B_CACHE is set for writes in the b*write()
3634 iosize = bp->b_bcount - bp->b_resid;
3635 if (cmd == BUF_CMD_READ &&
3636 (bp->b_flags & (B_INVAL|B_NOCACHE|B_ERROR)) == 0) {
3637 bp->b_flags |= B_CACHE;
3640 vm_object_hold(obj);
3641 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3645 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3650 * cleanup bogus pages, restoring the originals. Since
3651 * the originals should still be wired, we don't have
3652 * to worry about interrupt/freeing races destroying
3653 * the VM object association.
3655 m = bp->b_xio.xio_pages[i];
3656 if (m == bogus_page) {
3657 if ((bp->b_flags & B_HASBOGUS) == 0)
3658 panic("bpdone: bp %p corrupt bogus", bp);
3659 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3661 panic("bpdone: page disappeared");
3662 bp->b_xio.xio_pages[i] = m;
3667 #if defined(VFS_BIO_DEBUG)
3668 if (OFF_TO_IDX(foff) != m->pindex) {
3669 kprintf("bpdone: foff(%lu)/m->pindex(%ld) "
3671 (unsigned long)foff, (long)m->pindex);
3676 * In the write case, the valid and clean bits are
3677 * already changed correctly (see bdwrite()), so we
3678 * only need to do this here in the read case.
3680 vm_page_busy_wait(m, FALSE, "bpdpgw");
3681 if (cmd == BUF_CMD_READ && isbogus == 0 && resid > 0)
3682 vfs_clean_one_page(bp, i, m);
3685 * when debugging new filesystems or buffer I/O
3686 * methods, this is the most common error that pops
3687 * up. if you see this, you have not set the page
3688 * busy flag correctly!!!
3690 if ((m->busy_count & PBUSY_MASK) == 0) {
3691 kprintf("bpdone: page busy < 0, "
3692 "pindex: %d, foff: 0x(%x,%x), "
3693 "resid: %d, index: %d\n",
3694 (int) m->pindex, (int)(foff >> 32),
3695 (int) foff & 0xffffffff, resid, i);
3696 if (!vn_isdisk(vp, NULL))
3697 kprintf(" iosize: %ld, loffset: %lld, "
3698 "flags: 0x%08x, npages: %d\n",
3699 bp->b_vp->v_mount->mnt_stat.f_iosize,
3700 (long long)bp->b_loffset,
3701 bp->b_flags, bp->b_xio.xio_npages);
3703 kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
3704 (long long)bp->b_loffset,
3705 bp->b_flags, bp->b_xio.xio_npages);
3706 kprintf(" valid: 0x%x, dirty: 0x%x, "
3710 panic("bpdone: page busy < 0");
3712 vm_page_io_finish(m);
3714 vm_object_pip_wakeup(obj);
3715 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3718 if (bp->b_flags & B_HASBOGUS) {
3719 pmap_qenter_noinval(trunc_page((vm_offset_t)bp->b_data),
3720 bp->b_xio.xio_pages,
3721 bp->b_xio.xio_npages);
3722 bp->b_flags &= ~B_HASBOGUS;
3725 vm_object_drop(obj);
3729 * Finish up by releasing the buffer. There are no more synchronous
3730 * or asynchronous completions, those were handled by bio_done
3734 if (bp->b_flags & (B_NOCACHE|B_INVAL|B_ERROR|B_RELBUF))
3745 biodone(struct bio *bio)
3747 struct buf *bp = bio->bio_buf;
3749 runningbufwakeup(bp);
3752 * Run up the chain of BIO's. Leave b_cmd intact for the duration.
3755 biodone_t *done_func;
3756 struct bio_track *track;
3759 * BIO tracking. Most but not all BIOs are tracked.
3761 if ((track = bio->bio_track) != NULL) {
3762 bio_track_rel(track);
3763 bio->bio_track = NULL;
3767 * A bio_done function terminates the loop. The function
3768 * will be responsible for any further chaining and/or
3769 * buffer management.
3771 * WARNING! The done function can deallocate the buffer!
3773 if ((done_func = bio->bio_done) != NULL) {
3774 bio->bio_done = NULL;
3778 bio = bio->bio_prev;
3782 * If we've run out of bio's do normal [a]synchronous completion.
3788 * Synchronous biodone - this terminates a synchronous BIO.
3790 * bpdone() is called with elseit=FALSE, leaving the buffer completed
3791 * but still locked. The caller must brelse() the buffer after waiting
3795 biodone_sync(struct bio *bio)
3797 struct buf *bp = bio->bio_buf;
3801 KKASSERT(bio == &bp->b_bio1);
3805 flags = bio->bio_flags;
3806 nflags = (flags | BIO_DONE) & ~BIO_WANT;
3808 if (atomic_cmpset_int(&bio->bio_flags, flags, nflags)) {
3809 if (flags & BIO_WANT)
3819 * This routine is called in lieu of iodone in the case of
3820 * incomplete I/O. This keeps the busy status for pages
3824 vfs_unbusy_pages(struct buf *bp)
3828 runningbufwakeup(bp);
3830 if (bp->b_flags & B_VMIO) {
3831 struct vnode *vp = bp->b_vp;
3835 vm_object_hold(obj);
3837 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3838 vm_page_t m = bp->b_xio.xio_pages[i];
3841 * When restoring bogus changes the original pages
3842 * should still be wired, so we are in no danger of
3843 * losing the object association and do not need
3844 * critical section protection particularly.
3846 if (m == bogus_page) {
3847 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_loffset) + i);
3849 panic("vfs_unbusy_pages: page missing");
3851 bp->b_xio.xio_pages[i] = m;
3853 vm_page_busy_wait(m, FALSE, "bpdpgw");
3854 vm_page_io_finish(m);
3856 vm_object_pip_wakeup(obj);
3858 if (bp->b_flags & B_HASBOGUS) {
3859 pmap_qenter_noinval(trunc_page((vm_offset_t)bp->b_data),
3860 bp->b_xio.xio_pages,
3861 bp->b_xio.xio_npages);
3862 bp->b_flags &= ~B_HASBOGUS;
3865 vm_object_drop(obj);
3872 * This routine is called before a device strategy routine.
3873 * It is used to tell the VM system that paging I/O is in
3874 * progress, and treat the pages associated with the buffer
3875 * almost as being PBUSY_LOCKED. Also the object 'paging_in_progress'
3876 * flag is handled to make sure that the object doesn't become
3879 * Since I/O has not been initiated yet, certain buffer flags
3880 * such as B_ERROR or B_INVAL may be in an inconsistant state
3881 * and should be ignored.
3884 vfs_busy_pages(struct vnode *vp, struct buf *bp)
3887 struct lwp *lp = curthread->td_lwp;
3890 * The buffer's I/O command must already be set. If reading,
3891 * B_CACHE must be 0 (double check against callers only doing
3892 * I/O when B_CACHE is 0).
3894 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3895 KKASSERT(bp->b_cmd == BUF_CMD_WRITE || (bp->b_flags & B_CACHE) == 0);
3897 if (bp->b_flags & B_VMIO) {
3901 KASSERT(bp->b_loffset != NOOFFSET,
3902 ("vfs_busy_pages: no buffer offset"));
3905 * Busy all the pages. We have to busy them all at once
3906 * to avoid deadlocks.
3909 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3910 vm_page_t m = bp->b_xio.xio_pages[i];
3912 if (vm_page_busy_try(m, FALSE)) {
3913 vm_page_sleep_busy(m, FALSE, "vbpage");
3915 vm_page_wakeup(bp->b_xio.xio_pages[i]);
3921 * Setup for I/O, soft-busy the page right now because
3922 * the next loop may block.
3924 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3925 vm_page_t m = bp->b_xio.xio_pages[i];
3927 if ((bp->b_flags & B_CLUSTER) == 0) {
3928 vm_object_pip_add(obj, 1);
3929 vm_page_io_start(m);
3934 * Adjust protections for I/O and do bogus-page mapping.
3935 * Assume that vm_page_protect() can block (it can block
3936 * if VM_PROT_NONE, don't take any chances regardless).
3938 * In particular note that for writes we must incorporate
3939 * page dirtyness from the VM system into the buffer's
3942 * For reads we theoretically must incorporate page dirtyness
3943 * from the VM system to determine if the page needs bogus
3944 * replacement, but we shortcut the test by simply checking
3945 * that all m->valid bits are set, indicating that the page
3946 * is fully valid and does not need to be re-read. For any
3947 * VM system dirtyness the page will also be fully valid
3948 * since it was mapped at one point.
3951 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3952 vm_page_t m = bp->b_xio.xio_pages[i];
3954 if (bp->b_cmd == BUF_CMD_WRITE) {
3956 * When readying a vnode-backed buffer for
3957 * a write we must zero-fill any invalid
3958 * portions of the backing VM pages, mark
3959 * it valid and clear related dirty bits.
3961 * vfs_clean_one_page() incorporates any
3962 * VM dirtyness and updates the b_dirtyoff
3963 * range (after we've made the page RO).
3965 * It is also expected that the pmap modified
3966 * bit has already been cleared by the
3967 * vm_page_protect(). We may not be able
3968 * to clear all dirty bits for a page if it
3969 * was also memory mapped (NFS).
3971 * Finally be sure to unassign any swap-cache
3972 * backing store as it is now stale.
3974 vm_page_protect(m, VM_PROT_READ);
3975 vfs_clean_one_page(bp, i, m);
3976 swap_pager_unswapped(m);
3977 } else if (m->valid == VM_PAGE_BITS_ALL) {
3979 * When readying a vnode-backed buffer for
3980 * read we must replace any dirty pages with
3981 * a bogus page so dirty data is not destroyed
3982 * when filling gaps.
3984 * To avoid testing whether the page is
3985 * dirty we instead test that the page was
3986 * at some point mapped (m->valid fully
3987 * valid) with the understanding that
3988 * this also covers the dirty case.
3990 bp->b_xio.xio_pages[i] = bogus_page;
3991 bp->b_flags |= B_HASBOGUS;
3993 } else if (m->valid & m->dirty) {
3995 * This case should not occur as partial
3996 * dirtyment can only happen if the buffer
3997 * is B_CACHE, and this code is not entered
3998 * if the buffer is B_CACHE.
4000 kprintf("Warning: vfs_busy_pages - page not "
4001 "fully valid! loff=%jx bpf=%08x "
4002 "idx=%d val=%02x dir=%02x\n",
4003 (uintmax_t)bp->b_loffset, bp->b_flags,
4004 i, m->valid, m->dirty);
4005 vm_page_protect(m, VM_PROT_NONE);
4008 * The page is not valid and can be made
4011 vm_page_protect(m, VM_PROT_NONE);
4016 pmap_qenter_noinval(trunc_page((vm_offset_t)bp->b_data),
4017 bp->b_xio.xio_pages,
4018 bp->b_xio.xio_npages);
4024 * This is the easiest place to put the process accounting for the I/O
4028 if (bp->b_cmd == BUF_CMD_READ)
4029 lp->lwp_ru.ru_inblock++;
4031 lp->lwp_ru.ru_oublock++;
4036 * Tell the VM system that the pages associated with this buffer
4037 * are clean. This is used for delayed writes where the data is
4038 * going to go to disk eventually without additional VM intevention.
4040 * NOTE: While we only really need to clean through to b_bcount, we
4041 * just go ahead and clean through to b_bufsize.
4044 vfs_clean_pages(struct buf *bp)
4049 if ((bp->b_flags & B_VMIO) == 0)
4052 KASSERT(bp->b_loffset != NOOFFSET,
4053 ("vfs_clean_pages: no buffer offset"));
4055 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4056 m = bp->b_xio.xio_pages[i];
4057 vfs_clean_one_page(bp, i, m);
4062 * vfs_clean_one_page:
4064 * Set the valid bits and clear the dirty bits in a page within a
4065 * buffer. The range is restricted to the buffer's size and the
4066 * buffer's logical offset might index into the first page.
4068 * The caller has busied or soft-busied the page and it is not mapped,
4069 * test and incorporate the dirty bits into b_dirtyoff/end before
4070 * clearing them. Note that we need to clear the pmap modified bits
4071 * after determining the the page was dirty, vm_page_set_validclean()
4072 * does not do it for us.
4074 * This routine is typically called after a read completes (dirty should
4075 * be zero in that case as we are not called on bogus-replace pages),
4076 * or before a write is initiated.
4079 vfs_clean_one_page(struct buf *bp, int pageno, vm_page_t m)
4087 * Calculate offset range within the page but relative to buffer's
4088 * loffset. loffset might be offset into the first page.
4090 xoff = (int)bp->b_loffset & PAGE_MASK; /* loffset offset into pg 0 */
4091 bcount = bp->b_bcount + xoff; /* offset adjusted */
4097 soff = (pageno << PAGE_SHIFT);
4098 eoff = soff + PAGE_SIZE;
4106 * Test dirty bits and adjust b_dirtyoff/end.
4108 * If dirty pages are incorporated into the bp any prior
4109 * B_NEEDCOMMIT state (NFS) must be cleared because the
4110 * caller has not taken into account the new dirty data.
4112 * If the page was memory mapped the dirty bits might go beyond the
4113 * end of the buffer, but we can't really make the assumption that
4114 * a file EOF straddles the buffer (even though this is the case for
4115 * NFS if B_NEEDCOMMIT is also set). So for the purposes of clearing
4116 * B_NEEDCOMMIT we only test the dirty bits covered by the buffer.
4117 * This also saves some console spam.
4119 * When clearing B_NEEDCOMMIT we must also clear B_CLUSTEROK,
4120 * NFS can handle huge commits but not huge writes.
4122 vm_page_test_dirty(m);
4124 if ((bp->b_flags & B_NEEDCOMMIT) &&
4125 (m->dirty & vm_page_bits(soff & PAGE_MASK, eoff - soff))) {
4127 kprintf("Warning: vfs_clean_one_page: bp %p "
4128 "loff=%jx,%d flgs=%08x clr B_NEEDCOMMIT"
4129 " cmd %d vd %02x/%02x x/s/e %d %d %d "
4131 bp, (uintmax_t)bp->b_loffset, bp->b_bcount,
4132 bp->b_flags, bp->b_cmd,
4133 m->valid, m->dirty, xoff, soff, eoff,
4134 bp->b_dirtyoff, bp->b_dirtyend);
4135 bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
4137 print_backtrace(-1);
4140 * Only clear the pmap modified bits if ALL the dirty bits
4141 * are set, otherwise the system might mis-clear portions
4144 if (m->dirty == VM_PAGE_BITS_ALL &&
4145 (bp->b_flags & B_NEEDCOMMIT) == 0) {
4146 pmap_clear_modify(m);
4148 if (bp->b_dirtyoff > soff - xoff)
4149 bp->b_dirtyoff = soff - xoff;
4150 if (bp->b_dirtyend < eoff - xoff)
4151 bp->b_dirtyend = eoff - xoff;
4155 * Set related valid bits, clear related dirty bits.
4156 * Does not mess with the pmap modified bit.
4158 * WARNING! We cannot just clear all of m->dirty here as the
4159 * buffer cache buffers may use a DEV_BSIZE'd aligned
4160 * block size, or have an odd size (e.g. NFS at file EOF).
4161 * The putpages code can clear m->dirty to 0.
4163 * If a VOP_WRITE generates a buffer cache buffer which
4164 * covers the same space as mapped writable pages the
4165 * buffer flush might not be able to clear all the dirty
4166 * bits and still require a putpages from the VM system
4169 * WARNING! vm_page_set_validclean() currently assumes vm_token
4170 * is held. The page might not be busied (bdwrite() case).
4171 * XXX remove this comment once we've validated that this
4172 * is no longer an issue.
4174 vm_page_set_validclean(m, soff & PAGE_MASK, eoff - soff);
4179 * Similar to vfs_clean_one_page() but sets the bits to valid and dirty.
4180 * The page data is assumed to be valid (there is no zeroing here).
4183 vfs_dirty_one_page(struct buf *bp, int pageno, vm_page_t m)
4191 * Calculate offset range within the page but relative to buffer's
4192 * loffset. loffset might be offset into the first page.
4194 xoff = (int)bp->b_loffset & PAGE_MASK; /* loffset offset into pg 0 */
4195 bcount = bp->b_bcount + xoff; /* offset adjusted */
4201 soff = (pageno << PAGE_SHIFT);
4202 eoff = soff + PAGE_SIZE;
4208 vm_page_set_validdirty(m, soff & PAGE_MASK, eoff - soff);
4215 * Clear a buffer. This routine essentially fakes an I/O, so we need
4216 * to clear B_ERROR and B_INVAL.
4218 * Note that while we only theoretically need to clear through b_bcount,
4219 * we go ahead and clear through b_bufsize.
4222 vfs_bio_clrbuf(struct buf *bp)
4226 KKASSERT(bp->b_flags & B_VMIO);
4228 bp->b_flags &= ~(B_INVAL | B_EINTR | B_ERROR);
4231 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4232 (bp->b_loffset & PAGE_MASK) == 0) {
4233 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4234 if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
4238 if ((bp->b_xio.xio_pages[0]->valid & mask) == 0) {
4239 bzero(bp->b_data, bp->b_bufsize);
4240 bp->b_xio.xio_pages[0]->valid |= mask;
4246 for(i = 0; i < bp->b_xio.xio_npages; i++, sa=ea) {
4247 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
4248 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
4249 ea = (caddr_t)(vm_offset_t)ulmin(
4250 (u_long)(vm_offset_t)ea,
4251 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
4252 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4253 if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
4255 if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
4258 for (; sa < ea; sa += DEV_BSIZE, j++) {
4259 if ((bp->b_xio.xio_pages[i]->valid &
4261 bzero(sa, DEV_BSIZE);
4265 bp->b_xio.xio_pages[i]->valid |= mask;
4271 * Allocate a page for a buffer cache buffer.
4273 * If NULL is returned the caller is expected to retry (typically check if
4274 * the page already exists on retry before trying to allocate one).
4276 * NOTE! Low-memory handling is dealt with in b[q]relse(), not here. This
4277 * function will use the system reserve with the hope that the page
4278 * allocations can be returned to PQ_CACHE/PQ_FREE when the caller
4279 * is done with the buffer.
4281 * NOTE! However, TMPFS is a special case because flushing a dirty buffer
4282 * to TMPFS doesn't clean the page. For TMPFS, only the pagedaemon
4283 * is capable of retiring pages (to swap). For TMPFS we don't dig
4284 * into the system reserve because doing so could stall out pretty
4285 * much every process running on the system.
4289 bio_page_alloc(struct buf *bp, vm_object_t obj, vm_pindex_t pg, int deficit)
4291 int vmflags = VM_ALLOC_NORMAL | VM_ALLOC_NULL_OK;
4294 ASSERT_LWKT_TOKEN_HELD(vm_object_token(obj));
4297 * Try a normal allocation first.
4299 p = vm_page_alloc(obj, pg, vmflags);
4302 if (vm_page_lookup(obj, pg))
4304 vm_pageout_deficit += deficit;
4307 * Try again, digging into the system reserve.
4309 * Trying to recover pages from the buffer cache here can deadlock
4310 * against other threads trying to busy underlying pages so we
4311 * depend on the code in brelse() and bqrelse() to free/cache the
4312 * underlying buffer cache pages when memory is low.
4314 if (curthread->td_flags & TDF_SYSTHREAD)
4315 vmflags |= VM_ALLOC_SYSTEM | VM_ALLOC_INTERRUPT;
4316 else if (bp->b_vp && bp->b_vp->v_tag == VT_TMPFS)
4319 vmflags |= VM_ALLOC_SYSTEM;
4321 /*recoverbufpages();*/
4322 p = vm_page_alloc(obj, pg, vmflags);
4325 if (vm_page_lookup(obj, pg))
4329 * Wait for memory to free up and try again
4331 if (vm_page_count_severe())
4333 vm_wait(hz / 20 + 1);
4335 p = vm_page_alloc(obj, pg, vmflags);
4338 if (vm_page_lookup(obj, pg))
4342 * Ok, now we are really in trouble.
4345 static struct krate biokrate = { .freq = 1 };
4346 krateprintf(&biokrate,
4347 "Warning: bio_page_alloc: memory exhausted "
4348 "during buffer cache page allocation from %s\n",
4349 curthread->td_comm);
4351 if (curthread->td_flags & TDF_SYSTHREAD)
4352 vm_wait(hz / 20 + 1);
4354 vm_wait(hz / 2 + 1);
4359 * The buffer's mapping has changed. Adjust the buffer's memory
4360 * synchronization. The caller is the exclusive holder of the buffer
4361 * and has set or cleared B_KVABIO according to preference.
4363 * WARNING! If the caller is using B_KVABIO mode, this function will
4364 * not map the data to the current cpu. The caller must also
4365 * call bkvasync(bp).
4368 bkvareset(struct buf *bp)
4370 if (bp->b_flags & B_KVABIO) {
4371 CPUMASK_ASSZERO(bp->b_cpumask);
4373 CPUMASK_ORMASK(bp->b_cpumask, smp_active_mask);
4380 * The buffer will be used by the caller on the caller's cpu, synchronize
4381 * its data to the current cpu.
4383 * If B_KVABIO is not set, the buffer is already fully synchronized.
4386 bkvasync(struct buf *bp)
4388 int cpuid = mycpu->gd_cpuid;
4391 if ((bp->b_flags & B_KVABIO) &&
4392 CPUMASK_TESTBIT(bp->b_cpumask, cpuid) == 0) {
4394 while (bdata < bp->b_data + bp->b_bufsize) {
4396 bdata += PAGE_SIZE -
4397 ((intptr_t)bdata & PAGE_MASK);
4399 ATOMIC_CPUMASK_ORBIT(bp->b_cpumask, cpuid);
4404 * The buffer will be used by a subsystem that does not understand
4405 * the KVABIO API. Make sure its data is synchronized to all cpus.
4407 * If B_KVABIO is not set, the buffer is already fully synchronized.
4409 * NOTE! This is the only safe way to clear B_KVABIO on a buffer.
4412 bkvasync_all(struct buf *bp)
4414 if ((bp->b_flags & B_KVABIO) &&
4415 CPUMASK_CMPMASKNEQ(bp->b_cpumask, smp_active_mask)) {
4418 ATOMIC_CPUMASK_ORMASK(bp->b_cpumask, smp_active_mask);
4420 bp->b_flags &= ~B_KVABIO;
4424 * Scan all buffers in the system and issue the callback.
4427 scan_all_buffers(int (*callback)(struct buf *, void *), void *info)
4433 for (n = 0; n < nbuf; ++n) {
4434 if ((error = callback(&buf[n], info)) < 0) {
4444 * nestiobuf_iodone: biodone callback for nested buffers and propagate
4445 * completion to the master buffer.
4448 nestiobuf_iodone(struct bio *bio)
4451 struct buf *mbp, *bp;
4452 struct devstat *stats;
4457 mbio = bio->bio_caller_info1.ptr;
4458 stats = bio->bio_caller_info2.ptr;
4459 mbp = mbio->bio_buf;
4461 KKASSERT(bp->b_bcount <= bp->b_bufsize);
4462 KKASSERT(mbp != bp);
4464 error = bp->b_error;
4465 if (bp->b_error == 0 &&
4466 (bp->b_bcount < bp->b_bufsize || bp->b_resid > 0)) {
4468 * Not all got transfered, raise an error. We have no way to
4469 * propagate these conditions to mbp.
4474 donebytes = bp->b_bufsize;
4478 nestiobuf_done(mbio, donebytes, error, stats);
4482 nestiobuf_done(struct bio *mbio, int donebytes, int error, struct devstat *stats)
4486 mbp = mbio->bio_buf;
4488 KKASSERT((int)(intptr_t)mbio->bio_driver_info > 0);
4491 * If an error occured, propagate it to the master buffer.
4493 * Several biodone()s may wind up running concurrently so
4494 * use an atomic op to adjust b_flags.
4497 mbp->b_error = error;
4498 atomic_set_int(&mbp->b_flags, B_ERROR);
4502 * Decrement the operations in progress counter and terminate the
4503 * I/O if this was the last bit.
4505 if (atomic_fetchadd_int((int *)&mbio->bio_driver_info, -1) == 1) {
4508 devstat_end_transaction_buf(stats, mbp);
4514 * Initialize a nestiobuf for use. Set an initial count of 1 to prevent
4515 * the mbio from being biodone()'d while we are still adding sub-bios to
4519 nestiobuf_init(struct bio *bio)
4521 bio->bio_driver_info = (void *)1;
4525 * The BIOs added to the nestedio have already been started, remove the
4526 * count that placeheld our mbio and biodone() it if the count would
4530 nestiobuf_start(struct bio *mbio)
4532 struct buf *mbp = mbio->bio_buf;
4535 * Decrement the operations in progress counter and terminate the
4536 * I/O if this was the last bit.
4538 if (atomic_fetchadd_int((int *)&mbio->bio_driver_info, -1) == 1) {
4539 if (mbp->b_flags & B_ERROR)
4540 mbp->b_resid = mbp->b_bcount;
4548 * Set an intermediate error prior to calling nestiobuf_start()
4551 nestiobuf_error(struct bio *mbio, int error)
4553 struct buf *mbp = mbio->bio_buf;
4556 mbp->b_error = error;
4557 atomic_set_int(&mbp->b_flags, B_ERROR);
4562 * nestiobuf_add: setup a "nested" buffer.
4564 * => 'mbp' is a "master" buffer which is being divided into sub pieces.
4565 * => 'bp' should be a buffer allocated by getiobuf.
4566 * => 'offset' is a byte offset in the master buffer.
4567 * => 'size' is a size in bytes of this nested buffer.
4570 nestiobuf_add(struct bio *mbio, struct buf *bp, int offset, size_t size, struct devstat *stats)
4572 struct buf *mbp = mbio->bio_buf;
4573 struct vnode *vp = mbp->b_vp;
4575 KKASSERT(mbp->b_bcount >= offset + size);
4577 atomic_add_int((int *)&mbio->bio_driver_info, 1);
4579 /* kernel needs to own the lock for it to be released in biodone */
4582 bp->b_cmd = mbp->b_cmd;
4583 bp->b_bio1.bio_done = nestiobuf_iodone;
4584 bp->b_data = (char *)mbp->b_data + offset;
4585 bp->b_resid = bp->b_bcount = size;
4586 bp->b_bufsize = bp->b_bcount;
4588 bp->b_bio1.bio_track = NULL;
4589 bp->b_bio1.bio_caller_info1.ptr = mbio;
4590 bp->b_bio1.bio_caller_info2.ptr = stats;
4595 DB_SHOW_COMMAND(buffer, db_show_buffer)
4598 struct buf *bp = (struct buf *)addr;
4601 db_printf("usage: show buffer <addr>\n");
4605 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
4606 db_printf("b_cmd = %d\n", bp->b_cmd);
4607 db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
4608 "b_resid = %d\n, b_data = %p, "
4609 "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
4610 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4612 (long long)bp->b_bio2.bio_offset,
4613 (long long)(bp->b_bio2.bio_next ?
4614 bp->b_bio2.bio_next->bio_offset : (off_t)-1));
4615 if (bp->b_xio.xio_npages) {
4617 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
4618 bp->b_xio.xio_npages);
4619 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4621 m = bp->b_xio.xio_pages[i];
4622 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4623 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4624 if ((i + 1) < bp->b_xio.xio_npages)