]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zio.c
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r305145, and update
[FreeBSD/FreeBSD.git] / sys / cddl / contrib / opensolaris / uts / common / fs / 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, 2017 by Delphix. All rights reserved.
24  * Copyright (c) 2011 Nexenta Systems, Inc. All rights reserved.
25  * Copyright (c) 2014 Integros [integros.com]
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/zio_impl.h>
36 #include <sys/zio_compress.h>
37 #include <sys/zio_checksum.h>
38 #include <sys/dmu_objset.h>
39 #include <sys/arc.h>
40 #include <sys/ddt.h>
41 #include <sys/trim_map.h>
42 #include <sys/blkptr.h>
43 #include <sys/zfeature.h>
44 #include <sys/metaslab_impl.h>
45
46 SYSCTL_DECL(_vfs_zfs);
47 SYSCTL_NODE(_vfs_zfs, OID_AUTO, zio, CTLFLAG_RW, 0, "ZFS ZIO");
48 #if defined(__amd64__)
49 static int zio_use_uma = 1;
50 #else
51 static int zio_use_uma = 0;
52 #endif
53 SYSCTL_INT(_vfs_zfs_zio, OID_AUTO, use_uma, CTLFLAG_RDTUN, &zio_use_uma, 0,
54     "Use uma(9) for ZIO allocations");
55 static int zio_exclude_metadata = 0;
56 SYSCTL_INT(_vfs_zfs_zio, OID_AUTO, exclude_metadata, CTLFLAG_RDTUN, &zio_exclude_metadata, 0,
57     "Exclude metadata buffers from dumps as well");
58
59 zio_trim_stats_t zio_trim_stats = {
60         { "bytes",              KSTAT_DATA_UINT64,
61           "Number of bytes successfully TRIMmed" },
62         { "success",            KSTAT_DATA_UINT64,
63           "Number of successful TRIM requests" },
64         { "unsupported",        KSTAT_DATA_UINT64,
65           "Number of TRIM requests that failed because TRIM is not supported" },
66         { "failed",             KSTAT_DATA_UINT64,
67           "Number of TRIM requests that failed for reasons other than not supported" },
68 };
69
70 static kstat_t *zio_trim_ksp;
71
72 /*
73  * ==========================================================================
74  * I/O type descriptions
75  * ==========================================================================
76  */
77 const char *zio_type_name[ZIO_TYPES] = {
78         "zio_null", "zio_read", "zio_write", "zio_free", "zio_claim",
79         "zio_ioctl"
80 };
81
82 boolean_t zio_dva_throttle_enabled = B_TRUE;
83 SYSCTL_INT(_vfs_zfs_zio, OID_AUTO, dva_throttle_enabled, CTLFLAG_RDTUN,
84     &zio_dva_throttle_enabled, 0, "");
85
86 /*
87  * ==========================================================================
88  * I/O kmem caches
89  * ==========================================================================
90  */
91 kmem_cache_t *zio_cache;
92 kmem_cache_t *zio_link_cache;
93 kmem_cache_t *zio_buf_cache[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT];
94 kmem_cache_t *zio_data_buf_cache[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT];
95
96 #ifdef _KERNEL
97 extern vmem_t *zio_alloc_arena;
98 #endif
99
100 #define ZIO_PIPELINE_CONTINUE           0x100
101 #define ZIO_PIPELINE_STOP               0x101
102
103 #define BP_SPANB(indblkshift, level) \
104         (((uint64_t)1) << ((level) * ((indblkshift) - SPA_BLKPTRSHIFT)))
105 #define COMPARE_META_LEVEL      0x80000000ul
106 /*
107  * The following actions directly effect the spa's sync-to-convergence logic.
108  * The values below define the sync pass when we start performing the action.
109  * Care should be taken when changing these values as they directly impact
110  * spa_sync() performance. Tuning these values may introduce subtle performance
111  * pathologies and should only be done in the context of performance analysis.
112  * These tunables will eventually be removed and replaced with #defines once
113  * enough analysis has been done to determine optimal values.
114  *
115  * The 'zfs_sync_pass_deferred_free' pass must be greater than 1 to ensure that
116  * regular blocks are not deferred.
117  */
118 int zfs_sync_pass_deferred_free = 2; /* defer frees starting in this pass */
119 SYSCTL_INT(_vfs_zfs, OID_AUTO, sync_pass_deferred_free, CTLFLAG_RDTUN,
120     &zfs_sync_pass_deferred_free, 0, "defer frees starting in this pass");
121 int zfs_sync_pass_dont_compress = 5; /* don't compress starting in this pass */
122 SYSCTL_INT(_vfs_zfs, OID_AUTO, sync_pass_dont_compress, CTLFLAG_RDTUN,
123     &zfs_sync_pass_dont_compress, 0, "don't compress starting in this pass");
124 int zfs_sync_pass_rewrite = 2; /* rewrite new bps starting in this pass */
125 SYSCTL_INT(_vfs_zfs, OID_AUTO, sync_pass_rewrite, CTLFLAG_RDTUN,
126     &zfs_sync_pass_rewrite, 0, "rewrite new bps starting in this pass");
127
128 /*
129  * An allocating zio is one that either currently has the DVA allocate
130  * stage set or will have it later in its lifetime.
131  */
132 #define IO_IS_ALLOCATING(zio) ((zio)->io_orig_pipeline & ZIO_STAGE_DVA_ALLOCATE)
133
134 boolean_t       zio_requeue_io_start_cut_in_line = B_TRUE;
135
136 #ifdef illumos
137 #ifdef ZFS_DEBUG
138 int zio_buf_debug_limit = 16384;
139 #else
140 int zio_buf_debug_limit = 0;
141 #endif
142 #endif
143
144 static void zio_taskq_dispatch(zio_t *, zio_taskq_type_t, boolean_t);
145
146 void
147 zio_init(void)
148 {
149         size_t c;
150         zio_cache = kmem_cache_create("zio_cache",
151             sizeof (zio_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
152         zio_link_cache = kmem_cache_create("zio_link_cache",
153             sizeof (zio_link_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
154         if (!zio_use_uma)
155                 goto out;
156
157         /*
158          * For small buffers, we want a cache for each multiple of
159          * SPA_MINBLOCKSIZE.  For larger buffers, we want a cache
160          * for each quarter-power of 2.
161          */
162         for (c = 0; c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; c++) {
163                 size_t size = (c + 1) << SPA_MINBLOCKSHIFT;
164                 size_t p2 = size;
165                 size_t align = 0;
166                 int cflags = zio_exclude_metadata ? KMC_NODEBUG : 0;
167
168                 while (!ISP2(p2))
169                         p2 &= p2 - 1;
170
171 #ifdef illumos
172 #ifndef _KERNEL
173                 /*
174                  * If we are using watchpoints, put each buffer on its own page,
175                  * to eliminate the performance overhead of trapping to the
176                  * kernel when modifying a non-watched buffer that shares the
177                  * page with a watched buffer.
178                  */
179                 if (arc_watch && !IS_P2ALIGNED(size, PAGESIZE))
180                         continue;
181 #endif
182 #endif /* illumos */
183                 if (size <= 4 * SPA_MINBLOCKSIZE) {
184                         align = SPA_MINBLOCKSIZE;
185                 } else if (IS_P2ALIGNED(size, p2 >> 2)) {
186                         align = MIN(p2 >> 2, PAGESIZE);
187                 }
188
189                 if (align != 0) {
190                         char name[36];
191                         (void) sprintf(name, "zio_buf_%lu", (ulong_t)size);
192                         zio_buf_cache[c] = kmem_cache_create(name, size,
193                             align, NULL, NULL, NULL, NULL, NULL, cflags);
194
195                         /*
196                          * Since zio_data bufs do not appear in crash dumps, we
197                          * pass KMC_NOTOUCH so that no allocator metadata is
198                          * stored with the buffers.
199                          */
200                         (void) sprintf(name, "zio_data_buf_%lu", (ulong_t)size);
201                         zio_data_buf_cache[c] = kmem_cache_create(name, size,
202                             align, NULL, NULL, NULL, NULL, NULL,
203                             cflags | KMC_NOTOUCH | KMC_NODEBUG);
204                 }
205         }
206
207         while (--c != 0) {
208                 ASSERT(zio_buf_cache[c] != NULL);
209                 if (zio_buf_cache[c - 1] == NULL)
210                         zio_buf_cache[c - 1] = zio_buf_cache[c];
211
212                 ASSERT(zio_data_buf_cache[c] != NULL);
213                 if (zio_data_buf_cache[c - 1] == NULL)
214                         zio_data_buf_cache[c - 1] = zio_data_buf_cache[c];
215         }
216 out:
217
218         zio_inject_init();
219
220         zio_trim_ksp = kstat_create("zfs", 0, "zio_trim", "misc",
221             KSTAT_TYPE_NAMED,
222             sizeof(zio_trim_stats) / sizeof(kstat_named_t),
223             KSTAT_FLAG_VIRTUAL);
224
225         if (zio_trim_ksp != NULL) {
226                 zio_trim_ksp->ks_data = &zio_trim_stats;
227                 kstat_install(zio_trim_ksp);
228         }
229 }
230
231 void
232 zio_fini(void)
233 {
234         size_t c;
235         kmem_cache_t *last_cache = NULL;
236         kmem_cache_t *last_data_cache = NULL;
237
238         for (c = 0; c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; c++) {
239                 if (zio_buf_cache[c] != last_cache) {
240                         last_cache = zio_buf_cache[c];
241                         kmem_cache_destroy(zio_buf_cache[c]);
242                 }
243                 zio_buf_cache[c] = NULL;
244
245                 if (zio_data_buf_cache[c] != last_data_cache) {
246                         last_data_cache = zio_data_buf_cache[c];
247                         kmem_cache_destroy(zio_data_buf_cache[c]);
248                 }
249                 zio_data_buf_cache[c] = NULL;
250         }
251
252         kmem_cache_destroy(zio_link_cache);
253         kmem_cache_destroy(zio_cache);
254
255         zio_inject_fini();
256
257         if (zio_trim_ksp != NULL) {
258                 kstat_delete(zio_trim_ksp);
259                 zio_trim_ksp = NULL;
260         }
261 }
262
263 /*
264  * ==========================================================================
265  * Allocate and free I/O buffers
266  * ==========================================================================
267  */
268
269 /*
270  * Use zio_buf_alloc to allocate ZFS metadata.  This data will appear in a
271  * crashdump if the kernel panics, so use it judiciously.  Obviously, it's
272  * useful to inspect ZFS metadata, but if possible, we should avoid keeping
273  * excess / transient data in-core during a crashdump.
274  */
275 static void *
276 zio_buf_alloc_impl(size_t size, boolean_t canwait)
277 {
278         size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
279         int flags = zio_exclude_metadata ? KM_NODEBUG : 0;
280
281         VERIFY3U(c, <, SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
282
283         if (zio_use_uma) {
284                 return (kmem_cache_alloc(zio_buf_cache[c],
285                     canwait ? KM_PUSHPAGE : KM_NOSLEEP));
286         } else {
287                 return (kmem_alloc(size,
288                     (canwait ? KM_SLEEP : KM_NOSLEEP) | flags));
289         }
290 }
291
292 void *
293 zio_buf_alloc(size_t size)
294 {
295         return (zio_buf_alloc_impl(size, B_TRUE));
296 }
297
298 void *
299 zio_buf_alloc_nowait(size_t size)
300 {
301         return (zio_buf_alloc_impl(size, B_FALSE));
302 }
303
304 /*
305  * Use zio_data_buf_alloc to allocate data.  The data will not appear in a
306  * crashdump if the kernel panics.  This exists so that we will limit the amount
307  * of ZFS data that shows up in a kernel crashdump.  (Thus reducing the amount
308  * of kernel heap dumped to disk when the kernel panics)
309  */
310 void *
311 zio_data_buf_alloc(size_t size)
312 {
313         size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
314
315         VERIFY3U(c, <, SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
316
317         if (zio_use_uma)
318                 return (kmem_cache_alloc(zio_data_buf_cache[c], KM_PUSHPAGE));
319         else
320                 return (kmem_alloc(size, KM_SLEEP | KM_NODEBUG));
321 }
322
323 void
324 zio_buf_free(void *buf, size_t size)
325 {
326         size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
327
328         VERIFY3U(c, <, SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
329
330         if (zio_use_uma)
331                 kmem_cache_free(zio_buf_cache[c], buf);
332         else
333                 kmem_free(buf, size);
334 }
335
336 void
337 zio_data_buf_free(void *buf, size_t size)
338 {
339         size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
340
341         VERIFY3U(c, <, SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
342
343         if (zio_use_uma)
344                 kmem_cache_free(zio_data_buf_cache[c], buf);
345         else
346                 kmem_free(buf, size);
347 }
348
349 /*
350  * ==========================================================================
351  * Push and pop I/O transform buffers
352  * ==========================================================================
353  */
354 void
355 zio_push_transform(zio_t *zio, void *data, uint64_t size, uint64_t bufsize,
356     zio_transform_func_t *transform)
357 {
358         zio_transform_t *zt = kmem_alloc(sizeof (zio_transform_t), KM_SLEEP);
359
360         zt->zt_orig_data = zio->io_data;
361         zt->zt_orig_size = zio->io_size;
362         zt->zt_bufsize = bufsize;
363         zt->zt_transform = transform;
364
365         zt->zt_next = zio->io_transform_stack;
366         zio->io_transform_stack = zt;
367
368         zio->io_data = data;
369         zio->io_size = size;
370 }
371
372 void
373 zio_pop_transforms(zio_t *zio)
374 {
375         zio_transform_t *zt;
376
377         while ((zt = zio->io_transform_stack) != NULL) {
378                 if (zt->zt_transform != NULL)
379                         zt->zt_transform(zio,
380                             zt->zt_orig_data, zt->zt_orig_size);
381
382                 if (zt->zt_bufsize != 0)
383                         zio_buf_free(zio->io_data, zt->zt_bufsize);
384
385                 zio->io_data = zt->zt_orig_data;
386                 zio->io_size = zt->zt_orig_size;
387                 zio->io_transform_stack = zt->zt_next;
388
389                 kmem_free(zt, sizeof (zio_transform_t));
390         }
391 }
392
393 /*
394  * ==========================================================================
395  * I/O transform callbacks for subblocks and decompression
396  * ==========================================================================
397  */
398 static void
399 zio_subblock(zio_t *zio, void *data, uint64_t size)
400 {
401         ASSERT(zio->io_size > size);
402
403         if (zio->io_type == ZIO_TYPE_READ)
404                 bcopy(zio->io_data, data, size);
405 }
406
407 static void
408 zio_decompress(zio_t *zio, void *data, uint64_t size)
409 {
410         if (zio->io_error == 0 &&
411             zio_decompress_data(BP_GET_COMPRESS(zio->io_bp),
412             zio->io_data, data, zio->io_size, size) != 0)
413                 zio->io_error = SET_ERROR(EIO);
414 }
415
416 /*
417  * ==========================================================================
418  * I/O parent/child relationships and pipeline interlocks
419  * ==========================================================================
420  */
421 zio_t *
422 zio_walk_parents(zio_t *cio, zio_link_t **zl)
423 {
424         list_t *pl = &cio->io_parent_list;
425
426         *zl = (*zl == NULL) ? list_head(pl) : list_next(pl, *zl);
427         if (*zl == NULL)
428                 return (NULL);
429
430         ASSERT((*zl)->zl_child == cio);
431         return ((*zl)->zl_parent);
432 }
433
434 zio_t *
435 zio_walk_children(zio_t *pio, zio_link_t **zl)
436 {
437         list_t *cl = &pio->io_child_list;
438
439         *zl = (*zl == NULL) ? list_head(cl) : list_next(cl, *zl);
440         if (*zl == NULL)
441                 return (NULL);
442
443         ASSERT((*zl)->zl_parent == pio);
444         return ((*zl)->zl_child);
445 }
446
447 zio_t *
448 zio_unique_parent(zio_t *cio)
449 {
450         zio_link_t *zl = NULL;
451         zio_t *pio = zio_walk_parents(cio, &zl);
452
453         VERIFY3P(zio_walk_parents(cio, &zl), ==, NULL);
454         return (pio);
455 }
456
457 void
458 zio_add_child(zio_t *pio, zio_t *cio)
459 {
460         zio_link_t *zl = kmem_cache_alloc(zio_link_cache, KM_SLEEP);
461
462         /*
463          * Logical I/Os can have logical, gang, or vdev children.
464          * Gang I/Os can have gang or vdev children.
465          * Vdev I/Os can only have vdev children.
466          * The following ASSERT captures all of these constraints.
467          */
468         ASSERT(cio->io_child_type <= pio->io_child_type);
469
470         zl->zl_parent = pio;
471         zl->zl_child = cio;
472
473         mutex_enter(&cio->io_lock);
474         mutex_enter(&pio->io_lock);
475
476         ASSERT(pio->io_state[ZIO_WAIT_DONE] == 0);
477
478         for (int w = 0; w < ZIO_WAIT_TYPES; w++)
479                 pio->io_children[cio->io_child_type][w] += !cio->io_state[w];
480
481         list_insert_head(&pio->io_child_list, zl);
482         list_insert_head(&cio->io_parent_list, zl);
483
484         pio->io_child_count++;
485         cio->io_parent_count++;
486
487         mutex_exit(&pio->io_lock);
488         mutex_exit(&cio->io_lock);
489 }
490
491 static void
492 zio_remove_child(zio_t *pio, zio_t *cio, zio_link_t *zl)
493 {
494         ASSERT(zl->zl_parent == pio);
495         ASSERT(zl->zl_child == cio);
496
497         mutex_enter(&cio->io_lock);
498         mutex_enter(&pio->io_lock);
499
500         list_remove(&pio->io_child_list, zl);
501         list_remove(&cio->io_parent_list, zl);
502
503         pio->io_child_count--;
504         cio->io_parent_count--;
505
506         mutex_exit(&pio->io_lock);
507         mutex_exit(&cio->io_lock);
508
509         kmem_cache_free(zio_link_cache, zl);
510 }
511
512 static boolean_t
513 zio_wait_for_children(zio_t *zio, enum zio_child child, enum zio_wait_type wait)
514 {
515         uint64_t *countp = &zio->io_children[child][wait];
516         boolean_t waiting = B_FALSE;
517
518         mutex_enter(&zio->io_lock);
519         ASSERT(zio->io_stall == NULL);
520         if (*countp != 0) {
521                 zio->io_stage >>= 1;
522                 ASSERT3U(zio->io_stage, !=, ZIO_STAGE_OPEN);
523                 zio->io_stall = countp;
524                 waiting = B_TRUE;
525         }
526         mutex_exit(&zio->io_lock);
527
528         return (waiting);
529 }
530
531 static void
532 zio_notify_parent(zio_t *pio, zio_t *zio, enum zio_wait_type wait)
533 {
534         uint64_t *countp = &pio->io_children[zio->io_child_type][wait];
535         int *errorp = &pio->io_child_error[zio->io_child_type];
536
537         mutex_enter(&pio->io_lock);
538         if (zio->io_error && !(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE))
539                 *errorp = zio_worst_error(*errorp, zio->io_error);
540         pio->io_reexecute |= zio->io_reexecute;
541         ASSERT3U(*countp, >, 0);
542
543         (*countp)--;
544
545         if (*countp == 0 && pio->io_stall == countp) {
546                 zio_taskq_type_t type =
547                     pio->io_stage < ZIO_STAGE_VDEV_IO_START ? ZIO_TASKQ_ISSUE :
548                     ZIO_TASKQ_INTERRUPT;
549                 pio->io_stall = NULL;
550                 mutex_exit(&pio->io_lock);
551                 /*
552                  * Dispatch the parent zio in its own taskq so that
553                  * the child can continue to make progress. This also
554                  * prevents overflowing the stack when we have deeply nested
555                  * parent-child relationships.
556                  */
557                 zio_taskq_dispatch(pio, type, B_FALSE);
558         } else {
559                 mutex_exit(&pio->io_lock);
560         }
561 }
562
563 static void
564 zio_inherit_child_errors(zio_t *zio, enum zio_child c)
565 {
566         if (zio->io_child_error[c] != 0 && zio->io_error == 0)
567                 zio->io_error = zio->io_child_error[c];
568 }
569
570 int
571 zio_bookmark_compare(const void *x1, const void *x2)
572 {
573         const zio_t *z1 = x1;
574         const zio_t *z2 = x2;
575
576         if (z1->io_bookmark.zb_objset < z2->io_bookmark.zb_objset)
577                 return (-1);
578         if (z1->io_bookmark.zb_objset > z2->io_bookmark.zb_objset)
579                 return (1);
580
581         if (z1->io_bookmark.zb_object < z2->io_bookmark.zb_object)
582                 return (-1);
583         if (z1->io_bookmark.zb_object > z2->io_bookmark.zb_object)
584                 return (1);
585
586         if (z1->io_bookmark.zb_level < z2->io_bookmark.zb_level)
587                 return (-1);
588         if (z1->io_bookmark.zb_level > z2->io_bookmark.zb_level)
589                 return (1);
590
591         if (z1->io_bookmark.zb_blkid < z2->io_bookmark.zb_blkid)
592                 return (-1);
593         if (z1->io_bookmark.zb_blkid > z2->io_bookmark.zb_blkid)
594                 return (1);
595
596         if (z1 < z2)
597                 return (-1);
598         if (z1 > z2)
599                 return (1);
600
601         return (0);
602 }
603
604 /*
605  * ==========================================================================
606  * Create the various types of I/O (read, write, free, etc)
607  * ==========================================================================
608  */
609 static zio_t *
610 zio_create(zio_t *pio, spa_t *spa, uint64_t txg, const blkptr_t *bp,
611     void *data, uint64_t lsize, uint64_t psize, zio_done_func_t *done,
612     void *private, zio_type_t type, zio_priority_t priority,
613     enum zio_flag flags, vdev_t *vd, uint64_t offset,
614     const zbookmark_phys_t *zb, enum zio_stage stage, enum zio_stage pipeline)
615 {
616         zio_t *zio;
617
618         ASSERT3U(type == ZIO_TYPE_FREE || psize, <=, SPA_MAXBLOCKSIZE);
619         ASSERT(P2PHASE(psize, SPA_MINBLOCKSIZE) == 0);
620         ASSERT(P2PHASE(offset, SPA_MINBLOCKSIZE) == 0);
621
622         ASSERT(!vd || spa_config_held(spa, SCL_STATE_ALL, RW_READER));
623         ASSERT(!bp || !(flags & ZIO_FLAG_CONFIG_WRITER));
624         ASSERT(vd || stage == ZIO_STAGE_OPEN);
625
626         IMPLY(lsize != psize, (flags & ZIO_FLAG_RAW) != 0);
627
628         zio = kmem_cache_alloc(zio_cache, KM_SLEEP);
629         bzero(zio, sizeof (zio_t));
630
631         mutex_init(&zio->io_lock, NULL, MUTEX_DEFAULT, NULL);
632         cv_init(&zio->io_cv, NULL, CV_DEFAULT, NULL);
633
634         list_create(&zio->io_parent_list, sizeof (zio_link_t),
635             offsetof(zio_link_t, zl_parent_node));
636         list_create(&zio->io_child_list, sizeof (zio_link_t),
637             offsetof(zio_link_t, zl_child_node));
638         metaslab_trace_init(&zio->io_alloc_list);
639
640         if (vd != NULL)
641                 zio->io_child_type = ZIO_CHILD_VDEV;
642         else if (flags & ZIO_FLAG_GANG_CHILD)
643                 zio->io_child_type = ZIO_CHILD_GANG;
644         else if (flags & ZIO_FLAG_DDT_CHILD)
645                 zio->io_child_type = ZIO_CHILD_DDT;
646         else
647                 zio->io_child_type = ZIO_CHILD_LOGICAL;
648
649         if (bp != NULL) {
650                 zio->io_bp = (blkptr_t *)bp;
651                 zio->io_bp_copy = *bp;
652                 zio->io_bp_orig = *bp;
653                 if (type != ZIO_TYPE_WRITE ||
654                     zio->io_child_type == ZIO_CHILD_DDT)
655                         zio->io_bp = &zio->io_bp_copy;  /* so caller can free */
656                 if (zio->io_child_type == ZIO_CHILD_LOGICAL)
657                         zio->io_logical = zio;
658                 if (zio->io_child_type > ZIO_CHILD_GANG && BP_IS_GANG(bp))
659                         pipeline |= ZIO_GANG_STAGES;
660         }
661
662         zio->io_spa = spa;
663         zio->io_txg = txg;
664         zio->io_done = done;
665         zio->io_private = private;
666         zio->io_type = type;
667         zio->io_priority = priority;
668         zio->io_vd = vd;
669         zio->io_offset = offset;
670         zio->io_orig_data = zio->io_data = data;
671         zio->io_orig_size = zio->io_size = psize;
672         zio->io_lsize = lsize;
673         zio->io_orig_flags = zio->io_flags = flags;
674         zio->io_orig_stage = zio->io_stage = stage;
675         zio->io_orig_pipeline = zio->io_pipeline = pipeline;
676         zio->io_pipeline_trace = ZIO_STAGE_OPEN;
677
678         zio->io_state[ZIO_WAIT_READY] = (stage >= ZIO_STAGE_READY);
679         zio->io_state[ZIO_WAIT_DONE] = (stage >= ZIO_STAGE_DONE);
680
681         if (zb != NULL)
682                 zio->io_bookmark = *zb;
683
684         if (pio != NULL) {
685                 if (zio->io_logical == NULL)
686                         zio->io_logical = pio->io_logical;
687                 if (zio->io_child_type == ZIO_CHILD_GANG)
688                         zio->io_gang_leader = pio->io_gang_leader;
689                 zio_add_child(pio, zio);
690         }
691
692         return (zio);
693 }
694
695 static void
696 zio_destroy(zio_t *zio)
697 {
698         metaslab_trace_fini(&zio->io_alloc_list);
699         list_destroy(&zio->io_parent_list);
700         list_destroy(&zio->io_child_list);
701         mutex_destroy(&zio->io_lock);
702         cv_destroy(&zio->io_cv);
703         kmem_cache_free(zio_cache, zio);
704 }
705
706 zio_t *
707 zio_null(zio_t *pio, spa_t *spa, vdev_t *vd, zio_done_func_t *done,
708     void *private, enum zio_flag flags)
709 {
710         zio_t *zio;
711
712         zio = zio_create(pio, spa, 0, NULL, NULL, 0, 0, done, private,
713             ZIO_TYPE_NULL, ZIO_PRIORITY_NOW, flags, vd, 0, NULL,
714             ZIO_STAGE_OPEN, ZIO_INTERLOCK_PIPELINE);
715
716         return (zio);
717 }
718
719 zio_t *
720 zio_root(spa_t *spa, zio_done_func_t *done, void *private, enum zio_flag flags)
721 {
722         return (zio_null(NULL, spa, NULL, done, private, flags));
723 }
724
725 void
726 zfs_blkptr_verify(spa_t *spa, const blkptr_t *bp)
727 {
728         if (!DMU_OT_IS_VALID(BP_GET_TYPE(bp))) {
729                 zfs_panic_recover("blkptr at %p has invalid TYPE %llu",
730                     bp, (longlong_t)BP_GET_TYPE(bp));
731         }
732         if (BP_GET_CHECKSUM(bp) >= ZIO_CHECKSUM_FUNCTIONS ||
733             BP_GET_CHECKSUM(bp) <= ZIO_CHECKSUM_ON) {
734                 zfs_panic_recover("blkptr at %p has invalid CHECKSUM %llu",
735                     bp, (longlong_t)BP_GET_CHECKSUM(bp));
736         }
737         if (BP_GET_COMPRESS(bp) >= ZIO_COMPRESS_FUNCTIONS ||
738             BP_GET_COMPRESS(bp) <= ZIO_COMPRESS_ON) {
739                 zfs_panic_recover("blkptr at %p has invalid COMPRESS %llu",
740                     bp, (longlong_t)BP_GET_COMPRESS(bp));
741         }
742         if (BP_GET_LSIZE(bp) > SPA_MAXBLOCKSIZE) {
743                 zfs_panic_recover("blkptr at %p has invalid LSIZE %llu",
744                     bp, (longlong_t)BP_GET_LSIZE(bp));
745         }
746         if (BP_GET_PSIZE(bp) > SPA_MAXBLOCKSIZE) {
747                 zfs_panic_recover("blkptr at %p has invalid PSIZE %llu",
748                     bp, (longlong_t)BP_GET_PSIZE(bp));
749         }
750
751         if (BP_IS_EMBEDDED(bp)) {
752                 if (BPE_GET_ETYPE(bp) > NUM_BP_EMBEDDED_TYPES) {
753                         zfs_panic_recover("blkptr at %p has invalid ETYPE %llu",
754                             bp, (longlong_t)BPE_GET_ETYPE(bp));
755                 }
756         }
757
758         /*
759          * Pool-specific checks.
760          *
761          * Note: it would be nice to verify that the blk_birth and
762          * BP_PHYSICAL_BIRTH() are not too large.  However, spa_freeze()
763          * allows the birth time of log blocks (and dmu_sync()-ed blocks
764          * that are in the log) to be arbitrarily large.
765          */
766         for (int i = 0; i < BP_GET_NDVAS(bp); i++) {
767                 uint64_t vdevid = DVA_GET_VDEV(&bp->blk_dva[i]);
768                 if (vdevid >= spa->spa_root_vdev->vdev_children) {
769                         zfs_panic_recover("blkptr at %p DVA %u has invalid "
770                             "VDEV %llu",
771                             bp, i, (longlong_t)vdevid);
772                         continue;
773                 }
774                 vdev_t *vd = spa->spa_root_vdev->vdev_child[vdevid];
775                 if (vd == NULL) {
776                         zfs_panic_recover("blkptr at %p DVA %u has invalid "
777                             "VDEV %llu",
778                             bp, i, (longlong_t)vdevid);
779                         continue;
780                 }
781                 if (vd->vdev_ops == &vdev_hole_ops) {
782                         zfs_panic_recover("blkptr at %p DVA %u has hole "
783                             "VDEV %llu",
784                             bp, i, (longlong_t)vdevid);
785                         continue;
786                 }
787                 if (vd->vdev_ops == &vdev_missing_ops) {
788                         /*
789                          * "missing" vdevs are valid during import, but we
790                          * don't have their detailed info (e.g. asize), so
791                          * we can't perform any more checks on them.
792                          */
793                         continue;
794                 }
795                 uint64_t offset = DVA_GET_OFFSET(&bp->blk_dva[i]);
796                 uint64_t asize = DVA_GET_ASIZE(&bp->blk_dva[i]);
797                 if (BP_IS_GANG(bp))
798                         asize = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
799                 if (offset + asize > vd->vdev_asize) {
800                         zfs_panic_recover("blkptr at %p DVA %u has invalid "
801                             "OFFSET %llu",
802                             bp, i, (longlong_t)offset);
803                 }
804         }
805 }
806
807 zio_t *
808 zio_read(zio_t *pio, spa_t *spa, const blkptr_t *bp,
809     void *data, uint64_t size, zio_done_func_t *done, void *private,
810     zio_priority_t priority, enum zio_flag flags, const zbookmark_phys_t *zb)
811 {
812         zio_t *zio;
813
814         zfs_blkptr_verify(spa, bp);
815
816         zio = zio_create(pio, spa, BP_PHYSICAL_BIRTH(bp), bp,
817             data, size, size, done, private,
818             ZIO_TYPE_READ, priority, flags, NULL, 0, zb,
819             ZIO_STAGE_OPEN, (flags & ZIO_FLAG_DDT_CHILD) ?
820             ZIO_DDT_CHILD_READ_PIPELINE : ZIO_READ_PIPELINE);
821
822         return (zio);
823 }
824
825 zio_t *
826 zio_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
827     void *data, uint64_t lsize, uint64_t psize, const zio_prop_t *zp,
828     zio_done_func_t *ready, zio_done_func_t *children_ready,
829     zio_done_func_t *physdone, zio_done_func_t *done,
830     void *private, zio_priority_t priority, enum zio_flag flags,
831     const zbookmark_phys_t *zb)
832 {
833         zio_t *zio;
834
835         ASSERT(zp->zp_checksum >= ZIO_CHECKSUM_OFF &&
836             zp->zp_checksum < ZIO_CHECKSUM_FUNCTIONS &&
837             zp->zp_compress >= ZIO_COMPRESS_OFF &&
838             zp->zp_compress < ZIO_COMPRESS_FUNCTIONS &&
839             DMU_OT_IS_VALID(zp->zp_type) &&
840             zp->zp_level < 32 &&
841             zp->zp_copies > 0 &&
842             zp->zp_copies <= spa_max_replication(spa));
843
844         zio = zio_create(pio, spa, txg, bp, data, lsize, psize, done, private,
845             ZIO_TYPE_WRITE, priority, flags, NULL, 0, zb,
846             ZIO_STAGE_OPEN, (flags & ZIO_FLAG_DDT_CHILD) ?
847             ZIO_DDT_CHILD_WRITE_PIPELINE : ZIO_WRITE_PIPELINE);
848
849         zio->io_ready = ready;
850         zio->io_children_ready = children_ready;
851         zio->io_physdone = physdone;
852         zio->io_prop = *zp;
853
854         /*
855          * Data can be NULL if we are going to call zio_write_override() to
856          * provide the already-allocated BP.  But we may need the data to
857          * verify a dedup hit (if requested).  In this case, don't try to
858          * dedup (just take the already-allocated BP verbatim).
859          */
860         if (data == NULL && zio->io_prop.zp_dedup_verify) {
861                 zio->io_prop.zp_dedup = zio->io_prop.zp_dedup_verify = B_FALSE;
862         }
863
864         return (zio);
865 }
866
867 zio_t *
868 zio_rewrite(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, void *data,
869     uint64_t size, zio_done_func_t *done, void *private,
870     zio_priority_t priority, enum zio_flag flags, zbookmark_phys_t *zb)
871 {
872         zio_t *zio;
873
874         zio = zio_create(pio, spa, txg, bp, data, size, size, done, private,
875             ZIO_TYPE_WRITE, priority, flags | ZIO_FLAG_IO_REWRITE, NULL, 0, zb,
876             ZIO_STAGE_OPEN, ZIO_REWRITE_PIPELINE);
877
878         return (zio);
879 }
880
881 void
882 zio_write_override(zio_t *zio, blkptr_t *bp, int copies, boolean_t nopwrite)
883 {
884         ASSERT(zio->io_type == ZIO_TYPE_WRITE);
885         ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
886         ASSERT(zio->io_stage == ZIO_STAGE_OPEN);
887         ASSERT(zio->io_txg == spa_syncing_txg(zio->io_spa));
888
889         /*
890          * We must reset the io_prop to match the values that existed
891          * when the bp was first written by dmu_sync() keeping in mind
892          * that nopwrite and dedup are mutually exclusive.
893          */
894         zio->io_prop.zp_dedup = nopwrite ? B_FALSE : zio->io_prop.zp_dedup;
895         zio->io_prop.zp_nopwrite = nopwrite;
896         zio->io_prop.zp_copies = copies;
897         zio->io_bp_override = bp;
898 }
899
900 void
901 zio_free(spa_t *spa, uint64_t txg, const blkptr_t *bp)
902 {
903
904         /*
905          * The check for EMBEDDED is a performance optimization.  We
906          * process the free here (by ignoring it) rather than
907          * putting it on the list and then processing it in zio_free_sync().
908          */
909         if (BP_IS_EMBEDDED(bp))
910                 return;
911         metaslab_check_free(spa, bp);
912
913         /*
914          * Frees that are for the currently-syncing txg, are not going to be
915          * deferred, and which will not need to do a read (i.e. not GANG or
916          * DEDUP), can be processed immediately.  Otherwise, put them on the
917          * in-memory list for later processing.
918          */
919         if (zfs_trim_enabled || BP_IS_GANG(bp) || BP_GET_DEDUP(bp) ||
920             txg != spa->spa_syncing_txg ||
921             spa_sync_pass(spa) >= zfs_sync_pass_deferred_free) {
922                 bplist_append(&spa->spa_free_bplist[txg & TXG_MASK], bp);
923         } else {
924                 VERIFY0(zio_wait(zio_free_sync(NULL, spa, txg, bp,
925                     BP_GET_PSIZE(bp), 0)));
926         }
927 }
928
929 zio_t *
930 zio_free_sync(zio_t *pio, spa_t *spa, uint64_t txg, const blkptr_t *bp,
931     uint64_t size, enum zio_flag flags)
932 {
933         zio_t *zio;
934         enum zio_stage stage = ZIO_FREE_PIPELINE;
935
936         ASSERT(!BP_IS_HOLE(bp));
937         ASSERT(spa_syncing_txg(spa) == txg);
938         ASSERT(spa_sync_pass(spa) < zfs_sync_pass_deferred_free);
939
940         if (BP_IS_EMBEDDED(bp))
941                 return (zio_null(pio, spa, NULL, NULL, NULL, 0));
942
943         metaslab_check_free(spa, bp);
944         arc_freed(spa, bp);
945
946         if (zfs_trim_enabled)
947                 stage |= ZIO_STAGE_ISSUE_ASYNC | ZIO_STAGE_VDEV_IO_START |
948                     ZIO_STAGE_VDEV_IO_ASSESS;
949         /*
950          * GANG and DEDUP blocks can induce a read (for the gang block header,
951          * or the DDT), so issue them asynchronously so that this thread is
952          * not tied up.
953          */
954         else if (BP_IS_GANG(bp) || BP_GET_DEDUP(bp))
955                 stage |= ZIO_STAGE_ISSUE_ASYNC;
956
957         flags |= ZIO_FLAG_DONT_QUEUE;
958
959         zio = zio_create(pio, spa, txg, bp, NULL, size,
960             size, NULL, NULL, ZIO_TYPE_FREE, ZIO_PRIORITY_NOW,
961             flags, NULL, 0, NULL, ZIO_STAGE_OPEN, stage);
962
963         return (zio);
964 }
965
966 zio_t *
967 zio_claim(zio_t *pio, spa_t *spa, uint64_t txg, const blkptr_t *bp,
968     zio_done_func_t *done, void *private, enum zio_flag flags)
969 {
970         zio_t *zio;
971
972         dprintf_bp(bp, "claiming in txg %llu", txg);
973
974         if (BP_IS_EMBEDDED(bp))
975                 return (zio_null(pio, spa, NULL, NULL, NULL, 0));
976
977         /*
978          * A claim is an allocation of a specific block.  Claims are needed
979          * to support immediate writes in the intent log.  The issue is that
980          * immediate writes contain committed data, but in a txg that was
981          * *not* committed.  Upon opening the pool after an unclean shutdown,
982          * the intent log claims all blocks that contain immediate write data
983          * so that the SPA knows they're in use.
984          *
985          * All claims *must* be resolved in the first txg -- before the SPA
986          * starts allocating blocks -- so that nothing is allocated twice.
987          * If txg == 0 we just verify that the block is claimable.
988          */
989         ASSERT3U(spa->spa_uberblock.ub_rootbp.blk_birth, <, spa_first_txg(spa));
990         ASSERT(txg == spa_first_txg(spa) || txg == 0);
991         ASSERT(!BP_GET_DEDUP(bp) || !spa_writeable(spa));       /* zdb(1M) */
992
993         zio = zio_create(pio, spa, txg, bp, NULL, BP_GET_PSIZE(bp),
994             BP_GET_PSIZE(bp), done, private, ZIO_TYPE_CLAIM, ZIO_PRIORITY_NOW,
995             flags, NULL, 0, NULL, ZIO_STAGE_OPEN, ZIO_CLAIM_PIPELINE);
996         ASSERT0(zio->io_queued_timestamp);
997
998         return (zio);
999 }
1000
1001 zio_t *
1002 zio_ioctl(zio_t *pio, spa_t *spa, vdev_t *vd, int cmd, uint64_t offset,
1003     uint64_t size, zio_done_func_t *done, void *private,
1004     zio_priority_t priority, enum zio_flag flags)
1005 {
1006         zio_t *zio;
1007         int c;
1008
1009         if (vd->vdev_children == 0) {
1010                 zio = zio_create(pio, spa, 0, NULL, NULL, 0, 0, done, private,
1011                     ZIO_TYPE_IOCTL, ZIO_PRIORITY_NOW, flags, vd, 0, NULL,
1012                     ZIO_STAGE_OPEN, ZIO_IOCTL_PIPELINE);
1013
1014                 zio->io_cmd = cmd;
1015         } else {
1016                 zio = zio_null(pio, spa, NULL, NULL, NULL, flags);
1017
1018                 for (c = 0; c < vd->vdev_children; c++)
1019                         zio_nowait(zio_ioctl(zio, spa, vd->vdev_child[c], cmd,
1020                             offset, size, done, private, priority, flags));
1021         }
1022
1023         return (zio);
1024 }
1025
1026 zio_t *
1027 zio_read_phys(zio_t *pio, vdev_t *vd, uint64_t offset, uint64_t size,
1028     void *data, int checksum, zio_done_func_t *done, void *private,
1029     zio_priority_t priority, enum zio_flag flags, boolean_t labels)
1030 {
1031         zio_t *zio;
1032
1033         ASSERT(vd->vdev_children == 0);
1034         ASSERT(!labels || offset + size <= VDEV_LABEL_START_SIZE ||
1035             offset >= vd->vdev_psize - VDEV_LABEL_END_SIZE);
1036         ASSERT3U(offset + size, <=, vd->vdev_psize);
1037
1038         zio = zio_create(pio, vd->vdev_spa, 0, NULL, data, size, size, done,
1039             private, ZIO_TYPE_READ, priority, flags | ZIO_FLAG_PHYSICAL, vd,
1040             offset, NULL, ZIO_STAGE_OPEN, ZIO_READ_PHYS_PIPELINE);
1041
1042         zio->io_prop.zp_checksum = checksum;
1043
1044         return (zio);
1045 }
1046
1047 zio_t *
1048 zio_write_phys(zio_t *pio, vdev_t *vd, uint64_t offset, uint64_t size,
1049     void *data, int checksum, zio_done_func_t *done, void *private,
1050     zio_priority_t priority, enum zio_flag flags, boolean_t labels)
1051 {
1052         zio_t *zio;
1053
1054         ASSERT(vd->vdev_children == 0);
1055         ASSERT(!labels || offset + size <= VDEV_LABEL_START_SIZE ||
1056             offset >= vd->vdev_psize - VDEV_LABEL_END_SIZE);
1057         ASSERT3U(offset + size, <=, vd->vdev_psize);
1058
1059         zio = zio_create(pio, vd->vdev_spa, 0, NULL, data, size, size, done,
1060             private, ZIO_TYPE_WRITE, priority, flags | ZIO_FLAG_PHYSICAL, vd,
1061             offset, NULL, ZIO_STAGE_OPEN, ZIO_WRITE_PHYS_PIPELINE);
1062
1063         zio->io_prop.zp_checksum = checksum;
1064
1065         if (zio_checksum_table[checksum].ci_flags & ZCHECKSUM_FLAG_EMBEDDED) {
1066                 /*
1067                  * zec checksums are necessarily destructive -- they modify
1068                  * the end of the write buffer to hold the verifier/checksum.
1069                  * Therefore, we must make a local copy in case the data is
1070                  * being written to multiple places in parallel.
1071                  */
1072                 void *wbuf = zio_buf_alloc(size);
1073                 bcopy(data, wbuf, size);
1074                 zio_push_transform(zio, wbuf, size, size, NULL);
1075         }
1076
1077         return (zio);
1078 }
1079
1080 /*
1081  * Create a child I/O to do some work for us.
1082  */
1083 zio_t *
1084 zio_vdev_child_io(zio_t *pio, blkptr_t *bp, vdev_t *vd, uint64_t offset,
1085     void *data, uint64_t size, int type, zio_priority_t priority,
1086     enum zio_flag flags, zio_done_func_t *done, void *private)
1087 {
1088         enum zio_stage pipeline = ZIO_VDEV_CHILD_PIPELINE;
1089         zio_t *zio;
1090
1091         ASSERT(vd->vdev_parent ==
1092             (pio->io_vd ? pio->io_vd : pio->io_spa->spa_root_vdev));
1093
1094         if (type == ZIO_TYPE_READ && bp != NULL) {
1095                 /*
1096                  * If we have the bp, then the child should perform the
1097                  * checksum and the parent need not.  This pushes error
1098                  * detection as close to the leaves as possible and
1099                  * eliminates redundant checksums in the interior nodes.
1100                  */
1101                 pipeline |= ZIO_STAGE_CHECKSUM_VERIFY;
1102                 pio->io_pipeline &= ~ZIO_STAGE_CHECKSUM_VERIFY;
1103         }
1104
1105         /* Not all IO types require vdev io done stage e.g. free */
1106         if (!(pio->io_pipeline & ZIO_STAGE_VDEV_IO_DONE))
1107                 pipeline &= ~ZIO_STAGE_VDEV_IO_DONE;
1108
1109         if (vd->vdev_children == 0)
1110                 offset += VDEV_LABEL_START_SIZE;
1111
1112         flags |= ZIO_VDEV_CHILD_FLAGS(pio) | ZIO_FLAG_DONT_PROPAGATE;
1113
1114         /*
1115          * If we've decided to do a repair, the write is not speculative --
1116          * even if the original read was.
1117          */
1118         if (flags & ZIO_FLAG_IO_REPAIR)
1119                 flags &= ~ZIO_FLAG_SPECULATIVE;
1120
1121         /*
1122          * If we're creating a child I/O that is not associated with a
1123          * top-level vdev, then the child zio is not an allocating I/O.
1124          * If this is a retried I/O then we ignore it since we will
1125          * have already processed the original allocating I/O.
1126          */
1127         if (flags & ZIO_FLAG_IO_ALLOCATING &&
1128             (vd != vd->vdev_top || (flags & ZIO_FLAG_IO_RETRY))) {
1129                 metaslab_class_t *mc = spa_normal_class(pio->io_spa);
1130
1131                 ASSERT(mc->mc_alloc_throttle_enabled);
1132                 ASSERT(type == ZIO_TYPE_WRITE);
1133                 ASSERT(priority == ZIO_PRIORITY_ASYNC_WRITE);
1134                 ASSERT(!(flags & ZIO_FLAG_IO_REPAIR));
1135                 ASSERT(!(pio->io_flags & ZIO_FLAG_IO_REWRITE) ||
1136                     pio->io_child_type == ZIO_CHILD_GANG);
1137
1138                 flags &= ~ZIO_FLAG_IO_ALLOCATING;
1139         }
1140
1141         zio = zio_create(pio, pio->io_spa, pio->io_txg, bp, data, size, size,
1142             done, private, type, priority, flags, vd, offset, &pio->io_bookmark,
1143             ZIO_STAGE_VDEV_IO_START >> 1, pipeline);
1144         ASSERT3U(zio->io_child_type, ==, ZIO_CHILD_VDEV);
1145
1146         zio->io_physdone = pio->io_physdone;
1147         if (vd->vdev_ops->vdev_op_leaf && zio->io_logical != NULL)
1148                 zio->io_logical->io_phys_children++;
1149
1150         return (zio);
1151 }
1152
1153 zio_t *
1154 zio_vdev_delegated_io(vdev_t *vd, uint64_t offset, void *data, uint64_t size,
1155     int type, zio_priority_t priority, enum zio_flag flags,
1156     zio_done_func_t *done, void *private)
1157 {
1158         zio_t *zio;
1159
1160         ASSERT(vd->vdev_ops->vdev_op_leaf);
1161
1162         zio = zio_create(NULL, vd->vdev_spa, 0, NULL,
1163             data, size, size, done, private, type, priority,
1164             flags | ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_RETRY | ZIO_FLAG_DELEGATED,
1165             vd, offset, NULL,
1166             ZIO_STAGE_VDEV_IO_START >> 1, ZIO_VDEV_CHILD_PIPELINE);
1167
1168         return (zio);
1169 }
1170
1171 void
1172 zio_flush(zio_t *zio, vdev_t *vd)
1173 {
1174         zio_nowait(zio_ioctl(zio, zio->io_spa, vd, DKIOCFLUSHWRITECACHE, 0, 0,
1175             NULL, NULL, ZIO_PRIORITY_NOW,
1176             ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY));
1177 }
1178
1179 zio_t *
1180 zio_trim(zio_t *zio, spa_t *spa, vdev_t *vd, uint64_t offset, uint64_t size)
1181 {
1182
1183         ASSERT(vd->vdev_ops->vdev_op_leaf);
1184
1185         return (zio_create(zio, spa, 0, NULL, NULL, size, size, NULL, NULL,
1186             ZIO_TYPE_FREE, ZIO_PRIORITY_TRIM, ZIO_FLAG_DONT_AGGREGATE |
1187             ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY,
1188             vd, offset, NULL, ZIO_STAGE_OPEN, ZIO_FREE_PHYS_PIPELINE));
1189 }
1190
1191 void
1192 zio_shrink(zio_t *zio, uint64_t size)
1193 {
1194         ASSERT(zio->io_executor == NULL);
1195         ASSERT(zio->io_orig_size == zio->io_size);
1196         ASSERT(size <= zio->io_size);
1197
1198         /*
1199          * We don't shrink for raidz because of problems with the
1200          * reconstruction when reading back less than the block size.
1201          * Note, BP_IS_RAIDZ() assumes no compression.
1202          */
1203         ASSERT(BP_GET_COMPRESS(zio->io_bp) == ZIO_COMPRESS_OFF);
1204         if (!BP_IS_RAIDZ(zio->io_bp)) {
1205                 /* we are not doing a raw write */
1206                 ASSERT3U(zio->io_size, ==, zio->io_lsize);
1207                 zio->io_orig_size = zio->io_size = zio->io_lsize = size;
1208         }
1209 }
1210
1211 /*
1212  * ==========================================================================
1213  * Prepare to read and write logical blocks
1214  * ==========================================================================
1215  */
1216
1217 static int
1218 zio_read_bp_init(zio_t *zio)
1219 {
1220         blkptr_t *bp = zio->io_bp;
1221
1222         if (BP_GET_COMPRESS(bp) != ZIO_COMPRESS_OFF &&
1223             zio->io_child_type == ZIO_CHILD_LOGICAL &&
1224             !(zio->io_flags & ZIO_FLAG_RAW)) {
1225                 uint64_t psize =
1226                     BP_IS_EMBEDDED(bp) ? BPE_GET_PSIZE(bp) : BP_GET_PSIZE(bp);
1227                 void *cbuf = zio_buf_alloc(psize);
1228
1229                 zio_push_transform(zio, cbuf, psize, psize, zio_decompress);
1230         }
1231
1232         if (BP_IS_EMBEDDED(bp) && BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA) {
1233                 zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1234                 decode_embedded_bp_compressed(bp, zio->io_data);
1235         } else {
1236                 ASSERT(!BP_IS_EMBEDDED(bp));
1237         }
1238
1239         if (!DMU_OT_IS_METADATA(BP_GET_TYPE(bp)) && BP_GET_LEVEL(bp) == 0)
1240                 zio->io_flags |= ZIO_FLAG_DONT_CACHE;
1241
1242         if (BP_GET_TYPE(bp) == DMU_OT_DDT_ZAP)
1243                 zio->io_flags |= ZIO_FLAG_DONT_CACHE;
1244
1245         if (BP_GET_DEDUP(bp) && zio->io_child_type == ZIO_CHILD_LOGICAL)
1246                 zio->io_pipeline = ZIO_DDT_READ_PIPELINE;
1247
1248         return (ZIO_PIPELINE_CONTINUE);
1249 }
1250
1251 static int
1252 zio_write_bp_init(zio_t *zio)
1253 {
1254         if (!IO_IS_ALLOCATING(zio))
1255                 return (ZIO_PIPELINE_CONTINUE);
1256
1257         ASSERT(zio->io_child_type != ZIO_CHILD_DDT);
1258
1259         if (zio->io_bp_override) {
1260                 blkptr_t *bp = zio->io_bp;
1261                 zio_prop_t *zp = &zio->io_prop;
1262
1263                 ASSERT(bp->blk_birth != zio->io_txg);
1264                 ASSERT(BP_GET_DEDUP(zio->io_bp_override) == 0);
1265
1266                 *bp = *zio->io_bp_override;
1267                 zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1268
1269                 if (BP_IS_EMBEDDED(bp))
1270                         return (ZIO_PIPELINE_CONTINUE);
1271
1272                 /*
1273                  * If we've been overridden and nopwrite is set then
1274                  * set the flag accordingly to indicate that a nopwrite
1275                  * has already occurred.
1276                  */
1277                 if (!BP_IS_HOLE(bp) && zp->zp_nopwrite) {
1278                         ASSERT(!zp->zp_dedup);
1279                         ASSERT3U(BP_GET_CHECKSUM(bp), ==, zp->zp_checksum);
1280                         zio->io_flags |= ZIO_FLAG_NOPWRITE;
1281                         return (ZIO_PIPELINE_CONTINUE);
1282                 }
1283
1284                 ASSERT(!zp->zp_nopwrite);
1285
1286                 if (BP_IS_HOLE(bp) || !zp->zp_dedup)
1287                         return (ZIO_PIPELINE_CONTINUE);
1288
1289                 ASSERT((zio_checksum_table[zp->zp_checksum].ci_flags &
1290                     ZCHECKSUM_FLAG_DEDUP) || zp->zp_dedup_verify);
1291
1292                 if (BP_GET_CHECKSUM(bp) == zp->zp_checksum) {
1293                         BP_SET_DEDUP(bp, 1);
1294                         zio->io_pipeline |= ZIO_STAGE_DDT_WRITE;
1295                         return (ZIO_PIPELINE_CONTINUE);
1296                 }
1297
1298                 /*
1299                  * We were unable to handle this as an override bp, treat
1300                  * it as a regular write I/O.
1301                  */
1302                 zio->io_bp_override = NULL;
1303                 *bp = zio->io_bp_orig;
1304                 zio->io_pipeline = zio->io_orig_pipeline;
1305         }
1306
1307         return (ZIO_PIPELINE_CONTINUE);
1308 }
1309
1310 static int
1311 zio_write_compress(zio_t *zio)
1312 {
1313         spa_t *spa = zio->io_spa;
1314         zio_prop_t *zp = &zio->io_prop;
1315         enum zio_compress compress = zp->zp_compress;
1316         blkptr_t *bp = zio->io_bp;
1317         uint64_t lsize = zio->io_lsize;
1318         uint64_t psize = zio->io_size;
1319         int pass = 1;
1320
1321         EQUIV(lsize != psize, (zio->io_flags & ZIO_FLAG_RAW) != 0);
1322
1323         /*
1324          * If our children haven't all reached the ready stage,
1325          * wait for them and then repeat this pipeline stage.
1326          */
1327         if (zio_wait_for_children(zio, ZIO_CHILD_GANG, ZIO_WAIT_READY) ||
1328             zio_wait_for_children(zio, ZIO_CHILD_LOGICAL, ZIO_WAIT_READY))
1329                 return (ZIO_PIPELINE_STOP);
1330
1331         if (!IO_IS_ALLOCATING(zio))
1332                 return (ZIO_PIPELINE_CONTINUE);
1333
1334         if (zio->io_children_ready != NULL) {
1335                 /*
1336                  * Now that all our children are ready, run the callback
1337                  * associated with this zio in case it wants to modify the
1338                  * data to be written.
1339                  */
1340                 ASSERT3U(zp->zp_level, >, 0);
1341                 zio->io_children_ready(zio);
1342         }
1343
1344         ASSERT(zio->io_child_type != ZIO_CHILD_DDT);
1345         ASSERT(zio->io_bp_override == NULL);
1346
1347         if (!BP_IS_HOLE(bp) && bp->blk_birth == zio->io_txg) {
1348                 /*
1349                  * We're rewriting an existing block, which means we're
1350                  * working on behalf of spa_sync().  For spa_sync() to
1351                  * converge, it must eventually be the case that we don't
1352                  * have to allocate new blocks.  But compression changes
1353                  * the blocksize, which forces a reallocate, and makes
1354                  * convergence take longer.  Therefore, after the first
1355                  * few passes, stop compressing to ensure convergence.
1356                  */
1357                 pass = spa_sync_pass(spa);
1358
1359                 ASSERT(zio->io_txg == spa_syncing_txg(spa));
1360                 ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1361                 ASSERT(!BP_GET_DEDUP(bp));
1362
1363                 if (pass >= zfs_sync_pass_dont_compress)
1364                         compress = ZIO_COMPRESS_OFF;
1365
1366                 /* Make sure someone doesn't change their mind on overwrites */
1367                 ASSERT(BP_IS_EMBEDDED(bp) || MIN(zp->zp_copies + BP_IS_GANG(bp),
1368                     spa_max_replication(spa)) == BP_GET_NDVAS(bp));
1369         }
1370
1371         /* If it's a compressed write that is not raw, compress the buffer. */
1372         if (compress != ZIO_COMPRESS_OFF && psize == lsize) {
1373                 void *cbuf = zio_buf_alloc(lsize);
1374                 psize = zio_compress_data(compress, zio->io_data, cbuf, lsize);
1375                 if (psize == 0 || psize == lsize) {
1376                         compress = ZIO_COMPRESS_OFF;
1377                         zio_buf_free(cbuf, lsize);
1378                 } else if (!zp->zp_dedup && psize <= BPE_PAYLOAD_SIZE &&
1379                     zp->zp_level == 0 && !DMU_OT_HAS_FILL(zp->zp_type) &&
1380                     spa_feature_is_enabled(spa, SPA_FEATURE_EMBEDDED_DATA)) {
1381                         encode_embedded_bp_compressed(bp,
1382                             cbuf, compress, lsize, psize);
1383                         BPE_SET_ETYPE(bp, BP_EMBEDDED_TYPE_DATA);
1384                         BP_SET_TYPE(bp, zio->io_prop.zp_type);
1385                         BP_SET_LEVEL(bp, zio->io_prop.zp_level);
1386                         zio_buf_free(cbuf, lsize);
1387                         bp->blk_birth = zio->io_txg;
1388                         zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1389                         ASSERT(spa_feature_is_active(spa,
1390                             SPA_FEATURE_EMBEDDED_DATA));
1391                         return (ZIO_PIPELINE_CONTINUE);
1392                 } else {
1393                         /*
1394                          * Round up compressed size up to the ashift
1395                          * of the smallest-ashift device, and zero the tail.
1396                          * This ensures that the compressed size of the BP
1397                          * (and thus compressratio property) are correct,
1398                          * in that we charge for the padding used to fill out
1399                          * the last sector.
1400                          */
1401                         ASSERT3U(spa->spa_min_ashift, >=, SPA_MINBLOCKSHIFT);
1402                         size_t rounded = (size_t)P2ROUNDUP(psize,
1403                             1ULL << spa->spa_min_ashift);
1404                         if (rounded >= lsize) {
1405                                 compress = ZIO_COMPRESS_OFF;
1406                                 zio_buf_free(cbuf, lsize);
1407                                 psize = lsize;
1408                         } else {
1409                                 bzero((char *)cbuf + psize, rounded - psize);
1410                                 psize = rounded;
1411                                 zio_push_transform(zio, cbuf,
1412                                     psize, lsize, NULL);
1413                         }
1414                 }
1415
1416                 /*
1417                  * We were unable to handle this as an override bp, treat
1418                  * it as a regular write I/O.
1419                  */
1420                 zio->io_bp_override = NULL;
1421                 *bp = zio->io_bp_orig;
1422                 zio->io_pipeline = zio->io_orig_pipeline;
1423         } else {
1424                 ASSERT3U(psize, !=, 0);
1425         }
1426
1427         /*
1428          * The final pass of spa_sync() must be all rewrites, but the first
1429          * few passes offer a trade-off: allocating blocks defers convergence,
1430          * but newly allocated blocks are sequential, so they can be written
1431          * to disk faster.  Therefore, we allow the first few passes of
1432          * spa_sync() to allocate new blocks, but force rewrites after that.
1433          * There should only be a handful of blocks after pass 1 in any case.
1434          */
1435         if (!BP_IS_HOLE(bp) && bp->blk_birth == zio->io_txg &&
1436             BP_GET_PSIZE(bp) == psize &&
1437             pass >= zfs_sync_pass_rewrite) {
1438                 ASSERT(psize != 0);
1439                 enum zio_stage gang_stages = zio->io_pipeline & ZIO_GANG_STAGES;
1440                 zio->io_pipeline = ZIO_REWRITE_PIPELINE | gang_stages;
1441                 zio->io_flags |= ZIO_FLAG_IO_REWRITE;
1442         } else {
1443                 BP_ZERO(bp);
1444                 zio->io_pipeline = ZIO_WRITE_PIPELINE;
1445         }
1446
1447         if (psize == 0) {
1448                 if (zio->io_bp_orig.blk_birth != 0 &&
1449                     spa_feature_is_active(spa, SPA_FEATURE_HOLE_BIRTH)) {
1450                         BP_SET_LSIZE(bp, lsize);
1451                         BP_SET_TYPE(bp, zp->zp_type);
1452                         BP_SET_LEVEL(bp, zp->zp_level);
1453                         BP_SET_BIRTH(bp, zio->io_txg, 0);
1454                 }
1455                 zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1456         } else {
1457                 ASSERT(zp->zp_checksum != ZIO_CHECKSUM_GANG_HEADER);
1458                 BP_SET_LSIZE(bp, lsize);
1459                 BP_SET_TYPE(bp, zp->zp_type);
1460                 BP_SET_LEVEL(bp, zp->zp_level);
1461                 BP_SET_PSIZE(bp, psize);
1462                 BP_SET_COMPRESS(bp, compress);
1463                 BP_SET_CHECKSUM(bp, zp->zp_checksum);
1464                 BP_SET_DEDUP(bp, zp->zp_dedup);
1465                 BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
1466                 if (zp->zp_dedup) {
1467                         ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1468                         ASSERT(!(zio->io_flags & ZIO_FLAG_IO_REWRITE));
1469                         zio->io_pipeline = ZIO_DDT_WRITE_PIPELINE;
1470                 }
1471                 if (zp->zp_nopwrite) {
1472                         ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1473                         ASSERT(!(zio->io_flags & ZIO_FLAG_IO_REWRITE));
1474                         zio->io_pipeline |= ZIO_STAGE_NOP_WRITE;
1475                 }
1476         }
1477         return (ZIO_PIPELINE_CONTINUE);
1478 }
1479
1480 static int
1481 zio_free_bp_init(zio_t *zio)
1482 {
1483         blkptr_t *bp = zio->io_bp;
1484
1485         if (zio->io_child_type == ZIO_CHILD_LOGICAL) {
1486                 if (BP_GET_DEDUP(bp))
1487                         zio->io_pipeline = ZIO_DDT_FREE_PIPELINE;
1488         }
1489
1490         return (ZIO_PIPELINE_CONTINUE);
1491 }
1492
1493 /*
1494  * ==========================================================================
1495  * Execute the I/O pipeline
1496  * ==========================================================================
1497  */
1498
1499 static void
1500 zio_taskq_dispatch(zio_t *zio, zio_taskq_type_t q, boolean_t cutinline)
1501 {
1502         spa_t *spa = zio->io_spa;
1503         zio_type_t t = zio->io_type;
1504         int flags = (cutinline ? TQ_FRONT : 0);
1505
1506         ASSERT(q == ZIO_TASKQ_ISSUE || q == ZIO_TASKQ_INTERRUPT);
1507
1508         /*
1509          * If we're a config writer or a probe, the normal issue and
1510          * interrupt threads may all be blocked waiting for the config lock.
1511          * In this case, select the otherwise-unused taskq for ZIO_TYPE_NULL.
1512          */
1513         if (zio->io_flags & (ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_PROBE))
1514                 t = ZIO_TYPE_NULL;
1515
1516         /*
1517          * A similar issue exists for the L2ARC write thread until L2ARC 2.0.
1518          */
1519         if (t == ZIO_TYPE_WRITE && zio->io_vd && zio->io_vd->vdev_aux)
1520                 t = ZIO_TYPE_NULL;
1521
1522         /*
1523          * If this is a high priority I/O, then use the high priority taskq if
1524          * available.
1525          */
1526         if (zio->io_priority == ZIO_PRIORITY_NOW &&
1527             spa->spa_zio_taskq[t][q + 1].stqs_count != 0)
1528                 q++;
1529
1530         ASSERT3U(q, <, ZIO_TASKQ_TYPES);
1531
1532         /*
1533          * NB: We are assuming that the zio can only be dispatched
1534          * to a single taskq at a time.  It would be a grievous error
1535          * to dispatch the zio to another taskq at the same time.
1536          */
1537 #if defined(illumos) || !defined(_KERNEL)
1538         ASSERT(zio->io_tqent.tqent_next == NULL);
1539 #else
1540         ASSERT(zio->io_tqent.tqent_task.ta_pending == 0);
1541 #endif
1542         spa_taskq_dispatch_ent(spa, t, q, (task_func_t *)zio_execute, zio,
1543             flags, &zio->io_tqent);
1544 }
1545
1546 static boolean_t
1547 zio_taskq_member(zio_t *zio, zio_taskq_type_t q)
1548 {
1549         kthread_t *executor = zio->io_executor;
1550         spa_t *spa = zio->io_spa;
1551
1552         for (zio_type_t t = 0; t < ZIO_TYPES; t++) {
1553                 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1554                 uint_t i;
1555                 for (i = 0; i < tqs->stqs_count; i++) {
1556                         if (taskq_member(tqs->stqs_taskq[i], executor))
1557                                 return (B_TRUE);
1558                 }
1559         }
1560
1561         return (B_FALSE);
1562 }
1563
1564 static int
1565 zio_issue_async(zio_t *zio)
1566 {
1567         zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE, B_FALSE);
1568
1569         return (ZIO_PIPELINE_STOP);
1570 }
1571
1572 void
1573 zio_interrupt(zio_t *zio)
1574 {
1575         zio_taskq_dispatch(zio, ZIO_TASKQ_INTERRUPT, B_FALSE);
1576 }
1577
1578 void
1579 zio_delay_interrupt(zio_t *zio)
1580 {
1581         /*
1582          * The timeout_generic() function isn't defined in userspace, so
1583          * rather than trying to implement the function, the zio delay
1584          * functionality has been disabled for userspace builds.
1585          */
1586
1587 #ifdef _KERNEL
1588         /*
1589          * If io_target_timestamp is zero, then no delay has been registered
1590          * for this IO, thus jump to the end of this function and "skip" the
1591          * delay; issuing it directly to the zio layer.
1592          */
1593         if (zio->io_target_timestamp != 0) {
1594                 hrtime_t now = gethrtime();
1595
1596                 if (now >= zio->io_target_timestamp) {
1597                         /*
1598                          * This IO has already taken longer than the target
1599                          * delay to complete, so we don't want to delay it
1600                          * any longer; we "miss" the delay and issue it
1601                          * directly to the zio layer. This is likely due to
1602                          * the target latency being set to a value less than
1603                          * the underlying hardware can satisfy (e.g. delay
1604                          * set to 1ms, but the disks take 10ms to complete an
1605                          * IO request).
1606                          */
1607
1608                         DTRACE_PROBE2(zio__delay__miss, zio_t *, zio,
1609                             hrtime_t, now);
1610
1611                         zio_interrupt(zio);
1612                 } else {
1613                         hrtime_t diff = zio->io_target_timestamp - now;
1614
1615                         DTRACE_PROBE3(zio__delay__hit, zio_t *, zio,
1616                             hrtime_t, now, hrtime_t, diff);
1617
1618                         (void) timeout_generic(CALLOUT_NORMAL,
1619                             (void (*)(void *))zio_interrupt, zio, diff, 1, 0);
1620                 }
1621
1622                 return;
1623         }
1624 #endif
1625
1626         DTRACE_PROBE1(zio__delay__skip, zio_t *, zio);
1627         zio_interrupt(zio);
1628 }
1629
1630 /*
1631  * Execute the I/O pipeline until one of the following occurs:
1632  *
1633  *      (1) the I/O completes
1634  *      (2) the pipeline stalls waiting for dependent child I/Os
1635  *      (3) the I/O issues, so we're waiting for an I/O completion interrupt
1636  *      (4) the I/O is delegated by vdev-level caching or aggregation
1637  *      (5) the I/O is deferred due to vdev-level queueing
1638  *      (6) the I/O is handed off to another thread.
1639  *
1640  * In all cases, the pipeline stops whenever there's no CPU work; it never
1641  * burns a thread in cv_wait().
1642  *
1643  * There's no locking on io_stage because there's no legitimate way
1644  * for multiple threads to be attempting to process the same I/O.
1645  */
1646 static zio_pipe_stage_t *zio_pipeline[];
1647
1648 void
1649 zio_execute(zio_t *zio)
1650 {
1651         zio->io_executor = curthread;
1652
1653         ASSERT3U(zio->io_queued_timestamp, >, 0);
1654
1655         while (zio->io_stage < ZIO_STAGE_DONE) {
1656                 enum zio_stage pipeline = zio->io_pipeline;
1657                 enum zio_stage stage = zio->io_stage;
1658                 int rv;
1659
1660                 ASSERT(!MUTEX_HELD(&zio->io_lock));
1661                 ASSERT(ISP2(stage));
1662                 ASSERT(zio->io_stall == NULL);
1663
1664                 do {
1665                         stage <<= 1;
1666                 } while ((stage & pipeline) == 0);
1667
1668                 ASSERT(stage <= ZIO_STAGE_DONE);
1669
1670                 /*
1671                  * If we are in interrupt context and this pipeline stage
1672                  * will grab a config lock that is held across I/O,
1673                  * or may wait for an I/O that needs an interrupt thread
1674                  * to complete, issue async to avoid deadlock.
1675                  *
1676                  * For VDEV_IO_START, we cut in line so that the io will
1677                  * be sent to disk promptly.
1678                  */
1679                 if ((stage & ZIO_BLOCKING_STAGES) && zio->io_vd == NULL &&
1680                     zio_taskq_member(zio, ZIO_TASKQ_INTERRUPT)) {
1681                         boolean_t cut = (stage == ZIO_STAGE_VDEV_IO_START) ?
1682                             zio_requeue_io_start_cut_in_line : B_FALSE;
1683                         zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE, cut);
1684                         return;
1685                 }
1686
1687                 zio->io_stage = stage;
1688                 zio->io_pipeline_trace |= zio->io_stage;
1689                 rv = zio_pipeline[highbit64(stage) - 1](zio);
1690
1691                 if (rv == ZIO_PIPELINE_STOP)
1692                         return;
1693
1694                 ASSERT(rv == ZIO_PIPELINE_CONTINUE);
1695         }
1696 }
1697
1698 /*
1699  * ==========================================================================
1700  * Initiate I/O, either sync or async
1701  * ==========================================================================
1702  */
1703 int
1704 zio_wait(zio_t *zio)
1705 {
1706         int error;
1707
1708         ASSERT(zio->io_stage == ZIO_STAGE_OPEN);
1709         ASSERT(zio->io_executor == NULL);
1710
1711         zio->io_waiter = curthread;
1712         ASSERT0(zio->io_queued_timestamp);
1713         zio->io_queued_timestamp = gethrtime();
1714
1715         zio_execute(zio);
1716
1717         mutex_enter(&zio->io_lock);
1718         while (zio->io_executor != NULL)
1719                 cv_wait(&zio->io_cv, &zio->io_lock);
1720         mutex_exit(&zio->io_lock);
1721
1722         error = zio->io_error;
1723         zio_destroy(zio);
1724
1725         return (error);
1726 }
1727
1728 void
1729 zio_nowait(zio_t *zio)
1730 {
1731         ASSERT(zio->io_executor == NULL);
1732
1733         if (zio->io_child_type == ZIO_CHILD_LOGICAL &&
1734             zio_unique_parent(zio) == NULL) {
1735                 /*
1736                  * This is a logical async I/O with no parent to wait for it.
1737                  * We add it to the spa_async_root_zio "Godfather" I/O which
1738                  * will ensure they complete prior to unloading the pool.
1739                  */
1740                 spa_t *spa = zio->io_spa;
1741
1742                 zio_add_child(spa->spa_async_zio_root[CPU_SEQID], zio);
1743         }
1744
1745         ASSERT0(zio->io_queued_timestamp);
1746         zio->io_queued_timestamp = gethrtime();
1747         zio_execute(zio);
1748 }
1749
1750 /*
1751  * ==========================================================================
1752  * Reexecute or suspend/resume failed I/O
1753  * ==========================================================================
1754  */
1755
1756 static void
1757 zio_reexecute(zio_t *pio)
1758 {
1759         zio_t *cio, *cio_next;
1760
1761         ASSERT(pio->io_child_type == ZIO_CHILD_LOGICAL);
1762         ASSERT(pio->io_orig_stage == ZIO_STAGE_OPEN);
1763         ASSERT(pio->io_gang_leader == NULL);
1764         ASSERT(pio->io_gang_tree == NULL);
1765
1766         pio->io_flags = pio->io_orig_flags;
1767         pio->io_stage = pio->io_orig_stage;
1768         pio->io_pipeline = pio->io_orig_pipeline;
1769         pio->io_reexecute = 0;
1770         pio->io_flags |= ZIO_FLAG_REEXECUTED;
1771         pio->io_pipeline_trace = 0;
1772         pio->io_error = 0;
1773         for (int w = 0; w < ZIO_WAIT_TYPES; w++)
1774                 pio->io_state[w] = 0;
1775         for (int c = 0; c < ZIO_CHILD_TYPES; c++)
1776                 pio->io_child_error[c] = 0;
1777
1778         if (IO_IS_ALLOCATING(pio))
1779                 BP_ZERO(pio->io_bp);
1780
1781         /*
1782          * As we reexecute pio's children, new children could be created.
1783          * New children go to the head of pio's io_child_list, however,
1784          * so we will (correctly) not reexecute them.  The key is that
1785          * the remainder of pio's io_child_list, from 'cio_next' onward,
1786          * cannot be affected by any side effects of reexecuting 'cio'.
1787          */
1788         zio_link_t *zl = NULL;
1789         for (cio = zio_walk_children(pio, &zl); cio != NULL; cio = cio_next) {
1790                 cio_next = zio_walk_children(pio, &zl);
1791                 mutex_enter(&pio->io_lock);
1792                 for (int w = 0; w < ZIO_WAIT_TYPES; w++)
1793                         pio->io_children[cio->io_child_type][w]++;
1794                 mutex_exit(&pio->io_lock);
1795                 zio_reexecute(cio);
1796         }
1797
1798         /*
1799          * Now that all children have been reexecuted, execute the parent.
1800          * We don't reexecute "The Godfather" I/O here as it's the
1801          * responsibility of the caller to wait on him.
1802          */
1803         if (!(pio->io_flags & ZIO_FLAG_GODFATHER)) {
1804                 pio->io_queued_timestamp = gethrtime();
1805                 zio_execute(pio);
1806         }
1807 }
1808
1809 void
1810 zio_suspend(spa_t *spa, zio_t *zio)
1811 {
1812         if (spa_get_failmode(spa) == ZIO_FAILURE_MODE_PANIC)
1813                 fm_panic("Pool '%s' has encountered an uncorrectable I/O "
1814                     "failure and the failure mode property for this pool "
1815                     "is set to panic.", spa_name(spa));
1816
1817         zfs_ereport_post(FM_EREPORT_ZFS_IO_FAILURE, spa, NULL, NULL, 0, 0);
1818
1819         mutex_enter(&spa->spa_suspend_lock);
1820
1821         if (spa->spa_suspend_zio_root == NULL)
1822                 spa->spa_suspend_zio_root = zio_root(spa, NULL, NULL,
1823                     ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
1824                     ZIO_FLAG_GODFATHER);
1825
1826         spa->spa_suspended = B_TRUE;
1827
1828         if (zio != NULL) {
1829                 ASSERT(!(zio->io_flags & ZIO_FLAG_GODFATHER));
1830                 ASSERT(zio != spa->spa_suspend_zio_root);
1831                 ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1832                 ASSERT(zio_unique_parent(zio) == NULL);
1833                 ASSERT(zio->io_stage == ZIO_STAGE_DONE);
1834                 zio_add_child(spa->spa_suspend_zio_root, zio);
1835         }
1836
1837         mutex_exit(&spa->spa_suspend_lock);
1838 }
1839
1840 int
1841 zio_resume(spa_t *spa)
1842 {
1843         zio_t *pio;
1844
1845         /*
1846          * Reexecute all previously suspended i/o.
1847          */
1848         mutex_enter(&spa->spa_suspend_lock);
1849         spa->spa_suspended = B_FALSE;
1850         cv_broadcast(&spa->spa_suspend_cv);
1851         pio = spa->spa_suspend_zio_root;
1852         spa->spa_suspend_zio_root = NULL;
1853         mutex_exit(&spa->spa_suspend_lock);
1854
1855         if (pio == NULL)
1856                 return (0);
1857
1858         zio_reexecute(pio);
1859         return (zio_wait(pio));
1860 }
1861
1862 void
1863 zio_resume_wait(spa_t *spa)
1864 {
1865         mutex_enter(&spa->spa_suspend_lock);
1866         while (spa_suspended(spa))
1867                 cv_wait(&spa->spa_suspend_cv, &spa->spa_suspend_lock);
1868         mutex_exit(&spa->spa_suspend_lock);
1869 }
1870
1871 /*
1872  * ==========================================================================
1873  * Gang blocks.
1874  *
1875  * A gang block is a collection of small blocks that looks to the DMU
1876  * like one large block.  When zio_dva_allocate() cannot find a block
1877  * of the requested size, due to either severe fragmentation or the pool
1878  * being nearly full, it calls zio_write_gang_block() to construct the
1879  * block from smaller fragments.
1880  *
1881  * A gang block consists of a gang header (zio_gbh_phys_t) and up to
1882  * three (SPA_GBH_NBLKPTRS) gang members.  The gang header is just like
1883  * an indirect block: it's an array of block pointers.  It consumes
1884  * only one sector and hence is allocatable regardless of fragmentation.
1885  * The gang header's bps point to its gang members, which hold the data.
1886  *
1887  * Gang blocks are self-checksumming, using the bp's <vdev, offset, txg>
1888  * as the verifier to ensure uniqueness of the SHA256 checksum.
1889  * Critically, the gang block bp's blk_cksum is the checksum of the data,
1890  * not the gang header.  This ensures that data block signatures (needed for
1891  * deduplication) are independent of how the block is physically stored.
1892  *
1893  * Gang blocks can be nested: a gang member may itself be a gang block.
1894  * Thus every gang block is a tree in which root and all interior nodes are
1895  * gang headers, and the leaves are normal blocks that contain user data.
1896  * The root of the gang tree is called the gang leader.
1897  *
1898  * To perform any operation (read, rewrite, free, claim) on a gang block,
1899  * zio_gang_assemble() first assembles the gang tree (minus data leaves)
1900  * in the io_gang_tree field of the original logical i/o by recursively
1901  * reading the gang leader and all gang headers below it.  This yields
1902  * an in-core tree containing the contents of every gang header and the
1903  * bps for every constituent of the gang block.
1904  *
1905  * With the gang tree now assembled, zio_gang_issue() just walks the gang tree
1906  * and invokes a callback on each bp.  To free a gang block, zio_gang_issue()
1907  * calls zio_free_gang() -- a trivial wrapper around zio_free() -- for each bp.
1908  * zio_claim_gang() provides a similarly trivial wrapper for zio_claim().
1909  * zio_read_gang() is a wrapper around zio_read() that omits reading gang
1910  * headers, since we already have those in io_gang_tree.  zio_rewrite_gang()
1911  * performs a zio_rewrite() of the data or, for gang headers, a zio_rewrite()
1912  * of the gang header plus zio_checksum_compute() of the data to update the
1913  * gang header's blk_cksum as described above.
1914  *
1915  * The two-phase assemble/issue model solves the problem of partial failure --
1916  * what if you'd freed part of a gang block but then couldn't read the
1917  * gang header for another part?  Assembling the entire gang tree first
1918  * ensures that all the necessary gang header I/O has succeeded before
1919  * starting the actual work of free, claim, or write.  Once the gang tree
1920  * is assembled, free and claim are in-memory operations that cannot fail.
1921  *
1922  * In the event that a gang write fails, zio_dva_unallocate() walks the
1923  * gang tree to immediately free (i.e. insert back into the space map)
1924  * everything we've allocated.  This ensures that we don't get ENOSPC
1925  * errors during repeated suspend/resume cycles due to a flaky device.
1926  *
1927  * Gang rewrites only happen during sync-to-convergence.  If we can't assemble
1928  * the gang tree, we won't modify the block, so we can safely defer the free
1929  * (knowing that the block is still intact).  If we *can* assemble the gang
1930  * tree, then even if some of the rewrites fail, zio_dva_unallocate() will free
1931  * each constituent bp and we can allocate a new block on the next sync pass.
1932  *
1933  * In all cases, the gang tree allows complete recovery from partial failure.
1934  * ==========================================================================
1935  */
1936
1937 static zio_t *
1938 zio_read_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, void *data)
1939 {
1940         if (gn != NULL)
1941                 return (pio);
1942
1943         return (zio_read(pio, pio->io_spa, bp, data, BP_GET_PSIZE(bp),
1944             NULL, NULL, pio->io_priority, ZIO_GANG_CHILD_FLAGS(pio),
1945             &pio->io_bookmark));
1946 }
1947
1948 zio_t *
1949 zio_rewrite_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, void *data)
1950 {
1951         zio_t *zio;
1952
1953         if (gn != NULL) {
1954                 zio = zio_rewrite(pio, pio->io_spa, pio->io_txg, bp,
1955                     gn->gn_gbh, SPA_GANGBLOCKSIZE, NULL, NULL, pio->io_priority,
1956                     ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
1957                 /*
1958                  * As we rewrite each gang header, the pipeline will compute
1959                  * a new gang block header checksum for it; but no one will
1960                  * compute a new data checksum, so we do that here.  The one
1961                  * exception is the gang leader: the pipeline already computed
1962                  * its data checksum because that stage precedes gang assembly.
1963                  * (Presently, nothing actually uses interior data checksums;
1964                  * this is just good hygiene.)
1965                  */
1966                 if (gn != pio->io_gang_leader->io_gang_tree) {
1967                         zio_checksum_compute(zio, BP_GET_CHECKSUM(bp),
1968                             data, BP_GET_PSIZE(bp));
1969                 }
1970                 /*
1971                  * If we are here to damage data for testing purposes,
1972                  * leave the GBH alone so that we can detect the damage.
1973                  */
1974                 if (pio->io_gang_leader->io_flags & ZIO_FLAG_INDUCE_DAMAGE)
1975                         zio->io_pipeline &= ~ZIO_VDEV_IO_STAGES;
1976         } else {
1977                 zio = zio_rewrite(pio, pio->io_spa, pio->io_txg, bp,
1978                     data, BP_GET_PSIZE(bp), NULL, NULL, pio->io_priority,
1979                     ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
1980         }
1981
1982         return (zio);
1983 }
1984
1985 /* ARGSUSED */
1986 zio_t *
1987 zio_free_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, void *data)
1988 {
1989         return (zio_free_sync(pio, pio->io_spa, pio->io_txg, bp,
1990             BP_IS_GANG(bp) ? SPA_GANGBLOCKSIZE : BP_GET_PSIZE(bp),
1991             ZIO_GANG_CHILD_FLAGS(pio)));
1992 }
1993
1994 /* ARGSUSED */
1995 zio_t *
1996 zio_claim_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, void *data)
1997 {
1998         return (zio_claim(pio, pio->io_spa, pio->io_txg, bp,
1999             NULL, NULL, ZIO_GANG_CHILD_FLAGS(pio)));
2000 }
2001
2002 static zio_gang_issue_func_t *zio_gang_issue_func[ZIO_TYPES] = {
2003         NULL,
2004         zio_read_gang,
2005         zio_rewrite_gang,
2006         zio_free_gang,
2007         zio_claim_gang,
2008         NULL
2009 };
2010
2011 static void zio_gang_tree_assemble_done(zio_t *zio);
2012
2013 static zio_gang_node_t *
2014 zio_gang_node_alloc(zio_gang_node_t **gnpp)
2015 {
2016         zio_gang_node_t *gn;
2017
2018         ASSERT(*gnpp == NULL);
2019
2020         gn = kmem_zalloc(sizeof (*gn), KM_SLEEP);
2021         gn->gn_gbh = zio_buf_alloc(SPA_GANGBLOCKSIZE);
2022         *gnpp = gn;
2023
2024         return (gn);
2025 }
2026
2027 static void
2028 zio_gang_node_free(zio_gang_node_t **gnpp)
2029 {
2030         zio_gang_node_t *gn = *gnpp;
2031
2032         for (int g = 0; g < SPA_GBH_NBLKPTRS; g++)
2033                 ASSERT(gn->gn_child[g] == NULL);
2034
2035         zio_buf_free(gn->gn_gbh, SPA_GANGBLOCKSIZE);
2036         kmem_free(gn, sizeof (*gn));
2037         *gnpp = NULL;
2038 }
2039
2040 static void
2041 zio_gang_tree_free(zio_gang_node_t **gnpp)
2042 {
2043         zio_gang_node_t *gn = *gnpp;
2044
2045         if (gn == NULL)
2046                 return;
2047
2048         for (int g = 0; g < SPA_GBH_NBLKPTRS; g++)
2049                 zio_gang_tree_free(&gn->gn_child[g]);
2050
2051         zio_gang_node_free(gnpp);
2052 }
2053
2054 static void
2055 zio_gang_tree_assemble(zio_t *gio, blkptr_t *bp, zio_gang_node_t **gnpp)
2056 {
2057         zio_gang_node_t *gn = zio_gang_node_alloc(gnpp);
2058
2059         ASSERT(gio->io_gang_leader == gio);
2060         ASSERT(BP_IS_GANG(bp));
2061
2062         zio_nowait(zio_read(gio, gio->io_spa, bp, gn->gn_gbh,
2063             SPA_GANGBLOCKSIZE, zio_gang_tree_assemble_done, gn,
2064             gio->io_priority, ZIO_GANG_CHILD_FLAGS(gio), &gio->io_bookmark));
2065 }
2066
2067 static void
2068 zio_gang_tree_assemble_done(zio_t *zio)
2069 {
2070         zio_t *gio = zio->io_gang_leader;
2071         zio_gang_node_t *gn = zio->io_private;
2072         blkptr_t *bp = zio->io_bp;
2073
2074         ASSERT(gio == zio_unique_parent(zio));
2075         ASSERT(zio->io_child_count == 0);
2076
2077         if (zio->io_error)
2078                 return;
2079
2080         if (BP_SHOULD_BYTESWAP(bp))
2081                 byteswap_uint64_array(zio->io_data, zio->io_size);
2082
2083         ASSERT(zio->io_data == gn->gn_gbh);
2084         ASSERT(zio->io_size == SPA_GANGBLOCKSIZE);
2085         ASSERT(gn->gn_gbh->zg_tail.zec_magic == ZEC_MAGIC);
2086
2087         for (int g = 0; g < SPA_GBH_NBLKPTRS; g++) {
2088                 blkptr_t *gbp = &gn->gn_gbh->zg_blkptr[g];
2089                 if (!BP_IS_GANG(gbp))
2090                         continue;
2091                 zio_gang_tree_assemble(gio, gbp, &gn->gn_child[g]);
2092         }
2093 }
2094
2095 static void
2096 zio_gang_tree_issue(zio_t *pio, zio_gang_node_t *gn, blkptr_t *bp, void *data)
2097 {
2098         zio_t *gio = pio->io_gang_leader;
2099         zio_t *zio;
2100
2101         ASSERT(BP_IS_GANG(bp) == !!gn);
2102         ASSERT(BP_GET_CHECKSUM(bp) == BP_GET_CHECKSUM(gio->io_bp));
2103         ASSERT(BP_GET_LSIZE(bp) == BP_GET_PSIZE(bp) || gn == gio->io_gang_tree);
2104
2105         /*
2106          * If you're a gang header, your data is in gn->gn_gbh.
2107          * If you're a gang member, your data is in 'data' and gn == NULL.
2108          */
2109         zio = zio_gang_issue_func[gio->io_type](pio, bp, gn, data);
2110
2111         if (gn != NULL) {
2112                 ASSERT(gn->gn_gbh->zg_tail.zec_magic == ZEC_MAGIC);
2113
2114                 for (int g = 0; g < SPA_GBH_NBLKPTRS; g++) {
2115                         blkptr_t *gbp = &gn->gn_gbh->zg_blkptr[g];
2116                         if (BP_IS_HOLE(gbp))
2117                                 continue;
2118                         zio_gang_tree_issue(zio, gn->gn_child[g], gbp, data);
2119                         data = (char *)data + BP_GET_PSIZE(gbp);
2120                 }
2121         }
2122
2123         if (gn == gio->io_gang_tree && gio->io_data != NULL)
2124                 ASSERT3P((char *)gio->io_data + gio->io_size, ==, data);
2125
2126         if (zio != pio)
2127                 zio_nowait(zio);
2128 }
2129
2130 static int
2131 zio_gang_assemble(zio_t *zio)
2132 {
2133         blkptr_t *bp = zio->io_bp;
2134
2135         ASSERT(BP_IS_GANG(bp) && zio->io_gang_leader == NULL);
2136         ASSERT(zio->io_child_type > ZIO_CHILD_GANG);
2137
2138         zio->io_gang_leader = zio;
2139
2140         zio_gang_tree_assemble(zio, bp, &zio->io_gang_tree);
2141
2142         return (ZIO_PIPELINE_CONTINUE);
2143 }
2144
2145 static int
2146 zio_gang_issue(zio_t *zio)
2147 {
2148         blkptr_t *bp = zio->io_bp;
2149
2150         if (zio_wait_for_children(zio, ZIO_CHILD_GANG, ZIO_WAIT_DONE))
2151                 return (ZIO_PIPELINE_STOP);
2152
2153         ASSERT(BP_IS_GANG(bp) && zio->io_gang_leader == zio);
2154         ASSERT(zio->io_child_type > ZIO_CHILD_GANG);
2155
2156         if (zio->io_child_error[ZIO_CHILD_GANG] == 0)
2157                 zio_gang_tree_issue(zio, zio->io_gang_tree, bp, zio->io_data);
2158         else
2159                 zio_gang_tree_free(&zio->io_gang_tree);
2160
2161         zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
2162
2163         return (ZIO_PIPELINE_CONTINUE);
2164 }
2165
2166 static void
2167 zio_write_gang_member_ready(zio_t *zio)
2168 {
2169         zio_t *pio = zio_unique_parent(zio);
2170         zio_t *gio = zio->io_gang_leader;
2171         dva_t *cdva = zio->io_bp->blk_dva;
2172         dva_t *pdva = pio->io_bp->blk_dva;
2173         uint64_t asize;
2174
2175         if (BP_IS_HOLE(zio->io_bp))
2176                 return;
2177
2178         ASSERT(BP_IS_HOLE(&zio->io_bp_orig));
2179
2180         ASSERT(zio->io_child_type == ZIO_CHILD_GANG);
2181         ASSERT3U(zio->io_prop.zp_copies, ==, gio->io_prop.zp_copies);
2182         ASSERT3U(zio->io_prop.zp_copies, <=, BP_GET_NDVAS(zio->io_bp));
2183         ASSERT3U(pio->io_prop.zp_copies, <=, BP_GET_NDVAS(pio->io_bp));
2184         ASSERT3U(BP_GET_NDVAS(zio->io_bp), <=, BP_GET_NDVAS(pio->io_bp));
2185
2186         mutex_enter(&pio->io_lock);
2187         for (int d = 0; d < BP_GET_NDVAS(zio->io_bp); d++) {
2188                 ASSERT(DVA_GET_GANG(&pdva[d]));
2189                 asize = DVA_GET_ASIZE(&pdva[d]);
2190                 asize += DVA_GET_ASIZE(&cdva[d]);
2191                 DVA_SET_ASIZE(&pdva[d], asize);
2192         }
2193         mutex_exit(&pio->io_lock);
2194 }
2195
2196 static int
2197 zio_write_gang_block(zio_t *pio)
2198 {
2199         spa_t *spa = pio->io_spa;
2200         metaslab_class_t *mc = spa_normal_class(spa);
2201         blkptr_t *bp = pio->io_bp;
2202         zio_t *gio = pio->io_gang_leader;
2203         zio_t *zio;
2204         zio_gang_node_t *gn, **gnpp;
2205         zio_gbh_phys_t *gbh;
2206         uint64_t txg = pio->io_txg;
2207         uint64_t resid = pio->io_size;
2208         uint64_t lsize;
2209         int copies = gio->io_prop.zp_copies;
2210         int gbh_copies = MIN(copies + 1, spa_max_replication(spa));
2211         zio_prop_t zp;
2212         int error;
2213
2214         int flags = METASLAB_HINTBP_FAVOR | METASLAB_GANG_HEADER;
2215         if (pio->io_flags & ZIO_FLAG_IO_ALLOCATING) {
2216                 ASSERT(pio->io_priority == ZIO_PRIORITY_ASYNC_WRITE);
2217                 ASSERT(!(pio->io_flags & ZIO_FLAG_NODATA));
2218
2219                 flags |= METASLAB_ASYNC_ALLOC;
2220                 VERIFY(refcount_held(&mc->mc_alloc_slots, pio));
2221
2222                 /*
2223                  * The logical zio has already placed a reservation for
2224                  * 'copies' allocation slots but gang blocks may require
2225                  * additional copies. These additional copies
2226                  * (i.e. gbh_copies - copies) are guaranteed to succeed
2227                  * since metaslab_class_throttle_reserve() always allows
2228                  * additional reservations for gang blocks.
2229                  */
2230                 VERIFY(metaslab_class_throttle_reserve(mc, gbh_copies - copies,
2231                     pio, flags));
2232         }
2233
2234         error = metaslab_alloc(spa, mc, SPA_GANGBLOCKSIZE,
2235             bp, gbh_copies, txg, pio == gio ? NULL : gio->io_bp, flags,
2236             &pio->io_alloc_list, pio);
2237         if (error) {
2238                 if (pio->io_flags & ZIO_FLAG_IO_ALLOCATING) {
2239                         ASSERT(pio->io_priority == ZIO_PRIORITY_ASYNC_WRITE);
2240                         ASSERT(!(pio->io_flags & ZIO_FLAG_NODATA));
2241
2242                         /*
2243                          * If we failed to allocate the gang block header then
2244                          * we remove any additional allocation reservations that
2245                          * we placed here. The original reservation will
2246                          * be removed when the logical I/O goes to the ready
2247                          * stage.
2248                          */
2249                         metaslab_class_throttle_unreserve(mc,
2250                             gbh_copies - copies, pio);
2251                 }
2252                 pio->io_error = error;
2253                 return (ZIO_PIPELINE_CONTINUE);
2254         }
2255
2256         if (pio == gio) {
2257                 gnpp = &gio->io_gang_tree;
2258         } else {
2259                 gnpp = pio->io_private;
2260                 ASSERT(pio->io_ready == zio_write_gang_member_ready);
2261         }
2262
2263         gn = zio_gang_node_alloc(gnpp);
2264         gbh = gn->gn_gbh;
2265         bzero(gbh, SPA_GANGBLOCKSIZE);
2266
2267         /*
2268          * Create the gang header.
2269          */
2270         zio = zio_rewrite(pio, spa, txg, bp, gbh, SPA_GANGBLOCKSIZE, NULL, NULL,
2271             pio->io_priority, ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
2272
2273         /*
2274          * Create and nowait the gang children.
2275          */
2276         for (int g = 0; resid != 0; resid -= lsize, g++) {
2277                 lsize = P2ROUNDUP(resid / (SPA_GBH_NBLKPTRS - g),
2278                     SPA_MINBLOCKSIZE);
2279                 ASSERT(lsize >= SPA_MINBLOCKSIZE && lsize <= resid);
2280
2281                 zp.zp_checksum = gio->io_prop.zp_checksum;
2282                 zp.zp_compress = ZIO_COMPRESS_OFF;
2283                 zp.zp_type = DMU_OT_NONE;
2284                 zp.zp_level = 0;
2285                 zp.zp_copies = gio->io_prop.zp_copies;
2286                 zp.zp_dedup = B_FALSE;
2287                 zp.zp_dedup_verify = B_FALSE;
2288                 zp.zp_nopwrite = B_FALSE;
2289
2290                 zio_t *cio = zio_write(zio, spa, txg, &gbh->zg_blkptr[g],
2291                     (char *)pio->io_data + (pio->io_size - resid), lsize, lsize,
2292                     &zp, zio_write_gang_member_ready, NULL, NULL, NULL,
2293                     &gn->gn_child[g], pio->io_priority,
2294                     ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
2295
2296                 if (pio->io_flags & ZIO_FLAG_IO_ALLOCATING) {
2297                         ASSERT(pio->io_priority == ZIO_PRIORITY_ASYNC_WRITE);
2298                         ASSERT(!(pio->io_flags & ZIO_FLAG_NODATA));
2299
2300                         /*
2301                          * Gang children won't throttle but we should
2302                          * account for their work, so reserve an allocation
2303                          * slot for them here.
2304                          */
2305                         VERIFY(metaslab_class_throttle_reserve(mc,
2306                             zp.zp_copies, cio, flags));
2307                 }
2308                 zio_nowait(cio);
2309         }
2310
2311         /*
2312          * Set pio's pipeline to just wait for zio to finish.
2313          */
2314         pio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
2315
2316         zio_nowait(zio);
2317
2318         return (ZIO_PIPELINE_CONTINUE);
2319 }
2320
2321 /*
2322  * The zio_nop_write stage in the pipeline determines if allocating a
2323  * new bp is necessary.  The nopwrite feature can handle writes in
2324  * either syncing or open context (i.e. zil writes) and as a result is
2325  * mutually exclusive with dedup.
2326  *
2327  * By leveraging a cryptographically secure checksum, such as SHA256, we
2328  * can compare the checksums of the new data and the old to determine if
2329  * allocating a new block is required.  Note that our requirements for
2330  * cryptographic strength are fairly weak: there can't be any accidental
2331  * hash collisions, but we don't need to be secure against intentional
2332  * (malicious) collisions.  To trigger a nopwrite, you have to be able
2333  * to write the file to begin with, and triggering an incorrect (hash
2334  * collision) nopwrite is no worse than simply writing to the file.
2335  * That said, there are no known attacks against the checksum algorithms
2336  * used for nopwrite, assuming that the salt and the checksums
2337  * themselves remain secret.
2338  */
2339 static int
2340 zio_nop_write(zio_t *zio)
2341 {
2342         blkptr_t *bp = zio->io_bp;
2343         blkptr_t *bp_orig = &zio->io_bp_orig;
2344         zio_prop_t *zp = &zio->io_prop;
2345
2346         ASSERT(BP_GET_LEVEL(bp) == 0);
2347         ASSERT(!(zio->io_flags & ZIO_FLAG_IO_REWRITE));
2348         ASSERT(zp->zp_nopwrite);
2349         ASSERT(!zp->zp_dedup);
2350         ASSERT(zio->io_bp_override == NULL);
2351         ASSERT(IO_IS_ALLOCATING(zio));
2352
2353         /*
2354          * Check to see if the original bp and the new bp have matching
2355          * characteristics (i.e. same checksum, compression algorithms, etc).
2356          * If they don't then just continue with the pipeline which will
2357          * allocate a new bp.
2358          */
2359         if (BP_IS_HOLE(bp_orig) ||
2360             !(zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_flags &
2361             ZCHECKSUM_FLAG_NOPWRITE) ||
2362             BP_GET_CHECKSUM(bp) != BP_GET_CHECKSUM(bp_orig) ||
2363             BP_GET_COMPRESS(bp) != BP_GET_COMPRESS(bp_orig) ||
2364             BP_GET_DEDUP(bp) != BP_GET_DEDUP(bp_orig) ||
2365             zp->zp_copies != BP_GET_NDVAS(bp_orig))
2366                 return (ZIO_PIPELINE_CONTINUE);
2367
2368         /*
2369          * If the checksums match then reset the pipeline so that we
2370          * avoid allocating a new bp and issuing any I/O.
2371          */
2372         if (ZIO_CHECKSUM_EQUAL(bp->blk_cksum, bp_orig->blk_cksum)) {
2373                 ASSERT(zio_checksum_table[zp->zp_checksum].ci_flags &
2374                     ZCHECKSUM_FLAG_NOPWRITE);
2375                 ASSERT3U(BP_GET_PSIZE(bp), ==, BP_GET_PSIZE(bp_orig));
2376                 ASSERT3U(BP_GET_LSIZE(bp), ==, BP_GET_LSIZE(bp_orig));
2377                 ASSERT(zp->zp_compress != ZIO_COMPRESS_OFF);
2378                 ASSERT(bcmp(&bp->blk_prop, &bp_orig->blk_prop,
2379                     sizeof (uint64_t)) == 0);
2380
2381                 *bp = *bp_orig;
2382                 zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
2383                 zio->io_flags |= ZIO_FLAG_NOPWRITE;
2384         }
2385
2386         return (ZIO_PIPELINE_CONTINUE);
2387 }
2388
2389 /*
2390  * ==========================================================================
2391  * Dedup
2392  * ==========================================================================
2393  */
2394 static void
2395 zio_ddt_child_read_done(zio_t *zio)
2396 {
2397         blkptr_t *bp = zio->io_bp;
2398         ddt_entry_t *dde = zio->io_private;
2399         ddt_phys_t *ddp;
2400         zio_t *pio = zio_unique_parent(zio);
2401
2402         mutex_enter(&pio->io_lock);
2403         ddp = ddt_phys_select(dde, bp);
2404         if (zio->io_error == 0)
2405                 ddt_phys_clear(ddp);    /* this ddp doesn't need repair */
2406         if (zio->io_error == 0 && dde->dde_repair_data == NULL)
2407                 dde->dde_repair_data = zio->io_data;
2408         else
2409                 zio_buf_free(zio->io_data, zio->io_size);
2410         mutex_exit(&pio->io_lock);
2411 }
2412
2413 static int
2414 zio_ddt_read_start(zio_t *zio)
2415 {
2416         blkptr_t *bp = zio->io_bp;
2417
2418         ASSERT(BP_GET_DEDUP(bp));
2419         ASSERT(BP_GET_PSIZE(bp) == zio->io_size);
2420         ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
2421
2422         if (zio->io_child_error[ZIO_CHILD_DDT]) {
2423                 ddt_t *ddt = ddt_select(zio->io_spa, bp);
2424                 ddt_entry_t *dde = ddt_repair_start(ddt, bp);
2425                 ddt_phys_t *ddp = dde->dde_phys;
2426                 ddt_phys_t *ddp_self = ddt_phys_select(dde, bp);
2427                 blkptr_t blk;
2428
2429                 ASSERT(zio->io_vsd == NULL);
2430                 zio->io_vsd = dde;
2431
2432                 if (ddp_self == NULL)
2433                         return (ZIO_PIPELINE_CONTINUE);
2434
2435                 for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
2436                         if (ddp->ddp_phys_birth == 0 || ddp == ddp_self)
2437                                 continue;
2438                         ddt_bp_create(ddt->ddt_checksum, &dde->dde_key, ddp,
2439                             &blk);
2440                         zio_nowait(zio_read(zio, zio->io_spa, &blk,
2441                             zio_buf_alloc(zio->io_size), zio->io_size,
2442                             zio_ddt_child_read_done, dde, zio->io_priority,
2443                             ZIO_DDT_CHILD_FLAGS(zio) | ZIO_FLAG_DONT_PROPAGATE,
2444                             &zio->io_bookmark));
2445                 }
2446                 return (ZIO_PIPELINE_CONTINUE);
2447         }
2448
2449         zio_nowait(zio_read(zio, zio->io_spa, bp,
2450             zio->io_data, zio->io_size, NULL, NULL, zio->io_priority,
2451             ZIO_DDT_CHILD_FLAGS(zio), &zio->io_bookmark));
2452
2453         return (ZIO_PIPELINE_CONTINUE);
2454 }
2455
2456 static int
2457 zio_ddt_read_done(zio_t *zio)
2458 {
2459         blkptr_t *bp = zio->io_bp;
2460
2461         if (zio_wait_for_children(zio, ZIO_CHILD_DDT, ZIO_WAIT_DONE))
2462                 return (ZIO_PIPELINE_STOP);
2463
2464         ASSERT(BP_GET_DEDUP(bp));
2465         ASSERT(BP_GET_PSIZE(bp) == zio->io_size);
2466         ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
2467
2468         if (zio->io_child_error[ZIO_CHILD_DDT]) {
2469                 ddt_t *ddt = ddt_select(zio->io_spa, bp);
2470                 ddt_entry_t *dde = zio->io_vsd;
2471                 if (ddt == NULL) {
2472                         ASSERT(spa_load_state(zio->io_spa) != SPA_LOAD_NONE);
2473                         return (ZIO_PIPELINE_CONTINUE);
2474                 }
2475                 if (dde == NULL) {
2476                         zio->io_stage = ZIO_STAGE_DDT_READ_START >> 1;
2477                         zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE, B_FALSE);
2478                         return (ZIO_PIPELINE_STOP);
2479                 }
2480                 if (dde->dde_repair_data != NULL) {
2481                         bcopy(dde->dde_repair_data, zio->io_data, zio->io_size);
2482                         zio->io_child_error[ZIO_CHILD_DDT] = 0;
2483                 }
2484                 ddt_repair_done(ddt, dde);
2485                 zio->io_vsd = NULL;
2486         }
2487
2488         ASSERT(zio->io_vsd == NULL);
2489
2490         return (ZIO_PIPELINE_CONTINUE);
2491 }
2492
2493 static boolean_t
2494 zio_ddt_collision(zio_t *zio, ddt_t *ddt, ddt_entry_t *dde)
2495 {
2496         spa_t *spa = zio->io_spa;
2497         boolean_t do_raw = (zio->io_flags & ZIO_FLAG_RAW);
2498
2499         /* We should never get a raw, override zio */
2500         ASSERT(!(zio->io_bp_override && do_raw));
2501
2502         /*
2503          * Note: we compare the original data, not the transformed data,
2504          * because when zio->io_bp is an override bp, we will not have
2505          * pushed the I/O transforms.  That's an important optimization
2506          * because otherwise we'd compress/encrypt all dmu_sync() data twice.
2507          */
2508         for (int p = DDT_PHYS_SINGLE; p <= DDT_PHYS_TRIPLE; p++) {
2509                 zio_t *lio = dde->dde_lead_zio[p];
2510
2511                 if (lio != NULL) {
2512                         return (lio->io_orig_size != zio->io_orig_size ||
2513                             bcmp(zio->io_orig_data, lio->io_orig_data,
2514                             zio->io_orig_size) != 0);
2515                 }
2516         }
2517
2518         for (int p = DDT_PHYS_SINGLE; p <= DDT_PHYS_TRIPLE; p++) {
2519                 ddt_phys_t *ddp = &dde->dde_phys[p];
2520
2521                 if (ddp->ddp_phys_birth != 0) {
2522                         arc_buf_t *abuf = NULL;
2523                         arc_flags_t aflags = ARC_FLAG_WAIT;
2524                         int zio_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE;
2525                         blkptr_t blk = *zio->io_bp;
2526                         int error;
2527
2528                         ddt_bp_fill(ddp, &blk, ddp->ddp_phys_birth);
2529
2530                         ddt_exit(ddt);
2531
2532                         /*
2533                          * Intuitively, it would make more sense to compare
2534                          * io_data than io_orig_data in the raw case since you
2535                          * don't want to look at any transformations that have
2536                          * happened to the data. However, for raw I/Os the
2537                          * data will actually be the same in io_data and
2538                          * io_orig_data, so all we have to do is issue this as
2539                          * a raw ARC read.
2540                          */
2541                         if (do_raw) {
2542                                 zio_flags |= ZIO_FLAG_RAW;
2543                                 ASSERT3U(zio->io_size, ==, zio->io_orig_size);
2544                                 ASSERT0(bcmp(zio->io_data, zio->io_orig_data,
2545                                     zio->io_size));
2546                                 ASSERT3P(zio->io_transform_stack, ==, NULL);
2547                         }
2548
2549                         error = arc_read(NULL, spa, &blk,
2550                             arc_getbuf_func, &abuf, ZIO_PRIORITY_SYNC_READ,
2551                             zio_flags, &aflags, &zio->io_bookmark);
2552
2553                         if (error == 0) {
2554                                 if (arc_buf_size(abuf) != zio->io_orig_size ||
2555                                     bcmp(abuf->b_data, zio->io_orig_data,
2556                                     zio->io_orig_size) != 0)
2557                                         error = SET_ERROR(EEXIST);
2558                                 arc_buf_destroy(abuf, &abuf);
2559                         }
2560
2561                         ddt_enter(ddt);
2562                         return (error != 0);
2563                 }
2564         }
2565
2566         return (B_FALSE);
2567 }
2568
2569 static void
2570 zio_ddt_child_write_ready(zio_t *zio)
2571 {
2572         int p = zio->io_prop.zp_copies;
2573         ddt_t *ddt = ddt_select(zio->io_spa, zio->io_bp);
2574         ddt_entry_t *dde = zio->io_private;
2575         ddt_phys_t *ddp = &dde->dde_phys[p];
2576         zio_t *pio;
2577
2578         if (zio->io_error)
2579                 return;
2580
2581         ddt_enter(ddt);
2582
2583         ASSERT(dde->dde_lead_zio[p] == zio);
2584
2585         ddt_phys_fill(ddp, zio->io_bp);
2586
2587         zio_link_t *zl = NULL;
2588         while ((pio = zio_walk_parents(zio, &zl)) != NULL)
2589                 ddt_bp_fill(ddp, pio->io_bp, zio->io_txg);
2590
2591         ddt_exit(ddt);
2592 }
2593
2594 static void
2595 zio_ddt_child_write_done(zio_t *zio)
2596 {
2597         int p = zio->io_prop.zp_copies;
2598         ddt_t *ddt = ddt_select(zio->io_spa, zio->io_bp);
2599         ddt_entry_t *dde = zio->io_private;
2600         ddt_phys_t *ddp = &dde->dde_phys[p];
2601
2602         ddt_enter(ddt);
2603
2604         ASSERT(ddp->ddp_refcnt == 0);
2605         ASSERT(dde->dde_lead_zio[p] == zio);
2606         dde->dde_lead_zio[p] = NULL;
2607
2608         if (zio->io_error == 0) {
2609                 zio_link_t *zl = NULL;
2610                 while (zio_walk_parents(zio, &zl) != NULL)
2611                         ddt_phys_addref(ddp);
2612         } else {
2613                 ddt_phys_clear(ddp);
2614         }
2615
2616         ddt_exit(ddt);
2617 }
2618
2619 static void
2620 zio_ddt_ditto_write_done(zio_t *zio)
2621 {
2622         int p = DDT_PHYS_DITTO;
2623         zio_prop_t *zp = &zio->io_prop;
2624         blkptr_t *bp = zio->io_bp;
2625         ddt_t *ddt = ddt_select(zio->io_spa, bp);
2626         ddt_entry_t *dde = zio->io_private;
2627         ddt_phys_t *ddp = &dde->dde_phys[p];
2628         ddt_key_t *ddk = &dde->dde_key;
2629
2630         ddt_enter(ddt);
2631
2632         ASSERT(ddp->ddp_refcnt == 0);
2633         ASSERT(dde->dde_lead_zio[p] == zio);
2634         dde->dde_lead_zio[p] = NULL;
2635
2636         if (zio->io_error == 0) {
2637                 ASSERT(ZIO_CHECKSUM_EQUAL(bp->blk_cksum, ddk->ddk_cksum));
2638                 ASSERT(zp->zp_copies < SPA_DVAS_PER_BP);
2639                 ASSERT(zp->zp_copies == BP_GET_NDVAS(bp) - BP_IS_GANG(bp));
2640                 if (ddp->ddp_phys_birth != 0)
2641                         ddt_phys_free(ddt, ddk, ddp, zio->io_txg);
2642                 ddt_phys_fill(ddp, bp);
2643         }
2644
2645         ddt_exit(ddt);
2646 }
2647
2648 static int
2649 zio_ddt_write(zio_t *zio)
2650 {
2651         spa_t *spa = zio->io_spa;
2652         blkptr_t *bp = zio->io_bp;
2653         uint64_t txg = zio->io_txg;
2654         zio_prop_t *zp = &zio->io_prop;
2655         int p = zp->zp_copies;
2656         int ditto_copies;
2657         zio_t *cio = NULL;
2658         zio_t *dio = NULL;
2659         ddt_t *ddt = ddt_select(spa, bp);
2660         ddt_entry_t *dde;
2661         ddt_phys_t *ddp;
2662
2663         ASSERT(BP_GET_DEDUP(bp));
2664         ASSERT(BP_GET_CHECKSUM(bp) == zp->zp_checksum);
2665         ASSERT(BP_IS_HOLE(bp) || zio->io_bp_override);
2666         ASSERT(!(zio->io_bp_override && (zio->io_flags & ZIO_FLAG_RAW)));
2667
2668         ddt_enter(ddt);
2669         dde = ddt_lookup(ddt, bp, B_TRUE);
2670         ddp = &dde->dde_phys[p];
2671
2672         if (zp->zp_dedup_verify && zio_ddt_collision(zio, ddt, dde)) {
2673                 /*
2674                  * If we're using a weak checksum, upgrade to a strong checksum
2675                  * and try again.  If we're already using a strong checksum,
2676                  * we can't resolve it, so just convert to an ordinary write.
2677                  * (And automatically e-mail a paper to Nature?)
2678                  */
2679                 if (!(zio_checksum_table[zp->zp_checksum].ci_flags &
2680                     ZCHECKSUM_FLAG_DEDUP)) {
2681                         zp->zp_checksum = spa_dedup_checksum(spa);
2682                         zio_pop_transforms(zio);
2683                         zio->io_stage = ZIO_STAGE_OPEN;
2684                         BP_ZERO(bp);
2685                 } else {
2686                         zp->zp_dedup = B_FALSE;
2687                         BP_SET_DEDUP(bp, B_FALSE);
2688                 }
2689                 ASSERT(!BP_GET_DEDUP(bp));
2690                 zio->io_pipeline = ZIO_WRITE_PIPELINE;
2691                 ddt_exit(ddt);
2692                 return (ZIO_PIPELINE_CONTINUE);
2693         }
2694
2695         ditto_copies = ddt_ditto_copies_needed(ddt, dde, ddp);
2696         ASSERT(ditto_copies < SPA_DVAS_PER_BP);
2697
2698         if (ditto_copies > ddt_ditto_copies_present(dde) &&
2699             dde->dde_lead_zio[DDT_PHYS_DITTO] == NULL) {
2700                 zio_prop_t czp = *zp;
2701
2702                 czp.zp_copies = ditto_copies;
2703
2704                 /*
2705                  * If we arrived here with an override bp, we won't have run
2706                  * the transform stack, so we won't have the data we need to
2707                  * generate a child i/o.  So, toss the override bp and restart.
2708                  * This is safe, because using the override bp is just an
2709                  * optimization; and it's rare, so the cost doesn't matter.
2710                  */
2711                 if (zio->io_bp_override) {
2712                         zio_pop_transforms(zio);
2713                         zio->io_stage = ZIO_STAGE_OPEN;
2714                         zio->io_pipeline = ZIO_WRITE_PIPELINE;
2715                         zio->io_bp_override = NULL;
2716                         BP_ZERO(bp);
2717                         ddt_exit(ddt);
2718                         return (ZIO_PIPELINE_CONTINUE);
2719                 }
2720
2721                 dio = zio_write(zio, spa, txg, bp, zio->io_orig_data,
2722                     zio->io_orig_size, zio->io_orig_size, &czp, NULL, NULL,
2723                     NULL, zio_ddt_ditto_write_done, dde, zio->io_priority,
2724                     ZIO_DDT_CHILD_FLAGS(zio), &zio->io_bookmark);
2725
2726                 zio_push_transform(dio, zio->io_data, zio->io_size, 0, NULL);
2727                 dde->dde_lead_zio[DDT_PHYS_DITTO] = dio;
2728         }
2729
2730         if (ddp->ddp_phys_birth != 0 || dde->dde_lead_zio[p] != NULL) {
2731                 if (ddp->ddp_phys_birth != 0)
2732                         ddt_bp_fill(ddp, bp, txg);
2733                 if (dde->dde_lead_zio[p] != NULL)
2734                         zio_add_child(zio, dde->dde_lead_zio[p]);
2735                 else
2736                         ddt_phys_addref(ddp);
2737         } else if (zio->io_bp_override) {
2738                 ASSERT(bp->blk_birth == txg);
2739                 ASSERT(BP_EQUAL(bp, zio->io_bp_override));
2740                 ddt_phys_fill(ddp, bp);
2741                 ddt_phys_addref(ddp);
2742         } else {
2743                 cio = zio_write(zio, spa, txg, bp, zio->io_orig_data,
2744                     zio->io_orig_size, zio->io_orig_size, zp,
2745                     zio_ddt_child_write_ready, NULL, NULL,
2746                     zio_ddt_child_write_done, dde, zio->io_priority,
2747                     ZIO_DDT_CHILD_FLAGS(zio), &zio->io_bookmark);
2748
2749                 zio_push_transform(cio, zio->io_data, zio->io_size, 0, NULL);
2750                 dde->dde_lead_zio[p] = cio;
2751         }
2752
2753         ddt_exit(ddt);
2754
2755         if (cio)
2756                 zio_nowait(cio);
2757         if (dio)
2758                 zio_nowait(dio);
2759
2760         return (ZIO_PIPELINE_CONTINUE);
2761 }
2762
2763 ddt_entry_t *freedde; /* for debugging */
2764
2765 static int
2766 zio_ddt_free(zio_t *zio)
2767 {
2768         spa_t *spa = zio->io_spa;
2769         blkptr_t *bp = zio->io_bp;
2770         ddt_t *ddt = ddt_select(spa, bp);
2771         ddt_entry_t *dde;
2772         ddt_phys_t *ddp;
2773
2774         ASSERT(BP_GET_DEDUP(bp));
2775         ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
2776
2777         ddt_enter(ddt);
2778         freedde = dde = ddt_lookup(ddt, bp, B_TRUE);
2779         ddp = ddt_phys_select(dde, bp);
2780         ddt_phys_decref(ddp);
2781         ddt_exit(ddt);
2782
2783         return (ZIO_PIPELINE_CONTINUE);
2784 }
2785
2786 /*
2787  * ==========================================================================
2788  * Allocate and free blocks
2789  * ==========================================================================
2790  */
2791
2792 static zio_t *
2793 zio_io_to_allocate(spa_t *spa)
2794 {
2795         zio_t *zio;
2796
2797         ASSERT(MUTEX_HELD(&spa->spa_alloc_lock));
2798
2799         zio = avl_first(&spa->spa_alloc_tree);
2800         if (zio == NULL)
2801                 return (NULL);
2802
2803         ASSERT(IO_IS_ALLOCATING(zio));
2804
2805         /*
2806          * Try to place a reservation for this zio. If we're unable to
2807          * reserve then we throttle.
2808          */
2809         if (!metaslab_class_throttle_reserve(spa_normal_class(spa),
2810             zio->io_prop.zp_copies, zio, 0)) {
2811                 return (NULL);
2812         }
2813
2814         avl_remove(&spa->spa_alloc_tree, zio);
2815         ASSERT3U(zio->io_stage, <, ZIO_STAGE_DVA_ALLOCATE);
2816
2817         return (zio);
2818 }
2819
2820 static int
2821 zio_dva_throttle(zio_t *zio)
2822 {
2823         spa_t *spa = zio->io_spa;
2824         zio_t *nio;
2825
2826         if (zio->io_priority == ZIO_PRIORITY_SYNC_WRITE ||
2827             !spa_normal_class(zio->io_spa)->mc_alloc_throttle_enabled ||
2828             zio->io_child_type == ZIO_CHILD_GANG ||
2829             zio->io_flags & ZIO_FLAG_NODATA) {
2830                 return (ZIO_PIPELINE_CONTINUE);
2831         }
2832
2833         ASSERT(zio->io_child_type > ZIO_CHILD_GANG);
2834
2835         ASSERT3U(zio->io_queued_timestamp, >, 0);
2836         ASSERT(zio->io_stage == ZIO_STAGE_DVA_THROTTLE);
2837
2838         mutex_enter(&spa->spa_alloc_lock);
2839
2840         ASSERT(zio->io_type == ZIO_TYPE_WRITE);
2841         avl_add(&spa->spa_alloc_tree, zio);
2842
2843         nio = zio_io_to_allocate(zio->io_spa);
2844         mutex_exit(&spa->spa_alloc_lock);
2845
2846         if (nio == zio)
2847                 return (ZIO_PIPELINE_CONTINUE);
2848
2849         if (nio != NULL) {
2850                 ASSERT(nio->io_stage == ZIO_STAGE_DVA_THROTTLE);
2851                 /*
2852                  * We are passing control to a new zio so make sure that
2853                  * it is processed by a different thread. We do this to
2854                  * avoid stack overflows that can occur when parents are
2855                  * throttled and children are making progress. We allow
2856                  * it to go to the head of the taskq since it's already
2857                  * been waiting.
2858                  */
2859                 zio_taskq_dispatch(nio, ZIO_TASKQ_ISSUE, B_TRUE);
2860         }
2861         return (ZIO_PIPELINE_STOP);
2862 }
2863
2864 void
2865 zio_allocate_dispatch(spa_t *spa)
2866 {
2867         zio_t *zio;
2868
2869         mutex_enter(&spa->spa_alloc_lock);
2870         zio = zio_io_to_allocate(spa);
2871         mutex_exit(&spa->spa_alloc_lock);
2872         if (zio == NULL)
2873                 return;
2874
2875         ASSERT3U(zio->io_stage, ==, ZIO_STAGE_DVA_THROTTLE);
2876         ASSERT0(zio->io_error);
2877         zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE, B_TRUE);
2878 }
2879
2880 static int
2881 zio_dva_allocate(zio_t *zio)
2882 {
2883         spa_t *spa = zio->io_spa;
2884         metaslab_class_t *mc = spa_normal_class(spa);
2885         blkptr_t *bp = zio->io_bp;
2886         int error;
2887         int flags = 0;
2888
2889         if (zio->io_gang_leader == NULL) {
2890                 ASSERT(zio->io_child_type > ZIO_CHILD_GANG);
2891                 zio->io_gang_leader = zio;
2892         }
2893
2894         ASSERT(BP_IS_HOLE(bp));
2895         ASSERT0(BP_GET_NDVAS(bp));
2896         ASSERT3U(zio->io_prop.zp_copies, >, 0);
2897         ASSERT3U(zio->io_prop.zp_copies, <=, spa_max_replication(spa));
2898         ASSERT3U(zio->io_size, ==, BP_GET_PSIZE(bp));
2899
2900         if (zio->io_flags & ZIO_FLAG_NODATA) {
2901                 flags |= METASLAB_DONT_THROTTLE;
2902         }
2903         if (zio->io_flags & ZIO_FLAG_GANG_CHILD) {
2904                 flags |= METASLAB_GANG_CHILD;
2905         }
2906         if (zio->io_priority == ZIO_PRIORITY_ASYNC_WRITE) {
2907                 flags |= METASLAB_ASYNC_ALLOC;
2908         }
2909
2910         error = metaslab_alloc(spa, mc, zio->io_size, bp,
2911             zio->io_prop.zp_copies, zio->io_txg, NULL, flags,
2912             &zio->io_alloc_list, zio);
2913
2914         if (error != 0) {
2915                 spa_dbgmsg(spa, "%s: metaslab allocation failure: zio %p, "
2916                     "size %llu, error %d", spa_name(spa), zio, zio->io_size,
2917                     error);
2918                 if (error == ENOSPC && zio->io_size > SPA_MINBLOCKSIZE)
2919                         return (zio_write_gang_block(zio));
2920                 zio->io_error = error;
2921         }
2922
2923         return (ZIO_PIPELINE_CONTINUE);
2924 }
2925
2926 static int
2927 zio_dva_free(zio_t *zio)
2928 {
2929         metaslab_free(zio->io_spa, zio->io_bp, zio->io_txg, B_FALSE);
2930
2931         return (ZIO_PIPELINE_CONTINUE);
2932 }
2933
2934 static int
2935 zio_dva_claim(zio_t *zio)
2936 {
2937         int error;
2938
2939         error = metaslab_claim(zio->io_spa, zio->io_bp, zio->io_txg);
2940         if (error)
2941                 zio->io_error = error;
2942
2943         return (ZIO_PIPELINE_CONTINUE);
2944 }
2945
2946 /*
2947  * Undo an allocation.  This is used by zio_done() when an I/O fails
2948  * and we want to give back the block we just allocated.
2949  * This handles both normal blocks and gang blocks.
2950  */
2951 static void
2952 zio_dva_unallocate(zio_t *zio, zio_gang_node_t *gn, blkptr_t *bp)
2953 {
2954         ASSERT(bp->blk_birth == zio->io_txg || BP_IS_HOLE(bp));
2955         ASSERT(zio->io_bp_override == NULL);
2956
2957         if (!BP_IS_HOLE(bp))
2958                 metaslab_free(zio->io_spa, bp, bp->blk_birth, B_TRUE);
2959
2960         if (gn != NULL) {
2961                 for (int g = 0; g < SPA_GBH_NBLKPTRS; g++) {
2962                         zio_dva_unallocate(zio, gn->gn_child[g],
2963                             &gn->gn_gbh->zg_blkptr[g]);
2964                 }
2965         }
2966 }
2967
2968 /*
2969  * Try to allocate an intent log block.  Return 0 on success, errno on failure.
2970  */
2971 int
2972 zio_alloc_zil(spa_t *spa, uint64_t txg, blkptr_t *new_bp, blkptr_t *old_bp,
2973     uint64_t size, boolean_t *slog)
2974 {
2975         int error = 1;
2976         zio_alloc_list_t io_alloc_list;
2977
2978         ASSERT(txg > spa_syncing_txg(spa));
2979
2980         metaslab_trace_init(&io_alloc_list);
2981         error = metaslab_alloc(spa, spa_log_class(spa), size, new_bp, 1,
2982             txg, old_bp, METASLAB_HINTBP_AVOID, &io_alloc_list, NULL);
2983         if (error == 0) {
2984                 *slog = TRUE;
2985         } else {
2986                 error = metaslab_alloc(spa, spa_normal_class(spa), size,
2987                     new_bp, 1, txg, old_bp, METASLAB_HINTBP_AVOID,
2988                     &io_alloc_list, NULL);
2989                 if (error == 0)
2990                         *slog = FALSE;
2991         }
2992         metaslab_trace_fini(&io_alloc_list);
2993
2994         if (error == 0) {
2995                 BP_SET_LSIZE(new_bp, size);
2996                 BP_SET_PSIZE(new_bp, size);
2997                 BP_SET_COMPRESS(new_bp, ZIO_COMPRESS_OFF);
2998                 BP_SET_CHECKSUM(new_bp,
2999                     spa_version(spa) >= SPA_VERSION_SLIM_ZIL
3000                     ? ZIO_CHECKSUM_ZILOG2 : ZIO_CHECKSUM_ZILOG);
3001                 BP_SET_TYPE(new_bp, DMU_OT_INTENT_LOG);
3002                 BP_SET_LEVEL(new_bp, 0);
3003                 BP_SET_DEDUP(new_bp, 0);
3004                 BP_SET_BYTEORDER(new_bp, ZFS_HOST_BYTEORDER);
3005         }
3006
3007         return (error);
3008 }
3009
3010 /*
3011  * Free an intent log block.
3012  */
3013 void
3014 zio_free_zil(spa_t *spa, uint64_t txg, blkptr_t *bp)
3015 {
3016         ASSERT(BP_GET_TYPE(bp) == DMU_OT_INTENT_LOG);
3017         ASSERT(!BP_IS_GANG(bp));
3018
3019         zio_free(spa, txg, bp);
3020 }
3021
3022 /*
3023  * ==========================================================================
3024  * Read, write and delete to physical devices
3025  * ==========================================================================
3026  */
3027
3028
3029 /*
3030  * Issue an I/O to the underlying vdev. Typically the issue pipeline
3031  * stops after this stage and will resume upon I/O completion.
3032  * However, there are instances where the vdev layer may need to
3033  * continue the pipeline when an I/O was not issued. Since the I/O
3034  * that was sent to the vdev layer might be different than the one
3035  * currently active in the pipeline (see vdev_queue_io()), we explicitly
3036  * force the underlying vdev layers to call either zio_execute() or
3037  * zio_interrupt() to ensure that the pipeline continues with the correct I/O.
3038  */
3039 static int
3040 zio_vdev_io_start(zio_t *zio)
3041 {
3042         vdev_t *vd = zio->io_vd;
3043         uint64_t align;
3044         spa_t *spa = zio->io_spa;
3045         int ret;
3046
3047         ASSERT(zio->io_error == 0);
3048         ASSERT(zio->io_child_error[ZIO_CHILD_VDEV] == 0);
3049
3050         if (vd == NULL) {
3051                 if (!(zio->io_flags & ZIO_FLAG_CONFIG_WRITER))
3052                         spa_config_enter(spa, SCL_ZIO, zio, RW_READER);
3053
3054                 /*
3055                  * The mirror_ops handle multiple DVAs in a single BP.
3056                  */
3057                 vdev_mirror_ops.vdev_op_io_start(zio);
3058                 return (ZIO_PIPELINE_STOP);
3059         }
3060
3061         if (vd->vdev_ops->vdev_op_leaf && zio->io_type == ZIO_TYPE_FREE &&
3062             zio->io_priority == ZIO_PRIORITY_NOW) {
3063                 trim_map_free(vd, zio->io_offset, zio->io_size, zio->io_txg);
3064                 return (ZIO_PIPELINE_CONTINUE);
3065         }
3066
3067         ASSERT3P(zio->io_logical, !=, zio);
3068
3069         /*
3070          * We keep track of time-sensitive I/Os so that the scan thread
3071          * can quickly react to certain workloads.  In particular, we care
3072          * about non-scrubbing, top-level reads and writes with the following
3073          * characteristics:
3074          *      - synchronous writes of user data to non-slog devices
3075          *      - any reads of user data
3076          * When these conditions are met, adjust the timestamp of spa_last_io
3077          * which allows the scan thread to adjust its workload accordingly.
3078          */
3079         if (!(zio->io_flags & ZIO_FLAG_SCAN_THREAD) && zio->io_bp != NULL &&
3080             vd == vd->vdev_top && !vd->vdev_islog &&
3081             zio->io_bookmark.zb_objset != DMU_META_OBJSET &&
3082             zio->io_txg != spa_syncing_txg(spa)) {
3083                 uint64_t old = spa->spa_last_io;
3084                 uint64_t new = ddi_get_lbolt64();
3085                 if (old != new)
3086                         (void) atomic_cas_64(&spa->spa_last_io, old, new);
3087         }
3088
3089         align = 1ULL << vd->vdev_top->vdev_ashift;
3090
3091         if (!(zio->io_flags & ZIO_FLAG_PHYSICAL) &&
3092             P2PHASE(zio->io_size, align) != 0) {
3093                 /* Transform logical writes to be a full physical block size. */
3094                 uint64_t asize = P2ROUNDUP(zio->io_size, align);
3095                 char *abuf = NULL;
3096                 if (zio->io_type == ZIO_TYPE_READ ||
3097                     zio->io_type == ZIO_TYPE_WRITE)
3098                         abuf = zio_buf_alloc(asize);
3099                 ASSERT(vd == vd->vdev_top);
3100                 if (zio->io_type == ZIO_TYPE_WRITE) {
3101                         bcopy(zio->io_data, abuf, zio->io_size);
3102                         bzero(abuf + zio->io_size, asize - zio->io_size);
3103                 }
3104                 zio_push_transform(zio, abuf, asize, abuf ? asize : 0,
3105                     zio_subblock);
3106         }
3107
3108         /*
3109          * If this is not a physical io, make sure that it is properly aligned
3110          * before proceeding.
3111          */
3112         if (!(zio->io_flags & ZIO_FLAG_PHYSICAL)) {
3113                 ASSERT0(P2PHASE(zio->io_offset, align));
3114                 ASSERT0(P2PHASE(zio->io_size, align));
3115         } else {
3116                 /*
3117                  * For the physical io we allow alignment
3118                  * to a logical block size.
3119                  */
3120                 uint64_t log_align =
3121                     1ULL << vd->vdev_top->vdev_logical_ashift;
3122                 ASSERT0(P2PHASE(zio->io_offset, log_align));
3123                 ASSERT0(P2PHASE(zio->io_size, log_align));
3124         }
3125
3126         VERIFY(zio->io_type == ZIO_TYPE_READ || spa_writeable(spa));
3127
3128         /*
3129          * If this is a repair I/O, and there's no self-healing involved --
3130          * that is, we're just resilvering what we expect to resilver --
3131          * then don't do the I/O unless zio's txg is actually in vd's DTL.
3132          * This prevents spurious resilvering with nested replication.
3133          * For example, given a mirror of mirrors, (A+B)+(C+D), if only
3134          * A is out of date, we'll read from C+D, then use the data to
3135          * resilver A+B -- but we don't actually want to resilver B, just A.
3136          * The top-level mirror has no way to know this, so instead we just
3137          * discard unnecessary repairs as we work our way down the vdev tree.
3138          * The same logic applies to any form of nested replication:
3139          * ditto + mirror, RAID-Z + replacing, etc.  This covers them all.
3140          */
3141         if ((zio->io_flags & ZIO_FLAG_IO_REPAIR) &&
3142             !(zio->io_flags & ZIO_FLAG_SELF_HEAL) &&
3143             zio->io_txg != 0 && /* not a delegated i/o */
3144             !vdev_dtl_contains(vd, DTL_PARTIAL, zio->io_txg, 1)) {
3145                 ASSERT(zio->io_type == ZIO_TYPE_WRITE);
3146                 zio_vdev_io_bypass(zio);
3147                 return (ZIO_PIPELINE_CONTINUE);
3148         }
3149
3150         if (vd->vdev_ops->vdev_op_leaf) {
3151                 switch (zio->io_type) {
3152                 case ZIO_TYPE_READ:
3153                         if (vdev_cache_read(zio))
3154                                 return (ZIO_PIPELINE_CONTINUE);
3155                         /* FALLTHROUGH */
3156                 case ZIO_TYPE_WRITE:
3157                 case ZIO_TYPE_FREE:
3158                         if ((zio = vdev_queue_io(zio)) == NULL)
3159                                 return (ZIO_PIPELINE_STOP);
3160
3161                         if (!vdev_accessible(vd, zio)) {
3162                                 zio->io_error = SET_ERROR(ENXIO);
3163                                 zio_interrupt(zio);
3164                                 return (ZIO_PIPELINE_STOP);
3165                         }
3166                         break;
3167                 }
3168                 /*
3169                  * Note that we ignore repair writes for TRIM because they can
3170                  * conflict with normal writes. This isn't an issue because, by
3171                  * definition, we only repair blocks that aren't freed.
3172                  */
3173                 if (zio->io_type == ZIO_TYPE_WRITE &&
3174                     !(zio->io_flags & ZIO_FLAG_IO_REPAIR) &&
3175                     !trim_map_write_start(zio))
3176                         return (ZIO_PIPELINE_STOP);
3177         }
3178
3179         vd->vdev_ops->vdev_op_io_start(zio);
3180         return (ZIO_PIPELINE_STOP);
3181 }
3182
3183 static int
3184 zio_vdev_io_done(zio_t *zio)
3185 {
3186         vdev_t *vd = zio->io_vd;
3187         vdev_ops_t *ops = vd ? vd->vdev_ops : &vdev_mirror_ops;
3188         boolean_t unexpected_error = B_FALSE;
3189
3190         if (zio_wait_for_children(zio, ZIO_CHILD_VDEV, ZIO_WAIT_DONE))
3191                 return (ZIO_PIPELINE_STOP);
3192
3193         ASSERT(zio->io_type == ZIO_TYPE_READ ||
3194             zio->io_type == ZIO_TYPE_WRITE || zio->io_type == ZIO_TYPE_FREE);
3195
3196         if (vd != NULL && vd->vdev_ops->vdev_op_leaf &&
3197             (zio->io_type == ZIO_TYPE_READ || zio->io_type == ZIO_TYPE_WRITE ||
3198             zio->io_type == ZIO_TYPE_FREE)) {
3199
3200                 if (zio->io_type == ZIO_TYPE_WRITE &&
3201                     !(zio->io_flags & ZIO_FLAG_IO_REPAIR))
3202                         trim_map_write_done(zio);
3203
3204                 vdev_queue_io_done(zio);
3205
3206                 if (zio->io_type == ZIO_TYPE_WRITE)
3207                         vdev_cache_write(zio);
3208
3209                 if (zio_injection_enabled && zio->io_error == 0)
3210                         zio->io_error = zio_handle_device_injection(vd,
3211                             zio, EIO);
3212
3213                 if (zio_injection_enabled && zio->io_error == 0)
3214                         zio->io_error = zio_handle_label_injection(zio, EIO);
3215
3216                 if (zio->io_error) {
3217                         if (zio->io_error == ENOTSUP &&
3218                             zio->io_type == ZIO_TYPE_FREE) {
3219                                 /* Not all devices support TRIM. */
3220                         } else if (!vdev_accessible(vd, zio)) {
3221                                 zio->io_error = SET_ERROR(ENXIO);
3222                         } else {
3223                                 unexpected_error = B_TRUE;
3224                         }
3225                 }
3226         }
3227
3228         ops->vdev_op_io_done(zio);
3229
3230         if (unexpected_error)
3231                 VERIFY(vdev_probe(vd, zio) == NULL);
3232
3233         return (ZIO_PIPELINE_CONTINUE);
3234 }
3235
3236 /*
3237  * For non-raidz ZIOs, we can just copy aside the bad data read from the
3238  * disk, and use that to finish the checksum ereport later.
3239  */
3240 static void
3241 zio_vsd_default_cksum_finish(zio_cksum_report_t *zcr,
3242     const void *good_buf)
3243 {
3244         /* no processing needed */
3245         zfs_ereport_finish_checksum(zcr, good_buf, zcr->zcr_cbdata, B_FALSE);
3246 }
3247
3248 /*ARGSUSED*/
3249 void
3250 zio_vsd_default_cksum_report(zio_t *zio, zio_cksum_report_t *zcr, void *ignored)
3251 {
3252         void *buf = zio_buf_alloc(zio->io_size);
3253
3254         bcopy(zio->io_data, buf, zio->io_size);
3255
3256         zcr->zcr_cbinfo = zio->io_size;
3257         zcr->zcr_cbdata = buf;
3258         zcr->zcr_finish = zio_vsd_default_cksum_finish;
3259         zcr->zcr_free = zio_buf_free;
3260 }
3261
3262 static int
3263 zio_vdev_io_assess(zio_t *zio)
3264 {
3265         vdev_t *vd = zio->io_vd;
3266
3267         if (zio_wait_for_children(zio, ZIO_CHILD_VDEV, ZIO_WAIT_DONE))
3268                 return (ZIO_PIPELINE_STOP);
3269
3270         if (vd == NULL && !(zio->io_flags & ZIO_FLAG_CONFIG_WRITER))
3271                 spa_config_exit(zio->io_spa, SCL_ZIO, zio);
3272
3273         if (zio->io_vsd != NULL) {
3274                 zio->io_vsd_ops->vsd_free(zio);
3275                 zio->io_vsd = NULL;
3276         }
3277
3278         if (zio_injection_enabled && zio->io_error == 0)
3279                 zio->io_error = zio_handle_fault_injection(zio, EIO);
3280
3281         if (zio->io_type == ZIO_TYPE_FREE &&
3282             zio->io_priority != ZIO_PRIORITY_NOW) {
3283                 switch (zio->io_error) {
3284                 case 0:
3285                         ZIO_TRIM_STAT_INCR(bytes, zio->io_size);
3286                         ZIO_TRIM_STAT_BUMP(success);
3287                         break;
3288                 case EOPNOTSUPP:
3289                         ZIO_TRIM_STAT_BUMP(unsupported);
3290                         break;
3291                 default:
3292                         ZIO_TRIM_STAT_BUMP(failed);
3293                         break;
3294                 }
3295         }
3296
3297         /*
3298          * If the I/O failed, determine whether we should attempt to retry it.
3299          *
3300          * On retry, we cut in line in the issue queue, since we don't want
3301          * compression/checksumming/etc. work to prevent our (cheap) IO reissue.
3302          */
3303         if (zio->io_error && vd == NULL &&
3304             !(zio->io_flags & (ZIO_FLAG_DONT_RETRY | ZIO_FLAG_IO_RETRY))) {
3305                 ASSERT(!(zio->io_flags & ZIO_FLAG_DONT_QUEUE)); /* not a leaf */
3306                 ASSERT(!(zio->io_flags & ZIO_FLAG_IO_BYPASS));  /* not a leaf */
3307                 zio->io_error = 0;
3308                 zio->io_flags |= ZIO_FLAG_IO_RETRY |
3309                     ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_AGGREGATE;
3310                 zio->io_stage = ZIO_STAGE_VDEV_IO_START >> 1;
3311                 zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE,
3312                     zio_requeue_io_start_cut_in_line);
3313                 return (ZIO_PIPELINE_STOP);
3314         }
3315
3316         /*
3317          * If we got an error on a leaf device, convert it to ENXIO
3318          * if the device is not accessible at all.
3319          */
3320         if (zio->io_error && vd != NULL && vd->vdev_ops->vdev_op_leaf &&
3321             !vdev_accessible(vd, zio))
3322                 zio->io_error = SET_ERROR(ENXIO);
3323
3324         /*
3325          * If we can't write to an interior vdev (mirror or RAID-Z),
3326          * set vdev_cant_write so that we stop trying to allocate from it.
3327          */
3328         if (zio->io_error == ENXIO && zio->io_type == ZIO_TYPE_WRITE &&
3329             vd != NULL && !vd->vdev_ops->vdev_op_leaf) {
3330                 vd->vdev_cant_write = B_TRUE;
3331         }
3332
3333         /*
3334          * If a cache flush returns ENOTSUP or ENOTTY, we know that no future
3335          * attempts will ever succeed. In this case we set a persistent bit so
3336          * that we don't bother with it in the future.
3337          */
3338         if ((zio->io_error == ENOTSUP || zio->io_error == ENOTTY) &&
3339             zio->io_type == ZIO_TYPE_IOCTL &&
3340             zio->io_cmd == DKIOCFLUSHWRITECACHE && vd != NULL)
3341                 vd->vdev_nowritecache = B_TRUE;
3342
3343         if (zio->io_error)
3344                 zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
3345
3346         if (vd != NULL && vd->vdev_ops->vdev_op_leaf &&
3347             zio->io_physdone != NULL) {
3348                 ASSERT(!(zio->io_flags & ZIO_FLAG_DELEGATED));
3349                 ASSERT(zio->io_child_type == ZIO_CHILD_VDEV);
3350                 zio->io_physdone(zio->io_logical);
3351         }
3352
3353         return (ZIO_PIPELINE_CONTINUE);
3354 }
3355
3356 void
3357 zio_vdev_io_reissue(zio_t *zio)
3358 {
3359         ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_START);
3360         ASSERT(zio->io_error == 0);
3361
3362         zio->io_stage >>= 1;
3363 }
3364
3365 void
3366 zio_vdev_io_redone(zio_t *zio)
3367 {
3368         ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_DONE);
3369
3370         zio->io_stage >>= 1;
3371 }
3372
3373 void
3374 zio_vdev_io_bypass(zio_t *zio)
3375 {
3376         ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_START);
3377         ASSERT(zio->io_error == 0);
3378
3379         zio->io_flags |= ZIO_FLAG_IO_BYPASS;
3380         zio->io_stage = ZIO_STAGE_VDEV_IO_ASSESS >> 1;
3381 }
3382
3383 /*
3384  * ==========================================================================
3385  * Generate and verify checksums
3386  * ==========================================================================
3387  */
3388 static int
3389 zio_checksum_generate(zio_t *zio)
3390 {
3391         blkptr_t *bp = zio->io_bp;
3392         enum zio_checksum checksum;
3393
3394         if (bp == NULL) {
3395                 /*
3396                  * This is zio_write_phys().
3397                  * We're either generating a label checksum, or none at all.
3398                  */
3399                 checksum = zio->io_prop.zp_checksum;
3400
3401                 if (checksum == ZIO_CHECKSUM_OFF)
3402                         return (ZIO_PIPELINE_CONTINUE);
3403
3404                 ASSERT(checksum == ZIO_CHECKSUM_LABEL);
3405         } else {
3406                 if (BP_IS_GANG(bp) && zio->io_child_type == ZIO_CHILD_GANG) {
3407                         ASSERT(!IO_IS_ALLOCATING(zio));
3408                         checksum = ZIO_CHECKSUM_GANG_HEADER;
3409                 } else {
3410                         checksum = BP_GET_CHECKSUM(bp);
3411                 }
3412         }
3413
3414         zio_checksum_compute(zio, checksum, zio->io_data, zio->io_size);
3415
3416         return (ZIO_PIPELINE_CONTINUE);
3417 }
3418
3419 static int
3420 zio_checksum_verify(zio_t *zio)
3421 {
3422         zio_bad_cksum_t info;
3423         blkptr_t *bp = zio->io_bp;
3424         int error;
3425
3426         ASSERT(zio->io_vd != NULL);
3427
3428         if (bp == NULL) {
3429                 /*
3430                  * This is zio_read_phys().
3431                  * We're either verifying a label checksum, or nothing at all.
3432                  */
3433                 if (zio->io_prop.zp_checksum == ZIO_CHECKSUM_OFF)
3434                         return (ZIO_PIPELINE_CONTINUE);
3435
3436                 ASSERT(zio->io_prop.zp_checksum == ZIO_CHECKSUM_LABEL);
3437         }
3438
3439         if ((error = zio_checksum_error(zio, &info)) != 0) {
3440                 zio->io_error = error;
3441                 if (error == ECKSUM &&
3442                     !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
3443                         zfs_ereport_start_checksum(zio->io_spa,
3444                             zio->io_vd, zio, zio->io_offset,
3445                             zio->io_size, NULL, &info);
3446                 }
3447         }
3448
3449         return (ZIO_PIPELINE_CONTINUE);
3450 }
3451
3452 /*
3453  * Called by RAID-Z to ensure we don't compute the checksum twice.
3454  */
3455 void
3456 zio_checksum_verified(zio_t *zio)
3457 {
3458         zio->io_pipeline &= ~ZIO_STAGE_CHECKSUM_VERIFY;
3459 }
3460
3461 /*
3462  * ==========================================================================
3463  * Error rank.  Error are ranked in the order 0, ENXIO, ECKSUM, EIO, other.
3464  * An error of 0 indicates success.  ENXIO indicates whole-device failure,
3465  * which may be transient (e.g. unplugged) or permament.  ECKSUM and EIO
3466  * indicate errors that are specific to one I/O, and most likely permanent.
3467  * Any other error is presumed to be worse because we weren't expecting it.
3468  * ==========================================================================
3469  */
3470 int
3471 zio_worst_error(int e1, int e2)
3472 {
3473         static int zio_error_rank[] = { 0, ENXIO, ECKSUM, EIO };
3474         int r1, r2;
3475
3476         for (r1 = 0; r1 < sizeof (zio_error_rank) / sizeof (int); r1++)
3477                 if (e1 == zio_error_rank[r1])
3478                         break;
3479
3480         for (r2 = 0; r2 < sizeof (zio_error_rank) / sizeof (int); r2++)
3481                 if (e2 == zio_error_rank[r2])
3482                         break;
3483
3484         return (r1 > r2 ? e1 : e2);
3485 }
3486
3487 /*
3488  * ==========================================================================
3489  * I/O completion
3490  * ==========================================================================
3491  */
3492 static int
3493 zio_ready(zio_t *zio)
3494 {
3495         blkptr_t *bp = zio->io_bp;
3496         zio_t *pio, *pio_next;
3497         zio_link_t *zl = NULL;
3498
3499         if (zio_wait_for_children(zio, ZIO_CHILD_GANG, ZIO_WAIT_READY) ||
3500             zio_wait_for_children(zio, ZIO_CHILD_DDT, ZIO_WAIT_READY))
3501                 return (ZIO_PIPELINE_STOP);
3502
3503         if (zio->io_ready) {
3504                 ASSERT(IO_IS_ALLOCATING(zio));
3505                 ASSERT(bp->blk_birth == zio->io_txg || BP_IS_HOLE(bp) ||
3506                     (zio->io_flags & ZIO_FLAG_NOPWRITE));
3507                 ASSERT(zio->io_children[ZIO_CHILD_GANG][ZIO_WAIT_READY] == 0);
3508
3509                 zio->io_ready(zio);
3510         }
3511
3512         if (bp != NULL && bp != &zio->io_bp_copy)
3513                 zio->io_bp_copy = *bp;
3514
3515         if (zio->io_error != 0) {
3516                 zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
3517
3518                 if (zio->io_flags & ZIO_FLAG_IO_ALLOCATING) {
3519                         ASSERT(IO_IS_ALLOCATING(zio));
3520                         ASSERT(zio->io_priority == ZIO_PRIORITY_ASYNC_WRITE);
3521                         /*
3522                          * We were unable to allocate anything, unreserve and
3523                          * issue the next I/O to allocate.
3524                          */
3525                         metaslab_class_throttle_unreserve(
3526                             spa_normal_class(zio->io_spa),
3527                             zio->io_prop.zp_copies, zio);
3528                         zio_allocate_dispatch(zio->io_spa);
3529                 }
3530         }
3531
3532         mutex_enter(&zio->io_lock);
3533         zio->io_state[ZIO_WAIT_READY] = 1;
3534         pio = zio_walk_parents(zio, &zl);
3535         mutex_exit(&zio->io_lock);
3536
3537         /*
3538          * As we notify zio's parents, new parents could be added.
3539          * New parents go to the head of zio's io_parent_list, however,
3540          * so we will (correctly) not notify them.  The remainder of zio's
3541          * io_parent_list, from 'pio_next' onward, cannot change because
3542          * all parents must wait for us to be done before they can be done.
3543          */
3544         for (; pio != NULL; pio = pio_next) {
3545                 pio_next = zio_walk_parents(zio, &zl);
3546                 zio_notify_parent(pio, zio, ZIO_WAIT_READY);
3547         }
3548
3549         if (zio->io_flags & ZIO_FLAG_NODATA) {
3550                 if (BP_IS_GANG(bp)) {
3551                         zio->io_flags &= ~ZIO_FLAG_NODATA;
3552                 } else {
3553                         ASSERT((uintptr_t)zio->io_data < SPA_MAXBLOCKSIZE);
3554                         zio->io_pipeline &= ~ZIO_VDEV_IO_STAGES;
3555                 }
3556         }
3557
3558         if (zio_injection_enabled &&
3559             zio->io_spa->spa_syncing_txg == zio->io_txg)
3560                 zio_handle_ignored_writes(zio);
3561
3562         return (ZIO_PIPELINE_CONTINUE);
3563 }
3564
3565 /*
3566  * Update the allocation throttle accounting.
3567  */
3568 static void
3569 zio_dva_throttle_done(zio_t *zio)
3570 {
3571         zio_t *lio = zio->io_logical;
3572         zio_t *pio = zio_unique_parent(zio);
3573         vdev_t *vd = zio->io_vd;
3574         int flags = METASLAB_ASYNC_ALLOC;
3575
3576         ASSERT3P(zio->io_bp, !=, NULL);
3577         ASSERT3U(zio->io_type, ==, ZIO_TYPE_WRITE);
3578         ASSERT3U(zio->io_priority, ==, ZIO_PRIORITY_ASYNC_WRITE);
3579         ASSERT3U(zio->io_child_type, ==, ZIO_CHILD_VDEV);
3580         ASSERT(vd != NULL);
3581         ASSERT3P(vd, ==, vd->vdev_top);
3582         ASSERT(!(zio->io_flags & (ZIO_FLAG_IO_REPAIR | ZIO_FLAG_IO_RETRY)));
3583         ASSERT(zio->io_flags & ZIO_FLAG_IO_ALLOCATING);
3584         ASSERT(!(lio->io_flags & ZIO_FLAG_IO_REWRITE));
3585         ASSERT(!(lio->io_orig_flags & ZIO_FLAG_NODATA));
3586
3587         /*
3588          * Parents of gang children can have two flavors -- ones that
3589          * allocated the gang header (will have ZIO_FLAG_IO_REWRITE set)
3590          * and ones that allocated the constituent blocks. The allocation
3591          * throttle needs to know the allocating parent zio so we must find
3592          * it here.
3593          */
3594         if (pio->io_child_type == ZIO_CHILD_GANG) {
3595                 /*
3596                  * If our parent is a rewrite gang child then our grandparent
3597                  * would have been the one that performed the allocation.
3598                  */
3599                 if (pio->io_flags & ZIO_FLAG_IO_REWRITE)
3600                         pio = zio_unique_parent(pio);
3601                 flags |= METASLAB_GANG_CHILD;
3602         }
3603
3604         ASSERT(IO_IS_ALLOCATING(pio));
3605         ASSERT3P(zio, !=, zio->io_logical);
3606         ASSERT(zio->io_logical != NULL);
3607         ASSERT(!(zio->io_flags & ZIO_FLAG_IO_REPAIR));
3608         ASSERT0(zio->io_flags & ZIO_FLAG_NOPWRITE);
3609
3610         mutex_enter(&pio->io_lock);
3611         metaslab_group_alloc_decrement(zio->io_spa, vd->vdev_id, pio, flags);
3612         mutex_exit(&pio->io_lock);
3613
3614         metaslab_class_throttle_unreserve(spa_normal_class(zio->io_spa),
3615             1, pio);
3616
3617         /*
3618          * Call into the pipeline to see if there is more work that
3619          * needs to be done. If there is work to be done it will be
3620          * dispatched to another taskq thread.
3621          */
3622         zio_allocate_dispatch(zio->io_spa);
3623 }
3624
3625 static int
3626 zio_done(zio_t *zio)
3627 {
3628         spa_t *spa = zio->io_spa;
3629         zio_t *lio = zio->io_logical;
3630         blkptr_t *bp = zio->io_bp;
3631         vdev_t *vd = zio->io_vd;
3632         uint64_t psize = zio->io_size;
3633         zio_t *pio, *pio_next;
3634         metaslab_class_t *mc = spa_normal_class(spa);
3635         zio_link_t *zl = NULL;
3636
3637         /*
3638          * If our children haven't all completed,
3639          * wait for them and then repeat this pipeline stage.
3640          */
3641         if (zio_wait_for_children(zio, ZIO_CHILD_VDEV, ZIO_WAIT_DONE) ||
3642             zio_wait_for_children(zio, ZIO_CHILD_GANG, ZIO_WAIT_DONE) ||
3643             zio_wait_for_children(zio, ZIO_CHILD_DDT, ZIO_WAIT_DONE) ||
3644             zio_wait_for_children(zio, ZIO_CHILD_LOGICAL, ZIO_WAIT_DONE))
3645                 return (ZIO_PIPELINE_STOP);
3646
3647         /*
3648          * If the allocation throttle is enabled, then update the accounting.
3649          * We only track child I/Os that are part of an allocating async
3650          * write. We must do this since the allocation is performed
3651          * by the logical I/O but the actual write is done by child I/Os.
3652          */
3653         if (zio->io_flags & ZIO_FLAG_IO_ALLOCATING &&
3654             zio->io_child_type == ZIO_CHILD_VDEV) {
3655                 ASSERT(mc->mc_alloc_throttle_enabled);
3656                 zio_dva_throttle_done(zio);
3657         }
3658
3659         /*
3660          * If the allocation throttle is enabled, verify that
3661          * we have decremented the refcounts for every I/O that was throttled.
3662          */
3663         if (zio->io_flags & ZIO_FLAG_IO_ALLOCATING) {
3664                 ASSERT(zio->io_type == ZIO_TYPE_WRITE);
3665                 ASSERT(zio->io_priority == ZIO_PRIORITY_ASYNC_WRITE);
3666                 ASSERT(bp != NULL);
3667                 metaslab_group_alloc_verify(spa, zio->io_bp, zio);
3668                 VERIFY(refcount_not_held(&mc->mc_alloc_slots, zio));
3669         }
3670
3671         for (int c = 0; c < ZIO_CHILD_TYPES; c++)
3672                 for (int w = 0; w < ZIO_WAIT_TYPES; w++)
3673                         ASSERT(zio->io_children[c][w] == 0);
3674
3675         if (bp != NULL && !BP_IS_EMBEDDED(bp)) {
3676                 ASSERT(bp->blk_pad[0] == 0);
3677                 ASSERT(bp->blk_pad[1] == 0);
3678                 ASSERT(bcmp(bp, &zio->io_bp_copy, sizeof (blkptr_t)) == 0 ||
3679                     (bp == zio_unique_parent(zio)->io_bp));
3680                 if (zio->io_type == ZIO_TYPE_WRITE && !BP_IS_HOLE(bp) &&
3681                     zio->io_bp_override == NULL &&
3682                     !(zio->io_flags & ZIO_FLAG_IO_REPAIR)) {
3683                         ASSERT(!BP_SHOULD_BYTESWAP(bp));
3684                         ASSERT3U(zio->io_prop.zp_copies, <=, BP_GET_NDVAS(bp));
3685                         ASSERT(BP_COUNT_GANG(bp) == 0 ||
3686                             (BP_COUNT_GANG(bp) == BP_GET_NDVAS(bp)));
3687                 }
3688                 if (zio->io_flags & ZIO_FLAG_NOPWRITE)
3689                         VERIFY(BP_EQUAL(bp, &zio->io_bp_orig));
3690         }
3691
3692         /*
3693          * If there were child vdev/gang/ddt errors, they apply to us now.
3694          */
3695         zio_inherit_child_errors(zio, ZIO_CHILD_VDEV);
3696         zio_inherit_child_errors(zio, ZIO_CHILD_GANG);
3697         zio_inherit_child_errors(zio, ZIO_CHILD_DDT);
3698
3699         /*
3700          * If the I/O on the transformed data was successful, generate any
3701          * checksum reports now while we still have the transformed data.
3702          */
3703         if (zio->io_error == 0) {
3704                 while (zio->io_cksum_report != NULL) {
3705                         zio_cksum_report_t *zcr = zio->io_cksum_report;
3706                         uint64_t align = zcr->zcr_align;
3707                         uint64_t asize = P2ROUNDUP(psize, align);
3708                         char *abuf = zio->io_data;
3709
3710                         if (asize != psize) {
3711                                 abuf = zio_buf_alloc(asize);
3712                                 bcopy(zio->io_data, abuf, psize);
3713                                 bzero(abuf + psize, asize - psize);
3714                         }
3715
3716                         zio->io_cksum_report = zcr->zcr_next;
3717                         zcr->zcr_next = NULL;
3718                         zcr->zcr_finish(zcr, abuf);
3719                         zfs_ereport_free_checksum(zcr);
3720
3721                         if (asize != psize)
3722                                 zio_buf_free(abuf, asize);
3723                 }
3724         }
3725
3726         zio_pop_transforms(zio);        /* note: may set zio->io_error */
3727
3728         vdev_stat_update(zio, psize);
3729
3730         if (zio->io_error) {
3731                 /*
3732                  * If this I/O is attached to a particular vdev,
3733                  * generate an error message describing the I/O failure
3734                  * at the block level.  We ignore these errors if the
3735                  * device is currently unavailable.
3736                  */
3737                 if (zio->io_error != ECKSUM && vd != NULL && !vdev_is_dead(vd))
3738                         zfs_ereport_post(FM_EREPORT_ZFS_IO, spa, vd, zio, 0, 0);
3739
3740                 if ((zio->io_error == EIO || !(zio->io_flags &
3741                     (ZIO_FLAG_SPECULATIVE | ZIO_FLAG_DONT_PROPAGATE))) &&
3742                     zio == lio) {
3743                         /*
3744                          * For logical I/O requests, tell the SPA to log the
3745                          * error and generate a logical data ereport.
3746                          */
3747                         spa_log_error(spa, zio);
3748                         zfs_ereport_post(FM_EREPORT_ZFS_DATA, spa, NULL, zio,
3749                             0, 0);
3750                 }
3751         }
3752
3753         if (zio->io_error && zio == lio) {
3754                 /*
3755                  * Determine whether zio should be reexecuted.  This will
3756                  * propagate all the way to the root via zio_notify_parent().
3757                  */
3758                 ASSERT(vd == NULL && bp != NULL);
3759                 ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
3760
3761                 if (IO_IS_ALLOCATING(zio) &&
3762                     !(zio->io_flags & ZIO_FLAG_CANFAIL)) {
3763                         if (zio->io_error != ENOSPC)
3764                                 zio->io_reexecute |= ZIO_REEXECUTE_NOW;
3765                         else
3766                                 zio->io_reexecute |= ZIO_REEXECUTE_SUSPEND;
3767                 }
3768
3769                 if ((zio->io_type == ZIO_TYPE_READ ||
3770                     zio->io_type == ZIO_TYPE_FREE) &&
3771                     !(zio->io_flags & ZIO_FLAG_SCAN_THREAD) &&
3772                     zio->io_error == ENXIO &&
3773                     spa_load_state(spa) == SPA_LOAD_NONE &&
3774                     spa_get_failmode(spa) != ZIO_FAILURE_MODE_CONTINUE)
3775                         zio->io_reexecute |= ZIO_REEXECUTE_SUSPEND;
3776
3777                 if (!(zio->io_flags & ZIO_FLAG_CANFAIL) && !zio->io_reexecute)
3778                         zio->io_reexecute |= ZIO_REEXECUTE_SUSPEND;
3779
3780                 /*
3781                  * Here is a possibly good place to attempt to do
3782                  * either combinatorial reconstruction or error correction
3783                  * based on checksums.  It also might be a good place
3784                  * to send out preliminary ereports before we suspend
3785                  * processing.
3786                  */
3787         }
3788
3789         /*
3790          * If there were logical child errors, they apply to us now.
3791          * We defer this until now to avoid conflating logical child
3792          * errors with errors that happened to the zio itself when
3793          * updating vdev stats and reporting FMA events above.
3794          */
3795         zio_inherit_child_errors(zio, ZIO_CHILD_LOGICAL);
3796
3797         if ((zio->io_error || zio->io_reexecute) &&
3798             IO_IS_ALLOCATING(zio) && zio->io_gang_leader == zio &&
3799             !(zio->io_flags & (ZIO_FLAG_IO_REWRITE | ZIO_FLAG_NOPWRITE)))
3800                 zio_dva_unallocate(zio, zio->io_gang_tree, bp);
3801
3802         zio_gang_tree_free(&zio->io_gang_tree);
3803
3804         /*
3805          * Godfather I/Os should never suspend.
3806          */
3807         if ((zio->io_flags & ZIO_FLAG_GODFATHER) &&
3808             (zio->io_reexecute & ZIO_REEXECUTE_SUSPEND))
3809                 zio->io_reexecute = 0;
3810
3811         if (zio->io_reexecute) {
3812                 /*
3813                  * This is a logical I/O that wants to reexecute.
3814                  *
3815                  * Reexecute is top-down.  When an i/o fails, if it's not
3816                  * the root, it simply notifies its parent and sticks around.
3817                  * The parent, seeing that it still has children in zio_done(),
3818                  * does the same.  This percolates all the way up to the root.
3819                  * The root i/o will reexecute or suspend the entire tree.
3820                  *
3821                  * This approach ensures that zio_reexecute() honors
3822                  * all the original i/o dependency relationships, e.g.
3823                  * parents not executing until children are ready.
3824                  */
3825                 ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
3826
3827                 zio->io_gang_leader = NULL;
3828
3829                 mutex_enter(&zio->io_lock);
3830                 zio->io_state[ZIO_WAIT_DONE] = 1;
3831                 mutex_exit(&zio->io_lock);
3832
3833                 /*
3834                  * "The Godfather" I/O monitors its children but is
3835                  * not a true parent to them. It will track them through
3836                  * the pipeline but severs its ties whenever they get into
3837                  * trouble (e.g. suspended). This allows "The Godfather"
3838                  * I/O to return status without blocking.
3839                  */
3840                 zl = NULL;
3841                 for (pio = zio_walk_parents(zio, &zl); pio != NULL;
3842                     pio = pio_next) {
3843                         zio_link_t *remove_zl = zl;
3844                         pio_next = zio_walk_parents(zio, &zl);
3845
3846                         if ((pio->io_flags & ZIO_FLAG_GODFATHER) &&
3847                             (zio->io_reexecute & ZIO_REEXECUTE_SUSPEND)) {
3848                                 zio_remove_child(pio, zio, remove_zl);
3849                                 zio_notify_parent(pio, zio, ZIO_WAIT_DONE);
3850                         }
3851                 }
3852
3853                 if ((pio = zio_unique_parent(zio)) != NULL) {
3854                         /*
3855                          * We're not a root i/o, so there's nothing to do
3856                          * but notify our parent.  Don't propagate errors
3857                          * upward since we haven't permanently failed yet.
3858                          */
3859                         ASSERT(!(zio->io_flags & ZIO_FLAG_GODFATHER));
3860                         zio->io_flags |= ZIO_FLAG_DONT_PROPAGATE;
3861                         zio_notify_parent(pio, zio, ZIO_WAIT_DONE);
3862                 } else if (zio->io_reexecute & ZIO_REEXECUTE_SUSPEND) {
3863                         /*
3864                          * We'd fail again if we reexecuted now, so suspend
3865                          * until conditions improve (e.g. device comes online).
3866                          */
3867                         zio_suspend(spa, zio);
3868                 } else {
3869                         /*
3870                          * Reexecution is potentially a huge amount of work.
3871                          * Hand it off to the otherwise-unused claim taskq.
3872                          */
3873 #if defined(illumos) || !defined(_KERNEL)
3874                         ASSERT(zio->io_tqent.tqent_next == NULL);
3875 #else
3876                         ASSERT(zio->io_tqent.tqent_task.ta_pending == 0);
3877 #endif
3878                         spa_taskq_dispatch_ent(spa, ZIO_TYPE_CLAIM,
3879                             ZIO_TASKQ_ISSUE, (task_func_t *)zio_reexecute, zio,
3880                             0, &zio->io_tqent);
3881                 }
3882                 return (ZIO_PIPELINE_STOP);
3883         }
3884
3885         ASSERT(zio->io_child_count == 0);
3886         ASSERT(zio->io_reexecute == 0);
3887         ASSERT(zio->io_error == 0 || (zio->io_flags & ZIO_FLAG_CANFAIL));
3888
3889         /*
3890          * Report any checksum errors, since the I/O is complete.
3891          */
3892         while (zio->io_cksum_report != NULL) {
3893                 zio_cksum_report_t *zcr = zio->io_cksum_report;
3894                 zio->io_cksum_report = zcr->zcr_next;
3895                 zcr->zcr_next = NULL;
3896                 zcr->zcr_finish(zcr, NULL);
3897                 zfs_ereport_free_checksum(zcr);
3898         }
3899
3900         /*
3901          * It is the responsibility of the done callback to ensure that this
3902          * particular zio is no longer discoverable for adoption, and as
3903          * such, cannot acquire any new parents.
3904          */
3905         if (zio->io_done)
3906                 zio->io_done(zio);
3907
3908         mutex_enter(&zio->io_lock);
3909         zio->io_state[ZIO_WAIT_DONE] = 1;
3910         mutex_exit(&zio->io_lock);
3911
3912         zl = NULL;
3913         for (pio = zio_walk_parents(zio, &zl); pio != NULL; pio = pio_next) {
3914                 zio_link_t *remove_zl = zl;
3915                 pio_next = zio_walk_parents(zio, &zl);
3916                 zio_remove_child(pio, zio, remove_zl);
3917                 zio_notify_parent(pio, zio, ZIO_WAIT_DONE);
3918         }
3919
3920         if (zio->io_waiter != NULL) {
3921                 mutex_enter(&zio->io_lock);
3922                 zio->io_executor = NULL;
3923                 cv_broadcast(&zio->io_cv);
3924                 mutex_exit(&zio->io_lock);
3925         } else {
3926                 zio_destroy(zio);
3927         }
3928
3929         return (ZIO_PIPELINE_STOP);
3930 }
3931
3932 /*
3933  * ==========================================================================
3934  * I/O pipeline definition
3935  * ==========================================================================
3936  */
3937 static zio_pipe_stage_t *zio_pipeline[] = {
3938         NULL,
3939         zio_read_bp_init,
3940         zio_write_bp_init,
3941         zio_free_bp_init,
3942         zio_issue_async,
3943         zio_write_compress,
3944         zio_checksum_generate,
3945         zio_nop_write,
3946         zio_ddt_read_start,
3947         zio_ddt_read_done,
3948         zio_ddt_write,
3949         zio_ddt_free,
3950         zio_gang_assemble,
3951         zio_gang_issue,
3952         zio_dva_throttle,
3953         zio_dva_allocate,
3954         zio_dva_free,
3955         zio_dva_claim,
3956         zio_ready,
3957         zio_vdev_io_start,
3958         zio_vdev_io_done,
3959         zio_vdev_io_assess,
3960         zio_checksum_verify,
3961         zio_done
3962 };
3963
3964
3965
3966
3967 /*
3968  * Compare two zbookmark_phys_t's to see which we would reach first in a
3969  * pre-order traversal of the object tree.
3970  *
3971  * This is simple in every case aside from the meta-dnode object. For all other
3972  * objects, we traverse them in order (object 1 before object 2, and so on).
3973  * However, all of these objects are traversed while traversing object 0, since
3974  * the data it points to is the list of objects.  Thus, we need to convert to a
3975  * canonical representation so we can compare meta-dnode bookmarks to
3976  * non-meta-dnode bookmarks.
3977  *
3978  * We do this by calculating "equivalents" for each field of the zbookmark.
3979  * zbookmarks outside of the meta-dnode use their own object and level, and
3980  * calculate the level 0 equivalent (the first L0 blkid that is contained in the
3981  * blocks this bookmark refers to) by multiplying their blkid by their span
3982  * (the number of L0 blocks contained within one block at their level).
3983  * zbookmarks inside the meta-dnode calculate their object equivalent
3984  * (which is L0equiv * dnodes per data block), use 0 for their L0equiv, and use
3985  * level + 1<<31 (any value larger than a level could ever be) for their level.
3986  * This causes them to always compare before a bookmark in their object
3987  * equivalent, compare appropriately to bookmarks in other objects, and to
3988  * compare appropriately to other bookmarks in the meta-dnode.
3989  */
3990 int
3991 zbookmark_compare(uint16_t dbss1, uint8_t ibs1, uint16_t dbss2, uint8_t ibs2,
3992     const zbookmark_phys_t *zb1, const zbookmark_phys_t *zb2)
3993 {
3994         /*
3995          * These variables represent the "equivalent" values for the zbookmark,
3996          * after converting zbookmarks inside the meta dnode to their
3997          * normal-object equivalents.
3998          */
3999         uint64_t zb1obj, zb2obj;
4000         uint64_t zb1L0, zb2L0;
4001         uint64_t zb1level, zb2level;
4002
4003         if (zb1->zb_object == zb2->zb_object &&
4004             zb1->zb_level == zb2->zb_level &&
4005             zb1->zb_blkid == zb2->zb_blkid)
4006                 return (0);
4007
4008         /*
4009          * BP_SPANB calculates the span in blocks.
4010          */
4011         zb1L0 = (zb1->zb_blkid) * BP_SPANB(ibs1, zb1->zb_level);
4012         zb2L0 = (zb2->zb_blkid) * BP_SPANB(ibs2, zb2->zb_level);
4013
4014         if (zb1->zb_object == DMU_META_DNODE_OBJECT) {
4015                 zb1obj = zb1L0 * (dbss1 << (SPA_MINBLOCKSHIFT - DNODE_SHIFT));
4016                 zb1L0 = 0;
4017                 zb1level = zb1->zb_level + COMPARE_META_LEVEL;
4018         } else {
4019                 zb1obj = zb1->zb_object;
4020                 zb1level = zb1->zb_level;
4021         }
4022
4023         if (zb2->zb_object == DMU_META_DNODE_OBJECT) {
4024                 zb2obj = zb2L0 * (dbss2 << (SPA_MINBLOCKSHIFT - DNODE_SHIFT));
4025                 zb2L0 = 0;
4026                 zb2level = zb2->zb_level + COMPARE_META_LEVEL;
4027         } else {
4028                 zb2obj = zb2->zb_object;
4029                 zb2level = zb2->zb_level;
4030         }
4031
4032         /* Now that we have a canonical representation, do the comparison. */
4033         if (zb1obj != zb2obj)
4034                 return (zb1obj < zb2obj ? -1 : 1);
4035         else if (zb1L0 != zb2L0)
4036                 return (zb1L0 < zb2L0 ? -1 : 1);
4037         else if (zb1level != zb2level)
4038                 return (zb1level > zb2level ? -1 : 1);
4039         /*
4040          * This can (theoretically) happen if the bookmarks have the same object
4041          * and level, but different blkids, if the block sizes are not the same.
4042          * There is presently no way to change the indirect block sizes
4043          */
4044         return (0);
4045 }
4046
4047 /*
4048  *  This function checks the following: given that last_block is the place that
4049  *  our traversal stopped last time, does that guarantee that we've visited
4050  *  every node under subtree_root?  Therefore, we can't just use the raw output
4051  *  of zbookmark_compare.  We have to pass in a modified version of
4052  *  subtree_root; by incrementing the block id, and then checking whether
4053  *  last_block is before or equal to that, we can tell whether or not having
4054  *  visited last_block implies that all of subtree_root's children have been
4055  *  visited.
4056  */
4057 boolean_t
4058 zbookmark_subtree_completed(const dnode_phys_t *dnp,
4059     const zbookmark_phys_t *subtree_root, const zbookmark_phys_t *last_block)
4060 {
4061         zbookmark_phys_t mod_zb = *subtree_root;
4062         mod_zb.zb_blkid++;
4063         ASSERT(last_block->zb_level == 0);
4064
4065         /* The objset_phys_t isn't before anything. */
4066         if (dnp == NULL)
4067                 return (B_FALSE);
4068
4069         /*
4070          * We pass in 1ULL << (DNODE_BLOCK_SHIFT - SPA_MINBLOCKSHIFT) for the
4071          * data block size in sectors, because that variable is only used if
4072          * the bookmark refers to a block in the meta-dnode.  Since we don't
4073          * know without examining it what object it refers to, and there's no
4074          * harm in passing in this value in other cases, we always pass it in.
4075          *
4076          * We pass in 0 for the indirect block size shift because zb2 must be
4077          * level 0.  The indirect block size is only used to calculate the span
4078          * of the bookmark, but since the bookmark must be level 0, the span is
4079          * always 1, so the math works out.
4080          *
4081          * If you make changes to how the zbookmark_compare code works, be sure
4082          * to make sure that this code still works afterwards.
4083          */
4084         return (zbookmark_compare(dnp->dn_datablkszsec, dnp->dn_indblkshift,
4085             1ULL << (DNODE_BLOCK_SHIFT - SPA_MINBLOCKSHIFT), 0, &mod_zb,
4086             last_block) <= 0);
4087 }