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