2 * Copyright (c) 2000-2004 Apple Computer, Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
28 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
30 * Copyright (c) 1994 Christopher G. Demetriou
31 * Copyright (c) 1982, 1986, 1989, 1993
32 * The Regents of the University of California. All rights reserved.
33 * (c) UNIX System Laboratories, Inc.
34 * All or some portions of this file are derived from material licensed
35 * to the University of California by American Telephone and Telegraph
36 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
37 * the permission of UNIX System Laboratories, Inc.
39 * Redistribution and use in source and binary forms, with or without
40 * modification, are permitted provided that the following conditions
42 * 1. Redistributions of source code must retain the above copyright
43 * notice, this list of conditions and the following disclaimer.
44 * 2. Redistributions in binary form must reproduce the above copyright
45 * notice, this list of conditions and the following disclaimer in the
46 * documentation and/or other materials provided with the distribution.
47 * 3. All advertising materials mentioning features or use of this software
48 * must display the following acknowledgement:
49 * This product includes software developed by the University of
50 * California, Berkeley and its contributors.
51 * 4. Neither the name of the University nor the names of its contributors
52 * may be used to endorse or promote products derived from this software
53 * without specific prior written permission.
55 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
56 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
57 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
58 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
59 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
60 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
61 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
62 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
63 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
64 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
67 * @(#)vfs_bio.c 8.6 (Berkeley) 1/11/94
72 * Bach: The Design of the UNIX Operating System (Prentice Hall, 1986)
73 * Leffler, et al.: The Design and Implementation of the 4.3BSD
74 * UNIX Operating System (Addison Welley, 1989)
77 #include <sys/param.h>
78 #include <sys/systm.h>
79 #include <sys/proc_internal.h>
80 #include <sys/buf_internal.h>
81 #include <sys/vnode_internal.h>
82 #include <sys/mount_internal.h>
83 #include <sys/trace.h>
84 #include <sys/malloc.h>
85 #include <sys/resourcevar.h>
86 #include <miscfs/specfs/specdev.h>
88 #include <sys/kauth.h>
90 #include <kern/assert.h>
91 #endif /* DIAGNOSTIC */
92 #include <kern/task.h>
93 #include <kern/zalloc.h>
94 #include <kern/lock.h>
96 #include <vm/vm_kern.h>
98 #include <sys/kdebug.h>
99 #include <machine/spl.h>
102 static __inline__
void bufqinc(int q
);
103 static __inline__
void bufqdec(int q
);
106 static int bcleanbuf(buf_t bp
);
107 static int brecover_data(buf_t bp
);
108 static boolean_t
incore(vnode_t vp
, daddr64_t blkno
);
109 static buf_t
incore_locked(vnode_t vp
, daddr64_t blkno
);
110 /* timeout is in msecs */
111 static buf_t
getnewbuf(int slpflag
, int slptimeo
, int *queue
);
112 static void bremfree_locked(buf_t bp
);
113 static void buf_reassign(buf_t bp
, vnode_t newvp
);
114 static errno_t
buf_acquire_locked(buf_t bp
, int flags
, int slpflag
, int slptimeo
);
115 static int buf_iterprepare(vnode_t vp
, struct buflists
*, int flags
);
116 static void buf_itercomplete(vnode_t vp
, struct buflists
*, int flags
);
118 __private_extern__
int bdwrite_internal(buf_t
, int);
120 /* zone allocated buffer headers */
121 static void bufzoneinit(void);
122 static void bcleanbuf_thread_init(void);
123 static void bcleanbuf_thread(void);
125 static zone_t buf_hdr_zone
;
126 static int buf_hdr_count
;
130 * Definitions for the buffer hash lists.
132 #define BUFHASH(dvp, lbn) \
133 (&bufhashtbl[((long)(dvp) / sizeof(*(dvp)) + (int)(lbn)) & bufhash])
134 LIST_HEAD(bufhashhdr
, buf
) *bufhashtbl
, invalhash
;
137 /* Definitions for the buffer stats. */
138 struct bufstats bufstats
;
140 /* Number of delayed write buffers */
145 static TAILQ_HEAD(ioqueue
, buf
) iobufqueue
;
146 static TAILQ_HEAD(bqueues
, buf
) bufqueues
[BQUEUES
];
147 static int needbuffer
;
148 static int need_iobuffer
;
150 static lck_grp_t
*buf_mtx_grp
;
151 static lck_attr_t
*buf_mtx_attr
;
152 static lck_grp_attr_t
*buf_mtx_grp_attr
;
153 static lck_mtx_t
*iobuffer_mtxp
;
154 static lck_mtx_t
*buf_mtxp
;
156 static __inline__
int
165 * Insq/Remq for the buffer free lists.
168 #define binsheadfree(bp, dp, whichq) do { \
169 TAILQ_INSERT_HEAD(dp, bp, b_freelist); \
171 (bp)->b_whichq = whichq; \
172 (bp)->b_timestamp = buf_timestamp(); \
175 #define binstailfree(bp, dp, whichq) do { \
176 TAILQ_INSERT_TAIL(dp, bp, b_freelist); \
178 (bp)->b_whichq = whichq; \
179 (bp)->b_timestamp = buf_timestamp(); \
182 #define binsheadfree(bp, dp, whichq) do { \
183 TAILQ_INSERT_HEAD(dp, bp, b_freelist); \
184 (bp)->b_whichq = whichq; \
185 (bp)->b_timestamp = buf_timestamp(); \
188 #define binstailfree(bp, dp, whichq) do { \
189 TAILQ_INSERT_TAIL(dp, bp, b_freelist); \
190 (bp)->b_whichq = whichq; \
191 (bp)->b_timestamp = buf_timestamp(); \
196 #define BHASHENTCHECK(bp) \
197 if ((bp)->b_hash.le_prev != (struct buf **)0xdeadbeef) \
198 panic("%x: b_hash.le_prev is not deadbeef", (bp));
200 #define BLISTNONE(bp) \
201 (bp)->b_hash.le_next = (struct buf *)0; \
202 (bp)->b_hash.le_prev = (struct buf **)0xdeadbeef;
205 * Insq/Remq for the vnode usage lists.
207 #define bufinsvn(bp, dp) LIST_INSERT_HEAD(dp, bp, b_vnbufs)
208 #define bufremvn(bp) { \
209 LIST_REMOVE(bp, b_vnbufs); \
210 (bp)->b_vnbufs.le_next = NOLIST; \
214 * Time in seconds before a buffer on a list is
215 * considered as a stale buffer
217 #define LRU_IS_STALE 120 /* default value for the LRU */
218 #define AGE_IS_STALE 60 /* default value for the AGE */
219 #define META_IS_STALE 180 /* default value for the BQ_META */
221 int lru_is_stale
= LRU_IS_STALE
;
222 int age_is_stale
= AGE_IS_STALE
;
223 int meta_is_stale
= META_IS_STALE
;
227 /* LIST_INSERT_HEAD() with assertions */
228 static __inline__
void
229 blistenterhead(struct bufhashhdr
* head
, buf_t bp
)
231 if ((bp
->b_hash
.le_next
= (head
)->lh_first
) != NULL
)
232 (head
)->lh_first
->b_hash
.le_prev
= &(bp
)->b_hash
.le_next
;
233 (head
)->lh_first
= bp
;
234 bp
->b_hash
.le_prev
= &(head
)->lh_first
;
235 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
236 panic("blistenterhead: le_prev is deadbeef");
239 static __inline__
void
240 binshash(buf_t bp
, struct bufhashhdr
*dp
)
247 for(; nbp
!= NULL
; nbp
= nbp
->b_hash
.le_next
) {
249 panic("buf already in hashlist");
252 blistenterhead(dp
, bp
);
255 static __inline__
void
258 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
259 panic("bremhash le_prev is deadbeef");
260 if (bp
->b_hash
.le_next
== bp
)
261 panic("bremhash: next points to self");
263 if (bp
->b_hash
.le_next
!= NULL
)
264 bp
->b_hash
.le_next
->b_hash
.le_prev
= bp
->b_hash
.le_prev
;
265 *bp
->b_hash
.le_prev
= (bp
)->b_hash
.le_next
;
272 buf_valid(buf_t bp
) {
274 if ( (bp
->b_flags
& (B_DONE
| B_DELWRI
)) )
280 buf_fromcache(buf_t bp
) {
282 if ( (bp
->b_flags
& B_CACHE
) )
288 buf_markinvalid(buf_t bp
) {
290 SET(bp
->b_flags
, B_INVAL
);
294 buf_markdelayed(buf_t bp
) {
296 SET(bp
->b_flags
, B_DELWRI
);
297 buf_reassign(bp
, bp
->b_vp
);
301 buf_markeintr(buf_t bp
) {
303 SET(bp
->b_flags
, B_EINTR
);
307 buf_markaged(buf_t bp
) {
309 SET(bp
->b_flags
, B_AGE
);
313 buf_error(buf_t bp
) {
315 return (bp
->b_error
);
319 buf_seterror(buf_t bp
, errno_t error
) {
321 if ((bp
->b_error
= error
))
322 SET(bp
->b_flags
, B_ERROR
);
324 CLR(bp
->b_flags
, B_ERROR
);
328 buf_setflags(buf_t bp
, int32_t flags
) {
330 SET(bp
->b_flags
, (flags
& BUF_X_WRFLAGS
));
334 buf_clearflags(buf_t bp
, int32_t flags
) {
336 CLR(bp
->b_flags
, (flags
& BUF_X_WRFLAGS
));
340 buf_flags(buf_t bp
) {
342 return ((bp
->b_flags
& BUF_X_RDFLAGS
));
346 buf_reset(buf_t bp
, int32_t io_flags
) {
348 CLR(bp
->b_flags
, (B_READ
| B_WRITE
| B_ERROR
| B_DONE
| B_INVAL
| B_ASYNC
| B_NOCACHE
));
349 SET(bp
->b_flags
, (io_flags
& (B_ASYNC
| B_READ
| B_WRITE
| B_NOCACHE
)));
355 buf_count(buf_t bp
) {
357 return (bp
->b_bcount
);
361 buf_setcount(buf_t bp
, uint32_t bcount
) {
363 bp
->b_bcount
= bcount
;
369 return (bp
->b_bufsize
);
373 buf_setsize(buf_t bp
, uint32_t bufsize
) {
375 bp
->b_bufsize
= bufsize
;
379 buf_resid(buf_t bp
) {
381 return (bp
->b_resid
);
385 buf_setresid(buf_t bp
, uint32_t resid
) {
391 buf_dirtyoff(buf_t bp
) {
393 return (bp
->b_dirtyoff
);
397 buf_dirtyend(buf_t bp
) {
399 return (bp
->b_dirtyend
);
403 buf_setdirtyoff(buf_t bp
, uint32_t dirtyoff
) {
405 bp
->b_dirtyoff
= dirtyoff
;
409 buf_setdirtyend(buf_t bp
, uint32_t dirtyend
) {
411 bp
->b_dirtyend
= dirtyend
;
415 buf_dataptr(buf_t bp
) {
417 return (bp
->b_datap
);
421 buf_setdataptr(buf_t bp
, uintptr_t data
) {
427 buf_vnode(buf_t bp
) {
433 buf_setvnode(buf_t bp
, vnode_t vp
) {
440 buf_callback(buf_t bp
)
442 if ( !(bp
->b_lflags
& BL_IOBUF
) )
443 return ((void *) NULL
);
444 if ( !(bp
->b_flags
& B_CALL
) )
445 return ((void *) NULL
);
447 return ((void *)bp
->b_iodone
);
452 buf_setcallback(buf_t bp
, void (*callback
)(buf_t
, void *), void *transaction
)
455 if ( !(bp
->b_lflags
& BL_IOBUF
) )
459 bp
->b_flags
|= (B_CALL
| B_ASYNC
);
461 bp
->b_flags
&= ~B_CALL
;
462 bp
->b_transaction
= transaction
;
463 bp
->b_iodone
= callback
;
469 buf_setupl(buf_t bp
, upl_t upl
, uint32_t offset
)
472 if ( !(bp
->b_lflags
& BL_IOBUF
) )
476 bp
->b_flags
|= B_CLUSTER
;
478 bp
->b_flags
&= ~B_CLUSTER
;
480 bp
->b_uploffset
= offset
;
486 buf_clone(buf_t bp
, int io_offset
, int io_size
, void (*iodone
)(buf_t
, void *), void *arg
)
490 if (io_offset
< 0 || io_size
< 0)
493 if ((unsigned)(io_offset
+ io_size
) > (unsigned)bp
->b_bcount
)
496 if (bp
->b_flags
& B_CLUSTER
) {
497 if (io_offset
&& ((bp
->b_uploffset
+ io_offset
) & PAGE_MASK
))
500 if (((bp
->b_uploffset
+ io_offset
+ io_size
) & PAGE_MASK
) && ((io_offset
+ io_size
) < bp
->b_bcount
))
503 io_bp
= alloc_io_buf(bp
->b_vp
, 0);
505 io_bp
->b_flags
= bp
->b_flags
& (B_COMMIT_UPL
| B_META
| B_PAGEIO
| B_CLUSTER
| B_PHYS
| B_ASYNC
| B_READ
);
508 io_bp
->b_transaction
= arg
;
509 io_bp
->b_iodone
= iodone
;
510 io_bp
->b_flags
|= B_CALL
;
512 if (bp
->b_flags
& B_CLUSTER
) {
513 io_bp
->b_upl
= bp
->b_upl
;
514 io_bp
->b_uploffset
= bp
->b_uploffset
+ io_offset
;
516 io_bp
->b_datap
= (uintptr_t)(((char *)bp
->b_datap
) + io_offset
);
518 io_bp
->b_bcount
= io_size
;
526 buf_setfilter(buf_t bp
, void (*filter
)(buf_t
, void *), void *transaction
,
527 void **old_iodone
, void **old_transaction
)
530 *old_iodone
= (void *)(bp
->b_iodone
);
532 *old_transaction
= (void *)(bp
->b_transaction
);
534 bp
->b_transaction
= transaction
;
535 bp
->b_iodone
= filter
;
536 bp
->b_flags
|= B_FILTER
;
541 buf_blkno(buf_t bp
) {
543 return (bp
->b_blkno
);
547 buf_lblkno(buf_t bp
) {
549 return (bp
->b_lblkno
);
553 buf_setblkno(buf_t bp
, daddr64_t blkno
) {
559 buf_setlblkno(buf_t bp
, daddr64_t lblkno
) {
561 bp
->b_lblkno
= lblkno
;
565 buf_device(buf_t bp
) {
571 buf_setdevice(buf_t bp
, vnode_t vp
) {
573 if ((vp
->v_type
!= VBLK
) && (vp
->v_type
!= VCHR
))
575 bp
->b_dev
= vp
->v_rdev
;
582 buf_drvdata(buf_t bp
) {
584 return (bp
->b_drvdata
);
588 buf_setdrvdata(buf_t bp
, void *drvdata
) {
590 bp
->b_drvdata
= drvdata
;
594 buf_fsprivate(buf_t bp
) {
596 return (bp
->b_fsprivate
);
600 buf_setfsprivate(buf_t bp
, void *fsprivate
) {
602 bp
->b_fsprivate
= fsprivate
;
606 buf_rcred(buf_t bp
) {
608 return (bp
->b_rcred
);
612 buf_wcred(buf_t bp
) {
614 return (bp
->b_wcred
);
624 buf_uploffset(buf_t bp
) {
626 return ((uint32_t)(bp
->b_uploffset
));
637 buf_map(buf_t bp
, caddr_t
*io_addr
)
643 if ( !(bp
->b_flags
& B_CLUSTER
)) {
644 *io_addr
= (caddr_t
)bp
->b_datap
;
647 real_bp
= (buf_t
)(bp
->b_real_bp
);
649 if (real_bp
&& real_bp
->b_datap
) {
651 * b_real_bp is only valid if B_CLUSTER is SET
652 * if it's non-zero, than someone did a cluster_bp call
653 * if the backing physical pages were already mapped
654 * in before the call to cluster_bp (non-zero b_datap),
655 * than we just use that mapping
657 *io_addr
= (caddr_t
)real_bp
->b_datap
;
660 kret
= ubc_upl_map(bp
->b_upl
, &vaddr
); /* Map it in */
662 if (kret
!= KERN_SUCCESS
) {
667 vaddr
+= bp
->b_uploffset
;
669 *io_addr
= (caddr_t
)vaddr
;
680 if ( !(bp
->b_flags
& B_CLUSTER
))
683 * see buf_map for the explanation
685 real_bp
= (buf_t
)(bp
->b_real_bp
);
687 if (real_bp
&& real_bp
->b_datap
)
690 if (bp
->b_lflags
& BL_IOBUF
) {
692 * when we commit these pages, we'll hit
693 * it with UPL_COMMIT_INACTIVE which
694 * will clear the reference bit that got
695 * turned on when we touched the mapping
697 bp
->b_flags
|= B_AGE
;
699 kret
= ubc_upl_unmap(bp
->b_upl
);
701 if (kret
!= KERN_SUCCESS
)
708 buf_clear(buf_t bp
) {
711 if (buf_map(bp
, &baddr
) == 0) {
712 bzero(baddr
, bp
->b_bcount
);
721 * Read or write a buffer that is not contiguous on disk.
722 * buffer is marked done/error at the conclusion
725 buf_strategy_fragmented(vnode_t devvp
, buf_t bp
, off_t f_offset
, size_t contig_bytes
)
727 vnode_t vp
= buf_vnode(bp
);
728 buf_t io_bp
; /* For reading or writing a single block */
731 size_t io_contig_bytes
;
737 * save our starting point... the bp was already mapped
738 * in buf_strategy before we got called
739 * no sense doing it again.
741 io_blkno
= bp
->b_blkno
;
743 * Make sure we redo this mapping for the next I/O
744 * i.e. this can never be a 'permanent' mapping
746 bp
->b_blkno
= bp
->b_lblkno
;
749 * Get an io buffer to do the deblocking
751 io_bp
= alloc_io_buf(devvp
, 0);
753 io_bp
->b_lblkno
= bp
->b_lblkno
;
754 io_bp
->b_datap
= bp
->b_datap
;
755 io_resid
= bp
->b_bcount
;
756 io_direction
= bp
->b_flags
& B_READ
;
757 io_contig_bytes
= contig_bytes
;
759 if (bp
->b_flags
& B_READ
)
760 bmap_flags
= VNODE_READ
;
762 bmap_flags
= VNODE_WRITE
;
767 * this is unexepected, but we'll allow for it
769 bzero((caddr_t
)io_bp
->b_datap
, (int)io_contig_bytes
);
771 io_bp
->b_bcount
= io_contig_bytes
;
772 io_bp
->b_bufsize
= io_contig_bytes
;
773 io_bp
->b_resid
= io_contig_bytes
;
774 io_bp
->b_blkno
= io_blkno
;
776 buf_reset(io_bp
, io_direction
);
778 * Call the device to do the I/O and wait for it
780 if ((error
= VNOP_STRATEGY(io_bp
)))
782 if ((error
= (int)buf_biowait(io_bp
)))
784 if (io_bp
->b_resid
) {
785 io_resid
-= (io_contig_bytes
- io_bp
->b_resid
);
789 if ((io_resid
-= io_contig_bytes
) == 0)
791 f_offset
+= io_contig_bytes
;
792 io_bp
->b_datap
+= io_contig_bytes
;
795 * Map the current position to a physical block number
797 if ((error
= VNOP_BLOCKMAP(vp
, f_offset
, io_resid
, &io_blkno
, &io_contig_bytes
, NULL
, bmap_flags
, NULL
)))
803 buf_seterror(bp
, error
);
804 bp
->b_resid
= io_resid
;
806 * This I/O is now complete
815 * struct vnop_strategy_args {
820 buf_strategy(vnode_t devvp
, void *ap
)
822 buf_t bp
= ((struct vnop_strategy_args
*)ap
)->a_bp
;
823 vnode_t vp
= bp
->b_vp
;
827 if (vp
== NULL
|| vp
->v_type
== VCHR
|| vp
->v_type
== VBLK
)
828 panic("buf_strategy: b_vp == NULL || vtype == VCHR | VBLK\n");
830 * associate the physical device with
831 * with this buf_t even if we don't
832 * end up issuing the I/O...
834 bp
->b_dev
= devvp
->v_rdev
;
836 if (bp
->b_flags
& B_READ
)
837 bmap_flags
= VNODE_READ
;
839 bmap_flags
= VNODE_WRITE
;
841 if ( !(bp
->b_flags
& B_CLUSTER
)) {
845 * we have a UPL associated with this bp
846 * go through cluster_bp which knows how
847 * to deal with filesystem block sizes
848 * that aren't equal to the page size
850 return (cluster_bp(bp
));
852 if (bp
->b_blkno
== bp
->b_lblkno
) {
856 if ((error
= VNOP_BLKTOOFF(vp
, bp
->b_lblkno
, &f_offset
))) {
857 buf_seterror(bp
, error
);
862 if ((error
= VNOP_BLOCKMAP(vp
, f_offset
, bp
->b_bcount
, &bp
->b_blkno
, &contig_bytes
, NULL
, bmap_flags
, NULL
))) {
863 buf_seterror(bp
, error
);
868 if (bp
->b_blkno
== -1)
870 else if ((long)contig_bytes
< bp
->b_bcount
)
871 return (buf_strategy_fragmented(devvp
, bp
, f_offset
, contig_bytes
));
873 if (bp
->b_blkno
== -1) {
879 * we can issue the I/O because...
880 * either B_CLUSTER is set which
881 * means that the I/O is properly set
882 * up to be a multiple of the page size, or
883 * we were able to successfully set up the
884 * phsyical block mapping
886 return (VOCALL(devvp
->v_op
, VOFFSET(vnop_strategy
), ap
));
892 buf_alloc(vnode_t vp
)
894 return(alloc_io_buf(vp
, 0));
906 buf_iterate(vnode_t vp
, int (*callout
)(buf_t
, void *), int flags
, void *arg
) {
909 struct buflists local_iterblkhd
;
910 int lock_flags
= BAC_NOWAIT
| BAC_REMOVE
;
912 if (flags
& BUF_SKIP_LOCKED
)
913 lock_flags
|= BAC_SKIP_LOCKED
;
914 if (flags
& BUF_SKIP_NONLOCKED
)
915 lock_flags
|= BAC_SKIP_NONLOCKED
;
917 lck_mtx_lock(buf_mtxp
);
919 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_DIRTY
)) {
920 lck_mtx_unlock(buf_mtxp
);
923 while (!LIST_EMPTY(&local_iterblkhd
)) {
924 bp
= LIST_FIRST(&local_iterblkhd
);
925 LIST_REMOVE(bp
, b_vnbufs
);
926 LIST_INSERT_HEAD(&vp
->v_dirtyblkhd
, bp
, b_vnbufs
);
928 if (buf_acquire_locked(bp
, lock_flags
, 0, 0))
931 lck_mtx_unlock(buf_mtxp
);
933 retval
= callout(bp
, arg
);
941 case BUF_RETURNED_DONE
:
943 lck_mtx_lock(buf_mtxp
);
945 case BUF_CLAIMED_DONE
:
946 lck_mtx_lock(buf_mtxp
);
949 lck_mtx_lock(buf_mtxp
);
952 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
954 lck_mtx_unlock(buf_mtxp
);
959 * Flush out and invalidate all buffers associated with a vnode.
962 buf_invalidateblks(vnode_t vp
, int flags
, int slpflag
, int slptimeo
)
967 struct buflists local_iterblkhd
;
969 lck_mtx_lock(buf_mtxp
);
972 if (must_rescan
== 0)
974 * the lists may not be empty, but all that's left at this
975 * point are metadata or B_LOCKED buffers which are being
976 * skipped... we know this because we made it through both
977 * the clean and dirty lists without dropping buf_mtxp...
978 * each time we drop buf_mtxp we bump "must_rescan"
981 if (LIST_EMPTY(&vp
->v_cleanblkhd
) && LIST_EMPTY(&vp
->v_dirtyblkhd
))
985 * iterate the clean list
987 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_CLEAN
)) {
990 while (!LIST_EMPTY(&local_iterblkhd
)) {
991 bp
= LIST_FIRST(&local_iterblkhd
);
993 LIST_REMOVE(bp
, b_vnbufs
);
994 LIST_INSERT_HEAD(&vp
->v_cleanblkhd
, bp
, b_vnbufs
);
997 * some filesystems distinguish meta data blocks with a negative logical block #
999 if ((flags
& BUF_SKIP_META
) && (bp
->b_lblkno
< 0 || ISSET(bp
->b_flags
, B_META
)))
1002 if ( (error
= (int)buf_acquire_locked(bp
, BAC_REMOVE
| BAC_SKIP_LOCKED
, slpflag
, slptimeo
)) ) {
1003 if (error
== EDEADLK
)
1005 * this buffer was marked B_LOCKED...
1006 * we didn't drop buf_mtxp, so we
1007 * we don't need to rescan
1010 if (error
== EAGAIN
) {
1012 * found a busy buffer... we blocked and
1013 * dropped buf_mtxp, so we're going to
1014 * need to rescan after this pass is completed
1020 * got some kind of 'real' error out of the msleep
1021 * in buf_acquire_locked, terminate the scan and return the error
1023 buf_itercomplete(vp
, &local_iterblkhd
, VBI_CLEAN
);
1025 lck_mtx_unlock(buf_mtxp
);
1028 lck_mtx_unlock(buf_mtxp
);
1030 SET(bp
->b_flags
, B_INVAL
);
1033 lck_mtx_lock(buf_mtxp
);
1036 * by dropping buf_mtxp, we allow new
1037 * buffers to be added to the vnode list(s)
1038 * we'll have to rescan at least once more
1039 * if the queues aren't empty
1043 buf_itercomplete(vp
, &local_iterblkhd
, VBI_CLEAN
);
1047 * Now iterate on dirty blks
1049 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_DIRTY
)) {
1052 while (!LIST_EMPTY(&local_iterblkhd
)) {
1053 bp
= LIST_FIRST(&local_iterblkhd
);
1055 LIST_REMOVE(bp
, b_vnbufs
);
1056 LIST_INSERT_HEAD(&vp
->v_dirtyblkhd
, bp
, b_vnbufs
);
1059 * some filesystems distinguish meta data blocks with a negative logical block #
1061 if ((flags
& BUF_SKIP_META
) && (bp
->b_lblkno
< 0 || ISSET(bp
->b_flags
, B_META
)))
1064 if ( (error
= (int)buf_acquire_locked(bp
, BAC_REMOVE
| BAC_SKIP_LOCKED
, slpflag
, slptimeo
)) ) {
1065 if (error
== EDEADLK
)
1067 * this buffer was marked B_LOCKED...
1068 * we didn't drop buf_mtxp, so we
1069 * we don't need to rescan
1072 if (error
== EAGAIN
) {
1074 * found a busy buffer... we blocked and
1075 * dropped buf_mtxp, so we're going to
1076 * need to rescan after this pass is completed
1082 * got some kind of 'real' error out of the msleep
1083 * in buf_acquire_locked, terminate the scan and return the error
1085 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1087 lck_mtx_unlock(buf_mtxp
);
1090 lck_mtx_unlock(buf_mtxp
);
1092 SET(bp
->b_flags
, B_INVAL
);
1094 if (ISSET(bp
->b_flags
, B_DELWRI
) && (flags
& BUF_WRITE_DATA
))
1095 (void) VNOP_BWRITE(bp
);
1099 lck_mtx_lock(buf_mtxp
);
1101 * by dropping buf_mtxp, we allow new
1102 * buffers to be added to the vnode list(s)
1103 * we'll have to rescan at least once more
1104 * if the queues aren't empty
1108 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1110 lck_mtx_unlock(buf_mtxp
);
1116 buf_flushdirtyblks(vnode_t vp
, int wait
, int flags
, char *msg
) {
1118 int writes_issued
= 0;
1121 struct buflists local_iterblkhd
;
1122 int lock_flags
= BAC_NOWAIT
| BAC_REMOVE
;
1124 if (flags
& BUF_SKIP_LOCKED
)
1125 lock_flags
|= BAC_SKIP_LOCKED
;
1126 if (flags
& BUF_SKIP_NONLOCKED
)
1127 lock_flags
|= BAC_SKIP_NONLOCKED
;
1129 lck_mtx_lock(buf_mtxp
);
1131 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_DIRTY
) == 0) {
1132 while (!LIST_EMPTY(&local_iterblkhd
)) {
1133 bp
= LIST_FIRST(&local_iterblkhd
);
1134 LIST_REMOVE(bp
, b_vnbufs
);
1135 LIST_INSERT_HEAD(&vp
->v_dirtyblkhd
, bp
, b_vnbufs
);
1137 if ((error
= buf_acquire_locked(bp
, lock_flags
, 0, 0)) == EBUSY
)
1141 lck_mtx_unlock(buf_mtxp
);
1143 bp
->b_flags
&= ~B_LOCKED
;
1146 * Wait for I/O associated with indirect blocks to complete,
1147 * since there is no way to quickly wait for them below.
1149 if ((bp
->b_vp
== vp
) || (wait
== 0))
1150 (void) buf_bawrite(bp
);
1152 (void) VNOP_BWRITE(bp
);
1155 lck_mtx_lock(buf_mtxp
);
1157 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1159 lck_mtx_unlock(buf_mtxp
);
1162 (void)vnode_waitforwrites(vp
, 0, 0, 0, msg
);
1164 if (vp
->v_dirtyblkhd
.lh_first
&& busy
) {
1166 * we had one or more BUSY buffers on
1167 * the dirtyblock list... most likely
1168 * these are due to delayed writes that
1169 * were moved to the bclean queue but
1170 * have not yet been 'written'.
1171 * if we issued some writes on the
1172 * previous pass, we try again immediately
1173 * if we didn't, we'll sleep for some time
1174 * to allow the state to change...
1176 if (writes_issued
== 0) {
1177 (void)tsleep((caddr_t
)&vp
->v_numoutput
,
1178 PRIBIO
+ 1, "vnode_flushdirtyblks", hz
/20);
1190 * called with buf_mtxp held...
1191 * this lock protects the queue manipulation
1194 buf_iterprepare(vnode_t vp
, struct buflists
*iterheadp
, int flags
)
1196 struct buflists
* listheadp
;
1198 if (flags
& VBI_DIRTY
)
1199 listheadp
= &vp
->v_dirtyblkhd
;
1201 listheadp
= &vp
->v_cleanblkhd
;
1203 while (vp
->v_iterblkflags
& VBI_ITER
) {
1204 vp
->v_iterblkflags
|= VBI_ITERWANT
;
1205 msleep(&vp
->v_iterblkflags
, buf_mtxp
, 0, "buf_iterprepare", 0);
1207 if (LIST_EMPTY(listheadp
)) {
1208 LIST_INIT(iterheadp
);
1211 vp
->v_iterblkflags
|= VBI_ITER
;
1213 iterheadp
->lh_first
= listheadp
->lh_first
;
1214 listheadp
->lh_first
->b_vnbufs
.le_prev
= &iterheadp
->lh_first
;
1215 LIST_INIT(listheadp
);
1221 * called with buf_mtxp held...
1222 * this lock protects the queue manipulation
1225 buf_itercomplete(vnode_t vp
, struct buflists
*iterheadp
, int flags
)
1227 struct buflists
* listheadp
;
1230 if (flags
& VBI_DIRTY
)
1231 listheadp
= &vp
->v_dirtyblkhd
;
1233 listheadp
= &vp
->v_cleanblkhd
;
1235 while (!LIST_EMPTY(iterheadp
)) {
1236 bp
= LIST_FIRST(iterheadp
);
1237 LIST_REMOVE(bp
, b_vnbufs
);
1238 LIST_INSERT_HEAD(listheadp
, bp
, b_vnbufs
);
1240 vp
->v_iterblkflags
&= ~VBI_ITER
;
1242 if (vp
->v_iterblkflags
& VBI_ITERWANT
) {
1243 vp
->v_iterblkflags
&= ~VBI_ITERWANT
;
1244 wakeup(&vp
->v_iterblkflags
);
1250 bremfree_locked(buf_t bp
)
1252 struct bqueues
*dp
= NULL
;
1256 * We only calculate the head of the freelist when removing
1257 * the last element of the list as that is the only time that
1258 * it is needed (e.g. to reset the tail pointer).
1260 * NB: This makes an assumption about how tailq's are implemented.
1262 if (bp
->b_freelist
.tqe_next
== NULL
) {
1263 for (dp
= bufqueues
; dp
< &bufqueues
[BQUEUES
]; dp
++)
1264 if (dp
->tqh_last
== &bp
->b_freelist
.tqe_next
)
1266 if (dp
== &bufqueues
[BQUEUES
])
1267 panic("bremfree: lost tail");
1269 TAILQ_REMOVE(dp
, bp
, b_freelist
);
1270 whichq
= bp
->b_whichq
;
1275 bp
->b_timestamp
= 0;
1279 * Associate a buffer with a vnode.
1282 bgetvp(vnode_t vp
, buf_t bp
)
1286 panic("bgetvp: not free");
1288 if (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
)
1289 bp
->b_dev
= vp
->v_rdev
;
1293 * Insert onto list for new vnode.
1295 lck_mtx_lock(buf_mtxp
);
1296 bufinsvn(bp
, &vp
->v_cleanblkhd
);
1297 lck_mtx_unlock(buf_mtxp
);
1301 * Disassociate a buffer from a vnode.
1308 if ((vp
= bp
->b_vp
) == (vnode_t
)NULL
)
1309 panic("brelvp: NULL vp");
1311 * Delete from old vnode list, if on one.
1313 lck_mtx_lock(buf_mtxp
);
1314 if (bp
->b_vnbufs
.le_next
!= NOLIST
)
1316 lck_mtx_unlock(buf_mtxp
);
1318 bp
->b_vp
= (vnode_t
)NULL
;
1322 * Reassign a buffer from one vnode to another.
1323 * Used to assign file specific control information
1324 * (indirect blocks) to the vnode to which they belong.
1327 buf_reassign(buf_t bp
, vnode_t newvp
)
1329 register struct buflists
*listheadp
;
1331 if (newvp
== NULL
) {
1332 printf("buf_reassign: NULL");
1335 lck_mtx_lock(buf_mtxp
);
1338 * Delete from old vnode list, if on one.
1340 if (bp
->b_vnbufs
.le_next
!= NOLIST
)
1343 * If dirty, put on list of dirty buffers;
1344 * otherwise insert onto list of clean buffers.
1346 if (ISSET(bp
->b_flags
, B_DELWRI
))
1347 listheadp
= &newvp
->v_dirtyblkhd
;
1349 listheadp
= &newvp
->v_cleanblkhd
;
1350 bufinsvn(bp
, listheadp
);
1352 lck_mtx_unlock(buf_mtxp
);
1355 static __inline__
void
1356 bufhdrinit(buf_t bp
)
1358 bzero((char *)bp
, sizeof *bp
);
1360 bp
->b_rcred
= NOCRED
;
1361 bp
->b_wcred
= NOCRED
;
1362 bp
->b_vnbufs
.le_next
= NOLIST
;
1363 bp
->b_flags
= B_INVAL
;
1369 * Initialize buffers and hash links for buffers.
1371 __private_extern__
void
1380 /* Initialize the buffer queues ('freelists') and the hash table */
1381 for (dp
= bufqueues
; dp
< &bufqueues
[BQUEUES
]; dp
++)
1383 bufhashtbl
= hashinit(nbuf
, M_CACHE
, &bufhash
);
1385 metabuf
= nbuf
/8; /* reserved for meta buf */
1387 /* Initialize the buffer headers */
1388 for (i
= 0; i
< nbuf
; i
++) {
1393 * metabuf buffer headers on the meta-data list and
1394 * rest of the buffer headers on the empty list
1402 dp
= &bufqueues
[whichq
];
1403 binsheadfree(bp
, dp
, whichq
);
1404 binshash(bp
, &invalhash
);
1407 for (; i
< nbuf
+ niobuf
; i
++) {
1410 binsheadfree(bp
, &iobufqueue
, -1);
1414 * allocate lock group attribute and group
1416 buf_mtx_grp_attr
= lck_grp_attr_alloc_init();
1417 //lck_grp_attr_setstat(buf_mtx_grp_attr);
1418 buf_mtx_grp
= lck_grp_alloc_init("buffer cache", buf_mtx_grp_attr
);
1421 * allocate the lock attribute
1423 buf_mtx_attr
= lck_attr_alloc_init();
1424 //lck_attr_setdebug(buf_mtx_attr);
1427 * allocate and initialize mutex's for the buffer and iobuffer pools
1429 buf_mtxp
= lck_mtx_alloc_init(buf_mtx_grp
, buf_mtx_attr
);
1430 iobuffer_mtxp
= lck_mtx_alloc_init(buf_mtx_grp
, buf_mtx_attr
);
1432 if (iobuffer_mtxp
== NULL
)
1433 panic("couldn't create iobuffer mutex");
1435 if (buf_mtxp
== NULL
)
1436 panic("couldn't create buf mutex");
1439 * allocate and initialize cluster specific global locks...
1443 printf("using %d buffer headers and %d cluster IO buffer headers\n",
1446 /* Set up zones used by the buffer cache */
1449 /* start the bcleanbuf() thread */
1450 bcleanbuf_thread_init();
1454 static void bufq_balance_thread_init();
1455 /* create a thread to do dynamic buffer queue balancing */
1456 bufq_balance_thread_init();
1462 bio_doread(vnode_t vp
, daddr64_t blkno
, int size
, ucred_t cred
, int async
, int queuetype
)
1466 bp
= buf_getblk(vp
, blkno
, size
, 0, 0, queuetype
);
1469 * If buffer does not have data valid, start a read.
1470 * Note that if buffer is B_INVAL, buf_getblk() won't return it.
1471 * Therefore, it's valid if it's I/O has completed or been delayed.
1473 if (!ISSET(bp
->b_flags
, (B_DONE
| B_DELWRI
))) {
1478 /* Start I/O for the buffer (keeping credentials). */
1479 SET(bp
->b_flags
, B_READ
| async
);
1480 if (cred
!= NOCRED
&& bp
->b_rcred
== NOCRED
) {
1481 kauth_cred_ref(cred
);
1487 trace(TR_BREADMISS
, pack(vp
, size
), blkno
);
1489 /* Pay for the read. */
1490 if (p
&& p
->p_stats
)
1491 p
->p_stats
->p_ru
.ru_inblock
++; /* XXX */
1495 * since we asked for an ASYNC I/O
1496 * the biodone will do the brelse
1497 * we don't want to pass back a bp
1498 * that we don't 'own'
1507 trace(TR_BREADHIT
, pack(vp
, size
), blkno
);
1513 * Perform the reads for buf_breadn() and buf_meta_breadn().
1514 * Trivial modification to the breada algorithm presented in Bach (p.55).
1517 do_breadn_for_type(vnode_t vp
, daddr64_t blkno
, int size
, daddr64_t
*rablks
, int *rasizes
,
1518 int nrablks
, ucred_t cred
, buf_t
*bpp
, int queuetype
)
1523 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, queuetype
);
1526 * For each of the read-ahead blocks, start a read, if necessary.
1528 for (i
= 0; i
< nrablks
; i
++) {
1529 /* If it's in the cache, just go on to next one. */
1530 if (incore(vp
, rablks
[i
]))
1533 /* Get a buffer for the read-ahead block */
1534 (void) bio_doread(vp
, rablks
[i
], rasizes
[i
], cred
, B_ASYNC
, queuetype
);
1537 /* Otherwise, we had to start a read for it; wait until it's valid. */
1538 return (buf_biowait(bp
));
1543 * Read a disk block.
1544 * This algorithm described in Bach (p.54).
1547 buf_bread(vnode_t vp
, daddr64_t blkno
, int size
, ucred_t cred
, buf_t
*bpp
)
1551 /* Get buffer for block. */
1552 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, BLK_READ
);
1554 /* Wait for the read to complete, and return result. */
1555 return (buf_biowait(bp
));
1559 * Read a disk block. [bread() for meta-data]
1560 * This algorithm described in Bach (p.54).
1563 buf_meta_bread(vnode_t vp
, daddr64_t blkno
, int size
, ucred_t cred
, buf_t
*bpp
)
1567 /* Get buffer for block. */
1568 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, BLK_META
);
1570 /* Wait for the read to complete, and return result. */
1571 return (buf_biowait(bp
));
1575 * Read-ahead multiple disk blocks. The first is sync, the rest async.
1578 buf_breadn(vnode_t vp
, daddr64_t blkno
, int size
, daddr64_t
*rablks
, int *rasizes
, int nrablks
, ucred_t cred
, buf_t
*bpp
)
1580 return (do_breadn_for_type(vp
, blkno
, size
, rablks
, rasizes
, nrablks
, cred
, bpp
, BLK_READ
));
1584 * Read-ahead multiple disk blocks. The first is sync, the rest async.
1585 * [buf_breadn() for meta-data]
1588 buf_meta_breadn(vnode_t vp
, daddr64_t blkno
, int size
, daddr64_t
*rablks
, int *rasizes
, int nrablks
, ucred_t cred
, buf_t
*bpp
)
1590 return (do_breadn_for_type(vp
, blkno
, size
, rablks
, rasizes
, nrablks
, cred
, bpp
, BLK_META
));
1594 * Block write. Described in Bach (p.56)
1597 buf_bwrite(buf_t bp
)
1599 int sync
, wasdelayed
;
1601 proc_t p
= current_proc();
1602 vnode_t vp
= bp
->b_vp
;
1604 if (bp
->b_datap
== 0) {
1605 if (brecover_data(bp
) == 0)
1608 /* Remember buffer type, to switch on it later. */
1609 sync
= !ISSET(bp
->b_flags
, B_ASYNC
);
1610 wasdelayed
= ISSET(bp
->b_flags
, B_DELWRI
);
1611 CLR(bp
->b_flags
, (B_READ
| B_DONE
| B_ERROR
| B_DELWRI
));
1614 OSAddAtomic(-1, &nbdwrite
);
1618 * If not synchronous, pay for the I/O operation and make
1619 * sure the buf is on the correct vnode queue. We have
1620 * to do this now, because if we don't, the vnode may not
1621 * be properly notified that its I/O has completed.
1624 buf_reassign(bp
, vp
);
1626 if (p
&& p
->p_stats
)
1627 p
->p_stats
->p_ru
.ru_oublock
++; /* XXX */
1629 trace(TR_BUFWRITE
, pack(vp
, bp
->b_bcount
), bp
->b_lblkno
);
1631 /* Initiate disk write. Make sure the appropriate party is charged. */
1633 OSAddAtomic(1, &vp
->v_numoutput
);
1639 * If I/O was synchronous, wait for it to complete.
1641 rv
= buf_biowait(bp
);
1644 * Pay for the I/O operation, if it's not been paid for, and
1645 * make sure it's on the correct vnode queue. (async operatings
1646 * were payed for above.)
1649 buf_reassign(bp
, vp
);
1651 if (p
&& p
->p_stats
)
1652 p
->p_stats
->p_ru
.ru_oublock
++; /* XXX */
1654 /* Release the buffer. */
1655 // XXXdbg - only if the unused bit is set
1656 if (!ISSET(bp
->b_flags
, B_NORELSE
)) {
1659 CLR(bp
->b_flags
, B_NORELSE
);
1670 struct vnop_bwrite_args
*ap
;
1672 return (buf_bwrite(ap
->a_bp
));
1678 * The buffer is marked dirty, but is not queued for I/O.
1679 * This routine should be used when the buffer is expected
1680 * to be modified again soon, typically a small write that
1681 * partially fills a buffer.
1683 * NB: magnetic tapes cannot be delayed; they must be
1684 * written in the order that the writes are requested.
1686 * Described in Leffler, et al. (pp. 208-213).
1688 * Note: With the abilitty to allocate additional buffer
1689 * headers, we can get in to the situation where "too" many
1690 * buf_bdwrite()s can create situation where the kernel can create
1691 * buffers faster than the disks can service. Doing a buf_bawrite() in
1692 * cases were we have "too many" outstanding buf_bdwrite()s avoids that.
1694 __private_extern__
int
1695 bdwrite_internal(buf_t bp
, int return_error
)
1697 proc_t p
= current_proc();
1698 vnode_t vp
= bp
->b_vp
;
1701 * If the block hasn't been seen before:
1702 * (1) Mark it as having been seen,
1703 * (2) Charge for the write.
1704 * (3) Make sure it's on its vnode's correct block list,
1706 if (!ISSET(bp
->b_flags
, B_DELWRI
)) {
1707 SET(bp
->b_flags
, B_DELWRI
);
1708 if (p
&& p
->p_stats
)
1709 p
->p_stats
->p_ru
.ru_oublock
++; /* XXX */
1710 OSAddAtomic(1, &nbdwrite
);
1711 buf_reassign(bp
, vp
);
1714 /* If this is a tape block, write it the block now. */
1715 if (ISSET(bp
->b_flags
, B_TAPE
)) {
1721 * if we're not LOCKED, but the total number of delayed writes
1722 * has climbed above 75% of the total buffers in the system
1723 * return an error if the caller has indicated that it can
1724 * handle one in this case, otherwise schedule the I/O now
1725 * this is done to prevent us from allocating tons of extra
1726 * buffers when dealing with virtual disks (i.e. DiskImages),
1727 * because additional buffers are dynamically allocated to prevent
1728 * deadlocks from occurring
1730 * however, can't do a buf_bawrite() if the LOCKED bit is set because the
1731 * buffer is part of a transaction and can't go to disk until
1732 * the LOCKED bit is cleared.
1734 if (!ISSET(bp
->b_flags
, B_LOCKED
) && nbdwrite
> ((nbuf
/4)*3)) {
1738 * If the vnode has "too many" write operations in progress
1739 * wait for them to finish the IO
1741 (void)vnode_waitforwrites(vp
, VNODE_ASYNC_THROTTLE
, 0, 0, (char *)"buf_bdwrite");
1743 return (buf_bawrite(bp
));
1746 /* Otherwise, the "write" is done, so mark and release the buffer. */
1747 SET(bp
->b_flags
, B_DONE
);
1753 buf_bdwrite(buf_t bp
)
1755 return (bdwrite_internal(bp
, 0));
1760 * Asynchronous block write; just an asynchronous buf_bwrite().
1762 * Note: With the abilitty to allocate additional buffer
1763 * headers, we can get in to the situation where "too" many
1764 * buf_bawrite()s can create situation where the kernel can create
1765 * buffers faster than the disks can service.
1766 * We limit the number of "in flight" writes a vnode can have to
1770 bawrite_internal(buf_t bp
, int throttle
)
1772 vnode_t vp
= bp
->b_vp
;
1777 * If the vnode has "too many" write operations in progress
1778 * wait for them to finish the IO
1780 (void)vnode_waitforwrites(vp
, VNODE_ASYNC_THROTTLE
, 0, 0, (const char *)"buf_bawrite");
1781 else if (vp
->v_numoutput
>= VNODE_ASYNC_THROTTLE
)
1783 * return to the caller and
1784 * let him decide what to do
1786 return (EWOULDBLOCK
);
1788 SET(bp
->b_flags
, B_ASYNC
);
1790 return (VNOP_BWRITE(bp
));
1794 buf_bawrite(buf_t bp
)
1796 return (bawrite_internal(bp
, 1));
1801 * Release a buffer on to the free lists.
1802 * Described in Bach (p. 46).
1805 buf_brelse(buf_t bp
)
1807 struct bqueues
*bufq
;
1810 int need_wakeup
= 0;
1811 int need_bp_wakeup
= 0;
1814 if (bp
->b_whichq
!= -1 || !(bp
->b_lflags
& BL_BUSY
))
1815 panic("buf_brelse: bad buffer = %x\n", bp
);
1818 bp
->b_stackbrelse
[0] = __builtin_return_address(0);
1819 bp
->b_stackbrelse
[1] = __builtin_return_address(1);
1820 bp
->b_stackbrelse
[2] = __builtin_return_address(2);
1821 bp
->b_stackbrelse
[3] = __builtin_return_address(3);
1822 bp
->b_stackbrelse
[4] = __builtin_return_address(4);
1823 bp
->b_stackbrelse
[5] = __builtin_return_address(5);
1825 bp
->b_lastbrelse
= current_thread();
1828 if (bp
->b_lflags
& BL_IOBUF
) {
1833 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 388)) | DBG_FUNC_START
,
1834 bp
->b_lblkno
* PAGE_SIZE
, (int)bp
, (int)bp
->b_datap
,
1837 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
1840 * if we're invalidating a buffer that has the B_FILTER bit
1841 * set then call the b_iodone function so it gets cleaned
1844 * the HFS journal code depends on this
1846 if (ISSET(bp
->b_flags
, B_META
) && ISSET(bp
->b_flags
, B_INVAL
)) {
1847 if (ISSET(bp
->b_flags
, B_FILTER
)) { /* if necessary, call out */
1848 void (*iodone_func
)(struct buf
*, void *) = bp
->b_iodone
;
1849 void *arg
= (void *)bp
->b_transaction
;
1851 CLR(bp
->b_flags
, B_FILTER
); /* but note callout done */
1852 bp
->b_iodone
= NULL
;
1853 bp
->b_transaction
= NULL
;
1855 if (iodone_func
== NULL
) {
1856 panic("brelse: bp @ 0x%x has NULL b_iodone!\n", bp
);
1858 (*iodone_func
)(bp
, arg
);
1862 * I/O is done. Cleanup the UPL state
1866 if ( !ISSET(bp
->b_flags
, B_META
) && UBCINFOEXISTS(bp
->b_vp
) && bp
->b_bufsize
) {
1870 if ( (upl
== NULL
) ) {
1871 if ( !ISSET(bp
->b_flags
, B_INVAL
)) {
1872 kret
= ubc_create_upl(bp
->b_vp
,
1873 ubc_blktooff(bp
->b_vp
, bp
->b_lblkno
),
1879 if (kret
!= KERN_SUCCESS
)
1880 panic("brelse: Failed to create UPL");
1882 upl_ubc_alias_set(upl
, bp
, 5);
1883 #endif /* UPL_DEBUG */
1887 kret
= ubc_upl_unmap(upl
);
1889 if (kret
!= KERN_SUCCESS
)
1890 panic("ubc_upl_unmap failed");
1891 bp
->b_datap
= (uintptr_t)NULL
;
1895 if (bp
->b_flags
& (B_ERROR
| B_INVAL
)) {
1896 if (bp
->b_flags
& (B_READ
| B_INVAL
))
1897 upl_flags
= UPL_ABORT_DUMP_PAGES
;
1901 ubc_upl_abort(upl
, upl_flags
);
1903 if (ISSET(bp
->b_flags
, B_DELWRI
| B_WASDIRTY
))
1904 upl_flags
= UPL_COMMIT_SET_DIRTY
;
1906 upl_flags
= UPL_COMMIT_CLEAR_DIRTY
;
1908 ubc_upl_commit_range(upl
, 0, bp
->b_bufsize
, upl_flags
|
1909 UPL_COMMIT_INACTIVATE
| UPL_COMMIT_FREE_ON_EMPTY
);
1915 panic("brelse: UPL set for non VREG; vp=%x", bp
->b_vp
);
1919 * If it's locked, don't report an error; try again later.
1921 if (ISSET(bp
->b_flags
, (B_LOCKED
|B_ERROR
)) == (B_LOCKED
|B_ERROR
))
1922 CLR(bp
->b_flags
, B_ERROR
);
1924 * If it's not cacheable, or an error, mark it invalid.
1926 if (ISSET(bp
->b_flags
, (B_NOCACHE
|B_ERROR
)))
1927 SET(bp
->b_flags
, B_INVAL
);
1929 if ((bp
->b_bufsize
<= 0) || ISSET(bp
->b_flags
, B_INVAL
)) {
1931 * If it's invalid or empty, dissociate it from its vnode
1932 * and put on the head of the appropriate queue.
1937 if (ISSET(bp
->b_flags
, B_DELWRI
))
1938 OSAddAtomic(-1, &nbdwrite
);
1940 CLR(bp
->b_flags
, (B_DELWRI
| B_LOCKED
| B_AGE
| B_ASYNC
| B_NOCACHE
));
1942 * Determine which queue the buffer should be on, then put it there.
1944 if (bp
->b_bufsize
<= 0)
1945 whichq
= BQ_EMPTY
; /* no data */
1946 else if (ISSET(bp
->b_flags
, B_META
))
1947 whichq
= BQ_META
; /* meta-data */
1949 whichq
= BQ_AGE
; /* invalid data */
1950 bufq
= &bufqueues
[whichq
];
1952 lck_mtx_lock(buf_mtxp
);
1954 binsheadfree(bp
, bufq
, whichq
);
1957 * It has valid data. Put it on the end of the appropriate
1958 * queue, so that it'll stick around for as long as possible.
1960 if (ISSET(bp
->b_flags
, B_LOCKED
))
1961 whichq
= BQ_LOCKED
; /* locked in core */
1962 else if (ISSET(bp
->b_flags
, B_META
))
1963 whichq
= BQ_META
; /* meta-data */
1964 else if (ISSET(bp
->b_flags
, B_AGE
))
1965 whichq
= BQ_AGE
; /* stale but valid data */
1967 whichq
= BQ_LRU
; /* valid data */
1968 bufq
= &bufqueues
[whichq
];
1970 CLR(bp
->b_flags
, (B_AGE
| B_ASYNC
| B_NOCACHE
));
1972 lck_mtx_lock(buf_mtxp
);
1974 binstailfree(bp
, bufq
, whichq
);
1978 * needbuffer is a global
1979 * we're currently using buf_mtxp to protect it
1980 * delay doing the actual wakeup until after
1986 if (ISSET(bp
->b_lflags
, BL_WANTED
)) {
1988 * delay the actual wakeup until after we
1989 * clear BL_BUSY and we've dropped buf_mtxp
1994 * Unlock the buffer.
1996 CLR(bp
->b_lflags
, (BL_BUSY
| BL_WANTED
));
1998 lck_mtx_unlock(buf_mtxp
);
2002 * Wake up any processes waiting for any buffer to become free.
2004 wakeup(&needbuffer
);
2006 if (need_bp_wakeup
) {
2008 * Wake up any proceeses waiting for _this_ buffer to become free.
2012 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 388)) | DBG_FUNC_END
,
2013 (int)bp
, (int)bp
->b_datap
, bp
->b_flags
, 0, 0);
2017 * Determine if a block is in the cache.
2018 * Just look on what would be its hash chain. If it's there, return
2019 * a pointer to it, unless it's marked invalid. If it's marked invalid,
2020 * we normally don't return the buffer, unless the caller explicitly
2024 incore(vnode_t vp
, daddr64_t blkno
)
2028 lck_mtx_lock(buf_mtxp
);
2030 if (incore_locked(vp
, blkno
))
2034 lck_mtx_unlock(buf_mtxp
);
2041 incore_locked(vnode_t vp
, daddr64_t blkno
)
2045 bp
= BUFHASH(vp
, blkno
)->lh_first
;
2047 /* Search hash chain */
2048 for (; bp
!= NULL
; bp
= bp
->b_hash
.le_next
) {
2049 if (bp
->b_lblkno
== blkno
&& bp
->b_vp
== vp
&&
2050 !ISSET(bp
->b_flags
, B_INVAL
)) {
2058 /* XXX FIXME -- Update the comment to reflect the UBC changes (please) -- */
2060 * Get a block of requested size that is associated with
2061 * a given vnode and block offset. If it is found in the
2062 * block cache, mark it as having been found, make it busy
2063 * and return it. Otherwise, return an empty block of the
2064 * correct size. It is up to the caller to insure that the
2065 * cached blocks be of the correct size.
2068 buf_getblk(vnode_t vp
, daddr64_t blkno
, int size
, int slpflag
, int slptimeo
, int operation
)
2073 upl_page_info_t
*pl
;
2079 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_START
,
2080 (int)(blkno
* PAGE_SIZE
), size
, operation
, 0, 0);
2082 ret_only_valid
= operation
& BLK_ONLYVALID
;
2083 operation
&= ~BLK_ONLYVALID
;
2085 lck_mtx_lock(buf_mtxp
);
2087 if ((bp
= incore_locked(vp
, blkno
))) {
2089 * Found in the Buffer Cache
2091 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
2095 switch (operation
) {
2099 SET(bp
->b_lflags
, BL_WANTED
);
2100 bufstats
.bufs_busyincore
++;
2103 * don't retake the mutex after being awakened...
2104 * the time out is in msecs
2106 ts
.tv_sec
= (slptimeo
/1000);
2107 ts
.tv_nsec
= (slptimeo
% 1000) * 10 * NSEC_PER_USEC
* 1000;
2109 err
= msleep(bp
, buf_mtxp
, slpflag
| PDROP
| (PRIBIO
+ 1), "buf_getblk", &ts
);
2112 * Callers who call with PCATCH or timeout are
2113 * willing to deal with the NULL pointer
2115 if (err
&& ((slpflag
& PCATCH
) || ((err
== EWOULDBLOCK
) && slptimeo
)))
2123 * unknown operation requested
2125 panic("getblk: paging or unknown operation for incore busy buffer - %x\n", operation
);
2131 * buffer in core and not busy
2134 panic("buffer has UPL, but not marked BUSY: %x", bp
);
2135 SET(bp
->b_lflags
, BL_BUSY
);
2136 SET(bp
->b_flags
, B_CACHE
);
2138 bp
->b_owner
= current_thread();
2141 bremfree_locked(bp
);
2142 bufstats
.bufs_incore
++;
2144 lck_mtx_unlock(buf_mtxp
);
2146 if ( !ret_only_valid
)
2150 switch (operation
) {
2153 * "write" operation: let the UPL subsystem
2154 * know that we intend to modify the buffer
2155 * cache pages we're gathering.
2157 upl_flags
|= UPL_WILL_MODIFY
;
2159 upl_flags
|= UPL_PRECIOUS
;
2160 if (UBCINFOEXISTS(bp
->b_vp
) && bp
->b_bufsize
) {
2161 kret
= ubc_create_upl(vp
,
2162 ubc_blktooff(vp
, bp
->b_lblkno
),
2167 if (kret
!= KERN_SUCCESS
)
2168 panic("Failed to create UPL");
2172 if (upl_valid_page(pl
, 0)) {
2173 if (upl_dirty_page(pl
, 0))
2174 SET(bp
->b_flags
, B_WASDIRTY
);
2176 CLR(bp
->b_flags
, B_WASDIRTY
);
2178 CLR(bp
->b_flags
, (B_DONE
| B_CACHE
| B_WASDIRTY
| B_DELWRI
));
2180 kret
= ubc_upl_map(upl
, (vm_address_t
*)&(bp
->b_datap
));
2182 if (kret
!= KERN_SUCCESS
)
2183 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
2189 * VM is not involved in IO for the meta data
2190 * buffer already has valid data
2195 panic("getblk: paging or unknown operation for incore buffer- %d\n", operation
);
2200 } else { /* not incore() */
2201 int queue
= BQ_EMPTY
; /* Start with no preference */
2203 if (ret_only_valid
) {
2204 lck_mtx_unlock(buf_mtxp
);
2208 if ((UBCINVALID(vp
)) || !(UBCINFOEXISTS(vp
)))
2209 operation
= BLK_META
;
2211 if ((bp
= getnewbuf(slpflag
, slptimeo
, &queue
)) == NULL
)
2215 * getnewbuf may block for a number of different reasons...
2216 * if it does, it's then possible for someone else to
2217 * create a buffer for the same block and insert it into
2218 * the hash... if we see it incore at this point we dump
2219 * the buffer we were working on and start over
2221 if (incore_locked(vp
, blkno
)) {
2222 SET(bp
->b_flags
, B_INVAL
);
2223 binshash(bp
, &invalhash
);
2225 lck_mtx_unlock(buf_mtxp
);
2231 * NOTE: YOU CAN NOT BLOCK UNTIL binshash() HAS BEEN
2232 * CALLED! BE CAREFUL.
2236 * mark the buffer as B_META if indicated
2237 * so that when buffer is released it will goto META queue
2239 if (operation
== BLK_META
)
2240 SET(bp
->b_flags
, B_META
);
2242 bp
->b_blkno
= bp
->b_lblkno
= blkno
;
2246 * Insert in the hash so that incore() can find it
2248 binshash(bp
, BUFHASH(vp
, blkno
));
2250 lck_mtx_unlock(buf_mtxp
);
2257 switch (operation
) {
2260 * buffer data is invalid...
2262 * I don't want to have to retake buf_mtxp,
2263 * so the miss and vmhits counters are done
2264 * with Atomic updates... all other counters
2265 * in bufstats are protected with either
2266 * buf_mtxp or iobuffer_mtxp
2268 OSAddAtomic(1, &bufstats
.bufs_miss
);
2273 * "write" operation: let the UPL subsystem know
2274 * that we intend to modify the buffer cache pages
2277 upl_flags
|= UPL_WILL_MODIFY
;
2280 size_t contig_bytes
;
2284 panic("bp already has UPL: %x",bp
);
2286 f_offset
= ubc_blktooff(vp
, blkno
);
2288 upl_flags
|= UPL_PRECIOUS
;
2289 kret
= ubc_create_upl(vp
,
2296 if (kret
!= KERN_SUCCESS
)
2297 panic("Failed to create UPL");
2299 upl_ubc_alias_set(upl
, bp
, 4);
2300 #endif /* UPL_DEBUG */
2303 if (upl_valid_page(pl
, 0)) {
2305 if (operation
== BLK_READ
)
2306 bmap_flags
= VNODE_READ
;
2308 bmap_flags
= VNODE_WRITE
;
2310 SET(bp
->b_flags
, B_CACHE
| B_DONE
);
2312 OSAddAtomic(1, &bufstats
.bufs_vmhits
);
2317 if (upl_dirty_page(pl
, 0)) {
2319 SET(bp
->b_flags
, B_WASDIRTY
);
2321 bp
->b_validend
= bp
->b_bcount
;
2322 bp
->b_dirtyend
= bp
->b_bcount
;
2325 bp
->b_validend
= bp
->b_bcount
;
2329 * try to recreate the physical block number associated with
2332 if (VNOP_BLOCKMAP(vp
, f_offset
, bp
->b_bcount
, &bp
->b_blkno
, &contig_bytes
, NULL
, bmap_flags
, NULL
))
2333 panic("getblk: VNOP_BLOCKMAP failed");
2335 * if the extent represented by this buffer
2336 * is not completely physically contiguous on
2337 * disk, than we can't cache the physical mapping
2338 * in the buffer header
2340 if ((long)contig_bytes
< bp
->b_bcount
)
2341 bp
->b_blkno
= bp
->b_lblkno
;
2343 OSAddAtomic(1, &bufstats
.bufs_miss
);
2345 kret
= ubc_upl_map(upl
, (vm_address_t
*)&(bp
->b_datap
));
2347 if (kret
!= KERN_SUCCESS
)
2348 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
2352 panic("getblk: paging or unknown operation - %x", operation
);
2357 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_END
,
2358 (int)bp
, (int)bp
->b_datap
, bp
->b_flags
, 3, 0);
2361 bp
->b_stackgetblk
[0] = __builtin_return_address(0);
2362 bp
->b_stackgetblk
[1] = __builtin_return_address(1);
2363 bp
->b_stackgetblk
[2] = __builtin_return_address(2);
2364 bp
->b_stackgetblk
[3] = __builtin_return_address(3);
2365 bp
->b_stackgetblk
[4] = __builtin_return_address(4);
2366 bp
->b_stackgetblk
[5] = __builtin_return_address(5);
2372 * Get an empty, disassociated buffer of given size.
2379 int queue
= BQ_EMPTY
;
2381 lck_mtx_lock(buf_mtxp
);
2383 while ((bp
= getnewbuf(0, 0, &queue
)) == 0)
2385 SET(bp
->b_flags
, (B_META
|B_INVAL
));
2388 assert(queue
== BQ_EMPTY
);
2389 #endif /* DIAGNOSTIC */
2390 /* XXX need to implement logic to deal with other queues */
2392 binshash(bp
, &invalhash
);
2393 bufstats
.bufs_eblk
++;
2395 lck_mtx_unlock(buf_mtxp
);
2403 * Zones for the meta data buffers
2407 #define MAXMETA 4096
2409 struct meta_zone_entry
{
2416 struct meta_zone_entry meta_zones
[] = {
2417 {NULL
, (MINMETA
* 1), 128 * (MINMETA
* 1), "buf.512" },
2418 {NULL
, (MINMETA
* 2), 64 * (MINMETA
* 2), "buf.1024" },
2419 {NULL
, (MINMETA
* 4), 16 * (MINMETA
* 4), "buf.2048" },
2420 {NULL
, (MINMETA
* 8), 512 * (MINMETA
* 8), "buf.4096" },
2421 {NULL
, 0, 0, "" } /* End */
2425 * Initialize the meta data zones
2432 for (i
= 0; meta_zones
[i
].mz_size
!= 0; i
++) {
2433 meta_zones
[i
].mz_zone
=
2434 zinit(meta_zones
[i
].mz_size
,
2435 meta_zones
[i
].mz_max
,
2437 meta_zones
[i
].mz_name
);
2439 buf_hdr_zone
= zinit(sizeof(struct buf
), 32, PAGE_SIZE
, "buf headers");
2442 static __inline__ zone_t
2443 getbufzone(size_t size
)
2447 if ((size
% 512) || (size
< MINMETA
) || (size
> MAXMETA
))
2448 panic("getbufzone: incorect size = %d", size
);
2450 for (i
= 0; meta_zones
[i
].mz_size
!= 0; i
++) {
2451 if (meta_zones
[i
].mz_size
>= size
)
2455 return (meta_zones
[i
].mz_zone
);
2459 * With UBC, there is no need to expand / shrink the file data
2460 * buffer. The VM uses the same pages, hence no waste.
2461 * All the file data buffers can have one size.
2462 * In fact expand / shrink would be an expensive operation.
2464 * Only exception to this is meta-data buffers. Most of the
2465 * meta data operations are smaller than PAGE_SIZE. Having the
2466 * meta-data buffers grow and shrink as needed, optimizes use
2467 * of the kernel wired memory.
2471 allocbuf(buf_t bp
, int size
)
2473 vm_size_t desired_size
;
2475 desired_size
= roundup(size
, CLBYTES
);
2477 if (desired_size
< PAGE_SIZE
)
2478 desired_size
= PAGE_SIZE
;
2479 if (desired_size
> MAXBSIZE
)
2480 panic("allocbuf: buffer larger than MAXBSIZE requested");
2482 if (ISSET(bp
->b_flags
, B_META
)) {
2484 int nsize
= roundup(size
, MINMETA
);
2487 vm_offset_t elem
= (vm_offset_t
)bp
->b_datap
;
2489 if (ISSET(bp
->b_flags
, B_ZALLOC
)) {
2490 if (bp
->b_bufsize
< nsize
) {
2491 /* reallocate to a bigger size */
2493 zprev
= getbufzone(bp
->b_bufsize
);
2494 if (nsize
<= MAXMETA
) {
2495 desired_size
= nsize
;
2496 z
= getbufzone(nsize
);
2497 bp
->b_datap
= (uintptr_t)zalloc(z
);
2499 bp
->b_datap
= (uintptr_t)NULL
;
2500 kmem_alloc(kernel_map
, (vm_offset_t
*)&bp
->b_datap
, desired_size
);
2501 CLR(bp
->b_flags
, B_ZALLOC
);
2503 bcopy((void *)elem
, (caddr_t
)bp
->b_datap
, bp
->b_bufsize
);
2504 zfree(zprev
, (void *)elem
);
2506 desired_size
= bp
->b_bufsize
;
2510 if ((vm_size_t
)bp
->b_bufsize
< desired_size
) {
2511 /* reallocate to a bigger size */
2512 bp
->b_datap
= (uintptr_t)NULL
;
2513 kmem_alloc(kernel_map
, (vm_offset_t
*)&bp
->b_datap
, desired_size
);
2514 bcopy((const void *)elem
, (caddr_t
)bp
->b_datap
, bp
->b_bufsize
);
2515 kmem_free(kernel_map
, elem
, bp
->b_bufsize
);
2517 desired_size
= bp
->b_bufsize
;
2521 /* new allocation */
2522 if (nsize
<= MAXMETA
) {
2523 desired_size
= nsize
;
2524 z
= getbufzone(nsize
);
2525 bp
->b_datap
= (uintptr_t)zalloc(z
);
2526 SET(bp
->b_flags
, B_ZALLOC
);
2528 kmem_alloc(kernel_map
, (vm_offset_t
*)&bp
->b_datap
, desired_size
);
2531 bp
->b_bufsize
= desired_size
;
2532 bp
->b_bcount
= size
;
2538 * Get a new buffer from one of the free lists.
2540 * Request for a queue is passes in. The queue from which the buffer was taken
2541 * from is returned. Out of range queue requests get BQ_EMPTY. Request for
2542 * BQUEUE means no preference. Use heuristics in that case.
2543 * Heuristics is as follows:
2544 * Try BQ_AGE, BQ_LRU, BQ_EMPTY, BQ_META in that order.
2545 * If none available block till one is made available.
2546 * If buffers available on both BQ_AGE and BQ_LRU, check the timestamps.
2547 * Pick the most stale buffer.
2548 * If found buffer was marked delayed write, start the async. write
2549 * and restart the search.
2550 * Initialize the fields and disassociate the buffer from the vnode.
2551 * Remove the buffer from the hash. Return the buffer and the queue
2552 * on which it was found.
2554 * buf_mtxp is held upon entry
2555 * returns with buf_mtxp locked
2559 getnewbuf(int slpflag
, int slptimeo
, int * queue
)
2565 int age_time
, lru_time
, bp_time
, meta_time
;
2566 int req
= *queue
; /* save it for restarts */
2571 * invalid request gets empty queue
2573 if ((*queue
> BQUEUES
) || (*queue
< 0)
2574 || (*queue
== BQ_LAUNDRY
) || (*queue
== BQ_LOCKED
))
2578 * (*queue == BQUEUES) means no preference
2580 if (*queue
!= BQUEUES
) {
2581 /* Try for the requested queue first */
2582 bp
= bufqueues
[*queue
].tqh_first
;
2587 /* Unable to use requested queue */
2588 age_bp
= bufqueues
[BQ_AGE
].tqh_first
;
2589 lru_bp
= bufqueues
[BQ_LRU
].tqh_first
;
2590 meta_bp
= bufqueues
[BQ_META
].tqh_first
;
2592 if (!age_bp
&& !lru_bp
&& !meta_bp
) {
2594 * Unavailble on AGE or LRU or META queues
2595 * Try the empty list first
2597 bp
= bufqueues
[BQ_EMPTY
].tqh_first
;
2602 lck_mtx_unlock(buf_mtxp
);
2604 /* Create a new temporary buffer header */
2605 bp
= (struct buf
*)zalloc(buf_hdr_zone
);
2607 lck_mtx_lock(buf_mtxp
);
2612 binshash(bp
, &invalhash
);
2613 SET(bp
->b_flags
, B_HDRALLOC
);
2615 binsheadfree(bp
, &bufqueues
[BQ_EMPTY
], BQ_EMPTY
);
2619 bufstats
.bufs_sleeps
++;
2621 /* wait for a free buffer of any kind */
2623 /* hz value is 100 */
2624 ts
.tv_sec
= (slptimeo
/1000);
2625 /* the hz value is 100; which leads to 10ms */
2626 ts
.tv_nsec
= (slptimeo
% 1000) * NSEC_PER_USEC
* 1000 * 10;
2627 msleep(&needbuffer
, buf_mtxp
, slpflag
|(PRIBIO
+1), (char *)"getnewbuf", &ts
);
2632 /* Buffer available either on AGE or LRU or META */
2636 /* Buffer available either on AGE or LRU */
2640 } else if (!lru_bp
) {
2643 } else { /* buffer available on both AGE and LRU */
2644 int t
= buf_timestamp();
2646 age_time
= t
- age_bp
->b_timestamp
;
2647 lru_time
= t
- lru_bp
->b_timestamp
;
2648 if ((age_time
< 0) || (lru_time
< 0)) { /* time set backwards */
2652 * we should probably re-timestamp eveything in the
2653 * queues at this point with the current time
2656 if ((lru_time
>= lru_is_stale
) && (age_time
< age_is_stale
)) {
2666 if (!bp
) { /* Neither on AGE nor on LRU */
2669 } else if (meta_bp
) {
2670 int t
= buf_timestamp();
2672 bp_time
= t
- bp
->b_timestamp
;
2673 meta_time
= t
- meta_bp
->b_timestamp
;
2675 if (!(bp_time
< 0) && !(meta_time
< 0)) {
2676 /* time not set backwards */
2678 bp_is_stale
= (*queue
== BQ_LRU
) ?
2679 lru_is_stale
: age_is_stale
;
2681 if ((meta_time
>= meta_is_stale
) &&
2682 (bp_time
< bp_is_stale
)) {
2689 if (ISSET(bp
->b_flags
, B_LOCKED
) || ISSET(bp
->b_lflags
, BL_BUSY
))
2690 panic("getnewbuf: bp @ 0x%x is LOCKED or BUSY! (flags 0x%x)\n", bp
, bp
->b_flags
);
2693 if (bcleanbuf(bp
)) {
2695 * moved to the laundry thread, buffer not ready
2706 * Returns 0 is buffer is ready to use,
2707 * Returns 1 if issued a buf_bawrite() to indicate
2708 * that the buffer is not ready.
2710 * buf_mtxp is held upon entry
2711 * returns with buf_mtxp locked
2719 /* Remove from the queue */
2720 bremfree_locked(bp
);
2722 /* Buffer is no longer on free lists. */
2723 SET(bp
->b_lflags
, BL_BUSY
);
2725 bp
->b_owner
= current_thread();
2729 * If buffer was a delayed write, start the IO by queuing
2730 * it on the LAUNDRY queue, and return 1
2732 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
2733 binstailfree(bp
, &bufqueues
[BQ_LAUNDRY
], BQ_LAUNDRY
);
2736 lck_mtx_unlock(buf_mtxp
);
2738 wakeup(&blaundrycnt
);
2739 /* and give it a chance to run */
2740 (void)thread_block(THREAD_CONTINUE_NULL
);
2742 lck_mtx_lock(buf_mtxp
);
2747 lck_mtx_unlock(buf_mtxp
);
2751 * disassociate us from our vnode, if we had one...
2756 if (ISSET(bp
->b_flags
, B_META
)) {
2759 elem
= (vm_offset_t
)bp
->b_datap
;
2760 bp
->b_datap
= (uintptr_t)0xdeadbeef;
2762 if (ISSET(bp
->b_flags
, B_ZALLOC
)) {
2765 z
= getbufzone(bp
->b_bufsize
);
2766 zfree(z
, (void *)elem
);
2768 kmem_free(kernel_map
, elem
, bp
->b_bufsize
);
2771 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
2773 /* clear out various other fields */
2775 bp
->b_datap
= (uintptr_t)NULL
;
2776 bp
->b_upl
= (void *)NULL
;
2778 * preserve the state of whether this buffer
2779 * was allocated on the fly or not...
2780 * the only other flag that should be set at
2781 * this point is BL_BUSY...
2784 bp
->b_owner
= current_thread();
2787 bp
->b_lflags
= BL_BUSY
;
2788 bp
->b_flags
= (bp
->b_flags
& B_HDRALLOC
);
2790 bp
->b_blkno
= bp
->b_lblkno
= 0;
2791 bp
->b_iodone
= NULL
;
2795 bp
->b_dirtyoff
= bp
->b_dirtyend
= 0;
2796 bp
->b_validoff
= bp
->b_validend
= 0;
2798 /* nuke any credentials we were holding */
2800 if (cred
!= NOCRED
) {
2801 bp
->b_rcred
= NOCRED
;
2802 kauth_cred_rele(cred
);
2805 if (cred
!= NOCRED
) {
2806 bp
->b_wcred
= NOCRED
;
2807 kauth_cred_rele(cred
);
2809 lck_mtx_lock(buf_mtxp
);
2817 buf_invalblkno(vnode_t vp
, daddr64_t lblkno
, int flags
)
2822 lck_mtx_lock(buf_mtxp
);
2824 if ((bp
= incore_locked(vp
, lblkno
)) == (struct buf
*)0) {
2825 lck_mtx_unlock(buf_mtxp
);
2828 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
2829 if ( !ISSET(flags
, BUF_WAIT
)) {
2830 lck_mtx_unlock(buf_mtxp
);
2833 SET(bp
->b_lflags
, BL_WANTED
);
2835 error
= msleep((caddr_t
)bp
, buf_mtxp
, (PRIBIO
+ 1), (char *)"buf_invalblkno", 0);
2841 bremfree_locked(bp
);
2842 SET(bp
->b_lflags
, BL_BUSY
);
2843 SET(bp
->b_flags
, B_INVAL
);
2845 bp
->b_owner
= current_thread();
2848 lck_mtx_unlock(buf_mtxp
);
2858 int need_wakeup
= 0;
2860 lck_mtx_lock(buf_mtxp
);
2862 if (ISSET(bp
->b_lflags
, BL_WANTED
)) {
2864 * delay the actual wakeup until after we
2865 * clear BL_BUSY and we've dropped buf_mtxp
2870 * Unlock the buffer.
2872 CLR(bp
->b_lflags
, (BL_BUSY
| BL_WANTED
));
2874 lck_mtx_unlock(buf_mtxp
);
2878 * Wake up any proceeses waiting for _this_ buffer to become free.
2886 buf_acquire(buf_t bp
, int flags
, int slpflag
, int slptimeo
) {
2889 lck_mtx_lock(buf_mtxp
);
2891 error
= buf_acquire_locked(bp
, flags
, slpflag
, slptimeo
);
2893 lck_mtx_unlock(buf_mtxp
);
2900 buf_acquire_locked(buf_t bp
, int flags
, int slpflag
, int slptimeo
)
2905 if (ISSET(bp
->b_flags
, B_LOCKED
)) {
2906 if ((flags
& BAC_SKIP_LOCKED
))
2909 if ((flags
& BAC_SKIP_NONLOCKED
))
2912 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
2914 * since the mutex_lock may block, the buffer
2915 * may become BUSY, so we need to
2916 * recheck for a NOWAIT request
2918 if (flags
& BAC_NOWAIT
)
2920 SET(bp
->b_lflags
, BL_WANTED
);
2922 /* the hz value is 100; which leads to 10ms */
2923 ts
.tv_sec
= (slptimeo
/100);
2924 ts
.tv_nsec
= (slptimeo
% 100) * 10 * NSEC_PER_USEC
* 1000;
2925 error
= msleep((caddr_t
)bp
, buf_mtxp
, slpflag
| (PRIBIO
+ 1), (char *)"buf_acquire", &ts
);
2931 if (flags
& BAC_REMOVE
)
2932 bremfree_locked(bp
);
2933 SET(bp
->b_lflags
, BL_BUSY
);
2935 bp
->b_owner
= current_thread();
2943 * Wait for operations on the buffer to complete.
2944 * When they do, extract and return the I/O's error value.
2947 buf_biowait(buf_t bp
)
2949 lck_mtx_lock(buf_mtxp
);
2951 while (!ISSET(bp
->b_flags
, B_DONE
))
2952 (void) msleep(bp
, buf_mtxp
, (PRIBIO
+1), (char *)"buf_biowait", 0);
2954 lck_mtx_unlock(buf_mtxp
);
2956 /* check for interruption of I/O (e.g. via NFS), then errors. */
2957 if (ISSET(bp
->b_flags
, B_EINTR
)) {
2958 CLR(bp
->b_flags
, B_EINTR
);
2960 } else if (ISSET(bp
->b_flags
, B_ERROR
))
2961 return (bp
->b_error
? bp
->b_error
: EIO
);
2967 * Mark I/O complete on a buffer.
2969 * If a callback has been requested, e.g. the pageout
2970 * daemon, do so. Otherwise, awaken waiting processes.
2972 * [ Leffler, et al., says on p.247:
2973 * "This routine wakes up the blocked process, frees the buffer
2974 * for an asynchronous write, or, for a request by the pagedaemon
2975 * process, invokes a procedure specified in the buffer structure" ]
2977 * In real life, the pagedaemon (or other system processes) wants
2978 * to do async stuff to, and doesn't want the buffer buf_brelse()'d.
2979 * (for swap pager, that puts swap buffers on the free lists (!!!),
2980 * for the vn device, that puts malloc'd buffers on the free lists!)
2982 extern struct timeval priority_IO_timestamp_for_root
;
2983 extern int hard_throttle_on_root
;
2986 buf_biodone(buf_t bp
)
2988 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 387)) | DBG_FUNC_START
,
2989 (int)bp
, (int)bp
->b_datap
, bp
->b_flags
, 0, 0);
2991 if (ISSET(bp
->b_flags
, B_DONE
))
2992 panic("biodone already");
2994 if (kdebug_enable
) {
2995 int code
= DKIO_DONE
;
2997 if (bp
->b_flags
& B_READ
)
2999 if (bp
->b_flags
& B_ASYNC
)
3002 if (bp
->b_flags
& B_META
)
3004 else if (bp
->b_flags
& B_PAGEIO
)
3005 code
|= DKIO_PAGING
;
3007 KERNEL_DEBUG_CONSTANT(FSDBG_CODE(DBG_DKRW
, code
) | DBG_FUNC_NONE
,
3008 (unsigned int)bp
, (unsigned int)bp
->b_vp
,
3009 bp
->b_resid
, bp
->b_error
, 0);
3011 if ((bp
->b_vp
!= NULLVP
) &&
3012 ((bp
->b_flags
& (B_PAGEIO
| B_READ
)) == (B_PAGEIO
| B_READ
)) &&
3013 (bp
->b_vp
->v_mount
->mnt_kern_flag
& MNTK_ROOTDEV
)) {
3014 microuptime(&priority_IO_timestamp_for_root
);
3015 hard_throttle_on_root
= 0;
3018 * I/O was done, so don't believe
3019 * the DIRTY state from VM anymore
3021 CLR(bp
->b_flags
, B_WASDIRTY
);
3023 if (!ISSET(bp
->b_flags
, B_READ
) && !ISSET(bp
->b_flags
, B_RAW
))
3025 * wake up any writer's blocked
3026 * on throttle or waiting for I/O
3029 vnode_writedone(bp
->b_vp
);
3031 if (ISSET(bp
->b_flags
, (B_CALL
| B_FILTER
))) { /* if necessary, call out */
3032 void (*iodone_func
)(struct buf
*, void *) = bp
->b_iodone
;
3033 void *arg
= (void *)bp
->b_transaction
;
3034 int callout
= ISSET(bp
->b_flags
, B_CALL
);
3036 CLR(bp
->b_flags
, (B_CALL
| B_FILTER
)); /* filters and callouts are one-shot */
3037 bp
->b_iodone
= NULL
;
3038 bp
->b_transaction
= NULL
;
3040 if (iodone_func
== NULL
) {
3041 panic("biodone: bp @ 0x%x has NULL b_iodone!\n", bp
);
3044 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
3045 (*iodone_func
)(bp
, arg
);
3049 * assumes that the call back function takes
3050 * ownership of the bp and deals with releasing it if necessary
3054 * in this case the call back function is acting
3055 * strictly as a filter... it does not take
3056 * ownership of the bp and is expecting us
3057 * to finish cleaning up... this is currently used
3058 * by the HFS journaling code
3061 if (ISSET(bp
->b_flags
, B_ASYNC
)) { /* if async, release it */
3062 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
3065 } else { /* or just wakeup the buffer */
3067 * by taking the mutex, we serialize
3068 * the buf owner calling buf_biowait so that we'll
3069 * only see him in one of 2 states...
3070 * state 1: B_DONE wasn't set and he's
3072 * state 2: he's blocked trying to take the
3073 * mutex before looking at B_DONE
3074 * BL_WANTED is cleared in case anyone else
3075 * is blocked waiting for the buffer... note
3076 * that we haven't cleared B_BUSY yet, so if
3077 * they do get to run, their going to re-set
3078 * BL_WANTED and go back to sleep
3080 lck_mtx_lock(buf_mtxp
);
3082 CLR(bp
->b_lflags
, BL_WANTED
);
3083 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
3085 lck_mtx_unlock(buf_mtxp
);
3090 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 387)) | DBG_FUNC_END
,
3091 (int)bp
, (int)bp
->b_datap
, bp
->b_flags
, 0, 0);
3095 * Return a count of buffers on the "locked" queue.
3098 count_lock_queue(void)
3103 lck_mtx_lock(buf_mtxp
);
3105 for (bp
= bufqueues
[BQ_LOCKED
].tqh_first
; bp
;
3106 bp
= bp
->b_freelist
.tqe_next
)
3108 lck_mtx_unlock(buf_mtxp
);
3114 * Return a count of 'busy' buffers. Used at the time of shutdown.
3117 count_busy_buffers(void)
3122 for (bp
= &buf
[nbuf
]; --bp
>= buf
; )
3123 if (!ISSET(bp
->b_flags
, B_INVAL
) && ISSET(bp
->b_lflags
, BL_BUSY
))
3130 * Print out statistics on the current allocation of the buffer pool.
3131 * Can be enabled to print out on every ``sync'' by setting "syncprt"
3132 * in vfs_syscalls.c using sysctl.
3138 register struct buf
*bp
;
3139 register struct bqueues
*dp
;
3140 int counts
[MAXBSIZE
/CLBYTES
+1];
3141 static char *bname
[BQUEUES
] =
3142 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
3144 for (dp
= bufqueues
, i
= 0; dp
< &bufqueues
[BQUEUES
]; dp
++, i
++) {
3146 for (j
= 0; j
<= MAXBSIZE
/CLBYTES
; j
++)
3149 lck_mtx_lock(buf_mtxp
);
3151 for (bp
= dp
->tqh_first
; bp
; bp
= bp
->b_freelist
.tqe_next
) {
3152 counts
[bp
->b_bufsize
/CLBYTES
]++;
3155 lck_mtx_unlock(buf_mtxp
);
3157 printf("%s: total-%d", bname
[i
], count
);
3158 for (j
= 0; j
<= MAXBSIZE
/CLBYTES
; j
++)
3160 printf(", %d-%d", j
* CLBYTES
, counts
[j
]);
3164 #endif /* DIAGNOSTIC */
3166 #define NRESERVEDIOBUFS 64
3170 alloc_io_buf(vnode_t vp
, int priv
)
3174 lck_mtx_lock(iobuffer_mtxp
);
3176 while (((niobuf
- NRESERVEDIOBUFS
< bufstats
.bufs_iobufinuse
) && !priv
) ||
3177 (bp
= iobufqueue
.tqh_first
) == NULL
) {
3178 bufstats
.bufs_iobufsleeps
++;
3181 (void) msleep(&need_iobuffer
, iobuffer_mtxp
, (PRIBIO
+1), (const char *)"alloc_io_buf", 0);
3183 TAILQ_REMOVE(&iobufqueue
, bp
, b_freelist
);
3185 bufstats
.bufs_iobufinuse
++;
3186 if (bufstats
.bufs_iobufinuse
> bufstats
.bufs_iobufmax
)
3187 bufstats
.bufs_iobufmax
= bufstats
.bufs_iobufinuse
;
3189 lck_mtx_unlock(iobuffer_mtxp
);
3192 * initialize various fields
3193 * we don't need to hold the mutex since the buffer
3194 * is now private... the vp should have a reference
3195 * on it and is not protected by this mutex in any event
3197 bp
->b_timestamp
= 0;
3202 bp
->b_lflags
= BL_BUSY
| BL_IOBUF
;
3203 bp
->b_blkno
= bp
->b_lblkno
= 0;
3205 bp
->b_owner
= current_thread();
3208 bp
->b_iodone
= NULL
;
3216 if (vp
&& (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
))
3217 bp
->b_dev
= vp
->v_rdev
;
3226 free_io_buf(buf_t bp
)
3228 int need_wakeup
= 0;
3231 * put buffer back on the head of the iobufqueue
3234 bp
->b_flags
= B_INVAL
;
3236 lck_mtx_lock(iobuffer_mtxp
);
3238 binsheadfree(bp
, &iobufqueue
, -1);
3240 if (need_iobuffer
) {
3242 * Wake up any processes waiting because they need an io buffer
3244 * do the wakeup after we drop the mutex... it's possible that the
3245 * wakeup will be superfluous if need_iobuffer gets set again and
3246 * another thread runs this path, but it's highly unlikely, doesn't
3247 * hurt, and it means we don't hold up I/O progress if the wakeup blocks
3248 * trying to grab a task related lock...
3253 bufstats
.bufs_iobufinuse
--;
3255 lck_mtx_unlock(iobuffer_mtxp
);
3258 wakeup(&need_iobuffer
);
3264 * If getnewbuf() calls bcleanbuf() on the same thread
3265 * there is a potential for stack overrun and deadlocks.
3266 * So we always handoff the work to a worker thread for completion
3268 #include <mach/mach_types.h>
3269 #include <mach/memory_object_types.h>
3270 #include <kern/sched_prim.h>
3274 bcleanbuf_thread_init(void)
3276 /* create worker thread */
3277 kernel_thread(kernel_task
, bcleanbuf_thread
);
3281 bcleanbuf_thread(void)
3288 lck_mtx_lock(buf_mtxp
);
3290 while (blaundrycnt
== 0)
3291 (void)msleep((void *)&blaundrycnt
, buf_mtxp
, PRIBIO
, "blaundry", 0);
3293 bp
= TAILQ_FIRST(&bufqueues
[BQ_LAUNDRY
]);
3295 * Remove from the queue
3297 bremfree_locked(bp
);
3300 lck_mtx_unlock(buf_mtxp
);
3304 error
= bawrite_internal(bp
, 0);
3307 lck_mtx_lock(buf_mtxp
);
3309 binstailfree(bp
, &bufqueues
[BQ_LAUNDRY
], BQ_LAUNDRY
);
3312 lck_mtx_unlock(buf_mtxp
);
3315 (void)tsleep((void *)&blaundrycnt
, PRIBIO
, "blaundry", 1);
3318 (void)thread_block(THREAD_CONTINUE_NULL
);
3327 brecover_data(buf_t bp
)
3331 upl_page_info_t
*pl
;
3333 vnode_t vp
= bp
->b_vp
;
3337 if ( !UBCINFOEXISTS(vp
) || bp
->b_bufsize
== 0)
3340 upl_flags
= UPL_PRECIOUS
;
3341 if (! (buf_flags(bp
) & B_READ
)) {
3343 * "write" operation: let the UPL subsystem know
3344 * that we intend to modify the buffer cache pages we're
3347 upl_flags
|= UPL_WILL_MODIFY
;
3350 kret
= ubc_create_upl(vp
,
3351 ubc_blktooff(vp
, bp
->b_lblkno
),
3356 if (kret
!= KERN_SUCCESS
)
3357 panic("Failed to create UPL");
3359 for (upl_offset
= 0; upl_offset
< bp
->b_bufsize
; upl_offset
+= PAGE_SIZE
) {
3361 if (!upl_valid_page(pl
, upl_offset
/ PAGE_SIZE
) || !upl_dirty_page(pl
, upl_offset
/ PAGE_SIZE
)) {
3362 ubc_upl_abort(upl
, 0);
3368 kret
= ubc_upl_map(upl
, (vm_address_t
*)&(bp
->b_datap
));
3370 if (kret
!= KERN_SUCCESS
)
3371 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
3376 SET(bp
->b_flags
, B_INVAL
);
3393 bp_cmp(void *a
, void *b
)
3395 buf_t
*bp_a
= *(buf_t
**)a
,
3396 *bp_b
= *(buf_t
**)b
;
3399 // don't have to worry about negative block
3400 // numbers so this is ok to do.
3402 res
= (bp_a
->b_blkno
- bp_b
->b_blkno
);
3409 bflushq(int whichq
, mount_t mp
)
3413 int total_writes
= 0;
3414 static buf_t flush_table
[NFLUSH
];
3416 if (whichq
< 0 || whichq
>= BQUEUES
) {
3421 lck_mtx_lock(buf_mtxp
);
3423 bp
= TAILQ_FIRST(&bufqueues
[whichq
]);
3425 for (buf_count
= 0; bp
; bp
= next
) {
3426 next
= bp
->b_freelist
.tqe_next
;
3428 if (bp
->b_vp
== NULL
|| bp
->b_vp
->v_mount
!= mp
) {
3432 if (ISSET(bp
->b_flags
, B_DELWRI
) && !ISSET(bp
->b_lflags
, BL_BUSY
)) {
3434 bremfree_locked(bp
);
3436 bp
->b_owner
= current_thread();
3439 SET(bp
->b_lflags
, BL_BUSY
);
3440 flush_table
[buf_count
] = bp
;
3444 if (buf_count
>= NFLUSH
) {
3445 lck_mtx_unlock(buf_mtxp
);
3447 qsort(flush_table
, buf_count
, sizeof(struct buf
*), bp_cmp
);
3449 for (i
= 0; i
< buf_count
; i
++) {
3450 buf_bawrite(flush_table
[i
]);
3456 lck_mtx_unlock(buf_mtxp
);
3458 if (buf_count
> 0) {
3459 qsort(flush_table
, buf_count
, sizeof(struct buf
*), bp_cmp
);
3461 for (i
= 0; i
< buf_count
; i
++) {
3462 buf_bawrite(flush_table
[i
]);
3466 return (total_writes
);
3473 /* XXX move this to a separate file */
3476 * NOTE: THIS CODE HAS NOT BEEN UPDATED
3477 * WITH RESPECT TO THE NEW LOCKING MODEL
3482 * Dynamic Scaling of the Buffer Queues
3485 typedef long long blsize_t
;
3487 blsize_t MAXNBUF
; /* initialize to (sane_size / PAGE_SIZE) */
3488 /* Global tunable limits */
3489 blsize_t nbufh
; /* number of buffer headers */
3490 blsize_t nbuflow
; /* minimum number of buffer headers required */
3491 blsize_t nbufhigh
; /* maximum number of buffer headers allowed */
3492 blsize_t nbuftarget
; /* preferred number of buffer headers */
3497 * 1. 0 < nbuflow <= nbufh <= nbufhigh
3498 * 2. nbufhigh <= MAXNBUF
3499 * 3. 0 < nbuflow <= nbuftarget <= nbufhigh
3500 * 4. nbufh can not be set by sysctl().
3503 /* Per queue tunable limits */
3506 blsize_t bl_nlow
; /* minimum number of buffer headers required */
3507 blsize_t bl_num
; /* number of buffer headers on the queue */
3508 blsize_t bl_nlhigh
; /* maximum number of buffer headers allowed */
3509 blsize_t bl_target
; /* preferred number of buffer headers */
3510 long bl_stale
; /* Seconds after which a buffer is considered stale */
3516 * 1. 0 <= bl_nlow <= bl_num <= bl_nlhigh
3517 * 2. bl_nlhigh <= MAXNBUF
3518 * 3. bufqlim[BQ_META].bl_nlow != 0
3519 * 4. bufqlim[BQ_META].bl_nlow > (number of possible concurrent
3520 * file system IO operations)
3521 * 5. bl_num can not be set by sysctl().
3522 * 6. bl_nhigh <= nbufhigh
3528 * Defining it blsize_t as long permits 2^31 buffer headers per queue.
3529 * Which can describe (2^31 * PAGE_SIZE) memory per queue.
3531 * These limits are exported to by means of sysctl().
3532 * It was decided to define blsize_t as a 64 bit quantity.
3533 * This will make sure that we will not be required to change it
3534 * as long as we do not exceed 64 bit address space for the kernel.
3536 * low and high numbers parameters initialized at compile time
3537 * and boot arguments can be used to override them. sysctl()
3538 * would not change the value. sysctl() can get all the values
3539 * but can set only target. num is the current level.
3541 * Advantages of having a "bufqscan" thread doing the balancing are,
3542 * Keep enough bufs on BQ_EMPTY.
3543 * getnewbuf() by default will always select a buffer from the BQ_EMPTY.
3544 * getnewbuf() perfoms best if a buffer was found there.
3545 * Also this minimizes the possibility of starting IO
3546 * from getnewbuf(). That's a performance win, too.
3548 * Localize complex logic [balancing as well as time aging]
3551 * Simplify getnewbuf() logic by elimination of time aging code.
3557 * The goal of the dynamic scaling of the buffer queues to to keep
3558 * the size of the LRU close to bl_target. Buffers on a queue would
3561 * There would be a thread which will be responsible for "balancing"
3562 * the buffer cache queues.
3564 * The scan order would be: AGE, LRU, META, EMPTY.
3567 long bufqscanwait
= 0;
3569 static void bufqscan_thread();
3570 static int balancebufq(int q
);
3571 static int btrimempty(int n
);
3572 static __inline__
int initbufqscan(void);
3573 static __inline__
int nextbufq(int q
);
3574 static void buqlimprt(int all
);
3577 static __inline__
void
3580 if ((q
< 0) || (q
>= BQUEUES
))
3583 bufqlim
[q
].bl_num
++;
3587 static __inline__
void
3590 if ((q
< 0) || (q
>= BQUEUES
))
3593 bufqlim
[q
].bl_num
--;
3598 bufq_balance_thread_init()
3601 if (bufqscanwait
++ == 0) {
3603 /* Initalize globals */
3604 MAXNBUF
= (sane_size
/ PAGE_SIZE
);
3606 nbuflow
= min(nbufh
, 100);
3607 nbufhigh
= min(MAXNBUF
, max(nbufh
, 2048));
3608 nbuftarget
= (sane_size
>> 5) / PAGE_SIZE
;
3609 nbuftarget
= max(nbuflow
, nbuftarget
);
3610 nbuftarget
= min(nbufhigh
, nbuftarget
);
3613 * Initialize the bufqlim
3617 bufqlim
[BQ_LOCKED
].bl_nlow
= 0;
3618 bufqlim
[BQ_LOCKED
].bl_nlhigh
= 32;
3619 bufqlim
[BQ_LOCKED
].bl_target
= 0;
3620 bufqlim
[BQ_LOCKED
].bl_stale
= 30;
3623 bufqlim
[BQ_LRU
].bl_nlow
= 0;
3624 bufqlim
[BQ_LRU
].bl_nlhigh
= nbufhigh
/4;
3625 bufqlim
[BQ_LRU
].bl_target
= nbuftarget
/4;
3626 bufqlim
[BQ_LRU
].bl_stale
= LRU_IS_STALE
;
3629 bufqlim
[BQ_AGE
].bl_nlow
= 0;
3630 bufqlim
[BQ_AGE
].bl_nlhigh
= nbufhigh
/4;
3631 bufqlim
[BQ_AGE
].bl_target
= nbuftarget
/4;
3632 bufqlim
[BQ_AGE
].bl_stale
= AGE_IS_STALE
;
3635 bufqlim
[BQ_EMPTY
].bl_nlow
= 0;
3636 bufqlim
[BQ_EMPTY
].bl_nlhigh
= nbufhigh
/4;
3637 bufqlim
[BQ_EMPTY
].bl_target
= nbuftarget
/4;
3638 bufqlim
[BQ_EMPTY
].bl_stale
= 600000;
3641 bufqlim
[BQ_META
].bl_nlow
= 0;
3642 bufqlim
[BQ_META
].bl_nlhigh
= nbufhigh
/4;
3643 bufqlim
[BQ_META
].bl_target
= nbuftarget
/4;
3644 bufqlim
[BQ_META
].bl_stale
= META_IS_STALE
;
3647 bufqlim
[BQ_LOCKED
].bl_nlow
= 0;
3648 bufqlim
[BQ_LOCKED
].bl_nlhigh
= 32;
3649 bufqlim
[BQ_LOCKED
].bl_target
= 0;
3650 bufqlim
[BQ_LOCKED
].bl_stale
= 30;
3655 /* create worker thread */
3656 kernel_thread(kernel_task
, bufqscan_thread
);
3659 /* The workloop for the buffer balancing thread */
3667 int q
; /* buffer queue to process */
3671 moretodo
|= balancebufq(q
);
3680 (void)tsleep((void *)&bufqscanwait
, PRIBIO
, "bufqscanwait", 60 * hz
);
3685 /* Seed for the buffer queue balancing */
3686 static __inline__
int
3689 /* Start with AGE queue */
3693 /* Pick next buffer queue to balance */
3694 static __inline__
int
3697 int order
[] = { BQ_AGE
, BQ_LRU
, BQ_META
, BQ_EMPTY
, 0 };
3704 /* function to balance the buffer queues */
3712 /* reject invalid q */
3713 if ((q
< 0) || (q
>= BQUEUES
))
3716 /* LOCKED or LAUNDRY queue MUST not be balanced */
3717 if ((q
== BQ_LOCKED
) || (q
== BQ_LAUNDRY
))
3720 n
= (bufqlim
[q
].bl_num
- bufqlim
[q
].bl_target
);
3722 /* If queue has less than target nothing more to do */
3727 /* Balance only a small amount (12.5%) at a time */
3731 /* EMPTY queue needs special handling */
3732 if (q
== BQ_EMPTY
) {
3733 moretodo
|= btrimempty(n
);
3737 t
= buf_timestamp():
3739 for (; n
> 0; n
--) {
3740 struct buf
*bp
= bufqueues
[q
].tqh_first
;
3744 /* check if it's stale */
3745 if ((t
- bp
->b_timestamp
) > bufqlim
[q
].bl_stale
) {
3746 if (bcleanbuf(bp
)) {
3747 /* buf_bawrite() issued, bp not ready */
3750 /* release the cleaned buffer to BQ_EMPTY */
3751 SET(bp
->b_flags
, B_INVAL
);
3767 * When struct buf are allocated dynamically, this would
3768 * reclaim upto 'n' struct buf from the empty queue.
3778 static char *bname
[BQUEUES
] =
3779 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
3782 for (i
= 0; i
< BQUEUES
; i
++) {
3783 printf("%s : ", bname
[i
]);
3784 printf("min = %ld, ", (long)bufqlim
[i
].bl_nlow
);
3785 printf("cur = %ld, ", (long)bufqlim
[i
].bl_num
);
3786 printf("max = %ld, ", (long)bufqlim
[i
].bl_nlhigh
);
3787 printf("target = %ld, ", (long)bufqlim
[i
].bl_target
);
3788 printf("stale after %ld seconds\n", bufqlim
[i
].bl_stale
);
3791 for (i
= 0; i
< BQUEUES
; i
++) {
3792 printf("%s : ", bname
[i
]);
3793 printf("cur = %ld, ", (long)bufqlim
[i
].bl_num
);