2 * Copyright (c) 2000-2010 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>
115 static __inline__
void bufqinc(int q
);
116 static __inline__
void bufqdec(int q
);
119 int bcleanbuf(buf_t bp
, boolean_t discard
);
120 static int brecover_data(buf_t bp
);
121 static boolean_t
incore(vnode_t vp
, daddr64_t blkno
);
122 /* timeout is in msecs */
123 static buf_t
getnewbuf(int slpflag
, int slptimeo
, int *queue
);
124 static void bremfree_locked(buf_t bp
);
125 static void buf_reassign(buf_t bp
, vnode_t newvp
);
126 static errno_t
buf_acquire_locked(buf_t bp
, int flags
, int slpflag
, int slptimeo
);
127 static int buf_iterprepare(vnode_t vp
, struct buflists
*, int flags
);
128 static void buf_itercomplete(vnode_t vp
, struct buflists
*, int flags
);
129 static boolean_t
buffer_cache_gc(int);
130 static buf_t
buf_brelse_shadow(buf_t bp
);
131 static void buf_free_meta_store(buf_t bp
);
133 static buf_t
buf_create_shadow_internal(buf_t bp
, boolean_t force_copy
,
134 uintptr_t external_storage
, void (*iodone
)(buf_t
, void *), void *arg
, int priv
);
137 __private_extern__
int bdwrite_internal(buf_t
, int);
139 /* zone allocated buffer headers */
140 static void bufzoneinit(void) __attribute__((section("__TEXT, initcode")));
141 static void bcleanbuf_thread_init(void) __attribute__((section("__TEXT, initcode")));
142 static void bcleanbuf_thread(void);
144 static zone_t buf_hdr_zone
;
145 static int buf_hdr_count
;
149 * Definitions for the buffer hash lists.
151 #define BUFHASH(dvp, lbn) \
152 (&bufhashtbl[((long)(dvp) / sizeof(*(dvp)) + (int)(lbn)) & bufhash])
153 LIST_HEAD(bufhashhdr
, buf
) *bufhashtbl
, invalhash
;
156 static buf_t
incore_locked(vnode_t vp
, daddr64_t blkno
, struct bufhashhdr
*dp
);
158 /* Definitions for the buffer stats. */
159 struct bufstats bufstats
;
161 /* Number of delayed write buffers */
164 static int boot_nbuf_headers
= 0;
166 static TAILQ_HEAD(delayqueue
, buf
) delaybufqueue
;
168 static TAILQ_HEAD(ioqueue
, buf
) iobufqueue
;
169 static TAILQ_HEAD(bqueues
, buf
) bufqueues
[BQUEUES
];
170 static int needbuffer
;
171 static int need_iobuffer
;
173 static lck_grp_t
*buf_mtx_grp
;
174 static lck_attr_t
*buf_mtx_attr
;
175 static lck_grp_attr_t
*buf_mtx_grp_attr
;
176 static lck_mtx_t
*iobuffer_mtxp
;
177 static lck_mtx_t
*buf_mtxp
;
179 static int buf_busycount
;
181 static __inline__
int
190 * Insq/Remq for the buffer free lists.
193 #define binsheadfree(bp, dp, whichq) do { \
194 TAILQ_INSERT_HEAD(dp, bp, b_freelist); \
198 #define binstailfree(bp, dp, whichq) do { \
199 TAILQ_INSERT_TAIL(dp, bp, b_freelist); \
203 #define binsheadfree(bp, dp, whichq) do { \
204 TAILQ_INSERT_HEAD(dp, bp, b_freelist); \
207 #define binstailfree(bp, dp, whichq) do { \
208 TAILQ_INSERT_TAIL(dp, bp, b_freelist); \
213 #define BHASHENTCHECK(bp) \
214 if ((bp)->b_hash.le_prev != (struct buf **)0xdeadbeef) \
215 panic("%p: b_hash.le_prev is not deadbeef", (bp));
217 #define BLISTNONE(bp) \
218 (bp)->b_hash.le_next = (struct buf *)0; \
219 (bp)->b_hash.le_prev = (struct buf **)0xdeadbeef;
222 * Insq/Remq for the vnode usage lists.
224 #define bufinsvn(bp, dp) LIST_INSERT_HEAD(dp, bp, b_vnbufs)
225 #define bufremvn(bp) { \
226 LIST_REMOVE(bp, b_vnbufs); \
227 (bp)->b_vnbufs.le_next = NOLIST; \
231 * Time in seconds before a buffer on a list is
232 * considered as a stale buffer
234 #define LRU_IS_STALE 120 /* default value for the LRU */
235 #define AGE_IS_STALE 60 /* default value for the AGE */
236 #define META_IS_STALE 180 /* default value for the BQ_META */
238 int lru_is_stale
= LRU_IS_STALE
;
239 int age_is_stale
= AGE_IS_STALE
;
240 int meta_is_stale
= META_IS_STALE
;
242 #define MAXLAUNDRY 10
244 /* LIST_INSERT_HEAD() with assertions */
245 static __inline__
void
246 blistenterhead(struct bufhashhdr
* head
, buf_t bp
)
248 if ((bp
->b_hash
.le_next
= (head
)->lh_first
) != NULL
)
249 (head
)->lh_first
->b_hash
.le_prev
= &(bp
)->b_hash
.le_next
;
250 (head
)->lh_first
= bp
;
251 bp
->b_hash
.le_prev
= &(head
)->lh_first
;
252 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
253 panic("blistenterhead: le_prev is deadbeef");
256 static __inline__
void
257 binshash(buf_t bp
, struct bufhashhdr
*dp
)
261 #endif /* DIAGNOSTIC */
267 for(; nbp
!= NULL
; nbp
= nbp
->b_hash
.le_next
) {
269 panic("buf already in hashlist");
271 #endif /* DIAGNOSTIC */
273 blistenterhead(dp
, bp
);
276 static __inline__
void
279 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
280 panic("bremhash le_prev is deadbeef");
281 if (bp
->b_hash
.le_next
== bp
)
282 panic("bremhash: next points to self");
284 if (bp
->b_hash
.le_next
!= NULL
)
285 bp
->b_hash
.le_next
->b_hash
.le_prev
= bp
->b_hash
.le_prev
;
286 *bp
->b_hash
.le_prev
= (bp
)->b_hash
.le_next
;
292 static __inline__
void
293 bmovelaundry(buf_t bp
)
295 bp
->b_whichq
= BQ_LAUNDRY
;
296 bp
->b_timestamp
= buf_timestamp();
297 binstailfree(bp
, &bufqueues
[BQ_LAUNDRY
], BQ_LAUNDRY
);
301 static __inline__
void
302 buf_release_credentials(buf_t bp
)
304 if (IS_VALID_CRED(bp
->b_rcred
)) {
305 kauth_cred_unref(&bp
->b_rcred
);
307 if (IS_VALID_CRED(bp
->b_wcred
)) {
308 kauth_cred_unref(&bp
->b_wcred
);
314 buf_valid(buf_t bp
) {
316 if ( (bp
->b_flags
& (B_DONE
| B_DELWRI
)) )
322 buf_fromcache(buf_t bp
) {
324 if ( (bp
->b_flags
& B_CACHE
) )
330 buf_markinvalid(buf_t bp
) {
332 SET(bp
->b_flags
, B_INVAL
);
336 buf_markdelayed(buf_t bp
) {
338 if (!ISSET(bp
->b_flags
, B_DELWRI
)) {
339 SET(bp
->b_flags
, B_DELWRI
);
341 OSAddAtomicLong(1, &nbdwrite
);
342 buf_reassign(bp
, bp
->b_vp
);
344 SET(bp
->b_flags
, B_DONE
);
348 buf_markclean(buf_t bp
) {
350 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
351 CLR(bp
->b_flags
, B_DELWRI
);
353 OSAddAtomicLong(-1, &nbdwrite
);
354 buf_reassign(bp
, bp
->b_vp
);
359 buf_markeintr(buf_t bp
) {
361 SET(bp
->b_flags
, B_EINTR
);
366 buf_markaged(buf_t bp
) {
368 SET(bp
->b_flags
, B_AGE
);
374 if ((bp
->b_flags
& B_FUA
) == B_FUA
)
380 buf_markfua(buf_t bp
) {
382 SET(bp
->b_flags
, B_FUA
);
385 #ifdef CONFIG_PROTECT
387 buf_getcpaddr(buf_t bp
) {
388 return bp
->b_cpentry
;
392 buf_setcpaddr(buf_t bp
, void *cp_entry_addr
) {
393 bp
->b_cpentry
= (struct cprotect
*) cp_entry_addr
;
398 buf_getcpaddr(buf_t bp __unused
) {
403 buf_setcpaddr(buf_t bp __unused
, void *cp_entry_addr __unused
) {
406 #endif /* CONFIG_PROTECT */
409 buf_error(buf_t bp
) {
411 return (bp
->b_error
);
415 buf_seterror(buf_t bp
, errno_t error
) {
417 if ((bp
->b_error
= error
))
418 SET(bp
->b_flags
, B_ERROR
);
420 CLR(bp
->b_flags
, B_ERROR
);
424 buf_setflags(buf_t bp
, int32_t flags
) {
426 SET(bp
->b_flags
, (flags
& BUF_X_WRFLAGS
));
430 buf_clearflags(buf_t bp
, int32_t flags
) {
432 CLR(bp
->b_flags
, (flags
& BUF_X_WRFLAGS
));
436 buf_flags(buf_t bp
) {
438 return ((bp
->b_flags
& BUF_X_RDFLAGS
));
442 buf_reset(buf_t bp
, int32_t io_flags
) {
444 CLR(bp
->b_flags
, (B_READ
| B_WRITE
| B_ERROR
| B_DONE
| B_INVAL
| B_ASYNC
| B_NOCACHE
| B_FUA
));
445 SET(bp
->b_flags
, (io_flags
& (B_ASYNC
| B_READ
| B_WRITE
| B_NOCACHE
)));
451 buf_count(buf_t bp
) {
453 return (bp
->b_bcount
);
457 buf_setcount(buf_t bp
, uint32_t bcount
) {
459 bp
->b_bcount
= bcount
;
465 return (bp
->b_bufsize
);
469 buf_setsize(buf_t bp
, uint32_t bufsize
) {
471 bp
->b_bufsize
= bufsize
;
475 buf_resid(buf_t bp
) {
477 return (bp
->b_resid
);
481 buf_setresid(buf_t bp
, uint32_t resid
) {
487 buf_dirtyoff(buf_t bp
) {
489 return (bp
->b_dirtyoff
);
493 buf_dirtyend(buf_t bp
) {
495 return (bp
->b_dirtyend
);
499 buf_setdirtyoff(buf_t bp
, uint32_t dirtyoff
) {
501 bp
->b_dirtyoff
= dirtyoff
;
505 buf_setdirtyend(buf_t bp
, uint32_t dirtyend
) {
507 bp
->b_dirtyend
= dirtyend
;
511 buf_dataptr(buf_t bp
) {
513 return (bp
->b_datap
);
517 buf_setdataptr(buf_t bp
, uintptr_t data
) {
523 buf_vnode(buf_t bp
) {
529 buf_setvnode(buf_t bp
, vnode_t vp
) {
536 buf_callback(buf_t bp
)
538 if ( !(bp
->b_flags
& B_CALL
) )
539 return ((void *) NULL
);
541 return ((void *)bp
->b_iodone
);
546 buf_setcallback(buf_t bp
, void (*callback
)(buf_t
, void *), void *transaction
)
549 bp
->b_flags
|= (B_CALL
| B_ASYNC
);
551 bp
->b_flags
&= ~B_CALL
;
552 bp
->b_transaction
= transaction
;
553 bp
->b_iodone
= callback
;
559 buf_setupl(buf_t bp
, upl_t upl
, uint32_t offset
)
562 if ( !(bp
->b_lflags
& BL_IOBUF
) )
566 bp
->b_flags
|= B_CLUSTER
;
568 bp
->b_flags
&= ~B_CLUSTER
;
570 bp
->b_uploffset
= offset
;
576 buf_clone(buf_t bp
, int io_offset
, int io_size
, void (*iodone
)(buf_t
, void *), void *arg
)
580 if (io_offset
< 0 || io_size
< 0)
583 if ((unsigned)(io_offset
+ io_size
) > (unsigned)bp
->b_bcount
)
586 if (bp
->b_flags
& B_CLUSTER
) {
587 if (io_offset
&& ((bp
->b_uploffset
+ io_offset
) & PAGE_MASK
))
590 if (((bp
->b_uploffset
+ io_offset
+ io_size
) & PAGE_MASK
) && ((io_offset
+ io_size
) < bp
->b_bcount
))
593 io_bp
= alloc_io_buf(bp
->b_vp
, 0);
595 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
);
598 io_bp
->b_transaction
= arg
;
599 io_bp
->b_iodone
= iodone
;
600 io_bp
->b_flags
|= B_CALL
;
602 if (bp
->b_flags
& B_CLUSTER
) {
603 io_bp
->b_upl
= bp
->b_upl
;
604 io_bp
->b_uploffset
= bp
->b_uploffset
+ io_offset
;
606 io_bp
->b_datap
= (uintptr_t)(((char *)bp
->b_datap
) + io_offset
);
608 io_bp
->b_bcount
= io_size
;
617 if (bp
->b_lflags
& BL_SHADOW
)
624 buf_create_shadow_priv(buf_t bp
, boolean_t force_copy
, uintptr_t external_storage
, void (*iodone
)(buf_t
, void *), void *arg
)
626 return (buf_create_shadow_internal(bp
, force_copy
, external_storage
, iodone
, arg
, 1));
630 buf_create_shadow(buf_t bp
, boolean_t force_copy
, uintptr_t external_storage
, void (*iodone
)(buf_t
, void *), void *arg
)
632 return (buf_create_shadow_internal(bp
, force_copy
, external_storage
, iodone
, arg
, 0));
637 buf_create_shadow_internal(buf_t bp
, boolean_t force_copy
, uintptr_t external_storage
, void (*iodone
)(buf_t
, void *), void *arg
, int priv
)
641 KERNEL_DEBUG(0xbbbbc000 | DBG_FUNC_START
, bp
, 0, 0, 0, 0);
643 if ( !(bp
->b_flags
& B_META
) || (bp
->b_lflags
& BL_IOBUF
)) {
645 KERNEL_DEBUG(0xbbbbc000 | DBG_FUNC_END
, bp
, 0, 0, 0, 0);
648 #ifdef BUF_MAKE_PRIVATE
649 if (bp
->b_shadow_ref
&& bp
->b_data_ref
== 0 && external_storage
== 0)
650 panic("buf_create_shadow: %p is in the private state (%d, %d)", bp
, bp
->b_shadow_ref
, bp
->b_data_ref
);
652 io_bp
= alloc_io_buf(bp
->b_vp
, priv
);
654 io_bp
->b_flags
= bp
->b_flags
& (B_META
| B_ZALLOC
| B_ASYNC
| B_READ
| B_FUA
);
655 io_bp
->b_blkno
= bp
->b_blkno
;
656 io_bp
->b_lblkno
= bp
->b_lblkno
;
659 io_bp
->b_transaction
= arg
;
660 io_bp
->b_iodone
= iodone
;
661 io_bp
->b_flags
|= B_CALL
;
663 if (force_copy
== FALSE
) {
664 io_bp
->b_bcount
= bp
->b_bcount
;
665 io_bp
->b_bufsize
= bp
->b_bufsize
;
667 if (external_storage
) {
668 io_bp
->b_datap
= external_storage
;
669 #ifdef BUF_MAKE_PRIVATE
670 io_bp
->b_data_store
= NULL
;
673 io_bp
->b_datap
= bp
->b_datap
;
674 #ifdef BUF_MAKE_PRIVATE
675 io_bp
->b_data_store
= bp
;
678 *(buf_t
*)(&io_bp
->b_orig
) = bp
;
680 lck_mtx_lock_spin(buf_mtxp
);
682 io_bp
->b_lflags
|= BL_SHADOW
;
683 io_bp
->b_shadow
= bp
->b_shadow
;
684 bp
->b_shadow
= io_bp
;
687 #ifdef BUF_MAKE_PRIVATE
688 if (external_storage
)
689 io_bp
->b_lflags
|= BL_EXTERNAL
;
693 lck_mtx_unlock(buf_mtxp
);
695 if (external_storage
) {
696 #ifdef BUF_MAKE_PRIVATE
697 io_bp
->b_lflags
|= BL_EXTERNAL
;
699 io_bp
->b_bcount
= bp
->b_bcount
;
700 io_bp
->b_bufsize
= bp
->b_bufsize
;
701 io_bp
->b_datap
= external_storage
;
703 allocbuf(io_bp
, bp
->b_bcount
);
705 io_bp
->b_lflags
|= BL_IOBUF_ALLOC
;
707 bcopy((caddr_t
)bp
->b_datap
, (caddr_t
)io_bp
->b_datap
, bp
->b_bcount
);
709 #ifdef BUF_MAKE_PRIVATE
710 io_bp
->b_data_store
= NULL
;
713 KERNEL_DEBUG(0xbbbbc000 | DBG_FUNC_END
, bp
, bp
->b_shadow_ref
, 0, io_bp
, 0);
719 #ifdef BUF_MAKE_PRIVATE
721 buf_make_private(buf_t bp
)
727 KERNEL_DEBUG(0xbbbbc004 | DBG_FUNC_START
, bp
, bp
->b_shadow_ref
, 0, 0, 0);
729 if (bp
->b_shadow_ref
== 0 || bp
->b_data_ref
== 0 || ISSET(bp
->b_lflags
, BL_SHADOW
)) {
731 KERNEL_DEBUG(0xbbbbc004 | DBG_FUNC_END
, bp
, bp
->b_shadow_ref
, 0, EINVAL
, 0);
734 my_buf
.b_flags
= B_META
;
735 my_buf
.b_datap
= (uintptr_t)NULL
;
736 allocbuf(&my_buf
, bp
->b_bcount
);
738 bcopy((caddr_t
)bp
->b_datap
, (caddr_t
)my_buf
.b_datap
, bp
->b_bcount
);
740 lck_mtx_lock_spin(buf_mtxp
);
742 for (t_bp
= bp
->b_shadow
; t_bp
; t_bp
= t_bp
->b_shadow
) {
743 if ( !ISSET(bp
->b_lflags
, BL_EXTERNAL
))
748 if (ds_bp
== NULL
&& bp
->b_data_ref
)
749 panic("buf_make_private: b_data_ref != 0 && ds_bp == NULL");
751 if (ds_bp
&& (bp
->b_data_ref
== 0 || bp
->b_shadow_ref
== 0))
752 panic("buf_make_private: ref_count == 0 && ds_bp != NULL");
755 lck_mtx_unlock(buf_mtxp
);
757 buf_free_meta_store(&my_buf
);
759 KERNEL_DEBUG(0xbbbbc004 | DBG_FUNC_END
, bp
, bp
->b_shadow_ref
, 0, EINVAL
, 0);
762 for (t_bp
= bp
->b_shadow
; t_bp
; t_bp
= t_bp
->b_shadow
) {
763 if ( !ISSET(t_bp
->b_lflags
, BL_EXTERNAL
))
764 t_bp
->b_data_store
= ds_bp
;
766 ds_bp
->b_data_ref
= bp
->b_data_ref
;
769 bp
->b_datap
= my_buf
.b_datap
;
771 lck_mtx_unlock(buf_mtxp
);
773 KERNEL_DEBUG(0xbbbbc004 | DBG_FUNC_END
, bp
, bp
->b_shadow_ref
, 0, 0, 0);
780 buf_setfilter(buf_t bp
, void (*filter
)(buf_t
, void *), void *transaction
,
781 void (**old_iodone
)(buf_t
, void *), void **old_transaction
)
784 *old_iodone
= bp
->b_iodone
;
786 *old_transaction
= bp
->b_transaction
;
788 bp
->b_transaction
= transaction
;
789 bp
->b_iodone
= filter
;
791 bp
->b_flags
|= B_FILTER
;
793 bp
->b_flags
&= ~B_FILTER
;
798 buf_blkno(buf_t bp
) {
800 return (bp
->b_blkno
);
804 buf_lblkno(buf_t bp
) {
806 return (bp
->b_lblkno
);
810 buf_setblkno(buf_t bp
, daddr64_t blkno
) {
816 buf_setlblkno(buf_t bp
, daddr64_t lblkno
) {
818 bp
->b_lblkno
= lblkno
;
822 buf_device(buf_t bp
) {
828 buf_setdevice(buf_t bp
, vnode_t vp
) {
830 if ((vp
->v_type
!= VBLK
) && (vp
->v_type
!= VCHR
))
832 bp
->b_dev
= vp
->v_rdev
;
839 buf_drvdata(buf_t bp
) {
841 return (bp
->b_drvdata
);
845 buf_setdrvdata(buf_t bp
, void *drvdata
) {
847 bp
->b_drvdata
= drvdata
;
851 buf_fsprivate(buf_t bp
) {
853 return (bp
->b_fsprivate
);
857 buf_setfsprivate(buf_t bp
, void *fsprivate
) {
859 bp
->b_fsprivate
= fsprivate
;
863 buf_rcred(buf_t bp
) {
865 return (bp
->b_rcred
);
869 buf_wcred(buf_t bp
) {
871 return (bp
->b_wcred
);
881 buf_uploffset(buf_t bp
) {
883 return ((uint32_t)(bp
->b_uploffset
));
894 buf_map(buf_t bp
, caddr_t
*io_addr
)
900 if ( !(bp
->b_flags
& B_CLUSTER
)) {
901 *io_addr
= (caddr_t
)bp
->b_datap
;
904 real_bp
= (buf_t
)(bp
->b_real_bp
);
906 if (real_bp
&& real_bp
->b_datap
) {
908 * b_real_bp is only valid if B_CLUSTER is SET
909 * if it's non-zero, than someone did a cluster_bp call
910 * if the backing physical pages were already mapped
911 * in before the call to cluster_bp (non-zero b_datap),
912 * than we just use that mapping
914 *io_addr
= (caddr_t
)real_bp
->b_datap
;
917 kret
= ubc_upl_map(bp
->b_upl
, &vaddr
); /* Map it in */
919 if (kret
!= KERN_SUCCESS
) {
924 vaddr
+= bp
->b_uploffset
;
926 *io_addr
= (caddr_t
)vaddr
;
937 if ( !(bp
->b_flags
& B_CLUSTER
))
940 * see buf_map for the explanation
942 real_bp
= (buf_t
)(bp
->b_real_bp
);
944 if (real_bp
&& real_bp
->b_datap
)
947 if ((bp
->b_lflags
& BL_IOBUF
) &&
948 ((bp
->b_flags
& (B_PAGEIO
| B_READ
)) != (B_PAGEIO
| B_READ
))) {
950 * ignore pageins... the 'right' thing will
951 * happen due to the way we handle speculative
954 * when we commit these pages, we'll hit
955 * it with UPL_COMMIT_INACTIVE which
956 * will clear the reference bit that got
957 * turned on when we touched the mapping
959 bp
->b_flags
|= B_AGE
;
961 kret
= ubc_upl_unmap(bp
->b_upl
);
963 if (kret
!= KERN_SUCCESS
)
970 buf_clear(buf_t bp
) {
973 if (buf_map(bp
, &baddr
) == 0) {
974 bzero(baddr
, bp
->b_bcount
);
981 * Read or write a buffer that is not contiguous on disk.
982 * buffer is marked done/error at the conclusion
985 buf_strategy_fragmented(vnode_t devvp
, buf_t bp
, off_t f_offset
, size_t contig_bytes
)
987 vnode_t vp
= buf_vnode(bp
);
988 buf_t io_bp
; /* For reading or writing a single block */
991 size_t io_contig_bytes
;
997 * save our starting point... the bp was already mapped
998 * in buf_strategy before we got called
999 * no sense doing it again.
1001 io_blkno
= bp
->b_blkno
;
1003 * Make sure we redo this mapping for the next I/O
1004 * i.e. this can never be a 'permanent' mapping
1006 bp
->b_blkno
= bp
->b_lblkno
;
1009 * Get an io buffer to do the deblocking
1011 io_bp
= alloc_io_buf(devvp
, 0);
1013 io_bp
->b_lblkno
= bp
->b_lblkno
;
1014 io_bp
->b_datap
= bp
->b_datap
;
1015 io_resid
= bp
->b_bcount
;
1016 io_direction
= bp
->b_flags
& B_READ
;
1017 io_contig_bytes
= contig_bytes
;
1019 if (bp
->b_flags
& B_READ
)
1020 bmap_flags
= VNODE_READ
;
1022 bmap_flags
= VNODE_WRITE
;
1027 * this is unexepected, but we'll allow for it
1029 bzero((caddr_t
)io_bp
->b_datap
, (int)io_contig_bytes
);
1031 io_bp
->b_bcount
= io_contig_bytes
;
1032 io_bp
->b_bufsize
= io_contig_bytes
;
1033 io_bp
->b_resid
= io_contig_bytes
;
1034 io_bp
->b_blkno
= io_blkno
;
1036 buf_reset(io_bp
, io_direction
);
1039 * Call the device to do the I/O and wait for it. Make sure the appropriate party is charged for write
1042 if (!ISSET(bp
->b_flags
, B_READ
))
1043 OSAddAtomic(1, &devvp
->v_numoutput
);
1045 if ((error
= VNOP_STRATEGY(io_bp
)))
1047 if ((error
= (int)buf_biowait(io_bp
)))
1049 if (io_bp
->b_resid
) {
1050 io_resid
-= (io_contig_bytes
- io_bp
->b_resid
);
1054 if ((io_resid
-= io_contig_bytes
) == 0)
1056 f_offset
+= io_contig_bytes
;
1057 io_bp
->b_datap
+= io_contig_bytes
;
1060 * Map the current position to a physical block number
1062 if ((error
= VNOP_BLOCKMAP(vp
, f_offset
, io_resid
, &io_blkno
, &io_contig_bytes
, NULL
, bmap_flags
, NULL
)))
1068 buf_seterror(bp
, error
);
1069 bp
->b_resid
= io_resid
;
1071 * This I/O is now complete
1080 * struct vnop_strategy_args {
1085 buf_strategy(vnode_t devvp
, void *ap
)
1087 buf_t bp
= ((struct vnop_strategy_args
*)ap
)->a_bp
;
1088 vnode_t vp
= bp
->b_vp
;
1092 int dtrace_io_start_flag
= 0; /* We only want to trip the io:::start
1093 * probe once, with the true phisical
1094 * block in place (b_blkno)
1099 if (vp
== NULL
|| vp
->v_type
== VCHR
|| vp
->v_type
== VBLK
)
1100 panic("buf_strategy: b_vp == NULL || vtype == VCHR | VBLK\n");
1102 * associate the physical device with
1103 * with this buf_t even if we don't
1104 * end up issuing the I/O...
1106 bp
->b_dev
= devvp
->v_rdev
;
1108 if (bp
->b_flags
& B_READ
)
1109 bmap_flags
= VNODE_READ
;
1111 bmap_flags
= VNODE_WRITE
;
1113 if ( !(bp
->b_flags
& B_CLUSTER
)) {
1115 if ( (bp
->b_upl
) ) {
1117 * we have a UPL associated with this bp
1118 * go through cluster_bp which knows how
1119 * to deal with filesystem block sizes
1120 * that aren't equal to the page size
1122 DTRACE_IO1(start
, buf_t
, bp
);
1123 return (cluster_bp(bp
));
1125 if (bp
->b_blkno
== bp
->b_lblkno
) {
1127 size_t contig_bytes
;
1129 if ((error
= VNOP_BLKTOOFF(vp
, bp
->b_lblkno
, &f_offset
))) {
1130 DTRACE_IO1(start
, buf_t
, bp
);
1131 buf_seterror(bp
, error
);
1136 if ((error
= VNOP_BLOCKMAP(vp
, f_offset
, bp
->b_bcount
, &bp
->b_blkno
, &contig_bytes
, NULL
, bmap_flags
, NULL
))) {
1137 DTRACE_IO1(start
, buf_t
, bp
);
1138 buf_seterror(bp
, error
);
1144 DTRACE_IO1(start
, buf_t
, bp
);
1146 dtrace_io_start_flag
= 1;
1147 #endif /* CONFIG_DTRACE */
1149 if ((bp
->b_blkno
== -1) || (contig_bytes
== 0)) {
1150 /* Set block number to force biodone later */
1154 else if ((long)contig_bytes
< bp
->b_bcount
) {
1155 return (buf_strategy_fragmented(devvp
, bp
, f_offset
, contig_bytes
));
1160 if (dtrace_io_start_flag
== 0) {
1161 DTRACE_IO1(start
, buf_t
, bp
);
1162 dtrace_io_start_flag
= 1;
1164 #endif /* CONFIG_DTRACE */
1166 if (bp
->b_blkno
== -1) {
1173 if (dtrace_io_start_flag
== 0)
1174 DTRACE_IO1(start
, buf_t
, bp
);
1175 #endif /* CONFIG_DTRACE */
1178 * we can issue the I/O because...
1179 * either B_CLUSTER is set which
1180 * means that the I/O is properly set
1181 * up to be a multiple of the page size, or
1182 * we were able to successfully set up the
1183 * phsyical block mapping
1185 return (VOCALL(devvp
->v_op
, VOFFSET(vnop_strategy
), ap
));
1191 buf_alloc(vnode_t vp
)
1193 return(alloc_io_buf(vp
, 0));
1197 buf_free(buf_t bp
) {
1204 * iterate buffers for the specified vp.
1205 * if BUF_SCAN_DIRTY is set, do the dirty list
1206 * if BUF_SCAN_CLEAN is set, do the clean list
1207 * if neither flag is set, default to BUF_SCAN_DIRTY
1208 * if BUF_NOTIFY_BUSY is set, call the callout function using a NULL bp for busy pages
1211 struct buf_iterate_info_t
{
1213 struct buflists
*listhead
;
1217 buf_iterate(vnode_t vp
, int (*callout
)(buf_t
, void *), int flags
, void *arg
)
1221 struct buflists local_iterblkhd
;
1222 int lock_flags
= BAC_NOWAIT
| BAC_REMOVE
;
1223 int notify_busy
= flags
& BUF_NOTIFY_BUSY
;
1224 struct buf_iterate_info_t list
[2];
1227 if (flags
& BUF_SKIP_LOCKED
)
1228 lock_flags
|= BAC_SKIP_LOCKED
;
1229 if (flags
& BUF_SKIP_NONLOCKED
)
1230 lock_flags
|= BAC_SKIP_NONLOCKED
;
1232 if ( !(flags
& (BUF_SCAN_DIRTY
| BUF_SCAN_CLEAN
)))
1233 flags
|= BUF_SCAN_DIRTY
;
1237 if (flags
& BUF_SCAN_DIRTY
) {
1238 list
[num_lists
].flag
= VBI_DIRTY
;
1239 list
[num_lists
].listhead
= &vp
->v_dirtyblkhd
;
1242 if (flags
& BUF_SCAN_CLEAN
) {
1243 list
[num_lists
].flag
= VBI_CLEAN
;
1244 list
[num_lists
].listhead
= &vp
->v_cleanblkhd
;
1248 for (i
= 0; i
< num_lists
; i
++) {
1249 lck_mtx_lock(buf_mtxp
);
1251 if (buf_iterprepare(vp
, &local_iterblkhd
, list
[i
].flag
)) {
1252 lck_mtx_unlock(buf_mtxp
);
1255 while (!LIST_EMPTY(&local_iterblkhd
)) {
1256 bp
= LIST_FIRST(&local_iterblkhd
);
1257 LIST_REMOVE(bp
, b_vnbufs
);
1258 LIST_INSERT_HEAD(list
[i
].listhead
, bp
, b_vnbufs
);
1260 if (buf_acquire_locked(bp
, lock_flags
, 0, 0)) {
1268 lck_mtx_unlock(buf_mtxp
);
1270 retval
= callout(bp
, arg
);
1279 case BUF_RETURNED_DONE
:
1282 lck_mtx_lock(buf_mtxp
);
1284 case BUF_CLAIMED_DONE
:
1285 lck_mtx_lock(buf_mtxp
);
1288 lck_mtx_lock(buf_mtxp
);
1289 } /* while list has more nodes */
1291 buf_itercomplete(vp
, &local_iterblkhd
, list
[i
].flag
);
1292 lck_mtx_unlock(buf_mtxp
);
1293 } /* for each list */
1298 * Flush out and invalidate all buffers associated with a vnode.
1301 buf_invalidateblks(vnode_t vp
, int flags
, int slpflag
, int slptimeo
)
1306 int must_rescan
= 1;
1307 struct buflists local_iterblkhd
;
1310 if (LIST_EMPTY(&vp
->v_cleanblkhd
) && LIST_EMPTY(&vp
->v_dirtyblkhd
))
1313 lck_mtx_lock(buf_mtxp
);
1316 if (must_rescan
== 0)
1318 * the lists may not be empty, but all that's left at this
1319 * point are metadata or B_LOCKED buffers which are being
1320 * skipped... we know this because we made it through both
1321 * the clean and dirty lists without dropping buf_mtxp...
1322 * each time we drop buf_mtxp we bump "must_rescan"
1325 if (LIST_EMPTY(&vp
->v_cleanblkhd
) && LIST_EMPTY(&vp
->v_dirtyblkhd
))
1329 * iterate the clean list
1331 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_CLEAN
)) {
1332 goto try_dirty_list
;
1334 while (!LIST_EMPTY(&local_iterblkhd
)) {
1336 bp
= LIST_FIRST(&local_iterblkhd
);
1338 LIST_REMOVE(bp
, b_vnbufs
);
1339 LIST_INSERT_HEAD(&vp
->v_cleanblkhd
, bp
, b_vnbufs
);
1342 * some filesystems distinguish meta data blocks with a negative logical block #
1344 if ((flags
& BUF_SKIP_META
) && (bp
->b_lblkno
< 0 || ISSET(bp
->b_flags
, B_META
)))
1347 aflags
= BAC_REMOVE
;
1349 if ( !(flags
& BUF_INVALIDATE_LOCKED
) )
1350 aflags
|= BAC_SKIP_LOCKED
;
1352 if ( (error
= (int)buf_acquire_locked(bp
, aflags
, slpflag
, slptimeo
)) ) {
1353 if (error
== EDEADLK
)
1355 * this buffer was marked B_LOCKED...
1356 * we didn't drop buf_mtxp, so we
1357 * we don't need to rescan
1360 if (error
== EAGAIN
) {
1362 * found a busy buffer... we blocked and
1363 * dropped buf_mtxp, so we're going to
1364 * need to rescan after this pass is completed
1370 * got some kind of 'real' error out of the msleep
1371 * in buf_acquire_locked, terminate the scan and return the error
1373 buf_itercomplete(vp
, &local_iterblkhd
, VBI_CLEAN
);
1375 lck_mtx_unlock(buf_mtxp
);
1378 lck_mtx_unlock(buf_mtxp
);
1380 if (bp
->b_flags
& B_LOCKED
)
1381 KERNEL_DEBUG(0xbbbbc038, bp
, 0, 0, 0, 0);
1383 CLR(bp
->b_flags
, B_LOCKED
);
1384 SET(bp
->b_flags
, B_INVAL
);
1387 lck_mtx_lock(buf_mtxp
);
1390 * by dropping buf_mtxp, we allow new
1391 * buffers to be added to the vnode list(s)
1392 * we'll have to rescan at least once more
1393 * if the queues aren't empty
1397 buf_itercomplete(vp
, &local_iterblkhd
, VBI_CLEAN
);
1401 * Now iterate on dirty blks
1403 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_DIRTY
)) {
1406 while (!LIST_EMPTY(&local_iterblkhd
)) {
1407 bp
= LIST_FIRST(&local_iterblkhd
);
1409 LIST_REMOVE(bp
, b_vnbufs
);
1410 LIST_INSERT_HEAD(&vp
->v_dirtyblkhd
, bp
, b_vnbufs
);
1413 * some filesystems distinguish meta data blocks with a negative logical block #
1415 if ((flags
& BUF_SKIP_META
) && (bp
->b_lblkno
< 0 || ISSET(bp
->b_flags
, B_META
)))
1418 aflags
= BAC_REMOVE
;
1420 if ( !(flags
& BUF_INVALIDATE_LOCKED
) )
1421 aflags
|= BAC_SKIP_LOCKED
;
1423 if ( (error
= (int)buf_acquire_locked(bp
, aflags
, slpflag
, slptimeo
)) ) {
1424 if (error
== EDEADLK
)
1426 * this buffer was marked B_LOCKED...
1427 * we didn't drop buf_mtxp, so we
1428 * we don't need to rescan
1431 if (error
== EAGAIN
) {
1433 * found a busy buffer... we blocked and
1434 * dropped buf_mtxp, so we're going to
1435 * need to rescan after this pass is completed
1441 * got some kind of 'real' error out of the msleep
1442 * in buf_acquire_locked, terminate the scan and return the error
1444 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1446 lck_mtx_unlock(buf_mtxp
);
1449 lck_mtx_unlock(buf_mtxp
);
1451 if (bp
->b_flags
& B_LOCKED
)
1452 KERNEL_DEBUG(0xbbbbc038, bp
, 0, 0, 1, 0);
1454 CLR(bp
->b_flags
, B_LOCKED
);
1455 SET(bp
->b_flags
, B_INVAL
);
1457 if (ISSET(bp
->b_flags
, B_DELWRI
) && (flags
& BUF_WRITE_DATA
))
1458 (void) VNOP_BWRITE(bp
);
1462 lck_mtx_lock(buf_mtxp
);
1464 * by dropping buf_mtxp, we allow new
1465 * buffers to be added to the vnode list(s)
1466 * we'll have to rescan at least once more
1467 * if the queues aren't empty
1471 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1473 lck_mtx_unlock(buf_mtxp
);
1479 buf_flushdirtyblks(vnode_t vp
, int wait
, int flags
, const char *msg
) {
1481 int writes_issued
= 0;
1484 struct buflists local_iterblkhd
;
1485 int lock_flags
= BAC_NOWAIT
| BAC_REMOVE
;
1487 if (flags
& BUF_SKIP_LOCKED
)
1488 lock_flags
|= BAC_SKIP_LOCKED
;
1489 if (flags
& BUF_SKIP_NONLOCKED
)
1490 lock_flags
|= BAC_SKIP_NONLOCKED
;
1492 lck_mtx_lock(buf_mtxp
);
1494 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_DIRTY
) == 0) {
1495 while (!LIST_EMPTY(&local_iterblkhd
)) {
1496 bp
= LIST_FIRST(&local_iterblkhd
);
1497 LIST_REMOVE(bp
, b_vnbufs
);
1498 LIST_INSERT_HEAD(&vp
->v_dirtyblkhd
, bp
, b_vnbufs
);
1500 if ((error
= buf_acquire_locked(bp
, lock_flags
, 0, 0)) == EBUSY
)
1504 lck_mtx_unlock(buf_mtxp
);
1506 bp
->b_flags
&= ~B_LOCKED
;
1509 * Wait for I/O associated with indirect blocks to complete,
1510 * since there is no way to quickly wait for them below.
1512 if ((bp
->b_vp
== vp
) || (wait
== 0))
1513 (void) buf_bawrite(bp
);
1515 (void) VNOP_BWRITE(bp
);
1518 lck_mtx_lock(buf_mtxp
);
1520 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1522 lck_mtx_unlock(buf_mtxp
);
1525 (void)vnode_waitforwrites(vp
, 0, 0, 0, msg
);
1527 if (vp
->v_dirtyblkhd
.lh_first
&& busy
) {
1529 * we had one or more BUSY buffers on
1530 * the dirtyblock list... most likely
1531 * these are due to delayed writes that
1532 * were moved to the bclean queue but
1533 * have not yet been 'written'.
1534 * if we issued some writes on the
1535 * previous pass, we try again immediately
1536 * if we didn't, we'll sleep for some time
1537 * to allow the state to change...
1539 if (writes_issued
== 0) {
1540 (void)tsleep((caddr_t
)&vp
->v_numoutput
,
1541 PRIBIO
+ 1, "vnode_flushdirtyblks", hz
/20);
1553 * called with buf_mtxp held...
1554 * this lock protects the queue manipulation
1557 buf_iterprepare(vnode_t vp
, struct buflists
*iterheadp
, int flags
)
1559 struct buflists
* listheadp
;
1561 if (flags
& VBI_DIRTY
)
1562 listheadp
= &vp
->v_dirtyblkhd
;
1564 listheadp
= &vp
->v_cleanblkhd
;
1566 while (vp
->v_iterblkflags
& VBI_ITER
) {
1567 vp
->v_iterblkflags
|= VBI_ITERWANT
;
1568 msleep(&vp
->v_iterblkflags
, buf_mtxp
, 0, "buf_iterprepare", NULL
);
1570 if (LIST_EMPTY(listheadp
)) {
1571 LIST_INIT(iterheadp
);
1574 vp
->v_iterblkflags
|= VBI_ITER
;
1576 iterheadp
->lh_first
= listheadp
->lh_first
;
1577 listheadp
->lh_first
->b_vnbufs
.le_prev
= &iterheadp
->lh_first
;
1578 LIST_INIT(listheadp
);
1584 * called with buf_mtxp held...
1585 * this lock protects the queue manipulation
1588 buf_itercomplete(vnode_t vp
, struct buflists
*iterheadp
, int flags
)
1590 struct buflists
* listheadp
;
1593 if (flags
& VBI_DIRTY
)
1594 listheadp
= &vp
->v_dirtyblkhd
;
1596 listheadp
= &vp
->v_cleanblkhd
;
1598 while (!LIST_EMPTY(iterheadp
)) {
1599 bp
= LIST_FIRST(iterheadp
);
1600 LIST_REMOVE(bp
, b_vnbufs
);
1601 LIST_INSERT_HEAD(listheadp
, bp
, b_vnbufs
);
1603 vp
->v_iterblkflags
&= ~VBI_ITER
;
1605 if (vp
->v_iterblkflags
& VBI_ITERWANT
) {
1606 vp
->v_iterblkflags
&= ~VBI_ITERWANT
;
1607 wakeup(&vp
->v_iterblkflags
);
1613 bremfree_locked(buf_t bp
)
1615 struct bqueues
*dp
= NULL
;
1618 whichq
= bp
->b_whichq
;
1621 if (bp
->b_shadow_ref
== 0)
1622 panic("bremfree_locked: %p not on freelist", bp
);
1624 * there are clones pointing to 'bp'...
1625 * therefore, it was not put on a freelist
1626 * when buf_brelse was last called on 'bp'
1631 * We only calculate the head of the freelist when removing
1632 * the last element of the list as that is the only time that
1633 * it is needed (e.g. to reset the tail pointer).
1635 * NB: This makes an assumption about how tailq's are implemented.
1637 if (bp
->b_freelist
.tqe_next
== NULL
) {
1638 dp
= &bufqueues
[whichq
];
1640 if (dp
->tqh_last
!= &bp
->b_freelist
.tqe_next
)
1641 panic("bremfree: lost tail");
1643 TAILQ_REMOVE(dp
, bp
, b_freelist
);
1648 if (whichq
== BQ_LAUNDRY
)
1652 bp
->b_timestamp
= 0;
1657 * Associate a buffer with a vnode.
1658 * buf_mtxp must be locked on entry
1661 bgetvp_locked(vnode_t vp
, buf_t bp
)
1665 panic("bgetvp_locked: not free");
1667 if (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
)
1668 bp
->b_dev
= vp
->v_rdev
;
1672 * Insert onto list for new vnode.
1674 bufinsvn(bp
, &vp
->v_cleanblkhd
);
1678 * Disassociate a buffer from a vnode.
1679 * buf_mtxp must be locked on entry
1682 brelvp_locked(buf_t bp
)
1685 * Delete from old vnode list, if on one.
1687 if (bp
->b_vnbufs
.le_next
!= NOLIST
)
1690 bp
->b_vp
= (vnode_t
)NULL
;
1694 * Reassign a buffer from one vnode to another.
1695 * Used to assign file specific control information
1696 * (indirect blocks) to the vnode to which they belong.
1699 buf_reassign(buf_t bp
, vnode_t newvp
)
1701 struct buflists
*listheadp
;
1703 if (newvp
== NULL
) {
1704 printf("buf_reassign: NULL");
1707 lck_mtx_lock_spin(buf_mtxp
);
1710 * Delete from old vnode list, if on one.
1712 if (bp
->b_vnbufs
.le_next
!= NOLIST
)
1715 * If dirty, put on list of dirty buffers;
1716 * otherwise insert onto list of clean buffers.
1718 if (ISSET(bp
->b_flags
, B_DELWRI
))
1719 listheadp
= &newvp
->v_dirtyblkhd
;
1721 listheadp
= &newvp
->v_cleanblkhd
;
1722 bufinsvn(bp
, listheadp
);
1724 lck_mtx_unlock(buf_mtxp
);
1727 static __inline__
void
1728 bufhdrinit(buf_t bp
)
1730 bzero((char *)bp
, sizeof *bp
);
1732 bp
->b_rcred
= NOCRED
;
1733 bp
->b_wcred
= NOCRED
;
1734 bp
->b_vnbufs
.le_next
= NOLIST
;
1735 bp
->b_flags
= B_INVAL
;
1741 * Initialize buffers and hash links for buffers.
1743 __private_extern__
void
1751 /* Initialize the buffer queues ('freelists') and the hash table */
1752 for (dp
= bufqueues
; dp
< &bufqueues
[BQUEUES
]; dp
++)
1754 bufhashtbl
= hashinit(nbuf_hashelements
, M_CACHE
, &bufhash
);
1758 /* Initialize the buffer headers */
1759 for (i
= 0; i
< max_nbuf_headers
; i
++) {
1761 bp
= &buf_headers
[i
];
1765 dp
= &bufqueues
[BQ_EMPTY
];
1766 bp
->b_whichq
= BQ_EMPTY
;
1767 bp
->b_timestamp
= buf_timestamp();
1768 binsheadfree(bp
, dp
, BQ_EMPTY
);
1769 binshash(bp
, &invalhash
);
1771 boot_nbuf_headers
= nbuf_headers
;
1773 TAILQ_INIT(&iobufqueue
);
1774 TAILQ_INIT(&delaybufqueue
);
1776 for (; i
< nbuf_headers
+ niobuf_headers
; i
++) {
1777 bp
= &buf_headers
[i
];
1780 binsheadfree(bp
, &iobufqueue
, -1);
1784 * allocate lock group attribute and group
1786 buf_mtx_grp_attr
= lck_grp_attr_alloc_init();
1787 buf_mtx_grp
= lck_grp_alloc_init("buffer cache", buf_mtx_grp_attr
);
1790 * allocate the lock attribute
1792 buf_mtx_attr
= lck_attr_alloc_init();
1795 * allocate and initialize mutex's for the buffer and iobuffer pools
1797 buf_mtxp
= lck_mtx_alloc_init(buf_mtx_grp
, buf_mtx_attr
);
1798 iobuffer_mtxp
= lck_mtx_alloc_init(buf_mtx_grp
, buf_mtx_attr
);
1800 if (iobuffer_mtxp
== NULL
)
1801 panic("couldn't create iobuffer mutex");
1803 if (buf_mtxp
== NULL
)
1804 panic("couldn't create buf mutex");
1807 * allocate and initialize cluster specific global locks...
1811 printf("using %d buffer headers and %d cluster IO buffer headers\n",
1812 nbuf_headers
, niobuf_headers
);
1814 /* Set up zones used by the buffer cache */
1817 /* start the bcleanbuf() thread */
1818 bcleanbuf_thread_init();
1820 /* Register a callout for relieving vm pressure */
1821 if (vm_set_buffer_cleanup_callout(buffer_cache_gc
) != KERN_SUCCESS
) {
1822 panic("Couldn't register buffer cache callout for vm pressure!\n");
1827 static void bufq_balance_thread_init(void) __attribute__((section("__TEXT, initcode")));
1828 /* create a thread to do dynamic buffer queue balancing */
1829 bufq_balance_thread_init();
1837 * Zones for the meta data buffers
1841 #define MAXMETA 8192
1843 struct meta_zone_entry
{
1847 const char *mz_name
;
1850 struct meta_zone_entry meta_zones
[] = {
1851 {NULL
, (MINMETA
* 1), 128 * (MINMETA
* 1), "buf.512" },
1852 {NULL
, (MINMETA
* 2), 64 * (MINMETA
* 2), "buf.1024" },
1853 {NULL
, (MINMETA
* 4), 16 * (MINMETA
* 4), "buf.2048" },
1854 {NULL
, (MINMETA
* 8), 512 * (MINMETA
* 8), "buf.4096" },
1855 {NULL
, (MINMETA
* 16), 512 * (MINMETA
* 16), "buf.8192" },
1856 {NULL
, 0, 0, "" } /* End */
1860 * Initialize the meta data zones
1867 for (i
= 0; meta_zones
[i
].mz_size
!= 0; i
++) {
1868 meta_zones
[i
].mz_zone
=
1869 zinit(meta_zones
[i
].mz_size
,
1870 meta_zones
[i
].mz_max
,
1872 meta_zones
[i
].mz_name
);
1873 zone_change(meta_zones
[i
].mz_zone
, Z_CALLERACCT
, FALSE
);
1875 buf_hdr_zone
= zinit(sizeof(struct buf
), 32, PAGE_SIZE
, "buf headers");
1876 zone_change(buf_hdr_zone
, Z_CALLERACCT
, FALSE
);
1879 static __inline__ zone_t
1880 getbufzone(size_t size
)
1884 if ((size
% 512) || (size
< MINMETA
) || (size
> MAXMETA
))
1885 panic("getbufzone: incorect size = %lu", size
);
1887 for (i
= 0; meta_zones
[i
].mz_size
!= 0; i
++) {
1888 if (meta_zones
[i
].mz_size
>= size
)
1892 return (meta_zones
[i
].mz_zone
);
1898 bio_doread(vnode_t vp
, daddr64_t blkno
, int size
, kauth_cred_t cred
, int async
, int queuetype
)
1902 bp
= buf_getblk(vp
, blkno
, size
, 0, 0, queuetype
);
1905 * If buffer does not have data valid, start a read.
1906 * Note that if buffer is B_INVAL, buf_getblk() won't return it.
1907 * Therefore, it's valid if it's I/O has completed or been delayed.
1909 if (!ISSET(bp
->b_flags
, (B_DONE
| B_DELWRI
))) {
1914 /* Start I/O for the buffer (keeping credentials). */
1915 SET(bp
->b_flags
, B_READ
| async
);
1916 if (IS_VALID_CRED(cred
) && !IS_VALID_CRED(bp
->b_rcred
)) {
1917 kauth_cred_ref(cred
);
1923 trace(TR_BREADMISS
, pack(vp
, size
), blkno
);
1925 /* Pay for the read. */
1926 if (p
&& p
->p_stats
)
1927 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_inblock
); /* XXX */
1931 * since we asked for an ASYNC I/O
1932 * the biodone will do the brelse
1933 * we don't want to pass back a bp
1934 * that we don't 'own'
1943 trace(TR_BREADHIT
, pack(vp
, size
), blkno
);
1949 * Perform the reads for buf_breadn() and buf_meta_breadn().
1950 * Trivial modification to the breada algorithm presented in Bach (p.55).
1953 do_breadn_for_type(vnode_t vp
, daddr64_t blkno
, int size
, daddr64_t
*rablks
, int *rasizes
,
1954 int nrablks
, kauth_cred_t cred
, buf_t
*bpp
, int queuetype
)
1959 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, queuetype
);
1962 * For each of the read-ahead blocks, start a read, if necessary.
1964 for (i
= 0; i
< nrablks
; i
++) {
1965 /* If it's in the cache, just go on to next one. */
1966 if (incore(vp
, rablks
[i
]))
1969 /* Get a buffer for the read-ahead block */
1970 (void) bio_doread(vp
, rablks
[i
], rasizes
[i
], cred
, B_ASYNC
, queuetype
);
1973 /* Otherwise, we had to start a read for it; wait until it's valid. */
1974 return (buf_biowait(bp
));
1979 * Read a disk block.
1980 * This algorithm described in Bach (p.54).
1983 buf_bread(vnode_t vp
, daddr64_t blkno
, int size
, kauth_cred_t cred
, buf_t
*bpp
)
1987 /* Get buffer for block. */
1988 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, BLK_READ
);
1990 /* Wait for the read to complete, and return result. */
1991 return (buf_biowait(bp
));
1995 * Read a disk block. [bread() for meta-data]
1996 * This algorithm described in Bach (p.54).
1999 buf_meta_bread(vnode_t vp
, daddr64_t blkno
, int size
, kauth_cred_t cred
, buf_t
*bpp
)
2003 /* Get buffer for block. */
2004 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, BLK_META
);
2006 /* Wait for the read to complete, and return result. */
2007 return (buf_biowait(bp
));
2011 * Read-ahead multiple disk blocks. The first is sync, the rest async.
2014 buf_breadn(vnode_t vp
, daddr64_t blkno
, int size
, daddr64_t
*rablks
, int *rasizes
, int nrablks
, kauth_cred_t cred
, buf_t
*bpp
)
2016 return (do_breadn_for_type(vp
, blkno
, size
, rablks
, rasizes
, nrablks
, cred
, bpp
, BLK_READ
));
2020 * Read-ahead multiple disk blocks. The first is sync, the rest async.
2021 * [buf_breadn() for meta-data]
2024 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
)
2026 return (do_breadn_for_type(vp
, blkno
, size
, rablks
, rasizes
, nrablks
, cred
, bpp
, BLK_META
));
2030 * Block write. Described in Bach (p.56)
2033 buf_bwrite(buf_t bp
)
2035 int sync
, wasdelayed
;
2037 proc_t p
= current_proc();
2038 vnode_t vp
= bp
->b_vp
;
2040 if (bp
->b_datap
== 0) {
2041 if (brecover_data(bp
) == 0)
2044 /* Remember buffer type, to switch on it later. */
2045 sync
= !ISSET(bp
->b_flags
, B_ASYNC
);
2046 wasdelayed
= ISSET(bp
->b_flags
, B_DELWRI
);
2047 CLR(bp
->b_flags
, (B_READ
| B_DONE
| B_ERROR
| B_DELWRI
));
2050 OSAddAtomicLong(-1, &nbdwrite
);
2054 * If not synchronous, pay for the I/O operation and make
2055 * sure the buf is on the correct vnode queue. We have
2056 * to do this now, because if we don't, the vnode may not
2057 * be properly notified that its I/O has completed.
2060 buf_reassign(bp
, vp
);
2062 if (p
&& p
->p_stats
)
2063 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_oublock
); /* XXX */
2065 trace(TR_BUFWRITE
, pack(vp
, bp
->b_bcount
), bp
->b_lblkno
);
2067 /* Initiate disk write. Make sure the appropriate party is charged. */
2069 OSAddAtomic(1, &vp
->v_numoutput
);
2075 * If I/O was synchronous, wait for it to complete.
2077 rv
= buf_biowait(bp
);
2080 * Pay for the I/O operation, if it's not been paid for, and
2081 * make sure it's on the correct vnode queue. (async operatings
2082 * were payed for above.)
2085 buf_reassign(bp
, vp
);
2087 if (p
&& p
->p_stats
)
2088 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_oublock
); /* XXX */
2090 /* Release the buffer. */
2091 // XXXdbg - only if the unused bit is set
2092 if (!ISSET(bp
->b_flags
, B_NORELSE
)) {
2095 CLR(bp
->b_flags
, B_NORELSE
);
2105 vn_bwrite(struct vnop_bwrite_args
*ap
)
2107 return (buf_bwrite(ap
->a_bp
));
2113 * The buffer is marked dirty, but is not queued for I/O.
2114 * This routine should be used when the buffer is expected
2115 * to be modified again soon, typically a small write that
2116 * partially fills a buffer.
2118 * NB: magnetic tapes cannot be delayed; they must be
2119 * written in the order that the writes are requested.
2121 * Described in Leffler, et al. (pp. 208-213).
2123 * Note: With the ability to allocate additional buffer
2124 * headers, we can get in to the situation where "too" many
2125 * buf_bdwrite()s can create situation where the kernel can create
2126 * buffers faster than the disks can service. Doing a buf_bawrite() in
2127 * cases where we have "too many" outstanding buf_bdwrite()s avoids that.
2129 __private_extern__
int
2130 bdwrite_internal(buf_t bp
, int return_error
)
2132 proc_t p
= current_proc();
2133 vnode_t vp
= bp
->b_vp
;
2136 * If the block hasn't been seen before:
2137 * (1) Mark it as having been seen,
2138 * (2) Charge for the write.
2139 * (3) Make sure it's on its vnode's correct block list,
2141 if (!ISSET(bp
->b_flags
, B_DELWRI
)) {
2142 SET(bp
->b_flags
, B_DELWRI
);
2143 if (p
&& p
->p_stats
)
2144 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_oublock
); /* XXX */
2145 OSAddAtomicLong(1, &nbdwrite
);
2146 buf_reassign(bp
, vp
);
2150 * if we're not LOCKED, but the total number of delayed writes
2151 * has climbed above 75% of the total buffers in the system
2152 * return an error if the caller has indicated that it can
2153 * handle one in this case, otherwise schedule the I/O now
2154 * this is done to prevent us from allocating tons of extra
2155 * buffers when dealing with virtual disks (i.e. DiskImages),
2156 * because additional buffers are dynamically allocated to prevent
2157 * deadlocks from occurring
2159 * however, can't do a buf_bawrite() if the LOCKED bit is set because the
2160 * buffer is part of a transaction and can't go to disk until
2161 * the LOCKED bit is cleared.
2163 if (!ISSET(bp
->b_flags
, B_LOCKED
) && nbdwrite
> ((nbuf_headers
/4)*3)) {
2167 * If the vnode has "too many" write operations in progress
2168 * wait for them to finish the IO
2170 (void)vnode_waitforwrites(vp
, VNODE_ASYNC_THROTTLE
, 0, 0, "buf_bdwrite");
2172 return (buf_bawrite(bp
));
2175 /* Otherwise, the "write" is done, so mark and release the buffer. */
2176 SET(bp
->b_flags
, B_DONE
);
2182 buf_bdwrite(buf_t bp
)
2184 return (bdwrite_internal(bp
, 0));
2189 * Asynchronous block write; just an asynchronous buf_bwrite().
2191 * Note: With the abilitty to allocate additional buffer
2192 * headers, we can get in to the situation where "too" many
2193 * buf_bawrite()s can create situation where the kernel can create
2194 * buffers faster than the disks can service.
2195 * We limit the number of "in flight" writes a vnode can have to
2199 bawrite_internal(buf_t bp
, int throttle
)
2201 vnode_t vp
= bp
->b_vp
;
2206 * If the vnode has "too many" write operations in progress
2207 * wait for them to finish the IO
2209 (void)vnode_waitforwrites(vp
, VNODE_ASYNC_THROTTLE
, 0, 0, (const char *)"buf_bawrite");
2210 else if (vp
->v_numoutput
>= VNODE_ASYNC_THROTTLE
)
2212 * return to the caller and
2213 * let him decide what to do
2215 return (EWOULDBLOCK
);
2217 SET(bp
->b_flags
, B_ASYNC
);
2219 return (VNOP_BWRITE(bp
));
2223 buf_bawrite(buf_t bp
)
2225 return (bawrite_internal(bp
, 1));
2231 buf_free_meta_store(buf_t bp
)
2233 if (bp
->b_bufsize
) {
2234 if (ISSET(bp
->b_flags
, B_ZALLOC
)) {
2237 z
= getbufzone(bp
->b_bufsize
);
2238 zfree(z
, (void *)bp
->b_datap
);
2240 kmem_free(kernel_map
, bp
->b_datap
, bp
->b_bufsize
);
2242 bp
->b_datap
= (uintptr_t)NULL
;
2249 buf_brelse_shadow(buf_t bp
)
2253 buf_t bp_return
= NULL
;
2254 #ifdef BUF_MAKE_PRIVATE
2258 lck_mtx_lock_spin(buf_mtxp
);
2260 bp_head
= (buf_t
)bp
->b_orig
;
2262 if (bp_head
->b_whichq
!= -1)
2263 panic("buf_brelse_shadow: bp_head on freelist %d\n", bp_head
->b_whichq
);
2265 #ifdef BUF_MAKE_PRIVATE
2266 if (bp_data
= bp
->b_data_store
) {
2267 bp_data
->b_data_ref
--;
2269 * snapshot the ref count so that we can check it
2270 * outside of the lock... we only want the guy going
2271 * from 1 -> 0 to try and release the storage
2273 data_ref
= bp_data
->b_data_ref
;
2276 KERNEL_DEBUG(0xbbbbc008 | DBG_FUNC_START
, bp
, bp_head
, bp_head
->b_shadow_ref
, 0, 0);
2278 bp_head
->b_shadow_ref
--;
2280 for (bp_temp
= bp_head
; bp_temp
&& bp
!= bp_temp
->b_shadow
; bp_temp
= bp_temp
->b_shadow
);
2282 if (bp_temp
== NULL
)
2283 panic("buf_brelse_shadow: bp not on list %p", bp_head
);
2285 bp_temp
->b_shadow
= bp_temp
->b_shadow
->b_shadow
;
2287 #ifdef BUF_MAKE_PRIVATE
2289 * we're about to free the current 'owner' of the data buffer and
2290 * there is at least one other shadow buf_t still pointing at it
2291 * so transfer it to the first shadow buf left in the chain
2293 if (bp
== bp_data
&& data_ref
) {
2294 if ((bp_data
= bp_head
->b_shadow
) == NULL
)
2295 panic("buf_brelse_shadow: data_ref mismatch bp(%p)", bp
);
2297 for (bp_temp
= bp_data
; bp_temp
; bp_temp
= bp_temp
->b_shadow
)
2298 bp_temp
->b_data_store
= bp_data
;
2299 bp_data
->b_data_ref
= data_ref
;
2302 if (bp_head
->b_shadow_ref
== 0 && bp_head
->b_shadow
)
2303 panic("buf_relse_shadow: b_shadow != NULL && b_shadow_ref == 0 bp(%p)", bp
);
2304 if (bp_head
->b_shadow_ref
&& bp_head
->b_shadow
== 0)
2305 panic("buf_relse_shadow: b_shadow == NULL && b_shadow_ref != 0 bp(%p)", bp
);
2307 if (bp_head
->b_shadow_ref
== 0) {
2308 if (!ISSET(bp_head
->b_lflags
, BL_BUSY
)) {
2310 CLR(bp_head
->b_flags
, B_AGE
);
2311 bp_head
->b_timestamp
= buf_timestamp();
2313 if (ISSET(bp_head
->b_flags
, B_LOCKED
)) {
2314 bp_head
->b_whichq
= BQ_LOCKED
;
2315 binstailfree(bp_head
, &bufqueues
[BQ_LOCKED
], BQ_LOCKED
);
2317 bp_head
->b_whichq
= BQ_META
;
2318 binstailfree(bp_head
, &bufqueues
[BQ_META
], BQ_META
);
2320 } else if (ISSET(bp_head
->b_lflags
, BL_WAITSHADOW
)) {
2321 CLR(bp_head
->b_lflags
, BL_WAITSHADOW
);
2323 bp_return
= bp_head
;
2326 lck_mtx_unlock(buf_mtxp
);
2327 #ifdef BUF_MAKE_PRIVATE
2328 if (bp
== bp_data
&& data_ref
== 0)
2329 buf_free_meta_store(bp
);
2331 bp
->b_data_store
= NULL
;
2333 KERNEL_DEBUG(0xbbbbc008 | DBG_FUNC_END
, bp
, 0, 0, 0, 0);
2340 * Release a buffer on to the free lists.
2341 * Described in Bach (p. 46).
2344 buf_brelse(buf_t bp
)
2346 struct bqueues
*bufq
;
2349 int need_wakeup
= 0;
2350 int need_bp_wakeup
= 0;
2353 if (bp
->b_whichq
!= -1 || !(bp
->b_lflags
& BL_BUSY
))
2354 panic("buf_brelse: bad buffer = %p\n", bp
);
2357 (void) OSBacktrace(&bp
->b_stackbrelse
[0], 6);
2359 bp
->b_lastbrelse
= current_thread();
2362 if (bp
->b_lflags
& BL_IOBUF
) {
2363 buf_t shadow_master_bp
= NULL
;
2365 if (ISSET(bp
->b_lflags
, BL_SHADOW
))
2366 shadow_master_bp
= buf_brelse_shadow(bp
);
2367 else if (ISSET(bp
->b_lflags
, BL_IOBUF_ALLOC
))
2368 buf_free_meta_store(bp
);
2371 if (shadow_master_bp
) {
2372 bp
= shadow_master_bp
;
2373 goto finish_shadow_master
;
2378 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 388)) | DBG_FUNC_START
,
2379 bp
->b_lblkno
* PAGE_SIZE
, bp
, bp
->b_datap
,
2382 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
2385 * if we're invalidating a buffer that has the B_FILTER bit
2386 * set then call the b_iodone function so it gets cleaned
2389 * the HFS journal code depends on this
2391 if (ISSET(bp
->b_flags
, B_META
) && ISSET(bp
->b_flags
, B_INVAL
)) {
2392 if (ISSET(bp
->b_flags
, B_FILTER
)) { /* if necessary, call out */
2393 void (*iodone_func
)(struct buf
*, void *) = bp
->b_iodone
;
2394 void *arg
= bp
->b_transaction
;
2396 CLR(bp
->b_flags
, B_FILTER
); /* but note callout done */
2397 bp
->b_iodone
= NULL
;
2398 bp
->b_transaction
= NULL
;
2400 if (iodone_func
== NULL
) {
2401 panic("brelse: bp @ %p has NULL b_iodone!\n", bp
);
2403 (*iodone_func
)(bp
, arg
);
2407 * I/O is done. Cleanup the UPL state
2411 if ( !ISSET(bp
->b_flags
, B_META
) && UBCINFOEXISTS(bp
->b_vp
) && bp
->b_bufsize
) {
2416 if ( !ISSET(bp
->b_flags
, B_INVAL
)) {
2417 kret
= ubc_create_upl(bp
->b_vp
,
2418 ubc_blktooff(bp
->b_vp
, bp
->b_lblkno
),
2424 if (kret
!= KERN_SUCCESS
)
2425 panic("brelse: Failed to create UPL");
2427 upl_ubc_alias_set(upl
, (uintptr_t) bp
, (uintptr_t) 5);
2428 #endif /* UPL_DEBUG */
2432 kret
= ubc_upl_unmap(upl
);
2434 if (kret
!= KERN_SUCCESS
)
2435 panic("ubc_upl_unmap failed");
2436 bp
->b_datap
= (uintptr_t)NULL
;
2440 if (bp
->b_flags
& (B_ERROR
| B_INVAL
)) {
2441 if (bp
->b_flags
& (B_READ
| B_INVAL
))
2442 upl_flags
= UPL_ABORT_DUMP_PAGES
;
2446 ubc_upl_abort(upl
, upl_flags
);
2448 if (ISSET(bp
->b_flags
, B_DELWRI
| B_WASDIRTY
))
2449 upl_flags
= UPL_COMMIT_SET_DIRTY
;
2451 upl_flags
= UPL_COMMIT_CLEAR_DIRTY
;
2453 ubc_upl_commit_range(upl
, 0, bp
->b_bufsize
, upl_flags
|
2454 UPL_COMMIT_INACTIVATE
| UPL_COMMIT_FREE_ON_EMPTY
);
2460 panic("brelse: UPL set for non VREG; vp=%p", bp
->b_vp
);
2464 * If it's locked, don't report an error; try again later.
2466 if (ISSET(bp
->b_flags
, (B_LOCKED
|B_ERROR
)) == (B_LOCKED
|B_ERROR
))
2467 CLR(bp
->b_flags
, B_ERROR
);
2469 * If it's not cacheable, or an error, mark it invalid.
2471 if (ISSET(bp
->b_flags
, (B_NOCACHE
|B_ERROR
)))
2472 SET(bp
->b_flags
, B_INVAL
);
2474 if ((bp
->b_bufsize
<= 0) ||
2475 ISSET(bp
->b_flags
, B_INVAL
) ||
2476 (ISSET(bp
->b_lflags
, BL_WANTDEALLOC
) && !ISSET(bp
->b_flags
, B_DELWRI
))) {
2478 boolean_t delayed_buf_free_meta_store
= FALSE
;
2481 * If it's invalid or empty, dissociate it from its vnode,
2482 * release its storage if B_META, and
2483 * clean it up a bit and put it on the EMPTY queue
2485 if (ISSET(bp
->b_flags
, B_DELWRI
))
2486 OSAddAtomicLong(-1, &nbdwrite
);
2488 if (ISSET(bp
->b_flags
, B_META
)) {
2489 if (bp
->b_shadow_ref
)
2490 delayed_buf_free_meta_store
= TRUE
;
2492 buf_free_meta_store(bp
);
2495 * nuke any credentials we were holding
2497 buf_release_credentials(bp
);
2499 lck_mtx_lock_spin(buf_mtxp
);
2501 if (bp
->b_shadow_ref
) {
2502 SET(bp
->b_lflags
, BL_WAITSHADOW
);
2504 lck_mtx_unlock(buf_mtxp
);
2508 if (delayed_buf_free_meta_store
== TRUE
) {
2510 lck_mtx_unlock(buf_mtxp
);
2511 finish_shadow_master
:
2512 buf_free_meta_store(bp
);
2514 lck_mtx_lock_spin(buf_mtxp
);
2516 CLR(bp
->b_flags
, (B_META
| B_ZALLOC
| B_DELWRI
| B_LOCKED
| B_AGE
| B_ASYNC
| B_NOCACHE
| B_FUA
));
2523 binshash(bp
, &invalhash
);
2525 bp
->b_whichq
= BQ_EMPTY
;
2526 binsheadfree(bp
, &bufqueues
[BQ_EMPTY
], BQ_EMPTY
);
2530 * It has valid data. Put it on the end of the appropriate
2531 * queue, so that it'll stick around for as long as possible.
2533 if (ISSET(bp
->b_flags
, B_LOCKED
))
2534 whichq
= BQ_LOCKED
; /* locked in core */
2535 else if (ISSET(bp
->b_flags
, B_META
))
2536 whichq
= BQ_META
; /* meta-data */
2537 else if (ISSET(bp
->b_flags
, B_AGE
))
2538 whichq
= BQ_AGE
; /* stale but valid data */
2540 whichq
= BQ_LRU
; /* valid data */
2541 bufq
= &bufqueues
[whichq
];
2543 bp
->b_timestamp
= buf_timestamp();
2545 lck_mtx_lock_spin(buf_mtxp
);
2548 * the buf_brelse_shadow routine doesn't take 'ownership'
2549 * of the parent buf_t... it updates state that is protected by
2550 * the buf_mtxp, and checks for BL_BUSY to determine whether to
2551 * put the buf_t back on a free list. b_shadow_ref is protected
2552 * by the lock, and since we have not yet cleared B_BUSY, we need
2553 * to check it while holding the lock to insure that one of us
2554 * puts this buf_t back on a free list when it is safe to do so
2556 if (bp
->b_shadow_ref
== 0) {
2557 CLR(bp
->b_flags
, (B_AGE
| B_ASYNC
| B_NOCACHE
));
2558 bp
->b_whichq
= whichq
;
2559 binstailfree(bp
, bufq
, whichq
);
2562 * there are still cloned buf_t's pointing
2563 * at this guy... need to keep it off the
2564 * freelists until a buf_brelse is done on
2567 CLR(bp
->b_flags
, (B_ASYNC
| B_NOCACHE
));
2572 * needbuffer is a global
2573 * we're currently using buf_mtxp to protect it
2574 * delay doing the actual wakeup until after
2580 if (ISSET(bp
->b_lflags
, BL_WANTED
)) {
2582 * delay the actual wakeup until after we
2583 * clear BL_BUSY and we've dropped buf_mtxp
2588 * Unlock the buffer.
2590 CLR(bp
->b_lflags
, (BL_BUSY
| BL_WANTED
));
2593 lck_mtx_unlock(buf_mtxp
);
2597 * Wake up any processes waiting for any buffer to become free.
2599 wakeup(&needbuffer
);
2601 if (need_bp_wakeup
) {
2603 * Wake up any proceeses waiting for _this_ buffer to become free.
2607 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 388)) | DBG_FUNC_END
,
2608 bp
, bp
->b_datap
, bp
->b_flags
, 0, 0);
2612 * Determine if a block is in the cache.
2613 * Just look on what would be its hash chain. If it's there, return
2614 * a pointer to it, unless it's marked invalid. If it's marked invalid,
2615 * we normally don't return the buffer, unless the caller explicitly
2619 incore(vnode_t vp
, daddr64_t blkno
)
2622 struct bufhashhdr
*dp
;
2624 dp
= BUFHASH(vp
, blkno
);
2626 lck_mtx_lock_spin(buf_mtxp
);
2628 if (incore_locked(vp
, blkno
, dp
))
2632 lck_mtx_unlock(buf_mtxp
);
2639 incore_locked(vnode_t vp
, daddr64_t blkno
, struct bufhashhdr
*dp
)
2643 /* Search hash chain */
2644 for (bp
= dp
->lh_first
; bp
!= NULL
; bp
= bp
->b_hash
.le_next
) {
2645 if (bp
->b_lblkno
== blkno
&& bp
->b_vp
== vp
&&
2646 !ISSET(bp
->b_flags
, B_INVAL
)) {
2654 /* XXX FIXME -- Update the comment to reflect the UBC changes (please) -- */
2656 * Get a block of requested size that is associated with
2657 * a given vnode and block offset. If it is found in the
2658 * block cache, mark it as having been found, make it busy
2659 * and return it. Otherwise, return an empty block of the
2660 * correct size. It is up to the caller to insure that the
2661 * cached blocks be of the correct size.
2664 buf_getblk(vnode_t vp
, daddr64_t blkno
, int size
, int slpflag
, int slptimeo
, int operation
)
2669 upl_page_info_t
*pl
;
2674 struct bufhashhdr
*dp
;
2676 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_START
,
2677 (uintptr_t)(blkno
* PAGE_SIZE
), size
, operation
, 0, 0);
2679 ret_only_valid
= operation
& BLK_ONLYVALID
;
2680 operation
&= ~BLK_ONLYVALID
;
2681 dp
= BUFHASH(vp
, blkno
);
2683 lck_mtx_lock_spin(buf_mtxp
);
2685 if ((bp
= incore_locked(vp
, blkno
, dp
))) {
2687 * Found in the Buffer Cache
2689 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
2693 switch (operation
) {
2697 SET(bp
->b_lflags
, BL_WANTED
);
2698 bufstats
.bufs_busyincore
++;
2701 * don't retake the mutex after being awakened...
2702 * the time out is in msecs
2704 ts
.tv_sec
= (slptimeo
/1000);
2705 ts
.tv_nsec
= (slptimeo
% 1000) * 10 * NSEC_PER_USEC
* 1000;
2707 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 396)) | DBG_FUNC_NONE
,
2708 (uintptr_t)blkno
, size
, operation
, 0, 0);
2710 err
= msleep(bp
, buf_mtxp
, slpflag
| PDROP
| (PRIBIO
+ 1), "buf_getblk", &ts
);
2713 * Callers who call with PCATCH or timeout are
2714 * willing to deal with the NULL pointer
2716 if (err
&& ((slpflag
& PCATCH
) || ((err
== EWOULDBLOCK
) && slptimeo
)))
2724 * unknown operation requested
2726 panic("getblk: paging or unknown operation for incore busy buffer - %x\n", operation
);
2732 * buffer in core and not busy
2734 SET(bp
->b_lflags
, BL_BUSY
);
2735 SET(bp
->b_flags
, B_CACHE
);
2738 bremfree_locked(bp
);
2739 bufstats
.bufs_incore
++;
2741 lck_mtx_unlock(buf_mtxp
);
2743 bp
->b_owner
= current_thread();
2747 panic("buffer has UPL, but not marked BUSY: %p", bp
);
2749 if ( !ret_only_valid
&& bp
->b_bufsize
!= size
)
2753 switch (operation
) {
2756 * "write" operation: let the UPL subsystem
2757 * know that we intend to modify the buffer
2758 * cache pages we're gathering.
2760 upl_flags
|= UPL_WILL_MODIFY
;
2762 upl_flags
|= UPL_PRECIOUS
;
2763 if (UBCINFOEXISTS(bp
->b_vp
) && bp
->b_bufsize
) {
2764 kret
= ubc_create_upl(vp
,
2765 ubc_blktooff(vp
, bp
->b_lblkno
),
2770 if (kret
!= KERN_SUCCESS
)
2771 panic("Failed to create UPL");
2775 if (upl_valid_page(pl
, 0)) {
2776 if (upl_dirty_page(pl
, 0))
2777 SET(bp
->b_flags
, B_WASDIRTY
);
2779 CLR(bp
->b_flags
, B_WASDIRTY
);
2781 CLR(bp
->b_flags
, (B_DONE
| B_CACHE
| B_WASDIRTY
| B_DELWRI
));
2783 kret
= ubc_upl_map(upl
, (vm_offset_t
*)&(bp
->b_datap
));
2785 if (kret
!= KERN_SUCCESS
)
2786 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
2792 * VM is not involved in IO for the meta data
2793 * buffer already has valid data
2798 panic("getblk: paging or unknown operation for incore buffer- %d\n", operation
);
2803 } else { /* not incore() */
2804 int queue
= BQ_EMPTY
; /* Start with no preference */
2806 if (ret_only_valid
) {
2807 lck_mtx_unlock(buf_mtxp
);
2810 if ((vnode_isreg(vp
) == 0) || (UBCINFOEXISTS(vp
) == 0) /*|| (vnode_issystem(vp) == 1)*/)
2811 operation
= BLK_META
;
2813 if ((bp
= getnewbuf(slpflag
, slptimeo
, &queue
)) == NULL
)
2817 * getnewbuf may block for a number of different reasons...
2818 * if it does, it's then possible for someone else to
2819 * create a buffer for the same block and insert it into
2820 * the hash... if we see it incore at this point we dump
2821 * the buffer we were working on and start over
2823 if (incore_locked(vp
, blkno
, dp
)) {
2824 SET(bp
->b_flags
, B_INVAL
);
2825 binshash(bp
, &invalhash
);
2827 lck_mtx_unlock(buf_mtxp
);
2833 * NOTE: YOU CAN NOT BLOCK UNTIL binshash() HAS BEEN
2834 * CALLED! BE CAREFUL.
2838 * mark the buffer as B_META if indicated
2839 * so that when buffer is released it will goto META queue
2841 if (operation
== BLK_META
)
2842 SET(bp
->b_flags
, B_META
);
2844 bp
->b_blkno
= bp
->b_lblkno
= blkno
;
2848 * Insert in the hash so that incore() can find it
2850 binshash(bp
, BUFHASH(vp
, blkno
));
2852 bgetvp_locked(vp
, bp
);
2854 lck_mtx_unlock(buf_mtxp
);
2859 switch (operation
) {
2862 * buffer data is invalid...
2864 * I don't want to have to retake buf_mtxp,
2865 * so the miss and vmhits counters are done
2866 * with Atomic updates... all other counters
2867 * in bufstats are protected with either
2868 * buf_mtxp or iobuffer_mtxp
2870 OSAddAtomicLong(1, &bufstats
.bufs_miss
);
2875 * "write" operation: let the UPL subsystem know
2876 * that we intend to modify the buffer cache pages
2879 upl_flags
|= UPL_WILL_MODIFY
;
2882 size_t contig_bytes
;
2886 panic("bp already has UPL: %p",bp
);
2888 f_offset
= ubc_blktooff(vp
, blkno
);
2890 upl_flags
|= UPL_PRECIOUS
;
2891 kret
= ubc_create_upl(vp
,
2898 if (kret
!= KERN_SUCCESS
)
2899 panic("Failed to create UPL");
2901 upl_ubc_alias_set(upl
, (uintptr_t) bp
, (uintptr_t) 4);
2902 #endif /* UPL_DEBUG */
2905 if (upl_valid_page(pl
, 0)) {
2907 if (operation
== BLK_READ
)
2908 bmap_flags
= VNODE_READ
;
2910 bmap_flags
= VNODE_WRITE
;
2912 SET(bp
->b_flags
, B_CACHE
| B_DONE
);
2914 OSAddAtomicLong(1, &bufstats
.bufs_vmhits
);
2919 if (upl_dirty_page(pl
, 0)) {
2921 SET(bp
->b_flags
, B_WASDIRTY
);
2923 bp
->b_validend
= bp
->b_bcount
;
2924 bp
->b_dirtyend
= bp
->b_bcount
;
2927 bp
->b_validend
= bp
->b_bcount
;
2931 * try to recreate the physical block number associated with
2934 if (VNOP_BLOCKMAP(vp
, f_offset
, bp
->b_bcount
, &bp
->b_blkno
, &contig_bytes
, NULL
, bmap_flags
, NULL
))
2935 panic("getblk: VNOP_BLOCKMAP failed");
2937 * if the extent represented by this buffer
2938 * is not completely physically contiguous on
2939 * disk, than we can't cache the physical mapping
2940 * in the buffer header
2942 if ((long)contig_bytes
< bp
->b_bcount
)
2943 bp
->b_blkno
= bp
->b_lblkno
;
2945 OSAddAtomicLong(1, &bufstats
.bufs_miss
);
2947 kret
= ubc_upl_map(upl
, (vm_offset_t
*)&(bp
->b_datap
));
2949 if (kret
!= KERN_SUCCESS
)
2950 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
2954 panic("getblk: paging or unknown operation - %x", operation
);
2959 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_END
,
2960 bp
, bp
->b_datap
, bp
->b_flags
, 3, 0);
2963 (void) OSBacktrace(&bp
->b_stackgetblk
[0], 6);
2969 * Get an empty, disassociated buffer of given size.
2972 buf_geteblk(int size
)
2975 int queue
= BQ_EMPTY
;
2978 lck_mtx_lock_spin(buf_mtxp
);
2980 bp
= getnewbuf(0, 0, &queue
);
2981 } while (bp
== NULL
);
2983 SET(bp
->b_flags
, (B_META
|B_INVAL
));
2986 assert(queue
== BQ_EMPTY
);
2987 #endif /* DIAGNOSTIC */
2988 /* XXX need to implement logic to deal with other queues */
2990 binshash(bp
, &invalhash
);
2991 bufstats
.bufs_eblk
++;
2993 lck_mtx_unlock(buf_mtxp
);
3001 buf_redundancy_flags(buf_t bp
)
3003 return bp
->b_redundancy_flags
;
3007 buf_set_redundancy_flags(buf_t bp
, uint32_t flags
)
3009 SET(bp
->b_redundancy_flags
, flags
);
3013 buf_clear_redundancy_flags(buf_t bp
, uint32_t flags
)
3015 CLR(bp
->b_redundancy_flags
, flags
);
3019 * With UBC, there is no need to expand / shrink the file data
3020 * buffer. The VM uses the same pages, hence no waste.
3021 * All the file data buffers can have one size.
3022 * In fact expand / shrink would be an expensive operation.
3024 * Only exception to this is meta-data buffers. Most of the
3025 * meta data operations are smaller than PAGE_SIZE. Having the
3026 * meta-data buffers grow and shrink as needed, optimizes use
3027 * of the kernel wired memory.
3031 allocbuf(buf_t bp
, int size
)
3033 vm_size_t desired_size
;
3035 desired_size
= roundup(size
, CLBYTES
);
3037 if (desired_size
< PAGE_SIZE
)
3038 desired_size
= PAGE_SIZE
;
3039 if (desired_size
> MAXBSIZE
)
3040 panic("allocbuf: buffer larger than MAXBSIZE requested");
3042 if (ISSET(bp
->b_flags
, B_META
)) {
3044 int nsize
= roundup(size
, MINMETA
);
3047 vm_offset_t elem
= (vm_offset_t
)bp
->b_datap
;
3049 if (ISSET(bp
->b_flags
, B_ZALLOC
)) {
3050 if (bp
->b_bufsize
< nsize
) {
3051 /* reallocate to a bigger size */
3053 zprev
= getbufzone(bp
->b_bufsize
);
3054 if (nsize
<= MAXMETA
) {
3055 desired_size
= nsize
;
3056 z
= getbufzone(nsize
);
3057 /* b_datap not really a ptr */
3058 *(void **)(&bp
->b_datap
) = zalloc(z
);
3060 bp
->b_datap
= (uintptr_t)NULL
;
3061 kmem_alloc_kobject(kernel_map
, (vm_offset_t
*)&bp
->b_datap
, desired_size
);
3062 CLR(bp
->b_flags
, B_ZALLOC
);
3064 bcopy((void *)elem
, (caddr_t
)bp
->b_datap
, bp
->b_bufsize
);
3065 zfree(zprev
, (void *)elem
);
3067 desired_size
= bp
->b_bufsize
;
3071 if ((vm_size_t
)bp
->b_bufsize
< desired_size
) {
3072 /* reallocate to a bigger size */
3073 bp
->b_datap
= (uintptr_t)NULL
;
3074 kmem_alloc_kobject(kernel_map
, (vm_offset_t
*)&bp
->b_datap
, desired_size
);
3075 bcopy((const void *)elem
, (caddr_t
)bp
->b_datap
, bp
->b_bufsize
);
3076 kmem_free(kernel_map
, elem
, bp
->b_bufsize
);
3078 desired_size
= bp
->b_bufsize
;
3082 /* new allocation */
3083 if (nsize
<= MAXMETA
) {
3084 desired_size
= nsize
;
3085 z
= getbufzone(nsize
);
3086 /* b_datap not really a ptr */
3087 *(void **)(&bp
->b_datap
) = zalloc(z
);
3088 SET(bp
->b_flags
, B_ZALLOC
);
3090 kmem_alloc_kobject(kernel_map
, (vm_offset_t
*)&bp
->b_datap
, desired_size
);
3093 if (bp
->b_datap
== 0)
3094 panic("allocbuf: NULL b_datap");
3096 bp
->b_bufsize
= desired_size
;
3097 bp
->b_bcount
= size
;
3103 * Get a new buffer from one of the free lists.
3105 * Request for a queue is passes in. The queue from which the buffer was taken
3106 * from is returned. Out of range queue requests get BQ_EMPTY. Request for
3107 * BQUEUE means no preference. Use heuristics in that case.
3108 * Heuristics is as follows:
3109 * Try BQ_AGE, BQ_LRU, BQ_EMPTY, BQ_META in that order.
3110 * If none available block till one is made available.
3111 * If buffers available on both BQ_AGE and BQ_LRU, check the timestamps.
3112 * Pick the most stale buffer.
3113 * If found buffer was marked delayed write, start the async. write
3114 * and restart the search.
3115 * Initialize the fields and disassociate the buffer from the vnode.
3116 * Remove the buffer from the hash. Return the buffer and the queue
3117 * on which it was found.
3119 * buf_mtxp is held upon entry
3120 * returns with buf_mtxp locked if new buf available
3121 * returns with buf_mtxp UNlocked if new buf NOT available
3125 getnewbuf(int slpflag
, int slptimeo
, int * queue
)
3131 int age_time
, lru_time
, bp_time
, meta_time
;
3132 int req
= *queue
; /* save it for restarts */
3137 * invalid request gets empty queue
3139 if ((*queue
>= BQUEUES
) || (*queue
< 0)
3140 || (*queue
== BQ_LAUNDRY
) || (*queue
== BQ_LOCKED
))
3144 if (*queue
== BQ_EMPTY
&& (bp
= bufqueues
[*queue
].tqh_first
))
3148 * need to grow number of bufs, add another one rather than recycling
3150 if (nbuf_headers
< max_nbuf_headers
) {
3152 * Increment count now as lock
3153 * is dropped for allocation.
3154 * That avoids over commits
3159 /* Try for the requested queue first */
3160 bp
= bufqueues
[*queue
].tqh_first
;
3164 /* Unable to use requested queue */
3165 age_bp
= bufqueues
[BQ_AGE
].tqh_first
;
3166 lru_bp
= bufqueues
[BQ_LRU
].tqh_first
;
3167 meta_bp
= bufqueues
[BQ_META
].tqh_first
;
3169 if (!age_bp
&& !lru_bp
&& !meta_bp
) {
3171 * Unavailble on AGE or LRU or META queues
3172 * Try the empty list first
3174 bp
= bufqueues
[BQ_EMPTY
].tqh_first
;
3180 * We have seen is this is hard to trigger.
3181 * This is an overcommit of nbufs but needed
3182 * in some scenarios with diskiamges
3186 lck_mtx_unlock(buf_mtxp
);
3188 /* Create a new temporary buffer header */
3189 bp
= (struct buf
*)zalloc(buf_hdr_zone
);
3193 bp
->b_whichq
= BQ_EMPTY
;
3194 bp
->b_timestamp
= buf_timestamp();
3196 SET(bp
->b_flags
, B_HDRALLOC
);
3199 lck_mtx_lock_spin(buf_mtxp
);
3202 binshash(bp
, &invalhash
);
3203 binsheadfree(bp
, &bufqueues
[BQ_EMPTY
], BQ_EMPTY
);
3207 /* subtract already accounted bufcount */
3210 bufstats
.bufs_sleeps
++;
3212 /* wait for a free buffer of any kind */
3214 /* hz value is 100 */
3215 ts
.tv_sec
= (slptimeo
/1000);
3216 /* the hz value is 100; which leads to 10ms */
3217 ts
.tv_nsec
= (slptimeo
% 1000) * NSEC_PER_USEC
* 1000 * 10;
3219 msleep(&needbuffer
, buf_mtxp
, slpflag
| PDROP
| (PRIBIO
+1), "getnewbuf", &ts
);
3223 /* Buffer available either on AGE or LRU or META */
3227 /* Buffer available either on AGE or LRU */
3231 } else if (!lru_bp
) {
3234 } else { /* buffer available on both AGE and LRU */
3235 int t
= buf_timestamp();
3237 age_time
= t
- age_bp
->b_timestamp
;
3238 lru_time
= t
- lru_bp
->b_timestamp
;
3239 if ((age_time
< 0) || (lru_time
< 0)) { /* time set backwards */
3243 * we should probably re-timestamp eveything in the
3244 * queues at this point with the current time
3247 if ((lru_time
>= lru_is_stale
) && (age_time
< age_is_stale
)) {
3257 if (!bp
) { /* Neither on AGE nor on LRU */
3260 } else if (meta_bp
) {
3261 int t
= buf_timestamp();
3263 bp_time
= t
- bp
->b_timestamp
;
3264 meta_time
= t
- meta_bp
->b_timestamp
;
3266 if (!(bp_time
< 0) && !(meta_time
< 0)) {
3267 /* time not set backwards */
3269 bp_is_stale
= (*queue
== BQ_LRU
) ?
3270 lru_is_stale
: age_is_stale
;
3272 if ((meta_time
>= meta_is_stale
) &&
3273 (bp_time
< bp_is_stale
)) {
3280 if (ISSET(bp
->b_flags
, B_LOCKED
) || ISSET(bp
->b_lflags
, BL_BUSY
))
3281 panic("getnewbuf: bp @ %p is LOCKED or BUSY! (flags 0x%x)\n", bp
, bp
->b_flags
);
3284 if (bcleanbuf(bp
, FALSE
)) {
3286 * moved to the laundry thread, buffer not ready
3297 * Returns 0 if buffer is ready to use,
3298 * Returns 1 if issued a buf_bawrite() to indicate
3299 * that the buffer is not ready.
3301 * buf_mtxp is held upon entry
3302 * returns with buf_mtxp locked
3305 bcleanbuf(buf_t bp
, boolean_t discard
)
3307 /* Remove from the queue */
3308 bremfree_locked(bp
);
3311 bp
->b_owner
= current_thread();
3315 * If buffer was a delayed write, start the IO by queuing
3316 * it on the LAUNDRY queue, and return 1
3318 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
3320 SET(bp
->b_lflags
, BL_WANTDEALLOC
);
3325 lck_mtx_unlock(buf_mtxp
);
3327 wakeup(&bufqueues
[BQ_LAUNDRY
]);
3329 * and give it a chance to run
3331 (void)thread_block(THREAD_CONTINUE_NULL
);
3333 lck_mtx_lock_spin(buf_mtxp
);
3338 bp
->b_owner
= current_thread();
3342 * Buffer is no longer on any free list... we own it
3344 SET(bp
->b_lflags
, BL_BUSY
);
3350 * disassociate us from our vnode, if we had one...
3355 lck_mtx_unlock(buf_mtxp
);
3359 if (ISSET(bp
->b_flags
, B_META
))
3360 buf_free_meta_store(bp
);
3362 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
3364 buf_release_credentials(bp
);
3366 /* If discarding, just move to the empty queue */
3368 lck_mtx_lock_spin(buf_mtxp
);
3369 CLR(bp
->b_flags
, (B_META
| B_ZALLOC
| B_DELWRI
| B_LOCKED
| B_AGE
| B_ASYNC
| B_NOCACHE
| B_FUA
));
3370 bp
->b_whichq
= BQ_EMPTY
;
3371 binshash(bp
, &invalhash
);
3372 binsheadfree(bp
, &bufqueues
[BQ_EMPTY
], BQ_EMPTY
);
3373 CLR(bp
->b_lflags
, BL_BUSY
);
3376 /* Not discarding: clean up and prepare for reuse */
3378 bp
->b_datap
= (uintptr_t)NULL
;
3379 bp
->b_upl
= (void *)NULL
;
3381 * preserve the state of whether this buffer
3382 * was allocated on the fly or not...
3383 * the only other flag that should be set at
3384 * this point is BL_BUSY...
3387 bp
->b_owner
= current_thread();
3390 bp
->b_lflags
= BL_BUSY
;
3391 bp
->b_flags
= (bp
->b_flags
& B_HDRALLOC
);
3393 bp
->b_blkno
= bp
->b_lblkno
= 0;
3394 bp
->b_iodone
= NULL
;
3398 bp
->b_dirtyoff
= bp
->b_dirtyend
= 0;
3399 bp
->b_validoff
= bp
->b_validend
= 0;
3400 #ifdef CONFIG_PROTECT
3404 lck_mtx_lock_spin(buf_mtxp
);
3412 buf_invalblkno(vnode_t vp
, daddr64_t lblkno
, int flags
)
3416 struct bufhashhdr
*dp
;
3418 dp
= BUFHASH(vp
, lblkno
);
3421 lck_mtx_lock_spin(buf_mtxp
);
3423 if ((bp
= incore_locked(vp
, lblkno
, dp
)) == (struct buf
*)0) {
3424 lck_mtx_unlock(buf_mtxp
);
3427 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
3428 if ( !ISSET(flags
, BUF_WAIT
)) {
3429 lck_mtx_unlock(buf_mtxp
);
3432 SET(bp
->b_lflags
, BL_WANTED
);
3434 error
= msleep((caddr_t
)bp
, buf_mtxp
, PDROP
| (PRIBIO
+ 1), "buf_invalblkno", NULL
);
3441 bremfree_locked(bp
);
3442 SET(bp
->b_lflags
, BL_BUSY
);
3443 SET(bp
->b_flags
, B_INVAL
);
3446 bp
->b_owner
= current_thread();
3449 lck_mtx_unlock(buf_mtxp
);
3459 int need_wakeup
= 0;
3461 lck_mtx_lock_spin(buf_mtxp
);
3463 if (ISSET(bp
->b_lflags
, BL_WANTED
)) {
3465 * delay the actual wakeup until after we
3466 * clear BL_BUSY and we've dropped buf_mtxp
3471 bp
->b_owner
= current_thread();
3475 * Unlock the buffer.
3477 CLR(bp
->b_lflags
, (BL_BUSY
| BL_WANTED
));
3480 lck_mtx_unlock(buf_mtxp
);
3484 * Wake up any proceeses waiting for _this_ buffer to become free.
3492 buf_acquire(buf_t bp
, int flags
, int slpflag
, int slptimeo
) {
3495 lck_mtx_lock_spin(buf_mtxp
);
3497 error
= buf_acquire_locked(bp
, flags
, slpflag
, slptimeo
);
3499 lck_mtx_unlock(buf_mtxp
);
3506 buf_acquire_locked(buf_t bp
, int flags
, int slpflag
, int slptimeo
)
3511 if (ISSET(bp
->b_flags
, B_LOCKED
)) {
3512 if ((flags
& BAC_SKIP_LOCKED
))
3515 if ((flags
& BAC_SKIP_NONLOCKED
))
3518 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
3520 * since the lck_mtx_lock may block, the buffer
3521 * may become BUSY, so we need to
3522 * recheck for a NOWAIT request
3524 if (flags
& BAC_NOWAIT
)
3526 SET(bp
->b_lflags
, BL_WANTED
);
3528 /* the hz value is 100; which leads to 10ms */
3529 ts
.tv_sec
= (slptimeo
/100);
3530 ts
.tv_nsec
= (slptimeo
% 100) * 10 * NSEC_PER_USEC
* 1000;
3531 error
= msleep((caddr_t
)bp
, buf_mtxp
, slpflag
| (PRIBIO
+ 1), "buf_acquire", &ts
);
3537 if (flags
& BAC_REMOVE
)
3538 bremfree_locked(bp
);
3539 SET(bp
->b_lflags
, BL_BUSY
);
3543 bp
->b_owner
= current_thread();
3551 * Wait for operations on the buffer to complete.
3552 * When they do, extract and return the I/O's error value.
3555 buf_biowait(buf_t bp
)
3557 while (!ISSET(bp
->b_flags
, B_DONE
)) {
3559 lck_mtx_lock_spin(buf_mtxp
);
3561 if (!ISSET(bp
->b_flags
, B_DONE
)) {
3562 DTRACE_IO1(wait__start
, buf_t
, bp
);
3563 (void) msleep(bp
, buf_mtxp
, PDROP
| (PRIBIO
+1), "buf_biowait", NULL
);
3564 DTRACE_IO1(wait__done
, buf_t
, bp
);
3566 lck_mtx_unlock(buf_mtxp
);
3568 /* check for interruption of I/O (e.g. via NFS), then errors. */
3569 if (ISSET(bp
->b_flags
, B_EINTR
)) {
3570 CLR(bp
->b_flags
, B_EINTR
);
3572 } else if (ISSET(bp
->b_flags
, B_ERROR
))
3573 return (bp
->b_error
? bp
->b_error
: EIO
);
3580 * Mark I/O complete on a buffer.
3582 * If a callback has been requested, e.g. the pageout
3583 * daemon, do so. Otherwise, awaken waiting processes.
3585 * [ Leffler, et al., says on p.247:
3586 * "This routine wakes up the blocked process, frees the buffer
3587 * for an asynchronous write, or, for a request by the pagedaemon
3588 * process, invokes a procedure specified in the buffer structure" ]
3590 * In real life, the pagedaemon (or other system processes) wants
3591 * to do async stuff to, and doesn't want the buffer buf_brelse()'d.
3592 * (for swap pager, that puts swap buffers on the free lists (!!!),
3593 * for the vn device, that puts malloc'd buffers on the free lists!)
3595 extern struct timeval priority_IO_timestamp_for_root
;
3596 extern int hard_throttle_on_root
;
3599 buf_biodone(buf_t bp
)
3603 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 387)) | DBG_FUNC_START
,
3604 bp
, bp
->b_datap
, bp
->b_flags
, 0, 0);
3606 if (ISSET(bp
->b_flags
, B_DONE
))
3607 panic("biodone already");
3609 if (ISSET(bp
->b_flags
, B_ERROR
)) {
3613 if (bp
->b_vp
&& bp
->b_vp
->v_mount
) {
3614 mp
= bp
->b_vp
->v_mount
;
3619 if (mp
&& (bp
->b_flags
& B_READ
) == 0) {
3620 update_last_io_time(mp
);
3621 INCR_PENDING_IO(-(pending_io_t
)buf_count(bp
), mp
->mnt_pending_write_size
);
3623 INCR_PENDING_IO(-(pending_io_t
)buf_count(bp
), mp
->mnt_pending_read_size
);
3626 if (kdebug_enable
) {
3627 int code
= DKIO_DONE
;
3629 if (bp
->b_flags
& B_READ
)
3631 if (bp
->b_flags
& B_ASYNC
)
3634 if (bp
->b_flags
& B_META
)
3636 else if (bp
->b_flags
& B_PAGEIO
)
3637 code
|= DKIO_PAGING
;
3639 if (bp
->b_flags
& B_THROTTLED_IO
)
3640 code
|= DKIO_THROTTLE
;
3641 else if (bp
->b_flags
& B_PASSIVE
)
3642 code
|= DKIO_PASSIVE
;
3644 KERNEL_DEBUG_CONSTANT(FSDBG_CODE(DBG_DKRW
, code
) | DBG_FUNC_NONE
,
3645 bp
, (uintptr_t)bp
->b_vp
,
3646 bp
->b_resid
, bp
->b_error
, 0);
3648 if ((bp
->b_vp
!= NULLVP
) &&
3649 ((bp
->b_flags
& (B_IOSTREAMING
| B_PAGEIO
| B_READ
)) == (B_PAGEIO
| B_READ
)) &&
3650 (bp
->b_vp
->v_mount
->mnt_kern_flag
& MNTK_ROOTDEV
)) {
3651 microuptime(&priority_IO_timestamp_for_root
);
3652 hard_throttle_on_root
= 0;
3656 * I/O was done, so don't believe
3657 * the DIRTY state from VM anymore...
3658 * and we need to reset the THROTTLED/PASSIVE
3661 CLR(bp
->b_flags
, (B_WASDIRTY
| B_THROTTLED_IO
| B_PASSIVE
));
3662 DTRACE_IO1(done
, buf_t
, bp
);
3664 if (!ISSET(bp
->b_flags
, B_READ
) && !ISSET(bp
->b_flags
, B_RAW
))
3666 * wake up any writer's blocked
3667 * on throttle or waiting for I/O
3670 vnode_writedone(bp
->b_vp
);
3672 if (ISSET(bp
->b_flags
, (B_CALL
| B_FILTER
))) { /* if necessary, call out */
3673 void (*iodone_func
)(struct buf
*, void *) = bp
->b_iodone
;
3674 void *arg
= bp
->b_transaction
;
3675 int callout
= ISSET(bp
->b_flags
, B_CALL
);
3677 if (iodone_func
== NULL
)
3678 panic("biodone: bp @ %p has NULL b_iodone!\n", bp
);
3680 CLR(bp
->b_flags
, (B_CALL
| B_FILTER
)); /* filters and callouts are one-shot */
3681 bp
->b_iodone
= NULL
;
3682 bp
->b_transaction
= NULL
;
3685 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
3687 (*iodone_func
)(bp
, arg
);
3691 * assumes that the callback function takes
3692 * ownership of the bp and deals with releasing it if necessary
3697 * in this case the call back function is acting
3698 * strictly as a filter... it does not take
3699 * ownership of the bp and is expecting us
3700 * to finish cleaning up... this is currently used
3701 * by the HFS journaling code
3704 if (ISSET(bp
->b_flags
, B_ASYNC
)) { /* if async, release it */
3705 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
3708 } else { /* or just wakeup the buffer */
3710 * by taking the mutex, we serialize
3711 * the buf owner calling buf_biowait so that we'll
3712 * only see him in one of 2 states...
3713 * state 1: B_DONE wasn't set and he's
3715 * state 2: he's blocked trying to take the
3716 * mutex before looking at B_DONE
3717 * BL_WANTED is cleared in case anyone else
3718 * is blocked waiting for the buffer... note
3719 * that we haven't cleared B_BUSY yet, so if
3720 * they do get to run, their going to re-set
3721 * BL_WANTED and go back to sleep
3723 lck_mtx_lock_spin(buf_mtxp
);
3725 CLR(bp
->b_lflags
, BL_WANTED
);
3726 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
3728 lck_mtx_unlock(buf_mtxp
);
3733 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 387)) | DBG_FUNC_END
,
3734 (uintptr_t)bp
, (uintptr_t)bp
->b_datap
, bp
->b_flags
, 0, 0);
3738 * Return a count of buffers on the "locked" queue.
3741 count_lock_queue(void)
3746 lck_mtx_lock_spin(buf_mtxp
);
3748 for (bp
= bufqueues
[BQ_LOCKED
].tqh_first
; bp
;
3749 bp
= bp
->b_freelist
.tqe_next
)
3751 lck_mtx_unlock(buf_mtxp
);
3757 * Return a count of 'busy' buffers. Used at the time of shutdown.
3760 count_busy_buffers(void)
3762 return buf_busycount
+ bufstats
.bufs_iobufinuse
;
3767 * Print out statistics on the current allocation of the buffer pool.
3768 * Can be enabled to print out on every ``sync'' by setting "syncprt"
3769 * in vfs_syscalls.c using sysctl.
3777 int counts
[MAXBSIZE
/CLBYTES
+1];
3778 static char *bname
[BQUEUES
] =
3779 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
3781 for (dp
= bufqueues
, i
= 0; dp
< &bufqueues
[BQUEUES
]; dp
++, i
++) {
3783 for (j
= 0; j
<= MAXBSIZE
/CLBYTES
; j
++)
3786 lck_mtx_lock(buf_mtxp
);
3788 for (bp
= dp
->tqh_first
; bp
; bp
= bp
->b_freelist
.tqe_next
) {
3789 counts
[bp
->b_bufsize
/CLBYTES
]++;
3792 lck_mtx_unlock(buf_mtxp
);
3794 printf("%s: total-%d", bname
[i
], count
);
3795 for (j
= 0; j
<= MAXBSIZE
/CLBYTES
; j
++)
3797 printf(", %d-%d", j
* CLBYTES
, counts
[j
]);
3801 #endif /* DIAGNOSTIC */
3803 #define NRESERVEDIOBUFS 128
3807 alloc_io_buf(vnode_t vp
, int priv
)
3811 lck_mtx_lock_spin(iobuffer_mtxp
);
3813 while (((niobuf_headers
- NRESERVEDIOBUFS
< bufstats
.bufs_iobufinuse
) && !priv
) ||
3814 (bp
= iobufqueue
.tqh_first
) == NULL
) {
3815 bufstats
.bufs_iobufsleeps
++;
3818 (void) msleep(&need_iobuffer
, iobuffer_mtxp
, PSPIN
| (PRIBIO
+1), (const char *)"alloc_io_buf", NULL
);
3820 TAILQ_REMOVE(&iobufqueue
, bp
, b_freelist
);
3822 bufstats
.bufs_iobufinuse
++;
3823 if (bufstats
.bufs_iobufinuse
> bufstats
.bufs_iobufmax
)
3824 bufstats
.bufs_iobufmax
= bufstats
.bufs_iobufinuse
;
3826 lck_mtx_unlock(iobuffer_mtxp
);
3829 * initialize various fields
3830 * we don't need to hold the mutex since the buffer
3831 * is now private... the vp should have a reference
3832 * on it and is not protected by this mutex in any event
3834 bp
->b_timestamp
= 0;
3839 bp
->b_lflags
= BL_BUSY
| BL_IOBUF
;
3840 bp
->b_redundancy_flags
= 0;
3841 bp
->b_blkno
= bp
->b_lblkno
= 0;
3843 bp
->b_owner
= current_thread();
3846 bp
->b_iodone
= NULL
;
3853 #ifdef CONFIG_PROTECT
3857 if (vp
&& (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
))
3858 bp
->b_dev
= vp
->v_rdev
;
3867 free_io_buf(buf_t bp
)
3869 int need_wakeup
= 0;
3872 * put buffer back on the head of the iobufqueue
3875 bp
->b_flags
= B_INVAL
;
3877 lck_mtx_lock_spin(iobuffer_mtxp
);
3879 binsheadfree(bp
, &iobufqueue
, -1);
3881 if (need_iobuffer
) {
3883 * Wake up any processes waiting because they need an io buffer
3885 * do the wakeup after we drop the mutex... it's possible that the
3886 * wakeup will be superfluous if need_iobuffer gets set again and
3887 * another thread runs this path, but it's highly unlikely, doesn't
3888 * hurt, and it means we don't hold up I/O progress if the wakeup blocks
3889 * trying to grab a task related lock...
3894 if (bufstats
.bufs_iobufinuse
<= 0)
3895 panic("free_io_buf: bp(%p) - bufstats.bufs_iobufinuse < 0", bp
);
3897 bufstats
.bufs_iobufinuse
--;
3899 lck_mtx_unlock(iobuffer_mtxp
);
3902 wakeup(&need_iobuffer
);
3909 lck_mtx_lock_spin(buf_mtxp
);
3913 buf_list_unlock(void)
3915 lck_mtx_unlock(buf_mtxp
);
3919 * If getnewbuf() calls bcleanbuf() on the same thread
3920 * there is a potential for stack overrun and deadlocks.
3921 * So we always handoff the work to a worker thread for completion
3926 bcleanbuf_thread_init(void)
3928 thread_t thread
= THREAD_NULL
;
3930 /* create worker thread */
3931 kernel_thread_start((thread_continue_t
)bcleanbuf_thread
, NULL
, &thread
);
3932 thread_deallocate(thread
);
3935 typedef int (*bcleanbufcontinuation
)(int);
3938 bcleanbuf_thread(void)
3945 lck_mtx_lock_spin(buf_mtxp
);
3947 while ( (bp
= TAILQ_FIRST(&bufqueues
[BQ_LAUNDRY
])) == NULL
) {
3948 (void)msleep0(&bufqueues
[BQ_LAUNDRY
], buf_mtxp
, PRIBIO
|PDROP
, "blaundry", 0, (bcleanbufcontinuation
)bcleanbuf_thread
);
3952 * Remove from the queue
3954 bremfree_locked(bp
);
3957 * Buffer is no longer on any free list
3959 SET(bp
->b_lflags
, BL_BUSY
);
3963 bp
->b_owner
= current_thread();
3967 lck_mtx_unlock(buf_mtxp
);
3971 error
= bawrite_internal(bp
, 0);
3974 bp
->b_whichq
= BQ_LAUNDRY
;
3975 bp
->b_timestamp
= buf_timestamp();
3977 lck_mtx_lock_spin(buf_mtxp
);
3979 binstailfree(bp
, &bufqueues
[BQ_LAUNDRY
], BQ_LAUNDRY
);
3982 /* we never leave a busy page on the laundry queue */
3983 CLR(bp
->b_lflags
, BL_BUSY
);
3986 bp
->b_owner
= current_thread();
3990 lck_mtx_unlock(buf_mtxp
);
3992 if (loopcnt
> MAXLAUNDRY
) {
3994 * bawrite_internal() can return errors if we're throttled. If we've
3995 * done several I/Os and failed, give the system some time to unthrottle
3998 (void)tsleep((void *)&bufqueues
[BQ_LAUNDRY
], PRIBIO
, "blaundry", 1);
4001 /* give other threads a chance to run */
4002 (void)thread_block(THREAD_CONTINUE_NULL
);
4011 brecover_data(buf_t bp
)
4015 upl_page_info_t
*pl
;
4017 vnode_t vp
= bp
->b_vp
;
4021 if ( !UBCINFOEXISTS(vp
) || bp
->b_bufsize
== 0)
4024 upl_flags
= UPL_PRECIOUS
;
4025 if (! (buf_flags(bp
) & B_READ
)) {
4027 * "write" operation: let the UPL subsystem know
4028 * that we intend to modify the buffer cache pages we're
4031 upl_flags
|= UPL_WILL_MODIFY
;
4034 kret
= ubc_create_upl(vp
,
4035 ubc_blktooff(vp
, bp
->b_lblkno
),
4040 if (kret
!= KERN_SUCCESS
)
4041 panic("Failed to create UPL");
4043 for (upl_offset
= 0; upl_offset
< bp
->b_bufsize
; upl_offset
+= PAGE_SIZE
) {
4045 if (!upl_valid_page(pl
, upl_offset
/ PAGE_SIZE
) || !upl_dirty_page(pl
, upl_offset
/ PAGE_SIZE
)) {
4046 ubc_upl_abort(upl
, 0);
4052 kret
= ubc_upl_map(upl
, (vm_offset_t
*)&(bp
->b_datap
));
4054 if (kret
!= KERN_SUCCESS
)
4055 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
4060 SET(bp
->b_flags
, B_INVAL
);
4067 buffer_cache_gc(int all
)
4070 boolean_t did_large_zfree
= FALSE
;
4071 boolean_t need_wakeup
= FALSE
;
4072 int now
= buf_timestamp();
4073 uint32_t found
= 0, total_found
= 0;
4074 struct bqueues privq
;
4075 int thresh_hold
= BUF_STALE_THRESHHOLD
;
4080 * We only care about metadata (incore storage comes from zalloc()).
4081 * No more than 1024 buffers total, and only those not accessed within the
4082 * last 30s. We will also only examine 128 buffers during a single grab
4083 * of the lock in order to limit lock hold time.
4085 lck_mtx_lock(buf_mtxp
);
4089 need_wakeup
= FALSE
;
4091 while (((bp
= TAILQ_FIRST(&bufqueues
[BQ_META
]))) &&
4092 (now
> bp
->b_timestamp
) &&
4093 (now
- bp
->b_timestamp
> thresh_hold
) &&
4094 (found
< BUF_MAX_GC_BATCH_SIZE
)) {
4096 /* Remove from free list */
4097 bremfree_locked(bp
);
4101 bp
->b_owner
= current_thread();
4105 /* If dirty, move to laundry queue and remember to do wakeup */
4106 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
4107 SET(bp
->b_lflags
, BL_WANTDEALLOC
);
4116 * Mark busy and put on private list. We could technically get
4117 * away without setting BL_BUSY here.
4119 SET(bp
->b_lflags
, BL_BUSY
);
4123 * Remove from hash and dissociate from vp.
4130 TAILQ_INSERT_TAIL(&privq
, bp
, b_freelist
);
4137 /* Drop lock for batch processing */
4138 lck_mtx_unlock(buf_mtxp
);
4140 /* Wakeup and yield for laundry if need be */
4142 wakeup(&bufqueues
[BQ_LAUNDRY
]);
4143 (void)thread_block(THREAD_CONTINUE_NULL
);
4146 /* Clean up every buffer on private list */
4147 TAILQ_FOREACH(bp
, &privq
, b_freelist
) {
4148 /* Take note if we've definitely freed at least a page to a zone */
4149 if ((ISSET(bp
->b_flags
, B_ZALLOC
)) && (buf_size(bp
) >= PAGE_SIZE
)) {
4150 did_large_zfree
= TRUE
;
4153 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
4156 buf_free_meta_store(bp
);
4158 /* Release credentials */
4159 buf_release_credentials(bp
);
4161 /* Prepare for moving to empty queue */
4162 CLR(bp
->b_flags
, (B_META
| B_ZALLOC
| B_DELWRI
| B_LOCKED
4163 | B_AGE
| B_ASYNC
| B_NOCACHE
| B_FUA
));
4164 bp
->b_whichq
= BQ_EMPTY
;
4168 lck_mtx_lock(buf_mtxp
);
4170 /* Back under lock, move them all to invalid hash and clear busy */
4171 TAILQ_FOREACH(bp
, &privq
, b_freelist
) {
4172 binshash(bp
, &invalhash
);
4173 CLR(bp
->b_lflags
, BL_BUSY
);
4177 if (bp
->b_owner
!= current_thread()) {
4178 panic("Buffer stolen from buffer_cache_gc()");
4180 bp
->b_owner
= current_thread();
4185 /* And do a big bulk move to the empty queue */
4186 TAILQ_CONCAT(&bufqueues
[BQ_EMPTY
], &privq
, b_freelist
);
4187 total_found
+= found
;
4189 } while ((all
|| (total_found
< BUF_MAX_GC_COUNT
)) && (found
== BUF_MAX_GC_BATCH_SIZE
));
4191 lck_mtx_unlock(buf_mtxp
);
4193 return did_large_zfree
;
4206 bp_cmp(void *a
, void *b
)
4208 buf_t
*bp_a
= *(buf_t
**)a
,
4209 *bp_b
= *(buf_t
**)b
;
4212 // don't have to worry about negative block
4213 // numbers so this is ok to do.
4215 res
= (bp_a
->b_blkno
- bp_b
->b_blkno
);
4222 bflushq(int whichq
, mount_t mp
)
4226 int total_writes
= 0;
4227 static buf_t flush_table
[NFLUSH
];
4229 if (whichq
< 0 || whichq
>= BQUEUES
) {
4234 lck_mtx_lock(buf_mtxp
);
4236 bp
= TAILQ_FIRST(&bufqueues
[whichq
]);
4238 for (buf_count
= 0; bp
; bp
= next
) {
4239 next
= bp
->b_freelist
.tqe_next
;
4241 if (bp
->b_vp
== NULL
|| bp
->b_vp
->v_mount
!= mp
) {
4245 if (ISSET(bp
->b_flags
, B_DELWRI
) && !ISSET(bp
->b_lflags
, BL_BUSY
)) {
4247 bremfree_locked(bp
);
4249 bp
->b_owner
= current_thread();
4252 SET(bp
->b_lflags
, BL_BUSY
);
4255 flush_table
[buf_count
] = bp
;
4259 if (buf_count
>= NFLUSH
) {
4260 lck_mtx_unlock(buf_mtxp
);
4262 qsort(flush_table
, buf_count
, sizeof(struct buf
*), bp_cmp
);
4264 for (i
= 0; i
< buf_count
; i
++) {
4265 buf_bawrite(flush_table
[i
]);
4271 lck_mtx_unlock(buf_mtxp
);
4273 if (buf_count
> 0) {
4274 qsort(flush_table
, buf_count
, sizeof(struct buf
*), bp_cmp
);
4276 for (i
= 0; i
< buf_count
; i
++) {
4277 buf_bawrite(flush_table
[i
]);
4281 return (total_writes
);
4288 /* XXX move this to a separate file */
4291 * NOTE: THIS CODE HAS NOT BEEN UPDATED
4292 * WITH RESPECT TO THE NEW LOCKING MODEL
4297 * Dynamic Scaling of the Buffer Queues
4300 typedef long long blsize_t
;
4302 blsize_t MAXNBUF
; /* initialize to (sane_size / PAGE_SIZE) */
4303 /* Global tunable limits */
4304 blsize_t nbufh
; /* number of buffer headers */
4305 blsize_t nbuflow
; /* minimum number of buffer headers required */
4306 blsize_t nbufhigh
; /* maximum number of buffer headers allowed */
4307 blsize_t nbuftarget
; /* preferred number of buffer headers */
4312 * 1. 0 < nbuflow <= nbufh <= nbufhigh
4313 * 2. nbufhigh <= MAXNBUF
4314 * 3. 0 < nbuflow <= nbuftarget <= nbufhigh
4315 * 4. nbufh can not be set by sysctl().
4318 /* Per queue tunable limits */
4321 blsize_t bl_nlow
; /* minimum number of buffer headers required */
4322 blsize_t bl_num
; /* number of buffer headers on the queue */
4323 blsize_t bl_nlhigh
; /* maximum number of buffer headers allowed */
4324 blsize_t bl_target
; /* preferred number of buffer headers */
4325 long bl_stale
; /* Seconds after which a buffer is considered stale */
4331 * 1. 0 <= bl_nlow <= bl_num <= bl_nlhigh
4332 * 2. bl_nlhigh <= MAXNBUF
4333 * 3. bufqlim[BQ_META].bl_nlow != 0
4334 * 4. bufqlim[BQ_META].bl_nlow > (number of possible concurrent
4335 * file system IO operations)
4336 * 5. bl_num can not be set by sysctl().
4337 * 6. bl_nhigh <= nbufhigh
4343 * Defining it blsize_t as long permits 2^31 buffer headers per queue.
4344 * Which can describe (2^31 * PAGE_SIZE) memory per queue.
4346 * These limits are exported to by means of sysctl().
4347 * It was decided to define blsize_t as a 64 bit quantity.
4348 * This will make sure that we will not be required to change it
4349 * as long as we do not exceed 64 bit address space for the kernel.
4351 * low and high numbers parameters initialized at compile time
4352 * and boot arguments can be used to override them. sysctl()
4353 * would not change the value. sysctl() can get all the values
4354 * but can set only target. num is the current level.
4356 * Advantages of having a "bufqscan" thread doing the balancing are,
4357 * Keep enough bufs on BQ_EMPTY.
4358 * getnewbuf() by default will always select a buffer from the BQ_EMPTY.
4359 * getnewbuf() perfoms best if a buffer was found there.
4360 * Also this minimizes the possibility of starting IO
4361 * from getnewbuf(). That's a performance win, too.
4363 * Localize complex logic [balancing as well as time aging]
4366 * Simplify getnewbuf() logic by elimination of time aging code.
4372 * The goal of the dynamic scaling of the buffer queues to to keep
4373 * the size of the LRU close to bl_target. Buffers on a queue would
4376 * There would be a thread which will be responsible for "balancing"
4377 * the buffer cache queues.
4379 * The scan order would be: AGE, LRU, META, EMPTY.
4382 long bufqscanwait
= 0;
4384 static void bufqscan_thread();
4385 static int balancebufq(int q
);
4386 static int btrimempty(int n
);
4387 static __inline__
int initbufqscan(void);
4388 static __inline__
int nextbufq(int q
);
4389 static void buqlimprt(int all
);
4392 static __inline__
void
4395 if ((q
< 0) || (q
>= BQUEUES
))
4398 bufqlim
[q
].bl_num
++;
4402 static __inline__
void
4405 if ((q
< 0) || (q
>= BQUEUES
))
4408 bufqlim
[q
].bl_num
--;
4413 bufq_balance_thread_init(void)
4415 thread_t thread
= THREAD_NULL
;
4417 if (bufqscanwait
++ == 0) {
4419 /* Initalize globals */
4420 MAXNBUF
= (sane_size
/ PAGE_SIZE
);
4421 nbufh
= nbuf_headers
;
4422 nbuflow
= min(nbufh
, 100);
4423 nbufhigh
= min(MAXNBUF
, max(nbufh
, 2048));
4424 nbuftarget
= (sane_size
>> 5) / PAGE_SIZE
;
4425 nbuftarget
= max(nbuflow
, nbuftarget
);
4426 nbuftarget
= min(nbufhigh
, nbuftarget
);
4429 * Initialize the bufqlim
4433 bufqlim
[BQ_LOCKED
].bl_nlow
= 0;
4434 bufqlim
[BQ_LOCKED
].bl_nlhigh
= 32;
4435 bufqlim
[BQ_LOCKED
].bl_target
= 0;
4436 bufqlim
[BQ_LOCKED
].bl_stale
= 30;
4439 bufqlim
[BQ_LRU
].bl_nlow
= 0;
4440 bufqlim
[BQ_LRU
].bl_nlhigh
= nbufhigh
/4;
4441 bufqlim
[BQ_LRU
].bl_target
= nbuftarget
/4;
4442 bufqlim
[BQ_LRU
].bl_stale
= LRU_IS_STALE
;
4445 bufqlim
[BQ_AGE
].bl_nlow
= 0;
4446 bufqlim
[BQ_AGE
].bl_nlhigh
= nbufhigh
/4;
4447 bufqlim
[BQ_AGE
].bl_target
= nbuftarget
/4;
4448 bufqlim
[BQ_AGE
].bl_stale
= AGE_IS_STALE
;
4451 bufqlim
[BQ_EMPTY
].bl_nlow
= 0;
4452 bufqlim
[BQ_EMPTY
].bl_nlhigh
= nbufhigh
/4;
4453 bufqlim
[BQ_EMPTY
].bl_target
= nbuftarget
/4;
4454 bufqlim
[BQ_EMPTY
].bl_stale
= 600000;
4457 bufqlim
[BQ_META
].bl_nlow
= 0;
4458 bufqlim
[BQ_META
].bl_nlhigh
= nbufhigh
/4;
4459 bufqlim
[BQ_META
].bl_target
= nbuftarget
/4;
4460 bufqlim
[BQ_META
].bl_stale
= META_IS_STALE
;
4463 bufqlim
[BQ_LOCKED
].bl_nlow
= 0;
4464 bufqlim
[BQ_LOCKED
].bl_nlhigh
= 32;
4465 bufqlim
[BQ_LOCKED
].bl_target
= 0;
4466 bufqlim
[BQ_LOCKED
].bl_stale
= 30;
4471 /* create worker thread */
4472 kernel_thread_start((thread_continue_t
)bufqscan_thread
, NULL
, &thread
);
4473 thread_deallocate(thread
);
4476 /* The workloop for the buffer balancing thread */
4484 int q
; /* buffer queue to process */
4488 moretodo
|= balancebufq(q
);
4497 (void)tsleep((void *)&bufqscanwait
, PRIBIO
, "bufqscanwait", 60 * hz
);
4502 /* Seed for the buffer queue balancing */
4503 static __inline__
int
4506 /* Start with AGE queue */
4510 /* Pick next buffer queue to balance */
4511 static __inline__
int
4514 int order
[] = { BQ_AGE
, BQ_LRU
, BQ_META
, BQ_EMPTY
, 0 };
4521 /* function to balance the buffer queues */
4528 /* reject invalid q */
4529 if ((q
< 0) || (q
>= BQUEUES
))
4532 /* LOCKED or LAUNDRY queue MUST not be balanced */
4533 if ((q
== BQ_LOCKED
) || (q
== BQ_LAUNDRY
))
4536 n
= (bufqlim
[q
].bl_num
- bufqlim
[q
].bl_target
);
4538 /* If queue has less than target nothing more to do */
4543 /* Balance only a small amount (12.5%) at a time */
4547 /* EMPTY queue needs special handling */
4548 if (q
== BQ_EMPTY
) {
4549 moretodo
|= btrimempty(n
);
4553 t
= buf_timestamp():
4555 for (; n
> 0; n
--) {
4556 struct buf
*bp
= bufqueues
[q
].tqh_first
;
4560 /* check if it's stale */
4561 if ((t
- bp
->b_timestamp
) > bufqlim
[q
].bl_stale
) {
4562 if (bcleanbuf(bp
, FALSE
)) {
4563 /* buf_bawrite() issued, bp not ready */
4566 /* release the cleaned buffer to BQ_EMPTY */
4567 SET(bp
->b_flags
, B_INVAL
);
4582 * When struct buf are allocated dynamically, this would
4583 * reclaim upto 'n' struct buf from the empty queue.
4593 static char *bname
[BQUEUES
] =
4594 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
4597 for (i
= 0; i
< BQUEUES
; i
++) {
4598 printf("%s : ", bname
[i
]);
4599 printf("min = %ld, ", (long)bufqlim
[i
].bl_nlow
);
4600 printf("cur = %ld, ", (long)bufqlim
[i
].bl_num
);
4601 printf("max = %ld, ", (long)bufqlim
[i
].bl_nlhigh
);
4602 printf("target = %ld, ", (long)bufqlim
[i
].bl_target
);
4603 printf("stale after %ld seconds\n", bufqlim
[i
].bl_stale
);
4606 for (i
= 0; i
< BQUEUES
; i
++) {
4607 printf("%s : ", bname
[i
]);
4608 printf("cur = %ld, ", (long)bufqlim
[i
].bl_num
);