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