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