2 * Copyright (c) 2000-2012 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
28 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
30 * Copyright (c) 1994 Christopher G. Demetriou
31 * Copyright (c) 1982, 1986, 1989, 1993
32 * The Regents of the University of California. All rights reserved.
33 * (c) UNIX System Laboratories, Inc.
34 * All or some portions of this file are derived from material licensed
35 * to the University of California by American Telephone and Telegraph
36 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
37 * the permission of UNIX System Laboratories, Inc.
39 * Redistribution and use in source and binary forms, with or without
40 * modification, are permitted provided that the following conditions
42 * 1. Redistributions of source code must retain the above copyright
43 * notice, this list of conditions and the following disclaimer.
44 * 2. Redistributions in binary form must reproduce the above copyright
45 * notice, this list of conditions and the following disclaimer in the
46 * documentation and/or other materials provided with the distribution.
47 * 3. All advertising materials mentioning features or use of this software
48 * must display the following acknowledgement:
49 * This product includes software developed by the University of
50 * California, Berkeley and its contributors.
51 * 4. Neither the name of the University nor the names of its contributors
52 * may be used to endorse or promote products derived from this software
53 * without specific prior written permission.
55 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
56 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
57 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
58 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
59 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
60 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
61 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
62 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
63 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
64 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
67 * @(#)vfs_bio.c 8.6 (Berkeley) 1/11/94
72 * Bach: The Design of the UNIX Operating System (Prentice Hall, 1986)
73 * Leffler, et al.: The Design and Implementation of the 4.3BSD
74 * UNIX Operating System (Addison Welley, 1989)
77 #include <sys/param.h>
78 #include <sys/systm.h>
79 #include <sys/proc_internal.h>
80 #include <sys/buf_internal.h>
81 #include <sys/vnode_internal.h>
82 #include <sys/mount_internal.h>
83 #include <sys/trace.h>
84 #include <sys/malloc.h>
85 #include <sys/resourcevar.h>
86 #include <miscfs/specfs/specdev.h>
88 #include <sys/kauth.h>
90 #include <kern/assert.h>
91 #endif /* DIAGNOSTIC */
92 #include <kern/task.h>
93 #include <kern/zalloc.h>
94 #include <kern/lock.h>
96 #include <sys/fslog.h> /* fslog_io_error() */
98 #include <mach/mach_types.h>
99 #include <mach/memory_object_types.h>
100 #include <kern/sched_prim.h> /* thread_block() */
102 #include <vm/vm_kern.h>
103 #include <vm/vm_pageout.h>
105 #include <sys/kdebug.h>
107 #include <libkern/OSAtomic.h>
108 #include <libkern/OSDebug.h>
109 #include <sys/ubc_internal.h>
112 #include <sys/cprotect.h>
116 static __inline__
void bufqinc(int q
);
117 static __inline__
void bufqdec(int q
);
120 int bcleanbuf(buf_t bp
, boolean_t discard
);
121 static int brecover_data(buf_t bp
);
122 static boolean_t
incore(vnode_t vp
, daddr64_t blkno
);
123 /* timeout is in msecs */
124 static buf_t
getnewbuf(int slpflag
, int slptimeo
, int *queue
);
125 static void bremfree_locked(buf_t bp
);
126 static void buf_reassign(buf_t bp
, vnode_t newvp
);
127 static errno_t
buf_acquire_locked(buf_t bp
, int flags
, int slpflag
, int slptimeo
);
128 static int buf_iterprepare(vnode_t vp
, struct buflists
*, int flags
);
129 static void buf_itercomplete(vnode_t vp
, struct buflists
*, int flags
);
130 static boolean_t
buffer_cache_gc(int);
131 static buf_t
buf_brelse_shadow(buf_t bp
);
132 static void buf_free_meta_store(buf_t bp
);
134 static buf_t
buf_create_shadow_internal(buf_t bp
, boolean_t force_copy
,
135 uintptr_t external_storage
, void (*iodone
)(buf_t
, void *), void *arg
, int priv
);
138 __private_extern__
int bdwrite_internal(buf_t
, int);
140 /* zone allocated buffer headers */
141 static void bufzoneinit(void) __attribute__((section("__TEXT, initcode")));
142 static void bcleanbuf_thread_init(void) __attribute__((section("__TEXT, initcode")));
143 static void bcleanbuf_thread(void);
145 static zone_t buf_hdr_zone
;
146 static int buf_hdr_count
;
150 * Definitions for the buffer hash lists.
152 #define BUFHASH(dvp, lbn) \
153 (&bufhashtbl[((long)(dvp) / sizeof(*(dvp)) + (int)(lbn)) & bufhash])
154 LIST_HEAD(bufhashhdr
, buf
) *bufhashtbl
, invalhash
;
157 static buf_t
incore_locked(vnode_t vp
, daddr64_t blkno
, struct bufhashhdr
*dp
);
159 /* Definitions for the buffer stats. */
160 struct bufstats bufstats
;
162 /* Number of delayed write buffers */
165 static int boot_nbuf_headers
= 0;
167 static TAILQ_HEAD(delayqueue
, buf
) delaybufqueue
;
169 static TAILQ_HEAD(ioqueue
, buf
) iobufqueue
;
170 static TAILQ_HEAD(bqueues
, buf
) bufqueues
[BQUEUES
];
171 static int needbuffer
;
172 static int need_iobuffer
;
174 static lck_grp_t
*buf_mtx_grp
;
175 static lck_attr_t
*buf_mtx_attr
;
176 static lck_grp_attr_t
*buf_mtx_grp_attr
;
177 static lck_mtx_t
*iobuffer_mtxp
;
178 static lck_mtx_t
*buf_mtxp
;
180 static int buf_busycount
;
182 static __inline__
int
191 * Insq/Remq for the buffer free lists.
194 #define binsheadfree(bp, dp, whichq) do { \
195 TAILQ_INSERT_HEAD(dp, bp, b_freelist); \
199 #define binstailfree(bp, dp, whichq) do { \
200 TAILQ_INSERT_TAIL(dp, bp, b_freelist); \
204 #define binsheadfree(bp, dp, whichq) do { \
205 TAILQ_INSERT_HEAD(dp, bp, b_freelist); \
208 #define binstailfree(bp, dp, whichq) do { \
209 TAILQ_INSERT_TAIL(dp, bp, b_freelist); \
214 #define BHASHENTCHECK(bp) \
215 if ((bp)->b_hash.le_prev != (struct buf **)0xdeadbeef) \
216 panic("%p: b_hash.le_prev is not deadbeef", (bp));
218 #define BLISTNONE(bp) \
219 (bp)->b_hash.le_next = (struct buf *)0; \
220 (bp)->b_hash.le_prev = (struct buf **)0xdeadbeef;
223 * Insq/Remq for the vnode usage lists.
225 #define bufinsvn(bp, dp) LIST_INSERT_HEAD(dp, bp, b_vnbufs)
226 #define bufremvn(bp) { \
227 LIST_REMOVE(bp, b_vnbufs); \
228 (bp)->b_vnbufs.le_next = NOLIST; \
232 * Time in seconds before a buffer on a list is
233 * considered as a stale buffer
235 #define LRU_IS_STALE 120 /* default value for the LRU */
236 #define AGE_IS_STALE 60 /* default value for the AGE */
237 #define META_IS_STALE 180 /* default value for the BQ_META */
239 int lru_is_stale
= LRU_IS_STALE
;
240 int age_is_stale
= AGE_IS_STALE
;
241 int meta_is_stale
= META_IS_STALE
;
243 #define MAXLAUNDRY 10
245 /* LIST_INSERT_HEAD() with assertions */
246 static __inline__
void
247 blistenterhead(struct bufhashhdr
* head
, buf_t bp
)
249 if ((bp
->b_hash
.le_next
= (head
)->lh_first
) != NULL
)
250 (head
)->lh_first
->b_hash
.le_prev
= &(bp
)->b_hash
.le_next
;
251 (head
)->lh_first
= bp
;
252 bp
->b_hash
.le_prev
= &(head
)->lh_first
;
253 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
254 panic("blistenterhead: le_prev is deadbeef");
257 static __inline__
void
258 binshash(buf_t bp
, struct bufhashhdr
*dp
)
262 #endif /* DIAGNOSTIC */
268 for(; nbp
!= NULL
; nbp
= nbp
->b_hash
.le_next
) {
270 panic("buf already in hashlist");
272 #endif /* DIAGNOSTIC */
274 blistenterhead(dp
, bp
);
277 static __inline__
void
280 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
281 panic("bremhash le_prev is deadbeef");
282 if (bp
->b_hash
.le_next
== bp
)
283 panic("bremhash: next points to self");
285 if (bp
->b_hash
.le_next
!= NULL
)
286 bp
->b_hash
.le_next
->b_hash
.le_prev
= bp
->b_hash
.le_prev
;
287 *bp
->b_hash
.le_prev
= (bp
)->b_hash
.le_next
;
293 static __inline__
void
294 bmovelaundry(buf_t bp
)
296 bp
->b_whichq
= BQ_LAUNDRY
;
297 bp
->b_timestamp
= buf_timestamp();
298 binstailfree(bp
, &bufqueues
[BQ_LAUNDRY
], BQ_LAUNDRY
);
302 static __inline__
void
303 buf_release_credentials(buf_t bp
)
305 if (IS_VALID_CRED(bp
->b_rcred
)) {
306 kauth_cred_unref(&bp
->b_rcred
);
308 if (IS_VALID_CRED(bp
->b_wcred
)) {
309 kauth_cred_unref(&bp
->b_wcred
);
315 buf_valid(buf_t bp
) {
317 if ( (bp
->b_flags
& (B_DONE
| B_DELWRI
)) )
323 buf_fromcache(buf_t bp
) {
325 if ( (bp
->b_flags
& B_CACHE
) )
331 buf_markinvalid(buf_t bp
) {
333 SET(bp
->b_flags
, B_INVAL
);
337 buf_markdelayed(buf_t bp
) {
339 if (!ISSET(bp
->b_flags
, B_DELWRI
)) {
340 SET(bp
->b_flags
, B_DELWRI
);
342 OSAddAtomicLong(1, &nbdwrite
);
343 buf_reassign(bp
, bp
->b_vp
);
345 SET(bp
->b_flags
, B_DONE
);
349 buf_markclean(buf_t bp
) {
351 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
352 CLR(bp
->b_flags
, B_DELWRI
);
354 OSAddAtomicLong(-1, &nbdwrite
);
355 buf_reassign(bp
, bp
->b_vp
);
360 buf_markeintr(buf_t bp
) {
362 SET(bp
->b_flags
, B_EINTR
);
367 buf_markaged(buf_t bp
) {
369 SET(bp
->b_flags
, B_AGE
);
375 if ((bp
->b_flags
& B_FUA
) == B_FUA
)
381 buf_markfua(buf_t bp
) {
383 SET(bp
->b_flags
, B_FUA
);
388 buf_setcpaddr(buf_t bp
, struct cprotect
*entry
) {
389 bp
->b_attr
.ba_cpentry
= entry
;
393 buf_setcpoff (buf_t bp
, uint64_t foffset
) {
394 bp
->b_attr
.ba_cp_file_off
= foffset
;
398 bufattr_cpaddr(bufattr_t bap
) {
399 return (bap
->ba_cpentry
);
403 bufattr_cpoff(bufattr_t bap
) {
404 return (bap
->ba_cp_file_off
);
408 bufattr_setcpaddr(bufattr_t bap
, void *cp_entry_addr
) {
409 bap
->ba_cpentry
= cp_entry_addr
;
413 bufattr_setcpoff(bufattr_t bap
, uint64_t foffset
) {
414 bap
->ba_cp_file_off
= foffset
;
419 bufattr_cpaddr(bufattr_t bap __unused
) {
424 bufattr_cpoff(bufattr_t bap __unused
) {
429 bufattr_setcpaddr(bufattr_t bap __unused
, void *cp_entry_addr __unused
) {
433 bufattr_setcpoff(__unused bufattr_t bap
, __unused
uint64_t foffset
) {
436 #endif /* CONFIG_PROTECT */
441 MALLOC(bap
, bufattr_t
, sizeof(struct bufattr
), M_TEMP
, M_WAITOK
);
445 bzero(bap
, sizeof(struct bufattr
));
450 bufattr_free(bufattr_t bap
) {
456 bufattr_rawencrypted(bufattr_t bap
) {
457 if ( (bap
->ba_flags
& BA_RAW_ENCRYPTED_IO
) )
463 bufattr_throttled(bufattr_t bap
) {
464 if ( (bap
->ba_flags
& BA_THROTTLED_IO
) )
470 bufattr_nocache(bufattr_t bap
) {
471 if ( (bap
->ba_flags
& BA_NOCACHE
) )
477 bufattr_meta(bufattr_t bap
) {
478 if ( (bap
->ba_flags
& BA_META
) )
485 bufattr_delayidlesleep(bufattr_t bap
)
486 #else /* !CONFIG_EMBEDDED */
487 bufattr_delayidlesleep(__unused bufattr_t bap
)
488 #endif /* !CONFIG_EMBEDDED */
491 if ( (bap
->ba_flags
& BA_DELAYIDLESLEEP
) )
493 #endif /* !CONFIG_EMBEDDED */
503 buf_markstatic(buf_t bp __unused
) {
504 SET(bp
->b_flags
, B_STATICCONTENT
);
508 buf_static(buf_t bp
) {
509 if ( (bp
->b_flags
& B_STATICCONTENT
) )
515 buf_error(buf_t bp
) {
517 return (bp
->b_error
);
521 buf_seterror(buf_t bp
, errno_t error
) {
523 if ((bp
->b_error
= error
))
524 SET(bp
->b_flags
, B_ERROR
);
526 CLR(bp
->b_flags
, B_ERROR
);
530 buf_setflags(buf_t bp
, int32_t flags
) {
532 SET(bp
->b_flags
, (flags
& BUF_X_WRFLAGS
));
536 buf_clearflags(buf_t bp
, int32_t flags
) {
538 CLR(bp
->b_flags
, (flags
& BUF_X_WRFLAGS
));
542 buf_flags(buf_t bp
) {
544 return ((bp
->b_flags
& BUF_X_RDFLAGS
));
548 buf_reset(buf_t bp
, int32_t io_flags
) {
550 CLR(bp
->b_flags
, (B_READ
| B_WRITE
| B_ERROR
| B_DONE
| B_INVAL
| B_ASYNC
| B_NOCACHE
| B_FUA
));
551 SET(bp
->b_flags
, (io_flags
& (B_ASYNC
| B_READ
| B_WRITE
| B_NOCACHE
)));
557 buf_count(buf_t bp
) {
559 return (bp
->b_bcount
);
563 buf_setcount(buf_t bp
, uint32_t bcount
) {
565 bp
->b_bcount
= bcount
;
571 return (bp
->b_bufsize
);
575 buf_setsize(buf_t bp
, uint32_t bufsize
) {
577 bp
->b_bufsize
= bufsize
;
581 buf_resid(buf_t bp
) {
583 return (bp
->b_resid
);
587 buf_setresid(buf_t bp
, uint32_t resid
) {
593 buf_dirtyoff(buf_t bp
) {
595 return (bp
->b_dirtyoff
);
599 buf_dirtyend(buf_t bp
) {
601 return (bp
->b_dirtyend
);
605 buf_setdirtyoff(buf_t bp
, uint32_t dirtyoff
) {
607 bp
->b_dirtyoff
= dirtyoff
;
611 buf_setdirtyend(buf_t bp
, uint32_t dirtyend
) {
613 bp
->b_dirtyend
= dirtyend
;
617 buf_dataptr(buf_t bp
) {
619 return (bp
->b_datap
);
623 buf_setdataptr(buf_t bp
, uintptr_t data
) {
629 buf_vnode(buf_t bp
) {
635 buf_setvnode(buf_t bp
, vnode_t vp
) {
642 buf_callback(buf_t bp
)
644 if ( !(bp
->b_flags
& B_CALL
) )
645 return ((void *) NULL
);
647 return ((void *)bp
->b_iodone
);
652 buf_setcallback(buf_t bp
, void (*callback
)(buf_t
, void *), void *transaction
)
655 bp
->b_flags
|= (B_CALL
| B_ASYNC
);
657 bp
->b_flags
&= ~B_CALL
;
658 bp
->b_transaction
= transaction
;
659 bp
->b_iodone
= callback
;
665 buf_setupl(buf_t bp
, upl_t upl
, uint32_t offset
)
668 if ( !(bp
->b_lflags
& BL_IOBUF
) )
672 bp
->b_flags
|= B_CLUSTER
;
674 bp
->b_flags
&= ~B_CLUSTER
;
676 bp
->b_uploffset
= offset
;
682 buf_clone(buf_t bp
, int io_offset
, int io_size
, void (*iodone
)(buf_t
, void *), void *arg
)
686 if (io_offset
< 0 || io_size
< 0)
689 if ((unsigned)(io_offset
+ io_size
) > (unsigned)bp
->b_bcount
)
692 if (bp
->b_flags
& B_CLUSTER
) {
693 if (io_offset
&& ((bp
->b_uploffset
+ io_offset
) & PAGE_MASK
))
696 if (((bp
->b_uploffset
+ io_offset
+ io_size
) & PAGE_MASK
) && ((io_offset
+ io_size
) < bp
->b_bcount
))
699 io_bp
= alloc_io_buf(bp
->b_vp
, 0);
701 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
);
704 io_bp
->b_transaction
= arg
;
705 io_bp
->b_iodone
= iodone
;
706 io_bp
->b_flags
|= B_CALL
;
708 if (bp
->b_flags
& B_CLUSTER
) {
709 io_bp
->b_upl
= bp
->b_upl
;
710 io_bp
->b_uploffset
= bp
->b_uploffset
+ io_offset
;
712 io_bp
->b_datap
= (uintptr_t)(((char *)bp
->b_datap
) + io_offset
);
714 io_bp
->b_bcount
= io_size
;
723 if (bp
->b_lflags
& BL_SHADOW
)
730 buf_create_shadow_priv(buf_t bp
, boolean_t force_copy
, uintptr_t external_storage
, void (*iodone
)(buf_t
, void *), void *arg
)
732 return (buf_create_shadow_internal(bp
, force_copy
, external_storage
, iodone
, arg
, 1));
736 buf_create_shadow(buf_t bp
, boolean_t force_copy
, uintptr_t external_storage
, void (*iodone
)(buf_t
, void *), void *arg
)
738 return (buf_create_shadow_internal(bp
, force_copy
, external_storage
, iodone
, arg
, 0));
743 buf_create_shadow_internal(buf_t bp
, boolean_t force_copy
, uintptr_t external_storage
, void (*iodone
)(buf_t
, void *), void *arg
, int priv
)
747 KERNEL_DEBUG(0xbbbbc000 | DBG_FUNC_START
, bp
, 0, 0, 0, 0);
749 if ( !(bp
->b_flags
& B_META
) || (bp
->b_lflags
& BL_IOBUF
)) {
751 KERNEL_DEBUG(0xbbbbc000 | DBG_FUNC_END
, bp
, 0, 0, 0, 0);
754 #ifdef BUF_MAKE_PRIVATE
755 if (bp
->b_shadow_ref
&& bp
->b_data_ref
== 0 && external_storage
== 0)
756 panic("buf_create_shadow: %p is in the private state (%d, %d)", bp
, bp
->b_shadow_ref
, bp
->b_data_ref
);
758 io_bp
= alloc_io_buf(bp
->b_vp
, priv
);
760 io_bp
->b_flags
= bp
->b_flags
& (B_META
| B_ZALLOC
| B_ASYNC
| B_READ
| B_FUA
);
761 io_bp
->b_blkno
= bp
->b_blkno
;
762 io_bp
->b_lblkno
= bp
->b_lblkno
;
765 io_bp
->b_transaction
= arg
;
766 io_bp
->b_iodone
= iodone
;
767 io_bp
->b_flags
|= B_CALL
;
769 if (force_copy
== FALSE
) {
770 io_bp
->b_bcount
= bp
->b_bcount
;
771 io_bp
->b_bufsize
= bp
->b_bufsize
;
773 if (external_storage
) {
774 io_bp
->b_datap
= external_storage
;
775 #ifdef BUF_MAKE_PRIVATE
776 io_bp
->b_data_store
= NULL
;
779 io_bp
->b_datap
= bp
->b_datap
;
780 #ifdef BUF_MAKE_PRIVATE
781 io_bp
->b_data_store
= bp
;
784 *(buf_t
*)(&io_bp
->b_orig
) = bp
;
786 lck_mtx_lock_spin(buf_mtxp
);
788 io_bp
->b_lflags
|= BL_SHADOW
;
789 io_bp
->b_shadow
= bp
->b_shadow
;
790 bp
->b_shadow
= io_bp
;
793 #ifdef BUF_MAKE_PRIVATE
794 if (external_storage
)
795 io_bp
->b_lflags
|= BL_EXTERNAL
;
799 lck_mtx_unlock(buf_mtxp
);
801 if (external_storage
) {
802 #ifdef BUF_MAKE_PRIVATE
803 io_bp
->b_lflags
|= BL_EXTERNAL
;
805 io_bp
->b_bcount
= bp
->b_bcount
;
806 io_bp
->b_bufsize
= bp
->b_bufsize
;
807 io_bp
->b_datap
= external_storage
;
809 allocbuf(io_bp
, bp
->b_bcount
);
811 io_bp
->b_lflags
|= BL_IOBUF_ALLOC
;
813 bcopy((caddr_t
)bp
->b_datap
, (caddr_t
)io_bp
->b_datap
, bp
->b_bcount
);
815 #ifdef BUF_MAKE_PRIVATE
816 io_bp
->b_data_store
= NULL
;
819 KERNEL_DEBUG(0xbbbbc000 | DBG_FUNC_END
, bp
, bp
->b_shadow_ref
, 0, io_bp
, 0);
825 #ifdef BUF_MAKE_PRIVATE
827 buf_make_private(buf_t bp
)
833 KERNEL_DEBUG(0xbbbbc004 | DBG_FUNC_START
, bp
, bp
->b_shadow_ref
, 0, 0, 0);
835 if (bp
->b_shadow_ref
== 0 || bp
->b_data_ref
== 0 || ISSET(bp
->b_lflags
, BL_SHADOW
)) {
837 KERNEL_DEBUG(0xbbbbc004 | DBG_FUNC_END
, bp
, bp
->b_shadow_ref
, 0, EINVAL
, 0);
840 my_buf
.b_flags
= B_META
;
841 my_buf
.b_datap
= (uintptr_t)NULL
;
842 allocbuf(&my_buf
, bp
->b_bcount
);
844 bcopy((caddr_t
)bp
->b_datap
, (caddr_t
)my_buf
.b_datap
, bp
->b_bcount
);
846 lck_mtx_lock_spin(buf_mtxp
);
848 for (t_bp
= bp
->b_shadow
; t_bp
; t_bp
= t_bp
->b_shadow
) {
849 if ( !ISSET(bp
->b_lflags
, BL_EXTERNAL
))
854 if (ds_bp
== NULL
&& bp
->b_data_ref
)
855 panic("buf_make_private: b_data_ref != 0 && ds_bp == NULL");
857 if (ds_bp
&& (bp
->b_data_ref
== 0 || bp
->b_shadow_ref
== 0))
858 panic("buf_make_private: ref_count == 0 && ds_bp != NULL");
861 lck_mtx_unlock(buf_mtxp
);
863 buf_free_meta_store(&my_buf
);
865 KERNEL_DEBUG(0xbbbbc004 | DBG_FUNC_END
, bp
, bp
->b_shadow_ref
, 0, EINVAL
, 0);
868 for (t_bp
= bp
->b_shadow
; t_bp
; t_bp
= t_bp
->b_shadow
) {
869 if ( !ISSET(t_bp
->b_lflags
, BL_EXTERNAL
))
870 t_bp
->b_data_store
= ds_bp
;
872 ds_bp
->b_data_ref
= bp
->b_data_ref
;
875 bp
->b_datap
= my_buf
.b_datap
;
877 lck_mtx_unlock(buf_mtxp
);
879 KERNEL_DEBUG(0xbbbbc004 | DBG_FUNC_END
, bp
, bp
->b_shadow_ref
, 0, 0, 0);
886 buf_setfilter(buf_t bp
, void (*filter
)(buf_t
, void *), void *transaction
,
887 void (**old_iodone
)(buf_t
, void *), void **old_transaction
)
890 *old_iodone
= bp
->b_iodone
;
892 *old_transaction
= bp
->b_transaction
;
894 bp
->b_transaction
= transaction
;
895 bp
->b_iodone
= filter
;
897 bp
->b_flags
|= B_FILTER
;
899 bp
->b_flags
&= ~B_FILTER
;
904 buf_blkno(buf_t bp
) {
906 return (bp
->b_blkno
);
910 buf_lblkno(buf_t bp
) {
912 return (bp
->b_lblkno
);
916 buf_setblkno(buf_t bp
, daddr64_t blkno
) {
922 buf_setlblkno(buf_t bp
, daddr64_t lblkno
) {
924 bp
->b_lblkno
= lblkno
;
928 buf_device(buf_t bp
) {
934 buf_setdevice(buf_t bp
, vnode_t vp
) {
936 if ((vp
->v_type
!= VBLK
) && (vp
->v_type
!= VCHR
))
938 bp
->b_dev
= vp
->v_rdev
;
945 buf_drvdata(buf_t bp
) {
947 return (bp
->b_drvdata
);
951 buf_setdrvdata(buf_t bp
, void *drvdata
) {
953 bp
->b_drvdata
= drvdata
;
957 buf_fsprivate(buf_t bp
) {
959 return (bp
->b_fsprivate
);
963 buf_setfsprivate(buf_t bp
, void *fsprivate
) {
965 bp
->b_fsprivate
= fsprivate
;
969 buf_rcred(buf_t bp
) {
971 return (bp
->b_rcred
);
975 buf_wcred(buf_t bp
) {
977 return (bp
->b_wcred
);
987 buf_uploffset(buf_t bp
) {
989 return ((uint32_t)(bp
->b_uploffset
));
1000 buf_map(buf_t bp
, caddr_t
*io_addr
)
1006 if ( !(bp
->b_flags
& B_CLUSTER
)) {
1007 *io_addr
= (caddr_t
)bp
->b_datap
;
1010 real_bp
= (buf_t
)(bp
->b_real_bp
);
1012 if (real_bp
&& real_bp
->b_datap
) {
1014 * b_real_bp is only valid if B_CLUSTER is SET
1015 * if it's non-zero, than someone did a cluster_bp call
1016 * if the backing physical pages were already mapped
1017 * in before the call to cluster_bp (non-zero b_datap),
1018 * than we just use that mapping
1020 *io_addr
= (caddr_t
)real_bp
->b_datap
;
1023 kret
= ubc_upl_map(bp
->b_upl
, &vaddr
); /* Map it in */
1025 if (kret
!= KERN_SUCCESS
) {
1030 vaddr
+= bp
->b_uploffset
;
1032 *io_addr
= (caddr_t
)vaddr
;
1043 if ( !(bp
->b_flags
& B_CLUSTER
))
1046 * see buf_map for the explanation
1048 real_bp
= (buf_t
)(bp
->b_real_bp
);
1050 if (real_bp
&& real_bp
->b_datap
)
1053 if ((bp
->b_lflags
& BL_IOBUF
) &&
1054 ((bp
->b_flags
& (B_PAGEIO
| B_READ
)) != (B_PAGEIO
| B_READ
))) {
1056 * ignore pageins... the 'right' thing will
1057 * happen due to the way we handle speculative
1060 * when we commit these pages, we'll hit
1061 * it with UPL_COMMIT_INACTIVE which
1062 * will clear the reference bit that got
1063 * turned on when we touched the mapping
1065 bp
->b_flags
|= B_AGE
;
1067 kret
= ubc_upl_unmap(bp
->b_upl
);
1069 if (kret
!= KERN_SUCCESS
)
1076 buf_clear(buf_t bp
) {
1079 if (buf_map(bp
, &baddr
) == 0) {
1080 bzero(baddr
, bp
->b_bcount
);
1087 * Read or write a buffer that is not contiguous on disk.
1088 * buffer is marked done/error at the conclusion
1091 buf_strategy_fragmented(vnode_t devvp
, buf_t bp
, off_t f_offset
, size_t contig_bytes
)
1093 vnode_t vp
= buf_vnode(bp
);
1094 buf_t io_bp
; /* For reading or writing a single block */
1097 size_t io_contig_bytes
;
1103 * save our starting point... the bp was already mapped
1104 * in buf_strategy before we got called
1105 * no sense doing it again.
1107 io_blkno
= bp
->b_blkno
;
1109 * Make sure we redo this mapping for the next I/O
1110 * i.e. this can never be a 'permanent' mapping
1112 bp
->b_blkno
= bp
->b_lblkno
;
1115 * Get an io buffer to do the deblocking
1117 io_bp
= alloc_io_buf(devvp
, 0);
1119 io_bp
->b_lblkno
= bp
->b_lblkno
;
1120 io_bp
->b_datap
= bp
->b_datap
;
1121 io_resid
= bp
->b_bcount
;
1122 io_direction
= bp
->b_flags
& B_READ
;
1123 io_contig_bytes
= contig_bytes
;
1125 if (bp
->b_flags
& B_READ
)
1126 bmap_flags
= VNODE_READ
;
1128 bmap_flags
= VNODE_WRITE
;
1133 * this is unexepected, but we'll allow for it
1135 bzero((caddr_t
)io_bp
->b_datap
, (int)io_contig_bytes
);
1137 io_bp
->b_bcount
= io_contig_bytes
;
1138 io_bp
->b_bufsize
= io_contig_bytes
;
1139 io_bp
->b_resid
= io_contig_bytes
;
1140 io_bp
->b_blkno
= io_blkno
;
1142 buf_reset(io_bp
, io_direction
);
1145 * Call the device to do the I/O and wait for it. Make sure the appropriate party is charged for write
1148 if (!ISSET(bp
->b_flags
, B_READ
))
1149 OSAddAtomic(1, &devvp
->v_numoutput
);
1151 if ((error
= VNOP_STRATEGY(io_bp
)))
1153 if ((error
= (int)buf_biowait(io_bp
)))
1155 if (io_bp
->b_resid
) {
1156 io_resid
-= (io_contig_bytes
- io_bp
->b_resid
);
1160 if ((io_resid
-= io_contig_bytes
) == 0)
1162 f_offset
+= io_contig_bytes
;
1163 io_bp
->b_datap
+= io_contig_bytes
;
1166 * Map the current position to a physical block number
1168 if ((error
= VNOP_BLOCKMAP(vp
, f_offset
, io_resid
, &io_blkno
, &io_contig_bytes
, NULL
, bmap_flags
, NULL
)))
1174 buf_seterror(bp
, error
);
1175 bp
->b_resid
= io_resid
;
1177 * This I/O is now complete
1186 * struct vnop_strategy_args {
1191 buf_strategy(vnode_t devvp
, void *ap
)
1193 buf_t bp
= ((struct vnop_strategy_args
*)ap
)->a_bp
;
1194 vnode_t vp
= bp
->b_vp
;
1198 int dtrace_io_start_flag
= 0; /* We only want to trip the io:::start
1199 * probe once, with the true phisical
1200 * block in place (b_blkno)
1205 if (vp
== NULL
|| vp
->v_type
== VCHR
|| vp
->v_type
== VBLK
)
1206 panic("buf_strategy: b_vp == NULL || vtype == VCHR | VBLK\n");
1208 * associate the physical device with
1209 * with this buf_t even if we don't
1210 * end up issuing the I/O...
1212 bp
->b_dev
= devvp
->v_rdev
;
1214 if (bp
->b_flags
& B_READ
)
1215 bmap_flags
= VNODE_READ
;
1217 bmap_flags
= VNODE_WRITE
;
1219 if ( !(bp
->b_flags
& B_CLUSTER
)) {
1221 if ( (bp
->b_upl
) ) {
1223 * we have a UPL associated with this bp
1224 * go through cluster_bp which knows how
1225 * to deal with filesystem block sizes
1226 * that aren't equal to the page size
1228 DTRACE_IO1(start
, buf_t
, bp
);
1229 return (cluster_bp(bp
));
1231 if (bp
->b_blkno
== bp
->b_lblkno
) {
1233 size_t contig_bytes
;
1235 if ((error
= VNOP_BLKTOOFF(vp
, bp
->b_lblkno
, &f_offset
))) {
1236 DTRACE_IO1(start
, buf_t
, bp
);
1237 buf_seterror(bp
, error
);
1243 if ((error
= VNOP_BLOCKMAP(vp
, f_offset
, bp
->b_bcount
, &bp
->b_blkno
, &contig_bytes
, NULL
, bmap_flags
, NULL
))) {
1244 DTRACE_IO1(start
, buf_t
, bp
);
1245 buf_seterror(bp
, error
);
1251 DTRACE_IO1(start
, buf_t
, bp
);
1253 dtrace_io_start_flag
= 1;
1254 #endif /* CONFIG_DTRACE */
1256 if ((bp
->b_blkno
== -1) || (contig_bytes
== 0)) {
1257 /* Set block number to force biodone later */
1261 else if ((long)contig_bytes
< bp
->b_bcount
) {
1262 return (buf_strategy_fragmented(devvp
, bp
, f_offset
, contig_bytes
));
1267 if (dtrace_io_start_flag
== 0) {
1268 DTRACE_IO1(start
, buf_t
, bp
);
1269 dtrace_io_start_flag
= 1;
1271 #endif /* CONFIG_DTRACE */
1273 if (bp
->b_blkno
== -1) {
1280 if (dtrace_io_start_flag
== 0)
1281 DTRACE_IO1(start
, buf_t
, bp
);
1282 #endif /* CONFIG_DTRACE */
1285 /* Capture f_offset in the bufattr*/
1286 if (bp
->b_attr
.ba_cpentry
!= 0) {
1287 /* No need to go here for older EAs */
1288 if(bp
->b_attr
.ba_cpentry
->cp_flags
& CP_OFF_IV_ENABLED
) {
1290 if ((error
= VNOP_BLKTOOFF(bp
->b_vp
, bp
->b_lblkno
, &f_offset
)))
1294 * Attach the file offset to this buffer. The
1295 * bufattr attributes will be passed down the stack
1296 * until they reach IOFlashStorage. IOFlashStorage
1297 * will retain the offset in a local variable when it
1298 * issues its I/Os to the NAND controller.
1300 * Note that LwVM may end up splitting this I/O
1301 * into sub-I/Os if it crosses a chunk boundary. In this
1302 * case, LwVM will update this field when it dispatches
1303 * each I/O to IOFlashStorage. But from our perspective
1304 * we have only issued a single I/O.
1306 bufattr_setcpoff (&(bp
->b_attr
), (u_int64_t
)f_offset
);
1312 * we can issue the I/O because...
1313 * either B_CLUSTER is set which
1314 * means that the I/O is properly set
1315 * up to be a multiple of the page size, or
1316 * we were able to successfully set up the
1317 * phsyical block mapping
1319 return (VOCALL(devvp
->v_op
, VOFFSET(vnop_strategy
), ap
));
1325 buf_alloc(vnode_t vp
)
1327 return(alloc_io_buf(vp
, 0));
1331 buf_free(buf_t bp
) {
1338 * iterate buffers for the specified vp.
1339 * if BUF_SCAN_DIRTY is set, do the dirty list
1340 * if BUF_SCAN_CLEAN is set, do the clean list
1341 * if neither flag is set, default to BUF_SCAN_DIRTY
1342 * if BUF_NOTIFY_BUSY is set, call the callout function using a NULL bp for busy pages
1345 struct buf_iterate_info_t
{
1347 struct buflists
*listhead
;
1351 buf_iterate(vnode_t vp
, int (*callout
)(buf_t
, void *), int flags
, void *arg
)
1355 struct buflists local_iterblkhd
;
1356 int lock_flags
= BAC_NOWAIT
| BAC_REMOVE
;
1357 int notify_busy
= flags
& BUF_NOTIFY_BUSY
;
1358 struct buf_iterate_info_t list
[2];
1361 if (flags
& BUF_SKIP_LOCKED
)
1362 lock_flags
|= BAC_SKIP_LOCKED
;
1363 if (flags
& BUF_SKIP_NONLOCKED
)
1364 lock_flags
|= BAC_SKIP_NONLOCKED
;
1366 if ( !(flags
& (BUF_SCAN_DIRTY
| BUF_SCAN_CLEAN
)))
1367 flags
|= BUF_SCAN_DIRTY
;
1371 if (flags
& BUF_SCAN_DIRTY
) {
1372 list
[num_lists
].flag
= VBI_DIRTY
;
1373 list
[num_lists
].listhead
= &vp
->v_dirtyblkhd
;
1376 if (flags
& BUF_SCAN_CLEAN
) {
1377 list
[num_lists
].flag
= VBI_CLEAN
;
1378 list
[num_lists
].listhead
= &vp
->v_cleanblkhd
;
1382 for (i
= 0; i
< num_lists
; i
++) {
1383 lck_mtx_lock(buf_mtxp
);
1385 if (buf_iterprepare(vp
, &local_iterblkhd
, list
[i
].flag
)) {
1386 lck_mtx_unlock(buf_mtxp
);
1389 while (!LIST_EMPTY(&local_iterblkhd
)) {
1390 bp
= LIST_FIRST(&local_iterblkhd
);
1391 LIST_REMOVE(bp
, b_vnbufs
);
1392 LIST_INSERT_HEAD(list
[i
].listhead
, bp
, b_vnbufs
);
1394 if (buf_acquire_locked(bp
, lock_flags
, 0, 0)) {
1402 lck_mtx_unlock(buf_mtxp
);
1404 retval
= callout(bp
, arg
);
1413 case BUF_RETURNED_DONE
:
1416 lck_mtx_lock(buf_mtxp
);
1418 case BUF_CLAIMED_DONE
:
1419 lck_mtx_lock(buf_mtxp
);
1422 lck_mtx_lock(buf_mtxp
);
1423 } /* while list has more nodes */
1425 buf_itercomplete(vp
, &local_iterblkhd
, list
[i
].flag
);
1426 lck_mtx_unlock(buf_mtxp
);
1427 } /* for each list */
1432 * Flush out and invalidate all buffers associated with a vnode.
1435 buf_invalidateblks(vnode_t vp
, int flags
, int slpflag
, int slptimeo
)
1440 int must_rescan
= 1;
1441 struct buflists local_iterblkhd
;
1444 if (LIST_EMPTY(&vp
->v_cleanblkhd
) && LIST_EMPTY(&vp
->v_dirtyblkhd
))
1447 lck_mtx_lock(buf_mtxp
);
1450 if (must_rescan
== 0)
1452 * the lists may not be empty, but all that's left at this
1453 * point are metadata or B_LOCKED buffers which are being
1454 * skipped... we know this because we made it through both
1455 * the clean and dirty lists without dropping buf_mtxp...
1456 * each time we drop buf_mtxp we bump "must_rescan"
1459 if (LIST_EMPTY(&vp
->v_cleanblkhd
) && LIST_EMPTY(&vp
->v_dirtyblkhd
))
1463 * iterate the clean list
1465 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_CLEAN
)) {
1466 goto try_dirty_list
;
1468 while (!LIST_EMPTY(&local_iterblkhd
)) {
1470 bp
= LIST_FIRST(&local_iterblkhd
);
1472 LIST_REMOVE(bp
, b_vnbufs
);
1473 LIST_INSERT_HEAD(&vp
->v_cleanblkhd
, bp
, b_vnbufs
);
1476 * some filesystems distinguish meta data blocks with a negative logical block #
1478 if ((flags
& BUF_SKIP_META
) && (bp
->b_lblkno
< 0 || ISSET(bp
->b_flags
, B_META
)))
1481 aflags
= BAC_REMOVE
;
1483 if ( !(flags
& BUF_INVALIDATE_LOCKED
) )
1484 aflags
|= BAC_SKIP_LOCKED
;
1486 if ( (error
= (int)buf_acquire_locked(bp
, aflags
, slpflag
, slptimeo
)) ) {
1487 if (error
== EDEADLK
)
1489 * this buffer was marked B_LOCKED...
1490 * we didn't drop buf_mtxp, so we
1491 * we don't need to rescan
1494 if (error
== EAGAIN
) {
1496 * found a busy buffer... we blocked and
1497 * dropped buf_mtxp, so we're going to
1498 * need to rescan after this pass is completed
1504 * got some kind of 'real' error out of the msleep
1505 * in buf_acquire_locked, terminate the scan and return the error
1507 buf_itercomplete(vp
, &local_iterblkhd
, VBI_CLEAN
);
1509 lck_mtx_unlock(buf_mtxp
);
1512 lck_mtx_unlock(buf_mtxp
);
1514 if (bp
->b_flags
& B_LOCKED
)
1515 KERNEL_DEBUG(0xbbbbc038, bp
, 0, 0, 0, 0);
1517 CLR(bp
->b_flags
, B_LOCKED
);
1518 SET(bp
->b_flags
, B_INVAL
);
1521 lck_mtx_lock(buf_mtxp
);
1524 * by dropping buf_mtxp, we allow new
1525 * buffers to be added to the vnode list(s)
1526 * we'll have to rescan at least once more
1527 * if the queues aren't empty
1531 buf_itercomplete(vp
, &local_iterblkhd
, VBI_CLEAN
);
1535 * Now iterate on dirty blks
1537 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_DIRTY
)) {
1540 while (!LIST_EMPTY(&local_iterblkhd
)) {
1541 bp
= LIST_FIRST(&local_iterblkhd
);
1543 LIST_REMOVE(bp
, b_vnbufs
);
1544 LIST_INSERT_HEAD(&vp
->v_dirtyblkhd
, bp
, b_vnbufs
);
1547 * some filesystems distinguish meta data blocks with a negative logical block #
1549 if ((flags
& BUF_SKIP_META
) && (bp
->b_lblkno
< 0 || ISSET(bp
->b_flags
, B_META
)))
1552 aflags
= BAC_REMOVE
;
1554 if ( !(flags
& BUF_INVALIDATE_LOCKED
) )
1555 aflags
|= BAC_SKIP_LOCKED
;
1557 if ( (error
= (int)buf_acquire_locked(bp
, aflags
, slpflag
, slptimeo
)) ) {
1558 if (error
== EDEADLK
)
1560 * this buffer was marked B_LOCKED...
1561 * we didn't drop buf_mtxp, so we
1562 * we don't need to rescan
1565 if (error
== EAGAIN
) {
1567 * found a busy buffer... we blocked and
1568 * dropped buf_mtxp, so we're going to
1569 * need to rescan after this pass is completed
1575 * got some kind of 'real' error out of the msleep
1576 * in buf_acquire_locked, terminate the scan and return the error
1578 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1580 lck_mtx_unlock(buf_mtxp
);
1583 lck_mtx_unlock(buf_mtxp
);
1585 if (bp
->b_flags
& B_LOCKED
)
1586 KERNEL_DEBUG(0xbbbbc038, bp
, 0, 0, 1, 0);
1588 CLR(bp
->b_flags
, B_LOCKED
);
1589 SET(bp
->b_flags
, B_INVAL
);
1591 if (ISSET(bp
->b_flags
, B_DELWRI
) && (flags
& BUF_WRITE_DATA
))
1592 (void) VNOP_BWRITE(bp
);
1596 lck_mtx_lock(buf_mtxp
);
1598 * by dropping buf_mtxp, we allow new
1599 * buffers to be added to the vnode list(s)
1600 * we'll have to rescan at least once more
1601 * if the queues aren't empty
1605 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1607 lck_mtx_unlock(buf_mtxp
);
1613 buf_flushdirtyblks(vnode_t vp
, int wait
, int flags
, const char *msg
) {
1615 (void) buf_flushdirtyblks_skipinfo(vp
, wait
, flags
, msg
);
1620 buf_flushdirtyblks_skipinfo(vnode_t vp
, int wait
, int flags
, const char *msg
) {
1622 int writes_issued
= 0;
1625 struct buflists local_iterblkhd
;
1626 int lock_flags
= BAC_NOWAIT
| BAC_REMOVE
;
1629 if (flags
& BUF_SKIP_LOCKED
)
1630 lock_flags
|= BAC_SKIP_LOCKED
;
1631 if (flags
& BUF_SKIP_NONLOCKED
)
1632 lock_flags
|= BAC_SKIP_NONLOCKED
;
1634 lck_mtx_lock(buf_mtxp
);
1636 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_DIRTY
) == 0) {
1637 while (!LIST_EMPTY(&local_iterblkhd
)) {
1638 bp
= LIST_FIRST(&local_iterblkhd
);
1639 LIST_REMOVE(bp
, b_vnbufs
);
1640 LIST_INSERT_HEAD(&vp
->v_dirtyblkhd
, bp
, b_vnbufs
);
1642 if ((error
= buf_acquire_locked(bp
, lock_flags
, 0, 0)) == EBUSY
) {
1647 * If we passed in BUF_SKIP_LOCKED or BUF_SKIP_NONLOCKED,
1648 * we may want to do somethign differently if a locked or unlocked
1649 * buffer was encountered (depending on the arg specified).
1650 * In this case, we know that one of those two was set, and the
1651 * buf acquisition failed above.
1653 * If it failed with EDEADLK, then save state which can be emitted
1654 * later on to the caller. Most callers should not care.
1656 if (error
== EDEADLK
) {
1661 lck_mtx_unlock(buf_mtxp
);
1663 bp
->b_flags
&= ~B_LOCKED
;
1666 * Wait for I/O associated with indirect blocks to complete,
1667 * since there is no way to quickly wait for them below.
1669 if ((bp
->b_vp
== vp
) || (wait
== 0))
1670 (void) buf_bawrite(bp
);
1672 (void) VNOP_BWRITE(bp
);
1675 lck_mtx_lock(buf_mtxp
);
1677 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1679 lck_mtx_unlock(buf_mtxp
);
1682 (void)vnode_waitforwrites(vp
, 0, 0, 0, msg
);
1684 if (vp
->v_dirtyblkhd
.lh_first
&& busy
) {
1686 * we had one or more BUSY buffers on
1687 * the dirtyblock list... most likely
1688 * these are due to delayed writes that
1689 * were moved to the bclean queue but
1690 * have not yet been 'written'.
1691 * if we issued some writes on the
1692 * previous pass, we try again immediately
1693 * if we didn't, we'll sleep for some time
1694 * to allow the state to change...
1696 if (writes_issued
== 0) {
1697 (void)tsleep((caddr_t
)&vp
->v_numoutput
,
1698 PRIBIO
+ 1, "vnode_flushdirtyblks", hz
/20);
1712 * called with buf_mtxp held...
1713 * this lock protects the queue manipulation
1716 buf_iterprepare(vnode_t vp
, struct buflists
*iterheadp
, int flags
)
1718 struct buflists
* listheadp
;
1720 if (flags
& VBI_DIRTY
)
1721 listheadp
= &vp
->v_dirtyblkhd
;
1723 listheadp
= &vp
->v_cleanblkhd
;
1725 while (vp
->v_iterblkflags
& VBI_ITER
) {
1726 vp
->v_iterblkflags
|= VBI_ITERWANT
;
1727 msleep(&vp
->v_iterblkflags
, buf_mtxp
, 0, "buf_iterprepare", NULL
);
1729 if (LIST_EMPTY(listheadp
)) {
1730 LIST_INIT(iterheadp
);
1733 vp
->v_iterblkflags
|= VBI_ITER
;
1735 iterheadp
->lh_first
= listheadp
->lh_first
;
1736 listheadp
->lh_first
->b_vnbufs
.le_prev
= &iterheadp
->lh_first
;
1737 LIST_INIT(listheadp
);
1743 * called with buf_mtxp held...
1744 * this lock protects the queue manipulation
1747 buf_itercomplete(vnode_t vp
, struct buflists
*iterheadp
, int flags
)
1749 struct buflists
* listheadp
;
1752 if (flags
& VBI_DIRTY
)
1753 listheadp
= &vp
->v_dirtyblkhd
;
1755 listheadp
= &vp
->v_cleanblkhd
;
1757 while (!LIST_EMPTY(iterheadp
)) {
1758 bp
= LIST_FIRST(iterheadp
);
1759 LIST_REMOVE(bp
, b_vnbufs
);
1760 LIST_INSERT_HEAD(listheadp
, bp
, b_vnbufs
);
1762 vp
->v_iterblkflags
&= ~VBI_ITER
;
1764 if (vp
->v_iterblkflags
& VBI_ITERWANT
) {
1765 vp
->v_iterblkflags
&= ~VBI_ITERWANT
;
1766 wakeup(&vp
->v_iterblkflags
);
1772 bremfree_locked(buf_t bp
)
1774 struct bqueues
*dp
= NULL
;
1777 whichq
= bp
->b_whichq
;
1780 if (bp
->b_shadow_ref
== 0)
1781 panic("bremfree_locked: %p not on freelist", bp
);
1783 * there are clones pointing to 'bp'...
1784 * therefore, it was not put on a freelist
1785 * when buf_brelse was last called on 'bp'
1790 * We only calculate the head of the freelist when removing
1791 * the last element of the list as that is the only time that
1792 * it is needed (e.g. to reset the tail pointer).
1794 * NB: This makes an assumption about how tailq's are implemented.
1796 if (bp
->b_freelist
.tqe_next
== NULL
) {
1797 dp
= &bufqueues
[whichq
];
1799 if (dp
->tqh_last
!= &bp
->b_freelist
.tqe_next
)
1800 panic("bremfree: lost tail");
1802 TAILQ_REMOVE(dp
, bp
, b_freelist
);
1807 if (whichq
== BQ_LAUNDRY
)
1811 bp
->b_timestamp
= 0;
1816 * Associate a buffer with a vnode.
1817 * buf_mtxp must be locked on entry
1820 bgetvp_locked(vnode_t vp
, buf_t bp
)
1824 panic("bgetvp_locked: not free");
1826 if (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
)
1827 bp
->b_dev
= vp
->v_rdev
;
1831 * Insert onto list for new vnode.
1833 bufinsvn(bp
, &vp
->v_cleanblkhd
);
1837 * Disassociate a buffer from a vnode.
1838 * buf_mtxp must be locked on entry
1841 brelvp_locked(buf_t bp
)
1844 * Delete from old vnode list, if on one.
1846 if (bp
->b_vnbufs
.le_next
!= NOLIST
)
1849 bp
->b_vp
= (vnode_t
)NULL
;
1853 * Reassign a buffer from one vnode to another.
1854 * Used to assign file specific control information
1855 * (indirect blocks) to the vnode to which they belong.
1858 buf_reassign(buf_t bp
, vnode_t newvp
)
1860 struct buflists
*listheadp
;
1862 if (newvp
== NULL
) {
1863 printf("buf_reassign: NULL");
1866 lck_mtx_lock_spin(buf_mtxp
);
1869 * Delete from old vnode list, if on one.
1871 if (bp
->b_vnbufs
.le_next
!= NOLIST
)
1874 * If dirty, put on list of dirty buffers;
1875 * otherwise insert onto list of clean buffers.
1877 if (ISSET(bp
->b_flags
, B_DELWRI
))
1878 listheadp
= &newvp
->v_dirtyblkhd
;
1880 listheadp
= &newvp
->v_cleanblkhd
;
1881 bufinsvn(bp
, listheadp
);
1883 lck_mtx_unlock(buf_mtxp
);
1886 static __inline__
void
1887 bufhdrinit(buf_t bp
)
1889 bzero((char *)bp
, sizeof *bp
);
1891 bp
->b_rcred
= NOCRED
;
1892 bp
->b_wcred
= NOCRED
;
1893 bp
->b_vnbufs
.le_next
= NOLIST
;
1894 bp
->b_flags
= B_INVAL
;
1900 * Initialize buffers and hash links for buffers.
1902 __private_extern__
void
1910 /* Initialize the buffer queues ('freelists') and the hash table */
1911 for (dp
= bufqueues
; dp
< &bufqueues
[BQUEUES
]; dp
++)
1913 bufhashtbl
= hashinit(nbuf_hashelements
, M_CACHE
, &bufhash
);
1917 /* Initialize the buffer headers */
1918 for (i
= 0; i
< max_nbuf_headers
; i
++) {
1920 bp
= &buf_headers
[i
];
1924 dp
= &bufqueues
[BQ_EMPTY
];
1925 bp
->b_whichq
= BQ_EMPTY
;
1926 bp
->b_timestamp
= buf_timestamp();
1927 binsheadfree(bp
, dp
, BQ_EMPTY
);
1928 binshash(bp
, &invalhash
);
1930 boot_nbuf_headers
= nbuf_headers
;
1932 TAILQ_INIT(&iobufqueue
);
1933 TAILQ_INIT(&delaybufqueue
);
1935 for (; i
< nbuf_headers
+ niobuf_headers
; i
++) {
1936 bp
= &buf_headers
[i
];
1939 binsheadfree(bp
, &iobufqueue
, -1);
1943 * allocate lock group attribute and group
1945 buf_mtx_grp_attr
= lck_grp_attr_alloc_init();
1946 buf_mtx_grp
= lck_grp_alloc_init("buffer cache", buf_mtx_grp_attr
);
1949 * allocate the lock attribute
1951 buf_mtx_attr
= lck_attr_alloc_init();
1954 * allocate and initialize mutex's for the buffer and iobuffer pools
1956 buf_mtxp
= lck_mtx_alloc_init(buf_mtx_grp
, buf_mtx_attr
);
1957 iobuffer_mtxp
= lck_mtx_alloc_init(buf_mtx_grp
, buf_mtx_attr
);
1959 if (iobuffer_mtxp
== NULL
)
1960 panic("couldn't create iobuffer mutex");
1962 if (buf_mtxp
== NULL
)
1963 panic("couldn't create buf mutex");
1966 * allocate and initialize cluster specific global locks...
1970 printf("using %d buffer headers and %d cluster IO buffer headers\n",
1971 nbuf_headers
, niobuf_headers
);
1973 /* Set up zones used by the buffer cache */
1976 /* start the bcleanbuf() thread */
1977 bcleanbuf_thread_init();
1979 /* Register a callout for relieving vm pressure */
1980 if (vm_set_buffer_cleanup_callout(buffer_cache_gc
) != KERN_SUCCESS
) {
1981 panic("Couldn't register buffer cache callout for vm pressure!\n");
1986 static void bufq_balance_thread_init(void) __attribute__((section("__TEXT, initcode")));
1987 /* create a thread to do dynamic buffer queue balancing */
1988 bufq_balance_thread_init();
1996 * Zones for the meta data buffers
2000 #define MAXMETA 8192
2002 struct meta_zone_entry
{
2006 const char *mz_name
;
2009 struct meta_zone_entry meta_zones
[] = {
2010 {NULL
, (MINMETA
* 1), 128 * (MINMETA
* 1), "buf.512" },
2011 {NULL
, (MINMETA
* 2), 64 * (MINMETA
* 2), "buf.1024" },
2012 {NULL
, (MINMETA
* 4), 16 * (MINMETA
* 4), "buf.2048" },
2013 {NULL
, (MINMETA
* 8), 512 * (MINMETA
* 8), "buf.4096" },
2014 {NULL
, (MINMETA
* 16), 512 * (MINMETA
* 16), "buf.8192" },
2015 {NULL
, 0, 0, "" } /* End */
2019 * Initialize the meta data zones
2026 for (i
= 0; meta_zones
[i
].mz_size
!= 0; i
++) {
2027 meta_zones
[i
].mz_zone
=
2028 zinit(meta_zones
[i
].mz_size
,
2029 meta_zones
[i
].mz_max
,
2031 meta_zones
[i
].mz_name
);
2032 zone_change(meta_zones
[i
].mz_zone
, Z_CALLERACCT
, FALSE
);
2034 buf_hdr_zone
= zinit(sizeof(struct buf
), 32, PAGE_SIZE
, "buf headers");
2035 zone_change(buf_hdr_zone
, Z_CALLERACCT
, FALSE
);
2038 static __inline__ zone_t
2039 getbufzone(size_t size
)
2043 if ((size
% 512) || (size
< MINMETA
) || (size
> MAXMETA
))
2044 panic("getbufzone: incorect size = %lu", size
);
2046 for (i
= 0; meta_zones
[i
].mz_size
!= 0; i
++) {
2047 if (meta_zones
[i
].mz_size
>= size
)
2051 return (meta_zones
[i
].mz_zone
);
2057 bio_doread(vnode_t vp
, daddr64_t blkno
, int size
, kauth_cred_t cred
, int async
, int queuetype
)
2061 bp
= buf_getblk(vp
, blkno
, size
, 0, 0, queuetype
);
2064 * If buffer does not have data valid, start a read.
2065 * Note that if buffer is B_INVAL, buf_getblk() won't return it.
2066 * Therefore, it's valid if it's I/O has completed or been delayed.
2068 if (!ISSET(bp
->b_flags
, (B_DONE
| B_DELWRI
))) {
2073 /* Start I/O for the buffer (keeping credentials). */
2074 SET(bp
->b_flags
, B_READ
| async
);
2075 if (IS_VALID_CRED(cred
) && !IS_VALID_CRED(bp
->b_rcred
)) {
2076 kauth_cred_ref(cred
);
2082 trace(TR_BREADMISS
, pack(vp
, size
), blkno
);
2084 /* Pay for the read. */
2085 if (p
&& p
->p_stats
)
2086 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_inblock
); /* XXX */
2090 * since we asked for an ASYNC I/O
2091 * the biodone will do the brelse
2092 * we don't want to pass back a bp
2093 * that we don't 'own'
2102 trace(TR_BREADHIT
, pack(vp
, size
), blkno
);
2108 * Perform the reads for buf_breadn() and buf_meta_breadn().
2109 * Trivial modification to the breada algorithm presented in Bach (p.55).
2112 do_breadn_for_type(vnode_t vp
, daddr64_t blkno
, int size
, daddr64_t
*rablks
, int *rasizes
,
2113 int nrablks
, kauth_cred_t cred
, buf_t
*bpp
, int queuetype
)
2118 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, queuetype
);
2121 * For each of the read-ahead blocks, start a read, if necessary.
2123 for (i
= 0; i
< nrablks
; i
++) {
2124 /* If it's in the cache, just go on to next one. */
2125 if (incore(vp
, rablks
[i
]))
2128 /* Get a buffer for the read-ahead block */
2129 (void) bio_doread(vp
, rablks
[i
], rasizes
[i
], cred
, B_ASYNC
, queuetype
);
2132 /* Otherwise, we had to start a read for it; wait until it's valid. */
2133 return (buf_biowait(bp
));
2138 * Read a disk block.
2139 * This algorithm described in Bach (p.54).
2142 buf_bread(vnode_t vp
, daddr64_t blkno
, int size
, kauth_cred_t cred
, buf_t
*bpp
)
2146 /* Get buffer for block. */
2147 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, BLK_READ
);
2149 /* Wait for the read to complete, and return result. */
2150 return (buf_biowait(bp
));
2154 * Read a disk block. [bread() for meta-data]
2155 * This algorithm described in Bach (p.54).
2158 buf_meta_bread(vnode_t vp
, daddr64_t blkno
, int size
, kauth_cred_t cred
, buf_t
*bpp
)
2162 /* Get buffer for block. */
2163 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, BLK_META
);
2165 /* Wait for the read to complete, and return result. */
2166 return (buf_biowait(bp
));
2170 * Read-ahead multiple disk blocks. The first is sync, the rest async.
2173 buf_breadn(vnode_t vp
, daddr64_t blkno
, int size
, daddr64_t
*rablks
, int *rasizes
, int nrablks
, kauth_cred_t cred
, buf_t
*bpp
)
2175 return (do_breadn_for_type(vp
, blkno
, size
, rablks
, rasizes
, nrablks
, cred
, bpp
, BLK_READ
));
2179 * Read-ahead multiple disk blocks. The first is sync, the rest async.
2180 * [buf_breadn() for meta-data]
2183 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
)
2185 return (do_breadn_for_type(vp
, blkno
, size
, rablks
, rasizes
, nrablks
, cred
, bpp
, BLK_META
));
2189 * Block write. Described in Bach (p.56)
2192 buf_bwrite(buf_t bp
)
2194 int sync
, wasdelayed
;
2196 proc_t p
= current_proc();
2197 vnode_t vp
= bp
->b_vp
;
2199 if (bp
->b_datap
== 0) {
2200 if (brecover_data(bp
) == 0)
2203 /* Remember buffer type, to switch on it later. */
2204 sync
= !ISSET(bp
->b_flags
, B_ASYNC
);
2205 wasdelayed
= ISSET(bp
->b_flags
, B_DELWRI
);
2206 CLR(bp
->b_flags
, (B_READ
| B_DONE
| B_ERROR
| B_DELWRI
));
2209 OSAddAtomicLong(-1, &nbdwrite
);
2213 * If not synchronous, pay for the I/O operation and make
2214 * sure the buf is on the correct vnode queue. We have
2215 * to do this now, because if we don't, the vnode may not
2216 * be properly notified that its I/O has completed.
2219 buf_reassign(bp
, vp
);
2221 if (p
&& p
->p_stats
)
2222 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_oublock
); /* XXX */
2224 trace(TR_BUFWRITE
, pack(vp
, bp
->b_bcount
), bp
->b_lblkno
);
2226 /* Initiate disk write. Make sure the appropriate party is charged. */
2228 OSAddAtomic(1, &vp
->v_numoutput
);
2234 * If I/O was synchronous, wait for it to complete.
2236 rv
= buf_biowait(bp
);
2239 * Pay for the I/O operation, if it's not been paid for, and
2240 * make sure it's on the correct vnode queue. (async operatings
2241 * were payed for above.)
2244 buf_reassign(bp
, vp
);
2246 if (p
&& p
->p_stats
)
2247 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_oublock
); /* XXX */
2249 /* Release the buffer. */
2250 // XXXdbg - only if the unused bit is set
2251 if (!ISSET(bp
->b_flags
, B_NORELSE
)) {
2254 CLR(bp
->b_flags
, B_NORELSE
);
2264 vn_bwrite(struct vnop_bwrite_args
*ap
)
2266 return (buf_bwrite(ap
->a_bp
));
2272 * The buffer is marked dirty, but is not queued for I/O.
2273 * This routine should be used when the buffer is expected
2274 * to be modified again soon, typically a small write that
2275 * partially fills a buffer.
2277 * NB: magnetic tapes cannot be delayed; they must be
2278 * written in the order that the writes are requested.
2280 * Described in Leffler, et al. (pp. 208-213).
2282 * Note: With the ability to allocate additional buffer
2283 * headers, we can get in to the situation where "too" many
2284 * buf_bdwrite()s can create situation where the kernel can create
2285 * buffers faster than the disks can service. Doing a buf_bawrite() in
2286 * cases where we have "too many" outstanding buf_bdwrite()s avoids that.
2288 __private_extern__
int
2289 bdwrite_internal(buf_t bp
, int return_error
)
2291 proc_t p
= current_proc();
2292 vnode_t vp
= bp
->b_vp
;
2295 * If the block hasn't been seen before:
2296 * (1) Mark it as having been seen,
2297 * (2) Charge for the write.
2298 * (3) Make sure it's on its vnode's correct block list,
2300 if (!ISSET(bp
->b_flags
, B_DELWRI
)) {
2301 SET(bp
->b_flags
, B_DELWRI
);
2302 if (p
&& p
->p_stats
)
2303 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_oublock
); /* XXX */
2304 OSAddAtomicLong(1, &nbdwrite
);
2305 buf_reassign(bp
, vp
);
2309 * if we're not LOCKED, but the total number of delayed writes
2310 * has climbed above 75% of the total buffers in the system
2311 * return an error if the caller has indicated that it can
2312 * handle one in this case, otherwise schedule the I/O now
2313 * this is done to prevent us from allocating tons of extra
2314 * buffers when dealing with virtual disks (i.e. DiskImages),
2315 * because additional buffers are dynamically allocated to prevent
2316 * deadlocks from occurring
2318 * however, can't do a buf_bawrite() if the LOCKED bit is set because the
2319 * buffer is part of a transaction and can't go to disk until
2320 * the LOCKED bit is cleared.
2322 if (!ISSET(bp
->b_flags
, B_LOCKED
) && nbdwrite
> ((nbuf_headers
/4)*3)) {
2326 * If the vnode has "too many" write operations in progress
2327 * wait for them to finish the IO
2329 (void)vnode_waitforwrites(vp
, VNODE_ASYNC_THROTTLE
, 0, 0, "buf_bdwrite");
2331 return (buf_bawrite(bp
));
2334 /* Otherwise, the "write" is done, so mark and release the buffer. */
2335 SET(bp
->b_flags
, B_DONE
);
2341 buf_bdwrite(buf_t bp
)
2343 return (bdwrite_internal(bp
, 0));
2348 * Asynchronous block write; just an asynchronous buf_bwrite().
2350 * Note: With the abilitty to allocate additional buffer
2351 * headers, we can get in to the situation where "too" many
2352 * buf_bawrite()s can create situation where the kernel can create
2353 * buffers faster than the disks can service.
2354 * We limit the number of "in flight" writes a vnode can have to
2358 bawrite_internal(buf_t bp
, int throttle
)
2360 vnode_t vp
= bp
->b_vp
;
2365 * If the vnode has "too many" write operations in progress
2366 * wait for them to finish the IO
2368 (void)vnode_waitforwrites(vp
, VNODE_ASYNC_THROTTLE
, 0, 0, (const char *)"buf_bawrite");
2369 else if (vp
->v_numoutput
>= VNODE_ASYNC_THROTTLE
)
2371 * return to the caller and
2372 * let him decide what to do
2374 return (EWOULDBLOCK
);
2376 SET(bp
->b_flags
, B_ASYNC
);
2378 return (VNOP_BWRITE(bp
));
2382 buf_bawrite(buf_t bp
)
2384 return (bawrite_internal(bp
, 1));
2390 buf_free_meta_store(buf_t bp
)
2392 if (bp
->b_bufsize
) {
2393 if (ISSET(bp
->b_flags
, B_ZALLOC
)) {
2396 z
= getbufzone(bp
->b_bufsize
);
2397 zfree(z
, (void *)bp
->b_datap
);
2399 kmem_free(kernel_map
, bp
->b_datap
, bp
->b_bufsize
);
2401 bp
->b_datap
= (uintptr_t)NULL
;
2408 buf_brelse_shadow(buf_t bp
)
2412 buf_t bp_return
= NULL
;
2413 #ifdef BUF_MAKE_PRIVATE
2417 int need_wakeup
= 0;
2419 lck_mtx_lock_spin(buf_mtxp
);
2421 bp_head
= (buf_t
)bp
->b_orig
;
2423 if (bp_head
->b_whichq
!= -1)
2424 panic("buf_brelse_shadow: bp_head on freelist %d\n", bp_head
->b_whichq
);
2426 #ifdef BUF_MAKE_PRIVATE
2427 if (bp_data
= bp
->b_data_store
) {
2428 bp_data
->b_data_ref
--;
2430 * snapshot the ref count so that we can check it
2431 * outside of the lock... we only want the guy going
2432 * from 1 -> 0 to try and release the storage
2434 data_ref
= bp_data
->b_data_ref
;
2437 KERNEL_DEBUG(0xbbbbc008 | DBG_FUNC_START
, bp
, bp_head
, bp_head
->b_shadow_ref
, 0, 0);
2439 bp_head
->b_shadow_ref
--;
2441 for (bp_temp
= bp_head
; bp_temp
&& bp
!= bp_temp
->b_shadow
; bp_temp
= bp_temp
->b_shadow
);
2443 if (bp_temp
== NULL
)
2444 panic("buf_brelse_shadow: bp not on list %p", bp_head
);
2446 bp_temp
->b_shadow
= bp_temp
->b_shadow
->b_shadow
;
2448 #ifdef BUF_MAKE_PRIVATE
2450 * we're about to free the current 'owner' of the data buffer and
2451 * there is at least one other shadow buf_t still pointing at it
2452 * so transfer it to the first shadow buf left in the chain
2454 if (bp
== bp_data
&& data_ref
) {
2455 if ((bp_data
= bp_head
->b_shadow
) == NULL
)
2456 panic("buf_brelse_shadow: data_ref mismatch bp(%p)", bp
);
2458 for (bp_temp
= bp_data
; bp_temp
; bp_temp
= bp_temp
->b_shadow
)
2459 bp_temp
->b_data_store
= bp_data
;
2460 bp_data
->b_data_ref
= data_ref
;
2463 if (bp_head
->b_shadow_ref
== 0 && bp_head
->b_shadow
)
2464 panic("buf_relse_shadow: b_shadow != NULL && b_shadow_ref == 0 bp(%p)", bp
);
2465 if (bp_head
->b_shadow_ref
&& bp_head
->b_shadow
== 0)
2466 panic("buf_relse_shadow: b_shadow == NULL && b_shadow_ref != 0 bp(%p)", bp
);
2468 if (bp_head
->b_shadow_ref
== 0) {
2469 if (!ISSET(bp_head
->b_lflags
, BL_BUSY
)) {
2471 CLR(bp_head
->b_flags
, B_AGE
);
2472 bp_head
->b_timestamp
= buf_timestamp();
2474 if (ISSET(bp_head
->b_flags
, B_LOCKED
)) {
2475 bp_head
->b_whichq
= BQ_LOCKED
;
2476 binstailfree(bp_head
, &bufqueues
[BQ_LOCKED
], BQ_LOCKED
);
2478 bp_head
->b_whichq
= BQ_META
;
2479 binstailfree(bp_head
, &bufqueues
[BQ_META
], BQ_META
);
2481 } else if (ISSET(bp_head
->b_lflags
, BL_WAITSHADOW
)) {
2482 CLR(bp_head
->b_lflags
, BL_WAITSHADOW
);
2484 bp_return
= bp_head
;
2486 if (ISSET(bp_head
->b_lflags
, BL_WANTED_REF
)) {
2487 CLR(bp_head
->b_lflags
, BL_WANTED_REF
);
2491 lck_mtx_unlock(buf_mtxp
);
2497 #ifdef BUF_MAKE_PRIVATE
2498 if (bp
== bp_data
&& data_ref
== 0)
2499 buf_free_meta_store(bp
);
2501 bp
->b_data_store
= NULL
;
2503 KERNEL_DEBUG(0xbbbbc008 | DBG_FUNC_END
, bp
, 0, 0, 0, 0);
2510 * Release a buffer on to the free lists.
2511 * Described in Bach (p. 46).
2514 buf_brelse(buf_t bp
)
2516 struct bqueues
*bufq
;
2519 int need_wakeup
= 0;
2520 int need_bp_wakeup
= 0;
2523 if (bp
->b_whichq
!= -1 || !(bp
->b_lflags
& BL_BUSY
))
2524 panic("buf_brelse: bad buffer = %p\n", bp
);
2527 (void) OSBacktrace(&bp
->b_stackbrelse
[0], 6);
2529 bp
->b_lastbrelse
= current_thread();
2532 if (bp
->b_lflags
& BL_IOBUF
) {
2533 buf_t shadow_master_bp
= NULL
;
2535 if (ISSET(bp
->b_lflags
, BL_SHADOW
))
2536 shadow_master_bp
= buf_brelse_shadow(bp
);
2537 else if (ISSET(bp
->b_lflags
, BL_IOBUF_ALLOC
))
2538 buf_free_meta_store(bp
);
2541 if (shadow_master_bp
) {
2542 bp
= shadow_master_bp
;
2543 goto finish_shadow_master
;
2548 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 388)) | DBG_FUNC_START
,
2549 bp
->b_lblkno
* PAGE_SIZE
, bp
, bp
->b_datap
,
2552 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
2555 * if we're invalidating a buffer that has the B_FILTER bit
2556 * set then call the b_iodone function so it gets cleaned
2559 * the HFS journal code depends on this
2561 if (ISSET(bp
->b_flags
, B_META
) && ISSET(bp
->b_flags
, B_INVAL
)) {
2562 if (ISSET(bp
->b_flags
, B_FILTER
)) { /* if necessary, call out */
2563 void (*iodone_func
)(struct buf
*, void *) = bp
->b_iodone
;
2564 void *arg
= bp
->b_transaction
;
2566 CLR(bp
->b_flags
, B_FILTER
); /* but note callout done */
2567 bp
->b_iodone
= NULL
;
2568 bp
->b_transaction
= NULL
;
2570 if (iodone_func
== NULL
) {
2571 panic("brelse: bp @ %p has NULL b_iodone!\n", bp
);
2573 (*iodone_func
)(bp
, arg
);
2577 * I/O is done. Cleanup the UPL state
2581 if ( !ISSET(bp
->b_flags
, B_META
) && UBCINFOEXISTS(bp
->b_vp
) && bp
->b_bufsize
) {
2586 if ( !ISSET(bp
->b_flags
, B_INVAL
)) {
2587 kret
= ubc_create_upl(bp
->b_vp
,
2588 ubc_blktooff(bp
->b_vp
, bp
->b_lblkno
),
2594 if (kret
!= KERN_SUCCESS
)
2595 panic("brelse: Failed to create UPL");
2597 upl_ubc_alias_set(upl
, (uintptr_t) bp
, (uintptr_t) 5);
2598 #endif /* UPL_DEBUG */
2602 kret
= ubc_upl_unmap(upl
);
2604 if (kret
!= KERN_SUCCESS
)
2605 panic("ubc_upl_unmap failed");
2606 bp
->b_datap
= (uintptr_t)NULL
;
2610 if (bp
->b_flags
& (B_ERROR
| B_INVAL
)) {
2611 if (bp
->b_flags
& (B_READ
| B_INVAL
))
2612 upl_flags
= UPL_ABORT_DUMP_PAGES
;
2616 ubc_upl_abort(upl
, upl_flags
);
2618 if (ISSET(bp
->b_flags
, B_DELWRI
| B_WASDIRTY
))
2619 upl_flags
= UPL_COMMIT_SET_DIRTY
;
2621 upl_flags
= UPL_COMMIT_CLEAR_DIRTY
;
2623 ubc_upl_commit_range(upl
, 0, bp
->b_bufsize
, upl_flags
|
2624 UPL_COMMIT_INACTIVATE
| UPL_COMMIT_FREE_ON_EMPTY
);
2630 panic("brelse: UPL set for non VREG; vp=%p", bp
->b_vp
);
2634 * If it's locked, don't report an error; try again later.
2636 if (ISSET(bp
->b_flags
, (B_LOCKED
|B_ERROR
)) == (B_LOCKED
|B_ERROR
))
2637 CLR(bp
->b_flags
, B_ERROR
);
2639 * If it's not cacheable, or an error, mark it invalid.
2641 if (ISSET(bp
->b_flags
, (B_NOCACHE
|B_ERROR
)))
2642 SET(bp
->b_flags
, B_INVAL
);
2644 if ((bp
->b_bufsize
<= 0) ||
2645 ISSET(bp
->b_flags
, B_INVAL
) ||
2646 (ISSET(bp
->b_lflags
, BL_WANTDEALLOC
) && !ISSET(bp
->b_flags
, B_DELWRI
))) {
2648 boolean_t delayed_buf_free_meta_store
= FALSE
;
2651 * If it's invalid or empty, dissociate it from its vnode,
2652 * release its storage if B_META, and
2653 * clean it up a bit and put it on the EMPTY queue
2655 if (ISSET(bp
->b_flags
, B_DELWRI
))
2656 OSAddAtomicLong(-1, &nbdwrite
);
2658 if (ISSET(bp
->b_flags
, B_META
)) {
2659 if (bp
->b_shadow_ref
)
2660 delayed_buf_free_meta_store
= TRUE
;
2662 buf_free_meta_store(bp
);
2665 * nuke any credentials we were holding
2667 buf_release_credentials(bp
);
2669 lck_mtx_lock_spin(buf_mtxp
);
2671 if (bp
->b_shadow_ref
) {
2672 SET(bp
->b_lflags
, BL_WAITSHADOW
);
2674 lck_mtx_unlock(buf_mtxp
);
2678 if (delayed_buf_free_meta_store
== TRUE
) {
2680 lck_mtx_unlock(buf_mtxp
);
2681 finish_shadow_master
:
2682 buf_free_meta_store(bp
);
2684 lck_mtx_lock_spin(buf_mtxp
);
2686 CLR(bp
->b_flags
, (B_META
| B_ZALLOC
| B_DELWRI
| B_LOCKED
| B_AGE
| B_ASYNC
| B_NOCACHE
| B_FUA
));
2693 binshash(bp
, &invalhash
);
2695 bp
->b_whichq
= BQ_EMPTY
;
2696 binsheadfree(bp
, &bufqueues
[BQ_EMPTY
], BQ_EMPTY
);
2700 * It has valid data. Put it on the end of the appropriate
2701 * queue, so that it'll stick around for as long as possible.
2703 if (ISSET(bp
->b_flags
, B_LOCKED
))
2704 whichq
= BQ_LOCKED
; /* locked in core */
2705 else if (ISSET(bp
->b_flags
, B_META
))
2706 whichq
= BQ_META
; /* meta-data */
2707 else if (ISSET(bp
->b_flags
, B_AGE
))
2708 whichq
= BQ_AGE
; /* stale but valid data */
2710 whichq
= BQ_LRU
; /* valid data */
2711 bufq
= &bufqueues
[whichq
];
2713 bp
->b_timestamp
= buf_timestamp();
2715 lck_mtx_lock_spin(buf_mtxp
);
2718 * the buf_brelse_shadow routine doesn't take 'ownership'
2719 * of the parent buf_t... it updates state that is protected by
2720 * the buf_mtxp, and checks for BL_BUSY to determine whether to
2721 * put the buf_t back on a free list. b_shadow_ref is protected
2722 * by the lock, and since we have not yet cleared B_BUSY, we need
2723 * to check it while holding the lock to insure that one of us
2724 * puts this buf_t back on a free list when it is safe to do so
2726 if (bp
->b_shadow_ref
== 0) {
2727 CLR(bp
->b_flags
, (B_AGE
| B_ASYNC
| B_NOCACHE
));
2728 bp
->b_whichq
= whichq
;
2729 binstailfree(bp
, bufq
, whichq
);
2732 * there are still cloned buf_t's pointing
2733 * at this guy... need to keep it off the
2734 * freelists until a buf_brelse is done on
2737 CLR(bp
->b_flags
, (B_ASYNC
| B_NOCACHE
));
2742 * needbuffer is a global
2743 * we're currently using buf_mtxp to protect it
2744 * delay doing the actual wakeup until after
2750 if (ISSET(bp
->b_lflags
, BL_WANTED
)) {
2752 * delay the actual wakeup until after we
2753 * clear BL_BUSY and we've dropped buf_mtxp
2758 * Unlock the buffer.
2760 CLR(bp
->b_lflags
, (BL_BUSY
| BL_WANTED
));
2763 lck_mtx_unlock(buf_mtxp
);
2767 * Wake up any processes waiting for any buffer to become free.
2769 wakeup(&needbuffer
);
2771 if (need_bp_wakeup
) {
2773 * Wake up any proceeses waiting for _this_ buffer to become free.
2777 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 388)) | DBG_FUNC_END
,
2778 bp
, bp
->b_datap
, bp
->b_flags
, 0, 0);
2782 * Determine if a block is in the cache.
2783 * Just look on what would be its hash chain. If it's there, return
2784 * a pointer to it, unless it's marked invalid. If it's marked invalid,
2785 * we normally don't return the buffer, unless the caller explicitly
2789 incore(vnode_t vp
, daddr64_t blkno
)
2792 struct bufhashhdr
*dp
;
2794 dp
= BUFHASH(vp
, blkno
);
2796 lck_mtx_lock_spin(buf_mtxp
);
2798 if (incore_locked(vp
, blkno
, dp
))
2802 lck_mtx_unlock(buf_mtxp
);
2809 incore_locked(vnode_t vp
, daddr64_t blkno
, struct bufhashhdr
*dp
)
2813 /* Search hash chain */
2814 for (bp
= dp
->lh_first
; bp
!= NULL
; bp
= bp
->b_hash
.le_next
) {
2815 if (bp
->b_lblkno
== blkno
&& bp
->b_vp
== vp
&&
2816 !ISSET(bp
->b_flags
, B_INVAL
)) {
2824 buf_wait_for_shadow_io(vnode_t vp
, daddr64_t blkno
)
2827 struct bufhashhdr
*dp
;
2829 dp
= BUFHASH(vp
, blkno
);
2831 lck_mtx_lock_spin(buf_mtxp
);
2834 if ((bp
= incore_locked(vp
, blkno
, dp
)) == NULL
)
2837 if (bp
->b_shadow_ref
== 0)
2840 SET(bp
->b_lflags
, BL_WANTED_REF
);
2842 (void) msleep(bp
, buf_mtxp
, PSPIN
| (PRIBIO
+1), "buf_wait_for_shadow", NULL
);
2844 lck_mtx_unlock(buf_mtxp
);
2847 /* XXX FIXME -- Update the comment to reflect the UBC changes (please) -- */
2849 * Get a block of requested size that is associated with
2850 * a given vnode and block offset. If it is found in the
2851 * block cache, mark it as having been found, make it busy
2852 * and return it. Otherwise, return an empty block of the
2853 * correct size. It is up to the caller to insure that the
2854 * cached blocks be of the correct size.
2857 buf_getblk(vnode_t vp
, daddr64_t blkno
, int size
, int slpflag
, int slptimeo
, int operation
)
2862 upl_page_info_t
*pl
;
2867 struct bufhashhdr
*dp
;
2869 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_START
,
2870 (uintptr_t)(blkno
* PAGE_SIZE
), size
, operation
, 0, 0);
2872 ret_only_valid
= operation
& BLK_ONLYVALID
;
2873 operation
&= ~BLK_ONLYVALID
;
2874 dp
= BUFHASH(vp
, blkno
);
2876 lck_mtx_lock_spin(buf_mtxp
);
2878 if ((bp
= incore_locked(vp
, blkno
, dp
))) {
2880 * Found in the Buffer Cache
2882 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
2886 switch (operation
) {
2890 SET(bp
->b_lflags
, BL_WANTED
);
2891 bufstats
.bufs_busyincore
++;
2894 * don't retake the mutex after being awakened...
2895 * the time out is in msecs
2897 ts
.tv_sec
= (slptimeo
/1000);
2898 ts
.tv_nsec
= (slptimeo
% 1000) * 10 * NSEC_PER_USEC
* 1000;
2900 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 396)) | DBG_FUNC_NONE
,
2901 (uintptr_t)blkno
, size
, operation
, 0, 0);
2903 err
= msleep(bp
, buf_mtxp
, slpflag
| PDROP
| (PRIBIO
+ 1), "buf_getblk", &ts
);
2906 * Callers who call with PCATCH or timeout are
2907 * willing to deal with the NULL pointer
2909 if (err
&& ((slpflag
& PCATCH
) || ((err
== EWOULDBLOCK
) && slptimeo
)))
2917 * unknown operation requested
2919 panic("getblk: paging or unknown operation for incore busy buffer - %x\n", operation
);
2925 * buffer in core and not busy
2927 SET(bp
->b_lflags
, BL_BUSY
);
2928 SET(bp
->b_flags
, B_CACHE
);
2931 bremfree_locked(bp
);
2932 bufstats
.bufs_incore
++;
2934 lck_mtx_unlock(buf_mtxp
);
2936 bp
->b_owner
= current_thread();
2940 panic("buffer has UPL, but not marked BUSY: %p", bp
);
2942 if ( !ret_only_valid
&& bp
->b_bufsize
!= size
)
2946 switch (operation
) {
2949 * "write" operation: let the UPL subsystem
2950 * know that we intend to modify the buffer
2951 * cache pages we're gathering.
2953 upl_flags
|= UPL_WILL_MODIFY
;
2955 upl_flags
|= UPL_PRECIOUS
;
2956 if (UBCINFOEXISTS(bp
->b_vp
) && bp
->b_bufsize
) {
2957 kret
= ubc_create_upl(vp
,
2958 ubc_blktooff(vp
, bp
->b_lblkno
),
2963 if (kret
!= KERN_SUCCESS
)
2964 panic("Failed to create UPL");
2968 if (upl_valid_page(pl
, 0)) {
2969 if (upl_dirty_page(pl
, 0))
2970 SET(bp
->b_flags
, B_WASDIRTY
);
2972 CLR(bp
->b_flags
, B_WASDIRTY
);
2974 CLR(bp
->b_flags
, (B_DONE
| B_CACHE
| B_WASDIRTY
| B_DELWRI
));
2976 kret
= ubc_upl_map(upl
, (vm_offset_t
*)&(bp
->b_datap
));
2978 if (kret
!= KERN_SUCCESS
)
2979 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
2985 * VM is not involved in IO for the meta data
2986 * buffer already has valid data
2991 panic("getblk: paging or unknown operation for incore buffer- %d\n", operation
);
2996 } else { /* not incore() */
2997 int queue
= BQ_EMPTY
; /* Start with no preference */
2999 if (ret_only_valid
) {
3000 lck_mtx_unlock(buf_mtxp
);
3003 if ((vnode_isreg(vp
) == 0) || (UBCINFOEXISTS(vp
) == 0) /*|| (vnode_issystem(vp) == 1)*/)
3004 operation
= BLK_META
;
3006 if ((bp
= getnewbuf(slpflag
, slptimeo
, &queue
)) == NULL
)
3010 * getnewbuf may block for a number of different reasons...
3011 * if it does, it's then possible for someone else to
3012 * create a buffer for the same block and insert it into
3013 * the hash... if we see it incore at this point we dump
3014 * the buffer we were working on and start over
3016 if (incore_locked(vp
, blkno
, dp
)) {
3017 SET(bp
->b_flags
, B_INVAL
);
3018 binshash(bp
, &invalhash
);
3020 lck_mtx_unlock(buf_mtxp
);
3026 * NOTE: YOU CAN NOT BLOCK UNTIL binshash() HAS BEEN
3027 * CALLED! BE CAREFUL.
3031 * mark the buffer as B_META if indicated
3032 * so that when buffer is released it will goto META queue
3034 if (operation
== BLK_META
)
3035 SET(bp
->b_flags
, B_META
);
3037 bp
->b_blkno
= bp
->b_lblkno
= blkno
;
3041 * Insert in the hash so that incore() can find it
3043 binshash(bp
, BUFHASH(vp
, blkno
));
3045 bgetvp_locked(vp
, bp
);
3047 lck_mtx_unlock(buf_mtxp
);
3052 switch (operation
) {
3055 * buffer data is invalid...
3057 * I don't want to have to retake buf_mtxp,
3058 * so the miss and vmhits counters are done
3059 * with Atomic updates... all other counters
3060 * in bufstats are protected with either
3061 * buf_mtxp or iobuffer_mtxp
3063 OSAddAtomicLong(1, &bufstats
.bufs_miss
);
3068 * "write" operation: let the UPL subsystem know
3069 * that we intend to modify the buffer cache pages
3072 upl_flags
|= UPL_WILL_MODIFY
;
3075 size_t contig_bytes
;
3079 panic("bp already has UPL: %p",bp
);
3081 f_offset
= ubc_blktooff(vp
, blkno
);
3083 upl_flags
|= UPL_PRECIOUS
;
3084 kret
= ubc_create_upl(vp
,
3091 if (kret
!= KERN_SUCCESS
)
3092 panic("Failed to create UPL");
3094 upl_ubc_alias_set(upl
, (uintptr_t) bp
, (uintptr_t) 4);
3095 #endif /* UPL_DEBUG */
3098 if (upl_valid_page(pl
, 0)) {
3100 if (operation
== BLK_READ
)
3101 bmap_flags
= VNODE_READ
;
3103 bmap_flags
= VNODE_WRITE
;
3105 SET(bp
->b_flags
, B_CACHE
| B_DONE
);
3107 OSAddAtomicLong(1, &bufstats
.bufs_vmhits
);
3112 if (upl_dirty_page(pl
, 0)) {
3114 SET(bp
->b_flags
, B_WASDIRTY
);
3116 bp
->b_validend
= bp
->b_bcount
;
3117 bp
->b_dirtyend
= bp
->b_bcount
;
3120 bp
->b_validend
= bp
->b_bcount
;
3124 * try to recreate the physical block number associated with
3127 if (VNOP_BLOCKMAP(vp
, f_offset
, bp
->b_bcount
, &bp
->b_blkno
, &contig_bytes
, NULL
, bmap_flags
, NULL
))
3128 panic("getblk: VNOP_BLOCKMAP failed");
3130 * if the extent represented by this buffer
3131 * is not completely physically contiguous on
3132 * disk, than we can't cache the physical mapping
3133 * in the buffer header
3135 if ((long)contig_bytes
< bp
->b_bcount
)
3136 bp
->b_blkno
= bp
->b_lblkno
;
3138 OSAddAtomicLong(1, &bufstats
.bufs_miss
);
3140 kret
= ubc_upl_map(upl
, (vm_offset_t
*)&(bp
->b_datap
));
3142 if (kret
!= KERN_SUCCESS
)
3143 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
3147 panic("getblk: paging or unknown operation - %x", operation
);
3152 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_END
,
3153 bp
, bp
->b_datap
, bp
->b_flags
, 3, 0);
3156 (void) OSBacktrace(&bp
->b_stackgetblk
[0], 6);
3162 * Get an empty, disassociated buffer of given size.
3165 buf_geteblk(int size
)
3168 int queue
= BQ_EMPTY
;
3171 lck_mtx_lock_spin(buf_mtxp
);
3173 bp
= getnewbuf(0, 0, &queue
);
3174 } while (bp
== NULL
);
3176 SET(bp
->b_flags
, (B_META
|B_INVAL
));
3179 assert(queue
== BQ_EMPTY
);
3180 #endif /* DIAGNOSTIC */
3181 /* XXX need to implement logic to deal with other queues */
3183 binshash(bp
, &invalhash
);
3184 bufstats
.bufs_eblk
++;
3186 lck_mtx_unlock(buf_mtxp
);
3194 buf_redundancy_flags(buf_t bp
)
3196 return bp
->b_redundancy_flags
;
3200 buf_set_redundancy_flags(buf_t bp
, uint32_t flags
)
3202 SET(bp
->b_redundancy_flags
, flags
);
3206 buf_clear_redundancy_flags(buf_t bp
, uint32_t flags
)
3208 CLR(bp
->b_redundancy_flags
, flags
);
3212 * With UBC, there is no need to expand / shrink the file data
3213 * buffer. The VM uses the same pages, hence no waste.
3214 * All the file data buffers can have one size.
3215 * In fact expand / shrink would be an expensive operation.
3217 * Only exception to this is meta-data buffers. Most of the
3218 * meta data operations are smaller than PAGE_SIZE. Having the
3219 * meta-data buffers grow and shrink as needed, optimizes use
3220 * of the kernel wired memory.
3224 allocbuf(buf_t bp
, int size
)
3226 vm_size_t desired_size
;
3228 desired_size
= roundup(size
, CLBYTES
);
3230 if (desired_size
< PAGE_SIZE
)
3231 desired_size
= PAGE_SIZE
;
3232 if (desired_size
> MAXBSIZE
)
3233 panic("allocbuf: buffer larger than MAXBSIZE requested");
3235 if (ISSET(bp
->b_flags
, B_META
)) {
3237 int nsize
= roundup(size
, MINMETA
);
3240 vm_offset_t elem
= (vm_offset_t
)bp
->b_datap
;
3242 if (ISSET(bp
->b_flags
, B_ZALLOC
)) {
3243 if (bp
->b_bufsize
< nsize
) {
3244 /* reallocate to a bigger size */
3246 zprev
= getbufzone(bp
->b_bufsize
);
3247 if (nsize
<= MAXMETA
) {
3248 desired_size
= nsize
;
3249 z
= getbufzone(nsize
);
3250 /* b_datap not really a ptr */
3251 *(void **)(&bp
->b_datap
) = zalloc(z
);
3253 bp
->b_datap
= (uintptr_t)NULL
;
3254 kmem_alloc_kobject(kernel_map
, (vm_offset_t
*)&bp
->b_datap
, desired_size
);
3255 CLR(bp
->b_flags
, B_ZALLOC
);
3257 bcopy((void *)elem
, (caddr_t
)bp
->b_datap
, bp
->b_bufsize
);
3258 zfree(zprev
, (void *)elem
);
3260 desired_size
= bp
->b_bufsize
;
3264 if ((vm_size_t
)bp
->b_bufsize
< desired_size
) {
3265 /* reallocate to a bigger size */
3266 bp
->b_datap
= (uintptr_t)NULL
;
3267 kmem_alloc_kobject(kernel_map
, (vm_offset_t
*)&bp
->b_datap
, desired_size
);
3268 bcopy((const void *)elem
, (caddr_t
)bp
->b_datap
, bp
->b_bufsize
);
3269 kmem_free(kernel_map
, elem
, bp
->b_bufsize
);
3271 desired_size
= bp
->b_bufsize
;
3275 /* new allocation */
3276 if (nsize
<= MAXMETA
) {
3277 desired_size
= nsize
;
3278 z
= getbufzone(nsize
);
3279 /* b_datap not really a ptr */
3280 *(void **)(&bp
->b_datap
) = zalloc(z
);
3281 SET(bp
->b_flags
, B_ZALLOC
);
3283 kmem_alloc_kobject(kernel_map
, (vm_offset_t
*)&bp
->b_datap
, desired_size
);
3286 if (bp
->b_datap
== 0)
3287 panic("allocbuf: NULL b_datap");
3289 bp
->b_bufsize
= desired_size
;
3290 bp
->b_bcount
= size
;
3296 * Get a new buffer from one of the free lists.
3298 * Request for a queue is passes in. The queue from which the buffer was taken
3299 * from is returned. Out of range queue requests get BQ_EMPTY. Request for
3300 * BQUEUE means no preference. Use heuristics in that case.
3301 * Heuristics is as follows:
3302 * Try BQ_AGE, BQ_LRU, BQ_EMPTY, BQ_META in that order.
3303 * If none available block till one is made available.
3304 * If buffers available on both BQ_AGE and BQ_LRU, check the timestamps.
3305 * Pick the most stale buffer.
3306 * If found buffer was marked delayed write, start the async. write
3307 * and restart the search.
3308 * Initialize the fields and disassociate the buffer from the vnode.
3309 * Remove the buffer from the hash. Return the buffer and the queue
3310 * on which it was found.
3312 * buf_mtxp is held upon entry
3313 * returns with buf_mtxp locked if new buf available
3314 * returns with buf_mtxp UNlocked if new buf NOT available
3318 getnewbuf(int slpflag
, int slptimeo
, int * queue
)
3324 int age_time
, lru_time
, bp_time
, meta_time
;
3325 int req
= *queue
; /* save it for restarts */
3330 * invalid request gets empty queue
3332 if ((*queue
>= BQUEUES
) || (*queue
< 0)
3333 || (*queue
== BQ_LAUNDRY
) || (*queue
== BQ_LOCKED
))
3337 if (*queue
== BQ_EMPTY
&& (bp
= bufqueues
[*queue
].tqh_first
))
3341 * need to grow number of bufs, add another one rather than recycling
3343 if (nbuf_headers
< max_nbuf_headers
) {
3345 * Increment count now as lock
3346 * is dropped for allocation.
3347 * That avoids over commits
3352 /* Try for the requested queue first */
3353 bp
= bufqueues
[*queue
].tqh_first
;
3357 /* Unable to use requested queue */
3358 age_bp
= bufqueues
[BQ_AGE
].tqh_first
;
3359 lru_bp
= bufqueues
[BQ_LRU
].tqh_first
;
3360 meta_bp
= bufqueues
[BQ_META
].tqh_first
;
3362 if (!age_bp
&& !lru_bp
&& !meta_bp
) {
3364 * Unavailble on AGE or LRU or META queues
3365 * Try the empty list first
3367 bp
= bufqueues
[BQ_EMPTY
].tqh_first
;
3373 * We have seen is this is hard to trigger.
3374 * This is an overcommit of nbufs but needed
3375 * in some scenarios with diskiamges
3379 lck_mtx_unlock(buf_mtxp
);
3381 /* Create a new temporary buffer header */
3382 bp
= (struct buf
*)zalloc(buf_hdr_zone
);
3386 bp
->b_whichq
= BQ_EMPTY
;
3387 bp
->b_timestamp
= buf_timestamp();
3389 SET(bp
->b_flags
, B_HDRALLOC
);
3392 lck_mtx_lock_spin(buf_mtxp
);
3395 binshash(bp
, &invalhash
);
3396 binsheadfree(bp
, &bufqueues
[BQ_EMPTY
], BQ_EMPTY
);
3400 /* subtract already accounted bufcount */
3403 bufstats
.bufs_sleeps
++;
3405 /* wait for a free buffer of any kind */
3407 /* hz value is 100 */
3408 ts
.tv_sec
= (slptimeo
/1000);
3409 /* the hz value is 100; which leads to 10ms */
3410 ts
.tv_nsec
= (slptimeo
% 1000) * NSEC_PER_USEC
* 1000 * 10;
3412 msleep(&needbuffer
, buf_mtxp
, slpflag
| PDROP
| (PRIBIO
+1), "getnewbuf", &ts
);
3416 /* Buffer available either on AGE or LRU or META */
3420 /* Buffer available either on AGE or LRU */
3424 } else if (!lru_bp
) {
3427 } else { /* buffer available on both AGE and LRU */
3428 int t
= buf_timestamp();
3430 age_time
= t
- age_bp
->b_timestamp
;
3431 lru_time
= t
- lru_bp
->b_timestamp
;
3432 if ((age_time
< 0) || (lru_time
< 0)) { /* time set backwards */
3436 * we should probably re-timestamp eveything in the
3437 * queues at this point with the current time
3440 if ((lru_time
>= lru_is_stale
) && (age_time
< age_is_stale
)) {
3450 if (!bp
) { /* Neither on AGE nor on LRU */
3453 } else if (meta_bp
) {
3454 int t
= buf_timestamp();
3456 bp_time
= t
- bp
->b_timestamp
;
3457 meta_time
= t
- meta_bp
->b_timestamp
;
3459 if (!(bp_time
< 0) && !(meta_time
< 0)) {
3460 /* time not set backwards */
3462 bp_is_stale
= (*queue
== BQ_LRU
) ?
3463 lru_is_stale
: age_is_stale
;
3465 if ((meta_time
>= meta_is_stale
) &&
3466 (bp_time
< bp_is_stale
)) {
3473 if (ISSET(bp
->b_flags
, B_LOCKED
) || ISSET(bp
->b_lflags
, BL_BUSY
))
3474 panic("getnewbuf: bp @ %p is LOCKED or BUSY! (flags 0x%x)\n", bp
, bp
->b_flags
);
3477 if (bcleanbuf(bp
, FALSE
)) {
3479 * moved to the laundry thread, buffer not ready
3490 * Returns 0 if buffer is ready to use,
3491 * Returns 1 if issued a buf_bawrite() to indicate
3492 * that the buffer is not ready.
3494 * buf_mtxp is held upon entry
3495 * returns with buf_mtxp locked
3498 bcleanbuf(buf_t bp
, boolean_t discard
)
3500 /* Remove from the queue */
3501 bremfree_locked(bp
);
3504 bp
->b_owner
= current_thread();
3508 * If buffer was a delayed write, start the IO by queuing
3509 * it on the LAUNDRY queue, and return 1
3511 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
3513 SET(bp
->b_lflags
, BL_WANTDEALLOC
);
3518 lck_mtx_unlock(buf_mtxp
);
3520 wakeup(&bufqueues
[BQ_LAUNDRY
]);
3522 * and give it a chance to run
3524 (void)thread_block(THREAD_CONTINUE_NULL
);
3526 lck_mtx_lock_spin(buf_mtxp
);
3531 bp
->b_owner
= current_thread();
3535 * Buffer is no longer on any free list... we own it
3537 SET(bp
->b_lflags
, BL_BUSY
);
3543 * disassociate us from our vnode, if we had one...
3548 lck_mtx_unlock(buf_mtxp
);
3552 if (ISSET(bp
->b_flags
, B_META
))
3553 buf_free_meta_store(bp
);
3555 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
3557 buf_release_credentials(bp
);
3559 /* If discarding, just move to the empty queue */
3561 lck_mtx_lock_spin(buf_mtxp
);
3562 CLR(bp
->b_flags
, (B_META
| B_ZALLOC
| B_DELWRI
| B_LOCKED
| B_AGE
| B_ASYNC
| B_NOCACHE
| B_FUA
));
3563 bp
->b_whichq
= BQ_EMPTY
;
3564 binshash(bp
, &invalhash
);
3565 binsheadfree(bp
, &bufqueues
[BQ_EMPTY
], BQ_EMPTY
);
3566 CLR(bp
->b_lflags
, BL_BUSY
);
3569 /* Not discarding: clean up and prepare for reuse */
3571 bp
->b_datap
= (uintptr_t)NULL
;
3572 bp
->b_upl
= (void *)NULL
;
3574 * preserve the state of whether this buffer
3575 * was allocated on the fly or not...
3576 * the only other flag that should be set at
3577 * this point is BL_BUSY...
3580 bp
->b_owner
= current_thread();
3583 bp
->b_lflags
= BL_BUSY
;
3584 bp
->b_flags
= (bp
->b_flags
& B_HDRALLOC
);
3586 bp
->b_blkno
= bp
->b_lblkno
= 0;
3587 bp
->b_iodone
= NULL
;
3591 bp
->b_dirtyoff
= bp
->b_dirtyend
= 0;
3592 bp
->b_validoff
= bp
->b_validend
= 0;
3593 bzero(&bp
->b_attr
, sizeof(struct bufattr
));
3595 lck_mtx_lock_spin(buf_mtxp
);
3603 buf_invalblkno(vnode_t vp
, daddr64_t lblkno
, int flags
)
3607 struct bufhashhdr
*dp
;
3609 dp
= BUFHASH(vp
, lblkno
);
3612 lck_mtx_lock_spin(buf_mtxp
);
3614 if ((bp
= incore_locked(vp
, lblkno
, dp
)) == (struct buf
*)0) {
3615 lck_mtx_unlock(buf_mtxp
);
3618 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
3619 if ( !ISSET(flags
, BUF_WAIT
)) {
3620 lck_mtx_unlock(buf_mtxp
);
3623 SET(bp
->b_lflags
, BL_WANTED
);
3625 error
= msleep((caddr_t
)bp
, buf_mtxp
, PDROP
| (PRIBIO
+ 1), "buf_invalblkno", NULL
);
3632 bremfree_locked(bp
);
3633 SET(bp
->b_lflags
, BL_BUSY
);
3634 SET(bp
->b_flags
, B_INVAL
);
3637 bp
->b_owner
= current_thread();
3640 lck_mtx_unlock(buf_mtxp
);
3650 int need_wakeup
= 0;
3652 lck_mtx_lock_spin(buf_mtxp
);
3654 if (ISSET(bp
->b_lflags
, BL_WANTED
)) {
3656 * delay the actual wakeup until after we
3657 * clear BL_BUSY and we've dropped buf_mtxp
3662 bp
->b_owner
= current_thread();
3666 * Unlock the buffer.
3668 CLR(bp
->b_lflags
, (BL_BUSY
| BL_WANTED
));
3671 lck_mtx_unlock(buf_mtxp
);
3675 * Wake up any proceeses waiting for _this_ buffer to become free.
3683 buf_acquire(buf_t bp
, int flags
, int slpflag
, int slptimeo
) {
3686 lck_mtx_lock_spin(buf_mtxp
);
3688 error
= buf_acquire_locked(bp
, flags
, slpflag
, slptimeo
);
3690 lck_mtx_unlock(buf_mtxp
);
3697 buf_acquire_locked(buf_t bp
, int flags
, int slpflag
, int slptimeo
)
3702 if (ISSET(bp
->b_flags
, B_LOCKED
)) {
3703 if ((flags
& BAC_SKIP_LOCKED
))
3706 if ((flags
& BAC_SKIP_NONLOCKED
))
3709 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
3711 * since the lck_mtx_lock may block, the buffer
3712 * may become BUSY, so we need to
3713 * recheck for a NOWAIT request
3715 if (flags
& BAC_NOWAIT
)
3717 SET(bp
->b_lflags
, BL_WANTED
);
3719 /* the hz value is 100; which leads to 10ms */
3720 ts
.tv_sec
= (slptimeo
/100);
3721 ts
.tv_nsec
= (slptimeo
% 100) * 10 * NSEC_PER_USEC
* 1000;
3722 error
= msleep((caddr_t
)bp
, buf_mtxp
, slpflag
| (PRIBIO
+ 1), "buf_acquire", &ts
);
3728 if (flags
& BAC_REMOVE
)
3729 bremfree_locked(bp
);
3730 SET(bp
->b_lflags
, BL_BUSY
);
3734 bp
->b_owner
= current_thread();
3742 * Wait for operations on the buffer to complete.
3743 * When they do, extract and return the I/O's error value.
3746 buf_biowait(buf_t bp
)
3748 while (!ISSET(bp
->b_flags
, B_DONE
)) {
3750 lck_mtx_lock_spin(buf_mtxp
);
3752 if (!ISSET(bp
->b_flags
, B_DONE
)) {
3753 DTRACE_IO1(wait__start
, buf_t
, bp
);
3754 (void) msleep(bp
, buf_mtxp
, PDROP
| (PRIBIO
+1), "buf_biowait", NULL
);
3755 DTRACE_IO1(wait__done
, buf_t
, bp
);
3757 lck_mtx_unlock(buf_mtxp
);
3759 /* check for interruption of I/O (e.g. via NFS), then errors. */
3760 if (ISSET(bp
->b_flags
, B_EINTR
)) {
3761 CLR(bp
->b_flags
, B_EINTR
);
3763 } else if (ISSET(bp
->b_flags
, B_ERROR
))
3764 return (bp
->b_error
? bp
->b_error
: EIO
);
3771 * Mark I/O complete on a buffer.
3773 * If a callback has been requested, e.g. the pageout
3774 * daemon, do so. Otherwise, awaken waiting processes.
3776 * [ Leffler, et al., says on p.247:
3777 * "This routine wakes up the blocked process, frees the buffer
3778 * for an asynchronous write, or, for a request by the pagedaemon
3779 * process, invokes a procedure specified in the buffer structure" ]
3781 * In real life, the pagedaemon (or other system processes) wants
3782 * to do async stuff to, and doesn't want the buffer buf_brelse()'d.
3783 * (for swap pager, that puts swap buffers on the free lists (!!!),
3784 * for the vn device, that puts malloc'd buffers on the free lists!)
3786 extern struct timeval priority_IO_timestamp_for_root
;
3787 extern int hard_throttle_on_root
;
3790 buf_biodone(buf_t bp
)
3794 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 387)) | DBG_FUNC_START
,
3795 bp
, bp
->b_datap
, bp
->b_flags
, 0, 0);
3797 if (ISSET(bp
->b_flags
, B_DONE
))
3798 panic("biodone already");
3800 if (ISSET(bp
->b_flags
, B_ERROR
)) {
3804 if (bp
->b_vp
&& bp
->b_vp
->v_mount
) {
3805 mp
= bp
->b_vp
->v_mount
;
3810 if (mp
&& (bp
->b_flags
& B_READ
) == 0) {
3811 update_last_io_time(mp
);
3812 INCR_PENDING_IO(-(pending_io_t
)buf_count(bp
), mp
->mnt_pending_write_size
);
3814 INCR_PENDING_IO(-(pending_io_t
)buf_count(bp
), mp
->mnt_pending_read_size
);
3817 if (kdebug_enable
) {
3818 int code
= DKIO_DONE
;
3820 if (bp
->b_flags
& B_READ
)
3822 if (bp
->b_flags
& B_ASYNC
)
3825 if (bp
->b_flags
& B_META
)
3827 else if (bp
->b_flags
& B_PAGEIO
)
3828 code
|= DKIO_PAGING
;
3830 if (bp
->b_flags
& B_THROTTLED_IO
)
3831 code
|= DKIO_THROTTLE
;
3832 else if (bp
->b_flags
& B_PASSIVE
)
3833 code
|= DKIO_PASSIVE
;
3835 if (bp
->b_attr
.ba_flags
& BA_NOCACHE
)
3836 code
|= DKIO_NOCACHE
;
3838 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_COMMON
, FSDBG_CODE(DBG_DKRW
, code
) | DBG_FUNC_NONE
,
3839 bp
, (uintptr_t)bp
->b_vp
,
3840 bp
->b_resid
, bp
->b_error
, 0);
3842 if ((bp
->b_vp
!= NULLVP
) &&
3843 ((bp
->b_flags
& (B_THROTTLED_IO
| B_PASSIVE
| B_IOSTREAMING
| B_PAGEIO
| B_READ
| B_THROTTLED_IO
| B_PASSIVE
)) == (B_PAGEIO
| B_READ
)) &&
3844 (bp
->b_vp
->v_mount
->mnt_kern_flag
& MNTK_ROOTDEV
)) {
3845 microuptime(&priority_IO_timestamp_for_root
);
3846 hard_throttle_on_root
= 0;
3850 * I/O was done, so don't believe
3851 * the DIRTY state from VM anymore...
3852 * and we need to reset the THROTTLED/PASSIVE
3855 CLR(bp
->b_flags
, (B_WASDIRTY
| B_THROTTLED_IO
| B_PASSIVE
));
3856 CLR(bp
->b_attr
.ba_flags
, (BA_META
| BA_NOCACHE
));
3857 #if !CONFIG_EMBEDDED
3858 CLR(bp
->b_attr
.ba_flags
, (BA_THROTTLED_IO
| BA_DELAYIDLESLEEP
));
3860 CLR(bp
->b_attr
.ba_flags
, BA_THROTTLED_IO
);
3861 #endif /* !CONFIG_EMBEDDED */
3862 DTRACE_IO1(done
, buf_t
, bp
);
3864 if (!ISSET(bp
->b_flags
, B_READ
) && !ISSET(bp
->b_flags
, B_RAW
))
3866 * wake up any writer's blocked
3867 * on throttle or waiting for I/O
3870 vnode_writedone(bp
->b_vp
);
3872 if (ISSET(bp
->b_flags
, (B_CALL
| B_FILTER
))) { /* if necessary, call out */
3873 void (*iodone_func
)(struct buf
*, void *) = bp
->b_iodone
;
3874 void *arg
= bp
->b_transaction
;
3875 int callout
= ISSET(bp
->b_flags
, B_CALL
);
3877 if (iodone_func
== NULL
)
3878 panic("biodone: bp @ %p has NULL b_iodone!\n", bp
);
3880 CLR(bp
->b_flags
, (B_CALL
| B_FILTER
)); /* filters and callouts are one-shot */
3881 bp
->b_iodone
= NULL
;
3882 bp
->b_transaction
= NULL
;
3885 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
3887 (*iodone_func
)(bp
, arg
);
3891 * assumes that the callback function takes
3892 * ownership of the bp and deals with releasing it if necessary
3897 * in this case the call back function is acting
3898 * strictly as a filter... it does not take
3899 * ownership of the bp and is expecting us
3900 * to finish cleaning up... this is currently used
3901 * by the HFS journaling code
3904 if (ISSET(bp
->b_flags
, B_ASYNC
)) { /* if async, release it */
3905 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
3908 } else { /* or just wakeup the buffer */
3910 * by taking the mutex, we serialize
3911 * the buf owner calling buf_biowait so that we'll
3912 * only see him in one of 2 states...
3913 * state 1: B_DONE wasn't set and he's
3915 * state 2: he's blocked trying to take the
3916 * mutex before looking at B_DONE
3917 * BL_WANTED is cleared in case anyone else
3918 * is blocked waiting for the buffer... note
3919 * that we haven't cleared B_BUSY yet, so if
3920 * they do get to run, their going to re-set
3921 * BL_WANTED and go back to sleep
3923 lck_mtx_lock_spin(buf_mtxp
);
3925 CLR(bp
->b_lflags
, BL_WANTED
);
3926 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
3928 lck_mtx_unlock(buf_mtxp
);
3933 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 387)) | DBG_FUNC_END
,
3934 (uintptr_t)bp
, (uintptr_t)bp
->b_datap
, bp
->b_flags
, 0, 0);
3938 * Return a count of buffers on the "locked" queue.
3941 count_lock_queue(void)
3946 lck_mtx_lock_spin(buf_mtxp
);
3948 for (bp
= bufqueues
[BQ_LOCKED
].tqh_first
; bp
;
3949 bp
= bp
->b_freelist
.tqe_next
)
3951 lck_mtx_unlock(buf_mtxp
);
3957 * Return a count of 'busy' buffers. Used at the time of shutdown.
3958 * note: This is also called from the mach side in debug context in kdp.c
3961 count_busy_buffers(void)
3963 return buf_busycount
+ bufstats
.bufs_iobufinuse
;
3968 * Print out statistics on the current allocation of the buffer pool.
3969 * Can be enabled to print out on every ``sync'' by setting "syncprt"
3970 * in vfs_syscalls.c using sysctl.
3978 int counts
[MAXBSIZE
/CLBYTES
+1];
3979 static char *bname
[BQUEUES
] =
3980 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
3982 for (dp
= bufqueues
, i
= 0; dp
< &bufqueues
[BQUEUES
]; dp
++, i
++) {
3984 for (j
= 0; j
<= MAXBSIZE
/CLBYTES
; j
++)
3987 lck_mtx_lock(buf_mtxp
);
3989 for (bp
= dp
->tqh_first
; bp
; bp
= bp
->b_freelist
.tqe_next
) {
3990 counts
[bp
->b_bufsize
/CLBYTES
]++;
3993 lck_mtx_unlock(buf_mtxp
);
3995 printf("%s: total-%d", bname
[i
], count
);
3996 for (j
= 0; j
<= MAXBSIZE
/CLBYTES
; j
++)
3998 printf(", %d-%d", j
* CLBYTES
, counts
[j
]);
4002 #endif /* DIAGNOSTIC */
4004 #define NRESERVEDIOBUFS 128
4008 alloc_io_buf(vnode_t vp
, int priv
)
4012 lck_mtx_lock_spin(iobuffer_mtxp
);
4014 while (((niobuf_headers
- NRESERVEDIOBUFS
< bufstats
.bufs_iobufinuse
) && !priv
) ||
4015 (bp
= iobufqueue
.tqh_first
) == NULL
) {
4016 bufstats
.bufs_iobufsleeps
++;
4019 (void) msleep(&need_iobuffer
, iobuffer_mtxp
, PSPIN
| (PRIBIO
+1), (const char *)"alloc_io_buf", NULL
);
4021 TAILQ_REMOVE(&iobufqueue
, bp
, b_freelist
);
4023 bufstats
.bufs_iobufinuse
++;
4024 if (bufstats
.bufs_iobufinuse
> bufstats
.bufs_iobufmax
)
4025 bufstats
.bufs_iobufmax
= bufstats
.bufs_iobufinuse
;
4027 lck_mtx_unlock(iobuffer_mtxp
);
4030 * initialize various fields
4031 * we don't need to hold the mutex since the buffer
4032 * is now private... the vp should have a reference
4033 * on it and is not protected by this mutex in any event
4035 bp
->b_timestamp
= 0;
4040 bp
->b_lflags
= BL_BUSY
| BL_IOBUF
;
4041 bp
->b_redundancy_flags
= 0;
4042 bp
->b_blkno
= bp
->b_lblkno
= 0;
4044 bp
->b_owner
= current_thread();
4047 bp
->b_iodone
= NULL
;
4054 bzero(&bp
->b_attr
, sizeof(struct bufattr
));
4056 if (vp
&& (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
))
4057 bp
->b_dev
= vp
->v_rdev
;
4066 free_io_buf(buf_t bp
)
4068 int need_wakeup
= 0;
4071 * put buffer back on the head of the iobufqueue
4074 bp
->b_flags
= B_INVAL
;
4076 lck_mtx_lock_spin(iobuffer_mtxp
);
4078 binsheadfree(bp
, &iobufqueue
, -1);
4080 if (need_iobuffer
) {
4082 * Wake up any processes waiting because they need an io buffer
4084 * do the wakeup after we drop the mutex... it's possible that the
4085 * wakeup will be superfluous if need_iobuffer gets set again and
4086 * another thread runs this path, but it's highly unlikely, doesn't
4087 * hurt, and it means we don't hold up I/O progress if the wakeup blocks
4088 * trying to grab a task related lock...
4093 if (bufstats
.bufs_iobufinuse
<= 0)
4094 panic("free_io_buf: bp(%p) - bufstats.bufs_iobufinuse < 0", bp
);
4096 bufstats
.bufs_iobufinuse
--;
4098 lck_mtx_unlock(iobuffer_mtxp
);
4101 wakeup(&need_iobuffer
);
4108 lck_mtx_lock_spin(buf_mtxp
);
4112 buf_list_unlock(void)
4114 lck_mtx_unlock(buf_mtxp
);
4118 * If getnewbuf() calls bcleanbuf() on the same thread
4119 * there is a potential for stack overrun and deadlocks.
4120 * So we always handoff the work to a worker thread for completion
4125 bcleanbuf_thread_init(void)
4127 thread_t thread
= THREAD_NULL
;
4129 /* create worker thread */
4130 kernel_thread_start((thread_continue_t
)bcleanbuf_thread
, NULL
, &thread
);
4131 thread_deallocate(thread
);
4134 typedef int (*bcleanbufcontinuation
)(int);
4137 bcleanbuf_thread(void)
4144 lck_mtx_lock_spin(buf_mtxp
);
4146 while ( (bp
= TAILQ_FIRST(&bufqueues
[BQ_LAUNDRY
])) == NULL
) {
4147 (void)msleep0(&bufqueues
[BQ_LAUNDRY
], buf_mtxp
, PRIBIO
|PDROP
, "blaundry", 0, (bcleanbufcontinuation
)bcleanbuf_thread
);
4151 * Remove from the queue
4153 bremfree_locked(bp
);
4156 * Buffer is no longer on any free list
4158 SET(bp
->b_lflags
, BL_BUSY
);
4162 bp
->b_owner
= current_thread();
4166 lck_mtx_unlock(buf_mtxp
);
4170 error
= bawrite_internal(bp
, 0);
4173 bp
->b_whichq
= BQ_LAUNDRY
;
4174 bp
->b_timestamp
= buf_timestamp();
4176 lck_mtx_lock_spin(buf_mtxp
);
4178 binstailfree(bp
, &bufqueues
[BQ_LAUNDRY
], BQ_LAUNDRY
);
4181 /* we never leave a busy page on the laundry queue */
4182 CLR(bp
->b_lflags
, BL_BUSY
);
4185 bp
->b_owner
= current_thread();
4189 lck_mtx_unlock(buf_mtxp
);
4191 if (loopcnt
> MAXLAUNDRY
) {
4193 * bawrite_internal() can return errors if we're throttled. If we've
4194 * done several I/Os and failed, give the system some time to unthrottle
4197 (void)tsleep((void *)&bufqueues
[BQ_LAUNDRY
], PRIBIO
, "blaundry", 1);
4200 /* give other threads a chance to run */
4201 (void)thread_block(THREAD_CONTINUE_NULL
);
4210 brecover_data(buf_t bp
)
4214 upl_page_info_t
*pl
;
4216 vnode_t vp
= bp
->b_vp
;
4220 if ( !UBCINFOEXISTS(vp
) || bp
->b_bufsize
== 0)
4223 upl_flags
= UPL_PRECIOUS
;
4224 if (! (buf_flags(bp
) & B_READ
)) {
4226 * "write" operation: let the UPL subsystem know
4227 * that we intend to modify the buffer cache pages we're
4230 upl_flags
|= UPL_WILL_MODIFY
;
4233 kret
= ubc_create_upl(vp
,
4234 ubc_blktooff(vp
, bp
->b_lblkno
),
4239 if (kret
!= KERN_SUCCESS
)
4240 panic("Failed to create UPL");
4242 for (upl_offset
= 0; upl_offset
< bp
->b_bufsize
; upl_offset
+= PAGE_SIZE
) {
4244 if (!upl_valid_page(pl
, upl_offset
/ PAGE_SIZE
) || !upl_dirty_page(pl
, upl_offset
/ PAGE_SIZE
)) {
4245 ubc_upl_abort(upl
, 0);
4251 kret
= ubc_upl_map(upl
, (vm_offset_t
*)&(bp
->b_datap
));
4253 if (kret
!= KERN_SUCCESS
)
4254 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
4259 SET(bp
->b_flags
, B_INVAL
);
4266 buffer_cache_gc(int all
)
4269 boolean_t did_large_zfree
= FALSE
;
4270 boolean_t need_wakeup
= FALSE
;
4271 int now
= buf_timestamp();
4273 struct bqueues privq
;
4274 int thresh_hold
= BUF_STALE_THRESHHOLD
;
4279 * We only care about metadata (incore storage comes from zalloc()).
4280 * Unless "all" is set (used to evict meta data buffers in preparation
4281 * for deep sleep), we only evict up to BUF_MAX_GC_BATCH_SIZE buffers
4282 * that have not been accessed in the last 30s. This limit controls both
4283 * the hold time of the global lock "buf_mtxp" and the length of time
4284 * we spend compute bound in the GC thread which calls this function
4286 lck_mtx_lock(buf_mtxp
);
4291 need_wakeup
= FALSE
;
4293 while (((bp
= TAILQ_FIRST(&bufqueues
[BQ_META
]))) &&
4294 (now
> bp
->b_timestamp
) &&
4295 (now
- bp
->b_timestamp
> thresh_hold
) &&
4296 (found
< BUF_MAX_GC_BATCH_SIZE
)) {
4298 /* Remove from free list */
4299 bremfree_locked(bp
);
4303 bp
->b_owner
= current_thread();
4307 /* If dirty, move to laundry queue and remember to do wakeup */
4308 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
4309 SET(bp
->b_lflags
, BL_WANTDEALLOC
);
4318 * Mark busy and put on private list. We could technically get
4319 * away without setting BL_BUSY here.
4321 SET(bp
->b_lflags
, BL_BUSY
);
4325 * Remove from hash and dissociate from vp.
4332 TAILQ_INSERT_TAIL(&privq
, bp
, b_freelist
);
4339 /* Drop lock for batch processing */
4340 lck_mtx_unlock(buf_mtxp
);
4342 /* Wakeup and yield for laundry if need be */
4344 wakeup(&bufqueues
[BQ_LAUNDRY
]);
4345 (void)thread_block(THREAD_CONTINUE_NULL
);
4348 /* Clean up every buffer on private list */
4349 TAILQ_FOREACH(bp
, &privq
, b_freelist
) {
4350 /* Take note if we've definitely freed at least a page to a zone */
4351 if ((ISSET(bp
->b_flags
, B_ZALLOC
)) && (buf_size(bp
) >= PAGE_SIZE
)) {
4352 did_large_zfree
= TRUE
;
4355 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
4358 buf_free_meta_store(bp
);
4360 /* Release credentials */
4361 buf_release_credentials(bp
);
4363 /* Prepare for moving to empty queue */
4364 CLR(bp
->b_flags
, (B_META
| B_ZALLOC
| B_DELWRI
| B_LOCKED
4365 | B_AGE
| B_ASYNC
| B_NOCACHE
| B_FUA
));
4366 bp
->b_whichq
= BQ_EMPTY
;
4369 lck_mtx_lock(buf_mtxp
);
4371 /* Back under lock, move them all to invalid hash and clear busy */
4372 TAILQ_FOREACH(bp
, &privq
, b_freelist
) {
4373 binshash(bp
, &invalhash
);
4374 CLR(bp
->b_lflags
, BL_BUSY
);
4378 if (bp
->b_owner
!= current_thread()) {
4379 panic("Buffer stolen from buffer_cache_gc()");
4381 bp
->b_owner
= current_thread();
4386 /* And do a big bulk move to the empty queue */
4387 TAILQ_CONCAT(&bufqueues
[BQ_EMPTY
], &privq
, b_freelist
);
4389 } while (all
&& (found
== BUF_MAX_GC_BATCH_SIZE
));
4391 lck_mtx_unlock(buf_mtxp
);
4393 return did_large_zfree
;
4406 bp_cmp(void *a
, void *b
)
4408 buf_t
*bp_a
= *(buf_t
**)a
,
4409 *bp_b
= *(buf_t
**)b
;
4412 // don't have to worry about negative block
4413 // numbers so this is ok to do.
4415 res
= (bp_a
->b_blkno
- bp_b
->b_blkno
);
4422 bflushq(int whichq
, mount_t mp
)
4426 int total_writes
= 0;
4427 static buf_t flush_table
[NFLUSH
];
4429 if (whichq
< 0 || whichq
>= BQUEUES
) {
4434 lck_mtx_lock(buf_mtxp
);
4436 bp
= TAILQ_FIRST(&bufqueues
[whichq
]);
4438 for (buf_count
= 0; bp
; bp
= next
) {
4439 next
= bp
->b_freelist
.tqe_next
;
4441 if (bp
->b_vp
== NULL
|| bp
->b_vp
->v_mount
!= mp
) {
4445 if (ISSET(bp
->b_flags
, B_DELWRI
) && !ISSET(bp
->b_lflags
, BL_BUSY
)) {
4447 bremfree_locked(bp
);
4449 bp
->b_owner
= current_thread();
4452 SET(bp
->b_lflags
, BL_BUSY
);
4455 flush_table
[buf_count
] = bp
;
4459 if (buf_count
>= NFLUSH
) {
4460 lck_mtx_unlock(buf_mtxp
);
4462 qsort(flush_table
, buf_count
, sizeof(struct buf
*), bp_cmp
);
4464 for (i
= 0; i
< buf_count
; i
++) {
4465 buf_bawrite(flush_table
[i
]);
4471 lck_mtx_unlock(buf_mtxp
);
4473 if (buf_count
> 0) {
4474 qsort(flush_table
, buf_count
, sizeof(struct buf
*), bp_cmp
);
4476 for (i
= 0; i
< buf_count
; i
++) {
4477 buf_bawrite(flush_table
[i
]);
4481 return (total_writes
);
4488 /* XXX move this to a separate file */
4491 * NOTE: THIS CODE HAS NOT BEEN UPDATED
4492 * WITH RESPECT TO THE NEW LOCKING MODEL
4497 * Dynamic Scaling of the Buffer Queues
4500 typedef long long blsize_t
;
4502 blsize_t MAXNBUF
; /* initialize to (sane_size / PAGE_SIZE) */
4503 /* Global tunable limits */
4504 blsize_t nbufh
; /* number of buffer headers */
4505 blsize_t nbuflow
; /* minimum number of buffer headers required */
4506 blsize_t nbufhigh
; /* maximum number of buffer headers allowed */
4507 blsize_t nbuftarget
; /* preferred number of buffer headers */
4512 * 1. 0 < nbuflow <= nbufh <= nbufhigh
4513 * 2. nbufhigh <= MAXNBUF
4514 * 3. 0 < nbuflow <= nbuftarget <= nbufhigh
4515 * 4. nbufh can not be set by sysctl().
4518 /* Per queue tunable limits */
4521 blsize_t bl_nlow
; /* minimum number of buffer headers required */
4522 blsize_t bl_num
; /* number of buffer headers on the queue */
4523 blsize_t bl_nlhigh
; /* maximum number of buffer headers allowed */
4524 blsize_t bl_target
; /* preferred number of buffer headers */
4525 long bl_stale
; /* Seconds after which a buffer is considered stale */
4531 * 1. 0 <= bl_nlow <= bl_num <= bl_nlhigh
4532 * 2. bl_nlhigh <= MAXNBUF
4533 * 3. bufqlim[BQ_META].bl_nlow != 0
4534 * 4. bufqlim[BQ_META].bl_nlow > (number of possible concurrent
4535 * file system IO operations)
4536 * 5. bl_num can not be set by sysctl().
4537 * 6. bl_nhigh <= nbufhigh
4543 * Defining it blsize_t as long permits 2^31 buffer headers per queue.
4544 * Which can describe (2^31 * PAGE_SIZE) memory per queue.
4546 * These limits are exported to by means of sysctl().
4547 * It was decided to define blsize_t as a 64 bit quantity.
4548 * This will make sure that we will not be required to change it
4549 * as long as we do not exceed 64 bit address space for the kernel.
4551 * low and high numbers parameters initialized at compile time
4552 * and boot arguments can be used to override them. sysctl()
4553 * would not change the value. sysctl() can get all the values
4554 * but can set only target. num is the current level.
4556 * Advantages of having a "bufqscan" thread doing the balancing are,
4557 * Keep enough bufs on BQ_EMPTY.
4558 * getnewbuf() by default will always select a buffer from the BQ_EMPTY.
4559 * getnewbuf() perfoms best if a buffer was found there.
4560 * Also this minimizes the possibility of starting IO
4561 * from getnewbuf(). That's a performance win, too.
4563 * Localize complex logic [balancing as well as time aging]
4566 * Simplify getnewbuf() logic by elimination of time aging code.
4572 * The goal of the dynamic scaling of the buffer queues to to keep
4573 * the size of the LRU close to bl_target. Buffers on a queue would
4576 * There would be a thread which will be responsible for "balancing"
4577 * the buffer cache queues.
4579 * The scan order would be: AGE, LRU, META, EMPTY.
4582 long bufqscanwait
= 0;
4584 static void bufqscan_thread();
4585 static int balancebufq(int q
);
4586 static int btrimempty(int n
);
4587 static __inline__
int initbufqscan(void);
4588 static __inline__
int nextbufq(int q
);
4589 static void buqlimprt(int all
);
4592 static __inline__
void
4595 if ((q
< 0) || (q
>= BQUEUES
))
4598 bufqlim
[q
].bl_num
++;
4602 static __inline__
void
4605 if ((q
< 0) || (q
>= BQUEUES
))
4608 bufqlim
[q
].bl_num
--;
4613 bufq_balance_thread_init(void)
4615 thread_t thread
= THREAD_NULL
;
4617 if (bufqscanwait
++ == 0) {
4619 /* Initalize globals */
4620 MAXNBUF
= (sane_size
/ PAGE_SIZE
);
4621 nbufh
= nbuf_headers
;
4622 nbuflow
= min(nbufh
, 100);
4623 nbufhigh
= min(MAXNBUF
, max(nbufh
, 2048));
4624 nbuftarget
= (sane_size
>> 5) / PAGE_SIZE
;
4625 nbuftarget
= max(nbuflow
, nbuftarget
);
4626 nbuftarget
= min(nbufhigh
, nbuftarget
);
4629 * Initialize the bufqlim
4633 bufqlim
[BQ_LOCKED
].bl_nlow
= 0;
4634 bufqlim
[BQ_LOCKED
].bl_nlhigh
= 32;
4635 bufqlim
[BQ_LOCKED
].bl_target
= 0;
4636 bufqlim
[BQ_LOCKED
].bl_stale
= 30;
4639 bufqlim
[BQ_LRU
].bl_nlow
= 0;
4640 bufqlim
[BQ_LRU
].bl_nlhigh
= nbufhigh
/4;
4641 bufqlim
[BQ_LRU
].bl_target
= nbuftarget
/4;
4642 bufqlim
[BQ_LRU
].bl_stale
= LRU_IS_STALE
;
4645 bufqlim
[BQ_AGE
].bl_nlow
= 0;
4646 bufqlim
[BQ_AGE
].bl_nlhigh
= nbufhigh
/4;
4647 bufqlim
[BQ_AGE
].bl_target
= nbuftarget
/4;
4648 bufqlim
[BQ_AGE
].bl_stale
= AGE_IS_STALE
;
4651 bufqlim
[BQ_EMPTY
].bl_nlow
= 0;
4652 bufqlim
[BQ_EMPTY
].bl_nlhigh
= nbufhigh
/4;
4653 bufqlim
[BQ_EMPTY
].bl_target
= nbuftarget
/4;
4654 bufqlim
[BQ_EMPTY
].bl_stale
= 600000;
4657 bufqlim
[BQ_META
].bl_nlow
= 0;
4658 bufqlim
[BQ_META
].bl_nlhigh
= nbufhigh
/4;
4659 bufqlim
[BQ_META
].bl_target
= nbuftarget
/4;
4660 bufqlim
[BQ_META
].bl_stale
= META_IS_STALE
;
4663 bufqlim
[BQ_LOCKED
].bl_nlow
= 0;
4664 bufqlim
[BQ_LOCKED
].bl_nlhigh
= 32;
4665 bufqlim
[BQ_LOCKED
].bl_target
= 0;
4666 bufqlim
[BQ_LOCKED
].bl_stale
= 30;
4671 /* create worker thread */
4672 kernel_thread_start((thread_continue_t
)bufqscan_thread
, NULL
, &thread
);
4673 thread_deallocate(thread
);
4676 /* The workloop for the buffer balancing thread */
4684 int q
; /* buffer queue to process */
4688 moretodo
|= balancebufq(q
);
4697 (void)tsleep((void *)&bufqscanwait
, PRIBIO
, "bufqscanwait", 60 * hz
);
4702 /* Seed for the buffer queue balancing */
4703 static __inline__
int
4706 /* Start with AGE queue */
4710 /* Pick next buffer queue to balance */
4711 static __inline__
int
4714 int order
[] = { BQ_AGE
, BQ_LRU
, BQ_META
, BQ_EMPTY
, 0 };
4721 /* function to balance the buffer queues */
4728 /* reject invalid q */
4729 if ((q
< 0) || (q
>= BQUEUES
))
4732 /* LOCKED or LAUNDRY queue MUST not be balanced */
4733 if ((q
== BQ_LOCKED
) || (q
== BQ_LAUNDRY
))
4736 n
= (bufqlim
[q
].bl_num
- bufqlim
[q
].bl_target
);
4738 /* If queue has less than target nothing more to do */
4743 /* Balance only a small amount (12.5%) at a time */
4747 /* EMPTY queue needs special handling */
4748 if (q
== BQ_EMPTY
) {
4749 moretodo
|= btrimempty(n
);
4753 t
= buf_timestamp():
4755 for (; n
> 0; n
--) {
4756 struct buf
*bp
= bufqueues
[q
].tqh_first
;
4760 /* check if it's stale */
4761 if ((t
- bp
->b_timestamp
) > bufqlim
[q
].bl_stale
) {
4762 if (bcleanbuf(bp
, FALSE
)) {
4763 /* buf_bawrite() issued, bp not ready */
4766 /* release the cleaned buffer to BQ_EMPTY */
4767 SET(bp
->b_flags
, B_INVAL
);
4782 * When struct buf are allocated dynamically, this would
4783 * reclaim upto 'n' struct buf from the empty queue.
4793 static char *bname
[BQUEUES
] =
4794 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
4797 for (i
= 0; i
< BQUEUES
; i
++) {
4798 printf("%s : ", bname
[i
]);
4799 printf("min = %ld, ", (long)bufqlim
[i
].bl_nlow
);
4800 printf("cur = %ld, ", (long)bufqlim
[i
].bl_num
);
4801 printf("max = %ld, ", (long)bufqlim
[i
].bl_nlhigh
);
4802 printf("target = %ld, ", (long)bufqlim
[i
].bl_target
);
4803 printf("stale after %ld seconds\n", bufqlim
[i
].bl_stale
);
4806 for (i
= 0; i
< BQUEUES
; i
++) {
4807 printf("%s : ", bname
[i
]);
4808 printf("cur = %ld, ", (long)bufqlim
[i
].bl_num
);