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