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