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