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 <sys/mplock2.h>
64 #include <vm/vm_page2.h>
75 BQUEUE_NONE
, /* not on any queue */
76 BQUEUE_LOCKED
, /* locked buffers */
77 BQUEUE_CLEAN
, /* non-B_DELWRI buffers */
78 BQUEUE_DIRTY
, /* B_DELWRI buffers */
79 BQUEUE_DIRTY_HW
, /* B_DELWRI buffers - heavy weight */
80 BQUEUE_EMPTY
, /* empty buffer headers */
82 BUFFER_QUEUES
/* number of buffer queues */
85 typedef enum bufq_type bufq_type_t
;
87 #define BD_WAKE_SIZE 16384
88 #define BD_WAKE_MASK (BD_WAKE_SIZE - 1)
90 TAILQ_HEAD(bqueues
, buf
);
94 struct bqueues bufqueues
[BUFFER_QUEUES
];
97 struct bufpcpu bufpcpu
[MAXCPU
];
99 static MALLOC_DEFINE(M_BIOBUF
, "BIO buffer", "BIO buffer");
101 struct buf
*buf
; /* buffer header pool */
103 static void vfs_clean_pages(struct buf
*bp
);
104 static void vfs_clean_one_page(struct buf
*bp
, int pageno
, vm_page_t m
);
106 static void vfs_dirty_one_page(struct buf
*bp
, int pageno
, vm_page_t m
);
108 static void vfs_vmio_release(struct buf
*bp
);
109 static int flushbufqueues(struct buf
*marker
, bufq_type_t q
);
110 static void repurposebuf(struct buf
*bp
, int size
);
111 static vm_page_t
bio_page_alloc(struct buf
*bp
, vm_object_t obj
,
112 vm_pindex_t pg
, int deficit
);
114 static void bd_signal(long totalspace
);
115 static void buf_daemon(void);
116 static void buf_daemon_hw(void);
119 * bogus page -- for I/O to/from partially complete buffers
120 * this is a temporary solution to the problem, but it is not
121 * really that bad. it would be better to split the buffer
122 * for input in the case of buffers partially already in memory,
123 * but the code is intricate enough already.
125 vm_page_t bogus_page
;
128 * These are all static, but make the ones we export globals so we do
129 * not need to use compiler magic.
131 long bufspace
; /* atomic ops */
133 static long bufmallocspace
; /* atomic ops */
134 long maxbufmallocspace
, lobufspace
, hibufspace
;
135 static long lorunningspace
;
136 static long hirunningspace
;
137 static long dirtykvaspace
; /* atomic */
138 long dirtybufspace
; /* atomic (global for systat) */
139 static long dirtybufcount
; /* atomic */
140 static long dirtybufspacehw
; /* atomic */
141 static long dirtybufcounthw
; /* atomic */
142 static long runningbufspace
; /* atomic */
143 static long runningbufcount
; /* atomic */
144 static long repurposedspace
;
145 long lodirtybufspace
;
146 long hidirtybufspace
;
147 static int getnewbufcalls
;
148 static int recoverbufcalls
;
149 static int needsbuffer
; /* atomic */
150 static int runningbufreq
; /* atomic */
151 static int bd_request
; /* atomic */
152 static int bd_request_hw
; /* atomic */
153 static u_int bd_wake_ary
[BD_WAKE_SIZE
];
154 static u_int bd_wake_index
;
155 static u_int vm_cycle_point
= 40; /* 23-36 will migrate more act->inact */
156 static int debug_commit
;
157 static int debug_bufbio
;
158 static long bufcache_bw
= 200 * 1024 * 1024;
159 static long bufcache_bw_accum
;
160 static int bufcache_bw_ticks
;
162 static struct thread
*bufdaemon_td
;
163 static struct thread
*bufdaemonhw_td
;
164 static u_int lowmempgallocs
;
165 static u_int lowmempgfails
;
166 static u_int flushperqueue
= 1024;
167 static int repurpose_enable
;
170 * Sysctls for operational control of the buffer cache.
172 SYSCTL_UINT(_vfs
, OID_AUTO
, flushperqueue
, CTLFLAG_RW
, &flushperqueue
, 0,
173 "Number of buffers to flush from each per-cpu queue");
174 SYSCTL_LONG(_vfs
, OID_AUTO
, lodirtybufspace
, CTLFLAG_RW
, &lodirtybufspace
, 0,
175 "Number of dirty buffers to flush before bufdaemon becomes inactive");
176 SYSCTL_LONG(_vfs
, OID_AUTO
, hidirtybufspace
, CTLFLAG_RW
, &hidirtybufspace
, 0,
177 "High watermark used to trigger explicit flushing of dirty buffers");
178 SYSCTL_LONG(_vfs
, OID_AUTO
, lorunningspace
, CTLFLAG_RW
, &lorunningspace
, 0,
179 "Minimum amount of buffer space required for active I/O");
180 SYSCTL_LONG(_vfs
, OID_AUTO
, hirunningspace
, CTLFLAG_RW
, &hirunningspace
, 0,
181 "Maximum amount of buffer space to usable for active I/O");
182 SYSCTL_LONG(_vfs
, OID_AUTO
, bufcache_bw
, CTLFLAG_RW
, &bufcache_bw
, 0,
183 "Buffer-cache -> VM page cache transfer bandwidth");
184 SYSCTL_UINT(_vfs
, OID_AUTO
, lowmempgallocs
, CTLFLAG_RW
, &lowmempgallocs
, 0,
185 "Page allocations done during periods of very low free memory");
186 SYSCTL_UINT(_vfs
, OID_AUTO
, lowmempgfails
, CTLFLAG_RW
, &lowmempgfails
, 0,
187 "Page allocations which failed during periods of very low free memory");
188 SYSCTL_UINT(_vfs
, OID_AUTO
, vm_cycle_point
, CTLFLAG_RW
, &vm_cycle_point
, 0,
189 "Recycle pages to active or inactive queue transition pt 0-64");
190 SYSCTL_UINT(_vfs
, OID_AUTO
, repurpose_enable
, CTLFLAG_RW
, &repurpose_enable
, 0,
191 "Enable buffer cache VM repurposing for high-I/O");
193 * Sysctls determining current state of the buffer cache.
195 SYSCTL_LONG(_vfs
, OID_AUTO
, nbuf
, CTLFLAG_RD
, &nbuf
, 0,
196 "Total number of buffers in buffer cache");
197 SYSCTL_LONG(_vfs
, OID_AUTO
, dirtykvaspace
, CTLFLAG_RD
, &dirtykvaspace
, 0,
198 "KVA reserved by dirty buffers (all)");
199 SYSCTL_LONG(_vfs
, OID_AUTO
, dirtybufspace
, CTLFLAG_RD
, &dirtybufspace
, 0,
200 "Pending bytes of dirty buffers (all)");
201 SYSCTL_LONG(_vfs
, OID_AUTO
, dirtybufspacehw
, CTLFLAG_RD
, &dirtybufspacehw
, 0,
202 "Pending bytes of dirty buffers (heavy weight)");
203 SYSCTL_LONG(_vfs
, OID_AUTO
, dirtybufcount
, CTLFLAG_RD
, &dirtybufcount
, 0,
204 "Pending number of dirty buffers");
205 SYSCTL_LONG(_vfs
, OID_AUTO
, dirtybufcounthw
, CTLFLAG_RD
, &dirtybufcounthw
, 0,
206 "Pending number of dirty buffers (heavy weight)");
207 SYSCTL_LONG(_vfs
, OID_AUTO
, runningbufspace
, CTLFLAG_RD
, &runningbufspace
, 0,
208 "I/O bytes currently in progress due to asynchronous writes");
209 SYSCTL_LONG(_vfs
, OID_AUTO
, runningbufcount
, CTLFLAG_RD
, &runningbufcount
, 0,
210 "I/O buffers currently in progress due to asynchronous writes");
211 SYSCTL_LONG(_vfs
, OID_AUTO
, repurposedspace
, CTLFLAG_RD
, &repurposedspace
, 0,
212 "Buffer-cache memory repurposed in-place");
213 SYSCTL_LONG(_vfs
, OID_AUTO
, maxbufspace
, CTLFLAG_RD
, &maxbufspace
, 0,
214 "Hard limit on maximum amount of memory usable for buffer space");
215 SYSCTL_LONG(_vfs
, OID_AUTO
, hibufspace
, CTLFLAG_RD
, &hibufspace
, 0,
216 "Soft limit on maximum amount of memory usable for buffer space");
217 SYSCTL_LONG(_vfs
, OID_AUTO
, lobufspace
, CTLFLAG_RD
, &lobufspace
, 0,
218 "Minimum amount of memory to reserve for system buffer space");
219 SYSCTL_LONG(_vfs
, OID_AUTO
, bufspace
, CTLFLAG_RD
, &bufspace
, 0,
220 "Amount of memory available for buffers");
221 SYSCTL_LONG(_vfs
, OID_AUTO
, maxmallocbufspace
, CTLFLAG_RD
, &maxbufmallocspace
,
222 0, "Maximum amount of memory reserved for buffers using malloc");
223 SYSCTL_LONG(_vfs
, OID_AUTO
, bufmallocspace
, CTLFLAG_RD
, &bufmallocspace
, 0,
224 "Amount of memory left for buffers using malloc-scheme");
225 SYSCTL_INT(_vfs
, OID_AUTO
, getnewbufcalls
, CTLFLAG_RD
, &getnewbufcalls
, 0,
226 "New buffer header acquisition requests");
227 SYSCTL_INT(_vfs
, OID_AUTO
, recoverbufcalls
, CTLFLAG_RD
, &recoverbufcalls
, 0,
228 "Recover VM space in an emergency");
229 SYSCTL_INT(_vfs
, OID_AUTO
, debug_commit
, CTLFLAG_RW
, &debug_commit
, 0, "");
230 SYSCTL_INT(_vfs
, OID_AUTO
, debug_bufbio
, CTLFLAG_RW
, &debug_bufbio
, 0, "");
231 SYSCTL_INT(_debug_sizeof
, OID_AUTO
, buf
, CTLFLAG_RD
, 0, sizeof(struct buf
),
232 "sizeof(struct buf)");
234 char *buf_wmesg
= BUF_WMESG
;
236 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
237 #define VFS_BIO_NEED_UNUSED02 0x02
238 #define VFS_BIO_NEED_UNUSED04 0x04
239 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
242 * Called when buffer space is potentially available for recovery.
243 * getnewbuf() will block on this flag when it is unable to free
244 * sufficient buffer space. Buffer space becomes recoverable when
245 * bp's get placed back in the queues.
251 * If someone is waiting for BUF space, wake them up. Even
252 * though we haven't freed the kva space yet, the waiting
253 * process will be able to now.
256 int flags
= needsbuffer
;
258 if ((flags
& VFS_BIO_NEED_BUFSPACE
) == 0)
260 if (atomic_cmpset_int(&needsbuffer
, flags
,
261 flags
& ~VFS_BIO_NEED_BUFSPACE
)) {
262 wakeup(&needsbuffer
);
272 * Accounting for I/O in progress.
276 runningbufwakeup(struct buf
*bp
)
281 if ((totalspace
= bp
->b_runningbufspace
) != 0) {
282 atomic_add_long(&runningbufspace
, -totalspace
);
283 atomic_add_long(&runningbufcount
, -1);
284 bp
->b_runningbufspace
= 0;
287 * see waitrunningbufspace() for limit test.
290 flags
= runningbufreq
;
294 if (atomic_cmpset_int(&runningbufreq
, flags
, 0)) {
295 wakeup(&runningbufreq
);
300 bd_signal(totalspace
);
307 * Called when a buffer has been added to one of the free queues to
308 * account for the buffer and to wakeup anyone waiting for free buffers.
309 * This typically occurs when large amounts of metadata are being handled
310 * by the buffer cache ( else buffer space runs out first, usually ).
321 if (atomic_cmpset_int(&needsbuffer
, flags
,
322 (flags
& ~VFS_BIO_NEED_ANY
))) {
323 wakeup(&needsbuffer
);
331 * waitrunningbufspace()
333 * If runningbufspace exceeds 4/6 hirunningspace we block until
334 * runningbufspace drops to 3/6 hirunningspace. We also block if another
335 * thread blocked here in order to be fair, even if runningbufspace
336 * is now lower than the limit.
338 * The caller may be using this function to block in a tight loop, we
339 * must block while runningbufspace is greater than at least
340 * hirunningspace * 3 / 6.
343 waitrunningbufspace(void)
345 long limit
= hirunningspace
* 4 / 6;
348 while (runningbufspace
> limit
|| runningbufreq
) {
349 tsleep_interlock(&runningbufreq
, 0);
350 flags
= atomic_fetchadd_int(&runningbufreq
, 1);
351 if (runningbufspace
> limit
|| flags
)
352 tsleep(&runningbufreq
, PINTERLOCKED
, "wdrn1", hz
);
357 * buf_dirty_count_severe:
359 * Return true if we have too many dirty buffers.
362 buf_dirty_count_severe(void)
364 return (runningbufspace
+ dirtykvaspace
>= hidirtybufspace
||
365 dirtybufcount
>= nbuf
/ 2);
369 * Return true if the amount of running I/O is severe and BIOQ should
373 buf_runningbufspace_severe(void)
375 return (runningbufspace
>= hirunningspace
* 4 / 6);
379 * vfs_buf_test_cache:
381 * Called when a buffer is extended. This function clears the B_CACHE
382 * bit if the newly extended portion of the buffer does not contain
385 * NOTE! Dirty VM pages are not processed into dirty (B_DELWRI) buffer
386 * cache buffers. The VM pages remain dirty, as someone had mmap()'d
387 * them while a clean buffer was present.
391 vfs_buf_test_cache(struct buf
*bp
,
392 vm_ooffset_t foff
, vm_offset_t off
, vm_offset_t size
,
395 if (bp
->b_flags
& B_CACHE
) {
396 int base
= (foff
+ off
) & PAGE_MASK
;
397 if (vm_page_is_valid(m
, base
, size
) == 0)
398 bp
->b_flags
&= ~B_CACHE
;
405 * Spank the buf_daemon[_hw] if the total dirty buffer space exceeds the
412 if (dirtykvaspace
< lodirtybufspace
&& dirtybufcount
< nbuf
/ 2)
415 if (bd_request
== 0 &&
416 (dirtykvaspace
> lodirtybufspace
/ 2 ||
417 dirtybufcount
- dirtybufcounthw
>= nbuf
/ 2)) {
418 if (atomic_fetchadd_int(&bd_request
, 1) == 0)
421 if (bd_request_hw
== 0 &&
422 (dirtykvaspace
> lodirtybufspace
/ 2 ||
423 dirtybufcounthw
>= nbuf
/ 2)) {
424 if (atomic_fetchadd_int(&bd_request_hw
, 1) == 0)
425 wakeup(&bd_request_hw
);
432 * Get the buf_daemon heated up when the number of running and dirty
433 * buffers exceeds the mid-point.
435 * Return the total number of dirty bytes past the second mid point
436 * as a measure of how much excess dirty data there is in the system.
445 mid1
= lodirtybufspace
+ (hidirtybufspace
- lodirtybufspace
) / 2;
447 totalspace
= runningbufspace
+ dirtykvaspace
;
448 if (totalspace
>= mid1
|| dirtybufcount
>= nbuf
/ 2) {
450 mid2
= mid1
+ (hidirtybufspace
- mid1
) / 2;
451 if (totalspace
>= mid2
)
452 return(totalspace
- mid2
);
460 * Wait for the buffer cache to flush (totalspace) bytes worth of
461 * buffers, then return.
463 * Regardless this function blocks while the number of dirty buffers
464 * exceeds hidirtybufspace.
467 bd_wait(long totalspace
)
474 if (curthread
== bufdaemonhw_td
|| curthread
== bufdaemon_td
)
477 while (totalspace
> 0) {
481 * Order is important. Suppliers adjust bd_wake_index after
482 * updating runningbufspace/dirtykvaspace. We want to fetch
483 * bd_wake_index before accessing. Any error should thus
486 i
= atomic_fetchadd_int(&bd_wake_index
, 0);
487 if (totalspace
> runningbufspace
+ dirtykvaspace
)
488 totalspace
= runningbufspace
+ dirtykvaspace
;
489 count
= totalspace
/ MAXBSIZE
;
490 if (count
>= BD_WAKE_SIZE
/ 2)
491 count
= BD_WAKE_SIZE
/ 2;
493 mi
= i
& BD_WAKE_MASK
;
496 * This is not a strict interlock, so we play a bit loose
497 * with locking access to dirtybufspace*. We have to re-check
498 * bd_wake_index to ensure that it hasn't passed us.
500 tsleep_interlock(&bd_wake_ary
[mi
], 0);
501 atomic_add_int(&bd_wake_ary
[mi
], 1);
502 j
= atomic_fetchadd_int(&bd_wake_index
, 0);
503 if ((int)(i
- j
) >= 0)
504 tsleep(&bd_wake_ary
[mi
], PINTERLOCKED
, "flstik", hz
);
506 totalspace
= runningbufspace
+ dirtykvaspace
- hidirtybufspace
;
513 * This function is called whenever runningbufspace or dirtykvaspace
514 * is reduced. Track threads waiting for run+dirty buffer I/O
518 bd_signal(long totalspace
)
522 if (totalspace
> 0) {
523 if (totalspace
> MAXBSIZE
* BD_WAKE_SIZE
)
524 totalspace
= MAXBSIZE
* BD_WAKE_SIZE
;
525 while (totalspace
> 0) {
526 i
= atomic_fetchadd_int(&bd_wake_index
, 1);
528 if (atomic_readandclear_int(&bd_wake_ary
[i
]))
529 wakeup(&bd_wake_ary
[i
]);
530 totalspace
-= MAXBSIZE
;
536 * BIO tracking support routines.
538 * Release a ref on a bio_track. Wakeup requests are atomically released
539 * along with the last reference so bk_active will never wind up set to
544 bio_track_rel(struct bio_track
*track
)
552 active
= track
->bk_active
;
553 if (active
== 1 && atomic_cmpset_int(&track
->bk_active
, 1, 0))
557 * Full-on. Note that the wait flag is only atomically released on
558 * the 1->0 count transition.
560 * We check for a negative count transition using bit 30 since bit 31
561 * has a different meaning.
564 desired
= (active
& 0x7FFFFFFF) - 1;
566 desired
|= active
& 0x80000000;
567 if (atomic_cmpset_int(&track
->bk_active
, active
, desired
)) {
568 if (desired
& 0x40000000)
569 panic("bio_track_rel: bad count: %p", track
);
570 if (active
& 0x80000000)
574 active
= track
->bk_active
;
579 * Wait for the tracking count to reach 0.
581 * Use atomic ops such that the wait flag is only set atomically when
582 * bk_active is non-zero.
585 bio_track_wait(struct bio_track
*track
, int slp_flags
, int slp_timo
)
594 if (track
->bk_active
== 0)
598 * Full-on. Note that the wait flag may only be atomically set if
599 * the active count is non-zero.
601 * NOTE: We cannot optimize active == desired since a wakeup could
602 * clear active prior to our tsleep_interlock().
605 while ((active
= track
->bk_active
) != 0) {
607 desired
= active
| 0x80000000;
608 tsleep_interlock(track
, slp_flags
);
609 if (atomic_cmpset_int(&track
->bk_active
, active
, desired
)) {
610 error
= tsleep(track
, slp_flags
| PINTERLOCKED
,
622 * Load time initialisation of the buffer cache, called from machine
623 * dependant initialization code.
627 bufinit(void *dummy __unused
)
629 struct bufpcpu
*pcpu
;
631 vm_offset_t bogus_offset
;
636 /* next, make a null set of free lists */
637 for (i
= 0; i
< ncpus
; ++i
) {
639 spin_init(&pcpu
->spin
, "bufinit");
640 for (j
= 0; j
< BUFFER_QUEUES
; j
++)
641 TAILQ_INIT(&pcpu
->bufqueues
[j
]);
645 * Finally, initialize each buffer header and stick on empty q.
646 * Each buffer gets its own KVA reservation.
651 for (n
= 0; n
< nbuf
; n
++) {
653 bzero(bp
, sizeof *bp
);
654 bp
->b_flags
= B_INVAL
; /* we're just an empty header */
655 bp
->b_cmd
= BUF_CMD_DONE
;
656 bp
->b_qindex
= BQUEUE_EMPTY
;
658 bp
->b_kvabase
= (void *)(vm_map_min(&buffer_map
) +
660 bp
->b_kvasize
= MAXBSIZE
;
662 xio_init(&bp
->b_xio
);
664 TAILQ_INSERT_TAIL(&pcpu
->bufqueues
[bp
->b_qindex
],
672 * maxbufspace is the absolute maximum amount of buffer space we are
673 * allowed to reserve in KVM and in real terms. The absolute maximum
674 * is nominally used by buf_daemon. hibufspace is the nominal maximum
675 * used by most other processes. The differential is required to
676 * ensure that buf_daemon is able to run when other processes might
677 * be blocked waiting for buffer space.
679 * Calculate hysteresis (lobufspace, hibufspace). Don't make it
680 * too large or we might lockup a cpu for too long a period of
681 * time in our tight loop.
683 maxbufspace
= nbuf
* NBUFCALCSIZE
;
684 hibufspace
= lmax(3 * maxbufspace
/ 4, maxbufspace
- MAXBSIZE
* 10);
685 lobufspace
= hibufspace
* 7 / 8;
686 if (hibufspace
- lobufspace
> 64 * 1024 * 1024)
687 lobufspace
= hibufspace
- 64 * 1024 * 1024;
688 if (lobufspace
> hibufspace
- MAXBSIZE
)
689 lobufspace
= hibufspace
- MAXBSIZE
;
691 lorunningspace
= 512 * 1024;
692 /* hirunningspace -- see below */
695 * Limit the amount of malloc memory since it is wired permanently
696 * into the kernel space. Even though this is accounted for in
697 * the buffer allocation, we don't want the malloced region to grow
698 * uncontrolled. The malloc scheme improves memory utilization
699 * significantly on average (small) directories.
701 maxbufmallocspace
= hibufspace
/ 20;
704 * Reduce the chance of a deadlock occuring by limiting the number
705 * of delayed-write dirty buffers we allow to stack up.
707 * We don't want too much actually queued to the device at once
708 * (XXX this needs to be per-mount!), because the buffers will
709 * wind up locked for a very long period of time while the I/O
712 hidirtybufspace
= hibufspace
/ 2; /* dirty + running */
713 hirunningspace
= hibufspace
/ 16; /* locked & queued to device */
714 if (hirunningspace
< 1024 * 1024)
715 hirunningspace
= 1024 * 1024;
721 lodirtybufspace
= hidirtybufspace
/ 2;
724 * Maximum number of async ops initiated per buf_daemon loop. This is
725 * somewhat of a hack at the moment, we really need to limit ourselves
726 * based on the number of bytes of I/O in-transit that were initiated
730 bogus_offset
= kmem_alloc_pageable(&kernel_map
, PAGE_SIZE
);
731 vm_object_hold(&kernel_object
);
732 bogus_page
= vm_page_alloc(&kernel_object
,
733 (bogus_offset
>> PAGE_SHIFT
),
735 vm_object_drop(&kernel_object
);
736 vmstats
.v_wire_count
++;
740 SYSINIT(do_bufinit
, SI_BOOT2_MACHDEP
, SI_ORDER_FIRST
, bufinit
, NULL
);
743 * Initialize the embedded bio structures, typically used by
744 * deprecated code which tries to allocate its own struct bufs.
747 initbufbio(struct buf
*bp
)
749 bp
->b_bio1
.bio_buf
= bp
;
750 bp
->b_bio1
.bio_prev
= NULL
;
751 bp
->b_bio1
.bio_offset
= NOOFFSET
;
752 bp
->b_bio1
.bio_next
= &bp
->b_bio2
;
753 bp
->b_bio1
.bio_done
= NULL
;
754 bp
->b_bio1
.bio_flags
= 0;
756 bp
->b_bio2
.bio_buf
= bp
;
757 bp
->b_bio2
.bio_prev
= &bp
->b_bio1
;
758 bp
->b_bio2
.bio_offset
= NOOFFSET
;
759 bp
->b_bio2
.bio_next
= NULL
;
760 bp
->b_bio2
.bio_done
= NULL
;
761 bp
->b_bio2
.bio_flags
= 0;
767 * Reinitialize the embedded bio structures as well as any additional
768 * translation cache layers.
771 reinitbufbio(struct buf
*bp
)
775 for (bio
= &bp
->b_bio1
; bio
; bio
= bio
->bio_next
) {
776 bio
->bio_done
= NULL
;
777 bio
->bio_offset
= NOOFFSET
;
782 * Undo the effects of an initbufbio().
785 uninitbufbio(struct buf
*bp
)
792 * Push another BIO layer onto an existing BIO and return it. The new
793 * BIO layer may already exist, holding cached translation data.
796 push_bio(struct bio
*bio
)
800 if ((nbio
= bio
->bio_next
) == NULL
) {
801 int index
= bio
- &bio
->bio_buf
->b_bio_array
[0];
802 if (index
>= NBUF_BIO
- 1) {
803 panic("push_bio: too many layers %d for bp %p",
804 index
, bio
->bio_buf
);
806 nbio
= &bio
->bio_buf
->b_bio_array
[index
+ 1];
807 bio
->bio_next
= nbio
;
808 nbio
->bio_prev
= bio
;
809 nbio
->bio_buf
= bio
->bio_buf
;
810 nbio
->bio_offset
= NOOFFSET
;
811 nbio
->bio_done
= NULL
;
812 nbio
->bio_next
= NULL
;
814 KKASSERT(nbio
->bio_done
== NULL
);
819 * Pop a BIO translation layer, returning the previous layer. The
820 * must have been previously pushed.
823 pop_bio(struct bio
*bio
)
825 return(bio
->bio_prev
);
829 clearbiocache(struct bio
*bio
)
832 bio
->bio_offset
= NOOFFSET
;
838 * Remove the buffer from the appropriate free list.
839 * (caller must be locked)
842 _bremfree(struct buf
*bp
)
844 struct bufpcpu
*pcpu
= &bufpcpu
[bp
->b_qcpu
];
846 if (bp
->b_qindex
!= BQUEUE_NONE
) {
847 KASSERT(BUF_REFCNTNB(bp
) == 1,
848 ("bremfree: bp %p not locked",bp
));
849 TAILQ_REMOVE(&pcpu
->bufqueues
[bp
->b_qindex
], bp
, b_freelist
);
850 bp
->b_qindex
= BQUEUE_NONE
;
852 if (BUF_REFCNTNB(bp
) <= 1)
853 panic("bremfree: removing a buffer not on a queue");
858 * bremfree() - must be called with a locked buffer
861 bremfree(struct buf
*bp
)
863 struct bufpcpu
*pcpu
= &bufpcpu
[bp
->b_qcpu
];
865 spin_lock(&pcpu
->spin
);
867 spin_unlock(&pcpu
->spin
);
871 * bremfree_locked - must be called with pcpu->spin locked
874 bremfree_locked(struct buf
*bp
)
880 * This version of bread issues any required I/O asyncnronously and
881 * makes a callback on completion.
883 * The callback must check whether BIO_DONE is set in the bio and issue
884 * the bpdone(bp, 0) if it isn't. The callback is responsible for clearing
885 * BIO_DONE and disposing of the I/O (bqrelse()ing it).
888 breadcb(struct vnode
*vp
, off_t loffset
, int size
,
889 void (*func
)(struct bio
*), void *arg
)
893 bp
= getblk(vp
, loffset
, size
, 0, 0);
895 /* if not found in cache, do some I/O */
896 if ((bp
->b_flags
& B_CACHE
) == 0) {
897 bp
->b_flags
&= ~(B_ERROR
| B_EINTR
| B_INVAL
);
898 bp
->b_cmd
= BUF_CMD_READ
;
899 bp
->b_bio1
.bio_done
= func
;
900 bp
->b_bio1
.bio_caller_info1
.ptr
= arg
;
901 vfs_busy_pages(vp
, bp
);
903 vn_strategy(vp
, &bp
->b_bio1
);
906 * Since we are issuing the callback synchronously it cannot
907 * race the BIO_DONE, so no need for atomic ops here.
909 /*bp->b_bio1.bio_done = func;*/
910 bp
->b_bio1
.bio_caller_info1
.ptr
= arg
;
911 bp
->b_bio1
.bio_flags
|= BIO_DONE
;
919 * breadnx() - Terminal function for bread() and breadn().
921 * This function will start asynchronous I/O on read-ahead blocks as well
922 * as satisfy the primary request.
924 * We must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE is
925 * set, the buffer is valid and we do not have to do anything.
928 breadnx(struct vnode
*vp
, off_t loffset
, int size
, off_t
*raoffset
,
929 int *rabsize
, int cnt
, struct buf
**bpp
)
931 struct buf
*bp
, *rabp
;
933 int rv
= 0, readwait
= 0;
938 *bpp
= bp
= getblk(vp
, loffset
, size
, 0, 0);
940 /* if not found in cache, do some I/O */
941 if ((bp
->b_flags
& B_CACHE
) == 0) {
942 bp
->b_flags
&= ~(B_ERROR
| B_EINTR
| B_INVAL
);
943 bp
->b_cmd
= BUF_CMD_READ
;
944 bp
->b_bio1
.bio_done
= biodone_sync
;
945 bp
->b_bio1
.bio_flags
|= BIO_SYNC
;
946 vfs_busy_pages(vp
, bp
);
947 vn_strategy(vp
, &bp
->b_bio1
);
951 for (i
= 0; i
< cnt
; i
++, raoffset
++, rabsize
++) {
952 if (inmem(vp
, *raoffset
))
954 rabp
= getblk(vp
, *raoffset
, *rabsize
, 0, 0);
956 if ((rabp
->b_flags
& B_CACHE
) == 0) {
957 rabp
->b_flags
&= ~(B_ERROR
| B_EINTR
| B_INVAL
);
958 rabp
->b_cmd
= BUF_CMD_READ
;
959 vfs_busy_pages(vp
, rabp
);
961 vn_strategy(vp
, &rabp
->b_bio1
);
967 rv
= biowait(&bp
->b_bio1
, "biord");
974 * Synchronous write, waits for completion.
976 * Write, release buffer on completion. (Done by iodone
977 * if async). Do not bother writing anything if the buffer
980 * Note that we set B_CACHE here, indicating that buffer is
981 * fully valid and thus cacheable. This is true even of NFS
982 * now so we set it generally. This could be set either here
983 * or in biodone() since the I/O is synchronous. We put it
987 bwrite(struct buf
*bp
)
991 if (bp
->b_flags
& B_INVAL
) {
995 if (BUF_REFCNTNB(bp
) == 0)
996 panic("bwrite: buffer is not busy???");
999 * NOTE: We no longer mark the buffer clear prior to the vn_strategy()
1000 * call because it will remove the buffer from the vnode's
1001 * dirty buffer list prematurely and possibly cause filesystem
1002 * checks to race buffer flushes. This is now handled in
1005 * bundirty(bp); REMOVED
1008 bp
->b_flags
&= ~(B_ERROR
| B_EINTR
);
1009 bp
->b_flags
|= B_CACHE
;
1010 bp
->b_cmd
= BUF_CMD_WRITE
;
1011 bp
->b_bio1
.bio_done
= biodone_sync
;
1012 bp
->b_bio1
.bio_flags
|= BIO_SYNC
;
1013 vfs_busy_pages(bp
->b_vp
, bp
);
1016 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
1017 * valid for vnode-backed buffers.
1019 bsetrunningbufspace(bp
, bp
->b_bufsize
);
1020 vn_strategy(bp
->b_vp
, &bp
->b_bio1
);
1021 error
= biowait(&bp
->b_bio1
, "biows");
1030 * Asynchronous write. Start output on a buffer, but do not wait for
1031 * it to complete. The buffer is released when the output completes.
1033 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1034 * B_INVAL buffers. Not us.
1037 bawrite(struct buf
*bp
)
1039 if (bp
->b_flags
& B_INVAL
) {
1043 if (BUF_REFCNTNB(bp
) == 0)
1044 panic("bawrite: buffer is not busy???");
1047 * NOTE: We no longer mark the buffer clear prior to the vn_strategy()
1048 * call because it will remove the buffer from the vnode's
1049 * dirty buffer list prematurely and possibly cause filesystem
1050 * checks to race buffer flushes. This is now handled in
1053 * bundirty(bp); REMOVED
1055 bp
->b_flags
&= ~(B_ERROR
| B_EINTR
);
1056 bp
->b_flags
|= B_CACHE
;
1057 bp
->b_cmd
= BUF_CMD_WRITE
;
1058 KKASSERT(bp
->b_bio1
.bio_done
== NULL
);
1059 vfs_busy_pages(bp
->b_vp
, bp
);
1062 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
1063 * valid for vnode-backed buffers.
1065 bsetrunningbufspace(bp
, bp
->b_bufsize
);
1067 vn_strategy(bp
->b_vp
, &bp
->b_bio1
);
1073 * Ordered write. Start output on a buffer, and flag it so that the
1074 * device will write it in the order it was queued. The buffer is
1075 * released when the output completes. bwrite() ( or the VOP routine
1076 * anyway ) is responsible for handling B_INVAL buffers.
1079 bowrite(struct buf
*bp
)
1081 bp
->b_flags
|= B_ORDERED
;
1089 * Delayed write. (Buffer is marked dirty). Do not bother writing
1090 * anything if the buffer is marked invalid.
1092 * Note that since the buffer must be completely valid, we can safely
1093 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
1094 * biodone() in order to prevent getblk from writing the buffer
1095 * out synchronously.
1098 bdwrite(struct buf
*bp
)
1100 if (BUF_REFCNTNB(bp
) == 0)
1101 panic("bdwrite: buffer is not busy");
1103 if (bp
->b_flags
& B_INVAL
) {
1109 dsched_buf_enter(bp
); /* might stack */
1112 * Set B_CACHE, indicating that the buffer is fully valid. This is
1113 * true even of NFS now.
1115 bp
->b_flags
|= B_CACHE
;
1118 * This bmap keeps the system from needing to do the bmap later,
1119 * perhaps when the system is attempting to do a sync. Since it
1120 * is likely that the indirect block -- or whatever other datastructure
1121 * that the filesystem needs is still in memory now, it is a good
1122 * thing to do this. Note also, that if the pageout daemon is
1123 * requesting a sync -- there might not be enough memory to do
1124 * the bmap then... So, this is important to do.
1126 if (bp
->b_bio2
.bio_offset
== NOOFFSET
) {
1127 VOP_BMAP(bp
->b_vp
, bp
->b_loffset
, &bp
->b_bio2
.bio_offset
,
1128 NULL
, NULL
, BUF_CMD_WRITE
);
1132 * Because the underlying pages may still be mapped and
1133 * writable trying to set the dirty buffer (b_dirtyoff/end)
1134 * range here will be inaccurate.
1136 * However, we must still clean the pages to satisfy the
1137 * vnode_pager and pageout daemon, so they think the pages
1138 * have been "cleaned". What has really occured is that
1139 * they've been earmarked for later writing by the buffer
1142 * So we get the b_dirtyoff/end update but will not actually
1143 * depend on it (NFS that is) until the pages are busied for
1146 vfs_clean_pages(bp
);
1150 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1151 * due to the softdep code.
1156 * Fake write - return pages to VM system as dirty, leave the buffer clean.
1157 * This is used by tmpfs.
1159 * It is important for any VFS using this routine to NOT use it for
1160 * IO_SYNC or IO_ASYNC operations which occur when the system really
1161 * wants to flush VM pages to backing store.
1164 buwrite(struct buf
*bp
)
1170 * Only works for VMIO buffers. If the buffer is already
1171 * marked for delayed-write we can't avoid the bdwrite().
1173 if ((bp
->b_flags
& B_VMIO
) == 0 || (bp
->b_flags
& B_DELWRI
)) {
1179 * Mark as needing a commit.
1181 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
1182 m
= bp
->b_xio
.xio_pages
[i
];
1183 vm_page_need_commit(m
);
1191 * Turn buffer into delayed write request by marking it B_DELWRI.
1192 * B_RELBUF and B_NOCACHE must be cleared.
1194 * We reassign the buffer to itself to properly update it in the
1195 * dirty/clean lists.
1197 * Must be called from a critical section.
1198 * The buffer must be on BQUEUE_NONE.
1201 bdirty(struct buf
*bp
)
1203 KASSERT(bp
->b_qindex
== BQUEUE_NONE
,
1204 ("bdirty: buffer %p still on queue %d", bp
, bp
->b_qindex
));
1205 if (bp
->b_flags
& B_NOCACHE
) {
1206 kprintf("bdirty: clearing B_NOCACHE on buf %p\n", bp
);
1207 bp
->b_flags
&= ~B_NOCACHE
;
1209 if (bp
->b_flags
& B_INVAL
) {
1210 kprintf("bdirty: warning, dirtying invalid buffer %p\n", bp
);
1212 bp
->b_flags
&= ~B_RELBUF
;
1214 if ((bp
->b_flags
& B_DELWRI
) == 0) {
1215 lwkt_gettoken(&bp
->b_vp
->v_token
);
1216 bp
->b_flags
|= B_DELWRI
;
1218 lwkt_reltoken(&bp
->b_vp
->v_token
);
1220 atomic_add_long(&dirtybufcount
, 1);
1221 atomic_add_long(&dirtykvaspace
, bp
->b_kvasize
);
1222 atomic_add_long(&dirtybufspace
, bp
->b_bufsize
);
1223 if (bp
->b_flags
& B_HEAVY
) {
1224 atomic_add_long(&dirtybufcounthw
, 1);
1225 atomic_add_long(&dirtybufspacehw
, bp
->b_bufsize
);
1232 * Set B_HEAVY, indicating that this is a heavy-weight buffer that
1233 * needs to be flushed with a different buf_daemon thread to avoid
1234 * deadlocks. B_HEAVY also imposes restrictions in getnewbuf().
1237 bheavy(struct buf
*bp
)
1239 if ((bp
->b_flags
& B_HEAVY
) == 0) {
1240 bp
->b_flags
|= B_HEAVY
;
1241 if (bp
->b_flags
& B_DELWRI
) {
1242 atomic_add_long(&dirtybufcounthw
, 1);
1243 atomic_add_long(&dirtybufspacehw
, bp
->b_bufsize
);
1251 * Clear B_DELWRI for buffer.
1253 * Must be called from a critical section.
1255 * The buffer is typically on BQUEUE_NONE but there is one case in
1256 * brelse() that calls this function after placing the buffer on
1257 * a different queue.
1260 bundirty(struct buf
*bp
)
1262 if (bp
->b_flags
& B_DELWRI
) {
1263 lwkt_gettoken(&bp
->b_vp
->v_token
);
1264 bp
->b_flags
&= ~B_DELWRI
;
1266 lwkt_reltoken(&bp
->b_vp
->v_token
);
1268 atomic_add_long(&dirtybufcount
, -1);
1269 atomic_add_long(&dirtykvaspace
, -bp
->b_kvasize
);
1270 atomic_add_long(&dirtybufspace
, -bp
->b_bufsize
);
1271 if (bp
->b_flags
& B_HEAVY
) {
1272 atomic_add_long(&dirtybufcounthw
, -1);
1273 atomic_add_long(&dirtybufspacehw
, -bp
->b_bufsize
);
1275 bd_signal(bp
->b_bufsize
);
1278 * Since it is now being written, we can clear its deferred write flag.
1280 bp
->b_flags
&= ~B_DEFERRED
;
1284 * Set the b_runningbufspace field, used to track how much I/O is
1285 * in progress at any given moment.
1288 bsetrunningbufspace(struct buf
*bp
, int bytes
)
1290 bp
->b_runningbufspace
= bytes
;
1292 atomic_add_long(&runningbufspace
, bytes
);
1293 atomic_add_long(&runningbufcount
, 1);
1300 * Release a busy buffer and, if requested, free its resources. The
1301 * buffer will be stashed in the appropriate bufqueue[] allowing it
1302 * to be accessed later as a cache entity or reused for other purposes.
1305 brelse(struct buf
*bp
)
1307 struct bufpcpu
*pcpu
;
1309 int saved_flags
= bp
->b_flags
;
1312 KASSERT(!(bp
->b_flags
& (B_CLUSTER
|B_PAGING
)),
1313 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp
));
1316 * If B_NOCACHE is set we are being asked to destroy the buffer and
1317 * its backing store. Clear B_DELWRI.
1319 * B_NOCACHE is set in two cases: (1) when the caller really wants
1320 * to destroy the buffer and backing store and (2) when the caller
1321 * wants to destroy the buffer and backing store after a write
1324 if ((bp
->b_flags
& (B_NOCACHE
|B_DELWRI
)) == (B_NOCACHE
|B_DELWRI
)) {
1328 if ((bp
->b_flags
& (B_INVAL
| B_DELWRI
)) == B_DELWRI
) {
1330 * A re-dirtied buffer is only subject to destruction
1331 * by B_INVAL. B_ERROR and B_NOCACHE are ignored.
1333 /* leave buffer intact */
1334 } else if ((bp
->b_flags
& (B_NOCACHE
| B_INVAL
| B_ERROR
)) ||
1335 (bp
->b_bufsize
<= 0)) {
1337 * Either a failed read or we were asked to free or not
1338 * cache the buffer. This path is reached with B_DELWRI
1339 * set only if B_INVAL is already set. B_NOCACHE governs
1340 * backing store destruction.
1342 * NOTE: HAMMER will set B_LOCKED in buf_deallocate if the
1343 * buffer cannot be immediately freed.
1345 bp
->b_flags
|= B_INVAL
;
1346 if (LIST_FIRST(&bp
->b_dep
) != NULL
)
1348 if (bp
->b_flags
& B_DELWRI
) {
1349 atomic_add_long(&dirtybufcount
, -1);
1350 atomic_add_long(&dirtykvaspace
, -bp
->b_kvasize
);
1351 atomic_add_long(&dirtybufspace
, -bp
->b_bufsize
);
1352 if (bp
->b_flags
& B_HEAVY
) {
1353 atomic_add_long(&dirtybufcounthw
, -1);
1354 atomic_add_long(&dirtybufspacehw
,
1357 bd_signal(bp
->b_bufsize
);
1359 bp
->b_flags
&= ~(B_DELWRI
| B_CACHE
);
1363 * We must clear B_RELBUF if B_DELWRI or B_LOCKED is set,
1364 * or if b_refs is non-zero.
1366 * If vfs_vmio_release() is called with either bit set, the
1367 * underlying pages may wind up getting freed causing a previous
1368 * write (bdwrite()) to get 'lost' because pages associated with
1369 * a B_DELWRI bp are marked clean. Pages associated with a
1370 * B_LOCKED buffer may be mapped by the filesystem.
1372 * If we want to release the buffer ourselves (rather then the
1373 * originator asking us to release it), give the originator a
1374 * chance to countermand the release by setting B_LOCKED.
1376 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1377 * if B_DELWRI is set.
1379 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1380 * on pages to return pages to the VM page queues.
1382 if ((bp
->b_flags
& (B_DELWRI
| B_LOCKED
)) || bp
->b_refs
) {
1383 bp
->b_flags
&= ~B_RELBUF
;
1384 } else if (vm_page_count_min(0)) {
1385 if (LIST_FIRST(&bp
->b_dep
) != NULL
)
1386 buf_deallocate(bp
); /* can set B_LOCKED */
1387 if (bp
->b_flags
& (B_DELWRI
| B_LOCKED
))
1388 bp
->b_flags
&= ~B_RELBUF
;
1390 bp
->b_flags
|= B_RELBUF
;
1394 * Make sure b_cmd is clear. It may have already been cleared by
1397 * At this point destroying the buffer is governed by the B_INVAL
1398 * or B_RELBUF flags.
1400 bp
->b_cmd
= BUF_CMD_DONE
;
1401 dsched_buf_exit(bp
);
1404 * VMIO buffer rundown. Make sure the VM page array is restored
1405 * after an I/O may have replaces some of the pages with bogus pages
1406 * in order to not destroy dirty pages in a fill-in read.
1408 * Note that due to the code above, if a buffer is marked B_DELWRI
1409 * then the B_RELBUF and B_NOCACHE bits will always be clear.
1410 * B_INVAL may still be set, however.
1412 * For clean buffers, B_INVAL or B_RELBUF will destroy the buffer
1413 * but not the backing store. B_NOCACHE will destroy the backing
1416 * Note that dirty NFS buffers contain byte-granular write ranges
1417 * and should not be destroyed w/ B_INVAL even if the backing store
1420 if (bp
->b_flags
& B_VMIO
) {
1422 * Rundown for VMIO buffers which are not dirty NFS buffers.
1434 * Get the base offset and length of the buffer. Note that
1435 * in the VMIO case if the buffer block size is not
1436 * page-aligned then b_data pointer may not be page-aligned.
1437 * But our b_xio.xio_pages array *IS* page aligned.
1439 * block sizes less then DEV_BSIZE (usually 512) are not
1440 * supported due to the page granularity bits (m->valid,
1441 * m->dirty, etc...).
1443 * See man buf(9) for more information
1446 resid
= bp
->b_bufsize
;
1447 foff
= bp
->b_loffset
;
1449 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
1450 m
= bp
->b_xio
.xio_pages
[i
];
1451 vm_page_flag_clear(m
, PG_ZERO
);
1453 * If we hit a bogus page, fixup *all* of them
1454 * now. Note that we left these pages wired
1455 * when we removed them so they had better exist,
1456 * and they cannot be ripped out from under us so
1457 * no critical section protection is necessary.
1459 if (m
== bogus_page
) {
1461 poff
= OFF_TO_IDX(bp
->b_loffset
);
1463 vm_object_hold(obj
);
1464 for (j
= i
; j
< bp
->b_xio
.xio_npages
; j
++) {
1467 mtmp
= bp
->b_xio
.xio_pages
[j
];
1468 if (mtmp
== bogus_page
) {
1469 if ((bp
->b_flags
& B_HASBOGUS
) == 0)
1470 panic("brelse: bp %p corrupt bogus", bp
);
1471 mtmp
= vm_page_lookup(obj
, poff
+ j
);
1473 panic("brelse: bp %p page %d missing", bp
, j
);
1474 bp
->b_xio
.xio_pages
[j
] = mtmp
;
1477 vm_object_drop(obj
);
1479 if ((bp
->b_flags
& B_HASBOGUS
) || (bp
->b_flags
& B_INVAL
) == 0) {
1480 pmap_qenter(trunc_page((vm_offset_t
)bp
->b_data
),
1481 bp
->b_xio
.xio_pages
, bp
->b_xio
.xio_npages
);
1482 bp
->b_flags
&= ~B_HASBOGUS
;
1484 m
= bp
->b_xio
.xio_pages
[i
];
1488 * Invalidate the backing store if B_NOCACHE is set
1489 * (e.g. used with vinvalbuf()). If this is NFS
1490 * we impose a requirement that the block size be
1491 * a multiple of PAGE_SIZE and create a temporary
1492 * hack to basically invalidate the whole page. The
1493 * problem is that NFS uses really odd buffer sizes
1494 * especially when tracking piecemeal writes and
1495 * it also vinvalbuf()'s a lot, which would result
1496 * in only partial page validation and invalidation
1497 * here. If the file page is mmap()'d, however,
1498 * all the valid bits get set so after we invalidate
1499 * here we would end up with weird m->valid values
1500 * like 0xfc. nfs_getpages() can't handle this so
1501 * we clear all the valid bits for the NFS case
1502 * instead of just some of them.
1504 * The real bug is the VM system having to set m->valid
1505 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1506 * itself is an artifact of the whole 512-byte
1507 * granular mess that exists to support odd block
1508 * sizes and UFS meta-data block sizes (e.g. 6144).
1509 * A complete rewrite is required.
1513 if (bp
->b_flags
& (B_NOCACHE
|B_ERROR
)) {
1514 int poffset
= foff
& PAGE_MASK
;
1517 presid
= PAGE_SIZE
- poffset
;
1518 if (bp
->b_vp
->v_tag
== VT_NFS
&&
1519 bp
->b_vp
->v_type
== VREG
) {
1521 } else if (presid
> resid
) {
1524 KASSERT(presid
>= 0, ("brelse: extra page"));
1525 vm_page_set_invalid(m
, poffset
, presid
);
1528 * Also make sure any swap cache is removed
1529 * as it is now stale (HAMMER in particular
1530 * uses B_NOCACHE to deal with buffer
1533 swap_pager_unswapped(m
);
1535 resid
-= PAGE_SIZE
- (foff
& PAGE_MASK
);
1536 foff
= (foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
;
1538 if (bp
->b_flags
& (B_INVAL
| B_RELBUF
))
1539 vfs_vmio_release(bp
);
1542 * Rundown for non-VMIO buffers.
1544 if (bp
->b_flags
& (B_INVAL
| B_RELBUF
)) {
1547 KKASSERT (LIST_FIRST(&bp
->b_dep
) == NULL
);
1553 if (bp
->b_qindex
!= BQUEUE_NONE
)
1554 panic("brelse: free buffer onto another queue???");
1555 if (BUF_REFCNTNB(bp
) > 1) {
1556 /* Temporary panic to verify exclusive locking */
1557 /* This panic goes away when we allow shared refs */
1558 panic("brelse: multiple refs");
1564 * Figure out the correct queue to place the cleaned up buffer on.
1565 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1566 * disassociated from their vnode.
1568 * Return the buffer to its original pcpu area
1570 pcpu
= &bufpcpu
[bp
->b_qcpu
];
1571 spin_lock(&pcpu
->spin
);
1573 if (bp
->b_flags
& B_LOCKED
) {
1575 * Buffers that are locked are placed in the locked queue
1576 * immediately, regardless of their state.
1578 bp
->b_qindex
= BQUEUE_LOCKED
;
1579 TAILQ_INSERT_TAIL(&pcpu
->bufqueues
[bp
->b_qindex
],
1581 } else if (bp
->b_bufsize
== 0) {
1583 * Buffers with no memory. Due to conditionals near the top
1584 * of brelse() such buffers should probably already be
1585 * marked B_INVAL and disassociated from their vnode.
1587 bp
->b_flags
|= B_INVAL
;
1588 KASSERT(bp
->b_vp
== NULL
,
1589 ("bp1 %p flags %08x/%08x vnode %p "
1590 "unexpectededly still associated!",
1591 bp
, saved_flags
, bp
->b_flags
, bp
->b_vp
));
1592 KKASSERT((bp
->b_flags
& B_HASHED
) == 0);
1593 bp
->b_qindex
= BQUEUE_EMPTY
;
1594 TAILQ_INSERT_HEAD(&pcpu
->bufqueues
[bp
->b_qindex
],
1596 } else if (bp
->b_flags
& (B_INVAL
| B_NOCACHE
| B_RELBUF
)) {
1598 * Buffers with junk contents. Again these buffers had better
1599 * already be disassociated from their vnode.
1601 KASSERT(bp
->b_vp
== NULL
,
1602 ("bp2 %p flags %08x/%08x vnode %p unexpectededly "
1603 "still associated!",
1604 bp
, saved_flags
, bp
->b_flags
, bp
->b_vp
));
1605 KKASSERT((bp
->b_flags
& B_HASHED
) == 0);
1606 bp
->b_flags
|= B_INVAL
;
1607 bp
->b_qindex
= BQUEUE_CLEAN
;
1608 TAILQ_INSERT_HEAD(&pcpu
->bufqueues
[bp
->b_qindex
],
1612 * Remaining buffers. These buffers are still associated with
1615 switch(bp
->b_flags
& (B_DELWRI
|B_HEAVY
)) {
1617 bp
->b_qindex
= BQUEUE_DIRTY
;
1618 TAILQ_INSERT_TAIL(&pcpu
->bufqueues
[bp
->b_qindex
],
1621 case B_DELWRI
| B_HEAVY
:
1622 bp
->b_qindex
= BQUEUE_DIRTY_HW
;
1623 TAILQ_INSERT_TAIL(&pcpu
->bufqueues
[bp
->b_qindex
],
1628 * NOTE: Buffers are always placed at the end of the
1629 * queue. If B_AGE is not set the buffer will cycle
1630 * through the queue twice.
1632 bp
->b_qindex
= BQUEUE_CLEAN
;
1633 TAILQ_INSERT_TAIL(&pcpu
->bufqueues
[bp
->b_qindex
],
1638 spin_unlock(&pcpu
->spin
);
1641 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1642 * on the correct queue but we have not yet unlocked it.
1644 if ((bp
->b_flags
& (B_INVAL
|B_DELWRI
)) == (B_INVAL
|B_DELWRI
))
1648 * The bp is on an appropriate queue unless locked. If it is not
1649 * locked or dirty we can wakeup threads waiting for buffer space.
1651 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1652 * if B_INVAL is set ).
1654 if ((bp
->b_flags
& (B_LOCKED
|B_DELWRI
)) == 0)
1658 * Something we can maybe free or reuse
1660 if (bp
->b_bufsize
|| bp
->b_kvasize
)
1664 * Clean up temporary flags and unlock the buffer.
1666 bp
->b_flags
&= ~(B_ORDERED
| B_NOCACHE
| B_RELBUF
| B_DIRECT
);
1673 * Release a buffer back to the appropriate queue but do not try to free
1674 * it. The buffer is expected to be used again soon.
1676 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1677 * biodone() to requeue an async I/O on completion. It is also used when
1678 * known good buffers need to be requeued but we think we may need the data
1681 * XXX we should be able to leave the B_RELBUF hint set on completion.
1684 bqrelse(struct buf
*bp
)
1686 struct bufpcpu
*pcpu
;
1688 KASSERT(!(bp
->b_flags
& (B_CLUSTER
|B_PAGING
)),
1689 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp
));
1691 if (bp
->b_qindex
!= BQUEUE_NONE
)
1692 panic("bqrelse: free buffer onto another queue???");
1693 if (BUF_REFCNTNB(bp
) > 1) {
1694 /* do not release to free list */
1695 panic("bqrelse: multiple refs");
1699 buf_act_advance(bp
);
1701 pcpu
= &bufpcpu
[bp
->b_qcpu
];
1702 spin_lock(&pcpu
->spin
);
1704 if (bp
->b_flags
& B_LOCKED
) {
1706 * Locked buffers are released to the locked queue. However,
1707 * if the buffer is dirty it will first go into the dirty
1708 * queue and later on after the I/O completes successfully it
1709 * will be released to the locked queue.
1711 bp
->b_qindex
= BQUEUE_LOCKED
;
1712 TAILQ_INSERT_TAIL(&pcpu
->bufqueues
[bp
->b_qindex
],
1714 } else if (bp
->b_flags
& B_DELWRI
) {
1715 bp
->b_qindex
= (bp
->b_flags
& B_HEAVY
) ?
1716 BQUEUE_DIRTY_HW
: BQUEUE_DIRTY
;
1717 TAILQ_INSERT_TAIL(&pcpu
->bufqueues
[bp
->b_qindex
],
1719 } else if (vm_page_count_min(0)) {
1721 * We are too low on memory, we have to try to free the
1722 * buffer (most importantly: the wired pages making up its
1723 * backing store) *now*.
1725 spin_unlock(&pcpu
->spin
);
1729 bp
->b_qindex
= BQUEUE_CLEAN
;
1730 TAILQ_INSERT_TAIL(&pcpu
->bufqueues
[bp
->b_qindex
],
1733 spin_unlock(&pcpu
->spin
);
1736 * We have now placed the buffer on the proper queue, but have yet
1739 if ((bp
->b_flags
& B_LOCKED
) == 0 &&
1740 ((bp
->b_flags
& B_INVAL
) || (bp
->b_flags
& B_DELWRI
) == 0)) {
1745 * Something we can maybe free or reuse.
1747 if (bp
->b_bufsize
&& !(bp
->b_flags
& B_DELWRI
))
1751 * Final cleanup and unlock. Clear bits that are only used while a
1752 * buffer is actively locked.
1754 bp
->b_flags
&= ~(B_ORDERED
| B_NOCACHE
| B_RELBUF
);
1755 dsched_buf_exit(bp
);
1760 * Hold a buffer, preventing it from being reused. This will prevent
1761 * normal B_RELBUF operations on the buffer but will not prevent B_INVAL
1762 * operations. If a B_INVAL operation occurs the buffer will remain held
1763 * but the underlying pages may get ripped out.
1765 * These functions are typically used in VOP_READ/VOP_WRITE functions
1766 * to hold a buffer during a copyin or copyout, preventing deadlocks
1767 * or recursive lock panics when read()/write() is used over mmap()'d
1770 * NOTE: bqhold() requires that the buffer be locked at the time of the
1771 * hold. bqdrop() has no requirements other than the buffer having
1772 * previously been held.
1775 bqhold(struct buf
*bp
)
1777 atomic_add_int(&bp
->b_refs
, 1);
1781 bqdrop(struct buf
*bp
)
1783 KKASSERT(bp
->b_refs
> 0);
1784 atomic_add_int(&bp
->b_refs
, -1);
1788 * Return backing pages held by the buffer 'bp' back to the VM system.
1789 * This routine is called when the bp is invalidated, released, or
1792 * The KVA mapping (b_data) for the underlying pages is removed by
1795 * WARNING! This routine is integral to the low memory critical path
1796 * when a buffer is B_RELBUF'd. If the system has a severe page
1797 * deficit we need to get the page(s) onto the PQ_FREE or PQ_CACHE
1798 * queues so they can be reused in the current pageout daemon
1802 vfs_vmio_release(struct buf
*bp
)
1807 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
1808 m
= bp
->b_xio
.xio_pages
[i
];
1809 bp
->b_xio
.xio_pages
[i
] = NULL
;
1812 * We need to own the page in order to safely unwire it.
1814 vm_page_busy_wait(m
, FALSE
, "vmiopg");
1817 * The VFS is telling us this is not a meta-data buffer
1818 * even if it is backed by a block device.
1820 if (bp
->b_flags
& B_NOTMETA
)
1821 vm_page_flag_set(m
, PG_NOTMETA
);
1824 * This is a very important bit of code. We try to track
1825 * VM page use whether the pages are wired into the buffer
1826 * cache or not. While wired into the buffer cache the
1827 * bp tracks the act_count.
1829 * We can choose to place unwired pages on the inactive
1830 * queue (0) or active queue (1). If we place too many
1831 * on the active queue the queue will cycle the act_count
1832 * on pages we'd like to keep, just from single-use pages
1833 * (such as when doing a tar-up or file scan).
1835 if (bp
->b_act_count
< vm_cycle_point
)
1836 vm_page_unwire(m
, 0);
1838 vm_page_unwire(m
, 1);
1841 * If the wire_count has dropped to 0 we may need to take
1842 * further action before unbusying the page.
1844 * WARNING: vm_page_try_*() also checks PG_NEED_COMMIT for us.
1846 if (m
->wire_count
== 0) {
1847 vm_page_flag_clear(m
, PG_ZERO
);
1849 if (bp
->b_flags
& B_DIRECT
) {
1851 * Attempt to free the page if B_DIRECT is
1852 * set, the caller does not desire the page
1856 vm_page_try_to_free(m
);
1857 } else if ((bp
->b_flags
& B_NOTMETA
) ||
1858 vm_page_count_min(0)) {
1860 * Attempt to move the page to PQ_CACHE
1861 * if B_NOTMETA is set. This flag is set
1862 * by HAMMER to remove one of the two pages
1863 * present when double buffering is enabled.
1865 * Attempt to move the page to PQ_CACHE
1866 * If we have a severe page deficit. This
1867 * will cause buffer cache operations related
1868 * to pageouts to recycle the related pages
1869 * in order to avoid a low memory deadlock.
1871 m
->act_count
= bp
->b_act_count
;
1873 vm_page_try_to_cache(m
);
1876 * Nominal case, leave the page on the
1877 * queue the original unwiring placed it on
1878 * (active or inactive).
1880 m
->act_count
= bp
->b_act_count
;
1889 * Zero out the pmap pte's for the mapping, but don't bother
1890 * invalidating the TLB. The range will be properly invalidating
1891 * when new pages are entered into the mapping.
1893 * This in particular reduces tmpfs tear-down overhead and reduces
1894 * buffer cache re-use overhead (one invalidation sequence instead
1895 * of two per re-use).
1897 pmap_qremove_noinval(trunc_page((vm_offset_t
) bp
->b_data
),
1898 bp
->b_xio
.xio_npages
);
1899 if (bp
->b_bufsize
) {
1900 atomic_add_long(&bufspace
, -bp
->b_bufsize
);
1904 bp
->b_xio
.xio_npages
= 0;
1905 bp
->b_flags
&= ~B_VMIO
;
1906 KKASSERT (LIST_FIRST(&bp
->b_dep
) == NULL
);
1912 * Find and initialize a new buffer header, freeing up existing buffers
1913 * in the bufqueues as necessary. The new buffer is returned locked.
1915 * If repurpose is non-NULL getnewbuf() is allowed to re-purpose an existing
1916 * buffer. The buffer will be disassociated, its page and page mappings
1917 * left intact, and returned with *repurpose set to 1. Else *repurpose is set
1918 * to 0. If 1, the caller must repurpose the underlying VM pages.
1920 * If repurpose is NULL getnewbuf() is not allowed to re-purpose an
1921 * existing buffer. That is, it must completely initialize the returned
1924 * Important: B_INVAL is not set. If the caller wishes to throw the
1925 * buffer away, the caller must set B_INVAL prior to calling brelse().
1928 * We have insufficient buffer headers
1929 * We have insufficient buffer space
1931 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1932 * Instead we ask the buf daemon to do it for us. We attempt to
1933 * avoid piecemeal wakeups of the pageout daemon.
1936 getnewbuf(int blkflags
, int slptimeo
, int size
, int maxsize
,
1937 struct vm_object
**repurposep
)
1939 struct bufpcpu
*pcpu
;
1944 int slpflags
= (blkflags
& GETBLK_PCATCH
) ? PCATCH
: 0;
1945 int maxloops
= 200000;
1946 int restart_reason
= 0;
1947 struct buf
*restart_bp
= NULL
;
1948 static char flushingbufs
[MAXCPU
];
1952 * We can't afford to block since we might be holding a vnode lock,
1953 * which may prevent system daemons from running. We deal with
1954 * low-memory situations by proactively returning memory and running
1955 * async I/O rather then sync I/O.
1959 nqcpu
= mycpu
->gd_cpuid
;
1960 flushingp
= &flushingbufs
[nqcpu
];
1962 if (bufspace
< lobufspace
)
1965 if (debug_bufbio
&& --maxloops
== 0)
1966 panic("getnewbuf, excessive loops on cpu %d restart %d (%p)",
1967 mycpu
->gd_cpuid
, restart_reason
, restart_bp
);
1970 * Setup for scan. If we do not have enough free buffers,
1971 * we setup a degenerate case that immediately fails. Note
1972 * that if we are specially marked process, we are allowed to
1973 * dip into our reserves.
1975 * The scanning sequence is nominally: EMPTY->CLEAN
1977 pcpu
= &bufpcpu
[nqcpu
];
1978 spin_lock(&pcpu
->spin
);
1981 * Determine if repurposing should be disallowed. Generally speaking
1982 * do not repurpose buffers if the buffer cache hasn't capped. Also
1983 * control repurposing based on buffer-cache -> main-memory bandwidth.
1984 * That is, we want to recycle buffers normally up until the buffer
1985 * cache bandwidth (new-buffer bw) exceeds bufcache_bw.
1987 * (This is heuristical, SMP collisions are ok)
1990 int delta
= ticks
- bufcache_bw_ticks
;
1991 if (delta
< 0 || delta
>= hz
) {
1992 atomic_swap_long(&bufcache_bw_accum
, 0);
1993 atomic_swap_int(&bufcache_bw_ticks
, ticks
);
1995 atomic_add_long(&bufcache_bw_accum
, size
);
1996 if (bufspace
< lobufspace
) {
1998 } else if (bufcache_bw_accum
< bufcache_bw
) {
2004 * Prime the scan for this cpu. Locate the first buffer to
2005 * check. If we are flushing buffers we must skip the
2008 nqindex
= BQUEUE_EMPTY
;
2009 nbp
= TAILQ_FIRST(&pcpu
->bufqueues
[BQUEUE_EMPTY
]);
2010 if (nbp
== NULL
|| *flushingp
|| repurposep
) {
2011 nqindex
= BQUEUE_CLEAN
;
2012 nbp
= TAILQ_FIRST(&pcpu
->bufqueues
[BQUEUE_CLEAN
]);
2016 * Run scan, possibly freeing data and/or kva mappings on the fly,
2019 * WARNING! spin is held!
2021 while ((bp
= nbp
) != NULL
) {
2022 int qindex
= nqindex
;
2024 nbp
= TAILQ_NEXT(bp
, b_freelist
);
2027 * BQUEUE_CLEAN - B_AGE special case. If not set the bp
2028 * cycles through the queue twice before being selected.
2030 if (qindex
== BQUEUE_CLEAN
&&
2031 (bp
->b_flags
& B_AGE
) == 0 && nbp
) {
2032 bp
->b_flags
|= B_AGE
;
2033 TAILQ_REMOVE(&pcpu
->bufqueues
[qindex
],
2035 TAILQ_INSERT_TAIL(&pcpu
->bufqueues
[qindex
],
2041 * Calculate next bp ( we can only use it if we do not block
2042 * or do other fancy things ).
2047 nqindex
= BQUEUE_CLEAN
;
2048 if ((nbp
= TAILQ_FIRST(&pcpu
->bufqueues
[BQUEUE_CLEAN
])))
2062 KASSERT(bp
->b_qindex
== qindex
,
2063 ("getnewbuf: inconsistent queue %d bp %p", qindex
, bp
));
2066 * Note: we no longer distinguish between VMIO and non-VMIO
2069 KASSERT((bp
->b_flags
& B_DELWRI
) == 0,
2070 ("delwri buffer %p found in queue %d", bp
, qindex
));
2073 * Do not try to reuse a buffer with a non-zero b_refs.
2074 * This is an unsynchronized test. A synchronized test
2075 * is also performed after we lock the buffer.
2081 * Start freeing the bp. This is somewhat involved. nbp
2082 * remains valid only for BQUEUE_EMPTY bp's. Buffers
2083 * on the clean list must be disassociated from their
2084 * current vnode. Buffers on the empty lists have
2085 * already been disassociated.
2087 * b_refs is checked after locking along with queue changes.
2088 * We must check here to deal with zero->nonzero transitions
2089 * made by the owner of the buffer lock, which is used by
2090 * VFS's to hold the buffer while issuing an unlocked
2091 * uiomove()s. We cannot invalidate the buffer's pages
2092 * for this case. Once we successfully lock a buffer the
2093 * only 0->1 transitions of b_refs will occur via findblk().
2095 * We must also check for queue changes after successful
2096 * locking as the current lock holder may dispose of the
2097 * buffer and change its queue.
2099 if (BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_NOWAIT
) != 0) {
2100 spin_unlock(&pcpu
->spin
);
2101 tsleep(&bd_request
, 0, "gnbxxx", (hz
+ 99) / 100);
2106 if (bp
->b_qindex
!= qindex
|| bp
->b_refs
) {
2107 spin_unlock(&pcpu
->spin
);
2113 bremfree_locked(bp
);
2114 spin_unlock(&pcpu
->spin
);
2117 * Dependancies must be handled before we disassociate the
2120 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
2121 * be immediately disassociated. HAMMER then becomes
2122 * responsible for releasing the buffer.
2124 * NOTE: spin is UNLOCKED now.
2126 if (LIST_FIRST(&bp
->b_dep
) != NULL
) {
2128 if (bp
->b_flags
& B_LOCKED
) {
2134 KKASSERT(LIST_FIRST(&bp
->b_dep
) == NULL
);
2138 * CLEAN buffers have content or associations that must be
2139 * cleaned out if not repurposing.
2141 if (qindex
== BQUEUE_CLEAN
) {
2142 if (bp
->b_flags
& B_VMIO
) {
2143 if (repurpose_enable
&&
2144 repurposep
&& bp
->b_bufsize
&&
2145 (bp
->b_flags
& (B_DELWRI
| B_MALLOC
)) == 0) {
2146 *repurposep
= bp
->b_vp
->v_object
;
2147 vm_object_hold(*repurposep
);
2149 vfs_vmio_release(bp
);
2157 * NOTE: nbp is now entirely invalid. We can only restart
2158 * the scan from this point on.
2160 * Get the rest of the buffer freed up. b_kva* is still
2161 * valid after this operation.
2163 KASSERT(bp
->b_vp
== NULL
,
2164 ("bp3 %p flags %08x vnode %p qindex %d "
2165 "unexpectededly still associated!",
2166 bp
, bp
->b_flags
, bp
->b_vp
, qindex
));
2167 KKASSERT((bp
->b_flags
& B_HASHED
) == 0);
2169 if (repurposep
== NULL
|| *repurposep
== NULL
) {
2174 if (bp
->b_flags
& (B_VNDIRTY
| B_VNCLEAN
| B_HASHED
)) {
2175 kprintf("getnewbuf: caught bug vp queue "
2176 "%p/%08x qidx %d\n",
2177 bp
, bp
->b_flags
, qindex
);
2180 bp
->b_flags
= B_BNOCLIP
;
2181 bp
->b_cmd
= BUF_CMD_DONE
;
2186 if (repurposep
== NULL
|| *repurposep
== NULL
)
2187 bp
->b_xio
.xio_npages
= 0;
2188 bp
->b_dirtyoff
= bp
->b_dirtyend
= 0;
2189 bp
->b_act_count
= ACT_INIT
;
2191 KKASSERT(LIST_FIRST(&bp
->b_dep
) == NULL
);
2193 if (blkflags
& GETBLK_BHEAVY
)
2194 bp
->b_flags
|= B_HEAVY
;
2196 if (bufspace
>= hibufspace
)
2198 if (bufspace
< lobufspace
)
2201 if (repurposep
&& *repurposep
!= NULL
) {
2202 bp
->b_flags
|= B_VMIO
;
2203 vfs_vmio_release(bp
);
2206 vm_object_drop(*repurposep
);
2209 bp
->b_flags
|= B_INVAL
;
2217 * b_refs can transition to a non-zero value while we hold
2218 * the buffer locked due to a findblk(). Our brelvp() above
2219 * interlocked any future possible transitions due to
2222 * If we find b_refs to be non-zero we can destroy the
2223 * buffer's contents but we cannot yet reuse the buffer.
2226 if (repurposep
&& *repurposep
!= NULL
) {
2227 bp
->b_flags
|= B_VMIO
;
2228 vfs_vmio_release(bp
);
2231 vm_object_drop(*repurposep
);
2234 bp
->b_flags
|= B_INVAL
;
2243 * We found our buffer!
2249 * If we exhausted our list, iterate other cpus. If that fails,
2250 * sleep as appropriate. We may have to wakeup various daemons
2251 * and write out some dirty buffers.
2253 * Generally we are sleeping due to insufficient buffer space.
2255 * NOTE: spin is held if bp is NULL, else it is not held.
2261 spin_unlock(&pcpu
->spin
);
2263 nqcpu
= (nqcpu
+ 1) % ncpus
;
2264 if (nqcpu
!= mycpu
->gd_cpuid
) {
2270 if (bufspace
>= hibufspace
) {
2272 flags
= VFS_BIO_NEED_BUFSPACE
;
2275 flags
= VFS_BIO_NEED_ANY
;
2278 bd_speedup(); /* heeeelp */
2279 atomic_set_int(&needsbuffer
, flags
);
2280 while (needsbuffer
& flags
) {
2283 tsleep_interlock(&needsbuffer
, 0);
2284 value
= atomic_fetchadd_int(&needsbuffer
, 0);
2285 if (value
& flags
) {
2286 if (tsleep(&needsbuffer
, PINTERLOCKED
|slpflags
,
2287 waitmsg
, slptimeo
)) {
2294 * We finally have a valid bp. Reset b_data.
2296 * (spin is not held)
2298 bp
->b_data
= bp
->b_kvabase
;
2306 * Buffer flushing daemon. Buffers are normally flushed by the
2307 * update daemon but if it cannot keep up this process starts to
2308 * take the load in an attempt to prevent getnewbuf() from blocking.
2310 * Once a flush is initiated it does not stop until the number
2311 * of buffers falls below lodirtybuffers, but we will wake up anyone
2312 * waiting at the mid-point.
2314 static struct kproc_desc buf_kp
= {
2319 SYSINIT(bufdaemon
, SI_SUB_KTHREAD_BUF
, SI_ORDER_FIRST
,
2320 kproc_start
, &buf_kp
);
2322 static struct kproc_desc bufhw_kp
= {
2327 SYSINIT(bufdaemon_hw
, SI_SUB_KTHREAD_BUF
, SI_ORDER_FIRST
,
2328 kproc_start
, &bufhw_kp
);
2331 buf_daemon1(struct thread
*td
, int queue
, int (*buf_limit_fn
)(long),
2337 marker
= kmalloc(sizeof(*marker
), M_BIOBUF
, M_WAITOK
| M_ZERO
);
2338 marker
->b_flags
|= B_MARKER
;
2339 marker
->b_qindex
= BQUEUE_NONE
;
2343 * This process needs to be suspended prior to shutdown sync.
2345 EVENTHANDLER_REGISTER(shutdown_pre_sync
, shutdown_kproc
,
2346 td
, SHUTDOWN_PRI_LAST
);
2347 curthread
->td_flags
|= TDF_SYSTHREAD
;
2350 * This process is allowed to take the buffer cache to the limit
2353 kproc_suspend_loop();
2356 * Do the flush as long as the number of dirty buffers
2357 * (including those running) exceeds lodirtybufspace.
2359 * When flushing limit running I/O to hirunningspace
2360 * Do the flush. Limit the amount of in-transit I/O we
2361 * allow to build up, otherwise we would completely saturate
2362 * the I/O system. Wakeup any waiting processes before we
2363 * normally would so they can run in parallel with our drain.
2365 * Our aggregate normal+HW lo water mark is lodirtybufspace,
2366 * but because we split the operation into two threads we
2367 * have to cut it in half for each thread.
2369 waitrunningbufspace();
2370 limit
= lodirtybufspace
/ 2;
2371 while (buf_limit_fn(limit
)) {
2372 if (flushbufqueues(marker
, queue
) == 0)
2374 if (runningbufspace
< hirunningspace
)
2376 waitrunningbufspace();
2380 * We reached our low water mark, reset the
2381 * request and sleep until we are needed again.
2382 * The sleep is just so the suspend code works.
2384 tsleep_interlock(bd_req
, 0);
2385 if (atomic_swap_int(bd_req
, 0) == 0)
2386 tsleep(bd_req
, PINTERLOCKED
, "psleep", hz
);
2389 /*kfree(marker, M_BIOBUF);*/
2393 buf_daemon_limit(long limit
)
2395 return (runningbufspace
+ dirtykvaspace
> limit
||
2396 dirtybufcount
- dirtybufcounthw
>= nbuf
/ 2);
2400 buf_daemon_hw_limit(long limit
)
2402 return (runningbufspace
+ dirtykvaspace
> limit
||
2403 dirtybufcounthw
>= nbuf
/ 2);
2409 buf_daemon1(bufdaemon_td
, BQUEUE_DIRTY
, buf_daemon_limit
,
2416 buf_daemon1(bufdaemonhw_td
, BQUEUE_DIRTY_HW
, buf_daemon_hw_limit
,
2421 * Flush up to (flushperqueue) buffers in the dirty queue. Each cpu has a
2422 * localized version of the queue. Each call made to this function iterates
2423 * to another cpu. It is desireable to flush several buffers from the same
2424 * cpu's queue at once, as these are likely going to be linear.
2426 * We must be careful to free up B_INVAL buffers instead of write them, which
2427 * NFS is particularly sensitive to.
2429 * B_RELBUF may only be set by VFSs. We do set B_AGE to indicate that we
2430 * really want to try to get the buffer out and reuse it due to the write
2431 * load on the machine.
2433 * We must lock the buffer in order to check its validity before we can mess
2434 * with its contents. spin isn't enough.
2437 flushbufqueues(struct buf
*marker
, bufq_type_t q
)
2439 struct bufpcpu
*pcpu
;
2442 u_int loops
= flushperqueue
;
2443 int lcpu
= marker
->b_qcpu
;
2445 KKASSERT(marker
->b_qindex
== BQUEUE_NONE
);
2446 KKASSERT(marker
->b_flags
& B_MARKER
);
2450 * Spinlock needed to perform operations on the queue and may be
2451 * held through a non-blocking BUF_LOCK(), but cannot be held when
2452 * BUF_UNLOCK()ing or through any other major operation.
2454 pcpu
= &bufpcpu
[marker
->b_qcpu
];
2455 spin_lock(&pcpu
->spin
);
2456 marker
->b_qindex
= q
;
2457 TAILQ_INSERT_HEAD(&pcpu
->bufqueues
[q
], marker
, b_freelist
);
2460 while ((bp
= TAILQ_NEXT(bp
, b_freelist
)) != NULL
) {
2462 * NOTE: spinlock is always held at the top of the loop
2464 if (bp
->b_flags
& B_MARKER
)
2466 if ((bp
->b_flags
& B_DELWRI
) == 0) {
2467 kprintf("Unexpected clean buffer %p\n", bp
);
2470 if (BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_NOWAIT
))
2472 KKASSERT(bp
->b_qcpu
== marker
->b_qcpu
&& bp
->b_qindex
== q
);
2475 * Once the buffer is locked we will have no choice but to
2476 * unlock the spinlock around a later BUF_UNLOCK and re-set
2477 * bp = marker when looping. Move the marker now to make
2480 TAILQ_REMOVE(&pcpu
->bufqueues
[q
], marker
, b_freelist
);
2481 TAILQ_INSERT_AFTER(&pcpu
->bufqueues
[q
], bp
, marker
, b_freelist
);
2484 * Must recheck B_DELWRI after successfully locking
2487 if ((bp
->b_flags
& B_DELWRI
) == 0) {
2488 spin_unlock(&pcpu
->spin
);
2490 spin_lock(&pcpu
->spin
);
2496 * Remove the buffer from its queue. We still own the
2502 * Disposing of an invalid buffer counts as a flush op
2504 if (bp
->b_flags
& B_INVAL
) {
2505 spin_unlock(&pcpu
->spin
);
2511 * Release the spinlock for the more complex ops we
2512 * are now going to do.
2514 spin_unlock(&pcpu
->spin
);
2518 * This is a bit messy
2520 if (LIST_FIRST(&bp
->b_dep
) != NULL
&&
2521 (bp
->b_flags
& B_DEFERRED
) == 0 &&
2522 buf_countdeps(bp
, 0)) {
2523 spin_lock(&pcpu
->spin
);
2524 TAILQ_INSERT_TAIL(&pcpu
->bufqueues
[q
], bp
, b_freelist
);
2526 bp
->b_flags
|= B_DEFERRED
;
2527 spin_unlock(&pcpu
->spin
);
2529 spin_lock(&pcpu
->spin
);
2535 * spinlock not held here.
2537 * If the buffer has a dependancy, buf_checkwrite() must
2538 * also return 0 for us to be able to initate the write.
2540 * If the buffer is flagged B_ERROR it may be requeued
2541 * over and over again, we try to avoid a live lock.
2543 if (LIST_FIRST(&bp
->b_dep
) != NULL
&& buf_checkwrite(bp
)) {
2545 } else if (bp
->b_flags
& B_ERROR
) {
2546 tsleep(bp
, 0, "bioer", 1);
2547 bp
->b_flags
&= ~B_AGE
;
2550 bp
->b_flags
|= B_AGE
;
2553 /* bp invalid but needs to be NULL-tested if we break out */
2555 spin_lock(&pcpu
->spin
);
2561 /* bp is invalid here but can be NULL-tested to advance */
2563 TAILQ_REMOVE(&pcpu
->bufqueues
[q
], marker
, b_freelist
);
2564 marker
->b_qindex
= BQUEUE_NONE
;
2565 spin_unlock(&pcpu
->spin
);
2568 * Advance the marker to be fair.
2570 marker
->b_qcpu
= (marker
->b_qcpu
+ 1) % ncpus
;
2572 if (marker
->b_qcpu
!= lcpu
)
2582 * Returns true if no I/O is needed to access the associated VM object.
2583 * This is like findblk except it also hunts around in the VM system for
2586 * Note that we ignore vm_page_free() races from interrupts against our
2587 * lookup, since if the caller is not protected our return value will not
2588 * be any more valid then otherwise once we exit the critical section.
2591 inmem(struct vnode
*vp
, off_t loffset
)
2594 vm_offset_t toff
, tinc
, size
;
2598 if (findblk(vp
, loffset
, FINDBLK_TEST
))
2600 if (vp
->v_mount
== NULL
)
2602 if ((obj
= vp
->v_object
) == NULL
)
2606 if (size
> vp
->v_mount
->mnt_stat
.f_iosize
)
2607 size
= vp
->v_mount
->mnt_stat
.f_iosize
;
2609 vm_object_hold(obj
);
2610 for (toff
= 0; toff
< vp
->v_mount
->mnt_stat
.f_iosize
; toff
+= tinc
) {
2611 m
= vm_page_lookup(obj
, OFF_TO_IDX(loffset
+ toff
));
2617 if (tinc
> PAGE_SIZE
- ((toff
+ loffset
) & PAGE_MASK
))
2618 tinc
= PAGE_SIZE
- ((toff
+ loffset
) & PAGE_MASK
);
2619 if (vm_page_is_valid(m
,
2620 (vm_offset_t
) ((toff
+ loffset
) & PAGE_MASK
), tinc
) == 0) {
2625 vm_object_drop(obj
);
2632 * Locate and return the specified buffer. Unless flagged otherwise,
2633 * a locked buffer will be returned if it exists or NULL if it does not.
2635 * findblk()'d buffers are still on the bufqueues and if you intend
2636 * to use your (locked NON-TEST) buffer you need to bremfree(bp)
2637 * and possibly do other stuff to it.
2639 * FINDBLK_TEST - Do not lock the buffer. The caller is responsible
2640 * for locking the buffer and ensuring that it remains
2641 * the desired buffer after locking.
2643 * FINDBLK_NBLOCK - Lock the buffer non-blocking. If we are unable
2644 * to acquire the lock we return NULL, even if the
2647 * FINDBLK_REF - Returns the buffer ref'd, which prevents normal
2648 * reuse by getnewbuf() but does not prevent
2649 * disassociation (B_INVAL). Used to avoid deadlocks
2650 * against random (vp,loffset)s due to reassignment.
2652 * (0) - Lock the buffer blocking.
2655 findblk(struct vnode
*vp
, off_t loffset
, int flags
)
2660 lkflags
= LK_EXCLUSIVE
;
2661 if (flags
& FINDBLK_NBLOCK
)
2662 lkflags
|= LK_NOWAIT
;
2666 * Lookup. Ref the buf while holding v_token to prevent
2667 * reuse (but does not prevent diassociation).
2669 lwkt_gettoken_shared(&vp
->v_token
);
2670 bp
= buf_rb_hash_RB_LOOKUP(&vp
->v_rbhash_tree
, loffset
);
2672 lwkt_reltoken(&vp
->v_token
);
2676 lwkt_reltoken(&vp
->v_token
);
2679 * If testing only break and return bp, do not lock.
2681 if (flags
& FINDBLK_TEST
)
2685 * Lock the buffer, return an error if the lock fails.
2686 * (only FINDBLK_NBLOCK can cause the lock to fail).
2688 if (BUF_LOCK(bp
, lkflags
)) {
2689 atomic_subtract_int(&bp
->b_refs
, 1);
2690 /* bp = NULL; not needed */
2695 * Revalidate the locked buf before allowing it to be
2698 if (bp
->b_vp
== vp
&& bp
->b_loffset
== loffset
)
2700 atomic_subtract_int(&bp
->b_refs
, 1);
2707 if ((flags
& FINDBLK_REF
) == 0)
2708 atomic_subtract_int(&bp
->b_refs
, 1);
2715 * Similar to getblk() except only returns the buffer if it is
2716 * B_CACHE and requires no other manipulation. Otherwise NULL
2717 * is returned. NULL is also returned if GETBLK_NOWAIT is set
2718 * and the getblk() would block.
2720 * If B_RAM is set the buffer might be just fine, but we return
2721 * NULL anyway because we want the code to fall through to the
2722 * cluster read to issue more read-aheads. Otherwise read-ahead breaks.
2724 * If blksize is 0 the buffer cache buffer must already be fully
2727 * If blksize is non-zero getblk() will be used, allowing a buffer
2728 * to be reinstantiated from its VM backing store. The buffer must
2729 * still be fully cached after reinstantiation to be returned.
2732 getcacheblk(struct vnode
*vp
, off_t loffset
, int blksize
, int blkflags
)
2735 int fndflags
= (blkflags
& GETBLK_NOWAIT
) ? FINDBLK_NBLOCK
: 0;
2738 bp
= getblk(vp
, loffset
, blksize
, blkflags
, 0);
2740 if ((bp
->b_flags
& (B_INVAL
| B_CACHE
)) == B_CACHE
) {
2741 bp
->b_flags
&= ~B_AGE
;
2742 if (bp
->b_flags
& B_RAM
) {
2752 bp
= findblk(vp
, loffset
, fndflags
);
2754 if ((bp
->b_flags
& (B_INVAL
| B_CACHE
| B_RAM
)) ==
2756 bp
->b_flags
&= ~B_AGE
;
2770 * Get a block given a specified block and offset into a file/device.
2771 * B_INVAL may or may not be set on return. The caller should clear
2772 * B_INVAL prior to initiating a READ.
2774 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2775 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2776 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2777 * without doing any of those things the system will likely believe
2778 * the buffer to be valid (especially if it is not B_VMIO), and the
2779 * next getblk() will return the buffer with B_CACHE set.
2781 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2782 * an existing buffer.
2784 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2785 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2786 * and then cleared based on the backing VM. If the previous buffer is
2787 * non-0-sized but invalid, B_CACHE will be cleared.
2789 * If getblk() must create a new buffer, the new buffer is returned with
2790 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2791 * case it is returned with B_INVAL clear and B_CACHE set based on the
2794 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
2795 * B_CACHE bit is clear.
2797 * What this means, basically, is that the caller should use B_CACHE to
2798 * determine whether the buffer is fully valid or not and should clear
2799 * B_INVAL prior to issuing a read. If the caller intends to validate
2800 * the buffer by loading its data area with something, the caller needs
2801 * to clear B_INVAL. If the caller does this without issuing an I/O,
2802 * the caller should set B_CACHE ( as an optimization ), else the caller
2803 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2804 * a write attempt or if it was a successfull read. If the caller
2805 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2806 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2810 * GETBLK_PCATCH - catch signal if blocked, can cause NULL return
2811 * GETBLK_BHEAVY - heavy-weight buffer cache buffer
2814 getblk(struct vnode
*vp
, off_t loffset
, int size
, int blkflags
, int slptimeo
)
2817 int slpflags
= (blkflags
& GETBLK_PCATCH
) ? PCATCH
: 0;
2821 if (size
> MAXBSIZE
)
2822 panic("getblk: size(%d) > MAXBSIZE(%d)", size
, MAXBSIZE
);
2823 if (vp
->v_object
== NULL
)
2824 panic("getblk: vnode %p has no object!", vp
);
2827 if ((bp
= findblk(vp
, loffset
, FINDBLK_REF
| FINDBLK_TEST
)) != NULL
) {
2829 * The buffer was found in the cache, but we need to lock it.
2830 * We must acquire a ref on the bp to prevent reuse, but
2831 * this will not prevent disassociation (brelvp()) so we
2832 * must recheck (vp,loffset) after acquiring the lock.
2834 * Without the ref the buffer could potentially be reused
2835 * before we acquire the lock and create a deadlock
2836 * situation between the thread trying to reuse the buffer
2837 * and us due to the fact that we would wind up blocking
2838 * on a random (vp,loffset).
2840 if (BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_NOWAIT
)) {
2841 if (blkflags
& GETBLK_NOWAIT
) {
2845 lkflags
= LK_EXCLUSIVE
| LK_SLEEPFAIL
;
2846 if (blkflags
& GETBLK_PCATCH
)
2847 lkflags
|= LK_PCATCH
;
2848 error
= BUF_TIMELOCK(bp
, lkflags
, "getblk", slptimeo
);
2851 if (error
== ENOLCK
)
2855 /* buffer may have changed on us */
2860 * Once the buffer has been locked, make sure we didn't race
2861 * a buffer recyclement. Buffers that are no longer hashed
2862 * will have b_vp == NULL, so this takes care of that check
2865 if (bp
->b_vp
!= vp
|| bp
->b_loffset
!= loffset
) {
2867 kprintf("Warning buffer %p (vp %p loffset %lld) "
2869 bp
, vp
, (long long)loffset
);
2876 * If SZMATCH any pre-existing buffer must be of the requested
2877 * size or NULL is returned. The caller absolutely does not
2878 * want getblk() to bwrite() the buffer on a size mismatch.
2880 if ((blkflags
& GETBLK_SZMATCH
) && size
!= bp
->b_bcount
) {
2886 * All vnode-based buffers must be backed by a VM object.
2888 KKASSERT(bp
->b_flags
& B_VMIO
);
2889 KKASSERT(bp
->b_cmd
== BUF_CMD_DONE
);
2890 bp
->b_flags
&= ~B_AGE
;
2893 * Make sure that B_INVAL buffers do not have a cached
2894 * block number translation.
2896 if ((bp
->b_flags
& B_INVAL
) && (bp
->b_bio2
.bio_offset
!= NOOFFSET
)) {
2897 kprintf("Warning invalid buffer %p (vp %p loffset %lld)"
2898 " did not have cleared bio_offset cache\n",
2899 bp
, vp
, (long long)loffset
);
2900 clearbiocache(&bp
->b_bio2
);
2904 * The buffer is locked. B_CACHE is cleared if the buffer is
2907 if (bp
->b_flags
& B_INVAL
)
2908 bp
->b_flags
&= ~B_CACHE
;
2912 * Any size inconsistancy with a dirty buffer or a buffer
2913 * with a softupdates dependancy must be resolved. Resizing
2914 * the buffer in such circumstances can lead to problems.
2916 * Dirty or dependant buffers are written synchronously.
2917 * Other types of buffers are simply released and
2918 * reconstituted as they may be backed by valid, dirty VM
2919 * pages (but not marked B_DELWRI).
2921 * NFS NOTE: NFS buffers which straddle EOF are oddly-sized
2922 * and may be left over from a prior truncation (and thus
2923 * no longer represent the actual EOF point), so we
2924 * definitely do not want to B_NOCACHE the backing store.
2926 if (size
!= bp
->b_bcount
) {
2927 if (bp
->b_flags
& B_DELWRI
) {
2928 bp
->b_flags
|= B_RELBUF
;
2930 } else if (LIST_FIRST(&bp
->b_dep
)) {
2931 bp
->b_flags
|= B_RELBUF
;
2934 bp
->b_flags
|= B_RELBUF
;
2939 KKASSERT(size
<= bp
->b_kvasize
);
2940 KASSERT(bp
->b_loffset
!= NOOFFSET
,
2941 ("getblk: no buffer offset"));
2944 * A buffer with B_DELWRI set and B_CACHE clear must
2945 * be committed before we can return the buffer in
2946 * order to prevent the caller from issuing a read
2947 * ( due to B_CACHE not being set ) and overwriting
2950 * Most callers, including NFS and FFS, need this to
2951 * operate properly either because they assume they
2952 * can issue a read if B_CACHE is not set, or because
2953 * ( for example ) an uncached B_DELWRI might loop due
2954 * to softupdates re-dirtying the buffer. In the latter
2955 * case, B_CACHE is set after the first write completes,
2956 * preventing further loops.
2958 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2959 * above while extending the buffer, we cannot allow the
2960 * buffer to remain with B_CACHE set after the write
2961 * completes or it will represent a corrupt state. To
2962 * deal with this we set B_NOCACHE to scrap the buffer
2965 * XXX Should this be B_RELBUF instead of B_NOCACHE?
2966 * I'm not even sure this state is still possible
2967 * now that getblk() writes out any dirty buffers
2970 * We might be able to do something fancy, like setting
2971 * B_CACHE in bwrite() except if B_DELWRI is already set,
2972 * so the below call doesn't set B_CACHE, but that gets real
2973 * confusing. This is much easier.
2976 if ((bp
->b_flags
& (B_CACHE
|B_DELWRI
)) == B_DELWRI
) {
2977 kprintf("getblk: Warning, bp %p loff=%jx DELWRI set "
2978 "and CACHE clear, b_flags %08x\n",
2979 bp
, (uintmax_t)bp
->b_loffset
, bp
->b_flags
);
2980 bp
->b_flags
|= B_NOCACHE
;
2986 * Buffer is not in-core, create new buffer. The buffer
2987 * returned by getnewbuf() is locked. Note that the returned
2988 * buffer is also considered valid (not marked B_INVAL).
2990 * Calculating the offset for the I/O requires figuring out
2991 * the block size. We use DEV_BSIZE for VBLK or VCHR and
2992 * the mount's f_iosize otherwise. If the vnode does not
2993 * have an associated mount we assume that the passed size is
2996 * Note that vn_isdisk() cannot be used here since it may
2997 * return a failure for numerous reasons. Note that the
2998 * buffer size may be larger then the block size (the caller
2999 * will use block numbers with the proper multiple). Beware
3000 * of using any v_* fields which are part of unions. In
3001 * particular, in DragonFly the mount point overloading
3002 * mechanism uses the namecache only and the underlying
3003 * directory vnode is not a special case.
3006 vm_object_t repurpose
;
3008 if (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
)
3010 else if (vp
->v_mount
)
3011 bsize
= vp
->v_mount
->mnt_stat
.f_iosize
;
3015 maxsize
= size
+ (loffset
& PAGE_MASK
);
3016 maxsize
= imax(maxsize
, bsize
);
3020 * Allow repurposing. The returned buffer may contain VM
3021 * pages associated with its previous incarnation. These
3022 * pages must be repurposed for the new buffer (hopefully
3023 * without disturbing the KVM mapping).
3025 * WARNING! If repurpose != NULL on return, the buffer will
3026 * still contain some data from its prior
3027 * incarnation. We MUST properly dispose of this
3030 bp
= getnewbuf(blkflags
, slptimeo
, size
, maxsize
, &repurpose
);
3032 if (slpflags
|| slptimeo
)
3038 * Atomically insert the buffer into the hash, so that it can
3039 * be found by findblk().
3041 * If bgetvp() returns non-zero a collision occured, and the
3042 * bp will not be associated with the vnode.
3044 * Make sure the translation layer has been cleared.
3046 bp
->b_loffset
= loffset
;
3047 bp
->b_bio2
.bio_offset
= NOOFFSET
;
3048 /* bp->b_bio2.bio_next = NULL; */
3050 if (bgetvp(vp
, bp
, size
)) {
3052 bp
->b_flags
|= B_VMIO
;
3053 repurposebuf(bp
, 0);
3054 vm_object_drop(repurpose
);
3056 bp
->b_flags
|= B_INVAL
;
3062 * All vnode-based buffers must be backed by a VM object.
3064 KKASSERT(vp
->v_object
!= NULL
);
3065 bp
->b_flags
|= B_VMIO
;
3066 KKASSERT(bp
->b_cmd
== BUF_CMD_DONE
);
3069 * If we allowed repurposing of the buffer it will contain
3070 * free-but-held vm_page's, already kmapped, that can be
3071 * repurposed. The repurposebuf() code handles reassigning
3072 * those pages to the new (object, offsets) and dealing with
3073 * the case where the pages already exist.
3076 repurposebuf(bp
, size
);
3077 vm_object_drop(repurpose
);
3088 * Reacquire a buffer that was previously released to the locked queue,
3089 * or reacquire a buffer which is interlocked by having bioops->io_deallocate
3090 * set B_LOCKED (which handles the acquisition race).
3092 * To this end, either B_LOCKED must be set or the dependancy list must be
3096 regetblk(struct buf
*bp
)
3098 KKASSERT((bp
->b_flags
& B_LOCKED
) || LIST_FIRST(&bp
->b_dep
) != NULL
);
3099 BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_RETRY
);
3106 * Get an empty, disassociated buffer of given size. The buffer is
3107 * initially set to B_INVAL.
3109 * critical section protection is not required for the allocbuf()
3110 * call because races are impossible here.
3117 while ((bp
= getnewbuf(0, 0, size
, MAXBSIZE
, NULL
)) == NULL
)
3120 bp
->b_flags
|= B_INVAL
; /* b_dep cleared by getnewbuf() */
3128 * This code constitutes the buffer memory from either anonymous system
3129 * memory (in the case of non-VMIO operations) or from an associated
3130 * VM object (in the case of VMIO operations). This code is able to
3131 * resize a buffer up or down.
3133 * Note that this code is tricky, and has many complications to resolve
3134 * deadlock or inconsistant data situations. Tread lightly!!!
3135 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3136 * the caller. Calling this code willy nilly can result in the loss of
3139 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
3140 * B_CACHE for the non-VMIO case.
3142 * This routine does not need to be called from a critical section but you
3143 * must own the buffer.
3146 allocbuf(struct buf
*bp
, int size
)
3148 int newbsize
, mbsize
;
3151 if (BUF_REFCNT(bp
) == 0)
3152 panic("allocbuf: buffer not busy");
3154 if (bp
->b_kvasize
< size
)
3155 panic("allocbuf: buffer too small");
3157 if ((bp
->b_flags
& B_VMIO
) == 0) {
3161 * Just get anonymous memory from the kernel. Don't
3162 * mess with B_CACHE.
3164 mbsize
= roundup2(size
, DEV_BSIZE
);
3165 if (bp
->b_flags
& B_MALLOC
)
3168 newbsize
= round_page(size
);
3170 if (newbsize
< bp
->b_bufsize
) {
3172 * Malloced buffers are not shrunk
3174 if (bp
->b_flags
& B_MALLOC
) {
3176 bp
->b_bcount
= size
;
3178 kfree(bp
->b_data
, M_BIOBUF
);
3179 if (bp
->b_bufsize
) {
3180 atomic_subtract_long(&bufmallocspace
, bp
->b_bufsize
);
3184 bp
->b_data
= bp
->b_kvabase
;
3186 bp
->b_flags
&= ~B_MALLOC
;
3192 (vm_offset_t
) bp
->b_data
+ newbsize
,
3193 (vm_offset_t
) bp
->b_data
+ bp
->b_bufsize
);
3194 } else if (newbsize
> bp
->b_bufsize
) {
3196 * We only use malloced memory on the first allocation.
3197 * and revert to page-allocated memory when the buffer
3200 if ((bufmallocspace
< maxbufmallocspace
) &&
3201 (bp
->b_bufsize
== 0) &&
3202 (mbsize
<= PAGE_SIZE
/2)) {
3204 bp
->b_data
= kmalloc(mbsize
, M_BIOBUF
, M_WAITOK
);
3205 bp
->b_bufsize
= mbsize
;
3206 bp
->b_bcount
= size
;
3207 bp
->b_flags
|= B_MALLOC
;
3208 atomic_add_long(&bufmallocspace
, mbsize
);
3214 * If the buffer is growing on its other-than-first
3215 * allocation, then we revert to the page-allocation
3218 if (bp
->b_flags
& B_MALLOC
) {
3219 origbuf
= bp
->b_data
;
3220 origbufsize
= bp
->b_bufsize
;
3221 bp
->b_data
= bp
->b_kvabase
;
3222 if (bp
->b_bufsize
) {
3223 atomic_subtract_long(&bufmallocspace
,
3228 bp
->b_flags
&= ~B_MALLOC
;
3229 newbsize
= round_page(newbsize
);
3233 (vm_offset_t
) bp
->b_data
+ bp
->b_bufsize
,
3234 (vm_offset_t
) bp
->b_data
+ newbsize
);
3236 bcopy(origbuf
, bp
->b_data
, origbufsize
);
3237 kfree(origbuf
, M_BIOBUF
);
3244 newbsize
= roundup2(size
, DEV_BSIZE
);
3245 desiredpages
= ((int)(bp
->b_loffset
& PAGE_MASK
) +
3246 newbsize
+ PAGE_MASK
) >> PAGE_SHIFT
;
3247 KKASSERT(desiredpages
<= XIO_INTERNAL_PAGES
);
3249 if (bp
->b_flags
& B_MALLOC
)
3250 panic("allocbuf: VMIO buffer can't be malloced");
3252 * Set B_CACHE initially if buffer is 0 length or will become
3255 if (size
== 0 || bp
->b_bufsize
== 0)
3256 bp
->b_flags
|= B_CACHE
;
3258 if (newbsize
< bp
->b_bufsize
) {
3260 * DEV_BSIZE aligned new buffer size is less then the
3261 * DEV_BSIZE aligned existing buffer size. Figure out
3262 * if we have to remove any pages.
3264 if (desiredpages
< bp
->b_xio
.xio_npages
) {
3265 for (i
= desiredpages
; i
< bp
->b_xio
.xio_npages
; i
++) {
3267 * the page is not freed here -- it
3268 * is the responsibility of
3269 * vnode_pager_setsize
3271 m
= bp
->b_xio
.xio_pages
[i
];
3272 KASSERT(m
!= bogus_page
,
3273 ("allocbuf: bogus page found"));
3274 vm_page_busy_wait(m
, TRUE
, "biodep");
3275 bp
->b_xio
.xio_pages
[i
] = NULL
;
3276 vm_page_unwire(m
, 0);
3279 pmap_qremove((vm_offset_t
) trunc_page((vm_offset_t
)bp
->b_data
) +
3280 (desiredpages
<< PAGE_SHIFT
), (bp
->b_xio
.xio_npages
- desiredpages
));
3281 bp
->b_xio
.xio_npages
= desiredpages
;
3283 } else if (size
> bp
->b_bcount
) {
3285 * We are growing the buffer, possibly in a
3286 * byte-granular fashion.
3294 * Step 1, bring in the VM pages from the object,
3295 * allocating them if necessary. We must clear
3296 * B_CACHE if these pages are not valid for the
3297 * range covered by the buffer.
3302 vm_object_hold(obj
);
3303 while (bp
->b_xio
.xio_npages
< desiredpages
) {
3308 pi
= OFF_TO_IDX(bp
->b_loffset
) +
3309 bp
->b_xio
.xio_npages
;
3312 * Blocking on m->busy might lead to a
3315 * vm_fault->getpages->cluster_read->allocbuf
3317 m
= vm_page_lookup_busy_try(obj
, pi
, FALSE
,
3320 vm_page_sleep_busy(m
, FALSE
, "pgtblk");
3325 * note: must allocate system pages
3326 * since blocking here could intefere
3327 * with paging I/O, no matter which
3330 m
= bio_page_alloc(bp
, obj
, pi
, desiredpages
- bp
->b_xio
.xio_npages
);
3333 vm_page_flag_clear(m
, PG_ZERO
);
3335 bp
->b_flags
&= ~B_CACHE
;
3336 bp
->b_xio
.xio_pages
[bp
->b_xio
.xio_npages
] = m
;
3337 ++bp
->b_xio
.xio_npages
;
3343 * We found a page and were able to busy it.
3345 vm_page_flag_clear(m
, PG_ZERO
);
3348 bp
->b_xio
.xio_pages
[bp
->b_xio
.xio_npages
] = m
;
3349 ++bp
->b_xio
.xio_npages
;
3350 if (bp
->b_act_count
< m
->act_count
)
3351 bp
->b_act_count
= m
->act_count
;
3353 vm_object_drop(obj
);
3356 * Step 2. We've loaded the pages into the buffer,
3357 * we have to figure out if we can still have B_CACHE
3358 * set. Note that B_CACHE is set according to the
3359 * byte-granular range ( bcount and size ), not the
3360 * aligned range ( newbsize ).
3362 * The VM test is against m->valid, which is DEV_BSIZE
3363 * aligned. Needless to say, the validity of the data
3364 * needs to also be DEV_BSIZE aligned. Note that this
3365 * fails with NFS if the server or some other client
3366 * extends the file's EOF. If our buffer is resized,
3367 * B_CACHE may remain set! XXX
3370 toff
= bp
->b_bcount
;
3371 tinc
= PAGE_SIZE
- ((bp
->b_loffset
+ toff
) & PAGE_MASK
);
3373 while ((bp
->b_flags
& B_CACHE
) && toff
< size
) {
3376 if (tinc
> (size
- toff
))
3379 pi
= ((bp
->b_loffset
& PAGE_MASK
) + toff
) >>
3387 bp
->b_xio
.xio_pages
[pi
]
3394 * Step 3, fixup the KVM pmap. Remember that
3395 * bp->b_data is relative to bp->b_loffset, but
3396 * bp->b_loffset may be offset into the first page.
3398 bp
->b_data
= (caddr_t
)
3399 trunc_page((vm_offset_t
)bp
->b_data
);
3400 pmap_qenter((vm_offset_t
)bp
->b_data
,
3401 bp
->b_xio
.xio_pages
, bp
->b_xio
.xio_npages
);
3402 bp
->b_data
= (caddr_t
)((vm_offset_t
)bp
->b_data
|
3403 (vm_offset_t
)(bp
->b_loffset
& PAGE_MASK
));
3405 atomic_add_long(&bufspace
, newbsize
- bp
->b_bufsize
);
3408 /* adjust space use on already-dirty buffer */
3409 if (bp
->b_flags
& B_DELWRI
) {
3410 /* dirtykvaspace unchanged */
3411 atomic_add_long(&dirtybufspace
, newbsize
- bp
->b_bufsize
);
3412 if (bp
->b_flags
& B_HEAVY
) {
3413 atomic_add_long(&dirtybufspacehw
,
3414 newbsize
- bp
->b_bufsize
);
3417 bp
->b_bufsize
= newbsize
; /* actual buffer allocation */
3418 bp
->b_bcount
= size
; /* requested buffer size */
3423 * repurposebuf() (VMIO only)
3425 * This performs a function similar to allocbuf() but the passed-in buffer
3426 * may contain some detrius from its previous incarnation in the form of
3427 * the page array. We try to repurpose the underlying pages.
3429 * This code is nominally called to recycle buffer cache buffers AND (if
3430 * they are clean) to also recycle their underlying pages. We currently
3431 * can only recycle unmapped, clean pages. The code is called when buffer
3432 * cache 'newbuf' bandwidth exceeds (bufrate_cache) bytes per second.
3436 repurposebuf(struct buf
*bp
, int size
)
3445 int must_reenter
= 0;
3446 long deaccumulate
= 0;
3449 KKASSERT((bp
->b_flags
& (B_VMIO
| B_DELWRI
| B_MALLOC
)) == B_VMIO
);
3450 if (BUF_REFCNT(bp
) == 0)
3451 panic("repurposebuf: buffer not busy");
3453 if (bp
->b_kvasize
< size
)
3454 panic("repurposebuf: buffer too small");
3456 newbsize
= roundup2(size
, DEV_BSIZE
);
3457 desiredpages
= ((int)(bp
->b_loffset
& PAGE_MASK
) +
3458 newbsize
+ PAGE_MASK
) >> PAGE_SHIFT
;
3459 KKASSERT(desiredpages
<= XIO_INTERNAL_PAGES
);
3462 * Buffer starts out 0-length with B_CACHE set. We will clear
3463 * As we check the backing store we will clear B_CACHE if necessary.
3465 atomic_add_long(&bufspace
, newbsize
- bp
->b_bufsize
);
3468 bp
->b_flags
|= B_CACHE
;
3471 obj
= bp
->b_vp
->v_object
;
3472 vm_object_hold(obj
);
3478 * Step 1, bring in the VM pages from the object, repurposing or
3479 * allocating them if necessary. We must clear B_CACHE if these
3480 * pages are not valid for the range covered by the buffer.
3482 * We are growing the buffer, possibly in a byte-granular fashion.
3484 for (i
= 0; i
< desiredpages
; ++i
) {
3489 pi
= OFF_TO_IDX(bp
->b_loffset
) + i
;
3492 * Blocking on m->busy might lead to a
3495 * vm_fault->getpages->cluster_read->allocbuf
3497 m
= (i
< bp
->b_xio
.xio_npages
) ? bp
->b_xio
.xio_pages
[i
] : NULL
;
3498 bp
->b_xio
.xio_pages
[i
] = NULL
;
3499 KASSERT(m
!= bogus_page
, ("repurposebuf: bogus page found"));
3500 m
= vm_page_repurpose(obj
, pi
, FALSE
, &error
, m
,
3501 &must_reenter
, &iswired
);
3504 vm_page_sleep_busy(m
, FALSE
, "pgtblk");
3510 * note: must allocate system pages
3511 * since blocking here could intefere
3512 * with paging I/O, no matter which
3516 m
= bio_page_alloc(bp
, obj
, pi
, desiredpages
- i
);
3519 vm_page_flag_clear(m
, PG_ZERO
);
3521 bp
->b_flags
&= ~B_CACHE
;
3522 bp
->b_xio
.xio_pages
[i
] = m
;
3524 deaccumulate
+= PAGE_SIZE
;
3531 deaccumulate
+= PAGE_SIZE
;
3534 * We found a page and were able to busy it.
3536 vm_page_flag_clear(m
, PG_ZERO
);
3540 bp
->b_xio
.xio_pages
[i
] = m
;
3541 if (bp
->b_act_count
< m
->act_count
)
3542 bp
->b_act_count
= m
->act_count
;
3545 vm_object_drop(obj
);
3548 * Even though its a new buffer, any pages already in the VM
3549 * page cache should not count towards I/O bandwidth.
3552 atomic_add_long(&bufcache_bw_accum
, -deaccumulate
);
3555 * Clean-up any loose pages.
3557 while (i
< bp
->b_xio
.xio_npages
) {
3558 m
= bp
->b_xio
.xio_pages
[i
];
3559 KASSERT(m
!= bogus_page
, ("repurposebuf: bogus page found"));
3560 vm_page_busy_wait(m
, TRUE
, "biodep");
3561 bp
->b_xio
.xio_pages
[i
] = NULL
;
3562 vm_page_unwire(m
, 0);
3566 if (desiredpages
< bp
->b_xio
.xio_npages
) {
3567 pmap_qremove((vm_offset_t
)trunc_page((vm_offset_t
)bp
->b_data
) +
3568 (desiredpages
<< PAGE_SHIFT
),
3569 (bp
->b_xio
.xio_npages
- desiredpages
));
3571 bp
->b_xio
.xio_npages
= desiredpages
;
3574 * Step 2. We've loaded the pages into the buffer,
3575 * we have to figure out if we can still have B_CACHE
3576 * set. Note that B_CACHE is set according to the
3577 * byte-granular range ( bcount and size ), not the
3578 * aligned range ( newbsize ).
3580 * The VM test is against m->valid, which is DEV_BSIZE
3581 * aligned. Needless to say, the validity of the data
3582 * needs to also be DEV_BSIZE aligned. Note that this
3583 * fails with NFS if the server or some other client
3584 * extends the file's EOF. If our buffer is resized,
3585 * B_CACHE may remain set! XXX
3587 toff
= bp
->b_bcount
;
3588 tinc
= PAGE_SIZE
- ((bp
->b_loffset
+ toff
) & PAGE_MASK
);
3590 while ((bp
->b_flags
& B_CACHE
) && toff
< size
) {
3593 if (tinc
> (size
- toff
))
3596 pi
= ((bp
->b_loffset
& PAGE_MASK
) + toff
) >> PAGE_SHIFT
;
3598 vfs_buf_test_cache(bp
, bp
->b_loffset
, toff
,
3599 tinc
, bp
->b_xio
.xio_pages
[pi
]);
3605 * Step 3, fixup the KVM pmap. Remember that
3606 * bp->b_data is relative to bp->b_loffset, but
3607 * bp->b_loffset may be offset into the first page.
3609 bp
->b_data
= (caddr_t
)trunc_page((vm_offset_t
)bp
->b_data
);
3611 pmap_qenter((vm_offset_t
)bp
->b_data
,
3612 bp
->b_xio
.xio_pages
, bp
->b_xio
.xio_npages
);
3614 atomic_add_long(&repurposedspace
, newbsize
);
3616 bp
->b_data
= (caddr_t
)((vm_offset_t
)bp
->b_data
|
3617 (vm_offset_t
)(bp
->b_loffset
& PAGE_MASK
));
3619 if (newbsize
< bp
->b_bufsize
)
3621 bp
->b_bufsize
= newbsize
; /* actual buffer allocation */
3622 bp
->b_bcount
= size
; /* requested buffer size */
3628 * Wait for buffer I/O completion, returning error status. B_EINTR
3629 * is converted into an EINTR error but not cleared (since a chain
3630 * of biowait() calls may occur).
3632 * On return bpdone() will have been called but the buffer will remain
3633 * locked and will not have been brelse()'d.
3635 * NOTE! If a timeout is specified and ETIMEDOUT occurs the I/O is
3636 * likely still in progress on return.
3638 * NOTE! This operation is on a BIO, not a BUF.
3640 * NOTE! BIO_DONE is cleared by vn_strategy()
3643 _biowait(struct bio
*bio
, const char *wmesg
, int to
)
3645 struct buf
*bp
= bio
->bio_buf
;
3650 KKASSERT(bio
== &bp
->b_bio1
);
3652 flags
= bio
->bio_flags
;
3653 if (flags
& BIO_DONE
)
3655 nflags
= flags
| BIO_WANT
;
3656 tsleep_interlock(bio
, 0);
3657 if (atomic_cmpset_int(&bio
->bio_flags
, flags
, nflags
)) {
3659 error
= tsleep(bio
, PINTERLOCKED
, wmesg
, to
);
3660 else if (bp
->b_cmd
== BUF_CMD_READ
)
3661 error
= tsleep(bio
, PINTERLOCKED
, "biord", to
);
3663 error
= tsleep(bio
, PINTERLOCKED
, "biowr", to
);
3665 kprintf("tsleep error biowait %d\n", error
);
3674 KKASSERT(bp
->b_cmd
== BUF_CMD_DONE
);
3675 bio
->bio_flags
&= ~(BIO_DONE
| BIO_SYNC
);
3676 if (bp
->b_flags
& B_EINTR
)
3678 if (bp
->b_flags
& B_ERROR
)
3679 return (bp
->b_error
? bp
->b_error
: EIO
);
3684 biowait(struct bio
*bio
, const char *wmesg
)
3686 return(_biowait(bio
, wmesg
, 0));
3690 biowait_timeout(struct bio
*bio
, const char *wmesg
, int to
)
3692 return(_biowait(bio
, wmesg
, to
));
3696 * This associates a tracking count with an I/O. vn_strategy() and
3697 * dev_dstrategy() do this automatically but there are a few cases
3698 * where a vnode or device layer is bypassed when a block translation
3699 * is cached. In such cases bio_start_transaction() may be called on
3700 * the bypassed layers so the system gets an I/O in progress indication
3701 * for those higher layers.
3704 bio_start_transaction(struct bio
*bio
, struct bio_track
*track
)
3706 bio
->bio_track
= track
;
3707 bio_track_ref(track
);
3708 dsched_buf_enter(bio
->bio_buf
); /* might stack */
3712 * Initiate I/O on a vnode.
3714 * SWAPCACHE OPERATION:
3716 * Real buffer cache buffers have a non-NULL bp->b_vp. Unfortunately
3717 * devfs also uses b_vp for fake buffers so we also have to check
3718 * that B_PAGING is 0. In this case the passed 'vp' is probably the
3719 * underlying block device. The swap assignments are related to the
3720 * buffer cache buffer's b_vp, not the passed vp.
3722 * The passed vp == bp->b_vp only in the case where the strategy call
3723 * is made on the vp itself for its own buffers (a regular file or
3724 * block device vp). The filesystem usually then re-calls vn_strategy()
3725 * after translating the request to an underlying device.
3727 * Cluster buffers set B_CLUSTER and the passed vp is the vp of the
3728 * underlying buffer cache buffers.
3730 * We can only deal with page-aligned buffers at the moment, because
3731 * we can't tell what the real dirty state for pages straddling a buffer
3734 * In order to call swap_pager_strategy() we must provide the VM object
3735 * and base offset for the underlying buffer cache pages so it can find
3739 vn_strategy(struct vnode
*vp
, struct bio
*bio
)
3741 struct bio_track
*track
;
3742 struct buf
*bp
= bio
->bio_buf
;
3744 KKASSERT(bp
->b_cmd
!= BUF_CMD_DONE
);
3747 * Set when an I/O is issued on the bp. Cleared by consumers
3748 * (aka HAMMER), allowing the consumer to determine if I/O had
3749 * actually occurred.
3751 bp
->b_flags
|= B_IOISSUED
;
3754 * Handle the swap cache intercept.
3756 if (vn_cache_strategy(vp
, bio
))
3760 * Otherwise do the operation through the filesystem
3762 if (bp
->b_cmd
== BUF_CMD_READ
)
3763 track
= &vp
->v_track_read
;
3765 track
= &vp
->v_track_write
;
3766 KKASSERT((bio
->bio_flags
& BIO_DONE
) == 0);
3767 bio
->bio_track
= track
;
3768 bio_track_ref(track
);
3769 dsched_buf_enter(bp
); /* might stack */
3770 vop_strategy(*vp
->v_ops
, vp
, bio
);
3773 static void vn_cache_strategy_callback(struct bio
*bio
);
3776 vn_cache_strategy(struct vnode
*vp
, struct bio
*bio
)
3778 struct buf
*bp
= bio
->bio_buf
;
3785 * Stop using swapcache if paniced, dumping, or dumped
3787 if (panicstr
|| dumping
)
3791 * Is this buffer cache buffer suitable for reading from
3794 if (vm_swapcache_read_enable
== 0 ||
3795 bp
->b_cmd
!= BUF_CMD_READ
||
3796 ((bp
->b_flags
& B_CLUSTER
) == 0 &&
3797 (bp
->b_vp
== NULL
|| (bp
->b_flags
& B_PAGING
))) ||
3798 ((int)bp
->b_loffset
& PAGE_MASK
) != 0 ||
3799 (bp
->b_bcount
& PAGE_MASK
) != 0) {
3804 * Figure out the original VM object (it will match the underlying
3805 * VM pages). Note that swap cached data uses page indices relative
3806 * to that object, not relative to bio->bio_offset.
3808 if (bp
->b_flags
& B_CLUSTER
)
3809 object
= vp
->v_object
;
3811 object
= bp
->b_vp
->v_object
;
3814 * In order to be able to use the swap cache all underlying VM
3815 * pages must be marked as such, and we can't have any bogus pages.
3817 for (i
= 0; i
< bp
->b_xio
.xio_npages
; ++i
) {
3818 m
= bp
->b_xio
.xio_pages
[i
];
3819 if ((m
->flags
& PG_SWAPPED
) == 0)
3821 if (m
== bogus_page
)
3826 * If we are good then issue the I/O using swap_pager_strategy().
3828 * We can only do this if the buffer actually supports object-backed
3829 * I/O. If it doesn't npages will be 0.
3831 if (i
&& i
== bp
->b_xio
.xio_npages
) {
3832 m
= bp
->b_xio
.xio_pages
[0];
3833 nbio
= push_bio(bio
);
3834 nbio
->bio_done
= vn_cache_strategy_callback
;
3835 nbio
->bio_offset
= ptoa(m
->pindex
);
3836 KKASSERT(m
->object
== object
);
3837 swap_pager_strategy(object
, nbio
);
3844 * This is a bit of a hack but since the vn_cache_strategy() function can
3845 * override a VFS's strategy function we must make sure that the bio, which
3846 * is probably bio2, doesn't leak an unexpected offset value back to the
3847 * filesystem. The filesystem (e.g. UFS) might otherwise assume that the
3848 * bio went through its own file strategy function and the the bio2 offset
3849 * is a cached disk offset when, in fact, it isn't.
3852 vn_cache_strategy_callback(struct bio
*bio
)
3854 bio
->bio_offset
= NOOFFSET
;
3855 biodone(pop_bio(bio
));
3861 * Finish I/O on a buffer after all BIOs have been processed.
3862 * Called when the bio chain is exhausted or by biowait. If called
3863 * by biowait, elseit is typically 0.
3865 * bpdone is also responsible for setting B_CACHE in a B_VMIO bp.
3866 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3867 * assuming B_INVAL is clear.
3869 * For the VMIO case, we set B_CACHE if the op was a read and no
3870 * read error occured, or if the op was a write. B_CACHE is never
3871 * set if the buffer is invalid or otherwise uncacheable.
3873 * bpdone does not mess with B_INVAL, allowing the I/O routine or the
3874 * initiator to leave B_INVAL set to brelse the buffer out of existance
3875 * in the biodone routine.
3877 * bpdone is responsible for calling bundirty() on the buffer after a
3878 * successful write. We previously did this prior to initiating the
3879 * write under the assumption that the buffer might be dirtied again
3880 * while the write was in progress, however doing it before-hand creates
3881 * a race condition prior to the call to vn_strategy() where the
3882 * filesystem may not be aware that a dirty buffer is present.
3883 * It should not be possible for the buffer or its underlying pages to
3884 * be redirtied prior to bpdone()'s unbusying of the underlying VM
3888 bpdone(struct buf
*bp
, int elseit
)
3892 KASSERT(BUF_REFCNTNB(bp
) > 0,
3893 ("bpdone: bp %p not busy %d", bp
, BUF_REFCNTNB(bp
)));
3894 KASSERT(bp
->b_cmd
!= BUF_CMD_DONE
,
3895 ("bpdone: bp %p already done!", bp
));
3898 * No more BIOs are left. All completion functions have been dealt
3899 * with, now we clean up the buffer.
3902 bp
->b_cmd
= BUF_CMD_DONE
;
3905 * Only reads and writes are processed past this point.
3907 if (cmd
!= BUF_CMD_READ
&& cmd
!= BUF_CMD_WRITE
) {
3908 if (cmd
== BUF_CMD_FREEBLKS
)
3909 bp
->b_flags
|= B_NOCACHE
;
3916 * A failed write must re-dirty the buffer unless B_INVAL
3919 * A successful write must clear the dirty flag. This is done after
3920 * the write to ensure that the buffer remains on the vnode's dirty
3921 * list for filesystem interlocks / checks until the write is actually
3922 * complete. HAMMER2 is sensitive to this issue.
3924 * Only applicable to normal buffers (with VPs). vinum buffers may
3927 * Must be done prior to calling buf_complete() as the callback might
3928 * re-dirty the buffer.
3930 if (cmd
== BUF_CMD_WRITE
) {
3931 if ((bp
->b_flags
& (B_ERROR
| B_INVAL
)) == B_ERROR
) {
3932 bp
->b_flags
&= ~B_NOCACHE
;
3942 * Warning: softupdates may re-dirty the buffer, and HAMMER can do
3943 * a lot worse. XXX - move this above the clearing of b_cmd
3945 if (LIST_FIRST(&bp
->b_dep
) != NULL
)
3948 if (bp
->b_flags
& B_VMIO
) {
3954 struct vnode
*vp
= bp
->b_vp
;
3958 #if defined(VFS_BIO_DEBUG)
3959 if (vp
->v_auxrefs
== 0)
3960 panic("bpdone: zero vnode hold count");
3961 if ((vp
->v_flag
& VOBJBUF
) == 0)
3962 panic("bpdone: vnode is not setup for merged cache");
3965 foff
= bp
->b_loffset
;
3966 KASSERT(foff
!= NOOFFSET
, ("bpdone: no buffer offset"));
3967 KASSERT(obj
!= NULL
, ("bpdone: missing VM object"));
3969 #if defined(VFS_BIO_DEBUG)
3970 if (obj
->paging_in_progress
< bp
->b_xio
.xio_npages
) {
3971 kprintf("bpdone: paging in progress(%d) < "
3972 "bp->b_xio.xio_npages(%d)\n",
3973 obj
->paging_in_progress
,
3974 bp
->b_xio
.xio_npages
);
3979 * Set B_CACHE if the op was a normal read and no error
3980 * occured. B_CACHE is set for writes in the b*write()
3983 iosize
= bp
->b_bcount
- bp
->b_resid
;
3984 if (cmd
== BUF_CMD_READ
&&
3985 (bp
->b_flags
& (B_INVAL
|B_NOCACHE
|B_ERROR
)) == 0) {
3986 bp
->b_flags
|= B_CACHE
;
3989 vm_object_hold(obj
);
3990 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3994 resid
= ((foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
) - foff
;
3999 * cleanup bogus pages, restoring the originals. Since
4000 * the originals should still be wired, we don't have
4001 * to worry about interrupt/freeing races destroying
4002 * the VM object association.
4004 m
= bp
->b_xio
.xio_pages
[i
];
4005 if (m
== bogus_page
) {
4006 if ((bp
->b_flags
& B_HASBOGUS
) == 0)
4007 panic("bpdone: bp %p corrupt bogus", bp
);
4008 m
= vm_page_lookup(obj
, OFF_TO_IDX(foff
));
4010 panic("bpdone: page disappeared");
4011 bp
->b_xio
.xio_pages
[i
] = m
;
4016 #if defined(VFS_BIO_DEBUG)
4017 if (OFF_TO_IDX(foff
) != m
->pindex
) {
4018 kprintf("bpdone: foff(%lu)/m->pindex(%ld) "
4020 (unsigned long)foff
, (long)m
->pindex
);
4025 * In the write case, the valid and clean bits are
4026 * already changed correctly (see bdwrite()), so we
4027 * only need to do this here in the read case.
4029 vm_page_busy_wait(m
, FALSE
, "bpdpgw");
4030 if (cmd
== BUF_CMD_READ
&& isbogus
== 0 && resid
> 0)
4031 vfs_clean_one_page(bp
, i
, m
);
4032 vm_page_flag_clear(m
, PG_ZERO
);
4035 * when debugging new filesystems or buffer I/O
4036 * methods, this is the most common error that pops
4037 * up. if you see this, you have not set the page
4038 * busy flag correctly!!!
4041 kprintf("bpdone: page busy < 0, "
4042 "pindex: %d, foff: 0x(%x,%x), "
4043 "resid: %d, index: %d\n",
4044 (int) m
->pindex
, (int)(foff
>> 32),
4045 (int) foff
& 0xffffffff, resid
, i
);
4046 if (!vn_isdisk(vp
, NULL
))
4047 kprintf(" iosize: %ld, loffset: %lld, "
4048 "flags: 0x%08x, npages: %d\n",
4049 bp
->b_vp
->v_mount
->mnt_stat
.f_iosize
,
4050 (long long)bp
->b_loffset
,
4051 bp
->b_flags
, bp
->b_xio
.xio_npages
);
4053 kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
4054 (long long)bp
->b_loffset
,
4055 bp
->b_flags
, bp
->b_xio
.xio_npages
);
4056 kprintf(" valid: 0x%x, dirty: 0x%x, "
4060 panic("bpdone: page busy < 0");
4062 vm_page_io_finish(m
);
4064 vm_object_pip_wakeup(obj
);
4065 foff
= (foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
;
4068 if (bp
->b_flags
& B_HASBOGUS
) {
4069 pmap_qenter(trunc_page((vm_offset_t
)bp
->b_data
),
4070 bp
->b_xio
.xio_pages
, bp
->b_xio
.xio_npages
);
4071 bp
->b_flags
&= ~B_HASBOGUS
;
4073 vm_object_drop(obj
);
4077 * Finish up by releasing the buffer. There are no more synchronous
4078 * or asynchronous completions, those were handled by bio_done
4082 if (bp
->b_flags
& (B_NOCACHE
|B_INVAL
|B_ERROR
|B_RELBUF
))
4093 biodone(struct bio
*bio
)
4095 struct buf
*bp
= bio
->bio_buf
;
4097 runningbufwakeup(bp
);
4100 * Run up the chain of BIO's. Leave b_cmd intact for the duration.
4103 biodone_t
*done_func
;
4104 struct bio_track
*track
;
4107 * BIO tracking. Most but not all BIOs are tracked.
4109 if ((track
= bio
->bio_track
) != NULL
) {
4110 bio_track_rel(track
);
4111 bio
->bio_track
= NULL
;
4115 * A bio_done function terminates the loop. The function
4116 * will be responsible for any further chaining and/or
4117 * buffer management.
4119 * WARNING! The done function can deallocate the buffer!
4121 if ((done_func
= bio
->bio_done
) != NULL
) {
4122 bio
->bio_done
= NULL
;
4126 bio
= bio
->bio_prev
;
4130 * If we've run out of bio's do normal [a]synchronous completion.
4136 * Synchronous biodone - this terminates a synchronous BIO.
4138 * bpdone() is called with elseit=FALSE, leaving the buffer completed
4139 * but still locked. The caller must brelse() the buffer after waiting
4143 biodone_sync(struct bio
*bio
)
4145 struct buf
*bp
= bio
->bio_buf
;
4149 KKASSERT(bio
== &bp
->b_bio1
);
4153 flags
= bio
->bio_flags
;
4154 nflags
= (flags
| BIO_DONE
) & ~BIO_WANT
;
4156 if (atomic_cmpset_int(&bio
->bio_flags
, flags
, nflags
)) {
4157 if (flags
& BIO_WANT
)
4167 * This routine is called in lieu of iodone in the case of
4168 * incomplete I/O. This keeps the busy status for pages
4172 vfs_unbusy_pages(struct buf
*bp
)
4176 runningbufwakeup(bp
);
4178 if (bp
->b_flags
& B_VMIO
) {
4179 struct vnode
*vp
= bp
->b_vp
;
4183 vm_object_hold(obj
);
4185 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
4186 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
4189 * When restoring bogus changes the original pages
4190 * should still be wired, so we are in no danger of
4191 * losing the object association and do not need
4192 * critical section protection particularly.
4194 if (m
== bogus_page
) {
4195 m
= vm_page_lookup(obj
, OFF_TO_IDX(bp
->b_loffset
) + i
);
4197 panic("vfs_unbusy_pages: page missing");
4199 bp
->b_xio
.xio_pages
[i
] = m
;
4201 vm_page_busy_wait(m
, FALSE
, "bpdpgw");
4202 vm_page_flag_clear(m
, PG_ZERO
);
4203 vm_page_io_finish(m
);
4205 vm_object_pip_wakeup(obj
);
4207 if (bp
->b_flags
& B_HASBOGUS
) {
4208 pmap_qenter(trunc_page((vm_offset_t
)bp
->b_data
),
4209 bp
->b_xio
.xio_pages
, bp
->b_xio
.xio_npages
);
4210 bp
->b_flags
&= ~B_HASBOGUS
;
4212 vm_object_drop(obj
);
4219 * This routine is called before a device strategy routine.
4220 * It is used to tell the VM system that paging I/O is in
4221 * progress, and treat the pages associated with the buffer
4222 * almost as being PG_BUSY. Also the object 'paging_in_progress'
4223 * flag is handled to make sure that the object doesn't become
4226 * Since I/O has not been initiated yet, certain buffer flags
4227 * such as B_ERROR or B_INVAL may be in an inconsistant state
4228 * and should be ignored.
4231 vfs_busy_pages(struct vnode
*vp
, struct buf
*bp
)
4234 struct lwp
*lp
= curthread
->td_lwp
;
4237 * The buffer's I/O command must already be set. If reading,
4238 * B_CACHE must be 0 (double check against callers only doing
4239 * I/O when B_CACHE is 0).
4241 KKASSERT(bp
->b_cmd
!= BUF_CMD_DONE
);
4242 KKASSERT(bp
->b_cmd
== BUF_CMD_WRITE
|| (bp
->b_flags
& B_CACHE
) == 0);
4244 if (bp
->b_flags
& B_VMIO
) {
4248 KASSERT(bp
->b_loffset
!= NOOFFSET
,
4249 ("vfs_busy_pages: no buffer offset"));
4252 * Busy all the pages. We have to busy them all at once
4253 * to avoid deadlocks.
4256 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
4257 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
4259 if (vm_page_busy_try(m
, FALSE
)) {
4260 vm_page_sleep_busy(m
, FALSE
, "vbpage");
4262 vm_page_wakeup(bp
->b_xio
.xio_pages
[i
]);
4268 * Setup for I/O, soft-busy the page right now because
4269 * the next loop may block.
4271 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
4272 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
4274 vm_page_flag_clear(m
, PG_ZERO
);
4275 if ((bp
->b_flags
& B_CLUSTER
) == 0) {
4276 vm_object_pip_add(obj
, 1);
4277 vm_page_io_start(m
);
4282 * Adjust protections for I/O and do bogus-page mapping.
4283 * Assume that vm_page_protect() can block (it can block
4284 * if VM_PROT_NONE, don't take any chances regardless).
4286 * In particular note that for writes we must incorporate
4287 * page dirtyness from the VM system into the buffer's
4290 * For reads we theoretically must incorporate page dirtyness
4291 * from the VM system to determine if the page needs bogus
4292 * replacement, but we shortcut the test by simply checking
4293 * that all m->valid bits are set, indicating that the page
4294 * is fully valid and does not need to be re-read. For any
4295 * VM system dirtyness the page will also be fully valid
4296 * since it was mapped at one point.
4299 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
4300 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
4302 vm_page_flag_clear(m
, PG_ZERO
); /* XXX */
4303 if (bp
->b_cmd
== BUF_CMD_WRITE
) {
4305 * When readying a vnode-backed buffer for
4306 * a write we must zero-fill any invalid
4307 * portions of the backing VM pages, mark
4308 * it valid and clear related dirty bits.
4310 * vfs_clean_one_page() incorporates any
4311 * VM dirtyness and updates the b_dirtyoff
4312 * range (after we've made the page RO).
4314 * It is also expected that the pmap modified
4315 * bit has already been cleared by the
4316 * vm_page_protect(). We may not be able
4317 * to clear all dirty bits for a page if it
4318 * was also memory mapped (NFS).
4320 * Finally be sure to unassign any swap-cache
4321 * backing store as it is now stale.
4323 vm_page_protect(m
, VM_PROT_READ
);
4324 vfs_clean_one_page(bp
, i
, m
);
4325 swap_pager_unswapped(m
);
4326 } else if (m
->valid
== VM_PAGE_BITS_ALL
) {
4328 * When readying a vnode-backed buffer for
4329 * read we must replace any dirty pages with
4330 * a bogus page so dirty data is not destroyed
4331 * when filling gaps.
4333 * To avoid testing whether the page is
4334 * dirty we instead test that the page was
4335 * at some point mapped (m->valid fully
4336 * valid) with the understanding that
4337 * this also covers the dirty case.
4339 bp
->b_xio
.xio_pages
[i
] = bogus_page
;
4340 bp
->b_flags
|= B_HASBOGUS
;
4342 } else if (m
->valid
& m
->dirty
) {
4344 * This case should not occur as partial
4345 * dirtyment can only happen if the buffer
4346 * is B_CACHE, and this code is not entered
4347 * if the buffer is B_CACHE.
4349 kprintf("Warning: vfs_busy_pages - page not "
4350 "fully valid! loff=%jx bpf=%08x "
4351 "idx=%d val=%02x dir=%02x\n",
4352 (uintmax_t)bp
->b_loffset
, bp
->b_flags
,
4353 i
, m
->valid
, m
->dirty
);
4354 vm_page_protect(m
, VM_PROT_NONE
);
4357 * The page is not valid and can be made
4360 vm_page_protect(m
, VM_PROT_NONE
);
4365 pmap_qenter(trunc_page((vm_offset_t
)bp
->b_data
),
4366 bp
->b_xio
.xio_pages
, bp
->b_xio
.xio_npages
);
4371 * This is the easiest place to put the process accounting for the I/O
4375 if (bp
->b_cmd
== BUF_CMD_READ
)
4376 lp
->lwp_ru
.ru_inblock
++;
4378 lp
->lwp_ru
.ru_oublock
++;
4383 * Tell the VM system that the pages associated with this buffer
4384 * are clean. This is used for delayed writes where the data is
4385 * going to go to disk eventually without additional VM intevention.
4387 * NOTE: While we only really need to clean through to b_bcount, we
4388 * just go ahead and clean through to b_bufsize.
4391 vfs_clean_pages(struct buf
*bp
)
4396 if ((bp
->b_flags
& B_VMIO
) == 0)
4399 KASSERT(bp
->b_loffset
!= NOOFFSET
,
4400 ("vfs_clean_pages: no buffer offset"));
4402 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
4403 m
= bp
->b_xio
.xio_pages
[i
];
4404 vfs_clean_one_page(bp
, i
, m
);
4409 * vfs_clean_one_page:
4411 * Set the valid bits and clear the dirty bits in a page within a
4412 * buffer. The range is restricted to the buffer's size and the
4413 * buffer's logical offset might index into the first page.
4415 * The caller has busied or soft-busied the page and it is not mapped,
4416 * test and incorporate the dirty bits into b_dirtyoff/end before
4417 * clearing them. Note that we need to clear the pmap modified bits
4418 * after determining the the page was dirty, vm_page_set_validclean()
4419 * does not do it for us.
4421 * This routine is typically called after a read completes (dirty should
4422 * be zero in that case as we are not called on bogus-replace pages),
4423 * or before a write is initiated.
4426 vfs_clean_one_page(struct buf
*bp
, int pageno
, vm_page_t m
)
4434 * Calculate offset range within the page but relative to buffer's
4435 * loffset. loffset might be offset into the first page.
4437 xoff
= (int)bp
->b_loffset
& PAGE_MASK
; /* loffset offset into pg 0 */
4438 bcount
= bp
->b_bcount
+ xoff
; /* offset adjusted */
4444 soff
= (pageno
<< PAGE_SHIFT
);
4445 eoff
= soff
+ PAGE_SIZE
;
4453 * Test dirty bits and adjust b_dirtyoff/end.
4455 * If dirty pages are incorporated into the bp any prior
4456 * B_NEEDCOMMIT state (NFS) must be cleared because the
4457 * caller has not taken into account the new dirty data.
4459 * If the page was memory mapped the dirty bits might go beyond the
4460 * end of the buffer, but we can't really make the assumption that
4461 * a file EOF straddles the buffer (even though this is the case for
4462 * NFS if B_NEEDCOMMIT is also set). So for the purposes of clearing
4463 * B_NEEDCOMMIT we only test the dirty bits covered by the buffer.
4464 * This also saves some console spam.
4466 * When clearing B_NEEDCOMMIT we must also clear B_CLUSTEROK,
4467 * NFS can handle huge commits but not huge writes.
4469 vm_page_test_dirty(m
);
4471 if ((bp
->b_flags
& B_NEEDCOMMIT
) &&
4472 (m
->dirty
& vm_page_bits(soff
& PAGE_MASK
, eoff
- soff
))) {
4474 kprintf("Warning: vfs_clean_one_page: bp %p "
4475 "loff=%jx,%d flgs=%08x clr B_NEEDCOMMIT"
4476 " cmd %d vd %02x/%02x x/s/e %d %d %d "
4478 bp
, (uintmax_t)bp
->b_loffset
, bp
->b_bcount
,
4479 bp
->b_flags
, bp
->b_cmd
,
4480 m
->valid
, m
->dirty
, xoff
, soff
, eoff
,
4481 bp
->b_dirtyoff
, bp
->b_dirtyend
);
4482 bp
->b_flags
&= ~(B_NEEDCOMMIT
| B_CLUSTEROK
);
4484 print_backtrace(-1);
4487 * Only clear the pmap modified bits if ALL the dirty bits
4488 * are set, otherwise the system might mis-clear portions
4491 if (m
->dirty
== VM_PAGE_BITS_ALL
&&
4492 (bp
->b_flags
& B_NEEDCOMMIT
) == 0) {
4493 pmap_clear_modify(m
);
4495 if (bp
->b_dirtyoff
> soff
- xoff
)
4496 bp
->b_dirtyoff
= soff
- xoff
;
4497 if (bp
->b_dirtyend
< eoff
- xoff
)
4498 bp
->b_dirtyend
= eoff
- xoff
;
4502 * Set related valid bits, clear related dirty bits.
4503 * Does not mess with the pmap modified bit.
4505 * WARNING! We cannot just clear all of m->dirty here as the
4506 * buffer cache buffers may use a DEV_BSIZE'd aligned
4507 * block size, or have an odd size (e.g. NFS at file EOF).
4508 * The putpages code can clear m->dirty to 0.
4510 * If a VOP_WRITE generates a buffer cache buffer which
4511 * covers the same space as mapped writable pages the
4512 * buffer flush might not be able to clear all the dirty
4513 * bits and still require a putpages from the VM system
4516 * WARNING! vm_page_set_validclean() currently assumes vm_token
4517 * is held. The page might not be busied (bdwrite() case).
4518 * XXX remove this comment once we've validated that this
4519 * is no longer an issue.
4521 vm_page_set_validclean(m
, soff
& PAGE_MASK
, eoff
- soff
);
4526 * Similar to vfs_clean_one_page() but sets the bits to valid and dirty.
4527 * The page data is assumed to be valid (there is no zeroing here).
4530 vfs_dirty_one_page(struct buf
*bp
, int pageno
, vm_page_t m
)
4538 * Calculate offset range within the page but relative to buffer's
4539 * loffset. loffset might be offset into the first page.
4541 xoff
= (int)bp
->b_loffset
& PAGE_MASK
; /* loffset offset into pg 0 */
4542 bcount
= bp
->b_bcount
+ xoff
; /* offset adjusted */
4548 soff
= (pageno
<< PAGE_SHIFT
);
4549 eoff
= soff
+ PAGE_SIZE
;
4555 vm_page_set_validdirty(m
, soff
& PAGE_MASK
, eoff
- soff
);
4562 * Clear a buffer. This routine essentially fakes an I/O, so we need
4563 * to clear B_ERROR and B_INVAL.
4565 * Note that while we only theoretically need to clear through b_bcount,
4566 * we go ahead and clear through b_bufsize.
4570 vfs_bio_clrbuf(struct buf
*bp
)
4574 if ((bp
->b_flags
& (B_VMIO
| B_MALLOC
)) == B_VMIO
) {
4575 bp
->b_flags
&= ~(B_INVAL
| B_EINTR
| B_ERROR
);
4576 if ((bp
->b_xio
.xio_npages
== 1) && (bp
->b_bufsize
< PAGE_SIZE
) &&
4577 (bp
->b_loffset
& PAGE_MASK
) == 0) {
4578 mask
= (1 << (bp
->b_bufsize
/ DEV_BSIZE
)) - 1;
4579 if ((bp
->b_xio
.xio_pages
[0]->valid
& mask
) == mask
) {
4583 if (((bp
->b_xio
.xio_pages
[0]->flags
& PG_ZERO
) == 0) &&
4584 ((bp
->b_xio
.xio_pages
[0]->valid
& mask
) == 0)) {
4585 bzero(bp
->b_data
, bp
->b_bufsize
);
4586 bp
->b_xio
.xio_pages
[0]->valid
|= mask
;
4592 for(i
=0;i
<bp
->b_xio
.xio_npages
;i
++,sa
=ea
) {
4593 int j
= ((vm_offset_t
)sa
& PAGE_MASK
) / DEV_BSIZE
;
4594 ea
= (caddr_t
)trunc_page((vm_offset_t
)sa
+ PAGE_SIZE
);
4595 ea
= (caddr_t
)(vm_offset_t
)ulmin(
4596 (u_long
)(vm_offset_t
)ea
,
4597 (u_long
)(vm_offset_t
)bp
->b_data
+ bp
->b_bufsize
);
4598 mask
= ((1 << ((ea
- sa
) / DEV_BSIZE
)) - 1) << j
;
4599 if ((bp
->b_xio
.xio_pages
[i
]->valid
& mask
) == mask
)
4601 if ((bp
->b_xio
.xio_pages
[i
]->valid
& mask
) == 0) {
4602 if ((bp
->b_xio
.xio_pages
[i
]->flags
& PG_ZERO
) == 0) {
4606 for (; sa
< ea
; sa
+= DEV_BSIZE
, j
++) {
4607 if (((bp
->b_xio
.xio_pages
[i
]->flags
& PG_ZERO
) == 0) &&
4608 (bp
->b_xio
.xio_pages
[i
]->valid
& (1<<j
)) == 0)
4609 bzero(sa
, DEV_BSIZE
);
4612 bp
->b_xio
.xio_pages
[i
]->valid
|= mask
;
4613 vm_page_flag_clear(bp
->b_xio
.xio_pages
[i
], PG_ZERO
);
4622 * vm_hold_load_pages:
4624 * Load pages into the buffer's address space. The pages are
4625 * allocated from the kernel object in order to reduce interference
4626 * with the any VM paging I/O activity. The range of loaded
4627 * pages will be wired.
4629 * If a page cannot be allocated, the 'pagedaemon' is woken up to
4630 * retrieve the full range (to - from) of pages.
4633 vm_hold_load_pages(struct buf
*bp
, vm_offset_t from
, vm_offset_t to
)
4639 to
= round_page(to
);
4640 from
= round_page(from
);
4641 index
= (from
- trunc_page((vm_offset_t
)bp
->b_data
)) >> PAGE_SHIFT
;
4646 * Note: must allocate system pages since blocking here
4647 * could intefere with paging I/O, no matter which
4650 vm_object_hold(&kernel_object
);
4651 p
= bio_page_alloc(bp
, &kernel_object
, pg
>> PAGE_SHIFT
,
4652 (vm_pindex_t
)((to
- pg
) >> PAGE_SHIFT
));
4653 vm_object_drop(&kernel_object
);
4656 p
->valid
= VM_PAGE_BITS_ALL
;
4657 vm_page_flag_clear(p
, PG_ZERO
);
4658 pmap_kenter_noinval(pg
, VM_PAGE_TO_PHYS(p
));
4659 bp
->b_xio
.xio_pages
[index
] = p
;
4666 pmap_invalidate_range(&kernel_pmap
, from
, to
);
4667 bp
->b_xio
.xio_npages
= index
;
4671 * Allocate a page for a buffer cache buffer.
4673 * If NULL is returned the caller is expected to retry (typically check if
4674 * the page already exists on retry before trying to allocate one).
4676 * NOTE! Low-memory handling is dealt with in b[q]relse(), not here. This
4677 * function will use the system reserve with the hope that the page
4678 * allocations can be returned to PQ_CACHE/PQ_FREE when the caller
4679 * is done with the buffer.
4681 * NOTE! However, TMPFS is a special case because flushing a dirty buffer
4682 * to TMPFS doesn't clean the page. For TMPFS, only the pagedaemon
4683 * is capable of retiring pages (to swap). For TMPFS we don't dig
4684 * into the system reserve because doing so could stall out pretty
4685 * much every process running on the system.
4689 bio_page_alloc(struct buf
*bp
, vm_object_t obj
, vm_pindex_t pg
, int deficit
)
4691 int vmflags
= VM_ALLOC_NORMAL
| VM_ALLOC_NULL_OK
;
4694 ASSERT_LWKT_TOKEN_HELD(vm_object_token(obj
));
4697 * Try a normal allocation first.
4699 p
= vm_page_alloc(obj
, pg
, vmflags
);
4702 if (vm_page_lookup(obj
, pg
))
4704 vm_pageout_deficit
+= deficit
;
4707 * Try again, digging into the system reserve.
4709 * Trying to recover pages from the buffer cache here can deadlock
4710 * against other threads trying to busy underlying pages so we
4711 * depend on the code in brelse() and bqrelse() to free/cache the
4712 * underlying buffer cache pages when memory is low.
4714 if (curthread
->td_flags
& TDF_SYSTHREAD
)
4715 vmflags
|= VM_ALLOC_SYSTEM
| VM_ALLOC_INTERRUPT
;
4716 else if (bp
->b_vp
&& bp
->b_vp
->v_tag
== VT_TMPFS
)
4719 vmflags
|= VM_ALLOC_SYSTEM
;
4721 /*recoverbufpages();*/
4722 p
= vm_page_alloc(obj
, pg
, vmflags
);
4725 if (vm_page_lookup(obj
, pg
))
4729 * Wait for memory to free up and try again
4731 if (vm_page_count_severe())
4733 vm_wait(hz
/ 20 + 1);
4735 p
= vm_page_alloc(obj
, pg
, vmflags
);
4738 if (vm_page_lookup(obj
, pg
))
4742 * Ok, now we are really in trouble.
4745 static struct krate biokrate
= { .freq
= 1 };
4746 krateprintf(&biokrate
,
4747 "Warning: bio_page_alloc: memory exhausted "
4748 "during buffer cache page allocation from %s\n",
4749 curthread
->td_comm
);
4751 if (curthread
->td_flags
& TDF_SYSTHREAD
)
4752 vm_wait(hz
/ 20 + 1);
4754 vm_wait(hz
/ 2 + 1);
4759 * vm_hold_free_pages:
4761 * Return pages associated with the buffer back to the VM system.
4763 * The range of pages underlying the buffer's address space will
4764 * be unmapped and un-wired.
4767 vm_hold_free_pages(struct buf
*bp
, vm_offset_t from
, vm_offset_t to
)
4771 int index
, newnpages
;
4773 from
= round_page(from
);
4774 to
= round_page(to
);
4775 index
= (from
- trunc_page((vm_offset_t
)bp
->b_data
)) >> PAGE_SHIFT
;
4778 for (pg
= from
; pg
< to
; pg
+= PAGE_SIZE
, index
++) {
4779 p
= bp
->b_xio
.xio_pages
[index
];
4780 if (p
&& (index
< bp
->b_xio
.xio_npages
)) {
4782 kprintf("vm_hold_free_pages: doffset: %lld, "
4784 (long long)bp
->b_bio2
.bio_offset
,
4785 (long long)bp
->b_loffset
);
4787 bp
->b_xio
.xio_pages
[index
] = NULL
;
4788 pmap_kremove_noinval(pg
);
4789 vm_page_busy_wait(p
, FALSE
, "vmhldpg");
4790 vm_page_unwire(p
, 0);
4794 pmap_invalidate_range(&kernel_pmap
, from
, to
);
4795 bp
->b_xio
.xio_npages
= newnpages
;
4801 * Map a user buffer into KVM via a pbuf. On return the buffer's
4802 * b_data, b_bufsize, and b_bcount will be set, and its XIO page array
4806 vmapbuf(struct buf
*bp
, caddr_t udata
, int bytes
)
4817 * bp had better have a command and it better be a pbuf.
4819 KKASSERT(bp
->b_cmd
!= BUF_CMD_DONE
);
4820 KKASSERT(bp
->b_flags
& B_PAGING
);
4821 KKASSERT(bp
->b_kvabase
);
4827 * Map the user data into KVM. Mappings have to be page-aligned.
4829 addr
= (caddr_t
)trunc_page((vm_offset_t
)udata
);
4832 vmprot
= VM_PROT_READ
;
4833 if (bp
->b_cmd
== BUF_CMD_READ
)
4834 vmprot
|= VM_PROT_WRITE
;
4836 while (addr
< udata
+ bytes
) {
4838 * Do the vm_fault if needed; do the copy-on-write thing
4839 * when reading stuff off device into memory.
4841 * vm_fault_page*() returns a held VM page.
4843 va
= (addr
>= udata
) ? (vm_offset_t
)addr
: (vm_offset_t
)udata
;
4844 va
= trunc_page(va
);
4846 m
= vm_fault_page_quick(va
, vmprot
, &error
);
4848 for (i
= 0; i
< pidx
; ++i
) {
4849 vm_page_unhold(bp
->b_xio
.xio_pages
[i
]);
4850 bp
->b_xio
.xio_pages
[i
] = NULL
;
4854 bp
->b_xio
.xio_pages
[pidx
] = m
;
4860 * Map the page array and set the buffer fields to point to
4861 * the mapped data buffer.
4863 if (pidx
> btoc(MAXPHYS
))
4864 panic("vmapbuf: mapped more than MAXPHYS");
4865 pmap_qenter((vm_offset_t
)bp
->b_kvabase
, bp
->b_xio
.xio_pages
, pidx
);
4867 bp
->b_xio
.xio_npages
= pidx
;
4868 bp
->b_data
= bp
->b_kvabase
+ ((int)(intptr_t)udata
& PAGE_MASK
);
4869 bp
->b_bcount
= bytes
;
4870 bp
->b_bufsize
= bytes
;
4878 * Free the io map PTEs associated with this IO operation.
4879 * We also invalidate the TLB entries and restore the original b_addr.
4882 vunmapbuf(struct buf
*bp
)
4887 KKASSERT(bp
->b_flags
& B_PAGING
);
4889 npages
= bp
->b_xio
.xio_npages
;
4890 pmap_qremove(trunc_page((vm_offset_t
)bp
->b_data
), npages
);
4891 for (pidx
= 0; pidx
< npages
; ++pidx
) {
4892 vm_page_unhold(bp
->b_xio
.xio_pages
[pidx
]);
4893 bp
->b_xio
.xio_pages
[pidx
] = NULL
;
4895 bp
->b_xio
.xio_npages
= 0;
4896 bp
->b_data
= bp
->b_kvabase
;
4900 * Scan all buffers in the system and issue the callback.
4903 scan_all_buffers(int (*callback
)(struct buf
*, void *), void *info
)
4909 for (n
= 0; n
< nbuf
; ++n
) {
4910 if ((error
= callback(&buf
[n
], info
)) < 0) {
4920 * nestiobuf_iodone: biodone callback for nested buffers and propagate
4921 * completion to the master buffer.
4924 nestiobuf_iodone(struct bio
*bio
)
4927 struct buf
*mbp
, *bp
;
4928 struct devstat
*stats
;
4933 mbio
= bio
->bio_caller_info1
.ptr
;
4934 stats
= bio
->bio_caller_info2
.ptr
;
4935 mbp
= mbio
->bio_buf
;
4937 KKASSERT(bp
->b_bcount
<= bp
->b_bufsize
);
4938 KKASSERT(mbp
!= bp
);
4940 error
= bp
->b_error
;
4941 if (bp
->b_error
== 0 &&
4942 (bp
->b_bcount
< bp
->b_bufsize
|| bp
->b_resid
> 0)) {
4944 * Not all got transfered, raise an error. We have no way to
4945 * propagate these conditions to mbp.
4950 donebytes
= bp
->b_bufsize
;
4954 nestiobuf_done(mbio
, donebytes
, error
, stats
);
4958 nestiobuf_done(struct bio
*mbio
, int donebytes
, int error
, struct devstat
*stats
)
4962 mbp
= mbio
->bio_buf
;
4964 KKASSERT((int)(intptr_t)mbio
->bio_driver_info
> 0);
4967 * If an error occured, propagate it to the master buffer.
4969 * Several biodone()s may wind up running concurrently so
4970 * use an atomic op to adjust b_flags.
4973 mbp
->b_error
= error
;
4974 atomic_set_int(&mbp
->b_flags
, B_ERROR
);
4978 * Decrement the operations in progress counter and terminate the
4979 * I/O if this was the last bit.
4981 if (atomic_fetchadd_int((int *)&mbio
->bio_driver_info
, -1) == 1) {
4984 devstat_end_transaction_buf(stats
, mbp
);
4990 * Initialize a nestiobuf for use. Set an initial count of 1 to prevent
4991 * the mbio from being biodone()'d while we are still adding sub-bios to
4995 nestiobuf_init(struct bio
*bio
)
4997 bio
->bio_driver_info
= (void *)1;
5001 * The BIOs added to the nestedio have already been started, remove the
5002 * count that placeheld our mbio and biodone() it if the count would
5006 nestiobuf_start(struct bio
*mbio
)
5008 struct buf
*mbp
= mbio
->bio_buf
;
5011 * Decrement the operations in progress counter and terminate the
5012 * I/O if this was the last bit.
5014 if (atomic_fetchadd_int((int *)&mbio
->bio_driver_info
, -1) == 1) {
5015 if (mbp
->b_flags
& B_ERROR
)
5016 mbp
->b_resid
= mbp
->b_bcount
;
5024 * Set an intermediate error prior to calling nestiobuf_start()
5027 nestiobuf_error(struct bio
*mbio
, int error
)
5029 struct buf
*mbp
= mbio
->bio_buf
;
5032 mbp
->b_error
= error
;
5033 atomic_set_int(&mbp
->b_flags
, B_ERROR
);
5038 * nestiobuf_add: setup a "nested" buffer.
5040 * => 'mbp' is a "master" buffer which is being divided into sub pieces.
5041 * => 'bp' should be a buffer allocated by getiobuf.
5042 * => 'offset' is a byte offset in the master buffer.
5043 * => 'size' is a size in bytes of this nested buffer.
5046 nestiobuf_add(struct bio
*mbio
, struct buf
*bp
, int offset
, size_t size
, struct devstat
*stats
)
5048 struct buf
*mbp
= mbio
->bio_buf
;
5049 struct vnode
*vp
= mbp
->b_vp
;
5051 KKASSERT(mbp
->b_bcount
>= offset
+ size
);
5053 atomic_add_int((int *)&mbio
->bio_driver_info
, 1);
5055 /* kernel needs to own the lock for it to be released in biodone */
5058 bp
->b_cmd
= mbp
->b_cmd
;
5059 bp
->b_bio1
.bio_done
= nestiobuf_iodone
;
5060 bp
->b_data
= (char *)mbp
->b_data
+ offset
;
5061 bp
->b_resid
= bp
->b_bcount
= size
;
5062 bp
->b_bufsize
= bp
->b_bcount
;
5064 bp
->b_bio1
.bio_track
= NULL
;
5065 bp
->b_bio1
.bio_caller_info1
.ptr
= mbio
;
5066 bp
->b_bio1
.bio_caller_info2
.ptr
= stats
;
5071 DB_SHOW_COMMAND(buffer
, db_show_buffer
)
5074 struct buf
*bp
= (struct buf
*)addr
;
5077 db_printf("usage: show buffer <addr>\n");
5081 db_printf("b_flags = 0x%b\n", (u_int
)bp
->b_flags
, PRINT_BUF_FLAGS
);
5082 db_printf("b_cmd = %d\n", bp
->b_cmd
);
5083 db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
5084 "b_resid = %d\n, b_data = %p, "
5085 "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
5086 bp
->b_error
, bp
->b_bufsize
, bp
->b_bcount
, bp
->b_resid
,
5088 (long long)bp
->b_bio2
.bio_offset
,
5089 (long long)(bp
->b_bio2
.bio_next
?
5090 bp
->b_bio2
.bio_next
->bio_offset
: (off_t
)-1));
5091 if (bp
->b_xio
.xio_npages
) {
5093 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
5094 bp
->b_xio
.xio_npages
);
5095 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
5097 m
= bp
->b_xio
.xio_pages
[i
];
5098 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m
->object
,
5099 (u_long
)m
->pindex
, (u_long
)VM_PAGE_TO_PHYS(m
));
5100 if ((i
+ 1) < bp
->b_xio
.xio_npages
)