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