2 * Copyright (c) 2000-2004 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * The contents of this file constitute Original Code as defined in and
7 * are subject to the Apple Public Source License Version 1.1 (the
8 * "License"). You may not use this file except in compliance with the
9 * License. Please obtain a copy of the License at
10 * http://www.apple.com/publicsource and read it before using this file.
12 * This Original Code and all software distributed under the License are
13 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
14 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
15 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
17 * License for the specific language governing rights and limitations
20 * @APPLE_LICENSE_HEADER_END@
22 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
24 * Copyright (c) 1994 Christopher G. Demetriou
25 * Copyright (c) 1982, 1986, 1989, 1993
26 * The Regents of the University of California. All rights reserved.
27 * (c) UNIX System Laboratories, Inc.
28 * All or some portions of this file are derived from material licensed
29 * to the University of California by American Telephone and Telegraph
30 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
31 * the permission of UNIX System Laboratories, Inc.
33 * Redistribution and use in source and binary forms, with or without
34 * modification, are permitted provided that the following conditions
36 * 1. Redistributions of source code must retain the above copyright
37 * notice, this list of conditions and the following disclaimer.
38 * 2. Redistributions in binary form must reproduce the above copyright
39 * notice, this list of conditions and the following disclaimer in the
40 * documentation and/or other materials provided with the distribution.
41 * 3. All advertising materials mentioning features or use of this software
42 * must display the following acknowledgement:
43 * This product includes software developed by the University of
44 * California, Berkeley and its contributors.
45 * 4. Neither the name of the University nor the names of its contributors
46 * may be used to endorse or promote products derived from this software
47 * without specific prior written permission.
49 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
61 * @(#)vfs_bio.c 8.6 (Berkeley) 1/11/94
66 * Bach: The Design of the UNIX Operating System (Prentice Hall, 1986)
67 * Leffler, et al.: The Design and Implementation of the 4.3BSD
68 * UNIX Operating System (Addison Welley, 1989)
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/proc_internal.h>
74 #include <sys/buf_internal.h>
75 #include <sys/vnode_internal.h>
76 #include <sys/mount_internal.h>
77 #include <sys/trace.h>
78 #include <sys/malloc.h>
79 #include <sys/resourcevar.h>
80 #include <miscfs/specfs/specdev.h>
82 #include <sys/kauth.h>
84 #include <kern/assert.h>
85 #endif /* DIAGNOSTIC */
86 #include <kern/task.h>
87 #include <kern/zalloc.h>
88 #include <kern/lock.h>
90 #include <vm/vm_kern.h>
92 #include <sys/kdebug.h>
93 #include <machine/spl.h>
96 static __inline__
void bufqinc(int q
);
97 static __inline__
void bufqdec(int q
);
100 static int bcleanbuf(buf_t bp
);
101 static int brecover_data(buf_t bp
);
102 static boolean_t
incore(vnode_t vp
, daddr64_t blkno
);
103 static buf_t
incore_locked(vnode_t vp
, daddr64_t blkno
);
104 /* timeout is in msecs */
105 static buf_t
getnewbuf(int slpflag
, int slptimeo
, int *queue
);
106 static void bremfree_locked(buf_t bp
);
107 static void buf_reassign(buf_t bp
, vnode_t newvp
);
108 static errno_t
buf_acquire_locked(buf_t bp
, int flags
, int slpflag
, int slptimeo
);
109 static int buf_iterprepare(vnode_t vp
, struct buflists
*, int flags
);
110 static void buf_itercomplete(vnode_t vp
, struct buflists
*, int flags
);
112 __private_extern__
int bdwrite_internal(buf_t
, int);
114 /* zone allocated buffer headers */
115 static void bufzoneinit(void);
116 static void bcleanbuf_thread_init(void);
117 static void bcleanbuf_thread(void);
119 static zone_t buf_hdr_zone
;
120 static int buf_hdr_count
;
124 * Definitions for the buffer hash lists.
126 #define BUFHASH(dvp, lbn) \
127 (&bufhashtbl[((long)(dvp) / sizeof(*(dvp)) + (int)(lbn)) & bufhash])
128 LIST_HEAD(bufhashhdr
, buf
) *bufhashtbl
, invalhash
;
131 /* Definitions for the buffer stats. */
132 struct bufstats bufstats
;
134 /* Number of delayed write buffers */
139 static TAILQ_HEAD(ioqueue
, buf
) iobufqueue
;
140 static TAILQ_HEAD(bqueues
, buf
) bufqueues
[BQUEUES
];
141 static int needbuffer
;
142 static int need_iobuffer
;
144 static lck_grp_t
*buf_mtx_grp
;
145 static lck_attr_t
*buf_mtx_attr
;
146 static lck_grp_attr_t
*buf_mtx_grp_attr
;
147 static lck_mtx_t
*iobuffer_mtxp
;
148 static lck_mtx_t
*buf_mtxp
;
150 static __inline__
int
159 * Insq/Remq for the buffer free lists.
162 #define binsheadfree(bp, dp, whichq) do { \
163 TAILQ_INSERT_HEAD(dp, bp, b_freelist); \
165 (bp)->b_whichq = whichq; \
166 (bp)->b_timestamp = buf_timestamp(); \
169 #define binstailfree(bp, dp, whichq) do { \
170 TAILQ_INSERT_TAIL(dp, bp, b_freelist); \
172 (bp)->b_whichq = whichq; \
173 (bp)->b_timestamp = buf_timestamp(); \
176 #define binsheadfree(bp, dp, whichq) do { \
177 TAILQ_INSERT_HEAD(dp, bp, b_freelist); \
178 (bp)->b_whichq = whichq; \
179 (bp)->b_timestamp = buf_timestamp(); \
182 #define binstailfree(bp, dp, whichq) do { \
183 TAILQ_INSERT_TAIL(dp, bp, b_freelist); \
184 (bp)->b_whichq = whichq; \
185 (bp)->b_timestamp = buf_timestamp(); \
190 #define BHASHENTCHECK(bp) \
191 if ((bp)->b_hash.le_prev != (struct buf **)0xdeadbeef) \
192 panic("%x: b_hash.le_prev is not deadbeef", (bp));
194 #define BLISTNONE(bp) \
195 (bp)->b_hash.le_next = (struct buf *)0; \
196 (bp)->b_hash.le_prev = (struct buf **)0xdeadbeef;
199 * Insq/Remq for the vnode usage lists.
201 #define bufinsvn(bp, dp) LIST_INSERT_HEAD(dp, bp, b_vnbufs)
202 #define bufremvn(bp) { \
203 LIST_REMOVE(bp, b_vnbufs); \
204 (bp)->b_vnbufs.le_next = NOLIST; \
208 * Time in seconds before a buffer on a list is
209 * considered as a stale buffer
211 #define LRU_IS_STALE 120 /* default value for the LRU */
212 #define AGE_IS_STALE 60 /* default value for the AGE */
213 #define META_IS_STALE 180 /* default value for the BQ_META */
215 int lru_is_stale
= LRU_IS_STALE
;
216 int age_is_stale
= AGE_IS_STALE
;
217 int meta_is_stale
= META_IS_STALE
;
218 static int boot_nbuf
= 0;
221 /* LIST_INSERT_HEAD() with assertions */
222 static __inline__
void
223 blistenterhead(struct bufhashhdr
* head
, buf_t bp
)
225 if ((bp
->b_hash
.le_next
= (head
)->lh_first
) != NULL
)
226 (head
)->lh_first
->b_hash
.le_prev
= &(bp
)->b_hash
.le_next
;
227 (head
)->lh_first
= bp
;
228 bp
->b_hash
.le_prev
= &(head
)->lh_first
;
229 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
230 panic("blistenterhead: le_prev is deadbeef");
233 static __inline__
void
234 binshash(buf_t bp
, struct bufhashhdr
*dp
)
238 #endif /* DIAGNOSTIC */
244 for(; nbp
!= NULL
; nbp
= nbp
->b_hash
.le_next
) {
246 panic("buf already in hashlist");
248 #endif /* DIAGNOSTIC */
250 blistenterhead(dp
, bp
);
253 static __inline__
void
256 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
257 panic("bremhash le_prev is deadbeef");
258 if (bp
->b_hash
.le_next
== bp
)
259 panic("bremhash: next points to self");
261 if (bp
->b_hash
.le_next
!= NULL
)
262 bp
->b_hash
.le_next
->b_hash
.le_prev
= bp
->b_hash
.le_prev
;
263 *bp
->b_hash
.le_prev
= (bp
)->b_hash
.le_next
;
270 buf_valid(buf_t bp
) {
272 if ( (bp
->b_flags
& (B_DONE
| B_DELWRI
)) )
278 buf_fromcache(buf_t bp
) {
280 if ( (bp
->b_flags
& B_CACHE
) )
286 buf_markinvalid(buf_t bp
) {
288 SET(bp
->b_flags
, B_INVAL
);
292 buf_markdelayed(buf_t bp
) {
294 SET(bp
->b_flags
, B_DELWRI
);
295 buf_reassign(bp
, bp
->b_vp
);
299 buf_markeintr(buf_t bp
) {
301 SET(bp
->b_flags
, B_EINTR
);
305 buf_markaged(buf_t bp
) {
307 SET(bp
->b_flags
, B_AGE
);
311 buf_error(buf_t bp
) {
313 return (bp
->b_error
);
317 buf_seterror(buf_t bp
, errno_t error
) {
319 if ((bp
->b_error
= error
))
320 SET(bp
->b_flags
, B_ERROR
);
322 CLR(bp
->b_flags
, B_ERROR
);
326 buf_setflags(buf_t bp
, int32_t flags
) {
328 SET(bp
->b_flags
, (flags
& BUF_X_WRFLAGS
));
332 buf_clearflags(buf_t bp
, int32_t flags
) {
334 CLR(bp
->b_flags
, (flags
& BUF_X_WRFLAGS
));
338 buf_flags(buf_t bp
) {
340 return ((bp
->b_flags
& BUF_X_RDFLAGS
));
344 buf_reset(buf_t bp
, int32_t io_flags
) {
346 CLR(bp
->b_flags
, (B_READ
| B_WRITE
| B_ERROR
| B_DONE
| B_INVAL
| B_ASYNC
| B_NOCACHE
));
347 SET(bp
->b_flags
, (io_flags
& (B_ASYNC
| B_READ
| B_WRITE
| B_NOCACHE
)));
353 buf_count(buf_t bp
) {
355 return (bp
->b_bcount
);
359 buf_setcount(buf_t bp
, uint32_t bcount
) {
361 bp
->b_bcount
= bcount
;
367 return (bp
->b_bufsize
);
371 buf_setsize(buf_t bp
, uint32_t bufsize
) {
373 bp
->b_bufsize
= bufsize
;
377 buf_resid(buf_t bp
) {
379 return (bp
->b_resid
);
383 buf_setresid(buf_t bp
, uint32_t resid
) {
389 buf_dirtyoff(buf_t bp
) {
391 return (bp
->b_dirtyoff
);
395 buf_dirtyend(buf_t bp
) {
397 return (bp
->b_dirtyend
);
401 buf_setdirtyoff(buf_t bp
, uint32_t dirtyoff
) {
403 bp
->b_dirtyoff
= dirtyoff
;
407 buf_setdirtyend(buf_t bp
, uint32_t dirtyend
) {
409 bp
->b_dirtyend
= dirtyend
;
413 buf_dataptr(buf_t bp
) {
415 return (bp
->b_datap
);
419 buf_setdataptr(buf_t bp
, uintptr_t data
) {
425 buf_vnode(buf_t bp
) {
431 buf_setvnode(buf_t bp
, vnode_t vp
) {
438 buf_callback(buf_t bp
)
440 if ( !(bp
->b_lflags
& BL_IOBUF
) )
441 return ((void *) NULL
);
442 if ( !(bp
->b_flags
& B_CALL
) )
443 return ((void *) NULL
);
445 return ((void *)bp
->b_iodone
);
450 buf_setcallback(buf_t bp
, void (*callback
)(buf_t
, void *), void *transaction
)
453 if ( !(bp
->b_lflags
& BL_IOBUF
) )
457 bp
->b_flags
|= (B_CALL
| B_ASYNC
);
459 bp
->b_flags
&= ~B_CALL
;
460 bp
->b_transaction
= transaction
;
461 bp
->b_iodone
= callback
;
467 buf_setupl(buf_t bp
, upl_t upl
, uint32_t offset
)
470 if ( !(bp
->b_lflags
& BL_IOBUF
) )
474 bp
->b_flags
|= B_CLUSTER
;
476 bp
->b_flags
&= ~B_CLUSTER
;
478 bp
->b_uploffset
= offset
;
484 buf_clone(buf_t bp
, int io_offset
, int io_size
, void (*iodone
)(buf_t
, void *), void *arg
)
488 if (io_offset
< 0 || io_size
< 0)
491 if ((unsigned)(io_offset
+ io_size
) > (unsigned)bp
->b_bcount
)
494 if (bp
->b_flags
& B_CLUSTER
) {
495 if (io_offset
&& ((bp
->b_uploffset
+ io_offset
) & PAGE_MASK
))
498 if (((bp
->b_uploffset
+ io_offset
+ io_size
) & PAGE_MASK
) && ((io_offset
+ io_size
) < bp
->b_bcount
))
501 io_bp
= alloc_io_buf(bp
->b_vp
, 0);
503 io_bp
->b_flags
= bp
->b_flags
& (B_COMMIT_UPL
| B_META
| B_PAGEIO
| B_CLUSTER
| B_PHYS
| B_ASYNC
| B_READ
);
506 io_bp
->b_transaction
= arg
;
507 io_bp
->b_iodone
= iodone
;
508 io_bp
->b_flags
|= B_CALL
;
510 if (bp
->b_flags
& B_CLUSTER
) {
511 io_bp
->b_upl
= bp
->b_upl
;
512 io_bp
->b_uploffset
= bp
->b_uploffset
+ io_offset
;
514 io_bp
->b_datap
= (uintptr_t)(((char *)bp
->b_datap
) + io_offset
);
516 io_bp
->b_bcount
= io_size
;
524 buf_setfilter(buf_t bp
, void (*filter
)(buf_t
, void *), void *transaction
,
525 void **old_iodone
, void **old_transaction
)
528 *old_iodone
= (void *)(bp
->b_iodone
);
530 *old_transaction
= (void *)(bp
->b_transaction
);
532 bp
->b_transaction
= transaction
;
533 bp
->b_iodone
= filter
;
534 bp
->b_flags
|= B_FILTER
;
539 buf_blkno(buf_t bp
) {
541 return (bp
->b_blkno
);
545 buf_lblkno(buf_t bp
) {
547 return (bp
->b_lblkno
);
551 buf_setblkno(buf_t bp
, daddr64_t blkno
) {
557 buf_setlblkno(buf_t bp
, daddr64_t lblkno
) {
559 bp
->b_lblkno
= lblkno
;
563 buf_device(buf_t bp
) {
569 buf_setdevice(buf_t bp
, vnode_t vp
) {
571 if ((vp
->v_type
!= VBLK
) && (vp
->v_type
!= VCHR
))
573 bp
->b_dev
= vp
->v_rdev
;
580 buf_drvdata(buf_t bp
) {
582 return (bp
->b_drvdata
);
586 buf_setdrvdata(buf_t bp
, void *drvdata
) {
588 bp
->b_drvdata
= drvdata
;
592 buf_fsprivate(buf_t bp
) {
594 return (bp
->b_fsprivate
);
598 buf_setfsprivate(buf_t bp
, void *fsprivate
) {
600 bp
->b_fsprivate
= fsprivate
;
604 buf_rcred(buf_t bp
) {
606 return (bp
->b_rcred
);
610 buf_wcred(buf_t bp
) {
612 return (bp
->b_wcred
);
622 buf_uploffset(buf_t bp
) {
624 return ((uint32_t)(bp
->b_uploffset
));
635 buf_map(buf_t bp
, caddr_t
*io_addr
)
641 if ( !(bp
->b_flags
& B_CLUSTER
)) {
642 *io_addr
= (caddr_t
)bp
->b_datap
;
645 real_bp
= (buf_t
)(bp
->b_real_bp
);
647 if (real_bp
&& real_bp
->b_datap
) {
649 * b_real_bp is only valid if B_CLUSTER is SET
650 * if it's non-zero, than someone did a cluster_bp call
651 * if the backing physical pages were already mapped
652 * in before the call to cluster_bp (non-zero b_datap),
653 * than we just use that mapping
655 *io_addr
= (caddr_t
)real_bp
->b_datap
;
658 kret
= ubc_upl_map(bp
->b_upl
, &vaddr
); /* Map it in */
660 if (kret
!= KERN_SUCCESS
) {
665 vaddr
+= bp
->b_uploffset
;
667 *io_addr
= (caddr_t
)vaddr
;
678 if ( !(bp
->b_flags
& B_CLUSTER
))
681 * see buf_map for the explanation
683 real_bp
= (buf_t
)(bp
->b_real_bp
);
685 if (real_bp
&& real_bp
->b_datap
)
688 if (bp
->b_lflags
& BL_IOBUF
) {
690 * when we commit these pages, we'll hit
691 * it with UPL_COMMIT_INACTIVE which
692 * will clear the reference bit that got
693 * turned on when we touched the mapping
695 bp
->b_flags
|= B_AGE
;
697 kret
= ubc_upl_unmap(bp
->b_upl
);
699 if (kret
!= KERN_SUCCESS
)
706 buf_clear(buf_t bp
) {
709 if (buf_map(bp
, &baddr
) == 0) {
710 bzero(baddr
, bp
->b_bcount
);
719 * Read or write a buffer that is not contiguous on disk.
720 * buffer is marked done/error at the conclusion
723 buf_strategy_fragmented(vnode_t devvp
, buf_t bp
, off_t f_offset
, size_t contig_bytes
)
725 vnode_t vp
= buf_vnode(bp
);
726 buf_t io_bp
; /* For reading or writing a single block */
729 size_t io_contig_bytes
;
735 * save our starting point... the bp was already mapped
736 * in buf_strategy before we got called
737 * no sense doing it again.
739 io_blkno
= bp
->b_blkno
;
741 * Make sure we redo this mapping for the next I/O
742 * i.e. this can never be a 'permanent' mapping
744 bp
->b_blkno
= bp
->b_lblkno
;
747 * Get an io buffer to do the deblocking
749 io_bp
= alloc_io_buf(devvp
, 0);
751 io_bp
->b_lblkno
= bp
->b_lblkno
;
752 io_bp
->b_datap
= bp
->b_datap
;
753 io_resid
= bp
->b_bcount
;
754 io_direction
= bp
->b_flags
& B_READ
;
755 io_contig_bytes
= contig_bytes
;
757 if (bp
->b_flags
& B_READ
)
758 bmap_flags
= VNODE_READ
;
760 bmap_flags
= VNODE_WRITE
;
765 * this is unexepected, but we'll allow for it
767 bzero((caddr_t
)io_bp
->b_datap
, (int)io_contig_bytes
);
769 io_bp
->b_bcount
= io_contig_bytes
;
770 io_bp
->b_bufsize
= io_contig_bytes
;
771 io_bp
->b_resid
= io_contig_bytes
;
772 io_bp
->b_blkno
= io_blkno
;
774 buf_reset(io_bp
, io_direction
);
776 * Call the device to do the I/O and wait for it
778 if ((error
= VNOP_STRATEGY(io_bp
)))
780 if ((error
= (int)buf_biowait(io_bp
)))
782 if (io_bp
->b_resid
) {
783 io_resid
-= (io_contig_bytes
- io_bp
->b_resid
);
787 if ((io_resid
-= io_contig_bytes
) == 0)
789 f_offset
+= io_contig_bytes
;
790 io_bp
->b_datap
+= io_contig_bytes
;
793 * Map the current position to a physical block number
795 if ((error
= VNOP_BLOCKMAP(vp
, f_offset
, io_resid
, &io_blkno
, &io_contig_bytes
, NULL
, bmap_flags
, NULL
)))
801 buf_seterror(bp
, error
);
802 bp
->b_resid
= io_resid
;
804 * This I/O is now complete
813 * struct vnop_strategy_args {
818 buf_strategy(vnode_t devvp
, void *ap
)
820 buf_t bp
= ((struct vnop_strategy_args
*)ap
)->a_bp
;
821 vnode_t vp
= bp
->b_vp
;
825 if (vp
== NULL
|| vp
->v_type
== VCHR
|| vp
->v_type
== VBLK
)
826 panic("buf_strategy: b_vp == NULL || vtype == VCHR | VBLK\n");
828 * associate the physical device with
829 * with this buf_t even if we don't
830 * end up issuing the I/O...
832 bp
->b_dev
= devvp
->v_rdev
;
834 if (bp
->b_flags
& B_READ
)
835 bmap_flags
= VNODE_READ
;
837 bmap_flags
= VNODE_WRITE
;
839 if ( !(bp
->b_flags
& B_CLUSTER
)) {
843 * we have a UPL associated with this bp
844 * go through cluster_bp which knows how
845 * to deal with filesystem block sizes
846 * that aren't equal to the page size
848 return (cluster_bp(bp
));
850 if (bp
->b_blkno
== bp
->b_lblkno
) {
854 if ((error
= VNOP_BLKTOOFF(vp
, bp
->b_lblkno
, &f_offset
))) {
855 buf_seterror(bp
, error
);
860 if ((error
= VNOP_BLOCKMAP(vp
, f_offset
, bp
->b_bcount
, &bp
->b_blkno
, &contig_bytes
, NULL
, bmap_flags
, NULL
))) {
861 buf_seterror(bp
, error
);
866 if (bp
->b_blkno
== -1)
868 else if ((long)contig_bytes
< bp
->b_bcount
)
869 return (buf_strategy_fragmented(devvp
, bp
, f_offset
, contig_bytes
));
871 if (bp
->b_blkno
== -1) {
877 * we can issue the I/O because...
878 * either B_CLUSTER is set which
879 * means that the I/O is properly set
880 * up to be a multiple of the page size, or
881 * we were able to successfully set up the
882 * phsyical block mapping
884 return (VOCALL(devvp
->v_op
, VOFFSET(vnop_strategy
), ap
));
890 buf_alloc(vnode_t vp
)
892 return(alloc_io_buf(vp
, 0));
904 buf_iterate(vnode_t vp
, int (*callout
)(buf_t
, void *), int flags
, void *arg
) {
907 struct buflists local_iterblkhd
;
908 int lock_flags
= BAC_NOWAIT
| BAC_REMOVE
;
910 if (flags
& BUF_SKIP_LOCKED
)
911 lock_flags
|= BAC_SKIP_LOCKED
;
912 if (flags
& BUF_SKIP_NONLOCKED
)
913 lock_flags
|= BAC_SKIP_NONLOCKED
;
915 lck_mtx_lock(buf_mtxp
);
917 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_DIRTY
)) {
918 lck_mtx_unlock(buf_mtxp
);
921 while (!LIST_EMPTY(&local_iterblkhd
)) {
922 bp
= LIST_FIRST(&local_iterblkhd
);
923 LIST_REMOVE(bp
, b_vnbufs
);
924 LIST_INSERT_HEAD(&vp
->v_dirtyblkhd
, bp
, b_vnbufs
);
926 if (buf_acquire_locked(bp
, lock_flags
, 0, 0))
929 lck_mtx_unlock(buf_mtxp
);
931 retval
= callout(bp
, arg
);
939 case BUF_RETURNED_DONE
:
941 lck_mtx_lock(buf_mtxp
);
943 case BUF_CLAIMED_DONE
:
944 lck_mtx_lock(buf_mtxp
);
947 lck_mtx_lock(buf_mtxp
);
950 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
952 lck_mtx_unlock(buf_mtxp
);
957 * Flush out and invalidate all buffers associated with a vnode.
960 buf_invalidateblks(vnode_t vp
, int flags
, int slpflag
, int slptimeo
)
965 struct buflists local_iterblkhd
;
967 lck_mtx_lock(buf_mtxp
);
970 if (must_rescan
== 0)
972 * the lists may not be empty, but all that's left at this
973 * point are metadata or B_LOCKED buffers which are being
974 * skipped... we know this because we made it through both
975 * the clean and dirty lists without dropping buf_mtxp...
976 * each time we drop buf_mtxp we bump "must_rescan"
979 if (LIST_EMPTY(&vp
->v_cleanblkhd
) && LIST_EMPTY(&vp
->v_dirtyblkhd
))
983 * iterate the clean list
985 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_CLEAN
)) {
988 while (!LIST_EMPTY(&local_iterblkhd
)) {
989 bp
= LIST_FIRST(&local_iterblkhd
);
991 LIST_REMOVE(bp
, b_vnbufs
);
992 LIST_INSERT_HEAD(&vp
->v_cleanblkhd
, bp
, b_vnbufs
);
995 * some filesystems distinguish meta data blocks with a negative logical block #
997 if ((flags
& BUF_SKIP_META
) && (bp
->b_lblkno
< 0 || ISSET(bp
->b_flags
, B_META
)))
1000 if ( (error
= (int)buf_acquire_locked(bp
, BAC_REMOVE
| BAC_SKIP_LOCKED
, slpflag
, slptimeo
)) ) {
1001 if (error
== EDEADLK
)
1003 * this buffer was marked B_LOCKED...
1004 * we didn't drop buf_mtxp, so we
1005 * we don't need to rescan
1008 if (error
== EAGAIN
) {
1010 * found a busy buffer... we blocked and
1011 * dropped buf_mtxp, so we're going to
1012 * need to rescan after this pass is completed
1018 * got some kind of 'real' error out of the msleep
1019 * in buf_acquire_locked, terminate the scan and return the error
1021 buf_itercomplete(vp
, &local_iterblkhd
, VBI_CLEAN
);
1023 lck_mtx_unlock(buf_mtxp
);
1026 lck_mtx_unlock(buf_mtxp
);
1028 SET(bp
->b_flags
, B_INVAL
);
1031 lck_mtx_lock(buf_mtxp
);
1034 * by dropping buf_mtxp, we allow new
1035 * buffers to be added to the vnode list(s)
1036 * we'll have to rescan at least once more
1037 * if the queues aren't empty
1041 buf_itercomplete(vp
, &local_iterblkhd
, VBI_CLEAN
);
1045 * Now iterate on dirty blks
1047 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_DIRTY
)) {
1050 while (!LIST_EMPTY(&local_iterblkhd
)) {
1051 bp
= LIST_FIRST(&local_iterblkhd
);
1053 LIST_REMOVE(bp
, b_vnbufs
);
1054 LIST_INSERT_HEAD(&vp
->v_dirtyblkhd
, bp
, b_vnbufs
);
1057 * some filesystems distinguish meta data blocks with a negative logical block #
1059 if ((flags
& BUF_SKIP_META
) && (bp
->b_lblkno
< 0 || ISSET(bp
->b_flags
, B_META
)))
1062 if ( (error
= (int)buf_acquire_locked(bp
, BAC_REMOVE
| BAC_SKIP_LOCKED
, slpflag
, slptimeo
)) ) {
1063 if (error
== EDEADLK
)
1065 * this buffer was marked B_LOCKED...
1066 * we didn't drop buf_mtxp, so we
1067 * we don't need to rescan
1070 if (error
== EAGAIN
) {
1072 * found a busy buffer... we blocked and
1073 * dropped buf_mtxp, so we're going to
1074 * need to rescan after this pass is completed
1080 * got some kind of 'real' error out of the msleep
1081 * in buf_acquire_locked, terminate the scan and return the error
1083 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1085 lck_mtx_unlock(buf_mtxp
);
1088 lck_mtx_unlock(buf_mtxp
);
1090 SET(bp
->b_flags
, B_INVAL
);
1092 if (ISSET(bp
->b_flags
, B_DELWRI
) && (flags
& BUF_WRITE_DATA
))
1093 (void) VNOP_BWRITE(bp
);
1097 lck_mtx_lock(buf_mtxp
);
1099 * by dropping buf_mtxp, we allow new
1100 * buffers to be added to the vnode list(s)
1101 * we'll have to rescan at least once more
1102 * if the queues aren't empty
1106 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1108 lck_mtx_unlock(buf_mtxp
);
1114 buf_flushdirtyblks(vnode_t vp
, int wait
, int flags
, char *msg
) {
1116 int writes_issued
= 0;
1119 struct buflists local_iterblkhd
;
1120 int lock_flags
= BAC_NOWAIT
| BAC_REMOVE
;
1122 if (flags
& BUF_SKIP_LOCKED
)
1123 lock_flags
|= BAC_SKIP_LOCKED
;
1124 if (flags
& BUF_SKIP_NONLOCKED
)
1125 lock_flags
|= BAC_SKIP_NONLOCKED
;
1127 lck_mtx_lock(buf_mtxp
);
1129 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_DIRTY
) == 0) {
1130 while (!LIST_EMPTY(&local_iterblkhd
)) {
1131 bp
= LIST_FIRST(&local_iterblkhd
);
1132 LIST_REMOVE(bp
, b_vnbufs
);
1133 LIST_INSERT_HEAD(&vp
->v_dirtyblkhd
, bp
, b_vnbufs
);
1135 if ((error
= buf_acquire_locked(bp
, lock_flags
, 0, 0)) == EBUSY
)
1139 lck_mtx_unlock(buf_mtxp
);
1141 bp
->b_flags
&= ~B_LOCKED
;
1144 * Wait for I/O associated with indirect blocks to complete,
1145 * since there is no way to quickly wait for them below.
1147 if ((bp
->b_vp
== vp
) || (wait
== 0))
1148 (void) buf_bawrite(bp
);
1150 (void) VNOP_BWRITE(bp
);
1153 lck_mtx_lock(buf_mtxp
);
1155 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1157 lck_mtx_unlock(buf_mtxp
);
1160 (void)vnode_waitforwrites(vp
, 0, 0, 0, msg
);
1162 if (vp
->v_dirtyblkhd
.lh_first
&& busy
) {
1164 * we had one or more BUSY buffers on
1165 * the dirtyblock list... most likely
1166 * these are due to delayed writes that
1167 * were moved to the bclean queue but
1168 * have not yet been 'written'.
1169 * if we issued some writes on the
1170 * previous pass, we try again immediately
1171 * if we didn't, we'll sleep for some time
1172 * to allow the state to change...
1174 if (writes_issued
== 0) {
1175 (void)tsleep((caddr_t
)&vp
->v_numoutput
,
1176 PRIBIO
+ 1, "vnode_flushdirtyblks", hz
/20);
1188 * called with buf_mtxp held...
1189 * this lock protects the queue manipulation
1192 buf_iterprepare(vnode_t vp
, struct buflists
*iterheadp
, int flags
)
1194 struct buflists
* listheadp
;
1196 if (flags
& VBI_DIRTY
)
1197 listheadp
= &vp
->v_dirtyblkhd
;
1199 listheadp
= &vp
->v_cleanblkhd
;
1201 while (vp
->v_iterblkflags
& VBI_ITER
) {
1202 vp
->v_iterblkflags
|= VBI_ITERWANT
;
1203 msleep(&vp
->v_iterblkflags
, buf_mtxp
, 0, "buf_iterprepare", 0);
1205 if (LIST_EMPTY(listheadp
)) {
1206 LIST_INIT(iterheadp
);
1209 vp
->v_iterblkflags
|= VBI_ITER
;
1211 iterheadp
->lh_first
= listheadp
->lh_first
;
1212 listheadp
->lh_first
->b_vnbufs
.le_prev
= &iterheadp
->lh_first
;
1213 LIST_INIT(listheadp
);
1219 * called with buf_mtxp held...
1220 * this lock protects the queue manipulation
1223 buf_itercomplete(vnode_t vp
, struct buflists
*iterheadp
, int flags
)
1225 struct buflists
* listheadp
;
1228 if (flags
& VBI_DIRTY
)
1229 listheadp
= &vp
->v_dirtyblkhd
;
1231 listheadp
= &vp
->v_cleanblkhd
;
1233 while (!LIST_EMPTY(iterheadp
)) {
1234 bp
= LIST_FIRST(iterheadp
);
1235 LIST_REMOVE(bp
, b_vnbufs
);
1236 LIST_INSERT_HEAD(listheadp
, bp
, b_vnbufs
);
1238 vp
->v_iterblkflags
&= ~VBI_ITER
;
1240 if (vp
->v_iterblkflags
& VBI_ITERWANT
) {
1241 vp
->v_iterblkflags
&= ~VBI_ITERWANT
;
1242 wakeup(&vp
->v_iterblkflags
);
1248 bremfree_locked(buf_t bp
)
1250 struct bqueues
*dp
= NULL
;
1254 * We only calculate the head of the freelist when removing
1255 * the last element of the list as that is the only time that
1256 * it is needed (e.g. to reset the tail pointer).
1258 * NB: This makes an assumption about how tailq's are implemented.
1260 if (bp
->b_freelist
.tqe_next
== NULL
) {
1261 for (dp
= bufqueues
; dp
< &bufqueues
[BQUEUES
]; dp
++)
1262 if (dp
->tqh_last
== &bp
->b_freelist
.tqe_next
)
1264 if (dp
== &bufqueues
[BQUEUES
])
1265 panic("bremfree: lost tail");
1267 TAILQ_REMOVE(dp
, bp
, b_freelist
);
1268 whichq
= bp
->b_whichq
;
1273 bp
->b_timestamp
= 0;
1277 * Associate a buffer with a vnode.
1280 bgetvp(vnode_t vp
, buf_t bp
)
1284 panic("bgetvp: not free");
1286 if (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
)
1287 bp
->b_dev
= vp
->v_rdev
;
1291 * Insert onto list for new vnode.
1293 lck_mtx_lock(buf_mtxp
);
1294 bufinsvn(bp
, &vp
->v_cleanblkhd
);
1295 lck_mtx_unlock(buf_mtxp
);
1299 * Disassociate a buffer from a vnode.
1306 if ((vp
= bp
->b_vp
) == (vnode_t
)NULL
)
1307 panic("brelvp: NULL vp");
1309 * Delete from old vnode list, if on one.
1311 lck_mtx_lock(buf_mtxp
);
1312 if (bp
->b_vnbufs
.le_next
!= NOLIST
)
1314 lck_mtx_unlock(buf_mtxp
);
1316 bp
->b_vp
= (vnode_t
)NULL
;
1320 * Reassign a buffer from one vnode to another.
1321 * Used to assign file specific control information
1322 * (indirect blocks) to the vnode to which they belong.
1325 buf_reassign(buf_t bp
, vnode_t newvp
)
1327 register struct buflists
*listheadp
;
1329 if (newvp
== NULL
) {
1330 printf("buf_reassign: NULL");
1333 lck_mtx_lock(buf_mtxp
);
1336 * Delete from old vnode list, if on one.
1338 if (bp
->b_vnbufs
.le_next
!= NOLIST
)
1341 * If dirty, put on list of dirty buffers;
1342 * otherwise insert onto list of clean buffers.
1344 if (ISSET(bp
->b_flags
, B_DELWRI
))
1345 listheadp
= &newvp
->v_dirtyblkhd
;
1347 listheadp
= &newvp
->v_cleanblkhd
;
1348 bufinsvn(bp
, listheadp
);
1350 lck_mtx_unlock(buf_mtxp
);
1353 static __inline__
void
1354 bufhdrinit(buf_t bp
)
1356 bzero((char *)bp
, sizeof *bp
);
1358 bp
->b_rcred
= NOCRED
;
1359 bp
->b_wcred
= NOCRED
;
1360 bp
->b_vnbufs
.le_next
= NOLIST
;
1361 bp
->b_flags
= B_INVAL
;
1367 * Initialize buffers and hash links for buffers.
1369 __private_extern__
void
1379 /* Initialize the buffer queues ('freelists') and the hash table */
1380 for (dp
= bufqueues
; dp
< &bufqueues
[BQUEUES
]; dp
++)
1382 bufhashtbl
= hashinit(nbuf_hashelements
, M_CACHE
, &bufhash
);
1384 metabuf
= max_nbuf_headers
/8; /* reserved for meta buf */
1386 /* Initialize the buffer headers */
1387 for (i
= 0; i
< max_nbuf_headers
; 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
);
1409 for (; i
< nbuf
+ niobuf
; i
++) {
1412 binsheadfree(bp
, &iobufqueue
, -1);
1416 * allocate lock group attribute and group
1418 buf_mtx_grp_attr
= lck_grp_attr_alloc_init();
1419 buf_mtx_grp
= lck_grp_alloc_init("buffer cache", buf_mtx_grp_attr
);
1422 * allocate the lock attribute
1424 buf_mtx_attr
= lck_attr_alloc_init();
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 (IS_VALID_CRED(cred
) && !IS_VALID_CRED(bp
->b_rcred
)) {
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_wired(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_wired(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_wired(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
))
2576 /* need to grow number of bufs, add another one rather than recycling */
2577 if (nbuf
< max_nbuf_headers
) {
2579 * Increment count now as lock
2580 * is dropped for allocation.
2581 * That avoids over commits
2588 * (*queue == BQUEUES) means no preference
2590 if (*queue
!= BQUEUES
) {
2591 /* Try for the requested queue first */
2592 bp
= bufqueues
[*queue
].tqh_first
;
2597 /* Unable to use requested queue */
2598 age_bp
= bufqueues
[BQ_AGE
].tqh_first
;
2599 lru_bp
= bufqueues
[BQ_LRU
].tqh_first
;
2600 meta_bp
= bufqueues
[BQ_META
].tqh_first
;
2602 if (!age_bp
&& !lru_bp
&& !meta_bp
) {
2604 * Unavailble on AGE or LRU or META queues
2605 * Try the empty list first
2607 bp
= bufqueues
[BQ_EMPTY
].tqh_first
;
2613 * We have seen is this is hard to trigger.
2614 * This is an overcommit of nbufs but needed
2615 * in some scenarios with diskiamges
2619 lck_mtx_unlock(buf_mtxp
);
2621 /* Create a new temporary buffer header */
2622 bp
= (struct buf
*)zalloc(buf_hdr_zone
);
2624 lck_mtx_lock(buf_mtxp
);
2629 binshash(bp
, &invalhash
);
2630 SET(bp
->b_flags
, B_HDRALLOC
);
2632 binsheadfree(bp
, &bufqueues
[BQ_EMPTY
], BQ_EMPTY
);
2636 /* subtract already accounted bufcount */
2639 bufstats
.bufs_sleeps
++;
2641 /* wait for a free buffer of any kind */
2643 /* hz value is 100 */
2644 ts
.tv_sec
= (slptimeo
/1000);
2645 /* the hz value is 100; which leads to 10ms */
2646 ts
.tv_nsec
= (slptimeo
% 1000) * NSEC_PER_USEC
* 1000 * 10;
2647 msleep(&needbuffer
, buf_mtxp
, slpflag
|(PRIBIO
+1), (char *)"getnewbuf", &ts
);
2651 /* Buffer available either on AGE or LRU or META */
2655 /* Buffer available either on AGE or LRU */
2659 } else if (!lru_bp
) {
2662 } else { /* buffer available on both AGE and LRU */
2663 int t
= buf_timestamp();
2665 age_time
= t
- age_bp
->b_timestamp
;
2666 lru_time
= t
- lru_bp
->b_timestamp
;
2667 if ((age_time
< 0) || (lru_time
< 0)) { /* time set backwards */
2671 * we should probably re-timestamp eveything in the
2672 * queues at this point with the current time
2675 if ((lru_time
>= lru_is_stale
) && (age_time
< age_is_stale
)) {
2685 if (!bp
) { /* Neither on AGE nor on LRU */
2688 } else if (meta_bp
) {
2689 int t
= buf_timestamp();
2691 bp_time
= t
- bp
->b_timestamp
;
2692 meta_time
= t
- meta_bp
->b_timestamp
;
2694 if (!(bp_time
< 0) && !(meta_time
< 0)) {
2695 /* time not set backwards */
2697 bp_is_stale
= (*queue
== BQ_LRU
) ?
2698 lru_is_stale
: age_is_stale
;
2700 if ((meta_time
>= meta_is_stale
) &&
2701 (bp_time
< bp_is_stale
)) {
2708 if (ISSET(bp
->b_flags
, B_LOCKED
) || ISSET(bp
->b_lflags
, BL_BUSY
))
2709 panic("getnewbuf: bp @ 0x%x is LOCKED or BUSY! (flags 0x%x)\n", bp
, bp
->b_flags
);
2712 if (bcleanbuf(bp
)) {
2714 * moved to the laundry thread, buffer not ready
2725 * Returns 0 is buffer is ready to use,
2726 * Returns 1 if issued a buf_bawrite() to indicate
2727 * that the buffer is not ready.
2729 * buf_mtxp is held upon entry
2730 * returns with buf_mtxp locked
2735 /* Remove from the queue */
2736 bremfree_locked(bp
);
2738 /* Buffer is no longer on free lists. */
2739 SET(bp
->b_lflags
, BL_BUSY
);
2741 bp
->b_owner
= current_thread();
2745 * If buffer was a delayed write, start the IO by queuing
2746 * it on the LAUNDRY queue, and return 1
2748 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
2749 binstailfree(bp
, &bufqueues
[BQ_LAUNDRY
], BQ_LAUNDRY
);
2752 lck_mtx_unlock(buf_mtxp
);
2754 wakeup(&blaundrycnt
);
2755 /* and give it a chance to run */
2756 (void)thread_block(THREAD_CONTINUE_NULL
);
2758 lck_mtx_lock(buf_mtxp
);
2763 lck_mtx_unlock(buf_mtxp
);
2767 * disassociate us from our vnode, if we had one...
2772 if (ISSET(bp
->b_flags
, B_META
)) {
2775 elem
= (vm_offset_t
)bp
->b_datap
;
2776 bp
->b_datap
= (uintptr_t)0xdeadbeef;
2778 if (ISSET(bp
->b_flags
, B_ZALLOC
)) {
2781 z
= getbufzone(bp
->b_bufsize
);
2782 zfree(z
, (void *)elem
);
2784 kmem_free(kernel_map
, elem
, bp
->b_bufsize
);
2787 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
2789 /* clear out various other fields */
2791 bp
->b_datap
= (uintptr_t)NULL
;
2792 bp
->b_upl
= (void *)NULL
;
2794 * preserve the state of whether this buffer
2795 * was allocated on the fly or not...
2796 * the only other flag that should be set at
2797 * this point is BL_BUSY...
2800 bp
->b_owner
= current_thread();
2803 bp
->b_lflags
= BL_BUSY
;
2804 bp
->b_flags
= (bp
->b_flags
& B_HDRALLOC
);
2806 bp
->b_blkno
= bp
->b_lblkno
= 0;
2807 bp
->b_iodone
= NULL
;
2811 bp
->b_dirtyoff
= bp
->b_dirtyend
= 0;
2812 bp
->b_validoff
= bp
->b_validend
= 0;
2814 /* nuke any credentials we were holding */
2815 if (IS_VALID_CRED(bp
->b_rcred
)) {
2816 kauth_cred_unref(&bp
->b_rcred
);
2818 if (IS_VALID_CRED(bp
->b_wcred
)) {
2819 kauth_cred_unref(&bp
->b_wcred
);
2821 lck_mtx_lock(buf_mtxp
);
2829 buf_invalblkno(vnode_t vp
, daddr64_t lblkno
, int flags
)
2834 lck_mtx_lock(buf_mtxp
);
2836 if ((bp
= incore_locked(vp
, lblkno
)) == (struct buf
*)0) {
2837 lck_mtx_unlock(buf_mtxp
);
2840 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
2841 if ( !ISSET(flags
, BUF_WAIT
)) {
2842 lck_mtx_unlock(buf_mtxp
);
2845 SET(bp
->b_lflags
, BL_WANTED
);
2847 error
= msleep((caddr_t
)bp
, buf_mtxp
, (PRIBIO
+ 1), (char *)"buf_invalblkno", 0);
2853 bremfree_locked(bp
);
2854 SET(bp
->b_lflags
, BL_BUSY
);
2855 SET(bp
->b_flags
, B_INVAL
);
2857 bp
->b_owner
= current_thread();
2860 lck_mtx_unlock(buf_mtxp
);
2870 int need_wakeup
= 0;
2872 lck_mtx_lock(buf_mtxp
);
2874 if (ISSET(bp
->b_lflags
, BL_WANTED
)) {
2876 * delay the actual wakeup until after we
2877 * clear BL_BUSY and we've dropped buf_mtxp
2882 * Unlock the buffer.
2884 CLR(bp
->b_lflags
, (BL_BUSY
| BL_WANTED
));
2886 lck_mtx_unlock(buf_mtxp
);
2890 * Wake up any proceeses waiting for _this_ buffer to become free.
2898 buf_acquire(buf_t bp
, int flags
, int slpflag
, int slptimeo
) {
2901 lck_mtx_lock(buf_mtxp
);
2903 error
= buf_acquire_locked(bp
, flags
, slpflag
, slptimeo
);
2905 lck_mtx_unlock(buf_mtxp
);
2912 buf_acquire_locked(buf_t bp
, int flags
, int slpflag
, int slptimeo
)
2917 if (ISSET(bp
->b_flags
, B_LOCKED
)) {
2918 if ((flags
& BAC_SKIP_LOCKED
))
2921 if ((flags
& BAC_SKIP_NONLOCKED
))
2924 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
2926 * since the mutex_lock may block, the buffer
2927 * may become BUSY, so we need to
2928 * recheck for a NOWAIT request
2930 if (flags
& BAC_NOWAIT
)
2932 SET(bp
->b_lflags
, BL_WANTED
);
2934 /* the hz value is 100; which leads to 10ms */
2935 ts
.tv_sec
= (slptimeo
/100);
2936 ts
.tv_nsec
= (slptimeo
% 100) * 10 * NSEC_PER_USEC
* 1000;
2937 error
= msleep((caddr_t
)bp
, buf_mtxp
, slpflag
| (PRIBIO
+ 1), (char *)"buf_acquire", &ts
);
2943 if (flags
& BAC_REMOVE
)
2944 bremfree_locked(bp
);
2945 SET(bp
->b_lflags
, BL_BUSY
);
2947 bp
->b_owner
= current_thread();
2955 * Wait for operations on the buffer to complete.
2956 * When they do, extract and return the I/O's error value.
2959 buf_biowait(buf_t bp
)
2961 lck_mtx_lock(buf_mtxp
);
2963 while (!ISSET(bp
->b_flags
, B_DONE
))
2964 (void) msleep(bp
, buf_mtxp
, (PRIBIO
+1), (char *)"buf_biowait", 0);
2966 lck_mtx_unlock(buf_mtxp
);
2968 /* check for interruption of I/O (e.g. via NFS), then errors. */
2969 if (ISSET(bp
->b_flags
, B_EINTR
)) {
2970 CLR(bp
->b_flags
, B_EINTR
);
2972 } else if (ISSET(bp
->b_flags
, B_ERROR
))
2973 return (bp
->b_error
? bp
->b_error
: EIO
);
2979 * Mark I/O complete on a buffer.
2981 * If a callback has been requested, e.g. the pageout
2982 * daemon, do so. Otherwise, awaken waiting processes.
2984 * [ Leffler, et al., says on p.247:
2985 * "This routine wakes up the blocked process, frees the buffer
2986 * for an asynchronous write, or, for a request by the pagedaemon
2987 * process, invokes a procedure specified in the buffer structure" ]
2989 * In real life, the pagedaemon (or other system processes) wants
2990 * to do async stuff to, and doesn't want the buffer buf_brelse()'d.
2991 * (for swap pager, that puts swap buffers on the free lists (!!!),
2992 * for the vn device, that puts malloc'd buffers on the free lists!)
2994 extern struct timeval priority_IO_timestamp_for_root
;
2995 extern int hard_throttle_on_root
;
2998 buf_biodone(buf_t bp
)
3000 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 387)) | DBG_FUNC_START
,
3001 (int)bp
, (int)bp
->b_datap
, bp
->b_flags
, 0, 0);
3003 if (ISSET(bp
->b_flags
, B_DONE
))
3004 panic("biodone already");
3006 if (kdebug_enable
) {
3007 int code
= DKIO_DONE
;
3009 if (bp
->b_flags
& B_READ
)
3011 if (bp
->b_flags
& B_ASYNC
)
3014 if (bp
->b_flags
& B_META
)
3016 else if (bp
->b_flags
& B_PAGEIO
)
3017 code
|= DKIO_PAGING
;
3019 KERNEL_DEBUG_CONSTANT(FSDBG_CODE(DBG_DKRW
, code
) | DBG_FUNC_NONE
,
3020 (unsigned int)bp
, (unsigned int)bp
->b_vp
,
3021 bp
->b_resid
, bp
->b_error
, 0);
3023 if ((bp
->b_vp
!= NULLVP
) &&
3024 ((bp
->b_flags
& (B_PAGEIO
| B_READ
)) == (B_PAGEIO
| B_READ
)) &&
3025 (bp
->b_vp
->v_mount
->mnt_kern_flag
& MNTK_ROOTDEV
)) {
3026 microuptime(&priority_IO_timestamp_for_root
);
3027 hard_throttle_on_root
= 0;
3030 * I/O was done, so don't believe
3031 * the DIRTY state from VM anymore
3033 CLR(bp
->b_flags
, B_WASDIRTY
);
3035 if (!ISSET(bp
->b_flags
, B_READ
) && !ISSET(bp
->b_flags
, B_RAW
))
3037 * wake up any writer's blocked
3038 * on throttle or waiting for I/O
3041 vnode_writedone(bp
->b_vp
);
3043 if (ISSET(bp
->b_flags
, (B_CALL
| B_FILTER
))) { /* if necessary, call out */
3044 void (*iodone_func
)(struct buf
*, void *) = bp
->b_iodone
;
3045 void *arg
= (void *)bp
->b_transaction
;
3046 int callout
= ISSET(bp
->b_flags
, B_CALL
);
3048 CLR(bp
->b_flags
, (B_CALL
| B_FILTER
)); /* filters and callouts are one-shot */
3049 bp
->b_iodone
= NULL
;
3050 bp
->b_transaction
= NULL
;
3052 if (iodone_func
== NULL
) {
3053 panic("biodone: bp @ 0x%x has NULL b_iodone!\n", bp
);
3056 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
3057 (*iodone_func
)(bp
, arg
);
3061 * assumes that the call back function takes
3062 * ownership of the bp and deals with releasing it if necessary
3066 * in this case the call back function is acting
3067 * strictly as a filter... it does not take
3068 * ownership of the bp and is expecting us
3069 * to finish cleaning up... this is currently used
3070 * by the HFS journaling code
3073 if (ISSET(bp
->b_flags
, B_ASYNC
)) { /* if async, release it */
3074 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
3077 } else { /* or just wakeup the buffer */
3079 * by taking the mutex, we serialize
3080 * the buf owner calling buf_biowait so that we'll
3081 * only see him in one of 2 states...
3082 * state 1: B_DONE wasn't set and he's
3084 * state 2: he's blocked trying to take the
3085 * mutex before looking at B_DONE
3086 * BL_WANTED is cleared in case anyone else
3087 * is blocked waiting for the buffer... note
3088 * that we haven't cleared B_BUSY yet, so if
3089 * they do get to run, their going to re-set
3090 * BL_WANTED and go back to sleep
3092 lck_mtx_lock(buf_mtxp
);
3094 CLR(bp
->b_lflags
, BL_WANTED
);
3095 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
3097 lck_mtx_unlock(buf_mtxp
);
3102 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 387)) | DBG_FUNC_END
,
3103 (int)bp
, (int)bp
->b_datap
, bp
->b_flags
, 0, 0);
3107 * Return a count of buffers on the "locked" queue.
3110 count_lock_queue(void)
3115 lck_mtx_lock(buf_mtxp
);
3117 for (bp
= bufqueues
[BQ_LOCKED
].tqh_first
; bp
;
3118 bp
= bp
->b_freelist
.tqe_next
)
3120 lck_mtx_unlock(buf_mtxp
);
3126 * Return a count of 'busy' buffers. Used at the time of shutdown.
3129 count_busy_buffers(void)
3134 lck_mtx_lock(buf_mtxp
);
3135 for (bp
= &buf
[boot_nbuf
]; --bp
>= buf
; )
3136 if (!ISSET(bp
->b_flags
, B_INVAL
) && ISSET(bp
->b_lflags
, BL_BUSY
))
3138 lck_mtx_unlock(buf_mtxp
);
3145 * Print out statistics on the current allocation of the buffer pool.
3146 * Can be enabled to print out on every ``sync'' by setting "syncprt"
3147 * in vfs_syscalls.c using sysctl.
3153 register struct buf
*bp
;
3154 register struct bqueues
*dp
;
3155 int counts
[MAXBSIZE
/CLBYTES
+1];
3156 static char *bname
[BQUEUES
] =
3157 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
3159 for (dp
= bufqueues
, i
= 0; dp
< &bufqueues
[BQUEUES
]; dp
++, i
++) {
3161 for (j
= 0; j
<= MAXBSIZE
/CLBYTES
; j
++)
3164 lck_mtx_lock(buf_mtxp
);
3166 for (bp
= dp
->tqh_first
; bp
; bp
= bp
->b_freelist
.tqe_next
) {
3167 counts
[bp
->b_bufsize
/CLBYTES
]++;
3170 lck_mtx_unlock(buf_mtxp
);
3172 printf("%s: total-%d", bname
[i
], count
);
3173 for (j
= 0; j
<= MAXBSIZE
/CLBYTES
; j
++)
3175 printf(", %d-%d", j
* CLBYTES
, counts
[j
]);
3179 #endif /* DIAGNOSTIC */
3181 #define NRESERVEDIOBUFS 64
3185 alloc_io_buf(vnode_t vp
, int priv
)
3189 lck_mtx_lock(iobuffer_mtxp
);
3191 while (((niobuf
- NRESERVEDIOBUFS
< bufstats
.bufs_iobufinuse
) && !priv
) ||
3192 (bp
= iobufqueue
.tqh_first
) == NULL
) {
3193 bufstats
.bufs_iobufsleeps
++;
3196 (void) msleep(&need_iobuffer
, iobuffer_mtxp
, (PRIBIO
+1), (const char *)"alloc_io_buf", 0);
3198 TAILQ_REMOVE(&iobufqueue
, bp
, b_freelist
);
3200 bufstats
.bufs_iobufinuse
++;
3201 if (bufstats
.bufs_iobufinuse
> bufstats
.bufs_iobufmax
)
3202 bufstats
.bufs_iobufmax
= bufstats
.bufs_iobufinuse
;
3204 lck_mtx_unlock(iobuffer_mtxp
);
3207 * initialize various fields
3208 * we don't need to hold the mutex since the buffer
3209 * is now private... the vp should have a reference
3210 * on it and is not protected by this mutex in any event
3212 bp
->b_timestamp
= 0;
3217 bp
->b_lflags
= BL_BUSY
| BL_IOBUF
;
3218 bp
->b_blkno
= bp
->b_lblkno
= 0;
3220 bp
->b_owner
= current_thread();
3223 bp
->b_iodone
= NULL
;
3231 if (vp
&& (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
))
3232 bp
->b_dev
= vp
->v_rdev
;
3241 free_io_buf(buf_t bp
)
3243 int need_wakeup
= 0;
3246 * put buffer back on the head of the iobufqueue
3249 bp
->b_flags
= B_INVAL
;
3251 lck_mtx_lock(iobuffer_mtxp
);
3253 binsheadfree(bp
, &iobufqueue
, -1);
3255 if (need_iobuffer
) {
3257 * Wake up any processes waiting because they need an io buffer
3259 * do the wakeup after we drop the mutex... it's possible that the
3260 * wakeup will be superfluous if need_iobuffer gets set again and
3261 * another thread runs this path, but it's highly unlikely, doesn't
3262 * hurt, and it means we don't hold up I/O progress if the wakeup blocks
3263 * trying to grab a task related lock...
3268 bufstats
.bufs_iobufinuse
--;
3270 lck_mtx_unlock(iobuffer_mtxp
);
3273 wakeup(&need_iobuffer
);
3279 * If getnewbuf() calls bcleanbuf() on the same thread
3280 * there is a potential for stack overrun and deadlocks.
3281 * So we always handoff the work to a worker thread for completion
3283 #include <mach/mach_types.h>
3284 #include <mach/memory_object_types.h>
3285 #include <kern/sched_prim.h>
3289 bcleanbuf_thread_init(void)
3291 /* create worker thread */
3292 kernel_thread(kernel_task
, bcleanbuf_thread
);
3296 bcleanbuf_thread(void)
3303 lck_mtx_lock(buf_mtxp
);
3305 while (blaundrycnt
== 0)
3306 (void)msleep((void *)&blaundrycnt
, buf_mtxp
, PRIBIO
, "blaundry", 0);
3308 bp
= TAILQ_FIRST(&bufqueues
[BQ_LAUNDRY
]);
3310 * Remove from the queue
3312 bremfree_locked(bp
);
3315 lck_mtx_unlock(buf_mtxp
);
3319 error
= bawrite_internal(bp
, 0);
3322 lck_mtx_lock(buf_mtxp
);
3324 binstailfree(bp
, &bufqueues
[BQ_LAUNDRY
], BQ_LAUNDRY
);
3327 lck_mtx_unlock(buf_mtxp
);
3330 (void)tsleep((void *)&blaundrycnt
, PRIBIO
, "blaundry", 1);
3333 (void)thread_block(THREAD_CONTINUE_NULL
);
3342 brecover_data(buf_t bp
)
3346 upl_page_info_t
*pl
;
3348 vnode_t vp
= bp
->b_vp
;
3352 if ( !UBCINFOEXISTS(vp
) || bp
->b_bufsize
== 0)
3355 upl_flags
= UPL_PRECIOUS
;
3356 if (! (buf_flags(bp
) & B_READ
)) {
3358 * "write" operation: let the UPL subsystem know
3359 * that we intend to modify the buffer cache pages we're
3362 upl_flags
|= UPL_WILL_MODIFY
;
3365 kret
= ubc_create_upl(vp
,
3366 ubc_blktooff(vp
, bp
->b_lblkno
),
3371 if (kret
!= KERN_SUCCESS
)
3372 panic("Failed to create UPL");
3374 for (upl_offset
= 0; upl_offset
< bp
->b_bufsize
; upl_offset
+= PAGE_SIZE
) {
3376 if (!upl_valid_page(pl
, upl_offset
/ PAGE_SIZE
) || !upl_dirty_page(pl
, upl_offset
/ PAGE_SIZE
)) {
3377 ubc_upl_abort(upl
, 0);
3383 kret
= ubc_upl_map(upl
, (vm_address_t
*)&(bp
->b_datap
));
3385 if (kret
!= KERN_SUCCESS
)
3386 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
3391 SET(bp
->b_flags
, B_INVAL
);
3408 bp_cmp(void *a
, void *b
)
3410 buf_t
*bp_a
= *(buf_t
**)a
,
3411 *bp_b
= *(buf_t
**)b
;
3414 // don't have to worry about negative block
3415 // numbers so this is ok to do.
3417 res
= (bp_a
->b_blkno
- bp_b
->b_blkno
);
3424 bflushq(int whichq
, mount_t mp
)
3428 int total_writes
= 0;
3429 static buf_t flush_table
[NFLUSH
];
3431 if (whichq
< 0 || whichq
>= BQUEUES
) {
3436 lck_mtx_lock(buf_mtxp
);
3438 bp
= TAILQ_FIRST(&bufqueues
[whichq
]);
3440 for (buf_count
= 0; bp
; bp
= next
) {
3441 next
= bp
->b_freelist
.tqe_next
;
3443 if (bp
->b_vp
== NULL
|| bp
->b_vp
->v_mount
!= mp
) {
3447 if (ISSET(bp
->b_flags
, B_DELWRI
) && !ISSET(bp
->b_lflags
, BL_BUSY
)) {
3449 bremfree_locked(bp
);
3451 bp
->b_owner
= current_thread();
3454 SET(bp
->b_lflags
, BL_BUSY
);
3455 flush_table
[buf_count
] = bp
;
3459 if (buf_count
>= NFLUSH
) {
3460 lck_mtx_unlock(buf_mtxp
);
3462 qsort(flush_table
, buf_count
, sizeof(struct buf
*), bp_cmp
);
3464 for (i
= 0; i
< buf_count
; i
++) {
3465 buf_bawrite(flush_table
[i
]);
3471 lck_mtx_unlock(buf_mtxp
);
3473 if (buf_count
> 0) {
3474 qsort(flush_table
, buf_count
, sizeof(struct buf
*), bp_cmp
);
3476 for (i
= 0; i
< buf_count
; i
++) {
3477 buf_bawrite(flush_table
[i
]);
3481 return (total_writes
);
3488 /* XXX move this to a separate file */
3491 * NOTE: THIS CODE HAS NOT BEEN UPDATED
3492 * WITH RESPECT TO THE NEW LOCKING MODEL
3497 * Dynamic Scaling of the Buffer Queues
3500 typedef long long blsize_t
;
3502 blsize_t MAXNBUF
; /* initialize to (sane_size / PAGE_SIZE) */
3503 /* Global tunable limits */
3504 blsize_t nbufh
; /* number of buffer headers */
3505 blsize_t nbuflow
; /* minimum number of buffer headers required */
3506 blsize_t nbufhigh
; /* maximum number of buffer headers allowed */
3507 blsize_t nbuftarget
; /* preferred number of buffer headers */
3512 * 1. 0 < nbuflow <= nbufh <= nbufhigh
3513 * 2. nbufhigh <= MAXNBUF
3514 * 3. 0 < nbuflow <= nbuftarget <= nbufhigh
3515 * 4. nbufh can not be set by sysctl().
3518 /* Per queue tunable limits */
3521 blsize_t bl_nlow
; /* minimum number of buffer headers required */
3522 blsize_t bl_num
; /* number of buffer headers on the queue */
3523 blsize_t bl_nlhigh
; /* maximum number of buffer headers allowed */
3524 blsize_t bl_target
; /* preferred number of buffer headers */
3525 long bl_stale
; /* Seconds after which a buffer is considered stale */
3531 * 1. 0 <= bl_nlow <= bl_num <= bl_nlhigh
3532 * 2. bl_nlhigh <= MAXNBUF
3533 * 3. bufqlim[BQ_META].bl_nlow != 0
3534 * 4. bufqlim[BQ_META].bl_nlow > (number of possible concurrent
3535 * file system IO operations)
3536 * 5. bl_num can not be set by sysctl().
3537 * 6. bl_nhigh <= nbufhigh
3543 * Defining it blsize_t as long permits 2^31 buffer headers per queue.
3544 * Which can describe (2^31 * PAGE_SIZE) memory per queue.
3546 * These limits are exported to by means of sysctl().
3547 * It was decided to define blsize_t as a 64 bit quantity.
3548 * This will make sure that we will not be required to change it
3549 * as long as we do not exceed 64 bit address space for the kernel.
3551 * low and high numbers parameters initialized at compile time
3552 * and boot arguments can be used to override them. sysctl()
3553 * would not change the value. sysctl() can get all the values
3554 * but can set only target. num is the current level.
3556 * Advantages of having a "bufqscan" thread doing the balancing are,
3557 * Keep enough bufs on BQ_EMPTY.
3558 * getnewbuf() by default will always select a buffer from the BQ_EMPTY.
3559 * getnewbuf() perfoms best if a buffer was found there.
3560 * Also this minimizes the possibility of starting IO
3561 * from getnewbuf(). That's a performance win, too.
3563 * Localize complex logic [balancing as well as time aging]
3566 * Simplify getnewbuf() logic by elimination of time aging code.
3572 * The goal of the dynamic scaling of the buffer queues to to keep
3573 * the size of the LRU close to bl_target. Buffers on a queue would
3576 * There would be a thread which will be responsible for "balancing"
3577 * the buffer cache queues.
3579 * The scan order would be: AGE, LRU, META, EMPTY.
3582 long bufqscanwait
= 0;
3584 static void bufqscan_thread();
3585 static int balancebufq(int q
);
3586 static int btrimempty(int n
);
3587 static __inline__
int initbufqscan(void);
3588 static __inline__
int nextbufq(int q
);
3589 static void buqlimprt(int all
);
3592 static __inline__
void
3595 if ((q
< 0) || (q
>= BQUEUES
))
3598 bufqlim
[q
].bl_num
++;
3602 static __inline__
void
3605 if ((q
< 0) || (q
>= BQUEUES
))
3608 bufqlim
[q
].bl_num
--;
3613 bufq_balance_thread_init()
3616 if (bufqscanwait
++ == 0) {
3618 /* Initalize globals */
3619 MAXNBUF
= (sane_size
/ PAGE_SIZE
);
3621 nbuflow
= min(nbufh
, 100);
3622 nbufhigh
= min(MAXNBUF
, max(nbufh
, 2048));
3623 nbuftarget
= (sane_size
>> 5) / PAGE_SIZE
;
3624 nbuftarget
= max(nbuflow
, nbuftarget
);
3625 nbuftarget
= min(nbufhigh
, nbuftarget
);
3628 * Initialize the bufqlim
3632 bufqlim
[BQ_LOCKED
].bl_nlow
= 0;
3633 bufqlim
[BQ_LOCKED
].bl_nlhigh
= 32;
3634 bufqlim
[BQ_LOCKED
].bl_target
= 0;
3635 bufqlim
[BQ_LOCKED
].bl_stale
= 30;
3638 bufqlim
[BQ_LRU
].bl_nlow
= 0;
3639 bufqlim
[BQ_LRU
].bl_nlhigh
= nbufhigh
/4;
3640 bufqlim
[BQ_LRU
].bl_target
= nbuftarget
/4;
3641 bufqlim
[BQ_LRU
].bl_stale
= LRU_IS_STALE
;
3644 bufqlim
[BQ_AGE
].bl_nlow
= 0;
3645 bufqlim
[BQ_AGE
].bl_nlhigh
= nbufhigh
/4;
3646 bufqlim
[BQ_AGE
].bl_target
= nbuftarget
/4;
3647 bufqlim
[BQ_AGE
].bl_stale
= AGE_IS_STALE
;
3650 bufqlim
[BQ_EMPTY
].bl_nlow
= 0;
3651 bufqlim
[BQ_EMPTY
].bl_nlhigh
= nbufhigh
/4;
3652 bufqlim
[BQ_EMPTY
].bl_target
= nbuftarget
/4;
3653 bufqlim
[BQ_EMPTY
].bl_stale
= 600000;
3656 bufqlim
[BQ_META
].bl_nlow
= 0;
3657 bufqlim
[BQ_META
].bl_nlhigh
= nbufhigh
/4;
3658 bufqlim
[BQ_META
].bl_target
= nbuftarget
/4;
3659 bufqlim
[BQ_META
].bl_stale
= META_IS_STALE
;
3662 bufqlim
[BQ_LOCKED
].bl_nlow
= 0;
3663 bufqlim
[BQ_LOCKED
].bl_nlhigh
= 32;
3664 bufqlim
[BQ_LOCKED
].bl_target
= 0;
3665 bufqlim
[BQ_LOCKED
].bl_stale
= 30;
3670 /* create worker thread */
3671 kernel_thread(kernel_task
, bufqscan_thread
);
3674 /* The workloop for the buffer balancing thread */
3682 int q
; /* buffer queue to process */
3686 moretodo
|= balancebufq(q
);
3695 (void)tsleep((void *)&bufqscanwait
, PRIBIO
, "bufqscanwait", 60 * hz
);
3700 /* Seed for the buffer queue balancing */
3701 static __inline__
int
3704 /* Start with AGE queue */
3708 /* Pick next buffer queue to balance */
3709 static __inline__
int
3712 int order
[] = { BQ_AGE
, BQ_LRU
, BQ_META
, BQ_EMPTY
, 0 };
3719 /* function to balance the buffer queues */
3727 /* reject invalid q */
3728 if ((q
< 0) || (q
>= BQUEUES
))
3731 /* LOCKED or LAUNDRY queue MUST not be balanced */
3732 if ((q
== BQ_LOCKED
) || (q
== BQ_LAUNDRY
))
3735 n
= (bufqlim
[q
].bl_num
- bufqlim
[q
].bl_target
);
3737 /* If queue has less than target nothing more to do */
3742 /* Balance only a small amount (12.5%) at a time */
3746 /* EMPTY queue needs special handling */
3747 if (q
== BQ_EMPTY
) {
3748 moretodo
|= btrimempty(n
);
3752 t
= buf_timestamp():
3754 for (; n
> 0; n
--) {
3755 struct buf
*bp
= bufqueues
[q
].tqh_first
;
3759 /* check if it's stale */
3760 if ((t
- bp
->b_timestamp
) > bufqlim
[q
].bl_stale
) {
3761 if (bcleanbuf(bp
)) {
3762 /* buf_bawrite() issued, bp not ready */
3765 /* release the cleaned buffer to BQ_EMPTY */
3766 SET(bp
->b_flags
, B_INVAL
);
3782 * When struct buf are allocated dynamically, this would
3783 * reclaim upto 'n' struct buf from the empty queue.
3793 static char *bname
[BQUEUES
] =
3794 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
3797 for (i
= 0; i
< BQUEUES
; i
++) {
3798 printf("%s : ", bname
[i
]);
3799 printf("min = %ld, ", (long)bufqlim
[i
].bl_nlow
);
3800 printf("cur = %ld, ", (long)bufqlim
[i
].bl_num
);
3801 printf("max = %ld, ", (long)bufqlim
[i
].bl_nlhigh
);
3802 printf("target = %ld, ", (long)bufqlim
[i
].bl_target
);
3803 printf("stale after %ld seconds\n", bufqlim
[i
].bl_stale
);
3806 for (i
= 0; i
< BQUEUES
; i
++) {
3807 printf("%s : ", bname
[i
]);
3808 printf("cur = %ld, ", (long)bufqlim
[i
].bl_num
);