2 * Copyright (c) 2000 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)
73 #define ZALLOC_METADATA 1
75 #include <sys/param.h>
76 #include <sys/systm.h>
79 #include <sys/vnode.h>
80 #include <sys/mount.h>
81 #include <sys/trace.h>
82 #include <sys/malloc.h>
83 #include <sys/resourcevar.h>
84 #include <miscfs/specfs/specdev.h>
86 #include <vm/vm_pageout.h>
88 #include <kern/assert.h>
89 #endif /* DIAGNOSTIC */
90 #include <kern/task.h>
91 #include <kern/zalloc.h>
93 #include <sys/kdebug.h>
95 extern void bufqinc(int q
);
96 extern void bufqdec(int q
);
97 extern void bufq_balance_thread_init();
99 extern void reassignbuf(struct buf
*, struct vnode
*);
100 static struct buf
*getnewbuf(int slpflag
, int slptimeo
, int *queue
);
102 extern int niobuf
; /* The number of IO buffer headers for cluster IO */
106 struct proc
*traceproc
;
107 int tracewhich
, tracebuf
[TRCSIZ
];
109 char traceflags
[TR_NFLAGS
];
113 * Definitions for the buffer hash lists.
115 #define BUFHASH(dvp, lbn) \
116 (&bufhashtbl[((long)(dvp) / sizeof(*(dvp)) + (int)(lbn)) & bufhash])
117 LIST_HEAD(bufhashhdr
, buf
) *bufhashtbl
, invalhash
;
120 /* Definitions for the buffer stats. */
121 struct bufstats bufstats
;
124 * Insq/Remq for the buffer hash lists.
127 #define binshash(bp, dp) LIST_INSERT_HEAD(dp, bp, b_hash)
128 #define bremhash(bp) LIST_REMOVE(bp, b_hash)
132 TAILQ_HEAD(ioqueue
, buf
) iobufqueue
;
133 TAILQ_HEAD(bqueues
, buf
) bufqueues
[BQUEUES
];
138 * Insq/Remq for the buffer free lists.
140 #define binsheadfree(bp, dp, whichq) do { \
141 TAILQ_INSERT_HEAD(dp, bp, b_freelist); \
143 (bp)->b_whichq = whichq; \
144 (bp)->b_timestamp = time.tv_sec; \
147 #define binstailfree(bp, dp, whichq) do { \
148 TAILQ_INSERT_TAIL(dp, bp, b_freelist); \
150 (bp)->b_whichq = whichq; \
151 (bp)->b_timestamp = time.tv_sec; \
154 #define BHASHENTCHECK(bp) \
155 if ((bp)->b_hash.le_prev != (struct buf **)0xdeadbeef) \
156 panic("%x: b_hash.le_prev is not deadbeef", (bp));
158 #define BLISTNONE(bp) \
159 (bp)->b_hash.le_next = (struct buf *)0; \
160 (bp)->b_hash.le_prev = (struct buf **)0xdeadbeef;
162 simple_lock_data_t bufhashlist_slock
; /* lock on buffer hash list */
165 * Time in seconds before a buffer on a list is
166 * considered as a stale buffer
168 #define LRU_IS_STALE 120 /* default value for the LRU */
169 #define AGE_IS_STALE 60 /* default value for the AGE */
170 #define META_IS_STALE 180 /* default value for the BQ_META */
172 int lru_is_stale
= LRU_IS_STALE
;
173 int age_is_stale
= AGE_IS_STALE
;
174 int meta_is_stale
= META_IS_STALE
;
178 blistenterhead(struct bufhashhdr
* head
, struct buf
* bp
)
180 if ((bp
->b_hash
.le_next
= (head
)->lh_first
) != NULL
)
181 (head
)->lh_first
->b_hash
.le_prev
= &(bp
)->b_hash
.le_next
;
182 (head
)->lh_first
= bp
;
183 bp
->b_hash
.le_prev
= &(head
)->lh_first
;
184 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
185 panic("blistenterhead: le_prev is deadbeef");
192 binshash(struct buf
*bp
, struct bufhashhdr
*dp
)
198 simple_lock(&bufhashlist_slock
);
200 if(incore(bp
->b_vp
, bp
->b_lblkno
)) {
201 panic("adding to queue already existing element");
207 for(; nbp
!= NULL
; nbp
= nbp
->b_hash
.le_next
) {
209 panic("buf already in hashlist");
213 LIST_INSERT_HEAD(dp
, bp
, b_hash
);
215 blistenterhead(dp
, bp
);
217 simple_unlock(&bufhashlist_slock
);
221 bremhash(struct buf
*bp
)
225 simple_lock(&bufhashlist_slock
);
226 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
227 panic("bremhash le_prev is deadbeef");
228 if (bp
->b_hash
.le_next
== bp
)
229 panic("bremhash: next points to self");
231 if (bp
->b_hash
.le_next
!= NULL
)
232 bp
->b_hash
.le_next
->b_hash
.le_prev
= bp
->b_hash
.le_prev
;
233 *bp
->b_hash
.le_prev
= (bp
)->b_hash
.le_next
;
234 simple_unlock(&bufhashlist_slock
);
241 * Remove a buffer from the free list it's on
247 struct bqueues
*dp
= NULL
;
251 * We only calculate the head of the freelist when removing
252 * the last element of the list as that is the only time that
253 * it is needed (e.g. to reset the tail pointer).
255 * NB: This makes an assumption about how tailq's are implemented.
257 if (bp
->b_freelist
.tqe_next
== NULL
) {
258 for (dp
= bufqueues
; dp
< &bufqueues
[BQUEUES
]; dp
++)
259 if (dp
->tqh_last
== &bp
->b_freelist
.tqe_next
)
261 if (dp
== &bufqueues
[BQUEUES
])
262 panic("bremfree: lost tail");
264 TAILQ_REMOVE(dp
, bp
, b_freelist
);
265 whichq
= bp
->b_whichq
;
271 static __inline__
void
272 bufhdrinit(struct buf
*bp
)
274 bzero((char *)bp
, sizeof *bp
);
276 bp
->b_rcred
= NOCRED
;
277 bp
->b_wcred
= NOCRED
;
278 bp
->b_vnbufs
.le_next
= NOLIST
;
279 bp
->b_flags
= B_INVAL
;
285 * Initialize buffers and hash links for buffers.
290 register struct buf
*bp
;
291 register struct bqueues
*dp
;
295 static void bufzoneinit();
296 static void bcleanbuf_thread_init();
298 /* Initialize the buffer queues ('freelists') and the hash table */
299 for (dp
= bufqueues
; dp
< &bufqueues
[BQUEUES
]; dp
++)
301 bufhashtbl
= hashinit(nbuf
, M_CACHE
, &bufhash
);
303 simple_lock_init(&bufhashlist_slock
);
305 metabuf
= nbuf
/8; /* reserved for meta buf */
307 /* Initialize the buffer headers */
308 for (i
= 0; i
< nbuf
; i
++) {
313 * metabuf buffer headers on the meta-data list and
314 * rest of the buffer headers on the empty list
322 dp
= &bufqueues
[whichq
];
323 binsheadfree(bp
, dp
, whichq
);
324 binshash(bp
, &invalhash
);
327 for (; i
< nbuf
+ niobuf
; i
++) {
330 binsheadfree(bp
, &iobufqueue
, -1);
333 printf("using %d buffer headers and %d cluster IO buffer headers\n",
336 /* Set up zones used by the buffer cache */
339 /* start the bcleanbuf() thread */
340 bcleanbuf_thread_init();
343 /* create a thread to do dynamic buffer queue balancing */
344 bufq_balance_thread_init();
350 bio_doread(vp
, blkno
, size
, cred
, async
, queuetype
)
358 register struct buf
*bp
;
359 struct proc
*p
= current_proc();
361 bp
= getblk(vp
, blkno
, size
, 0, 0, queuetype
);
364 * If buffer does not have data valid, start a read.
365 * Note that if buffer is B_INVAL, getblk() won't return it.
366 * Therefore, it's valid if it's I/O has completed or been delayed.
368 if (!ISSET(bp
->b_flags
, (B_DONE
| B_DELWRI
))) {
369 /* Start I/O for the buffer (keeping credentials). */
370 SET(bp
->b_flags
, B_READ
| async
);
371 if (cred
!= NOCRED
&& bp
->b_rcred
== NOCRED
) {
373 * NFS has embedded ucred.
374 * Can not crhold() here as that causes zone corruption
376 bp
->b_rcred
= crdup(cred
);
380 trace(TR_BREADMISS
, pack(vp
, size
), blkno
);
382 /* Pay for the read. */
384 p
->p_stats
->p_ru
.ru_inblock
++; /* XXX */
389 trace(TR_BREADHIT
, pack(vp
, size
), blkno
);
395 * This algorithm described in Bach (p.54).
398 bread(vp
, blkno
, size
, cred
, bpp
)
405 register struct buf
*bp
;
407 /* Get buffer for block. */
408 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, BLK_READ
);
410 /* Wait for the read to complete, and return result. */
411 return (biowait(bp
));
415 * Read a disk block. [bread() for meta-data]
416 * This algorithm described in Bach (p.54).
419 meta_bread(vp
, blkno
, size
, cred
, bpp
)
426 register struct buf
*bp
;
428 /* Get buffer for block. */
429 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, BLK_META
);
431 /* Wait for the read to complete, and return result. */
432 return (biowait(bp
));
436 * Read-ahead multiple disk blocks. The first is sync, the rest async.
437 * Trivial modification to the breada algorithm presented in Bach (p.55).
440 breadn(vp
, blkno
, size
, rablks
, rasizes
, nrablks
, cred
, bpp
)
442 daddr_t blkno
; int size
;
443 daddr_t rablks
[]; int rasizes
[];
448 register struct buf
*bp
;
451 bp
= *bpp
= bio_doread(vp
, blkno
, size
, cred
, 0, BLK_READ
);
454 * For each of the read-ahead blocks, start a read, if necessary.
456 for (i
= 0; i
< nrablks
; i
++) {
457 /* If it's in the cache, just go on to next one. */
458 if (incore(vp
, rablks
[i
]))
461 /* Get a buffer for the read-ahead block */
462 (void) bio_doread(vp
, rablks
[i
], rasizes
[i
], cred
, B_ASYNC
, BLK_READ
);
465 /* Otherwise, we had to start a read for it; wait until it's valid. */
466 return (biowait(bp
));
470 * Read with single-block read-ahead. Defined in Bach (p.55), but
471 * implemented as a call to breadn().
472 * XXX for compatibility with old file systems.
475 breada(vp
, blkno
, size
, rablkno
, rabsize
, cred
, bpp
)
477 daddr_t blkno
; int size
;
478 daddr_t rablkno
; int rabsize
;
483 return (breadn(vp
, blkno
, size
, &rablkno
, &rabsize
, 1, cred
, bpp
));
487 * Block write. Described in Bach (p.56)
493 int rv
, sync
, wasdelayed
;
494 struct proc
*p
= current_proc();
499 struct vnode
*vp
= bp
->b_vp
;
501 /* Remember buffer type, to switch on it later. */
502 sync
= !ISSET(bp
->b_flags
, B_ASYNC
);
503 wasdelayed
= ISSET(bp
->b_flags
, B_DELWRI
);
504 CLR(bp
->b_flags
, (B_READ
| B_DONE
| B_ERROR
| B_DELWRI
));
508 * If not synchronous, pay for the I/O operation and make
509 * sure the buf is on the correct vnode queue. We have
510 * to do this now, because if we don't, the vnode may not
511 * be properly notified that its I/O has completed.
517 p
->p_stats
->p_ru
.ru_oublock
++; /* XXX */
520 trace(TR_BWRITE
, pack(vp
, bp
->b_bcount
), bp
->b_lblkno
);
522 /* Initiate disk write. Make sure the appropriate party is charged. */
523 SET(bp
->b_flags
, B_WRITEINPROG
);
530 * If I/O was synchronous, wait for it to complete.
535 * Pay for the I/O operation, if it's not been paid for, and
536 * make sure it's on the correct vnode queue. (async operatings
537 * were payed for above.)
543 p
->p_stats
->p_ru
.ru_oublock
++; /* XXX */
545 /* Release the buffer. */
556 struct vop_bwrite_args
*ap
;
558 return (bwrite(ap
->a_bp
));
564 * The buffer is marked dirty, but is not queued for I/O.
565 * This routine should be used when the buffer is expected
566 * to be modified again soon, typically a small write that
567 * partially fills a buffer.
569 * NB: magnetic tapes cannot be delayed; they must be
570 * written in the order that the writes are requested.
572 * Described in Leffler, et al. (pp. 208-213).
578 struct proc
*p
= current_proc();
584 * If the block hasn't been seen before:
585 * (1) Mark it as having been seen,
586 * (2) Charge for the write.
587 * (3) Make sure it's on its vnode's correct block list,
589 if (!ISSET(bp
->b_flags
, B_DELWRI
)) {
590 SET(bp
->b_flags
, B_DELWRI
);
592 p
->p_stats
->p_ru
.ru_oublock
++; /* XXX */
594 reassignbuf(bp
, bp
->b_vp
);
598 /* If this is a tape block, write it the block now. */
599 if (ISSET(bp
->b_flags
, B_TAPE
)) {
605 /* Otherwise, the "write" is done, so mark and release the buffer. */
606 SET(bp
->b_flags
, B_DONE
);
611 * Asynchronous block write; just an asynchronous bwrite().
618 SET(bp
->b_flags
, B_ASYNC
);
623 * Release a buffer on to the free lists.
624 * Described in Bach (p. 46).
630 struct bqueues
*bufq
;
634 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 388)) | DBG_FUNC_START
,
635 bp
->b_lblkno
* PAGE_SIZE
, bp
, bp
->b_data
, bp
->b_flags
, 0);
637 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
639 /* IO is done. Cleanup the UPL state */
640 if (!ISSET(bp
->b_flags
, B_META
)
641 && UBCINFOEXISTS(bp
->b_vp
) && bp
->b_bufsize
) {
646 if ( !ISSET(bp
->b_flags
, B_PAGELIST
)) {
647 if ( !ISSET(bp
->b_flags
, B_INVAL
)) {
648 kret
= ubc_create_upl(bp
->b_vp
,
649 ubc_blktooff(bp
->b_vp
, bp
->b_lblkno
),
654 if (kret
!= KERN_SUCCESS
)
655 panic("brelse: Failed to get pagelists");
657 upl_ubc_alias_set(upl
, bp
, 5);
658 #endif /* UBC_DEBUG */
662 upl
= bp
->b_pagelist
;
663 kret
= ubc_upl_unmap(upl
);
665 if (kret
!= KERN_SUCCESS
)
666 panic("kernel_upl_unmap failed");
670 if (bp
->b_flags
& (B_ERROR
| B_INVAL
)) {
671 if (bp
->b_flags
& (B_READ
| B_INVAL
))
672 upl_flags
= UPL_ABORT_DUMP_PAGES
;
675 ubc_upl_abort(upl
, upl_flags
);
677 if (ISSET(bp
->b_flags
, (B_DELWRI
| B_WASDIRTY
)))
678 upl_flags
= UPL_COMMIT_SET_DIRTY
;
680 upl_flags
= UPL_COMMIT_CLEAR_DIRTY
;
681 ubc_upl_commit_range(upl
, 0, bp
->b_bufsize
, upl_flags
|
682 UPL_COMMIT_INACTIVATE
| UPL_COMMIT_FREE_ON_EMPTY
);
685 CLR(bp
->b_flags
, B_PAGELIST
);
690 if(ISSET(bp
->b_flags
, B_PAGELIST
))
691 panic("brelse: pagelist set for non VREG; vp=%x", bp
->b_vp
);
694 /* Wake up any processes waiting for any buffer to become free. */
700 /* Wake up any proceeses waiting for _this_ buffer to become free. */
701 if (ISSET(bp
->b_flags
, B_WANTED
)) {
702 CLR(bp
->b_flags
, B_WANTED
);
706 /* Block disk interrupts. */
710 * Determine which queue the buffer should be on, then put it there.
713 /* If it's locked, don't report an error; try again later. */
714 if (ISSET(bp
->b_flags
, (B_LOCKED
|B_ERROR
)) == (B_LOCKED
|B_ERROR
))
715 CLR(bp
->b_flags
, B_ERROR
);
717 /* If it's not cacheable, or an error, mark it invalid. */
718 if (ISSET(bp
->b_flags
, (B_NOCACHE
|B_ERROR
)))
719 SET(bp
->b_flags
, B_INVAL
);
721 if ((bp
->b_bufsize
<= 0) || ISSET(bp
->b_flags
, B_INVAL
)) {
723 * If it's invalid or empty, dissociate it from its vnode
724 * and put on the head of the appropriate queue.
728 CLR(bp
->b_flags
, B_DELWRI
);
729 if (bp
->b_bufsize
<= 0)
730 whichq
= BQ_EMPTY
; /* no data */
732 whichq
= BQ_AGE
; /* invalid data */
734 bufq
= &bufqueues
[whichq
];
735 binsheadfree(bp
, bufq
, whichq
);
738 * It has valid data. Put it on the end of the appropriate
739 * queue, so that it'll stick around for as long as possible.
741 if (ISSET(bp
->b_flags
, B_LOCKED
))
742 whichq
= BQ_LOCKED
; /* locked in core */
743 else if (ISSET(bp
->b_flags
, B_META
))
744 whichq
= BQ_META
; /* meta-data */
745 else if (ISSET(bp
->b_flags
, B_AGE
))
746 whichq
= BQ_AGE
; /* stale but valid data */
748 whichq
= BQ_LRU
; /* valid data */
750 bufq
= &bufqueues
[whichq
];
751 binstailfree(bp
, bufq
, whichq
);
754 /* Unlock the buffer. */
755 CLR(bp
->b_flags
, (B_AGE
| B_ASYNC
| B_BUSY
| B_NOCACHE
));
757 /* Allow disk interrupts. */
760 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 388)) | DBG_FUNC_END
,
761 bp
, bp
->b_data
, bp
->b_flags
, 0, 0);
765 * Determine if a block is in the cache.
766 * Just look on what would be its hash chain. If it's there, return
767 * a pointer to it, unless it's marked invalid. If it's marked invalid,
768 * we normally don't return the buffer, unless the caller explicitly
779 bp
= BUFHASH(vp
, blkno
)->lh_first
;
781 /* Search hash chain */
782 for (; bp
!= NULL
; bp
= bp
->b_hash
.le_next
, bufseen
++) {
783 if (bp
->b_lblkno
== blkno
&& bp
->b_vp
== vp
&&
784 !ISSET(bp
->b_flags
, B_INVAL
))
787 panic("walked more than nbuf in incore");
794 /* XXX FIXME -- Update the comment to reflect the UBC changes -- */
796 * Get a block of requested size that is associated with
797 * a given vnode and block offset. If it is found in the
798 * block cache, mark it as having been found, make it busy
799 * and return it. Otherwise, return an empty block of the
800 * correct size. It is up to the caller to insure that the
801 * cached blocks be of the correct size.
804 getblk(vp
, blkno
, size
, slpflag
, slptimeo
, operation
)
805 register struct vnode
*vp
;
807 int size
, slpflag
, slptimeo
, operation
;
817 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_START
,
818 blkno
* PAGE_SIZE
, size
, operation
, 0, 0);
822 if (bp
= incore(vp
, blkno
)) {
823 /* Found in the Buffer Cache */
824 if (ISSET(bp
->b_flags
, B_BUSY
)) {
830 SET(bp
->b_flags
, B_WANTED
);
831 bufstats
.bufs_busyincore
++;
832 err
= tsleep(bp
, slpflag
| (PRIBIO
+ 1), "getblk",
836 * Callers who call with PCATCH or timeout are
837 * willing to deal with the NULL pointer
839 if (err
&& ((slpflag
& PCATCH
) ||
840 ((err
== EWOULDBLOCK
) && slptimeo
)))
847 /* pagein operation must not use getblk */
848 panic("getblk: pagein for incore busy buffer");
854 /* pageout operation must not use getblk */
855 panic("getblk: pageout for incore busy buffer");
861 panic("getblk: %d unknown operation 1", operation
);
867 SET(bp
->b_flags
, (B_BUSY
| B_CACHE
));
869 bufstats
.bufs_incore
++;
873 if (ISSET(bp
->b_flags
, B_PAGELIST
))
874 panic("pagelist buffer is not busy");
879 if (UBCISVALID(bp
->b_vp
) && bp
->b_bufsize
) {
880 kret
= ubc_create_upl(vp
,
881 ubc_blktooff(vp
, bp
->b_lblkno
),
886 if (kret
!= KERN_SUCCESS
)
887 panic("Failed to get pagelists");
889 SET(bp
->b_flags
, B_PAGELIST
);
890 bp
->b_pagelist
= upl
;
892 if ( !upl_valid_page(pl
, 0))
893 panic("getblk: incore buffer without valid page");
895 if (upl_dirty_page(pl
, 0))
896 SET(bp
->b_flags
, B_WASDIRTY
);
898 CLR(bp
->b_flags
, B_WASDIRTY
);
900 kret
= ubc_upl_map(upl
, (vm_address_t
*)&(bp
->b_data
));
901 if (kret
!= KERN_SUCCESS
) {
902 panic("getblk: ubc_upl_map() failed with (%d)",
905 if (bp
->b_data
== 0) panic("ubc_upl_map mapped 0");
911 * VM is not involved in IO for the meta data
912 * buffer already has valid data
915 panic("bp->b_data null incore buf=%x", bp
);
920 panic("getblk: paging operation 1");
924 panic("getblk: %d unknown operation 2", operation
);
929 } else { /* not incore() */
930 int queue
= BQ_EMPTY
; /* Start with no preference */
933 if ((operation
== BLK_META
) || (UBCINVALID(vp
)) ||
934 !(UBCINFOEXISTS(vp
))) {
935 operation
= BLK_META
;
937 if ((bp
= getnewbuf(slpflag
, slptimeo
, &queue
)) == NULL
)
939 if (incore(vp
, blkno
)) {
940 SET(bp
->b_flags
, B_INVAL
);
941 binshash(bp
, &invalhash
);
947 * if it is meta, the queue may be set to other
948 * type so reset as well as mark it to be B_META
949 * so that when buffer is released it will goto META queue
950 * Also, if the vnode is not VREG, then it is META
952 if (operation
== BLK_META
) {
953 SET(bp
->b_flags
, B_META
);
957 * Insert in the hash so that incore() can find it
959 binshash(bp
, BUFHASH(vp
, blkno
));
965 /* buffer data is invalid */
969 panic("bp->b_data is not nul; %x",bp
);
970 kret
= kmem_alloc(kernel_map
,
971 &bp
->b_data
, bp
->b_bufsize
);
972 if (kret
!= KERN_SUCCESS
)
973 panic("getblk: kmem_alloc() returned %d", kret
);
974 #endif /* ZALLOC_METADATA */
977 panic("bp->b_data is null %x",bp
);
979 bp
->b_blkno
= bp
->b_lblkno
= blkno
;
982 bufstats
.bufs_miss
++;
985 panic("b_data is 0: 2");
987 /* wakeup the buffer */
988 CLR(bp
->b_flags
, B_WANTED
);
995 if (ISSET(bp
->b_flags
, B_PAGELIST
))
996 panic("B_PAGELIST in bp=%x",bp
);
998 kret
= ubc_create_upl(vp
,
999 ubc_blktooff(vp
, blkno
),
1004 if (kret
!= KERN_SUCCESS
)
1005 panic("Failed to get pagelists");
1008 upl_ubc_alias_set(upl
, bp
, 4);
1009 #endif /* UBC_DEBUG */
1010 bp
->b_blkno
= bp
->b_lblkno
= blkno
;
1011 bp
->b_pagelist
= upl
;
1013 SET(bp
->b_flags
, B_PAGELIST
);
1015 if (upl_valid_page(pl
, 0)) {
1016 SET(bp
->b_flags
, B_CACHE
| B_DONE
);
1017 bufstats
.bufs_vmhits
++;
1019 pagedirty
= upl_dirty_page(pl
, 0);
1022 SET(bp
->b_flags
, B_WASDIRTY
);
1024 if (vp
->v_tag
== VT_NFS
) {
1031 f_offset
= ubc_blktooff(vp
, blkno
);
1033 if (f_offset
> vp
->v_ubcinfo
->ui_size
) {
1034 CLR(bp
->b_flags
, (B_CACHE
|B_DONE
|B_WASDIRTY
));
1038 valid_size
= min(((unsigned int)(vp
->v_ubcinfo
->ui_size
- f_offset
)), PAGE_SIZE
);
1039 bp
->b_validend
= valid_size
;
1042 bp
->b_dirtyend
= valid_size
;
1046 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_NONE
,
1047 bp
->b_validend
, bp
->b_dirtyend
,
1048 (int)vp
->v_ubcinfo
->ui_size
, 0, 0);
1056 bp
->b_validend
= bp
->b_bcount
;
1057 bp
->b_dirtyend
= bp
->b_bcount
;
1060 bp
->b_validend
= bp
->b_bcount
;
1064 if (error
= VOP_BMAP(vp
, bp
->b_lblkno
, NULL
, &bp
->b_blkno
, NULL
)) {
1065 panic("VOP_BMAP failed in getblk");
1068 * XXX: We probably should invalidate the VM Page
1070 bp
->b_error
= error
;
1071 SET(bp
->b_flags
, (B_ERROR
| B_INVAL
));
1072 /* undo B_DONE that was set before upl_commit() */
1073 CLR(bp
->b_flags
, B_DONE
);
1078 bufstats
.bufs_miss
++;
1080 kret
= ubc_upl_map(upl
, (vm_address_t
*)&(bp
->b_data
));
1081 if (kret
!= KERN_SUCCESS
) {
1082 panic("getblk: ubc_upl_map() "
1083 "failed with (%d)", kret
);
1085 if (bp
->b_data
== 0) panic("kernel_upl_map mapped 0");
1095 panic("getblk: paging operation 2");
1098 panic("getblk: %d unknown operation 3", operation
);
1104 if (bp
->b_data
== NULL
)
1105 panic("getblk: bp->b_addr is null");
1107 if (bp
->b_bufsize
& 0xfff) {
1109 if (ISSET(bp
->b_flags
, B_META
) && (bp
->b_bufsize
& 0x1ff))
1110 #endif /* ZALLOC_METADATA */
1111 panic("getblk: bp->b_bufsize = %d", bp
->b_bufsize
);
1114 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 386)) | DBG_FUNC_END
,
1115 bp
, bp
->b_data
, bp
->b_flags
, 3, 0);
1121 * Get an empty, disassociated buffer of given size.
1128 int queue
= BQ_EMPTY
;
1129 #if !ZALLOC_METADATA
1131 vm_size_t desired_size
= roundup(size
, CLBYTES
);
1133 if (desired_size
> MAXBSIZE
)
1134 panic("geteblk: buffer larger than MAXBSIZE requested");
1135 #endif /* ZALLOC_METADATA */
1137 while ((bp
= getnewbuf(0, 0, &queue
)) == 0)
1140 SET(bp
->b_flags
, (B_META
|B_INVAL
));
1142 SET(bp
->b_flags
, B_INVAL
);
1143 #endif /* ZALLOC_METADATA */
1146 assert(queue
== BQ_EMPTY
);
1147 #endif /* DIAGNOSTIC */
1148 /* XXX need to implement logic to deal with other queues */
1150 #if !ZALLOC_METADATA
1151 /* Empty buffer - allocate pages */
1152 kret
= kmem_alloc_aligned(kernel_map
, &bp
->b_data
, desired_size
);
1153 if (kret
!= KERN_SUCCESS
)
1154 panic("geteblk: kmem_alloc_aligned returned %d", kret
);
1155 #endif /* ZALLOC_METADATA */
1157 binshash(bp
, &invalhash
);
1159 bufstats
.bufs_eblk
++;
1166 * Zones for the meta data buffers
1170 #define MAXMETA 4096
1172 struct meta_zone_entry
{
1179 struct meta_zone_entry meta_zones
[] = {
1180 {NULL
, (MINMETA
* 1), 128 * (MINMETA
* 1), "buf.512" },
1181 {NULL
, (MINMETA
* 2), 64 * (MINMETA
* 2), "buf.1024" },
1182 {NULL
, (MINMETA
* 3), 16 * (MINMETA
* 3), "buf.1536" },
1183 {NULL
, (MINMETA
* 4), 16 * (MINMETA
* 4), "buf.2048" },
1184 {NULL
, (MINMETA
* 5), 16 * (MINMETA
* 5), "buf.2560" },
1185 {NULL
, (MINMETA
* 6), 16 * (MINMETA
* 6), "buf.3072" },
1186 {NULL
, (MINMETA
* 7), 16 * (MINMETA
* 7), "buf.3584" },
1187 {NULL
, (MINMETA
* 8), 512 * (MINMETA
* 8), "buf.4096" },
1188 {NULL
, 0, 0, "" } /* End */
1190 #endif /* ZALLOC_METADATA */
1192 zone_t buf_hdr_zone
;
1196 * Initialize the meta data zones
1204 for (i
= 0; meta_zones
[i
].mz_size
!= 0; i
++) {
1205 meta_zones
[i
].mz_zone
=
1206 zinit(meta_zones
[i
].mz_size
,
1207 meta_zones
[i
].mz_max
,
1209 meta_zones
[i
].mz_name
);
1211 #endif /* ZALLOC_METADATA */
1212 buf_hdr_zone
= zinit(sizeof(struct buf
), 32, PAGE_SIZE
, "buf headers");
1217 getbufzone(size_t size
)
1222 panic("getbufzone: incorect size = %d", size
);
1224 i
= (size
/ 512) - 1;
1225 return (meta_zones
[i
].mz_zone
);
1227 #endif /* ZALLOC_METADATA */
1230 * With UBC, there is no need to expand / shrink the file data
1231 * buffer. The VM uses the same pages, hence no waste.
1232 * All the file data buffers can have one size.
1233 * In fact expand / shrink would be an expensive operation.
1235 * Only exception to this is meta-data buffers. Most of the
1236 * meta data operations are smaller than PAGE_SIZE. Having the
1237 * meta-data buffers grow and shrink as needed, optimizes use
1238 * of the kernel wired memory.
1246 vm_size_t desired_size
;
1248 desired_size
= roundup(size
, CLBYTES
);
1250 if(desired_size
< PAGE_SIZE
)
1251 desired_size
= PAGE_SIZE
;
1252 if (desired_size
> MAXBSIZE
)
1253 panic("allocbuf: buffer larger than MAXBSIZE requested");
1256 if (ISSET(bp
->b_flags
, B_META
)) {
1259 size_t nsize
= roundup(size
, MINMETA
);
1262 vm_offset_t elem
= (vm_offset_t
)bp
->b_data
;
1264 if (ISSET(bp
->b_flags
, B_ZALLOC
))
1265 if (bp
->b_bufsize
<= MAXMETA
) {
1266 if (bp
->b_bufsize
< nsize
) {
1267 /* reallocate to a bigger size */
1268 desired_size
= nsize
;
1270 zprev
= getbufzone(bp
->b_bufsize
);
1271 z
= getbufzone(nsize
);
1272 bp
->b_data
= (caddr_t
)zalloc(z
);
1274 panic("allocbuf: zalloc() returned NULL");
1275 bcopy(elem
, bp
->b_data
, bp
->b_bufsize
);
1278 desired_size
= bp
->b_bufsize
;
1281 panic("allocbuf: B_ZALLOC set incorrectly");
1283 if (bp
->b_bufsize
< desired_size
) {
1284 /* reallocate to a bigger size */
1285 kret
= kmem_alloc(kernel_map
, &bp
->b_data
, desired_size
);
1286 if (kret
!= KERN_SUCCESS
)
1287 panic("allocbuf: kmem_alloc() returned %d", kret
);
1289 panic("allocbuf: null b_data");
1290 bcopy(elem
, bp
->b_data
, bp
->b_bufsize
);
1291 kmem_free(kernel_map
, elem
, bp
->b_bufsize
);
1293 desired_size
= bp
->b_bufsize
;
1296 /* new allocation */
1297 if (nsize
<= MAXMETA
) {
1298 desired_size
= nsize
;
1299 z
= getbufzone(nsize
);
1300 bp
->b_data
= (caddr_t
)zalloc(z
);
1302 panic("allocbuf: zalloc() returned NULL 2");
1303 SET(bp
->b_flags
, B_ZALLOC
);
1305 kret
= kmem_alloc(kernel_map
, &bp
->b_data
, desired_size
);
1306 if (kret
!= KERN_SUCCESS
)
1307 panic("allocbuf: kmem_alloc() 2 returned %d", kret
);
1309 panic("allocbuf: null b_data 2");
1314 if (ISSET(bp
->b_flags
, B_META
) && (bp
->b_data
== 0))
1315 panic("allocbuf: bp->b_data is NULL");
1316 #endif /* ZALLOC_METADATA */
1318 bp
->b_bufsize
= desired_size
;
1319 bp
->b_bcount
= size
;
1323 * Get a new buffer from one of the free lists.
1325 * Request for a queue is passes in. The queue from which the buffer was taken
1326 * from is returned. Out of range queue requests get BQ_EMPTY. Request for
1327 * BQUEUE means no preference. Use heuristics in that case.
1328 * Heuristics is as follows:
1329 * Try BQ_AGE, BQ_LRU, BQ_EMPTY, BQ_META in that order.
1330 * If none available block till one is made available.
1331 * If buffers available on both BQ_AGE and BQ_LRU, check the timestamps.
1332 * Pick the most stale buffer.
1333 * If found buffer was marked delayed write, start the async. write
1334 * and restart the search.
1335 * Initialize the fields and disassociate the buffer from the vnode.
1336 * Remove the buffer from the hash. Return the buffer and the queue
1337 * on which it was found.
1341 getnewbuf(slpflag
, slptimeo
, queue
)
1342 int slpflag
, slptimeo
;
1345 register struct buf
*bp
;
1346 register struct buf
*lru_bp
;
1347 register struct buf
*age_bp
;
1348 register struct buf
*meta_bp
;
1349 register int age_time
, lru_time
, bp_time
, meta_time
;
1352 int req
= *queue
; /* save it for restarts */
1357 /* invalid request gets empty queue */
1358 if ((*queue
> BQUEUES
) || (*queue
< 0)
1359 || (*queue
== BQ_LAUNDRY
) || (*queue
== BQ_LOCKED
))
1362 /* (*queue == BQUEUES) means no preference */
1363 if (*queue
!= BQUEUES
) {
1364 /* Try for the requested queue first */
1365 bp
= bufqueues
[*queue
].tqh_first
;
1370 /* Unable to use requested queue */
1371 age_bp
= bufqueues
[BQ_AGE
].tqh_first
;
1372 lru_bp
= bufqueues
[BQ_LRU
].tqh_first
;
1373 meta_bp
= bufqueues
[BQ_META
].tqh_first
;
1375 if (!age_bp
&& !lru_bp
&& !meta_bp
) { /* Unavailble on AGE or LRU */
1376 /* Try the empty list first */
1377 bp
= bufqueues
[BQ_EMPTY
].tqh_first
;
1383 /* Create a new temparory buffer header */
1384 bp
= (struct buf
*)zalloc(buf_hdr_zone
);
1389 binshash(bp
, &invalhash
);
1390 SET(bp
->b_flags
, B_HDRALLOC
);
1392 binsheadfree(bp
, &bufqueues
[BQ_EMPTY
], BQ_EMPTY
);
1397 /* Log this error condition */
1398 printf("getnewbuf: No useful buffers");
1400 /* wait for a free buffer of any kind */
1402 bufstats
.bufs_sleeps
++;
1403 tsleep(&needbuffer
, slpflag
|(PRIBIO
+1), "getnewbuf", slptimeo
);
1408 /* Buffer available either on AGE or LRU or META */
1412 /* Buffer available either on AGE or LRU */
1416 } else if (!lru_bp
) {
1419 } else { /* buffer available on both AGE and LRU */
1420 age_time
= time
.tv_sec
- age_bp
->b_timestamp
;
1421 lru_time
= time
.tv_sec
- lru_bp
->b_timestamp
;
1422 if ((age_time
< 0) || (lru_time
< 0)) { /* time set backwards */
1426 * we should probably re-timestamp eveything in the
1427 * queues at this point with the current time
1430 if ((lru_time
>= lru_is_stale
) && (age_time
< age_is_stale
)) {
1440 if (!bp
) { /* Neither on AGE nor on LRU */
1443 } else if (meta_bp
) {
1444 bp_time
= time
.tv_sec
- bp
->b_timestamp
;
1445 meta_time
= time
.tv_sec
- meta_bp
->b_timestamp
;
1447 if (!(bp_time
< 0) && !(meta_time
< 0)) {
1448 /* time not set backwards */
1450 bp_is_stale
= (*queue
== BQ_LRU
) ?
1451 lru_is_stale
: age_is_stale
;
1453 if ((meta_time
>= meta_is_stale
) &&
1454 (bp_time
< bp_is_stale
)) {
1462 panic("getnewbuf: null bp");
1465 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
1466 panic("getnewbuf: le_prev is deadbeef");
1468 if(ISSET(bp
->b_flags
, B_BUSY
))
1469 panic("getnewbuf reusing BUSY buf");
1472 if (bcleanbuf(bp
)) {
1473 /* bawrite() issued, buffer not ready */
1481 #include <mach/mach_types.h>
1482 #include <mach/memory_object_types.h>
1486 * Returns 0 is buffer is ready to use,
1487 * Returns 1 if issued a bawrite() to indicate
1488 * that the buffer is not ready.
1491 bcleanbuf(struct buf
*bp
)
1498 /* Remove from the queue */
1501 /* Buffer is no longer on free lists. */
1502 SET(bp
->b_flags
, B_BUSY
);
1504 if (bp
->b_hash
.le_prev
== (struct buf
**)0xdeadbeef)
1505 panic("bcleanbuf: le_prev is deadbeef");
1508 * If buffer was a delayed write, start the IO by queuing
1509 * it on the LAUNDRY queue, and return 1
1511 if (ISSET(bp
->b_flags
, B_DELWRI
)) {
1513 binstailfree(bp
, &bufqueues
[BQ_LAUNDRY
], BQ_LAUNDRY
);
1515 wakeup(&blaundrycnt
);
1526 if (ISSET(bp
->b_flags
, B_META
)) {
1528 vm_offset_t elem
= (vm_offset_t
)bp
->b_data
;
1530 panic("bcleanbuf: NULL bp->b_data B_META buffer");
1532 if (ISSET(bp
->b_flags
, B_ZALLOC
)) {
1533 if (bp
->b_bufsize
<= MAXMETA
) {
1536 z
= getbufzone(bp
->b_bufsize
);
1537 bp
->b_data
= (caddr_t
)0xdeadbeef;
1539 CLR(bp
->b_flags
, B_ZALLOC
);
1541 panic("bcleanbuf: B_ZALLOC set incorrectly");
1543 bp
->b_data
= (caddr_t
)0xdeadbeef;
1544 kmem_free(kernel_map
, elem
, bp
->b_bufsize
);
1547 if (bp
->b_data
== 0)
1548 panic("bcleanbuf: bp->b_data == NULL for B_META buffer");
1550 kmem_free(kernel_map
, bp
->b_data
, bp
->b_bufsize
);
1551 #endif /* ZALLOC_METADATA */
1554 trace(TR_BRELSE
, pack(bp
->b_vp
, bp
->b_bufsize
), bp
->b_lblkno
);
1556 /* disassociate us from our vnode, if we had one... */
1559 /* clear out various other fields */
1562 bp
->b_flags
= B_BUSY
;
1564 bp
->b_blkno
= bp
->b_lblkno
= 0;
1569 bp
->b_dirtyoff
= bp
->b_dirtyend
= 0;
1570 bp
->b_validoff
= bp
->b_validend
= 0;
1572 /* nuke any credentials we were holding */
1574 if (cred
!= NOCRED
) {
1575 bp
->b_rcred
= NOCRED
;
1579 if (cred
!= NOCRED
) {
1580 bp
->b_wcred
= NOCRED
;
1589 * Wait for operations on the buffer to complete.
1590 * When they do, extract and return the I/O's error value.
1597 upl_page_info_t
*pl
;
1602 while (!ISSET(bp
->b_flags
, B_DONE
))
1603 tsleep(bp
, PRIBIO
+ 1, "biowait", 0);
1606 /* check for interruption of I/O (e.g. via NFS), then errors. */
1607 if (ISSET(bp
->b_flags
, B_EINTR
)) {
1608 CLR(bp
->b_flags
, B_EINTR
);
1610 } else if (ISSET(bp
->b_flags
, B_ERROR
))
1611 return (bp
->b_error
? bp
->b_error
: EIO
);
1617 * Mark I/O complete on a buffer.
1619 * If a callback has been requested, e.g. the pageout
1620 * daemon, do so. Otherwise, awaken waiting processes.
1622 * [ Leffler, et al., says on p.247:
1623 * "This routine wakes up the blocked process, frees the buffer
1624 * for an asynchronous write, or, for a request by the pagedaemon
1625 * process, invokes a procedure specified in the buffer structure" ]
1627 * In real life, the pagedaemon (or other system processes) wants
1628 * to do async stuff to, and doesn't want the buffer brelse()'d.
1629 * (for swap pager, that puts swap buffers on the free lists (!!!),
1630 * for the vn device, that puts malloc'd buffers on the free lists!)
1636 boolean_t funnel_state
;
1639 funnel_state
= thread_funnel_set(kernel_flock
, TRUE
);
1641 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 387)) | DBG_FUNC_START
,
1642 bp
, bp
->b_data
, bp
->b_flags
, 0, 0);
1644 if (ISSET(bp
->b_flags
, B_DONE
))
1645 panic("biodone already");
1646 SET(bp
->b_flags
, B_DONE
); /* note that it's done */
1648 * I/O was done, so don't believe
1649 * the DIRTY state from VM anymore
1651 CLR(bp
->b_flags
, B_WASDIRTY
);
1653 if (!ISSET(bp
->b_flags
, B_READ
) && !ISSET(bp
->b_flags
, B_RAW
))
1654 vwakeup(bp
); /* wake up reader */
1656 if (ISSET(bp
->b_flags
, B_CALL
)) { /* if necessary, call out */
1657 CLR(bp
->b_flags
, B_CALL
); /* but note callout done */
1658 (*bp
->b_iodone
)(bp
);
1659 } else if (ISSET(bp
->b_flags
, B_ASYNC
)) /* if async, release it */
1661 else { /* or just wakeup the buffer */
1662 CLR(bp
->b_flags
, B_WANTED
);
1666 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW
, 387)) | DBG_FUNC_END
,
1667 bp
, bp
->b_data
, bp
->b_flags
, 0, 0);
1669 thread_funnel_set(kernel_flock
, funnel_state
);
1673 * Return a count of buffers on the "locked" queue.
1678 register struct buf
*bp
;
1681 for (bp
= bufqueues
[BQ_LOCKED
].tqh_first
; bp
;
1682 bp
= bp
->b_freelist
.tqe_next
)
1688 * Return a count of 'busy' buffers. Used at the time of shutdown.
1691 count_busy_buffers()
1693 register struct buf
*bp
;
1694 register int nbusy
= 0;
1696 for (bp
= &buf
[nbuf
]; --bp
>= buf
; )
1697 if ((bp
->b_flags
& (B_BUSY
|B_INVAL
)) == B_BUSY
)
1702 #if 1 /*DIAGNOSTIC */
1704 * Print out statistics on the current allocation of the buffer pool.
1705 * Can be enabled to print out on every ``sync'' by setting "syncprt"
1706 * in vfs_syscalls.c using sysctl.
1712 register struct buf
*bp
;
1713 register struct bqueues
*dp
;
1714 int counts
[MAXBSIZE
/CLBYTES
+1];
1715 static char *bname
[BQUEUES
] =
1716 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
1718 for (dp
= bufqueues
, i
= 0; dp
< &bufqueues
[BQUEUES
]; dp
++, i
++) {
1720 for (j
= 0; j
<= MAXBSIZE
/CLBYTES
; j
++)
1723 for (bp
= dp
->tqh_first
; bp
; bp
= bp
->b_freelist
.tqe_next
) {
1724 counts
[bp
->b_bufsize
/CLBYTES
]++;
1728 printf("%s: total-%d", bname
[i
], count
);
1729 for (j
= 0; j
<= MAXBSIZE
/CLBYTES
; j
++)
1731 printf(", %d-%d", j
* CLBYTES
, counts
[j
]);
1735 #endif /* DIAGNOSTIC */
1737 #define NRESERVEDIOBUFS 16
1740 alloc_io_buf(vp
, priv
)
1744 register struct buf
*bp
;
1749 while (niobuf
- NRESERVEDIOBUFS
< bufstats
.bufs_iobufinuse
&& !priv
) {
1751 bufstats
.bufs_iobufsleeps
++;
1752 (void) tsleep(&need_iobuffer
, (PRIBIO
+1), "alloc_io_buf", 0);
1755 while ((bp
= iobufqueue
.tqh_first
) == NULL
) {
1757 bufstats
.bufs_iobufsleeps
++;
1758 (void) tsleep(&need_iobuffer
, (PRIBIO
+1), "alloc_io_buf1", 0);
1761 TAILQ_REMOVE(&iobufqueue
, bp
, b_freelist
);
1762 bp
->b_timestamp
= 0;
1764 /* clear out various fields */
1765 bp
->b_flags
= B_BUSY
;
1766 bp
->b_blkno
= bp
->b_lblkno
= 0;
1774 if (vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
)
1775 bp
->b_dev
= vp
->v_rdev
;
1778 bufstats
.bufs_iobufinuse
++;
1779 if (bufstats
.bufs_iobufinuse
> bufstats
.bufs_iobufmax
)
1780 bufstats
.bufs_iobufmax
= bufstats
.bufs_iobufinuse
;
1793 /* put buffer back on the head of the iobufqueue */
1795 bp
->b_flags
= B_INVAL
;
1797 binsheadfree(bp
, &iobufqueue
, -1);
1799 /* Wake up any processes waiting for any buffer to become free. */
1800 if (need_iobuffer
) {
1802 wakeup(&need_iobuffer
);
1804 bufstats
.bufs_iobufinuse
--;
1809 /* not hookedup yet */
1811 /* XXX move this to a separate file */
1813 * Dynamic Scaling of the Buffer Queues
1816 typedef long long blsize_t
;
1818 blsize_t MAXNBUF
; /* initialize to (mem_size / PAGE_SIZE) */
1819 /* Global tunable limits */
1820 blsize_t nbufh
; /* number of buffer headers */
1821 blsize_t nbuflow
; /* minimum number of buffer headers required */
1822 blsize_t nbufhigh
; /* maximum number of buffer headers allowed */
1823 blsize_t nbuftarget
; /* preferred number of buffer headers */
1828 * 1. 0 < nbuflow <= nbufh <= nbufhigh
1829 * 2. nbufhigh <= MAXNBUF
1830 * 3. 0 < nbuflow <= nbuftarget <= nbufhigh
1831 * 4. nbufh can not be set by sysctl().
1834 /* Per queue tunable limits */
1837 blsize_t bl_nlow
; /* minimum number of buffer headers required */
1838 blsize_t bl_num
; /* number of buffer headers on the queue */
1839 blsize_t bl_nlhigh
; /* maximum number of buffer headers allowed */
1840 blsize_t bl_target
; /* preferred number of buffer headers */
1841 long bl_stale
; /* Seconds after which a buffer is considered stale */
1847 * 1. 0 <= bl_nlow <= bl_num <= bl_nlhigh
1848 * 2. bl_nlhigh <= MAXNBUF
1849 * 3. bufqlim[BQ_META].bl_nlow != 0
1850 * 4. bufqlim[BQ_META].bl_nlow > (number of possible concurrent
1851 * file system IO operations)
1852 * 5. bl_num can not be set by sysctl().
1853 * 6. bl_nhigh <= nbufhigh
1859 * Defining it blsize_t as long permits 2^31 buffer headers per queue.
1860 * Which can describe (2^31 * PAGE_SIZE) memory per queue.
1862 * These limits are exported to by means of sysctl().
1863 * It was decided to define blsize_t as a 64 bit quantity.
1864 * This will make sure that we will not be required to change it
1865 * as long as we do not exceed 64 bit address space for the kernel.
1867 * low and high numbers parameters initialized at compile time
1868 * and boot arguments can be used to override them. sysctl()
1869 * would not change the value. sysctl() can get all the values
1870 * but can set only target. num is the current level.
1872 * Advantages of having a "bufqscan" thread doing the balancing are,
1873 * Keep enough bufs on BQ_EMPTY.
1874 * getnewbuf() by default will always select a buffer from the BQ_EMPTY.
1875 * getnewbuf() perfoms best if a buffer was found there.
1876 * Also this minimizes the possibility of starting IO
1877 * from getnewbuf(). That's a performance win, too.
1879 * Localize complex logic [balancing as well as time aging]
1882 * Simplify getnewbuf() logic by elimination of time aging code.
1888 * The goal of the dynamic scaling of the buffer queues to to keep
1889 * the size of the LRU close to bl_target. Buffers on a queue would
1892 * There would be a thread which will be responsible for "balancing"
1893 * the buffer cache queues.
1895 * The scan order would be: AGE, LRU, META, EMPTY.
1898 long bufqscanwait
= 0;
1900 extern void bufqscan_thread();
1901 extern int balancebufq(int q
);
1902 extern int btrimempty(int n
);
1903 extern int initbufqscan(void);
1904 extern int nextbufq(int q
);
1905 extern void buqlimprt(int all
);
1908 bufq_balance_thread_init()
1911 if (bufqscanwait
++ == 0) {
1914 /* Initalize globals */
1915 MAXNBUF
= (mem_size
/ PAGE_SIZE
);
1917 nbuflow
= min(nbufh
, 100);
1918 nbufhigh
= min(MAXNBUF
, max(nbufh
, 2048));
1919 nbuftarget
= (mem_size
>> 5) / PAGE_SIZE
;
1920 nbuftarget
= max(nbuflow
, nbuftarget
);
1921 nbuftarget
= min(nbufhigh
, nbuftarget
);
1924 * Initialize the bufqlim
1928 bufqlim
[BQ_LOCKED
].bl_nlow
= 0;
1929 bufqlim
[BQ_LOCKED
].bl_nlhigh
= 32;
1930 bufqlim
[BQ_LOCKED
].bl_target
= 0;
1931 bufqlim
[BQ_LOCKED
].bl_stale
= 30;
1934 bufqlim
[BQ_LRU
].bl_nlow
= 0;
1935 bufqlim
[BQ_LRU
].bl_nlhigh
= nbufhigh
/4;
1936 bufqlim
[BQ_LRU
].bl_target
= nbuftarget
/4;
1937 bufqlim
[BQ_LRU
].bl_stale
= LRU_IS_STALE
;
1940 bufqlim
[BQ_AGE
].bl_nlow
= 0;
1941 bufqlim
[BQ_AGE
].bl_nlhigh
= nbufhigh
/4;
1942 bufqlim
[BQ_AGE
].bl_target
= nbuftarget
/4;
1943 bufqlim
[BQ_AGE
].bl_stale
= AGE_IS_STALE
;
1946 bufqlim
[BQ_EMPTY
].bl_nlow
= 0;
1947 bufqlim
[BQ_EMPTY
].bl_nlhigh
= nbufhigh
/4;
1948 bufqlim
[BQ_EMPTY
].bl_target
= nbuftarget
/4;
1949 bufqlim
[BQ_EMPTY
].bl_stale
= 600000;
1952 bufqlim
[BQ_META
].bl_nlow
= 0;
1953 bufqlim
[BQ_META
].bl_nlhigh
= nbufhigh
/4;
1954 bufqlim
[BQ_META
].bl_target
= nbuftarget
/4;
1955 bufqlim
[BQ_META
].bl_stale
= META_IS_STALE
;
1958 bufqlim
[BQ_LOCKED
].bl_nlow
= 0;
1959 bufqlim
[BQ_LOCKED
].bl_nlhigh
= 32;
1960 bufqlim
[BQ_LOCKED
].bl_target
= 0;
1961 bufqlim
[BQ_LOCKED
].bl_stale
= 30;
1966 /* create worker thread */
1967 kernel_thread(kernel_task
, bufqscan_thread
);
1970 /* The workloop for the buffer balancing thread */
1974 boolean_t funnel_state
;
1977 funnel_state
= thread_funnel_set(kernel_flock
, TRUE
);
1981 int q
; /* buffer queue to process */
1983 for (q
= initbufqscan(); q
; ) {
1984 moretodo
|= balancebufq(q
);
1993 (void)tsleep((void *)&bufqscanwait
, PRIBIO
, "bufqscanwait", 60 * hz
);
1997 (void) thread_funnel_set(kernel_flock
, FALSE
);
2000 /* Seed for the buffer queue balancing */
2004 /* Start with AGE queue */
2008 /* Pick next buffer queue to balance */
2012 int order
[] = { BQ_AGE
, BQ_LRU
, BQ_META
, BQ_EMPTY
, 0 };
2019 /* function to balance the buffer queues */
2027 /* reject invalid q */
2028 if ((q
< 0) || (q
>= BQUEUES
))
2031 /* LOCKED or LAUNDRY queue MUST not be balanced */
2032 if ((q
== BQ_LOCKED
) || (q
== BQ_LAUNDRY
))
2035 n
= (bufqlim
[q
].bl_num
- bufqlim
[q
].bl_target
);
2037 /* If queue has less than target nothing more to do */
2042 /* Balance only a small amount (12.5%) at a time */
2046 /* EMPTY queue needs special handling */
2047 if (q
== BQ_EMPTY
) {
2048 moretodo
|= btrimempty(n
);
2052 for (; n
> 0; n
--) {
2053 struct buf
*bp
= bufqueues
[q
].tqh_first
;
2057 /* check if it's stale */
2058 if ((time
.tv_sec
- bp
->b_timestamp
) > bufqlim
[q
].bl_stale
) {
2059 if (bcleanbuf(bp
)) {
2060 /* bawrite() issued, bp not ready */
2063 /* release the cleaned buffer to BQ_EMPTY */
2064 SET(bp
->b_flags
, B_INVAL
);
2080 * When struct buf are allocated dynamically, this would
2081 * reclaim upto 'n' struct buf from the empty queue.
2090 if ((q
< 0) || (q
>= BQUEUES
))
2093 bufqlim
[q
].bl_num
++;
2100 if ((q
< 0) || (q
>= BQUEUES
))
2103 bufqlim
[q
].bl_num
--;
2111 static char *bname
[BQUEUES
] =
2112 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
2115 for (i
= 0; i
< BQUEUES
; i
++) {
2116 printf("%s : ", bname
[i
]);
2117 printf("min = %d, ", (long)bufqlim
[i
].bl_nlow
);
2118 printf("cur = %d, ", (long)bufqlim
[i
].bl_num
);
2119 printf("max = %d, ", (long)bufqlim
[i
].bl_nlhigh
);
2120 printf("target = %d, ", (long)bufqlim
[i
].bl_target
);
2121 printf("stale after %d seconds\n", bufqlim
[i
].bl_stale
);
2124 for (i
= 0; i
< BQUEUES
; i
++) {
2125 printf("%s : ", bname
[i
]);
2126 printf("cur = %d, ", (long)bufqlim
[i
].bl_num
);
2131 * If the getnewbuf() calls bcleanbuf() on the same thread
2132 * there is a potential for stack overrun and deadlocks.
2133 * So we always handoff the work to worker thread for completion
2137 bcleanbuf_thread_init()
2139 static void bcleanbuf_thread();
2141 /* create worker thread */
2142 kernel_thread(kernel_task
, bcleanbuf_thread
);
2148 boolean_t funnel_state
;
2151 funnel_state
= thread_funnel_set(kernel_flock
, TRUE
);
2154 while (blaundrycnt
== 0)
2155 (void)tsleep((void *)&blaundrycnt
, PRIBIO
, "blaundry", 60 * hz
);
2156 bp
= TAILQ_FIRST(&bufqueues
[BQ_LAUNDRY
]);
2157 /* Remove from the queue */
2165 (void) thread_funnel_set(kernel_flock
, funnel_state
);