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