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