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.69 2006/04/30 18:52: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 <vm/vm_page2.h>
64 #define BUFFER_QUEUES 6
66 BQUEUE_NONE
, /* not on any queue */
67 BQUEUE_LOCKED
, /* locked buffers */
68 BQUEUE_CLEAN
, /* non-B_DELWRI buffers */
69 BQUEUE_DIRTY
, /* B_DELWRI buffers */
70 BQUEUE_EMPTYKVA
, /* empty buffer headers with KVA assignment */
71 BQUEUE_EMPTY
/* empty buffer headers */
73 TAILQ_HEAD(bqueues
, buf
) bufqueues
[BUFFER_QUEUES
];
75 static MALLOC_DEFINE(M_BIOBUF
, "BIO buffer", "BIO buffer");
77 struct bio_ops bioops
; /* I/O operation notification */
79 struct buf
*buf
; /* buffer header pool */
81 static void vm_hold_free_pages(struct buf
* bp
, vm_offset_t from
,
83 static void vm_hold_load_pages(struct buf
* bp
, vm_offset_t from
,
85 static void vfs_page_set_valid(struct buf
*bp
, vm_ooffset_t off
,
86 int pageno
, vm_page_t m
);
87 static void vfs_clean_pages(struct buf
* bp
);
88 static void vfs_setdirty(struct buf
*bp
);
89 static void vfs_vmio_release(struct buf
*bp
);
90 static int flushbufqueues(void);
92 static int bd_request
;
94 static void buf_daemon (void);
96 * bogus page -- for I/O to/from partially complete buffers
97 * this is a temporary solution to the problem, but it is not
98 * really that bad. it would be better to split the buffer
99 * for input in the case of buffers partially already in memory,
100 * but the code is intricate enough already.
102 vm_page_t bogus_page
;
105 static int bufspace
, maxbufspace
,
106 bufmallocspace
, maxbufmallocspace
, lobufspace
, hibufspace
;
107 static int bufreusecnt
, bufdefragcnt
, buffreekvacnt
;
108 static int needsbuffer
;
109 static int lorunningspace
, hirunningspace
, runningbufreq
;
110 static int numdirtybuffers
, lodirtybuffers
, hidirtybuffers
;
111 static int numfreebuffers
, lofreebuffers
, hifreebuffers
;
112 static int getnewbufcalls
;
113 static int getnewbufrestarts
;
116 * Sysctls for operational control of the buffer cache.
118 SYSCTL_INT(_vfs
, OID_AUTO
, lodirtybuffers
, CTLFLAG_RW
, &lodirtybuffers
, 0,
119 "Number of dirty buffers to flush before bufdaemon becomes inactive");
120 SYSCTL_INT(_vfs
, OID_AUTO
, hidirtybuffers
, CTLFLAG_RW
, &hidirtybuffers
, 0,
121 "High watermark used to trigger explicit flushing of dirty buffers");
122 SYSCTL_INT(_vfs
, OID_AUTO
, lofreebuffers
, CTLFLAG_RW
, &lofreebuffers
, 0,
123 "Low watermark for special reserve in low-memory situations");
124 SYSCTL_INT(_vfs
, OID_AUTO
, hifreebuffers
, CTLFLAG_RW
, &hifreebuffers
, 0,
125 "High watermark for special reserve in low-memory situations");
126 SYSCTL_INT(_vfs
, OID_AUTO
, lorunningspace
, CTLFLAG_RW
, &lorunningspace
, 0,
127 "Minimum amount of buffer space required for active I/O");
128 SYSCTL_INT(_vfs
, OID_AUTO
, hirunningspace
, CTLFLAG_RW
, &hirunningspace
, 0,
129 "Maximum amount of buffer space to usable for active I/O");
131 * Sysctls determining current state of the buffer cache.
133 SYSCTL_INT(_vfs
, OID_AUTO
, numdirtybuffers
, CTLFLAG_RD
, &numdirtybuffers
, 0,
134 "Pending number of dirty buffers");
135 SYSCTL_INT(_vfs
, OID_AUTO
, numfreebuffers
, CTLFLAG_RD
, &numfreebuffers
, 0,
136 "Number of free buffers on the buffer cache free list");
137 SYSCTL_INT(_vfs
, OID_AUTO
, runningbufspace
, CTLFLAG_RD
, &runningbufspace
, 0,
138 "I/O bytes currently in progress due to asynchronous writes");
139 SYSCTL_INT(_vfs
, OID_AUTO
, maxbufspace
, CTLFLAG_RD
, &maxbufspace
, 0,
140 "Hard limit on maximum amount of memory usable for buffer space");
141 SYSCTL_INT(_vfs
, OID_AUTO
, hibufspace
, CTLFLAG_RD
, &hibufspace
, 0,
142 "Soft limit on maximum amount of memory usable for buffer space");
143 SYSCTL_INT(_vfs
, OID_AUTO
, lobufspace
, CTLFLAG_RD
, &lobufspace
, 0,
144 "Minimum amount of memory to reserve for system buffer space");
145 SYSCTL_INT(_vfs
, OID_AUTO
, bufspace
, CTLFLAG_RD
, &bufspace
, 0,
146 "Amount of memory available for buffers");
147 SYSCTL_INT(_vfs
, OID_AUTO
, maxmallocbufspace
, CTLFLAG_RD
, &maxbufmallocspace
,
148 0, "Maximum amount of memory reserved for buffers using malloc");
149 SYSCTL_INT(_vfs
, OID_AUTO
, bufmallocspace
, CTLFLAG_RD
, &bufmallocspace
, 0,
150 "Amount of memory left for buffers using malloc-scheme");
151 SYSCTL_INT(_vfs
, OID_AUTO
, getnewbufcalls
, CTLFLAG_RD
, &getnewbufcalls
, 0,
152 "New buffer header acquisition requests");
153 SYSCTL_INT(_vfs
, OID_AUTO
, getnewbufrestarts
, CTLFLAG_RD
, &getnewbufrestarts
,
154 0, "New buffer header acquisition restarts");
155 SYSCTL_INT(_vfs
, OID_AUTO
, bufdefragcnt
, CTLFLAG_RD
, &bufdefragcnt
, 0,
156 "Buffer acquisition restarts due to fragmented buffer map");
157 SYSCTL_INT(_vfs
, OID_AUTO
, buffreekvacnt
, CTLFLAG_RD
, &buffreekvacnt
, 0,
158 "Amount of time KVA space was deallocated in an arbitrary buffer");
159 SYSCTL_INT(_vfs
, OID_AUTO
, bufreusecnt
, CTLFLAG_RD
, &bufreusecnt
, 0,
160 "Amount of time buffer re-use operations were successful");
161 SYSCTL_INT(_debug_sizeof
, OID_AUTO
, buf
, CTLFLAG_RD
, 0, sizeof(struct buf
),
162 "sizeof(struct buf)");
164 char *buf_wmesg
= BUF_WMESG
;
166 extern int vm_swap_size
;
168 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
169 #define VFS_BIO_NEED_DIRTYFLUSH 0x02 /* waiting for dirty buffer flush */
170 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
171 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
176 * If someone is blocked due to there being too many dirty buffers,
177 * and numdirtybuffers is now reasonable, wake them up.
181 numdirtywakeup(int level
)
183 if (numdirtybuffers
<= level
) {
184 if (needsbuffer
& VFS_BIO_NEED_DIRTYFLUSH
) {
185 needsbuffer
&= ~VFS_BIO_NEED_DIRTYFLUSH
;
186 wakeup(&needsbuffer
);
194 * Called when buffer space is potentially available for recovery.
195 * getnewbuf() will block on this flag when it is unable to free
196 * sufficient buffer space. Buffer space becomes recoverable when
197 * bp's get placed back in the queues.
204 * If someone is waiting for BUF space, wake them up. Even
205 * though we haven't freed the kva space yet, the waiting
206 * process will be able to now.
208 if (needsbuffer
& VFS_BIO_NEED_BUFSPACE
) {
209 needsbuffer
&= ~VFS_BIO_NEED_BUFSPACE
;
210 wakeup(&needsbuffer
);
217 * Accounting for I/O in progress.
221 runningbufwakeup(struct buf
*bp
)
223 if (bp
->b_runningbufspace
) {
224 runningbufspace
-= bp
->b_runningbufspace
;
225 bp
->b_runningbufspace
= 0;
226 if (runningbufreq
&& runningbufspace
<= lorunningspace
) {
228 wakeup(&runningbufreq
);
236 * Called when a buffer has been added to one of the free queues to
237 * account for the buffer and to wakeup anyone waiting for free buffers.
238 * This typically occurs when large amounts of metadata are being handled
239 * by the buffer cache ( else buffer space runs out first, usually ).
247 needsbuffer
&= ~VFS_BIO_NEED_ANY
;
248 if (numfreebuffers
>= hifreebuffers
)
249 needsbuffer
&= ~VFS_BIO_NEED_FREE
;
250 wakeup(&needsbuffer
);
255 * waitrunningbufspace()
257 * runningbufspace is a measure of the amount of I/O currently
258 * running. This routine is used in async-write situations to
259 * prevent creating huge backups of pending writes to a device.
260 * Only asynchronous writes are governed by this function.
262 * Reads will adjust runningbufspace, but will not block based on it.
263 * The read load has a side effect of reducing the allowed write load.
265 * This does NOT turn an async write into a sync write. It waits
266 * for earlier writes to complete and generally returns before the
267 * caller's write has reached the device.
270 waitrunningbufspace(void)
272 if (runningbufspace
> hirunningspace
) {
274 while (runningbufspace
> hirunningspace
) {
276 tsleep(&runningbufreq
, 0, "wdrain", 0);
283 * vfs_buf_test_cache:
285 * Called when a buffer is extended. This function clears the B_CACHE
286 * bit if the newly extended portion of the buffer does not contain
291 vfs_buf_test_cache(struct buf
*bp
,
292 vm_ooffset_t foff
, vm_offset_t off
, vm_offset_t size
,
295 if (bp
->b_flags
& B_CACHE
) {
296 int base
= (foff
+ off
) & PAGE_MASK
;
297 if (vm_page_is_valid(m
, base
, size
) == 0)
298 bp
->b_flags
&= ~B_CACHE
;
305 * Wake up the buffer daemon if the number of outstanding dirty buffers
306 * is above specified threshold 'dirtybuflevel'.
308 * The buffer daemon is explicitly woken up when (a) the pending number
309 * of dirty buffers exceeds the recovery and stall mid-point value,
310 * (b) during bwillwrite() or (c) buf freelist was exhausted.
314 bd_wakeup(int dirtybuflevel
)
316 if (bd_request
== 0 && numdirtybuffers
>= dirtybuflevel
) {
325 * Speed up the buffer cache flushing process.
338 * Load time initialisation of the buffer cache, called from machine
339 * dependant initialization code.
345 vm_offset_t bogus_offset
;
348 /* next, make a null set of free lists */
349 for (i
= 0; i
< BUFFER_QUEUES
; i
++)
350 TAILQ_INIT(&bufqueues
[i
]);
352 /* finally, initialize each buffer header and stick on empty q */
353 for (i
= 0; i
< nbuf
; i
++) {
355 bzero(bp
, sizeof *bp
);
356 bp
->b_flags
= B_INVAL
; /* we're just an empty header */
357 bp
->b_cmd
= BUF_CMD_DONE
;
358 bp
->b_qindex
= BQUEUE_EMPTY
;
360 xio_init(&bp
->b_xio
);
361 LIST_INIT(&bp
->b_dep
);
363 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_EMPTY
], bp
, b_freelist
);
367 * maxbufspace is the absolute maximum amount of buffer space we are
368 * allowed to reserve in KVM and in real terms. The absolute maximum
369 * is nominally used by buf_daemon. hibufspace is the nominal maximum
370 * used by most other processes. The differential is required to
371 * ensure that buf_daemon is able to run when other processes might
372 * be blocked waiting for buffer space.
374 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
375 * this may result in KVM fragmentation which is not handled optimally
378 maxbufspace
= nbuf
* BKVASIZE
;
379 hibufspace
= imax(3 * maxbufspace
/ 4, maxbufspace
- MAXBSIZE
* 10);
380 lobufspace
= hibufspace
- MAXBSIZE
;
382 lorunningspace
= 512 * 1024;
383 hirunningspace
= 1024 * 1024;
386 * Limit the amount of malloc memory since it is wired permanently into
387 * the kernel space. Even though this is accounted for in the buffer
388 * allocation, we don't want the malloced region to grow uncontrolled.
389 * The malloc scheme improves memory utilization significantly on average
390 * (small) directories.
392 maxbufmallocspace
= hibufspace
/ 20;
395 * Reduce the chance of a deadlock occuring by limiting the number
396 * of delayed-write dirty buffers we allow to stack up.
398 hidirtybuffers
= nbuf
/ 4 + 20;
401 * To support extreme low-memory systems, make sure hidirtybuffers cannot
402 * eat up all available buffer space. This occurs when our minimum cannot
403 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
404 * BKVASIZE'd (8K) buffers.
406 while (hidirtybuffers
* BKVASIZE
> 3 * hibufspace
/ 4) {
407 hidirtybuffers
>>= 1;
409 lodirtybuffers
= hidirtybuffers
/ 2;
412 * Try to keep the number of free buffers in the specified range,
413 * and give special processes (e.g. like buf_daemon) access to an
416 lofreebuffers
= nbuf
/ 18 + 5;
417 hifreebuffers
= 2 * lofreebuffers
;
418 numfreebuffers
= nbuf
;
421 * Maximum number of async ops initiated per buf_daemon loop. This is
422 * somewhat of a hack at the moment, we really need to limit ourselves
423 * based on the number of bytes of I/O in-transit that were initiated
427 bogus_offset
= kmem_alloc_pageable(kernel_map
, PAGE_SIZE
);
428 bogus_page
= vm_page_alloc(kernel_object
,
429 ((bogus_offset
- VM_MIN_KERNEL_ADDRESS
) >> PAGE_SHIFT
),
431 vmstats
.v_wire_count
++;
436 * Initialize the embedded bio structures
439 initbufbio(struct buf
*bp
)
441 bp
->b_bio1
.bio_buf
= bp
;
442 bp
->b_bio1
.bio_prev
= NULL
;
443 bp
->b_bio1
.bio_offset
= NOOFFSET
;
444 bp
->b_bio1
.bio_next
= &bp
->b_bio2
;
445 bp
->b_bio1
.bio_done
= NULL
;
447 bp
->b_bio2
.bio_buf
= bp
;
448 bp
->b_bio2
.bio_prev
= &bp
->b_bio1
;
449 bp
->b_bio2
.bio_offset
= NOOFFSET
;
450 bp
->b_bio2
.bio_next
= NULL
;
451 bp
->b_bio2
.bio_done
= NULL
;
455 * Reinitialize the embedded bio structures as well as any additional
456 * translation cache layers.
459 reinitbufbio(struct buf
*bp
)
463 for (bio
= &bp
->b_bio1
; bio
; bio
= bio
->bio_next
) {
464 bio
->bio_done
= NULL
;
465 bio
->bio_offset
= NOOFFSET
;
470 * Push another BIO layer onto an existing BIO and return it. The new
471 * BIO layer may already exist, holding cached translation data.
474 push_bio(struct bio
*bio
)
478 if ((nbio
= bio
->bio_next
) == NULL
) {
479 int index
= bio
- &bio
->bio_buf
->b_bio_array
[0];
480 if (index
>= NBUF_BIO
) {
481 panic("push_bio: too many layers bp %p\n",
484 nbio
= &bio
->bio_buf
->b_bio_array
[index
+ 1];
485 bio
->bio_next
= nbio
;
486 nbio
->bio_prev
= bio
;
487 nbio
->bio_buf
= bio
->bio_buf
;
488 nbio
->bio_offset
= NOOFFSET
;
489 nbio
->bio_done
= NULL
;
490 nbio
->bio_next
= NULL
;
492 KKASSERT(nbio
->bio_done
== NULL
);
497 pop_bio(struct bio
*bio
)
503 clearbiocache(struct bio
*bio
)
506 bio
->bio_offset
= NOOFFSET
;
514 * Free the KVA allocation for buffer 'bp'.
516 * Must be called from a critical section as this is the only locking for
519 * Since this call frees up buffer space, we call bufspacewakeup().
522 bfreekva(struct buf
*bp
)
528 count
= vm_map_entry_reserve(MAP_RESERVE_COUNT
);
529 vm_map_lock(buffer_map
);
530 bufspace
-= bp
->b_kvasize
;
531 vm_map_delete(buffer_map
,
532 (vm_offset_t
) bp
->b_kvabase
,
533 (vm_offset_t
) bp
->b_kvabase
+ bp
->b_kvasize
,
536 vm_map_unlock(buffer_map
);
537 vm_map_entry_release(count
);
546 * Remove the buffer from the appropriate free list.
549 bremfree(struct buf
* bp
)
554 old_qindex
= bp
->b_qindex
;
556 if (bp
->b_qindex
!= BQUEUE_NONE
) {
557 KASSERT(BUF_REFCNTNB(bp
) == 1,
558 ("bremfree: bp %p not locked",bp
));
559 TAILQ_REMOVE(&bufqueues
[bp
->b_qindex
], bp
, b_freelist
);
560 bp
->b_qindex
= BQUEUE_NONE
;
562 if (BUF_REFCNTNB(bp
) <= 1)
563 panic("bremfree: removing a buffer not on a queue");
567 * Fixup numfreebuffers count. If the buffer is invalid or not
568 * delayed-write, and it was on the EMPTY, LRU, or AGE queues,
569 * the buffer was free and we must decrement numfreebuffers.
571 if ((bp
->b_flags
& B_INVAL
) || (bp
->b_flags
& B_DELWRI
) == 0) {
576 case BQUEUE_EMPTYKVA
:
590 * Get a buffer with the specified data. Look in the cache first. We
591 * must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
592 * is set, the buffer is valid and we do not have to do anything ( see
596 bread(struct vnode
* vp
, off_t loffset
, int size
, struct buf
** bpp
)
600 bp
= getblk(vp
, loffset
, size
, 0, 0);
603 /* if not found in cache, do some I/O */
604 if ((bp
->b_flags
& B_CACHE
) == 0) {
605 KASSERT(!(bp
->b_flags
& B_ASYNC
), ("bread: illegal async bp %p", bp
));
606 bp
->b_flags
&= ~(B_ERROR
| B_INVAL
);
607 bp
->b_cmd
= BUF_CMD_READ
;
608 vfs_busy_pages(vp
, bp
);
609 vn_strategy(vp
, &bp
->b_bio1
);
610 return (biowait(bp
));
618 * Operates like bread, but also starts asynchronous I/O on
619 * read-ahead blocks. We must clear B_ERROR and B_INVAL prior
620 * to initiating I/O . If B_CACHE is set, the buffer is valid
621 * and we do not have to do anything.
624 breadn(struct vnode
*vp
, off_t loffset
, int size
, off_t
*raoffset
,
625 int *rabsize
, int cnt
, struct buf
** bpp
)
627 struct buf
*bp
, *rabp
;
629 int rv
= 0, readwait
= 0;
631 *bpp
= bp
= getblk(vp
, loffset
, size
, 0, 0);
633 /* if not found in cache, do some I/O */
634 if ((bp
->b_flags
& B_CACHE
) == 0) {
635 bp
->b_flags
&= ~(B_ERROR
| B_INVAL
);
636 bp
->b_cmd
= BUF_CMD_READ
;
637 vfs_busy_pages(vp
, bp
);
638 vn_strategy(vp
, &bp
->b_bio1
);
642 for (i
= 0; i
< cnt
; i
++, raoffset
++, rabsize
++) {
643 if (inmem(vp
, *raoffset
))
645 rabp
= getblk(vp
, *raoffset
, *rabsize
, 0, 0);
647 if ((rabp
->b_flags
& B_CACHE
) == 0) {
648 rabp
->b_flags
|= B_ASYNC
;
649 rabp
->b_flags
&= ~(B_ERROR
| B_INVAL
);
650 rabp
->b_cmd
= BUF_CMD_READ
;
651 vfs_busy_pages(vp
, rabp
);
653 vn_strategy(vp
, &rabp
->b_bio1
);
668 * Write, release buffer on completion. (Done by iodone
669 * if async). Do not bother writing anything if the buffer
672 * Note that we set B_CACHE here, indicating that buffer is
673 * fully valid and thus cacheable. This is true even of NFS
674 * now so we set it generally. This could be set either here
675 * or in biodone() since the I/O is synchronous. We put it
679 bwrite(struct buf
* bp
)
683 if (bp
->b_flags
& B_INVAL
) {
688 oldflags
= bp
->b_flags
;
690 if (BUF_REFCNTNB(bp
) == 0)
691 panic("bwrite: buffer is not busy???");
694 /* Mark the buffer clean */
697 bp
->b_flags
&= ~B_ERROR
;
698 bp
->b_flags
|= B_CACHE
;
699 bp
->b_cmd
= BUF_CMD_WRITE
;
700 vfs_busy_pages(bp
->b_vp
, bp
);
703 * Normal bwrites pipeline writes
705 bp
->b_runningbufspace
= bp
->b_bufsize
;
706 runningbufspace
+= bp
->b_runningbufspace
;
709 if (oldflags
& B_ASYNC
)
711 vn_strategy(bp
->b_vp
, &bp
->b_bio1
);
713 if ((oldflags
& B_ASYNC
) == 0) {
714 int rtval
= biowait(bp
);
717 } else if ((oldflags
& B_NOWDRAIN
) == 0) {
719 * don't allow the async write to saturate the I/O
720 * system. Deadlocks can occur only if a device strategy
721 * routine (like in VN) turns around and issues another
722 * high-level write, in which case B_NOWDRAIN is expected
723 * to be set. Otherwise we will not deadlock here because
724 * we are blocking waiting for I/O that is already in-progress
727 waitrunningbufspace();
736 * Delayed write. (Buffer is marked dirty). Do not bother writing
737 * anything if the buffer is marked invalid.
739 * Note that since the buffer must be completely valid, we can safely
740 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
741 * biodone() in order to prevent getblk from writing the buffer
745 bdwrite(struct buf
*bp
)
747 if (BUF_REFCNTNB(bp
) == 0)
748 panic("bdwrite: buffer is not busy");
750 if (bp
->b_flags
& B_INVAL
) {
757 * Set B_CACHE, indicating that the buffer is fully valid. This is
758 * true even of NFS now.
760 bp
->b_flags
|= B_CACHE
;
763 * This bmap keeps the system from needing to do the bmap later,
764 * perhaps when the system is attempting to do a sync. Since it
765 * is likely that the indirect block -- or whatever other datastructure
766 * that the filesystem needs is still in memory now, it is a good
767 * thing to do this. Note also, that if the pageout daemon is
768 * requesting a sync -- there might not be enough memory to do
769 * the bmap then... So, this is important to do.
771 if (bp
->b_bio2
.bio_offset
== NOOFFSET
) {
772 VOP_BMAP(bp
->b_vp
, bp
->b_loffset
, NULL
, &bp
->b_bio2
.bio_offset
,
777 * Set the *dirty* buffer range based upon the VM system dirty pages.
782 * We need to do this here to satisfy the vnode_pager and the
783 * pageout daemon, so that it thinks that the pages have been
784 * "cleaned". Note that since the pages are in a delayed write
785 * buffer -- the VFS layer "will" see that the pages get written
786 * out on the next sync, or perhaps the cluster will be completed.
792 * Wakeup the buffer flushing daemon if we have a lot of dirty
793 * buffers (midpoint between our recovery point and our stall
796 bd_wakeup((lodirtybuffers
+ hidirtybuffers
) / 2);
799 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
800 * due to the softdep code.
807 * Turn buffer into delayed write request by marking it B_DELWRI.
808 * B_RELBUF and B_NOCACHE must be cleared.
810 * We reassign the buffer to itself to properly update it in the
813 * Since the buffer is not on a queue, we do not update the
814 * numfreebuffers count.
816 * Must be called from a critical section.
817 * The buffer must be on BQUEUE_NONE.
820 bdirty(struct buf
*bp
)
822 KASSERT(bp
->b_qindex
== BQUEUE_NONE
, ("bdirty: buffer %p still on queue %d", bp
, bp
->b_qindex
));
823 if (bp
->b_flags
& B_NOCACHE
) {
824 printf("bdirty: clearing B_NOCACHE on buf %p\n", bp
);
825 bp
->b_flags
&= ~B_NOCACHE
;
827 if (bp
->b_flags
& B_INVAL
) {
828 printf("bdirty: warning, dirtying invalid buffer %p\n", bp
);
830 bp
->b_flags
&= ~B_RELBUF
;
832 if ((bp
->b_flags
& B_DELWRI
) == 0) {
833 bp
->b_flags
|= B_DELWRI
;
836 bd_wakeup((lodirtybuffers
+ hidirtybuffers
) / 2);
843 * Clear B_DELWRI for buffer.
845 * Since the buffer is not on a queue, we do not update the numfreebuffers
848 * Must be called from a critical section.
850 * The buffer is typically on BQUEUE_NONE but there is one case in
851 * brelse() that calls this function after placing the buffer on
856 bundirty(struct buf
*bp
)
858 if (bp
->b_flags
& B_DELWRI
) {
859 bp
->b_flags
&= ~B_DELWRI
;
862 numdirtywakeup(lodirtybuffers
);
865 * Since it is now being written, we can clear its deferred write flag.
867 bp
->b_flags
&= ~B_DEFERRED
;
873 * Asynchronous write. Start output on a buffer, but do not wait for
874 * it to complete. The buffer is released when the output completes.
876 * bwrite() ( or the VOP routine anyway ) is responsible for handling
877 * B_INVAL buffers. Not us.
880 bawrite(struct buf
* bp
)
882 bp
->b_flags
|= B_ASYNC
;
883 (void) VOP_BWRITE(bp
->b_vp
, bp
);
889 * Ordered write. Start output on a buffer, and flag it so that the
890 * device will write it in the order it was queued. The buffer is
891 * released when the output completes. bwrite() ( or the VOP routine
892 * anyway ) is responsible for handling B_INVAL buffers.
895 bowrite(struct buf
* bp
)
897 bp
->b_flags
|= B_ORDERED
| B_ASYNC
;
898 return (VOP_BWRITE(bp
->b_vp
, bp
));
904 * Called prior to the locking of any vnodes when we are expecting to
905 * write. We do not want to starve the buffer cache with too many
906 * dirty buffers so we block here. By blocking prior to the locking
907 * of any vnodes we attempt to avoid the situation where a locked vnode
908 * prevents the various system daemons from flushing related buffers.
914 if (numdirtybuffers
>= hidirtybuffers
) {
916 while (numdirtybuffers
>= hidirtybuffers
) {
918 needsbuffer
|= VFS_BIO_NEED_DIRTYFLUSH
;
919 tsleep(&needsbuffer
, 0, "flswai", 0);
926 * buf_dirty_count_severe:
928 * Return true if we have too many dirty buffers.
931 buf_dirty_count_severe(void)
933 return(numdirtybuffers
>= hidirtybuffers
);
939 * Release a busy buffer and, if requested, free its resources. The
940 * buffer will be stashed in the appropriate bufqueue[] allowing it
941 * to be accessed later as a cache entity or reused for other purposes.
944 brelse(struct buf
* bp
)
947 int saved_flags
= bp
->b_flags
;
950 KASSERT(!(bp
->b_flags
& (B_CLUSTER
|B_PAGING
)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp
));
954 if ((bp
->b_flags
& (B_NOCACHE
|B_DIRTY
)) == (B_NOCACHE
|B_DIRTY
)) {
955 printf("warning: buf %p marked dirty & B_NOCACHE, clearing B_NOCACHE\n", bp
);
956 bp
->b_flags
&= ~B_NOCACHE
;
959 if (bp
->b_flags
& B_LOCKED
)
960 bp
->b_flags
&= ~B_ERROR
;
962 if (bp
->b_cmd
== BUF_CMD_WRITE
&&
963 (bp
->b_flags
& (B_ERROR
| B_INVAL
)) == B_ERROR
) {
965 * Failed write, redirty. Must clear B_ERROR to prevent
966 * pages from being scrapped. If B_INVAL is set then
967 * this case is not run and the next case is run to
968 * destroy the buffer. B_INVAL can occur if the buffer
969 * is outside the range supported by the underlying device.
971 bp
->b_flags
&= ~B_ERROR
;
973 } else if ((bp
->b_flags
& (B_NOCACHE
| B_INVAL
| B_ERROR
)) ||
974 (bp
->b_bufsize
<= 0) || bp
->b_cmd
== BUF_CMD_FREEBLKS
) {
976 * Either a failed I/O or we were asked to free or not
979 bp
->b_flags
|= B_INVAL
;
980 if (LIST_FIRST(&bp
->b_dep
) != NULL
&& bioops
.io_deallocate
)
981 (*bioops
.io_deallocate
)(bp
);
982 if (bp
->b_flags
& B_DELWRI
) {
984 numdirtywakeup(lodirtybuffers
);
986 bp
->b_flags
&= ~(B_DELWRI
| B_CACHE
);
990 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
991 * is called with B_DELWRI set, the underlying pages may wind up
992 * getting freed causing a previous write (bdwrite()) to get 'lost'
993 * because pages associated with a B_DELWRI bp are marked clean.
995 * We still allow the B_INVAL case to call vfs_vmio_release(), even
996 * if B_DELWRI is set.
998 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
999 * on pages to return pages to the VM page queues.
1001 if (bp
->b_flags
& B_DELWRI
)
1002 bp
->b_flags
&= ~B_RELBUF
;
1003 else if (vm_page_count_severe())
1004 bp
->b_flags
|= B_RELBUF
;
1007 * At this point destroying the buffer is governed by the B_INVAL
1008 * or B_RELBUF flags.
1010 bp
->b_cmd
= BUF_CMD_DONE
;
1013 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1014 * constituted, not even NFS buffers now. Two flags effect this. If
1015 * B_INVAL, the struct buf is invalidated but the VM object is kept
1016 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1018 * If B_ERROR or B_NOCACHE is set, pages in the VM object will be
1019 * invalidated. B_ERROR cannot be set for a failed write unless the
1020 * buffer is also B_INVAL because it hits the re-dirtying code above.
1022 * Normally we can do this whether a buffer is B_DELWRI or not. If
1023 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1024 * the commit state and we cannot afford to lose the buffer. If the
1025 * buffer has a background write in progress, we need to keep it
1026 * around to prevent it from being reconstituted and starting a second
1029 if ((bp
->b_flags
& B_VMIO
)
1030 && !(bp
->b_vp
->v_tag
== VT_NFS
&&
1031 !vn_isdisk(bp
->b_vp
, NULL
) &&
1032 (bp
->b_flags
& B_DELWRI
))
1035 * Rundown for VMIO buffers which are not dirty NFS buffers.
1047 * Get the base offset and length of the buffer. Note that
1048 * in the VMIO case if the buffer block size is not
1049 * page-aligned then b_data pointer may not be page-aligned.
1050 * But our b_xio.xio_pages array *IS* page aligned.
1052 * block sizes less then DEV_BSIZE (usually 512) are not
1053 * supported due to the page granularity bits (m->valid,
1054 * m->dirty, etc...).
1056 * See man buf(9) for more information
1059 resid
= bp
->b_bufsize
;
1060 foff
= bp
->b_loffset
;
1062 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
1063 m
= bp
->b_xio
.xio_pages
[i
];
1064 vm_page_flag_clear(m
, PG_ZERO
);
1066 * If we hit a bogus page, fixup *all* of them
1067 * now. Note that we left these pages wired
1068 * when we removed them so they had better exist,
1069 * and they cannot be ripped out from under us so
1070 * no critical section protection is necessary.
1072 if (m
== bogus_page
) {
1074 poff
= OFF_TO_IDX(bp
->b_loffset
);
1076 for (j
= i
; j
< bp
->b_xio
.xio_npages
; j
++) {
1079 mtmp
= bp
->b_xio
.xio_pages
[j
];
1080 if (mtmp
== bogus_page
) {
1081 mtmp
= vm_page_lookup(obj
, poff
+ j
);
1083 panic("brelse: page missing");
1085 bp
->b_xio
.xio_pages
[j
] = mtmp
;
1089 if ((bp
->b_flags
& B_INVAL
) == 0) {
1090 pmap_qenter(trunc_page((vm_offset_t
)bp
->b_data
),
1091 bp
->b_xio
.xio_pages
, bp
->b_xio
.xio_npages
);
1093 m
= bp
->b_xio
.xio_pages
[i
];
1097 * Invalidate the backing store if B_NOCACHE is set
1098 * (e.g. used with vinvalbuf()). If this is NFS
1099 * we impose a requirement that the block size be
1100 * a multiple of PAGE_SIZE and create a temporary
1101 * hack to basically invalidate the whole page. The
1102 * problem is that NFS uses really odd buffer sizes
1103 * especially when tracking piecemeal writes and
1104 * it also vinvalbuf()'s a lot, which would result
1105 * in only partial page validation and invalidation
1106 * here. If the file page is mmap()'d, however,
1107 * all the valid bits get set so after we invalidate
1108 * here we would end up with weird m->valid values
1109 * like 0xfc. nfs_getpages() can't handle this so
1110 * we clear all the valid bits for the NFS case
1111 * instead of just some of them.
1113 * The real bug is the VM system having to set m->valid
1114 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1115 * itself is an artifact of the whole 512-byte
1116 * granular mess that exists to support odd block
1117 * sizes and UFS meta-data block sizes (e.g. 6144).
1118 * A complete rewrite is required.
1120 if (bp
->b_flags
& (B_NOCACHE
|B_ERROR
)) {
1121 int poffset
= foff
& PAGE_MASK
;
1124 presid
= PAGE_SIZE
- poffset
;
1125 if (bp
->b_vp
->v_tag
== VT_NFS
&&
1126 bp
->b_vp
->v_type
== VREG
) {
1128 } else if (presid
> resid
) {
1131 KASSERT(presid
>= 0, ("brelse: extra page"));
1132 vm_page_set_invalid(m
, poffset
, presid
);
1134 resid
-= PAGE_SIZE
- (foff
& PAGE_MASK
);
1135 foff
= (foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
;
1137 if (bp
->b_flags
& (B_INVAL
| B_RELBUF
))
1138 vfs_vmio_release(bp
);
1139 } else if (bp
->b_flags
& B_VMIO
) {
1141 * Rundown for VMIO buffers which are dirty NFS buffers. Such
1142 * buffers contain tracking ranges for NFS and cannot normally
1143 * be released. Due to the dirty check above this series of
1144 * conditionals, B_RELBUF probably will never be set in this
1147 if (bp
->b_flags
& (B_INVAL
| B_RELBUF
))
1148 vfs_vmio_release(bp
);
1151 * Rundown for non-VMIO buffers.
1153 if (bp
->b_flags
& (B_INVAL
| B_RELBUF
)) {
1156 printf("brelse bp %p %08x/%08x: Warning, caught and fixed brelvp bug\n", bp
, saved_flags
, bp
->b_flags
);
1165 if (bp
->b_qindex
!= BQUEUE_NONE
)
1166 panic("brelse: free buffer onto another queue???");
1167 if (BUF_REFCNTNB(bp
) > 1) {
1168 /* Temporary panic to verify exclusive locking */
1169 /* This panic goes away when we allow shared refs */
1170 panic("brelse: multiple refs");
1171 /* do not release to free list */
1178 * Figure out the correct queue to place the cleaned up buffer on.
1179 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1180 * disassociated from their vnode.
1183 if (bp
->b_bufsize
== 0) {
1185 * Buffers with no memory. Due to conditionals near the top
1186 * of brelse() such buffers should probably already be
1187 * marked B_INVAL and disassociated from their vnode.
1189 bp
->b_flags
|= B_INVAL
;
1190 KASSERT(bp
->b_vp
== NULL
, ("bp1 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp
, saved_flags
, bp
->b_flags
, bp
->b_vp
));
1191 KKASSERT((bp
->b_flags
& B_HASHED
) == 0);
1192 if (bp
->b_kvasize
) {
1193 bp
->b_qindex
= BQUEUE_EMPTYKVA
;
1195 bp
->b_qindex
= BQUEUE_EMPTY
;
1197 TAILQ_INSERT_HEAD(&bufqueues
[bp
->b_qindex
], bp
, b_freelist
);
1198 } else if (bp
->b_flags
& (B_ERROR
| B_INVAL
| B_NOCACHE
| B_RELBUF
)) {
1200 * Buffers with junk contents. Again these buffers had better
1201 * already be disassociated from their vnode.
1203 KASSERT(bp
->b_vp
== NULL
, ("bp2 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp
, saved_flags
, bp
->b_flags
, bp
->b_vp
));
1204 KKASSERT((bp
->b_flags
& B_HASHED
) == 0);
1205 bp
->b_flags
|= B_INVAL
;
1206 bp
->b_qindex
= BQUEUE_CLEAN
;
1207 TAILQ_INSERT_HEAD(&bufqueues
[BQUEUE_CLEAN
], bp
, b_freelist
);
1208 } else if (bp
->b_flags
& B_LOCKED
) {
1210 * Buffers that are locked.
1212 bp
->b_qindex
= BQUEUE_LOCKED
;
1213 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_LOCKED
], bp
, b_freelist
);
1216 * Remaining buffers. These buffers are still associated with
1219 switch(bp
->b_flags
& (B_DELWRI
|B_AGE
)) {
1220 case B_DELWRI
| B_AGE
:
1221 bp
->b_qindex
= BQUEUE_DIRTY
;
1222 TAILQ_INSERT_HEAD(&bufqueues
[BQUEUE_DIRTY
], bp
, b_freelist
);
1225 bp
->b_qindex
= BQUEUE_DIRTY
;
1226 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_DIRTY
], bp
, b_freelist
);
1229 bp
->b_qindex
= BQUEUE_CLEAN
;
1230 TAILQ_INSERT_HEAD(&bufqueues
[BQUEUE_CLEAN
], bp
, b_freelist
);
1233 bp
->b_qindex
= BQUEUE_CLEAN
;
1234 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_CLEAN
], bp
, b_freelist
);
1240 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1241 * on the correct queue.
1243 if ((bp
->b_flags
& (B_INVAL
|B_DELWRI
)) == (B_INVAL
|B_DELWRI
))
1247 * Fixup numfreebuffers count. The bp is on an appropriate queue
1248 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1249 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1250 * if B_INVAL is set ).
1252 if ((bp
->b_flags
& B_LOCKED
) == 0 && !(bp
->b_flags
& B_DELWRI
))
1256 * Something we can maybe free or reuse
1258 if (bp
->b_bufsize
|| bp
->b_kvasize
)
1262 * Clean up temporary flags and unlock the buffer.
1264 bp
->b_flags
&= ~(B_ORDERED
| B_ASYNC
| B_NOCACHE
| B_AGE
| B_RELBUF
|
1265 B_DIRECT
| B_NOWDRAIN
);
1273 * Release a buffer back to the appropriate queue but do not try to free
1274 * it. The buffer is expected to be used again soon.
1276 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1277 * biodone() to requeue an async I/O on completion. It is also used when
1278 * known good buffers need to be requeued but we think we may need the data
1281 * XXX we should be able to leave the B_RELBUF hint set on completion.
1284 bqrelse(struct buf
* bp
)
1288 KASSERT(!(bp
->b_flags
& (B_CLUSTER
|B_PAGING
)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp
));
1290 if (bp
->b_qindex
!= BQUEUE_NONE
)
1291 panic("bqrelse: free buffer onto another queue???");
1292 if (BUF_REFCNTNB(bp
) > 1) {
1293 /* do not release to free list */
1294 panic("bqrelse: multiple refs");
1299 if (bp
->b_flags
& B_LOCKED
) {
1300 bp
->b_flags
&= ~B_ERROR
;
1301 bp
->b_qindex
= BQUEUE_LOCKED
;
1302 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_LOCKED
], bp
, b_freelist
);
1303 /* buffers with stale but valid contents */
1304 } else if (bp
->b_flags
& B_DELWRI
) {
1305 bp
->b_qindex
= BQUEUE_DIRTY
;
1306 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_DIRTY
], bp
, b_freelist
);
1307 } else if (vm_page_count_severe()) {
1309 * We are too low on memory, we have to try to free the
1310 * buffer (most importantly: the wired pages making up its
1311 * backing store) *now*.
1317 bp
->b_qindex
= BQUEUE_CLEAN
;
1318 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_CLEAN
], bp
, b_freelist
);
1321 if ((bp
->b_flags
& B_LOCKED
) == 0 &&
1322 ((bp
->b_flags
& B_INVAL
) || !(bp
->b_flags
& B_DELWRI
))) {
1327 * Something we can maybe free or reuse.
1329 if (bp
->b_bufsize
&& !(bp
->b_flags
& B_DELWRI
))
1333 * Final cleanup and unlock. Clear bits that are only used while a
1334 * buffer is actively locked.
1336 bp
->b_flags
&= ~(B_ORDERED
| B_ASYNC
| B_NOCACHE
| B_AGE
| B_RELBUF
);
1344 * Return backing pages held by the buffer 'bp' back to the VM system
1345 * if possible. The pages are freed if they are no longer valid or
1346 * attempt to free if it was used for direct I/O otherwise they are
1347 * sent to the page cache.
1349 * Pages that were marked busy are left alone and skipped.
1351 * The KVA mapping (b_data) for the underlying pages is removed by
1355 vfs_vmio_release(struct buf
*bp
)
1361 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
1362 m
= bp
->b_xio
.xio_pages
[i
];
1363 bp
->b_xio
.xio_pages
[i
] = NULL
;
1365 * In order to keep page LRU ordering consistent, put
1366 * everything on the inactive queue.
1368 vm_page_unwire(m
, 0);
1370 * We don't mess with busy pages, it is
1371 * the responsibility of the process that
1372 * busied the pages to deal with them.
1374 if ((m
->flags
& PG_BUSY
) || (m
->busy
!= 0))
1377 if (m
->wire_count
== 0) {
1378 vm_page_flag_clear(m
, PG_ZERO
);
1380 * Might as well free the page if we can and it has
1381 * no valid data. We also free the page if the
1382 * buffer was used for direct I/O.
1384 if ((bp
->b_flags
& B_ASYNC
) == 0 && !m
->valid
&&
1385 m
->hold_count
== 0) {
1387 vm_page_protect(m
, VM_PROT_NONE
);
1389 } else if (bp
->b_flags
& B_DIRECT
) {
1390 vm_page_try_to_free(m
);
1391 } else if (vm_page_count_severe()) {
1392 vm_page_try_to_cache(m
);
1397 pmap_qremove(trunc_page((vm_offset_t
) bp
->b_data
), bp
->b_xio
.xio_npages
);
1398 if (bp
->b_bufsize
) {
1402 bp
->b_xio
.xio_npages
= 0;
1403 bp
->b_flags
&= ~B_VMIO
;
1411 * Implement clustered async writes for clearing out B_DELWRI buffers.
1412 * This is much better then the old way of writing only one buffer at
1413 * a time. Note that we may not be presented with the buffers in the
1414 * correct order, so we search for the cluster in both directions.
1416 * The buffer is locked on call.
1419 vfs_bio_awrite(struct buf
*bp
)
1423 off_t loffset
= bp
->b_loffset
;
1424 struct vnode
*vp
= bp
->b_vp
;
1432 * right now we support clustered writing only to regular files. If
1433 * we find a clusterable block we could be in the middle of a cluster
1434 * rather then at the beginning.
1436 * NOTE: b_bio1 contains the logical loffset and is aliased
1437 * to b_loffset. b_bio2 contains the translated block number.
1439 if ((vp
->v_type
== VREG
) &&
1440 (vp
->v_mount
!= 0) && /* Only on nodes that have the size info */
1441 (bp
->b_flags
& (B_CLUSTEROK
| B_INVAL
)) == B_CLUSTEROK
) {
1443 size
= vp
->v_mount
->mnt_stat
.f_iosize
;
1445 for (i
= size
; i
< MAXPHYS
; i
+= size
) {
1446 if ((bpa
= findblk(vp
, loffset
+ i
)) &&
1447 BUF_REFCNT(bpa
) == 0 &&
1448 ((bpa
->b_flags
& (B_DELWRI
| B_CLUSTEROK
| B_INVAL
)) ==
1449 (B_DELWRI
| B_CLUSTEROK
)) &&
1450 (bpa
->b_bufsize
== size
)) {
1451 if ((bpa
->b_bio2
.bio_offset
== NOOFFSET
) ||
1452 (bpa
->b_bio2
.bio_offset
!=
1453 bp
->b_bio2
.bio_offset
+ i
))
1459 for (j
= size
; i
+ j
<= MAXPHYS
&& j
<= loffset
; j
+= size
) {
1460 if ((bpa
= findblk(vp
, loffset
- j
)) &&
1461 BUF_REFCNT(bpa
) == 0 &&
1462 ((bpa
->b_flags
& (B_DELWRI
| B_CLUSTEROK
| B_INVAL
)) ==
1463 (B_DELWRI
| B_CLUSTEROK
)) &&
1464 (bpa
->b_bufsize
== size
)) {
1465 if ((bpa
->b_bio2
.bio_offset
== NOOFFSET
) ||
1466 (bpa
->b_bio2
.bio_offset
!=
1467 bp
->b_bio2
.bio_offset
- j
))
1476 * this is a possible cluster write
1478 if (nbytes
!= size
) {
1480 nwritten
= cluster_wbuild(vp
, size
,
1481 loffset
- j
, nbytes
);
1488 bp
->b_flags
|= B_ASYNC
;
1492 * default (old) behavior, writing out only one block
1494 * XXX returns b_bufsize instead of b_bcount for nwritten?
1496 nwritten
= bp
->b_bufsize
;
1497 (void) VOP_BWRITE(bp
->b_vp
, bp
);
1505 * Find and initialize a new buffer header, freeing up existing buffers
1506 * in the bufqueues as necessary. The new buffer is returned locked.
1508 * Important: B_INVAL is not set. If the caller wishes to throw the
1509 * buffer away, the caller must set B_INVAL prior to calling brelse().
1512 * We have insufficient buffer headers
1513 * We have insufficient buffer space
1514 * buffer_map is too fragmented ( space reservation fails )
1515 * If we have to flush dirty buffers ( but we try to avoid this )
1517 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1518 * Instead we ask the buf daemon to do it for us. We attempt to
1519 * avoid piecemeal wakeups of the pageout daemon.
1523 getnewbuf(int slpflag
, int slptimeo
, int size
, int maxsize
)
1529 static int flushingbufs
;
1532 * We can't afford to block since we might be holding a vnode lock,
1533 * which may prevent system daemons from running. We deal with
1534 * low-memory situations by proactively returning memory and running
1535 * async I/O rather then sync I/O.
1539 --getnewbufrestarts
;
1541 ++getnewbufrestarts
;
1544 * Setup for scan. If we do not have enough free buffers,
1545 * we setup a degenerate case that immediately fails. Note
1546 * that if we are specially marked process, we are allowed to
1547 * dip into our reserves.
1549 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1551 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1552 * However, there are a number of cases (defragging, reusing, ...)
1553 * where we cannot backup.
1555 nqindex
= BQUEUE_EMPTYKVA
;
1556 nbp
= TAILQ_FIRST(&bufqueues
[BQUEUE_EMPTYKVA
]);
1560 * If no EMPTYKVA buffers and we are either
1561 * defragging or reusing, locate a CLEAN buffer
1562 * to free or reuse. If bufspace useage is low
1563 * skip this step so we can allocate a new buffer.
1565 if (defrag
|| bufspace
>= lobufspace
) {
1566 nqindex
= BQUEUE_CLEAN
;
1567 nbp
= TAILQ_FIRST(&bufqueues
[BQUEUE_CLEAN
]);
1571 * If we could not find or were not allowed to reuse a
1572 * CLEAN buffer, check to see if it is ok to use an EMPTY
1573 * buffer. We can only use an EMPTY buffer if allocating
1574 * its KVA would not otherwise run us out of buffer space.
1576 if (nbp
== NULL
&& defrag
== 0 &&
1577 bufspace
+ maxsize
< hibufspace
) {
1578 nqindex
= BQUEUE_EMPTY
;
1579 nbp
= TAILQ_FIRST(&bufqueues
[BQUEUE_EMPTY
]);
1584 * Run scan, possibly freeing data and/or kva mappings on the fly
1588 while ((bp
= nbp
) != NULL
) {
1589 int qindex
= nqindex
;
1592 * Calculate next bp ( we can only use it if we do not block
1593 * or do other fancy things ).
1595 if ((nbp
= TAILQ_NEXT(bp
, b_freelist
)) == NULL
) {
1598 nqindex
= BQUEUE_EMPTYKVA
;
1599 if ((nbp
= TAILQ_FIRST(&bufqueues
[BQUEUE_EMPTYKVA
])))
1602 case BQUEUE_EMPTYKVA
:
1603 nqindex
= BQUEUE_CLEAN
;
1604 if ((nbp
= TAILQ_FIRST(&bufqueues
[BQUEUE_CLEAN
])))
1618 KASSERT(bp
->b_qindex
== qindex
, ("getnewbuf: inconsistant queue %d bp %p", qindex
, bp
));
1621 * Note: we no longer distinguish between VMIO and non-VMIO
1625 KASSERT((bp
->b_flags
& B_DELWRI
) == 0, ("delwri buffer %p found in queue %d", bp
, qindex
));
1628 * If we are defragging then we need a buffer with
1629 * b_kvasize != 0. XXX this situation should no longer
1630 * occur, if defrag is non-zero the buffer's b_kvasize
1631 * should also be non-zero at this point. XXX
1633 if (defrag
&& bp
->b_kvasize
== 0) {
1634 printf("Warning: defrag empty buffer %p\n", bp
);
1639 * Start freeing the bp. This is somewhat involved. nbp
1640 * remains valid only for BQUEUE_EMPTY[KVA] bp's. Buffers
1641 * on the clean list must be disassociated from their
1642 * current vnode. Buffers on the empty[kva] lists have
1643 * already been disassociated.
1646 if (BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_NOWAIT
) != 0) {
1647 printf("getnewbuf: warning, locked buf %p, race corrected\n", bp
);
1648 tsleep(&bd_request
, 0, "gnbxxx", hz
/ 100);
1651 if (bp
->b_qindex
!= qindex
) {
1652 printf("getnewbuf: warning, BUF_LOCK blocked unexpectedly on buf %p index %d->%d, race corrected\n", bp
, qindex
, bp
->b_qindex
);
1658 if (qindex
== BQUEUE_CLEAN
) {
1659 if (bp
->b_flags
& B_VMIO
) {
1660 bp
->b_flags
&= ~B_ASYNC
;
1661 vfs_vmio_release(bp
);
1668 * NOTE: nbp is now entirely invalid. We can only restart
1669 * the scan from this point on.
1671 * Get the rest of the buffer freed up. b_kva* is still
1672 * valid after this operation.
1675 KASSERT(bp
->b_vp
== NULL
, ("bp3 %p flags %08x vnode %p qindex %d unexpectededly still associated!", bp
, bp
->b_flags
, bp
->b_vp
, qindex
));
1676 KKASSERT((bp
->b_flags
& B_HASHED
) == 0);
1677 if (LIST_FIRST(&bp
->b_dep
) != NULL
&& bioops
.io_deallocate
)
1678 (*bioops
.io_deallocate
)(bp
);
1681 * critical section protection is not required when
1682 * scrapping a buffer's contents because it is already
1689 bp
->b_cmd
= BUF_CMD_DONE
;
1694 bp
->b_xio
.xio_npages
= 0;
1695 bp
->b_dirtyoff
= bp
->b_dirtyend
= 0;
1698 LIST_INIT(&bp
->b_dep
);
1701 * If we are defragging then free the buffer.
1704 bp
->b_flags
|= B_INVAL
;
1712 * If we are overcomitted then recover the buffer and its
1713 * KVM space. This occurs in rare situations when multiple
1714 * processes are blocked in getnewbuf() or allocbuf().
1716 if (bufspace
>= hibufspace
)
1718 if (flushingbufs
&& bp
->b_kvasize
!= 0) {
1719 bp
->b_flags
|= B_INVAL
;
1724 if (bufspace
< lobufspace
)
1730 * If we exhausted our list, sleep as appropriate. We may have to
1731 * wakeup various daemons and write out some dirty buffers.
1733 * Generally we are sleeping due to insufficient buffer space.
1741 flags
= VFS_BIO_NEED_BUFSPACE
;
1743 } else if (bufspace
>= hibufspace
) {
1745 flags
= VFS_BIO_NEED_BUFSPACE
;
1748 flags
= VFS_BIO_NEED_ANY
;
1751 bd_speedup(); /* heeeelp */
1753 needsbuffer
|= flags
;
1754 while (needsbuffer
& flags
) {
1755 if (tsleep(&needsbuffer
, slpflag
, waitmsg
, slptimeo
))
1760 * We finally have a valid bp. We aren't quite out of the
1761 * woods, we still have to reserve kva space. In order
1762 * to keep fragmentation sane we only allocate kva in
1765 maxsize
= (maxsize
+ BKVAMASK
) & ~BKVAMASK
;
1767 if (maxsize
!= bp
->b_kvasize
) {
1768 vm_offset_t addr
= 0;
1773 count
= vm_map_entry_reserve(MAP_RESERVE_COUNT
);
1774 vm_map_lock(buffer_map
);
1776 if (vm_map_findspace(buffer_map
,
1777 vm_map_min(buffer_map
), maxsize
,
1780 * Uh oh. Buffer map is too fragmented. We
1781 * must defragment the map.
1783 vm_map_unlock(buffer_map
);
1784 vm_map_entry_release(count
);
1787 bp
->b_flags
|= B_INVAL
;
1792 vm_map_insert(buffer_map
, &count
,
1794 addr
, addr
+ maxsize
,
1795 VM_PROT_ALL
, VM_PROT_ALL
, MAP_NOFAULT
);
1797 bp
->b_kvabase
= (caddr_t
) addr
;
1798 bp
->b_kvasize
= maxsize
;
1799 bufspace
+= bp
->b_kvasize
;
1802 vm_map_unlock(buffer_map
);
1803 vm_map_entry_release(count
);
1805 bp
->b_data
= bp
->b_kvabase
;
1813 * Buffer flushing daemon. Buffers are normally flushed by the
1814 * update daemon but if it cannot keep up this process starts to
1815 * take the load in an attempt to prevent getnewbuf() from blocking.
1818 static struct thread
*bufdaemonthread
;
1820 static struct kproc_desc buf_kp
= {
1825 SYSINIT(bufdaemon
, SI_SUB_KTHREAD_BUF
, SI_ORDER_FIRST
, kproc_start
, &buf_kp
)
1831 * This process needs to be suspended prior to shutdown sync.
1833 EVENTHANDLER_REGISTER(shutdown_pre_sync
, shutdown_kproc
,
1834 bufdaemonthread
, SHUTDOWN_PRI_LAST
);
1837 * This process is allowed to take the buffer cache to the limit
1842 kproc_suspend_loop();
1845 * Do the flush. Limit the amount of in-transit I/O we
1846 * allow to build up, otherwise we would completely saturate
1847 * the I/O system. Wakeup any waiting processes before we
1848 * normally would so they can run in parallel with our drain.
1850 while (numdirtybuffers
> lodirtybuffers
) {
1851 if (flushbufqueues() == 0)
1853 waitrunningbufspace();
1854 numdirtywakeup((lodirtybuffers
+ hidirtybuffers
) / 2);
1858 * Only clear bd_request if we have reached our low water
1859 * mark. The buf_daemon normally waits 5 seconds and
1860 * then incrementally flushes any dirty buffers that have
1861 * built up, within reason.
1863 * If we were unable to hit our low water mark and couldn't
1864 * find any flushable buffers, we sleep half a second.
1865 * Otherwise we loop immediately.
1867 if (numdirtybuffers
<= lodirtybuffers
) {
1869 * We reached our low water mark, reset the
1870 * request and sleep until we are needed again.
1871 * The sleep is just so the suspend code works.
1874 tsleep(&bd_request
, 0, "psleep", hz
);
1877 * We couldn't find any flushable dirty buffers but
1878 * still have too many dirty buffers, we
1879 * have to sleep and try again. (rare)
1881 tsleep(&bd_request
, 0, "qsleep", hz
/ 2);
1889 * Try to flush a buffer in the dirty queue. We must be careful to
1890 * free up B_INVAL buffers instead of write them, which NFS is
1891 * particularly sensitive to.
1895 flushbufqueues(void)
1900 bp
= TAILQ_FIRST(&bufqueues
[BQUEUE_DIRTY
]);
1903 KASSERT((bp
->b_flags
& B_DELWRI
), ("unexpected clean buffer %p", bp
));
1904 if (bp
->b_flags
& B_DELWRI
) {
1905 if (bp
->b_flags
& B_INVAL
) {
1906 if (BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_NOWAIT
) != 0)
1907 panic("flushbufqueues: locked buf");
1913 if (LIST_FIRST(&bp
->b_dep
) != NULL
&&
1914 bioops
.io_countdeps
&&
1915 (bp
->b_flags
& B_DEFERRED
) == 0 &&
1916 (*bioops
.io_countdeps
)(bp
, 0)) {
1917 TAILQ_REMOVE(&bufqueues
[BQUEUE_DIRTY
],
1919 TAILQ_INSERT_TAIL(&bufqueues
[BQUEUE_DIRTY
],
1921 bp
->b_flags
|= B_DEFERRED
;
1922 bp
= TAILQ_FIRST(&bufqueues
[BQUEUE_DIRTY
]);
1927 * Only write it out if we can successfully lock
1930 if (BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_NOWAIT
) == 0) {
1936 bp
= TAILQ_NEXT(bp
, b_freelist
);
1944 * Returns true if no I/O is needed to access the associated VM object.
1945 * This is like findblk except it also hunts around in the VM system for
1948 * Note that we ignore vm_page_free() races from interrupts against our
1949 * lookup, since if the caller is not protected our return value will not
1950 * be any more valid then otherwise once we exit the critical section.
1953 inmem(struct vnode
*vp
, off_t loffset
)
1956 vm_offset_t toff
, tinc
, size
;
1959 if (findblk(vp
, loffset
))
1961 if (vp
->v_mount
== NULL
)
1963 if ((obj
= vp
->v_object
) == NULL
)
1967 if (size
> vp
->v_mount
->mnt_stat
.f_iosize
)
1968 size
= vp
->v_mount
->mnt_stat
.f_iosize
;
1970 for (toff
= 0; toff
< vp
->v_mount
->mnt_stat
.f_iosize
; toff
+= tinc
) {
1971 m
= vm_page_lookup(obj
, OFF_TO_IDX(loffset
+ toff
));
1975 if (tinc
> PAGE_SIZE
- ((toff
+ loffset
) & PAGE_MASK
))
1976 tinc
= PAGE_SIZE
- ((toff
+ loffset
) & PAGE_MASK
);
1977 if (vm_page_is_valid(m
,
1978 (vm_offset_t
) ((toff
+ loffset
) & PAGE_MASK
), tinc
) == 0)
1987 * Sets the dirty range for a buffer based on the status of the dirty
1988 * bits in the pages comprising the buffer.
1990 * The range is limited to the size of the buffer.
1992 * This routine is primarily used by NFS, but is generalized for the
1996 vfs_setdirty(struct buf
*bp
)
2002 * Degenerate case - empty buffer
2005 if (bp
->b_bufsize
== 0)
2009 * We qualify the scan for modified pages on whether the
2010 * object has been flushed yet. The OBJ_WRITEABLE flag
2011 * is not cleared simply by protecting pages off.
2014 if ((bp
->b_flags
& B_VMIO
) == 0)
2017 object
= bp
->b_xio
.xio_pages
[0]->object
;
2019 if ((object
->flags
& OBJ_WRITEABLE
) && !(object
->flags
& OBJ_MIGHTBEDIRTY
))
2020 printf("Warning: object %p writeable but not mightbedirty\n", object
);
2021 if (!(object
->flags
& OBJ_WRITEABLE
) && (object
->flags
& OBJ_MIGHTBEDIRTY
))
2022 printf("Warning: object %p mightbedirty but not writeable\n", object
);
2024 if (object
->flags
& (OBJ_MIGHTBEDIRTY
|OBJ_CLEANING
)) {
2025 vm_offset_t boffset
;
2026 vm_offset_t eoffset
;
2029 * test the pages to see if they have been modified directly
2030 * by users through the VM system.
2032 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
2033 vm_page_flag_clear(bp
->b_xio
.xio_pages
[i
], PG_ZERO
);
2034 vm_page_test_dirty(bp
->b_xio
.xio_pages
[i
]);
2038 * Calculate the encompassing dirty range, boffset and eoffset,
2039 * (eoffset - boffset) bytes.
2042 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
2043 if (bp
->b_xio
.xio_pages
[i
]->dirty
)
2046 boffset
= (i
<< PAGE_SHIFT
) - (bp
->b_loffset
& PAGE_MASK
);
2048 for (i
= bp
->b_xio
.xio_npages
- 1; i
>= 0; --i
) {
2049 if (bp
->b_xio
.xio_pages
[i
]->dirty
) {
2053 eoffset
= ((i
+ 1) << PAGE_SHIFT
) - (bp
->b_loffset
& PAGE_MASK
);
2056 * Fit it to the buffer.
2059 if (eoffset
> bp
->b_bcount
)
2060 eoffset
= bp
->b_bcount
;
2063 * If we have a good dirty range, merge with the existing
2067 if (boffset
< eoffset
) {
2068 if (bp
->b_dirtyoff
> boffset
)
2069 bp
->b_dirtyoff
= boffset
;
2070 if (bp
->b_dirtyend
< eoffset
)
2071 bp
->b_dirtyend
= eoffset
;
2079 * Locate and return the specified buffer, or NULL if the buffer does
2080 * not exist. Do not attempt to lock the buffer or manipulate it in
2081 * any way. The caller must validate that the correct buffer has been
2082 * obtain after locking it.
2085 findblk(struct vnode
*vp
, off_t loffset
)
2090 bp
= buf_rb_hash_RB_LOOKUP(&vp
->v_rbhash_tree
, loffset
);
2098 * Get a block given a specified block and offset into a file/device.
2099 * B_INVAL may or may not be set on return. The caller should clear
2100 * B_INVAL prior to initiating a READ.
2102 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2103 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2104 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2105 * without doing any of those things the system will likely believe
2106 * the buffer to be valid (especially if it is not B_VMIO), and the
2107 * next getblk() will return the buffer with B_CACHE set.
2109 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2110 * an existing buffer.
2112 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2113 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2114 * and then cleared based on the backing VM. If the previous buffer is
2115 * non-0-sized but invalid, B_CACHE will be cleared.
2117 * If getblk() must create a new buffer, the new buffer is returned with
2118 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2119 * case it is returned with B_INVAL clear and B_CACHE set based on the
2122 * getblk() also forces a VOP_BWRITE() for any B_DELWRI buffer whos
2123 * B_CACHE bit is clear.
2125 * What this means, basically, is that the caller should use B_CACHE to
2126 * determine whether the buffer is fully valid or not and should clear
2127 * B_INVAL prior to issuing a read. If the caller intends to validate
2128 * the buffer by loading its data area with something, the caller needs
2129 * to clear B_INVAL. If the caller does this without issuing an I/O,
2130 * the caller should set B_CACHE ( as an optimization ), else the caller
2131 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2132 * a write attempt or if it was a successfull read. If the caller
2133 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2134 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2137 getblk(struct vnode
*vp
, off_t loffset
, int size
, int slpflag
, int slptimeo
)
2141 if (size
> MAXBSIZE
)
2142 panic("getblk: size(%d) > MAXBSIZE(%d)", size
, MAXBSIZE
);
2143 if (vp
->v_object
== NULL
)
2144 panic("getblk: vnode %p has no object!", vp
);
2149 * Block if we are low on buffers. Certain processes are allowed
2150 * to completely exhaust the buffer cache.
2152 * If this check ever becomes a bottleneck it may be better to
2153 * move it into the else, when findblk() fails. At the moment
2154 * it isn't a problem.
2156 * XXX remove, we cannot afford to block anywhere if holding a vnode
2157 * lock in low-memory situation, so take it to the max.
2159 if (numfreebuffers
== 0) {
2162 needsbuffer
|= VFS_BIO_NEED_ANY
;
2163 tsleep(&needsbuffer
, slpflag
, "newbuf", slptimeo
);
2166 if ((bp
= findblk(vp
, loffset
))) {
2168 * The buffer was found in the cache, but we need to lock it.
2169 * Even with LK_NOWAIT the lockmgr may break our critical
2170 * section, so double-check the validity of the buffer
2171 * once the lock has been obtained.
2173 if (BUF_LOCK(bp
, LK_EXCLUSIVE
| LK_NOWAIT
)) {
2174 int lkflags
= LK_EXCLUSIVE
| LK_SLEEPFAIL
;
2175 if (slpflag
& PCATCH
)
2176 lkflags
|= LK_PCATCH
;
2177 if (BUF_TIMELOCK(bp
, lkflags
, "getblk", slptimeo
) ==
2186 * Once the buffer has been locked, make sure we didn't race
2187 * a buffer recyclement. Buffers that are no longer hashed
2188 * will have b_vp == NULL, so this takes care of that check
2191 if (bp
->b_vp
!= vp
|| bp
->b_loffset
!= loffset
) {
2192 printf("Warning buffer %p (vp %p loffset %lld) was recycled\n", bp
, vp
, loffset
);
2198 * All vnode-based buffers must be backed by a VM object.
2200 KKASSERT(bp
->b_flags
& B_VMIO
);
2201 KKASSERT(bp
->b_cmd
== BUF_CMD_DONE
);
2204 * Make sure that B_INVAL buffers do not have a cached
2205 * block number translation.
2207 if ((bp
->b_flags
& B_INVAL
) && (bp
->b_bio2
.bio_offset
!= NOOFFSET
)) {
2208 printf("Warning invalid buffer %p (vp %p loffset %lld) did not have cleared bio_offset cache\n", bp
, vp
, loffset
);
2209 clearbiocache(&bp
->b_bio2
);
2213 * The buffer is locked. B_CACHE is cleared if the buffer is
2216 if (bp
->b_flags
& B_INVAL
)
2217 bp
->b_flags
&= ~B_CACHE
;
2221 * Any size inconsistancy with a dirty buffer or a buffer
2222 * with a softupdates dependancy must be resolved. Resizing
2223 * the buffer in such circumstances can lead to problems.
2225 if (size
!= bp
->b_bcount
) {
2226 if (bp
->b_flags
& B_DELWRI
) {
2227 bp
->b_flags
|= B_NOCACHE
;
2228 VOP_BWRITE(bp
->b_vp
, bp
);
2229 } else if (LIST_FIRST(&bp
->b_dep
)) {
2230 bp
->b_flags
|= B_NOCACHE
;
2231 VOP_BWRITE(bp
->b_vp
, bp
);
2233 bp
->b_flags
|= B_RELBUF
;
2238 KKASSERT(size
<= bp
->b_kvasize
);
2239 KASSERT(bp
->b_loffset
!= NOOFFSET
,
2240 ("getblk: no buffer offset"));
2243 * A buffer with B_DELWRI set and B_CACHE clear must
2244 * be committed before we can return the buffer in
2245 * order to prevent the caller from issuing a read
2246 * ( due to B_CACHE not being set ) and overwriting
2249 * Most callers, including NFS and FFS, need this to
2250 * operate properly either because they assume they
2251 * can issue a read if B_CACHE is not set, or because
2252 * ( for example ) an uncached B_DELWRI might loop due
2253 * to softupdates re-dirtying the buffer. In the latter
2254 * case, B_CACHE is set after the first write completes,
2255 * preventing further loops.
2257 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2258 * above while extending the buffer, we cannot allow the
2259 * buffer to remain with B_CACHE set after the write
2260 * completes or it will represent a corrupt state. To
2261 * deal with this we set B_NOCACHE to scrap the buffer
2264 * We might be able to do something fancy, like setting
2265 * B_CACHE in bwrite() except if B_DELWRI is already set,
2266 * so the below call doesn't set B_CACHE, but that gets real
2267 * confusing. This is much easier.
2270 if ((bp
->b_flags
& (B_CACHE
|B_DELWRI
)) == B_DELWRI
) {
2271 bp
->b_flags
|= B_NOCACHE
;
2272 VOP_BWRITE(bp
->b_vp
, bp
);
2278 * Buffer is not in-core, create new buffer. The buffer
2279 * returned by getnewbuf() is locked. Note that the returned
2280 * buffer is also considered valid (not marked B_INVAL).
2282 * Calculating the offset for the I/O requires figuring out
2283 * the block size. We use DEV_BSIZE for VBLK or VCHR and
2284 * the mount's f_iosize otherwise. If the vnode does not
2285 * have an associated mount we assume that the passed size is
2288 * Note that vn_isdisk() cannot be used here since it may
2289 * return a failure for numerous reasons. Note that the
2290 * buffer size may be larger then the block size (the caller
2291 * will use block numbers with the proper multiple). Beware
2292 * of using any v_* fields which are part of unions. In
2293 * particular, in DragonFly the mount point overloading
2294 * mechanism is such that the underlying directory (with a
2295 * non-NULL v_mountedhere) is not a special case.
2299 if (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
)
2301 else if (vp
->v_mount
)
2302 bsize
= vp
->v_mount
->mnt_stat
.f_iosize
;
2306 maxsize
= size
+ (loffset
& PAGE_MASK
);
2307 maxsize
= imax(maxsize
, bsize
);
2309 if ((bp
= getnewbuf(slpflag
, slptimeo
, size
, maxsize
)) == NULL
) {
2310 if (slpflag
|| slptimeo
) {
2318 * This code is used to make sure that a buffer is not
2319 * created while the getnewbuf routine is blocked.
2320 * This can be a problem whether the vnode is locked or not.
2321 * If the buffer is created out from under us, we have to
2322 * throw away the one we just created. There is now window
2323 * race because we are safely running in a critical section
2324 * from the point of the duplicate buffer creation through
2325 * to here, and we've locked the buffer.
2327 if (findblk(vp
, loffset
)) {
2328 bp
->b_flags
|= B_INVAL
;
2334 * Insert the buffer into the hash, so that it can
2335 * be found by findblk().
2337 * Make sure the translation layer has been cleared.
2339 bp
->b_loffset
= loffset
;
2340 bp
->b_bio2
.bio_offset
= NOOFFSET
;
2341 /* bp->b_bio2.bio_next = NULL; */
2346 * All vnode-based buffers must be backed by a VM object.
2348 KKASSERT(vp
->v_object
!= NULL
);
2349 bp
->b_flags
|= B_VMIO
;
2350 KKASSERT(bp
->b_cmd
== BUF_CMD_DONE
);
2362 * Get an empty, disassociated buffer of given size. The buffer is
2363 * initially set to B_INVAL.
2365 * critical section protection is not required for the allocbuf()
2366 * call because races are impossible here.
2374 maxsize
= (size
+ BKVAMASK
) & ~BKVAMASK
;
2377 while ((bp
= getnewbuf(0, 0, size
, maxsize
)) == 0)
2381 bp
->b_flags
|= B_INVAL
; /* b_dep cleared by getnewbuf() */
2389 * This code constitutes the buffer memory from either anonymous system
2390 * memory (in the case of non-VMIO operations) or from an associated
2391 * VM object (in the case of VMIO operations). This code is able to
2392 * resize a buffer up or down.
2394 * Note that this code is tricky, and has many complications to resolve
2395 * deadlock or inconsistant data situations. Tread lightly!!!
2396 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2397 * the caller. Calling this code willy nilly can result in the loss of data.
2399 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2400 * B_CACHE for the non-VMIO case.
2402 * This routine does not need to be called from a critical section but you
2403 * must own the buffer.
2406 allocbuf(struct buf
*bp
, int size
)
2408 int newbsize
, mbsize
;
2411 if (BUF_REFCNT(bp
) == 0)
2412 panic("allocbuf: buffer not busy");
2414 if (bp
->b_kvasize
< size
)
2415 panic("allocbuf: buffer too small");
2417 if ((bp
->b_flags
& B_VMIO
) == 0) {
2421 * Just get anonymous memory from the kernel. Don't
2422 * mess with B_CACHE.
2424 mbsize
= (size
+ DEV_BSIZE
- 1) & ~(DEV_BSIZE
- 1);
2425 if (bp
->b_flags
& B_MALLOC
)
2428 newbsize
= round_page(size
);
2430 if (newbsize
< bp
->b_bufsize
) {
2432 * Malloced buffers are not shrunk
2434 if (bp
->b_flags
& B_MALLOC
) {
2436 bp
->b_bcount
= size
;
2438 free(bp
->b_data
, M_BIOBUF
);
2439 if (bp
->b_bufsize
) {
2440 bufmallocspace
-= bp
->b_bufsize
;
2444 bp
->b_data
= bp
->b_kvabase
;
2446 bp
->b_flags
&= ~B_MALLOC
;
2452 (vm_offset_t
) bp
->b_data
+ newbsize
,
2453 (vm_offset_t
) bp
->b_data
+ bp
->b_bufsize
);
2454 } else if (newbsize
> bp
->b_bufsize
) {
2456 * We only use malloced memory on the first allocation.
2457 * and revert to page-allocated memory when the buffer
2460 if ((bufmallocspace
< maxbufmallocspace
) &&
2461 (bp
->b_bufsize
== 0) &&
2462 (mbsize
<= PAGE_SIZE
/2)) {
2464 bp
->b_data
= malloc(mbsize
, M_BIOBUF
, M_WAITOK
);
2465 bp
->b_bufsize
= mbsize
;
2466 bp
->b_bcount
= size
;
2467 bp
->b_flags
|= B_MALLOC
;
2468 bufmallocspace
+= mbsize
;
2474 * If the buffer is growing on its other-than-first
2475 * allocation, then we revert to the page-allocation
2478 if (bp
->b_flags
& B_MALLOC
) {
2479 origbuf
= bp
->b_data
;
2480 origbufsize
= bp
->b_bufsize
;
2481 bp
->b_data
= bp
->b_kvabase
;
2482 if (bp
->b_bufsize
) {
2483 bufmallocspace
-= bp
->b_bufsize
;
2487 bp
->b_flags
&= ~B_MALLOC
;
2488 newbsize
= round_page(newbsize
);
2492 (vm_offset_t
) bp
->b_data
+ bp
->b_bufsize
,
2493 (vm_offset_t
) bp
->b_data
+ newbsize
);
2495 bcopy(origbuf
, bp
->b_data
, origbufsize
);
2496 free(origbuf
, M_BIOBUF
);
2503 newbsize
= (size
+ DEV_BSIZE
- 1) & ~(DEV_BSIZE
- 1);
2504 desiredpages
= ((int)(bp
->b_loffset
& PAGE_MASK
) +
2505 newbsize
+ PAGE_MASK
) >> PAGE_SHIFT
;
2506 KKASSERT(desiredpages
<= XIO_INTERNAL_PAGES
);
2508 if (bp
->b_flags
& B_MALLOC
)
2509 panic("allocbuf: VMIO buffer can't be malloced");
2511 * Set B_CACHE initially if buffer is 0 length or will become
2514 if (size
== 0 || bp
->b_bufsize
== 0)
2515 bp
->b_flags
|= B_CACHE
;
2517 if (newbsize
< bp
->b_bufsize
) {
2519 * DEV_BSIZE aligned new buffer size is less then the
2520 * DEV_BSIZE aligned existing buffer size. Figure out
2521 * if we have to remove any pages.
2523 if (desiredpages
< bp
->b_xio
.xio_npages
) {
2524 for (i
= desiredpages
; i
< bp
->b_xio
.xio_npages
; i
++) {
2526 * the page is not freed here -- it
2527 * is the responsibility of
2528 * vnode_pager_setsize
2530 m
= bp
->b_xio
.xio_pages
[i
];
2531 KASSERT(m
!= bogus_page
,
2532 ("allocbuf: bogus page found"));
2533 while (vm_page_sleep_busy(m
, TRUE
, "biodep"))
2536 bp
->b_xio
.xio_pages
[i
] = NULL
;
2537 vm_page_unwire(m
, 0);
2539 pmap_qremove((vm_offset_t
) trunc_page((vm_offset_t
)bp
->b_data
) +
2540 (desiredpages
<< PAGE_SHIFT
), (bp
->b_xio
.xio_npages
- desiredpages
));
2541 bp
->b_xio
.xio_npages
= desiredpages
;
2543 } else if (size
> bp
->b_bcount
) {
2545 * We are growing the buffer, possibly in a
2546 * byte-granular fashion.
2554 * Step 1, bring in the VM pages from the object,
2555 * allocating them if necessary. We must clear
2556 * B_CACHE if these pages are not valid for the
2557 * range covered by the buffer.
2559 * critical section protection is required to protect
2560 * against interrupts unbusying and freeing pages
2561 * between our vm_page_lookup() and our
2562 * busycheck/wiring call.
2568 while (bp
->b_xio
.xio_npages
< desiredpages
) {
2572 pi
= OFF_TO_IDX(bp
->b_loffset
) + bp
->b_xio
.xio_npages
;
2573 if ((m
= vm_page_lookup(obj
, pi
)) == NULL
) {
2575 * note: must allocate system pages
2576 * since blocking here could intefere
2577 * with paging I/O, no matter which
2580 m
= vm_page_alloc(obj
, pi
, VM_ALLOC_NORMAL
| VM_ALLOC_SYSTEM
);
2583 vm_pageout_deficit
+= desiredpages
-
2584 bp
->b_xio
.xio_npages
;
2588 bp
->b_flags
&= ~B_CACHE
;
2589 bp
->b_xio
.xio_pages
[bp
->b_xio
.xio_npages
] = m
;
2590 ++bp
->b_xio
.xio_npages
;
2596 * We found a page. If we have to sleep on it,
2597 * retry because it might have gotten freed out
2600 * We can only test PG_BUSY here. Blocking on
2601 * m->busy might lead to a deadlock:
2603 * vm_fault->getpages->cluster_read->allocbuf
2607 if (vm_page_sleep_busy(m
, FALSE
, "pgtblk"))
2611 * We have a good page. Should we wakeup the
2614 if ((curthread
!= pagethread
) &&
2615 ((m
->queue
- m
->pc
) == PQ_CACHE
) &&
2616 ((vmstats
.v_free_count
+ vmstats
.v_cache_count
) <
2617 (vmstats
.v_free_min
+ vmstats
.v_cache_min
))) {
2618 pagedaemon_wakeup();
2620 vm_page_flag_clear(m
, PG_ZERO
);
2622 bp
->b_xio
.xio_pages
[bp
->b_xio
.xio_npages
] = m
;
2623 ++bp
->b_xio
.xio_npages
;
2628 * Step 2. We've loaded the pages into the buffer,
2629 * we have to figure out if we can still have B_CACHE
2630 * set. Note that B_CACHE is set according to the
2631 * byte-granular range ( bcount and size ), not the
2632 * aligned range ( newbsize ).
2634 * The VM test is against m->valid, which is DEV_BSIZE
2635 * aligned. Needless to say, the validity of the data
2636 * needs to also be DEV_BSIZE aligned. Note that this
2637 * fails with NFS if the server or some other client
2638 * extends the file's EOF. If our buffer is resized,
2639 * B_CACHE may remain set! XXX
2642 toff
= bp
->b_bcount
;
2643 tinc
= PAGE_SIZE
- ((bp
->b_loffset
+ toff
) & PAGE_MASK
);
2645 while ((bp
->b_flags
& B_CACHE
) && toff
< size
) {
2648 if (tinc
> (size
- toff
))
2651 pi
= ((bp
->b_loffset
& PAGE_MASK
) + toff
) >>
2659 bp
->b_xio
.xio_pages
[pi
]
2666 * Step 3, fixup the KVM pmap. Remember that
2667 * bp->b_data is relative to bp->b_loffset, but
2668 * bp->b_loffset may be offset into the first page.
2671 bp
->b_data
= (caddr_t
)
2672 trunc_page((vm_offset_t
)bp
->b_data
);
2674 (vm_offset_t
)bp
->b_data
,
2675 bp
->b_xio
.xio_pages
,
2676 bp
->b_xio
.xio_npages
2678 bp
->b_data
= (caddr_t
)((vm_offset_t
)bp
->b_data
|
2679 (vm_offset_t
)(bp
->b_loffset
& PAGE_MASK
));
2682 if (newbsize
< bp
->b_bufsize
)
2684 bp
->b_bufsize
= newbsize
; /* actual buffer allocation */
2685 bp
->b_bcount
= size
; /* requested buffer size */
2692 * Wait for buffer I/O completion, returning error status. The buffer
2693 * is left locked on return. B_EINTR is converted into an EINTR error
2696 * NOTE! The original b_cmd is lost on return, since b_cmd will be
2697 * set to BUF_CMD_DONE.
2700 biowait(struct buf
* bp
)
2703 while (bp
->b_cmd
!= BUF_CMD_DONE
) {
2704 if (bp
->b_cmd
== BUF_CMD_READ
)
2705 tsleep(bp
, 0, "biord", 0);
2707 tsleep(bp
, 0, "biowr", 0);
2710 if (bp
->b_flags
& B_EINTR
) {
2711 bp
->b_flags
&= ~B_EINTR
;
2714 if (bp
->b_flags
& B_ERROR
) {
2715 return (bp
->b_error
? bp
->b_error
: EIO
);
2722 * This associates a tracking count with an I/O. vn_strategy() and
2723 * dev_dstrategy() do this automatically but there are a few cases
2724 * where a vnode or device layer is bypassed when a block translation
2725 * is cached. In such cases bio_start_transaction() may be called on
2726 * the bypassed layers so the system gets an I/O in progress indication
2727 * for those higher layers.
2730 bio_start_transaction(struct bio
*bio
, struct bio_track
*track
)
2732 bio
->bio_track
= track
;
2733 atomic_add_int(&track
->bk_active
, 1);
2737 * Initiate I/O on a vnode.
2740 vn_strategy(struct vnode
*vp
, struct bio
*bio
)
2742 struct bio_track
*track
;
2744 KKASSERT(bio
->bio_buf
->b_cmd
!= BUF_CMD_DONE
);
2745 if (bio
->bio_buf
->b_cmd
== BUF_CMD_READ
)
2746 track
= &vp
->v_track_read
;
2748 track
= &vp
->v_track_write
;
2749 bio
->bio_track
= track
;
2750 atomic_add_int(&track
->bk_active
, 1);
2751 vop_strategy(*vp
->v_ops
, vp
, bio
);
2758 * Finish I/O on a buffer, optionally calling a completion function.
2759 * This is usually called from an interrupt so process blocking is
2762 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2763 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
2764 * assuming B_INVAL is clear.
2766 * For the VMIO case, we set B_CACHE if the op was a read and no
2767 * read error occured, or if the op was a write. B_CACHE is never
2768 * set if the buffer is invalid or otherwise uncacheable.
2770 * biodone does not mess with B_INVAL, allowing the I/O routine or the
2771 * initiator to leave B_INVAL set to brelse the buffer out of existance
2772 * in the biodone routine.
2775 biodone(struct bio
*bio
)
2777 struct buf
*bp
= bio
->bio_buf
;
2782 KASSERT(BUF_REFCNTNB(bp
) > 0,
2783 ("biodone: bp %p not busy %d", bp
, BUF_REFCNTNB(bp
)));
2784 KASSERT(bp
->b_cmd
!= BUF_CMD_DONE
,
2785 ("biodone: bp %p already done!", bp
));
2787 runningbufwakeup(bp
);
2790 * Run up the chain of BIO's. Leave b_cmd intact for the duration.
2793 biodone_t
*done_func
;
2794 struct bio_track
*track
;
2797 * BIO tracking. Most but not all BIOs are tracked.
2799 if ((track
= bio
->bio_track
) != NULL
) {
2800 atomic_subtract_int(&track
->bk_active
, 1);
2801 if (track
->bk_active
< 0) {
2802 panic("biodone: bad active count bio %p\n",
2805 if (track
->bk_waitflag
) {
2806 track
->bk_waitflag
= 0;
2809 bio
->bio_track
= NULL
;
2813 * A bio_done function terminates the loop. The function
2814 * will be responsible for any further chaining and/or
2815 * buffer management.
2817 * WARNING! The done function can deallocate the buffer!
2819 if ((done_func
= bio
->bio_done
) != NULL
) {
2820 bio
->bio_done
= NULL
;
2825 bio
= bio
->bio_prev
;
2829 bp
->b_cmd
= BUF_CMD_DONE
;
2832 * Only reads and writes are processed past this point.
2834 if (cmd
!= BUF_CMD_READ
&& cmd
!= BUF_CMD_WRITE
) {
2841 * Warning: softupdates may re-dirty the buffer.
2843 if (LIST_FIRST(&bp
->b_dep
) != NULL
&& bioops
.io_complete
)
2844 (*bioops
.io_complete
)(bp
);
2846 if (bp
->b_flags
& B_VMIO
) {
2852 struct vnode
*vp
= bp
->b_vp
;
2856 #if defined(VFS_BIO_DEBUG)
2857 if (vp
->v_holdcnt
== 0)
2858 panic("biodone: zero vnode hold count");
2859 if ((vp
->v_flag
& VOBJBUF
) == 0)
2860 panic("biodone: vnode is not setup for merged cache");
2863 foff
= bp
->b_loffset
;
2864 KASSERT(foff
!= NOOFFSET
, ("biodone: no buffer offset"));
2865 KASSERT(obj
!= NULL
, ("biodone: missing VM object"));
2867 #if defined(VFS_BIO_DEBUG)
2868 if (obj
->paging_in_progress
< bp
->b_xio
.xio_npages
) {
2869 printf("biodone: paging in progress(%d) < bp->b_xio.xio_npages(%d)\n",
2870 obj
->paging_in_progress
, bp
->b_xio
.xio_npages
);
2875 * Set B_CACHE if the op was a normal read and no error
2876 * occured. B_CACHE is set for writes in the b*write()
2879 iosize
= bp
->b_bcount
- bp
->b_resid
;
2880 if (cmd
== BUF_CMD_READ
&& (bp
->b_flags
& (B_INVAL
|B_NOCACHE
|B_ERROR
)) == 0) {
2881 bp
->b_flags
|= B_CACHE
;
2884 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
2888 resid
= ((foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
) - foff
;
2893 * cleanup bogus pages, restoring the originals. Since
2894 * the originals should still be wired, we don't have
2895 * to worry about interrupt/freeing races destroying
2896 * the VM object association.
2898 m
= bp
->b_xio
.xio_pages
[i
];
2899 if (m
== bogus_page
) {
2901 m
= vm_page_lookup(obj
, OFF_TO_IDX(foff
));
2903 panic("biodone: page disappeared");
2904 bp
->b_xio
.xio_pages
[i
] = m
;
2905 pmap_qenter(trunc_page((vm_offset_t
)bp
->b_data
),
2906 bp
->b_xio
.xio_pages
, bp
->b_xio
.xio_npages
);
2908 #if defined(VFS_BIO_DEBUG)
2909 if (OFF_TO_IDX(foff
) != m
->pindex
) {
2911 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
2912 (unsigned long)foff
, m
->pindex
);
2917 * In the write case, the valid and clean bits are
2918 * already changed correctly ( see bdwrite() ), so we
2919 * only need to do this here in the read case.
2921 if (cmd
== BUF_CMD_READ
&& !bogusflag
&& resid
> 0) {
2922 vfs_page_set_valid(bp
, foff
, i
, m
);
2924 vm_page_flag_clear(m
, PG_ZERO
);
2927 * when debugging new filesystems or buffer I/O methods, this
2928 * is the most common error that pops up. if you see this, you
2929 * have not set the page busy flag correctly!!!
2932 printf("biodone: page busy < 0, "
2933 "pindex: %d, foff: 0x(%x,%x), "
2934 "resid: %d, index: %d\n",
2935 (int) m
->pindex
, (int)(foff
>> 32),
2936 (int) foff
& 0xffffffff, resid
, i
);
2937 if (!vn_isdisk(vp
, NULL
))
2938 printf(" iosize: %ld, loffset: %lld, flags: 0x%08x, npages: %d\n",
2939 bp
->b_vp
->v_mount
->mnt_stat
.f_iosize
,
2941 bp
->b_flags
, bp
->b_xio
.xio_npages
);
2943 printf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
2945 bp
->b_flags
, bp
->b_xio
.xio_npages
);
2946 printf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
2947 m
->valid
, m
->dirty
, m
->wire_count
);
2948 panic("biodone: page busy < 0");
2950 vm_page_io_finish(m
);
2951 vm_object_pip_subtract(obj
, 1);
2952 foff
= (foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
;
2956 vm_object_pip_wakeupn(obj
, 0);
2960 * For asynchronous completions, release the buffer now. The brelse
2961 * will do a wakeup there if necessary - so no need to do a wakeup
2962 * here in the async case. The sync case always needs to do a wakeup.
2965 if (bp
->b_flags
& B_ASYNC
) {
2966 if ((bp
->b_flags
& (B_NOCACHE
| B_INVAL
| B_ERROR
| B_RELBUF
)) != 0)
2979 * This routine is called in lieu of iodone in the case of
2980 * incomplete I/O. This keeps the busy status for pages
2984 vfs_unbusy_pages(struct buf
*bp
)
2988 runningbufwakeup(bp
);
2989 if (bp
->b_flags
& B_VMIO
) {
2990 struct vnode
*vp
= bp
->b_vp
;
2995 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
2996 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
2999 * When restoring bogus changes the original pages
3000 * should still be wired, so we are in no danger of
3001 * losing the object association and do not need
3002 * critical section protection particularly.
3004 if (m
== bogus_page
) {
3005 m
= vm_page_lookup(obj
, OFF_TO_IDX(bp
->b_loffset
) + i
);
3007 panic("vfs_unbusy_pages: page missing");
3009 bp
->b_xio
.xio_pages
[i
] = m
;
3010 pmap_qenter(trunc_page((vm_offset_t
)bp
->b_data
),
3011 bp
->b_xio
.xio_pages
, bp
->b_xio
.xio_npages
);
3013 vm_object_pip_subtract(obj
, 1);
3014 vm_page_flag_clear(m
, PG_ZERO
);
3015 vm_page_io_finish(m
);
3017 vm_object_pip_wakeupn(obj
, 0);
3022 * vfs_page_set_valid:
3024 * Set the valid bits in a page based on the supplied offset. The
3025 * range is restricted to the buffer's size.
3027 * This routine is typically called after a read completes.
3030 vfs_page_set_valid(struct buf
*bp
, vm_ooffset_t off
, int pageno
, vm_page_t m
)
3032 vm_ooffset_t soff
, eoff
;
3035 * Start and end offsets in buffer. eoff - soff may not cross a
3036 * page boundry or cross the end of the buffer. The end of the
3037 * buffer, in this case, is our file EOF, not the allocation size
3041 eoff
= (off
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
;
3042 if (eoff
> bp
->b_loffset
+ bp
->b_bcount
)
3043 eoff
= bp
->b_loffset
+ bp
->b_bcount
;
3046 * Set valid range. This is typically the entire buffer and thus the
3050 vm_page_set_validclean(
3052 (vm_offset_t
) (soff
& PAGE_MASK
),
3053 (vm_offset_t
) (eoff
- soff
)
3061 * This routine is called before a device strategy routine.
3062 * It is used to tell the VM system that paging I/O is in
3063 * progress, and treat the pages associated with the buffer
3064 * almost as being PG_BUSY. Also the object 'paging_in_progress'
3065 * flag is handled to make sure that the object doesn't become
3068 * Since I/O has not been initiated yet, certain buffer flags
3069 * such as B_ERROR or B_INVAL may be in an inconsistant state
3070 * and should be ignored.
3073 vfs_busy_pages(struct vnode
*vp
, struct buf
*bp
)
3076 struct proc
*p
= curthread
->td_proc
;
3079 * The buffer's I/O command must already be set. If reading,
3080 * B_CACHE must be 0 (double check against callers only doing
3081 * I/O when B_CACHE is 0).
3083 KKASSERT(bp
->b_cmd
!= BUF_CMD_DONE
);
3084 KKASSERT(bp
->b_cmd
== BUF_CMD_WRITE
|| (bp
->b_flags
& B_CACHE
) == 0);
3086 if (bp
->b_flags
& B_VMIO
) {
3091 foff
= bp
->b_loffset
;
3092 KASSERT(bp
->b_loffset
!= NOOFFSET
,
3093 ("vfs_busy_pages: no buffer offset"));
3097 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3098 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
3099 if (vm_page_sleep_busy(m
, FALSE
, "vbpage"))
3104 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3105 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
3107 vm_page_flag_clear(m
, PG_ZERO
);
3108 if ((bp
->b_flags
& B_CLUSTER
) == 0) {
3109 vm_object_pip_add(obj
, 1);
3110 vm_page_io_start(m
);
3114 * When readying a vnode-backed buffer for a write
3115 * we must zero-fill any invalid portions of the
3118 * When readying a vnode-backed buffer for a read
3119 * we must replace any dirty pages with a bogus
3120 * page so we do not destroy dirty data when
3121 * filling in gaps. Dirty pages might not
3122 * necessarily be marked dirty yet, so use m->valid
3123 * as a reasonable test.
3125 * Bogus page replacement is, uh, bogus. We need
3126 * to find a better way.
3128 vm_page_protect(m
, VM_PROT_NONE
);
3129 if (bp
->b_cmd
== BUF_CMD_WRITE
) {
3130 vfs_page_set_valid(bp
, foff
, i
, m
);
3131 } else if (m
->valid
== VM_PAGE_BITS_ALL
) {
3132 bp
->b_xio
.xio_pages
[i
] = bogus_page
;
3135 foff
= (foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
;
3138 pmap_qenter(trunc_page((vm_offset_t
)bp
->b_data
),
3139 bp
->b_xio
.xio_pages
, bp
->b_xio
.xio_npages
);
3143 * This is the easiest place to put the process accounting for the I/O
3147 if (bp
->b_cmd
== BUF_CMD_READ
)
3148 p
->p_stats
->p_ru
.ru_inblock
++;
3150 p
->p_stats
->p_ru
.ru_oublock
++;
3157 * Tell the VM system that the pages associated with this buffer
3158 * are clean. This is used for delayed writes where the data is
3159 * going to go to disk eventually without additional VM intevention.
3161 * Note that while we only really need to clean through to b_bcount, we
3162 * just go ahead and clean through to b_bufsize.
3165 vfs_clean_pages(struct buf
*bp
)
3169 if (bp
->b_flags
& B_VMIO
) {
3172 foff
= bp
->b_loffset
;
3173 KASSERT(foff
!= NOOFFSET
, ("vfs_clean_pages: no buffer offset"));
3174 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3175 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
3176 vm_ooffset_t noff
= (foff
+ PAGE_SIZE
) & ~(off_t
)PAGE_MASK
;
3177 vm_ooffset_t eoff
= noff
;
3179 if (eoff
> bp
->b_loffset
+ bp
->b_bufsize
)
3180 eoff
= bp
->b_loffset
+ bp
->b_bufsize
;
3181 vfs_page_set_valid(bp
, foff
, i
, m
);
3182 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3189 * vfs_bio_set_validclean:
3191 * Set the range within the buffer to valid and clean. The range is
3192 * relative to the beginning of the buffer, b_loffset. Note that
3193 * b_loffset itself may be offset from the beginning of the first page.
3197 vfs_bio_set_validclean(struct buf
*bp
, int base
, int size
)
3199 if (bp
->b_flags
& B_VMIO
) {
3204 * Fixup base to be relative to beginning of first page.
3205 * Set initial n to be the maximum number of bytes in the
3206 * first page that can be validated.
3209 base
+= (bp
->b_loffset
& PAGE_MASK
);
3210 n
= PAGE_SIZE
- (base
& PAGE_MASK
);
3212 for (i
= base
/ PAGE_SIZE
; size
> 0 && i
< bp
->b_xio
.xio_npages
; ++i
) {
3213 vm_page_t m
= bp
->b_xio
.xio_pages
[i
];
3218 vm_page_set_validclean(m
, base
& PAGE_MASK
, n
);
3229 * Clear a buffer. This routine essentially fakes an I/O, so we need
3230 * to clear B_ERROR and B_INVAL.
3232 * Note that while we only theoretically need to clear through b_bcount,
3233 * we go ahead and clear through b_bufsize.
3237 vfs_bio_clrbuf(struct buf
*bp
)
3241 if ((bp
->b_flags
& (B_VMIO
| B_MALLOC
)) == B_VMIO
) {
3242 bp
->b_flags
&= ~(B_INVAL
|B_ERROR
);
3243 if ((bp
->b_xio
.xio_npages
== 1) && (bp
->b_bufsize
< PAGE_SIZE
) &&
3244 (bp
->b_loffset
& PAGE_MASK
) == 0) {
3245 mask
= (1 << (bp
->b_bufsize
/ DEV_BSIZE
)) - 1;
3246 if ((bp
->b_xio
.xio_pages
[0]->valid
& mask
) == mask
) {
3250 if (((bp
->b_xio
.xio_pages
[0]->flags
& PG_ZERO
) == 0) &&
3251 ((bp
->b_xio
.xio_pages
[0]->valid
& mask
) == 0)) {
3252 bzero(bp
->b_data
, bp
->b_bufsize
);
3253 bp
->b_xio
.xio_pages
[0]->valid
|= mask
;
3258 ea
= sa
= bp
->b_data
;
3259 for(i
=0;i
<bp
->b_xio
.xio_npages
;i
++,sa
=ea
) {
3260 int j
= ((vm_offset_t
)sa
& PAGE_MASK
) / DEV_BSIZE
;
3261 ea
= (caddr_t
)trunc_page((vm_offset_t
)sa
+ PAGE_SIZE
);
3262 ea
= (caddr_t
)(vm_offset_t
)ulmin(
3263 (u_long
)(vm_offset_t
)ea
,
3264 (u_long
)(vm_offset_t
)bp
->b_data
+ bp
->b_bufsize
);
3265 mask
= ((1 << ((ea
- sa
) / DEV_BSIZE
)) - 1) << j
;
3266 if ((bp
->b_xio
.xio_pages
[i
]->valid
& mask
) == mask
)
3268 if ((bp
->b_xio
.xio_pages
[i
]->valid
& mask
) == 0) {
3269 if ((bp
->b_xio
.xio_pages
[i
]->flags
& PG_ZERO
) == 0) {
3273 for (; sa
< ea
; sa
+= DEV_BSIZE
, j
++) {
3274 if (((bp
->b_xio
.xio_pages
[i
]->flags
& PG_ZERO
) == 0) &&
3275 (bp
->b_xio
.xio_pages
[i
]->valid
& (1<<j
)) == 0)
3276 bzero(sa
, DEV_BSIZE
);
3279 bp
->b_xio
.xio_pages
[i
]->valid
|= mask
;
3280 vm_page_flag_clear(bp
->b_xio
.xio_pages
[i
], PG_ZERO
);
3289 * vm_hold_load_pages:
3291 * Load pages into the buffer's address space. The pages are
3292 * allocated from the kernel object in order to reduce interference
3293 * with the any VM paging I/O activity. The range of loaded
3294 * pages will be wired.
3296 * If a page cannot be allocated, the 'pagedaemon' is woken up to
3297 * retrieve the full range (to - from) of pages.
3301 vm_hold_load_pages(struct buf
*bp
, vm_offset_t from
, vm_offset_t to
)
3307 to
= round_page(to
);
3308 from
= round_page(from
);
3309 index
= (from
- trunc_page((vm_offset_t
)bp
->b_data
)) >> PAGE_SHIFT
;
3311 for (pg
= from
; pg
< to
; pg
+= PAGE_SIZE
, index
++) {
3316 * Note: must allocate system pages since blocking here
3317 * could intefere with paging I/O, no matter which
3320 p
= vm_page_alloc(kernel_object
,
3321 ((pg
- VM_MIN_KERNEL_ADDRESS
) >> PAGE_SHIFT
),
3322 VM_ALLOC_NORMAL
| VM_ALLOC_SYSTEM
);
3324 vm_pageout_deficit
+= (to
- from
) >> PAGE_SHIFT
;
3329 p
->valid
= VM_PAGE_BITS_ALL
;
3330 vm_page_flag_clear(p
, PG_ZERO
);
3331 pmap_kenter(pg
, VM_PAGE_TO_PHYS(p
));
3332 bp
->b_xio
.xio_pages
[index
] = p
;
3335 bp
->b_xio
.xio_npages
= index
;
3339 * vm_hold_free_pages:
3341 * Return pages associated with the buffer back to the VM system.
3343 * The range of pages underlying the buffer's address space will
3344 * be unmapped and un-wired.
3347 vm_hold_free_pages(struct buf
*bp
, vm_offset_t from
, vm_offset_t to
)
3351 int index
, newnpages
;
3353 from
= round_page(from
);
3354 to
= round_page(to
);
3355 newnpages
= index
= (from
- trunc_page((vm_offset_t
)bp
->b_data
)) >> PAGE_SHIFT
;
3357 for (pg
= from
; pg
< to
; pg
+= PAGE_SIZE
, index
++) {
3358 p
= bp
->b_xio
.xio_pages
[index
];
3359 if (p
&& (index
< bp
->b_xio
.xio_npages
)) {
3361 printf("vm_hold_free_pages: doffset: %lld, loffset: %lld\n",
3362 bp
->b_bio2
.bio_offset
, bp
->b_loffset
);
3364 bp
->b_xio
.xio_pages
[index
] = NULL
;
3367 vm_page_unwire(p
, 0);
3371 bp
->b_xio
.xio_npages
= newnpages
;
3377 * Map an IO request into kernel virtual address space.
3379 * All requests are (re)mapped into kernel VA space.
3380 * Notice that we use b_bufsize for the size of the buffer
3381 * to be mapped. b_bcount might be modified by the driver.
3384 vmapbuf(struct buf
*bp
)
3386 caddr_t addr
, v
, kva
;
3393 * bp had better have a command
3395 KKASSERT(bp
->b_cmd
!= BUF_CMD_DONE
);
3397 if (bp
->b_bufsize
< 0)
3399 for (v
= bp
->b_saveaddr
,
3400 addr
= (caddr_t
)trunc_page((vm_offset_t
)bp
->b_data
),
3402 addr
< bp
->b_data
+ bp
->b_bufsize
;
3403 addr
+= PAGE_SIZE
, v
+= PAGE_SIZE
, pidx
++) {
3405 * Do the vm_fault if needed; do the copy-on-write thing
3406 * when reading stuff off device into memory.
3409 i
= vm_fault_quick((addr
>= bp
->b_data
) ? addr
: bp
->b_data
,
3410 (bp
->b_cmd
== BUF_CMD_READ
)?(VM_PROT_READ
|VM_PROT_WRITE
):VM_PROT_READ
);
3412 for (i
= 0; i
< pidx
; ++i
) {
3413 vm_page_unhold(bp
->b_xio
.xio_pages
[i
]);
3414 bp
->b_xio
.xio_pages
[i
] = NULL
;
3420 * WARNING! If sparc support is MFCd in the future this will
3421 * have to be changed from pmap_kextract() to pmap_extract()
3425 #error "If MFCing sparc support use pmap_extract"
3427 pa
= pmap_kextract((vm_offset_t
)addr
);
3429 printf("vmapbuf: warning, race against user address during I/O");
3432 m
= PHYS_TO_VM_PAGE(pa
);
3434 bp
->b_xio
.xio_pages
[pidx
] = m
;
3436 if (pidx
> btoc(MAXPHYS
))
3437 panic("vmapbuf: mapped more than MAXPHYS");
3438 pmap_qenter((vm_offset_t
)bp
->b_saveaddr
, bp
->b_xio
.xio_pages
, pidx
);
3440 kva
= bp
->b_saveaddr
;
3441 bp
->b_xio
.xio_npages
= pidx
;
3442 bp
->b_saveaddr
= bp
->b_data
;
3443 bp
->b_data
= kva
+ (((vm_offset_t
) bp
->b_data
) & PAGE_MASK
);
3450 * Free the io map PTEs associated with this IO operation.
3451 * We also invalidate the TLB entries and restore the original b_addr.
3454 vunmapbuf(struct buf
*bp
)
3460 npages
= bp
->b_xio
.xio_npages
;
3461 pmap_qremove(trunc_page((vm_offset_t
)bp
->b_data
),
3463 m
= bp
->b_xio
.xio_pages
;
3464 for (pidx
= 0; pidx
< npages
; pidx
++)
3465 vm_page_unhold(*m
++);
3467 bp
->b_data
= bp
->b_saveaddr
;
3471 * Scan all buffers in the system and issue the callback.
3474 scan_all_buffers(int (*callback
)(struct buf
*, void *), void *info
)
3480 for (n
= 0; n
< nbuf
; ++n
) {
3481 if ((error
= callback(&buf
[n
], info
)) < 0) {
3491 * print out statistics from the current status of the buffer pool
3492 * this can be toggeled by the system control option debug.syncprt
3501 int counts
[(MAXBSIZE
/ PAGE_SIZE
) + 1];
3502 static char *bname
[3] = { "LOCKED", "LRU", "AGE" };
3504 for (dp
= bufqueues
, i
= 0; dp
< &bufqueues
[3]; dp
++, i
++) {
3506 for (j
= 0; j
<= MAXBSIZE
/PAGE_SIZE
; j
++)
3509 TAILQ_FOREACH(bp
, dp
, b_freelist
) {
3510 counts
[bp
->b_bufsize
/PAGE_SIZE
]++;
3514 printf("%s: total-%d", bname
[i
], count
);
3515 for (j
= 0; j
<= MAXBSIZE
/PAGE_SIZE
; j
++)
3517 printf(", %d-%d", j
* PAGE_SIZE
, counts
[j
]);
3523 #include "opt_ddb.h"
3525 #include <ddb/ddb.h>
3527 DB_SHOW_COMMAND(buffer
, db_show_buffer
)
3530 struct buf
*bp
= (struct buf
*)addr
;
3533 db_printf("usage: show buffer <addr>\n");
3537 db_printf("b_flags = 0x%b\n", (u_int
)bp
->b_flags
, PRINT_BUF_FLAGS
);
3538 db_printf("b_cmd = %d\n", bp
->b_cmd
);
3539 db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
3540 "b_resid = %d\n, b_data = %p, "
3541 "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
3542 bp
->b_error
, bp
->b_bufsize
, bp
->b_bcount
, bp
->b_resid
,
3543 bp
->b_data
, bp
->b_bio2
.bio_offset
, (bp
->b_bio2
.bio_next
? bp
->b_bio2
.bio_next
->bio_offset
: (off_t
)-1));
3544 if (bp
->b_xio
.xio_npages
) {
3546 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
3547 bp
->b_xio
.xio_npages
);
3548 for (i
= 0; i
< bp
->b_xio
.xio_npages
; i
++) {
3550 m
= bp
->b_xio
.xio_pages
[i
];
3551 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m
->object
,
3552 (u_long
)m
->pindex
, (u_long
)VM_PAGE_TO_PHYS(m
));
3553 if ((i
+ 1) < bp
->b_xio
.xio_npages
)