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