2 * Copyright (c) 2000-2008 Apple 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 <sys/fslog.h> /* fslog_io_error() */
98 #include <mach/mach_types.h>
99 #include <mach/memory_object_types.h>
100 #include <kern/sched_prim.h> /* thread_block() */
102 #include <vm/vm_kern.h>
103 #include <vm/vm_pageout.h>
105 #include <sys/kdebug.h>
107 #include <libkern/OSAtomic.h>
108 #include <libkern/OSDebug.h>
109 #include <sys/ubc_internal.h>
114 static __inline__
void bufqinc(int q
);
115 static __inline__
void bufqdec(int q
);
118 static int bcleanbuf(buf_t bp
, boolean_t discard
);
119 static int brecover_data(buf_t bp
);
120 static boolean_t
incore(vnode_t vp
, daddr64_t blkno
);
121 /* timeout is in msecs */
122 static buf_t
getnewbuf(int slpflag
, int slptimeo
, int *queue
);
123 static void bremfree_locked(buf_t bp
);
124 static void buf_reassign(buf_t bp
, vnode_t newvp
);
125 static errno_t
buf_acquire_locked(buf_t bp
, int flags
, int slpflag
, int slptimeo
);
126 static int buf_iterprepare(vnode_t vp
, struct buflists
*, int flags
);
127 static void buf_itercomplete(vnode_t vp
, struct buflists
*, int flags
);
128 boolean_t
buffer_cache_gc(int);
130 __private_extern__
int bdwrite_internal(buf_t
, int);
132 /* zone allocated buffer headers */
133 static void bufzoneinit(void) __attribute__((section("__TEXT, initcode")));
134 static void bcleanbuf_thread_init(void) __attribute__((section("__TEXT, initcode")));
135 static void bcleanbuf_thread(void);
137 static zone_t buf_hdr_zone
;
138 static int buf_hdr_count
;
142 * Definitions for the buffer hash lists.
144 #define BUFHASH(dvp, lbn) \
145 (&bufhashtbl[((long)(dvp) / sizeof(*(dvp)) + (int)(lbn)) & bufhash])
146 LIST_HEAD(bufhashhdr
, buf
) *bufhashtbl
, invalhash
;
149 static buf_t
incore_locked(vnode_t vp
, daddr64_t blkno
, struct bufhashhdr
*dp
);
151 /* Definitions for the buffer stats. */
152 struct bufstats bufstats
;
154 /* Number of delayed write buffers */
157 static int boot_nbuf_headers
= 0;
160 static TAILQ_HEAD(ioqueue
, buf
) iobufqueue
;
161 static TAILQ_HEAD(bqueues
, buf
) bufqueues
[BQUEUES
];
162 static int needbuffer
;
163 static int need_iobuffer
;
165 static lck_grp_t
*buf_mtx_grp
;
166 static lck_attr_t
*buf_mtx_attr
;
167 static lck_grp_attr_t
*buf_mtx_grp_attr
;
168 static lck_mtx_t
*iobuffer_mtxp
;
169 static lck_mtx_t
*buf_mtxp
;
171 static int buf_busycount
;
173 static __inline__
int
182 * Insq/Remq for the buffer free lists.
185 #define binsheadfree(bp, dp, whichq) do { \
186 TAILQ_INSERT_HEAD(dp, bp, b_freelist); \
190 #define binstailfree(bp, dp, whichq) do { \
191 TAILQ_INSERT_TAIL(dp, bp, b_freelist); \
195 #define binsheadfree(bp, dp, whichq) do { \
196 TAILQ_INSERT_HEAD(dp, bp, b_freelist); \
199 #define binstailfree(bp, dp, whichq) do { \
200 TAILQ_INSERT_TAIL(dp, bp, b_freelist); \
205 #define BHASHENTCHECK(bp) \
206 if ((bp)->b_hash.le_prev != (struct buf **)0xdeadbeef) \
207 panic("%p: b_hash.le_prev is not deadbeef", (bp));
209 #define BLISTNONE(bp) \
210 (bp)->b_hash.le_next = (struct buf *)0; \
211 (bp)->b_hash.le_prev = (struct buf **)0xdeadbeef;
214 * Insq/Remq for the vnode usage lists.
216 #define bufinsvn(bp, dp) LIST_INSERT_HEAD(dp, bp, b_vnbufs)
217 #define bufremvn(bp) { \
218 LIST_REMOVE(bp, b_vnbufs); \
219 (bp)->b_vnbufs.le_next = NOLIST; \
223 * Time in seconds before a buffer on a list is
224 * considered as a stale buffer
226 #define LRU_IS_STALE 120 /* default value for the LRU */
227 #define AGE_IS_STALE 60 /* default value for the AGE */
228 #define META_IS_STALE 180 /* default value for the BQ_META */
230 int lru_is_stale
= LRU_IS_STALE
;
231 int age_is_stale
= AGE_IS_STALE
;
232 int meta_is_stale
= META_IS_STALE
;
236 /* LIST_INSERT_HEAD() with assertions */
237 static __inline__
void
238 blistenterhead(struct bufhashhdr
* head
, buf_t bp
)
240 if ((bp
->b_hash
.le_next
= (head
)->lh_first
) != NULL
)
241 (head
)->lh_first
->b_hash
.le_prev
= &(bp
)->b_hash
.le_next
;
242 (head
)->lh_first
= bp
;
243 bp
->b_hash
.le_prev
= &(head
)->lh_first
;
244 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
245 panic("blistenterhead: le_prev is deadbeef");
248 static __inline__
void
249 binshash(buf_t bp
, struct bufhashhdr
*dp
)
253 #endif /* DIAGNOSTIC */
259 for(; nbp
!= NULL
; nbp
= nbp
->b_hash
.le_next
) {
261 panic("buf already in hashlist");
263 #endif /* DIAGNOSTIC */
265 blistenterhead(dp
, bp
);
268 static __inline__
void
271 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
272 panic("bremhash le_prev is deadbeef");
273 if (bp
->b_hash
.le_next
== bp
)
274 panic("bremhash: next points to self");
276 if (bp
->b_hash
.le_next
!= NULL
)
277 bp
->b_hash
.le_next
->b_hash
.le_prev
= bp
->b_hash
.le_prev
;
278 *bp
->b_hash
.le_prev
= (bp
)->b_hash
.le_next
;
285 buf_valid(buf_t bp
) {
287 if ( (bp
->b_flags
& (B_DONE
| B_DELWRI
)) )
293 buf_fromcache(buf_t bp
) {
295 if ( (bp
->b_flags
& B_CACHE
) )
301 buf_markinvalid(buf_t bp
) {
303 SET(bp
->b_flags
, B_INVAL
);
307 buf_markdelayed(buf_t bp
) {
309 if (!ISSET(bp
->b_flags
, B_DELWRI
)) {
310 SET(bp
->b_flags
, B_DELWRI
);
312 OSAddAtomicLong(1, &nbdwrite
);
313 buf_reassign(bp
, bp
->b_vp
);
315 SET(bp
->b_flags
, B_DONE
);
319 buf_markeintr(buf_t bp
) {
321 SET(bp
->b_flags
, B_EINTR
);
326 buf_markaged(buf_t bp
) {
328 SET(bp
->b_flags
, B_AGE
);
334 if ((bp
->b_flags
& B_FUA
) == B_FUA
)
340 buf_markfua(buf_t bp
) {
342 SET(bp
->b_flags
, B_FUA
);
345 #ifdef CONFIG_PROTECT
347 buf_getcpaddr(buf_t bp
) {
348 return bp
->b_cpentry
;
352 buf_setcpaddr(buf_t bp
, void *cp_entry_addr
) {
353 bp
->b_cpentry
= (struct cprotect
*) cp_entry_addr
;
358 buf_getcpaddr(buf_t bp __unused
) {
363 buf_setcpaddr(buf_t bp __unused
, void *cp_entry_addr __unused
) {
366 #endif /* CONFIG_PROTECT */
369 buf_error(buf_t bp
) {
371 return (bp
->b_error
);
375 buf_seterror(buf_t bp
, errno_t error
) {
377 if ((bp
->b_error
= error
))
378 SET(bp
->b_flags
, B_ERROR
);
380 CLR(bp
->b_flags
, B_ERROR
);
384 buf_setflags(buf_t bp
, int32_t flags
) {
386 SET(bp
->b_flags
, (flags
& BUF_X_WRFLAGS
));
390 buf_clearflags(buf_t bp
, int32_t flags
) {
392 CLR(bp
->b_flags
, (flags
& BUF_X_WRFLAGS
));
396 buf_flags(buf_t bp
) {
398 return ((bp
->b_flags
& BUF_X_RDFLAGS
));
402 buf_reset(buf_t bp
, int32_t io_flags
) {
404 CLR(bp
->b_flags
, (B_READ
| B_WRITE
| B_ERROR
| B_DONE
| B_INVAL
| B_ASYNC
| B_NOCACHE
| B_FUA
));
405 SET(bp
->b_flags
, (io_flags
& (B_ASYNC
| B_READ
| B_WRITE
| B_NOCACHE
)));
411 buf_count(buf_t bp
) {
413 return (bp
->b_bcount
);
417 buf_setcount(buf_t bp
, uint32_t bcount
) {
419 bp
->b_bcount
= bcount
;
425 return (bp
->b_bufsize
);
429 buf_setsize(buf_t bp
, uint32_t bufsize
) {
431 bp
->b_bufsize
= bufsize
;
435 buf_resid(buf_t bp
) {
437 return (bp
->b_resid
);
441 buf_setresid(buf_t bp
, uint32_t resid
) {
447 buf_dirtyoff(buf_t bp
) {
449 return (bp
->b_dirtyoff
);
453 buf_dirtyend(buf_t bp
) {
455 return (bp
->b_dirtyend
);
459 buf_setdirtyoff(buf_t bp
, uint32_t dirtyoff
) {
461 bp
->b_dirtyoff
= dirtyoff
;
465 buf_setdirtyend(buf_t bp
, uint32_t dirtyend
) {
467 bp
->b_dirtyend
= dirtyend
;
471 buf_dataptr(buf_t bp
) {
473 return (bp
->b_datap
);
477 buf_setdataptr(buf_t bp
, uintptr_t data
) {
483 buf_vnode(buf_t bp
) {
489 buf_setvnode(buf_t bp
, vnode_t vp
) {
496 buf_callback(buf_t bp
)
498 if ( !(bp
->b_flags
& B_CALL
) )
499 return ((void *) NULL
);
501 return ((void *)bp
->b_iodone
);
506 buf_setcallback(buf_t bp
, void (*callback
)(buf_t
, void *), void *transaction
)
509 bp
->b_flags
|= (B_CALL
| B_ASYNC
);
511 bp
->b_flags
&= ~B_CALL
;
512 bp
->b_transaction
= transaction
;
513 bp
->b_iodone
= callback
;
519 buf_setupl(buf_t bp
, upl_t upl
, uint32_t offset
)
522 if ( !(bp
->b_lflags
& BL_IOBUF
) )
526 bp
->b_flags
|= B_CLUSTER
;
528 bp
->b_flags
&= ~B_CLUSTER
;
530 bp
->b_uploffset
= offset
;
536 buf_clone(buf_t bp
, int io_offset
, int io_size
, void (*iodone
)(buf_t
, void *), void *arg
)
540 if (io_offset
< 0 || io_size
< 0)
543 if ((unsigned)(io_offset
+ io_size
) > (unsigned)bp
->b_bcount
)
546 if (bp
->b_flags
& B_CLUSTER
) {
547 if (io_offset
&& ((bp
->b_uploffset
+ io_offset
) & PAGE_MASK
))
550 if (((bp
->b_uploffset
+ io_offset
+ io_size
) & PAGE_MASK
) && ((io_offset
+ io_size
) < bp
->b_bcount
))
553 io_bp
= alloc_io_buf(bp
->b_vp
, 0);
555 io_bp
->b_flags
= bp
->b_flags
& (B_COMMIT_UPL
| B_META
| B_PAGEIO
| B_CLUSTER
| B_PHYS
| B_RAW
| B_ASYNC
| B_READ
| B_FUA
);
558 io_bp
->b_transaction
= arg
;
559 io_bp
->b_iodone
= iodone
;
560 io_bp
->b_flags
|= B_CALL
;
562 if (bp
->b_flags
& B_CLUSTER
) {
563 io_bp
->b_upl
= bp
->b_upl
;
564 io_bp
->b_uploffset
= bp
->b_uploffset
+ io_offset
;
566 io_bp
->b_datap
= (uintptr_t)(((char *)bp
->b_datap
) + io_offset
);
568 io_bp
->b_bcount
= io_size
;
576 buf_setfilter(buf_t bp
, void (*filter
)(buf_t
, void *), void *transaction
,
577 void **old_iodone
, void **old_transaction
)
580 *old_iodone
= (void *)(bp
->b_iodone
);
582 *old_transaction
= (void *)(bp
->b_transaction
);
584 bp
->b_transaction
= transaction
;
585 bp
->b_iodone
= filter
;
587 bp
->b_flags
|= B_FILTER
;
589 bp
->b_flags
&= ~B_FILTER
;
594 buf_blkno(buf_t bp
) {
596 return (bp
->b_blkno
);
600 buf_lblkno(buf_t bp
) {
602 return (bp
->b_lblkno
);
606 buf_setblkno(buf_t bp
, daddr64_t blkno
) {
612 buf_setlblkno(buf_t bp
, daddr64_t lblkno
) {
614 bp
->b_lblkno
= lblkno
;
618 buf_device(buf_t bp
) {
624 buf_setdevice(buf_t bp
, vnode_t vp
) {
626 if ((vp
->v_type
!= VBLK
) && (vp
->v_type
!= VCHR
))
628 bp
->b_dev
= vp
->v_rdev
;
635 buf_drvdata(buf_t bp
) {
637 return (bp
->b_drvdata
);
641 buf_setdrvdata(buf_t bp
, void *drvdata
) {
643 bp
->b_drvdata
= drvdata
;
647 buf_fsprivate(buf_t bp
) {
649 return (bp
->b_fsprivate
);
653 buf_setfsprivate(buf_t bp
, void *fsprivate
) {
655 bp
->b_fsprivate
= fsprivate
;
659 buf_rcred(buf_t bp
) {
661 return (bp
->b_rcred
);
665 buf_wcred(buf_t bp
) {
667 return (bp
->b_wcred
);
677 buf_uploffset(buf_t bp
) {
679 return ((uint32_t)(bp
->b_uploffset
));
690 buf_map(buf_t bp
, caddr_t
*io_addr
)
696 if ( !(bp
->b_flags
& B_CLUSTER
)) {
697 *io_addr
= (caddr_t
)bp
->b_datap
;
700 real_bp
= (buf_t
)(bp
->b_real_bp
);
702 if (real_bp
&& real_bp
->b_datap
) {
704 * b_real_bp is only valid if B_CLUSTER is SET
705 * if it's non-zero, than someone did a cluster_bp call
706 * if the backing physical pages were already mapped
707 * in before the call to cluster_bp (non-zero b_datap),
708 * than we just use that mapping
710 *io_addr
= (caddr_t
)real_bp
->b_datap
;
713 kret
= ubc_upl_map(bp
->b_upl
, &vaddr
); /* Map it in */
715 if (kret
!= KERN_SUCCESS
) {
720 vaddr
+= bp
->b_uploffset
;
722 *io_addr
= (caddr_t
)vaddr
;
733 if ( !(bp
->b_flags
& B_CLUSTER
))
736 * see buf_map for the explanation
738 real_bp
= (buf_t
)(bp
->b_real_bp
);
740 if (real_bp
&& real_bp
->b_datap
)
743 if ((bp
->b_lflags
& BL_IOBUF
) &&
744 ((bp
->b_flags
& (B_PAGEIO
| B_READ
)) != (B_PAGEIO
| B_READ
))) {
746 * ignore pageins... the 'right' thing will
747 * happen due to the way we handle speculative
750 * when we commit these pages, we'll hit
751 * it with UPL_COMMIT_INACTIVE which
752 * will clear the reference bit that got
753 * turned on when we touched the mapping
755 bp
->b_flags
|= B_AGE
;
757 kret
= ubc_upl_unmap(bp
->b_upl
);
759 if (kret
!= KERN_SUCCESS
)
766 buf_clear(buf_t bp
) {
769 if (buf_map(bp
, &baddr
) == 0) {
770 bzero(baddr
, bp
->b_bcount
);
777 * Read or write a buffer that is not contiguous on disk.
778 * buffer is marked done/error at the conclusion
781 buf_strategy_fragmented(vnode_t devvp
, buf_t bp
, off_t f_offset
, size_t contig_bytes
)
783 vnode_t vp
= buf_vnode(bp
);
784 buf_t io_bp
; /* For reading or writing a single block */
787 size_t io_contig_bytes
;
793 * save our starting point... the bp was already mapped
794 * in buf_strategy before we got called
795 * no sense doing it again.
797 io_blkno
= bp
->b_blkno
;
799 * Make sure we redo this mapping for the next I/O
800 * i.e. this can never be a 'permanent' mapping
802 bp
->b_blkno
= bp
->b_lblkno
;
805 * Get an io buffer to do the deblocking
807 io_bp
= alloc_io_buf(devvp
, 0);
809 io_bp
->b_lblkno
= bp
->b_lblkno
;
810 io_bp
->b_datap
= bp
->b_datap
;
811 io_resid
= bp
->b_bcount
;
812 io_direction
= bp
->b_flags
& B_READ
;
813 io_contig_bytes
= contig_bytes
;
815 if (bp
->b_flags
& B_READ
)
816 bmap_flags
= VNODE_READ
;
818 bmap_flags
= VNODE_WRITE
;
823 * this is unexepected, but we'll allow for it
825 bzero((caddr_t
)io_bp
->b_datap
, (int)io_contig_bytes
);
827 io_bp
->b_bcount
= io_contig_bytes
;
828 io_bp
->b_bufsize
= io_contig_bytes
;
829 io_bp
->b_resid
= io_contig_bytes
;
830 io_bp
->b_blkno
= io_blkno
;
832 buf_reset(io_bp
, io_direction
);
835 * Call the device to do the I/O and wait for it. Make sure the appropriate party is charged for write
838 if (!ISSET(bp
->b_flags
, B_READ
))
839 OSAddAtomic(1, &devvp
->v_numoutput
);
841 if ((error
= VNOP_STRATEGY(io_bp
)))
843 if ((error
= (int)buf_biowait(io_bp
)))
845 if (io_bp
->b_resid
) {
846 io_resid
-= (io_contig_bytes
- io_bp
->b_resid
);
850 if ((io_resid
-= io_contig_bytes
) == 0)
852 f_offset
+= io_contig_bytes
;
853 io_bp
->b_datap
+= io_contig_bytes
;
856 * Map the current position to a physical block number
858 if ((error
= VNOP_BLOCKMAP(vp
, f_offset
, io_resid
, &io_blkno
, &io_contig_bytes
, NULL
, bmap_flags
, NULL
)))
864 buf_seterror(bp
, error
);
865 bp
->b_resid
= io_resid
;
867 * This I/O is now complete
876 * struct vnop_strategy_args {
881 buf_strategy(vnode_t devvp
, void *ap
)
883 buf_t bp
= ((struct vnop_strategy_args
*)ap
)->a_bp
;
884 vnode_t vp
= bp
->b_vp
;
888 if (vp
== NULL
|| vp
->v_type
== VCHR
|| vp
->v_type
== VBLK
)
889 panic("buf_strategy: b_vp == NULL || vtype == VCHR | VBLK\n");
891 * associate the physical device with
892 * with this buf_t even if we don't
893 * end up issuing the I/O...
895 bp
->b_dev
= devvp
->v_rdev
;
896 DTRACE_IO1(start
, buf_t
, bp
);
898 if (bp
->b_flags
& B_READ
)
899 bmap_flags
= VNODE_READ
;
901 bmap_flags
= VNODE_WRITE
;
903 if ( !(bp
->b_flags
& B_CLUSTER
)) {
907 * we have a UPL associated with this bp
908 * go through cluster_bp which knows how
909 * to deal with filesystem block sizes
910 * that aren't equal to the page size
912 return (cluster_bp(bp
));
914 if (bp
->b_blkno
== bp
->b_lblkno
) {
918 if ((error
= VNOP_BLKTOOFF(vp
, bp
->b_lblkno
, &f_offset
))) {
919 buf_seterror(bp
, error
);
924 if ((error
= VNOP_BLOCKMAP(vp
, f_offset
, bp
->b_bcount
, &bp
->b_blkno
, &contig_bytes
, NULL
, bmap_flags
, NULL
))) {
925 buf_seterror(bp
, error
);
930 if ((bp
->b_blkno
== -1) || (contig_bytes
== 0)) {
931 /* Set block number to force biodone later */
935 else if ((long)contig_bytes
< bp
->b_bcount
)
936 return (buf_strategy_fragmented(devvp
, bp
, f_offset
, contig_bytes
));
938 if (bp
->b_blkno
== -1) {
944 * we can issue the I/O because...
945 * either B_CLUSTER is set which
946 * means that the I/O is properly set
947 * up to be a multiple of the page size, or
948 * we were able to successfully set up the
949 * phsyical block mapping
951 return (VOCALL(devvp
->v_op
, VOFFSET(vnop_strategy
), ap
));
957 buf_alloc(vnode_t vp
)
959 return(alloc_io_buf(vp
, 0));
970 * iterate buffers for the specified vp.
971 * if BUF_SCAN_DIRTY is set, do the dirty list
972 * if BUF_SCAN_CLEAN is set, do the clean list
973 * if neither flag is set, default to BUF_SCAN_DIRTY
974 * if BUF_NOTIFY_BUSY is set, call the callout function using a NULL bp for busy pages
977 struct buf_iterate_info_t
{
979 struct buflists
*listhead
;
983 buf_iterate(vnode_t vp
, int (*callout
)(buf_t
, void *), int flags
, void *arg
)
987 struct buflists local_iterblkhd
;
988 int lock_flags
= BAC_NOWAIT
| BAC_REMOVE
;
989 int notify_busy
= flags
& BUF_NOTIFY_BUSY
;
990 struct buf_iterate_info_t list
[2];
993 if (flags
& BUF_SKIP_LOCKED
)
994 lock_flags
|= BAC_SKIP_LOCKED
;
995 if (flags
& BUF_SKIP_NONLOCKED
)
996 lock_flags
|= BAC_SKIP_NONLOCKED
;
998 if ( !(flags
& (BUF_SCAN_DIRTY
| BUF_SCAN_CLEAN
)))
999 flags
|= BUF_SCAN_DIRTY
;
1003 if (flags
& BUF_SCAN_DIRTY
) {
1004 list
[num_lists
].flag
= VBI_DIRTY
;
1005 list
[num_lists
].listhead
= &vp
->v_dirtyblkhd
;
1008 if (flags
& BUF_SCAN_CLEAN
) {
1009 list
[num_lists
].flag
= VBI_CLEAN
;
1010 list
[num_lists
].listhead
= &vp
->v_cleanblkhd
;
1014 for (i
= 0; i
< num_lists
; i
++) {
1015 lck_mtx_lock(buf_mtxp
);
1017 if (buf_iterprepare(vp
, &local_iterblkhd
, list
[i
].flag
)) {
1018 lck_mtx_unlock(buf_mtxp
);
1021 while (!LIST_EMPTY(&local_iterblkhd
)) {
1022 bp
= LIST_FIRST(&local_iterblkhd
);
1023 LIST_REMOVE(bp
, b_vnbufs
);
1024 LIST_INSERT_HEAD(list
[i
].listhead
, bp
, b_vnbufs
);
1026 if (buf_acquire_locked(bp
, lock_flags
, 0, 0)) {
1034 lck_mtx_unlock(buf_mtxp
);
1036 retval
= callout(bp
, arg
);
1045 case BUF_RETURNED_DONE
:
1048 lck_mtx_lock(buf_mtxp
);
1050 case BUF_CLAIMED_DONE
:
1051 lck_mtx_lock(buf_mtxp
);
1054 lck_mtx_lock(buf_mtxp
);
1055 } /* while list has more nodes */
1057 buf_itercomplete(vp
, &local_iterblkhd
, list
[i
].flag
);
1058 lck_mtx_unlock(buf_mtxp
);
1059 } /* for each list */
1064 * Flush out and invalidate all buffers associated with a vnode.
1067 buf_invalidateblks(vnode_t vp
, int flags
, int slpflag
, int slptimeo
)
1071 int must_rescan
= 1;
1072 struct buflists local_iterblkhd
;
1075 if (LIST_EMPTY(&vp
->v_cleanblkhd
) && LIST_EMPTY(&vp
->v_dirtyblkhd
))
1078 lck_mtx_lock(buf_mtxp
);
1081 if (must_rescan
== 0)
1083 * the lists may not be empty, but all that's left at this
1084 * point are metadata or B_LOCKED buffers which are being
1085 * skipped... we know this because we made it through both
1086 * the clean and dirty lists without dropping buf_mtxp...
1087 * each time we drop buf_mtxp we bump "must_rescan"
1090 if (LIST_EMPTY(&vp
->v_cleanblkhd
) && LIST_EMPTY(&vp
->v_dirtyblkhd
))
1094 * iterate the clean list
1096 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_CLEAN
)) {
1097 goto try_dirty_list
;
1099 while (!LIST_EMPTY(&local_iterblkhd
)) {
1100 bp
= LIST_FIRST(&local_iterblkhd
);
1102 LIST_REMOVE(bp
, b_vnbufs
);
1103 LIST_INSERT_HEAD(&vp
->v_cleanblkhd
, bp
, b_vnbufs
);
1106 * some filesystems distinguish meta data blocks with a negative logical block #
1108 if ((flags
& BUF_SKIP_META
) && (bp
->b_lblkno
< 0 || ISSET(bp
->b_flags
, B_META
)))
1111 if ( (error
= (int)buf_acquire_locked(bp
, BAC_REMOVE
| BAC_SKIP_LOCKED
, slpflag
, slptimeo
)) ) {
1112 if (error
== EDEADLK
)
1114 * this buffer was marked B_LOCKED...
1115 * we didn't drop buf_mtxp, so we
1116 * we don't need to rescan
1119 if (error
== EAGAIN
) {
1121 * found a busy buffer... we blocked and
1122 * dropped buf_mtxp, so we're going to
1123 * need to rescan after this pass is completed
1129 * got some kind of 'real' error out of the msleep
1130 * in buf_acquire_locked, terminate the scan and return the error
1132 buf_itercomplete(vp
, &local_iterblkhd
, VBI_CLEAN
);
1134 lck_mtx_unlock(buf_mtxp
);
1137 lck_mtx_unlock(buf_mtxp
);
1139 SET(bp
->b_flags
, B_INVAL
);
1142 lck_mtx_lock(buf_mtxp
);
1145 * by dropping buf_mtxp, we allow new
1146 * buffers to be added to the vnode list(s)
1147 * we'll have to rescan at least once more
1148 * if the queues aren't empty
1152 buf_itercomplete(vp
, &local_iterblkhd
, VBI_CLEAN
);
1156 * Now iterate on dirty blks
1158 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_DIRTY
)) {
1161 while (!LIST_EMPTY(&local_iterblkhd
)) {
1162 bp
= LIST_FIRST(&local_iterblkhd
);
1164 LIST_REMOVE(bp
, b_vnbufs
);
1165 LIST_INSERT_HEAD(&vp
->v_dirtyblkhd
, bp
, b_vnbufs
);
1168 * some filesystems distinguish meta data blocks with a negative logical block #
1170 if ((flags
& BUF_SKIP_META
) && (bp
->b_lblkno
< 0 || ISSET(bp
->b_flags
, B_META
)))
1173 if ( (error
= (int)buf_acquire_locked(bp
, BAC_REMOVE
| BAC_SKIP_LOCKED
, slpflag
, slptimeo
)) ) {
1174 if (error
== EDEADLK
)
1176 * this buffer was marked B_LOCKED...
1177 * we didn't drop buf_mtxp, so we
1178 * we don't need to rescan
1181 if (error
== EAGAIN
) {
1183 * found a busy buffer... we blocked and
1184 * dropped buf_mtxp, so we're going to
1185 * need to rescan after this pass is completed
1191 * got some kind of 'real' error out of the msleep
1192 * in buf_acquire_locked, terminate the scan and return the error
1194 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1196 lck_mtx_unlock(buf_mtxp
);
1199 lck_mtx_unlock(buf_mtxp
);
1201 SET(bp
->b_flags
, B_INVAL
);
1203 if (ISSET(bp
->b_flags
, B_DELWRI
) && (flags
& BUF_WRITE_DATA
))
1204 (void) VNOP_BWRITE(bp
);
1208 lck_mtx_lock(buf_mtxp
);
1210 * by dropping buf_mtxp, we allow new
1211 * buffers to be added to the vnode list(s)
1212 * we'll have to rescan at least once more
1213 * if the queues aren't empty
1217 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1219 lck_mtx_unlock(buf_mtxp
);
1225 buf_flushdirtyblks(vnode_t vp
, int wait
, int flags
, const char *msg
) {
1227 int writes_issued
= 0;
1230 struct buflists local_iterblkhd
;
1231 int lock_flags
= BAC_NOWAIT
| BAC_REMOVE
;
1233 if (flags
& BUF_SKIP_LOCKED
)
1234 lock_flags
|= BAC_SKIP_LOCKED
;
1235 if (flags
& BUF_SKIP_NONLOCKED
)
1236 lock_flags
|= BAC_SKIP_NONLOCKED
;
1238 lck_mtx_lock(buf_mtxp
);
1240 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_DIRTY
) == 0) {
1241 while (!LIST_EMPTY(&local_iterblkhd
)) {
1242 bp
= LIST_FIRST(&local_iterblkhd
);
1243 LIST_REMOVE(bp
, b_vnbufs
);
1244 LIST_INSERT_HEAD(&vp
->v_dirtyblkhd
, bp
, b_vnbufs
);
1246 if ((error
= buf_acquire_locked(bp
, lock_flags
, 0, 0)) == EBUSY
)
1250 lck_mtx_unlock(buf_mtxp
);
1252 bp
->b_flags
&= ~B_LOCKED
;
1255 * Wait for I/O associated with indirect blocks to complete,
1256 * since there is no way to quickly wait for them below.
1258 if ((bp
->b_vp
== vp
) || (wait
== 0))
1259 (void) buf_bawrite(bp
);
1261 (void) VNOP_BWRITE(bp
);
1264 lck_mtx_lock(buf_mtxp
);
1266 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1268 lck_mtx_unlock(buf_mtxp
);
1271 (void)vnode_waitforwrites(vp
, 0, 0, 0, msg
);
1273 if (vp
->v_dirtyblkhd
.lh_first
&& busy
) {
1275 * we had one or more BUSY buffers on
1276 * the dirtyblock list... most likely
1277 * these are due to delayed writes that
1278 * were moved to the bclean queue but
1279 * have not yet been 'written'.
1280 * if we issued some writes on the
1281 * previous pass, we try again immediately
1282 * if we didn't, we'll sleep for some time
1283 * to allow the state to change...
1285 if (writes_issued
== 0) {
1286 (void)tsleep((caddr_t
)&vp
->v_numoutput
,
1287 PRIBIO
+ 1, "vnode_flushdirtyblks", hz
/20);
1299 * called with buf_mtxp held...
1300 * this lock protects the queue manipulation
1303 buf_iterprepare(vnode_t vp
, struct buflists
*iterheadp
, int flags
)
1305 struct buflists
* listheadp
;
1307 if (flags
& VBI_DIRTY
)
1308 listheadp
= &vp
->v_dirtyblkhd
;
1310 listheadp
= &vp
->v_cleanblkhd
;
1312 while (vp
->v_iterblkflags
& VBI_ITER
) {
1313 vp
->v_iterblkflags
|= VBI_ITERWANT
;
1314 msleep(&vp
->v_iterblkflags
, buf_mtxp
, 0, "buf_iterprepare", NULL
);
1316 if (LIST_EMPTY(listheadp
)) {
1317 LIST_INIT(iterheadp
);
1320 vp
->v_iterblkflags
|= VBI_ITER
;
1322 iterheadp
->lh_first
= listheadp
->lh_first
;
1323 listheadp
->lh_first
->b_vnbufs
.le_prev
= &iterheadp
->lh_first
;
1324 LIST_INIT(listheadp
);
1330 * called with buf_mtxp held...
1331 * this lock protects the queue manipulation
1334 buf_itercomplete(vnode_t vp
, struct buflists
*iterheadp
, int flags
)
1336 struct buflists
* listheadp
;
1339 if (flags
& VBI_DIRTY
)
1340 listheadp
= &vp
->v_dirtyblkhd
;
1342 listheadp
= &vp
->v_cleanblkhd
;
1344 while (!LIST_EMPTY(iterheadp
)) {
1345 bp
= LIST_FIRST(iterheadp
);
1346 LIST_REMOVE(bp
, b_vnbufs
);
1347 LIST_INSERT_HEAD(listheadp
, bp
, b_vnbufs
);
1349 vp
->v_iterblkflags
&= ~VBI_ITER
;
1351 if (vp
->v_iterblkflags
& VBI_ITERWANT
) {
1352 vp
->v_iterblkflags
&= ~VBI_ITERWANT
;
1353 wakeup(&vp
->v_iterblkflags
);
1359 bremfree_locked(buf_t bp
)
1361 struct bqueues
*dp
= NULL
;
1364 * We only calculate the head of the freelist when removing
1365 * the last element of the list as that is the only time that
1366 * it is needed (e.g. to reset the tail pointer).
1368 * NB: This makes an assumption about how tailq's are implemented.
1370 whichq
= bp
->b_whichq
;
1372 if (bp
->b_freelist
.tqe_next
== NULL
) {
1373 dp
= &bufqueues
[whichq
];
1375 if (dp
->tqh_last
!= &bp
->b_freelist
.tqe_next
)
1376 panic("bremfree: lost tail");
1378 TAILQ_REMOVE(dp
, bp
, b_freelist
);
1383 if (whichq
== BQ_LAUNDRY
)
1387 bp
->b_timestamp
= 0;
1391 * Associate a buffer with a vnode.
1392 * buf_mtxp must be locked on entry
1395 bgetvp_locked(vnode_t vp
, buf_t bp
)
1399 panic("bgetvp_locked: not free");
1401 if (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
)
1402 bp
->b_dev
= vp
->v_rdev
;
1406 * Insert onto list for new vnode.
1408 bufinsvn(bp
, &vp
->v_cleanblkhd
);
1412 * Disassociate a buffer from a vnode.
1413 * buf_mtxp must be locked on entry
1416 brelvp_locked(buf_t bp
)
1419 * Delete from old vnode list, if on one.
1421 if (bp
->b_vnbufs
.le_next
!= NOLIST
)
1424 bp
->b_vp
= (vnode_t
)NULL
;
1428 * Reassign a buffer from one vnode to another.
1429 * Used to assign file specific control information
1430 * (indirect blocks) to the vnode to which they belong.
1433 buf_reassign(buf_t bp
, vnode_t newvp
)
1435 register struct buflists
*listheadp
;
1437 if (newvp
== NULL
) {
1438 printf("buf_reassign: NULL");
1441 lck_mtx_lock_spin(buf_mtxp
);
1444 * Delete from old vnode list, if on one.
1446 if (bp
->b_vnbufs
.le_next
!= NOLIST
)
1449 * If dirty, put on list of dirty buffers;
1450 * otherwise insert onto list of clean buffers.
1452 if (ISSET(bp
->b_flags
, B_DELWRI
))
1453 listheadp
= &newvp
->v_dirtyblkhd
;
1455 listheadp
= &newvp
->v_cleanblkhd
;
1456 bufinsvn(bp
, listheadp
);
1458 lck_mtx_unlock(buf_mtxp
);
1461 static __inline__
void
1462 bufhdrinit(buf_t bp
)
1464 bzero((char *)bp
, sizeof *bp
);
1466 bp
->b_rcred
= NOCRED
;
1467 bp
->b_wcred
= NOCRED
;
1468 bp
->b_vnbufs
.le_next
= NOLIST
;
1469 bp
->b_flags
= B_INVAL
;
1475 * Initialize buffers and hash links for buffers.
1477 __private_extern__
void
1485 /* Initialize the buffer queues ('freelists') and the hash table */
1486 for (dp
= bufqueues
; dp
< &bufqueues
[BQUEUES
]; dp
++)
1488 bufhashtbl
= hashinit(nbuf_hashelements
, M_CACHE
, &bufhash
);
1492 /* Initialize the buffer headers */
1493 for (i
= 0; i
< max_nbuf_headers
; i
++) {
1495 bp
= &buf_headers
[i
];
1499 dp
= &bufqueues
[BQ_EMPTY
];
1500 bp
->b_whichq
= BQ_EMPTY
;
1501 bp
->b_timestamp
= buf_timestamp();
1502 binsheadfree(bp
, dp
, BQ_EMPTY
);
1503 binshash(bp
, &invalhash
);
1506 boot_nbuf_headers
= nbuf_headers
;
1507 for (; i
< nbuf_headers
+ niobuf_headers
; i
++) {
1508 bp
= &buf_headers
[i
];
1511 binsheadfree(bp
, &iobufqueue
, -1);
1515 * allocate lock group attribute and group
1517 buf_mtx_grp_attr
= lck_grp_attr_alloc_init();
1518 buf_mtx_grp
= lck_grp_alloc_init("buffer cache", buf_mtx_grp_attr
);
1521 * allocate the lock attribute
1523 buf_mtx_attr
= lck_attr_alloc_init();
1526 * allocate and initialize mutex's for the buffer and iobuffer pools
1528 buf_mtxp
= lck_mtx_alloc_init(buf_mtx_grp
, buf_mtx_attr
);
1529 iobuffer_mtxp
= lck_mtx_alloc_init(buf_mtx_grp
, buf_mtx_attr
);
1531 if (iobuffer_mtxp
== NULL
)
1532 panic("couldn't create iobuffer mutex");
1534 if (buf_mtxp
== NULL
)
1535 panic("couldn't create buf mutex");
1538 * allocate and initialize cluster specific global locks...
1542 printf("using %d buffer headers and %d cluster IO buffer headers\n",
1543 nbuf_headers
, niobuf_headers
);
1545 /* Set up zones used by the buffer cache */
1548 /* start the bcleanbuf() thread */
1549 bcleanbuf_thread_init();
1551 /* Register a callout for relieving vm pressure */
1552 if (vm_set_buffer_cleanup_callout(buffer_cache_gc
) != KERN_SUCCESS
) {
1553 panic("Couldn't register buffer cache callout for vm pressure!\n");
1558 static void bufq_balance_thread_init(void) __attribute__((section("__TEXT, initcode")));
1559 /* create a thread to do dynamic buffer queue balancing */
1560 bufq_balance_thread_init();
1568 * Zones for the meta data buffers
1572 #define MAXMETA 8192
1574 struct meta_zone_entry
{
1578 const char *mz_name
;
1581 struct meta_zone_entry meta_zones
[] = {
1582 {NULL
, (MINMETA
* 1), 128 * (MINMETA
* 1), "buf.512" },
1583 {NULL
, (MINMETA
* 2), 64 * (MINMETA
* 2), "buf.1024" },
1584 {NULL
, (MINMETA
* 4), 16 * (MINMETA
* 4), "buf.2048" },
1585 {NULL
, (MINMETA
* 8), 512 * (MINMETA
* 8), "buf.4096" },
1586 {NULL
, (MINMETA
* 16), 512 * (MINMETA
* 16), "buf.8192" },
1587 {NULL
, 0, 0, "" } /* End */
1591 * Initialize the meta data zones
1598 for (i
= 0; meta_zones
[i
].mz_size
!= 0; i
++) {
1599 meta_zones
[i
].mz_zone
=
1600 zinit(meta_zones
[i
].mz_size
,
1601 meta_zones
[i
].mz_max
,
1603 meta_zones
[i
].mz_name
);
1605 buf_hdr_zone
= zinit(sizeof(struct buf
), 32, PAGE_SIZE
, "buf headers");
1608 static __inline__ zone_t
1609 getbufzone(size_t size
)
1613 if ((size
% 512) || (size
< MINMETA
) || (size
> MAXMETA
))
1614 panic("getbufzone: incorect size = %lu", size
);
1616 for (i
= 0; meta_zones
[i
].mz_size
!= 0; i
++) {
1617 if (meta_zones
[i
].mz_size
>= size
)
1621 return (meta_zones
[i
].mz_zone
);
1627 bio_doread(vnode_t vp
, daddr64_t blkno
, int size
, kauth_cred_t cred
, int async
, int queuetype
)
1631 bp
= buf_getblk(vp
, blkno
, size
, 0, 0, queuetype
);
1634 * If buffer does not have data valid, start a read.
1635 * Note that if buffer is B_INVAL, buf_getblk() won't return it.
1636 * Therefore, it's valid if it's I/O has completed or been delayed.
1638 if (!ISSET(bp
->b_flags
, (B_DONE
| B_DELWRI
))) {
1643 /* Start I/O for the buffer (keeping credentials). */
1644 SET(bp
->b_flags
, B_READ
| async
);
1645 if (IS_VALID_CRED(cred
) && !IS_VALID_CRED(bp
->b_rcred
)) {
1646 kauth_cred_ref(cred
);
1652 trace(TR_BREADMISS
, pack(vp
, size
), blkno
);
1654 /* Pay for the read. */
1655 if (p
&& p
->p_stats
)
1656 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_inblock
); /* XXX */
1660 * since we asked for an ASYNC I/O
1661 * the biodone will do the brelse
1662 * we don't want to pass back a bp
1663 * that we don't 'own'
1672 trace(TR_BREADHIT
, pack(vp
, size
), blkno
);
1678 * Perform the reads for buf_breadn() and buf_meta_breadn().
1679 * Trivial modification to the breada algorithm presented in Bach (p.55).
1682 do_breadn_for_type(vnode_t vp
, daddr64_t blkno
, int size
, daddr64_t
*rablks
, int *rasizes
,
1683 int nrablks
, kauth_cred_t cred
, buf_t
*bpp
, int queuetype
)
1688 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, queuetype
);
1691 * For each of the read-ahead blocks, start a read, if necessary.
1693 for (i
= 0; i
< nrablks
; i
++) {
1694 /* If it's in the cache, just go on to next one. */
1695 if (incore(vp
, rablks
[i
]))
1698 /* Get a buffer for the read-ahead block */
1699 (void) bio_doread(vp
, rablks
[i
], rasizes
[i
], cred
, B_ASYNC
, queuetype
);
1702 /* Otherwise, we had to start a read for it; wait until it's valid. */
1703 return (buf_biowait(bp
));
1708 * Read a disk block.
1709 * This algorithm described in Bach (p.54).
1712 buf_bread(vnode_t vp
, daddr64_t blkno
, int size
, kauth_cred_t cred
, buf_t
*bpp
)
1716 /* Get buffer for block. */
1717 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, BLK_READ
);
1719 /* Wait for the read to complete, and return result. */
1720 return (buf_biowait(bp
));
1724 * Read a disk block. [bread() for meta-data]
1725 * This algorithm described in Bach (p.54).
1728 buf_meta_bread(vnode_t vp
, daddr64_t blkno
, int size
, kauth_cred_t cred
, buf_t
*bpp
)
1732 /* Get buffer for block. */
1733 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, BLK_META
);
1735 /* Wait for the read to complete, and return result. */
1736 return (buf_biowait(bp
));
1740 * Read-ahead multiple disk blocks. The first is sync, the rest async.
1743 buf_breadn(vnode_t vp
, daddr64_t blkno
, int size
, daddr64_t
*rablks
, int *rasizes
, int nrablks
, kauth_cred_t cred
, buf_t
*bpp
)
1745 return (do_breadn_for_type(vp
, blkno
, size
, rablks
, rasizes
, nrablks
, cred
, bpp
, BLK_READ
));
1749 * Read-ahead multiple disk blocks. The first is sync, the rest async.
1750 * [buf_breadn() for meta-data]
1753 buf_meta_breadn(vnode_t vp
, daddr64_t blkno
, int size
, daddr64_t
*rablks
, int *rasizes
, int nrablks
, kauth_cred_t cred
, buf_t
*bpp
)
1755 return (do_breadn_for_type(vp
, blkno
, size
, rablks
, rasizes
, nrablks
, cred
, bpp
, BLK_META
));
1759 * Block write. Described in Bach (p.56)
1762 buf_bwrite(buf_t bp
)
1764 int sync
, wasdelayed
;
1766 proc_t p
= current_proc();
1767 vnode_t vp
= bp
->b_vp
;
1769 if (bp
->b_datap
== 0) {
1770 if (brecover_data(bp
) == 0)
1773 /* Remember buffer type, to switch on it later. */
1774 sync
= !ISSET(bp
->b_flags
, B_ASYNC
);
1775 wasdelayed
= ISSET(bp
->b_flags
, B_DELWRI
);
1776 CLR(bp
->b_flags
, (B_READ
| B_DONE
| B_ERROR
| B_DELWRI
));
1779 OSAddAtomicLong(-1, &nbdwrite
);
1783 * If not synchronous, pay for the I/O operation and make
1784 * sure the buf is on the correct vnode queue. We have
1785 * to do this now, because if we don't, the vnode may not
1786 * be properly notified that its I/O has completed.
1789 buf_reassign(bp
, vp
);
1791 if (p
&& p
->p_stats
)
1792 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_oublock
); /* XXX */
1794 trace(TR_BUFWRITE
, pack(vp
, bp
->b_bcount
), bp
->b_lblkno
);
1796 /* Initiate disk write. Make sure the appropriate party is charged. */
1798 OSAddAtomic(1, &vp
->v_numoutput
);
1804 * If I/O was synchronous, wait for it to complete.
1806 rv
= buf_biowait(bp
);
1809 * Pay for the I/O operation, if it's not been paid for, and
1810 * make sure it's on the correct vnode queue. (async operatings
1811 * were payed for above.)
1814 buf_reassign(bp
, vp
);
1816 if (p
&& p
->p_stats
)
1817 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_oublock
); /* XXX */
1819 /* Release the buffer. */
1820 // XXXdbg - only if the unused bit is set
1821 if (!ISSET(bp
->b_flags
, B_NORELSE
)) {
1824 CLR(bp
->b_flags
, B_NORELSE
);
1834 vn_bwrite(struct vnop_bwrite_args
*ap
)
1836 return (buf_bwrite(ap
->a_bp
));
1842 * The buffer is marked dirty, but is not queued for I/O.
1843 * This routine should be used when the buffer is expected
1844 * to be modified again soon, typically a small write that
1845 * partially fills a buffer.
1847 * NB: magnetic tapes cannot be delayed; they must be
1848 * written in the order that the writes are requested.
1850 * Described in Leffler, et al. (pp. 208-213).
1852 * Note: With the ability to allocate additional buffer
1853 * headers, we can get in to the situation where "too" many
1854 * buf_bdwrite()s can create situation where the kernel can create
1855 * buffers faster than the disks can service. Doing a buf_bawrite() in
1856 * cases were we have "too many" outstanding buf_bdwrite()s avoids that.
1858 __private_extern__
int
1859 bdwrite_internal(buf_t bp
, int return_error
)
1861 proc_t p
= current_proc();
1862 vnode_t vp
= bp
->b_vp
;
1865 * If the block hasn't been seen before:
1866 * (1) Mark it as having been seen,
1867 * (2) Charge for the write.
1868 * (3) Make sure it's on its vnode's correct block list,
1870 if (!ISSET(bp
->b_flags
, B_DELWRI
)) {
1871 SET(bp
->b_flags
, B_DELWRI
);
1872 if (p
&& p
->p_stats
)
1873 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_oublock
); /* XXX */
1874 OSAddAtomicLong(1, &nbdwrite
);
1875 buf_reassign(bp
, vp
);
1879 * if we're not LOCKED, but the total number of delayed writes
1880 * has climbed above 75% of the total buffers in the system
1881 * return an error if the caller has indicated that it can
1882 * handle one in this case, otherwise schedule the I/O now
1883 * this is done to prevent us from allocating tons of extra
1884 * buffers when dealing with virtual disks (i.e. DiskImages),
1885 * because additional buffers are dynamically allocated to prevent
1886 * deadlocks from occurring
1888 * however, can't do a buf_bawrite() if the LOCKED bit is set because the
1889 * buffer is part of a transaction and can't go to disk until
1890 * the LOCKED bit is cleared.
1892 if (!ISSET(bp
->b_flags
, B_LOCKED
) && nbdwrite
> ((nbuf_headers
/4)*3)) {
1896 * If the vnode has "too many" write operations in progress
1897 * wait for them to finish the IO
1899 (void)vnode_waitforwrites(vp
, VNODE_ASYNC_THROTTLE
, 0, 0, "buf_bdwrite");
1901 return (buf_bawrite(bp
));
1904 /* Otherwise, the "write" is done, so mark and release the buffer. */
1905 SET(bp
->b_flags
, B_DONE
);
1911 buf_bdwrite(buf_t bp
)
1913 return (bdwrite_internal(bp
, 0));
1918 * Asynchronous block write; just an asynchronous buf_bwrite().
1920 * Note: With the abilitty to allocate additional buffer
1921 * headers, we can get in to the situation where "too" many
1922 * buf_bawrite()s can create situation where the kernel can create
1923 * buffers faster than the disks can service.
1924 * We limit the number of "in flight" writes a vnode can have to
1928 bawrite_internal(buf_t bp
, int throttle
)
1930 vnode_t vp
= bp
->b_vp
;
1935 * If the vnode has "too many" write operations in progress
1936 * wait for them to finish the IO
1938 (void)vnode_waitforwrites(vp
, VNODE_ASYNC_THROTTLE
, 0, 0, (const char *)"buf_bawrite");
1939 else if (vp
->v_numoutput
>= VNODE_ASYNC_THROTTLE
)
1941 * return to the caller and
1942 * let him decide what to do
1944 return (EWOULDBLOCK
);
1946 SET(bp
->b_flags
, B_ASYNC
);
1948 return (VNOP_BWRITE(bp
));
1952 buf_bawrite(buf_t bp
)
1954 return (bawrite_internal(bp
, 1));
1959 * Release a buffer on to the free lists.
1960 * Described in Bach (p. 46).
1963 buf_brelse(buf_t bp
)
1965 struct bqueues
*bufq
;
1968 int need_wakeup
= 0;
1969 int need_bp_wakeup
= 0;
1972 if (bp
->b_whichq
!= -1 || !(bp
->b_lflags
& BL_BUSY
))
1973 panic("buf_brelse: bad buffer = %p\n", bp
);
1976 (void) OSBacktrace(&bp
->b_stackbrelse
[0], 6);
1978 bp
->b_lastbrelse
= current_thread();
1981 if (bp
->b_lflags
& BL_IOBUF
) {
1986 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 388)) | DBG_FUNC_START
,
1987 bp
->b_lblkno
* PAGE_SIZE
, bp
, bp
->b_datap
,
1990 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
1993 * if we're invalidating a buffer that has the B_FILTER bit
1994 * set then call the b_iodone function so it gets cleaned
1997 * the HFS journal code depends on this
1999 if (ISSET(bp
->b_flags
, B_META
) && ISSET(bp
->b_flags
, B_INVAL
)) {
2000 if (ISSET(bp
->b_flags
, B_FILTER
)) { /* if necessary, call out */
2001 void (*iodone_func
)(struct buf
*, void *) = bp
->b_iodone
;
2002 void *arg
= (void *)bp
->b_transaction
;
2004 CLR(bp
->b_flags
, B_FILTER
); /* but note callout done */
2005 bp
->b_iodone
= NULL
;
2006 bp
->b_transaction
= NULL
;
2008 if (iodone_func
== NULL
) {
2009 panic("brelse: bp @ %p has NULL b_iodone!\n", bp
);
2011 (*iodone_func
)(bp
, arg
);
2015 * I/O is done. Cleanup the UPL state
2019 if ( !ISSET(bp
->b_flags
, B_META
) && UBCINFOEXISTS(bp
->b_vp
) && bp
->b_bufsize
) {
2023 if ( (upl
== NULL
) ) {
2024 if ( !ISSET(bp
->b_flags
, B_INVAL
)) {
2025 kret
= ubc_create_upl(bp
->b_vp
,
2026 ubc_blktooff(bp
->b_vp
, bp
->b_lblkno
),
2032 if (kret
!= KERN_SUCCESS
)
2033 panic("brelse: Failed to create UPL");
2035 upl_ubc_alias_set(upl
, (uintptr_t) bp
, (uintptr_t) 5);
2036 #endif /* UPL_DEBUG */
2040 kret
= ubc_upl_unmap(upl
);
2042 if (kret
!= KERN_SUCCESS
)
2043 panic("ubc_upl_unmap failed");
2044 bp
->b_datap
= (uintptr_t)NULL
;
2048 if (bp
->b_flags
& (B_ERROR
| B_INVAL
)) {
2049 if (bp
->b_flags
& (B_READ
| B_INVAL
))
2050 upl_flags
= UPL_ABORT_DUMP_PAGES
;
2054 ubc_upl_abort(upl
, upl_flags
);
2056 if (ISSET(bp
->b_flags
, B_DELWRI
| B_WASDIRTY
))
2057 upl_flags
= UPL_COMMIT_SET_DIRTY
;
2059 upl_flags
= UPL_COMMIT_CLEAR_DIRTY
;
2061 ubc_upl_commit_range(upl
, 0, bp
->b_bufsize
, upl_flags
|
2062 UPL_COMMIT_INACTIVATE
| UPL_COMMIT_FREE_ON_EMPTY
);
2068 panic("brelse: UPL set for non VREG; vp=%p", bp
->b_vp
);
2072 * If it's locked, don't report an error; try again later.
2074 if (ISSET(bp
->b_flags
, (B_LOCKED
|B_ERROR
)) == (B_LOCKED
|B_ERROR
))
2075 CLR(bp
->b_flags
, B_ERROR
);
2077 * If it's not cacheable, or an error, mark it invalid.
2079 if (ISSET(bp
->b_flags
, (B_NOCACHE
|B_ERROR
)))
2080 SET(bp
->b_flags
, B_INVAL
);
2082 if ((bp
->b_bufsize
<= 0) ||
2083 ISSET(bp
->b_flags
, B_INVAL
) ||
2084 (ISSET(bp
->b_lflags
, BL_WANTDEALLOC
) && !ISSET(bp
->b_flags
, B_DELWRI
))) {
2086 * If it's invalid or empty, dissociate it from its vnode,
2087 * release its storage if B_META, and
2088 * clean it up a bit and put it on the EMPTY queue
2090 if (ISSET(bp
->b_flags
, B_DELWRI
))
2091 OSAddAtomicLong(-1, &nbdwrite
);
2093 if (ISSET(bp
->b_flags
, B_META
)) {
2094 if (bp
->b_bufsize
) {
2095 if (ISSET(bp
->b_flags
, B_ZALLOC
)) {
2098 z
= getbufzone(bp
->b_bufsize
);
2099 zfree(z
, (void *)bp
->b_datap
);
2101 kmem_free(kernel_map
, bp
->b_datap
, bp
->b_bufsize
);
2103 bp
->b_datap
= (uintptr_t)NULL
;
2108 * nuke any credentials we were holding
2110 if (IS_VALID_CRED(bp
->b_rcred
)) {
2111 kauth_cred_unref(&bp
->b_rcred
);
2113 if (IS_VALID_CRED(bp
->b_wcred
)) {
2114 kauth_cred_unref(&bp
->b_wcred
);
2116 CLR(bp
->b_flags
, (B_META
| B_ZALLOC
| B_DELWRI
| B_LOCKED
| B_AGE
| B_ASYNC
| B_NOCACHE
| B_FUA
));
2118 bufq
= &bufqueues
[BQ_EMPTY
];
2119 bp
->b_whichq
= BQ_EMPTY
;
2121 lck_mtx_lock_spin(buf_mtxp
);
2128 binshash(bp
, &invalhash
);
2130 binsheadfree(bp
, bufq
, BQ_EMPTY
);
2133 * It has valid data. Put it on the end of the appropriate
2134 * queue, so that it'll stick around for as long as possible.
2136 if (ISSET(bp
->b_flags
, B_LOCKED
))
2137 whichq
= BQ_LOCKED
; /* locked in core */
2138 else if (ISSET(bp
->b_flags
, B_META
))
2139 whichq
= BQ_META
; /* meta-data */
2140 else if (ISSET(bp
->b_flags
, B_AGE
))
2141 whichq
= BQ_AGE
; /* stale but valid data */
2143 whichq
= BQ_LRU
; /* valid data */
2144 bufq
= &bufqueues
[whichq
];
2146 CLR(bp
->b_flags
, (B_AGE
| B_ASYNC
| B_NOCACHE
));
2147 bp
->b_whichq
= whichq
;
2148 bp
->b_timestamp
= buf_timestamp();
2150 lck_mtx_lock_spin(buf_mtxp
);
2152 binstailfree(bp
, bufq
, whichq
);
2156 * needbuffer is a global
2157 * we're currently using buf_mtxp to protect it
2158 * delay doing the actual wakeup until after
2164 if (ISSET(bp
->b_lflags
, BL_WANTED
)) {
2166 * delay the actual wakeup until after we
2167 * clear BL_BUSY and we've dropped buf_mtxp
2172 * Unlock the buffer.
2174 CLR(bp
->b_lflags
, (BL_BUSY
| BL_WANTED
));
2177 lck_mtx_unlock(buf_mtxp
);
2181 * Wake up any processes waiting for any buffer to become free.
2183 wakeup(&needbuffer
);
2185 if (need_bp_wakeup
) {
2187 * Wake up any proceeses waiting for _this_ buffer to become free.
2191 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 388)) | DBG_FUNC_END
,
2192 bp
, bp
->b_datap
, bp
->b_flags
, 0, 0);
2196 * Determine if a block is in the cache.
2197 * Just look on what would be its hash chain. If it's there, return
2198 * a pointer to it, unless it's marked invalid. If it's marked invalid,
2199 * we normally don't return the buffer, unless the caller explicitly
2203 incore(vnode_t vp
, daddr64_t blkno
)
2206 struct bufhashhdr
*dp
;
2208 dp
= BUFHASH(vp
, blkno
);
2210 lck_mtx_lock_spin(buf_mtxp
);
2212 if (incore_locked(vp
, blkno
, dp
))
2216 lck_mtx_unlock(buf_mtxp
);
2223 incore_locked(vnode_t vp
, daddr64_t blkno
, struct bufhashhdr
*dp
)
2227 /* Search hash chain */
2228 for (bp
= dp
->lh_first
; bp
!= NULL
; bp
= bp
->b_hash
.le_next
) {
2229 if (bp
->b_lblkno
== blkno
&& bp
->b_vp
== vp
&&
2230 !ISSET(bp
->b_flags
, B_INVAL
)) {
2238 /* XXX FIXME -- Update the comment to reflect the UBC changes (please) -- */
2240 * Get a block of requested size that is associated with
2241 * a given vnode and block offset. If it is found in the
2242 * block cache, mark it as having been found, make it busy
2243 * and return it. Otherwise, return an empty block of the
2244 * correct size. It is up to the caller to insure that the
2245 * cached blocks be of the correct size.
2248 buf_getblk(vnode_t vp
, daddr64_t blkno
, int size
, int slpflag
, int slptimeo
, int operation
)
2253 upl_page_info_t
*pl
;
2258 struct bufhashhdr
*dp
;
2260 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_START
,
2261 (uintptr_t)(blkno
* PAGE_SIZE
), size
, operation
, 0, 0);
2263 ret_only_valid
= operation
& BLK_ONLYVALID
;
2264 operation
&= ~BLK_ONLYVALID
;
2265 dp
= BUFHASH(vp
, blkno
);
2267 lck_mtx_lock_spin(buf_mtxp
);
2269 if ((bp
= incore_locked(vp
, blkno
, dp
))) {
2271 * Found in the Buffer Cache
2273 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
2277 switch (operation
) {
2281 SET(bp
->b_lflags
, BL_WANTED
);
2282 bufstats
.bufs_busyincore
++;
2285 * don't retake the mutex after being awakened...
2286 * the time out is in msecs
2288 ts
.tv_sec
= (slptimeo
/1000);
2289 ts
.tv_nsec
= (slptimeo
% 1000) * 10 * NSEC_PER_USEC
* 1000;
2291 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 396)) | DBG_FUNC_NONE
,
2292 (uintptr_t)blkno
, size
, operation
, 0, 0);
2294 err
= msleep(bp
, buf_mtxp
, slpflag
| PDROP
| (PRIBIO
+ 1), "buf_getblk", &ts
);
2297 * Callers who call with PCATCH or timeout are
2298 * willing to deal with the NULL pointer
2300 if (err
&& ((slpflag
& PCATCH
) || ((err
== EWOULDBLOCK
) && slptimeo
)))
2308 * unknown operation requested
2310 panic("getblk: paging or unknown operation for incore busy buffer - %x\n", operation
);
2316 * buffer in core and not busy
2318 SET(bp
->b_lflags
, BL_BUSY
);
2319 SET(bp
->b_flags
, B_CACHE
);
2322 bremfree_locked(bp
);
2323 bufstats
.bufs_incore
++;
2325 lck_mtx_unlock(buf_mtxp
);
2327 bp
->b_owner
= current_thread();
2331 panic("buffer has UPL, but not marked BUSY: %p", bp
);
2333 if ( !ret_only_valid
&& bp
->b_bufsize
!= size
)
2337 switch (operation
) {
2340 * "write" operation: let the UPL subsystem
2341 * know that we intend to modify the buffer
2342 * cache pages we're gathering.
2344 upl_flags
|= UPL_WILL_MODIFY
;
2346 upl_flags
|= UPL_PRECIOUS
;
2347 if (UBCINFOEXISTS(bp
->b_vp
) && bp
->b_bufsize
) {
2348 kret
= ubc_create_upl(vp
,
2349 ubc_blktooff(vp
, bp
->b_lblkno
),
2354 if (kret
!= KERN_SUCCESS
)
2355 panic("Failed to create UPL");
2359 if (upl_valid_page(pl
, 0)) {
2360 if (upl_dirty_page(pl
, 0))
2361 SET(bp
->b_flags
, B_WASDIRTY
);
2363 CLR(bp
->b_flags
, B_WASDIRTY
);
2365 CLR(bp
->b_flags
, (B_DONE
| B_CACHE
| B_WASDIRTY
| B_DELWRI
));
2367 kret
= ubc_upl_map(upl
, (vm_offset_t
*)&(bp
->b_datap
));
2369 if (kret
!= KERN_SUCCESS
)
2370 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
2376 * VM is not involved in IO for the meta data
2377 * buffer already has valid data
2382 panic("getblk: paging or unknown operation for incore buffer- %d\n", operation
);
2387 } else { /* not incore() */
2388 int queue
= BQ_EMPTY
; /* Start with no preference */
2390 if (ret_only_valid
) {
2391 lck_mtx_unlock(buf_mtxp
);
2394 if ((vnode_isreg(vp
) == 0) || (UBCINFOEXISTS(vp
) == 0) /*|| (vnode_issystem(vp) == 1)*/)
2395 operation
= BLK_META
;
2397 if ((bp
= getnewbuf(slpflag
, slptimeo
, &queue
)) == NULL
)
2401 * getnewbuf may block for a number of different reasons...
2402 * if it does, it's then possible for someone else to
2403 * create a buffer for the same block and insert it into
2404 * the hash... if we see it incore at this point we dump
2405 * the buffer we were working on and start over
2407 if (incore_locked(vp
, blkno
, dp
)) {
2408 SET(bp
->b_flags
, B_INVAL
);
2409 binshash(bp
, &invalhash
);
2411 lck_mtx_unlock(buf_mtxp
);
2417 * NOTE: YOU CAN NOT BLOCK UNTIL binshash() HAS BEEN
2418 * CALLED! BE CAREFUL.
2422 * mark the buffer as B_META if indicated
2423 * so that when buffer is released it will goto META queue
2425 if (operation
== BLK_META
)
2426 SET(bp
->b_flags
, B_META
);
2428 bp
->b_blkno
= bp
->b_lblkno
= blkno
;
2432 * Insert in the hash so that incore() can find it
2434 binshash(bp
, BUFHASH(vp
, blkno
));
2436 bgetvp_locked(vp
, bp
);
2438 lck_mtx_unlock(buf_mtxp
);
2443 switch (operation
) {
2446 * buffer data is invalid...
2448 * I don't want to have to retake buf_mtxp,
2449 * so the miss and vmhits counters are done
2450 * with Atomic updates... all other counters
2451 * in bufstats are protected with either
2452 * buf_mtxp or iobuffer_mtxp
2454 OSAddAtomicLong(1, &bufstats
.bufs_miss
);
2459 * "write" operation: let the UPL subsystem know
2460 * that we intend to modify the buffer cache pages
2463 upl_flags
|= UPL_WILL_MODIFY
;
2466 size_t contig_bytes
;
2470 panic("bp already has UPL: %p",bp
);
2472 f_offset
= ubc_blktooff(vp
, blkno
);
2474 upl_flags
|= UPL_PRECIOUS
;
2475 kret
= ubc_create_upl(vp
,
2482 if (kret
!= KERN_SUCCESS
)
2483 panic("Failed to create UPL");
2485 upl_ubc_alias_set(upl
, (uintptr_t) bp
, (uintptr_t) 4);
2486 #endif /* UPL_DEBUG */
2489 if (upl_valid_page(pl
, 0)) {
2491 if (operation
== BLK_READ
)
2492 bmap_flags
= VNODE_READ
;
2494 bmap_flags
= VNODE_WRITE
;
2496 SET(bp
->b_flags
, B_CACHE
| B_DONE
);
2498 OSAddAtomicLong(1, &bufstats
.bufs_vmhits
);
2503 if (upl_dirty_page(pl
, 0)) {
2505 SET(bp
->b_flags
, B_WASDIRTY
);
2507 bp
->b_validend
= bp
->b_bcount
;
2508 bp
->b_dirtyend
= bp
->b_bcount
;
2511 bp
->b_validend
= bp
->b_bcount
;
2515 * try to recreate the physical block number associated with
2518 if (VNOP_BLOCKMAP(vp
, f_offset
, bp
->b_bcount
, &bp
->b_blkno
, &contig_bytes
, NULL
, bmap_flags
, NULL
))
2519 panic("getblk: VNOP_BLOCKMAP failed");
2521 * if the extent represented by this buffer
2522 * is not completely physically contiguous on
2523 * disk, than we can't cache the physical mapping
2524 * in the buffer header
2526 if ((long)contig_bytes
< bp
->b_bcount
)
2527 bp
->b_blkno
= bp
->b_lblkno
;
2529 OSAddAtomicLong(1, &bufstats
.bufs_miss
);
2531 kret
= ubc_upl_map(upl
, (vm_offset_t
*)&(bp
->b_datap
));
2533 if (kret
!= KERN_SUCCESS
)
2534 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
2538 panic("getblk: paging or unknown operation - %x", operation
);
2543 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_END
,
2544 bp
, bp
->b_datap
, bp
->b_flags
, 3, 0);
2547 (void) OSBacktrace(&bp
->b_stackgetblk
[0], 6);
2553 * Get an empty, disassociated buffer of given size.
2556 buf_geteblk(int size
)
2559 int queue
= BQ_EMPTY
;
2562 lck_mtx_lock_spin(buf_mtxp
);
2564 bp
= getnewbuf(0, 0, &queue
);
2565 } while (bp
== NULL
);
2567 SET(bp
->b_flags
, (B_META
|B_INVAL
));
2570 assert(queue
== BQ_EMPTY
);
2571 #endif /* DIAGNOSTIC */
2572 /* XXX need to implement logic to deal with other queues */
2574 binshash(bp
, &invalhash
);
2575 bufstats
.bufs_eblk
++;
2577 lck_mtx_unlock(buf_mtxp
);
2586 * With UBC, there is no need to expand / shrink the file data
2587 * buffer. The VM uses the same pages, hence no waste.
2588 * All the file data buffers can have one size.
2589 * In fact expand / shrink would be an expensive operation.
2591 * Only exception to this is meta-data buffers. Most of the
2592 * meta data operations are smaller than PAGE_SIZE. Having the
2593 * meta-data buffers grow and shrink as needed, optimizes use
2594 * of the kernel wired memory.
2598 allocbuf(buf_t bp
, int size
)
2600 vm_size_t desired_size
;
2602 desired_size
= roundup(size
, CLBYTES
);
2604 if (desired_size
< PAGE_SIZE
)
2605 desired_size
= PAGE_SIZE
;
2606 if (desired_size
> MAXBSIZE
)
2607 panic("allocbuf: buffer larger than MAXBSIZE requested");
2609 if (ISSET(bp
->b_flags
, B_META
)) {
2611 int nsize
= roundup(size
, MINMETA
);
2614 vm_offset_t elem
= (vm_offset_t
)bp
->b_datap
;
2616 if (ISSET(bp
->b_flags
, B_ZALLOC
)) {
2617 if (bp
->b_bufsize
< nsize
) {
2618 /* reallocate to a bigger size */
2620 zprev
= getbufzone(bp
->b_bufsize
);
2621 if (nsize
<= MAXMETA
) {
2622 desired_size
= nsize
;
2623 z
= getbufzone(nsize
);
2624 /* b_datap not really a ptr */
2625 *(void **)(&bp
->b_datap
) = zalloc(z
);
2627 bp
->b_datap
= (uintptr_t)NULL
;
2628 kmem_alloc_kobject(kernel_map
, (vm_offset_t
*)&bp
->b_datap
, desired_size
);
2629 CLR(bp
->b_flags
, B_ZALLOC
);
2631 bcopy((void *)elem
, (caddr_t
)bp
->b_datap
, bp
->b_bufsize
);
2632 zfree(zprev
, (void *)elem
);
2634 desired_size
= bp
->b_bufsize
;
2638 if ((vm_size_t
)bp
->b_bufsize
< desired_size
) {
2639 /* reallocate to a bigger size */
2640 bp
->b_datap
= (uintptr_t)NULL
;
2641 kmem_alloc_kobject(kernel_map
, (vm_offset_t
*)&bp
->b_datap
, desired_size
);
2642 bcopy((const void *)elem
, (caddr_t
)bp
->b_datap
, bp
->b_bufsize
);
2643 kmem_free(kernel_map
, elem
, bp
->b_bufsize
);
2645 desired_size
= bp
->b_bufsize
;
2649 /* new allocation */
2650 if (nsize
<= MAXMETA
) {
2651 desired_size
= nsize
;
2652 z
= getbufzone(nsize
);
2653 /* b_datap not really a ptr */
2654 *(void **)(&bp
->b_datap
) = zalloc(z
);
2655 SET(bp
->b_flags
, B_ZALLOC
);
2657 kmem_alloc_kobject(kernel_map
, (vm_offset_t
*)&bp
->b_datap
, desired_size
);
2660 if (bp
->b_datap
== 0)
2661 panic("allocbuf: NULL b_datap");
2663 bp
->b_bufsize
= desired_size
;
2664 bp
->b_bcount
= size
;
2670 * Get a new buffer from one of the free lists.
2672 * Request for a queue is passes in. The queue from which the buffer was taken
2673 * from is returned. Out of range queue requests get BQ_EMPTY. Request for
2674 * BQUEUE means no preference. Use heuristics in that case.
2675 * Heuristics is as follows:
2676 * Try BQ_AGE, BQ_LRU, BQ_EMPTY, BQ_META in that order.
2677 * If none available block till one is made available.
2678 * If buffers available on both BQ_AGE and BQ_LRU, check the timestamps.
2679 * Pick the most stale buffer.
2680 * If found buffer was marked delayed write, start the async. write
2681 * and restart the search.
2682 * Initialize the fields and disassociate the buffer from the vnode.
2683 * Remove the buffer from the hash. Return the buffer and the queue
2684 * on which it was found.
2686 * buf_mtxp is held upon entry
2687 * returns with buf_mtxp locked if new buf available
2688 * returns with buf_mtxp UNlocked if new buf NOT available
2692 getnewbuf(int slpflag
, int slptimeo
, int * queue
)
2698 int age_time
, lru_time
, bp_time
, meta_time
;
2699 int req
= *queue
; /* save it for restarts */
2704 * invalid request gets empty queue
2706 if ((*queue
>= BQUEUES
) || (*queue
< 0)
2707 || (*queue
== BQ_LAUNDRY
) || (*queue
== BQ_LOCKED
))
2711 if (*queue
== BQ_EMPTY
&& (bp
= bufqueues
[*queue
].tqh_first
))
2715 * need to grow number of bufs, add another one rather than recycling
2717 if (nbuf_headers
< max_nbuf_headers
) {
2719 * Increment count now as lock
2720 * is dropped for allocation.
2721 * That avoids over commits
2726 /* Try for the requested queue first */
2727 bp
= bufqueues
[*queue
].tqh_first
;
2731 /* Unable to use requested queue */
2732 age_bp
= bufqueues
[BQ_AGE
].tqh_first
;
2733 lru_bp
= bufqueues
[BQ_LRU
].tqh_first
;
2734 meta_bp
= bufqueues
[BQ_META
].tqh_first
;
2736 if (!age_bp
&& !lru_bp
&& !meta_bp
) {
2738 * Unavailble on AGE or LRU or META queues
2739 * Try the empty list first
2741 bp
= bufqueues
[BQ_EMPTY
].tqh_first
;
2747 * We have seen is this is hard to trigger.
2748 * This is an overcommit of nbufs but needed
2749 * in some scenarios with diskiamges
2753 lck_mtx_unlock(buf_mtxp
);
2755 /* Create a new temporary buffer header */
2756 bp
= (struct buf
*)zalloc(buf_hdr_zone
);
2760 bp
->b_whichq
= BQ_EMPTY
;
2761 bp
->b_timestamp
= buf_timestamp();
2763 SET(bp
->b_flags
, B_HDRALLOC
);
2766 lck_mtx_lock_spin(buf_mtxp
);
2769 binshash(bp
, &invalhash
);
2770 binsheadfree(bp
, &bufqueues
[BQ_EMPTY
], BQ_EMPTY
);
2774 /* subtract already accounted bufcount */
2777 bufstats
.bufs_sleeps
++;
2779 /* wait for a free buffer of any kind */
2781 /* hz value is 100 */
2782 ts
.tv_sec
= (slptimeo
/1000);
2783 /* the hz value is 100; which leads to 10ms */
2784 ts
.tv_nsec
= (slptimeo
% 1000) * NSEC_PER_USEC
* 1000 * 10;
2786 msleep(&needbuffer
, buf_mtxp
, slpflag
| PDROP
| (PRIBIO
+1), "getnewbuf", &ts
);
2790 /* Buffer available either on AGE or LRU or META */
2794 /* Buffer available either on AGE or LRU */
2798 } else if (!lru_bp
) {
2801 } else { /* buffer available on both AGE and LRU */
2802 int t
= buf_timestamp();
2804 age_time
= t
- age_bp
->b_timestamp
;
2805 lru_time
= t
- lru_bp
->b_timestamp
;
2806 if ((age_time
< 0) || (lru_time
< 0)) { /* time set backwards */
2810 * we should probably re-timestamp eveything in the
2811 * queues at this point with the current time
2814 if ((lru_time
>= lru_is_stale
) && (age_time
< age_is_stale
)) {
2824 if (!bp
) { /* Neither on AGE nor on LRU */
2827 } else if (meta_bp
) {
2828 int t
= buf_timestamp();
2830 bp_time
= t
- bp
->b_timestamp
;
2831 meta_time
= t
- meta_bp
->b_timestamp
;
2833 if (!(bp_time
< 0) && !(meta_time
< 0)) {
2834 /* time not set backwards */
2836 bp_is_stale
= (*queue
== BQ_LRU
) ?
2837 lru_is_stale
: age_is_stale
;
2839 if ((meta_time
>= meta_is_stale
) &&
2840 (bp_time
< bp_is_stale
)) {
2847 if (ISSET(bp
->b_flags
, B_LOCKED
) || ISSET(bp
->b_lflags
, BL_BUSY
))
2848 panic("getnewbuf: bp @ %p is LOCKED or BUSY! (flags 0x%x)\n", bp
, bp
->b_flags
);
2851 if (bcleanbuf(bp
, FALSE
)) {
2853 * moved to the laundry thread, buffer not ready
2864 * Returns 0 is buffer is ready to use,
2865 * Returns 1 if issued a buf_bawrite() to indicate
2866 * that the buffer is not ready.
2868 * buf_mtxp is held upon entry
2869 * returns with buf_mtxp locked
2872 bcleanbuf(buf_t bp
, boolean_t discard
)
2874 /* Remove from the queue */
2875 bremfree_locked(bp
);
2878 bp
->b_owner
= current_thread();
2882 * If buffer was a delayed write, start the IO by queuing
2883 * it on the LAUNDRY queue, and return 1
2885 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
2887 SET(bp
->b_lflags
, BL_WANTDEALLOC
);
2890 bp
->b_whichq
= BQ_LAUNDRY
;
2891 bp
->b_timestamp
= buf_timestamp();
2892 binstailfree(bp
, &bufqueues
[BQ_LAUNDRY
], BQ_LAUNDRY
);
2895 lck_mtx_unlock(buf_mtxp
);
2897 wakeup(&bufqueues
[BQ_LAUNDRY
]);
2899 * and give it a chance to run
2901 (void)thread_block(THREAD_CONTINUE_NULL
);
2903 lck_mtx_lock_spin(buf_mtxp
);
2908 bp
->b_owner
= current_thread();
2912 * Buffer is no longer on any free list... we own it
2914 SET(bp
->b_lflags
, BL_BUSY
);
2920 * disassociate us from our vnode, if we had one...
2925 lck_mtx_unlock(buf_mtxp
);
2929 if (ISSET(bp
->b_flags
, B_META
)) {
2932 elem
= (vm_offset_t
)bp
->b_datap
;
2933 bp
->b_datap
= (uintptr_t)0xdeadbeef;
2935 if (ISSET(bp
->b_flags
, B_ZALLOC
)) {
2938 z
= getbufzone(bp
->b_bufsize
);
2939 zfree(z
, (void *)elem
);
2941 kmem_free(kernel_map
, elem
, bp
->b_bufsize
);
2944 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
2946 /* nuke any credentials we were holding */
2947 if (IS_VALID_CRED(bp
->b_rcred
)) {
2948 kauth_cred_unref(&bp
->b_rcred
);
2950 if (IS_VALID_CRED(bp
->b_wcred
)) {
2951 kauth_cred_unref(&bp
->b_wcred
);
2954 /* If discarding, just move to the empty queue */
2956 lck_mtx_lock_spin(buf_mtxp
);
2957 CLR(bp
->b_flags
, (B_META
| B_ZALLOC
| B_DELWRI
| B_LOCKED
| B_AGE
| B_ASYNC
| B_NOCACHE
| B_FUA
));
2958 bp
->b_whichq
= BQ_EMPTY
;
2959 binshash(bp
, &invalhash
);
2960 binsheadfree(bp
, &bufqueues
[BQ_EMPTY
], BQ_EMPTY
);
2961 CLR(bp
->b_lflags
, BL_BUSY
);
2964 /* Not discarding: clean up and prepare for reuse */
2966 bp
->b_datap
= (uintptr_t)NULL
;
2967 bp
->b_upl
= (void *)NULL
;
2969 * preserve the state of whether this buffer
2970 * was allocated on the fly or not...
2971 * the only other flag that should be set at
2972 * this point is BL_BUSY...
2975 bp
->b_owner
= current_thread();
2978 bp
->b_lflags
= BL_BUSY
;
2979 bp
->b_flags
= (bp
->b_flags
& B_HDRALLOC
);
2981 bp
->b_blkno
= bp
->b_lblkno
= 0;
2982 bp
->b_iodone
= NULL
;
2986 bp
->b_dirtyoff
= bp
->b_dirtyend
= 0;
2987 bp
->b_validoff
= bp
->b_validend
= 0;
2988 #ifdef CONFIG_PROTECT
2992 lck_mtx_lock_spin(buf_mtxp
);
3000 buf_invalblkno(vnode_t vp
, daddr64_t lblkno
, int flags
)
3004 struct bufhashhdr
*dp
;
3006 dp
= BUFHASH(vp
, lblkno
);
3009 lck_mtx_lock_spin(buf_mtxp
);
3011 if ((bp
= incore_locked(vp
, lblkno
, dp
)) == (struct buf
*)0) {
3012 lck_mtx_unlock(buf_mtxp
);
3015 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
3016 if ( !ISSET(flags
, BUF_WAIT
)) {
3017 lck_mtx_unlock(buf_mtxp
);
3020 SET(bp
->b_lflags
, BL_WANTED
);
3022 error
= msleep((caddr_t
)bp
, buf_mtxp
, PDROP
| (PRIBIO
+ 1), "buf_invalblkno", NULL
);
3029 bremfree_locked(bp
);
3030 SET(bp
->b_lflags
, BL_BUSY
);
3031 SET(bp
->b_flags
, B_INVAL
);
3034 bp
->b_owner
= current_thread();
3037 lck_mtx_unlock(buf_mtxp
);
3047 int need_wakeup
= 0;
3049 lck_mtx_lock_spin(buf_mtxp
);
3051 if (ISSET(bp
->b_lflags
, BL_WANTED
)) {
3053 * delay the actual wakeup until after we
3054 * clear BL_BUSY and we've dropped buf_mtxp
3059 bp
->b_owner
= current_thread();
3063 * Unlock the buffer.
3065 CLR(bp
->b_lflags
, (BL_BUSY
| BL_WANTED
));
3068 lck_mtx_unlock(buf_mtxp
);
3072 * Wake up any proceeses waiting for _this_ buffer to become free.
3080 buf_acquire(buf_t bp
, int flags
, int slpflag
, int slptimeo
) {
3083 lck_mtx_lock_spin(buf_mtxp
);
3085 error
= buf_acquire_locked(bp
, flags
, slpflag
, slptimeo
);
3087 lck_mtx_unlock(buf_mtxp
);
3094 buf_acquire_locked(buf_t bp
, int flags
, int slpflag
, int slptimeo
)
3099 if (ISSET(bp
->b_flags
, B_LOCKED
)) {
3100 if ((flags
& BAC_SKIP_LOCKED
))
3103 if ((flags
& BAC_SKIP_NONLOCKED
))
3106 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
3108 * since the lck_mtx_lock may block, the buffer
3109 * may become BUSY, so we need to
3110 * recheck for a NOWAIT request
3112 if (flags
& BAC_NOWAIT
)
3114 SET(bp
->b_lflags
, BL_WANTED
);
3116 /* the hz value is 100; which leads to 10ms */
3117 ts
.tv_sec
= (slptimeo
/100);
3118 ts
.tv_nsec
= (slptimeo
% 100) * 10 * NSEC_PER_USEC
* 1000;
3119 error
= msleep((caddr_t
)bp
, buf_mtxp
, slpflag
| (PRIBIO
+ 1), "buf_acquire", &ts
);
3125 if (flags
& BAC_REMOVE
)
3126 bremfree_locked(bp
);
3127 SET(bp
->b_lflags
, BL_BUSY
);
3131 bp
->b_owner
= current_thread();
3139 * Wait for operations on the buffer to complete.
3140 * When they do, extract and return the I/O's error value.
3143 buf_biowait(buf_t bp
)
3145 while (!ISSET(bp
->b_flags
, B_DONE
)) {
3147 lck_mtx_lock_spin(buf_mtxp
);
3149 if (!ISSET(bp
->b_flags
, B_DONE
)) {
3150 DTRACE_IO1(wait__start
, buf_t
, bp
);
3151 (void) msleep(bp
, buf_mtxp
, PDROP
| (PRIBIO
+1), "buf_biowait", NULL
);
3152 DTRACE_IO1(wait__done
, buf_t
, bp
);
3154 lck_mtx_unlock(buf_mtxp
);
3156 /* check for interruption of I/O (e.g. via NFS), then errors. */
3157 if (ISSET(bp
->b_flags
, B_EINTR
)) {
3158 CLR(bp
->b_flags
, B_EINTR
);
3160 } else if (ISSET(bp
->b_flags
, B_ERROR
))
3161 return (bp
->b_error
? bp
->b_error
: EIO
);
3167 * Wait for the callback operation on a B_CALL buffer to complete.
3170 buf_biowait_callback(buf_t bp
)
3172 while (!ISSET(bp
->b_lflags
, BL_CALLDONE
)) {
3174 lck_mtx_lock_spin(buf_mtxp
);
3176 if (!ISSET(bp
->b_lflags
, BL_CALLDONE
)) {
3177 DTRACE_IO1(wait__start
, buf_t
, bp
);
3178 (void) msleep(bp
, buf_mtxp
, PDROP
| (PRIBIO
+1), "buf_biowait", NULL
);
3179 DTRACE_IO1(wait__done
, buf_t
, bp
);
3181 lck_mtx_unlock(buf_mtxp
);
3186 * Mark I/O complete on a buffer.
3188 * If a callback has been requested, e.g. the pageout
3189 * daemon, do so. Otherwise, awaken waiting processes.
3191 * [ Leffler, et al., says on p.247:
3192 * "This routine wakes up the blocked process, frees the buffer
3193 * for an asynchronous write, or, for a request by the pagedaemon
3194 * process, invokes a procedure specified in the buffer structure" ]
3196 * In real life, the pagedaemon (or other system processes) wants
3197 * to do async stuff to, and doesn't want the buffer buf_brelse()'d.
3198 * (for swap pager, that puts swap buffers on the free lists (!!!),
3199 * for the vn device, that puts malloc'd buffers on the free lists!)
3201 extern struct timeval priority_IO_timestamp_for_root
;
3202 extern int hard_throttle_on_root
;
3205 buf_biodone(buf_t bp
)
3209 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 387)) | DBG_FUNC_START
,
3210 bp
, bp
->b_datap
, bp
->b_flags
, 0, 0);
3212 if (ISSET(bp
->b_flags
, B_DONE
))
3213 panic("biodone already");
3215 if (ISSET(bp
->b_flags
, B_ERROR
)) {
3219 if (bp
->b_vp
&& bp
->b_vp
->v_mount
) {
3220 mp
= bp
->b_vp
->v_mount
;
3225 if (mp
&& (bp
->b_flags
& B_READ
) == 0) {
3226 update_last_io_time(mp
);
3227 INCR_PENDING_IO(-(pending_io_t
)buf_count(bp
), mp
->mnt_pending_write_size
);
3229 INCR_PENDING_IO(-(pending_io_t
)buf_count(bp
), mp
->mnt_pending_read_size
);
3232 if (kdebug_enable
) {
3233 int code
= DKIO_DONE
;
3235 if (bp
->b_flags
& B_READ
)
3237 if (bp
->b_flags
& B_ASYNC
)
3240 if (bp
->b_flags
& B_META
)
3242 else if (bp
->b_flags
& B_PAGEIO
)
3243 code
|= DKIO_PAGING
;
3245 KERNEL_DEBUG_CONSTANT(FSDBG_CODE(DBG_DKRW
, code
) | DBG_FUNC_NONE
,
3246 bp
, (uintptr_t)bp
->b_vp
,
3247 bp
->b_resid
, bp
->b_error
, 0);
3249 if ((bp
->b_vp
!= NULLVP
) &&
3250 ((bp
->b_flags
& (B_IOSTREAMING
| B_PAGEIO
| B_READ
)) == (B_PAGEIO
| B_READ
)) &&
3251 (bp
->b_vp
->v_mount
->mnt_kern_flag
& MNTK_ROOTDEV
)) {
3252 microuptime(&priority_IO_timestamp_for_root
);
3253 hard_throttle_on_root
= 0;
3256 * I/O was done, so don't believe
3257 * the DIRTY state from VM anymore
3259 CLR(bp
->b_flags
, B_WASDIRTY
);
3260 DTRACE_IO1(done
, buf_t
, bp
);
3262 if (!ISSET(bp
->b_flags
, B_READ
) && !ISSET(bp
->b_flags
, B_RAW
))
3264 * wake up any writer's blocked
3265 * on throttle or waiting for I/O
3268 vnode_writedone(bp
->b_vp
);
3270 if (ISSET(bp
->b_flags
, (B_CALL
| B_FILTER
))) { /* if necessary, call out */
3271 void (*iodone_func
)(struct buf
*, void *) = bp
->b_iodone
;
3272 void *arg
= (void *)bp
->b_transaction
;
3273 int callout
= ISSET(bp
->b_flags
, B_CALL
);
3275 CLR(bp
->b_flags
, (B_CALL
| B_FILTER
)); /* filters and callouts are one-shot */
3276 bp
->b_iodone
= NULL
;
3277 bp
->b_transaction
= NULL
;
3279 if (iodone_func
== NULL
) {
3280 panic("biodone: bp @ %p has NULL b_iodone!\n", bp
);
3283 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
3284 (*iodone_func
)(bp
, arg
);
3287 int need_wakeup
= 0;
3290 * assumes that the callback function takes
3291 * ownership of the bp and deals with releasing it if necessary
3292 * BL_WANTED indicates that we've decided to wait on the
3293 * completion of this I/O in a synchronous manner... we
3294 * still call the callback function, but in addition we
3295 * will do a wakeup... BL_CALLDONE indicates that the callback
3296 * routine has completed and its ok for the waiter to take
3297 * 'ownership' of this bp back
3299 lck_mtx_lock_spin(buf_mtxp
);
3301 if (bp
->b_lflags
& BL_WANTED
) {
3302 CLR(bp
->b_lflags
, BL_WANTED
);
3305 SET(bp
->b_lflags
, BL_CALLDONE
);
3307 lck_mtx_unlock(buf_mtxp
);
3315 * in this case the call back function is acting
3316 * strictly as a filter... it does not take
3317 * ownership of the bp and is expecting us
3318 * to finish cleaning up... this is currently used
3319 * by the HFS journaling code
3322 if (ISSET(bp
->b_flags
, B_ASYNC
)) { /* if async, release it */
3323 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
3326 } else { /* or just wakeup the buffer */
3328 * by taking the mutex, we serialize
3329 * the buf owner calling buf_biowait so that we'll
3330 * only see him in one of 2 states...
3331 * state 1: B_DONE wasn't set and he's
3333 * state 2: he's blocked trying to take the
3334 * mutex before looking at B_DONE
3335 * BL_WANTED is cleared in case anyone else
3336 * is blocked waiting for the buffer... note
3337 * that we haven't cleared B_BUSY yet, so if
3338 * they do get to run, their going to re-set
3339 * BL_WANTED and go back to sleep
3341 lck_mtx_lock_spin(buf_mtxp
);
3343 CLR(bp
->b_lflags
, BL_WANTED
);
3344 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
3346 lck_mtx_unlock(buf_mtxp
);
3351 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 387)) | DBG_FUNC_END
,
3352 (uintptr_t)bp
, (uintptr_t)bp
->b_datap
, bp
->b_flags
, 0, 0);
3356 * Return a count of buffers on the "locked" queue.
3359 count_lock_queue(void)
3364 lck_mtx_lock_spin(buf_mtxp
);
3366 for (bp
= bufqueues
[BQ_LOCKED
].tqh_first
; bp
;
3367 bp
= bp
->b_freelist
.tqe_next
)
3369 lck_mtx_unlock(buf_mtxp
);
3375 * Return a count of 'busy' buffers. Used at the time of shutdown.
3378 count_busy_buffers(void)
3380 return buf_busycount
+ bufstats
.bufs_iobufinuse
;
3385 * Print out statistics on the current allocation of the buffer pool.
3386 * Can be enabled to print out on every ``sync'' by setting "syncprt"
3387 * in vfs_syscalls.c using sysctl.
3393 register struct buf
*bp
;
3394 register struct bqueues
*dp
;
3395 int counts
[MAXBSIZE
/CLBYTES
+1];
3396 static char *bname
[BQUEUES
] =
3397 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
3399 for (dp
= bufqueues
, i
= 0; dp
< &bufqueues
[BQUEUES
]; dp
++, i
++) {
3401 for (j
= 0; j
<= MAXBSIZE
/CLBYTES
; j
++)
3404 lck_mtx_lock(buf_mtxp
);
3406 for (bp
= dp
->tqh_first
; bp
; bp
= bp
->b_freelist
.tqe_next
) {
3407 counts
[bp
->b_bufsize
/CLBYTES
]++;
3410 lck_mtx_unlock(buf_mtxp
);
3412 printf("%s: total-%d", bname
[i
], count
);
3413 for (j
= 0; j
<= MAXBSIZE
/CLBYTES
; j
++)
3415 printf(", %d-%d", j
* CLBYTES
, counts
[j
]);
3419 #endif /* DIAGNOSTIC */
3421 #define NRESERVEDIOBUFS 64
3425 alloc_io_buf(vnode_t vp
, int priv
)
3429 lck_mtx_lock_spin(iobuffer_mtxp
);
3431 while (((niobuf_headers
- NRESERVEDIOBUFS
< bufstats
.bufs_iobufinuse
) && !priv
) ||
3432 (bp
= iobufqueue
.tqh_first
) == NULL
) {
3433 bufstats
.bufs_iobufsleeps
++;
3436 (void) msleep(&need_iobuffer
, iobuffer_mtxp
, PDROP
| (PRIBIO
+1), (const char *)"alloc_io_buf", NULL
);
3438 lck_mtx_lock_spin(iobuffer_mtxp
);
3440 TAILQ_REMOVE(&iobufqueue
, bp
, b_freelist
);
3442 bufstats
.bufs_iobufinuse
++;
3443 if (bufstats
.bufs_iobufinuse
> bufstats
.bufs_iobufmax
)
3444 bufstats
.bufs_iobufmax
= bufstats
.bufs_iobufinuse
;
3446 lck_mtx_unlock(iobuffer_mtxp
);
3449 * initialize various fields
3450 * we don't need to hold the mutex since the buffer
3451 * is now private... the vp should have a reference
3452 * on it and is not protected by this mutex in any event
3454 bp
->b_timestamp
= 0;
3459 bp
->b_lflags
= BL_BUSY
| BL_IOBUF
;
3460 bp
->b_blkno
= bp
->b_lblkno
= 0;
3462 bp
->b_owner
= current_thread();
3465 bp
->b_iodone
= NULL
;
3472 #ifdef CONFIG_PROTECT
3476 if (vp
&& (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
))
3477 bp
->b_dev
= vp
->v_rdev
;
3486 free_io_buf(buf_t bp
)
3488 int need_wakeup
= 0;
3491 * put buffer back on the head of the iobufqueue
3494 bp
->b_flags
= B_INVAL
;
3496 lck_mtx_lock_spin(iobuffer_mtxp
);
3498 binsheadfree(bp
, &iobufqueue
, -1);
3500 if (need_iobuffer
) {
3502 * Wake up any processes waiting because they need an io buffer
3504 * do the wakeup after we drop the mutex... it's possible that the
3505 * wakeup will be superfluous if need_iobuffer gets set again and
3506 * another thread runs this path, but it's highly unlikely, doesn't
3507 * hurt, and it means we don't hold up I/O progress if the wakeup blocks
3508 * trying to grab a task related lock...
3513 if (bufstats
.bufs_iobufinuse
<= 0)
3514 panic("free_io_buf: bp(%p) - bufstats.bufs_iobufinuse < 0", bp
);
3516 bufstats
.bufs_iobufinuse
--;
3518 lck_mtx_unlock(iobuffer_mtxp
);
3521 wakeup(&need_iobuffer
);
3528 lck_mtx_lock_spin(buf_mtxp
);
3532 buf_list_unlock(void)
3534 lck_mtx_unlock(buf_mtxp
);
3538 * If getnewbuf() calls bcleanbuf() on the same thread
3539 * there is a potential for stack overrun and deadlocks.
3540 * So we always handoff the work to a worker thread for completion
3545 bcleanbuf_thread_init(void)
3547 thread_t thread
= THREAD_NULL
;
3549 /* create worker thread */
3550 kernel_thread_start((thread_continue_t
)bcleanbuf_thread
, NULL
, &thread
);
3551 thread_deallocate(thread
);
3555 bcleanbuf_thread(void)
3562 lck_mtx_lock_spin(buf_mtxp
);
3564 while ( (bp
= TAILQ_FIRST(&bufqueues
[BQ_LAUNDRY
])) == NULL
) {
3565 (void)msleep((void *)&bufqueues
[BQ_LAUNDRY
], buf_mtxp
, PDROP
| PRIBIO
, "blaundry", NULL
);
3567 lck_mtx_lock_spin(buf_mtxp
);
3570 * Remove from the queue
3572 bremfree_locked(bp
);
3575 * Buffer is no longer on any free list
3577 SET(bp
->b_lflags
, BL_BUSY
);
3581 bp
->b_owner
= current_thread();
3585 lck_mtx_unlock(buf_mtxp
);
3589 error
= bawrite_internal(bp
, 0);
3592 bp
->b_whichq
= BQ_LAUNDRY
;
3593 bp
->b_timestamp
= buf_timestamp();
3595 lck_mtx_lock_spin(buf_mtxp
);
3597 binstailfree(bp
, &bufqueues
[BQ_LAUNDRY
], BQ_LAUNDRY
);
3600 /* we never leave a busy page on the laundary queue */
3601 CLR(bp
->b_lflags
, BL_BUSY
);
3604 bp
->b_owner
= current_thread();
3608 lck_mtx_unlock(buf_mtxp
);
3611 (void)tsleep((void *)&bufqueues
[BQ_LAUNDRY
], PRIBIO
, "blaundry", 1);
3614 (void)thread_block(THREAD_CONTINUE_NULL
);
3623 brecover_data(buf_t bp
)
3627 upl_page_info_t
*pl
;
3629 vnode_t vp
= bp
->b_vp
;
3633 if ( !UBCINFOEXISTS(vp
) || bp
->b_bufsize
== 0)
3636 upl_flags
= UPL_PRECIOUS
;
3637 if (! (buf_flags(bp
) & B_READ
)) {
3639 * "write" operation: let the UPL subsystem know
3640 * that we intend to modify the buffer cache pages we're
3643 upl_flags
|= UPL_WILL_MODIFY
;
3646 kret
= ubc_create_upl(vp
,
3647 ubc_blktooff(vp
, bp
->b_lblkno
),
3652 if (kret
!= KERN_SUCCESS
)
3653 panic("Failed to create UPL");
3655 for (upl_offset
= 0; upl_offset
< bp
->b_bufsize
; upl_offset
+= PAGE_SIZE
) {
3657 if (!upl_valid_page(pl
, upl_offset
/ PAGE_SIZE
) || !upl_dirty_page(pl
, upl_offset
/ PAGE_SIZE
)) {
3658 ubc_upl_abort(upl
, 0);
3664 kret
= ubc_upl_map(upl
, (vm_offset_t
*)&(bp
->b_datap
));
3666 if (kret
!= KERN_SUCCESS
)
3667 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
3672 SET(bp
->b_flags
, B_INVAL
);
3679 buffer_cache_gc(int all
)
3682 boolean_t did_large_zfree
= FALSE
;
3683 int now
= buf_timestamp();
3685 int thresh_hold
= BUF_STALE_THRESHHOLD
;
3690 lck_mtx_lock_spin(buf_mtxp
);
3692 /* We only care about metadata (incore storage comes from zalloc()) */
3693 bp
= TAILQ_FIRST(&bufqueues
[BQ_META
]);
3695 /* Only collect buffers unused in the last N seconds. Note: ordered by timestamp. */
3696 while ((bp
!= NULL
) && ((now
- bp
->b_timestamp
) > thresh_hold
) && (all
|| (count
< BUF_MAX_GC_COUNT
))) {
3698 boolean_t is_zalloc
;
3700 size
= buf_size(bp
);
3701 is_zalloc
= ISSET(bp
->b_flags
, B_ZALLOC
);
3703 result
= bcleanbuf(bp
, TRUE
);
3704 if ((result
== 0) && is_zalloc
&& (size
>= PAGE_SIZE
)) {
3705 /* We've definitely freed at least a page to a zone */
3706 did_large_zfree
= TRUE
;
3708 bp
= TAILQ_FIRST(&bufqueues
[BQ_META
]);
3712 lck_mtx_unlock(buf_mtxp
);
3714 return did_large_zfree
;
3727 bp_cmp(void *a
, void *b
)
3729 buf_t
*bp_a
= *(buf_t
**)a
,
3730 *bp_b
= *(buf_t
**)b
;
3733 // don't have to worry about negative block
3734 // numbers so this is ok to do.
3736 res
= (bp_a
->b_blkno
- bp_b
->b_blkno
);
3743 bflushq(int whichq
, mount_t mp
)
3747 int total_writes
= 0;
3748 static buf_t flush_table
[NFLUSH
];
3750 if (whichq
< 0 || whichq
>= BQUEUES
) {
3755 lck_mtx_lock(buf_mtxp
);
3757 bp
= TAILQ_FIRST(&bufqueues
[whichq
]);
3759 for (buf_count
= 0; bp
; bp
= next
) {
3760 next
= bp
->b_freelist
.tqe_next
;
3762 if (bp
->b_vp
== NULL
|| bp
->b_vp
->v_mount
!= mp
) {
3766 if (ISSET(bp
->b_flags
, B_DELWRI
) && !ISSET(bp
->b_lflags
, BL_BUSY
)) {
3768 bremfree_locked(bp
);
3770 bp
->b_owner
= current_thread();
3773 SET(bp
->b_lflags
, BL_BUSY
);
3776 flush_table
[buf_count
] = bp
;
3780 if (buf_count
>= NFLUSH
) {
3781 lck_mtx_unlock(buf_mtxp
);
3783 qsort(flush_table
, buf_count
, sizeof(struct buf
*), bp_cmp
);
3785 for (i
= 0; i
< buf_count
; i
++) {
3786 buf_bawrite(flush_table
[i
]);
3792 lck_mtx_unlock(buf_mtxp
);
3794 if (buf_count
> 0) {
3795 qsort(flush_table
, buf_count
, sizeof(struct buf
*), bp_cmp
);
3797 for (i
= 0; i
< buf_count
; i
++) {
3798 buf_bawrite(flush_table
[i
]);
3802 return (total_writes
);
3809 /* XXX move this to a separate file */
3812 * NOTE: THIS CODE HAS NOT BEEN UPDATED
3813 * WITH RESPECT TO THE NEW LOCKING MODEL
3818 * Dynamic Scaling of the Buffer Queues
3821 typedef long long blsize_t
;
3823 blsize_t MAXNBUF
; /* initialize to (sane_size / PAGE_SIZE) */
3824 /* Global tunable limits */
3825 blsize_t nbufh
; /* number of buffer headers */
3826 blsize_t nbuflow
; /* minimum number of buffer headers required */
3827 blsize_t nbufhigh
; /* maximum number of buffer headers allowed */
3828 blsize_t nbuftarget
; /* preferred number of buffer headers */
3833 * 1. 0 < nbuflow <= nbufh <= nbufhigh
3834 * 2. nbufhigh <= MAXNBUF
3835 * 3. 0 < nbuflow <= nbuftarget <= nbufhigh
3836 * 4. nbufh can not be set by sysctl().
3839 /* Per queue tunable limits */
3842 blsize_t bl_nlow
; /* minimum number of buffer headers required */
3843 blsize_t bl_num
; /* number of buffer headers on the queue */
3844 blsize_t bl_nlhigh
; /* maximum number of buffer headers allowed */
3845 blsize_t bl_target
; /* preferred number of buffer headers */
3846 long bl_stale
; /* Seconds after which a buffer is considered stale */
3852 * 1. 0 <= bl_nlow <= bl_num <= bl_nlhigh
3853 * 2. bl_nlhigh <= MAXNBUF
3854 * 3. bufqlim[BQ_META].bl_nlow != 0
3855 * 4. bufqlim[BQ_META].bl_nlow > (number of possible concurrent
3856 * file system IO operations)
3857 * 5. bl_num can not be set by sysctl().
3858 * 6. bl_nhigh <= nbufhigh
3864 * Defining it blsize_t as long permits 2^31 buffer headers per queue.
3865 * Which can describe (2^31 * PAGE_SIZE) memory per queue.
3867 * These limits are exported to by means of sysctl().
3868 * It was decided to define blsize_t as a 64 bit quantity.
3869 * This will make sure that we will not be required to change it
3870 * as long as we do not exceed 64 bit address space for the kernel.
3872 * low and high numbers parameters initialized at compile time
3873 * and boot arguments can be used to override them. sysctl()
3874 * would not change the value. sysctl() can get all the values
3875 * but can set only target. num is the current level.
3877 * Advantages of having a "bufqscan" thread doing the balancing are,
3878 * Keep enough bufs on BQ_EMPTY.
3879 * getnewbuf() by default will always select a buffer from the BQ_EMPTY.
3880 * getnewbuf() perfoms best if a buffer was found there.
3881 * Also this minimizes the possibility of starting IO
3882 * from getnewbuf(). That's a performance win, too.
3884 * Localize complex logic [balancing as well as time aging]
3887 * Simplify getnewbuf() logic by elimination of time aging code.
3893 * The goal of the dynamic scaling of the buffer queues to to keep
3894 * the size of the LRU close to bl_target. Buffers on a queue would
3897 * There would be a thread which will be responsible for "balancing"
3898 * the buffer cache queues.
3900 * The scan order would be: AGE, LRU, META, EMPTY.
3903 long bufqscanwait
= 0;
3905 static void bufqscan_thread();
3906 static int balancebufq(int q
);
3907 static int btrimempty(int n
);
3908 static __inline__
int initbufqscan(void);
3909 static __inline__
int nextbufq(int q
);
3910 static void buqlimprt(int all
);
3913 static __inline__
void
3916 if ((q
< 0) || (q
>= BQUEUES
))
3919 bufqlim
[q
].bl_num
++;
3923 static __inline__
void
3926 if ((q
< 0) || (q
>= BQUEUES
))
3929 bufqlim
[q
].bl_num
--;
3934 bufq_balance_thread_init(void)
3936 thread_t thread
= THREAD_NULL
;
3938 if (bufqscanwait
++ == 0) {
3940 /* Initalize globals */
3941 MAXNBUF
= (sane_size
/ PAGE_SIZE
);
3942 nbufh
= nbuf_headers
;
3943 nbuflow
= min(nbufh
, 100);
3944 nbufhigh
= min(MAXNBUF
, max(nbufh
, 2048));
3945 nbuftarget
= (sane_size
>> 5) / PAGE_SIZE
;
3946 nbuftarget
= max(nbuflow
, nbuftarget
);
3947 nbuftarget
= min(nbufhigh
, nbuftarget
);
3950 * Initialize the bufqlim
3954 bufqlim
[BQ_LOCKED
].bl_nlow
= 0;
3955 bufqlim
[BQ_LOCKED
].bl_nlhigh
= 32;
3956 bufqlim
[BQ_LOCKED
].bl_target
= 0;
3957 bufqlim
[BQ_LOCKED
].bl_stale
= 30;
3960 bufqlim
[BQ_LRU
].bl_nlow
= 0;
3961 bufqlim
[BQ_LRU
].bl_nlhigh
= nbufhigh
/4;
3962 bufqlim
[BQ_LRU
].bl_target
= nbuftarget
/4;
3963 bufqlim
[BQ_LRU
].bl_stale
= LRU_IS_STALE
;
3966 bufqlim
[BQ_AGE
].bl_nlow
= 0;
3967 bufqlim
[BQ_AGE
].bl_nlhigh
= nbufhigh
/4;
3968 bufqlim
[BQ_AGE
].bl_target
= nbuftarget
/4;
3969 bufqlim
[BQ_AGE
].bl_stale
= AGE_IS_STALE
;
3972 bufqlim
[BQ_EMPTY
].bl_nlow
= 0;
3973 bufqlim
[BQ_EMPTY
].bl_nlhigh
= nbufhigh
/4;
3974 bufqlim
[BQ_EMPTY
].bl_target
= nbuftarget
/4;
3975 bufqlim
[BQ_EMPTY
].bl_stale
= 600000;
3978 bufqlim
[BQ_META
].bl_nlow
= 0;
3979 bufqlim
[BQ_META
].bl_nlhigh
= nbufhigh
/4;
3980 bufqlim
[BQ_META
].bl_target
= nbuftarget
/4;
3981 bufqlim
[BQ_META
].bl_stale
= META_IS_STALE
;
3984 bufqlim
[BQ_LOCKED
].bl_nlow
= 0;
3985 bufqlim
[BQ_LOCKED
].bl_nlhigh
= 32;
3986 bufqlim
[BQ_LOCKED
].bl_target
= 0;
3987 bufqlim
[BQ_LOCKED
].bl_stale
= 30;
3992 /* create worker thread */
3993 kernel_thread_start((thread_continue_t
)bufqscan_thread
, NULL
, &thread
);
3994 thread_deallocate(thread
);
3997 /* The workloop for the buffer balancing thread */
4005 int q
; /* buffer queue to process */
4009 moretodo
|= balancebufq(q
);
4018 (void)tsleep((void *)&bufqscanwait
, PRIBIO
, "bufqscanwait", 60 * hz
);
4023 /* Seed for the buffer queue balancing */
4024 static __inline__
int
4027 /* Start with AGE queue */
4031 /* Pick next buffer queue to balance */
4032 static __inline__
int
4035 int order
[] = { BQ_AGE
, BQ_LRU
, BQ_META
, BQ_EMPTY
, 0 };
4042 /* function to balance the buffer queues */
4049 /* reject invalid q */
4050 if ((q
< 0) || (q
>= BQUEUES
))
4053 /* LOCKED or LAUNDRY queue MUST not be balanced */
4054 if ((q
== BQ_LOCKED
) || (q
== BQ_LAUNDRY
))
4057 n
= (bufqlim
[q
].bl_num
- bufqlim
[q
].bl_target
);
4059 /* If queue has less than target nothing more to do */
4064 /* Balance only a small amount (12.5%) at a time */
4068 /* EMPTY queue needs special handling */
4069 if (q
== BQ_EMPTY
) {
4070 moretodo
|= btrimempty(n
);
4074 t
= buf_timestamp():
4076 for (; n
> 0; n
--) {
4077 struct buf
*bp
= bufqueues
[q
].tqh_first
;
4081 /* check if it's stale */
4082 if ((t
- bp
->b_timestamp
) > bufqlim
[q
].bl_stale
) {
4083 if (bcleanbuf(bp
, FALSE
)) {
4084 /* buf_bawrite() issued, bp not ready */
4087 /* release the cleaned buffer to BQ_EMPTY */
4088 SET(bp
->b_flags
, B_INVAL
);
4103 * When struct buf are allocated dynamically, this would
4104 * reclaim upto 'n' struct buf from the empty queue.
4114 static char *bname
[BQUEUES
] =
4115 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
4118 for (i
= 0; i
< BQUEUES
; i
++) {
4119 printf("%s : ", bname
[i
]);
4120 printf("min = %ld, ", (long)bufqlim
[i
].bl_nlow
);
4121 printf("cur = %ld, ", (long)bufqlim
[i
].bl_num
);
4122 printf("max = %ld, ", (long)bufqlim
[i
].bl_nlhigh
);
4123 printf("target = %ld, ", (long)bufqlim
[i
].bl_target
);
4124 printf("stale after %ld seconds\n", bufqlim
[i
].bl_stale
);
4127 for (i
= 0; i
< BQUEUES
; i
++) {
4128 printf("%s : ", bname
[i
]);
4129 printf("cur = %ld, ", (long)bufqlim
[i
].bl_num
);