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