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