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.91 2007/05/13 18:33:58 swildner 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>
70 #define BUFFER_QUEUES 6
72 BQUEUE_NONE
, /* not on any queue */
73 BQUEUE_LOCKED
, /* locked buffers */
74 BQUEUE_CLEAN
, /* non-B_DELWRI buffers */
75 BQUEUE_DIRTY
, /* B_DELWRI buffers */
76 BQUEUE_EMPTYKVA
, /* empty buffer headers with KVA assignment */
77 BQUEUE_EMPTY
/* empty buffer headers */
79 TAILQ_HEAD(bqueues
, buf
) bufqueues
[BUFFER_QUEUES
];
81 static MALLOC_DEFINE(M_BIOBUF
, "BIO buffer", "BIO buffer");
83 struct bio_ops bioops
; /* I/O operation notification */
85 struct buf
*buf
; /* buffer header pool */
87 static void vm_hold_free_pages(struct buf
*bp
, vm_offset_t from
,
89 static void vm_hold_load_pages(struct buf
*bp
, vm_offset_t from
,
91 static void vfs_page_set_valid(struct buf
*bp
, vm_ooffset_t off
,
92 int pageno
, vm_page_t m
);
93 static void vfs_clean_pages(struct buf
*bp
);
94 static void vfs_setdirty(struct buf
*bp
);
95 static void vfs_vmio_release(struct buf
*bp
);
96 static int flushbufqueues(void);
98 static void buf_daemon (void);
100 * bogus page -- for I/O to/from partially complete buffers
101 * this is a temporary solution to the problem, but it is not
102 * really that bad. it would be better to split the buffer
103 * for input in the case of buffers partially already in memory,
104 * but the code is intricate enough already.
106 vm_page_t bogus_page
;
110 * These are all static, but make the ones we export globals so we do
111 * not need to use compiler magic.
113 int bufspace
, maxbufspace
,
114 bufmallocspace
, maxbufmallocspace
, lobufspace
, hibufspace
;
115 static int bufreusecnt
, bufdefragcnt
, buffreekvacnt
;
116 static int lorunningspace
, hirunningspace
, runningbufreq
;
117 int numdirtybuffers
, lodirtybuffers
, hidirtybuffers
;
118 static int numfreebuffers
, lofreebuffers
, hifreebuffers
;
119 static int getnewbufcalls
;
120 static int getnewbufrestarts
;
122 static int needsbuffer
; /* locked by needsbuffer_spin */
123 static int bd_request
; /* locked by needsbuffer_spin */
124 static struct spinlock needsbuffer_spin
;
127 * Sysctls for operational control of the buffer cache.
129 SYSCTL_INT(_vfs
, OID_AUTO
, lodirtybuffers
, CTLFLAG_RW
, &lodirtybuffers
, 0,
130 "Number of dirty buffers to flush before bufdaemon becomes inactive");
131 SYSCTL_INT(_vfs
, OID_AUTO
, hidirtybuffers
, CTLFLAG_RW
, &hidirtybuffers
, 0,
132 "High watermark used to trigger explicit flushing of dirty buffers");
133 SYSCTL_INT(_vfs
, OID_AUTO
, lofreebuffers
, CTLFLAG_RW
, &lofreebuffers
, 0,
134 "Low watermark for special reserve in low-memory situations");
135 SYSCTL_INT(_vfs
, OID_AUTO
, hifreebuffers
, CTLFLAG_RW
, &hifreebuffers
, 0,
136 "High watermark for special reserve in low-memory situations");
137 SYSCTL_INT(_vfs
, OID_AUTO
, lorunningspace
, CTLFLAG_RW
, &lorunningspace
, 0,
138 "Minimum amount of buffer space required for active I/O");
139 SYSCTL_INT(_vfs
, OID_AUTO
, hirunningspace
, CTLFLAG_RW
, &hirunningspace
, 0,
140 "Maximum amount of buffer space to usable for active I/O");
142 * Sysctls determining current state of the buffer cache.
144 SYSCTL_INT(_vfs
, OID_AUTO
, numdirtybuffers
, CTLFLAG_RD
, &numdirtybuffers
, 0,
145 "Pending number of dirty buffers");
146 SYSCTL_INT(_vfs
, OID_AUTO
, numfreebuffers
, CTLFLAG_RD
, &numfreebuffers
, 0,
147 "Number of free buffers on the buffer cache free list");
148 SYSCTL_INT(_vfs
, OID_AUTO
, runningbufspace
, CTLFLAG_RD
, &runningbufspace
, 0,
149 "I/O bytes currently in progress due to asynchronous writes");
150 SYSCTL_INT(_vfs
, OID_AUTO
, maxbufspace
, CTLFLAG_RD
, &maxbufspace
, 0,
151 "Hard limit on maximum amount of memory usable for buffer space");
152 SYSCTL_INT(_vfs
, OID_AUTO
, hibufspace
, CTLFLAG_RD
, &hibufspace
, 0,
153 "Soft limit on maximum amount of memory usable for buffer space");
154 SYSCTL_INT(_vfs
, OID_AUTO
, lobufspace
, CTLFLAG_RD
, &lobufspace
, 0,
155 "Minimum amount of memory to reserve for system buffer space");
156 SYSCTL_INT(_vfs
, OID_AUTO
, bufspace
, CTLFLAG_RD
, &bufspace
, 0,
157 "Amount of memory available for buffers");
158 SYSCTL_INT(_vfs
, OID_AUTO
, maxmallocbufspace
, CTLFLAG_RD
, &maxbufmallocspace
,
159 0, "Maximum amount of memory reserved for buffers using malloc");
160 SYSCTL_INT(_vfs
, OID_AUTO
, bufmallocspace
, CTLFLAG_RD
, &bufmallocspace
, 0,
161 "Amount of memory left for buffers using malloc-scheme");
162 SYSCTL_INT(_vfs
, OID_AUTO
, getnewbufcalls
, CTLFLAG_RD
, &getnewbufcalls
, 0,
163 "New buffer header acquisition requests");
164 SYSCTL_INT(_vfs
, OID_AUTO
, getnewbufrestarts
, CTLFLAG_RD
, &getnewbufrestarts
,
165 0, "New buffer header acquisition restarts");
166 SYSCTL_INT(_vfs
, OID_AUTO
, bufdefragcnt
, CTLFLAG_RD
, &bufdefragcnt
, 0,
167 "Buffer acquisition restarts due to fragmented buffer map");
168 SYSCTL_INT(_vfs
, OID_AUTO
, buffreekvacnt
, CTLFLAG_RD
, &buffreekvacnt
, 0,
169 "Amount of time KVA space was deallocated in an arbitrary buffer");
170 SYSCTL_INT(_vfs
, OID_AUTO
, bufreusecnt
, CTLFLAG_RD
, &bufreusecnt
, 0,
171 "Amount of time buffer re-use operations were successful");
172 SYSCTL_INT(_debug_sizeof
, OID_AUTO
, buf
, CTLFLAG_RD
, 0, sizeof(struct buf
),
173 "sizeof(struct buf)");
175 char *buf_wmesg
= BUF_WMESG
;
177 extern int vm_swap_size
;
179 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
180 #define VFS_BIO_NEED_DIRTYFLUSH 0x02 /* waiting for dirty buffer flush */
181 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
182 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
187 * If someone is blocked due to there being too many dirty buffers,
188 * and numdirtybuffers is now reasonable, wake them up.
192 numdirtywakeup(int level
)
194 if (numdirtybuffers
<= level
) {
195 if (needsbuffer
& VFS_BIO_NEED_DIRTYFLUSH
) {
196 spin_lock_wr(&needsbuffer_spin
);
197 needsbuffer
&= ~VFS_BIO_NEED_DIRTYFLUSH
;
198 spin_unlock_wr(&needsbuffer_spin
);
199 wakeup(&needsbuffer
);
207 * Called when buffer space is potentially available for recovery.
208 * getnewbuf() will block on this flag when it is unable to free
209 * sufficient buffer space. Buffer space becomes recoverable when
210 * bp's get placed back in the queues.
217 * If someone is waiting for BUF space, wake them up. Even
218 * though we haven't freed the kva space yet, the waiting
219 * process will be able to now.
221 if (needsbuffer
& VFS_BIO_NEED_BUFSPACE
) {
222 spin_lock_wr(&needsbuffer_spin
);
223 needsbuffer
&= ~VFS_BIO_NEED_BUFSPACE
;
224 spin_unlock_wr(&needsbuffer_spin
);
225 wakeup(&needsbuffer
);
232 * Accounting for I/O in progress.
236 runningbufwakeup(struct buf
*bp
)
238 if (bp
->b_runningbufspace
) {
239 runningbufspace
-= bp
->b_runningbufspace
;
240 bp
->b_runningbufspace
= 0;
241 if (runningbufreq
&& runningbufspace
<= lorunningspace
) {
243 wakeup(&runningbufreq
);
251 * Called when a buffer has been added to one of the free queues to
252 * account for the buffer and to wakeup anyone waiting for free buffers.
253 * This typically occurs when large amounts of metadata are being handled
254 * by the buffer cache ( else buffer space runs out first, usually ).
262 spin_lock_wr(&needsbuffer_spin
);
263 needsbuffer
&= ~VFS_BIO_NEED_ANY
;
264 if (numfreebuffers
>= hifreebuffers
)
265 needsbuffer
&= ~VFS_BIO_NEED_FREE
;
266 spin_unlock_wr(&needsbuffer_spin
);
267 wakeup(&needsbuffer
);
272 * waitrunningbufspace()
274 * runningbufspace is a measure of the amount of I/O currently
275 * running. This routine is used in async-write situations to
276 * prevent creating huge backups of pending writes to a device.
277 * Only asynchronous writes are governed by this function.
279 * Reads will adjust runningbufspace, but will not block based on it.
280 * The read load has a side effect of reducing the allowed write load.
282 * This does NOT turn an async write into a sync write. It waits
283 * for earlier writes to complete and generally returns before the
284 * caller's write has reached the device.
287 waitrunningbufspace(void)
289 if (runningbufspace
> hirunningspace
) {
291 while (runningbufspace
> hirunningspace
) {
293 tsleep(&runningbufreq
, 0, "wdrain", 0);
300 * vfs_buf_test_cache:
302 * Called when a buffer is extended. This function clears the B_CACHE
303 * bit if the newly extended portion of the buffer does not contain
308 vfs_buf_test_cache(struct buf
*bp
,
309 vm_ooffset_t foff
, vm_offset_t off
, vm_offset_t size
,
312 if (bp
->b_flags
& B_CACHE
) {
313 int base
= (foff
+ off
) & PAGE_MASK
;
314 if (vm_page_is_valid(m
, base
, size
) == 0)
315 bp
->b_flags
&= ~B_CACHE
;
322 * Wake up the buffer daemon if the number of outstanding dirty buffers
323 * is above specified threshold 'dirtybuflevel'.
325 * The buffer daemon is explicitly woken up when (a) the pending number
326 * of dirty buffers exceeds the recovery and stall mid-point value,
327 * (b) during bwillwrite() or (c) buf freelist was exhausted.
331 bd_wakeup(int dirtybuflevel
)
333 if (bd_request
== 0 && numdirtybuffers
>= dirtybuflevel
) {
334 spin_lock_wr(&needsbuffer_spin
);
336 spin_unlock_wr(&needsbuffer_spin
);
344 * Speed up the buffer cache flushing process.
357 * Load time initialisation of the buffer cache, called from machine
358 * dependant initialization code.
364 vm_offset_t bogus_offset
;
367 spin_init(&needsbuffer_spin
);
369 /* next, make a null set of free lists */
370 for (i
= 0; i
< BUFFER_QUEUES
; i
++)
371 TAILQ_INIT(&bufqueues
[i
]);
373 /* finally, initialize each buffer header and stick on empty q */
374 for (i
= 0; i
< nbuf
; i
++) {
376 bzero(bp
, sizeof *bp
);
377 bp
->b_flags
= B_INVAL
; /* we're just an empty header */
378 bp
->b_cmd
= BUF_CMD_DONE
;
379 bp
->b_qindex
= BQUEUE_EMPTY
;
381 xio_init(&bp
->b_xio
);
382 LIST_INIT(&bp
->b_dep
);
384 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_EMPTY
], bp
, b_freelist
);
388 * maxbufspace is the absolute maximum amount of buffer space we are
389 * allowed to reserve in KVM and in real terms. The absolute maximum
390 * is nominally used by buf_daemon. hibufspace is the nominal maximum
391 * used by most other processes. The differential is required to
392 * ensure that buf_daemon is able to run when other processes might
393 * be blocked waiting for buffer space.
395 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
396 * this may result in KVM fragmentation which is not handled optimally
399 maxbufspace
= nbuf
* BKVASIZE
;
400 hibufspace
= imax(3 * maxbufspace
/ 4, maxbufspace
- MAXBSIZE
* 10);
401 lobufspace
= hibufspace
- MAXBSIZE
;
403 lorunningspace
= 512 * 1024;
404 hirunningspace
= 1024 * 1024;
407 * Limit the amount of malloc memory since it is wired permanently into
408 * the kernel space. Even though this is accounted for in the buffer
409 * allocation, we don't want the malloced region to grow uncontrolled.
410 * The malloc scheme improves memory utilization significantly on average
411 * (small) directories.
413 maxbufmallocspace
= hibufspace
/ 20;
416 * Reduce the chance of a deadlock occuring by limiting the number
417 * of delayed-write dirty buffers we allow to stack up.
419 hidirtybuffers
= nbuf
/ 4 + 20;
422 * To support extreme low-memory systems, make sure hidirtybuffers cannot
423 * eat up all available buffer space. This occurs when our minimum cannot
424 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
425 * BKVASIZE'd (8K) buffers.
427 while (hidirtybuffers
* BKVASIZE
> 3 * hibufspace
/ 4) {
428 hidirtybuffers
>>= 1;
430 lodirtybuffers
= hidirtybuffers
/ 2;
433 * Try to keep the number of free buffers in the specified range,
434 * and give special processes (e.g. like buf_daemon) access to an
437 lofreebuffers
= nbuf
/ 18 + 5;
438 hifreebuffers
= 2 * lofreebuffers
;
439 numfreebuffers
= nbuf
;
442 * Maximum number of async ops initiated per buf_daemon loop. This is
443 * somewhat of a hack at the moment, we really need to limit ourselves
444 * based on the number of bytes of I/O in-transit that were initiated
448 bogus_offset
= kmem_alloc_pageable(&kernel_map
, PAGE_SIZE
);
449 bogus_page
= vm_page_alloc(&kernel_object
,
450 (bogus_offset
>> PAGE_SHIFT
),
452 vmstats
.v_wire_count
++;
457 * Initialize the embedded bio structures
460 initbufbio(struct buf
*bp
)
462 bp
->b_bio1
.bio_buf
= bp
;
463 bp
->b_bio1
.bio_prev
= NULL
;
464 bp
->b_bio1
.bio_offset
= NOOFFSET
;
465 bp
->b_bio1
.bio_next
= &bp
->b_bio2
;
466 bp
->b_bio1
.bio_done
= NULL
;
468 bp
->b_bio2
.bio_buf
= bp
;
469 bp
->b_bio2
.bio_prev
= &bp
->b_bio1
;
470 bp
->b_bio2
.bio_offset
= NOOFFSET
;
471 bp
->b_bio2
.bio_next
= NULL
;
472 bp
->b_bio2
.bio_done
= NULL
;
476 * Reinitialize the embedded bio structures as well as any additional
477 * translation cache layers.
480 reinitbufbio(struct buf
*bp
)
484 for (bio
= &bp
->b_bio1
; bio
; bio
= bio
->bio_next
) {
485 bio
->bio_done
= NULL
;
486 bio
->bio_offset
= NOOFFSET
;
491 * Push another BIO layer onto an existing BIO and return it. The new
492 * BIO layer may already exist, holding cached translation data.
495 push_bio(struct bio
*bio
)
499 if ((nbio
= bio
->bio_next
) == NULL
) {
500 int index
= bio
- &bio
->bio_buf
->b_bio_array
[0];
501 if (index
>= NBUF_BIO
- 1) {
502 panic("push_bio: too many layers bp %p\n",
505 nbio
= &bio
->bio_buf
->b_bio_array
[index
+ 1];
506 bio
->bio_next
= nbio
;
507 nbio
->bio_prev
= bio
;
508 nbio
->bio_buf
= bio
->bio_buf
;
509 nbio
->bio_offset
= NOOFFSET
;
510 nbio
->bio_done
= NULL
;
511 nbio
->bio_next
= NULL
;
513 KKASSERT(nbio
->bio_done
== NULL
);
518 pop_bio(struct bio
*bio
)
524 clearbiocache(struct bio
*bio
)
527 bio
->bio_offset
= NOOFFSET
;
535 * Free the KVA allocation for buffer 'bp'.
537 * Must be called from a critical section as this is the only locking for
540 * Since this call frees up buffer space, we call bufspacewakeup().
543 bfreekva(struct buf
*bp
)
549 count
= vm_map_entry_reserve(MAP_RESERVE_COUNT
);
550 vm_map_lock(&buffer_map
);
551 bufspace
-= bp
->b_kvasize
;
552 vm_map_delete(&buffer_map
,
553 (vm_offset_t
) bp
->b_kvabase
,
554 (vm_offset_t
) bp
->b_kvabase
+ bp
->b_kvasize
,
557 vm_map_unlock(&buffer_map
);
558 vm_map_entry_release(count
);
567 * Remove the buffer from the appropriate free list.
570 bremfree(struct buf
*bp
)
575 old_qindex
= bp
->b_qindex
;
577 if (bp
->b_qindex
!= BQUEUE_NONE
) {
578 KASSERT(BUF_REFCNTNB(bp
) == 1,
579 ("bremfree: bp %p not locked",bp
));
580 TAILQ_REMOVE(&bufqueues
[bp
->b_qindex
], bp
, b_freelist
);
581 bp
->b_qindex
= BQUEUE_NONE
;
583 if (BUF_REFCNTNB(bp
) <= 1)
584 panic("bremfree: removing a buffer not on a queue");
588 * Fixup numfreebuffers count. If the buffer is invalid or not
589 * delayed-write, and it was on the EMPTY, LRU, or AGE queues,
590 * the buffer was free and we must decrement numfreebuffers.
592 if ((bp
->b_flags
& B_INVAL
) || (bp
->b_flags
& B_DELWRI
) == 0) {
597 case BQUEUE_EMPTYKVA
:
611 * Get a buffer with the specified data. Look in the cache first. We
612 * must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
613 * is set, the buffer is valid and we do not have to do anything ( see
617 bread(struct vnode
*vp
, off_t loffset
, int size
, struct buf
**bpp
)
621 bp
= getblk(vp
, loffset
, size
, 0, 0);
624 /* if not found in cache, do some I/O */
625 if ((bp
->b_flags
& B_CACHE
) == 0) {
626 KASSERT(!(bp
->b_flags
& B_ASYNC
), ("bread: illegal async bp %p", bp
));
627 bp
->b_flags
&= ~(B_ERROR
| B_INVAL
);
628 bp
->b_cmd
= BUF_CMD_READ
;
629 vfs_busy_pages(vp
, bp
);
630 vn_strategy(vp
, &bp
->b_bio1
);
631 return (biowait(bp
));
639 * Operates like bread, but also starts asynchronous I/O on
640 * read-ahead blocks. We must clear B_ERROR and B_INVAL prior
641 * to initiating I/O . If B_CACHE is set, the buffer is valid
642 * and we do not have to do anything.
645 breadn(struct vnode
*vp
, off_t loffset
, int size
, off_t
*raoffset
,
646 int *rabsize
, int cnt
, struct buf
**bpp
)
648 struct buf
*bp
, *rabp
;
650 int rv
= 0, readwait
= 0;
652 *bpp
= bp
= getblk(vp
, loffset
, size
, 0, 0);
654 /* if not found in cache, do some I/O */
655 if ((bp
->b_flags
& B_CACHE
) == 0) {
656 bp
->b_flags
&= ~(B_ERROR
| B_INVAL
);
657 bp
->b_cmd
= BUF_CMD_READ
;
658 vfs_busy_pages(vp
, bp
);
659 vn_strategy(vp
, &bp
->b_bio1
);
663 for (i
= 0; i
< cnt
; i
++, raoffset
++, rabsize
++) {
664 if (inmem(vp
, *raoffset
))
666 rabp
= getblk(vp
, *raoffset
, *rabsize
, 0, 0);
668 if ((rabp
->b_flags
& B_CACHE
) == 0) {
669 rabp
->b_flags
|= B_ASYNC
;
670 rabp
->b_flags
&= ~(B_ERROR
| B_INVAL
);
671 rabp
->b_cmd
= BUF_CMD_READ
;
672 vfs_busy_pages(vp
, rabp
);
674 vn_strategy(vp
, &rabp
->b_bio1
);
689 * Write, release buffer on completion. (Done by iodone
690 * if async). Do not bother writing anything if the buffer
693 * Note that we set B_CACHE here, indicating that buffer is
694 * fully valid and thus cacheable. This is true even of NFS
695 * now so we set it generally. This could be set either here
696 * or in biodone() since the I/O is synchronous. We put it
700 bwrite(struct buf
*bp
)
704 if (bp
->b_flags
& B_INVAL
) {
709 oldflags
= bp
->b_flags
;
711 if (BUF_REFCNTNB(bp
) == 0)
712 panic("bwrite: buffer is not busy???");
715 /* Mark the buffer clean */
718 bp
->b_flags
&= ~B_ERROR
;
719 bp
->b_flags
|= B_CACHE
;
720 bp
->b_cmd
= BUF_CMD_WRITE
;
721 vfs_busy_pages(bp
->b_vp
, bp
);
724 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
725 * valid for vnode-backed buffers.
727 bp
->b_runningbufspace
= bp
->b_bufsize
;
728 runningbufspace
+= bp
->b_runningbufspace
;
731 if (oldflags
& B_ASYNC
)
733 vn_strategy(bp
->b_vp
, &bp
->b_bio1
);
735 if ((oldflags
& B_ASYNC
) == 0) {
736 int rtval
= biowait(bp
);
739 } else if ((oldflags
& B_NOWDRAIN
) == 0) {
741 * don't allow the async write to saturate the I/O
742 * system. Deadlocks can occur only if a device strategy
743 * routine (like in VN) turns around and issues another
744 * high-level write, in which case B_NOWDRAIN is expected
745 * to be set. Otherwise we will not deadlock here because
746 * we are blocking waiting for I/O that is already in-progress
749 waitrunningbufspace();
758 * Delayed write. (Buffer is marked dirty). Do not bother writing
759 * anything if the buffer is marked invalid.
761 * Note that since the buffer must be completely valid, we can safely
762 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
763 * biodone() in order to prevent getblk from writing the buffer
767 bdwrite(struct buf
*bp
)
769 if (BUF_REFCNTNB(bp
) == 0)
770 panic("bdwrite: buffer is not busy");
772 if (bp
->b_flags
& B_INVAL
) {
779 * Set B_CACHE, indicating that the buffer is fully valid. This is
780 * true even of NFS now.
782 bp
->b_flags
|= B_CACHE
;
785 * This bmap keeps the system from needing to do the bmap later,
786 * perhaps when the system is attempting to do a sync. Since it
787 * is likely that the indirect block -- or whatever other datastructure
788 * that the filesystem needs is still in memory now, it is a good
789 * thing to do this. Note also, that if the pageout daemon is
790 * requesting a sync -- there might not be enough memory to do
791 * the bmap then... So, this is important to do.
793 if (bp
->b_bio2
.bio_offset
== NOOFFSET
) {
794 VOP_BMAP(bp
->b_vp
, bp
->b_loffset
, NULL
, &bp
->b_bio2
.bio_offset
,
799 * Set the *dirty* buffer range based upon the VM system dirty pages.
804 * We need to do this here to satisfy the vnode_pager and the
805 * pageout daemon, so that it thinks that the pages have been
806 * "cleaned". Note that since the pages are in a delayed write
807 * buffer -- the VFS layer "will" see that the pages get written
808 * out on the next sync, or perhaps the cluster will be completed.
814 * Wakeup the buffer flushing daemon if we have a lot of dirty
815 * buffers (midpoint between our recovery point and our stall
818 bd_wakeup((lodirtybuffers
+ hidirtybuffers
) / 2);
821 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
822 * due to the softdep code.
829 * Turn buffer into delayed write request by marking it B_DELWRI.
830 * B_RELBUF and B_NOCACHE must be cleared.
832 * We reassign the buffer to itself to properly update it in the
835 * Since the buffer is not on a queue, we do not update the
836 * numfreebuffers count.
838 * Must be called from a critical section.
839 * The buffer must be on BQUEUE_NONE.
842 bdirty(struct buf
*bp
)
844 KASSERT(bp
->b_qindex
== BQUEUE_NONE
, ("bdirty: buffer %p still on queue %d", bp
, bp
->b_qindex
));
845 if (bp
->b_flags
& B_NOCACHE
) {
846 kprintf("bdirty: clearing B_NOCACHE on buf %p\n", bp
);
847 bp
->b_flags
&= ~B_NOCACHE
;
849 if (bp
->b_flags
& B_INVAL
) {
850 kprintf("bdirty: warning, dirtying invalid buffer %p\n", bp
);
852 bp
->b_flags
&= ~B_RELBUF
;
854 if ((bp
->b_flags
& B_DELWRI
) == 0) {
855 bp
->b_flags
|= B_DELWRI
;
858 bd_wakeup((lodirtybuffers
+ hidirtybuffers
) / 2);
865 * Clear B_DELWRI for buffer.
867 * Since the buffer is not on a queue, we do not update the numfreebuffers
870 * Must be called from a critical section.
872 * The buffer is typically on BQUEUE_NONE but there is one case in
873 * brelse() that calls this function after placing the buffer on
878 bundirty(struct buf
*bp
)
880 if (bp
->b_flags
& B_DELWRI
) {
881 bp
->b_flags
&= ~B_DELWRI
;
884 numdirtywakeup(lodirtybuffers
);
887 * Since it is now being written, we can clear its deferred write flag.
889 bp
->b_flags
&= ~B_DEFERRED
;
895 * Asynchronous write. Start output on a buffer, but do not wait for
896 * it to complete. The buffer is released when the output completes.
898 * bwrite() ( or the VOP routine anyway ) is responsible for handling
899 * B_INVAL buffers. Not us.
902 bawrite(struct buf
*bp
)
904 bp
->b_flags
|= B_ASYNC
;
911 * Ordered write. Start output on a buffer, and flag it so that the
912 * device will write it in the order it was queued. The buffer is
913 * released when the output completes. bwrite() ( or the VOP routine
914 * anyway ) is responsible for handling B_INVAL buffers.
917 bowrite(struct buf
*bp
)
919 bp
->b_flags
|= B_ORDERED
| B_ASYNC
;
926 * Called prior to the locking of any vnodes when we are expecting to
927 * write. We do not want to starve the buffer cache with too many
928 * dirty buffers so we block here. By blocking prior to the locking
929 * of any vnodes we attempt to avoid the situation where a locked vnode
930 * prevents the various system daemons from flushing related buffers.
936 if (numdirtybuffers
>= hidirtybuffers
) {
937 while (numdirtybuffers
>= hidirtybuffers
) {
939 spin_lock_wr(&needsbuffer_spin
);
940 if (numdirtybuffers
>= hidirtybuffers
) {
941 needsbuffer
|= VFS_BIO_NEED_DIRTYFLUSH
;
942 msleep(&needsbuffer
, &needsbuffer_spin
, 0,
945 spin_unlock_wr(&needsbuffer_spin
);
951 * buf_dirty_count_severe:
953 * Return true if we have too many dirty buffers.
956 buf_dirty_count_severe(void)
958 return(numdirtybuffers
>= hidirtybuffers
);
964 * Release a busy buffer and, if requested, free its resources. The
965 * buffer will be stashed in the appropriate bufqueue[] allowing it
966 * to be accessed later as a cache entity or reused for other purposes.
969 brelse(struct buf
*bp
)
972 int saved_flags
= bp
->b_flags
;
975 KASSERT(!(bp
->b_flags
& (B_CLUSTER
|B_PAGING
)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp
));
980 * If B_NOCACHE is set we are being asked to destroy the buffer and
981 * its backing store. Clear B_DELWRI.
983 * B_NOCACHE is set in two cases: (1) when the caller really wants
984 * to destroy the buffer and backing store and (2) when the caller
985 * wants to destroy the buffer and backing store after a write
988 if ((bp
->b_flags
& (B_NOCACHE
|B_DELWRI
)) == (B_NOCACHE
|B_DELWRI
)) {
992 if (bp
->b_flags
& B_LOCKED
)
993 bp
->b_flags
&= ~B_ERROR
;
996 * If a write error occurs and the caller does not want to throw
997 * away the buffer, redirty the buffer. This will also clear
1000 if (bp
->b_cmd
== BUF_CMD_WRITE
&&
1001 (bp
->b_flags
& (B_ERROR
| B_INVAL
)) == B_ERROR
) {
1003 * Failed write, redirty. Must clear B_ERROR to prevent
1004 * pages from being scrapped. If B_INVAL is set then
1005 * this case is not run and the next case is run to
1006 * destroy the buffer. B_INVAL can occur if the buffer
1007 * is outside the range supported by the underlying device.
1009 bp
->b_flags
&= ~B_ERROR
;
1011 } else if ((bp
->b_flags
& (B_NOCACHE
| B_INVAL
| B_ERROR
)) ||
1012 (bp
->b_bufsize
<= 0) || bp
->b_cmd
== BUF_CMD_FREEBLKS
) {
1014 * Either a failed I/O or we were asked to free or not
1017 bp
->b_flags
|= B_INVAL
;
1018 if (LIST_FIRST(&bp
->b_dep
) != NULL
&& bioops
.io_deallocate
)
1019 (*bioops
.io_deallocate
)(bp
);
1020 if (bp
->b_flags
& B_DELWRI
) {
1022 numdirtywakeup(lodirtybuffers
);
1024 bp
->b_flags
&= ~(B_DELWRI
| B_CACHE
);
1028 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1029 * is called with B_DELWRI set, the underlying pages may wind up
1030 * getting freed causing a previous write (bdwrite()) to get 'lost'
1031 * because pages associated with a B_DELWRI bp are marked clean.
1033 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1034 * if B_DELWRI is set.
1036 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1037 * on pages to return pages to the VM page queues.
1039 if (bp
->b_flags
& B_DELWRI
)
1040 bp
->b_flags
&= ~B_RELBUF
;
1041 else if (vm_page_count_severe())
1042 bp
->b_flags
|= B_RELBUF
;
1045 * At this point destroying the buffer is governed by the B_INVAL
1046 * or B_RELBUF flags.
1048 bp
->b_cmd
= BUF_CMD_DONE
;
1051 * VMIO buffer rundown. Make sure the VM page array is restored
1052 * after an I/O may have replaces some of the pages with bogus pages
1053 * in order to not destroy dirty pages in a fill-in read.
1055 * Note that due to the code above, if a buffer is marked B_DELWRI
1056 * then the B_RELBUF and B_NOCACHE bits will always be clear.
1057 * B_INVAL may still be set, however.
1059 * For clean buffers, B_INVAL or B_RELBUF will destroy the buffer
1060 * but not the backing store. B_NOCACHE will destroy the backing
1063 * Note that dirty NFS buffers contain byte-granular write ranges
1064 * and should not be destroyed w/ B_INVAL even if the backing store
1067 if (bp
->b_flags
& B_VMIO
) {
1069 * Rundown for VMIO buffers which are not dirty NFS buffers.
1081 * Get the base offset and length of the buffer. Note that
1082 * in the VMIO case if the buffer block size is not
1083 * page-aligned then b_data pointer may not be page-aligned.
1084 * But our b_xio.xio_pages array *IS* page aligned.
1086 * block sizes less then DEV_BSIZE (usually 512) are not
1087 * supported due to the page granularity bits (m->valid,
1088 * m->dirty, etc...).
1090 * See man buf(9) for more information
1093 resid
= bp
->b_bufsize
;
1094 foff
= bp
->b_loffset
;
1096 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
1097 m
= bp
->b_xio
.xio_pages
[i
];
1098 vm_page_flag_clear(m
, PG_ZERO
);
1100 * If we hit a bogus page, fixup *all* of them
1101 * now. Note that we left these pages wired
1102 * when we removed them so they had better exist,
1103 * and they cannot be ripped out from under us so
1104 * no critical section protection is necessary.
1106 if (m
== bogus_page
) {
1108 poff
= OFF_TO_IDX(bp
->b_loffset
);
1110 for (j
= i
; j
< bp
->b_xio
.xio_npages
; j
++) {
1113 mtmp
= bp
->b_xio
.xio_pages
[j
];
1114 if (mtmp
== bogus_page
) {
1115 mtmp
= vm_page_lookup(obj
, poff
+ j
);
1117 panic("brelse: page missing");
1119 bp
->b_xio
.xio_pages
[j
] = mtmp
;
1123 if ((bp
->b_flags
& B_INVAL
) == 0) {
1124 pmap_qenter(trunc_page((vm_offset_t
)bp
->b_data
),
1125 bp
->b_xio
.xio_pages
, bp
->b_xio
.xio_npages
);
1127 m
= bp
->b_xio
.xio_pages
[i
];
1131 * Invalidate the backing store if B_NOCACHE is set
1132 * (e.g. used with vinvalbuf()). If this is NFS
1133 * we impose a requirement that the block size be
1134 * a multiple of PAGE_SIZE and create a temporary
1135 * hack to basically invalidate the whole page. The
1136 * problem is that NFS uses really odd buffer sizes
1137 * especially when tracking piecemeal writes and
1138 * it also vinvalbuf()'s a lot, which would result
1139 * in only partial page validation and invalidation
1140 * here. If the file page is mmap()'d, however,
1141 * all the valid bits get set so after we invalidate
1142 * here we would end up with weird m->valid values
1143 * like 0xfc. nfs_getpages() can't handle this so
1144 * we clear all the valid bits for the NFS case
1145 * instead of just some of them.
1147 * The real bug is the VM system having to set m->valid
1148 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1149 * itself is an artifact of the whole 512-byte
1150 * granular mess that exists to support odd block
1151 * sizes and UFS meta-data block sizes (e.g. 6144).
1152 * A complete rewrite is required.
1154 if (bp
->b_flags
& (B_NOCACHE
|B_ERROR
)) {
1155 int poffset
= foff
& PAGE_MASK
;
1158 presid
= PAGE_SIZE
- poffset
;
1159 if (bp
->b_vp
->v_tag
== VT_NFS
&&
1160 bp
->b_vp
->v_type
== VREG
) {
1162 } else if (presid
> resid
) {
1165 KASSERT(presid
>= 0, ("brelse: extra page"));
1166 vm_page_set_invalid(m
, poffset
, presid
);
1168 resid
-= PAGE_SIZE
- (foff
& PAGE_MASK
);
1169 foff
= (foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
;
1171 if (bp
->b_flags
& (B_INVAL
| B_RELBUF
))
1172 vfs_vmio_release(bp
);
1175 * Rundown for non-VMIO buffers.
1177 if (bp
->b_flags
& (B_INVAL
| B_RELBUF
)) {
1180 kprintf("brelse bp %p %08x/%08x: Warning, caught and fixed brelvp bug\n", bp
, saved_flags
, bp
->b_flags
);
1189 if (bp
->b_qindex
!= BQUEUE_NONE
)
1190 panic("brelse: free buffer onto another queue???");
1191 if (BUF_REFCNTNB(bp
) > 1) {
1192 /* Temporary panic to verify exclusive locking */
1193 /* This panic goes away when we allow shared refs */
1194 panic("brelse: multiple refs");
1195 /* do not release to free list */
1202 * Figure out the correct queue to place the cleaned up buffer on.
1203 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1204 * disassociated from their vnode.
1207 if (bp
->b_bufsize
== 0) {
1209 * Buffers with no memory. Due to conditionals near the top
1210 * of brelse() such buffers should probably already be
1211 * marked B_INVAL and disassociated from their vnode.
1213 bp
->b_flags
|= B_INVAL
;
1214 KASSERT(bp
->b_vp
== NULL
, ("bp1 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp
, saved_flags
, bp
->b_flags
, bp
->b_vp
));
1215 KKASSERT((bp
->b_flags
& B_HASHED
) == 0);
1216 if (bp
->b_kvasize
) {
1217 bp
->b_qindex
= BQUEUE_EMPTYKVA
;
1219 bp
->b_qindex
= BQUEUE_EMPTY
;
1221 TAILQ_INSERT_HEAD(&bufqueues
[bp
->b_qindex
], bp
, b_freelist
);
1222 } else if (bp
->b_flags
& (B_ERROR
| B_INVAL
| B_NOCACHE
| B_RELBUF
)) {
1224 * Buffers with junk contents. Again these buffers had better
1225 * already be disassociated from their vnode.
1227 KASSERT(bp
->b_vp
== NULL
, ("bp2 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp
, saved_flags
, bp
->b_flags
, bp
->b_vp
));
1228 KKASSERT((bp
->b_flags
& B_HASHED
) == 0);
1229 bp
->b_flags
|= B_INVAL
;
1230 bp
->b_qindex
= BQUEUE_CLEAN
;
1231 TAILQ_INSERT_HEAD(&bufqueues
[BQUEUE_CLEAN
], bp
, b_freelist
);
1232 } else if (bp
->b_flags
& B_LOCKED
) {
1234 * Buffers that are locked.
1236 bp
->b_qindex
= BQUEUE_LOCKED
;
1237 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_LOCKED
], bp
, b_freelist
);
1240 * Remaining buffers. These buffers are still associated with
1243 switch(bp
->b_flags
& (B_DELWRI
|B_AGE
)) {
1244 case B_DELWRI
| B_AGE
:
1245 bp
->b_qindex
= BQUEUE_DIRTY
;
1246 TAILQ_INSERT_HEAD(&bufqueues
[BQUEUE_DIRTY
], bp
, b_freelist
);
1249 bp
->b_qindex
= BQUEUE_DIRTY
;
1250 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_DIRTY
], bp
, b_freelist
);
1253 bp
->b_qindex
= BQUEUE_CLEAN
;
1254 TAILQ_INSERT_HEAD(&bufqueues
[BQUEUE_CLEAN
], bp
, b_freelist
);
1257 bp
->b_qindex
= BQUEUE_CLEAN
;
1258 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_CLEAN
], bp
, b_freelist
);
1264 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1265 * on the correct queue.
1267 if ((bp
->b_flags
& (B_INVAL
|B_DELWRI
)) == (B_INVAL
|B_DELWRI
))
1271 * Fixup numfreebuffers count. The bp is on an appropriate queue
1272 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1273 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1274 * if B_INVAL is set ).
1276 if ((bp
->b_flags
& B_LOCKED
) == 0 && !(bp
->b_flags
& B_DELWRI
))
1280 * Something we can maybe free or reuse
1282 if (bp
->b_bufsize
|| bp
->b_kvasize
)
1286 * Clean up temporary flags and unlock the buffer.
1288 bp
->b_flags
&= ~(B_ORDERED
| B_ASYNC
| B_NOCACHE
| B_AGE
| B_RELBUF
|
1289 B_DIRECT
| B_NOWDRAIN
);
1297 * Release a buffer back to the appropriate queue but do not try to free
1298 * it. The buffer is expected to be used again soon.
1300 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1301 * biodone() to requeue an async I/O on completion. It is also used when
1302 * known good buffers need to be requeued but we think we may need the data
1305 * XXX we should be able to leave the B_RELBUF hint set on completion.
1308 bqrelse(struct buf
*bp
)
1312 KASSERT(!(bp
->b_flags
& (B_CLUSTER
|B_PAGING
)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp
));
1314 if (bp
->b_qindex
!= BQUEUE_NONE
)
1315 panic("bqrelse: free buffer onto another queue???");
1316 if (BUF_REFCNTNB(bp
) > 1) {
1317 /* do not release to free list */
1318 panic("bqrelse: multiple refs");
1323 if (bp
->b_flags
& B_LOCKED
) {
1324 bp
->b_flags
&= ~B_ERROR
;
1325 bp
->b_qindex
= BQUEUE_LOCKED
;
1326 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_LOCKED
], bp
, b_freelist
);
1327 /* buffers with stale but valid contents */
1328 } else if (bp
->b_flags
& B_DELWRI
) {
1329 bp
->b_qindex
= BQUEUE_DIRTY
;
1330 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_DIRTY
], bp
, b_freelist
);
1331 } else if (vm_page_count_severe()) {
1333 * We are too low on memory, we have to try to free the
1334 * buffer (most importantly: the wired pages making up its
1335 * backing store) *now*.
1341 bp
->b_qindex
= BQUEUE_CLEAN
;
1342 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_CLEAN
], bp
, b_freelist
);
1345 if ((bp
->b_flags
& B_LOCKED
) == 0 &&
1346 ((bp
->b_flags
& B_INVAL
) || !(bp
->b_flags
& B_DELWRI
))) {
1351 * Something we can maybe free or reuse.
1353 if (bp
->b_bufsize
&& !(bp
->b_flags
& B_DELWRI
))
1357 * Final cleanup and unlock. Clear bits that are only used while a
1358 * buffer is actively locked.
1360 bp
->b_flags
&= ~(B_ORDERED
| B_ASYNC
| B_NOCACHE
| B_AGE
| B_RELBUF
);
1368 * Return backing pages held by the buffer 'bp' back to the VM system
1369 * if possible. The pages are freed if they are no longer valid or
1370 * attempt to free if it was used for direct I/O otherwise they are
1371 * sent to the page cache.
1373 * Pages that were marked busy are left alone and skipped.
1375 * The KVA mapping (b_data) for the underlying pages is removed by
1379 vfs_vmio_release(struct buf
*bp
)
1385 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
1386 m
= bp
->b_xio
.xio_pages
[i
];
1387 bp
->b_xio
.xio_pages
[i
] = NULL
;
1389 * In order to keep page LRU ordering consistent, put
1390 * everything on the inactive queue.
1392 vm_page_unwire(m
, 0);
1394 * We don't mess with busy pages, it is
1395 * the responsibility of the process that
1396 * busied the pages to deal with them.
1398 if ((m
->flags
& PG_BUSY
) || (m
->busy
!= 0))
1401 if (m
->wire_count
== 0) {
1402 vm_page_flag_clear(m
, PG_ZERO
);
1404 * Might as well free the page if we can and it has
1405 * no valid data. We also free the page if the
1406 * buffer was used for direct I/O.
1408 if ((bp
->b_flags
& B_ASYNC
) == 0 && !m
->valid
&&
1409 m
->hold_count
== 0) {
1411 vm_page_protect(m
, VM_PROT_NONE
);
1413 } else if (bp
->b_flags
& B_DIRECT
) {
1414 vm_page_try_to_free(m
);
1415 } else if (vm_page_count_severe()) {
1416 vm_page_try_to_cache(m
);
1421 pmap_qremove(trunc_page((vm_offset_t
) bp
->b_data
), bp
->b_xio
.xio_npages
);
1422 if (bp
->b_bufsize
) {
1426 bp
->b_xio
.xio_npages
= 0;
1427 bp
->b_flags
&= ~B_VMIO
;
1435 * Implement clustered async writes for clearing out B_DELWRI buffers.
1436 * This is much better then the old way of writing only one buffer at
1437 * a time. Note that we may not be presented with the buffers in the
1438 * correct order, so we search for the cluster in both directions.
1440 * The buffer is locked on call.
1443 vfs_bio_awrite(struct buf
*bp
)
1447 off_t loffset
= bp
->b_loffset
;
1448 struct vnode
*vp
= bp
->b_vp
;
1456 * right now we support clustered writing only to regular files. If
1457 * we find a clusterable block we could be in the middle of a cluster
1458 * rather then at the beginning.
1460 * NOTE: b_bio1 contains the logical loffset and is aliased
1461 * to b_loffset. b_bio2 contains the translated block number.
1463 if ((vp
->v_type
== VREG
) &&
1464 (vp
->v_mount
!= 0) && /* Only on nodes that have the size info */
1465 (bp
->b_flags
& (B_CLUSTEROK
| B_INVAL
)) == B_CLUSTEROK
) {
1467 size
= vp
->v_mount
->mnt_stat
.f_iosize
;
1469 for (i
= size
; i
< MAXPHYS
; i
+= size
) {
1470 if ((bpa
= findblk(vp
, loffset
+ i
)) &&
1471 BUF_REFCNT(bpa
) == 0 &&
1472 ((bpa
->b_flags
& (B_DELWRI
| B_CLUSTEROK
| B_INVAL
)) ==
1473 (B_DELWRI
| B_CLUSTEROK
)) &&
1474 (bpa
->b_bufsize
== size
)) {
1475 if ((bpa
->b_bio2
.bio_offset
== NOOFFSET
) ||
1476 (bpa
->b_bio2
.bio_offset
!=
1477 bp
->b_bio2
.bio_offset
+ i
))
1483 for (j
= size
; i
+ j
<= MAXPHYS
&& j
<= loffset
; j
+= size
) {
1484 if ((bpa
= findblk(vp
, loffset
- j
)) &&
1485 BUF_REFCNT(bpa
) == 0 &&
1486 ((bpa
->b_flags
& (B_DELWRI
| B_CLUSTEROK
| B_INVAL
)) ==
1487 (B_DELWRI
| B_CLUSTEROK
)) &&
1488 (bpa
->b_bufsize
== size
)) {
1489 if ((bpa
->b_bio2
.bio_offset
== NOOFFSET
) ||
1490 (bpa
->b_bio2
.bio_offset
!=
1491 bp
->b_bio2
.bio_offset
- j
))
1500 * this is a possible cluster write
1502 if (nbytes
!= size
) {
1504 nwritten
= cluster_wbuild(vp
, size
,
1505 loffset
- j
, nbytes
);
1512 bp
->b_flags
|= B_ASYNC
;
1516 * default (old) behavior, writing out only one block
1518 * XXX returns b_bufsize instead of b_bcount for nwritten?
1520 nwritten
= bp
->b_bufsize
;
1529 * Find and initialize a new buffer header, freeing up existing buffers
1530 * in the bufqueues as necessary. The new buffer is returned locked.
1532 * Important: B_INVAL is not set. If the caller wishes to throw the
1533 * buffer away, the caller must set B_INVAL prior to calling brelse().
1536 * We have insufficient buffer headers
1537 * We have insufficient buffer space
1538 * buffer_map is too fragmented ( space reservation fails )
1539 * If we have to flush dirty buffers ( but we try to avoid this )
1541 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1542 * Instead we ask the buf daemon to do it for us. We attempt to
1543 * avoid piecemeal wakeups of the pageout daemon.
1547 getnewbuf(int slpflag
, int slptimeo
, int size
, int maxsize
)
1553 static int flushingbufs
;
1556 * We can't afford to block since we might be holding a vnode lock,
1557 * which may prevent system daemons from running. We deal with
1558 * low-memory situations by proactively returning memory and running
1559 * async I/O rather then sync I/O.
1563 --getnewbufrestarts
;
1565 ++getnewbufrestarts
;
1568 * Setup for scan. If we do not have enough free buffers,
1569 * we setup a degenerate case that immediately fails. Note
1570 * that if we are specially marked process, we are allowed to
1571 * dip into our reserves.
1573 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1575 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1576 * However, there are a number of cases (defragging, reusing, ...)
1577 * where we cannot backup.
1579 nqindex
= BQUEUE_EMPTYKVA
;
1580 nbp
= TAILQ_FIRST(&bufqueues
[BQUEUE_EMPTYKVA
]);
1584 * If no EMPTYKVA buffers and we are either
1585 * defragging or reusing, locate a CLEAN buffer
1586 * to free or reuse. If bufspace useage is low
1587 * skip this step so we can allocate a new buffer.
1589 if (defrag
|| bufspace
>= lobufspace
) {
1590 nqindex
= BQUEUE_CLEAN
;
1591 nbp
= TAILQ_FIRST(&bufqueues
[BQUEUE_CLEAN
]);
1595 * If we could not find or were not allowed to reuse a
1596 * CLEAN buffer, check to see if it is ok to use an EMPTY
1597 * buffer. We can only use an EMPTY buffer if allocating
1598 * its KVA would not otherwise run us out of buffer space.
1600 if (nbp
== NULL
&& defrag
== 0 &&
1601 bufspace
+ maxsize
< hibufspace
) {
1602 nqindex
= BQUEUE_EMPTY
;
1603 nbp
= TAILQ_FIRST(&bufqueues
[BQUEUE_EMPTY
]);
1608 * Run scan, possibly freeing data and/or kva mappings on the fly
1612 while ((bp
= nbp
) != NULL
) {
1613 int qindex
= nqindex
;
1616 * Calculate next bp ( we can only use it if we do not block
1617 * or do other fancy things ).
1619 if ((nbp
= TAILQ_NEXT(bp
, b_freelist
)) == NULL
) {
1622 nqindex
= BQUEUE_EMPTYKVA
;
1623 if ((nbp
= TAILQ_FIRST(&bufqueues
[BQUEUE_EMPTYKVA
])))
1626 case BQUEUE_EMPTYKVA
:
1627 nqindex
= BQUEUE_CLEAN
;
1628 if ((nbp
= TAILQ_FIRST(&bufqueues
[BQUEUE_CLEAN
])))
1642 KASSERT(bp
->b_qindex
== qindex
, ("getnewbuf: inconsistent queue %d bp %p", qindex
, bp
));
1645 * Note: we no longer distinguish between VMIO and non-VMIO
1649 KASSERT((bp
->b_flags
& B_DELWRI
) == 0, ("delwri buffer %p found in queue %d", bp
, qindex
));
1652 * If we are defragging then we need a buffer with
1653 * b_kvasize != 0. XXX this situation should no longer
1654 * occur, if defrag is non-zero the buffer's b_kvasize
1655 * should also be non-zero at this point. XXX
1657 if (defrag
&& bp
->b_kvasize
== 0) {
1658 kprintf("Warning: defrag empty buffer %p\n", bp
);
1663 * Start freeing the bp. This is somewhat involved. nbp
1664 * remains valid only for BQUEUE_EMPTY[KVA] bp's. Buffers
1665 * on the clean list must be disassociated from their
1666 * current vnode. Buffers on the empty[kva] lists have
1667 * already been disassociated.
1670 if (BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_NOWAIT
) != 0) {
1671 kprintf("getnewbuf: warning, locked buf %p, race corrected\n", bp
);
1672 tsleep(&bd_request
, 0, "gnbxxx", hz
/ 100);
1675 if (bp
->b_qindex
!= qindex
) {
1676 kprintf("getnewbuf: warning, BUF_LOCK blocked unexpectedly on buf %p index %d->%d, race corrected\n", bp
, qindex
, bp
->b_qindex
);
1682 if (qindex
== BQUEUE_CLEAN
) {
1683 if (bp
->b_flags
& B_VMIO
) {
1684 bp
->b_flags
&= ~B_ASYNC
;
1685 vfs_vmio_release(bp
);
1692 * NOTE: nbp is now entirely invalid. We can only restart
1693 * the scan from this point on.
1695 * Get the rest of the buffer freed up. b_kva* is still
1696 * valid after this operation.
1699 KASSERT(bp
->b_vp
== NULL
, ("bp3 %p flags %08x vnode %p qindex %d unexpectededly still associated!", bp
, bp
->b_flags
, bp
->b_vp
, qindex
));
1700 KKASSERT((bp
->b_flags
& B_HASHED
) == 0);
1701 if (LIST_FIRST(&bp
->b_dep
) != NULL
&& bioops
.io_deallocate
)
1702 (*bioops
.io_deallocate
)(bp
);
1705 * critical section protection is not required when
1706 * scrapping a buffer's contents because it is already
1712 bp
->b_flags
= B_BNOCLIP
;
1713 bp
->b_cmd
= BUF_CMD_DONE
;
1718 bp
->b_xio
.xio_npages
= 0;
1719 bp
->b_dirtyoff
= bp
->b_dirtyend
= 0;
1722 LIST_INIT(&bp
->b_dep
);
1725 * If we are defragging then free the buffer.
1728 bp
->b_flags
|= B_INVAL
;
1736 * If we are overcomitted then recover the buffer and its
1737 * KVM space. This occurs in rare situations when multiple
1738 * processes are blocked in getnewbuf() or allocbuf().
1740 if (bufspace
>= hibufspace
)
1742 if (flushingbufs
&& bp
->b_kvasize
!= 0) {
1743 bp
->b_flags
|= B_INVAL
;
1748 if (bufspace
< lobufspace
)
1754 * If we exhausted our list, sleep as appropriate. We may have to
1755 * wakeup various daemons and write out some dirty buffers.
1757 * Generally we are sleeping due to insufficient buffer space.
1765 flags
= VFS_BIO_NEED_BUFSPACE
;
1767 } else if (bufspace
>= hibufspace
) {
1769 flags
= VFS_BIO_NEED_BUFSPACE
;
1772 flags
= VFS_BIO_NEED_ANY
;
1775 bd_speedup(); /* heeeelp */
1777 needsbuffer
|= flags
;
1778 while (needsbuffer
& flags
) {
1779 if (tsleep(&needsbuffer
, slpflag
, waitmsg
, slptimeo
))
1784 * We finally have a valid bp. We aren't quite out of the
1785 * woods, we still have to reserve kva space. In order
1786 * to keep fragmentation sane we only allocate kva in
1789 maxsize
= (maxsize
+ BKVAMASK
) & ~BKVAMASK
;
1791 if (maxsize
!= bp
->b_kvasize
) {
1792 vm_offset_t addr
= 0;
1797 count
= vm_map_entry_reserve(MAP_RESERVE_COUNT
);
1798 vm_map_lock(&buffer_map
);
1800 if (vm_map_findspace(&buffer_map
,
1801 vm_map_min(&buffer_map
), maxsize
,
1804 * Uh oh. Buffer map is too fragmented. We
1805 * must defragment the map.
1807 vm_map_unlock(&buffer_map
);
1808 vm_map_entry_release(count
);
1811 bp
->b_flags
|= B_INVAL
;
1816 vm_map_insert(&buffer_map
, &count
,
1818 addr
, addr
+ maxsize
,
1820 VM_PROT_ALL
, VM_PROT_ALL
,
1823 bp
->b_kvabase
= (caddr_t
) addr
;
1824 bp
->b_kvasize
= maxsize
;
1825 bufspace
+= bp
->b_kvasize
;
1828 vm_map_unlock(&buffer_map
);
1829 vm_map_entry_release(count
);
1831 bp
->b_data
= bp
->b_kvabase
;
1839 * Buffer flushing daemon. Buffers are normally flushed by the
1840 * update daemon but if it cannot keep up this process starts to
1841 * take the load in an attempt to prevent getnewbuf() from blocking.
1844 static struct thread
*bufdaemonthread
;
1846 static struct kproc_desc buf_kp
= {
1851 SYSINIT(bufdaemon
, SI_SUB_KTHREAD_BUF
, SI_ORDER_FIRST
, kproc_start
, &buf_kp
)
1857 * This process needs to be suspended prior to shutdown sync.
1859 EVENTHANDLER_REGISTER(shutdown_pre_sync
, shutdown_kproc
,
1860 bufdaemonthread
, SHUTDOWN_PRI_LAST
);
1863 * This process is allowed to take the buffer cache to the limit
1868 kproc_suspend_loop();
1871 * Do the flush. Limit the amount of in-transit I/O we
1872 * allow to build up, otherwise we would completely saturate
1873 * the I/O system. Wakeup any waiting processes before we
1874 * normally would so they can run in parallel with our drain.
1876 while (numdirtybuffers
> lodirtybuffers
) {
1877 if (flushbufqueues() == 0)
1879 waitrunningbufspace();
1880 numdirtywakeup((lodirtybuffers
+ hidirtybuffers
) / 2);
1884 * Only clear bd_request if we have reached our low water
1885 * mark. The buf_daemon normally waits 5 seconds and
1886 * then incrementally flushes any dirty buffers that have
1887 * built up, within reason.
1889 * If we were unable to hit our low water mark and couldn't
1890 * find any flushable buffers, we sleep half a second.
1891 * Otherwise we loop immediately.
1893 if (numdirtybuffers
<= lodirtybuffers
) {
1895 * We reached our low water mark, reset the
1896 * request and sleep until we are needed again.
1897 * The sleep is just so the suspend code works.
1899 spin_lock_wr(&needsbuffer_spin
);
1901 msleep(&bd_request
, &needsbuffer_spin
, 0, "psleep", hz
);
1902 spin_unlock_wr(&needsbuffer_spin
);
1905 * We couldn't find any flushable dirty buffers but
1906 * still have too many dirty buffers, we
1907 * have to sleep and try again. (rare)
1909 tsleep(&bd_request
, 0, "qsleep", hz
/ 2);
1917 * Try to flush a buffer in the dirty queue. We must be careful to
1918 * free up B_INVAL buffers instead of write them, which NFS is
1919 * particularly sensitive to.
1923 flushbufqueues(void)
1928 bp
= TAILQ_FIRST(&bufqueues
[BQUEUE_DIRTY
]);
1931 KASSERT((bp
->b_flags
& B_DELWRI
), ("unexpected clean buffer %p", bp
));
1932 if (bp
->b_flags
& B_DELWRI
) {
1933 if (bp
->b_flags
& B_INVAL
) {
1934 if (BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_NOWAIT
) != 0)
1935 panic("flushbufqueues: locked buf");
1941 if (LIST_FIRST(&bp
->b_dep
) != NULL
&&
1942 bioops
.io_countdeps
&&
1943 (bp
->b_flags
& B_DEFERRED
) == 0 &&
1944 (*bioops
.io_countdeps
)(bp
, 0)) {
1945 TAILQ_REMOVE(&bufqueues
[BQUEUE_DIRTY
],
1947 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_DIRTY
],
1949 bp
->b_flags
|= B_DEFERRED
;
1950 bp
= TAILQ_FIRST(&bufqueues
[BQUEUE_DIRTY
]);
1955 * Only write it out if we can successfully lock
1958 if (BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_NOWAIT
) == 0) {
1964 bp
= TAILQ_NEXT(bp
, b_freelist
);
1972 * Returns true if no I/O is needed to access the associated VM object.
1973 * This is like findblk except it also hunts around in the VM system for
1976 * Note that we ignore vm_page_free() races from interrupts against our
1977 * lookup, since if the caller is not protected our return value will not
1978 * be any more valid then otherwise once we exit the critical section.
1981 inmem(struct vnode
*vp
, off_t loffset
)
1984 vm_offset_t toff
, tinc
, size
;
1987 if (findblk(vp
, loffset
))
1989 if (vp
->v_mount
== NULL
)
1991 if ((obj
= vp
->v_object
) == NULL
)
1995 if (size
> vp
->v_mount
->mnt_stat
.f_iosize
)
1996 size
= vp
->v_mount
->mnt_stat
.f_iosize
;
1998 for (toff
= 0; toff
< vp
->v_mount
->mnt_stat
.f_iosize
; toff
+= tinc
) {
1999 m
= vm_page_lookup(obj
, OFF_TO_IDX(loffset
+ toff
));
2003 if (tinc
> PAGE_SIZE
- ((toff
+ loffset
) & PAGE_MASK
))
2004 tinc
= PAGE_SIZE
- ((toff
+ loffset
) & PAGE_MASK
);
2005 if (vm_page_is_valid(m
,
2006 (vm_offset_t
) ((toff
+ loffset
) & PAGE_MASK
), tinc
) == 0)
2015 * Sets the dirty range for a buffer based on the status of the dirty
2016 * bits in the pages comprising the buffer.
2018 * The range is limited to the size of the buffer.
2020 * This routine is primarily used by NFS, but is generalized for the
2024 vfs_setdirty(struct buf
*bp
)
2030 * Degenerate case - empty buffer
2033 if (bp
->b_bufsize
== 0)
2037 * We qualify the scan for modified pages on whether the
2038 * object has been flushed yet. The OBJ_WRITEABLE flag
2039 * is not cleared simply by protecting pages off.
2042 if ((bp
->b_flags
& B_VMIO
) == 0)
2045 object
= bp
->b_xio
.xio_pages
[0]->object
;
2047 if ((object
->flags
& OBJ_WRITEABLE
) && !(object
->flags
& OBJ_MIGHTBEDIRTY
))
2048 kprintf("Warning: object %p writeable but not mightbedirty\n", object
);
2049 if (!(object
->flags
& OBJ_WRITEABLE
) && (object
->flags
& OBJ_MIGHTBEDIRTY
))
2050 kprintf("Warning: object %p mightbedirty but not writeable\n", object
);
2052 if (object
->flags
& (OBJ_MIGHTBEDIRTY
|OBJ_CLEANING
)) {
2053 vm_offset_t boffset
;
2054 vm_offset_t eoffset
;
2057 * test the pages to see if they have been modified directly
2058 * by users through the VM system.
2060 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
2061 vm_page_flag_clear(bp
->b_xio
.xio_pages
[i
], PG_ZERO
);
2062 vm_page_test_dirty(bp
->b_xio
.xio_pages
[i
]);
2066 * Calculate the encompassing dirty range, boffset and eoffset,
2067 * (eoffset - boffset) bytes.
2070 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
2071 if (bp
->b_xio
.xio_pages
[i
]->dirty
)
2074 boffset
= (i
<< PAGE_SHIFT
) - (bp
->b_loffset
& PAGE_MASK
);
2076 for (i
= bp
->b_xio
.xio_npages
- 1; i
>= 0; --i
) {
2077 if (bp
->b_xio
.xio_pages
[i
]->dirty
) {
2081 eoffset
= ((i
+ 1) << PAGE_SHIFT
) - (bp
->b_loffset
& PAGE_MASK
);
2084 * Fit it to the buffer.
2087 if (eoffset
> bp
->b_bcount
)
2088 eoffset
= bp
->b_bcount
;
2091 * If we have a good dirty range, merge with the existing
2095 if (boffset
< eoffset
) {
2096 if (bp
->b_dirtyoff
> boffset
)
2097 bp
->b_dirtyoff
= boffset
;
2098 if (bp
->b_dirtyend
< eoffset
)
2099 bp
->b_dirtyend
= eoffset
;
2107 * Locate and return the specified buffer, or NULL if the buffer does
2108 * not exist. Do not attempt to lock the buffer or manipulate it in
2109 * any way. The caller must validate that the correct buffer has been
2110 * obtain after locking it.
2113 findblk(struct vnode
*vp
, off_t loffset
)
2118 bp
= buf_rb_hash_RB_LOOKUP(&vp
->v_rbhash_tree
, loffset
);
2126 * Get a block given a specified block and offset into a file/device.
2127 * B_INVAL may or may not be set on return. The caller should clear
2128 * B_INVAL prior to initiating a READ.
2130 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2131 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2132 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2133 * without doing any of those things the system will likely believe
2134 * the buffer to be valid (especially if it is not B_VMIO), and the
2135 * next getblk() will return the buffer with B_CACHE set.
2137 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2138 * an existing buffer.
2140 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2141 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2142 * and then cleared based on the backing VM. If the previous buffer is
2143 * non-0-sized but invalid, B_CACHE will be cleared.
2145 * If getblk() must create a new buffer, the new buffer is returned with
2146 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2147 * case it is returned with B_INVAL clear and B_CACHE set based on the
2150 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
2151 * B_CACHE bit is clear.
2153 * What this means, basically, is that the caller should use B_CACHE to
2154 * determine whether the buffer is fully valid or not and should clear
2155 * B_INVAL prior to issuing a read. If the caller intends to validate
2156 * the buffer by loading its data area with something, the caller needs
2157 * to clear B_INVAL. If the caller does this without issuing an I/O,
2158 * the caller should set B_CACHE ( as an optimization ), else the caller
2159 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2160 * a write attempt or if it was a successfull read. If the caller
2161 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2162 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2165 getblk(struct vnode
*vp
, off_t loffset
, int size
, int slpflag
, int slptimeo
)
2169 if (size
> MAXBSIZE
)
2170 panic("getblk: size(%d) > MAXBSIZE(%d)", size
, MAXBSIZE
);
2171 if (vp
->v_object
== NULL
)
2172 panic("getblk: vnode %p has no object!", vp
);
2177 * Block if we are low on buffers. Certain processes are allowed
2178 * to completely exhaust the buffer cache.
2180 * If this check ever becomes a bottleneck it may be better to
2181 * move it into the else, when findblk() fails. At the moment
2182 * it isn't a problem.
2184 * XXX remove, we cannot afford to block anywhere if holding a vnode
2185 * lock in low-memory situation, so take it to the max.
2187 if (numfreebuffers
== 0) {
2190 needsbuffer
|= VFS_BIO_NEED_ANY
;
2191 tsleep(&needsbuffer
, slpflag
, "newbuf", slptimeo
);
2194 if ((bp
= findblk(vp
, loffset
))) {
2196 * The buffer was found in the cache, but we need to lock it.
2197 * Even with LK_NOWAIT the lockmgr may break our critical
2198 * section, so double-check the validity of the buffer
2199 * once the lock has been obtained.
2201 if (BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_NOWAIT
)) {
2202 int lkflags
= LK_EXCLUSIVE
| LK_SLEEPFAIL
;
2203 if (slpflag
& PCATCH
)
2204 lkflags
|= LK_PCATCH
;
2205 if (BUF_TIMELOCK(bp
, lkflags
, "getblk", slptimeo
) ==
2214 * Once the buffer has been locked, make sure we didn't race
2215 * a buffer recyclement. Buffers that are no longer hashed
2216 * will have b_vp == NULL, so this takes care of that check
2219 if (bp
->b_vp
!= vp
|| bp
->b_loffset
!= loffset
) {
2220 kprintf("Warning buffer %p (vp %p loffset %lld) was recycled\n", bp
, vp
, loffset
);
2226 * All vnode-based buffers must be backed by a VM object.
2228 KKASSERT(bp
->b_flags
& B_VMIO
);
2229 KKASSERT(bp
->b_cmd
== BUF_CMD_DONE
);
2232 * Make sure that B_INVAL buffers do not have a cached
2233 * block number translation.
2235 if ((bp
->b_flags
& B_INVAL
) && (bp
->b_bio2
.bio_offset
!= NOOFFSET
)) {
2236 kprintf("Warning invalid buffer %p (vp %p loffset %lld) did not have cleared bio_offset cache\n", bp
, vp
, loffset
);
2237 clearbiocache(&bp
->b_bio2
);
2241 * The buffer is locked. B_CACHE is cleared if the buffer is
2244 if (bp
->b_flags
& B_INVAL
)
2245 bp
->b_flags
&= ~B_CACHE
;
2249 * Any size inconsistancy with a dirty buffer or a buffer
2250 * with a softupdates dependancy must be resolved. Resizing
2251 * the buffer in such circumstances can lead to problems.
2253 if (size
!= bp
->b_bcount
) {
2254 if (bp
->b_flags
& B_DELWRI
) {
2255 bp
->b_flags
|= B_NOCACHE
;
2257 } else if (LIST_FIRST(&bp
->b_dep
)) {
2258 bp
->b_flags
|= B_NOCACHE
;
2261 bp
->b_flags
|= B_RELBUF
;
2266 KKASSERT(size
<= bp
->b_kvasize
);
2267 KASSERT(bp
->b_loffset
!= NOOFFSET
,
2268 ("getblk: no buffer offset"));
2271 * A buffer with B_DELWRI set and B_CACHE clear must
2272 * be committed before we can return the buffer in
2273 * order to prevent the caller from issuing a read
2274 * ( due to B_CACHE not being set ) and overwriting
2277 * Most callers, including NFS and FFS, need this to
2278 * operate properly either because they assume they
2279 * can issue a read if B_CACHE is not set, or because
2280 * ( for example ) an uncached B_DELWRI might loop due
2281 * to softupdates re-dirtying the buffer. In the latter
2282 * case, B_CACHE is set after the first write completes,
2283 * preventing further loops.
2285 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2286 * above while extending the buffer, we cannot allow the
2287 * buffer to remain with B_CACHE set after the write
2288 * completes or it will represent a corrupt state. To
2289 * deal with this we set B_NOCACHE to scrap the buffer
2292 * We might be able to do something fancy, like setting
2293 * B_CACHE in bwrite() except if B_DELWRI is already set,
2294 * so the below call doesn't set B_CACHE, but that gets real
2295 * confusing. This is much easier.
2298 if ((bp
->b_flags
& (B_CACHE
|B_DELWRI
)) == B_DELWRI
) {
2299 bp
->b_flags
|= B_NOCACHE
;
2306 * Buffer is not in-core, create new buffer. The buffer
2307 * returned by getnewbuf() is locked. Note that the returned
2308 * buffer is also considered valid (not marked B_INVAL).
2310 * Calculating the offset for the I/O requires figuring out
2311 * the block size. We use DEV_BSIZE for VBLK or VCHR and
2312 * the mount's f_iosize otherwise. If the vnode does not
2313 * have an associated mount we assume that the passed size is
2316 * Note that vn_isdisk() cannot be used here since it may
2317 * return a failure for numerous reasons. Note that the
2318 * buffer size may be larger then the block size (the caller
2319 * will use block numbers with the proper multiple). Beware
2320 * of using any v_* fields which are part of unions. In
2321 * particular, in DragonFly the mount point overloading
2322 * mechanism uses the namecache only and the underlying
2323 * directory vnode is not a special case.
2327 if (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
)
2329 else if (vp
->v_mount
)
2330 bsize
= vp
->v_mount
->mnt_stat
.f_iosize
;
2334 maxsize
= size
+ (loffset
& PAGE_MASK
);
2335 maxsize
= imax(maxsize
, bsize
);
2337 if ((bp
= getnewbuf(slpflag
, slptimeo
, size
, maxsize
)) == NULL
) {
2338 if (slpflag
|| slptimeo
) {
2346 * This code is used to make sure that a buffer is not
2347 * created while the getnewbuf routine is blocked.
2348 * This can be a problem whether the vnode is locked or not.
2349 * If the buffer is created out from under us, we have to
2350 * throw away the one we just created. There is no window
2351 * race because we are safely running in a critical section
2352 * from the point of the duplicate buffer creation through
2353 * to here, and we've locked the buffer.
2355 if (findblk(vp
, loffset
)) {
2356 bp
->b_flags
|= B_INVAL
;
2362 * Insert the buffer into the hash, so that it can
2363 * be found by findblk().
2365 * Make sure the translation layer has been cleared.
2367 bp
->b_loffset
= loffset
;
2368 bp
->b_bio2
.bio_offset
= NOOFFSET
;
2369 /* bp->b_bio2.bio_next = NULL; */
2374 * All vnode-based buffers must be backed by a VM object.
2376 KKASSERT(vp
->v_object
!= NULL
);
2377 bp
->b_flags
|= B_VMIO
;
2378 KKASSERT(bp
->b_cmd
== BUF_CMD_DONE
);
2390 * Get an empty, disassociated buffer of given size. The buffer is
2391 * initially set to B_INVAL.
2393 * critical section protection is not required for the allocbuf()
2394 * call because races are impossible here.
2402 maxsize
= (size
+ BKVAMASK
) & ~BKVAMASK
;
2405 while ((bp
= getnewbuf(0, 0, size
, maxsize
)) == 0)
2409 bp
->b_flags
|= B_INVAL
; /* b_dep cleared by getnewbuf() */
2417 * This code constitutes the buffer memory from either anonymous system
2418 * memory (in the case of non-VMIO operations) or from an associated
2419 * VM object (in the case of VMIO operations). This code is able to
2420 * resize a buffer up or down.
2422 * Note that this code is tricky, and has many complications to resolve
2423 * deadlock or inconsistant data situations. Tread lightly!!!
2424 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2425 * the caller. Calling this code willy nilly can result in the loss of data.
2427 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2428 * B_CACHE for the non-VMIO case.
2430 * This routine does not need to be called from a critical section but you
2431 * must own the buffer.
2434 allocbuf(struct buf
*bp
, int size
)
2436 int newbsize
, mbsize
;
2439 if (BUF_REFCNT(bp
) == 0)
2440 panic("allocbuf: buffer not busy");
2442 if (bp
->b_kvasize
< size
)
2443 panic("allocbuf: buffer too small");
2445 if ((bp
->b_flags
& B_VMIO
) == 0) {
2449 * Just get anonymous memory from the kernel. Don't
2450 * mess with B_CACHE.
2452 mbsize
= (size
+ DEV_BSIZE
- 1) & ~(DEV_BSIZE
- 1);
2453 if (bp
->b_flags
& B_MALLOC
)
2456 newbsize
= round_page(size
);
2458 if (newbsize
< bp
->b_bufsize
) {
2460 * Malloced buffers are not shrunk
2462 if (bp
->b_flags
& B_MALLOC
) {
2464 bp
->b_bcount
= size
;
2466 kfree(bp
->b_data
, M_BIOBUF
);
2467 if (bp
->b_bufsize
) {
2468 bufmallocspace
-= bp
->b_bufsize
;
2472 bp
->b_data
= bp
->b_kvabase
;
2474 bp
->b_flags
&= ~B_MALLOC
;
2480 (vm_offset_t
) bp
->b_data
+ newbsize
,
2481 (vm_offset_t
) bp
->b_data
+ bp
->b_bufsize
);
2482 } else if (newbsize
> bp
->b_bufsize
) {
2484 * We only use malloced memory on the first allocation.
2485 * and revert to page-allocated memory when the buffer
2488 if ((bufmallocspace
< maxbufmallocspace
) &&
2489 (bp
->b_bufsize
== 0) &&
2490 (mbsize
<= PAGE_SIZE
/2)) {
2492 bp
->b_data
= kmalloc(mbsize
, M_BIOBUF
, M_WAITOK
);
2493 bp
->b_bufsize
= mbsize
;
2494 bp
->b_bcount
= size
;
2495 bp
->b_flags
|= B_MALLOC
;
2496 bufmallocspace
+= mbsize
;
2502 * If the buffer is growing on its other-than-first
2503 * allocation, then we revert to the page-allocation
2506 if (bp
->b_flags
& B_MALLOC
) {
2507 origbuf
= bp
->b_data
;
2508 origbufsize
= bp
->b_bufsize
;
2509 bp
->b_data
= bp
->b_kvabase
;
2510 if (bp
->b_bufsize
) {
2511 bufmallocspace
-= bp
->b_bufsize
;
2515 bp
->b_flags
&= ~B_MALLOC
;
2516 newbsize
= round_page(newbsize
);
2520 (vm_offset_t
) bp
->b_data
+ bp
->b_bufsize
,
2521 (vm_offset_t
) bp
->b_data
+ newbsize
);
2523 bcopy(origbuf
, bp
->b_data
, origbufsize
);
2524 kfree(origbuf
, M_BIOBUF
);
2531 newbsize
= (size
+ DEV_BSIZE
- 1) & ~(DEV_BSIZE
- 1);
2532 desiredpages
= ((int)(bp
->b_loffset
& PAGE_MASK
) +
2533 newbsize
+ PAGE_MASK
) >> PAGE_SHIFT
;
2534 KKASSERT(desiredpages
<= XIO_INTERNAL_PAGES
);
2536 if (bp
->b_flags
& B_MALLOC
)
2537 panic("allocbuf: VMIO buffer can't be malloced");
2539 * Set B_CACHE initially if buffer is 0 length or will become
2542 if (size
== 0 || bp
->b_bufsize
== 0)
2543 bp
->b_flags
|= B_CACHE
;
2545 if (newbsize
< bp
->b_bufsize
) {
2547 * DEV_BSIZE aligned new buffer size is less then the
2548 * DEV_BSIZE aligned existing buffer size. Figure out
2549 * if we have to remove any pages.
2551 if (desiredpages
< bp
->b_xio
.xio_npages
) {
2552 for (i
= desiredpages
; i
< bp
->b_xio
.xio_npages
; i
++) {
2554 * the page is not freed here -- it
2555 * is the responsibility of
2556 * vnode_pager_setsize
2558 m
= bp
->b_xio
.xio_pages
[i
];
2559 KASSERT(m
!= bogus_page
,
2560 ("allocbuf: bogus page found"));
2561 while (vm_page_sleep_busy(m
, TRUE
, "biodep"))
2564 bp
->b_xio
.xio_pages
[i
] = NULL
;
2565 vm_page_unwire(m
, 0);
2567 pmap_qremove((vm_offset_t
) trunc_page((vm_offset_t
)bp
->b_data
) +
2568 (desiredpages
<< PAGE_SHIFT
), (bp
->b_xio
.xio_npages
- desiredpages
));
2569 bp
->b_xio
.xio_npages
= desiredpages
;
2571 } else if (size
> bp
->b_bcount
) {
2573 * We are growing the buffer, possibly in a
2574 * byte-granular fashion.
2582 * Step 1, bring in the VM pages from the object,
2583 * allocating them if necessary. We must clear
2584 * B_CACHE if these pages are not valid for the
2585 * range covered by the buffer.
2587 * critical section protection is required to protect
2588 * against interrupts unbusying and freeing pages
2589 * between our vm_page_lookup() and our
2590 * busycheck/wiring call.
2596 while (bp
->b_xio
.xio_npages
< desiredpages
) {
2600 pi
= OFF_TO_IDX(bp
->b_loffset
) + bp
->b_xio
.xio_npages
;
2601 if ((m
= vm_page_lookup(obj
, pi
)) == NULL
) {
2603 * note: must allocate system pages
2604 * since blocking here could intefere
2605 * with paging I/O, no matter which
2608 m
= vm_page_alloc(obj
, pi
, VM_ALLOC_NORMAL
| VM_ALLOC_SYSTEM
);
2611 vm_pageout_deficit
+= desiredpages
-
2612 bp
->b_xio
.xio_npages
;
2616 bp
->b_flags
&= ~B_CACHE
;
2617 bp
->b_xio
.xio_pages
[bp
->b_xio
.xio_npages
] = m
;
2618 ++bp
->b_xio
.xio_npages
;
2624 * We found a page. If we have to sleep on it,
2625 * retry because it might have gotten freed out
2628 * We can only test PG_BUSY here. Blocking on
2629 * m->busy might lead to a deadlock:
2631 * vm_fault->getpages->cluster_read->allocbuf
2635 if (vm_page_sleep_busy(m
, FALSE
, "pgtblk"))
2639 * We have a good page. Should we wakeup the
2642 if ((curthread
!= pagethread
) &&
2643 ((m
->queue
- m
->pc
) == PQ_CACHE
) &&
2644 ((vmstats
.v_free_count
+ vmstats
.v_cache_count
) <
2645 (vmstats
.v_free_min
+ vmstats
.v_cache_min
))) {
2646 pagedaemon_wakeup();
2648 vm_page_flag_clear(m
, PG_ZERO
);
2650 bp
->b_xio
.xio_pages
[bp
->b_xio
.xio_npages
] = m
;
2651 ++bp
->b_xio
.xio_npages
;
2656 * Step 2. We've loaded the pages into the buffer,
2657 * we have to figure out if we can still have B_CACHE
2658 * set. Note that B_CACHE is set according to the
2659 * byte-granular range ( bcount and size ), not the
2660 * aligned range ( newbsize ).
2662 * The VM test is against m->valid, which is DEV_BSIZE
2663 * aligned. Needless to say, the validity of the data
2664 * needs to also be DEV_BSIZE aligned. Note that this
2665 * fails with NFS if the server or some other client
2666 * extends the file's EOF. If our buffer is resized,
2667 * B_CACHE may remain set! XXX
2670 toff
= bp
->b_bcount
;
2671 tinc
= PAGE_SIZE
- ((bp
->b_loffset
+ toff
) & PAGE_MASK
);
2673 while ((bp
->b_flags
& B_CACHE
) && toff
< size
) {
2676 if (tinc
> (size
- toff
))
2679 pi
= ((bp
->b_loffset
& PAGE_MASK
) + toff
) >>
2687 bp
->b_xio
.xio_pages
[pi
]
2694 * Step 3, fixup the KVM pmap. Remember that
2695 * bp->b_data is relative to bp->b_loffset, but
2696 * bp->b_loffset may be offset into the first page.
2699 bp
->b_data
= (caddr_t
)
2700 trunc_page((vm_offset_t
)bp
->b_data
);
2702 (vm_offset_t
)bp
->b_data
,
2703 bp
->b_xio
.xio_pages
,
2704 bp
->b_xio
.xio_npages
2706 bp
->b_data
= (caddr_t
)((vm_offset_t
)bp
->b_data
|
2707 (vm_offset_t
)(bp
->b_loffset
& PAGE_MASK
));
2710 if (newbsize
< bp
->b_bufsize
)
2712 bp
->b_bufsize
= newbsize
; /* actual buffer allocation */
2713 bp
->b_bcount
= size
; /* requested buffer size */
2720 * Wait for buffer I/O completion, returning error status. The buffer
2721 * is left locked on return. B_EINTR is converted into an EINTR error
2724 * NOTE! The original b_cmd is lost on return, since b_cmd will be
2725 * set to BUF_CMD_DONE.
2728 biowait(struct buf
*bp
)
2731 while (bp
->b_cmd
!= BUF_CMD_DONE
) {
2732 if (bp
->b_cmd
== BUF_CMD_READ
)
2733 tsleep(bp
, 0, "biord", 0);
2735 tsleep(bp
, 0, "biowr", 0);
2738 if (bp
->b_flags
& B_EINTR
) {
2739 bp
->b_flags
&= ~B_EINTR
;
2742 if (bp
->b_flags
& B_ERROR
) {
2743 return (bp
->b_error
? bp
->b_error
: EIO
);
2750 * This associates a tracking count with an I/O. vn_strategy() and
2751 * dev_dstrategy() do this automatically but there are a few cases
2752 * where a vnode or device layer is bypassed when a block translation
2753 * is cached. In such cases bio_start_transaction() may be called on
2754 * the bypassed layers so the system gets an I/O in progress indication
2755 * for those higher layers.
2758 bio_start_transaction(struct bio
*bio
, struct bio_track
*track
)
2760 bio
->bio_track
= track
;
2761 atomic_add_int(&track
->bk_active
, 1);
2765 * Initiate I/O on a vnode.
2768 vn_strategy(struct vnode
*vp
, struct bio
*bio
)
2770 struct bio_track
*track
;
2772 KKASSERT(bio
->bio_buf
->b_cmd
!= BUF_CMD_DONE
);
2773 if (bio
->bio_buf
->b_cmd
== BUF_CMD_READ
)
2774 track
= &vp
->v_track_read
;
2776 track
= &vp
->v_track_write
;
2777 bio
->bio_track
= track
;
2778 atomic_add_int(&track
->bk_active
, 1);
2779 vop_strategy(*vp
->v_ops
, vp
, bio
);
2786 * Finish I/O on a buffer, optionally calling a completion function.
2787 * This is usually called from an interrupt so process blocking is
2790 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2791 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
2792 * assuming B_INVAL is clear.
2794 * For the VMIO case, we set B_CACHE if the op was a read and no
2795 * read error occured, or if the op was a write. B_CACHE is never
2796 * set if the buffer is invalid or otherwise uncacheable.
2798 * biodone does not mess with B_INVAL, allowing the I/O routine or the
2799 * initiator to leave B_INVAL set to brelse the buffer out of existance
2800 * in the biodone routine.
2803 biodone(struct bio
*bio
)
2805 struct buf
*bp
= bio
->bio_buf
;
2810 KASSERT(BUF_REFCNTNB(bp
) > 0,
2811 ("biodone: bp %p not busy %d", bp
, BUF_REFCNTNB(bp
)));
2812 KASSERT(bp
->b_cmd
!= BUF_CMD_DONE
,
2813 ("biodone: bp %p already done!", bp
));
2815 runningbufwakeup(bp
);
2818 * Run up the chain of BIO's. Leave b_cmd intact for the duration.
2821 biodone_t
*done_func
;
2822 struct bio_track
*track
;
2825 * BIO tracking. Most but not all BIOs are tracked.
2827 if ((track
= bio
->bio_track
) != NULL
) {
2828 atomic_subtract_int(&track
->bk_active
, 1);
2829 if (track
->bk_active
< 0) {
2830 panic("biodone: bad active count bio %p\n",
2833 if (track
->bk_waitflag
) {
2834 track
->bk_waitflag
= 0;
2837 bio
->bio_track
= NULL
;
2841 * A bio_done function terminates the loop. The function
2842 * will be responsible for any further chaining and/or
2843 * buffer management.
2845 * WARNING! The done function can deallocate the buffer!
2847 if ((done_func
= bio
->bio_done
) != NULL
) {
2848 bio
->bio_done
= NULL
;
2853 bio
= bio
->bio_prev
;
2857 bp
->b_cmd
= BUF_CMD_DONE
;
2860 * Only reads and writes are processed past this point.
2862 if (cmd
!= BUF_CMD_READ
&& cmd
!= BUF_CMD_WRITE
) {
2869 * Warning: softupdates may re-dirty the buffer.
2871 if (LIST_FIRST(&bp
->b_dep
) != NULL
&& bioops
.io_complete
)
2872 (*bioops
.io_complete
)(bp
);
2874 if (bp
->b_flags
& B_VMIO
) {
2880 struct vnode
*vp
= bp
->b_vp
;
2884 #if defined(VFS_BIO_DEBUG)
2885 if (vp
->v_auxrefs
== 0)
2886 panic("biodone: zero vnode hold count");
2887 if ((vp
->v_flag
& VOBJBUF
) == 0)
2888 panic("biodone: vnode is not setup for merged cache");
2891 foff
= bp
->b_loffset
;
2892 KASSERT(foff
!= NOOFFSET
, ("biodone: no buffer offset"));
2893 KASSERT(obj
!= NULL
, ("biodone: missing VM object"));
2895 #if defined(VFS_BIO_DEBUG)
2896 if (obj
->paging_in_progress
< bp
->b_xio
.xio_npages
) {
2897 kprintf("biodone: paging in progress(%d) < bp->b_xio.xio_npages(%d)\n",
2898 obj
->paging_in_progress
, bp
->b_xio
.xio_npages
);
2903 * Set B_CACHE if the op was a normal read and no error
2904 * occured. B_CACHE is set for writes in the b*write()
2907 iosize
= bp
->b_bcount
- bp
->b_resid
;
2908 if (cmd
== BUF_CMD_READ
&& (bp
->b_flags
& (B_INVAL
|B_NOCACHE
|B_ERROR
)) == 0) {
2909 bp
->b_flags
|= B_CACHE
;
2912 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
2916 resid
= ((foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
) - foff
;
2921 * cleanup bogus pages, restoring the originals. Since
2922 * the originals should still be wired, we don't have
2923 * to worry about interrupt/freeing races destroying
2924 * the VM object association.
2926 m
= bp
->b_xio
.xio_pages
[i
];
2927 if (m
== bogus_page
) {
2929 m
= vm_page_lookup(obj
, OFF_TO_IDX(foff
));
2931 panic("biodone: page disappeared");
2932 bp
->b_xio
.xio_pages
[i
] = m
;
2933 pmap_qenter(trunc_page((vm_offset_t
)bp
->b_data
),
2934 bp
->b_xio
.xio_pages
, bp
->b_xio
.xio_npages
);
2936 #if defined(VFS_BIO_DEBUG)
2937 if (OFF_TO_IDX(foff
) != m
->pindex
) {
2939 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
2940 (unsigned long)foff
, m
->pindex
);
2945 * In the write case, the valid and clean bits are
2946 * already changed correctly ( see bdwrite() ), so we
2947 * only need to do this here in the read case.
2949 if (cmd
== BUF_CMD_READ
&& !bogusflag
&& resid
> 0) {
2950 vfs_page_set_valid(bp
, foff
, i
, m
);
2952 vm_page_flag_clear(m
, PG_ZERO
);
2955 * when debugging new filesystems or buffer I/O methods, this
2956 * is the most common error that pops up. if you see this, you
2957 * have not set the page busy flag correctly!!!
2960 kprintf("biodone: page busy < 0, "
2961 "pindex: %d, foff: 0x(%x,%x), "
2962 "resid: %d, index: %d\n",
2963 (int) m
->pindex
, (int)(foff
>> 32),
2964 (int) foff
& 0xffffffff, resid
, i
);
2965 if (!vn_isdisk(vp
, NULL
))
2966 kprintf(" iosize: %ld, loffset: %lld, flags: 0x%08x, npages: %d\n",
2967 bp
->b_vp
->v_mount
->mnt_stat
.f_iosize
,
2969 bp
->b_flags
, bp
->b_xio
.xio_npages
);
2971 kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
2973 bp
->b_flags
, bp
->b_xio
.xio_npages
);
2974 kprintf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
2975 m
->valid
, m
->dirty
, m
->wire_count
);
2976 panic("biodone: page busy < 0");
2978 vm_page_io_finish(m
);
2979 vm_object_pip_subtract(obj
, 1);
2980 foff
= (foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
;
2984 vm_object_pip_wakeupn(obj
, 0);
2988 * For asynchronous completions, release the buffer now. The brelse
2989 * will do a wakeup there if necessary - so no need to do a wakeup
2990 * here in the async case. The sync case always needs to do a wakeup.
2993 if (bp
->b_flags
& B_ASYNC
) {
2994 if ((bp
->b_flags
& (B_NOCACHE
| B_INVAL
| B_ERROR
| B_RELBUF
)) != 0)
3007 * This routine is called in lieu of iodone in the case of
3008 * incomplete I/O. This keeps the busy status for pages
3012 vfs_unbusy_pages(struct buf
*bp
)
3016 runningbufwakeup(bp
);
3017 if (bp
->b_flags
& B_VMIO
) {
3018 struct vnode
*vp
= bp
->b_vp
;
3023 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3024 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
3027 * When restoring bogus changes the original pages
3028 * should still be wired, so we are in no danger of
3029 * losing the object association and do not need
3030 * critical section protection particularly.
3032 if (m
== bogus_page
) {
3033 m
= vm_page_lookup(obj
, OFF_TO_IDX(bp
->b_loffset
) + i
);
3035 panic("vfs_unbusy_pages: page missing");
3037 bp
->b_xio
.xio_pages
[i
] = m
;
3038 pmap_qenter(trunc_page((vm_offset_t
)bp
->b_data
),
3039 bp
->b_xio
.xio_pages
, bp
->b_xio
.xio_npages
);
3041 vm_object_pip_subtract(obj
, 1);
3042 vm_page_flag_clear(m
, PG_ZERO
);
3043 vm_page_io_finish(m
);
3045 vm_object_pip_wakeupn(obj
, 0);
3050 * vfs_page_set_valid:
3052 * Set the valid bits in a page based on the supplied offset. The
3053 * range is restricted to the buffer's size.
3055 * This routine is typically called after a read completes.
3058 vfs_page_set_valid(struct buf
*bp
, vm_ooffset_t off
, int pageno
, vm_page_t m
)
3060 vm_ooffset_t soff
, eoff
;
3063 * Start and end offsets in buffer. eoff - soff may not cross a
3064 * page boundry or cross the end of the buffer. The end of the
3065 * buffer, in this case, is our file EOF, not the allocation size
3069 eoff
= (off
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
;
3070 if (eoff
> bp
->b_loffset
+ bp
->b_bcount
)
3071 eoff
= bp
->b_loffset
+ bp
->b_bcount
;
3074 * Set valid range. This is typically the entire buffer and thus the
3078 vm_page_set_validclean(
3080 (vm_offset_t
) (soff
& PAGE_MASK
),
3081 (vm_offset_t
) (eoff
- soff
)
3089 * This routine is called before a device strategy routine.
3090 * It is used to tell the VM system that paging I/O is in
3091 * progress, and treat the pages associated with the buffer
3092 * almost as being PG_BUSY. Also the object 'paging_in_progress'
3093 * flag is handled to make sure that the object doesn't become
3096 * Since I/O has not been initiated yet, certain buffer flags
3097 * such as B_ERROR or B_INVAL may be in an inconsistant state
3098 * and should be ignored.
3101 vfs_busy_pages(struct vnode
*vp
, struct buf
*bp
)
3104 struct lwp
*lp
= curthread
->td_lwp
;
3107 * The buffer's I/O command must already be set. If reading,
3108 * B_CACHE must be 0 (double check against callers only doing
3109 * I/O when B_CACHE is 0).
3111 KKASSERT(bp
->b_cmd
!= BUF_CMD_DONE
);
3112 KKASSERT(bp
->b_cmd
== BUF_CMD_WRITE
|| (bp
->b_flags
& B_CACHE
) == 0);
3114 if (bp
->b_flags
& B_VMIO
) {
3119 foff
= bp
->b_loffset
;
3120 KASSERT(bp
->b_loffset
!= NOOFFSET
,
3121 ("vfs_busy_pages: no buffer offset"));
3125 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3126 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
3127 if (vm_page_sleep_busy(m
, FALSE
, "vbpage"))
3132 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3133 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
3135 vm_page_flag_clear(m
, PG_ZERO
);
3136 if ((bp
->b_flags
& B_CLUSTER
) == 0) {
3137 vm_object_pip_add(obj
, 1);
3138 vm_page_io_start(m
);
3142 * When readying a vnode-backed buffer for a write
3143 * we must zero-fill any invalid portions of the
3146 * When readying a vnode-backed buffer for a read
3147 * we must replace any dirty pages with a bogus
3148 * page so we do not destroy dirty data when
3149 * filling in gaps. Dirty pages might not
3150 * necessarily be marked dirty yet, so use m->valid
3151 * as a reasonable test.
3153 * Bogus page replacement is, uh, bogus. We need
3154 * to find a better way.
3156 vm_page_protect(m
, VM_PROT_NONE
);
3157 if (bp
->b_cmd
== BUF_CMD_WRITE
) {
3158 vfs_page_set_valid(bp
, foff
, i
, m
);
3159 } else if (m
->valid
== VM_PAGE_BITS_ALL
) {
3160 bp
->b_xio
.xio_pages
[i
] = bogus_page
;
3163 foff
= (foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
;
3166 pmap_qenter(trunc_page((vm_offset_t
)bp
->b_data
),
3167 bp
->b_xio
.xio_pages
, bp
->b_xio
.xio_npages
);
3171 * This is the easiest place to put the process accounting for the I/O
3175 if (bp
->b_cmd
== BUF_CMD_READ
)
3176 lp
->lwp_ru
.ru_inblock
++;
3178 lp
->lwp_ru
.ru_oublock
++;
3185 * Tell the VM system that the pages associated with this buffer
3186 * are clean. This is used for delayed writes where the data is
3187 * going to go to disk eventually without additional VM intevention.
3189 * Note that while we only really need to clean through to b_bcount, we
3190 * just go ahead and clean through to b_bufsize.
3193 vfs_clean_pages(struct buf
*bp
)
3197 if (bp
->b_flags
& B_VMIO
) {
3200 foff
= bp
->b_loffset
;
3201 KASSERT(foff
!= NOOFFSET
, ("vfs_clean_pages: no buffer offset"));
3202 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3203 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
3204 vm_ooffset_t noff
= (foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
;
3205 vm_ooffset_t eoff
= noff
;
3207 if (eoff
> bp
->b_loffset
+ bp
->b_bufsize
)
3208 eoff
= bp
->b_loffset
+ bp
->b_bufsize
;
3209 vfs_page_set_valid(bp
, foff
, i
, m
);
3210 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3217 * vfs_bio_set_validclean:
3219 * Set the range within the buffer to valid and clean. The range is
3220 * relative to the beginning of the buffer, b_loffset. Note that
3221 * b_loffset itself may be offset from the beginning of the first page.
3225 vfs_bio_set_validclean(struct buf
*bp
, int base
, int size
)
3227 if (bp
->b_flags
& B_VMIO
) {
3232 * Fixup base to be relative to beginning of first page.
3233 * Set initial n to be the maximum number of bytes in the
3234 * first page that can be validated.
3237 base
+= (bp
->b_loffset
& PAGE_MASK
);
3238 n
= PAGE_SIZE
- (base
& PAGE_MASK
);
3240 for (i
= base
/ PAGE_SIZE
; size
> 0 && i
< bp
->b_xio
.xio_npages
; ++i
) {
3241 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
3246 vm_page_set_validclean(m
, base
& PAGE_MASK
, n
);
3257 * Clear a buffer. This routine essentially fakes an I/O, so we need
3258 * to clear B_ERROR and B_INVAL.
3260 * Note that while we only theoretically need to clear through b_bcount,
3261 * we go ahead and clear through b_bufsize.
3265 vfs_bio_clrbuf(struct buf
*bp
)
3269 if ((bp
->b_flags
& (B_VMIO
| B_MALLOC
)) == B_VMIO
) {
3270 bp
->b_flags
&= ~(B_INVAL
|B_ERROR
);
3271 if ((bp
->b_xio
.xio_npages
== 1) && (bp
->b_bufsize
< PAGE_SIZE
) &&
3272 (bp
->b_loffset
& PAGE_MASK
) == 0) {
3273 mask
= (1 << (bp
->b_bufsize
/ DEV_BSIZE
)) - 1;
3274 if ((bp
->b_xio
.xio_pages
[0]->valid
& mask
) == mask
) {
3278 if (((bp
->b_xio
.xio_pages
[0]->flags
& PG_ZERO
) == 0) &&
3279 ((bp
->b_xio
.xio_pages
[0]->valid
& mask
) == 0)) {
3280 bzero(bp
->b_data
, bp
->b_bufsize
);
3281 bp
->b_xio
.xio_pages
[0]->valid
|= mask
;
3286 ea
= sa
= bp
->b_data
;
3287 for(i
=0;i
<bp
->b_xio
.xio_npages
;i
++,sa
=ea
) {
3288 int j
= ((vm_offset_t
)sa
& PAGE_MASK
) / DEV_BSIZE
;
3289 ea
= (caddr_t
)trunc_page((vm_offset_t
)sa
+ PAGE_SIZE
);
3290 ea
= (caddr_t
)(vm_offset_t
)ulmin(
3291 (u_long
)(vm_offset_t
)ea
,
3292 (u_long
)(vm_offset_t
)bp
->b_data
+ bp
->b_bufsize
);
3293 mask
= ((1 << ((ea
- sa
) / DEV_BSIZE
)) - 1) << j
;
3294 if ((bp
->b_xio
.xio_pages
[i
]->valid
& mask
) == mask
)
3296 if ((bp
->b_xio
.xio_pages
[i
]->valid
& mask
) == 0) {
3297 if ((bp
->b_xio
.xio_pages
[i
]->flags
& PG_ZERO
) == 0) {
3301 for (; sa
< ea
; sa
+= DEV_BSIZE
, j
++) {
3302 if (((bp
->b_xio
.xio_pages
[i
]->flags
& PG_ZERO
) == 0) &&
3303 (bp
->b_xio
.xio_pages
[i
]->valid
& (1<<j
)) == 0)
3304 bzero(sa
, DEV_BSIZE
);
3307 bp
->b_xio
.xio_pages
[i
]->valid
|= mask
;
3308 vm_page_flag_clear(bp
->b_xio
.xio_pages
[i
], PG_ZERO
);
3317 * vm_hold_load_pages:
3319 * Load pages into the buffer's address space. The pages are
3320 * allocated from the kernel object in order to reduce interference
3321 * with the any VM paging I/O activity. The range of loaded
3322 * pages will be wired.
3324 * If a page cannot be allocated, the 'pagedaemon' is woken up to
3325 * retrieve the full range (to - from) of pages.
3329 vm_hold_load_pages(struct buf
*bp
, vm_offset_t from
, vm_offset_t to
)
3335 to
= round_page(to
);
3336 from
= round_page(from
);
3337 index
= (from
- trunc_page((vm_offset_t
)bp
->b_data
)) >> PAGE_SHIFT
;
3339 for (pg
= from
; pg
< to
; pg
+= PAGE_SIZE
, index
++) {
3344 * Note: must allocate system pages since blocking here
3345 * could intefere with paging I/O, no matter which
3348 p
= vm_page_alloc(&kernel_object
,
3350 VM_ALLOC_NORMAL
| VM_ALLOC_SYSTEM
);
3352 vm_pageout_deficit
+= (to
- from
) >> PAGE_SHIFT
;
3357 p
->valid
= VM_PAGE_BITS_ALL
;
3358 vm_page_flag_clear(p
, PG_ZERO
);
3359 pmap_kenter(pg
, VM_PAGE_TO_PHYS(p
));
3360 bp
->b_xio
.xio_pages
[index
] = p
;
3363 bp
->b_xio
.xio_npages
= index
;
3367 * vm_hold_free_pages:
3369 * Return pages associated with the buffer back to the VM system.
3371 * The range of pages underlying the buffer's address space will
3372 * be unmapped and un-wired.
3375 vm_hold_free_pages(struct buf
*bp
, vm_offset_t from
, vm_offset_t to
)
3379 int index
, newnpages
;
3381 from
= round_page(from
);
3382 to
= round_page(to
);
3383 newnpages
= index
= (from
- trunc_page((vm_offset_t
)bp
->b_data
)) >> PAGE_SHIFT
;
3385 for (pg
= from
; pg
< to
; pg
+= PAGE_SIZE
, index
++) {
3386 p
= bp
->b_xio
.xio_pages
[index
];
3387 if (p
&& (index
< bp
->b_xio
.xio_npages
)) {
3389 kprintf("vm_hold_free_pages: doffset: %lld, loffset: %lld\n",
3390 bp
->b_bio2
.bio_offset
, bp
->b_loffset
);
3392 bp
->b_xio
.xio_pages
[index
] = NULL
;
3395 vm_page_unwire(p
, 0);
3399 bp
->b_xio
.xio_npages
= newnpages
;
3405 * Map a user buffer into KVM via a pbuf. On return the buffer's
3406 * b_data, b_bufsize, and b_bcount will be set, and its XIO page array
3410 vmapbuf(struct buf
*bp
, caddr_t udata
, int bytes
)
3421 * bp had better have a command and it better be a pbuf.
3423 KKASSERT(bp
->b_cmd
!= BUF_CMD_DONE
);
3424 KKASSERT(bp
->b_flags
& B_PAGING
);
3430 * Map the user data into KVM. Mappings have to be page-aligned.
3432 addr
= (caddr_t
)trunc_page((vm_offset_t
)udata
);
3435 vmprot
= VM_PROT_READ
;
3436 if (bp
->b_cmd
== BUF_CMD_READ
)
3437 vmprot
|= VM_PROT_WRITE
;
3439 while (addr
< udata
+ bytes
) {
3441 * Do the vm_fault if needed; do the copy-on-write thing
3442 * when reading stuff off device into memory.
3444 * vm_fault_page*() returns a held VM page.
3446 va
= (addr
>= udata
) ? (vm_offset_t
)addr
: (vm_offset_t
)udata
;
3447 va
= trunc_page(va
);
3449 m
= vm_fault_page_quick(va
, vmprot
, &error
);
3451 for (i
= 0; i
< pidx
; ++i
) {
3452 vm_page_unhold(bp
->b_xio
.xio_pages
[i
]);
3453 bp
->b_xio
.xio_pages
[i
] = NULL
;
3457 bp
->b_xio
.xio_pages
[pidx
] = m
;
3463 * Map the page array and set the buffer fields to point to
3464 * the mapped data buffer.
3466 if (pidx
> btoc(MAXPHYS
))
3467 panic("vmapbuf: mapped more than MAXPHYS");
3468 pmap_qenter((vm_offset_t
)bp
->b_kvabase
, bp
->b_xio
.xio_pages
, pidx
);
3470 bp
->b_xio
.xio_npages
= pidx
;
3471 bp
->b_data
= bp
->b_kvabase
+ ((int)(intptr_t)udata
& PAGE_MASK
);
3472 bp
->b_bcount
= bytes
;
3473 bp
->b_bufsize
= bytes
;
3480 * Free the io map PTEs associated with this IO operation.
3481 * We also invalidate the TLB entries and restore the original b_addr.
3484 vunmapbuf(struct buf
*bp
)
3489 KKASSERT(bp
->b_flags
& B_PAGING
);
3491 npages
= bp
->b_xio
.xio_npages
;
3492 pmap_qremove(trunc_page((vm_offset_t
)bp
->b_data
), npages
);
3493 for (pidx
= 0; pidx
< npages
; ++pidx
) {
3494 vm_page_unhold(bp
->b_xio
.xio_pages
[pidx
]);
3495 bp
->b_xio
.xio_pages
[pidx
] = NULL
;
3497 bp
->b_xio
.xio_npages
= 0;
3498 bp
->b_data
= bp
->b_kvabase
;
3502 * Scan all buffers in the system and issue the callback.
3505 scan_all_buffers(int (*callback
)(struct buf
*, void *), void *info
)
3511 for (n
= 0; n
< nbuf
; ++n
) {
3512 if ((error
= callback(&buf
[n
], info
)) < 0) {
3522 * print out statistics from the current status of the buffer pool
3523 * this can be toggeled by the system control option debug.syncprt
3532 int counts
[(MAXBSIZE
/ PAGE_SIZE
) + 1];
3533 static char *bname
[3] = { "LOCKED", "LRU", "AGE" };
3535 for (dp
= bufqueues
, i
= 0; dp
< &bufqueues
[3]; dp
++, i
++) {
3537 for (j
= 0; j
<= MAXBSIZE
/PAGE_SIZE
; j
++)
3540 TAILQ_FOREACH(bp
, dp
, b_freelist
) {
3541 counts
[bp
->b_bufsize
/PAGE_SIZE
]++;
3545 kprintf("%s: total-%d", bname
[i
], count
);
3546 for (j
= 0; j
<= MAXBSIZE
/PAGE_SIZE
; j
++)
3548 kprintf(", %d-%d", j
* PAGE_SIZE
, counts
[j
]);
3556 DB_SHOW_COMMAND(buffer
, db_show_buffer
)
3559 struct buf
*bp
= (struct buf
*)addr
;
3562 db_printf("usage: show buffer <addr>\n");
3566 db_printf("b_flags = 0x%b\n", (u_int
)bp
->b_flags
, PRINT_BUF_FLAGS
);
3567 db_printf("b_cmd = %d\n", bp
->b_cmd
);
3568 db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
3569 "b_resid = %d\n, b_data = %p, "
3570 "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
3571 bp
->b_error
, bp
->b_bufsize
, bp
->b_bcount
, bp
->b_resid
,
3572 bp
->b_data
, bp
->b_bio2
.bio_offset
, (bp
->b_bio2
.bio_next
? bp
->b_bio2
.bio_next
->bio_offset
: (off_t
)-1));
3573 if (bp
->b_xio
.xio_npages
) {
3575 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
3576 bp
->b_xio
.xio_npages
);
3577 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3579 m
= bp
->b_xio
.xio_pages
[i
];
3580 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m
->object
,
3581 (u_long
)m
->pindex
, (u_long
)VM_PAGE_TO_PHYS(m
));
3582 if ((i
+ 1) < bp
->b_xio
.xio_npages
)