xref: /freebsd/sys/contrib/openzfs/module/zfs/zio.c (revision 0df1ee76950fc28c3c90a8aa85534fd44641c425)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * CDDL HEADER START
4  *
5  * The contents of this file are subject to the terms of the
6  * Common Development and Distribution License (the "License").
7  * You may not use this file except in compliance with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or https://opensource.org/licenses/CDDL-1.0.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2011, 2022 by Delphix. All rights reserved.
25  * Copyright (c) 2011 Nexenta Systems, Inc. All rights reserved.
26  * Copyright (c) 2017, Intel Corporation.
27  * Copyright (c) 2019, 2023, 2024, 2025, Klara, Inc.
28  * Copyright (c) 2019, Allan Jude
29  * Copyright (c) 2021, Datto, Inc.
30  * Copyright (c) 2021, 2024 by George Melikov. All rights reserved.
31  */
32 
33 #include <sys/sysmacros.h>
34 #include <sys/zfs_context.h>
35 #include <sys/fm/fs/zfs.h>
36 #include <sys/spa.h>
37 #include <sys/txg.h>
38 #include <sys/spa_impl.h>
39 #include <sys/vdev_impl.h>
40 #include <sys/vdev_trim.h>
41 #include <sys/zio_impl.h>
42 #include <sys/zio_compress.h>
43 #include <sys/zio_checksum.h>
44 #include <sys/dmu_objset.h>
45 #include <sys/arc.h>
46 #include <sys/brt.h>
47 #include <sys/ddt.h>
48 #include <sys/blkptr.h>
49 #include <sys/zfeature.h>
50 #include <sys/dsl_scan.h>
51 #include <sys/metaslab_impl.h>
52 #include <sys/time.h>
53 #include <sys/trace_zfs.h>
54 #include <sys/abd.h>
55 #include <sys/dsl_crypt.h>
56 #include <cityhash.h>
57 
58 /*
59  * ==========================================================================
60  * I/O type descriptions
61  * ==========================================================================
62  */
63 const char *const zio_type_name[ZIO_TYPES] = {
64 	/*
65 	 * Note: Linux kernel thread name length is limited
66 	 * so these names will differ from upstream open zfs.
67 	 */
68 	"z_null", "z_rd", "z_wr", "z_fr", "z_cl", "z_flush", "z_trim"
69 };
70 
71 int zio_dva_throttle_enabled = B_TRUE;
72 static int zio_deadman_log_all = B_FALSE;
73 
74 /*
75  * ==========================================================================
76  * I/O kmem caches
77  * ==========================================================================
78  */
79 static kmem_cache_t *zio_cache;
80 static kmem_cache_t *zio_link_cache;
81 kmem_cache_t *zio_buf_cache[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT];
82 kmem_cache_t *zio_data_buf_cache[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT];
83 #if defined(ZFS_DEBUG) && !defined(_KERNEL)
84 static uint64_t zio_buf_cache_allocs[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT];
85 static uint64_t zio_buf_cache_frees[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT];
86 #endif
87 
88 /* Mark IOs as "slow" if they take longer than 30 seconds */
89 static uint_t zio_slow_io_ms = (30 * MILLISEC);
90 
91 #define	BP_SPANB(indblkshift, level) \
92 	(((uint64_t)1) << ((level) * ((indblkshift) - SPA_BLKPTRSHIFT)))
93 #define	COMPARE_META_LEVEL	0x80000000ul
94 /*
95  * The following actions directly effect the spa's sync-to-convergence logic.
96  * The values below define the sync pass when we start performing the action.
97  * Care should be taken when changing these values as they directly impact
98  * spa_sync() performance. Tuning these values may introduce subtle performance
99  * pathologies and should only be done in the context of performance analysis.
100  * These tunables will eventually be removed and replaced with #defines once
101  * enough analysis has been done to determine optimal values.
102  *
103  * The 'zfs_sync_pass_deferred_free' pass must be greater than 1 to ensure that
104  * regular blocks are not deferred.
105  *
106  * Starting in sync pass 8 (zfs_sync_pass_dont_compress), we disable
107  * compression (including of metadata).  In practice, we don't have this
108  * many sync passes, so this has no effect.
109  *
110  * The original intent was that disabling compression would help the sync
111  * passes to converge. However, in practice disabling compression increases
112  * the average number of sync passes, because when we turn compression off, a
113  * lot of block's size will change and thus we have to re-allocate (not
114  * overwrite) them. It also increases the number of 128KB allocations (e.g.
115  * for indirect blocks and spacemaps) because these will not be compressed.
116  * The 128K allocations are especially detrimental to performance on highly
117  * fragmented systems, which may have very few free segments of this size,
118  * and may need to load new metaslabs to satisfy 128K allocations.
119  */
120 
121 /* defer frees starting in this pass */
122 uint_t zfs_sync_pass_deferred_free = 2;
123 
124 /* don't compress starting in this pass */
125 static uint_t zfs_sync_pass_dont_compress = 8;
126 
127 /* rewrite new bps starting in this pass */
128 static uint_t zfs_sync_pass_rewrite = 2;
129 
130 /*
131  * An allocating zio is one that either currently has the DVA allocate
132  * stage set or will have it later in its lifetime.
133  */
134 #define	IO_IS_ALLOCATING(zio) ((zio)->io_orig_pipeline & ZIO_STAGE_DVA_ALLOCATE)
135 
136 /*
137  * Enable smaller cores by excluding metadata
138  * allocations as well.
139  */
140 int zio_exclude_metadata = 0;
141 static int zio_requeue_io_start_cut_in_line = 1;
142 
143 #ifdef ZFS_DEBUG
144 static const int zio_buf_debug_limit = 16384;
145 #else
146 static const int zio_buf_debug_limit = 0;
147 #endif
148 
149 typedef struct zio_stats {
150 	kstat_named_t ziostat_total_allocations;
151 	kstat_named_t ziostat_alloc_class_fallbacks;
152 	kstat_named_t ziostat_gang_writes;
153 	kstat_named_t ziostat_gang_multilevel;
154 } zio_stats_t;
155 
156 static zio_stats_t zio_stats = {
157 	{ "total_allocations",	KSTAT_DATA_UINT64 },
158 	{ "alloc_class_fallbacks",	KSTAT_DATA_UINT64 },
159 	{ "gang_writes",	KSTAT_DATA_UINT64 },
160 	{ "gang_multilevel",	KSTAT_DATA_UINT64 },
161 };
162 
163 struct {
164 	wmsum_t ziostat_total_allocations;
165 	wmsum_t ziostat_alloc_class_fallbacks;
166 	wmsum_t ziostat_gang_writes;
167 	wmsum_t ziostat_gang_multilevel;
168 } ziostat_sums;
169 
170 #define	ZIOSTAT_BUMP(stat)	wmsum_add(&ziostat_sums.stat, 1);
171 
172 static kstat_t *zio_ksp;
173 
174 static inline void __zio_execute(zio_t *zio);
175 
176 static void zio_taskq_dispatch(zio_t *, zio_taskq_type_t, boolean_t);
177 
178 static int
zio_kstats_update(kstat_t * ksp,int rw)179 zio_kstats_update(kstat_t *ksp, int rw)
180 {
181 	zio_stats_t *zs = ksp->ks_data;
182 	if (rw == KSTAT_WRITE)
183 		return (EACCES);
184 
185 	zs->ziostat_total_allocations.value.ui64 =
186 	    wmsum_value(&ziostat_sums.ziostat_total_allocations);
187 	zs->ziostat_alloc_class_fallbacks.value.ui64 =
188 	    wmsum_value(&ziostat_sums.ziostat_alloc_class_fallbacks);
189 	zs->ziostat_gang_writes.value.ui64 =
190 	    wmsum_value(&ziostat_sums.ziostat_gang_writes);
191 	zs->ziostat_gang_multilevel.value.ui64 =
192 	    wmsum_value(&ziostat_sums.ziostat_gang_multilevel);
193 	return (0);
194 }
195 
196 void
zio_init(void)197 zio_init(void)
198 {
199 	size_t c;
200 
201 	zio_cache = kmem_cache_create("zio_cache",
202 	    sizeof (zio_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
203 	zio_link_cache = kmem_cache_create("zio_link_cache",
204 	    sizeof (zio_link_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
205 
206 	wmsum_init(&ziostat_sums.ziostat_total_allocations, 0);
207 	wmsum_init(&ziostat_sums.ziostat_alloc_class_fallbacks, 0);
208 	wmsum_init(&ziostat_sums.ziostat_gang_writes, 0);
209 	wmsum_init(&ziostat_sums.ziostat_gang_multilevel, 0);
210 	zio_ksp = kstat_create("zfs", 0, "zio_stats",
211 	    "misc", KSTAT_TYPE_NAMED, sizeof (zio_stats) /
212 	    sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
213 	if (zio_ksp != NULL) {
214 		zio_ksp->ks_data = &zio_stats;
215 		zio_ksp->ks_update = zio_kstats_update;
216 		kstat_install(zio_ksp);
217 	}
218 
219 	for (c = 0; c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; c++) {
220 		size_t size = (c + 1) << SPA_MINBLOCKSHIFT;
221 		size_t align, cflags, data_cflags;
222 		char name[32];
223 
224 		/*
225 		 * Create cache for each half-power of 2 size, starting from
226 		 * SPA_MINBLOCKSIZE.  It should give us memory space efficiency
227 		 * of ~7/8, sufficient for transient allocations mostly using
228 		 * these caches.
229 		 */
230 		size_t p2 = size;
231 		while (!ISP2(p2))
232 			p2 &= p2 - 1;
233 		if (!IS_P2ALIGNED(size, p2 / 2))
234 			continue;
235 
236 #ifndef _KERNEL
237 		/*
238 		 * If we are using watchpoints, put each buffer on its own page,
239 		 * to eliminate the performance overhead of trapping to the
240 		 * kernel when modifying a non-watched buffer that shares the
241 		 * page with a watched buffer.
242 		 */
243 		if (arc_watch && !IS_P2ALIGNED(size, PAGESIZE))
244 			continue;
245 #endif
246 
247 		if (IS_P2ALIGNED(size, PAGESIZE))
248 			align = PAGESIZE;
249 		else
250 			align = 1 << (highbit64(size ^ (size - 1)) - 1);
251 
252 		cflags = (zio_exclude_metadata || size > zio_buf_debug_limit) ?
253 		    KMC_NODEBUG : 0;
254 		data_cflags = KMC_NODEBUG;
255 		if (abd_size_alloc_linear(size)) {
256 			cflags |= KMC_RECLAIMABLE;
257 			data_cflags |= KMC_RECLAIMABLE;
258 		}
259 		if (cflags == data_cflags) {
260 			/*
261 			 * Resulting kmem caches would be identical.
262 			 * Save memory by creating only one.
263 			 */
264 			(void) snprintf(name, sizeof (name),
265 			    "zio_buf_comb_%lu", (ulong_t)size);
266 			zio_buf_cache[c] = kmem_cache_create(name, size, align,
267 			    NULL, NULL, NULL, NULL, NULL, cflags);
268 			zio_data_buf_cache[c] = zio_buf_cache[c];
269 			continue;
270 		}
271 		(void) snprintf(name, sizeof (name), "zio_buf_%lu",
272 		    (ulong_t)size);
273 		zio_buf_cache[c] = kmem_cache_create(name, size, align,
274 		    NULL, NULL, NULL, NULL, NULL, cflags);
275 
276 		(void) snprintf(name, sizeof (name), "zio_data_buf_%lu",
277 		    (ulong_t)size);
278 		zio_data_buf_cache[c] = kmem_cache_create(name, size, align,
279 		    NULL, NULL, NULL, NULL, NULL, data_cflags);
280 	}
281 
282 	while (--c != 0) {
283 		ASSERT(zio_buf_cache[c] != NULL);
284 		if (zio_buf_cache[c - 1] == NULL)
285 			zio_buf_cache[c - 1] = zio_buf_cache[c];
286 
287 		ASSERT(zio_data_buf_cache[c] != NULL);
288 		if (zio_data_buf_cache[c - 1] == NULL)
289 			zio_data_buf_cache[c - 1] = zio_data_buf_cache[c];
290 	}
291 
292 	zio_inject_init();
293 
294 	lz4_init();
295 }
296 
297 void
zio_fini(void)298 zio_fini(void)
299 {
300 	size_t n = SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT;
301 
302 #if defined(ZFS_DEBUG) && !defined(_KERNEL)
303 	for (size_t i = 0; i < n; i++) {
304 		if (zio_buf_cache_allocs[i] != zio_buf_cache_frees[i])
305 			(void) printf("zio_fini: [%d] %llu != %llu\n",
306 			    (int)((i + 1) << SPA_MINBLOCKSHIFT),
307 			    (long long unsigned)zio_buf_cache_allocs[i],
308 			    (long long unsigned)zio_buf_cache_frees[i]);
309 	}
310 #endif
311 
312 	/*
313 	 * The same kmem cache can show up multiple times in both zio_buf_cache
314 	 * and zio_data_buf_cache. Do a wasteful but trivially correct scan to
315 	 * sort it out.
316 	 */
317 	for (size_t i = 0; i < n; i++) {
318 		kmem_cache_t *cache = zio_buf_cache[i];
319 		if (cache == NULL)
320 			continue;
321 		for (size_t j = i; j < n; j++) {
322 			if (cache == zio_buf_cache[j])
323 				zio_buf_cache[j] = NULL;
324 			if (cache == zio_data_buf_cache[j])
325 				zio_data_buf_cache[j] = NULL;
326 		}
327 		kmem_cache_destroy(cache);
328 	}
329 
330 	for (size_t i = 0; i < n; i++) {
331 		kmem_cache_t *cache = zio_data_buf_cache[i];
332 		if (cache == NULL)
333 			continue;
334 		for (size_t j = i; j < n; j++) {
335 			if (cache == zio_data_buf_cache[j])
336 				zio_data_buf_cache[j] = NULL;
337 		}
338 		kmem_cache_destroy(cache);
339 	}
340 
341 	for (size_t i = 0; i < n; i++) {
342 		VERIFY3P(zio_buf_cache[i], ==, NULL);
343 		VERIFY3P(zio_data_buf_cache[i], ==, NULL);
344 	}
345 
346 	if (zio_ksp != NULL) {
347 		kstat_delete(zio_ksp);
348 		zio_ksp = NULL;
349 	}
350 
351 	wmsum_fini(&ziostat_sums.ziostat_total_allocations);
352 	wmsum_fini(&ziostat_sums.ziostat_alloc_class_fallbacks);
353 	wmsum_fini(&ziostat_sums.ziostat_gang_writes);
354 	wmsum_fini(&ziostat_sums.ziostat_gang_multilevel);
355 
356 	kmem_cache_destroy(zio_link_cache);
357 	kmem_cache_destroy(zio_cache);
358 
359 	zio_inject_fini();
360 
361 	lz4_fini();
362 }
363 
364 /*
365  * ==========================================================================
366  * Allocate and free I/O buffers
367  * ==========================================================================
368  */
369 
370 #if defined(ZFS_DEBUG) && defined(_KERNEL)
371 #define	ZFS_ZIO_BUF_CANARY	1
372 #endif
373 
374 #ifdef ZFS_ZIO_BUF_CANARY
375 static const ulong_t zio_buf_canary = (ulong_t)0xdeadc0dedead210b;
376 
377 /*
378  * Use empty space after the buffer to detect overflows.
379  *
380  * Since zio_init() creates kmem caches only for certain set of buffer sizes,
381  * allocations of different sizes may have some unused space after the data.
382  * Filling part of that space with a known pattern on allocation and checking
383  * it on free should allow us to detect some buffer overflows.
384  */
385 static void
zio_buf_put_canary(ulong_t * p,size_t size,kmem_cache_t ** cache,size_t c)386 zio_buf_put_canary(ulong_t *p, size_t size, kmem_cache_t **cache, size_t c)
387 {
388 	size_t off = P2ROUNDUP(size, sizeof (ulong_t));
389 	ulong_t *canary = p + off / sizeof (ulong_t);
390 	size_t asize = (c + 1) << SPA_MINBLOCKSHIFT;
391 	if (c + 1 < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT &&
392 	    cache[c] == cache[c + 1])
393 		asize = (c + 2) << SPA_MINBLOCKSHIFT;
394 	for (; off < asize; canary++, off += sizeof (ulong_t))
395 		*canary = zio_buf_canary;
396 }
397 
398 static void
zio_buf_check_canary(ulong_t * p,size_t size,kmem_cache_t ** cache,size_t c)399 zio_buf_check_canary(ulong_t *p, size_t size, kmem_cache_t **cache, size_t c)
400 {
401 	size_t off = P2ROUNDUP(size, sizeof (ulong_t));
402 	ulong_t *canary = p + off / sizeof (ulong_t);
403 	size_t asize = (c + 1) << SPA_MINBLOCKSHIFT;
404 	if (c + 1 < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT &&
405 	    cache[c] == cache[c + 1])
406 		asize = (c + 2) << SPA_MINBLOCKSHIFT;
407 	for (; off < asize; canary++, off += sizeof (ulong_t)) {
408 		if (unlikely(*canary != zio_buf_canary)) {
409 			PANIC("ZIO buffer overflow %p (%zu) + %zu %#lx != %#lx",
410 			    p, size, (canary - p) * sizeof (ulong_t),
411 			    *canary, zio_buf_canary);
412 		}
413 	}
414 }
415 #endif
416 
417 /*
418  * Use zio_buf_alloc to allocate ZFS metadata.  This data will appear in a
419  * crashdump if the kernel panics, so use it judiciously.  Obviously, it's
420  * useful to inspect ZFS metadata, but if possible, we should avoid keeping
421  * excess / transient data in-core during a crashdump.
422  */
423 void *
zio_buf_alloc(size_t size)424 zio_buf_alloc(size_t size)
425 {
426 	size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
427 
428 	VERIFY3U(c, <, SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
429 #if defined(ZFS_DEBUG) && !defined(_KERNEL)
430 	atomic_add_64(&zio_buf_cache_allocs[c], 1);
431 #endif
432 
433 	void *p = kmem_cache_alloc(zio_buf_cache[c], KM_PUSHPAGE);
434 #ifdef ZFS_ZIO_BUF_CANARY
435 	zio_buf_put_canary(p, size, zio_buf_cache, c);
436 #endif
437 	return (p);
438 }
439 
440 /*
441  * Use zio_data_buf_alloc to allocate data.  The data will not appear in a
442  * crashdump if the kernel panics.  This exists so that we will limit the amount
443  * of ZFS data that shows up in a kernel crashdump.  (Thus reducing the amount
444  * of kernel heap dumped to disk when the kernel panics)
445  */
446 void *
zio_data_buf_alloc(size_t size)447 zio_data_buf_alloc(size_t size)
448 {
449 	size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
450 
451 	VERIFY3U(c, <, SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
452 
453 	void *p = kmem_cache_alloc(zio_data_buf_cache[c], KM_PUSHPAGE);
454 #ifdef ZFS_ZIO_BUF_CANARY
455 	zio_buf_put_canary(p, size, zio_data_buf_cache, c);
456 #endif
457 	return (p);
458 }
459 
460 void
zio_buf_free(void * buf,size_t size)461 zio_buf_free(void *buf, size_t size)
462 {
463 	size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
464 
465 	VERIFY3U(c, <, SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
466 #if defined(ZFS_DEBUG) && !defined(_KERNEL)
467 	atomic_add_64(&zio_buf_cache_frees[c], 1);
468 #endif
469 
470 #ifdef ZFS_ZIO_BUF_CANARY
471 	zio_buf_check_canary(buf, size, zio_buf_cache, c);
472 #endif
473 	kmem_cache_free(zio_buf_cache[c], buf);
474 }
475 
476 void
zio_data_buf_free(void * buf,size_t size)477 zio_data_buf_free(void *buf, size_t size)
478 {
479 	size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
480 
481 	VERIFY3U(c, <, SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
482 
483 #ifdef ZFS_ZIO_BUF_CANARY
484 	zio_buf_check_canary(buf, size, zio_data_buf_cache, c);
485 #endif
486 	kmem_cache_free(zio_data_buf_cache[c], buf);
487 }
488 
489 static void
zio_abd_free(void * abd,size_t size)490 zio_abd_free(void *abd, size_t size)
491 {
492 	(void) size;
493 	abd_free((abd_t *)abd);
494 }
495 
496 /*
497  * ==========================================================================
498  * Push and pop I/O transform buffers
499  * ==========================================================================
500  */
501 void
zio_push_transform(zio_t * zio,abd_t * data,uint64_t size,uint64_t bufsize,zio_transform_func_t * transform)502 zio_push_transform(zio_t *zio, abd_t *data, uint64_t size, uint64_t bufsize,
503     zio_transform_func_t *transform)
504 {
505 	zio_transform_t *zt = kmem_alloc(sizeof (zio_transform_t), KM_SLEEP);
506 
507 	zt->zt_orig_abd = zio->io_abd;
508 	zt->zt_orig_size = zio->io_size;
509 	zt->zt_bufsize = bufsize;
510 	zt->zt_transform = transform;
511 
512 	zt->zt_next = zio->io_transform_stack;
513 	zio->io_transform_stack = zt;
514 
515 	zio->io_abd = data;
516 	zio->io_size = size;
517 }
518 
519 void
zio_pop_transforms(zio_t * zio)520 zio_pop_transforms(zio_t *zio)
521 {
522 	zio_transform_t *zt;
523 
524 	while ((zt = zio->io_transform_stack) != NULL) {
525 		if (zt->zt_transform != NULL)
526 			zt->zt_transform(zio,
527 			    zt->zt_orig_abd, zt->zt_orig_size);
528 
529 		if (zt->zt_bufsize != 0)
530 			abd_free(zio->io_abd);
531 
532 		zio->io_abd = zt->zt_orig_abd;
533 		zio->io_size = zt->zt_orig_size;
534 		zio->io_transform_stack = zt->zt_next;
535 
536 		kmem_free(zt, sizeof (zio_transform_t));
537 	}
538 }
539 
540 /*
541  * ==========================================================================
542  * I/O transform callbacks for subblocks, decompression, and decryption
543  * ==========================================================================
544  */
545 static void
zio_subblock(zio_t * zio,abd_t * data,uint64_t size)546 zio_subblock(zio_t *zio, abd_t *data, uint64_t size)
547 {
548 	ASSERT(zio->io_size > size);
549 
550 	if (zio->io_type == ZIO_TYPE_READ)
551 		abd_copy(data, zio->io_abd, size);
552 }
553 
554 static void
zio_decompress(zio_t * zio,abd_t * data,uint64_t size)555 zio_decompress(zio_t *zio, abd_t *data, uint64_t size)
556 {
557 	if (zio->io_error == 0) {
558 		int ret = zio_decompress_data(BP_GET_COMPRESS(zio->io_bp),
559 		    zio->io_abd, data, zio->io_size, size,
560 		    &zio->io_prop.zp_complevel);
561 
562 		if (zio_injection_enabled && ret == 0)
563 			ret = zio_handle_fault_injection(zio, EINVAL);
564 
565 		if (ret != 0)
566 			zio->io_error = SET_ERROR(EIO);
567 	}
568 }
569 
570 static void
zio_decrypt(zio_t * zio,abd_t * data,uint64_t size)571 zio_decrypt(zio_t *zio, abd_t *data, uint64_t size)
572 {
573 	int ret;
574 	void *tmp;
575 	blkptr_t *bp = zio->io_bp;
576 	spa_t *spa = zio->io_spa;
577 	uint64_t dsobj = zio->io_bookmark.zb_objset;
578 	uint64_t lsize = BP_GET_LSIZE(bp);
579 	dmu_object_type_t ot = BP_GET_TYPE(bp);
580 	uint8_t salt[ZIO_DATA_SALT_LEN];
581 	uint8_t iv[ZIO_DATA_IV_LEN];
582 	uint8_t mac[ZIO_DATA_MAC_LEN];
583 	boolean_t no_crypt = B_FALSE;
584 
585 	ASSERT(BP_USES_CRYPT(bp));
586 	ASSERT3U(size, !=, 0);
587 
588 	if (zio->io_error != 0)
589 		return;
590 
591 	/*
592 	 * Verify the cksum of MACs stored in an indirect bp. It will always
593 	 * be possible to verify this since it does not require an encryption
594 	 * key.
595 	 */
596 	if (BP_HAS_INDIRECT_MAC_CKSUM(bp)) {
597 		zio_crypt_decode_mac_bp(bp, mac);
598 
599 		if (BP_GET_COMPRESS(bp) != ZIO_COMPRESS_OFF) {
600 			/*
601 			 * We haven't decompressed the data yet, but
602 			 * zio_crypt_do_indirect_mac_checksum() requires
603 			 * decompressed data to be able to parse out the MACs
604 			 * from the indirect block. We decompress it now and
605 			 * throw away the result after we are finished.
606 			 */
607 			abd_t *abd = abd_alloc_linear(lsize, B_TRUE);
608 			ret = zio_decompress_data(BP_GET_COMPRESS(bp),
609 			    zio->io_abd, abd, zio->io_size, lsize,
610 			    &zio->io_prop.zp_complevel);
611 			if (ret != 0) {
612 				abd_free(abd);
613 				ret = SET_ERROR(EIO);
614 				goto error;
615 			}
616 			ret = zio_crypt_do_indirect_mac_checksum_abd(B_FALSE,
617 			    abd, lsize, BP_SHOULD_BYTESWAP(bp), mac);
618 			abd_free(abd);
619 		} else {
620 			ret = zio_crypt_do_indirect_mac_checksum_abd(B_FALSE,
621 			    zio->io_abd, size, BP_SHOULD_BYTESWAP(bp), mac);
622 		}
623 		abd_copy(data, zio->io_abd, size);
624 
625 		if (zio_injection_enabled && ot != DMU_OT_DNODE && ret == 0) {
626 			ret = zio_handle_decrypt_injection(spa,
627 			    &zio->io_bookmark, ot, ECKSUM);
628 		}
629 		if (ret != 0)
630 			goto error;
631 
632 		return;
633 	}
634 
635 	/*
636 	 * If this is an authenticated block, just check the MAC. It would be
637 	 * nice to separate this out into its own flag, but when this was done,
638 	 * we had run out of bits in what is now zio_flag_t. Future cleanup
639 	 * could make this a flag bit.
640 	 */
641 	if (BP_IS_AUTHENTICATED(bp)) {
642 		if (ot == DMU_OT_OBJSET) {
643 			ret = spa_do_crypt_objset_mac_abd(B_FALSE, spa,
644 			    dsobj, zio->io_abd, size, BP_SHOULD_BYTESWAP(bp));
645 		} else {
646 			zio_crypt_decode_mac_bp(bp, mac);
647 			ret = spa_do_crypt_mac_abd(B_FALSE, spa, dsobj,
648 			    zio->io_abd, size, mac);
649 			if (zio_injection_enabled && ret == 0) {
650 				ret = zio_handle_decrypt_injection(spa,
651 				    &zio->io_bookmark, ot, ECKSUM);
652 			}
653 		}
654 		abd_copy(data, zio->io_abd, size);
655 
656 		if (ret != 0)
657 			goto error;
658 
659 		return;
660 	}
661 
662 	zio_crypt_decode_params_bp(bp, salt, iv);
663 
664 	if (ot == DMU_OT_INTENT_LOG) {
665 		tmp = abd_borrow_buf_copy(zio->io_abd, sizeof (zil_chain_t));
666 		zio_crypt_decode_mac_zil(tmp, mac);
667 		abd_return_buf(zio->io_abd, tmp, sizeof (zil_chain_t));
668 	} else {
669 		zio_crypt_decode_mac_bp(bp, mac);
670 	}
671 
672 	ret = spa_do_crypt_abd(B_FALSE, spa, &zio->io_bookmark, BP_GET_TYPE(bp),
673 	    BP_GET_DEDUP(bp), BP_SHOULD_BYTESWAP(bp), salt, iv, mac, size, data,
674 	    zio->io_abd, &no_crypt);
675 	if (no_crypt)
676 		abd_copy(data, zio->io_abd, size);
677 
678 	if (ret != 0)
679 		goto error;
680 
681 	return;
682 
683 error:
684 	/* assert that the key was found unless this was speculative */
685 	ASSERT(ret != EACCES || (zio->io_flags & ZIO_FLAG_SPECULATIVE));
686 
687 	/*
688 	 * If there was a decryption / authentication error return EIO as
689 	 * the io_error. If this was not a speculative zio, create an ereport.
690 	 */
691 	if (ret == ECKSUM) {
692 		zio->io_error = SET_ERROR(EIO);
693 		if ((zio->io_flags & ZIO_FLAG_SPECULATIVE) == 0) {
694 			spa_log_error(spa, &zio->io_bookmark,
695 			    BP_GET_LOGICAL_BIRTH(zio->io_bp));
696 			(void) zfs_ereport_post(FM_EREPORT_ZFS_AUTHENTICATION,
697 			    spa, NULL, &zio->io_bookmark, zio, 0);
698 		}
699 	} else {
700 		zio->io_error = ret;
701 	}
702 }
703 
704 /*
705  * ==========================================================================
706  * I/O parent/child relationships and pipeline interlocks
707  * ==========================================================================
708  */
709 zio_t *
zio_walk_parents(zio_t * cio,zio_link_t ** zl)710 zio_walk_parents(zio_t *cio, zio_link_t **zl)
711 {
712 	list_t *pl = &cio->io_parent_list;
713 
714 	*zl = (*zl == NULL) ? list_head(pl) : list_next(pl, *zl);
715 	if (*zl == NULL)
716 		return (NULL);
717 
718 	ASSERT((*zl)->zl_child == cio);
719 	return ((*zl)->zl_parent);
720 }
721 
722 zio_t *
zio_walk_children(zio_t * pio,zio_link_t ** zl)723 zio_walk_children(zio_t *pio, zio_link_t **zl)
724 {
725 	list_t *cl = &pio->io_child_list;
726 
727 	ASSERT(MUTEX_HELD(&pio->io_lock));
728 
729 	*zl = (*zl == NULL) ? list_head(cl) : list_next(cl, *zl);
730 	if (*zl == NULL)
731 		return (NULL);
732 
733 	ASSERT((*zl)->zl_parent == pio);
734 	return ((*zl)->zl_child);
735 }
736 
737 zio_t *
zio_unique_parent(zio_t * cio)738 zio_unique_parent(zio_t *cio)
739 {
740 	zio_link_t *zl = NULL;
741 	zio_t *pio = zio_walk_parents(cio, &zl);
742 
743 	VERIFY3P(zio_walk_parents(cio, &zl), ==, NULL);
744 	return (pio);
745 }
746 
747 static void
zio_add_child_impl(zio_t * pio,zio_t * cio,boolean_t first)748 zio_add_child_impl(zio_t *pio, zio_t *cio, boolean_t first)
749 {
750 	/*
751 	 * Logical I/Os can have logical, gang, or vdev children.
752 	 * Gang I/Os can have gang or vdev children.
753 	 * Vdev I/Os can only have vdev children.
754 	 * The following ASSERT captures all of these constraints.
755 	 */
756 	ASSERT3S(cio->io_child_type, <=, pio->io_child_type);
757 
758 	/* Parent should not have READY stage if child doesn't have it. */
759 	IMPLY((cio->io_pipeline & ZIO_STAGE_READY) == 0 &&
760 	    (cio->io_child_type != ZIO_CHILD_VDEV),
761 	    (pio->io_pipeline & ZIO_STAGE_READY) == 0);
762 
763 	zio_link_t *zl = kmem_cache_alloc(zio_link_cache, KM_SLEEP);
764 	zl->zl_parent = pio;
765 	zl->zl_child = cio;
766 
767 	mutex_enter(&pio->io_lock);
768 
769 	if (first)
770 		ASSERT(list_is_empty(&cio->io_parent_list));
771 	else
772 		mutex_enter(&cio->io_lock);
773 
774 	ASSERT(pio->io_state[ZIO_WAIT_DONE] == 0);
775 
776 	uint64_t *countp = pio->io_children[cio->io_child_type];
777 	for (int w = 0; w < ZIO_WAIT_TYPES; w++)
778 		countp[w] += !cio->io_state[w];
779 
780 	list_insert_head(&pio->io_child_list, zl);
781 	list_insert_head(&cio->io_parent_list, zl);
782 
783 	if (!first)
784 		mutex_exit(&cio->io_lock);
785 
786 	mutex_exit(&pio->io_lock);
787 }
788 
789 void
zio_add_child(zio_t * pio,zio_t * cio)790 zio_add_child(zio_t *pio, zio_t *cio)
791 {
792 	zio_add_child_impl(pio, cio, B_FALSE);
793 }
794 
795 static void
zio_add_child_first(zio_t * pio,zio_t * cio)796 zio_add_child_first(zio_t *pio, zio_t *cio)
797 {
798 	zio_add_child_impl(pio, cio, B_TRUE);
799 }
800 
801 static void
zio_remove_child(zio_t * pio,zio_t * cio,zio_link_t * zl)802 zio_remove_child(zio_t *pio, zio_t *cio, zio_link_t *zl)
803 {
804 	ASSERT(zl->zl_parent == pio);
805 	ASSERT(zl->zl_child == cio);
806 
807 	mutex_enter(&pio->io_lock);
808 	mutex_enter(&cio->io_lock);
809 
810 	list_remove(&pio->io_child_list, zl);
811 	list_remove(&cio->io_parent_list, zl);
812 
813 	mutex_exit(&cio->io_lock);
814 	mutex_exit(&pio->io_lock);
815 	kmem_cache_free(zio_link_cache, zl);
816 }
817 
818 static boolean_t
zio_wait_for_children(zio_t * zio,uint8_t childbits,enum zio_wait_type wait)819 zio_wait_for_children(zio_t *zio, uint8_t childbits, enum zio_wait_type wait)
820 {
821 	boolean_t waiting = B_FALSE;
822 
823 	mutex_enter(&zio->io_lock);
824 	ASSERT(zio->io_stall == NULL);
825 	for (int c = 0; c < ZIO_CHILD_TYPES; c++) {
826 		if (!(ZIO_CHILD_BIT_IS_SET(childbits, c)))
827 			continue;
828 
829 		uint64_t *countp = &zio->io_children[c][wait];
830 		if (*countp != 0) {
831 			zio->io_stage >>= 1;
832 			ASSERT3U(zio->io_stage, !=, ZIO_STAGE_OPEN);
833 			zio->io_stall = countp;
834 			waiting = B_TRUE;
835 			break;
836 		}
837 	}
838 	mutex_exit(&zio->io_lock);
839 	return (waiting);
840 }
841 
842 __attribute__((always_inline))
843 static inline void
zio_notify_parent(zio_t * pio,zio_t * zio,enum zio_wait_type wait,zio_t ** next_to_executep)844 zio_notify_parent(zio_t *pio, zio_t *zio, enum zio_wait_type wait,
845     zio_t **next_to_executep)
846 {
847 	uint64_t *countp = &pio->io_children[zio->io_child_type][wait];
848 	int *errorp = &pio->io_child_error[zio->io_child_type];
849 
850 	mutex_enter(&pio->io_lock);
851 	if (zio->io_error && !(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE))
852 		*errorp = zio_worst_error(*errorp, zio->io_error);
853 	pio->io_reexecute |= zio->io_reexecute;
854 	ASSERT3U(*countp, >, 0);
855 
856 	/*
857 	 * Propogate the Direct I/O checksum verify failure to the parent.
858 	 */
859 	if (zio->io_flags & ZIO_FLAG_DIO_CHKSUM_ERR)
860 		pio->io_flags |= ZIO_FLAG_DIO_CHKSUM_ERR;
861 
862 	(*countp)--;
863 
864 	if (*countp == 0 && pio->io_stall == countp) {
865 		zio_taskq_type_t type =
866 		    pio->io_stage < ZIO_STAGE_VDEV_IO_START ? ZIO_TASKQ_ISSUE :
867 		    ZIO_TASKQ_INTERRUPT;
868 		pio->io_stall = NULL;
869 		mutex_exit(&pio->io_lock);
870 
871 		/*
872 		 * If we can tell the caller to execute this parent next, do
873 		 * so. We do this if the parent's zio type matches the child's
874 		 * type, or if it's a zio_null() with no done callback, and so
875 		 * has no actual work to do. Otherwise dispatch the parent zio
876 		 * in its own taskq.
877 		 *
878 		 * Having the caller execute the parent when possible reduces
879 		 * locking on the zio taskq's, reduces context switch
880 		 * overhead, and has no recursion penalty.  Note that one
881 		 * read from disk typically causes at least 3 zio's: a
882 		 * zio_null(), the logical zio_read(), and then a physical
883 		 * zio.  When the physical ZIO completes, we are able to call
884 		 * zio_done() on all 3 of these zio's from one invocation of
885 		 * zio_execute() by returning the parent back to
886 		 * zio_execute().  Since the parent isn't executed until this
887 		 * thread returns back to zio_execute(), the caller should do
888 		 * so promptly.
889 		 *
890 		 * In other cases, dispatching the parent prevents
891 		 * overflowing the stack when we have deeply nested
892 		 * parent-child relationships, as we do with the "mega zio"
893 		 * of writes for spa_sync(), and the chain of ZIL blocks.
894 		 */
895 		if (next_to_executep != NULL && *next_to_executep == NULL &&
896 		    (pio->io_type == zio->io_type ||
897 		    (pio->io_type == ZIO_TYPE_NULL && !pio->io_done))) {
898 			*next_to_executep = pio;
899 		} else {
900 			zio_taskq_dispatch(pio, type, B_FALSE);
901 		}
902 	} else {
903 		mutex_exit(&pio->io_lock);
904 	}
905 }
906 
907 static void
zio_inherit_child_errors(zio_t * zio,enum zio_child c)908 zio_inherit_child_errors(zio_t *zio, enum zio_child c)
909 {
910 	if (zio->io_child_error[c] != 0 && zio->io_error == 0)
911 		zio->io_error = zio->io_child_error[c];
912 }
913 
914 int
zio_bookmark_compare(const void * x1,const void * x2)915 zio_bookmark_compare(const void *x1, const void *x2)
916 {
917 	const zio_t *z1 = x1;
918 	const zio_t *z2 = x2;
919 
920 	if (z1->io_bookmark.zb_objset < z2->io_bookmark.zb_objset)
921 		return (-1);
922 	if (z1->io_bookmark.zb_objset > z2->io_bookmark.zb_objset)
923 		return (1);
924 
925 	if (z1->io_bookmark.zb_object < z2->io_bookmark.zb_object)
926 		return (-1);
927 	if (z1->io_bookmark.zb_object > z2->io_bookmark.zb_object)
928 		return (1);
929 
930 	if (z1->io_bookmark.zb_level < z2->io_bookmark.zb_level)
931 		return (-1);
932 	if (z1->io_bookmark.zb_level > z2->io_bookmark.zb_level)
933 		return (1);
934 
935 	if (z1->io_bookmark.zb_blkid < z2->io_bookmark.zb_blkid)
936 		return (-1);
937 	if (z1->io_bookmark.zb_blkid > z2->io_bookmark.zb_blkid)
938 		return (1);
939 
940 	if (z1 < z2)
941 		return (-1);
942 	if (z1 > z2)
943 		return (1);
944 
945 	return (0);
946 }
947 
948 /*
949  * ==========================================================================
950  * Create the various types of I/O (read, write, free, etc)
951  * ==========================================================================
952  */
953 static zio_t *
zio_create(zio_t * pio,spa_t * spa,uint64_t txg,const blkptr_t * bp,abd_t * data,uint64_t lsize,uint64_t psize,zio_done_func_t * done,void * private,zio_type_t type,zio_priority_t priority,zio_flag_t flags,vdev_t * vd,uint64_t offset,const zbookmark_phys_t * zb,enum zio_stage stage,enum zio_stage pipeline)954 zio_create(zio_t *pio, spa_t *spa, uint64_t txg, const blkptr_t *bp,
955     abd_t *data, uint64_t lsize, uint64_t psize, zio_done_func_t *done,
956     void *private, zio_type_t type, zio_priority_t priority,
957     zio_flag_t flags, vdev_t *vd, uint64_t offset,
958     const zbookmark_phys_t *zb, enum zio_stage stage,
959     enum zio_stage pipeline)
960 {
961 	zio_t *zio;
962 
963 	IMPLY(type != ZIO_TYPE_TRIM, psize <= SPA_MAXBLOCKSIZE);
964 	ASSERT(P2PHASE(psize, SPA_MINBLOCKSIZE) == 0);
965 	ASSERT(P2PHASE(offset, SPA_MINBLOCKSIZE) == 0);
966 
967 	ASSERT(!vd || spa_config_held(spa, SCL_STATE_ALL, RW_READER));
968 	ASSERT(!bp || !(flags & ZIO_FLAG_CONFIG_WRITER));
969 	ASSERT(vd || stage == ZIO_STAGE_OPEN);
970 
971 	IMPLY(lsize != psize, (flags & ZIO_FLAG_RAW_COMPRESS) != 0);
972 
973 	zio = kmem_cache_alloc(zio_cache, KM_SLEEP);
974 	memset(zio, 0, sizeof (zio_t));
975 
976 	mutex_init(&zio->io_lock, NULL, MUTEX_NOLOCKDEP, NULL);
977 	cv_init(&zio->io_cv, NULL, CV_DEFAULT, NULL);
978 
979 	list_create(&zio->io_parent_list, sizeof (zio_link_t),
980 	    offsetof(zio_link_t, zl_parent_node));
981 	list_create(&zio->io_child_list, sizeof (zio_link_t),
982 	    offsetof(zio_link_t, zl_child_node));
983 	metaslab_trace_init(&zio->io_alloc_list);
984 
985 	if (vd != NULL)
986 		zio->io_child_type = ZIO_CHILD_VDEV;
987 	else if (flags & ZIO_FLAG_GANG_CHILD)
988 		zio->io_child_type = ZIO_CHILD_GANG;
989 	else if (flags & ZIO_FLAG_DDT_CHILD)
990 		zio->io_child_type = ZIO_CHILD_DDT;
991 	else
992 		zio->io_child_type = ZIO_CHILD_LOGICAL;
993 
994 	if (bp != NULL) {
995 		if (type != ZIO_TYPE_WRITE ||
996 		    zio->io_child_type == ZIO_CHILD_DDT) {
997 			zio->io_bp_copy = *bp;
998 			zio->io_bp = &zio->io_bp_copy;	/* so caller can free */
999 		} else {
1000 			zio->io_bp = (blkptr_t *)bp;
1001 		}
1002 		zio->io_bp_orig = *bp;
1003 		if (zio->io_child_type == ZIO_CHILD_LOGICAL)
1004 			zio->io_logical = zio;
1005 		if (zio->io_child_type > ZIO_CHILD_GANG && BP_IS_GANG(bp))
1006 			pipeline |= ZIO_GANG_STAGES;
1007 		if (flags & ZIO_FLAG_PREALLOCATED) {
1008 			BP_ZERO_DVAS(zio->io_bp);
1009 			BP_SET_BIRTH(zio->io_bp, 0, 0);
1010 		}
1011 	}
1012 
1013 	zio->io_spa = spa;
1014 	zio->io_txg = txg;
1015 	zio->io_done = done;
1016 	zio->io_private = private;
1017 	zio->io_type = type;
1018 	zio->io_priority = priority;
1019 	zio->io_vd = vd;
1020 	zio->io_offset = offset;
1021 	zio->io_orig_abd = zio->io_abd = data;
1022 	zio->io_orig_size = zio->io_size = psize;
1023 	zio->io_lsize = lsize;
1024 	zio->io_orig_flags = zio->io_flags = flags;
1025 	zio->io_orig_stage = zio->io_stage = stage;
1026 	zio->io_orig_pipeline = zio->io_pipeline = pipeline;
1027 	zio->io_pipeline_trace = ZIO_STAGE_OPEN;
1028 	zio->io_allocator = ZIO_ALLOCATOR_NONE;
1029 
1030 	zio->io_state[ZIO_WAIT_READY] = (stage >= ZIO_STAGE_READY) ||
1031 	    (pipeline & ZIO_STAGE_READY) == 0;
1032 	zio->io_state[ZIO_WAIT_DONE] = (stage >= ZIO_STAGE_DONE);
1033 
1034 	if (zb != NULL)
1035 		zio->io_bookmark = *zb;
1036 
1037 	if (pio != NULL) {
1038 		zio->io_metaslab_class = pio->io_metaslab_class;
1039 		if (zio->io_logical == NULL)
1040 			zio->io_logical = pio->io_logical;
1041 		if (zio->io_child_type == ZIO_CHILD_GANG)
1042 			zio->io_gang_leader = pio->io_gang_leader;
1043 		zio_add_child_first(pio, zio);
1044 	}
1045 
1046 	taskq_init_ent(&zio->io_tqent);
1047 
1048 	return (zio);
1049 }
1050 
1051 void
zio_destroy(zio_t * zio)1052 zio_destroy(zio_t *zio)
1053 {
1054 	metaslab_trace_fini(&zio->io_alloc_list);
1055 	list_destroy(&zio->io_parent_list);
1056 	list_destroy(&zio->io_child_list);
1057 	mutex_destroy(&zio->io_lock);
1058 	cv_destroy(&zio->io_cv);
1059 	kmem_cache_free(zio_cache, zio);
1060 }
1061 
1062 /*
1063  * ZIO intended to be between others.  Provides synchronization at READY
1064  * and DONE pipeline stages and calls the respective callbacks.
1065  */
1066 zio_t *
zio_null(zio_t * pio,spa_t * spa,vdev_t * vd,zio_done_func_t * done,void * private,zio_flag_t flags)1067 zio_null(zio_t *pio, spa_t *spa, vdev_t *vd, zio_done_func_t *done,
1068     void *private, zio_flag_t flags)
1069 {
1070 	zio_t *zio;
1071 
1072 	zio = zio_create(pio, spa, 0, NULL, NULL, 0, 0, done, private,
1073 	    ZIO_TYPE_NULL, ZIO_PRIORITY_NOW, flags, vd, 0, NULL,
1074 	    ZIO_STAGE_OPEN, ZIO_INTERLOCK_PIPELINE);
1075 
1076 	return (zio);
1077 }
1078 
1079 /*
1080  * ZIO intended to be a root of a tree.  Unlike null ZIO does not have a
1081  * READY pipeline stage (is ready on creation), so it should not be used
1082  * as child of any ZIO that may need waiting for grandchildren READY stage
1083  * (any other ZIO type).
1084  */
1085 zio_t *
zio_root(spa_t * spa,zio_done_func_t * done,void * private,zio_flag_t flags)1086 zio_root(spa_t *spa, zio_done_func_t *done, void *private, zio_flag_t flags)
1087 {
1088 	zio_t *zio;
1089 
1090 	zio = zio_create(NULL, spa, 0, NULL, NULL, 0, 0, done, private,
1091 	    ZIO_TYPE_NULL, ZIO_PRIORITY_NOW, flags, NULL, 0, NULL,
1092 	    ZIO_STAGE_OPEN, ZIO_ROOT_PIPELINE);
1093 
1094 	return (zio);
1095 }
1096 
1097 static int
zfs_blkptr_verify_log(spa_t * spa,const blkptr_t * bp,enum blk_verify_flag blk_verify,const char * fmt,...)1098 zfs_blkptr_verify_log(spa_t *spa, const blkptr_t *bp,
1099     enum blk_verify_flag blk_verify, const char *fmt, ...)
1100 {
1101 	va_list adx;
1102 	char buf[256];
1103 
1104 	va_start(adx, fmt);
1105 	(void) vsnprintf(buf, sizeof (buf), fmt, adx);
1106 	va_end(adx);
1107 
1108 	zfs_dbgmsg("bad blkptr at %px: "
1109 	    "DVA[0]=%#llx/%#llx "
1110 	    "DVA[1]=%#llx/%#llx "
1111 	    "DVA[2]=%#llx/%#llx "
1112 	    "prop=%#llx "
1113 	    "pad=%#llx,%#llx "
1114 	    "phys_birth=%#llx "
1115 	    "birth=%#llx "
1116 	    "fill=%#llx "
1117 	    "cksum=%#llx/%#llx/%#llx/%#llx",
1118 	    bp,
1119 	    (long long)bp->blk_dva[0].dva_word[0],
1120 	    (long long)bp->blk_dva[0].dva_word[1],
1121 	    (long long)bp->blk_dva[1].dva_word[0],
1122 	    (long long)bp->blk_dva[1].dva_word[1],
1123 	    (long long)bp->blk_dva[2].dva_word[0],
1124 	    (long long)bp->blk_dva[2].dva_word[1],
1125 	    (long long)bp->blk_prop,
1126 	    (long long)bp->blk_pad[0],
1127 	    (long long)bp->blk_pad[1],
1128 	    (long long)BP_GET_PHYSICAL_BIRTH(bp),
1129 	    (long long)BP_GET_LOGICAL_BIRTH(bp),
1130 	    (long long)bp->blk_fill,
1131 	    (long long)bp->blk_cksum.zc_word[0],
1132 	    (long long)bp->blk_cksum.zc_word[1],
1133 	    (long long)bp->blk_cksum.zc_word[2],
1134 	    (long long)bp->blk_cksum.zc_word[3]);
1135 	switch (blk_verify) {
1136 	case BLK_VERIFY_HALT:
1137 		zfs_panic_recover("%s: %s", spa_name(spa), buf);
1138 		break;
1139 	case BLK_VERIFY_LOG:
1140 		zfs_dbgmsg("%s: %s", spa_name(spa), buf);
1141 		break;
1142 	case BLK_VERIFY_ONLY:
1143 		break;
1144 	}
1145 
1146 	return (1);
1147 }
1148 
1149 /*
1150  * Verify the block pointer fields contain reasonable values.  This means
1151  * it only contains known object types, checksum/compression identifiers,
1152  * block sizes within the maximum allowed limits, valid DVAs, etc.
1153  *
1154  * If everything checks out 0 is returned.  The zfs_blkptr_verify
1155  * argument controls the behavior when an invalid field is detected.
1156  *
1157  * Values for blk_verify_flag:
1158  *   BLK_VERIFY_ONLY: evaluate the block
1159  *   BLK_VERIFY_LOG: evaluate the block and log problems
1160  *   BLK_VERIFY_HALT: call zfs_panic_recover on error
1161  *
1162  * Values for blk_config_flag:
1163  *   BLK_CONFIG_HELD: caller holds SCL_VDEV for writer
1164  *   BLK_CONFIG_NEEDED: caller holds no config lock, SCL_VDEV will be
1165  *   obtained for reader
1166  *   BLK_CONFIG_SKIP: skip checks which require SCL_VDEV, for better
1167  *   performance
1168  */
1169 int
zfs_blkptr_verify(spa_t * spa,const blkptr_t * bp,enum blk_config_flag blk_config,enum blk_verify_flag blk_verify)1170 zfs_blkptr_verify(spa_t *spa, const blkptr_t *bp,
1171     enum blk_config_flag blk_config, enum blk_verify_flag blk_verify)
1172 {
1173 	int errors = 0;
1174 
1175 	if (unlikely(!DMU_OT_IS_VALID(BP_GET_TYPE(bp)))) {
1176 		errors += zfs_blkptr_verify_log(spa, bp, blk_verify,
1177 		    "blkptr at %px has invalid TYPE %llu",
1178 		    bp, (longlong_t)BP_GET_TYPE(bp));
1179 	}
1180 	if (unlikely(BP_GET_COMPRESS(bp) >= ZIO_COMPRESS_FUNCTIONS)) {
1181 		errors += zfs_blkptr_verify_log(spa, bp, blk_verify,
1182 		    "blkptr at %px has invalid COMPRESS %llu",
1183 		    bp, (longlong_t)BP_GET_COMPRESS(bp));
1184 	}
1185 	if (unlikely(BP_GET_LSIZE(bp) > SPA_MAXBLOCKSIZE)) {
1186 		errors += zfs_blkptr_verify_log(spa, bp, blk_verify,
1187 		    "blkptr at %px has invalid LSIZE %llu",
1188 		    bp, (longlong_t)BP_GET_LSIZE(bp));
1189 	}
1190 	if (BP_IS_EMBEDDED(bp)) {
1191 		if (unlikely(BPE_GET_ETYPE(bp) >= NUM_BP_EMBEDDED_TYPES)) {
1192 			errors += zfs_blkptr_verify_log(spa, bp, blk_verify,
1193 			    "blkptr at %px has invalid ETYPE %llu",
1194 			    bp, (longlong_t)BPE_GET_ETYPE(bp));
1195 		}
1196 		if (unlikely(BPE_GET_PSIZE(bp) > BPE_PAYLOAD_SIZE)) {
1197 			errors += zfs_blkptr_verify_log(spa, bp, blk_verify,
1198 			    "blkptr at %px has invalid PSIZE %llu",
1199 			    bp, (longlong_t)BPE_GET_PSIZE(bp));
1200 		}
1201 		return (errors ? ECKSUM : 0);
1202 	} else if (BP_IS_HOLE(bp)) {
1203 		/*
1204 		 * Holes are allowed (expected, even) to have no DVAs, no
1205 		 * checksum, and no psize.
1206 		 */
1207 		return (errors ? ECKSUM : 0);
1208 	} else if (unlikely(!DVA_IS_VALID(&bp->blk_dva[0]))) {
1209 		/* Non-hole, non-embedded BPs _must_ have at least one DVA */
1210 		errors += zfs_blkptr_verify_log(spa, bp, blk_verify,
1211 		    "blkptr at %px has no valid DVAs", bp);
1212 	}
1213 	if (unlikely(BP_GET_CHECKSUM(bp) >= ZIO_CHECKSUM_FUNCTIONS)) {
1214 		errors += zfs_blkptr_verify_log(spa, bp, blk_verify,
1215 		    "blkptr at %px has invalid CHECKSUM %llu",
1216 		    bp, (longlong_t)BP_GET_CHECKSUM(bp));
1217 	}
1218 	if (unlikely(BP_GET_PSIZE(bp) > SPA_MAXBLOCKSIZE)) {
1219 		errors += zfs_blkptr_verify_log(spa, bp, blk_verify,
1220 		    "blkptr at %px has invalid PSIZE %llu",
1221 		    bp, (longlong_t)BP_GET_PSIZE(bp));
1222 	}
1223 
1224 	/*
1225 	 * Do not verify individual DVAs if the config is not trusted. This
1226 	 * will be done once the zio is executed in vdev_mirror_map_alloc.
1227 	 */
1228 	if (unlikely(!spa->spa_trust_config))
1229 		return (errors ? ECKSUM : 0);
1230 
1231 	switch (blk_config) {
1232 	case BLK_CONFIG_HELD:
1233 		ASSERT(spa_config_held(spa, SCL_VDEV, RW_WRITER));
1234 		break;
1235 	case BLK_CONFIG_NEEDED:
1236 		spa_config_enter(spa, SCL_VDEV, bp, RW_READER);
1237 		break;
1238 	case BLK_CONFIG_NEEDED_TRY:
1239 		if (!spa_config_tryenter(spa, SCL_VDEV, bp, RW_READER))
1240 			return (EBUSY);
1241 		break;
1242 	case BLK_CONFIG_SKIP:
1243 		return (errors ? ECKSUM : 0);
1244 	default:
1245 		panic("invalid blk_config %u", blk_config);
1246 	}
1247 
1248 	/*
1249 	 * Pool-specific checks.
1250 	 *
1251 	 * Note: it would be nice to verify that the logical birth
1252 	 * and physical birth are not too large.  However,
1253 	 * spa_freeze() allows the birth time of log blocks (and
1254 	 * dmu_sync()-ed blocks that are in the log) to be arbitrarily
1255 	 * large.
1256 	 */
1257 	for (int i = 0; i < BP_GET_NDVAS(bp); i++) {
1258 		const dva_t *dva = &bp->blk_dva[i];
1259 		uint64_t vdevid = DVA_GET_VDEV(dva);
1260 
1261 		if (unlikely(vdevid >= spa->spa_root_vdev->vdev_children)) {
1262 			errors += zfs_blkptr_verify_log(spa, bp, blk_verify,
1263 			    "blkptr at %px DVA %u has invalid VDEV %llu",
1264 			    bp, i, (longlong_t)vdevid);
1265 			continue;
1266 		}
1267 		vdev_t *vd = spa->spa_root_vdev->vdev_child[vdevid];
1268 		if (unlikely(vd == NULL)) {
1269 			errors += zfs_blkptr_verify_log(spa, bp, blk_verify,
1270 			    "blkptr at %px DVA %u has invalid VDEV %llu",
1271 			    bp, i, (longlong_t)vdevid);
1272 			continue;
1273 		}
1274 		if (unlikely(vd->vdev_ops == &vdev_hole_ops)) {
1275 			errors += zfs_blkptr_verify_log(spa, bp, blk_verify,
1276 			    "blkptr at %px DVA %u has hole VDEV %llu",
1277 			    bp, i, (longlong_t)vdevid);
1278 			continue;
1279 		}
1280 		if (vd->vdev_ops == &vdev_missing_ops) {
1281 			/*
1282 			 * "missing" vdevs are valid during import, but we
1283 			 * don't have their detailed info (e.g. asize), so
1284 			 * we can't perform any more checks on them.
1285 			 */
1286 			continue;
1287 		}
1288 		uint64_t offset = DVA_GET_OFFSET(dva);
1289 		uint64_t asize = DVA_GET_ASIZE(dva);
1290 		if (DVA_GET_GANG(dva))
1291 			asize = vdev_gang_header_asize(vd);
1292 		if (unlikely(offset + asize > vd->vdev_asize)) {
1293 			errors += zfs_blkptr_verify_log(spa, bp, blk_verify,
1294 			    "blkptr at %px DVA %u has invalid OFFSET %llu",
1295 			    bp, i, (longlong_t)offset);
1296 		}
1297 	}
1298 	if (blk_config == BLK_CONFIG_NEEDED || blk_config ==
1299 	    BLK_CONFIG_NEEDED_TRY)
1300 		spa_config_exit(spa, SCL_VDEV, bp);
1301 
1302 	return (errors ? ECKSUM : 0);
1303 }
1304 
1305 boolean_t
zfs_dva_valid(spa_t * spa,const dva_t * dva,const blkptr_t * bp)1306 zfs_dva_valid(spa_t *spa, const dva_t *dva, const blkptr_t *bp)
1307 {
1308 	(void) bp;
1309 	uint64_t vdevid = DVA_GET_VDEV(dva);
1310 
1311 	if (vdevid >= spa->spa_root_vdev->vdev_children)
1312 		return (B_FALSE);
1313 
1314 	vdev_t *vd = spa->spa_root_vdev->vdev_child[vdevid];
1315 	if (vd == NULL)
1316 		return (B_FALSE);
1317 
1318 	if (vd->vdev_ops == &vdev_hole_ops)
1319 		return (B_FALSE);
1320 
1321 	if (vd->vdev_ops == &vdev_missing_ops) {
1322 		return (B_FALSE);
1323 	}
1324 
1325 	uint64_t offset = DVA_GET_OFFSET(dva);
1326 	uint64_t asize = DVA_GET_ASIZE(dva);
1327 
1328 	if (DVA_GET_GANG(dva))
1329 		asize = vdev_gang_header_asize(vd);
1330 	if (offset + asize > vd->vdev_asize)
1331 		return (B_FALSE);
1332 
1333 	return (B_TRUE);
1334 }
1335 
1336 zio_t *
zio_read(zio_t * pio,spa_t * spa,const blkptr_t * bp,abd_t * data,uint64_t size,zio_done_func_t * done,void * private,zio_priority_t priority,zio_flag_t flags,const zbookmark_phys_t * zb)1337 zio_read(zio_t *pio, spa_t *spa, const blkptr_t *bp,
1338     abd_t *data, uint64_t size, zio_done_func_t *done, void *private,
1339     zio_priority_t priority, zio_flag_t flags, const zbookmark_phys_t *zb)
1340 {
1341 	zio_t *zio;
1342 
1343 	zio = zio_create(pio, spa, BP_GET_BIRTH(bp), bp,
1344 	    data, size, size, done, private,
1345 	    ZIO_TYPE_READ, priority, flags, NULL, 0, zb,
1346 	    ZIO_STAGE_OPEN, (flags & ZIO_FLAG_DDT_CHILD) ?
1347 	    ZIO_DDT_CHILD_READ_PIPELINE : ZIO_READ_PIPELINE);
1348 
1349 	return (zio);
1350 }
1351 
1352 zio_t *
zio_write(zio_t * pio,spa_t * spa,uint64_t txg,blkptr_t * bp,abd_t * data,uint64_t lsize,uint64_t psize,const zio_prop_t * zp,zio_done_func_t * ready,zio_done_func_t * children_ready,zio_done_func_t * done,void * private,zio_priority_t priority,zio_flag_t flags,const zbookmark_phys_t * zb)1353 zio_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
1354     abd_t *data, uint64_t lsize, uint64_t psize, const zio_prop_t *zp,
1355     zio_done_func_t *ready, zio_done_func_t *children_ready,
1356     zio_done_func_t *done, void *private, zio_priority_t priority,
1357     zio_flag_t flags, const zbookmark_phys_t *zb)
1358 {
1359 	zio_t *zio;
1360 	enum zio_stage pipeline = zp->zp_direct_write == B_TRUE ?
1361 	    ZIO_DIRECT_WRITE_PIPELINE : (flags & ZIO_FLAG_DDT_CHILD) ?
1362 	    ZIO_DDT_CHILD_WRITE_PIPELINE : ZIO_WRITE_PIPELINE;
1363 
1364 
1365 	zio = zio_create(pio, spa, txg, bp, data, lsize, psize, done, private,
1366 	    ZIO_TYPE_WRITE, priority, flags, NULL, 0, zb,
1367 	    ZIO_STAGE_OPEN, pipeline);
1368 
1369 	zio->io_ready = ready;
1370 	zio->io_children_ready = children_ready;
1371 	zio->io_prop = *zp;
1372 
1373 	/*
1374 	 * Data can be NULL if we are going to call zio_write_override() to
1375 	 * provide the already-allocated BP.  But we may need the data to
1376 	 * verify a dedup hit (if requested).  In this case, don't try to
1377 	 * dedup (just take the already-allocated BP verbatim). Encrypted
1378 	 * dedup blocks need data as well so we also disable dedup in this
1379 	 * case.
1380 	 */
1381 	if (data == NULL &&
1382 	    (zio->io_prop.zp_dedup_verify || zio->io_prop.zp_encrypt)) {
1383 		zio->io_prop.zp_dedup = zio->io_prop.zp_dedup_verify = B_FALSE;
1384 	}
1385 
1386 	return (zio);
1387 }
1388 
1389 zio_t *
zio_rewrite(zio_t * pio,spa_t * spa,uint64_t txg,blkptr_t * bp,abd_t * data,uint64_t size,zio_done_func_t * done,void * private,zio_priority_t priority,zio_flag_t flags,zbookmark_phys_t * zb)1390 zio_rewrite(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, abd_t *data,
1391     uint64_t size, zio_done_func_t *done, void *private,
1392     zio_priority_t priority, zio_flag_t flags, zbookmark_phys_t *zb)
1393 {
1394 	zio_t *zio;
1395 
1396 	zio = zio_create(pio, spa, txg, bp, data, size, size, done, private,
1397 	    ZIO_TYPE_WRITE, priority, flags | ZIO_FLAG_IO_REWRITE, NULL, 0, zb,
1398 	    ZIO_STAGE_OPEN, ZIO_REWRITE_PIPELINE);
1399 
1400 	return (zio);
1401 }
1402 
1403 void
zio_write_override(zio_t * zio,blkptr_t * bp,int copies,int gang_copies,boolean_t nopwrite,boolean_t brtwrite)1404 zio_write_override(zio_t *zio, blkptr_t *bp, int copies, int gang_copies,
1405     boolean_t nopwrite, boolean_t brtwrite)
1406 {
1407 	ASSERT(zio->io_type == ZIO_TYPE_WRITE);
1408 	ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1409 	ASSERT(zio->io_stage == ZIO_STAGE_OPEN);
1410 	ASSERT(zio->io_txg == spa_syncing_txg(zio->io_spa));
1411 	ASSERT(!brtwrite || !nopwrite);
1412 
1413 	/*
1414 	 * We must reset the io_prop to match the values that existed
1415 	 * when the bp was first written by dmu_sync() keeping in mind
1416 	 * that nopwrite and dedup are mutually exclusive.
1417 	 */
1418 	zio->io_prop.zp_dedup = nopwrite ? B_FALSE : zio->io_prop.zp_dedup;
1419 	zio->io_prop.zp_nopwrite = nopwrite;
1420 	zio->io_prop.zp_brtwrite = brtwrite;
1421 	zio->io_prop.zp_copies = copies;
1422 	zio->io_prop.zp_gang_copies = gang_copies;
1423 	zio->io_bp_override = bp;
1424 }
1425 
1426 void
zio_free(spa_t * spa,uint64_t txg,const blkptr_t * bp)1427 zio_free(spa_t *spa, uint64_t txg, const blkptr_t *bp)
1428 {
1429 
1430 	(void) zfs_blkptr_verify(spa, bp, BLK_CONFIG_NEEDED, BLK_VERIFY_HALT);
1431 
1432 	/*
1433 	 * The check for EMBEDDED is a performance optimization.  We
1434 	 * process the free here (by ignoring it) rather than
1435 	 * putting it on the list and then processing it in zio_free_sync().
1436 	 */
1437 	if (BP_IS_EMBEDDED(bp))
1438 		return;
1439 
1440 	/*
1441 	 * Frees that are for the currently-syncing txg, are not going to be
1442 	 * deferred, and which will not need to do a read (i.e. not GANG or
1443 	 * DEDUP), can be processed immediately.  Otherwise, put them on the
1444 	 * in-memory list for later processing.
1445 	 *
1446 	 * Note that we only defer frees after zfs_sync_pass_deferred_free
1447 	 * when the log space map feature is disabled. [see relevant comment
1448 	 * in spa_sync_iterate_to_convergence()]
1449 	 */
1450 	if (BP_IS_GANG(bp) ||
1451 	    BP_GET_DEDUP(bp) ||
1452 	    txg != spa->spa_syncing_txg ||
1453 	    (spa_sync_pass(spa) >= zfs_sync_pass_deferred_free &&
1454 	    !spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP)) ||
1455 	    brt_maybe_exists(spa, bp)) {
1456 		metaslab_check_free(spa, bp);
1457 		bplist_append(&spa->spa_free_bplist[txg & TXG_MASK], bp);
1458 	} else {
1459 		VERIFY3P(zio_free_sync(NULL, spa, txg, bp, 0), ==, NULL);
1460 	}
1461 }
1462 
1463 /*
1464  * To improve performance, this function may return NULL if we were able
1465  * to do the free immediately.  This avoids the cost of creating a zio
1466  * (and linking it to the parent, etc).
1467  */
1468 zio_t *
zio_free_sync(zio_t * pio,spa_t * spa,uint64_t txg,const blkptr_t * bp,zio_flag_t flags)1469 zio_free_sync(zio_t *pio, spa_t *spa, uint64_t txg, const blkptr_t *bp,
1470     zio_flag_t flags)
1471 {
1472 	ASSERT(!BP_IS_HOLE(bp));
1473 	ASSERT(spa_syncing_txg(spa) == txg);
1474 
1475 	if (BP_IS_EMBEDDED(bp))
1476 		return (NULL);
1477 
1478 	metaslab_check_free(spa, bp);
1479 	arc_freed(spa, bp);
1480 	dsl_scan_freed(spa, bp);
1481 
1482 	if (BP_IS_GANG(bp) ||
1483 	    BP_GET_DEDUP(bp) ||
1484 	    brt_maybe_exists(spa, bp)) {
1485 		/*
1486 		 * GANG, DEDUP and BRT blocks can induce a read (for the gang
1487 		 * block header, the DDT or the BRT), so issue them
1488 		 * asynchronously so that this thread is not tied up.
1489 		 */
1490 		enum zio_stage stage =
1491 		    ZIO_FREE_PIPELINE | ZIO_STAGE_ISSUE_ASYNC;
1492 
1493 		return (zio_create(pio, spa, txg, bp, NULL, BP_GET_PSIZE(bp),
1494 		    BP_GET_PSIZE(bp), NULL, NULL,
1495 		    ZIO_TYPE_FREE, ZIO_PRIORITY_NOW,
1496 		    flags, NULL, 0, NULL, ZIO_STAGE_OPEN, stage));
1497 	} else {
1498 		metaslab_free(spa, bp, txg, B_FALSE);
1499 		return (NULL);
1500 	}
1501 }
1502 
1503 zio_t *
zio_claim(zio_t * pio,spa_t * spa,uint64_t txg,const blkptr_t * bp,zio_done_func_t * done,void * private,zio_flag_t flags)1504 zio_claim(zio_t *pio, spa_t *spa, uint64_t txg, const blkptr_t *bp,
1505     zio_done_func_t *done, void *private, zio_flag_t flags)
1506 {
1507 	zio_t *zio;
1508 
1509 	(void) zfs_blkptr_verify(spa, bp, (flags & ZIO_FLAG_CONFIG_WRITER) ?
1510 	    BLK_CONFIG_HELD : BLK_CONFIG_NEEDED, BLK_VERIFY_HALT);
1511 
1512 	if (BP_IS_EMBEDDED(bp))
1513 		return (zio_null(pio, spa, NULL, NULL, NULL, 0));
1514 
1515 	/*
1516 	 * A claim is an allocation of a specific block.  Claims are needed
1517 	 * to support immediate writes in the intent log.  The issue is that
1518 	 * immediate writes contain committed data, but in a txg that was
1519 	 * *not* committed.  Upon opening the pool after an unclean shutdown,
1520 	 * the intent log claims all blocks that contain immediate write data
1521 	 * so that the SPA knows they're in use.
1522 	 *
1523 	 * All claims *must* be resolved in the first txg -- before the SPA
1524 	 * starts allocating blocks -- so that nothing is allocated twice.
1525 	 * If txg == 0 we just verify that the block is claimable.
1526 	 */
1527 	ASSERT3U(BP_GET_LOGICAL_BIRTH(&spa->spa_uberblock.ub_rootbp), <,
1528 	    spa_min_claim_txg(spa));
1529 	ASSERT(txg == spa_min_claim_txg(spa) || txg == 0);
1530 	ASSERT(!BP_GET_DEDUP(bp) || !spa_writeable(spa));	/* zdb(8) */
1531 
1532 	zio = zio_create(pio, spa, txg, bp, NULL, BP_GET_PSIZE(bp),
1533 	    BP_GET_PSIZE(bp), done, private, ZIO_TYPE_CLAIM, ZIO_PRIORITY_NOW,
1534 	    flags, NULL, 0, NULL, ZIO_STAGE_OPEN, ZIO_CLAIM_PIPELINE);
1535 	ASSERT0(zio->io_queued_timestamp);
1536 
1537 	return (zio);
1538 }
1539 
1540 zio_t *
zio_trim(zio_t * pio,vdev_t * vd,uint64_t offset,uint64_t size,zio_done_func_t * done,void * private,zio_priority_t priority,zio_flag_t flags,enum trim_flag trim_flags)1541 zio_trim(zio_t *pio, vdev_t *vd, uint64_t offset, uint64_t size,
1542     zio_done_func_t *done, void *private, zio_priority_t priority,
1543     zio_flag_t flags, enum trim_flag trim_flags)
1544 {
1545 	zio_t *zio;
1546 
1547 	ASSERT0(vd->vdev_children);
1548 	ASSERT0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
1549 	ASSERT0(P2PHASE(size, 1ULL << vd->vdev_ashift));
1550 	ASSERT3U(size, !=, 0);
1551 
1552 	zio = zio_create(pio, vd->vdev_spa, 0, NULL, NULL, size, size, done,
1553 	    private, ZIO_TYPE_TRIM, priority, flags | ZIO_FLAG_PHYSICAL,
1554 	    vd, offset, NULL, ZIO_STAGE_OPEN, ZIO_TRIM_PIPELINE);
1555 	zio->io_trim_flags = trim_flags;
1556 
1557 	return (zio);
1558 }
1559 
1560 zio_t *
zio_read_phys(zio_t * pio,vdev_t * vd,uint64_t offset,uint64_t size,abd_t * data,int checksum,zio_done_func_t * done,void * private,zio_priority_t priority,zio_flag_t flags,boolean_t labels)1561 zio_read_phys(zio_t *pio, vdev_t *vd, uint64_t offset, uint64_t size,
1562     abd_t *data, int checksum, zio_done_func_t *done, void *private,
1563     zio_priority_t priority, zio_flag_t flags, boolean_t labels)
1564 {
1565 	zio_t *zio;
1566 
1567 	ASSERT(vd->vdev_children == 0);
1568 	ASSERT(!labels || offset + size <= VDEV_LABEL_START_SIZE ||
1569 	    offset >= vd->vdev_psize - VDEV_LABEL_END_SIZE);
1570 	ASSERT3U(offset + size, <=, vd->vdev_psize);
1571 
1572 	zio = zio_create(pio, vd->vdev_spa, 0, NULL, data, size, size, done,
1573 	    private, ZIO_TYPE_READ, priority, flags | ZIO_FLAG_PHYSICAL, vd,
1574 	    offset, NULL, ZIO_STAGE_OPEN, ZIO_READ_PHYS_PIPELINE);
1575 
1576 	zio->io_prop.zp_checksum = checksum;
1577 
1578 	return (zio);
1579 }
1580 
1581 zio_t *
zio_write_phys(zio_t * pio,vdev_t * vd,uint64_t offset,uint64_t size,abd_t * data,int checksum,zio_done_func_t * done,void * private,zio_priority_t priority,zio_flag_t flags,boolean_t labels)1582 zio_write_phys(zio_t *pio, vdev_t *vd, uint64_t offset, uint64_t size,
1583     abd_t *data, int checksum, zio_done_func_t *done, void *private,
1584     zio_priority_t priority, zio_flag_t flags, boolean_t labels)
1585 {
1586 	zio_t *zio;
1587 
1588 	ASSERT(vd->vdev_children == 0);
1589 	ASSERT(!labels || offset + size <= VDEV_LABEL_START_SIZE ||
1590 	    offset >= vd->vdev_psize - VDEV_LABEL_END_SIZE);
1591 	ASSERT3U(offset + size, <=, vd->vdev_psize);
1592 
1593 	zio = zio_create(pio, vd->vdev_spa, 0, NULL, data, size, size, done,
1594 	    private, ZIO_TYPE_WRITE, priority, flags | ZIO_FLAG_PHYSICAL, vd,
1595 	    offset, NULL, ZIO_STAGE_OPEN, ZIO_WRITE_PHYS_PIPELINE);
1596 
1597 	zio->io_prop.zp_checksum = checksum;
1598 
1599 	if (zio_checksum_table[checksum].ci_flags & ZCHECKSUM_FLAG_EMBEDDED) {
1600 		/*
1601 		 * zec checksums are necessarily destructive -- they modify
1602 		 * the end of the write buffer to hold the verifier/checksum.
1603 		 * Therefore, we must make a local copy in case the data is
1604 		 * being written to multiple places in parallel.
1605 		 */
1606 		abd_t *wbuf = abd_alloc_sametype(data, size);
1607 		abd_copy(wbuf, data, size);
1608 
1609 		zio_push_transform(zio, wbuf, size, size, NULL);
1610 	}
1611 
1612 	return (zio);
1613 }
1614 
1615 /*
1616  * Create a child I/O to do some work for us.
1617  */
1618 zio_t *
zio_vdev_child_io(zio_t * pio,blkptr_t * bp,vdev_t * vd,uint64_t offset,abd_t * data,uint64_t size,int type,zio_priority_t priority,zio_flag_t flags,zio_done_func_t * done,void * private)1619 zio_vdev_child_io(zio_t *pio, blkptr_t *bp, vdev_t *vd, uint64_t offset,
1620     abd_t *data, uint64_t size, int type, zio_priority_t priority,
1621     zio_flag_t flags, zio_done_func_t *done, void *private)
1622 {
1623 	enum zio_stage pipeline = ZIO_VDEV_CHILD_PIPELINE;
1624 	zio_t *zio;
1625 
1626 	/*
1627 	 * vdev child I/Os do not propagate their error to the parent.
1628 	 * Therefore, for correct operation the caller *must* check for
1629 	 * and handle the error in the child i/o's done callback.
1630 	 * The only exceptions are i/os that we don't care about
1631 	 * (OPTIONAL or REPAIR).
1632 	 */
1633 	ASSERT((flags & ZIO_FLAG_OPTIONAL) || (flags & ZIO_FLAG_IO_REPAIR) ||
1634 	    done != NULL);
1635 
1636 	if (type == ZIO_TYPE_READ && bp != NULL) {
1637 		/*
1638 		 * If we have the bp, then the child should perform the
1639 		 * checksum and the parent need not.  This pushes error
1640 		 * detection as close to the leaves as possible and
1641 		 * eliminates redundant checksums in the interior nodes.
1642 		 */
1643 		pipeline |= ZIO_STAGE_CHECKSUM_VERIFY;
1644 		pio->io_pipeline &= ~ZIO_STAGE_CHECKSUM_VERIFY;
1645 		/*
1646 		 * We never allow the mirror VDEV to attempt reading from any
1647 		 * additional data copies after the first Direct I/O checksum
1648 		 * verify failure. This is to avoid bad data being written out
1649 		 * through the mirror during self healing. See comment in
1650 		 * vdev_mirror_io_done() for more details.
1651 		 */
1652 		ASSERT0(pio->io_flags & ZIO_FLAG_DIO_CHKSUM_ERR);
1653 	} else if (type == ZIO_TYPE_WRITE &&
1654 	    pio->io_prop.zp_direct_write == B_TRUE) {
1655 		/*
1656 		 * By default we only will verify checksums for Direct I/O
1657 		 * writes for Linux. FreeBSD is able to place user pages under
1658 		 * write protection before issuing them to the ZIO pipeline.
1659 		 *
1660 		 * Checksum validation errors will only be reported through
1661 		 * the top-level VDEV, which is set by this child ZIO.
1662 		 */
1663 		ASSERT3P(bp, !=, NULL);
1664 		ASSERT3U(pio->io_child_type, ==, ZIO_CHILD_LOGICAL);
1665 		pipeline |= ZIO_STAGE_DIO_CHECKSUM_VERIFY;
1666 	}
1667 
1668 	if (vd->vdev_ops->vdev_op_leaf) {
1669 		ASSERT0(vd->vdev_children);
1670 		offset += VDEV_LABEL_START_SIZE;
1671 	}
1672 
1673 	flags |= ZIO_VDEV_CHILD_FLAGS(pio);
1674 
1675 	/*
1676 	 * If we've decided to do a repair, the write is not speculative --
1677 	 * even if the original read was.
1678 	 */
1679 	if (flags & ZIO_FLAG_IO_REPAIR)
1680 		flags &= ~ZIO_FLAG_SPECULATIVE;
1681 
1682 	/*
1683 	 * If we're creating a child I/O that is not associated with a
1684 	 * top-level vdev, then the child zio is not an allocating I/O.
1685 	 * If this is a retried I/O then we ignore it since we will
1686 	 * have already processed the original allocating I/O.
1687 	 */
1688 	if (flags & ZIO_FLAG_IO_ALLOCATING &&
1689 	    (vd != vd->vdev_top || (flags & ZIO_FLAG_IO_RETRY))) {
1690 		ASSERT(pio->io_metaslab_class != NULL);
1691 		ASSERT(pio->io_metaslab_class->mc_alloc_throttle_enabled);
1692 		ASSERT(type == ZIO_TYPE_WRITE);
1693 		ASSERT(priority == ZIO_PRIORITY_ASYNC_WRITE);
1694 		ASSERT(!(flags & ZIO_FLAG_IO_REPAIR));
1695 		ASSERT(!(pio->io_flags & ZIO_FLAG_IO_REWRITE) ||
1696 		    pio->io_child_type == ZIO_CHILD_GANG);
1697 
1698 		flags &= ~ZIO_FLAG_IO_ALLOCATING;
1699 	}
1700 
1701 	zio = zio_create(pio, pio->io_spa, pio->io_txg, bp, data, size, size,
1702 	    done, private, type, priority, flags, vd, offset, &pio->io_bookmark,
1703 	    ZIO_STAGE_VDEV_IO_START >> 1, pipeline);
1704 	ASSERT3U(zio->io_child_type, ==, ZIO_CHILD_VDEV);
1705 
1706 	return (zio);
1707 }
1708 
1709 zio_t *
zio_vdev_delegated_io(vdev_t * vd,uint64_t offset,abd_t * data,uint64_t size,zio_type_t type,zio_priority_t priority,zio_flag_t flags,zio_done_func_t * done,void * private)1710 zio_vdev_delegated_io(vdev_t *vd, uint64_t offset, abd_t *data, uint64_t size,
1711     zio_type_t type, zio_priority_t priority, zio_flag_t flags,
1712     zio_done_func_t *done, void *private)
1713 {
1714 	zio_t *zio;
1715 
1716 	ASSERT(vd->vdev_ops->vdev_op_leaf);
1717 
1718 	zio = zio_create(NULL, vd->vdev_spa, 0, NULL,
1719 	    data, size, size, done, private, type, priority,
1720 	    flags | ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_RETRY | ZIO_FLAG_DELEGATED,
1721 	    vd, offset, NULL,
1722 	    ZIO_STAGE_VDEV_IO_START >> 1, ZIO_VDEV_CHILD_PIPELINE);
1723 
1724 	return (zio);
1725 }
1726 
1727 
1728 /*
1729  * Send a flush command to the given vdev. Unlike most zio creation functions,
1730  * the flush zios are issued immediately. You can wait on pio to pause until
1731  * the flushes complete.
1732  */
1733 void
zio_flush(zio_t * pio,vdev_t * vd)1734 zio_flush(zio_t *pio, vdev_t *vd)
1735 {
1736 	const zio_flag_t flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE |
1737 	    ZIO_FLAG_DONT_RETRY;
1738 
1739 	if (vd->vdev_nowritecache)
1740 		return;
1741 
1742 	if (vd->vdev_children == 0) {
1743 		zio_nowait(zio_create(pio, vd->vdev_spa, 0, NULL, NULL, 0, 0,
1744 		    NULL, NULL, ZIO_TYPE_FLUSH, ZIO_PRIORITY_NOW, flags, vd, 0,
1745 		    NULL, ZIO_STAGE_OPEN, ZIO_FLUSH_PIPELINE));
1746 	} else {
1747 		for (uint64_t c = 0; c < vd->vdev_children; c++)
1748 			zio_flush(pio, vd->vdev_child[c]);
1749 	}
1750 }
1751 
1752 void
zio_shrink(zio_t * zio,uint64_t size)1753 zio_shrink(zio_t *zio, uint64_t size)
1754 {
1755 	ASSERT3P(zio->io_executor, ==, NULL);
1756 	ASSERT3U(zio->io_orig_size, ==, zio->io_size);
1757 	ASSERT3U(size, <=, zio->io_size);
1758 
1759 	/*
1760 	 * We don't shrink for raidz because of problems with the
1761 	 * reconstruction when reading back less than the block size.
1762 	 * Note, BP_IS_RAIDZ() assumes no compression.
1763 	 */
1764 	ASSERT(BP_GET_COMPRESS(zio->io_bp) == ZIO_COMPRESS_OFF);
1765 	if (!BP_IS_RAIDZ(zio->io_bp)) {
1766 		/* we are not doing a raw write */
1767 		ASSERT3U(zio->io_size, ==, zio->io_lsize);
1768 		zio->io_orig_size = zio->io_size = zio->io_lsize = size;
1769 	}
1770 }
1771 
1772 /*
1773  * Round provided allocation size up to a value that can be allocated
1774  * by at least some vdev(s) in the pool with minimum or no additional
1775  * padding and without extra space usage on others
1776  */
1777 static uint64_t
zio_roundup_alloc_size(spa_t * spa,uint64_t size)1778 zio_roundup_alloc_size(spa_t *spa, uint64_t size)
1779 {
1780 	if (size > spa->spa_min_alloc)
1781 		return (roundup(size, spa->spa_gcd_alloc));
1782 	return (spa->spa_min_alloc);
1783 }
1784 
1785 size_t
zio_get_compression_max_size(enum zio_compress compress,uint64_t gcd_alloc,uint64_t min_alloc,size_t s_len)1786 zio_get_compression_max_size(enum zio_compress compress, uint64_t gcd_alloc,
1787     uint64_t min_alloc, size_t s_len)
1788 {
1789 	size_t d_len;
1790 
1791 	/* minimum 12.5% must be saved (legacy value, may be changed later) */
1792 	d_len = s_len - (s_len >> 3);
1793 
1794 	/* ZLE can't use exactly d_len bytes, it needs more, so ignore it */
1795 	if (compress == ZIO_COMPRESS_ZLE)
1796 		return (d_len);
1797 
1798 	d_len = d_len - d_len % gcd_alloc;
1799 
1800 	if (d_len < min_alloc)
1801 		return (BPE_PAYLOAD_SIZE);
1802 	return (d_len);
1803 }
1804 
1805 /*
1806  * ==========================================================================
1807  * Prepare to read and write logical blocks
1808  * ==========================================================================
1809  */
1810 
1811 static zio_t *
zio_read_bp_init(zio_t * zio)1812 zio_read_bp_init(zio_t *zio)
1813 {
1814 	blkptr_t *bp = zio->io_bp;
1815 	uint64_t psize =
1816 	    BP_IS_EMBEDDED(bp) ? BPE_GET_PSIZE(bp) : BP_GET_PSIZE(bp);
1817 
1818 	ASSERT3P(zio->io_bp, ==, &zio->io_bp_copy);
1819 
1820 	if (BP_GET_COMPRESS(bp) != ZIO_COMPRESS_OFF &&
1821 	    zio->io_child_type == ZIO_CHILD_LOGICAL &&
1822 	    !(zio->io_flags & ZIO_FLAG_RAW_COMPRESS)) {
1823 		zio_push_transform(zio, abd_alloc_sametype(zio->io_abd, psize),
1824 		    psize, psize, zio_decompress);
1825 	}
1826 
1827 	if (((BP_IS_PROTECTED(bp) && !(zio->io_flags & ZIO_FLAG_RAW_ENCRYPT)) ||
1828 	    BP_HAS_INDIRECT_MAC_CKSUM(bp)) &&
1829 	    zio->io_child_type == ZIO_CHILD_LOGICAL) {
1830 		zio_push_transform(zio, abd_alloc_sametype(zio->io_abd, psize),
1831 		    psize, psize, zio_decrypt);
1832 	}
1833 
1834 	if (BP_IS_EMBEDDED(bp) && BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA) {
1835 		int psize = BPE_GET_PSIZE(bp);
1836 		void *data = abd_borrow_buf(zio->io_abd, psize);
1837 
1838 		zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1839 		decode_embedded_bp_compressed(bp, data);
1840 		abd_return_buf_copy(zio->io_abd, data, psize);
1841 	} else {
1842 		ASSERT(!BP_IS_EMBEDDED(bp));
1843 	}
1844 
1845 	if (BP_GET_DEDUP(bp) && zio->io_child_type == ZIO_CHILD_LOGICAL)
1846 		zio->io_pipeline = ZIO_DDT_READ_PIPELINE;
1847 
1848 	return (zio);
1849 }
1850 
1851 static zio_t *
zio_write_bp_init(zio_t * zio)1852 zio_write_bp_init(zio_t *zio)
1853 {
1854 	if (!IO_IS_ALLOCATING(zio))
1855 		return (zio);
1856 
1857 	ASSERT(zio->io_child_type != ZIO_CHILD_DDT);
1858 
1859 	if (zio->io_bp_override) {
1860 		blkptr_t *bp = zio->io_bp;
1861 		zio_prop_t *zp = &zio->io_prop;
1862 
1863 		ASSERT(BP_GET_LOGICAL_BIRTH(bp) != zio->io_txg);
1864 
1865 		*bp = *zio->io_bp_override;
1866 		zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1867 
1868 		if (zp->zp_brtwrite)
1869 			return (zio);
1870 
1871 		ASSERT(!BP_GET_DEDUP(zio->io_bp_override));
1872 
1873 		if (BP_IS_EMBEDDED(bp))
1874 			return (zio);
1875 
1876 		/*
1877 		 * If we've been overridden and nopwrite is set then
1878 		 * set the flag accordingly to indicate that a nopwrite
1879 		 * has already occurred.
1880 		 */
1881 		if (!BP_IS_HOLE(bp) && zp->zp_nopwrite) {
1882 			ASSERT(!zp->zp_dedup);
1883 			ASSERT3U(BP_GET_CHECKSUM(bp), ==, zp->zp_checksum);
1884 			zio->io_flags |= ZIO_FLAG_NOPWRITE;
1885 			return (zio);
1886 		}
1887 
1888 		ASSERT(!zp->zp_nopwrite);
1889 
1890 		if (BP_IS_HOLE(bp) || !zp->zp_dedup)
1891 			return (zio);
1892 
1893 		ASSERT((zio_checksum_table[zp->zp_checksum].ci_flags &
1894 		    ZCHECKSUM_FLAG_DEDUP) || zp->zp_dedup_verify);
1895 
1896 		if (BP_GET_CHECKSUM(bp) == zp->zp_checksum &&
1897 		    !zp->zp_encrypt) {
1898 			BP_SET_DEDUP(bp, 1);
1899 			zio->io_pipeline |= ZIO_STAGE_DDT_WRITE;
1900 			return (zio);
1901 		}
1902 
1903 		/*
1904 		 * We were unable to handle this as an override bp, treat
1905 		 * it as a regular write I/O.
1906 		 */
1907 		zio->io_bp_override = NULL;
1908 		*bp = zio->io_bp_orig;
1909 		zio->io_pipeline = zio->io_orig_pipeline;
1910 	}
1911 
1912 	return (zio);
1913 }
1914 
1915 static zio_t *
zio_write_compress(zio_t * zio)1916 zio_write_compress(zio_t *zio)
1917 {
1918 	spa_t *spa = zio->io_spa;
1919 	zio_prop_t *zp = &zio->io_prop;
1920 	enum zio_compress compress = zp->zp_compress;
1921 	blkptr_t *bp = zio->io_bp;
1922 	uint64_t lsize = zio->io_lsize;
1923 	uint64_t psize = zio->io_size;
1924 	uint32_t pass = 1;
1925 
1926 	/*
1927 	 * If our children haven't all reached the ready stage,
1928 	 * wait for them and then repeat this pipeline stage.
1929 	 */
1930 	if (zio_wait_for_children(zio, ZIO_CHILD_LOGICAL_BIT |
1931 	    ZIO_CHILD_GANG_BIT, ZIO_WAIT_READY)) {
1932 		return (NULL);
1933 	}
1934 
1935 	if (!IO_IS_ALLOCATING(zio))
1936 		return (zio);
1937 
1938 	if (zio->io_children_ready != NULL) {
1939 		/*
1940 		 * Now that all our children are ready, run the callback
1941 		 * associated with this zio in case it wants to modify the
1942 		 * data to be written.
1943 		 */
1944 		ASSERT3U(zp->zp_level, >, 0);
1945 		zio->io_children_ready(zio);
1946 	}
1947 
1948 	ASSERT(zio->io_child_type != ZIO_CHILD_DDT);
1949 	ASSERT(zio->io_bp_override == NULL);
1950 
1951 	if (!BP_IS_HOLE(bp) && BP_GET_LOGICAL_BIRTH(bp) == zio->io_txg) {
1952 		/*
1953 		 * We're rewriting an existing block, which means we're
1954 		 * working on behalf of spa_sync().  For spa_sync() to
1955 		 * converge, it must eventually be the case that we don't
1956 		 * have to allocate new blocks.  But compression changes
1957 		 * the blocksize, which forces a reallocate, and makes
1958 		 * convergence take longer.  Therefore, after the first
1959 		 * few passes, stop compressing to ensure convergence.
1960 		 */
1961 		pass = spa_sync_pass(spa);
1962 
1963 		ASSERT(zio->io_txg == spa_syncing_txg(spa));
1964 		ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1965 		ASSERT(!BP_GET_DEDUP(bp));
1966 
1967 		if (pass >= zfs_sync_pass_dont_compress)
1968 			compress = ZIO_COMPRESS_OFF;
1969 
1970 		/* Make sure someone doesn't change their mind on overwrites */
1971 		ASSERT(BP_IS_EMBEDDED(bp) || BP_IS_GANG(bp) ||
1972 		    MIN(zp->zp_copies, spa_max_replication(spa))
1973 		    == BP_GET_NDVAS(bp));
1974 	}
1975 
1976 	/* If it's a compressed write that is not raw, compress the buffer. */
1977 	if (compress != ZIO_COMPRESS_OFF &&
1978 	    !(zio->io_flags & ZIO_FLAG_RAW_COMPRESS)) {
1979 		abd_t *cabd = NULL;
1980 		if (abd_cmp_zero(zio->io_abd, lsize) == 0)
1981 			psize = 0;
1982 		else if (compress == ZIO_COMPRESS_EMPTY)
1983 			psize = lsize;
1984 		else
1985 			psize = zio_compress_data(compress, zio->io_abd, &cabd,
1986 			    lsize,
1987 			    zio_get_compression_max_size(compress,
1988 			    spa->spa_gcd_alloc, spa->spa_min_alloc, lsize),
1989 			    zp->zp_complevel);
1990 		if (psize == 0) {
1991 			compress = ZIO_COMPRESS_OFF;
1992 		} else if (psize >= lsize) {
1993 			compress = ZIO_COMPRESS_OFF;
1994 			if (cabd != NULL)
1995 				abd_free(cabd);
1996 		} else if (psize <= BPE_PAYLOAD_SIZE && !zp->zp_encrypt &&
1997 		    zp->zp_level == 0 && !DMU_OT_HAS_FILL(zp->zp_type) &&
1998 		    spa_feature_is_enabled(spa, SPA_FEATURE_EMBEDDED_DATA)) {
1999 			void *cbuf = abd_borrow_buf_copy(cabd, lsize);
2000 			encode_embedded_bp_compressed(bp,
2001 			    cbuf, compress, lsize, psize);
2002 			BPE_SET_ETYPE(bp, BP_EMBEDDED_TYPE_DATA);
2003 			BP_SET_TYPE(bp, zio->io_prop.zp_type);
2004 			BP_SET_LEVEL(bp, zio->io_prop.zp_level);
2005 			abd_return_buf(cabd, cbuf, lsize);
2006 			abd_free(cabd);
2007 			BP_SET_LOGICAL_BIRTH(bp, zio->io_txg);
2008 			zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
2009 			ASSERT(spa_feature_is_active(spa,
2010 			    SPA_FEATURE_EMBEDDED_DATA));
2011 			return (zio);
2012 		} else {
2013 			/*
2014 			 * Round compressed size up to the minimum allocation
2015 			 * size of the smallest-ashift device, and zero the
2016 			 * tail. This ensures that the compressed size of the
2017 			 * BP (and thus compressratio property) are correct,
2018 			 * in that we charge for the padding used to fill out
2019 			 * the last sector.
2020 			 */
2021 			size_t rounded = (size_t)zio_roundup_alloc_size(spa,
2022 			    psize);
2023 			if (rounded >= lsize) {
2024 				compress = ZIO_COMPRESS_OFF;
2025 				abd_free(cabd);
2026 				psize = lsize;
2027 			} else {
2028 				abd_zero_off(cabd, psize, rounded - psize);
2029 				psize = rounded;
2030 				zio_push_transform(zio, cabd,
2031 				    psize, lsize, NULL);
2032 			}
2033 		}
2034 
2035 		/*
2036 		 * We were unable to handle this as an override bp, treat
2037 		 * it as a regular write I/O.
2038 		 */
2039 		zio->io_bp_override = NULL;
2040 		*bp = zio->io_bp_orig;
2041 		zio->io_pipeline = zio->io_orig_pipeline;
2042 
2043 	} else if ((zio->io_flags & ZIO_FLAG_RAW_ENCRYPT) != 0 &&
2044 	    zp->zp_type == DMU_OT_DNODE) {
2045 		/*
2046 		 * The DMU actually relies on the zio layer's compression
2047 		 * to free metadnode blocks that have had all contained
2048 		 * dnodes freed. As a result, even when doing a raw
2049 		 * receive, we must check whether the block can be compressed
2050 		 * to a hole.
2051 		 */
2052 		if (abd_cmp_zero(zio->io_abd, lsize) == 0) {
2053 			psize = 0;
2054 			compress = ZIO_COMPRESS_OFF;
2055 		} else {
2056 			psize = lsize;
2057 		}
2058 	} else if (zio->io_flags & ZIO_FLAG_RAW_COMPRESS &&
2059 	    !(zio->io_flags & ZIO_FLAG_RAW_ENCRYPT)) {
2060 		/*
2061 		 * If we are raw receiving an encrypted dataset we should not
2062 		 * take this codepath because it will change the on-disk block
2063 		 * and decryption will fail.
2064 		 */
2065 		size_t rounded = MIN((size_t)zio_roundup_alloc_size(spa, psize),
2066 		    lsize);
2067 
2068 		if (rounded != psize) {
2069 			abd_t *cdata = abd_alloc_linear(rounded, B_TRUE);
2070 			abd_zero_off(cdata, psize, rounded - psize);
2071 			abd_copy_off(cdata, zio->io_abd, 0, 0, psize);
2072 			psize = rounded;
2073 			zio_push_transform(zio, cdata,
2074 			    psize, rounded, NULL);
2075 		}
2076 	} else {
2077 		ASSERT3U(psize, !=, 0);
2078 	}
2079 
2080 	/*
2081 	 * The final pass of spa_sync() must be all rewrites, but the first
2082 	 * few passes offer a trade-off: allocating blocks defers convergence,
2083 	 * but newly allocated blocks are sequential, so they can be written
2084 	 * to disk faster.  Therefore, we allow the first few passes of
2085 	 * spa_sync() to allocate new blocks, but force rewrites after that.
2086 	 * There should only be a handful of blocks after pass 1 in any case.
2087 	 */
2088 	if (!BP_IS_HOLE(bp) && BP_GET_LOGICAL_BIRTH(bp) == zio->io_txg &&
2089 	    BP_GET_PSIZE(bp) == psize &&
2090 	    pass >= zfs_sync_pass_rewrite) {
2091 		VERIFY3U(psize, !=, 0);
2092 		enum zio_stage gang_stages = zio->io_pipeline & ZIO_GANG_STAGES;
2093 
2094 		zio->io_pipeline = ZIO_REWRITE_PIPELINE | gang_stages;
2095 		zio->io_flags |= ZIO_FLAG_IO_REWRITE;
2096 	} else {
2097 		BP_ZERO(bp);
2098 		zio->io_pipeline = ZIO_WRITE_PIPELINE;
2099 	}
2100 
2101 	if (psize == 0) {
2102 		if (BP_GET_LOGICAL_BIRTH(&zio->io_bp_orig) != 0 &&
2103 		    spa_feature_is_active(spa, SPA_FEATURE_HOLE_BIRTH)) {
2104 			BP_SET_LSIZE(bp, lsize);
2105 			BP_SET_TYPE(bp, zp->zp_type);
2106 			BP_SET_LEVEL(bp, zp->zp_level);
2107 			BP_SET_BIRTH(bp, zio->io_txg, 0);
2108 		}
2109 		zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
2110 	} else {
2111 		ASSERT(zp->zp_checksum != ZIO_CHECKSUM_GANG_HEADER);
2112 		BP_SET_LSIZE(bp, lsize);
2113 		BP_SET_TYPE(bp, zp->zp_type);
2114 		BP_SET_LEVEL(bp, zp->zp_level);
2115 		BP_SET_PSIZE(bp, psize);
2116 		BP_SET_COMPRESS(bp, compress);
2117 		BP_SET_CHECKSUM(bp, zp->zp_checksum);
2118 		BP_SET_DEDUP(bp, zp->zp_dedup);
2119 		BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
2120 		if (zp->zp_dedup) {
2121 			ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
2122 			ASSERT(!(zio->io_flags & ZIO_FLAG_IO_REWRITE));
2123 			ASSERT(!zp->zp_encrypt ||
2124 			    DMU_OT_IS_ENCRYPTED(zp->zp_type));
2125 			zio->io_pipeline = ZIO_DDT_WRITE_PIPELINE;
2126 		}
2127 		if (zp->zp_nopwrite) {
2128 			ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
2129 			ASSERT(!(zio->io_flags & ZIO_FLAG_IO_REWRITE));
2130 			zio->io_pipeline |= ZIO_STAGE_NOP_WRITE;
2131 		}
2132 	}
2133 	return (zio);
2134 }
2135 
2136 static zio_t *
zio_free_bp_init(zio_t * zio)2137 zio_free_bp_init(zio_t *zio)
2138 {
2139 	blkptr_t *bp = zio->io_bp;
2140 
2141 	if (zio->io_child_type == ZIO_CHILD_LOGICAL) {
2142 		if (BP_GET_DEDUP(bp))
2143 			zio->io_pipeline = ZIO_DDT_FREE_PIPELINE;
2144 	}
2145 
2146 	ASSERT3P(zio->io_bp, ==, &zio->io_bp_copy);
2147 
2148 	return (zio);
2149 }
2150 
2151 /*
2152  * ==========================================================================
2153  * Execute the I/O pipeline
2154  * ==========================================================================
2155  */
2156 
2157 static void
zio_taskq_dispatch(zio_t * zio,zio_taskq_type_t q,boolean_t cutinline)2158 zio_taskq_dispatch(zio_t *zio, zio_taskq_type_t q, boolean_t cutinline)
2159 {
2160 	spa_t *spa = zio->io_spa;
2161 	zio_type_t t = zio->io_type;
2162 
2163 	/*
2164 	 * If we're a config writer or a probe, the normal issue and
2165 	 * interrupt threads may all be blocked waiting for the config lock.
2166 	 * In this case, select the otherwise-unused taskq for ZIO_TYPE_NULL.
2167 	 */
2168 	if (zio->io_flags & (ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_PROBE))
2169 		t = ZIO_TYPE_NULL;
2170 
2171 	/*
2172 	 * A similar issue exists for the L2ARC write thread until L2ARC 2.0.
2173 	 */
2174 	if (t == ZIO_TYPE_WRITE && zio->io_vd && zio->io_vd->vdev_aux)
2175 		t = ZIO_TYPE_NULL;
2176 
2177 	/*
2178 	 * If this is a high priority I/O, then use the high priority taskq if
2179 	 * available or cut the line otherwise.
2180 	 */
2181 	if (zio->io_priority == ZIO_PRIORITY_SYNC_WRITE) {
2182 		if (spa->spa_zio_taskq[t][q + 1].stqs_count != 0)
2183 			q++;
2184 		else
2185 			cutinline = B_TRUE;
2186 	}
2187 
2188 	ASSERT3U(q, <, ZIO_TASKQ_TYPES);
2189 
2190 	spa_taskq_dispatch(spa, t, q, zio_execute, zio, cutinline);
2191 }
2192 
2193 static boolean_t
zio_taskq_member(zio_t * zio,zio_taskq_type_t q)2194 zio_taskq_member(zio_t *zio, zio_taskq_type_t q)
2195 {
2196 	spa_t *spa = zio->io_spa;
2197 
2198 	taskq_t *tq = taskq_of_curthread();
2199 
2200 	for (zio_type_t t = 0; t < ZIO_TYPES; t++) {
2201 		spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
2202 		uint_t i;
2203 		for (i = 0; i < tqs->stqs_count; i++) {
2204 			if (tqs->stqs_taskq[i] == tq)
2205 				return (B_TRUE);
2206 		}
2207 	}
2208 
2209 	return (B_FALSE);
2210 }
2211 
2212 static zio_t *
zio_issue_async(zio_t * zio)2213 zio_issue_async(zio_t *zio)
2214 {
2215 	ASSERT((zio->io_type != ZIO_TYPE_WRITE) || ZIO_HAS_ALLOCATOR(zio));
2216 	zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE, B_FALSE);
2217 	return (NULL);
2218 }
2219 
2220 void
zio_interrupt(void * zio)2221 zio_interrupt(void *zio)
2222 {
2223 	zio_taskq_dispatch(zio, ZIO_TASKQ_INTERRUPT, B_FALSE);
2224 }
2225 
2226 void
zio_delay_interrupt(zio_t * zio)2227 zio_delay_interrupt(zio_t *zio)
2228 {
2229 	/*
2230 	 * The timeout_generic() function isn't defined in userspace, so
2231 	 * rather than trying to implement the function, the zio delay
2232 	 * functionality has been disabled for userspace builds.
2233 	 */
2234 
2235 #ifdef _KERNEL
2236 	/*
2237 	 * If io_target_timestamp is zero, then no delay has been registered
2238 	 * for this IO, thus jump to the end of this function and "skip" the
2239 	 * delay; issuing it directly to the zio layer.
2240 	 */
2241 	if (zio->io_target_timestamp != 0) {
2242 		hrtime_t now = gethrtime();
2243 
2244 		if (now >= zio->io_target_timestamp) {
2245 			/*
2246 			 * This IO has already taken longer than the target
2247 			 * delay to complete, so we don't want to delay it
2248 			 * any longer; we "miss" the delay and issue it
2249 			 * directly to the zio layer. This is likely due to
2250 			 * the target latency being set to a value less than
2251 			 * the underlying hardware can satisfy (e.g. delay
2252 			 * set to 1ms, but the disks take 10ms to complete an
2253 			 * IO request).
2254 			 */
2255 
2256 			DTRACE_PROBE2(zio__delay__miss, zio_t *, zio,
2257 			    hrtime_t, now);
2258 
2259 			zio_interrupt(zio);
2260 		} else {
2261 			taskqid_t tid;
2262 			hrtime_t diff = zio->io_target_timestamp - now;
2263 			int ticks = MAX(1, NSEC_TO_TICK(diff));
2264 			clock_t expire_at_tick = ddi_get_lbolt() + ticks;
2265 
2266 			DTRACE_PROBE3(zio__delay__hit, zio_t *, zio,
2267 			    hrtime_t, now, hrtime_t, diff);
2268 
2269 			tid = taskq_dispatch_delay(system_taskq, zio_interrupt,
2270 			    zio, TQ_NOSLEEP, expire_at_tick);
2271 			if (tid == TASKQID_INVALID) {
2272 				/*
2273 				 * Couldn't allocate a task.  Just finish the
2274 				 * zio without a delay.
2275 				 */
2276 				zio_interrupt(zio);
2277 			}
2278 		}
2279 		return;
2280 	}
2281 #endif
2282 	DTRACE_PROBE1(zio__delay__skip, zio_t *, zio);
2283 	zio_interrupt(zio);
2284 }
2285 
2286 static void
zio_deadman_impl(zio_t * pio,int ziodepth)2287 zio_deadman_impl(zio_t *pio, int ziodepth)
2288 {
2289 	zio_t *cio, *cio_next;
2290 	zio_link_t *zl = NULL;
2291 	vdev_t *vd = pio->io_vd;
2292 	uint64_t failmode = spa_get_deadman_failmode(pio->io_spa);
2293 
2294 	if (zio_deadman_log_all || (vd != NULL && vd->vdev_ops->vdev_op_leaf)) {
2295 		vdev_queue_t *vq = vd ? &vd->vdev_queue : NULL;
2296 		zbookmark_phys_t *zb = &pio->io_bookmark;
2297 		uint64_t delta = gethrtime() - pio->io_timestamp;
2298 
2299 		zfs_dbgmsg("slow zio[%d]: zio=%px timestamp=%llu "
2300 		    "delta=%llu queued=%llu io=%llu "
2301 		    "path=%s "
2302 		    "last=%llu type=%d "
2303 		    "priority=%d flags=0x%llx stage=0x%x "
2304 		    "pipeline=0x%x pipeline-trace=0x%x "
2305 		    "objset=%llu object=%llu "
2306 		    "level=%llu blkid=%llu "
2307 		    "offset=%llu size=%llu "
2308 		    "error=%d",
2309 		    ziodepth, pio, pio->io_timestamp,
2310 		    (u_longlong_t)delta, pio->io_delta, pio->io_delay,
2311 		    vd ? vd->vdev_path : "NULL",
2312 		    vq ? vq->vq_io_complete_ts : 0, pio->io_type,
2313 		    pio->io_priority, (u_longlong_t)pio->io_flags,
2314 		    pio->io_stage, pio->io_pipeline, pio->io_pipeline_trace,
2315 		    (u_longlong_t)zb->zb_objset, (u_longlong_t)zb->zb_object,
2316 		    (u_longlong_t)zb->zb_level, (u_longlong_t)zb->zb_blkid,
2317 		    (u_longlong_t)pio->io_offset, (u_longlong_t)pio->io_size,
2318 		    pio->io_error);
2319 		(void) zfs_ereport_post(FM_EREPORT_ZFS_DEADMAN,
2320 		    pio->io_spa, vd, zb, pio, 0);
2321 	}
2322 
2323 	if (vd != NULL && vd->vdev_ops->vdev_op_leaf &&
2324 	    list_is_empty(&pio->io_child_list) &&
2325 	    failmode == ZIO_FAILURE_MODE_CONTINUE &&
2326 	    taskq_empty_ent(&pio->io_tqent) &&
2327 	    pio->io_queue_state == ZIO_QS_ACTIVE) {
2328 		pio->io_error = EINTR;
2329 		zio_interrupt(pio);
2330 	}
2331 
2332 	mutex_enter(&pio->io_lock);
2333 	for (cio = zio_walk_children(pio, &zl); cio != NULL; cio = cio_next) {
2334 		cio_next = zio_walk_children(pio, &zl);
2335 		zio_deadman_impl(cio, ziodepth + 1);
2336 	}
2337 	mutex_exit(&pio->io_lock);
2338 }
2339 
2340 /*
2341  * Log the critical information describing this zio and all of its children
2342  * using the zfs_dbgmsg() interface then post deadman event for the ZED.
2343  */
2344 void
zio_deadman(zio_t * pio,const char * tag)2345 zio_deadman(zio_t *pio, const char *tag)
2346 {
2347 	spa_t *spa = pio->io_spa;
2348 	char *name = spa_name(spa);
2349 
2350 	if (!zfs_deadman_enabled || spa_suspended(spa))
2351 		return;
2352 
2353 	zio_deadman_impl(pio, 0);
2354 
2355 	switch (spa_get_deadman_failmode(spa)) {
2356 	case ZIO_FAILURE_MODE_WAIT:
2357 		zfs_dbgmsg("%s waiting for hung I/O to pool '%s'", tag, name);
2358 		break;
2359 
2360 	case ZIO_FAILURE_MODE_CONTINUE:
2361 		zfs_dbgmsg("%s restarting hung I/O for pool '%s'", tag, name);
2362 		break;
2363 
2364 	case ZIO_FAILURE_MODE_PANIC:
2365 		fm_panic("%s determined I/O to pool '%s' is hung.", tag, name);
2366 		break;
2367 	}
2368 }
2369 
2370 /*
2371  * Execute the I/O pipeline until one of the following occurs:
2372  * (1) the I/O completes; (2) the pipeline stalls waiting for
2373  * dependent child I/Os; (3) the I/O issues, so we're waiting
2374  * for an I/O completion interrupt; (4) the I/O is delegated by
2375  * vdev-level caching or aggregation; (5) the I/O is deferred
2376  * due to vdev-level queueing; (6) the I/O is handed off to
2377  * another thread.  In all cases, the pipeline stops whenever
2378  * there's no CPU work; it never burns a thread in cv_wait_io().
2379  *
2380  * There's no locking on io_stage because there's no legitimate way
2381  * for multiple threads to be attempting to process the same I/O.
2382  */
2383 static zio_pipe_stage_t *zio_pipeline[];
2384 
2385 /*
2386  * zio_execute() is a wrapper around the static function
2387  * __zio_execute() so that we can force  __zio_execute() to be
2388  * inlined.  This reduces stack overhead which is important
2389  * because __zio_execute() is called recursively in several zio
2390  * code paths.  zio_execute() itself cannot be inlined because
2391  * it is externally visible.
2392  */
2393 void
zio_execute(void * zio)2394 zio_execute(void *zio)
2395 {
2396 	fstrans_cookie_t cookie;
2397 
2398 	cookie = spl_fstrans_mark();
2399 	__zio_execute(zio);
2400 	spl_fstrans_unmark(cookie);
2401 }
2402 
2403 /*
2404  * Used to determine if in the current context the stack is sized large
2405  * enough to allow zio_execute() to be called recursively.  A minimum
2406  * stack size of 16K is required to avoid needing to re-dispatch the zio.
2407  */
2408 static boolean_t
zio_execute_stack_check(zio_t * zio)2409 zio_execute_stack_check(zio_t *zio)
2410 {
2411 #if !defined(HAVE_LARGE_STACKS)
2412 	dsl_pool_t *dp = spa_get_dsl(zio->io_spa);
2413 
2414 	/* Executing in txg_sync_thread() context. */
2415 	if (dp && curthread == dp->dp_tx.tx_sync_thread)
2416 		return (B_TRUE);
2417 
2418 	/* Pool initialization outside of zio_taskq context. */
2419 	if (dp && spa_is_initializing(dp->dp_spa) &&
2420 	    !zio_taskq_member(zio, ZIO_TASKQ_ISSUE) &&
2421 	    !zio_taskq_member(zio, ZIO_TASKQ_ISSUE_HIGH))
2422 		return (B_TRUE);
2423 #else
2424 	(void) zio;
2425 #endif /* HAVE_LARGE_STACKS */
2426 
2427 	return (B_FALSE);
2428 }
2429 
2430 __attribute__((always_inline))
2431 static inline void
__zio_execute(zio_t * zio)2432 __zio_execute(zio_t *zio)
2433 {
2434 	ASSERT3U(zio->io_queued_timestamp, >, 0);
2435 
2436 	while (zio->io_stage < ZIO_STAGE_DONE) {
2437 		enum zio_stage pipeline = zio->io_pipeline;
2438 		enum zio_stage stage = zio->io_stage;
2439 
2440 		zio->io_executor = curthread;
2441 
2442 		ASSERT(!MUTEX_HELD(&zio->io_lock));
2443 		ASSERT(ISP2(stage));
2444 		ASSERT(zio->io_stall == NULL);
2445 
2446 		do {
2447 			stage <<= 1;
2448 		} while ((stage & pipeline) == 0);
2449 
2450 		ASSERT(stage <= ZIO_STAGE_DONE);
2451 
2452 		/*
2453 		 * If we are in interrupt context and this pipeline stage
2454 		 * will grab a config lock that is held across I/O,
2455 		 * or may wait for an I/O that needs an interrupt thread
2456 		 * to complete, issue async to avoid deadlock.
2457 		 *
2458 		 * For VDEV_IO_START, we cut in line so that the io will
2459 		 * be sent to disk promptly.
2460 		 */
2461 		if ((stage & ZIO_BLOCKING_STAGES) && zio->io_vd == NULL &&
2462 		    zio_taskq_member(zio, ZIO_TASKQ_INTERRUPT)) {
2463 			boolean_t cut = (stage == ZIO_STAGE_VDEV_IO_START) ?
2464 			    zio_requeue_io_start_cut_in_line : B_FALSE;
2465 			zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE, cut);
2466 			return;
2467 		}
2468 
2469 		/*
2470 		 * If the current context doesn't have large enough stacks
2471 		 * the zio must be issued asynchronously to prevent overflow.
2472 		 */
2473 		if (zio_execute_stack_check(zio)) {
2474 			boolean_t cut = (stage == ZIO_STAGE_VDEV_IO_START) ?
2475 			    zio_requeue_io_start_cut_in_line : B_FALSE;
2476 			zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE, cut);
2477 			return;
2478 		}
2479 
2480 		zio->io_stage = stage;
2481 		zio->io_pipeline_trace |= zio->io_stage;
2482 
2483 		/*
2484 		 * The zio pipeline stage returns the next zio to execute
2485 		 * (typically the same as this one), or NULL if we should
2486 		 * stop.
2487 		 */
2488 		zio = zio_pipeline[highbit64(stage) - 1](zio);
2489 
2490 		if (zio == NULL)
2491 			return;
2492 	}
2493 }
2494 
2495 
2496 /*
2497  * ==========================================================================
2498  * Initiate I/O, either sync or async
2499  * ==========================================================================
2500  */
2501 int
zio_wait(zio_t * zio)2502 zio_wait(zio_t *zio)
2503 {
2504 	/*
2505 	 * Some routines, like zio_free_sync(), may return a NULL zio
2506 	 * to avoid the performance overhead of creating and then destroying
2507 	 * an unneeded zio.  For the callers' simplicity, we accept a NULL
2508 	 * zio and ignore it.
2509 	 */
2510 	if (zio == NULL)
2511 		return (0);
2512 
2513 	long timeout = MSEC_TO_TICK(zfs_deadman_ziotime_ms);
2514 	int error;
2515 
2516 	ASSERT3S(zio->io_stage, ==, ZIO_STAGE_OPEN);
2517 	ASSERT3P(zio->io_executor, ==, NULL);
2518 
2519 	zio->io_waiter = curthread;
2520 	ASSERT0(zio->io_queued_timestamp);
2521 	zio->io_queued_timestamp = gethrtime();
2522 
2523 	if (zio->io_type == ZIO_TYPE_WRITE) {
2524 		spa_select_allocator(zio);
2525 	}
2526 	__zio_execute(zio);
2527 
2528 	mutex_enter(&zio->io_lock);
2529 	while (zio->io_executor != NULL) {
2530 		error = cv_timedwait_io(&zio->io_cv, &zio->io_lock,
2531 		    ddi_get_lbolt() + timeout);
2532 
2533 		if (zfs_deadman_enabled && error == -1 &&
2534 		    gethrtime() - zio->io_queued_timestamp >
2535 		    spa_deadman_ziotime(zio->io_spa)) {
2536 			mutex_exit(&zio->io_lock);
2537 			timeout = MSEC_TO_TICK(zfs_deadman_checktime_ms);
2538 			zio_deadman(zio, FTAG);
2539 			mutex_enter(&zio->io_lock);
2540 		}
2541 	}
2542 	mutex_exit(&zio->io_lock);
2543 
2544 	error = zio->io_error;
2545 	zio_destroy(zio);
2546 
2547 	return (error);
2548 }
2549 
2550 void
zio_nowait(zio_t * zio)2551 zio_nowait(zio_t *zio)
2552 {
2553 	/*
2554 	 * See comment in zio_wait().
2555 	 */
2556 	if (zio == NULL)
2557 		return;
2558 
2559 	ASSERT3P(zio->io_executor, ==, NULL);
2560 
2561 	if (zio->io_child_type == ZIO_CHILD_LOGICAL &&
2562 	    list_is_empty(&zio->io_parent_list)) {
2563 		zio_t *pio;
2564 
2565 		/*
2566 		 * This is a logical async I/O with no parent to wait for it.
2567 		 * We add it to the spa_async_root_zio "Godfather" I/O which
2568 		 * will ensure they complete prior to unloading the pool.
2569 		 */
2570 		spa_t *spa = zio->io_spa;
2571 		pio = spa->spa_async_zio_root[CPU_SEQID_UNSTABLE];
2572 
2573 		zio_add_child(pio, zio);
2574 	}
2575 
2576 	ASSERT0(zio->io_queued_timestamp);
2577 	zio->io_queued_timestamp = gethrtime();
2578 	if (zio->io_type == ZIO_TYPE_WRITE) {
2579 		spa_select_allocator(zio);
2580 	}
2581 	__zio_execute(zio);
2582 }
2583 
2584 /*
2585  * ==========================================================================
2586  * Reexecute, cancel, or suspend/resume failed I/O
2587  * ==========================================================================
2588  */
2589 
2590 static void
zio_reexecute(void * arg)2591 zio_reexecute(void *arg)
2592 {
2593 	zio_t *pio = arg;
2594 	zio_t *cio, *cio_next, *gio;
2595 
2596 	ASSERT(pio->io_child_type == ZIO_CHILD_LOGICAL);
2597 	ASSERT(pio->io_orig_stage == ZIO_STAGE_OPEN);
2598 	ASSERT(pio->io_gang_leader == NULL);
2599 	ASSERT(pio->io_gang_tree == NULL);
2600 
2601 	mutex_enter(&pio->io_lock);
2602 	pio->io_flags = pio->io_orig_flags;
2603 	pio->io_stage = pio->io_orig_stage;
2604 	pio->io_pipeline = pio->io_orig_pipeline;
2605 	pio->io_reexecute = 0;
2606 	pio->io_flags |= ZIO_FLAG_REEXECUTED;
2607 	pio->io_pipeline_trace = 0;
2608 	pio->io_error = 0;
2609 	pio->io_state[ZIO_WAIT_READY] = (pio->io_stage >= ZIO_STAGE_READY) ||
2610 	    (pio->io_pipeline & ZIO_STAGE_READY) == 0;
2611 	pio->io_state[ZIO_WAIT_DONE] = (pio->io_stage >= ZIO_STAGE_DONE);
2612 
2613 	/*
2614 	 * It's possible for a failed ZIO to be a descendant of more than one
2615 	 * ZIO tree. When reexecuting it, we have to be sure to add its wait
2616 	 * states to all parent wait counts.
2617 	 *
2618 	 * Those parents, in turn, may have other children that are currently
2619 	 * active, usually because they've already been reexecuted after
2620 	 * resuming. Those children may be executing and may call
2621 	 * zio_notify_parent() at the same time as we're updating our parent's
2622 	 * counts. To avoid races while updating the counts, we take
2623 	 * gio->io_lock before each update.
2624 	 */
2625 	zio_link_t *zl = NULL;
2626 	while ((gio = zio_walk_parents(pio, &zl)) != NULL) {
2627 		mutex_enter(&gio->io_lock);
2628 		for (int w = 0; w < ZIO_WAIT_TYPES; w++) {
2629 			gio->io_children[pio->io_child_type][w] +=
2630 			    !pio->io_state[w];
2631 		}
2632 		mutex_exit(&gio->io_lock);
2633 	}
2634 
2635 	for (int c = 0; c < ZIO_CHILD_TYPES; c++)
2636 		pio->io_child_error[c] = 0;
2637 
2638 	if (IO_IS_ALLOCATING(pio))
2639 		BP_ZERO(pio->io_bp);
2640 
2641 	/*
2642 	 * As we reexecute pio's children, new children could be created.
2643 	 * New children go to the head of pio's io_child_list, however,
2644 	 * so we will (correctly) not reexecute them.  The key is that
2645 	 * the remainder of pio's io_child_list, from 'cio_next' onward,
2646 	 * cannot be affected by any side effects of reexecuting 'cio'.
2647 	 */
2648 	zl = NULL;
2649 	for (cio = zio_walk_children(pio, &zl); cio != NULL; cio = cio_next) {
2650 		cio_next = zio_walk_children(pio, &zl);
2651 		mutex_exit(&pio->io_lock);
2652 		zio_reexecute(cio);
2653 		mutex_enter(&pio->io_lock);
2654 	}
2655 	mutex_exit(&pio->io_lock);
2656 
2657 	/*
2658 	 * Now that all children have been reexecuted, execute the parent.
2659 	 * We don't reexecute "The Godfather" I/O here as it's the
2660 	 * responsibility of the caller to wait on it.
2661 	 */
2662 	if (!(pio->io_flags & ZIO_FLAG_GODFATHER)) {
2663 		pio->io_queued_timestamp = gethrtime();
2664 		__zio_execute(pio);
2665 	}
2666 }
2667 
2668 void
zio_suspend(spa_t * spa,zio_t * zio,zio_suspend_reason_t reason)2669 zio_suspend(spa_t *spa, zio_t *zio, zio_suspend_reason_t reason)
2670 {
2671 	if (spa_get_failmode(spa) == ZIO_FAILURE_MODE_PANIC)
2672 		fm_panic("Pool '%s' has encountered an uncorrectable I/O "
2673 		    "failure and the failure mode property for this pool "
2674 		    "is set to panic.", spa_name(spa));
2675 
2676 	if (reason != ZIO_SUSPEND_MMP) {
2677 		cmn_err(CE_WARN, "Pool '%s' has encountered an uncorrectable "
2678 		    "I/O failure and has been suspended.", spa_name(spa));
2679 	}
2680 
2681 	(void) zfs_ereport_post(FM_EREPORT_ZFS_IO_FAILURE, spa, NULL,
2682 	    NULL, NULL, 0);
2683 
2684 	mutex_enter(&spa->spa_suspend_lock);
2685 
2686 	if (spa->spa_suspend_zio_root == NULL)
2687 		spa->spa_suspend_zio_root = zio_root(spa, NULL, NULL,
2688 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2689 		    ZIO_FLAG_GODFATHER);
2690 
2691 	spa->spa_suspended = reason;
2692 
2693 	if (zio != NULL) {
2694 		ASSERT(!(zio->io_flags & ZIO_FLAG_GODFATHER));
2695 		ASSERT(zio != spa->spa_suspend_zio_root);
2696 		ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
2697 		ASSERT(zio_unique_parent(zio) == NULL);
2698 		ASSERT(zio->io_stage == ZIO_STAGE_DONE);
2699 		zio_add_child(spa->spa_suspend_zio_root, zio);
2700 	}
2701 
2702 	mutex_exit(&spa->spa_suspend_lock);
2703 
2704 	txg_wait_kick(spa->spa_dsl_pool);
2705 }
2706 
2707 int
zio_resume(spa_t * spa)2708 zio_resume(spa_t *spa)
2709 {
2710 	zio_t *pio;
2711 
2712 	/*
2713 	 * Reexecute all previously suspended i/o.
2714 	 */
2715 	mutex_enter(&spa->spa_suspend_lock);
2716 	if (spa->spa_suspended != ZIO_SUSPEND_NONE)
2717 		cmn_err(CE_WARN, "Pool '%s' was suspended and is being "
2718 		    "resumed. Failed I/O will be retried.",
2719 		    spa_name(spa));
2720 	spa->spa_suspended = ZIO_SUSPEND_NONE;
2721 	cv_broadcast(&spa->spa_suspend_cv);
2722 	pio = spa->spa_suspend_zio_root;
2723 	spa->spa_suspend_zio_root = NULL;
2724 	mutex_exit(&spa->spa_suspend_lock);
2725 
2726 	if (pio == NULL)
2727 		return (0);
2728 
2729 	zio_reexecute(pio);
2730 	return (zio_wait(pio));
2731 }
2732 
2733 void
zio_resume_wait(spa_t * spa)2734 zio_resume_wait(spa_t *spa)
2735 {
2736 	mutex_enter(&spa->spa_suspend_lock);
2737 	while (spa_suspended(spa))
2738 		cv_wait(&spa->spa_suspend_cv, &spa->spa_suspend_lock);
2739 	mutex_exit(&spa->spa_suspend_lock);
2740 }
2741 
2742 /*
2743  * ==========================================================================
2744  * Gang blocks.
2745  *
2746  * A gang block is a collection of small blocks that looks to the DMU
2747  * like one large block.  When zio_dva_allocate() cannot find a block
2748  * of the requested size, due to either severe fragmentation or the pool
2749  * being nearly full, it calls zio_write_gang_block() to construct the
2750  * block from smaller fragments.
2751  *
2752  * A gang block consists of a gang header (zio_gbh_phys_t) and up to
2753  * three (SPA_GBH_NBLKPTRS) gang members.  The gang header is just like
2754  * an indirect block: it's an array of block pointers.  It consumes
2755  * only one sector and hence is allocatable regardless of fragmentation.
2756  * The gang header's bps point to its gang members, which hold the data.
2757  *
2758  * Gang blocks are self-checksumming, using the bp's <vdev, offset, txg>
2759  * as the verifier to ensure uniqueness of the SHA256 checksum.
2760  * Critically, the gang block bp's blk_cksum is the checksum of the data,
2761  * not the gang header.  This ensures that data block signatures (needed for
2762  * deduplication) are independent of how the block is physically stored.
2763  *
2764  * Gang blocks can be nested: a gang member may itself be a gang block.
2765  * Thus every gang block is a tree in which root and all interior nodes are
2766  * gang headers, and the leaves are normal blocks that contain user data.
2767  * The root of the gang tree is called the gang leader.
2768  *
2769  * To perform any operation (read, rewrite, free, claim) on a gang block,
2770  * zio_gang_assemble() first assembles the gang tree (minus data leaves)
2771  * in the io_gang_tree field of the original logical i/o by recursively
2772  * reading the gang leader and all gang headers below it.  This yields
2773  * an in-core tree containing the contents of every gang header and the
2774  * bps for every constituent of the gang block.
2775  *
2776  * With the gang tree now assembled, zio_gang_issue() just walks the gang tree
2777  * and invokes a callback on each bp.  To free a gang block, zio_gang_issue()
2778  * calls zio_free_gang() -- a trivial wrapper around zio_free() -- for each bp.
2779  * zio_claim_gang() provides a similarly trivial wrapper for zio_claim().
2780  * zio_read_gang() is a wrapper around zio_read() that omits reading gang
2781  * headers, since we already have those in io_gang_tree.  zio_rewrite_gang()
2782  * performs a zio_rewrite() of the data or, for gang headers, a zio_rewrite()
2783  * of the gang header plus zio_checksum_compute() of the data to update the
2784  * gang header's blk_cksum as described above.
2785  *
2786  * The two-phase assemble/issue model solves the problem of partial failure --
2787  * what if you'd freed part of a gang block but then couldn't read the
2788  * gang header for another part?  Assembling the entire gang tree first
2789  * ensures that all the necessary gang header I/O has succeeded before
2790  * starting the actual work of free, claim, or write.  Once the gang tree
2791  * is assembled, free and claim are in-memory operations that cannot fail.
2792  *
2793  * In the event that a gang write fails, zio_dva_unallocate() walks the
2794  * gang tree to immediately free (i.e. insert back into the space map)
2795  * everything we've allocated.  This ensures that we don't get ENOSPC
2796  * errors during repeated suspend/resume cycles due to a flaky device.
2797  *
2798  * Gang rewrites only happen during sync-to-convergence.  If we can't assemble
2799  * the gang tree, we won't modify the block, so we can safely defer the free
2800  * (knowing that the block is still intact).  If we *can* assemble the gang
2801  * tree, then even if some of the rewrites fail, zio_dva_unallocate() will free
2802  * each constituent bp and we can allocate a new block on the next sync pass.
2803  *
2804  * In all cases, the gang tree allows complete recovery from partial failure.
2805  * ==========================================================================
2806  */
2807 
2808 static void
zio_gang_issue_func_done(zio_t * zio)2809 zio_gang_issue_func_done(zio_t *zio)
2810 {
2811 	abd_free(zio->io_abd);
2812 }
2813 
2814 static zio_t *
zio_read_gang(zio_t * pio,blkptr_t * bp,zio_gang_node_t * gn,abd_t * data,uint64_t offset)2815 zio_read_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, abd_t *data,
2816     uint64_t offset)
2817 {
2818 	if (gn != NULL)
2819 		return (pio);
2820 
2821 	return (zio_read(pio, pio->io_spa, bp, abd_get_offset(data, offset),
2822 	    BP_GET_PSIZE(bp), zio_gang_issue_func_done,
2823 	    NULL, pio->io_priority, ZIO_GANG_CHILD_FLAGS(pio),
2824 	    &pio->io_bookmark));
2825 }
2826 
2827 static zio_t *
zio_rewrite_gang(zio_t * pio,blkptr_t * bp,zio_gang_node_t * gn,abd_t * data,uint64_t offset)2828 zio_rewrite_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, abd_t *data,
2829     uint64_t offset)
2830 {
2831 	zio_t *zio;
2832 
2833 	if (gn != NULL) {
2834 		abd_t *gbh_abd =
2835 		    abd_get_from_buf(gn->gn_gbh, SPA_GANGBLOCKSIZE);
2836 		zio = zio_rewrite(pio, pio->io_spa, pio->io_txg, bp,
2837 		    gbh_abd, SPA_GANGBLOCKSIZE, zio_gang_issue_func_done, NULL,
2838 		    pio->io_priority, ZIO_GANG_CHILD_FLAGS(pio),
2839 		    &pio->io_bookmark);
2840 		/*
2841 		 * As we rewrite each gang header, the pipeline will compute
2842 		 * a new gang block header checksum for it; but no one will
2843 		 * compute a new data checksum, so we do that here.  The one
2844 		 * exception is the gang leader: the pipeline already computed
2845 		 * its data checksum because that stage precedes gang assembly.
2846 		 * (Presently, nothing actually uses interior data checksums;
2847 		 * this is just good hygiene.)
2848 		 */
2849 		if (gn != pio->io_gang_leader->io_gang_tree) {
2850 			abd_t *buf = abd_get_offset(data, offset);
2851 
2852 			zio_checksum_compute(zio, BP_GET_CHECKSUM(bp),
2853 			    buf, BP_GET_PSIZE(bp));
2854 
2855 			abd_free(buf);
2856 		}
2857 		/*
2858 		 * If we are here to damage data for testing purposes,
2859 		 * leave the GBH alone so that we can detect the damage.
2860 		 */
2861 		if (pio->io_gang_leader->io_flags & ZIO_FLAG_INDUCE_DAMAGE)
2862 			zio->io_pipeline &= ~ZIO_VDEV_IO_STAGES;
2863 	} else {
2864 		zio = zio_rewrite(pio, pio->io_spa, pio->io_txg, bp,
2865 		    abd_get_offset(data, offset), BP_GET_PSIZE(bp),
2866 		    zio_gang_issue_func_done, NULL, pio->io_priority,
2867 		    ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
2868 	}
2869 
2870 	return (zio);
2871 }
2872 
2873 static zio_t *
zio_free_gang(zio_t * pio,blkptr_t * bp,zio_gang_node_t * gn,abd_t * data,uint64_t offset)2874 zio_free_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, abd_t *data,
2875     uint64_t offset)
2876 {
2877 	(void) gn, (void) data, (void) offset;
2878 
2879 	zio_t *zio = zio_free_sync(pio, pio->io_spa, pio->io_txg, bp,
2880 	    ZIO_GANG_CHILD_FLAGS(pio));
2881 	if (zio == NULL) {
2882 		zio = zio_null(pio, pio->io_spa,
2883 		    NULL, NULL, NULL, ZIO_GANG_CHILD_FLAGS(pio));
2884 	}
2885 	return (zio);
2886 }
2887 
2888 static zio_t *
zio_claim_gang(zio_t * pio,blkptr_t * bp,zio_gang_node_t * gn,abd_t * data,uint64_t offset)2889 zio_claim_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, abd_t *data,
2890     uint64_t offset)
2891 {
2892 	(void) gn, (void) data, (void) offset;
2893 	return (zio_claim(pio, pio->io_spa, pio->io_txg, bp,
2894 	    NULL, NULL, ZIO_GANG_CHILD_FLAGS(pio)));
2895 }
2896 
2897 static zio_gang_issue_func_t *zio_gang_issue_func[ZIO_TYPES] = {
2898 	NULL,
2899 	zio_read_gang,
2900 	zio_rewrite_gang,
2901 	zio_free_gang,
2902 	zio_claim_gang,
2903 	NULL
2904 };
2905 
2906 static void zio_gang_tree_assemble_done(zio_t *zio);
2907 
2908 static zio_gang_node_t *
zio_gang_node_alloc(zio_gang_node_t ** gnpp)2909 zio_gang_node_alloc(zio_gang_node_t **gnpp)
2910 {
2911 	zio_gang_node_t *gn;
2912 
2913 	ASSERT(*gnpp == NULL);
2914 
2915 	gn = kmem_zalloc(sizeof (*gn), KM_SLEEP);
2916 	gn->gn_gbh = zio_buf_alloc(SPA_GANGBLOCKSIZE);
2917 	*gnpp = gn;
2918 
2919 	return (gn);
2920 }
2921 
2922 static void
zio_gang_node_free(zio_gang_node_t ** gnpp)2923 zio_gang_node_free(zio_gang_node_t **gnpp)
2924 {
2925 	zio_gang_node_t *gn = *gnpp;
2926 
2927 	for (int g = 0; g < SPA_GBH_NBLKPTRS; g++)
2928 		ASSERT(gn->gn_child[g] == NULL);
2929 
2930 	zio_buf_free(gn->gn_gbh, SPA_GANGBLOCKSIZE);
2931 	kmem_free(gn, sizeof (*gn));
2932 	*gnpp = NULL;
2933 }
2934 
2935 static void
zio_gang_tree_free(zio_gang_node_t ** gnpp)2936 zio_gang_tree_free(zio_gang_node_t **gnpp)
2937 {
2938 	zio_gang_node_t *gn = *gnpp;
2939 
2940 	if (gn == NULL)
2941 		return;
2942 
2943 	for (int g = 0; g < SPA_GBH_NBLKPTRS; g++)
2944 		zio_gang_tree_free(&gn->gn_child[g]);
2945 
2946 	zio_gang_node_free(gnpp);
2947 }
2948 
2949 static void
zio_gang_tree_assemble(zio_t * gio,blkptr_t * bp,zio_gang_node_t ** gnpp)2950 zio_gang_tree_assemble(zio_t *gio, blkptr_t *bp, zio_gang_node_t **gnpp)
2951 {
2952 	zio_gang_node_t *gn = zio_gang_node_alloc(gnpp);
2953 	abd_t *gbh_abd = abd_get_from_buf(gn->gn_gbh, SPA_GANGBLOCKSIZE);
2954 
2955 	ASSERT(gio->io_gang_leader == gio);
2956 	ASSERT(BP_IS_GANG(bp));
2957 
2958 	zio_nowait(zio_read(gio, gio->io_spa, bp, gbh_abd, SPA_GANGBLOCKSIZE,
2959 	    zio_gang_tree_assemble_done, gn, gio->io_priority,
2960 	    ZIO_GANG_CHILD_FLAGS(gio), &gio->io_bookmark));
2961 }
2962 
2963 static void
zio_gang_tree_assemble_done(zio_t * zio)2964 zio_gang_tree_assemble_done(zio_t *zio)
2965 {
2966 	zio_t *gio = zio->io_gang_leader;
2967 	zio_gang_node_t *gn = zio->io_private;
2968 	blkptr_t *bp = zio->io_bp;
2969 
2970 	ASSERT(gio == zio_unique_parent(zio));
2971 	ASSERT(list_is_empty(&zio->io_child_list));
2972 
2973 	if (zio->io_error)
2974 		return;
2975 
2976 	/* this ABD was created from a linear buf in zio_gang_tree_assemble */
2977 	if (BP_SHOULD_BYTESWAP(bp))
2978 		byteswap_uint64_array(abd_to_buf(zio->io_abd), zio->io_size);
2979 
2980 	ASSERT3P(abd_to_buf(zio->io_abd), ==, gn->gn_gbh);
2981 	ASSERT(zio->io_size == SPA_GANGBLOCKSIZE);
2982 	ASSERT(gn->gn_gbh->zg_tail.zec_magic == ZEC_MAGIC);
2983 
2984 	abd_free(zio->io_abd);
2985 
2986 	for (int g = 0; g < SPA_GBH_NBLKPTRS; g++) {
2987 		blkptr_t *gbp = &gn->gn_gbh->zg_blkptr[g];
2988 		if (!BP_IS_GANG(gbp))
2989 			continue;
2990 		zio_gang_tree_assemble(gio, gbp, &gn->gn_child[g]);
2991 	}
2992 }
2993 
2994 static void
zio_gang_tree_issue(zio_t * pio,zio_gang_node_t * gn,blkptr_t * bp,abd_t * data,uint64_t offset)2995 zio_gang_tree_issue(zio_t *pio, zio_gang_node_t *gn, blkptr_t *bp, abd_t *data,
2996     uint64_t offset)
2997 {
2998 	zio_t *gio = pio->io_gang_leader;
2999 	zio_t *zio;
3000 
3001 	ASSERT(BP_IS_GANG(bp) == !!gn);
3002 	ASSERT(BP_GET_CHECKSUM(bp) == BP_GET_CHECKSUM(gio->io_bp));
3003 	ASSERT(BP_GET_LSIZE(bp) == BP_GET_PSIZE(bp) || gn == gio->io_gang_tree);
3004 
3005 	/*
3006 	 * If you're a gang header, your data is in gn->gn_gbh.
3007 	 * If you're a gang member, your data is in 'data' and gn == NULL.
3008 	 */
3009 	zio = zio_gang_issue_func[gio->io_type](pio, bp, gn, data, offset);
3010 
3011 	if (gn != NULL) {
3012 		ASSERT(gn->gn_gbh->zg_tail.zec_magic == ZEC_MAGIC);
3013 
3014 		for (int g = 0; g < SPA_GBH_NBLKPTRS; g++) {
3015 			blkptr_t *gbp = &gn->gn_gbh->zg_blkptr[g];
3016 			if (BP_IS_HOLE(gbp))
3017 				continue;
3018 			zio_gang_tree_issue(zio, gn->gn_child[g], gbp, data,
3019 			    offset);
3020 			offset += BP_GET_PSIZE(gbp);
3021 		}
3022 	}
3023 
3024 	if (gn == gio->io_gang_tree)
3025 		ASSERT3U(gio->io_size, ==, offset);
3026 
3027 	if (zio != pio)
3028 		zio_nowait(zio);
3029 }
3030 
3031 static zio_t *
zio_gang_assemble(zio_t * zio)3032 zio_gang_assemble(zio_t *zio)
3033 {
3034 	blkptr_t *bp = zio->io_bp;
3035 
3036 	ASSERT(BP_IS_GANG(bp) && zio->io_gang_leader == NULL);
3037 	ASSERT(zio->io_child_type > ZIO_CHILD_GANG);
3038 
3039 	zio->io_gang_leader = zio;
3040 
3041 	zio_gang_tree_assemble(zio, bp, &zio->io_gang_tree);
3042 
3043 	return (zio);
3044 }
3045 
3046 static zio_t *
zio_gang_issue(zio_t * zio)3047 zio_gang_issue(zio_t *zio)
3048 {
3049 	blkptr_t *bp = zio->io_bp;
3050 
3051 	if (zio_wait_for_children(zio, ZIO_CHILD_GANG_BIT, ZIO_WAIT_DONE)) {
3052 		return (NULL);
3053 	}
3054 
3055 	ASSERT(BP_IS_GANG(bp) && zio->io_gang_leader == zio);
3056 	ASSERT(zio->io_child_type > ZIO_CHILD_GANG);
3057 
3058 	if (zio->io_child_error[ZIO_CHILD_GANG] == 0)
3059 		zio_gang_tree_issue(zio, zio->io_gang_tree, bp, zio->io_abd,
3060 		    0);
3061 	else
3062 		zio_gang_tree_free(&zio->io_gang_tree);
3063 
3064 	zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
3065 
3066 	return (zio);
3067 }
3068 
3069 static void
zio_gang_inherit_allocator(zio_t * pio,zio_t * cio)3070 zio_gang_inherit_allocator(zio_t *pio, zio_t *cio)
3071 {
3072 	cio->io_allocator = pio->io_allocator;
3073 }
3074 
3075 static void
zio_write_gang_member_ready(zio_t * zio)3076 zio_write_gang_member_ready(zio_t *zio)
3077 {
3078 	zio_t *pio = zio_unique_parent(zio);
3079 	dva_t *cdva = zio->io_bp->blk_dva;
3080 	dva_t *pdva = pio->io_bp->blk_dva;
3081 	uint64_t asize;
3082 	zio_t *gio __maybe_unused = zio->io_gang_leader;
3083 
3084 	if (BP_IS_HOLE(zio->io_bp))
3085 		return;
3086 
3087 	/*
3088 	 * If we're getting direct-invoked from zio_write_gang_block(),
3089 	 * the bp_orig will be set.
3090 	 */
3091 	ASSERT(BP_IS_HOLE(&zio->io_bp_orig) ||
3092 	    zio->io_flags & ZIO_FLAG_PREALLOCATED);
3093 
3094 	ASSERT(zio->io_child_type == ZIO_CHILD_GANG);
3095 	ASSERT3U(zio->io_prop.zp_copies, ==, gio->io_prop.zp_copies);
3096 	ASSERT3U(zio->io_prop.zp_copies, <=, BP_GET_NDVAS(zio->io_bp));
3097 	ASSERT3U(pio->io_prop.zp_copies, <=, BP_GET_NDVAS(pio->io_bp));
3098 	VERIFY3U(BP_GET_NDVAS(zio->io_bp), <=, BP_GET_NDVAS(pio->io_bp));
3099 
3100 	mutex_enter(&pio->io_lock);
3101 	for (int d = 0; d < BP_GET_NDVAS(zio->io_bp); d++) {
3102 		ASSERT(DVA_GET_GANG(&pdva[d]));
3103 		asize = DVA_GET_ASIZE(&pdva[d]);
3104 		asize += DVA_GET_ASIZE(&cdva[d]);
3105 		DVA_SET_ASIZE(&pdva[d], asize);
3106 	}
3107 	mutex_exit(&pio->io_lock);
3108 }
3109 
3110 static void
zio_write_gang_done(zio_t * zio)3111 zio_write_gang_done(zio_t *zio)
3112 {
3113 	/*
3114 	 * The io_abd field will be NULL for a zio with no data.  The io_flags
3115 	 * will initially have the ZIO_FLAG_NODATA bit flag set, but we can't
3116 	 * check for it here as it is cleared in zio_ready.
3117 	 */
3118 	if (zio->io_abd != NULL)
3119 		abd_free(zio->io_abd);
3120 }
3121 
3122 static zio_t *
zio_write_gang_block(zio_t * pio,metaslab_class_t * mc)3123 zio_write_gang_block(zio_t *pio, metaslab_class_t *mc)
3124 {
3125 	spa_t *spa = pio->io_spa;
3126 	blkptr_t *bp = pio->io_bp;
3127 	zio_t *gio = pio->io_gang_leader;
3128 	zio_t *zio;
3129 	zio_gang_node_t *gn, **gnpp;
3130 	zio_gbh_phys_t *gbh;
3131 	abd_t *gbh_abd;
3132 	uint64_t txg = pio->io_txg;
3133 	uint64_t resid = pio->io_size;
3134 	zio_prop_t zp;
3135 	int error;
3136 	boolean_t has_data = !(pio->io_flags & ZIO_FLAG_NODATA);
3137 
3138 	/*
3139 	 * Store multiple copies of the GBH, so that we can still traverse
3140 	 * all the data (e.g. to free or scrub) even if a block is damaged.
3141 	 * This value respects the redundant_metadata property.
3142 	 */
3143 	int gbh_copies = gio->io_prop.zp_gang_copies;
3144 	if (gbh_copies == 0) {
3145 		/*
3146 		 * This should only happen in the case where we're filling in
3147 		 * DDT entries for a parent that wants more copies than the DDT
3148 		 * has.  In that case, we cannot gang without creating a mixed
3149 		 * blkptr, which is illegal.
3150 		 */
3151 		ASSERT3U(gio->io_child_type, ==, ZIO_CHILD_DDT);
3152 		pio->io_error = EAGAIN;
3153 		return (pio);
3154 	}
3155 	ASSERT3S(gbh_copies, >, 0);
3156 	ASSERT3S(gbh_copies, <=, SPA_DVAS_PER_BP);
3157 
3158 	ASSERT(ZIO_HAS_ALLOCATOR(pio));
3159 	int flags = METASLAB_GANG_HEADER;
3160 	if (pio->io_flags & ZIO_FLAG_IO_ALLOCATING) {
3161 		ASSERT(pio->io_priority == ZIO_PRIORITY_ASYNC_WRITE);
3162 		ASSERT(has_data);
3163 
3164 		flags |= METASLAB_ASYNC_ALLOC;
3165 	}
3166 
3167 	error = metaslab_alloc(spa, mc, SPA_GANGBLOCKSIZE,
3168 	    bp, gbh_copies, txg, pio == gio ? NULL : gio->io_bp, flags,
3169 	    &pio->io_alloc_list, pio->io_allocator, pio);
3170 	if (error) {
3171 		pio->io_error = error;
3172 		return (pio);
3173 	}
3174 
3175 	if (pio == gio) {
3176 		gnpp = &gio->io_gang_tree;
3177 	} else {
3178 		gnpp = pio->io_private;
3179 		ASSERT(pio->io_ready == zio_write_gang_member_ready);
3180 	}
3181 
3182 	gn = zio_gang_node_alloc(gnpp);
3183 	gbh = gn->gn_gbh;
3184 	memset(gbh, 0, SPA_GANGBLOCKSIZE);
3185 	gbh_abd = abd_get_from_buf(gbh, SPA_GANGBLOCKSIZE);
3186 
3187 	/*
3188 	 * Create the gang header.
3189 	 */
3190 	zio = zio_rewrite(pio, spa, txg, bp, gbh_abd, SPA_GANGBLOCKSIZE,
3191 	    zio_write_gang_done, NULL, pio->io_priority,
3192 	    ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
3193 
3194 	zio_gang_inherit_allocator(pio, zio);
3195 	if (pio->io_flags & ZIO_FLAG_IO_ALLOCATING) {
3196 		boolean_t more;
3197 		VERIFY(metaslab_class_throttle_reserve(mc, gbh_copies,
3198 		    zio, B_TRUE, &more));
3199 	}
3200 
3201 	/*
3202 	 * Create and nowait the gang children. First, we try to do
3203 	 * opportunistic allocations. If that fails to generate enough
3204 	 * space, we fall back to normal zio_write calls for nested gang.
3205 	 */
3206 	for (int g = 0; resid != 0; g++) {
3207 		flags &= METASLAB_ASYNC_ALLOC;
3208 		flags |= METASLAB_GANG_CHILD;
3209 		zp.zp_checksum = gio->io_prop.zp_checksum;
3210 		zp.zp_compress = ZIO_COMPRESS_OFF;
3211 		zp.zp_complevel = gio->io_prop.zp_complevel;
3212 		zp.zp_type = zp.zp_storage_type = DMU_OT_NONE;
3213 		zp.zp_level = 0;
3214 		zp.zp_copies = gio->io_prop.zp_copies;
3215 		zp.zp_gang_copies = gio->io_prop.zp_gang_copies;
3216 		zp.zp_dedup = B_FALSE;
3217 		zp.zp_dedup_verify = B_FALSE;
3218 		zp.zp_nopwrite = B_FALSE;
3219 		zp.zp_encrypt = gio->io_prop.zp_encrypt;
3220 		zp.zp_byteorder = gio->io_prop.zp_byteorder;
3221 		zp.zp_direct_write = B_FALSE;
3222 		memset(zp.zp_salt, 0, ZIO_DATA_SALT_LEN);
3223 		memset(zp.zp_iv, 0, ZIO_DATA_IV_LEN);
3224 		memset(zp.zp_mac, 0, ZIO_DATA_MAC_LEN);
3225 
3226 		uint64_t min_size = zio_roundup_alloc_size(spa,
3227 		    resid / (SPA_GBH_NBLKPTRS - g));
3228 		min_size = MIN(min_size, resid);
3229 		bp = &gbh->zg_blkptr[g];
3230 
3231 		zio_alloc_list_t cio_list;
3232 		metaslab_trace_init(&cio_list);
3233 		uint64_t allocated_size = UINT64_MAX;
3234 		error = metaslab_alloc_range(spa, mc, min_size, resid,
3235 		    bp, gio->io_prop.zp_copies, txg, NULL,
3236 		    flags, &cio_list, zio->io_allocator, NULL, &allocated_size);
3237 
3238 		boolean_t allocated = error == 0;
3239 
3240 		uint64_t psize = allocated ? MIN(resid, allocated_size) :
3241 		    min_size;
3242 		ASSERT3U(psize, >=, min_size);
3243 
3244 		zio_t *cio = zio_write(zio, spa, txg, bp, has_data ?
3245 		    abd_get_offset(pio->io_abd, pio->io_size - resid) : NULL,
3246 		    psize, psize, &zp, zio_write_gang_member_ready, NULL,
3247 		    zio_write_gang_done, &gn->gn_child[g], pio->io_priority,
3248 		    ZIO_GANG_CHILD_FLAGS(pio) |
3249 		    (allocated ? ZIO_FLAG_PREALLOCATED : 0), &pio->io_bookmark);
3250 
3251 		resid -= psize;
3252 		zio_gang_inherit_allocator(zio, cio);
3253 		if (allocated) {
3254 			metaslab_trace_move(&cio_list, &cio->io_alloc_list);
3255 			metaslab_group_alloc_increment_all(spa,
3256 			    &cio->io_bp_orig, zio->io_allocator, flags, psize,
3257 			    cio);
3258 		}
3259 		/*
3260 		 * We do not reserve for the child writes, since we already
3261 		 * reserved for the parent.  Unreserve though will be called
3262 		 * for individual children.  We can do this since sum of all
3263 		 * child's physical sizes is equal to parent's physical size.
3264 		 * It would not work for potentially bigger allocation sizes.
3265 		 */
3266 
3267 		zio_nowait(cio);
3268 	}
3269 
3270 	/*
3271 	 * Set pio's pipeline to just wait for zio to finish.
3272 	 */
3273 	pio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
3274 
3275 	zio_nowait(zio);
3276 
3277 	return (pio);
3278 }
3279 
3280 /*
3281  * The zio_nop_write stage in the pipeline determines if allocating a
3282  * new bp is necessary.  The nopwrite feature can handle writes in
3283  * either syncing or open context (i.e. zil writes) and as a result is
3284  * mutually exclusive with dedup.
3285  *
3286  * By leveraging a cryptographically secure checksum, such as SHA256, we
3287  * can compare the checksums of the new data and the old to determine if
3288  * allocating a new block is required.  Note that our requirements for
3289  * cryptographic strength are fairly weak: there can't be any accidental
3290  * hash collisions, but we don't need to be secure against intentional
3291  * (malicious) collisions.  To trigger a nopwrite, you have to be able
3292  * to write the file to begin with, and triggering an incorrect (hash
3293  * collision) nopwrite is no worse than simply writing to the file.
3294  * That said, there are no known attacks against the checksum algorithms
3295  * used for nopwrite, assuming that the salt and the checksums
3296  * themselves remain secret.
3297  */
3298 static zio_t *
zio_nop_write(zio_t * zio)3299 zio_nop_write(zio_t *zio)
3300 {
3301 	blkptr_t *bp = zio->io_bp;
3302 	blkptr_t *bp_orig = &zio->io_bp_orig;
3303 	zio_prop_t *zp = &zio->io_prop;
3304 
3305 	ASSERT(BP_IS_HOLE(bp));
3306 	ASSERT(BP_GET_LEVEL(bp) == 0);
3307 	ASSERT(!(zio->io_flags & ZIO_FLAG_IO_REWRITE));
3308 	ASSERT(zp->zp_nopwrite);
3309 	ASSERT(!zp->zp_dedup);
3310 	ASSERT(zio->io_bp_override == NULL);
3311 	ASSERT(IO_IS_ALLOCATING(zio));
3312 
3313 	/*
3314 	 * Check to see if the original bp and the new bp have matching
3315 	 * characteristics (i.e. same checksum, compression algorithms, etc).
3316 	 * If they don't then just continue with the pipeline which will
3317 	 * allocate a new bp.
3318 	 */
3319 	if (BP_IS_HOLE(bp_orig) ||
3320 	    !(zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_flags &
3321 	    ZCHECKSUM_FLAG_NOPWRITE) ||
3322 	    BP_IS_ENCRYPTED(bp) || BP_IS_ENCRYPTED(bp_orig) ||
3323 	    BP_GET_CHECKSUM(bp) != BP_GET_CHECKSUM(bp_orig) ||
3324 	    BP_GET_COMPRESS(bp) != BP_GET_COMPRESS(bp_orig) ||
3325 	    BP_GET_DEDUP(bp) != BP_GET_DEDUP(bp_orig) ||
3326 	    zp->zp_copies != BP_GET_NDVAS(bp_orig))
3327 		return (zio);
3328 
3329 	/*
3330 	 * If the checksums match then reset the pipeline so that we
3331 	 * avoid allocating a new bp and issuing any I/O.
3332 	 */
3333 	if (ZIO_CHECKSUM_EQUAL(bp->blk_cksum, bp_orig->blk_cksum)) {
3334 		ASSERT(zio_checksum_table[zp->zp_checksum].ci_flags &
3335 		    ZCHECKSUM_FLAG_NOPWRITE);
3336 		ASSERT3U(BP_GET_PSIZE(bp), ==, BP_GET_PSIZE(bp_orig));
3337 		ASSERT3U(BP_GET_LSIZE(bp), ==, BP_GET_LSIZE(bp_orig));
3338 		ASSERT(zp->zp_compress != ZIO_COMPRESS_OFF);
3339 		ASSERT3U(bp->blk_prop, ==, bp_orig->blk_prop);
3340 
3341 		/*
3342 		 * If we're overwriting a block that is currently on an
3343 		 * indirect vdev, then ignore the nopwrite request and
3344 		 * allow a new block to be allocated on a concrete vdev.
3345 		 */
3346 		spa_config_enter(zio->io_spa, SCL_VDEV, FTAG, RW_READER);
3347 		for (int d = 0; d < BP_GET_NDVAS(bp_orig); d++) {
3348 			vdev_t *tvd = vdev_lookup_top(zio->io_spa,
3349 			    DVA_GET_VDEV(&bp_orig->blk_dva[d]));
3350 			if (tvd->vdev_ops == &vdev_indirect_ops) {
3351 				spa_config_exit(zio->io_spa, SCL_VDEV, FTAG);
3352 				return (zio);
3353 			}
3354 		}
3355 		spa_config_exit(zio->io_spa, SCL_VDEV, FTAG);
3356 
3357 		*bp = *bp_orig;
3358 		zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
3359 		zio->io_flags |= ZIO_FLAG_NOPWRITE;
3360 	}
3361 
3362 	return (zio);
3363 }
3364 
3365 /*
3366  * ==========================================================================
3367  * Block Reference Table
3368  * ==========================================================================
3369  */
3370 static zio_t *
zio_brt_free(zio_t * zio)3371 zio_brt_free(zio_t *zio)
3372 {
3373 	blkptr_t *bp;
3374 
3375 	bp = zio->io_bp;
3376 
3377 	if (BP_GET_LEVEL(bp) > 0 ||
3378 	    BP_IS_METADATA(bp) ||
3379 	    !brt_maybe_exists(zio->io_spa, bp)) {
3380 		return (zio);
3381 	}
3382 
3383 	if (!brt_entry_decref(zio->io_spa, bp)) {
3384 		/*
3385 		 * This isn't the last reference, so we cannot free
3386 		 * the data yet.
3387 		 */
3388 		zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
3389 	}
3390 
3391 	return (zio);
3392 }
3393 
3394 /*
3395  * ==========================================================================
3396  * Dedup
3397  * ==========================================================================
3398  */
3399 static void
zio_ddt_child_read_done(zio_t * zio)3400 zio_ddt_child_read_done(zio_t *zio)
3401 {
3402 	blkptr_t *bp = zio->io_bp;
3403 	ddt_t *ddt;
3404 	ddt_entry_t *dde = zio->io_private;
3405 	zio_t *pio = zio_unique_parent(zio);
3406 
3407 	mutex_enter(&pio->io_lock);
3408 	ddt = ddt_select(zio->io_spa, bp);
3409 
3410 	if (zio->io_error == 0) {
3411 		ddt_phys_variant_t v = ddt_phys_select(ddt, dde, bp);
3412 		/* this phys variant doesn't need repair */
3413 		ddt_phys_clear(dde->dde_phys, v);
3414 	}
3415 
3416 	if (zio->io_error == 0 && dde->dde_io->dde_repair_abd == NULL)
3417 		dde->dde_io->dde_repair_abd = zio->io_abd;
3418 	else
3419 		abd_free(zio->io_abd);
3420 	mutex_exit(&pio->io_lock);
3421 }
3422 
3423 static zio_t *
zio_ddt_read_start(zio_t * zio)3424 zio_ddt_read_start(zio_t *zio)
3425 {
3426 	blkptr_t *bp = zio->io_bp;
3427 
3428 	ASSERT(BP_GET_DEDUP(bp));
3429 	ASSERT(BP_GET_PSIZE(bp) == zio->io_size);
3430 	ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
3431 
3432 	if (zio->io_child_error[ZIO_CHILD_DDT]) {
3433 		ddt_t *ddt = ddt_select(zio->io_spa, bp);
3434 		ddt_entry_t *dde = ddt_repair_start(ddt, bp);
3435 		ddt_phys_variant_t v_self = ddt_phys_select(ddt, dde, bp);
3436 		ddt_univ_phys_t *ddp = dde->dde_phys;
3437 		blkptr_t blk;
3438 
3439 		ASSERT(zio->io_vsd == NULL);
3440 		zio->io_vsd = dde;
3441 
3442 		if (v_self == DDT_PHYS_NONE)
3443 			return (zio);
3444 
3445 		/* issue I/O for the other copies */
3446 		for (int p = 0; p < DDT_NPHYS(ddt); p++) {
3447 			ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);
3448 
3449 			if (ddt_phys_birth(ddp, v) == 0 || v == v_self)
3450 				continue;
3451 
3452 			ddt_bp_create(ddt->ddt_checksum, &dde->dde_key,
3453 			    ddp, v, &blk);
3454 			zio_nowait(zio_read(zio, zio->io_spa, &blk,
3455 			    abd_alloc_for_io(zio->io_size, B_TRUE),
3456 			    zio->io_size, zio_ddt_child_read_done, dde,
3457 			    zio->io_priority, ZIO_DDT_CHILD_FLAGS(zio) |
3458 			    ZIO_FLAG_DONT_PROPAGATE, &zio->io_bookmark));
3459 		}
3460 		return (zio);
3461 	}
3462 
3463 	zio_nowait(zio_read(zio, zio->io_spa, bp,
3464 	    zio->io_abd, zio->io_size, NULL, NULL, zio->io_priority,
3465 	    ZIO_DDT_CHILD_FLAGS(zio), &zio->io_bookmark));
3466 
3467 	return (zio);
3468 }
3469 
3470 static zio_t *
zio_ddt_read_done(zio_t * zio)3471 zio_ddt_read_done(zio_t *zio)
3472 {
3473 	blkptr_t *bp = zio->io_bp;
3474 
3475 	if (zio_wait_for_children(zio, ZIO_CHILD_DDT_BIT, ZIO_WAIT_DONE)) {
3476 		return (NULL);
3477 	}
3478 
3479 	ASSERT(BP_GET_DEDUP(bp));
3480 	ASSERT(BP_GET_PSIZE(bp) == zio->io_size);
3481 	ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
3482 
3483 	if (zio->io_child_error[ZIO_CHILD_DDT]) {
3484 		ddt_t *ddt = ddt_select(zio->io_spa, bp);
3485 		ddt_entry_t *dde = zio->io_vsd;
3486 		if (ddt == NULL) {
3487 			ASSERT(spa_load_state(zio->io_spa) != SPA_LOAD_NONE);
3488 			return (zio);
3489 		}
3490 		if (dde == NULL) {
3491 			zio->io_stage = ZIO_STAGE_DDT_READ_START >> 1;
3492 			zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE, B_FALSE);
3493 			return (NULL);
3494 		}
3495 		if (dde->dde_io->dde_repair_abd != NULL) {
3496 			abd_copy(zio->io_abd, dde->dde_io->dde_repair_abd,
3497 			    zio->io_size);
3498 			zio->io_child_error[ZIO_CHILD_DDT] = 0;
3499 		}
3500 		ddt_repair_done(ddt, dde);
3501 		zio->io_vsd = NULL;
3502 	}
3503 
3504 	ASSERT(zio->io_vsd == NULL);
3505 
3506 	return (zio);
3507 }
3508 
3509 static boolean_t
zio_ddt_collision(zio_t * zio,ddt_t * ddt,ddt_entry_t * dde)3510 zio_ddt_collision(zio_t *zio, ddt_t *ddt, ddt_entry_t *dde)
3511 {
3512 	spa_t *spa = zio->io_spa;
3513 	boolean_t do_raw = !!(zio->io_flags & ZIO_FLAG_RAW);
3514 
3515 	ASSERT(!(zio->io_bp_override && do_raw));
3516 
3517 	/*
3518 	 * Note: we compare the original data, not the transformed data,
3519 	 * because when zio->io_bp is an override bp, we will not have
3520 	 * pushed the I/O transforms.  That's an important optimization
3521 	 * because otherwise we'd compress/encrypt all dmu_sync() data twice.
3522 	 * However, we should never get a raw, override zio so in these
3523 	 * cases we can compare the io_abd directly. This is useful because
3524 	 * it allows us to do dedup verification even if we don't have access
3525 	 * to the original data (for instance, if the encryption keys aren't
3526 	 * loaded).
3527 	 */
3528 
3529 	for (int p = 0; p < DDT_NPHYS(ddt); p++) {
3530 		if (DDT_PHYS_IS_DITTO(ddt, p))
3531 			continue;
3532 
3533 		if (dde->dde_io == NULL)
3534 			continue;
3535 
3536 		zio_t *lio = dde->dde_io->dde_lead_zio[p];
3537 		if (lio == NULL)
3538 			continue;
3539 
3540 		if (do_raw)
3541 			return (lio->io_size != zio->io_size ||
3542 			    abd_cmp(zio->io_abd, lio->io_abd) != 0);
3543 
3544 		return (lio->io_orig_size != zio->io_orig_size ||
3545 		    abd_cmp(zio->io_orig_abd, lio->io_orig_abd) != 0);
3546 	}
3547 
3548 	for (int p = 0; p < DDT_NPHYS(ddt); p++) {
3549 		ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);
3550 		uint64_t phys_birth = ddt_phys_birth(dde->dde_phys, v);
3551 
3552 		if (phys_birth != 0 && do_raw) {
3553 			blkptr_t blk = *zio->io_bp;
3554 			uint64_t psize;
3555 			abd_t *tmpabd;
3556 			int error;
3557 
3558 			ddt_bp_fill(dde->dde_phys, v, &blk, phys_birth);
3559 			psize = BP_GET_PSIZE(&blk);
3560 
3561 			if (psize != zio->io_size)
3562 				return (B_TRUE);
3563 
3564 			ddt_exit(ddt);
3565 
3566 			tmpabd = abd_alloc_for_io(psize, B_TRUE);
3567 
3568 			error = zio_wait(zio_read(NULL, spa, &blk, tmpabd,
3569 			    psize, NULL, NULL, ZIO_PRIORITY_SYNC_READ,
3570 			    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
3571 			    ZIO_FLAG_RAW, &zio->io_bookmark));
3572 
3573 			if (error == 0) {
3574 				if (abd_cmp(tmpabd, zio->io_abd) != 0)
3575 					error = SET_ERROR(ENOENT);
3576 			}
3577 
3578 			abd_free(tmpabd);
3579 			ddt_enter(ddt);
3580 			return (error != 0);
3581 		} else if (phys_birth != 0) {
3582 			arc_buf_t *abuf = NULL;
3583 			arc_flags_t aflags = ARC_FLAG_WAIT;
3584 			blkptr_t blk = *zio->io_bp;
3585 			int error;
3586 
3587 			ddt_bp_fill(dde->dde_phys, v, &blk, phys_birth);
3588 
3589 			if (BP_GET_LSIZE(&blk) != zio->io_orig_size)
3590 				return (B_TRUE);
3591 
3592 			ddt_exit(ddt);
3593 
3594 			error = arc_read(NULL, spa, &blk,
3595 			    arc_getbuf_func, &abuf, ZIO_PRIORITY_SYNC_READ,
3596 			    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
3597 			    &aflags, &zio->io_bookmark);
3598 
3599 			if (error == 0) {
3600 				if (abd_cmp_buf(zio->io_orig_abd, abuf->b_data,
3601 				    zio->io_orig_size) != 0)
3602 					error = SET_ERROR(ENOENT);
3603 				arc_buf_destroy(abuf, &abuf);
3604 			}
3605 
3606 			ddt_enter(ddt);
3607 			return (error != 0);
3608 		}
3609 	}
3610 
3611 	return (B_FALSE);
3612 }
3613 
3614 static void
zio_ddt_child_write_done(zio_t * zio)3615 zio_ddt_child_write_done(zio_t *zio)
3616 {
3617 	ddt_t *ddt = ddt_select(zio->io_spa, zio->io_bp);
3618 	ddt_entry_t *dde = zio->io_private;
3619 
3620 	zio_link_t *zl = NULL;
3621 	ASSERT3P(zio_walk_parents(zio, &zl), !=, NULL);
3622 
3623 	int p = DDT_PHYS_FOR_COPIES(ddt, zio->io_prop.zp_copies);
3624 	ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);
3625 	ddt_univ_phys_t *ddp = dde->dde_phys;
3626 
3627 	ddt_enter(ddt);
3628 
3629 	/* we're the lead, so once we're done there's no one else outstanding */
3630 	if (dde->dde_io->dde_lead_zio[p] == zio)
3631 		dde->dde_io->dde_lead_zio[p] = NULL;
3632 
3633 	ddt_univ_phys_t *orig = &dde->dde_io->dde_orig_phys;
3634 
3635 	if (zio->io_error != 0) {
3636 		/*
3637 		 * The write failed, so we're about to abort the entire IO
3638 		 * chain. We need to revert the entry back to what it was at
3639 		 * the last time it was successfully extended.
3640 		 */
3641 		ddt_phys_unextend(ddp, orig, v);
3642 		ddt_phys_clear(orig, v);
3643 
3644 		ddt_exit(ddt);
3645 		return;
3646 	}
3647 
3648 	/*
3649 	 * Add references for all dedup writes that were waiting on the
3650 	 * physical one, skipping any other physical writes that are waiting.
3651 	 */
3652 	zio_t *pio;
3653 	zl = NULL;
3654 	while ((pio = zio_walk_parents(zio, &zl)) != NULL) {
3655 		if (!(pio->io_flags & ZIO_FLAG_DDT_CHILD))
3656 			ddt_phys_addref(ddp, v);
3657 	}
3658 
3659 	/*
3660 	 * We've successfully added new DVAs to the entry. Clear the saved
3661 	 * state or, if there's still outstanding IO, remember it so we can
3662 	 * revert to a known good state if that IO fails.
3663 	 */
3664 	if (dde->dde_io->dde_lead_zio[p] == NULL)
3665 		ddt_phys_clear(orig, v);
3666 	else
3667 		ddt_phys_copy(orig, ddp, v);
3668 
3669 	ddt_exit(ddt);
3670 }
3671 
3672 static void
zio_ddt_child_write_ready(zio_t * zio)3673 zio_ddt_child_write_ready(zio_t *zio)
3674 {
3675 	ddt_t *ddt = ddt_select(zio->io_spa, zio->io_bp);
3676 	ddt_entry_t *dde = zio->io_private;
3677 
3678 	zio_link_t *zl = NULL;
3679 	ASSERT3P(zio_walk_parents(zio, &zl), !=, NULL);
3680 
3681 	int p = DDT_PHYS_FOR_COPIES(ddt, zio->io_prop.zp_copies);
3682 	ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);
3683 
3684 	if (ddt_phys_is_gang(dde->dde_phys, v)) {
3685 		for (int i = 0; i < BP_GET_NDVAS(zio->io_bp); i++) {
3686 			dva_t *d = &zio->io_bp->blk_dva[i];
3687 			metaslab_group_alloc_decrement(zio->io_spa,
3688 			    DVA_GET_VDEV(d), zio->io_allocator,
3689 			    METASLAB_ASYNC_ALLOC, zio->io_size, zio);
3690 		}
3691 		zio->io_error = EAGAIN;
3692 	}
3693 
3694 	if (zio->io_error != 0)
3695 		return;
3696 
3697 	ddt_enter(ddt);
3698 
3699 	ddt_phys_extend(dde->dde_phys, v, zio->io_bp);
3700 
3701 	zio_t *pio;
3702 	zl = NULL;
3703 	while ((pio = zio_walk_parents(zio, &zl)) != NULL) {
3704 		if (!(pio->io_flags & ZIO_FLAG_DDT_CHILD))
3705 			ddt_bp_fill(dde->dde_phys, v, pio->io_bp, zio->io_txg);
3706 	}
3707 
3708 	ddt_exit(ddt);
3709 }
3710 
3711 static zio_t *
zio_ddt_write(zio_t * zio)3712 zio_ddt_write(zio_t *zio)
3713 {
3714 	spa_t *spa = zio->io_spa;
3715 	blkptr_t *bp = zio->io_bp;
3716 	uint64_t txg = zio->io_txg;
3717 	zio_prop_t *zp = &zio->io_prop;
3718 	ddt_t *ddt = ddt_select(spa, bp);
3719 	ddt_entry_t *dde;
3720 
3721 	ASSERT(BP_GET_DEDUP(bp));
3722 	ASSERT(BP_GET_CHECKSUM(bp) == zp->zp_checksum);
3723 	ASSERT(BP_IS_HOLE(bp) || zio->io_bp_override);
3724 	ASSERT(!(zio->io_bp_override && (zio->io_flags & ZIO_FLAG_RAW)));
3725 	/*
3726 	 * Deduplication will not take place for Direct I/O writes. The
3727 	 * ddt_tree will be emptied in syncing context. Direct I/O writes take
3728 	 * place in the open-context. Direct I/O write can not attempt to
3729 	 * modify the ddt_tree while issuing out a write.
3730 	 */
3731 	ASSERT3B(zio->io_prop.zp_direct_write, ==, B_FALSE);
3732 
3733 	ddt_enter(ddt);
3734 	/*
3735 	 * Search DDT for matching entry.  Skip DVAs verification here, since
3736 	 * they can go only from override, and once we get here the override
3737 	 * pointer can't have "D" flag to be confused with pruned DDT entries.
3738 	 */
3739 	IMPLY(zio->io_bp_override, !BP_GET_DEDUP(zio->io_bp_override));
3740 	dde = ddt_lookup(ddt, bp, B_FALSE);
3741 	if (dde == NULL) {
3742 		/* DDT size is over its quota so no new entries */
3743 		zp->zp_dedup = B_FALSE;
3744 		BP_SET_DEDUP(bp, B_FALSE);
3745 		if (zio->io_bp_override == NULL)
3746 			zio->io_pipeline = ZIO_WRITE_PIPELINE;
3747 		ddt_exit(ddt);
3748 		return (zio);
3749 	}
3750 
3751 	if (zp->zp_dedup_verify && zio_ddt_collision(zio, ddt, dde)) {
3752 		/*
3753 		 * If we're using a weak checksum, upgrade to a strong checksum
3754 		 * and try again.  If we're already using a strong checksum,
3755 		 * we can't resolve it, so just convert to an ordinary write.
3756 		 * (And automatically e-mail a paper to Nature?)
3757 		 */
3758 		if (!(zio_checksum_table[zp->zp_checksum].ci_flags &
3759 		    ZCHECKSUM_FLAG_DEDUP)) {
3760 			zp->zp_checksum = spa_dedup_checksum(spa);
3761 			zio_pop_transforms(zio);
3762 			zio->io_stage = ZIO_STAGE_OPEN;
3763 			BP_ZERO(bp);
3764 		} else {
3765 			zp->zp_dedup = B_FALSE;
3766 			BP_SET_DEDUP(bp, B_FALSE);
3767 		}
3768 		ASSERT(!BP_GET_DEDUP(bp));
3769 		zio->io_pipeline = ZIO_WRITE_PIPELINE;
3770 		ddt_exit(ddt);
3771 		return (zio);
3772 	}
3773 
3774 	int p = DDT_PHYS_FOR_COPIES(ddt, zp->zp_copies);
3775 	ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);
3776 	ddt_univ_phys_t *ddp = dde->dde_phys;
3777 
3778 	/*
3779 	 * In the common cases, at this point we have a regular BP with no
3780 	 * allocated DVAs, and the corresponding DDT entry for its checksum.
3781 	 * Our goal is to fill the BP with enough DVAs to satisfy its copies=
3782 	 * requirement.
3783 	 *
3784 	 * One of three things needs to happen to fulfill this:
3785 	 *
3786 	 * - if the DDT entry has enough DVAs to satisfy the BP, we just copy
3787 	 *   them out of the entry and return;
3788 	 *
3789 	 * - if the DDT entry has no DVAs (ie its brand new), then we have to
3790 	 *   issue the write as normal so that DVAs can be allocated and the
3791 	 *   data land on disk. We then copy the DVAs into the DDT entry on
3792 	 *   return.
3793 	 *
3794 	 * - if the DDT entry has some DVAs, but too few, we have to issue the
3795 	 *   write, adjusted to have allocate fewer copies. When it returns, we
3796 	 *   add the new DVAs to the DDT entry, and update the BP to have the
3797 	 *   full amount it originally requested.
3798 	 *
3799 	 * In all cases, if there's already a writing IO in flight, we need to
3800 	 * defer the action until after the write is done. If our action is to
3801 	 * write, we need to adjust our request for additional DVAs to match
3802 	 * what will be in the DDT entry after it completes. In this way every
3803 	 * IO can be guaranteed to recieve enough DVAs simply by joining the
3804 	 * end of the chain and letting the sequence play out.
3805 	 */
3806 
3807 	/*
3808 	 * Number of DVAs in the DDT entry. If the BP is encrypted we ignore
3809 	 * the third one as normal.
3810 	 */
3811 	int have_dvas = ddt_phys_dva_count(ddp, v, BP_IS_ENCRYPTED(bp));
3812 	IMPLY(have_dvas == 0, ddt_phys_birth(ddp, v) == 0);
3813 	boolean_t is_ganged = ddt_phys_is_gang(ddp, v);
3814 
3815 	/* Number of DVAs requested by the IO. */
3816 	uint8_t need_dvas = zp->zp_copies;
3817 	/* Number of DVAs in outstanding writes for this dde. */
3818 	uint8_t parent_dvas = 0;
3819 
3820 	/*
3821 	 * What we do next depends on whether or not there's IO outstanding that
3822 	 * will update this entry.
3823 	 */
3824 	if (dde->dde_io == NULL || dde->dde_io->dde_lead_zio[p] == NULL) {
3825 		/*
3826 		 * No IO outstanding, so we only need to worry about ourselves.
3827 		 */
3828 
3829 		/*
3830 		 * Override BPs bring their own DVAs and their own problems.
3831 		 */
3832 		if (zio->io_bp_override) {
3833 			/*
3834 			 * For a brand-new entry, all the work has been done
3835 			 * for us, and we can just fill it out from the provided
3836 			 * block and leave.
3837 			 */
3838 			if (have_dvas == 0) {
3839 				ASSERT(BP_GET_LOGICAL_BIRTH(bp) == txg);
3840 				ASSERT(BP_EQUAL(bp, zio->io_bp_override));
3841 				ddt_phys_extend(ddp, v, bp);
3842 				ddt_phys_addref(ddp, v);
3843 				ddt_exit(ddt);
3844 				return (zio);
3845 			}
3846 
3847 			/*
3848 			 * If we already have this entry, then we want to treat
3849 			 * it like a regular write. To do this we just wipe
3850 			 * them out and proceed like a regular write.
3851 			 *
3852 			 * Even if there are some DVAs in the entry, we still
3853 			 * have to clear them out. We can't use them to fill
3854 			 * out the dedup entry, as they are all referenced
3855 			 * together by a bp already on disk, and will be freed
3856 			 * as a group.
3857 			 */
3858 			BP_ZERO_DVAS(bp);
3859 			BP_SET_BIRTH(bp, 0, 0);
3860 		}
3861 
3862 		/*
3863 		 * If there are enough DVAs in the entry to service our request,
3864 		 * then we can just use them as-is.
3865 		 */
3866 		if (have_dvas >= need_dvas) {
3867 			ddt_bp_fill(ddp, v, bp, txg);
3868 			ddt_phys_addref(ddp, v);
3869 			ddt_exit(ddt);
3870 			return (zio);
3871 		}
3872 
3873 		/*
3874 		 * Otherwise, we have to issue IO to fill the entry up to the
3875 		 * amount we need.
3876 		 */
3877 		need_dvas -= have_dvas;
3878 	} else {
3879 		/*
3880 		 * There's a write in-flight. If there's already enough DVAs on
3881 		 * the entry, then either there were already enough to start
3882 		 * with, or the in-flight IO is between READY and DONE, and so
3883 		 * has extended the entry with new DVAs. Either way, we don't
3884 		 * need to do anything, we can just slot in behind it.
3885 		 */
3886 
3887 		if (zio->io_bp_override) {
3888 			/*
3889 			 * If there's a write out, then we're soon going to
3890 			 * have our own copies of this block, so clear out the
3891 			 * override block and treat it as a regular dedup
3892 			 * write. See comment above.
3893 			 */
3894 			BP_ZERO_DVAS(bp);
3895 			BP_SET_BIRTH(bp, 0, 0);
3896 		}
3897 
3898 		if (have_dvas >= need_dvas) {
3899 			/*
3900 			 * A minor point: there might already be enough
3901 			 * committed DVAs in the entry to service our request,
3902 			 * but we don't know which are completed and which are
3903 			 * allocated but not yet written. In this case, should
3904 			 * the IO for the new DVAs fail, we will be on the end
3905 			 * of the IO chain and will also recieve an error, even
3906 			 * though our request could have been serviced.
3907 			 *
3908 			 * This is an extremely rare case, as it requires the
3909 			 * original block to be copied with a request for a
3910 			 * larger number of DVAs, then copied again requesting
3911 			 * the same (or already fulfilled) number of DVAs while
3912 			 * the first request is active, and then that first
3913 			 * request errors. In return, the logic required to
3914 			 * catch and handle it is complex. For now, I'm just
3915 			 * not going to bother with it.
3916 			 */
3917 
3918 			/*
3919 			 * We always fill the bp here as we may have arrived
3920 			 * after the in-flight write has passed READY, and so
3921 			 * missed out.
3922 			 */
3923 			ddt_bp_fill(ddp, v, bp, txg);
3924 			zio_add_child(zio, dde->dde_io->dde_lead_zio[p]);
3925 			ddt_exit(ddt);
3926 			return (zio);
3927 		}
3928 
3929 		/*
3930 		 * There's not enough in the entry yet, so we need to look at
3931 		 * the write in-flight and see how many DVAs it will have once
3932 		 * it completes.
3933 		 *
3934 		 * The in-flight write has potentially had its copies request
3935 		 * reduced (if we're filling out an existing entry), so we need
3936 		 * to reach in and get the original write to find out what it is
3937 		 * expecting.
3938 		 *
3939 		 * Note that the parent of the lead zio will always have the
3940 		 * highest zp_copies of any zio in the chain, because ones that
3941 		 * can be serviced without additional IO are always added to
3942 		 * the back of the chain.
3943 		 */
3944 		zio_link_t *zl = NULL;
3945 		zio_t *pio =
3946 		    zio_walk_parents(dde->dde_io->dde_lead_zio[p], &zl);
3947 		ASSERT(pio);
3948 		parent_dvas = pio->io_prop.zp_copies;
3949 
3950 		if (parent_dvas >= need_dvas) {
3951 			zio_add_child(zio, dde->dde_io->dde_lead_zio[p]);
3952 			ddt_exit(ddt);
3953 			return (zio);
3954 		}
3955 
3956 		/*
3957 		 * Still not enough, so we will need to issue to get the
3958 		 * shortfall.
3959 		 */
3960 		need_dvas -= parent_dvas;
3961 	}
3962 
3963 	if (is_ganged) {
3964 		zp->zp_dedup = B_FALSE;
3965 		BP_SET_DEDUP(bp, B_FALSE);
3966 		zio->io_pipeline = ZIO_WRITE_PIPELINE;
3967 		ddt_exit(ddt);
3968 		return (zio);
3969 	}
3970 
3971 	/*
3972 	 * We need to write. We will create a new write with the copies
3973 	 * property adjusted to match the number of DVAs we need to need to
3974 	 * grow the DDT entry by to satisfy the request.
3975 	 */
3976 	zio_prop_t czp = *zp;
3977 	if (have_dvas > 0 || parent_dvas > 0) {
3978 		czp.zp_copies = need_dvas;
3979 		czp.zp_gang_copies = 0;
3980 	} else {
3981 		ASSERT3U(czp.zp_copies, ==, need_dvas);
3982 	}
3983 
3984 	zio_t *cio = zio_write(zio, spa, txg, bp, zio->io_orig_abd,
3985 	    zio->io_orig_size, zio->io_orig_size, &czp,
3986 	    zio_ddt_child_write_ready, NULL,
3987 	    zio_ddt_child_write_done, dde, zio->io_priority,
3988 	    ZIO_DDT_CHILD_FLAGS(zio), &zio->io_bookmark);
3989 
3990 	zio_push_transform(cio, zio->io_abd, zio->io_size, 0, NULL);
3991 
3992 	/*
3993 	 * We are the new lead zio, because our parent has the highest
3994 	 * zp_copies that has been requested for this entry so far.
3995 	 */
3996 	ddt_alloc_entry_io(dde);
3997 	if (dde->dde_io->dde_lead_zio[p] == NULL) {
3998 		/*
3999 		 * First time out, take a copy of the stable entry to revert
4000 		 * to if there's an error (see zio_ddt_child_write_done())
4001 		 */
4002 		ddt_phys_copy(&dde->dde_io->dde_orig_phys, dde->dde_phys, v);
4003 	} else {
4004 		/*
4005 		 * Make the existing chain our child, because it cannot
4006 		 * complete until we have.
4007 		 */
4008 		zio_add_child(cio, dde->dde_io->dde_lead_zio[p]);
4009 	}
4010 	dde->dde_io->dde_lead_zio[p] = cio;
4011 
4012 	ddt_exit(ddt);
4013 
4014 	zio_nowait(cio);
4015 
4016 	return (zio);
4017 }
4018 
4019 static ddt_entry_t *freedde; /* for debugging */
4020 
4021 static zio_t *
zio_ddt_free(zio_t * zio)4022 zio_ddt_free(zio_t *zio)
4023 {
4024 	spa_t *spa = zio->io_spa;
4025 	blkptr_t *bp = zio->io_bp;
4026 	ddt_t *ddt = ddt_select(spa, bp);
4027 	ddt_entry_t *dde = NULL;
4028 
4029 	ASSERT(BP_GET_DEDUP(bp));
4030 	ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
4031 
4032 	ddt_enter(ddt);
4033 	freedde = dde = ddt_lookup(ddt, bp, B_TRUE);
4034 	if (dde) {
4035 		ddt_phys_variant_t v = ddt_phys_select(ddt, dde, bp);
4036 		if (v != DDT_PHYS_NONE)
4037 			ddt_phys_decref(dde->dde_phys, v);
4038 	}
4039 	ddt_exit(ddt);
4040 
4041 	/*
4042 	 * When no entry was found, it must have been pruned,
4043 	 * so we can free it now instead of decrementing the
4044 	 * refcount in the DDT.
4045 	 */
4046 	if (!dde) {
4047 		BP_SET_DEDUP(bp, 0);
4048 		zio->io_pipeline |= ZIO_STAGE_DVA_FREE;
4049 	}
4050 
4051 	return (zio);
4052 }
4053 
4054 /*
4055  * ==========================================================================
4056  * Allocate and free blocks
4057  * ==========================================================================
4058  */
4059 
4060 static zio_t *
zio_io_to_allocate(metaslab_class_allocator_t * mca,boolean_t * more)4061 zio_io_to_allocate(metaslab_class_allocator_t *mca, boolean_t *more)
4062 {
4063 	zio_t *zio;
4064 
4065 	ASSERT(MUTEX_HELD(&mca->mca_lock));
4066 
4067 	zio = avl_first(&mca->mca_tree);
4068 	if (zio == NULL) {
4069 		*more = B_FALSE;
4070 		return (NULL);
4071 	}
4072 
4073 	ASSERT(IO_IS_ALLOCATING(zio));
4074 	ASSERT(ZIO_HAS_ALLOCATOR(zio));
4075 
4076 	/*
4077 	 * Try to place a reservation for this zio. If we're unable to
4078 	 * reserve then we throttle.
4079 	 */
4080 	if (!metaslab_class_throttle_reserve(zio->io_metaslab_class,
4081 	    zio->io_prop.zp_copies, zio, B_FALSE, more)) {
4082 		return (NULL);
4083 	}
4084 
4085 	avl_remove(&mca->mca_tree, zio);
4086 	ASSERT3U(zio->io_stage, <, ZIO_STAGE_DVA_ALLOCATE);
4087 
4088 	if (avl_is_empty(&mca->mca_tree))
4089 		*more = B_FALSE;
4090 	return (zio);
4091 }
4092 
4093 static zio_t *
zio_dva_throttle(zio_t * zio)4094 zio_dva_throttle(zio_t *zio)
4095 {
4096 	spa_t *spa = zio->io_spa;
4097 	zio_t *nio;
4098 	metaslab_class_t *mc;
4099 	boolean_t more;
4100 
4101 	/*
4102 	 * If not already chosen, choose an appropriate allocation class.
4103 	 */
4104 	mc = zio->io_metaslab_class;
4105 	if (mc == NULL)
4106 		mc = spa_preferred_class(spa, zio);
4107 
4108 	if (zio->io_priority == ZIO_PRIORITY_SYNC_WRITE ||
4109 	    !mc->mc_alloc_throttle_enabled ||
4110 	    zio->io_child_type == ZIO_CHILD_GANG ||
4111 	    zio->io_flags & ZIO_FLAG_NODATA) {
4112 		return (zio);
4113 	}
4114 
4115 	ASSERT(zio->io_type == ZIO_TYPE_WRITE);
4116 	ASSERT(ZIO_HAS_ALLOCATOR(zio));
4117 	ASSERT(zio->io_child_type > ZIO_CHILD_GANG);
4118 	ASSERT3U(zio->io_queued_timestamp, >, 0);
4119 	ASSERT(zio->io_stage == ZIO_STAGE_DVA_THROTTLE);
4120 
4121 	zio->io_metaslab_class = mc;
4122 	metaslab_class_allocator_t *mca = &mc->mc_allocator[zio->io_allocator];
4123 	mutex_enter(&mca->mca_lock);
4124 	avl_add(&mca->mca_tree, zio);
4125 	nio = zio_io_to_allocate(mca, &more);
4126 	mutex_exit(&mca->mca_lock);
4127 	return (nio);
4128 }
4129 
4130 static void
zio_allocate_dispatch(metaslab_class_t * mc,int allocator)4131 zio_allocate_dispatch(metaslab_class_t *mc, int allocator)
4132 {
4133 	metaslab_class_allocator_t *mca = &mc->mc_allocator[allocator];
4134 	zio_t *zio;
4135 	boolean_t more;
4136 
4137 	do {
4138 		mutex_enter(&mca->mca_lock);
4139 		zio = zio_io_to_allocate(mca, &more);
4140 		mutex_exit(&mca->mca_lock);
4141 		if (zio == NULL)
4142 			return;
4143 
4144 		ASSERT3U(zio->io_stage, ==, ZIO_STAGE_DVA_THROTTLE);
4145 		ASSERT0(zio->io_error);
4146 		zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE, B_TRUE);
4147 	} while (more);
4148 }
4149 
4150 static zio_t *
zio_dva_allocate(zio_t * zio)4151 zio_dva_allocate(zio_t *zio)
4152 {
4153 	spa_t *spa = zio->io_spa;
4154 	metaslab_class_t *mc, *newmc;
4155 	blkptr_t *bp = zio->io_bp;
4156 	int error;
4157 	int flags = 0;
4158 
4159 	if (zio->io_gang_leader == NULL) {
4160 		ASSERT(zio->io_child_type > ZIO_CHILD_GANG);
4161 		zio->io_gang_leader = zio;
4162 	}
4163 	if (zio->io_flags & ZIO_FLAG_PREALLOCATED) {
4164 		ASSERT3U(zio->io_child_type, ==, ZIO_CHILD_GANG);
4165 		memcpy(zio->io_bp->blk_dva, zio->io_bp_orig.blk_dva,
4166 		    3 * sizeof (dva_t));
4167 		BP_SET_BIRTH(zio->io_bp, BP_GET_LOGICAL_BIRTH(&zio->io_bp_orig),
4168 		    BP_GET_PHYSICAL_BIRTH(&zio->io_bp_orig));
4169 		return (zio);
4170 	}
4171 
4172 	ASSERT(BP_IS_HOLE(bp));
4173 	ASSERT0(BP_GET_NDVAS(bp));
4174 	ASSERT3U(zio->io_prop.zp_copies, >, 0);
4175 
4176 	ASSERT3U(zio->io_prop.zp_copies, <=, spa_max_replication(spa));
4177 	ASSERT3U(zio->io_size, ==, BP_GET_PSIZE(bp));
4178 
4179 	if (zio->io_flags & ZIO_FLAG_GANG_CHILD)
4180 		flags |= METASLAB_GANG_CHILD;
4181 	if (zio->io_priority == ZIO_PRIORITY_ASYNC_WRITE)
4182 		flags |= METASLAB_ASYNC_ALLOC;
4183 
4184 	/*
4185 	 * If not already chosen, choose an appropriate allocation class.
4186 	 */
4187 	mc = zio->io_metaslab_class;
4188 	if (mc == NULL) {
4189 		mc = spa_preferred_class(spa, zio);
4190 		zio->io_metaslab_class = mc;
4191 	}
4192 	ZIOSTAT_BUMP(ziostat_total_allocations);
4193 
4194 again:
4195 	/*
4196 	 * Try allocating the block in the usual metaslab class.
4197 	 * If that's full, allocate it in some other class(es).
4198 	 * If that's full, allocate as a gang block,
4199 	 * and if all are full, the allocation fails (which shouldn't happen).
4200 	 *
4201 	 * Note that we do not fall back on embedded slog (ZIL) space, to
4202 	 * preserve unfragmented slog space, which is critical for decent
4203 	 * sync write performance.  If a log allocation fails, we will fall
4204 	 * back to spa_sync() which is abysmal for performance.
4205 	 */
4206 	ASSERT(ZIO_HAS_ALLOCATOR(zio));
4207 	error = metaslab_alloc(spa, mc, zio->io_size, bp,
4208 	    zio->io_prop.zp_copies, zio->io_txg, NULL, flags,
4209 	    &zio->io_alloc_list, zio->io_allocator, zio);
4210 
4211 	/*
4212 	 * When the dedup or special class is spilling into the normal class,
4213 	 * there can still be significant space available due to deferred
4214 	 * frees that are in-flight.  We track the txg when this occurred and
4215 	 * back off adding new DDT entries for a few txgs to allow the free
4216 	 * blocks to be processed.
4217 	 */
4218 	if (error == ENOSPC && spa->spa_dedup_class_full_txg != zio->io_txg &&
4219 	    (mc == spa_dedup_class(spa) || (mc == spa_special_class(spa) &&
4220 	    !spa_has_dedup(spa) && spa_special_has_ddt(spa)))) {
4221 		spa->spa_dedup_class_full_txg = zio->io_txg;
4222 		zfs_dbgmsg("%s[%llu]: %s class spilling, req size %llu, "
4223 		    "%llu allocated of %llu",
4224 		    spa_name(spa), (u_longlong_t)zio->io_txg,
4225 		    metaslab_class_get_name(mc),
4226 		    (u_longlong_t)zio->io_size,
4227 		    (u_longlong_t)metaslab_class_get_alloc(mc),
4228 		    (u_longlong_t)metaslab_class_get_space(mc));
4229 	}
4230 
4231 	/*
4232 	 * Fall back to some other class when this one is full.
4233 	 */
4234 	if (error == ENOSPC && (newmc = spa_preferred_class(spa, zio)) != mc) {
4235 		/*
4236 		 * If we are holding old class reservation, drop it.
4237 		 * Dispatch the next ZIO(s) there if some are waiting.
4238 		 */
4239 		if (zio->io_flags & ZIO_FLAG_IO_ALLOCATING) {
4240 			if (metaslab_class_throttle_unreserve(mc,
4241 			    zio->io_prop.zp_copies, zio)) {
4242 				zio_allocate_dispatch(zio->io_metaslab_class,
4243 				    zio->io_allocator);
4244 			}
4245 			zio->io_flags &= ~ZIO_FLAG_IO_ALLOCATING;
4246 		}
4247 
4248 		if (zfs_flags & ZFS_DEBUG_METASLAB_ALLOC) {
4249 			zfs_dbgmsg("%s: metaslab allocation failure in %s "
4250 			    "class, trying fallback to %s class: zio %px, "
4251 			    "size %llu, error %d", spa_name(spa),
4252 			    metaslab_class_get_name(mc),
4253 			    metaslab_class_get_name(newmc),
4254 			    zio, (u_longlong_t)zio->io_size, error);
4255 		}
4256 		zio->io_metaslab_class = mc = newmc;
4257 		ZIOSTAT_BUMP(ziostat_alloc_class_fallbacks);
4258 
4259 		/*
4260 		 * If the new class uses throttling, return to that pipeline
4261 		 * stage.  Otherwise just do another allocation attempt.
4262 		 */
4263 		if (zio->io_priority != ZIO_PRIORITY_SYNC_WRITE &&
4264 		    mc->mc_alloc_throttle_enabled &&
4265 		    zio->io_child_type != ZIO_CHILD_GANG &&
4266 		    !(zio->io_flags & ZIO_FLAG_NODATA)) {
4267 			zio->io_stage = ZIO_STAGE_DVA_THROTTLE >> 1;
4268 			return (zio);
4269 		}
4270 		goto again;
4271 	}
4272 
4273 	if (error == ENOSPC && zio->io_size > spa->spa_min_alloc) {
4274 		if (zfs_flags & ZFS_DEBUG_METASLAB_ALLOC) {
4275 			zfs_dbgmsg("%s: metaslab allocation failure, "
4276 			    "trying ganging: zio %px, size %llu, error %d",
4277 			    spa_name(spa), zio, (u_longlong_t)zio->io_size,
4278 			    error);
4279 		}
4280 		ZIOSTAT_BUMP(ziostat_gang_writes);
4281 		if (flags & METASLAB_GANG_CHILD)
4282 			ZIOSTAT_BUMP(ziostat_gang_multilevel);
4283 		return (zio_write_gang_block(zio, mc));
4284 	}
4285 	if (error != 0) {
4286 		if (error != ENOSPC ||
4287 		    (zfs_flags & ZFS_DEBUG_METASLAB_ALLOC)) {
4288 			zfs_dbgmsg("%s: metaslab allocation failure: zio %px, "
4289 			    "size %llu, error %d",
4290 			    spa_name(spa), zio, (u_longlong_t)zio->io_size,
4291 			    error);
4292 		}
4293 		zio->io_error = error;
4294 	}
4295 
4296 	return (zio);
4297 }
4298 
4299 static zio_t *
zio_dva_free(zio_t * zio)4300 zio_dva_free(zio_t *zio)
4301 {
4302 	metaslab_free(zio->io_spa, zio->io_bp, zio->io_txg, B_FALSE);
4303 
4304 	return (zio);
4305 }
4306 
4307 static zio_t *
zio_dva_claim(zio_t * zio)4308 zio_dva_claim(zio_t *zio)
4309 {
4310 	int error;
4311 
4312 	error = metaslab_claim(zio->io_spa, zio->io_bp, zio->io_txg);
4313 	if (error)
4314 		zio->io_error = error;
4315 
4316 	return (zio);
4317 }
4318 
4319 /*
4320  * Undo an allocation.  This is used by zio_done() when an I/O fails
4321  * and we want to give back the block we just allocated.
4322  * This handles both normal blocks and gang blocks.
4323  */
4324 static void
zio_dva_unallocate(zio_t * zio,zio_gang_node_t * gn,blkptr_t * bp)4325 zio_dva_unallocate(zio_t *zio, zio_gang_node_t *gn, blkptr_t *bp)
4326 {
4327 	ASSERT(BP_GET_LOGICAL_BIRTH(bp) == zio->io_txg || BP_IS_HOLE(bp));
4328 	ASSERT(zio->io_bp_override == NULL);
4329 
4330 	if (!BP_IS_HOLE(bp)) {
4331 		metaslab_free(zio->io_spa, bp, BP_GET_LOGICAL_BIRTH(bp),
4332 		    B_TRUE);
4333 	}
4334 
4335 	if (gn != NULL) {
4336 		for (int g = 0; g < SPA_GBH_NBLKPTRS; g++) {
4337 			zio_dva_unallocate(zio, gn->gn_child[g],
4338 			    &gn->gn_gbh->zg_blkptr[g]);
4339 		}
4340 	}
4341 }
4342 
4343 /*
4344  * Try to allocate an intent log block.  Return 0 on success, errno on failure.
4345  */
4346 int
zio_alloc_zil(spa_t * spa,objset_t * os,uint64_t txg,blkptr_t * new_bp,uint64_t size,boolean_t * slog)4347 zio_alloc_zil(spa_t *spa, objset_t *os, uint64_t txg, blkptr_t *new_bp,
4348     uint64_t size, boolean_t *slog)
4349 {
4350 	int error = 1;
4351 	zio_alloc_list_t io_alloc_list;
4352 
4353 	ASSERT(txg > spa_syncing_txg(spa));
4354 
4355 	metaslab_trace_init(&io_alloc_list);
4356 
4357 	/*
4358 	 * Block pointer fields are useful to metaslabs for stats and debugging.
4359 	 * Fill in the obvious ones before calling into metaslab_alloc().
4360 	 */
4361 	BP_SET_TYPE(new_bp, DMU_OT_INTENT_LOG);
4362 	BP_SET_PSIZE(new_bp, size);
4363 	BP_SET_LEVEL(new_bp, 0);
4364 
4365 	/*
4366 	 * When allocating a zil block, we don't have information about
4367 	 * the final destination of the block except the objset it's part
4368 	 * of, so we just hash the objset ID to pick the allocator to get
4369 	 * some parallelism.
4370 	 */
4371 	int flags = METASLAB_ZIL;
4372 	int allocator = (uint_t)cityhash1(os->os_dsl_dataset->ds_object)
4373 	    % spa->spa_alloc_count;
4374 	ZIOSTAT_BUMP(ziostat_total_allocations);
4375 	error = metaslab_alloc(spa, spa_log_class(spa), size, new_bp, 1,
4376 	    txg, NULL, flags, &io_alloc_list, allocator, NULL);
4377 	*slog = (error == 0);
4378 	if (error != 0) {
4379 		error = metaslab_alloc(spa, spa_embedded_log_class(spa), size,
4380 		    new_bp, 1, txg, NULL, flags, &io_alloc_list, allocator,
4381 		    NULL);
4382 	}
4383 	if (error != 0) {
4384 		ZIOSTAT_BUMP(ziostat_alloc_class_fallbacks);
4385 		error = metaslab_alloc(spa, spa_normal_class(spa), size,
4386 		    new_bp, 1, txg, NULL, flags, &io_alloc_list, allocator,
4387 		    NULL);
4388 	}
4389 	metaslab_trace_fini(&io_alloc_list);
4390 
4391 	if (error == 0) {
4392 		BP_SET_LSIZE(new_bp, size);
4393 		BP_SET_PSIZE(new_bp, size);
4394 		BP_SET_COMPRESS(new_bp, ZIO_COMPRESS_OFF);
4395 		BP_SET_CHECKSUM(new_bp,
4396 		    spa_version(spa) >= SPA_VERSION_SLIM_ZIL
4397 		    ? ZIO_CHECKSUM_ZILOG2 : ZIO_CHECKSUM_ZILOG);
4398 		BP_SET_TYPE(new_bp, DMU_OT_INTENT_LOG);
4399 		BP_SET_LEVEL(new_bp, 0);
4400 		BP_SET_DEDUP(new_bp, 0);
4401 		BP_SET_BYTEORDER(new_bp, ZFS_HOST_BYTEORDER);
4402 
4403 		/*
4404 		 * encrypted blocks will require an IV and salt. We generate
4405 		 * these now since we will not be rewriting the bp at
4406 		 * rewrite time.
4407 		 */
4408 		if (os->os_encrypted) {
4409 			uint8_t iv[ZIO_DATA_IV_LEN];
4410 			uint8_t salt[ZIO_DATA_SALT_LEN];
4411 
4412 			BP_SET_CRYPT(new_bp, B_TRUE);
4413 			VERIFY0(spa_crypt_get_salt(spa,
4414 			    dmu_objset_id(os), salt));
4415 			VERIFY0(zio_crypt_generate_iv(iv));
4416 
4417 			zio_crypt_encode_params_bp(new_bp, salt, iv);
4418 		}
4419 	} else {
4420 		zfs_dbgmsg("%s: zil block allocation failure: "
4421 		    "size %llu, error %d", spa_name(spa), (u_longlong_t)size,
4422 		    error);
4423 	}
4424 
4425 	return (error);
4426 }
4427 
4428 /*
4429  * ==========================================================================
4430  * Read and write to physical devices
4431  * ==========================================================================
4432  */
4433 
4434 /*
4435  * Issue an I/O to the underlying vdev. Typically the issue pipeline
4436  * stops after this stage and will resume upon I/O completion.
4437  * However, there are instances where the vdev layer may need to
4438  * continue the pipeline when an I/O was not issued. Since the I/O
4439  * that was sent to the vdev layer might be different than the one
4440  * currently active in the pipeline (see vdev_queue_io()), we explicitly
4441  * force the underlying vdev layers to call either zio_execute() or
4442  * zio_interrupt() to ensure that the pipeline continues with the correct I/O.
4443  */
4444 static zio_t *
zio_vdev_io_start(zio_t * zio)4445 zio_vdev_io_start(zio_t *zio)
4446 {
4447 	vdev_t *vd = zio->io_vd;
4448 	uint64_t align;
4449 	spa_t *spa = zio->io_spa;
4450 
4451 	zio->io_delay = 0;
4452 
4453 	ASSERT(zio->io_error == 0);
4454 	ASSERT(zio->io_child_error[ZIO_CHILD_VDEV] == 0);
4455 
4456 	if (vd == NULL) {
4457 		if (!(zio->io_flags & ZIO_FLAG_CONFIG_WRITER))
4458 			spa_config_enter(spa, SCL_ZIO, zio, RW_READER);
4459 
4460 		/*
4461 		 * The mirror_ops handle multiple DVAs in a single BP.
4462 		 */
4463 		vdev_mirror_ops.vdev_op_io_start(zio);
4464 		return (NULL);
4465 	}
4466 
4467 	ASSERT3P(zio->io_logical, !=, zio);
4468 	if (zio->io_type == ZIO_TYPE_WRITE) {
4469 		ASSERT(spa->spa_trust_config);
4470 
4471 		/*
4472 		 * Note: the code can handle other kinds of writes,
4473 		 * but we don't expect them.
4474 		 */
4475 		if (zio->io_vd->vdev_noalloc) {
4476 			ASSERT(zio->io_flags &
4477 			    (ZIO_FLAG_PHYSICAL | ZIO_FLAG_SELF_HEAL |
4478 			    ZIO_FLAG_RESILVER | ZIO_FLAG_INDUCE_DAMAGE));
4479 		}
4480 	}
4481 
4482 	align = 1ULL << vd->vdev_top->vdev_ashift;
4483 
4484 	if (!(zio->io_flags & ZIO_FLAG_PHYSICAL) &&
4485 	    P2PHASE(zio->io_size, align) != 0) {
4486 		/* Transform logical writes to be a full physical block size. */
4487 		uint64_t asize = P2ROUNDUP(zio->io_size, align);
4488 		abd_t *abuf = abd_alloc_sametype(zio->io_abd, asize);
4489 		ASSERT(vd == vd->vdev_top);
4490 		if (zio->io_type == ZIO_TYPE_WRITE) {
4491 			abd_copy(abuf, zio->io_abd, zio->io_size);
4492 			abd_zero_off(abuf, zio->io_size, asize - zio->io_size);
4493 		}
4494 		zio_push_transform(zio, abuf, asize, asize, zio_subblock);
4495 	}
4496 
4497 	/*
4498 	 * If this is not a physical io, make sure that it is properly aligned
4499 	 * before proceeding.
4500 	 */
4501 	if (!(zio->io_flags & ZIO_FLAG_PHYSICAL)) {
4502 		ASSERT0(P2PHASE(zio->io_offset, align));
4503 		ASSERT0(P2PHASE(zio->io_size, align));
4504 	} else {
4505 		/*
4506 		 * For physical writes, we allow 512b aligned writes and assume
4507 		 * the device will perform a read-modify-write as necessary.
4508 		 */
4509 		ASSERT0(P2PHASE(zio->io_offset, SPA_MINBLOCKSIZE));
4510 		ASSERT0(P2PHASE(zio->io_size, SPA_MINBLOCKSIZE));
4511 	}
4512 
4513 	VERIFY(zio->io_type != ZIO_TYPE_WRITE || spa_writeable(spa));
4514 
4515 	/*
4516 	 * If this is a repair I/O, and there's no self-healing involved --
4517 	 * that is, we're just resilvering what we expect to resilver --
4518 	 * then don't do the I/O unless zio's txg is actually in vd's DTL.
4519 	 * This prevents spurious resilvering.
4520 	 *
4521 	 * There are a few ways that we can end up creating these spurious
4522 	 * resilver i/os:
4523 	 *
4524 	 * 1. A resilver i/o will be issued if any DVA in the BP has a
4525 	 * dirty DTL.  The mirror code will issue resilver writes to
4526 	 * each DVA, including the one(s) that are not on vdevs with dirty
4527 	 * DTLs.
4528 	 *
4529 	 * 2. With nested replication, which happens when we have a
4530 	 * "replacing" or "spare" vdev that's a child of a mirror or raidz.
4531 	 * For example, given mirror(replacing(A+B), C), it's likely that
4532 	 * only A is out of date (it's the new device). In this case, we'll
4533 	 * read from C, then use the data to resilver A+B -- but we don't
4534 	 * actually want to resilver B, just A. The top-level mirror has no
4535 	 * way to know this, so instead we just discard unnecessary repairs
4536 	 * as we work our way down the vdev tree.
4537 	 *
4538 	 * 3. ZTEST also creates mirrors of mirrors, mirrors of raidz, etc.
4539 	 * The same logic applies to any form of nested replication: ditto
4540 	 * + mirror, RAID-Z + replacing, etc.
4541 	 *
4542 	 * However, indirect vdevs point off to other vdevs which may have
4543 	 * DTL's, so we never bypass them.  The child i/os on concrete vdevs
4544 	 * will be properly bypassed instead.
4545 	 *
4546 	 * Leaf DTL_PARTIAL can be empty when a legitimate write comes from
4547 	 * a dRAID spare vdev. For example, when a dRAID spare is first
4548 	 * used, its spare blocks need to be written to but the leaf vdev's
4549 	 * of such blocks can have empty DTL_PARTIAL.
4550 	 *
4551 	 * There seemed no clean way to allow such writes while bypassing
4552 	 * spurious ones. At this point, just avoid all bypassing for dRAID
4553 	 * for correctness.
4554 	 */
4555 	if ((zio->io_flags & ZIO_FLAG_IO_REPAIR) &&
4556 	    !(zio->io_flags & ZIO_FLAG_SELF_HEAL) &&
4557 	    zio->io_txg != 0 &&	/* not a delegated i/o */
4558 	    vd->vdev_ops != &vdev_indirect_ops &&
4559 	    vd->vdev_top->vdev_ops != &vdev_draid_ops &&
4560 	    !vdev_dtl_contains(vd, DTL_PARTIAL, zio->io_txg, 1)) {
4561 		ASSERT(zio->io_type == ZIO_TYPE_WRITE);
4562 		zio_vdev_io_bypass(zio);
4563 		return (zio);
4564 	}
4565 
4566 	/*
4567 	 * Select the next best leaf I/O to process.  Distributed spares are
4568 	 * excluded since they dispatch the I/O directly to a leaf vdev after
4569 	 * applying the dRAID mapping.
4570 	 */
4571 	if (vd->vdev_ops->vdev_op_leaf &&
4572 	    vd->vdev_ops != &vdev_draid_spare_ops &&
4573 	    (zio->io_type == ZIO_TYPE_READ ||
4574 	    zio->io_type == ZIO_TYPE_WRITE ||
4575 	    zio->io_type == ZIO_TYPE_TRIM)) {
4576 
4577 		if ((zio = vdev_queue_io(zio)) == NULL)
4578 			return (NULL);
4579 
4580 		if (!vdev_accessible(vd, zio)) {
4581 			zio->io_error = SET_ERROR(ENXIO);
4582 			zio_interrupt(zio);
4583 			return (NULL);
4584 		}
4585 		zio->io_delay = gethrtime();
4586 
4587 		if (zio_handle_device_injection(vd, zio, ENOSYS) != 0) {
4588 			/*
4589 			 * "no-op" injections return success, but do no actual
4590 			 * work. Just return it.
4591 			 */
4592 			zio_delay_interrupt(zio);
4593 			return (NULL);
4594 		}
4595 	}
4596 
4597 	vd->vdev_ops->vdev_op_io_start(zio);
4598 	return (NULL);
4599 }
4600 
4601 static zio_t *
zio_vdev_io_done(zio_t * zio)4602 zio_vdev_io_done(zio_t *zio)
4603 {
4604 	vdev_t *vd = zio->io_vd;
4605 	vdev_ops_t *ops = vd ? vd->vdev_ops : &vdev_mirror_ops;
4606 	boolean_t unexpected_error = B_FALSE;
4607 
4608 	if (zio_wait_for_children(zio, ZIO_CHILD_VDEV_BIT, ZIO_WAIT_DONE)) {
4609 		return (NULL);
4610 	}
4611 
4612 	ASSERT(zio->io_type == ZIO_TYPE_READ ||
4613 	    zio->io_type == ZIO_TYPE_WRITE ||
4614 	    zio->io_type == ZIO_TYPE_FLUSH ||
4615 	    zio->io_type == ZIO_TYPE_TRIM);
4616 
4617 	if (zio->io_delay)
4618 		zio->io_delay = gethrtime() - zio->io_delay;
4619 
4620 	if (vd != NULL && vd->vdev_ops->vdev_op_leaf &&
4621 	    vd->vdev_ops != &vdev_draid_spare_ops) {
4622 		if (zio->io_type != ZIO_TYPE_FLUSH)
4623 			vdev_queue_io_done(zio);
4624 
4625 		if (zio_injection_enabled && zio->io_error == 0)
4626 			zio->io_error = zio_handle_device_injections(vd, zio,
4627 			    EIO, EILSEQ);
4628 
4629 		if (zio_injection_enabled && zio->io_error == 0)
4630 			zio->io_error = zio_handle_label_injection(zio, EIO);
4631 
4632 		if (zio->io_error && zio->io_type != ZIO_TYPE_FLUSH &&
4633 		    zio->io_type != ZIO_TYPE_TRIM) {
4634 			if (!vdev_accessible(vd, zio)) {
4635 				zio->io_error = SET_ERROR(ENXIO);
4636 			} else {
4637 				unexpected_error = B_TRUE;
4638 			}
4639 		}
4640 	}
4641 
4642 	ops->vdev_op_io_done(zio);
4643 
4644 	if (unexpected_error && vd->vdev_remove_wanted == B_FALSE)
4645 		VERIFY(vdev_probe(vd, zio) == NULL);
4646 
4647 	return (zio);
4648 }
4649 
4650 /*
4651  * This function is used to change the priority of an existing zio that is
4652  * currently in-flight. This is used by the arc to upgrade priority in the
4653  * event that a demand read is made for a block that is currently queued
4654  * as a scrub or async read IO. Otherwise, the high priority read request
4655  * would end up having to wait for the lower priority IO.
4656  */
4657 void
zio_change_priority(zio_t * pio,zio_priority_t priority)4658 zio_change_priority(zio_t *pio, zio_priority_t priority)
4659 {
4660 	zio_t *cio, *cio_next;
4661 	zio_link_t *zl = NULL;
4662 
4663 	ASSERT3U(priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
4664 
4665 	if (pio->io_vd != NULL && pio->io_vd->vdev_ops->vdev_op_leaf) {
4666 		vdev_queue_change_io_priority(pio, priority);
4667 	} else {
4668 		pio->io_priority = priority;
4669 	}
4670 
4671 	mutex_enter(&pio->io_lock);
4672 	for (cio = zio_walk_children(pio, &zl); cio != NULL; cio = cio_next) {
4673 		cio_next = zio_walk_children(pio, &zl);
4674 		zio_change_priority(cio, priority);
4675 	}
4676 	mutex_exit(&pio->io_lock);
4677 }
4678 
4679 /*
4680  * For non-raidz ZIOs, we can just copy aside the bad data read from the
4681  * disk, and use that to finish the checksum ereport later.
4682  */
4683 static void
zio_vsd_default_cksum_finish(zio_cksum_report_t * zcr,const abd_t * good_buf)4684 zio_vsd_default_cksum_finish(zio_cksum_report_t *zcr,
4685     const abd_t *good_buf)
4686 {
4687 	/* no processing needed */
4688 	zfs_ereport_finish_checksum(zcr, good_buf, zcr->zcr_cbdata, B_FALSE);
4689 }
4690 
4691 void
zio_vsd_default_cksum_report(zio_t * zio,zio_cksum_report_t * zcr)4692 zio_vsd_default_cksum_report(zio_t *zio, zio_cksum_report_t *zcr)
4693 {
4694 	void *abd = abd_alloc_sametype(zio->io_abd, zio->io_size);
4695 
4696 	abd_copy(abd, zio->io_abd, zio->io_size);
4697 
4698 	zcr->zcr_cbinfo = zio->io_size;
4699 	zcr->zcr_cbdata = abd;
4700 	zcr->zcr_finish = zio_vsd_default_cksum_finish;
4701 	zcr->zcr_free = zio_abd_free;
4702 }
4703 
4704 static zio_t *
zio_vdev_io_assess(zio_t * zio)4705 zio_vdev_io_assess(zio_t *zio)
4706 {
4707 	vdev_t *vd = zio->io_vd;
4708 
4709 	if (zio_wait_for_children(zio, ZIO_CHILD_VDEV_BIT, ZIO_WAIT_DONE)) {
4710 		return (NULL);
4711 	}
4712 
4713 	if (vd == NULL && !(zio->io_flags & ZIO_FLAG_CONFIG_WRITER))
4714 		spa_config_exit(zio->io_spa, SCL_ZIO, zio);
4715 
4716 	if (zio->io_vsd != NULL) {
4717 		zio->io_vsd_ops->vsd_free(zio);
4718 		zio->io_vsd = NULL;
4719 	}
4720 
4721 	/*
4722 	 * If a Direct I/O operation has a checksum verify error then this I/O
4723 	 * should not attempt to be issued again.
4724 	 */
4725 	if (zio->io_flags & ZIO_FLAG_DIO_CHKSUM_ERR) {
4726 		if (zio->io_type == ZIO_TYPE_WRITE) {
4727 			ASSERT3U(zio->io_child_type, ==, ZIO_CHILD_LOGICAL);
4728 			ASSERT3U(zio->io_error, ==, EIO);
4729 		}
4730 		zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
4731 		return (zio);
4732 	}
4733 
4734 	if (zio_injection_enabled && zio->io_error == 0)
4735 		zio->io_error = zio_handle_fault_injection(zio, EIO);
4736 
4737 	/*
4738 	 * If the I/O failed, determine whether we should attempt to retry it.
4739 	 *
4740 	 * On retry, we cut in line in the issue queue, since we don't want
4741 	 * compression/checksumming/etc. work to prevent our (cheap) IO reissue.
4742 	 */
4743 	if (zio->io_error && vd == NULL &&
4744 	    !(zio->io_flags & (ZIO_FLAG_DONT_RETRY | ZIO_FLAG_IO_RETRY))) {
4745 		ASSERT(!(zio->io_flags & ZIO_FLAG_DONT_QUEUE));	/* not a leaf */
4746 		ASSERT(!(zio->io_flags & ZIO_FLAG_IO_BYPASS));	/* not a leaf */
4747 		zio->io_error = 0;
4748 		zio->io_flags |= ZIO_FLAG_IO_RETRY | ZIO_FLAG_DONT_AGGREGATE;
4749 		zio->io_stage = ZIO_STAGE_VDEV_IO_START >> 1;
4750 		zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE,
4751 		    zio_requeue_io_start_cut_in_line);
4752 		return (NULL);
4753 	}
4754 
4755 	/*
4756 	 * If we got an error on a leaf device, convert it to ENXIO
4757 	 * if the device is not accessible at all.
4758 	 */
4759 	if (zio->io_error && vd != NULL && vd->vdev_ops->vdev_op_leaf &&
4760 	    !vdev_accessible(vd, zio))
4761 		zio->io_error = SET_ERROR(ENXIO);
4762 
4763 	/*
4764 	 * If we can't write to an interior vdev (mirror or RAID-Z),
4765 	 * set vdev_cant_write so that we stop trying to allocate from it.
4766 	 */
4767 	if (zio->io_error == ENXIO && zio->io_type == ZIO_TYPE_WRITE &&
4768 	    vd != NULL && !vd->vdev_ops->vdev_op_leaf) {
4769 		vdev_dbgmsg(vd, "zio_vdev_io_assess(zio=%px) setting "
4770 		    "cant_write=TRUE due to write failure with ENXIO",
4771 		    zio);
4772 		vd->vdev_cant_write = B_TRUE;
4773 	}
4774 
4775 	/*
4776 	 * If a cache flush returns ENOTSUP we know that no future
4777 	 * attempts will ever succeed. In this case we set a persistent
4778 	 * boolean flag so that we don't bother with it in the future, and
4779 	 * then we act like the flush succeeded.
4780 	 */
4781 	if (zio->io_error == ENOTSUP && zio->io_type == ZIO_TYPE_FLUSH &&
4782 	    vd != NULL) {
4783 		vd->vdev_nowritecache = B_TRUE;
4784 		zio->io_error = 0;
4785 	}
4786 
4787 	if (zio->io_error)
4788 		zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
4789 
4790 	return (zio);
4791 }
4792 
4793 void
zio_vdev_io_reissue(zio_t * zio)4794 zio_vdev_io_reissue(zio_t *zio)
4795 {
4796 	ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_START);
4797 	ASSERT(zio->io_error == 0);
4798 
4799 	zio->io_stage >>= 1;
4800 }
4801 
4802 void
zio_vdev_io_redone(zio_t * zio)4803 zio_vdev_io_redone(zio_t *zio)
4804 {
4805 	ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_DONE);
4806 
4807 	zio->io_stage >>= 1;
4808 }
4809 
4810 void
zio_vdev_io_bypass(zio_t * zio)4811 zio_vdev_io_bypass(zio_t *zio)
4812 {
4813 	ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_START);
4814 	ASSERT(zio->io_error == 0);
4815 
4816 	zio->io_flags |= ZIO_FLAG_IO_BYPASS;
4817 	zio->io_stage = ZIO_STAGE_VDEV_IO_ASSESS >> 1;
4818 }
4819 
4820 /*
4821  * ==========================================================================
4822  * Encrypt and store encryption parameters
4823  * ==========================================================================
4824  */
4825 
4826 
4827 /*
4828  * This function is used for ZIO_STAGE_ENCRYPT. It is responsible for
4829  * managing the storage of encryption parameters and passing them to the
4830  * lower-level encryption functions.
4831  */
4832 static zio_t *
zio_encrypt(zio_t * zio)4833 zio_encrypt(zio_t *zio)
4834 {
4835 	zio_prop_t *zp = &zio->io_prop;
4836 	spa_t *spa = zio->io_spa;
4837 	blkptr_t *bp = zio->io_bp;
4838 	uint64_t psize = BP_GET_PSIZE(bp);
4839 	uint64_t dsobj = zio->io_bookmark.zb_objset;
4840 	dmu_object_type_t ot = BP_GET_TYPE(bp);
4841 	void *enc_buf = NULL;
4842 	abd_t *eabd = NULL;
4843 	uint8_t salt[ZIO_DATA_SALT_LEN];
4844 	uint8_t iv[ZIO_DATA_IV_LEN];
4845 	uint8_t mac[ZIO_DATA_MAC_LEN];
4846 	boolean_t no_crypt = B_FALSE;
4847 
4848 	/* the root zio already encrypted the data */
4849 	if (zio->io_child_type == ZIO_CHILD_GANG)
4850 		return (zio);
4851 
4852 	/* only ZIL blocks are re-encrypted on rewrite */
4853 	if (!IO_IS_ALLOCATING(zio) && ot != DMU_OT_INTENT_LOG)
4854 		return (zio);
4855 
4856 	if (!(zp->zp_encrypt || BP_IS_ENCRYPTED(bp))) {
4857 		BP_SET_CRYPT(bp, B_FALSE);
4858 		return (zio);
4859 	}
4860 
4861 	/* if we are doing raw encryption set the provided encryption params */
4862 	if (zio->io_flags & ZIO_FLAG_RAW_ENCRYPT) {
4863 		ASSERT0(BP_GET_LEVEL(bp));
4864 		BP_SET_CRYPT(bp, B_TRUE);
4865 		BP_SET_BYTEORDER(bp, zp->zp_byteorder);
4866 		if (ot != DMU_OT_OBJSET)
4867 			zio_crypt_encode_mac_bp(bp, zp->zp_mac);
4868 
4869 		/* dnode blocks must be written out in the provided byteorder */
4870 		if (zp->zp_byteorder != ZFS_HOST_BYTEORDER &&
4871 		    ot == DMU_OT_DNODE) {
4872 			void *bswap_buf = zio_buf_alloc(psize);
4873 			abd_t *babd = abd_get_from_buf(bswap_buf, psize);
4874 
4875 			ASSERT3U(BP_GET_COMPRESS(bp), ==, ZIO_COMPRESS_OFF);
4876 			abd_copy_to_buf(bswap_buf, zio->io_abd, psize);
4877 			dmu_ot_byteswap[DMU_OT_BYTESWAP(ot)].ob_func(bswap_buf,
4878 			    psize);
4879 
4880 			abd_take_ownership_of_buf(babd, B_TRUE);
4881 			zio_push_transform(zio, babd, psize, psize, NULL);
4882 		}
4883 
4884 		if (DMU_OT_IS_ENCRYPTED(ot))
4885 			zio_crypt_encode_params_bp(bp, zp->zp_salt, zp->zp_iv);
4886 		return (zio);
4887 	}
4888 
4889 	/* indirect blocks only maintain a cksum of the lower level MACs */
4890 	if (BP_GET_LEVEL(bp) > 0) {
4891 		BP_SET_CRYPT(bp, B_TRUE);
4892 		VERIFY0(zio_crypt_do_indirect_mac_checksum_abd(B_TRUE,
4893 		    zio->io_orig_abd, BP_GET_LSIZE(bp), BP_SHOULD_BYTESWAP(bp),
4894 		    mac));
4895 		zio_crypt_encode_mac_bp(bp, mac);
4896 		return (zio);
4897 	}
4898 
4899 	/*
4900 	 * Objset blocks are a special case since they have 2 256-bit MACs
4901 	 * embedded within them.
4902 	 */
4903 	if (ot == DMU_OT_OBJSET) {
4904 		ASSERT0(DMU_OT_IS_ENCRYPTED(ot));
4905 		ASSERT3U(BP_GET_COMPRESS(bp), ==, ZIO_COMPRESS_OFF);
4906 		BP_SET_CRYPT(bp, B_TRUE);
4907 		VERIFY0(spa_do_crypt_objset_mac_abd(B_TRUE, spa, dsobj,
4908 		    zio->io_abd, psize, BP_SHOULD_BYTESWAP(bp)));
4909 		return (zio);
4910 	}
4911 
4912 	/* unencrypted object types are only authenticated with a MAC */
4913 	if (!DMU_OT_IS_ENCRYPTED(ot)) {
4914 		BP_SET_CRYPT(bp, B_TRUE);
4915 		VERIFY0(spa_do_crypt_mac_abd(B_TRUE, spa, dsobj,
4916 		    zio->io_abd, psize, mac));
4917 		zio_crypt_encode_mac_bp(bp, mac);
4918 		return (zio);
4919 	}
4920 
4921 	/*
4922 	 * Later passes of sync-to-convergence may decide to rewrite data
4923 	 * in place to avoid more disk reallocations. This presents a problem
4924 	 * for encryption because this constitutes rewriting the new data with
4925 	 * the same encryption key and IV. However, this only applies to blocks
4926 	 * in the MOS (particularly the spacemaps) and we do not encrypt the
4927 	 * MOS. We assert that the zio is allocating or an intent log write
4928 	 * to enforce this.
4929 	 */
4930 	ASSERT(IO_IS_ALLOCATING(zio) || ot == DMU_OT_INTENT_LOG);
4931 	ASSERT(BP_GET_LEVEL(bp) == 0 || ot == DMU_OT_INTENT_LOG);
4932 	ASSERT(spa_feature_is_active(spa, SPA_FEATURE_ENCRYPTION));
4933 	ASSERT3U(psize, !=, 0);
4934 
4935 	enc_buf = zio_buf_alloc(psize);
4936 	eabd = abd_get_from_buf(enc_buf, psize);
4937 	abd_take_ownership_of_buf(eabd, B_TRUE);
4938 
4939 	/*
4940 	 * For an explanation of what encryption parameters are stored
4941 	 * where, see the block comment in zio_crypt.c.
4942 	 */
4943 	if (ot == DMU_OT_INTENT_LOG) {
4944 		zio_crypt_decode_params_bp(bp, salt, iv);
4945 	} else {
4946 		BP_SET_CRYPT(bp, B_TRUE);
4947 	}
4948 
4949 	/* Perform the encryption. This should not fail */
4950 	VERIFY0(spa_do_crypt_abd(B_TRUE, spa, &zio->io_bookmark,
4951 	    BP_GET_TYPE(bp), BP_GET_DEDUP(bp), BP_SHOULD_BYTESWAP(bp),
4952 	    salt, iv, mac, psize, zio->io_abd, eabd, &no_crypt));
4953 
4954 	/* encode encryption metadata into the bp */
4955 	if (ot == DMU_OT_INTENT_LOG) {
4956 		/*
4957 		 * ZIL blocks store the MAC in the embedded checksum, so the
4958 		 * transform must always be applied.
4959 		 */
4960 		zio_crypt_encode_mac_zil(enc_buf, mac);
4961 		zio_push_transform(zio, eabd, psize, psize, NULL);
4962 	} else {
4963 		BP_SET_CRYPT(bp, B_TRUE);
4964 		zio_crypt_encode_params_bp(bp, salt, iv);
4965 		zio_crypt_encode_mac_bp(bp, mac);
4966 
4967 		if (no_crypt) {
4968 			ASSERT3U(ot, ==, DMU_OT_DNODE);
4969 			abd_free(eabd);
4970 		} else {
4971 			zio_push_transform(zio, eabd, psize, psize, NULL);
4972 		}
4973 	}
4974 
4975 	return (zio);
4976 }
4977 
4978 /*
4979  * ==========================================================================
4980  * Generate and verify checksums
4981  * ==========================================================================
4982  */
4983 static zio_t *
zio_checksum_generate(zio_t * zio)4984 zio_checksum_generate(zio_t *zio)
4985 {
4986 	blkptr_t *bp = zio->io_bp;
4987 	enum zio_checksum checksum;
4988 
4989 	if (bp == NULL) {
4990 		/*
4991 		 * This is zio_write_phys().
4992 		 * We're either generating a label checksum, or none at all.
4993 		 */
4994 		checksum = zio->io_prop.zp_checksum;
4995 
4996 		if (checksum == ZIO_CHECKSUM_OFF)
4997 			return (zio);
4998 
4999 		ASSERT(checksum == ZIO_CHECKSUM_LABEL);
5000 	} else {
5001 		if (BP_IS_GANG(bp) && zio->io_child_type == ZIO_CHILD_GANG) {
5002 			ASSERT(!IO_IS_ALLOCATING(zio));
5003 			checksum = ZIO_CHECKSUM_GANG_HEADER;
5004 		} else {
5005 			checksum = BP_GET_CHECKSUM(bp);
5006 		}
5007 	}
5008 
5009 	zio_checksum_compute(zio, checksum, zio->io_abd, zio->io_size);
5010 
5011 	return (zio);
5012 }
5013 
5014 static zio_t *
zio_checksum_verify(zio_t * zio)5015 zio_checksum_verify(zio_t *zio)
5016 {
5017 	zio_bad_cksum_t info;
5018 	blkptr_t *bp = zio->io_bp;
5019 	int error;
5020 
5021 	ASSERT(zio->io_vd != NULL);
5022 
5023 	if (bp == NULL) {
5024 		/*
5025 		 * This is zio_read_phys().
5026 		 * We're either verifying a label checksum, or nothing at all.
5027 		 */
5028 		if (zio->io_prop.zp_checksum == ZIO_CHECKSUM_OFF)
5029 			return (zio);
5030 
5031 		ASSERT3U(zio->io_prop.zp_checksum, ==, ZIO_CHECKSUM_LABEL);
5032 	}
5033 
5034 	ASSERT0(zio->io_flags & ZIO_FLAG_DIO_CHKSUM_ERR);
5035 	IMPLY(zio->io_flags & ZIO_FLAG_DIO_READ,
5036 	    !(zio->io_flags & ZIO_FLAG_SPECULATIVE));
5037 
5038 	if ((error = zio_checksum_error(zio, &info)) != 0) {
5039 		zio->io_error = error;
5040 		if (error == ECKSUM &&
5041 		    !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
5042 			if (zio->io_flags & ZIO_FLAG_DIO_READ) {
5043 				zio->io_flags |= ZIO_FLAG_DIO_CHKSUM_ERR;
5044 				zio_t *pio = zio_unique_parent(zio);
5045 				/*
5046 				 * Any Direct I/O read that has a checksum
5047 				 * error must be treated as suspicous as the
5048 				 * contents of the buffer could be getting
5049 				 * manipulated while the I/O is taking place.
5050 				 *
5051 				 * The checksum verify error will only be
5052 				 * reported here for disk and file VDEV's and
5053 				 * will be reported on those that the failure
5054 				 * occurred on. Other types of VDEV's report the
5055 				 * verify failure in their own code paths.
5056 				 */
5057 				if (pio->io_child_type == ZIO_CHILD_LOGICAL) {
5058 					zio_dio_chksum_verify_error_report(zio);
5059 				}
5060 			} else {
5061 				mutex_enter(&zio->io_vd->vdev_stat_lock);
5062 				zio->io_vd->vdev_stat.vs_checksum_errors++;
5063 				mutex_exit(&zio->io_vd->vdev_stat_lock);
5064 				(void) zfs_ereport_start_checksum(zio->io_spa,
5065 				    zio->io_vd, &zio->io_bookmark, zio,
5066 				    zio->io_offset, zio->io_size, &info);
5067 			}
5068 		}
5069 	}
5070 
5071 	return (zio);
5072 }
5073 
5074 static zio_t *
zio_dio_checksum_verify(zio_t * zio)5075 zio_dio_checksum_verify(zio_t *zio)
5076 {
5077 	zio_t *pio = zio_unique_parent(zio);
5078 	int error;
5079 
5080 	ASSERT3P(zio->io_vd, !=, NULL);
5081 	ASSERT3P(zio->io_bp, !=, NULL);
5082 	ASSERT3U(zio->io_child_type, ==, ZIO_CHILD_VDEV);
5083 	ASSERT3U(zio->io_type, ==, ZIO_TYPE_WRITE);
5084 	ASSERT3B(pio->io_prop.zp_direct_write, ==, B_TRUE);
5085 	ASSERT3U(pio->io_child_type, ==, ZIO_CHILD_LOGICAL);
5086 
5087 	if (zfs_vdev_direct_write_verify == 0 || zio->io_error != 0)
5088 		goto out;
5089 
5090 	if ((error = zio_checksum_error(zio, NULL)) != 0) {
5091 		zio->io_error = error;
5092 		if (error == ECKSUM) {
5093 			zio->io_flags |= ZIO_FLAG_DIO_CHKSUM_ERR;
5094 			zio_dio_chksum_verify_error_report(zio);
5095 		}
5096 	}
5097 
5098 out:
5099 	return (zio);
5100 }
5101 
5102 
5103 /*
5104  * Called by RAID-Z to ensure we don't compute the checksum twice.
5105  */
5106 void
zio_checksum_verified(zio_t * zio)5107 zio_checksum_verified(zio_t *zio)
5108 {
5109 	zio->io_pipeline &= ~ZIO_STAGE_CHECKSUM_VERIFY;
5110 }
5111 
5112 /*
5113  * Report Direct I/O checksum verify error and create ZED event.
5114  */
5115 void
zio_dio_chksum_verify_error_report(zio_t * zio)5116 zio_dio_chksum_verify_error_report(zio_t *zio)
5117 {
5118 	ASSERT(zio->io_flags & ZIO_FLAG_DIO_CHKSUM_ERR);
5119 
5120 	if (zio->io_child_type == ZIO_CHILD_LOGICAL)
5121 		return;
5122 
5123 	mutex_enter(&zio->io_vd->vdev_stat_lock);
5124 	zio->io_vd->vdev_stat.vs_dio_verify_errors++;
5125 	mutex_exit(&zio->io_vd->vdev_stat_lock);
5126 	if (zio->io_type == ZIO_TYPE_WRITE) {
5127 		/*
5128 		 * Convert checksum error for writes into EIO.
5129 		 */
5130 		zio->io_error = SET_ERROR(EIO);
5131 		/*
5132 		 * Report dio_verify_wr ZED event.
5133 		 */
5134 		(void) zfs_ereport_post(FM_EREPORT_ZFS_DIO_VERIFY_WR,
5135 		    zio->io_spa,  zio->io_vd, &zio->io_bookmark, zio, 0);
5136 	} else {
5137 		/*
5138 		 * Report dio_verify_rd ZED event.
5139 		 */
5140 		(void) zfs_ereport_post(FM_EREPORT_ZFS_DIO_VERIFY_RD,
5141 		    zio->io_spa, zio->io_vd, &zio->io_bookmark, zio, 0);
5142 	}
5143 }
5144 
5145 /*
5146  * ==========================================================================
5147  * Error rank.  Error are ranked in the order 0, ENXIO, ECKSUM, EIO, other.
5148  * An error of 0 indicates success.  ENXIO indicates whole-device failure,
5149  * which may be transient (e.g. unplugged) or permanent.  ECKSUM and EIO
5150  * indicate errors that are specific to one I/O, and most likely permanent.
5151  * Any other error is presumed to be worse because we weren't expecting it.
5152  * ==========================================================================
5153  */
5154 int
zio_worst_error(int e1,int e2)5155 zio_worst_error(int e1, int e2)
5156 {
5157 	static int zio_error_rank[] = { 0, ENXIO, ECKSUM, EIO };
5158 	int r1, r2;
5159 
5160 	for (r1 = 0; r1 < sizeof (zio_error_rank) / sizeof (int); r1++)
5161 		if (e1 == zio_error_rank[r1])
5162 			break;
5163 
5164 	for (r2 = 0; r2 < sizeof (zio_error_rank) / sizeof (int); r2++)
5165 		if (e2 == zio_error_rank[r2])
5166 			break;
5167 
5168 	return (r1 > r2 ? e1 : e2);
5169 }
5170 
5171 /*
5172  * ==========================================================================
5173  * I/O completion
5174  * ==========================================================================
5175  */
5176 static zio_t *
zio_ready(zio_t * zio)5177 zio_ready(zio_t *zio)
5178 {
5179 	blkptr_t *bp = zio->io_bp;
5180 	zio_t *pio, *pio_next;
5181 	zio_link_t *zl = NULL;
5182 
5183 	if (zio_wait_for_children(zio, ZIO_CHILD_LOGICAL_BIT |
5184 	    ZIO_CHILD_GANG_BIT | ZIO_CHILD_DDT_BIT, ZIO_WAIT_READY)) {
5185 		return (NULL);
5186 	}
5187 
5188 	if (zio->io_ready) {
5189 		ASSERT(IO_IS_ALLOCATING(zio));
5190 		ASSERT(BP_GET_LOGICAL_BIRTH(bp) == zio->io_txg ||
5191 		    BP_IS_HOLE(bp) || (zio->io_flags & ZIO_FLAG_NOPWRITE));
5192 		ASSERT(zio->io_children[ZIO_CHILD_GANG][ZIO_WAIT_READY] == 0);
5193 
5194 		zio->io_ready(zio);
5195 	}
5196 
5197 #ifdef ZFS_DEBUG
5198 	if (bp != NULL && bp != &zio->io_bp_copy)
5199 		zio->io_bp_copy = *bp;
5200 #endif
5201 
5202 	if (zio->io_error != 0) {
5203 		zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
5204 
5205 		if (zio->io_flags & ZIO_FLAG_IO_ALLOCATING) {
5206 			ASSERT(IO_IS_ALLOCATING(zio));
5207 			ASSERT(zio->io_priority == ZIO_PRIORITY_ASYNC_WRITE);
5208 			ASSERT(zio->io_metaslab_class != NULL);
5209 			ASSERT(ZIO_HAS_ALLOCATOR(zio));
5210 
5211 			/*
5212 			 * We were unable to allocate anything, unreserve and
5213 			 * issue the next I/O to allocate.
5214 			 */
5215 			if (metaslab_class_throttle_unreserve(
5216 			    zio->io_metaslab_class, zio->io_prop.zp_copies,
5217 			    zio)) {
5218 				zio_allocate_dispatch(zio->io_metaslab_class,
5219 				    zio->io_allocator);
5220 			}
5221 		}
5222 	}
5223 
5224 	mutex_enter(&zio->io_lock);
5225 	zio->io_state[ZIO_WAIT_READY] = 1;
5226 	pio = zio_walk_parents(zio, &zl);
5227 	mutex_exit(&zio->io_lock);
5228 
5229 	/*
5230 	 * As we notify zio's parents, new parents could be added.
5231 	 * New parents go to the head of zio's io_parent_list, however,
5232 	 * so we will (correctly) not notify them.  The remainder of zio's
5233 	 * io_parent_list, from 'pio_next' onward, cannot change because
5234 	 * all parents must wait for us to be done before they can be done.
5235 	 */
5236 	for (; pio != NULL; pio = pio_next) {
5237 		pio_next = zio_walk_parents(zio, &zl);
5238 		zio_notify_parent(pio, zio, ZIO_WAIT_READY, NULL);
5239 	}
5240 
5241 	if (zio->io_flags & ZIO_FLAG_NODATA) {
5242 		if (bp != NULL && BP_IS_GANG(bp)) {
5243 			zio->io_flags &= ~ZIO_FLAG_NODATA;
5244 		} else {
5245 			ASSERT((uintptr_t)zio->io_abd < SPA_MAXBLOCKSIZE);
5246 			zio->io_pipeline &= ~ZIO_VDEV_IO_STAGES;
5247 		}
5248 	}
5249 
5250 	if (zio_injection_enabled &&
5251 	    zio->io_spa->spa_syncing_txg == zio->io_txg)
5252 		zio_handle_ignored_writes(zio);
5253 
5254 	return (zio);
5255 }
5256 
5257 /*
5258  * Update the allocation throttle accounting.
5259  */
5260 static void
zio_dva_throttle_done(zio_t * zio)5261 zio_dva_throttle_done(zio_t *zio)
5262 {
5263 	zio_t *pio = zio_unique_parent(zio);
5264 	vdev_t *vd = zio->io_vd;
5265 	int flags = METASLAB_ASYNC_ALLOC;
5266 	const void *tag = pio;
5267 
5268 	ASSERT3P(zio->io_bp, !=, NULL);
5269 	ASSERT3U(zio->io_type, ==, ZIO_TYPE_WRITE);
5270 	ASSERT3U(zio->io_priority, ==, ZIO_PRIORITY_ASYNC_WRITE);
5271 	ASSERT3U(zio->io_child_type, ==, ZIO_CHILD_VDEV);
5272 	ASSERT(vd != NULL);
5273 	ASSERT3P(vd, ==, vd->vdev_top);
5274 	ASSERT(zio_injection_enabled || !(zio->io_flags & ZIO_FLAG_IO_RETRY));
5275 	ASSERT(!(zio->io_flags & ZIO_FLAG_IO_REPAIR));
5276 	ASSERT(zio->io_flags & ZIO_FLAG_IO_ALLOCATING);
5277 
5278 	/*
5279 	 * Parents of gang children can have two flavors -- ones that allocated
5280 	 * the gang header (will have ZIO_FLAG_IO_REWRITE set) and ones that
5281 	 * allocated the constituent blocks.  The first use their parent as tag.
5282 	 */
5283 	if (pio->io_child_type == ZIO_CHILD_GANG &&
5284 	    (pio->io_flags & ZIO_FLAG_IO_REWRITE))
5285 		tag = zio_unique_parent(pio);
5286 
5287 	ASSERT(IO_IS_ALLOCATING(pio) || (pio->io_child_type == ZIO_CHILD_GANG &&
5288 	    (pio->io_flags & ZIO_FLAG_IO_REWRITE)));
5289 	ASSERT(ZIO_HAS_ALLOCATOR(pio));
5290 	ASSERT3P(zio, !=, zio->io_logical);
5291 	ASSERT(zio->io_logical != NULL);
5292 	ASSERT(!(zio->io_flags & ZIO_FLAG_IO_REPAIR));
5293 	ASSERT0(zio->io_flags & ZIO_FLAG_NOPWRITE);
5294 	ASSERT(zio->io_metaslab_class != NULL);
5295 	ASSERT(zio->io_metaslab_class->mc_alloc_throttle_enabled);
5296 
5297 	metaslab_group_alloc_decrement(zio->io_spa, vd->vdev_id,
5298 	    pio->io_allocator, flags, pio->io_size, tag);
5299 
5300 	if (metaslab_class_throttle_unreserve(zio->io_metaslab_class, 1, pio)) {
5301 		zio_allocate_dispatch(zio->io_metaslab_class,
5302 		    pio->io_allocator);
5303 	}
5304 }
5305 
5306 static zio_t *
zio_done(zio_t * zio)5307 zio_done(zio_t *zio)
5308 {
5309 	/*
5310 	 * Always attempt to keep stack usage minimal here since
5311 	 * we can be called recursively up to 19 levels deep.
5312 	 */
5313 	const uint64_t psize = zio->io_size;
5314 	zio_t *pio, *pio_next;
5315 	zio_link_t *zl = NULL;
5316 
5317 	/*
5318 	 * If our children haven't all completed,
5319 	 * wait for them and then repeat this pipeline stage.
5320 	 */
5321 	if (zio_wait_for_children(zio, ZIO_CHILD_ALL_BITS, ZIO_WAIT_DONE)) {
5322 		return (NULL);
5323 	}
5324 
5325 	/*
5326 	 * If the allocation throttle is enabled, then update the accounting.
5327 	 * We only track child I/Os that are part of an allocating async
5328 	 * write. We must do this since the allocation is performed
5329 	 * by the logical I/O but the actual write is done by child I/Os.
5330 	 */
5331 	if (zio->io_flags & ZIO_FLAG_IO_ALLOCATING &&
5332 	    zio->io_child_type == ZIO_CHILD_VDEV)
5333 		zio_dva_throttle_done(zio);
5334 
5335 	for (int c = 0; c < ZIO_CHILD_TYPES; c++)
5336 		for (int w = 0; w < ZIO_WAIT_TYPES; w++)
5337 			ASSERT(zio->io_children[c][w] == 0);
5338 
5339 	if (zio->io_bp != NULL && !BP_IS_EMBEDDED(zio->io_bp)) {
5340 		ASSERT(zio->io_bp->blk_pad[0] == 0);
5341 		ASSERT(zio->io_bp->blk_pad[1] == 0);
5342 		ASSERT(memcmp(zio->io_bp, &zio->io_bp_copy,
5343 		    sizeof (blkptr_t)) == 0 ||
5344 		    (zio->io_bp == zio_unique_parent(zio)->io_bp));
5345 		if (zio->io_type == ZIO_TYPE_WRITE && !BP_IS_HOLE(zio->io_bp) &&
5346 		    zio->io_bp_override == NULL &&
5347 		    !(zio->io_flags & ZIO_FLAG_IO_REPAIR)) {
5348 			ASSERT3U(zio->io_prop.zp_copies, <=,
5349 			    BP_GET_NDVAS(zio->io_bp));
5350 			ASSERT(BP_COUNT_GANG(zio->io_bp) == 0 ||
5351 			    (BP_COUNT_GANG(zio->io_bp) ==
5352 			    BP_GET_NDVAS(zio->io_bp)));
5353 		}
5354 		if (zio->io_flags & ZIO_FLAG_NOPWRITE)
5355 			VERIFY(BP_EQUAL(zio->io_bp, &zio->io_bp_orig));
5356 	}
5357 
5358 	/*
5359 	 * If there were child vdev/gang/ddt errors, they apply to us now.
5360 	 */
5361 	zio_inherit_child_errors(zio, ZIO_CHILD_VDEV);
5362 	zio_inherit_child_errors(zio, ZIO_CHILD_GANG);
5363 	zio_inherit_child_errors(zio, ZIO_CHILD_DDT);
5364 
5365 	/*
5366 	 * If the I/O on the transformed data was successful, generate any
5367 	 * checksum reports now while we still have the transformed data.
5368 	 */
5369 	if (zio->io_error == 0) {
5370 		while (zio->io_cksum_report != NULL) {
5371 			zio_cksum_report_t *zcr = zio->io_cksum_report;
5372 			uint64_t align = zcr->zcr_align;
5373 			uint64_t asize = P2ROUNDUP(psize, align);
5374 			abd_t *adata = zio->io_abd;
5375 
5376 			if (adata != NULL && asize != psize) {
5377 				adata = abd_alloc(asize, B_TRUE);
5378 				abd_copy(adata, zio->io_abd, psize);
5379 				abd_zero_off(adata, psize, asize - psize);
5380 			}
5381 
5382 			zio->io_cksum_report = zcr->zcr_next;
5383 			zcr->zcr_next = NULL;
5384 			zcr->zcr_finish(zcr, adata);
5385 			zfs_ereport_free_checksum(zcr);
5386 
5387 			if (adata != NULL && asize != psize)
5388 				abd_free(adata);
5389 		}
5390 	}
5391 
5392 	zio_pop_transforms(zio);	/* note: may set zio->io_error */
5393 
5394 	vdev_stat_update(zio, psize);
5395 
5396 	/*
5397 	 * If this I/O is attached to a particular vdev is slow, exceeding
5398 	 * 30 seconds to complete, post an error described the I/O delay.
5399 	 * We ignore these errors if the device is currently unavailable.
5400 	 */
5401 	if (zio->io_delay >= MSEC2NSEC(zio_slow_io_ms)) {
5402 		if (zio->io_vd != NULL && !vdev_is_dead(zio->io_vd)) {
5403 			/*
5404 			 * We want to only increment our slow IO counters if
5405 			 * the IO is valid (i.e. not if the drive is removed).
5406 			 *
5407 			 * zfs_ereport_post() will also do these checks, but
5408 			 * it can also ratelimit and have other failures, so we
5409 			 * need to increment the slow_io counters independent
5410 			 * of it.
5411 			 */
5412 			if (zfs_ereport_is_valid(FM_EREPORT_ZFS_DELAY,
5413 			    zio->io_spa, zio->io_vd, zio)) {
5414 				mutex_enter(&zio->io_vd->vdev_stat_lock);
5415 				zio->io_vd->vdev_stat.vs_slow_ios++;
5416 				mutex_exit(&zio->io_vd->vdev_stat_lock);
5417 
5418 				(void) zfs_ereport_post(FM_EREPORT_ZFS_DELAY,
5419 				    zio->io_spa, zio->io_vd, &zio->io_bookmark,
5420 				    zio, 0);
5421 			}
5422 		}
5423 	}
5424 
5425 	if (zio->io_error) {
5426 		/*
5427 		 * If this I/O is attached to a particular vdev,
5428 		 * generate an error message describing the I/O failure
5429 		 * at the block level.  We ignore these errors if the
5430 		 * device is currently unavailable.
5431 		 */
5432 		if (zio->io_error != ECKSUM && zio->io_vd != NULL &&
5433 		    !vdev_is_dead(zio->io_vd) &&
5434 		    !(zio->io_flags & ZIO_FLAG_DIO_CHKSUM_ERR)) {
5435 			int ret = zfs_ereport_post(FM_EREPORT_ZFS_IO,
5436 			    zio->io_spa, zio->io_vd, &zio->io_bookmark, zio, 0);
5437 			if (ret != EALREADY) {
5438 				mutex_enter(&zio->io_vd->vdev_stat_lock);
5439 				if (zio->io_type == ZIO_TYPE_READ)
5440 					zio->io_vd->vdev_stat.vs_read_errors++;
5441 				else if (zio->io_type == ZIO_TYPE_WRITE)
5442 					zio->io_vd->vdev_stat.vs_write_errors++;
5443 				mutex_exit(&zio->io_vd->vdev_stat_lock);
5444 			}
5445 		}
5446 
5447 		if ((zio->io_error == EIO || !(zio->io_flags &
5448 		    (ZIO_FLAG_SPECULATIVE | ZIO_FLAG_DONT_PROPAGATE))) &&
5449 		    !(zio->io_flags & ZIO_FLAG_DIO_CHKSUM_ERR) &&
5450 		    zio == zio->io_logical) {
5451 			/*
5452 			 * For logical I/O requests, tell the SPA to log the
5453 			 * error and generate a logical data ereport.
5454 			 */
5455 			spa_log_error(zio->io_spa, &zio->io_bookmark,
5456 			    BP_GET_LOGICAL_BIRTH(zio->io_bp));
5457 			(void) zfs_ereport_post(FM_EREPORT_ZFS_DATA,
5458 			    zio->io_spa, NULL, &zio->io_bookmark, zio, 0);
5459 		}
5460 	}
5461 
5462 	if (zio->io_error && zio == zio->io_logical) {
5463 
5464 		/*
5465 		 * A DDT child tried to create a mixed gang/non-gang BP. We're
5466 		 * going to have to just retry as a non-dedup IO.
5467 		 */
5468 		if (zio->io_error == EAGAIN && IO_IS_ALLOCATING(zio) &&
5469 		    zio->io_prop.zp_dedup) {
5470 			zio->io_reexecute |= ZIO_REEXECUTE_NOW;
5471 			zio->io_prop.zp_dedup = B_FALSE;
5472 		}
5473 		/*
5474 		 * Determine whether zio should be reexecuted.  This will
5475 		 * propagate all the way to the root via zio_notify_parent().
5476 		 */
5477 		ASSERT(zio->io_vd == NULL && zio->io_bp != NULL);
5478 		ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
5479 
5480 		if (IO_IS_ALLOCATING(zio) &&
5481 		    !(zio->io_flags & ZIO_FLAG_CANFAIL) &&
5482 		    !(zio->io_flags & ZIO_FLAG_DIO_CHKSUM_ERR)) {
5483 			if (zio->io_error != ENOSPC)
5484 				zio->io_reexecute |= ZIO_REEXECUTE_NOW;
5485 			else
5486 				zio->io_reexecute |= ZIO_REEXECUTE_SUSPEND;
5487 		}
5488 
5489 		if ((zio->io_type == ZIO_TYPE_READ ||
5490 		    zio->io_type == ZIO_TYPE_FREE) &&
5491 		    !(zio->io_flags & ZIO_FLAG_SCAN_THREAD) &&
5492 		    zio->io_error == ENXIO &&
5493 		    spa_load_state(zio->io_spa) == SPA_LOAD_NONE &&
5494 		    spa_get_failmode(zio->io_spa) != ZIO_FAILURE_MODE_CONTINUE)
5495 			zio->io_reexecute |= ZIO_REEXECUTE_SUSPEND;
5496 
5497 		if (!(zio->io_flags & ZIO_FLAG_CANFAIL) && !zio->io_reexecute)
5498 			zio->io_reexecute |= ZIO_REEXECUTE_SUSPEND;
5499 
5500 		/*
5501 		 * Here is a possibly good place to attempt to do
5502 		 * either combinatorial reconstruction or error correction
5503 		 * based on checksums.  It also might be a good place
5504 		 * to send out preliminary ereports before we suspend
5505 		 * processing.
5506 		 */
5507 	}
5508 
5509 	/*
5510 	 * If there were logical child errors, they apply to us now.
5511 	 * We defer this until now to avoid conflating logical child
5512 	 * errors with errors that happened to the zio itself when
5513 	 * updating vdev stats and reporting FMA events above.
5514 	 */
5515 	zio_inherit_child_errors(zio, ZIO_CHILD_LOGICAL);
5516 
5517 	if ((zio->io_error || zio->io_reexecute) &&
5518 	    IO_IS_ALLOCATING(zio) && zio->io_gang_leader == zio &&
5519 	    !(zio->io_flags & (ZIO_FLAG_IO_REWRITE | ZIO_FLAG_NOPWRITE)))
5520 		zio_dva_unallocate(zio, zio->io_gang_tree, zio->io_bp);
5521 
5522 	zio_gang_tree_free(&zio->io_gang_tree);
5523 
5524 	/*
5525 	 * Godfather I/Os should never suspend.
5526 	 */
5527 	if ((zio->io_flags & ZIO_FLAG_GODFATHER) &&
5528 	    (zio->io_reexecute & ZIO_REEXECUTE_SUSPEND))
5529 		zio->io_reexecute &= ~ZIO_REEXECUTE_SUSPEND;
5530 
5531 	if (zio->io_reexecute) {
5532 		/*
5533 		 * A Direct I/O operation that has a checksum verify error
5534 		 * should not attempt to reexecute. Instead, the error should
5535 		 * just be propagated back.
5536 		 */
5537 		ASSERT(!(zio->io_flags & ZIO_FLAG_DIO_CHKSUM_ERR));
5538 
5539 		/*
5540 		 * This is a logical I/O that wants to reexecute.
5541 		 *
5542 		 * Reexecute is top-down.  When an i/o fails, if it's not
5543 		 * the root, it simply notifies its parent and sticks around.
5544 		 * The parent, seeing that it still has children in zio_done(),
5545 		 * does the same.  This percolates all the way up to the root.
5546 		 * The root i/o will reexecute or suspend the entire tree.
5547 		 *
5548 		 * This approach ensures that zio_reexecute() honors
5549 		 * all the original i/o dependency relationships, e.g.
5550 		 * parents not executing until children are ready.
5551 		 */
5552 		ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
5553 
5554 		zio->io_gang_leader = NULL;
5555 
5556 		mutex_enter(&zio->io_lock);
5557 		zio->io_state[ZIO_WAIT_DONE] = 1;
5558 		mutex_exit(&zio->io_lock);
5559 
5560 		/*
5561 		 * "The Godfather" I/O monitors its children but is
5562 		 * not a true parent to them. It will track them through
5563 		 * the pipeline but severs its ties whenever they get into
5564 		 * trouble (e.g. suspended). This allows "The Godfather"
5565 		 * I/O to return status without blocking.
5566 		 */
5567 		zl = NULL;
5568 		for (pio = zio_walk_parents(zio, &zl); pio != NULL;
5569 		    pio = pio_next) {
5570 			zio_link_t *remove_zl = zl;
5571 			pio_next = zio_walk_parents(zio, &zl);
5572 
5573 			if ((pio->io_flags & ZIO_FLAG_GODFATHER) &&
5574 			    (zio->io_reexecute & ZIO_REEXECUTE_SUSPEND)) {
5575 				zio_remove_child(pio, zio, remove_zl);
5576 				/*
5577 				 * This is a rare code path, so we don't
5578 				 * bother with "next_to_execute".
5579 				 */
5580 				zio_notify_parent(pio, zio, ZIO_WAIT_DONE,
5581 				    NULL);
5582 			}
5583 		}
5584 
5585 		if ((pio = zio_unique_parent(zio)) != NULL) {
5586 			/*
5587 			 * We're not a root i/o, so there's nothing to do
5588 			 * but notify our parent.  Don't propagate errors
5589 			 * upward since we haven't permanently failed yet.
5590 			 */
5591 			ASSERT(!(zio->io_flags & ZIO_FLAG_GODFATHER));
5592 			zio->io_flags |= ZIO_FLAG_DONT_PROPAGATE;
5593 			/*
5594 			 * This is a rare code path, so we don't bother with
5595 			 * "next_to_execute".
5596 			 */
5597 			zio_notify_parent(pio, zio, ZIO_WAIT_DONE, NULL);
5598 		} else if (zio->io_reexecute & ZIO_REEXECUTE_SUSPEND) {
5599 			/*
5600 			 * We'd fail again if we reexecuted now, so suspend
5601 			 * until conditions improve (e.g. device comes online).
5602 			 */
5603 			zio_suspend(zio->io_spa, zio, ZIO_SUSPEND_IOERR);
5604 		} else {
5605 			/*
5606 			 * Reexecution is potentially a huge amount of work.
5607 			 * Hand it off to the otherwise-unused claim taskq.
5608 			 */
5609 			spa_taskq_dispatch(zio->io_spa,
5610 			    ZIO_TYPE_CLAIM, ZIO_TASKQ_ISSUE,
5611 			    zio_reexecute, zio, B_FALSE);
5612 		}
5613 		return (NULL);
5614 	}
5615 
5616 	ASSERT(list_is_empty(&zio->io_child_list));
5617 	ASSERT(zio->io_reexecute == 0);
5618 	ASSERT(zio->io_error == 0 || (zio->io_flags & ZIO_FLAG_CANFAIL));
5619 
5620 	/*
5621 	 * Report any checksum errors, since the I/O is complete.
5622 	 */
5623 	while (zio->io_cksum_report != NULL) {
5624 		zio_cksum_report_t *zcr = zio->io_cksum_report;
5625 		zio->io_cksum_report = zcr->zcr_next;
5626 		zcr->zcr_next = NULL;
5627 		zcr->zcr_finish(zcr, NULL);
5628 		zfs_ereport_free_checksum(zcr);
5629 	}
5630 
5631 	/*
5632 	 * It is the responsibility of the done callback to ensure that this
5633 	 * particular zio is no longer discoverable for adoption, and as
5634 	 * such, cannot acquire any new parents.
5635 	 */
5636 	if (zio->io_done)
5637 		zio->io_done(zio);
5638 
5639 	mutex_enter(&zio->io_lock);
5640 	zio->io_state[ZIO_WAIT_DONE] = 1;
5641 	mutex_exit(&zio->io_lock);
5642 
5643 	/*
5644 	 * We are done executing this zio.  We may want to execute a parent
5645 	 * next.  See the comment in zio_notify_parent().
5646 	 */
5647 	zio_t *next_to_execute = NULL;
5648 	zl = NULL;
5649 	for (pio = zio_walk_parents(zio, &zl); pio != NULL; pio = pio_next) {
5650 		zio_link_t *remove_zl = zl;
5651 		pio_next = zio_walk_parents(zio, &zl);
5652 		zio_remove_child(pio, zio, remove_zl);
5653 		zio_notify_parent(pio, zio, ZIO_WAIT_DONE, &next_to_execute);
5654 	}
5655 
5656 	if (zio->io_waiter != NULL) {
5657 		mutex_enter(&zio->io_lock);
5658 		zio->io_executor = NULL;
5659 		cv_broadcast(&zio->io_cv);
5660 		mutex_exit(&zio->io_lock);
5661 	} else {
5662 		zio_destroy(zio);
5663 	}
5664 
5665 	return (next_to_execute);
5666 }
5667 
5668 /*
5669  * ==========================================================================
5670  * I/O pipeline definition
5671  * ==========================================================================
5672  */
5673 static zio_pipe_stage_t *zio_pipeline[] = {
5674 	NULL,
5675 	zio_read_bp_init,
5676 	zio_write_bp_init,
5677 	zio_free_bp_init,
5678 	zio_issue_async,
5679 	zio_write_compress,
5680 	zio_encrypt,
5681 	zio_checksum_generate,
5682 	zio_nop_write,
5683 	zio_brt_free,
5684 	zio_ddt_read_start,
5685 	zio_ddt_read_done,
5686 	zio_ddt_write,
5687 	zio_ddt_free,
5688 	zio_gang_assemble,
5689 	zio_gang_issue,
5690 	zio_dva_throttle,
5691 	zio_dva_allocate,
5692 	zio_dva_free,
5693 	zio_dva_claim,
5694 	zio_ready,
5695 	zio_vdev_io_start,
5696 	zio_vdev_io_done,
5697 	zio_vdev_io_assess,
5698 	zio_checksum_verify,
5699 	zio_dio_checksum_verify,
5700 	zio_done
5701 };
5702 
5703 
5704 
5705 
5706 /*
5707  * Compare two zbookmark_phys_t's to see which we would reach first in a
5708  * pre-order traversal of the object tree.
5709  *
5710  * This is simple in every case aside from the meta-dnode object. For all other
5711  * objects, we traverse them in order (object 1 before object 2, and so on).
5712  * However, all of these objects are traversed while traversing object 0, since
5713  * the data it points to is the list of objects.  Thus, we need to convert to a
5714  * canonical representation so we can compare meta-dnode bookmarks to
5715  * non-meta-dnode bookmarks.
5716  *
5717  * We do this by calculating "equivalents" for each field of the zbookmark.
5718  * zbookmarks outside of the meta-dnode use their own object and level, and
5719  * calculate the level 0 equivalent (the first L0 blkid that is contained in the
5720  * blocks this bookmark refers to) by multiplying their blkid by their span
5721  * (the number of L0 blocks contained within one block at their level).
5722  * zbookmarks inside the meta-dnode calculate their object equivalent
5723  * (which is L0equiv * dnodes per data block), use 0 for their L0equiv, and use
5724  * level + 1<<31 (any value larger than a level could ever be) for their level.
5725  * This causes them to always compare before a bookmark in their object
5726  * equivalent, compare appropriately to bookmarks in other objects, and to
5727  * compare appropriately to other bookmarks in the meta-dnode.
5728  */
5729 int
zbookmark_compare(uint16_t dbss1,uint8_t ibs1,uint16_t dbss2,uint8_t ibs2,const zbookmark_phys_t * zb1,const zbookmark_phys_t * zb2)5730 zbookmark_compare(uint16_t dbss1, uint8_t ibs1, uint16_t dbss2, uint8_t ibs2,
5731     const zbookmark_phys_t *zb1, const zbookmark_phys_t *zb2)
5732 {
5733 	/*
5734 	 * These variables represent the "equivalent" values for the zbookmark,
5735 	 * after converting zbookmarks inside the meta dnode to their
5736 	 * normal-object equivalents.
5737 	 */
5738 	uint64_t zb1obj, zb2obj;
5739 	uint64_t zb1L0, zb2L0;
5740 	uint64_t zb1level, zb2level;
5741 
5742 	if (zb1->zb_object == zb2->zb_object &&
5743 	    zb1->zb_level == zb2->zb_level &&
5744 	    zb1->zb_blkid == zb2->zb_blkid)
5745 		return (0);
5746 
5747 	IMPLY(zb1->zb_level > 0, ibs1 >= SPA_MINBLOCKSHIFT);
5748 	IMPLY(zb2->zb_level > 0, ibs2 >= SPA_MINBLOCKSHIFT);
5749 
5750 	/*
5751 	 * BP_SPANB calculates the span in blocks.
5752 	 */
5753 	zb1L0 = (zb1->zb_blkid) * BP_SPANB(ibs1, zb1->zb_level);
5754 	zb2L0 = (zb2->zb_blkid) * BP_SPANB(ibs2, zb2->zb_level);
5755 
5756 	if (zb1->zb_object == DMU_META_DNODE_OBJECT) {
5757 		zb1obj = zb1L0 * (dbss1 << (SPA_MINBLOCKSHIFT - DNODE_SHIFT));
5758 		zb1L0 = 0;
5759 		zb1level = zb1->zb_level + COMPARE_META_LEVEL;
5760 	} else {
5761 		zb1obj = zb1->zb_object;
5762 		zb1level = zb1->zb_level;
5763 	}
5764 
5765 	if (zb2->zb_object == DMU_META_DNODE_OBJECT) {
5766 		zb2obj = zb2L0 * (dbss2 << (SPA_MINBLOCKSHIFT - DNODE_SHIFT));
5767 		zb2L0 = 0;
5768 		zb2level = zb2->zb_level + COMPARE_META_LEVEL;
5769 	} else {
5770 		zb2obj = zb2->zb_object;
5771 		zb2level = zb2->zb_level;
5772 	}
5773 
5774 	/* Now that we have a canonical representation, do the comparison. */
5775 	if (zb1obj != zb2obj)
5776 		return (zb1obj < zb2obj ? -1 : 1);
5777 	else if (zb1L0 != zb2L0)
5778 		return (zb1L0 < zb2L0 ? -1 : 1);
5779 	else if (zb1level != zb2level)
5780 		return (zb1level > zb2level ? -1 : 1);
5781 	/*
5782 	 * This can (theoretically) happen if the bookmarks have the same object
5783 	 * and level, but different blkids, if the block sizes are not the same.
5784 	 * There is presently no way to change the indirect block sizes
5785 	 */
5786 	return (0);
5787 }
5788 
5789 /*
5790  *  This function checks the following: given that last_block is the place that
5791  *  our traversal stopped last time, does that guarantee that we've visited
5792  *  every node under subtree_root?  Therefore, we can't just use the raw output
5793  *  of zbookmark_compare.  We have to pass in a modified version of
5794  *  subtree_root; by incrementing the block id, and then checking whether
5795  *  last_block is before or equal to that, we can tell whether or not having
5796  *  visited last_block implies that all of subtree_root's children have been
5797  *  visited.
5798  */
5799 boolean_t
zbookmark_subtree_completed(const dnode_phys_t * dnp,const zbookmark_phys_t * subtree_root,const zbookmark_phys_t * last_block)5800 zbookmark_subtree_completed(const dnode_phys_t *dnp,
5801     const zbookmark_phys_t *subtree_root, const zbookmark_phys_t *last_block)
5802 {
5803 	zbookmark_phys_t mod_zb = *subtree_root;
5804 	mod_zb.zb_blkid++;
5805 	ASSERT0(last_block->zb_level);
5806 
5807 	/* The objset_phys_t isn't before anything. */
5808 	if (dnp == NULL)
5809 		return (B_FALSE);
5810 
5811 	/*
5812 	 * We pass in 1ULL << (DNODE_BLOCK_SHIFT - SPA_MINBLOCKSHIFT) for the
5813 	 * data block size in sectors, because that variable is only used if
5814 	 * the bookmark refers to a block in the meta-dnode.  Since we don't
5815 	 * know without examining it what object it refers to, and there's no
5816 	 * harm in passing in this value in other cases, we always pass it in.
5817 	 *
5818 	 * We pass in 0 for the indirect block size shift because zb2 must be
5819 	 * level 0.  The indirect block size is only used to calculate the span
5820 	 * of the bookmark, but since the bookmark must be level 0, the span is
5821 	 * always 1, so the math works out.
5822 	 *
5823 	 * If you make changes to how the zbookmark_compare code works, be sure
5824 	 * to make sure that this code still works afterwards.
5825 	 */
5826 	return (zbookmark_compare(dnp->dn_datablkszsec, dnp->dn_indblkshift,
5827 	    1ULL << (DNODE_BLOCK_SHIFT - SPA_MINBLOCKSHIFT), 0, &mod_zb,
5828 	    last_block) <= 0);
5829 }
5830 
5831 /*
5832  * This function is similar to zbookmark_subtree_completed(), but returns true
5833  * if subtree_root is equal or ahead of last_block, i.e. still to be done.
5834  */
5835 boolean_t
zbookmark_subtree_tbd(const dnode_phys_t * dnp,const zbookmark_phys_t * subtree_root,const zbookmark_phys_t * last_block)5836 zbookmark_subtree_tbd(const dnode_phys_t *dnp,
5837     const zbookmark_phys_t *subtree_root, const zbookmark_phys_t *last_block)
5838 {
5839 	ASSERT0(last_block->zb_level);
5840 	if (dnp == NULL)
5841 		return (B_FALSE);
5842 	return (zbookmark_compare(dnp->dn_datablkszsec, dnp->dn_indblkshift,
5843 	    1ULL << (DNODE_BLOCK_SHIFT - SPA_MINBLOCKSHIFT), 0, subtree_root,
5844 	    last_block) >= 0);
5845 }
5846 
5847 EXPORT_SYMBOL(zio_type_name);
5848 EXPORT_SYMBOL(zio_buf_alloc);
5849 EXPORT_SYMBOL(zio_data_buf_alloc);
5850 EXPORT_SYMBOL(zio_buf_free);
5851 EXPORT_SYMBOL(zio_data_buf_free);
5852 
5853 ZFS_MODULE_PARAM(zfs_zio, zio_, slow_io_ms, INT, ZMOD_RW,
5854 	"Max I/O completion time (milliseconds) before marking it as slow");
5855 
5856 ZFS_MODULE_PARAM(zfs_zio, zio_, requeue_io_start_cut_in_line, INT, ZMOD_RW,
5857 	"Prioritize requeued I/O");
5858 
5859 ZFS_MODULE_PARAM(zfs, zfs_, sync_pass_deferred_free,  UINT, ZMOD_RW,
5860 	"Defer frees starting in this pass");
5861 
5862 ZFS_MODULE_PARAM(zfs, zfs_, sync_pass_dont_compress, UINT, ZMOD_RW,
5863 	"Don't compress starting in this pass");
5864 
5865 ZFS_MODULE_PARAM(zfs, zfs_, sync_pass_rewrite, UINT, ZMOD_RW,
5866 	"Rewrite new bps starting in this pass");
5867 
5868 ZFS_MODULE_PARAM(zfs_zio, zio_, dva_throttle_enabled, INT, ZMOD_RW,
5869 	"Throttle block allocations in the ZIO pipeline");
5870 
5871 ZFS_MODULE_PARAM(zfs_zio, zio_, deadman_log_all, INT, ZMOD_RW,
5872 	"Log all slow ZIOs, not just those with vdevs");
5873