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