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