145d3dd9Robert Mustacchi/*
245d3dd9Robert Mustacchi * CDDL HEADER START
345d3dd9Robert Mustacchi *
445d3dd9Robert Mustacchi * The contents of this file are subject to the terms of the
545d3dd9Robert Mustacchi * Common Development and Distribution License (the "License").
645d3dd9Robert Mustacchi * You may not use this file except in compliance with the License.
745d3dd9Robert Mustacchi *
845d3dd9Robert Mustacchi * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
945d3dd9Robert Mustacchi * or http://www.opensolaris.org/os/licensing.
1045d3dd9Robert Mustacchi * See the License for the specific language governing permissions
1145d3dd9Robert Mustacchi * and limitations under the License.
1245d3dd9Robert Mustacchi *
1345d3dd9Robert Mustacchi * When distributing Covered Code, include this CDDL HEADER in each
1445d3dd9Robert Mustacchi * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
1545d3dd9Robert Mustacchi * If applicable, add the following below this CDDL HEADER, with the
1645d3dd9Robert Mustacchi * fields enclosed by brackets "[]" replaced with your own identifying
1745d3dd9Robert Mustacchi * information: Portions Copyright [yyyy] [name of copyright owner]
1845d3dd9Robert Mustacchi *
1945d3dd9Robert Mustacchi * CDDL HEADER END
2045d3dd9Robert Mustacchi */
2145d3dd9Robert Mustacchi/*
2245d3dd9Robert Mustacchi * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
2345d3dd9Robert Mustacchi * Copyright (c) 2011, 2018 by Delphix. All rights reserved.
2445d3dd9Robert Mustacchi * Copyright (c) 2011 Nexenta Systems, Inc. All rights reserved.
2545d3dd9Robert Mustacchi * Copyright (c) 2014 Integros [integros.com]
2645d3dd9Robert Mustacchi * Copyright (c) 2017, Intel Corporation.
2745d3dd9Robert Mustacchi */
2845d3dd9Robert Mustacchi
2945d3dd9Robert Mustacchi#include <sys/sysmacros.h>
3045d3dd9Robert Mustacchi#include <sys/zfs_context.h>
3145d3dd9Robert Mustacchi#include <sys/fm/fs/zfs.h>
3245d3dd9Robert Mustacchi#include <sys/spa.h>
3345d3dd9Robert Mustacchi#include <sys/txg.h>
3445d3dd9Robert Mustacchi#include <sys/spa_impl.h>
3545d3dd9Robert Mustacchi#include <sys/vdev_impl.h>
3645d3dd9Robert Mustacchi#include <sys/vdev_trim.h>
3745d3dd9Robert Mustacchi#include <sys/zio_impl.h>
3845d3dd9Robert Mustacchi#include <sys/zio_compress.h>
3945d3dd9Robert Mustacchi#include <sys/zio_checksum.h>
4045d3dd9Robert Mustacchi#include <sys/dmu_objset.h>
4145d3dd9Robert Mustacchi#include <sys/arc.h>
4245d3dd9Robert Mustacchi#include <sys/ddt.h>
4345d3dd9Robert Mustacchi#include <sys/blkptr.h>
4445d3dd9Robert Mustacchi#include <sys/zfeature.h>
4545d3dd9Robert Mustacchi#include <sys/time.h>
4645d3dd9Robert Mustacchi#include <sys/dsl_scan.h>
4745d3dd9Robert Mustacchi#include <sys/metaslab_impl.h>
4845d3dd9Robert Mustacchi#include <sys/abd.h>
4945d3dd9Robert Mustacchi#include <sys/cityhash.h>
5045d3dd9Robert Mustacchi#include <sys/dsl_crypt.h>
5145d3dd9Robert Mustacchi
5245d3dd9Robert Mustacchi/*
5345d3dd9Robert Mustacchi * ==========================================================================
5445d3dd9Robert Mustacchi * I/O type descriptions
5545d3dd9Robert Mustacchi * ==========================================================================
5645d3dd9Robert Mustacchi */
5745d3dd9Robert Mustacchiconst char *zio_type_name[ZIO_TYPES] = {
5845d3dd9Robert Mustacchi	"zio_null", "zio_read", "zio_write", "zio_free", "zio_claim",
5945d3dd9Robert Mustacchi	"zio_ioctl", "z_trim"
6045d3dd9Robert Mustacchi};
6145d3dd9Robert Mustacchi
6245d3dd9Robert Mustacchiboolean_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