xref: /illumos-gate/usr/src/uts/common/fs/zfs/zio.c (revision 1f7ad2e1275fff503991bf4b43bc5cf1d815669f)
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 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #include <sys/zfs_context.h>
29 #include <sys/fm/fs/zfs.h>
30 #include <sys/spa.h>
31 #include <sys/txg.h>
32 #include <sys/spa_impl.h>
33 #include <sys/vdev_impl.h>
34 #include <sys/zio_impl.h>
35 #include <sys/zio_compress.h>
36 #include <sys/zio_checksum.h>
37 
38 /*
39  * ==========================================================================
40  * I/O priority table
41  * ==========================================================================
42  */
43 uint8_t zio_priority_table[ZIO_PRIORITY_TABLE_SIZE] = {
44 	0,	/* ZIO_PRIORITY_NOW		*/
45 	0,	/* ZIO_PRIORITY_SYNC_READ	*/
46 	0,	/* ZIO_PRIORITY_SYNC_WRITE	*/
47 	6,	/* ZIO_PRIORITY_ASYNC_READ	*/
48 	4,	/* ZIO_PRIORITY_ASYNC_WRITE	*/
49 	4,	/* ZIO_PRIORITY_FREE		*/
50 	0,	/* ZIO_PRIORITY_CACHE_FILL	*/
51 	0,	/* ZIO_PRIORITY_LOG_WRITE	*/
52 	10,	/* ZIO_PRIORITY_RESILVER	*/
53 	20,	/* ZIO_PRIORITY_SCRUB		*/
54 };
55 
56 /*
57  * ==========================================================================
58  * I/O type descriptions
59  * ==========================================================================
60  */
61 char *zio_type_name[ZIO_TYPES] = {
62 	"null", "read", "write", "free", "claim", "ioctl" };
63 
64 /* At or above this size, force gang blocking - for testing */
65 uint64_t zio_gang_bang = SPA_MAXBLOCKSIZE + 1;
66 
67 /* Force an allocation failure when non-zero */
68 uint16_t zio_zil_fail_shift = 0;
69 uint16_t zio_io_fail_shift = 0;
70 
71 /* Enable/disable the write-retry logic */
72 int zio_write_retry = 1;
73 
74 /* Taskq to handle reissuing of I/Os */
75 taskq_t *zio_taskq;
76 int zio_resume_threads = 4;
77 
78 typedef struct zio_sync_pass {
79 	int	zp_defer_free;		/* defer frees after this pass */
80 	int	zp_dontcompress;	/* don't compress after this pass */
81 	int	zp_rewrite;		/* rewrite new bps after this pass */
82 } zio_sync_pass_t;
83 
84 zio_sync_pass_t zio_sync_pass = {
85 	1,	/* zp_defer_free */
86 	4,	/* zp_dontcompress */
87 	1,	/* zp_rewrite */
88 };
89 
90 static boolean_t zio_io_should_fail(uint16_t);
91 
92 /*
93  * ==========================================================================
94  * I/O kmem caches
95  * ==========================================================================
96  */
97 kmem_cache_t *zio_cache;
98 kmem_cache_t *zio_buf_cache[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT];
99 kmem_cache_t *zio_data_buf_cache[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT];
100 
101 #ifdef _KERNEL
102 extern vmem_t *zio_alloc_arena;
103 #endif
104 
105 /*
106  * Determine if we are allowed to issue the IO based on the
107  * pool state. If we must wait then block until we are told
108  * that we may continue.
109  */
110 #define	ZIO_ENTER(spa) {						\
111 	if (spa->spa_state == POOL_STATE_IO_FAILURE) {			\
112 		mutex_enter(&spa->spa_zio_lock);			\
113 		while (spa->spa_state == POOL_STATE_IO_FAILURE)		\
114 			cv_wait(&spa->spa_zio_cv, &spa->spa_zio_lock);	\
115 		mutex_exit(&spa->spa_zio_lock);				\
116 	}								\
117 }
118 
119 /*
120  * An allocation zio is one that either currently has the DVA allocate
121  * stage set or will have it later in it's lifetime.
122  */
123 #define	IO_IS_ALLOCATING(zio) \
124 	((zio)->io_orig_pipeline == ZIO_WRITE_PIPELINE ||		\
125 	(zio)->io_pipeline & (1U << ZIO_STAGE_DVA_ALLOCATE))
126 
127 /*
128  * The only way to tell is by looking for the gang pipeline stage
129  */
130 #define	IO_IS_REWRITE(zio)						\
131 	((zio)->io_pipeline & (1U << ZIO_STAGE_GANG_PIPELINE))
132 
133 void
134 zio_init(void)
135 {
136 	size_t c;
137 	vmem_t *data_alloc_arena = NULL;
138 
139 #ifdef _KERNEL
140 	data_alloc_arena = zio_alloc_arena;
141 #endif
142 
143 	zio_cache = kmem_cache_create("zio_cache", sizeof (zio_t), 0,
144 	    NULL, NULL, NULL, NULL, NULL, 0);
145 
146 	/*
147 	 * For small buffers, we want a cache for each multiple of
148 	 * SPA_MINBLOCKSIZE.  For medium-size buffers, we want a cache
149 	 * for each quarter-power of 2.  For large buffers, we want
150 	 * a cache for each multiple of PAGESIZE.
151 	 */
152 	for (c = 0; c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; c++) {
153 		size_t size = (c + 1) << SPA_MINBLOCKSHIFT;
154 		size_t p2 = size;
155 		size_t align = 0;
156 
157 		while (p2 & (p2 - 1))
158 			p2 &= p2 - 1;
159 
160 		if (size <= 4 * SPA_MINBLOCKSIZE) {
161 			align = SPA_MINBLOCKSIZE;
162 		} else if (P2PHASE(size, PAGESIZE) == 0) {
163 			align = PAGESIZE;
164 		} else if (P2PHASE(size, p2 >> 2) == 0) {
165 			align = p2 >> 2;
166 		}
167 
168 		if (align != 0) {
169 			char name[36];
170 			(void) sprintf(name, "zio_buf_%lu", (ulong_t)size);
171 			zio_buf_cache[c] = kmem_cache_create(name, size,
172 			    align, NULL, NULL, NULL, NULL, NULL, KMC_NODEBUG);
173 
174 			(void) sprintf(name, "zio_data_buf_%lu", (ulong_t)size);
175 			zio_data_buf_cache[c] = kmem_cache_create(name, size,
176 			    align, NULL, NULL, NULL, NULL, data_alloc_arena,
177 			    KMC_NODEBUG);
178 
179 			dprintf("creating cache for size %5lx align %5lx\n",
180 			    size, align);
181 		}
182 	}
183 
184 	while (--c != 0) {
185 		ASSERT(zio_buf_cache[c] != NULL);
186 		if (zio_buf_cache[c - 1] == NULL)
187 			zio_buf_cache[c - 1] = zio_buf_cache[c];
188 
189 		ASSERT(zio_data_buf_cache[c] != NULL);
190 		if (zio_data_buf_cache[c - 1] == NULL)
191 			zio_data_buf_cache[c - 1] = zio_data_buf_cache[c];
192 	}
193 
194 	zio_taskq = taskq_create("zio_taskq", zio_resume_threads,
195 	    maxclsyspri, 50, INT_MAX, TASKQ_PREPOPULATE);
196 
197 	zio_inject_init();
198 }
199 
200 void
201 zio_fini(void)
202 {
203 	size_t c;
204 	kmem_cache_t *last_cache = NULL;
205 	kmem_cache_t *last_data_cache = NULL;
206 
207 	for (c = 0; c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; c++) {
208 		if (zio_buf_cache[c] != last_cache) {
209 			last_cache = zio_buf_cache[c];
210 			kmem_cache_destroy(zio_buf_cache[c]);
211 		}
212 		zio_buf_cache[c] = NULL;
213 
214 		if (zio_data_buf_cache[c] != last_data_cache) {
215 			last_data_cache = zio_data_buf_cache[c];
216 			kmem_cache_destroy(zio_data_buf_cache[c]);
217 		}
218 		zio_data_buf_cache[c] = NULL;
219 	}
220 
221 	taskq_destroy(zio_taskq);
222 
223 	kmem_cache_destroy(zio_cache);
224 
225 	zio_inject_fini();
226 }
227 
228 /*
229  * ==========================================================================
230  * Allocate and free I/O buffers
231  * ==========================================================================
232  */
233 
234 /*
235  * Use zio_buf_alloc to allocate ZFS metadata.  This data will appear in a
236  * crashdump if the kernel panics, so use it judiciously.  Obviously, it's
237  * useful to inspect ZFS metadata, but if possible, we should avoid keeping
238  * excess / transient data in-core during a crashdump.
239  */
240 void *
241 zio_buf_alloc(size_t size)
242 {
243 	size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
244 
245 	ASSERT(c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
246 
247 	return (kmem_cache_alloc(zio_buf_cache[c], KM_SLEEP));
248 }
249 
250 /*
251  * Use zio_data_buf_alloc to allocate data.  The data will not appear in a
252  * crashdump if the kernel panics.  This exists so that we will limit the amount
253  * of ZFS data that shows up in a kernel crashdump.  (Thus reducing the amount
254  * of kernel heap dumped to disk when the kernel panics)
255  */
256 void *
257 zio_data_buf_alloc(size_t size)
258 {
259 	size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
260 
261 	ASSERT(c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
262 
263 	return (kmem_cache_alloc(zio_data_buf_cache[c], KM_SLEEP));
264 }
265 
266 void
267 zio_buf_free(void *buf, size_t size)
268 {
269 	size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
270 
271 	ASSERT(c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
272 
273 	kmem_cache_free(zio_buf_cache[c], buf);
274 }
275 
276 void
277 zio_data_buf_free(void *buf, size_t size)
278 {
279 	size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
280 
281 	ASSERT(c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
282 
283 	kmem_cache_free(zio_data_buf_cache[c], buf);
284 }
285 
286 /*
287  * ==========================================================================
288  * Push and pop I/O transform buffers
289  * ==========================================================================
290  */
291 static void
292 zio_push_transform(zio_t *zio, void *data, uint64_t size, uint64_t bufsize)
293 {
294 	zio_transform_t *zt = kmem_alloc(sizeof (zio_transform_t), KM_SLEEP);
295 
296 	zt->zt_data = data;
297 	zt->zt_size = size;
298 	zt->zt_bufsize = bufsize;
299 
300 	zt->zt_next = zio->io_transform_stack;
301 	zio->io_transform_stack = zt;
302 
303 	zio->io_data = data;
304 	zio->io_size = size;
305 }
306 
307 static void
308 zio_pop_transform(zio_t *zio, void **data, uint64_t *size, uint64_t *bufsize)
309 {
310 	zio_transform_t *zt = zio->io_transform_stack;
311 
312 	*data = zt->zt_data;
313 	*size = zt->zt_size;
314 	*bufsize = zt->zt_bufsize;
315 
316 	zio->io_transform_stack = zt->zt_next;
317 	kmem_free(zt, sizeof (zio_transform_t));
318 
319 	if ((zt = zio->io_transform_stack) != NULL) {
320 		zio->io_data = zt->zt_data;
321 		zio->io_size = zt->zt_size;
322 	}
323 }
324 
325 static void
326 zio_clear_transform_stack(zio_t *zio)
327 {
328 	void *data;
329 	uint64_t size, bufsize;
330 
331 	ASSERT(zio->io_transform_stack != NULL);
332 
333 	zio_pop_transform(zio, &data, &size, &bufsize);
334 	while (zio->io_transform_stack != NULL) {
335 		zio_buf_free(data, bufsize);
336 		zio_pop_transform(zio, &data, &size, &bufsize);
337 	}
338 }
339 
340 /*
341  * ==========================================================================
342  * Create the various types of I/O (read, write, free)
343  * ==========================================================================
344  */
345 static zio_t *
346 zio_create(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
347     void *data, uint64_t size, zio_done_func_t *done, void *private,
348     zio_type_t type, int priority, int flags, uint8_t stage, uint32_t pipeline)
349 {
350 	zio_t *zio;
351 
352 	ASSERT3U(size, <=, SPA_MAXBLOCKSIZE);
353 	ASSERT(P2PHASE(size, SPA_MINBLOCKSIZE) == 0);
354 
355 	zio = kmem_cache_alloc(zio_cache, KM_SLEEP);
356 	bzero(zio, sizeof (zio_t));
357 	zio->io_parent = pio;
358 	zio->io_spa = spa;
359 	zio->io_txg = txg;
360 	zio->io_flags = flags;
361 	if (bp != NULL) {
362 		zio->io_bp = bp;
363 		zio->io_bp_copy = *bp;
364 		zio->io_bp_orig = *bp;
365 		if (dmu_ot[BP_GET_TYPE(bp)].ot_metadata ||
366 		    BP_GET_LEVEL(bp) != 0)
367 			zio->io_flags |= ZIO_FLAG_METADATA;
368 	}
369 	zio->io_done = done;
370 	zio->io_private = private;
371 	zio->io_type = type;
372 	zio->io_priority = priority;
373 	zio->io_stage = stage;
374 	zio->io_pipeline = pipeline;
375 	zio->io_async_stages = ZIO_ASYNC_PIPELINE_STAGES;
376 	zio->io_timestamp = lbolt64;
377 	if (pio != NULL)
378 		zio->io_flags |= (pio->io_flags & ZIO_FLAG_METADATA);
379 	mutex_init(&zio->io_lock, NULL, MUTEX_DEFAULT, NULL);
380 	cv_init(&zio->io_cv, NULL, CV_DEFAULT, NULL);
381 	zio_push_transform(zio, data, size, size);
382 
383 	/*
384 	 * Note on config lock:
385 	 *
386 	 * If CONFIG_HELD is set, then the caller already has the config
387 	 * lock, so we don't need it for this io.
388 	 *
389 	 * We set CONFIG_GRABBED to indicate that we have grabbed the
390 	 * config lock on behalf of this io, so it should be released
391 	 * in zio_done.
392 	 *
393 	 * Unless CONFIG_HELD is set, we will grab the config lock for
394 	 * any top-level (parent-less) io, *except* NULL top-level ios.
395 	 * The NULL top-level ios rarely have any children, so we delay
396 	 * grabbing the lock until the first child is added (but it is
397 	 * still grabbed on behalf of the top-level i/o, so additional
398 	 * children don't need to also grab it).  This greatly reduces
399 	 * contention on the config lock.
400 	 */
401 	if (pio == NULL) {
402 		if (type != ZIO_TYPE_NULL &&
403 		    !(flags & ZIO_FLAG_CONFIG_HELD)) {
404 			spa_config_enter(zio->io_spa, RW_READER, zio);
405 			zio->io_flags |= ZIO_FLAG_CONFIG_GRABBED;
406 		}
407 		zio->io_root = zio;
408 	} else {
409 		zio->io_root = pio->io_root;
410 		if (!(flags & ZIO_FLAG_NOBOOKMARK))
411 			zio->io_logical = pio->io_logical;
412 		mutex_enter(&pio->io_lock);
413 		if (pio->io_parent == NULL &&
414 		    pio->io_type == ZIO_TYPE_NULL &&
415 		    !(pio->io_flags & ZIO_FLAG_CONFIG_GRABBED) &&
416 		    !(pio->io_flags & ZIO_FLAG_CONFIG_HELD)) {
417 			pio->io_flags |= ZIO_FLAG_CONFIG_GRABBED;
418 			spa_config_enter(zio->io_spa, RW_READER, pio);
419 		}
420 		if (stage < ZIO_STAGE_READY)
421 			pio->io_children_notready++;
422 		pio->io_children_notdone++;
423 		zio->io_sibling_next = pio->io_child;
424 		zio->io_sibling_prev = NULL;
425 		if (pio->io_child != NULL)
426 			pio->io_child->io_sibling_prev = zio;
427 		pio->io_child = zio;
428 		zio->io_ndvas = pio->io_ndvas;
429 		mutex_exit(&pio->io_lock);
430 	}
431 
432 	/*
433 	 * Save off the original state incase we need to retry later.
434 	 */
435 	zio->io_orig_stage = zio->io_stage;
436 	zio->io_orig_pipeline = zio->io_pipeline;
437 	zio->io_orig_flags = zio->io_flags;
438 
439 	return (zio);
440 }
441 
442 static void
443 zio_reset(zio_t *zio)
444 {
445 	zio_clear_transform_stack(zio);
446 
447 	zio->io_flags = zio->io_orig_flags;
448 	zio->io_stage = zio->io_orig_stage;
449 	zio->io_pipeline = zio->io_orig_pipeline;
450 	zio_push_transform(zio, zio->io_data, zio->io_size, zio->io_size);
451 }
452 
453 zio_t *
454 zio_null(zio_t *pio, spa_t *spa, zio_done_func_t *done, void *private,
455 	int flags)
456 {
457 	zio_t *zio;
458 
459 	zio = zio_create(pio, spa, 0, NULL, NULL, 0, done, private,
460 	    ZIO_TYPE_NULL, ZIO_PRIORITY_NOW, flags, ZIO_STAGE_OPEN,
461 	    ZIO_WAIT_FOR_CHILDREN_PIPELINE);
462 
463 	return (zio);
464 }
465 
466 zio_t *
467 zio_root(spa_t *spa, zio_done_func_t *done, void *private, int flags)
468 {
469 	return (zio_null(NULL, spa, done, private, flags));
470 }
471 
472 zio_t *
473 zio_read(zio_t *pio, spa_t *spa, blkptr_t *bp, void *data,
474     uint64_t size, zio_done_func_t *done, void *private,
475     int priority, int flags, zbookmark_t *zb)
476 {
477 	zio_t *zio;
478 
479 	ASSERT3U(size, ==, BP_GET_LSIZE(bp));
480 
481 	/*
482 	 * If the user has specified that we allow I/Os to continue
483 	 * then attempt to satisfy the read.
484 	 */
485 	if (spa_get_failmode(spa) != ZIO_FAILURE_MODE_CONTINUE)
486 		ZIO_ENTER(spa);
487 
488 	zio = zio_create(pio, spa, bp->blk_birth, bp, data, size, done, private,
489 	    ZIO_TYPE_READ, priority, flags | ZIO_FLAG_USER,
490 	    ZIO_STAGE_OPEN, ZIO_READ_PIPELINE);
491 	zio->io_bookmark = *zb;
492 
493 	zio->io_logical = zio;
494 
495 	/*
496 	 * Work off our copy of the bp so the caller can free it.
497 	 */
498 	zio->io_bp = &zio->io_bp_copy;
499 
500 	return (zio);
501 }
502 
503 zio_t *
504 zio_write(zio_t *pio, spa_t *spa, int checksum, int compress, int ncopies,
505     uint64_t txg, blkptr_t *bp, void *data, uint64_t size,
506     zio_done_func_t *ready, zio_done_func_t *done, void *private, int priority,
507     int flags, zbookmark_t *zb)
508 {
509 	zio_t *zio;
510 
511 	ASSERT(checksum >= ZIO_CHECKSUM_OFF &&
512 	    checksum < ZIO_CHECKSUM_FUNCTIONS);
513 
514 	ASSERT(compress >= ZIO_COMPRESS_OFF &&
515 	    compress < ZIO_COMPRESS_FUNCTIONS);
516 
517 	ZIO_ENTER(spa);
518 
519 	zio = zio_create(pio, spa, txg, bp, data, size, done, private,
520 	    ZIO_TYPE_WRITE, priority, flags | ZIO_FLAG_USER,
521 	    ZIO_STAGE_OPEN, ZIO_WRITE_PIPELINE);
522 
523 	zio->io_ready = ready;
524 
525 	zio->io_bookmark = *zb;
526 
527 	zio->io_logical = zio;
528 
529 	zio->io_checksum = checksum;
530 	zio->io_compress = compress;
531 	zio->io_ndvas = ncopies;
532 
533 	if (compress != ZIO_COMPRESS_OFF)
534 		zio->io_async_stages |= 1U << ZIO_STAGE_WRITE_COMPRESS;
535 
536 	if (bp->blk_birth != txg) {
537 		/* XXX the bp usually (always?) gets re-zeroed later */
538 		BP_ZERO(bp);
539 		BP_SET_LSIZE(bp, size);
540 		BP_SET_PSIZE(bp, size);
541 	} else {
542 		/* Make sure someone doesn't change their mind on overwrites */
543 		ASSERT(MIN(zio->io_ndvas + BP_IS_GANG(bp),
544 		    spa_max_replication(spa)) == BP_GET_NDVAS(bp));
545 	}
546 
547 	return (zio);
548 }
549 
550 zio_t *
551 zio_rewrite(zio_t *pio, spa_t *spa, int checksum,
552     uint64_t txg, blkptr_t *bp, void *data, uint64_t size,
553     zio_done_func_t *done, void *private, int priority, int flags,
554     zbookmark_t *zb)
555 {
556 	zio_t *zio;
557 
558 	zio = zio_create(pio, spa, txg, bp, data, size, done, private,
559 	    ZIO_TYPE_WRITE, priority, flags | ZIO_FLAG_USER,
560 	    ZIO_STAGE_OPEN, ZIO_REWRITE_PIPELINE);
561 
562 	zio->io_bookmark = *zb;
563 	zio->io_checksum = checksum;
564 	zio->io_compress = ZIO_COMPRESS_OFF;
565 
566 	if (pio != NULL)
567 		ASSERT3U(zio->io_ndvas, <=, BP_GET_NDVAS(bp));
568 
569 	return (zio);
570 }
571 
572 static void
573 zio_write_allocate_ready(zio_t *zio)
574 {
575 	/* Free up the previous block */
576 	if (!BP_IS_HOLE(&zio->io_bp_orig)) {
577 		zio_nowait(zio_free(zio, zio->io_spa, zio->io_txg,
578 		    &zio->io_bp_orig, NULL, NULL));
579 	}
580 }
581 
582 static zio_t *
583 zio_write_allocate(zio_t *pio, spa_t *spa, int checksum,
584     uint64_t txg, blkptr_t *bp, void *data, uint64_t size,
585     zio_done_func_t *done, void *private, int priority, int flags)
586 {
587 	zio_t *zio;
588 
589 	BP_ZERO(bp);
590 	BP_SET_LSIZE(bp, size);
591 	BP_SET_PSIZE(bp, size);
592 	BP_SET_COMPRESS(bp, ZIO_COMPRESS_OFF);
593 
594 	zio = zio_create(pio, spa, txg, bp, data, size, done, private,
595 	    ZIO_TYPE_WRITE, priority, flags,
596 	    ZIO_STAGE_OPEN, ZIO_WRITE_ALLOCATE_PIPELINE);
597 
598 	zio->io_checksum = checksum;
599 	zio->io_compress = ZIO_COMPRESS_OFF;
600 	zio->io_ready = zio_write_allocate_ready;
601 
602 	return (zio);
603 }
604 
605 zio_t *
606 zio_free(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
607     zio_done_func_t *done, void *private)
608 {
609 	zio_t *zio;
610 
611 	ASSERT(!BP_IS_HOLE(bp));
612 
613 	if (txg == spa->spa_syncing_txg &&
614 	    spa->spa_sync_pass > zio_sync_pass.zp_defer_free) {
615 		bplist_enqueue_deferred(&spa->spa_sync_bplist, bp);
616 		return (zio_null(pio, spa, NULL, NULL, 0));
617 	}
618 
619 	zio = zio_create(pio, spa, txg, bp, NULL, 0, done, private,
620 	    ZIO_TYPE_FREE, ZIO_PRIORITY_FREE, ZIO_FLAG_USER,
621 	    ZIO_STAGE_OPEN, ZIO_FREE_PIPELINE);
622 
623 	zio->io_bp = &zio->io_bp_copy;
624 
625 	return (zio);
626 }
627 
628 zio_t *
629 zio_claim(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
630     zio_done_func_t *done, void *private)
631 {
632 	zio_t *zio;
633 
634 	/*
635 	 * A claim is an allocation of a specific block.  Claims are needed
636 	 * to support immediate writes in the intent log.  The issue is that
637 	 * immediate writes contain committed data, but in a txg that was
638 	 * *not* committed.  Upon opening the pool after an unclean shutdown,
639 	 * the intent log claims all blocks that contain immediate write data
640 	 * so that the SPA knows they're in use.
641 	 *
642 	 * All claims *must* be resolved in the first txg -- before the SPA
643 	 * starts allocating blocks -- so that nothing is allocated twice.
644 	 */
645 	ASSERT3U(spa->spa_uberblock.ub_rootbp.blk_birth, <, spa_first_txg(spa));
646 	ASSERT3U(spa_first_txg(spa), <=, txg);
647 
648 	zio = zio_create(pio, spa, txg, bp, NULL, 0, done, private,
649 	    ZIO_TYPE_CLAIM, ZIO_PRIORITY_NOW, 0,
650 	    ZIO_STAGE_OPEN, ZIO_CLAIM_PIPELINE);
651 
652 	zio->io_bp = &zio->io_bp_copy;
653 
654 	return (zio);
655 }
656 
657 zio_t *
658 zio_ioctl(zio_t *pio, spa_t *spa, vdev_t *vd, int cmd,
659     zio_done_func_t *done, void *private, int priority, int flags)
660 {
661 	zio_t *zio;
662 	int c;
663 
664 	if (vd->vdev_children == 0) {
665 		zio = zio_create(pio, spa, 0, NULL, NULL, 0, done, private,
666 		    ZIO_TYPE_IOCTL, priority, flags,
667 		    ZIO_STAGE_OPEN, ZIO_IOCTL_PIPELINE);
668 
669 		zio->io_vd = vd;
670 		zio->io_cmd = cmd;
671 	} else {
672 		zio = zio_null(pio, spa, NULL, NULL, flags);
673 
674 		for (c = 0; c < vd->vdev_children; c++)
675 			zio_nowait(zio_ioctl(zio, spa, vd->vdev_child[c], cmd,
676 			    done, private, priority, flags));
677 	}
678 
679 	return (zio);
680 }
681 
682 static void
683 zio_phys_bp_init(vdev_t *vd, blkptr_t *bp, uint64_t offset, uint64_t size,
684     int checksum)
685 {
686 	ASSERT(vd->vdev_children == 0);
687 
688 	ASSERT(size <= SPA_MAXBLOCKSIZE);
689 	ASSERT(P2PHASE(size, SPA_MINBLOCKSIZE) == 0);
690 	ASSERT(P2PHASE(offset, SPA_MINBLOCKSIZE) == 0);
691 
692 	ASSERT(offset + size <= VDEV_LABEL_START_SIZE ||
693 	    offset >= vd->vdev_psize - VDEV_LABEL_END_SIZE);
694 	ASSERT3U(offset + size, <=, vd->vdev_psize);
695 
696 	BP_ZERO(bp);
697 
698 	BP_SET_LSIZE(bp, size);
699 	BP_SET_PSIZE(bp, size);
700 
701 	BP_SET_CHECKSUM(bp, checksum);
702 	BP_SET_COMPRESS(bp, ZIO_COMPRESS_OFF);
703 	BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
704 
705 	if (checksum != ZIO_CHECKSUM_OFF)
706 		ZIO_SET_CHECKSUM(&bp->blk_cksum, offset, 0, 0, 0);
707 }
708 
709 zio_t *
710 zio_read_phys(zio_t *pio, vdev_t *vd, uint64_t offset, uint64_t size,
711     void *data, int checksum, zio_done_func_t *done, void *private,
712     int priority, int flags)
713 {
714 	zio_t *zio;
715 	blkptr_t blk;
716 
717 	ZIO_ENTER(vd->vdev_spa);
718 
719 	zio_phys_bp_init(vd, &blk, offset, size, checksum);
720 
721 	zio = zio_create(pio, vd->vdev_spa, 0, &blk, data, size, done, private,
722 	    ZIO_TYPE_READ, priority, flags | ZIO_FLAG_PHYSICAL,
723 	    ZIO_STAGE_OPEN, ZIO_READ_PHYS_PIPELINE);
724 
725 	zio->io_vd = vd;
726 	zio->io_offset = offset;
727 
728 	/*
729 	 * Work off our copy of the bp so the caller can free it.
730 	 */
731 	zio->io_bp = &zio->io_bp_copy;
732 
733 	return (zio);
734 }
735 
736 zio_t *
737 zio_write_phys(zio_t *pio, vdev_t *vd, uint64_t offset, uint64_t size,
738     void *data, int checksum, zio_done_func_t *done, void *private,
739     int priority, int flags)
740 {
741 	zio_block_tail_t *zbt;
742 	void *wbuf;
743 	zio_t *zio;
744 	blkptr_t blk;
745 
746 	ZIO_ENTER(vd->vdev_spa);
747 
748 	zio_phys_bp_init(vd, &blk, offset, size, checksum);
749 
750 	zio = zio_create(pio, vd->vdev_spa, 0, &blk, data, size, done, private,
751 	    ZIO_TYPE_WRITE, priority, flags | ZIO_FLAG_PHYSICAL,
752 	    ZIO_STAGE_OPEN, ZIO_WRITE_PHYS_PIPELINE);
753 
754 	zio->io_vd = vd;
755 	zio->io_offset = offset;
756 
757 	zio->io_bp = &zio->io_bp_copy;
758 	zio->io_checksum = checksum;
759 
760 	if (zio_checksum_table[checksum].ci_zbt) {
761 		/*
762 		 * zbt checksums are necessarily destructive -- they modify
763 		 * one word of the write buffer to hold the verifier/checksum.
764 		 * Therefore, we must make a local copy in case the data is
765 		 * being written to multiple places.
766 		 */
767 		wbuf = zio_buf_alloc(size);
768 		bcopy(data, wbuf, size);
769 		zio_push_transform(zio, wbuf, size, size);
770 
771 		zbt = (zio_block_tail_t *)((char *)wbuf + size) - 1;
772 		zbt->zbt_cksum = blk.blk_cksum;
773 	}
774 
775 	return (zio);
776 }
777 
778 /*
779  * Create a child I/O to do some work for us.  It has no associated bp.
780  */
781 zio_t *
782 zio_vdev_child_io(zio_t *zio, blkptr_t *bp, vdev_t *vd, uint64_t offset,
783 	void *data, uint64_t size, int type, int priority, int flags,
784 	zio_done_func_t *done, void *private)
785 {
786 	uint32_t pipeline = ZIO_VDEV_CHILD_PIPELINE;
787 	zio_t *cio;
788 
789 	if (type == ZIO_TYPE_READ && bp != NULL) {
790 		/*
791 		 * If we have the bp, then the child should perform the
792 		 * checksum and the parent need not.  This pushes error
793 		 * detection as close to the leaves as possible and
794 		 * eliminates redundant checksums in the interior nodes.
795 		 */
796 		pipeline |= 1U << ZIO_STAGE_CHECKSUM_VERIFY;
797 		zio->io_pipeline &= ~(1U << ZIO_STAGE_CHECKSUM_VERIFY);
798 	}
799 
800 	cio = zio_create(zio, zio->io_spa, zio->io_txg, bp, data, size,
801 	    done, private, type, priority,
802 	    (zio->io_flags & ZIO_FLAG_VDEV_INHERIT) | ZIO_FLAG_CANFAIL | flags,
803 	    ZIO_STAGE_VDEV_IO_START - 1, pipeline);
804 
805 	cio->io_vd = vd;
806 	cio->io_offset = offset;
807 
808 	return (cio);
809 }
810 
811 /*
812  * ==========================================================================
813  * Initiate I/O, either sync or async
814  * ==========================================================================
815  */
816 int
817 zio_wait(zio_t *zio)
818 {
819 	int error;
820 
821 	ASSERT(zio->io_stage == ZIO_STAGE_OPEN);
822 
823 	zio->io_waiter = curthread;
824 
825 	zio_next_stage_async(zio);
826 
827 	mutex_enter(&zio->io_lock);
828 	while (zio->io_stalled != ZIO_STAGE_DONE)
829 		cv_wait(&zio->io_cv, &zio->io_lock);
830 	mutex_exit(&zio->io_lock);
831 
832 	error = zio->io_error;
833 	mutex_destroy(&zio->io_lock);
834 	cv_destroy(&zio->io_cv);
835 	kmem_cache_free(zio_cache, zio);
836 
837 	return (error);
838 }
839 
840 void
841 zio_nowait(zio_t *zio)
842 {
843 	zio_next_stage_async(zio);
844 }
845 
846 /*
847  * ==========================================================================
848  * I/O pipeline interlocks: parent/child dependency scoreboarding
849  * ==========================================================================
850  */
851 static void
852 zio_wait_for_children(zio_t *zio, uint32_t stage, uint64_t *countp)
853 {
854 	mutex_enter(&zio->io_lock);
855 	if (*countp == 0) {
856 		ASSERT(zio->io_stalled == 0);
857 		mutex_exit(&zio->io_lock);
858 		zio_next_stage(zio);
859 	} else {
860 		zio->io_stalled = stage;
861 		mutex_exit(&zio->io_lock);
862 	}
863 }
864 
865 static void
866 zio_notify_parent(zio_t *zio, uint32_t stage, uint64_t *countp)
867 {
868 	zio_t *pio = zio->io_parent;
869 
870 	mutex_enter(&pio->io_lock);
871 	if (pio->io_error == 0 && !(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE))
872 		pio->io_error = zio->io_error;
873 	ASSERT3U(*countp, >, 0);
874 	if (--*countp == 0 && pio->io_stalled == stage) {
875 		pio->io_stalled = 0;
876 		mutex_exit(&pio->io_lock);
877 		zio_next_stage_async(pio);
878 	} else {
879 		mutex_exit(&pio->io_lock);
880 	}
881 }
882 
883 static void
884 zio_wait_children_ready(zio_t *zio)
885 {
886 	zio_wait_for_children(zio, ZIO_STAGE_WAIT_CHILDREN_READY,
887 	    &zio->io_children_notready);
888 }
889 
890 void
891 zio_wait_children_done(zio_t *zio)
892 {
893 	zio_wait_for_children(zio, ZIO_STAGE_WAIT_CHILDREN_DONE,
894 	    &zio->io_children_notdone);
895 }
896 
897 static void
898 zio_read_init(zio_t *zio)
899 {
900 	if (BP_GET_COMPRESS(zio->io_bp) != ZIO_COMPRESS_OFF) {
901 		uint64_t csize = BP_GET_PSIZE(zio->io_bp);
902 		void *cbuf = zio_buf_alloc(csize);
903 
904 		zio_push_transform(zio, cbuf, csize, csize);
905 		zio->io_pipeline |= 1U << ZIO_STAGE_READ_DECOMPRESS;
906 	}
907 
908 	if (BP_IS_GANG(zio->io_bp)) {
909 		uint64_t gsize = SPA_GANGBLOCKSIZE;
910 		void *gbuf = zio_buf_alloc(gsize);
911 
912 		zio_push_transform(zio, gbuf, gsize, gsize);
913 		zio->io_pipeline |= 1U << ZIO_STAGE_READ_GANG_MEMBERS;
914 	}
915 	zio_next_stage(zio);
916 }
917 
918 static void
919 zio_ready(zio_t *zio)
920 {
921 	zio_t *pio = zio->io_parent;
922 
923 	if (zio->io_ready)
924 		zio->io_ready(zio);
925 
926 	if (pio != NULL)
927 		zio_notify_parent(zio, ZIO_STAGE_WAIT_CHILDREN_READY,
928 		    &pio->io_children_notready);
929 
930 	if (zio->io_bp)
931 		zio->io_bp_copy = *zio->io_bp;
932 
933 	zio_next_stage(zio);
934 }
935 
936 static void
937 zio_vdev_retry_io(zio_t *zio)
938 {
939 	zio_t *pio = zio->io_parent;
940 
941 	/*
942 	 * Preserve the failed bp so that the io_ready() callback can
943 	 * update the accounting accordingly. The callback will also be
944 	 * responsible for freeing the previously allocated block, if one
945 	 * exists.
946 	 */
947 	zio->io_bp_orig = *zio->io_bp;
948 
949 	/*
950 	 * We must zero out the old DVA and blk_birth before reallocating
951 	 * the bp. We don't want to do this if this is a rewrite however.
952 	 */
953 	if (!IO_IS_REWRITE(zio)) {
954 		BP_ZERO_DVAS(zio->io_bp);
955 	}
956 
957 	zio_reset(zio);
958 
959 	if (pio) {
960 		/*
961 		 * Let the parent know that we will
962 		 * re-alloc the write (=> new bp info).
963 		 */
964 		mutex_enter(&pio->io_lock);
965 		pio->io_children_notready++;
966 
967 		/*
968 		 * If the parent I/O is still in the open stage, then
969 		 * don't bother telling it to retry since it hasn't
970 		 * progressed far enough for it to care.
971 		 */
972 		if (pio->io_stage > ZIO_STAGE_OPEN && IO_IS_ALLOCATING(pio))
973 			pio->io_flags |= ZIO_FLAG_WRITE_RETRY;
974 
975 		ASSERT(pio->io_stage <= ZIO_STAGE_WAIT_CHILDREN_DONE);
976 		mutex_exit(&pio->io_lock);
977 	}
978 
979 	/*
980 	 * We are getting ready to process the retry request so clear
981 	 * the flag and the zio's current error status.
982 	 */
983 	zio->io_flags &= ~ZIO_FLAG_WRITE_RETRY;
984 	zio->io_error = 0;
985 	zio_next_stage_async(zio);
986 }
987 
988 int
989 zio_vdev_resume_io(spa_t *spa)
990 {
991 	zio_t *zio;
992 
993 	mutex_enter(&spa->spa_zio_lock);
994 
995 	/*
996 	 * Probe all of vdevs that have experienced an I/O error.
997 	 * If we are still unable to verify the integrity of the vdev
998 	 * then we prevent the resume from proceeeding.
999 	 */
1000 	for (zio = list_head(&spa->spa_zio_list); zio != NULL;
1001 	    zio = list_next(&spa->spa_zio_list, zio)) {
1002 		int error = 0;
1003 
1004 		/* We only care about I/Os that must succeed */
1005 		if (zio->io_vd == NULL || zio->io_flags & ZIO_FLAG_CANFAIL)
1006 			continue;
1007 		error = vdev_probe(zio->io_vd);
1008 		if (error) {
1009 			mutex_exit(&spa->spa_zio_lock);
1010 			return (error);
1011 		}
1012 	}
1013 
1014 	/*
1015 	 * Clear the vdev stats so that I/O can flow.
1016 	 */
1017 	vdev_clear(spa, NULL, B_FALSE);
1018 
1019 	spa->spa_state = POOL_STATE_ACTIVE;
1020 	while ((zio = list_head(&spa->spa_zio_list)) != NULL) {
1021 		list_remove(&spa->spa_zio_list, zio);
1022 		zio->io_error = 0;
1023 
1024 		/*
1025 		 * If we are resuming an allocating I/O then we force it
1026 		 * to retry and let it resume operation where it left off.
1027 		 * Otherwise, go back to the ready stage and pick up from
1028 		 * there.
1029 		 */
1030 		if (zio_write_retry && IO_IS_ALLOCATING(zio)) {
1031 			zio->io_flags |= ZIO_FLAG_WRITE_RETRY;
1032 			zio->io_stage--;
1033 		} else {
1034 			zio->io_stage = ZIO_STAGE_READY;
1035 		}
1036 
1037 		(void) taskq_dispatch(zio_taskq, zio_resubmit_stage_async,
1038 		    zio, TQ_SLEEP);
1039 	}
1040 	mutex_exit(&spa->spa_zio_lock);
1041 
1042 	/*
1043 	 * Wait for the taskqs to finish and recheck the pool state since
1044 	 * it's possible that a resumed I/O has failed again.
1045 	 */
1046 	taskq_wait(zio_taskq);
1047 	if (spa_state(spa) == POOL_STATE_IO_FAILURE)
1048 		return (EIO);
1049 
1050 	mutex_enter(&spa->spa_zio_lock);
1051 	cv_broadcast(&spa->spa_zio_cv);
1052 	mutex_exit(&spa->spa_zio_lock);
1053 
1054 	return (0);
1055 }
1056 
1057 static void
1058 zio_vdev_suspend_io(zio_t *zio)
1059 {
1060 	spa_t *spa = zio->io_spa;
1061 
1062 	/*
1063 	 * We've experienced an unrecoverable failure so
1064 	 * set the pool state accordingly and queue all
1065 	 * failed IOs.
1066 	 */
1067 	spa->spa_state = POOL_STATE_IO_FAILURE;
1068 
1069 	mutex_enter(&spa->spa_zio_lock);
1070 	list_insert_tail(&spa->spa_zio_list, zio);
1071 
1072 #ifndef _KERNEL
1073 	/* Used to notify ztest that the pool has suspended */
1074 	cv_broadcast(&spa->spa_zio_cv);
1075 #endif
1076 	mutex_exit(&spa->spa_zio_lock);
1077 }
1078 
1079 static void
1080 zio_assess(zio_t *zio)
1081 {
1082 	spa_t *spa = zio->io_spa;
1083 	blkptr_t *bp = zio->io_bp;
1084 	vdev_t *vd = zio->io_vd;
1085 
1086 	ASSERT(zio->io_children_notready == 0);
1087 	ASSERT(zio->io_children_notdone == 0);
1088 
1089 	if (bp != NULL) {
1090 		ASSERT(bp->blk_pad[0] == 0);
1091 		ASSERT(bp->blk_pad[1] == 0);
1092 		ASSERT(bp->blk_pad[2] == 0);
1093 		ASSERT(bcmp(bp, &zio->io_bp_copy, sizeof (blkptr_t)) == 0);
1094 		if (zio->io_type == ZIO_TYPE_WRITE && !BP_IS_HOLE(bp) &&
1095 		    !(zio->io_flags & ZIO_FLAG_IO_REPAIR)) {
1096 			ASSERT(!BP_SHOULD_BYTESWAP(bp));
1097 			if (zio->io_ndvas != 0)
1098 				ASSERT3U(zio->io_ndvas, <=, BP_GET_NDVAS(bp));
1099 			ASSERT(BP_COUNT_GANG(bp) == 0 ||
1100 			    (BP_COUNT_GANG(bp) == BP_GET_NDVAS(bp)));
1101 		}
1102 	}
1103 
1104 	/*
1105 	 * Some child I/O has indicated that a retry is necessary, so
1106 	 * we set an error on the I/O and let the logic below do the
1107 	 * rest.
1108 	 */
1109 	if (zio->io_flags & ZIO_FLAG_WRITE_RETRY)
1110 		zio->io_error = ERESTART;
1111 
1112 	if (vd != NULL)
1113 		vdev_stat_update(zio);
1114 
1115 	if (zio->io_error) {
1116 		/*
1117 		 * If this I/O is attached to a particular vdev,
1118 		 * generate an error message describing the I/O failure
1119 		 * at the block level.  We ignore these errors if the
1120 		 * device is currently unavailable.
1121 		 */
1122 		if (zio->io_error != ECKSUM && vd != NULL && !vdev_is_dead(vd))
1123 			zfs_ereport_post(FM_EREPORT_ZFS_IO, spa, vd, zio, 0, 0);
1124 
1125 		if ((zio->io_error == EIO ||
1126 		    !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) &&
1127 		    zio->io_logical == zio) {
1128 			/*
1129 			 * For root I/O requests, tell the SPA to log the error
1130 			 * appropriately.  Also, generate a logical data
1131 			 * ereport.
1132 			 */
1133 			spa_log_error(spa, zio);
1134 
1135 			zfs_ereport_post(FM_EREPORT_ZFS_DATA, spa, NULL, zio,
1136 			    0, 0);
1137 		}
1138 
1139 		/*
1140 		 * If we are an allocating I/O or have been told to retry
1141 		 * then attempt to reissue the I/O on another vdev unless
1142 		 * the pool is out of space.  We handle this condition
1143 		 * based on the spa's failmode property.
1144 		 */
1145 		if (zio_write_retry && zio->io_error != ENOSPC &&
1146 		    (IO_IS_ALLOCATING(zio) ||
1147 		    zio->io_flags & ZIO_FLAG_WRITE_RETRY)) {
1148 			zio_vdev_retry_io(zio);
1149 			return;
1150 		}
1151 		ASSERT(!(zio->io_flags & ZIO_FLAG_WRITE_RETRY));
1152 
1153 		/*
1154 		 * For I/O requests that cannot fail, we carry out
1155 		 * the requested behavior based on the failmode pool
1156 		 * property.
1157 		 *
1158 		 * XXX - Need to differentiate between an ENOSPC as
1159 		 * a result of vdev failures vs. a full pool.
1160 		 */
1161 		if (!(zio->io_flags & ZIO_FLAG_CANFAIL)) {
1162 			char *blkbuf;
1163 
1164 #ifdef ZFS_DEBUG
1165 			blkbuf = kmem_alloc(BP_SPRINTF_LEN, KM_NOSLEEP);
1166 			if (blkbuf) {
1167 				sprintf_blkptr(blkbuf, BP_SPRINTF_LEN,
1168 				    bp ? bp : &zio->io_bp_copy);
1169 			}
1170 			cmn_err(CE_WARN, "ZFS: %s (%s on %s off %llx: zio %p "
1171 			    "%s): error %d", zio->io_error == ECKSUM ?
1172 			    "bad checksum" : "I/O failure",
1173 			    zio_type_name[zio->io_type],
1174 			    vdev_description(vd),
1175 			    (u_longlong_t)zio->io_offset,
1176 			    (void *)zio, blkbuf ? blkbuf : "", zio->io_error);
1177 #endif
1178 
1179 			if (spa_get_failmode(spa) == ZIO_FAILURE_MODE_PANIC) {
1180 				fm_panic("Pool '%s' has encountered an "
1181 				    "uncorrectable I/O failure and the "
1182 				    "failure mode property for this pool "
1183 				    "is set to panic.", spa_name(spa));
1184 			} else {
1185 				cmn_err(CE_WARN, "Pool '%s' has encountered "
1186 				    "an uncorrectable I/O error. Manual "
1187 				    "intervention is required.",
1188 				    spa_name(spa));
1189 				zio_vdev_suspend_io(zio);
1190 			}
1191 			return;
1192 		}
1193 	}
1194 	ASSERT(!(zio->io_flags & ZIO_FLAG_WRITE_RETRY));
1195 	ASSERT(zio->io_children_notready == 0);
1196 	zio_next_stage(zio);
1197 }
1198 
1199 static void
1200 zio_done(zio_t *zio)
1201 {
1202 	zio_t *pio = zio->io_parent;
1203 	spa_t *spa = zio->io_spa;
1204 
1205 	ASSERT(zio->io_children_notready == 0);
1206 	ASSERT(zio->io_children_notdone == 0);
1207 
1208 	zio_clear_transform_stack(zio);
1209 
1210 	if (zio->io_done)
1211 		zio->io_done(zio);
1212 
1213 	ASSERT(zio->io_delegate_list == NULL);
1214 	ASSERT(zio->io_delegate_next == NULL);
1215 
1216 	if (pio != NULL) {
1217 		zio_t *next, *prev;
1218 
1219 		mutex_enter(&pio->io_lock);
1220 		next = zio->io_sibling_next;
1221 		prev = zio->io_sibling_prev;
1222 		if (next != NULL)
1223 			next->io_sibling_prev = prev;
1224 		if (prev != NULL)
1225 			prev->io_sibling_next = next;
1226 		if (pio->io_child == zio)
1227 			pio->io_child = next;
1228 		mutex_exit(&pio->io_lock);
1229 
1230 		zio_notify_parent(zio, ZIO_STAGE_WAIT_CHILDREN_DONE,
1231 		    &pio->io_children_notdone);
1232 	}
1233 
1234 	/*
1235 	 * Note: this I/O is now done, and will shortly be freed, so there is no
1236 	 * need to clear this (or any other) flag.
1237 	 */
1238 	if (zio->io_flags & ZIO_FLAG_CONFIG_GRABBED)
1239 		spa_config_exit(spa, zio);
1240 
1241 	if (zio->io_waiter != NULL) {
1242 		mutex_enter(&zio->io_lock);
1243 		ASSERT(zio->io_stage == ZIO_STAGE_DONE);
1244 		zio->io_stalled = zio->io_stage;
1245 		cv_broadcast(&zio->io_cv);
1246 		mutex_exit(&zio->io_lock);
1247 	} else {
1248 		mutex_destroy(&zio->io_lock);
1249 		cv_destroy(&zio->io_cv);
1250 		kmem_cache_free(zio_cache, zio);
1251 	}
1252 }
1253 
1254 /*
1255  * ==========================================================================
1256  * Compression support
1257  * ==========================================================================
1258  */
1259 static void
1260 zio_write_compress(zio_t *zio)
1261 {
1262 	int compress = zio->io_compress;
1263 	blkptr_t *bp = zio->io_bp;
1264 	void *cbuf;
1265 	uint64_t lsize = zio->io_size;
1266 	uint64_t csize = lsize;
1267 	uint64_t cbufsize = 0;
1268 	int pass;
1269 
1270 	if (bp->blk_birth == zio->io_txg) {
1271 		/*
1272 		 * We're rewriting an existing block, which means we're
1273 		 * working on behalf of spa_sync().  For spa_sync() to
1274 		 * converge, it must eventually be the case that we don't
1275 		 * have to allocate new blocks.  But compression changes
1276 		 * the blocksize, which forces a reallocate, and makes
1277 		 * convergence take longer.  Therefore, after the first
1278 		 * few passes, stop compressing to ensure convergence.
1279 		 */
1280 		pass = spa_sync_pass(zio->io_spa);
1281 		if (pass > zio_sync_pass.zp_dontcompress)
1282 			compress = ZIO_COMPRESS_OFF;
1283 	} else {
1284 		ASSERT(BP_IS_HOLE(bp));
1285 		pass = 1;
1286 	}
1287 
1288 	if (compress != ZIO_COMPRESS_OFF)
1289 		if (!zio_compress_data(compress, zio->io_data, zio->io_size,
1290 		    &cbuf, &csize, &cbufsize))
1291 			compress = ZIO_COMPRESS_OFF;
1292 
1293 	if (compress != ZIO_COMPRESS_OFF && csize != 0)
1294 		zio_push_transform(zio, cbuf, csize, cbufsize);
1295 
1296 	/*
1297 	 * The final pass of spa_sync() must be all rewrites, but the first
1298 	 * few passes offer a trade-off: allocating blocks defers convergence,
1299 	 * but newly allocated blocks are sequential, so they can be written
1300 	 * to disk faster.  Therefore, we allow the first few passes of
1301 	 * spa_sync() to reallocate new blocks, but force rewrites after that.
1302 	 * There should only be a handful of blocks after pass 1 in any case.
1303 	 */
1304 	if (bp->blk_birth == zio->io_txg && BP_GET_PSIZE(bp) == csize &&
1305 	    pass > zio_sync_pass.zp_rewrite) {
1306 		ASSERT(csize != 0);
1307 		BP_SET_LSIZE(bp, lsize);
1308 		BP_SET_COMPRESS(bp, compress);
1309 		zio->io_pipeline = ZIO_REWRITE_PIPELINE;
1310 	} else {
1311 		if (bp->blk_birth == zio->io_txg)
1312 			BP_ZERO(bp);
1313 		if (csize == 0) {
1314 			BP_ZERO(bp);
1315 			zio->io_pipeline = ZIO_WAIT_FOR_CHILDREN_PIPELINE;
1316 		} else {
1317 			ASSERT3U(BP_GET_NDVAS(bp), ==, 0);
1318 			BP_SET_LSIZE(bp, lsize);
1319 			BP_SET_PSIZE(bp, csize);
1320 			BP_SET_COMPRESS(bp, compress);
1321 			zio->io_pipeline = ZIO_WRITE_ALLOCATE_PIPELINE;
1322 		}
1323 	}
1324 
1325 	zio_next_stage(zio);
1326 }
1327 
1328 static void
1329 zio_read_decompress(zio_t *zio)
1330 {
1331 	blkptr_t *bp = zio->io_bp;
1332 	void *data;
1333 	uint64_t size;
1334 	uint64_t bufsize;
1335 	int compress = BP_GET_COMPRESS(bp);
1336 
1337 	ASSERT(compress != ZIO_COMPRESS_OFF);
1338 
1339 	zio_pop_transform(zio, &data, &size, &bufsize);
1340 
1341 	if (zio_decompress_data(compress, data, size,
1342 	    zio->io_data, zio->io_size))
1343 		zio->io_error = EIO;
1344 
1345 	zio_buf_free(data, bufsize);
1346 
1347 	zio_next_stage(zio);
1348 }
1349 
1350 /*
1351  * ==========================================================================
1352  * Gang block support
1353  * ==========================================================================
1354  */
1355 static void
1356 zio_gang_pipeline(zio_t *zio)
1357 {
1358 	/*
1359 	 * By default, the pipeline assumes that we're dealing with a gang
1360 	 * block.  If we're not, strip out any gang-specific stages.
1361 	 */
1362 	if (!BP_IS_GANG(zio->io_bp))
1363 		zio->io_pipeline &= ~ZIO_GANG_STAGES;
1364 
1365 	zio_next_stage(zio);
1366 }
1367 
1368 static void
1369 zio_gang_byteswap(zio_t *zio)
1370 {
1371 	ASSERT(zio->io_size == SPA_GANGBLOCKSIZE);
1372 
1373 	if (BP_SHOULD_BYTESWAP(zio->io_bp))
1374 		byteswap_uint64_array(zio->io_data, zio->io_size);
1375 }
1376 
1377 static void
1378 zio_get_gang_header(zio_t *zio)
1379 {
1380 	blkptr_t *bp = zio->io_bp;
1381 	uint64_t gsize = SPA_GANGBLOCKSIZE;
1382 	void *gbuf = zio_buf_alloc(gsize);
1383 
1384 	ASSERT(BP_IS_GANG(bp));
1385 
1386 	zio_push_transform(zio, gbuf, gsize, gsize);
1387 
1388 	zio_nowait(zio_create(zio, zio->io_spa, bp->blk_birth, bp, gbuf, gsize,
1389 	    NULL, NULL, ZIO_TYPE_READ, zio->io_priority,
1390 	    zio->io_flags & ZIO_FLAG_GANG_INHERIT,
1391 	    ZIO_STAGE_OPEN, ZIO_READ_GANG_PIPELINE));
1392 
1393 	zio_wait_children_done(zio);
1394 }
1395 
1396 static void
1397 zio_read_gang_members(zio_t *zio)
1398 {
1399 	zio_gbh_phys_t *gbh;
1400 	uint64_t gsize, gbufsize, loff, lsize;
1401 	int i;
1402 
1403 	ASSERT(BP_IS_GANG(zio->io_bp));
1404 
1405 	zio_gang_byteswap(zio);
1406 	zio_pop_transform(zio, (void **)&gbh, &gsize, &gbufsize);
1407 
1408 	for (loff = 0, i = 0; loff != zio->io_size; loff += lsize, i++) {
1409 		blkptr_t *gbp = &gbh->zg_blkptr[i];
1410 		lsize = BP_GET_PSIZE(gbp);
1411 
1412 		ASSERT(BP_GET_COMPRESS(gbp) == ZIO_COMPRESS_OFF);
1413 		ASSERT3U(lsize, ==, BP_GET_LSIZE(gbp));
1414 		ASSERT3U(loff + lsize, <=, zio->io_size);
1415 		ASSERT(i < SPA_GBH_NBLKPTRS);
1416 		ASSERT(!BP_IS_HOLE(gbp));
1417 
1418 		zio_nowait(zio_read(zio, zio->io_spa, gbp,
1419 		    (char *)zio->io_data + loff, lsize, NULL, NULL,
1420 		    zio->io_priority, zio->io_flags & ZIO_FLAG_GANG_INHERIT,
1421 		    &zio->io_bookmark));
1422 	}
1423 
1424 	zio_buf_free(gbh, gbufsize);
1425 	zio_wait_children_done(zio);
1426 }
1427 
1428 static void
1429 zio_rewrite_gang_members(zio_t *zio)
1430 {
1431 	zio_gbh_phys_t *gbh;
1432 	uint64_t gsize, gbufsize, loff, lsize;
1433 	int i;
1434 
1435 	ASSERT(BP_IS_GANG(zio->io_bp));
1436 	ASSERT3U(zio->io_size, ==, SPA_GANGBLOCKSIZE);
1437 
1438 	zio_gang_byteswap(zio);
1439 	zio_pop_transform(zio, (void **)&gbh, &gsize, &gbufsize);
1440 
1441 	ASSERT(gsize == gbufsize);
1442 
1443 	for (loff = 0, i = 0; loff != zio->io_size; loff += lsize, i++) {
1444 		blkptr_t *gbp = &gbh->zg_blkptr[i];
1445 		lsize = BP_GET_PSIZE(gbp);
1446 
1447 		ASSERT(BP_GET_COMPRESS(gbp) == ZIO_COMPRESS_OFF);
1448 		ASSERT3U(lsize, ==, BP_GET_LSIZE(gbp));
1449 		ASSERT3U(loff + lsize, <=, zio->io_size);
1450 		ASSERT(i < SPA_GBH_NBLKPTRS);
1451 		ASSERT(!BP_IS_HOLE(gbp));
1452 
1453 		zio_nowait(zio_rewrite(zio, zio->io_spa, zio->io_checksum,
1454 		    zio->io_txg, gbp, (char *)zio->io_data + loff, lsize,
1455 		    NULL, NULL, zio->io_priority, zio->io_flags,
1456 		    &zio->io_bookmark));
1457 	}
1458 
1459 	zio_push_transform(zio, gbh, gsize, gbufsize);
1460 	zio_wait_children_ready(zio);
1461 }
1462 
1463 static void
1464 zio_free_gang_members(zio_t *zio)
1465 {
1466 	zio_gbh_phys_t *gbh;
1467 	uint64_t gsize, gbufsize;
1468 	int i;
1469 
1470 	ASSERT(BP_IS_GANG(zio->io_bp));
1471 
1472 	zio_gang_byteswap(zio);
1473 	zio_pop_transform(zio, (void **)&gbh, &gsize, &gbufsize);
1474 
1475 	for (i = 0; i < SPA_GBH_NBLKPTRS; i++) {
1476 		blkptr_t *gbp = &gbh->zg_blkptr[i];
1477 
1478 		if (BP_IS_HOLE(gbp))
1479 			continue;
1480 		zio_nowait(zio_free(zio, zio->io_spa, zio->io_txg,
1481 		    gbp, NULL, NULL));
1482 	}
1483 
1484 	zio_buf_free(gbh, gbufsize);
1485 	zio_next_stage(zio);
1486 }
1487 
1488 static void
1489 zio_claim_gang_members(zio_t *zio)
1490 {
1491 	zio_gbh_phys_t *gbh;
1492 	uint64_t gsize, gbufsize;
1493 	int i;
1494 
1495 	ASSERT(BP_IS_GANG(zio->io_bp));
1496 
1497 	zio_gang_byteswap(zio);
1498 	zio_pop_transform(zio, (void **)&gbh, &gsize, &gbufsize);
1499 
1500 	for (i = 0; i < SPA_GBH_NBLKPTRS; i++) {
1501 		blkptr_t *gbp = &gbh->zg_blkptr[i];
1502 		if (BP_IS_HOLE(gbp))
1503 			continue;
1504 		zio_nowait(zio_claim(zio, zio->io_spa, zio->io_txg,
1505 		    gbp, NULL, NULL));
1506 	}
1507 
1508 	zio_buf_free(gbh, gbufsize);
1509 	zio_next_stage(zio);
1510 }
1511 
1512 static void
1513 zio_write_allocate_gang_member_done(zio_t *zio)
1514 {
1515 	zio_t *pio = zio->io_parent;
1516 	dva_t *cdva = zio->io_bp->blk_dva;
1517 	dva_t *pdva = pio->io_bp->blk_dva;
1518 	uint64_t asize;
1519 	int d;
1520 
1521 	ASSERT3U(pio->io_ndvas, ==, zio->io_ndvas);
1522 	ASSERT3U(BP_GET_NDVAS(zio->io_bp), <=, BP_GET_NDVAS(pio->io_bp));
1523 	ASSERT3U(zio->io_ndvas, <=, BP_GET_NDVAS(zio->io_bp));
1524 	ASSERT3U(pio->io_ndvas, <=, BP_GET_NDVAS(pio->io_bp));
1525 
1526 	mutex_enter(&pio->io_lock);
1527 	for (d = 0; d < BP_GET_NDVAS(pio->io_bp); d++) {
1528 		ASSERT(DVA_GET_GANG(&pdva[d]));
1529 		asize = DVA_GET_ASIZE(&pdva[d]);
1530 		asize += DVA_GET_ASIZE(&cdva[d]);
1531 		DVA_SET_ASIZE(&pdva[d], asize);
1532 	}
1533 	mutex_exit(&pio->io_lock);
1534 }
1535 
1536 static int
1537 zio_write_allocate_gang_members(zio_t *zio, metaslab_class_t *mc)
1538 {
1539 	blkptr_t *bp = zio->io_bp;
1540 	dva_t *dva = bp->blk_dva;
1541 	spa_t *spa = zio->io_spa;
1542 	zio_gbh_phys_t *gbh;
1543 	uint64_t txg = zio->io_txg;
1544 	uint64_t resid = zio->io_size;
1545 	uint64_t maxalloc = P2ROUNDUP(zio->io_size >> 1, SPA_MINBLOCKSIZE);
1546 	uint64_t gsize, loff, lsize;
1547 	uint32_t gbps_left;
1548 	int ndvas = zio->io_ndvas;
1549 	int gbh_ndvas = MIN(ndvas + 1, spa_max_replication(spa));
1550 	int error;
1551 	int i, d;
1552 
1553 	gsize = SPA_GANGBLOCKSIZE;
1554 	gbps_left = SPA_GBH_NBLKPTRS;
1555 
1556 	error = metaslab_alloc(spa, mc, gsize, bp, gbh_ndvas, txg, NULL,
1557 	    B_FALSE);
1558 	if (error)
1559 		return (error);
1560 
1561 	for (d = 0; d < gbh_ndvas; d++)
1562 		DVA_SET_GANG(&dva[d], 1);
1563 
1564 	bp->blk_birth = txg;
1565 
1566 	gbh = zio_buf_alloc(gsize);
1567 	bzero(gbh, gsize);
1568 
1569 	/* We need to test multi-level gang blocks */
1570 	if (maxalloc >= zio_gang_bang && (lbolt & 0x1) == 0)
1571 		maxalloc = MAX(maxalloc >> 2, SPA_MINBLOCKSIZE);
1572 
1573 	for (loff = 0, i = 0; loff != zio->io_size;
1574 	    loff += lsize, resid -= lsize, gbps_left--, i++) {
1575 		blkptr_t *gbp = &gbh->zg_blkptr[i];
1576 		dva = gbp->blk_dva;
1577 
1578 		ASSERT(gbps_left != 0);
1579 		maxalloc = MIN(maxalloc, resid);
1580 
1581 		while (resid <= maxalloc * gbps_left) {
1582 			error = metaslab_alloc(spa, mc, maxalloc, gbp, ndvas,
1583 			    txg, bp, B_FALSE);
1584 			if (error == 0)
1585 				break;
1586 			ASSERT3U(error, ==, ENOSPC);
1587 			/* XXX - free up previous allocations? */
1588 			if (maxalloc == SPA_MINBLOCKSIZE)
1589 				return (error);
1590 			maxalloc = P2ROUNDUP(maxalloc >> 1, SPA_MINBLOCKSIZE);
1591 		}
1592 
1593 		if (resid <= maxalloc * gbps_left) {
1594 			lsize = maxalloc;
1595 			BP_SET_LSIZE(gbp, lsize);
1596 			BP_SET_PSIZE(gbp, lsize);
1597 			BP_SET_COMPRESS(gbp, ZIO_COMPRESS_OFF);
1598 			gbp->blk_birth = txg;
1599 			zio_nowait(zio_rewrite(zio, spa,
1600 			    zio->io_checksum, txg, gbp,
1601 			    (char *)zio->io_data + loff, lsize,
1602 			    zio_write_allocate_gang_member_done, NULL,
1603 			    zio->io_priority, zio->io_flags,
1604 			    &zio->io_bookmark));
1605 		} else {
1606 			lsize = P2ROUNDUP(resid / gbps_left, SPA_MINBLOCKSIZE);
1607 			ASSERT(lsize != SPA_MINBLOCKSIZE);
1608 			zio_nowait(zio_write_allocate(zio, spa,
1609 			    zio->io_checksum, txg, gbp,
1610 			    (char *)zio->io_data + loff, lsize,
1611 			    zio_write_allocate_gang_member_done, NULL,
1612 			    zio->io_priority, zio->io_flags));
1613 		}
1614 	}
1615 
1616 	ASSERT(resid == 0 && loff == zio->io_size);
1617 
1618 	zio->io_pipeline |= 1U << ZIO_STAGE_GANG_CHECKSUM_GENERATE;
1619 
1620 	zio_push_transform(zio, gbh, gsize, gsize);
1621 	/*
1622 	 * As much as we'd like this to be zio_wait_children_ready(),
1623 	 * updating our ASIZE doesn't happen until the io_done callback,
1624 	 * so we have to wait for that to finish in order for our BP
1625 	 * to be stable.
1626 	 */
1627 	zio_wait_children_done(zio);
1628 	return (0);
1629 }
1630 
1631 /*
1632  * ==========================================================================
1633  * Allocate and free blocks
1634  * ==========================================================================
1635  */
1636 static void
1637 zio_dva_allocate(zio_t *zio)
1638 {
1639 	spa_t *spa = zio->io_spa;
1640 	metaslab_class_t *mc = spa->spa_normal_class;
1641 	blkptr_t *bp = zio->io_bp;
1642 	int error;
1643 
1644 	ASSERT(BP_IS_HOLE(bp));
1645 	ASSERT3U(BP_GET_NDVAS(bp), ==, 0);
1646 	ASSERT3U(zio->io_ndvas, >, 0);
1647 	ASSERT3U(zio->io_ndvas, <=, spa_max_replication(spa));
1648 
1649 	/* For testing, make some blocks above a certain size be gang blocks */
1650 	if (zio->io_size >= zio_gang_bang && (lbolt & 0x3) == 0) {
1651 		error = zio_write_allocate_gang_members(zio, mc);
1652 		if (error)
1653 			zio->io_error = error;
1654 		return;
1655 	}
1656 
1657 	/*
1658 	 * For testing purposes, we force I/Os to retry. We don't allow
1659 	 * retries beyond the first pass since those I/Os are non-allocating
1660 	 * writes. We do this after the gang block testing block so that
1661 	 * they don't inherit the retry flag.
1662 	 */
1663 	if (zio_io_fail_shift &&
1664 	    spa_sync_pass(zio->io_spa) <= zio_sync_pass.zp_rewrite &&
1665 	    zio_io_should_fail(zio_io_fail_shift))
1666 		zio->io_flags |= ZIO_FLAG_WRITE_RETRY;
1667 
1668 	ASSERT3U(zio->io_size, ==, BP_GET_PSIZE(bp));
1669 
1670 	error = metaslab_alloc(spa, mc, zio->io_size, bp, zio->io_ndvas,
1671 	    zio->io_txg, NULL, B_FALSE);
1672 
1673 	if (error == 0) {
1674 		bp->blk_birth = zio->io_txg;
1675 	} else if (error == ENOSPC && zio->io_size > SPA_MINBLOCKSIZE) {
1676 		error = zio_write_allocate_gang_members(zio, mc);
1677 		if (error == 0)
1678 			return;
1679 		zio->io_error = error;
1680 	} else {
1681 		zio->io_error = error;
1682 	}
1683 	zio_next_stage(zio);
1684 }
1685 
1686 static void
1687 zio_dva_free(zio_t *zio)
1688 {
1689 	blkptr_t *bp = zio->io_bp;
1690 
1691 	metaslab_free(zio->io_spa, bp, zio->io_txg, B_FALSE);
1692 
1693 	BP_ZERO(bp);
1694 
1695 	zio_next_stage(zio);
1696 }
1697 
1698 static void
1699 zio_dva_claim(zio_t *zio)
1700 {
1701 	zio->io_error = metaslab_claim(zio->io_spa, zio->io_bp, zio->io_txg);
1702 
1703 	zio_next_stage(zio);
1704 }
1705 
1706 /*
1707  * ==========================================================================
1708  * Read and write to physical devices
1709  * ==========================================================================
1710  */
1711 
1712 static void
1713 zio_vdev_io_start(zio_t *zio)
1714 {
1715 	vdev_t *vd = zio->io_vd;
1716 	vdev_t *tvd = vd ? vd->vdev_top : NULL;
1717 	blkptr_t *bp = zio->io_bp;
1718 	uint64_t align;
1719 	spa_t *spa = zio->io_spa;
1720 
1721 	/*
1722 	 * If the pool is already in a failure state then just suspend
1723 	 * this IO until the problem is resolved. We will reissue them
1724 	 * at that time.
1725 	 */
1726 	if (spa_state(spa) == POOL_STATE_IO_FAILURE &&
1727 	    zio->io_type == ZIO_TYPE_WRITE) {
1728 		zio_vdev_suspend_io(zio);
1729 		return;
1730 	}
1731 
1732 	if (vd == NULL) {
1733 		/* The mirror_ops handle multiple DVAs in a single BP */
1734 		vdev_mirror_ops.vdev_op_io_start(zio);
1735 		return;
1736 	}
1737 
1738 	align = 1ULL << tvd->vdev_ashift;
1739 
1740 	if (zio->io_retries == 0 && vd == tvd)
1741 		zio->io_flags |= ZIO_FLAG_FAILFAST;
1742 
1743 	if (!(zio->io_flags & ZIO_FLAG_PHYSICAL) &&
1744 	    vd->vdev_children == 0) {
1745 		zio->io_flags |= ZIO_FLAG_PHYSICAL;
1746 		zio->io_offset += VDEV_LABEL_START_SIZE;
1747 	}
1748 
1749 	if (P2PHASE(zio->io_size, align) != 0) {
1750 		uint64_t asize = P2ROUNDUP(zio->io_size, align);
1751 		char *abuf = zio_buf_alloc(asize);
1752 		ASSERT(vd == tvd);
1753 		if (zio->io_type == ZIO_TYPE_WRITE) {
1754 			bcopy(zio->io_data, abuf, zio->io_size);
1755 			bzero(abuf + zio->io_size, asize - zio->io_size);
1756 		}
1757 		zio_push_transform(zio, abuf, asize, asize);
1758 		ASSERT(!(zio->io_flags & ZIO_FLAG_SUBBLOCK));
1759 		zio->io_flags |= ZIO_FLAG_SUBBLOCK;
1760 	}
1761 
1762 	ASSERT(P2PHASE(zio->io_offset, align) == 0);
1763 	ASSERT(P2PHASE(zio->io_size, align) == 0);
1764 	ASSERT(bp == NULL ||
1765 	    P2ROUNDUP(ZIO_GET_IOSIZE(zio), align) == zio->io_size);
1766 	ASSERT(zio->io_type != ZIO_TYPE_WRITE || (spa_mode & FWRITE));
1767 
1768 	vdev_io_start(zio);
1769 
1770 	/* zio_next_stage_async() gets called from io completion interrupt */
1771 }
1772 
1773 static void
1774 zio_vdev_io_done(zio_t *zio)
1775 {
1776 	if (zio->io_vd == NULL)
1777 		/* The mirror_ops handle multiple DVAs in a single BP */
1778 		vdev_mirror_ops.vdev_op_io_done(zio);
1779 	else
1780 		vdev_io_done(zio);
1781 }
1782 
1783 /* XXPOLICY */
1784 boolean_t
1785 zio_should_retry(zio_t *zio)
1786 {
1787 	vdev_t *vd = zio->io_vd;
1788 
1789 	if (zio->io_error == 0)
1790 		return (B_FALSE);
1791 	if (zio->io_delegate_list != NULL)
1792 		return (B_FALSE);
1793 	if (vd && vd != vd->vdev_top)
1794 		return (B_FALSE);
1795 	if (zio->io_flags & ZIO_FLAG_DONT_RETRY)
1796 		return (B_FALSE);
1797 	if (zio->io_retries > 0)
1798 		return (B_FALSE);
1799 
1800 	return (B_TRUE);
1801 }
1802 
1803 static void
1804 zio_vdev_io_assess(zio_t *zio)
1805 {
1806 	vdev_t *vd = zio->io_vd;
1807 	vdev_t *tvd = vd ? vd->vdev_top : NULL;
1808 
1809 	ASSERT(zio->io_vsd == NULL);
1810 
1811 	if (zio->io_flags & ZIO_FLAG_SUBBLOCK) {
1812 		void *abuf;
1813 		uint64_t asize;
1814 		ASSERT(vd == tvd);
1815 		zio_pop_transform(zio, &abuf, &asize, &asize);
1816 		if (zio->io_type == ZIO_TYPE_READ)
1817 			bcopy(abuf, zio->io_data, zio->io_size);
1818 		zio_buf_free(abuf, asize);
1819 		zio->io_flags &= ~ZIO_FLAG_SUBBLOCK;
1820 	}
1821 
1822 	if (zio_injection_enabled && !zio->io_error)
1823 		zio->io_error = zio_handle_fault_injection(zio, EIO);
1824 
1825 	/*
1826 	 * If the I/O failed, determine whether we should attempt to retry it.
1827 	 */
1828 	/* XXPOLICY */
1829 	if (zio_should_retry(zio)) {
1830 		ASSERT(tvd == vd);
1831 
1832 		zio->io_retries++;
1833 		zio->io_error = 0;
1834 		zio->io_flags &= ZIO_FLAG_VDEV_INHERIT |
1835 		    ZIO_FLAG_CONFIG_GRABBED;
1836 		/* XXPOLICY */
1837 		zio->io_flags &= ~ZIO_FLAG_FAILFAST;
1838 		zio->io_flags |= ZIO_FLAG_DONT_CACHE;
1839 		zio->io_stage = ZIO_STAGE_VDEV_IO_START - 1;
1840 
1841 		dprintf("retry #%d for %s to %s offset %llx\n",
1842 		    zio->io_retries, zio_type_name[zio->io_type],
1843 		    vdev_description(vd), zio->io_offset);
1844 
1845 		zio_next_stage_async(zio);
1846 		return;
1847 	}
1848 
1849 	zio_next_stage(zio);
1850 }
1851 
1852 void
1853 zio_vdev_io_reissue(zio_t *zio)
1854 {
1855 	ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_START);
1856 	ASSERT(zio->io_error == 0);
1857 
1858 	zio->io_stage--;
1859 }
1860 
1861 void
1862 zio_vdev_io_redone(zio_t *zio)
1863 {
1864 	ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_DONE);
1865 
1866 	zio->io_stage--;
1867 }
1868 
1869 void
1870 zio_vdev_io_bypass(zio_t *zio)
1871 {
1872 	ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_START);
1873 	ASSERT(zio->io_error == 0);
1874 
1875 	zio->io_flags |= ZIO_FLAG_IO_BYPASS;
1876 	zio->io_stage = ZIO_STAGE_VDEV_IO_ASSESS - 1;
1877 }
1878 
1879 /*
1880  * ==========================================================================
1881  * Generate and verify checksums
1882  * ==========================================================================
1883  */
1884 static void
1885 zio_checksum_generate(zio_t *zio)
1886 {
1887 	int checksum = zio->io_checksum;
1888 	blkptr_t *bp = zio->io_bp;
1889 
1890 	ASSERT3U(zio->io_size, ==, BP_GET_PSIZE(bp));
1891 
1892 	BP_SET_CHECKSUM(bp, checksum);
1893 	BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
1894 
1895 	zio_checksum(checksum, &bp->blk_cksum, zio->io_data, zio->io_size);
1896 
1897 	zio_next_stage(zio);
1898 }
1899 
1900 static void
1901 zio_gang_checksum_generate(zio_t *zio)
1902 {
1903 	zio_cksum_t zc;
1904 	zio_gbh_phys_t *gbh = zio->io_data;
1905 
1906 	ASSERT(BP_IS_GANG(zio->io_bp));
1907 	ASSERT3U(zio->io_size, ==, SPA_GANGBLOCKSIZE);
1908 
1909 	zio_set_gang_verifier(zio, &gbh->zg_tail.zbt_cksum);
1910 
1911 	zio_checksum(ZIO_CHECKSUM_GANG_HEADER, &zc, zio->io_data, zio->io_size);
1912 
1913 	zio_next_stage(zio);
1914 }
1915 
1916 static void
1917 zio_checksum_verify(zio_t *zio)
1918 {
1919 	if (zio->io_bp != NULL) {
1920 		zio->io_error = zio_checksum_error(zio);
1921 		if (zio->io_error && !(zio->io_flags & ZIO_FLAG_SPECULATIVE))
1922 			zfs_ereport_post(FM_EREPORT_ZFS_CHECKSUM,
1923 			    zio->io_spa, zio->io_vd, zio, 0, 0);
1924 	}
1925 
1926 	zio_next_stage(zio);
1927 }
1928 
1929 /*
1930  * Called by RAID-Z to ensure we don't compute the checksum twice.
1931  */
1932 void
1933 zio_checksum_verified(zio_t *zio)
1934 {
1935 	zio->io_pipeline &= ~(1U << ZIO_STAGE_CHECKSUM_VERIFY);
1936 }
1937 
1938 /*
1939  * Set the external verifier for a gang block based on stuff in the bp
1940  */
1941 void
1942 zio_set_gang_verifier(zio_t *zio, zio_cksum_t *zcp)
1943 {
1944 	blkptr_t *bp = zio->io_bp;
1945 
1946 	zcp->zc_word[0] = DVA_GET_VDEV(BP_IDENTITY(bp));
1947 	zcp->zc_word[1] = DVA_GET_OFFSET(BP_IDENTITY(bp));
1948 	zcp->zc_word[2] = bp->blk_birth;
1949 	zcp->zc_word[3] = 0;
1950 }
1951 
1952 /*
1953  * ==========================================================================
1954  * Define the pipeline
1955  * ==========================================================================
1956  */
1957 typedef void zio_pipe_stage_t(zio_t *zio);
1958 
1959 static void
1960 zio_badop(zio_t *zio)
1961 {
1962 	panic("Invalid I/O pipeline stage %u for zio %p", zio->io_stage, zio);
1963 }
1964 
1965 zio_pipe_stage_t *zio_pipeline[ZIO_STAGE_DONE + 2] = {
1966 	zio_badop,
1967 	zio_wait_children_ready,
1968 	zio_write_compress,
1969 	zio_checksum_generate,
1970 	zio_gang_pipeline,
1971 	zio_get_gang_header,
1972 	zio_rewrite_gang_members,
1973 	zio_free_gang_members,
1974 	zio_claim_gang_members,
1975 	zio_dva_allocate,
1976 	zio_dva_free,
1977 	zio_dva_claim,
1978 	zio_gang_checksum_generate,
1979 	zio_ready,
1980 	zio_read_init,
1981 	zio_vdev_io_start,
1982 	zio_vdev_io_done,
1983 	zio_vdev_io_assess,
1984 	zio_wait_children_done,
1985 	zio_checksum_verify,
1986 	zio_read_gang_members,
1987 	zio_read_decompress,
1988 	zio_assess,
1989 	zio_done,
1990 	zio_badop
1991 };
1992 
1993 /*
1994  * Move an I/O to the next stage of the pipeline and execute that stage.
1995  * There's no locking on io_stage because there's no legitimate way for
1996  * multiple threads to be attempting to process the same I/O.
1997  */
1998 void
1999 zio_next_stage(zio_t *zio)
2000 {
2001 	uint32_t pipeline = zio->io_pipeline;
2002 
2003 	ASSERT(!MUTEX_HELD(&zio->io_lock));
2004 
2005 	if (zio->io_error) {
2006 		dprintf("zio %p vdev %s offset %llx stage %d error %d\n",
2007 		    zio, vdev_description(zio->io_vd),
2008 		    zio->io_offset, zio->io_stage, zio->io_error);
2009 		if (((1U << zio->io_stage) & ZIO_VDEV_IO_PIPELINE) == 0)
2010 			pipeline &= ZIO_ERROR_PIPELINE_MASK;
2011 	}
2012 
2013 	while (((1U << ++zio->io_stage) & pipeline) == 0)
2014 		continue;
2015 
2016 	ASSERT(zio->io_stage <= ZIO_STAGE_DONE);
2017 	ASSERT(zio->io_stalled == 0);
2018 
2019 	/*
2020 	 * See the comment in zio_next_stage_async() about per-CPU taskqs.
2021 	 */
2022 	if (((1U << zio->io_stage) & zio->io_async_stages) &&
2023 	    (zio->io_stage == ZIO_STAGE_WRITE_COMPRESS) &&
2024 	    !(zio->io_flags & ZIO_FLAG_METADATA)) {
2025 		taskq_t *tq = zio->io_spa->spa_zio_issue_taskq[zio->io_type];
2026 		(void) taskq_dispatch(tq,
2027 		    (task_func_t *)zio_pipeline[zio->io_stage], zio, TQ_SLEEP);
2028 	} else {
2029 		zio_pipeline[zio->io_stage](zio);
2030 	}
2031 }
2032 
2033 void
2034 zio_next_stage_async(zio_t *zio)
2035 {
2036 	taskq_t *tq;
2037 	uint32_t pipeline = zio->io_pipeline;
2038 
2039 	ASSERT(!MUTEX_HELD(&zio->io_lock));
2040 
2041 	if (zio->io_error) {
2042 		dprintf("zio %p vdev %s offset %llx stage %d error %d\n",
2043 		    zio, vdev_description(zio->io_vd),
2044 		    zio->io_offset, zio->io_stage, zio->io_error);
2045 		if (((1U << zio->io_stage) & ZIO_VDEV_IO_PIPELINE) == 0)
2046 			pipeline &= ZIO_ERROR_PIPELINE_MASK;
2047 	}
2048 
2049 	while (((1U << ++zio->io_stage) & pipeline) == 0)
2050 		continue;
2051 
2052 	ASSERT(zio->io_stage <= ZIO_STAGE_DONE);
2053 	ASSERT(zio->io_stalled == 0);
2054 
2055 	/*
2056 	 * For performance, we'll probably want two sets of task queues:
2057 	 * per-CPU issue taskqs and per-CPU completion taskqs.  The per-CPU
2058 	 * part is for read performance: since we have to make a pass over
2059 	 * the data to checksum it anyway, we want to do this on the same CPU
2060 	 * that issued the read, because (assuming CPU scheduling affinity)
2061 	 * that thread is probably still there.  Getting this optimization
2062 	 * right avoids performance-hostile cache-to-cache transfers.
2063 	 *
2064 	 * Note that having two sets of task queues is also necessary for
2065 	 * correctness: if all of the issue threads get bogged down waiting
2066 	 * for dependent reads (e.g. metaslab freelist) to complete, then
2067 	 * there won't be any threads available to service I/O completion
2068 	 * interrupts.
2069 	 */
2070 	if ((1U << zio->io_stage) & zio->io_async_stages) {
2071 		if (zio->io_stage < ZIO_STAGE_VDEV_IO_DONE)
2072 			tq = zio->io_spa->spa_zio_issue_taskq[zio->io_type];
2073 		else
2074 			tq = zio->io_spa->spa_zio_intr_taskq[zio->io_type];
2075 		(void) taskq_dispatch(tq,
2076 		    (task_func_t *)zio_pipeline[zio->io_stage], zio, TQ_SLEEP);
2077 	} else {
2078 		zio_pipeline[zio->io_stage](zio);
2079 	}
2080 }
2081 
2082 void
2083 zio_resubmit_stage_async(void *arg)
2084 {
2085 	zio_t *zio = (zio_t *)(uintptr_t)arg;
2086 
2087 	zio_next_stage_async(zio);
2088 }
2089 
2090 static boolean_t
2091 zio_io_should_fail(uint16_t range)
2092 {
2093 	static uint16_t	allocs = 0;
2094 
2095 	return (P2PHASE(allocs++, 1U<<range) == 0);
2096 }
2097 
2098 /*
2099  * Try to allocate an intent log block.  Return 0 on success, errno on failure.
2100  */
2101 int
2102 zio_alloc_blk(spa_t *spa, uint64_t size, blkptr_t *new_bp, blkptr_t *old_bp,
2103     uint64_t txg)
2104 {
2105 	int error;
2106 
2107 	spa_config_enter(spa, RW_READER, FTAG);
2108 
2109 	if (zio_zil_fail_shift && zio_io_should_fail(zio_zil_fail_shift)) {
2110 		spa_config_exit(spa, FTAG);
2111 		return (ENOSPC);
2112 	}
2113 
2114 	/*
2115 	 * We were passed the previous log block's DVA in bp->blk_dva[0].
2116 	 * We use that as a hint for which vdev to allocate from next.
2117 	 */
2118 	error = metaslab_alloc(spa, spa->spa_log_class, size,
2119 	    new_bp, 1, txg, old_bp, B_TRUE);
2120 
2121 	if (error)
2122 		error = metaslab_alloc(spa, spa->spa_normal_class, size,
2123 		    new_bp, 1, txg, old_bp, B_TRUE);
2124 
2125 	if (error == 0) {
2126 		BP_SET_LSIZE(new_bp, size);
2127 		BP_SET_PSIZE(new_bp, size);
2128 		BP_SET_COMPRESS(new_bp, ZIO_COMPRESS_OFF);
2129 		BP_SET_CHECKSUM(new_bp, ZIO_CHECKSUM_ZILOG);
2130 		BP_SET_TYPE(new_bp, DMU_OT_INTENT_LOG);
2131 		BP_SET_LEVEL(new_bp, 0);
2132 		BP_SET_BYTEORDER(new_bp, ZFS_HOST_BYTEORDER);
2133 		new_bp->blk_birth = txg;
2134 	}
2135 
2136 	spa_config_exit(spa, FTAG);
2137 
2138 	return (error);
2139 }
2140 
2141 /*
2142  * Free an intent log block.  We know it can't be a gang block, so there's
2143  * nothing to do except metaslab_free() it.
2144  */
2145 void
2146 zio_free_blk(spa_t *spa, blkptr_t *bp, uint64_t txg)
2147 {
2148 	ASSERT(!BP_IS_GANG(bp));
2149 
2150 	spa_config_enter(spa, RW_READER, FTAG);
2151 
2152 	metaslab_free(spa, bp, txg, B_FALSE);
2153 
2154 	spa_config_exit(spa, FTAG);
2155 }
2156 
2157 /*
2158  * start an async flush of the write cache for this vdev
2159  */
2160 void
2161 zio_flush_vdev(spa_t *spa, uint64_t vdev, zio_t **zio)
2162 {
2163 	vdev_t *vd;
2164 
2165 	/*
2166 	 * Lock out configuration changes.
2167 	 */
2168 	spa_config_enter(spa, RW_READER, FTAG);
2169 
2170 	if (*zio == NULL)
2171 		*zio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
2172 
2173 	vd = vdev_lookup_top(spa, vdev);
2174 	ASSERT(vd);
2175 
2176 	(void) zio_nowait(zio_ioctl(*zio, spa, vd, DKIOCFLUSHWRITECACHE,
2177 	    NULL, NULL, ZIO_PRIORITY_NOW,
2178 	    ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_RETRY));
2179 
2180 	spa_config_exit(spa, FTAG);
2181 }
2182