2 * Copyright (c) 2000-2007 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>
104 #include <sys/kdebug.h>
106 #include <libkern/OSAtomic.h>
107 #include <sys/ubc_internal.h>
112 static __inline__
void bufqinc(int q
);
113 static __inline__
void bufqdec(int q
);
116 static int bcleanbuf(buf_t bp
);
117 static int brecover_data(buf_t bp
);
118 static boolean_t
incore(vnode_t vp
, daddr64_t blkno
);
119 /* timeout is in msecs */
120 static buf_t
getnewbuf(int slpflag
, int slptimeo
, int *queue
);
121 static void bremfree_locked(buf_t bp
);
122 static void buf_reassign(buf_t bp
, vnode_t newvp
);
123 static errno_t
buf_acquire_locked(buf_t bp
, int flags
, int slpflag
, int slptimeo
);
124 static int buf_iterprepare(vnode_t vp
, struct buflists
*, int flags
);
125 static void buf_itercomplete(vnode_t vp
, struct buflists
*, int flags
);
127 __private_extern__
int bdwrite_internal(buf_t
, int);
129 /* zone allocated buffer headers */
130 static void bufzoneinit(void) __attribute__((section("__TEXT, initcode")));
131 static void bcleanbuf_thread_init(void) __attribute__((section("__TEXT, initcode")));
132 static void bcleanbuf_thread(void);
134 static zone_t buf_hdr_zone
;
135 static int buf_hdr_count
;
139 * Definitions for the buffer hash lists.
141 #define BUFHASH(dvp, lbn) \
142 (&bufhashtbl[((long)(dvp) / sizeof(*(dvp)) + (int)(lbn)) & bufhash])
143 LIST_HEAD(bufhashhdr
, buf
) *bufhashtbl
, invalhash
;
146 static buf_t
incore_locked(vnode_t vp
, daddr64_t blkno
, struct bufhashhdr
*dp
);
148 /* Definitions for the buffer stats. */
149 struct bufstats bufstats
;
151 /* Number of delayed write buffers */
154 static int boot_nbuf_headers
= 0;
157 static TAILQ_HEAD(ioqueue
, buf
) iobufqueue
;
158 static TAILQ_HEAD(bqueues
, buf
) bufqueues
[BQUEUES
];
159 static int needbuffer
;
160 static int need_iobuffer
;
162 static lck_grp_t
*buf_mtx_grp
;
163 static lck_attr_t
*buf_mtx_attr
;
164 static lck_grp_attr_t
*buf_mtx_grp_attr
;
165 static lck_mtx_t
*iobuffer_mtxp
;
166 static lck_mtx_t
*buf_mtxp
;
168 static __inline__
int
177 * Insq/Remq for the buffer free lists.
180 #define binsheadfree(bp, dp, whichq) do { \
181 TAILQ_INSERT_HEAD(dp, bp, b_freelist); \
185 #define binstailfree(bp, dp, whichq) do { \
186 TAILQ_INSERT_TAIL(dp, bp, b_freelist); \
190 #define binsheadfree(bp, dp, whichq) do { \
191 TAILQ_INSERT_HEAD(dp, bp, b_freelist); \
194 #define binstailfree(bp, dp, whichq) do { \
195 TAILQ_INSERT_TAIL(dp, bp, b_freelist); \
200 #define BHASHENTCHECK(bp) \
201 if ((bp)->b_hash.le_prev != (struct buf **)0xdeadbeef) \
202 panic("%p: b_hash.le_prev is not deadbeef", (bp));
204 #define BLISTNONE(bp) \
205 (bp)->b_hash.le_next = (struct buf *)0; \
206 (bp)->b_hash.le_prev = (struct buf **)0xdeadbeef;
209 * Insq/Remq for the vnode usage lists.
211 #define bufinsvn(bp, dp) LIST_INSERT_HEAD(dp, bp, b_vnbufs)
212 #define bufremvn(bp) { \
213 LIST_REMOVE(bp, b_vnbufs); \
214 (bp)->b_vnbufs.le_next = NOLIST; \
218 * Time in seconds before a buffer on a list is
219 * considered as a stale buffer
221 #define LRU_IS_STALE 120 /* default value for the LRU */
222 #define AGE_IS_STALE 60 /* default value for the AGE */
223 #define META_IS_STALE 180 /* default value for the BQ_META */
225 int lru_is_stale
= LRU_IS_STALE
;
226 int age_is_stale
= AGE_IS_STALE
;
227 int meta_is_stale
= META_IS_STALE
;
231 /* LIST_INSERT_HEAD() with assertions */
232 static __inline__
void
233 blistenterhead(struct bufhashhdr
* head
, buf_t bp
)
235 if ((bp
->b_hash
.le_next
= (head
)->lh_first
) != NULL
)
236 (head
)->lh_first
->b_hash
.le_prev
= &(bp
)->b_hash
.le_next
;
237 (head
)->lh_first
= bp
;
238 bp
->b_hash
.le_prev
= &(head
)->lh_first
;
239 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
240 panic("blistenterhead: le_prev is deadbeef");
243 static __inline__
void
244 binshash(buf_t bp
, struct bufhashhdr
*dp
)
248 #endif /* DIAGNOSTIC */
254 for(; nbp
!= NULL
; nbp
= nbp
->b_hash
.le_next
) {
256 panic("buf already in hashlist");
258 #endif /* DIAGNOSTIC */
260 blistenterhead(dp
, bp
);
263 static __inline__
void
266 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
267 panic("bremhash le_prev is deadbeef");
268 if (bp
->b_hash
.le_next
== bp
)
269 panic("bremhash: next points to self");
271 if (bp
->b_hash
.le_next
!= NULL
)
272 bp
->b_hash
.le_next
->b_hash
.le_prev
= bp
->b_hash
.le_prev
;
273 *bp
->b_hash
.le_prev
= (bp
)->b_hash
.le_next
;
280 buf_valid(buf_t bp
) {
282 if ( (bp
->b_flags
& (B_DONE
| B_DELWRI
)) )
288 buf_fromcache(buf_t bp
) {
290 if ( (bp
->b_flags
& B_CACHE
) )
296 buf_markinvalid(buf_t bp
) {
298 SET(bp
->b_flags
, B_INVAL
);
302 buf_markdelayed(buf_t bp
) {
304 if (!ISSET(bp
->b_flags
, B_DELWRI
)) {
305 SET(bp
->b_flags
, B_DELWRI
);
307 OSAddAtomic(1, &nbdwrite
);
308 buf_reassign(bp
, bp
->b_vp
);
310 SET(bp
->b_flags
, B_DONE
);
314 buf_markeintr(buf_t bp
) {
316 SET(bp
->b_flags
, B_EINTR
);
321 buf_markaged(buf_t bp
) {
323 SET(bp
->b_flags
, B_AGE
);
329 if ((bp
->b_flags
& B_FUA
) == B_FUA
)
335 buf_markfua(buf_t bp
) {
337 SET(bp
->b_flags
, B_FUA
);
341 buf_error(buf_t bp
) {
343 return (bp
->b_error
);
347 buf_seterror(buf_t bp
, errno_t error
) {
349 if ((bp
->b_error
= error
))
350 SET(bp
->b_flags
, B_ERROR
);
352 CLR(bp
->b_flags
, B_ERROR
);
356 buf_setflags(buf_t bp
, int32_t flags
) {
358 SET(bp
->b_flags
, (flags
& BUF_X_WRFLAGS
));
362 buf_clearflags(buf_t bp
, int32_t flags
) {
364 CLR(bp
->b_flags
, (flags
& BUF_X_WRFLAGS
));
368 buf_flags(buf_t bp
) {
370 return ((bp
->b_flags
& BUF_X_RDFLAGS
));
374 buf_reset(buf_t bp
, int32_t io_flags
) {
376 CLR(bp
->b_flags
, (B_READ
| B_WRITE
| B_ERROR
| B_DONE
| B_INVAL
| B_ASYNC
| B_NOCACHE
| B_FUA
));
377 SET(bp
->b_flags
, (io_flags
& (B_ASYNC
| B_READ
| B_WRITE
| B_NOCACHE
)));
383 buf_count(buf_t bp
) {
385 return (bp
->b_bcount
);
389 buf_setcount(buf_t bp
, uint32_t bcount
) {
391 bp
->b_bcount
= bcount
;
397 return (bp
->b_bufsize
);
401 buf_setsize(buf_t bp
, uint32_t bufsize
) {
403 bp
->b_bufsize
= bufsize
;
407 buf_resid(buf_t bp
) {
409 return (bp
->b_resid
);
413 buf_setresid(buf_t bp
, uint32_t resid
) {
419 buf_dirtyoff(buf_t bp
) {
421 return (bp
->b_dirtyoff
);
425 buf_dirtyend(buf_t bp
) {
427 return (bp
->b_dirtyend
);
431 buf_setdirtyoff(buf_t bp
, uint32_t dirtyoff
) {
433 bp
->b_dirtyoff
= dirtyoff
;
437 buf_setdirtyend(buf_t bp
, uint32_t dirtyend
) {
439 bp
->b_dirtyend
= dirtyend
;
443 buf_dataptr(buf_t bp
) {
445 return (bp
->b_datap
);
449 buf_setdataptr(buf_t bp
, uintptr_t data
) {
455 buf_vnode(buf_t bp
) {
461 buf_setvnode(buf_t bp
, vnode_t vp
) {
468 buf_callback(buf_t bp
)
470 if ( !(bp
->b_flags
& B_CALL
) )
471 return ((void *) NULL
);
473 return ((void *)bp
->b_iodone
);
478 buf_setcallback(buf_t bp
, void (*callback
)(buf_t
, void *), void *transaction
)
481 bp
->b_flags
|= (B_CALL
| B_ASYNC
);
483 bp
->b_flags
&= ~B_CALL
;
484 bp
->b_transaction
= transaction
;
485 bp
->b_iodone
= callback
;
491 buf_setupl(buf_t bp
, upl_t upl
, uint32_t offset
)
494 if ( !(bp
->b_lflags
& BL_IOBUF
) )
498 bp
->b_flags
|= B_CLUSTER
;
500 bp
->b_flags
&= ~B_CLUSTER
;
502 bp
->b_uploffset
= offset
;
508 buf_clone(buf_t bp
, int io_offset
, int io_size
, void (*iodone
)(buf_t
, void *), void *arg
)
512 if (io_offset
< 0 || io_size
< 0)
515 if ((unsigned)(io_offset
+ io_size
) > (unsigned)bp
->b_bcount
)
518 if (bp
->b_flags
& B_CLUSTER
) {
519 if (io_offset
&& ((bp
->b_uploffset
+ io_offset
) & PAGE_MASK
))
522 if (((bp
->b_uploffset
+ io_offset
+ io_size
) & PAGE_MASK
) && ((io_offset
+ io_size
) < bp
->b_bcount
))
525 io_bp
= alloc_io_buf(bp
->b_vp
, 0);
527 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
);
530 io_bp
->b_transaction
= arg
;
531 io_bp
->b_iodone
= iodone
;
532 io_bp
->b_flags
|= B_CALL
;
534 if (bp
->b_flags
& B_CLUSTER
) {
535 io_bp
->b_upl
= bp
->b_upl
;
536 io_bp
->b_uploffset
= bp
->b_uploffset
+ io_offset
;
538 io_bp
->b_datap
= (uintptr_t)(((char *)bp
->b_datap
) + io_offset
);
540 io_bp
->b_bcount
= io_size
;
548 buf_setfilter(buf_t bp
, void (*filter
)(buf_t
, void *), void *transaction
,
549 void **old_iodone
, void **old_transaction
)
552 *old_iodone
= (void *)(bp
->b_iodone
);
554 *old_transaction
= (void *)(bp
->b_transaction
);
556 bp
->b_transaction
= transaction
;
557 bp
->b_iodone
= filter
;
559 bp
->b_flags
|= B_FILTER
;
561 bp
->b_flags
&= ~B_FILTER
;
566 buf_blkno(buf_t bp
) {
568 return (bp
->b_blkno
);
572 buf_lblkno(buf_t bp
) {
574 return (bp
->b_lblkno
);
578 buf_setblkno(buf_t bp
, daddr64_t blkno
) {
584 buf_setlblkno(buf_t bp
, daddr64_t lblkno
) {
586 bp
->b_lblkno
= lblkno
;
590 buf_device(buf_t bp
) {
596 buf_setdevice(buf_t bp
, vnode_t vp
) {
598 if ((vp
->v_type
!= VBLK
) && (vp
->v_type
!= VCHR
))
600 bp
->b_dev
= vp
->v_rdev
;
607 buf_drvdata(buf_t bp
) {
609 return (bp
->b_drvdata
);
613 buf_setdrvdata(buf_t bp
, void *drvdata
) {
615 bp
->b_drvdata
= drvdata
;
619 buf_fsprivate(buf_t bp
) {
621 return (bp
->b_fsprivate
);
625 buf_setfsprivate(buf_t bp
, void *fsprivate
) {
627 bp
->b_fsprivate
= fsprivate
;
631 buf_rcred(buf_t bp
) {
633 return (bp
->b_rcred
);
637 buf_wcred(buf_t bp
) {
639 return (bp
->b_wcred
);
649 buf_uploffset(buf_t bp
) {
651 return ((uint32_t)(bp
->b_uploffset
));
662 buf_map(buf_t bp
, caddr_t
*io_addr
)
668 if ( !(bp
->b_flags
& B_CLUSTER
)) {
669 *io_addr
= (caddr_t
)bp
->b_datap
;
672 real_bp
= (buf_t
)(bp
->b_real_bp
);
674 if (real_bp
&& real_bp
->b_datap
) {
676 * b_real_bp is only valid if B_CLUSTER is SET
677 * if it's non-zero, than someone did a cluster_bp call
678 * if the backing physical pages were already mapped
679 * in before the call to cluster_bp (non-zero b_datap),
680 * than we just use that mapping
682 *io_addr
= (caddr_t
)real_bp
->b_datap
;
685 kret
= ubc_upl_map(bp
->b_upl
, &vaddr
); /* Map it in */
687 if (kret
!= KERN_SUCCESS
) {
692 vaddr
+= bp
->b_uploffset
;
694 *io_addr
= (caddr_t
)vaddr
;
705 if ( !(bp
->b_flags
& B_CLUSTER
))
708 * see buf_map for the explanation
710 real_bp
= (buf_t
)(bp
->b_real_bp
);
712 if (real_bp
&& real_bp
->b_datap
)
715 if ((bp
->b_lflags
& BL_IOBUF
) &&
716 ((bp
->b_flags
& (B_PAGEIO
| B_READ
)) != (B_PAGEIO
| B_READ
))) {
718 * ignore pageins... the 'right' thing will
719 * happen due to the way we handle speculative
722 * when we commit these pages, we'll hit
723 * it with UPL_COMMIT_INACTIVE which
724 * will clear the reference bit that got
725 * turned on when we touched the mapping
727 bp
->b_flags
|= B_AGE
;
729 kret
= ubc_upl_unmap(bp
->b_upl
);
731 if (kret
!= KERN_SUCCESS
)
738 buf_clear(buf_t bp
) {
741 if (buf_map(bp
, &baddr
) == 0) {
742 bzero(baddr
, bp
->b_bcount
);
751 * Read or write a buffer that is not contiguous on disk.
752 * buffer is marked done/error at the conclusion
755 buf_strategy_fragmented(vnode_t devvp
, buf_t bp
, off_t f_offset
, size_t contig_bytes
)
757 vnode_t vp
= buf_vnode(bp
);
758 buf_t io_bp
; /* For reading or writing a single block */
761 size_t io_contig_bytes
;
767 * save our starting point... the bp was already mapped
768 * in buf_strategy before we got called
769 * no sense doing it again.
771 io_blkno
= bp
->b_blkno
;
773 * Make sure we redo this mapping for the next I/O
774 * i.e. this can never be a 'permanent' mapping
776 bp
->b_blkno
= bp
->b_lblkno
;
779 * Get an io buffer to do the deblocking
781 io_bp
= alloc_io_buf(devvp
, 0);
783 io_bp
->b_lblkno
= bp
->b_lblkno
;
784 io_bp
->b_datap
= bp
->b_datap
;
785 io_resid
= bp
->b_bcount
;
786 io_direction
= bp
->b_flags
& B_READ
;
787 io_contig_bytes
= contig_bytes
;
789 if (bp
->b_flags
& B_READ
)
790 bmap_flags
= VNODE_READ
;
792 bmap_flags
= VNODE_WRITE
;
797 * this is unexepected, but we'll allow for it
799 bzero((caddr_t
)io_bp
->b_datap
, (int)io_contig_bytes
);
801 io_bp
->b_bcount
= io_contig_bytes
;
802 io_bp
->b_bufsize
= io_contig_bytes
;
803 io_bp
->b_resid
= io_contig_bytes
;
804 io_bp
->b_blkno
= io_blkno
;
806 buf_reset(io_bp
, io_direction
);
809 * Call the device to do the I/O and wait for it. Make sure the appropriate party is charged for write
812 if (!ISSET(bp
->b_flags
, B_READ
))
813 OSAddAtomic(1, &devvp
->v_numoutput
);
815 if ((error
= VNOP_STRATEGY(io_bp
)))
817 if ((error
= (int)buf_biowait(io_bp
)))
819 if (io_bp
->b_resid
) {
820 io_resid
-= (io_contig_bytes
- io_bp
->b_resid
);
824 if ((io_resid
-= io_contig_bytes
) == 0)
826 f_offset
+= io_contig_bytes
;
827 io_bp
->b_datap
+= io_contig_bytes
;
830 * Map the current position to a physical block number
832 if ((error
= VNOP_BLOCKMAP(vp
, f_offset
, io_resid
, &io_blkno
, &io_contig_bytes
, NULL
, bmap_flags
, NULL
)))
838 buf_seterror(bp
, error
);
839 bp
->b_resid
= io_resid
;
841 * This I/O is now complete
850 * struct vnop_strategy_args {
855 buf_strategy(vnode_t devvp
, void *ap
)
857 buf_t bp
= ((struct vnop_strategy_args
*)ap
)->a_bp
;
858 vnode_t vp
= bp
->b_vp
;
862 if (vp
== NULL
|| vp
->v_type
== VCHR
|| vp
->v_type
== VBLK
)
863 panic("buf_strategy: b_vp == NULL || vtype == VCHR | VBLK\n");
865 * associate the physical device with
866 * with this buf_t even if we don't
867 * end up issuing the I/O...
869 bp
->b_dev
= devvp
->v_rdev
;
870 DTRACE_IO1(start
, buf_t
, bp
);
872 if (bp
->b_flags
& B_READ
)
873 bmap_flags
= VNODE_READ
;
875 bmap_flags
= VNODE_WRITE
;
877 if ( !(bp
->b_flags
& B_CLUSTER
)) {
881 * we have a UPL associated with this bp
882 * go through cluster_bp which knows how
883 * to deal with filesystem block sizes
884 * that aren't equal to the page size
886 return (cluster_bp(bp
));
888 if (bp
->b_blkno
== bp
->b_lblkno
) {
892 if ((error
= VNOP_BLKTOOFF(vp
, bp
->b_lblkno
, &f_offset
))) {
893 buf_seterror(bp
, error
);
898 if ((error
= VNOP_BLOCKMAP(vp
, f_offset
, bp
->b_bcount
, &bp
->b_blkno
, &contig_bytes
, NULL
, bmap_flags
, NULL
))) {
899 buf_seterror(bp
, error
);
904 if (bp
->b_blkno
== -1)
906 else if ((long)contig_bytes
< bp
->b_bcount
)
907 return (buf_strategy_fragmented(devvp
, bp
, f_offset
, contig_bytes
));
909 if (bp
->b_blkno
== -1) {
915 * we can issue the I/O because...
916 * either B_CLUSTER is set which
917 * means that the I/O is properly set
918 * up to be a multiple of the page size, or
919 * we were able to successfully set up the
920 * phsyical block mapping
922 return (VOCALL(devvp
->v_op
, VOFFSET(vnop_strategy
), ap
));
928 buf_alloc(vnode_t vp
)
930 return(alloc_io_buf(vp
, 0));
941 * iterate buffers for the specified vp.
942 * if BUF_SCAN_DIRTY is set, do the dirty list
943 * if BUF_SCAN_CLEAN is set, do the clean list
944 * if neither flag is set, default to BUF_SCAN_DIRTY
945 * if BUF_NOTIFY_BUSY is set, call the callout function using a NULL bp for busy pages
948 struct buf_iterate_info_t
{
950 struct buflists
*listhead
;
954 buf_iterate(vnode_t vp
, int (*callout
)(buf_t
, void *), int flags
, void *arg
)
958 struct buflists local_iterblkhd
;
959 int lock_flags
= BAC_NOWAIT
| BAC_REMOVE
;
960 int notify_busy
= flags
& BUF_NOTIFY_BUSY
;
961 struct buf_iterate_info_t list
[2];
964 if (flags
& BUF_SKIP_LOCKED
)
965 lock_flags
|= BAC_SKIP_LOCKED
;
966 if (flags
& BUF_SKIP_NONLOCKED
)
967 lock_flags
|= BAC_SKIP_NONLOCKED
;
969 if ( !(flags
& (BUF_SCAN_DIRTY
| BUF_SCAN_CLEAN
)))
970 flags
|= BUF_SCAN_DIRTY
;
974 if (flags
& BUF_SCAN_DIRTY
) {
975 list
[num_lists
].flag
= VBI_DIRTY
;
976 list
[num_lists
].listhead
= &vp
->v_dirtyblkhd
;
979 if (flags
& BUF_SCAN_CLEAN
) {
980 list
[num_lists
].flag
= VBI_CLEAN
;
981 list
[num_lists
].listhead
= &vp
->v_cleanblkhd
;
985 for (i
= 0; i
< num_lists
; i
++) {
986 lck_mtx_lock(buf_mtxp
);
988 if (buf_iterprepare(vp
, &local_iterblkhd
, list
[i
].flag
)) {
989 lck_mtx_unlock(buf_mtxp
);
992 while (!LIST_EMPTY(&local_iterblkhd
)) {
993 bp
= LIST_FIRST(&local_iterblkhd
);
994 LIST_REMOVE(bp
, b_vnbufs
);
995 LIST_INSERT_HEAD(list
[i
].listhead
, bp
, b_vnbufs
);
997 if (buf_acquire_locked(bp
, lock_flags
, 0, 0)) {
1005 lck_mtx_unlock(buf_mtxp
);
1007 retval
= callout(bp
, arg
);
1016 case BUF_RETURNED_DONE
:
1019 lck_mtx_lock(buf_mtxp
);
1021 case BUF_CLAIMED_DONE
:
1022 lck_mtx_lock(buf_mtxp
);
1025 lck_mtx_lock(buf_mtxp
);
1026 } /* while list has more nodes */
1028 buf_itercomplete(vp
, &local_iterblkhd
, list
[i
].flag
);
1029 lck_mtx_unlock(buf_mtxp
);
1030 } /* for each list */
1035 * Flush out and invalidate all buffers associated with a vnode.
1038 buf_invalidateblks(vnode_t vp
, int flags
, int slpflag
, int slptimeo
)
1042 int must_rescan
= 1;
1043 struct buflists local_iterblkhd
;
1045 lck_mtx_lock(buf_mtxp
);
1048 if (must_rescan
== 0)
1050 * the lists may not be empty, but all that's left at this
1051 * point are metadata or B_LOCKED buffers which are being
1052 * skipped... we know this because we made it through both
1053 * the clean and dirty lists without dropping buf_mtxp...
1054 * each time we drop buf_mtxp we bump "must_rescan"
1057 if (LIST_EMPTY(&vp
->v_cleanblkhd
) && LIST_EMPTY(&vp
->v_dirtyblkhd
))
1061 * iterate the clean list
1063 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_CLEAN
)) {
1064 goto try_dirty_list
;
1066 while (!LIST_EMPTY(&local_iterblkhd
)) {
1067 bp
= LIST_FIRST(&local_iterblkhd
);
1069 LIST_REMOVE(bp
, b_vnbufs
);
1070 LIST_INSERT_HEAD(&vp
->v_cleanblkhd
, bp
, b_vnbufs
);
1073 * some filesystems distinguish meta data blocks with a negative logical block #
1075 if ((flags
& BUF_SKIP_META
) && (bp
->b_lblkno
< 0 || ISSET(bp
->b_flags
, B_META
)))
1078 if ( (error
= (int)buf_acquire_locked(bp
, BAC_REMOVE
| BAC_SKIP_LOCKED
, slpflag
, slptimeo
)) ) {
1079 if (error
== EDEADLK
)
1081 * this buffer was marked B_LOCKED...
1082 * we didn't drop buf_mtxp, so we
1083 * we don't need to rescan
1086 if (error
== EAGAIN
) {
1088 * found a busy buffer... we blocked and
1089 * dropped buf_mtxp, so we're going to
1090 * need to rescan after this pass is completed
1096 * got some kind of 'real' error out of the msleep
1097 * in buf_acquire_locked, terminate the scan and return the error
1099 buf_itercomplete(vp
, &local_iterblkhd
, VBI_CLEAN
);
1101 lck_mtx_unlock(buf_mtxp
);
1104 lck_mtx_unlock(buf_mtxp
);
1106 SET(bp
->b_flags
, B_INVAL
);
1109 lck_mtx_lock(buf_mtxp
);
1112 * by dropping buf_mtxp, we allow new
1113 * buffers to be added to the vnode list(s)
1114 * we'll have to rescan at least once more
1115 * if the queues aren't empty
1119 buf_itercomplete(vp
, &local_iterblkhd
, VBI_CLEAN
);
1123 * Now iterate on dirty blks
1125 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_DIRTY
)) {
1128 while (!LIST_EMPTY(&local_iterblkhd
)) {
1129 bp
= LIST_FIRST(&local_iterblkhd
);
1131 LIST_REMOVE(bp
, b_vnbufs
);
1132 LIST_INSERT_HEAD(&vp
->v_dirtyblkhd
, bp
, b_vnbufs
);
1135 * some filesystems distinguish meta data blocks with a negative logical block #
1137 if ((flags
& BUF_SKIP_META
) && (bp
->b_lblkno
< 0 || ISSET(bp
->b_flags
, B_META
)))
1140 if ( (error
= (int)buf_acquire_locked(bp
, BAC_REMOVE
| BAC_SKIP_LOCKED
, slpflag
, slptimeo
)) ) {
1141 if (error
== EDEADLK
)
1143 * this buffer was marked B_LOCKED...
1144 * we didn't drop buf_mtxp, so we
1145 * we don't need to rescan
1148 if (error
== EAGAIN
) {
1150 * found a busy buffer... we blocked and
1151 * dropped buf_mtxp, so we're going to
1152 * need to rescan after this pass is completed
1158 * got some kind of 'real' error out of the msleep
1159 * in buf_acquire_locked, terminate the scan and return the error
1161 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1163 lck_mtx_unlock(buf_mtxp
);
1166 lck_mtx_unlock(buf_mtxp
);
1168 SET(bp
->b_flags
, B_INVAL
);
1170 if (ISSET(bp
->b_flags
, B_DELWRI
) && (flags
& BUF_WRITE_DATA
))
1171 (void) VNOP_BWRITE(bp
);
1175 lck_mtx_lock(buf_mtxp
);
1177 * by dropping buf_mtxp, we allow new
1178 * buffers to be added to the vnode list(s)
1179 * we'll have to rescan at least once more
1180 * if the queues aren't empty
1184 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1186 lck_mtx_unlock(buf_mtxp
);
1192 buf_flushdirtyblks(vnode_t vp
, int wait
, int flags
, const char *msg
) {
1194 int writes_issued
= 0;
1197 struct buflists local_iterblkhd
;
1198 int lock_flags
= BAC_NOWAIT
| BAC_REMOVE
;
1200 if (flags
& BUF_SKIP_LOCKED
)
1201 lock_flags
|= BAC_SKIP_LOCKED
;
1202 if (flags
& BUF_SKIP_NONLOCKED
)
1203 lock_flags
|= BAC_SKIP_NONLOCKED
;
1205 lck_mtx_lock(buf_mtxp
);
1207 if (buf_iterprepare(vp
, &local_iterblkhd
, VBI_DIRTY
) == 0) {
1208 while (!LIST_EMPTY(&local_iterblkhd
)) {
1209 bp
= LIST_FIRST(&local_iterblkhd
);
1210 LIST_REMOVE(bp
, b_vnbufs
);
1211 LIST_INSERT_HEAD(&vp
->v_dirtyblkhd
, bp
, b_vnbufs
);
1213 if ((error
= buf_acquire_locked(bp
, lock_flags
, 0, 0)) == EBUSY
)
1217 lck_mtx_unlock(buf_mtxp
);
1219 bp
->b_flags
&= ~B_LOCKED
;
1222 * Wait for I/O associated with indirect blocks to complete,
1223 * since there is no way to quickly wait for them below.
1225 if ((bp
->b_vp
== vp
) || (wait
== 0))
1226 (void) buf_bawrite(bp
);
1228 (void) VNOP_BWRITE(bp
);
1231 lck_mtx_lock(buf_mtxp
);
1233 buf_itercomplete(vp
, &local_iterblkhd
, VBI_DIRTY
);
1235 lck_mtx_unlock(buf_mtxp
);
1238 (void)vnode_waitforwrites(vp
, 0, 0, 0, msg
);
1240 if (vp
->v_dirtyblkhd
.lh_first
&& busy
) {
1242 * we had one or more BUSY buffers on
1243 * the dirtyblock list... most likely
1244 * these are due to delayed writes that
1245 * were moved to the bclean queue but
1246 * have not yet been 'written'.
1247 * if we issued some writes on the
1248 * previous pass, we try again immediately
1249 * if we didn't, we'll sleep for some time
1250 * to allow the state to change...
1252 if (writes_issued
== 0) {
1253 (void)tsleep((caddr_t
)&vp
->v_numoutput
,
1254 PRIBIO
+ 1, "vnode_flushdirtyblks", hz
/20);
1266 * called with buf_mtxp held...
1267 * this lock protects the queue manipulation
1270 buf_iterprepare(vnode_t vp
, struct buflists
*iterheadp
, int flags
)
1272 struct buflists
* listheadp
;
1274 if (flags
& VBI_DIRTY
)
1275 listheadp
= &vp
->v_dirtyblkhd
;
1277 listheadp
= &vp
->v_cleanblkhd
;
1279 while (vp
->v_iterblkflags
& VBI_ITER
) {
1280 vp
->v_iterblkflags
|= VBI_ITERWANT
;
1281 msleep(&vp
->v_iterblkflags
, buf_mtxp
, 0, "buf_iterprepare", NULL
);
1283 if (LIST_EMPTY(listheadp
)) {
1284 LIST_INIT(iterheadp
);
1287 vp
->v_iterblkflags
|= VBI_ITER
;
1289 iterheadp
->lh_first
= listheadp
->lh_first
;
1290 listheadp
->lh_first
->b_vnbufs
.le_prev
= &iterheadp
->lh_first
;
1291 LIST_INIT(listheadp
);
1297 * called with buf_mtxp held...
1298 * this lock protects the queue manipulation
1301 buf_itercomplete(vnode_t vp
, struct buflists
*iterheadp
, int flags
)
1303 struct buflists
* listheadp
;
1306 if (flags
& VBI_DIRTY
)
1307 listheadp
= &vp
->v_dirtyblkhd
;
1309 listheadp
= &vp
->v_cleanblkhd
;
1311 while (!LIST_EMPTY(iterheadp
)) {
1312 bp
= LIST_FIRST(iterheadp
);
1313 LIST_REMOVE(bp
, b_vnbufs
);
1314 LIST_INSERT_HEAD(listheadp
, bp
, b_vnbufs
);
1316 vp
->v_iterblkflags
&= ~VBI_ITER
;
1318 if (vp
->v_iterblkflags
& VBI_ITERWANT
) {
1319 vp
->v_iterblkflags
&= ~VBI_ITERWANT
;
1320 wakeup(&vp
->v_iterblkflags
);
1326 bremfree_locked(buf_t bp
)
1328 struct bqueues
*dp
= NULL
;
1331 * We only calculate the head of the freelist when removing
1332 * the last element of the list as that is the only time that
1333 * it is needed (e.g. to reset the tail pointer).
1335 * NB: This makes an assumption about how tailq's are implemented.
1337 whichq
= bp
->b_whichq
;
1339 if (bp
->b_freelist
.tqe_next
== NULL
) {
1340 dp
= &bufqueues
[whichq
];
1342 if (dp
->tqh_last
!= &bp
->b_freelist
.tqe_next
)
1343 panic("bremfree: lost tail");
1345 TAILQ_REMOVE(dp
, bp
, b_freelist
);
1350 if (whichq
== BQ_LAUNDRY
)
1354 bp
->b_timestamp
= 0;
1358 * Associate a buffer with a vnode.
1359 * buf_mtxp must be locked on entry
1362 bgetvp_locked(vnode_t vp
, buf_t bp
)
1366 panic("bgetvp_locked: not free");
1368 if (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
)
1369 bp
->b_dev
= vp
->v_rdev
;
1373 * Insert onto list for new vnode.
1375 bufinsvn(bp
, &vp
->v_cleanblkhd
);
1379 * Disassociate a buffer from a vnode.
1380 * buf_mtxp must be locked on entry
1383 brelvp_locked(buf_t bp
)
1386 * Delete from old vnode list, if on one.
1388 if (bp
->b_vnbufs
.le_next
!= NOLIST
)
1391 bp
->b_vp
= (vnode_t
)NULL
;
1395 * Reassign a buffer from one vnode to another.
1396 * Used to assign file specific control information
1397 * (indirect blocks) to the vnode to which they belong.
1400 buf_reassign(buf_t bp
, vnode_t newvp
)
1402 register struct buflists
*listheadp
;
1404 if (newvp
== NULL
) {
1405 printf("buf_reassign: NULL");
1408 lck_mtx_lock_spin(buf_mtxp
);
1411 * Delete from old vnode list, if on one.
1413 if (bp
->b_vnbufs
.le_next
!= NOLIST
)
1416 * If dirty, put on list of dirty buffers;
1417 * otherwise insert onto list of clean buffers.
1419 if (ISSET(bp
->b_flags
, B_DELWRI
))
1420 listheadp
= &newvp
->v_dirtyblkhd
;
1422 listheadp
= &newvp
->v_cleanblkhd
;
1423 bufinsvn(bp
, listheadp
);
1425 lck_mtx_unlock(buf_mtxp
);
1428 static __inline__
void
1429 bufhdrinit(buf_t bp
)
1431 bzero((char *)bp
, sizeof *bp
);
1433 bp
->b_rcred
= NOCRED
;
1434 bp
->b_wcred
= NOCRED
;
1435 bp
->b_vnbufs
.le_next
= NOLIST
;
1436 bp
->b_flags
= B_INVAL
;
1442 * Initialize buffers and hash links for buffers.
1444 __private_extern__
void
1452 /* Initialize the buffer queues ('freelists') and the hash table */
1453 for (dp
= bufqueues
; dp
< &bufqueues
[BQUEUES
]; dp
++)
1455 bufhashtbl
= hashinit(nbuf_hashelements
, M_CACHE
, &bufhash
);
1457 /* Initialize the buffer headers */
1458 for (i
= 0; i
< max_nbuf_headers
; i
++) {
1460 bp
= &buf_headers
[i
];
1464 dp
= &bufqueues
[BQ_EMPTY
];
1465 bp
->b_whichq
= BQ_EMPTY
;
1466 bp
->b_timestamp
= buf_timestamp();
1467 binsheadfree(bp
, dp
, BQ_EMPTY
);
1468 binshash(bp
, &invalhash
);
1471 boot_nbuf_headers
= nbuf_headers
;
1472 for (; i
< nbuf_headers
+ niobuf_headers
; i
++) {
1473 bp
= &buf_headers
[i
];
1476 binsheadfree(bp
, &iobufqueue
, -1);
1480 * allocate lock group attribute and group
1482 buf_mtx_grp_attr
= lck_grp_attr_alloc_init();
1483 buf_mtx_grp
= lck_grp_alloc_init("buffer cache", buf_mtx_grp_attr
);
1486 * allocate the lock attribute
1488 buf_mtx_attr
= lck_attr_alloc_init();
1491 * allocate and initialize mutex's for the buffer and iobuffer pools
1493 buf_mtxp
= lck_mtx_alloc_init(buf_mtx_grp
, buf_mtx_attr
);
1494 iobuffer_mtxp
= lck_mtx_alloc_init(buf_mtx_grp
, buf_mtx_attr
);
1496 if (iobuffer_mtxp
== NULL
)
1497 panic("couldn't create iobuffer mutex");
1499 if (buf_mtxp
== NULL
)
1500 panic("couldn't create buf mutex");
1503 * allocate and initialize cluster specific global locks...
1507 printf("using %d buffer headers and %d cluster IO buffer headers\n",
1508 nbuf_headers
, niobuf_headers
);
1510 /* Set up zones used by the buffer cache */
1513 /* start the bcleanbuf() thread */
1514 bcleanbuf_thread_init();
1518 static void bufq_balance_thread_init(void) __attribute__((section("__TEXT, initcode")));
1519 /* create a thread to do dynamic buffer queue balancing */
1520 bufq_balance_thread_init();
1528 * Zones for the meta data buffers
1532 #define MAXMETA 8192
1534 struct meta_zone_entry
{
1538 const char *mz_name
;
1541 struct meta_zone_entry meta_zones
[] = {
1542 {NULL
, (MINMETA
* 1), 128 * (MINMETA
* 1), "buf.512" },
1543 {NULL
, (MINMETA
* 2), 64 * (MINMETA
* 2), "buf.1024" },
1544 {NULL
, (MINMETA
* 4), 16 * (MINMETA
* 4), "buf.2048" },
1545 {NULL
, (MINMETA
* 8), 512 * (MINMETA
* 8), "buf.4096" },
1546 {NULL
, (MINMETA
* 16), 512 * (MINMETA
* 16), "buf.8192" },
1547 {NULL
, 0, 0, "" } /* End */
1551 * Initialize the meta data zones
1558 for (i
= 0; meta_zones
[i
].mz_size
!= 0; i
++) {
1559 meta_zones
[i
].mz_zone
=
1560 zinit(meta_zones
[i
].mz_size
,
1561 meta_zones
[i
].mz_max
,
1563 meta_zones
[i
].mz_name
);
1565 buf_hdr_zone
= zinit(sizeof(struct buf
), 32, PAGE_SIZE
, "buf headers");
1568 static __inline__ zone_t
1569 getbufzone(size_t size
)
1573 if ((size
% 512) || (size
< MINMETA
) || (size
> MAXMETA
))
1574 panic("getbufzone: incorect size = %lu", size
);
1576 for (i
= 0; meta_zones
[i
].mz_size
!= 0; i
++) {
1577 if (meta_zones
[i
].mz_size
>= size
)
1581 return (meta_zones
[i
].mz_zone
);
1587 bio_doread(vnode_t vp
, daddr64_t blkno
, int size
, ucred_t cred
, int async
, int queuetype
)
1591 bp
= buf_getblk(vp
, blkno
, size
, 0, 0, queuetype
);
1594 * If buffer does not have data valid, start a read.
1595 * Note that if buffer is B_INVAL, buf_getblk() won't return it.
1596 * Therefore, it's valid if it's I/O has completed or been delayed.
1598 if (!ISSET(bp
->b_flags
, (B_DONE
| B_DELWRI
))) {
1603 /* Start I/O for the buffer (keeping credentials). */
1604 SET(bp
->b_flags
, B_READ
| async
);
1605 if (IS_VALID_CRED(cred
) && !IS_VALID_CRED(bp
->b_rcred
)) {
1606 kauth_cred_ref(cred
);
1612 trace(TR_BREADMISS
, pack(vp
, size
), blkno
);
1614 /* Pay for the read. */
1615 if (p
&& p
->p_stats
)
1616 OSIncrementAtomic(&p
->p_stats
->p_ru
.ru_inblock
); /* XXX */
1620 * since we asked for an ASYNC I/O
1621 * the biodone will do the brelse
1622 * we don't want to pass back a bp
1623 * that we don't 'own'
1632 trace(TR_BREADHIT
, pack(vp
, size
), blkno
);
1638 * Perform the reads for buf_breadn() and buf_meta_breadn().
1639 * Trivial modification to the breada algorithm presented in Bach (p.55).
1642 do_breadn_for_type(vnode_t vp
, daddr64_t blkno
, int size
, daddr64_t
*rablks
, int *rasizes
,
1643 int nrablks
, ucred_t cred
, buf_t
*bpp
, int queuetype
)
1648 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, queuetype
);
1651 * For each of the read-ahead blocks, start a read, if necessary.
1653 for (i
= 0; i
< nrablks
; i
++) {
1654 /* If it's in the cache, just go on to next one. */
1655 if (incore(vp
, rablks
[i
]))
1658 /* Get a buffer for the read-ahead block */
1659 (void) bio_doread(vp
, rablks
[i
], rasizes
[i
], cred
, B_ASYNC
, queuetype
);
1662 /* Otherwise, we had to start a read for it; wait until it's valid. */
1663 return (buf_biowait(bp
));
1668 * Read a disk block.
1669 * This algorithm described in Bach (p.54).
1672 buf_bread(vnode_t vp
, daddr64_t blkno
, int size
, ucred_t cred
, buf_t
*bpp
)
1676 /* Get buffer for block. */
1677 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, BLK_READ
);
1679 /* Wait for the read to complete, and return result. */
1680 return (buf_biowait(bp
));
1684 * Read a disk block. [bread() for meta-data]
1685 * This algorithm described in Bach (p.54).
1688 buf_meta_bread(vnode_t vp
, daddr64_t blkno
, int size
, ucred_t cred
, buf_t
*bpp
)
1692 /* Get buffer for block. */
1693 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, BLK_META
);
1695 /* Wait for the read to complete, and return result. */
1696 return (buf_biowait(bp
));
1700 * Read-ahead multiple disk blocks. The first is sync, the rest async.
1703 buf_breadn(vnode_t vp
, daddr64_t blkno
, int size
, daddr64_t
*rablks
, int *rasizes
, int nrablks
, ucred_t cred
, buf_t
*bpp
)
1705 return (do_breadn_for_type(vp
, blkno
, size
, rablks
, rasizes
, nrablks
, cred
, bpp
, BLK_READ
));
1709 * Read-ahead multiple disk blocks. The first is sync, the rest async.
1710 * [buf_breadn() for meta-data]
1713 buf_meta_breadn(vnode_t vp
, daddr64_t blkno
, int size
, daddr64_t
*rablks
, int *rasizes
, int nrablks
, ucred_t cred
, buf_t
*bpp
)
1715 return (do_breadn_for_type(vp
, blkno
, size
, rablks
, rasizes
, nrablks
, cred
, bpp
, BLK_META
));
1719 * Block write. Described in Bach (p.56)
1722 buf_bwrite(buf_t bp
)
1724 int sync
, wasdelayed
;
1726 proc_t p
= current_proc();
1727 vnode_t vp
= bp
->b_vp
;
1729 if (bp
->b_datap
== 0) {
1730 if (brecover_data(bp
) == 0)
1733 /* Remember buffer type, to switch on it later. */
1734 sync
= !ISSET(bp
->b_flags
, B_ASYNC
);
1735 wasdelayed
= ISSET(bp
->b_flags
, B_DELWRI
);
1736 CLR(bp
->b_flags
, (B_READ
| B_DONE
| B_ERROR
| B_DELWRI
));
1739 OSAddAtomic(-1, &nbdwrite
);
1743 * If not synchronous, pay for the I/O operation and make
1744 * sure the buf is on the correct vnode queue. We have
1745 * to do this now, because if we don't, the vnode may not
1746 * be properly notified that its I/O has completed.
1749 buf_reassign(bp
, vp
);
1751 if (p
&& p
->p_stats
)
1752 OSIncrementAtomic(&p
->p_stats
->p_ru
.ru_oublock
); /* XXX */
1754 trace(TR_BUFWRITE
, pack(vp
, bp
->b_bcount
), bp
->b_lblkno
);
1756 /* Initiate disk write. Make sure the appropriate party is charged. */
1758 OSAddAtomic(1, &vp
->v_numoutput
);
1764 * If I/O was synchronous, wait for it to complete.
1766 rv
= buf_biowait(bp
);
1769 * Pay for the I/O operation, if it's not been paid for, and
1770 * make sure it's on the correct vnode queue. (async operatings
1771 * were payed for above.)
1774 buf_reassign(bp
, vp
);
1776 if (p
&& p
->p_stats
)
1777 OSIncrementAtomic(&p
->p_stats
->p_ru
.ru_oublock
); /* XXX */
1779 /* Release the buffer. */
1780 // XXXdbg - only if the unused bit is set
1781 if (!ISSET(bp
->b_flags
, B_NORELSE
)) {
1784 CLR(bp
->b_flags
, B_NORELSE
);
1794 vn_bwrite(struct vnop_bwrite_args
*ap
)
1796 return (buf_bwrite(ap
->a_bp
));
1802 * The buffer is marked dirty, but is not queued for I/O.
1803 * This routine should be used when the buffer is expected
1804 * to be modified again soon, typically a small write that
1805 * partially fills a buffer.
1807 * NB: magnetic tapes cannot be delayed; they must be
1808 * written in the order that the writes are requested.
1810 * Described in Leffler, et al. (pp. 208-213).
1812 * Note: With the abilitty to allocate additional buffer
1813 * headers, we can get in to the situation where "too" many
1814 * buf_bdwrite()s can create situation where the kernel can create
1815 * buffers faster than the disks can service. Doing a buf_bawrite() in
1816 * cases were we have "too many" outstanding buf_bdwrite()s avoids that.
1818 __private_extern__
int
1819 bdwrite_internal(buf_t bp
, int return_error
)
1821 proc_t p
= current_proc();
1822 vnode_t vp
= bp
->b_vp
;
1825 * If the block hasn't been seen before:
1826 * (1) Mark it as having been seen,
1827 * (2) Charge for the write.
1828 * (3) Make sure it's on its vnode's correct block list,
1830 if (!ISSET(bp
->b_flags
, B_DELWRI
)) {
1831 SET(bp
->b_flags
, B_DELWRI
);
1832 if (p
&& p
->p_stats
)
1833 OSIncrementAtomic(&p
->p_stats
->p_ru
.ru_oublock
); /* XXX */
1834 OSAddAtomic(1, &nbdwrite
);
1835 buf_reassign(bp
, vp
);
1838 /* If this is a tape block, write it the block now. */
1839 if (ISSET(bp
->b_flags
, B_TAPE
)) {
1845 * if we're not LOCKED, but the total number of delayed writes
1846 * has climbed above 75% of the total buffers in the system
1847 * return an error if the caller has indicated that it can
1848 * handle one in this case, otherwise schedule the I/O now
1849 * this is done to prevent us from allocating tons of extra
1850 * buffers when dealing with virtual disks (i.e. DiskImages),
1851 * because additional buffers are dynamically allocated to prevent
1852 * deadlocks from occurring
1854 * however, can't do a buf_bawrite() if the LOCKED bit is set because the
1855 * buffer is part of a transaction and can't go to disk until
1856 * the LOCKED bit is cleared.
1858 if (!ISSET(bp
->b_flags
, B_LOCKED
) && nbdwrite
> ((nbuf_headers
/4)*3)) {
1862 * If the vnode has "too many" write operations in progress
1863 * wait for them to finish the IO
1865 (void)vnode_waitforwrites(vp
, VNODE_ASYNC_THROTTLE
, 0, 0, "buf_bdwrite");
1867 return (buf_bawrite(bp
));
1870 /* Otherwise, the "write" is done, so mark and release the buffer. */
1871 SET(bp
->b_flags
, B_DONE
);
1877 buf_bdwrite(buf_t bp
)
1879 return (bdwrite_internal(bp
, 0));
1884 * Asynchronous block write; just an asynchronous buf_bwrite().
1886 * Note: With the abilitty to allocate additional buffer
1887 * headers, we can get in to the situation where "too" many
1888 * buf_bawrite()s can create situation where the kernel can create
1889 * buffers faster than the disks can service.
1890 * We limit the number of "in flight" writes a vnode can have to
1894 bawrite_internal(buf_t bp
, int throttle
)
1896 vnode_t vp
= bp
->b_vp
;
1901 * If the vnode has "too many" write operations in progress
1902 * wait for them to finish the IO
1904 (void)vnode_waitforwrites(vp
, VNODE_ASYNC_THROTTLE
, 0, 0, (const char *)"buf_bawrite");
1905 else if (vp
->v_numoutput
>= VNODE_ASYNC_THROTTLE
)
1907 * return to the caller and
1908 * let him decide what to do
1910 return (EWOULDBLOCK
);
1912 SET(bp
->b_flags
, B_ASYNC
);
1914 return (VNOP_BWRITE(bp
));
1918 buf_bawrite(buf_t bp
)
1920 return (bawrite_internal(bp
, 1));
1925 * Release a buffer on to the free lists.
1926 * Described in Bach (p. 46).
1929 buf_brelse(buf_t bp
)
1931 struct bqueues
*bufq
;
1934 int need_wakeup
= 0;
1935 int need_bp_wakeup
= 0;
1938 if (bp
->b_whichq
!= -1 || !(bp
->b_lflags
& BL_BUSY
))
1939 panic("buf_brelse: bad buffer = %p\n", bp
);
1942 bp
->b_stackbrelse
[0] = (int)__builtin_return_address(0);
1943 bp
->b_stackbrelse
[1] = (int)__builtin_return_address(1);
1944 bp
->b_stackbrelse
[2] = (int)__builtin_return_address(2);
1945 bp
->b_stackbrelse
[3] = (int)__builtin_return_address(3);
1946 bp
->b_stackbrelse
[4] = (int)__builtin_return_address(4);
1947 bp
->b_stackbrelse
[5] = (int)__builtin_return_address(5);
1949 bp
->b_lastbrelse
= current_thread();
1952 if (bp
->b_lflags
& BL_IOBUF
) {
1957 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 388)) | DBG_FUNC_START
,
1958 bp
->b_lblkno
* PAGE_SIZE
, (int)bp
, (int)bp
->b_datap
,
1961 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
1964 * if we're invalidating a buffer that has the B_FILTER bit
1965 * set then call the b_iodone function so it gets cleaned
1968 * the HFS journal code depends on this
1970 if (ISSET(bp
->b_flags
, B_META
) && ISSET(bp
->b_flags
, B_INVAL
)) {
1971 if (ISSET(bp
->b_flags
, B_FILTER
)) { /* if necessary, call out */
1972 void (*iodone_func
)(struct buf
*, void *) = bp
->b_iodone
;
1973 void *arg
= (void *)bp
->b_transaction
;
1975 CLR(bp
->b_flags
, B_FILTER
); /* but note callout done */
1976 bp
->b_iodone
= NULL
;
1977 bp
->b_transaction
= NULL
;
1979 if (iodone_func
== NULL
) {
1980 panic("brelse: bp @ %p has NULL b_iodone!\n", bp
);
1982 (*iodone_func
)(bp
, arg
);
1986 * I/O is done. Cleanup the UPL state
1990 if ( !ISSET(bp
->b_flags
, B_META
) && UBCINFOEXISTS(bp
->b_vp
) && bp
->b_bufsize
) {
1994 if ( (upl
== NULL
) ) {
1995 if ( !ISSET(bp
->b_flags
, B_INVAL
)) {
1996 kret
= ubc_create_upl(bp
->b_vp
,
1997 ubc_blktooff(bp
->b_vp
, bp
->b_lblkno
),
2003 if (kret
!= KERN_SUCCESS
)
2004 panic("brelse: Failed to create UPL");
2006 upl_ubc_alias_set(upl
, bp
, 5);
2007 #endif /* UPL_DEBUG */
2011 kret
= ubc_upl_unmap(upl
);
2013 if (kret
!= KERN_SUCCESS
)
2014 panic("ubc_upl_unmap failed");
2015 bp
->b_datap
= (uintptr_t)NULL
;
2019 if (bp
->b_flags
& (B_ERROR
| B_INVAL
)) {
2020 if (bp
->b_flags
& (B_READ
| B_INVAL
))
2021 upl_flags
= UPL_ABORT_DUMP_PAGES
;
2025 ubc_upl_abort(upl
, upl_flags
);
2027 if (ISSET(bp
->b_flags
, B_DELWRI
| B_WASDIRTY
))
2028 upl_flags
= UPL_COMMIT_SET_DIRTY
;
2030 upl_flags
= UPL_COMMIT_CLEAR_DIRTY
;
2032 ubc_upl_commit_range(upl
, 0, bp
->b_bufsize
, upl_flags
|
2033 UPL_COMMIT_INACTIVATE
| UPL_COMMIT_FREE_ON_EMPTY
);
2039 panic("brelse: UPL set for non VREG; vp=%p", bp
->b_vp
);
2043 * If it's locked, don't report an error; try again later.
2045 if (ISSET(bp
->b_flags
, (B_LOCKED
|B_ERROR
)) == (B_LOCKED
|B_ERROR
))
2046 CLR(bp
->b_flags
, B_ERROR
);
2048 * If it's not cacheable, or an error, mark it invalid.
2050 if (ISSET(bp
->b_flags
, (B_NOCACHE
|B_ERROR
)))
2051 SET(bp
->b_flags
, B_INVAL
);
2053 if ((bp
->b_bufsize
<= 0) || ISSET(bp
->b_flags
, B_INVAL
)) {
2055 * If it's invalid or empty, dissociate it from its vnode,
2056 * release its storage if B_META, and
2057 * clean it up a bit and put it on the EMPTY queue
2059 if (ISSET(bp
->b_flags
, B_DELWRI
))
2060 OSAddAtomic(-1, &nbdwrite
);
2062 if (ISSET(bp
->b_flags
, B_META
)) {
2063 if (bp
->b_bufsize
) {
2064 if (ISSET(bp
->b_flags
, B_ZALLOC
)) {
2067 z
= getbufzone(bp
->b_bufsize
);
2068 zfree(z
, (void *)bp
->b_datap
);
2070 kmem_free(kernel_map
, bp
->b_datap
, bp
->b_bufsize
);
2072 bp
->b_datap
= (uintptr_t)NULL
;
2077 * nuke any credentials we were holding
2079 if (IS_VALID_CRED(bp
->b_rcred
)) {
2080 kauth_cred_unref(&bp
->b_rcred
);
2082 if (IS_VALID_CRED(bp
->b_wcred
)) {
2083 kauth_cred_unref(&bp
->b_wcred
);
2085 CLR(bp
->b_flags
, (B_META
| B_ZALLOC
| B_DELWRI
| B_LOCKED
| B_AGE
| B_ASYNC
| B_NOCACHE
| B_FUA
));
2087 bufq
= &bufqueues
[BQ_EMPTY
];
2088 bp
->b_whichq
= BQ_EMPTY
;
2090 lck_mtx_lock_spin(buf_mtxp
);
2097 binshash(bp
, &invalhash
);
2099 binsheadfree(bp
, bufq
, BQ_EMPTY
);
2102 * It has valid data. Put it on the end of the appropriate
2103 * queue, so that it'll stick around for as long as possible.
2105 if (ISSET(bp
->b_flags
, B_LOCKED
))
2106 whichq
= BQ_LOCKED
; /* locked in core */
2107 else if (ISSET(bp
->b_flags
, B_META
))
2108 whichq
= BQ_META
; /* meta-data */
2109 else if (ISSET(bp
->b_flags
, B_AGE
))
2110 whichq
= BQ_AGE
; /* stale but valid data */
2112 whichq
= BQ_LRU
; /* valid data */
2113 bufq
= &bufqueues
[whichq
];
2115 CLR(bp
->b_flags
, (B_AGE
| B_ASYNC
| B_NOCACHE
));
2116 bp
->b_whichq
= whichq
;
2117 bp
->b_timestamp
= buf_timestamp();
2119 lck_mtx_lock_spin(buf_mtxp
);
2121 binstailfree(bp
, bufq
, whichq
);
2125 * needbuffer is a global
2126 * we're currently using buf_mtxp to protect it
2127 * delay doing the actual wakeup until after
2133 if (ISSET(bp
->b_lflags
, BL_WANTED
)) {
2135 * delay the actual wakeup until after we
2136 * clear BL_BUSY and we've dropped buf_mtxp
2141 * Unlock the buffer.
2143 CLR(bp
->b_lflags
, (BL_BUSY
| BL_WANTED
));
2145 lck_mtx_unlock(buf_mtxp
);
2149 * Wake up any processes waiting for any buffer to become free.
2151 wakeup(&needbuffer
);
2153 if (need_bp_wakeup
) {
2155 * Wake up any proceeses waiting for _this_ buffer to become free.
2159 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 388)) | DBG_FUNC_END
,
2160 (int)bp
, (int)bp
->b_datap
, bp
->b_flags
, 0, 0);
2164 * Determine if a block is in the cache.
2165 * Just look on what would be its hash chain. If it's there, return
2166 * a pointer to it, unless it's marked invalid. If it's marked invalid,
2167 * we normally don't return the buffer, unless the caller explicitly
2171 incore(vnode_t vp
, daddr64_t blkno
)
2174 struct bufhashhdr
*dp
;
2176 dp
= BUFHASH(vp
, blkno
);
2178 lck_mtx_lock_spin(buf_mtxp
);
2180 if (incore_locked(vp
, blkno
, dp
))
2184 lck_mtx_unlock(buf_mtxp
);
2191 incore_locked(vnode_t vp
, daddr64_t blkno
, struct bufhashhdr
*dp
)
2195 /* Search hash chain */
2196 for (bp
= dp
->lh_first
; bp
!= NULL
; bp
= bp
->b_hash
.le_next
) {
2197 if (bp
->b_lblkno
== blkno
&& bp
->b_vp
== vp
&&
2198 !ISSET(bp
->b_flags
, B_INVAL
)) {
2206 /* XXX FIXME -- Update the comment to reflect the UBC changes (please) -- */
2208 * Get a block of requested size that is associated with
2209 * a given vnode and block offset. If it is found in the
2210 * block cache, mark it as having been found, make it busy
2211 * and return it. Otherwise, return an empty block of the
2212 * correct size. It is up to the caller to insure that the
2213 * cached blocks be of the correct size.
2216 buf_getblk(vnode_t vp
, daddr64_t blkno
, int size
, int slpflag
, int slptimeo
, int operation
)
2221 upl_page_info_t
*pl
;
2226 struct bufhashhdr
*dp
;
2228 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_START
,
2229 (int)(blkno
* PAGE_SIZE
), size
, operation
, 0, 0);
2231 ret_only_valid
= operation
& BLK_ONLYVALID
;
2232 operation
&= ~BLK_ONLYVALID
;
2233 dp
= BUFHASH(vp
, blkno
);
2235 lck_mtx_lock_spin(buf_mtxp
);
2237 if ((bp
= incore_locked(vp
, blkno
, dp
))) {
2239 * Found in the Buffer Cache
2241 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
2245 switch (operation
) {
2249 SET(bp
->b_lflags
, BL_WANTED
);
2250 bufstats
.bufs_busyincore
++;
2252 lck_mtx_convert_spin(buf_mtxp
);
2254 * don't retake the mutex after being awakened...
2255 * the time out is in msecs
2257 ts
.tv_sec
= (slptimeo
/1000);
2258 ts
.tv_nsec
= (slptimeo
% 1000) * 10 * NSEC_PER_USEC
* 1000;
2260 err
= msleep(bp
, buf_mtxp
, slpflag
| PDROP
| (PRIBIO
+ 1), "buf_getblk", &ts
);
2263 * Callers who call with PCATCH or timeout are
2264 * willing to deal with the NULL pointer
2266 if (err
&& ((slpflag
& PCATCH
) || ((err
== EWOULDBLOCK
) && slptimeo
)))
2274 * unknown operation requested
2276 panic("getblk: paging or unknown operation for incore busy buffer - %x\n", operation
);
2282 * buffer in core and not busy
2284 SET(bp
->b_lflags
, BL_BUSY
);
2285 SET(bp
->b_flags
, B_CACHE
);
2287 bremfree_locked(bp
);
2288 bufstats
.bufs_incore
++;
2290 lck_mtx_unlock(buf_mtxp
);
2292 bp
->b_owner
= current_thread();
2296 panic("buffer has UPL, but not marked BUSY: %p", bp
);
2298 if ( !ret_only_valid
&& bp
->b_bufsize
!= size
)
2302 switch (operation
) {
2305 * "write" operation: let the UPL subsystem
2306 * know that we intend to modify the buffer
2307 * cache pages we're gathering.
2309 upl_flags
|= UPL_WILL_MODIFY
;
2311 upl_flags
|= UPL_PRECIOUS
;
2312 if (UBCINFOEXISTS(bp
->b_vp
) && bp
->b_bufsize
) {
2313 kret
= ubc_create_upl(vp
,
2314 ubc_blktooff(vp
, bp
->b_lblkno
),
2319 if (kret
!= KERN_SUCCESS
)
2320 panic("Failed to create UPL");
2324 if (upl_valid_page(pl
, 0)) {
2325 if (upl_dirty_page(pl
, 0))
2326 SET(bp
->b_flags
, B_WASDIRTY
);
2328 CLR(bp
->b_flags
, B_WASDIRTY
);
2330 CLR(bp
->b_flags
, (B_DONE
| B_CACHE
| B_WASDIRTY
| B_DELWRI
));
2332 kret
= ubc_upl_map(upl
, (vm_address_t
*)&(bp
->b_datap
));
2334 if (kret
!= KERN_SUCCESS
)
2335 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
2341 * VM is not involved in IO for the meta data
2342 * buffer already has valid data
2347 panic("getblk: paging or unknown operation for incore buffer- %d\n", operation
);
2352 } else { /* not incore() */
2353 int queue
= BQ_EMPTY
; /* Start with no preference */
2355 if (ret_only_valid
) {
2356 lck_mtx_unlock(buf_mtxp
);
2359 lck_mtx_convert_spin(buf_mtxp
);
2361 if ((vnode_isreg(vp
) == 0) || (UBCINFOEXISTS(vp
) == 0) /*|| (vnode_issystem(vp) == 1)*/)
2362 operation
= BLK_META
;
2364 if ((bp
= getnewbuf(slpflag
, slptimeo
, &queue
)) == NULL
)
2368 * getnewbuf may block for a number of different reasons...
2369 * if it does, it's then possible for someone else to
2370 * create a buffer for the same block and insert it into
2371 * the hash... if we see it incore at this point we dump
2372 * the buffer we were working on and start over
2374 if (incore_locked(vp
, blkno
, dp
)) {
2375 SET(bp
->b_flags
, B_INVAL
);
2376 binshash(bp
, &invalhash
);
2378 lck_mtx_unlock(buf_mtxp
);
2384 * NOTE: YOU CAN NOT BLOCK UNTIL binshash() HAS BEEN
2385 * CALLED! BE CAREFUL.
2389 * mark the buffer as B_META if indicated
2390 * so that when buffer is released it will goto META queue
2392 if (operation
== BLK_META
)
2393 SET(bp
->b_flags
, B_META
);
2395 bp
->b_blkno
= bp
->b_lblkno
= blkno
;
2399 * Insert in the hash so that incore() can find it
2401 binshash(bp
, BUFHASH(vp
, blkno
));
2403 bgetvp_locked(vp
, bp
);
2405 lck_mtx_unlock(buf_mtxp
);
2410 switch (operation
) {
2413 * buffer data is invalid...
2415 * I don't want to have to retake buf_mtxp,
2416 * so the miss and vmhits counters are done
2417 * with Atomic updates... all other counters
2418 * in bufstats are protected with either
2419 * buf_mtxp or iobuffer_mtxp
2421 OSAddAtomic(1, &bufstats
.bufs_miss
);
2426 * "write" operation: let the UPL subsystem know
2427 * that we intend to modify the buffer cache pages
2430 upl_flags
|= UPL_WILL_MODIFY
;
2433 size_t contig_bytes
;
2437 panic("bp already has UPL: %p",bp
);
2439 f_offset
= ubc_blktooff(vp
, blkno
);
2441 upl_flags
|= UPL_PRECIOUS
;
2442 kret
= ubc_create_upl(vp
,
2449 if (kret
!= KERN_SUCCESS
)
2450 panic("Failed to create UPL");
2452 upl_ubc_alias_set(upl
, bp
, 4);
2453 #endif /* UPL_DEBUG */
2456 if (upl_valid_page(pl
, 0)) {
2458 if (operation
== BLK_READ
)
2459 bmap_flags
= VNODE_READ
;
2461 bmap_flags
= VNODE_WRITE
;
2463 SET(bp
->b_flags
, B_CACHE
| B_DONE
);
2465 OSAddAtomic(1, &bufstats
.bufs_vmhits
);
2470 if (upl_dirty_page(pl
, 0)) {
2472 SET(bp
->b_flags
, B_WASDIRTY
);
2474 bp
->b_validend
= bp
->b_bcount
;
2475 bp
->b_dirtyend
= bp
->b_bcount
;
2478 bp
->b_validend
= bp
->b_bcount
;
2482 * try to recreate the physical block number associated with
2485 if (VNOP_BLOCKMAP(vp
, f_offset
, bp
->b_bcount
, &bp
->b_blkno
, &contig_bytes
, NULL
, bmap_flags
, NULL
))
2486 panic("getblk: VNOP_BLOCKMAP failed");
2488 * if the extent represented by this buffer
2489 * is not completely physically contiguous on
2490 * disk, than we can't cache the physical mapping
2491 * in the buffer header
2493 if ((long)contig_bytes
< bp
->b_bcount
)
2494 bp
->b_blkno
= bp
->b_lblkno
;
2496 OSAddAtomic(1, &bufstats
.bufs_miss
);
2498 kret
= ubc_upl_map(upl
, (vm_address_t
*)&(bp
->b_datap
));
2500 if (kret
!= KERN_SUCCESS
)
2501 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
2505 panic("getblk: paging or unknown operation - %x", operation
);
2510 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_END
,
2511 (int)bp
, (int)bp
->b_datap
, bp
->b_flags
, 3, 0);
2514 bp
->b_stackgetblk
[0] = (int)__builtin_return_address(0);
2515 bp
->b_stackgetblk
[1] = (int)__builtin_return_address(1);
2516 bp
->b_stackgetblk
[2] = (int)__builtin_return_address(2);
2517 bp
->b_stackgetblk
[3] = (int)__builtin_return_address(3);
2518 bp
->b_stackgetblk
[4] = (int)__builtin_return_address(4);
2519 bp
->b_stackgetblk
[5] = (int)__builtin_return_address(5);
2525 * Get an empty, disassociated buffer of given size.
2528 buf_geteblk(int size
)
2531 int queue
= BQ_EMPTY
;
2533 lck_mtx_lock(buf_mtxp
);
2535 while ((bp
= getnewbuf(0, 0, &queue
)) == 0)
2537 SET(bp
->b_flags
, (B_META
|B_INVAL
));
2540 assert(queue
== BQ_EMPTY
);
2541 #endif /* DIAGNOSTIC */
2542 /* XXX need to implement logic to deal with other queues */
2544 binshash(bp
, &invalhash
);
2545 bufstats
.bufs_eblk
++;
2547 lck_mtx_unlock(buf_mtxp
);
2556 * With UBC, there is no need to expand / shrink the file data
2557 * buffer. The VM uses the same pages, hence no waste.
2558 * All the file data buffers can have one size.
2559 * In fact expand / shrink would be an expensive operation.
2561 * Only exception to this is meta-data buffers. Most of the
2562 * meta data operations are smaller than PAGE_SIZE. Having the
2563 * meta-data buffers grow and shrink as needed, optimizes use
2564 * of the kernel wired memory.
2568 allocbuf(buf_t bp
, int size
)
2570 vm_size_t desired_size
;
2572 desired_size
= roundup(size
, CLBYTES
);
2574 if (desired_size
< PAGE_SIZE
)
2575 desired_size
= PAGE_SIZE
;
2576 if (desired_size
> MAXBSIZE
)
2577 panic("allocbuf: buffer larger than MAXBSIZE requested");
2579 if (ISSET(bp
->b_flags
, B_META
)) {
2581 int nsize
= roundup(size
, MINMETA
);
2584 vm_offset_t elem
= (vm_offset_t
)bp
->b_datap
;
2586 if (ISSET(bp
->b_flags
, B_ZALLOC
)) {
2587 if (bp
->b_bufsize
< nsize
) {
2588 /* reallocate to a bigger size */
2590 zprev
= getbufzone(bp
->b_bufsize
);
2591 if (nsize
<= MAXMETA
) {
2592 desired_size
= nsize
;
2593 z
= getbufzone(nsize
);
2594 /* b_datap not really a ptr */
2595 *(void **)(&bp
->b_datap
) = zalloc(z
);
2597 bp
->b_datap
= (uintptr_t)NULL
;
2598 kmem_alloc_wired(kernel_map
, (vm_offset_t
*)&bp
->b_datap
, desired_size
);
2599 CLR(bp
->b_flags
, B_ZALLOC
);
2601 bcopy((void *)elem
, (caddr_t
)bp
->b_datap
, bp
->b_bufsize
);
2602 zfree(zprev
, (void *)elem
);
2604 desired_size
= bp
->b_bufsize
;
2608 if ((vm_size_t
)bp
->b_bufsize
< desired_size
) {
2609 /* reallocate to a bigger size */
2610 bp
->b_datap
= (uintptr_t)NULL
;
2611 kmem_alloc_wired(kernel_map
, (vm_offset_t
*)&bp
->b_datap
, desired_size
);
2612 bcopy((const void *)elem
, (caddr_t
)bp
->b_datap
, bp
->b_bufsize
);
2613 kmem_free(kernel_map
, elem
, bp
->b_bufsize
);
2615 desired_size
= bp
->b_bufsize
;
2619 /* new allocation */
2620 if (nsize
<= MAXMETA
) {
2621 desired_size
= nsize
;
2622 z
= getbufzone(nsize
);
2623 /* b_datap not really a ptr */
2624 *(void **)(&bp
->b_datap
) = zalloc(z
);
2625 SET(bp
->b_flags
, B_ZALLOC
);
2627 kmem_alloc_wired(kernel_map
, (vm_offset_t
*)&bp
->b_datap
, desired_size
);
2630 if (bp
->b_datap
== 0)
2631 panic("allocbuf: NULL b_datap");
2633 bp
->b_bufsize
= desired_size
;
2634 bp
->b_bcount
= size
;
2640 * Get a new buffer from one of the free lists.
2642 * Request for a queue is passes in. The queue from which the buffer was taken
2643 * from is returned. Out of range queue requests get BQ_EMPTY. Request for
2644 * BQUEUE means no preference. Use heuristics in that case.
2645 * Heuristics is as follows:
2646 * Try BQ_AGE, BQ_LRU, BQ_EMPTY, BQ_META in that order.
2647 * If none available block till one is made available.
2648 * If buffers available on both BQ_AGE and BQ_LRU, check the timestamps.
2649 * Pick the most stale buffer.
2650 * If found buffer was marked delayed write, start the async. write
2651 * and restart the search.
2652 * Initialize the fields and disassociate the buffer from the vnode.
2653 * Remove the buffer from the hash. Return the buffer and the queue
2654 * on which it was found.
2656 * buf_mtxp is held upon entry
2657 * returns with buf_mtxp locked
2661 getnewbuf(int slpflag
, int slptimeo
, int * queue
)
2667 int age_time
, lru_time
, bp_time
, meta_time
;
2668 int req
= *queue
; /* save it for restarts */
2673 * invalid request gets empty queue
2675 if ((*queue
>= BQUEUES
) || (*queue
< 0)
2676 || (*queue
== BQ_LAUNDRY
) || (*queue
== BQ_LOCKED
))
2680 if (*queue
== BQ_EMPTY
&& (bp
= bufqueues
[*queue
].tqh_first
))
2684 * need to grow number of bufs, add another one rather than recycling
2686 if (nbuf_headers
< max_nbuf_headers
) {
2688 * Increment count now as lock
2689 * is dropped for allocation.
2690 * That avoids over commits
2695 /* Try for the requested queue first */
2696 bp
= bufqueues
[*queue
].tqh_first
;
2700 /* Unable to use requested queue */
2701 age_bp
= bufqueues
[BQ_AGE
].tqh_first
;
2702 lru_bp
= bufqueues
[BQ_LRU
].tqh_first
;
2703 meta_bp
= bufqueues
[BQ_META
].tqh_first
;
2705 if (!age_bp
&& !lru_bp
&& !meta_bp
) {
2707 * Unavailble on AGE or LRU or META queues
2708 * Try the empty list first
2710 bp
= bufqueues
[BQ_EMPTY
].tqh_first
;
2716 * We have seen is this is hard to trigger.
2717 * This is an overcommit of nbufs but needed
2718 * in some scenarios with diskiamges
2722 lck_mtx_unlock(buf_mtxp
);
2724 /* Create a new temporary buffer header */
2725 bp
= (struct buf
*)zalloc(buf_hdr_zone
);
2729 bp
->b_whichq
= BQ_EMPTY
;
2730 bp
->b_timestamp
= buf_timestamp();
2732 SET(bp
->b_flags
, B_HDRALLOC
);
2735 lck_mtx_lock(buf_mtxp
);
2738 binshash(bp
, &invalhash
);
2739 binsheadfree(bp
, &bufqueues
[BQ_EMPTY
], BQ_EMPTY
);
2743 /* subtract already accounted bufcount */
2746 bufstats
.bufs_sleeps
++;
2748 /* wait for a free buffer of any kind */
2750 /* hz value is 100 */
2751 ts
.tv_sec
= (slptimeo
/1000);
2752 /* the hz value is 100; which leads to 10ms */
2753 ts
.tv_nsec
= (slptimeo
% 1000) * NSEC_PER_USEC
* 1000 * 10;
2754 msleep(&needbuffer
, buf_mtxp
, slpflag
|(PRIBIO
+1), "getnewbuf", &ts
);
2758 /* Buffer available either on AGE or LRU or META */
2762 /* Buffer available either on AGE or LRU */
2766 } else if (!lru_bp
) {
2769 } else { /* buffer available on both AGE and LRU */
2770 int t
= buf_timestamp();
2772 age_time
= t
- age_bp
->b_timestamp
;
2773 lru_time
= t
- lru_bp
->b_timestamp
;
2774 if ((age_time
< 0) || (lru_time
< 0)) { /* time set backwards */
2778 * we should probably re-timestamp eveything in the
2779 * queues at this point with the current time
2782 if ((lru_time
>= lru_is_stale
) && (age_time
< age_is_stale
)) {
2792 if (!bp
) { /* Neither on AGE nor on LRU */
2795 } else if (meta_bp
) {
2796 int t
= buf_timestamp();
2798 bp_time
= t
- bp
->b_timestamp
;
2799 meta_time
= t
- meta_bp
->b_timestamp
;
2801 if (!(bp_time
< 0) && !(meta_time
< 0)) {
2802 /* time not set backwards */
2804 bp_is_stale
= (*queue
== BQ_LRU
) ?
2805 lru_is_stale
: age_is_stale
;
2807 if ((meta_time
>= meta_is_stale
) &&
2808 (bp_time
< bp_is_stale
)) {
2815 if (ISSET(bp
->b_flags
, B_LOCKED
) || ISSET(bp
->b_lflags
, BL_BUSY
))
2816 panic("getnewbuf: bp @ %p is LOCKED or BUSY! (flags 0x%lx)\n", bp
, bp
->b_flags
);
2819 if (bcleanbuf(bp
)) {
2821 * moved to the laundry thread, buffer not ready
2832 * Returns 0 is buffer is ready to use,
2833 * Returns 1 if issued a buf_bawrite() to indicate
2834 * that the buffer is not ready.
2836 * buf_mtxp is held upon entry
2837 * returns with buf_mtxp locked
2842 /* Remove from the queue */
2843 bremfree_locked(bp
);
2846 bp
->b_owner
= current_thread();
2850 * If buffer was a delayed write, start the IO by queuing
2851 * it on the LAUNDRY queue, and return 1
2853 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
2854 bp
->b_whichq
= BQ_LAUNDRY
;
2855 bp
->b_timestamp
= buf_timestamp();
2856 binstailfree(bp
, &bufqueues
[BQ_LAUNDRY
], BQ_LAUNDRY
);
2859 lck_mtx_unlock(buf_mtxp
);
2861 wakeup(&bufqueues
[BQ_LAUNDRY
]);
2863 * and give it a chance to run
2865 (void)thread_block(THREAD_CONTINUE_NULL
);
2867 lck_mtx_lock(buf_mtxp
);
2872 bp
->b_owner
= current_thread();
2876 * Buffer is no longer on any free list... we own it
2878 SET(bp
->b_lflags
, BL_BUSY
);
2883 * disassociate us from our vnode, if we had one...
2888 lck_mtx_unlock(buf_mtxp
);
2892 if (ISSET(bp
->b_flags
, B_META
)) {
2895 elem
= (vm_offset_t
)bp
->b_datap
;
2896 bp
->b_datap
= (uintptr_t)0xdeadbeef;
2898 if (ISSET(bp
->b_flags
, B_ZALLOC
)) {
2901 z
= getbufzone(bp
->b_bufsize
);
2902 zfree(z
, (void *)elem
);
2904 kmem_free(kernel_map
, elem
, bp
->b_bufsize
);
2907 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
2909 /* clear out various other fields */
2911 bp
->b_datap
= (uintptr_t)NULL
;
2912 bp
->b_upl
= (void *)NULL
;
2914 * preserve the state of whether this buffer
2915 * was allocated on the fly or not...
2916 * the only other flag that should be set at
2917 * this point is BL_BUSY...
2920 bp
->b_owner
= current_thread();
2923 bp
->b_lflags
= BL_BUSY
;
2924 bp
->b_flags
= (bp
->b_flags
& B_HDRALLOC
);
2926 bp
->b_blkno
= bp
->b_lblkno
= 0;
2927 bp
->b_iodone
= NULL
;
2931 bp
->b_dirtyoff
= bp
->b_dirtyend
= 0;
2932 bp
->b_validoff
= bp
->b_validend
= 0;
2934 /* nuke any credentials we were holding */
2935 if (IS_VALID_CRED(bp
->b_rcred
)) {
2936 kauth_cred_unref(&bp
->b_rcred
);
2938 if (IS_VALID_CRED(bp
->b_wcred
)) {
2939 kauth_cred_unref(&bp
->b_wcred
);
2941 lck_mtx_lock(buf_mtxp
);
2949 buf_invalblkno(vnode_t vp
, daddr64_t lblkno
, int flags
)
2953 struct bufhashhdr
*dp
;
2955 dp
= BUFHASH(vp
, lblkno
);
2957 lck_mtx_lock(buf_mtxp
);
2959 if ((bp
= incore_locked(vp
, lblkno
, dp
)) == (struct buf
*)0) {
2960 lck_mtx_unlock(buf_mtxp
);
2963 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
2964 if ( !ISSET(flags
, BUF_WAIT
)) {
2965 lck_mtx_unlock(buf_mtxp
);
2968 SET(bp
->b_lflags
, BL_WANTED
);
2970 error
= msleep((caddr_t
)bp
, buf_mtxp
, (PRIBIO
+ 1), "buf_invalblkno", NULL
);
2973 lck_mtx_unlock(buf_mtxp
);
2978 bremfree_locked(bp
);
2979 SET(bp
->b_lflags
, BL_BUSY
);
2980 SET(bp
->b_flags
, B_INVAL
);
2982 bp
->b_owner
= current_thread();
2985 lck_mtx_unlock(buf_mtxp
);
2995 int need_wakeup
= 0;
2997 lck_mtx_lock_spin(buf_mtxp
);
2999 if (ISSET(bp
->b_lflags
, BL_WANTED
)) {
3001 * delay the actual wakeup until after we
3002 * clear BL_BUSY and we've dropped buf_mtxp
3007 bp
->b_owner
= current_thread();
3011 * Unlock the buffer.
3013 CLR(bp
->b_lflags
, (BL_BUSY
| BL_WANTED
));
3015 lck_mtx_unlock(buf_mtxp
);
3019 * Wake up any proceeses waiting for _this_ buffer to become free.
3027 buf_acquire(buf_t bp
, int flags
, int slpflag
, int slptimeo
) {
3030 lck_mtx_lock(buf_mtxp
);
3032 error
= buf_acquire_locked(bp
, flags
, slpflag
, slptimeo
);
3034 lck_mtx_unlock(buf_mtxp
);
3041 buf_acquire_locked(buf_t bp
, int flags
, int slpflag
, int slptimeo
)
3046 if (ISSET(bp
->b_flags
, B_LOCKED
)) {
3047 if ((flags
& BAC_SKIP_LOCKED
))
3050 if ((flags
& BAC_SKIP_NONLOCKED
))
3053 if (ISSET(bp
->b_lflags
, BL_BUSY
)) {
3055 * since the mutex_lock may block, the buffer
3056 * may become BUSY, so we need to
3057 * recheck for a NOWAIT request
3059 if (flags
& BAC_NOWAIT
)
3061 SET(bp
->b_lflags
, BL_WANTED
);
3063 /* the hz value is 100; which leads to 10ms */
3064 ts
.tv_sec
= (slptimeo
/100);
3065 ts
.tv_nsec
= (slptimeo
% 100) * 10 * NSEC_PER_USEC
* 1000;
3066 error
= msleep((caddr_t
)bp
, buf_mtxp
, slpflag
| (PRIBIO
+ 1), "buf_acquire", &ts
);
3072 if (flags
& BAC_REMOVE
)
3073 bremfree_locked(bp
);
3074 SET(bp
->b_lflags
, BL_BUSY
);
3076 bp
->b_owner
= current_thread();
3084 * Wait for operations on the buffer to complete.
3085 * When they do, extract and return the I/O's error value.
3088 buf_biowait(buf_t bp
)
3090 lck_mtx_lock(buf_mtxp
);
3092 DTRACE_IO1(wait__start
, buf_t
, bp
);
3093 while (!ISSET(bp
->b_flags
, B_DONE
))
3094 (void) msleep(bp
, buf_mtxp
, (PRIBIO
+1), "buf_biowait", NULL
);
3095 DTRACE_IO1(wait__done
, buf_t
, bp
);
3097 lck_mtx_unlock(buf_mtxp
);
3099 /* check for interruption of I/O (e.g. via NFS), then errors. */
3100 if (ISSET(bp
->b_flags
, B_EINTR
)) {
3101 CLR(bp
->b_flags
, B_EINTR
);
3103 } else if (ISSET(bp
->b_flags
, B_ERROR
))
3104 return (bp
->b_error
? bp
->b_error
: EIO
);
3110 * Wait for the callback operation on a B_CALL buffer to complete.
3113 buf_biowait_callback(buf_t bp
)
3115 lck_mtx_lock(buf_mtxp
);
3117 DTRACE_IO1(wait__start
, buf_t
, bp
);
3118 while (!ISSET(bp
->b_lflags
, BL_CALLDONE
))
3119 (void) msleep(bp
, buf_mtxp
, (PRIBIO
+1), "buf_biowait", NULL
);
3120 DTRACE_IO1(wait__done
, buf_t
, bp
);
3122 lck_mtx_unlock(buf_mtxp
);
3126 * Mark I/O complete on a buffer.
3128 * If a callback has been requested, e.g. the pageout
3129 * daemon, do so. Otherwise, awaken waiting processes.
3131 * [ Leffler, et al., says on p.247:
3132 * "This routine wakes up the blocked process, frees the buffer
3133 * for an asynchronous write, or, for a request by the pagedaemon
3134 * process, invokes a procedure specified in the buffer structure" ]
3136 * In real life, the pagedaemon (or other system processes) wants
3137 * to do async stuff to, and doesn't want the buffer buf_brelse()'d.
3138 * (for swap pager, that puts swap buffers on the free lists (!!!),
3139 * for the vn device, that puts malloc'd buffers on the free lists!)
3141 extern struct timeval priority_IO_timestamp_for_root
;
3142 extern int hard_throttle_on_root
;
3145 buf_biodone(buf_t bp
)
3147 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 387)) | DBG_FUNC_START
,
3148 (int)bp
, (int)bp
->b_datap
, bp
->b_flags
, 0, 0);
3150 if (ISSET(bp
->b_flags
, B_DONE
))
3151 panic("biodone already");
3153 if (ISSET(bp
->b_flags
, B_ERROR
)) {
3157 if (kdebug_enable
) {
3158 int code
= DKIO_DONE
;
3160 if (bp
->b_flags
& B_READ
)
3162 if (bp
->b_flags
& B_ASYNC
)
3165 if (bp
->b_flags
& B_META
)
3167 else if (bp
->b_flags
& B_PAGEIO
)
3168 code
|= DKIO_PAGING
;
3170 KERNEL_DEBUG_CONSTANT(FSDBG_CODE(DBG_DKRW
, code
) | DBG_FUNC_NONE
,
3171 (unsigned int)bp
, (unsigned int)bp
->b_vp
,
3172 bp
->b_resid
, bp
->b_error
, 0);
3174 if ((bp
->b_vp
!= NULLVP
) &&
3175 ((bp
->b_flags
& (B_PAGEIO
| B_READ
)) == (B_PAGEIO
| B_READ
)) &&
3176 (bp
->b_vp
->v_mount
->mnt_kern_flag
& MNTK_ROOTDEV
)) {
3177 microuptime(&priority_IO_timestamp_for_root
);
3178 hard_throttle_on_root
= 0;
3181 * I/O was done, so don't believe
3182 * the DIRTY state from VM anymore
3184 CLR(bp
->b_flags
, B_WASDIRTY
);
3185 DTRACE_IO1(done
, buf_t
, bp
);
3187 if (!ISSET(bp
->b_flags
, B_READ
) && !ISSET(bp
->b_flags
, B_RAW
))
3189 * wake up any writer's blocked
3190 * on throttle or waiting for I/O
3193 vnode_writedone(bp
->b_vp
);
3195 if (ISSET(bp
->b_flags
, (B_CALL
| B_FILTER
))) { /* if necessary, call out */
3196 void (*iodone_func
)(struct buf
*, void *) = bp
->b_iodone
;
3197 void *arg
= (void *)bp
->b_transaction
;
3198 int callout
= ISSET(bp
->b_flags
, B_CALL
);
3200 CLR(bp
->b_flags
, (B_CALL
| B_FILTER
)); /* filters and callouts are one-shot */
3201 bp
->b_iodone
= NULL
;
3202 bp
->b_transaction
= NULL
;
3204 if (iodone_func
== NULL
) {
3205 panic("biodone: bp @ %p has NULL b_iodone!\n", bp
);
3208 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
3209 (*iodone_func
)(bp
, arg
);
3212 int need_wakeup
= 0;
3215 * assumes that the callback function takes
3216 * ownership of the bp and deals with releasing it if necessary
3217 * BL_WANTED indicates that we've decided to wait on the
3218 * completion of this I/O in a synchronous manner... we
3219 * still call the callback function, but in addition we
3220 * will do a wakeup... BL_CALLDONE indicates that the callback
3221 * routine has completed and its ok for the waiter to take
3222 * 'ownership' of this bp back
3224 lck_mtx_lock_spin(buf_mtxp
);
3226 if (bp
->b_lflags
& BL_WANTED
) {
3227 CLR(bp
->b_lflags
, BL_WANTED
);
3230 SET(bp
->b_lflags
, BL_CALLDONE
);
3232 lck_mtx_unlock(buf_mtxp
);
3240 * in this case the call back function is acting
3241 * strictly as a filter... it does not take
3242 * ownership of the bp and is expecting us
3243 * to finish cleaning up... this is currently used
3244 * by the HFS journaling code
3247 if (ISSET(bp
->b_flags
, B_ASYNC
)) { /* if async, release it */
3248 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
3251 } else { /* or just wakeup the buffer */
3253 * by taking the mutex, we serialize
3254 * the buf owner calling buf_biowait so that we'll
3255 * only see him in one of 2 states...
3256 * state 1: B_DONE wasn't set and he's
3258 * state 2: he's blocked trying to take the
3259 * mutex before looking at B_DONE
3260 * BL_WANTED is cleared in case anyone else
3261 * is blocked waiting for the buffer... note
3262 * that we haven't cleared B_BUSY yet, so if
3263 * they do get to run, their going to re-set
3264 * BL_WANTED and go back to sleep
3266 lck_mtx_lock_spin(buf_mtxp
);
3268 CLR(bp
->b_lflags
, BL_WANTED
);
3269 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
3271 lck_mtx_unlock(buf_mtxp
);
3276 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 387)) | DBG_FUNC_END
,
3277 (int)bp
, (int)bp
->b_datap
, bp
->b_flags
, 0, 0);
3281 * Return a count of buffers on the "locked" queue.
3284 count_lock_queue(void)
3289 lck_mtx_lock(buf_mtxp
);
3291 for (bp
= bufqueues
[BQ_LOCKED
].tqh_first
; bp
;
3292 bp
= bp
->b_freelist
.tqe_next
)
3294 lck_mtx_unlock(buf_mtxp
);
3300 * Return a count of 'busy' buffers. Used at the time of shutdown.
3303 count_busy_buffers(void)
3308 lck_mtx_lock(buf_mtxp
);
3309 for (bp
= &buf_headers
[boot_nbuf_headers
]; --bp
>= buf_headers
; )
3310 if (!ISSET(bp
->b_flags
, B_INVAL
) && ISSET(bp
->b_lflags
, BL_BUSY
))
3312 lck_mtx_unlock(buf_mtxp
);
3319 * Print out statistics on the current allocation of the buffer pool.
3320 * Can be enabled to print out on every ``sync'' by setting "syncprt"
3321 * in vfs_syscalls.c using sysctl.
3327 register struct buf
*bp
;
3328 register struct bqueues
*dp
;
3329 int counts
[MAXBSIZE
/CLBYTES
+1];
3330 static char *bname
[BQUEUES
] =
3331 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
3333 for (dp
= bufqueues
, i
= 0; dp
< &bufqueues
[BQUEUES
]; dp
++, i
++) {
3335 for (j
= 0; j
<= MAXBSIZE
/CLBYTES
; j
++)
3338 lck_mtx_lock(buf_mtxp
);
3340 for (bp
= dp
->tqh_first
; bp
; bp
= bp
->b_freelist
.tqe_next
) {
3341 counts
[bp
->b_bufsize
/CLBYTES
]++;
3344 lck_mtx_unlock(buf_mtxp
);
3346 printf("%s: total-%d", bname
[i
], count
);
3347 for (j
= 0; j
<= MAXBSIZE
/CLBYTES
; j
++)
3349 printf(", %d-%d", j
* CLBYTES
, counts
[j
]);
3353 #endif /* DIAGNOSTIC */
3355 #define NRESERVEDIOBUFS 64
3359 alloc_io_buf(vnode_t vp
, int priv
)
3363 lck_mtx_lock(iobuffer_mtxp
);
3365 while (((niobuf_headers
- NRESERVEDIOBUFS
< bufstats
.bufs_iobufinuse
) && !priv
) ||
3366 (bp
= iobufqueue
.tqh_first
) == NULL
) {
3367 bufstats
.bufs_iobufsleeps
++;
3370 (void) msleep(&need_iobuffer
, iobuffer_mtxp
, (PRIBIO
+1), (const char *)"alloc_io_buf", NULL
);
3372 TAILQ_REMOVE(&iobufqueue
, bp
, b_freelist
);
3374 bufstats
.bufs_iobufinuse
++;
3375 if (bufstats
.bufs_iobufinuse
> bufstats
.bufs_iobufmax
)
3376 bufstats
.bufs_iobufmax
= bufstats
.bufs_iobufinuse
;
3378 lck_mtx_unlock(iobuffer_mtxp
);
3381 * initialize various fields
3382 * we don't need to hold the mutex since the buffer
3383 * is now private... the vp should have a reference
3384 * on it and is not protected by this mutex in any event
3386 bp
->b_timestamp
= 0;
3391 bp
->b_lflags
= BL_BUSY
| BL_IOBUF
;
3392 bp
->b_blkno
= bp
->b_lblkno
= 0;
3394 bp
->b_owner
= current_thread();
3397 bp
->b_iodone
= NULL
;
3405 if (vp
&& (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
))
3406 bp
->b_dev
= vp
->v_rdev
;
3415 free_io_buf(buf_t bp
)
3417 int need_wakeup
= 0;
3420 * put buffer back on the head of the iobufqueue
3423 bp
->b_flags
= B_INVAL
;
3425 lck_mtx_lock_spin(iobuffer_mtxp
);
3427 binsheadfree(bp
, &iobufqueue
, -1);
3429 if (need_iobuffer
) {
3431 * Wake up any processes waiting because they need an io buffer
3433 * do the wakeup after we drop the mutex... it's possible that the
3434 * wakeup will be superfluous if need_iobuffer gets set again and
3435 * another thread runs this path, but it's highly unlikely, doesn't
3436 * hurt, and it means we don't hold up I/O progress if the wakeup blocks
3437 * trying to grab a task related lock...
3442 bufstats
.bufs_iobufinuse
--;
3444 lck_mtx_unlock(iobuffer_mtxp
);
3447 wakeup(&need_iobuffer
);
3454 lck_mtx_lock(buf_mtxp
);
3458 buf_list_unlock(void)
3460 lck_mtx_unlock(buf_mtxp
);
3464 * If getnewbuf() calls bcleanbuf() on the same thread
3465 * there is a potential for stack overrun and deadlocks.
3466 * So we always handoff the work to a worker thread for completion
3471 bcleanbuf_thread_init(void)
3473 /* create worker thread */
3474 kernel_thread(kernel_task
, bcleanbuf_thread
);
3478 bcleanbuf_thread(void)
3485 lck_mtx_lock(buf_mtxp
);
3487 while ( (bp
= TAILQ_FIRST(&bufqueues
[BQ_LAUNDRY
])) == NULL
)
3488 (void)msleep((void *)&bufqueues
[BQ_LAUNDRY
], buf_mtxp
, PRIBIO
, "blaundry", NULL
);
3491 * Remove from the queue
3493 bremfree_locked(bp
);
3496 * Buffer is no longer on any free list
3498 SET(bp
->b_lflags
, BL_BUSY
);
3501 bp
->b_owner
= current_thread();
3505 lck_mtx_unlock(buf_mtxp
);
3509 error
= bawrite_internal(bp
, 0);
3512 bp
->b_whichq
= BQ_LAUNDRY
;
3513 bp
->b_timestamp
= buf_timestamp();
3515 lck_mtx_lock_spin(buf_mtxp
);
3517 binstailfree(bp
, &bufqueues
[BQ_LAUNDRY
], BQ_LAUNDRY
);
3520 /* we never leave a busy page on the laundary queue */
3521 CLR(bp
->b_lflags
, BL_BUSY
);
3523 bp
->b_owner
= current_thread();
3527 lck_mtx_unlock(buf_mtxp
);
3530 (void)tsleep((void *)&bufqueues
[BQ_LAUNDRY
], PRIBIO
, "blaundry", 1);
3533 (void)thread_block(THREAD_CONTINUE_NULL
);
3542 brecover_data(buf_t bp
)
3546 upl_page_info_t
*pl
;
3548 vnode_t vp
= bp
->b_vp
;
3552 if ( !UBCINFOEXISTS(vp
) || bp
->b_bufsize
== 0)
3555 upl_flags
= UPL_PRECIOUS
;
3556 if (! (buf_flags(bp
) & B_READ
)) {
3558 * "write" operation: let the UPL subsystem know
3559 * that we intend to modify the buffer cache pages we're
3562 upl_flags
|= UPL_WILL_MODIFY
;
3565 kret
= ubc_create_upl(vp
,
3566 ubc_blktooff(vp
, bp
->b_lblkno
),
3571 if (kret
!= KERN_SUCCESS
)
3572 panic("Failed to create UPL");
3574 for (upl_offset
= 0; upl_offset
< bp
->b_bufsize
; upl_offset
+= PAGE_SIZE
) {
3576 if (!upl_valid_page(pl
, upl_offset
/ PAGE_SIZE
) || !upl_dirty_page(pl
, upl_offset
/ PAGE_SIZE
)) {
3577 ubc_upl_abort(upl
, 0);
3583 kret
= ubc_upl_map(upl
, (vm_address_t
*)&(bp
->b_datap
));
3585 if (kret
!= KERN_SUCCESS
)
3586 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
3591 SET(bp
->b_flags
, B_INVAL
);
3608 bp_cmp(void *a
, void *b
)
3610 buf_t
*bp_a
= *(buf_t
**)a
,
3611 *bp_b
= *(buf_t
**)b
;
3614 // don't have to worry about negative block
3615 // numbers so this is ok to do.
3617 res
= (bp_a
->b_blkno
- bp_b
->b_blkno
);
3624 bflushq(int whichq
, mount_t mp
)
3628 int total_writes
= 0;
3629 static buf_t flush_table
[NFLUSH
];
3631 if (whichq
< 0 || whichq
>= BQUEUES
) {
3636 lck_mtx_lock(buf_mtxp
);
3638 bp
= TAILQ_FIRST(&bufqueues
[whichq
]);
3640 for (buf_count
= 0; bp
; bp
= next
) {
3641 next
= bp
->b_freelist
.tqe_next
;
3643 if (bp
->b_vp
== NULL
|| bp
->b_vp
->v_mount
!= mp
) {
3647 if (ISSET(bp
->b_flags
, B_DELWRI
) && !ISSET(bp
->b_lflags
, BL_BUSY
)) {
3649 bremfree_locked(bp
);
3651 bp
->b_owner
= current_thread();
3654 SET(bp
->b_lflags
, BL_BUSY
);
3655 flush_table
[buf_count
] = bp
;
3659 if (buf_count
>= NFLUSH
) {
3660 lck_mtx_unlock(buf_mtxp
);
3662 qsort(flush_table
, buf_count
, sizeof(struct buf
*), bp_cmp
);
3664 for (i
= 0; i
< buf_count
; i
++) {
3665 buf_bawrite(flush_table
[i
]);
3671 lck_mtx_unlock(buf_mtxp
);
3673 if (buf_count
> 0) {
3674 qsort(flush_table
, buf_count
, sizeof(struct buf
*), bp_cmp
);
3676 for (i
= 0; i
< buf_count
; i
++) {
3677 buf_bawrite(flush_table
[i
]);
3681 return (total_writes
);
3688 /* XXX move this to a separate file */
3691 * NOTE: THIS CODE HAS NOT BEEN UPDATED
3692 * WITH RESPECT TO THE NEW LOCKING MODEL
3697 * Dynamic Scaling of the Buffer Queues
3700 typedef long long blsize_t
;
3702 blsize_t MAXNBUF
; /* initialize to (sane_size / PAGE_SIZE) */
3703 /* Global tunable limits */
3704 blsize_t nbufh
; /* number of buffer headers */
3705 blsize_t nbuflow
; /* minimum number of buffer headers required */
3706 blsize_t nbufhigh
; /* maximum number of buffer headers allowed */
3707 blsize_t nbuftarget
; /* preferred number of buffer headers */
3712 * 1. 0 < nbuflow <= nbufh <= nbufhigh
3713 * 2. nbufhigh <= MAXNBUF
3714 * 3. 0 < nbuflow <= nbuftarget <= nbufhigh
3715 * 4. nbufh can not be set by sysctl().
3718 /* Per queue tunable limits */
3721 blsize_t bl_nlow
; /* minimum number of buffer headers required */
3722 blsize_t bl_num
; /* number of buffer headers on the queue */
3723 blsize_t bl_nlhigh
; /* maximum number of buffer headers allowed */
3724 blsize_t bl_target
; /* preferred number of buffer headers */
3725 long bl_stale
; /* Seconds after which a buffer is considered stale */
3731 * 1. 0 <= bl_nlow <= bl_num <= bl_nlhigh
3732 * 2. bl_nlhigh <= MAXNBUF
3733 * 3. bufqlim[BQ_META].bl_nlow != 0
3734 * 4. bufqlim[BQ_META].bl_nlow > (number of possible concurrent
3735 * file system IO operations)
3736 * 5. bl_num can not be set by sysctl().
3737 * 6. bl_nhigh <= nbufhigh
3743 * Defining it blsize_t as long permits 2^31 buffer headers per queue.
3744 * Which can describe (2^31 * PAGE_SIZE) memory per queue.
3746 * These limits are exported to by means of sysctl().
3747 * It was decided to define blsize_t as a 64 bit quantity.
3748 * This will make sure that we will not be required to change it
3749 * as long as we do not exceed 64 bit address space for the kernel.
3751 * low and high numbers parameters initialized at compile time
3752 * and boot arguments can be used to override them. sysctl()
3753 * would not change the value. sysctl() can get all the values
3754 * but can set only target. num is the current level.
3756 * Advantages of having a "bufqscan" thread doing the balancing are,
3757 * Keep enough bufs on BQ_EMPTY.
3758 * getnewbuf() by default will always select a buffer from the BQ_EMPTY.
3759 * getnewbuf() perfoms best if a buffer was found there.
3760 * Also this minimizes the possibility of starting IO
3761 * from getnewbuf(). That's a performance win, too.
3763 * Localize complex logic [balancing as well as time aging]
3766 * Simplify getnewbuf() logic by elimination of time aging code.
3772 * The goal of the dynamic scaling of the buffer queues to to keep
3773 * the size of the LRU close to bl_target. Buffers on a queue would
3776 * There would be a thread which will be responsible for "balancing"
3777 * the buffer cache queues.
3779 * The scan order would be: AGE, LRU, META, EMPTY.
3782 long bufqscanwait
= 0;
3784 static void bufqscan_thread();
3785 static int balancebufq(int q
);
3786 static int btrimempty(int n
);
3787 static __inline__
int initbufqscan(void);
3788 static __inline__
int nextbufq(int q
);
3789 static void buqlimprt(int all
);
3792 static __inline__
void
3795 if ((q
< 0) || (q
>= BQUEUES
))
3798 bufqlim
[q
].bl_num
++;
3802 static __inline__
void
3805 if ((q
< 0) || (q
>= BQUEUES
))
3808 bufqlim
[q
].bl_num
--;
3813 bufq_balance_thread_init(void)
3816 if (bufqscanwait
++ == 0) {
3818 /* Initalize globals */
3819 MAXNBUF
= (sane_size
/ PAGE_SIZE
);
3820 nbufh
= nbuf_headers
;
3821 nbuflow
= min(nbufh
, 100);
3822 nbufhigh
= min(MAXNBUF
, max(nbufh
, 2048));
3823 nbuftarget
= (sane_size
>> 5) / PAGE_SIZE
;
3824 nbuftarget
= max(nbuflow
, nbuftarget
);
3825 nbuftarget
= min(nbufhigh
, nbuftarget
);
3828 * Initialize the bufqlim
3832 bufqlim
[BQ_LOCKED
].bl_nlow
= 0;
3833 bufqlim
[BQ_LOCKED
].bl_nlhigh
= 32;
3834 bufqlim
[BQ_LOCKED
].bl_target
= 0;
3835 bufqlim
[BQ_LOCKED
].bl_stale
= 30;
3838 bufqlim
[BQ_LRU
].bl_nlow
= 0;
3839 bufqlim
[BQ_LRU
].bl_nlhigh
= nbufhigh
/4;
3840 bufqlim
[BQ_LRU
].bl_target
= nbuftarget
/4;
3841 bufqlim
[BQ_LRU
].bl_stale
= LRU_IS_STALE
;
3844 bufqlim
[BQ_AGE
].bl_nlow
= 0;
3845 bufqlim
[BQ_AGE
].bl_nlhigh
= nbufhigh
/4;
3846 bufqlim
[BQ_AGE
].bl_target
= nbuftarget
/4;
3847 bufqlim
[BQ_AGE
].bl_stale
= AGE_IS_STALE
;
3850 bufqlim
[BQ_EMPTY
].bl_nlow
= 0;
3851 bufqlim
[BQ_EMPTY
].bl_nlhigh
= nbufhigh
/4;
3852 bufqlim
[BQ_EMPTY
].bl_target
= nbuftarget
/4;
3853 bufqlim
[BQ_EMPTY
].bl_stale
= 600000;
3856 bufqlim
[BQ_META
].bl_nlow
= 0;
3857 bufqlim
[BQ_META
].bl_nlhigh
= nbufhigh
/4;
3858 bufqlim
[BQ_META
].bl_target
= nbuftarget
/4;
3859 bufqlim
[BQ_META
].bl_stale
= META_IS_STALE
;
3862 bufqlim
[BQ_LOCKED
].bl_nlow
= 0;
3863 bufqlim
[BQ_LOCKED
].bl_nlhigh
= 32;
3864 bufqlim
[BQ_LOCKED
].bl_target
= 0;
3865 bufqlim
[BQ_LOCKED
].bl_stale
= 30;
3870 /* create worker thread */
3871 kernel_thread(kernel_task
, bufqscan_thread
);
3874 /* The workloop for the buffer balancing thread */
3882 int q
; /* buffer queue to process */
3886 moretodo
|= balancebufq(q
);
3895 (void)tsleep((void *)&bufqscanwait
, PRIBIO
, "bufqscanwait", 60 * hz
);
3900 /* Seed for the buffer queue balancing */
3901 static __inline__
int
3904 /* Start with AGE queue */
3908 /* Pick next buffer queue to balance */
3909 static __inline__
int
3912 int order
[] = { BQ_AGE
, BQ_LRU
, BQ_META
, BQ_EMPTY
, 0 };
3919 /* function to balance the buffer queues */
3926 /* reject invalid q */
3927 if ((q
< 0) || (q
>= BQUEUES
))
3930 /* LOCKED or LAUNDRY queue MUST not be balanced */
3931 if ((q
== BQ_LOCKED
) || (q
== BQ_LAUNDRY
))
3934 n
= (bufqlim
[q
].bl_num
- bufqlim
[q
].bl_target
);
3936 /* If queue has less than target nothing more to do */
3941 /* Balance only a small amount (12.5%) at a time */
3945 /* EMPTY queue needs special handling */
3946 if (q
== BQ_EMPTY
) {
3947 moretodo
|= btrimempty(n
);
3951 t
= buf_timestamp():
3953 for (; n
> 0; n
--) {
3954 struct buf
*bp
= bufqueues
[q
].tqh_first
;
3958 /* check if it's stale */
3959 if ((t
- bp
->b_timestamp
) > bufqlim
[q
].bl_stale
) {
3960 if (bcleanbuf(bp
)) {
3961 /* buf_bawrite() issued, bp not ready */
3964 /* release the cleaned buffer to BQ_EMPTY */
3965 SET(bp
->b_flags
, B_INVAL
);
3980 * When struct buf are allocated dynamically, this would
3981 * reclaim upto 'n' struct buf from the empty queue.
3991 static char *bname
[BQUEUES
] =
3992 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
3995 for (i
= 0; i
< BQUEUES
; i
++) {
3996 printf("%s : ", bname
[i
]);
3997 printf("min = %ld, ", (long)bufqlim
[i
].bl_nlow
);
3998 printf("cur = %ld, ", (long)bufqlim
[i
].bl_num
);
3999 printf("max = %ld, ", (long)bufqlim
[i
].bl_nlhigh
);
4000 printf("target = %ld, ", (long)bufqlim
[i
].bl_target
);
4001 printf("stale after %ld seconds\n", bufqlim
[i
].bl_stale
);
4004 for (i
= 0; i
< BQUEUES
; i
++) {
4005 printf("%s : ", bname
[i
]);
4006 printf("cur = %ld, ", (long)bufqlim
[i
].bl_num
);