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