xref: /titanic_51/usr/src/uts/common/fs/zfs/zio.c (revision f6cfb02b955a670e8c39660b2d0468385cbc7e80)
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 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #include <sys/zfs_context.h>
27 #include <sys/fm/fs/zfs.h>
28 #include <sys/spa.h>
29 #include <sys/txg.h>
30 #include <sys/spa_impl.h>
31 #include <sys/vdev_impl.h>
32 #include <sys/zio_impl.h>
33 #include <sys/zio_compress.h>
34 #include <sys/zio_checksum.h>
35 
36 /*
37  * ==========================================================================
38  * I/O priority table
39  * ==========================================================================
40  */
41 uint8_t zio_priority_table[ZIO_PRIORITY_TABLE_SIZE] = {
42 	0,	/* ZIO_PRIORITY_NOW		*/
43 	0,	/* ZIO_PRIORITY_SYNC_READ	*/
44 	0,	/* ZIO_PRIORITY_SYNC_WRITE	*/
45 	6,	/* ZIO_PRIORITY_ASYNC_READ	*/
46 	4,	/* ZIO_PRIORITY_ASYNC_WRITE	*/
47 	4,	/* ZIO_PRIORITY_FREE		*/
48 	0,	/* ZIO_PRIORITY_CACHE_FILL	*/
49 	0,	/* ZIO_PRIORITY_LOG_WRITE	*/
50 	10,	/* ZIO_PRIORITY_RESILVER	*/
51 	20,	/* ZIO_PRIORITY_SCRUB		*/
52 };
53 
54 /*
55  * ==========================================================================
56  * I/O type descriptions
57  * ==========================================================================
58  */
59 char *zio_type_name[ZIO_TYPES] = {
60 	"null", "read", "write", "free", "claim", "ioctl" };
61 
62 #define	SYNC_PASS_DEFERRED_FREE	1	/* defer frees after this pass */
63 #define	SYNC_PASS_DONT_COMPRESS	4	/* don't compress after this pass */
64 #define	SYNC_PASS_REWRITE	1	/* rewrite new bps after this pass */
65 
66 /*
67  * ==========================================================================
68  * I/O kmem caches
69  * ==========================================================================
70  */
71 kmem_cache_t *zio_cache;
72 kmem_cache_t *zio_buf_cache[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT];
73 kmem_cache_t *zio_data_buf_cache[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT];
74 
75 #ifdef _KERNEL
76 extern vmem_t *zio_alloc_arena;
77 #endif
78 
79 /*
80  * An allocating zio is one that either currently has the DVA allocate
81  * stage set or will have it later in its lifetime.
82  */
83 #define	IO_IS_ALLOCATING(zio) \
84 	((zio)->io_orig_pipeline & (1U << ZIO_STAGE_DVA_ALLOCATE))
85 
86 void
87 zio_init(void)
88 {
89 	size_t c;
90 	vmem_t *data_alloc_arena = NULL;
91 
92 #ifdef _KERNEL
93 	data_alloc_arena = zio_alloc_arena;
94 #endif
95 	zio_cache = kmem_cache_create("zio_cache", sizeof (zio_t), 0,
96 	    NULL, NULL, NULL, NULL, NULL, 0);
97 
98 	/*
99 	 * For small buffers, we want a cache for each multiple of
100 	 * SPA_MINBLOCKSIZE.  For medium-size buffers, we want a cache
101 	 * for each quarter-power of 2.  For large buffers, we want
102 	 * a cache for each multiple of PAGESIZE.
103 	 */
104 	for (c = 0; c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; c++) {
105 		size_t size = (c + 1) << SPA_MINBLOCKSHIFT;
106 		size_t p2 = size;
107 		size_t align = 0;
108 
109 		while (p2 & (p2 - 1))
110 			p2 &= p2 - 1;
111 
112 		if (size <= 4 * SPA_MINBLOCKSIZE) {
113 			align = SPA_MINBLOCKSIZE;
114 		} else if (P2PHASE(size, PAGESIZE) == 0) {
115 			align = PAGESIZE;
116 		} else if (P2PHASE(size, p2 >> 2) == 0) {
117 			align = p2 >> 2;
118 		}
119 
120 		if (align != 0) {
121 			char name[36];
122 			(void) sprintf(name, "zio_buf_%lu", (ulong_t)size);
123 			zio_buf_cache[c] = kmem_cache_create(name, size,
124 			    align, NULL, NULL, NULL, NULL, NULL, KMC_NODEBUG);
125 
126 			(void) sprintf(name, "zio_data_buf_%lu", (ulong_t)size);
127 			zio_data_buf_cache[c] = kmem_cache_create(name, size,
128 			    align, NULL, NULL, NULL, NULL, data_alloc_arena,
129 			    KMC_NODEBUG);
130 		}
131 	}
132 
133 	while (--c != 0) {
134 		ASSERT(zio_buf_cache[c] != NULL);
135 		if (zio_buf_cache[c - 1] == NULL)
136 			zio_buf_cache[c - 1] = zio_buf_cache[c];
137 
138 		ASSERT(zio_data_buf_cache[c] != NULL);
139 		if (zio_data_buf_cache[c - 1] == NULL)
140 			zio_data_buf_cache[c - 1] = zio_data_buf_cache[c];
141 	}
142 
143 	zio_inject_init();
144 }
145 
146 void
147 zio_fini(void)
148 {
149 	size_t c;
150 	kmem_cache_t *last_cache = NULL;
151 	kmem_cache_t *last_data_cache = NULL;
152 
153 	for (c = 0; c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; c++) {
154 		if (zio_buf_cache[c] != last_cache) {
155 			last_cache = zio_buf_cache[c];
156 			kmem_cache_destroy(zio_buf_cache[c]);
157 		}
158 		zio_buf_cache[c] = NULL;
159 
160 		if (zio_data_buf_cache[c] != last_data_cache) {
161 			last_data_cache = zio_data_buf_cache[c];
162 			kmem_cache_destroy(zio_data_buf_cache[c]);
163 		}
164 		zio_data_buf_cache[c] = NULL;
165 	}
166 
167 	kmem_cache_destroy(zio_cache);
168 
169 	zio_inject_fini();
170 }
171 
172 /*
173  * ==========================================================================
174  * Allocate and free I/O buffers
175  * ==========================================================================
176  */
177 
178 /*
179  * Use zio_buf_alloc to allocate ZFS metadata.  This data will appear in a
180  * crashdump if the kernel panics, so use it judiciously.  Obviously, it's
181  * useful to inspect ZFS metadata, but if possible, we should avoid keeping
182  * excess / transient data in-core during a crashdump.
183  */
184 void *
185 zio_buf_alloc(size_t size)
186 {
187 	size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
188 
189 	ASSERT(c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
190 
191 	return (kmem_cache_alloc(zio_buf_cache[c], KM_PUSHPAGE));
192 }
193 
194 /*
195  * Use zio_data_buf_alloc to allocate data.  The data will not appear in a
196  * crashdump if the kernel panics.  This exists so that we will limit the amount
197  * of ZFS data that shows up in a kernel crashdump.  (Thus reducing the amount
198  * of kernel heap dumped to disk when the kernel panics)
199  */
200 void *
201 zio_data_buf_alloc(size_t size)
202 {
203 	size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
204 
205 	ASSERT(c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
206 
207 	return (kmem_cache_alloc(zio_data_buf_cache[c], KM_PUSHPAGE));
208 }
209 
210 void
211 zio_buf_free(void *buf, size_t size)
212 {
213 	size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
214 
215 	ASSERT(c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
216 
217 	kmem_cache_free(zio_buf_cache[c], buf);
218 }
219 
220 void
221 zio_data_buf_free(void *buf, size_t size)
222 {
223 	size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
224 
225 	ASSERT(c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
226 
227 	kmem_cache_free(zio_data_buf_cache[c], buf);
228 }
229 
230 /*
231  * ==========================================================================
232  * Push and pop I/O transform buffers
233  * ==========================================================================
234  */
235 static void
236 zio_push_transform(zio_t *zio, void *data, uint64_t size, uint64_t bufsize,
237 	zio_transform_func_t *transform)
238 {
239 	zio_transform_t *zt = kmem_alloc(sizeof (zio_transform_t), KM_SLEEP);
240 
241 	zt->zt_orig_data = zio->io_data;
242 	zt->zt_orig_size = zio->io_size;
243 	zt->zt_bufsize = bufsize;
244 	zt->zt_transform = transform;
245 
246 	zt->zt_next = zio->io_transform_stack;
247 	zio->io_transform_stack = zt;
248 
249 	zio->io_data = data;
250 	zio->io_size = size;
251 }
252 
253 static void
254 zio_pop_transforms(zio_t *zio)
255 {
256 	zio_transform_t *zt;
257 
258 	while ((zt = zio->io_transform_stack) != NULL) {
259 		if (zt->zt_transform != NULL)
260 			zt->zt_transform(zio,
261 			    zt->zt_orig_data, zt->zt_orig_size);
262 
263 		zio_buf_free(zio->io_data, zt->zt_bufsize);
264 
265 		zio->io_data = zt->zt_orig_data;
266 		zio->io_size = zt->zt_orig_size;
267 		zio->io_transform_stack = zt->zt_next;
268 
269 		kmem_free(zt, sizeof (zio_transform_t));
270 	}
271 }
272 
273 /*
274  * ==========================================================================
275  * I/O transform callbacks for subblocks and decompression
276  * ==========================================================================
277  */
278 static void
279 zio_subblock(zio_t *zio, void *data, uint64_t size)
280 {
281 	ASSERT(zio->io_size > size);
282 
283 	if (zio->io_type == ZIO_TYPE_READ)
284 		bcopy(zio->io_data, data, size);
285 }
286 
287 static void
288 zio_decompress(zio_t *zio, void *data, uint64_t size)
289 {
290 	if (zio->io_error == 0 &&
291 	    zio_decompress_data(BP_GET_COMPRESS(zio->io_bp),
292 	    zio->io_data, zio->io_size, data, size) != 0)
293 		zio->io_error = EIO;
294 }
295 
296 /*
297  * ==========================================================================
298  * I/O parent/child relationships and pipeline interlocks
299  * ==========================================================================
300  */
301 
302 static void
303 zio_add_child(zio_t *pio, zio_t *zio)
304 {
305 	mutex_enter(&pio->io_lock);
306 	if (zio->io_stage < ZIO_STAGE_READY)
307 		pio->io_children[zio->io_child_type][ZIO_WAIT_READY]++;
308 	if (zio->io_stage < ZIO_STAGE_DONE)
309 		pio->io_children[zio->io_child_type][ZIO_WAIT_DONE]++;
310 	zio->io_sibling_prev = NULL;
311 	zio->io_sibling_next = pio->io_child;
312 	if (pio->io_child != NULL)
313 		pio->io_child->io_sibling_prev = zio;
314 	pio->io_child = zio;
315 	zio->io_parent = pio;
316 	mutex_exit(&pio->io_lock);
317 }
318 
319 static void
320 zio_remove_child(zio_t *pio, zio_t *zio)
321 {
322 	zio_t *next, *prev;
323 
324 	ASSERT(zio->io_parent == pio);
325 
326 	mutex_enter(&pio->io_lock);
327 	next = zio->io_sibling_next;
328 	prev = zio->io_sibling_prev;
329 	if (next != NULL)
330 		next->io_sibling_prev = prev;
331 	if (prev != NULL)
332 		prev->io_sibling_next = next;
333 	if (pio->io_child == zio)
334 		pio->io_child = next;
335 	mutex_exit(&pio->io_lock);
336 }
337 
338 static boolean_t
339 zio_wait_for_children(zio_t *zio, enum zio_child child, enum zio_wait_type wait)
340 {
341 	uint64_t *countp = &zio->io_children[child][wait];
342 	boolean_t waiting = B_FALSE;
343 
344 	mutex_enter(&zio->io_lock);
345 	ASSERT(zio->io_stall == NULL);
346 	if (*countp != 0) {
347 		zio->io_stage--;
348 		zio->io_stall = countp;
349 		waiting = B_TRUE;
350 	}
351 	mutex_exit(&zio->io_lock);
352 
353 	return (waiting);
354 }
355 
356 static void
357 zio_notify_parent(zio_t *pio, zio_t *zio, enum zio_wait_type wait)
358 {
359 	uint64_t *countp = &pio->io_children[zio->io_child_type][wait];
360 	int *errorp = &pio->io_child_error[zio->io_child_type];
361 
362 	mutex_enter(&pio->io_lock);
363 	if (zio->io_error && !(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE))
364 		*errorp = zio_worst_error(*errorp, zio->io_error);
365 	pio->io_reexecute |= zio->io_reexecute;
366 	ASSERT3U(*countp, >, 0);
367 	if (--*countp == 0 && pio->io_stall == countp) {
368 		pio->io_stall = NULL;
369 		mutex_exit(&pio->io_lock);
370 		zio_execute(pio);
371 	} else {
372 		mutex_exit(&pio->io_lock);
373 	}
374 }
375 
376 static void
377 zio_inherit_child_errors(zio_t *zio, enum zio_child c)
378 {
379 	if (zio->io_child_error[c] != 0 && zio->io_error == 0)
380 		zio->io_error = zio->io_child_error[c];
381 }
382 
383 /*
384  * ==========================================================================
385  * Create the various types of I/O (read, write, free, etc)
386  * ==========================================================================
387  */
388 static zio_t *
389 zio_create(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
390     void *data, uint64_t size, zio_done_func_t *done, void *private,
391     zio_type_t type, int priority, int flags, vdev_t *vd, uint64_t offset,
392     const zbookmark_t *zb, uint8_t stage, uint32_t pipeline)
393 {
394 	zio_t *zio;
395 
396 	ASSERT3U(size, <=, SPA_MAXBLOCKSIZE);
397 	ASSERT(P2PHASE(size, SPA_MINBLOCKSIZE) == 0);
398 	ASSERT(P2PHASE(offset, SPA_MINBLOCKSIZE) == 0);
399 
400 	ASSERT(!vd || spa_config_held(spa, SCL_STATE_ALL, RW_READER));
401 	ASSERT(!bp || !(flags & ZIO_FLAG_CONFIG_WRITER));
402 	ASSERT(vd || stage == ZIO_STAGE_OPEN);
403 
404 	zio = kmem_cache_alloc(zio_cache, KM_SLEEP);
405 	bzero(zio, sizeof (zio_t));
406 
407 	mutex_init(&zio->io_lock, NULL, MUTEX_DEFAULT, NULL);
408 	cv_init(&zio->io_cv, NULL, CV_DEFAULT, NULL);
409 
410 	if (vd != NULL)
411 		zio->io_child_type = ZIO_CHILD_VDEV;
412 	else if (flags & ZIO_FLAG_GANG_CHILD)
413 		zio->io_child_type = ZIO_CHILD_GANG;
414 	else
415 		zio->io_child_type = ZIO_CHILD_LOGICAL;
416 
417 	if (bp != NULL) {
418 		zio->io_bp = bp;
419 		zio->io_bp_copy = *bp;
420 		zio->io_bp_orig = *bp;
421 		if (type != ZIO_TYPE_WRITE)
422 			zio->io_bp = &zio->io_bp_copy;	/* so caller can free */
423 		if (zio->io_child_type == ZIO_CHILD_LOGICAL) {
424 			if (BP_IS_GANG(bp))
425 				pipeline |= ZIO_GANG_STAGES;
426 			zio->io_logical = zio;
427 		}
428 	}
429 
430 	zio->io_spa = spa;
431 	zio->io_txg = txg;
432 	zio->io_data = data;
433 	zio->io_size = size;
434 	zio->io_done = done;
435 	zio->io_private = private;
436 	zio->io_type = type;
437 	zio->io_priority = priority;
438 	zio->io_vd = vd;
439 	zio->io_offset = offset;
440 	zio->io_orig_flags = zio->io_flags = flags;
441 	zio->io_orig_stage = zio->io_stage = stage;
442 	zio->io_orig_pipeline = zio->io_pipeline = pipeline;
443 
444 	if (zb != NULL)
445 		zio->io_bookmark = *zb;
446 
447 	if (pio != NULL) {
448 		/*
449 		 * Logical I/Os can have logical, gang, or vdev children.
450 		 * Gang I/Os can have gang or vdev children.
451 		 * Vdev I/Os can only have vdev children.
452 		 * The following ASSERT captures all of these constraints.
453 		 */
454 		ASSERT(zio->io_child_type <= pio->io_child_type);
455 		if (zio->io_logical == NULL)
456 			zio->io_logical = pio->io_logical;
457 		zio_add_child(pio, zio);
458 	}
459 
460 	return (zio);
461 }
462 
463 static void
464 zio_destroy(zio_t *zio)
465 {
466 	spa_t *spa = zio->io_spa;
467 	uint8_t async_root = zio->io_async_root;
468 
469 	mutex_destroy(&zio->io_lock);
470 	cv_destroy(&zio->io_cv);
471 	kmem_cache_free(zio_cache, zio);
472 
473 	if (async_root) {
474 		mutex_enter(&spa->spa_async_root_lock);
475 		if (--spa->spa_async_root_count == 0)
476 			cv_broadcast(&spa->spa_async_root_cv);
477 		mutex_exit(&spa->spa_async_root_lock);
478 	}
479 }
480 
481 zio_t *
482 zio_null(zio_t *pio, spa_t *spa, zio_done_func_t *done, void *private,
483 	int flags)
484 {
485 	zio_t *zio;
486 
487 	zio = zio_create(pio, spa, 0, NULL, NULL, 0, done, private,
488 	    ZIO_TYPE_NULL, ZIO_PRIORITY_NOW, flags, NULL, 0, NULL,
489 	    ZIO_STAGE_OPEN, ZIO_INTERLOCK_PIPELINE);
490 
491 	return (zio);
492 }
493 
494 zio_t *
495 zio_root(spa_t *spa, zio_done_func_t *done, void *private, int flags)
496 {
497 	return (zio_null(NULL, spa, done, private, flags));
498 }
499 
500 zio_t *
501 zio_read(zio_t *pio, spa_t *spa, const blkptr_t *bp,
502     void *data, uint64_t size, zio_done_func_t *done, void *private,
503     int priority, int flags, const zbookmark_t *zb)
504 {
505 	zio_t *zio;
506 
507 	zio = zio_create(pio, spa, bp->blk_birth, (blkptr_t *)bp,
508 	    data, size, done, private,
509 	    ZIO_TYPE_READ, priority, flags, NULL, 0, zb,
510 	    ZIO_STAGE_OPEN, ZIO_READ_PIPELINE);
511 
512 	return (zio);
513 }
514 
515 zio_t *
516 zio_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
517     void *data, uint64_t size, zio_prop_t *zp,
518     zio_done_func_t *ready, zio_done_func_t *done, void *private,
519     int priority, int flags, const zbookmark_t *zb)
520 {
521 	zio_t *zio;
522 
523 	ASSERT(zp->zp_checksum >= ZIO_CHECKSUM_OFF &&
524 	    zp->zp_checksum < ZIO_CHECKSUM_FUNCTIONS &&
525 	    zp->zp_compress >= ZIO_COMPRESS_OFF &&
526 	    zp->zp_compress < ZIO_COMPRESS_FUNCTIONS &&
527 	    zp->zp_type < DMU_OT_NUMTYPES &&
528 	    zp->zp_level < 32 &&
529 	    zp->zp_ndvas > 0 &&
530 	    zp->zp_ndvas <= spa_max_replication(spa));
531 	ASSERT(ready != NULL);
532 
533 	zio = zio_create(pio, spa, txg, bp, data, size, done, private,
534 	    ZIO_TYPE_WRITE, priority, flags, NULL, 0, zb,
535 	    ZIO_STAGE_OPEN, ZIO_WRITE_PIPELINE);
536 
537 	zio->io_ready = ready;
538 	zio->io_prop = *zp;
539 
540 	return (zio);
541 }
542 
543 zio_t *
544 zio_rewrite(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, void *data,
545     uint64_t size, zio_done_func_t *done, void *private, int priority,
546     int flags, zbookmark_t *zb)
547 {
548 	zio_t *zio;
549 
550 	zio = zio_create(pio, spa, txg, bp, data, size, done, private,
551 	    ZIO_TYPE_WRITE, priority, flags, NULL, 0, zb,
552 	    ZIO_STAGE_OPEN, ZIO_REWRITE_PIPELINE);
553 
554 	return (zio);
555 }
556 
557 zio_t *
558 zio_free(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
559     zio_done_func_t *done, void *private, int flags)
560 {
561 	zio_t *zio;
562 
563 	ASSERT(!BP_IS_HOLE(bp));
564 
565 	if (bp->blk_fill == BLK_FILL_ALREADY_FREED)
566 		return (zio_null(pio, spa, NULL, NULL, flags));
567 
568 	if (txg == spa->spa_syncing_txg &&
569 	    spa_sync_pass(spa) > SYNC_PASS_DEFERRED_FREE) {
570 		bplist_enqueue_deferred(&spa->spa_sync_bplist, bp);
571 		return (zio_null(pio, spa, NULL, NULL, flags));
572 	}
573 
574 	zio = zio_create(pio, spa, txg, bp, NULL, BP_GET_PSIZE(bp),
575 	    done, private, ZIO_TYPE_FREE, ZIO_PRIORITY_FREE, flags,
576 	    NULL, 0, NULL, ZIO_STAGE_OPEN, ZIO_FREE_PIPELINE);
577 
578 	return (zio);
579 }
580 
581 zio_t *
582 zio_claim(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
583     zio_done_func_t *done, void *private, int flags)
584 {
585 	zio_t *zio;
586 
587 	/*
588 	 * A claim is an allocation of a specific block.  Claims are needed
589 	 * to support immediate writes in the intent log.  The issue is that
590 	 * immediate writes contain committed data, but in a txg that was
591 	 * *not* committed.  Upon opening the pool after an unclean shutdown,
592 	 * the intent log claims all blocks that contain immediate write data
593 	 * so that the SPA knows they're in use.
594 	 *
595 	 * All claims *must* be resolved in the first txg -- before the SPA
596 	 * starts allocating blocks -- so that nothing is allocated twice.
597 	 */
598 	ASSERT3U(spa->spa_uberblock.ub_rootbp.blk_birth, <, spa_first_txg(spa));
599 	ASSERT3U(spa_first_txg(spa), <=, txg);
600 
601 	zio = zio_create(pio, spa, txg, bp, NULL, BP_GET_PSIZE(bp),
602 	    done, private, ZIO_TYPE_CLAIM, ZIO_PRIORITY_NOW, flags,
603 	    NULL, 0, NULL, ZIO_STAGE_OPEN, ZIO_CLAIM_PIPELINE);
604 
605 	return (zio);
606 }
607 
608 zio_t *
609 zio_ioctl(zio_t *pio, spa_t *spa, vdev_t *vd, int cmd,
610     zio_done_func_t *done, void *private, int priority, int flags)
611 {
612 	zio_t *zio;
613 	int c;
614 
615 	if (vd->vdev_children == 0) {
616 		zio = zio_create(pio, spa, 0, NULL, NULL, 0, done, private,
617 		    ZIO_TYPE_IOCTL, priority, flags, vd, 0, NULL,
618 		    ZIO_STAGE_OPEN, ZIO_IOCTL_PIPELINE);
619 
620 		zio->io_cmd = cmd;
621 	} else {
622 		zio = zio_null(pio, spa, NULL, NULL, flags);
623 
624 		for (c = 0; c < vd->vdev_children; c++)
625 			zio_nowait(zio_ioctl(zio, spa, vd->vdev_child[c], cmd,
626 			    done, private, priority, flags));
627 	}
628 
629 	return (zio);
630 }
631 
632 zio_t *
633 zio_read_phys(zio_t *pio, vdev_t *vd, uint64_t offset, uint64_t size,
634     void *data, int checksum, zio_done_func_t *done, void *private,
635     int priority, int flags, boolean_t labels)
636 {
637 	zio_t *zio;
638 
639 	ASSERT(vd->vdev_children == 0);
640 	ASSERT(!labels || offset + size <= VDEV_LABEL_START_SIZE ||
641 	    offset >= vd->vdev_psize - VDEV_LABEL_END_SIZE);
642 	ASSERT3U(offset + size, <=, vd->vdev_psize);
643 
644 	zio = zio_create(pio, vd->vdev_spa, 0, NULL, data, size, done, private,
645 	    ZIO_TYPE_READ, priority, flags, vd, offset, NULL,
646 	    ZIO_STAGE_OPEN, ZIO_READ_PHYS_PIPELINE);
647 
648 	zio->io_prop.zp_checksum = checksum;
649 
650 	return (zio);
651 }
652 
653 zio_t *
654 zio_write_phys(zio_t *pio, vdev_t *vd, uint64_t offset, uint64_t size,
655     void *data, int checksum, zio_done_func_t *done, void *private,
656     int priority, int flags, boolean_t labels)
657 {
658 	zio_t *zio;
659 
660 	ASSERT(vd->vdev_children == 0);
661 	ASSERT(!labels || offset + size <= VDEV_LABEL_START_SIZE ||
662 	    offset >= vd->vdev_psize - VDEV_LABEL_END_SIZE);
663 	ASSERT3U(offset + size, <=, vd->vdev_psize);
664 
665 	zio = zio_create(pio, vd->vdev_spa, 0, NULL, data, size, done, private,
666 	    ZIO_TYPE_WRITE, priority, flags, vd, offset, NULL,
667 	    ZIO_STAGE_OPEN, ZIO_WRITE_PHYS_PIPELINE);
668 
669 	zio->io_prop.zp_checksum = checksum;
670 
671 	if (zio_checksum_table[checksum].ci_zbt) {
672 		/*
673 		 * zbt checksums are necessarily destructive -- they modify
674 		 * the end of the write buffer to hold the verifier/checksum.
675 		 * Therefore, we must make a local copy in case the data is
676 		 * being written to multiple places in parallel.
677 		 */
678 		void *wbuf = zio_buf_alloc(size);
679 		bcopy(data, wbuf, size);
680 		zio_push_transform(zio, wbuf, size, size, NULL);
681 	}
682 
683 	return (zio);
684 }
685 
686 /*
687  * Create a child I/O to do some work for us.
688  */
689 zio_t *
690 zio_vdev_child_io(zio_t *pio, blkptr_t *bp, vdev_t *vd, uint64_t offset,
691 	void *data, uint64_t size, int type, int priority, int flags,
692 	zio_done_func_t *done, void *private)
693 {
694 	uint32_t pipeline = ZIO_VDEV_CHILD_PIPELINE;
695 	zio_t *zio;
696 
697 	ASSERT(vd->vdev_parent ==
698 	    (pio->io_vd ? pio->io_vd : pio->io_spa->spa_root_vdev));
699 
700 	if (type == ZIO_TYPE_READ && bp != NULL) {
701 		/*
702 		 * If we have the bp, then the child should perform the
703 		 * checksum and the parent need not.  This pushes error
704 		 * detection as close to the leaves as possible and
705 		 * eliminates redundant checksums in the interior nodes.
706 		 */
707 		pipeline |= 1U << ZIO_STAGE_CHECKSUM_VERIFY;
708 		pio->io_pipeline &= ~(1U << ZIO_STAGE_CHECKSUM_VERIFY);
709 	}
710 
711 	if (vd->vdev_children == 0)
712 		offset += VDEV_LABEL_START_SIZE;
713 
714 	zio = zio_create(pio, pio->io_spa, pio->io_txg, bp, data, size,
715 	    done, private, type, priority,
716 	    (pio->io_flags & ZIO_FLAG_VDEV_INHERIT) |
717 	    ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE | flags,
718 	    vd, offset, &pio->io_bookmark,
719 	    ZIO_STAGE_VDEV_IO_START - 1, pipeline);
720 
721 	return (zio);
722 }
723 
724 zio_t *
725 zio_vdev_delegated_io(vdev_t *vd, uint64_t offset, void *data, uint64_t size,
726 	int type, int priority, int flags, zio_done_func_t *done, void *private)
727 {
728 	zio_t *zio;
729 
730 	ASSERT(vd->vdev_ops->vdev_op_leaf);
731 
732 	zio = zio_create(NULL, vd->vdev_spa, 0, NULL,
733 	    data, size, done, private, type, priority,
734 	    flags | ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_RETRY,
735 	    vd, offset, NULL,
736 	    ZIO_STAGE_VDEV_IO_START - 1, ZIO_VDEV_CHILD_PIPELINE);
737 
738 	return (zio);
739 }
740 
741 void
742 zio_flush(zio_t *zio, vdev_t *vd)
743 {
744 	zio_nowait(zio_ioctl(zio, zio->io_spa, vd, DKIOCFLUSHWRITECACHE,
745 	    NULL, NULL, ZIO_PRIORITY_NOW,
746 	    ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY));
747 }
748 
749 /*
750  * ==========================================================================
751  * Prepare to read and write logical blocks
752  * ==========================================================================
753  */
754 
755 static int
756 zio_read_bp_init(zio_t *zio)
757 {
758 	blkptr_t *bp = zio->io_bp;
759 
760 	if (BP_GET_COMPRESS(bp) != ZIO_COMPRESS_OFF && zio->io_logical == zio) {
761 		uint64_t csize = BP_GET_PSIZE(bp);
762 		void *cbuf = zio_buf_alloc(csize);
763 
764 		zio_push_transform(zio, cbuf, csize, csize, zio_decompress);
765 	}
766 
767 	if (!dmu_ot[BP_GET_TYPE(bp)].ot_metadata && BP_GET_LEVEL(bp) == 0)
768 		zio->io_flags |= ZIO_FLAG_DONT_CACHE;
769 
770 	return (ZIO_PIPELINE_CONTINUE);
771 }
772 
773 static int
774 zio_write_bp_init(zio_t *zio)
775 {
776 	zio_prop_t *zp = &zio->io_prop;
777 	int compress = zp->zp_compress;
778 	blkptr_t *bp = zio->io_bp;
779 	void *cbuf;
780 	uint64_t lsize = zio->io_size;
781 	uint64_t csize = lsize;
782 	uint64_t cbufsize = 0;
783 	int pass = 1;
784 
785 	/*
786 	 * If our children haven't all reached the ready stage,
787 	 * wait for them and then repeat this pipeline stage.
788 	 */
789 	if (zio_wait_for_children(zio, ZIO_CHILD_GANG, ZIO_WAIT_READY) ||
790 	    zio_wait_for_children(zio, ZIO_CHILD_LOGICAL, ZIO_WAIT_READY))
791 		return (ZIO_PIPELINE_STOP);
792 
793 	if (!IO_IS_ALLOCATING(zio))
794 		return (ZIO_PIPELINE_CONTINUE);
795 
796 	ASSERT(compress != ZIO_COMPRESS_INHERIT);
797 
798 	if (bp->blk_birth == zio->io_txg) {
799 		/*
800 		 * We're rewriting an existing block, which means we're
801 		 * working on behalf of spa_sync().  For spa_sync() to
802 		 * converge, it must eventually be the case that we don't
803 		 * have to allocate new blocks.  But compression changes
804 		 * the blocksize, which forces a reallocate, and makes
805 		 * convergence take longer.  Therefore, after the first
806 		 * few passes, stop compressing to ensure convergence.
807 		 */
808 		pass = spa_sync_pass(zio->io_spa);
809 		ASSERT(pass > 1);
810 
811 		if (pass > SYNC_PASS_DONT_COMPRESS)
812 			compress = ZIO_COMPRESS_OFF;
813 
814 		/*
815 		 * Only MOS (objset 0) data should need to be rewritten.
816 		 */
817 		ASSERT(zio->io_logical->io_bookmark.zb_objset == 0);
818 
819 		/* Make sure someone doesn't change their mind on overwrites */
820 		ASSERT(MIN(zp->zp_ndvas + BP_IS_GANG(bp),
821 		    spa_max_replication(zio->io_spa)) == BP_GET_NDVAS(bp));
822 	}
823 
824 	if (compress != ZIO_COMPRESS_OFF) {
825 		if (!zio_compress_data(compress, zio->io_data, zio->io_size,
826 		    &cbuf, &csize, &cbufsize)) {
827 			compress = ZIO_COMPRESS_OFF;
828 		} else if (csize != 0) {
829 			zio_push_transform(zio, cbuf, csize, cbufsize, NULL);
830 		}
831 	}
832 
833 	/*
834 	 * The final pass of spa_sync() must be all rewrites, but the first
835 	 * few passes offer a trade-off: allocating blocks defers convergence,
836 	 * but newly allocated blocks are sequential, so they can be written
837 	 * to disk faster.  Therefore, we allow the first few passes of
838 	 * spa_sync() to allocate new blocks, but force rewrites after that.
839 	 * There should only be a handful of blocks after pass 1 in any case.
840 	 */
841 	if (bp->blk_birth == zio->io_txg && BP_GET_PSIZE(bp) == csize &&
842 	    pass > SYNC_PASS_REWRITE) {
843 		ASSERT(csize != 0);
844 		uint32_t gang_stages = zio->io_pipeline & ZIO_GANG_STAGES;
845 		zio->io_pipeline = ZIO_REWRITE_PIPELINE | gang_stages;
846 		zio->io_flags |= ZIO_FLAG_IO_REWRITE;
847 	} else {
848 		BP_ZERO(bp);
849 		zio->io_pipeline = ZIO_WRITE_PIPELINE;
850 	}
851 
852 	if (csize == 0) {
853 		zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
854 	} else {
855 		ASSERT(zp->zp_checksum != ZIO_CHECKSUM_GANG_HEADER);
856 		BP_SET_LSIZE(bp, lsize);
857 		BP_SET_PSIZE(bp, csize);
858 		BP_SET_COMPRESS(bp, compress);
859 		BP_SET_CHECKSUM(bp, zp->zp_checksum);
860 		BP_SET_TYPE(bp, zp->zp_type);
861 		BP_SET_LEVEL(bp, zp->zp_level);
862 		BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
863 	}
864 
865 	return (ZIO_PIPELINE_CONTINUE);
866 }
867 
868 /*
869  * ==========================================================================
870  * Execute the I/O pipeline
871  * ==========================================================================
872  */
873 
874 static void
875 zio_taskq_dispatch(zio_t *zio, enum zio_taskq_type q)
876 {
877 	zio_type_t t = zio->io_type;
878 
879 	/*
880 	 * If we're a config writer, the normal issue and interrupt threads
881 	 * may all be blocked waiting for the config lock.  In this case,
882 	 * select the otherwise-unused taskq for ZIO_TYPE_NULL.
883 	 */
884 	if (zio->io_flags & ZIO_FLAG_CONFIG_WRITER)
885 		t = ZIO_TYPE_NULL;
886 
887 	/*
888 	 * A similar issue exists for the L2ARC write thread until L2ARC 2.0.
889 	 */
890 	if (t == ZIO_TYPE_WRITE && zio->io_vd && zio->io_vd->vdev_aux)
891 		t = ZIO_TYPE_NULL;
892 
893 	(void) taskq_dispatch(zio->io_spa->spa_zio_taskq[t][q],
894 	    (task_func_t *)zio_execute, zio, TQ_SLEEP);
895 }
896 
897 static boolean_t
898 zio_taskq_member(zio_t *zio, enum zio_taskq_type q)
899 {
900 	kthread_t *executor = zio->io_executor;
901 	spa_t *spa = zio->io_spa;
902 
903 	for (zio_type_t t = 0; t < ZIO_TYPES; t++)
904 		if (taskq_member(spa->spa_zio_taskq[t][q], executor))
905 			return (B_TRUE);
906 
907 	return (B_FALSE);
908 }
909 
910 static int
911 zio_issue_async(zio_t *zio)
912 {
913 	zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE);
914 
915 	return (ZIO_PIPELINE_STOP);
916 }
917 
918 void
919 zio_interrupt(zio_t *zio)
920 {
921 	zio_taskq_dispatch(zio, ZIO_TASKQ_INTERRUPT);
922 }
923 
924 /*
925  * Execute the I/O pipeline until one of the following occurs:
926  * (1) the I/O completes; (2) the pipeline stalls waiting for
927  * dependent child I/Os; (3) the I/O issues, so we're waiting
928  * for an I/O completion interrupt; (4) the I/O is delegated by
929  * vdev-level caching or aggregation; (5) the I/O is deferred
930  * due to vdev-level queueing; (6) the I/O is handed off to
931  * another thread.  In all cases, the pipeline stops whenever
932  * there's no CPU work; it never burns a thread in cv_wait().
933  *
934  * There's no locking on io_stage because there's no legitimate way
935  * for multiple threads to be attempting to process the same I/O.
936  */
937 static zio_pipe_stage_t *zio_pipeline[ZIO_STAGES];
938 
939 void
940 zio_execute(zio_t *zio)
941 {
942 	zio->io_executor = curthread;
943 
944 	while (zio->io_stage < ZIO_STAGE_DONE) {
945 		uint32_t pipeline = zio->io_pipeline;
946 		zio_stage_t stage = zio->io_stage;
947 		int rv;
948 
949 		ASSERT(!MUTEX_HELD(&zio->io_lock));
950 
951 		while (((1U << ++stage) & pipeline) == 0)
952 			continue;
953 
954 		ASSERT(stage <= ZIO_STAGE_DONE);
955 		ASSERT(zio->io_stall == NULL);
956 
957 		/*
958 		 * If we are in interrupt context and this pipeline stage
959 		 * will grab a config lock that is held across I/O,
960 		 * issue async to avoid deadlock.
961 		 */
962 		if (((1U << stage) & ZIO_CONFIG_LOCK_BLOCKING_STAGES) &&
963 		    zio->io_vd == NULL &&
964 		    zio_taskq_member(zio, ZIO_TASKQ_INTERRUPT)) {
965 			zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE);
966 			return;
967 		}
968 
969 		zio->io_stage = stage;
970 		rv = zio_pipeline[stage](zio);
971 
972 		if (rv == ZIO_PIPELINE_STOP)
973 			return;
974 
975 		ASSERT(rv == ZIO_PIPELINE_CONTINUE);
976 	}
977 }
978 
979 /*
980  * ==========================================================================
981  * Initiate I/O, either sync or async
982  * ==========================================================================
983  */
984 int
985 zio_wait(zio_t *zio)
986 {
987 	int error;
988 
989 	ASSERT(zio->io_stage == ZIO_STAGE_OPEN);
990 	ASSERT(zio->io_executor == NULL);
991 
992 	zio->io_waiter = curthread;
993 
994 	zio_execute(zio);
995 
996 	mutex_enter(&zio->io_lock);
997 	while (zio->io_executor != NULL)
998 		cv_wait(&zio->io_cv, &zio->io_lock);
999 	mutex_exit(&zio->io_lock);
1000 
1001 	error = zio->io_error;
1002 	zio_destroy(zio);
1003 
1004 	return (error);
1005 }
1006 
1007 void
1008 zio_nowait(zio_t *zio)
1009 {
1010 	ASSERT(zio->io_executor == NULL);
1011 
1012 	if (zio->io_parent == NULL && zio->io_child_type == ZIO_CHILD_LOGICAL) {
1013 		/*
1014 		 * This is a logical async I/O with no parent to wait for it.
1015 		 * Attach it to the pool's global async root zio so that
1016 		 * spa_unload() has a way of waiting for async I/O to finish.
1017 		 */
1018 		spa_t *spa = zio->io_spa;
1019 		zio->io_async_root = B_TRUE;
1020 		mutex_enter(&spa->spa_async_root_lock);
1021 		spa->spa_async_root_count++;
1022 		mutex_exit(&spa->spa_async_root_lock);
1023 	}
1024 
1025 	zio_execute(zio);
1026 }
1027 
1028 /*
1029  * ==========================================================================
1030  * Reexecute or suspend/resume failed I/O
1031  * ==========================================================================
1032  */
1033 
1034 static void
1035 zio_reexecute(zio_t *pio)
1036 {
1037 	zio_t *zio, *zio_next;
1038 
1039 	pio->io_flags = pio->io_orig_flags;
1040 	pio->io_stage = pio->io_orig_stage;
1041 	pio->io_pipeline = pio->io_orig_pipeline;
1042 	pio->io_reexecute = 0;
1043 	pio->io_error = 0;
1044 	for (int c = 0; c < ZIO_CHILD_TYPES; c++)
1045 		pio->io_child_error[c] = 0;
1046 
1047 	if (IO_IS_ALLOCATING(pio)) {
1048 		/*
1049 		 * Remember the failed bp so that the io_ready() callback
1050 		 * can update its accounting upon reexecution.  The block
1051 		 * was already freed in zio_done(); we indicate this with
1052 		 * a fill count of -1 so that zio_free() knows to skip it.
1053 		 */
1054 		blkptr_t *bp = pio->io_bp;
1055 		ASSERT(bp->blk_birth == 0 || bp->blk_birth == pio->io_txg);
1056 		bp->blk_fill = BLK_FILL_ALREADY_FREED;
1057 		pio->io_bp_orig = *bp;
1058 		BP_ZERO(bp);
1059 	}
1060 
1061 	/*
1062 	 * As we reexecute pio's children, new children could be created.
1063 	 * New children go to the head of the io_child list, however,
1064 	 * so we will (correctly) not reexecute them.  The key is that
1065 	 * the remainder of the io_child list, from 'zio_next' onward,
1066 	 * cannot be affected by any side effects of reexecuting 'zio'.
1067 	 */
1068 	for (zio = pio->io_child; zio != NULL; zio = zio_next) {
1069 		zio_next = zio->io_sibling_next;
1070 		mutex_enter(&pio->io_lock);
1071 		pio->io_children[zio->io_child_type][ZIO_WAIT_READY]++;
1072 		pio->io_children[zio->io_child_type][ZIO_WAIT_DONE]++;
1073 		mutex_exit(&pio->io_lock);
1074 		zio_reexecute(zio);
1075 	}
1076 
1077 	/*
1078 	 * Now that all children have been reexecuted, execute the parent.
1079 	 */
1080 	zio_execute(pio);
1081 }
1082 
1083 void
1084 zio_suspend(spa_t *spa, zio_t *zio)
1085 {
1086 	if (spa_get_failmode(spa) == ZIO_FAILURE_MODE_PANIC)
1087 		fm_panic("Pool '%s' has encountered an uncorrectable I/O "
1088 		    "failure and the failure mode property for this pool "
1089 		    "is set to panic.", spa_name(spa));
1090 
1091 	zfs_ereport_post(FM_EREPORT_ZFS_IO_FAILURE, spa, NULL, NULL, 0, 0);
1092 
1093 	mutex_enter(&spa->spa_suspend_lock);
1094 
1095 	if (spa->spa_suspend_zio_root == NULL)
1096 		spa->spa_suspend_zio_root = zio_root(spa, NULL, NULL, 0);
1097 
1098 	spa->spa_suspended = B_TRUE;
1099 
1100 	if (zio != NULL) {
1101 		ASSERT(zio != spa->spa_suspend_zio_root);
1102 		ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1103 		ASSERT(zio->io_parent == NULL);
1104 		ASSERT(zio->io_stage == ZIO_STAGE_DONE);
1105 		zio_add_child(spa->spa_suspend_zio_root, zio);
1106 	}
1107 
1108 	mutex_exit(&spa->spa_suspend_lock);
1109 }
1110 
1111 void
1112 zio_resume(spa_t *spa)
1113 {
1114 	zio_t *pio, *zio;
1115 
1116 	/*
1117 	 * Reexecute all previously suspended i/o.
1118 	 */
1119 	mutex_enter(&spa->spa_suspend_lock);
1120 	spa->spa_suspended = B_FALSE;
1121 	cv_broadcast(&spa->spa_suspend_cv);
1122 	pio = spa->spa_suspend_zio_root;
1123 	spa->spa_suspend_zio_root = NULL;
1124 	mutex_exit(&spa->spa_suspend_lock);
1125 
1126 	if (pio == NULL)
1127 		return;
1128 
1129 	while ((zio = pio->io_child) != NULL) {
1130 		zio_remove_child(pio, zio);
1131 		zio->io_parent = NULL;
1132 		zio_reexecute(zio);
1133 	}
1134 
1135 	ASSERT(pio->io_children[ZIO_CHILD_LOGICAL][ZIO_WAIT_DONE] == 0);
1136 
1137 	(void) zio_wait(pio);
1138 }
1139 
1140 void
1141 zio_resume_wait(spa_t *spa)
1142 {
1143 	mutex_enter(&spa->spa_suspend_lock);
1144 	while (spa_suspended(spa))
1145 		cv_wait(&spa->spa_suspend_cv, &spa->spa_suspend_lock);
1146 	mutex_exit(&spa->spa_suspend_lock);
1147 }
1148 
1149 /*
1150  * ==========================================================================
1151  * Gang blocks.
1152  *
1153  * A gang block is a collection of small blocks that looks to the DMU
1154  * like one large block.  When zio_dva_allocate() cannot find a block
1155  * of the requested size, due to either severe fragmentation or the pool
1156  * being nearly full, it calls zio_write_gang_block() to construct the
1157  * block from smaller fragments.
1158  *
1159  * A gang block consists of a gang header (zio_gbh_phys_t) and up to
1160  * three (SPA_GBH_NBLKPTRS) gang members.  The gang header is just like
1161  * an indirect block: it's an array of block pointers.  It consumes
1162  * only one sector and hence is allocatable regardless of fragmentation.
1163  * The gang header's bps point to its gang members, which hold the data.
1164  *
1165  * Gang blocks are self-checksumming, using the bp's <vdev, offset, txg>
1166  * as the verifier to ensure uniqueness of the SHA256 checksum.
1167  * Critically, the gang block bp's blk_cksum is the checksum of the data,
1168  * not the gang header.  This ensures that data block signatures (needed for
1169  * deduplication) are independent of how the block is physically stored.
1170  *
1171  * Gang blocks can be nested: a gang member may itself be a gang block.
1172  * Thus every gang block is a tree in which root and all interior nodes are
1173  * gang headers, and the leaves are normal blocks that contain user data.
1174  * The root of the gang tree is called the gang leader.
1175  *
1176  * To perform any operation (read, rewrite, free, claim) on a gang block,
1177  * zio_gang_assemble() first assembles the gang tree (minus data leaves)
1178  * in the io_gang_tree field of the original logical i/o by recursively
1179  * reading the gang leader and all gang headers below it.  This yields
1180  * an in-core tree containing the contents of every gang header and the
1181  * bps for every constituent of the gang block.
1182  *
1183  * With the gang tree now assembled, zio_gang_issue() just walks the gang tree
1184  * and invokes a callback on each bp.  To free a gang block, zio_gang_issue()
1185  * calls zio_free_gang() -- a trivial wrapper around zio_free() -- for each bp.
1186  * zio_claim_gang() provides a similarly trivial wrapper for zio_claim().
1187  * zio_read_gang() is a wrapper around zio_read() that omits reading gang
1188  * headers, since we already have those in io_gang_tree.  zio_rewrite_gang()
1189  * performs a zio_rewrite() of the data or, for gang headers, a zio_rewrite()
1190  * of the gang header plus zio_checksum_compute() of the data to update the
1191  * gang header's blk_cksum as described above.
1192  *
1193  * The two-phase assemble/issue model solves the problem of partial failure --
1194  * what if you'd freed part of a gang block but then couldn't read the
1195  * gang header for another part?  Assembling the entire gang tree first
1196  * ensures that all the necessary gang header I/O has succeeded before
1197  * starting the actual work of free, claim, or write.  Once the gang tree
1198  * is assembled, free and claim are in-memory operations that cannot fail.
1199  *
1200  * In the event that a gang write fails, zio_dva_unallocate() walks the
1201  * gang tree to immediately free (i.e. insert back into the space map)
1202  * everything we've allocated.  This ensures that we don't get ENOSPC
1203  * errors during repeated suspend/resume cycles due to a flaky device.
1204  *
1205  * Gang rewrites only happen during sync-to-convergence.  If we can't assemble
1206  * the gang tree, we won't modify the block, so we can safely defer the free
1207  * (knowing that the block is still intact).  If we *can* assemble the gang
1208  * tree, then even if some of the rewrites fail, zio_dva_unallocate() will free
1209  * each constituent bp and we can allocate a new block on the next sync pass.
1210  *
1211  * In all cases, the gang tree allows complete recovery from partial failure.
1212  * ==========================================================================
1213  */
1214 
1215 static zio_t *
1216 zio_read_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, void *data)
1217 {
1218 	if (gn != NULL)
1219 		return (pio);
1220 
1221 	return (zio_read(pio, pio->io_spa, bp, data, BP_GET_PSIZE(bp),
1222 	    NULL, NULL, pio->io_priority, ZIO_GANG_CHILD_FLAGS(pio),
1223 	    &pio->io_bookmark));
1224 }
1225 
1226 zio_t *
1227 zio_rewrite_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, void *data)
1228 {
1229 	zio_t *zio;
1230 
1231 	if (gn != NULL) {
1232 		zio = zio_rewrite(pio, pio->io_spa, pio->io_txg, bp,
1233 		    gn->gn_gbh, SPA_GANGBLOCKSIZE, NULL, NULL, pio->io_priority,
1234 		    ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
1235 		/*
1236 		 * As we rewrite each gang header, the pipeline will compute
1237 		 * a new gang block header checksum for it; but no one will
1238 		 * compute a new data checksum, so we do that here.  The one
1239 		 * exception is the gang leader: the pipeline already computed
1240 		 * its data checksum because that stage precedes gang assembly.
1241 		 * (Presently, nothing actually uses interior data checksums;
1242 		 * this is just good hygiene.)
1243 		 */
1244 		if (gn != pio->io_logical->io_gang_tree) {
1245 			zio_checksum_compute(zio, BP_GET_CHECKSUM(bp),
1246 			    data, BP_GET_PSIZE(bp));
1247 		}
1248 	} else {
1249 		zio = zio_rewrite(pio, pio->io_spa, pio->io_txg, bp,
1250 		    data, BP_GET_PSIZE(bp), NULL, NULL, pio->io_priority,
1251 		    ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
1252 	}
1253 
1254 	return (zio);
1255 }
1256 
1257 /* ARGSUSED */
1258 zio_t *
1259 zio_free_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, void *data)
1260 {
1261 	return (zio_free(pio, pio->io_spa, pio->io_txg, bp,
1262 	    NULL, NULL, ZIO_GANG_CHILD_FLAGS(pio)));
1263 }
1264 
1265 /* ARGSUSED */
1266 zio_t *
1267 zio_claim_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, void *data)
1268 {
1269 	return (zio_claim(pio, pio->io_spa, pio->io_txg, bp,
1270 	    NULL, NULL, ZIO_GANG_CHILD_FLAGS(pio)));
1271 }
1272 
1273 static zio_gang_issue_func_t *zio_gang_issue_func[ZIO_TYPES] = {
1274 	NULL,
1275 	zio_read_gang,
1276 	zio_rewrite_gang,
1277 	zio_free_gang,
1278 	zio_claim_gang,
1279 	NULL
1280 };
1281 
1282 static void zio_gang_tree_assemble_done(zio_t *zio);
1283 
1284 static zio_gang_node_t *
1285 zio_gang_node_alloc(zio_gang_node_t **gnpp)
1286 {
1287 	zio_gang_node_t *gn;
1288 
1289 	ASSERT(*gnpp == NULL);
1290 
1291 	gn = kmem_zalloc(sizeof (*gn), KM_SLEEP);
1292 	gn->gn_gbh = zio_buf_alloc(SPA_GANGBLOCKSIZE);
1293 	*gnpp = gn;
1294 
1295 	return (gn);
1296 }
1297 
1298 static void
1299 zio_gang_node_free(zio_gang_node_t **gnpp)
1300 {
1301 	zio_gang_node_t *gn = *gnpp;
1302 
1303 	for (int g = 0; g < SPA_GBH_NBLKPTRS; g++)
1304 		ASSERT(gn->gn_child[g] == NULL);
1305 
1306 	zio_buf_free(gn->gn_gbh, SPA_GANGBLOCKSIZE);
1307 	kmem_free(gn, sizeof (*gn));
1308 	*gnpp = NULL;
1309 }
1310 
1311 static void
1312 zio_gang_tree_free(zio_gang_node_t **gnpp)
1313 {
1314 	zio_gang_node_t *gn = *gnpp;
1315 
1316 	if (gn == NULL)
1317 		return;
1318 
1319 	for (int g = 0; g < SPA_GBH_NBLKPTRS; g++)
1320 		zio_gang_tree_free(&gn->gn_child[g]);
1321 
1322 	zio_gang_node_free(gnpp);
1323 }
1324 
1325 static void
1326 zio_gang_tree_assemble(zio_t *lio, blkptr_t *bp, zio_gang_node_t **gnpp)
1327 {
1328 	zio_gang_node_t *gn = zio_gang_node_alloc(gnpp);
1329 
1330 	ASSERT(lio->io_logical == lio);
1331 	ASSERT(BP_IS_GANG(bp));
1332 
1333 	zio_nowait(zio_read(lio, lio->io_spa, bp, gn->gn_gbh,
1334 	    SPA_GANGBLOCKSIZE, zio_gang_tree_assemble_done, gn,
1335 	    lio->io_priority, ZIO_GANG_CHILD_FLAGS(lio), &lio->io_bookmark));
1336 }
1337 
1338 static void
1339 zio_gang_tree_assemble_done(zio_t *zio)
1340 {
1341 	zio_t *lio = zio->io_logical;
1342 	zio_gang_node_t *gn = zio->io_private;
1343 	blkptr_t *bp = zio->io_bp;
1344 
1345 	ASSERT(zio->io_parent == lio);
1346 	ASSERT(zio->io_child == NULL);
1347 
1348 	if (zio->io_error)
1349 		return;
1350 
1351 	if (BP_SHOULD_BYTESWAP(bp))
1352 		byteswap_uint64_array(zio->io_data, zio->io_size);
1353 
1354 	ASSERT(zio->io_data == gn->gn_gbh);
1355 	ASSERT(zio->io_size == SPA_GANGBLOCKSIZE);
1356 	ASSERT(gn->gn_gbh->zg_tail.zbt_magic == ZBT_MAGIC);
1357 
1358 	for (int g = 0; g < SPA_GBH_NBLKPTRS; g++) {
1359 		blkptr_t *gbp = &gn->gn_gbh->zg_blkptr[g];
1360 		if (!BP_IS_GANG(gbp))
1361 			continue;
1362 		zio_gang_tree_assemble(lio, gbp, &gn->gn_child[g]);
1363 	}
1364 }
1365 
1366 static void
1367 zio_gang_tree_issue(zio_t *pio, zio_gang_node_t *gn, blkptr_t *bp, void *data)
1368 {
1369 	zio_t *lio = pio->io_logical;
1370 	zio_t *zio;
1371 
1372 	ASSERT(BP_IS_GANG(bp) == !!gn);
1373 	ASSERT(BP_GET_CHECKSUM(bp) == BP_GET_CHECKSUM(lio->io_bp));
1374 	ASSERT(BP_GET_LSIZE(bp) == BP_GET_PSIZE(bp) || gn == lio->io_gang_tree);
1375 
1376 	/*
1377 	 * If you're a gang header, your data is in gn->gn_gbh.
1378 	 * If you're a gang member, your data is in 'data' and gn == NULL.
1379 	 */
1380 	zio = zio_gang_issue_func[lio->io_type](pio, bp, gn, data);
1381 
1382 	if (gn != NULL) {
1383 		ASSERT(gn->gn_gbh->zg_tail.zbt_magic == ZBT_MAGIC);
1384 
1385 		for (int g = 0; g < SPA_GBH_NBLKPTRS; g++) {
1386 			blkptr_t *gbp = &gn->gn_gbh->zg_blkptr[g];
1387 			if (BP_IS_HOLE(gbp))
1388 				continue;
1389 			zio_gang_tree_issue(zio, gn->gn_child[g], gbp, data);
1390 			data = (char *)data + BP_GET_PSIZE(gbp);
1391 		}
1392 	}
1393 
1394 	if (gn == lio->io_gang_tree)
1395 		ASSERT3P((char *)lio->io_data + lio->io_size, ==, data);
1396 
1397 	if (zio != pio)
1398 		zio_nowait(zio);
1399 }
1400 
1401 static int
1402 zio_gang_assemble(zio_t *zio)
1403 {
1404 	blkptr_t *bp = zio->io_bp;
1405 
1406 	ASSERT(BP_IS_GANG(bp) && zio == zio->io_logical);
1407 
1408 	zio_gang_tree_assemble(zio, bp, &zio->io_gang_tree);
1409 
1410 	return (ZIO_PIPELINE_CONTINUE);
1411 }
1412 
1413 static int
1414 zio_gang_issue(zio_t *zio)
1415 {
1416 	zio_t *lio = zio->io_logical;
1417 	blkptr_t *bp = zio->io_bp;
1418 
1419 	if (zio_wait_for_children(zio, ZIO_CHILD_GANG, ZIO_WAIT_DONE))
1420 		return (ZIO_PIPELINE_STOP);
1421 
1422 	ASSERT(BP_IS_GANG(bp) && zio == lio);
1423 
1424 	if (zio->io_child_error[ZIO_CHILD_GANG] == 0)
1425 		zio_gang_tree_issue(lio, lio->io_gang_tree, bp, lio->io_data);
1426 	else
1427 		zio_gang_tree_free(&lio->io_gang_tree);
1428 
1429 	zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1430 
1431 	return (ZIO_PIPELINE_CONTINUE);
1432 }
1433 
1434 static void
1435 zio_write_gang_member_ready(zio_t *zio)
1436 {
1437 	zio_t *pio = zio->io_parent;
1438 	zio_t *lio = zio->io_logical;
1439 	dva_t *cdva = zio->io_bp->blk_dva;
1440 	dva_t *pdva = pio->io_bp->blk_dva;
1441 	uint64_t asize;
1442 
1443 	if (BP_IS_HOLE(zio->io_bp))
1444 		return;
1445 
1446 	ASSERT(BP_IS_HOLE(&zio->io_bp_orig));
1447 
1448 	ASSERT(zio->io_child_type == ZIO_CHILD_GANG);
1449 	ASSERT3U(zio->io_prop.zp_ndvas, ==, lio->io_prop.zp_ndvas);
1450 	ASSERT3U(zio->io_prop.zp_ndvas, <=, BP_GET_NDVAS(zio->io_bp));
1451 	ASSERT3U(pio->io_prop.zp_ndvas, <=, BP_GET_NDVAS(pio->io_bp));
1452 	ASSERT3U(BP_GET_NDVAS(zio->io_bp), <=, BP_GET_NDVAS(pio->io_bp));
1453 
1454 	mutex_enter(&pio->io_lock);
1455 	for (int d = 0; d < BP_GET_NDVAS(zio->io_bp); d++) {
1456 		ASSERT(DVA_GET_GANG(&pdva[d]));
1457 		asize = DVA_GET_ASIZE(&pdva[d]);
1458 		asize += DVA_GET_ASIZE(&cdva[d]);
1459 		DVA_SET_ASIZE(&pdva[d], asize);
1460 	}
1461 	mutex_exit(&pio->io_lock);
1462 }
1463 
1464 static int
1465 zio_write_gang_block(zio_t *pio)
1466 {
1467 	spa_t *spa = pio->io_spa;
1468 	blkptr_t *bp = pio->io_bp;
1469 	zio_t *lio = pio->io_logical;
1470 	zio_t *zio;
1471 	zio_gang_node_t *gn, **gnpp;
1472 	zio_gbh_phys_t *gbh;
1473 	uint64_t txg = pio->io_txg;
1474 	uint64_t resid = pio->io_size;
1475 	uint64_t lsize;
1476 	int ndvas = lio->io_prop.zp_ndvas;
1477 	int gbh_ndvas = MIN(ndvas + 1, spa_max_replication(spa));
1478 	zio_prop_t zp;
1479 	int error;
1480 
1481 	error = metaslab_alloc(spa, spa->spa_normal_class, SPA_GANGBLOCKSIZE,
1482 	    bp, gbh_ndvas, txg, pio == lio ? NULL : lio->io_bp,
1483 	    METASLAB_HINTBP_FAVOR | METASLAB_GANG_HEADER);
1484 	if (error) {
1485 		pio->io_error = error;
1486 		return (ZIO_PIPELINE_CONTINUE);
1487 	}
1488 
1489 	if (pio == lio) {
1490 		gnpp = &lio->io_gang_tree;
1491 	} else {
1492 		gnpp = pio->io_private;
1493 		ASSERT(pio->io_ready == zio_write_gang_member_ready);
1494 	}
1495 
1496 	gn = zio_gang_node_alloc(gnpp);
1497 	gbh = gn->gn_gbh;
1498 	bzero(gbh, SPA_GANGBLOCKSIZE);
1499 
1500 	/*
1501 	 * Create the gang header.
1502 	 */
1503 	zio = zio_rewrite(pio, spa, txg, bp, gbh, SPA_GANGBLOCKSIZE, NULL, NULL,
1504 	    pio->io_priority, ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
1505 
1506 	/*
1507 	 * Create and nowait the gang children.
1508 	 */
1509 	for (int g = 0; resid != 0; resid -= lsize, g++) {
1510 		lsize = P2ROUNDUP(resid / (SPA_GBH_NBLKPTRS - g),
1511 		    SPA_MINBLOCKSIZE);
1512 		ASSERT(lsize >= SPA_MINBLOCKSIZE && lsize <= resid);
1513 
1514 		zp.zp_checksum = lio->io_prop.zp_checksum;
1515 		zp.zp_compress = ZIO_COMPRESS_OFF;
1516 		zp.zp_type = DMU_OT_NONE;
1517 		zp.zp_level = 0;
1518 		zp.zp_ndvas = lio->io_prop.zp_ndvas;
1519 
1520 		zio_nowait(zio_write(zio, spa, txg, &gbh->zg_blkptr[g],
1521 		    (char *)pio->io_data + (pio->io_size - resid), lsize, &zp,
1522 		    zio_write_gang_member_ready, NULL, &gn->gn_child[g],
1523 		    pio->io_priority, ZIO_GANG_CHILD_FLAGS(pio),
1524 		    &pio->io_bookmark));
1525 	}
1526 
1527 	/*
1528 	 * Set pio's pipeline to just wait for zio to finish.
1529 	 */
1530 	pio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1531 
1532 	zio_nowait(zio);
1533 
1534 	return (ZIO_PIPELINE_CONTINUE);
1535 }
1536 
1537 /*
1538  * ==========================================================================
1539  * Allocate and free blocks
1540  * ==========================================================================
1541  */
1542 
1543 static int
1544 zio_dva_allocate(zio_t *zio)
1545 {
1546 	spa_t *spa = zio->io_spa;
1547 	metaslab_class_t *mc = spa->spa_normal_class;
1548 	blkptr_t *bp = zio->io_bp;
1549 	int error;
1550 
1551 	ASSERT(BP_IS_HOLE(bp));
1552 	ASSERT3U(BP_GET_NDVAS(bp), ==, 0);
1553 	ASSERT3U(zio->io_prop.zp_ndvas, >, 0);
1554 	ASSERT3U(zio->io_prop.zp_ndvas, <=, spa_max_replication(spa));
1555 	ASSERT3U(zio->io_size, ==, BP_GET_PSIZE(bp));
1556 
1557 	error = metaslab_alloc(spa, mc, zio->io_size, bp,
1558 	    zio->io_prop.zp_ndvas, zio->io_txg, NULL, 0);
1559 
1560 	if (error) {
1561 		if (error == ENOSPC && zio->io_size > SPA_MINBLOCKSIZE)
1562 			return (zio_write_gang_block(zio));
1563 		zio->io_error = error;
1564 	}
1565 
1566 	return (ZIO_PIPELINE_CONTINUE);
1567 }
1568 
1569 static int
1570 zio_dva_free(zio_t *zio)
1571 {
1572 	metaslab_free(zio->io_spa, zio->io_bp, zio->io_txg, B_FALSE);
1573 
1574 	return (ZIO_PIPELINE_CONTINUE);
1575 }
1576 
1577 static int
1578 zio_dva_claim(zio_t *zio)
1579 {
1580 	int error;
1581 
1582 	error = metaslab_claim(zio->io_spa, zio->io_bp, zio->io_txg);
1583 	if (error)
1584 		zio->io_error = error;
1585 
1586 	return (ZIO_PIPELINE_CONTINUE);
1587 }
1588 
1589 /*
1590  * Undo an allocation.  This is used by zio_done() when an I/O fails
1591  * and we want to give back the block we just allocated.
1592  * This handles both normal blocks and gang blocks.
1593  */
1594 static void
1595 zio_dva_unallocate(zio_t *zio, zio_gang_node_t *gn, blkptr_t *bp)
1596 {
1597 	spa_t *spa = zio->io_spa;
1598 	boolean_t now = !(zio->io_flags & ZIO_FLAG_IO_REWRITE);
1599 
1600 	ASSERT(bp->blk_birth == zio->io_txg || BP_IS_HOLE(bp));
1601 
1602 	if (zio->io_bp == bp && !now) {
1603 		/*
1604 		 * This is a rewrite for sync-to-convergence.
1605 		 * We can't do a metaslab_free(NOW) because bp wasn't allocated
1606 		 * during this sync pass, which means that metaslab_sync()
1607 		 * already committed the allocation.
1608 		 */
1609 		ASSERT(DVA_EQUAL(BP_IDENTITY(bp),
1610 		    BP_IDENTITY(&zio->io_bp_orig)));
1611 		ASSERT(spa_sync_pass(spa) > 1);
1612 
1613 		if (BP_IS_GANG(bp) && gn == NULL) {
1614 			/*
1615 			 * This is a gang leader whose gang header(s) we
1616 			 * couldn't read now, so defer the free until later.
1617 			 * The block should still be intact because without
1618 			 * the headers, we'd never even start the rewrite.
1619 			 */
1620 			bplist_enqueue_deferred(&spa->spa_sync_bplist, bp);
1621 			return;
1622 		}
1623 	}
1624 
1625 	if (!BP_IS_HOLE(bp))
1626 		metaslab_free(spa, bp, bp->blk_birth, now);
1627 
1628 	if (gn != NULL) {
1629 		for (int g = 0; g < SPA_GBH_NBLKPTRS; g++) {
1630 			zio_dva_unallocate(zio, gn->gn_child[g],
1631 			    &gn->gn_gbh->zg_blkptr[g]);
1632 		}
1633 	}
1634 }
1635 
1636 /*
1637  * Try to allocate an intent log block.  Return 0 on success, errno on failure.
1638  */
1639 int
1640 zio_alloc_blk(spa_t *spa, uint64_t size, blkptr_t *new_bp, blkptr_t *old_bp,
1641     uint64_t txg)
1642 {
1643 	int error;
1644 
1645 	error = metaslab_alloc(spa, spa->spa_log_class, size,
1646 	    new_bp, 1, txg, old_bp, METASLAB_HINTBP_AVOID);
1647 
1648 	if (error)
1649 		error = metaslab_alloc(spa, spa->spa_normal_class, size,
1650 		    new_bp, 1, txg, old_bp, METASLAB_HINTBP_AVOID);
1651 
1652 	if (error == 0) {
1653 		BP_SET_LSIZE(new_bp, size);
1654 		BP_SET_PSIZE(new_bp, size);
1655 		BP_SET_COMPRESS(new_bp, ZIO_COMPRESS_OFF);
1656 		BP_SET_CHECKSUM(new_bp, ZIO_CHECKSUM_ZILOG);
1657 		BP_SET_TYPE(new_bp, DMU_OT_INTENT_LOG);
1658 		BP_SET_LEVEL(new_bp, 0);
1659 		BP_SET_BYTEORDER(new_bp, ZFS_HOST_BYTEORDER);
1660 	}
1661 
1662 	return (error);
1663 }
1664 
1665 /*
1666  * Free an intent log block.  We know it can't be a gang block, so there's
1667  * nothing to do except metaslab_free() it.
1668  */
1669 void
1670 zio_free_blk(spa_t *spa, blkptr_t *bp, uint64_t txg)
1671 {
1672 	ASSERT(!BP_IS_GANG(bp));
1673 
1674 	metaslab_free(spa, bp, txg, B_FALSE);
1675 }
1676 
1677 /*
1678  * ==========================================================================
1679  * Read and write to physical devices
1680  * ==========================================================================
1681  */
1682 
1683 static void
1684 zio_vdev_io_probe_done(zio_t *zio)
1685 {
1686 	zio_t *dio;
1687 	vdev_t *vd = zio->io_private;
1688 
1689 	mutex_enter(&vd->vdev_probe_lock);
1690 	ASSERT(vd->vdev_probe_zio == zio);
1691 	vd->vdev_probe_zio = NULL;
1692 	mutex_exit(&vd->vdev_probe_lock);
1693 
1694 	while ((dio = zio->io_delegate_list) != NULL) {
1695 		zio->io_delegate_list = dio->io_delegate_next;
1696 		dio->io_delegate_next = NULL;
1697 		if (!vdev_accessible(vd, dio))
1698 			dio->io_error = ENXIO;
1699 		zio_execute(dio);
1700 	}
1701 }
1702 
1703 /*
1704  * Probe the device to determine whether I/O failure is specific to this
1705  * zio (e.g. a bad sector) or affects the entire vdev (e.g. unplugged).
1706  */
1707 static int
1708 zio_vdev_io_probe(zio_t *zio)
1709 {
1710 	vdev_t *vd = zio->io_vd;
1711 	zio_t *pio = NULL;
1712 	boolean_t created_pio = B_FALSE;
1713 
1714 	/*
1715 	 * Don't probe the probe.
1716 	 */
1717 	if (zio->io_flags & ZIO_FLAG_PROBE)
1718 		return (ZIO_PIPELINE_CONTINUE);
1719 
1720 	/*
1721 	 * To prevent 'probe storms' when a device fails, we create
1722 	 * just one probe i/o at a time.  All zios that want to probe
1723 	 * this vdev will join the probe zio's io_delegate_list.
1724 	 */
1725 	mutex_enter(&vd->vdev_probe_lock);
1726 
1727 	if ((pio = vd->vdev_probe_zio) == NULL) {
1728 		vd->vdev_probe_zio = pio = zio_root(zio->io_spa,
1729 		    zio_vdev_io_probe_done, vd, ZIO_FLAG_CANFAIL);
1730 		created_pio = B_TRUE;
1731 		vd->vdev_probe_wanted = B_TRUE;
1732 		spa_async_request(zio->io_spa, SPA_ASYNC_PROBE);
1733 	}
1734 
1735 	zio->io_delegate_next = pio->io_delegate_list;
1736 	pio->io_delegate_list = zio;
1737 
1738 	mutex_exit(&vd->vdev_probe_lock);
1739 
1740 	if (created_pio) {
1741 		zio_nowait(vdev_probe(vd, pio));
1742 		zio_nowait(pio);
1743 	}
1744 
1745 	return (ZIO_PIPELINE_STOP);
1746 }
1747 
1748 static int
1749 zio_vdev_io_start(zio_t *zio)
1750 {
1751 	vdev_t *vd = zio->io_vd;
1752 	uint64_t align;
1753 	spa_t *spa = zio->io_spa;
1754 
1755 	ASSERT(zio->io_error == 0);
1756 	ASSERT(zio->io_child_error[ZIO_CHILD_VDEV] == 0);
1757 
1758 	if (vd == NULL) {
1759 		if (!(zio->io_flags & ZIO_FLAG_CONFIG_WRITER))
1760 			spa_config_enter(spa, SCL_ZIO, zio, RW_READER);
1761 
1762 		/*
1763 		 * The mirror_ops handle multiple DVAs in a single BP.
1764 		 */
1765 		return (vdev_mirror_ops.vdev_op_io_start(zio));
1766 	}
1767 
1768 	align = 1ULL << vd->vdev_top->vdev_ashift;
1769 
1770 	if (P2PHASE(zio->io_size, align) != 0) {
1771 		uint64_t asize = P2ROUNDUP(zio->io_size, align);
1772 		char *abuf = zio_buf_alloc(asize);
1773 		ASSERT(vd == vd->vdev_top);
1774 		if (zio->io_type == ZIO_TYPE_WRITE) {
1775 			bcopy(zio->io_data, abuf, zio->io_size);
1776 			bzero(abuf + zio->io_size, asize - zio->io_size);
1777 		}
1778 		zio_push_transform(zio, abuf, asize, asize, zio_subblock);
1779 	}
1780 
1781 	ASSERT(P2PHASE(zio->io_offset, align) == 0);
1782 	ASSERT(P2PHASE(zio->io_size, align) == 0);
1783 	ASSERT(zio->io_type != ZIO_TYPE_WRITE || (spa_mode & FWRITE));
1784 
1785 	if (vd->vdev_ops->vdev_op_leaf &&
1786 	    (zio->io_type == ZIO_TYPE_READ || zio->io_type == ZIO_TYPE_WRITE)) {
1787 
1788 		if (zio->io_type == ZIO_TYPE_READ && vdev_cache_read(zio) == 0)
1789 			return (ZIO_PIPELINE_STOP);
1790 
1791 		if ((zio = vdev_queue_io(zio)) == NULL)
1792 			return (ZIO_PIPELINE_STOP);
1793 
1794 		if (!vdev_accessible(vd, zio)) {
1795 			zio->io_error = ENXIO;
1796 			zio_interrupt(zio);
1797 			return (ZIO_PIPELINE_STOP);
1798 		}
1799 
1800 	}
1801 
1802 	return (vd->vdev_ops->vdev_op_io_start(zio));
1803 }
1804 
1805 static int
1806 zio_vdev_io_done(zio_t *zio)
1807 {
1808 	vdev_t *vd = zio->io_vd;
1809 	vdev_ops_t *ops = vd ? vd->vdev_ops : &vdev_mirror_ops;
1810 	boolean_t unexpected_error = B_FALSE;
1811 
1812 	if (zio_wait_for_children(zio, ZIO_CHILD_VDEV, ZIO_WAIT_DONE))
1813 		return (ZIO_PIPELINE_STOP);
1814 
1815 	ASSERT(zio->io_type == ZIO_TYPE_READ || zio->io_type == ZIO_TYPE_WRITE);
1816 
1817 	if (vd != NULL && vd->vdev_ops->vdev_op_leaf) {
1818 
1819 		vdev_queue_io_done(zio);
1820 
1821 		if (zio->io_type == ZIO_TYPE_WRITE)
1822 			vdev_cache_write(zio);
1823 
1824 		if (zio_injection_enabled && zio->io_error == 0)
1825 			zio->io_error = zio_handle_device_injection(vd, EIO);
1826 
1827 		if (zio_injection_enabled && zio->io_error == 0)
1828 			zio->io_error = zio_handle_label_injection(zio, EIO);
1829 
1830 		if (zio->io_error) {
1831 			if (!vdev_accessible(vd, zio)) {
1832 				zio->io_error = ENXIO;
1833 			} else {
1834 				unexpected_error = B_TRUE;
1835 			}
1836 		}
1837 	}
1838 
1839 	ops->vdev_op_io_done(zio);
1840 
1841 	if (unexpected_error)
1842 		return (zio_vdev_io_probe(zio));
1843 
1844 	return (ZIO_PIPELINE_CONTINUE);
1845 }
1846 
1847 static int
1848 zio_vdev_io_assess(zio_t *zio)
1849 {
1850 	vdev_t *vd = zio->io_vd;
1851 
1852 	if (zio_wait_for_children(zio, ZIO_CHILD_VDEV, ZIO_WAIT_DONE))
1853 		return (ZIO_PIPELINE_STOP);
1854 
1855 	if (vd == NULL && !(zio->io_flags & ZIO_FLAG_CONFIG_WRITER))
1856 		spa_config_exit(zio->io_spa, SCL_ZIO, zio);
1857 
1858 	if (zio->io_vsd != NULL) {
1859 		zio->io_vsd_free(zio);
1860 		zio->io_vsd = NULL;
1861 	}
1862 
1863 	if (zio_injection_enabled && zio->io_error == 0)
1864 		zio->io_error = zio_handle_fault_injection(zio, EIO);
1865 
1866 	/*
1867 	 * If the I/O failed, determine whether we should attempt to retry it.
1868 	 */
1869 	if (zio->io_error && vd == NULL &&
1870 	    !(zio->io_flags & (ZIO_FLAG_DONT_RETRY | ZIO_FLAG_IO_RETRY))) {
1871 		ASSERT(!(zio->io_flags & ZIO_FLAG_DONT_QUEUE));	/* not a leaf */
1872 		ASSERT(!(zio->io_flags & ZIO_FLAG_IO_BYPASS));	/* not a leaf */
1873 		zio->io_error = 0;
1874 		zio->io_flags |= ZIO_FLAG_IO_RETRY |
1875 		    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_AGGREGATE;
1876 		zio->io_stage = ZIO_STAGE_VDEV_IO_START - 1;
1877 		zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE);
1878 		return (ZIO_PIPELINE_STOP);
1879 	}
1880 
1881 	/*
1882 	 * If we got an error on a leaf device, convert it to ENXIO
1883 	 * if the device is not accessible at all.
1884 	 */
1885 	if (zio->io_error && vd != NULL && vd->vdev_ops->vdev_op_leaf &&
1886 	    !vdev_accessible(vd, zio))
1887 		zio->io_error = ENXIO;
1888 
1889 	/*
1890 	 * If we can't write to an interior vdev (mirror or RAID-Z),
1891 	 * set vdev_cant_write so that we stop trying to allocate from it.
1892 	 */
1893 	if (zio->io_error == ENXIO && zio->io_type == ZIO_TYPE_WRITE &&
1894 	    vd != NULL && !vd->vdev_ops->vdev_op_leaf)
1895 		vd->vdev_cant_write = B_TRUE;
1896 
1897 	if (zio->io_error)
1898 		zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1899 
1900 	return (ZIO_PIPELINE_CONTINUE);
1901 }
1902 
1903 void
1904 zio_vdev_io_reissue(zio_t *zio)
1905 {
1906 	ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_START);
1907 	ASSERT(zio->io_error == 0);
1908 
1909 	zio->io_stage--;
1910 }
1911 
1912 void
1913 zio_vdev_io_redone(zio_t *zio)
1914 {
1915 	ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_DONE);
1916 
1917 	zio->io_stage--;
1918 }
1919 
1920 void
1921 zio_vdev_io_bypass(zio_t *zio)
1922 {
1923 	ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_START);
1924 	ASSERT(zio->io_error == 0);
1925 
1926 	zio->io_flags |= ZIO_FLAG_IO_BYPASS;
1927 	zio->io_stage = ZIO_STAGE_VDEV_IO_ASSESS - 1;
1928 }
1929 
1930 /*
1931  * ==========================================================================
1932  * Generate and verify checksums
1933  * ==========================================================================
1934  */
1935 static int
1936 zio_checksum_generate(zio_t *zio)
1937 {
1938 	blkptr_t *bp = zio->io_bp;
1939 	enum zio_checksum checksum;
1940 
1941 	if (bp == NULL) {
1942 		/*
1943 		 * This is zio_write_phys().
1944 		 * We're either generating a label checksum, or none at all.
1945 		 */
1946 		checksum = zio->io_prop.zp_checksum;
1947 
1948 		if (checksum == ZIO_CHECKSUM_OFF)
1949 			return (ZIO_PIPELINE_CONTINUE);
1950 
1951 		ASSERT(checksum == ZIO_CHECKSUM_LABEL);
1952 	} else {
1953 		if (BP_IS_GANG(bp) && zio->io_child_type == ZIO_CHILD_GANG) {
1954 			ASSERT(!IO_IS_ALLOCATING(zio));
1955 			checksum = ZIO_CHECKSUM_GANG_HEADER;
1956 		} else {
1957 			checksum = BP_GET_CHECKSUM(bp);
1958 		}
1959 	}
1960 
1961 	zio_checksum_compute(zio, checksum, zio->io_data, zio->io_size);
1962 
1963 	return (ZIO_PIPELINE_CONTINUE);
1964 }
1965 
1966 static int
1967 zio_checksum_verify(zio_t *zio)
1968 {
1969 	blkptr_t *bp = zio->io_bp;
1970 	int error;
1971 
1972 	if (bp == NULL) {
1973 		/*
1974 		 * This is zio_read_phys().
1975 		 * We're either verifying a label checksum, or nothing at all.
1976 		 */
1977 		if (zio->io_prop.zp_checksum == ZIO_CHECKSUM_OFF)
1978 			return (ZIO_PIPELINE_CONTINUE);
1979 
1980 		ASSERT(zio->io_prop.zp_checksum == ZIO_CHECKSUM_LABEL);
1981 	}
1982 
1983 	if ((error = zio_checksum_error(zio)) != 0) {
1984 		zio->io_error = error;
1985 		if (!(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
1986 			zfs_ereport_post(FM_EREPORT_ZFS_CHECKSUM,
1987 			    zio->io_spa, zio->io_vd, zio, 0, 0);
1988 		}
1989 	}
1990 
1991 	return (ZIO_PIPELINE_CONTINUE);
1992 }
1993 
1994 /*
1995  * Called by RAID-Z to ensure we don't compute the checksum twice.
1996  */
1997 void
1998 zio_checksum_verified(zio_t *zio)
1999 {
2000 	zio->io_pipeline &= ~(1U << ZIO_STAGE_CHECKSUM_VERIFY);
2001 }
2002 
2003 /*
2004  * ==========================================================================
2005  * Error rank.  Error are ranked in the order 0, ENXIO, ECKSUM, EIO, other.
2006  * An error of 0 indictes success.  ENXIO indicates whole-device failure,
2007  * which may be transient (e.g. unplugged) or permament.  ECKSUM and EIO
2008  * indicate errors that are specific to one I/O, and most likely permanent.
2009  * Any other error is presumed to be worse because we weren't expecting it.
2010  * ==========================================================================
2011  */
2012 int
2013 zio_worst_error(int e1, int e2)
2014 {
2015 	static int zio_error_rank[] = { 0, ENXIO, ECKSUM, EIO };
2016 	int r1, r2;
2017 
2018 	for (r1 = 0; r1 < sizeof (zio_error_rank) / sizeof (int); r1++)
2019 		if (e1 == zio_error_rank[r1])
2020 			break;
2021 
2022 	for (r2 = 0; r2 < sizeof (zio_error_rank) / sizeof (int); r2++)
2023 		if (e2 == zio_error_rank[r2])
2024 			break;
2025 
2026 	return (r1 > r2 ? e1 : e2);
2027 }
2028 
2029 /*
2030  * ==========================================================================
2031  * I/O completion
2032  * ==========================================================================
2033  */
2034 static int
2035 zio_ready(zio_t *zio)
2036 {
2037 	blkptr_t *bp = zio->io_bp;
2038 	zio_t *pio = zio->io_parent;
2039 
2040 	if (zio->io_ready) {
2041 		if (BP_IS_GANG(bp) &&
2042 		    zio_wait_for_children(zio, ZIO_CHILD_GANG, ZIO_WAIT_READY))
2043 			return (ZIO_PIPELINE_STOP);
2044 
2045 		ASSERT(IO_IS_ALLOCATING(zio));
2046 		ASSERT(bp->blk_birth == zio->io_txg || BP_IS_HOLE(bp));
2047 		ASSERT(zio->io_children[ZIO_CHILD_GANG][ZIO_WAIT_READY] == 0);
2048 
2049 		zio->io_ready(zio);
2050 	}
2051 
2052 	if (bp != NULL && bp != &zio->io_bp_copy)
2053 		zio->io_bp_copy = *bp;
2054 
2055 	if (zio->io_error)
2056 		zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
2057 
2058 	if (pio != NULL)
2059 		zio_notify_parent(pio, zio, ZIO_WAIT_READY);
2060 
2061 	return (ZIO_PIPELINE_CONTINUE);
2062 }
2063 
2064 static int
2065 zio_done(zio_t *zio)
2066 {
2067 	spa_t *spa = zio->io_spa;
2068 	zio_t *pio = zio->io_parent;
2069 	zio_t *lio = zio->io_logical;
2070 	blkptr_t *bp = zio->io_bp;
2071 	vdev_t *vd = zio->io_vd;
2072 	uint64_t psize = zio->io_size;
2073 
2074 	/*
2075 	 * If our of children haven't all completed,
2076 	 * wait for them and then repeat this pipeline stage.
2077 	 */
2078 	if (zio_wait_for_children(zio, ZIO_CHILD_VDEV, ZIO_WAIT_DONE) ||
2079 	    zio_wait_for_children(zio, ZIO_CHILD_GANG, ZIO_WAIT_DONE) ||
2080 	    zio_wait_for_children(zio, ZIO_CHILD_LOGICAL, ZIO_WAIT_DONE))
2081 		return (ZIO_PIPELINE_STOP);
2082 
2083 	for (int c = 0; c < ZIO_CHILD_TYPES; c++)
2084 		for (int w = 0; w < ZIO_WAIT_TYPES; w++)
2085 			ASSERT(zio->io_children[c][w] == 0);
2086 
2087 	if (bp != NULL) {
2088 		ASSERT(bp->blk_pad[0] == 0);
2089 		ASSERT(bp->blk_pad[1] == 0);
2090 		ASSERT(bp->blk_pad[2] == 0);
2091 		ASSERT(bcmp(bp, &zio->io_bp_copy, sizeof (blkptr_t)) == 0 ||
2092 		    (pio != NULL && bp == pio->io_bp));
2093 		if (zio->io_type == ZIO_TYPE_WRITE && !BP_IS_HOLE(bp) &&
2094 		    !(zio->io_flags & ZIO_FLAG_IO_REPAIR)) {
2095 			ASSERT(!BP_SHOULD_BYTESWAP(bp));
2096 			ASSERT3U(zio->io_prop.zp_ndvas, <=, BP_GET_NDVAS(bp));
2097 			ASSERT(BP_COUNT_GANG(bp) == 0 ||
2098 			    (BP_COUNT_GANG(bp) == BP_GET_NDVAS(bp)));
2099 		}
2100 	}
2101 
2102 	/*
2103 	 * If there were child vdev or gang errors, they apply to us now.
2104 	 */
2105 	zio_inherit_child_errors(zio, ZIO_CHILD_VDEV);
2106 	zio_inherit_child_errors(zio, ZIO_CHILD_GANG);
2107 
2108 	zio_pop_transforms(zio);	/* note: may set zio->io_error */
2109 
2110 	vdev_stat_update(zio, psize);
2111 
2112 	if (zio->io_error) {
2113 		/*
2114 		 * If this I/O is attached to a particular vdev,
2115 		 * generate an error message describing the I/O failure
2116 		 * at the block level.  We ignore these errors if the
2117 		 * device is currently unavailable.
2118 		 */
2119 		if (zio->io_error != ECKSUM && vd != NULL && !vdev_is_dead(vd))
2120 			zfs_ereport_post(FM_EREPORT_ZFS_IO, spa, vd, zio, 0, 0);
2121 
2122 		if ((zio->io_error == EIO ||
2123 		    !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) && zio == lio) {
2124 			/*
2125 			 * For logical I/O requests, tell the SPA to log the
2126 			 * error and generate a logical data ereport.
2127 			 */
2128 			spa_log_error(spa, zio);
2129 			zfs_ereport_post(FM_EREPORT_ZFS_DATA, spa, NULL, zio,
2130 			    0, 0);
2131 		}
2132 	}
2133 
2134 	if (zio->io_error && zio == lio) {
2135 		/*
2136 		 * Determine whether zio should be reexecuted.  This will
2137 		 * propagate all the way to the root via zio_notify_parent().
2138 		 */
2139 		ASSERT(vd == NULL && bp != NULL);
2140 
2141 		if (IO_IS_ALLOCATING(zio))
2142 			if (zio->io_error != ENOSPC)
2143 				zio->io_reexecute |= ZIO_REEXECUTE_NOW;
2144 			else
2145 				zio->io_reexecute |= ZIO_REEXECUTE_SUSPEND;
2146 
2147 		if ((zio->io_type == ZIO_TYPE_READ ||
2148 		    zio->io_type == ZIO_TYPE_FREE) &&
2149 		    zio->io_error == ENXIO &&
2150 		    spa_get_failmode(spa) != ZIO_FAILURE_MODE_CONTINUE)
2151 			zio->io_reexecute |= ZIO_REEXECUTE_SUSPEND;
2152 
2153 		if (!(zio->io_flags & ZIO_FLAG_CANFAIL) && !zio->io_reexecute)
2154 			zio->io_reexecute |= ZIO_REEXECUTE_SUSPEND;
2155 	}
2156 
2157 	/*
2158 	 * If there were logical child errors, they apply to us now.
2159 	 * We defer this until now to avoid conflating logical child
2160 	 * errors with errors that happened to the zio itself when
2161 	 * updating vdev stats and reporting FMA events above.
2162 	 */
2163 	zio_inherit_child_errors(zio, ZIO_CHILD_LOGICAL);
2164 
2165 	if (zio->io_reexecute) {
2166 		/*
2167 		 * This is a logical I/O that wants to reexecute.
2168 		 *
2169 		 * Reexecute is top-down.  When an i/o fails, if it's not
2170 		 * the root, it simply notifies its parent and sticks around.
2171 		 * The parent, seeing that it still has children in zio_done(),
2172 		 * does the same.  This percolates all the way up to the root.
2173 		 * The root i/o will reexecute or suspend the entire tree.
2174 		 *
2175 		 * This approach ensures that zio_reexecute() honors
2176 		 * all the original i/o dependency relationships, e.g.
2177 		 * parents not executing until children are ready.
2178 		 */
2179 		ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
2180 
2181 		if (IO_IS_ALLOCATING(zio))
2182 			zio_dva_unallocate(zio, zio->io_gang_tree, bp);
2183 
2184 		zio_gang_tree_free(&zio->io_gang_tree);
2185 
2186 		if (pio != NULL) {
2187 			/*
2188 			 * We're not a root i/o, so there's nothing to do
2189 			 * but notify our parent.  Don't propagate errors
2190 			 * upward since we haven't permanently failed yet.
2191 			 */
2192 			zio->io_flags |= ZIO_FLAG_DONT_PROPAGATE;
2193 			zio_notify_parent(pio, zio, ZIO_WAIT_DONE);
2194 		} else if (zio->io_reexecute & ZIO_REEXECUTE_SUSPEND) {
2195 			/*
2196 			 * We'd fail again if we reexecuted now, so suspend
2197 			 * until conditions improve (e.g. device comes online).
2198 			 */
2199 			zio_suspend(spa, zio);
2200 		} else {
2201 			/*
2202 			 * Reexecution is potentially a huge amount of work.
2203 			 * Hand it off to the otherwise-unused claim taskq.
2204 			 */
2205 			(void) taskq_dispatch(
2206 			    spa->spa_zio_taskq[ZIO_TYPE_CLAIM][ZIO_TASKQ_ISSUE],
2207 			    (task_func_t *)zio_reexecute, zio, TQ_SLEEP);
2208 		}
2209 		return (ZIO_PIPELINE_STOP);
2210 	}
2211 
2212 	ASSERT(zio->io_child == NULL);
2213 	ASSERT(zio->io_reexecute == 0);
2214 	ASSERT(zio->io_error == 0 || (zio->io_flags & ZIO_FLAG_CANFAIL));
2215 
2216 	if (zio->io_done)
2217 		zio->io_done(zio);
2218 
2219 	zio_gang_tree_free(&zio->io_gang_tree);
2220 
2221 	ASSERT(zio->io_delegate_list == NULL);
2222 	ASSERT(zio->io_delegate_next == NULL);
2223 
2224 	if (pio != NULL) {
2225 		zio_remove_child(pio, zio);
2226 		zio_notify_parent(pio, zio, ZIO_WAIT_DONE);
2227 	}
2228 
2229 	if (zio->io_waiter != NULL) {
2230 		mutex_enter(&zio->io_lock);
2231 		zio->io_executor = NULL;
2232 		cv_broadcast(&zio->io_cv);
2233 		mutex_exit(&zio->io_lock);
2234 	} else {
2235 		zio_destroy(zio);
2236 	}
2237 
2238 	return (ZIO_PIPELINE_STOP);
2239 }
2240 
2241 /*
2242  * ==========================================================================
2243  * I/O pipeline definition
2244  * ==========================================================================
2245  */
2246 static zio_pipe_stage_t *zio_pipeline[ZIO_STAGES] = {
2247 	NULL,
2248 	zio_issue_async,
2249 	zio_read_bp_init,
2250 	zio_write_bp_init,
2251 	zio_checksum_generate,
2252 	zio_gang_assemble,
2253 	zio_gang_issue,
2254 	zio_dva_allocate,
2255 	zio_dva_free,
2256 	zio_dva_claim,
2257 	zio_ready,
2258 	zio_vdev_io_start,
2259 	zio_vdev_io_done,
2260 	zio_vdev_io_assess,
2261 	zio_checksum_verify,
2262 	zio_done
2263 };
2264