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