xref: /freebsd/sys/contrib/openzfs/module/zfs/zio.c (revision 87b759f0fa1f7554d50ce640c40138512bbded44)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or https://opensource.org/licenses/CDDL-1.0.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 2011, 2022 by Delphix. All rights reserved.
24  * Copyright (c) 2011 Nexenta Systems, Inc. All rights reserved.
25  * Copyright (c) 2017, Intel Corporation.
26  * Copyright (c) 2019, 2023, 2024, Klara Inc.
27  * Copyright (c) 2019, Allan Jude
28  * Copyright (c) 2021, Datto, Inc.
29  * Copyright (c) 2021, 2024 by George Melikov. All rights reserved.
30  */
31 
32 #include <sys/sysmacros.h>
33 #include <sys/zfs_context.h>
34 #include <sys/fm/fs/zfs.h>
35 #include <sys/spa.h>
36 #include <sys/txg.h>
37 #include <sys/spa_impl.h>
38 #include <sys/vdev_impl.h>
39 #include <sys/vdev_trim.h>
40 #include <sys/zio_impl.h>
41 #include <sys/zio_compress.h>
42 #include <sys/zio_checksum.h>
43 #include <sys/dmu_objset.h>
44 #include <sys/arc.h>
45 #include <sys/brt.h>
46 #include <sys/ddt.h>
47 #include <sys/blkptr.h>
48 #include <sys/zfeature.h>
49 #include <sys/dsl_scan.h>
50 #include <sys/metaslab_impl.h>
51 #include <sys/time.h>
52 #include <sys/trace_zfs.h>
53 #include <sys/abd.h>
54 #include <sys/dsl_crypt.h>
55 #include <cityhash.h>
56 
57 /*
58  * ==========================================================================
59  * I/O type descriptions
60  * ==========================================================================
61  */
62 const char *const zio_type_name[ZIO_TYPES] = {
63 	/*
64 	 * Note: Linux kernel thread name length is limited
65 	 * so these names will differ from upstream open zfs.
66 	 */
67 	"z_null", "z_rd", "z_wr", "z_fr", "z_cl", "z_flush", "z_trim"
68 };
69 
70 int zio_dva_throttle_enabled = B_TRUE;
71 static int zio_deadman_log_all = B_FALSE;
72 
73 /*
74  * ==========================================================================
75  * I/O kmem caches
76  * ==========================================================================
77  */
78 static kmem_cache_t *zio_cache;
79 static kmem_cache_t *zio_link_cache;
80 kmem_cache_t *zio_buf_cache[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT];
81 kmem_cache_t *zio_data_buf_cache[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT];
82 #if defined(ZFS_DEBUG) && !defined(_KERNEL)
83 static uint64_t zio_buf_cache_allocs[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT];
84 static uint64_t zio_buf_cache_frees[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT];
85 #endif
86 
87 /* Mark IOs as "slow" if they take longer than 30 seconds */
88 static uint_t zio_slow_io_ms = (30 * MILLISEC);
89 
90 #define	BP_SPANB(indblkshift, level) \
91 	(((uint64_t)1) << ((level) * ((indblkshift) - SPA_BLKPTRSHIFT)))
92 #define	COMPARE_META_LEVEL	0x80000000ul
93 /*
94  * The following actions directly effect the spa's sync-to-convergence logic.
95  * The values below define the sync pass when we start performing the action.
96  * Care should be taken when changing these values as they directly impact
97  * spa_sync() performance. Tuning these values may introduce subtle performance
98  * pathologies and should only be done in the context of performance analysis.
99  * These tunables will eventually be removed and replaced with #defines once
100  * enough analysis has been done to determine optimal values.
101  *
102  * The 'zfs_sync_pass_deferred_free' pass must be greater than 1 to ensure that
103  * regular blocks are not deferred.
104  *
105  * Starting in sync pass 8 (zfs_sync_pass_dont_compress), we disable
106  * compression (including of metadata).  In practice, we don't have this
107  * many sync passes, so this has no effect.
108  *
109  * The original intent was that disabling compression would help the sync
110  * passes to converge. However, in practice disabling compression increases
111  * the average number of sync passes, because when we turn compression off, a
112  * lot of block's size will change and thus we have to re-allocate (not
113  * overwrite) them. It also increases the number of 128KB allocations (e.g.
114  * for indirect blocks and spacemaps) because these will not be compressed.
115  * The 128K allocations are especially detrimental to performance on highly
116  * fragmented systems, which may have very few free segments of this size,
117  * and may need to load new metaslabs to satisfy 128K allocations.
118  */
119 
120 /* defer frees starting in this pass */
121 uint_t zfs_sync_pass_deferred_free = 2;
122 
123 /* don't compress starting in this pass */
124 static uint_t zfs_sync_pass_dont_compress = 8;
125 
126 /* rewrite new bps starting in this pass */
127 static uint_t zfs_sync_pass_rewrite = 2;
128 
129 /*
130  * An allocating zio is one that either currently has the DVA allocate
131  * stage set or will have it later in its lifetime.
132  */
133 #define	IO_IS_ALLOCATING(zio) ((zio)->io_orig_pipeline & ZIO_STAGE_DVA_ALLOCATE)
134 
135 /*
136  * Enable smaller cores by excluding metadata
137  * allocations as well.
138  */
139 int zio_exclude_metadata = 0;
140 static int zio_requeue_io_start_cut_in_line = 1;
141 
142 #ifdef ZFS_DEBUG
143 static const int zio_buf_debug_limit = 16384;
144 #else
145 static const int zio_buf_debug_limit = 0;
146 #endif
147 
148 static inline void __zio_execute(zio_t *zio);
149 
150 static void zio_taskq_dispatch(zio_t *, zio_taskq_type_t, boolean_t);
151 
152 void
153 zio_init(void)
154 {
155 	size_t c;
156 
157 	zio_cache = kmem_cache_create("zio_cache",
158 	    sizeof (zio_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
159 	zio_link_cache = kmem_cache_create("zio_link_cache",
160 	    sizeof (zio_link_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
161 
162 	for (c = 0; c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; c++) {
163 		size_t size = (c + 1) << SPA_MINBLOCKSHIFT;
164 		size_t align, cflags, data_cflags;
165 		char name[32];
166 
167 		/*
168 		 * Create cache for each half-power of 2 size, starting from
169 		 * SPA_MINBLOCKSIZE.  It should give us memory space efficiency
170 		 * of ~7/8, sufficient for transient allocations mostly using
171 		 * these caches.
172 		 */
173 		size_t p2 = size;
174 		while (!ISP2(p2))
175 			p2 &= p2 - 1;
176 		if (!IS_P2ALIGNED(size, p2 / 2))
177 			continue;
178 
179 #ifndef _KERNEL
180 		/*
181 		 * If we are using watchpoints, put each buffer on its own page,
182 		 * to eliminate the performance overhead of trapping to the
183 		 * kernel when modifying a non-watched buffer that shares the
184 		 * page with a watched buffer.
185 		 */
186 		if (arc_watch && !IS_P2ALIGNED(size, PAGESIZE))
187 			continue;
188 #endif
189 
190 		if (IS_P2ALIGNED(size, PAGESIZE))
191 			align = PAGESIZE;
192 		else
193 			align = 1 << (highbit64(size ^ (size - 1)) - 1);
194 
195 		cflags = (zio_exclude_metadata || size > zio_buf_debug_limit) ?
196 		    KMC_NODEBUG : 0;
197 		data_cflags = KMC_NODEBUG;
198 		if (abd_size_alloc_linear(size)) {
199 			cflags |= KMC_RECLAIMABLE;
200 			data_cflags |= KMC_RECLAIMABLE;
201 		}
202 		if (cflags == data_cflags) {
203 			/*
204 			 * Resulting kmem caches would be identical.
205 			 * Save memory by creating only one.
206 			 */
207 			(void) snprintf(name, sizeof (name),
208 			    "zio_buf_comb_%lu", (ulong_t)size);
209 			zio_buf_cache[c] = kmem_cache_create(name, size, align,
210 			    NULL, NULL, NULL, NULL, NULL, cflags);
211 			zio_data_buf_cache[c] = zio_buf_cache[c];
212 			continue;
213 		}
214 		(void) snprintf(name, sizeof (name), "zio_buf_%lu",
215 		    (ulong_t)size);
216 		zio_buf_cache[c] = kmem_cache_create(name, size, align,
217 		    NULL, NULL, NULL, NULL, NULL, cflags);
218 
219 		(void) snprintf(name, sizeof (name), "zio_data_buf_%lu",
220 		    (ulong_t)size);
221 		zio_data_buf_cache[c] = kmem_cache_create(name, size, align,
222 		    NULL, NULL, NULL, NULL, NULL, data_cflags);
223 	}
224 
225 	while (--c != 0) {
226 		ASSERT(zio_buf_cache[c] != NULL);
227 		if (zio_buf_cache[c - 1] == NULL)
228 			zio_buf_cache[c - 1] = zio_buf_cache[c];
229 
230 		ASSERT(zio_data_buf_cache[c] != NULL);
231 		if (zio_data_buf_cache[c - 1] == NULL)
232 			zio_data_buf_cache[c - 1] = zio_data_buf_cache[c];
233 	}
234 
235 	zio_inject_init();
236 
237 	lz4_init();
238 }
239 
240 void
241 zio_fini(void)
242 {
243 	size_t n = SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT;
244 
245 #if defined(ZFS_DEBUG) && !defined(_KERNEL)
246 	for (size_t i = 0; i < n; i++) {
247 		if (zio_buf_cache_allocs[i] != zio_buf_cache_frees[i])
248 			(void) printf("zio_fini: [%d] %llu != %llu\n",
249 			    (int)((i + 1) << SPA_MINBLOCKSHIFT),
250 			    (long long unsigned)zio_buf_cache_allocs[i],
251 			    (long long unsigned)zio_buf_cache_frees[i]);
252 	}
253 #endif
254 
255 	/*
256 	 * The same kmem cache can show up multiple times in both zio_buf_cache
257 	 * and zio_data_buf_cache. Do a wasteful but trivially correct scan to
258 	 * sort it out.
259 	 */
260 	for (size_t i = 0; i < n; i++) {
261 		kmem_cache_t *cache = zio_buf_cache[i];
262 		if (cache == NULL)
263 			continue;
264 		for (size_t j = i; j < n; j++) {
265 			if (cache == zio_buf_cache[j])
266 				zio_buf_cache[j] = NULL;
267 			if (cache == zio_data_buf_cache[j])
268 				zio_data_buf_cache[j] = NULL;
269 		}
270 		kmem_cache_destroy(cache);
271 	}
272 
273 	for (size_t i = 0; i < n; i++) {
274 		kmem_cache_t *cache = zio_data_buf_cache[i];
275 		if (cache == NULL)
276 			continue;
277 		for (size_t j = i; j < n; j++) {
278 			if (cache == zio_data_buf_cache[j])
279 				zio_data_buf_cache[j] = NULL;
280 		}
281 		kmem_cache_destroy(cache);
282 	}
283 
284 	for (size_t i = 0; i < n; i++) {
285 		VERIFY3P(zio_buf_cache[i], ==, NULL);
286 		VERIFY3P(zio_data_buf_cache[i], ==, NULL);
287 	}
288 
289 	kmem_cache_destroy(zio_link_cache);
290 	kmem_cache_destroy(zio_cache);
291 
292 	zio_inject_fini();
293 
294 	lz4_fini();
295 }
296 
297 /*
298  * ==========================================================================
299  * Allocate and free I/O buffers
300  * ==========================================================================
301  */
302 
303 #if defined(ZFS_DEBUG) && defined(_KERNEL)
304 #define	ZFS_ZIO_BUF_CANARY	1
305 #endif
306 
307 #ifdef ZFS_ZIO_BUF_CANARY
308 static const ulong_t zio_buf_canary = (ulong_t)0xdeadc0dedead210b;
309 
310 /*
311  * Use empty space after the buffer to detect overflows.
312  *
313  * Since zio_init() creates kmem caches only for certain set of buffer sizes,
314  * allocations of different sizes may have some unused space after the data.
315  * Filling part of that space with a known pattern on allocation and checking
316  * it on free should allow us to detect some buffer overflows.
317  */
318 static void
319 zio_buf_put_canary(ulong_t *p, size_t size, kmem_cache_t **cache, size_t c)
320 {
321 	size_t off = P2ROUNDUP(size, sizeof (ulong_t));
322 	ulong_t *canary = p + off / sizeof (ulong_t);
323 	size_t asize = (c + 1) << SPA_MINBLOCKSHIFT;
324 	if (c + 1 < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT &&
325 	    cache[c] == cache[c + 1])
326 		asize = (c + 2) << SPA_MINBLOCKSHIFT;
327 	for (; off < asize; canary++, off += sizeof (ulong_t))
328 		*canary = zio_buf_canary;
329 }
330 
331 static void
332 zio_buf_check_canary(ulong_t *p, size_t size, kmem_cache_t **cache, size_t c)
333 {
334 	size_t off = P2ROUNDUP(size, sizeof (ulong_t));
335 	ulong_t *canary = p + off / sizeof (ulong_t);
336 	size_t asize = (c + 1) << SPA_MINBLOCKSHIFT;
337 	if (c + 1 < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT &&
338 	    cache[c] == cache[c + 1])
339 		asize = (c + 2) << SPA_MINBLOCKSHIFT;
340 	for (; off < asize; canary++, off += sizeof (ulong_t)) {
341 		if (unlikely(*canary != zio_buf_canary)) {
342 			PANIC("ZIO buffer overflow %p (%zu) + %zu %#lx != %#lx",
343 			    p, size, (canary - p) * sizeof (ulong_t),
344 			    *canary, zio_buf_canary);
345 		}
346 	}
347 }
348 #endif
349 
350 /*
351  * Use zio_buf_alloc to allocate ZFS metadata.  This data will appear in a
352  * crashdump if the kernel panics, so use it judiciously.  Obviously, it's
353  * useful to inspect ZFS metadata, but if possible, we should avoid keeping
354  * excess / transient data in-core during a crashdump.
355  */
356 void *
357 zio_buf_alloc(size_t size)
358 {
359 	size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
360 
361 	VERIFY3U(c, <, SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
362 #if defined(ZFS_DEBUG) && !defined(_KERNEL)
363 	atomic_add_64(&zio_buf_cache_allocs[c], 1);
364 #endif
365 
366 	void *p = kmem_cache_alloc(zio_buf_cache[c], KM_PUSHPAGE);
367 #ifdef ZFS_ZIO_BUF_CANARY
368 	zio_buf_put_canary(p, size, zio_buf_cache, c);
369 #endif
370 	return (p);
371 }
372 
373 /*
374  * Use zio_data_buf_alloc to allocate data.  The data will not appear in a
375  * crashdump if the kernel panics.  This exists so that we will limit the amount
376  * of ZFS data that shows up in a kernel crashdump.  (Thus reducing the amount
377  * of kernel heap dumped to disk when the kernel panics)
378  */
379 void *
380 zio_data_buf_alloc(size_t size)
381 {
382 	size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
383 
384 	VERIFY3U(c, <, SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
385 
386 	void *p = kmem_cache_alloc(zio_data_buf_cache[c], KM_PUSHPAGE);
387 #ifdef ZFS_ZIO_BUF_CANARY
388 	zio_buf_put_canary(p, size, zio_data_buf_cache, c);
389 #endif
390 	return (p);
391 }
392 
393 void
394 zio_buf_free(void *buf, size_t size)
395 {
396 	size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
397 
398 	VERIFY3U(c, <, SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
399 #if defined(ZFS_DEBUG) && !defined(_KERNEL)
400 	atomic_add_64(&zio_buf_cache_frees[c], 1);
401 #endif
402 
403 #ifdef ZFS_ZIO_BUF_CANARY
404 	zio_buf_check_canary(buf, size, zio_buf_cache, c);
405 #endif
406 	kmem_cache_free(zio_buf_cache[c], buf);
407 }
408 
409 void
410 zio_data_buf_free(void *buf, size_t size)
411 {
412 	size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
413 
414 	VERIFY3U(c, <, SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
415 
416 #ifdef ZFS_ZIO_BUF_CANARY
417 	zio_buf_check_canary(buf, size, zio_data_buf_cache, c);
418 #endif
419 	kmem_cache_free(zio_data_buf_cache[c], buf);
420 }
421 
422 static void
423 zio_abd_free(void *abd, size_t size)
424 {
425 	(void) size;
426 	abd_free((abd_t *)abd);
427 }
428 
429 /*
430  * ==========================================================================
431  * Push and pop I/O transform buffers
432  * ==========================================================================
433  */
434 void
435 zio_push_transform(zio_t *zio, abd_t *data, uint64_t size, uint64_t bufsize,
436     zio_transform_func_t *transform)
437 {
438 	zio_transform_t *zt = kmem_alloc(sizeof (zio_transform_t), KM_SLEEP);
439 
440 	zt->zt_orig_abd = zio->io_abd;
441 	zt->zt_orig_size = zio->io_size;
442 	zt->zt_bufsize = bufsize;
443 	zt->zt_transform = transform;
444 
445 	zt->zt_next = zio->io_transform_stack;
446 	zio->io_transform_stack = zt;
447 
448 	zio->io_abd = data;
449 	zio->io_size = size;
450 }
451 
452 void
453 zio_pop_transforms(zio_t *zio)
454 {
455 	zio_transform_t *zt;
456 
457 	while ((zt = zio->io_transform_stack) != NULL) {
458 		if (zt->zt_transform != NULL)
459 			zt->zt_transform(zio,
460 			    zt->zt_orig_abd, zt->zt_orig_size);
461 
462 		if (zt->zt_bufsize != 0)
463 			abd_free(zio->io_abd);
464 
465 		zio->io_abd = zt->zt_orig_abd;
466 		zio->io_size = zt->zt_orig_size;
467 		zio->io_transform_stack = zt->zt_next;
468 
469 		kmem_free(zt, sizeof (zio_transform_t));
470 	}
471 }
472 
473 /*
474  * ==========================================================================
475  * I/O transform callbacks for subblocks, decompression, and decryption
476  * ==========================================================================
477  */
478 static void
479 zio_subblock(zio_t *zio, abd_t *data, uint64_t size)
480 {
481 	ASSERT(zio->io_size > size);
482 
483 	if (zio->io_type == ZIO_TYPE_READ)
484 		abd_copy(data, zio->io_abd, size);
485 }
486 
487 static void
488 zio_decompress(zio_t *zio, abd_t *data, uint64_t size)
489 {
490 	if (zio->io_error == 0) {
491 		int ret = zio_decompress_data(BP_GET_COMPRESS(zio->io_bp),
492 		    zio->io_abd, data, zio->io_size, size,
493 		    &zio->io_prop.zp_complevel);
494 
495 		if (zio_injection_enabled && ret == 0)
496 			ret = zio_handle_fault_injection(zio, EINVAL);
497 
498 		if (ret != 0)
499 			zio->io_error = SET_ERROR(EIO);
500 	}
501 }
502 
503 static void
504 zio_decrypt(zio_t *zio, abd_t *data, uint64_t size)
505 {
506 	int ret;
507 	void *tmp;
508 	blkptr_t *bp = zio->io_bp;
509 	spa_t *spa = zio->io_spa;
510 	uint64_t dsobj = zio->io_bookmark.zb_objset;
511 	uint64_t lsize = BP_GET_LSIZE(bp);
512 	dmu_object_type_t ot = BP_GET_TYPE(bp);
513 	uint8_t salt[ZIO_DATA_SALT_LEN];
514 	uint8_t iv[ZIO_DATA_IV_LEN];
515 	uint8_t mac[ZIO_DATA_MAC_LEN];
516 	boolean_t no_crypt = B_FALSE;
517 
518 	ASSERT(BP_USES_CRYPT(bp));
519 	ASSERT3U(size, !=, 0);
520 
521 	if (zio->io_error != 0)
522 		return;
523 
524 	/*
525 	 * Verify the cksum of MACs stored in an indirect bp. It will always
526 	 * be possible to verify this since it does not require an encryption
527 	 * key.
528 	 */
529 	if (BP_HAS_INDIRECT_MAC_CKSUM(bp)) {
530 		zio_crypt_decode_mac_bp(bp, mac);
531 
532 		if (BP_GET_COMPRESS(bp) != ZIO_COMPRESS_OFF) {
533 			/*
534 			 * We haven't decompressed the data yet, but
535 			 * zio_crypt_do_indirect_mac_checksum() requires
536 			 * decompressed data to be able to parse out the MACs
537 			 * from the indirect block. We decompress it now and
538 			 * throw away the result after we are finished.
539 			 */
540 			abd_t *abd = abd_alloc_linear(lsize, B_TRUE);
541 			ret = zio_decompress_data(BP_GET_COMPRESS(bp),
542 			    zio->io_abd, abd, zio->io_size, lsize,
543 			    &zio->io_prop.zp_complevel);
544 			if (ret != 0) {
545 				abd_free(abd);
546 				ret = SET_ERROR(EIO);
547 				goto error;
548 			}
549 			ret = zio_crypt_do_indirect_mac_checksum_abd(B_FALSE,
550 			    abd, lsize, BP_SHOULD_BYTESWAP(bp), mac);
551 			abd_free(abd);
552 		} else {
553 			ret = zio_crypt_do_indirect_mac_checksum_abd(B_FALSE,
554 			    zio->io_abd, size, BP_SHOULD_BYTESWAP(bp), mac);
555 		}
556 		abd_copy(data, zio->io_abd, size);
557 
558 		if (zio_injection_enabled && ot != DMU_OT_DNODE && ret == 0) {
559 			ret = zio_handle_decrypt_injection(spa,
560 			    &zio->io_bookmark, ot, ECKSUM);
561 		}
562 		if (ret != 0)
563 			goto error;
564 
565 		return;
566 	}
567 
568 	/*
569 	 * If this is an authenticated block, just check the MAC. It would be
570 	 * nice to separate this out into its own flag, but when this was done,
571 	 * we had run out of bits in what is now zio_flag_t. Future cleanup
572 	 * could make this a flag bit.
573 	 */
574 	if (BP_IS_AUTHENTICATED(bp)) {
575 		if (ot == DMU_OT_OBJSET) {
576 			ret = spa_do_crypt_objset_mac_abd(B_FALSE, spa,
577 			    dsobj, zio->io_abd, size, BP_SHOULD_BYTESWAP(bp));
578 		} else {
579 			zio_crypt_decode_mac_bp(bp, mac);
580 			ret = spa_do_crypt_mac_abd(B_FALSE, spa, dsobj,
581 			    zio->io_abd, size, mac);
582 			if (zio_injection_enabled && ret == 0) {
583 				ret = zio_handle_decrypt_injection(spa,
584 				    &zio->io_bookmark, ot, ECKSUM);
585 			}
586 		}
587 		abd_copy(data, zio->io_abd, size);
588 
589 		if (ret != 0)
590 			goto error;
591 
592 		return;
593 	}
594 
595 	zio_crypt_decode_params_bp(bp, salt, iv);
596 
597 	if (ot == DMU_OT_INTENT_LOG) {
598 		tmp = abd_borrow_buf_copy(zio->io_abd, sizeof (zil_chain_t));
599 		zio_crypt_decode_mac_zil(tmp, mac);
600 		abd_return_buf(zio->io_abd, tmp, sizeof (zil_chain_t));
601 	} else {
602 		zio_crypt_decode_mac_bp(bp, mac);
603 	}
604 
605 	ret = spa_do_crypt_abd(B_FALSE, spa, &zio->io_bookmark, BP_GET_TYPE(bp),
606 	    BP_GET_DEDUP(bp), BP_SHOULD_BYTESWAP(bp), salt, iv, mac, size, data,
607 	    zio->io_abd, &no_crypt);
608 	if (no_crypt)
609 		abd_copy(data, zio->io_abd, size);
610 
611 	if (ret != 0)
612 		goto error;
613 
614 	return;
615 
616 error:
617 	/* assert that the key was found unless this was speculative */
618 	ASSERT(ret != EACCES || (zio->io_flags & ZIO_FLAG_SPECULATIVE));
619 
620 	/*
621 	 * If there was a decryption / authentication error return EIO as
622 	 * the io_error. If this was not a speculative zio, create an ereport.
623 	 */
624 	if (ret == ECKSUM) {
625 		zio->io_error = SET_ERROR(EIO);
626 		if ((zio->io_flags & ZIO_FLAG_SPECULATIVE) == 0) {
627 			spa_log_error(spa, &zio->io_bookmark,
628 			    BP_GET_LOGICAL_BIRTH(zio->io_bp));
629 			(void) zfs_ereport_post(FM_EREPORT_ZFS_AUTHENTICATION,
630 			    spa, NULL, &zio->io_bookmark, zio, 0);
631 		}
632 	} else {
633 		zio->io_error = ret;
634 	}
635 }
636 
637 /*
638  * ==========================================================================
639  * I/O parent/child relationships and pipeline interlocks
640  * ==========================================================================
641  */
642 zio_t *
643 zio_walk_parents(zio_t *cio, zio_link_t **zl)
644 {
645 	list_t *pl = &cio->io_parent_list;
646 
647 	*zl = (*zl == NULL) ? list_head(pl) : list_next(pl, *zl);
648 	if (*zl == NULL)
649 		return (NULL);
650 
651 	ASSERT((*zl)->zl_child == cio);
652 	return ((*zl)->zl_parent);
653 }
654 
655 zio_t *
656 zio_walk_children(zio_t *pio, zio_link_t **zl)
657 {
658 	list_t *cl = &pio->io_child_list;
659 
660 	ASSERT(MUTEX_HELD(&pio->io_lock));
661 
662 	*zl = (*zl == NULL) ? list_head(cl) : list_next(cl, *zl);
663 	if (*zl == NULL)
664 		return (NULL);
665 
666 	ASSERT((*zl)->zl_parent == pio);
667 	return ((*zl)->zl_child);
668 }
669 
670 zio_t *
671 zio_unique_parent(zio_t *cio)
672 {
673 	zio_link_t *zl = NULL;
674 	zio_t *pio = zio_walk_parents(cio, &zl);
675 
676 	VERIFY3P(zio_walk_parents(cio, &zl), ==, NULL);
677 	return (pio);
678 }
679 
680 void
681 zio_add_child(zio_t *pio, zio_t *cio)
682 {
683 	/*
684 	 * Logical I/Os can have logical, gang, or vdev children.
685 	 * Gang I/Os can have gang or vdev children.
686 	 * Vdev I/Os can only have vdev children.
687 	 * The following ASSERT captures all of these constraints.
688 	 */
689 	ASSERT3S(cio->io_child_type, <=, pio->io_child_type);
690 
691 	/* Parent should not have READY stage if child doesn't have it. */
692 	IMPLY((cio->io_pipeline & ZIO_STAGE_READY) == 0 &&
693 	    (cio->io_child_type != ZIO_CHILD_VDEV),
694 	    (pio->io_pipeline & ZIO_STAGE_READY) == 0);
695 
696 	zio_link_t *zl = kmem_cache_alloc(zio_link_cache, KM_SLEEP);
697 	zl->zl_parent = pio;
698 	zl->zl_child = cio;
699 
700 	mutex_enter(&pio->io_lock);
701 	mutex_enter(&cio->io_lock);
702 
703 	ASSERT(pio->io_state[ZIO_WAIT_DONE] == 0);
704 
705 	uint64_t *countp = pio->io_children[cio->io_child_type];
706 	for (int w = 0; w < ZIO_WAIT_TYPES; w++)
707 		countp[w] += !cio->io_state[w];
708 
709 	list_insert_head(&pio->io_child_list, zl);
710 	list_insert_head(&cio->io_parent_list, zl);
711 
712 	mutex_exit(&cio->io_lock);
713 	mutex_exit(&pio->io_lock);
714 }
715 
716 void
717 zio_add_child_first(zio_t *pio, zio_t *cio)
718 {
719 	/*
720 	 * Logical I/Os can have logical, gang, or vdev children.
721 	 * Gang I/Os can have gang or vdev children.
722 	 * Vdev I/Os can only have vdev children.
723 	 * The following ASSERT captures all of these constraints.
724 	 */
725 	ASSERT3S(cio->io_child_type, <=, pio->io_child_type);
726 
727 	/* Parent should not have READY stage if child doesn't have it. */
728 	IMPLY((cio->io_pipeline & ZIO_STAGE_READY) == 0 &&
729 	    (cio->io_child_type != ZIO_CHILD_VDEV),
730 	    (pio->io_pipeline & ZIO_STAGE_READY) == 0);
731 
732 	zio_link_t *zl = kmem_cache_alloc(zio_link_cache, KM_SLEEP);
733 	zl->zl_parent = pio;
734 	zl->zl_child = cio;
735 
736 	ASSERT(list_is_empty(&cio->io_parent_list));
737 	list_insert_head(&cio->io_parent_list, zl);
738 
739 	mutex_enter(&pio->io_lock);
740 
741 	ASSERT(pio->io_state[ZIO_WAIT_DONE] == 0);
742 
743 	uint64_t *countp = pio->io_children[cio->io_child_type];
744 	for (int w = 0; w < ZIO_WAIT_TYPES; w++)
745 		countp[w] += !cio->io_state[w];
746 
747 	list_insert_head(&pio->io_child_list, zl);
748 
749 	mutex_exit(&pio->io_lock);
750 }
751 
752 static void
753 zio_remove_child(zio_t *pio, zio_t *cio, zio_link_t *zl)
754 {
755 	ASSERT(zl->zl_parent == pio);
756 	ASSERT(zl->zl_child == cio);
757 
758 	mutex_enter(&pio->io_lock);
759 	mutex_enter(&cio->io_lock);
760 
761 	list_remove(&pio->io_child_list, zl);
762 	list_remove(&cio->io_parent_list, zl);
763 
764 	mutex_exit(&cio->io_lock);
765 	mutex_exit(&pio->io_lock);
766 	kmem_cache_free(zio_link_cache, zl);
767 }
768 
769 static boolean_t
770 zio_wait_for_children(zio_t *zio, uint8_t childbits, enum zio_wait_type wait)
771 {
772 	boolean_t waiting = B_FALSE;
773 
774 	mutex_enter(&zio->io_lock);
775 	ASSERT(zio->io_stall == NULL);
776 	for (int c = 0; c < ZIO_CHILD_TYPES; c++) {
777 		if (!(ZIO_CHILD_BIT_IS_SET(childbits, c)))
778 			continue;
779 
780 		uint64_t *countp = &zio->io_children[c][wait];
781 		if (*countp != 0) {
782 			zio->io_stage >>= 1;
783 			ASSERT3U(zio->io_stage, !=, ZIO_STAGE_OPEN);
784 			zio->io_stall = countp;
785 			waiting = B_TRUE;
786 			break;
787 		}
788 	}
789 	mutex_exit(&zio->io_lock);
790 	return (waiting);
791 }
792 
793 __attribute__((always_inline))
794 static inline void
795 zio_notify_parent(zio_t *pio, zio_t *zio, enum zio_wait_type wait,
796     zio_t **next_to_executep)
797 {
798 	uint64_t *countp = &pio->io_children[zio->io_child_type][wait];
799 	int *errorp = &pio->io_child_error[zio->io_child_type];
800 
801 	mutex_enter(&pio->io_lock);
802 	if (zio->io_error && !(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE))
803 		*errorp = zio_worst_error(*errorp, zio->io_error);
804 	pio->io_reexecute |= zio->io_reexecute;
805 	ASSERT3U(*countp, >, 0);
806 
807 	if (zio->io_flags & ZIO_FLAG_DIO_CHKSUM_ERR) {
808 		ASSERT3U(*errorp, ==, EIO);
809 		ASSERT3U(pio->io_child_type, ==, ZIO_CHILD_LOGICAL);
810 		pio->io_flags |= ZIO_FLAG_DIO_CHKSUM_ERR;
811 	}
812 
813 	(*countp)--;
814 
815 	if (*countp == 0 && pio->io_stall == countp) {
816 		zio_taskq_type_t type =
817 		    pio->io_stage < ZIO_STAGE_VDEV_IO_START ? ZIO_TASKQ_ISSUE :
818 		    ZIO_TASKQ_INTERRUPT;
819 		pio->io_stall = NULL;
820 		mutex_exit(&pio->io_lock);
821 
822 		/*
823 		 * If we can tell the caller to execute this parent next, do
824 		 * so. We do this if the parent's zio type matches the child's
825 		 * type, or if it's a zio_null() with no done callback, and so
826 		 * has no actual work to do. Otherwise dispatch the parent zio
827 		 * in its own taskq.
828 		 *
829 		 * Having the caller execute the parent when possible reduces
830 		 * locking on the zio taskq's, reduces context switch
831 		 * overhead, and has no recursion penalty.  Note that one
832 		 * read from disk typically causes at least 3 zio's: a
833 		 * zio_null(), the logical zio_read(), and then a physical
834 		 * zio.  When the physical ZIO completes, we are able to call
835 		 * zio_done() on all 3 of these zio's from one invocation of
836 		 * zio_execute() by returning the parent back to
837 		 * zio_execute().  Since the parent isn't executed until this
838 		 * thread returns back to zio_execute(), the caller should do
839 		 * so promptly.
840 		 *
841 		 * In other cases, dispatching the parent prevents
842 		 * overflowing the stack when we have deeply nested
843 		 * parent-child relationships, as we do with the "mega zio"
844 		 * of writes for spa_sync(), and the chain of ZIL blocks.
845 		 */
846 		if (next_to_executep != NULL && *next_to_executep == NULL &&
847 		    (pio->io_type == zio->io_type ||
848 		    (pio->io_type == ZIO_TYPE_NULL && !pio->io_done))) {
849 			*next_to_executep = pio;
850 		} else {
851 			zio_taskq_dispatch(pio, type, B_FALSE);
852 		}
853 	} else {
854 		mutex_exit(&pio->io_lock);
855 	}
856 }
857 
858 static void
859 zio_inherit_child_errors(zio_t *zio, enum zio_child c)
860 {
861 	if (zio->io_child_error[c] != 0 && zio->io_error == 0)
862 		zio->io_error = zio->io_child_error[c];
863 }
864 
865 int
866 zio_bookmark_compare(const void *x1, const void *x2)
867 {
868 	const zio_t *z1 = x1;
869 	const zio_t *z2 = x2;
870 
871 	if (z1->io_bookmark.zb_objset < z2->io_bookmark.zb_objset)
872 		return (-1);
873 	if (z1->io_bookmark.zb_objset > z2->io_bookmark.zb_objset)
874 		return (1);
875 
876 	if (z1->io_bookmark.zb_object < z2->io_bookmark.zb_object)
877 		return (-1);
878 	if (z1->io_bookmark.zb_object > z2->io_bookmark.zb_object)
879 		return (1);
880 
881 	if (z1->io_bookmark.zb_level < z2->io_bookmark.zb_level)
882 		return (-1);
883 	if (z1->io_bookmark.zb_level > z2->io_bookmark.zb_level)
884 		return (1);
885 
886 	if (z1->io_bookmark.zb_blkid < z2->io_bookmark.zb_blkid)
887 		return (-1);
888 	if (z1->io_bookmark.zb_blkid > z2->io_bookmark.zb_blkid)
889 		return (1);
890 
891 	if (z1 < z2)
892 		return (-1);
893 	if (z1 > z2)
894 		return (1);
895 
896 	return (0);
897 }
898 
899 /*
900  * ==========================================================================
901  * Create the various types of I/O (read, write, free, etc)
902  * ==========================================================================
903  */
904 static zio_t *
905 zio_create(zio_t *pio, spa_t *spa, uint64_t txg, const blkptr_t *bp,
906     abd_t *data, uint64_t lsize, uint64_t psize, zio_done_func_t *done,
907     void *private, zio_type_t type, zio_priority_t priority,
908     zio_flag_t flags, vdev_t *vd, uint64_t offset,
909     const zbookmark_phys_t *zb, enum zio_stage stage,
910     enum zio_stage pipeline)
911 {
912 	zio_t *zio;
913 
914 	IMPLY(type != ZIO_TYPE_TRIM, psize <= SPA_MAXBLOCKSIZE);
915 	ASSERT(P2PHASE(psize, SPA_MINBLOCKSIZE) == 0);
916 	ASSERT(P2PHASE(offset, SPA_MINBLOCKSIZE) == 0);
917 
918 	ASSERT(!vd || spa_config_held(spa, SCL_STATE_ALL, RW_READER));
919 	ASSERT(!bp || !(flags & ZIO_FLAG_CONFIG_WRITER));
920 	ASSERT(vd || stage == ZIO_STAGE_OPEN);
921 
922 	IMPLY(lsize != psize, (flags & ZIO_FLAG_RAW_COMPRESS) != 0);
923 
924 	zio = kmem_cache_alloc(zio_cache, KM_SLEEP);
925 	memset(zio, 0, sizeof (zio_t));
926 
927 	mutex_init(&zio->io_lock, NULL, MUTEX_NOLOCKDEP, NULL);
928 	cv_init(&zio->io_cv, NULL, CV_DEFAULT, NULL);
929 
930 	list_create(&zio->io_parent_list, sizeof (zio_link_t),
931 	    offsetof(zio_link_t, zl_parent_node));
932 	list_create(&zio->io_child_list, sizeof (zio_link_t),
933 	    offsetof(zio_link_t, zl_child_node));
934 	metaslab_trace_init(&zio->io_alloc_list);
935 
936 	if (vd != NULL)
937 		zio->io_child_type = ZIO_CHILD_VDEV;
938 	else if (flags & ZIO_FLAG_GANG_CHILD)
939 		zio->io_child_type = ZIO_CHILD_GANG;
940 	else if (flags & ZIO_FLAG_DDT_CHILD)
941 		zio->io_child_type = ZIO_CHILD_DDT;
942 	else
943 		zio->io_child_type = ZIO_CHILD_LOGICAL;
944 
945 	if (bp != NULL) {
946 		if (type != ZIO_TYPE_WRITE ||
947 		    zio->io_child_type == ZIO_CHILD_DDT) {
948 			zio->io_bp_copy = *bp;
949 			zio->io_bp = &zio->io_bp_copy;	/* so caller can free */
950 		} else {
951 			zio->io_bp = (blkptr_t *)bp;
952 		}
953 		zio->io_bp_orig = *bp;
954 		if (zio->io_child_type == ZIO_CHILD_LOGICAL)
955 			zio->io_logical = zio;
956 		if (zio->io_child_type > ZIO_CHILD_GANG && BP_IS_GANG(bp))
957 			pipeline |= ZIO_GANG_STAGES;
958 	}
959 
960 	zio->io_spa = spa;
961 	zio->io_txg = txg;
962 	zio->io_done = done;
963 	zio->io_private = private;
964 	zio->io_type = type;
965 	zio->io_priority = priority;
966 	zio->io_vd = vd;
967 	zio->io_offset = offset;
968 	zio->io_orig_abd = zio->io_abd = data;
969 	zio->io_orig_size = zio->io_size = psize;
970 	zio->io_lsize = lsize;
971 	zio->io_orig_flags = zio->io_flags = flags;
972 	zio->io_orig_stage = zio->io_stage = stage;
973 	zio->io_orig_pipeline = zio->io_pipeline = pipeline;
974 	zio->io_pipeline_trace = ZIO_STAGE_OPEN;
975 	zio->io_allocator = ZIO_ALLOCATOR_NONE;
976 
977 	zio->io_state[ZIO_WAIT_READY] = (stage >= ZIO_STAGE_READY) ||
978 	    (pipeline & ZIO_STAGE_READY) == 0;
979 	zio->io_state[ZIO_WAIT_DONE] = (stage >= ZIO_STAGE_DONE);
980 
981 	if (zb != NULL)
982 		zio->io_bookmark = *zb;
983 
984 	if (pio != NULL) {
985 		zio->io_metaslab_class = pio->io_metaslab_class;
986 		if (zio->io_logical == NULL)
987 			zio->io_logical = pio->io_logical;
988 		if (zio->io_child_type == ZIO_CHILD_GANG)
989 			zio->io_gang_leader = pio->io_gang_leader;
990 		zio_add_child_first(pio, zio);
991 	}
992 
993 	taskq_init_ent(&zio->io_tqent);
994 
995 	return (zio);
996 }
997 
998 void
999 zio_destroy(zio_t *zio)
1000 {
1001 	metaslab_trace_fini(&zio->io_alloc_list);
1002 	list_destroy(&zio->io_parent_list);
1003 	list_destroy(&zio->io_child_list);
1004 	mutex_destroy(&zio->io_lock);
1005 	cv_destroy(&zio->io_cv);
1006 	kmem_cache_free(zio_cache, zio);
1007 }
1008 
1009 /*
1010  * ZIO intended to be between others.  Provides synchronization at READY
1011  * and DONE pipeline stages and calls the respective callbacks.
1012  */
1013 zio_t *
1014 zio_null(zio_t *pio, spa_t *spa, vdev_t *vd, zio_done_func_t *done,
1015     void *private, zio_flag_t flags)
1016 {
1017 	zio_t *zio;
1018 
1019 	zio = zio_create(pio, spa, 0, NULL, NULL, 0, 0, done, private,
1020 	    ZIO_TYPE_NULL, ZIO_PRIORITY_NOW, flags, vd, 0, NULL,
1021 	    ZIO_STAGE_OPEN, ZIO_INTERLOCK_PIPELINE);
1022 
1023 	return (zio);
1024 }
1025 
1026 /*
1027  * ZIO intended to be a root of a tree.  Unlike null ZIO does not have a
1028  * READY pipeline stage (is ready on creation), so it should not be used
1029  * as child of any ZIO that may need waiting for grandchildren READY stage
1030  * (any other ZIO type).
1031  */
1032 zio_t *
1033 zio_root(spa_t *spa, zio_done_func_t *done, void *private, zio_flag_t flags)
1034 {
1035 	zio_t *zio;
1036 
1037 	zio = zio_create(NULL, spa, 0, NULL, NULL, 0, 0, done, private,
1038 	    ZIO_TYPE_NULL, ZIO_PRIORITY_NOW, flags, NULL, 0, NULL,
1039 	    ZIO_STAGE_OPEN, ZIO_ROOT_PIPELINE);
1040 
1041 	return (zio);
1042 }
1043 
1044 static int
1045 zfs_blkptr_verify_log(spa_t *spa, const blkptr_t *bp,
1046     enum blk_verify_flag blk_verify, const char *fmt, ...)
1047 {
1048 	va_list adx;
1049 	char buf[256];
1050 
1051 	va_start(adx, fmt);
1052 	(void) vsnprintf(buf, sizeof (buf), fmt, adx);
1053 	va_end(adx);
1054 
1055 	zfs_dbgmsg("bad blkptr at %px: "
1056 	    "DVA[0]=%#llx/%#llx "
1057 	    "DVA[1]=%#llx/%#llx "
1058 	    "DVA[2]=%#llx/%#llx "
1059 	    "prop=%#llx "
1060 	    "pad=%#llx,%#llx "
1061 	    "phys_birth=%#llx "
1062 	    "birth=%#llx "
1063 	    "fill=%#llx "
1064 	    "cksum=%#llx/%#llx/%#llx/%#llx",
1065 	    bp,
1066 	    (long long)bp->blk_dva[0].dva_word[0],
1067 	    (long long)bp->blk_dva[0].dva_word[1],
1068 	    (long long)bp->blk_dva[1].dva_word[0],
1069 	    (long long)bp->blk_dva[1].dva_word[1],
1070 	    (long long)bp->blk_dva[2].dva_word[0],
1071 	    (long long)bp->blk_dva[2].dva_word[1],
1072 	    (long long)bp->blk_prop,
1073 	    (long long)bp->blk_pad[0],
1074 	    (long long)bp->blk_pad[1],
1075 	    (long long)BP_GET_PHYSICAL_BIRTH(bp),
1076 	    (long long)BP_GET_LOGICAL_BIRTH(bp),
1077 	    (long long)bp->blk_fill,
1078 	    (long long)bp->blk_cksum.zc_word[0],
1079 	    (long long)bp->blk_cksum.zc_word[1],
1080 	    (long long)bp->blk_cksum.zc_word[2],
1081 	    (long long)bp->blk_cksum.zc_word[3]);
1082 	switch (blk_verify) {
1083 	case BLK_VERIFY_HALT:
1084 		zfs_panic_recover("%s: %s", spa_name(spa), buf);
1085 		break;
1086 	case BLK_VERIFY_LOG:
1087 		zfs_dbgmsg("%s: %s", spa_name(spa), buf);
1088 		break;
1089 	case BLK_VERIFY_ONLY:
1090 		break;
1091 	}
1092 
1093 	return (1);
1094 }
1095 
1096 /*
1097  * Verify the block pointer fields contain reasonable values.  This means
1098  * it only contains known object types, checksum/compression identifiers,
1099  * block sizes within the maximum allowed limits, valid DVAs, etc.
1100  *
1101  * If everything checks out B_TRUE is returned.  The zfs_blkptr_verify
1102  * argument controls the behavior when an invalid field is detected.
1103  *
1104  * Values for blk_verify_flag:
1105  *   BLK_VERIFY_ONLY: evaluate the block
1106  *   BLK_VERIFY_LOG: evaluate the block and log problems
1107  *   BLK_VERIFY_HALT: call zfs_panic_recover on error
1108  *
1109  * Values for blk_config_flag:
1110  *   BLK_CONFIG_HELD: caller holds SCL_VDEV for writer
1111  *   BLK_CONFIG_NEEDED: caller holds no config lock, SCL_VDEV will be
1112  *   obtained for reader
1113  *   BLK_CONFIG_SKIP: skip checks which require SCL_VDEV, for better
1114  *   performance
1115  */
1116 boolean_t
1117 zfs_blkptr_verify(spa_t *spa, const blkptr_t *bp,
1118     enum blk_config_flag blk_config, enum blk_verify_flag blk_verify)
1119 {
1120 	int errors = 0;
1121 
1122 	if (unlikely(!DMU_OT_IS_VALID(BP_GET_TYPE(bp)))) {
1123 		errors += zfs_blkptr_verify_log(spa, bp, blk_verify,
1124 		    "blkptr at %px has invalid TYPE %llu",
1125 		    bp, (longlong_t)BP_GET_TYPE(bp));
1126 	}
1127 	if (unlikely(BP_GET_COMPRESS(bp) >= ZIO_COMPRESS_FUNCTIONS)) {
1128 		errors += zfs_blkptr_verify_log(spa, bp, blk_verify,
1129 		    "blkptr at %px has invalid COMPRESS %llu",
1130 		    bp, (longlong_t)BP_GET_COMPRESS(bp));
1131 	}
1132 	if (unlikely(BP_GET_LSIZE(bp) > SPA_MAXBLOCKSIZE)) {
1133 		errors += zfs_blkptr_verify_log(spa, bp, blk_verify,
1134 		    "blkptr at %px has invalid LSIZE %llu",
1135 		    bp, (longlong_t)BP_GET_LSIZE(bp));
1136 	}
1137 	if (BP_IS_EMBEDDED(bp)) {
1138 		if (unlikely(BPE_GET_ETYPE(bp) >= NUM_BP_EMBEDDED_TYPES)) {
1139 			errors += zfs_blkptr_verify_log(spa, bp, blk_verify,
1140 			    "blkptr at %px has invalid ETYPE %llu",
1141 			    bp, (longlong_t)BPE_GET_ETYPE(bp));
1142 		}
1143 		if (unlikely(BPE_GET_PSIZE(bp) > BPE_PAYLOAD_SIZE)) {
1144 			errors += zfs_blkptr_verify_log(spa, bp, blk_verify,
1145 			    "blkptr at %px has invalid PSIZE %llu",
1146 			    bp, (longlong_t)BPE_GET_PSIZE(bp));
1147 		}
1148 		return (errors == 0);
1149 	}
1150 	if (unlikely(BP_GET_CHECKSUM(bp) >= ZIO_CHECKSUM_FUNCTIONS)) {
1151 		errors += zfs_blkptr_verify_log(spa, bp, blk_verify,
1152 		    "blkptr at %px has invalid CHECKSUM %llu",
1153 		    bp, (longlong_t)BP_GET_CHECKSUM(bp));
1154 	}
1155 	if (unlikely(BP_GET_PSIZE(bp) > SPA_MAXBLOCKSIZE)) {
1156 		errors += zfs_blkptr_verify_log(spa, bp, blk_verify,
1157 		    "blkptr at %px has invalid PSIZE %llu",
1158 		    bp, (longlong_t)BP_GET_PSIZE(bp));
1159 	}
1160 
1161 	/*
1162 	 * Do not verify individual DVAs if the config is not trusted. This
1163 	 * will be done once the zio is executed in vdev_mirror_map_alloc.
1164 	 */
1165 	if (unlikely(!spa->spa_trust_config))
1166 		return (errors == 0);
1167 
1168 	switch (blk_config) {
1169 	case BLK_CONFIG_HELD:
1170 		ASSERT(spa_config_held(spa, SCL_VDEV, RW_WRITER));
1171 		break;
1172 	case BLK_CONFIG_NEEDED:
1173 		spa_config_enter(spa, SCL_VDEV, bp, RW_READER);
1174 		break;
1175 	case BLK_CONFIG_SKIP:
1176 		return (errors == 0);
1177 	default:
1178 		panic("invalid blk_config %u", blk_config);
1179 	}
1180 
1181 	/*
1182 	 * Pool-specific checks.
1183 	 *
1184 	 * Note: it would be nice to verify that the logical birth
1185 	 * and physical birth are not too large.  However,
1186 	 * spa_freeze() allows the birth time of log blocks (and
1187 	 * dmu_sync()-ed blocks that are in the log) to be arbitrarily
1188 	 * large.
1189 	 */
1190 	for (int i = 0; i < BP_GET_NDVAS(bp); i++) {
1191 		const dva_t *dva = &bp->blk_dva[i];
1192 		uint64_t vdevid = DVA_GET_VDEV(dva);
1193 
1194 		if (unlikely(vdevid >= spa->spa_root_vdev->vdev_children)) {
1195 			errors += zfs_blkptr_verify_log(spa, bp, blk_verify,
1196 			    "blkptr at %px DVA %u has invalid VDEV %llu",
1197 			    bp, i, (longlong_t)vdevid);
1198 			continue;
1199 		}
1200 		vdev_t *vd = spa->spa_root_vdev->vdev_child[vdevid];
1201 		if (unlikely(vd == NULL)) {
1202 			errors += zfs_blkptr_verify_log(spa, bp, blk_verify,
1203 			    "blkptr at %px DVA %u has invalid VDEV %llu",
1204 			    bp, i, (longlong_t)vdevid);
1205 			continue;
1206 		}
1207 		if (unlikely(vd->vdev_ops == &vdev_hole_ops)) {
1208 			errors += zfs_blkptr_verify_log(spa, bp, blk_verify,
1209 			    "blkptr at %px DVA %u has hole VDEV %llu",
1210 			    bp, i, (longlong_t)vdevid);
1211 			continue;
1212 		}
1213 		if (vd->vdev_ops == &vdev_missing_ops) {
1214 			/*
1215 			 * "missing" vdevs are valid during import, but we
1216 			 * don't have their detailed info (e.g. asize), so
1217 			 * we can't perform any more checks on them.
1218 			 */
1219 			continue;
1220 		}
1221 		uint64_t offset = DVA_GET_OFFSET(dva);
1222 		uint64_t asize = DVA_GET_ASIZE(dva);
1223 		if (DVA_GET_GANG(dva))
1224 			asize = vdev_gang_header_asize(vd);
1225 		if (unlikely(offset + asize > vd->vdev_asize)) {
1226 			errors += zfs_blkptr_verify_log(spa, bp, blk_verify,
1227 			    "blkptr at %px DVA %u has invalid OFFSET %llu",
1228 			    bp, i, (longlong_t)offset);
1229 		}
1230 	}
1231 	if (blk_config == BLK_CONFIG_NEEDED)
1232 		spa_config_exit(spa, SCL_VDEV, bp);
1233 
1234 	return (errors == 0);
1235 }
1236 
1237 boolean_t
1238 zfs_dva_valid(spa_t *spa, const dva_t *dva, const blkptr_t *bp)
1239 {
1240 	(void) bp;
1241 	uint64_t vdevid = DVA_GET_VDEV(dva);
1242 
1243 	if (vdevid >= spa->spa_root_vdev->vdev_children)
1244 		return (B_FALSE);
1245 
1246 	vdev_t *vd = spa->spa_root_vdev->vdev_child[vdevid];
1247 	if (vd == NULL)
1248 		return (B_FALSE);
1249 
1250 	if (vd->vdev_ops == &vdev_hole_ops)
1251 		return (B_FALSE);
1252 
1253 	if (vd->vdev_ops == &vdev_missing_ops) {
1254 		return (B_FALSE);
1255 	}
1256 
1257 	uint64_t offset = DVA_GET_OFFSET(dva);
1258 	uint64_t asize = DVA_GET_ASIZE(dva);
1259 
1260 	if (DVA_GET_GANG(dva))
1261 		asize = vdev_gang_header_asize(vd);
1262 	if (offset + asize > vd->vdev_asize)
1263 		return (B_FALSE);
1264 
1265 	return (B_TRUE);
1266 }
1267 
1268 zio_t *
1269 zio_read(zio_t *pio, spa_t *spa, const blkptr_t *bp,
1270     abd_t *data, uint64_t size, zio_done_func_t *done, void *private,
1271     zio_priority_t priority, zio_flag_t flags, const zbookmark_phys_t *zb)
1272 {
1273 	zio_t *zio;
1274 
1275 	zio = zio_create(pio, spa, BP_GET_BIRTH(bp), bp,
1276 	    data, size, size, done, private,
1277 	    ZIO_TYPE_READ, priority, flags, NULL, 0, zb,
1278 	    ZIO_STAGE_OPEN, (flags & ZIO_FLAG_DDT_CHILD) ?
1279 	    ZIO_DDT_CHILD_READ_PIPELINE : ZIO_READ_PIPELINE);
1280 
1281 	return (zio);
1282 }
1283 
1284 zio_t *
1285 zio_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
1286     abd_t *data, uint64_t lsize, uint64_t psize, const zio_prop_t *zp,
1287     zio_done_func_t *ready, zio_done_func_t *children_ready,
1288     zio_done_func_t *done, void *private, zio_priority_t priority,
1289     zio_flag_t flags, const zbookmark_phys_t *zb)
1290 {
1291 	zio_t *zio;
1292 	enum zio_stage pipeline = zp->zp_direct_write == B_TRUE ?
1293 	    ZIO_DIRECT_WRITE_PIPELINE : (flags & ZIO_FLAG_DDT_CHILD) ?
1294 	    ZIO_DDT_CHILD_WRITE_PIPELINE : ZIO_WRITE_PIPELINE;
1295 
1296 
1297 	zio = zio_create(pio, spa, txg, bp, data, lsize, psize, done, private,
1298 	    ZIO_TYPE_WRITE, priority, flags, NULL, 0, zb,
1299 	    ZIO_STAGE_OPEN, pipeline);
1300 
1301 	zio->io_ready = ready;
1302 	zio->io_children_ready = children_ready;
1303 	zio->io_prop = *zp;
1304 
1305 	/*
1306 	 * Data can be NULL if we are going to call zio_write_override() to
1307 	 * provide the already-allocated BP.  But we may need the data to
1308 	 * verify a dedup hit (if requested).  In this case, don't try to
1309 	 * dedup (just take the already-allocated BP verbatim). Encrypted
1310 	 * dedup blocks need data as well so we also disable dedup in this
1311 	 * case.
1312 	 */
1313 	if (data == NULL &&
1314 	    (zio->io_prop.zp_dedup_verify || zio->io_prop.zp_encrypt)) {
1315 		zio->io_prop.zp_dedup = zio->io_prop.zp_dedup_verify = B_FALSE;
1316 	}
1317 
1318 	return (zio);
1319 }
1320 
1321 zio_t *
1322 zio_rewrite(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, abd_t *data,
1323     uint64_t size, zio_done_func_t *done, void *private,
1324     zio_priority_t priority, zio_flag_t flags, zbookmark_phys_t *zb)
1325 {
1326 	zio_t *zio;
1327 
1328 	zio = zio_create(pio, spa, txg, bp, data, size, size, done, private,
1329 	    ZIO_TYPE_WRITE, priority, flags | ZIO_FLAG_IO_REWRITE, NULL, 0, zb,
1330 	    ZIO_STAGE_OPEN, ZIO_REWRITE_PIPELINE);
1331 
1332 	return (zio);
1333 }
1334 
1335 void
1336 zio_write_override(zio_t *zio, blkptr_t *bp, int copies, boolean_t nopwrite,
1337     boolean_t brtwrite)
1338 {
1339 	ASSERT(zio->io_type == ZIO_TYPE_WRITE);
1340 	ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1341 	ASSERT(zio->io_stage == ZIO_STAGE_OPEN);
1342 	ASSERT(zio->io_txg == spa_syncing_txg(zio->io_spa));
1343 	ASSERT(!brtwrite || !nopwrite);
1344 
1345 	/*
1346 	 * We must reset the io_prop to match the values that existed
1347 	 * when the bp was first written by dmu_sync() keeping in mind
1348 	 * that nopwrite and dedup are mutually exclusive.
1349 	 */
1350 	zio->io_prop.zp_dedup = nopwrite ? B_FALSE : zio->io_prop.zp_dedup;
1351 	zio->io_prop.zp_nopwrite = nopwrite;
1352 	zio->io_prop.zp_brtwrite = brtwrite;
1353 	zio->io_prop.zp_copies = copies;
1354 	zio->io_bp_override = bp;
1355 }
1356 
1357 void
1358 zio_free(spa_t *spa, uint64_t txg, const blkptr_t *bp)
1359 {
1360 
1361 	(void) zfs_blkptr_verify(spa, bp, BLK_CONFIG_NEEDED, BLK_VERIFY_HALT);
1362 
1363 	/*
1364 	 * The check for EMBEDDED is a performance optimization.  We
1365 	 * process the free here (by ignoring it) rather than
1366 	 * putting it on the list and then processing it in zio_free_sync().
1367 	 */
1368 	if (BP_IS_EMBEDDED(bp))
1369 		return;
1370 
1371 	/*
1372 	 * Frees that are for the currently-syncing txg, are not going to be
1373 	 * deferred, and which will not need to do a read (i.e. not GANG or
1374 	 * DEDUP), can be processed immediately.  Otherwise, put them on the
1375 	 * in-memory list for later processing.
1376 	 *
1377 	 * Note that we only defer frees after zfs_sync_pass_deferred_free
1378 	 * when the log space map feature is disabled. [see relevant comment
1379 	 * in spa_sync_iterate_to_convergence()]
1380 	 */
1381 	if (BP_IS_GANG(bp) ||
1382 	    BP_GET_DEDUP(bp) ||
1383 	    txg != spa->spa_syncing_txg ||
1384 	    (spa_sync_pass(spa) >= zfs_sync_pass_deferred_free &&
1385 	    !spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP)) ||
1386 	    brt_maybe_exists(spa, bp)) {
1387 		metaslab_check_free(spa, bp);
1388 		bplist_append(&spa->spa_free_bplist[txg & TXG_MASK], bp);
1389 	} else {
1390 		VERIFY3P(zio_free_sync(NULL, spa, txg, bp, 0), ==, NULL);
1391 	}
1392 }
1393 
1394 /*
1395  * To improve performance, this function may return NULL if we were able
1396  * to do the free immediately.  This avoids the cost of creating a zio
1397  * (and linking it to the parent, etc).
1398  */
1399 zio_t *
1400 zio_free_sync(zio_t *pio, spa_t *spa, uint64_t txg, const blkptr_t *bp,
1401     zio_flag_t flags)
1402 {
1403 	ASSERT(!BP_IS_HOLE(bp));
1404 	ASSERT(spa_syncing_txg(spa) == txg);
1405 
1406 	if (BP_IS_EMBEDDED(bp))
1407 		return (NULL);
1408 
1409 	metaslab_check_free(spa, bp);
1410 	arc_freed(spa, bp);
1411 	dsl_scan_freed(spa, bp);
1412 
1413 	if (BP_IS_GANG(bp) ||
1414 	    BP_GET_DEDUP(bp) ||
1415 	    brt_maybe_exists(spa, bp)) {
1416 		/*
1417 		 * GANG, DEDUP and BRT blocks can induce a read (for the gang
1418 		 * block header, the DDT or the BRT), so issue them
1419 		 * asynchronously so that this thread is not tied up.
1420 		 */
1421 		enum zio_stage stage =
1422 		    ZIO_FREE_PIPELINE | ZIO_STAGE_ISSUE_ASYNC;
1423 
1424 		return (zio_create(pio, spa, txg, bp, NULL, BP_GET_PSIZE(bp),
1425 		    BP_GET_PSIZE(bp), NULL, NULL,
1426 		    ZIO_TYPE_FREE, ZIO_PRIORITY_NOW,
1427 		    flags, NULL, 0, NULL, ZIO_STAGE_OPEN, stage));
1428 	} else {
1429 		metaslab_free(spa, bp, txg, B_FALSE);
1430 		return (NULL);
1431 	}
1432 }
1433 
1434 zio_t *
1435 zio_claim(zio_t *pio, spa_t *spa, uint64_t txg, const blkptr_t *bp,
1436     zio_done_func_t *done, void *private, zio_flag_t flags)
1437 {
1438 	zio_t *zio;
1439 
1440 	(void) zfs_blkptr_verify(spa, bp, (flags & ZIO_FLAG_CONFIG_WRITER) ?
1441 	    BLK_CONFIG_HELD : BLK_CONFIG_NEEDED, BLK_VERIFY_HALT);
1442 
1443 	if (BP_IS_EMBEDDED(bp))
1444 		return (zio_null(pio, spa, NULL, NULL, NULL, 0));
1445 
1446 	/*
1447 	 * A claim is an allocation of a specific block.  Claims are needed
1448 	 * to support immediate writes in the intent log.  The issue is that
1449 	 * immediate writes contain committed data, but in a txg that was
1450 	 * *not* committed.  Upon opening the pool after an unclean shutdown,
1451 	 * the intent log claims all blocks that contain immediate write data
1452 	 * so that the SPA knows they're in use.
1453 	 *
1454 	 * All claims *must* be resolved in the first txg -- before the SPA
1455 	 * starts allocating blocks -- so that nothing is allocated twice.
1456 	 * If txg == 0 we just verify that the block is claimable.
1457 	 */
1458 	ASSERT3U(BP_GET_LOGICAL_BIRTH(&spa->spa_uberblock.ub_rootbp), <,
1459 	    spa_min_claim_txg(spa));
1460 	ASSERT(txg == spa_min_claim_txg(spa) || txg == 0);
1461 	ASSERT(!BP_GET_DEDUP(bp) || !spa_writeable(spa));	/* zdb(8) */
1462 
1463 	zio = zio_create(pio, spa, txg, bp, NULL, BP_GET_PSIZE(bp),
1464 	    BP_GET_PSIZE(bp), done, private, ZIO_TYPE_CLAIM, ZIO_PRIORITY_NOW,
1465 	    flags, NULL, 0, NULL, ZIO_STAGE_OPEN, ZIO_CLAIM_PIPELINE);
1466 	ASSERT0(zio->io_queued_timestamp);
1467 
1468 	return (zio);
1469 }
1470 
1471 zio_t *
1472 zio_trim(zio_t *pio, vdev_t *vd, uint64_t offset, uint64_t size,
1473     zio_done_func_t *done, void *private, zio_priority_t priority,
1474     zio_flag_t flags, enum trim_flag trim_flags)
1475 {
1476 	zio_t *zio;
1477 
1478 	ASSERT0(vd->vdev_children);
1479 	ASSERT0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
1480 	ASSERT0(P2PHASE(size, 1ULL << vd->vdev_ashift));
1481 	ASSERT3U(size, !=, 0);
1482 
1483 	zio = zio_create(pio, vd->vdev_spa, 0, NULL, NULL, size, size, done,
1484 	    private, ZIO_TYPE_TRIM, priority, flags | ZIO_FLAG_PHYSICAL,
1485 	    vd, offset, NULL, ZIO_STAGE_OPEN, ZIO_TRIM_PIPELINE);
1486 	zio->io_trim_flags = trim_flags;
1487 
1488 	return (zio);
1489 }
1490 
1491 zio_t *
1492 zio_read_phys(zio_t *pio, vdev_t *vd, uint64_t offset, uint64_t size,
1493     abd_t *data, int checksum, zio_done_func_t *done, void *private,
1494     zio_priority_t priority, zio_flag_t flags, boolean_t labels)
1495 {
1496 	zio_t *zio;
1497 
1498 	ASSERT(vd->vdev_children == 0);
1499 	ASSERT(!labels || offset + size <= VDEV_LABEL_START_SIZE ||
1500 	    offset >= vd->vdev_psize - VDEV_LABEL_END_SIZE);
1501 	ASSERT3U(offset + size, <=, vd->vdev_psize);
1502 
1503 	zio = zio_create(pio, vd->vdev_spa, 0, NULL, data, size, size, done,
1504 	    private, ZIO_TYPE_READ, priority, flags | ZIO_FLAG_PHYSICAL, vd,
1505 	    offset, NULL, ZIO_STAGE_OPEN, ZIO_READ_PHYS_PIPELINE);
1506 
1507 	zio->io_prop.zp_checksum = checksum;
1508 
1509 	return (zio);
1510 }
1511 
1512 zio_t *
1513 zio_write_phys(zio_t *pio, vdev_t *vd, uint64_t offset, uint64_t size,
1514     abd_t *data, int checksum, zio_done_func_t *done, void *private,
1515     zio_priority_t priority, zio_flag_t flags, boolean_t labels)
1516 {
1517 	zio_t *zio;
1518 
1519 	ASSERT(vd->vdev_children == 0);
1520 	ASSERT(!labels || offset + size <= VDEV_LABEL_START_SIZE ||
1521 	    offset >= vd->vdev_psize - VDEV_LABEL_END_SIZE);
1522 	ASSERT3U(offset + size, <=, vd->vdev_psize);
1523 
1524 	zio = zio_create(pio, vd->vdev_spa, 0, NULL, data, size, size, done,
1525 	    private, ZIO_TYPE_WRITE, priority, flags | ZIO_FLAG_PHYSICAL, vd,
1526 	    offset, NULL, ZIO_STAGE_OPEN, ZIO_WRITE_PHYS_PIPELINE);
1527 
1528 	zio->io_prop.zp_checksum = checksum;
1529 
1530 	if (zio_checksum_table[checksum].ci_flags & ZCHECKSUM_FLAG_EMBEDDED) {
1531 		/*
1532 		 * zec checksums are necessarily destructive -- they modify
1533 		 * the end of the write buffer to hold the verifier/checksum.
1534 		 * Therefore, we must make a local copy in case the data is
1535 		 * being written to multiple places in parallel.
1536 		 */
1537 		abd_t *wbuf = abd_alloc_sametype(data, size);
1538 		abd_copy(wbuf, data, size);
1539 
1540 		zio_push_transform(zio, wbuf, size, size, NULL);
1541 	}
1542 
1543 	return (zio);
1544 }
1545 
1546 /*
1547  * Create a child I/O to do some work for us.
1548  */
1549 zio_t *
1550 zio_vdev_child_io(zio_t *pio, blkptr_t *bp, vdev_t *vd, uint64_t offset,
1551     abd_t *data, uint64_t size, int type, zio_priority_t priority,
1552     zio_flag_t flags, zio_done_func_t *done, void *private)
1553 {
1554 	enum zio_stage pipeline = ZIO_VDEV_CHILD_PIPELINE;
1555 	zio_t *zio;
1556 
1557 	/*
1558 	 * vdev child I/Os do not propagate their error to the parent.
1559 	 * Therefore, for correct operation the caller *must* check for
1560 	 * and handle the error in the child i/o's done callback.
1561 	 * The only exceptions are i/os that we don't care about
1562 	 * (OPTIONAL or REPAIR).
1563 	 */
1564 	ASSERT((flags & ZIO_FLAG_OPTIONAL) || (flags & ZIO_FLAG_IO_REPAIR) ||
1565 	    done != NULL);
1566 
1567 	if (type == ZIO_TYPE_READ && bp != NULL) {
1568 		/*
1569 		 * If we have the bp, then the child should perform the
1570 		 * checksum and the parent need not.  This pushes error
1571 		 * detection as close to the leaves as possible and
1572 		 * eliminates redundant checksums in the interior nodes.
1573 		 */
1574 		pipeline |= ZIO_STAGE_CHECKSUM_VERIFY;
1575 		pio->io_pipeline &= ~ZIO_STAGE_CHECKSUM_VERIFY;
1576 	} else if (type == ZIO_TYPE_WRITE &&
1577 	    pio->io_prop.zp_direct_write == B_TRUE) {
1578 		/*
1579 		 * By default we only will verify checksums for Direct I/O
1580 		 * writes for Linux. FreeBSD is able to place user pages under
1581 		 * write protection before issuing them to the ZIO pipeline.
1582 		 *
1583 		 * Checksum validation errors will only be reported through
1584 		 * the top-level VDEV, which is set by this child ZIO.
1585 		 */
1586 		ASSERT3P(bp, !=, NULL);
1587 		ASSERT3U(pio->io_child_type, ==, ZIO_CHILD_LOGICAL);
1588 		pipeline |= ZIO_STAGE_DIO_CHECKSUM_VERIFY;
1589 	}
1590 
1591 	if (vd->vdev_ops->vdev_op_leaf) {
1592 		ASSERT0(vd->vdev_children);
1593 		offset += VDEV_LABEL_START_SIZE;
1594 	}
1595 
1596 	flags |= ZIO_VDEV_CHILD_FLAGS(pio);
1597 
1598 	/*
1599 	 * If we've decided to do a repair, the write is not speculative --
1600 	 * even if the original read was.
1601 	 */
1602 	if (flags & ZIO_FLAG_IO_REPAIR)
1603 		flags &= ~ZIO_FLAG_SPECULATIVE;
1604 
1605 	/*
1606 	 * If we're creating a child I/O that is not associated with a
1607 	 * top-level vdev, then the child zio is not an allocating I/O.
1608 	 * If this is a retried I/O then we ignore it since we will
1609 	 * have already processed the original allocating I/O.
1610 	 */
1611 	if (flags & ZIO_FLAG_IO_ALLOCATING &&
1612 	    (vd != vd->vdev_top || (flags & ZIO_FLAG_IO_RETRY))) {
1613 		ASSERT(pio->io_metaslab_class != NULL);
1614 		ASSERT(pio->io_metaslab_class->mc_alloc_throttle_enabled);
1615 		ASSERT(type == ZIO_TYPE_WRITE);
1616 		ASSERT(priority == ZIO_PRIORITY_ASYNC_WRITE);
1617 		ASSERT(!(flags & ZIO_FLAG_IO_REPAIR));
1618 		ASSERT(!(pio->io_flags & ZIO_FLAG_IO_REWRITE) ||
1619 		    pio->io_child_type == ZIO_CHILD_GANG);
1620 
1621 		flags &= ~ZIO_FLAG_IO_ALLOCATING;
1622 	}
1623 
1624 	zio = zio_create(pio, pio->io_spa, pio->io_txg, bp, data, size, size,
1625 	    done, private, type, priority, flags, vd, offset, &pio->io_bookmark,
1626 	    ZIO_STAGE_VDEV_IO_START >> 1, pipeline);
1627 	ASSERT3U(zio->io_child_type, ==, ZIO_CHILD_VDEV);
1628 
1629 	return (zio);
1630 }
1631 
1632 zio_t *
1633 zio_vdev_delegated_io(vdev_t *vd, uint64_t offset, abd_t *data, uint64_t size,
1634     zio_type_t type, zio_priority_t priority, zio_flag_t flags,
1635     zio_done_func_t *done, void *private)
1636 {
1637 	zio_t *zio;
1638 
1639 	ASSERT(vd->vdev_ops->vdev_op_leaf);
1640 
1641 	zio = zio_create(NULL, vd->vdev_spa, 0, NULL,
1642 	    data, size, size, done, private, type, priority,
1643 	    flags | ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_RETRY | ZIO_FLAG_DELEGATED,
1644 	    vd, offset, NULL,
1645 	    ZIO_STAGE_VDEV_IO_START >> 1, ZIO_VDEV_CHILD_PIPELINE);
1646 
1647 	return (zio);
1648 }
1649 
1650 
1651 /*
1652  * Send a flush command to the given vdev. Unlike most zio creation functions,
1653  * the flush zios are issued immediately. You can wait on pio to pause until
1654  * the flushes complete.
1655  */
1656 void
1657 zio_flush(zio_t *pio, vdev_t *vd)
1658 {
1659 	const zio_flag_t flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE |
1660 	    ZIO_FLAG_DONT_RETRY;
1661 
1662 	if (vd->vdev_nowritecache)
1663 		return;
1664 
1665 	if (vd->vdev_children == 0) {
1666 		zio_nowait(zio_create(pio, vd->vdev_spa, 0, NULL, NULL, 0, 0,
1667 		    NULL, NULL, ZIO_TYPE_FLUSH, ZIO_PRIORITY_NOW, flags, vd, 0,
1668 		    NULL, ZIO_STAGE_OPEN, ZIO_FLUSH_PIPELINE));
1669 	} else {
1670 		for (uint64_t c = 0; c < vd->vdev_children; c++)
1671 			zio_flush(pio, vd->vdev_child[c]);
1672 	}
1673 }
1674 
1675 void
1676 zio_shrink(zio_t *zio, uint64_t size)
1677 {
1678 	ASSERT3P(zio->io_executor, ==, NULL);
1679 	ASSERT3U(zio->io_orig_size, ==, zio->io_size);
1680 	ASSERT3U(size, <=, zio->io_size);
1681 
1682 	/*
1683 	 * We don't shrink for raidz because of problems with the
1684 	 * reconstruction when reading back less than the block size.
1685 	 * Note, BP_IS_RAIDZ() assumes no compression.
1686 	 */
1687 	ASSERT(BP_GET_COMPRESS(zio->io_bp) == ZIO_COMPRESS_OFF);
1688 	if (!BP_IS_RAIDZ(zio->io_bp)) {
1689 		/* we are not doing a raw write */
1690 		ASSERT3U(zio->io_size, ==, zio->io_lsize);
1691 		zio->io_orig_size = zio->io_size = zio->io_lsize = size;
1692 	}
1693 }
1694 
1695 /*
1696  * Round provided allocation size up to a value that can be allocated
1697  * by at least some vdev(s) in the pool with minimum or no additional
1698  * padding and without extra space usage on others
1699  */
1700 static uint64_t
1701 zio_roundup_alloc_size(spa_t *spa, uint64_t size)
1702 {
1703 	if (size > spa->spa_min_alloc)
1704 		return (roundup(size, spa->spa_gcd_alloc));
1705 	return (spa->spa_min_alloc);
1706 }
1707 
1708 size_t
1709 zio_get_compression_max_size(enum zio_compress compress, uint64_t gcd_alloc,
1710     uint64_t min_alloc, size_t s_len)
1711 {
1712 	size_t d_len;
1713 
1714 	/* minimum 12.5% must be saved (legacy value, may be changed later) */
1715 	d_len = s_len - (s_len >> 3);
1716 
1717 	/* ZLE can't use exactly d_len bytes, it needs more, so ignore it */
1718 	if (compress == ZIO_COMPRESS_ZLE)
1719 		return (d_len);
1720 
1721 	d_len = d_len - d_len % gcd_alloc;
1722 
1723 	if (d_len < min_alloc)
1724 		return (BPE_PAYLOAD_SIZE);
1725 	return (d_len);
1726 }
1727 
1728 /*
1729  * ==========================================================================
1730  * Prepare to read and write logical blocks
1731  * ==========================================================================
1732  */
1733 
1734 static zio_t *
1735 zio_read_bp_init(zio_t *zio)
1736 {
1737 	blkptr_t *bp = zio->io_bp;
1738 	uint64_t psize =
1739 	    BP_IS_EMBEDDED(bp) ? BPE_GET_PSIZE(bp) : BP_GET_PSIZE(bp);
1740 
1741 	ASSERT3P(zio->io_bp, ==, &zio->io_bp_copy);
1742 
1743 	if (BP_GET_COMPRESS(bp) != ZIO_COMPRESS_OFF &&
1744 	    zio->io_child_type == ZIO_CHILD_LOGICAL &&
1745 	    !(zio->io_flags & ZIO_FLAG_RAW_COMPRESS)) {
1746 		zio_push_transform(zio, abd_alloc_sametype(zio->io_abd, psize),
1747 		    psize, psize, zio_decompress);
1748 	}
1749 
1750 	if (((BP_IS_PROTECTED(bp) && !(zio->io_flags & ZIO_FLAG_RAW_ENCRYPT)) ||
1751 	    BP_HAS_INDIRECT_MAC_CKSUM(bp)) &&
1752 	    zio->io_child_type == ZIO_CHILD_LOGICAL) {
1753 		zio_push_transform(zio, abd_alloc_sametype(zio->io_abd, psize),
1754 		    psize, psize, zio_decrypt);
1755 	}
1756 
1757 	if (BP_IS_EMBEDDED(bp) && BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA) {
1758 		int psize = BPE_GET_PSIZE(bp);
1759 		void *data = abd_borrow_buf(zio->io_abd, psize);
1760 
1761 		zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1762 		decode_embedded_bp_compressed(bp, data);
1763 		abd_return_buf_copy(zio->io_abd, data, psize);
1764 	} else {
1765 		ASSERT(!BP_IS_EMBEDDED(bp));
1766 	}
1767 
1768 	if (BP_GET_DEDUP(bp) && zio->io_child_type == ZIO_CHILD_LOGICAL)
1769 		zio->io_pipeline = ZIO_DDT_READ_PIPELINE;
1770 
1771 	return (zio);
1772 }
1773 
1774 static zio_t *
1775 zio_write_bp_init(zio_t *zio)
1776 {
1777 	if (!IO_IS_ALLOCATING(zio))
1778 		return (zio);
1779 
1780 	ASSERT(zio->io_child_type != ZIO_CHILD_DDT);
1781 
1782 	if (zio->io_bp_override) {
1783 		blkptr_t *bp = zio->io_bp;
1784 		zio_prop_t *zp = &zio->io_prop;
1785 
1786 		ASSERT(BP_GET_LOGICAL_BIRTH(bp) != zio->io_txg);
1787 
1788 		*bp = *zio->io_bp_override;
1789 		zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1790 
1791 		if (zp->zp_brtwrite)
1792 			return (zio);
1793 
1794 		ASSERT(!BP_GET_DEDUP(zio->io_bp_override));
1795 
1796 		if (BP_IS_EMBEDDED(bp))
1797 			return (zio);
1798 
1799 		/*
1800 		 * If we've been overridden and nopwrite is set then
1801 		 * set the flag accordingly to indicate that a nopwrite
1802 		 * has already occurred.
1803 		 */
1804 		if (!BP_IS_HOLE(bp) && zp->zp_nopwrite) {
1805 			ASSERT(!zp->zp_dedup);
1806 			ASSERT3U(BP_GET_CHECKSUM(bp), ==, zp->zp_checksum);
1807 			zio->io_flags |= ZIO_FLAG_NOPWRITE;
1808 			return (zio);
1809 		}
1810 
1811 		ASSERT(!zp->zp_nopwrite);
1812 
1813 		if (BP_IS_HOLE(bp) || !zp->zp_dedup)
1814 			return (zio);
1815 
1816 		ASSERT((zio_checksum_table[zp->zp_checksum].ci_flags &
1817 		    ZCHECKSUM_FLAG_DEDUP) || zp->zp_dedup_verify);
1818 
1819 		if (BP_GET_CHECKSUM(bp) == zp->zp_checksum &&
1820 		    !zp->zp_encrypt) {
1821 			BP_SET_DEDUP(bp, 1);
1822 			zio->io_pipeline |= ZIO_STAGE_DDT_WRITE;
1823 			return (zio);
1824 		}
1825 
1826 		/*
1827 		 * We were unable to handle this as an override bp, treat
1828 		 * it as a regular write I/O.
1829 		 */
1830 		zio->io_bp_override = NULL;
1831 		*bp = zio->io_bp_orig;
1832 		zio->io_pipeline = zio->io_orig_pipeline;
1833 	}
1834 
1835 	return (zio);
1836 }
1837 
1838 static zio_t *
1839 zio_write_compress(zio_t *zio)
1840 {
1841 	spa_t *spa = zio->io_spa;
1842 	zio_prop_t *zp = &zio->io_prop;
1843 	enum zio_compress compress = zp->zp_compress;
1844 	blkptr_t *bp = zio->io_bp;
1845 	uint64_t lsize = zio->io_lsize;
1846 	uint64_t psize = zio->io_size;
1847 	uint32_t pass = 1;
1848 
1849 	/*
1850 	 * If our children haven't all reached the ready stage,
1851 	 * wait for them and then repeat this pipeline stage.
1852 	 */
1853 	if (zio_wait_for_children(zio, ZIO_CHILD_LOGICAL_BIT |
1854 	    ZIO_CHILD_GANG_BIT, ZIO_WAIT_READY)) {
1855 		return (NULL);
1856 	}
1857 
1858 	if (!IO_IS_ALLOCATING(zio))
1859 		return (zio);
1860 
1861 	if (zio->io_children_ready != NULL) {
1862 		/*
1863 		 * Now that all our children are ready, run the callback
1864 		 * associated with this zio in case it wants to modify the
1865 		 * data to be written.
1866 		 */
1867 		ASSERT3U(zp->zp_level, >, 0);
1868 		zio->io_children_ready(zio);
1869 	}
1870 
1871 	ASSERT(zio->io_child_type != ZIO_CHILD_DDT);
1872 	ASSERT(zio->io_bp_override == NULL);
1873 
1874 	if (!BP_IS_HOLE(bp) && BP_GET_LOGICAL_BIRTH(bp) == zio->io_txg) {
1875 		/*
1876 		 * We're rewriting an existing block, which means we're
1877 		 * working on behalf of spa_sync().  For spa_sync() to
1878 		 * converge, it must eventually be the case that we don't
1879 		 * have to allocate new blocks.  But compression changes
1880 		 * the blocksize, which forces a reallocate, and makes
1881 		 * convergence take longer.  Therefore, after the first
1882 		 * few passes, stop compressing to ensure convergence.
1883 		 */
1884 		pass = spa_sync_pass(spa);
1885 
1886 		ASSERT(zio->io_txg == spa_syncing_txg(spa));
1887 		ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1888 		ASSERT(!BP_GET_DEDUP(bp));
1889 
1890 		if (pass >= zfs_sync_pass_dont_compress)
1891 			compress = ZIO_COMPRESS_OFF;
1892 
1893 		/* Make sure someone doesn't change their mind on overwrites */
1894 		ASSERT(BP_IS_EMBEDDED(bp) || BP_IS_GANG(bp) ||
1895 		    MIN(zp->zp_copies, spa_max_replication(spa))
1896 		    == BP_GET_NDVAS(bp));
1897 	}
1898 
1899 	/* If it's a compressed write that is not raw, compress the buffer. */
1900 	if (compress != ZIO_COMPRESS_OFF &&
1901 	    !(zio->io_flags & ZIO_FLAG_RAW_COMPRESS)) {
1902 		abd_t *cabd = NULL;
1903 		if (abd_cmp_zero(zio->io_abd, lsize) == 0)
1904 			psize = 0;
1905 		else if (compress == ZIO_COMPRESS_EMPTY)
1906 			psize = lsize;
1907 		else
1908 			psize = zio_compress_data(compress, zio->io_abd, &cabd,
1909 			    lsize,
1910 			    zio_get_compression_max_size(compress,
1911 			    spa->spa_gcd_alloc, spa->spa_min_alloc, lsize),
1912 			    zp->zp_complevel);
1913 		if (psize == 0) {
1914 			compress = ZIO_COMPRESS_OFF;
1915 		} else if (psize >= lsize) {
1916 			compress = ZIO_COMPRESS_OFF;
1917 			if (cabd != NULL)
1918 				abd_free(cabd);
1919 		} else if (!zp->zp_dedup && !zp->zp_encrypt &&
1920 		    psize <= BPE_PAYLOAD_SIZE &&
1921 		    zp->zp_level == 0 && !DMU_OT_HAS_FILL(zp->zp_type) &&
1922 		    spa_feature_is_enabled(spa, SPA_FEATURE_EMBEDDED_DATA)) {
1923 			void *cbuf = abd_borrow_buf_copy(cabd, lsize);
1924 			encode_embedded_bp_compressed(bp,
1925 			    cbuf, compress, lsize, psize);
1926 			BPE_SET_ETYPE(bp, BP_EMBEDDED_TYPE_DATA);
1927 			BP_SET_TYPE(bp, zio->io_prop.zp_type);
1928 			BP_SET_LEVEL(bp, zio->io_prop.zp_level);
1929 			abd_return_buf(cabd, cbuf, lsize);
1930 			abd_free(cabd);
1931 			BP_SET_LOGICAL_BIRTH(bp, zio->io_txg);
1932 			zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1933 			ASSERT(spa_feature_is_active(spa,
1934 			    SPA_FEATURE_EMBEDDED_DATA));
1935 			return (zio);
1936 		} else {
1937 			/*
1938 			 * Round compressed size up to the minimum allocation
1939 			 * size of the smallest-ashift device, and zero the
1940 			 * tail. This ensures that the compressed size of the
1941 			 * BP (and thus compressratio property) are correct,
1942 			 * in that we charge for the padding used to fill out
1943 			 * the last sector.
1944 			 */
1945 			size_t rounded = (size_t)zio_roundup_alloc_size(spa,
1946 			    psize);
1947 			if (rounded >= lsize) {
1948 				compress = ZIO_COMPRESS_OFF;
1949 				abd_free(cabd);
1950 				psize = lsize;
1951 			} else {
1952 				abd_zero_off(cabd, psize, rounded - psize);
1953 				psize = rounded;
1954 				zio_push_transform(zio, cabd,
1955 				    psize, lsize, NULL);
1956 			}
1957 		}
1958 
1959 		/*
1960 		 * We were unable to handle this as an override bp, treat
1961 		 * it as a regular write I/O.
1962 		 */
1963 		zio->io_bp_override = NULL;
1964 		*bp = zio->io_bp_orig;
1965 		zio->io_pipeline = zio->io_orig_pipeline;
1966 
1967 	} else if ((zio->io_flags & ZIO_FLAG_RAW_ENCRYPT) != 0 &&
1968 	    zp->zp_type == DMU_OT_DNODE) {
1969 		/*
1970 		 * The DMU actually relies on the zio layer's compression
1971 		 * to free metadnode blocks that have had all contained
1972 		 * dnodes freed. As a result, even when doing a raw
1973 		 * receive, we must check whether the block can be compressed
1974 		 * to a hole.
1975 		 */
1976 		if (abd_cmp_zero(zio->io_abd, lsize) == 0) {
1977 			psize = 0;
1978 			compress = ZIO_COMPRESS_OFF;
1979 		} else {
1980 			psize = lsize;
1981 		}
1982 	} else if (zio->io_flags & ZIO_FLAG_RAW_COMPRESS &&
1983 	    !(zio->io_flags & ZIO_FLAG_RAW_ENCRYPT)) {
1984 		/*
1985 		 * If we are raw receiving an encrypted dataset we should not
1986 		 * take this codepath because it will change the on-disk block
1987 		 * and decryption will fail.
1988 		 */
1989 		size_t rounded = MIN((size_t)zio_roundup_alloc_size(spa, psize),
1990 		    lsize);
1991 
1992 		if (rounded != psize) {
1993 			abd_t *cdata = abd_alloc_linear(rounded, B_TRUE);
1994 			abd_zero_off(cdata, psize, rounded - psize);
1995 			abd_copy_off(cdata, zio->io_abd, 0, 0, psize);
1996 			psize = rounded;
1997 			zio_push_transform(zio, cdata,
1998 			    psize, rounded, NULL);
1999 		}
2000 	} else {
2001 		ASSERT3U(psize, !=, 0);
2002 	}
2003 
2004 	/*
2005 	 * The final pass of spa_sync() must be all rewrites, but the first
2006 	 * few passes offer a trade-off: allocating blocks defers convergence,
2007 	 * but newly allocated blocks are sequential, so they can be written
2008 	 * to disk faster.  Therefore, we allow the first few passes of
2009 	 * spa_sync() to allocate new blocks, but force rewrites after that.
2010 	 * There should only be a handful of blocks after pass 1 in any case.
2011 	 */
2012 	if (!BP_IS_HOLE(bp) && BP_GET_LOGICAL_BIRTH(bp) == zio->io_txg &&
2013 	    BP_GET_PSIZE(bp) == psize &&
2014 	    pass >= zfs_sync_pass_rewrite) {
2015 		VERIFY3U(psize, !=, 0);
2016 		enum zio_stage gang_stages = zio->io_pipeline & ZIO_GANG_STAGES;
2017 
2018 		zio->io_pipeline = ZIO_REWRITE_PIPELINE | gang_stages;
2019 		zio->io_flags |= ZIO_FLAG_IO_REWRITE;
2020 	} else {
2021 		BP_ZERO(bp);
2022 		zio->io_pipeline = ZIO_WRITE_PIPELINE;
2023 	}
2024 
2025 	if (psize == 0) {
2026 		if (BP_GET_LOGICAL_BIRTH(&zio->io_bp_orig) != 0 &&
2027 		    spa_feature_is_active(spa, SPA_FEATURE_HOLE_BIRTH)) {
2028 			BP_SET_LSIZE(bp, lsize);
2029 			BP_SET_TYPE(bp, zp->zp_type);
2030 			BP_SET_LEVEL(bp, zp->zp_level);
2031 			BP_SET_BIRTH(bp, zio->io_txg, 0);
2032 		}
2033 		zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
2034 	} else {
2035 		ASSERT(zp->zp_checksum != ZIO_CHECKSUM_GANG_HEADER);
2036 		BP_SET_LSIZE(bp, lsize);
2037 		BP_SET_TYPE(bp, zp->zp_type);
2038 		BP_SET_LEVEL(bp, zp->zp_level);
2039 		BP_SET_PSIZE(bp, psize);
2040 		BP_SET_COMPRESS(bp, compress);
2041 		BP_SET_CHECKSUM(bp, zp->zp_checksum);
2042 		BP_SET_DEDUP(bp, zp->zp_dedup);
2043 		BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
2044 		if (zp->zp_dedup) {
2045 			ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
2046 			ASSERT(!(zio->io_flags & ZIO_FLAG_IO_REWRITE));
2047 			ASSERT(!zp->zp_encrypt ||
2048 			    DMU_OT_IS_ENCRYPTED(zp->zp_type));
2049 			zio->io_pipeline = ZIO_DDT_WRITE_PIPELINE;
2050 		}
2051 		if (zp->zp_nopwrite) {
2052 			ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
2053 			ASSERT(!(zio->io_flags & ZIO_FLAG_IO_REWRITE));
2054 			zio->io_pipeline |= ZIO_STAGE_NOP_WRITE;
2055 		}
2056 	}
2057 	return (zio);
2058 }
2059 
2060 static zio_t *
2061 zio_free_bp_init(zio_t *zio)
2062 {
2063 	blkptr_t *bp = zio->io_bp;
2064 
2065 	if (zio->io_child_type == ZIO_CHILD_LOGICAL) {
2066 		if (BP_GET_DEDUP(bp))
2067 			zio->io_pipeline = ZIO_DDT_FREE_PIPELINE;
2068 	}
2069 
2070 	ASSERT3P(zio->io_bp, ==, &zio->io_bp_copy);
2071 
2072 	return (zio);
2073 }
2074 
2075 /*
2076  * ==========================================================================
2077  * Execute the I/O pipeline
2078  * ==========================================================================
2079  */
2080 
2081 static void
2082 zio_taskq_dispatch(zio_t *zio, zio_taskq_type_t q, boolean_t cutinline)
2083 {
2084 	spa_t *spa = zio->io_spa;
2085 	zio_type_t t = zio->io_type;
2086 
2087 	/*
2088 	 * If we're a config writer or a probe, the normal issue and
2089 	 * interrupt threads may all be blocked waiting for the config lock.
2090 	 * In this case, select the otherwise-unused taskq for ZIO_TYPE_NULL.
2091 	 */
2092 	if (zio->io_flags & (ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_PROBE))
2093 		t = ZIO_TYPE_NULL;
2094 
2095 	/*
2096 	 * A similar issue exists for the L2ARC write thread until L2ARC 2.0.
2097 	 */
2098 	if (t == ZIO_TYPE_WRITE && zio->io_vd && zio->io_vd->vdev_aux)
2099 		t = ZIO_TYPE_NULL;
2100 
2101 	/*
2102 	 * If this is a high priority I/O, then use the high priority taskq if
2103 	 * available or cut the line otherwise.
2104 	 */
2105 	if (zio->io_priority == ZIO_PRIORITY_SYNC_WRITE) {
2106 		if (spa->spa_zio_taskq[t][q + 1].stqs_count != 0)
2107 			q++;
2108 		else
2109 			cutinline = B_TRUE;
2110 	}
2111 
2112 	ASSERT3U(q, <, ZIO_TASKQ_TYPES);
2113 
2114 	spa_taskq_dispatch(spa, t, q, zio_execute, zio, cutinline);
2115 }
2116 
2117 static boolean_t
2118 zio_taskq_member(zio_t *zio, zio_taskq_type_t q)
2119 {
2120 	spa_t *spa = zio->io_spa;
2121 
2122 	taskq_t *tq = taskq_of_curthread();
2123 
2124 	for (zio_type_t t = 0; t < ZIO_TYPES; t++) {
2125 		spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
2126 		uint_t i;
2127 		for (i = 0; i < tqs->stqs_count; i++) {
2128 			if (tqs->stqs_taskq[i] == tq)
2129 				return (B_TRUE);
2130 		}
2131 	}
2132 
2133 	return (B_FALSE);
2134 }
2135 
2136 static zio_t *
2137 zio_issue_async(zio_t *zio)
2138 {
2139 	ASSERT((zio->io_type != ZIO_TYPE_WRITE) || ZIO_HAS_ALLOCATOR(zio));
2140 	zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE, B_FALSE);
2141 	return (NULL);
2142 }
2143 
2144 void
2145 zio_interrupt(void *zio)
2146 {
2147 	zio_taskq_dispatch(zio, ZIO_TASKQ_INTERRUPT, B_FALSE);
2148 }
2149 
2150 void
2151 zio_delay_interrupt(zio_t *zio)
2152 {
2153 	/*
2154 	 * The timeout_generic() function isn't defined in userspace, so
2155 	 * rather than trying to implement the function, the zio delay
2156 	 * functionality has been disabled for userspace builds.
2157 	 */
2158 
2159 #ifdef _KERNEL
2160 	/*
2161 	 * If io_target_timestamp is zero, then no delay has been registered
2162 	 * for this IO, thus jump to the end of this function and "skip" the
2163 	 * delay; issuing it directly to the zio layer.
2164 	 */
2165 	if (zio->io_target_timestamp != 0) {
2166 		hrtime_t now = gethrtime();
2167 
2168 		if (now >= zio->io_target_timestamp) {
2169 			/*
2170 			 * This IO has already taken longer than the target
2171 			 * delay to complete, so we don't want to delay it
2172 			 * any longer; we "miss" the delay and issue it
2173 			 * directly to the zio layer. This is likely due to
2174 			 * the target latency being set to a value less than
2175 			 * the underlying hardware can satisfy (e.g. delay
2176 			 * set to 1ms, but the disks take 10ms to complete an
2177 			 * IO request).
2178 			 */
2179 
2180 			DTRACE_PROBE2(zio__delay__miss, zio_t *, zio,
2181 			    hrtime_t, now);
2182 
2183 			zio_interrupt(zio);
2184 		} else {
2185 			taskqid_t tid;
2186 			hrtime_t diff = zio->io_target_timestamp - now;
2187 			clock_t expire_at_tick = ddi_get_lbolt() +
2188 			    NSEC_TO_TICK(diff);
2189 
2190 			DTRACE_PROBE3(zio__delay__hit, zio_t *, zio,
2191 			    hrtime_t, now, hrtime_t, diff);
2192 
2193 			if (NSEC_TO_TICK(diff) == 0) {
2194 				/* Our delay is less than a jiffy - just spin */
2195 				zfs_sleep_until(zio->io_target_timestamp);
2196 				zio_interrupt(zio);
2197 			} else {
2198 				/*
2199 				 * Use taskq_dispatch_delay() in the place of
2200 				 * OpenZFS's timeout_generic().
2201 				 */
2202 				tid = taskq_dispatch_delay(system_taskq,
2203 				    zio_interrupt, zio, TQ_NOSLEEP,
2204 				    expire_at_tick);
2205 				if (tid == TASKQID_INVALID) {
2206 					/*
2207 					 * Couldn't allocate a task.  Just
2208 					 * finish the zio without a delay.
2209 					 */
2210 					zio_interrupt(zio);
2211 				}
2212 			}
2213 		}
2214 		return;
2215 	}
2216 #endif
2217 	DTRACE_PROBE1(zio__delay__skip, zio_t *, zio);
2218 	zio_interrupt(zio);
2219 }
2220 
2221 static void
2222 zio_deadman_impl(zio_t *pio, int ziodepth)
2223 {
2224 	zio_t *cio, *cio_next;
2225 	zio_link_t *zl = NULL;
2226 	vdev_t *vd = pio->io_vd;
2227 
2228 	if (zio_deadman_log_all || (vd != NULL && vd->vdev_ops->vdev_op_leaf)) {
2229 		vdev_queue_t *vq = vd ? &vd->vdev_queue : NULL;
2230 		zbookmark_phys_t *zb = &pio->io_bookmark;
2231 		uint64_t delta = gethrtime() - pio->io_timestamp;
2232 		uint64_t failmode = spa_get_deadman_failmode(pio->io_spa);
2233 
2234 		zfs_dbgmsg("slow zio[%d]: zio=%px timestamp=%llu "
2235 		    "delta=%llu queued=%llu io=%llu "
2236 		    "path=%s "
2237 		    "last=%llu type=%d "
2238 		    "priority=%d flags=0x%llx stage=0x%x "
2239 		    "pipeline=0x%x pipeline-trace=0x%x "
2240 		    "objset=%llu object=%llu "
2241 		    "level=%llu blkid=%llu "
2242 		    "offset=%llu size=%llu "
2243 		    "error=%d",
2244 		    ziodepth, pio, pio->io_timestamp,
2245 		    (u_longlong_t)delta, pio->io_delta, pio->io_delay,
2246 		    vd ? vd->vdev_path : "NULL",
2247 		    vq ? vq->vq_io_complete_ts : 0, pio->io_type,
2248 		    pio->io_priority, (u_longlong_t)pio->io_flags,
2249 		    pio->io_stage, pio->io_pipeline, pio->io_pipeline_trace,
2250 		    (u_longlong_t)zb->zb_objset, (u_longlong_t)zb->zb_object,
2251 		    (u_longlong_t)zb->zb_level, (u_longlong_t)zb->zb_blkid,
2252 		    (u_longlong_t)pio->io_offset, (u_longlong_t)pio->io_size,
2253 		    pio->io_error);
2254 		(void) zfs_ereport_post(FM_EREPORT_ZFS_DEADMAN,
2255 		    pio->io_spa, vd, zb, pio, 0);
2256 
2257 		if (failmode == ZIO_FAILURE_MODE_CONTINUE &&
2258 		    taskq_empty_ent(&pio->io_tqent)) {
2259 			zio_interrupt(pio);
2260 		}
2261 	}
2262 
2263 	mutex_enter(&pio->io_lock);
2264 	for (cio = zio_walk_children(pio, &zl); cio != NULL; cio = cio_next) {
2265 		cio_next = zio_walk_children(pio, &zl);
2266 		zio_deadman_impl(cio, ziodepth + 1);
2267 	}
2268 	mutex_exit(&pio->io_lock);
2269 }
2270 
2271 /*
2272  * Log the critical information describing this zio and all of its children
2273  * using the zfs_dbgmsg() interface then post deadman event for the ZED.
2274  */
2275 void
2276 zio_deadman(zio_t *pio, const char *tag)
2277 {
2278 	spa_t *spa = pio->io_spa;
2279 	char *name = spa_name(spa);
2280 
2281 	if (!zfs_deadman_enabled || spa_suspended(spa))
2282 		return;
2283 
2284 	zio_deadman_impl(pio, 0);
2285 
2286 	switch (spa_get_deadman_failmode(spa)) {
2287 	case ZIO_FAILURE_MODE_WAIT:
2288 		zfs_dbgmsg("%s waiting for hung I/O to pool '%s'", tag, name);
2289 		break;
2290 
2291 	case ZIO_FAILURE_MODE_CONTINUE:
2292 		zfs_dbgmsg("%s restarting hung I/O for pool '%s'", tag, name);
2293 		break;
2294 
2295 	case ZIO_FAILURE_MODE_PANIC:
2296 		fm_panic("%s determined I/O to pool '%s' is hung.", tag, name);
2297 		break;
2298 	}
2299 }
2300 
2301 /*
2302  * Execute the I/O pipeline until one of the following occurs:
2303  * (1) the I/O completes; (2) the pipeline stalls waiting for
2304  * dependent child I/Os; (3) the I/O issues, so we're waiting
2305  * for an I/O completion interrupt; (4) the I/O is delegated by
2306  * vdev-level caching or aggregation; (5) the I/O is deferred
2307  * due to vdev-level queueing; (6) the I/O is handed off to
2308  * another thread.  In all cases, the pipeline stops whenever
2309  * there's no CPU work; it never burns a thread in cv_wait_io().
2310  *
2311  * There's no locking on io_stage because there's no legitimate way
2312  * for multiple threads to be attempting to process the same I/O.
2313  */
2314 static zio_pipe_stage_t *zio_pipeline[];
2315 
2316 /*
2317  * zio_execute() is a wrapper around the static function
2318  * __zio_execute() so that we can force  __zio_execute() to be
2319  * inlined.  This reduces stack overhead which is important
2320  * because __zio_execute() is called recursively in several zio
2321  * code paths.  zio_execute() itself cannot be inlined because
2322  * it is externally visible.
2323  */
2324 void
2325 zio_execute(void *zio)
2326 {
2327 	fstrans_cookie_t cookie;
2328 
2329 	cookie = spl_fstrans_mark();
2330 	__zio_execute(zio);
2331 	spl_fstrans_unmark(cookie);
2332 }
2333 
2334 /*
2335  * Used to determine if in the current context the stack is sized large
2336  * enough to allow zio_execute() to be called recursively.  A minimum
2337  * stack size of 16K is required to avoid needing to re-dispatch the zio.
2338  */
2339 static boolean_t
2340 zio_execute_stack_check(zio_t *zio)
2341 {
2342 #if !defined(HAVE_LARGE_STACKS)
2343 	dsl_pool_t *dp = spa_get_dsl(zio->io_spa);
2344 
2345 	/* Executing in txg_sync_thread() context. */
2346 	if (dp && curthread == dp->dp_tx.tx_sync_thread)
2347 		return (B_TRUE);
2348 
2349 	/* Pool initialization outside of zio_taskq context. */
2350 	if (dp && spa_is_initializing(dp->dp_spa) &&
2351 	    !zio_taskq_member(zio, ZIO_TASKQ_ISSUE) &&
2352 	    !zio_taskq_member(zio, ZIO_TASKQ_ISSUE_HIGH))
2353 		return (B_TRUE);
2354 #else
2355 	(void) zio;
2356 #endif /* HAVE_LARGE_STACKS */
2357 
2358 	return (B_FALSE);
2359 }
2360 
2361 __attribute__((always_inline))
2362 static inline void
2363 __zio_execute(zio_t *zio)
2364 {
2365 	ASSERT3U(zio->io_queued_timestamp, >, 0);
2366 
2367 	while (zio->io_stage < ZIO_STAGE_DONE) {
2368 		enum zio_stage pipeline = zio->io_pipeline;
2369 		enum zio_stage stage = zio->io_stage;
2370 
2371 		zio->io_executor = curthread;
2372 
2373 		ASSERT(!MUTEX_HELD(&zio->io_lock));
2374 		ASSERT(ISP2(stage));
2375 		ASSERT(zio->io_stall == NULL);
2376 
2377 		do {
2378 			stage <<= 1;
2379 		} while ((stage & pipeline) == 0);
2380 
2381 		ASSERT(stage <= ZIO_STAGE_DONE);
2382 
2383 		/*
2384 		 * If we are in interrupt context and this pipeline stage
2385 		 * will grab a config lock that is held across I/O,
2386 		 * or may wait for an I/O that needs an interrupt thread
2387 		 * to complete, issue async to avoid deadlock.
2388 		 *
2389 		 * For VDEV_IO_START, we cut in line so that the io will
2390 		 * be sent to disk promptly.
2391 		 */
2392 		if ((stage & ZIO_BLOCKING_STAGES) && zio->io_vd == NULL &&
2393 		    zio_taskq_member(zio, ZIO_TASKQ_INTERRUPT)) {
2394 			boolean_t cut = (stage == ZIO_STAGE_VDEV_IO_START) ?
2395 			    zio_requeue_io_start_cut_in_line : B_FALSE;
2396 			zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE, cut);
2397 			return;
2398 		}
2399 
2400 		/*
2401 		 * If the current context doesn't have large enough stacks
2402 		 * the zio must be issued asynchronously to prevent overflow.
2403 		 */
2404 		if (zio_execute_stack_check(zio)) {
2405 			boolean_t cut = (stage == ZIO_STAGE_VDEV_IO_START) ?
2406 			    zio_requeue_io_start_cut_in_line : B_FALSE;
2407 			zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE, cut);
2408 			return;
2409 		}
2410 
2411 		zio->io_stage = stage;
2412 		zio->io_pipeline_trace |= zio->io_stage;
2413 
2414 		/*
2415 		 * The zio pipeline stage returns the next zio to execute
2416 		 * (typically the same as this one), or NULL if we should
2417 		 * stop.
2418 		 */
2419 		zio = zio_pipeline[highbit64(stage) - 1](zio);
2420 
2421 		if (zio == NULL)
2422 			return;
2423 	}
2424 }
2425 
2426 
2427 /*
2428  * ==========================================================================
2429  * Initiate I/O, either sync or async
2430  * ==========================================================================
2431  */
2432 int
2433 zio_wait(zio_t *zio)
2434 {
2435 	/*
2436 	 * Some routines, like zio_free_sync(), may return a NULL zio
2437 	 * to avoid the performance overhead of creating and then destroying
2438 	 * an unneeded zio.  For the callers' simplicity, we accept a NULL
2439 	 * zio and ignore it.
2440 	 */
2441 	if (zio == NULL)
2442 		return (0);
2443 
2444 	long timeout = MSEC_TO_TICK(zfs_deadman_ziotime_ms);
2445 	int error;
2446 
2447 	ASSERT3S(zio->io_stage, ==, ZIO_STAGE_OPEN);
2448 	ASSERT3P(zio->io_executor, ==, NULL);
2449 
2450 	zio->io_waiter = curthread;
2451 	ASSERT0(zio->io_queued_timestamp);
2452 	zio->io_queued_timestamp = gethrtime();
2453 
2454 	if (zio->io_type == ZIO_TYPE_WRITE) {
2455 		spa_select_allocator(zio);
2456 	}
2457 	__zio_execute(zio);
2458 
2459 	mutex_enter(&zio->io_lock);
2460 	while (zio->io_executor != NULL) {
2461 		error = cv_timedwait_io(&zio->io_cv, &zio->io_lock,
2462 		    ddi_get_lbolt() + timeout);
2463 
2464 		if (zfs_deadman_enabled && error == -1 &&
2465 		    gethrtime() - zio->io_queued_timestamp >
2466 		    spa_deadman_ziotime(zio->io_spa)) {
2467 			mutex_exit(&zio->io_lock);
2468 			timeout = MSEC_TO_TICK(zfs_deadman_checktime_ms);
2469 			zio_deadman(zio, FTAG);
2470 			mutex_enter(&zio->io_lock);
2471 		}
2472 	}
2473 	mutex_exit(&zio->io_lock);
2474 
2475 	error = zio->io_error;
2476 	zio_destroy(zio);
2477 
2478 	return (error);
2479 }
2480 
2481 void
2482 zio_nowait(zio_t *zio)
2483 {
2484 	/*
2485 	 * See comment in zio_wait().
2486 	 */
2487 	if (zio == NULL)
2488 		return;
2489 
2490 	ASSERT3P(zio->io_executor, ==, NULL);
2491 
2492 	if (zio->io_child_type == ZIO_CHILD_LOGICAL &&
2493 	    list_is_empty(&zio->io_parent_list)) {
2494 		zio_t *pio;
2495 
2496 		/*
2497 		 * This is a logical async I/O with no parent to wait for it.
2498 		 * We add it to the spa_async_root_zio "Godfather" I/O which
2499 		 * will ensure they complete prior to unloading the pool.
2500 		 */
2501 		spa_t *spa = zio->io_spa;
2502 		pio = spa->spa_async_zio_root[CPU_SEQID_UNSTABLE];
2503 
2504 		zio_add_child(pio, zio);
2505 	}
2506 
2507 	ASSERT0(zio->io_queued_timestamp);
2508 	zio->io_queued_timestamp = gethrtime();
2509 	if (zio->io_type == ZIO_TYPE_WRITE) {
2510 		spa_select_allocator(zio);
2511 	}
2512 	__zio_execute(zio);
2513 }
2514 
2515 /*
2516  * ==========================================================================
2517  * Reexecute, cancel, or suspend/resume failed I/O
2518  * ==========================================================================
2519  */
2520 
2521 static void
2522 zio_reexecute(void *arg)
2523 {
2524 	zio_t *pio = arg;
2525 	zio_t *cio, *cio_next, *gio;
2526 
2527 	ASSERT(pio->io_child_type == ZIO_CHILD_LOGICAL);
2528 	ASSERT(pio->io_orig_stage == ZIO_STAGE_OPEN);
2529 	ASSERT(pio->io_gang_leader == NULL);
2530 	ASSERT(pio->io_gang_tree == NULL);
2531 
2532 	mutex_enter(&pio->io_lock);
2533 	pio->io_flags = pio->io_orig_flags;
2534 	pio->io_stage = pio->io_orig_stage;
2535 	pio->io_pipeline = pio->io_orig_pipeline;
2536 	pio->io_reexecute = 0;
2537 	pio->io_flags |= ZIO_FLAG_REEXECUTED;
2538 	pio->io_pipeline_trace = 0;
2539 	pio->io_error = 0;
2540 	pio->io_state[ZIO_WAIT_READY] = (pio->io_stage >= ZIO_STAGE_READY) ||
2541 	    (pio->io_pipeline & ZIO_STAGE_READY) == 0;
2542 	pio->io_state[ZIO_WAIT_DONE] = (pio->io_stage >= ZIO_STAGE_DONE);
2543 	zio_link_t *zl = NULL;
2544 	while ((gio = zio_walk_parents(pio, &zl)) != NULL) {
2545 		for (int w = 0; w < ZIO_WAIT_TYPES; w++) {
2546 			gio->io_children[pio->io_child_type][w] +=
2547 			    !pio->io_state[w];
2548 		}
2549 	}
2550 	for (int c = 0; c < ZIO_CHILD_TYPES; c++)
2551 		pio->io_child_error[c] = 0;
2552 
2553 	if (IO_IS_ALLOCATING(pio))
2554 		BP_ZERO(pio->io_bp);
2555 
2556 	/*
2557 	 * As we reexecute pio's children, new children could be created.
2558 	 * New children go to the head of pio's io_child_list, however,
2559 	 * so we will (correctly) not reexecute them.  The key is that
2560 	 * the remainder of pio's io_child_list, from 'cio_next' onward,
2561 	 * cannot be affected by any side effects of reexecuting 'cio'.
2562 	 */
2563 	zl = NULL;
2564 	for (cio = zio_walk_children(pio, &zl); cio != NULL; cio = cio_next) {
2565 		cio_next = zio_walk_children(pio, &zl);
2566 		mutex_exit(&pio->io_lock);
2567 		zio_reexecute(cio);
2568 		mutex_enter(&pio->io_lock);
2569 	}
2570 	mutex_exit(&pio->io_lock);
2571 
2572 	/*
2573 	 * Now that all children have been reexecuted, execute the parent.
2574 	 * We don't reexecute "The Godfather" I/O here as it's the
2575 	 * responsibility of the caller to wait on it.
2576 	 */
2577 	if (!(pio->io_flags & ZIO_FLAG_GODFATHER)) {
2578 		pio->io_queued_timestamp = gethrtime();
2579 		__zio_execute(pio);
2580 	}
2581 }
2582 
2583 void
2584 zio_suspend(spa_t *spa, zio_t *zio, zio_suspend_reason_t reason)
2585 {
2586 	if (spa_get_failmode(spa) == ZIO_FAILURE_MODE_PANIC)
2587 		fm_panic("Pool '%s' has encountered an uncorrectable I/O "
2588 		    "failure and the failure mode property for this pool "
2589 		    "is set to panic.", spa_name(spa));
2590 
2591 	if (reason != ZIO_SUSPEND_MMP) {
2592 		cmn_err(CE_WARN, "Pool '%s' has encountered an uncorrectable "
2593 		    "I/O failure and has been suspended.", spa_name(spa));
2594 	}
2595 
2596 	(void) zfs_ereport_post(FM_EREPORT_ZFS_IO_FAILURE, spa, NULL,
2597 	    NULL, NULL, 0);
2598 
2599 	mutex_enter(&spa->spa_suspend_lock);
2600 
2601 	if (spa->spa_suspend_zio_root == NULL)
2602 		spa->spa_suspend_zio_root = zio_root(spa, NULL, NULL,
2603 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2604 		    ZIO_FLAG_GODFATHER);
2605 
2606 	spa->spa_suspended = reason;
2607 
2608 	if (zio != NULL) {
2609 		ASSERT(!(zio->io_flags & ZIO_FLAG_GODFATHER));
2610 		ASSERT(zio != spa->spa_suspend_zio_root);
2611 		ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
2612 		ASSERT(zio_unique_parent(zio) == NULL);
2613 		ASSERT(zio->io_stage == ZIO_STAGE_DONE);
2614 		zio_add_child(spa->spa_suspend_zio_root, zio);
2615 	}
2616 
2617 	mutex_exit(&spa->spa_suspend_lock);
2618 }
2619 
2620 int
2621 zio_resume(spa_t *spa)
2622 {
2623 	zio_t *pio;
2624 
2625 	/*
2626 	 * Reexecute all previously suspended i/o.
2627 	 */
2628 	mutex_enter(&spa->spa_suspend_lock);
2629 	if (spa->spa_suspended != ZIO_SUSPEND_NONE)
2630 		cmn_err(CE_WARN, "Pool '%s' was suspended and is being "
2631 		    "resumed. Failed I/O will be retried.",
2632 		    spa_name(spa));
2633 	spa->spa_suspended = ZIO_SUSPEND_NONE;
2634 	cv_broadcast(&spa->spa_suspend_cv);
2635 	pio = spa->spa_suspend_zio_root;
2636 	spa->spa_suspend_zio_root = NULL;
2637 	mutex_exit(&spa->spa_suspend_lock);
2638 
2639 	if (pio == NULL)
2640 		return (0);
2641 
2642 	zio_reexecute(pio);
2643 	return (zio_wait(pio));
2644 }
2645 
2646 void
2647 zio_resume_wait(spa_t *spa)
2648 {
2649 	mutex_enter(&spa->spa_suspend_lock);
2650 	while (spa_suspended(spa))
2651 		cv_wait(&spa->spa_suspend_cv, &spa->spa_suspend_lock);
2652 	mutex_exit(&spa->spa_suspend_lock);
2653 }
2654 
2655 /*
2656  * ==========================================================================
2657  * Gang blocks.
2658  *
2659  * A gang block is a collection of small blocks that looks to the DMU
2660  * like one large block.  When zio_dva_allocate() cannot find a block
2661  * of the requested size, due to either severe fragmentation or the pool
2662  * being nearly full, it calls zio_write_gang_block() to construct the
2663  * block from smaller fragments.
2664  *
2665  * A gang block consists of a gang header (zio_gbh_phys_t) and up to
2666  * three (SPA_GBH_NBLKPTRS) gang members.  The gang header is just like
2667  * an indirect block: it's an array of block pointers.  It consumes
2668  * only one sector and hence is allocatable regardless of fragmentation.
2669  * The gang header's bps point to its gang members, which hold the data.
2670  *
2671  * Gang blocks are self-checksumming, using the bp's <vdev, offset, txg>
2672  * as the verifier to ensure uniqueness of the SHA256 checksum.
2673  * Critically, the gang block bp's blk_cksum is the checksum of the data,
2674  * not the gang header.  This ensures that data block signatures (needed for
2675  * deduplication) are independent of how the block is physically stored.
2676  *
2677  * Gang blocks can be nested: a gang member may itself be a gang block.
2678  * Thus every gang block is a tree in which root and all interior nodes are
2679  * gang headers, and the leaves are normal blocks that contain user data.
2680  * The root of the gang tree is called the gang leader.
2681  *
2682  * To perform any operation (read, rewrite, free, claim) on a gang block,
2683  * zio_gang_assemble() first assembles the gang tree (minus data leaves)
2684  * in the io_gang_tree field of the original logical i/o by recursively
2685  * reading the gang leader and all gang headers below it.  This yields
2686  * an in-core tree containing the contents of every gang header and the
2687  * bps for every constituent of the gang block.
2688  *
2689  * With the gang tree now assembled, zio_gang_issue() just walks the gang tree
2690  * and invokes a callback on each bp.  To free a gang block, zio_gang_issue()
2691  * calls zio_free_gang() -- a trivial wrapper around zio_free() -- for each bp.
2692  * zio_claim_gang() provides a similarly trivial wrapper for zio_claim().
2693  * zio_read_gang() is a wrapper around zio_read() that omits reading gang
2694  * headers, since we already have those in io_gang_tree.  zio_rewrite_gang()
2695  * performs a zio_rewrite() of the data or, for gang headers, a zio_rewrite()
2696  * of the gang header plus zio_checksum_compute() of the data to update the
2697  * gang header's blk_cksum as described above.
2698  *
2699  * The two-phase assemble/issue model solves the problem of partial failure --
2700  * what if you'd freed part of a gang block but then couldn't read the
2701  * gang header for another part?  Assembling the entire gang tree first
2702  * ensures that all the necessary gang header I/O has succeeded before
2703  * starting the actual work of free, claim, or write.  Once the gang tree
2704  * is assembled, free and claim are in-memory operations that cannot fail.
2705  *
2706  * In the event that a gang write fails, zio_dva_unallocate() walks the
2707  * gang tree to immediately free (i.e. insert back into the space map)
2708  * everything we've allocated.  This ensures that we don't get ENOSPC
2709  * errors during repeated suspend/resume cycles due to a flaky device.
2710  *
2711  * Gang rewrites only happen during sync-to-convergence.  If we can't assemble
2712  * the gang tree, we won't modify the block, so we can safely defer the free
2713  * (knowing that the block is still intact).  If we *can* assemble the gang
2714  * tree, then even if some of the rewrites fail, zio_dva_unallocate() will free
2715  * each constituent bp and we can allocate a new block on the next sync pass.
2716  *
2717  * In all cases, the gang tree allows complete recovery from partial failure.
2718  * ==========================================================================
2719  */
2720 
2721 static void
2722 zio_gang_issue_func_done(zio_t *zio)
2723 {
2724 	abd_free(zio->io_abd);
2725 }
2726 
2727 static zio_t *
2728 zio_read_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, abd_t *data,
2729     uint64_t offset)
2730 {
2731 	if (gn != NULL)
2732 		return (pio);
2733 
2734 	return (zio_read(pio, pio->io_spa, bp, abd_get_offset(data, offset),
2735 	    BP_GET_PSIZE(bp), zio_gang_issue_func_done,
2736 	    NULL, pio->io_priority, ZIO_GANG_CHILD_FLAGS(pio),
2737 	    &pio->io_bookmark));
2738 }
2739 
2740 static zio_t *
2741 zio_rewrite_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, abd_t *data,
2742     uint64_t offset)
2743 {
2744 	zio_t *zio;
2745 
2746 	if (gn != NULL) {
2747 		abd_t *gbh_abd =
2748 		    abd_get_from_buf(gn->gn_gbh, SPA_GANGBLOCKSIZE);
2749 		zio = zio_rewrite(pio, pio->io_spa, pio->io_txg, bp,
2750 		    gbh_abd, SPA_GANGBLOCKSIZE, zio_gang_issue_func_done, NULL,
2751 		    pio->io_priority, ZIO_GANG_CHILD_FLAGS(pio),
2752 		    &pio->io_bookmark);
2753 		/*
2754 		 * As we rewrite each gang header, the pipeline will compute
2755 		 * a new gang block header checksum for it; but no one will
2756 		 * compute a new data checksum, so we do that here.  The one
2757 		 * exception is the gang leader: the pipeline already computed
2758 		 * its data checksum because that stage precedes gang assembly.
2759 		 * (Presently, nothing actually uses interior data checksums;
2760 		 * this is just good hygiene.)
2761 		 */
2762 		if (gn != pio->io_gang_leader->io_gang_tree) {
2763 			abd_t *buf = abd_get_offset(data, offset);
2764 
2765 			zio_checksum_compute(zio, BP_GET_CHECKSUM(bp),
2766 			    buf, BP_GET_PSIZE(bp));
2767 
2768 			abd_free(buf);
2769 		}
2770 		/*
2771 		 * If we are here to damage data for testing purposes,
2772 		 * leave the GBH alone so that we can detect the damage.
2773 		 */
2774 		if (pio->io_gang_leader->io_flags & ZIO_FLAG_INDUCE_DAMAGE)
2775 			zio->io_pipeline &= ~ZIO_VDEV_IO_STAGES;
2776 	} else {
2777 		zio = zio_rewrite(pio, pio->io_spa, pio->io_txg, bp,
2778 		    abd_get_offset(data, offset), BP_GET_PSIZE(bp),
2779 		    zio_gang_issue_func_done, NULL, pio->io_priority,
2780 		    ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
2781 	}
2782 
2783 	return (zio);
2784 }
2785 
2786 static zio_t *
2787 zio_free_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, abd_t *data,
2788     uint64_t offset)
2789 {
2790 	(void) gn, (void) data, (void) offset;
2791 
2792 	zio_t *zio = zio_free_sync(pio, pio->io_spa, pio->io_txg, bp,
2793 	    ZIO_GANG_CHILD_FLAGS(pio));
2794 	if (zio == NULL) {
2795 		zio = zio_null(pio, pio->io_spa,
2796 		    NULL, NULL, NULL, ZIO_GANG_CHILD_FLAGS(pio));
2797 	}
2798 	return (zio);
2799 }
2800 
2801 static zio_t *
2802 zio_claim_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, abd_t *data,
2803     uint64_t offset)
2804 {
2805 	(void) gn, (void) data, (void) offset;
2806 	return (zio_claim(pio, pio->io_spa, pio->io_txg, bp,
2807 	    NULL, NULL, ZIO_GANG_CHILD_FLAGS(pio)));
2808 }
2809 
2810 static zio_gang_issue_func_t *zio_gang_issue_func[ZIO_TYPES] = {
2811 	NULL,
2812 	zio_read_gang,
2813 	zio_rewrite_gang,
2814 	zio_free_gang,
2815 	zio_claim_gang,
2816 	NULL
2817 };
2818 
2819 static void zio_gang_tree_assemble_done(zio_t *zio);
2820 
2821 static zio_gang_node_t *
2822 zio_gang_node_alloc(zio_gang_node_t **gnpp)
2823 {
2824 	zio_gang_node_t *gn;
2825 
2826 	ASSERT(*gnpp == NULL);
2827 
2828 	gn = kmem_zalloc(sizeof (*gn), KM_SLEEP);
2829 	gn->gn_gbh = zio_buf_alloc(SPA_GANGBLOCKSIZE);
2830 	*gnpp = gn;
2831 
2832 	return (gn);
2833 }
2834 
2835 static void
2836 zio_gang_node_free(zio_gang_node_t **gnpp)
2837 {
2838 	zio_gang_node_t *gn = *gnpp;
2839 
2840 	for (int g = 0; g < SPA_GBH_NBLKPTRS; g++)
2841 		ASSERT(gn->gn_child[g] == NULL);
2842 
2843 	zio_buf_free(gn->gn_gbh, SPA_GANGBLOCKSIZE);
2844 	kmem_free(gn, sizeof (*gn));
2845 	*gnpp = NULL;
2846 }
2847 
2848 static void
2849 zio_gang_tree_free(zio_gang_node_t **gnpp)
2850 {
2851 	zio_gang_node_t *gn = *gnpp;
2852 
2853 	if (gn == NULL)
2854 		return;
2855 
2856 	for (int g = 0; g < SPA_GBH_NBLKPTRS; g++)
2857 		zio_gang_tree_free(&gn->gn_child[g]);
2858 
2859 	zio_gang_node_free(gnpp);
2860 }
2861 
2862 static void
2863 zio_gang_tree_assemble(zio_t *gio, blkptr_t *bp, zio_gang_node_t **gnpp)
2864 {
2865 	zio_gang_node_t *gn = zio_gang_node_alloc(gnpp);
2866 	abd_t *gbh_abd = abd_get_from_buf(gn->gn_gbh, SPA_GANGBLOCKSIZE);
2867 
2868 	ASSERT(gio->io_gang_leader == gio);
2869 	ASSERT(BP_IS_GANG(bp));
2870 
2871 	zio_nowait(zio_read(gio, gio->io_spa, bp, gbh_abd, SPA_GANGBLOCKSIZE,
2872 	    zio_gang_tree_assemble_done, gn, gio->io_priority,
2873 	    ZIO_GANG_CHILD_FLAGS(gio), &gio->io_bookmark));
2874 }
2875 
2876 static void
2877 zio_gang_tree_assemble_done(zio_t *zio)
2878 {
2879 	zio_t *gio = zio->io_gang_leader;
2880 	zio_gang_node_t *gn = zio->io_private;
2881 	blkptr_t *bp = zio->io_bp;
2882 
2883 	ASSERT(gio == zio_unique_parent(zio));
2884 	ASSERT(list_is_empty(&zio->io_child_list));
2885 
2886 	if (zio->io_error)
2887 		return;
2888 
2889 	/* this ABD was created from a linear buf in zio_gang_tree_assemble */
2890 	if (BP_SHOULD_BYTESWAP(bp))
2891 		byteswap_uint64_array(abd_to_buf(zio->io_abd), zio->io_size);
2892 
2893 	ASSERT3P(abd_to_buf(zio->io_abd), ==, gn->gn_gbh);
2894 	ASSERT(zio->io_size == SPA_GANGBLOCKSIZE);
2895 	ASSERT(gn->gn_gbh->zg_tail.zec_magic == ZEC_MAGIC);
2896 
2897 	abd_free(zio->io_abd);
2898 
2899 	for (int g = 0; g < SPA_GBH_NBLKPTRS; g++) {
2900 		blkptr_t *gbp = &gn->gn_gbh->zg_blkptr[g];
2901 		if (!BP_IS_GANG(gbp))
2902 			continue;
2903 		zio_gang_tree_assemble(gio, gbp, &gn->gn_child[g]);
2904 	}
2905 }
2906 
2907 static void
2908 zio_gang_tree_issue(zio_t *pio, zio_gang_node_t *gn, blkptr_t *bp, abd_t *data,
2909     uint64_t offset)
2910 {
2911 	zio_t *gio = pio->io_gang_leader;
2912 	zio_t *zio;
2913 
2914 	ASSERT(BP_IS_GANG(bp) == !!gn);
2915 	ASSERT(BP_GET_CHECKSUM(bp) == BP_GET_CHECKSUM(gio->io_bp));
2916 	ASSERT(BP_GET_LSIZE(bp) == BP_GET_PSIZE(bp) || gn == gio->io_gang_tree);
2917 
2918 	/*
2919 	 * If you're a gang header, your data is in gn->gn_gbh.
2920 	 * If you're a gang member, your data is in 'data' and gn == NULL.
2921 	 */
2922 	zio = zio_gang_issue_func[gio->io_type](pio, bp, gn, data, offset);
2923 
2924 	if (gn != NULL) {
2925 		ASSERT(gn->gn_gbh->zg_tail.zec_magic == ZEC_MAGIC);
2926 
2927 		for (int g = 0; g < SPA_GBH_NBLKPTRS; g++) {
2928 			blkptr_t *gbp = &gn->gn_gbh->zg_blkptr[g];
2929 			if (BP_IS_HOLE(gbp))
2930 				continue;
2931 			zio_gang_tree_issue(zio, gn->gn_child[g], gbp, data,
2932 			    offset);
2933 			offset += BP_GET_PSIZE(gbp);
2934 		}
2935 	}
2936 
2937 	if (gn == gio->io_gang_tree)
2938 		ASSERT3U(gio->io_size, ==, offset);
2939 
2940 	if (zio != pio)
2941 		zio_nowait(zio);
2942 }
2943 
2944 static zio_t *
2945 zio_gang_assemble(zio_t *zio)
2946 {
2947 	blkptr_t *bp = zio->io_bp;
2948 
2949 	ASSERT(BP_IS_GANG(bp) && zio->io_gang_leader == NULL);
2950 	ASSERT(zio->io_child_type > ZIO_CHILD_GANG);
2951 
2952 	zio->io_gang_leader = zio;
2953 
2954 	zio_gang_tree_assemble(zio, bp, &zio->io_gang_tree);
2955 
2956 	return (zio);
2957 }
2958 
2959 static zio_t *
2960 zio_gang_issue(zio_t *zio)
2961 {
2962 	blkptr_t *bp = zio->io_bp;
2963 
2964 	if (zio_wait_for_children(zio, ZIO_CHILD_GANG_BIT, ZIO_WAIT_DONE)) {
2965 		return (NULL);
2966 	}
2967 
2968 	ASSERT(BP_IS_GANG(bp) && zio->io_gang_leader == zio);
2969 	ASSERT(zio->io_child_type > ZIO_CHILD_GANG);
2970 
2971 	if (zio->io_child_error[ZIO_CHILD_GANG] == 0)
2972 		zio_gang_tree_issue(zio, zio->io_gang_tree, bp, zio->io_abd,
2973 		    0);
2974 	else
2975 		zio_gang_tree_free(&zio->io_gang_tree);
2976 
2977 	zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
2978 
2979 	return (zio);
2980 }
2981 
2982 static void
2983 zio_gang_inherit_allocator(zio_t *pio, zio_t *cio)
2984 {
2985 	cio->io_allocator = pio->io_allocator;
2986 }
2987 
2988 static void
2989 zio_write_gang_member_ready(zio_t *zio)
2990 {
2991 	zio_t *pio = zio_unique_parent(zio);
2992 	dva_t *cdva = zio->io_bp->blk_dva;
2993 	dva_t *pdva = pio->io_bp->blk_dva;
2994 	uint64_t asize;
2995 	zio_t *gio __maybe_unused = zio->io_gang_leader;
2996 
2997 	if (BP_IS_HOLE(zio->io_bp))
2998 		return;
2999 
3000 	ASSERT(BP_IS_HOLE(&zio->io_bp_orig));
3001 
3002 	ASSERT(zio->io_child_type == ZIO_CHILD_GANG);
3003 	ASSERT3U(zio->io_prop.zp_copies, ==, gio->io_prop.zp_copies);
3004 	ASSERT3U(zio->io_prop.zp_copies, <=, BP_GET_NDVAS(zio->io_bp));
3005 	ASSERT3U(pio->io_prop.zp_copies, <=, BP_GET_NDVAS(pio->io_bp));
3006 	VERIFY3U(BP_GET_NDVAS(zio->io_bp), <=, BP_GET_NDVAS(pio->io_bp));
3007 
3008 	mutex_enter(&pio->io_lock);
3009 	for (int d = 0; d < BP_GET_NDVAS(zio->io_bp); d++) {
3010 		ASSERT(DVA_GET_GANG(&pdva[d]));
3011 		asize = DVA_GET_ASIZE(&pdva[d]);
3012 		asize += DVA_GET_ASIZE(&cdva[d]);
3013 		DVA_SET_ASIZE(&pdva[d], asize);
3014 	}
3015 	mutex_exit(&pio->io_lock);
3016 }
3017 
3018 static void
3019 zio_write_gang_done(zio_t *zio)
3020 {
3021 	/*
3022 	 * The io_abd field will be NULL for a zio with no data.  The io_flags
3023 	 * will initially have the ZIO_FLAG_NODATA bit flag set, but we can't
3024 	 * check for it here as it is cleared in zio_ready.
3025 	 */
3026 	if (zio->io_abd != NULL)
3027 		abd_free(zio->io_abd);
3028 }
3029 
3030 static zio_t *
3031 zio_write_gang_block(zio_t *pio, metaslab_class_t *mc)
3032 {
3033 	spa_t *spa = pio->io_spa;
3034 	blkptr_t *bp = pio->io_bp;
3035 	zio_t *gio = pio->io_gang_leader;
3036 	zio_t *zio;
3037 	zio_gang_node_t *gn, **gnpp;
3038 	zio_gbh_phys_t *gbh;
3039 	abd_t *gbh_abd;
3040 	uint64_t txg = pio->io_txg;
3041 	uint64_t resid = pio->io_size;
3042 	uint64_t lsize;
3043 	int copies = gio->io_prop.zp_copies;
3044 	zio_prop_t zp;
3045 	int error;
3046 	boolean_t has_data = !(pio->io_flags & ZIO_FLAG_NODATA);
3047 
3048 	/*
3049 	 * If one copy was requested, store 2 copies of the GBH, so that we
3050 	 * can still traverse all the data (e.g. to free or scrub) even if a
3051 	 * block is damaged.  Note that we can't store 3 copies of the GBH in
3052 	 * all cases, e.g. with encryption, which uses DVA[2] for the IV+salt.
3053 	 */
3054 	int gbh_copies = copies;
3055 	if (gbh_copies == 1) {
3056 		gbh_copies = MIN(2, spa_max_replication(spa));
3057 	}
3058 
3059 	ASSERT(ZIO_HAS_ALLOCATOR(pio));
3060 	int flags = METASLAB_HINTBP_FAVOR | METASLAB_GANG_HEADER;
3061 	if (pio->io_flags & ZIO_FLAG_IO_ALLOCATING) {
3062 		ASSERT(pio->io_priority == ZIO_PRIORITY_ASYNC_WRITE);
3063 		ASSERT(has_data);
3064 
3065 		flags |= METASLAB_ASYNC_ALLOC;
3066 		VERIFY(zfs_refcount_held(&mc->mc_allocator[pio->io_allocator].
3067 		    mca_alloc_slots, pio));
3068 
3069 		/*
3070 		 * The logical zio has already placed a reservation for
3071 		 * 'copies' allocation slots but gang blocks may require
3072 		 * additional copies. These additional copies
3073 		 * (i.e. gbh_copies - copies) are guaranteed to succeed
3074 		 * since metaslab_class_throttle_reserve() always allows
3075 		 * additional reservations for gang blocks.
3076 		 */
3077 		VERIFY(metaslab_class_throttle_reserve(mc, gbh_copies - copies,
3078 		    pio->io_allocator, pio, flags));
3079 	}
3080 
3081 	error = metaslab_alloc(spa, mc, SPA_GANGBLOCKSIZE,
3082 	    bp, gbh_copies, txg, pio == gio ? NULL : gio->io_bp, flags,
3083 	    &pio->io_alloc_list, pio, pio->io_allocator);
3084 	if (error) {
3085 		if (pio->io_flags & ZIO_FLAG_IO_ALLOCATING) {
3086 			ASSERT(pio->io_priority == ZIO_PRIORITY_ASYNC_WRITE);
3087 			ASSERT(has_data);
3088 
3089 			/*
3090 			 * If we failed to allocate the gang block header then
3091 			 * we remove any additional allocation reservations that
3092 			 * we placed here. The original reservation will
3093 			 * be removed when the logical I/O goes to the ready
3094 			 * stage.
3095 			 */
3096 			metaslab_class_throttle_unreserve(mc,
3097 			    gbh_copies - copies, pio->io_allocator, pio);
3098 		}
3099 
3100 		pio->io_error = error;
3101 		return (pio);
3102 	}
3103 
3104 	if (pio == gio) {
3105 		gnpp = &gio->io_gang_tree;
3106 	} else {
3107 		gnpp = pio->io_private;
3108 		ASSERT(pio->io_ready == zio_write_gang_member_ready);
3109 	}
3110 
3111 	gn = zio_gang_node_alloc(gnpp);
3112 	gbh = gn->gn_gbh;
3113 	memset(gbh, 0, SPA_GANGBLOCKSIZE);
3114 	gbh_abd = abd_get_from_buf(gbh, SPA_GANGBLOCKSIZE);
3115 
3116 	/*
3117 	 * Create the gang header.
3118 	 */
3119 	zio = zio_rewrite(pio, spa, txg, bp, gbh_abd, SPA_GANGBLOCKSIZE,
3120 	    zio_write_gang_done, NULL, pio->io_priority,
3121 	    ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
3122 
3123 	zio_gang_inherit_allocator(pio, zio);
3124 
3125 	/*
3126 	 * Create and nowait the gang children.
3127 	 */
3128 	for (int g = 0; resid != 0; resid -= lsize, g++) {
3129 		lsize = P2ROUNDUP(resid / (SPA_GBH_NBLKPTRS - g),
3130 		    SPA_MINBLOCKSIZE);
3131 		ASSERT(lsize >= SPA_MINBLOCKSIZE && lsize <= resid);
3132 
3133 		zp.zp_checksum = gio->io_prop.zp_checksum;
3134 		zp.zp_compress = ZIO_COMPRESS_OFF;
3135 		zp.zp_complevel = gio->io_prop.zp_complevel;
3136 		zp.zp_type = zp.zp_storage_type = DMU_OT_NONE;
3137 		zp.zp_level = 0;
3138 		zp.zp_copies = gio->io_prop.zp_copies;
3139 		zp.zp_dedup = B_FALSE;
3140 		zp.zp_dedup_verify = B_FALSE;
3141 		zp.zp_nopwrite = B_FALSE;
3142 		zp.zp_encrypt = gio->io_prop.zp_encrypt;
3143 		zp.zp_byteorder = gio->io_prop.zp_byteorder;
3144 		zp.zp_direct_write = B_FALSE;
3145 		memset(zp.zp_salt, 0, ZIO_DATA_SALT_LEN);
3146 		memset(zp.zp_iv, 0, ZIO_DATA_IV_LEN);
3147 		memset(zp.zp_mac, 0, ZIO_DATA_MAC_LEN);
3148 
3149 		zio_t *cio = zio_write(zio, spa, txg, &gbh->zg_blkptr[g],
3150 		    has_data ? abd_get_offset(pio->io_abd, pio->io_size -
3151 		    resid) : NULL, lsize, lsize, &zp,
3152 		    zio_write_gang_member_ready, NULL,
3153 		    zio_write_gang_done, &gn->gn_child[g], pio->io_priority,
3154 		    ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
3155 
3156 		zio_gang_inherit_allocator(zio, cio);
3157 
3158 		if (pio->io_flags & ZIO_FLAG_IO_ALLOCATING) {
3159 			ASSERT(pio->io_priority == ZIO_PRIORITY_ASYNC_WRITE);
3160 			ASSERT(has_data);
3161 
3162 			/*
3163 			 * Gang children won't throttle but we should
3164 			 * account for their work, so reserve an allocation
3165 			 * slot for them here.
3166 			 */
3167 			VERIFY(metaslab_class_throttle_reserve(mc,
3168 			    zp.zp_copies, cio->io_allocator, cio, flags));
3169 		}
3170 		zio_nowait(cio);
3171 	}
3172 
3173 	/*
3174 	 * Set pio's pipeline to just wait for zio to finish.
3175 	 */
3176 	pio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
3177 
3178 	zio_nowait(zio);
3179 
3180 	return (pio);
3181 }
3182 
3183 /*
3184  * The zio_nop_write stage in the pipeline determines if allocating a
3185  * new bp is necessary.  The nopwrite feature can handle writes in
3186  * either syncing or open context (i.e. zil writes) and as a result is
3187  * mutually exclusive with dedup.
3188  *
3189  * By leveraging a cryptographically secure checksum, such as SHA256, we
3190  * can compare the checksums of the new data and the old to determine if
3191  * allocating a new block is required.  Note that our requirements for
3192  * cryptographic strength are fairly weak: there can't be any accidental
3193  * hash collisions, but we don't need to be secure against intentional
3194  * (malicious) collisions.  To trigger a nopwrite, you have to be able
3195  * to write the file to begin with, and triggering an incorrect (hash
3196  * collision) nopwrite is no worse than simply writing to the file.
3197  * That said, there are no known attacks against the checksum algorithms
3198  * used for nopwrite, assuming that the salt and the checksums
3199  * themselves remain secret.
3200  */
3201 static zio_t *
3202 zio_nop_write(zio_t *zio)
3203 {
3204 	blkptr_t *bp = zio->io_bp;
3205 	blkptr_t *bp_orig = &zio->io_bp_orig;
3206 	zio_prop_t *zp = &zio->io_prop;
3207 
3208 	ASSERT(BP_IS_HOLE(bp));
3209 	ASSERT(BP_GET_LEVEL(bp) == 0);
3210 	ASSERT(!(zio->io_flags & ZIO_FLAG_IO_REWRITE));
3211 	ASSERT(zp->zp_nopwrite);
3212 	ASSERT(!zp->zp_dedup);
3213 	ASSERT(zio->io_bp_override == NULL);
3214 	ASSERT(IO_IS_ALLOCATING(zio));
3215 
3216 	/*
3217 	 * Check to see if the original bp and the new bp have matching
3218 	 * characteristics (i.e. same checksum, compression algorithms, etc).
3219 	 * If they don't then just continue with the pipeline which will
3220 	 * allocate a new bp.
3221 	 */
3222 	if (BP_IS_HOLE(bp_orig) ||
3223 	    !(zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_flags &
3224 	    ZCHECKSUM_FLAG_NOPWRITE) ||
3225 	    BP_IS_ENCRYPTED(bp) || BP_IS_ENCRYPTED(bp_orig) ||
3226 	    BP_GET_CHECKSUM(bp) != BP_GET_CHECKSUM(bp_orig) ||
3227 	    BP_GET_COMPRESS(bp) != BP_GET_COMPRESS(bp_orig) ||
3228 	    BP_GET_DEDUP(bp) != BP_GET_DEDUP(bp_orig) ||
3229 	    zp->zp_copies != BP_GET_NDVAS(bp_orig))
3230 		return (zio);
3231 
3232 	/*
3233 	 * If the checksums match then reset the pipeline so that we
3234 	 * avoid allocating a new bp and issuing any I/O.
3235 	 */
3236 	if (ZIO_CHECKSUM_EQUAL(bp->blk_cksum, bp_orig->blk_cksum)) {
3237 		ASSERT(zio_checksum_table[zp->zp_checksum].ci_flags &
3238 		    ZCHECKSUM_FLAG_NOPWRITE);
3239 		ASSERT3U(BP_GET_PSIZE(bp), ==, BP_GET_PSIZE(bp_orig));
3240 		ASSERT3U(BP_GET_LSIZE(bp), ==, BP_GET_LSIZE(bp_orig));
3241 		ASSERT(zp->zp_compress != ZIO_COMPRESS_OFF);
3242 		ASSERT3U(bp->blk_prop, ==, bp_orig->blk_prop);
3243 
3244 		/*
3245 		 * If we're overwriting a block that is currently on an
3246 		 * indirect vdev, then ignore the nopwrite request and
3247 		 * allow a new block to be allocated on a concrete vdev.
3248 		 */
3249 		spa_config_enter(zio->io_spa, SCL_VDEV, FTAG, RW_READER);
3250 		for (int d = 0; d < BP_GET_NDVAS(bp_orig); d++) {
3251 			vdev_t *tvd = vdev_lookup_top(zio->io_spa,
3252 			    DVA_GET_VDEV(&bp_orig->blk_dva[d]));
3253 			if (tvd->vdev_ops == &vdev_indirect_ops) {
3254 				spa_config_exit(zio->io_spa, SCL_VDEV, FTAG);
3255 				return (zio);
3256 			}
3257 		}
3258 		spa_config_exit(zio->io_spa, SCL_VDEV, FTAG);
3259 
3260 		*bp = *bp_orig;
3261 		zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
3262 		zio->io_flags |= ZIO_FLAG_NOPWRITE;
3263 	}
3264 
3265 	return (zio);
3266 }
3267 
3268 /*
3269  * ==========================================================================
3270  * Block Reference Table
3271  * ==========================================================================
3272  */
3273 static zio_t *
3274 zio_brt_free(zio_t *zio)
3275 {
3276 	blkptr_t *bp;
3277 
3278 	bp = zio->io_bp;
3279 
3280 	if (BP_GET_LEVEL(bp) > 0 ||
3281 	    BP_IS_METADATA(bp) ||
3282 	    !brt_maybe_exists(zio->io_spa, bp)) {
3283 		return (zio);
3284 	}
3285 
3286 	if (!brt_entry_decref(zio->io_spa, bp)) {
3287 		/*
3288 		 * This isn't the last reference, so we cannot free
3289 		 * the data yet.
3290 		 */
3291 		zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
3292 	}
3293 
3294 	return (zio);
3295 }
3296 
3297 /*
3298  * ==========================================================================
3299  * Dedup
3300  * ==========================================================================
3301  */
3302 static void
3303 zio_ddt_child_read_done(zio_t *zio)
3304 {
3305 	blkptr_t *bp = zio->io_bp;
3306 	ddt_t *ddt;
3307 	ddt_entry_t *dde = zio->io_private;
3308 	zio_t *pio = zio_unique_parent(zio);
3309 
3310 	mutex_enter(&pio->io_lock);
3311 	ddt = ddt_select(zio->io_spa, bp);
3312 
3313 	if (zio->io_error == 0) {
3314 		ddt_phys_variant_t v = ddt_phys_select(ddt, dde, bp);
3315 		/* this phys variant doesn't need repair */
3316 		ddt_phys_clear(dde->dde_phys, v);
3317 	}
3318 
3319 	if (zio->io_error == 0 && dde->dde_io->dde_repair_abd == NULL)
3320 		dde->dde_io->dde_repair_abd = zio->io_abd;
3321 	else
3322 		abd_free(zio->io_abd);
3323 	mutex_exit(&pio->io_lock);
3324 }
3325 
3326 static zio_t *
3327 zio_ddt_read_start(zio_t *zio)
3328 {
3329 	blkptr_t *bp = zio->io_bp;
3330 
3331 	ASSERT(BP_GET_DEDUP(bp));
3332 	ASSERT(BP_GET_PSIZE(bp) == zio->io_size);
3333 	ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
3334 
3335 	if (zio->io_child_error[ZIO_CHILD_DDT]) {
3336 		ddt_t *ddt = ddt_select(zio->io_spa, bp);
3337 		ddt_entry_t *dde = ddt_repair_start(ddt, bp);
3338 		ddt_phys_variant_t v_self = ddt_phys_select(ddt, dde, bp);
3339 		ddt_univ_phys_t *ddp = dde->dde_phys;
3340 		blkptr_t blk;
3341 
3342 		ASSERT(zio->io_vsd == NULL);
3343 		zio->io_vsd = dde;
3344 
3345 		if (v_self == DDT_PHYS_NONE)
3346 			return (zio);
3347 
3348 		/* issue I/O for the other copies */
3349 		for (int p = 0; p < DDT_NPHYS(ddt); p++) {
3350 			ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);
3351 
3352 			if (ddt_phys_birth(ddp, v) == 0 || v == v_self)
3353 				continue;
3354 
3355 			ddt_bp_create(ddt->ddt_checksum, &dde->dde_key,
3356 			    ddp, v, &blk);
3357 			zio_nowait(zio_read(zio, zio->io_spa, &blk,
3358 			    abd_alloc_for_io(zio->io_size, B_TRUE),
3359 			    zio->io_size, zio_ddt_child_read_done, dde,
3360 			    zio->io_priority, ZIO_DDT_CHILD_FLAGS(zio) |
3361 			    ZIO_FLAG_DONT_PROPAGATE, &zio->io_bookmark));
3362 		}
3363 		return (zio);
3364 	}
3365 
3366 	zio_nowait(zio_read(zio, zio->io_spa, bp,
3367 	    zio->io_abd, zio->io_size, NULL, NULL, zio->io_priority,
3368 	    ZIO_DDT_CHILD_FLAGS(zio), &zio->io_bookmark));
3369 
3370 	return (zio);
3371 }
3372 
3373 static zio_t *
3374 zio_ddt_read_done(zio_t *zio)
3375 {
3376 	blkptr_t *bp = zio->io_bp;
3377 
3378 	if (zio_wait_for_children(zio, ZIO_CHILD_DDT_BIT, ZIO_WAIT_DONE)) {
3379 		return (NULL);
3380 	}
3381 
3382 	ASSERT(BP_GET_DEDUP(bp));
3383 	ASSERT(BP_GET_PSIZE(bp) == zio->io_size);
3384 	ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
3385 
3386 	if (zio->io_child_error[ZIO_CHILD_DDT]) {
3387 		ddt_t *ddt = ddt_select(zio->io_spa, bp);
3388 		ddt_entry_t *dde = zio->io_vsd;
3389 		if (ddt == NULL) {
3390 			ASSERT(spa_load_state(zio->io_spa) != SPA_LOAD_NONE);
3391 			return (zio);
3392 		}
3393 		if (dde == NULL) {
3394 			zio->io_stage = ZIO_STAGE_DDT_READ_START >> 1;
3395 			zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE, B_FALSE);
3396 			return (NULL);
3397 		}
3398 		if (dde->dde_io->dde_repair_abd != NULL) {
3399 			abd_copy(zio->io_abd, dde->dde_io->dde_repair_abd,
3400 			    zio->io_size);
3401 			zio->io_child_error[ZIO_CHILD_DDT] = 0;
3402 		}
3403 		ddt_repair_done(ddt, dde);
3404 		zio->io_vsd = NULL;
3405 	}
3406 
3407 	ASSERT(zio->io_vsd == NULL);
3408 
3409 	return (zio);
3410 }
3411 
3412 static boolean_t
3413 zio_ddt_collision(zio_t *zio, ddt_t *ddt, ddt_entry_t *dde)
3414 {
3415 	spa_t *spa = zio->io_spa;
3416 	boolean_t do_raw = !!(zio->io_flags & ZIO_FLAG_RAW);
3417 
3418 	ASSERT(!(zio->io_bp_override && do_raw));
3419 
3420 	/*
3421 	 * Note: we compare the original data, not the transformed data,
3422 	 * because when zio->io_bp is an override bp, we will not have
3423 	 * pushed the I/O transforms.  That's an important optimization
3424 	 * because otherwise we'd compress/encrypt all dmu_sync() data twice.
3425 	 * However, we should never get a raw, override zio so in these
3426 	 * cases we can compare the io_abd directly. This is useful because
3427 	 * it allows us to do dedup verification even if we don't have access
3428 	 * to the original data (for instance, if the encryption keys aren't
3429 	 * loaded).
3430 	 */
3431 
3432 	for (int p = 0; p < DDT_NPHYS(ddt); p++) {
3433 		if (DDT_PHYS_IS_DITTO(ddt, p))
3434 			continue;
3435 
3436 		if (dde->dde_io == NULL)
3437 			continue;
3438 
3439 		zio_t *lio = dde->dde_io->dde_lead_zio[p];
3440 		if (lio == NULL)
3441 			continue;
3442 
3443 		if (do_raw)
3444 			return (lio->io_size != zio->io_size ||
3445 			    abd_cmp(zio->io_abd, lio->io_abd) != 0);
3446 
3447 		return (lio->io_orig_size != zio->io_orig_size ||
3448 		    abd_cmp(zio->io_orig_abd, lio->io_orig_abd) != 0);
3449 	}
3450 
3451 	for (int p = 0; p < DDT_NPHYS(ddt); p++) {
3452 		ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);
3453 		uint64_t phys_birth = ddt_phys_birth(dde->dde_phys, v);
3454 
3455 		if (phys_birth != 0 && do_raw) {
3456 			blkptr_t blk = *zio->io_bp;
3457 			uint64_t psize;
3458 			abd_t *tmpabd;
3459 			int error;
3460 
3461 			ddt_bp_fill(dde->dde_phys, v, &blk, phys_birth);
3462 			psize = BP_GET_PSIZE(&blk);
3463 
3464 			if (psize != zio->io_size)
3465 				return (B_TRUE);
3466 
3467 			ddt_exit(ddt);
3468 
3469 			tmpabd = abd_alloc_for_io(psize, B_TRUE);
3470 
3471 			error = zio_wait(zio_read(NULL, spa, &blk, tmpabd,
3472 			    psize, NULL, NULL, ZIO_PRIORITY_SYNC_READ,
3473 			    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
3474 			    ZIO_FLAG_RAW, &zio->io_bookmark));
3475 
3476 			if (error == 0) {
3477 				if (abd_cmp(tmpabd, zio->io_abd) != 0)
3478 					error = SET_ERROR(ENOENT);
3479 			}
3480 
3481 			abd_free(tmpabd);
3482 			ddt_enter(ddt);
3483 			return (error != 0);
3484 		} else if (phys_birth != 0) {
3485 			arc_buf_t *abuf = NULL;
3486 			arc_flags_t aflags = ARC_FLAG_WAIT;
3487 			blkptr_t blk = *zio->io_bp;
3488 			int error;
3489 
3490 			ddt_bp_fill(dde->dde_phys, v, &blk, phys_birth);
3491 
3492 			if (BP_GET_LSIZE(&blk) != zio->io_orig_size)
3493 				return (B_TRUE);
3494 
3495 			ddt_exit(ddt);
3496 
3497 			error = arc_read(NULL, spa, &blk,
3498 			    arc_getbuf_func, &abuf, ZIO_PRIORITY_SYNC_READ,
3499 			    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
3500 			    &aflags, &zio->io_bookmark);
3501 
3502 			if (error == 0) {
3503 				if (abd_cmp_buf(zio->io_orig_abd, abuf->b_data,
3504 				    zio->io_orig_size) != 0)
3505 					error = SET_ERROR(ENOENT);
3506 				arc_buf_destroy(abuf, &abuf);
3507 			}
3508 
3509 			ddt_enter(ddt);
3510 			return (error != 0);
3511 		}
3512 	}
3513 
3514 	return (B_FALSE);
3515 }
3516 
3517 static void
3518 zio_ddt_child_write_done(zio_t *zio)
3519 {
3520 	ddt_t *ddt = ddt_select(zio->io_spa, zio->io_bp);
3521 	ddt_entry_t *dde = zio->io_private;
3522 
3523 	zio_link_t *zl = NULL;
3524 	ASSERT3P(zio_walk_parents(zio, &zl), !=, NULL);
3525 
3526 	int p = DDT_PHYS_FOR_COPIES(ddt, zio->io_prop.zp_copies);
3527 	ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);
3528 	ddt_univ_phys_t *ddp = dde->dde_phys;
3529 
3530 	ddt_enter(ddt);
3531 
3532 	/* we're the lead, so once we're done there's no one else outstanding */
3533 	if (dde->dde_io->dde_lead_zio[p] == zio)
3534 		dde->dde_io->dde_lead_zio[p] = NULL;
3535 
3536 	ddt_univ_phys_t *orig = &dde->dde_io->dde_orig_phys;
3537 
3538 	if (zio->io_error != 0) {
3539 		/*
3540 		 * The write failed, so we're about to abort the entire IO
3541 		 * chain. We need to revert the entry back to what it was at
3542 		 * the last time it was successfully extended.
3543 		 */
3544 		ddt_phys_copy(ddp, orig, v);
3545 		ddt_phys_clear(orig, v);
3546 
3547 		ddt_exit(ddt);
3548 		return;
3549 	}
3550 
3551 	/*
3552 	 * We've successfully added new DVAs to the entry. Clear the saved
3553 	 * state or, if there's still outstanding IO, remember it so we can
3554 	 * revert to a known good state if that IO fails.
3555 	 */
3556 	if (dde->dde_io->dde_lead_zio[p] == NULL)
3557 		ddt_phys_clear(orig, v);
3558 	else
3559 		ddt_phys_copy(orig, ddp, v);
3560 
3561 	/*
3562 	 * Add references for all dedup writes that were waiting on the
3563 	 * physical one, skipping any other physical writes that are waiting.
3564 	 */
3565 	zio_t *pio;
3566 	zl = NULL;
3567 	while ((pio = zio_walk_parents(zio, &zl)) != NULL) {
3568 		if (!(pio->io_flags & ZIO_FLAG_DDT_CHILD))
3569 			ddt_phys_addref(ddp, v);
3570 	}
3571 
3572 	ddt_exit(ddt);
3573 }
3574 
3575 static void
3576 zio_ddt_child_write_ready(zio_t *zio)
3577 {
3578 	ddt_t *ddt = ddt_select(zio->io_spa, zio->io_bp);
3579 	ddt_entry_t *dde = zio->io_private;
3580 
3581 	zio_link_t *zl = NULL;
3582 	ASSERT3P(zio_walk_parents(zio, &zl), !=, NULL);
3583 
3584 	int p = DDT_PHYS_FOR_COPIES(ddt, zio->io_prop.zp_copies);
3585 	ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);
3586 
3587 	if (zio->io_error != 0)
3588 		return;
3589 
3590 	ddt_enter(ddt);
3591 
3592 	ddt_phys_extend(dde->dde_phys, v, zio->io_bp);
3593 
3594 	zio_t *pio;
3595 	zl = NULL;
3596 	while ((pio = zio_walk_parents(zio, &zl)) != NULL) {
3597 		if (!(pio->io_flags & ZIO_FLAG_DDT_CHILD))
3598 			ddt_bp_fill(dde->dde_phys, v, pio->io_bp, zio->io_txg);
3599 	}
3600 
3601 	ddt_exit(ddt);
3602 }
3603 
3604 static zio_t *
3605 zio_ddt_write(zio_t *zio)
3606 {
3607 	spa_t *spa = zio->io_spa;
3608 	blkptr_t *bp = zio->io_bp;
3609 	uint64_t txg = zio->io_txg;
3610 	zio_prop_t *zp = &zio->io_prop;
3611 	ddt_t *ddt = ddt_select(spa, bp);
3612 	ddt_entry_t *dde;
3613 
3614 	ASSERT(BP_GET_DEDUP(bp));
3615 	ASSERT(BP_GET_CHECKSUM(bp) == zp->zp_checksum);
3616 	ASSERT(BP_IS_HOLE(bp) || zio->io_bp_override);
3617 	ASSERT(!(zio->io_bp_override && (zio->io_flags & ZIO_FLAG_RAW)));
3618 	/*
3619 	 * Deduplication will not take place for Direct I/O writes. The
3620 	 * ddt_tree will be emptied in syncing context. Direct I/O writes take
3621 	 * place in the open-context. Direct I/O write can not attempt to
3622 	 * modify the ddt_tree while issuing out a write.
3623 	 */
3624 	ASSERT3B(zio->io_prop.zp_direct_write, ==, B_FALSE);
3625 
3626 	ddt_enter(ddt);
3627 	dde = ddt_lookup(ddt, bp);
3628 	if (dde == NULL) {
3629 		/* DDT size is over its quota so no new entries */
3630 		zp->zp_dedup = B_FALSE;
3631 		BP_SET_DEDUP(bp, B_FALSE);
3632 		if (zio->io_bp_override == NULL)
3633 			zio->io_pipeline = ZIO_WRITE_PIPELINE;
3634 		ddt_exit(ddt);
3635 		return (zio);
3636 	}
3637 
3638 	if (zp->zp_dedup_verify && zio_ddt_collision(zio, ddt, dde)) {
3639 		/*
3640 		 * If we're using a weak checksum, upgrade to a strong checksum
3641 		 * and try again.  If we're already using a strong checksum,
3642 		 * we can't resolve it, so just convert to an ordinary write.
3643 		 * (And automatically e-mail a paper to Nature?)
3644 		 */
3645 		if (!(zio_checksum_table[zp->zp_checksum].ci_flags &
3646 		    ZCHECKSUM_FLAG_DEDUP)) {
3647 			zp->zp_checksum = spa_dedup_checksum(spa);
3648 			zio_pop_transforms(zio);
3649 			zio->io_stage = ZIO_STAGE_OPEN;
3650 			BP_ZERO(bp);
3651 		} else {
3652 			zp->zp_dedup = B_FALSE;
3653 			BP_SET_DEDUP(bp, B_FALSE);
3654 		}
3655 		ASSERT(!BP_GET_DEDUP(bp));
3656 		zio->io_pipeline = ZIO_WRITE_PIPELINE;
3657 		ddt_exit(ddt);
3658 		return (zio);
3659 	}
3660 
3661 	int p = DDT_PHYS_FOR_COPIES(ddt, zp->zp_copies);
3662 	ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);
3663 	ddt_univ_phys_t *ddp = dde->dde_phys;
3664 
3665 	/*
3666 	 * In the common cases, at this point we have a regular BP with no
3667 	 * allocated DVAs, and the corresponding DDT entry for its checksum.
3668 	 * Our goal is to fill the BP with enough DVAs to satisfy its copies=
3669 	 * requirement.
3670 	 *
3671 	 * One of three things needs to happen to fulfill this:
3672 	 *
3673 	 * - if the DDT entry has enough DVAs to satisfy the BP, we just copy
3674 	 *   them out of the entry and return;
3675 	 *
3676 	 * - if the DDT entry has no DVAs (ie its brand new), then we have to
3677 	 *   issue the write as normal so that DVAs can be allocated and the
3678 	 *   data land on disk. We then copy the DVAs into the DDT entry on
3679 	 *   return.
3680 	 *
3681 	 * - if the DDT entry has some DVAs, but too few, we have to issue the
3682 	 *   write, adjusted to have allocate fewer copies. When it returns, we
3683 	 *   add the new DVAs to the DDT entry, and update the BP to have the
3684 	 *   full amount it originally requested.
3685 	 *
3686 	 * In all cases, if there's already a writing IO in flight, we need to
3687 	 * defer the action until after the write is done. If our action is to
3688 	 * write, we need to adjust our request for additional DVAs to match
3689 	 * what will be in the DDT entry after it completes. In this way every
3690 	 * IO can be guaranteed to recieve enough DVAs simply by joining the
3691 	 * end of the chain and letting the sequence play out.
3692 	 */
3693 
3694 	/*
3695 	 * Number of DVAs in the DDT entry. If the BP is encrypted we ignore
3696 	 * the third one as normal.
3697 	 */
3698 	int have_dvas = ddt_phys_dva_count(ddp, v, BP_IS_ENCRYPTED(bp));
3699 	IMPLY(have_dvas == 0, ddt_phys_birth(ddp, v) == 0);
3700 
3701 	/* Number of DVAs requested bya the IO. */
3702 	uint8_t need_dvas = zp->zp_copies;
3703 
3704 	/*
3705 	 * What we do next depends on whether or not there's IO outstanding that
3706 	 * will update this entry.
3707 	 */
3708 	if (dde->dde_io == NULL || dde->dde_io->dde_lead_zio[p] == NULL) {
3709 		/*
3710 		 * No IO outstanding, so we only need to worry about ourselves.
3711 		 */
3712 
3713 		/*
3714 		 * Override BPs bring their own DVAs and their own problems.
3715 		 */
3716 		if (zio->io_bp_override) {
3717 			/*
3718 			 * For a brand-new entry, all the work has been done
3719 			 * for us, and we can just fill it out from the provided
3720 			 * block and leave.
3721 			 */
3722 			if (have_dvas == 0) {
3723 				ASSERT(BP_GET_LOGICAL_BIRTH(bp) == txg);
3724 				ASSERT(BP_EQUAL(bp, zio->io_bp_override));
3725 				ddt_phys_extend(ddp, v, bp);
3726 				ddt_phys_addref(ddp, v);
3727 				ddt_exit(ddt);
3728 				return (zio);
3729 			}
3730 
3731 			/*
3732 			 * If we already have this entry, then we want to treat
3733 			 * it like a regular write. To do this we just wipe
3734 			 * them out and proceed like a regular write.
3735 			 *
3736 			 * Even if there are some DVAs in the entry, we still
3737 			 * have to clear them out. We can't use them to fill
3738 			 * out the dedup entry, as they are all referenced
3739 			 * together by a bp already on disk, and will be freed
3740 			 * as a group.
3741 			 */
3742 			BP_ZERO_DVAS(bp);
3743 			BP_SET_BIRTH(bp, 0, 0);
3744 		}
3745 
3746 		/*
3747 		 * If there are enough DVAs in the entry to service our request,
3748 		 * then we can just use them as-is.
3749 		 */
3750 		if (have_dvas >= need_dvas) {
3751 			ddt_bp_fill(ddp, v, bp, txg);
3752 			ddt_phys_addref(ddp, v);
3753 			ddt_exit(ddt);
3754 			return (zio);
3755 		}
3756 
3757 		/*
3758 		 * Otherwise, we have to issue IO to fill the entry up to the
3759 		 * amount we need.
3760 		 */
3761 		need_dvas -= have_dvas;
3762 	} else {
3763 		/*
3764 		 * There's a write in-flight. If there's already enough DVAs on
3765 		 * the entry, then either there were already enough to start
3766 		 * with, or the in-flight IO is between READY and DONE, and so
3767 		 * has extended the entry with new DVAs. Either way, we don't
3768 		 * need to do anything, we can just slot in behind it.
3769 		 */
3770 
3771 		if (zio->io_bp_override) {
3772 			/*
3773 			 * If there's a write out, then we're soon going to
3774 			 * have our own copies of this block, so clear out the
3775 			 * override block and treat it as a regular dedup
3776 			 * write. See comment above.
3777 			 */
3778 			BP_ZERO_DVAS(bp);
3779 			BP_SET_BIRTH(bp, 0, 0);
3780 		}
3781 
3782 		if (have_dvas >= need_dvas) {
3783 			/*
3784 			 * A minor point: there might already be enough
3785 			 * committed DVAs in the entry to service our request,
3786 			 * but we don't know which are completed and which are
3787 			 * allocated but not yet written. In this case, should
3788 			 * the IO for the new DVAs fail, we will be on the end
3789 			 * of the IO chain and will also recieve an error, even
3790 			 * though our request could have been serviced.
3791 			 *
3792 			 * This is an extremely rare case, as it requires the
3793 			 * original block to be copied with a request for a
3794 			 * larger number of DVAs, then copied again requesting
3795 			 * the same (or already fulfilled) number of DVAs while
3796 			 * the first request is active, and then that first
3797 			 * request errors. In return, the logic required to
3798 			 * catch and handle it is complex. For now, I'm just
3799 			 * not going to bother with it.
3800 			 */
3801 
3802 			/*
3803 			 * We always fill the bp here as we may have arrived
3804 			 * after the in-flight write has passed READY, and so
3805 			 * missed out.
3806 			 */
3807 			ddt_bp_fill(ddp, v, bp, txg);
3808 			zio_add_child(zio, dde->dde_io->dde_lead_zio[p]);
3809 			ddt_exit(ddt);
3810 			return (zio);
3811 		}
3812 
3813 		/*
3814 		 * There's not enough in the entry yet, so we need to look at
3815 		 * the write in-flight and see how many DVAs it will have once
3816 		 * it completes.
3817 		 *
3818 		 * The in-flight write has potentially had its copies request
3819 		 * reduced (if we're filling out an existing entry), so we need
3820 		 * to reach in and get the original write to find out what it is
3821 		 * expecting.
3822 		 *
3823 		 * Note that the parent of the lead zio will always have the
3824 		 * highest zp_copies of any zio in the chain, because ones that
3825 		 * can be serviced without additional IO are always added to
3826 		 * the back of the chain.
3827 		 */
3828 		zio_link_t *zl = NULL;
3829 		zio_t *pio =
3830 		    zio_walk_parents(dde->dde_io->dde_lead_zio[p], &zl);
3831 		ASSERT(pio);
3832 		uint8_t parent_dvas = pio->io_prop.zp_copies;
3833 
3834 		if (parent_dvas >= need_dvas) {
3835 			zio_add_child(zio, dde->dde_io->dde_lead_zio[p]);
3836 			ddt_exit(ddt);
3837 			return (zio);
3838 		}
3839 
3840 		/*
3841 		 * Still not enough, so we will need to issue to get the
3842 		 * shortfall.
3843 		 */
3844 		need_dvas -= parent_dvas;
3845 	}
3846 
3847 	/*
3848 	 * We need to write. We will create a new write with the copies
3849 	 * property adjusted to match the number of DVAs we need to need to
3850 	 * grow the DDT entry by to satisfy the request.
3851 	 */
3852 	zio_prop_t czp = *zp;
3853 	czp.zp_copies = need_dvas;
3854 	zio_t *cio = zio_write(zio, spa, txg, bp, zio->io_orig_abd,
3855 	    zio->io_orig_size, zio->io_orig_size, &czp,
3856 	    zio_ddt_child_write_ready, NULL,
3857 	    zio_ddt_child_write_done, dde, zio->io_priority,
3858 	    ZIO_DDT_CHILD_FLAGS(zio), &zio->io_bookmark);
3859 
3860 	zio_push_transform(cio, zio->io_abd, zio->io_size, 0, NULL);
3861 
3862 	/*
3863 	 * We are the new lead zio, because our parent has the highest
3864 	 * zp_copies that has been requested for this entry so far.
3865 	 */
3866 	ddt_alloc_entry_io(dde);
3867 	if (dde->dde_io->dde_lead_zio[p] == NULL) {
3868 		/*
3869 		 * First time out, take a copy of the stable entry to revert
3870 		 * to if there's an error (see zio_ddt_child_write_done())
3871 		 */
3872 		ddt_phys_copy(&dde->dde_io->dde_orig_phys, dde->dde_phys, v);
3873 	} else {
3874 		/*
3875 		 * Make the existing chain our child, because it cannot
3876 		 * complete until we have.
3877 		 */
3878 		zio_add_child(cio, dde->dde_io->dde_lead_zio[p]);
3879 	}
3880 	dde->dde_io->dde_lead_zio[p] = cio;
3881 
3882 	ddt_exit(ddt);
3883 
3884 	zio_nowait(cio);
3885 
3886 	return (zio);
3887 }
3888 
3889 static ddt_entry_t *freedde; /* for debugging */
3890 
3891 static zio_t *
3892 zio_ddt_free(zio_t *zio)
3893 {
3894 	spa_t *spa = zio->io_spa;
3895 	blkptr_t *bp = zio->io_bp;
3896 	ddt_t *ddt = ddt_select(spa, bp);
3897 	ddt_entry_t *dde = NULL;
3898 
3899 	ASSERT(BP_GET_DEDUP(bp));
3900 	ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
3901 
3902 	ddt_enter(ddt);
3903 	freedde = dde = ddt_lookup(ddt, bp);
3904 	if (dde) {
3905 		ddt_phys_variant_t v = ddt_phys_select(ddt, dde, bp);
3906 		if (v != DDT_PHYS_NONE)
3907 			ddt_phys_decref(dde->dde_phys, v);
3908 	}
3909 	ddt_exit(ddt);
3910 
3911 	/*
3912 	 * When no entry was found, it must have been pruned,
3913 	 * so we can free it now instead of decrementing the
3914 	 * refcount in the DDT.
3915 	 */
3916 	if (!dde) {
3917 		BP_SET_DEDUP(bp, 0);
3918 		zio->io_pipeline |= ZIO_STAGE_DVA_FREE;
3919 	}
3920 
3921 	return (zio);
3922 }
3923 
3924 /*
3925  * ==========================================================================
3926  * Allocate and free blocks
3927  * ==========================================================================
3928  */
3929 
3930 static zio_t *
3931 zio_io_to_allocate(spa_t *spa, int allocator)
3932 {
3933 	zio_t *zio;
3934 
3935 	ASSERT(MUTEX_HELD(&spa->spa_allocs[allocator].spaa_lock));
3936 
3937 	zio = avl_first(&spa->spa_allocs[allocator].spaa_tree);
3938 	if (zio == NULL)
3939 		return (NULL);
3940 
3941 	ASSERT(IO_IS_ALLOCATING(zio));
3942 	ASSERT(ZIO_HAS_ALLOCATOR(zio));
3943 
3944 	/*
3945 	 * Try to place a reservation for this zio. If we're unable to
3946 	 * reserve then we throttle.
3947 	 */
3948 	ASSERT3U(zio->io_allocator, ==, allocator);
3949 	if (!metaslab_class_throttle_reserve(zio->io_metaslab_class,
3950 	    zio->io_prop.zp_copies, allocator, zio, 0)) {
3951 		return (NULL);
3952 	}
3953 
3954 	avl_remove(&spa->spa_allocs[allocator].spaa_tree, zio);
3955 	ASSERT3U(zio->io_stage, <, ZIO_STAGE_DVA_ALLOCATE);
3956 
3957 	return (zio);
3958 }
3959 
3960 static zio_t *
3961 zio_dva_throttle(zio_t *zio)
3962 {
3963 	spa_t *spa = zio->io_spa;
3964 	zio_t *nio;
3965 	metaslab_class_t *mc;
3966 
3967 	/* locate an appropriate allocation class */
3968 	mc = spa_preferred_class(spa, zio);
3969 
3970 	if (zio->io_priority == ZIO_PRIORITY_SYNC_WRITE ||
3971 	    !mc->mc_alloc_throttle_enabled ||
3972 	    zio->io_child_type == ZIO_CHILD_GANG ||
3973 	    zio->io_flags & ZIO_FLAG_NODATA) {
3974 		return (zio);
3975 	}
3976 
3977 	ASSERT(zio->io_type == ZIO_TYPE_WRITE);
3978 	ASSERT(ZIO_HAS_ALLOCATOR(zio));
3979 	ASSERT(zio->io_child_type > ZIO_CHILD_GANG);
3980 	ASSERT3U(zio->io_queued_timestamp, >, 0);
3981 	ASSERT(zio->io_stage == ZIO_STAGE_DVA_THROTTLE);
3982 
3983 	int allocator = zio->io_allocator;
3984 	zio->io_metaslab_class = mc;
3985 	mutex_enter(&spa->spa_allocs[allocator].spaa_lock);
3986 	avl_add(&spa->spa_allocs[allocator].spaa_tree, zio);
3987 	nio = zio_io_to_allocate(spa, allocator);
3988 	mutex_exit(&spa->spa_allocs[allocator].spaa_lock);
3989 	return (nio);
3990 }
3991 
3992 static void
3993 zio_allocate_dispatch(spa_t *spa, int allocator)
3994 {
3995 	zio_t *zio;
3996 
3997 	mutex_enter(&spa->spa_allocs[allocator].spaa_lock);
3998 	zio = zio_io_to_allocate(spa, allocator);
3999 	mutex_exit(&spa->spa_allocs[allocator].spaa_lock);
4000 	if (zio == NULL)
4001 		return;
4002 
4003 	ASSERT3U(zio->io_stage, ==, ZIO_STAGE_DVA_THROTTLE);
4004 	ASSERT0(zio->io_error);
4005 	zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE, B_TRUE);
4006 }
4007 
4008 static zio_t *
4009 zio_dva_allocate(zio_t *zio)
4010 {
4011 	spa_t *spa = zio->io_spa;
4012 	metaslab_class_t *mc;
4013 	blkptr_t *bp = zio->io_bp;
4014 	int error;
4015 	int flags = 0;
4016 
4017 	if (zio->io_gang_leader == NULL) {
4018 		ASSERT(zio->io_child_type > ZIO_CHILD_GANG);
4019 		zio->io_gang_leader = zio;
4020 	}
4021 
4022 	ASSERT(BP_IS_HOLE(bp));
4023 	ASSERT0(BP_GET_NDVAS(bp));
4024 	ASSERT3U(zio->io_prop.zp_copies, >, 0);
4025 	ASSERT3U(zio->io_prop.zp_copies, <=, spa_max_replication(spa));
4026 	ASSERT3U(zio->io_size, ==, BP_GET_PSIZE(bp));
4027 
4028 	if (zio->io_flags & ZIO_FLAG_NODATA)
4029 		flags |= METASLAB_DONT_THROTTLE;
4030 	if (zio->io_flags & ZIO_FLAG_GANG_CHILD)
4031 		flags |= METASLAB_GANG_CHILD;
4032 	if (zio->io_priority == ZIO_PRIORITY_ASYNC_WRITE)
4033 		flags |= METASLAB_ASYNC_ALLOC;
4034 
4035 	/*
4036 	 * if not already chosen, locate an appropriate allocation class
4037 	 */
4038 	mc = zio->io_metaslab_class;
4039 	if (mc == NULL) {
4040 		mc = spa_preferred_class(spa, zio);
4041 		zio->io_metaslab_class = mc;
4042 	}
4043 
4044 	/*
4045 	 * Try allocating the block in the usual metaslab class.
4046 	 * If that's full, allocate it in the normal class.
4047 	 * If that's full, allocate as a gang block,
4048 	 * and if all are full, the allocation fails (which shouldn't happen).
4049 	 *
4050 	 * Note that we do not fall back on embedded slog (ZIL) space, to
4051 	 * preserve unfragmented slog space, which is critical for decent
4052 	 * sync write performance.  If a log allocation fails, we will fall
4053 	 * back to spa_sync() which is abysmal for performance.
4054 	 */
4055 	ASSERT(ZIO_HAS_ALLOCATOR(zio));
4056 	error = metaslab_alloc(spa, mc, zio->io_size, bp,
4057 	    zio->io_prop.zp_copies, zio->io_txg, NULL, flags,
4058 	    &zio->io_alloc_list, zio, zio->io_allocator);
4059 
4060 	/*
4061 	 * Fallback to normal class when an alloc class is full
4062 	 */
4063 	if (error == ENOSPC && mc != spa_normal_class(spa)) {
4064 		/*
4065 		 * When the dedup or special class is spilling into the  normal
4066 		 * class, there can still be significant space available due
4067 		 * to deferred frees that are in-flight.  We track the txg when
4068 		 * this occurred and back off adding new DDT entries for a few
4069 		 * txgs to allow the free blocks to be processed.
4070 		 */
4071 		if ((mc == spa_dedup_class(spa) || (spa_special_has_ddt(spa) &&
4072 		    mc == spa_special_class(spa))) &&
4073 		    spa->spa_dedup_class_full_txg != zio->io_txg) {
4074 			spa->spa_dedup_class_full_txg = zio->io_txg;
4075 			zfs_dbgmsg("%s[%d]: %s class spilling, req size %d, "
4076 			    "%llu allocated of %llu",
4077 			    spa_name(spa), (int)zio->io_txg,
4078 			    mc == spa_dedup_class(spa) ? "dedup" : "special",
4079 			    (int)zio->io_size,
4080 			    (u_longlong_t)metaslab_class_get_alloc(mc),
4081 			    (u_longlong_t)metaslab_class_get_space(mc));
4082 		}
4083 
4084 		/*
4085 		 * If throttling, transfer reservation over to normal class.
4086 		 * The io_allocator slot can remain the same even though we
4087 		 * are switching classes.
4088 		 */
4089 		if (mc->mc_alloc_throttle_enabled &&
4090 		    (zio->io_flags & ZIO_FLAG_IO_ALLOCATING)) {
4091 			metaslab_class_throttle_unreserve(mc,
4092 			    zio->io_prop.zp_copies, zio->io_allocator, zio);
4093 			zio->io_flags &= ~ZIO_FLAG_IO_ALLOCATING;
4094 
4095 			VERIFY(metaslab_class_throttle_reserve(
4096 			    spa_normal_class(spa),
4097 			    zio->io_prop.zp_copies, zio->io_allocator, zio,
4098 			    flags | METASLAB_MUST_RESERVE));
4099 		}
4100 		zio->io_metaslab_class = mc = spa_normal_class(spa);
4101 		if (zfs_flags & ZFS_DEBUG_METASLAB_ALLOC) {
4102 			zfs_dbgmsg("%s: metaslab allocation failure, "
4103 			    "trying normal class: zio %px, size %llu, error %d",
4104 			    spa_name(spa), zio, (u_longlong_t)zio->io_size,
4105 			    error);
4106 		}
4107 
4108 		error = metaslab_alloc(spa, mc, zio->io_size, bp,
4109 		    zio->io_prop.zp_copies, zio->io_txg, NULL, flags,
4110 		    &zio->io_alloc_list, zio, zio->io_allocator);
4111 	}
4112 
4113 	if (error == ENOSPC && zio->io_size > SPA_MINBLOCKSIZE) {
4114 		if (zfs_flags & ZFS_DEBUG_METASLAB_ALLOC) {
4115 			zfs_dbgmsg("%s: metaslab allocation failure, "
4116 			    "trying ganging: zio %px, size %llu, error %d",
4117 			    spa_name(spa), zio, (u_longlong_t)zio->io_size,
4118 			    error);
4119 		}
4120 		return (zio_write_gang_block(zio, mc));
4121 	}
4122 	if (error != 0) {
4123 		if (error != ENOSPC ||
4124 		    (zfs_flags & ZFS_DEBUG_METASLAB_ALLOC)) {
4125 			zfs_dbgmsg("%s: metaslab allocation failure: zio %px, "
4126 			    "size %llu, error %d",
4127 			    spa_name(spa), zio, (u_longlong_t)zio->io_size,
4128 			    error);
4129 		}
4130 		zio->io_error = error;
4131 	}
4132 
4133 	return (zio);
4134 }
4135 
4136 static zio_t *
4137 zio_dva_free(zio_t *zio)
4138 {
4139 	metaslab_free(zio->io_spa, zio->io_bp, zio->io_txg, B_FALSE);
4140 
4141 	return (zio);
4142 }
4143 
4144 static zio_t *
4145 zio_dva_claim(zio_t *zio)
4146 {
4147 	int error;
4148 
4149 	error = metaslab_claim(zio->io_spa, zio->io_bp, zio->io_txg);
4150 	if (error)
4151 		zio->io_error = error;
4152 
4153 	return (zio);
4154 }
4155 
4156 /*
4157  * Undo an allocation.  This is used by zio_done() when an I/O fails
4158  * and we want to give back the block we just allocated.
4159  * This handles both normal blocks and gang blocks.
4160  */
4161 static void
4162 zio_dva_unallocate(zio_t *zio, zio_gang_node_t *gn, blkptr_t *bp)
4163 {
4164 	ASSERT(BP_GET_LOGICAL_BIRTH(bp) == zio->io_txg || BP_IS_HOLE(bp));
4165 	ASSERT(zio->io_bp_override == NULL);
4166 
4167 	if (!BP_IS_HOLE(bp)) {
4168 		metaslab_free(zio->io_spa, bp, BP_GET_LOGICAL_BIRTH(bp),
4169 		    B_TRUE);
4170 	}
4171 
4172 	if (gn != NULL) {
4173 		for (int g = 0; g < SPA_GBH_NBLKPTRS; g++) {
4174 			zio_dva_unallocate(zio, gn->gn_child[g],
4175 			    &gn->gn_gbh->zg_blkptr[g]);
4176 		}
4177 	}
4178 }
4179 
4180 /*
4181  * Try to allocate an intent log block.  Return 0 on success, errno on failure.
4182  */
4183 int
4184 zio_alloc_zil(spa_t *spa, objset_t *os, uint64_t txg, blkptr_t *new_bp,
4185     uint64_t size, boolean_t *slog)
4186 {
4187 	int error = 1;
4188 	zio_alloc_list_t io_alloc_list;
4189 
4190 	ASSERT(txg > spa_syncing_txg(spa));
4191 
4192 	metaslab_trace_init(&io_alloc_list);
4193 
4194 	/*
4195 	 * Block pointer fields are useful to metaslabs for stats and debugging.
4196 	 * Fill in the obvious ones before calling into metaslab_alloc().
4197 	 */
4198 	BP_SET_TYPE(new_bp, DMU_OT_INTENT_LOG);
4199 	BP_SET_PSIZE(new_bp, size);
4200 	BP_SET_LEVEL(new_bp, 0);
4201 
4202 	/*
4203 	 * When allocating a zil block, we don't have information about
4204 	 * the final destination of the block except the objset it's part
4205 	 * of, so we just hash the objset ID to pick the allocator to get
4206 	 * some parallelism.
4207 	 */
4208 	int flags = METASLAB_ZIL;
4209 	int allocator = (uint_t)cityhash1(os->os_dsl_dataset->ds_object)
4210 	    % spa->spa_alloc_count;
4211 	error = metaslab_alloc(spa, spa_log_class(spa), size, new_bp, 1,
4212 	    txg, NULL, flags, &io_alloc_list, NULL, allocator);
4213 	*slog = (error == 0);
4214 	if (error != 0) {
4215 		error = metaslab_alloc(spa, spa_embedded_log_class(spa), size,
4216 		    new_bp, 1, txg, NULL, flags,
4217 		    &io_alloc_list, NULL, allocator);
4218 	}
4219 	if (error != 0) {
4220 		error = metaslab_alloc(spa, spa_normal_class(spa), size,
4221 		    new_bp, 1, txg, NULL, flags,
4222 		    &io_alloc_list, NULL, allocator);
4223 	}
4224 	metaslab_trace_fini(&io_alloc_list);
4225 
4226 	if (error == 0) {
4227 		BP_SET_LSIZE(new_bp, size);
4228 		BP_SET_PSIZE(new_bp, size);
4229 		BP_SET_COMPRESS(new_bp, ZIO_COMPRESS_OFF);
4230 		BP_SET_CHECKSUM(new_bp,
4231 		    spa_version(spa) >= SPA_VERSION_SLIM_ZIL
4232 		    ? ZIO_CHECKSUM_ZILOG2 : ZIO_CHECKSUM_ZILOG);
4233 		BP_SET_TYPE(new_bp, DMU_OT_INTENT_LOG);
4234 		BP_SET_LEVEL(new_bp, 0);
4235 		BP_SET_DEDUP(new_bp, 0);
4236 		BP_SET_BYTEORDER(new_bp, ZFS_HOST_BYTEORDER);
4237 
4238 		/*
4239 		 * encrypted blocks will require an IV and salt. We generate
4240 		 * these now since we will not be rewriting the bp at
4241 		 * rewrite time.
4242 		 */
4243 		if (os->os_encrypted) {
4244 			uint8_t iv[ZIO_DATA_IV_LEN];
4245 			uint8_t salt[ZIO_DATA_SALT_LEN];
4246 
4247 			BP_SET_CRYPT(new_bp, B_TRUE);
4248 			VERIFY0(spa_crypt_get_salt(spa,
4249 			    dmu_objset_id(os), salt));
4250 			VERIFY0(zio_crypt_generate_iv(iv));
4251 
4252 			zio_crypt_encode_params_bp(new_bp, salt, iv);
4253 		}
4254 	} else {
4255 		zfs_dbgmsg("%s: zil block allocation failure: "
4256 		    "size %llu, error %d", spa_name(spa), (u_longlong_t)size,
4257 		    error);
4258 	}
4259 
4260 	return (error);
4261 }
4262 
4263 /*
4264  * ==========================================================================
4265  * Read and write to physical devices
4266  * ==========================================================================
4267  */
4268 
4269 /*
4270  * Issue an I/O to the underlying vdev. Typically the issue pipeline
4271  * stops after this stage and will resume upon I/O completion.
4272  * However, there are instances where the vdev layer may need to
4273  * continue the pipeline when an I/O was not issued. Since the I/O
4274  * that was sent to the vdev layer might be different than the one
4275  * currently active in the pipeline (see vdev_queue_io()), we explicitly
4276  * force the underlying vdev layers to call either zio_execute() or
4277  * zio_interrupt() to ensure that the pipeline continues with the correct I/O.
4278  */
4279 static zio_t *
4280 zio_vdev_io_start(zio_t *zio)
4281 {
4282 	vdev_t *vd = zio->io_vd;
4283 	uint64_t align;
4284 	spa_t *spa = zio->io_spa;
4285 
4286 	zio->io_delay = 0;
4287 
4288 	ASSERT(zio->io_error == 0);
4289 	ASSERT(zio->io_child_error[ZIO_CHILD_VDEV] == 0);
4290 
4291 	if (vd == NULL) {
4292 		if (!(zio->io_flags & ZIO_FLAG_CONFIG_WRITER))
4293 			spa_config_enter(spa, SCL_ZIO, zio, RW_READER);
4294 
4295 		/*
4296 		 * The mirror_ops handle multiple DVAs in a single BP.
4297 		 */
4298 		vdev_mirror_ops.vdev_op_io_start(zio);
4299 		return (NULL);
4300 	}
4301 
4302 	ASSERT3P(zio->io_logical, !=, zio);
4303 	if (zio->io_type == ZIO_TYPE_WRITE) {
4304 		ASSERT(spa->spa_trust_config);
4305 
4306 		/*
4307 		 * Note: the code can handle other kinds of writes,
4308 		 * but we don't expect them.
4309 		 */
4310 		if (zio->io_vd->vdev_noalloc) {
4311 			ASSERT(zio->io_flags &
4312 			    (ZIO_FLAG_PHYSICAL | ZIO_FLAG_SELF_HEAL |
4313 			    ZIO_FLAG_RESILVER | ZIO_FLAG_INDUCE_DAMAGE));
4314 		}
4315 	}
4316 
4317 	align = 1ULL << vd->vdev_top->vdev_ashift;
4318 
4319 	if (!(zio->io_flags & ZIO_FLAG_PHYSICAL) &&
4320 	    P2PHASE(zio->io_size, align) != 0) {
4321 		/* Transform logical writes to be a full physical block size. */
4322 		uint64_t asize = P2ROUNDUP(zio->io_size, align);
4323 		abd_t *abuf = abd_alloc_sametype(zio->io_abd, asize);
4324 		ASSERT(vd == vd->vdev_top);
4325 		if (zio->io_type == ZIO_TYPE_WRITE) {
4326 			abd_copy(abuf, zio->io_abd, zio->io_size);
4327 			abd_zero_off(abuf, zio->io_size, asize - zio->io_size);
4328 		}
4329 		zio_push_transform(zio, abuf, asize, asize, zio_subblock);
4330 	}
4331 
4332 	/*
4333 	 * If this is not a physical io, make sure that it is properly aligned
4334 	 * before proceeding.
4335 	 */
4336 	if (!(zio->io_flags & ZIO_FLAG_PHYSICAL)) {
4337 		ASSERT0(P2PHASE(zio->io_offset, align));
4338 		ASSERT0(P2PHASE(zio->io_size, align));
4339 	} else {
4340 		/*
4341 		 * For physical writes, we allow 512b aligned writes and assume
4342 		 * the device will perform a read-modify-write as necessary.
4343 		 */
4344 		ASSERT0(P2PHASE(zio->io_offset, SPA_MINBLOCKSIZE));
4345 		ASSERT0(P2PHASE(zio->io_size, SPA_MINBLOCKSIZE));
4346 	}
4347 
4348 	VERIFY(zio->io_type != ZIO_TYPE_WRITE || spa_writeable(spa));
4349 
4350 	/*
4351 	 * If this is a repair I/O, and there's no self-healing involved --
4352 	 * that is, we're just resilvering what we expect to resilver --
4353 	 * then don't do the I/O unless zio's txg is actually in vd's DTL.
4354 	 * This prevents spurious resilvering.
4355 	 *
4356 	 * There are a few ways that we can end up creating these spurious
4357 	 * resilver i/os:
4358 	 *
4359 	 * 1. A resilver i/o will be issued if any DVA in the BP has a
4360 	 * dirty DTL.  The mirror code will issue resilver writes to
4361 	 * each DVA, including the one(s) that are not on vdevs with dirty
4362 	 * DTLs.
4363 	 *
4364 	 * 2. With nested replication, which happens when we have a
4365 	 * "replacing" or "spare" vdev that's a child of a mirror or raidz.
4366 	 * For example, given mirror(replacing(A+B), C), it's likely that
4367 	 * only A is out of date (it's the new device). In this case, we'll
4368 	 * read from C, then use the data to resilver A+B -- but we don't
4369 	 * actually want to resilver B, just A. The top-level mirror has no
4370 	 * way to know this, so instead we just discard unnecessary repairs
4371 	 * as we work our way down the vdev tree.
4372 	 *
4373 	 * 3. ZTEST also creates mirrors of mirrors, mirrors of raidz, etc.
4374 	 * The same logic applies to any form of nested replication: ditto
4375 	 * + mirror, RAID-Z + replacing, etc.
4376 	 *
4377 	 * However, indirect vdevs point off to other vdevs which may have
4378 	 * DTL's, so we never bypass them.  The child i/os on concrete vdevs
4379 	 * will be properly bypassed instead.
4380 	 *
4381 	 * Leaf DTL_PARTIAL can be empty when a legitimate write comes from
4382 	 * a dRAID spare vdev. For example, when a dRAID spare is first
4383 	 * used, its spare blocks need to be written to but the leaf vdev's
4384 	 * of such blocks can have empty DTL_PARTIAL.
4385 	 *
4386 	 * There seemed no clean way to allow such writes while bypassing
4387 	 * spurious ones. At this point, just avoid all bypassing for dRAID
4388 	 * for correctness.
4389 	 */
4390 	if ((zio->io_flags & ZIO_FLAG_IO_REPAIR) &&
4391 	    !(zio->io_flags & ZIO_FLAG_SELF_HEAL) &&
4392 	    zio->io_txg != 0 &&	/* not a delegated i/o */
4393 	    vd->vdev_ops != &vdev_indirect_ops &&
4394 	    vd->vdev_top->vdev_ops != &vdev_draid_ops &&
4395 	    !vdev_dtl_contains(vd, DTL_PARTIAL, zio->io_txg, 1)) {
4396 		ASSERT(zio->io_type == ZIO_TYPE_WRITE);
4397 		zio_vdev_io_bypass(zio);
4398 		return (zio);
4399 	}
4400 
4401 	/*
4402 	 * Select the next best leaf I/O to process.  Distributed spares are
4403 	 * excluded since they dispatch the I/O directly to a leaf vdev after
4404 	 * applying the dRAID mapping.
4405 	 */
4406 	if (vd->vdev_ops->vdev_op_leaf &&
4407 	    vd->vdev_ops != &vdev_draid_spare_ops &&
4408 	    (zio->io_type == ZIO_TYPE_READ ||
4409 	    zio->io_type == ZIO_TYPE_WRITE ||
4410 	    zio->io_type == ZIO_TYPE_TRIM)) {
4411 
4412 		if (zio_handle_device_injection(vd, zio, ENOSYS) != 0) {
4413 			/*
4414 			 * "no-op" injections return success, but do no actual
4415 			 * work. Just skip the remaining vdev stages.
4416 			 */
4417 			zio_vdev_io_bypass(zio);
4418 			zio_interrupt(zio);
4419 			return (NULL);
4420 		}
4421 
4422 		if ((zio = vdev_queue_io(zio)) == NULL)
4423 			return (NULL);
4424 
4425 		if (!vdev_accessible(vd, zio)) {
4426 			zio->io_error = SET_ERROR(ENXIO);
4427 			zio_interrupt(zio);
4428 			return (NULL);
4429 		}
4430 		zio->io_delay = gethrtime();
4431 	}
4432 
4433 	vd->vdev_ops->vdev_op_io_start(zio);
4434 	return (NULL);
4435 }
4436 
4437 static zio_t *
4438 zio_vdev_io_done(zio_t *zio)
4439 {
4440 	vdev_t *vd = zio->io_vd;
4441 	vdev_ops_t *ops = vd ? vd->vdev_ops : &vdev_mirror_ops;
4442 	boolean_t unexpected_error = B_FALSE;
4443 
4444 	if (zio_wait_for_children(zio, ZIO_CHILD_VDEV_BIT, ZIO_WAIT_DONE)) {
4445 		return (NULL);
4446 	}
4447 
4448 	ASSERT(zio->io_type == ZIO_TYPE_READ ||
4449 	    zio->io_type == ZIO_TYPE_WRITE ||
4450 	    zio->io_type == ZIO_TYPE_FLUSH ||
4451 	    zio->io_type == ZIO_TYPE_TRIM);
4452 
4453 	if (zio->io_delay)
4454 		zio->io_delay = gethrtime() - zio->io_delay;
4455 
4456 	if (vd != NULL && vd->vdev_ops->vdev_op_leaf &&
4457 	    vd->vdev_ops != &vdev_draid_spare_ops) {
4458 		if (zio->io_type != ZIO_TYPE_FLUSH)
4459 			vdev_queue_io_done(zio);
4460 
4461 		if (zio_injection_enabled && zio->io_error == 0)
4462 			zio->io_error = zio_handle_device_injections(vd, zio,
4463 			    EIO, EILSEQ);
4464 
4465 		if (zio_injection_enabled && zio->io_error == 0)
4466 			zio->io_error = zio_handle_label_injection(zio, EIO);
4467 
4468 		if (zio->io_error && zio->io_type != ZIO_TYPE_FLUSH &&
4469 		    zio->io_type != ZIO_TYPE_TRIM) {
4470 			if (!vdev_accessible(vd, zio)) {
4471 				zio->io_error = SET_ERROR(ENXIO);
4472 			} else {
4473 				unexpected_error = B_TRUE;
4474 			}
4475 		}
4476 	}
4477 
4478 	ops->vdev_op_io_done(zio);
4479 
4480 	if (unexpected_error && vd->vdev_remove_wanted == B_FALSE)
4481 		VERIFY(vdev_probe(vd, zio) == NULL);
4482 
4483 	return (zio);
4484 }
4485 
4486 /*
4487  * This function is used to change the priority of an existing zio that is
4488  * currently in-flight. This is used by the arc to upgrade priority in the
4489  * event that a demand read is made for a block that is currently queued
4490  * as a scrub or async read IO. Otherwise, the high priority read request
4491  * would end up having to wait for the lower priority IO.
4492  */
4493 void
4494 zio_change_priority(zio_t *pio, zio_priority_t priority)
4495 {
4496 	zio_t *cio, *cio_next;
4497 	zio_link_t *zl = NULL;
4498 
4499 	ASSERT3U(priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
4500 
4501 	if (pio->io_vd != NULL && pio->io_vd->vdev_ops->vdev_op_leaf) {
4502 		vdev_queue_change_io_priority(pio, priority);
4503 	} else {
4504 		pio->io_priority = priority;
4505 	}
4506 
4507 	mutex_enter(&pio->io_lock);
4508 	for (cio = zio_walk_children(pio, &zl); cio != NULL; cio = cio_next) {
4509 		cio_next = zio_walk_children(pio, &zl);
4510 		zio_change_priority(cio, priority);
4511 	}
4512 	mutex_exit(&pio->io_lock);
4513 }
4514 
4515 /*
4516  * For non-raidz ZIOs, we can just copy aside the bad data read from the
4517  * disk, and use that to finish the checksum ereport later.
4518  */
4519 static void
4520 zio_vsd_default_cksum_finish(zio_cksum_report_t *zcr,
4521     const abd_t *good_buf)
4522 {
4523 	/* no processing needed */
4524 	zfs_ereport_finish_checksum(zcr, good_buf, zcr->zcr_cbdata, B_FALSE);
4525 }
4526 
4527 void
4528 zio_vsd_default_cksum_report(zio_t *zio, zio_cksum_report_t *zcr)
4529 {
4530 	void *abd = abd_alloc_sametype(zio->io_abd, zio->io_size);
4531 
4532 	abd_copy(abd, zio->io_abd, zio->io_size);
4533 
4534 	zcr->zcr_cbinfo = zio->io_size;
4535 	zcr->zcr_cbdata = abd;
4536 	zcr->zcr_finish = zio_vsd_default_cksum_finish;
4537 	zcr->zcr_free = zio_abd_free;
4538 }
4539 
4540 static zio_t *
4541 zio_vdev_io_assess(zio_t *zio)
4542 {
4543 	vdev_t *vd = zio->io_vd;
4544 
4545 	if (zio_wait_for_children(zio, ZIO_CHILD_VDEV_BIT, ZIO_WAIT_DONE)) {
4546 		return (NULL);
4547 	}
4548 
4549 	if (vd == NULL && !(zio->io_flags & ZIO_FLAG_CONFIG_WRITER))
4550 		spa_config_exit(zio->io_spa, SCL_ZIO, zio);
4551 
4552 	if (zio->io_vsd != NULL) {
4553 		zio->io_vsd_ops->vsd_free(zio);
4554 		zio->io_vsd = NULL;
4555 	}
4556 
4557 	/*
4558 	 * If a Direct I/O write checksum verify error has occurred then this
4559 	 * I/O should not attempt to be issued again. Instead the EIO will
4560 	 * be returned.
4561 	 */
4562 	if (zio->io_flags & ZIO_FLAG_DIO_CHKSUM_ERR) {
4563 		ASSERT3U(zio->io_child_type, ==, ZIO_CHILD_LOGICAL);
4564 		ASSERT3U(zio->io_error, ==, EIO);
4565 		zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
4566 		return (zio);
4567 	}
4568 
4569 
4570 	if (zio_injection_enabled && zio->io_error == 0)
4571 		zio->io_error = zio_handle_fault_injection(zio, EIO);
4572 
4573 	/*
4574 	 * If the I/O failed, determine whether we should attempt to retry it.
4575 	 *
4576 	 * On retry, we cut in line in the issue queue, since we don't want
4577 	 * compression/checksumming/etc. work to prevent our (cheap) IO reissue.
4578 	 */
4579 	if (zio->io_error && vd == NULL &&
4580 	    !(zio->io_flags & (ZIO_FLAG_DONT_RETRY | ZIO_FLAG_IO_RETRY))) {
4581 		ASSERT(!(zio->io_flags & ZIO_FLAG_DONT_QUEUE));	/* not a leaf */
4582 		ASSERT(!(zio->io_flags & ZIO_FLAG_IO_BYPASS));	/* not a leaf */
4583 		zio->io_error = 0;
4584 		zio->io_flags |= ZIO_FLAG_IO_RETRY | ZIO_FLAG_DONT_AGGREGATE;
4585 		zio->io_stage = ZIO_STAGE_VDEV_IO_START >> 1;
4586 		zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE,
4587 		    zio_requeue_io_start_cut_in_line);
4588 		return (NULL);
4589 	}
4590 
4591 	/*
4592 	 * If we got an error on a leaf device, convert it to ENXIO
4593 	 * if the device is not accessible at all.
4594 	 */
4595 	if (zio->io_error && vd != NULL && vd->vdev_ops->vdev_op_leaf &&
4596 	    !vdev_accessible(vd, zio))
4597 		zio->io_error = SET_ERROR(ENXIO);
4598 
4599 	/*
4600 	 * If we can't write to an interior vdev (mirror or RAID-Z),
4601 	 * set vdev_cant_write so that we stop trying to allocate from it.
4602 	 */
4603 	if (zio->io_error == ENXIO && zio->io_type == ZIO_TYPE_WRITE &&
4604 	    vd != NULL && !vd->vdev_ops->vdev_op_leaf) {
4605 		vdev_dbgmsg(vd, "zio_vdev_io_assess(zio=%px) setting "
4606 		    "cant_write=TRUE due to write failure with ENXIO",
4607 		    zio);
4608 		vd->vdev_cant_write = B_TRUE;
4609 	}
4610 
4611 	/*
4612 	 * If a cache flush returns ENOTSUP or ENOTTY, we know that no future
4613 	 * attempts will ever succeed. In this case we set a persistent
4614 	 * boolean flag so that we don't bother with it in the future.
4615 	 */
4616 	if ((zio->io_error == ENOTSUP || zio->io_error == ENOTTY) &&
4617 	    zio->io_type == ZIO_TYPE_FLUSH && vd != NULL)
4618 		vd->vdev_nowritecache = B_TRUE;
4619 
4620 	if (zio->io_error)
4621 		zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
4622 
4623 	return (zio);
4624 }
4625 
4626 void
4627 zio_vdev_io_reissue(zio_t *zio)
4628 {
4629 	ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_START);
4630 	ASSERT(zio->io_error == 0);
4631 
4632 	zio->io_stage >>= 1;
4633 }
4634 
4635 void
4636 zio_vdev_io_redone(zio_t *zio)
4637 {
4638 	ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_DONE);
4639 
4640 	zio->io_stage >>= 1;
4641 }
4642 
4643 void
4644 zio_vdev_io_bypass(zio_t *zio)
4645 {
4646 	ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_START);
4647 	ASSERT(zio->io_error == 0);
4648 
4649 	zio->io_flags |= ZIO_FLAG_IO_BYPASS;
4650 	zio->io_stage = ZIO_STAGE_VDEV_IO_ASSESS >> 1;
4651 }
4652 
4653 /*
4654  * ==========================================================================
4655  * Encrypt and store encryption parameters
4656  * ==========================================================================
4657  */
4658 
4659 
4660 /*
4661  * This function is used for ZIO_STAGE_ENCRYPT. It is responsible for
4662  * managing the storage of encryption parameters and passing them to the
4663  * lower-level encryption functions.
4664  */
4665 static zio_t *
4666 zio_encrypt(zio_t *zio)
4667 {
4668 	zio_prop_t *zp = &zio->io_prop;
4669 	spa_t *spa = zio->io_spa;
4670 	blkptr_t *bp = zio->io_bp;
4671 	uint64_t psize = BP_GET_PSIZE(bp);
4672 	uint64_t dsobj = zio->io_bookmark.zb_objset;
4673 	dmu_object_type_t ot = BP_GET_TYPE(bp);
4674 	void *enc_buf = NULL;
4675 	abd_t *eabd = NULL;
4676 	uint8_t salt[ZIO_DATA_SALT_LEN];
4677 	uint8_t iv[ZIO_DATA_IV_LEN];
4678 	uint8_t mac[ZIO_DATA_MAC_LEN];
4679 	boolean_t no_crypt = B_FALSE;
4680 
4681 	/* the root zio already encrypted the data */
4682 	if (zio->io_child_type == ZIO_CHILD_GANG)
4683 		return (zio);
4684 
4685 	/* only ZIL blocks are re-encrypted on rewrite */
4686 	if (!IO_IS_ALLOCATING(zio) && ot != DMU_OT_INTENT_LOG)
4687 		return (zio);
4688 
4689 	if (!(zp->zp_encrypt || BP_IS_ENCRYPTED(bp))) {
4690 		BP_SET_CRYPT(bp, B_FALSE);
4691 		return (zio);
4692 	}
4693 
4694 	/* if we are doing raw encryption set the provided encryption params */
4695 	if (zio->io_flags & ZIO_FLAG_RAW_ENCRYPT) {
4696 		ASSERT0(BP_GET_LEVEL(bp));
4697 		BP_SET_CRYPT(bp, B_TRUE);
4698 		BP_SET_BYTEORDER(bp, zp->zp_byteorder);
4699 		if (ot != DMU_OT_OBJSET)
4700 			zio_crypt_encode_mac_bp(bp, zp->zp_mac);
4701 
4702 		/* dnode blocks must be written out in the provided byteorder */
4703 		if (zp->zp_byteorder != ZFS_HOST_BYTEORDER &&
4704 		    ot == DMU_OT_DNODE) {
4705 			void *bswap_buf = zio_buf_alloc(psize);
4706 			abd_t *babd = abd_get_from_buf(bswap_buf, psize);
4707 
4708 			ASSERT3U(BP_GET_COMPRESS(bp), ==, ZIO_COMPRESS_OFF);
4709 			abd_copy_to_buf(bswap_buf, zio->io_abd, psize);
4710 			dmu_ot_byteswap[DMU_OT_BYTESWAP(ot)].ob_func(bswap_buf,
4711 			    psize);
4712 
4713 			abd_take_ownership_of_buf(babd, B_TRUE);
4714 			zio_push_transform(zio, babd, psize, psize, NULL);
4715 		}
4716 
4717 		if (DMU_OT_IS_ENCRYPTED(ot))
4718 			zio_crypt_encode_params_bp(bp, zp->zp_salt, zp->zp_iv);
4719 		return (zio);
4720 	}
4721 
4722 	/* indirect blocks only maintain a cksum of the lower level MACs */
4723 	if (BP_GET_LEVEL(bp) > 0) {
4724 		BP_SET_CRYPT(bp, B_TRUE);
4725 		VERIFY0(zio_crypt_do_indirect_mac_checksum_abd(B_TRUE,
4726 		    zio->io_orig_abd, BP_GET_LSIZE(bp), BP_SHOULD_BYTESWAP(bp),
4727 		    mac));
4728 		zio_crypt_encode_mac_bp(bp, mac);
4729 		return (zio);
4730 	}
4731 
4732 	/*
4733 	 * Objset blocks are a special case since they have 2 256-bit MACs
4734 	 * embedded within them.
4735 	 */
4736 	if (ot == DMU_OT_OBJSET) {
4737 		ASSERT0(DMU_OT_IS_ENCRYPTED(ot));
4738 		ASSERT3U(BP_GET_COMPRESS(bp), ==, ZIO_COMPRESS_OFF);
4739 		BP_SET_CRYPT(bp, B_TRUE);
4740 		VERIFY0(spa_do_crypt_objset_mac_abd(B_TRUE, spa, dsobj,
4741 		    zio->io_abd, psize, BP_SHOULD_BYTESWAP(bp)));
4742 		return (zio);
4743 	}
4744 
4745 	/* unencrypted object types are only authenticated with a MAC */
4746 	if (!DMU_OT_IS_ENCRYPTED(ot)) {
4747 		BP_SET_CRYPT(bp, B_TRUE);
4748 		VERIFY0(spa_do_crypt_mac_abd(B_TRUE, spa, dsobj,
4749 		    zio->io_abd, psize, mac));
4750 		zio_crypt_encode_mac_bp(bp, mac);
4751 		return (zio);
4752 	}
4753 
4754 	/*
4755 	 * Later passes of sync-to-convergence may decide to rewrite data
4756 	 * in place to avoid more disk reallocations. This presents a problem
4757 	 * for encryption because this constitutes rewriting the new data with
4758 	 * the same encryption key and IV. However, this only applies to blocks
4759 	 * in the MOS (particularly the spacemaps) and we do not encrypt the
4760 	 * MOS. We assert that the zio is allocating or an intent log write
4761 	 * to enforce this.
4762 	 */
4763 	ASSERT(IO_IS_ALLOCATING(zio) || ot == DMU_OT_INTENT_LOG);
4764 	ASSERT(BP_GET_LEVEL(bp) == 0 || ot == DMU_OT_INTENT_LOG);
4765 	ASSERT(spa_feature_is_active(spa, SPA_FEATURE_ENCRYPTION));
4766 	ASSERT3U(psize, !=, 0);
4767 
4768 	enc_buf = zio_buf_alloc(psize);
4769 	eabd = abd_get_from_buf(enc_buf, psize);
4770 	abd_take_ownership_of_buf(eabd, B_TRUE);
4771 
4772 	/*
4773 	 * For an explanation of what encryption parameters are stored
4774 	 * where, see the block comment in zio_crypt.c.
4775 	 */
4776 	if (ot == DMU_OT_INTENT_LOG) {
4777 		zio_crypt_decode_params_bp(bp, salt, iv);
4778 	} else {
4779 		BP_SET_CRYPT(bp, B_TRUE);
4780 	}
4781 
4782 	/* Perform the encryption. This should not fail */
4783 	VERIFY0(spa_do_crypt_abd(B_TRUE, spa, &zio->io_bookmark,
4784 	    BP_GET_TYPE(bp), BP_GET_DEDUP(bp), BP_SHOULD_BYTESWAP(bp),
4785 	    salt, iv, mac, psize, zio->io_abd, eabd, &no_crypt));
4786 
4787 	/* encode encryption metadata into the bp */
4788 	if (ot == DMU_OT_INTENT_LOG) {
4789 		/*
4790 		 * ZIL blocks store the MAC in the embedded checksum, so the
4791 		 * transform must always be applied.
4792 		 */
4793 		zio_crypt_encode_mac_zil(enc_buf, mac);
4794 		zio_push_transform(zio, eabd, psize, psize, NULL);
4795 	} else {
4796 		BP_SET_CRYPT(bp, B_TRUE);
4797 		zio_crypt_encode_params_bp(bp, salt, iv);
4798 		zio_crypt_encode_mac_bp(bp, mac);
4799 
4800 		if (no_crypt) {
4801 			ASSERT3U(ot, ==, DMU_OT_DNODE);
4802 			abd_free(eabd);
4803 		} else {
4804 			zio_push_transform(zio, eabd, psize, psize, NULL);
4805 		}
4806 	}
4807 
4808 	return (zio);
4809 }
4810 
4811 /*
4812  * ==========================================================================
4813  * Generate and verify checksums
4814  * ==========================================================================
4815  */
4816 static zio_t *
4817 zio_checksum_generate(zio_t *zio)
4818 {
4819 	blkptr_t *bp = zio->io_bp;
4820 	enum zio_checksum checksum;
4821 
4822 	if (bp == NULL) {
4823 		/*
4824 		 * This is zio_write_phys().
4825 		 * We're either generating a label checksum, or none at all.
4826 		 */
4827 		checksum = zio->io_prop.zp_checksum;
4828 
4829 		if (checksum == ZIO_CHECKSUM_OFF)
4830 			return (zio);
4831 
4832 		ASSERT(checksum == ZIO_CHECKSUM_LABEL);
4833 	} else {
4834 		if (BP_IS_GANG(bp) && zio->io_child_type == ZIO_CHILD_GANG) {
4835 			ASSERT(!IO_IS_ALLOCATING(zio));
4836 			checksum = ZIO_CHECKSUM_GANG_HEADER;
4837 		} else {
4838 			checksum = BP_GET_CHECKSUM(bp);
4839 		}
4840 	}
4841 
4842 	zio_checksum_compute(zio, checksum, zio->io_abd, zio->io_size);
4843 
4844 	return (zio);
4845 }
4846 
4847 static zio_t *
4848 zio_checksum_verify(zio_t *zio)
4849 {
4850 	zio_bad_cksum_t info;
4851 	blkptr_t *bp = zio->io_bp;
4852 	int error;
4853 
4854 	ASSERT(zio->io_vd != NULL);
4855 
4856 	if (bp == NULL) {
4857 		/*
4858 		 * This is zio_read_phys().
4859 		 * We're either verifying a label checksum, or nothing at all.
4860 		 */
4861 		if (zio->io_prop.zp_checksum == ZIO_CHECKSUM_OFF)
4862 			return (zio);
4863 
4864 		ASSERT3U(zio->io_prop.zp_checksum, ==, ZIO_CHECKSUM_LABEL);
4865 	}
4866 
4867 	if ((error = zio_checksum_error(zio, &info)) != 0) {
4868 		zio->io_error = error;
4869 		if (error == ECKSUM &&
4870 		    !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
4871 			mutex_enter(&zio->io_vd->vdev_stat_lock);
4872 			zio->io_vd->vdev_stat.vs_checksum_errors++;
4873 			mutex_exit(&zio->io_vd->vdev_stat_lock);
4874 			(void) zfs_ereport_start_checksum(zio->io_spa,
4875 			    zio->io_vd, &zio->io_bookmark, zio,
4876 			    zio->io_offset, zio->io_size, &info);
4877 		}
4878 	}
4879 
4880 	return (zio);
4881 }
4882 
4883 static zio_t *
4884 zio_dio_checksum_verify(zio_t *zio)
4885 {
4886 	zio_t *pio = zio_unique_parent(zio);
4887 	int error;
4888 
4889 	ASSERT3P(zio->io_vd, !=, NULL);
4890 	ASSERT3P(zio->io_bp, !=, NULL);
4891 	ASSERT3U(zio->io_child_type, ==, ZIO_CHILD_VDEV);
4892 	ASSERT3U(zio->io_type, ==, ZIO_TYPE_WRITE);
4893 	ASSERT3B(pio->io_prop.zp_direct_write, ==, B_TRUE);
4894 	ASSERT3U(pio->io_child_type, ==, ZIO_CHILD_LOGICAL);
4895 
4896 	if (zfs_vdev_direct_write_verify == 0 || zio->io_error != 0)
4897 		goto out;
4898 
4899 	if ((error = zio_checksum_error(zio, NULL)) != 0) {
4900 		zio->io_error = error;
4901 		if (error == ECKSUM) {
4902 			mutex_enter(&zio->io_vd->vdev_stat_lock);
4903 			zio->io_vd->vdev_stat.vs_dio_verify_errors++;
4904 			mutex_exit(&zio->io_vd->vdev_stat_lock);
4905 			zio->io_error = SET_ERROR(EIO);
4906 			zio->io_flags |= ZIO_FLAG_DIO_CHKSUM_ERR;
4907 
4908 			/*
4909 			 * The EIO error must be propagated up to the logical
4910 			 * parent ZIO in zio_notify_parent() so it can be
4911 			 * returned to dmu_write_abd().
4912 			 */
4913 			zio->io_flags &= ~ZIO_FLAG_DONT_PROPAGATE;
4914 
4915 			(void) zfs_ereport_post(FM_EREPORT_ZFS_DIO_VERIFY,
4916 			    zio->io_spa, zio->io_vd, &zio->io_bookmark,
4917 			    zio, 0);
4918 		}
4919 	}
4920 
4921 out:
4922 	return (zio);
4923 }
4924 
4925 
4926 /*
4927  * Called by RAID-Z to ensure we don't compute the checksum twice.
4928  */
4929 void
4930 zio_checksum_verified(zio_t *zio)
4931 {
4932 	zio->io_pipeline &= ~ZIO_STAGE_CHECKSUM_VERIFY;
4933 }
4934 
4935 /*
4936  * ==========================================================================
4937  * Error rank.  Error are ranked in the order 0, ENXIO, ECKSUM, EIO, other.
4938  * An error of 0 indicates success.  ENXIO indicates whole-device failure,
4939  * which may be transient (e.g. unplugged) or permanent.  ECKSUM and EIO
4940  * indicate errors that are specific to one I/O, and most likely permanent.
4941  * Any other error is presumed to be worse because we weren't expecting it.
4942  * ==========================================================================
4943  */
4944 int
4945 zio_worst_error(int e1, int e2)
4946 {
4947 	static int zio_error_rank[] = { 0, ENXIO, ECKSUM, EIO };
4948 	int r1, r2;
4949 
4950 	for (r1 = 0; r1 < sizeof (zio_error_rank) / sizeof (int); r1++)
4951 		if (e1 == zio_error_rank[r1])
4952 			break;
4953 
4954 	for (r2 = 0; r2 < sizeof (zio_error_rank) / sizeof (int); r2++)
4955 		if (e2 == zio_error_rank[r2])
4956 			break;
4957 
4958 	return (r1 > r2 ? e1 : e2);
4959 }
4960 
4961 /*
4962  * ==========================================================================
4963  * I/O completion
4964  * ==========================================================================
4965  */
4966 static zio_t *
4967 zio_ready(zio_t *zio)
4968 {
4969 	blkptr_t *bp = zio->io_bp;
4970 	zio_t *pio, *pio_next;
4971 	zio_link_t *zl = NULL;
4972 
4973 	if (zio_wait_for_children(zio, ZIO_CHILD_LOGICAL_BIT |
4974 	    ZIO_CHILD_GANG_BIT | ZIO_CHILD_DDT_BIT, ZIO_WAIT_READY)) {
4975 		return (NULL);
4976 	}
4977 
4978 	if (zio->io_ready) {
4979 		ASSERT(IO_IS_ALLOCATING(zio));
4980 		ASSERT(BP_GET_LOGICAL_BIRTH(bp) == zio->io_txg ||
4981 		    BP_IS_HOLE(bp) || (zio->io_flags & ZIO_FLAG_NOPWRITE));
4982 		ASSERT(zio->io_children[ZIO_CHILD_GANG][ZIO_WAIT_READY] == 0);
4983 
4984 		zio->io_ready(zio);
4985 	}
4986 
4987 #ifdef ZFS_DEBUG
4988 	if (bp != NULL && bp != &zio->io_bp_copy)
4989 		zio->io_bp_copy = *bp;
4990 #endif
4991 
4992 	if (zio->io_error != 0) {
4993 		zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
4994 
4995 		if (zio->io_flags & ZIO_FLAG_IO_ALLOCATING) {
4996 			ASSERT(IO_IS_ALLOCATING(zio));
4997 			ASSERT(zio->io_priority == ZIO_PRIORITY_ASYNC_WRITE);
4998 			ASSERT(zio->io_metaslab_class != NULL);
4999 			ASSERT(ZIO_HAS_ALLOCATOR(zio));
5000 
5001 			/*
5002 			 * We were unable to allocate anything, unreserve and
5003 			 * issue the next I/O to allocate.
5004 			 */
5005 			metaslab_class_throttle_unreserve(
5006 			    zio->io_metaslab_class, zio->io_prop.zp_copies,
5007 			    zio->io_allocator, zio);
5008 			zio_allocate_dispatch(zio->io_spa, zio->io_allocator);
5009 		}
5010 	}
5011 
5012 	mutex_enter(&zio->io_lock);
5013 	zio->io_state[ZIO_WAIT_READY] = 1;
5014 	pio = zio_walk_parents(zio, &zl);
5015 	mutex_exit(&zio->io_lock);
5016 
5017 	/*
5018 	 * As we notify zio's parents, new parents could be added.
5019 	 * New parents go to the head of zio's io_parent_list, however,
5020 	 * so we will (correctly) not notify them.  The remainder of zio's
5021 	 * io_parent_list, from 'pio_next' onward, cannot change because
5022 	 * all parents must wait for us to be done before they can be done.
5023 	 */
5024 	for (; pio != NULL; pio = pio_next) {
5025 		pio_next = zio_walk_parents(zio, &zl);
5026 		zio_notify_parent(pio, zio, ZIO_WAIT_READY, NULL);
5027 	}
5028 
5029 	if (zio->io_flags & ZIO_FLAG_NODATA) {
5030 		if (bp != NULL && BP_IS_GANG(bp)) {
5031 			zio->io_flags &= ~ZIO_FLAG_NODATA;
5032 		} else {
5033 			ASSERT((uintptr_t)zio->io_abd < SPA_MAXBLOCKSIZE);
5034 			zio->io_pipeline &= ~ZIO_VDEV_IO_STAGES;
5035 		}
5036 	}
5037 
5038 	if (zio_injection_enabled &&
5039 	    zio->io_spa->spa_syncing_txg == zio->io_txg)
5040 		zio_handle_ignored_writes(zio);
5041 
5042 	return (zio);
5043 }
5044 
5045 /*
5046  * Update the allocation throttle accounting.
5047  */
5048 static void
5049 zio_dva_throttle_done(zio_t *zio)
5050 {
5051 	zio_t *lio __maybe_unused = zio->io_logical;
5052 	zio_t *pio = zio_unique_parent(zio);
5053 	vdev_t *vd = zio->io_vd;
5054 	int flags = METASLAB_ASYNC_ALLOC;
5055 
5056 	ASSERT3P(zio->io_bp, !=, NULL);
5057 	ASSERT3U(zio->io_type, ==, ZIO_TYPE_WRITE);
5058 	ASSERT3U(zio->io_priority, ==, ZIO_PRIORITY_ASYNC_WRITE);
5059 	ASSERT3U(zio->io_child_type, ==, ZIO_CHILD_VDEV);
5060 	ASSERT(vd != NULL);
5061 	ASSERT3P(vd, ==, vd->vdev_top);
5062 	ASSERT(zio_injection_enabled || !(zio->io_flags & ZIO_FLAG_IO_RETRY));
5063 	ASSERT(!(zio->io_flags & ZIO_FLAG_IO_REPAIR));
5064 	ASSERT(zio->io_flags & ZIO_FLAG_IO_ALLOCATING);
5065 	ASSERT(!(lio->io_flags & ZIO_FLAG_IO_REWRITE));
5066 	ASSERT(!(lio->io_orig_flags & ZIO_FLAG_NODATA));
5067 
5068 	/*
5069 	 * Parents of gang children can have two flavors -- ones that
5070 	 * allocated the gang header (will have ZIO_FLAG_IO_REWRITE set)
5071 	 * and ones that allocated the constituent blocks. The allocation
5072 	 * throttle needs to know the allocating parent zio so we must find
5073 	 * it here.
5074 	 */
5075 	if (pio->io_child_type == ZIO_CHILD_GANG) {
5076 		/*
5077 		 * If our parent is a rewrite gang child then our grandparent
5078 		 * would have been the one that performed the allocation.
5079 		 */
5080 		if (pio->io_flags & ZIO_FLAG_IO_REWRITE)
5081 			pio = zio_unique_parent(pio);
5082 		flags |= METASLAB_GANG_CHILD;
5083 	}
5084 
5085 	ASSERT(IO_IS_ALLOCATING(pio));
5086 	ASSERT(ZIO_HAS_ALLOCATOR(pio));
5087 	ASSERT3P(zio, !=, zio->io_logical);
5088 	ASSERT(zio->io_logical != NULL);
5089 	ASSERT(!(zio->io_flags & ZIO_FLAG_IO_REPAIR));
5090 	ASSERT0(zio->io_flags & ZIO_FLAG_NOPWRITE);
5091 	ASSERT(zio->io_metaslab_class != NULL);
5092 
5093 	mutex_enter(&pio->io_lock);
5094 	metaslab_group_alloc_decrement(zio->io_spa, vd->vdev_id, pio, flags,
5095 	    pio->io_allocator, B_TRUE);
5096 	mutex_exit(&pio->io_lock);
5097 
5098 	metaslab_class_throttle_unreserve(zio->io_metaslab_class, 1,
5099 	    pio->io_allocator, pio);
5100 
5101 	/*
5102 	 * Call into the pipeline to see if there is more work that
5103 	 * needs to be done. If there is work to be done it will be
5104 	 * dispatched to another taskq thread.
5105 	 */
5106 	zio_allocate_dispatch(zio->io_spa, pio->io_allocator);
5107 }
5108 
5109 static zio_t *
5110 zio_done(zio_t *zio)
5111 {
5112 	/*
5113 	 * Always attempt to keep stack usage minimal here since
5114 	 * we can be called recursively up to 19 levels deep.
5115 	 */
5116 	const uint64_t psize = zio->io_size;
5117 	zio_t *pio, *pio_next;
5118 	zio_link_t *zl = NULL;
5119 
5120 	/*
5121 	 * If our children haven't all completed,
5122 	 * wait for them and then repeat this pipeline stage.
5123 	 */
5124 	if (zio_wait_for_children(zio, ZIO_CHILD_ALL_BITS, ZIO_WAIT_DONE)) {
5125 		return (NULL);
5126 	}
5127 
5128 	/*
5129 	 * If the allocation throttle is enabled, then update the accounting.
5130 	 * We only track child I/Os that are part of an allocating async
5131 	 * write. We must do this since the allocation is performed
5132 	 * by the logical I/O but the actual write is done by child I/Os.
5133 	 */
5134 	if (zio->io_flags & ZIO_FLAG_IO_ALLOCATING &&
5135 	    zio->io_child_type == ZIO_CHILD_VDEV) {
5136 		ASSERT(zio->io_metaslab_class != NULL);
5137 		ASSERT(zio->io_metaslab_class->mc_alloc_throttle_enabled);
5138 		zio_dva_throttle_done(zio);
5139 	}
5140 
5141 	/*
5142 	 * If the allocation throttle is enabled, verify that
5143 	 * we have decremented the refcounts for every I/O that was throttled.
5144 	 */
5145 	if (zio->io_flags & ZIO_FLAG_IO_ALLOCATING) {
5146 		ASSERT(zio->io_type == ZIO_TYPE_WRITE);
5147 		ASSERT(zio->io_priority == ZIO_PRIORITY_ASYNC_WRITE);
5148 		ASSERT(zio->io_bp != NULL);
5149 		ASSERT(ZIO_HAS_ALLOCATOR(zio));
5150 
5151 		metaslab_group_alloc_verify(zio->io_spa, zio->io_bp, zio,
5152 		    zio->io_allocator);
5153 		VERIFY(zfs_refcount_not_held(&zio->io_metaslab_class->
5154 		    mc_allocator[zio->io_allocator].mca_alloc_slots, zio));
5155 	}
5156 
5157 
5158 	for (int c = 0; c < ZIO_CHILD_TYPES; c++)
5159 		for (int w = 0; w < ZIO_WAIT_TYPES; w++)
5160 			ASSERT(zio->io_children[c][w] == 0);
5161 
5162 	if (zio->io_bp != NULL && !BP_IS_EMBEDDED(zio->io_bp)) {
5163 		ASSERT(zio->io_bp->blk_pad[0] == 0);
5164 		ASSERT(zio->io_bp->blk_pad[1] == 0);
5165 		ASSERT(memcmp(zio->io_bp, &zio->io_bp_copy,
5166 		    sizeof (blkptr_t)) == 0 ||
5167 		    (zio->io_bp == zio_unique_parent(zio)->io_bp));
5168 		if (zio->io_type == ZIO_TYPE_WRITE && !BP_IS_HOLE(zio->io_bp) &&
5169 		    zio->io_bp_override == NULL &&
5170 		    !(zio->io_flags & ZIO_FLAG_IO_REPAIR)) {
5171 			ASSERT3U(zio->io_prop.zp_copies, <=,
5172 			    BP_GET_NDVAS(zio->io_bp));
5173 			ASSERT(BP_COUNT_GANG(zio->io_bp) == 0 ||
5174 			    (BP_COUNT_GANG(zio->io_bp) ==
5175 			    BP_GET_NDVAS(zio->io_bp)));
5176 		}
5177 		if (zio->io_flags & ZIO_FLAG_NOPWRITE)
5178 			VERIFY(BP_EQUAL(zio->io_bp, &zio->io_bp_orig));
5179 	}
5180 
5181 	/*
5182 	 * If there were child vdev/gang/ddt errors, they apply to us now.
5183 	 */
5184 	zio_inherit_child_errors(zio, ZIO_CHILD_VDEV);
5185 	zio_inherit_child_errors(zio, ZIO_CHILD_GANG);
5186 	zio_inherit_child_errors(zio, ZIO_CHILD_DDT);
5187 
5188 	/*
5189 	 * If the I/O on the transformed data was successful, generate any
5190 	 * checksum reports now while we still have the transformed data.
5191 	 */
5192 	if (zio->io_error == 0) {
5193 		while (zio->io_cksum_report != NULL) {
5194 			zio_cksum_report_t *zcr = zio->io_cksum_report;
5195 			uint64_t align = zcr->zcr_align;
5196 			uint64_t asize = P2ROUNDUP(psize, align);
5197 			abd_t *adata = zio->io_abd;
5198 
5199 			if (adata != NULL && asize != psize) {
5200 				adata = abd_alloc(asize, B_TRUE);
5201 				abd_copy(adata, zio->io_abd, psize);
5202 				abd_zero_off(adata, psize, asize - psize);
5203 			}
5204 
5205 			zio->io_cksum_report = zcr->zcr_next;
5206 			zcr->zcr_next = NULL;
5207 			zcr->zcr_finish(zcr, adata);
5208 			zfs_ereport_free_checksum(zcr);
5209 
5210 			if (adata != NULL && asize != psize)
5211 				abd_free(adata);
5212 		}
5213 	}
5214 
5215 	zio_pop_transforms(zio);	/* note: may set zio->io_error */
5216 
5217 	vdev_stat_update(zio, psize);
5218 
5219 	/*
5220 	 * If this I/O is attached to a particular vdev is slow, exceeding
5221 	 * 30 seconds to complete, post an error described the I/O delay.
5222 	 * We ignore these errors if the device is currently unavailable.
5223 	 */
5224 	if (zio->io_delay >= MSEC2NSEC(zio_slow_io_ms)) {
5225 		if (zio->io_vd != NULL && !vdev_is_dead(zio->io_vd)) {
5226 			/*
5227 			 * We want to only increment our slow IO counters if
5228 			 * the IO is valid (i.e. not if the drive is removed).
5229 			 *
5230 			 * zfs_ereport_post() will also do these checks, but
5231 			 * it can also ratelimit and have other failures, so we
5232 			 * need to increment the slow_io counters independent
5233 			 * of it.
5234 			 */
5235 			if (zfs_ereport_is_valid(FM_EREPORT_ZFS_DELAY,
5236 			    zio->io_spa, zio->io_vd, zio)) {
5237 				mutex_enter(&zio->io_vd->vdev_stat_lock);
5238 				zio->io_vd->vdev_stat.vs_slow_ios++;
5239 				mutex_exit(&zio->io_vd->vdev_stat_lock);
5240 
5241 				(void) zfs_ereport_post(FM_EREPORT_ZFS_DELAY,
5242 				    zio->io_spa, zio->io_vd, &zio->io_bookmark,
5243 				    zio, 0);
5244 			}
5245 		}
5246 	}
5247 
5248 	if (zio->io_error) {
5249 		/*
5250 		 * If this I/O is attached to a particular vdev,
5251 		 * generate an error message describing the I/O failure
5252 		 * at the block level.  We ignore these errors if the
5253 		 * device is currently unavailable.
5254 		 */
5255 		if (zio->io_error != ECKSUM && zio->io_vd != NULL &&
5256 		    !vdev_is_dead(zio->io_vd) &&
5257 		    !(zio->io_flags & ZIO_FLAG_DIO_CHKSUM_ERR)) {
5258 			int ret = zfs_ereport_post(FM_EREPORT_ZFS_IO,
5259 			    zio->io_spa, zio->io_vd, &zio->io_bookmark, zio, 0);
5260 			if (ret != EALREADY) {
5261 				mutex_enter(&zio->io_vd->vdev_stat_lock);
5262 				if (zio->io_type == ZIO_TYPE_READ)
5263 					zio->io_vd->vdev_stat.vs_read_errors++;
5264 				else if (zio->io_type == ZIO_TYPE_WRITE)
5265 					zio->io_vd->vdev_stat.vs_write_errors++;
5266 				mutex_exit(&zio->io_vd->vdev_stat_lock);
5267 			}
5268 		}
5269 
5270 		if ((zio->io_error == EIO || !(zio->io_flags &
5271 		    (ZIO_FLAG_SPECULATIVE | ZIO_FLAG_DONT_PROPAGATE))) &&
5272 		    !(zio->io_flags & ZIO_FLAG_DIO_CHKSUM_ERR) &&
5273 		    zio == zio->io_logical) {
5274 			/*
5275 			 * For logical I/O requests, tell the SPA to log the
5276 			 * error and generate a logical data ereport.
5277 			 */
5278 			spa_log_error(zio->io_spa, &zio->io_bookmark,
5279 			    BP_GET_LOGICAL_BIRTH(zio->io_bp));
5280 			(void) zfs_ereport_post(FM_EREPORT_ZFS_DATA,
5281 			    zio->io_spa, NULL, &zio->io_bookmark, zio, 0);
5282 		}
5283 	}
5284 
5285 	if (zio->io_error && zio == zio->io_logical) {
5286 		/*
5287 		 * Determine whether zio should be reexecuted.  This will
5288 		 * propagate all the way to the root via zio_notify_parent().
5289 		 */
5290 		ASSERT(zio->io_vd == NULL && zio->io_bp != NULL);
5291 		ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
5292 
5293 		if (IO_IS_ALLOCATING(zio) &&
5294 		    !(zio->io_flags & ZIO_FLAG_CANFAIL) &&
5295 		    !(zio->io_flags & ZIO_FLAG_DIO_CHKSUM_ERR)) {
5296 			if (zio->io_error != ENOSPC)
5297 				zio->io_reexecute |= ZIO_REEXECUTE_NOW;
5298 			else
5299 				zio->io_reexecute |= ZIO_REEXECUTE_SUSPEND;
5300 		}
5301 
5302 		if ((zio->io_type == ZIO_TYPE_READ ||
5303 		    zio->io_type == ZIO_TYPE_FREE) &&
5304 		    !(zio->io_flags & ZIO_FLAG_SCAN_THREAD) &&
5305 		    zio->io_error == ENXIO &&
5306 		    spa_load_state(zio->io_spa) == SPA_LOAD_NONE &&
5307 		    spa_get_failmode(zio->io_spa) != ZIO_FAILURE_MODE_CONTINUE)
5308 			zio->io_reexecute |= ZIO_REEXECUTE_SUSPEND;
5309 
5310 		if (!(zio->io_flags & ZIO_FLAG_CANFAIL) && !zio->io_reexecute)
5311 			zio->io_reexecute |= ZIO_REEXECUTE_SUSPEND;
5312 
5313 		/*
5314 		 * Here is a possibly good place to attempt to do
5315 		 * either combinatorial reconstruction or error correction
5316 		 * based on checksums.  It also might be a good place
5317 		 * to send out preliminary ereports before we suspend
5318 		 * processing.
5319 		 */
5320 	}
5321 
5322 	/*
5323 	 * If there were logical child errors, they apply to us now.
5324 	 * We defer this until now to avoid conflating logical child
5325 	 * errors with errors that happened to the zio itself when
5326 	 * updating vdev stats and reporting FMA events above.
5327 	 */
5328 	zio_inherit_child_errors(zio, ZIO_CHILD_LOGICAL);
5329 
5330 	if ((zio->io_error || zio->io_reexecute) &&
5331 	    IO_IS_ALLOCATING(zio) && zio->io_gang_leader == zio &&
5332 	    !(zio->io_flags & (ZIO_FLAG_IO_REWRITE | ZIO_FLAG_NOPWRITE)))
5333 		zio_dva_unallocate(zio, zio->io_gang_tree, zio->io_bp);
5334 
5335 	zio_gang_tree_free(&zio->io_gang_tree);
5336 
5337 	/*
5338 	 * Godfather I/Os should never suspend.
5339 	 */
5340 	if ((zio->io_flags & ZIO_FLAG_GODFATHER) &&
5341 	    (zio->io_reexecute & ZIO_REEXECUTE_SUSPEND))
5342 		zio->io_reexecute &= ~ZIO_REEXECUTE_SUSPEND;
5343 
5344 	if (zio->io_reexecute) {
5345 		/*
5346 		 * A Direct I/O write that has a checksum verify error should
5347 		 * not attempt to reexecute. Instead, EAGAIN should just be
5348 		 * propagated back up so the write can be attempt to be issued
5349 		 * through the ARC.
5350 		 */
5351 		ASSERT(!(zio->io_flags & ZIO_FLAG_DIO_CHKSUM_ERR));
5352 
5353 		/*
5354 		 * This is a logical I/O that wants to reexecute.
5355 		 *
5356 		 * Reexecute is top-down.  When an i/o fails, if it's not
5357 		 * the root, it simply notifies its parent and sticks around.
5358 		 * The parent, seeing that it still has children in zio_done(),
5359 		 * does the same.  This percolates all the way up to the root.
5360 		 * The root i/o will reexecute or suspend the entire tree.
5361 		 *
5362 		 * This approach ensures that zio_reexecute() honors
5363 		 * all the original i/o dependency relationships, e.g.
5364 		 * parents not executing until children are ready.
5365 		 */
5366 		ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
5367 
5368 		zio->io_gang_leader = NULL;
5369 
5370 		mutex_enter(&zio->io_lock);
5371 		zio->io_state[ZIO_WAIT_DONE] = 1;
5372 		mutex_exit(&zio->io_lock);
5373 
5374 		/*
5375 		 * "The Godfather" I/O monitors its children but is
5376 		 * not a true parent to them. It will track them through
5377 		 * the pipeline but severs its ties whenever they get into
5378 		 * trouble (e.g. suspended). This allows "The Godfather"
5379 		 * I/O to return status without blocking.
5380 		 */
5381 		zl = NULL;
5382 		for (pio = zio_walk_parents(zio, &zl); pio != NULL;
5383 		    pio = pio_next) {
5384 			zio_link_t *remove_zl = zl;
5385 			pio_next = zio_walk_parents(zio, &zl);
5386 
5387 			if ((pio->io_flags & ZIO_FLAG_GODFATHER) &&
5388 			    (zio->io_reexecute & ZIO_REEXECUTE_SUSPEND)) {
5389 				zio_remove_child(pio, zio, remove_zl);
5390 				/*
5391 				 * This is a rare code path, so we don't
5392 				 * bother with "next_to_execute".
5393 				 */
5394 				zio_notify_parent(pio, zio, ZIO_WAIT_DONE,
5395 				    NULL);
5396 			}
5397 		}
5398 
5399 		if ((pio = zio_unique_parent(zio)) != NULL) {
5400 			/*
5401 			 * We're not a root i/o, so there's nothing to do
5402 			 * but notify our parent.  Don't propagate errors
5403 			 * upward since we haven't permanently failed yet.
5404 			 */
5405 			ASSERT(!(zio->io_flags & ZIO_FLAG_GODFATHER));
5406 			zio->io_flags |= ZIO_FLAG_DONT_PROPAGATE;
5407 			/*
5408 			 * This is a rare code path, so we don't bother with
5409 			 * "next_to_execute".
5410 			 */
5411 			zio_notify_parent(pio, zio, ZIO_WAIT_DONE, NULL);
5412 		} else if (zio->io_reexecute & ZIO_REEXECUTE_SUSPEND) {
5413 			/*
5414 			 * We'd fail again if we reexecuted now, so suspend
5415 			 * until conditions improve (e.g. device comes online).
5416 			 */
5417 			zio_suspend(zio->io_spa, zio, ZIO_SUSPEND_IOERR);
5418 		} else {
5419 			/*
5420 			 * Reexecution is potentially a huge amount of work.
5421 			 * Hand it off to the otherwise-unused claim taskq.
5422 			 */
5423 			spa_taskq_dispatch(zio->io_spa,
5424 			    ZIO_TYPE_CLAIM, ZIO_TASKQ_ISSUE,
5425 			    zio_reexecute, zio, B_FALSE);
5426 		}
5427 		return (NULL);
5428 	}
5429 
5430 	ASSERT(list_is_empty(&zio->io_child_list));
5431 	ASSERT(zio->io_reexecute == 0);
5432 	ASSERT(zio->io_error == 0 || (zio->io_flags & ZIO_FLAG_CANFAIL));
5433 
5434 	/*
5435 	 * Report any checksum errors, since the I/O is complete.
5436 	 */
5437 	while (zio->io_cksum_report != NULL) {
5438 		zio_cksum_report_t *zcr = zio->io_cksum_report;
5439 		zio->io_cksum_report = zcr->zcr_next;
5440 		zcr->zcr_next = NULL;
5441 		zcr->zcr_finish(zcr, NULL);
5442 		zfs_ereport_free_checksum(zcr);
5443 	}
5444 
5445 	/*
5446 	 * It is the responsibility of the done callback to ensure that this
5447 	 * particular zio is no longer discoverable for adoption, and as
5448 	 * such, cannot acquire any new parents.
5449 	 */
5450 	if (zio->io_done)
5451 		zio->io_done(zio);
5452 
5453 	mutex_enter(&zio->io_lock);
5454 	zio->io_state[ZIO_WAIT_DONE] = 1;
5455 	mutex_exit(&zio->io_lock);
5456 
5457 	/*
5458 	 * We are done executing this zio.  We may want to execute a parent
5459 	 * next.  See the comment in zio_notify_parent().
5460 	 */
5461 	zio_t *next_to_execute = NULL;
5462 	zl = NULL;
5463 	for (pio = zio_walk_parents(zio, &zl); pio != NULL; pio = pio_next) {
5464 		zio_link_t *remove_zl = zl;
5465 		pio_next = zio_walk_parents(zio, &zl);
5466 		zio_remove_child(pio, zio, remove_zl);
5467 		zio_notify_parent(pio, zio, ZIO_WAIT_DONE, &next_to_execute);
5468 	}
5469 
5470 	if (zio->io_waiter != NULL) {
5471 		mutex_enter(&zio->io_lock);
5472 		zio->io_executor = NULL;
5473 		cv_broadcast(&zio->io_cv);
5474 		mutex_exit(&zio->io_lock);
5475 	} else {
5476 		zio_destroy(zio);
5477 	}
5478 
5479 	return (next_to_execute);
5480 }
5481 
5482 /*
5483  * ==========================================================================
5484  * I/O pipeline definition
5485  * ==========================================================================
5486  */
5487 static zio_pipe_stage_t *zio_pipeline[] = {
5488 	NULL,
5489 	zio_read_bp_init,
5490 	zio_write_bp_init,
5491 	zio_free_bp_init,
5492 	zio_issue_async,
5493 	zio_write_compress,
5494 	zio_encrypt,
5495 	zio_checksum_generate,
5496 	zio_nop_write,
5497 	zio_brt_free,
5498 	zio_ddt_read_start,
5499 	zio_ddt_read_done,
5500 	zio_ddt_write,
5501 	zio_ddt_free,
5502 	zio_gang_assemble,
5503 	zio_gang_issue,
5504 	zio_dva_throttle,
5505 	zio_dva_allocate,
5506 	zio_dva_free,
5507 	zio_dva_claim,
5508 	zio_ready,
5509 	zio_vdev_io_start,
5510 	zio_vdev_io_done,
5511 	zio_vdev_io_assess,
5512 	zio_checksum_verify,
5513 	zio_dio_checksum_verify,
5514 	zio_done
5515 };
5516 
5517 
5518 
5519 
5520 /*
5521  * Compare two zbookmark_phys_t's to see which we would reach first in a
5522  * pre-order traversal of the object tree.
5523  *
5524  * This is simple in every case aside from the meta-dnode object. For all other
5525  * objects, we traverse them in order (object 1 before object 2, and so on).
5526  * However, all of these objects are traversed while traversing object 0, since
5527  * the data it points to is the list of objects.  Thus, we need to convert to a
5528  * canonical representation so we can compare meta-dnode bookmarks to
5529  * non-meta-dnode bookmarks.
5530  *
5531  * We do this by calculating "equivalents" for each field of the zbookmark.
5532  * zbookmarks outside of the meta-dnode use their own object and level, and
5533  * calculate the level 0 equivalent (the first L0 blkid that is contained in the
5534  * blocks this bookmark refers to) by multiplying their blkid by their span
5535  * (the number of L0 blocks contained within one block at their level).
5536  * zbookmarks inside the meta-dnode calculate their object equivalent
5537  * (which is L0equiv * dnodes per data block), use 0 for their L0equiv, and use
5538  * level + 1<<31 (any value larger than a level could ever be) for their level.
5539  * This causes them to always compare before a bookmark in their object
5540  * equivalent, compare appropriately to bookmarks in other objects, and to
5541  * compare appropriately to other bookmarks in the meta-dnode.
5542  */
5543 int
5544 zbookmark_compare(uint16_t dbss1, uint8_t ibs1, uint16_t dbss2, uint8_t ibs2,
5545     const zbookmark_phys_t *zb1, const zbookmark_phys_t *zb2)
5546 {
5547 	/*
5548 	 * These variables represent the "equivalent" values for the zbookmark,
5549 	 * after converting zbookmarks inside the meta dnode to their
5550 	 * normal-object equivalents.
5551 	 */
5552 	uint64_t zb1obj, zb2obj;
5553 	uint64_t zb1L0, zb2L0;
5554 	uint64_t zb1level, zb2level;
5555 
5556 	if (zb1->zb_object == zb2->zb_object &&
5557 	    zb1->zb_level == zb2->zb_level &&
5558 	    zb1->zb_blkid == zb2->zb_blkid)
5559 		return (0);
5560 
5561 	IMPLY(zb1->zb_level > 0, ibs1 >= SPA_MINBLOCKSHIFT);
5562 	IMPLY(zb2->zb_level > 0, ibs2 >= SPA_MINBLOCKSHIFT);
5563 
5564 	/*
5565 	 * BP_SPANB calculates the span in blocks.
5566 	 */
5567 	zb1L0 = (zb1->zb_blkid) * BP_SPANB(ibs1, zb1->zb_level);
5568 	zb2L0 = (zb2->zb_blkid) * BP_SPANB(ibs2, zb2->zb_level);
5569 
5570 	if (zb1->zb_object == DMU_META_DNODE_OBJECT) {
5571 		zb1obj = zb1L0 * (dbss1 << (SPA_MINBLOCKSHIFT - DNODE_SHIFT));
5572 		zb1L0 = 0;
5573 		zb1level = zb1->zb_level + COMPARE_META_LEVEL;
5574 	} else {
5575 		zb1obj = zb1->zb_object;
5576 		zb1level = zb1->zb_level;
5577 	}
5578 
5579 	if (zb2->zb_object == DMU_META_DNODE_OBJECT) {
5580 		zb2obj = zb2L0 * (dbss2 << (SPA_MINBLOCKSHIFT - DNODE_SHIFT));
5581 		zb2L0 = 0;
5582 		zb2level = zb2->zb_level + COMPARE_META_LEVEL;
5583 	} else {
5584 		zb2obj = zb2->zb_object;
5585 		zb2level = zb2->zb_level;
5586 	}
5587 
5588 	/* Now that we have a canonical representation, do the comparison. */
5589 	if (zb1obj != zb2obj)
5590 		return (zb1obj < zb2obj ? -1 : 1);
5591 	else if (zb1L0 != zb2L0)
5592 		return (zb1L0 < zb2L0 ? -1 : 1);
5593 	else if (zb1level != zb2level)
5594 		return (zb1level > zb2level ? -1 : 1);
5595 	/*
5596 	 * This can (theoretically) happen if the bookmarks have the same object
5597 	 * and level, but different blkids, if the block sizes are not the same.
5598 	 * There is presently no way to change the indirect block sizes
5599 	 */
5600 	return (0);
5601 }
5602 
5603 /*
5604  *  This function checks the following: given that last_block is the place that
5605  *  our traversal stopped last time, does that guarantee that we've visited
5606  *  every node under subtree_root?  Therefore, we can't just use the raw output
5607  *  of zbookmark_compare.  We have to pass in a modified version of
5608  *  subtree_root; by incrementing the block id, and then checking whether
5609  *  last_block is before or equal to that, we can tell whether or not having
5610  *  visited last_block implies that all of subtree_root's children have been
5611  *  visited.
5612  */
5613 boolean_t
5614 zbookmark_subtree_completed(const dnode_phys_t *dnp,
5615     const zbookmark_phys_t *subtree_root, const zbookmark_phys_t *last_block)
5616 {
5617 	zbookmark_phys_t mod_zb = *subtree_root;
5618 	mod_zb.zb_blkid++;
5619 	ASSERT0(last_block->zb_level);
5620 
5621 	/* The objset_phys_t isn't before anything. */
5622 	if (dnp == NULL)
5623 		return (B_FALSE);
5624 
5625 	/*
5626 	 * We pass in 1ULL << (DNODE_BLOCK_SHIFT - SPA_MINBLOCKSHIFT) for the
5627 	 * data block size in sectors, because that variable is only used if
5628 	 * the bookmark refers to a block in the meta-dnode.  Since we don't
5629 	 * know without examining it what object it refers to, and there's no
5630 	 * harm in passing in this value in other cases, we always pass it in.
5631 	 *
5632 	 * We pass in 0 for the indirect block size shift because zb2 must be
5633 	 * level 0.  The indirect block size is only used to calculate the span
5634 	 * of the bookmark, but since the bookmark must be level 0, the span is
5635 	 * always 1, so the math works out.
5636 	 *
5637 	 * If you make changes to how the zbookmark_compare code works, be sure
5638 	 * to make sure that this code still works afterwards.
5639 	 */
5640 	return (zbookmark_compare(dnp->dn_datablkszsec, dnp->dn_indblkshift,
5641 	    1ULL << (DNODE_BLOCK_SHIFT - SPA_MINBLOCKSHIFT), 0, &mod_zb,
5642 	    last_block) <= 0);
5643 }
5644 
5645 /*
5646  * This function is similar to zbookmark_subtree_completed(), but returns true
5647  * if subtree_root is equal or ahead of last_block, i.e. still to be done.
5648  */
5649 boolean_t
5650 zbookmark_subtree_tbd(const dnode_phys_t *dnp,
5651     const zbookmark_phys_t *subtree_root, const zbookmark_phys_t *last_block)
5652 {
5653 	ASSERT0(last_block->zb_level);
5654 	if (dnp == NULL)
5655 		return (B_FALSE);
5656 	return (zbookmark_compare(dnp->dn_datablkszsec, dnp->dn_indblkshift,
5657 	    1ULL << (DNODE_BLOCK_SHIFT - SPA_MINBLOCKSHIFT), 0, subtree_root,
5658 	    last_block) >= 0);
5659 }
5660 
5661 EXPORT_SYMBOL(zio_type_name);
5662 EXPORT_SYMBOL(zio_buf_alloc);
5663 EXPORT_SYMBOL(zio_data_buf_alloc);
5664 EXPORT_SYMBOL(zio_buf_free);
5665 EXPORT_SYMBOL(zio_data_buf_free);
5666 
5667 ZFS_MODULE_PARAM(zfs_zio, zio_, slow_io_ms, INT, ZMOD_RW,
5668 	"Max I/O completion time (milliseconds) before marking it as slow");
5669 
5670 ZFS_MODULE_PARAM(zfs_zio, zio_, requeue_io_start_cut_in_line, INT, ZMOD_RW,
5671 	"Prioritize requeued I/O");
5672 
5673 ZFS_MODULE_PARAM(zfs, zfs_, sync_pass_deferred_free,  UINT, ZMOD_RW,
5674 	"Defer frees starting in this pass");
5675 
5676 ZFS_MODULE_PARAM(zfs, zfs_, sync_pass_dont_compress, UINT, ZMOD_RW,
5677 	"Don't compress starting in this pass");
5678 
5679 ZFS_MODULE_PARAM(zfs, zfs_, sync_pass_rewrite, UINT, ZMOD_RW,
5680 	"Rewrite new bps starting in this pass");
5681 
5682 ZFS_MODULE_PARAM(zfs_zio, zio_, dva_throttle_enabled, INT, ZMOD_RW,
5683 	"Throttle block allocations in the ZIO pipeline");
5684 
5685 ZFS_MODULE_PARAM(zfs_zio, zio_, deadman_log_all, INT, ZMOD_RW,
5686 	"Log all slow ZIOs, not just those with vdevs");
5687