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 int do_breadn_for_type(struct vnode
*vp
, daddr_t blkno
, int size
, daddr_t
*rablks
,
99 int *rasizes
, int nrablks
, struct ucred
*cred
, struct buf
**bpp
, int queuetype
);
100 static struct buf
*getnewbuf(int slpflag
, int slptimeo
, int *queue
);
101 static int bcleanbuf(struct buf
*bp
);
102 static int brecover_data(struct buf
*bp
);
103 extern void vwakeup();
105 extern int niobuf
; /* The number of IO buffer headers for cluster IO */
108 /* zone allocated buffer headers */
109 static zone_t buf_hdr_zone
;
110 static int buf_hdr_count
;
113 struct proc
*traceproc
;
114 int tracewhich
, tracebuf
[TRCSIZ
];
116 char traceflags
[TR_NFLAGS
];
120 * Definitions for the buffer hash lists.
122 #define BUFHASH(dvp, lbn) \
123 (&bufhashtbl[((long)(dvp) / sizeof(*(dvp)) + (int)(lbn)) & bufhash])
124 LIST_HEAD(bufhashhdr
, buf
) *bufhashtbl
, invalhash
;
127 /* Definitions for the buffer stats. */
128 struct bufstats bufstats
;
130 /* Number of delayed write buffers */
134 * Insq/Remq for the buffer hash lists.
137 #define binshash(bp, dp) LIST_INSERT_HEAD(dp, bp, b_hash)
138 #define bremhash(bp) LIST_REMOVE(bp, b_hash)
142 TAILQ_HEAD(ioqueue
, buf
) iobufqueue
;
143 TAILQ_HEAD(bqueues
, buf
) bufqueues
[BQUEUES
];
144 static int needbuffer
;
145 static int need_iobuffer
;
148 * Insq/Remq for the buffer free lists.
150 #define binsheadfree(bp, dp, whichq) do { \
151 TAILQ_INSERT_HEAD(dp, bp, b_freelist); \
153 (bp)->b_whichq = whichq; \
154 (bp)->b_timestamp = time.tv_sec; \
157 #define binstailfree(bp, dp, whichq) do { \
158 TAILQ_INSERT_TAIL(dp, bp, b_freelist); \
160 (bp)->b_whichq = whichq; \
161 (bp)->b_timestamp = time.tv_sec; \
164 #define BHASHENTCHECK(bp) \
165 if ((bp)->b_hash.le_prev != (struct buf **)0xdeadbeef) \
166 panic("%x: b_hash.le_prev is not deadbeef", (bp));
168 #define BLISTNONE(bp) \
169 (bp)->b_hash.le_next = (struct buf *)0; \
170 (bp)->b_hash.le_prev = (struct buf **)0xdeadbeef;
173 * Insq/Remq for the vnode usage lists.
175 #define bufinsvn(bp, dp) LIST_INSERT_HEAD(dp, bp, b_vnbufs)
176 #define bufremvn(bp) { \
177 LIST_REMOVE(bp, b_vnbufs); \
178 (bp)->b_vnbufs.le_next = NOLIST; \
181 simple_lock_data_t bufhashlist_slock
; /* lock on buffer hash list */
183 /* number of per vnode, "in flight" buffer writes */
184 #define BUFWRITE_THROTTLE 9
188 * Time in seconds before a buffer on a list is
189 * considered as a stale buffer
191 #define LRU_IS_STALE 120 /* default value for the LRU */
192 #define AGE_IS_STALE 60 /* default value for the AGE */
193 #define META_IS_STALE 180 /* default value for the BQ_META */
195 int lru_is_stale
= LRU_IS_STALE
;
196 int age_is_stale
= AGE_IS_STALE
;
197 int meta_is_stale
= META_IS_STALE
;
199 /* LIST_INSERT_HEAD() with assertions */
200 static __inline__
void
201 blistenterhead(struct bufhashhdr
* head
, struct buf
* bp
)
203 if ((bp
->b_hash
.le_next
= (head
)->lh_first
) != NULL
)
204 (head
)->lh_first
->b_hash
.le_prev
= &(bp
)->b_hash
.le_next
;
205 (head
)->lh_first
= bp
;
206 bp
->b_hash
.le_prev
= &(head
)->lh_first
;
207 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
208 panic("blistenterhead: le_prev is deadbeef");
211 static __inline__
void
212 binshash(struct buf
*bp
, struct bufhashhdr
*dp
)
216 simple_lock(&bufhashlist_slock
);
219 if((bad
= incore(bp
->b_vp
, bp
->b_lblkno
)))
220 panic("binshash: already incore bp 0x%x, bad 0x%x\n", bp
, bad
);
226 for(; nbp
!= NULL
; nbp
= nbp
->b_hash
.le_next
) {
228 panic("buf already in hashlist");
231 blistenterhead(dp
, bp
);
232 simple_unlock(&bufhashlist_slock
);
235 static __inline__
void
236 bremhash(struct buf
*bp
)
238 simple_lock(&bufhashlist_slock
);
239 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
240 panic("bremhash le_prev is deadbeef");
241 if (bp
->b_hash
.le_next
== bp
)
242 panic("bremhash: next points to self");
244 if (bp
->b_hash
.le_next
!= NULL
)
245 bp
->b_hash
.le_next
->b_hash
.le_prev
= bp
->b_hash
.le_prev
;
246 *bp
->b_hash
.le_prev
= (bp
)->b_hash
.le_next
;
247 simple_unlock(&bufhashlist_slock
);
251 * Remove a buffer from the free list it's on
257 struct bqueues
*dp
= NULL
;
261 * We only calculate the head of the freelist when removing
262 * the last element of the list as that is the only time that
263 * it is needed (e.g. to reset the tail pointer).
265 * NB: This makes an assumption about how tailq's are implemented.
267 if (bp
->b_freelist
.tqe_next
== NULL
) {
268 for (dp
= bufqueues
; dp
< &bufqueues
[BQUEUES
]; dp
++)
269 if (dp
->tqh_last
== &bp
->b_freelist
.tqe_next
)
271 if (dp
== &bufqueues
[BQUEUES
])
272 panic("bremfree: lost tail");
274 TAILQ_REMOVE(dp
, bp
, b_freelist
);
275 whichq
= bp
->b_whichq
;
282 * Associate a buffer with a vnode.
286 register struct vnode
*vp
;
287 register struct buf
*bp
;
291 panic("bgetvp: not free");
294 if (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
)
295 bp
->b_dev
= vp
->v_rdev
;
299 * Insert onto list for new vnode.
301 bufinsvn(bp
, &vp
->v_cleanblkhd
);
305 * Disassociate a buffer from a vnode.
309 register struct buf
*bp
;
313 if (bp
->b_vp
== (struct vnode
*) 0)
314 panic("brelvp: NULL vp");
316 * Delete from old vnode list, if on one.
318 if (bp
->b_vnbufs
.le_next
!= NOLIST
)
321 bp
->b_vp
= (struct vnode
*) 0;
326 * Reassign a buffer from one vnode to another.
327 * Used to assign file specific control information
328 * (indirect blocks) to the vnode to which they belong.
331 reassignbuf(bp
, newvp
)
332 register struct buf
*bp
;
333 register struct vnode
*newvp
;
335 register struct buflists
*listheadp
;
338 printf("reassignbuf: NULL");
342 * Delete from old vnode list, if on one.
344 if (bp
->b_vnbufs
.le_next
!= NOLIST
)
347 * If dirty, put on list of dirty buffers;
348 * otherwise insert onto list of clean buffers.
350 if (ISSET(bp
->b_flags
, B_DELWRI
))
351 listheadp
= &newvp
->v_dirtyblkhd
;
353 listheadp
= &newvp
->v_cleanblkhd
;
354 bufinsvn(bp
, listheadp
);
357 static __inline__
void
358 bufhdrinit(struct buf
*bp
)
360 bzero((char *)bp
, sizeof *bp
);
362 bp
->b_rcred
= NOCRED
;
363 bp
->b_wcred
= NOCRED
;
364 bp
->b_vnbufs
.le_next
= NOLIST
;
365 bp
->b_flags
= B_INVAL
;
371 * Initialize buffers and hash links for buffers.
373 __private_extern__
void
376 register struct buf
*bp
;
377 register struct bqueues
*dp
;
381 static void bufzoneinit();
382 static void bcleanbuf_thread_init();
384 /* Initialize the buffer queues ('freelists') and the hash table */
385 for (dp
= bufqueues
; dp
< &bufqueues
[BQUEUES
]; dp
++)
387 bufhashtbl
= hashinit(nbuf
, M_CACHE
, &bufhash
);
389 simple_lock_init(&bufhashlist_slock
);
391 metabuf
= nbuf
/8; /* reserved for meta buf */
393 /* Initialize the buffer headers */
394 for (i
= 0; i
< nbuf
; i
++) {
399 * metabuf buffer headers on the meta-data list and
400 * rest of the buffer headers on the empty list
408 dp
= &bufqueues
[whichq
];
409 binsheadfree(bp
, dp
, whichq
);
410 binshash(bp
, &invalhash
);
413 for (; i
< nbuf
+ niobuf
; i
++) {
416 binsheadfree(bp
, &iobufqueue
, -1);
419 printf("using %d buffer headers and %d cluster IO buffer headers\n",
422 /* Set up zones used by the buffer cache */
425 /* start the bcleanbuf() thread */
426 bcleanbuf_thread_init();
430 static void bufq_balance_thread_init();
431 /* create a thread to do dynamic buffer queue balancing */
432 bufq_balance_thread_init();
438 bio_doread(vp
, blkno
, size
, cred
, async
, queuetype
)
446 register struct buf
*bp
;
447 struct proc
*p
= current_proc();
449 bp
= getblk(vp
, blkno
, size
, 0, 0, queuetype
);
452 * If buffer does not have data valid, start a read.
453 * Note that if buffer is B_INVAL, getblk() won't return it.
454 * Therefore, it's valid if it's I/O has completed or been delayed.
456 if (!ISSET(bp
->b_flags
, (B_DONE
| B_DELWRI
))) {
457 /* Start I/O for the buffer (keeping credentials). */
458 SET(bp
->b_flags
, B_READ
| async
);
459 if (cred
!= NOCRED
&& bp
->b_rcred
== NOCRED
) {
461 * NFS has embedded ucred.
462 * Can not crhold() here as that causes zone corruption
464 bp
->b_rcred
= crdup(cred
);
469 trace(TR_BREADMISS
, pack(vp
, size
), blkno
);
471 /* Pay for the read. */
473 p
->p_stats
->p_ru
.ru_inblock
++; /* XXX */
478 trace(TR_BREADHIT
, pack(vp
, size
), blkno
);
484 * This algorithm described in Bach (p.54).
487 bread(vp
, blkno
, size
, cred
, bpp
)
494 register struct buf
*bp
;
496 /* Get buffer for block. */
497 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, BLK_READ
);
499 /* Wait for the read to complete, and return result. */
500 return (biowait(bp
));
504 * Read a disk block. [bread() for meta-data]
505 * This algorithm described in Bach (p.54).
508 meta_bread(vp
, blkno
, size
, cred
, bpp
)
515 register struct buf
*bp
;
517 /* Get buffer for block. */
518 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, BLK_META
);
520 /* Wait for the read to complete, and return result. */
521 return (biowait(bp
));
525 * Read-ahead multiple disk blocks. The first is sync, the rest async.
528 breadn(vp
, blkno
, size
, rablks
, rasizes
, nrablks
, cred
, bpp
)
530 daddr_t blkno
; int size
;
531 daddr_t rablks
[]; int rasizes
[];
536 return (do_breadn_for_type(vp
, blkno
, size
, rablks
, rasizes
, nrablks
, cred
, bpp
, BLK_READ
));
540 * Read-ahead multiple disk blocks. The first is sync, the rest async.
541 * [breadn() for meta-data]
544 meta_breadn(vp
, blkno
, size
, rablks
, rasizes
, nrablks
, cred
, bpp
)
546 daddr_t blkno
; int size
;
547 daddr_t rablks
[]; int rasizes
[];
552 return (do_breadn_for_type(vp
, blkno
, size
, rablks
, rasizes
, nrablks
, cred
, bpp
, BLK_META
));
556 * Perform the reads for breadn() and meta_breadn().
557 * Trivial modification to the breada algorithm presented in Bach (p.55).
560 do_breadn_for_type(struct vnode
*vp
, daddr_t blkno
, int size
, daddr_t
*rablks
, int *rasizes
,
561 int nrablks
, struct ucred
*cred
, struct buf
**bpp
, int queuetype
)
563 register struct buf
*bp
;
566 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, queuetype
);
569 * For each of the read-ahead blocks, start a read, if necessary.
571 for (i
= 0; i
< nrablks
; i
++) {
572 /* If it's in the cache, just go on to next one. */
573 if (incore(vp
, rablks
[i
]))
576 /* Get a buffer for the read-ahead block */
577 (void) bio_doread(vp
, rablks
[i
], rasizes
[i
], cred
, B_ASYNC
, queuetype
);
580 /* Otherwise, we had to start a read for it; wait until it's valid. */
581 return (biowait(bp
));
585 * Read with single-block read-ahead. Defined in Bach (p.55), but
586 * implemented as a call to breadn().
587 * XXX for compatibility with old file systems.
590 breada(vp
, blkno
, size
, rablkno
, rabsize
, cred
, bpp
)
592 daddr_t blkno
; int size
;
593 daddr_t rablkno
; int rabsize
;
598 return (breadn(vp
, blkno
, size
, &rablkno
, &rabsize
, 1, cred
, bpp
));
602 * Block write. Described in Bach (p.56)
608 int rv
, sync
, wasdelayed
;
609 struct proc
*p
= current_proc();
610 struct vnode
*vp
= bp
->b_vp
;
612 if (bp
->b_data
== 0) {
613 if (brecover_data(bp
) == 0)
616 /* Remember buffer type, to switch on it later. */
617 sync
= !ISSET(bp
->b_flags
, B_ASYNC
);
618 wasdelayed
= ISSET(bp
->b_flags
, B_DELWRI
);
619 CLR(bp
->b_flags
, (B_READ
| B_DONE
| B_ERROR
| B_DELWRI
));
622 wakeup((caddr_t
)&nbdwrite
);
627 * If not synchronous, pay for the I/O operation and make
628 * sure the buf is on the correct vnode queue. We have
629 * to do this now, because if we don't, the vnode may not
630 * be properly notified that its I/O has completed.
636 p
->p_stats
->p_ru
.ru_oublock
++; /* XXX */
639 trace(TR_BUFWRITE
, pack(vp
, bp
->b_bcount
), bp
->b_lblkno
);
641 /* Initiate disk write. Make sure the appropriate party is charged. */
642 SET(bp
->b_flags
, B_WRITEINPROG
);
649 * If I/O was synchronous, wait for it to complete.
654 * Pay for the I/O operation, if it's not been paid for, and
655 * make sure it's on the correct vnode queue. (async operatings
656 * were payed for above.)
662 p
->p_stats
->p_ru
.ru_oublock
++; /* XXX */
664 /* Release the buffer. */
665 // XXXdbg - only if the unused bit is set
666 if (!ISSET(bp
->b_flags
, B_NORELSE
)) {
669 CLR(bp
->b_flags
, B_NORELSE
);
680 struct vop_bwrite_args
*ap
;
682 return (bwrite(ap
->a_bp
));
688 * The buffer is marked dirty, but is not queued for I/O.
689 * This routine should be used when the buffer is expected
690 * to be modified again soon, typically a small write that
691 * partially fills a buffer.
693 * NB: magnetic tapes cannot be delayed; they must be
694 * written in the order that the writes are requested.
696 * Described in Leffler, et al. (pp. 208-213).
698 * Note: With the abilitty to allocate additional buffer
699 * headers, we can get in to the situation where "too" many
700 * bdwrite()s can create situation where the kernel can create
701 * buffers faster than the disks can service. Doing a bawrite() in
702 * cases were we have "too many" outstanding bdwrite()s avoids that.
704 __private_extern__
int
705 bdwrite_internal(bp
, return_error
)
709 struct proc
*p
= current_proc();
710 struct vnode
*vp
= bp
->b_vp
;
713 * If the block hasn't been seen before:
714 * (1) Mark it as having been seen,
715 * (2) Charge for the write.
716 * (3) Make sure it's on its vnode's correct block list,
718 if (!ISSET(bp
->b_flags
, B_DELWRI
)) {
719 SET(bp
->b_flags
, B_DELWRI
);
721 p
->p_stats
->p_ru
.ru_oublock
++; /* XXX */
726 /* If this is a tape block, write it the block now. */
727 if (ISSET(bp
->b_flags
, B_TAPE
)) {
734 * If the vnode has "too many" write operations in progress
735 * wait for them to finish the IO
737 while (vp
->v_numoutput
>= BUFWRITE_THROTTLE
) {
738 vp
->v_flag
|= VTHROTTLED
;
739 (void)tsleep((caddr_t
)&vp
->v_numoutput
, PRIBIO
+ 1, "bdwrite", 0);
743 * If we have too many delayed write buffers,
744 * more than we can "safely" handle, just fall back to
745 * doing the async write
748 panic("bdwrite: Negative nbdwrite");
750 // can't do a bawrite() if the LOCKED bit is set because the
751 // buffer is part of a transaction and can't go to disk until
752 // the LOCKED bit is cleared.
753 if (!ISSET(bp
->b_flags
, B_LOCKED
) && nbdwrite
> ((nbuf
/4)*3)) {
761 /* Otherwise, the "write" is done, so mark and release the buffer. */
762 SET(bp
->b_flags
, B_DONE
);
771 (void) bdwrite_internal(bp
, 0);
776 * Asynchronous block write; just an asynchronous bwrite().
778 * Note: With the abilitty to allocate additional buffer
779 * headers, we can get in to the situation where "too" many
780 * bawrite()s can create situation where the kernel can create
781 * buffers faster than the disks can service.
782 * We limit the number of "in flight" writes a vnode can have to
786 bawrite_internal(bp
, throttle
)
790 struct vnode
*vp
= bp
->b_vp
;
794 * If the vnode has "too many" write operations in progress
795 * wait for them to finish the IO
797 while (vp
->v_numoutput
>= BUFWRITE_THROTTLE
) {
799 vp
->v_flag
|= VTHROTTLED
;
800 (void)tsleep((caddr_t
)&vp
->v_numoutput
,
801 PRIBIO
+ 1, "bawrite", 0);
803 return (EWOULDBLOCK
);
807 SET(bp
->b_flags
, B_ASYNC
);
816 (void) bawrite_internal(bp
, 1);
822 * Called prior to the locking of any vnodes when we are expecting to
823 * write. We do not want to starve the buffer cache with too many
824 * dirty buffers so we block here. By blocking prior to the locking
825 * of any vnodes we attempt to avoid the situation where a locked vnode
826 * prevents the various system daemons from flushing related buffers.
832 /* XXX To be implemented later */
836 * Release a buffer on to the free lists.
837 * Described in Bach (p. 46).
843 struct bqueues
*bufq
;
847 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 388)) | DBG_FUNC_START
,
848 bp
->b_lblkno
* PAGE_SIZE
, (int)bp
, (int)bp
->b_data
,
851 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
853 // if we're invalidating a buffer that has the B_CALL bit
854 // set then call the b_iodone function so it gets cleaned
857 if (ISSET(bp
->b_flags
, B_META
) && ISSET(bp
->b_flags
, B_INVAL
)) {
858 if (ISSET(bp
->b_flags
, B_CALL
) && !ISSET(bp
->b_flags
, B_DELWRI
)) {
859 panic("brelse: CALL flag set but not DELWRI! bp 0x%x\n", bp
);
861 if (ISSET(bp
->b_flags
, B_CALL
)) { /* if necessary, call out */
862 void (*iodone_func
)(struct buf
*) = bp
->b_iodone
;
864 CLR(bp
->b_flags
, B_CALL
); /* but note callout done */
867 if (iodone_func
== NULL
) {
868 panic("brelse: bp @ 0x%x has NULL b_iodone!\n", bp
);
874 /* IO is done. Cleanup the UPL state */
875 if (!ISSET(bp
->b_flags
, B_META
)
876 && UBCINFOEXISTS(bp
->b_vp
) && bp
->b_bufsize
) {
881 if ( !ISSET(bp
->b_flags
, B_PAGELIST
)) {
882 if ( !ISSET(bp
->b_flags
, B_INVAL
)) {
883 kret
= ubc_create_upl(bp
->b_vp
,
884 ubc_blktooff(bp
->b_vp
, bp
->b_lblkno
),
889 if (kret
!= KERN_SUCCESS
)
890 panic("brelse: Failed to get pagelists");
892 upl_ubc_alias_set(upl
, bp
, 5);
893 #endif /* UBC_DEBUG */
897 upl
= bp
->b_pagelist
;
900 kret
= ubc_upl_unmap(upl
);
902 if (kret
!= KERN_SUCCESS
)
903 panic("kernel_upl_unmap failed");
908 if (bp
->b_flags
& (B_ERROR
| B_INVAL
)) {
909 if (bp
->b_flags
& (B_READ
| B_INVAL
))
910 upl_flags
= UPL_ABORT_DUMP_PAGES
;
913 ubc_upl_abort(upl
, upl_flags
);
915 if (ISSET(bp
->b_flags
, B_NEEDCOMMIT
))
916 upl_flags
= UPL_COMMIT_CLEAR_DIRTY
;
917 else if (ISSET(bp
->b_flags
, B_DELWRI
| B_WASDIRTY
))
918 upl_flags
= UPL_COMMIT_SET_DIRTY
;
920 upl_flags
= UPL_COMMIT_CLEAR_DIRTY
;
921 ubc_upl_commit_range(upl
, 0, bp
->b_bufsize
, upl_flags
|
922 UPL_COMMIT_INACTIVATE
| UPL_COMMIT_FREE_ON_EMPTY
);
925 CLR(bp
->b_flags
, B_PAGELIST
);
930 if(ISSET(bp
->b_flags
, B_PAGELIST
))
931 panic("brelse: pagelist set for non VREG; vp=%x", bp
->b_vp
);
934 /* Wake up any processes waiting for any buffer to become free. */
940 /* Wake up any proceeses waiting for _this_ buffer to become free. */
941 if (ISSET(bp
->b_flags
, B_WANTED
)) {
942 CLR(bp
->b_flags
, B_WANTED
);
946 /* Block disk interrupts. */
950 * Determine which queue the buffer should be on, then put it there.
953 /* If it's locked, don't report an error; try again later. */
954 if (ISSET(bp
->b_flags
, (B_LOCKED
|B_ERROR
)) == (B_LOCKED
|B_ERROR
))
955 CLR(bp
->b_flags
, B_ERROR
);
957 /* If it's not cacheable, or an error, mark it invalid. */
958 if (ISSET(bp
->b_flags
, (B_NOCACHE
|B_ERROR
)))
959 SET(bp
->b_flags
, B_INVAL
);
961 if ((bp
->b_bufsize
<= 0) || ISSET(bp
->b_flags
, B_INVAL
)) {
963 * If it's invalid or empty, dissociate it from its vnode
964 * and put on the head of the appropriate queue.
968 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
969 CLR(bp
->b_flags
, B_DELWRI
);
971 wakeup((caddr_t
)&nbdwrite
);
973 if (bp
->b_bufsize
<= 0)
974 whichq
= BQ_EMPTY
; /* no data */
975 else if (ISSET(bp
->b_flags
, B_META
))
976 whichq
= BQ_META
; /* meta-data */
978 whichq
= BQ_AGE
; /* invalid data */
980 bufq
= &bufqueues
[whichq
];
981 binsheadfree(bp
, bufq
, whichq
);
984 * It has valid data. Put it on the end of the appropriate
985 * queue, so that it'll stick around for as long as possible.
987 if (ISSET(bp
->b_flags
, B_LOCKED
))
988 whichq
= BQ_LOCKED
; /* locked in core */
989 else if (ISSET(bp
->b_flags
, B_META
))
990 whichq
= BQ_META
; /* meta-data */
991 else if (ISSET(bp
->b_flags
, B_AGE
))
992 whichq
= BQ_AGE
; /* stale but valid data */
994 whichq
= BQ_LRU
; /* valid data */
996 bufq
= &bufqueues
[whichq
];
997 binstailfree(bp
, bufq
, whichq
);
1000 /* Unlock the buffer. */
1001 CLR(bp
->b_flags
, (B_AGE
| B_ASYNC
| B_BUSY
| B_NOCACHE
));
1003 /* Allow disk interrupts. */
1006 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 388)) | DBG_FUNC_END
,
1007 (int)bp
, (int)bp
->b_data
, bp
->b_flags
, 0, 0);
1011 * Determine if a block is in the cache.
1012 * Just look on what would be its hash chain. If it's there, return
1013 * a pointer to it, unless it's marked invalid. If it's marked invalid,
1014 * we normally don't return the buffer, unless the caller explicitly
1024 bp
= BUFHASH(vp
, blkno
)->lh_first
;
1026 /* Search hash chain */
1027 for (; bp
!= NULL
; bp
= bp
->b_hash
.le_next
) {
1028 if (bp
->b_lblkno
== blkno
&& bp
->b_vp
== vp
&&
1029 !ISSET(bp
->b_flags
, B_INVAL
))
1037 /* XXX FIXME -- Update the comment to reflect the UBC changes (please) -- */
1039 * Get a block of requested size that is associated with
1040 * a given vnode and block offset. If it is found in the
1041 * block cache, mark it as having been found, make it busy
1042 * and return it. Otherwise, return an empty block of the
1043 * correct size. It is up to the caller to insure that the
1044 * cached blocks be of the correct size.
1047 getblk(vp
, blkno
, size
, slpflag
, slptimeo
, operation
)
1048 register struct vnode
*vp
;
1050 int size
, slpflag
, slptimeo
, operation
;
1055 upl_page_info_t
*pl
;
1060 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_START
,
1061 blkno
* PAGE_SIZE
, size
, operation
, 0, 0);
1065 if ((bp
= incore(vp
, blkno
))) {
1066 /* Found in the Buffer Cache */
1067 if (ISSET(bp
->b_flags
, B_BUSY
)) {
1069 switch (operation
) {
1073 SET(bp
->b_flags
, B_WANTED
);
1074 bufstats
.bufs_busyincore
++;
1075 err
= tsleep(bp
, slpflag
| (PRIBIO
+ 1), "getblk",
1079 * Callers who call with PCATCH or timeout are
1080 * willing to deal with the NULL pointer
1082 if (err
&& ((slpflag
& PCATCH
) ||
1083 ((err
== EWOULDBLOCK
) && slptimeo
)))
1090 /* pagein operation must not use getblk */
1091 panic("getblk: pagein for incore busy buffer");
1097 /* pageout operation must not use getblk */
1098 panic("getblk: pageout for incore busy buffer");
1104 panic("getblk: %d unknown operation 1", operation
);
1110 SET(bp
->b_flags
, (B_BUSY
| B_CACHE
));
1112 bufstats
.bufs_incore
++;
1116 if (ISSET(bp
->b_flags
, B_PAGELIST
))
1117 panic("pagelist buffer is not busy");
1119 switch (operation
) {
1122 if (UBCISVALID(bp
->b_vp
) && bp
->b_bufsize
) {
1123 kret
= ubc_create_upl(vp
,
1124 ubc_blktooff(vp
, bp
->b_lblkno
),
1129 if (kret
!= KERN_SUCCESS
)
1130 panic("Failed to get pagelists");
1132 SET(bp
->b_flags
, B_PAGELIST
);
1133 bp
->b_pagelist
= upl
;
1135 if (!upl_valid_page(pl
, 0)) {
1136 if (vp
->v_tag
!= VT_NFS
)
1137 panic("getblk: incore buffer without valid page");
1138 CLR(bp
->b_flags
, B_CACHE
);
1141 if (upl_dirty_page(pl
, 0))
1142 SET(bp
->b_flags
, B_WASDIRTY
);
1144 CLR(bp
->b_flags
, B_WASDIRTY
);
1146 kret
= ubc_upl_map(upl
, (vm_address_t
*)&(bp
->b_data
));
1147 if (kret
!= KERN_SUCCESS
)
1148 panic("getblk: ubc_upl_map() failed with (%d)",
1150 if (bp
->b_data
== 0)
1151 panic("ubc_upl_map mapped 0");
1157 * VM is not involved in IO for the meta data
1158 * buffer already has valid data
1161 panic("bp->b_data null incore buf=%x", bp
);
1166 panic("getblk: paging operation 1");
1170 panic("getblk: %d unknown operation 2", operation
);
1175 } else { /* not incore() */
1176 int queue
= BQ_EMPTY
; /* Start with no preference */
1179 if ((operation
== BLK_META
) || (UBCINVALID(vp
)) ||
1180 !(UBCINFOEXISTS(vp
))) {
1181 operation
= BLK_META
;
1183 if ((bp
= getnewbuf(slpflag
, slptimeo
, &queue
)) == NULL
)
1185 if (incore(vp
, blkno
)) {
1186 SET(bp
->b_flags
, B_INVAL
);
1187 binshash(bp
, &invalhash
);
1192 * NOTE: YOU CAN NOT BLOCK UNTIL binshash() HAS BEEN
1193 * CALLED! BE CAREFUL.
1197 * if it is meta, the queue may be set to other
1198 * type so reset as well as mark it to be B_META
1199 * so that when buffer is released it will goto META queue
1200 * Also, if the vnode is not VREG, then it is META
1202 if (operation
== BLK_META
) {
1203 SET(bp
->b_flags
, B_META
);
1207 bp
->b_blkno
= bp
->b_lblkno
= blkno
;
1211 * Insert in the hash so that incore() can find it
1213 binshash(bp
, BUFHASH(vp
, blkno
));
1221 switch (operation
) {
1223 /* buffer data is invalid */
1226 panic("bp->b_data is null %x",bp
);
1228 bufstats
.bufs_miss
++;
1230 /* wakeup the buffer */
1231 CLR(bp
->b_flags
, B_WANTED
);
1238 if (ISSET(bp
->b_flags
, B_PAGELIST
))
1239 panic("B_PAGELIST in bp=%x",bp
);
1241 kret
= ubc_create_upl(vp
,
1242 ubc_blktooff(vp
, blkno
),
1247 if (kret
!= KERN_SUCCESS
)
1248 panic("Failed to get pagelists");
1251 upl_ubc_alias_set(upl
, bp
, 4);
1252 #endif /* UBC_DEBUG */
1253 bp
->b_pagelist
= upl
;
1255 SET(bp
->b_flags
, B_PAGELIST
);
1257 if (upl_valid_page(pl
, 0)) {
1258 SET(bp
->b_flags
, B_CACHE
| B_DONE
);
1259 bufstats
.bufs_vmhits
++;
1261 pagedirty
= upl_dirty_page(pl
, 0);
1264 SET(bp
->b_flags
, B_WASDIRTY
);
1266 if (vp
->v_tag
== VT_NFS
) {
1273 f_offset
= ubc_blktooff(vp
, blkno
);
1275 if (f_offset
> vp
->v_ubcinfo
->ui_size
) {
1276 CLR(bp
->b_flags
, (B_CACHE
|B_DONE
|B_WASDIRTY
));
1280 valid_size
= min(((unsigned int)(vp
->v_ubcinfo
->ui_size
- f_offset
)), PAGE_SIZE
);
1281 bp
->b_validend
= valid_size
;
1284 bp
->b_dirtyend
= valid_size
;
1288 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_NONE
,
1289 bp
->b_validend
, bp
->b_dirtyend
,
1290 (int)vp
->v_ubcinfo
->ui_size
, 0, 0);
1298 bp
->b_validend
= bp
->b_bcount
;
1299 bp
->b_dirtyend
= bp
->b_bcount
;
1302 bp
->b_validend
= bp
->b_bcount
;
1306 error
= VOP_BMAP(vp
, bp
->b_lblkno
, NULL
, &bp
->b_blkno
, NULL
);
1308 panic("getblk: VOP_BMAP failed");
1311 * XXX: We probably should invalidate the VM Page
1313 bp
->b_error
= error
;
1314 SET(bp
->b_flags
, (B_ERROR
| B_INVAL
));
1315 /* undo B_DONE that was set before upl_commit() */
1316 CLR(bp
->b_flags
, B_DONE
);
1321 bufstats
.bufs_miss
++;
1323 kret
= ubc_upl_map(upl
, (vm_address_t
*)&(bp
->b_data
));
1324 if (kret
!= KERN_SUCCESS
) {
1325 panic("getblk: ubc_upl_map() "
1326 "failed with (%d)", kret
);
1328 if (bp
->b_data
== 0)
1329 panic("kernel_upl_map mapped 0");
1335 panic("getblk: paging operation 2");
1338 panic("getblk: %d unknown operation 3", operation
);
1344 if (bp
->b_data
== NULL
)
1345 panic("getblk: bp->b_addr is null");
1347 if (bp
->b_bufsize
& 0xfff) {
1348 if (ISSET(bp
->b_flags
, B_META
) && (bp
->b_bufsize
& 0x1ff))
1349 panic("getblk: bp->b_bufsize = %d", bp
->b_bufsize
);
1352 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_END
,
1353 (int)bp
, (int)bp
->b_data
, bp
->b_flags
, 3, 0);
1359 * Get an empty, disassociated buffer of given size.
1366 int queue
= BQ_EMPTY
;
1368 while ((bp
= getnewbuf(0, 0, &queue
)) == 0)
1370 SET(bp
->b_flags
, (B_META
|B_INVAL
));
1373 assert(queue
== BQ_EMPTY
);
1374 #endif /* DIAGNOSTIC */
1375 /* XXX need to implement logic to deal with other queues */
1377 binshash(bp
, &invalhash
);
1379 bufstats
.bufs_eblk
++;
1385 * Zones for the meta data buffers
1389 #define MAXMETA 4096
1391 struct meta_zone_entry
{
1398 struct meta_zone_entry meta_zones
[] = {
1399 {NULL
, (MINMETA
* 1), 128 * (MINMETA
* 1), "buf.512" },
1400 {NULL
, (MINMETA
* 2), 64 * (MINMETA
* 2), "buf.1024" },
1401 {NULL
, (MINMETA
* 4), 16 * (MINMETA
* 4), "buf.2048" },
1402 {NULL
, (MINMETA
* 8), 512 * (MINMETA
* 8), "buf.4096" },
1403 {NULL
, 0, 0, "" } /* End */
1407 * Initialize the meta data zones
1414 for (i
= 0; meta_zones
[i
].mz_size
!= 0; i
++) {
1415 meta_zones
[i
].mz_zone
=
1416 zinit(meta_zones
[i
].mz_size
,
1417 meta_zones
[i
].mz_max
,
1419 meta_zones
[i
].mz_name
);
1421 buf_hdr_zone
= zinit(sizeof(struct buf
), 32, PAGE_SIZE
, "buf headers");
1424 static __inline__ zone_t
1425 getbufzone(size_t size
)
1429 if ((size
% 512) || (size
< MINMETA
) || (size
> MAXMETA
))
1430 panic("getbufzone: incorect size = %d", size
);
1432 for (i
= 0; meta_zones
[i
].mz_size
!= 0; i
++) {
1433 if (meta_zones
[i
].mz_size
>= size
)
1437 return (meta_zones
[i
].mz_zone
);
1441 * With UBC, there is no need to expand / shrink the file data
1442 * buffer. The VM uses the same pages, hence no waste.
1443 * All the file data buffers can have one size.
1444 * In fact expand / shrink would be an expensive operation.
1446 * Only exception to this is meta-data buffers. Most of the
1447 * meta data operations are smaller than PAGE_SIZE. Having the
1448 * meta-data buffers grow and shrink as needed, optimizes use
1449 * of the kernel wired memory.
1457 vm_size_t desired_size
;
1459 desired_size
= roundup(size
, CLBYTES
);
1461 if(desired_size
< PAGE_SIZE
)
1462 desired_size
= PAGE_SIZE
;
1463 if (desired_size
> MAXBSIZE
)
1464 panic("allocbuf: buffer larger than MAXBSIZE requested");
1466 if (ISSET(bp
->b_flags
, B_META
)) {
1469 size_t nsize
= roundup(size
, MINMETA
);
1472 vm_offset_t elem
= (vm_offset_t
)bp
->b_data
;
1474 if (ISSET(bp
->b_flags
, B_ZALLOC
))
1475 if (bp
->b_bufsize
<= MAXMETA
) {
1476 if (bp
->b_bufsize
< nsize
) {
1477 /* reallocate to a bigger size */
1479 zprev
= getbufzone(bp
->b_bufsize
);
1480 if (nsize
<= MAXMETA
) {
1481 desired_size
= nsize
;
1482 z
= getbufzone(nsize
);
1483 bp
->b_data
= (caddr_t
)zalloc(z
);
1485 panic("allocbuf: zalloc() returned NULL");
1487 kret
= kmem_alloc(kernel_map
, &bp
->b_data
, desired_size
);
1488 if (kret
!= KERN_SUCCESS
)
1489 panic("allocbuf: kmem_alloc() 0 returned %d", kret
);
1491 panic("allocbuf: null b_data 0");
1492 CLR(bp
->b_flags
, B_ZALLOC
);
1494 bcopy((const void *)elem
, bp
->b_data
, bp
->b_bufsize
);
1497 desired_size
= bp
->b_bufsize
;
1500 panic("allocbuf: B_ZALLOC set incorrectly");
1502 if (bp
->b_bufsize
< desired_size
) {
1503 /* reallocate to a bigger size */
1504 kret
= kmem_alloc(kernel_map
, &bp
->b_data
, desired_size
);
1505 if (kret
!= KERN_SUCCESS
)
1506 panic("allocbuf: kmem_alloc() returned %d", kret
);
1508 panic("allocbuf: null b_data");
1509 bcopy((const void *)elem
, bp
->b_data
, bp
->b_bufsize
);
1510 kmem_free(kernel_map
, elem
, bp
->b_bufsize
);
1512 desired_size
= bp
->b_bufsize
;
1515 /* new allocation */
1516 if (nsize
<= MAXMETA
) {
1517 desired_size
= nsize
;
1518 z
= getbufzone(nsize
);
1519 bp
->b_data
= (caddr_t
)zalloc(z
);
1521 panic("allocbuf: zalloc() returned NULL 2");
1522 SET(bp
->b_flags
, B_ZALLOC
);
1524 kret
= kmem_alloc(kernel_map
, &bp
->b_data
, desired_size
);
1525 if (kret
!= KERN_SUCCESS
)
1526 panic("allocbuf: kmem_alloc() 2 returned %d", kret
);
1528 panic("allocbuf: null b_data 2");
1533 if (ISSET(bp
->b_flags
, B_META
) && (bp
->b_data
== 0))
1534 panic("allocbuf: bp->b_data is NULL, buf @ 0x%x", bp
);
1536 bp
->b_bufsize
= desired_size
;
1537 bp
->b_bcount
= size
;
1542 * Get a new buffer from one of the free lists.
1544 * Request for a queue is passes in. The queue from which the buffer was taken
1545 * from is returned. Out of range queue requests get BQ_EMPTY. Request for
1546 * BQUEUE means no preference. Use heuristics in that case.
1547 * Heuristics is as follows:
1548 * Try BQ_AGE, BQ_LRU, BQ_EMPTY, BQ_META in that order.
1549 * If none available block till one is made available.
1550 * If buffers available on both BQ_AGE and BQ_LRU, check the timestamps.
1551 * Pick the most stale buffer.
1552 * If found buffer was marked delayed write, start the async. write
1553 * and restart the search.
1554 * Initialize the fields and disassociate the buffer from the vnode.
1555 * Remove the buffer from the hash. Return the buffer and the queue
1556 * on which it was found.
1560 getnewbuf(slpflag
, slptimeo
, queue
)
1561 int slpflag
, slptimeo
;
1564 register struct buf
*bp
;
1565 register struct buf
*lru_bp
;
1566 register struct buf
*age_bp
;
1567 register struct buf
*meta_bp
;
1568 register int age_time
, lru_time
, bp_time
, meta_time
;
1570 int req
= *queue
; /* save it for restarts */
1575 /* invalid request gets empty queue */
1576 if ((*queue
> BQUEUES
) || (*queue
< 0)
1577 || (*queue
== BQ_LAUNDRY
) || (*queue
== BQ_LOCKED
))
1580 /* (*queue == BQUEUES) means no preference */
1581 if (*queue
!= BQUEUES
) {
1582 /* Try for the requested queue first */
1583 bp
= bufqueues
[*queue
].tqh_first
;
1588 /* Unable to use requested queue */
1589 age_bp
= bufqueues
[BQ_AGE
].tqh_first
;
1590 lru_bp
= bufqueues
[BQ_LRU
].tqh_first
;
1591 meta_bp
= bufqueues
[BQ_META
].tqh_first
;
1593 if (!age_bp
&& !lru_bp
&& !meta_bp
) {
1595 * Unavailble on AGE or LRU or META queues
1596 * Try the empty list first
1598 bp
= bufqueues
[BQ_EMPTY
].tqh_first
;
1604 /* Create a new temparory buffer header */
1605 bp
= (struct buf
*)zalloc(buf_hdr_zone
);
1610 binshash(bp
, &invalhash
);
1611 SET(bp
->b_flags
, B_HDRALLOC
);
1613 binsheadfree(bp
, &bufqueues
[BQ_EMPTY
], BQ_EMPTY
);
1618 /* Log this error condition */
1619 printf("getnewbuf: No useful buffers");
1621 /* wait for a free buffer of any kind */
1623 bufstats
.bufs_sleeps
++;
1624 tsleep(&needbuffer
, slpflag
|(PRIBIO
+1), "getnewbuf", slptimeo
);
1629 /* Buffer available either on AGE or LRU or META */
1633 /* Buffer available either on AGE or LRU */
1637 } else if (!lru_bp
) {
1640 } else { /* buffer available on both AGE and LRU */
1641 age_time
= time
.tv_sec
- age_bp
->b_timestamp
;
1642 lru_time
= time
.tv_sec
- lru_bp
->b_timestamp
;
1643 if ((age_time
< 0) || (lru_time
< 0)) { /* time set backwards */
1647 * we should probably re-timestamp eveything in the
1648 * queues at this point with the current time
1651 if ((lru_time
>= lru_is_stale
) && (age_time
< age_is_stale
)) {
1661 if (!bp
) { /* Neither on AGE nor on LRU */
1664 } else if (meta_bp
) {
1665 bp_time
= time
.tv_sec
- bp
->b_timestamp
;
1666 meta_time
= time
.tv_sec
- meta_bp
->b_timestamp
;
1668 if (!(bp_time
< 0) && !(meta_time
< 0)) {
1669 /* time not set backwards */
1671 bp_is_stale
= (*queue
== BQ_LRU
) ?
1672 lru_is_stale
: age_is_stale
;
1674 if ((meta_time
>= meta_is_stale
) &&
1675 (bp_time
< bp_is_stale
)) {
1683 panic("getnewbuf: null bp");
1686 if (ISSET(bp
->b_flags
, B_LOCKED
)) {
1687 panic("getnewbuf: bp @ 0x%x is LOCKED! (flags 0x%x)\n", bp
, bp
->b_flags
);
1690 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
1691 panic("getnewbuf: le_prev is deadbeef, buf @ 0x%x", bp
);
1693 if(ISSET(bp
->b_flags
, B_BUSY
))
1694 panic("getnewbuf reusing BUSY buf @ 0x%x", bp
);
1697 if (bcleanbuf(bp
)) {
1698 /* bawrite() issued, buffer not ready */
1707 #include <mach/mach_types.h>
1708 #include <mach/memory_object_types.h>
1709 #include <kern/sched_prim.h>
1713 * Returns 0 is buffer is ready to use,
1714 * Returns 1 if issued a bawrite() to indicate
1715 * that the buffer is not ready.
1718 bcleanbuf(struct buf
*bp
)
1726 /* Remove from the queue */
1729 /* Buffer is no longer on free lists. */
1730 SET(bp
->b_flags
, B_BUSY
);
1732 /* Check whether the buffer header was "allocated" */
1733 if (ISSET(bp
->b_flags
, B_HDRALLOC
))
1736 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
1737 panic("bcleanbuf: le_prev is deadbeef");
1740 * If buffer was a delayed write, start the IO by queuing
1741 * it on the LAUNDRY queue, and return 1
1743 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
1745 binstailfree(bp
, &bufqueues
[BQ_LAUNDRY
], BQ_LAUNDRY
);
1747 wakeup(&blaundrycnt
);
1748 /* and give it a chance to run */
1749 (void)thread_block(THREAD_CONTINUE_NULL
);
1760 if (ISSET(bp
->b_flags
, B_META
)) {
1761 vm_offset_t elem
= (vm_offset_t
)bp
->b_data
;
1763 panic("bcleanbuf: NULL bp->b_data B_META buffer");
1765 if (ISSET(bp
->b_flags
, B_ZALLOC
)) {
1766 if (bp
->b_bufsize
<= MAXMETA
) {
1769 z
= getbufzone(bp
->b_bufsize
);
1770 bp
->b_data
= (caddr_t
)0xdeadbeef;
1772 CLR(bp
->b_flags
, B_ZALLOC
);
1774 panic("bcleanbuf: B_ZALLOC set incorrectly");
1776 bp
->b_data
= (caddr_t
)0xdeadbeef;
1777 kmem_free(kernel_map
, elem
, bp
->b_bufsize
);
1781 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
1783 /* disassociate us from our vnode, if we had one... */
1786 /* clear out various other fields */
1789 bp
->b_flags
= B_BUSY
;
1791 SET(bp
->b_flags
, B_HDRALLOC
);
1793 bp
->b_blkno
= bp
->b_lblkno
= 0;
1798 bp
->b_dirtyoff
= bp
->b_dirtyend
= 0;
1799 bp
->b_validoff
= bp
->b_validend
= 0;
1801 /* nuke any credentials we were holding */
1803 if (cred
!= NOCRED
) {
1804 bp
->b_rcred
= NOCRED
;
1808 if (cred
!= NOCRED
) {
1809 bp
->b_wcred
= NOCRED
;
1818 * Wait for operations on the buffer to complete.
1819 * When they do, extract and return the I/O's error value.
1828 while (!ISSET(bp
->b_flags
, B_DONE
))
1829 tsleep(bp
, PRIBIO
+ 1, "biowait", 0);
1832 /* check for interruption of I/O (e.g. via NFS), then errors. */
1833 if (ISSET(bp
->b_flags
, B_EINTR
)) {
1834 CLR(bp
->b_flags
, B_EINTR
);
1836 } else if (ISSET(bp
->b_flags
, B_ERROR
))
1837 return (bp
->b_error
? bp
->b_error
: EIO
);
1843 * Mark I/O complete on a buffer.
1845 * If a callback has been requested, e.g. the pageout
1846 * daemon, do so. Otherwise, awaken waiting processes.
1848 * [ Leffler, et al., says on p.247:
1849 * "This routine wakes up the blocked process, frees the buffer
1850 * for an asynchronous write, or, for a request by the pagedaemon
1851 * process, invokes a procedure specified in the buffer structure" ]
1853 * In real life, the pagedaemon (or other system processes) wants
1854 * to do async stuff to, and doesn't want the buffer brelse()'d.
1855 * (for swap pager, that puts swap buffers on the free lists (!!!),
1856 * for the vn device, that puts malloc'd buffers on the free lists!)
1862 boolean_t funnel_state
;
1864 extern struct timeval priority_IO_timestamp_for_root
;
1865 extern int hard_throttle_on_root
;
1867 funnel_state
= thread_funnel_set(kernel_flock
, TRUE
);
1869 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 387)) | DBG_FUNC_START
,
1870 (int)bp
, (int)bp
->b_data
, bp
->b_flags
, 0, 0);
1872 if (ISSET(bp
->b_flags
, B_DONE
))
1873 panic("biodone already");
1874 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
1876 * I/O was done, so don't believe
1877 * the DIRTY state from VM anymore
1879 CLR(bp
->b_flags
, B_WASDIRTY
);
1881 if (!ISSET(bp
->b_flags
, B_READ
) && !ISSET(bp
->b_flags
, B_RAW
))
1882 vwakeup(bp
); /* wake up reader */
1884 if (kdebug_enable
) {
1885 int code
= DKIO_DONE
;
1887 if (bp
->b_flags
& B_READ
)
1889 if (bp
->b_flags
& B_ASYNC
)
1892 if (bp
->b_flags
& B_META
)
1894 else if (bp
->b_flags
& (B_PGIN
| B_PAGEOUT
))
1895 code
|= DKIO_PAGING
;
1897 KERNEL_DEBUG_CONSTANT(FSDBG_CODE(DBG_DKRW
, code
) | DBG_FUNC_NONE
,
1898 (unsigned int)bp
, (unsigned int)bp
->b_vp
,
1899 bp
->b_resid
, bp
->b_error
, 0);
1902 /* Wakeup the throttled write operations as needed */
1905 && (vp
->v_flag
& VTHROTTLED
)
1906 && (vp
->v_numoutput
<= (BUFWRITE_THROTTLE
/ 3))) {
1907 vp
->v_flag
&= ~VTHROTTLED
;
1908 wakeup((caddr_t
)&vp
->v_numoutput
);
1910 if ((bp
->b_flags
& B_PGIN
) && (vp
->v_mount
->mnt_kern_flag
& MNTK_ROOTDEV
)) {
1911 priority_IO_timestamp_for_root
= time
;
1912 hard_throttle_on_root
= 0;
1914 if (ISSET(bp
->b_flags
, B_CALL
)) { /* if necessary, call out */
1915 void (*iodone_func
)(struct buf
*) = bp
->b_iodone
;
1917 CLR(bp
->b_flags
, B_CALL
); /* but note callout done */
1918 bp
->b_iodone
= NULL
;
1920 if (iodone_func
== NULL
) {
1921 panic("biodone: bp @ 0x%x has NULL b_iodone!\n", bp
);
1925 } else if (ISSET(bp
->b_flags
, B_ASYNC
)) /* if async, release it */
1927 else { /* or just wakeup the buffer */
1928 CLR(bp
->b_flags
, B_WANTED
);
1932 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 387)) | DBG_FUNC_END
,
1933 (int)bp
, (int)bp
->b_data
, bp
->b_flags
, 0, 0);
1935 thread_funnel_set(kernel_flock
, funnel_state
);
1939 * Return a count of buffers on the "locked" queue.
1944 register struct buf
*bp
;
1947 for (bp
= bufqueues
[BQ_LOCKED
].tqh_first
; bp
;
1948 bp
= bp
->b_freelist
.tqe_next
)
1954 * Return a count of 'busy' buffers. Used at the time of shutdown.
1957 count_busy_buffers()
1959 register struct buf
*bp
;
1960 register int nbusy
= 0;
1962 for (bp
= &buf
[nbuf
]; --bp
>= buf
; )
1963 if ((bp
->b_flags
& (B_BUSY
|B_INVAL
)) == B_BUSY
)
1970 * Print out statistics on the current allocation of the buffer pool.
1971 * Can be enabled to print out on every ``sync'' by setting "syncprt"
1972 * in vfs_syscalls.c using sysctl.
1978 register struct buf
*bp
;
1979 register struct bqueues
*dp
;
1980 int counts
[MAXBSIZE
/CLBYTES
+1];
1981 static char *bname
[BQUEUES
] =
1982 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
1984 for (dp
= bufqueues
, i
= 0; dp
< &bufqueues
[BQUEUES
]; dp
++, i
++) {
1986 for (j
= 0; j
<= MAXBSIZE
/CLBYTES
; j
++)
1989 for (bp
= dp
->tqh_first
; bp
; bp
= bp
->b_freelist
.tqe_next
) {
1990 counts
[bp
->b_bufsize
/CLBYTES
]++;
1994 printf("%s: total-%d", bname
[i
], count
);
1995 for (j
= 0; j
<= MAXBSIZE
/CLBYTES
; j
++)
1997 printf(", %d-%d", j
* CLBYTES
, counts
[j
]);
2001 #endif /* DIAGNOSTIC */
2003 #define NRESERVEDIOBUFS 64
2005 __private_extern__
struct buf
*
2006 alloc_io_buf(vp
, priv
)
2010 register struct buf
*bp
;
2015 while (niobuf
- NRESERVEDIOBUFS
< bufstats
.bufs_iobufinuse
&& !priv
) {
2017 bufstats
.bufs_iobufsleeps
++;
2018 (void) tsleep(&need_iobuffer
, (PRIBIO
+1), "alloc_io_buf", 0);
2021 while ((bp
= iobufqueue
.tqh_first
) == NULL
) {
2023 bufstats
.bufs_iobufsleeps
++;
2024 (void) tsleep(&need_iobuffer
, (PRIBIO
+1), "alloc_io_buf1", 0);
2027 TAILQ_REMOVE(&iobufqueue
, bp
, b_freelist
);
2028 bp
->b_timestamp
= 0;
2030 /* clear out various fields */
2031 bp
->b_flags
= B_BUSY
;
2032 bp
->b_blkno
= bp
->b_lblkno
= 0;
2041 if (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
)
2042 bp
->b_dev
= vp
->v_rdev
;
2045 bufstats
.bufs_iobufinuse
++;
2046 if (bufstats
.bufs_iobufinuse
> bufstats
.bufs_iobufmax
)
2047 bufstats
.bufs_iobufmax
= bufstats
.bufs_iobufinuse
;
2053 __private_extern__
void
2060 /* put buffer back on the head of the iobufqueue */
2062 bp
->b_flags
= B_INVAL
;
2064 binsheadfree(bp
, &iobufqueue
, -1);
2066 /* Wake up any processes waiting for any buffer to become free. */
2067 if (need_iobuffer
) {
2069 wakeup(&need_iobuffer
);
2071 bufstats
.bufs_iobufinuse
--;
2075 /* disabled for now */
2077 /* XXX move this to a separate file */
2079 * Dynamic Scaling of the Buffer Queues
2082 typedef long long blsize_t
;
2084 blsize_t MAXNBUF
; /* initialize to (sane_size / PAGE_SIZE) */
2085 /* Global tunable limits */
2086 blsize_t nbufh
; /* number of buffer headers */
2087 blsize_t nbuflow
; /* minimum number of buffer headers required */
2088 blsize_t nbufhigh
; /* maximum number of buffer headers allowed */
2089 blsize_t nbuftarget
; /* preferred number of buffer headers */
2094 * 1. 0 < nbuflow <= nbufh <= nbufhigh
2095 * 2. nbufhigh <= MAXNBUF
2096 * 3. 0 < nbuflow <= nbuftarget <= nbufhigh
2097 * 4. nbufh can not be set by sysctl().
2100 /* Per queue tunable limits */
2103 blsize_t bl_nlow
; /* minimum number of buffer headers required */
2104 blsize_t bl_num
; /* number of buffer headers on the queue */
2105 blsize_t bl_nlhigh
; /* maximum number of buffer headers allowed */
2106 blsize_t bl_target
; /* preferred number of buffer headers */
2107 long bl_stale
; /* Seconds after which a buffer is considered stale */
2113 * 1. 0 <= bl_nlow <= bl_num <= bl_nlhigh
2114 * 2. bl_nlhigh <= MAXNBUF
2115 * 3. bufqlim[BQ_META].bl_nlow != 0
2116 * 4. bufqlim[BQ_META].bl_nlow > (number of possible concurrent
2117 * file system IO operations)
2118 * 5. bl_num can not be set by sysctl().
2119 * 6. bl_nhigh <= nbufhigh
2125 * Defining it blsize_t as long permits 2^31 buffer headers per queue.
2126 * Which can describe (2^31 * PAGE_SIZE) memory per queue.
2128 * These limits are exported to by means of sysctl().
2129 * It was decided to define blsize_t as a 64 bit quantity.
2130 * This will make sure that we will not be required to change it
2131 * as long as we do not exceed 64 bit address space for the kernel.
2133 * low and high numbers parameters initialized at compile time
2134 * and boot arguments can be used to override them. sysctl()
2135 * would not change the value. sysctl() can get all the values
2136 * but can set only target. num is the current level.
2138 * Advantages of having a "bufqscan" thread doing the balancing are,
2139 * Keep enough bufs on BQ_EMPTY.
2140 * getnewbuf() by default will always select a buffer from the BQ_EMPTY.
2141 * getnewbuf() perfoms best if a buffer was found there.
2142 * Also this minimizes the possibility of starting IO
2143 * from getnewbuf(). That's a performance win, too.
2145 * Localize complex logic [balancing as well as time aging]
2148 * Simplify getnewbuf() logic by elimination of time aging code.
2154 * The goal of the dynamic scaling of the buffer queues to to keep
2155 * the size of the LRU close to bl_target. Buffers on a queue would
2158 * There would be a thread which will be responsible for "balancing"
2159 * the buffer cache queues.
2161 * The scan order would be: AGE, LRU, META, EMPTY.
2164 long bufqscanwait
= 0;
2166 static void bufqscan_thread();
2167 static int balancebufq(int q
);
2168 static int btrimempty(int n
);
2169 static __inline__
int initbufqscan(void);
2170 static __inline__
int nextbufq(int q
);
2171 static void buqlimprt(int all
);
2174 bufq_balance_thread_init()
2177 if (bufqscanwait
++ == 0) {
2179 /* Initalize globals */
2180 MAXNBUF
= (sane_size
/ PAGE_SIZE
);
2182 nbuflow
= min(nbufh
, 100);
2183 nbufhigh
= min(MAXNBUF
, max(nbufh
, 2048));
2184 nbuftarget
= (sane_size
>> 5) / PAGE_SIZE
;
2185 nbuftarget
= max(nbuflow
, nbuftarget
);
2186 nbuftarget
= min(nbufhigh
, nbuftarget
);
2189 * Initialize the bufqlim
2193 bufqlim
[BQ_LOCKED
].bl_nlow
= 0;
2194 bufqlim
[BQ_LOCKED
].bl_nlhigh
= 32;
2195 bufqlim
[BQ_LOCKED
].bl_target
= 0;
2196 bufqlim
[BQ_LOCKED
].bl_stale
= 30;
2199 bufqlim
[BQ_LRU
].bl_nlow
= 0;
2200 bufqlim
[BQ_LRU
].bl_nlhigh
= nbufhigh
/4;
2201 bufqlim
[BQ_LRU
].bl_target
= nbuftarget
/4;
2202 bufqlim
[BQ_LRU
].bl_stale
= LRU_IS_STALE
;
2205 bufqlim
[BQ_AGE
].bl_nlow
= 0;
2206 bufqlim
[BQ_AGE
].bl_nlhigh
= nbufhigh
/4;
2207 bufqlim
[BQ_AGE
].bl_target
= nbuftarget
/4;
2208 bufqlim
[BQ_AGE
].bl_stale
= AGE_IS_STALE
;
2211 bufqlim
[BQ_EMPTY
].bl_nlow
= 0;
2212 bufqlim
[BQ_EMPTY
].bl_nlhigh
= nbufhigh
/4;
2213 bufqlim
[BQ_EMPTY
].bl_target
= nbuftarget
/4;
2214 bufqlim
[BQ_EMPTY
].bl_stale
= 600000;
2217 bufqlim
[BQ_META
].bl_nlow
= 0;
2218 bufqlim
[BQ_META
].bl_nlhigh
= nbufhigh
/4;
2219 bufqlim
[BQ_META
].bl_target
= nbuftarget
/4;
2220 bufqlim
[BQ_META
].bl_stale
= META_IS_STALE
;
2223 bufqlim
[BQ_LOCKED
].bl_nlow
= 0;
2224 bufqlim
[BQ_LOCKED
].bl_nlhigh
= 32;
2225 bufqlim
[BQ_LOCKED
].bl_target
= 0;
2226 bufqlim
[BQ_LOCKED
].bl_stale
= 30;
2231 /* create worker thread */
2232 kernel_thread(kernel_task
, bufqscan_thread
);
2235 /* The workloop for the buffer balancing thread */
2239 boolean_t funnel_state
;
2242 funnel_state
= thread_funnel_set(kernel_flock
, TRUE
);
2246 int q
; /* buffer queue to process */
2250 moretodo
|= balancebufq(q
);
2259 (void)tsleep((void *)&bufqscanwait
, PRIBIO
, "bufqscanwait", 60 * hz
);
2263 (void) thread_funnel_set(kernel_flock
, FALSE
);
2266 /* Seed for the buffer queue balancing */
2267 static __inline__
int
2270 /* Start with AGE queue */
2274 /* Pick next buffer queue to balance */
2275 static __inline__
int
2278 int order
[] = { BQ_AGE
, BQ_LRU
, BQ_META
, BQ_EMPTY
, 0 };
2285 /* function to balance the buffer queues */
2293 /* reject invalid q */
2294 if ((q
< 0) || (q
>= BQUEUES
))
2297 /* LOCKED or LAUNDRY queue MUST not be balanced */
2298 if ((q
== BQ_LOCKED
) || (q
== BQ_LAUNDRY
))
2301 n
= (bufqlim
[q
].bl_num
- bufqlim
[q
].bl_target
);
2303 /* If queue has less than target nothing more to do */
2308 /* Balance only a small amount (12.5%) at a time */
2312 /* EMPTY queue needs special handling */
2313 if (q
== BQ_EMPTY
) {
2314 moretodo
|= btrimempty(n
);
2318 for (; n
> 0; n
--) {
2319 struct buf
*bp
= bufqueues
[q
].tqh_first
;
2323 /* check if it's stale */
2324 if ((time
.tv_sec
- bp
->b_timestamp
) > bufqlim
[q
].bl_stale
) {
2325 if (bcleanbuf(bp
)) {
2326 /* bawrite() issued, bp not ready */
2329 /* release the cleaned buffer to BQ_EMPTY */
2330 SET(bp
->b_flags
, B_INVAL
);
2346 * When struct buf are allocated dynamically, this would
2347 * reclaim upto 'n' struct buf from the empty queue.
2353 static __inline__
void
2356 if ((q
< 0) || (q
>= BQUEUES
))
2359 bufqlim
[q
].bl_num
++;
2363 static __inline__
void
2366 if ((q
< 0) || (q
>= BQUEUES
))
2369 bufqlim
[q
].bl_num
--;
2377 static char *bname
[BQUEUES
] =
2378 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
2381 for (i
= 0; i
< BQUEUES
; i
++) {
2382 printf("%s : ", bname
[i
]);
2383 printf("min = %ld, ", (long)bufqlim
[i
].bl_nlow
);
2384 printf("cur = %ld, ", (long)bufqlim
[i
].bl_num
);
2385 printf("max = %ld, ", (long)bufqlim
[i
].bl_nlhigh
);
2386 printf("target = %ld, ", (long)bufqlim
[i
].bl_target
);
2387 printf("stale after %ld seconds\n", bufqlim
[i
].bl_stale
);
2390 for (i
= 0; i
< BQUEUES
; i
++) {
2391 printf("%s : ", bname
[i
]);
2392 printf("cur = %ld, ", (long)bufqlim
[i
].bl_num
);
2397 * If the getnewbuf() calls bcleanbuf() on the same thread
2398 * there is a potential for stack overrun and deadlocks.
2399 * So we always handoff the work to worker thread for completion
2403 bcleanbuf_thread_init()
2405 static void bcleanbuf_thread();
2407 /* create worker thread */
2408 kernel_thread(kernel_task
, bcleanbuf_thread
);
2414 boolean_t funnel_state
;
2419 funnel_state
= thread_funnel_set(kernel_flock
, TRUE
);
2422 while (blaundrycnt
== 0)
2423 (void)tsleep((void *)&blaundrycnt
, PRIBIO
, "blaundry", 60 * hz
);
2424 bp
= TAILQ_FIRST(&bufqueues
[BQ_LAUNDRY
]);
2425 /* Remove from the queue */
2430 error
= bawrite_internal(bp
, 0);
2432 binstailfree(bp
, &bufqueues
[BQ_LAUNDRY
], BQ_LAUNDRY
);
2435 (void)tsleep((void *)&blaundrycnt
, PRIBIO
, "blaundry", 1);
2438 (void)thread_block(THREAD_CONTINUE_NULL
);
2445 (void) thread_funnel_set(kernel_flock
, funnel_state
);
2450 brecover_data(struct buf
*bp
)
2453 upl_page_info_t
*pl
;
2456 struct vnode
*vp
= bp
->b_vp
;
2458 if (vp
->v_tag
== VT_NFS
)
2460 * NFS currently deals with this case
2461 * in a slightly different manner...
2462 * continue to let it do so
2466 if (!UBCISVALID(vp
) || bp
->b_bufsize
== 0)
2469 kret
= ubc_create_upl(vp
,
2470 ubc_blktooff(vp
, bp
->b_lblkno
),
2475 if (kret
!= KERN_SUCCESS
)
2476 panic("Failed to get pagelists");
2478 for (upl_offset
= 0; upl_offset
< bp
->b_bufsize
; upl_offset
+= PAGE_SIZE
) {
2480 if (!upl_valid_page(pl
, upl_offset
/ PAGE_SIZE
) || !upl_dirty_page(pl
, upl_offset
/ PAGE_SIZE
)) {
2481 ubc_upl_abort(upl
, 0);
2485 SET(bp
->b_flags
, B_PAGELIST
);
2486 bp
->b_pagelist
= upl
;
2488 kret
= ubc_upl_map(upl
, (vm_address_t
*)&(bp
->b_data
));
2489 if (kret
!= KERN_SUCCESS
)
2490 panic("getblk: ubc_upl_map() failed with (%d)", kret
);
2491 if (bp
->b_data
== 0)
2492 panic("ubc_upl_map mapped 0");
2498 SET(bp
->b_flags
, B_INVAL
);
2506 bp_cmp(void *a
, void *b
)
2508 struct buf
*bp_a
= *(struct buf
**)a
,
2509 *bp_b
= *(struct buf
**)b
;
2512 // don't have to worry about negative block
2513 // numbers so this is ok to do.
2515 res
= (bp_a
->b_blkno
- bp_b
->b_blkno
);
2523 bflushq(int whichq
, struct mount
*mp
)
2525 struct buf
*bp
, *next
;
2526 int i
, buf_count
, s
;
2527 int counter
=0, total_writes
=0;
2528 static struct buf
*flush_table
[NFLUSH
];
2530 if (whichq
< 0 || whichq
>= BQUEUES
) {
2536 bp
= TAILQ_FIRST(&bufqueues
[whichq
]);
2537 for(buf_count
=0; bp
; bp
=next
) {
2538 next
= bp
->b_freelist
.tqe_next
;
2540 if (bp
->b_vp
== NULL
|| bp
->b_vp
->v_mount
!= mp
) {
2544 if ((bp
->b_flags
& B_DELWRI
) && (bp
->b_flags
& B_BUSY
) == 0) {
2545 if (whichq
!= BQ_LOCKED
&& (bp
->b_flags
& B_LOCKED
)) {
2546 panic("bflushq: bp @ 0x%x is locked!\n", bp
);
2550 bp
->b_flags
|= B_BUSY
;
2551 flush_table
[buf_count
] = bp
;
2555 if (buf_count
>= NFLUSH
) {
2556 qsort(flush_table
, buf_count
, sizeof(struct buf
*), bp_cmp
);
2558 for(i
=0; i
< buf_count
; i
++) {
2559 bawrite(flush_table
[i
]);
2567 if (buf_count
> 0) {
2568 qsort(flush_table
, buf_count
, sizeof(struct buf
*), bp_cmp
);
2569 for(i
=0; i
< buf_count
; i
++) {
2570 bawrite(flush_table
[i
]);
2574 return total_writes
;