]> git.saurik.com Git - apple/xnu.git/blob - bsd/vfs/vfs_bio.c
xnu-1504.9.37.tar.gz
[apple/xnu.git] / bsd / vfs / vfs_bio.c
1 /*
2 * Copyright (c) 2000-2008 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
29 /*-
30 * Copyright (c) 1994 Christopher G. Demetriou
31 * Copyright (c) 1982, 1986, 1989, 1993
32 * The Regents of the University of California. All rights reserved.
33 * (c) UNIX System Laboratories, Inc.
34 * All or some portions of this file are derived from material licensed
35 * to the University of California by American Telephone and Telegraph
36 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
37 * the permission of UNIX System Laboratories, Inc.
38 *
39 * Redistribution and use in source and binary forms, with or without
40 * modification, are permitted provided that the following conditions
41 * are met:
42 * 1. Redistributions of source code must retain the above copyright
43 * notice, this list of conditions and the following disclaimer.
44 * 2. Redistributions in binary form must reproduce the above copyright
45 * notice, this list of conditions and the following disclaimer in the
46 * documentation and/or other materials provided with the distribution.
47 * 3. All advertising materials mentioning features or use of this software
48 * must display the following acknowledgement:
49 * This product includes software developed by the University of
50 * California, Berkeley and its contributors.
51 * 4. Neither the name of the University nor the names of its contributors
52 * may be used to endorse or promote products derived from this software
53 * without specific prior written permission.
54 *
55 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
56 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
57 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
58 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
59 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
60 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
61 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
62 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
63 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
64 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
65 * SUCH DAMAGE.
66 *
67 * @(#)vfs_bio.c 8.6 (Berkeley) 1/11/94
68 */
69
70 /*
71 * Some references:
72 * Bach: The Design of the UNIX Operating System (Prentice Hall, 1986)
73 * Leffler, et al.: The Design and Implementation of the 4.3BSD
74 * UNIX Operating System (Addison Welley, 1989)
75 */
76
77 #include <sys/param.h>
78 #include <sys/systm.h>
79 #include <sys/proc_internal.h>
80 #include <sys/buf_internal.h>
81 #include <sys/vnode_internal.h>
82 #include <sys/mount_internal.h>
83 #include <sys/trace.h>
84 #include <sys/malloc.h>
85 #include <sys/resourcevar.h>
86 #include <miscfs/specfs/specdev.h>
87 #include <sys/ubc.h>
88 #include <sys/kauth.h>
89 #if DIAGNOSTIC
90 #include <kern/assert.h>
91 #endif /* DIAGNOSTIC */
92 #include <kern/task.h>
93 #include <kern/zalloc.h>
94 #include <kern/lock.h>
95
96 #include <sys/fslog.h> /* fslog_io_error() */
97
98 #include <mach/mach_types.h>
99 #include <mach/memory_object_types.h>
100 #include <kern/sched_prim.h> /* thread_block() */
101
102 #include <vm/vm_kern.h>
103 #include <vm/vm_pageout.h>
104
105 #include <sys/kdebug.h>
106
107 #include <libkern/OSAtomic.h>
108 #include <libkern/OSDebug.h>
109 #include <sys/ubc_internal.h>
110
111 #include <sys/sdt.h>
112
113 #if BALANCE_QUEUES
114 static __inline__ void bufqinc(int q);
115 static __inline__ void bufqdec(int q);
116 #endif
117
118 static int bcleanbuf(buf_t bp, boolean_t discard);
119 static int brecover_data(buf_t bp);
120 static boolean_t incore(vnode_t vp, daddr64_t blkno);
121 /* timeout is in msecs */
122 static buf_t getnewbuf(int slpflag, int slptimeo, int *queue);
123 static void bremfree_locked(buf_t bp);
124 static void buf_reassign(buf_t bp, vnode_t newvp);
125 static errno_t buf_acquire_locked(buf_t bp, int flags, int slpflag, int slptimeo);
126 static int buf_iterprepare(vnode_t vp, struct buflists *, int flags);
127 static void buf_itercomplete(vnode_t vp, struct buflists *, int flags);
128 boolean_t buffer_cache_gc(int);
129
130 __private_extern__ int bdwrite_internal(buf_t, int);
131
132 /* zone allocated buffer headers */
133 static void bufzoneinit(void) __attribute__((section("__TEXT, initcode")));
134 static void bcleanbuf_thread_init(void) __attribute__((section("__TEXT, initcode")));
135 static void bcleanbuf_thread(void);
136
137 static zone_t buf_hdr_zone;
138 static int buf_hdr_count;
139
140
141 /*
142 * Definitions for the buffer hash lists.
143 */
144 #define BUFHASH(dvp, lbn) \
145 (&bufhashtbl[((long)(dvp) / sizeof(*(dvp)) + (int)(lbn)) & bufhash])
146 LIST_HEAD(bufhashhdr, buf) *bufhashtbl, invalhash;
147 u_long bufhash;
148
149 static buf_t incore_locked(vnode_t vp, daddr64_t blkno, struct bufhashhdr *dp);
150
151 /* Definitions for the buffer stats. */
152 struct bufstats bufstats;
153
154 /* Number of delayed write buffers */
155 long nbdwrite = 0;
156 int blaundrycnt = 0;
157 static int boot_nbuf_headers = 0;
158
159
160 static TAILQ_HEAD(ioqueue, buf) iobufqueue;
161 static TAILQ_HEAD(bqueues, buf) bufqueues[BQUEUES];
162 static int needbuffer;
163 static int need_iobuffer;
164
165 static lck_grp_t *buf_mtx_grp;
166 static lck_attr_t *buf_mtx_attr;
167 static lck_grp_attr_t *buf_mtx_grp_attr;
168 static lck_mtx_t *iobuffer_mtxp;
169 static lck_mtx_t *buf_mtxp;
170
171 static int buf_busycount;
172
173 static __inline__ int
174 buf_timestamp(void)
175 {
176 struct timeval t;
177 microuptime(&t);
178 return (t.tv_sec);
179 }
180
181 /*
182 * Insq/Remq for the buffer free lists.
183 */
184 #if BALANCE_QUEUES
185 #define binsheadfree(bp, dp, whichq) do { \
186 TAILQ_INSERT_HEAD(dp, bp, b_freelist); \
187 bufqinc((whichq)); \
188 } while (0)
189
190 #define binstailfree(bp, dp, whichq) do { \
191 TAILQ_INSERT_TAIL(dp, bp, b_freelist); \
192 bufqinc((whichq)); \
193 } while (0)
194 #else
195 #define binsheadfree(bp, dp, whichq) do { \
196 TAILQ_INSERT_HEAD(dp, bp, b_freelist); \
197 } while (0)
198
199 #define binstailfree(bp, dp, whichq) do { \
200 TAILQ_INSERT_TAIL(dp, bp, b_freelist); \
201 } while (0)
202 #endif
203
204
205 #define BHASHENTCHECK(bp) \
206 if ((bp)->b_hash.le_prev != (struct buf **)0xdeadbeef) \
207 panic("%p: b_hash.le_prev is not deadbeef", (bp));
208
209 #define BLISTNONE(bp) \
210 (bp)->b_hash.le_next = (struct buf *)0; \
211 (bp)->b_hash.le_prev = (struct buf **)0xdeadbeef;
212
213 /*
214 * Insq/Remq for the vnode usage lists.
215 */
216 #define bufinsvn(bp, dp) LIST_INSERT_HEAD(dp, bp, b_vnbufs)
217 #define bufremvn(bp) { \
218 LIST_REMOVE(bp, b_vnbufs); \
219 (bp)->b_vnbufs.le_next = NOLIST; \
220 }
221
222 /*
223 * Time in seconds before a buffer on a list is
224 * considered as a stale buffer
225 */
226 #define LRU_IS_STALE 120 /* default value for the LRU */
227 #define AGE_IS_STALE 60 /* default value for the AGE */
228 #define META_IS_STALE 180 /* default value for the BQ_META */
229
230 int lru_is_stale = LRU_IS_STALE;
231 int age_is_stale = AGE_IS_STALE;
232 int meta_is_stale = META_IS_STALE;
233
234
235
236 /* LIST_INSERT_HEAD() with assertions */
237 static __inline__ void
238 blistenterhead(struct bufhashhdr * head, buf_t bp)
239 {
240 if ((bp->b_hash.le_next = (head)->lh_first) != NULL)
241 (head)->lh_first->b_hash.le_prev = &(bp)->b_hash.le_next;
242 (head)->lh_first = bp;
243 bp->b_hash.le_prev = &(head)->lh_first;
244 if (bp->b_hash.le_prev == (struct buf **)0xdeadbeef)
245 panic("blistenterhead: le_prev is deadbeef");
246 }
247
248 static __inline__ void
249 binshash(buf_t bp, struct bufhashhdr *dp)
250 {
251 #if DIAGNOSTIC
252 buf_t nbp;
253 #endif /* DIAGNOSTIC */
254
255 BHASHENTCHECK(bp);
256
257 #if DIAGNOSTIC
258 nbp = dp->lh_first;
259 for(; nbp != NULL; nbp = nbp->b_hash.le_next) {
260 if(nbp == bp)
261 panic("buf already in hashlist");
262 }
263 #endif /* DIAGNOSTIC */
264
265 blistenterhead(dp, bp);
266 }
267
268 static __inline__ void
269 bremhash(buf_t bp)
270 {
271 if (bp->b_hash.le_prev == (struct buf **)0xdeadbeef)
272 panic("bremhash le_prev is deadbeef");
273 if (bp->b_hash.le_next == bp)
274 panic("bremhash: next points to self");
275
276 if (bp->b_hash.le_next != NULL)
277 bp->b_hash.le_next->b_hash.le_prev = bp->b_hash.le_prev;
278 *bp->b_hash.le_prev = (bp)->b_hash.le_next;
279 }
280
281
282
283
284 int
285 buf_valid(buf_t bp) {
286
287 if ( (bp->b_flags & (B_DONE | B_DELWRI)) )
288 return 1;
289 return 0;
290 }
291
292 int
293 buf_fromcache(buf_t bp) {
294
295 if ( (bp->b_flags & B_CACHE) )
296 return 1;
297 return 0;
298 }
299
300 void
301 buf_markinvalid(buf_t bp) {
302
303 SET(bp->b_flags, B_INVAL);
304 }
305
306 void
307 buf_markdelayed(buf_t bp) {
308
309 if (!ISSET(bp->b_flags, B_DELWRI)) {
310 SET(bp->b_flags, B_DELWRI);
311
312 OSAddAtomicLong(1, &nbdwrite);
313 buf_reassign(bp, bp->b_vp);
314 }
315 SET(bp->b_flags, B_DONE);
316 }
317
318 void
319 buf_markeintr(buf_t bp) {
320
321 SET(bp->b_flags, B_EINTR);
322 }
323
324
325 void
326 buf_markaged(buf_t bp) {
327
328 SET(bp->b_flags, B_AGE);
329 }
330
331 int
332 buf_fua(buf_t bp) {
333
334 if ((bp->b_flags & B_FUA) == B_FUA)
335 return 1;
336 return 0;
337 }
338
339 void
340 buf_markfua(buf_t bp) {
341
342 SET(bp->b_flags, B_FUA);
343 }
344
345 #ifdef CONFIG_PROTECT
346 void *
347 buf_getcpaddr(buf_t bp) {
348 return bp->b_cpentry;
349 }
350
351 void
352 buf_setcpaddr(buf_t bp, void *cp_entry_addr) {
353 bp->b_cpentry = (struct cprotect *) cp_entry_addr;
354 }
355
356 #else
357 void *
358 buf_getcpaddr(buf_t bp __unused) {
359 return NULL;
360 }
361
362 void
363 buf_setcpaddr(buf_t bp __unused, void *cp_entry_addr __unused) {
364 return;
365 }
366 #endif /* CONFIG_PROTECT */
367
368 errno_t
369 buf_error(buf_t bp) {
370
371 return (bp->b_error);
372 }
373
374 void
375 buf_seterror(buf_t bp, errno_t error) {
376
377 if ((bp->b_error = error))
378 SET(bp->b_flags, B_ERROR);
379 else
380 CLR(bp->b_flags, B_ERROR);
381 }
382
383 void
384 buf_setflags(buf_t bp, int32_t flags) {
385
386 SET(bp->b_flags, (flags & BUF_X_WRFLAGS));
387 }
388
389 void
390 buf_clearflags(buf_t bp, int32_t flags) {
391
392 CLR(bp->b_flags, (flags & BUF_X_WRFLAGS));
393 }
394
395 int32_t
396 buf_flags(buf_t bp) {
397
398 return ((bp->b_flags & BUF_X_RDFLAGS));
399 }
400
401 void
402 buf_reset(buf_t bp, int32_t io_flags) {
403
404 CLR(bp->b_flags, (B_READ | B_WRITE | B_ERROR | B_DONE | B_INVAL | B_ASYNC | B_NOCACHE | B_FUA));
405 SET(bp->b_flags, (io_flags & (B_ASYNC | B_READ | B_WRITE | B_NOCACHE)));
406
407 bp->b_error = 0;
408 }
409
410 uint32_t
411 buf_count(buf_t bp) {
412
413 return (bp->b_bcount);
414 }
415
416 void
417 buf_setcount(buf_t bp, uint32_t bcount) {
418
419 bp->b_bcount = bcount;
420 }
421
422 uint32_t
423 buf_size(buf_t bp) {
424
425 return (bp->b_bufsize);
426 }
427
428 void
429 buf_setsize(buf_t bp, uint32_t bufsize) {
430
431 bp->b_bufsize = bufsize;
432 }
433
434 uint32_t
435 buf_resid(buf_t bp) {
436
437 return (bp->b_resid);
438 }
439
440 void
441 buf_setresid(buf_t bp, uint32_t resid) {
442
443 bp->b_resid = resid;
444 }
445
446 uint32_t
447 buf_dirtyoff(buf_t bp) {
448
449 return (bp->b_dirtyoff);
450 }
451
452 uint32_t
453 buf_dirtyend(buf_t bp) {
454
455 return (bp->b_dirtyend);
456 }
457
458 void
459 buf_setdirtyoff(buf_t bp, uint32_t dirtyoff) {
460
461 bp->b_dirtyoff = dirtyoff;
462 }
463
464 void
465 buf_setdirtyend(buf_t bp, uint32_t dirtyend) {
466
467 bp->b_dirtyend = dirtyend;
468 }
469
470 uintptr_t
471 buf_dataptr(buf_t bp) {
472
473 return (bp->b_datap);
474 }
475
476 void
477 buf_setdataptr(buf_t bp, uintptr_t data) {
478
479 bp->b_datap = data;
480 }
481
482 vnode_t
483 buf_vnode(buf_t bp) {
484
485 return (bp->b_vp);
486 }
487
488 void
489 buf_setvnode(buf_t bp, vnode_t vp) {
490
491 bp->b_vp = vp;
492 }
493
494
495 void *
496 buf_callback(buf_t bp)
497 {
498 if ( !(bp->b_flags & B_CALL) )
499 return ((void *) NULL);
500
501 return ((void *)bp->b_iodone);
502 }
503
504
505 errno_t
506 buf_setcallback(buf_t bp, void (*callback)(buf_t, void *), void *transaction)
507 {
508 if (callback)
509 bp->b_flags |= (B_CALL | B_ASYNC);
510 else
511 bp->b_flags &= ~B_CALL;
512 bp->b_transaction = transaction;
513 bp->b_iodone = callback;
514
515 return (0);
516 }
517
518 errno_t
519 buf_setupl(buf_t bp, upl_t upl, uint32_t offset)
520 {
521
522 if ( !(bp->b_lflags & BL_IOBUF) )
523 return (EINVAL);
524
525 if (upl)
526 bp->b_flags |= B_CLUSTER;
527 else
528 bp->b_flags &= ~B_CLUSTER;
529 bp->b_upl = upl;
530 bp->b_uploffset = offset;
531
532 return (0);
533 }
534
535 buf_t
536 buf_clone(buf_t bp, int io_offset, int io_size, void (*iodone)(buf_t, void *), void *arg)
537 {
538 buf_t io_bp;
539
540 if (io_offset < 0 || io_size < 0)
541 return (NULL);
542
543 if ((unsigned)(io_offset + io_size) > (unsigned)bp->b_bcount)
544 return (NULL);
545
546 if (bp->b_flags & B_CLUSTER) {
547 if (io_offset && ((bp->b_uploffset + io_offset) & PAGE_MASK))
548 return (NULL);
549
550 if (((bp->b_uploffset + io_offset + io_size) & PAGE_MASK) && ((io_offset + io_size) < bp->b_bcount))
551 return (NULL);
552 }
553 io_bp = alloc_io_buf(bp->b_vp, 0);
554
555 io_bp->b_flags = bp->b_flags & (B_COMMIT_UPL | B_META | B_PAGEIO | B_CLUSTER | B_PHYS | B_RAW | B_ASYNC | B_READ | B_FUA);
556
557 if (iodone) {
558 io_bp->b_transaction = arg;
559 io_bp->b_iodone = iodone;
560 io_bp->b_flags |= B_CALL;
561 }
562 if (bp->b_flags & B_CLUSTER) {
563 io_bp->b_upl = bp->b_upl;
564 io_bp->b_uploffset = bp->b_uploffset + io_offset;
565 } else {
566 io_bp->b_datap = (uintptr_t)(((char *)bp->b_datap) + io_offset);
567 }
568 io_bp->b_bcount = io_size;
569
570 return (io_bp);
571 }
572
573
574
575 void
576 buf_setfilter(buf_t bp, void (*filter)(buf_t, void *), void *transaction,
577 void **old_iodone, void **old_transaction)
578 {
579 if (old_iodone)
580 *old_iodone = (void *)(bp->b_iodone);
581 if (old_transaction)
582 *old_transaction = (void *)(bp->b_transaction);
583
584 bp->b_transaction = transaction;
585 bp->b_iodone = filter;
586 if (filter)
587 bp->b_flags |= B_FILTER;
588 else
589 bp->b_flags &= ~B_FILTER;
590 }
591
592
593 daddr64_t
594 buf_blkno(buf_t bp) {
595
596 return (bp->b_blkno);
597 }
598
599 daddr64_t
600 buf_lblkno(buf_t bp) {
601
602 return (bp->b_lblkno);
603 }
604
605 void
606 buf_setblkno(buf_t bp, daddr64_t blkno) {
607
608 bp->b_blkno = blkno;
609 }
610
611 void
612 buf_setlblkno(buf_t bp, daddr64_t lblkno) {
613
614 bp->b_lblkno = lblkno;
615 }
616
617 dev_t
618 buf_device(buf_t bp) {
619
620 return (bp->b_dev);
621 }
622
623 errno_t
624 buf_setdevice(buf_t bp, vnode_t vp) {
625
626 if ((vp->v_type != VBLK) && (vp->v_type != VCHR))
627 return EINVAL;
628 bp->b_dev = vp->v_rdev;
629
630 return 0;
631 }
632
633
634 void *
635 buf_drvdata(buf_t bp) {
636
637 return (bp->b_drvdata);
638 }
639
640 void
641 buf_setdrvdata(buf_t bp, void *drvdata) {
642
643 bp->b_drvdata = drvdata;
644 }
645
646 void *
647 buf_fsprivate(buf_t bp) {
648
649 return (bp->b_fsprivate);
650 }
651
652 void
653 buf_setfsprivate(buf_t bp, void *fsprivate) {
654
655 bp->b_fsprivate = fsprivate;
656 }
657
658 kauth_cred_t
659 buf_rcred(buf_t bp) {
660
661 return (bp->b_rcred);
662 }
663
664 kauth_cred_t
665 buf_wcred(buf_t bp) {
666
667 return (bp->b_wcred);
668 }
669
670 void *
671 buf_upl(buf_t bp) {
672
673 return (bp->b_upl);
674 }
675
676 uint32_t
677 buf_uploffset(buf_t bp) {
678
679 return ((uint32_t)(bp->b_uploffset));
680 }
681
682 proc_t
683 buf_proc(buf_t bp) {
684
685 return (bp->b_proc);
686 }
687
688
689 errno_t
690 buf_map(buf_t bp, caddr_t *io_addr)
691 {
692 buf_t real_bp;
693 vm_offset_t vaddr;
694 kern_return_t kret;
695
696 if ( !(bp->b_flags & B_CLUSTER)) {
697 *io_addr = (caddr_t)bp->b_datap;
698 return (0);
699 }
700 real_bp = (buf_t)(bp->b_real_bp);
701
702 if (real_bp && real_bp->b_datap) {
703 /*
704 * b_real_bp is only valid if B_CLUSTER is SET
705 * if it's non-zero, than someone did a cluster_bp call
706 * if the backing physical pages were already mapped
707 * in before the call to cluster_bp (non-zero b_datap),
708 * than we just use that mapping
709 */
710 *io_addr = (caddr_t)real_bp->b_datap;
711 return (0);
712 }
713 kret = ubc_upl_map(bp->b_upl, &vaddr); /* Map it in */
714
715 if (kret != KERN_SUCCESS) {
716 *io_addr = NULL;
717
718 return(ENOMEM);
719 }
720 vaddr += bp->b_uploffset;
721
722 *io_addr = (caddr_t)vaddr;
723
724 return (0);
725 }
726
727 errno_t
728 buf_unmap(buf_t bp)
729 {
730 buf_t real_bp;
731 kern_return_t kret;
732
733 if ( !(bp->b_flags & B_CLUSTER))
734 return (0);
735 /*
736 * see buf_map for the explanation
737 */
738 real_bp = (buf_t)(bp->b_real_bp);
739
740 if (real_bp && real_bp->b_datap)
741 return (0);
742
743 if ((bp->b_lflags & BL_IOBUF) &&
744 ((bp->b_flags & (B_PAGEIO | B_READ)) != (B_PAGEIO | B_READ))) {
745 /*
746 * ignore pageins... the 'right' thing will
747 * happen due to the way we handle speculative
748 * clusters...
749 *
750 * when we commit these pages, we'll hit
751 * it with UPL_COMMIT_INACTIVE which
752 * will clear the reference bit that got
753 * turned on when we touched the mapping
754 */
755 bp->b_flags |= B_AGE;
756 }
757 kret = ubc_upl_unmap(bp->b_upl);
758
759 if (kret != KERN_SUCCESS)
760 return (EINVAL);
761 return (0);
762 }
763
764
765 void
766 buf_clear(buf_t bp) {
767 caddr_t baddr;
768
769 if (buf_map(bp, &baddr) == 0) {
770 bzero(baddr, bp->b_bcount);
771 buf_unmap(bp);
772 }
773 bp->b_resid = 0;
774 }
775
776 /*
777 * Read or write a buffer that is not contiguous on disk.
778 * buffer is marked done/error at the conclusion
779 */
780 static int
781 buf_strategy_fragmented(vnode_t devvp, buf_t bp, off_t f_offset, size_t contig_bytes)
782 {
783 vnode_t vp = buf_vnode(bp);
784 buf_t io_bp; /* For reading or writing a single block */
785 int io_direction;
786 int io_resid;
787 size_t io_contig_bytes;
788 daddr64_t io_blkno;
789 int error = 0;
790 int bmap_flags;
791
792 /*
793 * save our starting point... the bp was already mapped
794 * in buf_strategy before we got called
795 * no sense doing it again.
796 */
797 io_blkno = bp->b_blkno;
798 /*
799 * Make sure we redo this mapping for the next I/O
800 * i.e. this can never be a 'permanent' mapping
801 */
802 bp->b_blkno = bp->b_lblkno;
803
804 /*
805 * Get an io buffer to do the deblocking
806 */
807 io_bp = alloc_io_buf(devvp, 0);
808
809 io_bp->b_lblkno = bp->b_lblkno;
810 io_bp->b_datap = bp->b_datap;
811 io_resid = bp->b_bcount;
812 io_direction = bp->b_flags & B_READ;
813 io_contig_bytes = contig_bytes;
814
815 if (bp->b_flags & B_READ)
816 bmap_flags = VNODE_READ;
817 else
818 bmap_flags = VNODE_WRITE;
819
820 for (;;) {
821 if (io_blkno == -1)
822 /*
823 * this is unexepected, but we'll allow for it
824 */
825 bzero((caddr_t)io_bp->b_datap, (int)io_contig_bytes);
826 else {
827 io_bp->b_bcount = io_contig_bytes;
828 io_bp->b_bufsize = io_contig_bytes;
829 io_bp->b_resid = io_contig_bytes;
830 io_bp->b_blkno = io_blkno;
831
832 buf_reset(io_bp, io_direction);
833
834 /*
835 * Call the device to do the I/O and wait for it. Make sure the appropriate party is charged for write
836 */
837
838 if (!ISSET(bp->b_flags, B_READ))
839 OSAddAtomic(1, &devvp->v_numoutput);
840
841 if ((error = VNOP_STRATEGY(io_bp)))
842 break;
843 if ((error = (int)buf_biowait(io_bp)))
844 break;
845 if (io_bp->b_resid) {
846 io_resid -= (io_contig_bytes - io_bp->b_resid);
847 break;
848 }
849 }
850 if ((io_resid -= io_contig_bytes) == 0)
851 break;
852 f_offset += io_contig_bytes;
853 io_bp->b_datap += io_contig_bytes;
854
855 /*
856 * Map the current position to a physical block number
857 */
858 if ((error = VNOP_BLOCKMAP(vp, f_offset, io_resid, &io_blkno, &io_contig_bytes, NULL, bmap_flags, NULL)))
859 break;
860 }
861 buf_free(io_bp);
862
863 if (error)
864 buf_seterror(bp, error);
865 bp->b_resid = io_resid;
866 /*
867 * This I/O is now complete
868 */
869 buf_biodone(bp);
870
871 return error;
872 }
873
874
875 /*
876 * struct vnop_strategy_args {
877 * struct buf *a_bp;
878 * } *ap;
879 */
880 errno_t
881 buf_strategy(vnode_t devvp, void *ap)
882 {
883 buf_t bp = ((struct vnop_strategy_args *)ap)->a_bp;
884 vnode_t vp = bp->b_vp;
885 int bmap_flags;
886 errno_t error;
887
888 if (vp == NULL || vp->v_type == VCHR || vp->v_type == VBLK)
889 panic("buf_strategy: b_vp == NULL || vtype == VCHR | VBLK\n");
890 /*
891 * associate the physical device with
892 * with this buf_t even if we don't
893 * end up issuing the I/O...
894 */
895 bp->b_dev = devvp->v_rdev;
896 DTRACE_IO1(start, buf_t, bp);
897
898 if (bp->b_flags & B_READ)
899 bmap_flags = VNODE_READ;
900 else
901 bmap_flags = VNODE_WRITE;
902
903 if ( !(bp->b_flags & B_CLUSTER)) {
904
905 if ( (bp->b_upl) ) {
906 /*
907 * we have a UPL associated with this bp
908 * go through cluster_bp which knows how
909 * to deal with filesystem block sizes
910 * that aren't equal to the page size
911 */
912 return (cluster_bp(bp));
913 }
914 if (bp->b_blkno == bp->b_lblkno) {
915 off_t f_offset;
916 size_t contig_bytes;
917
918 if ((error = VNOP_BLKTOOFF(vp, bp->b_lblkno, &f_offset))) {
919 buf_seterror(bp, error);
920 buf_biodone(bp);
921
922 return (error);
923 }
924 if ((error = VNOP_BLOCKMAP(vp, f_offset, bp->b_bcount, &bp->b_blkno, &contig_bytes, NULL, bmap_flags, NULL))) {
925 buf_seterror(bp, error);
926 buf_biodone(bp);
927
928 return (error);
929 }
930 if ((bp->b_blkno == -1) || (contig_bytes == 0)) {
931 /* Set block number to force biodone later */
932 bp->b_blkno = -1;
933 buf_clear(bp);
934 }
935 else if ((long)contig_bytes < bp->b_bcount)
936 return (buf_strategy_fragmented(devvp, bp, f_offset, contig_bytes));
937 }
938 if (bp->b_blkno == -1) {
939 buf_biodone(bp);
940 return (0);
941 }
942 }
943 /*
944 * we can issue the I/O because...
945 * either B_CLUSTER is set which
946 * means that the I/O is properly set
947 * up to be a multiple of the page size, or
948 * we were able to successfully set up the
949 * phsyical block mapping
950 */
951 return (VOCALL(devvp->v_op, VOFFSET(vnop_strategy), ap));
952 }
953
954
955
956 buf_t
957 buf_alloc(vnode_t vp)
958 {
959 return(alloc_io_buf(vp, 0));
960 }
961
962 void
963 buf_free(buf_t bp) {
964
965 free_io_buf(bp);
966 }
967
968
969 /*
970 * iterate buffers for the specified vp.
971 * if BUF_SCAN_DIRTY is set, do the dirty list
972 * if BUF_SCAN_CLEAN is set, do the clean list
973 * if neither flag is set, default to BUF_SCAN_DIRTY
974 * if BUF_NOTIFY_BUSY is set, call the callout function using a NULL bp for busy pages
975 */
976
977 struct buf_iterate_info_t {
978 int flag;
979 struct buflists *listhead;
980 };
981
982 void
983 buf_iterate(vnode_t vp, int (*callout)(buf_t, void *), int flags, void *arg)
984 {
985 buf_t bp;
986 int retval;
987 struct buflists local_iterblkhd;
988 int lock_flags = BAC_NOWAIT | BAC_REMOVE;
989 int notify_busy = flags & BUF_NOTIFY_BUSY;
990 struct buf_iterate_info_t list[2];
991 int num_lists, i;
992
993 if (flags & BUF_SKIP_LOCKED)
994 lock_flags |= BAC_SKIP_LOCKED;
995 if (flags & BUF_SKIP_NONLOCKED)
996 lock_flags |= BAC_SKIP_NONLOCKED;
997
998 if ( !(flags & (BUF_SCAN_DIRTY | BUF_SCAN_CLEAN)))
999 flags |= BUF_SCAN_DIRTY;
1000
1001 num_lists = 0;
1002
1003 if (flags & BUF_SCAN_DIRTY) {
1004 list[num_lists].flag = VBI_DIRTY;
1005 list[num_lists].listhead = &vp->v_dirtyblkhd;
1006 num_lists++;
1007 }
1008 if (flags & BUF_SCAN_CLEAN) {
1009 list[num_lists].flag = VBI_CLEAN;
1010 list[num_lists].listhead = &vp->v_cleanblkhd;
1011 num_lists++;
1012 }
1013
1014 for (i = 0; i < num_lists; i++) {
1015 lck_mtx_lock(buf_mtxp);
1016
1017 if (buf_iterprepare(vp, &local_iterblkhd, list[i].flag)) {
1018 lck_mtx_unlock(buf_mtxp);
1019 continue;
1020 }
1021 while (!LIST_EMPTY(&local_iterblkhd)) {
1022 bp = LIST_FIRST(&local_iterblkhd);
1023 LIST_REMOVE(bp, b_vnbufs);
1024 LIST_INSERT_HEAD(list[i].listhead, bp, b_vnbufs);
1025
1026 if (buf_acquire_locked(bp, lock_flags, 0, 0)) {
1027 if (notify_busy) {
1028 bp = NULL;
1029 } else {
1030 continue;
1031 }
1032 }
1033
1034 lck_mtx_unlock(buf_mtxp);
1035
1036 retval = callout(bp, arg);
1037
1038 switch (retval) {
1039 case BUF_RETURNED:
1040 if (bp)
1041 buf_brelse(bp);
1042 break;
1043 case BUF_CLAIMED:
1044 break;
1045 case BUF_RETURNED_DONE:
1046 if (bp)
1047 buf_brelse(bp);
1048 lck_mtx_lock(buf_mtxp);
1049 goto out;
1050 case BUF_CLAIMED_DONE:
1051 lck_mtx_lock(buf_mtxp);
1052 goto out;
1053 }
1054 lck_mtx_lock(buf_mtxp);
1055 } /* while list has more nodes */
1056 out:
1057 buf_itercomplete(vp, &local_iterblkhd, list[i].flag);
1058 lck_mtx_unlock(buf_mtxp);
1059 } /* for each list */
1060 } /* buf_iterate */
1061
1062
1063 /*
1064 * Flush out and invalidate all buffers associated with a vnode.
1065 */
1066 int
1067 buf_invalidateblks(vnode_t vp, int flags, int slpflag, int slptimeo)
1068 {
1069 buf_t bp;
1070 int error = 0;
1071 int must_rescan = 1;
1072 struct buflists local_iterblkhd;
1073
1074
1075 if (LIST_EMPTY(&vp->v_cleanblkhd) && LIST_EMPTY(&vp->v_dirtyblkhd))
1076 return (0);
1077
1078 lck_mtx_lock(buf_mtxp);
1079
1080 for (;;) {
1081 if (must_rescan == 0)
1082 /*
1083 * the lists may not be empty, but all that's left at this
1084 * point are metadata or B_LOCKED buffers which are being
1085 * skipped... we know this because we made it through both
1086 * the clean and dirty lists without dropping buf_mtxp...
1087 * each time we drop buf_mtxp we bump "must_rescan"
1088 */
1089 break;
1090 if (LIST_EMPTY(&vp->v_cleanblkhd) && LIST_EMPTY(&vp->v_dirtyblkhd))
1091 break;
1092 must_rescan = 0;
1093 /*
1094 * iterate the clean list
1095 */
1096 if (buf_iterprepare(vp, &local_iterblkhd, VBI_CLEAN)) {
1097 goto try_dirty_list;
1098 }
1099 while (!LIST_EMPTY(&local_iterblkhd)) {
1100 bp = LIST_FIRST(&local_iterblkhd);
1101
1102 LIST_REMOVE(bp, b_vnbufs);
1103 LIST_INSERT_HEAD(&vp->v_cleanblkhd, bp, b_vnbufs);
1104
1105 /*
1106 * some filesystems distinguish meta data blocks with a negative logical block #
1107 */
1108 if ((flags & BUF_SKIP_META) && (bp->b_lblkno < 0 || ISSET(bp->b_flags, B_META)))
1109 continue;
1110
1111 if ( (error = (int)buf_acquire_locked(bp, BAC_REMOVE | BAC_SKIP_LOCKED, slpflag, slptimeo)) ) {
1112 if (error == EDEADLK)
1113 /*
1114 * this buffer was marked B_LOCKED...
1115 * we didn't drop buf_mtxp, so we
1116 * we don't need to rescan
1117 */
1118 continue;
1119 if (error == EAGAIN) {
1120 /*
1121 * found a busy buffer... we blocked and
1122 * dropped buf_mtxp, so we're going to
1123 * need to rescan after this pass is completed
1124 */
1125 must_rescan++;
1126 continue;
1127 }
1128 /*
1129 * got some kind of 'real' error out of the msleep
1130 * in buf_acquire_locked, terminate the scan and return the error
1131 */
1132 buf_itercomplete(vp, &local_iterblkhd, VBI_CLEAN);
1133
1134 lck_mtx_unlock(buf_mtxp);
1135 return (error);
1136 }
1137 lck_mtx_unlock(buf_mtxp);
1138
1139 SET(bp->b_flags, B_INVAL);
1140 buf_brelse(bp);
1141
1142 lck_mtx_lock(buf_mtxp);
1143
1144 /*
1145 * by dropping buf_mtxp, we allow new
1146 * buffers to be added to the vnode list(s)
1147 * we'll have to rescan at least once more
1148 * if the queues aren't empty
1149 */
1150 must_rescan++;
1151 }
1152 buf_itercomplete(vp, &local_iterblkhd, VBI_CLEAN);
1153
1154 try_dirty_list:
1155 /*
1156 * Now iterate on dirty blks
1157 */
1158 if (buf_iterprepare(vp, &local_iterblkhd, VBI_DIRTY)) {
1159 continue;
1160 }
1161 while (!LIST_EMPTY(&local_iterblkhd)) {
1162 bp = LIST_FIRST(&local_iterblkhd);
1163
1164 LIST_REMOVE(bp, b_vnbufs);
1165 LIST_INSERT_HEAD(&vp->v_dirtyblkhd, bp, b_vnbufs);
1166
1167 /*
1168 * some filesystems distinguish meta data blocks with a negative logical block #
1169 */
1170 if ((flags & BUF_SKIP_META) && (bp->b_lblkno < 0 || ISSET(bp->b_flags, B_META)))
1171 continue;
1172
1173 if ( (error = (int)buf_acquire_locked(bp, BAC_REMOVE | BAC_SKIP_LOCKED, slpflag, slptimeo)) ) {
1174 if (error == EDEADLK)
1175 /*
1176 * this buffer was marked B_LOCKED...
1177 * we didn't drop buf_mtxp, so we
1178 * we don't need to rescan
1179 */
1180 continue;
1181 if (error == EAGAIN) {
1182 /*
1183 * found a busy buffer... we blocked and
1184 * dropped buf_mtxp, so we're going to
1185 * need to rescan after this pass is completed
1186 */
1187 must_rescan++;
1188 continue;
1189 }
1190 /*
1191 * got some kind of 'real' error out of the msleep
1192 * in buf_acquire_locked, terminate the scan and return the error
1193 */
1194 buf_itercomplete(vp, &local_iterblkhd, VBI_DIRTY);
1195
1196 lck_mtx_unlock(buf_mtxp);
1197 return (error);
1198 }
1199 lck_mtx_unlock(buf_mtxp);
1200
1201 SET(bp->b_flags, B_INVAL);
1202
1203 if (ISSET(bp->b_flags, B_DELWRI) && (flags & BUF_WRITE_DATA))
1204 (void) VNOP_BWRITE(bp);
1205 else
1206 buf_brelse(bp);
1207
1208 lck_mtx_lock(buf_mtxp);
1209 /*
1210 * by dropping buf_mtxp, we allow new
1211 * buffers to be added to the vnode list(s)
1212 * we'll have to rescan at least once more
1213 * if the queues aren't empty
1214 */
1215 must_rescan++;
1216 }
1217 buf_itercomplete(vp, &local_iterblkhd, VBI_DIRTY);
1218 }
1219 lck_mtx_unlock(buf_mtxp);
1220
1221 return (0);
1222 }
1223
1224 void
1225 buf_flushdirtyblks(vnode_t vp, int wait, int flags, const char *msg) {
1226 buf_t bp;
1227 int writes_issued = 0;
1228 errno_t error;
1229 int busy = 0;
1230 struct buflists local_iterblkhd;
1231 int lock_flags = BAC_NOWAIT | BAC_REMOVE;
1232
1233 if (flags & BUF_SKIP_LOCKED)
1234 lock_flags |= BAC_SKIP_LOCKED;
1235 if (flags & BUF_SKIP_NONLOCKED)
1236 lock_flags |= BAC_SKIP_NONLOCKED;
1237 loop:
1238 lck_mtx_lock(buf_mtxp);
1239
1240 if (buf_iterprepare(vp, &local_iterblkhd, VBI_DIRTY) == 0) {
1241 while (!LIST_EMPTY(&local_iterblkhd)) {
1242 bp = LIST_FIRST(&local_iterblkhd);
1243 LIST_REMOVE(bp, b_vnbufs);
1244 LIST_INSERT_HEAD(&vp->v_dirtyblkhd, bp, b_vnbufs);
1245
1246 if ((error = buf_acquire_locked(bp, lock_flags, 0, 0)) == EBUSY)
1247 busy++;
1248 if (error)
1249 continue;
1250 lck_mtx_unlock(buf_mtxp);
1251
1252 bp->b_flags &= ~B_LOCKED;
1253
1254 /*
1255 * Wait for I/O associated with indirect blocks to complete,
1256 * since there is no way to quickly wait for them below.
1257 */
1258 if ((bp->b_vp == vp) || (wait == 0))
1259 (void) buf_bawrite(bp);
1260 else
1261 (void) VNOP_BWRITE(bp);
1262 writes_issued++;
1263
1264 lck_mtx_lock(buf_mtxp);
1265 }
1266 buf_itercomplete(vp, &local_iterblkhd, VBI_DIRTY);
1267 }
1268 lck_mtx_unlock(buf_mtxp);
1269
1270 if (wait) {
1271 (void)vnode_waitforwrites(vp, 0, 0, 0, msg);
1272
1273 if (vp->v_dirtyblkhd.lh_first && busy) {
1274 /*
1275 * we had one or more BUSY buffers on
1276 * the dirtyblock list... most likely
1277 * these are due to delayed writes that
1278 * were moved to the bclean queue but
1279 * have not yet been 'written'.
1280 * if we issued some writes on the
1281 * previous pass, we try again immediately
1282 * if we didn't, we'll sleep for some time
1283 * to allow the state to change...
1284 */
1285 if (writes_issued == 0) {
1286 (void)tsleep((caddr_t)&vp->v_numoutput,
1287 PRIBIO + 1, "vnode_flushdirtyblks", hz/20);
1288 }
1289 writes_issued = 0;
1290 busy = 0;
1291
1292 goto loop;
1293 }
1294 }
1295 }
1296
1297
1298 /*
1299 * called with buf_mtxp held...
1300 * this lock protects the queue manipulation
1301 */
1302 static int
1303 buf_iterprepare(vnode_t vp, struct buflists *iterheadp, int flags)
1304 {
1305 struct buflists * listheadp;
1306
1307 if (flags & VBI_DIRTY)
1308 listheadp = &vp->v_dirtyblkhd;
1309 else
1310 listheadp = &vp->v_cleanblkhd;
1311
1312 while (vp->v_iterblkflags & VBI_ITER) {
1313 vp->v_iterblkflags |= VBI_ITERWANT;
1314 msleep(&vp->v_iterblkflags, buf_mtxp, 0, "buf_iterprepare", NULL);
1315 }
1316 if (LIST_EMPTY(listheadp)) {
1317 LIST_INIT(iterheadp);
1318 return(EINVAL);
1319 }
1320 vp->v_iterblkflags |= VBI_ITER;
1321
1322 iterheadp->lh_first = listheadp->lh_first;
1323 listheadp->lh_first->b_vnbufs.le_prev = &iterheadp->lh_first;
1324 LIST_INIT(listheadp);
1325
1326 return(0);
1327 }
1328
1329 /*
1330 * called with buf_mtxp held...
1331 * this lock protects the queue manipulation
1332 */
1333 static void
1334 buf_itercomplete(vnode_t vp, struct buflists *iterheadp, int flags)
1335 {
1336 struct buflists * listheadp;
1337 buf_t bp;
1338
1339 if (flags & VBI_DIRTY)
1340 listheadp = &vp->v_dirtyblkhd;
1341 else
1342 listheadp = &vp->v_cleanblkhd;
1343
1344 while (!LIST_EMPTY(iterheadp)) {
1345 bp = LIST_FIRST(iterheadp);
1346 LIST_REMOVE(bp, b_vnbufs);
1347 LIST_INSERT_HEAD(listheadp, bp, b_vnbufs);
1348 }
1349 vp->v_iterblkflags &= ~VBI_ITER;
1350
1351 if (vp->v_iterblkflags & VBI_ITERWANT) {
1352 vp->v_iterblkflags &= ~VBI_ITERWANT;
1353 wakeup(&vp->v_iterblkflags);
1354 }
1355 }
1356
1357
1358 static void
1359 bremfree_locked(buf_t bp)
1360 {
1361 struct bqueues *dp = NULL;
1362 int whichq;
1363 /*
1364 * We only calculate the head of the freelist when removing
1365 * the last element of the list as that is the only time that
1366 * it is needed (e.g. to reset the tail pointer).
1367 *
1368 * NB: This makes an assumption about how tailq's are implemented.
1369 */
1370 whichq = bp->b_whichq;
1371
1372 if (bp->b_freelist.tqe_next == NULL) {
1373 dp = &bufqueues[whichq];
1374
1375 if (dp->tqh_last != &bp->b_freelist.tqe_next)
1376 panic("bremfree: lost tail");
1377 }
1378 TAILQ_REMOVE(dp, bp, b_freelist);
1379
1380 #if BALANCE_QUEUES
1381 bufqdec(whichq);
1382 #endif
1383 if (whichq == BQ_LAUNDRY)
1384 blaundrycnt--;
1385
1386 bp->b_whichq = -1;
1387 bp->b_timestamp = 0;
1388 }
1389
1390 /*
1391 * Associate a buffer with a vnode.
1392 * buf_mtxp must be locked on entry
1393 */
1394 static void
1395 bgetvp_locked(vnode_t vp, buf_t bp)
1396 {
1397
1398 if (bp->b_vp != vp)
1399 panic("bgetvp_locked: not free");
1400
1401 if (vp->v_type == VBLK || vp->v_type == VCHR)
1402 bp->b_dev = vp->v_rdev;
1403 else
1404 bp->b_dev = NODEV;
1405 /*
1406 * Insert onto list for new vnode.
1407 */
1408 bufinsvn(bp, &vp->v_cleanblkhd);
1409 }
1410
1411 /*
1412 * Disassociate a buffer from a vnode.
1413 * buf_mtxp must be locked on entry
1414 */
1415 static void
1416 brelvp_locked(buf_t bp)
1417 {
1418 /*
1419 * Delete from old vnode list, if on one.
1420 */
1421 if (bp->b_vnbufs.le_next != NOLIST)
1422 bufremvn(bp);
1423
1424 bp->b_vp = (vnode_t)NULL;
1425 }
1426
1427 /*
1428 * Reassign a buffer from one vnode to another.
1429 * Used to assign file specific control information
1430 * (indirect blocks) to the vnode to which they belong.
1431 */
1432 static void
1433 buf_reassign(buf_t bp, vnode_t newvp)
1434 {
1435 register struct buflists *listheadp;
1436
1437 if (newvp == NULL) {
1438 printf("buf_reassign: NULL");
1439 return;
1440 }
1441 lck_mtx_lock_spin(buf_mtxp);
1442
1443 /*
1444 * Delete from old vnode list, if on one.
1445 */
1446 if (bp->b_vnbufs.le_next != NOLIST)
1447 bufremvn(bp);
1448 /*
1449 * If dirty, put on list of dirty buffers;
1450 * otherwise insert onto list of clean buffers.
1451 */
1452 if (ISSET(bp->b_flags, B_DELWRI))
1453 listheadp = &newvp->v_dirtyblkhd;
1454 else
1455 listheadp = &newvp->v_cleanblkhd;
1456 bufinsvn(bp, listheadp);
1457
1458 lck_mtx_unlock(buf_mtxp);
1459 }
1460
1461 static __inline__ void
1462 bufhdrinit(buf_t bp)
1463 {
1464 bzero((char *)bp, sizeof *bp);
1465 bp->b_dev = NODEV;
1466 bp->b_rcred = NOCRED;
1467 bp->b_wcred = NOCRED;
1468 bp->b_vnbufs.le_next = NOLIST;
1469 bp->b_flags = B_INVAL;
1470
1471 return;
1472 }
1473
1474 /*
1475 * Initialize buffers and hash links for buffers.
1476 */
1477 __private_extern__ void
1478 bufinit(void)
1479 {
1480 buf_t bp;
1481 struct bqueues *dp;
1482 int i;
1483
1484 nbuf_headers = 0;
1485 /* Initialize the buffer queues ('freelists') and the hash table */
1486 for (dp = bufqueues; dp < &bufqueues[BQUEUES]; dp++)
1487 TAILQ_INIT(dp);
1488 bufhashtbl = hashinit(nbuf_hashelements, M_CACHE, &bufhash);
1489
1490 buf_busycount = 0;
1491
1492 /* Initialize the buffer headers */
1493 for (i = 0; i < max_nbuf_headers; i++) {
1494 nbuf_headers++;
1495 bp = &buf_headers[i];
1496 bufhdrinit(bp);
1497
1498 BLISTNONE(bp);
1499 dp = &bufqueues[BQ_EMPTY];
1500 bp->b_whichq = BQ_EMPTY;
1501 bp->b_timestamp = buf_timestamp();
1502 binsheadfree(bp, dp, BQ_EMPTY);
1503 binshash(bp, &invalhash);
1504 }
1505
1506 boot_nbuf_headers = nbuf_headers;
1507 for (; i < nbuf_headers + niobuf_headers; i++) {
1508 bp = &buf_headers[i];
1509 bufhdrinit(bp);
1510 bp->b_whichq = -1;
1511 binsheadfree(bp, &iobufqueue, -1);
1512 }
1513
1514 /*
1515 * allocate lock group attribute and group
1516 */
1517 buf_mtx_grp_attr = lck_grp_attr_alloc_init();
1518 buf_mtx_grp = lck_grp_alloc_init("buffer cache", buf_mtx_grp_attr);
1519
1520 /*
1521 * allocate the lock attribute
1522 */
1523 buf_mtx_attr = lck_attr_alloc_init();
1524
1525 /*
1526 * allocate and initialize mutex's for the buffer and iobuffer pools
1527 */
1528 buf_mtxp = lck_mtx_alloc_init(buf_mtx_grp, buf_mtx_attr);
1529 iobuffer_mtxp = lck_mtx_alloc_init(buf_mtx_grp, buf_mtx_attr);
1530
1531 if (iobuffer_mtxp == NULL)
1532 panic("couldn't create iobuffer mutex");
1533
1534 if (buf_mtxp == NULL)
1535 panic("couldn't create buf mutex");
1536
1537 /*
1538 * allocate and initialize cluster specific global locks...
1539 */
1540 cluster_init();
1541
1542 printf("using %d buffer headers and %d cluster IO buffer headers\n",
1543 nbuf_headers, niobuf_headers);
1544
1545 /* Set up zones used by the buffer cache */
1546 bufzoneinit();
1547
1548 /* start the bcleanbuf() thread */
1549 bcleanbuf_thread_init();
1550
1551 /* Register a callout for relieving vm pressure */
1552 if (vm_set_buffer_cleanup_callout(buffer_cache_gc) != KERN_SUCCESS) {
1553 panic("Couldn't register buffer cache callout for vm pressure!\n");
1554 }
1555
1556 #if BALANCE_QUEUES
1557 {
1558 static void bufq_balance_thread_init(void) __attribute__((section("__TEXT, initcode")));
1559 /* create a thread to do dynamic buffer queue balancing */
1560 bufq_balance_thread_init();
1561 }
1562 #endif /* notyet */
1563 }
1564
1565
1566
1567 /*
1568 * Zones for the meta data buffers
1569 */
1570
1571 #define MINMETA 512
1572 #define MAXMETA 8192
1573
1574 struct meta_zone_entry {
1575 zone_t mz_zone;
1576 vm_size_t mz_size;
1577 vm_size_t mz_max;
1578 const char *mz_name;
1579 };
1580
1581 struct meta_zone_entry meta_zones[] = {
1582 {NULL, (MINMETA * 1), 128 * (MINMETA * 1), "buf.512" },
1583 {NULL, (MINMETA * 2), 64 * (MINMETA * 2), "buf.1024" },
1584 {NULL, (MINMETA * 4), 16 * (MINMETA * 4), "buf.2048" },
1585 {NULL, (MINMETA * 8), 512 * (MINMETA * 8), "buf.4096" },
1586 {NULL, (MINMETA * 16), 512 * (MINMETA * 16), "buf.8192" },
1587 {NULL, 0, 0, "" } /* End */
1588 };
1589
1590 /*
1591 * Initialize the meta data zones
1592 */
1593 static void
1594 bufzoneinit(void)
1595 {
1596 int i;
1597
1598 for (i = 0; meta_zones[i].mz_size != 0; i++) {
1599 meta_zones[i].mz_zone =
1600 zinit(meta_zones[i].mz_size,
1601 meta_zones[i].mz_max,
1602 PAGE_SIZE,
1603 meta_zones[i].mz_name);
1604 }
1605 buf_hdr_zone = zinit(sizeof(struct buf), 32, PAGE_SIZE, "buf headers");
1606 }
1607
1608 static __inline__ zone_t
1609 getbufzone(size_t size)
1610 {
1611 int i;
1612
1613 if ((size % 512) || (size < MINMETA) || (size > MAXMETA))
1614 panic("getbufzone: incorect size = %lu", size);
1615
1616 for (i = 0; meta_zones[i].mz_size != 0; i++) {
1617 if (meta_zones[i].mz_size >= size)
1618 break;
1619 }
1620
1621 return (meta_zones[i].mz_zone);
1622 }
1623
1624
1625
1626 static struct buf *
1627 bio_doread(vnode_t vp, daddr64_t blkno, int size, kauth_cred_t cred, int async, int queuetype)
1628 {
1629 buf_t bp;
1630
1631 bp = buf_getblk(vp, blkno, size, 0, 0, queuetype);
1632
1633 /*
1634 * If buffer does not have data valid, start a read.
1635 * Note that if buffer is B_INVAL, buf_getblk() won't return it.
1636 * Therefore, it's valid if it's I/O has completed or been delayed.
1637 */
1638 if (!ISSET(bp->b_flags, (B_DONE | B_DELWRI))) {
1639 struct proc *p;
1640
1641 p = current_proc();
1642
1643 /* Start I/O for the buffer (keeping credentials). */
1644 SET(bp->b_flags, B_READ | async);
1645 if (IS_VALID_CRED(cred) && !IS_VALID_CRED(bp->b_rcred)) {
1646 kauth_cred_ref(cred);
1647 bp->b_rcred = cred;
1648 }
1649
1650 VNOP_STRATEGY(bp);
1651
1652 trace(TR_BREADMISS, pack(vp, size), blkno);
1653
1654 /* Pay for the read. */
1655 if (p && p->p_stats)
1656 OSIncrementAtomicLong(&p->p_stats->p_ru.ru_inblock); /* XXX */
1657
1658 if (async) {
1659 /*
1660 * since we asked for an ASYNC I/O
1661 * the biodone will do the brelse
1662 * we don't want to pass back a bp
1663 * that we don't 'own'
1664 */
1665 bp = NULL;
1666 }
1667 } else if (async) {
1668 buf_brelse(bp);
1669 bp = NULL;
1670 }
1671
1672 trace(TR_BREADHIT, pack(vp, size), blkno);
1673
1674 return (bp);
1675 }
1676
1677 /*
1678 * Perform the reads for buf_breadn() and buf_meta_breadn().
1679 * Trivial modification to the breada algorithm presented in Bach (p.55).
1680 */
1681 static errno_t
1682 do_breadn_for_type(vnode_t vp, daddr64_t blkno, int size, daddr64_t *rablks, int *rasizes,
1683 int nrablks, kauth_cred_t cred, buf_t *bpp, int queuetype)
1684 {
1685 buf_t bp;
1686 int i;
1687
1688 bp = *bpp = bio_doread(vp, blkno, size, cred, 0, queuetype);
1689
1690 /*
1691 * For each of the read-ahead blocks, start a read, if necessary.
1692 */
1693 for (i = 0; i < nrablks; i++) {
1694 /* If it's in the cache, just go on to next one. */
1695 if (incore(vp, rablks[i]))
1696 continue;
1697
1698 /* Get a buffer for the read-ahead block */
1699 (void) bio_doread(vp, rablks[i], rasizes[i], cred, B_ASYNC, queuetype);
1700 }
1701
1702 /* Otherwise, we had to start a read for it; wait until it's valid. */
1703 return (buf_biowait(bp));
1704 }
1705
1706
1707 /*
1708 * Read a disk block.
1709 * This algorithm described in Bach (p.54).
1710 */
1711 errno_t
1712 buf_bread(vnode_t vp, daddr64_t blkno, int size, kauth_cred_t cred, buf_t *bpp)
1713 {
1714 buf_t bp;
1715
1716 /* Get buffer for block. */
1717 bp = *bpp = bio_doread(vp, blkno, size, cred, 0, BLK_READ);
1718
1719 /* Wait for the read to complete, and return result. */
1720 return (buf_biowait(bp));
1721 }
1722
1723 /*
1724 * Read a disk block. [bread() for meta-data]
1725 * This algorithm described in Bach (p.54).
1726 */
1727 errno_t
1728 buf_meta_bread(vnode_t vp, daddr64_t blkno, int size, kauth_cred_t cred, buf_t *bpp)
1729 {
1730 buf_t bp;
1731
1732 /* Get buffer for block. */
1733 bp = *bpp = bio_doread(vp, blkno, size, cred, 0, BLK_META);
1734
1735 /* Wait for the read to complete, and return result. */
1736 return (buf_biowait(bp));
1737 }
1738
1739 /*
1740 * Read-ahead multiple disk blocks. The first is sync, the rest async.
1741 */
1742 errno_t
1743 buf_breadn(vnode_t vp, daddr64_t blkno, int size, daddr64_t *rablks, int *rasizes, int nrablks, kauth_cred_t cred, buf_t *bpp)
1744 {
1745 return (do_breadn_for_type(vp, blkno, size, rablks, rasizes, nrablks, cred, bpp, BLK_READ));
1746 }
1747
1748 /*
1749 * Read-ahead multiple disk blocks. The first is sync, the rest async.
1750 * [buf_breadn() for meta-data]
1751 */
1752 errno_t
1753 buf_meta_breadn(vnode_t vp, daddr64_t blkno, int size, daddr64_t *rablks, int *rasizes, int nrablks, kauth_cred_t cred, buf_t *bpp)
1754 {
1755 return (do_breadn_for_type(vp, blkno, size, rablks, rasizes, nrablks, cred, bpp, BLK_META));
1756 }
1757
1758 /*
1759 * Block write. Described in Bach (p.56)
1760 */
1761 errno_t
1762 buf_bwrite(buf_t bp)
1763 {
1764 int sync, wasdelayed;
1765 errno_t rv;
1766 proc_t p = current_proc();
1767 vnode_t vp = bp->b_vp;
1768
1769 if (bp->b_datap == 0) {
1770 if (brecover_data(bp) == 0)
1771 return (0);
1772 }
1773 /* Remember buffer type, to switch on it later. */
1774 sync = !ISSET(bp->b_flags, B_ASYNC);
1775 wasdelayed = ISSET(bp->b_flags, B_DELWRI);
1776 CLR(bp->b_flags, (B_READ | B_DONE | B_ERROR | B_DELWRI));
1777
1778 if (wasdelayed)
1779 OSAddAtomicLong(-1, &nbdwrite);
1780
1781 if (!sync) {
1782 /*
1783 * If not synchronous, pay for the I/O operation and make
1784 * sure the buf is on the correct vnode queue. We have
1785 * to do this now, because if we don't, the vnode may not
1786 * be properly notified that its I/O has completed.
1787 */
1788 if (wasdelayed)
1789 buf_reassign(bp, vp);
1790 else
1791 if (p && p->p_stats)
1792 OSIncrementAtomicLong(&p->p_stats->p_ru.ru_oublock); /* XXX */
1793 }
1794 trace(TR_BUFWRITE, pack(vp, bp->b_bcount), bp->b_lblkno);
1795
1796 /* Initiate disk write. Make sure the appropriate party is charged. */
1797
1798 OSAddAtomic(1, &vp->v_numoutput);
1799
1800 VNOP_STRATEGY(bp);
1801
1802 if (sync) {
1803 /*
1804 * If I/O was synchronous, wait for it to complete.
1805 */
1806 rv = buf_biowait(bp);
1807
1808 /*
1809 * Pay for the I/O operation, if it's not been paid for, and
1810 * make sure it's on the correct vnode queue. (async operatings
1811 * were payed for above.)
1812 */
1813 if (wasdelayed)
1814 buf_reassign(bp, vp);
1815 else
1816 if (p && p->p_stats)
1817 OSIncrementAtomicLong(&p->p_stats->p_ru.ru_oublock); /* XXX */
1818
1819 /* Release the buffer. */
1820 // XXXdbg - only if the unused bit is set
1821 if (!ISSET(bp->b_flags, B_NORELSE)) {
1822 buf_brelse(bp);
1823 } else {
1824 CLR(bp->b_flags, B_NORELSE);
1825 }
1826
1827 return (rv);
1828 } else {
1829 return (0);
1830 }
1831 }
1832
1833 int
1834 vn_bwrite(struct vnop_bwrite_args *ap)
1835 {
1836 return (buf_bwrite(ap->a_bp));
1837 }
1838
1839 /*
1840 * Delayed write.
1841 *
1842 * The buffer is marked dirty, but is not queued for I/O.
1843 * This routine should be used when the buffer is expected
1844 * to be modified again soon, typically a small write that
1845 * partially fills a buffer.
1846 *
1847 * NB: magnetic tapes cannot be delayed; they must be
1848 * written in the order that the writes are requested.
1849 *
1850 * Described in Leffler, et al. (pp. 208-213).
1851 *
1852 * Note: With the ability to allocate additional buffer
1853 * headers, we can get in to the situation where "too" many
1854 * buf_bdwrite()s can create situation where the kernel can create
1855 * buffers faster than the disks can service. Doing a buf_bawrite() in
1856 * cases were we have "too many" outstanding buf_bdwrite()s avoids that.
1857 */
1858 __private_extern__ int
1859 bdwrite_internal(buf_t bp, int return_error)
1860 {
1861 proc_t p = current_proc();
1862 vnode_t vp = bp->b_vp;
1863
1864 /*
1865 * If the block hasn't been seen before:
1866 * (1) Mark it as having been seen,
1867 * (2) Charge for the write.
1868 * (3) Make sure it's on its vnode's correct block list,
1869 */
1870 if (!ISSET(bp->b_flags, B_DELWRI)) {
1871 SET(bp->b_flags, B_DELWRI);
1872 if (p && p->p_stats)
1873 OSIncrementAtomicLong(&p->p_stats->p_ru.ru_oublock); /* XXX */
1874 OSAddAtomicLong(1, &nbdwrite);
1875 buf_reassign(bp, vp);
1876 }
1877
1878 /*
1879 * if we're not LOCKED, but the total number of delayed writes
1880 * has climbed above 75% of the total buffers in the system
1881 * return an error if the caller has indicated that it can
1882 * handle one in this case, otherwise schedule the I/O now
1883 * this is done to prevent us from allocating tons of extra
1884 * buffers when dealing with virtual disks (i.e. DiskImages),
1885 * because additional buffers are dynamically allocated to prevent
1886 * deadlocks from occurring
1887 *
1888 * however, can't do a buf_bawrite() if the LOCKED bit is set because the
1889 * buffer is part of a transaction and can't go to disk until
1890 * the LOCKED bit is cleared.
1891 */
1892 if (!ISSET(bp->b_flags, B_LOCKED) && nbdwrite > ((nbuf_headers/4)*3)) {
1893 if (return_error)
1894 return (EAGAIN);
1895 /*
1896 * If the vnode has "too many" write operations in progress
1897 * wait for them to finish the IO
1898 */
1899 (void)vnode_waitforwrites(vp, VNODE_ASYNC_THROTTLE, 0, 0, "buf_bdwrite");
1900
1901 return (buf_bawrite(bp));
1902 }
1903
1904 /* Otherwise, the "write" is done, so mark and release the buffer. */
1905 SET(bp->b_flags, B_DONE);
1906 buf_brelse(bp);
1907 return (0);
1908 }
1909
1910 errno_t
1911 buf_bdwrite(buf_t bp)
1912 {
1913 return (bdwrite_internal(bp, 0));
1914 }
1915
1916
1917 /*
1918 * Asynchronous block write; just an asynchronous buf_bwrite().
1919 *
1920 * Note: With the abilitty to allocate additional buffer
1921 * headers, we can get in to the situation where "too" many
1922 * buf_bawrite()s can create situation where the kernel can create
1923 * buffers faster than the disks can service.
1924 * We limit the number of "in flight" writes a vnode can have to
1925 * avoid this.
1926 */
1927 static int
1928 bawrite_internal(buf_t bp, int throttle)
1929 {
1930 vnode_t vp = bp->b_vp;
1931
1932 if (vp) {
1933 if (throttle)
1934 /*
1935 * If the vnode has "too many" write operations in progress
1936 * wait for them to finish the IO
1937 */
1938 (void)vnode_waitforwrites(vp, VNODE_ASYNC_THROTTLE, 0, 0, (const char *)"buf_bawrite");
1939 else if (vp->v_numoutput >= VNODE_ASYNC_THROTTLE)
1940 /*
1941 * return to the caller and
1942 * let him decide what to do
1943 */
1944 return (EWOULDBLOCK);
1945 }
1946 SET(bp->b_flags, B_ASYNC);
1947
1948 return (VNOP_BWRITE(bp));
1949 }
1950
1951 errno_t
1952 buf_bawrite(buf_t bp)
1953 {
1954 return (bawrite_internal(bp, 1));
1955 }
1956
1957
1958 /*
1959 * Release a buffer on to the free lists.
1960 * Described in Bach (p. 46).
1961 */
1962 void
1963 buf_brelse(buf_t bp)
1964 {
1965 struct bqueues *bufq;
1966 long whichq;
1967 upl_t upl;
1968 int need_wakeup = 0;
1969 int need_bp_wakeup = 0;
1970
1971
1972 if (bp->b_whichq != -1 || !(bp->b_lflags & BL_BUSY))
1973 panic("buf_brelse: bad buffer = %p\n", bp);
1974
1975 #ifdef JOE_DEBUG
1976 (void) OSBacktrace(&bp->b_stackbrelse[0], 6);
1977
1978 bp->b_lastbrelse = current_thread();
1979 bp->b_tag = 0;
1980 #endif
1981 if (bp->b_lflags & BL_IOBUF) {
1982 free_io_buf(bp);
1983 return;
1984 }
1985
1986 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 388)) | DBG_FUNC_START,
1987 bp->b_lblkno * PAGE_SIZE, bp, bp->b_datap,
1988 bp->b_flags, 0);
1989
1990 trace(TR_BRELSE, pack(bp->b_vp, bp->b_bufsize), bp->b_lblkno);
1991
1992 /*
1993 * if we're invalidating a buffer that has the B_FILTER bit
1994 * set then call the b_iodone function so it gets cleaned
1995 * up properly.
1996 *
1997 * the HFS journal code depends on this
1998 */
1999 if (ISSET(bp->b_flags, B_META) && ISSET(bp->b_flags, B_INVAL)) {
2000 if (ISSET(bp->b_flags, B_FILTER)) { /* if necessary, call out */
2001 void (*iodone_func)(struct buf *, void *) = bp->b_iodone;
2002 void *arg = (void *)bp->b_transaction;
2003
2004 CLR(bp->b_flags, B_FILTER); /* but note callout done */
2005 bp->b_iodone = NULL;
2006 bp->b_transaction = NULL;
2007
2008 if (iodone_func == NULL) {
2009 panic("brelse: bp @ %p has NULL b_iodone!\n", bp);
2010 }
2011 (*iodone_func)(bp, arg);
2012 }
2013 }
2014 /*
2015 * I/O is done. Cleanup the UPL state
2016 */
2017 upl = bp->b_upl;
2018
2019 if ( !ISSET(bp->b_flags, B_META) && UBCINFOEXISTS(bp->b_vp) && bp->b_bufsize) {
2020 kern_return_t kret;
2021 int upl_flags;
2022
2023 if ( (upl == NULL) ) {
2024 if ( !ISSET(bp->b_flags, B_INVAL)) {
2025 kret = ubc_create_upl(bp->b_vp,
2026 ubc_blktooff(bp->b_vp, bp->b_lblkno),
2027 bp->b_bufsize,
2028 &upl,
2029 NULL,
2030 UPL_PRECIOUS);
2031
2032 if (kret != KERN_SUCCESS)
2033 panic("brelse: Failed to create UPL");
2034 #if UPL_DEBUG
2035 upl_ubc_alias_set(upl, (uintptr_t) bp, (uintptr_t) 5);
2036 #endif /* UPL_DEBUG */
2037 }
2038 } else {
2039 if (bp->b_datap) {
2040 kret = ubc_upl_unmap(upl);
2041
2042 if (kret != KERN_SUCCESS)
2043 panic("ubc_upl_unmap failed");
2044 bp->b_datap = (uintptr_t)NULL;
2045 }
2046 }
2047 if (upl) {
2048 if (bp->b_flags & (B_ERROR | B_INVAL)) {
2049 if (bp->b_flags & (B_READ | B_INVAL))
2050 upl_flags = UPL_ABORT_DUMP_PAGES;
2051 else
2052 upl_flags = 0;
2053
2054 ubc_upl_abort(upl, upl_flags);
2055 } else {
2056 if (ISSET(bp->b_flags, B_DELWRI | B_WASDIRTY))
2057 upl_flags = UPL_COMMIT_SET_DIRTY ;
2058 else
2059 upl_flags = UPL_COMMIT_CLEAR_DIRTY ;
2060
2061 ubc_upl_commit_range(upl, 0, bp->b_bufsize, upl_flags |
2062 UPL_COMMIT_INACTIVATE | UPL_COMMIT_FREE_ON_EMPTY);
2063 }
2064 bp->b_upl = NULL;
2065 }
2066 } else {
2067 if ( (upl) )
2068 panic("brelse: UPL set for non VREG; vp=%p", bp->b_vp);
2069 }
2070
2071 /*
2072 * If it's locked, don't report an error; try again later.
2073 */
2074 if (ISSET(bp->b_flags, (B_LOCKED|B_ERROR)) == (B_LOCKED|B_ERROR))
2075 CLR(bp->b_flags, B_ERROR);
2076 /*
2077 * If it's not cacheable, or an error, mark it invalid.
2078 */
2079 if (ISSET(bp->b_flags, (B_NOCACHE|B_ERROR)))
2080 SET(bp->b_flags, B_INVAL);
2081
2082 if ((bp->b_bufsize <= 0) ||
2083 ISSET(bp->b_flags, B_INVAL) ||
2084 (ISSET(bp->b_lflags, BL_WANTDEALLOC) && !ISSET(bp->b_flags, B_DELWRI))) {
2085 /*
2086 * If it's invalid or empty, dissociate it from its vnode,
2087 * release its storage if B_META, and
2088 * clean it up a bit and put it on the EMPTY queue
2089 */
2090 if (ISSET(bp->b_flags, B_DELWRI))
2091 OSAddAtomicLong(-1, &nbdwrite);
2092
2093 if (ISSET(bp->b_flags, B_META)) {
2094 if (bp->b_bufsize) {
2095 if (ISSET(bp->b_flags, B_ZALLOC)) {
2096 zone_t z;
2097
2098 z = getbufzone(bp->b_bufsize);
2099 zfree(z, (void *)bp->b_datap);
2100 } else
2101 kmem_free(kernel_map, bp->b_datap, bp->b_bufsize);
2102
2103 bp->b_datap = (uintptr_t)NULL;
2104 bp->b_bufsize = 0;
2105 }
2106 }
2107 /*
2108 * nuke any credentials we were holding
2109 */
2110 if (IS_VALID_CRED(bp->b_rcred)) {
2111 kauth_cred_unref(&bp->b_rcred);
2112 }
2113 if (IS_VALID_CRED(bp->b_wcred)) {
2114 kauth_cred_unref(&bp->b_wcred);
2115 }
2116 CLR(bp->b_flags, (B_META | B_ZALLOC | B_DELWRI | B_LOCKED | B_AGE | B_ASYNC | B_NOCACHE | B_FUA));
2117
2118 bufq = &bufqueues[BQ_EMPTY];
2119 bp->b_whichq = BQ_EMPTY;
2120
2121 lck_mtx_lock_spin(buf_mtxp);
2122
2123 if (bp->b_vp)
2124 brelvp_locked(bp);
2125
2126 bremhash(bp);
2127 BLISTNONE(bp);
2128 binshash(bp, &invalhash);
2129
2130 binsheadfree(bp, bufq, BQ_EMPTY);
2131 } else {
2132 /*
2133 * It has valid data. Put it on the end of the appropriate
2134 * queue, so that it'll stick around for as long as possible.
2135 */
2136 if (ISSET(bp->b_flags, B_LOCKED))
2137 whichq = BQ_LOCKED; /* locked in core */
2138 else if (ISSET(bp->b_flags, B_META))
2139 whichq = BQ_META; /* meta-data */
2140 else if (ISSET(bp->b_flags, B_AGE))
2141 whichq = BQ_AGE; /* stale but valid data */
2142 else
2143 whichq = BQ_LRU; /* valid data */
2144 bufq = &bufqueues[whichq];
2145
2146 CLR(bp->b_flags, (B_AGE | B_ASYNC | B_NOCACHE));
2147 bp->b_whichq = whichq;
2148 bp->b_timestamp = buf_timestamp();
2149
2150 lck_mtx_lock_spin(buf_mtxp);
2151
2152 binstailfree(bp, bufq, whichq);
2153 }
2154 if (needbuffer) {
2155 /*
2156 * needbuffer is a global
2157 * we're currently using buf_mtxp to protect it
2158 * delay doing the actual wakeup until after
2159 * we drop buf_mtxp
2160 */
2161 needbuffer = 0;
2162 need_wakeup = 1;
2163 }
2164 if (ISSET(bp->b_lflags, BL_WANTED)) {
2165 /*
2166 * delay the actual wakeup until after we
2167 * clear BL_BUSY and we've dropped buf_mtxp
2168 */
2169 need_bp_wakeup = 1;
2170 }
2171 /*
2172 * Unlock the buffer.
2173 */
2174 CLR(bp->b_lflags, (BL_BUSY | BL_WANTED));
2175 buf_busycount--;
2176
2177 lck_mtx_unlock(buf_mtxp);
2178
2179 if (need_wakeup) {
2180 /*
2181 * Wake up any processes waiting for any buffer to become free.
2182 */
2183 wakeup(&needbuffer);
2184 }
2185 if (need_bp_wakeup) {
2186 /*
2187 * Wake up any proceeses waiting for _this_ buffer to become free.
2188 */
2189 wakeup(bp);
2190 }
2191 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 388)) | DBG_FUNC_END,
2192 bp, bp->b_datap, bp->b_flags, 0, 0);
2193 }
2194
2195 /*
2196 * Determine if a block is in the cache.
2197 * Just look on what would be its hash chain. If it's there, return
2198 * a pointer to it, unless it's marked invalid. If it's marked invalid,
2199 * we normally don't return the buffer, unless the caller explicitly
2200 * wants us to.
2201 */
2202 static boolean_t
2203 incore(vnode_t vp, daddr64_t blkno)
2204 {
2205 boolean_t retval;
2206 struct bufhashhdr *dp;
2207
2208 dp = BUFHASH(vp, blkno);
2209
2210 lck_mtx_lock_spin(buf_mtxp);
2211
2212 if (incore_locked(vp, blkno, dp))
2213 retval = TRUE;
2214 else
2215 retval = FALSE;
2216 lck_mtx_unlock(buf_mtxp);
2217
2218 return (retval);
2219 }
2220
2221
2222 static buf_t
2223 incore_locked(vnode_t vp, daddr64_t blkno, struct bufhashhdr *dp)
2224 {
2225 struct buf *bp;
2226
2227 /* Search hash chain */
2228 for (bp = dp->lh_first; bp != NULL; bp = bp->b_hash.le_next) {
2229 if (bp->b_lblkno == blkno && bp->b_vp == vp &&
2230 !ISSET(bp->b_flags, B_INVAL)) {
2231 return (bp);
2232 }
2233 }
2234 return (NULL);
2235 }
2236
2237
2238 /* XXX FIXME -- Update the comment to reflect the UBC changes (please) -- */
2239 /*
2240 * Get a block of requested size that is associated with
2241 * a given vnode and block offset. If it is found in the
2242 * block cache, mark it as having been found, make it busy
2243 * and return it. Otherwise, return an empty block of the
2244 * correct size. It is up to the caller to insure that the
2245 * cached blocks be of the correct size.
2246 */
2247 buf_t
2248 buf_getblk(vnode_t vp, daddr64_t blkno, int size, int slpflag, int slptimeo, int operation)
2249 {
2250 buf_t bp;
2251 int err;
2252 upl_t upl;
2253 upl_page_info_t *pl;
2254 kern_return_t kret;
2255 int ret_only_valid;
2256 struct timespec ts;
2257 int upl_flags;
2258 struct bufhashhdr *dp;
2259
2260 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 386)) | DBG_FUNC_START,
2261 (uintptr_t)(blkno * PAGE_SIZE), size, operation, 0, 0);
2262
2263 ret_only_valid = operation & BLK_ONLYVALID;
2264 operation &= ~BLK_ONLYVALID;
2265 dp = BUFHASH(vp, blkno);
2266 start:
2267 lck_mtx_lock_spin(buf_mtxp);
2268
2269 if ((bp = incore_locked(vp, blkno, dp))) {
2270 /*
2271 * Found in the Buffer Cache
2272 */
2273 if (ISSET(bp->b_lflags, BL_BUSY)) {
2274 /*
2275 * but is busy
2276 */
2277 switch (operation) {
2278 case BLK_READ:
2279 case BLK_WRITE:
2280 case BLK_META:
2281 SET(bp->b_lflags, BL_WANTED);
2282 bufstats.bufs_busyincore++;
2283
2284 /*
2285 * don't retake the mutex after being awakened...
2286 * the time out is in msecs
2287 */
2288 ts.tv_sec = (slptimeo/1000);
2289 ts.tv_nsec = (slptimeo % 1000) * 10 * NSEC_PER_USEC * 1000;
2290
2291 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 396)) | DBG_FUNC_NONE,
2292 (uintptr_t)blkno, size, operation, 0, 0);
2293
2294 err = msleep(bp, buf_mtxp, slpflag | PDROP | (PRIBIO + 1), "buf_getblk", &ts);
2295
2296 /*
2297 * Callers who call with PCATCH or timeout are
2298 * willing to deal with the NULL pointer
2299 */
2300 if (err && ((slpflag & PCATCH) || ((err == EWOULDBLOCK) && slptimeo)))
2301 return (NULL);
2302 goto start;
2303 /*NOTREACHED*/
2304 break;
2305
2306 default:
2307 /*
2308 * unknown operation requested
2309 */
2310 panic("getblk: paging or unknown operation for incore busy buffer - %x\n", operation);
2311 /*NOTREACHED*/
2312 break;
2313 }
2314 } else {
2315 /*
2316 * buffer in core and not busy
2317 */
2318 SET(bp->b_lflags, BL_BUSY);
2319 SET(bp->b_flags, B_CACHE);
2320 buf_busycount++;
2321
2322 bremfree_locked(bp);
2323 bufstats.bufs_incore++;
2324
2325 lck_mtx_unlock(buf_mtxp);
2326 #ifdef JOE_DEBUG
2327 bp->b_owner = current_thread();
2328 bp->b_tag = 1;
2329 #endif
2330 if ( (bp->b_upl) )
2331 panic("buffer has UPL, but not marked BUSY: %p", bp);
2332
2333 if ( !ret_only_valid && bp->b_bufsize != size)
2334 allocbuf(bp, size);
2335
2336 upl_flags = 0;
2337 switch (operation) {
2338 case BLK_WRITE:
2339 /*
2340 * "write" operation: let the UPL subsystem
2341 * know that we intend to modify the buffer
2342 * cache pages we're gathering.
2343 */
2344 upl_flags |= UPL_WILL_MODIFY;
2345 case BLK_READ:
2346 upl_flags |= UPL_PRECIOUS;
2347 if (UBCINFOEXISTS(bp->b_vp) && bp->b_bufsize) {
2348 kret = ubc_create_upl(vp,
2349 ubc_blktooff(vp, bp->b_lblkno),
2350 bp->b_bufsize,
2351 &upl,
2352 &pl,
2353 upl_flags);
2354 if (kret != KERN_SUCCESS)
2355 panic("Failed to create UPL");
2356
2357 bp->b_upl = upl;
2358
2359 if (upl_valid_page(pl, 0)) {
2360 if (upl_dirty_page(pl, 0))
2361 SET(bp->b_flags, B_WASDIRTY);
2362 else
2363 CLR(bp->b_flags, B_WASDIRTY);
2364 } else
2365 CLR(bp->b_flags, (B_DONE | B_CACHE | B_WASDIRTY | B_DELWRI));
2366
2367 kret = ubc_upl_map(upl, (vm_offset_t*)&(bp->b_datap));
2368
2369 if (kret != KERN_SUCCESS)
2370 panic("getblk: ubc_upl_map() failed with (%d)", kret);
2371 }
2372 break;
2373
2374 case BLK_META:
2375 /*
2376 * VM is not involved in IO for the meta data
2377 * buffer already has valid data
2378 */
2379 break;
2380
2381 default:
2382 panic("getblk: paging or unknown operation for incore buffer- %d\n", operation);
2383 /*NOTREACHED*/
2384 break;
2385 }
2386 }
2387 } else { /* not incore() */
2388 int queue = BQ_EMPTY; /* Start with no preference */
2389
2390 if (ret_only_valid) {
2391 lck_mtx_unlock(buf_mtxp);
2392 return (NULL);
2393 }
2394 if ((vnode_isreg(vp) == 0) || (UBCINFOEXISTS(vp) == 0) /*|| (vnode_issystem(vp) == 1)*/)
2395 operation = BLK_META;
2396
2397 if ((bp = getnewbuf(slpflag, slptimeo, &queue)) == NULL)
2398 goto start;
2399
2400 /*
2401 * getnewbuf may block for a number of different reasons...
2402 * if it does, it's then possible for someone else to
2403 * create a buffer for the same block and insert it into
2404 * the hash... if we see it incore at this point we dump
2405 * the buffer we were working on and start over
2406 */
2407 if (incore_locked(vp, blkno, dp)) {
2408 SET(bp->b_flags, B_INVAL);
2409 binshash(bp, &invalhash);
2410
2411 lck_mtx_unlock(buf_mtxp);
2412
2413 buf_brelse(bp);
2414 goto start;
2415 }
2416 /*
2417 * NOTE: YOU CAN NOT BLOCK UNTIL binshash() HAS BEEN
2418 * CALLED! BE CAREFUL.
2419 */
2420
2421 /*
2422 * mark the buffer as B_META if indicated
2423 * so that when buffer is released it will goto META queue
2424 */
2425 if (operation == BLK_META)
2426 SET(bp->b_flags, B_META);
2427
2428 bp->b_blkno = bp->b_lblkno = blkno;
2429 bp->b_vp = vp;
2430
2431 /*
2432 * Insert in the hash so that incore() can find it
2433 */
2434 binshash(bp, BUFHASH(vp, blkno));
2435
2436 bgetvp_locked(vp, bp);
2437
2438 lck_mtx_unlock(buf_mtxp);
2439
2440 allocbuf(bp, size);
2441
2442 upl_flags = 0;
2443 switch (operation) {
2444 case BLK_META:
2445 /*
2446 * buffer data is invalid...
2447 *
2448 * I don't want to have to retake buf_mtxp,
2449 * so the miss and vmhits counters are done
2450 * with Atomic updates... all other counters
2451 * in bufstats are protected with either
2452 * buf_mtxp or iobuffer_mtxp
2453 */
2454 OSAddAtomicLong(1, &bufstats.bufs_miss);
2455 break;
2456
2457 case BLK_WRITE:
2458 /*
2459 * "write" operation: let the UPL subsystem know
2460 * that we intend to modify the buffer cache pages
2461 * we're gathering.
2462 */
2463 upl_flags |= UPL_WILL_MODIFY;
2464 case BLK_READ:
2465 { off_t f_offset;
2466 size_t contig_bytes;
2467 int bmap_flags;
2468
2469 if ( (bp->b_upl) )
2470 panic("bp already has UPL: %p",bp);
2471
2472 f_offset = ubc_blktooff(vp, blkno);
2473
2474 upl_flags |= UPL_PRECIOUS;
2475 kret = ubc_create_upl(vp,
2476 f_offset,
2477 bp->b_bufsize,
2478 &upl,
2479 &pl,
2480 upl_flags);
2481
2482 if (kret != KERN_SUCCESS)
2483 panic("Failed to create UPL");
2484 #if UPL_DEBUG
2485 upl_ubc_alias_set(upl, (uintptr_t) bp, (uintptr_t) 4);
2486 #endif /* UPL_DEBUG */
2487 bp->b_upl = upl;
2488
2489 if (upl_valid_page(pl, 0)) {
2490
2491 if (operation == BLK_READ)
2492 bmap_flags = VNODE_READ;
2493 else
2494 bmap_flags = VNODE_WRITE;
2495
2496 SET(bp->b_flags, B_CACHE | B_DONE);
2497
2498 OSAddAtomicLong(1, &bufstats.bufs_vmhits);
2499
2500 bp->b_validoff = 0;
2501 bp->b_dirtyoff = 0;
2502
2503 if (upl_dirty_page(pl, 0)) {
2504 /* page is dirty */
2505 SET(bp->b_flags, B_WASDIRTY);
2506
2507 bp->b_validend = bp->b_bcount;
2508 bp->b_dirtyend = bp->b_bcount;
2509 } else {
2510 /* page is clean */
2511 bp->b_validend = bp->b_bcount;
2512 bp->b_dirtyend = 0;
2513 }
2514 /*
2515 * try to recreate the physical block number associated with
2516 * this buffer...
2517 */
2518 if (VNOP_BLOCKMAP(vp, f_offset, bp->b_bcount, &bp->b_blkno, &contig_bytes, NULL, bmap_flags, NULL))
2519 panic("getblk: VNOP_BLOCKMAP failed");
2520 /*
2521 * if the extent represented by this buffer
2522 * is not completely physically contiguous on
2523 * disk, than we can't cache the physical mapping
2524 * in the buffer header
2525 */
2526 if ((long)contig_bytes < bp->b_bcount)
2527 bp->b_blkno = bp->b_lblkno;
2528 } else {
2529 OSAddAtomicLong(1, &bufstats.bufs_miss);
2530 }
2531 kret = ubc_upl_map(upl, (vm_offset_t *)&(bp->b_datap));
2532
2533 if (kret != KERN_SUCCESS)
2534 panic("getblk: ubc_upl_map() failed with (%d)", kret);
2535 break;
2536 }
2537 default:
2538 panic("getblk: paging or unknown operation - %x", operation);
2539 /*NOTREACHED*/
2540 break;
2541 }
2542 }
2543 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 386)) | DBG_FUNC_END,
2544 bp, bp->b_datap, bp->b_flags, 3, 0);
2545
2546 #ifdef JOE_DEBUG
2547 (void) OSBacktrace(&bp->b_stackgetblk[0], 6);
2548 #endif
2549 return (bp);
2550 }
2551
2552 /*
2553 * Get an empty, disassociated buffer of given size.
2554 */
2555 buf_t
2556 buf_geteblk(int size)
2557 {
2558 buf_t bp = NULL;
2559 int queue = BQ_EMPTY;
2560
2561 do {
2562 lck_mtx_lock_spin(buf_mtxp);
2563
2564 bp = getnewbuf(0, 0, &queue);
2565 } while (bp == NULL);
2566
2567 SET(bp->b_flags, (B_META|B_INVAL));
2568
2569 #if DIAGNOSTIC
2570 assert(queue == BQ_EMPTY);
2571 #endif /* DIAGNOSTIC */
2572 /* XXX need to implement logic to deal with other queues */
2573
2574 binshash(bp, &invalhash);
2575 bufstats.bufs_eblk++;
2576
2577 lck_mtx_unlock(buf_mtxp);
2578
2579 allocbuf(bp, size);
2580
2581 return (bp);
2582 }
2583
2584
2585 /*
2586 * With UBC, there is no need to expand / shrink the file data
2587 * buffer. The VM uses the same pages, hence no waste.
2588 * All the file data buffers can have one size.
2589 * In fact expand / shrink would be an expensive operation.
2590 *
2591 * Only exception to this is meta-data buffers. Most of the
2592 * meta data operations are smaller than PAGE_SIZE. Having the
2593 * meta-data buffers grow and shrink as needed, optimizes use
2594 * of the kernel wired memory.
2595 */
2596
2597 int
2598 allocbuf(buf_t bp, int size)
2599 {
2600 vm_size_t desired_size;
2601
2602 desired_size = roundup(size, CLBYTES);
2603
2604 if (desired_size < PAGE_SIZE)
2605 desired_size = PAGE_SIZE;
2606 if (desired_size > MAXBSIZE)
2607 panic("allocbuf: buffer larger than MAXBSIZE requested");
2608
2609 if (ISSET(bp->b_flags, B_META)) {
2610 zone_t zprev, z;
2611 int nsize = roundup(size, MINMETA);
2612
2613 if (bp->b_datap) {
2614 vm_offset_t elem = (vm_offset_t)bp->b_datap;
2615
2616 if (ISSET(bp->b_flags, B_ZALLOC)) {
2617 if (bp->b_bufsize < nsize) {
2618 /* reallocate to a bigger size */
2619
2620 zprev = getbufzone(bp->b_bufsize);
2621 if (nsize <= MAXMETA) {
2622 desired_size = nsize;
2623 z = getbufzone(nsize);
2624 /* b_datap not really a ptr */
2625 *(void **)(&bp->b_datap) = zalloc(z);
2626 } else {
2627 bp->b_datap = (uintptr_t)NULL;
2628 kmem_alloc_kobject(kernel_map, (vm_offset_t *)&bp->b_datap, desired_size);
2629 CLR(bp->b_flags, B_ZALLOC);
2630 }
2631 bcopy((void *)elem, (caddr_t)bp->b_datap, bp->b_bufsize);
2632 zfree(zprev, (void *)elem);
2633 } else {
2634 desired_size = bp->b_bufsize;
2635 }
2636
2637 } else {
2638 if ((vm_size_t)bp->b_bufsize < desired_size) {
2639 /* reallocate to a bigger size */
2640 bp->b_datap = (uintptr_t)NULL;
2641 kmem_alloc_kobject(kernel_map, (vm_offset_t *)&bp->b_datap, desired_size);
2642 bcopy((const void *)elem, (caddr_t)bp->b_datap, bp->b_bufsize);
2643 kmem_free(kernel_map, elem, bp->b_bufsize);
2644 } else {
2645 desired_size = bp->b_bufsize;
2646 }
2647 }
2648 } else {
2649 /* new allocation */
2650 if (nsize <= MAXMETA) {
2651 desired_size = nsize;
2652 z = getbufzone(nsize);
2653 /* b_datap not really a ptr */
2654 *(void **)(&bp->b_datap) = zalloc(z);
2655 SET(bp->b_flags, B_ZALLOC);
2656 } else
2657 kmem_alloc_kobject(kernel_map, (vm_offset_t *)&bp->b_datap, desired_size);
2658 }
2659
2660 if (bp->b_datap == 0)
2661 panic("allocbuf: NULL b_datap");
2662 }
2663 bp->b_bufsize = desired_size;
2664 bp->b_bcount = size;
2665
2666 return (0);
2667 }
2668
2669 /*
2670 * Get a new buffer from one of the free lists.
2671 *
2672 * Request for a queue is passes in. The queue from which the buffer was taken
2673 * from is returned. Out of range queue requests get BQ_EMPTY. Request for
2674 * BQUEUE means no preference. Use heuristics in that case.
2675 * Heuristics is as follows:
2676 * Try BQ_AGE, BQ_LRU, BQ_EMPTY, BQ_META in that order.
2677 * If none available block till one is made available.
2678 * If buffers available on both BQ_AGE and BQ_LRU, check the timestamps.
2679 * Pick the most stale buffer.
2680 * If found buffer was marked delayed write, start the async. write
2681 * and restart the search.
2682 * Initialize the fields and disassociate the buffer from the vnode.
2683 * Remove the buffer from the hash. Return the buffer and the queue
2684 * on which it was found.
2685 *
2686 * buf_mtxp is held upon entry
2687 * returns with buf_mtxp locked if new buf available
2688 * returns with buf_mtxp UNlocked if new buf NOT available
2689 */
2690
2691 static buf_t
2692 getnewbuf(int slpflag, int slptimeo, int * queue)
2693 {
2694 buf_t bp;
2695 buf_t lru_bp;
2696 buf_t age_bp;
2697 buf_t meta_bp;
2698 int age_time, lru_time, bp_time, meta_time;
2699 int req = *queue; /* save it for restarts */
2700 struct timespec ts;
2701
2702 start:
2703 /*
2704 * invalid request gets empty queue
2705 */
2706 if ((*queue >= BQUEUES) || (*queue < 0)
2707 || (*queue == BQ_LAUNDRY) || (*queue == BQ_LOCKED))
2708 *queue = BQ_EMPTY;
2709
2710
2711 if (*queue == BQ_EMPTY && (bp = bufqueues[*queue].tqh_first))
2712 goto found;
2713
2714 /*
2715 * need to grow number of bufs, add another one rather than recycling
2716 */
2717 if (nbuf_headers < max_nbuf_headers) {
2718 /*
2719 * Increment count now as lock
2720 * is dropped for allocation.
2721 * That avoids over commits
2722 */
2723 nbuf_headers++;
2724 goto add_newbufs;
2725 }
2726 /* Try for the requested queue first */
2727 bp = bufqueues[*queue].tqh_first;
2728 if (bp)
2729 goto found;
2730
2731 /* Unable to use requested queue */
2732 age_bp = bufqueues[BQ_AGE].tqh_first;
2733 lru_bp = bufqueues[BQ_LRU].tqh_first;
2734 meta_bp = bufqueues[BQ_META].tqh_first;
2735
2736 if (!age_bp && !lru_bp && !meta_bp) {
2737 /*
2738 * Unavailble on AGE or LRU or META queues
2739 * Try the empty list first
2740 */
2741 bp = bufqueues[BQ_EMPTY].tqh_first;
2742 if (bp) {
2743 *queue = BQ_EMPTY;
2744 goto found;
2745 }
2746 /*
2747 * We have seen is this is hard to trigger.
2748 * This is an overcommit of nbufs but needed
2749 * in some scenarios with diskiamges
2750 */
2751
2752 add_newbufs:
2753 lck_mtx_unlock(buf_mtxp);
2754
2755 /* Create a new temporary buffer header */
2756 bp = (struct buf *)zalloc(buf_hdr_zone);
2757
2758 if (bp) {
2759 bufhdrinit(bp);
2760 bp->b_whichq = BQ_EMPTY;
2761 bp->b_timestamp = buf_timestamp();
2762 BLISTNONE(bp);
2763 SET(bp->b_flags, B_HDRALLOC);
2764 *queue = BQ_EMPTY;
2765 }
2766 lck_mtx_lock_spin(buf_mtxp);
2767
2768 if (bp) {
2769 binshash(bp, &invalhash);
2770 binsheadfree(bp, &bufqueues[BQ_EMPTY], BQ_EMPTY);
2771 buf_hdr_count++;
2772 goto found;
2773 }
2774 /* subtract already accounted bufcount */
2775 nbuf_headers--;
2776
2777 bufstats.bufs_sleeps++;
2778
2779 /* wait for a free buffer of any kind */
2780 needbuffer = 1;
2781 /* hz value is 100 */
2782 ts.tv_sec = (slptimeo/1000);
2783 /* the hz value is 100; which leads to 10ms */
2784 ts.tv_nsec = (slptimeo % 1000) * NSEC_PER_USEC * 1000 * 10;
2785
2786 msleep(&needbuffer, buf_mtxp, slpflag | PDROP | (PRIBIO+1), "getnewbuf", &ts);
2787 return (NULL);
2788 }
2789
2790 /* Buffer available either on AGE or LRU or META */
2791 bp = NULL;
2792 *queue = -1;
2793
2794 /* Buffer available either on AGE or LRU */
2795 if (!age_bp) {
2796 bp = lru_bp;
2797 *queue = BQ_LRU;
2798 } else if (!lru_bp) {
2799 bp = age_bp;
2800 *queue = BQ_AGE;
2801 } else { /* buffer available on both AGE and LRU */
2802 int t = buf_timestamp();
2803
2804 age_time = t - age_bp->b_timestamp;
2805 lru_time = t - lru_bp->b_timestamp;
2806 if ((age_time < 0) || (lru_time < 0)) { /* time set backwards */
2807 bp = age_bp;
2808 *queue = BQ_AGE;
2809 /*
2810 * we should probably re-timestamp eveything in the
2811 * queues at this point with the current time
2812 */
2813 } else {
2814 if ((lru_time >= lru_is_stale) && (age_time < age_is_stale)) {
2815 bp = lru_bp;
2816 *queue = BQ_LRU;
2817 } else {
2818 bp = age_bp;
2819 *queue = BQ_AGE;
2820 }
2821 }
2822 }
2823
2824 if (!bp) { /* Neither on AGE nor on LRU */
2825 bp = meta_bp;
2826 *queue = BQ_META;
2827 } else if (meta_bp) {
2828 int t = buf_timestamp();
2829
2830 bp_time = t - bp->b_timestamp;
2831 meta_time = t - meta_bp->b_timestamp;
2832
2833 if (!(bp_time < 0) && !(meta_time < 0)) {
2834 /* time not set backwards */
2835 int bp_is_stale;
2836 bp_is_stale = (*queue == BQ_LRU) ?
2837 lru_is_stale : age_is_stale;
2838
2839 if ((meta_time >= meta_is_stale) &&
2840 (bp_time < bp_is_stale)) {
2841 bp = meta_bp;
2842 *queue = BQ_META;
2843 }
2844 }
2845 }
2846 found:
2847 if (ISSET(bp->b_flags, B_LOCKED) || ISSET(bp->b_lflags, BL_BUSY))
2848 panic("getnewbuf: bp @ %p is LOCKED or BUSY! (flags 0x%x)\n", bp, bp->b_flags);
2849
2850 /* Clean it */
2851 if (bcleanbuf(bp, FALSE)) {
2852 /*
2853 * moved to the laundry thread, buffer not ready
2854 */
2855 *queue = req;
2856 goto start;
2857 }
2858 return (bp);
2859 }
2860
2861
2862 /*
2863 * Clean a buffer.
2864 * Returns 0 is buffer is ready to use,
2865 * Returns 1 if issued a buf_bawrite() to indicate
2866 * that the buffer is not ready.
2867 *
2868 * buf_mtxp is held upon entry
2869 * returns with buf_mtxp locked
2870 */
2871 static int
2872 bcleanbuf(buf_t bp, boolean_t discard)
2873 {
2874 /* Remove from the queue */
2875 bremfree_locked(bp);
2876
2877 #ifdef JOE_DEBUG
2878 bp->b_owner = current_thread();
2879 bp->b_tag = 2;
2880 #endif
2881 /*
2882 * If buffer was a delayed write, start the IO by queuing
2883 * it on the LAUNDRY queue, and return 1
2884 */
2885 if (ISSET(bp->b_flags, B_DELWRI)) {
2886 if (discard) {
2887 SET(bp->b_lflags, BL_WANTDEALLOC);
2888 }
2889
2890 bp->b_whichq = BQ_LAUNDRY;
2891 bp->b_timestamp = buf_timestamp();
2892 binstailfree(bp, &bufqueues[BQ_LAUNDRY], BQ_LAUNDRY);
2893 blaundrycnt++;
2894
2895 lck_mtx_unlock(buf_mtxp);
2896
2897 wakeup(&bufqueues[BQ_LAUNDRY]);
2898 /*
2899 * and give it a chance to run
2900 */
2901 (void)thread_block(THREAD_CONTINUE_NULL);
2902
2903 lck_mtx_lock_spin(buf_mtxp);
2904
2905 return (1);
2906 }
2907 #ifdef JOE_DEBUG
2908 bp->b_owner = current_thread();
2909 bp->b_tag = 8;
2910 #endif
2911 /*
2912 * Buffer is no longer on any free list... we own it
2913 */
2914 SET(bp->b_lflags, BL_BUSY);
2915 buf_busycount++;
2916
2917 bremhash(bp);
2918
2919 /*
2920 * disassociate us from our vnode, if we had one...
2921 */
2922 if (bp->b_vp)
2923 brelvp_locked(bp);
2924
2925 lck_mtx_unlock(buf_mtxp);
2926
2927 BLISTNONE(bp);
2928
2929 if (ISSET(bp->b_flags, B_META)) {
2930 vm_offset_t elem;
2931
2932 elem = (vm_offset_t)bp->b_datap;
2933 bp->b_datap = (uintptr_t)0xdeadbeef;
2934
2935 if (ISSET(bp->b_flags, B_ZALLOC)) {
2936 zone_t z;
2937
2938 z = getbufzone(bp->b_bufsize);
2939 zfree(z, (void *)elem);
2940 } else
2941 kmem_free(kernel_map, elem, bp->b_bufsize);
2942 }
2943
2944 trace(TR_BRELSE, pack(bp->b_vp, bp->b_bufsize), bp->b_lblkno);
2945
2946 /* nuke any credentials we were holding */
2947 if (IS_VALID_CRED(bp->b_rcred)) {
2948 kauth_cred_unref(&bp->b_rcred);
2949 }
2950 if (IS_VALID_CRED(bp->b_wcred)) {
2951 kauth_cred_unref(&bp->b_wcred);
2952 }
2953
2954 /* If discarding, just move to the empty queue */
2955 if (discard) {
2956 lck_mtx_lock_spin(buf_mtxp);
2957 CLR(bp->b_flags, (B_META | B_ZALLOC | B_DELWRI | B_LOCKED | B_AGE | B_ASYNC | B_NOCACHE | B_FUA));
2958 bp->b_whichq = BQ_EMPTY;
2959 binshash(bp, &invalhash);
2960 binsheadfree(bp, &bufqueues[BQ_EMPTY], BQ_EMPTY);
2961 CLR(bp->b_lflags, BL_BUSY);
2962 buf_busycount--;
2963 } else {
2964 /* Not discarding: clean up and prepare for reuse */
2965 bp->b_bufsize = 0;
2966 bp->b_datap = (uintptr_t)NULL;
2967 bp->b_upl = (void *)NULL;
2968 /*
2969 * preserve the state of whether this buffer
2970 * was allocated on the fly or not...
2971 * the only other flag that should be set at
2972 * this point is BL_BUSY...
2973 */
2974 #ifdef JOE_DEBUG
2975 bp->b_owner = current_thread();
2976 bp->b_tag = 3;
2977 #endif
2978 bp->b_lflags = BL_BUSY;
2979 bp->b_flags = (bp->b_flags & B_HDRALLOC);
2980 bp->b_dev = NODEV;
2981 bp->b_blkno = bp->b_lblkno = 0;
2982 bp->b_iodone = NULL;
2983 bp->b_error = 0;
2984 bp->b_resid = 0;
2985 bp->b_bcount = 0;
2986 bp->b_dirtyoff = bp->b_dirtyend = 0;
2987 bp->b_validoff = bp->b_validend = 0;
2988 #ifdef CONFIG_PROTECT
2989 bp->b_cpentry = 0;
2990 #endif
2991
2992 lck_mtx_lock_spin(buf_mtxp);
2993 }
2994 return (0);
2995 }
2996
2997
2998
2999 errno_t
3000 buf_invalblkno(vnode_t vp, daddr64_t lblkno, int flags)
3001 {
3002 buf_t bp;
3003 errno_t error;
3004 struct bufhashhdr *dp;
3005
3006 dp = BUFHASH(vp, lblkno);
3007
3008 relook:
3009 lck_mtx_lock_spin(buf_mtxp);
3010
3011 if ((bp = incore_locked(vp, lblkno, dp)) == (struct buf *)0) {
3012 lck_mtx_unlock(buf_mtxp);
3013 return (0);
3014 }
3015 if (ISSET(bp->b_lflags, BL_BUSY)) {
3016 if ( !ISSET(flags, BUF_WAIT)) {
3017 lck_mtx_unlock(buf_mtxp);
3018 return (EBUSY);
3019 }
3020 SET(bp->b_lflags, BL_WANTED);
3021
3022 error = msleep((caddr_t)bp, buf_mtxp, PDROP | (PRIBIO + 1), "buf_invalblkno", NULL);
3023
3024 if (error) {
3025 return (error);
3026 }
3027 goto relook;
3028 }
3029 bremfree_locked(bp);
3030 SET(bp->b_lflags, BL_BUSY);
3031 SET(bp->b_flags, B_INVAL);
3032 buf_busycount++;
3033 #ifdef JOE_DEBUG
3034 bp->b_owner = current_thread();
3035 bp->b_tag = 4;
3036 #endif
3037 lck_mtx_unlock(buf_mtxp);
3038 buf_brelse(bp);
3039
3040 return (0);
3041 }
3042
3043
3044 void
3045 buf_drop(buf_t bp)
3046 {
3047 int need_wakeup = 0;
3048
3049 lck_mtx_lock_spin(buf_mtxp);
3050
3051 if (ISSET(bp->b_lflags, BL_WANTED)) {
3052 /*
3053 * delay the actual wakeup until after we
3054 * clear BL_BUSY and we've dropped buf_mtxp
3055 */
3056 need_wakeup = 1;
3057 }
3058 #ifdef JOE_DEBUG
3059 bp->b_owner = current_thread();
3060 bp->b_tag = 9;
3061 #endif
3062 /*
3063 * Unlock the buffer.
3064 */
3065 CLR(bp->b_lflags, (BL_BUSY | BL_WANTED));
3066 buf_busycount--;
3067
3068 lck_mtx_unlock(buf_mtxp);
3069
3070 if (need_wakeup) {
3071 /*
3072 * Wake up any proceeses waiting for _this_ buffer to become free.
3073 */
3074 wakeup(bp);
3075 }
3076 }
3077
3078
3079 errno_t
3080 buf_acquire(buf_t bp, int flags, int slpflag, int slptimeo) {
3081 errno_t error;
3082
3083 lck_mtx_lock_spin(buf_mtxp);
3084
3085 error = buf_acquire_locked(bp, flags, slpflag, slptimeo);
3086
3087 lck_mtx_unlock(buf_mtxp);
3088
3089 return (error);
3090 }
3091
3092
3093 static errno_t
3094 buf_acquire_locked(buf_t bp, int flags, int slpflag, int slptimeo)
3095 {
3096 errno_t error;
3097 struct timespec ts;
3098
3099 if (ISSET(bp->b_flags, B_LOCKED)) {
3100 if ((flags & BAC_SKIP_LOCKED))
3101 return (EDEADLK);
3102 } else {
3103 if ((flags & BAC_SKIP_NONLOCKED))
3104 return (EDEADLK);
3105 }
3106 if (ISSET(bp->b_lflags, BL_BUSY)) {
3107 /*
3108 * since the lck_mtx_lock may block, the buffer
3109 * may become BUSY, so we need to
3110 * recheck for a NOWAIT request
3111 */
3112 if (flags & BAC_NOWAIT)
3113 return (EBUSY);
3114 SET(bp->b_lflags, BL_WANTED);
3115
3116 /* the hz value is 100; which leads to 10ms */
3117 ts.tv_sec = (slptimeo/100);
3118 ts.tv_nsec = (slptimeo % 100) * 10 * NSEC_PER_USEC * 1000;
3119 error = msleep((caddr_t)bp, buf_mtxp, slpflag | (PRIBIO + 1), "buf_acquire", &ts);
3120
3121 if (error)
3122 return (error);
3123 return (EAGAIN);
3124 }
3125 if (flags & BAC_REMOVE)
3126 bremfree_locked(bp);
3127 SET(bp->b_lflags, BL_BUSY);
3128 buf_busycount++;
3129
3130 #ifdef JOE_DEBUG
3131 bp->b_owner = current_thread();
3132 bp->b_tag = 5;
3133 #endif
3134 return (0);
3135 }
3136
3137
3138 /*
3139 * Wait for operations on the buffer to complete.
3140 * When they do, extract and return the I/O's error value.
3141 */
3142 errno_t
3143 buf_biowait(buf_t bp)
3144 {
3145 while (!ISSET(bp->b_flags, B_DONE)) {
3146
3147 lck_mtx_lock_spin(buf_mtxp);
3148
3149 if (!ISSET(bp->b_flags, B_DONE)) {
3150 DTRACE_IO1(wait__start, buf_t, bp);
3151 (void) msleep(bp, buf_mtxp, PDROP | (PRIBIO+1), "buf_biowait", NULL);
3152 DTRACE_IO1(wait__done, buf_t, bp);
3153 } else
3154 lck_mtx_unlock(buf_mtxp);
3155 }
3156 /* check for interruption of I/O (e.g. via NFS), then errors. */
3157 if (ISSET(bp->b_flags, B_EINTR)) {
3158 CLR(bp->b_flags, B_EINTR);
3159 return (EINTR);
3160 } else if (ISSET(bp->b_flags, B_ERROR))
3161 return (bp->b_error ? bp->b_error : EIO);
3162 else
3163 return (0);
3164 }
3165
3166 /*
3167 * Wait for the callback operation on a B_CALL buffer to complete.
3168 */
3169 void
3170 buf_biowait_callback(buf_t bp)
3171 {
3172 while (!ISSET(bp->b_lflags, BL_CALLDONE)) {
3173
3174 lck_mtx_lock_spin(buf_mtxp);
3175
3176 if (!ISSET(bp->b_lflags, BL_CALLDONE)) {
3177 DTRACE_IO1(wait__start, buf_t, bp);
3178 (void) msleep(bp, buf_mtxp, PDROP | (PRIBIO+1), "buf_biowait", NULL);
3179 DTRACE_IO1(wait__done, buf_t, bp);
3180 } else
3181 lck_mtx_unlock(buf_mtxp);
3182 }
3183 }
3184
3185 /*
3186 * Mark I/O complete on a buffer.
3187 *
3188 * If a callback has been requested, e.g. the pageout
3189 * daemon, do so. Otherwise, awaken waiting processes.
3190 *
3191 * [ Leffler, et al., says on p.247:
3192 * "This routine wakes up the blocked process, frees the buffer
3193 * for an asynchronous write, or, for a request by the pagedaemon
3194 * process, invokes a procedure specified in the buffer structure" ]
3195 *
3196 * In real life, the pagedaemon (or other system processes) wants
3197 * to do async stuff to, and doesn't want the buffer buf_brelse()'d.
3198 * (for swap pager, that puts swap buffers on the free lists (!!!),
3199 * for the vn device, that puts malloc'd buffers on the free lists!)
3200 */
3201 extern struct timeval priority_IO_timestamp_for_root;
3202 extern int hard_throttle_on_root;
3203
3204 void
3205 buf_biodone(buf_t bp)
3206 {
3207 mount_t mp;
3208
3209 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 387)) | DBG_FUNC_START,
3210 bp, bp->b_datap, bp->b_flags, 0, 0);
3211
3212 if (ISSET(bp->b_flags, B_DONE))
3213 panic("biodone already");
3214
3215 if (ISSET(bp->b_flags, B_ERROR)) {
3216 fslog_io_error(bp);
3217 }
3218
3219 if (bp->b_vp && bp->b_vp->v_mount) {
3220 mp = bp->b_vp->v_mount;
3221 } else {
3222 mp = NULL;
3223 }
3224
3225 if (mp && (bp->b_flags & B_READ) == 0) {
3226 update_last_io_time(mp);
3227 INCR_PENDING_IO(-(pending_io_t)buf_count(bp), mp->mnt_pending_write_size);
3228 } else if (mp) {
3229 INCR_PENDING_IO(-(pending_io_t)buf_count(bp), mp->mnt_pending_read_size);
3230 }
3231
3232 if (kdebug_enable) {
3233 int code = DKIO_DONE;
3234
3235 if (bp->b_flags & B_READ)
3236 code |= DKIO_READ;
3237 if (bp->b_flags & B_ASYNC)
3238 code |= DKIO_ASYNC;
3239
3240 if (bp->b_flags & B_META)
3241 code |= DKIO_META;
3242 else if (bp->b_flags & B_PAGEIO)
3243 code |= DKIO_PAGING;
3244
3245 KERNEL_DEBUG_CONSTANT(FSDBG_CODE(DBG_DKRW, code) | DBG_FUNC_NONE,
3246 bp, (uintptr_t)bp->b_vp,
3247 bp->b_resid, bp->b_error, 0);
3248 }
3249 if ((bp->b_vp != NULLVP) &&
3250 ((bp->b_flags & (B_IOSTREAMING | B_PAGEIO | B_READ)) == (B_PAGEIO | B_READ)) &&
3251 (bp->b_vp->v_mount->mnt_kern_flag & MNTK_ROOTDEV)) {
3252 microuptime(&priority_IO_timestamp_for_root);
3253 hard_throttle_on_root = 0;
3254 }
3255 /*
3256 * I/O was done, so don't believe
3257 * the DIRTY state from VM anymore
3258 */
3259 CLR(bp->b_flags, B_WASDIRTY);
3260 DTRACE_IO1(done, buf_t, bp);
3261
3262 if (!ISSET(bp->b_flags, B_READ) && !ISSET(bp->b_flags, B_RAW))
3263 /*
3264 * wake up any writer's blocked
3265 * on throttle or waiting for I/O
3266 * to drain
3267 */
3268 vnode_writedone(bp->b_vp);
3269
3270 if (ISSET(bp->b_flags, (B_CALL | B_FILTER))) { /* if necessary, call out */
3271 void (*iodone_func)(struct buf *, void *) = bp->b_iodone;
3272 void *arg = (void *)bp->b_transaction;
3273 int callout = ISSET(bp->b_flags, B_CALL);
3274
3275 CLR(bp->b_flags, (B_CALL | B_FILTER)); /* filters and callouts are one-shot */
3276 bp->b_iodone = NULL;
3277 bp->b_transaction = NULL;
3278
3279 if (iodone_func == NULL) {
3280 panic("biodone: bp @ %p has NULL b_iodone!\n", bp);
3281 } else {
3282 if (callout)
3283 SET(bp->b_flags, B_DONE); /* note that it's done */
3284 (*iodone_func)(bp, arg);
3285 }
3286 if (callout) {
3287 int need_wakeup = 0;
3288
3289 /*
3290 * assumes that the callback function takes
3291 * ownership of the bp and deals with releasing it if necessary
3292 * BL_WANTED indicates that we've decided to wait on the
3293 * completion of this I/O in a synchronous manner... we
3294 * still call the callback function, but in addition we
3295 * will do a wakeup... BL_CALLDONE indicates that the callback
3296 * routine has completed and its ok for the waiter to take
3297 * 'ownership' of this bp back
3298 */
3299 lck_mtx_lock_spin(buf_mtxp);
3300
3301 if (bp->b_lflags & BL_WANTED) {
3302 CLR(bp->b_lflags, BL_WANTED);
3303 need_wakeup = 1;
3304 }
3305 SET(bp->b_lflags, BL_CALLDONE);
3306
3307 lck_mtx_unlock(buf_mtxp);
3308
3309 if (need_wakeup)
3310 wakeup(bp);
3311
3312 goto biodone_done;
3313 }
3314 /*
3315 * in this case the call back function is acting
3316 * strictly as a filter... it does not take
3317 * ownership of the bp and is expecting us
3318 * to finish cleaning up... this is currently used
3319 * by the HFS journaling code
3320 */
3321 }
3322 if (ISSET(bp->b_flags, B_ASYNC)) { /* if async, release it */
3323 SET(bp->b_flags, B_DONE); /* note that it's done */
3324
3325 buf_brelse(bp);
3326 } else { /* or just wakeup the buffer */
3327 /*
3328 * by taking the mutex, we serialize
3329 * the buf owner calling buf_biowait so that we'll
3330 * only see him in one of 2 states...
3331 * state 1: B_DONE wasn't set and he's
3332 * blocked in msleep
3333 * state 2: he's blocked trying to take the
3334 * mutex before looking at B_DONE
3335 * BL_WANTED is cleared in case anyone else
3336 * is blocked waiting for the buffer... note
3337 * that we haven't cleared B_BUSY yet, so if
3338 * they do get to run, their going to re-set
3339 * BL_WANTED and go back to sleep
3340 */
3341 lck_mtx_lock_spin(buf_mtxp);
3342
3343 CLR(bp->b_lflags, BL_WANTED);
3344 SET(bp->b_flags, B_DONE); /* note that it's done */
3345
3346 lck_mtx_unlock(buf_mtxp);
3347
3348 wakeup(bp);
3349 }
3350 biodone_done:
3351 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 387)) | DBG_FUNC_END,
3352 (uintptr_t)bp, (uintptr_t)bp->b_datap, bp->b_flags, 0, 0);
3353 }
3354
3355 /*
3356 * Return a count of buffers on the "locked" queue.
3357 */
3358 int
3359 count_lock_queue(void)
3360 {
3361 buf_t bp;
3362 int n = 0;
3363
3364 lck_mtx_lock_spin(buf_mtxp);
3365
3366 for (bp = bufqueues[BQ_LOCKED].tqh_first; bp;
3367 bp = bp->b_freelist.tqe_next)
3368 n++;
3369 lck_mtx_unlock(buf_mtxp);
3370
3371 return (n);
3372 }
3373
3374 /*
3375 * Return a count of 'busy' buffers. Used at the time of shutdown.
3376 */
3377 int
3378 count_busy_buffers(void)
3379 {
3380 return buf_busycount + bufstats.bufs_iobufinuse;
3381 }
3382
3383 #if DIAGNOSTIC
3384 /*
3385 * Print out statistics on the current allocation of the buffer pool.
3386 * Can be enabled to print out on every ``sync'' by setting "syncprt"
3387 * in vfs_syscalls.c using sysctl.
3388 */
3389 void
3390 vfs_bufstats()
3391 {
3392 int i, j, count;
3393 register struct buf *bp;
3394 register struct bqueues *dp;
3395 int counts[MAXBSIZE/CLBYTES+1];
3396 static char *bname[BQUEUES] =
3397 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
3398
3399 for (dp = bufqueues, i = 0; dp < &bufqueues[BQUEUES]; dp++, i++) {
3400 count = 0;
3401 for (j = 0; j <= MAXBSIZE/CLBYTES; j++)
3402 counts[j] = 0;
3403
3404 lck_mtx_lock(buf_mtxp);
3405
3406 for (bp = dp->tqh_first; bp; bp = bp->b_freelist.tqe_next) {
3407 counts[bp->b_bufsize/CLBYTES]++;
3408 count++;
3409 }
3410 lck_mtx_unlock(buf_mtxp);
3411
3412 printf("%s: total-%d", bname[i], count);
3413 for (j = 0; j <= MAXBSIZE/CLBYTES; j++)
3414 if (counts[j] != 0)
3415 printf(", %d-%d", j * CLBYTES, counts[j]);
3416 printf("\n");
3417 }
3418 }
3419 #endif /* DIAGNOSTIC */
3420
3421 #define NRESERVEDIOBUFS 64
3422
3423
3424 buf_t
3425 alloc_io_buf(vnode_t vp, int priv)
3426 {
3427 buf_t bp;
3428
3429 lck_mtx_lock_spin(iobuffer_mtxp);
3430
3431 while (((niobuf_headers - NRESERVEDIOBUFS < bufstats.bufs_iobufinuse) && !priv) ||
3432 (bp = iobufqueue.tqh_first) == NULL) {
3433 bufstats.bufs_iobufsleeps++;
3434
3435 need_iobuffer = 1;
3436 (void) msleep(&need_iobuffer, iobuffer_mtxp, PDROP | (PRIBIO+1), (const char *)"alloc_io_buf", NULL);
3437
3438 lck_mtx_lock_spin(iobuffer_mtxp);
3439 }
3440 TAILQ_REMOVE(&iobufqueue, bp, b_freelist);
3441
3442 bufstats.bufs_iobufinuse++;
3443 if (bufstats.bufs_iobufinuse > bufstats.bufs_iobufmax)
3444 bufstats.bufs_iobufmax = bufstats.bufs_iobufinuse;
3445
3446 lck_mtx_unlock(iobuffer_mtxp);
3447
3448 /*
3449 * initialize various fields
3450 * we don't need to hold the mutex since the buffer
3451 * is now private... the vp should have a reference
3452 * on it and is not protected by this mutex in any event
3453 */
3454 bp->b_timestamp = 0;
3455 bp->b_proc = NULL;
3456
3457 bp->b_datap = 0;
3458 bp->b_flags = 0;
3459 bp->b_lflags = BL_BUSY | BL_IOBUF;
3460 bp->b_blkno = bp->b_lblkno = 0;
3461 #ifdef JOE_DEBUG
3462 bp->b_owner = current_thread();
3463 bp->b_tag = 6;
3464 #endif
3465 bp->b_iodone = NULL;
3466 bp->b_error = 0;
3467 bp->b_resid = 0;
3468 bp->b_bcount = 0;
3469 bp->b_bufsize = 0;
3470 bp->b_upl = NULL;
3471 bp->b_vp = vp;
3472 #ifdef CONFIG_PROTECT
3473 bp->b_cpentry = 0;
3474 #endif
3475
3476 if (vp && (vp->v_type == VBLK || vp->v_type == VCHR))
3477 bp->b_dev = vp->v_rdev;
3478 else
3479 bp->b_dev = NODEV;
3480
3481 return (bp);
3482 }
3483
3484
3485 void
3486 free_io_buf(buf_t bp)
3487 {
3488 int need_wakeup = 0;
3489
3490 /*
3491 * put buffer back on the head of the iobufqueue
3492 */
3493 bp->b_vp = NULL;
3494 bp->b_flags = B_INVAL;
3495
3496 lck_mtx_lock_spin(iobuffer_mtxp);
3497
3498 binsheadfree(bp, &iobufqueue, -1);
3499
3500 if (need_iobuffer) {
3501 /*
3502 * Wake up any processes waiting because they need an io buffer
3503 *
3504 * do the wakeup after we drop the mutex... it's possible that the
3505 * wakeup will be superfluous if need_iobuffer gets set again and
3506 * another thread runs this path, but it's highly unlikely, doesn't
3507 * hurt, and it means we don't hold up I/O progress if the wakeup blocks
3508 * trying to grab a task related lock...
3509 */
3510 need_iobuffer = 0;
3511 need_wakeup = 1;
3512 }
3513 if (bufstats.bufs_iobufinuse <= 0)
3514 panic("free_io_buf: bp(%p) - bufstats.bufs_iobufinuse < 0", bp);
3515
3516 bufstats.bufs_iobufinuse--;
3517
3518 lck_mtx_unlock(iobuffer_mtxp);
3519
3520 if (need_wakeup)
3521 wakeup(&need_iobuffer);
3522 }
3523
3524
3525 void
3526 buf_list_lock(void)
3527 {
3528 lck_mtx_lock_spin(buf_mtxp);
3529 }
3530
3531 void
3532 buf_list_unlock(void)
3533 {
3534 lck_mtx_unlock(buf_mtxp);
3535 }
3536
3537 /*
3538 * If getnewbuf() calls bcleanbuf() on the same thread
3539 * there is a potential for stack overrun and deadlocks.
3540 * So we always handoff the work to a worker thread for completion
3541 */
3542
3543
3544 static void
3545 bcleanbuf_thread_init(void)
3546 {
3547 thread_t thread = THREAD_NULL;
3548
3549 /* create worker thread */
3550 kernel_thread_start((thread_continue_t)bcleanbuf_thread, NULL, &thread);
3551 thread_deallocate(thread);
3552 }
3553
3554 static void
3555 bcleanbuf_thread(void)
3556 {
3557 struct buf *bp;
3558 int error = 0;
3559 int loopcnt = 0;
3560
3561 for (;;) {
3562 lck_mtx_lock_spin(buf_mtxp);
3563
3564 while ( (bp = TAILQ_FIRST(&bufqueues[BQ_LAUNDRY])) == NULL) {
3565 (void)msleep((void *)&bufqueues[BQ_LAUNDRY], buf_mtxp, PDROP | PRIBIO, "blaundry", NULL);
3566
3567 lck_mtx_lock_spin(buf_mtxp);
3568 }
3569 /*
3570 * Remove from the queue
3571 */
3572 bremfree_locked(bp);
3573
3574 /*
3575 * Buffer is no longer on any free list
3576 */
3577 SET(bp->b_lflags, BL_BUSY);
3578 buf_busycount++;
3579
3580 #ifdef JOE_DEBUG
3581 bp->b_owner = current_thread();
3582 bp->b_tag = 10;
3583 #endif
3584
3585 lck_mtx_unlock(buf_mtxp);
3586 /*
3587 * do the IO
3588 */
3589 error = bawrite_internal(bp, 0);
3590
3591 if (error) {
3592 bp->b_whichq = BQ_LAUNDRY;
3593 bp->b_timestamp = buf_timestamp();
3594
3595 lck_mtx_lock_spin(buf_mtxp);
3596
3597 binstailfree(bp, &bufqueues[BQ_LAUNDRY], BQ_LAUNDRY);
3598 blaundrycnt++;
3599
3600 /* we never leave a busy page on the laundary queue */
3601 CLR(bp->b_lflags, BL_BUSY);
3602 buf_busycount--;
3603 #ifdef JOE_DEBUG
3604 bp->b_owner = current_thread();
3605 bp->b_tag = 11;
3606 #endif
3607
3608 lck_mtx_unlock(buf_mtxp);
3609
3610 if (loopcnt > 10) {
3611 (void)tsleep((void *)&bufqueues[BQ_LAUNDRY], PRIBIO, "blaundry", 1);
3612 loopcnt = 0;
3613 } else {
3614 (void)thread_block(THREAD_CONTINUE_NULL);
3615 loopcnt++;
3616 }
3617 }
3618 }
3619 }
3620
3621
3622 static int
3623 brecover_data(buf_t bp)
3624 {
3625 int upl_offset;
3626 upl_t upl;
3627 upl_page_info_t *pl;
3628 kern_return_t kret;
3629 vnode_t vp = bp->b_vp;
3630 int upl_flags;
3631
3632
3633 if ( !UBCINFOEXISTS(vp) || bp->b_bufsize == 0)
3634 goto dump_buffer;
3635
3636 upl_flags = UPL_PRECIOUS;
3637 if (! (buf_flags(bp) & B_READ)) {
3638 /*
3639 * "write" operation: let the UPL subsystem know
3640 * that we intend to modify the buffer cache pages we're
3641 * gathering.
3642 */
3643 upl_flags |= UPL_WILL_MODIFY;
3644 }
3645
3646 kret = ubc_create_upl(vp,
3647 ubc_blktooff(vp, bp->b_lblkno),
3648 bp->b_bufsize,
3649 &upl,
3650 &pl,
3651 upl_flags);
3652 if (kret != KERN_SUCCESS)
3653 panic("Failed to create UPL");
3654
3655 for (upl_offset = 0; upl_offset < bp->b_bufsize; upl_offset += PAGE_SIZE) {
3656
3657 if (!upl_valid_page(pl, upl_offset / PAGE_SIZE) || !upl_dirty_page(pl, upl_offset / PAGE_SIZE)) {
3658 ubc_upl_abort(upl, 0);
3659 goto dump_buffer;
3660 }
3661 }
3662 bp->b_upl = upl;
3663
3664 kret = ubc_upl_map(upl, (vm_offset_t *)&(bp->b_datap));
3665
3666 if (kret != KERN_SUCCESS)
3667 panic("getblk: ubc_upl_map() failed with (%d)", kret);
3668 return (1);
3669
3670 dump_buffer:
3671 bp->b_bufsize = 0;
3672 SET(bp->b_flags, B_INVAL);
3673 buf_brelse(bp);
3674
3675 return(0);
3676 }
3677
3678 boolean_t
3679 buffer_cache_gc(int all)
3680 {
3681 buf_t bp;
3682 boolean_t did_large_zfree = FALSE;
3683 int now = buf_timestamp();
3684 uint32_t count = 0;
3685 int thresh_hold = BUF_STALE_THRESHHOLD;
3686
3687 if (all)
3688 thresh_hold = 0;
3689
3690 lck_mtx_lock_spin(buf_mtxp);
3691
3692 /* We only care about metadata (incore storage comes from zalloc()) */
3693 bp = TAILQ_FIRST(&bufqueues[BQ_META]);
3694
3695 /* Only collect buffers unused in the last N seconds. Note: ordered by timestamp. */
3696 while ((bp != NULL) && ((now - bp->b_timestamp) > thresh_hold) && (all || (count < BUF_MAX_GC_COUNT))) {
3697 int result, size;
3698 boolean_t is_zalloc;
3699
3700 size = buf_size(bp);
3701 is_zalloc = ISSET(bp->b_flags, B_ZALLOC);
3702
3703 result = bcleanbuf(bp, TRUE);
3704 if ((result == 0) && is_zalloc && (size >= PAGE_SIZE)) {
3705 /* We've definitely freed at least a page to a zone */
3706 did_large_zfree = TRUE;
3707 }
3708 bp = TAILQ_FIRST(&bufqueues[BQ_META]);
3709 count++;
3710 }
3711
3712 lck_mtx_unlock(buf_mtxp);
3713
3714 return did_large_zfree;
3715 }
3716
3717
3718 /*
3719 * disabled for now
3720 */
3721
3722 #if FLUSH_QUEUES
3723
3724 #define NFLUSH 32
3725
3726 static int
3727 bp_cmp(void *a, void *b)
3728 {
3729 buf_t *bp_a = *(buf_t **)a,
3730 *bp_b = *(buf_t **)b;
3731 daddr64_t res;
3732
3733 // don't have to worry about negative block
3734 // numbers so this is ok to do.
3735 //
3736 res = (bp_a->b_blkno - bp_b->b_blkno);
3737
3738 return (int)res;
3739 }
3740
3741
3742 int
3743 bflushq(int whichq, mount_t mp)
3744 {
3745 buf_t bp, next;
3746 int i, buf_count;
3747 int total_writes = 0;
3748 static buf_t flush_table[NFLUSH];
3749
3750 if (whichq < 0 || whichq >= BQUEUES) {
3751 return (0);
3752 }
3753
3754 restart:
3755 lck_mtx_lock(buf_mtxp);
3756
3757 bp = TAILQ_FIRST(&bufqueues[whichq]);
3758
3759 for (buf_count = 0; bp; bp = next) {
3760 next = bp->b_freelist.tqe_next;
3761
3762 if (bp->b_vp == NULL || bp->b_vp->v_mount != mp) {
3763 continue;
3764 }
3765
3766 if (ISSET(bp->b_flags, B_DELWRI) && !ISSET(bp->b_lflags, BL_BUSY)) {
3767
3768 bremfree_locked(bp);
3769 #ifdef JOE_DEBUG
3770 bp->b_owner = current_thread();
3771 bp->b_tag = 7;
3772 #endif
3773 SET(bp->b_lflags, BL_BUSY);
3774 buf_busycount++;
3775
3776 flush_table[buf_count] = bp;
3777 buf_count++;
3778 total_writes++;
3779
3780 if (buf_count >= NFLUSH) {
3781 lck_mtx_unlock(buf_mtxp);
3782
3783 qsort(flush_table, buf_count, sizeof(struct buf *), bp_cmp);
3784
3785 for (i = 0; i < buf_count; i++) {
3786 buf_bawrite(flush_table[i]);
3787 }
3788 goto restart;
3789 }
3790 }
3791 }
3792 lck_mtx_unlock(buf_mtxp);
3793
3794 if (buf_count > 0) {
3795 qsort(flush_table, buf_count, sizeof(struct buf *), bp_cmp);
3796
3797 for (i = 0; i < buf_count; i++) {
3798 buf_bawrite(flush_table[i]);
3799 }
3800 }
3801
3802 return (total_writes);
3803 }
3804 #endif
3805
3806
3807 #if BALANCE_QUEUES
3808
3809 /* XXX move this to a separate file */
3810
3811 /*
3812 * NOTE: THIS CODE HAS NOT BEEN UPDATED
3813 * WITH RESPECT TO THE NEW LOCKING MODEL
3814 */
3815
3816
3817 /*
3818 * Dynamic Scaling of the Buffer Queues
3819 */
3820
3821 typedef long long blsize_t;
3822
3823 blsize_t MAXNBUF; /* initialize to (sane_size / PAGE_SIZE) */
3824 /* Global tunable limits */
3825 blsize_t nbufh; /* number of buffer headers */
3826 blsize_t nbuflow; /* minimum number of buffer headers required */
3827 blsize_t nbufhigh; /* maximum number of buffer headers allowed */
3828 blsize_t nbuftarget; /* preferred number of buffer headers */
3829
3830 /*
3831 * assertions:
3832 *
3833 * 1. 0 < nbuflow <= nbufh <= nbufhigh
3834 * 2. nbufhigh <= MAXNBUF
3835 * 3. 0 < nbuflow <= nbuftarget <= nbufhigh
3836 * 4. nbufh can not be set by sysctl().
3837 */
3838
3839 /* Per queue tunable limits */
3840
3841 struct bufqlim {
3842 blsize_t bl_nlow; /* minimum number of buffer headers required */
3843 blsize_t bl_num; /* number of buffer headers on the queue */
3844 blsize_t bl_nlhigh; /* maximum number of buffer headers allowed */
3845 blsize_t bl_target; /* preferred number of buffer headers */
3846 long bl_stale; /* Seconds after which a buffer is considered stale */
3847 } bufqlim[BQUEUES];
3848
3849 /*
3850 * assertions:
3851 *
3852 * 1. 0 <= bl_nlow <= bl_num <= bl_nlhigh
3853 * 2. bl_nlhigh <= MAXNBUF
3854 * 3. bufqlim[BQ_META].bl_nlow != 0
3855 * 4. bufqlim[BQ_META].bl_nlow > (number of possible concurrent
3856 * file system IO operations)
3857 * 5. bl_num can not be set by sysctl().
3858 * 6. bl_nhigh <= nbufhigh
3859 */
3860
3861 /*
3862 * Rationale:
3863 * ----------
3864 * Defining it blsize_t as long permits 2^31 buffer headers per queue.
3865 * Which can describe (2^31 * PAGE_SIZE) memory per queue.
3866 *
3867 * These limits are exported to by means of sysctl().
3868 * It was decided to define blsize_t as a 64 bit quantity.
3869 * This will make sure that we will not be required to change it
3870 * as long as we do not exceed 64 bit address space for the kernel.
3871 *
3872 * low and high numbers parameters initialized at compile time
3873 * and boot arguments can be used to override them. sysctl()
3874 * would not change the value. sysctl() can get all the values
3875 * but can set only target. num is the current level.
3876 *
3877 * Advantages of having a "bufqscan" thread doing the balancing are,
3878 * Keep enough bufs on BQ_EMPTY.
3879 * getnewbuf() by default will always select a buffer from the BQ_EMPTY.
3880 * getnewbuf() perfoms best if a buffer was found there.
3881 * Also this minimizes the possibility of starting IO
3882 * from getnewbuf(). That's a performance win, too.
3883 *
3884 * Localize complex logic [balancing as well as time aging]
3885 * to balancebufq().
3886 *
3887 * Simplify getnewbuf() logic by elimination of time aging code.
3888 */
3889
3890 /*
3891 * Algorithm:
3892 * -----------
3893 * The goal of the dynamic scaling of the buffer queues to to keep
3894 * the size of the LRU close to bl_target. Buffers on a queue would
3895 * be time aged.
3896 *
3897 * There would be a thread which will be responsible for "balancing"
3898 * the buffer cache queues.
3899 *
3900 * The scan order would be: AGE, LRU, META, EMPTY.
3901 */
3902
3903 long bufqscanwait = 0;
3904
3905 static void bufqscan_thread();
3906 static int balancebufq(int q);
3907 static int btrimempty(int n);
3908 static __inline__ int initbufqscan(void);
3909 static __inline__ int nextbufq(int q);
3910 static void buqlimprt(int all);
3911
3912
3913 static __inline__ void
3914 bufqinc(int q)
3915 {
3916 if ((q < 0) || (q >= BQUEUES))
3917 return;
3918
3919 bufqlim[q].bl_num++;
3920 return;
3921 }
3922
3923 static __inline__ void
3924 bufqdec(int q)
3925 {
3926 if ((q < 0) || (q >= BQUEUES))
3927 return;
3928
3929 bufqlim[q].bl_num--;
3930 return;
3931 }
3932
3933 static void
3934 bufq_balance_thread_init(void)
3935 {
3936 thread_t thread = THREAD_NULL;
3937
3938 if (bufqscanwait++ == 0) {
3939
3940 /* Initalize globals */
3941 MAXNBUF = (sane_size / PAGE_SIZE);
3942 nbufh = nbuf_headers;
3943 nbuflow = min(nbufh, 100);
3944 nbufhigh = min(MAXNBUF, max(nbufh, 2048));
3945 nbuftarget = (sane_size >> 5) / PAGE_SIZE;
3946 nbuftarget = max(nbuflow, nbuftarget);
3947 nbuftarget = min(nbufhigh, nbuftarget);
3948
3949 /*
3950 * Initialize the bufqlim
3951 */
3952
3953 /* LOCKED queue */
3954 bufqlim[BQ_LOCKED].bl_nlow = 0;
3955 bufqlim[BQ_LOCKED].bl_nlhigh = 32;
3956 bufqlim[BQ_LOCKED].bl_target = 0;
3957 bufqlim[BQ_LOCKED].bl_stale = 30;
3958
3959 /* LRU queue */
3960 bufqlim[BQ_LRU].bl_nlow = 0;
3961 bufqlim[BQ_LRU].bl_nlhigh = nbufhigh/4;
3962 bufqlim[BQ_LRU].bl_target = nbuftarget/4;
3963 bufqlim[BQ_LRU].bl_stale = LRU_IS_STALE;
3964
3965 /* AGE queue */
3966 bufqlim[BQ_AGE].bl_nlow = 0;
3967 bufqlim[BQ_AGE].bl_nlhigh = nbufhigh/4;
3968 bufqlim[BQ_AGE].bl_target = nbuftarget/4;
3969 bufqlim[BQ_AGE].bl_stale = AGE_IS_STALE;
3970
3971 /* EMPTY queue */
3972 bufqlim[BQ_EMPTY].bl_nlow = 0;
3973 bufqlim[BQ_EMPTY].bl_nlhigh = nbufhigh/4;
3974 bufqlim[BQ_EMPTY].bl_target = nbuftarget/4;
3975 bufqlim[BQ_EMPTY].bl_stale = 600000;
3976
3977 /* META queue */
3978 bufqlim[BQ_META].bl_nlow = 0;
3979 bufqlim[BQ_META].bl_nlhigh = nbufhigh/4;
3980 bufqlim[BQ_META].bl_target = nbuftarget/4;
3981 bufqlim[BQ_META].bl_stale = META_IS_STALE;
3982
3983 /* LAUNDRY queue */
3984 bufqlim[BQ_LOCKED].bl_nlow = 0;
3985 bufqlim[BQ_LOCKED].bl_nlhigh = 32;
3986 bufqlim[BQ_LOCKED].bl_target = 0;
3987 bufqlim[BQ_LOCKED].bl_stale = 30;
3988
3989 buqlimprt(1);
3990 }
3991
3992 /* create worker thread */
3993 kernel_thread_start((thread_continue_t)bufqscan_thread, NULL, &thread);
3994 thread_deallocate(thread);
3995 }
3996
3997 /* The workloop for the buffer balancing thread */
3998 static void
3999 bufqscan_thread()
4000 {
4001 int moretodo = 0;
4002
4003 for(;;) {
4004 do {
4005 int q; /* buffer queue to process */
4006
4007 q = initbufqscan();
4008 for (; q; ) {
4009 moretodo |= balancebufq(q);
4010 q = nextbufq(q);
4011 }
4012 } while (moretodo);
4013
4014 #if DIAGNOSTIC
4015 vfs_bufstats();
4016 buqlimprt(0);
4017 #endif
4018 (void)tsleep((void *)&bufqscanwait, PRIBIO, "bufqscanwait", 60 * hz);
4019 moretodo = 0;
4020 }
4021 }
4022
4023 /* Seed for the buffer queue balancing */
4024 static __inline__ int
4025 initbufqscan()
4026 {
4027 /* Start with AGE queue */
4028 return (BQ_AGE);
4029 }
4030
4031 /* Pick next buffer queue to balance */
4032 static __inline__ int
4033 nextbufq(int q)
4034 {
4035 int order[] = { BQ_AGE, BQ_LRU, BQ_META, BQ_EMPTY, 0 };
4036
4037 q++;
4038 q %= sizeof(order);
4039 return (order[q]);
4040 }
4041
4042 /* function to balance the buffer queues */
4043 static int
4044 balancebufq(int q)
4045 {
4046 int moretodo = 0;
4047 int n, t;
4048
4049 /* reject invalid q */
4050 if ((q < 0) || (q >= BQUEUES))
4051 goto out;
4052
4053 /* LOCKED or LAUNDRY queue MUST not be balanced */
4054 if ((q == BQ_LOCKED) || (q == BQ_LAUNDRY))
4055 goto out;
4056
4057 n = (bufqlim[q].bl_num - bufqlim[q].bl_target);
4058
4059 /* If queue has less than target nothing more to do */
4060 if (n < 0)
4061 goto out;
4062
4063 if ( n > 8 ) {
4064 /* Balance only a small amount (12.5%) at a time */
4065 n >>= 3;
4066 }
4067
4068 /* EMPTY queue needs special handling */
4069 if (q == BQ_EMPTY) {
4070 moretodo |= btrimempty(n);
4071 goto out;
4072 }
4073
4074 t = buf_timestamp():
4075
4076 for (; n > 0; n--) {
4077 struct buf *bp = bufqueues[q].tqh_first;
4078 if (!bp)
4079 break;
4080
4081 /* check if it's stale */
4082 if ((t - bp->b_timestamp) > bufqlim[q].bl_stale) {
4083 if (bcleanbuf(bp, FALSE)) {
4084 /* buf_bawrite() issued, bp not ready */
4085 moretodo = 1;
4086 } else {
4087 /* release the cleaned buffer to BQ_EMPTY */
4088 SET(bp->b_flags, B_INVAL);
4089 buf_brelse(bp);
4090 }
4091 } else
4092 break;
4093 }
4094
4095 out:
4096 return (moretodo);
4097 }
4098
4099 static int
4100 btrimempty(int n)
4101 {
4102 /*
4103 * When struct buf are allocated dynamically, this would
4104 * reclaim upto 'n' struct buf from the empty queue.
4105 */
4106
4107 return (0);
4108 }
4109
4110 static void
4111 buqlimprt(int all)
4112 {
4113 int i;
4114 static char *bname[BQUEUES] =
4115 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
4116
4117 if (all)
4118 for (i = 0; i < BQUEUES; i++) {
4119 printf("%s : ", bname[i]);
4120 printf("min = %ld, ", (long)bufqlim[i].bl_nlow);
4121 printf("cur = %ld, ", (long)bufqlim[i].bl_num);
4122 printf("max = %ld, ", (long)bufqlim[i].bl_nlhigh);
4123 printf("target = %ld, ", (long)bufqlim[i].bl_target);
4124 printf("stale after %ld seconds\n", bufqlim[i].bl_stale);
4125 }
4126 else
4127 for (i = 0; i < BQUEUES; i++) {
4128 printf("%s : ", bname[i]);
4129 printf("cur = %ld, ", (long)bufqlim[i].bl_num);
4130 }
4131 }
4132
4133 #endif
4134
4135