2 * Copyright (c) 2000-2014 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() */
99 #include <mach/mach_types.h>
100 #include <mach/memory_object_types.h>
101 #include <kern/sched_prim.h> /* thread_block() */
103 #include <vm/vm_kern.h>
104 #include <vm/vm_pageout.h>
106 #include <sys/kdebug.h>
108 #include <libkern/OSAtomic.h>
109 #include <libkern/OSDebug.h>
110 #include <sys/ubc_internal.h>
113 #include <sys/cprotect.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 __private_extern__
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
);
370 buf_setcpaddr(buf_t bp
, struct cprotect
*entry
) {
371 bp
->b_attr
.ba_cpentry
= entry
;
375 buf_setcpoff (buf_t bp
, uint64_t foffset
) {
376 bp
->b_attr
.ba_cp_file_off
= foffset
;
380 bufattr_cpaddr(bufattr_t bap
) {
381 return (bap
->ba_cpentry
);
385 bufattr_cpoff(bufattr_t bap
) {
386 return (bap
->ba_cp_file_off
);
390 bufattr_setcpaddr(bufattr_t bap
, void *cp_entry_addr
) {
391 bap
->ba_cpentry
= cp_entry_addr
;
395 bufattr_setcpoff(bufattr_t bap
, uint64_t foffset
) {
396 bap
->ba_cp_file_off
= foffset
;
401 bufattr_cpaddr(bufattr_t bap __unused
) {
406 bufattr_cpoff(bufattr_t bap __unused
) {
411 bufattr_setcpaddr(bufattr_t bap __unused
, void *cp_entry_addr __unused
) {
415 bufattr_setcpoff(__unused bufattr_t bap
, __unused
uint64_t foffset
) {
418 #endif /* CONFIG_PROTECT */
423 MALLOC(bap
, bufattr_t
, sizeof(struct bufattr
), M_TEMP
, M_WAITOK
);
427 bzero(bap
, sizeof(struct bufattr
));
432 bufattr_free(bufattr_t bap
) {
438 bufattr_dup(bufattr_t bap
) {
439 bufattr_t new_bufattr
;
440 MALLOC(new_bufattr
, bufattr_t
, sizeof(struct bufattr
), M_TEMP
, M_WAITOK
);
441 if (new_bufattr
== NULL
)
444 /* Copy the provided one into the new copy */
445 memcpy (new_bufattr
, bap
, sizeof(struct bufattr
));
450 bufattr_rawencrypted(bufattr_t bap
) {
451 if ( (bap
->ba_flags
& BA_RAW_ENCRYPTED_IO
) )
457 bufattr_throttled(bufattr_t bap
) {
458 return (GET_BUFATTR_IO_TIER(bap
));
462 bufattr_passive(bufattr_t bap
) {
463 if ( (bap
->ba_flags
& BA_PASSIVE
) )
469 bufattr_nocache(bufattr_t bap
) {
470 if ( (bap
->ba_flags
& BA_NOCACHE
) )
476 bufattr_meta(bufattr_t bap
) {
477 if ( (bap
->ba_flags
& BA_META
) )
483 bufattr_markmeta(bufattr_t bap
) {
484 SET(bap
->ba_flags
, BA_META
);
488 bufattr_delayidlesleep(bufattr_t bap
)
490 if ( (bap
->ba_flags
& BA_DELAYIDLESLEEP
) )
501 buf_markstatic(buf_t bp __unused
) {
502 SET(bp
->b_flags
, B_STATICCONTENT
);
506 buf_static(buf_t bp
) {
507 if ( (bp
->b_flags
& B_STATICCONTENT
) )
513 bufattr_markgreedymode(bufattr_t bap
) {
514 SET(bap
->ba_flags
, BA_GREEDY_MODE
);
518 bufattr_greedymode(bufattr_t bap
) {
519 if ( (bap
->ba_flags
& BA_GREEDY_MODE
) )
525 bufattr_markisochronous(bufattr_t bap
) {
526 SET(bap
->ba_flags
, BA_ISOCHRONOUS
);
530 bufattr_isochronous(bufattr_t bap
) {
531 if ( (bap
->ba_flags
& BA_ISOCHRONOUS
) )
537 bufattr_markquickcomplete(bufattr_t bap
) {
538 SET(bap
->ba_flags
, BA_QUICK_COMPLETE
);
542 bufattr_quickcomplete(bufattr_t bap
) {
543 if ( (bap
->ba_flags
& BA_QUICK_COMPLETE
) )
549 buf_error(buf_t bp
) {
551 return (bp
->b_error
);
555 buf_seterror(buf_t bp
, errno_t error
) {
557 if ((bp
->b_error
= error
))
558 SET(bp
->b_flags
, B_ERROR
);
560 CLR(bp
->b_flags
, B_ERROR
);
564 buf_setflags(buf_t bp
, int32_t flags
) {
566 SET(bp
->b_flags
, (flags
& BUF_X_WRFLAGS
));
570 buf_clearflags(buf_t bp
, int32_t flags
) {
572 CLR(bp
->b_flags
, (flags
& BUF_X_WRFLAGS
));
576 buf_flags(buf_t bp
) {
578 return ((bp
->b_flags
& BUF_X_RDFLAGS
));
582 buf_reset(buf_t bp
, int32_t io_flags
) {
584 CLR(bp
->b_flags
, (B_READ
| B_WRITE
| B_ERROR
| B_DONE
| B_INVAL
| B_ASYNC
| B_NOCACHE
| B_FUA
));
585 SET(bp
->b_flags
, (io_flags
& (B_ASYNC
| B_READ
| B_WRITE
| B_NOCACHE
)));
591 buf_count(buf_t bp
) {
593 return (bp
->b_bcount
);
597 buf_setcount(buf_t bp
, uint32_t bcount
) {
599 bp
->b_bcount
= bcount
;
605 return (bp
->b_bufsize
);
609 buf_setsize(buf_t bp
, uint32_t bufsize
) {
611 bp
->b_bufsize
= bufsize
;
615 buf_resid(buf_t bp
) {
617 return (bp
->b_resid
);
621 buf_setresid(buf_t bp
, uint32_t resid
) {
627 buf_dirtyoff(buf_t bp
) {
629 return (bp
->b_dirtyoff
);
633 buf_dirtyend(buf_t bp
) {
635 return (bp
->b_dirtyend
);
639 buf_setdirtyoff(buf_t bp
, uint32_t dirtyoff
) {
641 bp
->b_dirtyoff
= dirtyoff
;
645 buf_setdirtyend(buf_t bp
, uint32_t dirtyend
) {
647 bp
->b_dirtyend
= dirtyend
;
651 buf_dataptr(buf_t bp
) {
653 return (bp
->b_datap
);
657 buf_setdataptr(buf_t bp
, uintptr_t data
) {
663 buf_vnode(buf_t bp
) {
669 buf_setvnode(buf_t bp
, vnode_t vp
) {
676 buf_callback(buf_t bp
)
678 if ( !(bp
->b_flags
& B_CALL
) )
679 return ((void *) NULL
);
681 return ((void *)bp
->b_iodone
);
686 buf_setcallback(buf_t bp
, void (*callback
)(buf_t
, void *), void *transaction
)
689 bp
->b_flags
|= (B_CALL
| B_ASYNC
);
691 bp
->b_flags
&= ~B_CALL
;
692 bp
->b_transaction
= transaction
;
693 bp
->b_iodone
= callback
;
699 buf_setupl(buf_t bp
, upl_t upl
, uint32_t offset
)
702 if ( !(bp
->b_lflags
& BL_IOBUF
) )
706 bp
->b_flags
|= B_CLUSTER
;
708 bp
->b_flags
&= ~B_CLUSTER
;
710 bp
->b_uploffset
= offset
;
716 buf_clone(buf_t bp
, int io_offset
, int io_size
, void (*iodone
)(buf_t
, void *), void *arg
)
720 if (io_offset
< 0 || io_size
< 0)
723 if ((unsigned)(io_offset
+ io_size
) > (unsigned)bp
->b_bcount
)
726 if (bp
->b_flags
& B_CLUSTER
) {
727 if (io_offset
&& ((bp
->b_uploffset
+ io_offset
) & PAGE_MASK
))
730 if (((bp
->b_uploffset
+ io_offset
+ io_size
) & PAGE_MASK
) && ((io_offset
+ io_size
) < bp
->b_bcount
))
733 io_bp
= alloc_io_buf(bp
->b_vp
, 0);
735 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
);
738 io_bp
->b_transaction
= arg
;
739 io_bp
->b_iodone
= iodone
;
740 io_bp
->b_flags
|= B_CALL
;
742 if (bp
->b_flags
& B_CLUSTER
) {
743 io_bp
->b_upl
= bp
->b_upl
;
744 io_bp
->b_uploffset
= bp
->b_uploffset
+ io_offset
;
746 io_bp
->b_datap
= (uintptr_t)(((char *)bp
->b_datap
) + io_offset
);
748 io_bp
->b_bcount
= io_size
;
757 if (bp
->b_lflags
& BL_SHADOW
)
764 buf_create_shadow_priv(buf_t bp
, boolean_t force_copy
, uintptr_t external_storage
, void (*iodone
)(buf_t
, void *), void *arg
)
766 return (buf_create_shadow_internal(bp
, force_copy
, external_storage
, iodone
, arg
, 1));
770 buf_create_shadow(buf_t bp
, boolean_t force_copy
, uintptr_t external_storage
, void (*iodone
)(buf_t
, void *), void *arg
)
772 return (buf_create_shadow_internal(bp
, force_copy
, external_storage
, iodone
, arg
, 0));
777 buf_create_shadow_internal(buf_t bp
, boolean_t force_copy
, uintptr_t external_storage
, void (*iodone
)(buf_t
, void *), void *arg
, int priv
)
781 KERNEL_DEBUG(0xbbbbc000 | DBG_FUNC_START
, bp
, 0, 0, 0, 0);
783 if ( !(bp
->b_flags
& B_META
) || (bp
->b_lflags
& BL_IOBUF
)) {
785 KERNEL_DEBUG(0xbbbbc000 | DBG_FUNC_END
, bp
, 0, 0, 0, 0);
788 #ifdef BUF_MAKE_PRIVATE
789 if (bp
->b_shadow_ref
&& bp
->b_data_ref
== 0 && external_storage
== 0)
790 panic("buf_create_shadow: %p is in the private state (%d, %d)", bp
, bp
->b_shadow_ref
, bp
->b_data_ref
);
792 io_bp
= alloc_io_buf(bp
->b_vp
, priv
);
794 io_bp
->b_flags
= bp
->b_flags
& (B_META
| B_ZALLOC
| B_ASYNC
| B_READ
| B_FUA
);
795 io_bp
->b_blkno
= bp
->b_blkno
;
796 io_bp
->b_lblkno
= bp
->b_lblkno
;
799 io_bp
->b_transaction
= arg
;
800 io_bp
->b_iodone
= iodone
;
801 io_bp
->b_flags
|= B_CALL
;
803 if (force_copy
== FALSE
) {
804 io_bp
->b_bcount
= bp
->b_bcount
;
805 io_bp
->b_bufsize
= bp
->b_bufsize
;
807 if (external_storage
) {
808 io_bp
->b_datap
= external_storage
;
809 #ifdef BUF_MAKE_PRIVATE
810 io_bp
->b_data_store
= NULL
;
813 io_bp
->b_datap
= bp
->b_datap
;
814 #ifdef BUF_MAKE_PRIVATE
815 io_bp
->b_data_store
= bp
;
818 *(buf_t
*)(&io_bp
->b_orig
) = bp
;
820 lck_mtx_lock_spin(buf_mtxp
);
822 io_bp
->b_lflags
|= BL_SHADOW
;
823 io_bp
->b_shadow
= bp
->b_shadow
;
824 bp
->b_shadow
= io_bp
;
827 #ifdef BUF_MAKE_PRIVATE
828 if (external_storage
)
829 io_bp
->b_lflags
|= BL_EXTERNAL
;
833 lck_mtx_unlock(buf_mtxp
);
835 if (external_storage
) {
836 #ifdef BUF_MAKE_PRIVATE
837 io_bp
->b_lflags
|= BL_EXTERNAL
;
839 io_bp
->b_bcount
= bp
->b_bcount
;
840 io_bp
->b_bufsize
= bp
->b_bufsize
;
841 io_bp
->b_datap
= external_storage
;
843 allocbuf(io_bp
, bp
->b_bcount
);
845 io_bp
->b_lflags
|= BL_IOBUF_ALLOC
;
847 bcopy((caddr_t
)bp
->b_datap
, (caddr_t
)io_bp
->b_datap
, bp
->b_bcount
);
849 #ifdef BUF_MAKE_PRIVATE
850 io_bp
->b_data_store
= NULL
;
853 KERNEL_DEBUG(0xbbbbc000 | DBG_FUNC_END
, bp
, bp
->b_shadow_ref
, 0, io_bp
, 0);
859 #ifdef BUF_MAKE_PRIVATE
861 buf_make_private(buf_t bp
)
867 KERNEL_DEBUG(0xbbbbc004 | DBG_FUNC_START
, bp
, bp
->b_shadow_ref
, 0, 0, 0);
869 if (bp
->b_shadow_ref
== 0 || bp
->b_data_ref
== 0 || ISSET(bp
->b_lflags
, BL_SHADOW
)) {
871 KERNEL_DEBUG(0xbbbbc004 | DBG_FUNC_END
, bp
, bp
->b_shadow_ref
, 0, EINVAL
, 0);
874 my_buf
.b_flags
= B_META
;
875 my_buf
.b_datap
= (uintptr_t)NULL
;
876 allocbuf(&my_buf
, bp
->b_bcount
);
878 bcopy((caddr_t
)bp
->b_datap
, (caddr_t
)my_buf
.b_datap
, bp
->b_bcount
);
880 lck_mtx_lock_spin(buf_mtxp
);
882 for (t_bp
= bp
->b_shadow
; t_bp
; t_bp
= t_bp
->b_shadow
) {
883 if ( !ISSET(bp
->b_lflags
, BL_EXTERNAL
))
888 if (ds_bp
== NULL
&& bp
->b_data_ref
)
889 panic("buf_make_private: b_data_ref != 0 && ds_bp == NULL");
891 if (ds_bp
&& (bp
->b_data_ref
== 0 || bp
->b_shadow_ref
== 0))
892 panic("buf_make_private: ref_count == 0 && ds_bp != NULL");
895 lck_mtx_unlock(buf_mtxp
);
897 buf_free_meta_store(&my_buf
);
899 KERNEL_DEBUG(0xbbbbc004 | DBG_FUNC_END
, bp
, bp
->b_shadow_ref
, 0, EINVAL
, 0);
902 for (t_bp
= bp
->b_shadow
; t_bp
; t_bp
= t_bp
->b_shadow
) {
903 if ( !ISSET(t_bp
->b_lflags
, BL_EXTERNAL
))
904 t_bp
->b_data_store
= ds_bp
;
906 ds_bp
->b_data_ref
= bp
->b_data_ref
;
909 bp
->b_datap
= my_buf
.b_datap
;
911 lck_mtx_unlock(buf_mtxp
);
913 KERNEL_DEBUG(0xbbbbc004 | DBG_FUNC_END
, bp
, bp
->b_shadow_ref
, 0, 0, 0);
920 buf_setfilter(buf_t bp
, void (*filter
)(buf_t
, void *), void *transaction
,
921 void (**old_iodone
)(buf_t
, void *), void **old_transaction
)
924 *old_iodone
= bp
->b_iodone
;
926 *old_transaction
= bp
->b_transaction
;
928 bp
->b_transaction
= transaction
;
929 bp
->b_iodone
= filter
;
931 bp
->b_flags
|= B_FILTER
;
933 bp
->b_flags
&= ~B_FILTER
;
938 buf_blkno(buf_t bp
) {
940 return (bp
->b_blkno
);
944 buf_lblkno(buf_t bp
) {
946 return (bp
->b_lblkno
);
950 buf_setblkno(buf_t bp
, daddr64_t blkno
) {
956 buf_setlblkno(buf_t bp
, daddr64_t lblkno
) {
958 bp
->b_lblkno
= lblkno
;
962 buf_device(buf_t bp
) {
968 buf_setdevice(buf_t bp
, vnode_t vp
) {
970 if ((vp
->v_type
!= VBLK
) && (vp
->v_type
!= VCHR
))
972 bp
->b_dev
= vp
->v_rdev
;
979 buf_drvdata(buf_t bp
) {
981 return (bp
->b_drvdata
);
985 buf_setdrvdata(buf_t bp
, void *drvdata
) {
987 bp
->b_drvdata
= drvdata
;
991 buf_fsprivate(buf_t bp
) {
993 return (bp
->b_fsprivate
);
997 buf_setfsprivate(buf_t bp
, void *fsprivate
) {
999 bp
->b_fsprivate
= fsprivate
;
1003 buf_rcred(buf_t bp
) {
1005 return (bp
->b_rcred
);
1009 buf_wcred(buf_t bp
) {
1011 return (bp
->b_wcred
);
1021 buf_uploffset(buf_t bp
) {
1023 return ((uint32_t)(bp
->b_uploffset
));
1027 buf_proc(buf_t bp
) {
1029 return (bp
->b_proc
);
1034 buf_map(buf_t bp
, caddr_t
*io_addr
)
1040 if ( !(bp
->b_flags
& B_CLUSTER
)) {
1041 *io_addr
= (caddr_t
)bp
->b_datap
;
1044 real_bp
= (buf_t
)(bp
->b_real_bp
);
1046 if (real_bp
&& real_bp
->b_datap
) {
1048 * b_real_bp is only valid if B_CLUSTER is SET
1049 * if it's non-zero, than someone did a cluster_bp call
1050 * if the backing physical pages were already mapped
1051 * in before the call to cluster_bp (non-zero b_datap),
1052 * than we just use that mapping
1054 *io_addr
= (caddr_t
)real_bp
->b_datap
;
1057 kret
= ubc_upl_map(bp
->b_upl
, &vaddr
); /* Map it in */
1059 if (kret
!= KERN_SUCCESS
) {
1064 vaddr
+= bp
->b_uploffset
;
1066 *io_addr
= (caddr_t
)vaddr
;
1077 if ( !(bp
->b_flags
& B_CLUSTER
))
1080 * see buf_map for the explanation
1082 real_bp
= (buf_t
)(bp
->b_real_bp
);
1084 if (real_bp
&& real_bp
->b_datap
)
1087 if ((bp
->b_lflags
& BL_IOBUF
) &&
1088 ((bp
->b_flags
& (B_PAGEIO
| B_READ
)) != (B_PAGEIO
| B_READ
))) {
1090 * ignore pageins... the 'right' thing will
1091 * happen due to the way we handle speculative
1094 * when we commit these pages, we'll hit
1095 * it with UPL_COMMIT_INACTIVE which
1096 * will clear the reference bit that got
1097 * turned on when we touched the mapping
1099 bp
->b_flags
|= B_AGE
;
1101 kret
= ubc_upl_unmap(bp
->b_upl
);
1103 if (kret
!= KERN_SUCCESS
)
1110 buf_clear(buf_t bp
) {
1113 if (buf_map(bp
, &baddr
) == 0) {
1114 bzero(baddr
, bp
->b_bcount
);
1121 * Read or write a buffer that is not contiguous on disk.
1122 * buffer is marked done/error at the conclusion
1125 buf_strategy_fragmented(vnode_t devvp
, buf_t bp
, off_t f_offset
, size_t contig_bytes
)
1127 vnode_t vp
= buf_vnode(bp
);
1128 buf_t io_bp
; /* For reading or writing a single block */
1131 size_t io_contig_bytes
;
1137 * save our starting point... the bp was already mapped
1138 * in buf_strategy before we got called
1139 * no sense doing it again.
1141 io_blkno
= bp
->b_blkno
;
1143 * Make sure we redo this mapping for the next I/O
1144 * i.e. this can never be a 'permanent' mapping
1146 bp
->b_blkno
= bp
->b_lblkno
;
1149 * Get an io buffer to do the deblocking
1151 io_bp
= alloc_io_buf(devvp
, 0);
1153 io_bp
->b_lblkno
= bp
->b_lblkno
;
1154 io_bp
->b_datap
= bp
->b_datap
;
1155 io_resid
= bp
->b_bcount
;
1156 io_direction
= bp
->b_flags
& B_READ
;
1157 io_contig_bytes
= contig_bytes
;
1159 if (bp
->b_flags
& B_READ
)
1160 bmap_flags
= VNODE_READ
;
1162 bmap_flags
= VNODE_WRITE
;
1167 * this is unexepected, but we'll allow for it
1169 bzero((caddr_t
)io_bp
->b_datap
, (int)io_contig_bytes
);
1171 io_bp
->b_bcount
= io_contig_bytes
;
1172 io_bp
->b_bufsize
= io_contig_bytes
;
1173 io_bp
->b_resid
= io_contig_bytes
;
1174 io_bp
->b_blkno
= io_blkno
;
1176 buf_reset(io_bp
, io_direction
);
1179 * Call the device to do the I/O and wait for it. Make sure the appropriate party is charged for write
1182 if (!ISSET(bp
->b_flags
, B_READ
))
1183 OSAddAtomic(1, &devvp
->v_numoutput
);
1185 if ((error
= VNOP_STRATEGY(io_bp
)))
1187 if ((error
= (int)buf_biowait(io_bp
)))
1189 if (io_bp
->b_resid
) {
1190 io_resid
-= (io_contig_bytes
- io_bp
->b_resid
);
1194 if ((io_resid
-= io_contig_bytes
) == 0)
1196 f_offset
+= io_contig_bytes
;
1197 io_bp
->b_datap
+= io_contig_bytes
;
1200 * Map the current position to a physical block number
1202 if ((error
= VNOP_BLOCKMAP(vp
, f_offset
, io_resid
, &io_blkno
, &io_contig_bytes
, NULL
, bmap_flags
, NULL
)))
1208 buf_seterror(bp
, error
);
1209 bp
->b_resid
= io_resid
;
1211 * This I/O is now complete
1220 * struct vnop_strategy_args {
1225 buf_strategy(vnode_t devvp
, void *ap
)
1227 buf_t bp
= ((struct vnop_strategy_args
*)ap
)->a_bp
;
1228 vnode_t vp
= bp
->b_vp
;
1232 int dtrace_io_start_flag
= 0; /* We only want to trip the io:::start
1233 * probe once, with the true physical
1234 * block in place (b_blkno)
1239 if (vp
== NULL
|| vp
->v_type
== VCHR
|| vp
->v_type
== VBLK
)
1240 panic("buf_strategy: b_vp == NULL || vtype == VCHR | VBLK\n");
1242 * associate the physical device with
1243 * with this buf_t even if we don't
1244 * end up issuing the I/O...
1246 bp
->b_dev
= devvp
->v_rdev
;
1248 if (bp
->b_flags
& B_READ
)
1249 bmap_flags
= VNODE_READ
;
1251 bmap_flags
= VNODE_WRITE
;
1253 if ( !(bp
->b_flags
& B_CLUSTER
)) {
1255 if ( (bp
->b_upl
) ) {
1257 * we have a UPL associated with this bp
1258 * go through cluster_bp which knows how
1259 * to deal with filesystem block sizes
1260 * that aren't equal to the page size
1262 DTRACE_IO1(start
, buf_t
, bp
);
1263 return (cluster_bp(bp
));
1265 if (bp
->b_blkno
== bp
->b_lblkno
) {
1267 size_t contig_bytes
;
1269 if ((error
= VNOP_BLKTOOFF(vp
, bp
->b_lblkno
, &f_offset
))) {
1270 DTRACE_IO1(start
, buf_t
, bp
);
1271 buf_seterror(bp
, error
);
1277 if ((error
= VNOP_BLOCKMAP(vp
, f_offset
, bp
->b_bcount
, &bp
->b_blkno
, &contig_bytes
, NULL
, bmap_flags
, NULL
))) {
1278 DTRACE_IO1(start
, buf_t
, bp
);
1279 buf_seterror(bp
, error
);
1285 DTRACE_IO1(start
, buf_t
, bp
);
1287 dtrace_io_start_flag
= 1;
1288 #endif /* CONFIG_DTRACE */
1290 if ((bp
->b_blkno
== -1) || (contig_bytes
== 0)) {
1291 /* Set block number to force biodone later */
1295 else if ((long)contig_bytes
< bp
->b_bcount
) {
1296 return (buf_strategy_fragmented(devvp
, bp
, f_offset
, contig_bytes
));
1301 if (dtrace_io_start_flag
== 0) {
1302 DTRACE_IO1(start
, buf_t
, bp
);
1303 dtrace_io_start_flag
= 1;
1305 #endif /* CONFIG_DTRACE */
1307 if (bp
->b_blkno
== -1) {
1314 if (dtrace_io_start_flag
== 0)
1315 DTRACE_IO1(start
, buf_t
, bp
);
1316 #endif /* CONFIG_DTRACE */
1319 /* Capture f_offset in the bufattr*/
1320 if (bp
->b_attr
.ba_cpentry
!= 0) {
1321 /* No need to go here for older EAs */
1322 if(bp
->b_attr
.ba_cpentry
->cp_flags
& CP_OFF_IV_ENABLED
) {
1324 if ((error
= VNOP_BLKTOOFF(bp
->b_vp
, bp
->b_lblkno
, &f_offset
)))
1328 * Attach the file offset to this buffer. The
1329 * bufattr attributes will be passed down the stack
1330 * until they reach IOFlashStorage. IOFlashStorage
1331 * will retain the offset in a local variable when it
1332 * issues its I/Os to the NAND controller.
1334 * Note that LwVM may end up splitting this I/O
1335 * into sub-I/Os if it crosses a chunk boundary. In this
1336 * case, LwVM will update this field when it dispatches
1337 * each I/O to IOFlashStorage. But from our perspective
1338 * we have only issued a single I/O.
1340 bufattr_setcpoff (&(bp
->b_attr
), (u_int64_t
)f_offset
);
1341 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);
1347 * we can issue the I/O because...
1348 * either B_CLUSTER is set which
1349 * means that the I/O is properly set
1350 * up to be a multiple of the page size, or
1351 * we were able to successfully set up the
1352 * physical block mapping
1354 error
= VOCALL(devvp
->v_op
, VOFFSET(vnop_strategy
), ap
);
1355 DTRACE_FSINFO(strategy
, vnode_t
, vp
);
1362 buf_alloc(vnode_t vp
)
1364 return(alloc_io_buf(vp
, 0));
1368 buf_free(buf_t bp
) {
1375 * iterate buffers for the specified vp.
1376 * if BUF_SCAN_DIRTY is set, do the dirty list
1377 * if BUF_SCAN_CLEAN is set, do the clean list
1378 * if neither flag is set, default to BUF_SCAN_DIRTY
1379 * if BUF_NOTIFY_BUSY is set, call the callout function using a NULL bp for busy pages
1382 struct buf_iterate_info_t
{
1384 struct buflists
*listhead
;
1388 buf_iterate(vnode_t vp
, int (*callout
)(buf_t
, void *), int flags
, void *arg
)
1392 struct buflists local_iterblkhd
;
1393 int lock_flags
= BAC_NOWAIT
| BAC_REMOVE
;
1394 int notify_busy
= flags
& BUF_NOTIFY_BUSY
;
1395 struct buf_iterate_info_t list
[2];
1398 if (flags
& BUF_SKIP_LOCKED
)
1399 lock_flags
|= BAC_SKIP_LOCKED
;
1400 if (flags
& BUF_SKIP_NONLOCKED
)
1401 lock_flags
|= BAC_SKIP_NONLOCKED
;
1403 if ( !(flags
& (BUF_SCAN_DIRTY
| BUF_SCAN_CLEAN
)))
1404 flags
|= BUF_SCAN_DIRTY
;
1408 if (flags
& BUF_SCAN_DIRTY
) {
1409 list
[num_lists
].flag
= VBI_DIRTY
;
1410 list
[num_lists
].listhead
= &vp
->v_dirtyblkhd
;
1413 if (flags
& BUF_SCAN_CLEAN
) {
1414 list
[num_lists
].flag
= VBI_CLEAN
;
1415 list
[num_lists
].listhead
= &vp
->v_cleanblkhd
;
1419 for (i
= 0; i
< num_lists
; i
++) {
1420 lck_mtx_lock(buf_mtxp
);
1422 if (buf_iterprepare(vp
, &local_iterblkhd
, list
[i
].flag
)) {
1423 lck_mtx_unlock(buf_mtxp
);
1426 while (!LIST_EMPTY(&local_iterblkhd
)) {
1427 bp
= LIST_FIRST(&local_iterblkhd
);
1428 LIST_REMOVE(bp
, b_vnbufs
);
1429 LIST_INSERT_HEAD(list
[i
].listhead
, bp
, b_vnbufs
);
1431 if (buf_acquire_locked(bp
, lock_flags
, 0, 0)) {
1439 lck_mtx_unlock(buf_mtxp
);
1441 retval
= callout(bp
, arg
);
1450 case BUF_RETURNED_DONE
:
1453 lck_mtx_lock(buf_mtxp
);
1455 case BUF_CLAIMED_DONE
:
1456 lck_mtx_lock(buf_mtxp
);
1459 lck_mtx_lock(buf_mtxp
);
1460 } /* while list has more nodes */
1462 buf_itercomplete(vp
, &local_iterblkhd
, list
[i
].flag
);
1463 lck_mtx_unlock(buf_mtxp
);
1464 } /* for each list */
1469 * Flush out and invalidate all buffers associated with a vnode.
1472 buf_invalidateblks(vnode_t vp
, int flags
, int slpflag
, int slptimeo
)
1477 int must_rescan
= 1;
1478 struct buflists local_iterblkhd
;
1481 if (LIST_EMPTY(&vp
->v_cleanblkhd
) && LIST_EMPTY(&vp
->v_dirtyblkhd
))
1484 lck_mtx_lock(buf_mtxp
);
1487 if (must_rescan
== 0)
1489 * the lists may not be empty, but all that's left at this
1490 * point are metadata or B_LOCKED buffers which are being
1491 * skipped... we know this because we made it through both
1492 * the clean and dirty lists without dropping buf_mtxp...
1493 * each time we drop buf_mtxp we bump "must_rescan"
1496 if (LIST_EMPTY(&vp
->v_cleanblkhd
) && LIST_EMPTY(&vp
->v_dirtyblkhd
))
1500 * iterate the clean list
1502 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_CLEAN
)) {
1503 goto try_dirty_list
;
1505 while (!LIST_EMPTY(&local_iterblkhd
)) {
1507 bp
= LIST_FIRST(&local_iterblkhd
);
1509 LIST_REMOVE(bp
, b_vnbufs
);
1510 LIST_INSERT_HEAD(&vp
->v_cleanblkhd
, bp
, b_vnbufs
);
1513 * some filesystems distinguish meta data blocks with a negative logical block #
1515 if ((flags
& BUF_SKIP_META
) && (bp
->b_lblkno
< 0 || ISSET(bp
->b_flags
, B_META
)))
1518 aflags
= BAC_REMOVE
;
1520 if ( !(flags
& BUF_INVALIDATE_LOCKED
) )
1521 aflags
|= BAC_SKIP_LOCKED
;
1523 if ( (error
= (int)buf_acquire_locked(bp
, aflags
, slpflag
, slptimeo
)) ) {
1524 if (error
== EDEADLK
)
1526 * this buffer was marked B_LOCKED...
1527 * we didn't drop buf_mtxp, so we
1528 * we don't need to rescan
1531 if (error
== EAGAIN
) {
1533 * found a busy buffer... we blocked and
1534 * dropped buf_mtxp, so we're going to
1535 * need to rescan after this pass is completed
1541 * got some kind of 'real' error out of the msleep
1542 * in buf_acquire_locked, terminate the scan and return the error
1544 buf_itercomplete(vp
, &local_iterblkhd
, VBI_CLEAN
);
1546 lck_mtx_unlock(buf_mtxp
);
1549 lck_mtx_unlock(buf_mtxp
);
1551 if (bp
->b_flags
& B_LOCKED
)
1552 KERNEL_DEBUG(0xbbbbc038, bp
, 0, 0, 0, 0);
1554 CLR(bp
->b_flags
, B_LOCKED
);
1555 SET(bp
->b_flags
, B_INVAL
);
1558 lck_mtx_lock(buf_mtxp
);
1561 * by dropping buf_mtxp, we allow new
1562 * buffers to be added to the vnode list(s)
1563 * we'll have to rescan at least once more
1564 * if the queues aren't empty
1568 buf_itercomplete(vp
, &local_iterblkhd
, VBI_CLEAN
);
1572 * Now iterate on dirty blks
1574 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_DIRTY
)) {
1577 while (!LIST_EMPTY(&local_iterblkhd
)) {
1578 bp
= LIST_FIRST(&local_iterblkhd
);
1580 LIST_REMOVE(bp
, b_vnbufs
);
1581 LIST_INSERT_HEAD(&vp
->v_dirtyblkhd
, bp
, b_vnbufs
);
1584 * some filesystems distinguish meta data blocks with a negative logical block #
1586 if ((flags
& BUF_SKIP_META
) && (bp
->b_lblkno
< 0 || ISSET(bp
->b_flags
, B_META
)))
1589 aflags
= BAC_REMOVE
;
1591 if ( !(flags
& BUF_INVALIDATE_LOCKED
) )
1592 aflags
|= BAC_SKIP_LOCKED
;
1594 if ( (error
= (int)buf_acquire_locked(bp
, aflags
, slpflag
, slptimeo
)) ) {
1595 if (error
== EDEADLK
)
1597 * this buffer was marked B_LOCKED...
1598 * we didn't drop buf_mtxp, so we
1599 * we don't need to rescan
1602 if (error
== EAGAIN
) {
1604 * found a busy buffer... we blocked and
1605 * dropped buf_mtxp, so we're going to
1606 * need to rescan after this pass is completed
1612 * got some kind of 'real' error out of the msleep
1613 * in buf_acquire_locked, terminate the scan and return the error
1615 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1617 lck_mtx_unlock(buf_mtxp
);
1620 lck_mtx_unlock(buf_mtxp
);
1622 if (bp
->b_flags
& B_LOCKED
)
1623 KERNEL_DEBUG(0xbbbbc038, bp
, 0, 0, 1, 0);
1625 CLR(bp
->b_flags
, B_LOCKED
);
1626 SET(bp
->b_flags
, B_INVAL
);
1628 if (ISSET(bp
->b_flags
, B_DELWRI
) && (flags
& BUF_WRITE_DATA
))
1629 (void) VNOP_BWRITE(bp
);
1633 lck_mtx_lock(buf_mtxp
);
1635 * by dropping buf_mtxp, we allow new
1636 * buffers to be added to the vnode list(s)
1637 * we'll have to rescan at least once more
1638 * if the queues aren't empty
1642 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1644 lck_mtx_unlock(buf_mtxp
);
1650 buf_flushdirtyblks(vnode_t vp
, int wait
, int flags
, const char *msg
) {
1652 (void) buf_flushdirtyblks_skipinfo(vp
, wait
, flags
, msg
);
1657 buf_flushdirtyblks_skipinfo(vnode_t vp
, int wait
, int flags
, const char *msg
) {
1659 int writes_issued
= 0;
1662 struct buflists local_iterblkhd
;
1663 int lock_flags
= BAC_NOWAIT
| BAC_REMOVE
;
1666 if (flags
& BUF_SKIP_LOCKED
)
1667 lock_flags
|= BAC_SKIP_LOCKED
;
1668 if (flags
& BUF_SKIP_NONLOCKED
)
1669 lock_flags
|= BAC_SKIP_NONLOCKED
;
1671 lck_mtx_lock(buf_mtxp
);
1673 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_DIRTY
) == 0) {
1674 while (!LIST_EMPTY(&local_iterblkhd
)) {
1675 bp
= LIST_FIRST(&local_iterblkhd
);
1676 LIST_REMOVE(bp
, b_vnbufs
);
1677 LIST_INSERT_HEAD(&vp
->v_dirtyblkhd
, bp
, b_vnbufs
);
1679 if ((error
= buf_acquire_locked(bp
, lock_flags
, 0, 0)) == EBUSY
) {
1684 * If we passed in BUF_SKIP_LOCKED or BUF_SKIP_NONLOCKED,
1685 * we may want to do somethign differently if a locked or unlocked
1686 * buffer was encountered (depending on the arg specified).
1687 * In this case, we know that one of those two was set, and the
1688 * buf acquisition failed above.
1690 * If it failed with EDEADLK, then save state which can be emitted
1691 * later on to the caller. Most callers should not care.
1693 if (error
== EDEADLK
) {
1698 lck_mtx_unlock(buf_mtxp
);
1700 bp
->b_flags
&= ~B_LOCKED
;
1703 * Wait for I/O associated with indirect blocks to complete,
1704 * since there is no way to quickly wait for them below.
1706 if ((bp
->b_vp
== vp
) || (wait
== 0))
1707 (void) buf_bawrite(bp
);
1709 (void) VNOP_BWRITE(bp
);
1712 lck_mtx_lock(buf_mtxp
);
1714 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1716 lck_mtx_unlock(buf_mtxp
);
1719 (void)vnode_waitforwrites(vp
, 0, 0, 0, msg
);
1721 if (vp
->v_dirtyblkhd
.lh_first
&& busy
) {
1723 * we had one or more BUSY buffers on
1724 * the dirtyblock list... most likely
1725 * these are due to delayed writes that
1726 * were moved to the bclean queue but
1727 * have not yet been 'written'.
1728 * if we issued some writes on the
1729 * previous pass, we try again immediately
1730 * if we didn't, we'll sleep for some time
1731 * to allow the state to change...
1733 if (writes_issued
== 0) {
1734 (void)tsleep((caddr_t
)&vp
->v_numoutput
,
1735 PRIBIO
+ 1, "vnode_flushdirtyblks", hz
/20);
1749 * called with buf_mtxp held...
1750 * this lock protects the queue manipulation
1753 buf_iterprepare(vnode_t vp
, struct buflists
*iterheadp
, int flags
)
1755 struct buflists
* listheadp
;
1757 if (flags
& VBI_DIRTY
)
1758 listheadp
= &vp
->v_dirtyblkhd
;
1760 listheadp
= &vp
->v_cleanblkhd
;
1762 while (vp
->v_iterblkflags
& VBI_ITER
) {
1763 vp
->v_iterblkflags
|= VBI_ITERWANT
;
1764 msleep(&vp
->v_iterblkflags
, buf_mtxp
, 0, "buf_iterprepare", NULL
);
1766 if (LIST_EMPTY(listheadp
)) {
1767 LIST_INIT(iterheadp
);
1770 vp
->v_iterblkflags
|= VBI_ITER
;
1772 iterheadp
->lh_first
= listheadp
->lh_first
;
1773 listheadp
->lh_first
->b_vnbufs
.le_prev
= &iterheadp
->lh_first
;
1774 LIST_INIT(listheadp
);
1780 * called with buf_mtxp held...
1781 * this lock protects the queue manipulation
1784 buf_itercomplete(vnode_t vp
, struct buflists
*iterheadp
, int flags
)
1786 struct buflists
* listheadp
;
1789 if (flags
& VBI_DIRTY
)
1790 listheadp
= &vp
->v_dirtyblkhd
;
1792 listheadp
= &vp
->v_cleanblkhd
;
1794 while (!LIST_EMPTY(iterheadp
)) {
1795 bp
= LIST_FIRST(iterheadp
);
1796 LIST_REMOVE(bp
, b_vnbufs
);
1797 LIST_INSERT_HEAD(listheadp
, bp
, b_vnbufs
);
1799 vp
->v_iterblkflags
&= ~VBI_ITER
;
1801 if (vp
->v_iterblkflags
& VBI_ITERWANT
) {
1802 vp
->v_iterblkflags
&= ~VBI_ITERWANT
;
1803 wakeup(&vp
->v_iterblkflags
);
1809 bremfree_locked(buf_t bp
)
1811 struct bqueues
*dp
= NULL
;
1814 whichq
= bp
->b_whichq
;
1817 if (bp
->b_shadow_ref
== 0)
1818 panic("bremfree_locked: %p not on freelist", bp
);
1820 * there are clones pointing to 'bp'...
1821 * therefore, it was not put on a freelist
1822 * when buf_brelse was last called on 'bp'
1827 * We only calculate the head of the freelist when removing
1828 * the last element of the list as that is the only time that
1829 * it is needed (e.g. to reset the tail pointer).
1831 * NB: This makes an assumption about how tailq's are implemented.
1833 if (bp
->b_freelist
.tqe_next
== NULL
) {
1834 dp
= &bufqueues
[whichq
];
1836 if (dp
->tqh_last
!= &bp
->b_freelist
.tqe_next
)
1837 panic("bremfree: lost tail");
1839 TAILQ_REMOVE(dp
, bp
, b_freelist
);
1841 if (whichq
== BQ_LAUNDRY
)
1845 bp
->b_timestamp
= 0;
1850 * Associate a buffer with a vnode.
1851 * buf_mtxp must be locked on entry
1854 bgetvp_locked(vnode_t vp
, buf_t bp
)
1858 panic("bgetvp_locked: not free");
1860 if (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
)
1861 bp
->b_dev
= vp
->v_rdev
;
1865 * Insert onto list for new vnode.
1867 bufinsvn(bp
, &vp
->v_cleanblkhd
);
1871 * Disassociate a buffer from a vnode.
1872 * buf_mtxp must be locked on entry
1875 brelvp_locked(buf_t bp
)
1878 * Delete from old vnode list, if on one.
1880 if (bp
->b_vnbufs
.le_next
!= NOLIST
)
1883 bp
->b_vp
= (vnode_t
)NULL
;
1887 * Reassign a buffer from one vnode to another.
1888 * Used to assign file specific control information
1889 * (indirect blocks) to the vnode to which they belong.
1892 buf_reassign(buf_t bp
, vnode_t newvp
)
1894 struct buflists
*listheadp
;
1896 if (newvp
== NULL
) {
1897 printf("buf_reassign: NULL");
1900 lck_mtx_lock_spin(buf_mtxp
);
1903 * Delete from old vnode list, if on one.
1905 if (bp
->b_vnbufs
.le_next
!= NOLIST
)
1908 * If dirty, put on list of dirty buffers;
1909 * otherwise insert onto list of clean buffers.
1911 if (ISSET(bp
->b_flags
, B_DELWRI
))
1912 listheadp
= &newvp
->v_dirtyblkhd
;
1914 listheadp
= &newvp
->v_cleanblkhd
;
1915 bufinsvn(bp
, listheadp
);
1917 lck_mtx_unlock(buf_mtxp
);
1920 static __inline__
void
1921 bufhdrinit(buf_t bp
)
1923 bzero((char *)bp
, sizeof *bp
);
1925 bp
->b_rcred
= NOCRED
;
1926 bp
->b_wcred
= NOCRED
;
1927 bp
->b_vnbufs
.le_next
= NOLIST
;
1928 bp
->b_flags
= B_INVAL
;
1934 * Initialize buffers and hash links for buffers.
1936 __private_extern__
void
1944 /* Initialize the buffer queues ('freelists') and the hash table */
1945 for (dp
= bufqueues
; dp
< &bufqueues
[BQUEUES
]; dp
++)
1947 bufhashtbl
= hashinit(nbuf_hashelements
, M_CACHE
, &bufhash
);
1951 /* Initialize the buffer headers */
1952 for (i
= 0; i
< max_nbuf_headers
; i
++) {
1954 bp
= &buf_headers
[i
];
1958 dp
= &bufqueues
[BQ_EMPTY
];
1959 bp
->b_whichq
= BQ_EMPTY
;
1960 bp
->b_timestamp
= buf_timestamp();
1961 binsheadfree(bp
, dp
, BQ_EMPTY
);
1962 binshash(bp
, &invalhash
);
1964 boot_nbuf_headers
= nbuf_headers
;
1966 TAILQ_INIT(&iobufqueue
);
1967 TAILQ_INIT(&delaybufqueue
);
1969 for (; i
< nbuf_headers
+ niobuf_headers
; i
++) {
1970 bp
= &buf_headers
[i
];
1973 binsheadfree(bp
, &iobufqueue
, -1);
1977 * allocate lock group attribute and group
1979 buf_mtx_grp_attr
= lck_grp_attr_alloc_init();
1980 buf_mtx_grp
= lck_grp_alloc_init("buffer cache", buf_mtx_grp_attr
);
1983 * allocate the lock attribute
1985 buf_mtx_attr
= lck_attr_alloc_init();
1988 * allocate and initialize mutex's for the buffer and iobuffer pools
1990 buf_mtxp
= lck_mtx_alloc_init(buf_mtx_grp
, buf_mtx_attr
);
1991 iobuffer_mtxp
= lck_mtx_alloc_init(buf_mtx_grp
, buf_mtx_attr
);
1993 if (iobuffer_mtxp
== NULL
)
1994 panic("couldn't create iobuffer mutex");
1996 if (buf_mtxp
== NULL
)
1997 panic("couldn't create buf mutex");
2000 * allocate and initialize cluster specific global locks...
2004 printf("using %d buffer headers and %d cluster IO buffer headers\n",
2005 nbuf_headers
, niobuf_headers
);
2007 /* Set up zones used by the buffer cache */
2010 /* start the bcleanbuf() thread */
2011 bcleanbuf_thread_init();
2013 /* Register a callout for relieving vm pressure */
2014 if (vm_set_buffer_cleanup_callout(buffer_cache_gc
) != KERN_SUCCESS
) {
2015 panic("Couldn't register buffer cache callout for vm pressure!\n");
2021 * Zones for the meta data buffers
2025 #define MAXMETA 8192
2027 struct meta_zone_entry
{
2031 const char *mz_name
;
2034 struct meta_zone_entry meta_zones
[] = {
2035 {NULL
, (MINMETA
* 1), 128 * (MINMETA
* 1), "buf.512" },
2036 {NULL
, (MINMETA
* 2), 64 * (MINMETA
* 2), "buf.1024" },
2037 {NULL
, (MINMETA
* 4), 16 * (MINMETA
* 4), "buf.2048" },
2038 {NULL
, (MINMETA
* 8), 512 * (MINMETA
* 8), "buf.4096" },
2039 {NULL
, (MINMETA
* 16), 512 * (MINMETA
* 16), "buf.8192" },
2040 {NULL
, 0, 0, "" } /* End */
2044 * Initialize the meta data zones
2051 for (i
= 0; meta_zones
[i
].mz_size
!= 0; i
++) {
2052 meta_zones
[i
].mz_zone
=
2053 zinit(meta_zones
[i
].mz_size
,
2054 meta_zones
[i
].mz_max
,
2056 meta_zones
[i
].mz_name
);
2057 zone_change(meta_zones
[i
].mz_zone
, Z_CALLERACCT
, FALSE
);
2059 buf_hdr_zone
= zinit(sizeof(struct buf
), 32, PAGE_SIZE
, "buf headers");
2060 zone_change(buf_hdr_zone
, Z_CALLERACCT
, FALSE
);
2063 static __inline__ zone_t
2064 getbufzone(size_t size
)
2068 if ((size
% 512) || (size
< MINMETA
) || (size
> MAXMETA
))
2069 panic("getbufzone: incorect size = %lu", size
);
2071 for (i
= 0; meta_zones
[i
].mz_size
!= 0; i
++) {
2072 if (meta_zones
[i
].mz_size
>= size
)
2076 return (meta_zones
[i
].mz_zone
);
2082 bio_doread(vnode_t vp
, daddr64_t blkno
, int size
, kauth_cred_t cred
, int async
, int queuetype
)
2086 bp
= buf_getblk(vp
, blkno
, size
, 0, 0, queuetype
);
2089 * If buffer does not have data valid, start a read.
2090 * Note that if buffer is B_INVAL, buf_getblk() won't return it.
2091 * Therefore, it's valid if it's I/O has completed or been delayed.
2093 if (!ISSET(bp
->b_flags
, (B_DONE
| B_DELWRI
))) {
2098 /* Start I/O for the buffer (keeping credentials). */
2099 SET(bp
->b_flags
, B_READ
| async
);
2100 if (IS_VALID_CRED(cred
) && !IS_VALID_CRED(bp
->b_rcred
)) {
2101 kauth_cred_ref(cred
);
2107 trace(TR_BREADMISS
, pack(vp
, size
), blkno
);
2109 /* Pay for the read. */
2110 if (p
&& p
->p_stats
) {
2111 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_inblock
); /* XXX */
2116 * since we asked for an ASYNC I/O
2117 * the biodone will do the brelse
2118 * we don't want to pass back a bp
2119 * that we don't 'own'
2128 trace(TR_BREADHIT
, pack(vp
, size
), blkno
);
2134 * Perform the reads for buf_breadn() and buf_meta_breadn().
2135 * Trivial modification to the breada algorithm presented in Bach (p.55).
2138 do_breadn_for_type(vnode_t vp
, daddr64_t blkno
, int size
, daddr64_t
*rablks
, int *rasizes
,
2139 int nrablks
, kauth_cred_t cred
, buf_t
*bpp
, int queuetype
)
2144 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, queuetype
);
2147 * For each of the read-ahead blocks, start a read, if necessary.
2149 for (i
= 0; i
< nrablks
; i
++) {
2150 /* If it's in the cache, just go on to next one. */
2151 if (incore(vp
, rablks
[i
]))
2154 /* Get a buffer for the read-ahead block */
2155 (void) bio_doread(vp
, rablks
[i
], rasizes
[i
], cred
, B_ASYNC
, queuetype
);
2158 /* Otherwise, we had to start a read for it; wait until it's valid. */
2159 return (buf_biowait(bp
));
2164 * Read a disk block.
2165 * This algorithm described in Bach (p.54).
2168 buf_bread(vnode_t vp
, daddr64_t blkno
, int size
, kauth_cred_t cred
, buf_t
*bpp
)
2172 /* Get buffer for block. */
2173 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, BLK_READ
);
2175 /* Wait for the read to complete, and return result. */
2176 return (buf_biowait(bp
));
2180 * Read a disk block. [bread() for meta-data]
2181 * This algorithm described in Bach (p.54).
2184 buf_meta_bread(vnode_t vp
, daddr64_t blkno
, int size
, kauth_cred_t cred
, buf_t
*bpp
)
2188 /* Get buffer for block. */
2189 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, BLK_META
);
2191 /* Wait for the read to complete, and return result. */
2192 return (buf_biowait(bp
));
2196 * Read-ahead multiple disk blocks. The first is sync, the rest async.
2199 buf_breadn(vnode_t vp
, daddr64_t blkno
, int size
, daddr64_t
*rablks
, int *rasizes
, int nrablks
, kauth_cred_t cred
, buf_t
*bpp
)
2201 return (do_breadn_for_type(vp
, blkno
, size
, rablks
, rasizes
, nrablks
, cred
, bpp
, BLK_READ
));
2205 * Read-ahead multiple disk blocks. The first is sync, the rest async.
2206 * [buf_breadn() for meta-data]
2209 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
)
2211 return (do_breadn_for_type(vp
, blkno
, size
, rablks
, rasizes
, nrablks
, cred
, bpp
, BLK_META
));
2215 * Block write. Described in Bach (p.56)
2218 buf_bwrite(buf_t bp
)
2220 int sync
, wasdelayed
;
2222 proc_t p
= current_proc();
2223 vnode_t vp
= bp
->b_vp
;
2225 if (bp
->b_datap
== 0) {
2226 if (brecover_data(bp
) == 0)
2229 /* Remember buffer type, to switch on it later. */
2230 sync
= !ISSET(bp
->b_flags
, B_ASYNC
);
2231 wasdelayed
= ISSET(bp
->b_flags
, B_DELWRI
);
2232 CLR(bp
->b_flags
, (B_READ
| B_DONE
| B_ERROR
| B_DELWRI
));
2235 OSAddAtomicLong(-1, &nbdwrite
);
2239 * If not synchronous, pay for the I/O operation and make
2240 * sure the buf is on the correct vnode queue. We have
2241 * to do this now, because if we don't, the vnode may not
2242 * be properly notified that its I/O has completed.
2245 buf_reassign(bp
, vp
);
2247 if (p
&& p
->p_stats
) {
2248 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_oublock
); /* XXX */
2251 trace(TR_BUFWRITE
, pack(vp
, bp
->b_bcount
), bp
->b_lblkno
);
2253 /* Initiate disk write. Make sure the appropriate party is charged. */
2255 OSAddAtomic(1, &vp
->v_numoutput
);
2261 * If I/O was synchronous, wait for it to complete.
2263 rv
= buf_biowait(bp
);
2266 * Pay for the I/O operation, if it's not been paid for, and
2267 * make sure it's on the correct vnode queue. (async operatings
2268 * were payed for above.)
2271 buf_reassign(bp
, vp
);
2273 if (p
&& p
->p_stats
) {
2274 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_oublock
); /* XXX */
2277 /* Release the buffer. */
2278 // XXXdbg - only if the unused bit is set
2279 if (!ISSET(bp
->b_flags
, B_NORELSE
)) {
2282 CLR(bp
->b_flags
, B_NORELSE
);
2292 vn_bwrite(struct vnop_bwrite_args
*ap
)
2294 return (buf_bwrite(ap
->a_bp
));
2300 * The buffer is marked dirty, but is not queued for I/O.
2301 * This routine should be used when the buffer is expected
2302 * to be modified again soon, typically a small write that
2303 * partially fills a buffer.
2305 * NB: magnetic tapes cannot be delayed; they must be
2306 * written in the order that the writes are requested.
2308 * Described in Leffler, et al. (pp. 208-213).
2310 * Note: With the ability to allocate additional buffer
2311 * headers, we can get in to the situation where "too" many
2312 * buf_bdwrite()s can create situation where the kernel can create
2313 * buffers faster than the disks can service. Doing a buf_bawrite() in
2314 * cases where we have "too many" outstanding buf_bdwrite()s avoids that.
2316 __private_extern__
int
2317 bdwrite_internal(buf_t bp
, int return_error
)
2319 proc_t p
= current_proc();
2320 vnode_t vp
= bp
->b_vp
;
2323 * If the block hasn't been seen before:
2324 * (1) Mark it as having been seen,
2325 * (2) Charge for the write.
2326 * (3) Make sure it's on its vnode's correct block list,
2328 if (!ISSET(bp
->b_flags
, B_DELWRI
)) {
2329 SET(bp
->b_flags
, B_DELWRI
);
2330 if (p
&& p
->p_stats
) {
2331 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_oublock
); /* XXX */
2333 OSAddAtomicLong(1, &nbdwrite
);
2334 buf_reassign(bp
, vp
);
2338 * if we're not LOCKED, but the total number of delayed writes
2339 * has climbed above 75% of the total buffers in the system
2340 * return an error if the caller has indicated that it can
2341 * handle one in this case, otherwise schedule the I/O now
2342 * this is done to prevent us from allocating tons of extra
2343 * buffers when dealing with virtual disks (i.e. DiskImages),
2344 * because additional buffers are dynamically allocated to prevent
2345 * deadlocks from occurring
2347 * however, can't do a buf_bawrite() if the LOCKED bit is set because the
2348 * buffer is part of a transaction and can't go to disk until
2349 * the LOCKED bit is cleared.
2351 if (!ISSET(bp
->b_flags
, B_LOCKED
) && nbdwrite
> ((nbuf_headers
/4)*3)) {
2355 * If the vnode has "too many" write operations in progress
2356 * wait for them to finish the IO
2358 (void)vnode_waitforwrites(vp
, VNODE_ASYNC_THROTTLE
, 0, 0, "buf_bdwrite");
2360 return (buf_bawrite(bp
));
2363 /* Otherwise, the "write" is done, so mark and release the buffer. */
2364 SET(bp
->b_flags
, B_DONE
);
2370 buf_bdwrite(buf_t bp
)
2372 return (bdwrite_internal(bp
, 0));
2377 * Asynchronous block write; just an asynchronous buf_bwrite().
2379 * Note: With the abilitty to allocate additional buffer
2380 * headers, we can get in to the situation where "too" many
2381 * buf_bawrite()s can create situation where the kernel can create
2382 * buffers faster than the disks can service.
2383 * We limit the number of "in flight" writes a vnode can have to
2387 bawrite_internal(buf_t bp
, int throttle
)
2389 vnode_t vp
= bp
->b_vp
;
2394 * If the vnode has "too many" write operations in progress
2395 * wait for them to finish the IO
2397 (void)vnode_waitforwrites(vp
, VNODE_ASYNC_THROTTLE
, 0, 0, (const char *)"buf_bawrite");
2398 else if (vp
->v_numoutput
>= VNODE_ASYNC_THROTTLE
)
2400 * return to the caller and
2401 * let him decide what to do
2403 return (EWOULDBLOCK
);
2405 SET(bp
->b_flags
, B_ASYNC
);
2407 return (VNOP_BWRITE(bp
));
2411 buf_bawrite(buf_t bp
)
2413 return (bawrite_internal(bp
, 1));
2419 buf_free_meta_store(buf_t bp
)
2421 if (bp
->b_bufsize
) {
2422 if (ISSET(bp
->b_flags
, B_ZALLOC
)) {
2425 z
= getbufzone(bp
->b_bufsize
);
2426 zfree(z
, (void *)bp
->b_datap
);
2428 kmem_free(kernel_map
, bp
->b_datap
, bp
->b_bufsize
);
2430 bp
->b_datap
= (uintptr_t)NULL
;
2437 buf_brelse_shadow(buf_t bp
)
2441 buf_t bp_return
= NULL
;
2442 #ifdef BUF_MAKE_PRIVATE
2446 int need_wakeup
= 0;
2448 lck_mtx_lock_spin(buf_mtxp
);
2450 bp_head
= (buf_t
)bp
->b_orig
;
2452 if (bp_head
->b_whichq
!= -1)
2453 panic("buf_brelse_shadow: bp_head on freelist %d\n", bp_head
->b_whichq
);
2455 #ifdef BUF_MAKE_PRIVATE
2456 if (bp_data
= bp
->b_data_store
) {
2457 bp_data
->b_data_ref
--;
2459 * snapshot the ref count so that we can check it
2460 * outside of the lock... we only want the guy going
2461 * from 1 -> 0 to try and release the storage
2463 data_ref
= bp_data
->b_data_ref
;
2466 KERNEL_DEBUG(0xbbbbc008 | DBG_FUNC_START
, bp
, bp_head
, bp_head
->b_shadow_ref
, 0, 0);
2468 bp_head
->b_shadow_ref
--;
2470 for (bp_temp
= bp_head
; bp_temp
&& bp
!= bp_temp
->b_shadow
; bp_temp
= bp_temp
->b_shadow
);
2472 if (bp_temp
== NULL
)
2473 panic("buf_brelse_shadow: bp not on list %p", bp_head
);
2475 bp_temp
->b_shadow
= bp_temp
->b_shadow
->b_shadow
;
2477 #ifdef BUF_MAKE_PRIVATE
2479 * we're about to free the current 'owner' of the data buffer and
2480 * there is at least one other shadow buf_t still pointing at it
2481 * so transfer it to the first shadow buf left in the chain
2483 if (bp
== bp_data
&& data_ref
) {
2484 if ((bp_data
= bp_head
->b_shadow
) == NULL
)
2485 panic("buf_brelse_shadow: data_ref mismatch bp(%p)", bp
);
2487 for (bp_temp
= bp_data
; bp_temp
; bp_temp
= bp_temp
->b_shadow
)
2488 bp_temp
->b_data_store
= bp_data
;
2489 bp_data
->b_data_ref
= data_ref
;
2492 if (bp_head
->b_shadow_ref
== 0 && bp_head
->b_shadow
)
2493 panic("buf_relse_shadow: b_shadow != NULL && b_shadow_ref == 0 bp(%p)", bp
);
2494 if (bp_head
->b_shadow_ref
&& bp_head
->b_shadow
== 0)
2495 panic("buf_relse_shadow: b_shadow == NULL && b_shadow_ref != 0 bp(%p)", bp
);
2497 if (bp_head
->b_shadow_ref
== 0) {
2498 if (!ISSET(bp_head
->b_lflags
, BL_BUSY
)) {
2500 CLR(bp_head
->b_flags
, B_AGE
);
2501 bp_head
->b_timestamp
= buf_timestamp();
2503 if (ISSET(bp_head
->b_flags
, B_LOCKED
)) {
2504 bp_head
->b_whichq
= BQ_LOCKED
;
2505 binstailfree(bp_head
, &bufqueues
[BQ_LOCKED
], BQ_LOCKED
);
2507 bp_head
->b_whichq
= BQ_META
;
2508 binstailfree(bp_head
, &bufqueues
[BQ_META
], BQ_META
);
2510 } else if (ISSET(bp_head
->b_lflags
, BL_WAITSHADOW
)) {
2511 CLR(bp_head
->b_lflags
, BL_WAITSHADOW
);
2513 bp_return
= bp_head
;
2515 if (ISSET(bp_head
->b_lflags
, BL_WANTED_REF
)) {
2516 CLR(bp_head
->b_lflags
, BL_WANTED_REF
);
2520 lck_mtx_unlock(buf_mtxp
);
2525 #ifdef BUF_MAKE_PRIVATE
2526 if (bp
== bp_data
&& data_ref
== 0)
2527 buf_free_meta_store(bp
);
2529 bp
->b_data_store
= NULL
;
2531 KERNEL_DEBUG(0xbbbbc008 | DBG_FUNC_END
, bp
, 0, 0, 0, 0);
2538 * Release a buffer on to the free lists.
2539 * Described in Bach (p. 46).
2542 buf_brelse(buf_t bp
)
2544 struct bqueues
*bufq
;
2547 int need_wakeup
= 0;
2548 int need_bp_wakeup
= 0;
2551 if (bp
->b_whichq
!= -1 || !(bp
->b_lflags
& BL_BUSY
))
2552 panic("buf_brelse: bad buffer = %p\n", bp
);
2555 (void) OSBacktrace(&bp
->b_stackbrelse
[0], 6);
2557 bp
->b_lastbrelse
= current_thread();
2560 if (bp
->b_lflags
& BL_IOBUF
) {
2561 buf_t shadow_master_bp
= NULL
;
2563 if (ISSET(bp
->b_lflags
, BL_SHADOW
))
2564 shadow_master_bp
= buf_brelse_shadow(bp
);
2565 else if (ISSET(bp
->b_lflags
, BL_IOBUF_ALLOC
))
2566 buf_free_meta_store(bp
);
2569 if (shadow_master_bp
) {
2570 bp
= shadow_master_bp
;
2571 goto finish_shadow_master
;
2576 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 388)) | DBG_FUNC_START
,
2577 bp
->b_lblkno
* PAGE_SIZE
, bp
, bp
->b_datap
,
2580 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
2583 * if we're invalidating a buffer that has the B_FILTER bit
2584 * set then call the b_iodone function so it gets cleaned
2587 * the HFS journal code depends on this
2589 if (ISSET(bp
->b_flags
, B_META
) && ISSET(bp
->b_flags
, B_INVAL
)) {
2590 if (ISSET(bp
->b_flags
, B_FILTER
)) { /* if necessary, call out */
2591 void (*iodone_func
)(struct buf
*, void *) = bp
->b_iodone
;
2592 void *arg
= bp
->b_transaction
;
2594 CLR(bp
->b_flags
, B_FILTER
); /* but note callout done */
2595 bp
->b_iodone
= NULL
;
2596 bp
->b_transaction
= NULL
;
2598 if (iodone_func
== NULL
) {
2599 panic("brelse: bp @ %p has NULL b_iodone!\n", bp
);
2601 (*iodone_func
)(bp
, arg
);
2605 * I/O is done. Cleanup the UPL state
2609 if ( !ISSET(bp
->b_flags
, B_META
) && UBCINFOEXISTS(bp
->b_vp
) && bp
->b_bufsize
) {
2614 if ( !ISSET(bp
->b_flags
, B_INVAL
)) {
2615 kret
= ubc_create_upl(bp
->b_vp
,
2616 ubc_blktooff(bp
->b_vp
, bp
->b_lblkno
),
2622 if (kret
!= KERN_SUCCESS
)
2623 panic("brelse: Failed to create UPL");
2625 upl_ubc_alias_set(upl
, (uintptr_t) bp
, (uintptr_t) 5);
2626 #endif /* UPL_DEBUG */
2630 kret
= ubc_upl_unmap(upl
);
2632 if (kret
!= KERN_SUCCESS
)
2633 panic("ubc_upl_unmap failed");
2634 bp
->b_datap
= (uintptr_t)NULL
;
2638 if (bp
->b_flags
& (B_ERROR
| B_INVAL
)) {
2639 if (bp
->b_flags
& (B_READ
| B_INVAL
))
2640 upl_flags
= UPL_ABORT_DUMP_PAGES
;
2644 ubc_upl_abort(upl
, upl_flags
);
2646 if (ISSET(bp
->b_flags
, B_DELWRI
| B_WASDIRTY
))
2647 upl_flags
= UPL_COMMIT_SET_DIRTY
;
2649 upl_flags
= UPL_COMMIT_CLEAR_DIRTY
;
2651 ubc_upl_commit_range(upl
, 0, bp
->b_bufsize
, upl_flags
|
2652 UPL_COMMIT_INACTIVATE
| UPL_COMMIT_FREE_ON_EMPTY
);
2658 panic("brelse: UPL set for non VREG; vp=%p", bp
->b_vp
);
2662 * If it's locked, don't report an error; try again later.
2664 if (ISSET(bp
->b_flags
, (B_LOCKED
|B_ERROR
)) == (B_LOCKED
|B_ERROR
))
2665 CLR(bp
->b_flags
, B_ERROR
);
2667 * If it's not cacheable, or an error, mark it invalid.
2669 if (ISSET(bp
->b_flags
, (B_NOCACHE
|B_ERROR
)))
2670 SET(bp
->b_flags
, B_INVAL
);
2672 if ((bp
->b_bufsize
<= 0) ||
2673 ISSET(bp
->b_flags
, B_INVAL
) ||
2674 (ISSET(bp
->b_lflags
, BL_WANTDEALLOC
) && !ISSET(bp
->b_flags
, B_DELWRI
))) {
2676 boolean_t delayed_buf_free_meta_store
= FALSE
;
2679 * If it's invalid or empty, dissociate it from its vnode,
2680 * release its storage if B_META, and
2681 * clean it up a bit and put it on the EMPTY queue
2683 if (ISSET(bp
->b_flags
, B_DELWRI
))
2684 OSAddAtomicLong(-1, &nbdwrite
);
2686 if (ISSET(bp
->b_flags
, B_META
)) {
2687 if (bp
->b_shadow_ref
)
2688 delayed_buf_free_meta_store
= TRUE
;
2690 buf_free_meta_store(bp
);
2693 * nuke any credentials we were holding
2695 buf_release_credentials(bp
);
2697 lck_mtx_lock_spin(buf_mtxp
);
2699 if (bp
->b_shadow_ref
) {
2700 SET(bp
->b_lflags
, BL_WAITSHADOW
);
2702 lck_mtx_unlock(buf_mtxp
);
2706 if (delayed_buf_free_meta_store
== TRUE
) {
2708 lck_mtx_unlock(buf_mtxp
);
2709 finish_shadow_master
:
2710 buf_free_meta_store(bp
);
2712 lck_mtx_lock_spin(buf_mtxp
);
2714 CLR(bp
->b_flags
, (B_META
| B_ZALLOC
| B_DELWRI
| B_LOCKED
| B_AGE
| B_ASYNC
| B_NOCACHE
| B_FUA
));
2721 binshash(bp
, &invalhash
);
2723 bp
->b_whichq
= BQ_EMPTY
;
2724 binsheadfree(bp
, &bufqueues
[BQ_EMPTY
], BQ_EMPTY
);
2728 * It has valid data. Put it on the end of the appropriate
2729 * queue, so that it'll stick around for as long as possible.
2731 if (ISSET(bp
->b_flags
, B_LOCKED
))
2732 whichq
= BQ_LOCKED
; /* locked in core */
2733 else if (ISSET(bp
->b_flags
, B_META
))
2734 whichq
= BQ_META
; /* meta-data */
2735 else if (ISSET(bp
->b_flags
, B_AGE
))
2736 whichq
= BQ_AGE
; /* stale but valid data */
2738 whichq
= BQ_LRU
; /* valid data */
2739 bufq
= &bufqueues
[whichq
];
2741 bp
->b_timestamp
= buf_timestamp();
2743 lck_mtx_lock_spin(buf_mtxp
);
2746 * the buf_brelse_shadow routine doesn't take 'ownership'
2747 * of the parent buf_t... it updates state that is protected by
2748 * the buf_mtxp, and checks for BL_BUSY to determine whether to
2749 * put the buf_t back on a free list. b_shadow_ref is protected
2750 * by the lock, and since we have not yet cleared B_BUSY, we need
2751 * to check it while holding the lock to insure that one of us
2752 * puts this buf_t back on a free list when it is safe to do so
2754 if (bp
->b_shadow_ref
== 0) {
2755 CLR(bp
->b_flags
, (B_AGE
| B_ASYNC
| B_NOCACHE
));
2756 bp
->b_whichq
= whichq
;
2757 binstailfree(bp
, bufq
, whichq
);
2760 * there are still cloned buf_t's pointing
2761 * at this guy... need to keep it off the
2762 * freelists until a buf_brelse is done on
2765 CLR(bp
->b_flags
, (B_ASYNC
| B_NOCACHE
));
2770 * needbuffer is a global
2771 * we're currently using buf_mtxp to protect it
2772 * delay doing the actual wakeup until after
2778 if (ISSET(bp
->b_lflags
, BL_WANTED
)) {
2780 * delay the actual wakeup until after we
2781 * clear BL_BUSY and we've dropped buf_mtxp
2786 * Unlock the buffer.
2788 CLR(bp
->b_lflags
, (BL_BUSY
| BL_WANTED
));
2791 lck_mtx_unlock(buf_mtxp
);
2795 * Wake up any processes waiting for any buffer to become free.
2797 wakeup(&needbuffer
);
2799 if (need_bp_wakeup
) {
2801 * Wake up any proceeses waiting for _this_ buffer to become free.
2805 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 388)) | DBG_FUNC_END
,
2806 bp
, bp
->b_datap
, bp
->b_flags
, 0, 0);
2810 * Determine if a block is in the cache.
2811 * Just look on what would be its hash chain. If it's there, return
2812 * a pointer to it, unless it's marked invalid. If it's marked invalid,
2813 * we normally don't return the buffer, unless the caller explicitly
2817 incore(vnode_t vp
, daddr64_t blkno
)
2820 struct bufhashhdr
*dp
;
2822 dp
= BUFHASH(vp
, blkno
);
2824 lck_mtx_lock_spin(buf_mtxp
);
2826 if (incore_locked(vp
, blkno
, dp
))
2830 lck_mtx_unlock(buf_mtxp
);
2837 incore_locked(vnode_t vp
, daddr64_t blkno
, struct bufhashhdr
*dp
)
2841 /* Search hash chain */
2842 for (bp
= dp
->lh_first
; bp
!= NULL
; bp
= bp
->b_hash
.le_next
) {
2843 if (bp
->b_lblkno
== blkno
&& bp
->b_vp
== vp
&&
2844 !ISSET(bp
->b_flags
, B_INVAL
)) {
2853 buf_wait_for_shadow_io(vnode_t vp
, daddr64_t blkno
)
2856 struct bufhashhdr
*dp
;
2858 dp
= BUFHASH(vp
, blkno
);
2860 lck_mtx_lock_spin(buf_mtxp
);
2863 if ((bp
= incore_locked(vp
, blkno
, dp
)) == NULL
)
2866 if (bp
->b_shadow_ref
== 0)
2869 SET(bp
->b_lflags
, BL_WANTED_REF
);
2871 (void) msleep(bp
, buf_mtxp
, PSPIN
| (PRIBIO
+1), "buf_wait_for_shadow", NULL
);
2873 lck_mtx_unlock(buf_mtxp
);
2876 /* XXX FIXME -- Update the comment to reflect the UBC changes (please) -- */
2878 * Get a block of requested size that is associated with
2879 * a given vnode and block offset. If it is found in the
2880 * block cache, mark it as having been found, make it busy
2881 * and return it. Otherwise, return an empty block of the
2882 * correct size. It is up to the caller to insure that the
2883 * cached blocks be of the correct size.
2886 buf_getblk(vnode_t vp
, daddr64_t blkno
, int size
, int slpflag
, int slptimeo
, int operation
)
2891 upl_page_info_t
*pl
;
2896 struct bufhashhdr
*dp
;
2898 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_START
,
2899 (uintptr_t)(blkno
* PAGE_SIZE
), size
, operation
, 0, 0);
2901 ret_only_valid
= operation
& BLK_ONLYVALID
;
2902 operation
&= ~BLK_ONLYVALID
;
2903 dp
= BUFHASH(vp
, blkno
);
2905 lck_mtx_lock_spin(buf_mtxp
);
2907 if ((bp
= incore_locked(vp
, blkno
, dp
))) {
2909 * Found in the Buffer Cache
2911 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
2915 switch (operation
) {
2919 SET(bp
->b_lflags
, BL_WANTED
);
2920 bufstats
.bufs_busyincore
++;
2923 * don't retake the mutex after being awakened...
2924 * the time out is in msecs
2926 ts
.tv_sec
= (slptimeo
/1000);
2927 ts
.tv_nsec
= (slptimeo
% 1000) * 10 * NSEC_PER_USEC
* 1000;
2929 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 396)) | DBG_FUNC_NONE
,
2930 (uintptr_t)blkno
, size
, operation
, 0, 0);
2932 err
= msleep(bp
, buf_mtxp
, slpflag
| PDROP
| (PRIBIO
+ 1), "buf_getblk", &ts
);
2935 * Callers who call with PCATCH or timeout are
2936 * willing to deal with the NULL pointer
2938 if (err
&& ((slpflag
& PCATCH
) || ((err
== EWOULDBLOCK
) && slptimeo
)))
2946 * unknown operation requested
2948 panic("getblk: paging or unknown operation for incore busy buffer - %x\n", operation
);
2954 * buffer in core and not busy
2956 SET(bp
->b_lflags
, BL_BUSY
);
2957 SET(bp
->b_flags
, B_CACHE
);
2960 bremfree_locked(bp
);
2961 bufstats
.bufs_incore
++;
2963 lck_mtx_unlock(buf_mtxp
);
2965 bp
->b_owner
= current_thread();
2969 panic("buffer has UPL, but not marked BUSY: %p", bp
);
2971 if ( !ret_only_valid
&& bp
->b_bufsize
!= size
)
2975 switch (operation
) {
2978 * "write" operation: let the UPL subsystem
2979 * know that we intend to modify the buffer
2980 * cache pages we're gathering.
2982 upl_flags
|= UPL_WILL_MODIFY
;
2984 upl_flags
|= UPL_PRECIOUS
;
2985 if (UBCINFOEXISTS(bp
->b_vp
) && bp
->b_bufsize
) {
2986 kret
= ubc_create_upl(vp
,
2987 ubc_blktooff(vp
, bp
->b_lblkno
),
2992 if (kret
!= KERN_SUCCESS
)
2993 panic("Failed to create UPL");
2997 if (upl_valid_page(pl
, 0)) {
2998 if (upl_dirty_page(pl
, 0))
2999 SET(bp
->b_flags
, B_WASDIRTY
);
3001 CLR(bp
->b_flags
, B_WASDIRTY
);
3003 CLR(bp
->b_flags
, (B_DONE
| B_CACHE
| B_WASDIRTY
| B_DELWRI
));
3005 kret
= ubc_upl_map(upl
, (vm_offset_t
*)&(bp
->b_datap
));
3007 if (kret
!= KERN_SUCCESS
)
3008 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
3014 * VM is not involved in IO for the meta data
3015 * buffer already has valid data
3020 panic("getblk: paging or unknown operation for incore buffer- %d\n", operation
);
3025 } else { /* not incore() */
3026 int queue
= BQ_EMPTY
; /* Start with no preference */
3028 if (ret_only_valid
) {
3029 lck_mtx_unlock(buf_mtxp
);
3032 if ((vnode_isreg(vp
) == 0) || (UBCINFOEXISTS(vp
) == 0) /*|| (vnode_issystem(vp) == 1)*/)
3033 operation
= BLK_META
;
3035 if ((bp
= getnewbuf(slpflag
, slptimeo
, &queue
)) == NULL
)
3039 * getnewbuf may block for a number of different reasons...
3040 * if it does, it's then possible for someone else to
3041 * create a buffer for the same block and insert it into
3042 * the hash... if we see it incore at this point we dump
3043 * the buffer we were working on and start over
3045 if (incore_locked(vp
, blkno
, dp
)) {
3046 SET(bp
->b_flags
, B_INVAL
);
3047 binshash(bp
, &invalhash
);
3049 lck_mtx_unlock(buf_mtxp
);
3055 * NOTE: YOU CAN NOT BLOCK UNTIL binshash() HAS BEEN
3056 * CALLED! BE CAREFUL.
3060 * mark the buffer as B_META if indicated
3061 * so that when buffer is released it will goto META queue
3063 if (operation
== BLK_META
)
3064 SET(bp
->b_flags
, B_META
);
3066 bp
->b_blkno
= bp
->b_lblkno
= blkno
;
3070 * Insert in the hash so that incore() can find it
3072 binshash(bp
, BUFHASH(vp
, blkno
));
3074 bgetvp_locked(vp
, bp
);
3076 lck_mtx_unlock(buf_mtxp
);
3081 switch (operation
) {
3084 * buffer data is invalid...
3086 * I don't want to have to retake buf_mtxp,
3087 * so the miss and vmhits counters are done
3088 * with Atomic updates... all other counters
3089 * in bufstats are protected with either
3090 * buf_mtxp or iobuffer_mtxp
3092 OSAddAtomicLong(1, &bufstats
.bufs_miss
);
3097 * "write" operation: let the UPL subsystem know
3098 * that we intend to modify the buffer cache pages
3101 upl_flags
|= UPL_WILL_MODIFY
;
3104 size_t contig_bytes
;
3108 panic("bp already has UPL: %p",bp
);
3110 f_offset
= ubc_blktooff(vp
, blkno
);
3112 upl_flags
|= UPL_PRECIOUS
;
3113 kret
= ubc_create_upl(vp
,
3120 if (kret
!= KERN_SUCCESS
)
3121 panic("Failed to create UPL");
3123 upl_ubc_alias_set(upl
, (uintptr_t) bp
, (uintptr_t) 4);
3124 #endif /* UPL_DEBUG */
3127 if (upl_valid_page(pl
, 0)) {
3129 if (operation
== BLK_READ
)
3130 bmap_flags
= VNODE_READ
;
3132 bmap_flags
= VNODE_WRITE
;
3134 SET(bp
->b_flags
, B_CACHE
| B_DONE
);
3136 OSAddAtomicLong(1, &bufstats
.bufs_vmhits
);
3141 if (upl_dirty_page(pl
, 0)) {
3143 SET(bp
->b_flags
, B_WASDIRTY
);
3145 bp
->b_validend
= bp
->b_bcount
;
3146 bp
->b_dirtyend
= bp
->b_bcount
;
3149 bp
->b_validend
= bp
->b_bcount
;
3153 * try to recreate the physical block number associated with
3156 if (VNOP_BLOCKMAP(vp
, f_offset
, bp
->b_bcount
, &bp
->b_blkno
, &contig_bytes
, NULL
, bmap_flags
, NULL
))
3157 panic("getblk: VNOP_BLOCKMAP failed");
3159 * if the extent represented by this buffer
3160 * is not completely physically contiguous on
3161 * disk, than we can't cache the physical mapping
3162 * in the buffer header
3164 if ((long)contig_bytes
< bp
->b_bcount
)
3165 bp
->b_blkno
= bp
->b_lblkno
;
3167 OSAddAtomicLong(1, &bufstats
.bufs_miss
);
3169 kret
= ubc_upl_map(upl
, (vm_offset_t
*)&(bp
->b_datap
));
3171 if (kret
!= KERN_SUCCESS
)
3172 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
3176 panic("getblk: paging or unknown operation - %x", operation
);
3181 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_END
,
3182 bp
, bp
->b_datap
, bp
->b_flags
, 3, 0);
3185 (void) OSBacktrace(&bp
->b_stackgetblk
[0], 6);
3191 * Get an empty, disassociated buffer of given size.
3194 buf_geteblk(int size
)
3197 int queue
= BQ_EMPTY
;
3200 lck_mtx_lock_spin(buf_mtxp
);
3202 bp
= getnewbuf(0, 0, &queue
);
3203 } while (bp
== NULL
);
3205 SET(bp
->b_flags
, (B_META
|B_INVAL
));
3208 assert(queue
== BQ_EMPTY
);
3209 #endif /* DIAGNOSTIC */
3210 /* XXX need to implement logic to deal with other queues */
3212 binshash(bp
, &invalhash
);
3213 bufstats
.bufs_eblk
++;
3215 lck_mtx_unlock(buf_mtxp
);
3223 buf_redundancy_flags(buf_t bp
)
3225 return bp
->b_redundancy_flags
;
3229 buf_set_redundancy_flags(buf_t bp
, uint32_t flags
)
3231 SET(bp
->b_redundancy_flags
, flags
);
3235 buf_clear_redundancy_flags(buf_t bp
, uint32_t flags
)
3237 CLR(bp
->b_redundancy_flags
, flags
);
3243 recycle_buf_from_pool(int nsize
)
3248 lck_mtx_lock_spin(buf_mtxp
);
3250 TAILQ_FOREACH(bp
, &bufqueues
[BQ_META
], b_freelist
) {
3251 if (ISSET(bp
->b_flags
, B_DELWRI
) || bp
->b_bufsize
!= nsize
)
3253 ptr
= (void *)bp
->b_datap
;
3256 bcleanbuf(bp
, TRUE
);
3259 lck_mtx_unlock(buf_mtxp
);
3266 int zalloc_nopagewait_failed
= 0;
3267 int recycle_buf_failed
= 0;
3270 grab_memory_for_meta_buf(int nsize
)
3274 boolean_t was_vmpriv
;
3276 z
= getbufzone(nsize
);
3279 * make sure we're NOT priviliged so that
3280 * if a vm_page_grab is needed, it won't
3281 * block if we're out of free pages... if
3282 * it blocks, then we can't honor the
3283 * nopagewait request
3285 was_vmpriv
= set_vm_privilege(FALSE
);
3287 ptr
= zalloc_nopagewait(z
);
3289 if (was_vmpriv
== TRUE
)
3290 set_vm_privilege(TRUE
);
3294 zalloc_nopagewait_failed
++;
3296 ptr
= recycle_buf_from_pool(nsize
);
3300 recycle_buf_failed
++;
3302 if (was_vmpriv
== FALSE
)
3303 set_vm_privilege(TRUE
);
3307 if (was_vmpriv
== FALSE
)
3308 set_vm_privilege(FALSE
);
3315 * With UBC, there is no need to expand / shrink the file data
3316 * buffer. The VM uses the same pages, hence no waste.
3317 * All the file data buffers can have one size.
3318 * In fact expand / shrink would be an expensive operation.
3320 * Only exception to this is meta-data buffers. Most of the
3321 * meta data operations are smaller than PAGE_SIZE. Having the
3322 * meta-data buffers grow and shrink as needed, optimizes use
3323 * of the kernel wired memory.
3327 allocbuf(buf_t bp
, int size
)
3329 vm_size_t desired_size
;
3331 desired_size
= roundup(size
, CLBYTES
);
3333 if (desired_size
< PAGE_SIZE
)
3334 desired_size
= PAGE_SIZE
;
3335 if (desired_size
> MAXBSIZE
)
3336 panic("allocbuf: buffer larger than MAXBSIZE requested");
3338 if (ISSET(bp
->b_flags
, B_META
)) {
3339 int nsize
= roundup(size
, MINMETA
);
3342 vm_offset_t elem
= (vm_offset_t
)bp
->b_datap
;
3344 if (ISSET(bp
->b_flags
, B_ZALLOC
)) {
3345 if (bp
->b_bufsize
< nsize
) {
3348 /* reallocate to a bigger size */
3350 zprev
= getbufzone(bp
->b_bufsize
);
3351 if (nsize
<= MAXMETA
) {
3352 desired_size
= nsize
;
3354 /* b_datap not really a ptr */
3355 *(void **)(&bp
->b_datap
) = grab_memory_for_meta_buf(nsize
);
3357 bp
->b_datap
= (uintptr_t)NULL
;
3358 kmem_alloc_kobject(kernel_map
, (vm_offset_t
*)&bp
->b_datap
, desired_size
);
3359 CLR(bp
->b_flags
, B_ZALLOC
);
3361 bcopy((void *)elem
, (caddr_t
)bp
->b_datap
, bp
->b_bufsize
);
3362 zfree(zprev
, (void *)elem
);
3364 desired_size
= bp
->b_bufsize
;
3368 if ((vm_size_t
)bp
->b_bufsize
< desired_size
) {
3369 /* reallocate to a bigger size */
3370 bp
->b_datap
= (uintptr_t)NULL
;
3371 kmem_alloc_kobject(kernel_map
, (vm_offset_t
*)&bp
->b_datap
, desired_size
);
3372 bcopy((const void *)elem
, (caddr_t
)bp
->b_datap
, bp
->b_bufsize
);
3373 kmem_free(kernel_map
, elem
, bp
->b_bufsize
);
3375 desired_size
= bp
->b_bufsize
;
3379 /* new allocation */
3380 if (nsize
<= MAXMETA
) {
3381 desired_size
= nsize
;
3383 /* b_datap not really a ptr */
3384 *(void **)(&bp
->b_datap
) = grab_memory_for_meta_buf(nsize
);
3385 SET(bp
->b_flags
, B_ZALLOC
);
3387 kmem_alloc_kobject(kernel_map
, (vm_offset_t
*)&bp
->b_datap
, desired_size
);
3390 if (bp
->b_datap
== 0)
3391 panic("allocbuf: NULL b_datap");
3393 bp
->b_bufsize
= desired_size
;
3394 bp
->b_bcount
= size
;
3400 * Get a new buffer from one of the free lists.
3402 * Request for a queue is passes in. The queue from which the buffer was taken
3403 * from is returned. Out of range queue requests get BQ_EMPTY. Request for
3404 * BQUEUE means no preference. Use heuristics in that case.
3405 * Heuristics is as follows:
3406 * Try BQ_AGE, BQ_LRU, BQ_EMPTY, BQ_META in that order.
3407 * If none available block till one is made available.
3408 * If buffers available on both BQ_AGE and BQ_LRU, check the timestamps.
3409 * Pick the most stale buffer.
3410 * If found buffer was marked delayed write, start the async. write
3411 * and restart the search.
3412 * Initialize the fields and disassociate the buffer from the vnode.
3413 * Remove the buffer from the hash. Return the buffer and the queue
3414 * on which it was found.
3416 * buf_mtxp is held upon entry
3417 * returns with buf_mtxp locked if new buf available
3418 * returns with buf_mtxp UNlocked if new buf NOT available
3422 getnewbuf(int slpflag
, int slptimeo
, int * queue
)
3428 int age_time
, lru_time
, bp_time
, meta_time
;
3429 int req
= *queue
; /* save it for restarts */
3434 * invalid request gets empty queue
3436 if ((*queue
>= BQUEUES
) || (*queue
< 0)
3437 || (*queue
== BQ_LAUNDRY
) || (*queue
== BQ_LOCKED
))
3441 if (*queue
== BQ_EMPTY
&& (bp
= bufqueues
[*queue
].tqh_first
))
3445 * need to grow number of bufs, add another one rather than recycling
3447 if (nbuf_headers
< max_nbuf_headers
) {
3449 * Increment count now as lock
3450 * is dropped for allocation.
3451 * That avoids over commits
3456 /* Try for the requested queue first */
3457 bp
= bufqueues
[*queue
].tqh_first
;
3461 /* Unable to use requested queue */
3462 age_bp
= bufqueues
[BQ_AGE
].tqh_first
;
3463 lru_bp
= bufqueues
[BQ_LRU
].tqh_first
;
3464 meta_bp
= bufqueues
[BQ_META
].tqh_first
;
3466 if (!age_bp
&& !lru_bp
&& !meta_bp
) {
3468 * Unavailble on AGE or LRU or META queues
3469 * Try the empty list first
3471 bp
= bufqueues
[BQ_EMPTY
].tqh_first
;
3477 * We have seen is this is hard to trigger.
3478 * This is an overcommit of nbufs but needed
3479 * in some scenarios with diskiamges
3483 lck_mtx_unlock(buf_mtxp
);
3485 /* Create a new temporary buffer header */
3486 bp
= (struct buf
*)zalloc(buf_hdr_zone
);
3490 bp
->b_whichq
= BQ_EMPTY
;
3491 bp
->b_timestamp
= buf_timestamp();
3493 SET(bp
->b_flags
, B_HDRALLOC
);
3496 lck_mtx_lock_spin(buf_mtxp
);
3499 binshash(bp
, &invalhash
);
3500 binsheadfree(bp
, &bufqueues
[BQ_EMPTY
], BQ_EMPTY
);
3504 /* subtract already accounted bufcount */
3507 bufstats
.bufs_sleeps
++;
3509 /* wait for a free buffer of any kind */
3511 /* hz value is 100 */
3512 ts
.tv_sec
= (slptimeo
/1000);
3513 /* the hz value is 100; which leads to 10ms */
3514 ts
.tv_nsec
= (slptimeo
% 1000) * NSEC_PER_USEC
* 1000 * 10;
3516 msleep(&needbuffer
, buf_mtxp
, slpflag
| PDROP
| (PRIBIO
+1), "getnewbuf", &ts
);
3520 /* Buffer available either on AGE or LRU or META */
3524 /* Buffer available either on AGE or LRU */
3528 } else if (!lru_bp
) {
3531 } else { /* buffer available on both AGE and LRU */
3532 int t
= buf_timestamp();
3534 age_time
= t
- age_bp
->b_timestamp
;
3535 lru_time
= t
- lru_bp
->b_timestamp
;
3536 if ((age_time
< 0) || (lru_time
< 0)) { /* time set backwards */
3540 * we should probably re-timestamp eveything in the
3541 * queues at this point with the current time
3544 if ((lru_time
>= lru_is_stale
) && (age_time
< age_is_stale
)) {
3554 if (!bp
) { /* Neither on AGE nor on LRU */
3557 } else if (meta_bp
) {
3558 int t
= buf_timestamp();
3560 bp_time
= t
- bp
->b_timestamp
;
3561 meta_time
= t
- meta_bp
->b_timestamp
;
3563 if (!(bp_time
< 0) && !(meta_time
< 0)) {
3564 /* time not set backwards */
3566 bp_is_stale
= (*queue
== BQ_LRU
) ?
3567 lru_is_stale
: age_is_stale
;
3569 if ((meta_time
>= meta_is_stale
) &&
3570 (bp_time
< bp_is_stale
)) {
3577 if (ISSET(bp
->b_flags
, B_LOCKED
) || ISSET(bp
->b_lflags
, BL_BUSY
))
3578 panic("getnewbuf: bp @ %p is LOCKED or BUSY! (flags 0x%x)\n", bp
, bp
->b_flags
);
3581 if (bcleanbuf(bp
, FALSE
)) {
3583 * moved to the laundry thread, buffer not ready
3594 * Returns 0 if buffer is ready to use,
3595 * Returns 1 if issued a buf_bawrite() to indicate
3596 * that the buffer is not ready.
3598 * buf_mtxp is held upon entry
3599 * returns with buf_mtxp locked
3602 bcleanbuf(buf_t bp
, boolean_t discard
)
3604 /* Remove from the queue */
3605 bremfree_locked(bp
);
3608 bp
->b_owner
= current_thread();
3612 * If buffer was a delayed write, start the IO by queuing
3613 * it on the LAUNDRY queue, and return 1
3615 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
3617 SET(bp
->b_lflags
, BL_WANTDEALLOC
);
3622 lck_mtx_unlock(buf_mtxp
);
3624 wakeup(&bufqueues
[BQ_LAUNDRY
]);
3626 * and give it a chance to run
3628 (void)thread_block(THREAD_CONTINUE_NULL
);
3630 lck_mtx_lock_spin(buf_mtxp
);
3635 bp
->b_owner
= current_thread();
3639 * Buffer is no longer on any free list... we own it
3641 SET(bp
->b_lflags
, BL_BUSY
);
3647 * disassociate us from our vnode, if we had one...
3652 lck_mtx_unlock(buf_mtxp
);
3656 if (ISSET(bp
->b_flags
, B_META
))
3657 buf_free_meta_store(bp
);
3659 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
3661 buf_release_credentials(bp
);
3663 bp
->b_redundancy_flags
= 0;
3665 /* If discarding, just move to the empty queue */
3667 lck_mtx_lock_spin(buf_mtxp
);
3668 CLR(bp
->b_flags
, (B_META
| B_ZALLOC
| B_DELWRI
| B_LOCKED
| B_AGE
| B_ASYNC
| B_NOCACHE
| B_FUA
));
3669 bp
->b_whichq
= BQ_EMPTY
;
3670 binshash(bp
, &invalhash
);
3671 binsheadfree(bp
, &bufqueues
[BQ_EMPTY
], BQ_EMPTY
);
3672 CLR(bp
->b_lflags
, BL_BUSY
);
3675 /* Not discarding: clean up and prepare for reuse */
3677 bp
->b_datap
= (uintptr_t)NULL
;
3678 bp
->b_upl
= (void *)NULL
;
3680 * preserve the state of whether this buffer
3681 * was allocated on the fly or not...
3682 * the only other flag that should be set at
3683 * this point is BL_BUSY...
3686 bp
->b_owner
= current_thread();
3689 bp
->b_lflags
= BL_BUSY
;
3690 bp
->b_flags
= (bp
->b_flags
& B_HDRALLOC
);
3692 bp
->b_blkno
= bp
->b_lblkno
= 0;
3693 bp
->b_iodone
= NULL
;
3697 bp
->b_dirtyoff
= bp
->b_dirtyend
= 0;
3698 bp
->b_validoff
= bp
->b_validend
= 0;
3699 bzero(&bp
->b_attr
, sizeof(struct bufattr
));
3701 lck_mtx_lock_spin(buf_mtxp
);
3709 buf_invalblkno(vnode_t vp
, daddr64_t lblkno
, int flags
)
3713 struct bufhashhdr
*dp
;
3715 dp
= BUFHASH(vp
, lblkno
);
3718 lck_mtx_lock_spin(buf_mtxp
);
3720 if ((bp
= incore_locked(vp
, lblkno
, dp
)) == (struct buf
*)0) {
3721 lck_mtx_unlock(buf_mtxp
);
3724 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
3725 if ( !ISSET(flags
, BUF_WAIT
)) {
3726 lck_mtx_unlock(buf_mtxp
);
3729 SET(bp
->b_lflags
, BL_WANTED
);
3731 error
= msleep((caddr_t
)bp
, buf_mtxp
, PDROP
| (PRIBIO
+ 1), "buf_invalblkno", NULL
);
3738 bremfree_locked(bp
);
3739 SET(bp
->b_lflags
, BL_BUSY
);
3740 SET(bp
->b_flags
, B_INVAL
);
3743 bp
->b_owner
= current_thread();
3746 lck_mtx_unlock(buf_mtxp
);
3756 int need_wakeup
= 0;
3758 lck_mtx_lock_spin(buf_mtxp
);
3760 if (ISSET(bp
->b_lflags
, BL_WANTED
)) {
3762 * delay the actual wakeup until after we
3763 * clear BL_BUSY and we've dropped buf_mtxp
3768 bp
->b_owner
= current_thread();
3772 * Unlock the buffer.
3774 CLR(bp
->b_lflags
, (BL_BUSY
| BL_WANTED
));
3777 lck_mtx_unlock(buf_mtxp
);
3781 * Wake up any proceeses waiting for _this_ buffer to become free.
3789 buf_acquire(buf_t bp
, int flags
, int slpflag
, int slptimeo
) {
3792 lck_mtx_lock_spin(buf_mtxp
);
3794 error
= buf_acquire_locked(bp
, flags
, slpflag
, slptimeo
);
3796 lck_mtx_unlock(buf_mtxp
);
3803 buf_acquire_locked(buf_t bp
, int flags
, int slpflag
, int slptimeo
)
3808 if (ISSET(bp
->b_flags
, B_LOCKED
)) {
3809 if ((flags
& BAC_SKIP_LOCKED
))
3812 if ((flags
& BAC_SKIP_NONLOCKED
))
3815 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
3817 * since the lck_mtx_lock may block, the buffer
3818 * may become BUSY, so we need to
3819 * recheck for a NOWAIT request
3821 if (flags
& BAC_NOWAIT
)
3823 SET(bp
->b_lflags
, BL_WANTED
);
3825 /* the hz value is 100; which leads to 10ms */
3826 ts
.tv_sec
= (slptimeo
/100);
3827 ts
.tv_nsec
= (slptimeo
% 100) * 10 * NSEC_PER_USEC
* 1000;
3828 error
= msleep((caddr_t
)bp
, buf_mtxp
, slpflag
| (PRIBIO
+ 1), "buf_acquire", &ts
);
3834 if (flags
& BAC_REMOVE
)
3835 bremfree_locked(bp
);
3836 SET(bp
->b_lflags
, BL_BUSY
);
3840 bp
->b_owner
= current_thread();
3848 * Wait for operations on the buffer to complete.
3849 * When they do, extract and return the I/O's error value.
3852 buf_biowait(buf_t bp
)
3854 while (!ISSET(bp
->b_flags
, B_DONE
)) {
3856 lck_mtx_lock_spin(buf_mtxp
);
3858 if (!ISSET(bp
->b_flags
, B_DONE
)) {
3859 DTRACE_IO1(wait__start
, buf_t
, bp
);
3860 (void) msleep(bp
, buf_mtxp
, PDROP
| (PRIBIO
+1), "buf_biowait", NULL
);
3861 DTRACE_IO1(wait__done
, buf_t
, bp
);
3863 lck_mtx_unlock(buf_mtxp
);
3865 /* check for interruption of I/O (e.g. via NFS), then errors. */
3866 if (ISSET(bp
->b_flags
, B_EINTR
)) {
3867 CLR(bp
->b_flags
, B_EINTR
);
3869 } else if (ISSET(bp
->b_flags
, B_ERROR
))
3870 return (bp
->b_error
? bp
->b_error
: EIO
);
3877 * Mark I/O complete on a buffer.
3879 * If a callback has been requested, e.g. the pageout
3880 * daemon, do so. Otherwise, awaken waiting processes.
3882 * [ Leffler, et al., says on p.247:
3883 * "This routine wakes up the blocked process, frees the buffer
3884 * for an asynchronous write, or, for a request by the pagedaemon
3885 * process, invokes a procedure specified in the buffer structure" ]
3887 * In real life, the pagedaemon (or other system processes) wants
3888 * to do async stuff to, and doesn't want the buffer buf_brelse()'d.
3889 * (for swap pager, that puts swap buffers on the free lists (!!!),
3890 * for the vn device, that puts malloc'd buffers on the free lists!)
3894 buf_biodone(buf_t bp
)
3897 struct bufattr
*bap
;
3899 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 387)) | DBG_FUNC_START
,
3900 bp
, bp
->b_datap
, bp
->b_flags
, 0, 0);
3902 if (ISSET(bp
->b_flags
, B_DONE
))
3903 panic("biodone already");
3907 if (bp
->b_vp
&& bp
->b_vp
->v_mount
) {
3908 mp
= bp
->b_vp
->v_mount
;
3913 if (mp
&& (bp
->b_flags
& B_READ
) == 0) {
3914 update_last_io_time(mp
);
3915 INCR_PENDING_IO(-(pending_io_t
)buf_count(bp
), mp
->mnt_pending_write_size
);
3917 INCR_PENDING_IO(-(pending_io_t
)buf_count(bp
), mp
->mnt_pending_read_size
);
3920 if (kdebug_enable
) {
3921 int code
= DKIO_DONE
;
3922 int io_tier
= GET_BUFATTR_IO_TIER(bap
);
3924 if (bp
->b_flags
& B_READ
)
3926 if (bp
->b_flags
& B_ASYNC
)
3929 if (bp
->b_flags
& B_META
)
3931 else if (bp
->b_flags
& B_PAGEIO
)
3932 code
|= DKIO_PAGING
;
3935 code
|= DKIO_THROTTLE
;
3937 code
|= ((io_tier
<< DKIO_TIER_SHIFT
) & DKIO_TIER_MASK
);
3939 if (bp
->b_flags
& B_PASSIVE
)
3940 code
|= DKIO_PASSIVE
;
3942 if (bap
->ba_flags
& BA_NOCACHE
)
3943 code
|= DKIO_NOCACHE
;
3945 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_COMMON
, FSDBG_CODE(DBG_DKRW
, code
) | DBG_FUNC_NONE
,
3946 buf_kernel_addrperm_addr(bp
), (uintptr_t)VM_KERNEL_ADDRPERM(bp
->b_vp
), bp
->b_resid
, bp
->b_error
, 0);
3950 * I/O was done, so don't believe
3951 * the DIRTY state from VM anymore...
3952 * and we need to reset the THROTTLED/PASSIVE
3955 CLR(bp
->b_flags
, (B_WASDIRTY
| B_PASSIVE
));
3956 CLR(bap
->ba_flags
, (BA_META
| BA_NOCACHE
| BA_DELAYIDLESLEEP
));
3958 SET_BUFATTR_IO_TIER(bap
, 0);
3960 DTRACE_IO1(done
, buf_t
, bp
);
3962 if (!ISSET(bp
->b_flags
, B_READ
) && !ISSET(bp
->b_flags
, B_RAW
))
3964 * wake up any writer's blocked
3965 * on throttle or waiting for I/O
3968 vnode_writedone(bp
->b_vp
);
3970 if (ISSET(bp
->b_flags
, (B_CALL
| B_FILTER
))) { /* if necessary, call out */
3971 void (*iodone_func
)(struct buf
*, void *) = bp
->b_iodone
;
3972 void *arg
= bp
->b_transaction
;
3973 int callout
= ISSET(bp
->b_flags
, B_CALL
);
3975 if (iodone_func
== NULL
)
3976 panic("biodone: bp @ %p has NULL b_iodone!\n", bp
);
3978 CLR(bp
->b_flags
, (B_CALL
| B_FILTER
)); /* filters and callouts are one-shot */
3979 bp
->b_iodone
= NULL
;
3980 bp
->b_transaction
= NULL
;
3983 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
3985 (*iodone_func
)(bp
, arg
);
3989 * assumes that the callback function takes
3990 * ownership of the bp and deals with releasing it if necessary
3995 * in this case the call back function is acting
3996 * strictly as a filter... it does not take
3997 * ownership of the bp and is expecting us
3998 * to finish cleaning up... this is currently used
3999 * by the HFS journaling code
4002 if (ISSET(bp
->b_flags
, B_ASYNC
)) { /* if async, release it */
4003 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
4006 } else { /* or just wakeup the buffer */
4008 * by taking the mutex, we serialize
4009 * the buf owner calling buf_biowait so that we'll
4010 * only see him in one of 2 states...
4011 * state 1: B_DONE wasn't set and he's
4013 * state 2: he's blocked trying to take the
4014 * mutex before looking at B_DONE
4015 * BL_WANTED is cleared in case anyone else
4016 * is blocked waiting for the buffer... note
4017 * that we haven't cleared B_BUSY yet, so if
4018 * they do get to run, their going to re-set
4019 * BL_WANTED and go back to sleep
4021 lck_mtx_lock_spin(buf_mtxp
);
4023 CLR(bp
->b_lflags
, BL_WANTED
);
4024 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
4026 lck_mtx_unlock(buf_mtxp
);
4031 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 387)) | DBG_FUNC_END
,
4032 (uintptr_t)bp
, (uintptr_t)bp
->b_datap
, bp
->b_flags
, 0, 0);
4036 * Obfuscate buf pointers.
4039 buf_kernel_addrperm_addr(void * addr
)
4041 if ((vm_offset_t
)addr
== 0)
4044 return ((vm_offset_t
)addr
+ buf_kernel_addrperm
);
4048 * Return a count of buffers on the "locked" queue.
4051 count_lock_queue(void)
4056 lck_mtx_lock_spin(buf_mtxp
);
4058 for (bp
= bufqueues
[BQ_LOCKED
].tqh_first
; bp
;
4059 bp
= bp
->b_freelist
.tqe_next
)
4061 lck_mtx_unlock(buf_mtxp
);
4067 * Return a count of 'busy' buffers. Used at the time of shutdown.
4068 * note: This is also called from the mach side in debug context in kdp.c
4071 count_busy_buffers(void)
4073 return buf_busycount
+ bufstats
.bufs_iobufinuse
;
4078 * Print out statistics on the current allocation of the buffer pool.
4079 * Can be enabled to print out on every ``sync'' by setting "syncprt"
4080 * in vfs_syscalls.c using sysctl.
4088 int counts
[MAXBSIZE
/CLBYTES
+1];
4089 static char *bname
[BQUEUES
] =
4090 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
4092 for (dp
= bufqueues
, i
= 0; dp
< &bufqueues
[BQUEUES
]; dp
++, i
++) {
4094 for (j
= 0; j
<= MAXBSIZE
/CLBYTES
; j
++)
4097 lck_mtx_lock(buf_mtxp
);
4099 for (bp
= dp
->tqh_first
; bp
; bp
= bp
->b_freelist
.tqe_next
) {
4100 counts
[bp
->b_bufsize
/CLBYTES
]++;
4103 lck_mtx_unlock(buf_mtxp
);
4105 printf("%s: total-%d", bname
[i
], count
);
4106 for (j
= 0; j
<= MAXBSIZE
/CLBYTES
; j
++)
4108 printf(", %d-%d", j
* CLBYTES
, counts
[j
]);
4112 #endif /* DIAGNOSTIC */
4114 #define NRESERVEDIOBUFS 128
4118 alloc_io_buf(vnode_t vp
, int priv
)
4122 lck_mtx_lock_spin(iobuffer_mtxp
);
4124 while (((niobuf_headers
- NRESERVEDIOBUFS
< bufstats
.bufs_iobufinuse
) && !priv
) ||
4125 (bp
= iobufqueue
.tqh_first
) == NULL
) {
4126 bufstats
.bufs_iobufsleeps
++;
4129 (void) msleep(&need_iobuffer
, iobuffer_mtxp
, PSPIN
| (PRIBIO
+1), (const char *)"alloc_io_buf", NULL
);
4131 TAILQ_REMOVE(&iobufqueue
, bp
, b_freelist
);
4133 bufstats
.bufs_iobufinuse
++;
4134 if (bufstats
.bufs_iobufinuse
> bufstats
.bufs_iobufmax
)
4135 bufstats
.bufs_iobufmax
= bufstats
.bufs_iobufinuse
;
4137 lck_mtx_unlock(iobuffer_mtxp
);
4140 * initialize various fields
4141 * we don't need to hold the mutex since the buffer
4142 * is now private... the vp should have a reference
4143 * on it and is not protected by this mutex in any event
4145 bp
->b_timestamp
= 0;
4150 bp
->b_lflags
= BL_BUSY
| BL_IOBUF
;
4151 bp
->b_redundancy_flags
= 0;
4152 bp
->b_blkno
= bp
->b_lblkno
= 0;
4154 bp
->b_owner
= current_thread();
4157 bp
->b_iodone
= NULL
;
4164 bzero(&bp
->b_attr
, sizeof(struct bufattr
));
4166 if (vp
&& (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
))
4167 bp
->b_dev
= vp
->v_rdev
;
4176 free_io_buf(buf_t bp
)
4178 int need_wakeup
= 0;
4181 * put buffer back on the head of the iobufqueue
4184 bp
->b_flags
= B_INVAL
;
4186 /* Zero out the bufattr and its flags before relinquishing this iobuf */
4187 bzero (&bp
->b_attr
, sizeof(struct bufattr
));
4189 lck_mtx_lock_spin(iobuffer_mtxp
);
4191 binsheadfree(bp
, &iobufqueue
, -1);
4193 if (need_iobuffer
) {
4195 * Wake up any processes waiting because they need an io buffer
4197 * do the wakeup after we drop the mutex... it's possible that the
4198 * wakeup will be superfluous if need_iobuffer gets set again and
4199 * another thread runs this path, but it's highly unlikely, doesn't
4200 * hurt, and it means we don't hold up I/O progress if the wakeup blocks
4201 * trying to grab a task related lock...
4206 if (bufstats
.bufs_iobufinuse
<= 0)
4207 panic("free_io_buf: bp(%p) - bufstats.bufs_iobufinuse < 0", bp
);
4209 bufstats
.bufs_iobufinuse
--;
4211 lck_mtx_unlock(iobuffer_mtxp
);
4214 wakeup(&need_iobuffer
);
4221 lck_mtx_lock_spin(buf_mtxp
);
4225 buf_list_unlock(void)
4227 lck_mtx_unlock(buf_mtxp
);
4231 * If getnewbuf() calls bcleanbuf() on the same thread
4232 * there is a potential for stack overrun and deadlocks.
4233 * So we always handoff the work to a worker thread for completion
4238 bcleanbuf_thread_init(void)
4240 thread_t thread
= THREAD_NULL
;
4242 /* create worker thread */
4243 kernel_thread_start((thread_continue_t
)bcleanbuf_thread
, NULL
, &thread
);
4244 thread_deallocate(thread
);
4247 typedef int (*bcleanbufcontinuation
)(int);
4250 bcleanbuf_thread(void)
4257 lck_mtx_lock_spin(buf_mtxp
);
4259 while ( (bp
= TAILQ_FIRST(&bufqueues
[BQ_LAUNDRY
])) == NULL
) {
4260 (void)msleep0(&bufqueues
[BQ_LAUNDRY
], buf_mtxp
, PRIBIO
|PDROP
, "blaundry", 0, (bcleanbufcontinuation
)bcleanbuf_thread
);
4264 * Remove from the queue
4266 bremfree_locked(bp
);
4269 * Buffer is no longer on any free list
4271 SET(bp
->b_lflags
, BL_BUSY
);
4275 bp
->b_owner
= current_thread();
4279 lck_mtx_unlock(buf_mtxp
);
4283 error
= bawrite_internal(bp
, 0);
4286 bp
->b_whichq
= BQ_LAUNDRY
;
4287 bp
->b_timestamp
= buf_timestamp();
4289 lck_mtx_lock_spin(buf_mtxp
);
4291 binstailfree(bp
, &bufqueues
[BQ_LAUNDRY
], BQ_LAUNDRY
);
4294 /* we never leave a busy page on the laundry queue */
4295 CLR(bp
->b_lflags
, BL_BUSY
);
4298 bp
->b_owner
= current_thread();
4302 lck_mtx_unlock(buf_mtxp
);
4304 if (loopcnt
> MAXLAUNDRY
) {
4306 * bawrite_internal() can return errors if we're throttled. If we've
4307 * done several I/Os and failed, give the system some time to unthrottle
4310 (void)tsleep((void *)&bufqueues
[BQ_LAUNDRY
], PRIBIO
, "blaundry", 1);
4313 /* give other threads a chance to run */
4314 (void)thread_block(THREAD_CONTINUE_NULL
);
4323 brecover_data(buf_t bp
)
4327 upl_page_info_t
*pl
;
4329 vnode_t vp
= bp
->b_vp
;
4333 if ( !UBCINFOEXISTS(vp
) || bp
->b_bufsize
== 0)
4336 upl_flags
= UPL_PRECIOUS
;
4337 if (! (buf_flags(bp
) & B_READ
)) {
4339 * "write" operation: let the UPL subsystem know
4340 * that we intend to modify the buffer cache pages we're
4343 upl_flags
|= UPL_WILL_MODIFY
;
4346 kret
= ubc_create_upl(vp
,
4347 ubc_blktooff(vp
, bp
->b_lblkno
),
4352 if (kret
!= KERN_SUCCESS
)
4353 panic("Failed to create UPL");
4355 for (upl_offset
= 0; upl_offset
< bp
->b_bufsize
; upl_offset
+= PAGE_SIZE
) {
4357 if (!upl_valid_page(pl
, upl_offset
/ PAGE_SIZE
) || !upl_dirty_page(pl
, upl_offset
/ PAGE_SIZE
)) {
4358 ubc_upl_abort(upl
, 0);
4364 kret
= ubc_upl_map(upl
, (vm_offset_t
*)&(bp
->b_datap
));
4366 if (kret
!= KERN_SUCCESS
)
4367 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
4372 SET(bp
->b_flags
, B_INVAL
);
4379 buffer_cache_gc(int all
)
4382 boolean_t did_large_zfree
= FALSE
;
4383 boolean_t need_wakeup
= FALSE
;
4384 int now
= buf_timestamp();
4386 struct bqueues privq
;
4387 int thresh_hold
= BUF_STALE_THRESHHOLD
;
4392 * We only care about metadata (incore storage comes from zalloc()).
4393 * Unless "all" is set (used to evict meta data buffers in preparation
4394 * for deep sleep), we only evict up to BUF_MAX_GC_BATCH_SIZE buffers
4395 * that have not been accessed in the last BUF_STALE_THRESHOLD seconds.
4396 * BUF_MAX_GC_BATCH_SIZE controls both the hold time of the global lock
4397 * "buf_mtxp" and the length of time we spend compute bound in the GC
4398 * thread which calls this function
4400 lck_mtx_lock(buf_mtxp
);
4405 need_wakeup
= FALSE
;
4407 while (((bp
= TAILQ_FIRST(&bufqueues
[BQ_META
]))) &&
4408 (now
> bp
->b_timestamp
) &&
4409 (now
- bp
->b_timestamp
> thresh_hold
) &&
4410 (found
< BUF_MAX_GC_BATCH_SIZE
)) {
4412 /* Remove from free list */
4413 bremfree_locked(bp
);
4417 bp
->b_owner
= current_thread();
4421 /* If dirty, move to laundry queue and remember to do wakeup */
4422 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
4423 SET(bp
->b_lflags
, BL_WANTDEALLOC
);
4432 * Mark busy and put on private list. We could technically get
4433 * away without setting BL_BUSY here.
4435 SET(bp
->b_lflags
, BL_BUSY
);
4439 * Remove from hash and dissociate from vp.
4446 TAILQ_INSERT_TAIL(&privq
, bp
, b_freelist
);
4453 /* Drop lock for batch processing */
4454 lck_mtx_unlock(buf_mtxp
);
4456 /* Wakeup and yield for laundry if need be */
4458 wakeup(&bufqueues
[BQ_LAUNDRY
]);
4459 (void)thread_block(THREAD_CONTINUE_NULL
);
4462 /* Clean up every buffer on private list */
4463 TAILQ_FOREACH(bp
, &privq
, b_freelist
) {
4464 /* Take note if we've definitely freed at least a page to a zone */
4465 if ((ISSET(bp
->b_flags
, B_ZALLOC
)) && (buf_size(bp
) >= PAGE_SIZE
)) {
4466 did_large_zfree
= TRUE
;
4469 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
4472 buf_free_meta_store(bp
);
4474 /* Release credentials */
4475 buf_release_credentials(bp
);
4477 /* Prepare for moving to empty queue */
4478 CLR(bp
->b_flags
, (B_META
| B_ZALLOC
| B_DELWRI
| B_LOCKED
4479 | B_AGE
| B_ASYNC
| B_NOCACHE
| B_FUA
));
4480 bp
->b_whichq
= BQ_EMPTY
;
4483 lck_mtx_lock(buf_mtxp
);
4485 /* Back under lock, move them all to invalid hash and clear busy */
4486 TAILQ_FOREACH(bp
, &privq
, b_freelist
) {
4487 binshash(bp
, &invalhash
);
4488 CLR(bp
->b_lflags
, BL_BUSY
);
4492 if (bp
->b_owner
!= current_thread()) {
4493 panic("Buffer stolen from buffer_cache_gc()");
4495 bp
->b_owner
= current_thread();
4500 /* And do a big bulk move to the empty queue */
4501 TAILQ_CONCAT(&bufqueues
[BQ_EMPTY
], &privq
, b_freelist
);
4503 } while (all
&& (found
== BUF_MAX_GC_BATCH_SIZE
));
4505 lck_mtx_unlock(buf_mtxp
);
4507 return did_large_zfree
;
4520 bp_cmp(void *a
, void *b
)
4522 buf_t
*bp_a
= *(buf_t
**)a
,
4523 *bp_b
= *(buf_t
**)b
;
4526 // don't have to worry about negative block
4527 // numbers so this is ok to do.
4529 res
= (bp_a
->b_blkno
- bp_b
->b_blkno
);
4536 bflushq(int whichq
, mount_t mp
)
4540 int total_writes
= 0;
4541 static buf_t flush_table
[NFLUSH
];
4543 if (whichq
< 0 || whichq
>= BQUEUES
) {
4548 lck_mtx_lock(buf_mtxp
);
4550 bp
= TAILQ_FIRST(&bufqueues
[whichq
]);
4552 for (buf_count
= 0; bp
; bp
= next
) {
4553 next
= bp
->b_freelist
.tqe_next
;
4555 if (bp
->b_vp
== NULL
|| bp
->b_vp
->v_mount
!= mp
) {
4559 if (ISSET(bp
->b_flags
, B_DELWRI
) && !ISSET(bp
->b_lflags
, BL_BUSY
)) {
4561 bremfree_locked(bp
);
4563 bp
->b_owner
= current_thread();
4566 SET(bp
->b_lflags
, BL_BUSY
);
4569 flush_table
[buf_count
] = bp
;
4573 if (buf_count
>= NFLUSH
) {
4574 lck_mtx_unlock(buf_mtxp
);
4576 qsort(flush_table
, buf_count
, sizeof(struct buf
*), bp_cmp
);
4578 for (i
= 0; i
< buf_count
; i
++) {
4579 buf_bawrite(flush_table
[i
]);
4585 lck_mtx_unlock(buf_mtxp
);
4587 if (buf_count
> 0) {
4588 qsort(flush_table
, buf_count
, sizeof(struct buf
*), bp_cmp
);
4590 for (i
= 0; i
< buf_count
; i
++) {
4591 buf_bawrite(flush_table
[i
]);
4595 return (total_writes
);