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