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.95 2007/11/07 00:46:36 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>
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 buf
*buf
; /* buffer header pool */
85 static void vm_hold_free_pages(struct buf
*bp
, vm_offset_t from
,
87 static void vm_hold_load_pages(struct buf
*bp
, vm_offset_t from
,
89 static void vfs_page_set_valid(struct buf
*bp
, vm_ooffset_t off
,
90 int pageno
, vm_page_t m
);
91 static void vfs_clean_pages(struct buf
*bp
);
92 static void vfs_setdirty(struct buf
*bp
);
93 static void vfs_vmio_release(struct buf
*bp
);
94 static int flushbufqueues(void);
96 static void buf_daemon (void);
98 * bogus page -- for I/O to/from partially complete buffers
99 * this is a temporary solution to the problem, but it is not
100 * really that bad. it would be better to split the buffer
101 * for input in the case of buffers partially already in memory,
102 * but the code is intricate enough already.
104 vm_page_t bogus_page
;
108 * These are all static, but make the ones we export globals so we do
109 * not need to use compiler magic.
111 int bufspace
, maxbufspace
,
112 bufmallocspace
, maxbufmallocspace
, lobufspace
, hibufspace
;
113 static int bufreusecnt
, bufdefragcnt
, buffreekvacnt
;
114 static int lorunningspace
, hirunningspace
, runningbufreq
;
115 int numdirtybuffers
, lodirtybuffers
, hidirtybuffers
;
116 static int numfreebuffers
, lofreebuffers
, hifreebuffers
;
117 static int getnewbufcalls
;
118 static int getnewbufrestarts
;
120 static int needsbuffer
; /* locked by needsbuffer_spin */
121 static int bd_request
; /* locked by needsbuffer_spin */
122 static struct spinlock needsbuffer_spin
;
125 * Sysctls for operational control of the buffer cache.
127 SYSCTL_INT(_vfs
, OID_AUTO
, lodirtybuffers
, CTLFLAG_RW
, &lodirtybuffers
, 0,
128 "Number of dirty buffers to flush before bufdaemon becomes inactive");
129 SYSCTL_INT(_vfs
, OID_AUTO
, hidirtybuffers
, CTLFLAG_RW
, &hidirtybuffers
, 0,
130 "High watermark used to trigger explicit flushing of dirty buffers");
131 SYSCTL_INT(_vfs
, OID_AUTO
, lofreebuffers
, CTLFLAG_RW
, &lofreebuffers
, 0,
132 "Low watermark for special reserve in low-memory situations");
133 SYSCTL_INT(_vfs
, OID_AUTO
, hifreebuffers
, CTLFLAG_RW
, &hifreebuffers
, 0,
134 "High watermark for special reserve in low-memory situations");
135 SYSCTL_INT(_vfs
, OID_AUTO
, lorunningspace
, CTLFLAG_RW
, &lorunningspace
, 0,
136 "Minimum amount of buffer space required for active I/O");
137 SYSCTL_INT(_vfs
, OID_AUTO
, hirunningspace
, CTLFLAG_RW
, &hirunningspace
, 0,
138 "Maximum amount of buffer space to usable for active I/O");
140 * Sysctls determining current state of the buffer cache.
142 SYSCTL_INT(_vfs
, OID_AUTO
, numdirtybuffers
, CTLFLAG_RD
, &numdirtybuffers
, 0,
143 "Pending number of dirty buffers");
144 SYSCTL_INT(_vfs
, OID_AUTO
, numfreebuffers
, CTLFLAG_RD
, &numfreebuffers
, 0,
145 "Number of free buffers on the buffer cache free list");
146 SYSCTL_INT(_vfs
, OID_AUTO
, runningbufspace
, CTLFLAG_RD
, &runningbufspace
, 0,
147 "I/O bytes currently in progress due to asynchronous writes");
148 SYSCTL_INT(_vfs
, OID_AUTO
, maxbufspace
, CTLFLAG_RD
, &maxbufspace
, 0,
149 "Hard limit on maximum amount of memory usable for buffer space");
150 SYSCTL_INT(_vfs
, OID_AUTO
, hibufspace
, CTLFLAG_RD
, &hibufspace
, 0,
151 "Soft limit on maximum amount of memory usable for buffer space");
152 SYSCTL_INT(_vfs
, OID_AUTO
, lobufspace
, CTLFLAG_RD
, &lobufspace
, 0,
153 "Minimum amount of memory to reserve for system buffer space");
154 SYSCTL_INT(_vfs
, OID_AUTO
, bufspace
, CTLFLAG_RD
, &bufspace
, 0,
155 "Amount of memory available for buffers");
156 SYSCTL_INT(_vfs
, OID_AUTO
, maxmallocbufspace
, CTLFLAG_RD
, &maxbufmallocspace
,
157 0, "Maximum amount of memory reserved for buffers using malloc");
158 SYSCTL_INT(_vfs
, OID_AUTO
, bufmallocspace
, CTLFLAG_RD
, &bufmallocspace
, 0,
159 "Amount of memory left for buffers using malloc-scheme");
160 SYSCTL_INT(_vfs
, OID_AUTO
, getnewbufcalls
, CTLFLAG_RD
, &getnewbufcalls
, 0,
161 "New buffer header acquisition requests");
162 SYSCTL_INT(_vfs
, OID_AUTO
, getnewbufrestarts
, CTLFLAG_RD
, &getnewbufrestarts
,
163 0, "New buffer header acquisition restarts");
164 SYSCTL_INT(_vfs
, OID_AUTO
, bufdefragcnt
, CTLFLAG_RD
, &bufdefragcnt
, 0,
165 "Buffer acquisition restarts due to fragmented buffer map");
166 SYSCTL_INT(_vfs
, OID_AUTO
, buffreekvacnt
, CTLFLAG_RD
, &buffreekvacnt
, 0,
167 "Amount of time KVA space was deallocated in an arbitrary buffer");
168 SYSCTL_INT(_vfs
, OID_AUTO
, bufreusecnt
, CTLFLAG_RD
, &bufreusecnt
, 0,
169 "Amount of time buffer re-use operations were successful");
170 SYSCTL_INT(_debug_sizeof
, OID_AUTO
, buf
, CTLFLAG_RD
, 0, sizeof(struct buf
),
171 "sizeof(struct buf)");
173 char *buf_wmesg
= BUF_WMESG
;
175 extern int vm_swap_size
;
177 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
178 #define VFS_BIO_NEED_DIRTYFLUSH 0x02 /* waiting for dirty buffer flush */
179 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
180 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
185 * If someone is blocked due to there being too many dirty buffers,
186 * and numdirtybuffers is now reasonable, wake them up.
190 numdirtywakeup(int level
)
192 if (numdirtybuffers
<= level
) {
193 if (needsbuffer
& VFS_BIO_NEED_DIRTYFLUSH
) {
194 spin_lock_wr(&needsbuffer_spin
);
195 needsbuffer
&= ~VFS_BIO_NEED_DIRTYFLUSH
;
196 spin_unlock_wr(&needsbuffer_spin
);
197 wakeup(&needsbuffer
);
205 * Called when buffer space is potentially available for recovery.
206 * getnewbuf() will block on this flag when it is unable to free
207 * sufficient buffer space. Buffer space becomes recoverable when
208 * bp's get placed back in the queues.
215 * If someone is waiting for BUF space, wake them up. Even
216 * though we haven't freed the kva space yet, the waiting
217 * process will be able to now.
219 if (needsbuffer
& VFS_BIO_NEED_BUFSPACE
) {
220 spin_lock_wr(&needsbuffer_spin
);
221 needsbuffer
&= ~VFS_BIO_NEED_BUFSPACE
;
222 spin_unlock_wr(&needsbuffer_spin
);
223 wakeup(&needsbuffer
);
230 * Accounting for I/O in progress.
234 runningbufwakeup(struct buf
*bp
)
236 if (bp
->b_runningbufspace
) {
237 runningbufspace
-= bp
->b_runningbufspace
;
238 bp
->b_runningbufspace
= 0;
239 if (runningbufreq
&& runningbufspace
<= lorunningspace
) {
241 wakeup(&runningbufreq
);
249 * Called when a buffer has been added to one of the free queues to
250 * account for the buffer and to wakeup anyone waiting for free buffers.
251 * This typically occurs when large amounts of metadata are being handled
252 * by the buffer cache ( else buffer space runs out first, usually ).
260 spin_lock_wr(&needsbuffer_spin
);
261 needsbuffer
&= ~VFS_BIO_NEED_ANY
;
262 if (numfreebuffers
>= hifreebuffers
)
263 needsbuffer
&= ~VFS_BIO_NEED_FREE
;
264 spin_unlock_wr(&needsbuffer_spin
);
265 wakeup(&needsbuffer
);
270 * waitrunningbufspace()
272 * runningbufspace is a measure of the amount of I/O currently
273 * running. This routine is used in async-write situations to
274 * prevent creating huge backups of pending writes to a device.
275 * Only asynchronous writes are governed by this function.
277 * Reads will adjust runningbufspace, but will not block based on it.
278 * The read load has a side effect of reducing the allowed write load.
280 * This does NOT turn an async write into a sync write. It waits
281 * for earlier writes to complete and generally returns before the
282 * caller's write has reached the device.
285 waitrunningbufspace(void)
287 if (runningbufspace
> hirunningspace
) {
289 while (runningbufspace
> hirunningspace
) {
291 tsleep(&runningbufreq
, 0, "wdrain", 0);
298 * vfs_buf_test_cache:
300 * Called when a buffer is extended. This function clears the B_CACHE
301 * bit if the newly extended portion of the buffer does not contain
306 vfs_buf_test_cache(struct buf
*bp
,
307 vm_ooffset_t foff
, vm_offset_t off
, vm_offset_t size
,
310 if (bp
->b_flags
& B_CACHE
) {
311 int base
= (foff
+ off
) & PAGE_MASK
;
312 if (vm_page_is_valid(m
, base
, size
) == 0)
313 bp
->b_flags
&= ~B_CACHE
;
320 * Wake up the buffer daemon if the number of outstanding dirty buffers
321 * is above specified threshold 'dirtybuflevel'.
323 * The buffer daemon is explicitly woken up when (a) the pending number
324 * of dirty buffers exceeds the recovery and stall mid-point value,
325 * (b) during bwillwrite() or (c) buf freelist was exhausted.
329 bd_wakeup(int dirtybuflevel
)
331 if (bd_request
== 0 && numdirtybuffers
>= dirtybuflevel
) {
332 spin_lock_wr(&needsbuffer_spin
);
334 spin_unlock_wr(&needsbuffer_spin
);
342 * Speed up the buffer cache flushing process.
355 * Load time initialisation of the buffer cache, called from machine
356 * dependant initialization code.
362 vm_offset_t bogus_offset
;
365 spin_init(&needsbuffer_spin
);
367 /* next, make a null set of free lists */
368 for (i
= 0; i
< BUFFER_QUEUES
; i
++)
369 TAILQ_INIT(&bufqueues
[i
]);
371 /* finally, initialize each buffer header and stick on empty q */
372 for (i
= 0; i
< nbuf
; i
++) {
374 bzero(bp
, sizeof *bp
);
375 bp
->b_flags
= B_INVAL
; /* we're just an empty header */
376 bp
->b_cmd
= BUF_CMD_DONE
;
377 bp
->b_qindex
= BQUEUE_EMPTY
;
379 xio_init(&bp
->b_xio
);
382 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_EMPTY
], bp
, b_freelist
);
386 * maxbufspace is the absolute maximum amount of buffer space we are
387 * allowed to reserve in KVM and in real terms. The absolute maximum
388 * is nominally used by buf_daemon. hibufspace is the nominal maximum
389 * used by most other processes. The differential is required to
390 * ensure that buf_daemon is able to run when other processes might
391 * be blocked waiting for buffer space.
393 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
394 * this may result in KVM fragmentation which is not handled optimally
397 maxbufspace
= nbuf
* BKVASIZE
;
398 hibufspace
= imax(3 * maxbufspace
/ 4, maxbufspace
- MAXBSIZE
* 10);
399 lobufspace
= hibufspace
- MAXBSIZE
;
401 lorunningspace
= 512 * 1024;
402 hirunningspace
= 1024 * 1024;
405 * Limit the amount of malloc memory since it is wired permanently into
406 * the kernel space. Even though this is accounted for in the buffer
407 * allocation, we don't want the malloced region to grow uncontrolled.
408 * The malloc scheme improves memory utilization significantly on average
409 * (small) directories.
411 maxbufmallocspace
= hibufspace
/ 20;
414 * Reduce the chance of a deadlock occuring by limiting the number
415 * of delayed-write dirty buffers we allow to stack up.
417 hidirtybuffers
= nbuf
/ 4 + 20;
420 * To support extreme low-memory systems, make sure hidirtybuffers cannot
421 * eat up all available buffer space. This occurs when our minimum cannot
422 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
423 * BKVASIZE'd (8K) buffers.
425 while (hidirtybuffers
* BKVASIZE
> 3 * hibufspace
/ 4) {
426 hidirtybuffers
>>= 1;
428 lodirtybuffers
= hidirtybuffers
/ 2;
431 * Try to keep the number of free buffers in the specified range,
432 * and give special processes (e.g. like buf_daemon) access to an
435 lofreebuffers
= nbuf
/ 18 + 5;
436 hifreebuffers
= 2 * lofreebuffers
;
437 numfreebuffers
= nbuf
;
440 * Maximum number of async ops initiated per buf_daemon loop. This is
441 * somewhat of a hack at the moment, we really need to limit ourselves
442 * based on the number of bytes of I/O in-transit that were initiated
446 bogus_offset
= kmem_alloc_pageable(&kernel_map
, PAGE_SIZE
);
447 bogus_page
= vm_page_alloc(&kernel_object
,
448 (bogus_offset
>> PAGE_SHIFT
),
450 vmstats
.v_wire_count
++;
455 * Initialize the embedded bio structures
458 initbufbio(struct buf
*bp
)
460 bp
->b_bio1
.bio_buf
= bp
;
461 bp
->b_bio1
.bio_prev
= NULL
;
462 bp
->b_bio1
.bio_offset
= NOOFFSET
;
463 bp
->b_bio1
.bio_next
= &bp
->b_bio2
;
464 bp
->b_bio1
.bio_done
= NULL
;
466 bp
->b_bio2
.bio_buf
= bp
;
467 bp
->b_bio2
.bio_prev
= &bp
->b_bio1
;
468 bp
->b_bio2
.bio_offset
= NOOFFSET
;
469 bp
->b_bio2
.bio_next
= NULL
;
470 bp
->b_bio2
.bio_done
= NULL
;
474 * Reinitialize the embedded bio structures as well as any additional
475 * translation cache layers.
478 reinitbufbio(struct buf
*bp
)
482 for (bio
= &bp
->b_bio1
; bio
; bio
= bio
->bio_next
) {
483 bio
->bio_done
= NULL
;
484 bio
->bio_offset
= NOOFFSET
;
489 * Push another BIO layer onto an existing BIO and return it. The new
490 * BIO layer may already exist, holding cached translation data.
493 push_bio(struct bio
*bio
)
497 if ((nbio
= bio
->bio_next
) == NULL
) {
498 int index
= bio
- &bio
->bio_buf
->b_bio_array
[0];
499 if (index
>= NBUF_BIO
- 1) {
500 panic("push_bio: too many layers bp %p\n",
503 nbio
= &bio
->bio_buf
->b_bio_array
[index
+ 1];
504 bio
->bio_next
= nbio
;
505 nbio
->bio_prev
= bio
;
506 nbio
->bio_buf
= bio
->bio_buf
;
507 nbio
->bio_offset
= NOOFFSET
;
508 nbio
->bio_done
= NULL
;
509 nbio
->bio_next
= NULL
;
511 KKASSERT(nbio
->bio_done
== NULL
);
516 pop_bio(struct bio
*bio
)
522 clearbiocache(struct bio
*bio
)
525 bio
->bio_offset
= NOOFFSET
;
533 * Free the KVA allocation for buffer 'bp'.
535 * Must be called from a critical section as this is the only locking for
538 * Since this call frees up buffer space, we call bufspacewakeup().
541 bfreekva(struct buf
*bp
)
547 count
= vm_map_entry_reserve(MAP_RESERVE_COUNT
);
548 vm_map_lock(&buffer_map
);
549 bufspace
-= bp
->b_kvasize
;
550 vm_map_delete(&buffer_map
,
551 (vm_offset_t
) bp
->b_kvabase
,
552 (vm_offset_t
) bp
->b_kvabase
+ bp
->b_kvasize
,
555 vm_map_unlock(&buffer_map
);
556 vm_map_entry_release(count
);
565 * Remove the buffer from the appropriate free list.
568 bremfree(struct buf
*bp
)
573 old_qindex
= bp
->b_qindex
;
575 if (bp
->b_qindex
!= BQUEUE_NONE
) {
576 KASSERT(BUF_REFCNTNB(bp
) == 1,
577 ("bremfree: bp %p not locked",bp
));
578 TAILQ_REMOVE(&bufqueues
[bp
->b_qindex
], bp
, b_freelist
);
579 bp
->b_qindex
= BQUEUE_NONE
;
581 if (BUF_REFCNTNB(bp
) <= 1)
582 panic("bremfree: removing a buffer not on a queue");
586 * Fixup numfreebuffers count. If the buffer is invalid or not
587 * delayed-write, and it was on the EMPTY, LRU, or AGE queues,
588 * the buffer was free and we must decrement numfreebuffers.
590 if ((bp
->b_flags
& B_INVAL
) || (bp
->b_flags
& B_DELWRI
) == 0) {
595 case BQUEUE_EMPTYKVA
:
609 * Get a buffer with the specified data. Look in the cache first. We
610 * must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
611 * is set, the buffer is valid and we do not have to do anything ( see
615 bread(struct vnode
*vp
, off_t loffset
, int size
, struct buf
**bpp
)
619 bp
= getblk(vp
, loffset
, size
, 0, 0);
622 /* if not found in cache, do some I/O */
623 if ((bp
->b_flags
& B_CACHE
) == 0) {
624 KASSERT(!(bp
->b_flags
& B_ASYNC
), ("bread: illegal async bp %p", bp
));
625 bp
->b_flags
&= ~(B_ERROR
| B_INVAL
);
626 bp
->b_cmd
= BUF_CMD_READ
;
627 vfs_busy_pages(vp
, bp
);
628 vn_strategy(vp
, &bp
->b_bio1
);
629 return (biowait(bp
));
637 * Operates like bread, but also starts asynchronous I/O on
638 * read-ahead blocks. We must clear B_ERROR and B_INVAL prior
639 * to initiating I/O . If B_CACHE is set, the buffer is valid
640 * and we do not have to do anything.
643 breadn(struct vnode
*vp
, off_t loffset
, int size
, off_t
*raoffset
,
644 int *rabsize
, int cnt
, struct buf
**bpp
)
646 struct buf
*bp
, *rabp
;
648 int rv
= 0, readwait
= 0;
650 *bpp
= bp
= getblk(vp
, loffset
, size
, 0, 0);
652 /* if not found in cache, do some I/O */
653 if ((bp
->b_flags
& B_CACHE
) == 0) {
654 bp
->b_flags
&= ~(B_ERROR
| B_INVAL
);
655 bp
->b_cmd
= BUF_CMD_READ
;
656 vfs_busy_pages(vp
, bp
);
657 vn_strategy(vp
, &bp
->b_bio1
);
661 for (i
= 0; i
< cnt
; i
++, raoffset
++, rabsize
++) {
662 if (inmem(vp
, *raoffset
))
664 rabp
= getblk(vp
, *raoffset
, *rabsize
, 0, 0);
666 if ((rabp
->b_flags
& B_CACHE
) == 0) {
667 rabp
->b_flags
|= B_ASYNC
;
668 rabp
->b_flags
&= ~(B_ERROR
| B_INVAL
);
669 rabp
->b_cmd
= BUF_CMD_READ
;
670 vfs_busy_pages(vp
, rabp
);
672 vn_strategy(vp
, &rabp
->b_bio1
);
687 * Write, release buffer on completion. (Done by iodone
688 * if async). Do not bother writing anything if the buffer
691 * Note that we set B_CACHE here, indicating that buffer is
692 * fully valid and thus cacheable. This is true even of NFS
693 * now so we set it generally. This could be set either here
694 * or in biodone() since the I/O is synchronous. We put it
698 bwrite(struct buf
*bp
)
702 if (bp
->b_flags
& B_INVAL
) {
707 oldflags
= bp
->b_flags
;
709 if (BUF_REFCNTNB(bp
) == 0)
710 panic("bwrite: buffer is not busy???");
713 /* Mark the buffer clean */
716 bp
->b_flags
&= ~B_ERROR
;
717 bp
->b_flags
|= B_CACHE
;
718 bp
->b_cmd
= BUF_CMD_WRITE
;
719 vfs_busy_pages(bp
->b_vp
, bp
);
722 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
723 * valid for vnode-backed buffers.
725 bp
->b_runningbufspace
= bp
->b_bufsize
;
726 runningbufspace
+= bp
->b_runningbufspace
;
729 if (oldflags
& B_ASYNC
)
731 vn_strategy(bp
->b_vp
, &bp
->b_bio1
);
733 if ((oldflags
& B_ASYNC
) == 0) {
734 int rtval
= biowait(bp
);
737 } else if ((oldflags
& B_NOWDRAIN
) == 0) {
739 * don't allow the async write to saturate the I/O
740 * system. Deadlocks can occur only if a device strategy
741 * routine (like in VN) turns around and issues another
742 * high-level write, in which case B_NOWDRAIN is expected
743 * to be set. Otherwise we will not deadlock here because
744 * we are blocking waiting for I/O that is already in-progress
747 waitrunningbufspace();
756 * Delayed write. (Buffer is marked dirty). Do not bother writing
757 * anything if the buffer is marked invalid.
759 * Note that since the buffer must be completely valid, we can safely
760 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
761 * biodone() in order to prevent getblk from writing the buffer
765 bdwrite(struct buf
*bp
)
767 if (BUF_REFCNTNB(bp
) == 0)
768 panic("bdwrite: buffer is not busy");
770 if (bp
->b_flags
& B_INVAL
) {
777 * Set B_CACHE, indicating that the buffer is fully valid. This is
778 * true even of NFS now.
780 bp
->b_flags
|= B_CACHE
;
783 * This bmap keeps the system from needing to do the bmap later,
784 * perhaps when the system is attempting to do a sync. Since it
785 * is likely that the indirect block -- or whatever other datastructure
786 * that the filesystem needs is still in memory now, it is a good
787 * thing to do this. Note also, that if the pageout daemon is
788 * requesting a sync -- there might not be enough memory to do
789 * the bmap then... So, this is important to do.
791 if (bp
->b_bio2
.bio_offset
== NOOFFSET
) {
792 VOP_BMAP(bp
->b_vp
, bp
->b_loffset
, &bp
->b_bio2
.bio_offset
,
797 * Set the *dirty* buffer range based upon the VM system dirty pages.
802 * We need to do this here to satisfy the vnode_pager and the
803 * pageout daemon, so that it thinks that the pages have been
804 * "cleaned". Note that since the pages are in a delayed write
805 * buffer -- the VFS layer "will" see that the pages get written
806 * out on the next sync, or perhaps the cluster will be completed.
812 * Wakeup the buffer flushing daemon if we have a lot of dirty
813 * buffers (midpoint between our recovery point and our stall
816 bd_wakeup((lodirtybuffers
+ hidirtybuffers
) / 2);
819 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
820 * due to the softdep code.
827 * Turn buffer into delayed write request by marking it B_DELWRI.
828 * B_RELBUF and B_NOCACHE must be cleared.
830 * We reassign the buffer to itself to properly update it in the
833 * Since the buffer is not on a queue, we do not update the
834 * numfreebuffers count.
836 * Must be called from a critical section.
837 * The buffer must be on BQUEUE_NONE.
840 bdirty(struct buf
*bp
)
842 KASSERT(bp
->b_qindex
== BQUEUE_NONE
, ("bdirty: buffer %p still on queue %d", bp
, bp
->b_qindex
));
843 if (bp
->b_flags
& B_NOCACHE
) {
844 kprintf("bdirty: clearing B_NOCACHE on buf %p\n", bp
);
845 bp
->b_flags
&= ~B_NOCACHE
;
847 if (bp
->b_flags
& B_INVAL
) {
848 kprintf("bdirty: warning, dirtying invalid buffer %p\n", bp
);
850 bp
->b_flags
&= ~B_RELBUF
;
852 if ((bp
->b_flags
& B_DELWRI
) == 0) {
853 bp
->b_flags
|= B_DELWRI
;
856 bd_wakeup((lodirtybuffers
+ hidirtybuffers
) / 2);
863 * Clear B_DELWRI for buffer.
865 * Since the buffer is not on a queue, we do not update the numfreebuffers
868 * Must be called from a critical section.
870 * The buffer is typically on BQUEUE_NONE but there is one case in
871 * brelse() that calls this function after placing the buffer on
876 bundirty(struct buf
*bp
)
878 if (bp
->b_flags
& B_DELWRI
) {
879 bp
->b_flags
&= ~B_DELWRI
;
882 numdirtywakeup(lodirtybuffers
);
885 * Since it is now being written, we can clear its deferred write flag.
887 bp
->b_flags
&= ~B_DEFERRED
;
893 * Asynchronous write. Start output on a buffer, but do not wait for
894 * it to complete. The buffer is released when the output completes.
896 * bwrite() ( or the VOP routine anyway ) is responsible for handling
897 * B_INVAL buffers. Not us.
900 bawrite(struct buf
*bp
)
902 bp
->b_flags
|= B_ASYNC
;
909 * Ordered write. Start output on a buffer, and flag it so that the
910 * device will write it in the order it was queued. The buffer is
911 * released when the output completes. bwrite() ( or the VOP routine
912 * anyway ) is responsible for handling B_INVAL buffers.
915 bowrite(struct buf
*bp
)
917 bp
->b_flags
|= B_ORDERED
| B_ASYNC
;
924 * Called prior to the locking of any vnodes when we are expecting to
925 * write. We do not want to starve the buffer cache with too many
926 * dirty buffers so we block here. By blocking prior to the locking
927 * of any vnodes we attempt to avoid the situation where a locked vnode
928 * prevents the various system daemons from flushing related buffers.
934 if (numdirtybuffers
>= hidirtybuffers
) {
935 while (numdirtybuffers
>= hidirtybuffers
) {
937 spin_lock_wr(&needsbuffer_spin
);
938 if (numdirtybuffers
>= hidirtybuffers
) {
939 needsbuffer
|= VFS_BIO_NEED_DIRTYFLUSH
;
940 msleep(&needsbuffer
, &needsbuffer_spin
, 0,
943 spin_unlock_wr(&needsbuffer_spin
);
949 * buf_dirty_count_severe:
951 * Return true if we have too many dirty buffers.
954 buf_dirty_count_severe(void)
956 return(numdirtybuffers
>= hidirtybuffers
);
962 * Release a busy buffer and, if requested, free its resources. The
963 * buffer will be stashed in the appropriate bufqueue[] allowing it
964 * to be accessed later as a cache entity or reused for other purposes.
967 brelse(struct buf
*bp
)
970 int saved_flags
= bp
->b_flags
;
973 KASSERT(!(bp
->b_flags
& (B_CLUSTER
|B_PAGING
)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp
));
978 * If B_NOCACHE is set we are being asked to destroy the buffer and
979 * its backing store. Clear B_DELWRI.
981 * B_NOCACHE is set in two cases: (1) when the caller really wants
982 * to destroy the buffer and backing store and (2) when the caller
983 * wants to destroy the buffer and backing store after a write
986 if ((bp
->b_flags
& (B_NOCACHE
|B_DELWRI
)) == (B_NOCACHE
|B_DELWRI
)) {
990 if (bp
->b_flags
& B_LOCKED
)
991 bp
->b_flags
&= ~B_ERROR
;
994 * If a write error occurs and the caller does not want to throw
995 * away the buffer, redirty the buffer. This will also clear
998 if (bp
->b_cmd
== BUF_CMD_WRITE
&&
999 (bp
->b_flags
& (B_ERROR
| B_INVAL
)) == B_ERROR
) {
1001 * Failed write, redirty. Must clear B_ERROR to prevent
1002 * pages from being scrapped. If B_INVAL is set then
1003 * this case is not run and the next case is run to
1004 * destroy the buffer. B_INVAL can occur if the buffer
1005 * is outside the range supported by the underlying device.
1007 bp
->b_flags
&= ~B_ERROR
;
1009 } else if ((bp
->b_flags
& (B_NOCACHE
| B_INVAL
| B_ERROR
)) ||
1010 (bp
->b_bufsize
<= 0) || bp
->b_cmd
== BUF_CMD_FREEBLKS
) {
1012 * Either a failed I/O or we were asked to free or not
1015 * NOTE: HAMMER will set B_LOCKED in buf_deallocate if the
1016 * buffer cannot be immediately freed.
1018 bp
->b_flags
|= B_INVAL
;
1019 if (LIST_FIRST(&bp
->b_dep
) != NULL
)
1021 if (bp
->b_flags
& B_DELWRI
) {
1023 numdirtywakeup(lodirtybuffers
);
1025 bp
->b_flags
&= ~(B_DELWRI
| B_CACHE
);
1029 * We must clear B_RELBUF if B_DELWRI or B_LOCKED is set.
1030 * If vfs_vmio_release() is called with either bit set, the
1031 * underlying pages may wind up getting freed causing a previous
1032 * write (bdwrite()) to get 'lost' because pages associated with
1033 * a B_DELWRI bp are marked clean. Pages associated with a
1034 * B_LOCKED buffer may be mapped by the filesystem.
1036 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1037 * if B_DELWRI is set.
1039 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1040 * on pages to return pages to the VM page queues.
1042 if (bp
->b_flags
& (B_DELWRI
| B_LOCKED
))
1043 bp
->b_flags
&= ~B_RELBUF
;
1044 else if (vm_page_count_severe())
1045 bp
->b_flags
|= B_RELBUF
;
1048 * At this point destroying the buffer is governed by the B_INVAL
1049 * or B_RELBUF flags.
1051 bp
->b_cmd
= BUF_CMD_DONE
;
1054 * VMIO buffer rundown. Make sure the VM page array is restored
1055 * after an I/O may have replaces some of the pages with bogus pages
1056 * in order to not destroy dirty pages in a fill-in read.
1058 * Note that due to the code above, if a buffer is marked B_DELWRI
1059 * then the B_RELBUF and B_NOCACHE bits will always be clear.
1060 * B_INVAL may still be set, however.
1062 * For clean buffers, B_INVAL or B_RELBUF will destroy the buffer
1063 * but not the backing store. B_NOCACHE will destroy the backing
1066 * Note that dirty NFS buffers contain byte-granular write ranges
1067 * and should not be destroyed w/ B_INVAL even if the backing store
1070 if (bp
->b_flags
& B_VMIO
) {
1072 * Rundown for VMIO buffers which are not dirty NFS buffers.
1084 * Get the base offset and length of the buffer. Note that
1085 * in the VMIO case if the buffer block size is not
1086 * page-aligned then b_data pointer may not be page-aligned.
1087 * But our b_xio.xio_pages array *IS* page aligned.
1089 * block sizes less then DEV_BSIZE (usually 512) are not
1090 * supported due to the page granularity bits (m->valid,
1091 * m->dirty, etc...).
1093 * See man buf(9) for more information
1096 resid
= bp
->b_bufsize
;
1097 foff
= bp
->b_loffset
;
1099 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
1100 m
= bp
->b_xio
.xio_pages
[i
];
1101 vm_page_flag_clear(m
, PG_ZERO
);
1103 * If we hit a bogus page, fixup *all* of them
1104 * now. Note that we left these pages wired
1105 * when we removed them so they had better exist,
1106 * and they cannot be ripped out from under us so
1107 * no critical section protection is necessary.
1109 if (m
== bogus_page
) {
1111 poff
= OFF_TO_IDX(bp
->b_loffset
);
1113 for (j
= i
; j
< bp
->b_xio
.xio_npages
; j
++) {
1116 mtmp
= bp
->b_xio
.xio_pages
[j
];
1117 if (mtmp
== bogus_page
) {
1118 mtmp
= vm_page_lookup(obj
, poff
+ j
);
1120 panic("brelse: page missing");
1122 bp
->b_xio
.xio_pages
[j
] = mtmp
;
1126 if ((bp
->b_flags
& B_INVAL
) == 0) {
1127 pmap_qenter(trunc_page((vm_offset_t
)bp
->b_data
),
1128 bp
->b_xio
.xio_pages
, bp
->b_xio
.xio_npages
);
1130 m
= bp
->b_xio
.xio_pages
[i
];
1134 * Invalidate the backing store if B_NOCACHE is set
1135 * (e.g. used with vinvalbuf()). If this is NFS
1136 * we impose a requirement that the block size be
1137 * a multiple of PAGE_SIZE and create a temporary
1138 * hack to basically invalidate the whole page. The
1139 * problem is that NFS uses really odd buffer sizes
1140 * especially when tracking piecemeal writes and
1141 * it also vinvalbuf()'s a lot, which would result
1142 * in only partial page validation and invalidation
1143 * here. If the file page is mmap()'d, however,
1144 * all the valid bits get set so after we invalidate
1145 * here we would end up with weird m->valid values
1146 * like 0xfc. nfs_getpages() can't handle this so
1147 * we clear all the valid bits for the NFS case
1148 * instead of just some of them.
1150 * The real bug is the VM system having to set m->valid
1151 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1152 * itself is an artifact of the whole 512-byte
1153 * granular mess that exists to support odd block
1154 * sizes and UFS meta-data block sizes (e.g. 6144).
1155 * A complete rewrite is required.
1157 if (bp
->b_flags
& (B_NOCACHE
|B_ERROR
)) {
1158 int poffset
= foff
& PAGE_MASK
;
1161 presid
= PAGE_SIZE
- poffset
;
1162 if (bp
->b_vp
->v_tag
== VT_NFS
&&
1163 bp
->b_vp
->v_type
== VREG
) {
1165 } else if (presid
> resid
) {
1168 KASSERT(presid
>= 0, ("brelse: extra page"));
1169 vm_page_set_invalid(m
, poffset
, presid
);
1171 resid
-= PAGE_SIZE
- (foff
& PAGE_MASK
);
1172 foff
= (foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
;
1174 if (bp
->b_flags
& (B_INVAL
| B_RELBUF
))
1175 vfs_vmio_release(bp
);
1178 * Rundown for non-VMIO buffers.
1180 if (bp
->b_flags
& (B_INVAL
| B_RELBUF
)) {
1183 kprintf("brelse bp %p %08x/%08x: Warning, caught and fixed brelvp bug\n", bp
, saved_flags
, bp
->b_flags
);
1192 if (bp
->b_qindex
!= BQUEUE_NONE
)
1193 panic("brelse: free buffer onto another queue???");
1194 if (BUF_REFCNTNB(bp
) > 1) {
1195 /* Temporary panic to verify exclusive locking */
1196 /* This panic goes away when we allow shared refs */
1197 panic("brelse: multiple refs");
1198 /* do not release to free list */
1205 * Figure out the correct queue to place the cleaned up buffer on.
1206 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1207 * disassociated from their vnode.
1209 if (bp
->b_flags
& B_LOCKED
) {
1211 * Buffers that are locked are placed in the locked queue
1212 * immediately, regardless of their state.
1214 bp
->b_qindex
= BQUEUE_LOCKED
;
1215 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_LOCKED
], bp
, b_freelist
);
1216 } else if (bp
->b_bufsize
== 0) {
1218 * Buffers with no memory. Due to conditionals near the top
1219 * of brelse() such buffers should probably already be
1220 * marked B_INVAL and disassociated from their vnode.
1222 bp
->b_flags
|= B_INVAL
;
1223 KASSERT(bp
->b_vp
== NULL
, ("bp1 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp
, saved_flags
, bp
->b_flags
, bp
->b_vp
));
1224 KKASSERT((bp
->b_flags
& B_HASHED
) == 0);
1225 if (bp
->b_kvasize
) {
1226 bp
->b_qindex
= BQUEUE_EMPTYKVA
;
1228 bp
->b_qindex
= BQUEUE_EMPTY
;
1230 TAILQ_INSERT_HEAD(&bufqueues
[bp
->b_qindex
], bp
, b_freelist
);
1231 } else if (bp
->b_flags
& (B_ERROR
| B_INVAL
| B_NOCACHE
| B_RELBUF
)) {
1233 * Buffers with junk contents. Again these buffers had better
1234 * already be disassociated from their vnode.
1236 KASSERT(bp
->b_vp
== NULL
, ("bp2 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp
, saved_flags
, bp
->b_flags
, bp
->b_vp
));
1237 KKASSERT((bp
->b_flags
& B_HASHED
) == 0);
1238 bp
->b_flags
|= B_INVAL
;
1239 bp
->b_qindex
= BQUEUE_CLEAN
;
1240 TAILQ_INSERT_HEAD(&bufqueues
[BQUEUE_CLEAN
], bp
, b_freelist
);
1243 * Remaining buffers. These buffers are still associated with
1246 switch(bp
->b_flags
& (B_DELWRI
|B_AGE
)) {
1247 case B_DELWRI
| B_AGE
:
1248 bp
->b_qindex
= BQUEUE_DIRTY
;
1249 TAILQ_INSERT_HEAD(&bufqueues
[BQUEUE_DIRTY
], bp
, b_freelist
);
1252 bp
->b_qindex
= BQUEUE_DIRTY
;
1253 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_DIRTY
], bp
, b_freelist
);
1256 bp
->b_qindex
= BQUEUE_CLEAN
;
1257 TAILQ_INSERT_HEAD(&bufqueues
[BQUEUE_CLEAN
], bp
, b_freelist
);
1260 bp
->b_qindex
= BQUEUE_CLEAN
;
1261 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_CLEAN
], bp
, b_freelist
);
1267 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1268 * on the correct queue.
1270 if ((bp
->b_flags
& (B_INVAL
|B_DELWRI
)) == (B_INVAL
|B_DELWRI
))
1274 * Fixup numfreebuffers count. The bp is on an appropriate queue
1275 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1276 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1277 * if B_INVAL is set ).
1279 if ((bp
->b_flags
& (B_LOCKED
|B_DELWRI
)) == 0)
1283 * Something we can maybe free or reuse
1285 if (bp
->b_bufsize
|| bp
->b_kvasize
)
1289 * Clean up temporary flags and unlock the buffer.
1291 bp
->b_flags
&= ~(B_ORDERED
| B_ASYNC
| B_NOCACHE
| B_AGE
| B_RELBUF
|
1292 B_DIRECT
| B_NOWDRAIN
);
1300 * Release a buffer back to the appropriate queue but do not try to free
1301 * it. The buffer is expected to be used again soon.
1303 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1304 * biodone() to requeue an async I/O on completion. It is also used when
1305 * known good buffers need to be requeued but we think we may need the data
1308 * XXX we should be able to leave the B_RELBUF hint set on completion.
1311 bqrelse(struct buf
*bp
)
1315 KASSERT(!(bp
->b_flags
& (B_CLUSTER
|B_PAGING
)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp
));
1317 if (bp
->b_qindex
!= BQUEUE_NONE
)
1318 panic("bqrelse: free buffer onto another queue???");
1319 if (BUF_REFCNTNB(bp
) > 1) {
1320 /* do not release to free list */
1321 panic("bqrelse: multiple refs");
1326 if (bp
->b_flags
& B_LOCKED
) {
1328 * Locked buffers are released to the locked queue. However,
1329 * if the buffer is dirty it will first go into the dirty
1330 * queue and later on after the I/O completes successfully it
1331 * will be released to the locked queue.
1333 bp
->b_flags
&= ~B_ERROR
;
1334 bp
->b_qindex
= BQUEUE_LOCKED
;
1335 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_LOCKED
], bp
, b_freelist
);
1336 } else if (bp
->b_flags
& B_DELWRI
) {
1337 bp
->b_qindex
= BQUEUE_DIRTY
;
1338 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_DIRTY
], bp
, b_freelist
);
1339 } else if (vm_page_count_severe()) {
1341 * We are too low on memory, we have to try to free the
1342 * buffer (most importantly: the wired pages making up its
1343 * backing store) *now*.
1349 bp
->b_qindex
= BQUEUE_CLEAN
;
1350 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_CLEAN
], bp
, b_freelist
);
1353 if ((bp
->b_flags
& B_LOCKED
) == 0 &&
1354 ((bp
->b_flags
& B_INVAL
) || (bp
->b_flags
& B_DELWRI
) == 0)) {
1359 * Something we can maybe free or reuse.
1361 if (bp
->b_bufsize
&& !(bp
->b_flags
& B_DELWRI
))
1365 * Final cleanup and unlock. Clear bits that are only used while a
1366 * buffer is actively locked.
1368 bp
->b_flags
&= ~(B_ORDERED
| B_ASYNC
| B_NOCACHE
| B_AGE
| B_RELBUF
);
1376 * Return backing pages held by the buffer 'bp' back to the VM system
1377 * if possible. The pages are freed if they are no longer valid or
1378 * attempt to free if it was used for direct I/O otherwise they are
1379 * sent to the page cache.
1381 * Pages that were marked busy are left alone and skipped.
1383 * The KVA mapping (b_data) for the underlying pages is removed by
1387 vfs_vmio_release(struct buf
*bp
)
1393 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
1394 m
= bp
->b_xio
.xio_pages
[i
];
1395 bp
->b_xio
.xio_pages
[i
] = NULL
;
1397 * In order to keep page LRU ordering consistent, put
1398 * everything on the inactive queue.
1400 vm_page_unwire(m
, 0);
1402 * We don't mess with busy pages, it is
1403 * the responsibility of the process that
1404 * busied the pages to deal with them.
1406 if ((m
->flags
& PG_BUSY
) || (m
->busy
!= 0))
1409 if (m
->wire_count
== 0) {
1410 vm_page_flag_clear(m
, PG_ZERO
);
1412 * Might as well free the page if we can and it has
1413 * no valid data. We also free the page if the
1414 * buffer was used for direct I/O.
1416 if ((bp
->b_flags
& B_ASYNC
) == 0 && !m
->valid
&&
1417 m
->hold_count
== 0) {
1419 vm_page_protect(m
, VM_PROT_NONE
);
1421 } else if (bp
->b_flags
& B_DIRECT
) {
1422 vm_page_try_to_free(m
);
1423 } else if (vm_page_count_severe()) {
1424 vm_page_try_to_cache(m
);
1429 pmap_qremove(trunc_page((vm_offset_t
) bp
->b_data
), bp
->b_xio
.xio_npages
);
1430 if (bp
->b_bufsize
) {
1434 bp
->b_xio
.xio_npages
= 0;
1435 bp
->b_flags
&= ~B_VMIO
;
1443 * Implement clustered async writes for clearing out B_DELWRI buffers.
1444 * This is much better then the old way of writing only one buffer at
1445 * a time. Note that we may not be presented with the buffers in the
1446 * correct order, so we search for the cluster in both directions.
1448 * The buffer is locked on call.
1451 vfs_bio_awrite(struct buf
*bp
)
1455 off_t loffset
= bp
->b_loffset
;
1456 struct vnode
*vp
= bp
->b_vp
;
1464 * right now we support clustered writing only to regular files. If
1465 * we find a clusterable block we could be in the middle of a cluster
1466 * rather then at the beginning.
1468 * NOTE: b_bio1 contains the logical loffset and is aliased
1469 * to b_loffset. b_bio2 contains the translated block number.
1471 if ((vp
->v_type
== VREG
) &&
1472 (vp
->v_mount
!= 0) && /* Only on nodes that have the size info */
1473 (bp
->b_flags
& (B_CLUSTEROK
| B_INVAL
)) == B_CLUSTEROK
) {
1475 size
= vp
->v_mount
->mnt_stat
.f_iosize
;
1477 for (i
= size
; i
< MAXPHYS
; i
+= size
) {
1478 if ((bpa
= findblk(vp
, loffset
+ i
)) &&
1479 BUF_REFCNT(bpa
) == 0 &&
1480 ((bpa
->b_flags
& (B_DELWRI
| B_CLUSTEROK
| B_INVAL
)) ==
1481 (B_DELWRI
| B_CLUSTEROK
)) &&
1482 (bpa
->b_bufsize
== size
)) {
1483 if ((bpa
->b_bio2
.bio_offset
== NOOFFSET
) ||
1484 (bpa
->b_bio2
.bio_offset
!=
1485 bp
->b_bio2
.bio_offset
+ i
))
1491 for (j
= size
; i
+ j
<= MAXPHYS
&& j
<= loffset
; j
+= size
) {
1492 if ((bpa
= findblk(vp
, loffset
- j
)) &&
1493 BUF_REFCNT(bpa
) == 0 &&
1494 ((bpa
->b_flags
& (B_DELWRI
| B_CLUSTEROK
| B_INVAL
)) ==
1495 (B_DELWRI
| B_CLUSTEROK
)) &&
1496 (bpa
->b_bufsize
== size
)) {
1497 if ((bpa
->b_bio2
.bio_offset
== NOOFFSET
) ||
1498 (bpa
->b_bio2
.bio_offset
!=
1499 bp
->b_bio2
.bio_offset
- j
))
1508 * this is a possible cluster write
1510 if (nbytes
!= size
) {
1512 nwritten
= cluster_wbuild(vp
, size
,
1513 loffset
- j
, nbytes
);
1520 bp
->b_flags
|= B_ASYNC
;
1524 * default (old) behavior, writing out only one block
1526 * XXX returns b_bufsize instead of b_bcount for nwritten?
1528 nwritten
= bp
->b_bufsize
;
1537 * Find and initialize a new buffer header, freeing up existing buffers
1538 * in the bufqueues as necessary. The new buffer is returned locked.
1540 * Important: B_INVAL is not set. If the caller wishes to throw the
1541 * buffer away, the caller must set B_INVAL prior to calling brelse().
1544 * We have insufficient buffer headers
1545 * We have insufficient buffer space
1546 * buffer_map is too fragmented ( space reservation fails )
1547 * If we have to flush dirty buffers ( but we try to avoid this )
1549 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1550 * Instead we ask the buf daemon to do it for us. We attempt to
1551 * avoid piecemeal wakeups of the pageout daemon.
1555 getnewbuf(int slpflag
, int slptimeo
, int size
, int maxsize
)
1561 static int flushingbufs
;
1564 * We can't afford to block since we might be holding a vnode lock,
1565 * which may prevent system daemons from running. We deal with
1566 * low-memory situations by proactively returning memory and running
1567 * async I/O rather then sync I/O.
1571 --getnewbufrestarts
;
1573 ++getnewbufrestarts
;
1576 * Setup for scan. If we do not have enough free buffers,
1577 * we setup a degenerate case that immediately fails. Note
1578 * that if we are specially marked process, we are allowed to
1579 * dip into our reserves.
1581 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1583 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1584 * However, there are a number of cases (defragging, reusing, ...)
1585 * where we cannot backup.
1587 nqindex
= BQUEUE_EMPTYKVA
;
1588 nbp
= TAILQ_FIRST(&bufqueues
[BQUEUE_EMPTYKVA
]);
1592 * If no EMPTYKVA buffers and we are either
1593 * defragging or reusing, locate a CLEAN buffer
1594 * to free or reuse. If bufspace useage is low
1595 * skip this step so we can allocate a new buffer.
1597 if (defrag
|| bufspace
>= lobufspace
) {
1598 nqindex
= BQUEUE_CLEAN
;
1599 nbp
= TAILQ_FIRST(&bufqueues
[BQUEUE_CLEAN
]);
1603 * If we could not find or were not allowed to reuse a
1604 * CLEAN buffer, check to see if it is ok to use an EMPTY
1605 * buffer. We can only use an EMPTY buffer if allocating
1606 * its KVA would not otherwise run us out of buffer space.
1608 if (nbp
== NULL
&& defrag
== 0 &&
1609 bufspace
+ maxsize
< hibufspace
) {
1610 nqindex
= BQUEUE_EMPTY
;
1611 nbp
= TAILQ_FIRST(&bufqueues
[BQUEUE_EMPTY
]);
1616 * Run scan, possibly freeing data and/or kva mappings on the fly
1620 while ((bp
= nbp
) != NULL
) {
1621 int qindex
= nqindex
;
1624 * Calculate next bp ( we can only use it if we do not block
1625 * or do other fancy things ).
1627 if ((nbp
= TAILQ_NEXT(bp
, b_freelist
)) == NULL
) {
1630 nqindex
= BQUEUE_EMPTYKVA
;
1631 if ((nbp
= TAILQ_FIRST(&bufqueues
[BQUEUE_EMPTYKVA
])))
1634 case BQUEUE_EMPTYKVA
:
1635 nqindex
= BQUEUE_CLEAN
;
1636 if ((nbp
= TAILQ_FIRST(&bufqueues
[BQUEUE_CLEAN
])))
1650 KASSERT(bp
->b_qindex
== qindex
, ("getnewbuf: inconsistent queue %d bp %p", qindex
, bp
));
1653 * Note: we no longer distinguish between VMIO and non-VMIO
1657 KASSERT((bp
->b_flags
& B_DELWRI
) == 0, ("delwri buffer %p found in queue %d", bp
, qindex
));
1660 * If we are defragging then we need a buffer with
1661 * b_kvasize != 0. XXX this situation should no longer
1662 * occur, if defrag is non-zero the buffer's b_kvasize
1663 * should also be non-zero at this point. XXX
1665 if (defrag
&& bp
->b_kvasize
== 0) {
1666 kprintf("Warning: defrag empty buffer %p\n", bp
);
1671 * Start freeing the bp. This is somewhat involved. nbp
1672 * remains valid only for BQUEUE_EMPTY[KVA] bp's. Buffers
1673 * on the clean list must be disassociated from their
1674 * current vnode. Buffers on the empty[kva] lists have
1675 * already been disassociated.
1678 if (BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_NOWAIT
) != 0) {
1679 kprintf("getnewbuf: warning, locked buf %p, race corrected\n", bp
);
1680 tsleep(&bd_request
, 0, "gnbxxx", hz
/ 100);
1683 if (bp
->b_qindex
!= qindex
) {
1684 kprintf("getnewbuf: warning, BUF_LOCK blocked unexpectedly on buf %p index %d->%d, race corrected\n", bp
, qindex
, bp
->b_qindex
);
1691 * Dependancies must be handled before we disassociate the
1694 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
1695 * be immediately disassociated. HAMMER then becomes
1696 * responsible for releasing the buffer.
1698 if (LIST_FIRST(&bp
->b_dep
) != NULL
) {
1700 if (bp
->b_flags
& B_LOCKED
) {
1706 if (qindex
== BQUEUE_CLEAN
) {
1707 if (bp
->b_flags
& B_VMIO
) {
1708 bp
->b_flags
&= ~B_ASYNC
;
1709 vfs_vmio_release(bp
);
1716 * NOTE: nbp is now entirely invalid. We can only restart
1717 * the scan from this point on.
1719 * Get the rest of the buffer freed up. b_kva* is still
1720 * valid after this operation.
1723 KASSERT(bp
->b_vp
== NULL
, ("bp3 %p flags %08x vnode %p qindex %d unexpectededly still associated!", bp
, bp
->b_flags
, bp
->b_vp
, qindex
));
1724 KKASSERT((bp
->b_flags
& B_HASHED
) == 0);
1727 * critical section protection is not required when
1728 * scrapping a buffer's contents because it is already
1734 bp
->b_flags
= B_BNOCLIP
;
1735 bp
->b_cmd
= BUF_CMD_DONE
;
1740 bp
->b_xio
.xio_npages
= 0;
1741 bp
->b_dirtyoff
= bp
->b_dirtyend
= 0;
1746 * If we are defragging then free the buffer.
1749 bp
->b_flags
|= B_INVAL
;
1757 * If we are overcomitted then recover the buffer and its
1758 * KVM space. This occurs in rare situations when multiple
1759 * processes are blocked in getnewbuf() or allocbuf().
1761 if (bufspace
>= hibufspace
)
1763 if (flushingbufs
&& bp
->b_kvasize
!= 0) {
1764 bp
->b_flags
|= B_INVAL
;
1769 if (bufspace
< lobufspace
)
1775 * If we exhausted our list, sleep as appropriate. We may have to
1776 * wakeup various daemons and write out some dirty buffers.
1778 * Generally we are sleeping due to insufficient buffer space.
1786 flags
= VFS_BIO_NEED_BUFSPACE
;
1788 } else if (bufspace
>= hibufspace
) {
1790 flags
= VFS_BIO_NEED_BUFSPACE
;
1793 flags
= VFS_BIO_NEED_ANY
;
1796 bd_speedup(); /* heeeelp */
1798 needsbuffer
|= flags
;
1799 while (needsbuffer
& flags
) {
1800 if (tsleep(&needsbuffer
, slpflag
, waitmsg
, slptimeo
))
1805 * We finally have a valid bp. We aren't quite out of the
1806 * woods, we still have to reserve kva space. In order
1807 * to keep fragmentation sane we only allocate kva in
1810 maxsize
= (maxsize
+ BKVAMASK
) & ~BKVAMASK
;
1812 if (maxsize
!= bp
->b_kvasize
) {
1813 vm_offset_t addr
= 0;
1818 count
= vm_map_entry_reserve(MAP_RESERVE_COUNT
);
1819 vm_map_lock(&buffer_map
);
1821 if (vm_map_findspace(&buffer_map
,
1822 vm_map_min(&buffer_map
), maxsize
,
1825 * Uh oh. Buffer map is too fragmented. We
1826 * must defragment the map.
1828 vm_map_unlock(&buffer_map
);
1829 vm_map_entry_release(count
);
1832 bp
->b_flags
|= B_INVAL
;
1837 vm_map_insert(&buffer_map
, &count
,
1839 addr
, addr
+ maxsize
,
1841 VM_PROT_ALL
, VM_PROT_ALL
,
1844 bp
->b_kvabase
= (caddr_t
) addr
;
1845 bp
->b_kvasize
= maxsize
;
1846 bufspace
+= bp
->b_kvasize
;
1849 vm_map_unlock(&buffer_map
);
1850 vm_map_entry_release(count
);
1852 bp
->b_data
= bp
->b_kvabase
;
1860 * Buffer flushing daemon. Buffers are normally flushed by the
1861 * update daemon but if it cannot keep up this process starts to
1862 * take the load in an attempt to prevent getnewbuf() from blocking.
1865 static struct thread
*bufdaemonthread
;
1867 static struct kproc_desc buf_kp
= {
1872 SYSINIT(bufdaemon
, SI_SUB_KTHREAD_BUF
, SI_ORDER_FIRST
, kproc_start
, &buf_kp
)
1878 * This process needs to be suspended prior to shutdown sync.
1880 EVENTHANDLER_REGISTER(shutdown_pre_sync
, shutdown_kproc
,
1881 bufdaemonthread
, SHUTDOWN_PRI_LAST
);
1884 * This process is allowed to take the buffer cache to the limit
1889 kproc_suspend_loop();
1892 * Do the flush. Limit the amount of in-transit I/O we
1893 * allow to build up, otherwise we would completely saturate
1894 * the I/O system. Wakeup any waiting processes before we
1895 * normally would so they can run in parallel with our drain.
1897 while (numdirtybuffers
> lodirtybuffers
) {
1898 if (flushbufqueues() == 0)
1900 waitrunningbufspace();
1901 numdirtywakeup((lodirtybuffers
+ hidirtybuffers
) / 2);
1905 * Only clear bd_request if we have reached our low water
1906 * mark. The buf_daemon normally waits 5 seconds and
1907 * then incrementally flushes any dirty buffers that have
1908 * built up, within reason.
1910 * If we were unable to hit our low water mark and couldn't
1911 * find any flushable buffers, we sleep half a second.
1912 * Otherwise we loop immediately.
1914 if (numdirtybuffers
<= lodirtybuffers
) {
1916 * We reached our low water mark, reset the
1917 * request and sleep until we are needed again.
1918 * The sleep is just so the suspend code works.
1920 spin_lock_wr(&needsbuffer_spin
);
1922 msleep(&bd_request
, &needsbuffer_spin
, 0, "psleep", hz
);
1923 spin_unlock_wr(&needsbuffer_spin
);
1926 * We couldn't find any flushable dirty buffers but
1927 * still have too many dirty buffers, we
1928 * have to sleep and try again. (rare)
1930 tsleep(&bd_request
, 0, "qsleep", hz
/ 2);
1938 * Try to flush a buffer in the dirty queue. We must be careful to
1939 * free up B_INVAL buffers instead of write them, which NFS is
1940 * particularly sensitive to.
1944 flushbufqueues(void)
1949 bp
= TAILQ_FIRST(&bufqueues
[BQUEUE_DIRTY
]);
1952 KASSERT((bp
->b_flags
& B_DELWRI
),
1953 ("unexpected clean buffer %p", bp
));
1954 if (bp
->b_flags
& B_DELWRI
) {
1955 if (bp
->b_flags
& B_INVAL
) {
1956 if (BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_NOWAIT
) != 0)
1957 panic("flushbufqueues: locked buf");
1963 if (LIST_FIRST(&bp
->b_dep
) != NULL
&&
1964 (bp
->b_flags
& B_DEFERRED
) == 0 &&
1965 buf_countdeps(bp
, 0)) {
1966 TAILQ_REMOVE(&bufqueues
[BQUEUE_DIRTY
],
1968 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_DIRTY
],
1970 bp
->b_flags
|= B_DEFERRED
;
1971 bp
= TAILQ_FIRST(&bufqueues
[BQUEUE_DIRTY
]);
1976 * Only write it out if we can successfully lock
1977 * it. If the buffer has a dependancy,
1978 * buf_checkwrite must also return 0.
1980 if (BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_NOWAIT
) == 0) {
1981 if (LIST_FIRST(&bp
->b_dep
) != NULL
&&
1982 buf_checkwrite(bp
)) {
1992 bp
= TAILQ_NEXT(bp
, b_freelist
);
2000 * Returns true if no I/O is needed to access the associated VM object.
2001 * This is like findblk except it also hunts around in the VM system for
2004 * Note that we ignore vm_page_free() races from interrupts against our
2005 * lookup, since if the caller is not protected our return value will not
2006 * be any more valid then otherwise once we exit the critical section.
2009 inmem(struct vnode
*vp
, off_t loffset
)
2012 vm_offset_t toff
, tinc
, size
;
2015 if (findblk(vp
, loffset
))
2017 if (vp
->v_mount
== NULL
)
2019 if ((obj
= vp
->v_object
) == NULL
)
2023 if (size
> vp
->v_mount
->mnt_stat
.f_iosize
)
2024 size
= vp
->v_mount
->mnt_stat
.f_iosize
;
2026 for (toff
= 0; toff
< vp
->v_mount
->mnt_stat
.f_iosize
; toff
+= tinc
) {
2027 m
= vm_page_lookup(obj
, OFF_TO_IDX(loffset
+ toff
));
2031 if (tinc
> PAGE_SIZE
- ((toff
+ loffset
) & PAGE_MASK
))
2032 tinc
= PAGE_SIZE
- ((toff
+ loffset
) & PAGE_MASK
);
2033 if (vm_page_is_valid(m
,
2034 (vm_offset_t
) ((toff
+ loffset
) & PAGE_MASK
), tinc
) == 0)
2043 * Sets the dirty range for a buffer based on the status of the dirty
2044 * bits in the pages comprising the buffer.
2046 * The range is limited to the size of the buffer.
2048 * This routine is primarily used by NFS, but is generalized for the
2052 vfs_setdirty(struct buf
*bp
)
2058 * Degenerate case - empty buffer
2061 if (bp
->b_bufsize
== 0)
2065 * We qualify the scan for modified pages on whether the
2066 * object has been flushed yet. The OBJ_WRITEABLE flag
2067 * is not cleared simply by protecting pages off.
2070 if ((bp
->b_flags
& B_VMIO
) == 0)
2073 object
= bp
->b_xio
.xio_pages
[0]->object
;
2075 if ((object
->flags
& OBJ_WRITEABLE
) && !(object
->flags
& OBJ_MIGHTBEDIRTY
))
2076 kprintf("Warning: object %p writeable but not mightbedirty\n", object
);
2077 if (!(object
->flags
& OBJ_WRITEABLE
) && (object
->flags
& OBJ_MIGHTBEDIRTY
))
2078 kprintf("Warning: object %p mightbedirty but not writeable\n", object
);
2080 if (object
->flags
& (OBJ_MIGHTBEDIRTY
|OBJ_CLEANING
)) {
2081 vm_offset_t boffset
;
2082 vm_offset_t eoffset
;
2085 * test the pages to see if they have been modified directly
2086 * by users through the VM system.
2088 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
2089 vm_page_flag_clear(bp
->b_xio
.xio_pages
[i
], PG_ZERO
);
2090 vm_page_test_dirty(bp
->b_xio
.xio_pages
[i
]);
2094 * Calculate the encompassing dirty range, boffset and eoffset,
2095 * (eoffset - boffset) bytes.
2098 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
2099 if (bp
->b_xio
.xio_pages
[i
]->dirty
)
2102 boffset
= (i
<< PAGE_SHIFT
) - (bp
->b_loffset
& PAGE_MASK
);
2104 for (i
= bp
->b_xio
.xio_npages
- 1; i
>= 0; --i
) {
2105 if (bp
->b_xio
.xio_pages
[i
]->dirty
) {
2109 eoffset
= ((i
+ 1) << PAGE_SHIFT
) - (bp
->b_loffset
& PAGE_MASK
);
2112 * Fit it to the buffer.
2115 if (eoffset
> bp
->b_bcount
)
2116 eoffset
= bp
->b_bcount
;
2119 * If we have a good dirty range, merge with the existing
2123 if (boffset
< eoffset
) {
2124 if (bp
->b_dirtyoff
> boffset
)
2125 bp
->b_dirtyoff
= boffset
;
2126 if (bp
->b_dirtyend
< eoffset
)
2127 bp
->b_dirtyend
= eoffset
;
2135 * Locate and return the specified buffer, or NULL if the buffer does
2136 * not exist. Do not attempt to lock the buffer or manipulate it in
2137 * any way. The caller must validate that the correct buffer has been
2138 * obtain after locking it.
2141 findblk(struct vnode
*vp
, off_t loffset
)
2146 bp
= buf_rb_hash_RB_LOOKUP(&vp
->v_rbhash_tree
, loffset
);
2154 * Get a block given a specified block and offset into a file/device.
2155 * B_INVAL may or may not be set on return. The caller should clear
2156 * B_INVAL prior to initiating a READ.
2158 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2159 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2160 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2161 * without doing any of those things the system will likely believe
2162 * the buffer to be valid (especially if it is not B_VMIO), and the
2163 * next getblk() will return the buffer with B_CACHE set.
2165 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2166 * an existing buffer.
2168 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2169 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2170 * and then cleared based on the backing VM. If the previous buffer is
2171 * non-0-sized but invalid, B_CACHE will be cleared.
2173 * If getblk() must create a new buffer, the new buffer is returned with
2174 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2175 * case it is returned with B_INVAL clear and B_CACHE set based on the
2178 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
2179 * B_CACHE bit is clear.
2181 * What this means, basically, is that the caller should use B_CACHE to
2182 * determine whether the buffer is fully valid or not and should clear
2183 * B_INVAL prior to issuing a read. If the caller intends to validate
2184 * the buffer by loading its data area with something, the caller needs
2185 * to clear B_INVAL. If the caller does this without issuing an I/O,
2186 * the caller should set B_CACHE ( as an optimization ), else the caller
2187 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2188 * a write attempt or if it was a successfull read. If the caller
2189 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2190 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2193 getblk(struct vnode
*vp
, off_t loffset
, int size
, int slpflag
, int slptimeo
)
2197 if (size
> MAXBSIZE
)
2198 panic("getblk: size(%d) > MAXBSIZE(%d)", size
, MAXBSIZE
);
2199 if (vp
->v_object
== NULL
)
2200 panic("getblk: vnode %p has no object!", vp
);
2205 * Block if we are low on buffers. Certain processes are allowed
2206 * to completely exhaust the buffer cache.
2208 * If this check ever becomes a bottleneck it may be better to
2209 * move it into the else, when findblk() fails. At the moment
2210 * it isn't a problem.
2212 * XXX remove, we cannot afford to block anywhere if holding a vnode
2213 * lock in low-memory situation, so take it to the max.
2215 if (numfreebuffers
== 0) {
2218 needsbuffer
|= VFS_BIO_NEED_ANY
;
2219 tsleep(&needsbuffer
, slpflag
, "newbuf", slptimeo
);
2222 if ((bp
= findblk(vp
, loffset
))) {
2224 * The buffer was found in the cache, but we need to lock it.
2225 * Even with LK_NOWAIT the lockmgr may break our critical
2226 * section, so double-check the validity of the buffer
2227 * once the lock has been obtained.
2229 if (BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_NOWAIT
)) {
2230 int lkflags
= LK_EXCLUSIVE
| LK_SLEEPFAIL
;
2231 if (slpflag
& PCATCH
)
2232 lkflags
|= LK_PCATCH
;
2233 if (BUF_TIMELOCK(bp
, lkflags
, "getblk", slptimeo
) ==
2242 * Once the buffer has been locked, make sure we didn't race
2243 * a buffer recyclement. Buffers that are no longer hashed
2244 * will have b_vp == NULL, so this takes care of that check
2247 if (bp
->b_vp
!= vp
|| bp
->b_loffset
!= loffset
) {
2248 kprintf("Warning buffer %p (vp %p loffset %lld) was recycled\n", bp
, vp
, loffset
);
2254 * All vnode-based buffers must be backed by a VM object.
2256 KKASSERT(bp
->b_flags
& B_VMIO
);
2257 KKASSERT(bp
->b_cmd
== BUF_CMD_DONE
);
2260 * Make sure that B_INVAL buffers do not have a cached
2261 * block number translation.
2263 if ((bp
->b_flags
& B_INVAL
) && (bp
->b_bio2
.bio_offset
!= NOOFFSET
)) {
2264 kprintf("Warning invalid buffer %p (vp %p loffset %lld) did not have cleared bio_offset cache\n", bp
, vp
, loffset
);
2265 clearbiocache(&bp
->b_bio2
);
2269 * The buffer is locked. B_CACHE is cleared if the buffer is
2272 if (bp
->b_flags
& B_INVAL
)
2273 bp
->b_flags
&= ~B_CACHE
;
2277 * Any size inconsistancy with a dirty buffer or a buffer
2278 * with a softupdates dependancy must be resolved. Resizing
2279 * the buffer in such circumstances can lead to problems.
2281 if (size
!= bp
->b_bcount
) {
2282 if (bp
->b_flags
& B_DELWRI
) {
2283 bp
->b_flags
|= B_NOCACHE
;
2285 } else if (LIST_FIRST(&bp
->b_dep
)) {
2286 bp
->b_flags
|= B_NOCACHE
;
2289 bp
->b_flags
|= B_RELBUF
;
2294 KKASSERT(size
<= bp
->b_kvasize
);
2295 KASSERT(bp
->b_loffset
!= NOOFFSET
,
2296 ("getblk: no buffer offset"));
2299 * A buffer with B_DELWRI set and B_CACHE clear must
2300 * be committed before we can return the buffer in
2301 * order to prevent the caller from issuing a read
2302 * ( due to B_CACHE not being set ) and overwriting
2305 * Most callers, including NFS and FFS, need this to
2306 * operate properly either because they assume they
2307 * can issue a read if B_CACHE is not set, or because
2308 * ( for example ) an uncached B_DELWRI might loop due
2309 * to softupdates re-dirtying the buffer. In the latter
2310 * case, B_CACHE is set after the first write completes,
2311 * preventing further loops.
2313 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2314 * above while extending the buffer, we cannot allow the
2315 * buffer to remain with B_CACHE set after the write
2316 * completes or it will represent a corrupt state. To
2317 * deal with this we set B_NOCACHE to scrap the buffer
2320 * We might be able to do something fancy, like setting
2321 * B_CACHE in bwrite() except if B_DELWRI is already set,
2322 * so the below call doesn't set B_CACHE, but that gets real
2323 * confusing. This is much easier.
2326 if ((bp
->b_flags
& (B_CACHE
|B_DELWRI
)) == B_DELWRI
) {
2327 bp
->b_flags
|= B_NOCACHE
;
2334 * Buffer is not in-core, create new buffer. The buffer
2335 * returned by getnewbuf() is locked. Note that the returned
2336 * buffer is also considered valid (not marked B_INVAL).
2338 * Calculating the offset for the I/O requires figuring out
2339 * the block size. We use DEV_BSIZE for VBLK or VCHR and
2340 * the mount's f_iosize otherwise. If the vnode does not
2341 * have an associated mount we assume that the passed size is
2344 * Note that vn_isdisk() cannot be used here since it may
2345 * return a failure for numerous reasons. Note that the
2346 * buffer size may be larger then the block size (the caller
2347 * will use block numbers with the proper multiple). Beware
2348 * of using any v_* fields which are part of unions. In
2349 * particular, in DragonFly the mount point overloading
2350 * mechanism uses the namecache only and the underlying
2351 * directory vnode is not a special case.
2355 if (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
)
2357 else if (vp
->v_mount
)
2358 bsize
= vp
->v_mount
->mnt_stat
.f_iosize
;
2362 maxsize
= size
+ (loffset
& PAGE_MASK
);
2363 maxsize
= imax(maxsize
, bsize
);
2365 if ((bp
= getnewbuf(slpflag
, slptimeo
, size
, maxsize
)) == NULL
) {
2366 if (slpflag
|| slptimeo
) {
2374 * This code is used to make sure that a buffer is not
2375 * created while the getnewbuf routine is blocked.
2376 * This can be a problem whether the vnode is locked or not.
2377 * If the buffer is created out from under us, we have to
2378 * throw away the one we just created. There is no window
2379 * race because we are safely running in a critical section
2380 * from the point of the duplicate buffer creation through
2381 * to here, and we've locked the buffer.
2383 if (findblk(vp
, loffset
)) {
2384 bp
->b_flags
|= B_INVAL
;
2390 * Insert the buffer into the hash, so that it can
2391 * be found by findblk().
2393 * Make sure the translation layer has been cleared.
2395 bp
->b_loffset
= loffset
;
2396 bp
->b_bio2
.bio_offset
= NOOFFSET
;
2397 /* bp->b_bio2.bio_next = NULL; */
2402 * All vnode-based buffers must be backed by a VM object.
2404 KKASSERT(vp
->v_object
!= NULL
);
2405 bp
->b_flags
|= B_VMIO
;
2406 KKASSERT(bp
->b_cmd
== BUF_CMD_DONE
);
2418 * Reacquire a buffer that was previously released to the locked queue,
2419 * or reacquire a buffer which is interlocked by having bioops->io_deallocate
2420 * set B_LOCKED (which handles the acquisition race).
2422 * To this end, either B_LOCKED must be set or the dependancy list must be
2426 regetblk(struct buf
*bp
)
2428 KKASSERT((bp
->b_flags
& B_LOCKED
) || LIST_FIRST(&bp
->b_dep
) != NULL
);
2429 BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_RETRY
);
2438 * Get an empty, disassociated buffer of given size. The buffer is
2439 * initially set to B_INVAL.
2441 * critical section protection is not required for the allocbuf()
2442 * call because races are impossible here.
2450 maxsize
= (size
+ BKVAMASK
) & ~BKVAMASK
;
2453 while ((bp
= getnewbuf(0, 0, size
, maxsize
)) == 0)
2457 bp
->b_flags
|= B_INVAL
; /* b_dep cleared by getnewbuf() */
2465 * This code constitutes the buffer memory from either anonymous system
2466 * memory (in the case of non-VMIO operations) or from an associated
2467 * VM object (in the case of VMIO operations). This code is able to
2468 * resize a buffer up or down.
2470 * Note that this code is tricky, and has many complications to resolve
2471 * deadlock or inconsistant data situations. Tread lightly!!!
2472 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2473 * the caller. Calling this code willy nilly can result in the loss of data.
2475 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2476 * B_CACHE for the non-VMIO case.
2478 * This routine does not need to be called from a critical section but you
2479 * must own the buffer.
2482 allocbuf(struct buf
*bp
, int size
)
2484 int newbsize
, mbsize
;
2487 if (BUF_REFCNT(bp
) == 0)
2488 panic("allocbuf: buffer not busy");
2490 if (bp
->b_kvasize
< size
)
2491 panic("allocbuf: buffer too small");
2493 if ((bp
->b_flags
& B_VMIO
) == 0) {
2497 * Just get anonymous memory from the kernel. Don't
2498 * mess with B_CACHE.
2500 mbsize
= (size
+ DEV_BSIZE
- 1) & ~(DEV_BSIZE
- 1);
2501 if (bp
->b_flags
& B_MALLOC
)
2504 newbsize
= round_page(size
);
2506 if (newbsize
< bp
->b_bufsize
) {
2508 * Malloced buffers are not shrunk
2510 if (bp
->b_flags
& B_MALLOC
) {
2512 bp
->b_bcount
= size
;
2514 kfree(bp
->b_data
, M_BIOBUF
);
2515 if (bp
->b_bufsize
) {
2516 bufmallocspace
-= bp
->b_bufsize
;
2520 bp
->b_data
= bp
->b_kvabase
;
2522 bp
->b_flags
&= ~B_MALLOC
;
2528 (vm_offset_t
) bp
->b_data
+ newbsize
,
2529 (vm_offset_t
) bp
->b_data
+ bp
->b_bufsize
);
2530 } else if (newbsize
> bp
->b_bufsize
) {
2532 * We only use malloced memory on the first allocation.
2533 * and revert to page-allocated memory when the buffer
2536 if ((bufmallocspace
< maxbufmallocspace
) &&
2537 (bp
->b_bufsize
== 0) &&
2538 (mbsize
<= PAGE_SIZE
/2)) {
2540 bp
->b_data
= kmalloc(mbsize
, M_BIOBUF
, M_WAITOK
);
2541 bp
->b_bufsize
= mbsize
;
2542 bp
->b_bcount
= size
;
2543 bp
->b_flags
|= B_MALLOC
;
2544 bufmallocspace
+= mbsize
;
2550 * If the buffer is growing on its other-than-first
2551 * allocation, then we revert to the page-allocation
2554 if (bp
->b_flags
& B_MALLOC
) {
2555 origbuf
= bp
->b_data
;
2556 origbufsize
= bp
->b_bufsize
;
2557 bp
->b_data
= bp
->b_kvabase
;
2558 if (bp
->b_bufsize
) {
2559 bufmallocspace
-= bp
->b_bufsize
;
2563 bp
->b_flags
&= ~B_MALLOC
;
2564 newbsize
= round_page(newbsize
);
2568 (vm_offset_t
) bp
->b_data
+ bp
->b_bufsize
,
2569 (vm_offset_t
) bp
->b_data
+ newbsize
);
2571 bcopy(origbuf
, bp
->b_data
, origbufsize
);
2572 kfree(origbuf
, M_BIOBUF
);
2579 newbsize
= (size
+ DEV_BSIZE
- 1) & ~(DEV_BSIZE
- 1);
2580 desiredpages
= ((int)(bp
->b_loffset
& PAGE_MASK
) +
2581 newbsize
+ PAGE_MASK
) >> PAGE_SHIFT
;
2582 KKASSERT(desiredpages
<= XIO_INTERNAL_PAGES
);
2584 if (bp
->b_flags
& B_MALLOC
)
2585 panic("allocbuf: VMIO buffer can't be malloced");
2587 * Set B_CACHE initially if buffer is 0 length or will become
2590 if (size
== 0 || bp
->b_bufsize
== 0)
2591 bp
->b_flags
|= B_CACHE
;
2593 if (newbsize
< bp
->b_bufsize
) {
2595 * DEV_BSIZE aligned new buffer size is less then the
2596 * DEV_BSIZE aligned existing buffer size. Figure out
2597 * if we have to remove any pages.
2599 if (desiredpages
< bp
->b_xio
.xio_npages
) {
2600 for (i
= desiredpages
; i
< bp
->b_xio
.xio_npages
; i
++) {
2602 * the page is not freed here -- it
2603 * is the responsibility of
2604 * vnode_pager_setsize
2606 m
= bp
->b_xio
.xio_pages
[i
];
2607 KASSERT(m
!= bogus_page
,
2608 ("allocbuf: bogus page found"));
2609 while (vm_page_sleep_busy(m
, TRUE
, "biodep"))
2612 bp
->b_xio
.xio_pages
[i
] = NULL
;
2613 vm_page_unwire(m
, 0);
2615 pmap_qremove((vm_offset_t
) trunc_page((vm_offset_t
)bp
->b_data
) +
2616 (desiredpages
<< PAGE_SHIFT
), (bp
->b_xio
.xio_npages
- desiredpages
));
2617 bp
->b_xio
.xio_npages
= desiredpages
;
2619 } else if (size
> bp
->b_bcount
) {
2621 * We are growing the buffer, possibly in a
2622 * byte-granular fashion.
2630 * Step 1, bring in the VM pages from the object,
2631 * allocating them if necessary. We must clear
2632 * B_CACHE if these pages are not valid for the
2633 * range covered by the buffer.
2635 * critical section protection is required to protect
2636 * against interrupts unbusying and freeing pages
2637 * between our vm_page_lookup() and our
2638 * busycheck/wiring call.
2644 while (bp
->b_xio
.xio_npages
< desiredpages
) {
2648 pi
= OFF_TO_IDX(bp
->b_loffset
) + bp
->b_xio
.xio_npages
;
2649 if ((m
= vm_page_lookup(obj
, pi
)) == NULL
) {
2651 * note: must allocate system pages
2652 * since blocking here could intefere
2653 * with paging I/O, no matter which
2656 m
= vm_page_alloc(obj
, pi
, VM_ALLOC_NORMAL
| VM_ALLOC_SYSTEM
);
2659 vm_pageout_deficit
+= desiredpages
-
2660 bp
->b_xio
.xio_npages
;
2664 bp
->b_flags
&= ~B_CACHE
;
2665 bp
->b_xio
.xio_pages
[bp
->b_xio
.xio_npages
] = m
;
2666 ++bp
->b_xio
.xio_npages
;
2672 * We found a page. If we have to sleep on it,
2673 * retry because it might have gotten freed out
2676 * We can only test PG_BUSY here. Blocking on
2677 * m->busy might lead to a deadlock:
2679 * vm_fault->getpages->cluster_read->allocbuf
2683 if (vm_page_sleep_busy(m
, FALSE
, "pgtblk"))
2687 * We have a good page. Should we wakeup the
2690 if ((curthread
!= pagethread
) &&
2691 ((m
->queue
- m
->pc
) == PQ_CACHE
) &&
2692 ((vmstats
.v_free_count
+ vmstats
.v_cache_count
) <
2693 (vmstats
.v_free_min
+ vmstats
.v_cache_min
))) {
2694 pagedaemon_wakeup();
2696 vm_page_flag_clear(m
, PG_ZERO
);
2698 bp
->b_xio
.xio_pages
[bp
->b_xio
.xio_npages
] = m
;
2699 ++bp
->b_xio
.xio_npages
;
2704 * Step 2. We've loaded the pages into the buffer,
2705 * we have to figure out if we can still have B_CACHE
2706 * set. Note that B_CACHE is set according to the
2707 * byte-granular range ( bcount and size ), not the
2708 * aligned range ( newbsize ).
2710 * The VM test is against m->valid, which is DEV_BSIZE
2711 * aligned. Needless to say, the validity of the data
2712 * needs to also be DEV_BSIZE aligned. Note that this
2713 * fails with NFS if the server or some other client
2714 * extends the file's EOF. If our buffer is resized,
2715 * B_CACHE may remain set! XXX
2718 toff
= bp
->b_bcount
;
2719 tinc
= PAGE_SIZE
- ((bp
->b_loffset
+ toff
) & PAGE_MASK
);
2721 while ((bp
->b_flags
& B_CACHE
) && toff
< size
) {
2724 if (tinc
> (size
- toff
))
2727 pi
= ((bp
->b_loffset
& PAGE_MASK
) + toff
) >>
2735 bp
->b_xio
.xio_pages
[pi
]
2742 * Step 3, fixup the KVM pmap. Remember that
2743 * bp->b_data is relative to bp->b_loffset, but
2744 * bp->b_loffset may be offset into the first page.
2747 bp
->b_data
= (caddr_t
)
2748 trunc_page((vm_offset_t
)bp
->b_data
);
2750 (vm_offset_t
)bp
->b_data
,
2751 bp
->b_xio
.xio_pages
,
2752 bp
->b_xio
.xio_npages
2754 bp
->b_data
= (caddr_t
)((vm_offset_t
)bp
->b_data
|
2755 (vm_offset_t
)(bp
->b_loffset
& PAGE_MASK
));
2758 if (newbsize
< bp
->b_bufsize
)
2760 bp
->b_bufsize
= newbsize
; /* actual buffer allocation */
2761 bp
->b_bcount
= size
; /* requested buffer size */
2768 * Wait for buffer I/O completion, returning error status. The buffer
2769 * is left locked on return. B_EINTR is converted into an EINTR error
2772 * NOTE! The original b_cmd is lost on return, since b_cmd will be
2773 * set to BUF_CMD_DONE.
2776 biowait(struct buf
*bp
)
2779 while (bp
->b_cmd
!= BUF_CMD_DONE
) {
2780 if (bp
->b_cmd
== BUF_CMD_READ
)
2781 tsleep(bp
, 0, "biord", 0);
2783 tsleep(bp
, 0, "biowr", 0);
2786 if (bp
->b_flags
& B_EINTR
) {
2787 bp
->b_flags
&= ~B_EINTR
;
2790 if (bp
->b_flags
& B_ERROR
) {
2791 return (bp
->b_error
? bp
->b_error
: EIO
);
2798 * This associates a tracking count with an I/O. vn_strategy() and
2799 * dev_dstrategy() do this automatically but there are a few cases
2800 * where a vnode or device layer is bypassed when a block translation
2801 * is cached. In such cases bio_start_transaction() may be called on
2802 * the bypassed layers so the system gets an I/O in progress indication
2803 * for those higher layers.
2806 bio_start_transaction(struct bio
*bio
, struct bio_track
*track
)
2808 bio
->bio_track
= track
;
2809 atomic_add_int(&track
->bk_active
, 1);
2813 * Initiate I/O on a vnode.
2816 vn_strategy(struct vnode
*vp
, struct bio
*bio
)
2818 struct bio_track
*track
;
2820 KKASSERT(bio
->bio_buf
->b_cmd
!= BUF_CMD_DONE
);
2821 if (bio
->bio_buf
->b_cmd
== BUF_CMD_READ
)
2822 track
= &vp
->v_track_read
;
2824 track
= &vp
->v_track_write
;
2825 bio
->bio_track
= track
;
2826 atomic_add_int(&track
->bk_active
, 1);
2827 vop_strategy(*vp
->v_ops
, vp
, bio
);
2834 * Finish I/O on a buffer, optionally calling a completion function.
2835 * This is usually called from an interrupt so process blocking is
2838 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2839 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
2840 * assuming B_INVAL is clear.
2842 * For the VMIO case, we set B_CACHE if the op was a read and no
2843 * read error occured, or if the op was a write. B_CACHE is never
2844 * set if the buffer is invalid or otherwise uncacheable.
2846 * biodone does not mess with B_INVAL, allowing the I/O routine or the
2847 * initiator to leave B_INVAL set to brelse the buffer out of existance
2848 * in the biodone routine.
2851 biodone(struct bio
*bio
)
2853 struct buf
*bp
= bio
->bio_buf
;
2858 KASSERT(BUF_REFCNTNB(bp
) > 0,
2859 ("biodone: bp %p not busy %d", bp
, BUF_REFCNTNB(bp
)));
2860 KASSERT(bp
->b_cmd
!= BUF_CMD_DONE
,
2861 ("biodone: bp %p already done!", bp
));
2863 runningbufwakeup(bp
);
2866 * Run up the chain of BIO's. Leave b_cmd intact for the duration.
2869 biodone_t
*done_func
;
2870 struct bio_track
*track
;
2873 * BIO tracking. Most but not all BIOs are tracked.
2875 if ((track
= bio
->bio_track
) != NULL
) {
2876 atomic_subtract_int(&track
->bk_active
, 1);
2877 if (track
->bk_active
< 0) {
2878 panic("biodone: bad active count bio %p\n",
2881 if (track
->bk_waitflag
) {
2882 track
->bk_waitflag
= 0;
2885 bio
->bio_track
= NULL
;
2889 * A bio_done function terminates the loop. The function
2890 * will be responsible for any further chaining and/or
2891 * buffer management.
2893 * WARNING! The done function can deallocate the buffer!
2895 if ((done_func
= bio
->bio_done
) != NULL
) {
2896 bio
->bio_done
= NULL
;
2901 bio
= bio
->bio_prev
;
2905 bp
->b_cmd
= BUF_CMD_DONE
;
2908 * Only reads and writes are processed past this point.
2910 if (cmd
!= BUF_CMD_READ
&& cmd
!= BUF_CMD_WRITE
) {
2917 * Warning: softupdates may re-dirty the buffer.
2919 if (LIST_FIRST(&bp
->b_dep
) != NULL
)
2922 if (bp
->b_flags
& B_VMIO
) {
2928 struct vnode
*vp
= bp
->b_vp
;
2932 #if defined(VFS_BIO_DEBUG)
2933 if (vp
->v_auxrefs
== 0)
2934 panic("biodone: zero vnode hold count");
2935 if ((vp
->v_flag
& VOBJBUF
) == 0)
2936 panic("biodone: vnode is not setup for merged cache");
2939 foff
= bp
->b_loffset
;
2940 KASSERT(foff
!= NOOFFSET
, ("biodone: no buffer offset"));
2941 KASSERT(obj
!= NULL
, ("biodone: missing VM object"));
2943 #if defined(VFS_BIO_DEBUG)
2944 if (obj
->paging_in_progress
< bp
->b_xio
.xio_npages
) {
2945 kprintf("biodone: paging in progress(%d) < bp->b_xio.xio_npages(%d)\n",
2946 obj
->paging_in_progress
, bp
->b_xio
.xio_npages
);
2951 * Set B_CACHE if the op was a normal read and no error
2952 * occured. B_CACHE is set for writes in the b*write()
2955 iosize
= bp
->b_bcount
- bp
->b_resid
;
2956 if (cmd
== BUF_CMD_READ
&& (bp
->b_flags
& (B_INVAL
|B_NOCACHE
|B_ERROR
)) == 0) {
2957 bp
->b_flags
|= B_CACHE
;
2960 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
2964 resid
= ((foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
) - foff
;
2969 * cleanup bogus pages, restoring the originals. Since
2970 * the originals should still be wired, we don't have
2971 * to worry about interrupt/freeing races destroying
2972 * the VM object association.
2974 m
= bp
->b_xio
.xio_pages
[i
];
2975 if (m
== bogus_page
) {
2977 m
= vm_page_lookup(obj
, OFF_TO_IDX(foff
));
2979 panic("biodone: page disappeared");
2980 bp
->b_xio
.xio_pages
[i
] = m
;
2981 pmap_qenter(trunc_page((vm_offset_t
)bp
->b_data
),
2982 bp
->b_xio
.xio_pages
, bp
->b_xio
.xio_npages
);
2984 #if defined(VFS_BIO_DEBUG)
2985 if (OFF_TO_IDX(foff
) != m
->pindex
) {
2987 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
2988 (unsigned long)foff
, m
->pindex
);
2993 * In the write case, the valid and clean bits are
2994 * already changed correctly ( see bdwrite() ), so we
2995 * only need to do this here in the read case.
2997 if (cmd
== BUF_CMD_READ
&& !bogusflag
&& resid
> 0) {
2998 vfs_page_set_valid(bp
, foff
, i
, m
);
3000 vm_page_flag_clear(m
, PG_ZERO
);
3003 * when debugging new filesystems or buffer I/O methods, this
3004 * is the most common error that pops up. if you see this, you
3005 * have not set the page busy flag correctly!!!
3008 kprintf("biodone: page busy < 0, "
3009 "pindex: %d, foff: 0x(%x,%x), "
3010 "resid: %d, index: %d\n",
3011 (int) m
->pindex
, (int)(foff
>> 32),
3012 (int) foff
& 0xffffffff, resid
, i
);
3013 if (!vn_isdisk(vp
, NULL
))
3014 kprintf(" iosize: %ld, loffset: %lld, flags: 0x%08x, npages: %d\n",
3015 bp
->b_vp
->v_mount
->mnt_stat
.f_iosize
,
3017 bp
->b_flags
, bp
->b_xio
.xio_npages
);
3019 kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
3021 bp
->b_flags
, bp
->b_xio
.xio_npages
);
3022 kprintf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
3023 m
->valid
, m
->dirty
, m
->wire_count
);
3024 panic("biodone: page busy < 0");
3026 vm_page_io_finish(m
);
3027 vm_object_pip_subtract(obj
, 1);
3028 foff
= (foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
;
3032 vm_object_pip_wakeupn(obj
, 0);
3036 * For asynchronous completions, release the buffer now. The brelse
3037 * will do a wakeup there if necessary - so no need to do a wakeup
3038 * here in the async case. The sync case always needs to do a wakeup.
3041 if (bp
->b_flags
& B_ASYNC
) {
3042 if ((bp
->b_flags
& (B_NOCACHE
| B_INVAL
| B_ERROR
| B_RELBUF
)) != 0)
3055 * This routine is called in lieu of iodone in the case of
3056 * incomplete I/O. This keeps the busy status for pages
3060 vfs_unbusy_pages(struct buf
*bp
)
3064 runningbufwakeup(bp
);
3065 if (bp
->b_flags
& B_VMIO
) {
3066 struct vnode
*vp
= bp
->b_vp
;
3071 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3072 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
3075 * When restoring bogus changes the original pages
3076 * should still be wired, so we are in no danger of
3077 * losing the object association and do not need
3078 * critical section protection particularly.
3080 if (m
== bogus_page
) {
3081 m
= vm_page_lookup(obj
, OFF_TO_IDX(bp
->b_loffset
) + i
);
3083 panic("vfs_unbusy_pages: page missing");
3085 bp
->b_xio
.xio_pages
[i
] = m
;
3086 pmap_qenter(trunc_page((vm_offset_t
)bp
->b_data
),
3087 bp
->b_xio
.xio_pages
, bp
->b_xio
.xio_npages
);
3089 vm_object_pip_subtract(obj
, 1);
3090 vm_page_flag_clear(m
, PG_ZERO
);
3091 vm_page_io_finish(m
);
3093 vm_object_pip_wakeupn(obj
, 0);
3098 * vfs_page_set_valid:
3100 * Set the valid bits in a page based on the supplied offset. The
3101 * range is restricted to the buffer's size.
3103 * This routine is typically called after a read completes.
3106 vfs_page_set_valid(struct buf
*bp
, vm_ooffset_t off
, int pageno
, vm_page_t m
)
3108 vm_ooffset_t soff
, eoff
;
3111 * Start and end offsets in buffer. eoff - soff may not cross a
3112 * page boundry or cross the end of the buffer. The end of the
3113 * buffer, in this case, is our file EOF, not the allocation size
3117 eoff
= (off
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
;
3118 if (eoff
> bp
->b_loffset
+ bp
->b_bcount
)
3119 eoff
= bp
->b_loffset
+ bp
->b_bcount
;
3122 * Set valid range. This is typically the entire buffer and thus the
3126 vm_page_set_validclean(
3128 (vm_offset_t
) (soff
& PAGE_MASK
),
3129 (vm_offset_t
) (eoff
- soff
)
3137 * This routine is called before a device strategy routine.
3138 * It is used to tell the VM system that paging I/O is in
3139 * progress, and treat the pages associated with the buffer
3140 * almost as being PG_BUSY. Also the object 'paging_in_progress'
3141 * flag is handled to make sure that the object doesn't become
3144 * Since I/O has not been initiated yet, certain buffer flags
3145 * such as B_ERROR or B_INVAL may be in an inconsistant state
3146 * and should be ignored.
3149 vfs_busy_pages(struct vnode
*vp
, struct buf
*bp
)
3152 struct lwp
*lp
= curthread
->td_lwp
;
3155 * The buffer's I/O command must already be set. If reading,
3156 * B_CACHE must be 0 (double check against callers only doing
3157 * I/O when B_CACHE is 0).
3159 KKASSERT(bp
->b_cmd
!= BUF_CMD_DONE
);
3160 KKASSERT(bp
->b_cmd
== BUF_CMD_WRITE
|| (bp
->b_flags
& B_CACHE
) == 0);
3162 if (bp
->b_flags
& B_VMIO
) {
3167 foff
= bp
->b_loffset
;
3168 KASSERT(bp
->b_loffset
!= NOOFFSET
,
3169 ("vfs_busy_pages: no buffer offset"));
3173 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3174 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
3175 if (vm_page_sleep_busy(m
, FALSE
, "vbpage"))
3180 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3181 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
3183 vm_page_flag_clear(m
, PG_ZERO
);
3184 if ((bp
->b_flags
& B_CLUSTER
) == 0) {
3185 vm_object_pip_add(obj
, 1);
3186 vm_page_io_start(m
);
3190 * When readying a vnode-backed buffer for a write
3191 * we must zero-fill any invalid portions of the
3194 * When readying a vnode-backed buffer for a read
3195 * we must replace any dirty pages with a bogus
3196 * page so we do not destroy dirty data when
3197 * filling in gaps. Dirty pages might not
3198 * necessarily be marked dirty yet, so use m->valid
3199 * as a reasonable test.
3201 * Bogus page replacement is, uh, bogus. We need
3202 * to find a better way.
3204 vm_page_protect(m
, VM_PROT_NONE
);
3205 if (bp
->b_cmd
== BUF_CMD_WRITE
) {
3206 vfs_page_set_valid(bp
, foff
, i
, m
);
3207 } else if (m
->valid
== VM_PAGE_BITS_ALL
) {
3208 bp
->b_xio
.xio_pages
[i
] = bogus_page
;
3211 foff
= (foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
;
3214 pmap_qenter(trunc_page((vm_offset_t
)bp
->b_data
),
3215 bp
->b_xio
.xio_pages
, bp
->b_xio
.xio_npages
);
3219 * This is the easiest place to put the process accounting for the I/O
3223 if (bp
->b_cmd
== BUF_CMD_READ
)
3224 lp
->lwp_ru
.ru_inblock
++;
3226 lp
->lwp_ru
.ru_oublock
++;
3233 * Tell the VM system that the pages associated with this buffer
3234 * are clean. This is used for delayed writes where the data is
3235 * going to go to disk eventually without additional VM intevention.
3237 * Note that while we only really need to clean through to b_bcount, we
3238 * just go ahead and clean through to b_bufsize.
3241 vfs_clean_pages(struct buf
*bp
)
3245 if (bp
->b_flags
& B_VMIO
) {
3248 foff
= bp
->b_loffset
;
3249 KASSERT(foff
!= NOOFFSET
, ("vfs_clean_pages: no buffer offset"));
3250 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3251 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
3252 vm_ooffset_t noff
= (foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
;
3253 vm_ooffset_t eoff
= noff
;
3255 if (eoff
> bp
->b_loffset
+ bp
->b_bufsize
)
3256 eoff
= bp
->b_loffset
+ bp
->b_bufsize
;
3257 vfs_page_set_valid(bp
, foff
, i
, m
);
3258 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3265 * vfs_bio_set_validclean:
3267 * Set the range within the buffer to valid and clean. The range is
3268 * relative to the beginning of the buffer, b_loffset. Note that
3269 * b_loffset itself may be offset from the beginning of the first page.
3273 vfs_bio_set_validclean(struct buf
*bp
, int base
, int size
)
3275 if (bp
->b_flags
& B_VMIO
) {
3280 * Fixup base to be relative to beginning of first page.
3281 * Set initial n to be the maximum number of bytes in the
3282 * first page that can be validated.
3285 base
+= (bp
->b_loffset
& PAGE_MASK
);
3286 n
= PAGE_SIZE
- (base
& PAGE_MASK
);
3288 for (i
= base
/ PAGE_SIZE
; size
> 0 && i
< bp
->b_xio
.xio_npages
; ++i
) {
3289 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
3294 vm_page_set_validclean(m
, base
& PAGE_MASK
, n
);
3305 * Clear a buffer. This routine essentially fakes an I/O, so we need
3306 * to clear B_ERROR and B_INVAL.
3308 * Note that while we only theoretically need to clear through b_bcount,
3309 * we go ahead and clear through b_bufsize.
3313 vfs_bio_clrbuf(struct buf
*bp
)
3317 if ((bp
->b_flags
& (B_VMIO
| B_MALLOC
)) == B_VMIO
) {
3318 bp
->b_flags
&= ~(B_INVAL
|B_ERROR
);
3319 if ((bp
->b_xio
.xio_npages
== 1) && (bp
->b_bufsize
< PAGE_SIZE
) &&
3320 (bp
->b_loffset
& PAGE_MASK
) == 0) {
3321 mask
= (1 << (bp
->b_bufsize
/ DEV_BSIZE
)) - 1;
3322 if ((bp
->b_xio
.xio_pages
[0]->valid
& mask
) == mask
) {
3326 if (((bp
->b_xio
.xio_pages
[0]->flags
& PG_ZERO
) == 0) &&
3327 ((bp
->b_xio
.xio_pages
[0]->valid
& mask
) == 0)) {
3328 bzero(bp
->b_data
, bp
->b_bufsize
);
3329 bp
->b_xio
.xio_pages
[0]->valid
|= mask
;
3334 ea
= sa
= bp
->b_data
;
3335 for(i
=0;i
<bp
->b_xio
.xio_npages
;i
++,sa
=ea
) {
3336 int j
= ((vm_offset_t
)sa
& PAGE_MASK
) / DEV_BSIZE
;
3337 ea
= (caddr_t
)trunc_page((vm_offset_t
)sa
+ PAGE_SIZE
);
3338 ea
= (caddr_t
)(vm_offset_t
)ulmin(
3339 (u_long
)(vm_offset_t
)ea
,
3340 (u_long
)(vm_offset_t
)bp
->b_data
+ bp
->b_bufsize
);
3341 mask
= ((1 << ((ea
- sa
) / DEV_BSIZE
)) - 1) << j
;
3342 if ((bp
->b_xio
.xio_pages
[i
]->valid
& mask
) == mask
)
3344 if ((bp
->b_xio
.xio_pages
[i
]->valid
& mask
) == 0) {
3345 if ((bp
->b_xio
.xio_pages
[i
]->flags
& PG_ZERO
) == 0) {
3349 for (; sa
< ea
; sa
+= DEV_BSIZE
, j
++) {
3350 if (((bp
->b_xio
.xio_pages
[i
]->flags
& PG_ZERO
) == 0) &&
3351 (bp
->b_xio
.xio_pages
[i
]->valid
& (1<<j
)) == 0)
3352 bzero(sa
, DEV_BSIZE
);
3355 bp
->b_xio
.xio_pages
[i
]->valid
|= mask
;
3356 vm_page_flag_clear(bp
->b_xio
.xio_pages
[i
], PG_ZERO
);
3365 * vm_hold_load_pages:
3367 * Load pages into the buffer's address space. The pages are
3368 * allocated from the kernel object in order to reduce interference
3369 * with the any VM paging I/O activity. The range of loaded
3370 * pages will be wired.
3372 * If a page cannot be allocated, the 'pagedaemon' is woken up to
3373 * retrieve the full range (to - from) of pages.
3377 vm_hold_load_pages(struct buf
*bp
, vm_offset_t from
, vm_offset_t to
)
3383 to
= round_page(to
);
3384 from
= round_page(from
);
3385 index
= (from
- trunc_page((vm_offset_t
)bp
->b_data
)) >> PAGE_SHIFT
;
3387 for (pg
= from
; pg
< to
; pg
+= PAGE_SIZE
, index
++) {
3392 * Note: must allocate system pages since blocking here
3393 * could intefere with paging I/O, no matter which
3396 p
= vm_page_alloc(&kernel_object
,
3398 VM_ALLOC_NORMAL
| VM_ALLOC_SYSTEM
);
3400 vm_pageout_deficit
+= (to
- from
) >> PAGE_SHIFT
;
3405 p
->valid
= VM_PAGE_BITS_ALL
;
3406 vm_page_flag_clear(p
, PG_ZERO
);
3407 pmap_kenter(pg
, VM_PAGE_TO_PHYS(p
));
3408 bp
->b_xio
.xio_pages
[index
] = p
;
3411 bp
->b_xio
.xio_npages
= index
;
3415 * vm_hold_free_pages:
3417 * Return pages associated with the buffer back to the VM system.
3419 * The range of pages underlying the buffer's address space will
3420 * be unmapped and un-wired.
3423 vm_hold_free_pages(struct buf
*bp
, vm_offset_t from
, vm_offset_t to
)
3427 int index
, newnpages
;
3429 from
= round_page(from
);
3430 to
= round_page(to
);
3431 newnpages
= index
= (from
- trunc_page((vm_offset_t
)bp
->b_data
)) >> PAGE_SHIFT
;
3433 for (pg
= from
; pg
< to
; pg
+= PAGE_SIZE
, index
++) {
3434 p
= bp
->b_xio
.xio_pages
[index
];
3435 if (p
&& (index
< bp
->b_xio
.xio_npages
)) {
3437 kprintf("vm_hold_free_pages: doffset: %lld, loffset: %lld\n",
3438 bp
->b_bio2
.bio_offset
, bp
->b_loffset
);
3440 bp
->b_xio
.xio_pages
[index
] = NULL
;
3443 vm_page_unwire(p
, 0);
3447 bp
->b_xio
.xio_npages
= newnpages
;
3453 * Map a user buffer into KVM via a pbuf. On return the buffer's
3454 * b_data, b_bufsize, and b_bcount will be set, and its XIO page array
3458 vmapbuf(struct buf
*bp
, caddr_t udata
, int bytes
)
3469 * bp had better have a command and it better be a pbuf.
3471 KKASSERT(bp
->b_cmd
!= BUF_CMD_DONE
);
3472 KKASSERT(bp
->b_flags
& B_PAGING
);
3478 * Map the user data into KVM. Mappings have to be page-aligned.
3480 addr
= (caddr_t
)trunc_page((vm_offset_t
)udata
);
3483 vmprot
= VM_PROT_READ
;
3484 if (bp
->b_cmd
== BUF_CMD_READ
)
3485 vmprot
|= VM_PROT_WRITE
;
3487 while (addr
< udata
+ bytes
) {
3489 * Do the vm_fault if needed; do the copy-on-write thing
3490 * when reading stuff off device into memory.
3492 * vm_fault_page*() returns a held VM page.
3494 va
= (addr
>= udata
) ? (vm_offset_t
)addr
: (vm_offset_t
)udata
;
3495 va
= trunc_page(va
);
3497 m
= vm_fault_page_quick(va
, vmprot
, &error
);
3499 for (i
= 0; i
< pidx
; ++i
) {
3500 vm_page_unhold(bp
->b_xio
.xio_pages
[i
]);
3501 bp
->b_xio
.xio_pages
[i
] = NULL
;
3505 bp
->b_xio
.xio_pages
[pidx
] = m
;
3511 * Map the page array and set the buffer fields to point to
3512 * the mapped data buffer.
3514 if (pidx
> btoc(MAXPHYS
))
3515 panic("vmapbuf: mapped more than MAXPHYS");
3516 pmap_qenter((vm_offset_t
)bp
->b_kvabase
, bp
->b_xio
.xio_pages
, pidx
);
3518 bp
->b_xio
.xio_npages
= pidx
;
3519 bp
->b_data
= bp
->b_kvabase
+ ((int)(intptr_t)udata
& PAGE_MASK
);
3520 bp
->b_bcount
= bytes
;
3521 bp
->b_bufsize
= bytes
;
3528 * Free the io map PTEs associated with this IO operation.
3529 * We also invalidate the TLB entries and restore the original b_addr.
3532 vunmapbuf(struct buf
*bp
)
3537 KKASSERT(bp
->b_flags
& B_PAGING
);
3539 npages
= bp
->b_xio
.xio_npages
;
3540 pmap_qremove(trunc_page((vm_offset_t
)bp
->b_data
), npages
);
3541 for (pidx
= 0; pidx
< npages
; ++pidx
) {
3542 vm_page_unhold(bp
->b_xio
.xio_pages
[pidx
]);
3543 bp
->b_xio
.xio_pages
[pidx
] = NULL
;
3545 bp
->b_xio
.xio_npages
= 0;
3546 bp
->b_data
= bp
->b_kvabase
;
3550 * Scan all buffers in the system and issue the callback.
3553 scan_all_buffers(int (*callback
)(struct buf
*, void *), void *info
)
3559 for (n
= 0; n
< nbuf
; ++n
) {
3560 if ((error
= callback(&buf
[n
], info
)) < 0) {
3570 * print out statistics from the current status of the buffer pool
3571 * this can be toggeled by the system control option debug.syncprt
3580 int counts
[(MAXBSIZE
/ PAGE_SIZE
) + 1];
3581 static char *bname
[3] = { "LOCKED", "LRU", "AGE" };
3583 for (dp
= bufqueues
, i
= 0; dp
< &bufqueues
[3]; dp
++, i
++) {
3585 for (j
= 0; j
<= MAXBSIZE
/PAGE_SIZE
; j
++)
3588 TAILQ_FOREACH(bp
, dp
, b_freelist
) {
3589 counts
[bp
->b_bufsize
/PAGE_SIZE
]++;
3593 kprintf("%s: total-%d", bname
[i
], count
);
3594 for (j
= 0; j
<= MAXBSIZE
/PAGE_SIZE
; j
++)
3596 kprintf(", %d-%d", j
* PAGE_SIZE
, counts
[j
]);
3604 DB_SHOW_COMMAND(buffer
, db_show_buffer
)
3607 struct buf
*bp
= (struct buf
*)addr
;
3610 db_printf("usage: show buffer <addr>\n");
3614 db_printf("b_flags = 0x%b\n", (u_int
)bp
->b_flags
, PRINT_BUF_FLAGS
);
3615 db_printf("b_cmd = %d\n", bp
->b_cmd
);
3616 db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
3617 "b_resid = %d\n, b_data = %p, "
3618 "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
3619 bp
->b_error
, bp
->b_bufsize
, bp
->b_bcount
, bp
->b_resid
,
3620 bp
->b_data
, bp
->b_bio2
.bio_offset
, (bp
->b_bio2
.bio_next
? bp
->b_bio2
.bio_next
->bio_offset
: (off_t
)-1));
3621 if (bp
->b_xio
.xio_npages
) {
3623 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
3624 bp
->b_xio
.xio_npages
);
3625 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3627 m
= bp
->b_xio
.xio_pages
[i
];
3628 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m
->object
,
3629 (u_long
)m
->pindex
, (u_long
)VM_PAGE_TO_PHYS(m
));
3630 if ((i
+ 1) < bp
->b_xio
.xio_npages
)