2 * Copyright (c) 2000-2019 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/locks.h>
95 #include <kern/thread.h>
97 #include <sys/fslog.h> /* fslog_io_error() */
98 #include <sys/disk.h> /* dk_error_description_t */
100 #include <mach/mach_types.h>
101 #include <mach/memory_object_types.h>
102 #include <kern/sched_prim.h> /* thread_block() */
104 #include <vm/vm_kern.h>
105 #include <vm/vm_pageout.h>
107 #include <sys/kdebug.h>
109 #include <libkern/OSAtomic.h>
110 #include <libkern/OSDebug.h>
111 #include <sys/ubc_internal.h>
115 int bcleanbuf(buf_t bp
, boolean_t discard
);
116 static int brecover_data(buf_t bp
);
117 static boolean_t
incore(vnode_t vp
, daddr64_t blkno
);
118 /* timeout is in msecs */
119 static buf_t
getnewbuf(int slpflag
, int slptimeo
, int *queue
);
120 static void bremfree_locked(buf_t bp
);
121 static void buf_reassign(buf_t bp
, vnode_t newvp
);
122 static errno_t
buf_acquire_locked(buf_t bp
, int flags
, int slpflag
, int slptimeo
);
123 static int buf_iterprepare(vnode_t vp
, struct buflists
*, int flags
);
124 static void buf_itercomplete(vnode_t vp
, struct buflists
*, int flags
);
125 static boolean_t
buffer_cache_gc(int);
126 static buf_t
buf_brelse_shadow(buf_t bp
);
127 static void buf_free_meta_store(buf_t bp
);
129 static buf_t
buf_create_shadow_internal(buf_t bp
, boolean_t force_copy
,
130 uintptr_t external_storage
, void (*iodone
)(buf_t
, void *), void *arg
, int priv
);
133 int bdwrite_internal(buf_t
, int);
135 extern void disk_conditioner_delay(buf_t
, int, int, uint64_t);
137 /* zone allocated buffer headers */
138 static void bufzoneinit(void);
139 static void bcleanbuf_thread_init(void);
140 static void bcleanbuf_thread(void);
142 static zone_t buf_hdr_zone
;
143 static int buf_hdr_count
;
147 * Definitions for the buffer hash lists.
149 #define BUFHASH(dvp, lbn) \
150 (&bufhashtbl[((long)(dvp) / sizeof(*(dvp)) + (int)(lbn)) & bufhash])
151 LIST_HEAD(bufhashhdr
, buf
) * bufhashtbl
, invalhash
;
154 static buf_t
incore_locked(vnode_t vp
, daddr64_t blkno
, struct bufhashhdr
*dp
);
156 /* Definitions for the buffer stats. */
157 struct bufstats bufstats
;
159 /* Number of delayed write buffers */
162 static int boot_nbuf_headers
= 0;
164 static TAILQ_HEAD(delayqueue
, buf
) delaybufqueue
;
166 static TAILQ_HEAD(ioqueue
, buf
) iobufqueue
;
167 static TAILQ_HEAD(bqueues
, buf
) bufqueues
[BQUEUES
];
168 static int needbuffer
;
169 static int need_iobuffer
;
171 static lck_grp_t
*buf_mtx_grp
;
172 static lck_attr_t
*buf_mtx_attr
;
173 static lck_grp_attr_t
*buf_mtx_grp_attr
;
174 static lck_mtx_t
*iobuffer_mtxp
;
175 static lck_mtx_t
*buf_mtxp
;
176 static lck_mtx_t
*buf_gc_callout
;
178 static int buf_busycount
;
180 #define FS_BUFFER_CACHE_GC_CALLOUTS_MAX_SIZE 16
182 void (* callout
)(int, void *);
184 } fs_buffer_cache_gc_callout_t
;
186 fs_buffer_cache_gc_callout_t fs_callouts
[FS_BUFFER_CACHE_GC_CALLOUTS_MAX_SIZE
] = { {NULL
, NULL
} };
188 static __inline__
int
197 * Insq/Remq for the buffer free lists.
199 #define binsheadfree(bp, dp, whichq) do { \
200 TAILQ_INSERT_HEAD(dp, bp, b_freelist); \
203 #define binstailfree(bp, dp, whichq) do { \
204 TAILQ_INSERT_TAIL(dp, bp, b_freelist); \
207 #define BHASHENTCHECK(bp) \
208 if ((bp)->b_hash.le_prev != (struct buf **)0xdeadbeef) \
209 panic("%p: b_hash.le_prev is not deadbeef", (bp));
211 #define BLISTNONE(bp) \
212 (bp)->b_hash.le_next = (struct buf *)0; \
213 (bp)->b_hash.le_prev = (struct buf **)0xdeadbeef;
216 * Insq/Remq for the vnode usage lists.
218 #define bufinsvn(bp, dp) LIST_INSERT_HEAD(dp, bp, b_vnbufs)
219 #define bufremvn(bp) { \
220 LIST_REMOVE(bp, b_vnbufs); \
221 (bp)->b_vnbufs.le_next = NOLIST; \
225 * Time in seconds before a buffer on a list is
226 * considered as a stale buffer
228 #define LRU_IS_STALE 120 /* default value for the LRU */
229 #define AGE_IS_STALE 60 /* default value for the AGE */
230 #define META_IS_STALE 180 /* default value for the BQ_META */
232 int lru_is_stale
= LRU_IS_STALE
;
233 int age_is_stale
= AGE_IS_STALE
;
234 int meta_is_stale
= META_IS_STALE
;
236 #define MAXLAUNDRY 10
238 /* LIST_INSERT_HEAD() with assertions */
239 static __inline__
void
240 blistenterhead(struct bufhashhdr
* head
, buf_t bp
)
242 if ((bp
->b_hash
.le_next
= (head
)->lh_first
) != NULL
) {
243 (head
)->lh_first
->b_hash
.le_prev
= &(bp
)->b_hash
.le_next
;
245 (head
)->lh_first
= bp
;
246 bp
->b_hash
.le_prev
= &(head
)->lh_first
;
247 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef) {
248 panic("blistenterhead: le_prev is deadbeef");
252 static __inline__
void
253 binshash(buf_t bp
, struct bufhashhdr
*dp
)
257 #endif /* DIAGNOSTIC */
263 for (; nbp
!= NULL
; nbp
= nbp
->b_hash
.le_next
) {
265 panic("buf already in hashlist");
268 #endif /* DIAGNOSTIC */
270 blistenterhead(dp
, bp
);
273 static __inline__
void
276 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef) {
277 panic("bremhash le_prev is deadbeef");
279 if (bp
->b_hash
.le_next
== bp
) {
280 panic("bremhash: next points to self");
283 if (bp
->b_hash
.le_next
!= NULL
) {
284 bp
->b_hash
.le_next
->b_hash
.le_prev
= bp
->b_hash
.le_prev
;
286 *bp
->b_hash
.le_prev
= (bp
)->b_hash
.le_next
;
292 static __inline__
void
293 bmovelaundry(buf_t bp
)
295 bp
->b_whichq
= BQ_LAUNDRY
;
296 bp
->b_timestamp
= buf_timestamp();
297 binstailfree(bp
, &bufqueues
[BQ_LAUNDRY
], BQ_LAUNDRY
);
301 static __inline__
void
302 buf_release_credentials(buf_t bp
)
304 if (IS_VALID_CRED(bp
->b_rcred
)) {
305 kauth_cred_unref(&bp
->b_rcred
);
307 if (IS_VALID_CRED(bp
->b_wcred
)) {
308 kauth_cred_unref(&bp
->b_wcred
);
316 if ((bp
->b_flags
& (B_DONE
| B_DELWRI
))) {
323 buf_fromcache(buf_t bp
)
325 if ((bp
->b_flags
& B_CACHE
)) {
332 buf_markinvalid(buf_t bp
)
334 SET(bp
->b_flags
, B_INVAL
);
338 buf_markdelayed(buf_t bp
)
340 if (!ISSET(bp
->b_flags
, B_DELWRI
)) {
341 SET(bp
->b_flags
, B_DELWRI
);
343 OSAddAtomicLong(1, &nbdwrite
);
344 buf_reassign(bp
, bp
->b_vp
);
346 SET(bp
->b_flags
, B_DONE
);
350 buf_markclean(buf_t bp
)
352 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
353 CLR(bp
->b_flags
, B_DELWRI
);
355 OSAddAtomicLong(-1, &nbdwrite
);
356 buf_reassign(bp
, bp
->b_vp
);
361 buf_markeintr(buf_t bp
)
363 SET(bp
->b_flags
, B_EINTR
);
368 buf_markaged(buf_t bp
)
370 SET(bp
->b_flags
, B_AGE
);
376 if ((bp
->b_flags
& B_FUA
) == B_FUA
) {
383 buf_markfua(buf_t bp
)
385 SET(bp
->b_flags
, B_FUA
);
390 bufattr_cpx(bufattr_t bap
)
396 bufattr_setcpx(bufattr_t bap
, cpx_t cpx
)
402 buf_setcpoff(buf_t bp
, uint64_t foffset
)
404 bp
->b_attr
.ba_cp_file_off
= foffset
;
408 bufattr_cpoff(bufattr_t bap
)
410 return bap
->ba_cp_file_off
;
414 bufattr_setcpoff(bufattr_t bap
, uint64_t foffset
)
416 bap
->ba_cp_file_off
= foffset
;
419 #else // !CONTECT_PROTECT
422 bufattr_cpoff(bufattr_t bap __unused
)
428 bufattr_setcpoff(__unused bufattr_t bap
, __unused
uint64_t foffset
)
434 bufattr_cpx(__unused bufattr_t bap
)
440 bufattr_setcpx(__unused bufattr_t bap
, __unused
struct cpx
*cpx
)
444 #endif /* !CONFIG_PROTECT */
450 MALLOC(bap
, bufattr_t
, sizeof(struct bufattr
), M_TEMP
, M_WAITOK
);
455 bzero(bap
, sizeof(struct bufattr
));
460 bufattr_free(bufattr_t bap
)
468 bufattr_dup(bufattr_t bap
)
470 bufattr_t new_bufattr
;
471 MALLOC(new_bufattr
, bufattr_t
, sizeof(struct bufattr
), M_TEMP
, M_WAITOK
);
472 if (new_bufattr
== NULL
) {
476 /* Copy the provided one into the new copy */
477 memcpy(new_bufattr
, bap
, sizeof(struct bufattr
));
482 bufattr_rawencrypted(bufattr_t bap
)
484 if ((bap
->ba_flags
& BA_RAW_ENCRYPTED_IO
)) {
491 bufattr_throttled(bufattr_t bap
)
493 return GET_BUFATTR_IO_TIER(bap
);
497 bufattr_passive(bufattr_t bap
)
499 if ((bap
->ba_flags
& BA_PASSIVE
)) {
506 bufattr_nocache(bufattr_t bap
)
508 if ((bap
->ba_flags
& BA_NOCACHE
)) {
515 bufattr_meta(bufattr_t bap
)
517 if ((bap
->ba_flags
& BA_META
)) {
524 bufattr_markmeta(bufattr_t bap
)
526 SET(bap
->ba_flags
, BA_META
);
531 bufattr_delayidlesleep(bufattr_t bap
)
532 #else /* !CONFIG_EMBEDDED */
533 bufattr_delayidlesleep(__unused bufattr_t bap
)
534 #endif /* !CONFIG_EMBEDDED */
537 if ((bap
->ba_flags
& BA_DELAYIDLESLEEP
)) {
540 #endif /* !CONFIG_EMBEDDED */
551 buf_markstatic(buf_t bp __unused
)
553 SET(bp
->b_flags
, B_STATICCONTENT
);
559 if ((bp
->b_flags
& B_STATICCONTENT
)) {
566 bufattr_markgreedymode(bufattr_t bap
)
568 SET(bap
->ba_flags
, BA_GREEDY_MODE
);
572 bufattr_greedymode(bufattr_t bap
)
574 if ((bap
->ba_flags
& BA_GREEDY_MODE
)) {
581 bufattr_markisochronous(bufattr_t bap
)
583 SET(bap
->ba_flags
, BA_ISOCHRONOUS
);
587 bufattr_isochronous(bufattr_t bap
)
589 if ((bap
->ba_flags
& BA_ISOCHRONOUS
)) {
596 bufattr_markquickcomplete(bufattr_t bap
)
598 SET(bap
->ba_flags
, BA_QUICK_COMPLETE
);
602 bufattr_quickcomplete(bufattr_t bap
)
604 if ((bap
->ba_flags
& BA_QUICK_COMPLETE
)) {
611 bufattr_markioscheduled(bufattr_t bap
)
613 SET(bap
->ba_flags
, BA_IO_SCHEDULED
);
618 bufattr_ioscheduled(bufattr_t bap
)
620 if ((bap
->ba_flags
& BA_IO_SCHEDULED
)) {
633 buf_seterror(buf_t bp
, errno_t error
)
635 if ((bp
->b_error
= error
)) {
636 SET(bp
->b_flags
, B_ERROR
);
638 CLR(bp
->b_flags
, B_ERROR
);
643 buf_setflags(buf_t bp
, int32_t flags
)
645 SET(bp
->b_flags
, (flags
& BUF_X_WRFLAGS
));
649 buf_clearflags(buf_t bp
, int32_t flags
)
651 CLR(bp
->b_flags
, (flags
& BUF_X_WRFLAGS
));
657 return bp
->b_flags
& BUF_X_RDFLAGS
;
661 buf_reset(buf_t bp
, int32_t io_flags
)
663 CLR(bp
->b_flags
, (B_READ
| B_WRITE
| B_ERROR
| B_DONE
| B_INVAL
| B_ASYNC
| B_NOCACHE
| B_FUA
));
664 SET(bp
->b_flags
, (io_flags
& (B_ASYNC
| B_READ
| B_WRITE
| B_NOCACHE
)));
676 buf_setcount(buf_t bp
, uint32_t bcount
)
678 bp
->b_bcount
= bcount
;
684 return bp
->b_bufsize
;
688 buf_setsize(buf_t bp
, uint32_t bufsize
)
690 bp
->b_bufsize
= bufsize
;
700 buf_setresid(buf_t bp
, uint32_t resid
)
706 buf_dirtyoff(buf_t bp
)
708 return bp
->b_dirtyoff
;
712 buf_dirtyend(buf_t bp
)
714 return bp
->b_dirtyend
;
718 buf_setdirtyoff(buf_t bp
, uint32_t dirtyoff
)
720 bp
->b_dirtyoff
= dirtyoff
;
724 buf_setdirtyend(buf_t bp
, uint32_t dirtyend
)
726 bp
->b_dirtyend
= dirtyend
;
730 buf_dataptr(buf_t bp
)
736 buf_setdataptr(buf_t bp
, uintptr_t data
)
748 buf_setvnode(buf_t bp
, vnode_t vp
)
755 buf_callback(buf_t bp
)
757 if (!(bp
->b_flags
& B_CALL
)) {
758 return (void *) NULL
;
761 return (void *)bp
->b_iodone
;
766 buf_setcallback(buf_t bp
, void (*callback
)(buf_t
, void *), void *transaction
)
768 assert(!ISSET(bp
->b_flags
, B_FILTER
) && ISSET(bp
->b_lflags
, BL_BUSY
));
771 bp
->b_flags
|= (B_CALL
| B_ASYNC
);
773 bp
->b_flags
&= ~B_CALL
;
775 bp
->b_transaction
= transaction
;
776 bp
->b_iodone
= callback
;
782 buf_setupl(buf_t bp
, upl_t upl
, uint32_t offset
)
784 if (!(bp
->b_lflags
& BL_IOBUF
)) {
789 bp
->b_flags
|= B_CLUSTER
;
791 bp
->b_flags
&= ~B_CLUSTER
;
794 bp
->b_uploffset
= offset
;
800 buf_clone(buf_t bp
, int io_offset
, int io_size
, void (*iodone
)(buf_t
, void *), void *arg
)
804 if (io_offset
< 0 || io_size
< 0) {
808 if ((unsigned)(io_offset
+ io_size
) > (unsigned)bp
->b_bcount
) {
812 if (bp
->b_flags
& B_CLUSTER
) {
813 if (io_offset
&& ((bp
->b_uploffset
+ io_offset
) & PAGE_MASK
)) {
817 if (((bp
->b_uploffset
+ io_offset
+ io_size
) & PAGE_MASK
) && ((io_offset
+ io_size
) < bp
->b_bcount
)) {
821 io_bp
= alloc_io_buf(bp
->b_vp
, 0);
823 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
);
826 io_bp
->b_transaction
= arg
;
827 io_bp
->b_iodone
= iodone
;
828 io_bp
->b_flags
|= B_CALL
;
830 if (bp
->b_flags
& B_CLUSTER
) {
831 io_bp
->b_upl
= bp
->b_upl
;
832 io_bp
->b_uploffset
= bp
->b_uploffset
+ io_offset
;
834 io_bp
->b_datap
= (uintptr_t)(((char *)bp
->b_datap
) + io_offset
);
836 io_bp
->b_bcount
= io_size
;
845 if (bp
->b_lflags
& BL_SHADOW
) {
853 buf_create_shadow_priv(buf_t bp
, boolean_t force_copy
, uintptr_t external_storage
, void (*iodone
)(buf_t
, void *), void *arg
)
855 return buf_create_shadow_internal(bp
, force_copy
, external_storage
, iodone
, arg
, 1);
859 buf_create_shadow(buf_t bp
, boolean_t force_copy
, uintptr_t external_storage
, void (*iodone
)(buf_t
, void *), void *arg
)
861 return buf_create_shadow_internal(bp
, force_copy
, external_storage
, iodone
, arg
, 0);
866 buf_create_shadow_internal(buf_t bp
, boolean_t force_copy
, uintptr_t external_storage
, void (*iodone
)(buf_t
, void *), void *arg
, int priv
)
870 KERNEL_DEBUG(0xbbbbc000 | DBG_FUNC_START
, bp
, 0, 0, 0, 0);
872 if (!(bp
->b_flags
& B_META
) || (bp
->b_lflags
& BL_IOBUF
)) {
873 KERNEL_DEBUG(0xbbbbc000 | DBG_FUNC_END
, bp
, 0, 0, 0, 0);
876 #ifdef BUF_MAKE_PRIVATE
877 if (bp
->b_shadow_ref
&& bp
->b_data_ref
== 0 && external_storage
== 0) {
878 panic("buf_create_shadow: %p is in the private state (%d, %d)", bp
, bp
->b_shadow_ref
, bp
->b_data_ref
);
881 io_bp
= alloc_io_buf(bp
->b_vp
, priv
);
883 io_bp
->b_flags
= bp
->b_flags
& (B_META
| B_ZALLOC
| B_ASYNC
| B_READ
| B_FUA
);
884 io_bp
->b_blkno
= bp
->b_blkno
;
885 io_bp
->b_lblkno
= bp
->b_lblkno
;
888 io_bp
->b_transaction
= arg
;
889 io_bp
->b_iodone
= iodone
;
890 io_bp
->b_flags
|= B_CALL
;
892 if (force_copy
== FALSE
) {
893 io_bp
->b_bcount
= bp
->b_bcount
;
894 io_bp
->b_bufsize
= bp
->b_bufsize
;
896 if (external_storage
) {
897 io_bp
->b_datap
= external_storage
;
898 #ifdef BUF_MAKE_PRIVATE
899 io_bp
->b_data_store
= NULL
;
902 io_bp
->b_datap
= bp
->b_datap
;
903 #ifdef BUF_MAKE_PRIVATE
904 io_bp
->b_data_store
= bp
;
907 *(buf_t
*)(&io_bp
->b_orig
) = bp
;
909 lck_mtx_lock_spin(buf_mtxp
);
911 io_bp
->b_lflags
|= BL_SHADOW
;
912 io_bp
->b_shadow
= bp
->b_shadow
;
913 bp
->b_shadow
= io_bp
;
916 #ifdef BUF_MAKE_PRIVATE
917 if (external_storage
) {
918 io_bp
->b_lflags
|= BL_EXTERNAL
;
923 lck_mtx_unlock(buf_mtxp
);
925 if (external_storage
) {
926 #ifdef BUF_MAKE_PRIVATE
927 io_bp
->b_lflags
|= BL_EXTERNAL
;
929 io_bp
->b_bcount
= bp
->b_bcount
;
930 io_bp
->b_bufsize
= bp
->b_bufsize
;
931 io_bp
->b_datap
= external_storage
;
933 allocbuf(io_bp
, bp
->b_bcount
);
935 io_bp
->b_lflags
|= BL_IOBUF_ALLOC
;
937 bcopy((caddr_t
)bp
->b_datap
, (caddr_t
)io_bp
->b_datap
, bp
->b_bcount
);
939 #ifdef BUF_MAKE_PRIVATE
940 io_bp
->b_data_store
= NULL
;
943 KERNEL_DEBUG(0xbbbbc000 | DBG_FUNC_END
, bp
, bp
->b_shadow_ref
, 0, io_bp
, 0);
949 #ifdef BUF_MAKE_PRIVATE
951 buf_make_private(buf_t bp
)
957 KERNEL_DEBUG(0xbbbbc004 | DBG_FUNC_START
, bp
, bp
->b_shadow_ref
, 0, 0, 0);
959 if (bp
->b_shadow_ref
== 0 || bp
->b_data_ref
== 0 || ISSET(bp
->b_lflags
, BL_SHADOW
)) {
960 KERNEL_DEBUG(0xbbbbc004 | DBG_FUNC_END
, bp
, bp
->b_shadow_ref
, 0, EINVAL
, 0);
963 my_buf
.b_flags
= B_META
;
964 my_buf
.b_datap
= (uintptr_t)NULL
;
965 allocbuf(&my_buf
, bp
->b_bcount
);
967 bcopy((caddr_t
)bp
->b_datap
, (caddr_t
)my_buf
.b_datap
, bp
->b_bcount
);
969 lck_mtx_lock_spin(buf_mtxp
);
971 for (t_bp
= bp
->b_shadow
; t_bp
; t_bp
= t_bp
->b_shadow
) {
972 if (!ISSET(bp
->b_lflags
, BL_EXTERNAL
)) {
978 if (ds_bp
== NULL
&& bp
->b_data_ref
) {
979 panic("buf_make_private: b_data_ref != 0 && ds_bp == NULL");
982 if (ds_bp
&& (bp
->b_data_ref
== 0 || bp
->b_shadow_ref
== 0)) {
983 panic("buf_make_private: ref_count == 0 && ds_bp != NULL");
987 lck_mtx_unlock(buf_mtxp
);
989 buf_free_meta_store(&my_buf
);
991 KERNEL_DEBUG(0xbbbbc004 | DBG_FUNC_END
, bp
, bp
->b_shadow_ref
, 0, EINVAL
, 0);
994 for (t_bp
= bp
->b_shadow
; t_bp
; t_bp
= t_bp
->b_shadow
) {
995 if (!ISSET(t_bp
->b_lflags
, BL_EXTERNAL
)) {
996 t_bp
->b_data_store
= ds_bp
;
999 ds_bp
->b_data_ref
= bp
->b_data_ref
;
1002 bp
->b_datap
= my_buf
.b_datap
;
1004 lck_mtx_unlock(buf_mtxp
);
1006 KERNEL_DEBUG(0xbbbbc004 | DBG_FUNC_END
, bp
, bp
->b_shadow_ref
, 0, 0, 0);
1013 buf_setfilter(buf_t bp
, void (*filter
)(buf_t
, void *), void *transaction
,
1014 void(**old_iodone
)(buf_t
, void *), void **old_transaction
)
1016 assert(ISSET(bp
->b_lflags
, BL_BUSY
));
1019 *old_iodone
= bp
->b_iodone
;
1021 if (old_transaction
) {
1022 *old_transaction
= bp
->b_transaction
;
1025 bp
->b_transaction
= transaction
;
1026 bp
->b_iodone
= filter
;
1028 bp
->b_flags
|= B_FILTER
;
1030 bp
->b_flags
&= ~B_FILTER
;
1042 buf_lblkno(buf_t bp
)
1044 return bp
->b_lblkno
;
1048 buf_setblkno(buf_t bp
, daddr64_t blkno
)
1050 bp
->b_blkno
= blkno
;
1054 buf_setlblkno(buf_t bp
, daddr64_t lblkno
)
1056 bp
->b_lblkno
= lblkno
;
1060 buf_device(buf_t bp
)
1066 buf_setdevice(buf_t bp
, vnode_t vp
)
1068 if ((vp
->v_type
!= VBLK
) && (vp
->v_type
!= VCHR
)) {
1071 bp
->b_dev
= vp
->v_rdev
;
1078 buf_drvdata(buf_t bp
)
1080 return bp
->b_drvdata
;
1084 buf_setdrvdata(buf_t bp
, void *drvdata
)
1086 bp
->b_drvdata
= drvdata
;
1090 buf_fsprivate(buf_t bp
)
1092 return bp
->b_fsprivate
;
1096 buf_setfsprivate(buf_t bp
, void *fsprivate
)
1098 bp
->b_fsprivate
= fsprivate
;
1120 buf_uploffset(buf_t bp
)
1122 return (uint32_t)(bp
->b_uploffset
);
1133 buf_map(buf_t bp
, caddr_t
*io_addr
)
1139 if (!(bp
->b_flags
& B_CLUSTER
)) {
1140 *io_addr
= (caddr_t
)bp
->b_datap
;
1143 real_bp
= (buf_t
)(bp
->b_real_bp
);
1145 if (real_bp
&& real_bp
->b_datap
) {
1147 * b_real_bp is only valid if B_CLUSTER is SET
1148 * if it's non-zero, than someone did a cluster_bp call
1149 * if the backing physical pages were already mapped
1150 * in before the call to cluster_bp (non-zero b_datap),
1151 * than we just use that mapping
1153 *io_addr
= (caddr_t
)real_bp
->b_datap
;
1156 kret
= ubc_upl_map(bp
->b_upl
, &vaddr
); /* Map it in */
1158 if (kret
!= KERN_SUCCESS
) {
1163 vaddr
+= bp
->b_uploffset
;
1165 *io_addr
= (caddr_t
)vaddr
;
1176 if (!(bp
->b_flags
& B_CLUSTER
)) {
1180 * see buf_map for the explanation
1182 real_bp
= (buf_t
)(bp
->b_real_bp
);
1184 if (real_bp
&& real_bp
->b_datap
) {
1188 if ((bp
->b_lflags
& BL_IOBUF
) &&
1189 ((bp
->b_flags
& (B_PAGEIO
| B_READ
)) != (B_PAGEIO
| B_READ
))) {
1191 * ignore pageins... the 'right' thing will
1192 * happen due to the way we handle speculative
1195 * when we commit these pages, we'll hit
1196 * it with UPL_COMMIT_INACTIVE which
1197 * will clear the reference bit that got
1198 * turned on when we touched the mapping
1200 bp
->b_flags
|= B_AGE
;
1202 kret
= ubc_upl_unmap(bp
->b_upl
);
1204 if (kret
!= KERN_SUCCESS
) {
1216 if (buf_map(bp
, &baddr
) == 0) {
1217 bzero(baddr
, bp
->b_bcount
);
1224 * Read or write a buffer that is not contiguous on disk.
1225 * buffer is marked done/error at the conclusion
1228 buf_strategy_fragmented(vnode_t devvp
, buf_t bp
, off_t f_offset
, size_t contig_bytes
)
1230 vnode_t vp
= buf_vnode(bp
);
1231 buf_t io_bp
; /* For reading or writing a single block */
1234 size_t io_contig_bytes
;
1240 * save our starting point... the bp was already mapped
1241 * in buf_strategy before we got called
1242 * no sense doing it again.
1244 io_blkno
= bp
->b_blkno
;
1246 * Make sure we redo this mapping for the next I/O
1247 * i.e. this can never be a 'permanent' mapping
1249 bp
->b_blkno
= bp
->b_lblkno
;
1252 * Get an io buffer to do the deblocking
1254 io_bp
= alloc_io_buf(devvp
, 0);
1256 io_bp
->b_lblkno
= bp
->b_lblkno
;
1257 io_bp
->b_datap
= bp
->b_datap
;
1258 io_resid
= bp
->b_bcount
;
1259 io_direction
= bp
->b_flags
& B_READ
;
1260 io_contig_bytes
= contig_bytes
;
1262 if (bp
->b_flags
& B_READ
) {
1263 bmap_flags
= VNODE_READ
;
1265 bmap_flags
= VNODE_WRITE
;
1269 if (io_blkno
== -1) {
1271 * this is unexepected, but we'll allow for it
1273 bzero((caddr_t
)io_bp
->b_datap
, (int)io_contig_bytes
);
1275 io_bp
->b_bcount
= io_contig_bytes
;
1276 io_bp
->b_bufsize
= io_contig_bytes
;
1277 io_bp
->b_resid
= io_contig_bytes
;
1278 io_bp
->b_blkno
= io_blkno
;
1280 buf_reset(io_bp
, io_direction
);
1283 * Call the device to do the I/O and wait for it. Make sure the appropriate party is charged for write
1286 if (!ISSET(bp
->b_flags
, B_READ
)) {
1287 OSAddAtomic(1, &devvp
->v_numoutput
);
1290 if ((error
= VNOP_STRATEGY(io_bp
))) {
1293 if ((error
= (int)buf_biowait(io_bp
))) {
1296 if (io_bp
->b_resid
) {
1297 io_resid
-= (io_contig_bytes
- io_bp
->b_resid
);
1301 if ((io_resid
-= io_contig_bytes
) == 0) {
1304 f_offset
+= io_contig_bytes
;
1305 io_bp
->b_datap
+= io_contig_bytes
;
1308 * Map the current position to a physical block number
1310 if ((error
= VNOP_BLOCKMAP(vp
, f_offset
, io_resid
, &io_blkno
, &io_contig_bytes
, NULL
, bmap_flags
, NULL
))) {
1317 buf_seterror(bp
, error
);
1319 bp
->b_resid
= io_resid
;
1321 * This I/O is now complete
1330 * struct vnop_strategy_args {
1335 buf_strategy(vnode_t devvp
, void *ap
)
1337 buf_t bp
= ((struct vnop_strategy_args
*)ap
)->a_bp
;
1338 vnode_t vp
= bp
->b_vp
;
1342 int dtrace_io_start_flag
= 0; /* We only want to trip the io:::start
1343 * probe once, with the true physical
1344 * block in place (b_blkno)
1349 if (vp
== NULL
|| vp
->v_type
== VCHR
|| vp
->v_type
== VBLK
) {
1350 panic("buf_strategy: b_vp == NULL || vtype == VCHR | VBLK\n");
1353 * associate the physical device with
1354 * with this buf_t even if we don't
1355 * end up issuing the I/O...
1357 bp
->b_dev
= devvp
->v_rdev
;
1359 if (bp
->b_flags
& B_READ
) {
1360 bmap_flags
= VNODE_READ
;
1362 bmap_flags
= VNODE_WRITE
;
1365 if (!(bp
->b_flags
& B_CLUSTER
)) {
1368 * we have a UPL associated with this bp
1369 * go through cluster_bp which knows how
1370 * to deal with filesystem block sizes
1371 * that aren't equal to the page size
1373 DTRACE_IO1(start
, buf_t
, bp
);
1374 return cluster_bp(bp
);
1376 if (bp
->b_blkno
== bp
->b_lblkno
) {
1378 size_t contig_bytes
;
1380 if ((error
= VNOP_BLKTOOFF(vp
, bp
->b_lblkno
, &f_offset
))) {
1381 DTRACE_IO1(start
, buf_t
, bp
);
1382 buf_seterror(bp
, error
);
1388 if ((error
= VNOP_BLOCKMAP(vp
, f_offset
, bp
->b_bcount
, &bp
->b_blkno
, &contig_bytes
, NULL
, bmap_flags
, NULL
))) {
1389 DTRACE_IO1(start
, buf_t
, bp
);
1390 buf_seterror(bp
, error
);
1396 DTRACE_IO1(start
, buf_t
, bp
);
1398 dtrace_io_start_flag
= 1;
1399 #endif /* CONFIG_DTRACE */
1401 if ((bp
->b_blkno
== -1) || (contig_bytes
== 0)) {
1402 /* Set block number to force biodone later */
1405 } else if ((long)contig_bytes
< bp
->b_bcount
) {
1406 return buf_strategy_fragmented(devvp
, bp
, f_offset
, contig_bytes
);
1411 if (dtrace_io_start_flag
== 0) {
1412 DTRACE_IO1(start
, buf_t
, bp
);
1413 dtrace_io_start_flag
= 1;
1415 #endif /* CONFIG_DTRACE */
1417 if (bp
->b_blkno
== -1) {
1424 if (dtrace_io_start_flag
== 0) {
1425 DTRACE_IO1(start
, buf_t
, bp
);
1427 #endif /* CONFIG_DTRACE */
1430 /* Capture f_offset in the bufattr*/
1431 cpx_t cpx
= bufattr_cpx(buf_attr(bp
));
1433 /* No need to go here for older EAs */
1434 if (cpx_use_offset_for_iv(cpx
) && !cpx_synthetic_offset_for_iv(cpx
)) {
1436 if ((error
= VNOP_BLKTOOFF(bp
->b_vp
, bp
->b_lblkno
, &f_offset
))) {
1441 * Attach the file offset to this buffer. The
1442 * bufattr attributes will be passed down the stack
1443 * until they reach the storage driver (whether
1444 * IOFlashStorage, ASP, or IONVMe). The driver
1445 * will retain the offset in a local variable when it
1446 * issues its I/Os to the NAND controller.
1448 * Note that LwVM may end up splitting this I/O
1449 * into sub-I/Os if it crosses a chunk boundary. In this
1450 * case, LwVM will update this field when it dispatches
1451 * each I/O to IOFlashStorage. But from our perspective
1452 * we have only issued a single I/O.
1454 * In the case of APFS we do not bounce through another
1455 * intermediate layer (such as CoreStorage). APFS will
1456 * issue the I/Os directly to the block device / IOMedia
1457 * via buf_strategy on the specfs node.
1459 buf_setcpoff(bp
, f_offset
);
1460 CP_DEBUG((CPDBG_OFFSET_IO
| DBG_FUNC_NONE
), (uint32_t) f_offset
, (uint32_t) bp
->b_lblkno
, (uint32_t) bp
->b_blkno
, (uint32_t) bp
->b_bcount
, 0);
1466 * we can issue the I/O because...
1467 * either B_CLUSTER is set which
1468 * means that the I/O is properly set
1469 * up to be a multiple of the page size, or
1470 * we were able to successfully set up the
1471 * physical block mapping
1473 error
= VOCALL(devvp
->v_op
, VOFFSET(vnop_strategy
), ap
);
1474 DTRACE_FSINFO(strategy
, vnode_t
, vp
);
1481 buf_alloc(vnode_t vp
)
1483 return alloc_io_buf(vp
, is_vm_privileged());
1494 * iterate buffers for the specified vp.
1495 * if BUF_SCAN_DIRTY is set, do the dirty list
1496 * if BUF_SCAN_CLEAN is set, do the clean list
1497 * if neither flag is set, default to BUF_SCAN_DIRTY
1498 * if BUF_NOTIFY_BUSY is set, call the callout function using a NULL bp for busy pages
1501 struct buf_iterate_info_t
{
1503 struct buflists
*listhead
;
1507 buf_iterate(vnode_t vp
, int (*callout
)(buf_t
, void *), int flags
, void *arg
)
1511 struct buflists local_iterblkhd
;
1512 int lock_flags
= BAC_NOWAIT
| BAC_REMOVE
;
1513 int notify_busy
= flags
& BUF_NOTIFY_BUSY
;
1514 struct buf_iterate_info_t list
[2];
1517 if (flags
& BUF_SKIP_LOCKED
) {
1518 lock_flags
|= BAC_SKIP_LOCKED
;
1520 if (flags
& BUF_SKIP_NONLOCKED
) {
1521 lock_flags
|= BAC_SKIP_NONLOCKED
;
1524 if (!(flags
& (BUF_SCAN_DIRTY
| BUF_SCAN_CLEAN
))) {
1525 flags
|= BUF_SCAN_DIRTY
;
1530 if (flags
& BUF_SCAN_DIRTY
) {
1531 list
[num_lists
].flag
= VBI_DIRTY
;
1532 list
[num_lists
].listhead
= &vp
->v_dirtyblkhd
;
1535 if (flags
& BUF_SCAN_CLEAN
) {
1536 list
[num_lists
].flag
= VBI_CLEAN
;
1537 list
[num_lists
].listhead
= &vp
->v_cleanblkhd
;
1541 for (i
= 0; i
< num_lists
; i
++) {
1542 lck_mtx_lock(buf_mtxp
);
1544 if (buf_iterprepare(vp
, &local_iterblkhd
, list
[i
].flag
)) {
1545 lck_mtx_unlock(buf_mtxp
);
1548 while (!LIST_EMPTY(&local_iterblkhd
)) {
1549 bp
= LIST_FIRST(&local_iterblkhd
);
1550 LIST_REMOVE(bp
, b_vnbufs
);
1551 LIST_INSERT_HEAD(list
[i
].listhead
, bp
, b_vnbufs
);
1553 if (buf_acquire_locked(bp
, lock_flags
, 0, 0)) {
1561 lck_mtx_unlock(buf_mtxp
);
1563 retval
= callout(bp
, arg
);
1573 case BUF_RETURNED_DONE
:
1577 lck_mtx_lock(buf_mtxp
);
1579 case BUF_CLAIMED_DONE
:
1580 lck_mtx_lock(buf_mtxp
);
1583 lck_mtx_lock(buf_mtxp
);
1584 } /* while list has more nodes */
1586 buf_itercomplete(vp
, &local_iterblkhd
, list
[i
].flag
);
1587 lck_mtx_unlock(buf_mtxp
);
1588 } /* for each list */
1593 * Flush out and invalidate all buffers associated with a vnode.
1596 buf_invalidateblks(vnode_t vp
, int flags
, int slpflag
, int slptimeo
)
1601 int must_rescan
= 1;
1602 struct buflists local_iterblkhd
;
1605 if (LIST_EMPTY(&vp
->v_cleanblkhd
) && LIST_EMPTY(&vp
->v_dirtyblkhd
)) {
1609 lck_mtx_lock(buf_mtxp
);
1612 if (must_rescan
== 0) {
1614 * the lists may not be empty, but all that's left at this
1615 * point are metadata or B_LOCKED buffers which are being
1616 * skipped... we know this because we made it through both
1617 * the clean and dirty lists without dropping buf_mtxp...
1618 * each time we drop buf_mtxp we bump "must_rescan"
1622 if (LIST_EMPTY(&vp
->v_cleanblkhd
) && LIST_EMPTY(&vp
->v_dirtyblkhd
)) {
1627 * iterate the clean list
1629 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_CLEAN
)) {
1630 goto try_dirty_list
;
1632 while (!LIST_EMPTY(&local_iterblkhd
)) {
1633 bp
= LIST_FIRST(&local_iterblkhd
);
1635 LIST_REMOVE(bp
, b_vnbufs
);
1636 LIST_INSERT_HEAD(&vp
->v_cleanblkhd
, bp
, b_vnbufs
);
1639 * some filesystems distinguish meta data blocks with a negative logical block #
1641 if ((flags
& BUF_SKIP_META
) && (bp
->b_lblkno
< 0 || ISSET(bp
->b_flags
, B_META
))) {
1645 aflags
= BAC_REMOVE
;
1647 if (!(flags
& BUF_INVALIDATE_LOCKED
)) {
1648 aflags
|= BAC_SKIP_LOCKED
;
1651 if ((error
= (int)buf_acquire_locked(bp
, aflags
, slpflag
, slptimeo
))) {
1652 if (error
== EDEADLK
) {
1654 * this buffer was marked B_LOCKED...
1655 * we didn't drop buf_mtxp, so we
1656 * we don't need to rescan
1660 if (error
== EAGAIN
) {
1662 * found a busy buffer... we blocked and
1663 * dropped buf_mtxp, so we're going to
1664 * need to rescan after this pass is completed
1670 * got some kind of 'real' error out of the msleep
1671 * in buf_acquire_locked, terminate the scan and return the error
1673 buf_itercomplete(vp
, &local_iterblkhd
, VBI_CLEAN
);
1675 lck_mtx_unlock(buf_mtxp
);
1678 lck_mtx_unlock(buf_mtxp
);
1680 if (bp
->b_flags
& B_LOCKED
) {
1681 KERNEL_DEBUG(0xbbbbc038, bp
, 0, 0, 0, 0);
1684 CLR(bp
->b_flags
, B_LOCKED
);
1685 SET(bp
->b_flags
, B_INVAL
);
1688 lck_mtx_lock(buf_mtxp
);
1691 * by dropping buf_mtxp, we allow new
1692 * buffers to be added to the vnode list(s)
1693 * we'll have to rescan at least once more
1694 * if the queues aren't empty
1698 buf_itercomplete(vp
, &local_iterblkhd
, VBI_CLEAN
);
1702 * Now iterate on dirty blks
1704 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_DIRTY
)) {
1707 while (!LIST_EMPTY(&local_iterblkhd
)) {
1708 bp
= LIST_FIRST(&local_iterblkhd
);
1710 LIST_REMOVE(bp
, b_vnbufs
);
1711 LIST_INSERT_HEAD(&vp
->v_dirtyblkhd
, bp
, b_vnbufs
);
1714 * some filesystems distinguish meta data blocks with a negative logical block #
1716 if ((flags
& BUF_SKIP_META
) && (bp
->b_lblkno
< 0 || ISSET(bp
->b_flags
, B_META
))) {
1720 aflags
= BAC_REMOVE
;
1722 if (!(flags
& BUF_INVALIDATE_LOCKED
)) {
1723 aflags
|= BAC_SKIP_LOCKED
;
1726 if ((error
= (int)buf_acquire_locked(bp
, aflags
, slpflag
, slptimeo
))) {
1727 if (error
== EDEADLK
) {
1729 * this buffer was marked B_LOCKED...
1730 * we didn't drop buf_mtxp, so we
1731 * we don't need to rescan
1735 if (error
== EAGAIN
) {
1737 * found a busy buffer... we blocked and
1738 * dropped buf_mtxp, so we're going to
1739 * need to rescan after this pass is completed
1745 * got some kind of 'real' error out of the msleep
1746 * in buf_acquire_locked, terminate the scan and return the error
1748 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1750 lck_mtx_unlock(buf_mtxp
);
1753 lck_mtx_unlock(buf_mtxp
);
1755 if (bp
->b_flags
& B_LOCKED
) {
1756 KERNEL_DEBUG(0xbbbbc038, bp
, 0, 0, 1, 0);
1759 CLR(bp
->b_flags
, B_LOCKED
);
1760 SET(bp
->b_flags
, B_INVAL
);
1762 if (ISSET(bp
->b_flags
, B_DELWRI
) && (flags
& BUF_WRITE_DATA
)) {
1763 (void) VNOP_BWRITE(bp
);
1768 lck_mtx_lock(buf_mtxp
);
1770 * by dropping buf_mtxp, we allow new
1771 * buffers to be added to the vnode list(s)
1772 * we'll have to rescan at least once more
1773 * if the queues aren't empty
1777 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1779 lck_mtx_unlock(buf_mtxp
);
1785 buf_flushdirtyblks(vnode_t vp
, int wait
, int flags
, const char *msg
)
1787 (void) buf_flushdirtyblks_skipinfo(vp
, wait
, flags
, msg
);
1792 buf_flushdirtyblks_skipinfo(vnode_t vp
, int wait
, int flags
, const char *msg
)
1795 int writes_issued
= 0;
1798 struct buflists local_iterblkhd
;
1799 int lock_flags
= BAC_NOWAIT
| BAC_REMOVE
;
1802 if (flags
& BUF_SKIP_LOCKED
) {
1803 lock_flags
|= BAC_SKIP_LOCKED
;
1805 if (flags
& BUF_SKIP_NONLOCKED
) {
1806 lock_flags
|= BAC_SKIP_NONLOCKED
;
1809 lck_mtx_lock(buf_mtxp
);
1811 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_DIRTY
) == 0) {
1812 while (!LIST_EMPTY(&local_iterblkhd
)) {
1813 bp
= LIST_FIRST(&local_iterblkhd
);
1814 LIST_REMOVE(bp
, b_vnbufs
);
1815 LIST_INSERT_HEAD(&vp
->v_dirtyblkhd
, bp
, b_vnbufs
);
1817 if ((error
= buf_acquire_locked(bp
, lock_flags
, 0, 0)) == EBUSY
) {
1822 * If we passed in BUF_SKIP_LOCKED or BUF_SKIP_NONLOCKED,
1823 * we may want to do somethign differently if a locked or unlocked
1824 * buffer was encountered (depending on the arg specified).
1825 * In this case, we know that one of those two was set, and the
1826 * buf acquisition failed above.
1828 * If it failed with EDEADLK, then save state which can be emitted
1829 * later on to the caller. Most callers should not care.
1831 if (error
== EDEADLK
) {
1836 lck_mtx_unlock(buf_mtxp
);
1838 bp
->b_flags
&= ~B_LOCKED
;
1841 * Wait for I/O associated with indirect blocks to complete,
1842 * since there is no way to quickly wait for them below.
1844 if ((bp
->b_vp
== vp
) || (wait
== 0)) {
1845 (void) buf_bawrite(bp
);
1847 (void) VNOP_BWRITE(bp
);
1851 lck_mtx_lock(buf_mtxp
);
1853 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1855 lck_mtx_unlock(buf_mtxp
);
1858 (void)vnode_waitforwrites(vp
, 0, 0, 0, msg
);
1860 if (vp
->v_dirtyblkhd
.lh_first
&& busy
) {
1862 * we had one or more BUSY buffers on
1863 * the dirtyblock list... most likely
1864 * these are due to delayed writes that
1865 * were moved to the bclean queue but
1866 * have not yet been 'written'.
1867 * if we issued some writes on the
1868 * previous pass, we try again immediately
1869 * if we didn't, we'll sleep for some time
1870 * to allow the state to change...
1872 if (writes_issued
== 0) {
1873 (void)tsleep((caddr_t
)&vp
->v_numoutput
,
1874 PRIBIO
+ 1, "vnode_flushdirtyblks", hz
/ 20);
1888 * called with buf_mtxp held...
1889 * this lock protects the queue manipulation
1892 buf_iterprepare(vnode_t vp
, struct buflists
*iterheadp
, int flags
)
1894 struct buflists
* listheadp
;
1896 if (flags
& VBI_DIRTY
) {
1897 listheadp
= &vp
->v_dirtyblkhd
;
1899 listheadp
= &vp
->v_cleanblkhd
;
1902 while (vp
->v_iterblkflags
& VBI_ITER
) {
1903 vp
->v_iterblkflags
|= VBI_ITERWANT
;
1904 msleep(&vp
->v_iterblkflags
, buf_mtxp
, 0, "buf_iterprepare", NULL
);
1906 if (LIST_EMPTY(listheadp
)) {
1907 LIST_INIT(iterheadp
);
1910 vp
->v_iterblkflags
|= VBI_ITER
;
1912 iterheadp
->lh_first
= listheadp
->lh_first
;
1913 listheadp
->lh_first
->b_vnbufs
.le_prev
= &iterheadp
->lh_first
;
1914 LIST_INIT(listheadp
);
1920 * called with buf_mtxp held...
1921 * this lock protects the queue manipulation
1924 buf_itercomplete(vnode_t vp
, struct buflists
*iterheadp
, int flags
)
1926 struct buflists
* listheadp
;
1929 if (flags
& VBI_DIRTY
) {
1930 listheadp
= &vp
->v_dirtyblkhd
;
1932 listheadp
= &vp
->v_cleanblkhd
;
1935 while (!LIST_EMPTY(iterheadp
)) {
1936 bp
= LIST_FIRST(iterheadp
);
1937 LIST_REMOVE(bp
, b_vnbufs
);
1938 LIST_INSERT_HEAD(listheadp
, bp
, b_vnbufs
);
1940 vp
->v_iterblkflags
&= ~VBI_ITER
;
1942 if (vp
->v_iterblkflags
& VBI_ITERWANT
) {
1943 vp
->v_iterblkflags
&= ~VBI_ITERWANT
;
1944 wakeup(&vp
->v_iterblkflags
);
1950 bremfree_locked(buf_t bp
)
1952 struct bqueues
*dp
= NULL
;
1955 whichq
= bp
->b_whichq
;
1958 if (bp
->b_shadow_ref
== 0) {
1959 panic("bremfree_locked: %p not on freelist", bp
);
1962 * there are clones pointing to 'bp'...
1963 * therefore, it was not put on a freelist
1964 * when buf_brelse was last called on 'bp'
1969 * We only calculate the head of the freelist when removing
1970 * the last element of the list as that is the only time that
1971 * it is needed (e.g. to reset the tail pointer).
1973 * NB: This makes an assumption about how tailq's are implemented.
1975 if (bp
->b_freelist
.tqe_next
== NULL
) {
1976 dp
= &bufqueues
[whichq
];
1978 if (dp
->tqh_last
!= &bp
->b_freelist
.tqe_next
) {
1979 panic("bremfree: lost tail");
1982 TAILQ_REMOVE(dp
, bp
, b_freelist
);
1984 if (whichq
== BQ_LAUNDRY
) {
1989 bp
->b_timestamp
= 0;
1994 * Associate a buffer with a vnode.
1995 * buf_mtxp must be locked on entry
1998 bgetvp_locked(vnode_t vp
, buf_t bp
)
2000 if (bp
->b_vp
!= vp
) {
2001 panic("bgetvp_locked: not free");
2004 if (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
) {
2005 bp
->b_dev
= vp
->v_rdev
;
2010 * Insert onto list for new vnode.
2012 bufinsvn(bp
, &vp
->v_cleanblkhd
);
2016 * Disassociate a buffer from a vnode.
2017 * buf_mtxp must be locked on entry
2020 brelvp_locked(buf_t bp
)
2023 * Delete from old vnode list, if on one.
2025 if (bp
->b_vnbufs
.le_next
!= NOLIST
) {
2029 bp
->b_vp
= (vnode_t
)NULL
;
2033 * Reassign a buffer from one vnode to another.
2034 * Used to assign file specific control information
2035 * (indirect blocks) to the vnode to which they belong.
2038 buf_reassign(buf_t bp
, vnode_t newvp
)
2040 struct buflists
*listheadp
;
2042 if (newvp
== NULL
) {
2043 printf("buf_reassign: NULL");
2046 lck_mtx_lock_spin(buf_mtxp
);
2049 * Delete from old vnode list, if on one.
2051 if (bp
->b_vnbufs
.le_next
!= NOLIST
) {
2055 * If dirty, put on list of dirty buffers;
2056 * otherwise insert onto list of clean buffers.
2058 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
2059 listheadp
= &newvp
->v_dirtyblkhd
;
2061 listheadp
= &newvp
->v_cleanblkhd
;
2063 bufinsvn(bp
, listheadp
);
2065 lck_mtx_unlock(buf_mtxp
);
2068 static __inline__
void
2069 bufhdrinit(buf_t bp
)
2071 bzero((char *)bp
, sizeof *bp
);
2073 bp
->b_rcred
= NOCRED
;
2074 bp
->b_wcred
= NOCRED
;
2075 bp
->b_vnbufs
.le_next
= NOLIST
;
2076 bp
->b_flags
= B_INVAL
;
2082 * Initialize buffers and hash links for buffers.
2084 __private_extern__
void
2092 /* Initialize the buffer queues ('freelists') and the hash table */
2093 for (dp
= bufqueues
; dp
< &bufqueues
[BQUEUES
]; dp
++) {
2096 bufhashtbl
= hashinit(nbuf_hashelements
, M_CACHE
, &bufhash
);
2100 /* Initialize the buffer headers */
2101 for (i
= 0; i
< max_nbuf_headers
; i
++) {
2103 bp
= &buf_headers
[i
];
2107 dp
= &bufqueues
[BQ_EMPTY
];
2108 bp
->b_whichq
= BQ_EMPTY
;
2109 bp
->b_timestamp
= buf_timestamp();
2110 binsheadfree(bp
, dp
, BQ_EMPTY
);
2111 binshash(bp
, &invalhash
);
2113 boot_nbuf_headers
= nbuf_headers
;
2115 TAILQ_INIT(&iobufqueue
);
2116 TAILQ_INIT(&delaybufqueue
);
2118 for (; i
< nbuf_headers
+ niobuf_headers
; i
++) {
2119 bp
= &buf_headers
[i
];
2122 binsheadfree(bp
, &iobufqueue
, -1);
2126 * allocate lock group attribute and group
2128 buf_mtx_grp_attr
= lck_grp_attr_alloc_init();
2129 buf_mtx_grp
= lck_grp_alloc_init("buffer cache", buf_mtx_grp_attr
);
2132 * allocate the lock attribute
2134 buf_mtx_attr
= lck_attr_alloc_init();
2137 * allocate and initialize mutex's for the buffer and iobuffer pools
2139 buf_mtxp
= lck_mtx_alloc_init(buf_mtx_grp
, buf_mtx_attr
);
2140 iobuffer_mtxp
= lck_mtx_alloc_init(buf_mtx_grp
, buf_mtx_attr
);
2141 buf_gc_callout
= lck_mtx_alloc_init(buf_mtx_grp
, buf_mtx_attr
);
2143 if (iobuffer_mtxp
== NULL
) {
2144 panic("couldn't create iobuffer mutex");
2147 if (buf_mtxp
== NULL
) {
2148 panic("couldn't create buf mutex");
2151 if (buf_gc_callout
== NULL
) {
2152 panic("couldn't create buf_gc_callout mutex");
2156 * allocate and initialize cluster specific global locks...
2160 printf("using %d buffer headers and %d cluster IO buffer headers\n",
2161 nbuf_headers
, niobuf_headers
);
2163 /* Set up zones used by the buffer cache */
2166 /* start the bcleanbuf() thread */
2167 bcleanbuf_thread_init();
2169 /* Register a callout for relieving vm pressure */
2170 if (vm_set_buffer_cleanup_callout(buffer_cache_gc
) != KERN_SUCCESS
) {
2171 panic("Couldn't register buffer cache callout for vm pressure!\n");
2176 * Zones for the meta data buffers
2180 #define MAXMETA 16384
2182 struct meta_zone_entry
{
2186 const char *mz_name
;
2189 struct meta_zone_entry meta_zones
[] = {
2190 {.mz_zone
= NULL
, .mz_size
= (MINMETA
* 1), .mz_max
= 128 * (MINMETA
* 1), .mz_name
= "buf.512" },
2191 {.mz_zone
= NULL
, .mz_size
= (MINMETA
* 2), .mz_max
= 64 * (MINMETA
* 2), .mz_name
= "buf.1024" },
2192 {.mz_zone
= NULL
, .mz_size
= (MINMETA
* 4), .mz_max
= 16 * (MINMETA
* 4), .mz_name
= "buf.2048" },
2193 {.mz_zone
= NULL
, .mz_size
= (MINMETA
* 8), .mz_max
= 512 * (MINMETA
* 8), .mz_name
= "buf.4096" },
2194 {.mz_zone
= NULL
, .mz_size
= (MINMETA
* 16), .mz_max
= 512 * (MINMETA
* 16), .mz_name
= "buf.8192" },
2195 {.mz_zone
= NULL
, .mz_size
= (MINMETA
* 32), .mz_max
= 512 * (MINMETA
* 32), .mz_name
= "buf.16384" },
2196 {.mz_zone
= NULL
, .mz_size
= 0, .mz_max
= 0, .mz_name
= "" } /* End */
2200 * Initialize the meta data zones
2207 for (i
= 0; meta_zones
[i
].mz_size
!= 0; i
++) {
2208 meta_zones
[i
].mz_zone
=
2209 zinit(meta_zones
[i
].mz_size
,
2210 meta_zones
[i
].mz_max
,
2212 meta_zones
[i
].mz_name
);
2213 zone_change(meta_zones
[i
].mz_zone
, Z_CALLERACCT
, FALSE
);
2215 buf_hdr_zone
= zinit(sizeof(struct buf
), 32, PAGE_SIZE
, "buf headers");
2216 zone_change(buf_hdr_zone
, Z_CALLERACCT
, FALSE
);
2219 static __inline__ zone_t
2220 getbufzone(size_t size
)
2224 if ((size
% 512) || (size
< MINMETA
) || (size
> MAXMETA
)) {
2225 panic("getbufzone: incorect size = %lu", size
);
2228 for (i
= 0; meta_zones
[i
].mz_size
!= 0; i
++) {
2229 if (meta_zones
[i
].mz_size
>= size
) {
2234 return meta_zones
[i
].mz_zone
;
2240 bio_doread(vnode_t vp
, daddr64_t blkno
, int size
, kauth_cred_t cred
, int async
, int queuetype
)
2244 bp
= buf_getblk(vp
, blkno
, size
, 0, 0, queuetype
);
2247 * If buffer does not have data valid, start a read.
2248 * Note that if buffer is B_INVAL, buf_getblk() won't return it.
2249 * Therefore, it's valid if it's I/O has completed or been delayed.
2251 if (!ISSET(bp
->b_flags
, (B_DONE
| B_DELWRI
))) {
2256 /* Start I/O for the buffer (keeping credentials). */
2257 SET(bp
->b_flags
, B_READ
| async
);
2258 if (IS_VALID_CRED(cred
) && !IS_VALID_CRED(bp
->b_rcred
)) {
2259 kauth_cred_ref(cred
);
2265 trace(TR_BREADMISS
, pack(vp
, size
), blkno
);
2267 /* Pay for the read. */
2268 if (p
&& p
->p_stats
) {
2269 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_inblock
); /* XXX */
2274 * since we asked for an ASYNC I/O
2275 * the biodone will do the brelse
2276 * we don't want to pass back a bp
2277 * that we don't 'own'
2286 trace(TR_BREADHIT
, pack(vp
, size
), blkno
);
2292 * Perform the reads for buf_breadn() and buf_meta_breadn().
2293 * Trivial modification to the breada algorithm presented in Bach (p.55).
2296 do_breadn_for_type(vnode_t vp
, daddr64_t blkno
, int size
, daddr64_t
*rablks
, int *rasizes
,
2297 int nrablks
, kauth_cred_t cred
, buf_t
*bpp
, int queuetype
)
2302 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, queuetype
);
2305 * For each of the read-ahead blocks, start a read, if necessary.
2307 for (i
= 0; i
< nrablks
; i
++) {
2308 /* If it's in the cache, just go on to next one. */
2309 if (incore(vp
, rablks
[i
])) {
2313 /* Get a buffer for the read-ahead block */
2314 (void) bio_doread(vp
, rablks
[i
], rasizes
[i
], cred
, B_ASYNC
, queuetype
);
2317 /* Otherwise, we had to start a read for it; wait until it's valid. */
2318 return buf_biowait(bp
);
2323 * Read a disk block.
2324 * This algorithm described in Bach (p.54).
2327 buf_bread(vnode_t vp
, daddr64_t blkno
, int size
, kauth_cred_t cred
, buf_t
*bpp
)
2331 /* Get buffer for block. */
2332 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, BLK_READ
);
2334 /* Wait for the read to complete, and return result. */
2335 return buf_biowait(bp
);
2339 * Read a disk block. [bread() for meta-data]
2340 * This algorithm described in Bach (p.54).
2343 buf_meta_bread(vnode_t vp
, daddr64_t blkno
, int size
, kauth_cred_t cred
, buf_t
*bpp
)
2347 /* Get buffer for block. */
2348 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, BLK_META
);
2350 /* Wait for the read to complete, and return result. */
2351 return buf_biowait(bp
);
2355 * Read-ahead multiple disk blocks. The first is sync, the rest async.
2358 buf_breadn(vnode_t vp
, daddr64_t blkno
, int size
, daddr64_t
*rablks
, int *rasizes
, int nrablks
, kauth_cred_t cred
, buf_t
*bpp
)
2360 return do_breadn_for_type(vp
, blkno
, size
, rablks
, rasizes
, nrablks
, cred
, bpp
, BLK_READ
);
2364 * Read-ahead multiple disk blocks. The first is sync, the rest async.
2365 * [buf_breadn() for meta-data]
2368 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
)
2370 return do_breadn_for_type(vp
, blkno
, size
, rablks
, rasizes
, nrablks
, cred
, bpp
, BLK_META
);
2374 * Block write. Described in Bach (p.56)
2377 buf_bwrite(buf_t bp
)
2379 int sync
, wasdelayed
;
2381 proc_t p
= current_proc();
2382 vnode_t vp
= bp
->b_vp
;
2384 if (bp
->b_datap
== 0) {
2385 if (brecover_data(bp
) == 0) {
2389 /* Remember buffer type, to switch on it later. */
2390 sync
= !ISSET(bp
->b_flags
, B_ASYNC
);
2391 wasdelayed
= ISSET(bp
->b_flags
, B_DELWRI
);
2392 CLR(bp
->b_flags
, (B_READ
| B_DONE
| B_ERROR
| B_DELWRI
));
2395 OSAddAtomicLong(-1, &nbdwrite
);
2400 * If not synchronous, pay for the I/O operation and make
2401 * sure the buf is on the correct vnode queue. We have
2402 * to do this now, because if we don't, the vnode may not
2403 * be properly notified that its I/O has completed.
2406 buf_reassign(bp
, vp
);
2407 } else if (p
&& p
->p_stats
) {
2408 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_oublock
); /* XXX */
2411 trace(TR_BUFWRITE
, pack(vp
, bp
->b_bcount
), bp
->b_lblkno
);
2413 /* Initiate disk write. Make sure the appropriate party is charged. */
2415 OSAddAtomic(1, &vp
->v_numoutput
);
2421 * If I/O was synchronous, wait for it to complete.
2423 rv
= buf_biowait(bp
);
2426 * Pay for the I/O operation, if it's not been paid for, and
2427 * make sure it's on the correct vnode queue. (async operatings
2428 * were payed for above.)
2431 buf_reassign(bp
, vp
);
2432 } else if (p
&& p
->p_stats
) {
2433 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_oublock
); /* XXX */
2436 /* Release the buffer. */
2446 vn_bwrite(struct vnop_bwrite_args
*ap
)
2448 return buf_bwrite(ap
->a_bp
);
2454 * The buffer is marked dirty, but is not queued for I/O.
2455 * This routine should be used when the buffer is expected
2456 * to be modified again soon, typically a small write that
2457 * partially fills a buffer.
2459 * NB: magnetic tapes cannot be delayed; they must be
2460 * written in the order that the writes are requested.
2462 * Described in Leffler, et al. (pp. 208-213).
2464 * Note: With the ability to allocate additional buffer
2465 * headers, we can get in to the situation where "too" many
2466 * buf_bdwrite()s can create situation where the kernel can create
2467 * buffers faster than the disks can service. Doing a buf_bawrite() in
2468 * cases where we have "too many" outstanding buf_bdwrite()s avoids that.
2471 bdwrite_internal(buf_t bp
, int return_error
)
2473 proc_t p
= current_proc();
2474 vnode_t vp
= bp
->b_vp
;
2477 * If the block hasn't been seen before:
2478 * (1) Mark it as having been seen,
2479 * (2) Charge for the write.
2480 * (3) Make sure it's on its vnode's correct block list,
2482 if (!ISSET(bp
->b_flags
, B_DELWRI
)) {
2483 SET(bp
->b_flags
, B_DELWRI
);
2484 if (p
&& p
->p_stats
) {
2485 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_oublock
); /* XXX */
2487 OSAddAtomicLong(1, &nbdwrite
);
2488 buf_reassign(bp
, vp
);
2492 * if we're not LOCKED, but the total number of delayed writes
2493 * has climbed above 75% of the total buffers in the system
2494 * return an error if the caller has indicated that it can
2495 * handle one in this case, otherwise schedule the I/O now
2496 * this is done to prevent us from allocating tons of extra
2497 * buffers when dealing with virtual disks (i.e. DiskImages),
2498 * because additional buffers are dynamically allocated to prevent
2499 * deadlocks from occurring
2501 * however, can't do a buf_bawrite() if the LOCKED bit is set because the
2502 * buffer is part of a transaction and can't go to disk until
2503 * the LOCKED bit is cleared.
2505 if (!ISSET(bp
->b_flags
, B_LOCKED
) && nbdwrite
> ((nbuf_headers
/ 4) * 3)) {
2510 * If the vnode has "too many" write operations in progress
2511 * wait for them to finish the IO
2513 (void)vnode_waitforwrites(vp
, VNODE_ASYNC_THROTTLE
, 0, 0, "buf_bdwrite");
2515 return buf_bawrite(bp
);
2518 /* Otherwise, the "write" is done, so mark and release the buffer. */
2519 SET(bp
->b_flags
, B_DONE
);
2525 buf_bdwrite(buf_t bp
)
2527 return bdwrite_internal(bp
, 0);
2532 * Asynchronous block write; just an asynchronous buf_bwrite().
2534 * Note: With the abilitty to allocate additional buffer
2535 * headers, we can get in to the situation where "too" many
2536 * buf_bawrite()s can create situation where the kernel can create
2537 * buffers faster than the disks can service.
2538 * We limit the number of "in flight" writes a vnode can have to
2542 bawrite_internal(buf_t bp
, int throttle
)
2544 vnode_t vp
= bp
->b_vp
;
2549 * If the vnode has "too many" write operations in progress
2550 * wait for them to finish the IO
2552 (void)vnode_waitforwrites(vp
, VNODE_ASYNC_THROTTLE
, 0, 0, (const char *)"buf_bawrite");
2553 } else if (vp
->v_numoutput
>= VNODE_ASYNC_THROTTLE
) {
2555 * return to the caller and
2556 * let him decide what to do
2561 SET(bp
->b_flags
, B_ASYNC
);
2563 return VNOP_BWRITE(bp
);
2567 buf_bawrite(buf_t bp
)
2569 return bawrite_internal(bp
, 1);
2575 buf_free_meta_store(buf_t bp
)
2577 if (bp
->b_bufsize
) {
2578 if (ISSET(bp
->b_flags
, B_ZALLOC
)) {
2581 z
= getbufzone(bp
->b_bufsize
);
2582 zfree(z
, bp
->b_datap
);
2584 kmem_free(kernel_map
, bp
->b_datap
, bp
->b_bufsize
);
2587 bp
->b_datap
= (uintptr_t)NULL
;
2594 buf_brelse_shadow(buf_t bp
)
2598 buf_t bp_return
= NULL
;
2599 #ifdef BUF_MAKE_PRIVATE
2603 int need_wakeup
= 0;
2605 lck_mtx_lock_spin(buf_mtxp
);
2607 __IGNORE_WCASTALIGN(bp_head
= (buf_t
)bp
->b_orig
);
2609 if (bp_head
->b_whichq
!= -1) {
2610 panic("buf_brelse_shadow: bp_head on freelist %d\n", bp_head
->b_whichq
);
2613 #ifdef BUF_MAKE_PRIVATE
2614 if (bp_data
= bp
->b_data_store
) {
2615 bp_data
->b_data_ref
--;
2617 * snapshot the ref count so that we can check it
2618 * outside of the lock... we only want the guy going
2619 * from 1 -> 0 to try and release the storage
2621 data_ref
= bp_data
->b_data_ref
;
2624 KERNEL_DEBUG(0xbbbbc008 | DBG_FUNC_START
, bp
, bp_head
, bp_head
->b_shadow_ref
, 0, 0);
2626 bp_head
->b_shadow_ref
--;
2628 for (bp_temp
= bp_head
; bp_temp
&& bp
!= bp_temp
->b_shadow
; bp_temp
= bp_temp
->b_shadow
) {
2632 if (bp_temp
== NULL
) {
2633 panic("buf_brelse_shadow: bp not on list %p", bp_head
);
2636 bp_temp
->b_shadow
= bp_temp
->b_shadow
->b_shadow
;
2638 #ifdef BUF_MAKE_PRIVATE
2640 * we're about to free the current 'owner' of the data buffer and
2641 * there is at least one other shadow buf_t still pointing at it
2642 * so transfer it to the first shadow buf left in the chain
2644 if (bp
== bp_data
&& data_ref
) {
2645 if ((bp_data
= bp_head
->b_shadow
) == NULL
) {
2646 panic("buf_brelse_shadow: data_ref mismatch bp(%p)", bp
);
2649 for (bp_temp
= bp_data
; bp_temp
; bp_temp
= bp_temp
->b_shadow
) {
2650 bp_temp
->b_data_store
= bp_data
;
2652 bp_data
->b_data_ref
= data_ref
;
2655 if (bp_head
->b_shadow_ref
== 0 && bp_head
->b_shadow
) {
2656 panic("buf_relse_shadow: b_shadow != NULL && b_shadow_ref == 0 bp(%p)", bp
);
2658 if (bp_head
->b_shadow_ref
&& bp_head
->b_shadow
== 0) {
2659 panic("buf_relse_shadow: b_shadow == NULL && b_shadow_ref != 0 bp(%p)", bp
);
2662 if (bp_head
->b_shadow_ref
== 0) {
2663 if (!ISSET(bp_head
->b_lflags
, BL_BUSY
)) {
2664 CLR(bp_head
->b_flags
, B_AGE
);
2665 bp_head
->b_timestamp
= buf_timestamp();
2667 if (ISSET(bp_head
->b_flags
, B_LOCKED
)) {
2668 bp_head
->b_whichq
= BQ_LOCKED
;
2669 binstailfree(bp_head
, &bufqueues
[BQ_LOCKED
], BQ_LOCKED
);
2671 bp_head
->b_whichq
= BQ_META
;
2672 binstailfree(bp_head
, &bufqueues
[BQ_META
], BQ_META
);
2674 } else if (ISSET(bp_head
->b_lflags
, BL_WAITSHADOW
)) {
2675 CLR(bp_head
->b_lflags
, BL_WAITSHADOW
);
2677 bp_return
= bp_head
;
2679 if (ISSET(bp_head
->b_lflags
, BL_WANTED_REF
)) {
2680 CLR(bp_head
->b_lflags
, BL_WANTED_REF
);
2684 lck_mtx_unlock(buf_mtxp
);
2690 #ifdef BUF_MAKE_PRIVATE
2691 if (bp
== bp_data
&& data_ref
== 0) {
2692 buf_free_meta_store(bp
);
2695 bp
->b_data_store
= NULL
;
2697 KERNEL_DEBUG(0xbbbbc008 | DBG_FUNC_END
, bp
, 0, 0, 0, 0);
2704 * Release a buffer on to the free lists.
2705 * Described in Bach (p. 46).
2708 buf_brelse(buf_t bp
)
2710 struct bqueues
*bufq
;
2713 int need_wakeup
= 0;
2714 int need_bp_wakeup
= 0;
2717 if (bp
->b_whichq
!= -1 || !(bp
->b_lflags
& BL_BUSY
)) {
2718 panic("buf_brelse: bad buffer = %p\n", bp
);
2722 (void) OSBacktrace(&bp
->b_stackbrelse
[0], 6);
2724 bp
->b_lastbrelse
= current_thread();
2727 if (bp
->b_lflags
& BL_IOBUF
) {
2728 buf_t shadow_master_bp
= NULL
;
2730 if (ISSET(bp
->b_lflags
, BL_SHADOW
)) {
2731 shadow_master_bp
= buf_brelse_shadow(bp
);
2732 } else if (ISSET(bp
->b_lflags
, BL_IOBUF_ALLOC
)) {
2733 buf_free_meta_store(bp
);
2737 if (shadow_master_bp
) {
2738 bp
= shadow_master_bp
;
2739 goto finish_shadow_master
;
2744 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 388)) | DBG_FUNC_START
,
2745 bp
->b_lblkno
* PAGE_SIZE
, bp
, bp
->b_datap
,
2748 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
2751 * if we're invalidating a buffer that has the B_FILTER bit
2752 * set then call the b_iodone function so it gets cleaned
2755 * the HFS journal code depends on this
2757 if (ISSET(bp
->b_flags
, B_META
) && ISSET(bp
->b_flags
, B_INVAL
)) {
2758 if (ISSET(bp
->b_flags
, B_FILTER
)) { /* if necessary, call out */
2759 void (*iodone_func
)(struct buf
*, void *) = bp
->b_iodone
;
2760 void *arg
= bp
->b_transaction
;
2762 CLR(bp
->b_flags
, B_FILTER
); /* but note callout done */
2763 bp
->b_iodone
= NULL
;
2764 bp
->b_transaction
= NULL
;
2766 if (iodone_func
== NULL
) {
2767 panic("brelse: bp @ %p has NULL b_iodone!\n", bp
);
2769 (*iodone_func
)(bp
, arg
);
2773 * I/O is done. Cleanup the UPL state
2777 if (!ISSET(bp
->b_flags
, B_META
) && UBCINFOEXISTS(bp
->b_vp
) && bp
->b_bufsize
) {
2782 if (!ISSET(bp
->b_flags
, B_INVAL
)) {
2783 kret
= ubc_create_upl_kernel(bp
->b_vp
,
2784 ubc_blktooff(bp
->b_vp
, bp
->b_lblkno
),
2789 VM_KERN_MEMORY_FILE
);
2791 if (kret
!= KERN_SUCCESS
) {
2792 panic("brelse: Failed to create UPL");
2795 upl_ubc_alias_set(upl
, (uintptr_t) bp
, (uintptr_t) 5);
2796 #endif /* UPL_DEBUG */
2800 kret
= ubc_upl_unmap(upl
);
2802 if (kret
!= KERN_SUCCESS
) {
2803 panic("ubc_upl_unmap failed");
2805 bp
->b_datap
= (uintptr_t)NULL
;
2809 if (bp
->b_flags
& (B_ERROR
| B_INVAL
)) {
2810 if (bp
->b_flags
& (B_READ
| B_INVAL
)) {
2811 upl_flags
= UPL_ABORT_DUMP_PAGES
;
2816 ubc_upl_abort(upl
, upl_flags
);
2818 if (ISSET(bp
->b_flags
, B_DELWRI
| B_WASDIRTY
)) {
2819 upl_flags
= UPL_COMMIT_SET_DIRTY
;
2821 upl_flags
= UPL_COMMIT_CLEAR_DIRTY
;
2824 ubc_upl_commit_range(upl
, 0, bp
->b_bufsize
, upl_flags
|
2825 UPL_COMMIT_INACTIVATE
| UPL_COMMIT_FREE_ON_EMPTY
);
2831 panic("brelse: UPL set for non VREG; vp=%p", bp
->b_vp
);
2836 * If it's locked, don't report an error; try again later.
2838 if (ISSET(bp
->b_flags
, (B_LOCKED
| B_ERROR
)) == (B_LOCKED
| B_ERROR
)) {
2839 CLR(bp
->b_flags
, B_ERROR
);
2842 * If it's not cacheable, or an error, mark it invalid.
2844 if (ISSET(bp
->b_flags
, (B_NOCACHE
| B_ERROR
))) {
2845 SET(bp
->b_flags
, B_INVAL
);
2848 if ((bp
->b_bufsize
<= 0) ||
2849 ISSET(bp
->b_flags
, B_INVAL
) ||
2850 (ISSET(bp
->b_lflags
, BL_WANTDEALLOC
) && !ISSET(bp
->b_flags
, B_DELWRI
))) {
2851 boolean_t delayed_buf_free_meta_store
= FALSE
;
2854 * If it's invalid or empty, dissociate it from its vnode,
2855 * release its storage if B_META, and
2856 * clean it up a bit and put it on the EMPTY queue
2858 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
2859 OSAddAtomicLong(-1, &nbdwrite
);
2862 if (ISSET(bp
->b_flags
, B_META
)) {
2863 if (bp
->b_shadow_ref
) {
2864 delayed_buf_free_meta_store
= TRUE
;
2866 buf_free_meta_store(bp
);
2870 * nuke any credentials we were holding
2872 buf_release_credentials(bp
);
2874 lck_mtx_lock_spin(buf_mtxp
);
2876 if (bp
->b_shadow_ref
) {
2877 SET(bp
->b_lflags
, BL_WAITSHADOW
);
2879 lck_mtx_unlock(buf_mtxp
);
2883 if (delayed_buf_free_meta_store
== TRUE
) {
2884 lck_mtx_unlock(buf_mtxp
);
2885 finish_shadow_master
:
2886 buf_free_meta_store(bp
);
2888 lck_mtx_lock_spin(buf_mtxp
);
2890 CLR(bp
->b_flags
, (B_META
| B_ZALLOC
| B_DELWRI
| B_LOCKED
| B_AGE
| B_ASYNC
| B_NOCACHE
| B_FUA
));
2898 binshash(bp
, &invalhash
);
2900 bp
->b_whichq
= BQ_EMPTY
;
2901 binsheadfree(bp
, &bufqueues
[BQ_EMPTY
], BQ_EMPTY
);
2904 * It has valid data. Put it on the end of the appropriate
2905 * queue, so that it'll stick around for as long as possible.
2907 if (ISSET(bp
->b_flags
, B_LOCKED
)) {
2908 whichq
= BQ_LOCKED
; /* locked in core */
2909 } else if (ISSET(bp
->b_flags
, B_META
)) {
2910 whichq
= BQ_META
; /* meta-data */
2911 } else if (ISSET(bp
->b_flags
, B_AGE
)) {
2912 whichq
= BQ_AGE
; /* stale but valid data */
2914 whichq
= BQ_LRU
; /* valid data */
2916 bufq
= &bufqueues
[whichq
];
2918 bp
->b_timestamp
= buf_timestamp();
2920 lck_mtx_lock_spin(buf_mtxp
);
2923 * the buf_brelse_shadow routine doesn't take 'ownership'
2924 * of the parent buf_t... it updates state that is protected by
2925 * the buf_mtxp, and checks for BL_BUSY to determine whether to
2926 * put the buf_t back on a free list. b_shadow_ref is protected
2927 * by the lock, and since we have not yet cleared B_BUSY, we need
2928 * to check it while holding the lock to insure that one of us
2929 * puts this buf_t back on a free list when it is safe to do so
2931 if (bp
->b_shadow_ref
== 0) {
2932 CLR(bp
->b_flags
, (B_AGE
| B_ASYNC
| B_NOCACHE
));
2933 bp
->b_whichq
= whichq
;
2934 binstailfree(bp
, bufq
, whichq
);
2937 * there are still cloned buf_t's pointing
2938 * at this guy... need to keep it off the
2939 * freelists until a buf_brelse is done on
2942 CLR(bp
->b_flags
, (B_ASYNC
| B_NOCACHE
));
2947 * needbuffer is a global
2948 * we're currently using buf_mtxp to protect it
2949 * delay doing the actual wakeup until after
2955 if (ISSET(bp
->b_lflags
, BL_WANTED
)) {
2957 * delay the actual wakeup until after we
2958 * clear BL_BUSY and we've dropped buf_mtxp
2963 * Unlock the buffer.
2965 CLR(bp
->b_lflags
, (BL_BUSY
| BL_WANTED
));
2968 lck_mtx_unlock(buf_mtxp
);
2972 * Wake up any processes waiting for any buffer to become free.
2974 wakeup(&needbuffer
);
2976 if (need_bp_wakeup
) {
2978 * Wake up any proceeses waiting for _this_ buffer to become free.
2982 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 388)) | DBG_FUNC_END
,
2983 bp
, bp
->b_datap
, bp
->b_flags
, 0, 0);
2987 * Determine if a block is in the cache.
2988 * Just look on what would be its hash chain. If it's there, return
2989 * a pointer to it, unless it's marked invalid. If it's marked invalid,
2990 * we normally don't return the buffer, unless the caller explicitly
2994 incore(vnode_t vp
, daddr64_t blkno
)
2997 struct bufhashhdr
*dp
;
2999 dp
= BUFHASH(vp
, blkno
);
3001 lck_mtx_lock_spin(buf_mtxp
);
3003 if (incore_locked(vp
, blkno
, dp
)) {
3008 lck_mtx_unlock(buf_mtxp
);
3015 incore_locked(vnode_t vp
, daddr64_t blkno
, struct bufhashhdr
*dp
)
3019 /* Search hash chain */
3020 for (bp
= dp
->lh_first
; bp
!= NULL
; bp
= bp
->b_hash
.le_next
) {
3021 if (bp
->b_lblkno
== blkno
&& bp
->b_vp
== vp
&&
3022 !ISSET(bp
->b_flags
, B_INVAL
)) {
3031 buf_wait_for_shadow_io(vnode_t vp
, daddr64_t blkno
)
3034 struct bufhashhdr
*dp
;
3036 dp
= BUFHASH(vp
, blkno
);
3038 lck_mtx_lock_spin(buf_mtxp
);
3041 if ((bp
= incore_locked(vp
, blkno
, dp
)) == NULL
) {
3045 if (bp
->b_shadow_ref
== 0) {
3049 SET(bp
->b_lflags
, BL_WANTED_REF
);
3051 (void) msleep(bp
, buf_mtxp
, PSPIN
| (PRIBIO
+ 1), "buf_wait_for_shadow", NULL
);
3053 lck_mtx_unlock(buf_mtxp
);
3056 /* XXX FIXME -- Update the comment to reflect the UBC changes (please) -- */
3058 * Get a block of requested size that is associated with
3059 * a given vnode and block offset. If it is found in the
3060 * block cache, mark it as having been found, make it busy
3061 * and return it. Otherwise, return an empty block of the
3062 * correct size. It is up to the caller to insure that the
3063 * cached blocks be of the correct size.
3066 buf_getblk(vnode_t vp
, daddr64_t blkno
, int size
, int slpflag
, int slptimeo
, int operation
)
3071 upl_page_info_t
*pl
;
3076 struct bufhashhdr
*dp
;
3078 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_START
,
3079 (uintptr_t)(blkno
* PAGE_SIZE
), size
, operation
, 0, 0);
3081 ret_only_valid
= operation
& BLK_ONLYVALID
;
3082 operation
&= ~BLK_ONLYVALID
;
3083 dp
= BUFHASH(vp
, blkno
);
3085 lck_mtx_lock_spin(buf_mtxp
);
3087 if ((bp
= incore_locked(vp
, blkno
, dp
))) {
3089 * Found in the Buffer Cache
3091 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
3095 switch (operation
) {
3099 SET(bp
->b_lflags
, BL_WANTED
);
3100 bufstats
.bufs_busyincore
++;
3103 * don't retake the mutex after being awakened...
3104 * the time out is in msecs
3106 ts
.tv_sec
= (slptimeo
/ 1000);
3107 ts
.tv_nsec
= (slptimeo
% 1000) * 10 * NSEC_PER_USEC
* 1000;
3109 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 396)) | DBG_FUNC_NONE
,
3110 (uintptr_t)blkno
, size
, operation
, 0, 0);
3112 err
= msleep(bp
, buf_mtxp
, slpflag
| PDROP
| (PRIBIO
+ 1), "buf_getblk", &ts
);
3115 * Callers who call with PCATCH or timeout are
3116 * willing to deal with the NULL pointer
3118 if (err
&& ((slpflag
& PCATCH
) || ((err
== EWOULDBLOCK
) && slptimeo
))) {
3126 * unknown operation requested
3128 panic("getblk: paging or unknown operation for incore busy buffer - %x\n", operation
);
3136 * buffer in core and not busy
3138 SET(bp
->b_lflags
, BL_BUSY
);
3139 SET(bp
->b_flags
, B_CACHE
);
3142 bremfree_locked(bp
);
3143 bufstats
.bufs_incore
++;
3145 lck_mtx_unlock(buf_mtxp
);
3147 bp
->b_owner
= current_thread();
3151 panic("buffer has UPL, but not marked BUSY: %p", bp
);
3154 clear_bdone
= FALSE
;
3155 if (!ret_only_valid
) {
3157 * If the number bytes that are valid is going
3158 * to increase (even if we end up not doing a
3159 * reallocation through allocbuf) we have to read
3160 * the new size first.
3162 * This is required in cases where we doing a read
3163 * modify write of a already valid data on disk but
3164 * in cases where the data on disk beyond (blkno + b_bcount)
3165 * is invalid, we may end up doing extra I/O.
3167 if (operation
== BLK_META
&& bp
->b_bcount
< size
) {
3169 * Since we are going to read in the whole size first
3170 * we first have to ensure that any pending delayed write
3171 * is flushed to disk first.
3173 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
3174 CLR(bp
->b_flags
, B_CACHE
);
3179 * clear B_DONE before returning from
3180 * this function so that the caller can
3181 * can issue a read for the new size.
3186 if (bp
->b_bufsize
!= size
) {
3192 switch (operation
) {
3195 * "write" operation: let the UPL subsystem
3196 * know that we intend to modify the buffer
3197 * cache pages we're gathering.
3199 upl_flags
|= UPL_WILL_MODIFY
;
3201 upl_flags
|= UPL_PRECIOUS
;
3202 if (UBCINFOEXISTS(bp
->b_vp
) && bp
->b_bufsize
) {
3203 kret
= ubc_create_upl_kernel(vp
,
3204 ubc_blktooff(vp
, bp
->b_lblkno
),
3209 VM_KERN_MEMORY_FILE
);
3210 if (kret
!= KERN_SUCCESS
) {
3211 panic("Failed to create UPL");
3216 if (upl_valid_page(pl
, 0)) {
3217 if (upl_dirty_page(pl
, 0)) {
3218 SET(bp
->b_flags
, B_WASDIRTY
);
3220 CLR(bp
->b_flags
, B_WASDIRTY
);
3223 CLR(bp
->b_flags
, (B_DONE
| B_CACHE
| B_WASDIRTY
| B_DELWRI
));
3226 kret
= ubc_upl_map(upl
, (vm_offset_t
*)&(bp
->b_datap
));
3228 if (kret
!= KERN_SUCCESS
) {
3229 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
3236 * VM is not involved in IO for the meta data
3237 * buffer already has valid data
3242 panic("getblk: paging or unknown operation for incore buffer- %d\n", operation
);
3248 CLR(bp
->b_flags
, B_DONE
);
3251 } else { /* not incore() */
3252 int queue
= BQ_EMPTY
; /* Start with no preference */
3254 if (ret_only_valid
) {
3255 lck_mtx_unlock(buf_mtxp
);
3258 if ((vnode_isreg(vp
) == 0) || (UBCINFOEXISTS(vp
) == 0) /*|| (vnode_issystem(vp) == 1)*/) {
3259 operation
= BLK_META
;
3262 if ((bp
= getnewbuf(slpflag
, slptimeo
, &queue
)) == NULL
) {
3267 * getnewbuf may block for a number of different reasons...
3268 * if it does, it's then possible for someone else to
3269 * create a buffer for the same block and insert it into
3270 * the hash... if we see it incore at this point we dump
3271 * the buffer we were working on and start over
3273 if (incore_locked(vp
, blkno
, dp
)) {
3274 SET(bp
->b_flags
, B_INVAL
);
3275 binshash(bp
, &invalhash
);
3277 lck_mtx_unlock(buf_mtxp
);
3283 * NOTE: YOU CAN NOT BLOCK UNTIL binshash() HAS BEEN
3284 * CALLED! BE CAREFUL.
3288 * mark the buffer as B_META if indicated
3289 * so that when buffer is released it will goto META queue
3291 if (operation
== BLK_META
) {
3292 SET(bp
->b_flags
, B_META
);
3295 bp
->b_blkno
= bp
->b_lblkno
= blkno
;
3299 * Insert in the hash so that incore() can find it
3301 binshash(bp
, BUFHASH(vp
, blkno
));
3303 bgetvp_locked(vp
, bp
);
3305 lck_mtx_unlock(buf_mtxp
);
3310 switch (operation
) {
3313 * buffer data is invalid...
3315 * I don't want to have to retake buf_mtxp,
3316 * so the miss and vmhits counters are done
3317 * with Atomic updates... all other counters
3318 * in bufstats are protected with either
3319 * buf_mtxp or iobuffer_mtxp
3321 OSAddAtomicLong(1, &bufstats
.bufs_miss
);
3326 * "write" operation: let the UPL subsystem know
3327 * that we intend to modify the buffer cache pages
3330 upl_flags
|= UPL_WILL_MODIFY
;
3333 size_t contig_bytes
;
3336 #if DEVELOPMENT || DEBUG
3338 * Apple implemented file systems use UBC excludively; they should
3339 * not call in here."
3341 const char* excldfs
[] = {"hfs", "afpfs", "smbfs", "acfs",
3342 "exfat", "msdos", "webdav", NULL
};
3344 for (int i
= 0; excldfs
[i
] != NULL
; i
++) {
3346 !strcmp(vp
->v_mount
->mnt_vfsstat
.f_fstypename
,
3348 panic("%s %s calls buf_getblk",
3350 operation
== BLK_READ
? "BLK_READ" : "BLK_WRITE");
3356 panic("bp already has UPL: %p", bp
);
3359 f_offset
= ubc_blktooff(vp
, blkno
);
3361 upl_flags
|= UPL_PRECIOUS
;
3362 kret
= ubc_create_upl_kernel(vp
,
3368 VM_KERN_MEMORY_FILE
);
3370 if (kret
!= KERN_SUCCESS
) {
3371 panic("Failed to create UPL");
3374 upl_ubc_alias_set(upl
, (uintptr_t) bp
, (uintptr_t) 4);
3375 #endif /* UPL_DEBUG */
3378 if (upl_valid_page(pl
, 0)) {
3379 if (operation
== BLK_READ
) {
3380 bmap_flags
= VNODE_READ
;
3382 bmap_flags
= VNODE_WRITE
;
3385 SET(bp
->b_flags
, B_CACHE
| B_DONE
);
3387 OSAddAtomicLong(1, &bufstats
.bufs_vmhits
);
3392 if (upl_dirty_page(pl
, 0)) {
3394 SET(bp
->b_flags
, B_WASDIRTY
);
3396 bp
->b_validend
= bp
->b_bcount
;
3397 bp
->b_dirtyend
= bp
->b_bcount
;
3400 bp
->b_validend
= bp
->b_bcount
;
3404 * try to recreate the physical block number associated with
3407 if (VNOP_BLOCKMAP(vp
, f_offset
, bp
->b_bcount
, &bp
->b_blkno
, &contig_bytes
, NULL
, bmap_flags
, NULL
)) {
3408 panic("getblk: VNOP_BLOCKMAP failed");
3411 * if the extent represented by this buffer
3412 * is not completely physically contiguous on
3413 * disk, than we can't cache the physical mapping
3414 * in the buffer header
3416 if ((long)contig_bytes
< bp
->b_bcount
) {
3417 bp
->b_blkno
= bp
->b_lblkno
;
3420 OSAddAtomicLong(1, &bufstats
.bufs_miss
);
3422 kret
= ubc_upl_map(upl
, (vm_offset_t
*)&(bp
->b_datap
));
3424 if (kret
!= KERN_SUCCESS
) {
3425 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
3427 break;} // end BLK_READ
3429 panic("getblk: paging or unknown operation - %x", operation
);
3433 } //end buf_t !incore
3435 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_END
,
3436 bp
, bp
->b_datap
, bp
->b_flags
, 3, 0);
3439 (void) OSBacktrace(&bp
->b_stackgetblk
[0], 6);
3445 * Get an empty, disassociated buffer of given size.
3448 buf_geteblk(int size
)
3451 int queue
= BQ_EMPTY
;
3454 lck_mtx_lock_spin(buf_mtxp
);
3456 bp
= getnewbuf(0, 0, &queue
);
3457 } while (bp
== NULL
);
3459 SET(bp
->b_flags
, (B_META
| B_INVAL
));
3462 assert(queue
== BQ_EMPTY
);
3463 #endif /* DIAGNOSTIC */
3464 /* XXX need to implement logic to deal with other queues */
3466 binshash(bp
, &invalhash
);
3467 bufstats
.bufs_eblk
++;
3469 lck_mtx_unlock(buf_mtxp
);
3477 buf_redundancy_flags(buf_t bp
)
3479 return bp
->b_redundancy_flags
;
3483 buf_set_redundancy_flags(buf_t bp
, uint32_t flags
)
3485 SET(bp
->b_redundancy_flags
, flags
);
3489 buf_clear_redundancy_flags(buf_t bp
, uint32_t flags
)
3491 CLR(bp
->b_redundancy_flags
, flags
);
3497 recycle_buf_from_pool(int nsize
)
3502 lck_mtx_lock_spin(buf_mtxp
);
3504 TAILQ_FOREACH(bp
, &bufqueues
[BQ_META
], b_freelist
) {
3505 if (ISSET(bp
->b_flags
, B_DELWRI
) || bp
->b_bufsize
!= nsize
) {
3508 ptr
= (void *)bp
->b_datap
;
3511 bcleanbuf(bp
, TRUE
);
3514 lck_mtx_unlock(buf_mtxp
);
3521 int zalloc_nopagewait_failed
= 0;
3522 int recycle_buf_failed
= 0;
3525 grab_memory_for_meta_buf(int nsize
)
3529 boolean_t was_vmpriv
;
3531 z
= getbufzone(nsize
);
3534 * make sure we're NOT priviliged so that
3535 * if a vm_page_grab is needed, it won't
3536 * block if we're out of free pages... if
3537 * it blocks, then we can't honor the
3538 * nopagewait request
3540 was_vmpriv
= set_vm_privilege(FALSE
);
3542 ptr
= zalloc_nopagewait(z
);
3544 if (was_vmpriv
== TRUE
) {
3545 set_vm_privilege(TRUE
);
3549 zalloc_nopagewait_failed
++;
3551 ptr
= recycle_buf_from_pool(nsize
);
3554 recycle_buf_failed
++;
3556 if (was_vmpriv
== FALSE
) {
3557 set_vm_privilege(TRUE
);
3562 if (was_vmpriv
== FALSE
) {
3563 set_vm_privilege(FALSE
);
3571 * With UBC, there is no need to expand / shrink the file data
3572 * buffer. The VM uses the same pages, hence no waste.
3573 * All the file data buffers can have one size.
3574 * In fact expand / shrink would be an expensive operation.
3576 * Only exception to this is meta-data buffers. Most of the
3577 * meta data operations are smaller than PAGE_SIZE. Having the
3578 * meta-data buffers grow and shrink as needed, optimizes use
3579 * of the kernel wired memory.
3583 allocbuf(buf_t bp
, int size
)
3585 vm_size_t desired_size
;
3587 desired_size
= roundup(size
, CLBYTES
);
3589 if (desired_size
< PAGE_SIZE
) {
3590 desired_size
= PAGE_SIZE
;
3592 if (desired_size
> MAXBSIZE
) {
3593 panic("allocbuf: buffer larger than MAXBSIZE requested");
3596 if (ISSET(bp
->b_flags
, B_META
)) {
3597 int nsize
= roundup(size
, MINMETA
);
3600 vm_offset_t elem
= (vm_offset_t
)bp
->b_datap
;
3602 if (ISSET(bp
->b_flags
, B_ZALLOC
)) {
3603 if (bp
->b_bufsize
< nsize
) {
3606 /* reallocate to a bigger size */
3608 zprev
= getbufzone(bp
->b_bufsize
);
3609 if (nsize
<= MAXMETA
) {
3610 desired_size
= nsize
;
3612 /* b_datap not really a ptr */
3613 *(void **)(&bp
->b_datap
) = grab_memory_for_meta_buf(nsize
);
3615 bp
->b_datap
= (uintptr_t)NULL
;
3616 kmem_alloc_kobject(kernel_map
, (vm_offset_t
*)&bp
->b_datap
, desired_size
, VM_KERN_MEMORY_FILE
);
3617 CLR(bp
->b_flags
, B_ZALLOC
);
3619 bcopy((void *)elem
, (caddr_t
)bp
->b_datap
, bp
->b_bufsize
);
3622 desired_size
= bp
->b_bufsize
;
3625 if ((vm_size_t
)bp
->b_bufsize
< desired_size
) {
3626 /* reallocate to a bigger size */
3627 bp
->b_datap
= (uintptr_t)NULL
;
3628 kmem_alloc_kobject(kernel_map
, (vm_offset_t
*)&bp
->b_datap
, desired_size
, VM_KERN_MEMORY_FILE
);
3629 bcopy((const void *)elem
, (caddr_t
)bp
->b_datap
, bp
->b_bufsize
);
3630 kmem_free(kernel_map
, elem
, bp
->b_bufsize
);
3632 desired_size
= bp
->b_bufsize
;
3636 /* new allocation */
3637 if (nsize
<= MAXMETA
) {
3638 desired_size
= nsize
;
3640 /* b_datap not really a ptr */
3641 *(void **)(&bp
->b_datap
) = grab_memory_for_meta_buf(nsize
);
3642 SET(bp
->b_flags
, B_ZALLOC
);
3644 kmem_alloc_kobject(kernel_map
, (vm_offset_t
*)&bp
->b_datap
, desired_size
, VM_KERN_MEMORY_FILE
);
3648 if (bp
->b_datap
== 0) {
3649 panic("allocbuf: NULL b_datap");
3652 bp
->b_bufsize
= desired_size
;
3653 bp
->b_bcount
= size
;
3659 * Get a new buffer from one of the free lists.
3661 * Request for a queue is passes in. The queue from which the buffer was taken
3662 * from is returned. Out of range queue requests get BQ_EMPTY. Request for
3663 * BQUEUE means no preference. Use heuristics in that case.
3664 * Heuristics is as follows:
3665 * Try BQ_AGE, BQ_LRU, BQ_EMPTY, BQ_META in that order.
3666 * If none available block till one is made available.
3667 * If buffers available on both BQ_AGE and BQ_LRU, check the timestamps.
3668 * Pick the most stale buffer.
3669 * If found buffer was marked delayed write, start the async. write
3670 * and restart the search.
3671 * Initialize the fields and disassociate the buffer from the vnode.
3672 * Remove the buffer from the hash. Return the buffer and the queue
3673 * on which it was found.
3675 * buf_mtxp is held upon entry
3676 * returns with buf_mtxp locked if new buf available
3677 * returns with buf_mtxp UNlocked if new buf NOT available
3681 getnewbuf(int slpflag
, int slptimeo
, int * queue
)
3687 int age_time
, lru_time
, bp_time
, meta_time
;
3688 int req
= *queue
; /* save it for restarts */
3693 * invalid request gets empty queue
3695 if ((*queue
>= BQUEUES
) || (*queue
< 0)
3696 || (*queue
== BQ_LAUNDRY
) || (*queue
== BQ_LOCKED
)) {
3701 if (*queue
== BQ_EMPTY
&& (bp
= bufqueues
[*queue
].tqh_first
)) {
3706 * need to grow number of bufs, add another one rather than recycling
3708 if (nbuf_headers
< max_nbuf_headers
) {
3710 * Increment count now as lock
3711 * is dropped for allocation.
3712 * That avoids over commits
3717 /* Try for the requested queue first */
3718 bp
= bufqueues
[*queue
].tqh_first
;
3723 /* Unable to use requested queue */
3724 age_bp
= bufqueues
[BQ_AGE
].tqh_first
;
3725 lru_bp
= bufqueues
[BQ_LRU
].tqh_first
;
3726 meta_bp
= bufqueues
[BQ_META
].tqh_first
;
3728 if (!age_bp
&& !lru_bp
&& !meta_bp
) {
3730 * Unavailble on AGE or LRU or META queues
3731 * Try the empty list first
3733 bp
= bufqueues
[BQ_EMPTY
].tqh_first
;
3739 * We have seen is this is hard to trigger.
3740 * This is an overcommit of nbufs but needed
3741 * in some scenarios with diskiamges
3745 lck_mtx_unlock(buf_mtxp
);
3747 /* Create a new temporary buffer header */
3748 bp
= (struct buf
*)zalloc(buf_hdr_zone
);
3752 bp
->b_whichq
= BQ_EMPTY
;
3753 bp
->b_timestamp
= buf_timestamp();
3755 SET(bp
->b_flags
, B_HDRALLOC
);
3758 lck_mtx_lock_spin(buf_mtxp
);
3761 binshash(bp
, &invalhash
);
3762 binsheadfree(bp
, &bufqueues
[BQ_EMPTY
], BQ_EMPTY
);
3766 /* subtract already accounted bufcount */
3769 bufstats
.bufs_sleeps
++;
3771 /* wait for a free buffer of any kind */
3773 /* hz value is 100 */
3774 ts
.tv_sec
= (slptimeo
/ 1000);
3775 /* the hz value is 100; which leads to 10ms */
3776 ts
.tv_nsec
= (slptimeo
% 1000) * NSEC_PER_USEC
* 1000 * 10;
3778 msleep(&needbuffer
, buf_mtxp
, slpflag
| PDROP
| (PRIBIO
+ 1), "getnewbuf", &ts
);
3782 /* Buffer available either on AGE or LRU or META */
3786 /* Buffer available either on AGE or LRU */
3790 } else if (!lru_bp
) {
3793 } else { /* buffer available on both AGE and LRU */
3794 int t
= buf_timestamp();
3796 age_time
= t
- age_bp
->b_timestamp
;
3797 lru_time
= t
- lru_bp
->b_timestamp
;
3798 if ((age_time
< 0) || (lru_time
< 0)) { /* time set backwards */
3802 * we should probably re-timestamp eveything in the
3803 * queues at this point with the current time
3806 if ((lru_time
>= lru_is_stale
) && (age_time
< age_is_stale
)) {
3816 if (!bp
) { /* Neither on AGE nor on LRU */
3819 } else if (meta_bp
) {
3820 int t
= buf_timestamp();
3822 bp_time
= t
- bp
->b_timestamp
;
3823 meta_time
= t
- meta_bp
->b_timestamp
;
3825 if (!(bp_time
< 0) && !(meta_time
< 0)) {
3826 /* time not set backwards */
3828 bp_is_stale
= (*queue
== BQ_LRU
) ?
3829 lru_is_stale
: age_is_stale
;
3831 if ((meta_time
>= meta_is_stale
) &&
3832 (bp_time
< bp_is_stale
)) {
3839 if (ISSET(bp
->b_flags
, B_LOCKED
) || ISSET(bp
->b_lflags
, BL_BUSY
)) {
3840 panic("getnewbuf: bp @ %p is LOCKED or BUSY! (flags 0x%x)\n", bp
, bp
->b_flags
);
3844 if (bcleanbuf(bp
, FALSE
)) {
3846 * moved to the laundry thread, buffer not ready
3857 * Returns 0 if buffer is ready to use,
3858 * Returns 1 if issued a buf_bawrite() to indicate
3859 * that the buffer is not ready.
3861 * buf_mtxp is held upon entry
3862 * returns with buf_mtxp locked
3865 bcleanbuf(buf_t bp
, boolean_t discard
)
3867 /* Remove from the queue */
3868 bremfree_locked(bp
);
3871 bp
->b_owner
= current_thread();
3875 * If buffer was a delayed write, start the IO by queuing
3876 * it on the LAUNDRY queue, and return 1
3878 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
3880 SET(bp
->b_lflags
, BL_WANTDEALLOC
);
3885 lck_mtx_unlock(buf_mtxp
);
3887 wakeup(&bufqueues
[BQ_LAUNDRY
]);
3889 * and give it a chance to run
3891 (void)thread_block(THREAD_CONTINUE_NULL
);
3893 lck_mtx_lock_spin(buf_mtxp
);
3898 bp
->b_owner
= current_thread();
3902 * Buffer is no longer on any free list... we own it
3904 SET(bp
->b_lflags
, BL_BUSY
);
3910 * disassociate us from our vnode, if we had one...
3916 lck_mtx_unlock(buf_mtxp
);
3920 if (ISSET(bp
->b_flags
, B_META
)) {
3921 buf_free_meta_store(bp
);
3924 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
3926 buf_release_credentials(bp
);
3928 /* If discarding, just move to the empty queue */
3930 lck_mtx_lock_spin(buf_mtxp
);
3931 CLR(bp
->b_flags
, (B_META
| B_ZALLOC
| B_DELWRI
| B_LOCKED
| B_AGE
| B_ASYNC
| B_NOCACHE
| B_FUA
));
3932 bp
->b_whichq
= BQ_EMPTY
;
3933 binshash(bp
, &invalhash
);
3934 binsheadfree(bp
, &bufqueues
[BQ_EMPTY
], BQ_EMPTY
);
3935 CLR(bp
->b_lflags
, BL_BUSY
);
3938 /* Not discarding: clean up and prepare for reuse */
3940 bp
->b_datap
= (uintptr_t)NULL
;
3941 bp
->b_upl
= (void *)NULL
;
3942 bp
->b_fsprivate
= (void *)NULL
;
3944 * preserve the state of whether this buffer
3945 * was allocated on the fly or not...
3946 * the only other flag that should be set at
3947 * this point is BL_BUSY...
3950 bp
->b_owner
= current_thread();
3953 bp
->b_lflags
= BL_BUSY
;
3954 bp
->b_flags
= (bp
->b_flags
& B_HDRALLOC
);
3955 bp
->b_redundancy_flags
= 0;
3957 bp
->b_blkno
= bp
->b_lblkno
= 0;
3958 bp
->b_iodone
= NULL
;
3962 bp
->b_dirtyoff
= bp
->b_dirtyend
= 0;
3963 bp
->b_validoff
= bp
->b_validend
= 0;
3964 bzero(&bp
->b_attr
, sizeof(struct bufattr
));
3966 lck_mtx_lock_spin(buf_mtxp
);
3974 buf_invalblkno(vnode_t vp
, daddr64_t lblkno
, int flags
)
3978 struct bufhashhdr
*dp
;
3980 dp
= BUFHASH(vp
, lblkno
);
3983 lck_mtx_lock_spin(buf_mtxp
);
3985 if ((bp
= incore_locked(vp
, lblkno
, dp
)) == (struct buf
*)0) {
3986 lck_mtx_unlock(buf_mtxp
);
3989 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
3990 if (!ISSET(flags
, BUF_WAIT
)) {
3991 lck_mtx_unlock(buf_mtxp
);
3994 SET(bp
->b_lflags
, BL_WANTED
);
3996 error
= msleep((caddr_t
)bp
, buf_mtxp
, PDROP
| (PRIBIO
+ 1), "buf_invalblkno", NULL
);
4003 bremfree_locked(bp
);
4004 SET(bp
->b_lflags
, BL_BUSY
);
4005 SET(bp
->b_flags
, B_INVAL
);
4008 bp
->b_owner
= current_thread();
4011 lck_mtx_unlock(buf_mtxp
);
4021 int need_wakeup
= 0;
4023 lck_mtx_lock_spin(buf_mtxp
);
4025 if (ISSET(bp
->b_lflags
, BL_WANTED
)) {
4027 * delay the actual wakeup until after we
4028 * clear BL_BUSY and we've dropped buf_mtxp
4033 bp
->b_owner
= current_thread();
4037 * Unlock the buffer.
4039 CLR(bp
->b_lflags
, (BL_BUSY
| BL_WANTED
));
4042 lck_mtx_unlock(buf_mtxp
);
4046 * Wake up any proceeses waiting for _this_ buffer to become free.
4054 buf_acquire(buf_t bp
, int flags
, int slpflag
, int slptimeo
)
4058 lck_mtx_lock_spin(buf_mtxp
);
4060 error
= buf_acquire_locked(bp
, flags
, slpflag
, slptimeo
);
4062 lck_mtx_unlock(buf_mtxp
);
4069 buf_acquire_locked(buf_t bp
, int flags
, int slpflag
, int slptimeo
)
4074 if (ISSET(bp
->b_flags
, B_LOCKED
)) {
4075 if ((flags
& BAC_SKIP_LOCKED
)) {
4079 if ((flags
& BAC_SKIP_NONLOCKED
)) {
4083 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
4085 * since the lck_mtx_lock may block, the buffer
4086 * may become BUSY, so we need to
4087 * recheck for a NOWAIT request
4089 if (flags
& BAC_NOWAIT
) {
4092 SET(bp
->b_lflags
, BL_WANTED
);
4094 /* the hz value is 100; which leads to 10ms */
4095 ts
.tv_sec
= (slptimeo
/ 100);
4096 ts
.tv_nsec
= (slptimeo
% 100) * 10 * NSEC_PER_USEC
* 1000;
4097 error
= msleep((caddr_t
)bp
, buf_mtxp
, slpflag
| (PRIBIO
+ 1), "buf_acquire", &ts
);
4104 if (flags
& BAC_REMOVE
) {
4105 bremfree_locked(bp
);
4107 SET(bp
->b_lflags
, BL_BUSY
);
4111 bp
->b_owner
= current_thread();
4119 * Wait for operations on the buffer to complete.
4120 * When they do, extract and return the I/O's error value.
4123 buf_biowait(buf_t bp
)
4125 while (!ISSET(bp
->b_flags
, B_DONE
)) {
4126 lck_mtx_lock_spin(buf_mtxp
);
4128 if (!ISSET(bp
->b_flags
, B_DONE
)) {
4129 DTRACE_IO1(wait__start
, buf_t
, bp
);
4130 (void) msleep(bp
, buf_mtxp
, PDROP
| (PRIBIO
+ 1), "buf_biowait", NULL
);
4131 DTRACE_IO1(wait__done
, buf_t
, bp
);
4133 lck_mtx_unlock(buf_mtxp
);
4136 /* check for interruption of I/O (e.g. via NFS), then errors. */
4137 if (ISSET(bp
->b_flags
, B_EINTR
)) {
4138 CLR(bp
->b_flags
, B_EINTR
);
4140 } else if (ISSET(bp
->b_flags
, B_ERROR
)) {
4141 return bp
->b_error
? bp
->b_error
: EIO
;
4149 * Mark I/O complete on a buffer.
4151 * If a callback has been requested, e.g. the pageout
4152 * daemon, do so. Otherwise, awaken waiting processes.
4154 * [ Leffler, et al., says on p.247:
4155 * "This routine wakes up the blocked process, frees the buffer
4156 * for an asynchronous write, or, for a request by the pagedaemon
4157 * process, invokes a procedure specified in the buffer structure" ]
4159 * In real life, the pagedaemon (or other system processes) wants
4160 * to do async stuff to, and doesn't want the buffer buf_brelse()'d.
4161 * (for swap pager, that puts swap buffers on the free lists (!!!),
4162 * for the vn device, that puts malloc'd buffers on the free lists!)
4166 buf_biodone(buf_t bp
)
4169 struct bufattr
*bap
;
4170 struct timeval real_elapsed
;
4171 uint64_t real_elapsed_usec
= 0;
4173 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 387)) | DBG_FUNC_START
,
4174 bp
, bp
->b_datap
, bp
->b_flags
, 0, 0);
4176 if (ISSET(bp
->b_flags
, B_DONE
)) {
4177 panic("biodone already");
4182 if (bp
->b_vp
&& bp
->b_vp
->v_mount
) {
4183 mp
= bp
->b_vp
->v_mount
;
4188 if (ISSET(bp
->b_flags
, B_ERROR
)) {
4189 if (mp
&& (MNT_ROOTFS
& mp
->mnt_flag
)) {
4190 dk_error_description_t desc
;
4191 bzero(&desc
, sizeof(desc
));
4192 desc
.description
= panic_disk_error_description
;
4193 desc
.description_size
= panic_disk_error_description_size
;
4194 VNOP_IOCTL(mp
->mnt_devvp
, DKIOCGETERRORDESCRIPTION
, (caddr_t
)&desc
, 0, vfs_context_kernel());
4198 if (mp
&& (bp
->b_flags
& B_READ
) == 0) {
4199 update_last_io_time(mp
);
4200 INCR_PENDING_IO(-(pending_io_t
)buf_count(bp
), mp
->mnt_pending_write_size
);
4202 INCR_PENDING_IO(-(pending_io_t
)buf_count(bp
), mp
->mnt_pending_read_size
);
4205 throttle_info_end_io(bp
);
4207 if (kdebug_enable
) {
4208 int code
= DKIO_DONE
;
4209 int io_tier
= GET_BUFATTR_IO_TIER(bap
);
4211 if (bp
->b_flags
& B_READ
) {
4214 if (bp
->b_flags
& B_ASYNC
) {
4218 if (bp
->b_flags
& B_META
) {
4220 } else if (bp
->b_flags
& B_PAGEIO
) {
4221 code
|= DKIO_PAGING
;
4225 code
|= DKIO_THROTTLE
;
4228 code
|= ((io_tier
<< DKIO_TIER_SHIFT
) & DKIO_TIER_MASK
);
4230 if (bp
->b_flags
& B_PASSIVE
) {
4231 code
|= DKIO_PASSIVE
;
4234 if (bap
->ba_flags
& BA_NOCACHE
) {
4235 code
|= DKIO_NOCACHE
;
4238 if (bap
->ba_flags
& BA_IO_TIER_UPGRADE
) {
4239 code
|= DKIO_TIER_UPGRADE
;
4242 KDBG_RELEASE_NOPROCFILT(FSDBG_CODE(DBG_DKRW
, code
),
4243 buf_kernel_addrperm_addr(bp
),
4244 (uintptr_t)VM_KERNEL_ADDRPERM(bp
->b_vp
), bp
->b_resid
,
4248 microuptime(&real_elapsed
);
4249 timevalsub(&real_elapsed
, &bp
->b_timestamp_tv
);
4250 real_elapsed_usec
= real_elapsed
.tv_sec
* USEC_PER_SEC
+ real_elapsed
.tv_usec
;
4251 disk_conditioner_delay(bp
, 1, bp
->b_bcount
, real_elapsed_usec
);
4254 * I/O was done, so don't believe
4255 * the DIRTY state from VM anymore...
4256 * and we need to reset the THROTTLED/PASSIVE
4259 CLR(bp
->b_flags
, (B_WASDIRTY
| B_PASSIVE
));
4260 CLR(bap
->ba_flags
, (BA_META
| BA_NOCACHE
| BA_DELAYIDLESLEEP
| BA_IO_TIER_UPGRADE
));
4262 SET_BUFATTR_IO_TIER(bap
, 0);
4264 DTRACE_IO1(done
, buf_t
, bp
);
4266 if (!ISSET(bp
->b_flags
, B_READ
) && !ISSET(bp
->b_flags
, B_RAW
)) {
4268 * wake up any writer's blocked
4269 * on throttle or waiting for I/O
4272 vnode_writedone(bp
->b_vp
);
4275 if (ISSET(bp
->b_flags
, (B_CALL
| B_FILTER
))) { /* if necessary, call out */
4276 void (*iodone_func
)(struct buf
*, void *) = bp
->b_iodone
;
4277 void *arg
= bp
->b_transaction
;
4278 int callout
= ISSET(bp
->b_flags
, B_CALL
);
4280 if (iodone_func
== NULL
) {
4281 panic("biodone: bp @ %p has NULL b_iodone!\n", bp
);
4284 CLR(bp
->b_flags
, (B_CALL
| B_FILTER
)); /* filters and callouts are one-shot */
4285 bp
->b_iodone
= NULL
;
4286 bp
->b_transaction
= NULL
;
4289 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
4291 (*iodone_func
)(bp
, arg
);
4295 * assumes that the callback function takes
4296 * ownership of the bp and deals with releasing it if necessary
4301 * in this case the call back function is acting
4302 * strictly as a filter... it does not take
4303 * ownership of the bp and is expecting us
4304 * to finish cleaning up... this is currently used
4305 * by the HFS journaling code
4308 if (ISSET(bp
->b_flags
, B_ASYNC
)) { /* if async, release it */
4309 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
4312 } else { /* or just wakeup the buffer */
4314 * by taking the mutex, we serialize
4315 * the buf owner calling buf_biowait so that we'll
4316 * only see him in one of 2 states...
4317 * state 1: B_DONE wasn't set and he's
4319 * state 2: he's blocked trying to take the
4320 * mutex before looking at B_DONE
4321 * BL_WANTED is cleared in case anyone else
4322 * is blocked waiting for the buffer... note
4323 * that we haven't cleared B_BUSY yet, so if
4324 * they do get to run, their going to re-set
4325 * BL_WANTED and go back to sleep
4327 lck_mtx_lock_spin(buf_mtxp
);
4329 CLR(bp
->b_lflags
, BL_WANTED
);
4330 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
4332 lck_mtx_unlock(buf_mtxp
);
4337 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 387)) | DBG_FUNC_END
,
4338 (uintptr_t)bp
, (uintptr_t)bp
->b_datap
, bp
->b_flags
, 0, 0);
4342 * Obfuscate buf pointers.
4345 buf_kernel_addrperm_addr(void * addr
)
4347 if ((vm_offset_t
)addr
== 0) {
4350 return (vm_offset_t
)addr
+ buf_kernel_addrperm
;
4355 * Return a count of buffers on the "locked" queue.
4358 count_lock_queue(void)
4363 lck_mtx_lock_spin(buf_mtxp
);
4365 for (bp
= bufqueues
[BQ_LOCKED
].tqh_first
; bp
;
4366 bp
= bp
->b_freelist
.tqe_next
) {
4369 lck_mtx_unlock(buf_mtxp
);
4375 * Return a count of 'busy' buffers. Used at the time of shutdown.
4376 * note: This is also called from the mach side in debug context in kdp.c
4379 count_busy_buffers(void)
4381 return buf_busycount
+ bufstats
.bufs_iobufinuse
;
4386 * Print out statistics on the current allocation of the buffer pool.
4387 * Can be enabled to print out on every ``sync'' by setting "syncprt"
4388 * in vfs_syscalls.c using sysctl.
4396 int counts
[MAXBSIZE
/ CLBYTES
+ 1];
4397 static char *bname
[BQUEUES
] =
4398 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
4400 for (dp
= bufqueues
, i
= 0; dp
< &bufqueues
[BQUEUES
]; dp
++, i
++) {
4402 for (j
= 0; j
<= MAXBSIZE
/ CLBYTES
; j
++) {
4406 lck_mtx_lock(buf_mtxp
);
4408 for (bp
= dp
->tqh_first
; bp
; bp
= bp
->b_freelist
.tqe_next
) {
4409 counts
[bp
->b_bufsize
/ CLBYTES
]++;
4412 lck_mtx_unlock(buf_mtxp
);
4414 printf("%s: total-%d", bname
[i
], count
);
4415 for (j
= 0; j
<= MAXBSIZE
/ CLBYTES
; j
++) {
4416 if (counts
[j
] != 0) {
4417 printf(", %d-%d", j
* CLBYTES
, counts
[j
]);
4423 #endif /* DIAGNOSTIC */
4425 #define NRESERVEDIOBUFS 128
4427 #define MNT_VIRTUALDEV_MAX_IOBUFS 16
4428 #define VIRTUALDEV_MAX_IOBUFS ((40*niobuf_headers)/100)
4431 alloc_io_buf(vnode_t vp
, int priv
)
4435 int alloc_for_virtualdev
= FALSE
;
4437 lck_mtx_lock_spin(iobuffer_mtxp
);
4440 * We subject iobuf requests for diskimages to additional restrictions.
4442 * a) A single diskimage mount cannot use up more than
4443 * MNT_VIRTUALDEV_MAX_IOBUFS. However,vm privileged (pageout) requests
4444 * are not subject to this restriction.
4445 * b) iobuf headers used by all diskimage headers by all mount
4446 * points cannot exceed VIRTUALDEV_MAX_IOBUFS.
4448 if (vp
&& ((mp
= vp
->v_mount
)) && mp
!= dead_mountp
&&
4449 mp
->mnt_kern_flag
& MNTK_VIRTUALDEV
) {
4450 alloc_for_virtualdev
= TRUE
;
4451 while ((!priv
&& mp
->mnt_iobufinuse
> MNT_VIRTUALDEV_MAX_IOBUFS
) ||
4452 bufstats
.bufs_iobufinuse_vdev
> VIRTUALDEV_MAX_IOBUFS
) {
4453 bufstats
.bufs_iobufsleeps
++;
4456 (void)msleep(&need_iobuffer
, iobuffer_mtxp
,
4457 PSPIN
| (PRIBIO
+ 1), (const char *)"alloc_io_buf (1)",
4462 while (((niobuf_headers
- NRESERVEDIOBUFS
< bufstats
.bufs_iobufinuse
) && !priv
) ||
4463 (bp
= iobufqueue
.tqh_first
) == NULL
) {
4464 bufstats
.bufs_iobufsleeps
++;
4467 (void)msleep(&need_iobuffer
, iobuffer_mtxp
, PSPIN
| (PRIBIO
+ 1),
4468 (const char *)"alloc_io_buf (2)", NULL
);
4470 TAILQ_REMOVE(&iobufqueue
, bp
, b_freelist
);
4472 bufstats
.bufs_iobufinuse
++;
4473 if (bufstats
.bufs_iobufinuse
> bufstats
.bufs_iobufmax
) {
4474 bufstats
.bufs_iobufmax
= bufstats
.bufs_iobufinuse
;
4477 if (alloc_for_virtualdev
) {
4478 mp
->mnt_iobufinuse
++;
4479 bufstats
.bufs_iobufinuse_vdev
++;
4482 lck_mtx_unlock(iobuffer_mtxp
);
4485 * initialize various fields
4486 * we don't need to hold the mutex since the buffer
4487 * is now private... the vp should have a reference
4488 * on it and is not protected by this mutex in any event
4490 bp
->b_timestamp
= 0;
4495 bp
->b_lflags
= BL_BUSY
| BL_IOBUF
;
4496 if (alloc_for_virtualdev
) {
4497 bp
->b_lflags
|= BL_IOBUF_VDEV
;
4499 bp
->b_redundancy_flags
= 0;
4500 bp
->b_blkno
= bp
->b_lblkno
= 0;
4502 bp
->b_owner
= current_thread();
4505 bp
->b_iodone
= NULL
;
4511 bp
->b_fsprivate
= (void *)NULL
;
4513 bzero(&bp
->b_attr
, sizeof(struct bufattr
));
4515 if (vp
&& (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
)) {
4516 bp
->b_dev
= vp
->v_rdev
;
4526 free_io_buf(buf_t bp
)
4528 int need_wakeup
= 0;
4529 int free_for_virtualdev
= FALSE
;
4532 /* Was this iobuf for a diskimage ? */
4533 if (bp
->b_lflags
& BL_IOBUF_VDEV
) {
4534 free_for_virtualdev
= TRUE
;
4536 mp
= bp
->b_vp
->v_mount
;
4541 * put buffer back on the head of the iobufqueue
4544 bp
->b_flags
= B_INVAL
;
4546 /* Zero out the bufattr and its flags before relinquishing this iobuf */
4547 bzero(&bp
->b_attr
, sizeof(struct bufattr
));
4549 lck_mtx_lock_spin(iobuffer_mtxp
);
4551 binsheadfree(bp
, &iobufqueue
, -1);
4553 if (need_iobuffer
) {
4555 * Wake up any processes waiting because they need an io buffer
4557 * do the wakeup after we drop the mutex... it's possible that the
4558 * wakeup will be superfluous if need_iobuffer gets set again and
4559 * another thread runs this path, but it's highly unlikely, doesn't
4560 * hurt, and it means we don't hold up I/O progress if the wakeup blocks
4561 * trying to grab a task related lock...
4566 if (bufstats
.bufs_iobufinuse
<= 0) {
4567 panic("free_io_buf: bp(%p) - bufstats.bufs_iobufinuse < 0", bp
);
4570 bufstats
.bufs_iobufinuse
--;
4572 if (free_for_virtualdev
) {
4573 bufstats
.bufs_iobufinuse_vdev
--;
4574 if (mp
&& mp
!= dead_mountp
) {
4575 mp
->mnt_iobufinuse
--;
4579 lck_mtx_unlock(iobuffer_mtxp
);
4582 wakeup(&need_iobuffer
);
4590 lck_mtx_lock_spin(buf_mtxp
);
4594 buf_list_unlock(void)
4596 lck_mtx_unlock(buf_mtxp
);
4600 * If getnewbuf() calls bcleanbuf() on the same thread
4601 * there is a potential for stack overrun and deadlocks.
4602 * So we always handoff the work to a worker thread for completion
4607 bcleanbuf_thread_init(void)
4609 thread_t thread
= THREAD_NULL
;
4611 /* create worker thread */
4612 kernel_thread_start((thread_continue_t
)bcleanbuf_thread
, NULL
, &thread
);
4613 thread_deallocate(thread
);
4616 typedef int (*bcleanbufcontinuation
)(int);
4618 __attribute__((noreturn
))
4620 bcleanbuf_thread(void)
4627 lck_mtx_lock_spin(buf_mtxp
);
4629 while ((bp
= TAILQ_FIRST(&bufqueues
[BQ_LAUNDRY
])) == NULL
) {
4630 (void)msleep0(&bufqueues
[BQ_LAUNDRY
], buf_mtxp
, PRIBIO
| PDROP
, "blaundry", 0, (bcleanbufcontinuation
)bcleanbuf_thread
);
4634 * Remove from the queue
4636 bremfree_locked(bp
);
4639 * Buffer is no longer on any free list
4641 SET(bp
->b_lflags
, BL_BUSY
);
4645 bp
->b_owner
= current_thread();
4649 lck_mtx_unlock(buf_mtxp
);
4653 error
= bawrite_internal(bp
, 0);
4656 bp
->b_whichq
= BQ_LAUNDRY
;
4657 bp
->b_timestamp
= buf_timestamp();
4659 lck_mtx_lock_spin(buf_mtxp
);
4661 binstailfree(bp
, &bufqueues
[BQ_LAUNDRY
], BQ_LAUNDRY
);
4664 /* we never leave a busy page on the laundry queue */
4665 CLR(bp
->b_lflags
, BL_BUSY
);
4668 bp
->b_owner
= current_thread();
4672 lck_mtx_unlock(buf_mtxp
);
4674 if (loopcnt
> MAXLAUNDRY
) {
4676 * bawrite_internal() can return errors if we're throttled. If we've
4677 * done several I/Os and failed, give the system some time to unthrottle
4680 (void)tsleep((void *)&bufqueues
[BQ_LAUNDRY
], PRIBIO
, "blaundry", 1);
4683 /* give other threads a chance to run */
4684 (void)thread_block(THREAD_CONTINUE_NULL
);
4693 brecover_data(buf_t bp
)
4697 upl_page_info_t
*pl
;
4699 vnode_t vp
= bp
->b_vp
;
4703 if (!UBCINFOEXISTS(vp
) || bp
->b_bufsize
== 0) {
4707 upl_flags
= UPL_PRECIOUS
;
4708 if (!(buf_flags(bp
) & B_READ
)) {
4710 * "write" operation: let the UPL subsystem know
4711 * that we intend to modify the buffer cache pages we're
4714 upl_flags
|= UPL_WILL_MODIFY
;
4717 kret
= ubc_create_upl_kernel(vp
,
4718 ubc_blktooff(vp
, bp
->b_lblkno
),
4723 VM_KERN_MEMORY_FILE
);
4724 if (kret
!= KERN_SUCCESS
) {
4725 panic("Failed to create UPL");
4728 for (upl_offset
= 0; upl_offset
< bp
->b_bufsize
; upl_offset
+= PAGE_SIZE
) {
4729 if (!upl_valid_page(pl
, upl_offset
/ PAGE_SIZE
) || !upl_dirty_page(pl
, upl_offset
/ PAGE_SIZE
)) {
4730 ubc_upl_abort(upl
, 0);
4736 kret
= ubc_upl_map(upl
, (vm_offset_t
*)&(bp
->b_datap
));
4738 if (kret
!= KERN_SUCCESS
) {
4739 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
4745 SET(bp
->b_flags
, B_INVAL
);
4752 fs_buffer_cache_gc_register(void (* callout
)(int, void *), void *context
)
4754 lck_mtx_lock(buf_gc_callout
);
4755 for (int i
= 0; i
< FS_BUFFER_CACHE_GC_CALLOUTS_MAX_SIZE
; i
++) {
4756 if (fs_callouts
[i
].callout
== NULL
) {
4757 fs_callouts
[i
].callout
= callout
;
4758 fs_callouts
[i
].context
= context
;
4759 lck_mtx_unlock(buf_gc_callout
);
4764 lck_mtx_unlock(buf_gc_callout
);
4769 fs_buffer_cache_gc_unregister(void (* callout
)(int, void *), void *context
)
4771 lck_mtx_lock(buf_gc_callout
);
4772 for (int i
= 0; i
< FS_BUFFER_CACHE_GC_CALLOUTS_MAX_SIZE
; i
++) {
4773 if (fs_callouts
[i
].callout
== callout
&&
4774 fs_callouts
[i
].context
== context
) {
4775 fs_callouts
[i
].callout
= NULL
;
4776 fs_callouts
[i
].context
= NULL
;
4779 lck_mtx_unlock(buf_gc_callout
);
4784 fs_buffer_cache_gc_dispatch_callouts(int all
)
4786 lck_mtx_lock(buf_gc_callout
);
4787 for (int i
= 0; i
< FS_BUFFER_CACHE_GC_CALLOUTS_MAX_SIZE
; i
++) {
4788 if (fs_callouts
[i
].callout
!= NULL
) {
4789 fs_callouts
[i
].callout(all
, fs_callouts
[i
].context
);
4792 lck_mtx_unlock(buf_gc_callout
);
4796 buffer_cache_gc(int all
)
4799 boolean_t did_large_zfree
= FALSE
;
4800 boolean_t need_wakeup
= FALSE
;
4801 int now
= buf_timestamp();
4803 struct bqueues privq
;
4804 int thresh_hold
= BUF_STALE_THRESHHOLD
;
4810 * We only care about metadata (incore storage comes from zalloc()).
4811 * Unless "all" is set (used to evict meta data buffers in preparation
4812 * for deep sleep), we only evict up to BUF_MAX_GC_BATCH_SIZE buffers
4813 * that have not been accessed in the last BUF_STALE_THRESHOLD seconds.
4814 * BUF_MAX_GC_BATCH_SIZE controls both the hold time of the global lock
4815 * "buf_mtxp" and the length of time we spend compute bound in the GC
4816 * thread which calls this function
4818 lck_mtx_lock(buf_mtxp
);
4823 need_wakeup
= FALSE
;
4825 while (((bp
= TAILQ_FIRST(&bufqueues
[BQ_META
]))) &&
4826 (now
> bp
->b_timestamp
) &&
4827 (now
- bp
->b_timestamp
> thresh_hold
) &&
4828 (found
< BUF_MAX_GC_BATCH_SIZE
)) {
4829 /* Remove from free list */
4830 bremfree_locked(bp
);
4834 bp
->b_owner
= current_thread();
4838 /* If dirty, move to laundry queue and remember to do wakeup */
4839 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
4840 SET(bp
->b_lflags
, BL_WANTDEALLOC
);
4849 * Mark busy and put on private list. We could technically get
4850 * away without setting BL_BUSY here.
4852 SET(bp
->b_lflags
, BL_BUSY
);
4856 * Remove from hash and dissociate from vp.
4863 TAILQ_INSERT_TAIL(&privq
, bp
, b_freelist
);
4870 /* Drop lock for batch processing */
4871 lck_mtx_unlock(buf_mtxp
);
4873 /* Wakeup and yield for laundry if need be */
4875 wakeup(&bufqueues
[BQ_LAUNDRY
]);
4876 (void)thread_block(THREAD_CONTINUE_NULL
);
4879 /* Clean up every buffer on private list */
4880 TAILQ_FOREACH(bp
, &privq
, b_freelist
) {
4881 /* Take note if we've definitely freed at least a page to a zone */
4882 if ((ISSET(bp
->b_flags
, B_ZALLOC
)) && (buf_size(bp
) >= PAGE_SIZE
)) {
4883 did_large_zfree
= TRUE
;
4886 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
4889 buf_free_meta_store(bp
);
4891 /* Release credentials */
4892 buf_release_credentials(bp
);
4894 /* Prepare for moving to empty queue */
4895 CLR(bp
->b_flags
, (B_META
| B_ZALLOC
| B_DELWRI
| B_LOCKED
4896 | B_AGE
| B_ASYNC
| B_NOCACHE
| B_FUA
));
4897 bp
->b_whichq
= BQ_EMPTY
;
4900 lck_mtx_lock(buf_mtxp
);
4902 /* Back under lock, move them all to invalid hash and clear busy */
4903 TAILQ_FOREACH(bp
, &privq
, b_freelist
) {
4904 binshash(bp
, &invalhash
);
4905 CLR(bp
->b_lflags
, BL_BUSY
);
4909 if (bp
->b_owner
!= current_thread()) {
4910 panic("Buffer stolen from buffer_cache_gc()");
4912 bp
->b_owner
= current_thread();
4917 /* And do a big bulk move to the empty queue */
4918 TAILQ_CONCAT(&bufqueues
[BQ_EMPTY
], &privq
, b_freelist
);
4919 } while (all
&& (found
== BUF_MAX_GC_BATCH_SIZE
));
4921 lck_mtx_unlock(buf_mtxp
);
4923 fs_buffer_cache_gc_dispatch_callouts(all
);
4925 return did_large_zfree
;
4938 bp_cmp(void *a
, void *b
)
4940 buf_t
*bp_a
= *(buf_t
**)a
,
4941 *bp_b
= *(buf_t
**)b
;
4944 // don't have to worry about negative block
4945 // numbers so this is ok to do.
4947 res
= (bp_a
->b_blkno
- bp_b
->b_blkno
);
4954 bflushq(int whichq
, mount_t mp
)
4958 int total_writes
= 0;
4959 static buf_t flush_table
[NFLUSH
];
4961 if (whichq
< 0 || whichq
>= BQUEUES
) {
4966 lck_mtx_lock(buf_mtxp
);
4968 bp
= TAILQ_FIRST(&bufqueues
[whichq
]);
4970 for (buf_count
= 0; bp
; bp
= next
) {
4971 next
= bp
->b_freelist
.tqe_next
;
4973 if (bp
->b_vp
== NULL
|| bp
->b_vp
->v_mount
!= mp
) {
4977 if (ISSET(bp
->b_flags
, B_DELWRI
) && !ISSET(bp
->b_lflags
, BL_BUSY
)) {
4978 bremfree_locked(bp
);
4980 bp
->b_owner
= current_thread();
4983 SET(bp
->b_lflags
, BL_BUSY
);
4986 flush_table
[buf_count
] = bp
;
4990 if (buf_count
>= NFLUSH
) {
4991 lck_mtx_unlock(buf_mtxp
);
4993 qsort(flush_table
, buf_count
, sizeof(struct buf
*), bp_cmp
);
4995 for (i
= 0; i
< buf_count
; i
++) {
4996 buf_bawrite(flush_table
[i
]);
5002 lck_mtx_unlock(buf_mtxp
);
5004 if (buf_count
> 0) {
5005 qsort(flush_table
, buf_count
, sizeof(struct buf
*), bp_cmp
);
5007 for (i
= 0; i
< buf_count
; i
++) {
5008 buf_bawrite(flush_table
[i
]);
5012 return total_writes
;