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