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 $
15 * $DragonFly: src/sys/kern/vfs_bio.c,v 1.103 2008/06/10 05:02:09 dillon Exp $
19 * this file contains a new buffer I/O scheme implementing a coherent
20 * VM object and buffer cache scheme. Pains have been taken to make
21 * sure that the performance degradation associated with schemes such
22 * as this is not realized.
24 * Author: John S. Dyson
25 * Significant help during the development and debugging phases
26 * had been provided by David Greenman, also of the FreeBSD core team.
28 * see man buf(9) for more info.
31 #include <sys/param.h>
32 #include <sys/systm.h>
35 #include <sys/eventhandler.h>
37 #include <sys/malloc.h>
38 #include <sys/mount.h>
39 #include <sys/kernel.h>
40 #include <sys/kthread.h>
42 #include <sys/reboot.h>
43 #include <sys/resourcevar.h>
44 #include <sys/sysctl.h>
45 #include <sys/vmmeter.h>
46 #include <sys/vnode.h>
49 #include <vm/vm_param.h>
50 #include <vm/vm_kern.h>
51 #include <vm/vm_pageout.h>
52 #include <vm/vm_page.h>
53 #include <vm/vm_object.h>
54 #include <vm/vm_extern.h>
55 #include <vm/vm_map.h>
58 #include <sys/thread2.h>
59 #include <sys/spinlock2.h>
60 #include <vm/vm_page2.h>
71 BQUEUE_NONE
, /* not on any queue */
72 BQUEUE_LOCKED
, /* locked buffers */
73 BQUEUE_CLEAN
, /* non-B_DELWRI buffers */
74 BQUEUE_DIRTY
, /* B_DELWRI buffers */
75 BQUEUE_DIRTY_HW
, /* B_DELWRI buffers - heavy weight */
76 BQUEUE_EMPTYKVA
, /* empty buffer headers with KVA assignment */
77 BQUEUE_EMPTY
, /* empty buffer headers */
79 BUFFER_QUEUES
/* number of buffer queues */
82 typedef enum bufq_type bufq_type_t
;
84 TAILQ_HEAD(bqueues
, buf
) bufqueues
[BUFFER_QUEUES
];
86 static MALLOC_DEFINE(M_BIOBUF
, "BIO buffer", "BIO buffer");
88 struct buf
*buf
; /* buffer header pool */
90 static void vm_hold_free_pages(struct buf
*bp
, vm_offset_t from
,
92 static void vm_hold_load_pages(struct buf
*bp
, vm_offset_t from
,
94 static void vfs_page_set_valid(struct buf
*bp
, vm_ooffset_t off
,
95 int pageno
, vm_page_t m
);
96 static void vfs_clean_pages(struct buf
*bp
);
97 static void vfs_setdirty(struct buf
*bp
);
98 static void vfs_vmio_release(struct buf
*bp
);
99 static int flushbufqueues(bufq_type_t q
);
101 static void buf_daemon(void);
102 static void buf_daemon_hw(void);
104 * bogus page -- for I/O to/from partially complete buffers
105 * this is a temporary solution to the problem, but it is not
106 * really that bad. it would be better to split the buffer
107 * for input in the case of buffers partially already in memory,
108 * but the code is intricate enough already.
110 vm_page_t bogus_page
;
113 * These are all static, but make the ones we export globals so we do
114 * not need to use compiler magic.
116 int bufspace
, maxbufspace
,
117 bufmallocspace
, maxbufmallocspace
, lobufspace
, hibufspace
;
118 static int bufreusecnt
, bufdefragcnt
, buffreekvacnt
;
119 static int lorunningspace
, hirunningspace
, runningbufreq
;
120 int numdirtybuffers
, numdirtybuffershw
, lodirtybuffers
, hidirtybuffers
;
121 int runningbufspace
, runningbufcount
;
122 static int numfreebuffers
, lofreebuffers
, hifreebuffers
;
123 static int getnewbufcalls
;
124 static int getnewbufrestarts
;
126 static int needsbuffer
; /* locked by needsbuffer_spin */
127 static int bd_request
; /* locked by needsbuffer_spin */
128 static int bd_request_hw
; /* locked by needsbuffer_spin */
129 static struct spinlock needsbuffer_spin
;
132 * Sysctls for operational control of the buffer cache.
134 SYSCTL_INT(_vfs
, OID_AUTO
, lodirtybuffers
, CTLFLAG_RW
, &lodirtybuffers
, 0,
135 "Number of dirty buffers to flush before bufdaemon becomes inactive");
136 SYSCTL_INT(_vfs
, OID_AUTO
, hidirtybuffers
, CTLFLAG_RW
, &hidirtybuffers
, 0,
137 "High watermark used to trigger explicit flushing of dirty buffers");
138 SYSCTL_INT(_vfs
, OID_AUTO
, lofreebuffers
, CTLFLAG_RW
, &lofreebuffers
, 0,
139 "Low watermark for special reserve in low-memory situations");
140 SYSCTL_INT(_vfs
, OID_AUTO
, hifreebuffers
, CTLFLAG_RW
, &hifreebuffers
, 0,
141 "High watermark for special reserve in low-memory situations");
142 SYSCTL_INT(_vfs
, OID_AUTO
, lorunningspace
, CTLFLAG_RW
, &lorunningspace
, 0,
143 "Minimum amount of buffer space required for active I/O");
144 SYSCTL_INT(_vfs
, OID_AUTO
, hirunningspace
, CTLFLAG_RW
, &hirunningspace
, 0,
145 "Maximum amount of buffer space to usable for active I/O");
147 * Sysctls determining current state of the buffer cache.
149 SYSCTL_INT(_vfs
, OID_AUTO
, nbuf
, CTLFLAG_RD
, &nbuf
, 0,
150 "Total number of buffers in buffer cache");
151 SYSCTL_INT(_vfs
, OID_AUTO
, numdirtybuffers
, CTLFLAG_RD
, &numdirtybuffers
, 0,
152 "Pending number of dirty buffers (all)");
153 SYSCTL_INT(_vfs
, OID_AUTO
, numdirtybuffershw
, CTLFLAG_RD
, &numdirtybuffershw
, 0,
154 "Pending number of dirty buffers (heavy weight)");
155 SYSCTL_INT(_vfs
, OID_AUTO
, numfreebuffers
, CTLFLAG_RD
, &numfreebuffers
, 0,
156 "Number of free buffers on the buffer cache free list");
157 SYSCTL_INT(_vfs
, OID_AUTO
, runningbufspace
, CTLFLAG_RD
, &runningbufspace
, 0,
158 "I/O bytes currently in progress due to asynchronous writes");
159 SYSCTL_INT(_vfs
, OID_AUTO
, runningbufcount
, CTLFLAG_RD
, &runningbufcount
, 0,
160 "I/O buffers currently in progress due to asynchronous writes");
161 SYSCTL_INT(_vfs
, OID_AUTO
, maxbufspace
, CTLFLAG_RD
, &maxbufspace
, 0,
162 "Hard limit on maximum amount of memory usable for buffer space");
163 SYSCTL_INT(_vfs
, OID_AUTO
, hibufspace
, CTLFLAG_RD
, &hibufspace
, 0,
164 "Soft limit on maximum amount of memory usable for buffer space");
165 SYSCTL_INT(_vfs
, OID_AUTO
, lobufspace
, CTLFLAG_RD
, &lobufspace
, 0,
166 "Minimum amount of memory to reserve for system buffer space");
167 SYSCTL_INT(_vfs
, OID_AUTO
, bufspace
, CTLFLAG_RD
, &bufspace
, 0,
168 "Amount of memory available for buffers");
169 SYSCTL_INT(_vfs
, OID_AUTO
, maxmallocbufspace
, CTLFLAG_RD
, &maxbufmallocspace
,
170 0, "Maximum amount of memory reserved for buffers using malloc");
171 SYSCTL_INT(_vfs
, OID_AUTO
, bufmallocspace
, CTLFLAG_RD
, &bufmallocspace
, 0,
172 "Amount of memory left for buffers using malloc-scheme");
173 SYSCTL_INT(_vfs
, OID_AUTO
, getnewbufcalls
, CTLFLAG_RD
, &getnewbufcalls
, 0,
174 "New buffer header acquisition requests");
175 SYSCTL_INT(_vfs
, OID_AUTO
, getnewbufrestarts
, CTLFLAG_RD
, &getnewbufrestarts
,
176 0, "New buffer header acquisition restarts");
177 SYSCTL_INT(_vfs
, OID_AUTO
, bufdefragcnt
, CTLFLAG_RD
, &bufdefragcnt
, 0,
178 "Buffer acquisition restarts due to fragmented buffer map");
179 SYSCTL_INT(_vfs
, OID_AUTO
, buffreekvacnt
, CTLFLAG_RD
, &buffreekvacnt
, 0,
180 "Amount of time KVA space was deallocated in an arbitrary buffer");
181 SYSCTL_INT(_vfs
, OID_AUTO
, bufreusecnt
, CTLFLAG_RD
, &bufreusecnt
, 0,
182 "Amount of time buffer re-use operations were successful");
183 SYSCTL_INT(_debug_sizeof
, OID_AUTO
, buf
, CTLFLAG_RD
, 0, sizeof(struct buf
),
184 "sizeof(struct buf)");
186 char *buf_wmesg
= BUF_WMESG
;
188 extern int vm_swap_size
;
190 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
191 #define VFS_BIO_NEED_DIRTYFLUSH 0x02 /* waiting for dirty buffer flush */
192 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
193 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
198 * If someone is blocked due to there being too many dirty buffers,
199 * and numdirtybuffers is now reasonable, wake them up.
204 if (runningbufcount
+ numdirtybuffers
<=
205 (lodirtybuffers
+ hidirtybuffers
) / 2) {
206 if (needsbuffer
& VFS_BIO_NEED_DIRTYFLUSH
) {
207 spin_lock_wr(&needsbuffer_spin
);
208 needsbuffer
&= ~VFS_BIO_NEED_DIRTYFLUSH
;
209 spin_unlock_wr(&needsbuffer_spin
);
210 wakeup(&needsbuffer
);
218 * Called when buffer space is potentially available for recovery.
219 * getnewbuf() will block on this flag when it is unable to free
220 * sufficient buffer space. Buffer space becomes recoverable when
221 * bp's get placed back in the queues.
228 * If someone is waiting for BUF space, wake them up. Even
229 * though we haven't freed the kva space yet, the waiting
230 * process will be able to now.
232 if (needsbuffer
& VFS_BIO_NEED_BUFSPACE
) {
233 spin_lock_wr(&needsbuffer_spin
);
234 needsbuffer
&= ~VFS_BIO_NEED_BUFSPACE
;
235 spin_unlock_wr(&needsbuffer_spin
);
236 wakeup(&needsbuffer
);
243 * Accounting for I/O in progress.
247 runningbufwakeup(struct buf
*bp
)
249 if (bp
->b_runningbufspace
) {
250 runningbufspace
-= bp
->b_runningbufspace
;
252 bp
->b_runningbufspace
= 0;
253 if (runningbufreq
&& runningbufspace
<= lorunningspace
) {
255 wakeup(&runningbufreq
);
264 * Called when a buffer has been added to one of the free queues to
265 * account for the buffer and to wakeup anyone waiting for free buffers.
266 * This typically occurs when large amounts of metadata are being handled
267 * by the buffer cache ( else buffer space runs out first, usually ).
275 spin_lock_wr(&needsbuffer_spin
);
276 needsbuffer
&= ~VFS_BIO_NEED_ANY
;
277 if (numfreebuffers
>= hifreebuffers
)
278 needsbuffer
&= ~VFS_BIO_NEED_FREE
;
279 spin_unlock_wr(&needsbuffer_spin
);
280 wakeup(&needsbuffer
);
285 * waitrunningbufspace()
287 * runningbufspace is a measure of the amount of I/O currently
288 * running. This routine is used in async-write situations to
289 * prevent creating huge backups of pending writes to a device.
290 * Only asynchronous writes are governed by this function.
292 * Reads will adjust runningbufspace, but will not block based on it.
293 * The read load has a side effect of reducing the allowed write load.
295 * This does NOT turn an async write into a sync write. It waits
296 * for earlier writes to complete and generally returns before the
297 * caller's write has reached the device.
300 waitrunningbufspace(void)
302 if (runningbufspace
> hirunningspace
) {
304 while (runningbufspace
> hirunningspace
) {
306 tsleep(&runningbufreq
, 0, "wdrain", 0);
313 * vfs_buf_test_cache:
315 * Called when a buffer is extended. This function clears the B_CACHE
316 * bit if the newly extended portion of the buffer does not contain
321 vfs_buf_test_cache(struct buf
*bp
,
322 vm_ooffset_t foff
, vm_offset_t off
, vm_offset_t size
,
325 if (bp
->b_flags
& B_CACHE
) {
326 int base
= (foff
+ off
) & PAGE_MASK
;
327 if (vm_page_is_valid(m
, base
, size
) == 0)
328 bp
->b_flags
&= ~B_CACHE
;
335 * Wake up the buffer daemon if the number of outstanding dirty buffers
336 * is above specified threshold 'dirtybuflevel'.
338 * The buffer daemons are explicitly woken up when (a) the pending number
339 * of dirty buffers exceeds the recovery and stall mid-point value,
340 * (b) during bwillwrite() or (c) buf freelist was exhausted.
342 * The buffer daemons will generally not stop flushing until the dirty
343 * buffer count goes below lodirtybuffers.
347 bd_wakeup(int dirtybuflevel
)
349 if (bd_request
== 0 && numdirtybuffers
&&
350 runningbufcount
+ numdirtybuffers
>= dirtybuflevel
) {
351 spin_lock_wr(&needsbuffer_spin
);
353 spin_unlock_wr(&needsbuffer_spin
);
356 if (bd_request_hw
== 0 && numdirtybuffershw
&&
357 numdirtybuffershw
>= dirtybuflevel
) {
358 spin_lock_wr(&needsbuffer_spin
);
360 spin_unlock_wr(&needsbuffer_spin
);
361 wakeup(&bd_request_hw
);
368 * Speed up the buffer cache flushing process.
381 * Load time initialisation of the buffer cache, called from machine
382 * dependant initialization code.
388 vm_offset_t bogus_offset
;
391 spin_init(&needsbuffer_spin
);
393 /* next, make a null set of free lists */
394 for (i
= 0; i
< BUFFER_QUEUES
; i
++)
395 TAILQ_INIT(&bufqueues
[i
]);
397 /* finally, initialize each buffer header and stick on empty q */
398 for (i
= 0; i
< nbuf
; i
++) {
400 bzero(bp
, sizeof *bp
);
401 bp
->b_flags
= B_INVAL
; /* we're just an empty header */
402 bp
->b_cmd
= BUF_CMD_DONE
;
403 bp
->b_qindex
= BQUEUE_EMPTY
;
405 xio_init(&bp
->b_xio
);
408 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_EMPTY
], bp
, b_freelist
);
412 * maxbufspace is the absolute maximum amount of buffer space we are
413 * allowed to reserve in KVM and in real terms. The absolute maximum
414 * is nominally used by buf_daemon. hibufspace is the nominal maximum
415 * used by most other processes. The differential is required to
416 * ensure that buf_daemon is able to run when other processes might
417 * be blocked waiting for buffer space.
419 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
420 * this may result in KVM fragmentation which is not handled optimally
423 maxbufspace
= nbuf
* BKVASIZE
;
424 hibufspace
= imax(3 * maxbufspace
/ 4, maxbufspace
- MAXBSIZE
* 10);
425 lobufspace
= hibufspace
- MAXBSIZE
;
427 lorunningspace
= 512 * 1024;
428 hirunningspace
= 1024 * 1024;
431 * Limit the amount of malloc memory since it is wired permanently into
432 * the kernel space. Even though this is accounted for in the buffer
433 * allocation, we don't want the malloced region to grow uncontrolled.
434 * The malloc scheme improves memory utilization significantly on average
435 * (small) directories.
437 maxbufmallocspace
= hibufspace
/ 20;
440 * Reduce the chance of a deadlock occuring by limiting the number
441 * of delayed-write dirty buffers we allow to stack up.
443 hidirtybuffers
= nbuf
/ 4 + 20;
445 numdirtybuffershw
= 0;
447 * To support extreme low-memory systems, make sure hidirtybuffers cannot
448 * eat up all available buffer space. This occurs when our minimum cannot
449 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
450 * BKVASIZE'd (8K) buffers.
452 while (hidirtybuffers
* BKVASIZE
> 3 * hibufspace
/ 4) {
453 hidirtybuffers
>>= 1;
455 lodirtybuffers
= hidirtybuffers
/ 2;
458 * Try to keep the number of free buffers in the specified range,
459 * and give special processes (e.g. like buf_daemon) access to an
462 lofreebuffers
= nbuf
/ 18 + 5;
463 hifreebuffers
= 2 * lofreebuffers
;
464 numfreebuffers
= nbuf
;
467 * Maximum number of async ops initiated per buf_daemon loop. This is
468 * somewhat of a hack at the moment, we really need to limit ourselves
469 * based on the number of bytes of I/O in-transit that were initiated
473 bogus_offset
= kmem_alloc_pageable(&kernel_map
, PAGE_SIZE
);
474 bogus_page
= vm_page_alloc(&kernel_object
,
475 (bogus_offset
>> PAGE_SHIFT
),
477 vmstats
.v_wire_count
++;
482 * Initialize the embedded bio structures
485 initbufbio(struct buf
*bp
)
487 bp
->b_bio1
.bio_buf
= bp
;
488 bp
->b_bio1
.bio_prev
= NULL
;
489 bp
->b_bio1
.bio_offset
= NOOFFSET
;
490 bp
->b_bio1
.bio_next
= &bp
->b_bio2
;
491 bp
->b_bio1
.bio_done
= NULL
;
493 bp
->b_bio2
.bio_buf
= bp
;
494 bp
->b_bio2
.bio_prev
= &bp
->b_bio1
;
495 bp
->b_bio2
.bio_offset
= NOOFFSET
;
496 bp
->b_bio2
.bio_next
= NULL
;
497 bp
->b_bio2
.bio_done
= NULL
;
501 * Reinitialize the embedded bio structures as well as any additional
502 * translation cache layers.
505 reinitbufbio(struct buf
*bp
)
509 for (bio
= &bp
->b_bio1
; bio
; bio
= bio
->bio_next
) {
510 bio
->bio_done
= NULL
;
511 bio
->bio_offset
= NOOFFSET
;
516 * Push another BIO layer onto an existing BIO and return it. The new
517 * BIO layer may already exist, holding cached translation data.
520 push_bio(struct bio
*bio
)
524 if ((nbio
= bio
->bio_next
) == NULL
) {
525 int index
= bio
- &bio
->bio_buf
->b_bio_array
[0];
526 if (index
>= NBUF_BIO
- 1) {
527 panic("push_bio: too many layers bp %p\n",
530 nbio
= &bio
->bio_buf
->b_bio_array
[index
+ 1];
531 bio
->bio_next
= nbio
;
532 nbio
->bio_prev
= bio
;
533 nbio
->bio_buf
= bio
->bio_buf
;
534 nbio
->bio_offset
= NOOFFSET
;
535 nbio
->bio_done
= NULL
;
536 nbio
->bio_next
= NULL
;
538 KKASSERT(nbio
->bio_done
== NULL
);
543 pop_bio(struct bio
*bio
)
549 clearbiocache(struct bio
*bio
)
552 bio
->bio_offset
= NOOFFSET
;
560 * Free the KVA allocation for buffer 'bp'.
562 * Must be called from a critical section as this is the only locking for
565 * Since this call frees up buffer space, we call bufspacewakeup().
568 bfreekva(struct buf
*bp
)
574 count
= vm_map_entry_reserve(MAP_RESERVE_COUNT
);
575 vm_map_lock(&buffer_map
);
576 bufspace
-= bp
->b_kvasize
;
577 vm_map_delete(&buffer_map
,
578 (vm_offset_t
) bp
->b_kvabase
,
579 (vm_offset_t
) bp
->b_kvabase
+ bp
->b_kvasize
,
582 vm_map_unlock(&buffer_map
);
583 vm_map_entry_release(count
);
592 * Remove the buffer from the appropriate free list.
595 bremfree(struct buf
*bp
)
600 old_qindex
= bp
->b_qindex
;
602 if (bp
->b_qindex
!= BQUEUE_NONE
) {
603 KASSERT(BUF_REFCNTNB(bp
) == 1,
604 ("bremfree: bp %p not locked",bp
));
605 TAILQ_REMOVE(&bufqueues
[bp
->b_qindex
], bp
, b_freelist
);
606 bp
->b_qindex
= BQUEUE_NONE
;
608 if (BUF_REFCNTNB(bp
) <= 1)
609 panic("bremfree: removing a buffer not on a queue");
613 * Fixup numfreebuffers count. If the buffer is invalid or not
614 * delayed-write, and it was on the EMPTY, LRU, or AGE queues,
615 * the buffer was free and we must decrement numfreebuffers.
617 if ((bp
->b_flags
& B_INVAL
) || (bp
->b_flags
& B_DELWRI
) == 0) {
620 case BQUEUE_DIRTY_HW
:
623 case BQUEUE_EMPTYKVA
:
637 * Get a buffer with the specified data. Look in the cache first. We
638 * must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
639 * is set, the buffer is valid and we do not have to do anything ( see
643 bread(struct vnode
*vp
, off_t loffset
, int size
, struct buf
**bpp
)
647 bp
= getblk(vp
, loffset
, size
, 0, 0);
650 /* if not found in cache, do some I/O */
651 if ((bp
->b_flags
& B_CACHE
) == 0) {
652 KASSERT(!(bp
->b_flags
& B_ASYNC
), ("bread: illegal async bp %p", bp
));
653 bp
->b_flags
&= ~(B_ERROR
| B_INVAL
);
654 bp
->b_cmd
= BUF_CMD_READ
;
655 vfs_busy_pages(vp
, bp
);
656 vn_strategy(vp
, &bp
->b_bio1
);
657 return (biowait(bp
));
665 * Operates like bread, but also starts asynchronous I/O on
666 * read-ahead blocks. We must clear B_ERROR and B_INVAL prior
667 * to initiating I/O . If B_CACHE is set, the buffer is valid
668 * and we do not have to do anything.
671 breadn(struct vnode
*vp
, off_t loffset
, int size
, off_t
*raoffset
,
672 int *rabsize
, int cnt
, struct buf
**bpp
)
674 struct buf
*bp
, *rabp
;
676 int rv
= 0, readwait
= 0;
678 *bpp
= bp
= getblk(vp
, loffset
, size
, 0, 0);
680 /* if not found in cache, do some I/O */
681 if ((bp
->b_flags
& B_CACHE
) == 0) {
682 bp
->b_flags
&= ~(B_ERROR
| B_INVAL
);
683 bp
->b_cmd
= BUF_CMD_READ
;
684 vfs_busy_pages(vp
, bp
);
685 vn_strategy(vp
, &bp
->b_bio1
);
689 for (i
= 0; i
< cnt
; i
++, raoffset
++, rabsize
++) {
690 if (inmem(vp
, *raoffset
))
692 rabp
= getblk(vp
, *raoffset
, *rabsize
, 0, 0);
694 if ((rabp
->b_flags
& B_CACHE
) == 0) {
695 rabp
->b_flags
|= B_ASYNC
;
696 rabp
->b_flags
&= ~(B_ERROR
| B_INVAL
);
697 rabp
->b_cmd
= BUF_CMD_READ
;
698 vfs_busy_pages(vp
, rabp
);
700 vn_strategy(vp
, &rabp
->b_bio1
);
715 * Write, release buffer on completion. (Done by iodone
716 * if async). Do not bother writing anything if the buffer
719 * Note that we set B_CACHE here, indicating that buffer is
720 * fully valid and thus cacheable. This is true even of NFS
721 * now so we set it generally. This could be set either here
722 * or in biodone() since the I/O is synchronous. We put it
726 bwrite(struct buf
*bp
)
730 if (bp
->b_flags
& B_INVAL
) {
735 oldflags
= bp
->b_flags
;
737 if (BUF_REFCNTNB(bp
) == 0)
738 panic("bwrite: buffer is not busy???");
741 /* Mark the buffer clean */
744 bp
->b_flags
&= ~B_ERROR
;
745 bp
->b_flags
|= B_CACHE
;
746 bp
->b_cmd
= BUF_CMD_WRITE
;
747 vfs_busy_pages(bp
->b_vp
, bp
);
750 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
751 * valid for vnode-backed buffers.
753 bp
->b_runningbufspace
= bp
->b_bufsize
;
754 if (bp
->b_runningbufspace
) {
755 runningbufspace
+= bp
->b_runningbufspace
;
760 if (oldflags
& B_ASYNC
)
762 vn_strategy(bp
->b_vp
, &bp
->b_bio1
);
764 if ((oldflags
& B_ASYNC
) == 0) {
765 int rtval
= biowait(bp
);
775 * Delayed write. (Buffer is marked dirty). Do not bother writing
776 * anything if the buffer is marked invalid.
778 * Note that since the buffer must be completely valid, we can safely
779 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
780 * biodone() in order to prevent getblk from writing the buffer
784 bdwrite(struct buf
*bp
)
786 if (BUF_REFCNTNB(bp
) == 0)
787 panic("bdwrite: buffer is not busy");
789 if (bp
->b_flags
& B_INVAL
) {
796 * Set B_CACHE, indicating that the buffer is fully valid. This is
797 * true even of NFS now.
799 bp
->b_flags
|= B_CACHE
;
802 * This bmap keeps the system from needing to do the bmap later,
803 * perhaps when the system is attempting to do a sync. Since it
804 * is likely that the indirect block -- or whatever other datastructure
805 * that the filesystem needs is still in memory now, it is a good
806 * thing to do this. Note also, that if the pageout daemon is
807 * requesting a sync -- there might not be enough memory to do
808 * the bmap then... So, this is important to do.
810 if (bp
->b_bio2
.bio_offset
== NOOFFSET
) {
811 VOP_BMAP(bp
->b_vp
, bp
->b_loffset
, &bp
->b_bio2
.bio_offset
,
816 * Set the *dirty* buffer range based upon the VM system dirty pages.
821 * We need to do this here to satisfy the vnode_pager and the
822 * pageout daemon, so that it thinks that the pages have been
823 * "cleaned". Note that since the pages are in a delayed write
824 * buffer -- the VFS layer "will" see that the pages get written
825 * out on the next sync, or perhaps the cluster will be completed.
831 * Wakeup the buffer flushing daemon if we have a lot of dirty
832 * buffers (midpoint between our recovery point and our stall
835 bd_wakeup((lodirtybuffers
+ hidirtybuffers
) / 2);
838 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
839 * due to the softdep code.
846 * Turn buffer into delayed write request by marking it B_DELWRI.
847 * B_RELBUF and B_NOCACHE must be cleared.
849 * We reassign the buffer to itself to properly update it in the
852 * Since the buffer is not on a queue, we do not update the
853 * numfreebuffers count.
855 * Must be called from a critical section.
856 * The buffer must be on BQUEUE_NONE.
859 bdirty(struct buf
*bp
)
861 KASSERT(bp
->b_qindex
== BQUEUE_NONE
, ("bdirty: buffer %p still on queue %d", bp
, bp
->b_qindex
));
862 if (bp
->b_flags
& B_NOCACHE
) {
863 kprintf("bdirty: clearing B_NOCACHE on buf %p\n", bp
);
864 bp
->b_flags
&= ~B_NOCACHE
;
866 if (bp
->b_flags
& B_INVAL
) {
867 kprintf("bdirty: warning, dirtying invalid buffer %p\n", bp
);
869 bp
->b_flags
&= ~B_RELBUF
;
871 if ((bp
->b_flags
& B_DELWRI
) == 0) {
872 bp
->b_flags
|= B_DELWRI
;
875 if (bp
->b_flags
& B_HEAVY
)
877 bd_wakeup((lodirtybuffers
+ hidirtybuffers
) / 2);
882 * Set B_HEAVY, indicating that this is a heavy-weight buffer that
883 * needs to be flushed with a different buf_daemon thread to avoid
884 * deadlocks. B_HEAVY also imposes restrictions in getnewbuf().
887 bheavy(struct buf
*bp
)
889 if ((bp
->b_flags
& B_HEAVY
) == 0) {
890 bp
->b_flags
|= B_HEAVY
;
891 if (bp
->b_flags
& B_DELWRI
)
899 * Clear B_DELWRI for buffer.
901 * Since the buffer is not on a queue, we do not update the numfreebuffers
904 * Must be called from a critical section.
906 * The buffer is typically on BQUEUE_NONE but there is one case in
907 * brelse() that calls this function after placing the buffer on
912 bundirty(struct buf
*bp
)
914 if (bp
->b_flags
& B_DELWRI
) {
915 bp
->b_flags
&= ~B_DELWRI
;
918 if (bp
->b_flags
& B_HEAVY
)
923 * Since it is now being written, we can clear its deferred write flag.
925 bp
->b_flags
&= ~B_DEFERRED
;
931 * Asynchronous write. Start output on a buffer, but do not wait for
932 * it to complete. The buffer is released when the output completes.
934 * bwrite() ( or the VOP routine anyway ) is responsible for handling
935 * B_INVAL buffers. Not us.
938 bawrite(struct buf
*bp
)
940 bp
->b_flags
|= B_ASYNC
;
947 * Ordered write. Start output on a buffer, and flag it so that the
948 * device will write it in the order it was queued. The buffer is
949 * released when the output completes. bwrite() ( or the VOP routine
950 * anyway ) is responsible for handling B_INVAL buffers.
953 bowrite(struct buf
*bp
)
955 bp
->b_flags
|= B_ORDERED
| B_ASYNC
;
962 * Called prior to the locking of any vnodes when we are expecting to
963 * write. We do not want to starve the buffer cache with too many
964 * dirty buffers so we block here. By blocking prior to the locking
965 * of any vnodes we attempt to avoid the situation where a locked vnode
966 * prevents the various system daemons from flushing related buffers.
971 int mid1
= hidirtybuffers
/ 2;
972 int mid2
= mid1
+ hidirtybuffers
/ 4;
977 count
= runningbufcount
+ numdirtybuffers
;
980 * Nothing to do if nothing is stressed.
986 * Get the buffer daemon heated up
990 while (count
>= mid2
) {
992 * Start slowing down writes, down to 1 per second.
994 if (count
< hidirtybuffers
) {
995 delay
= (count
- mid2
) * hz
/ (hidirtybuffers
- mid2
);
996 delay
= delay
* 10 / (10 + priority
);
999 tsleep(&count
, 0, "flstik", delay
);
1004 * Now we are really in trouble.
1007 spin_lock_wr(&needsbuffer_spin
);
1008 count
= runningbufcount
+ numdirtybuffers
;
1009 if (count
>= hidirtybuffers
) {
1010 needsbuffer
|= VFS_BIO_NEED_DIRTYFLUSH
;
1011 msleep(&needsbuffer
, &needsbuffer_spin
, 0, "flswai", 0);
1012 spin_unlock_wr(&needsbuffer_spin
);
1014 count
= runningbufcount
+ numdirtybuffers
;
1017 /* FUTURE - maybe */
1018 else if (runningbufcount
+ numdirtybuffershw
> hidirtybuffers
/ 2) {
1021 while (runningbufcount
+ numdirtybuffershw
> hidirtybuffers
) {
1022 needsbuffer
|= VFS_BIO_NEED_DIRTYFLUSH
;
1023 tsleep(&needsbuffer
, slpflags
, "newbuf",
1031 * buf_dirty_count_severe:
1033 * Return true if we have too many dirty buffers.
1036 buf_dirty_count_severe(void)
1038 return(runningbufcount
+ numdirtybuffers
>= hidirtybuffers
);
1044 * Release a busy buffer and, if requested, free its resources. The
1045 * buffer will be stashed in the appropriate bufqueue[] allowing it
1046 * to be accessed later as a cache entity or reused for other purposes.
1049 brelse(struct buf
*bp
)
1052 int saved_flags
= bp
->b_flags
;
1055 KASSERT(!(bp
->b_flags
& (B_CLUSTER
|B_PAGING
)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp
));
1060 * If B_NOCACHE is set we are being asked to destroy the buffer and
1061 * its backing store. Clear B_DELWRI.
1063 * B_NOCACHE is set in two cases: (1) when the caller really wants
1064 * to destroy the buffer and backing store and (2) when the caller
1065 * wants to destroy the buffer and backing store after a write
1068 if ((bp
->b_flags
& (B_NOCACHE
|B_DELWRI
)) == (B_NOCACHE
|B_DELWRI
)) {
1072 if (bp
->b_flags
& B_LOCKED
)
1073 bp
->b_flags
&= ~B_ERROR
;
1076 * If a write error occurs and the caller does not want to throw
1077 * away the buffer, redirty the buffer. This will also clear
1080 if (bp
->b_cmd
== BUF_CMD_WRITE
&&
1081 (bp
->b_flags
& (B_ERROR
| B_INVAL
)) == B_ERROR
) {
1083 * Failed write, redirty. Must clear B_ERROR to prevent
1084 * pages from being scrapped. If B_INVAL is set then
1085 * this case is not run and the next case is run to
1086 * destroy the buffer. B_INVAL can occur if the buffer
1087 * is outside the range supported by the underlying device.
1089 bp
->b_flags
&= ~B_ERROR
;
1091 } else if ((bp
->b_flags
& (B_NOCACHE
| B_INVAL
| B_ERROR
)) ||
1092 (bp
->b_bufsize
<= 0) || bp
->b_cmd
== BUF_CMD_FREEBLKS
) {
1094 * Either a failed I/O or we were asked to free or not
1097 * NOTE: HAMMER will set B_LOCKED in buf_deallocate if the
1098 * buffer cannot be immediately freed.
1100 bp
->b_flags
|= B_INVAL
;
1101 if (LIST_FIRST(&bp
->b_dep
) != NULL
)
1103 if (bp
->b_flags
& B_DELWRI
) {
1105 if (bp
->b_flags
& B_HEAVY
)
1106 --numdirtybuffershw
;
1109 bp
->b_flags
&= ~(B_DELWRI
| B_CACHE
);
1113 * We must clear B_RELBUF if B_DELWRI or B_LOCKED is set.
1114 * If vfs_vmio_release() is called with either bit set, the
1115 * underlying pages may wind up getting freed causing a previous
1116 * write (bdwrite()) to get 'lost' because pages associated with
1117 * a B_DELWRI bp are marked clean. Pages associated with a
1118 * B_LOCKED buffer may be mapped by the filesystem.
1120 * If we want to release the buffer ourselves (rather then the
1121 * originator asking us to release it), give the originator a
1122 * chance to countermand the release by setting B_LOCKED.
1124 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1125 * if B_DELWRI is set.
1127 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1128 * on pages to return pages to the VM page queues.
1130 if (bp
->b_flags
& (B_DELWRI
| B_LOCKED
)) {
1131 bp
->b_flags
&= ~B_RELBUF
;
1132 } else if (vm_page_count_severe()) {
1133 if (LIST_FIRST(&bp
->b_dep
) != NULL
)
1135 if (bp
->b_flags
& (B_DELWRI
| B_LOCKED
))
1136 bp
->b_flags
&= ~B_RELBUF
;
1138 bp
->b_flags
|= B_RELBUF
;
1142 * At this point destroying the buffer is governed by the B_INVAL
1143 * or B_RELBUF flags.
1145 bp
->b_cmd
= BUF_CMD_DONE
;
1148 * VMIO buffer rundown. Make sure the VM page array is restored
1149 * after an I/O may have replaces some of the pages with bogus pages
1150 * in order to not destroy dirty pages in a fill-in read.
1152 * Note that due to the code above, if a buffer is marked B_DELWRI
1153 * then the B_RELBUF and B_NOCACHE bits will always be clear.
1154 * B_INVAL may still be set, however.
1156 * For clean buffers, B_INVAL or B_RELBUF will destroy the buffer
1157 * but not the backing store. B_NOCACHE will destroy the backing
1160 * Note that dirty NFS buffers contain byte-granular write ranges
1161 * and should not be destroyed w/ B_INVAL even if the backing store
1164 if (bp
->b_flags
& B_VMIO
) {
1166 * Rundown for VMIO buffers which are not dirty NFS buffers.
1178 * Get the base offset and length of the buffer. Note that
1179 * in the VMIO case if the buffer block size is not
1180 * page-aligned then b_data pointer may not be page-aligned.
1181 * But our b_xio.xio_pages array *IS* page aligned.
1183 * block sizes less then DEV_BSIZE (usually 512) are not
1184 * supported due to the page granularity bits (m->valid,
1185 * m->dirty, etc...).
1187 * See man buf(9) for more information
1190 resid
= bp
->b_bufsize
;
1191 foff
= bp
->b_loffset
;
1193 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
1194 m
= bp
->b_xio
.xio_pages
[i
];
1195 vm_page_flag_clear(m
, PG_ZERO
);
1197 * If we hit a bogus page, fixup *all* of them
1198 * now. Note that we left these pages wired
1199 * when we removed them so they had better exist,
1200 * and they cannot be ripped out from under us so
1201 * no critical section protection is necessary.
1203 if (m
== bogus_page
) {
1205 poff
= OFF_TO_IDX(bp
->b_loffset
);
1207 for (j
= i
; j
< bp
->b_xio
.xio_npages
; j
++) {
1210 mtmp
= bp
->b_xio
.xio_pages
[j
];
1211 if (mtmp
== bogus_page
) {
1212 mtmp
= vm_page_lookup(obj
, poff
+ j
);
1214 panic("brelse: page missing");
1216 bp
->b_xio
.xio_pages
[j
] = mtmp
;
1220 if ((bp
->b_flags
& B_INVAL
) == 0) {
1221 pmap_qenter(trunc_page((vm_offset_t
)bp
->b_data
),
1222 bp
->b_xio
.xio_pages
, bp
->b_xio
.xio_npages
);
1224 m
= bp
->b_xio
.xio_pages
[i
];
1228 * Invalidate the backing store if B_NOCACHE is set
1229 * (e.g. used with vinvalbuf()). If this is NFS
1230 * we impose a requirement that the block size be
1231 * a multiple of PAGE_SIZE and create a temporary
1232 * hack to basically invalidate the whole page. The
1233 * problem is that NFS uses really odd buffer sizes
1234 * especially when tracking piecemeal writes and
1235 * it also vinvalbuf()'s a lot, which would result
1236 * in only partial page validation and invalidation
1237 * here. If the file page is mmap()'d, however,
1238 * all the valid bits get set so after we invalidate
1239 * here we would end up with weird m->valid values
1240 * like 0xfc. nfs_getpages() can't handle this so
1241 * we clear all the valid bits for the NFS case
1242 * instead of just some of them.
1244 * The real bug is the VM system having to set m->valid
1245 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1246 * itself is an artifact of the whole 512-byte
1247 * granular mess that exists to support odd block
1248 * sizes and UFS meta-data block sizes (e.g. 6144).
1249 * A complete rewrite is required.
1251 if (bp
->b_flags
& (B_NOCACHE
|B_ERROR
)) {
1252 int poffset
= foff
& PAGE_MASK
;
1255 presid
= PAGE_SIZE
- poffset
;
1256 if (bp
->b_vp
->v_tag
== VT_NFS
&&
1257 bp
->b_vp
->v_type
== VREG
) {
1259 } else if (presid
> resid
) {
1262 KASSERT(presid
>= 0, ("brelse: extra page"));
1263 vm_page_set_invalid(m
, poffset
, presid
);
1265 resid
-= PAGE_SIZE
- (foff
& PAGE_MASK
);
1266 foff
= (foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
;
1268 if (bp
->b_flags
& (B_INVAL
| B_RELBUF
))
1269 vfs_vmio_release(bp
);
1272 * Rundown for non-VMIO buffers.
1274 if (bp
->b_flags
& (B_INVAL
| B_RELBUF
)) {
1277 kprintf("brelse bp %p %08x/%08x: Warning, caught and fixed brelvp bug\n", bp
, saved_flags
, bp
->b_flags
);
1281 KKASSERT (LIST_FIRST(&bp
->b_dep
) == NULL
);
1287 if (bp
->b_qindex
!= BQUEUE_NONE
)
1288 panic("brelse: free buffer onto another queue???");
1289 if (BUF_REFCNTNB(bp
) > 1) {
1290 /* Temporary panic to verify exclusive locking */
1291 /* This panic goes away when we allow shared refs */
1292 panic("brelse: multiple refs");
1293 /* do not release to free list */
1300 * Figure out the correct queue to place the cleaned up buffer on.
1301 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1302 * disassociated from their vnode.
1304 if (bp
->b_flags
& B_LOCKED
) {
1306 * Buffers that are locked are placed in the locked queue
1307 * immediately, regardless of their state.
1309 bp
->b_qindex
= BQUEUE_LOCKED
;
1310 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_LOCKED
], bp
, b_freelist
);
1311 } else if (bp
->b_bufsize
== 0) {
1313 * Buffers with no memory. Due to conditionals near the top
1314 * of brelse() such buffers should probably already be
1315 * marked B_INVAL and disassociated from their vnode.
1317 bp
->b_flags
|= B_INVAL
;
1318 KASSERT(bp
->b_vp
== NULL
, ("bp1 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp
, saved_flags
, bp
->b_flags
, bp
->b_vp
));
1319 KKASSERT((bp
->b_flags
& B_HASHED
) == 0);
1320 if (bp
->b_kvasize
) {
1321 bp
->b_qindex
= BQUEUE_EMPTYKVA
;
1323 bp
->b_qindex
= BQUEUE_EMPTY
;
1325 TAILQ_INSERT_HEAD(&bufqueues
[bp
->b_qindex
], bp
, b_freelist
);
1326 } else if (bp
->b_flags
& (B_ERROR
| B_INVAL
| B_NOCACHE
| B_RELBUF
)) {
1328 * Buffers with junk contents. Again these buffers had better
1329 * already be disassociated from their vnode.
1331 KASSERT(bp
->b_vp
== NULL
, ("bp2 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp
, saved_flags
, bp
->b_flags
, bp
->b_vp
));
1332 KKASSERT((bp
->b_flags
& B_HASHED
) == 0);
1333 bp
->b_flags
|= B_INVAL
;
1334 bp
->b_qindex
= BQUEUE_CLEAN
;
1335 TAILQ_INSERT_HEAD(&bufqueues
[BQUEUE_CLEAN
], bp
, b_freelist
);
1338 * Remaining buffers. These buffers are still associated with
1341 switch(bp
->b_flags
& (B_DELWRI
|B_HEAVY
|B_AGE
)) {
1342 case B_DELWRI
| B_AGE
:
1343 bp
->b_qindex
= BQUEUE_DIRTY
;
1344 TAILQ_INSERT_HEAD(&bufqueues
[BQUEUE_DIRTY
], bp
, b_freelist
);
1347 bp
->b_qindex
= BQUEUE_DIRTY
;
1348 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_DIRTY
], bp
, b_freelist
);
1350 case B_DELWRI
| B_HEAVY
| B_AGE
:
1351 bp
->b_qindex
= BQUEUE_DIRTY_HW
;
1352 TAILQ_INSERT_HEAD(&bufqueues
[BQUEUE_DIRTY_HW
], bp
,
1355 case B_DELWRI
| B_HEAVY
:
1356 bp
->b_qindex
= BQUEUE_DIRTY_HW
;
1357 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_DIRTY_HW
], bp
,
1360 case B_HEAVY
| B_AGE
:
1362 bp
->b_qindex
= BQUEUE_CLEAN
;
1363 TAILQ_INSERT_HEAD(&bufqueues
[BQUEUE_CLEAN
], bp
, b_freelist
);
1366 bp
->b_qindex
= BQUEUE_CLEAN
;
1367 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_CLEAN
], bp
, b_freelist
);
1373 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1374 * on the correct queue.
1376 if ((bp
->b_flags
& (B_INVAL
|B_DELWRI
)) == (B_INVAL
|B_DELWRI
))
1380 * Fixup numfreebuffers count. The bp is on an appropriate queue
1381 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1382 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1383 * if B_INVAL is set ).
1385 if ((bp
->b_flags
& (B_LOCKED
|B_DELWRI
)) == 0)
1389 * Something we can maybe free or reuse
1391 if (bp
->b_bufsize
|| bp
->b_kvasize
)
1395 * Clean up temporary flags and unlock the buffer.
1397 bp
->b_flags
&= ~(B_ORDERED
| B_ASYNC
| B_NOCACHE
| B_AGE
| B_RELBUF
|
1406 * Release a buffer back to the appropriate queue but do not try to free
1407 * it. The buffer is expected to be used again soon.
1409 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1410 * biodone() to requeue an async I/O on completion. It is also used when
1411 * known good buffers need to be requeued but we think we may need the data
1414 * XXX we should be able to leave the B_RELBUF hint set on completion.
1417 bqrelse(struct buf
*bp
)
1421 KASSERT(!(bp
->b_flags
& (B_CLUSTER
|B_PAGING
)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp
));
1423 if (bp
->b_qindex
!= BQUEUE_NONE
)
1424 panic("bqrelse: free buffer onto another queue???");
1425 if (BUF_REFCNTNB(bp
) > 1) {
1426 /* do not release to free list */
1427 panic("bqrelse: multiple refs");
1432 if (bp
->b_flags
& B_LOCKED
) {
1434 * Locked buffers are released to the locked queue. However,
1435 * if the buffer is dirty it will first go into the dirty
1436 * queue and later on after the I/O completes successfully it
1437 * will be released to the locked queue.
1439 bp
->b_flags
&= ~B_ERROR
;
1440 bp
->b_qindex
= BQUEUE_LOCKED
;
1441 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_LOCKED
], bp
, b_freelist
);
1442 } else if (bp
->b_flags
& B_DELWRI
) {
1443 bp
->b_qindex
= (bp
->b_flags
& B_HEAVY
) ?
1444 BQUEUE_DIRTY_HW
: BQUEUE_DIRTY
;
1445 TAILQ_INSERT_TAIL(&bufqueues
[bp
->b_qindex
], bp
, b_freelist
);
1446 } else if (vm_page_count_severe()) {
1448 * We are too low on memory, we have to try to free the
1449 * buffer (most importantly: the wired pages making up its
1450 * backing store) *now*.
1456 bp
->b_qindex
= BQUEUE_CLEAN
;
1457 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_CLEAN
], bp
, b_freelist
);
1460 if ((bp
->b_flags
& B_LOCKED
) == 0 &&
1461 ((bp
->b_flags
& B_INVAL
) || (bp
->b_flags
& B_DELWRI
) == 0)) {
1466 * Something we can maybe free or reuse.
1468 if (bp
->b_bufsize
&& !(bp
->b_flags
& B_DELWRI
))
1472 * Final cleanup and unlock. Clear bits that are only used while a
1473 * buffer is actively locked.
1475 bp
->b_flags
&= ~(B_ORDERED
| B_ASYNC
| B_NOCACHE
| B_AGE
| B_RELBUF
);
1483 * Return backing pages held by the buffer 'bp' back to the VM system
1484 * if possible. The pages are freed if they are no longer valid or
1485 * attempt to free if it was used for direct I/O otherwise they are
1486 * sent to the page cache.
1488 * Pages that were marked busy are left alone and skipped.
1490 * The KVA mapping (b_data) for the underlying pages is removed by
1494 vfs_vmio_release(struct buf
*bp
)
1500 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
1501 m
= bp
->b_xio
.xio_pages
[i
];
1502 bp
->b_xio
.xio_pages
[i
] = NULL
;
1504 * In order to keep page LRU ordering consistent, put
1505 * everything on the inactive queue.
1507 vm_page_unwire(m
, 0);
1509 * We don't mess with busy pages, it is
1510 * the responsibility of the process that
1511 * busied the pages to deal with them.
1513 if ((m
->flags
& PG_BUSY
) || (m
->busy
!= 0))
1516 if (m
->wire_count
== 0) {
1517 vm_page_flag_clear(m
, PG_ZERO
);
1519 * Might as well free the page if we can and it has
1520 * no valid data. We also free the page if the
1521 * buffer was used for direct I/O.
1523 if ((bp
->b_flags
& B_ASYNC
) == 0 && !m
->valid
&&
1524 m
->hold_count
== 0) {
1526 vm_page_protect(m
, VM_PROT_NONE
);
1528 } else if (bp
->b_flags
& B_DIRECT
) {
1529 vm_page_try_to_free(m
);
1530 } else if (vm_page_count_severe()) {
1531 vm_page_try_to_cache(m
);
1536 pmap_qremove(trunc_page((vm_offset_t
) bp
->b_data
), bp
->b_xio
.xio_npages
);
1537 if (bp
->b_bufsize
) {
1541 bp
->b_xio
.xio_npages
= 0;
1542 bp
->b_flags
&= ~B_VMIO
;
1543 KKASSERT (LIST_FIRST(&bp
->b_dep
) == NULL
);
1551 * Implement clustered async writes for clearing out B_DELWRI buffers.
1552 * This is much better then the old way of writing only one buffer at
1553 * a time. Note that we may not be presented with the buffers in the
1554 * correct order, so we search for the cluster in both directions.
1556 * The buffer is locked on call.
1559 vfs_bio_awrite(struct buf
*bp
)
1563 off_t loffset
= bp
->b_loffset
;
1564 struct vnode
*vp
= bp
->b_vp
;
1572 * right now we support clustered writing only to regular files. If
1573 * we find a clusterable block we could be in the middle of a cluster
1574 * rather then at the beginning.
1576 * NOTE: b_bio1 contains the logical loffset and is aliased
1577 * to b_loffset. b_bio2 contains the translated block number.
1579 if ((vp
->v_type
== VREG
) &&
1580 (vp
->v_mount
!= 0) && /* Only on nodes that have the size info */
1581 (bp
->b_flags
& (B_CLUSTEROK
| B_INVAL
)) == B_CLUSTEROK
) {
1583 size
= vp
->v_mount
->mnt_stat
.f_iosize
;
1585 for (i
= size
; i
< MAXPHYS
; i
+= size
) {
1586 if ((bpa
= findblk(vp
, loffset
+ i
)) &&
1587 BUF_REFCNT(bpa
) == 0 &&
1588 ((bpa
->b_flags
& (B_DELWRI
| B_CLUSTEROK
| B_INVAL
)) ==
1589 (B_DELWRI
| B_CLUSTEROK
)) &&
1590 (bpa
->b_bufsize
== size
)) {
1591 if ((bpa
->b_bio2
.bio_offset
== NOOFFSET
) ||
1592 (bpa
->b_bio2
.bio_offset
!=
1593 bp
->b_bio2
.bio_offset
+ i
))
1599 for (j
= size
; i
+ j
<= MAXPHYS
&& j
<= loffset
; j
+= size
) {
1600 if ((bpa
= findblk(vp
, loffset
- j
)) &&
1601 BUF_REFCNT(bpa
) == 0 &&
1602 ((bpa
->b_flags
& (B_DELWRI
| B_CLUSTEROK
| B_INVAL
)) ==
1603 (B_DELWRI
| B_CLUSTEROK
)) &&
1604 (bpa
->b_bufsize
== size
)) {
1605 if ((bpa
->b_bio2
.bio_offset
== NOOFFSET
) ||
1606 (bpa
->b_bio2
.bio_offset
!=
1607 bp
->b_bio2
.bio_offset
- j
))
1616 * this is a possible cluster write
1618 if (nbytes
!= size
) {
1620 nwritten
= cluster_wbuild(vp
, size
,
1621 loffset
- j
, nbytes
);
1628 bp
->b_flags
|= B_ASYNC
;
1632 * default (old) behavior, writing out only one block
1634 * XXX returns b_bufsize instead of b_bcount for nwritten?
1636 nwritten
= bp
->b_bufsize
;
1645 * Find and initialize a new buffer header, freeing up existing buffers
1646 * in the bufqueues as necessary. The new buffer is returned locked.
1648 * Important: B_INVAL is not set. If the caller wishes to throw the
1649 * buffer away, the caller must set B_INVAL prior to calling brelse().
1652 * We have insufficient buffer headers
1653 * We have insufficient buffer space
1654 * buffer_map is too fragmented ( space reservation fails )
1655 * If we have to flush dirty buffers ( but we try to avoid this )
1657 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1658 * Instead we ask the buf daemon to do it for us. We attempt to
1659 * avoid piecemeal wakeups of the pageout daemon.
1663 getnewbuf(int blkflags
, int slptimeo
, int size
, int maxsize
)
1669 int slpflags
= (blkflags
& GETBLK_PCATCH
) ? PCATCH
: 0;
1670 static int flushingbufs
;
1673 * We can't afford to block since we might be holding a vnode lock,
1674 * which may prevent system daemons from running. We deal with
1675 * low-memory situations by proactively returning memory and running
1676 * async I/O rather then sync I/O.
1680 --getnewbufrestarts
;
1682 ++getnewbufrestarts
;
1685 * Setup for scan. If we do not have enough free buffers,
1686 * we setup a degenerate case that immediately fails. Note
1687 * that if we are specially marked process, we are allowed to
1688 * dip into our reserves.
1690 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1692 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1693 * However, there are a number of cases (defragging, reusing, ...)
1694 * where we cannot backup.
1696 nqindex
= BQUEUE_EMPTYKVA
;
1697 nbp
= TAILQ_FIRST(&bufqueues
[BQUEUE_EMPTYKVA
]);
1701 * If no EMPTYKVA buffers and we are either
1702 * defragging or reusing, locate a CLEAN buffer
1703 * to free or reuse. If bufspace useage is low
1704 * skip this step so we can allocate a new buffer.
1706 if (defrag
|| bufspace
>= lobufspace
) {
1707 nqindex
= BQUEUE_CLEAN
;
1708 nbp
= TAILQ_FIRST(&bufqueues
[BQUEUE_CLEAN
]);
1712 * If we could not find or were not allowed to reuse a
1713 * CLEAN buffer, check to see if it is ok to use an EMPTY
1714 * buffer. We can only use an EMPTY buffer if allocating
1715 * its KVA would not otherwise run us out of buffer space.
1717 if (nbp
== NULL
&& defrag
== 0 &&
1718 bufspace
+ maxsize
< hibufspace
) {
1719 nqindex
= BQUEUE_EMPTY
;
1720 nbp
= TAILQ_FIRST(&bufqueues
[BQUEUE_EMPTY
]);
1725 * Run scan, possibly freeing data and/or kva mappings on the fly
1729 while ((bp
= nbp
) != NULL
) {
1730 int qindex
= nqindex
;
1733 * Calculate next bp ( we can only use it if we do not block
1734 * or do other fancy things ).
1736 if ((nbp
= TAILQ_NEXT(bp
, b_freelist
)) == NULL
) {
1739 nqindex
= BQUEUE_EMPTYKVA
;
1740 if ((nbp
= TAILQ_FIRST(&bufqueues
[BQUEUE_EMPTYKVA
])))
1743 case BQUEUE_EMPTYKVA
:
1744 nqindex
= BQUEUE_CLEAN
;
1745 if ((nbp
= TAILQ_FIRST(&bufqueues
[BQUEUE_CLEAN
])))
1759 KASSERT(bp
->b_qindex
== qindex
, ("getnewbuf: inconsistent queue %d bp %p", qindex
, bp
));
1762 * Note: we no longer distinguish between VMIO and non-VMIO
1766 KASSERT((bp
->b_flags
& B_DELWRI
) == 0, ("delwri buffer %p found in queue %d", bp
, qindex
));
1769 * If we are defragging then we need a buffer with
1770 * b_kvasize != 0. XXX this situation should no longer
1771 * occur, if defrag is non-zero the buffer's b_kvasize
1772 * should also be non-zero at this point. XXX
1774 if (defrag
&& bp
->b_kvasize
== 0) {
1775 kprintf("Warning: defrag empty buffer %p\n", bp
);
1780 * Start freeing the bp. This is somewhat involved. nbp
1781 * remains valid only for BQUEUE_EMPTY[KVA] bp's. Buffers
1782 * on the clean list must be disassociated from their
1783 * current vnode. Buffers on the empty[kva] lists have
1784 * already been disassociated.
1787 if (BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_NOWAIT
) != 0) {
1788 kprintf("getnewbuf: warning, locked buf %p, race corrected\n", bp
);
1789 tsleep(&bd_request
, 0, "gnbxxx", hz
/ 100);
1792 if (bp
->b_qindex
!= qindex
) {
1793 kprintf("getnewbuf: warning, BUF_LOCK blocked unexpectedly on buf %p index %d->%d, race corrected\n", bp
, qindex
, bp
->b_qindex
);
1800 * Dependancies must be handled before we disassociate the
1803 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
1804 * be immediately disassociated. HAMMER then becomes
1805 * responsible for releasing the buffer.
1807 if (LIST_FIRST(&bp
->b_dep
) != NULL
) {
1809 if (bp
->b_flags
& B_LOCKED
) {
1813 KKASSERT(LIST_FIRST(&bp
->b_dep
) == NULL
);
1816 if (qindex
== BQUEUE_CLEAN
) {
1817 if (bp
->b_flags
& B_VMIO
) {
1818 bp
->b_flags
&= ~B_ASYNC
;
1819 vfs_vmio_release(bp
);
1826 * NOTE: nbp is now entirely invalid. We can only restart
1827 * the scan from this point on.
1829 * Get the rest of the buffer freed up. b_kva* is still
1830 * valid after this operation.
1833 KASSERT(bp
->b_vp
== NULL
, ("bp3 %p flags %08x vnode %p qindex %d unexpectededly still associated!", bp
, bp
->b_flags
, bp
->b_vp
, qindex
));
1834 KKASSERT((bp
->b_flags
& B_HASHED
) == 0);
1837 * critical section protection is not required when
1838 * scrapping a buffer's contents because it is already
1844 bp
->b_flags
= B_BNOCLIP
;
1845 bp
->b_cmd
= BUF_CMD_DONE
;
1850 bp
->b_xio
.xio_npages
= 0;
1851 bp
->b_dirtyoff
= bp
->b_dirtyend
= 0;
1854 if (blkflags
& GETBLK_BHEAVY
)
1855 bp
->b_flags
|= B_HEAVY
;
1858 * If we are defragging then free the buffer.
1861 bp
->b_flags
|= B_INVAL
;
1869 * If we are overcomitted then recover the buffer and its
1870 * KVM space. This occurs in rare situations when multiple
1871 * processes are blocked in getnewbuf() or allocbuf().
1873 if (bufspace
>= hibufspace
)
1875 if (flushingbufs
&& bp
->b_kvasize
!= 0) {
1876 bp
->b_flags
|= B_INVAL
;
1881 if (bufspace
< lobufspace
)
1887 * If we exhausted our list, sleep as appropriate. We may have to
1888 * wakeup various daemons and write out some dirty buffers.
1890 * Generally we are sleeping due to insufficient buffer space.
1898 flags
= VFS_BIO_NEED_BUFSPACE
;
1900 } else if (bufspace
>= hibufspace
) {
1902 flags
= VFS_BIO_NEED_BUFSPACE
;
1905 flags
= VFS_BIO_NEED_ANY
;
1908 needsbuffer
|= flags
;
1909 bd_speedup(); /* heeeelp */
1910 while (needsbuffer
& flags
) {
1911 if (tsleep(&needsbuffer
, slpflags
, waitmsg
, slptimeo
))
1916 * We finally have a valid bp. We aren't quite out of the
1917 * woods, we still have to reserve kva space. In order
1918 * to keep fragmentation sane we only allocate kva in
1921 maxsize
= (maxsize
+ BKVAMASK
) & ~BKVAMASK
;
1923 if (maxsize
!= bp
->b_kvasize
) {
1924 vm_offset_t addr
= 0;
1929 count
= vm_map_entry_reserve(MAP_RESERVE_COUNT
);
1930 vm_map_lock(&buffer_map
);
1932 if (vm_map_findspace(&buffer_map
,
1933 vm_map_min(&buffer_map
), maxsize
,
1936 * Uh oh. Buffer map is too fragmented. We
1937 * must defragment the map.
1939 vm_map_unlock(&buffer_map
);
1940 vm_map_entry_release(count
);
1943 bp
->b_flags
|= B_INVAL
;
1948 vm_map_insert(&buffer_map
, &count
,
1950 addr
, addr
+ maxsize
,
1952 VM_PROT_ALL
, VM_PROT_ALL
,
1955 bp
->b_kvabase
= (caddr_t
) addr
;
1956 bp
->b_kvasize
= maxsize
;
1957 bufspace
+= bp
->b_kvasize
;
1960 vm_map_unlock(&buffer_map
);
1961 vm_map_entry_release(count
);
1963 bp
->b_data
= bp
->b_kvabase
;
1971 * Buffer flushing daemon. Buffers are normally flushed by the
1972 * update daemon but if it cannot keep up this process starts to
1973 * take the load in an attempt to prevent getnewbuf() from blocking.
1975 * Once a flush is initiated it does not stop until the number
1976 * of buffers falls below lodirtybuffers, but we will wake up anyone
1977 * waiting at the mid-point.
1980 static struct thread
*bufdaemon_td
;
1981 static struct thread
*bufdaemonhw_td
;
1983 static struct kproc_desc buf_kp
= {
1988 SYSINIT(bufdaemon
, SI_SUB_KTHREAD_BUF
, SI_ORDER_FIRST
,
1989 kproc_start
, &buf_kp
)
1991 static struct kproc_desc bufhw_kp
= {
1996 SYSINIT(bufdaemon_hw
, SI_SUB_KTHREAD_BUF
, SI_ORDER_FIRST
,
1997 kproc_start
, &bufhw_kp
)
2003 * This process needs to be suspended prior to shutdown sync.
2005 EVENTHANDLER_REGISTER(shutdown_pre_sync
, shutdown_kproc
,
2006 bufdaemon_td
, SHUTDOWN_PRI_LAST
);
2009 * This process is allowed to take the buffer cache to the limit
2014 kproc_suspend_loop();
2017 * Do the flush. Limit the amount of in-transit I/O we
2018 * allow to build up, otherwise we would completely saturate
2019 * the I/O system. Wakeup any waiting processes before we
2020 * normally would so they can run in parallel with our drain.
2022 while (numdirtybuffers
> lodirtybuffers
) {
2023 if (flushbufqueues(BQUEUE_DIRTY
) == 0)
2025 waitrunningbufspace();
2028 if (runningbufcount
+ numdirtybuffers
> lodirtybuffers
) {
2029 waitrunningbufspace();
2034 * Only clear bd_request if we have reached our low water
2035 * mark. The buf_daemon normally waits 5 seconds and
2036 * then incrementally flushes any dirty buffers that have
2037 * built up, within reason.
2039 * If we were unable to hit our low water mark and couldn't
2040 * find any flushable buffers, we sleep half a second.
2041 * Otherwise we loop immediately.
2043 if (runningbufcount
+ numdirtybuffers
<= lodirtybuffers
) {
2045 * We reached our low water mark, reset the
2046 * request and sleep until we are needed again.
2047 * The sleep is just so the suspend code works.
2049 spin_lock_wr(&needsbuffer_spin
);
2051 msleep(&bd_request
, &needsbuffer_spin
, 0,
2053 spin_unlock_wr(&needsbuffer_spin
);
2056 * We couldn't find any flushable dirty buffers but
2057 * still have too many dirty buffers, we
2058 * have to sleep and try again. (rare)
2060 tsleep(&bd_request
, 0, "qsleep", hz
/ 2);
2069 * This process needs to be suspended prior to shutdown sync.
2071 EVENTHANDLER_REGISTER(shutdown_pre_sync
, shutdown_kproc
,
2072 bufdaemonhw_td
, SHUTDOWN_PRI_LAST
);
2075 * This process is allowed to take the buffer cache to the limit
2080 kproc_suspend_loop();
2083 * Do the flush. Limit the amount of in-transit I/O we
2084 * allow to build up, otherwise we would completely saturate
2085 * the I/O system. Wakeup any waiting processes before we
2086 * normally would so they can run in parallel with our drain.
2088 while (numdirtybuffershw
> lodirtybuffers
) {
2089 if (flushbufqueues(BQUEUE_DIRTY_HW
) == 0)
2091 waitrunningbufspace();
2094 if (runningbufcount
+ numdirtybuffershw
> lodirtybuffers
) {
2095 waitrunningbufspace();
2099 * Only clear bd_request if we have reached our low water
2100 * mark. The buf_daemon normally waits 5 seconds and
2101 * then incrementally flushes any dirty buffers that have
2102 * built up, within reason.
2104 * If we were unable to hit our low water mark and couldn't
2105 * find any flushable buffers, we sleep half a second.
2106 * Otherwise we loop immediately.
2108 if (runningbufcount
+ numdirtybuffershw
<= lodirtybuffers
) {
2110 * We reached our low water mark, reset the
2111 * request and sleep until we are needed again.
2112 * The sleep is just so the suspend code works.
2114 spin_lock_wr(&needsbuffer_spin
);
2116 msleep(&bd_request_hw
, &needsbuffer_spin
, 0,
2118 spin_unlock_wr(&needsbuffer_spin
);
2121 * We couldn't find any flushable dirty buffers but
2122 * still have too many dirty buffers, we
2123 * have to sleep and try again. (rare)
2125 tsleep(&bd_request_hw
, 0, "qsleep", hz
/ 2);
2133 * Try to flush a buffer in the dirty queue. We must be careful to
2134 * free up B_INVAL buffers instead of write them, which NFS is
2135 * particularly sensitive to.
2139 flushbufqueues(bufq_type_t q
)
2144 bp
= TAILQ_FIRST(&bufqueues
[q
]);
2147 KASSERT((bp
->b_flags
& B_DELWRI
),
2148 ("unexpected clean buffer %p", bp
));
2149 if (bp
->b_flags
& B_DELWRI
) {
2150 if (bp
->b_flags
& B_INVAL
) {
2151 if (BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_NOWAIT
) != 0)
2152 panic("flushbufqueues: locked buf");
2158 if (LIST_FIRST(&bp
->b_dep
) != NULL
&&
2159 (bp
->b_flags
& B_DEFERRED
) == 0 &&
2160 buf_countdeps(bp
, 0)) {
2161 TAILQ_REMOVE(&bufqueues
[q
], bp
, b_freelist
);
2162 TAILQ_INSERT_TAIL(&bufqueues
[q
], bp
,
2164 bp
->b_flags
|= B_DEFERRED
;
2165 bp
= TAILQ_FIRST(&bufqueues
[q
]);
2170 * Only write it out if we can successfully lock
2171 * it. If the buffer has a dependancy,
2172 * buf_checkwrite must also return 0.
2174 if (BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_NOWAIT
) == 0) {
2175 if (LIST_FIRST(&bp
->b_dep
) != NULL
&&
2176 buf_checkwrite(bp
)) {
2186 bp
= TAILQ_NEXT(bp
, b_freelist
);
2194 * Returns true if no I/O is needed to access the associated VM object.
2195 * This is like findblk except it also hunts around in the VM system for
2198 * Note that we ignore vm_page_free() races from interrupts against our
2199 * lookup, since if the caller is not protected our return value will not
2200 * be any more valid then otherwise once we exit the critical section.
2203 inmem(struct vnode
*vp
, off_t loffset
)
2206 vm_offset_t toff
, tinc
, size
;
2209 if (findblk(vp
, loffset
))
2211 if (vp
->v_mount
== NULL
)
2213 if ((obj
= vp
->v_object
) == NULL
)
2217 if (size
> vp
->v_mount
->mnt_stat
.f_iosize
)
2218 size
= vp
->v_mount
->mnt_stat
.f_iosize
;
2220 for (toff
= 0; toff
< vp
->v_mount
->mnt_stat
.f_iosize
; toff
+= tinc
) {
2221 m
= vm_page_lookup(obj
, OFF_TO_IDX(loffset
+ toff
));
2225 if (tinc
> PAGE_SIZE
- ((toff
+ loffset
) & PAGE_MASK
))
2226 tinc
= PAGE_SIZE
- ((toff
+ loffset
) & PAGE_MASK
);
2227 if (vm_page_is_valid(m
,
2228 (vm_offset_t
) ((toff
+ loffset
) & PAGE_MASK
), tinc
) == 0)
2237 * Sets the dirty range for a buffer based on the status of the dirty
2238 * bits in the pages comprising the buffer.
2240 * The range is limited to the size of the buffer.
2242 * This routine is primarily used by NFS, but is generalized for the
2246 vfs_setdirty(struct buf
*bp
)
2252 * Degenerate case - empty buffer
2255 if (bp
->b_bufsize
== 0)
2259 * We qualify the scan for modified pages on whether the
2260 * object has been flushed yet. The OBJ_WRITEABLE flag
2261 * is not cleared simply by protecting pages off.
2264 if ((bp
->b_flags
& B_VMIO
) == 0)
2267 object
= bp
->b_xio
.xio_pages
[0]->object
;
2269 if ((object
->flags
& OBJ_WRITEABLE
) && !(object
->flags
& OBJ_MIGHTBEDIRTY
))
2270 kprintf("Warning: object %p writeable but not mightbedirty\n", object
);
2271 if (!(object
->flags
& OBJ_WRITEABLE
) && (object
->flags
& OBJ_MIGHTBEDIRTY
))
2272 kprintf("Warning: object %p mightbedirty but not writeable\n", object
);
2274 if (object
->flags
& (OBJ_MIGHTBEDIRTY
|OBJ_CLEANING
)) {
2275 vm_offset_t boffset
;
2276 vm_offset_t eoffset
;
2279 * test the pages to see if they have been modified directly
2280 * by users through the VM system.
2282 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
2283 vm_page_flag_clear(bp
->b_xio
.xio_pages
[i
], PG_ZERO
);
2284 vm_page_test_dirty(bp
->b_xio
.xio_pages
[i
]);
2288 * Calculate the encompassing dirty range, boffset and eoffset,
2289 * (eoffset - boffset) bytes.
2292 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
2293 if (bp
->b_xio
.xio_pages
[i
]->dirty
)
2296 boffset
= (i
<< PAGE_SHIFT
) - (bp
->b_loffset
& PAGE_MASK
);
2298 for (i
= bp
->b_xio
.xio_npages
- 1; i
>= 0; --i
) {
2299 if (bp
->b_xio
.xio_pages
[i
]->dirty
) {
2303 eoffset
= ((i
+ 1) << PAGE_SHIFT
) - (bp
->b_loffset
& PAGE_MASK
);
2306 * Fit it to the buffer.
2309 if (eoffset
> bp
->b_bcount
)
2310 eoffset
= bp
->b_bcount
;
2313 * If we have a good dirty range, merge with the existing
2317 if (boffset
< eoffset
) {
2318 if (bp
->b_dirtyoff
> boffset
)
2319 bp
->b_dirtyoff
= boffset
;
2320 if (bp
->b_dirtyend
< eoffset
)
2321 bp
->b_dirtyend
= eoffset
;
2329 * Locate and return the specified buffer, or NULL if the buffer does
2330 * not exist. Do not attempt to lock the buffer or manipulate it in
2331 * any way. The caller must validate that the correct buffer has been
2332 * obtain after locking it.
2335 findblk(struct vnode
*vp
, off_t loffset
)
2340 bp
= buf_rb_hash_RB_LOOKUP(&vp
->v_rbhash_tree
, loffset
);
2348 * Get a block given a specified block and offset into a file/device.
2349 * B_INVAL may or may not be set on return. The caller should clear
2350 * B_INVAL prior to initiating a READ.
2352 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2353 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2354 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2355 * without doing any of those things the system will likely believe
2356 * the buffer to be valid (especially if it is not B_VMIO), and the
2357 * next getblk() will return the buffer with B_CACHE set.
2359 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2360 * an existing buffer.
2362 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2363 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2364 * and then cleared based on the backing VM. If the previous buffer is
2365 * non-0-sized but invalid, B_CACHE will be cleared.
2367 * If getblk() must create a new buffer, the new buffer is returned with
2368 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2369 * case it is returned with B_INVAL clear and B_CACHE set based on the
2372 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
2373 * B_CACHE bit is clear.
2375 * What this means, basically, is that the caller should use B_CACHE to
2376 * determine whether the buffer is fully valid or not and should clear
2377 * B_INVAL prior to issuing a read. If the caller intends to validate
2378 * the buffer by loading its data area with something, the caller needs
2379 * to clear B_INVAL. If the caller does this without issuing an I/O,
2380 * the caller should set B_CACHE ( as an optimization ), else the caller
2381 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2382 * a write attempt or if it was a successfull read. If the caller
2383 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2384 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2388 * GETBLK_PCATCH - catch signal if blocked, can cause NULL return
2389 * GETBLK_BHEAVY - heavy-weight buffer cache buffer
2392 getblk(struct vnode
*vp
, off_t loffset
, int size
, int blkflags
, int slptimeo
)
2395 int slpflags
= (blkflags
& GETBLK_PCATCH
) ? PCATCH
: 0;
2397 if (size
> MAXBSIZE
)
2398 panic("getblk: size(%d) > MAXBSIZE(%d)", size
, MAXBSIZE
);
2399 if (vp
->v_object
== NULL
)
2400 panic("getblk: vnode %p has no object!", vp
);
2404 if ((bp
= findblk(vp
, loffset
))) {
2406 * The buffer was found in the cache, but we need to lock it.
2407 * Even with LK_NOWAIT the lockmgr may break our critical
2408 * section, so double-check the validity of the buffer
2409 * once the lock has been obtained.
2411 if (BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_NOWAIT
)) {
2412 int lkflags
= LK_EXCLUSIVE
| LK_SLEEPFAIL
;
2413 if (blkflags
& GETBLK_PCATCH
)
2414 lkflags
|= LK_PCATCH
;
2415 if (BUF_TIMELOCK(bp
, lkflags
, "getblk", slptimeo
) ==
2424 * Once the buffer has been locked, make sure we didn't race
2425 * a buffer recyclement. Buffers that are no longer hashed
2426 * will have b_vp == NULL, so this takes care of that check
2429 if (bp
->b_vp
!= vp
|| bp
->b_loffset
!= loffset
) {
2430 kprintf("Warning buffer %p (vp %p loffset %lld) was recycled\n", bp
, vp
, loffset
);
2436 * All vnode-based buffers must be backed by a VM object.
2438 KKASSERT(bp
->b_flags
& B_VMIO
);
2439 KKASSERT(bp
->b_cmd
== BUF_CMD_DONE
);
2442 * Make sure that B_INVAL buffers do not have a cached
2443 * block number translation.
2445 if ((bp
->b_flags
& B_INVAL
) && (bp
->b_bio2
.bio_offset
!= NOOFFSET
)) {
2446 kprintf("Warning invalid buffer %p (vp %p loffset %lld) did not have cleared bio_offset cache\n", bp
, vp
, loffset
);
2447 clearbiocache(&bp
->b_bio2
);
2451 * The buffer is locked. B_CACHE is cleared if the buffer is
2454 if (bp
->b_flags
& B_INVAL
)
2455 bp
->b_flags
&= ~B_CACHE
;
2459 * Any size inconsistancy with a dirty buffer or a buffer
2460 * with a softupdates dependancy must be resolved. Resizing
2461 * the buffer in such circumstances can lead to problems.
2463 if (size
!= bp
->b_bcount
) {
2464 if (bp
->b_flags
& B_DELWRI
) {
2465 bp
->b_flags
|= B_NOCACHE
;
2467 } else if (LIST_FIRST(&bp
->b_dep
)) {
2468 bp
->b_flags
|= B_NOCACHE
;
2471 bp
->b_flags
|= B_RELBUF
;
2476 KKASSERT(size
<= bp
->b_kvasize
);
2477 KASSERT(bp
->b_loffset
!= NOOFFSET
,
2478 ("getblk: no buffer offset"));
2481 * A buffer with B_DELWRI set and B_CACHE clear must
2482 * be committed before we can return the buffer in
2483 * order to prevent the caller from issuing a read
2484 * ( due to B_CACHE not being set ) and overwriting
2487 * Most callers, including NFS and FFS, need this to
2488 * operate properly either because they assume they
2489 * can issue a read if B_CACHE is not set, or because
2490 * ( for example ) an uncached B_DELWRI might loop due
2491 * to softupdates re-dirtying the buffer. In the latter
2492 * case, B_CACHE is set after the first write completes,
2493 * preventing further loops.
2495 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2496 * above while extending the buffer, we cannot allow the
2497 * buffer to remain with B_CACHE set after the write
2498 * completes or it will represent a corrupt state. To
2499 * deal with this we set B_NOCACHE to scrap the buffer
2502 * We might be able to do something fancy, like setting
2503 * B_CACHE in bwrite() except if B_DELWRI is already set,
2504 * so the below call doesn't set B_CACHE, but that gets real
2505 * confusing. This is much easier.
2508 if ((bp
->b_flags
& (B_CACHE
|B_DELWRI
)) == B_DELWRI
) {
2509 bp
->b_flags
|= B_NOCACHE
;
2516 * Buffer is not in-core, create new buffer. The buffer
2517 * returned by getnewbuf() is locked. Note that the returned
2518 * buffer is also considered valid (not marked B_INVAL).
2520 * Calculating the offset for the I/O requires figuring out
2521 * the block size. We use DEV_BSIZE for VBLK or VCHR and
2522 * the mount's f_iosize otherwise. If the vnode does not
2523 * have an associated mount we assume that the passed size is
2526 * Note that vn_isdisk() cannot be used here since it may
2527 * return a failure for numerous reasons. Note that the
2528 * buffer size may be larger then the block size (the caller
2529 * will use block numbers with the proper multiple). Beware
2530 * of using any v_* fields which are part of unions. In
2531 * particular, in DragonFly the mount point overloading
2532 * mechanism uses the namecache only and the underlying
2533 * directory vnode is not a special case.
2537 if (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
)
2539 else if (vp
->v_mount
)
2540 bsize
= vp
->v_mount
->mnt_stat
.f_iosize
;
2544 maxsize
= size
+ (loffset
& PAGE_MASK
);
2545 maxsize
= imax(maxsize
, bsize
);
2547 if ((bp
= getnewbuf(blkflags
, slptimeo
, size
, maxsize
)) == NULL
) {
2548 if (slpflags
|| slptimeo
) {
2556 * This code is used to make sure that a buffer is not
2557 * created while the getnewbuf routine is blocked.
2558 * This can be a problem whether the vnode is locked or not.
2559 * If the buffer is created out from under us, we have to
2560 * throw away the one we just created. There is no window
2561 * race because we are safely running in a critical section
2562 * from the point of the duplicate buffer creation through
2563 * to here, and we've locked the buffer.
2565 if (findblk(vp
, loffset
)) {
2566 bp
->b_flags
|= B_INVAL
;
2572 * Insert the buffer into the hash, so that it can
2573 * be found by findblk().
2575 * Make sure the translation layer has been cleared.
2577 bp
->b_loffset
= loffset
;
2578 bp
->b_bio2
.bio_offset
= NOOFFSET
;
2579 /* bp->b_bio2.bio_next = NULL; */
2584 * All vnode-based buffers must be backed by a VM object.
2586 KKASSERT(vp
->v_object
!= NULL
);
2587 bp
->b_flags
|= B_VMIO
;
2588 KKASSERT(bp
->b_cmd
== BUF_CMD_DONE
);
2600 * Reacquire a buffer that was previously released to the locked queue,
2601 * or reacquire a buffer which is interlocked by having bioops->io_deallocate
2602 * set B_LOCKED (which handles the acquisition race).
2604 * To this end, either B_LOCKED must be set or the dependancy list must be
2608 regetblk(struct buf
*bp
)
2610 KKASSERT((bp
->b_flags
& B_LOCKED
) || LIST_FIRST(&bp
->b_dep
) != NULL
);
2611 BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_RETRY
);
2620 * Get an empty, disassociated buffer of given size. The buffer is
2621 * initially set to B_INVAL.
2623 * critical section protection is not required for the allocbuf()
2624 * call because races are impossible here.
2632 maxsize
= (size
+ BKVAMASK
) & ~BKVAMASK
;
2635 while ((bp
= getnewbuf(0, 0, size
, maxsize
)) == 0)
2639 bp
->b_flags
|= B_INVAL
; /* b_dep cleared by getnewbuf() */
2647 * This code constitutes the buffer memory from either anonymous system
2648 * memory (in the case of non-VMIO operations) or from an associated
2649 * VM object (in the case of VMIO operations). This code is able to
2650 * resize a buffer up or down.
2652 * Note that this code is tricky, and has many complications to resolve
2653 * deadlock or inconsistant data situations. Tread lightly!!!
2654 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2655 * the caller. Calling this code willy nilly can result in the loss of data.
2657 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2658 * B_CACHE for the non-VMIO case.
2660 * This routine does not need to be called from a critical section but you
2661 * must own the buffer.
2664 allocbuf(struct buf
*bp
, int size
)
2666 int newbsize
, mbsize
;
2669 if (BUF_REFCNT(bp
) == 0)
2670 panic("allocbuf: buffer not busy");
2672 if (bp
->b_kvasize
< size
)
2673 panic("allocbuf: buffer too small");
2675 if ((bp
->b_flags
& B_VMIO
) == 0) {
2679 * Just get anonymous memory from the kernel. Don't
2680 * mess with B_CACHE.
2682 mbsize
= (size
+ DEV_BSIZE
- 1) & ~(DEV_BSIZE
- 1);
2683 if (bp
->b_flags
& B_MALLOC
)
2686 newbsize
= round_page(size
);
2688 if (newbsize
< bp
->b_bufsize
) {
2690 * Malloced buffers are not shrunk
2692 if (bp
->b_flags
& B_MALLOC
) {
2694 bp
->b_bcount
= size
;
2696 kfree(bp
->b_data
, M_BIOBUF
);
2697 if (bp
->b_bufsize
) {
2698 bufmallocspace
-= bp
->b_bufsize
;
2702 bp
->b_data
= bp
->b_kvabase
;
2704 bp
->b_flags
&= ~B_MALLOC
;
2710 (vm_offset_t
) bp
->b_data
+ newbsize
,
2711 (vm_offset_t
) bp
->b_data
+ bp
->b_bufsize
);
2712 } else if (newbsize
> bp
->b_bufsize
) {
2714 * We only use malloced memory on the first allocation.
2715 * and revert to page-allocated memory when the buffer
2718 if ((bufmallocspace
< maxbufmallocspace
) &&
2719 (bp
->b_bufsize
== 0) &&
2720 (mbsize
<= PAGE_SIZE
/2)) {
2722 bp
->b_data
= kmalloc(mbsize
, M_BIOBUF
, M_WAITOK
);
2723 bp
->b_bufsize
= mbsize
;
2724 bp
->b_bcount
= size
;
2725 bp
->b_flags
|= B_MALLOC
;
2726 bufmallocspace
+= mbsize
;
2732 * If the buffer is growing on its other-than-first
2733 * allocation, then we revert to the page-allocation
2736 if (bp
->b_flags
& B_MALLOC
) {
2737 origbuf
= bp
->b_data
;
2738 origbufsize
= bp
->b_bufsize
;
2739 bp
->b_data
= bp
->b_kvabase
;
2740 if (bp
->b_bufsize
) {
2741 bufmallocspace
-= bp
->b_bufsize
;
2745 bp
->b_flags
&= ~B_MALLOC
;
2746 newbsize
= round_page(newbsize
);
2750 (vm_offset_t
) bp
->b_data
+ bp
->b_bufsize
,
2751 (vm_offset_t
) bp
->b_data
+ newbsize
);
2753 bcopy(origbuf
, bp
->b_data
, origbufsize
);
2754 kfree(origbuf
, M_BIOBUF
);
2761 newbsize
= (size
+ DEV_BSIZE
- 1) & ~(DEV_BSIZE
- 1);
2762 desiredpages
= ((int)(bp
->b_loffset
& PAGE_MASK
) +
2763 newbsize
+ PAGE_MASK
) >> PAGE_SHIFT
;
2764 KKASSERT(desiredpages
<= XIO_INTERNAL_PAGES
);
2766 if (bp
->b_flags
& B_MALLOC
)
2767 panic("allocbuf: VMIO buffer can't be malloced");
2769 * Set B_CACHE initially if buffer is 0 length or will become
2772 if (size
== 0 || bp
->b_bufsize
== 0)
2773 bp
->b_flags
|= B_CACHE
;
2775 if (newbsize
< bp
->b_bufsize
) {
2777 * DEV_BSIZE aligned new buffer size is less then the
2778 * DEV_BSIZE aligned existing buffer size. Figure out
2779 * if we have to remove any pages.
2781 if (desiredpages
< bp
->b_xio
.xio_npages
) {
2782 for (i
= desiredpages
; i
< bp
->b_xio
.xio_npages
; i
++) {
2784 * the page is not freed here -- it
2785 * is the responsibility of
2786 * vnode_pager_setsize
2788 m
= bp
->b_xio
.xio_pages
[i
];
2789 KASSERT(m
!= bogus_page
,
2790 ("allocbuf: bogus page found"));
2791 while (vm_page_sleep_busy(m
, TRUE
, "biodep"))
2794 bp
->b_xio
.xio_pages
[i
] = NULL
;
2795 vm_page_unwire(m
, 0);
2797 pmap_qremove((vm_offset_t
) trunc_page((vm_offset_t
)bp
->b_data
) +
2798 (desiredpages
<< PAGE_SHIFT
), (bp
->b_xio
.xio_npages
- desiredpages
));
2799 bp
->b_xio
.xio_npages
= desiredpages
;
2801 } else if (size
> bp
->b_bcount
) {
2803 * We are growing the buffer, possibly in a
2804 * byte-granular fashion.
2812 * Step 1, bring in the VM pages from the object,
2813 * allocating them if necessary. We must clear
2814 * B_CACHE if these pages are not valid for the
2815 * range covered by the buffer.
2817 * critical section protection is required to protect
2818 * against interrupts unbusying and freeing pages
2819 * between our vm_page_lookup() and our
2820 * busycheck/wiring call.
2826 while (bp
->b_xio
.xio_npages
< desiredpages
) {
2830 pi
= OFF_TO_IDX(bp
->b_loffset
) + bp
->b_xio
.xio_npages
;
2831 if ((m
= vm_page_lookup(obj
, pi
)) == NULL
) {
2833 * note: must allocate system pages
2834 * since blocking here could intefere
2835 * with paging I/O, no matter which
2838 m
= vm_page_alloc(obj
, pi
, VM_ALLOC_NORMAL
| VM_ALLOC_SYSTEM
);
2841 vm_pageout_deficit
+= desiredpages
-
2842 bp
->b_xio
.xio_npages
;
2846 bp
->b_flags
&= ~B_CACHE
;
2847 bp
->b_xio
.xio_pages
[bp
->b_xio
.xio_npages
] = m
;
2848 ++bp
->b_xio
.xio_npages
;
2854 * We found a page. If we have to sleep on it,
2855 * retry because it might have gotten freed out
2858 * We can only test PG_BUSY here. Blocking on
2859 * m->busy might lead to a deadlock:
2861 * vm_fault->getpages->cluster_read->allocbuf
2865 if (vm_page_sleep_busy(m
, FALSE
, "pgtblk"))
2869 * We have a good page. Should we wakeup the
2872 if ((curthread
!= pagethread
) &&
2873 ((m
->queue
- m
->pc
) == PQ_CACHE
) &&
2874 ((vmstats
.v_free_count
+ vmstats
.v_cache_count
) <
2875 (vmstats
.v_free_min
+ vmstats
.v_cache_min
))) {
2876 pagedaemon_wakeup();
2878 vm_page_flag_clear(m
, PG_ZERO
);
2880 bp
->b_xio
.xio_pages
[bp
->b_xio
.xio_npages
] = m
;
2881 ++bp
->b_xio
.xio_npages
;
2886 * Step 2. We've loaded the pages into the buffer,
2887 * we have to figure out if we can still have B_CACHE
2888 * set. Note that B_CACHE is set according to the
2889 * byte-granular range ( bcount and size ), not the
2890 * aligned range ( newbsize ).
2892 * The VM test is against m->valid, which is DEV_BSIZE
2893 * aligned. Needless to say, the validity of the data
2894 * needs to also be DEV_BSIZE aligned. Note that this
2895 * fails with NFS if the server or some other client
2896 * extends the file's EOF. If our buffer is resized,
2897 * B_CACHE may remain set! XXX
2900 toff
= bp
->b_bcount
;
2901 tinc
= PAGE_SIZE
- ((bp
->b_loffset
+ toff
) & PAGE_MASK
);
2903 while ((bp
->b_flags
& B_CACHE
) && toff
< size
) {
2906 if (tinc
> (size
- toff
))
2909 pi
= ((bp
->b_loffset
& PAGE_MASK
) + toff
) >>
2917 bp
->b_xio
.xio_pages
[pi
]
2924 * Step 3, fixup the KVM pmap. Remember that
2925 * bp->b_data is relative to bp->b_loffset, but
2926 * bp->b_loffset may be offset into the first page.
2929 bp
->b_data
= (caddr_t
)
2930 trunc_page((vm_offset_t
)bp
->b_data
);
2932 (vm_offset_t
)bp
->b_data
,
2933 bp
->b_xio
.xio_pages
,
2934 bp
->b_xio
.xio_npages
2936 bp
->b_data
= (caddr_t
)((vm_offset_t
)bp
->b_data
|
2937 (vm_offset_t
)(bp
->b_loffset
& PAGE_MASK
));
2940 if (newbsize
< bp
->b_bufsize
)
2942 bp
->b_bufsize
= newbsize
; /* actual buffer allocation */
2943 bp
->b_bcount
= size
; /* requested buffer size */
2950 * Wait for buffer I/O completion, returning error status. The buffer
2951 * is left locked on return. B_EINTR is converted into an EINTR error
2954 * NOTE! The original b_cmd is lost on return, since b_cmd will be
2955 * set to BUF_CMD_DONE.
2958 biowait(struct buf
*bp
)
2961 while (bp
->b_cmd
!= BUF_CMD_DONE
) {
2962 if (bp
->b_cmd
== BUF_CMD_READ
)
2963 tsleep(bp
, 0, "biord", 0);
2965 tsleep(bp
, 0, "biowr", 0);
2968 if (bp
->b_flags
& B_EINTR
) {
2969 bp
->b_flags
&= ~B_EINTR
;
2972 if (bp
->b_flags
& B_ERROR
) {
2973 return (bp
->b_error
? bp
->b_error
: EIO
);
2980 * This associates a tracking count with an I/O. vn_strategy() and
2981 * dev_dstrategy() do this automatically but there are a few cases
2982 * where a vnode or device layer is bypassed when a block translation
2983 * is cached. In such cases bio_start_transaction() may be called on
2984 * the bypassed layers so the system gets an I/O in progress indication
2985 * for those higher layers.
2988 bio_start_transaction(struct bio
*bio
, struct bio_track
*track
)
2990 bio
->bio_track
= track
;
2991 atomic_add_int(&track
->bk_active
, 1);
2995 * Initiate I/O on a vnode.
2998 vn_strategy(struct vnode
*vp
, struct bio
*bio
)
3000 struct bio_track
*track
;
3002 KKASSERT(bio
->bio_buf
->b_cmd
!= BUF_CMD_DONE
);
3003 if (bio
->bio_buf
->b_cmd
== BUF_CMD_READ
)
3004 track
= &vp
->v_track_read
;
3006 track
= &vp
->v_track_write
;
3007 bio
->bio_track
= track
;
3008 atomic_add_int(&track
->bk_active
, 1);
3009 vop_strategy(*vp
->v_ops
, vp
, bio
);
3016 * Finish I/O on a buffer, optionally calling a completion function.
3017 * This is usually called from an interrupt so process blocking is
3020 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3021 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3022 * assuming B_INVAL is clear.
3024 * For the VMIO case, we set B_CACHE if the op was a read and no
3025 * read error occured, or if the op was a write. B_CACHE is never
3026 * set if the buffer is invalid or otherwise uncacheable.
3028 * biodone does not mess with B_INVAL, allowing the I/O routine or the
3029 * initiator to leave B_INVAL set to brelse the buffer out of existance
3030 * in the biodone routine.
3033 biodone(struct bio
*bio
)
3035 struct buf
*bp
= bio
->bio_buf
;
3040 KASSERT(BUF_REFCNTNB(bp
) > 0,
3041 ("biodone: bp %p not busy %d", bp
, BUF_REFCNTNB(bp
)));
3042 KASSERT(bp
->b_cmd
!= BUF_CMD_DONE
,
3043 ("biodone: bp %p already done!", bp
));
3045 runningbufwakeup(bp
);
3048 * Run up the chain of BIO's. Leave b_cmd intact for the duration.
3051 biodone_t
*done_func
;
3052 struct bio_track
*track
;
3055 * BIO tracking. Most but not all BIOs are tracked.
3057 if ((track
= bio
->bio_track
) != NULL
) {
3058 atomic_subtract_int(&track
->bk_active
, 1);
3059 if (track
->bk_active
< 0) {
3060 panic("biodone: bad active count bio %p\n",
3063 if (track
->bk_waitflag
) {
3064 track
->bk_waitflag
= 0;
3067 bio
->bio_track
= NULL
;
3071 * A bio_done function terminates the loop. The function
3072 * will be responsible for any further chaining and/or
3073 * buffer management.
3075 * WARNING! The done function can deallocate the buffer!
3077 if ((done_func
= bio
->bio_done
) != NULL
) {
3078 bio
->bio_done
= NULL
;
3083 bio
= bio
->bio_prev
;
3087 bp
->b_cmd
= BUF_CMD_DONE
;
3090 * Only reads and writes are processed past this point.
3092 if (cmd
!= BUF_CMD_READ
&& cmd
!= BUF_CMD_WRITE
) {
3099 * Warning: softupdates may re-dirty the buffer.
3101 if (LIST_FIRST(&bp
->b_dep
) != NULL
)
3104 if (bp
->b_flags
& B_VMIO
) {
3110 struct vnode
*vp
= bp
->b_vp
;
3114 #if defined(VFS_BIO_DEBUG)
3115 if (vp
->v_auxrefs
== 0)
3116 panic("biodone: zero vnode hold count");
3117 if ((vp
->v_flag
& VOBJBUF
) == 0)
3118 panic("biodone: vnode is not setup for merged cache");
3121 foff
= bp
->b_loffset
;
3122 KASSERT(foff
!= NOOFFSET
, ("biodone: no buffer offset"));
3123 KASSERT(obj
!= NULL
, ("biodone: missing VM object"));
3125 #if defined(VFS_BIO_DEBUG)
3126 if (obj
->paging_in_progress
< bp
->b_xio
.xio_npages
) {
3127 kprintf("biodone: paging in progress(%d) < bp->b_xio.xio_npages(%d)\n",
3128 obj
->paging_in_progress
, bp
->b_xio
.xio_npages
);
3133 * Set B_CACHE if the op was a normal read and no error
3134 * occured. B_CACHE is set for writes in the b*write()
3137 iosize
= bp
->b_bcount
- bp
->b_resid
;
3138 if (cmd
== BUF_CMD_READ
&& (bp
->b_flags
& (B_INVAL
|B_NOCACHE
|B_ERROR
)) == 0) {
3139 bp
->b_flags
|= B_CACHE
;
3142 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3146 resid
= ((foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
) - foff
;
3151 * cleanup bogus pages, restoring the originals. Since
3152 * the originals should still be wired, we don't have
3153 * to worry about interrupt/freeing races destroying
3154 * the VM object association.
3156 m
= bp
->b_xio
.xio_pages
[i
];
3157 if (m
== bogus_page
) {
3159 m
= vm_page_lookup(obj
, OFF_TO_IDX(foff
));
3161 panic("biodone: page disappeared");
3162 bp
->b_xio
.xio_pages
[i
] = m
;
3163 pmap_qenter(trunc_page((vm_offset_t
)bp
->b_data
),
3164 bp
->b_xio
.xio_pages
, bp
->b_xio
.xio_npages
);
3166 #if defined(VFS_BIO_DEBUG)
3167 if (OFF_TO_IDX(foff
) != m
->pindex
) {
3169 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
3170 (unsigned long)foff
, m
->pindex
);
3175 * In the write case, the valid and clean bits are
3176 * already changed correctly ( see bdwrite() ), so we
3177 * only need to do this here in the read case.
3179 if (cmd
== BUF_CMD_READ
&& !bogusflag
&& resid
> 0) {
3180 vfs_page_set_valid(bp
, foff
, i
, m
);
3182 vm_page_flag_clear(m
, PG_ZERO
);
3185 * when debugging new filesystems or buffer I/O methods, this
3186 * is the most common error that pops up. if you see this, you
3187 * have not set the page busy flag correctly!!!
3190 kprintf("biodone: page busy < 0, "
3191 "pindex: %d, foff: 0x(%x,%x), "
3192 "resid: %d, index: %d\n",
3193 (int) m
->pindex
, (int)(foff
>> 32),
3194 (int) foff
& 0xffffffff, resid
, i
);
3195 if (!vn_isdisk(vp
, NULL
))
3196 kprintf(" iosize: %ld, loffset: %lld, flags: 0x%08x, npages: %d\n",
3197 bp
->b_vp
->v_mount
->mnt_stat
.f_iosize
,
3199 bp
->b_flags
, bp
->b_xio
.xio_npages
);
3201 kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
3203 bp
->b_flags
, bp
->b_xio
.xio_npages
);
3204 kprintf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
3205 m
->valid
, m
->dirty
, m
->wire_count
);
3206 panic("biodone: page busy < 0");
3208 vm_page_io_finish(m
);
3209 vm_object_pip_subtract(obj
, 1);
3210 foff
= (foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
;
3214 vm_object_pip_wakeupn(obj
, 0);
3218 * For asynchronous completions, release the buffer now. The brelse
3219 * will do a wakeup there if necessary - so no need to do a wakeup
3220 * here in the async case. The sync case always needs to do a wakeup.
3223 if (bp
->b_flags
& B_ASYNC
) {
3224 if ((bp
->b_flags
& (B_NOCACHE
| B_INVAL
| B_ERROR
| B_RELBUF
)) != 0)
3237 * This routine is called in lieu of iodone in the case of
3238 * incomplete I/O. This keeps the busy status for pages
3242 vfs_unbusy_pages(struct buf
*bp
)
3246 runningbufwakeup(bp
);
3247 if (bp
->b_flags
& B_VMIO
) {
3248 struct vnode
*vp
= bp
->b_vp
;
3253 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3254 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
3257 * When restoring bogus changes the original pages
3258 * should still be wired, so we are in no danger of
3259 * losing the object association and do not need
3260 * critical section protection particularly.
3262 if (m
== bogus_page
) {
3263 m
= vm_page_lookup(obj
, OFF_TO_IDX(bp
->b_loffset
) + i
);
3265 panic("vfs_unbusy_pages: page missing");
3267 bp
->b_xio
.xio_pages
[i
] = m
;
3268 pmap_qenter(trunc_page((vm_offset_t
)bp
->b_data
),
3269 bp
->b_xio
.xio_pages
, bp
->b_xio
.xio_npages
);
3271 vm_object_pip_subtract(obj
, 1);
3272 vm_page_flag_clear(m
, PG_ZERO
);
3273 vm_page_io_finish(m
);
3275 vm_object_pip_wakeupn(obj
, 0);
3280 * vfs_page_set_valid:
3282 * Set the valid bits in a page based on the supplied offset. The
3283 * range is restricted to the buffer's size.
3285 * This routine is typically called after a read completes.
3288 vfs_page_set_valid(struct buf
*bp
, vm_ooffset_t off
, int pageno
, vm_page_t m
)
3290 vm_ooffset_t soff
, eoff
;
3293 * Start and end offsets in buffer. eoff - soff may not cross a
3294 * page boundry or cross the end of the buffer. The end of the
3295 * buffer, in this case, is our file EOF, not the allocation size
3299 eoff
= (off
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
;
3300 if (eoff
> bp
->b_loffset
+ bp
->b_bcount
)
3301 eoff
= bp
->b_loffset
+ bp
->b_bcount
;
3304 * Set valid range. This is typically the entire buffer and thus the
3308 vm_page_set_validclean(
3310 (vm_offset_t
) (soff
& PAGE_MASK
),
3311 (vm_offset_t
) (eoff
- soff
)
3319 * This routine is called before a device strategy routine.
3320 * It is used to tell the VM system that paging I/O is in
3321 * progress, and treat the pages associated with the buffer
3322 * almost as being PG_BUSY. Also the object 'paging_in_progress'
3323 * flag is handled to make sure that the object doesn't become
3326 * Since I/O has not been initiated yet, certain buffer flags
3327 * such as B_ERROR or B_INVAL may be in an inconsistant state
3328 * and should be ignored.
3331 vfs_busy_pages(struct vnode
*vp
, struct buf
*bp
)
3334 struct lwp
*lp
= curthread
->td_lwp
;
3337 * The buffer's I/O command must already be set. If reading,
3338 * B_CACHE must be 0 (double check against callers only doing
3339 * I/O when B_CACHE is 0).
3341 KKASSERT(bp
->b_cmd
!= BUF_CMD_DONE
);
3342 KKASSERT(bp
->b_cmd
== BUF_CMD_WRITE
|| (bp
->b_flags
& B_CACHE
) == 0);
3344 if (bp
->b_flags
& B_VMIO
) {
3349 foff
= bp
->b_loffset
;
3350 KASSERT(bp
->b_loffset
!= NOOFFSET
,
3351 ("vfs_busy_pages: no buffer offset"));
3355 * Loop until none of the pages are busy.
3358 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3359 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
3361 if (vm_page_sleep_busy(m
, FALSE
, "vbpage"))
3366 * Setup for I/O, soft-busy the page right now because
3367 * the next loop may block.
3369 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3370 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
3372 vm_page_flag_clear(m
, PG_ZERO
);
3373 if ((bp
->b_flags
& B_CLUSTER
) == 0) {
3374 vm_object_pip_add(obj
, 1);
3375 vm_page_io_start(m
);
3380 * Adjust protections for I/O and do bogus-page mapping.
3381 * Assume that vm_page_protect() can block (it can block
3382 * if VM_PROT_NONE, don't take any chances regardless).
3385 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3386 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
3389 * When readying a vnode-backed buffer for a write
3390 * we must zero-fill any invalid portions of the
3393 * When readying a vnode-backed buffer for a read
3394 * we must replace any dirty pages with a bogus
3395 * page so we do not destroy dirty data when
3396 * filling in gaps. Dirty pages might not
3397 * necessarily be marked dirty yet, so use m->valid
3398 * as a reasonable test.
3400 * Bogus page replacement is, uh, bogus. We need
3401 * to find a better way.
3403 if (bp
->b_cmd
== BUF_CMD_WRITE
) {
3404 vm_page_protect(m
, VM_PROT_READ
);
3405 vfs_page_set_valid(bp
, foff
, i
, m
);
3406 } else if (m
->valid
== VM_PAGE_BITS_ALL
) {
3407 bp
->b_xio
.xio_pages
[i
] = bogus_page
;
3410 vm_page_protect(m
, VM_PROT_NONE
);
3412 foff
= (foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
;
3415 pmap_qenter(trunc_page((vm_offset_t
)bp
->b_data
),
3416 bp
->b_xio
.xio_pages
, bp
->b_xio
.xio_npages
);
3420 * This is the easiest place to put the process accounting for the I/O
3424 if (bp
->b_cmd
== BUF_CMD_READ
)
3425 lp
->lwp_ru
.ru_inblock
++;
3427 lp
->lwp_ru
.ru_oublock
++;
3434 * Tell the VM system that the pages associated with this buffer
3435 * are clean. This is used for delayed writes where the data is
3436 * going to go to disk eventually without additional VM intevention.
3438 * Note that while we only really need to clean through to b_bcount, we
3439 * just go ahead and clean through to b_bufsize.
3442 vfs_clean_pages(struct buf
*bp
)
3446 if (bp
->b_flags
& B_VMIO
) {
3449 foff
= bp
->b_loffset
;
3450 KASSERT(foff
!= NOOFFSET
, ("vfs_clean_pages: no buffer offset"));
3451 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3452 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
3453 vm_ooffset_t noff
= (foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
;
3454 vm_ooffset_t eoff
= noff
;
3456 if (eoff
> bp
->b_loffset
+ bp
->b_bufsize
)
3457 eoff
= bp
->b_loffset
+ bp
->b_bufsize
;
3458 vfs_page_set_valid(bp
, foff
, i
, m
);
3459 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3466 * vfs_bio_set_validclean:
3468 * Set the range within the buffer to valid and clean. The range is
3469 * relative to the beginning of the buffer, b_loffset. Note that
3470 * b_loffset itself may be offset from the beginning of the first page.
3474 vfs_bio_set_validclean(struct buf
*bp
, int base
, int size
)
3476 if (bp
->b_flags
& B_VMIO
) {
3481 * Fixup base to be relative to beginning of first page.
3482 * Set initial n to be the maximum number of bytes in the
3483 * first page that can be validated.
3486 base
+= (bp
->b_loffset
& PAGE_MASK
);
3487 n
= PAGE_SIZE
- (base
& PAGE_MASK
);
3489 for (i
= base
/ PAGE_SIZE
; size
> 0 && i
< bp
->b_xio
.xio_npages
; ++i
) {
3490 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
3495 vm_page_set_validclean(m
, base
& PAGE_MASK
, n
);
3506 * Clear a buffer. This routine essentially fakes an I/O, so we need
3507 * to clear B_ERROR and B_INVAL.
3509 * Note that while we only theoretically need to clear through b_bcount,
3510 * we go ahead and clear through b_bufsize.
3514 vfs_bio_clrbuf(struct buf
*bp
)
3518 if ((bp
->b_flags
& (B_VMIO
| B_MALLOC
)) == B_VMIO
) {
3519 bp
->b_flags
&= ~(B_INVAL
|B_ERROR
);
3520 if ((bp
->b_xio
.xio_npages
== 1) && (bp
->b_bufsize
< PAGE_SIZE
) &&
3521 (bp
->b_loffset
& PAGE_MASK
) == 0) {
3522 mask
= (1 << (bp
->b_bufsize
/ DEV_BSIZE
)) - 1;
3523 if ((bp
->b_xio
.xio_pages
[0]->valid
& mask
) == mask
) {
3527 if (((bp
->b_xio
.xio_pages
[0]->flags
& PG_ZERO
) == 0) &&
3528 ((bp
->b_xio
.xio_pages
[0]->valid
& mask
) == 0)) {
3529 bzero(bp
->b_data
, bp
->b_bufsize
);
3530 bp
->b_xio
.xio_pages
[0]->valid
|= mask
;
3535 ea
= sa
= bp
->b_data
;
3536 for(i
=0;i
<bp
->b_xio
.xio_npages
;i
++,sa
=ea
) {
3537 int j
= ((vm_offset_t
)sa
& PAGE_MASK
) / DEV_BSIZE
;
3538 ea
= (caddr_t
)trunc_page((vm_offset_t
)sa
+ PAGE_SIZE
);
3539 ea
= (caddr_t
)(vm_offset_t
)ulmin(
3540 (u_long
)(vm_offset_t
)ea
,
3541 (u_long
)(vm_offset_t
)bp
->b_data
+ bp
->b_bufsize
);
3542 mask
= ((1 << ((ea
- sa
) / DEV_BSIZE
)) - 1) << j
;
3543 if ((bp
->b_xio
.xio_pages
[i
]->valid
& mask
) == mask
)
3545 if ((bp
->b_xio
.xio_pages
[i
]->valid
& mask
) == 0) {
3546 if ((bp
->b_xio
.xio_pages
[i
]->flags
& PG_ZERO
) == 0) {
3550 for (; sa
< ea
; sa
+= DEV_BSIZE
, j
++) {
3551 if (((bp
->b_xio
.xio_pages
[i
]->flags
& PG_ZERO
) == 0) &&
3552 (bp
->b_xio
.xio_pages
[i
]->valid
& (1<<j
)) == 0)
3553 bzero(sa
, DEV_BSIZE
);
3556 bp
->b_xio
.xio_pages
[i
]->valid
|= mask
;
3557 vm_page_flag_clear(bp
->b_xio
.xio_pages
[i
], PG_ZERO
);
3566 * vm_hold_load_pages:
3568 * Load pages into the buffer's address space. The pages are
3569 * allocated from the kernel object in order to reduce interference
3570 * with the any VM paging I/O activity. The range of loaded
3571 * pages will be wired.
3573 * If a page cannot be allocated, the 'pagedaemon' is woken up to
3574 * retrieve the full range (to - from) of pages.
3578 vm_hold_load_pages(struct buf
*bp
, vm_offset_t from
, vm_offset_t to
)
3584 to
= round_page(to
);
3585 from
= round_page(from
);
3586 index
= (from
- trunc_page((vm_offset_t
)bp
->b_data
)) >> PAGE_SHIFT
;
3588 for (pg
= from
; pg
< to
; pg
+= PAGE_SIZE
, index
++) {
3593 * Note: must allocate system pages since blocking here
3594 * could intefere with paging I/O, no matter which
3597 p
= vm_page_alloc(&kernel_object
,
3599 VM_ALLOC_NORMAL
| VM_ALLOC_SYSTEM
);
3601 vm_pageout_deficit
+= (to
- from
) >> PAGE_SHIFT
;
3606 p
->valid
= VM_PAGE_BITS_ALL
;
3607 vm_page_flag_clear(p
, PG_ZERO
);
3608 pmap_kenter(pg
, VM_PAGE_TO_PHYS(p
));
3609 bp
->b_xio
.xio_pages
[index
] = p
;
3612 bp
->b_xio
.xio_npages
= index
;
3616 * vm_hold_free_pages:
3618 * Return pages associated with the buffer back to the VM system.
3620 * The range of pages underlying the buffer's address space will
3621 * be unmapped and un-wired.
3624 vm_hold_free_pages(struct buf
*bp
, vm_offset_t from
, vm_offset_t to
)
3628 int index
, newnpages
;
3630 from
= round_page(from
);
3631 to
= round_page(to
);
3632 newnpages
= index
= (from
- trunc_page((vm_offset_t
)bp
->b_data
)) >> PAGE_SHIFT
;
3634 for (pg
= from
; pg
< to
; pg
+= PAGE_SIZE
, index
++) {
3635 p
= bp
->b_xio
.xio_pages
[index
];
3636 if (p
&& (index
< bp
->b_xio
.xio_npages
)) {
3638 kprintf("vm_hold_free_pages: doffset: %lld, loffset: %lld\n",
3639 bp
->b_bio2
.bio_offset
, bp
->b_loffset
);
3641 bp
->b_xio
.xio_pages
[index
] = NULL
;
3644 vm_page_unwire(p
, 0);
3648 bp
->b_xio
.xio_npages
= newnpages
;
3654 * Map a user buffer into KVM via a pbuf. On return the buffer's
3655 * b_data, b_bufsize, and b_bcount will be set, and its XIO page array
3659 vmapbuf(struct buf
*bp
, caddr_t udata
, int bytes
)
3670 * bp had better have a command and it better be a pbuf.
3672 KKASSERT(bp
->b_cmd
!= BUF_CMD_DONE
);
3673 KKASSERT(bp
->b_flags
& B_PAGING
);
3679 * Map the user data into KVM. Mappings have to be page-aligned.
3681 addr
= (caddr_t
)trunc_page((vm_offset_t
)udata
);
3684 vmprot
= VM_PROT_READ
;
3685 if (bp
->b_cmd
== BUF_CMD_READ
)
3686 vmprot
|= VM_PROT_WRITE
;
3688 while (addr
< udata
+ bytes
) {
3690 * Do the vm_fault if needed; do the copy-on-write thing
3691 * when reading stuff off device into memory.
3693 * vm_fault_page*() returns a held VM page.
3695 va
= (addr
>= udata
) ? (vm_offset_t
)addr
: (vm_offset_t
)udata
;
3696 va
= trunc_page(va
);
3698 m
= vm_fault_page_quick(va
, vmprot
, &error
);
3700 for (i
= 0; i
< pidx
; ++i
) {
3701 vm_page_unhold(bp
->b_xio
.xio_pages
[i
]);
3702 bp
->b_xio
.xio_pages
[i
] = NULL
;
3706 bp
->b_xio
.xio_pages
[pidx
] = m
;
3712 * Map the page array and set the buffer fields to point to
3713 * the mapped data buffer.
3715 if (pidx
> btoc(MAXPHYS
))
3716 panic("vmapbuf: mapped more than MAXPHYS");
3717 pmap_qenter((vm_offset_t
)bp
->b_kvabase
, bp
->b_xio
.xio_pages
, pidx
);
3719 bp
->b_xio
.xio_npages
= pidx
;
3720 bp
->b_data
= bp
->b_kvabase
+ ((int)(intptr_t)udata
& PAGE_MASK
);
3721 bp
->b_bcount
= bytes
;
3722 bp
->b_bufsize
= bytes
;
3729 * Free the io map PTEs associated with this IO operation.
3730 * We also invalidate the TLB entries and restore the original b_addr.
3733 vunmapbuf(struct buf
*bp
)
3738 KKASSERT(bp
->b_flags
& B_PAGING
);
3740 npages
= bp
->b_xio
.xio_npages
;
3741 pmap_qremove(trunc_page((vm_offset_t
)bp
->b_data
), npages
);
3742 for (pidx
= 0; pidx
< npages
; ++pidx
) {
3743 vm_page_unhold(bp
->b_xio
.xio_pages
[pidx
]);
3744 bp
->b_xio
.xio_pages
[pidx
] = NULL
;
3746 bp
->b_xio
.xio_npages
= 0;
3747 bp
->b_data
= bp
->b_kvabase
;
3751 * Scan all buffers in the system and issue the callback.
3754 scan_all_buffers(int (*callback
)(struct buf
*, void *), void *info
)
3760 for (n
= 0; n
< nbuf
; ++n
) {
3761 if ((error
= callback(&buf
[n
], info
)) < 0) {
3771 * print out statistics from the current status of the buffer pool
3772 * this can be toggeled by the system control option debug.syncprt
3781 int counts
[(MAXBSIZE
/ PAGE_SIZE
) + 1];
3782 static char *bname
[3] = { "LOCKED", "LRU", "AGE" };
3784 for (dp
= bufqueues
, i
= 0; dp
< &bufqueues
[3]; dp
++, i
++) {
3786 for (j
= 0; j
<= MAXBSIZE
/PAGE_SIZE
; j
++)
3789 TAILQ_FOREACH(bp
, dp
, b_freelist
) {
3790 counts
[bp
->b_bufsize
/PAGE_SIZE
]++;
3794 kprintf("%s: total-%d", bname
[i
], count
);
3795 for (j
= 0; j
<= MAXBSIZE
/PAGE_SIZE
; j
++)
3797 kprintf(", %d-%d", j
* PAGE_SIZE
, counts
[j
]);
3805 DB_SHOW_COMMAND(buffer
, db_show_buffer
)
3808 struct buf
*bp
= (struct buf
*)addr
;
3811 db_printf("usage: show buffer <addr>\n");
3815 db_printf("b_flags = 0x%b\n", (u_int
)bp
->b_flags
, PRINT_BUF_FLAGS
);
3816 db_printf("b_cmd = %d\n", bp
->b_cmd
);
3817 db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
3818 "b_resid = %d\n, b_data = %p, "
3819 "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
3820 bp
->b_error
, bp
->b_bufsize
, bp
->b_bcount
, bp
->b_resid
,
3821 bp
->b_data
, bp
->b_bio2
.bio_offset
, (bp
->b_bio2
.bio_next
? bp
->b_bio2
.bio_next
->bio_offset
: (off_t
)-1));
3822 if (bp
->b_xio
.xio_npages
) {
3824 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
3825 bp
->b_xio
.xio_npages
);
3826 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3828 m
= bp
->b_xio
.xio_pages
[i
];
3829 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m
->object
,
3830 (u_long
)m
->pindex
, (u_long
)VM_PAGE_TO_PHYS(m
));
3831 if ((i
+ 1) < bp
->b_xio
.xio_npages
)