2 * Copyright (c) 2000-2002 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * The contents of this file constitute Original Code as defined in and
7 * are subject to the Apple Public Source License Version 1.1 (the
8 * "License"). You may not use this file except in compliance with the
9 * License. Please obtain a copy of the License at
10 * http://www.apple.com/publicsource and read it before using this file.
12 * This Original Code and all software distributed under the License are
13 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
14 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
15 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
17 * License for the specific language governing rights and limitations
20 * @APPLE_LICENSE_HEADER_END@
22 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
24 * Copyright (c) 1994 Christopher G. Demetriou
25 * Copyright (c) 1982, 1986, 1989, 1993
26 * The Regents of the University of California. All rights reserved.
27 * (c) UNIX System Laboratories, Inc.
28 * All or some portions of this file are derived from material licensed
29 * to the University of California by American Telephone and Telegraph
30 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
31 * the permission of UNIX System Laboratories, Inc.
33 * Redistribution and use in source and binary forms, with or without
34 * modification, are permitted provided that the following conditions
36 * 1. Redistributions of source code must retain the above copyright
37 * notice, this list of conditions and the following disclaimer.
38 * 2. Redistributions in binary form must reproduce the above copyright
39 * notice, this list of conditions and the following disclaimer in the
40 * documentation and/or other materials provided with the distribution.
41 * 3. All advertising materials mentioning features or use of this software
42 * must display the following acknowledgement:
43 * This product includes software developed by the University of
44 * California, Berkeley and its contributors.
45 * 4. Neither the name of the University nor the names of its contributors
46 * may be used to endorse or promote products derived from this software
47 * without specific prior written permission.
49 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
61 * The NEXTSTEP Software License Agreement specifies the terms
62 * and conditions for redistribution.
64 * @(#)vfs_bio.c 8.6 (Berkeley) 1/11/94
69 * Bach: The Design of the UNIX Operating System (Prentice Hall, 1986)
70 * Leffler, et al.: The Design and Implementation of the 4.3BSD
71 * UNIX Operating System (Addison Welley, 1989)
74 #include <sys/param.h>
75 #include <sys/systm.h>
78 #include <sys/vnode.h>
79 #include <sys/mount.h>
80 #include <sys/trace.h>
81 #include <sys/malloc.h>
82 #include <sys/resourcevar.h>
83 #include <miscfs/specfs/specdev.h>
85 #include <vm/vm_pageout.h>
87 #include <kern/assert.h>
88 #endif /* DIAGNOSTIC */
89 #include <kern/task.h>
90 #include <kern/zalloc.h>
92 #include <sys/kdebug.h>
93 #include <machine/spl.h>
95 static __inline__
void bufqinc(int q
);
96 static __inline__
void bufqdec(int q
);
98 static struct buf
*getnewbuf(int slpflag
, int slptimeo
, int *queue
);
99 static int bcleanbuf(struct buf
*bp
);
100 extern void vwakeup();
102 extern int niobuf
; /* The number of IO buffer headers for cluster IO */
105 /* zone allocated buffer headers */
106 static zone_t buf_hdr_zone
;
107 static int buf_hdr_count
;
110 struct proc
*traceproc
;
111 int tracewhich
, tracebuf
[TRCSIZ
];
113 char traceflags
[TR_NFLAGS
];
117 * Definitions for the buffer hash lists.
119 #define BUFHASH(dvp, lbn) \
120 (&bufhashtbl[((long)(dvp) / sizeof(*(dvp)) + (int)(lbn)) & bufhash])
121 LIST_HEAD(bufhashhdr
, buf
) *bufhashtbl
, invalhash
;
124 /* Definitions for the buffer stats. */
125 struct bufstats bufstats
;
127 /* Number of delayed write buffers */
131 * Insq/Remq for the buffer hash lists.
134 #define binshash(bp, dp) LIST_INSERT_HEAD(dp, bp, b_hash)
135 #define bremhash(bp) LIST_REMOVE(bp, b_hash)
139 TAILQ_HEAD(ioqueue
, buf
) iobufqueue
;
140 TAILQ_HEAD(bqueues
, buf
) bufqueues
[BQUEUES
];
141 static int needbuffer
;
142 static int need_iobuffer
;
145 * Insq/Remq for the buffer free lists.
147 #define binsheadfree(bp, dp, whichq) do { \
148 TAILQ_INSERT_HEAD(dp, bp, b_freelist); \
150 (bp)->b_whichq = whichq; \
151 (bp)->b_timestamp = time.tv_sec; \
154 #define binstailfree(bp, dp, whichq) do { \
155 TAILQ_INSERT_TAIL(dp, bp, b_freelist); \
157 (bp)->b_whichq = whichq; \
158 (bp)->b_timestamp = time.tv_sec; \
161 #define BHASHENTCHECK(bp) \
162 if ((bp)->b_hash.le_prev != (struct buf **)0xdeadbeef) \
163 panic("%x: b_hash.le_prev is not deadbeef", (bp));
165 #define BLISTNONE(bp) \
166 (bp)->b_hash.le_next = (struct buf *)0; \
167 (bp)->b_hash.le_prev = (struct buf **)0xdeadbeef;
170 * Insq/Remq for the vnode usage lists.
172 #define bufinsvn(bp, dp) LIST_INSERT_HEAD(dp, bp, b_vnbufs)
173 #define bufremvn(bp) { \
174 LIST_REMOVE(bp, b_vnbufs); \
175 (bp)->b_vnbufs.le_next = NOLIST; \
178 simple_lock_data_t bufhashlist_slock
; /* lock on buffer hash list */
180 /* number of per vnode, "in flight" buffer writes */
181 #define BUFWRITE_THROTTLE 9
185 * Time in seconds before a buffer on a list is
186 * considered as a stale buffer
188 #define LRU_IS_STALE 120 /* default value for the LRU */
189 #define AGE_IS_STALE 60 /* default value for the AGE */
190 #define META_IS_STALE 180 /* default value for the BQ_META */
192 int lru_is_stale
= LRU_IS_STALE
;
193 int age_is_stale
= AGE_IS_STALE
;
194 int meta_is_stale
= META_IS_STALE
;
196 /* LIST_INSERT_HEAD() with assertions */
197 static __inline__
void
198 blistenterhead(struct bufhashhdr
* head
, struct buf
* bp
)
200 if ((bp
->b_hash
.le_next
= (head
)->lh_first
) != NULL
)
201 (head
)->lh_first
->b_hash
.le_prev
= &(bp
)->b_hash
.le_next
;
202 (head
)->lh_first
= bp
;
203 bp
->b_hash
.le_prev
= &(head
)->lh_first
;
204 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
205 panic("blistenterhead: le_prev is deadbeef");
208 static __inline__
void
209 binshash(struct buf
*bp
, struct bufhashhdr
*dp
)
213 simple_lock(&bufhashlist_slock
);
216 if((bad
= incore(bp
->b_vp
, bp
->b_lblkno
)))
217 panic("binshash: already incore bp 0x%x, bad 0x%x\n", bp
, bad
);
223 for(; nbp
!= NULL
; nbp
= nbp
->b_hash
.le_next
) {
225 panic("buf already in hashlist");
228 blistenterhead(dp
, bp
);
229 simple_unlock(&bufhashlist_slock
);
232 static __inline__
void
233 bremhash(struct buf
*bp
)
235 simple_lock(&bufhashlist_slock
);
236 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
237 panic("bremhash le_prev is deadbeef");
238 if (bp
->b_hash
.le_next
== bp
)
239 panic("bremhash: next points to self");
241 if (bp
->b_hash
.le_next
!= NULL
)
242 bp
->b_hash
.le_next
->b_hash
.le_prev
= bp
->b_hash
.le_prev
;
243 *bp
->b_hash
.le_prev
= (bp
)->b_hash
.le_next
;
244 simple_unlock(&bufhashlist_slock
);
248 * Remove a buffer from the free list it's on
254 struct bqueues
*dp
= NULL
;
258 * We only calculate the head of the freelist when removing
259 * the last element of the list as that is the only time that
260 * it is needed (e.g. to reset the tail pointer).
262 * NB: This makes an assumption about how tailq's are implemented.
264 if (bp
->b_freelist
.tqe_next
== NULL
) {
265 for (dp
= bufqueues
; dp
< &bufqueues
[BQUEUES
]; dp
++)
266 if (dp
->tqh_last
== &bp
->b_freelist
.tqe_next
)
268 if (dp
== &bufqueues
[BQUEUES
])
269 panic("bremfree: lost tail");
271 TAILQ_REMOVE(dp
, bp
, b_freelist
);
272 whichq
= bp
->b_whichq
;
279 * Associate a buffer with a vnode.
283 register struct vnode
*vp
;
284 register struct buf
*bp
;
288 panic("bgetvp: not free");
291 if (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
)
292 bp
->b_dev
= vp
->v_rdev
;
296 * Insert onto list for new vnode.
298 bufinsvn(bp
, &vp
->v_cleanblkhd
);
302 * Disassociate a buffer from a vnode.
306 register struct buf
*bp
;
310 if (bp
->b_vp
== (struct vnode
*) 0)
311 panic("brelvp: NULL vp");
313 * Delete from old vnode list, if on one.
315 if (bp
->b_vnbufs
.le_next
!= NOLIST
)
318 bp
->b_vp
= (struct vnode
*) 0;
323 * Reassign a buffer from one vnode to another.
324 * Used to assign file specific control information
325 * (indirect blocks) to the vnode to which they belong.
328 reassignbuf(bp
, newvp
)
329 register struct buf
*bp
;
330 register struct vnode
*newvp
;
332 register struct buflists
*listheadp
;
335 printf("reassignbuf: NULL");
339 * Delete from old vnode list, if on one.
341 if (bp
->b_vnbufs
.le_next
!= NOLIST
)
344 * If dirty, put on list of dirty buffers;
345 * otherwise insert onto list of clean buffers.
347 if (ISSET(bp
->b_flags
, B_DELWRI
))
348 listheadp
= &newvp
->v_dirtyblkhd
;
350 listheadp
= &newvp
->v_cleanblkhd
;
351 bufinsvn(bp
, listheadp
);
354 static __inline__
void
355 bufhdrinit(struct buf
*bp
)
357 bzero((char *)bp
, sizeof *bp
);
359 bp
->b_rcred
= NOCRED
;
360 bp
->b_wcred
= NOCRED
;
361 bp
->b_vnbufs
.le_next
= NOLIST
;
362 bp
->b_flags
= B_INVAL
;
368 * Initialize buffers and hash links for buffers.
370 __private_extern__
void
373 register struct buf
*bp
;
374 register struct bqueues
*dp
;
378 static void bufzoneinit();
379 static void bcleanbuf_thread_init();
381 /* Initialize the buffer queues ('freelists') and the hash table */
382 for (dp
= bufqueues
; dp
< &bufqueues
[BQUEUES
]; dp
++)
384 bufhashtbl
= hashinit(nbuf
, M_CACHE
, &bufhash
);
386 simple_lock_init(&bufhashlist_slock
);
388 metabuf
= nbuf
/8; /* reserved for meta buf */
390 /* Initialize the buffer headers */
391 for (i
= 0; i
< nbuf
; i
++) {
396 * metabuf buffer headers on the meta-data list and
397 * rest of the buffer headers on the empty list
405 dp
= &bufqueues
[whichq
];
406 binsheadfree(bp
, dp
, whichq
);
407 binshash(bp
, &invalhash
);
410 for (; i
< nbuf
+ niobuf
; i
++) {
413 binsheadfree(bp
, &iobufqueue
, -1);
416 printf("using %d buffer headers and %d cluster IO buffer headers\n",
419 /* Set up zones used by the buffer cache */
422 /* start the bcleanbuf() thread */
423 bcleanbuf_thread_init();
427 static void bufq_balance_thread_init();
428 /* create a thread to do dynamic buffer queue balancing */
429 bufq_balance_thread_init();
435 bio_doread(vp
, blkno
, size
, cred
, async
, queuetype
)
443 register struct buf
*bp
;
444 struct proc
*p
= current_proc();
446 bp
= getblk(vp
, blkno
, size
, 0, 0, queuetype
);
449 * If buffer does not have data valid, start a read.
450 * Note that if buffer is B_INVAL, getblk() won't return it.
451 * Therefore, it's valid if it's I/O has completed or been delayed.
453 if (!ISSET(bp
->b_flags
, (B_DONE
| B_DELWRI
))) {
454 /* Start I/O for the buffer (keeping credentials). */
455 SET(bp
->b_flags
, B_READ
| async
);
456 if (cred
!= NOCRED
&& bp
->b_rcred
== NOCRED
) {
458 * NFS has embedded ucred.
459 * Can not crhold() here as that causes zone corruption
461 bp
->b_rcred
= crdup(cred
);
466 trace(TR_BREADMISS
, pack(vp
, size
), blkno
);
468 /* Pay for the read. */
470 p
->p_stats
->p_ru
.ru_inblock
++; /* XXX */
475 trace(TR_BREADHIT
, pack(vp
, size
), blkno
);
481 * This algorithm described in Bach (p.54).
484 bread(vp
, blkno
, size
, cred
, bpp
)
491 register struct buf
*bp
;
493 /* Get buffer for block. */
494 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, BLK_READ
);
496 /* Wait for the read to complete, and return result. */
497 return (biowait(bp
));
501 * Read a disk block. [bread() for meta-data]
502 * This algorithm described in Bach (p.54).
505 meta_bread(vp
, blkno
, size
, cred
, bpp
)
512 register struct buf
*bp
;
514 /* Get buffer for block. */
515 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, BLK_META
);
517 /* Wait for the read to complete, and return result. */
518 return (biowait(bp
));
522 * Read-ahead multiple disk blocks. The first is sync, the rest async.
523 * Trivial modification to the breada algorithm presented in Bach (p.55).
526 breadn(vp
, blkno
, size
, rablks
, rasizes
, nrablks
, cred
, bpp
)
528 daddr_t blkno
; int size
;
529 daddr_t rablks
[]; int rasizes
[];
534 register struct buf
*bp
;
537 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, BLK_READ
);
540 * For each of the read-ahead blocks, start a read, if necessary.
542 for (i
= 0; i
< nrablks
; i
++) {
543 /* If it's in the cache, just go on to next one. */
544 if (incore(vp
, rablks
[i
]))
547 /* Get a buffer for the read-ahead block */
548 (void) bio_doread(vp
, rablks
[i
], rasizes
[i
], cred
, B_ASYNC
, BLK_READ
);
551 /* Otherwise, we had to start a read for it; wait until it's valid. */
552 return (biowait(bp
));
556 * Read with single-block read-ahead. Defined in Bach (p.55), but
557 * implemented as a call to breadn().
558 * XXX for compatibility with old file systems.
561 breada(vp
, blkno
, size
, rablkno
, rabsize
, cred
, bpp
)
563 daddr_t blkno
; int size
;
564 daddr_t rablkno
; int rabsize
;
569 return (breadn(vp
, blkno
, size
, &rablkno
, &rabsize
, 1, cred
, bpp
));
573 * Block write. Described in Bach (p.56)
579 int rv
, sync
, wasdelayed
;
580 struct proc
*p
= current_proc();
581 struct vnode
*vp
= bp
->b_vp
;
583 /* Remember buffer type, to switch on it later. */
584 sync
= !ISSET(bp
->b_flags
, B_ASYNC
);
585 wasdelayed
= ISSET(bp
->b_flags
, B_DELWRI
);
586 CLR(bp
->b_flags
, (B_READ
| B_DONE
| B_ERROR
| B_DELWRI
));
589 wakeup((caddr_t
)&nbdwrite
);
594 * If not synchronous, pay for the I/O operation and make
595 * sure the buf is on the correct vnode queue. We have
596 * to do this now, because if we don't, the vnode may not
597 * be properly notified that its I/O has completed.
603 p
->p_stats
->p_ru
.ru_oublock
++; /* XXX */
606 trace(TR_BUFWRITE
, pack(vp
, bp
->b_bcount
), bp
->b_lblkno
);
608 /* Initiate disk write. Make sure the appropriate party is charged. */
609 SET(bp
->b_flags
, B_WRITEINPROG
);
616 * If I/O was synchronous, wait for it to complete.
621 * Pay for the I/O operation, if it's not been paid for, and
622 * make sure it's on the correct vnode queue. (async operatings
623 * were payed for above.)
629 p
->p_stats
->p_ru
.ru_oublock
++; /* XXX */
631 /* Release the buffer. */
632 // XXXdbg - only if the unused bit is set
633 if (!ISSET(bp
->b_flags
, B_NORELSE
)) {
636 CLR(bp
->b_flags
, B_NORELSE
);
647 struct vop_bwrite_args
*ap
;
649 return (bwrite(ap
->a_bp
));
655 * The buffer is marked dirty, but is not queued for I/O.
656 * This routine should be used when the buffer is expected
657 * to be modified again soon, typically a small write that
658 * partially fills a buffer.
660 * NB: magnetic tapes cannot be delayed; they must be
661 * written in the order that the writes are requested.
663 * Described in Leffler, et al. (pp. 208-213).
665 * Note: With the abilitty to allocate additional buffer
666 * headers, we can get in to the situation where "too" many
667 * bdwrite()s can create situation where the kernel can create
668 * buffers faster than the disks can service. Doing a bawrite() in
669 * cases were we have "too many" outstanding bdwrite()s avoids that.
671 __private_extern__
int
672 bdwrite_internal(bp
, return_error
)
676 struct proc
*p
= current_proc();
677 struct vnode
*vp
= bp
->b_vp
;
680 * If the block hasn't been seen before:
681 * (1) Mark it as having been seen,
682 * (2) Charge for the write.
683 * (3) Make sure it's on its vnode's correct block list,
685 if (!ISSET(bp
->b_flags
, B_DELWRI
)) {
686 SET(bp
->b_flags
, B_DELWRI
);
688 p
->p_stats
->p_ru
.ru_oublock
++; /* XXX */
693 /* If this is a tape block, write it the block now. */
694 if (ISSET(bp
->b_flags
, B_TAPE
)) {
701 * If the vnode has "too many" write operations in progress
702 * wait for them to finish the IO
704 while (vp
->v_numoutput
>= BUFWRITE_THROTTLE
) {
705 vp
->v_flag
|= VTHROTTLED
;
706 (void)tsleep((caddr_t
)&vp
->v_numoutput
, PRIBIO
+ 1, "bdwrite", 0);
710 * If we have too many delayed write buffers,
711 * more than we can "safely" handle, just fall back to
712 * doing the async write
715 panic("bdwrite: Negative nbdwrite");
717 // can't do a bawrite() if the LOCKED bit is set because the
718 // buffer is part of a transaction and can't go to disk until
719 // the LOCKED bit is cleared.
720 if (!ISSET(bp
->b_flags
, B_LOCKED
) && nbdwrite
> ((nbuf
/4)*3)) {
728 /* Otherwise, the "write" is done, so mark and release the buffer. */
729 SET(bp
->b_flags
, B_DONE
);
738 (void) bdwrite_internal(bp
, 0);
743 * Asynchronous block write; just an asynchronous bwrite().
745 * Note: With the abilitty to allocate additional buffer
746 * headers, we can get in to the situation where "too" many
747 * bawrite()s can create situation where the kernel can create
748 * buffers faster than the disks can service.
749 * We limit the number of "in flight" writes a vnode can have to
753 bawrite_internal(bp
, throttle
)
757 struct vnode
*vp
= bp
->b_vp
;
761 * If the vnode has "too many" write operations in progress
762 * wait for them to finish the IO
764 while (vp
->v_numoutput
>= BUFWRITE_THROTTLE
) {
766 vp
->v_flag
|= VTHROTTLED
;
767 (void)tsleep((caddr_t
)&vp
->v_numoutput
,
768 PRIBIO
+ 1, "bawrite", 0);
770 return (EWOULDBLOCK
);
774 SET(bp
->b_flags
, B_ASYNC
);
783 (void) bawrite_internal(bp
, 1);
789 * Called prior to the locking of any vnodes when we are expecting to
790 * write. We do not want to starve the buffer cache with too many
791 * dirty buffers so we block here. By blocking prior to the locking
792 * of any vnodes we attempt to avoid the situation where a locked vnode
793 * prevents the various system daemons from flushing related buffers.
799 /* XXX To be implemented later */
803 * Release a buffer on to the free lists.
804 * Described in Bach (p. 46).
810 struct bqueues
*bufq
;
814 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 388)) | DBG_FUNC_START
,
815 bp
->b_lblkno
* PAGE_SIZE
, (int)bp
, (int)bp
->b_data
,
818 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
820 // if we're invalidating a buffer that has the B_CALL bit
821 // set then call the b_iodone function so it gets cleaned
824 if (ISSET(bp
->b_flags
, B_META
) && ISSET(bp
->b_flags
, B_INVAL
)) {
825 if (ISSET(bp
->b_flags
, B_CALL
) && !ISSET(bp
->b_flags
, B_DELWRI
)) {
826 panic("brelse: CALL flag set but not DELWRI! bp 0x%x\n", bp
);
828 if (ISSET(bp
->b_flags
, B_CALL
)) { /* if necessary, call out */
829 void (*iodone_func
)(struct buf
*) = bp
->b_iodone
;
831 CLR(bp
->b_flags
, B_CALL
); /* but note callout done */
834 if (iodone_func
== NULL
) {
835 panic("brelse: bp @ 0x%x has NULL b_iodone!\n", bp
);
841 /* IO is done. Cleanup the UPL state */
842 if (!ISSET(bp
->b_flags
, B_META
)
843 && UBCINFOEXISTS(bp
->b_vp
) && bp
->b_bufsize
) {
848 if ( !ISSET(bp
->b_flags
, B_PAGELIST
)) {
849 if ( !ISSET(bp
->b_flags
, B_INVAL
)) {
850 kret
= ubc_create_upl(bp
->b_vp
,
851 ubc_blktooff(bp
->b_vp
, bp
->b_lblkno
),
856 if (kret
!= KERN_SUCCESS
)
857 panic("brelse: Failed to get pagelists");
859 upl_ubc_alias_set(upl
, bp
, 5);
860 #endif /* UBC_DEBUG */
864 upl
= bp
->b_pagelist
;
865 kret
= ubc_upl_unmap(upl
);
867 if (kret
!= KERN_SUCCESS
)
868 panic("kernel_upl_unmap failed");
872 if (bp
->b_flags
& (B_ERROR
| B_INVAL
)) {
873 if (bp
->b_flags
& (B_READ
| B_INVAL
))
874 upl_flags
= UPL_ABORT_DUMP_PAGES
;
877 ubc_upl_abort(upl
, upl_flags
);
879 if (ISSET(bp
->b_flags
, B_NEEDCOMMIT
))
880 upl_flags
= UPL_COMMIT_CLEAR_DIRTY
;
881 else if (ISSET(bp
->b_flags
, B_DELWRI
| B_WASDIRTY
))
882 upl_flags
= UPL_COMMIT_SET_DIRTY
;
884 upl_flags
= UPL_COMMIT_CLEAR_DIRTY
;
885 ubc_upl_commit_range(upl
, 0, bp
->b_bufsize
, upl_flags
|
886 UPL_COMMIT_INACTIVATE
| UPL_COMMIT_FREE_ON_EMPTY
);
889 CLR(bp
->b_flags
, B_PAGELIST
);
894 if(ISSET(bp
->b_flags
, B_PAGELIST
))
895 panic("brelse: pagelist set for non VREG; vp=%x", bp
->b_vp
);
898 /* Wake up any processes waiting for any buffer to become free. */
904 /* Wake up any proceeses waiting for _this_ buffer to become free. */
905 if (ISSET(bp
->b_flags
, B_WANTED
)) {
906 CLR(bp
->b_flags
, B_WANTED
);
910 /* Block disk interrupts. */
914 * Determine which queue the buffer should be on, then put it there.
917 /* If it's locked, don't report an error; try again later. */
918 if (ISSET(bp
->b_flags
, (B_LOCKED
|B_ERROR
)) == (B_LOCKED
|B_ERROR
))
919 CLR(bp
->b_flags
, B_ERROR
);
921 /* If it's not cacheable, or an error, mark it invalid. */
922 if (ISSET(bp
->b_flags
, (B_NOCACHE
|B_ERROR
)))
923 SET(bp
->b_flags
, B_INVAL
);
925 if ((bp
->b_bufsize
<= 0) || ISSET(bp
->b_flags
, B_INVAL
)) {
927 * If it's invalid or empty, dissociate it from its vnode
928 * and put on the head of the appropriate queue.
932 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
933 CLR(bp
->b_flags
, B_DELWRI
);
935 wakeup((caddr_t
)&nbdwrite
);
937 if (bp
->b_bufsize
<= 0)
938 whichq
= BQ_EMPTY
; /* no data */
939 else if (ISSET(bp
->b_flags
, B_META
))
940 whichq
= BQ_META
; /* meta-data */
942 whichq
= BQ_AGE
; /* invalid data */
944 bufq
= &bufqueues
[whichq
];
945 binsheadfree(bp
, bufq
, whichq
);
948 * It has valid data. Put it on the end of the appropriate
949 * queue, so that it'll stick around for as long as possible.
951 if (ISSET(bp
->b_flags
, B_LOCKED
))
952 whichq
= BQ_LOCKED
; /* locked in core */
953 else if (ISSET(bp
->b_flags
, B_META
))
954 whichq
= BQ_META
; /* meta-data */
955 else if (ISSET(bp
->b_flags
, B_AGE
))
956 whichq
= BQ_AGE
; /* stale but valid data */
958 whichq
= BQ_LRU
; /* valid data */
960 bufq
= &bufqueues
[whichq
];
961 binstailfree(bp
, bufq
, whichq
);
964 /* Unlock the buffer. */
965 CLR(bp
->b_flags
, (B_AGE
| B_ASYNC
| B_BUSY
| B_NOCACHE
));
967 /* Allow disk interrupts. */
970 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 388)) | DBG_FUNC_END
,
971 (int)bp
, (int)bp
->b_data
, bp
->b_flags
, 0, 0);
975 * Determine if a block is in the cache.
976 * Just look on what would be its hash chain. If it's there, return
977 * a pointer to it, unless it's marked invalid. If it's marked invalid,
978 * we normally don't return the buffer, unless the caller explicitly
988 bp
= BUFHASH(vp
, blkno
)->lh_first
;
990 /* Search hash chain */
991 for (; bp
!= NULL
; bp
= bp
->b_hash
.le_next
) {
992 if (bp
->b_lblkno
== blkno
&& bp
->b_vp
== vp
&&
993 !ISSET(bp
->b_flags
, B_INVAL
))
1001 /* XXX FIXME -- Update the comment to reflect the UBC changes (please) -- */
1003 * Get a block of requested size that is associated with
1004 * a given vnode and block offset. If it is found in the
1005 * block cache, mark it as having been found, make it busy
1006 * and return it. Otherwise, return an empty block of the
1007 * correct size. It is up to the caller to insure that the
1008 * cached blocks be of the correct size.
1011 getblk(vp
, blkno
, size
, slpflag
, slptimeo
, operation
)
1012 register struct vnode
*vp
;
1014 int size
, slpflag
, slptimeo
, operation
;
1019 upl_page_info_t
*pl
;
1024 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_START
,
1025 blkno
* PAGE_SIZE
, size
, operation
, 0, 0);
1029 if ((bp
= incore(vp
, blkno
))) {
1030 /* Found in the Buffer Cache */
1031 if (ISSET(bp
->b_flags
, B_BUSY
)) {
1033 switch (operation
) {
1037 SET(bp
->b_flags
, B_WANTED
);
1038 bufstats
.bufs_busyincore
++;
1039 err
= tsleep(bp
, slpflag
| (PRIBIO
+ 1), "getblk",
1043 * Callers who call with PCATCH or timeout are
1044 * willing to deal with the NULL pointer
1046 if (err
&& ((slpflag
& PCATCH
) ||
1047 ((err
== EWOULDBLOCK
) && slptimeo
)))
1054 /* pagein operation must not use getblk */
1055 panic("getblk: pagein for incore busy buffer");
1061 /* pageout operation must not use getblk */
1062 panic("getblk: pageout for incore busy buffer");
1068 panic("getblk: %d unknown operation 1", operation
);
1074 SET(bp
->b_flags
, (B_BUSY
| B_CACHE
));
1076 bufstats
.bufs_incore
++;
1080 if (ISSET(bp
->b_flags
, B_PAGELIST
))
1081 panic("pagelist buffer is not busy");
1083 switch (operation
) {
1086 if (UBCISVALID(bp
->b_vp
) && bp
->b_bufsize
) {
1087 kret
= ubc_create_upl(vp
,
1088 ubc_blktooff(vp
, bp
->b_lblkno
),
1093 if (kret
!= KERN_SUCCESS
)
1094 panic("Failed to get pagelists");
1096 SET(bp
->b_flags
, B_PAGELIST
);
1097 bp
->b_pagelist
= upl
;
1099 if (!upl_valid_page(pl
, 0)) {
1100 if (vp
->v_tag
!= VT_NFS
)
1101 panic("getblk: incore buffer without valid page");
1102 CLR(bp
->b_flags
, B_CACHE
);
1105 if (upl_dirty_page(pl
, 0))
1106 SET(bp
->b_flags
, B_WASDIRTY
);
1108 CLR(bp
->b_flags
, B_WASDIRTY
);
1110 kret
= ubc_upl_map(upl
, (vm_address_t
*)&(bp
->b_data
));
1111 if (kret
!= KERN_SUCCESS
)
1112 panic("getblk: ubc_upl_map() failed with (%d)",
1114 if (bp
->b_data
== 0)
1115 panic("ubc_upl_map mapped 0");
1121 * VM is not involved in IO for the meta data
1122 * buffer already has valid data
1125 panic("bp->b_data null incore buf=%x", bp
);
1130 panic("getblk: paging operation 1");
1134 panic("getblk: %d unknown operation 2", operation
);
1139 } else { /* not incore() */
1140 int queue
= BQ_EMPTY
; /* Start with no preference */
1143 if ((operation
== BLK_META
) || (UBCINVALID(vp
)) ||
1144 !(UBCINFOEXISTS(vp
))) {
1145 operation
= BLK_META
;
1147 if ((bp
= getnewbuf(slpflag
, slptimeo
, &queue
)) == NULL
)
1149 if (incore(vp
, blkno
)) {
1150 SET(bp
->b_flags
, B_INVAL
);
1151 binshash(bp
, &invalhash
);
1156 * NOTE: YOU CAN NOT BLOCK UNTIL binshash() HAS BEEN
1157 * CALLED! BE CAREFUL.
1161 * if it is meta, the queue may be set to other
1162 * type so reset as well as mark it to be B_META
1163 * so that when buffer is released it will goto META queue
1164 * Also, if the vnode is not VREG, then it is META
1166 if (operation
== BLK_META
) {
1167 SET(bp
->b_flags
, B_META
);
1171 bp
->b_blkno
= bp
->b_lblkno
= blkno
;
1175 * Insert in the hash so that incore() can find it
1177 binshash(bp
, BUFHASH(vp
, blkno
));
1185 switch (operation
) {
1187 /* buffer data is invalid */
1190 panic("bp->b_data is null %x",bp
);
1192 bufstats
.bufs_miss
++;
1194 /* wakeup the buffer */
1195 CLR(bp
->b_flags
, B_WANTED
);
1202 if (ISSET(bp
->b_flags
, B_PAGELIST
))
1203 panic("B_PAGELIST in bp=%x",bp
);
1205 kret
= ubc_create_upl(vp
,
1206 ubc_blktooff(vp
, blkno
),
1211 if (kret
!= KERN_SUCCESS
)
1212 panic("Failed to get pagelists");
1215 upl_ubc_alias_set(upl
, bp
, 4);
1216 #endif /* UBC_DEBUG */
1217 bp
->b_pagelist
= upl
;
1219 SET(bp
->b_flags
, B_PAGELIST
);
1221 if (upl_valid_page(pl
, 0)) {
1222 SET(bp
->b_flags
, B_CACHE
| B_DONE
);
1223 bufstats
.bufs_vmhits
++;
1225 pagedirty
= upl_dirty_page(pl
, 0);
1228 SET(bp
->b_flags
, B_WASDIRTY
);
1230 if (vp
->v_tag
== VT_NFS
) {
1237 f_offset
= ubc_blktooff(vp
, blkno
);
1239 if (f_offset
> vp
->v_ubcinfo
->ui_size
) {
1240 CLR(bp
->b_flags
, (B_CACHE
|B_DONE
|B_WASDIRTY
));
1244 valid_size
= min(((unsigned int)(vp
->v_ubcinfo
->ui_size
- f_offset
)), PAGE_SIZE
);
1245 bp
->b_validend
= valid_size
;
1248 bp
->b_dirtyend
= valid_size
;
1252 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_NONE
,
1253 bp
->b_validend
, bp
->b_dirtyend
,
1254 (int)vp
->v_ubcinfo
->ui_size
, 0, 0);
1262 bp
->b_validend
= bp
->b_bcount
;
1263 bp
->b_dirtyend
= bp
->b_bcount
;
1266 bp
->b_validend
= bp
->b_bcount
;
1270 error
= VOP_BMAP(vp
, bp
->b_lblkno
, NULL
, &bp
->b_blkno
, NULL
);
1272 panic("getblk: VOP_BMAP failed");
1275 * XXX: We probably should invalidate the VM Page
1277 bp
->b_error
= error
;
1278 SET(bp
->b_flags
, (B_ERROR
| B_INVAL
));
1279 /* undo B_DONE that was set before upl_commit() */
1280 CLR(bp
->b_flags
, B_DONE
);
1285 bufstats
.bufs_miss
++;
1287 kret
= ubc_upl_map(upl
, (vm_address_t
*)&(bp
->b_data
));
1288 if (kret
!= KERN_SUCCESS
) {
1289 panic("getblk: ubc_upl_map() "
1290 "failed with (%d)", kret
);
1292 if (bp
->b_data
== 0)
1293 panic("kernel_upl_map mapped 0");
1299 panic("getblk: paging operation 2");
1302 panic("getblk: %d unknown operation 3", operation
);
1308 if (bp
->b_data
== NULL
)
1309 panic("getblk: bp->b_addr is null");
1311 if (bp
->b_bufsize
& 0xfff) {
1312 if (ISSET(bp
->b_flags
, B_META
) && (bp
->b_bufsize
& 0x1ff))
1313 panic("getblk: bp->b_bufsize = %d", bp
->b_bufsize
);
1316 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_END
,
1317 (int)bp
, (int)bp
->b_data
, bp
->b_flags
, 3, 0);
1323 * Get an empty, disassociated buffer of given size.
1330 int queue
= BQ_EMPTY
;
1332 while ((bp
= getnewbuf(0, 0, &queue
)) == 0)
1334 SET(bp
->b_flags
, (B_META
|B_INVAL
));
1337 assert(queue
== BQ_EMPTY
);
1338 #endif /* DIAGNOSTIC */
1339 /* XXX need to implement logic to deal with other queues */
1341 binshash(bp
, &invalhash
);
1343 bufstats
.bufs_eblk
++;
1349 * Zones for the meta data buffers
1353 #define MAXMETA 4096
1355 struct meta_zone_entry
{
1362 struct meta_zone_entry meta_zones
[] = {
1363 {NULL
, (MINMETA
* 1), 128 * (MINMETA
* 1), "buf.512" },
1364 {NULL
, (MINMETA
* 2), 64 * (MINMETA
* 2), "buf.1024" },
1365 {NULL
, (MINMETA
* 4), 16 * (MINMETA
* 4), "buf.2048" },
1366 {NULL
, (MINMETA
* 8), 512 * (MINMETA
* 8), "buf.4096" },
1367 {NULL
, 0, 0, "" } /* End */
1371 * Initialize the meta data zones
1378 for (i
= 0; meta_zones
[i
].mz_size
!= 0; i
++) {
1379 meta_zones
[i
].mz_zone
=
1380 zinit(meta_zones
[i
].mz_size
,
1381 meta_zones
[i
].mz_max
,
1383 meta_zones
[i
].mz_name
);
1385 buf_hdr_zone
= zinit(sizeof(struct buf
), 32, PAGE_SIZE
, "buf headers");
1388 static __inline__ zone_t
1389 getbufzone(size_t size
)
1393 if ((size
% 512) || (size
< MINMETA
) || (size
> MAXMETA
))
1394 panic("getbufzone: incorect size = %d", size
);
1396 for (i
= 0; meta_zones
[i
].mz_size
!= 0; i
++) {
1397 if (meta_zones
[i
].mz_size
>= size
)
1401 return (meta_zones
[i
].mz_zone
);
1405 * With UBC, there is no need to expand / shrink the file data
1406 * buffer. The VM uses the same pages, hence no waste.
1407 * All the file data buffers can have one size.
1408 * In fact expand / shrink would be an expensive operation.
1410 * Only exception to this is meta-data buffers. Most of the
1411 * meta data operations are smaller than PAGE_SIZE. Having the
1412 * meta-data buffers grow and shrink as needed, optimizes use
1413 * of the kernel wired memory.
1421 vm_size_t desired_size
;
1423 desired_size
= roundup(size
, CLBYTES
);
1425 if(desired_size
< PAGE_SIZE
)
1426 desired_size
= PAGE_SIZE
;
1427 if (desired_size
> MAXBSIZE
)
1428 panic("allocbuf: buffer larger than MAXBSIZE requested");
1430 if (ISSET(bp
->b_flags
, B_META
)) {
1433 size_t nsize
= roundup(size
, MINMETA
);
1436 vm_offset_t elem
= (vm_offset_t
)bp
->b_data
;
1438 if (ISSET(bp
->b_flags
, B_ZALLOC
))
1439 if (bp
->b_bufsize
<= MAXMETA
) {
1440 if (bp
->b_bufsize
< nsize
) {
1441 /* reallocate to a bigger size */
1442 desired_size
= nsize
;
1444 zprev
= getbufzone(bp
->b_bufsize
);
1445 z
= getbufzone(nsize
);
1446 bp
->b_data
= (caddr_t
)zalloc(z
);
1448 panic("allocbuf: zalloc() returned NULL");
1449 bcopy(elem
, bp
->b_data
, bp
->b_bufsize
);
1452 desired_size
= bp
->b_bufsize
;
1455 panic("allocbuf: B_ZALLOC set incorrectly");
1457 if (bp
->b_bufsize
< desired_size
) {
1458 /* reallocate to a bigger size */
1459 kret
= kmem_alloc(kernel_map
, &bp
->b_data
, desired_size
);
1460 if (kret
!= KERN_SUCCESS
)
1461 panic("allocbuf: kmem_alloc() returned %d", kret
);
1463 panic("allocbuf: null b_data");
1464 bcopy(elem
, bp
->b_data
, bp
->b_bufsize
);
1465 kmem_free(kernel_map
, elem
, bp
->b_bufsize
);
1467 desired_size
= bp
->b_bufsize
;
1470 /* new allocation */
1471 if (nsize
<= MAXMETA
) {
1472 desired_size
= nsize
;
1473 z
= getbufzone(nsize
);
1474 bp
->b_data
= (caddr_t
)zalloc(z
);
1476 panic("allocbuf: zalloc() returned NULL 2");
1477 SET(bp
->b_flags
, B_ZALLOC
);
1479 kret
= kmem_alloc(kernel_map
, &bp
->b_data
, desired_size
);
1480 if (kret
!= KERN_SUCCESS
)
1481 panic("allocbuf: kmem_alloc() 2 returned %d", kret
);
1483 panic("allocbuf: null b_data 2");
1488 if (ISSET(bp
->b_flags
, B_META
) && (bp
->b_data
== 0))
1489 panic("allocbuf: bp->b_data is NULL, buf @ 0x%x", bp
);
1491 bp
->b_bufsize
= desired_size
;
1492 bp
->b_bcount
= size
;
1497 * Get a new buffer from one of the free lists.
1499 * Request for a queue is passes in. The queue from which the buffer was taken
1500 * from is returned. Out of range queue requests get BQ_EMPTY. Request for
1501 * BQUEUE means no preference. Use heuristics in that case.
1502 * Heuristics is as follows:
1503 * Try BQ_AGE, BQ_LRU, BQ_EMPTY, BQ_META in that order.
1504 * If none available block till one is made available.
1505 * If buffers available on both BQ_AGE and BQ_LRU, check the timestamps.
1506 * Pick the most stale buffer.
1507 * If found buffer was marked delayed write, start the async. write
1508 * and restart the search.
1509 * Initialize the fields and disassociate the buffer from the vnode.
1510 * Remove the buffer from the hash. Return the buffer and the queue
1511 * on which it was found.
1515 getnewbuf(slpflag
, slptimeo
, queue
)
1516 int slpflag
, slptimeo
;
1519 register struct buf
*bp
;
1520 register struct buf
*lru_bp
;
1521 register struct buf
*age_bp
;
1522 register struct buf
*meta_bp
;
1523 register int age_time
, lru_time
, bp_time
, meta_time
;
1525 int req
= *queue
; /* save it for restarts */
1530 /* invalid request gets empty queue */
1531 if ((*queue
> BQUEUES
) || (*queue
< 0)
1532 || (*queue
== BQ_LAUNDRY
) || (*queue
== BQ_LOCKED
))
1535 /* (*queue == BQUEUES) means no preference */
1536 if (*queue
!= BQUEUES
) {
1537 /* Try for the requested queue first */
1538 bp
= bufqueues
[*queue
].tqh_first
;
1543 /* Unable to use requested queue */
1544 age_bp
= bufqueues
[BQ_AGE
].tqh_first
;
1545 lru_bp
= bufqueues
[BQ_LRU
].tqh_first
;
1546 meta_bp
= bufqueues
[BQ_META
].tqh_first
;
1548 if (!age_bp
&& !lru_bp
&& !meta_bp
) {
1550 * Unavailble on AGE or LRU or META queues
1551 * Try the empty list first
1553 bp
= bufqueues
[BQ_EMPTY
].tqh_first
;
1559 /* Create a new temparory buffer header */
1560 bp
= (struct buf
*)zalloc(buf_hdr_zone
);
1565 binshash(bp
, &invalhash
);
1566 SET(bp
->b_flags
, B_HDRALLOC
);
1568 binsheadfree(bp
, &bufqueues
[BQ_EMPTY
], BQ_EMPTY
);
1573 /* Log this error condition */
1574 printf("getnewbuf: No useful buffers");
1576 /* wait for a free buffer of any kind */
1578 bufstats
.bufs_sleeps
++;
1579 tsleep(&needbuffer
, slpflag
|(PRIBIO
+1), "getnewbuf", slptimeo
);
1584 /* Buffer available either on AGE or LRU or META */
1588 /* Buffer available either on AGE or LRU */
1592 } else if (!lru_bp
) {
1595 } else { /* buffer available on both AGE and LRU */
1596 age_time
= time
.tv_sec
- age_bp
->b_timestamp
;
1597 lru_time
= time
.tv_sec
- lru_bp
->b_timestamp
;
1598 if ((age_time
< 0) || (lru_time
< 0)) { /* time set backwards */
1602 * we should probably re-timestamp eveything in the
1603 * queues at this point with the current time
1606 if ((lru_time
>= lru_is_stale
) && (age_time
< age_is_stale
)) {
1616 if (!bp
) { /* Neither on AGE nor on LRU */
1619 } else if (meta_bp
) {
1620 bp_time
= time
.tv_sec
- bp
->b_timestamp
;
1621 meta_time
= time
.tv_sec
- meta_bp
->b_timestamp
;
1623 if (!(bp_time
< 0) && !(meta_time
< 0)) {
1624 /* time not set backwards */
1626 bp_is_stale
= (*queue
== BQ_LRU
) ?
1627 lru_is_stale
: age_is_stale
;
1629 if ((meta_time
>= meta_is_stale
) &&
1630 (bp_time
< bp_is_stale
)) {
1638 panic("getnewbuf: null bp");
1641 if (ISSET(bp
->b_flags
, B_LOCKED
)) {
1642 panic("getnewbuf: bp @ 0x%x is LOCKED! (flags 0x%x)\n", bp
, bp
->b_flags
);
1645 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
1646 panic("getnewbuf: le_prev is deadbeef, buf @ 0x%x", bp
);
1648 if(ISSET(bp
->b_flags
, B_BUSY
))
1649 panic("getnewbuf reusing BUSY buf @ 0x%x", bp
);
1652 if (bcleanbuf(bp
)) {
1653 /* bawrite() issued, buffer not ready */
1662 #include <mach/mach_types.h>
1663 #include <mach/memory_object_types.h>
1664 #include <kern/sched_prim.h>
1668 * Returns 0 is buffer is ready to use,
1669 * Returns 1 if issued a bawrite() to indicate
1670 * that the buffer is not ready.
1673 bcleanbuf(struct buf
*bp
)
1681 /* Remove from the queue */
1684 /* Buffer is no longer on free lists. */
1685 SET(bp
->b_flags
, B_BUSY
);
1687 /* Check whether the buffer header was "allocated" */
1688 if (ISSET(bp
->b_flags
, B_HDRALLOC
))
1691 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
1692 panic("bcleanbuf: le_prev is deadbeef");
1695 * If buffer was a delayed write, start the IO by queuing
1696 * it on the LAUNDRY queue, and return 1
1698 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
1700 binstailfree(bp
, &bufqueues
[BQ_LAUNDRY
], BQ_LAUNDRY
);
1702 wakeup(&blaundrycnt
);
1703 /* and give it a chance to run */
1704 (void)thread_block(THREAD_CONTINUE_NULL
);
1715 if (ISSET(bp
->b_flags
, B_META
)) {
1716 vm_offset_t elem
= (vm_offset_t
)bp
->b_data
;
1718 panic("bcleanbuf: NULL bp->b_data B_META buffer");
1720 if (ISSET(bp
->b_flags
, B_ZALLOC
)) {
1721 if (bp
->b_bufsize
<= MAXMETA
) {
1724 z
= getbufzone(bp
->b_bufsize
);
1725 bp
->b_data
= (caddr_t
)0xdeadbeef;
1727 CLR(bp
->b_flags
, B_ZALLOC
);
1729 panic("bcleanbuf: B_ZALLOC set incorrectly");
1731 bp
->b_data
= (caddr_t
)0xdeadbeef;
1732 kmem_free(kernel_map
, elem
, bp
->b_bufsize
);
1736 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
1738 /* disassociate us from our vnode, if we had one... */
1741 /* clear out various other fields */
1744 bp
->b_flags
= B_BUSY
;
1746 SET(bp
->b_flags
, B_HDRALLOC
);
1748 bp
->b_blkno
= bp
->b_lblkno
= 0;
1753 bp
->b_dirtyoff
= bp
->b_dirtyend
= 0;
1754 bp
->b_validoff
= bp
->b_validend
= 0;
1756 /* nuke any credentials we were holding */
1758 if (cred
!= NOCRED
) {
1759 bp
->b_rcred
= NOCRED
;
1763 if (cred
!= NOCRED
) {
1764 bp
->b_wcred
= NOCRED
;
1773 * Wait for operations on the buffer to complete.
1774 * When they do, extract and return the I/O's error value.
1783 while (!ISSET(bp
->b_flags
, B_DONE
))
1784 tsleep(bp
, PRIBIO
+ 1, "biowait", 0);
1787 /* check for interruption of I/O (e.g. via NFS), then errors. */
1788 if (ISSET(bp
->b_flags
, B_EINTR
)) {
1789 CLR(bp
->b_flags
, B_EINTR
);
1791 } else if (ISSET(bp
->b_flags
, B_ERROR
))
1792 return (bp
->b_error
? bp
->b_error
: EIO
);
1798 * Mark I/O complete on a buffer.
1800 * If a callback has been requested, e.g. the pageout
1801 * daemon, do so. Otherwise, awaken waiting processes.
1803 * [ Leffler, et al., says on p.247:
1804 * "This routine wakes up the blocked process, frees the buffer
1805 * for an asynchronous write, or, for a request by the pagedaemon
1806 * process, invokes a procedure specified in the buffer structure" ]
1808 * In real life, the pagedaemon (or other system processes) wants
1809 * to do async stuff to, and doesn't want the buffer brelse()'d.
1810 * (for swap pager, that puts swap buffers on the free lists (!!!),
1811 * for the vn device, that puts malloc'd buffers on the free lists!)
1817 boolean_t funnel_state
;
1820 funnel_state
= thread_funnel_set(kernel_flock
, TRUE
);
1822 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 387)) | DBG_FUNC_START
,
1823 (int)bp
, (int)bp
->b_data
, bp
->b_flags
, 0, 0);
1825 if (ISSET(bp
->b_flags
, B_DONE
))
1826 panic("biodone already");
1827 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
1829 * I/O was done, so don't believe
1830 * the DIRTY state from VM anymore
1832 CLR(bp
->b_flags
, B_WASDIRTY
);
1834 if (!ISSET(bp
->b_flags
, B_READ
) && !ISSET(bp
->b_flags
, B_RAW
))
1835 vwakeup(bp
); /* wake up reader */
1837 if (kdebug_enable
) {
1838 int code
= DKIO_DONE
;
1840 if (bp
->b_flags
& B_READ
)
1842 if (bp
->b_flags
& B_ASYNC
)
1845 if (bp
->b_flags
& B_META
)
1847 else if (bp
->b_flags
& (B_PGIN
| B_PAGEOUT
))
1848 code
|= DKIO_PAGING
;
1850 KERNEL_DEBUG_CONSTANT(FSDBG_CODE(DBG_DKRW
, code
) | DBG_FUNC_NONE
,
1851 bp
, bp
->b_vp
, bp
->b_resid
, bp
->b_error
, 0);
1854 /* Wakeup the throttled write operations as needed */
1857 && (vp
->v_flag
& VTHROTTLED
)
1858 && (vp
->v_numoutput
<= (BUFWRITE_THROTTLE
/ 3))) {
1859 vp
->v_flag
&= ~VTHROTTLED
;
1860 wakeup((caddr_t
)&vp
->v_numoutput
);
1863 if (ISSET(bp
->b_flags
, B_CALL
)) { /* if necessary, call out */
1864 void (*iodone_func
)(struct buf
*) = bp
->b_iodone
;
1866 CLR(bp
->b_flags
, B_CALL
); /* but note callout done */
1867 bp
->b_iodone
= NULL
;
1869 if (iodone_func
== NULL
) {
1870 panic("biodone: bp @ 0x%x has NULL b_iodone!\n", bp
);
1874 } else if (ISSET(bp
->b_flags
, B_ASYNC
)) /* if async, release it */
1876 else { /* or just wakeup the buffer */
1877 CLR(bp
->b_flags
, B_WANTED
);
1881 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 387)) | DBG_FUNC_END
,
1882 (int)bp
, (int)bp
->b_data
, bp
->b_flags
, 0, 0);
1884 thread_funnel_set(kernel_flock
, funnel_state
);
1888 * Return a count of buffers on the "locked" queue.
1893 register struct buf
*bp
;
1896 for (bp
= bufqueues
[BQ_LOCKED
].tqh_first
; bp
;
1897 bp
= bp
->b_freelist
.tqe_next
)
1903 * Return a count of 'busy' buffers. Used at the time of shutdown.
1906 count_busy_buffers()
1908 register struct buf
*bp
;
1909 register int nbusy
= 0;
1911 for (bp
= &buf
[nbuf
]; --bp
>= buf
; )
1912 if ((bp
->b_flags
& (B_BUSY
|B_INVAL
)) == B_BUSY
)
1919 * Print out statistics on the current allocation of the buffer pool.
1920 * Can be enabled to print out on every ``sync'' by setting "syncprt"
1921 * in vfs_syscalls.c using sysctl.
1927 register struct buf
*bp
;
1928 register struct bqueues
*dp
;
1929 int counts
[MAXBSIZE
/CLBYTES
+1];
1930 static char *bname
[BQUEUES
] =
1931 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
1933 for (dp
= bufqueues
, i
= 0; dp
< &bufqueues
[BQUEUES
]; dp
++, i
++) {
1935 for (j
= 0; j
<= MAXBSIZE
/CLBYTES
; j
++)
1938 for (bp
= dp
->tqh_first
; bp
; bp
= bp
->b_freelist
.tqe_next
) {
1939 counts
[bp
->b_bufsize
/CLBYTES
]++;
1943 printf("%s: total-%d", bname
[i
], count
);
1944 for (j
= 0; j
<= MAXBSIZE
/CLBYTES
; j
++)
1946 printf(", %d-%d", j
* CLBYTES
, counts
[j
]);
1950 #endif /* DIAGNOSTIC */
1952 #define NRESERVEDIOBUFS 64
1954 __private_extern__
struct buf
*
1955 alloc_io_buf(vp
, priv
)
1959 register struct buf
*bp
;
1964 while (niobuf
- NRESERVEDIOBUFS
< bufstats
.bufs_iobufinuse
&& !priv
) {
1966 bufstats
.bufs_iobufsleeps
++;
1967 (void) tsleep(&need_iobuffer
, (PRIBIO
+1), "alloc_io_buf", 0);
1970 while ((bp
= iobufqueue
.tqh_first
) == NULL
) {
1972 bufstats
.bufs_iobufsleeps
++;
1973 (void) tsleep(&need_iobuffer
, (PRIBIO
+1), "alloc_io_buf1", 0);
1976 TAILQ_REMOVE(&iobufqueue
, bp
, b_freelist
);
1977 bp
->b_timestamp
= 0;
1979 /* clear out various fields */
1980 bp
->b_flags
= B_BUSY
;
1981 bp
->b_blkno
= bp
->b_lblkno
= 0;
1990 if (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
)
1991 bp
->b_dev
= vp
->v_rdev
;
1994 bufstats
.bufs_iobufinuse
++;
1995 if (bufstats
.bufs_iobufinuse
> bufstats
.bufs_iobufmax
)
1996 bufstats
.bufs_iobufmax
= bufstats
.bufs_iobufinuse
;
2002 __private_extern__
void
2009 /* put buffer back on the head of the iobufqueue */
2011 bp
->b_flags
= B_INVAL
;
2013 binsheadfree(bp
, &iobufqueue
, -1);
2015 /* Wake up any processes waiting for any buffer to become free. */
2016 if (need_iobuffer
) {
2018 wakeup(&need_iobuffer
);
2020 bufstats
.bufs_iobufinuse
--;
2024 /* disabled for now */
2026 /* XXX move this to a separate file */
2028 * Dynamic Scaling of the Buffer Queues
2031 typedef long long blsize_t
;
2033 blsize_t MAXNBUF
; /* initialize to (mem_size / PAGE_SIZE) */
2034 /* Global tunable limits */
2035 blsize_t nbufh
; /* number of buffer headers */
2036 blsize_t nbuflow
; /* minimum number of buffer headers required */
2037 blsize_t nbufhigh
; /* maximum number of buffer headers allowed */
2038 blsize_t nbuftarget
; /* preferred number of buffer headers */
2043 * 1. 0 < nbuflow <= nbufh <= nbufhigh
2044 * 2. nbufhigh <= MAXNBUF
2045 * 3. 0 < nbuflow <= nbuftarget <= nbufhigh
2046 * 4. nbufh can not be set by sysctl().
2049 /* Per queue tunable limits */
2052 blsize_t bl_nlow
; /* minimum number of buffer headers required */
2053 blsize_t bl_num
; /* number of buffer headers on the queue */
2054 blsize_t bl_nlhigh
; /* maximum number of buffer headers allowed */
2055 blsize_t bl_target
; /* preferred number of buffer headers */
2056 long bl_stale
; /* Seconds after which a buffer is considered stale */
2062 * 1. 0 <= bl_nlow <= bl_num <= bl_nlhigh
2063 * 2. bl_nlhigh <= MAXNBUF
2064 * 3. bufqlim[BQ_META].bl_nlow != 0
2065 * 4. bufqlim[BQ_META].bl_nlow > (number of possible concurrent
2066 * file system IO operations)
2067 * 5. bl_num can not be set by sysctl().
2068 * 6. bl_nhigh <= nbufhigh
2074 * Defining it blsize_t as long permits 2^31 buffer headers per queue.
2075 * Which can describe (2^31 * PAGE_SIZE) memory per queue.
2077 * These limits are exported to by means of sysctl().
2078 * It was decided to define blsize_t as a 64 bit quantity.
2079 * This will make sure that we will not be required to change it
2080 * as long as we do not exceed 64 bit address space for the kernel.
2082 * low and high numbers parameters initialized at compile time
2083 * and boot arguments can be used to override them. sysctl()
2084 * would not change the value. sysctl() can get all the values
2085 * but can set only target. num is the current level.
2087 * Advantages of having a "bufqscan" thread doing the balancing are,
2088 * Keep enough bufs on BQ_EMPTY.
2089 * getnewbuf() by default will always select a buffer from the BQ_EMPTY.
2090 * getnewbuf() perfoms best if a buffer was found there.
2091 * Also this minimizes the possibility of starting IO
2092 * from getnewbuf(). That's a performance win, too.
2094 * Localize complex logic [balancing as well as time aging]
2097 * Simplify getnewbuf() logic by elimination of time aging code.
2103 * The goal of the dynamic scaling of the buffer queues to to keep
2104 * the size of the LRU close to bl_target. Buffers on a queue would
2107 * There would be a thread which will be responsible for "balancing"
2108 * the buffer cache queues.
2110 * The scan order would be: AGE, LRU, META, EMPTY.
2113 long bufqscanwait
= 0;
2115 static void bufqscan_thread();
2116 static int balancebufq(int q
);
2117 static int btrimempty(int n
);
2118 static __inline__
int initbufqscan(void);
2119 static __inline__
int nextbufq(int q
);
2120 static void buqlimprt(int all
);
2123 bufq_balance_thread_init()
2126 if (bufqscanwait
++ == 0) {
2128 /* Initalize globals */
2129 MAXNBUF
= (mem_size
/ PAGE_SIZE
);
2131 nbuflow
= min(nbufh
, 100);
2132 nbufhigh
= min(MAXNBUF
, max(nbufh
, 2048));
2133 nbuftarget
= (mem_size
>> 5) / PAGE_SIZE
;
2134 nbuftarget
= max(nbuflow
, nbuftarget
);
2135 nbuftarget
= min(nbufhigh
, nbuftarget
);
2138 * Initialize the bufqlim
2142 bufqlim
[BQ_LOCKED
].bl_nlow
= 0;
2143 bufqlim
[BQ_LOCKED
].bl_nlhigh
= 32;
2144 bufqlim
[BQ_LOCKED
].bl_target
= 0;
2145 bufqlim
[BQ_LOCKED
].bl_stale
= 30;
2148 bufqlim
[BQ_LRU
].bl_nlow
= 0;
2149 bufqlim
[BQ_LRU
].bl_nlhigh
= nbufhigh
/4;
2150 bufqlim
[BQ_LRU
].bl_target
= nbuftarget
/4;
2151 bufqlim
[BQ_LRU
].bl_stale
= LRU_IS_STALE
;
2154 bufqlim
[BQ_AGE
].bl_nlow
= 0;
2155 bufqlim
[BQ_AGE
].bl_nlhigh
= nbufhigh
/4;
2156 bufqlim
[BQ_AGE
].bl_target
= nbuftarget
/4;
2157 bufqlim
[BQ_AGE
].bl_stale
= AGE_IS_STALE
;
2160 bufqlim
[BQ_EMPTY
].bl_nlow
= 0;
2161 bufqlim
[BQ_EMPTY
].bl_nlhigh
= nbufhigh
/4;
2162 bufqlim
[BQ_EMPTY
].bl_target
= nbuftarget
/4;
2163 bufqlim
[BQ_EMPTY
].bl_stale
= 600000;
2166 bufqlim
[BQ_META
].bl_nlow
= 0;
2167 bufqlim
[BQ_META
].bl_nlhigh
= nbufhigh
/4;
2168 bufqlim
[BQ_META
].bl_target
= nbuftarget
/4;
2169 bufqlim
[BQ_META
].bl_stale
= META_IS_STALE
;
2172 bufqlim
[BQ_LOCKED
].bl_nlow
= 0;
2173 bufqlim
[BQ_LOCKED
].bl_nlhigh
= 32;
2174 bufqlim
[BQ_LOCKED
].bl_target
= 0;
2175 bufqlim
[BQ_LOCKED
].bl_stale
= 30;
2180 /* create worker thread */
2181 kernel_thread(kernel_task
, bufqscan_thread
);
2184 /* The workloop for the buffer balancing thread */
2188 boolean_t funnel_state
;
2191 funnel_state
= thread_funnel_set(kernel_flock
, TRUE
);
2195 int q
; /* buffer queue to process */
2199 moretodo
|= balancebufq(q
);
2208 (void)tsleep((void *)&bufqscanwait
, PRIBIO
, "bufqscanwait", 60 * hz
);
2212 (void) thread_funnel_set(kernel_flock
, FALSE
);
2215 /* Seed for the buffer queue balancing */
2216 static __inline__
int
2219 /* Start with AGE queue */
2223 /* Pick next buffer queue to balance */
2224 static __inline__
int
2227 int order
[] = { BQ_AGE
, BQ_LRU
, BQ_META
, BQ_EMPTY
, 0 };
2234 /* function to balance the buffer queues */
2242 /* reject invalid q */
2243 if ((q
< 0) || (q
>= BQUEUES
))
2246 /* LOCKED or LAUNDRY queue MUST not be balanced */
2247 if ((q
== BQ_LOCKED
) || (q
== BQ_LAUNDRY
))
2250 n
= (bufqlim
[q
].bl_num
- bufqlim
[q
].bl_target
);
2252 /* If queue has less than target nothing more to do */
2257 /* Balance only a small amount (12.5%) at a time */
2261 /* EMPTY queue needs special handling */
2262 if (q
== BQ_EMPTY
) {
2263 moretodo
|= btrimempty(n
);
2267 for (; n
> 0; n
--) {
2268 struct buf
*bp
= bufqueues
[q
].tqh_first
;
2272 /* check if it's stale */
2273 if ((time
.tv_sec
- bp
->b_timestamp
) > bufqlim
[q
].bl_stale
) {
2274 if (bcleanbuf(bp
)) {
2275 /* bawrite() issued, bp not ready */
2278 /* release the cleaned buffer to BQ_EMPTY */
2279 SET(bp
->b_flags
, B_INVAL
);
2295 * When struct buf are allocated dynamically, this would
2296 * reclaim upto 'n' struct buf from the empty queue.
2302 static __inline__
void
2305 if ((q
< 0) || (q
>= BQUEUES
))
2308 bufqlim
[q
].bl_num
++;
2312 static __inline__
void
2315 if ((q
< 0) || (q
>= BQUEUES
))
2318 bufqlim
[q
].bl_num
--;
2326 static char *bname
[BQUEUES
] =
2327 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
2330 for (i
= 0; i
< BQUEUES
; i
++) {
2331 printf("%s : ", bname
[i
]);
2332 printf("min = %ld, ", (long)bufqlim
[i
].bl_nlow
);
2333 printf("cur = %ld, ", (long)bufqlim
[i
].bl_num
);
2334 printf("max = %ld, ", (long)bufqlim
[i
].bl_nlhigh
);
2335 printf("target = %ld, ", (long)bufqlim
[i
].bl_target
);
2336 printf("stale after %ld seconds\n", bufqlim
[i
].bl_stale
);
2339 for (i
= 0; i
< BQUEUES
; i
++) {
2340 printf("%s : ", bname
[i
]);
2341 printf("cur = %ld, ", (long)bufqlim
[i
].bl_num
);
2346 * If the getnewbuf() calls bcleanbuf() on the same thread
2347 * there is a potential for stack overrun and deadlocks.
2348 * So we always handoff the work to worker thread for completion
2352 bcleanbuf_thread_init()
2354 static void bcleanbuf_thread();
2356 /* create worker thread */
2357 kernel_thread(kernel_task
, bcleanbuf_thread
);
2363 boolean_t funnel_state
;
2368 funnel_state
= thread_funnel_set(kernel_flock
, TRUE
);
2371 while (blaundrycnt
== 0)
2372 (void)tsleep((void *)&blaundrycnt
, PRIBIO
, "blaundry", 60 * hz
);
2373 bp
= TAILQ_FIRST(&bufqueues
[BQ_LAUNDRY
]);
2374 /* Remove from the queue */
2378 error
= bawrite_internal(bp
, 0);
2380 binstailfree(bp
, &bufqueues
[BQ_LAUNDRY
], BQ_LAUNDRY
);
2383 (void)tsleep((void *)&blaundrycnt
, PRIBIO
, "blaundry", 1);
2386 (void)thread_block(THREAD_CONTINUE_NULL
);
2393 (void) thread_funnel_set(kernel_flock
, funnel_state
);
2398 bp_cmp(void *a
, void *b
)
2400 struct buf
*bp_a
= *(struct buf
**)a
,
2401 *bp_b
= *(struct buf
**)b
;
2404 // don't have to worry about negative block
2405 // numbers so this is ok to do.
2407 res
= (bp_a
->b_blkno
- bp_b
->b_blkno
);
2415 bflushq(int whichq
, struct mount
*mp
)
2417 struct buf
*bp
, *next
;
2418 int i
, buf_count
, s
;
2419 int counter
=0, total_writes
=0;
2420 static struct buf
*flush_table
[NFLUSH
];
2422 if (whichq
< 0 || whichq
>= BQUEUES
) {
2428 bp
= TAILQ_FIRST(&bufqueues
[whichq
]);
2429 for(buf_count
=0; bp
; bp
=next
) {
2430 next
= bp
->b_freelist
.tqe_next
;
2432 if (bp
->b_vp
== NULL
|| bp
->b_vp
->v_mount
!= mp
) {
2436 if ((bp
->b_flags
& B_DELWRI
) && (bp
->b_flags
& B_BUSY
) == 0) {
2437 if (whichq
!= BQ_LOCKED
&& (bp
->b_flags
& B_LOCKED
)) {
2438 panic("bflushq: bp @ 0x%x is locked!\n", bp
);
2442 bp
->b_flags
|= B_BUSY
;
2443 flush_table
[buf_count
] = bp
;
2447 if (buf_count
>= NFLUSH
) {
2448 qsort(flush_table
, buf_count
, sizeof(struct buf
*), bp_cmp
);
2450 for(i
=0; i
< buf_count
; i
++) {
2451 bawrite(flush_table
[i
]);
2459 if (buf_count
> 0) {
2460 qsort(flush_table
, buf_count
, sizeof(struct buf
*), bp_cmp
);
2461 for(i
=0; i
< buf_count
; i
++) {
2462 bawrite(flush_table
[i
]);
2466 return total_writes
;