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