2 * Copyright (c) 2000-2016 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 /* zone allocated buffer headers */
136 static void bufzoneinit(void);
137 static void bcleanbuf_thread_init(void);
138 static void bcleanbuf_thread(void);
140 static zone_t buf_hdr_zone
;
141 static int buf_hdr_count
;
145 * Definitions for the buffer hash lists.
147 #define BUFHASH(dvp, lbn) \
148 (&bufhashtbl[((long)(dvp) / sizeof(*(dvp)) + (int)(lbn)) & bufhash])
149 LIST_HEAD(bufhashhdr
, buf
) *bufhashtbl
, invalhash
;
152 static buf_t
incore_locked(vnode_t vp
, daddr64_t blkno
, struct bufhashhdr
*dp
);
154 /* Definitions for the buffer stats. */
155 struct bufstats bufstats
;
157 /* Number of delayed write buffers */
160 static int boot_nbuf_headers
= 0;
162 static TAILQ_HEAD(delayqueue
, buf
) delaybufqueue
;
164 static TAILQ_HEAD(ioqueue
, buf
) iobufqueue
;
165 static TAILQ_HEAD(bqueues
, buf
) bufqueues
[BQUEUES
];
166 static int needbuffer
;
167 static int need_iobuffer
;
169 static lck_grp_t
*buf_mtx_grp
;
170 static lck_attr_t
*buf_mtx_attr
;
171 static lck_grp_attr_t
*buf_mtx_grp_attr
;
172 static lck_mtx_t
*iobuffer_mtxp
;
173 static lck_mtx_t
*buf_mtxp
;
175 static int buf_busycount
;
177 static __inline__
int
186 * Insq/Remq for the buffer free lists.
188 #define binsheadfree(bp, dp, whichq) do { \
189 TAILQ_INSERT_HEAD(dp, bp, b_freelist); \
192 #define binstailfree(bp, dp, whichq) do { \
193 TAILQ_INSERT_TAIL(dp, bp, b_freelist); \
196 #define BHASHENTCHECK(bp) \
197 if ((bp)->b_hash.le_prev != (struct buf **)0xdeadbeef) \
198 panic("%p: b_hash.le_prev is not deadbeef", (bp));
200 #define BLISTNONE(bp) \
201 (bp)->b_hash.le_next = (struct buf *)0; \
202 (bp)->b_hash.le_prev = (struct buf **)0xdeadbeef;
205 * Insq/Remq for the vnode usage lists.
207 #define bufinsvn(bp, dp) LIST_INSERT_HEAD(dp, bp, b_vnbufs)
208 #define bufremvn(bp) { \
209 LIST_REMOVE(bp, b_vnbufs); \
210 (bp)->b_vnbufs.le_next = NOLIST; \
214 * Time in seconds before a buffer on a list is
215 * considered as a stale buffer
217 #define LRU_IS_STALE 120 /* default value for the LRU */
218 #define AGE_IS_STALE 60 /* default value for the AGE */
219 #define META_IS_STALE 180 /* default value for the BQ_META */
221 int lru_is_stale
= LRU_IS_STALE
;
222 int age_is_stale
= AGE_IS_STALE
;
223 int meta_is_stale
= META_IS_STALE
;
225 #define MAXLAUNDRY 10
227 /* LIST_INSERT_HEAD() with assertions */
228 static __inline__
void
229 blistenterhead(struct bufhashhdr
* head
, buf_t bp
)
231 if ((bp
->b_hash
.le_next
= (head
)->lh_first
) != NULL
)
232 (head
)->lh_first
->b_hash
.le_prev
= &(bp
)->b_hash
.le_next
;
233 (head
)->lh_first
= bp
;
234 bp
->b_hash
.le_prev
= &(head
)->lh_first
;
235 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
236 panic("blistenterhead: le_prev is deadbeef");
239 static __inline__
void
240 binshash(buf_t bp
, struct bufhashhdr
*dp
)
244 #endif /* DIAGNOSTIC */
250 for(; nbp
!= NULL
; nbp
= nbp
->b_hash
.le_next
) {
252 panic("buf already in hashlist");
254 #endif /* DIAGNOSTIC */
256 blistenterhead(dp
, bp
);
259 static __inline__
void
262 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
263 panic("bremhash le_prev is deadbeef");
264 if (bp
->b_hash
.le_next
== bp
)
265 panic("bremhash: next points to self");
267 if (bp
->b_hash
.le_next
!= NULL
)
268 bp
->b_hash
.le_next
->b_hash
.le_prev
= bp
->b_hash
.le_prev
;
269 *bp
->b_hash
.le_prev
= (bp
)->b_hash
.le_next
;
275 static __inline__
void
276 bmovelaundry(buf_t bp
)
278 bp
->b_whichq
= BQ_LAUNDRY
;
279 bp
->b_timestamp
= buf_timestamp();
280 binstailfree(bp
, &bufqueues
[BQ_LAUNDRY
], BQ_LAUNDRY
);
284 static __inline__
void
285 buf_release_credentials(buf_t bp
)
287 if (IS_VALID_CRED(bp
->b_rcred
)) {
288 kauth_cred_unref(&bp
->b_rcred
);
290 if (IS_VALID_CRED(bp
->b_wcred
)) {
291 kauth_cred_unref(&bp
->b_wcred
);
297 buf_valid(buf_t bp
) {
299 if ( (bp
->b_flags
& (B_DONE
| B_DELWRI
)) )
305 buf_fromcache(buf_t bp
) {
307 if ( (bp
->b_flags
& B_CACHE
) )
313 buf_markinvalid(buf_t bp
) {
315 SET(bp
->b_flags
, B_INVAL
);
319 buf_markdelayed(buf_t bp
) {
321 if (!ISSET(bp
->b_flags
, B_DELWRI
)) {
322 SET(bp
->b_flags
, B_DELWRI
);
324 OSAddAtomicLong(1, &nbdwrite
);
325 buf_reassign(bp
, bp
->b_vp
);
327 SET(bp
->b_flags
, B_DONE
);
331 buf_markclean(buf_t bp
) {
333 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
334 CLR(bp
->b_flags
, B_DELWRI
);
336 OSAddAtomicLong(-1, &nbdwrite
);
337 buf_reassign(bp
, bp
->b_vp
);
342 buf_markeintr(buf_t bp
) {
344 SET(bp
->b_flags
, B_EINTR
);
349 buf_markaged(buf_t bp
) {
351 SET(bp
->b_flags
, B_AGE
);
357 if ((bp
->b_flags
& B_FUA
) == B_FUA
)
363 buf_markfua(buf_t bp
) {
365 SET(bp
->b_flags
, B_FUA
);
369 cpx_t
bufattr_cpx(bufattr_t bap
)
374 void bufattr_setcpx(bufattr_t bap
, cpx_t cpx
)
380 buf_setcpoff (buf_t bp
, uint64_t foffset
) {
381 bp
->b_attr
.ba_cp_file_off
= foffset
;
385 bufattr_cpoff(bufattr_t bap
) {
386 return bap
->ba_cp_file_off
;
390 bufattr_setcpoff(bufattr_t bap
, uint64_t foffset
) {
391 bap
->ba_cp_file_off
= foffset
;
394 #else // !CONTECT_PROTECT
397 bufattr_cpoff(bufattr_t bap __unused
) {
402 bufattr_setcpoff(__unused bufattr_t bap
, __unused
uint64_t foffset
) {
406 struct cpx
*bufattr_cpx(__unused bufattr_t bap
)
411 void bufattr_setcpx(__unused bufattr_t bap
, __unused
struct cpx
*cpx
)
415 #endif /* !CONFIG_PROTECT */
420 MALLOC(bap
, bufattr_t
, sizeof(struct bufattr
), M_TEMP
, M_WAITOK
);
424 bzero(bap
, sizeof(struct bufattr
));
429 bufattr_free(bufattr_t bap
) {
435 bufattr_dup(bufattr_t bap
) {
436 bufattr_t new_bufattr
;
437 MALLOC(new_bufattr
, bufattr_t
, sizeof(struct bufattr
), M_TEMP
, M_WAITOK
);
438 if (new_bufattr
== NULL
)
441 /* Copy the provided one into the new copy */
442 memcpy (new_bufattr
, bap
, sizeof(struct bufattr
));
447 bufattr_rawencrypted(bufattr_t bap
) {
448 if ( (bap
->ba_flags
& BA_RAW_ENCRYPTED_IO
) )
454 bufattr_throttled(bufattr_t bap
) {
455 return (GET_BUFATTR_IO_TIER(bap
));
459 bufattr_passive(bufattr_t bap
) {
460 if ( (bap
->ba_flags
& BA_PASSIVE
) )
466 bufattr_nocache(bufattr_t bap
) {
467 if ( (bap
->ba_flags
& BA_NOCACHE
) )
473 bufattr_meta(bufattr_t bap
) {
474 if ( (bap
->ba_flags
& BA_META
) )
480 bufattr_markmeta(bufattr_t bap
) {
481 SET(bap
->ba_flags
, BA_META
);
485 bufattr_delayidlesleep(bufattr_t bap
)
487 if ( (bap
->ba_flags
& BA_DELAYIDLESLEEP
) )
498 buf_markstatic(buf_t bp __unused
) {
499 SET(bp
->b_flags
, B_STATICCONTENT
);
503 buf_static(buf_t bp
) {
504 if ( (bp
->b_flags
& B_STATICCONTENT
) )
510 bufattr_markgreedymode(bufattr_t bap
) {
511 SET(bap
->ba_flags
, BA_GREEDY_MODE
);
515 bufattr_greedymode(bufattr_t bap
) {
516 if ( (bap
->ba_flags
& BA_GREEDY_MODE
) )
522 bufattr_markisochronous(bufattr_t bap
) {
523 SET(bap
->ba_flags
, BA_ISOCHRONOUS
);
527 bufattr_isochronous(bufattr_t bap
) {
528 if ( (bap
->ba_flags
& BA_ISOCHRONOUS
) )
534 bufattr_markquickcomplete(bufattr_t bap
) {
535 SET(bap
->ba_flags
, BA_QUICK_COMPLETE
);
539 bufattr_quickcomplete(bufattr_t bap
) {
540 if ( (bap
->ba_flags
& BA_QUICK_COMPLETE
) )
546 buf_error(buf_t bp
) {
548 return (bp
->b_error
);
552 buf_seterror(buf_t bp
, errno_t error
) {
554 if ((bp
->b_error
= error
))
555 SET(bp
->b_flags
, B_ERROR
);
557 CLR(bp
->b_flags
, B_ERROR
);
561 buf_setflags(buf_t bp
, int32_t flags
) {
563 SET(bp
->b_flags
, (flags
& BUF_X_WRFLAGS
));
567 buf_clearflags(buf_t bp
, int32_t flags
) {
569 CLR(bp
->b_flags
, (flags
& BUF_X_WRFLAGS
));
573 buf_flags(buf_t bp
) {
575 return ((bp
->b_flags
& BUF_X_RDFLAGS
));
579 buf_reset(buf_t bp
, int32_t io_flags
) {
581 CLR(bp
->b_flags
, (B_READ
| B_WRITE
| B_ERROR
| B_DONE
| B_INVAL
| B_ASYNC
| B_NOCACHE
| B_FUA
));
582 SET(bp
->b_flags
, (io_flags
& (B_ASYNC
| B_READ
| B_WRITE
| B_NOCACHE
)));
588 buf_count(buf_t bp
) {
590 return (bp
->b_bcount
);
594 buf_setcount(buf_t bp
, uint32_t bcount
) {
596 bp
->b_bcount
= bcount
;
602 return (bp
->b_bufsize
);
606 buf_setsize(buf_t bp
, uint32_t bufsize
) {
608 bp
->b_bufsize
= bufsize
;
612 buf_resid(buf_t bp
) {
614 return (bp
->b_resid
);
618 buf_setresid(buf_t bp
, uint32_t resid
) {
624 buf_dirtyoff(buf_t bp
) {
626 return (bp
->b_dirtyoff
);
630 buf_dirtyend(buf_t bp
) {
632 return (bp
->b_dirtyend
);
636 buf_setdirtyoff(buf_t bp
, uint32_t dirtyoff
) {
638 bp
->b_dirtyoff
= dirtyoff
;
642 buf_setdirtyend(buf_t bp
, uint32_t dirtyend
) {
644 bp
->b_dirtyend
= dirtyend
;
648 buf_dataptr(buf_t bp
) {
650 return (bp
->b_datap
);
654 buf_setdataptr(buf_t bp
, uintptr_t data
) {
660 buf_vnode(buf_t bp
) {
666 buf_setvnode(buf_t bp
, vnode_t vp
) {
673 buf_callback(buf_t bp
)
675 if ( !(bp
->b_flags
& B_CALL
) )
676 return ((void *) NULL
);
678 return ((void *)bp
->b_iodone
);
683 buf_setcallback(buf_t bp
, void (*callback
)(buf_t
, void *), void *transaction
)
685 assert(!ISSET(bp
->b_flags
, B_FILTER
) && ISSET(bp
->b_lflags
, BL_BUSY
));
688 bp
->b_flags
|= (B_CALL
| B_ASYNC
);
690 bp
->b_flags
&= ~B_CALL
;
691 bp
->b_transaction
= transaction
;
692 bp
->b_iodone
= callback
;
698 buf_setupl(buf_t bp
, upl_t upl
, uint32_t offset
)
701 if ( !(bp
->b_lflags
& BL_IOBUF
) )
705 bp
->b_flags
|= B_CLUSTER
;
707 bp
->b_flags
&= ~B_CLUSTER
;
709 bp
->b_uploffset
= offset
;
715 buf_clone(buf_t bp
, int io_offset
, int io_size
, void (*iodone
)(buf_t
, void *), void *arg
)
719 if (io_offset
< 0 || io_size
< 0)
722 if ((unsigned)(io_offset
+ io_size
) > (unsigned)bp
->b_bcount
)
725 if (bp
->b_flags
& B_CLUSTER
) {
726 if (io_offset
&& ((bp
->b_uploffset
+ io_offset
) & PAGE_MASK
))
729 if (((bp
->b_uploffset
+ io_offset
+ io_size
) & PAGE_MASK
) && ((io_offset
+ io_size
) < bp
->b_bcount
))
732 io_bp
= alloc_io_buf(bp
->b_vp
, 0);
734 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
);
737 io_bp
->b_transaction
= arg
;
738 io_bp
->b_iodone
= iodone
;
739 io_bp
->b_flags
|= B_CALL
;
741 if (bp
->b_flags
& B_CLUSTER
) {
742 io_bp
->b_upl
= bp
->b_upl
;
743 io_bp
->b_uploffset
= bp
->b_uploffset
+ io_offset
;
745 io_bp
->b_datap
= (uintptr_t)(((char *)bp
->b_datap
) + io_offset
);
747 io_bp
->b_bcount
= io_size
;
756 if (bp
->b_lflags
& BL_SHADOW
)
763 buf_create_shadow_priv(buf_t bp
, boolean_t force_copy
, uintptr_t external_storage
, void (*iodone
)(buf_t
, void *), void *arg
)
765 return (buf_create_shadow_internal(bp
, force_copy
, external_storage
, iodone
, arg
, 1));
769 buf_create_shadow(buf_t bp
, boolean_t force_copy
, uintptr_t external_storage
, void (*iodone
)(buf_t
, void *), void *arg
)
771 return (buf_create_shadow_internal(bp
, force_copy
, external_storage
, iodone
, arg
, 0));
776 buf_create_shadow_internal(buf_t bp
, boolean_t force_copy
, uintptr_t external_storage
, void (*iodone
)(buf_t
, void *), void *arg
, int priv
)
780 KERNEL_DEBUG(0xbbbbc000 | DBG_FUNC_START
, bp
, 0, 0, 0, 0);
782 if ( !(bp
->b_flags
& B_META
) || (bp
->b_lflags
& BL_IOBUF
)) {
784 KERNEL_DEBUG(0xbbbbc000 | DBG_FUNC_END
, bp
, 0, 0, 0, 0);
787 #ifdef BUF_MAKE_PRIVATE
788 if (bp
->b_shadow_ref
&& bp
->b_data_ref
== 0 && external_storage
== 0)
789 panic("buf_create_shadow: %p is in the private state (%d, %d)", bp
, bp
->b_shadow_ref
, bp
->b_data_ref
);
791 io_bp
= alloc_io_buf(bp
->b_vp
, priv
);
793 io_bp
->b_flags
= bp
->b_flags
& (B_META
| B_ZALLOC
| B_ASYNC
| B_READ
| B_FUA
);
794 io_bp
->b_blkno
= bp
->b_blkno
;
795 io_bp
->b_lblkno
= bp
->b_lblkno
;
798 io_bp
->b_transaction
= arg
;
799 io_bp
->b_iodone
= iodone
;
800 io_bp
->b_flags
|= B_CALL
;
802 if (force_copy
== FALSE
) {
803 io_bp
->b_bcount
= bp
->b_bcount
;
804 io_bp
->b_bufsize
= bp
->b_bufsize
;
806 if (external_storage
) {
807 io_bp
->b_datap
= external_storage
;
808 #ifdef BUF_MAKE_PRIVATE
809 io_bp
->b_data_store
= NULL
;
812 io_bp
->b_datap
= bp
->b_datap
;
813 #ifdef BUF_MAKE_PRIVATE
814 io_bp
->b_data_store
= bp
;
817 *(buf_t
*)(&io_bp
->b_orig
) = bp
;
819 lck_mtx_lock_spin(buf_mtxp
);
821 io_bp
->b_lflags
|= BL_SHADOW
;
822 io_bp
->b_shadow
= bp
->b_shadow
;
823 bp
->b_shadow
= io_bp
;
826 #ifdef BUF_MAKE_PRIVATE
827 if (external_storage
)
828 io_bp
->b_lflags
|= BL_EXTERNAL
;
832 lck_mtx_unlock(buf_mtxp
);
834 if (external_storage
) {
835 #ifdef BUF_MAKE_PRIVATE
836 io_bp
->b_lflags
|= BL_EXTERNAL
;
838 io_bp
->b_bcount
= bp
->b_bcount
;
839 io_bp
->b_bufsize
= bp
->b_bufsize
;
840 io_bp
->b_datap
= external_storage
;
842 allocbuf(io_bp
, bp
->b_bcount
);
844 io_bp
->b_lflags
|= BL_IOBUF_ALLOC
;
846 bcopy((caddr_t
)bp
->b_datap
, (caddr_t
)io_bp
->b_datap
, bp
->b_bcount
);
848 #ifdef BUF_MAKE_PRIVATE
849 io_bp
->b_data_store
= NULL
;
852 KERNEL_DEBUG(0xbbbbc000 | DBG_FUNC_END
, bp
, bp
->b_shadow_ref
, 0, io_bp
, 0);
858 #ifdef BUF_MAKE_PRIVATE
860 buf_make_private(buf_t bp
)
866 KERNEL_DEBUG(0xbbbbc004 | DBG_FUNC_START
, bp
, bp
->b_shadow_ref
, 0, 0, 0);
868 if (bp
->b_shadow_ref
== 0 || bp
->b_data_ref
== 0 || ISSET(bp
->b_lflags
, BL_SHADOW
)) {
870 KERNEL_DEBUG(0xbbbbc004 | DBG_FUNC_END
, bp
, bp
->b_shadow_ref
, 0, EINVAL
, 0);
873 my_buf
.b_flags
= B_META
;
874 my_buf
.b_datap
= (uintptr_t)NULL
;
875 allocbuf(&my_buf
, bp
->b_bcount
);
877 bcopy((caddr_t
)bp
->b_datap
, (caddr_t
)my_buf
.b_datap
, bp
->b_bcount
);
879 lck_mtx_lock_spin(buf_mtxp
);
881 for (t_bp
= bp
->b_shadow
; t_bp
; t_bp
= t_bp
->b_shadow
) {
882 if ( !ISSET(bp
->b_lflags
, BL_EXTERNAL
))
887 if (ds_bp
== NULL
&& bp
->b_data_ref
)
888 panic("buf_make_private: b_data_ref != 0 && ds_bp == NULL");
890 if (ds_bp
&& (bp
->b_data_ref
== 0 || bp
->b_shadow_ref
== 0))
891 panic("buf_make_private: ref_count == 0 && ds_bp != NULL");
894 lck_mtx_unlock(buf_mtxp
);
896 buf_free_meta_store(&my_buf
);
898 KERNEL_DEBUG(0xbbbbc004 | DBG_FUNC_END
, bp
, bp
->b_shadow_ref
, 0, EINVAL
, 0);
901 for (t_bp
= bp
->b_shadow
; t_bp
; t_bp
= t_bp
->b_shadow
) {
902 if ( !ISSET(t_bp
->b_lflags
, BL_EXTERNAL
))
903 t_bp
->b_data_store
= ds_bp
;
905 ds_bp
->b_data_ref
= bp
->b_data_ref
;
908 bp
->b_datap
= my_buf
.b_datap
;
910 lck_mtx_unlock(buf_mtxp
);
912 KERNEL_DEBUG(0xbbbbc004 | DBG_FUNC_END
, bp
, bp
->b_shadow_ref
, 0, 0, 0);
919 buf_setfilter(buf_t bp
, void (*filter
)(buf_t
, void *), void *transaction
,
920 void (**old_iodone
)(buf_t
, void *), void **old_transaction
)
922 assert(ISSET(bp
->b_lflags
, BL_BUSY
));
925 *old_iodone
= bp
->b_iodone
;
927 *old_transaction
= bp
->b_transaction
;
929 bp
->b_transaction
= transaction
;
930 bp
->b_iodone
= filter
;
932 bp
->b_flags
|= B_FILTER
;
934 bp
->b_flags
&= ~B_FILTER
;
939 buf_blkno(buf_t bp
) {
941 return (bp
->b_blkno
);
945 buf_lblkno(buf_t bp
) {
947 return (bp
->b_lblkno
);
951 buf_setblkno(buf_t bp
, daddr64_t blkno
) {
957 buf_setlblkno(buf_t bp
, daddr64_t lblkno
) {
959 bp
->b_lblkno
= lblkno
;
963 buf_device(buf_t bp
) {
969 buf_setdevice(buf_t bp
, vnode_t vp
) {
971 if ((vp
->v_type
!= VBLK
) && (vp
->v_type
!= VCHR
))
973 bp
->b_dev
= vp
->v_rdev
;
980 buf_drvdata(buf_t bp
) {
982 return (bp
->b_drvdata
);
986 buf_setdrvdata(buf_t bp
, void *drvdata
) {
988 bp
->b_drvdata
= drvdata
;
992 buf_fsprivate(buf_t bp
) {
994 return (bp
->b_fsprivate
);
998 buf_setfsprivate(buf_t bp
, void *fsprivate
) {
1000 bp
->b_fsprivate
= fsprivate
;
1004 buf_rcred(buf_t bp
) {
1006 return (bp
->b_rcred
);
1010 buf_wcred(buf_t bp
) {
1012 return (bp
->b_wcred
);
1022 buf_uploffset(buf_t bp
) {
1024 return ((uint32_t)(bp
->b_uploffset
));
1028 buf_proc(buf_t bp
) {
1030 return (bp
->b_proc
);
1035 buf_map(buf_t bp
, caddr_t
*io_addr
)
1041 if ( !(bp
->b_flags
& B_CLUSTER
)) {
1042 *io_addr
= (caddr_t
)bp
->b_datap
;
1045 real_bp
= (buf_t
)(bp
->b_real_bp
);
1047 if (real_bp
&& real_bp
->b_datap
) {
1049 * b_real_bp is only valid if B_CLUSTER is SET
1050 * if it's non-zero, than someone did a cluster_bp call
1051 * if the backing physical pages were already mapped
1052 * in before the call to cluster_bp (non-zero b_datap),
1053 * than we just use that mapping
1055 *io_addr
= (caddr_t
)real_bp
->b_datap
;
1058 kret
= ubc_upl_map(bp
->b_upl
, &vaddr
); /* Map it in */
1060 if (kret
!= KERN_SUCCESS
) {
1065 vaddr
+= bp
->b_uploffset
;
1067 *io_addr
= (caddr_t
)vaddr
;
1078 if ( !(bp
->b_flags
& B_CLUSTER
))
1081 * see buf_map for the explanation
1083 real_bp
= (buf_t
)(bp
->b_real_bp
);
1085 if (real_bp
&& real_bp
->b_datap
)
1088 if ((bp
->b_lflags
& BL_IOBUF
) &&
1089 ((bp
->b_flags
& (B_PAGEIO
| B_READ
)) != (B_PAGEIO
| B_READ
))) {
1091 * ignore pageins... the 'right' thing will
1092 * happen due to the way we handle speculative
1095 * when we commit these pages, we'll hit
1096 * it with UPL_COMMIT_INACTIVE which
1097 * will clear the reference bit that got
1098 * turned on when we touched the mapping
1100 bp
->b_flags
|= B_AGE
;
1102 kret
= ubc_upl_unmap(bp
->b_upl
);
1104 if (kret
!= KERN_SUCCESS
)
1111 buf_clear(buf_t bp
) {
1114 if (buf_map(bp
, &baddr
) == 0) {
1115 bzero(baddr
, bp
->b_bcount
);
1122 * Read or write a buffer that is not contiguous on disk.
1123 * buffer is marked done/error at the conclusion
1126 buf_strategy_fragmented(vnode_t devvp
, buf_t bp
, off_t f_offset
, size_t contig_bytes
)
1128 vnode_t vp
= buf_vnode(bp
);
1129 buf_t io_bp
; /* For reading or writing a single block */
1132 size_t io_contig_bytes
;
1138 * save our starting point... the bp was already mapped
1139 * in buf_strategy before we got called
1140 * no sense doing it again.
1142 io_blkno
= bp
->b_blkno
;
1144 * Make sure we redo this mapping for the next I/O
1145 * i.e. this can never be a 'permanent' mapping
1147 bp
->b_blkno
= bp
->b_lblkno
;
1150 * Get an io buffer to do the deblocking
1152 io_bp
= alloc_io_buf(devvp
, 0);
1154 io_bp
->b_lblkno
= bp
->b_lblkno
;
1155 io_bp
->b_datap
= bp
->b_datap
;
1156 io_resid
= bp
->b_bcount
;
1157 io_direction
= bp
->b_flags
& B_READ
;
1158 io_contig_bytes
= contig_bytes
;
1160 if (bp
->b_flags
& B_READ
)
1161 bmap_flags
= VNODE_READ
;
1163 bmap_flags
= VNODE_WRITE
;
1168 * this is unexepected, but we'll allow for it
1170 bzero((caddr_t
)io_bp
->b_datap
, (int)io_contig_bytes
);
1172 io_bp
->b_bcount
= io_contig_bytes
;
1173 io_bp
->b_bufsize
= io_contig_bytes
;
1174 io_bp
->b_resid
= io_contig_bytes
;
1175 io_bp
->b_blkno
= io_blkno
;
1177 buf_reset(io_bp
, io_direction
);
1180 * Call the device to do the I/O and wait for it. Make sure the appropriate party is charged for write
1183 if (!ISSET(bp
->b_flags
, B_READ
))
1184 OSAddAtomic(1, &devvp
->v_numoutput
);
1186 if ((error
= VNOP_STRATEGY(io_bp
)))
1188 if ((error
= (int)buf_biowait(io_bp
)))
1190 if (io_bp
->b_resid
) {
1191 io_resid
-= (io_contig_bytes
- io_bp
->b_resid
);
1195 if ((io_resid
-= io_contig_bytes
) == 0)
1197 f_offset
+= io_contig_bytes
;
1198 io_bp
->b_datap
+= io_contig_bytes
;
1201 * Map the current position to a physical block number
1203 if ((error
= VNOP_BLOCKMAP(vp
, f_offset
, io_resid
, &io_blkno
, &io_contig_bytes
, NULL
, bmap_flags
, NULL
)))
1209 buf_seterror(bp
, error
);
1210 bp
->b_resid
= io_resid
;
1212 * This I/O is now complete
1221 * struct vnop_strategy_args {
1226 buf_strategy(vnode_t devvp
, void *ap
)
1228 buf_t bp
= ((struct vnop_strategy_args
*)ap
)->a_bp
;
1229 vnode_t vp
= bp
->b_vp
;
1233 int dtrace_io_start_flag
= 0; /* We only want to trip the io:::start
1234 * probe once, with the true physical
1235 * block in place (b_blkno)
1240 if (vp
== NULL
|| vp
->v_type
== VCHR
|| vp
->v_type
== VBLK
)
1241 panic("buf_strategy: b_vp == NULL || vtype == VCHR | VBLK\n");
1243 * associate the physical device with
1244 * with this buf_t even if we don't
1245 * end up issuing the I/O...
1247 bp
->b_dev
= devvp
->v_rdev
;
1249 if (bp
->b_flags
& B_READ
)
1250 bmap_flags
= VNODE_READ
;
1252 bmap_flags
= VNODE_WRITE
;
1254 if ( !(bp
->b_flags
& B_CLUSTER
)) {
1256 if ( (bp
->b_upl
) ) {
1258 * we have a UPL associated with this bp
1259 * go through cluster_bp which knows how
1260 * to deal with filesystem block sizes
1261 * that aren't equal to the page size
1263 DTRACE_IO1(start
, buf_t
, bp
);
1264 return (cluster_bp(bp
));
1266 if (bp
->b_blkno
== bp
->b_lblkno
) {
1268 size_t contig_bytes
;
1270 if ((error
= VNOP_BLKTOOFF(vp
, bp
->b_lblkno
, &f_offset
))) {
1271 DTRACE_IO1(start
, buf_t
, bp
);
1272 buf_seterror(bp
, error
);
1278 if ((error
= VNOP_BLOCKMAP(vp
, f_offset
, bp
->b_bcount
, &bp
->b_blkno
, &contig_bytes
, NULL
, bmap_flags
, NULL
))) {
1279 DTRACE_IO1(start
, buf_t
, bp
);
1280 buf_seterror(bp
, error
);
1286 DTRACE_IO1(start
, buf_t
, bp
);
1288 dtrace_io_start_flag
= 1;
1289 #endif /* CONFIG_DTRACE */
1291 if ((bp
->b_blkno
== -1) || (contig_bytes
== 0)) {
1292 /* Set block number to force biodone later */
1296 else if ((long)contig_bytes
< bp
->b_bcount
) {
1297 return (buf_strategy_fragmented(devvp
, bp
, f_offset
, contig_bytes
));
1302 if (dtrace_io_start_flag
== 0) {
1303 DTRACE_IO1(start
, buf_t
, bp
);
1304 dtrace_io_start_flag
= 1;
1306 #endif /* CONFIG_DTRACE */
1308 if (bp
->b_blkno
== -1) {
1315 if (dtrace_io_start_flag
== 0)
1316 DTRACE_IO1(start
, buf_t
, bp
);
1317 #endif /* CONFIG_DTRACE */
1320 /* Capture f_offset in the bufattr*/
1321 cpx_t cpx
= bufattr_cpx(buf_attr(bp
));
1323 /* No need to go here for older EAs */
1324 if(cpx_use_offset_for_iv(cpx
) && !cpx_synthetic_offset_for_iv(cpx
)) {
1326 if ((error
= VNOP_BLKTOOFF(bp
->b_vp
, bp
->b_lblkno
, &f_offset
)))
1330 * Attach the file offset to this buffer. The
1331 * bufattr attributes will be passed down the stack
1332 * until they reach IOFlashStorage. IOFlashStorage
1333 * will retain the offset in a local variable when it
1334 * issues its I/Os to the NAND controller.
1336 * Note that LwVM may end up splitting this I/O
1337 * into sub-I/Os if it crosses a chunk boundary. In this
1338 * case, LwVM will update this field when it dispatches
1339 * each I/O to IOFlashStorage. But from our perspective
1340 * we have only issued a single I/O.
1342 buf_setcpoff(bp
, f_offset
);
1343 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);
1349 * we can issue the I/O because...
1350 * either B_CLUSTER is set which
1351 * means that the I/O is properly set
1352 * up to be a multiple of the page size, or
1353 * we were able to successfully set up the
1354 * physical block mapping
1356 error
= VOCALL(devvp
->v_op
, VOFFSET(vnop_strategy
), ap
);
1357 DTRACE_FSINFO(strategy
, vnode_t
, vp
);
1364 buf_alloc(vnode_t vp
)
1366 return(alloc_io_buf(vp
, is_vm_privileged()));
1370 buf_free(buf_t bp
) {
1377 * iterate buffers for the specified vp.
1378 * if BUF_SCAN_DIRTY is set, do the dirty list
1379 * if BUF_SCAN_CLEAN is set, do the clean list
1380 * if neither flag is set, default to BUF_SCAN_DIRTY
1381 * if BUF_NOTIFY_BUSY is set, call the callout function using a NULL bp for busy pages
1384 struct buf_iterate_info_t
{
1386 struct buflists
*listhead
;
1390 buf_iterate(vnode_t vp
, int (*callout
)(buf_t
, void *), int flags
, void *arg
)
1394 struct buflists local_iterblkhd
;
1395 int lock_flags
= BAC_NOWAIT
| BAC_REMOVE
;
1396 int notify_busy
= flags
& BUF_NOTIFY_BUSY
;
1397 struct buf_iterate_info_t list
[2];
1400 if (flags
& BUF_SKIP_LOCKED
)
1401 lock_flags
|= BAC_SKIP_LOCKED
;
1402 if (flags
& BUF_SKIP_NONLOCKED
)
1403 lock_flags
|= BAC_SKIP_NONLOCKED
;
1405 if ( !(flags
& (BUF_SCAN_DIRTY
| BUF_SCAN_CLEAN
)))
1406 flags
|= BUF_SCAN_DIRTY
;
1410 if (flags
& BUF_SCAN_DIRTY
) {
1411 list
[num_lists
].flag
= VBI_DIRTY
;
1412 list
[num_lists
].listhead
= &vp
->v_dirtyblkhd
;
1415 if (flags
& BUF_SCAN_CLEAN
) {
1416 list
[num_lists
].flag
= VBI_CLEAN
;
1417 list
[num_lists
].listhead
= &vp
->v_cleanblkhd
;
1421 for (i
= 0; i
< num_lists
; i
++) {
1422 lck_mtx_lock(buf_mtxp
);
1424 if (buf_iterprepare(vp
, &local_iterblkhd
, list
[i
].flag
)) {
1425 lck_mtx_unlock(buf_mtxp
);
1428 while (!LIST_EMPTY(&local_iterblkhd
)) {
1429 bp
= LIST_FIRST(&local_iterblkhd
);
1430 LIST_REMOVE(bp
, b_vnbufs
);
1431 LIST_INSERT_HEAD(list
[i
].listhead
, bp
, b_vnbufs
);
1433 if (buf_acquire_locked(bp
, lock_flags
, 0, 0)) {
1441 lck_mtx_unlock(buf_mtxp
);
1443 retval
= callout(bp
, arg
);
1452 case BUF_RETURNED_DONE
:
1455 lck_mtx_lock(buf_mtxp
);
1457 case BUF_CLAIMED_DONE
:
1458 lck_mtx_lock(buf_mtxp
);
1461 lck_mtx_lock(buf_mtxp
);
1462 } /* while list has more nodes */
1464 buf_itercomplete(vp
, &local_iterblkhd
, list
[i
].flag
);
1465 lck_mtx_unlock(buf_mtxp
);
1466 } /* for each list */
1471 * Flush out and invalidate all buffers associated with a vnode.
1474 buf_invalidateblks(vnode_t vp
, int flags
, int slpflag
, int slptimeo
)
1479 int must_rescan
= 1;
1480 struct buflists local_iterblkhd
;
1483 if (LIST_EMPTY(&vp
->v_cleanblkhd
) && LIST_EMPTY(&vp
->v_dirtyblkhd
))
1486 lck_mtx_lock(buf_mtxp
);
1489 if (must_rescan
== 0)
1491 * the lists may not be empty, but all that's left at this
1492 * point are metadata or B_LOCKED buffers which are being
1493 * skipped... we know this because we made it through both
1494 * the clean and dirty lists without dropping buf_mtxp...
1495 * each time we drop buf_mtxp we bump "must_rescan"
1498 if (LIST_EMPTY(&vp
->v_cleanblkhd
) && LIST_EMPTY(&vp
->v_dirtyblkhd
))
1502 * iterate the clean list
1504 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_CLEAN
)) {
1505 goto try_dirty_list
;
1507 while (!LIST_EMPTY(&local_iterblkhd
)) {
1509 bp
= LIST_FIRST(&local_iterblkhd
);
1511 LIST_REMOVE(bp
, b_vnbufs
);
1512 LIST_INSERT_HEAD(&vp
->v_cleanblkhd
, bp
, b_vnbufs
);
1515 * some filesystems distinguish meta data blocks with a negative logical block #
1517 if ((flags
& BUF_SKIP_META
) && (bp
->b_lblkno
< 0 || ISSET(bp
->b_flags
, B_META
)))
1520 aflags
= BAC_REMOVE
;
1522 if ( !(flags
& BUF_INVALIDATE_LOCKED
) )
1523 aflags
|= BAC_SKIP_LOCKED
;
1525 if ( (error
= (int)buf_acquire_locked(bp
, aflags
, slpflag
, slptimeo
)) ) {
1526 if (error
== EDEADLK
)
1528 * this buffer was marked B_LOCKED...
1529 * we didn't drop buf_mtxp, so we
1530 * we don't need to rescan
1533 if (error
== EAGAIN
) {
1535 * found a busy buffer... we blocked and
1536 * dropped buf_mtxp, so we're going to
1537 * need to rescan after this pass is completed
1543 * got some kind of 'real' error out of the msleep
1544 * in buf_acquire_locked, terminate the scan and return the error
1546 buf_itercomplete(vp
, &local_iterblkhd
, VBI_CLEAN
);
1548 lck_mtx_unlock(buf_mtxp
);
1551 lck_mtx_unlock(buf_mtxp
);
1553 if (bp
->b_flags
& B_LOCKED
)
1554 KERNEL_DEBUG(0xbbbbc038, bp
, 0, 0, 0, 0);
1556 CLR(bp
->b_flags
, B_LOCKED
);
1557 SET(bp
->b_flags
, B_INVAL
);
1560 lck_mtx_lock(buf_mtxp
);
1563 * by dropping buf_mtxp, we allow new
1564 * buffers to be added to the vnode list(s)
1565 * we'll have to rescan at least once more
1566 * if the queues aren't empty
1570 buf_itercomplete(vp
, &local_iterblkhd
, VBI_CLEAN
);
1574 * Now iterate on dirty blks
1576 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_DIRTY
)) {
1579 while (!LIST_EMPTY(&local_iterblkhd
)) {
1580 bp
= LIST_FIRST(&local_iterblkhd
);
1582 LIST_REMOVE(bp
, b_vnbufs
);
1583 LIST_INSERT_HEAD(&vp
->v_dirtyblkhd
, bp
, b_vnbufs
);
1586 * some filesystems distinguish meta data blocks with a negative logical block #
1588 if ((flags
& BUF_SKIP_META
) && (bp
->b_lblkno
< 0 || ISSET(bp
->b_flags
, B_META
)))
1591 aflags
= BAC_REMOVE
;
1593 if ( !(flags
& BUF_INVALIDATE_LOCKED
) )
1594 aflags
|= BAC_SKIP_LOCKED
;
1596 if ( (error
= (int)buf_acquire_locked(bp
, aflags
, slpflag
, slptimeo
)) ) {
1597 if (error
== EDEADLK
)
1599 * this buffer was marked B_LOCKED...
1600 * we didn't drop buf_mtxp, so we
1601 * we don't need to rescan
1604 if (error
== EAGAIN
) {
1606 * found a busy buffer... we blocked and
1607 * dropped buf_mtxp, so we're going to
1608 * need to rescan after this pass is completed
1614 * got some kind of 'real' error out of the msleep
1615 * in buf_acquire_locked, terminate the scan and return the error
1617 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1619 lck_mtx_unlock(buf_mtxp
);
1622 lck_mtx_unlock(buf_mtxp
);
1624 if (bp
->b_flags
& B_LOCKED
)
1625 KERNEL_DEBUG(0xbbbbc038, bp
, 0, 0, 1, 0);
1627 CLR(bp
->b_flags
, B_LOCKED
);
1628 SET(bp
->b_flags
, B_INVAL
);
1630 if (ISSET(bp
->b_flags
, B_DELWRI
) && (flags
& BUF_WRITE_DATA
))
1631 (void) VNOP_BWRITE(bp
);
1635 lck_mtx_lock(buf_mtxp
);
1637 * by dropping buf_mtxp, we allow new
1638 * buffers to be added to the vnode list(s)
1639 * we'll have to rescan at least once more
1640 * if the queues aren't empty
1644 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1646 lck_mtx_unlock(buf_mtxp
);
1652 buf_flushdirtyblks(vnode_t vp
, int wait
, int flags
, const char *msg
) {
1654 (void) buf_flushdirtyblks_skipinfo(vp
, wait
, flags
, msg
);
1659 buf_flushdirtyblks_skipinfo(vnode_t vp
, int wait
, int flags
, const char *msg
) {
1661 int writes_issued
= 0;
1664 struct buflists local_iterblkhd
;
1665 int lock_flags
= BAC_NOWAIT
| BAC_REMOVE
;
1668 if (flags
& BUF_SKIP_LOCKED
)
1669 lock_flags
|= BAC_SKIP_LOCKED
;
1670 if (flags
& BUF_SKIP_NONLOCKED
)
1671 lock_flags
|= BAC_SKIP_NONLOCKED
;
1673 lck_mtx_lock(buf_mtxp
);
1675 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_DIRTY
) == 0) {
1676 while (!LIST_EMPTY(&local_iterblkhd
)) {
1677 bp
= LIST_FIRST(&local_iterblkhd
);
1678 LIST_REMOVE(bp
, b_vnbufs
);
1679 LIST_INSERT_HEAD(&vp
->v_dirtyblkhd
, bp
, b_vnbufs
);
1681 if ((error
= buf_acquire_locked(bp
, lock_flags
, 0, 0)) == EBUSY
) {
1686 * If we passed in BUF_SKIP_LOCKED or BUF_SKIP_NONLOCKED,
1687 * we may want to do somethign differently if a locked or unlocked
1688 * buffer was encountered (depending on the arg specified).
1689 * In this case, we know that one of those two was set, and the
1690 * buf acquisition failed above.
1692 * If it failed with EDEADLK, then save state which can be emitted
1693 * later on to the caller. Most callers should not care.
1695 if (error
== EDEADLK
) {
1700 lck_mtx_unlock(buf_mtxp
);
1702 bp
->b_flags
&= ~B_LOCKED
;
1705 * Wait for I/O associated with indirect blocks to complete,
1706 * since there is no way to quickly wait for them below.
1708 if ((bp
->b_vp
== vp
) || (wait
== 0))
1709 (void) buf_bawrite(bp
);
1711 (void) VNOP_BWRITE(bp
);
1714 lck_mtx_lock(buf_mtxp
);
1716 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1718 lck_mtx_unlock(buf_mtxp
);
1721 (void)vnode_waitforwrites(vp
, 0, 0, 0, msg
);
1723 if (vp
->v_dirtyblkhd
.lh_first
&& busy
) {
1725 * we had one or more BUSY buffers on
1726 * the dirtyblock list... most likely
1727 * these are due to delayed writes that
1728 * were moved to the bclean queue but
1729 * have not yet been 'written'.
1730 * if we issued some writes on the
1731 * previous pass, we try again immediately
1732 * if we didn't, we'll sleep for some time
1733 * to allow the state to change...
1735 if (writes_issued
== 0) {
1736 (void)tsleep((caddr_t
)&vp
->v_numoutput
,
1737 PRIBIO
+ 1, "vnode_flushdirtyblks", hz
/20);
1751 * called with buf_mtxp held...
1752 * this lock protects the queue manipulation
1755 buf_iterprepare(vnode_t vp
, struct buflists
*iterheadp
, int flags
)
1757 struct buflists
* listheadp
;
1759 if (flags
& VBI_DIRTY
)
1760 listheadp
= &vp
->v_dirtyblkhd
;
1762 listheadp
= &vp
->v_cleanblkhd
;
1764 while (vp
->v_iterblkflags
& VBI_ITER
) {
1765 vp
->v_iterblkflags
|= VBI_ITERWANT
;
1766 msleep(&vp
->v_iterblkflags
, buf_mtxp
, 0, "buf_iterprepare", NULL
);
1768 if (LIST_EMPTY(listheadp
)) {
1769 LIST_INIT(iterheadp
);
1772 vp
->v_iterblkflags
|= VBI_ITER
;
1774 iterheadp
->lh_first
= listheadp
->lh_first
;
1775 listheadp
->lh_first
->b_vnbufs
.le_prev
= &iterheadp
->lh_first
;
1776 LIST_INIT(listheadp
);
1782 * called with buf_mtxp held...
1783 * this lock protects the queue manipulation
1786 buf_itercomplete(vnode_t vp
, struct buflists
*iterheadp
, int flags
)
1788 struct buflists
* listheadp
;
1791 if (flags
& VBI_DIRTY
)
1792 listheadp
= &vp
->v_dirtyblkhd
;
1794 listheadp
= &vp
->v_cleanblkhd
;
1796 while (!LIST_EMPTY(iterheadp
)) {
1797 bp
= LIST_FIRST(iterheadp
);
1798 LIST_REMOVE(bp
, b_vnbufs
);
1799 LIST_INSERT_HEAD(listheadp
, bp
, b_vnbufs
);
1801 vp
->v_iterblkflags
&= ~VBI_ITER
;
1803 if (vp
->v_iterblkflags
& VBI_ITERWANT
) {
1804 vp
->v_iterblkflags
&= ~VBI_ITERWANT
;
1805 wakeup(&vp
->v_iterblkflags
);
1811 bremfree_locked(buf_t bp
)
1813 struct bqueues
*dp
= NULL
;
1816 whichq
= bp
->b_whichq
;
1819 if (bp
->b_shadow_ref
== 0)
1820 panic("bremfree_locked: %p not on freelist", bp
);
1822 * there are clones pointing to 'bp'...
1823 * therefore, it was not put on a freelist
1824 * when buf_brelse was last called on 'bp'
1829 * We only calculate the head of the freelist when removing
1830 * the last element of the list as that is the only time that
1831 * it is needed (e.g. to reset the tail pointer).
1833 * NB: This makes an assumption about how tailq's are implemented.
1835 if (bp
->b_freelist
.tqe_next
== NULL
) {
1836 dp
= &bufqueues
[whichq
];
1838 if (dp
->tqh_last
!= &bp
->b_freelist
.tqe_next
)
1839 panic("bremfree: lost tail");
1841 TAILQ_REMOVE(dp
, bp
, b_freelist
);
1843 if (whichq
== BQ_LAUNDRY
)
1847 bp
->b_timestamp
= 0;
1852 * Associate a buffer with a vnode.
1853 * buf_mtxp must be locked on entry
1856 bgetvp_locked(vnode_t vp
, buf_t bp
)
1860 panic("bgetvp_locked: not free");
1862 if (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
)
1863 bp
->b_dev
= vp
->v_rdev
;
1867 * Insert onto list for new vnode.
1869 bufinsvn(bp
, &vp
->v_cleanblkhd
);
1873 * Disassociate a buffer from a vnode.
1874 * buf_mtxp must be locked on entry
1877 brelvp_locked(buf_t bp
)
1880 * Delete from old vnode list, if on one.
1882 if (bp
->b_vnbufs
.le_next
!= NOLIST
)
1885 bp
->b_vp
= (vnode_t
)NULL
;
1889 * Reassign a buffer from one vnode to another.
1890 * Used to assign file specific control information
1891 * (indirect blocks) to the vnode to which they belong.
1894 buf_reassign(buf_t bp
, vnode_t newvp
)
1896 struct buflists
*listheadp
;
1898 if (newvp
== NULL
) {
1899 printf("buf_reassign: NULL");
1902 lck_mtx_lock_spin(buf_mtxp
);
1905 * Delete from old vnode list, if on one.
1907 if (bp
->b_vnbufs
.le_next
!= NOLIST
)
1910 * If dirty, put on list of dirty buffers;
1911 * otherwise insert onto list of clean buffers.
1913 if (ISSET(bp
->b_flags
, B_DELWRI
))
1914 listheadp
= &newvp
->v_dirtyblkhd
;
1916 listheadp
= &newvp
->v_cleanblkhd
;
1917 bufinsvn(bp
, listheadp
);
1919 lck_mtx_unlock(buf_mtxp
);
1922 static __inline__
void
1923 bufhdrinit(buf_t bp
)
1925 bzero((char *)bp
, sizeof *bp
);
1927 bp
->b_rcred
= NOCRED
;
1928 bp
->b_wcred
= NOCRED
;
1929 bp
->b_vnbufs
.le_next
= NOLIST
;
1930 bp
->b_flags
= B_INVAL
;
1936 * Initialize buffers and hash links for buffers.
1938 __private_extern__
void
1946 /* Initialize the buffer queues ('freelists') and the hash table */
1947 for (dp
= bufqueues
; dp
< &bufqueues
[BQUEUES
]; dp
++)
1949 bufhashtbl
= hashinit(nbuf_hashelements
, M_CACHE
, &bufhash
);
1953 /* Initialize the buffer headers */
1954 for (i
= 0; i
< max_nbuf_headers
; i
++) {
1956 bp
= &buf_headers
[i
];
1960 dp
= &bufqueues
[BQ_EMPTY
];
1961 bp
->b_whichq
= BQ_EMPTY
;
1962 bp
->b_timestamp
= buf_timestamp();
1963 binsheadfree(bp
, dp
, BQ_EMPTY
);
1964 binshash(bp
, &invalhash
);
1966 boot_nbuf_headers
= nbuf_headers
;
1968 TAILQ_INIT(&iobufqueue
);
1969 TAILQ_INIT(&delaybufqueue
);
1971 for (; i
< nbuf_headers
+ niobuf_headers
; i
++) {
1972 bp
= &buf_headers
[i
];
1975 binsheadfree(bp
, &iobufqueue
, -1);
1979 * allocate lock group attribute and group
1981 buf_mtx_grp_attr
= lck_grp_attr_alloc_init();
1982 buf_mtx_grp
= lck_grp_alloc_init("buffer cache", buf_mtx_grp_attr
);
1985 * allocate the lock attribute
1987 buf_mtx_attr
= lck_attr_alloc_init();
1990 * allocate and initialize mutex's for the buffer and iobuffer pools
1992 buf_mtxp
= lck_mtx_alloc_init(buf_mtx_grp
, buf_mtx_attr
);
1993 iobuffer_mtxp
= lck_mtx_alloc_init(buf_mtx_grp
, buf_mtx_attr
);
1995 if (iobuffer_mtxp
== NULL
)
1996 panic("couldn't create iobuffer mutex");
1998 if (buf_mtxp
== NULL
)
1999 panic("couldn't create buf mutex");
2002 * allocate and initialize cluster specific global locks...
2006 printf("using %d buffer headers and %d cluster IO buffer headers\n",
2007 nbuf_headers
, niobuf_headers
);
2009 /* Set up zones used by the buffer cache */
2012 /* start the bcleanbuf() thread */
2013 bcleanbuf_thread_init();
2015 /* Register a callout for relieving vm pressure */
2016 if (vm_set_buffer_cleanup_callout(buffer_cache_gc
) != KERN_SUCCESS
) {
2017 panic("Couldn't register buffer cache callout for vm pressure!\n");
2023 * Zones for the meta data buffers
2027 #define MAXMETA 8192
2029 struct meta_zone_entry
{
2033 const char *mz_name
;
2036 struct meta_zone_entry meta_zones
[] = {
2037 {NULL
, (MINMETA
* 1), 128 * (MINMETA
* 1), "buf.512" },
2038 {NULL
, (MINMETA
* 2), 64 * (MINMETA
* 2), "buf.1024" },
2039 {NULL
, (MINMETA
* 4), 16 * (MINMETA
* 4), "buf.2048" },
2040 {NULL
, (MINMETA
* 8), 512 * (MINMETA
* 8), "buf.4096" },
2041 {NULL
, (MINMETA
* 16), 512 * (MINMETA
* 16), "buf.8192" },
2042 {NULL
, 0, 0, "" } /* End */
2046 * Initialize the meta data zones
2053 for (i
= 0; meta_zones
[i
].mz_size
!= 0; i
++) {
2054 meta_zones
[i
].mz_zone
=
2055 zinit(meta_zones
[i
].mz_size
,
2056 meta_zones
[i
].mz_max
,
2058 meta_zones
[i
].mz_name
);
2059 zone_change(meta_zones
[i
].mz_zone
, Z_CALLERACCT
, FALSE
);
2061 buf_hdr_zone
= zinit(sizeof(struct buf
), 32, PAGE_SIZE
, "buf headers");
2062 zone_change(buf_hdr_zone
, Z_CALLERACCT
, FALSE
);
2065 static __inline__ zone_t
2066 getbufzone(size_t size
)
2070 if ((size
% 512) || (size
< MINMETA
) || (size
> MAXMETA
))
2071 panic("getbufzone: incorect size = %lu", size
);
2073 for (i
= 0; meta_zones
[i
].mz_size
!= 0; i
++) {
2074 if (meta_zones
[i
].mz_size
>= size
)
2078 return (meta_zones
[i
].mz_zone
);
2084 bio_doread(vnode_t vp
, daddr64_t blkno
, int size
, kauth_cred_t cred
, int async
, int queuetype
)
2088 bp
= buf_getblk(vp
, blkno
, size
, 0, 0, queuetype
);
2091 * If buffer does not have data valid, start a read.
2092 * Note that if buffer is B_INVAL, buf_getblk() won't return it.
2093 * Therefore, it's valid if it's I/O has completed or been delayed.
2095 if (!ISSET(bp
->b_flags
, (B_DONE
| B_DELWRI
))) {
2100 /* Start I/O for the buffer (keeping credentials). */
2101 SET(bp
->b_flags
, B_READ
| async
);
2102 if (IS_VALID_CRED(cred
) && !IS_VALID_CRED(bp
->b_rcred
)) {
2103 kauth_cred_ref(cred
);
2109 trace(TR_BREADMISS
, pack(vp
, size
), blkno
);
2111 /* Pay for the read. */
2112 if (p
&& p
->p_stats
) {
2113 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_inblock
); /* XXX */
2118 * since we asked for an ASYNC I/O
2119 * the biodone will do the brelse
2120 * we don't want to pass back a bp
2121 * that we don't 'own'
2130 trace(TR_BREADHIT
, pack(vp
, size
), blkno
);
2136 * Perform the reads for buf_breadn() and buf_meta_breadn().
2137 * Trivial modification to the breada algorithm presented in Bach (p.55).
2140 do_breadn_for_type(vnode_t vp
, daddr64_t blkno
, int size
, daddr64_t
*rablks
, int *rasizes
,
2141 int nrablks
, kauth_cred_t cred
, buf_t
*bpp
, int queuetype
)
2146 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, queuetype
);
2149 * For each of the read-ahead blocks, start a read, if necessary.
2151 for (i
= 0; i
< nrablks
; i
++) {
2152 /* If it's in the cache, just go on to next one. */
2153 if (incore(vp
, rablks
[i
]))
2156 /* Get a buffer for the read-ahead block */
2157 (void) bio_doread(vp
, rablks
[i
], rasizes
[i
], cred
, B_ASYNC
, queuetype
);
2160 /* Otherwise, we had to start a read for it; wait until it's valid. */
2161 return (buf_biowait(bp
));
2166 * Read a disk block.
2167 * This algorithm described in Bach (p.54).
2170 buf_bread(vnode_t vp
, daddr64_t blkno
, int size
, kauth_cred_t cred
, buf_t
*bpp
)
2174 /* Get buffer for block. */
2175 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, BLK_READ
);
2177 /* Wait for the read to complete, and return result. */
2178 return (buf_biowait(bp
));
2182 * Read a disk block. [bread() for meta-data]
2183 * This algorithm described in Bach (p.54).
2186 buf_meta_bread(vnode_t vp
, daddr64_t blkno
, int size
, kauth_cred_t cred
, buf_t
*bpp
)
2190 /* Get buffer for block. */
2191 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, BLK_META
);
2193 /* Wait for the read to complete, and return result. */
2194 return (buf_biowait(bp
));
2198 * Read-ahead multiple disk blocks. The first is sync, the rest async.
2201 buf_breadn(vnode_t vp
, daddr64_t blkno
, int size
, daddr64_t
*rablks
, int *rasizes
, int nrablks
, kauth_cred_t cred
, buf_t
*bpp
)
2203 return (do_breadn_for_type(vp
, blkno
, size
, rablks
, rasizes
, nrablks
, cred
, bpp
, BLK_READ
));
2207 * Read-ahead multiple disk blocks. The first is sync, the rest async.
2208 * [buf_breadn() for meta-data]
2211 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
)
2213 return (do_breadn_for_type(vp
, blkno
, size
, rablks
, rasizes
, nrablks
, cred
, bpp
, BLK_META
));
2217 * Block write. Described in Bach (p.56)
2220 buf_bwrite(buf_t bp
)
2222 int sync
, wasdelayed
;
2224 proc_t p
= current_proc();
2225 vnode_t vp
= bp
->b_vp
;
2227 if (bp
->b_datap
== 0) {
2228 if (brecover_data(bp
) == 0)
2231 /* Remember buffer type, to switch on it later. */
2232 sync
= !ISSET(bp
->b_flags
, B_ASYNC
);
2233 wasdelayed
= ISSET(bp
->b_flags
, B_DELWRI
);
2234 CLR(bp
->b_flags
, (B_READ
| B_DONE
| B_ERROR
| B_DELWRI
));
2237 OSAddAtomicLong(-1, &nbdwrite
);
2241 * If not synchronous, pay for the I/O operation and make
2242 * sure the buf is on the correct vnode queue. We have
2243 * to do this now, because if we don't, the vnode may not
2244 * be properly notified that its I/O has completed.
2247 buf_reassign(bp
, vp
);
2249 if (p
&& p
->p_stats
) {
2250 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_oublock
); /* XXX */
2253 trace(TR_BUFWRITE
, pack(vp
, bp
->b_bcount
), bp
->b_lblkno
);
2255 /* Initiate disk write. Make sure the appropriate party is charged. */
2257 OSAddAtomic(1, &vp
->v_numoutput
);
2263 * If I/O was synchronous, wait for it to complete.
2265 rv
= buf_biowait(bp
);
2268 * Pay for the I/O operation, if it's not been paid for, and
2269 * make sure it's on the correct vnode queue. (async operatings
2270 * were payed for above.)
2273 buf_reassign(bp
, vp
);
2275 if (p
&& p
->p_stats
) {
2276 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_oublock
); /* XXX */
2279 /* Release the buffer. */
2289 vn_bwrite(struct vnop_bwrite_args
*ap
)
2291 return (buf_bwrite(ap
->a_bp
));
2297 * The buffer is marked dirty, but is not queued for I/O.
2298 * This routine should be used when the buffer is expected
2299 * to be modified again soon, typically a small write that
2300 * partially fills a buffer.
2302 * NB: magnetic tapes cannot be delayed; they must be
2303 * written in the order that the writes are requested.
2305 * Described in Leffler, et al. (pp. 208-213).
2307 * Note: With the ability to allocate additional buffer
2308 * headers, we can get in to the situation where "too" many
2309 * buf_bdwrite()s can create situation where the kernel can create
2310 * buffers faster than the disks can service. Doing a buf_bawrite() in
2311 * cases where we have "too many" outstanding buf_bdwrite()s avoids that.
2314 bdwrite_internal(buf_t bp
, int return_error
)
2316 proc_t p
= current_proc();
2317 vnode_t vp
= bp
->b_vp
;
2320 * If the block hasn't been seen before:
2321 * (1) Mark it as having been seen,
2322 * (2) Charge for the write.
2323 * (3) Make sure it's on its vnode's correct block list,
2325 if (!ISSET(bp
->b_flags
, B_DELWRI
)) {
2326 SET(bp
->b_flags
, B_DELWRI
);
2327 if (p
&& p
->p_stats
) {
2328 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_oublock
); /* XXX */
2330 OSAddAtomicLong(1, &nbdwrite
);
2331 buf_reassign(bp
, vp
);
2335 * if we're not LOCKED, but the total number of delayed writes
2336 * has climbed above 75% of the total buffers in the system
2337 * return an error if the caller has indicated that it can
2338 * handle one in this case, otherwise schedule the I/O now
2339 * this is done to prevent us from allocating tons of extra
2340 * buffers when dealing with virtual disks (i.e. DiskImages),
2341 * because additional buffers are dynamically allocated to prevent
2342 * deadlocks from occurring
2344 * however, can't do a buf_bawrite() if the LOCKED bit is set because the
2345 * buffer is part of a transaction and can't go to disk until
2346 * the LOCKED bit is cleared.
2348 if (!ISSET(bp
->b_flags
, B_LOCKED
) && nbdwrite
> ((nbuf_headers
/4)*3)) {
2352 * If the vnode has "too many" write operations in progress
2353 * wait for them to finish the IO
2355 (void)vnode_waitforwrites(vp
, VNODE_ASYNC_THROTTLE
, 0, 0, "buf_bdwrite");
2357 return (buf_bawrite(bp
));
2360 /* Otherwise, the "write" is done, so mark and release the buffer. */
2361 SET(bp
->b_flags
, B_DONE
);
2367 buf_bdwrite(buf_t bp
)
2369 return (bdwrite_internal(bp
, 0));
2374 * Asynchronous block write; just an asynchronous buf_bwrite().
2376 * Note: With the abilitty to allocate additional buffer
2377 * headers, we can get in to the situation where "too" many
2378 * buf_bawrite()s can create situation where the kernel can create
2379 * buffers faster than the disks can service.
2380 * We limit the number of "in flight" writes a vnode can have to
2384 bawrite_internal(buf_t bp
, int throttle
)
2386 vnode_t vp
= bp
->b_vp
;
2391 * If the vnode has "too many" write operations in progress
2392 * wait for them to finish the IO
2394 (void)vnode_waitforwrites(vp
, VNODE_ASYNC_THROTTLE
, 0, 0, (const char *)"buf_bawrite");
2395 else if (vp
->v_numoutput
>= VNODE_ASYNC_THROTTLE
)
2397 * return to the caller and
2398 * let him decide what to do
2400 return (EWOULDBLOCK
);
2402 SET(bp
->b_flags
, B_ASYNC
);
2404 return (VNOP_BWRITE(bp
));
2408 buf_bawrite(buf_t bp
)
2410 return (bawrite_internal(bp
, 1));
2416 buf_free_meta_store(buf_t bp
)
2418 if (bp
->b_bufsize
) {
2419 if (ISSET(bp
->b_flags
, B_ZALLOC
)) {
2422 z
= getbufzone(bp
->b_bufsize
);
2423 zfree(z
, (void *)bp
->b_datap
);
2425 kmem_free(kernel_map
, bp
->b_datap
, bp
->b_bufsize
);
2427 bp
->b_datap
= (uintptr_t)NULL
;
2434 buf_brelse_shadow(buf_t bp
)
2438 buf_t bp_return
= NULL
;
2439 #ifdef BUF_MAKE_PRIVATE
2443 int need_wakeup
= 0;
2445 lck_mtx_lock_spin(buf_mtxp
);
2447 __IGNORE_WCASTALIGN(bp_head
= (buf_t
)bp
->b_orig
);
2449 if (bp_head
->b_whichq
!= -1)
2450 panic("buf_brelse_shadow: bp_head on freelist %d\n", bp_head
->b_whichq
);
2452 #ifdef BUF_MAKE_PRIVATE
2453 if (bp_data
= bp
->b_data_store
) {
2454 bp_data
->b_data_ref
--;
2456 * snapshot the ref count so that we can check it
2457 * outside of the lock... we only want the guy going
2458 * from 1 -> 0 to try and release the storage
2460 data_ref
= bp_data
->b_data_ref
;
2463 KERNEL_DEBUG(0xbbbbc008 | DBG_FUNC_START
, bp
, bp_head
, bp_head
->b_shadow_ref
, 0, 0);
2465 bp_head
->b_shadow_ref
--;
2467 for (bp_temp
= bp_head
; bp_temp
&& bp
!= bp_temp
->b_shadow
; bp_temp
= bp_temp
->b_shadow
);
2469 if (bp_temp
== NULL
)
2470 panic("buf_brelse_shadow: bp not on list %p", bp_head
);
2472 bp_temp
->b_shadow
= bp_temp
->b_shadow
->b_shadow
;
2474 #ifdef BUF_MAKE_PRIVATE
2476 * we're about to free the current 'owner' of the data buffer and
2477 * there is at least one other shadow buf_t still pointing at it
2478 * so transfer it to the first shadow buf left in the chain
2480 if (bp
== bp_data
&& data_ref
) {
2481 if ((bp_data
= bp_head
->b_shadow
) == NULL
)
2482 panic("buf_brelse_shadow: data_ref mismatch bp(%p)", bp
);
2484 for (bp_temp
= bp_data
; bp_temp
; bp_temp
= bp_temp
->b_shadow
)
2485 bp_temp
->b_data_store
= bp_data
;
2486 bp_data
->b_data_ref
= data_ref
;
2489 if (bp_head
->b_shadow_ref
== 0 && bp_head
->b_shadow
)
2490 panic("buf_relse_shadow: b_shadow != NULL && b_shadow_ref == 0 bp(%p)", bp
);
2491 if (bp_head
->b_shadow_ref
&& bp_head
->b_shadow
== 0)
2492 panic("buf_relse_shadow: b_shadow == NULL && b_shadow_ref != 0 bp(%p)", bp
);
2494 if (bp_head
->b_shadow_ref
== 0) {
2495 if (!ISSET(bp_head
->b_lflags
, BL_BUSY
)) {
2497 CLR(bp_head
->b_flags
, B_AGE
);
2498 bp_head
->b_timestamp
= buf_timestamp();
2500 if (ISSET(bp_head
->b_flags
, B_LOCKED
)) {
2501 bp_head
->b_whichq
= BQ_LOCKED
;
2502 binstailfree(bp_head
, &bufqueues
[BQ_LOCKED
], BQ_LOCKED
);
2504 bp_head
->b_whichq
= BQ_META
;
2505 binstailfree(bp_head
, &bufqueues
[BQ_META
], BQ_META
);
2507 } else if (ISSET(bp_head
->b_lflags
, BL_WAITSHADOW
)) {
2508 CLR(bp_head
->b_lflags
, BL_WAITSHADOW
);
2510 bp_return
= bp_head
;
2512 if (ISSET(bp_head
->b_lflags
, BL_WANTED_REF
)) {
2513 CLR(bp_head
->b_lflags
, BL_WANTED_REF
);
2517 lck_mtx_unlock(buf_mtxp
);
2522 #ifdef BUF_MAKE_PRIVATE
2523 if (bp
== bp_data
&& data_ref
== 0)
2524 buf_free_meta_store(bp
);
2526 bp
->b_data_store
= NULL
;
2528 KERNEL_DEBUG(0xbbbbc008 | DBG_FUNC_END
, bp
, 0, 0, 0, 0);
2535 * Release a buffer on to the free lists.
2536 * Described in Bach (p. 46).
2539 buf_brelse(buf_t bp
)
2541 struct bqueues
*bufq
;
2544 int need_wakeup
= 0;
2545 int need_bp_wakeup
= 0;
2548 if (bp
->b_whichq
!= -1 || !(bp
->b_lflags
& BL_BUSY
))
2549 panic("buf_brelse: bad buffer = %p\n", bp
);
2552 (void) OSBacktrace(&bp
->b_stackbrelse
[0], 6);
2554 bp
->b_lastbrelse
= current_thread();
2557 if (bp
->b_lflags
& BL_IOBUF
) {
2558 buf_t shadow_master_bp
= NULL
;
2560 if (ISSET(bp
->b_lflags
, BL_SHADOW
))
2561 shadow_master_bp
= buf_brelse_shadow(bp
);
2562 else if (ISSET(bp
->b_lflags
, BL_IOBUF_ALLOC
))
2563 buf_free_meta_store(bp
);
2566 if (shadow_master_bp
) {
2567 bp
= shadow_master_bp
;
2568 goto finish_shadow_master
;
2573 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 388)) | DBG_FUNC_START
,
2574 bp
->b_lblkno
* PAGE_SIZE
, bp
, bp
->b_datap
,
2577 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
2580 * if we're invalidating a buffer that has the B_FILTER bit
2581 * set then call the b_iodone function so it gets cleaned
2584 * the HFS journal code depends on this
2586 if (ISSET(bp
->b_flags
, B_META
) && ISSET(bp
->b_flags
, B_INVAL
)) {
2587 if (ISSET(bp
->b_flags
, B_FILTER
)) { /* if necessary, call out */
2588 void (*iodone_func
)(struct buf
*, void *) = bp
->b_iodone
;
2589 void *arg
= bp
->b_transaction
;
2591 CLR(bp
->b_flags
, B_FILTER
); /* but note callout done */
2592 bp
->b_iodone
= NULL
;
2593 bp
->b_transaction
= NULL
;
2595 if (iodone_func
== NULL
) {
2596 panic("brelse: bp @ %p has NULL b_iodone!\n", bp
);
2598 (*iodone_func
)(bp
, arg
);
2602 * I/O is done. Cleanup the UPL state
2606 if ( !ISSET(bp
->b_flags
, B_META
) && UBCINFOEXISTS(bp
->b_vp
) && bp
->b_bufsize
) {
2611 if ( !ISSET(bp
->b_flags
, B_INVAL
)) {
2612 kret
= ubc_create_upl(bp
->b_vp
,
2613 ubc_blktooff(bp
->b_vp
, bp
->b_lblkno
),
2619 if (kret
!= KERN_SUCCESS
)
2620 panic("brelse: Failed to create UPL");
2622 upl_ubc_alias_set(upl
, (uintptr_t) bp
, (uintptr_t) 5);
2623 #endif /* UPL_DEBUG */
2627 kret
= ubc_upl_unmap(upl
);
2629 if (kret
!= KERN_SUCCESS
)
2630 panic("ubc_upl_unmap failed");
2631 bp
->b_datap
= (uintptr_t)NULL
;
2635 if (bp
->b_flags
& (B_ERROR
| B_INVAL
)) {
2636 if (bp
->b_flags
& (B_READ
| B_INVAL
))
2637 upl_flags
= UPL_ABORT_DUMP_PAGES
;
2641 ubc_upl_abort(upl
, upl_flags
);
2643 if (ISSET(bp
->b_flags
, B_DELWRI
| B_WASDIRTY
))
2644 upl_flags
= UPL_COMMIT_SET_DIRTY
;
2646 upl_flags
= UPL_COMMIT_CLEAR_DIRTY
;
2648 ubc_upl_commit_range(upl
, 0, bp
->b_bufsize
, upl_flags
|
2649 UPL_COMMIT_INACTIVATE
| UPL_COMMIT_FREE_ON_EMPTY
);
2655 panic("brelse: UPL set for non VREG; vp=%p", bp
->b_vp
);
2659 * If it's locked, don't report an error; try again later.
2661 if (ISSET(bp
->b_flags
, (B_LOCKED
|B_ERROR
)) == (B_LOCKED
|B_ERROR
))
2662 CLR(bp
->b_flags
, B_ERROR
);
2664 * If it's not cacheable, or an error, mark it invalid.
2666 if (ISSET(bp
->b_flags
, (B_NOCACHE
|B_ERROR
)))
2667 SET(bp
->b_flags
, B_INVAL
);
2669 if ((bp
->b_bufsize
<= 0) ||
2670 ISSET(bp
->b_flags
, B_INVAL
) ||
2671 (ISSET(bp
->b_lflags
, BL_WANTDEALLOC
) && !ISSET(bp
->b_flags
, B_DELWRI
))) {
2673 boolean_t delayed_buf_free_meta_store
= FALSE
;
2676 * If it's invalid or empty, dissociate it from its vnode,
2677 * release its storage if B_META, and
2678 * clean it up a bit and put it on the EMPTY queue
2680 if (ISSET(bp
->b_flags
, B_DELWRI
))
2681 OSAddAtomicLong(-1, &nbdwrite
);
2683 if (ISSET(bp
->b_flags
, B_META
)) {
2684 if (bp
->b_shadow_ref
)
2685 delayed_buf_free_meta_store
= TRUE
;
2687 buf_free_meta_store(bp
);
2690 * nuke any credentials we were holding
2692 buf_release_credentials(bp
);
2694 lck_mtx_lock_spin(buf_mtxp
);
2696 if (bp
->b_shadow_ref
) {
2697 SET(bp
->b_lflags
, BL_WAITSHADOW
);
2699 lck_mtx_unlock(buf_mtxp
);
2703 if (delayed_buf_free_meta_store
== TRUE
) {
2705 lck_mtx_unlock(buf_mtxp
);
2706 finish_shadow_master
:
2707 buf_free_meta_store(bp
);
2709 lck_mtx_lock_spin(buf_mtxp
);
2711 CLR(bp
->b_flags
, (B_META
| B_ZALLOC
| B_DELWRI
| B_LOCKED
| B_AGE
| B_ASYNC
| B_NOCACHE
| B_FUA
));
2718 binshash(bp
, &invalhash
);
2720 bp
->b_whichq
= BQ_EMPTY
;
2721 binsheadfree(bp
, &bufqueues
[BQ_EMPTY
], BQ_EMPTY
);
2725 * It has valid data. Put it on the end of the appropriate
2726 * queue, so that it'll stick around for as long as possible.
2728 if (ISSET(bp
->b_flags
, B_LOCKED
))
2729 whichq
= BQ_LOCKED
; /* locked in core */
2730 else if (ISSET(bp
->b_flags
, B_META
))
2731 whichq
= BQ_META
; /* meta-data */
2732 else if (ISSET(bp
->b_flags
, B_AGE
))
2733 whichq
= BQ_AGE
; /* stale but valid data */
2735 whichq
= BQ_LRU
; /* valid data */
2736 bufq
= &bufqueues
[whichq
];
2738 bp
->b_timestamp
= buf_timestamp();
2740 lck_mtx_lock_spin(buf_mtxp
);
2743 * the buf_brelse_shadow routine doesn't take 'ownership'
2744 * of the parent buf_t... it updates state that is protected by
2745 * the buf_mtxp, and checks for BL_BUSY to determine whether to
2746 * put the buf_t back on a free list. b_shadow_ref is protected
2747 * by the lock, and since we have not yet cleared B_BUSY, we need
2748 * to check it while holding the lock to insure that one of us
2749 * puts this buf_t back on a free list when it is safe to do so
2751 if (bp
->b_shadow_ref
== 0) {
2752 CLR(bp
->b_flags
, (B_AGE
| B_ASYNC
| B_NOCACHE
));
2753 bp
->b_whichq
= whichq
;
2754 binstailfree(bp
, bufq
, whichq
);
2757 * there are still cloned buf_t's pointing
2758 * at this guy... need to keep it off the
2759 * freelists until a buf_brelse is done on
2762 CLR(bp
->b_flags
, (B_ASYNC
| B_NOCACHE
));
2767 * needbuffer is a global
2768 * we're currently using buf_mtxp to protect it
2769 * delay doing the actual wakeup until after
2775 if (ISSET(bp
->b_lflags
, BL_WANTED
)) {
2777 * delay the actual wakeup until after we
2778 * clear BL_BUSY and we've dropped buf_mtxp
2783 * Unlock the buffer.
2785 CLR(bp
->b_lflags
, (BL_BUSY
| BL_WANTED
));
2788 lck_mtx_unlock(buf_mtxp
);
2792 * Wake up any processes waiting for any buffer to become free.
2794 wakeup(&needbuffer
);
2796 if (need_bp_wakeup
) {
2798 * Wake up any proceeses waiting for _this_ buffer to become free.
2802 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 388)) | DBG_FUNC_END
,
2803 bp
, bp
->b_datap
, bp
->b_flags
, 0, 0);
2807 * Determine if a block is in the cache.
2808 * Just look on what would be its hash chain. If it's there, return
2809 * a pointer to it, unless it's marked invalid. If it's marked invalid,
2810 * we normally don't return the buffer, unless the caller explicitly
2814 incore(vnode_t vp
, daddr64_t blkno
)
2817 struct bufhashhdr
*dp
;
2819 dp
= BUFHASH(vp
, blkno
);
2821 lck_mtx_lock_spin(buf_mtxp
);
2823 if (incore_locked(vp
, blkno
, dp
))
2827 lck_mtx_unlock(buf_mtxp
);
2834 incore_locked(vnode_t vp
, daddr64_t blkno
, struct bufhashhdr
*dp
)
2838 /* Search hash chain */
2839 for (bp
= dp
->lh_first
; bp
!= NULL
; bp
= bp
->b_hash
.le_next
) {
2840 if (bp
->b_lblkno
== blkno
&& bp
->b_vp
== vp
&&
2841 !ISSET(bp
->b_flags
, B_INVAL
)) {
2850 buf_wait_for_shadow_io(vnode_t vp
, daddr64_t blkno
)
2853 struct bufhashhdr
*dp
;
2855 dp
= BUFHASH(vp
, blkno
);
2857 lck_mtx_lock_spin(buf_mtxp
);
2860 if ((bp
= incore_locked(vp
, blkno
, dp
)) == NULL
)
2863 if (bp
->b_shadow_ref
== 0)
2866 SET(bp
->b_lflags
, BL_WANTED_REF
);
2868 (void) msleep(bp
, buf_mtxp
, PSPIN
| (PRIBIO
+1), "buf_wait_for_shadow", NULL
);
2870 lck_mtx_unlock(buf_mtxp
);
2873 /* XXX FIXME -- Update the comment to reflect the UBC changes (please) -- */
2875 * Get a block of requested size that is associated with
2876 * a given vnode and block offset. If it is found in the
2877 * block cache, mark it as having been found, make it busy
2878 * and return it. Otherwise, return an empty block of the
2879 * correct size. It is up to the caller to insure that the
2880 * cached blocks be of the correct size.
2883 buf_getblk(vnode_t vp
, daddr64_t blkno
, int size
, int slpflag
, int slptimeo
, int operation
)
2888 upl_page_info_t
*pl
;
2893 struct bufhashhdr
*dp
;
2895 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_START
,
2896 (uintptr_t)(blkno
* PAGE_SIZE
), size
, operation
, 0, 0);
2898 ret_only_valid
= operation
& BLK_ONLYVALID
;
2899 operation
&= ~BLK_ONLYVALID
;
2900 dp
= BUFHASH(vp
, blkno
);
2902 lck_mtx_lock_spin(buf_mtxp
);
2904 if ((bp
= incore_locked(vp
, blkno
, dp
))) {
2906 * Found in the Buffer Cache
2908 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
2912 switch (operation
) {
2916 SET(bp
->b_lflags
, BL_WANTED
);
2917 bufstats
.bufs_busyincore
++;
2920 * don't retake the mutex after being awakened...
2921 * the time out is in msecs
2923 ts
.tv_sec
= (slptimeo
/1000);
2924 ts
.tv_nsec
= (slptimeo
% 1000) * 10 * NSEC_PER_USEC
* 1000;
2926 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 396)) | DBG_FUNC_NONE
,
2927 (uintptr_t)blkno
, size
, operation
, 0, 0);
2929 err
= msleep(bp
, buf_mtxp
, slpflag
| PDROP
| (PRIBIO
+ 1), "buf_getblk", &ts
);
2932 * Callers who call with PCATCH or timeout are
2933 * willing to deal with the NULL pointer
2935 if (err
&& ((slpflag
& PCATCH
) || ((err
== EWOULDBLOCK
) && slptimeo
)))
2942 * unknown operation requested
2944 panic("getblk: paging or unknown operation for incore busy buffer - %x\n", operation
);
2952 * buffer in core and not busy
2954 SET(bp
->b_lflags
, BL_BUSY
);
2955 SET(bp
->b_flags
, B_CACHE
);
2958 bremfree_locked(bp
);
2959 bufstats
.bufs_incore
++;
2961 lck_mtx_unlock(buf_mtxp
);
2963 bp
->b_owner
= current_thread();
2967 panic("buffer has UPL, but not marked BUSY: %p", bp
);
2969 clear_bdone
= FALSE
;
2970 if (!ret_only_valid
) {
2972 * If the number bytes that are valid is going
2973 * to increase (even if we end up not doing a
2974 * reallocation through allocbuf) we have to read
2975 * the new size first.
2977 * This is required in cases where we doing a read
2978 * modify write of a already valid data on disk but
2979 * in cases where the data on disk beyond (blkno + b_bcount)
2980 * is invalid, we may end up doing extra I/O.
2982 if (operation
== BLK_META
&& bp
->b_bcount
< size
) {
2984 * Since we are going to read in the whole size first
2985 * we first have to ensure that any pending delayed write
2986 * is flushed to disk first.
2988 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
2989 CLR(bp
->b_flags
, B_CACHE
);
2994 * clear B_DONE before returning from
2995 * this function so that the caller can
2996 * can issue a read for the new size.
3001 if (bp
->b_bufsize
!= size
)
3006 switch (operation
) {
3009 * "write" operation: let the UPL subsystem
3010 * know that we intend to modify the buffer
3011 * cache pages we're gathering.
3013 upl_flags
|= UPL_WILL_MODIFY
;
3015 upl_flags
|= UPL_PRECIOUS
;
3016 if (UBCINFOEXISTS(bp
->b_vp
) && bp
->b_bufsize
) {
3017 kret
= ubc_create_upl(vp
,
3018 ubc_blktooff(vp
, bp
->b_lblkno
),
3023 if (kret
!= KERN_SUCCESS
)
3024 panic("Failed to create UPL");
3028 if (upl_valid_page(pl
, 0)) {
3029 if (upl_dirty_page(pl
, 0))
3030 SET(bp
->b_flags
, B_WASDIRTY
);
3032 CLR(bp
->b_flags
, B_WASDIRTY
);
3034 CLR(bp
->b_flags
, (B_DONE
| B_CACHE
| B_WASDIRTY
| B_DELWRI
));
3036 kret
= ubc_upl_map(upl
, (vm_offset_t
*)&(bp
->b_datap
));
3038 if (kret
!= KERN_SUCCESS
)
3039 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
3045 * VM is not involved in IO for the meta data
3046 * buffer already has valid data
3051 panic("getblk: paging or unknown operation for incore buffer- %d\n", operation
);
3057 CLR(bp
->b_flags
, B_DONE
);
3059 } else { /* not incore() */
3060 int queue
= BQ_EMPTY
; /* Start with no preference */
3062 if (ret_only_valid
) {
3063 lck_mtx_unlock(buf_mtxp
);
3066 if ((vnode_isreg(vp
) == 0) || (UBCINFOEXISTS(vp
) == 0) /*|| (vnode_issystem(vp) == 1)*/)
3067 operation
= BLK_META
;
3069 if ((bp
= getnewbuf(slpflag
, slptimeo
, &queue
)) == NULL
)
3073 * getnewbuf may block for a number of different reasons...
3074 * if it does, it's then possible for someone else to
3075 * create a buffer for the same block and insert it into
3076 * the hash... if we see it incore at this point we dump
3077 * the buffer we were working on and start over
3079 if (incore_locked(vp
, blkno
, dp
)) {
3080 SET(bp
->b_flags
, B_INVAL
);
3081 binshash(bp
, &invalhash
);
3083 lck_mtx_unlock(buf_mtxp
);
3089 * NOTE: YOU CAN NOT BLOCK UNTIL binshash() HAS BEEN
3090 * CALLED! BE CAREFUL.
3094 * mark the buffer as B_META if indicated
3095 * so that when buffer is released it will goto META queue
3097 if (operation
== BLK_META
)
3098 SET(bp
->b_flags
, B_META
);
3100 bp
->b_blkno
= bp
->b_lblkno
= blkno
;
3104 * Insert in the hash so that incore() can find it
3106 binshash(bp
, BUFHASH(vp
, blkno
));
3108 bgetvp_locked(vp
, bp
);
3110 lck_mtx_unlock(buf_mtxp
);
3115 switch (operation
) {
3118 * buffer data is invalid...
3120 * I don't want to have to retake buf_mtxp,
3121 * so the miss and vmhits counters are done
3122 * with Atomic updates... all other counters
3123 * in bufstats are protected with either
3124 * buf_mtxp or iobuffer_mtxp
3126 OSAddAtomicLong(1, &bufstats
.bufs_miss
);
3131 * "write" operation: let the UPL subsystem know
3132 * that we intend to modify the buffer cache pages
3135 upl_flags
|= UPL_WILL_MODIFY
;
3138 size_t contig_bytes
;
3141 #if DEVELOPMENT || DEBUG
3143 * Apple implemented file systems use UBC excludively; they should
3144 * not call in here."
3146 const char* excldfs
[] = {"hfs", "afpfs", "smbfs", "acfs",
3147 "exfat", "msdos", "webdav", NULL
};
3149 for (int i
= 0; excldfs
[i
] != NULL
; i
++) {
3151 !strcmp(vp
->v_mount
->mnt_vfsstat
.f_fstypename
,
3153 panic("%s %s calls buf_getblk",
3155 operation
== BLK_READ
? "BLK_READ" : "BLK_WRITE");
3161 panic("bp already has UPL: %p",bp
);
3163 f_offset
= ubc_blktooff(vp
, blkno
);
3165 upl_flags
|= UPL_PRECIOUS
;
3166 kret
= ubc_create_upl(vp
,
3173 if (kret
!= KERN_SUCCESS
)
3174 panic("Failed to create UPL");
3176 upl_ubc_alias_set(upl
, (uintptr_t) bp
, (uintptr_t) 4);
3177 #endif /* UPL_DEBUG */
3180 if (upl_valid_page(pl
, 0)) {
3182 if (operation
== BLK_READ
)
3183 bmap_flags
= VNODE_READ
;
3185 bmap_flags
= VNODE_WRITE
;
3187 SET(bp
->b_flags
, B_CACHE
| B_DONE
);
3189 OSAddAtomicLong(1, &bufstats
.bufs_vmhits
);
3194 if (upl_dirty_page(pl
, 0)) {
3196 SET(bp
->b_flags
, B_WASDIRTY
);
3198 bp
->b_validend
= bp
->b_bcount
;
3199 bp
->b_dirtyend
= bp
->b_bcount
;
3202 bp
->b_validend
= bp
->b_bcount
;
3206 * try to recreate the physical block number associated with
3209 if (VNOP_BLOCKMAP(vp
, f_offset
, bp
->b_bcount
, &bp
->b_blkno
, &contig_bytes
, NULL
, bmap_flags
, NULL
))
3210 panic("getblk: VNOP_BLOCKMAP failed");
3212 * if the extent represented by this buffer
3213 * is not completely physically contiguous on
3214 * disk, than we can't cache the physical mapping
3215 * in the buffer header
3217 if ((long)contig_bytes
< bp
->b_bcount
)
3218 bp
->b_blkno
= bp
->b_lblkno
;
3220 OSAddAtomicLong(1, &bufstats
.bufs_miss
);
3222 kret
= ubc_upl_map(upl
, (vm_offset_t
*)&(bp
->b_datap
));
3224 if (kret
!= KERN_SUCCESS
)
3225 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
3229 panic("getblk: paging or unknown operation - %x", operation
);
3234 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_END
,
3235 bp
, bp
->b_datap
, bp
->b_flags
, 3, 0);
3238 (void) OSBacktrace(&bp
->b_stackgetblk
[0], 6);
3244 * Get an empty, disassociated buffer of given size.
3247 buf_geteblk(int size
)
3250 int queue
= BQ_EMPTY
;
3253 lck_mtx_lock_spin(buf_mtxp
);
3255 bp
= getnewbuf(0, 0, &queue
);
3256 } while (bp
== NULL
);
3258 SET(bp
->b_flags
, (B_META
|B_INVAL
));
3261 assert(queue
== BQ_EMPTY
);
3262 #endif /* DIAGNOSTIC */
3263 /* XXX need to implement logic to deal with other queues */
3265 binshash(bp
, &invalhash
);
3266 bufstats
.bufs_eblk
++;
3268 lck_mtx_unlock(buf_mtxp
);
3276 buf_redundancy_flags(buf_t bp
)
3278 return bp
->b_redundancy_flags
;
3282 buf_set_redundancy_flags(buf_t bp
, uint32_t flags
)
3284 SET(bp
->b_redundancy_flags
, flags
);
3288 buf_clear_redundancy_flags(buf_t bp
, uint32_t flags
)
3290 CLR(bp
->b_redundancy_flags
, flags
);
3296 recycle_buf_from_pool(int nsize
)
3301 lck_mtx_lock_spin(buf_mtxp
);
3303 TAILQ_FOREACH(bp
, &bufqueues
[BQ_META
], b_freelist
) {
3304 if (ISSET(bp
->b_flags
, B_DELWRI
) || bp
->b_bufsize
!= nsize
)
3306 ptr
= (void *)bp
->b_datap
;
3309 bcleanbuf(bp
, TRUE
);
3312 lck_mtx_unlock(buf_mtxp
);
3319 int zalloc_nopagewait_failed
= 0;
3320 int recycle_buf_failed
= 0;
3323 grab_memory_for_meta_buf(int nsize
)
3327 boolean_t was_vmpriv
;
3329 z
= getbufzone(nsize
);
3332 * make sure we're NOT priviliged so that
3333 * if a vm_page_grab is needed, it won't
3334 * block if we're out of free pages... if
3335 * it blocks, then we can't honor the
3336 * nopagewait request
3338 was_vmpriv
= set_vm_privilege(FALSE
);
3340 ptr
= zalloc_nopagewait(z
);
3342 if (was_vmpriv
== TRUE
)
3343 set_vm_privilege(TRUE
);
3347 zalloc_nopagewait_failed
++;
3349 ptr
= recycle_buf_from_pool(nsize
);
3353 recycle_buf_failed
++;
3355 if (was_vmpriv
== FALSE
)
3356 set_vm_privilege(TRUE
);
3360 if (was_vmpriv
== FALSE
)
3361 set_vm_privilege(FALSE
);
3368 * With UBC, there is no need to expand / shrink the file data
3369 * buffer. The VM uses the same pages, hence no waste.
3370 * All the file data buffers can have one size.
3371 * In fact expand / shrink would be an expensive operation.
3373 * Only exception to this is meta-data buffers. Most of the
3374 * meta data operations are smaller than PAGE_SIZE. Having the
3375 * meta-data buffers grow and shrink as needed, optimizes use
3376 * of the kernel wired memory.
3380 allocbuf(buf_t bp
, int size
)
3382 vm_size_t desired_size
;
3384 desired_size
= roundup(size
, CLBYTES
);
3386 if (desired_size
< PAGE_SIZE
)
3387 desired_size
= PAGE_SIZE
;
3388 if (desired_size
> MAXBSIZE
)
3389 panic("allocbuf: buffer larger than MAXBSIZE requested");
3391 if (ISSET(bp
->b_flags
, B_META
)) {
3392 int nsize
= roundup(size
, MINMETA
);
3395 vm_offset_t elem
= (vm_offset_t
)bp
->b_datap
;
3397 if (ISSET(bp
->b_flags
, B_ZALLOC
)) {
3398 if (bp
->b_bufsize
< nsize
) {
3401 /* reallocate to a bigger size */
3403 zprev
= getbufzone(bp
->b_bufsize
);
3404 if (nsize
<= MAXMETA
) {
3405 desired_size
= nsize
;
3407 /* b_datap not really a ptr */
3408 *(void **)(&bp
->b_datap
) = grab_memory_for_meta_buf(nsize
);
3410 bp
->b_datap
= (uintptr_t)NULL
;
3411 kmem_alloc_kobject(kernel_map
, (vm_offset_t
*)&bp
->b_datap
, desired_size
, VM_KERN_MEMORY_FILE
);
3412 CLR(bp
->b_flags
, B_ZALLOC
);
3414 bcopy((void *)elem
, (caddr_t
)bp
->b_datap
, bp
->b_bufsize
);
3415 zfree(zprev
, (void *)elem
);
3417 desired_size
= bp
->b_bufsize
;
3421 if ((vm_size_t
)bp
->b_bufsize
< desired_size
) {
3422 /* reallocate to a bigger size */
3423 bp
->b_datap
= (uintptr_t)NULL
;
3424 kmem_alloc_kobject(kernel_map
, (vm_offset_t
*)&bp
->b_datap
, desired_size
, VM_KERN_MEMORY_FILE
);
3425 bcopy((const void *)elem
, (caddr_t
)bp
->b_datap
, bp
->b_bufsize
);
3426 kmem_free(kernel_map
, elem
, bp
->b_bufsize
);
3428 desired_size
= bp
->b_bufsize
;
3432 /* new allocation */
3433 if (nsize
<= MAXMETA
) {
3434 desired_size
= nsize
;
3436 /* b_datap not really a ptr */
3437 *(void **)(&bp
->b_datap
) = grab_memory_for_meta_buf(nsize
);
3438 SET(bp
->b_flags
, B_ZALLOC
);
3440 kmem_alloc_kobject(kernel_map
, (vm_offset_t
*)&bp
->b_datap
, desired_size
, VM_KERN_MEMORY_FILE
);
3443 if (bp
->b_datap
== 0)
3444 panic("allocbuf: NULL b_datap");
3446 bp
->b_bufsize
= desired_size
;
3447 bp
->b_bcount
= size
;
3453 * Get a new buffer from one of the free lists.
3455 * Request for a queue is passes in. The queue from which the buffer was taken
3456 * from is returned. Out of range queue requests get BQ_EMPTY. Request for
3457 * BQUEUE means no preference. Use heuristics in that case.
3458 * Heuristics is as follows:
3459 * Try BQ_AGE, BQ_LRU, BQ_EMPTY, BQ_META in that order.
3460 * If none available block till one is made available.
3461 * If buffers available on both BQ_AGE and BQ_LRU, check the timestamps.
3462 * Pick the most stale buffer.
3463 * If found buffer was marked delayed write, start the async. write
3464 * and restart the search.
3465 * Initialize the fields and disassociate the buffer from the vnode.
3466 * Remove the buffer from the hash. Return the buffer and the queue
3467 * on which it was found.
3469 * buf_mtxp is held upon entry
3470 * returns with buf_mtxp locked if new buf available
3471 * returns with buf_mtxp UNlocked if new buf NOT available
3475 getnewbuf(int slpflag
, int slptimeo
, int * queue
)
3481 int age_time
, lru_time
, bp_time
, meta_time
;
3482 int req
= *queue
; /* save it for restarts */
3487 * invalid request gets empty queue
3489 if ((*queue
>= BQUEUES
) || (*queue
< 0)
3490 || (*queue
== BQ_LAUNDRY
) || (*queue
== BQ_LOCKED
))
3494 if (*queue
== BQ_EMPTY
&& (bp
= bufqueues
[*queue
].tqh_first
))
3498 * need to grow number of bufs, add another one rather than recycling
3500 if (nbuf_headers
< max_nbuf_headers
) {
3502 * Increment count now as lock
3503 * is dropped for allocation.
3504 * That avoids over commits
3509 /* Try for the requested queue first */
3510 bp
= bufqueues
[*queue
].tqh_first
;
3514 /* Unable to use requested queue */
3515 age_bp
= bufqueues
[BQ_AGE
].tqh_first
;
3516 lru_bp
= bufqueues
[BQ_LRU
].tqh_first
;
3517 meta_bp
= bufqueues
[BQ_META
].tqh_first
;
3519 if (!age_bp
&& !lru_bp
&& !meta_bp
) {
3521 * Unavailble on AGE or LRU or META queues
3522 * Try the empty list first
3524 bp
= bufqueues
[BQ_EMPTY
].tqh_first
;
3530 * We have seen is this is hard to trigger.
3531 * This is an overcommit of nbufs but needed
3532 * in some scenarios with diskiamges
3536 lck_mtx_unlock(buf_mtxp
);
3538 /* Create a new temporary buffer header */
3539 bp
= (struct buf
*)zalloc(buf_hdr_zone
);
3543 bp
->b_whichq
= BQ_EMPTY
;
3544 bp
->b_timestamp
= buf_timestamp();
3546 SET(bp
->b_flags
, B_HDRALLOC
);
3549 lck_mtx_lock_spin(buf_mtxp
);
3552 binshash(bp
, &invalhash
);
3553 binsheadfree(bp
, &bufqueues
[BQ_EMPTY
], BQ_EMPTY
);
3557 /* subtract already accounted bufcount */
3560 bufstats
.bufs_sleeps
++;
3562 /* wait for a free buffer of any kind */
3564 /* hz value is 100 */
3565 ts
.tv_sec
= (slptimeo
/1000);
3566 /* the hz value is 100; which leads to 10ms */
3567 ts
.tv_nsec
= (slptimeo
% 1000) * NSEC_PER_USEC
* 1000 * 10;
3569 msleep(&needbuffer
, buf_mtxp
, slpflag
| PDROP
| (PRIBIO
+1), "getnewbuf", &ts
);
3573 /* Buffer available either on AGE or LRU or META */
3577 /* Buffer available either on AGE or LRU */
3581 } else if (!lru_bp
) {
3584 } else { /* buffer available on both AGE and LRU */
3585 int t
= buf_timestamp();
3587 age_time
= t
- age_bp
->b_timestamp
;
3588 lru_time
= t
- lru_bp
->b_timestamp
;
3589 if ((age_time
< 0) || (lru_time
< 0)) { /* time set backwards */
3593 * we should probably re-timestamp eveything in the
3594 * queues at this point with the current time
3597 if ((lru_time
>= lru_is_stale
) && (age_time
< age_is_stale
)) {
3607 if (!bp
) { /* Neither on AGE nor on LRU */
3610 } else if (meta_bp
) {
3611 int t
= buf_timestamp();
3613 bp_time
= t
- bp
->b_timestamp
;
3614 meta_time
= t
- meta_bp
->b_timestamp
;
3616 if (!(bp_time
< 0) && !(meta_time
< 0)) {
3617 /* time not set backwards */
3619 bp_is_stale
= (*queue
== BQ_LRU
) ?
3620 lru_is_stale
: age_is_stale
;
3622 if ((meta_time
>= meta_is_stale
) &&
3623 (bp_time
< bp_is_stale
)) {
3630 if (ISSET(bp
->b_flags
, B_LOCKED
) || ISSET(bp
->b_lflags
, BL_BUSY
))
3631 panic("getnewbuf: bp @ %p is LOCKED or BUSY! (flags 0x%x)\n", bp
, bp
->b_flags
);
3634 if (bcleanbuf(bp
, FALSE
)) {
3636 * moved to the laundry thread, buffer not ready
3647 * Returns 0 if buffer is ready to use,
3648 * Returns 1 if issued a buf_bawrite() to indicate
3649 * that the buffer is not ready.
3651 * buf_mtxp is held upon entry
3652 * returns with buf_mtxp locked
3655 bcleanbuf(buf_t bp
, boolean_t discard
)
3657 /* Remove from the queue */
3658 bremfree_locked(bp
);
3661 bp
->b_owner
= current_thread();
3665 * If buffer was a delayed write, start the IO by queuing
3666 * it on the LAUNDRY queue, and return 1
3668 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
3670 SET(bp
->b_lflags
, BL_WANTDEALLOC
);
3675 lck_mtx_unlock(buf_mtxp
);
3677 wakeup(&bufqueues
[BQ_LAUNDRY
]);
3679 * and give it a chance to run
3681 (void)thread_block(THREAD_CONTINUE_NULL
);
3683 lck_mtx_lock_spin(buf_mtxp
);
3688 bp
->b_owner
= current_thread();
3692 * Buffer is no longer on any free list... we own it
3694 SET(bp
->b_lflags
, BL_BUSY
);
3700 * disassociate us from our vnode, if we had one...
3705 lck_mtx_unlock(buf_mtxp
);
3709 if (ISSET(bp
->b_flags
, B_META
))
3710 buf_free_meta_store(bp
);
3712 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
3714 buf_release_credentials(bp
);
3716 /* If discarding, just move to the empty queue */
3718 lck_mtx_lock_spin(buf_mtxp
);
3719 CLR(bp
->b_flags
, (B_META
| B_ZALLOC
| B_DELWRI
| B_LOCKED
| B_AGE
| B_ASYNC
| B_NOCACHE
| B_FUA
));
3720 bp
->b_whichq
= BQ_EMPTY
;
3721 binshash(bp
, &invalhash
);
3722 binsheadfree(bp
, &bufqueues
[BQ_EMPTY
], BQ_EMPTY
);
3723 CLR(bp
->b_lflags
, BL_BUSY
);
3726 /* Not discarding: clean up and prepare for reuse */
3728 bp
->b_datap
= (uintptr_t)NULL
;
3729 bp
->b_upl
= (void *)NULL
;
3730 bp
->b_fsprivate
= (void *)NULL
;
3732 * preserve the state of whether this buffer
3733 * was allocated on the fly or not...
3734 * the only other flag that should be set at
3735 * this point is BL_BUSY...
3738 bp
->b_owner
= current_thread();
3741 bp
->b_lflags
= BL_BUSY
;
3742 bp
->b_flags
= (bp
->b_flags
& B_HDRALLOC
);
3743 bp
->b_redundancy_flags
= 0;
3745 bp
->b_blkno
= bp
->b_lblkno
= 0;
3746 bp
->b_iodone
= NULL
;
3750 bp
->b_dirtyoff
= bp
->b_dirtyend
= 0;
3751 bp
->b_validoff
= bp
->b_validend
= 0;
3752 bzero(&bp
->b_attr
, sizeof(struct bufattr
));
3754 lck_mtx_lock_spin(buf_mtxp
);
3762 buf_invalblkno(vnode_t vp
, daddr64_t lblkno
, int flags
)
3766 struct bufhashhdr
*dp
;
3768 dp
= BUFHASH(vp
, lblkno
);
3771 lck_mtx_lock_spin(buf_mtxp
);
3773 if ((bp
= incore_locked(vp
, lblkno
, dp
)) == (struct buf
*)0) {
3774 lck_mtx_unlock(buf_mtxp
);
3777 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
3778 if ( !ISSET(flags
, BUF_WAIT
)) {
3779 lck_mtx_unlock(buf_mtxp
);
3782 SET(bp
->b_lflags
, BL_WANTED
);
3784 error
= msleep((caddr_t
)bp
, buf_mtxp
, PDROP
| (PRIBIO
+ 1), "buf_invalblkno", NULL
);
3791 bremfree_locked(bp
);
3792 SET(bp
->b_lflags
, BL_BUSY
);
3793 SET(bp
->b_flags
, B_INVAL
);
3796 bp
->b_owner
= current_thread();
3799 lck_mtx_unlock(buf_mtxp
);
3809 int need_wakeup
= 0;
3811 lck_mtx_lock_spin(buf_mtxp
);
3813 if (ISSET(bp
->b_lflags
, BL_WANTED
)) {
3815 * delay the actual wakeup until after we
3816 * clear BL_BUSY and we've dropped buf_mtxp
3821 bp
->b_owner
= current_thread();
3825 * Unlock the buffer.
3827 CLR(bp
->b_lflags
, (BL_BUSY
| BL_WANTED
));
3830 lck_mtx_unlock(buf_mtxp
);
3834 * Wake up any proceeses waiting for _this_ buffer to become free.
3842 buf_acquire(buf_t bp
, int flags
, int slpflag
, int slptimeo
) {
3845 lck_mtx_lock_spin(buf_mtxp
);
3847 error
= buf_acquire_locked(bp
, flags
, slpflag
, slptimeo
);
3849 lck_mtx_unlock(buf_mtxp
);
3856 buf_acquire_locked(buf_t bp
, int flags
, int slpflag
, int slptimeo
)
3861 if (ISSET(bp
->b_flags
, B_LOCKED
)) {
3862 if ((flags
& BAC_SKIP_LOCKED
))
3865 if ((flags
& BAC_SKIP_NONLOCKED
))
3868 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
3870 * since the lck_mtx_lock may block, the buffer
3871 * may become BUSY, so we need to
3872 * recheck for a NOWAIT request
3874 if (flags
& BAC_NOWAIT
)
3876 SET(bp
->b_lflags
, BL_WANTED
);
3878 /* the hz value is 100; which leads to 10ms */
3879 ts
.tv_sec
= (slptimeo
/100);
3880 ts
.tv_nsec
= (slptimeo
% 100) * 10 * NSEC_PER_USEC
* 1000;
3881 error
= msleep((caddr_t
)bp
, buf_mtxp
, slpflag
| (PRIBIO
+ 1), "buf_acquire", &ts
);
3887 if (flags
& BAC_REMOVE
)
3888 bremfree_locked(bp
);
3889 SET(bp
->b_lflags
, BL_BUSY
);
3893 bp
->b_owner
= current_thread();
3901 * Wait for operations on the buffer to complete.
3902 * When they do, extract and return the I/O's error value.
3905 buf_biowait(buf_t bp
)
3907 while (!ISSET(bp
->b_flags
, B_DONE
)) {
3909 lck_mtx_lock_spin(buf_mtxp
);
3911 if (!ISSET(bp
->b_flags
, B_DONE
)) {
3912 DTRACE_IO1(wait__start
, buf_t
, bp
);
3913 (void) msleep(bp
, buf_mtxp
, PDROP
| (PRIBIO
+1), "buf_biowait", NULL
);
3914 DTRACE_IO1(wait__done
, buf_t
, bp
);
3916 lck_mtx_unlock(buf_mtxp
);
3918 /* check for interruption of I/O (e.g. via NFS), then errors. */
3919 if (ISSET(bp
->b_flags
, B_EINTR
)) {
3920 CLR(bp
->b_flags
, B_EINTR
);
3922 } else if (ISSET(bp
->b_flags
, B_ERROR
))
3923 return (bp
->b_error
? bp
->b_error
: EIO
);
3930 * Mark I/O complete on a buffer.
3932 * If a callback has been requested, e.g. the pageout
3933 * daemon, do so. Otherwise, awaken waiting processes.
3935 * [ Leffler, et al., says on p.247:
3936 * "This routine wakes up the blocked process, frees the buffer
3937 * for an asynchronous write, or, for a request by the pagedaemon
3938 * process, invokes a procedure specified in the buffer structure" ]
3940 * In real life, the pagedaemon (or other system processes) wants
3941 * to do async stuff to, and doesn't want the buffer buf_brelse()'d.
3942 * (for swap pager, that puts swap buffers on the free lists (!!!),
3943 * for the vn device, that puts malloc'd buffers on the free lists!)
3947 buf_biodone(buf_t bp
)
3950 struct bufattr
*bap
;
3952 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 387)) | DBG_FUNC_START
,
3953 bp
, bp
->b_datap
, bp
->b_flags
, 0, 0);
3955 if (ISSET(bp
->b_flags
, B_DONE
))
3956 panic("biodone already");
3960 if (bp
->b_vp
&& bp
->b_vp
->v_mount
) {
3961 mp
= bp
->b_vp
->v_mount
;
3966 if (ISSET(bp
->b_flags
, B_ERROR
)) {
3967 if (mp
&& (MNT_ROOTFS
& mp
->mnt_flag
)) {
3968 dk_error_description_t desc
;
3969 bzero(&desc
, sizeof(desc
));
3970 desc
.description
= panic_disk_error_description
;
3971 desc
.description_size
= panic_disk_error_description_size
;
3972 VNOP_IOCTL(mp
->mnt_devvp
, DKIOCGETERRORDESCRIPTION
, (caddr_t
)&desc
, 0, vfs_context_kernel());
3976 if (mp
&& (bp
->b_flags
& B_READ
) == 0) {
3977 update_last_io_time(mp
);
3978 INCR_PENDING_IO(-(pending_io_t
)buf_count(bp
), mp
->mnt_pending_write_size
);
3980 INCR_PENDING_IO(-(pending_io_t
)buf_count(bp
), mp
->mnt_pending_read_size
);
3983 throttle_info_end_io(bp
);
3985 if (kdebug_enable
) {
3986 int code
= DKIO_DONE
;
3987 int io_tier
= GET_BUFATTR_IO_TIER(bap
);
3989 if (bp
->b_flags
& B_READ
)
3991 if (bp
->b_flags
& B_ASYNC
)
3994 if (bp
->b_flags
& B_META
)
3996 else if (bp
->b_flags
& B_PAGEIO
)
3997 code
|= DKIO_PAGING
;
4000 code
|= DKIO_THROTTLE
;
4002 code
|= ((io_tier
<< DKIO_TIER_SHIFT
) & DKIO_TIER_MASK
);
4004 if (bp
->b_flags
& B_PASSIVE
)
4005 code
|= DKIO_PASSIVE
;
4007 if (bap
->ba_flags
& BA_NOCACHE
)
4008 code
|= DKIO_NOCACHE
;
4010 if (bap
->ba_flags
& BA_IO_TIER_UPGRADE
) {
4011 code
|= DKIO_TIER_UPGRADE
;
4014 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_COMMON
, FSDBG_CODE(DBG_DKRW
, code
) | DBG_FUNC_NONE
,
4015 buf_kernel_addrperm_addr(bp
), (uintptr_t)VM_KERNEL_ADDRPERM(bp
->b_vp
), bp
->b_resid
, bp
->b_error
, 0);
4019 * I/O was done, so don't believe
4020 * the DIRTY state from VM anymore...
4021 * and we need to reset the THROTTLED/PASSIVE
4024 CLR(bp
->b_flags
, (B_WASDIRTY
| B_PASSIVE
));
4025 CLR(bap
->ba_flags
, (BA_META
| BA_NOCACHE
| BA_DELAYIDLESLEEP
| BA_IO_TIER_UPGRADE
));
4027 SET_BUFATTR_IO_TIER(bap
, 0);
4029 DTRACE_IO1(done
, buf_t
, bp
);
4031 if (!ISSET(bp
->b_flags
, B_READ
) && !ISSET(bp
->b_flags
, B_RAW
))
4033 * wake up any writer's blocked
4034 * on throttle or waiting for I/O
4037 vnode_writedone(bp
->b_vp
);
4039 if (ISSET(bp
->b_flags
, (B_CALL
| B_FILTER
))) { /* if necessary, call out */
4040 void (*iodone_func
)(struct buf
*, void *) = bp
->b_iodone
;
4041 void *arg
= bp
->b_transaction
;
4042 int callout
= ISSET(bp
->b_flags
, B_CALL
);
4044 if (iodone_func
== NULL
)
4045 panic("biodone: bp @ %p has NULL b_iodone!\n", bp
);
4047 CLR(bp
->b_flags
, (B_CALL
| B_FILTER
)); /* filters and callouts are one-shot */
4048 bp
->b_iodone
= NULL
;
4049 bp
->b_transaction
= NULL
;
4052 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
4054 (*iodone_func
)(bp
, arg
);
4058 * assumes that the callback function takes
4059 * ownership of the bp and deals with releasing it if necessary
4064 * in this case the call back function is acting
4065 * strictly as a filter... it does not take
4066 * ownership of the bp and is expecting us
4067 * to finish cleaning up... this is currently used
4068 * by the HFS journaling code
4071 if (ISSET(bp
->b_flags
, B_ASYNC
)) { /* if async, release it */
4072 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
4075 } else { /* or just wakeup the buffer */
4077 * by taking the mutex, we serialize
4078 * the buf owner calling buf_biowait so that we'll
4079 * only see him in one of 2 states...
4080 * state 1: B_DONE wasn't set and he's
4082 * state 2: he's blocked trying to take the
4083 * mutex before looking at B_DONE
4084 * BL_WANTED is cleared in case anyone else
4085 * is blocked waiting for the buffer... note
4086 * that we haven't cleared B_BUSY yet, so if
4087 * they do get to run, their going to re-set
4088 * BL_WANTED and go back to sleep
4090 lck_mtx_lock_spin(buf_mtxp
);
4092 CLR(bp
->b_lflags
, BL_WANTED
);
4093 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
4095 lck_mtx_unlock(buf_mtxp
);
4100 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 387)) | DBG_FUNC_END
,
4101 (uintptr_t)bp
, (uintptr_t)bp
->b_datap
, bp
->b_flags
, 0, 0);
4105 * Obfuscate buf pointers.
4108 buf_kernel_addrperm_addr(void * addr
)
4110 if ((vm_offset_t
)addr
== 0)
4113 return ((vm_offset_t
)addr
+ buf_kernel_addrperm
);
4117 * Return a count of buffers on the "locked" queue.
4120 count_lock_queue(void)
4125 lck_mtx_lock_spin(buf_mtxp
);
4127 for (bp
= bufqueues
[BQ_LOCKED
].tqh_first
; bp
;
4128 bp
= bp
->b_freelist
.tqe_next
)
4130 lck_mtx_unlock(buf_mtxp
);
4136 * Return a count of 'busy' buffers. Used at the time of shutdown.
4137 * note: This is also called from the mach side in debug context in kdp.c
4140 count_busy_buffers(void)
4142 return buf_busycount
+ bufstats
.bufs_iobufinuse
;
4147 * Print out statistics on the current allocation of the buffer pool.
4148 * Can be enabled to print out on every ``sync'' by setting "syncprt"
4149 * in vfs_syscalls.c using sysctl.
4157 int counts
[MAXBSIZE
/CLBYTES
+1];
4158 static char *bname
[BQUEUES
] =
4159 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
4161 for (dp
= bufqueues
, i
= 0; dp
< &bufqueues
[BQUEUES
]; dp
++, i
++) {
4163 for (j
= 0; j
<= MAXBSIZE
/CLBYTES
; j
++)
4166 lck_mtx_lock(buf_mtxp
);
4168 for (bp
= dp
->tqh_first
; bp
; bp
= bp
->b_freelist
.tqe_next
) {
4169 counts
[bp
->b_bufsize
/CLBYTES
]++;
4172 lck_mtx_unlock(buf_mtxp
);
4174 printf("%s: total-%d", bname
[i
], count
);
4175 for (j
= 0; j
<= MAXBSIZE
/CLBYTES
; j
++)
4177 printf(", %d-%d", j
* CLBYTES
, counts
[j
]);
4181 #endif /* DIAGNOSTIC */
4183 #define NRESERVEDIOBUFS 128
4185 #define MNT_VIRTUALDEV_MAX_IOBUFS 16
4186 #define VIRTUALDEV_MAX_IOBUFS ((40*niobuf_headers)/100)
4189 alloc_io_buf(vnode_t vp
, int priv
)
4193 int alloc_for_virtualdev
= FALSE
;
4195 lck_mtx_lock_spin(iobuffer_mtxp
);
4198 * We subject iobuf requests for diskimages to additional restrictions.
4200 * a) A single diskimage mount cannot use up more than
4201 * MNT_VIRTUALDEV_MAX_IOBUFS. However,vm privileged (pageout) requests
4202 * are not subject to this restriction.
4203 * b) iobuf headers used by all diskimage headers by all mount
4204 * points cannot exceed VIRTUALDEV_MAX_IOBUFS.
4206 if (vp
&& ((mp
= vp
->v_mount
)) && mp
!= dead_mountp
&&
4207 mp
->mnt_kern_flag
& MNTK_VIRTUALDEV
) {
4208 alloc_for_virtualdev
= TRUE
;
4209 while ((!priv
&& mp
->mnt_iobufinuse
> MNT_VIRTUALDEV_MAX_IOBUFS
) ||
4210 bufstats
.bufs_iobufinuse_vdev
> VIRTUALDEV_MAX_IOBUFS
) {
4211 bufstats
.bufs_iobufsleeps
++;
4214 (void)msleep(&need_iobuffer
, iobuffer_mtxp
,
4215 PSPIN
| (PRIBIO
+1), (const char *)"alloc_io_buf (1)",
4220 while (((niobuf_headers
- NRESERVEDIOBUFS
< bufstats
.bufs_iobufinuse
) && !priv
) ||
4221 (bp
= iobufqueue
.tqh_first
) == NULL
) {
4222 bufstats
.bufs_iobufsleeps
++;
4225 (void)msleep(&need_iobuffer
, iobuffer_mtxp
, PSPIN
| (PRIBIO
+1),
4226 (const char *)"alloc_io_buf (2)", NULL
);
4228 TAILQ_REMOVE(&iobufqueue
, bp
, b_freelist
);
4230 bufstats
.bufs_iobufinuse
++;
4231 if (bufstats
.bufs_iobufinuse
> bufstats
.bufs_iobufmax
)
4232 bufstats
.bufs_iobufmax
= bufstats
.bufs_iobufinuse
;
4234 if (alloc_for_virtualdev
) {
4235 mp
->mnt_iobufinuse
++;
4236 bufstats
.bufs_iobufinuse_vdev
++;
4239 lck_mtx_unlock(iobuffer_mtxp
);
4242 * initialize various fields
4243 * we don't need to hold the mutex since the buffer
4244 * is now private... the vp should have a reference
4245 * on it and is not protected by this mutex in any event
4247 bp
->b_timestamp
= 0;
4252 bp
->b_lflags
= BL_BUSY
| BL_IOBUF
;
4253 if (alloc_for_virtualdev
)
4254 bp
->b_lflags
|= BL_IOBUF_VDEV
;
4255 bp
->b_redundancy_flags
= 0;
4256 bp
->b_blkno
= bp
->b_lblkno
= 0;
4258 bp
->b_owner
= current_thread();
4261 bp
->b_iodone
= NULL
;
4267 bp
->b_fsprivate
= (void *)NULL
;
4269 bzero(&bp
->b_attr
, sizeof(struct bufattr
));
4271 if (vp
&& (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
))
4272 bp
->b_dev
= vp
->v_rdev
;
4281 free_io_buf(buf_t bp
)
4283 int need_wakeup
= 0;
4284 int free_for_virtualdev
= FALSE
;
4287 /* Was this iobuf for a diskimage ? */
4288 if (bp
->b_lflags
& BL_IOBUF_VDEV
) {
4289 free_for_virtualdev
= TRUE
;
4291 mp
= bp
->b_vp
->v_mount
;
4295 * put buffer back on the head of the iobufqueue
4298 bp
->b_flags
= B_INVAL
;
4300 /* Zero out the bufattr and its flags before relinquishing this iobuf */
4301 bzero (&bp
->b_attr
, sizeof(struct bufattr
));
4303 lck_mtx_lock_spin(iobuffer_mtxp
);
4305 binsheadfree(bp
, &iobufqueue
, -1);
4307 if (need_iobuffer
) {
4309 * Wake up any processes waiting because they need an io buffer
4311 * do the wakeup after we drop the mutex... it's possible that the
4312 * wakeup will be superfluous if need_iobuffer gets set again and
4313 * another thread runs this path, but it's highly unlikely, doesn't
4314 * hurt, and it means we don't hold up I/O progress if the wakeup blocks
4315 * trying to grab a task related lock...
4320 if (bufstats
.bufs_iobufinuse
<= 0)
4321 panic("free_io_buf: bp(%p) - bufstats.bufs_iobufinuse < 0", bp
);
4323 bufstats
.bufs_iobufinuse
--;
4325 if (free_for_virtualdev
) {
4326 bufstats
.bufs_iobufinuse_vdev
--;
4327 if (mp
&& mp
!= dead_mountp
)
4328 mp
->mnt_iobufinuse
--;
4331 lck_mtx_unlock(iobuffer_mtxp
);
4334 wakeup(&need_iobuffer
);
4341 lck_mtx_lock_spin(buf_mtxp
);
4345 buf_list_unlock(void)
4347 lck_mtx_unlock(buf_mtxp
);
4351 * If getnewbuf() calls bcleanbuf() on the same thread
4352 * there is a potential for stack overrun and deadlocks.
4353 * So we always handoff the work to a worker thread for completion
4358 bcleanbuf_thread_init(void)
4360 thread_t thread
= THREAD_NULL
;
4362 /* create worker thread */
4363 kernel_thread_start((thread_continue_t
)bcleanbuf_thread
, NULL
, &thread
);
4364 thread_deallocate(thread
);
4367 typedef int (*bcleanbufcontinuation
)(int);
4369 __attribute__((noreturn
))
4371 bcleanbuf_thread(void)
4378 lck_mtx_lock_spin(buf_mtxp
);
4380 while ( (bp
= TAILQ_FIRST(&bufqueues
[BQ_LAUNDRY
])) == NULL
) {
4381 (void)msleep0(&bufqueues
[BQ_LAUNDRY
], buf_mtxp
, PRIBIO
|PDROP
, "blaundry", 0, (bcleanbufcontinuation
)bcleanbuf_thread
);
4385 * Remove from the queue
4387 bremfree_locked(bp
);
4390 * Buffer is no longer on any free list
4392 SET(bp
->b_lflags
, BL_BUSY
);
4396 bp
->b_owner
= current_thread();
4400 lck_mtx_unlock(buf_mtxp
);
4404 error
= bawrite_internal(bp
, 0);
4407 bp
->b_whichq
= BQ_LAUNDRY
;
4408 bp
->b_timestamp
= buf_timestamp();
4410 lck_mtx_lock_spin(buf_mtxp
);
4412 binstailfree(bp
, &bufqueues
[BQ_LAUNDRY
], BQ_LAUNDRY
);
4415 /* we never leave a busy page on the laundry queue */
4416 CLR(bp
->b_lflags
, BL_BUSY
);
4419 bp
->b_owner
= current_thread();
4423 lck_mtx_unlock(buf_mtxp
);
4425 if (loopcnt
> MAXLAUNDRY
) {
4427 * bawrite_internal() can return errors if we're throttled. If we've
4428 * done several I/Os and failed, give the system some time to unthrottle
4431 (void)tsleep((void *)&bufqueues
[BQ_LAUNDRY
], PRIBIO
, "blaundry", 1);
4434 /* give other threads a chance to run */
4435 (void)thread_block(THREAD_CONTINUE_NULL
);
4444 brecover_data(buf_t bp
)
4448 upl_page_info_t
*pl
;
4450 vnode_t vp
= bp
->b_vp
;
4454 if ( !UBCINFOEXISTS(vp
) || bp
->b_bufsize
== 0)
4457 upl_flags
= UPL_PRECIOUS
;
4458 if (! (buf_flags(bp
) & B_READ
)) {
4460 * "write" operation: let the UPL subsystem know
4461 * that we intend to modify the buffer cache pages we're
4464 upl_flags
|= UPL_WILL_MODIFY
;
4467 kret
= ubc_create_upl(vp
,
4468 ubc_blktooff(vp
, bp
->b_lblkno
),
4473 if (kret
!= KERN_SUCCESS
)
4474 panic("Failed to create UPL");
4476 for (upl_offset
= 0; upl_offset
< bp
->b_bufsize
; upl_offset
+= PAGE_SIZE
) {
4478 if (!upl_valid_page(pl
, upl_offset
/ PAGE_SIZE
) || !upl_dirty_page(pl
, upl_offset
/ PAGE_SIZE
)) {
4479 ubc_upl_abort(upl
, 0);
4485 kret
= ubc_upl_map(upl
, (vm_offset_t
*)&(bp
->b_datap
));
4487 if (kret
!= KERN_SUCCESS
)
4488 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
4493 SET(bp
->b_flags
, B_INVAL
);
4500 buffer_cache_gc(int all
)
4503 boolean_t did_large_zfree
= FALSE
;
4504 boolean_t need_wakeup
= FALSE
;
4505 int now
= buf_timestamp();
4507 struct bqueues privq
;
4508 int thresh_hold
= BUF_STALE_THRESHHOLD
;
4513 * We only care about metadata (incore storage comes from zalloc()).
4514 * Unless "all" is set (used to evict meta data buffers in preparation
4515 * for deep sleep), we only evict up to BUF_MAX_GC_BATCH_SIZE buffers
4516 * that have not been accessed in the last BUF_STALE_THRESHOLD seconds.
4517 * BUF_MAX_GC_BATCH_SIZE controls both the hold time of the global lock
4518 * "buf_mtxp" and the length of time we spend compute bound in the GC
4519 * thread which calls this function
4521 lck_mtx_lock(buf_mtxp
);
4526 need_wakeup
= FALSE
;
4528 while (((bp
= TAILQ_FIRST(&bufqueues
[BQ_META
]))) &&
4529 (now
> bp
->b_timestamp
) &&
4530 (now
- bp
->b_timestamp
> thresh_hold
) &&
4531 (found
< BUF_MAX_GC_BATCH_SIZE
)) {
4533 /* Remove from free list */
4534 bremfree_locked(bp
);
4538 bp
->b_owner
= current_thread();
4542 /* If dirty, move to laundry queue and remember to do wakeup */
4543 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
4544 SET(bp
->b_lflags
, BL_WANTDEALLOC
);
4553 * Mark busy and put on private list. We could technically get
4554 * away without setting BL_BUSY here.
4556 SET(bp
->b_lflags
, BL_BUSY
);
4560 * Remove from hash and dissociate from vp.
4567 TAILQ_INSERT_TAIL(&privq
, bp
, b_freelist
);
4574 /* Drop lock for batch processing */
4575 lck_mtx_unlock(buf_mtxp
);
4577 /* Wakeup and yield for laundry if need be */
4579 wakeup(&bufqueues
[BQ_LAUNDRY
]);
4580 (void)thread_block(THREAD_CONTINUE_NULL
);
4583 /* Clean up every buffer on private list */
4584 TAILQ_FOREACH(bp
, &privq
, b_freelist
) {
4585 /* Take note if we've definitely freed at least a page to a zone */
4586 if ((ISSET(bp
->b_flags
, B_ZALLOC
)) && (buf_size(bp
) >= PAGE_SIZE
)) {
4587 did_large_zfree
= TRUE
;
4590 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
4593 buf_free_meta_store(bp
);
4595 /* Release credentials */
4596 buf_release_credentials(bp
);
4598 /* Prepare for moving to empty queue */
4599 CLR(bp
->b_flags
, (B_META
| B_ZALLOC
| B_DELWRI
| B_LOCKED
4600 | B_AGE
| B_ASYNC
| B_NOCACHE
| B_FUA
));
4601 bp
->b_whichq
= BQ_EMPTY
;
4604 lck_mtx_lock(buf_mtxp
);
4606 /* Back under lock, move them all to invalid hash and clear busy */
4607 TAILQ_FOREACH(bp
, &privq
, b_freelist
) {
4608 binshash(bp
, &invalhash
);
4609 CLR(bp
->b_lflags
, BL_BUSY
);
4613 if (bp
->b_owner
!= current_thread()) {
4614 panic("Buffer stolen from buffer_cache_gc()");
4616 bp
->b_owner
= current_thread();
4621 /* And do a big bulk move to the empty queue */
4622 TAILQ_CONCAT(&bufqueues
[BQ_EMPTY
], &privq
, b_freelist
);
4624 } while (all
&& (found
== BUF_MAX_GC_BATCH_SIZE
));
4626 lck_mtx_unlock(buf_mtxp
);
4628 return did_large_zfree
;
4641 bp_cmp(void *a
, void *b
)
4643 buf_t
*bp_a
= *(buf_t
**)a
,
4644 *bp_b
= *(buf_t
**)b
;
4647 // don't have to worry about negative block
4648 // numbers so this is ok to do.
4650 res
= (bp_a
->b_blkno
- bp_b
->b_blkno
);
4657 bflushq(int whichq
, mount_t mp
)
4661 int total_writes
= 0;
4662 static buf_t flush_table
[NFLUSH
];
4664 if (whichq
< 0 || whichq
>= BQUEUES
) {
4669 lck_mtx_lock(buf_mtxp
);
4671 bp
= TAILQ_FIRST(&bufqueues
[whichq
]);
4673 for (buf_count
= 0; bp
; bp
= next
) {
4674 next
= bp
->b_freelist
.tqe_next
;
4676 if (bp
->b_vp
== NULL
|| bp
->b_vp
->v_mount
!= mp
) {
4680 if (ISSET(bp
->b_flags
, B_DELWRI
) && !ISSET(bp
->b_lflags
, BL_BUSY
)) {
4682 bremfree_locked(bp
);
4684 bp
->b_owner
= current_thread();
4687 SET(bp
->b_lflags
, BL_BUSY
);
4690 flush_table
[buf_count
] = bp
;
4694 if (buf_count
>= NFLUSH
) {
4695 lck_mtx_unlock(buf_mtxp
);
4697 qsort(flush_table
, buf_count
, sizeof(struct buf
*), bp_cmp
);
4699 for (i
= 0; i
< buf_count
; i
++) {
4700 buf_bawrite(flush_table
[i
]);
4706 lck_mtx_unlock(buf_mtxp
);
4708 if (buf_count
> 0) {
4709 qsort(flush_table
, buf_count
, sizeof(struct buf
*), bp_cmp
);
4711 for (i
= 0; i
< buf_count
; i
++) {
4712 buf_bawrite(flush_table
[i
]);
4716 return (total_writes
);