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