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 long maxbufmallocspace
, lobufspace
, hibufspace
;
132 static long lorunningspace
;
133 static long hirunningspace
;
134 static long dirtykvaspace
; /* atomic */
135 long dirtybufspace
; /* atomic (global for systat) */
136 static long dirtybufcount
; /* atomic */
137 static long dirtybufspacehw
; /* atomic */
138 static long dirtybufcounthw
; /* atomic */
139 static long runningbufspace
; /* atomic */
140 static long runningbufcount
; /* atomic */
141 long lodirtybufspace
;
142 long hidirtybufspace
;
143 static int getnewbufcalls
;
144 static int needsbuffer
; /* atomic */
145 static int runningbufreq
; /* atomic */
146 static int bd_request
; /* atomic */
147 static int bd_request_hw
; /* atomic */
148 static u_int bd_wake_ary
[BD_WAKE_SIZE
];
149 static u_int bd_wake_index
;
150 static u_int vm_cycle_point
= 40; /* 23-36 will migrate more act->inact */
151 static int debug_commit
;
152 static int debug_bufbio
;
153 static int debug_kvabio
;
154 static long bufcache_bw
= 200 * 1024 * 1024;
156 static struct thread
*bufdaemon_td
;
157 static struct thread
*bufdaemonhw_td
;
158 static u_int lowmempgallocs
;
159 static u_int flushperqueue
= 1024;
162 * Sysctls for operational control of the buffer cache.
164 SYSCTL_UINT(_vfs
, OID_AUTO
, flushperqueue
, CTLFLAG_RW
, &flushperqueue
, 0,
165 "Number of buffers to flush from each per-cpu queue");
166 SYSCTL_LONG(_vfs
, OID_AUTO
, lodirtybufspace
, CTLFLAG_RW
, &lodirtybufspace
, 0,
167 "Number of dirty buffers to flush before bufdaemon becomes inactive");
168 SYSCTL_LONG(_vfs
, OID_AUTO
, hidirtybufspace
, CTLFLAG_RW
, &hidirtybufspace
, 0,
169 "High watermark used to trigger explicit flushing of dirty buffers");
170 SYSCTL_LONG(_vfs
, OID_AUTO
, lorunningspace
, CTLFLAG_RW
, &lorunningspace
, 0,
171 "Minimum amount of buffer space required for active I/O");
172 SYSCTL_LONG(_vfs
, OID_AUTO
, hirunningspace
, CTLFLAG_RW
, &hirunningspace
, 0,
173 "Maximum amount of buffer space to usable for active I/O");
174 SYSCTL_LONG(_vfs
, OID_AUTO
, bufcache_bw
, CTLFLAG_RW
, &bufcache_bw
, 0,
175 "Buffer-cache -> VM page cache transfer bandwidth");
176 SYSCTL_UINT(_vfs
, OID_AUTO
, lowmempgallocs
, CTLFLAG_RW
, &lowmempgallocs
, 0,
177 "Page allocations done during periods of very low free memory");
178 SYSCTL_UINT(_vfs
, OID_AUTO
, vm_cycle_point
, CTLFLAG_RW
, &vm_cycle_point
, 0,
179 "Recycle pages to active or inactive queue transition pt 0-64");
181 * Sysctls determining current state of the buffer cache.
183 SYSCTL_LONG(_vfs
, OID_AUTO
, nbuf
, CTLFLAG_RD
, &nbuf
, 0,
184 "Total number of buffers in buffer cache");
185 SYSCTL_LONG(_vfs
, OID_AUTO
, dirtykvaspace
, CTLFLAG_RD
, &dirtykvaspace
, 0,
186 "KVA reserved by dirty buffers (all)");
187 SYSCTL_LONG(_vfs
, OID_AUTO
, dirtybufspace
, CTLFLAG_RD
, &dirtybufspace
, 0,
188 "Pending bytes of dirty buffers (all)");
189 SYSCTL_LONG(_vfs
, OID_AUTO
, dirtybufspacehw
, CTLFLAG_RD
, &dirtybufspacehw
, 0,
190 "Pending bytes of dirty buffers (heavy weight)");
191 SYSCTL_LONG(_vfs
, OID_AUTO
, dirtybufcount
, CTLFLAG_RD
, &dirtybufcount
, 0,
192 "Pending number of dirty buffers");
193 SYSCTL_LONG(_vfs
, OID_AUTO
, dirtybufcounthw
, CTLFLAG_RD
, &dirtybufcounthw
, 0,
194 "Pending number of dirty buffers (heavy weight)");
195 SYSCTL_LONG(_vfs
, OID_AUTO
, runningbufspace
, CTLFLAG_RD
, &runningbufspace
, 0,
196 "I/O bytes currently in progress due to asynchronous writes");
197 SYSCTL_LONG(_vfs
, OID_AUTO
, runningbufcount
, CTLFLAG_RD
, &runningbufcount
, 0,
198 "I/O buffers currently in progress due to asynchronous writes");
199 SYSCTL_LONG(_vfs
, OID_AUTO
, maxbufspace
, CTLFLAG_RD
, &maxbufspace
, 0,
200 "Hard limit on maximum amount of memory usable for buffer space");
201 SYSCTL_LONG(_vfs
, OID_AUTO
, hibufspace
, CTLFLAG_RD
, &hibufspace
, 0,
202 "Soft limit on maximum amount of memory usable for buffer space");
203 SYSCTL_LONG(_vfs
, OID_AUTO
, lobufspace
, CTLFLAG_RD
, &lobufspace
, 0,
204 "Minimum amount of memory to reserve for system buffer space");
205 SYSCTL_LONG(_vfs
, OID_AUTO
, bufspace
, CTLFLAG_RD
, &bufspace
, 0,
206 "Amount of memory available for buffers");
207 SYSCTL_LONG(_vfs
, OID_AUTO
, maxmallocbufspace
, CTLFLAG_RD
, &maxbufmallocspace
,
208 0, "Maximum amount of memory reserved for buffers using malloc");
209 SYSCTL_INT(_vfs
, OID_AUTO
, getnewbufcalls
, CTLFLAG_RD
, &getnewbufcalls
, 0,
210 "New buffer header acquisition requests");
211 SYSCTL_INT(_vfs
, OID_AUTO
, debug_commit
, CTLFLAG_RW
, &debug_commit
, 0, "");
212 SYSCTL_INT(_vfs
, OID_AUTO
, debug_bufbio
, CTLFLAG_RW
, &debug_bufbio
, 0, "");
213 SYSCTL_INT(_vfs
, OID_AUTO
, debug_kvabio
, CTLFLAG_RW
, &debug_kvabio
, 0, "");
214 SYSCTL_INT(_debug_sizeof
, OID_AUTO
, buf
, CTLFLAG_RD
, 0, sizeof(struct buf
),
215 "sizeof(struct buf)");
217 char *buf_wmesg
= BUF_WMESG
;
219 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
220 #define VFS_BIO_NEED_UNUSED02 0x02
221 #define VFS_BIO_NEED_UNUSED04 0x04
222 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
225 * Called when buffer space is potentially available for recovery.
226 * getnewbuf() will block on this flag when it is unable to free
227 * sufficient buffer space. Buffer space becomes recoverable when
228 * bp's get placed back in the queues.
234 * If someone is waiting for BUF space, wake them up. Even
235 * though we haven't freed the kva space yet, the waiting
236 * process will be able to now.
239 int flags
= needsbuffer
;
241 if ((flags
& VFS_BIO_NEED_BUFSPACE
) == 0)
243 if (atomic_cmpset_int(&needsbuffer
, flags
,
244 flags
& ~VFS_BIO_NEED_BUFSPACE
)) {
245 wakeup(&needsbuffer
);
255 * Accounting for I/O in progress.
259 runningbufwakeup(struct buf
*bp
)
264 if ((totalspace
= bp
->b_runningbufspace
) != 0) {
265 atomic_add_long(&runningbufspace
, -totalspace
);
266 atomic_add_long(&runningbufcount
, -1);
267 bp
->b_runningbufspace
= 0;
270 * see waitrunningbufspace() for limit test.
273 flags
= runningbufreq
;
277 if (atomic_cmpset_int(&runningbufreq
, flags
, 0)) {
278 wakeup(&runningbufreq
);
283 bd_signal(totalspace
);
290 * Called when a buffer has been added to one of the free queues to
291 * account for the buffer and to wakeup anyone waiting for free buffers.
292 * This typically occurs when large amounts of metadata are being handled
293 * by the buffer cache ( else buffer space runs out first, usually ).
304 if (atomic_cmpset_int(&needsbuffer
, flags
,
305 (flags
& ~VFS_BIO_NEED_ANY
))) {
306 wakeup(&needsbuffer
);
314 * waitrunningbufspace()
316 * If runningbufspace exceeds 4/6 hirunningspace we block until
317 * runningbufspace drops to 3/6 hirunningspace. We also block if another
318 * thread blocked here in order to be fair, even if runningbufspace
319 * is now lower than the limit.
321 * The caller may be using this function to block in a tight loop, we
322 * must block while runningbufspace is greater than at least
323 * hirunningspace * 3 / 6.
326 waitrunningbufspace(void)
328 long limit
= hirunningspace
* 4 / 6;
331 while (runningbufspace
> limit
|| runningbufreq
) {
332 tsleep_interlock(&runningbufreq
, 0);
333 flags
= atomic_fetchadd_int(&runningbufreq
, 1);
334 if (runningbufspace
> limit
|| flags
)
335 tsleep(&runningbufreq
, PINTERLOCKED
, "wdrn1", hz
);
340 * buf_dirty_count_severe:
342 * Return true if we have too many dirty buffers.
345 buf_dirty_count_severe(void)
347 return (runningbufspace
+ dirtykvaspace
>= hidirtybufspace
||
348 dirtybufcount
>= nbuf
/ 2);
352 * Return true if the amount of running I/O is severe and BIOQ should
356 buf_runningbufspace_severe(void)
358 return (runningbufspace
>= hirunningspace
* 4 / 6);
362 * vfs_buf_test_cache:
364 * Called when a buffer is extended. This function clears the B_CACHE
365 * bit if the newly extended portion of the buffer does not contain
368 * NOTE! Dirty VM pages are not processed into dirty (B_DELWRI) buffer
369 * cache buffers. The VM pages remain dirty, as someone had mmap()'d
370 * them while a clean buffer was present.
374 vfs_buf_test_cache(struct buf
*bp
,
375 vm_ooffset_t foff
, vm_offset_t off
, vm_offset_t size
,
378 if (bp
->b_flags
& B_CACHE
) {
379 int base
= (foff
+ off
) & PAGE_MASK
;
380 if (vm_page_is_valid(m
, base
, size
) == 0)
381 bp
->b_flags
&= ~B_CACHE
;
388 * Spank the buf_daemon[_hw] if the total dirty buffer space exceeds the
395 if (dirtykvaspace
< lodirtybufspace
&& dirtybufcount
< nbuf
/ 2)
398 if (bd_request
== 0 &&
399 (dirtykvaspace
> lodirtybufspace
/ 2 ||
400 dirtybufcount
- dirtybufcounthw
>= nbuf
/ 2)) {
401 if (atomic_fetchadd_int(&bd_request
, 1) == 0)
404 if (bd_request_hw
== 0 &&
405 (dirtykvaspace
> lodirtybufspace
/ 2 ||
406 dirtybufcounthw
>= nbuf
/ 2)) {
407 if (atomic_fetchadd_int(&bd_request_hw
, 1) == 0)
408 wakeup(&bd_request_hw
);
415 * Get the buf_daemon heated up when the number of running and dirty
416 * buffers exceeds the mid-point.
418 * Return the total number of dirty bytes past the second mid point
419 * as a measure of how much excess dirty data there is in the system.
428 mid1
= lodirtybufspace
+ (hidirtybufspace
- lodirtybufspace
) / 2;
430 totalspace
= runningbufspace
+ dirtykvaspace
;
431 if (totalspace
>= mid1
|| dirtybufcount
>= nbuf
/ 2) {
433 mid2
= mid1
+ (hidirtybufspace
- mid1
) / 2;
434 if (totalspace
>= mid2
)
435 return(totalspace
- mid2
);
443 * Wait for the buffer cache to flush (totalspace) bytes worth of
444 * buffers, then return.
446 * Regardless this function blocks while the number of dirty buffers
447 * exceeds hidirtybufspace.
450 bd_wait(long totalspace
)
457 if (curthread
== bufdaemonhw_td
|| curthread
== bufdaemon_td
)
460 while (totalspace
> 0) {
464 * Order is important. Suppliers adjust bd_wake_index after
465 * updating runningbufspace/dirtykvaspace. We want to fetch
466 * bd_wake_index before accessing. Any error should thus
469 i
= atomic_fetchadd_int(&bd_wake_index
, 0);
470 if (totalspace
> runningbufspace
+ dirtykvaspace
)
471 totalspace
= runningbufspace
+ dirtykvaspace
;
472 count
= totalspace
/ MAXBSIZE
;
473 if (count
>= BD_WAKE_SIZE
/ 2)
474 count
= BD_WAKE_SIZE
/ 2;
476 mi
= i
& BD_WAKE_MASK
;
479 * This is not a strict interlock, so we play a bit loose
480 * with locking access to dirtybufspace*. We have to re-check
481 * bd_wake_index to ensure that it hasn't passed us.
483 tsleep_interlock(&bd_wake_ary
[mi
], 0);
484 atomic_add_int(&bd_wake_ary
[mi
], 1);
485 j
= atomic_fetchadd_int(&bd_wake_index
, 0);
486 if ((int)(i
- j
) >= 0)
487 tsleep(&bd_wake_ary
[mi
], PINTERLOCKED
, "flstik", hz
);
489 totalspace
= runningbufspace
+ dirtykvaspace
- hidirtybufspace
;
496 * This function is called whenever runningbufspace or dirtykvaspace
497 * is reduced. Track threads waiting for run+dirty buffer I/O
501 bd_signal(long totalspace
)
505 if (totalspace
> 0) {
506 if (totalspace
> MAXBSIZE
* BD_WAKE_SIZE
)
507 totalspace
= MAXBSIZE
* BD_WAKE_SIZE
;
508 while (totalspace
> 0) {
509 i
= atomic_fetchadd_int(&bd_wake_index
, 1);
511 if (atomic_readandclear_int(&bd_wake_ary
[i
]))
512 wakeup(&bd_wake_ary
[i
]);
513 totalspace
-= MAXBSIZE
;
519 * BIO tracking support routines.
521 * Release a ref on a bio_track. Wakeup requests are atomically released
522 * along with the last reference so bk_active will never wind up set to
527 bio_track_rel(struct bio_track
*track
)
535 active
= track
->bk_active
;
536 if (active
== 1 && atomic_cmpset_int(&track
->bk_active
, 1, 0))
540 * Full-on. Note that the wait flag is only atomically released on
541 * the 1->0 count transition.
543 * We check for a negative count transition using bit 30 since bit 31
544 * has a different meaning.
547 desired
= (active
& 0x7FFFFFFF) - 1;
549 desired
|= active
& 0x80000000;
550 if (atomic_cmpset_int(&track
->bk_active
, active
, desired
)) {
551 if (desired
& 0x40000000)
552 panic("bio_track_rel: bad count: %p", track
);
553 if (active
& 0x80000000)
557 active
= track
->bk_active
;
562 * Wait for the tracking count to reach 0.
564 * Use atomic ops such that the wait flag is only set atomically when
565 * bk_active is non-zero.
568 bio_track_wait(struct bio_track
*track
, int slp_flags
, int slp_timo
)
577 if (track
->bk_active
== 0)
581 * Full-on. Note that the wait flag may only be atomically set if
582 * the active count is non-zero.
584 * NOTE: We cannot optimize active == desired since a wakeup could
585 * clear active prior to our tsleep_interlock().
588 while ((active
= track
->bk_active
) != 0) {
590 desired
= active
| 0x80000000;
591 tsleep_interlock(track
, slp_flags
);
592 if (atomic_cmpset_int(&track
->bk_active
, active
, desired
)) {
593 error
= tsleep(track
, slp_flags
| PINTERLOCKED
,
605 * Load time initialisation of the buffer cache, called from machine
606 * dependant initialization code.
610 bufinit(void *dummy __unused
)
612 struct bufpcpu
*pcpu
;
614 vm_offset_t bogus_offset
;
619 /* next, make a null set of free lists */
620 for (i
= 0; i
< ncpus
; ++i
) {
622 spin_init(&pcpu
->spin
, "bufinit");
623 for (j
= 0; j
< BUFFER_QUEUES
; j
++)
624 TAILQ_INIT(&pcpu
->bufqueues
[j
]);
628 * Finally, initialize each buffer header and stick on empty q.
629 * Each buffer gets its own KVA reservation.
634 for (n
= 0; n
< nbuf
; n
++) {
636 bzero(bp
, sizeof *bp
);
637 bp
->b_flags
= B_INVAL
; /* we're just an empty header */
638 bp
->b_cmd
= BUF_CMD_DONE
;
639 bp
->b_qindex
= BQUEUE_EMPTY
;
641 bp
->b_kvabase
= (void *)(vm_map_min(&buffer_map
) +
643 bp
->b_kvasize
= MAXBSIZE
;
645 xio_init(&bp
->b_xio
);
647 TAILQ_INSERT_TAIL(&pcpu
->bufqueues
[bp
->b_qindex
],
655 * maxbufspace is the absolute maximum amount of buffer space we are
656 * allowed to reserve in KVM and in real terms. The absolute maximum
657 * is nominally used by buf_daemon. hibufspace is the nominal maximum
658 * used by most other processes. The differential is required to
659 * ensure that buf_daemon is able to run when other processes might
660 * be blocked waiting for buffer space.
662 * Calculate hysteresis (lobufspace, hibufspace). Don't make it
663 * too large or we might lockup a cpu for too long a period of
664 * time in our tight loop.
666 maxbufspace
= nbuf
* NBUFCALCSIZE
;
667 hibufspace
= lmax(3 * maxbufspace
/ 4, maxbufspace
- MAXBSIZE
* 10);
668 lobufspace
= hibufspace
* 7 / 8;
669 if (hibufspace
- lobufspace
> 64 * 1024 * 1024)
670 lobufspace
= hibufspace
- 64 * 1024 * 1024;
671 if (lobufspace
> hibufspace
- MAXBSIZE
)
672 lobufspace
= hibufspace
- MAXBSIZE
;
674 lorunningspace
= 512 * 1024;
675 /* hirunningspace -- see below */
678 * Limit the amount of malloc memory since it is wired permanently
679 * into the kernel space. Even though this is accounted for in
680 * the buffer allocation, we don't want the malloced region to grow
681 * uncontrolled. The malloc scheme improves memory utilization
682 * significantly on average (small) directories.
684 maxbufmallocspace
= hibufspace
/ 20;
687 * Reduce the chance of a deadlock occuring by limiting the number
688 * of delayed-write dirty buffers we allow to stack up.
690 * We don't want too much actually queued to the device at once
691 * (XXX this needs to be per-mount!), because the buffers will
692 * wind up locked for a very long period of time while the I/O
695 hidirtybufspace
= hibufspace
/ 2; /* dirty + running */
696 hirunningspace
= hibufspace
/ 16; /* locked & queued to device */
697 if (hirunningspace
< 1024 * 1024)
698 hirunningspace
= 1024 * 1024;
704 lodirtybufspace
= hidirtybufspace
/ 2;
707 * Maximum number of async ops initiated per buf_daemon loop. This is
708 * somewhat of a hack at the moment, we really need to limit ourselves
709 * based on the number of bytes of I/O in-transit that were initiated
713 bogus_offset
= kmem_alloc_pageable(&kernel_map
, PAGE_SIZE
,
715 vm_object_hold(&kernel_object
);
716 bogus_page
= vm_page_alloc(&kernel_object
,
717 (bogus_offset
>> PAGE_SHIFT
),
719 vm_object_drop(&kernel_object
);
720 vmstats
.v_wire_count
++;
724 SYSINIT(do_bufinit
, SI_BOOT2_MACHDEP
, SI_ORDER_FIRST
, bufinit
, NULL
);
727 * Initialize the embedded bio structures, typically used by
728 * deprecated code which tries to allocate its own struct bufs.
731 initbufbio(struct buf
*bp
)
733 bp
->b_bio1
.bio_buf
= bp
;
734 bp
->b_bio1
.bio_prev
= NULL
;
735 bp
->b_bio1
.bio_offset
= NOOFFSET
;
736 bp
->b_bio1
.bio_next
= &bp
->b_bio2
;
737 bp
->b_bio1
.bio_done
= NULL
;
738 bp
->b_bio1
.bio_flags
= 0;
740 bp
->b_bio2
.bio_buf
= bp
;
741 bp
->b_bio2
.bio_prev
= &bp
->b_bio1
;
742 bp
->b_bio2
.bio_offset
= NOOFFSET
;
743 bp
->b_bio2
.bio_next
= NULL
;
744 bp
->b_bio2
.bio_done
= NULL
;
745 bp
->b_bio2
.bio_flags
= 0;
751 * Reinitialize the embedded bio structures as well as any additional
752 * translation cache layers.
755 reinitbufbio(struct buf
*bp
)
759 for (bio
= &bp
->b_bio1
; bio
; bio
= bio
->bio_next
) {
760 bio
->bio_done
= NULL
;
761 bio
->bio_offset
= NOOFFSET
;
766 * Undo the effects of an initbufbio().
769 uninitbufbio(struct buf
*bp
)
776 * Push another BIO layer onto an existing BIO and return it. The new
777 * BIO layer may already exist, holding cached translation data.
780 push_bio(struct bio
*bio
)
784 if ((nbio
= bio
->bio_next
) == NULL
) {
785 int index
= bio
- &bio
->bio_buf
->b_bio_array
[0];
786 if (index
>= NBUF_BIO
- 1) {
787 panic("push_bio: too many layers %d for bp %p",
788 index
, bio
->bio_buf
);
790 nbio
= &bio
->bio_buf
->b_bio_array
[index
+ 1];
791 bio
->bio_next
= nbio
;
792 nbio
->bio_prev
= bio
;
793 nbio
->bio_buf
= bio
->bio_buf
;
794 nbio
->bio_offset
= NOOFFSET
;
795 nbio
->bio_done
= NULL
;
796 nbio
->bio_next
= NULL
;
798 KKASSERT(nbio
->bio_done
== NULL
);
803 * Pop a BIO translation layer, returning the previous layer. The
804 * must have been previously pushed.
807 pop_bio(struct bio
*bio
)
809 return(bio
->bio_prev
);
813 clearbiocache(struct bio
*bio
)
816 bio
->bio_offset
= NOOFFSET
;
822 * Remove the buffer from the appropriate free list.
823 * (caller must be locked)
826 _bremfree(struct buf
*bp
)
828 struct bufpcpu
*pcpu
= &bufpcpu
[bp
->b_qcpu
];
830 if (bp
->b_qindex
!= BQUEUE_NONE
) {
831 KASSERT(BUF_LOCKINUSE(bp
), ("bremfree: bp %p not locked", bp
));
832 TAILQ_REMOVE(&pcpu
->bufqueues
[bp
->b_qindex
], bp
, b_freelist
);
833 bp
->b_qindex
= BQUEUE_NONE
;
835 if (!BUF_LOCKINUSE(bp
))
836 panic("bremfree: removing a buffer not on a queue");
841 * bremfree() - must be called with a locked buffer
844 bremfree(struct buf
*bp
)
846 struct bufpcpu
*pcpu
= &bufpcpu
[bp
->b_qcpu
];
848 spin_lock(&pcpu
->spin
);
850 spin_unlock(&pcpu
->spin
);
854 * bremfree_locked - must be called with pcpu->spin locked
857 bremfree_locked(struct buf
*bp
)
863 * This version of bread issues any required I/O asyncnronously and
864 * makes a callback on completion.
866 * The callback must check whether BIO_DONE is set in the bio and issue
867 * the bpdone(bp, 0) if it isn't. The callback is responsible for clearing
868 * BIO_DONE and disposing of the I/O (bqrelse()ing it).
871 breadcb(struct vnode
*vp
, off_t loffset
, int size
, int bflags
,
872 void (*func
)(struct bio
*), void *arg
)
876 bp
= getblk(vp
, loffset
, size
, 0, 0);
878 /* if not found in cache, do some I/O */
879 if ((bp
->b_flags
& B_CACHE
) == 0) {
880 bp
->b_flags
&= ~(B_ERROR
| B_EINTR
| B_INVAL
| B_NOTMETA
);
881 bp
->b_flags
|= bflags
;
882 bp
->b_cmd
= BUF_CMD_READ
;
883 bp
->b_bio1
.bio_done
= func
;
884 bp
->b_bio1
.bio_caller_info1
.ptr
= arg
;
885 vfs_busy_pages(vp
, bp
);
887 vn_strategy(vp
, &bp
->b_bio1
);
890 * Since we are issuing the callback synchronously it cannot
891 * race the BIO_DONE, so no need for atomic ops here.
893 /*bp->b_bio1.bio_done = func;*/
894 bp
->b_bio1
.bio_caller_info1
.ptr
= arg
;
895 bp
->b_bio1
.bio_flags
|= BIO_DONE
;
903 * breadnx() - Terminal function for bread() and breadn().
905 * This function will start asynchronous I/O on read-ahead blocks as well
906 * as satisfy the primary request.
908 * We must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE is
909 * set, the buffer is valid and we do not have to do anything.
912 breadnx(struct vnode
*vp
, off_t loffset
, int size
, int bflags
,
913 off_t
*raoffset
, int *rabsize
,
914 int cnt
, struct buf
**bpp
)
916 struct buf
*bp
, *rabp
;
918 int rv
= 0, readwait
= 0;
919 int blkflags
= (bflags
& B_KVABIO
) ? GETBLK_KVABIO
: 0;
924 *bpp
= bp
= getblk(vp
, loffset
, size
, blkflags
, 0);
926 /* if not found in cache, do some I/O */
927 if ((bp
->b_flags
& B_CACHE
) == 0) {
928 bp
->b_flags
&= ~(B_ERROR
| B_EINTR
| B_INVAL
| B_NOTMETA
);
929 bp
->b_flags
|= bflags
;
930 bp
->b_cmd
= BUF_CMD_READ
;
931 bp
->b_bio1
.bio_done
= biodone_sync
;
932 bp
->b_bio1
.bio_flags
|= BIO_SYNC
;
933 vfs_busy_pages(vp
, bp
);
934 vn_strategy(vp
, &bp
->b_bio1
);
938 for (i
= 0; i
< cnt
; i
++, raoffset
++, rabsize
++) {
939 if (inmem(vp
, *raoffset
))
941 rabp
= getblk(vp
, *raoffset
, *rabsize
, GETBLK_KVABIO
, 0);
943 if ((rabp
->b_flags
& B_CACHE
) == 0) {
944 rabp
->b_flags
&= ~(B_ERROR
| B_EINTR
|
945 B_INVAL
| B_NOTMETA
);
946 rabp
->b_flags
|= (bflags
& ~B_KVABIO
);
947 rabp
->b_cmd
= BUF_CMD_READ
;
948 vfs_busy_pages(vp
, rabp
);
950 vn_strategy(vp
, &rabp
->b_bio1
);
956 rv
= biowait(&bp
->b_bio1
, "biord");
963 * Synchronous write, waits for completion.
965 * Write, release buffer on completion. (Done by iodone
966 * if async). Do not bother writing anything if the buffer
969 * Note that we set B_CACHE here, indicating that buffer is
970 * fully valid and thus cacheable. This is true even of NFS
971 * now so we set it generally. This could be set either here
972 * or in biodone() since the I/O is synchronous. We put it
976 bwrite(struct buf
*bp
)
980 if (bp
->b_flags
& B_INVAL
) {
984 if (BUF_LOCKINUSE(bp
) == 0)
985 panic("bwrite: buffer is not busy???");
988 * NOTE: We no longer mark the buffer clear prior to the vn_strategy()
989 * call because it will remove the buffer from the vnode's
990 * dirty buffer list prematurely and possibly cause filesystem
991 * checks to race buffer flushes. This is now handled in
994 * bundirty(bp); REMOVED
997 bp
->b_flags
&= ~(B_ERROR
| B_EINTR
);
998 bp
->b_flags
|= B_CACHE
;
999 bp
->b_cmd
= BUF_CMD_WRITE
;
1000 bp
->b_bio1
.bio_done
= biodone_sync
;
1001 bp
->b_bio1
.bio_flags
|= BIO_SYNC
;
1002 vfs_busy_pages(bp
->b_vp
, bp
);
1005 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
1006 * valid for vnode-backed buffers.
1008 bsetrunningbufspace(bp
, bp
->b_bufsize
);
1009 vn_strategy(bp
->b_vp
, &bp
->b_bio1
);
1010 error
= biowait(&bp
->b_bio1
, "biows");
1019 * Asynchronous write. Start output on a buffer, but do not wait for
1020 * it to complete. The buffer is released when the output completes.
1022 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1023 * B_INVAL buffers. Not us.
1026 bawrite(struct buf
*bp
)
1028 if (bp
->b_flags
& B_INVAL
) {
1032 if (BUF_LOCKINUSE(bp
) == 0)
1033 panic("bawrite: buffer is not busy???");
1036 * NOTE: We no longer mark the buffer clear prior to the vn_strategy()
1037 * call because it will remove the buffer from the vnode's
1038 * dirty buffer list prematurely and possibly cause filesystem
1039 * checks to race buffer flushes. This is now handled in
1042 * bundirty(bp); REMOVED
1044 bp
->b_flags
&= ~(B_ERROR
| B_EINTR
);
1045 bp
->b_flags
|= B_CACHE
;
1046 bp
->b_cmd
= BUF_CMD_WRITE
;
1047 KKASSERT(bp
->b_bio1
.bio_done
== NULL
);
1048 vfs_busy_pages(bp
->b_vp
, bp
);
1051 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
1052 * valid for vnode-backed buffers.
1054 bsetrunningbufspace(bp
, bp
->b_bufsize
);
1056 vn_strategy(bp
->b_vp
, &bp
->b_bio1
);
1062 * Delayed write. (Buffer is marked dirty). Do not bother writing
1063 * anything if the buffer is marked invalid.
1065 * Note that since the buffer must be completely valid, we can safely
1066 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
1067 * biodone() in order to prevent getblk from writing the buffer
1068 * out synchronously.
1071 bdwrite(struct buf
*bp
)
1073 if (BUF_LOCKINUSE(bp
) == 0)
1074 panic("bdwrite: buffer is not busy");
1076 if (bp
->b_flags
& B_INVAL
) {
1082 dsched_buf_enter(bp
); /* might stack */
1085 * Set B_CACHE, indicating that the buffer is fully valid. This is
1086 * true even of NFS now.
1088 bp
->b_flags
|= B_CACHE
;
1091 * This bmap keeps the system from needing to do the bmap later,
1092 * perhaps when the system is attempting to do a sync. Since it
1093 * is likely that the indirect block -- or whatever other datastructure
1094 * that the filesystem needs is still in memory now, it is a good
1095 * thing to do this. Note also, that if the pageout daemon is
1096 * requesting a sync -- there might not be enough memory to do
1097 * the bmap then... So, this is important to do.
1099 if (bp
->b_bio2
.bio_offset
== NOOFFSET
) {
1100 VOP_BMAP(bp
->b_vp
, bp
->b_loffset
, &bp
->b_bio2
.bio_offset
,
1101 NULL
, NULL
, BUF_CMD_WRITE
);
1105 * Because the underlying pages may still be mapped and
1106 * writable trying to set the dirty buffer (b_dirtyoff/end)
1107 * range here will be inaccurate.
1109 * However, we must still clean the pages to satisfy the
1110 * vnode_pager and pageout daemon, so they think the pages
1111 * have been "cleaned". What has really occured is that
1112 * they've been earmarked for later writing by the buffer
1115 * So we get the b_dirtyoff/end update but will not actually
1116 * depend on it (NFS that is) until the pages are busied for
1119 vfs_clean_pages(bp
);
1123 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1124 * due to the softdep code.
1129 * Fake write - return pages to VM system as dirty, leave the buffer clean.
1130 * This is used by tmpfs.
1132 * It is important for any VFS using this routine to NOT use it for
1133 * IO_SYNC or IO_ASYNC operations which occur when the system really
1134 * wants to flush VM pages to backing store.
1137 buwrite(struct buf
*bp
)
1143 * Only works for VMIO buffers. If the buffer is already
1144 * marked for delayed-write we can't avoid the bdwrite().
1146 if ((bp
->b_flags
& B_VMIO
) == 0 || (bp
->b_flags
& B_DELWRI
)) {
1152 * Mark as needing a commit.
1154 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
1155 m
= bp
->b_xio
.xio_pages
[i
];
1156 vm_page_need_commit(m
);
1164 * Turn buffer into delayed write request by marking it B_DELWRI.
1165 * B_RELBUF and B_NOCACHE must be cleared.
1167 * We reassign the buffer to itself to properly update it in the
1168 * dirty/clean lists.
1170 * Must be called from a critical section.
1171 * The buffer must be on BQUEUE_NONE.
1174 bdirty(struct buf
*bp
)
1176 KASSERT(bp
->b_qindex
== BQUEUE_NONE
,
1177 ("bdirty: buffer %p still on queue %d", bp
, bp
->b_qindex
));
1178 if (bp
->b_flags
& B_NOCACHE
) {
1179 kprintf("bdirty: clearing B_NOCACHE on buf %p\n", bp
);
1180 bp
->b_flags
&= ~B_NOCACHE
;
1182 if (bp
->b_flags
& B_INVAL
) {
1183 kprintf("bdirty: warning, dirtying invalid buffer %p\n", bp
);
1185 bp
->b_flags
&= ~B_RELBUF
;
1187 if ((bp
->b_flags
& B_DELWRI
) == 0) {
1188 lwkt_gettoken(&bp
->b_vp
->v_token
);
1189 bp
->b_flags
|= B_DELWRI
;
1191 lwkt_reltoken(&bp
->b_vp
->v_token
);
1193 atomic_add_long(&dirtybufcount
, 1);
1194 atomic_add_long(&dirtykvaspace
, bp
->b_kvasize
);
1195 atomic_add_long(&dirtybufspace
, bp
->b_bufsize
);
1196 if (bp
->b_flags
& B_HEAVY
) {
1197 atomic_add_long(&dirtybufcounthw
, 1);
1198 atomic_add_long(&dirtybufspacehw
, bp
->b_bufsize
);
1205 * Set B_HEAVY, indicating that this is a heavy-weight buffer that
1206 * needs to be flushed with a different buf_daemon thread to avoid
1207 * deadlocks. B_HEAVY also imposes restrictions in getnewbuf().
1210 bheavy(struct buf
*bp
)
1212 if ((bp
->b_flags
& B_HEAVY
) == 0) {
1213 bp
->b_flags
|= B_HEAVY
;
1214 if (bp
->b_flags
& B_DELWRI
) {
1215 atomic_add_long(&dirtybufcounthw
, 1);
1216 atomic_add_long(&dirtybufspacehw
, bp
->b_bufsize
);
1224 * Clear B_DELWRI for buffer.
1226 * Must be called from a critical section.
1228 * The buffer is typically on BQUEUE_NONE but there is one case in
1229 * brelse() that calls this function after placing the buffer on
1230 * a different queue.
1233 bundirty(struct buf
*bp
)
1235 if (bp
->b_flags
& B_DELWRI
) {
1236 lwkt_gettoken(&bp
->b_vp
->v_token
);
1237 bp
->b_flags
&= ~B_DELWRI
;
1239 lwkt_reltoken(&bp
->b_vp
->v_token
);
1241 atomic_add_long(&dirtybufcount
, -1);
1242 atomic_add_long(&dirtykvaspace
, -bp
->b_kvasize
);
1243 atomic_add_long(&dirtybufspace
, -bp
->b_bufsize
);
1244 if (bp
->b_flags
& B_HEAVY
) {
1245 atomic_add_long(&dirtybufcounthw
, -1);
1246 atomic_add_long(&dirtybufspacehw
, -bp
->b_bufsize
);
1248 bd_signal(bp
->b_bufsize
);
1251 * Since it is now being written, we can clear its deferred write flag.
1253 bp
->b_flags
&= ~B_DEFERRED
;
1257 * Set the b_runningbufspace field, used to track how much I/O is
1258 * in progress at any given moment.
1261 bsetrunningbufspace(struct buf
*bp
, int bytes
)
1263 bp
->b_runningbufspace
= bytes
;
1265 atomic_add_long(&runningbufspace
, bytes
);
1266 atomic_add_long(&runningbufcount
, 1);
1273 * Release a busy buffer and, if requested, free its resources. The
1274 * buffer will be stashed in the appropriate bufqueue[] allowing it
1275 * to be accessed later as a cache entity or reused for other purposes.
1278 brelse(struct buf
*bp
)
1280 struct bufpcpu
*pcpu
;
1282 int saved_flags
= bp
->b_flags
;
1285 KASSERT(!(bp
->b_flags
& (B_CLUSTER
|B_PAGING
)),
1286 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp
));
1289 * If B_NOCACHE is set we are being asked to destroy the buffer and
1290 * its backing store. Clear B_DELWRI.
1292 * B_NOCACHE is set in two cases: (1) when the caller really wants
1293 * to destroy the buffer and backing store and (2) when the caller
1294 * wants to destroy the buffer and backing store after a write
1297 if ((bp
->b_flags
& (B_NOCACHE
|B_DELWRI
)) == (B_NOCACHE
|B_DELWRI
)) {
1301 if ((bp
->b_flags
& (B_INVAL
| B_DELWRI
)) == B_DELWRI
) {
1303 * A re-dirtied buffer is only subject to destruction
1304 * by B_INVAL. B_ERROR and B_NOCACHE are ignored.
1306 /* leave buffer intact */
1307 } else if ((bp
->b_flags
& (B_NOCACHE
| B_INVAL
| B_ERROR
)) ||
1308 (bp
->b_bufsize
<= 0)) {
1310 * Either a failed read or we were asked to free or not
1311 * cache the buffer. This path is reached with B_DELWRI
1312 * set only if B_INVAL is already set. B_NOCACHE governs
1313 * backing store destruction.
1315 * NOTE: HAMMER will set B_LOCKED in buf_deallocate if the
1316 * buffer cannot be immediately freed.
1318 bp
->b_flags
|= B_INVAL
;
1319 if (LIST_FIRST(&bp
->b_dep
) != NULL
)
1321 if (bp
->b_flags
& B_DELWRI
) {
1322 atomic_add_long(&dirtybufcount
, -1);
1323 atomic_add_long(&dirtykvaspace
, -bp
->b_kvasize
);
1324 atomic_add_long(&dirtybufspace
, -bp
->b_bufsize
);
1325 if (bp
->b_flags
& B_HEAVY
) {
1326 atomic_add_long(&dirtybufcounthw
, -1);
1327 atomic_add_long(&dirtybufspacehw
,
1330 bd_signal(bp
->b_bufsize
);
1332 bp
->b_flags
&= ~(B_DELWRI
| B_CACHE
);
1336 * We must clear B_RELBUF if B_DELWRI or B_LOCKED is set,
1337 * or if b_refs is non-zero.
1339 * If vfs_vmio_release() is called with either bit set, the
1340 * underlying pages may wind up getting freed causing a previous
1341 * write (bdwrite()) to get 'lost' because pages associated with
1342 * a B_DELWRI bp are marked clean. Pages associated with a
1343 * B_LOCKED buffer may be mapped by the filesystem.
1345 * If we want to release the buffer ourselves (rather then the
1346 * originator asking us to release it), give the originator a
1347 * chance to countermand the release by setting B_LOCKED.
1349 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1350 * if B_DELWRI is set.
1352 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1353 * on pages to return pages to the VM page queues.
1355 if ((bp
->b_flags
& (B_DELWRI
| B_LOCKED
)) || bp
->b_refs
) {
1356 bp
->b_flags
&= ~B_RELBUF
;
1357 } else if (vm_page_count_min(0)) {
1358 if (LIST_FIRST(&bp
->b_dep
) != NULL
)
1359 buf_deallocate(bp
); /* can set B_LOCKED */
1360 if (bp
->b_flags
& (B_DELWRI
| B_LOCKED
))
1361 bp
->b_flags
&= ~B_RELBUF
;
1363 bp
->b_flags
|= B_RELBUF
;
1367 * Make sure b_cmd is clear. It may have already been cleared by
1370 * At this point destroying the buffer is governed by the B_INVAL
1371 * or B_RELBUF flags.
1373 bp
->b_cmd
= BUF_CMD_DONE
;
1374 dsched_buf_exit(bp
);
1377 * VMIO buffer rundown. Make sure the VM page array is restored
1378 * after an I/O may have replaces some of the pages with bogus pages
1379 * in order to not destroy dirty pages in a fill-in read.
1381 * Note that due to the code above, if a buffer is marked B_DELWRI
1382 * then the B_RELBUF and B_NOCACHE bits will always be clear.
1383 * B_INVAL may still be set, however.
1385 * For clean buffers, B_INVAL or B_RELBUF will destroy the buffer
1386 * but not the backing store. B_NOCACHE will destroy the backing
1389 * Note that dirty NFS buffers contain byte-granular write ranges
1390 * and should not be destroyed w/ B_INVAL even if the backing store
1393 if (bp
->b_flags
& B_VMIO
) {
1395 * Rundown for VMIO buffers which are not dirty NFS buffers.
1407 * Get the base offset and length of the buffer. Note that
1408 * in the VMIO case if the buffer block size is not
1409 * page-aligned then b_data pointer may not be page-aligned.
1410 * But our b_xio.xio_pages array *IS* page aligned.
1412 * block sizes less then DEV_BSIZE (usually 512) are not
1413 * supported due to the page granularity bits (m->valid,
1414 * m->dirty, etc...).
1416 * See man buf(9) for more information
1419 resid
= bp
->b_bufsize
;
1420 foff
= bp
->b_loffset
;
1422 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
1423 m
= bp
->b_xio
.xio_pages
[i
];
1426 * If we hit a bogus page, fixup *all* of them
1427 * now. Note that we left these pages wired
1428 * when we removed them so they had better exist,
1429 * and they cannot be ripped out from under us so
1430 * no critical section protection is necessary.
1432 if (m
== bogus_page
) {
1434 poff
= OFF_TO_IDX(bp
->b_loffset
);
1436 vm_object_hold(obj
);
1437 for (j
= i
; j
< bp
->b_xio
.xio_npages
; j
++) {
1440 mtmp
= bp
->b_xio
.xio_pages
[j
];
1441 if (mtmp
== bogus_page
) {
1442 if ((bp
->b_flags
& B_HASBOGUS
) == 0)
1443 panic("brelse: bp %p corrupt bogus", bp
);
1444 mtmp
= vm_page_lookup(obj
, poff
+ j
);
1446 panic("brelse: bp %p page %d missing", bp
, j
);
1447 bp
->b_xio
.xio_pages
[j
] = mtmp
;
1450 vm_object_drop(obj
);
1452 if ((bp
->b_flags
& B_HASBOGUS
) ||
1453 (bp
->b_flags
& B_INVAL
) == 0) {
1454 pmap_qenter_noinval(
1455 trunc_page((vm_offset_t
)bp
->b_data
),
1456 bp
->b_xio
.xio_pages
,
1457 bp
->b_xio
.xio_npages
);
1458 bp
->b_flags
&= ~B_HASBOGUS
;
1459 bp
->b_flags
|= B_KVABIO
;
1462 m
= bp
->b_xio
.xio_pages
[i
];
1466 * Invalidate the backing store if B_NOCACHE is set
1467 * (e.g. used with vinvalbuf()). If this is NFS
1468 * we impose a requirement that the block size be
1469 * a multiple of PAGE_SIZE and create a temporary
1470 * hack to basically invalidate the whole page. The
1471 * problem is that NFS uses really odd buffer sizes
1472 * especially when tracking piecemeal writes and
1473 * it also vinvalbuf()'s a lot, which would result
1474 * in only partial page validation and invalidation
1475 * here. If the file page is mmap()'d, however,
1476 * all the valid bits get set so after we invalidate
1477 * here we would end up with weird m->valid values
1478 * like 0xfc. nfs_getpages() can't handle this so
1479 * we clear all the valid bits for the NFS case
1480 * instead of just some of them.
1482 * The real bug is the VM system having to set m->valid
1483 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1484 * itself is an artifact of the whole 512-byte
1485 * granular mess that exists to support odd block
1486 * sizes and UFS meta-data block sizes (e.g. 6144).
1487 * A complete rewrite is required.
1491 if (bp
->b_flags
& (B_NOCACHE
|B_ERROR
)) {
1492 int poffset
= foff
& PAGE_MASK
;
1495 presid
= PAGE_SIZE
- poffset
;
1496 if (bp
->b_vp
->v_tag
== VT_NFS
&&
1497 bp
->b_vp
->v_type
== VREG
) {
1499 } else if (presid
> resid
) {
1502 KASSERT(presid
>= 0, ("brelse: extra page"));
1503 vm_page_set_invalid(m
, poffset
, presid
);
1506 * Also make sure any swap cache is removed
1507 * as it is now stale (HAMMER in particular
1508 * uses B_NOCACHE to deal with buffer
1511 swap_pager_unswapped(m
);
1513 resid
-= PAGE_SIZE
- (foff
& PAGE_MASK
);
1514 foff
= (foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
;
1516 if (bp
->b_flags
& (B_INVAL
| B_RELBUF
))
1517 vfs_vmio_release(bp
);
1520 * Rundown for non-VMIO buffers.
1522 if (bp
->b_flags
& (B_INVAL
| B_RELBUF
)) {
1525 KKASSERT (LIST_FIRST(&bp
->b_dep
) == NULL
);
1531 if (bp
->b_qindex
!= BQUEUE_NONE
)
1532 panic("brelse: free buffer onto another queue???");
1535 * Figure out the correct queue to place the cleaned up buffer on.
1536 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1537 * disassociated from their vnode.
1539 * Return the buffer to its original pcpu area
1541 pcpu
= &bufpcpu
[bp
->b_qcpu
];
1542 spin_lock(&pcpu
->spin
);
1544 if (bp
->b_flags
& B_LOCKED
) {
1546 * Buffers that are locked are placed in the locked queue
1547 * immediately, regardless of their state.
1549 bp
->b_qindex
= BQUEUE_LOCKED
;
1550 TAILQ_INSERT_TAIL(&pcpu
->bufqueues
[bp
->b_qindex
],
1552 } else if (bp
->b_bufsize
== 0) {
1554 * Buffers with no memory. Due to conditionals near the top
1555 * of brelse() such buffers should probably already be
1556 * marked B_INVAL and disassociated from their vnode.
1558 bp
->b_flags
|= B_INVAL
;
1559 KASSERT(bp
->b_vp
== NULL
,
1560 ("bp1 %p flags %08x/%08x vnode %p "
1561 "unexpectededly still associated!",
1562 bp
, saved_flags
, bp
->b_flags
, bp
->b_vp
));
1563 KKASSERT((bp
->b_flags
& B_HASHED
) == 0);
1564 bp
->b_qindex
= BQUEUE_EMPTY
;
1565 TAILQ_INSERT_HEAD(&pcpu
->bufqueues
[bp
->b_qindex
],
1567 } else if (bp
->b_flags
& (B_INVAL
| B_NOCACHE
| B_RELBUF
)) {
1569 * Buffers with junk contents. Again these buffers had better
1570 * already be disassociated from their vnode.
1572 KASSERT(bp
->b_vp
== NULL
,
1573 ("bp2 %p flags %08x/%08x vnode %p unexpectededly "
1574 "still associated!",
1575 bp
, saved_flags
, bp
->b_flags
, bp
->b_vp
));
1576 KKASSERT((bp
->b_flags
& B_HASHED
) == 0);
1577 bp
->b_flags
|= B_INVAL
;
1578 bp
->b_qindex
= BQUEUE_CLEAN
;
1579 TAILQ_INSERT_HEAD(&pcpu
->bufqueues
[bp
->b_qindex
],
1583 * Remaining buffers. These buffers are still associated with
1586 switch(bp
->b_flags
& (B_DELWRI
|B_HEAVY
)) {
1588 bp
->b_qindex
= BQUEUE_DIRTY
;
1589 TAILQ_INSERT_TAIL(&pcpu
->bufqueues
[bp
->b_qindex
],
1592 case B_DELWRI
| B_HEAVY
:
1593 bp
->b_qindex
= BQUEUE_DIRTY_HW
;
1594 TAILQ_INSERT_TAIL(&pcpu
->bufqueues
[bp
->b_qindex
],
1599 * NOTE: Buffers are always placed at the end of the
1600 * queue. If B_AGE is not set the buffer will cycle
1601 * through the queue twice.
1603 bp
->b_qindex
= BQUEUE_CLEAN
;
1604 TAILQ_INSERT_TAIL(&pcpu
->bufqueues
[bp
->b_qindex
],
1609 spin_unlock(&pcpu
->spin
);
1612 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1613 * on the correct queue but we have not yet unlocked it.
1615 if ((bp
->b_flags
& (B_INVAL
|B_DELWRI
)) == (B_INVAL
|B_DELWRI
))
1619 * The bp is on an appropriate queue unless locked. If it is not
1620 * locked or dirty we can wakeup threads waiting for buffer space.
1622 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1623 * if B_INVAL is set ).
1625 if ((bp
->b_flags
& (B_LOCKED
|B_DELWRI
)) == 0)
1629 * Something we can maybe free or reuse
1631 if (bp
->b_bufsize
|| bp
->b_kvasize
)
1635 * Clean up temporary flags and unlock the buffer.
1637 bp
->b_flags
&= ~(B_NOCACHE
| B_RELBUF
| B_DIRECT
);
1644 * Release a buffer back to the appropriate queue but do not try to free
1645 * it. The buffer is expected to be used again soon.
1647 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1648 * biodone() to requeue an async I/O on completion. It is also used when
1649 * known good buffers need to be requeued but we think we may need the data
1652 * XXX we should be able to leave the B_RELBUF hint set on completion.
1655 bqrelse(struct buf
*bp
)
1657 struct bufpcpu
*pcpu
;
1659 KASSERT(!(bp
->b_flags
& (B_CLUSTER
|B_PAGING
)),
1660 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp
));
1662 if (bp
->b_qindex
!= BQUEUE_NONE
)
1663 panic("bqrelse: free buffer onto another queue???");
1665 buf_act_advance(bp
);
1667 pcpu
= &bufpcpu
[bp
->b_qcpu
];
1668 spin_lock(&pcpu
->spin
);
1670 if (bp
->b_flags
& B_LOCKED
) {
1672 * Locked buffers are released to the locked queue. However,
1673 * if the buffer is dirty it will first go into the dirty
1674 * queue and later on after the I/O completes successfully it
1675 * will be released to the locked queue.
1677 bp
->b_qindex
= BQUEUE_LOCKED
;
1678 TAILQ_INSERT_TAIL(&pcpu
->bufqueues
[bp
->b_qindex
],
1680 } else if (bp
->b_flags
& B_DELWRI
) {
1681 bp
->b_qindex
= (bp
->b_flags
& B_HEAVY
) ?
1682 BQUEUE_DIRTY_HW
: BQUEUE_DIRTY
;
1683 TAILQ_INSERT_TAIL(&pcpu
->bufqueues
[bp
->b_qindex
],
1685 } else if (vm_page_count_min(0)) {
1687 * We are too low on memory, we have to try to free the
1688 * buffer (most importantly: the wired pages making up its
1689 * backing store) *now*.
1691 spin_unlock(&pcpu
->spin
);
1695 bp
->b_qindex
= BQUEUE_CLEAN
;
1696 TAILQ_INSERT_TAIL(&pcpu
->bufqueues
[bp
->b_qindex
],
1699 spin_unlock(&pcpu
->spin
);
1702 * We have now placed the buffer on the proper queue, but have yet
1705 if ((bp
->b_flags
& B_LOCKED
) == 0 &&
1706 ((bp
->b_flags
& B_INVAL
) || (bp
->b_flags
& B_DELWRI
) == 0)) {
1711 * Something we can maybe free or reuse.
1713 if (bp
->b_bufsize
&& !(bp
->b_flags
& B_DELWRI
))
1717 * Final cleanup and unlock. Clear bits that are only used while a
1718 * buffer is actively locked.
1720 bp
->b_flags
&= ~(B_NOCACHE
| B_RELBUF
);
1721 dsched_buf_exit(bp
);
1726 * Hold a buffer, preventing it from being reused. This will prevent
1727 * normal B_RELBUF operations on the buffer but will not prevent B_INVAL
1728 * operations. If a B_INVAL operation occurs the buffer will remain held
1729 * but the underlying pages may get ripped out.
1731 * These functions are typically used in VOP_READ/VOP_WRITE functions
1732 * to hold a buffer during a copyin or copyout, preventing deadlocks
1733 * or recursive lock panics when read()/write() is used over mmap()'d
1736 * NOTE: bqhold() requires that the buffer be locked at the time of the
1737 * hold. bqdrop() has no requirements other than the buffer having
1738 * previously been held.
1741 bqhold(struct buf
*bp
)
1743 atomic_add_int(&bp
->b_refs
, 1);
1747 bqdrop(struct buf
*bp
)
1749 KKASSERT(bp
->b_refs
> 0);
1750 atomic_add_int(&bp
->b_refs
, -1);
1754 * Return backing pages held by the buffer 'bp' back to the VM system.
1755 * This routine is called when the bp is invalidated, released, or
1758 * The KVA mapping (b_data) for the underlying pages is removed by
1761 * WARNING! This routine is integral to the low memory critical path
1762 * when a buffer is B_RELBUF'd. If the system has a severe page
1763 * deficit we need to get the page(s) onto the PQ_FREE or PQ_CACHE
1764 * queues so they can be reused in the current pageout daemon
1768 vfs_vmio_release(struct buf
*bp
)
1773 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
1774 m
= bp
->b_xio
.xio_pages
[i
];
1775 bp
->b_xio
.xio_pages
[i
] = NULL
;
1778 * We need to own the page in order to safely unwire it.
1780 vm_page_busy_wait(m
, FALSE
, "vmiopg");
1783 * The VFS is telling us this is not a meta-data buffer
1784 * even if it is backed by a block device.
1786 if (bp
->b_flags
& B_NOTMETA
)
1787 vm_page_flag_set(m
, PG_NOTMETA
);
1790 * This is a very important bit of code. We try to track
1791 * VM page use whether the pages are wired into the buffer
1792 * cache or not. While wired into the buffer cache the
1793 * bp tracks the act_count.
1795 * We can choose to place unwired pages on the inactive
1796 * queue (0) or active queue (1). If we place too many
1797 * on the active queue the queue will cycle the act_count
1798 * on pages we'd like to keep, just from single-use pages
1799 * (such as when doing a tar-up or file scan).
1801 if (bp
->b_act_count
< vm_cycle_point
)
1802 vm_page_unwire(m
, 0);
1804 vm_page_unwire(m
, 1);
1807 * If the wire_count has dropped to 0 we may need to take
1808 * further action before unbusying the page.
1810 * WARNING: vm_page_try_*() also checks PG_NEED_COMMIT for us.
1812 if (m
->wire_count
== 0) {
1813 if (bp
->b_flags
& B_DIRECT
) {
1815 * Attempt to free the page if B_DIRECT is
1816 * set, the caller does not desire the page
1820 vm_page_try_to_free(m
);
1821 } else if ((bp
->b_flags
& B_NOTMETA
) ||
1822 vm_page_count_min(0)) {
1824 * Attempt to move the page to PQ_CACHE
1825 * if B_NOTMETA is set. This flag is set
1826 * by HAMMER to remove one of the two pages
1827 * present when double buffering is enabled.
1829 * Attempt to move the page to PQ_CACHE
1830 * If we have a severe page deficit. This
1831 * will cause buffer cache operations related
1832 * to pageouts to recycle the related pages
1833 * in order to avoid a low memory deadlock.
1835 m
->act_count
= bp
->b_act_count
;
1836 vm_page_try_to_cache(m
);
1839 * Nominal case, leave the page on the
1840 * queue the original unwiring placed it on
1841 * (active or inactive).
1843 m
->act_count
= bp
->b_act_count
;
1852 * Zero out the pmap pte's for the mapping, but don't bother
1853 * invalidating the TLB. The range will be properly invalidating
1854 * when new pages are entered into the mapping.
1856 * This in particular reduces tmpfs tear-down overhead and reduces
1857 * buffer cache re-use overhead (one invalidation sequence instead
1858 * of two per re-use).
1860 pmap_qremove_noinval(trunc_page((vm_offset_t
) bp
->b_data
),
1861 bp
->b_xio
.xio_npages
);
1862 CPUMASK_ASSZERO(bp
->b_cpumask
);
1863 if (bp
->b_bufsize
) {
1864 atomic_add_long(&bufspace
, -bp
->b_bufsize
);
1868 bp
->b_xio
.xio_npages
= 0;
1869 bp
->b_flags
&= ~B_VMIO
;
1870 KKASSERT (LIST_FIRST(&bp
->b_dep
) == NULL
);
1876 * Find and initialize a new buffer header, freeing up existing buffers
1877 * in the bufqueues as necessary. The new buffer is returned locked.
1879 * Important: B_INVAL is not set. If the caller wishes to throw the
1880 * buffer away, the caller must set B_INVAL prior to calling brelse().
1883 * We have insufficient buffer headers
1884 * We have insufficient buffer space
1886 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1887 * Instead we ask the buf daemon to do it for us. We attempt to
1888 * avoid piecemeal wakeups of the pageout daemon.
1891 getnewbuf(int blkflags
, int slptimeo
, int size
, int maxsize
)
1893 struct bufpcpu
*pcpu
;
1898 int slpflags
= (blkflags
& GETBLK_PCATCH
) ? PCATCH
: 0;
1899 int maxloops
= 200000;
1900 int restart_reason
= 0;
1901 struct buf
*restart_bp
= NULL
;
1902 static char flushingbufs
[MAXCPU
];
1906 * We can't afford to block since we might be holding a vnode lock,
1907 * which may prevent system daemons from running. We deal with
1908 * low-memory situations by proactively returning memory and running
1909 * async I/O rather then sync I/O.
1913 nqcpu
= mycpu
->gd_cpuid
;
1914 flushingp
= &flushingbufs
[nqcpu
];
1916 if (bufspace
< lobufspace
)
1919 if (debug_bufbio
&& --maxloops
== 0)
1920 panic("getnewbuf, excessive loops on cpu %d restart %d (%p)",
1921 mycpu
->gd_cpuid
, restart_reason
, restart_bp
);
1924 * Setup for scan. If we do not have enough free buffers,
1925 * we setup a degenerate case that immediately fails. Note
1926 * that if we are specially marked process, we are allowed to
1927 * dip into our reserves.
1929 * The scanning sequence is nominally: EMPTY->CLEAN
1931 pcpu
= &bufpcpu
[nqcpu
];
1932 spin_lock(&pcpu
->spin
);
1935 * Prime the scan for this cpu. Locate the first buffer to
1936 * check. If we are flushing buffers we must skip the
1939 nqindex
= BQUEUE_EMPTY
;
1940 nbp
= TAILQ_FIRST(&pcpu
->bufqueues
[BQUEUE_EMPTY
]);
1941 if (nbp
== NULL
|| *flushingp
) {
1942 nqindex
= BQUEUE_CLEAN
;
1943 nbp
= TAILQ_FIRST(&pcpu
->bufqueues
[BQUEUE_CLEAN
]);
1947 * Run scan, possibly freeing data and/or kva mappings on the fly,
1950 * WARNING! spin is held!
1952 while ((bp
= nbp
) != NULL
) {
1953 int qindex
= nqindex
;
1955 nbp
= TAILQ_NEXT(bp
, b_freelist
);
1958 * BQUEUE_CLEAN - B_AGE special case. If not set the bp
1959 * cycles through the queue twice before being selected.
1961 if (qindex
== BQUEUE_CLEAN
&&
1962 (bp
->b_flags
& B_AGE
) == 0 && nbp
) {
1963 bp
->b_flags
|= B_AGE
;
1964 TAILQ_REMOVE(&pcpu
->bufqueues
[qindex
],
1966 TAILQ_INSERT_TAIL(&pcpu
->bufqueues
[qindex
],
1972 * Calculate next bp ( we can only use it if we do not block
1973 * or do other fancy things ).
1978 nqindex
= BQUEUE_CLEAN
;
1979 if ((nbp
= TAILQ_FIRST(&pcpu
->bufqueues
[BQUEUE_CLEAN
])))
1993 KASSERT(bp
->b_qindex
== qindex
,
1994 ("getnewbuf: inconsistent queue %d bp %p", qindex
, bp
));
1997 * Note: we no longer distinguish between VMIO and non-VMIO
2000 KASSERT((bp
->b_flags
& B_DELWRI
) == 0,
2001 ("delwri buffer %p found in queue %d", bp
, qindex
));
2004 * Do not try to reuse a buffer with a non-zero b_refs.
2005 * This is an unsynchronized test. A synchronized test
2006 * is also performed after we lock the buffer.
2012 * Start freeing the bp. This is somewhat involved. nbp
2013 * remains valid only for BQUEUE_EMPTY bp's. Buffers
2014 * on the clean list must be disassociated from their
2015 * current vnode. Buffers on the empty lists have
2016 * already been disassociated.
2018 * b_refs is checked after locking along with queue changes.
2019 * We must check here to deal with zero->nonzero transitions
2020 * made by the owner of the buffer lock, which is used by
2021 * VFS's to hold the buffer while issuing an unlocked
2022 * uiomove()s. We cannot invalidate the buffer's pages
2023 * for this case. Once we successfully lock a buffer the
2024 * only 0->1 transitions of b_refs will occur via findblk().
2026 * We must also check for queue changes after successful
2027 * locking as the current lock holder may dispose of the
2028 * buffer and change its queue.
2030 if (BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_NOWAIT
) != 0) {
2031 spin_unlock(&pcpu
->spin
);
2032 tsleep(&bd_request
, 0, "gnbxxx", (hz
+ 99) / 100);
2037 if (bp
->b_qindex
!= qindex
|| bp
->b_refs
) {
2038 spin_unlock(&pcpu
->spin
);
2044 bremfree_locked(bp
);
2045 spin_unlock(&pcpu
->spin
);
2048 * Dependancies must be handled before we disassociate the
2051 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
2052 * be immediately disassociated. HAMMER then becomes
2053 * responsible for releasing the buffer.
2055 * NOTE: spin is UNLOCKED now.
2057 if (LIST_FIRST(&bp
->b_dep
) != NULL
) {
2059 if (bp
->b_flags
& B_LOCKED
) {
2065 KKASSERT(LIST_FIRST(&bp
->b_dep
) == NULL
);
2069 * CLEAN buffers have content or associations that must be
2070 * cleaned out if not repurposing.
2072 if (qindex
== BQUEUE_CLEAN
) {
2073 if (bp
->b_flags
& B_VMIO
)
2074 vfs_vmio_release(bp
);
2080 * NOTE: nbp is now entirely invalid. We can only restart
2081 * the scan from this point on.
2083 * Get the rest of the buffer freed up. b_kva* is still
2084 * valid after this operation.
2086 KASSERT(bp
->b_vp
== NULL
,
2087 ("bp3 %p flags %08x vnode %p qindex %d "
2088 "unexpectededly still associated!",
2089 bp
, bp
->b_flags
, bp
->b_vp
, qindex
));
2090 KKASSERT((bp
->b_flags
& B_HASHED
) == 0);
2095 if (bp
->b_flags
& (B_VNDIRTY
| B_VNCLEAN
| B_HASHED
)) {
2096 kprintf("getnewbuf: caught bug vp queue "
2097 "%p/%08x qidx %d\n",
2098 bp
, bp
->b_flags
, qindex
);
2101 bp
->b_flags
= B_BNOCLIP
;
2102 bp
->b_cmd
= BUF_CMD_DONE
;
2107 bp
->b_xio
.xio_npages
= 0;
2108 bp
->b_dirtyoff
= bp
->b_dirtyend
= 0;
2109 bp
->b_act_count
= ACT_INIT
;
2111 KKASSERT(LIST_FIRST(&bp
->b_dep
) == NULL
);
2113 if (blkflags
& GETBLK_BHEAVY
)
2114 bp
->b_flags
|= B_HEAVY
;
2116 if (bufspace
>= hibufspace
)
2118 if (bufspace
< lobufspace
)
2121 bp
->b_flags
|= B_INVAL
;
2129 * b_refs can transition to a non-zero value while we hold
2130 * the buffer locked due to a findblk(). Our brelvp() above
2131 * interlocked any future possible transitions due to
2134 * If we find b_refs to be non-zero we can destroy the
2135 * buffer's contents but we cannot yet reuse the buffer.
2138 bp
->b_flags
|= B_INVAL
;
2147 * We found our buffer!
2153 * If we exhausted our list, iterate other cpus. If that fails,
2154 * sleep as appropriate. We may have to wakeup various daemons
2155 * and write out some dirty buffers.
2157 * Generally we are sleeping due to insufficient buffer space.
2159 * NOTE: spin is held if bp is NULL, else it is not held.
2165 spin_unlock(&pcpu
->spin
);
2167 nqcpu
= (nqcpu
+ 1) % ncpus
;
2168 if (nqcpu
!= mycpu
->gd_cpuid
) {
2174 if (bufspace
>= hibufspace
) {
2176 flags
= VFS_BIO_NEED_BUFSPACE
;
2179 flags
= VFS_BIO_NEED_ANY
;
2182 bd_speedup(); /* heeeelp */
2183 atomic_set_int(&needsbuffer
, flags
);
2184 while (needsbuffer
& flags
) {
2187 tsleep_interlock(&needsbuffer
, 0);
2188 value
= atomic_fetchadd_int(&needsbuffer
, 0);
2189 if (value
& flags
) {
2190 if (tsleep(&needsbuffer
, PINTERLOCKED
|slpflags
,
2191 waitmsg
, slptimeo
)) {
2198 * We finally have a valid bp. Reset b_data.
2200 * (spin is not held)
2202 bp
->b_data
= bp
->b_kvabase
;
2210 * Buffer flushing daemon. Buffers are normally flushed by the
2211 * update daemon but if it cannot keep up this process starts to
2212 * take the load in an attempt to prevent getnewbuf() from blocking.
2214 * Once a flush is initiated it does not stop until the number
2215 * of buffers falls below lodirtybuffers, but we will wake up anyone
2216 * waiting at the mid-point.
2218 static struct kproc_desc buf_kp
= {
2223 SYSINIT(bufdaemon
, SI_SUB_KTHREAD_BUF
, SI_ORDER_FIRST
,
2224 kproc_start
, &buf_kp
);
2226 static struct kproc_desc bufhw_kp
= {
2231 SYSINIT(bufdaemon_hw
, SI_SUB_KTHREAD_BUF
, SI_ORDER_FIRST
,
2232 kproc_start
, &bufhw_kp
);
2235 buf_daemon1(struct thread
*td
, int queue
, int (*buf_limit_fn
)(long),
2241 marker
= kmalloc(sizeof(*marker
), M_BIOBUF
, M_WAITOK
| M_ZERO
);
2242 marker
->b_flags
|= B_MARKER
;
2243 marker
->b_qindex
= BQUEUE_NONE
;
2247 * This process needs to be suspended prior to shutdown sync.
2249 EVENTHANDLER_REGISTER(shutdown_pre_sync
, shutdown_kproc
,
2250 td
, SHUTDOWN_PRI_LAST
);
2251 curthread
->td_flags
|= TDF_SYSTHREAD
;
2254 * This process is allowed to take the buffer cache to the limit
2257 kproc_suspend_loop();
2260 * Do the flush as long as the number of dirty buffers
2261 * (including those running) exceeds lodirtybufspace.
2263 * When flushing limit running I/O to hirunningspace
2264 * Do the flush. Limit the amount of in-transit I/O we
2265 * allow to build up, otherwise we would completely saturate
2266 * the I/O system. Wakeup any waiting processes before we
2267 * normally would so they can run in parallel with our drain.
2269 * Our aggregate normal+HW lo water mark is lodirtybufspace,
2270 * but because we split the operation into two threads we
2271 * have to cut it in half for each thread.
2273 waitrunningbufspace();
2274 limit
= lodirtybufspace
/ 2;
2275 while (buf_limit_fn(limit
)) {
2276 if (flushbufqueues(marker
, queue
) == 0)
2278 if (runningbufspace
< hirunningspace
)
2280 waitrunningbufspace();
2284 * We reached our low water mark, reset the
2285 * request and sleep until we are needed again.
2286 * The sleep is just so the suspend code works.
2288 tsleep_interlock(bd_req
, 0);
2289 if (atomic_swap_int(bd_req
, 0) == 0)
2290 tsleep(bd_req
, PINTERLOCKED
, "psleep", hz
);
2293 /*kfree(marker, M_BIOBUF);*/
2297 buf_daemon_limit(long limit
)
2299 return (runningbufspace
+ dirtykvaspace
> limit
||
2300 dirtybufcount
- dirtybufcounthw
>= nbuf
/ 2);
2304 buf_daemon_hw_limit(long limit
)
2306 return (runningbufspace
+ dirtykvaspace
> limit
||
2307 dirtybufcounthw
>= nbuf
/ 2);
2313 buf_daemon1(bufdaemon_td
, BQUEUE_DIRTY
, buf_daemon_limit
,
2320 buf_daemon1(bufdaemonhw_td
, BQUEUE_DIRTY_HW
, buf_daemon_hw_limit
,
2325 * Flush up to (flushperqueue) buffers in the dirty queue. Each cpu has a
2326 * localized version of the queue. Each call made to this function iterates
2327 * to another cpu. It is desireable to flush several buffers from the same
2328 * cpu's queue at once, as these are likely going to be linear.
2330 * We must be careful to free up B_INVAL buffers instead of write them, which
2331 * NFS is particularly sensitive to.
2333 * B_RELBUF may only be set by VFSs. We do set B_AGE to indicate that we
2334 * really want to try to get the buffer out and reuse it due to the write
2335 * load on the machine.
2337 * We must lock the buffer in order to check its validity before we can mess
2338 * with its contents. spin isn't enough.
2341 flushbufqueues(struct buf
*marker
, bufq_type_t q
)
2343 struct bufpcpu
*pcpu
;
2346 u_int loops
= flushperqueue
;
2347 int lcpu
= marker
->b_qcpu
;
2349 KKASSERT(marker
->b_qindex
== BQUEUE_NONE
);
2350 KKASSERT(marker
->b_flags
& B_MARKER
);
2354 * Spinlock needed to perform operations on the queue and may be
2355 * held through a non-blocking BUF_LOCK(), but cannot be held when
2356 * BUF_UNLOCK()ing or through any other major operation.
2358 pcpu
= &bufpcpu
[marker
->b_qcpu
];
2359 spin_lock(&pcpu
->spin
);
2360 marker
->b_qindex
= q
;
2361 TAILQ_INSERT_HEAD(&pcpu
->bufqueues
[q
], marker
, b_freelist
);
2364 while ((bp
= TAILQ_NEXT(bp
, b_freelist
)) != NULL
) {
2366 * NOTE: spinlock is always held at the top of the loop
2368 if (bp
->b_flags
& B_MARKER
)
2370 if ((bp
->b_flags
& B_DELWRI
) == 0) {
2371 kprintf("Unexpected clean buffer %p\n", bp
);
2374 if (BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_NOWAIT
))
2376 KKASSERT(bp
->b_qcpu
== marker
->b_qcpu
&& bp
->b_qindex
== q
);
2379 * Once the buffer is locked we will have no choice but to
2380 * unlock the spinlock around a later BUF_UNLOCK and re-set
2381 * bp = marker when looping. Move the marker now to make
2384 TAILQ_REMOVE(&pcpu
->bufqueues
[q
], marker
, b_freelist
);
2385 TAILQ_INSERT_AFTER(&pcpu
->bufqueues
[q
], bp
, marker
, b_freelist
);
2388 * Must recheck B_DELWRI after successfully locking
2391 if ((bp
->b_flags
& B_DELWRI
) == 0) {
2392 spin_unlock(&pcpu
->spin
);
2394 spin_lock(&pcpu
->spin
);
2400 * Remove the buffer from its queue. We still own the
2406 * Disposing of an invalid buffer counts as a flush op
2408 if (bp
->b_flags
& B_INVAL
) {
2409 spin_unlock(&pcpu
->spin
);
2415 * Release the spinlock for the more complex ops we
2416 * are now going to do.
2418 spin_unlock(&pcpu
->spin
);
2422 * This is a bit messy
2424 if (LIST_FIRST(&bp
->b_dep
) != NULL
&&
2425 (bp
->b_flags
& B_DEFERRED
) == 0 &&
2426 buf_countdeps(bp
, 0)) {
2427 spin_lock(&pcpu
->spin
);
2428 TAILQ_INSERT_TAIL(&pcpu
->bufqueues
[q
], bp
, b_freelist
);
2430 bp
->b_flags
|= B_DEFERRED
;
2431 spin_unlock(&pcpu
->spin
);
2433 spin_lock(&pcpu
->spin
);
2439 * spinlock not held here.
2441 * If the buffer has a dependancy, buf_checkwrite() must
2442 * also return 0 for us to be able to initate the write.
2444 * If the buffer is flagged B_ERROR it may be requeued
2445 * over and over again, we try to avoid a live lock.
2447 if (LIST_FIRST(&bp
->b_dep
) != NULL
&& buf_checkwrite(bp
)) {
2449 } else if (bp
->b_flags
& B_ERROR
) {
2450 tsleep(bp
, 0, "bioer", 1);
2451 bp
->b_flags
&= ~B_AGE
;
2454 bp
->b_flags
|= B_AGE
| B_KVABIO
;
2457 /* bp invalid but needs to be NULL-tested if we break out */
2459 spin_lock(&pcpu
->spin
);
2465 /* bp is invalid here but can be NULL-tested to advance */
2467 TAILQ_REMOVE(&pcpu
->bufqueues
[q
], marker
, b_freelist
);
2468 marker
->b_qindex
= BQUEUE_NONE
;
2469 spin_unlock(&pcpu
->spin
);
2472 * Advance the marker to be fair.
2474 marker
->b_qcpu
= (marker
->b_qcpu
+ 1) % ncpus
;
2476 if (marker
->b_qcpu
!= lcpu
)
2486 * Returns true if no I/O is needed to access the associated VM object.
2487 * This is like findblk except it also hunts around in the VM system for
2490 * Note that we ignore vm_page_free() races from interrupts against our
2491 * lookup, since if the caller is not protected our return value will not
2492 * be any more valid then otherwise once we exit the critical section.
2495 inmem(struct vnode
*vp
, off_t loffset
)
2498 vm_offset_t toff
, tinc
, size
;
2502 if (findblk(vp
, loffset
, FINDBLK_TEST
))
2504 if (vp
->v_mount
== NULL
)
2506 if ((obj
= vp
->v_object
) == NULL
)
2510 if (size
> vp
->v_mount
->mnt_stat
.f_iosize
)
2511 size
= vp
->v_mount
->mnt_stat
.f_iosize
;
2513 vm_object_hold(obj
);
2514 for (toff
= 0; toff
< vp
->v_mount
->mnt_stat
.f_iosize
; toff
+= tinc
) {
2515 m
= vm_page_lookup(obj
, OFF_TO_IDX(loffset
+ toff
));
2521 if (tinc
> PAGE_SIZE
- ((toff
+ loffset
) & PAGE_MASK
))
2522 tinc
= PAGE_SIZE
- ((toff
+ loffset
) & PAGE_MASK
);
2523 if (vm_page_is_valid(m
,
2524 (vm_offset_t
) ((toff
+ loffset
) & PAGE_MASK
), tinc
) == 0) {
2529 vm_object_drop(obj
);
2536 * Locate and return the specified buffer. Unless flagged otherwise,
2537 * a locked buffer will be returned if it exists or NULL if it does not.
2539 * findblk()'d buffers are still on the bufqueues and if you intend
2540 * to use your (locked NON-TEST) buffer you need to bremfree(bp)
2541 * and possibly do other stuff to it.
2543 * FINDBLK_TEST - Do not lock the buffer. The caller is responsible
2544 * for locking the buffer and ensuring that it remains
2545 * the desired buffer after locking.
2547 * FINDBLK_NBLOCK - Lock the buffer non-blocking. If we are unable
2548 * to acquire the lock we return NULL, even if the
2551 * FINDBLK_REF - Returns the buffer ref'd, which prevents normal
2552 * reuse by getnewbuf() but does not prevent
2553 * disassociation (B_INVAL). Used to avoid deadlocks
2554 * against random (vp,loffset)s due to reassignment.
2556 * FINDBLK_KVABIO - Only applicable when returning a locked buffer.
2557 * Indicates that the caller supports B_KVABIO.
2559 * (0) - Lock the buffer blocking.
2562 findblk(struct vnode
*vp
, off_t loffset
, int flags
)
2567 lkflags
= LK_EXCLUSIVE
;
2568 if (flags
& FINDBLK_NBLOCK
)
2569 lkflags
|= LK_NOWAIT
;
2573 * Lookup. Ref the buf while holding v_token to prevent
2574 * reuse (but does not prevent diassociation).
2576 lwkt_gettoken_shared(&vp
->v_token
);
2577 bp
= buf_rb_hash_RB_LOOKUP(&vp
->v_rbhash_tree
, loffset
);
2579 lwkt_reltoken(&vp
->v_token
);
2583 lwkt_reltoken(&vp
->v_token
);
2586 * If testing only break and return bp, do not lock.
2588 if (flags
& FINDBLK_TEST
)
2592 * Lock the buffer, return an error if the lock fails.
2593 * (only FINDBLK_NBLOCK can cause the lock to fail).
2595 if (BUF_LOCK(bp
, lkflags
)) {
2596 atomic_subtract_int(&bp
->b_refs
, 1);
2597 /* bp = NULL; not needed */
2602 * Revalidate the locked buf before allowing it to be
2605 * B_KVABIO is only set/cleared when locking. When
2606 * clearing B_KVABIO, we must ensure that the buffer
2607 * is synchronized to all cpus.
2609 if (bp
->b_vp
== vp
&& bp
->b_loffset
== loffset
) {
2610 if (flags
& FINDBLK_KVABIO
)
2611 bp
->b_flags
|= B_KVABIO
;
2616 atomic_subtract_int(&bp
->b_refs
, 1);
2623 if ((flags
& FINDBLK_REF
) == 0)
2624 atomic_subtract_int(&bp
->b_refs
, 1);
2631 * Similar to getblk() except only returns the buffer if it is
2632 * B_CACHE and requires no other manipulation. Otherwise NULL
2633 * is returned. NULL is also returned if GETBLK_NOWAIT is set
2634 * and the getblk() would block.
2636 * If B_RAM is set the buffer might be just fine, but we return
2637 * NULL anyway because we want the code to fall through to the
2638 * cluster read to issue more read-aheads. Otherwise read-ahead breaks.
2640 * If blksize is 0 the buffer cache buffer must already be fully
2643 * If blksize is non-zero getblk() will be used, allowing a buffer
2644 * to be reinstantiated from its VM backing store. The buffer must
2645 * still be fully cached after reinstantiation to be returned.
2648 getcacheblk(struct vnode
*vp
, off_t loffset
, int blksize
, int blkflags
)
2653 if (blkflags
& GETBLK_NOWAIT
)
2654 fndflags
|= FINDBLK_NBLOCK
;
2655 if (blkflags
& GETBLK_KVABIO
)
2656 fndflags
|= FINDBLK_KVABIO
;
2659 bp
= getblk(vp
, loffset
, blksize
, blkflags
, 0);
2661 if ((bp
->b_flags
& (B_INVAL
| B_CACHE
)) == B_CACHE
) {
2662 bp
->b_flags
&= ~B_AGE
;
2663 if (bp
->b_flags
& B_RAM
) {
2673 bp
= findblk(vp
, loffset
, fndflags
);
2675 if ((bp
->b_flags
& (B_INVAL
| B_CACHE
| B_RAM
)) ==
2677 bp
->b_flags
&= ~B_AGE
;
2691 * Get a block given a specified block and offset into a file/device.
2692 * B_INVAL may or may not be set on return. The caller should clear
2693 * B_INVAL prior to initiating a READ.
2695 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2696 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2697 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2698 * without doing any of those things the system will likely believe
2699 * the buffer to be valid (especially if it is not B_VMIO), and the
2700 * next getblk() will return the buffer with B_CACHE set.
2702 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2703 * an existing buffer.
2705 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2706 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2707 * and then cleared based on the backing VM. If the previous buffer is
2708 * non-0-sized but invalid, B_CACHE will be cleared.
2710 * If getblk() must create a new buffer, the new buffer is returned with
2711 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2712 * case it is returned with B_INVAL clear and B_CACHE set based on the
2715 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
2716 * B_CACHE bit is clear.
2718 * What this means, basically, is that the caller should use B_CACHE to
2719 * determine whether the buffer is fully valid or not and should clear
2720 * B_INVAL prior to issuing a read. If the caller intends to validate
2721 * the buffer by loading its data area with something, the caller needs
2722 * to clear B_INVAL. If the caller does this without issuing an I/O,
2723 * the caller should set B_CACHE ( as an optimization ), else the caller
2724 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2725 * a write attempt or if it was a successfull read. If the caller
2726 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2727 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2731 * GETBLK_PCATCH - catch signal if blocked, can cause NULL return
2732 * GETBLK_BHEAVY - heavy-weight buffer cache buffer
2735 getblk(struct vnode
*vp
, off_t loffset
, int size
, int blkflags
, int slptimeo
)
2738 int slpflags
= (blkflags
& GETBLK_PCATCH
) ? PCATCH
: 0;
2742 if (size
> MAXBSIZE
)
2743 panic("getblk: size(%d) > MAXBSIZE(%d)", size
, MAXBSIZE
);
2744 if (vp
->v_object
== NULL
)
2745 panic("getblk: vnode %p has no object!", vp
);
2748 * NOTE: findblk does not try to resolve KVABIO in REF-only mode.
2749 * we still have to handle that ourselves.
2752 if ((bp
= findblk(vp
, loffset
, FINDBLK_REF
| FINDBLK_TEST
)) != NULL
) {
2754 * The buffer was found in the cache, but we need to lock it.
2755 * We must acquire a ref on the bp to prevent reuse, but
2756 * this will not prevent disassociation (brelvp()) so we
2757 * must recheck (vp,loffset) after acquiring the lock.
2759 * Without the ref the buffer could potentially be reused
2760 * before we acquire the lock and create a deadlock
2761 * situation between the thread trying to reuse the buffer
2762 * and us due to the fact that we would wind up blocking
2763 * on a random (vp,loffset).
2765 if (BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_NOWAIT
)) {
2766 if (blkflags
& GETBLK_NOWAIT
) {
2770 lkflags
= LK_EXCLUSIVE
| LK_SLEEPFAIL
;
2771 if (blkflags
& GETBLK_PCATCH
)
2772 lkflags
|= LK_PCATCH
;
2773 error
= BUF_TIMELOCK(bp
, lkflags
, "getblk", slptimeo
);
2776 if (error
== ENOLCK
)
2780 /* buffer may have changed on us */
2785 * Once the buffer has been locked, make sure we didn't race
2786 * a buffer recyclement. Buffers that are no longer hashed
2787 * will have b_vp == NULL, so this takes care of that check
2790 if (bp
->b_vp
!= vp
|| bp
->b_loffset
!= loffset
) {
2792 kprintf("Warning buffer %p (vp %p loffset %lld) "
2794 bp
, vp
, (long long)loffset
);
2801 * If SZMATCH any pre-existing buffer must be of the requested
2802 * size or NULL is returned. The caller absolutely does not
2803 * want getblk() to bwrite() the buffer on a size mismatch.
2805 if ((blkflags
& GETBLK_SZMATCH
) && size
!= bp
->b_bcount
) {
2811 * All vnode-based buffers must be backed by a VM object.
2813 * Set B_KVABIO for any incidental work, we will fix it
2816 KKASSERT(bp
->b_flags
& B_VMIO
);
2817 KKASSERT(bp
->b_cmd
== BUF_CMD_DONE
);
2818 bp
->b_flags
&= ~B_AGE
;
2819 bp
->b_flags
|= B_KVABIO
;
2822 * Make sure that B_INVAL buffers do not have a cached
2823 * block number translation.
2825 if ((bp
->b_flags
& B_INVAL
) &&
2826 (bp
->b_bio2
.bio_offset
!= NOOFFSET
)) {
2827 kprintf("Warning invalid buffer %p (vp %p loffset %lld)"
2828 " did not have cleared bio_offset cache\n",
2829 bp
, vp
, (long long)loffset
);
2830 clearbiocache(&bp
->b_bio2
);
2834 * The buffer is locked. B_CACHE is cleared if the buffer is
2837 * After the bremfree(), disposals must use b[q]relse().
2839 if (bp
->b_flags
& B_INVAL
)
2840 bp
->b_flags
&= ~B_CACHE
;
2844 * Any size inconsistancy with a dirty buffer or a buffer
2845 * with a softupdates dependancy must be resolved. Resizing
2846 * the buffer in such circumstances can lead to problems.
2848 * Dirty or dependant buffers are written synchronously.
2849 * Other types of buffers are simply released and
2850 * reconstituted as they may be backed by valid, dirty VM
2851 * pages (but not marked B_DELWRI).
2853 * NFS NOTE: NFS buffers which straddle EOF are oddly-sized
2854 * and may be left over from a prior truncation (and thus
2855 * no longer represent the actual EOF point), so we
2856 * definitely do not want to B_NOCACHE the backing store.
2858 if (size
!= bp
->b_bcount
) {
2859 if (bp
->b_flags
& B_DELWRI
) {
2860 bp
->b_flags
|= B_RELBUF
;
2862 } else if (LIST_FIRST(&bp
->b_dep
)) {
2863 bp
->b_flags
|= B_RELBUF
;
2866 bp
->b_flags
|= B_RELBUF
;
2871 KKASSERT(size
<= bp
->b_kvasize
);
2872 KASSERT(bp
->b_loffset
!= NOOFFSET
,
2873 ("getblk: no buffer offset"));
2876 * A buffer with B_DELWRI set and B_CACHE clear must
2877 * be committed before we can return the buffer in
2878 * order to prevent the caller from issuing a read
2879 * ( due to B_CACHE not being set ) and overwriting
2882 * Most callers, including NFS and FFS, need this to
2883 * operate properly either because they assume they
2884 * can issue a read if B_CACHE is not set, or because
2885 * ( for example ) an uncached B_DELWRI might loop due
2886 * to softupdates re-dirtying the buffer. In the latter
2887 * case, B_CACHE is set after the first write completes,
2888 * preventing further loops.
2890 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2891 * above while extending the buffer, we cannot allow the
2892 * buffer to remain with B_CACHE set after the write
2893 * completes or it will represent a corrupt state. To
2894 * deal with this we set B_NOCACHE to scrap the buffer
2897 * XXX Should this be B_RELBUF instead of B_NOCACHE?
2898 * I'm not even sure this state is still possible
2899 * now that getblk() writes out any dirty buffers
2902 * We might be able to do something fancy, like setting
2903 * B_CACHE in bwrite() except if B_DELWRI is already set,
2904 * so the below call doesn't set B_CACHE, but that gets real
2905 * confusing. This is much easier.
2907 if ((bp
->b_flags
& (B_CACHE
|B_DELWRI
)) == B_DELWRI
) {
2908 kprintf("getblk: Warning, bp %p loff=%jx DELWRI set "
2909 "and CACHE clear, b_flags %08x\n",
2910 bp
, (uintmax_t)bp
->b_loffset
, bp
->b_flags
);
2911 bp
->b_flags
|= B_NOCACHE
;
2917 * Buffer is not in-core, create new buffer. The buffer
2918 * returned by getnewbuf() is locked. Note that the returned
2919 * buffer is also considered valid (not marked B_INVAL).
2921 * Calculating the offset for the I/O requires figuring out
2922 * the block size. We use DEV_BSIZE for VBLK or VCHR and
2923 * the mount's f_iosize otherwise. If the vnode does not
2924 * have an associated mount we assume that the passed size is
2927 * Note that vn_isdisk() cannot be used here since it may
2928 * return a failure for numerous reasons. Note that the
2929 * buffer size may be larger then the block size (the caller
2930 * will use block numbers with the proper multiple). Beware
2931 * of using any v_* fields which are part of unions. In
2932 * particular, in DragonFly the mount point overloading
2933 * mechanism uses the namecache only and the underlying
2934 * directory vnode is not a special case.
2938 if (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
)
2940 else if (vp
->v_mount
)
2941 bsize
= vp
->v_mount
->mnt_stat
.f_iosize
;
2945 maxsize
= size
+ (loffset
& PAGE_MASK
);
2946 maxsize
= imax(maxsize
, bsize
);
2948 bp
= getnewbuf(blkflags
, slptimeo
, size
, maxsize
);
2950 if (slpflags
|| slptimeo
)
2956 * Atomically insert the buffer into the hash, so that it can
2957 * be found by findblk().
2959 * If bgetvp() returns non-zero a collision occured, and the
2960 * bp will not be associated with the vnode.
2962 * Make sure the translation layer has been cleared.
2964 bp
->b_loffset
= loffset
;
2965 bp
->b_bio2
.bio_offset
= NOOFFSET
;
2966 /* bp->b_bio2.bio_next = NULL; */
2968 if (bgetvp(vp
, bp
, size
)) {
2969 bp
->b_flags
|= B_INVAL
;
2975 * All vnode-based buffers must be backed by a VM object.
2977 * Set B_KVABIO for incidental work
2979 KKASSERT(vp
->v_object
!= NULL
);
2980 bp
->b_flags
|= B_VMIO
| B_KVABIO
;
2981 KKASSERT(bp
->b_cmd
== BUF_CMD_DONE
);
2987 * Do the nasty smp broadcast (if the buffer needs it) when KVABIO
2990 if (bp
&& (blkflags
& GETBLK_KVABIO
) == 0) {
2999 * Reacquire a buffer that was previously released to the locked queue,
3000 * or reacquire a buffer which is interlocked by having bioops->io_deallocate
3001 * set B_LOCKED (which handles the acquisition race).
3003 * To this end, either B_LOCKED must be set or the dependancy list must be
3007 regetblk(struct buf
*bp
)
3009 KKASSERT((bp
->b_flags
& B_LOCKED
) || LIST_FIRST(&bp
->b_dep
) != NULL
);
3010 BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_RETRY
);
3017 * This code constitutes the buffer memory from either anonymous system
3018 * memory (in the case of non-VMIO operations) or from an associated
3019 * VM object (in the case of VMIO operations). This code is able to
3020 * resize a buffer up or down.
3022 * Note that this code is tricky, and has many complications to resolve
3023 * deadlock or inconsistant data situations. Tread lightly!!!
3024 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3025 * the caller. Calling this code willy nilly can result in the loss of
3028 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
3029 * B_CACHE for the non-VMIO case.
3031 * This routine does not need to be called from a critical section but you
3032 * must own the buffer.
3035 allocbuf(struct buf
*bp
, int size
)
3042 if (BUF_LOCKINUSE(bp
) == 0)
3043 panic("allocbuf: buffer not busy");
3045 if (bp
->b_kvasize
< size
)
3046 panic("allocbuf: buffer too small");
3048 KKASSERT(bp
->b_flags
& B_VMIO
);
3050 newbsize
= roundup2(size
, DEV_BSIZE
);
3051 desiredpages
= ((int)(bp
->b_loffset
& PAGE_MASK
) +
3052 newbsize
+ PAGE_MASK
) >> PAGE_SHIFT
;
3053 KKASSERT(desiredpages
<= XIO_INTERNAL_PAGES
);
3056 * Set B_CACHE initially if buffer is 0 length or will become
3059 if (size
== 0 || bp
->b_bufsize
== 0)
3060 bp
->b_flags
|= B_CACHE
;
3062 if (newbsize
< bp
->b_bufsize
) {
3064 * DEV_BSIZE aligned new buffer size is less then the
3065 * DEV_BSIZE aligned existing buffer size. Figure out
3066 * if we have to remove any pages.
3068 if (desiredpages
< bp
->b_xio
.xio_npages
) {
3069 for (i
= desiredpages
; i
< bp
->b_xio
.xio_npages
; i
++) {
3071 * the page is not freed here -- it
3072 * is the responsibility of
3073 * vnode_pager_setsize
3075 m
= bp
->b_xio
.xio_pages
[i
];
3076 KASSERT(m
!= bogus_page
,
3077 ("allocbuf: bogus page found"));
3078 vm_page_busy_wait(m
, TRUE
, "biodep");
3079 bp
->b_xio
.xio_pages
[i
] = NULL
;
3080 vm_page_unwire(m
, 0);
3083 pmap_qremove_noinval((vm_offset_t
)
3084 trunc_page((vm_offset_t
)bp
->b_data
) +
3085 (desiredpages
<< PAGE_SHIFT
),
3086 (bp
->b_xio
.xio_npages
- desiredpages
));
3087 bp
->b_xio
.xio_npages
= desiredpages
;
3090 * Don't bother invalidating the pmap changes
3091 * (which wastes global SMP invalidation IPIs)
3092 * when setting the size to 0. This case occurs
3093 * when called via getnewbuf() during buffer
3096 if (desiredpages
== 0) {
3097 CPUMASK_ASSZERO(bp
->b_cpumask
);
3102 } else if (size
> bp
->b_bcount
) {
3104 * We are growing the buffer, possibly in a
3105 * byte-granular fashion.
3113 * Step 1, bring in the VM pages from the object,
3114 * allocating them if necessary. We must clear
3115 * B_CACHE if these pages are not valid for the
3116 * range covered by the buffer.
3121 vm_object_hold(obj
);
3122 while (bp
->b_xio
.xio_npages
< desiredpages
) {
3127 pi
= OFF_TO_IDX(bp
->b_loffset
) +
3128 bp
->b_xio
.xio_npages
;
3131 * Blocking on m->busy_count might lead to a
3134 * vm_fault->getpages->cluster_read->allocbuf
3136 m
= vm_page_lookup_busy_try(obj
, pi
, FALSE
,
3139 vm_page_sleep_busy(m
, FALSE
, "pgtblk");
3144 * note: must allocate system pages
3145 * since blocking here could intefere
3146 * with paging I/O, no matter which
3149 m
= bio_page_alloc(bp
, obj
, pi
,
3151 bp
->b_xio
.xio_npages
);
3155 bp
->b_flags
&= ~B_CACHE
;
3156 bp
->b_xio
.xio_pages
[bp
->b_xio
.xio_npages
] = m
;
3157 ++bp
->b_xio
.xio_npages
;
3163 * We found a page and were able to busy it.
3167 bp
->b_xio
.xio_pages
[bp
->b_xio
.xio_npages
] = m
;
3168 ++bp
->b_xio
.xio_npages
;
3169 if (bp
->b_act_count
< m
->act_count
)
3170 bp
->b_act_count
= m
->act_count
;
3172 vm_object_drop(obj
);
3175 * Step 2. We've loaded the pages into the buffer,
3176 * we have to figure out if we can still have B_CACHE
3177 * set. Note that B_CACHE is set according to the
3178 * byte-granular range ( bcount and size ), not the
3179 * aligned range ( newbsize ).
3181 * The VM test is against m->valid, which is DEV_BSIZE
3182 * aligned. Needless to say, the validity of the data
3183 * needs to also be DEV_BSIZE aligned. Note that this
3184 * fails with NFS if the server or some other client
3185 * extends the file's EOF. If our buffer is resized,
3186 * B_CACHE may remain set! XXX
3189 toff
= bp
->b_bcount
;
3190 tinc
= PAGE_SIZE
- ((bp
->b_loffset
+ toff
) & PAGE_MASK
);
3192 while ((bp
->b_flags
& B_CACHE
) && toff
< size
) {
3195 if (tinc
> (size
- toff
))
3198 pi
= ((bp
->b_loffset
& PAGE_MASK
) + toff
) >>
3206 bp
->b_xio
.xio_pages
[pi
]
3213 * Step 3, fixup the KVM pmap. Remember that
3214 * bp->b_data is relative to bp->b_loffset, but
3215 * bp->b_loffset may be offset into the first page.
3217 bp
->b_data
= (caddr_t
)trunc_page((vm_offset_t
)bp
->b_data
);
3218 pmap_qenter_noinval((vm_offset_t
)bp
->b_data
,
3219 bp
->b_xio
.xio_pages
, bp
->b_xio
.xio_npages
);
3220 bp
->b_data
= (caddr_t
)((vm_offset_t
)bp
->b_data
|
3221 (vm_offset_t
)(bp
->b_loffset
& PAGE_MASK
));
3224 atomic_add_long(&bufspace
, newbsize
- bp
->b_bufsize
);
3226 /* adjust space use on already-dirty buffer */
3227 if (bp
->b_flags
& B_DELWRI
) {
3228 /* dirtykvaspace unchanged */
3229 atomic_add_long(&dirtybufspace
, newbsize
- bp
->b_bufsize
);
3230 if (bp
->b_flags
& B_HEAVY
) {
3231 atomic_add_long(&dirtybufspacehw
,
3232 newbsize
- bp
->b_bufsize
);
3235 bp
->b_bufsize
= newbsize
; /* actual buffer allocation */
3236 bp
->b_bcount
= size
; /* requested buffer size */
3243 * Wait for buffer I/O completion, returning error status. B_EINTR
3244 * is converted into an EINTR error but not cleared (since a chain
3245 * of biowait() calls may occur).
3247 * On return bpdone() will have been called but the buffer will remain
3248 * locked and will not have been brelse()'d.
3250 * NOTE! If a timeout is specified and ETIMEDOUT occurs the I/O is
3251 * likely still in progress on return.
3253 * NOTE! This operation is on a BIO, not a BUF.
3255 * NOTE! BIO_DONE is cleared by vn_strategy()
3258 _biowait(struct bio
*bio
, const char *wmesg
, int to
)
3260 struct buf
*bp
= bio
->bio_buf
;
3265 KKASSERT(bio
== &bp
->b_bio1
);
3267 flags
= bio
->bio_flags
;
3268 if (flags
& BIO_DONE
)
3270 nflags
= flags
| BIO_WANT
;
3271 tsleep_interlock(bio
, 0);
3272 if (atomic_cmpset_int(&bio
->bio_flags
, flags
, nflags
)) {
3274 error
= tsleep(bio
, PINTERLOCKED
, wmesg
, to
);
3275 else if (bp
->b_cmd
== BUF_CMD_READ
)
3276 error
= tsleep(bio
, PINTERLOCKED
, "biord", to
);
3278 error
= tsleep(bio
, PINTERLOCKED
, "biowr", to
);
3280 kprintf("tsleep error biowait %d\n", error
);
3289 KKASSERT(bp
->b_cmd
== BUF_CMD_DONE
);
3290 bio
->bio_flags
&= ~(BIO_DONE
| BIO_SYNC
);
3291 if (bp
->b_flags
& B_EINTR
)
3293 if (bp
->b_flags
& B_ERROR
)
3294 return (bp
->b_error
? bp
->b_error
: EIO
);
3299 biowait(struct bio
*bio
, const char *wmesg
)
3301 return(_biowait(bio
, wmesg
, 0));
3305 biowait_timeout(struct bio
*bio
, const char *wmesg
, int to
)
3307 return(_biowait(bio
, wmesg
, to
));
3311 * This associates a tracking count with an I/O. vn_strategy() and
3312 * dev_dstrategy() do this automatically but there are a few cases
3313 * where a vnode or device layer is bypassed when a block translation
3314 * is cached. In such cases bio_start_transaction() may be called on
3315 * the bypassed layers so the system gets an I/O in progress indication
3316 * for those higher layers.
3319 bio_start_transaction(struct bio
*bio
, struct bio_track
*track
)
3321 bio
->bio_track
= track
;
3322 bio_track_ref(track
);
3323 dsched_buf_enter(bio
->bio_buf
); /* might stack */
3327 * Initiate I/O on a vnode.
3329 * SWAPCACHE OPERATION:
3331 * Real buffer cache buffers have a non-NULL bp->b_vp. Unfortunately
3332 * devfs also uses b_vp for fake buffers so we also have to check
3333 * that B_PAGING is 0. In this case the passed 'vp' is probably the
3334 * underlying block device. The swap assignments are related to the
3335 * buffer cache buffer's b_vp, not the passed vp.
3337 * The passed vp == bp->b_vp only in the case where the strategy call
3338 * is made on the vp itself for its own buffers (a regular file or
3339 * block device vp). The filesystem usually then re-calls vn_strategy()
3340 * after translating the request to an underlying device.
3342 * Cluster buffers set B_CLUSTER and the passed vp is the vp of the
3343 * underlying buffer cache buffers.
3345 * We can only deal with page-aligned buffers at the moment, because
3346 * we can't tell what the real dirty state for pages straddling a buffer
3349 * In order to call swap_pager_strategy() we must provide the VM object
3350 * and base offset for the underlying buffer cache pages so it can find
3354 vn_strategy(struct vnode
*vp
, struct bio
*bio
)
3356 struct bio_track
*track
;
3357 struct buf
*bp
= bio
->bio_buf
;
3359 KKASSERT(bp
->b_cmd
!= BUF_CMD_DONE
);
3362 * Set when an I/O is issued on the bp. Cleared by consumers
3363 * (aka HAMMER), allowing the consumer to determine if I/O had
3364 * actually occurred.
3366 bp
->b_flags
|= B_IOISSUED
;
3369 * Handle the swapcache intercept.
3371 * NOTE: The swapcache itself always supports KVABIO and will
3372 * do the right thing if its underlying devices do not.
3374 if (vn_cache_strategy(vp
, bio
))
3378 * If the vnode does not support KVABIO and the buffer is using
3379 * KVABIO, we must synchronize b_data to all cpus before dispatching.
3381 if ((vp
->v_flag
& VKVABIO
) == 0 && (bp
->b_flags
& B_KVABIO
))
3385 * Otherwise do the operation through the filesystem
3387 if (bp
->b_cmd
== BUF_CMD_READ
)
3388 track
= &vp
->v_track_read
;
3390 track
= &vp
->v_track_write
;
3391 KKASSERT((bio
->bio_flags
& BIO_DONE
) == 0);
3392 bio
->bio_track
= track
;
3393 bio_track_ref(track
);
3394 dsched_buf_enter(bp
); /* might stack */
3395 vop_strategy(*vp
->v_ops
, vp
, bio
);
3399 * vn_cache_strategy()
3401 * Returns 1 if the interrupt was successful, 0 if not.
3403 * NOTE: This function supports the KVABIO API wherein b_data might not
3404 * be synchronized to the current cpu.
3406 static void vn_cache_strategy_callback(struct bio
*bio
);
3409 vn_cache_strategy(struct vnode
*vp
, struct bio
*bio
)
3411 struct buf
*bp
= bio
->bio_buf
;
3418 * Stop using swapcache if paniced, dumping, or dumped
3420 if (panicstr
|| dumping
)
3424 * Is this buffer cache buffer suitable for reading from
3427 if (vm_swapcache_read_enable
== 0 ||
3428 bp
->b_cmd
!= BUF_CMD_READ
||
3429 ((bp
->b_flags
& B_CLUSTER
) == 0 &&
3430 (bp
->b_vp
== NULL
|| (bp
->b_flags
& B_PAGING
))) ||
3431 ((int)bp
->b_loffset
& PAGE_MASK
) != 0 ||
3432 (bp
->b_bcount
& PAGE_MASK
) != 0) {
3437 * Figure out the original VM object (it will match the underlying
3438 * VM pages). Note that swap cached data uses page indices relative
3439 * to that object, not relative to bio->bio_offset.
3441 if (bp
->b_flags
& B_CLUSTER
)
3442 object
= vp
->v_object
;
3444 object
= bp
->b_vp
->v_object
;
3447 * In order to be able to use the swap cache all underlying VM
3448 * pages must be marked as such, and we can't have any bogus pages.
3450 for (i
= 0; i
< bp
->b_xio
.xio_npages
; ++i
) {
3451 m
= bp
->b_xio
.xio_pages
[i
];
3452 if ((m
->flags
& PG_SWAPPED
) == 0)
3454 if (m
== bogus_page
)
3459 * If we are good then issue the I/O using swap_pager_strategy().
3461 * We can only do this if the buffer actually supports object-backed
3462 * I/O. If it doesn't npages will be 0.
3464 if (i
&& i
== bp
->b_xio
.xio_npages
) {
3465 m
= bp
->b_xio
.xio_pages
[0];
3466 nbio
= push_bio(bio
);
3467 nbio
->bio_done
= vn_cache_strategy_callback
;
3468 nbio
->bio_offset
= ptoa(m
->pindex
);
3469 KKASSERT(m
->object
== object
);
3470 swap_pager_strategy(object
, nbio
);
3477 * This is a bit of a hack but since the vn_cache_strategy() function can
3478 * override a VFS's strategy function we must make sure that the bio, which
3479 * is probably bio2, doesn't leak an unexpected offset value back to the
3480 * filesystem. The filesystem (e.g. UFS) might otherwise assume that the
3481 * bio went through its own file strategy function and the the bio2 offset
3482 * is a cached disk offset when, in fact, it isn't.
3485 vn_cache_strategy_callback(struct bio
*bio
)
3487 bio
->bio_offset
= NOOFFSET
;
3488 biodone(pop_bio(bio
));
3494 * Finish I/O on a buffer after all BIOs have been processed.
3495 * Called when the bio chain is exhausted or by biowait. If called
3496 * by biowait, elseit is typically 0.
3498 * bpdone is also responsible for setting B_CACHE in a B_VMIO bp.
3499 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3500 * assuming B_INVAL is clear.
3502 * For the VMIO case, we set B_CACHE if the op was a read and no
3503 * read error occured, or if the op was a write. B_CACHE is never
3504 * set if the buffer is invalid or otherwise uncacheable.
3506 * bpdone does not mess with B_INVAL, allowing the I/O routine or the
3507 * initiator to leave B_INVAL set to brelse the buffer out of existance
3508 * in the biodone routine.
3510 * bpdone is responsible for calling bundirty() on the buffer after a
3511 * successful write. We previously did this prior to initiating the
3512 * write under the assumption that the buffer might be dirtied again
3513 * while the write was in progress, however doing it before-hand creates
3514 * a race condition prior to the call to vn_strategy() where the
3515 * filesystem may not be aware that a dirty buffer is present.
3516 * It should not be possible for the buffer or its underlying pages to
3517 * be redirtied prior to bpdone()'s unbusying of the underlying VM
3521 bpdone(struct buf
*bp
, int elseit
)
3525 KASSERT(BUF_LOCKINUSE(bp
), ("bpdone: bp %p not busy", bp
));
3526 KASSERT(bp
->b_cmd
!= BUF_CMD_DONE
,
3527 ("bpdone: bp %p already done!", bp
));
3530 * No more BIOs are left. All completion functions have been dealt
3531 * with, now we clean up the buffer.
3534 bp
->b_cmd
= BUF_CMD_DONE
;
3537 * Only reads and writes are processed past this point.
3539 if (cmd
!= BUF_CMD_READ
&& cmd
!= BUF_CMD_WRITE
) {
3540 if (cmd
== BUF_CMD_FREEBLKS
)
3541 bp
->b_flags
|= B_NOCACHE
;
3548 * A failed write must re-dirty the buffer unless B_INVAL
3551 * A successful write must clear the dirty flag. This is done after
3552 * the write to ensure that the buffer remains on the vnode's dirty
3553 * list for filesystem interlocks / checks until the write is actually
3554 * complete. HAMMER2 is sensitive to this issue.
3556 * Only applicable to normal buffers (with VPs). vinum buffers may
3559 * Must be done prior to calling buf_complete() as the callback might
3560 * re-dirty the buffer.
3562 if (cmd
== BUF_CMD_WRITE
) {
3563 if ((bp
->b_flags
& (B_ERROR
| B_INVAL
)) == B_ERROR
) {
3564 bp
->b_flags
&= ~B_NOCACHE
;
3574 * Warning: softupdates may re-dirty the buffer, and HAMMER can do
3575 * a lot worse. XXX - move this above the clearing of b_cmd
3577 if (LIST_FIRST(&bp
->b_dep
) != NULL
)
3580 if (bp
->b_flags
& B_VMIO
) {
3586 struct vnode
*vp
= bp
->b_vp
;
3590 #if defined(VFS_BIO_DEBUG)
3591 if (vp
->v_auxrefs
== 0)
3592 panic("bpdone: zero vnode hold count");
3593 if ((vp
->v_flag
& VOBJBUF
) == 0)
3594 panic("bpdone: vnode is not setup for merged cache");
3597 foff
= bp
->b_loffset
;
3598 KASSERT(foff
!= NOOFFSET
, ("bpdone: no buffer offset"));
3599 KASSERT(obj
!= NULL
, ("bpdone: missing VM object"));
3601 #if defined(VFS_BIO_DEBUG)
3602 if (obj
->paging_in_progress
< bp
->b_xio
.xio_npages
) {
3603 kprintf("bpdone: paging in progress(%d) < "
3604 "bp->b_xio.xio_npages(%d)\n",
3605 obj
->paging_in_progress
,
3606 bp
->b_xio
.xio_npages
);
3611 * Set B_CACHE if the op was a normal read and no error
3612 * occured. B_CACHE is set for writes in the b*write()
3615 iosize
= bp
->b_bcount
- bp
->b_resid
;
3616 if (cmd
== BUF_CMD_READ
&&
3617 (bp
->b_flags
& (B_INVAL
|B_NOCACHE
|B_ERROR
)) == 0) {
3618 bp
->b_flags
|= B_CACHE
;
3621 vm_object_hold(obj
);
3622 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3626 resid
= ((foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
) - foff
;
3631 * cleanup bogus pages, restoring the originals. Since
3632 * the originals should still be wired, we don't have
3633 * to worry about interrupt/freeing races destroying
3634 * the VM object association.
3636 m
= bp
->b_xio
.xio_pages
[i
];
3637 if (m
== bogus_page
) {
3638 if ((bp
->b_flags
& B_HASBOGUS
) == 0)
3639 panic("bpdone: bp %p corrupt bogus", bp
);
3640 m
= vm_page_lookup(obj
, OFF_TO_IDX(foff
));
3642 panic("bpdone: page disappeared");
3643 bp
->b_xio
.xio_pages
[i
] = m
;
3648 #if defined(VFS_BIO_DEBUG)
3649 if (OFF_TO_IDX(foff
) != m
->pindex
) {
3650 kprintf("bpdone: foff(%lu)/m->pindex(%ld) "
3652 (unsigned long)foff
, (long)m
->pindex
);
3657 * In the write case, the valid and clean bits are
3658 * already changed correctly (see bdwrite()), so we
3659 * only need to do this here in the read case.
3661 vm_page_busy_wait(m
, FALSE
, "bpdpgw");
3662 if (cmd
== BUF_CMD_READ
&& isbogus
== 0 && resid
> 0)
3663 vfs_clean_one_page(bp
, i
, m
);
3666 * when debugging new filesystems or buffer I/O
3667 * methods, this is the most common error that pops
3668 * up. if you see this, you have not set the page
3669 * busy flag correctly!!!
3671 if ((m
->busy_count
& PBUSY_MASK
) == 0) {
3672 kprintf("bpdone: page busy < 0, "
3673 "pindex: %d, foff: 0x(%x,%x), "
3674 "resid: %d, index: %d\n",
3675 (int) m
->pindex
, (int)(foff
>> 32),
3676 (int) foff
& 0xffffffff, resid
, i
);
3677 if (!vn_isdisk(vp
, NULL
))
3678 kprintf(" iosize: %ld, loffset: %lld, "
3679 "flags: 0x%08x, npages: %d\n",
3680 bp
->b_vp
->v_mount
->mnt_stat
.f_iosize
,
3681 (long long)bp
->b_loffset
,
3682 bp
->b_flags
, bp
->b_xio
.xio_npages
);
3684 kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
3685 (long long)bp
->b_loffset
,
3686 bp
->b_flags
, bp
->b_xio
.xio_npages
);
3687 kprintf(" valid: 0x%x, dirty: 0x%x, "
3691 panic("bpdone: page busy < 0");
3693 vm_page_io_finish(m
);
3695 vm_object_pip_wakeup(obj
);
3696 foff
= (foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
;
3699 if (bp
->b_flags
& B_HASBOGUS
) {
3700 pmap_qenter_noinval(trunc_page((vm_offset_t
)bp
->b_data
),
3701 bp
->b_xio
.xio_pages
,
3702 bp
->b_xio
.xio_npages
);
3703 bp
->b_flags
&= ~B_HASBOGUS
;
3706 vm_object_drop(obj
);
3710 * Finish up by releasing the buffer. There are no more synchronous
3711 * or asynchronous completions, those were handled by bio_done
3715 if (bp
->b_flags
& (B_NOCACHE
|B_INVAL
|B_ERROR
|B_RELBUF
))
3726 biodone(struct bio
*bio
)
3728 struct buf
*bp
= bio
->bio_buf
;
3730 runningbufwakeup(bp
);
3733 * Run up the chain of BIO's. Leave b_cmd intact for the duration.
3736 biodone_t
*done_func
;
3737 struct bio_track
*track
;
3740 * BIO tracking. Most but not all BIOs are tracked.
3742 if ((track
= bio
->bio_track
) != NULL
) {
3743 bio_track_rel(track
);
3744 bio
->bio_track
= NULL
;
3748 * A bio_done function terminates the loop. The function
3749 * will be responsible for any further chaining and/or
3750 * buffer management.
3752 * WARNING! The done function can deallocate the buffer!
3754 if ((done_func
= bio
->bio_done
) != NULL
) {
3755 bio
->bio_done
= NULL
;
3759 bio
= bio
->bio_prev
;
3763 * If we've run out of bio's do normal [a]synchronous completion.
3769 * Synchronous biodone - this terminates a synchronous BIO.
3771 * bpdone() is called with elseit=FALSE, leaving the buffer completed
3772 * but still locked. The caller must brelse() the buffer after waiting
3776 biodone_sync(struct bio
*bio
)
3778 struct buf
*bp
= bio
->bio_buf
;
3782 KKASSERT(bio
== &bp
->b_bio1
);
3786 flags
= bio
->bio_flags
;
3787 nflags
= (flags
| BIO_DONE
) & ~BIO_WANT
;
3789 if (atomic_cmpset_int(&bio
->bio_flags
, flags
, nflags
)) {
3790 if (flags
& BIO_WANT
)
3800 * This routine is called in lieu of iodone in the case of
3801 * incomplete I/O. This keeps the busy status for pages
3805 vfs_unbusy_pages(struct buf
*bp
)
3809 runningbufwakeup(bp
);
3811 if (bp
->b_flags
& B_VMIO
) {
3812 struct vnode
*vp
= bp
->b_vp
;
3816 vm_object_hold(obj
);
3818 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3819 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
3822 * When restoring bogus changes the original pages
3823 * should still be wired, so we are in no danger of
3824 * losing the object association and do not need
3825 * critical section protection particularly.
3827 if (m
== bogus_page
) {
3828 m
= vm_page_lookup(obj
, OFF_TO_IDX(bp
->b_loffset
) + i
);
3830 panic("vfs_unbusy_pages: page missing");
3832 bp
->b_xio
.xio_pages
[i
] = m
;
3834 vm_page_busy_wait(m
, FALSE
, "bpdpgw");
3835 vm_page_io_finish(m
);
3837 vm_object_pip_wakeup(obj
);
3839 if (bp
->b_flags
& B_HASBOGUS
) {
3840 pmap_qenter_noinval(trunc_page((vm_offset_t
)bp
->b_data
),
3841 bp
->b_xio
.xio_pages
,
3842 bp
->b_xio
.xio_npages
);
3843 bp
->b_flags
&= ~B_HASBOGUS
;
3846 vm_object_drop(obj
);
3853 * This routine is called before a device strategy routine.
3854 * It is used to tell the VM system that paging I/O is in
3855 * progress, and treat the pages associated with the buffer
3856 * almost as being PBUSY_LOCKED. Also the object 'paging_in_progress'
3857 * flag is handled to make sure that the object doesn't become
3860 * Since I/O has not been initiated yet, certain buffer flags
3861 * such as B_ERROR or B_INVAL may be in an inconsistant state
3862 * and should be ignored.
3865 vfs_busy_pages(struct vnode
*vp
, struct buf
*bp
)
3868 struct lwp
*lp
= curthread
->td_lwp
;
3871 * The buffer's I/O command must already be set. If reading,
3872 * B_CACHE must be 0 (double check against callers only doing
3873 * I/O when B_CACHE is 0).
3875 KKASSERT(bp
->b_cmd
!= BUF_CMD_DONE
);
3876 KKASSERT(bp
->b_cmd
== BUF_CMD_WRITE
|| (bp
->b_flags
& B_CACHE
) == 0);
3878 if (bp
->b_flags
& B_VMIO
) {
3882 KASSERT(bp
->b_loffset
!= NOOFFSET
,
3883 ("vfs_busy_pages: no buffer offset"));
3886 * Busy all the pages. We have to busy them all at once
3887 * to avoid deadlocks.
3890 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3891 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
3893 if (vm_page_busy_try(m
, FALSE
)) {
3894 vm_page_sleep_busy(m
, FALSE
, "vbpage");
3896 vm_page_wakeup(bp
->b_xio
.xio_pages
[i
]);
3902 * Setup for I/O, soft-busy the page right now because
3903 * the next loop may block.
3905 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3906 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
3908 if ((bp
->b_flags
& B_CLUSTER
) == 0) {
3909 vm_object_pip_add(obj
, 1);
3910 vm_page_io_start(m
);
3915 * Adjust protections for I/O and do bogus-page mapping.
3916 * Assume that vm_page_protect() can block (it can block
3917 * if VM_PROT_NONE, don't take any chances regardless).
3919 * In particular note that for writes we must incorporate
3920 * page dirtyness from the VM system into the buffer's
3923 * For reads we theoretically must incorporate page dirtyness
3924 * from the VM system to determine if the page needs bogus
3925 * replacement, but we shortcut the test by simply checking
3926 * that all m->valid bits are set, indicating that the page
3927 * is fully valid and does not need to be re-read. For any
3928 * VM system dirtyness the page will also be fully valid
3929 * since it was mapped at one point.
3932 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3933 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
3935 if (bp
->b_cmd
== BUF_CMD_WRITE
) {
3937 * When readying a vnode-backed buffer for
3938 * a write we must zero-fill any invalid
3939 * portions of the backing VM pages, mark
3940 * it valid and clear related dirty bits.
3942 * vfs_clean_one_page() incorporates any
3943 * VM dirtyness and updates the b_dirtyoff
3944 * range (after we've made the page RO).
3946 * It is also expected that the pmap modified
3947 * bit has already been cleared by the
3948 * vm_page_protect(). We may not be able
3949 * to clear all dirty bits for a page if it
3950 * was also memory mapped (NFS).
3952 * Finally be sure to unassign any swap-cache
3953 * backing store as it is now stale.
3955 vm_page_protect(m
, VM_PROT_READ
);
3956 vfs_clean_one_page(bp
, i
, m
);
3957 swap_pager_unswapped(m
);
3958 } else if (m
->valid
== VM_PAGE_BITS_ALL
) {
3960 * When readying a vnode-backed buffer for
3961 * read we must replace any dirty pages with
3962 * a bogus page so dirty data is not destroyed
3963 * when filling gaps.
3965 * To avoid testing whether the page is
3966 * dirty we instead test that the page was
3967 * at some point mapped (m->valid fully
3968 * valid) with the understanding that
3969 * this also covers the dirty case.
3971 bp
->b_xio
.xio_pages
[i
] = bogus_page
;
3972 bp
->b_flags
|= B_HASBOGUS
;
3974 } else if (m
->valid
& m
->dirty
) {
3976 * This case should not occur as partial
3977 * dirtyment can only happen if the buffer
3978 * is B_CACHE, and this code is not entered
3979 * if the buffer is B_CACHE.
3981 kprintf("Warning: vfs_busy_pages - page not "
3982 "fully valid! loff=%jx bpf=%08x "
3983 "idx=%d val=%02x dir=%02x\n",
3984 (uintmax_t)bp
->b_loffset
, bp
->b_flags
,
3985 i
, m
->valid
, m
->dirty
);
3986 vm_page_protect(m
, VM_PROT_NONE
);
3989 * The page is not valid and can be made
3992 vm_page_protect(m
, VM_PROT_NONE
);
3997 pmap_qenter_noinval(trunc_page((vm_offset_t
)bp
->b_data
),
3998 bp
->b_xio
.xio_pages
,
3999 bp
->b_xio
.xio_npages
);
4005 * This is the easiest place to put the process accounting for the I/O
4009 if (bp
->b_cmd
== BUF_CMD_READ
)
4010 lp
->lwp_ru
.ru_inblock
++;
4012 lp
->lwp_ru
.ru_oublock
++;
4017 * Tell the VM system that the pages associated with this buffer
4018 * are clean. This is used for delayed writes where the data is
4019 * going to go to disk eventually without additional VM intevention.
4021 * NOTE: While we only really need to clean through to b_bcount, we
4022 * just go ahead and clean through to b_bufsize.
4025 vfs_clean_pages(struct buf
*bp
)
4030 if ((bp
->b_flags
& B_VMIO
) == 0)
4033 KASSERT(bp
->b_loffset
!= NOOFFSET
,
4034 ("vfs_clean_pages: no buffer offset"));
4036 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
4037 m
= bp
->b_xio
.xio_pages
[i
];
4038 vfs_clean_one_page(bp
, i
, m
);
4043 * vfs_clean_one_page:
4045 * Set the valid bits and clear the dirty bits in a page within a
4046 * buffer. The range is restricted to the buffer's size and the
4047 * buffer's logical offset might index into the first page.
4049 * The caller has busied or soft-busied the page and it is not mapped,
4050 * test and incorporate the dirty bits into b_dirtyoff/end before
4051 * clearing them. Note that we need to clear the pmap modified bits
4052 * after determining the the page was dirty, vm_page_set_validclean()
4053 * does not do it for us.
4055 * This routine is typically called after a read completes (dirty should
4056 * be zero in that case as we are not called on bogus-replace pages),
4057 * or before a write is initiated.
4060 vfs_clean_one_page(struct buf
*bp
, int pageno
, vm_page_t m
)
4068 * Calculate offset range within the page but relative to buffer's
4069 * loffset. loffset might be offset into the first page.
4071 xoff
= (int)bp
->b_loffset
& PAGE_MASK
; /* loffset offset into pg 0 */
4072 bcount
= bp
->b_bcount
+ xoff
; /* offset adjusted */
4078 soff
= (pageno
<< PAGE_SHIFT
);
4079 eoff
= soff
+ PAGE_SIZE
;
4087 * Test dirty bits and adjust b_dirtyoff/end.
4089 * If dirty pages are incorporated into the bp any prior
4090 * B_NEEDCOMMIT state (NFS) must be cleared because the
4091 * caller has not taken into account the new dirty data.
4093 * If the page was memory mapped the dirty bits might go beyond the
4094 * end of the buffer, but we can't really make the assumption that
4095 * a file EOF straddles the buffer (even though this is the case for
4096 * NFS if B_NEEDCOMMIT is also set). So for the purposes of clearing
4097 * B_NEEDCOMMIT we only test the dirty bits covered by the buffer.
4098 * This also saves some console spam.
4100 * When clearing B_NEEDCOMMIT we must also clear B_CLUSTEROK,
4101 * NFS can handle huge commits but not huge writes.
4103 vm_page_test_dirty(m
);
4105 if ((bp
->b_flags
& B_NEEDCOMMIT
) &&
4106 (m
->dirty
& vm_page_bits(soff
& PAGE_MASK
, eoff
- soff
))) {
4108 kprintf("Warning: vfs_clean_one_page: bp %p "
4109 "loff=%jx,%d flgs=%08x clr B_NEEDCOMMIT"
4110 " cmd %d vd %02x/%02x x/s/e %d %d %d "
4112 bp
, (uintmax_t)bp
->b_loffset
, bp
->b_bcount
,
4113 bp
->b_flags
, bp
->b_cmd
,
4114 m
->valid
, m
->dirty
, xoff
, soff
, eoff
,
4115 bp
->b_dirtyoff
, bp
->b_dirtyend
);
4116 bp
->b_flags
&= ~(B_NEEDCOMMIT
| B_CLUSTEROK
);
4118 print_backtrace(-1);
4121 * Only clear the pmap modified bits if ALL the dirty bits
4122 * are set, otherwise the system might mis-clear portions
4125 if (m
->dirty
== VM_PAGE_BITS_ALL
&&
4126 (bp
->b_flags
& B_NEEDCOMMIT
) == 0) {
4127 pmap_clear_modify(m
);
4129 if (bp
->b_dirtyoff
> soff
- xoff
)
4130 bp
->b_dirtyoff
= soff
- xoff
;
4131 if (bp
->b_dirtyend
< eoff
- xoff
)
4132 bp
->b_dirtyend
= eoff
- xoff
;
4136 * Set related valid bits, clear related dirty bits.
4137 * Does not mess with the pmap modified bit.
4139 * WARNING! We cannot just clear all of m->dirty here as the
4140 * buffer cache buffers may use a DEV_BSIZE'd aligned
4141 * block size, or have an odd size (e.g. NFS at file EOF).
4142 * The putpages code can clear m->dirty to 0.
4144 * If a VOP_WRITE generates a buffer cache buffer which
4145 * covers the same space as mapped writable pages the
4146 * buffer flush might not be able to clear all the dirty
4147 * bits and still require a putpages from the VM system
4150 * WARNING! vm_page_set_validclean() currently assumes vm_token
4151 * is held. The page might not be busied (bdwrite() case).
4152 * XXX remove this comment once we've validated that this
4153 * is no longer an issue.
4155 vm_page_set_validclean(m
, soff
& PAGE_MASK
, eoff
- soff
);
4160 * Similar to vfs_clean_one_page() but sets the bits to valid and dirty.
4161 * The page data is assumed to be valid (there is no zeroing here).
4164 vfs_dirty_one_page(struct buf
*bp
, int pageno
, vm_page_t m
)
4172 * Calculate offset range within the page but relative to buffer's
4173 * loffset. loffset might be offset into the first page.
4175 xoff
= (int)bp
->b_loffset
& PAGE_MASK
; /* loffset offset into pg 0 */
4176 bcount
= bp
->b_bcount
+ xoff
; /* offset adjusted */
4182 soff
= (pageno
<< PAGE_SHIFT
);
4183 eoff
= soff
+ PAGE_SIZE
;
4189 vm_page_set_validdirty(m
, soff
& PAGE_MASK
, eoff
- soff
);
4196 * Clear a buffer. This routine essentially fakes an I/O, so we need
4197 * to clear B_ERROR and B_INVAL.
4199 * Note that while we only theoretically need to clear through b_bcount,
4200 * we go ahead and clear through b_bufsize.
4203 vfs_bio_clrbuf(struct buf
*bp
)
4207 KKASSERT(bp
->b_flags
& B_VMIO
);
4209 bp
->b_flags
&= ~(B_INVAL
| B_EINTR
| B_ERROR
);
4212 if ((bp
->b_xio
.xio_npages
== 1) && (bp
->b_bufsize
< PAGE_SIZE
) &&
4213 (bp
->b_loffset
& PAGE_MASK
) == 0) {
4214 mask
= (1 << (bp
->b_bufsize
/ DEV_BSIZE
)) - 1;
4215 if ((bp
->b_xio
.xio_pages
[0]->valid
& mask
) == mask
) {
4219 if ((bp
->b_xio
.xio_pages
[0]->valid
& mask
) == 0) {
4220 bzero(bp
->b_data
, bp
->b_bufsize
);
4221 bp
->b_xio
.xio_pages
[0]->valid
|= mask
;
4227 for(i
= 0; i
< bp
->b_xio
.xio_npages
; i
++, sa
=ea
) {
4228 int j
= ((vm_offset_t
)sa
& PAGE_MASK
) / DEV_BSIZE
;
4229 ea
= (caddr_t
)trunc_page((vm_offset_t
)sa
+ PAGE_SIZE
);
4230 ea
= (caddr_t
)(vm_offset_t
)ulmin(
4231 (u_long
)(vm_offset_t
)ea
,
4232 (u_long
)(vm_offset_t
)bp
->b_data
+ bp
->b_bufsize
);
4233 mask
= ((1 << ((ea
- sa
) / DEV_BSIZE
)) - 1) << j
;
4234 if ((bp
->b_xio
.xio_pages
[i
]->valid
& mask
) == mask
)
4236 if ((bp
->b_xio
.xio_pages
[i
]->valid
& mask
) == 0) {
4239 for (; sa
< ea
; sa
+= DEV_BSIZE
, j
++) {
4240 if ((bp
->b_xio
.xio_pages
[i
]->valid
&
4242 bzero(sa
, DEV_BSIZE
);
4246 bp
->b_xio
.xio_pages
[i
]->valid
|= mask
;
4252 * Allocate a page for a buffer cache buffer.
4254 * If NULL is returned the caller is expected to retry (typically check if
4255 * the page already exists on retry before trying to allocate one).
4257 * NOTE! Low-memory handling is dealt with in b[q]relse(), not here. This
4258 * function will use the system reserve with the hope that the page
4259 * allocations can be returned to PQ_CACHE/PQ_FREE when the caller
4260 * is done with the buffer.
4262 * NOTE! However, TMPFS is a special case because flushing a dirty buffer
4263 * to TMPFS doesn't clean the page. For TMPFS, only the pagedaemon
4264 * is capable of retiring pages (to swap). For TMPFS we don't dig
4265 * into the system reserve because doing so could stall out pretty
4266 * much every process running on the system.
4270 bio_page_alloc(struct buf
*bp
, vm_object_t obj
, vm_pindex_t pg
, int deficit
)
4272 int vmflags
= VM_ALLOC_NORMAL
| VM_ALLOC_NULL_OK
;
4275 ASSERT_LWKT_TOKEN_HELD(vm_object_token(obj
));
4278 * Try a normal allocation first.
4280 p
= vm_page_alloc(obj
, pg
, vmflags
);
4283 if (vm_page_lookup(obj
, pg
))
4285 vm_pageout_deficit
+= deficit
;
4288 * Try again, digging into the system reserve.
4290 * Trying to recover pages from the buffer cache here can deadlock
4291 * against other threads trying to busy underlying pages so we
4292 * depend on the code in brelse() and bqrelse() to free/cache the
4293 * underlying buffer cache pages when memory is low.
4295 if (curthread
->td_flags
& TDF_SYSTHREAD
)
4296 vmflags
|= VM_ALLOC_SYSTEM
| VM_ALLOC_INTERRUPT
;
4297 else if (bp
->b_vp
&& bp
->b_vp
->v_tag
== VT_TMPFS
)
4300 vmflags
|= VM_ALLOC_SYSTEM
;
4302 /*recoverbufpages();*/
4303 p
= vm_page_alloc(obj
, pg
, vmflags
);
4306 if (vm_page_lookup(obj
, pg
))
4310 * Wait for memory to free up and try again
4312 if (vm_page_count_severe())
4314 vm_wait(hz
/ 20 + 1);
4316 p
= vm_page_alloc(obj
, pg
, vmflags
);
4319 if (vm_page_lookup(obj
, pg
))
4323 * Ok, now we are really in trouble.
4326 static struct krate biokrate
= { .freq
= 1 };
4327 krateprintf(&biokrate
,
4328 "Warning: bio_page_alloc: memory exhausted "
4329 "during buffer cache page allocation from %s\n",
4330 curthread
->td_comm
);
4332 if (curthread
->td_flags
& TDF_SYSTHREAD
)
4333 vm_wait(hz
/ 20 + 1);
4335 vm_wait(hz
/ 2 + 1);
4340 * The buffer's mapping has changed. Adjust the buffer's memory
4341 * synchronization. The caller is the exclusive holder of the buffer
4342 * and has set or cleared B_KVABIO according to preference.
4344 * WARNING! If the caller is using B_KVABIO mode, this function will
4345 * not map the data to the current cpu. The caller must also
4346 * call bkvasync(bp).
4349 bkvareset(struct buf
*bp
)
4351 if (bp
->b_flags
& B_KVABIO
) {
4352 CPUMASK_ASSZERO(bp
->b_cpumask
);
4354 CPUMASK_ORMASK(bp
->b_cpumask
, smp_active_mask
);
4361 * The buffer will be used by the caller on the caller's cpu, synchronize
4362 * its data to the current cpu. Caller must control the buffer by holding
4363 * its lock, but calling cpu does not necessarily have to be the owner of
4364 * the lock (i.e. HAMMER2's concurrent I/O accessors).
4366 * If B_KVABIO is not set, the buffer is already fully synchronized.
4369 bkvasync(struct buf
*bp
)
4371 int cpuid
= mycpu
->gd_cpuid
;
4374 if ((bp
->b_flags
& B_KVABIO
) &&
4375 CPUMASK_TESTBIT(bp
->b_cpumask
, cpuid
) == 0) {
4377 while (bdata
< bp
->b_data
+ bp
->b_bufsize
) {
4379 bdata
+= PAGE_SIZE
-
4380 ((intptr_t)bdata
& PAGE_MASK
);
4382 ATOMIC_CPUMASK_ORBIT(bp
->b_cpumask
, cpuid
);
4387 * The buffer will be used by a subsystem that does not understand
4388 * the KVABIO API. Make sure its data is synchronized to all cpus.
4390 * If B_KVABIO is not set, the buffer is already fully synchronized.
4392 * NOTE! This is the only safe way to clear B_KVABIO on a buffer.
4395 bkvasync_all(struct buf
*bp
)
4397 if (debug_kvabio
> 0) {
4399 print_backtrace(10);
4402 if ((bp
->b_flags
& B_KVABIO
) &&
4403 CPUMASK_CMPMASKNEQ(bp
->b_cpumask
, smp_active_mask
)) {
4406 ATOMIC_CPUMASK_ORMASK(bp
->b_cpumask
, smp_active_mask
);
4408 bp
->b_flags
&= ~B_KVABIO
;
4412 * Scan all buffers in the system and issue the callback.
4415 scan_all_buffers(int (*callback
)(struct buf
*, void *), void *info
)
4421 for (n
= 0; n
< nbuf
; ++n
) {
4422 if ((error
= callback(&buf
[n
], info
)) < 0) {
4432 * nestiobuf_iodone: biodone callback for nested buffers and propagate
4433 * completion to the master buffer.
4436 nestiobuf_iodone(struct bio
*bio
)
4439 struct buf
*mbp
, *bp
;
4440 struct devstat
*stats
;
4445 mbio
= bio
->bio_caller_info1
.ptr
;
4446 stats
= bio
->bio_caller_info2
.ptr
;
4447 mbp
= mbio
->bio_buf
;
4449 KKASSERT(bp
->b_bcount
<= bp
->b_bufsize
);
4450 KKASSERT(mbp
!= bp
);
4452 error
= bp
->b_error
;
4453 if (bp
->b_error
== 0 &&
4454 (bp
->b_bcount
< bp
->b_bufsize
|| bp
->b_resid
> 0)) {
4456 * Not all got transfered, raise an error. We have no way to
4457 * propagate these conditions to mbp.
4462 donebytes
= bp
->b_bufsize
;
4466 nestiobuf_done(mbio
, donebytes
, error
, stats
);
4470 nestiobuf_done(struct bio
*mbio
, int donebytes
, int error
, struct devstat
*stats
)
4474 mbp
= mbio
->bio_buf
;
4476 KKASSERT((int)(intptr_t)mbio
->bio_driver_info
> 0);
4479 * If an error occured, propagate it to the master buffer.
4481 * Several biodone()s may wind up running concurrently so
4482 * use an atomic op to adjust b_flags.
4485 mbp
->b_error
= error
;
4486 atomic_set_int(&mbp
->b_flags
, B_ERROR
);
4490 * Decrement the operations in progress counter and terminate the
4491 * I/O if this was the last bit.
4493 if (atomic_fetchadd_int((int *)&mbio
->bio_driver_info
, -1) == 1) {
4496 devstat_end_transaction_buf(stats
, mbp
);
4502 * Initialize a nestiobuf for use. Set an initial count of 1 to prevent
4503 * the mbio from being biodone()'d while we are still adding sub-bios to
4507 nestiobuf_init(struct bio
*bio
)
4509 bio
->bio_driver_info
= (void *)1;
4513 * The BIOs added to the nestedio have already been started, remove the
4514 * count that placeheld our mbio and biodone() it if the count would
4518 nestiobuf_start(struct bio
*mbio
)
4520 struct buf
*mbp
= mbio
->bio_buf
;
4523 * Decrement the operations in progress counter and terminate the
4524 * I/O if this was the last bit.
4526 if (atomic_fetchadd_int((int *)&mbio
->bio_driver_info
, -1) == 1) {
4527 if (mbp
->b_flags
& B_ERROR
)
4528 mbp
->b_resid
= mbp
->b_bcount
;
4536 * Set an intermediate error prior to calling nestiobuf_start()
4539 nestiobuf_error(struct bio
*mbio
, int error
)
4541 struct buf
*mbp
= mbio
->bio_buf
;
4544 mbp
->b_error
= error
;
4545 atomic_set_int(&mbp
->b_flags
, B_ERROR
);
4550 * nestiobuf_add: setup a "nested" buffer.
4552 * => 'mbp' is a "master" buffer which is being divided into sub pieces.
4553 * => 'bp' should be a buffer allocated by getiobuf.
4554 * => 'offset' is a byte offset in the master buffer.
4555 * => 'size' is a size in bytes of this nested buffer.
4558 nestiobuf_add(struct bio
*mbio
, struct buf
*bp
, int offset
, size_t size
, struct devstat
*stats
)
4560 struct buf
*mbp
= mbio
->bio_buf
;
4561 struct vnode
*vp
= mbp
->b_vp
;
4563 KKASSERT(mbp
->b_bcount
>= offset
+ size
);
4565 atomic_add_int((int *)&mbio
->bio_driver_info
, 1);
4567 /* kernel needs to own the lock for it to be released in biodone */
4570 bp
->b_cmd
= mbp
->b_cmd
;
4571 bp
->b_bio1
.bio_done
= nestiobuf_iodone
;
4572 bp
->b_data
= (char *)mbp
->b_data
+ offset
;
4573 bp
->b_resid
= bp
->b_bcount
= size
;
4574 bp
->b_bufsize
= bp
->b_bcount
;
4576 bp
->b_bio1
.bio_track
= NULL
;
4577 bp
->b_bio1
.bio_caller_info1
.ptr
= mbio
;
4578 bp
->b_bio1
.bio_caller_info2
.ptr
= stats
;
4583 DB_SHOW_COMMAND(buffer
, db_show_buffer
)
4586 struct buf
*bp
= (struct buf
*)addr
;
4589 db_printf("usage: show buffer <addr>\n");
4593 db_printf("b_flags = 0x%pb%i\n", PRINT_BUF_FLAGS
, bp
->b_flags
);
4594 db_printf("b_cmd = %d\n", bp
->b_cmd
);
4595 db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
4596 "b_resid = %d\n, b_data = %p, "
4597 "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
4598 bp
->b_error
, bp
->b_bufsize
, bp
->b_bcount
, bp
->b_resid
,
4600 (long long)bp
->b_bio2
.bio_offset
,
4601 (long long)(bp
->b_bio2
.bio_next
?
4602 bp
->b_bio2
.bio_next
->bio_offset
: (off_t
)-1));
4603 if (bp
->b_xio
.xio_npages
) {
4605 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
4606 bp
->b_xio
.xio_npages
);
4607 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
4609 m
= bp
->b_xio
.xio_pages
[i
];
4610 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m
->object
,
4611 (u_long
)m
->pindex
, (u_long
)VM_PAGE_TO_PHYS(m
));
4612 if ((i
+ 1) < bp
->b_xio
.xio_npages
)