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