1 /*
   2  * CDDL HEADER START
   3  *
   4  * The contents of this file are subject to the terms of the
   5  * Common Development and Distribution License (the "License").
   6  * You may not use this file except in compliance with the License.
   7  *
   8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
   9  * or http://www.opensolaris.org/os/licensing.
  10  * See the License for the specific language governing permissions
  11  * and limitations under the License.
  12  *
  13  * When distributing Covered Code, include this CDDL HEADER in each
  14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
  15  * If applicable, add the following below this CDDL HEADER, with the
  16  * fields enclosed by brackets "[]" replaced with your own identifying
  17  * information: Portions Copyright [yyyy] [name of copyright owner]
  18  *
  19  * CDDL HEADER END
  20  */
  21 /*
  22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
  23  * Copyright (c) 2011, 2014 by Delphix. All rights reserved.
  24  * Copyright (c) 2011 Nexenta Systems, Inc. All rights reserved.
  25  * Copyright 2013 Joyent, Inc. All rights reserved.
  26  */
  27 
  28 #include <sys/zfs_context.h>
  29 #include <sys/fm/fs/zfs.h>
  30 #include <sys/spa.h>
  31 #include <sys/txg.h>
  32 #include <sys/spa_impl.h>
  33 #include <sys/vdev_impl.h>
  34 #include <sys/zio_impl.h>
  35 #include <sys/zio_compress.h>
  36 #include <sys/zio_checksum.h>
  37 #include <sys/dmu_objset.h>
  38 #include <sys/arc.h>
  39 #include <sys/ddt.h>
  40 #include <sys/zfs_zone.h>
  41 #include <sys/zfeature.h>
  42 
  43 /*
  44  * ==========================================================================
  45  * I/O type descriptions
  46  * ==========================================================================
  47  */
  48 const char *zio_type_name[ZIO_TYPES] = {
  49         "zio_null", "zio_read", "zio_write", "zio_free", "zio_claim",
  50         "zio_ioctl"
  51 };
  52 
  53 /*
  54  * ==========================================================================
  55  * I/O kmem caches
  56  * ==========================================================================
  57  */
  58 kmem_cache_t *zio_cache;
  59 kmem_cache_t *zio_link_cache;
  60 kmem_cache_t *zio_buf_cache[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT];
  61 kmem_cache_t *zio_data_buf_cache[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT];
  62 
  63 #ifdef _KERNEL
  64 extern vmem_t *zio_alloc_arena;
  65 #endif
  66 extern int zfs_mg_alloc_failures;
  67 
  68 /*
  69  * The following actions directly effect the spa's sync-to-convergence logic.
  70  * The values below define the sync pass when we start performing the action.
  71  * Care should be taken when changing these values as they directly impact
  72  * spa_sync() performance. Tuning these values may introduce subtle performance
  73  * pathologies and should only be done in the context of performance analysis.
  74  * These tunables will eventually be removed and replaced with #defines once
  75  * enough analysis has been done to determine optimal values.
  76  *
  77  * The 'zfs_sync_pass_deferred_free' pass must be greater than 1 to ensure that
  78  * regular blocks are not deferred.
  79  */
  80 int zfs_sync_pass_deferred_free = 2; /* defer frees starting in this pass */
  81 int zfs_sync_pass_dont_compress = 5; /* don't compress starting in this pass */
  82 int zfs_sync_pass_rewrite = 2; /* rewrite new bps starting in this pass */
  83 
  84 /*
  85  * An allocating zio is one that either currently has the DVA allocate
  86  * stage set or will have it later in its lifetime.
  87  */
  88 #define IO_IS_ALLOCATING(zio) ((zio)->io_orig_pipeline & ZIO_STAGE_DVA_ALLOCATE)
  89 
  90 boolean_t       zio_requeue_io_start_cut_in_line = B_TRUE;
  91 
  92 #ifdef ZFS_DEBUG
  93 int zio_buf_debug_limit = 16384;
  94 #else
  95 int zio_buf_debug_limit = 0;
  96 #endif
  97 
  98 void
  99 zio_init(void)
 100 {
 101         size_t c;
 102         vmem_t *data_alloc_arena = NULL;
 103 
 104 #ifdef _KERNEL
 105         data_alloc_arena = zio_alloc_arena;
 106 #endif
 107         zio_cache = kmem_cache_create("zio_cache",
 108             sizeof (zio_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
 109         zio_link_cache = kmem_cache_create("zio_link_cache",
 110             sizeof (zio_link_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
 111 
 112         /*
 113          * For small buffers, we want a cache for each multiple of
 114          * SPA_MINBLOCKSIZE.  For medium-size buffers, we want a cache
 115          * for each quarter-power of 2.  For large buffers, we want
 116          * a cache for each multiple of PAGESIZE.
 117          */
 118         for (c = 0; c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; c++) {
 119                 size_t size = (c + 1) << SPA_MINBLOCKSHIFT;
 120                 size_t p2 = size;
 121                 size_t align = 0;
 122                 size_t cflags = (size > zio_buf_debug_limit) ? KMC_NODEBUG : 0;
 123 
 124                 while (p2 & (p2 - 1))
 125                         p2 &= p2 - 1;
 126 
 127 #ifndef _KERNEL
 128                 /*
 129                  * If we are using watchpoints, put each buffer on its own page,
 130                  * to eliminate the performance overhead of trapping to the
 131                  * kernel when modifying a non-watched buffer that shares the
 132                  * page with a watched buffer.
 133                  */
 134                 if (arc_watch && !IS_P2ALIGNED(size, PAGESIZE))
 135                         continue;
 136 #endif
 137                 if (size <= 4 * SPA_MINBLOCKSIZE) {
 138                         align = SPA_MINBLOCKSIZE;
 139                 } else if (IS_P2ALIGNED(size, PAGESIZE)) {
 140                         align = PAGESIZE;
 141                 } else if (IS_P2ALIGNED(size, p2 >> 2)) {
 142                         align = p2 >> 2;
 143                 }
 144 
 145                 if (align != 0) {
 146                         char name[36];
 147                         (void) sprintf(name, "zio_buf_%lu", (ulong_t)size);
 148                         zio_buf_cache[c] = kmem_cache_create(name, size,
 149                             align, NULL, NULL, NULL, NULL, NULL, cflags);
 150 
 151                         /*
 152                          * Since zio_data bufs do not appear in crash dumps, we
 153                          * pass KMC_NOTOUCH so that no allocator metadata is
 154                          * stored with the buffers.
 155                          */
 156                         (void) sprintf(name, "zio_data_buf_%lu", (ulong_t)size);
 157                         zio_data_buf_cache[c] = kmem_cache_create(name, size,
 158                             align, NULL, NULL, NULL, NULL, data_alloc_arena,
 159                             cflags | KMC_NOTOUCH);
 160                 }
 161         }
 162 
 163         while (--c != 0) {
 164                 ASSERT(zio_buf_cache[c] != NULL);
 165                 if (zio_buf_cache[c - 1] == NULL)
 166                         zio_buf_cache[c - 1] = zio_buf_cache[c];
 167 
 168                 ASSERT(zio_data_buf_cache[c] != NULL);
 169                 if (zio_data_buf_cache[c - 1] == NULL)
 170                         zio_data_buf_cache[c - 1] = zio_data_buf_cache[c];
 171         }
 172 
 173         /*
 174          * The zio write taskqs have 1 thread per cpu, allow 1/2 of the taskqs
 175          * to fail 3 times per txg or 8 failures, whichever is greater.
 176          */
 177         if (zfs_mg_alloc_failures == 0)
 178                 zfs_mg_alloc_failures = MAX((3 * max_ncpus / 2), 8);
 179 
 180         zio_inject_init();
 181 }
 182 
 183 void
 184 zio_fini(void)
 185 {
 186         size_t c;
 187         kmem_cache_t *last_cache = NULL;
 188         kmem_cache_t *last_data_cache = NULL;
 189 
 190         for (c = 0; c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; c++) {
 191                 if (zio_buf_cache[c] != last_cache) {
 192                         last_cache = zio_buf_cache[c];
 193                         kmem_cache_destroy(zio_buf_cache[c]);
 194                 }
 195                 zio_buf_cache[c] = NULL;
 196 
 197                 if (zio_data_buf_cache[c] != last_data_cache) {
 198                         last_data_cache = zio_data_buf_cache[c];
 199                         kmem_cache_destroy(zio_data_buf_cache[c]);
 200                 }
 201                 zio_data_buf_cache[c] = NULL;
 202         }
 203 
 204         kmem_cache_destroy(zio_link_cache);
 205         kmem_cache_destroy(zio_cache);
 206 
 207         zio_inject_fini();
 208 }
 209 
 210 /*
 211  * ==========================================================================
 212  * Allocate and free I/O buffers
 213  * ==========================================================================
 214  */
 215 
 216 /*
 217  * Use zio_buf_alloc to allocate ZFS metadata.  This data will appear in a
 218  * crashdump if the kernel panics, so use it judiciously.  Obviously, it's
 219  * useful to inspect ZFS metadata, but if possible, we should avoid keeping
 220  * excess / transient data in-core during a crashdump.
 221  */
 222 void *
 223 zio_buf_alloc(size_t size)
 224 {
 225         size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
 226 
 227         ASSERT(c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
 228 
 229         return (kmem_cache_alloc(zio_buf_cache[c], KM_PUSHPAGE));
 230 }
 231 
 232 /*
 233  * Use zio_data_buf_alloc to allocate data.  The data will not appear in a
 234  * crashdump if the kernel panics.  This exists so that we will limit the amount
 235  * of ZFS data that shows up in a kernel crashdump.  (Thus reducing the amount
 236  * of kernel heap dumped to disk when the kernel panics)
 237  */
 238 void *
 239 zio_data_buf_alloc(size_t size)
 240 {
 241         size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
 242 
 243         ASSERT(c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
 244 
 245         return (kmem_cache_alloc(zio_data_buf_cache[c], KM_PUSHPAGE));
 246 }
 247 
 248 void
 249 zio_buf_free(void *buf, size_t size)
 250 {
 251         size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
 252 
 253         ASSERT(c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
 254 
 255         kmem_cache_free(zio_buf_cache[c], buf);
 256 }
 257 
 258 void
 259 zio_data_buf_free(void *buf, size_t size)
 260 {
 261         size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
 262 
 263         ASSERT(c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
 264 
 265         kmem_cache_free(zio_data_buf_cache[c], buf);
 266 }
 267 
 268 /*
 269  * ==========================================================================
 270  * Push and pop I/O transform buffers
 271  * ==========================================================================
 272  */
 273 static void
 274 zio_push_transform(zio_t *zio, void *data, uint64_t size, uint64_t bufsize,
 275         zio_transform_func_t *transform)
 276 {
 277         zio_transform_t *zt = kmem_alloc(sizeof (zio_transform_t), KM_SLEEP);
 278 
 279         zt->zt_orig_data = zio->io_data;
 280         zt->zt_orig_size = zio->io_size;
 281         zt->zt_bufsize = bufsize;
 282         zt->zt_transform = transform;
 283 
 284         zt->zt_next = zio->io_transform_stack;
 285         zio->io_transform_stack = zt;
 286 
 287         zio->io_data = data;
 288         zio->io_size = size;
 289 }
 290 
 291 static void
 292 zio_pop_transforms(zio_t *zio)
 293 {
 294         zio_transform_t *zt;
 295 
 296         while ((zt = zio->io_transform_stack) != NULL) {
 297                 if (zt->zt_transform != NULL)
 298                         zt->zt_transform(zio,
 299                             zt->zt_orig_data, zt->zt_orig_size);
 300 
 301                 if (zt->zt_bufsize != 0)
 302                         zio_buf_free(zio->io_data, zt->zt_bufsize);
 303 
 304                 zio->io_data = zt->zt_orig_data;
 305                 zio->io_size = zt->zt_orig_size;
 306                 zio->io_transform_stack = zt->zt_next;
 307 
 308                 kmem_free(zt, sizeof (zio_transform_t));
 309         }
 310 }
 311 
 312 /*
 313  * ==========================================================================
 314  * I/O transform callbacks for subblocks and decompression
 315  * ==========================================================================
 316  */
 317 static void
 318 zio_subblock(zio_t *zio, void *data, uint64_t size)
 319 {
 320         ASSERT(zio->io_size > size);
 321 
 322         if (zio->io_type == ZIO_TYPE_READ)
 323                 bcopy(zio->io_data, data, size);
 324 }
 325 
 326 static void
 327 zio_decompress(zio_t *zio, void *data, uint64_t size)
 328 {
 329         if (zio->io_error == 0 &&
 330             zio_decompress_data(BP_GET_COMPRESS(zio->io_bp),
 331             zio->io_data, data, zio->io_size, size) != 0)
 332                 zio->io_error = SET_ERROR(EIO);
 333 }
 334 
 335 /*
 336  * ==========================================================================
 337  * I/O parent/child relationships and pipeline interlocks
 338  * ==========================================================================
 339  */
 340 /*
 341  * NOTE - Callers to zio_walk_parents() and zio_walk_children must
 342  *        continue calling these functions until they return NULL.
 343  *        Otherwise, the next caller will pick up the list walk in
 344  *        some indeterminate state.  (Otherwise every caller would
 345  *        have to pass in a cookie to keep the state represented by
 346  *        io_walk_link, which gets annoying.)
 347  */
 348 zio_t *
 349 zio_walk_parents(zio_t *cio)
 350 {
 351         zio_link_t *zl = cio->io_walk_link;
 352         list_t *pl = &cio->io_parent_list;
 353 
 354         zl = (zl == NULL) ? list_head(pl) : list_next(pl, zl);
 355         cio->io_walk_link = zl;
 356 
 357         if (zl == NULL)
 358                 return (NULL);
 359 
 360         ASSERT(zl->zl_child == cio);
 361         return (zl->zl_parent);
 362 }
 363 
 364 zio_t *
 365 zio_walk_children(zio_t *pio)
 366 {
 367         zio_link_t *zl = pio->io_walk_link;
 368         list_t *cl = &pio->io_child_list;
 369 
 370         zl = (zl == NULL) ? list_head(cl) : list_next(cl, zl);
 371         pio->io_walk_link = zl;
 372 
 373         if (zl == NULL)
 374                 return (NULL);
 375 
 376         ASSERT(zl->zl_parent == pio);
 377         return (zl->zl_child);
 378 }
 379 
 380 zio_t *
 381 zio_unique_parent(zio_t *cio)
 382 {
 383         zio_t *pio = zio_walk_parents(cio);
 384 
 385         VERIFY(zio_walk_parents(cio) == NULL);
 386         return (pio);
 387 }
 388 
 389 void
 390 zio_add_child(zio_t *pio, zio_t *cio)
 391 {
 392         zio_link_t *zl = kmem_cache_alloc(zio_link_cache, KM_SLEEP);
 393 
 394         /*
 395          * Logical I/Os can have logical, gang, or vdev children.
 396          * Gang I/Os can have gang or vdev children.
 397          * Vdev I/Os can only have vdev children.
 398          * The following ASSERT captures all of these constraints.
 399          */
 400         ASSERT(cio->io_child_type <= pio->io_child_type);
 401 
 402         zl->zl_parent = pio;
 403         zl->zl_child = cio;
 404 
 405         mutex_enter(&cio->io_lock);
 406         mutex_enter(&pio->io_lock);
 407 
 408         ASSERT(pio->io_state[ZIO_WAIT_DONE] == 0);
 409 
 410         for (int w = 0; w < ZIO_WAIT_TYPES; w++)
 411                 pio->io_children[cio->io_child_type][w] += !cio->io_state[w];
 412 
 413         list_insert_head(&pio->io_child_list, zl);
 414         list_insert_head(&cio->io_parent_list, zl);
 415 
 416         pio->io_child_count++;
 417         cio->io_parent_count++;
 418 
 419         mutex_exit(&pio->io_lock);
 420         mutex_exit(&cio->io_lock);
 421 }
 422 
 423 static void
 424 zio_remove_child(zio_t *pio, zio_t *cio, zio_link_t *zl)
 425 {
 426         ASSERT(zl->zl_parent == pio);
 427         ASSERT(zl->zl_child == cio);
 428 
 429         mutex_enter(&cio->io_lock);
 430         mutex_enter(&pio->io_lock);
 431 
 432         list_remove(&pio->io_child_list, zl);
 433         list_remove(&cio->io_parent_list, zl);
 434 
 435         pio->io_child_count--;
 436         cio->io_parent_count--;
 437 
 438         mutex_exit(&pio->io_lock);
 439         mutex_exit(&cio->io_lock);
 440 
 441         kmem_cache_free(zio_link_cache, zl);
 442 }
 443 
 444 static boolean_t
 445 zio_wait_for_children(zio_t *zio, enum zio_child child, enum zio_wait_type wait)
 446 {
 447         uint64_t *countp = &zio->io_children[child][wait];
 448         boolean_t waiting = B_FALSE;
 449 
 450         mutex_enter(&zio->io_lock);
 451         ASSERT(zio->io_stall == NULL);
 452         if (*countp != 0) {
 453                 zio->io_stage >>= 1;
 454                 zio->io_stall = countp;
 455                 waiting = B_TRUE;
 456         }
 457         mutex_exit(&zio->io_lock);
 458 
 459         return (waiting);
 460 }
 461 
 462 static void
 463 zio_notify_parent(zio_t *pio, zio_t *zio, enum zio_wait_type wait)
 464 {
 465         uint64_t *countp = &pio->io_children[zio->io_child_type][wait];
 466         int *errorp = &pio->io_child_error[zio->io_child_type];
 467 
 468         mutex_enter(&pio->io_lock);
 469         if (zio->io_error && !(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE))
 470                 *errorp = zio_worst_error(*errorp, zio->io_error);
 471         pio->io_reexecute |= zio->io_reexecute;
 472         ASSERT3U(*countp, >, 0);
 473 
 474         (*countp)--;
 475 
 476         if (*countp == 0 && pio->io_stall == countp) {
 477                 pio->io_stall = NULL;
 478                 mutex_exit(&pio->io_lock);
 479                 zio_execute(pio);
 480         } else {
 481                 mutex_exit(&pio->io_lock);
 482         }
 483 }
 484 
 485 static void
 486 zio_inherit_child_errors(zio_t *zio, enum zio_child c)
 487 {
 488         if (zio->io_child_error[c] != 0 && zio->io_error == 0)
 489                 zio->io_error = zio->io_child_error[c];
 490 }
 491 
 492 /*
 493  * ==========================================================================
 494  * Create the various types of I/O (read, write, free, etc)
 495  * ==========================================================================
 496  */
 497 static zio_t *
 498 zio_create(zio_t *pio, spa_t *spa, uint64_t txg, const blkptr_t *bp,
 499     void *data, uint64_t size, zio_done_func_t *done, void *private,
 500     zio_type_t type, zio_priority_t priority, enum zio_flag flags,
 501     vdev_t *vd, uint64_t offset, const zbookmark_t *zb,
 502     enum zio_stage stage, enum zio_stage pipeline)
 503 {
 504         zio_t *zio;
 505 
 506         ASSERT3U(size, <=, SPA_MAXBLOCKSIZE);
 507         ASSERT(P2PHASE(size, SPA_MINBLOCKSIZE) == 0);
 508         ASSERT(P2PHASE(offset, SPA_MINBLOCKSIZE) == 0);
 509 
 510         ASSERT(!vd || spa_config_held(spa, SCL_STATE_ALL, RW_READER));
 511         ASSERT(!bp || !(flags & ZIO_FLAG_CONFIG_WRITER));
 512         ASSERT(vd || stage == ZIO_STAGE_OPEN);
 513 
 514         zio = kmem_cache_alloc(zio_cache, KM_SLEEP);
 515         bzero(zio, sizeof (zio_t));
 516 
 517         mutex_init(&zio->io_lock, NULL, MUTEX_DEFAULT, NULL);
 518         cv_init(&zio->io_cv, NULL, CV_DEFAULT, NULL);
 519 
 520         list_create(&zio->io_parent_list, sizeof (zio_link_t),
 521             offsetof(zio_link_t, zl_parent_node));
 522         list_create(&zio->io_child_list, sizeof (zio_link_t),
 523             offsetof(zio_link_t, zl_child_node));
 524 
 525         if (vd != NULL)
 526                 zio->io_child_type = ZIO_CHILD_VDEV;
 527         else if (flags & ZIO_FLAG_GANG_CHILD)
 528                 zio->io_child_type = ZIO_CHILD_GANG;
 529         else if (flags & ZIO_FLAG_DDT_CHILD)
 530                 zio->io_child_type = ZIO_CHILD_DDT;
 531         else
 532                 zio->io_child_type = ZIO_CHILD_LOGICAL;
 533 
 534         if (bp != NULL) {
 535                 zio->io_bp = (blkptr_t *)bp;
 536                 zio->io_bp_copy = *bp;
 537                 zio->io_bp_orig = *bp;
 538                 if (type != ZIO_TYPE_WRITE ||
 539                     zio->io_child_type == ZIO_CHILD_DDT)
 540                         zio->io_bp = &zio->io_bp_copy;        /* so caller can free */
 541                 if (zio->io_child_type == ZIO_CHILD_LOGICAL)
 542                         zio->io_logical = zio;
 543                 if (zio->io_child_type > ZIO_CHILD_GANG && BP_IS_GANG(bp))
 544                         pipeline |= ZIO_GANG_STAGES;
 545         }
 546 
 547         zio->io_spa = spa;
 548         zio->io_txg = txg;
 549         zio->io_done = done;
 550         zio->io_private = private;
 551         zio->io_type = type;
 552         zio->io_priority = priority;
 553         zio->io_vd = vd;
 554         zio->io_offset = offset;
 555         zio->io_orig_data = zio->io_data = data;
 556         zio->io_orig_size = zio->io_size = size;
 557         zio->io_orig_flags = zio->io_flags = flags;
 558         zio->io_orig_stage = zio->io_stage = stage;
 559         zio->io_orig_pipeline = zio->io_pipeline = pipeline;
 560 
 561         zio->io_state[ZIO_WAIT_READY] = (stage >= ZIO_STAGE_READY);
 562         zio->io_state[ZIO_WAIT_DONE] = (stage >= ZIO_STAGE_DONE);
 563 
 564         if (zb != NULL)
 565                 zio->io_bookmark = *zb;
 566 
 567         if (pio != NULL) {
 568                 zio->io_zoneid = pio->io_zoneid;
 569                 if (zio->io_logical == NULL)
 570                         zio->io_logical = pio->io_logical;
 571                 if (zio->io_child_type == ZIO_CHILD_GANG)
 572                         zio->io_gang_leader = pio->io_gang_leader;
 573                 zio_add_child(pio, zio);
 574         } else {
 575                 zfs_zone_zio_init(zio);
 576         }
 577 
 578         return (zio);
 579 }
 580 
 581 static void
 582 zio_destroy(zio_t *zio)
 583 {
 584         list_destroy(&zio->io_parent_list);
 585         list_destroy(&zio->io_child_list);
 586         mutex_destroy(&zio->io_lock);
 587         cv_destroy(&zio->io_cv);
 588         kmem_cache_free(zio_cache, zio);
 589 }
 590 
 591 zio_t *
 592 zio_null(zio_t *pio, spa_t *spa, vdev_t *vd, zio_done_func_t *done,
 593     void *private, enum zio_flag flags)
 594 {
 595         zio_t *zio;
 596 
 597         zio = zio_create(pio, spa, 0, NULL, NULL, 0, done, private,
 598             ZIO_TYPE_NULL, ZIO_PRIORITY_NOW, flags, vd, 0, NULL,
 599             ZIO_STAGE_OPEN, ZIO_INTERLOCK_PIPELINE);
 600 
 601         return (zio);
 602 }
 603 
 604 zio_t *
 605 zio_root(spa_t *spa, zio_done_func_t *done, void *private, enum zio_flag flags)
 606 {
 607         return (zio_null(NULL, spa, NULL, done, private, flags));
 608 }
 609 
 610 zio_t *
 611 zio_read(zio_t *pio, spa_t *spa, const blkptr_t *bp,
 612     void *data, uint64_t size, zio_done_func_t *done, void *private,
 613     zio_priority_t priority, enum zio_flag flags, const zbookmark_t *zb)
 614 {
 615         zio_t *zio;
 616 
 617         zio = zio_create(pio, spa, BP_PHYSICAL_BIRTH(bp), bp,
 618             data, size, done, private,
 619             ZIO_TYPE_READ, priority, flags, NULL, 0, zb,
 620             ZIO_STAGE_OPEN, (flags & ZIO_FLAG_DDT_CHILD) ?
 621             ZIO_DDT_CHILD_READ_PIPELINE : ZIO_READ_PIPELINE);
 622 
 623         return (zio);
 624 }
 625 
 626 zio_t *
 627 zio_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
 628     void *data, uint64_t size, const zio_prop_t *zp,
 629     zio_done_func_t *ready, zio_done_func_t *physdone, zio_done_func_t *done,
 630     void *private,
 631     zio_priority_t priority, enum zio_flag flags, const zbookmark_t *zb)
 632 {
 633         zio_t *zio;
 634 
 635         ASSERT(zp->zp_checksum >= ZIO_CHECKSUM_OFF &&
 636             zp->zp_checksum < ZIO_CHECKSUM_FUNCTIONS &&
 637             zp->zp_compress >= ZIO_COMPRESS_OFF &&
 638             zp->zp_compress < ZIO_COMPRESS_FUNCTIONS &&
 639             DMU_OT_IS_VALID(zp->zp_type) &&
 640             zp->zp_level < 32 &&
 641             zp->zp_copies > 0 &&
 642             zp->zp_copies <= spa_max_replication(spa));
 643 
 644         zio = zio_create(pio, spa, txg, bp, data, size, done, private,
 645             ZIO_TYPE_WRITE, priority, flags, NULL, 0, zb,
 646             ZIO_STAGE_OPEN, (flags & ZIO_FLAG_DDT_CHILD) ?
 647             ZIO_DDT_CHILD_WRITE_PIPELINE : ZIO_WRITE_PIPELINE);
 648 
 649         zio->io_ready = ready;
 650         zio->io_physdone = physdone;
 651         zio->io_prop = *zp;
 652 
 653         return (zio);
 654 }
 655 
 656 zio_t *
 657 zio_rewrite(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, void *data,
 658     uint64_t size, zio_done_func_t *done, void *private,
 659     zio_priority_t priority, enum zio_flag flags, zbookmark_t *zb)
 660 {
 661         zio_t *zio;
 662 
 663         zio = zio_create(pio, spa, txg, bp, data, size, done, private,
 664             ZIO_TYPE_WRITE, priority, flags, NULL, 0, zb,
 665             ZIO_STAGE_OPEN, ZIO_REWRITE_PIPELINE);
 666 
 667         return (zio);
 668 }
 669 
 670 void
 671 zio_write_override(zio_t *zio, blkptr_t *bp, int copies, boolean_t nopwrite)
 672 {
 673         ASSERT(zio->io_type == ZIO_TYPE_WRITE);
 674         ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
 675         ASSERT(zio->io_stage == ZIO_STAGE_OPEN);
 676         ASSERT(zio->io_txg == spa_syncing_txg(zio->io_spa));
 677 
 678         /*
 679          * We must reset the io_prop to match the values that existed
 680          * when the bp was first written by dmu_sync() keeping in mind
 681          * that nopwrite and dedup are mutually exclusive.
 682          */
 683         zio->io_prop.zp_dedup = nopwrite ? B_FALSE : zio->io_prop.zp_dedup;
 684         zio->io_prop.zp_nopwrite = nopwrite;
 685         zio->io_prop.zp_copies = copies;
 686         zio->io_bp_override = bp;
 687 }
 688 
 689 void
 690 zio_free(spa_t *spa, uint64_t txg, const blkptr_t *bp)
 691 {
 692         metaslab_check_free(spa, bp);
 693 
 694         /*
 695          * Frees that are for the currently-syncing txg, are not going to be
 696          * deferred, and which will not need to do a read (i.e. not GANG or
 697          * DEDUP), can be processed immediately.  Otherwise, put them on the
 698          * in-memory list for later processing.
 699          */
 700         if (BP_IS_GANG(bp) || BP_GET_DEDUP(bp) ||
 701             txg != spa->spa_syncing_txg ||
 702             spa_sync_pass(spa) >= zfs_sync_pass_deferred_free) {
 703                 bplist_append(&spa->spa_free_bplist[txg & TXG_MASK], bp);
 704         } else {
 705                 VERIFY0(zio_wait(zio_free_sync(NULL, spa, txg, bp, 0)));
 706         }
 707 }
 708 
 709 zio_t *
 710 zio_free_sync(zio_t *pio, spa_t *spa, uint64_t txg, const blkptr_t *bp,
 711     enum zio_flag flags)
 712 {
 713         zio_t *zio;
 714         enum zio_stage stage = ZIO_FREE_PIPELINE;
 715 
 716         dprintf_bp(bp, "freeing in txg %llu, pass %u",
 717             (longlong_t)txg, spa->spa_sync_pass);
 718 
 719         ASSERT(!BP_IS_HOLE(bp));
 720         ASSERT(spa_syncing_txg(spa) == txg);
 721         ASSERT(spa_sync_pass(spa) < zfs_sync_pass_deferred_free);
 722 
 723         metaslab_check_free(spa, bp);
 724         arc_freed(spa, bp);
 725 
 726         /*
 727          * GANG and DEDUP blocks can induce a read (for the gang block header,
 728          * or the DDT), so issue them asynchronously so that this thread is
 729          * not tied up.
 730          */
 731         if (BP_IS_GANG(bp) || BP_GET_DEDUP(bp))
 732                 stage |= ZIO_STAGE_ISSUE_ASYNC;
 733 
 734         zio = zio_create(pio, spa, txg, bp, NULL, BP_GET_PSIZE(bp),
 735             NULL, NULL, ZIO_TYPE_FREE, ZIO_PRIORITY_NOW, flags,
 736             NULL, 0, NULL, ZIO_STAGE_OPEN, stage);
 737 
 738 
 739         return (zio);
 740 }
 741 
 742 zio_t *
 743 zio_claim(zio_t *pio, spa_t *spa, uint64_t txg, const blkptr_t *bp,
 744     zio_done_func_t *done, void *private, enum zio_flag flags)
 745 {
 746         zio_t *zio;
 747 
 748         /*
 749          * A claim is an allocation of a specific block.  Claims are needed
 750          * to support immediate writes in the intent log.  The issue is that
 751          * immediate writes contain committed data, but in a txg that was
 752          * *not* committed.  Upon opening the pool after an unclean shutdown,
 753          * the intent log claims all blocks that contain immediate write data
 754          * so that the SPA knows they're in use.
 755          *
 756          * All claims *must* be resolved in the first txg -- before the SPA
 757          * starts allocating blocks -- so that nothing is allocated twice.
 758          * If txg == 0 we just verify that the block is claimable.
 759          */
 760         ASSERT3U(spa->spa_uberblock.ub_rootbp.blk_birth, <, spa_first_txg(spa));
 761         ASSERT(txg == spa_first_txg(spa) || txg == 0);
 762         ASSERT(!BP_GET_DEDUP(bp) || !spa_writeable(spa));       /* zdb(1M) */
 763 
 764         zio = zio_create(pio, spa, txg, bp, NULL, BP_GET_PSIZE(bp),
 765             done, private, ZIO_TYPE_CLAIM, ZIO_PRIORITY_NOW, flags,
 766             NULL, 0, NULL, ZIO_STAGE_OPEN, ZIO_CLAIM_PIPELINE);
 767 
 768         return (zio);
 769 }
 770 
 771 zio_t *
 772 zio_ioctl(zio_t *pio, spa_t *spa, vdev_t *vd, int cmd,
 773     zio_done_func_t *done, void *private, enum zio_flag flags)
 774 {
 775         zio_t *zio;
 776         int c;
 777 
 778         if (vd->vdev_children == 0) {
 779                 zio = zio_create(pio, spa, 0, NULL, NULL, 0, done, private,
 780                     ZIO_TYPE_IOCTL, ZIO_PRIORITY_NOW, flags, vd, 0, NULL,
 781                     ZIO_STAGE_OPEN, ZIO_IOCTL_PIPELINE);
 782 
 783                 zio->io_cmd = cmd;
 784         } else {
 785                 zio = zio_null(pio, spa, NULL, NULL, NULL, flags);
 786 
 787                 for (c = 0; c < vd->vdev_children; c++)
 788                         zio_nowait(zio_ioctl(zio, spa, vd->vdev_child[c], cmd,
 789                             done, private, flags));
 790         }
 791 
 792         return (zio);
 793 }
 794 
 795 zio_t *
 796 zio_read_phys(zio_t *pio, vdev_t *vd, uint64_t offset, uint64_t size,
 797     void *data, int checksum, zio_done_func_t *done, void *private,
 798     zio_priority_t priority, enum zio_flag flags, boolean_t labels)
 799 {
 800         zio_t *zio;
 801 
 802         ASSERT(vd->vdev_children == 0);
 803         ASSERT(!labels || offset + size <= VDEV_LABEL_START_SIZE ||
 804             offset >= vd->vdev_psize - VDEV_LABEL_END_SIZE);
 805         ASSERT3U(offset + size, <=, vd->vdev_psize);
 806 
 807         zio = zio_create(pio, vd->vdev_spa, 0, NULL, data, size, done, private,
 808             ZIO_TYPE_READ, priority, flags, vd, offset, NULL,
 809             ZIO_STAGE_OPEN, ZIO_READ_PHYS_PIPELINE);
 810 
 811         zio->io_prop.zp_checksum = checksum;
 812 
 813         return (zio);
 814 }
 815 
 816 zio_t *
 817 zio_write_phys(zio_t *pio, vdev_t *vd, uint64_t offset, uint64_t size,
 818     void *data, int checksum, zio_done_func_t *done, void *private,
 819     zio_priority_t priority, enum zio_flag flags, boolean_t labels)
 820 {
 821         zio_t *zio;
 822 
 823         ASSERT(vd->vdev_children == 0);
 824         ASSERT(!labels || offset + size <= VDEV_LABEL_START_SIZE ||
 825             offset >= vd->vdev_psize - VDEV_LABEL_END_SIZE);
 826         ASSERT3U(offset + size, <=, vd->vdev_psize);
 827 
 828         zio = zio_create(pio, vd->vdev_spa, 0, NULL, data, size, done, private,
 829             ZIO_TYPE_WRITE, priority, flags, vd, offset, NULL,
 830             ZIO_STAGE_OPEN, ZIO_WRITE_PHYS_PIPELINE);
 831 
 832         zio->io_prop.zp_checksum = checksum;
 833 
 834         if (zio_checksum_table[checksum].ci_eck) {
 835                 /*
 836                  * zec checksums are necessarily destructive -- they modify
 837                  * the end of the write buffer to hold the verifier/checksum.
 838                  * Therefore, we must make a local copy in case the data is
 839                  * being written to multiple places in parallel.
 840                  */
 841                 void *wbuf = zio_buf_alloc(size);
 842                 bcopy(data, wbuf, size);
 843                 zio_push_transform(zio, wbuf, size, size, NULL);
 844         }
 845 
 846         return (zio);
 847 }
 848 
 849 /*
 850  * Create a child I/O to do some work for us.
 851  */
 852 zio_t *
 853 zio_vdev_child_io(zio_t *pio, blkptr_t *bp, vdev_t *vd, uint64_t offset,
 854         void *data, uint64_t size, int type, zio_priority_t priority,
 855         enum zio_flag flags, zio_done_func_t *done, void *private)
 856 {
 857         enum zio_stage pipeline = ZIO_VDEV_CHILD_PIPELINE;
 858         zio_t *zio;
 859 
 860         ASSERT(vd->vdev_parent ==
 861             (pio->io_vd ? pio->io_vd : pio->io_spa->spa_root_vdev));
 862 
 863         if (type == ZIO_TYPE_READ && bp != NULL) {
 864                 /*
 865                  * If we have the bp, then the child should perform the
 866                  * checksum and the parent need not.  This pushes error
 867                  * detection as close to the leaves as possible and
 868                  * eliminates redundant checksums in the interior nodes.
 869                  */
 870                 pipeline |= ZIO_STAGE_CHECKSUM_VERIFY;
 871                 pio->io_pipeline &= ~ZIO_STAGE_CHECKSUM_VERIFY;
 872         }
 873 
 874         if (vd->vdev_children == 0)
 875                 offset += VDEV_LABEL_START_SIZE;
 876 
 877         flags |= ZIO_VDEV_CHILD_FLAGS(pio) | ZIO_FLAG_DONT_PROPAGATE;
 878 
 879         /*
 880          * If we've decided to do a repair, the write is not speculative --
 881          * even if the original read was.
 882          */
 883         if (flags & ZIO_FLAG_IO_REPAIR)
 884                 flags &= ~ZIO_FLAG_SPECULATIVE;
 885 
 886         zio = zio_create(pio, pio->io_spa, pio->io_txg, bp, data, size,
 887             done, private, type, priority, flags, vd, offset, &pio->io_bookmark,
 888             ZIO_STAGE_VDEV_IO_START >> 1, pipeline);
 889 
 890         zio->io_physdone = pio->io_physdone;
 891         if (vd->vdev_ops->vdev_op_leaf && zio->io_logical != NULL)
 892                 zio->io_logical->io_phys_children++;
 893 
 894         return (zio);
 895 }
 896 
 897 zio_t *
 898 zio_vdev_delegated_io(vdev_t *vd, uint64_t offset, void *data, uint64_t size,
 899         int type, zio_priority_t priority, enum zio_flag flags,
 900         zio_done_func_t *done, void *private)
 901 {
 902         zio_t *zio;
 903 
 904         ASSERT(vd->vdev_ops->vdev_op_leaf);
 905 
 906         zio = zio_create(NULL, vd->vdev_spa, 0, NULL,
 907             data, size, done, private, type, priority,
 908             flags | ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_RETRY | ZIO_FLAG_DELEGATED,
 909             vd, offset, NULL,
 910             ZIO_STAGE_VDEV_IO_START >> 1, ZIO_VDEV_CHILD_PIPELINE);
 911 
 912         return (zio);
 913 }
 914 
 915 void
 916 zio_flush(zio_t *zio, vdev_t *vd)
 917 {
 918         zio_nowait(zio_ioctl(zio, zio->io_spa, vd, DKIOCFLUSHWRITECACHE,
 919             NULL, NULL,
 920             ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY));
 921 }
 922 
 923 void
 924 zio_shrink(zio_t *zio, uint64_t size)
 925 {
 926         ASSERT(zio->io_executor == NULL);
 927         ASSERT(zio->io_orig_size == zio->io_size);
 928         ASSERT(size <= zio->io_size);
 929 
 930         /*
 931          * We don't shrink for raidz because of problems with the
 932          * reconstruction when reading back less than the block size.
 933          * Note, BP_IS_RAIDZ() assumes no compression.
 934          */
 935         ASSERT(BP_GET_COMPRESS(zio->io_bp) == ZIO_COMPRESS_OFF);
 936         if (!BP_IS_RAIDZ(zio->io_bp))
 937                 zio->io_orig_size = zio->io_size = size;
 938 }
 939 
 940 /*
 941  * ==========================================================================
 942  * Prepare to read and write logical blocks
 943  * ==========================================================================
 944  */
 945 
 946 static int
 947 zio_read_bp_init(zio_t *zio)
 948 {
 949         blkptr_t *bp = zio->io_bp;
 950 
 951         if (BP_GET_COMPRESS(bp) != ZIO_COMPRESS_OFF &&
 952             zio->io_child_type == ZIO_CHILD_LOGICAL &&
 953             !(zio->io_flags & ZIO_FLAG_RAW)) {
 954                 uint64_t psize = BP_GET_PSIZE(bp);
 955                 void *cbuf = zio_buf_alloc(psize);
 956 
 957                 zio_push_transform(zio, cbuf, psize, psize, zio_decompress);
 958         }
 959 
 960         if (!DMU_OT_IS_METADATA(BP_GET_TYPE(bp)) && BP_GET_LEVEL(bp) == 0)
 961                 zio->io_flags |= ZIO_FLAG_DONT_CACHE;
 962 
 963         if (BP_GET_TYPE(bp) == DMU_OT_DDT_ZAP)
 964                 zio->io_flags |= ZIO_FLAG_DONT_CACHE;
 965 
 966         if (BP_GET_DEDUP(bp) && zio->io_child_type == ZIO_CHILD_LOGICAL)
 967                 zio->io_pipeline = ZIO_DDT_READ_PIPELINE;
 968 
 969         return (ZIO_PIPELINE_CONTINUE);
 970 }
 971 
 972 static int
 973 zio_write_bp_init(zio_t *zio)
 974 {
 975         spa_t *spa = zio->io_spa;
 976         zio_prop_t *zp = &zio->io_prop;
 977         enum zio_compress compress = zp->zp_compress;
 978         blkptr_t *bp = zio->io_bp;
 979         uint64_t lsize = zio->io_size;
 980         uint64_t psize = lsize;
 981         int pass = 1;
 982 
 983         /*
 984          * If our children haven't all reached the ready stage,
 985          * wait for them and then repeat this pipeline stage.
 986          */
 987         if (zio_wait_for_children(zio, ZIO_CHILD_GANG, ZIO_WAIT_READY) ||
 988             zio_wait_for_children(zio, ZIO_CHILD_LOGICAL, ZIO_WAIT_READY))
 989                 return (ZIO_PIPELINE_STOP);
 990 
 991         if (!IO_IS_ALLOCATING(zio))
 992                 return (ZIO_PIPELINE_CONTINUE);
 993 
 994         ASSERT(zio->io_child_type != ZIO_CHILD_DDT);
 995 
 996         if (zio->io_bp_override) {
 997                 ASSERT(bp->blk_birth != zio->io_txg);
 998                 ASSERT(BP_GET_DEDUP(zio->io_bp_override) == 0);
 999 
1000                 *bp = *zio->io_bp_override;
1001                 zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1002 
1003                 /*
1004                  * If we've been overridden and nopwrite is set then
1005                  * set the flag accordingly to indicate that a nopwrite
1006                  * has already occurred.
1007                  */
1008                 if (!BP_IS_HOLE(bp) && zp->zp_nopwrite) {
1009                         ASSERT(!zp->zp_dedup);
1010                         zio->io_flags |= ZIO_FLAG_NOPWRITE;
1011                         return (ZIO_PIPELINE_CONTINUE);
1012                 }
1013 
1014                 ASSERT(!zp->zp_nopwrite);
1015 
1016                 if (BP_IS_HOLE(bp) || !zp->zp_dedup)
1017                         return (ZIO_PIPELINE_CONTINUE);
1018 
1019                 ASSERT(zio_checksum_table[zp->zp_checksum].ci_dedup ||
1020                     zp->zp_dedup_verify);
1021 
1022                 if (BP_GET_CHECKSUM(bp) == zp->zp_checksum) {
1023                         BP_SET_DEDUP(bp, 1);
1024                         zio->io_pipeline |= ZIO_STAGE_DDT_WRITE;
1025                         return (ZIO_PIPELINE_CONTINUE);
1026                 }
1027                 zio->io_bp_override = NULL;
1028                 BP_ZERO(bp);
1029         }
1030 
1031         if (!BP_IS_HOLE(bp) && bp->blk_birth == zio->io_txg) {
1032                 /*
1033                  * We're rewriting an existing block, which means we're
1034                  * working on behalf of spa_sync().  For spa_sync() to
1035                  * converge, it must eventually be the case that we don't
1036                  * have to allocate new blocks.  But compression changes
1037                  * the blocksize, which forces a reallocate, and makes
1038                  * convergence take longer.  Therefore, after the first
1039                  * few passes, stop compressing to ensure convergence.
1040                  */
1041                 pass = spa_sync_pass(spa);
1042 
1043                 ASSERT(zio->io_txg == spa_syncing_txg(spa));
1044                 ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1045                 ASSERT(!BP_GET_DEDUP(bp));
1046 
1047                 if (pass >= zfs_sync_pass_dont_compress)
1048                         compress = ZIO_COMPRESS_OFF;
1049 
1050                 /* Make sure someone doesn't change their mind on overwrites */
1051                 ASSERT(MIN(zp->zp_copies + BP_IS_GANG(bp),
1052                     spa_max_replication(spa)) == BP_GET_NDVAS(bp));
1053         }
1054 
1055         if (compress != ZIO_COMPRESS_OFF) {
1056                 void *cbuf = zio_buf_alloc(lsize);
1057                 psize = zio_compress_data(compress, zio->io_data, cbuf, lsize);
1058                 if (psize == 0 || psize == lsize) {
1059                         compress = ZIO_COMPRESS_OFF;
1060                         zio_buf_free(cbuf, lsize);
1061                 } else {
1062                         ASSERT(psize < lsize);
1063                         zio_push_transform(zio, cbuf, psize, lsize, NULL);
1064                 }
1065         }
1066 
1067         /*
1068          * The final pass of spa_sync() must be all rewrites, but the first
1069          * few passes offer a trade-off: allocating blocks defers convergence,
1070          * but newly allocated blocks are sequential, so they can be written
1071          * to disk faster.  Therefore, we allow the first few passes of
1072          * spa_sync() to allocate new blocks, but force rewrites after that.
1073          * There should only be a handful of blocks after pass 1 in any case.
1074          */
1075         if (!BP_IS_HOLE(bp) && bp->blk_birth == zio->io_txg &&
1076             BP_GET_PSIZE(bp) == psize &&
1077             pass >= zfs_sync_pass_rewrite) {
1078                 ASSERT(psize != 0);
1079                 enum zio_stage gang_stages = zio->io_pipeline & ZIO_GANG_STAGES;
1080                 zio->io_pipeline = ZIO_REWRITE_PIPELINE | gang_stages;
1081                 zio->io_flags |= ZIO_FLAG_IO_REWRITE;
1082         } else {
1083                 BP_ZERO(bp);
1084                 zio->io_pipeline = ZIO_WRITE_PIPELINE;
1085         }
1086 
1087         if (psize == 0) {
1088                 if (zio->io_bp_orig.blk_birth != 0 &&
1089                     spa_feature_is_active(spa, SPA_FEATURE_HOLE_BIRTH)) {
1090                         BP_SET_LSIZE(bp, lsize);
1091                         BP_SET_TYPE(bp, zp->zp_type);
1092                         BP_SET_LEVEL(bp, zp->zp_level);
1093                         BP_SET_BIRTH(bp, zio->io_txg, 0);
1094                 }
1095                 zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1096         } else {
1097                 ASSERT(zp->zp_checksum != ZIO_CHECKSUM_GANG_HEADER);
1098                 BP_SET_LSIZE(bp, lsize);
1099                 BP_SET_TYPE(bp, zp->zp_type);
1100                 BP_SET_LEVEL(bp, zp->zp_level);
1101                 BP_SET_PSIZE(bp, psize);
1102                 BP_SET_COMPRESS(bp, compress);
1103                 BP_SET_CHECKSUM(bp, zp->zp_checksum);
1104                 BP_SET_DEDUP(bp, zp->zp_dedup);
1105                 BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
1106                 if (zp->zp_dedup) {
1107                         ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1108                         ASSERT(!(zio->io_flags & ZIO_FLAG_IO_REWRITE));
1109                         zio->io_pipeline = ZIO_DDT_WRITE_PIPELINE;
1110                 }
1111                 if (zp->zp_nopwrite) {
1112                         ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1113                         ASSERT(!(zio->io_flags & ZIO_FLAG_IO_REWRITE));
1114                         zio->io_pipeline |= ZIO_STAGE_NOP_WRITE;
1115                 }
1116         }
1117 
1118         return (ZIO_PIPELINE_CONTINUE);
1119 }
1120 
1121 static int
1122 zio_free_bp_init(zio_t *zio)
1123 {
1124         blkptr_t *bp = zio->io_bp;
1125 
1126         if (zio->io_child_type == ZIO_CHILD_LOGICAL) {
1127                 if (BP_GET_DEDUP(bp))
1128                         zio->io_pipeline = ZIO_DDT_FREE_PIPELINE;
1129         }
1130 
1131         return (ZIO_PIPELINE_CONTINUE);
1132 }
1133 
1134 /*
1135  * ==========================================================================
1136  * Execute the I/O pipeline
1137  * ==========================================================================
1138  */
1139 
1140 static void
1141 zio_taskq_dispatch(zio_t *zio, zio_taskq_type_t q, boolean_t cutinline)
1142 {
1143         spa_t *spa = zio->io_spa;
1144         zio_type_t t = zio->io_type;
1145         int flags = (cutinline ? TQ_FRONT : 0);
1146 
1147         /*
1148          * If we're a config writer or a probe, the normal issue and
1149          * interrupt threads may all be blocked waiting for the config lock.
1150          * In this case, select the otherwise-unused taskq for ZIO_TYPE_NULL.
1151          */
1152         if (zio->io_flags & (ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_PROBE))
1153                 t = ZIO_TYPE_NULL;
1154 
1155         /*
1156          * A similar issue exists for the L2ARC write thread until L2ARC 2.0.
1157          */
1158         if (t == ZIO_TYPE_WRITE && zio->io_vd && zio->io_vd->vdev_aux)
1159                 t = ZIO_TYPE_NULL;
1160 
1161         /*
1162          * If this is a high priority I/O, then use the high priority taskq if
1163          * available.
1164          */
1165         if (zio->io_priority == ZIO_PRIORITY_NOW &&
1166             spa->spa_zio_taskq[t][q + 1].stqs_count != 0)
1167                 q++;
1168 
1169         ASSERT3U(q, <, ZIO_TASKQ_TYPES);
1170 
1171         /*
1172          * NB: We are assuming that the zio can only be dispatched
1173          * to a single taskq at a time.  It would be a grievous error
1174          * to dispatch the zio to another taskq at the same time.
1175          */
1176         ASSERT(zio->io_tqent.tqent_next == NULL);
1177         spa_taskq_dispatch_ent(spa, t, q, (task_func_t *)zio_execute, zio,
1178             flags, &zio->io_tqent);
1179 }
1180 
1181 static boolean_t
1182 zio_taskq_member(zio_t *zio, zio_taskq_type_t q)
1183 {
1184         kthread_t *executor = zio->io_executor;
1185         spa_t *spa = zio->io_spa;
1186 
1187         for (zio_type_t t = 0; t < ZIO_TYPES; t++) {
1188                 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1189                 uint_t i;
1190                 for (i = 0; i < tqs->stqs_count; i++) {
1191                         if (taskq_member(tqs->stqs_taskq[i], executor))
1192                                 return (B_TRUE);
1193                 }
1194         }
1195 
1196         return (B_FALSE);
1197 }
1198 
1199 static int
1200 zio_issue_async(zio_t *zio)
1201 {
1202         zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE, B_FALSE);
1203 
1204         return (ZIO_PIPELINE_STOP);
1205 }
1206 
1207 void
1208 zio_interrupt(zio_t *zio)
1209 {
1210         zio_taskq_dispatch(zio, ZIO_TASKQ_INTERRUPT, B_FALSE);
1211 }
1212 
1213 /*
1214  * Execute the I/O pipeline until one of the following occurs:
1215  *
1216  *      (1) the I/O completes
1217  *      (2) the pipeline stalls waiting for dependent child I/Os
1218  *      (3) the I/O issues, so we're waiting for an I/O completion interrupt
1219  *      (4) the I/O is delegated by vdev-level caching or aggregation
1220  *      (5) the I/O is deferred due to vdev-level queueing
1221  *      (6) the I/O is handed off to another thread.
1222  *
1223  * In all cases, the pipeline stops whenever there's no CPU work; it never
1224  * burns a thread in cv_wait().
1225  *
1226  * There's no locking on io_stage because there's no legitimate way
1227  * for multiple threads to be attempting to process the same I/O.
1228  */
1229 static zio_pipe_stage_t *zio_pipeline[];
1230 
1231 void
1232 zio_execute(zio_t *zio)
1233 {
1234         zio->io_executor = curthread;
1235 
1236         while (zio->io_stage < ZIO_STAGE_DONE) {
1237                 enum zio_stage pipeline = zio->io_pipeline;
1238                 enum zio_stage stage = zio->io_stage;
1239                 int rv;
1240 
1241                 ASSERT(!MUTEX_HELD(&zio->io_lock));
1242                 ASSERT(ISP2(stage));
1243                 ASSERT(zio->io_stall == NULL);
1244 
1245                 do {
1246                         stage <<= 1;
1247                 } while ((stage & pipeline) == 0);
1248 
1249                 ASSERT(stage <= ZIO_STAGE_DONE);
1250 
1251                 /*
1252                  * If we are in interrupt context and this pipeline stage
1253                  * will grab a config lock that is held across I/O,
1254                  * or may wait for an I/O that needs an interrupt thread
1255                  * to complete, issue async to avoid deadlock.
1256                  *
1257                  * For VDEV_IO_START, we cut in line so that the io will
1258                  * be sent to disk promptly.
1259                  */
1260                 if ((stage & ZIO_BLOCKING_STAGES) && zio->io_vd == NULL &&
1261                     zio_taskq_member(zio, ZIO_TASKQ_INTERRUPT)) {
1262                         boolean_t cut = (stage == ZIO_STAGE_VDEV_IO_START) ?
1263                             zio_requeue_io_start_cut_in_line : B_FALSE;
1264                         zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE, cut);
1265                         return;
1266                 }
1267 
1268                 zio->io_stage = stage;
1269                 rv = zio_pipeline[highbit64(stage) - 1](zio);
1270 
1271                 if (rv == ZIO_PIPELINE_STOP)
1272                         return;
1273 
1274                 ASSERT(rv == ZIO_PIPELINE_CONTINUE);
1275         }
1276 }
1277 
1278 /*
1279  * ==========================================================================
1280  * Initiate I/O, either sync or async
1281  * ==========================================================================
1282  */
1283 int
1284 zio_wait(zio_t *zio)
1285 {
1286         int error;
1287 
1288         ASSERT(zio->io_stage == ZIO_STAGE_OPEN);
1289         ASSERT(zio->io_executor == NULL);
1290 
1291         zio->io_waiter = curthread;
1292 
1293         zio_execute(zio);
1294 
1295         mutex_enter(&zio->io_lock);
1296         while (zio->io_executor != NULL)
1297                 cv_wait(&zio->io_cv, &zio->io_lock);
1298         mutex_exit(&zio->io_lock);
1299 
1300         error = zio->io_error;
1301         zio_destroy(zio);
1302 
1303         return (error);
1304 }
1305 
1306 void
1307 zio_nowait(zio_t *zio)
1308 {
1309         ASSERT(zio->io_executor == NULL);
1310 
1311         if (zio->io_child_type == ZIO_CHILD_LOGICAL &&
1312             zio_unique_parent(zio) == NULL) {
1313                 /*
1314                  * This is a logical async I/O with no parent to wait for it.
1315                  * We add it to the spa_async_root_zio "Godfather" I/O which
1316                  * will ensure they complete prior to unloading the pool.
1317                  */
1318                 spa_t *spa = zio->io_spa;
1319 
1320                 zio_add_child(spa->spa_async_zio_root, zio);
1321         }
1322 
1323         zio_execute(zio);
1324 }
1325 
1326 /*
1327  * ==========================================================================
1328  * Reexecute or suspend/resume failed I/O
1329  * ==========================================================================
1330  */
1331 
1332 static void
1333 zio_reexecute(zio_t *pio)
1334 {
1335         zio_t *cio, *cio_next;
1336 
1337         ASSERT(pio->io_child_type == ZIO_CHILD_LOGICAL);
1338         ASSERT(pio->io_orig_stage == ZIO_STAGE_OPEN);
1339         ASSERT(pio->io_gang_leader == NULL);
1340         ASSERT(pio->io_gang_tree == NULL);
1341 
1342         pio->io_flags = pio->io_orig_flags;
1343         pio->io_stage = pio->io_orig_stage;
1344         pio->io_pipeline = pio->io_orig_pipeline;
1345         pio->io_reexecute = 0;
1346         pio->io_flags |= ZIO_FLAG_REEXECUTED;
1347         pio->io_error = 0;
1348         for (int w = 0; w < ZIO_WAIT_TYPES; w++)
1349                 pio->io_state[w] = 0;
1350         for (int c = 0; c < ZIO_CHILD_TYPES; c++)
1351                 pio->io_child_error[c] = 0;
1352 
1353         if (IO_IS_ALLOCATING(pio))
1354                 BP_ZERO(pio->io_bp);
1355 
1356         /*
1357          * As we reexecute pio's children, new children could be created.
1358          * New children go to the head of pio's io_child_list, however,
1359          * so we will (correctly) not reexecute them.  The key is that
1360          * the remainder of pio's io_child_list, from 'cio_next' onward,
1361          * cannot be affected by any side effects of reexecuting 'cio'.
1362          */
1363         for (cio = zio_walk_children(pio); cio != NULL; cio = cio_next) {
1364                 cio_next = zio_walk_children(pio);
1365                 mutex_enter(&pio->io_lock);
1366                 for (int w = 0; w < ZIO_WAIT_TYPES; w++)
1367                         pio->io_children[cio->io_child_type][w]++;
1368                 mutex_exit(&pio->io_lock);
1369                 zio_reexecute(cio);
1370         }
1371 
1372         /*
1373          * Now that all children have been reexecuted, execute the parent.
1374          * We don't reexecute "The Godfather" I/O here as it's the
1375          * responsibility of the caller to wait on him.
1376          */
1377         if (!(pio->io_flags & ZIO_FLAG_GODFATHER))
1378                 zio_execute(pio);
1379 }
1380 
1381 void
1382 zio_suspend(spa_t *spa, zio_t *zio)
1383 {
1384         if (spa_get_failmode(spa) == ZIO_FAILURE_MODE_PANIC)
1385                 fm_panic("Pool '%s' has encountered an uncorrectable I/O "
1386                     "failure and the failure mode property for this pool "
1387                     "is set to panic.", spa_name(spa));
1388 
1389         zfs_ereport_post(FM_EREPORT_ZFS_IO_FAILURE, spa, NULL, NULL, 0, 0);
1390 
1391         mutex_enter(&spa->spa_suspend_lock);
1392 
1393         if (spa->spa_suspend_zio_root == NULL)
1394                 spa->spa_suspend_zio_root = zio_root(spa, NULL, NULL,
1395                     ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
1396                     ZIO_FLAG_GODFATHER);
1397 
1398         spa->spa_suspended = B_TRUE;
1399 
1400         if (zio != NULL) {
1401                 ASSERT(!(zio->io_flags & ZIO_FLAG_GODFATHER));
1402                 ASSERT(zio != spa->spa_suspend_zio_root);
1403                 ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1404                 ASSERT(zio_unique_parent(zio) == NULL);
1405                 ASSERT(zio->io_stage == ZIO_STAGE_DONE);
1406                 zio_add_child(spa->spa_suspend_zio_root, zio);
1407         }
1408 
1409         mutex_exit(&spa->spa_suspend_lock);
1410 }
1411 
1412 int
1413 zio_resume(spa_t *spa)
1414 {
1415         zio_t *pio;
1416 
1417         /*
1418          * Reexecute all previously suspended i/o.
1419          */
1420         mutex_enter(&spa->spa_suspend_lock);
1421         spa->spa_suspended = B_FALSE;
1422         cv_broadcast(&spa->spa_suspend_cv);
1423         pio = spa->spa_suspend_zio_root;
1424         spa->spa_suspend_zio_root = NULL;
1425         mutex_exit(&spa->spa_suspend_lock);
1426 
1427         if (pio == NULL)
1428                 return (0);
1429 
1430         zio_reexecute(pio);
1431         return (zio_wait(pio));
1432 }
1433 
1434 void
1435 zio_resume_wait(spa_t *spa)
1436 {
1437         mutex_enter(&spa->spa_suspend_lock);
1438         while (spa_suspended(spa))
1439                 cv_wait(&spa->spa_suspend_cv, &spa->spa_suspend_lock);
1440         mutex_exit(&spa->spa_suspend_lock);
1441 }
1442 
1443 /*
1444  * ==========================================================================
1445  * Gang blocks.
1446  *
1447  * A gang block is a collection of small blocks that looks to the DMU
1448  * like one large block.  When zio_dva_allocate() cannot find a block
1449  * of the requested size, due to either severe fragmentation or the pool
1450  * being nearly full, it calls zio_write_gang_block() to construct the
1451  * block from smaller fragments.
1452  *
1453  * A gang block consists of a gang header (zio_gbh_phys_t) and up to
1454  * three (SPA_GBH_NBLKPTRS) gang members.  The gang header is just like
1455  * an indirect block: it's an array of block pointers.  It consumes
1456  * only one sector and hence is allocatable regardless of fragmentation.
1457  * The gang header's bps point to its gang members, which hold the data.
1458  *
1459  * Gang blocks are self-checksumming, using the bp's <vdev, offset, txg>
1460  * as the verifier to ensure uniqueness of the SHA256 checksum.
1461  * Critically, the gang block bp's blk_cksum is the checksum of the data,
1462  * not the gang header.  This ensures that data block signatures (needed for
1463  * deduplication) are independent of how the block is physically stored.
1464  *
1465  * Gang blocks can be nested: a gang member may itself be a gang block.
1466  * Thus every gang block is a tree in which root and all interior nodes are
1467  * gang headers, and the leaves are normal blocks that contain user data.
1468  * The root of the gang tree is called the gang leader.
1469  *
1470  * To perform any operation (read, rewrite, free, claim) on a gang block,
1471  * zio_gang_assemble() first assembles the gang tree (minus data leaves)
1472  * in the io_gang_tree field of the original logical i/o by recursively
1473  * reading the gang leader and all gang headers below it.  This yields
1474  * an in-core tree containing the contents of every gang header and the
1475  * bps for every constituent of the gang block.
1476  *
1477  * With the gang tree now assembled, zio_gang_issue() just walks the gang tree
1478  * and invokes a callback on each bp.  To free a gang block, zio_gang_issue()
1479  * calls zio_free_gang() -- a trivial wrapper around zio_free() -- for each bp.
1480  * zio_claim_gang() provides a similarly trivial wrapper for zio_claim().
1481  * zio_read_gang() is a wrapper around zio_read() that omits reading gang
1482  * headers, since we already have those in io_gang_tree.  zio_rewrite_gang()
1483  * performs a zio_rewrite() of the data or, for gang headers, a zio_rewrite()
1484  * of the gang header plus zio_checksum_compute() of the data to update the
1485  * gang header's blk_cksum as described above.
1486  *
1487  * The two-phase assemble/issue model solves the problem of partial failure --
1488  * what if you'd freed part of a gang block but then couldn't read the
1489  * gang header for another part?  Assembling the entire gang tree first
1490  * ensures that all the necessary gang header I/O has succeeded before
1491  * starting the actual work of free, claim, or write.  Once the gang tree
1492  * is assembled, free and claim are in-memory operations that cannot fail.
1493  *
1494  * In the event that a gang write fails, zio_dva_unallocate() walks the
1495  * gang tree to immediately free (i.e. insert back into the space map)
1496  * everything we've allocated.  This ensures that we don't get ENOSPC
1497  * errors during repeated suspend/resume cycles due to a flaky device.
1498  *
1499  * Gang rewrites only happen during sync-to-convergence.  If we can't assemble
1500  * the gang tree, we won't modify the block, so we can safely defer the free
1501  * (knowing that the block is still intact).  If we *can* assemble the gang
1502  * tree, then even if some of the rewrites fail, zio_dva_unallocate() will free
1503  * each constituent bp and we can allocate a new block on the next sync pass.
1504  *
1505  * In all cases, the gang tree allows complete recovery from partial failure.
1506  * ==========================================================================
1507  */
1508 
1509 static zio_t *
1510 zio_read_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, void *data)
1511 {
1512         if (gn != NULL)
1513                 return (pio);
1514 
1515         return (zio_read(pio, pio->io_spa, bp, data, BP_GET_PSIZE(bp),
1516             NULL, NULL, pio->io_priority, ZIO_GANG_CHILD_FLAGS(pio),
1517             &pio->io_bookmark));
1518 }
1519 
1520 zio_t *
1521 zio_rewrite_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, void *data)
1522 {
1523         zio_t *zio;
1524 
1525         if (gn != NULL) {
1526                 zio = zio_rewrite(pio, pio->io_spa, pio->io_txg, bp,
1527                     gn->gn_gbh, SPA_GANGBLOCKSIZE, NULL, NULL, pio->io_priority,
1528                     ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
1529                 /*
1530                  * As we rewrite each gang header, the pipeline will compute
1531                  * a new gang block header checksum for it; but no one will
1532                  * compute a new data checksum, so we do that here.  The one
1533                  * exception is the gang leader: the pipeline already computed
1534                  * its data checksum because that stage precedes gang assembly.
1535                  * (Presently, nothing actually uses interior data checksums;
1536                  * this is just good hygiene.)
1537                  */
1538                 if (gn != pio->io_gang_leader->io_gang_tree) {
1539                         zio_checksum_compute(zio, BP_GET_CHECKSUM(bp),
1540                             data, BP_GET_PSIZE(bp));
1541                 }
1542                 /*
1543                  * If we are here to damage data for testing purposes,
1544                  * leave the GBH alone so that we can detect the damage.
1545                  */
1546                 if (pio->io_gang_leader->io_flags & ZIO_FLAG_INDUCE_DAMAGE)
1547                         zio->io_pipeline &= ~ZIO_VDEV_IO_STAGES;
1548         } else {
1549                 zio = zio_rewrite(pio, pio->io_spa, pio->io_txg, bp,
1550                     data, BP_GET_PSIZE(bp), NULL, NULL, pio->io_priority,
1551                     ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
1552         }
1553 
1554         return (zio);
1555 }
1556 
1557 /* ARGSUSED */
1558 zio_t *
1559 zio_free_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, void *data)
1560 {
1561         return (zio_free_sync(pio, pio->io_spa, pio->io_txg, bp,
1562             ZIO_GANG_CHILD_FLAGS(pio)));
1563 }
1564 
1565 /* ARGSUSED */
1566 zio_t *
1567 zio_claim_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, void *data)
1568 {
1569         return (zio_claim(pio, pio->io_spa, pio->io_txg, bp,
1570             NULL, NULL, ZIO_GANG_CHILD_FLAGS(pio)));
1571 }
1572 
1573 static zio_gang_issue_func_t *zio_gang_issue_func[ZIO_TYPES] = {
1574         NULL,
1575         zio_read_gang,
1576         zio_rewrite_gang,
1577         zio_free_gang,
1578         zio_claim_gang,
1579         NULL
1580 };
1581 
1582 static void zio_gang_tree_assemble_done(zio_t *zio);
1583 
1584 static zio_gang_node_t *
1585 zio_gang_node_alloc(zio_gang_node_t **gnpp)
1586 {
1587         zio_gang_node_t *gn;
1588 
1589         ASSERT(*gnpp == NULL);
1590 
1591         gn = kmem_zalloc(sizeof (*gn), KM_SLEEP);
1592         gn->gn_gbh = zio_buf_alloc(SPA_GANGBLOCKSIZE);
1593         *gnpp = gn;
1594 
1595         return (gn);
1596 }
1597 
1598 static void
1599 zio_gang_node_free(zio_gang_node_t **gnpp)
1600 {
1601         zio_gang_node_t *gn = *gnpp;
1602 
1603         for (int g = 0; g < SPA_GBH_NBLKPTRS; g++)
1604                 ASSERT(gn->gn_child[g] == NULL);
1605 
1606         zio_buf_free(gn->gn_gbh, SPA_GANGBLOCKSIZE);
1607         kmem_free(gn, sizeof (*gn));
1608         *gnpp = NULL;
1609 }
1610 
1611 static void
1612 zio_gang_tree_free(zio_gang_node_t **gnpp)
1613 {
1614         zio_gang_node_t *gn = *gnpp;
1615 
1616         if (gn == NULL)
1617                 return;
1618 
1619         for (int g = 0; g < SPA_GBH_NBLKPTRS; g++)
1620                 zio_gang_tree_free(&gn->gn_child[g]);
1621 
1622         zio_gang_node_free(gnpp);
1623 }
1624 
1625 static void
1626 zio_gang_tree_assemble(zio_t *gio, blkptr_t *bp, zio_gang_node_t **gnpp)
1627 {
1628         zio_gang_node_t *gn = zio_gang_node_alloc(gnpp);
1629 
1630         ASSERT(gio->io_gang_leader == gio);
1631         ASSERT(BP_IS_GANG(bp));
1632 
1633         zio_nowait(zio_read(gio, gio->io_spa, bp, gn->gn_gbh,
1634             SPA_GANGBLOCKSIZE, zio_gang_tree_assemble_done, gn,
1635             gio->io_priority, ZIO_GANG_CHILD_FLAGS(gio), &gio->io_bookmark));
1636 }
1637 
1638 static void
1639 zio_gang_tree_assemble_done(zio_t *zio)
1640 {
1641         zio_t *gio = zio->io_gang_leader;
1642         zio_gang_node_t *gn = zio->io_private;
1643         blkptr_t *bp = zio->io_bp;
1644 
1645         ASSERT(gio == zio_unique_parent(zio));
1646         ASSERT(zio->io_child_count == 0);
1647 
1648         if (zio->io_error)
1649                 return;
1650 
1651         if (BP_SHOULD_BYTESWAP(bp))
1652                 byteswap_uint64_array(zio->io_data, zio->io_size);
1653 
1654         ASSERT(zio->io_data == gn->gn_gbh);
1655         ASSERT(zio->io_size == SPA_GANGBLOCKSIZE);
1656         ASSERT(gn->gn_gbh->zg_tail.zec_magic == ZEC_MAGIC);
1657 
1658         for (int g = 0; g < SPA_GBH_NBLKPTRS; g++) {
1659                 blkptr_t *gbp = &gn->gn_gbh->zg_blkptr[g];
1660                 if (!BP_IS_GANG(gbp))
1661                         continue;
1662                 zio_gang_tree_assemble(gio, gbp, &gn->gn_child[g]);
1663         }
1664 }
1665 
1666 static void
1667 zio_gang_tree_issue(zio_t *pio, zio_gang_node_t *gn, blkptr_t *bp, void *data)
1668 {
1669         zio_t *gio = pio->io_gang_leader;
1670         zio_t *zio;
1671 
1672         ASSERT(BP_IS_GANG(bp) == !!gn);
1673         ASSERT(BP_GET_CHECKSUM(bp) == BP_GET_CHECKSUM(gio->io_bp));
1674         ASSERT(BP_GET_LSIZE(bp) == BP_GET_PSIZE(bp) || gn == gio->io_gang_tree);
1675 
1676         /*
1677          * If you're a gang header, your data is in gn->gn_gbh.
1678          * If you're a gang member, your data is in 'data' and gn == NULL.
1679          */
1680         zio = zio_gang_issue_func[gio->io_type](pio, bp, gn, data);
1681 
1682         if (gn != NULL) {
1683                 ASSERT(gn->gn_gbh->zg_tail.zec_magic == ZEC_MAGIC);
1684 
1685                 for (int g = 0; g < SPA_GBH_NBLKPTRS; g++) {
1686                         blkptr_t *gbp = &gn->gn_gbh->zg_blkptr[g];
1687                         if (BP_IS_HOLE(gbp))
1688                                 continue;
1689                         zio_gang_tree_issue(zio, gn->gn_child[g], gbp, data);
1690                         data = (char *)data + BP_GET_PSIZE(gbp);
1691                 }
1692         }
1693 
1694         if (gn == gio->io_gang_tree)
1695                 ASSERT3P((char *)gio->io_data + gio->io_size, ==, data);
1696 
1697         if (zio != pio)
1698                 zio_nowait(zio);
1699 }
1700 
1701 static int
1702 zio_gang_assemble(zio_t *zio)
1703 {
1704         blkptr_t *bp = zio->io_bp;
1705 
1706         ASSERT(BP_IS_GANG(bp) && zio->io_gang_leader == NULL);
1707         ASSERT(zio->io_child_type > ZIO_CHILD_GANG);
1708 
1709         zio->io_gang_leader = zio;
1710 
1711         zio_gang_tree_assemble(zio, bp, &zio->io_gang_tree);
1712 
1713         return (ZIO_PIPELINE_CONTINUE);
1714 }
1715 
1716 static int
1717 zio_gang_issue(zio_t *zio)
1718 {
1719         blkptr_t *bp = zio->io_bp;
1720 
1721         if (zio_wait_for_children(zio, ZIO_CHILD_GANG, ZIO_WAIT_DONE))
1722                 return (ZIO_PIPELINE_STOP);
1723 
1724         ASSERT(BP_IS_GANG(bp) && zio->io_gang_leader == zio);
1725         ASSERT(zio->io_child_type > ZIO_CHILD_GANG);
1726 
1727         if (zio->io_child_error[ZIO_CHILD_GANG] == 0)
1728                 zio_gang_tree_issue(zio, zio->io_gang_tree, bp, zio->io_data);
1729         else
1730                 zio_gang_tree_free(&zio->io_gang_tree);
1731 
1732         zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1733 
1734         return (ZIO_PIPELINE_CONTINUE);
1735 }
1736 
1737 static void
1738 zio_write_gang_member_ready(zio_t *zio)
1739 {
1740         zio_t *pio = zio_unique_parent(zio);
1741         zio_t *gio = zio->io_gang_leader;
1742         dva_t *cdva = zio->io_bp->blk_dva;
1743         dva_t *pdva = pio->io_bp->blk_dva;
1744         uint64_t asize;
1745 
1746         if (BP_IS_HOLE(zio->io_bp))
1747                 return;
1748 
1749         ASSERT(BP_IS_HOLE(&zio->io_bp_orig));
1750 
1751         ASSERT(zio->io_child_type == ZIO_CHILD_GANG);
1752         ASSERT3U(zio->io_prop.zp_copies, ==, gio->io_prop.zp_copies);
1753         ASSERT3U(zio->io_prop.zp_copies, <=, BP_GET_NDVAS(zio->io_bp));
1754         ASSERT3U(pio->io_prop.zp_copies, <=, BP_GET_NDVAS(pio->io_bp));
1755         ASSERT3U(BP_GET_NDVAS(zio->io_bp), <=, BP_GET_NDVAS(pio->io_bp));
1756 
1757         mutex_enter(&pio->io_lock);
1758         for (int d = 0; d < BP_GET_NDVAS(zio->io_bp); d++) {
1759                 ASSERT(DVA_GET_GANG(&pdva[d]));
1760                 asize = DVA_GET_ASIZE(&pdva[d]);
1761                 asize += DVA_GET_ASIZE(&cdva[d]);
1762                 DVA_SET_ASIZE(&pdva[d], asize);
1763         }
1764         mutex_exit(&pio->io_lock);
1765 }
1766 
1767 static int
1768 zio_write_gang_block(zio_t *pio)
1769 {
1770         spa_t *spa = pio->io_spa;
1771         blkptr_t *bp = pio->io_bp;
1772         zio_t *gio = pio->io_gang_leader;
1773         zio_t *zio;
1774         zio_gang_node_t *gn, **gnpp;
1775         zio_gbh_phys_t *gbh;
1776         uint64_t txg = pio->io_txg;
1777         uint64_t resid = pio->io_size;
1778         uint64_t lsize;
1779         int copies = gio->io_prop.zp_copies;
1780         int gbh_copies = MIN(copies + 1, spa_max_replication(spa));
1781         zio_prop_t zp;
1782         int error;
1783 
1784         error = metaslab_alloc(spa, spa_normal_class(spa), SPA_GANGBLOCKSIZE,
1785             bp, gbh_copies, txg, pio == gio ? NULL : gio->io_bp,
1786             METASLAB_HINTBP_FAVOR | METASLAB_GANG_HEADER);
1787         if (error) {
1788                 pio->io_error = error;
1789                 return (ZIO_PIPELINE_CONTINUE);
1790         }
1791 
1792         if (pio == gio) {
1793                 gnpp = &gio->io_gang_tree;
1794         } else {
1795                 gnpp = pio->io_private;
1796                 ASSERT(pio->io_ready == zio_write_gang_member_ready);
1797         }
1798 
1799         gn = zio_gang_node_alloc(gnpp);
1800         gbh = gn->gn_gbh;
1801         bzero(gbh, SPA_GANGBLOCKSIZE);
1802 
1803         /*
1804          * Create the gang header.
1805          */
1806         zio = zio_rewrite(pio, spa, txg, bp, gbh, SPA_GANGBLOCKSIZE, NULL, NULL,
1807             pio->io_priority, ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
1808 
1809         /*
1810          * Create and nowait the gang children.
1811          */
1812         for (int g = 0; resid != 0; resid -= lsize, g++) {
1813                 lsize = P2ROUNDUP(resid / (SPA_GBH_NBLKPTRS - g),
1814                     SPA_MINBLOCKSIZE);
1815                 ASSERT(lsize >= SPA_MINBLOCKSIZE && lsize <= resid);
1816 
1817                 zp.zp_checksum = gio->io_prop.zp_checksum;
1818                 zp.zp_compress = ZIO_COMPRESS_OFF;
1819                 zp.zp_type = DMU_OT_NONE;
1820                 zp.zp_level = 0;
1821                 zp.zp_copies = gio->io_prop.zp_copies;
1822                 zp.zp_dedup = B_FALSE;
1823                 zp.zp_dedup_verify = B_FALSE;
1824                 zp.zp_nopwrite = B_FALSE;
1825 
1826                 zio_nowait(zio_write(zio, spa, txg, &gbh->zg_blkptr[g],
1827                     (char *)pio->io_data + (pio->io_size - resid), lsize, &zp,
1828                     zio_write_gang_member_ready, NULL, NULL, &gn->gn_child[g],
1829                     pio->io_priority, ZIO_GANG_CHILD_FLAGS(pio),
1830                     &pio->io_bookmark));
1831         }
1832 
1833         /*
1834          * Set pio's pipeline to just wait for zio to finish.
1835          */
1836         pio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1837 
1838         zio_nowait(zio);
1839 
1840         return (ZIO_PIPELINE_CONTINUE);
1841 }
1842 
1843 /*
1844  * The zio_nop_write stage in the pipeline determines if allocating
1845  * a new bp is necessary.  By leveraging a cryptographically secure checksum,
1846  * such as SHA256, we can compare the checksums of the new data and the old
1847  * to determine if allocating a new block is required.  The nopwrite
1848  * feature can handle writes in either syncing or open context (i.e. zil
1849  * writes) and as a result is mutually exclusive with dedup.
1850  */
1851 static int
1852 zio_nop_write(zio_t *zio)
1853 {
1854         blkptr_t *bp = zio->io_bp;
1855         blkptr_t *bp_orig = &zio->io_bp_orig;
1856         zio_prop_t *zp = &zio->io_prop;
1857 
1858         ASSERT(BP_GET_LEVEL(bp) == 0);
1859         ASSERT(!(zio->io_flags & ZIO_FLAG_IO_REWRITE));
1860         ASSERT(zp->zp_nopwrite);
1861         ASSERT(!zp->zp_dedup);
1862         ASSERT(zio->io_bp_override == NULL);
1863         ASSERT(IO_IS_ALLOCATING(zio));
1864 
1865         /*
1866          * Check to see if the original bp and the new bp have matching
1867          * characteristics (i.e. same checksum, compression algorithms, etc).
1868          * If they don't then just continue with the pipeline which will
1869          * allocate a new bp.
1870          */
1871         if (BP_IS_HOLE(bp_orig) ||
1872             !zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_dedup ||
1873             BP_GET_CHECKSUM(bp) != BP_GET_CHECKSUM(bp_orig) ||
1874             BP_GET_COMPRESS(bp) != BP_GET_COMPRESS(bp_orig) ||
1875             BP_GET_DEDUP(bp) != BP_GET_DEDUP(bp_orig) ||
1876             zp->zp_copies != BP_GET_NDVAS(bp_orig))
1877                 return (ZIO_PIPELINE_CONTINUE);
1878 
1879         /*
1880          * If the checksums match then reset the pipeline so that we
1881          * avoid allocating a new bp and issuing any I/O.
1882          */
1883         if (ZIO_CHECKSUM_EQUAL(bp->blk_cksum, bp_orig->blk_cksum)) {
1884                 ASSERT(zio_checksum_table[zp->zp_checksum].ci_dedup);
1885                 ASSERT3U(BP_GET_PSIZE(bp), ==, BP_GET_PSIZE(bp_orig));
1886                 ASSERT3U(BP_GET_LSIZE(bp), ==, BP_GET_LSIZE(bp_orig));
1887                 ASSERT(zp->zp_compress != ZIO_COMPRESS_OFF);
1888                 ASSERT(bcmp(&bp->blk_prop, &bp_orig->blk_prop,
1889                     sizeof (uint64_t)) == 0);
1890 
1891                 *bp = *bp_orig;
1892                 zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1893                 zio->io_flags |= ZIO_FLAG_NOPWRITE;
1894         }
1895 
1896         return (ZIO_PIPELINE_CONTINUE);
1897 }
1898 
1899 /*
1900  * ==========================================================================
1901  * Dedup
1902  * ==========================================================================
1903  */
1904 static void
1905 zio_ddt_child_read_done(zio_t *zio)
1906 {
1907         blkptr_t *bp = zio->io_bp;
1908         ddt_entry_t *dde = zio->io_private;
1909         ddt_phys_t *ddp;
1910         zio_t *pio = zio_unique_parent(zio);
1911 
1912         mutex_enter(&pio->io_lock);
1913         ddp = ddt_phys_select(dde, bp);
1914         if (zio->io_error == 0)
1915                 ddt_phys_clear(ddp);    /* this ddp doesn't need repair */
1916         if (zio->io_error == 0 && dde->dde_repair_data == NULL)
1917                 dde->dde_repair_data = zio->io_data;
1918         else
1919                 zio_buf_free(zio->io_data, zio->io_size);
1920         mutex_exit(&pio->io_lock);
1921 }
1922 
1923 static int
1924 zio_ddt_read_start(zio_t *zio)
1925 {
1926         blkptr_t *bp = zio->io_bp;
1927 
1928         ASSERT(BP_GET_DEDUP(bp));
1929         ASSERT(BP_GET_PSIZE(bp) == zio->io_size);
1930         ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1931 
1932         if (zio->io_child_error[ZIO_CHILD_DDT]) {
1933                 ddt_t *ddt = ddt_select(zio->io_spa, bp);
1934                 ddt_entry_t *dde = ddt_repair_start(ddt, bp);
1935                 ddt_phys_t *ddp = dde->dde_phys;
1936                 ddt_phys_t *ddp_self = ddt_phys_select(dde, bp);
1937                 blkptr_t blk;
1938 
1939                 ASSERT(zio->io_vsd == NULL);
1940                 zio->io_vsd = dde;
1941 
1942                 if (ddp_self == NULL)
1943                         return (ZIO_PIPELINE_CONTINUE);
1944 
1945                 for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
1946                         if (ddp->ddp_phys_birth == 0 || ddp == ddp_self)
1947                                 continue;
1948                         ddt_bp_create(ddt->ddt_checksum, &dde->dde_key, ddp,
1949                             &blk);
1950                         zio_nowait(zio_read(zio, zio->io_spa, &blk,
1951                             zio_buf_alloc(zio->io_size), zio->io_size,
1952                             zio_ddt_child_read_done, dde, zio->io_priority,
1953                             ZIO_DDT_CHILD_FLAGS(zio) | ZIO_FLAG_DONT_PROPAGATE,
1954                             &zio->io_bookmark));
1955                 }
1956                 return (ZIO_PIPELINE_CONTINUE);
1957         }
1958 
1959         zio_nowait(zio_read(zio, zio->io_spa, bp,
1960             zio->io_data, zio->io_size, NULL, NULL, zio->io_priority,
1961             ZIO_DDT_CHILD_FLAGS(zio), &zio->io_bookmark));
1962 
1963         return (ZIO_PIPELINE_CONTINUE);
1964 }
1965 
1966 static int
1967 zio_ddt_read_done(zio_t *zio)
1968 {
1969         blkptr_t *bp = zio->io_bp;
1970 
1971         if (zio_wait_for_children(zio, ZIO_CHILD_DDT, ZIO_WAIT_DONE))
1972                 return (ZIO_PIPELINE_STOP);
1973 
1974         ASSERT(BP_GET_DEDUP(bp));
1975         ASSERT(BP_GET_PSIZE(bp) == zio->io_size);
1976         ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1977 
1978         if (zio->io_child_error[ZIO_CHILD_DDT]) {
1979                 ddt_t *ddt = ddt_select(zio->io_spa, bp);
1980                 ddt_entry_t *dde = zio->io_vsd;
1981                 if (ddt == NULL) {
1982                         ASSERT(spa_load_state(zio->io_spa) != SPA_LOAD_NONE);
1983                         return (ZIO_PIPELINE_CONTINUE);
1984                 }
1985                 if (dde == NULL) {
1986                         zio->io_stage = ZIO_STAGE_DDT_READ_START >> 1;
1987                         zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE, B_FALSE);
1988                         return (ZIO_PIPELINE_STOP);
1989                 }
1990                 if (dde->dde_repair_data != NULL) {
1991                         bcopy(dde->dde_repair_data, zio->io_data, zio->io_size);
1992                         zio->io_child_error[ZIO_CHILD_DDT] = 0;
1993                 }
1994                 ddt_repair_done(ddt, dde);
1995                 zio->io_vsd = NULL;
1996         }
1997 
1998         ASSERT(zio->io_vsd == NULL);
1999 
2000         return (ZIO_PIPELINE_CONTINUE);
2001 }
2002 
2003 static boolean_t
2004 zio_ddt_collision(zio_t *zio, ddt_t *ddt, ddt_entry_t *dde)
2005 {
2006         spa_t *spa = zio->io_spa;
2007 
2008         /*
2009          * Note: we compare the original data, not the transformed data,
2010          * because when zio->io_bp is an override bp, we will not have
2011          * pushed the I/O transforms.  That's an important optimization
2012          * because otherwise we'd compress/encrypt all dmu_sync() data twice.
2013          */
2014         for (int p = DDT_PHYS_SINGLE; p <= DDT_PHYS_TRIPLE; p++) {
2015                 zio_t *lio = dde->dde_lead_zio[p];
2016 
2017                 if (lio != NULL) {
2018                         return (lio->io_orig_size != zio->io_orig_size ||
2019                             bcmp(zio->io_orig_data, lio->io_orig_data,
2020                             zio->io_orig_size) != 0);
2021                 }
2022         }
2023 
2024         for (int p = DDT_PHYS_SINGLE; p <= DDT_PHYS_TRIPLE; p++) {
2025                 ddt_phys_t *ddp = &dde->dde_phys[p];
2026 
2027                 if (ddp->ddp_phys_birth != 0) {
2028                         arc_buf_t *abuf = NULL;
2029                         uint32_t aflags = ARC_WAIT;
2030                         blkptr_t blk = *zio->io_bp;
2031                         int error;
2032 
2033                         ddt_bp_fill(ddp, &blk, ddp->ddp_phys_birth);
2034 
2035                         ddt_exit(ddt);
2036 
2037                         error = arc_read(NULL, spa, &blk,
2038                             arc_getbuf_func, &abuf, ZIO_PRIORITY_SYNC_READ,
2039                             ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2040                             &aflags, &zio->io_bookmark);
2041 
2042                         if (error == 0) {
2043                                 if (arc_buf_size(abuf) != zio->io_orig_size ||
2044                                     bcmp(abuf->b_data, zio->io_orig_data,
2045                                     zio->io_orig_size) != 0)
2046                                         error = SET_ERROR(EEXIST);
2047                                 VERIFY(arc_buf_remove_ref(abuf, &abuf));
2048                         }
2049 
2050                         ddt_enter(ddt);
2051                         return (error != 0);
2052                 }
2053         }
2054 
2055         return (B_FALSE);
2056 }
2057 
2058 static void
2059 zio_ddt_child_write_ready(zio_t *zio)
2060 {
2061         int p = zio->io_prop.zp_copies;
2062         ddt_t *ddt = ddt_select(zio->io_spa, zio->io_bp);
2063         ddt_entry_t *dde = zio->io_private;
2064         ddt_phys_t *ddp = &dde->dde_phys[p];
2065         zio_t *pio;
2066 
2067         if (zio->io_error)
2068                 return;
2069 
2070         ddt_enter(ddt);
2071 
2072         ASSERT(dde->dde_lead_zio[p] == zio);
2073 
2074         ddt_phys_fill(ddp, zio->io_bp);
2075 
2076         while ((pio = zio_walk_parents(zio)) != NULL)
2077                 ddt_bp_fill(ddp, pio->io_bp, zio->io_txg);
2078 
2079         ddt_exit(ddt);
2080 }
2081 
2082 static void
2083 zio_ddt_child_write_done(zio_t *zio)
2084 {
2085         int p = zio->io_prop.zp_copies;
2086         ddt_t *ddt = ddt_select(zio->io_spa, zio->io_bp);
2087         ddt_entry_t *dde = zio->io_private;
2088         ddt_phys_t *ddp = &dde->dde_phys[p];
2089 
2090         ddt_enter(ddt);
2091 
2092         ASSERT(ddp->ddp_refcnt == 0);
2093         ASSERT(dde->dde_lead_zio[p] == zio);
2094         dde->dde_lead_zio[p] = NULL;
2095 
2096         if (zio->io_error == 0) {
2097                 while (zio_walk_parents(zio) != NULL)
2098                         ddt_phys_addref(ddp);
2099         } else {
2100                 ddt_phys_clear(ddp);
2101         }
2102 
2103         ddt_exit(ddt);
2104 }
2105 
2106 static void
2107 zio_ddt_ditto_write_done(zio_t *zio)
2108 {
2109         int p = DDT_PHYS_DITTO;
2110         zio_prop_t *zp = &zio->io_prop;
2111         blkptr_t *bp = zio->io_bp;
2112         ddt_t *ddt = ddt_select(zio->io_spa, bp);
2113         ddt_entry_t *dde = zio->io_private;
2114         ddt_phys_t *ddp = &dde->dde_phys[p];
2115         ddt_key_t *ddk = &dde->dde_key;
2116 
2117         ddt_enter(ddt);
2118 
2119         ASSERT(ddp->ddp_refcnt == 0);
2120         ASSERT(dde->dde_lead_zio[p] == zio);
2121         dde->dde_lead_zio[p] = NULL;
2122 
2123         if (zio->io_error == 0) {
2124                 ASSERT(ZIO_CHECKSUM_EQUAL(bp->blk_cksum, ddk->ddk_cksum));
2125                 ASSERT(zp->zp_copies < SPA_DVAS_PER_BP);
2126                 ASSERT(zp->zp_copies == BP_GET_NDVAS(bp) - BP_IS_GANG(bp));
2127                 if (ddp->ddp_phys_birth != 0)
2128                         ddt_phys_free(ddt, ddk, ddp, zio->io_txg);
2129                 ddt_phys_fill(ddp, bp);
2130         }
2131 
2132         ddt_exit(ddt);
2133 }
2134 
2135 static int
2136 zio_ddt_write(zio_t *zio)
2137 {
2138         spa_t *spa = zio->io_spa;
2139         blkptr_t *bp = zio->io_bp;
2140         uint64_t txg = zio->io_txg;
2141         zio_prop_t *zp = &zio->io_prop;
2142         int p = zp->zp_copies;
2143         int ditto_copies;
2144         zio_t *cio = NULL;
2145         zio_t *dio = NULL;
2146         ddt_t *ddt = ddt_select(spa, bp);
2147         ddt_entry_t *dde;
2148         ddt_phys_t *ddp;
2149 
2150         ASSERT(BP_GET_DEDUP(bp));
2151         ASSERT(BP_GET_CHECKSUM(bp) == zp->zp_checksum);
2152         ASSERT(BP_IS_HOLE(bp) || zio->io_bp_override);
2153 
2154         ddt_enter(ddt);
2155         dde = ddt_lookup(ddt, bp, B_TRUE);
2156         ddp = &dde->dde_phys[p];
2157 
2158         if (zp->zp_dedup_verify && zio_ddt_collision(zio, ddt, dde)) {
2159                 /*
2160                  * If we're using a weak checksum, upgrade to a strong checksum
2161                  * and try again.  If we're already using a strong checksum,
2162                  * we can't resolve it, so just convert to an ordinary write.
2163                  * (And automatically e-mail a paper to Nature?)
2164                  */
2165                 if (!zio_checksum_table[zp->zp_checksum].ci_dedup) {
2166                         zp->zp_checksum = spa_dedup_checksum(spa);
2167                         zio_pop_transforms(zio);
2168                         zio->io_stage = ZIO_STAGE_OPEN;
2169                         BP_ZERO(bp);
2170                 } else {
2171                         zp->zp_dedup = B_FALSE;
2172                 }
2173                 zio->io_pipeline = ZIO_WRITE_PIPELINE;
2174                 ddt_exit(ddt);
2175                 return (ZIO_PIPELINE_CONTINUE);
2176         }
2177 
2178         ditto_copies = ddt_ditto_copies_needed(ddt, dde, ddp);
2179         ASSERT(ditto_copies < SPA_DVAS_PER_BP);
2180 
2181         if (ditto_copies > ddt_ditto_copies_present(dde) &&
2182             dde->dde_lead_zio[DDT_PHYS_DITTO] == NULL) {
2183                 zio_prop_t czp = *zp;
2184 
2185                 czp.zp_copies = ditto_copies;
2186 
2187                 /*
2188                  * If we arrived here with an override bp, we won't have run
2189                  * the transform stack, so we won't have the data we need to
2190                  * generate a child i/o.  So, toss the override bp and restart.
2191                  * This is safe, because using the override bp is just an
2192                  * optimization; and it's rare, so the cost doesn't matter.
2193                  */
2194                 if (zio->io_bp_override) {
2195                         zio_pop_transforms(zio);
2196                         zio->io_stage = ZIO_STAGE_OPEN;
2197                         zio->io_pipeline = ZIO_WRITE_PIPELINE;
2198                         zio->io_bp_override = NULL;
2199                         BP_ZERO(bp);
2200                         ddt_exit(ddt);
2201                         return (ZIO_PIPELINE_CONTINUE);
2202                 }
2203 
2204                 dio = zio_write(zio, spa, txg, bp, zio->io_orig_data,
2205                     zio->io_orig_size, &czp, NULL, NULL,
2206                     zio_ddt_ditto_write_done, dde, zio->io_priority,
2207                     ZIO_DDT_CHILD_FLAGS(zio), &zio->io_bookmark);
2208 
2209                 zio_push_transform(dio, zio->io_data, zio->io_size, 0, NULL);
2210                 dde->dde_lead_zio[DDT_PHYS_DITTO] = dio;
2211         }
2212 
2213         if (ddp->ddp_phys_birth != 0 || dde->dde_lead_zio[p] != NULL) {
2214                 if (ddp->ddp_phys_birth != 0)
2215                         ddt_bp_fill(ddp, bp, txg);
2216                 if (dde->dde_lead_zio[p] != NULL)
2217                         zio_add_child(zio, dde->dde_lead_zio[p]);
2218                 else
2219                         ddt_phys_addref(ddp);
2220         } else if (zio->io_bp_override) {
2221                 ASSERT(bp->blk_birth == txg);
2222                 ASSERT(BP_EQUAL(bp, zio->io_bp_override));
2223                 ddt_phys_fill(ddp, bp);
2224                 ddt_phys_addref(ddp);
2225         } else {
2226                 cio = zio_write(zio, spa, txg, bp, zio->io_orig_data,
2227                     zio->io_orig_size, zp, zio_ddt_child_write_ready, NULL,
2228                     zio_ddt_child_write_done, dde, zio->io_priority,
2229                     ZIO_DDT_CHILD_FLAGS(zio), &zio->io_bookmark);
2230 
2231                 zio_push_transform(cio, zio->io_data, zio->io_size, 0, NULL);
2232                 dde->dde_lead_zio[p] = cio;
2233         }
2234 
2235         ddt_exit(ddt);
2236 
2237         if (cio)
2238                 zio_nowait(cio);
2239         if (dio)
2240                 zio_nowait(dio);
2241 
2242         return (ZIO_PIPELINE_CONTINUE);
2243 }
2244 
2245 ddt_entry_t *freedde; /* for debugging */
2246 
2247 static int
2248 zio_ddt_free(zio_t *zio)
2249 {
2250         spa_t *spa = zio->io_spa;
2251         blkptr_t *bp = zio->io_bp;
2252         ddt_t *ddt = ddt_select(spa, bp);
2253         ddt_entry_t *dde;
2254         ddt_phys_t *ddp;
2255 
2256         ASSERT(BP_GET_DEDUP(bp));
2257         ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
2258 
2259         ddt_enter(ddt);
2260         freedde = dde = ddt_lookup(ddt, bp, B_TRUE);
2261         ddp = ddt_phys_select(dde, bp);
2262         ddt_phys_decref(ddp);
2263         ddt_exit(ddt);
2264 
2265         return (ZIO_PIPELINE_CONTINUE);
2266 }
2267 
2268 /*
2269  * ==========================================================================
2270  * Allocate and free blocks
2271  * ==========================================================================
2272  */
2273 static int
2274 zio_dva_allocate(zio_t *zio)
2275 {
2276         spa_t *spa = zio->io_spa;
2277         metaslab_class_t *mc = spa_normal_class(spa);
2278         blkptr_t *bp = zio->io_bp;
2279         int error;
2280         int flags = 0;
2281 
2282         if (zio->io_gang_leader == NULL) {
2283                 ASSERT(zio->io_child_type > ZIO_CHILD_GANG);
2284                 zio->io_gang_leader = zio;
2285         }
2286 
2287         ASSERT(BP_IS_HOLE(bp));
2288         ASSERT0(BP_GET_NDVAS(bp));
2289         ASSERT3U(zio->io_prop.zp_copies, >, 0);
2290         ASSERT3U(zio->io_prop.zp_copies, <=, spa_max_replication(spa));
2291         ASSERT3U(zio->io_size, ==, BP_GET_PSIZE(bp));
2292 
2293         /*
2294          * The dump device does not support gang blocks so allocation on
2295          * behalf of the dump device (i.e. ZIO_FLAG_NODATA) must avoid
2296          * the "fast" gang feature.
2297          */
2298         flags |= (zio->io_flags & ZIO_FLAG_NODATA) ? METASLAB_GANG_AVOID : 0;
2299         flags |= (zio->io_flags & ZIO_FLAG_GANG_CHILD) ?
2300             METASLAB_GANG_CHILD : 0;
2301         error = metaslab_alloc(spa, mc, zio->io_size, bp,
2302             zio->io_prop.zp_copies, zio->io_txg, NULL, flags);
2303 
2304         if (error) {
2305                 spa_dbgmsg(spa, "%s: metaslab allocation failure: zio %p, "
2306                     "size %llu, error %d", spa_name(spa), zio, zio->io_size,
2307                     error);
2308                 if (error == ENOSPC && zio->io_size > SPA_MINBLOCKSIZE)
2309                         return (zio_write_gang_block(zio));
2310                 zio->io_error = error;
2311         }
2312 
2313         return (ZIO_PIPELINE_CONTINUE);
2314 }
2315 
2316 static int
2317 zio_dva_free(zio_t *zio)
2318 {
2319         metaslab_free(zio->io_spa, zio->io_bp, zio->io_txg, B_FALSE);
2320 
2321         return (ZIO_PIPELINE_CONTINUE);
2322 }
2323 
2324 static int
2325 zio_dva_claim(zio_t *zio)
2326 {
2327         int error;
2328 
2329         error = metaslab_claim(zio->io_spa, zio->io_bp, zio->io_txg);
2330         if (error)
2331                 zio->io_error = error;
2332 
2333         return (ZIO_PIPELINE_CONTINUE);
2334 }
2335 
2336 /*
2337  * Undo an allocation.  This is used by zio_done() when an I/O fails
2338  * and we want to give back the block we just allocated.
2339  * This handles both normal blocks and gang blocks.
2340  */
2341 static void
2342 zio_dva_unallocate(zio_t *zio, zio_gang_node_t *gn, blkptr_t *bp)
2343 {
2344         ASSERT(bp->blk_birth == zio->io_txg || BP_IS_HOLE(bp));
2345         ASSERT(zio->io_bp_override == NULL);
2346 
2347         if (!BP_IS_HOLE(bp))
2348                 metaslab_free(zio->io_spa, bp, bp->blk_birth, B_TRUE);
2349 
2350         if (gn != NULL) {
2351                 for (int g = 0; g < SPA_GBH_NBLKPTRS; g++) {
2352                         zio_dva_unallocate(zio, gn->gn_child[g],
2353                             &gn->gn_gbh->zg_blkptr[g]);
2354                 }
2355         }
2356 }
2357 
2358 /*
2359  * Try to allocate an intent log block.  Return 0 on success, errno on failure.
2360  */
2361 int
2362 zio_alloc_zil(spa_t *spa, uint64_t txg, blkptr_t *new_bp, blkptr_t *old_bp,
2363     uint64_t size, boolean_t use_slog)
2364 {
2365         int error = 1;
2366 
2367         ASSERT(txg > spa_syncing_txg(spa));
2368 
2369         /*
2370          * ZIL blocks are always contiguous (i.e. not gang blocks) so we
2371          * set the METASLAB_GANG_AVOID flag so that they don't "fast gang"
2372          * when allocating them.
2373          */
2374         if (use_slog) {
2375                 error = metaslab_alloc(spa, spa_log_class(spa), size,
2376                     new_bp, 1, txg, old_bp,
2377                     METASLAB_HINTBP_AVOID | METASLAB_GANG_AVOID);
2378         }
2379 
2380         if (error) {
2381                 error = metaslab_alloc(spa, spa_normal_class(spa), size,
2382                     new_bp, 1, txg, old_bp,
2383                     METASLAB_HINTBP_AVOID);
2384         }
2385 
2386         if (error == 0) {
2387                 BP_SET_LSIZE(new_bp, size);
2388                 BP_SET_PSIZE(new_bp, size);
2389                 BP_SET_COMPRESS(new_bp, ZIO_COMPRESS_OFF);
2390                 BP_SET_CHECKSUM(new_bp,
2391                     spa_version(spa) >= SPA_VERSION_SLIM_ZIL
2392                     ? ZIO_CHECKSUM_ZILOG2 : ZIO_CHECKSUM_ZILOG);
2393                 BP_SET_TYPE(new_bp, DMU_OT_INTENT_LOG);
2394                 BP_SET_LEVEL(new_bp, 0);
2395                 BP_SET_DEDUP(new_bp, 0);
2396                 BP_SET_BYTEORDER(new_bp, ZFS_HOST_BYTEORDER);
2397         }
2398 
2399         return (error);
2400 }
2401 
2402 /*
2403  * Free an intent log block.
2404  */
2405 void
2406 zio_free_zil(spa_t *spa, uint64_t txg, blkptr_t *bp)
2407 {
2408         ASSERT(BP_GET_TYPE(bp) == DMU_OT_INTENT_LOG);
2409         ASSERT(!BP_IS_GANG(bp));
2410 
2411         zio_free(spa, txg, bp);
2412 }
2413 
2414 /*
2415  * ==========================================================================
2416  * Read and write to physical devices
2417  * ==========================================================================
2418  */
2419 static int
2420 zio_vdev_io_start(zio_t *zio)
2421 {
2422         vdev_t *vd = zio->io_vd;
2423         uint64_t align;
2424         spa_t *spa = zio->io_spa;
2425 
2426         ASSERT(zio->io_error == 0);
2427         ASSERT(zio->io_child_error[ZIO_CHILD_VDEV] == 0);
2428 
2429         if (vd == NULL) {
2430                 if (!(zio->io_flags & ZIO_FLAG_CONFIG_WRITER))
2431                         spa_config_enter(spa, SCL_ZIO, zio, RW_READER);
2432 
2433                 /*
2434                  * The mirror_ops handle multiple DVAs in a single BP.
2435                  */
2436                 return (vdev_mirror_ops.vdev_op_io_start(zio));
2437         }
2438 
2439         /*
2440          * We keep track of time-sensitive I/Os so that the scan thread
2441          * can quickly react to certain workloads.  In particular, we care
2442          * about non-scrubbing, top-level reads and writes with the following
2443          * characteristics:
2444          *      - synchronous writes of user data to non-slog devices
2445          *      - any reads of user data
2446          * When these conditions are met, adjust the timestamp of spa_last_io
2447          * which allows the scan thread to adjust its workload accordingly.
2448          */
2449         if (!(zio->io_flags & ZIO_FLAG_SCAN_THREAD) && zio->io_bp != NULL &&
2450             vd == vd->vdev_top && !vd->vdev_islog &&
2451             zio->io_bookmark.zb_objset != DMU_META_OBJSET &&
2452             zio->io_txg != spa_syncing_txg(spa)) {
2453                 uint64_t old = spa->spa_last_io;
2454                 uint64_t new = ddi_get_lbolt64();
2455                 if (old != new)
2456                         (void) atomic_cas_64(&spa->spa_last_io, old, new);
2457         }
2458 
2459         align = 1ULL << vd->vdev_top->vdev_ashift;
2460 
2461         if (P2PHASE(zio->io_size, align) != 0) {
2462                 uint64_t asize = P2ROUNDUP(zio->io_size, align);
2463                 char *abuf = zio_buf_alloc(asize);
2464                 ASSERT(vd == vd->vdev_top);
2465                 if (zio->io_type == ZIO_TYPE_WRITE) {
2466                         bcopy(zio->io_data, abuf, zio->io_size);
2467                         bzero(abuf + zio->io_size, asize - zio->io_size);
2468                 }
2469                 zio_push_transform(zio, abuf, asize, asize, zio_subblock);
2470         }
2471 
2472         ASSERT(P2PHASE(zio->io_offset, align) == 0);
2473         ASSERT(P2PHASE(zio->io_size, align) == 0);
2474         VERIFY(zio->io_type != ZIO_TYPE_WRITE || spa_writeable(spa));
2475 
2476         /*
2477          * If this is a repair I/O, and there's no self-healing involved --
2478          * that is, we're just resilvering what we expect to resilver --
2479          * then don't do the I/O unless zio's txg is actually in vd's DTL.
2480          * This prevents spurious resilvering with nested replication.
2481          * For example, given a mirror of mirrors, (A+B)+(C+D), if only
2482          * A is out of date, we'll read from C+D, then use the data to
2483          * resilver A+B -- but we don't actually want to resilver B, just A.
2484          * The top-level mirror has no way to know this, so instead we just
2485          * discard unnecessary repairs as we work our way down the vdev tree.
2486          * The same logic applies to any form of nested replication:
2487          * ditto + mirror, RAID-Z + replacing, etc.  This covers them all.
2488          */
2489         if ((zio->io_flags & ZIO_FLAG_IO_REPAIR) &&
2490             !(zio->io_flags & ZIO_FLAG_SELF_HEAL) &&
2491             zio->io_txg != 0 &&      /* not a delegated i/o */
2492             !vdev_dtl_contains(vd, DTL_PARTIAL, zio->io_txg, 1)) {
2493                 ASSERT(zio->io_type == ZIO_TYPE_WRITE);
2494                 zio_vdev_io_bypass(zio);
2495                 return (ZIO_PIPELINE_CONTINUE);
2496         }
2497 
2498         if (vd->vdev_ops->vdev_op_leaf &&
2499             (zio->io_type == ZIO_TYPE_READ || zio->io_type == ZIO_TYPE_WRITE)) {
2500 
2501                 if (zio->io_type == ZIO_TYPE_READ && vdev_cache_read(zio))
2502                         return (ZIO_PIPELINE_CONTINUE);
2503 
2504                 if ((zio = vdev_queue_io(zio)) == NULL)
2505                         return (ZIO_PIPELINE_STOP);
2506 
2507                 if (!vdev_accessible(vd, zio)) {
2508                         zio->io_error = SET_ERROR(ENXIO);
2509                         zio_interrupt(zio);
2510                         return (ZIO_PIPELINE_STOP);
2511                 }
2512         }
2513 
2514         return (vd->vdev_ops->vdev_op_io_start(zio));
2515 }
2516 
2517 static int
2518 zio_vdev_io_done(zio_t *zio)
2519 {
2520         vdev_t *vd = zio->io_vd;
2521         vdev_ops_t *ops = vd ? vd->vdev_ops : &vdev_mirror_ops;
2522         boolean_t unexpected_error = B_FALSE;
2523 
2524         if (zio_wait_for_children(zio, ZIO_CHILD_VDEV, ZIO_WAIT_DONE))
2525                 return (ZIO_PIPELINE_STOP);
2526 
2527         ASSERT(zio->io_type == ZIO_TYPE_READ || zio->io_type == ZIO_TYPE_WRITE);
2528 
2529         if (vd != NULL && vd->vdev_ops->vdev_op_leaf) {
2530 
2531                 vdev_queue_io_done(zio);
2532 
2533                 if (zio->io_type == ZIO_TYPE_WRITE)
2534                         vdev_cache_write(zio);
2535 
2536                 if (zio_injection_enabled && zio->io_error == 0)
2537                         zio->io_error = zio_handle_device_injection(vd,
2538                             zio, EIO);
2539 
2540                 if (zio_injection_enabled && zio->io_error == 0)
2541                         zio->io_error = zio_handle_label_injection(zio, EIO);
2542 
2543                 if (zio->io_error) {
2544                         if (!vdev_accessible(vd, zio)) {
2545                                 zio->io_error = SET_ERROR(ENXIO);
2546                         } else {
2547                                 unexpected_error = B_TRUE;
2548                         }
2549                 }
2550         }
2551 
2552         ops->vdev_op_io_done(zio);
2553 
2554         if (unexpected_error)
2555                 VERIFY(vdev_probe(vd, zio) == NULL);
2556 
2557         return (ZIO_PIPELINE_CONTINUE);
2558 }
2559 
2560 /*
2561  * For non-raidz ZIOs, we can just copy aside the bad data read from the
2562  * disk, and use that to finish the checksum ereport later.
2563  */
2564 static void
2565 zio_vsd_default_cksum_finish(zio_cksum_report_t *zcr,
2566     const void *good_buf)
2567 {
2568         /* no processing needed */
2569         zfs_ereport_finish_checksum(zcr, good_buf, zcr->zcr_cbdata, B_FALSE);
2570 }
2571 
2572 /*ARGSUSED*/
2573 void
2574 zio_vsd_default_cksum_report(zio_t *zio, zio_cksum_report_t *zcr, void *ignored)
2575 {
2576         void *buf = zio_buf_alloc(zio->io_size);
2577 
2578         bcopy(zio->io_data, buf, zio->io_size);
2579 
2580         zcr->zcr_cbinfo = zio->io_size;
2581         zcr->zcr_cbdata = buf;
2582         zcr->zcr_finish = zio_vsd_default_cksum_finish;
2583         zcr->zcr_free = zio_buf_free;
2584 }
2585 
2586 static int
2587 zio_vdev_io_assess(zio_t *zio)
2588 {
2589         vdev_t *vd = zio->io_vd;
2590 
2591         if (zio_wait_for_children(zio, ZIO_CHILD_VDEV, ZIO_WAIT_DONE))
2592                 return (ZIO_PIPELINE_STOP);
2593 
2594         if (vd == NULL && !(zio->io_flags & ZIO_FLAG_CONFIG_WRITER))
2595                 spa_config_exit(zio->io_spa, SCL_ZIO, zio);
2596 
2597         if (zio->io_vsd != NULL) {
2598                 zio->io_vsd_ops->vsd_free(zio);
2599                 zio->io_vsd = NULL;
2600         }
2601 
2602         if (zio_injection_enabled && zio->io_error == 0)
2603                 zio->io_error = zio_handle_fault_injection(zio, EIO);
2604 
2605         /*
2606          * If the I/O failed, determine whether we should attempt to retry it.
2607          *
2608          * On retry, we cut in line in the issue queue, since we don't want
2609          * compression/checksumming/etc. work to prevent our (cheap) IO reissue.
2610          */
2611         if (zio->io_error && vd == NULL &&
2612             !(zio->io_flags & (ZIO_FLAG_DONT_RETRY | ZIO_FLAG_IO_RETRY))) {
2613                 ASSERT(!(zio->io_flags & ZIO_FLAG_DONT_QUEUE));  /* not a leaf */
2614                 ASSERT(!(zio->io_flags & ZIO_FLAG_IO_BYPASS));   /* not a leaf */
2615                 zio->io_error = 0;
2616                 zio->io_flags |= ZIO_FLAG_IO_RETRY |
2617                     ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_AGGREGATE;
2618                 zio->io_stage = ZIO_STAGE_VDEV_IO_START >> 1;
2619                 zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE,
2620                     zio_requeue_io_start_cut_in_line);
2621                 return (ZIO_PIPELINE_STOP);
2622         }
2623 
2624         /*
2625          * If we got an error on a leaf device, convert it to ENXIO
2626          * if the device is not accessible at all.
2627          */
2628         if (zio->io_error && vd != NULL && vd->vdev_ops->vdev_op_leaf &&
2629             !vdev_accessible(vd, zio))
2630                 zio->io_error = SET_ERROR(ENXIO);
2631 
2632         /*
2633          * If we can't write to an interior vdev (mirror or RAID-Z),
2634          * set vdev_cant_write so that we stop trying to allocate from it.
2635          */
2636         if (zio->io_error == ENXIO && zio->io_type == ZIO_TYPE_WRITE &&
2637             vd != NULL && !vd->vdev_ops->vdev_op_leaf) {
2638                 vd->vdev_cant_write = B_TRUE;
2639         }
2640 
2641         if (zio->io_error)
2642                 zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
2643 
2644         if (vd != NULL && vd->vdev_ops->vdev_op_leaf &&
2645             zio->io_physdone != NULL) {
2646                 ASSERT(!(zio->io_flags & ZIO_FLAG_DELEGATED));
2647                 ASSERT(zio->io_child_type == ZIO_CHILD_VDEV);
2648                 zio->io_physdone(zio->io_logical);
2649         }
2650 
2651         return (ZIO_PIPELINE_CONTINUE);
2652 }
2653 
2654 void
2655 zio_vdev_io_reissue(zio_t *zio)
2656 {
2657         ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_START);
2658         ASSERT(zio->io_error == 0);
2659 
2660         zio->io_stage >>= 1;
2661 }
2662 
2663 void
2664 zio_vdev_io_redone(zio_t *zio)
2665 {
2666         ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_DONE);
2667 
2668         zio->io_stage >>= 1;
2669 }
2670 
2671 void
2672 zio_vdev_io_bypass(zio_t *zio)
2673 {
2674         ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_START);
2675         ASSERT(zio->io_error == 0);
2676 
2677         zio->io_flags |= ZIO_FLAG_IO_BYPASS;
2678         zio->io_stage = ZIO_STAGE_VDEV_IO_ASSESS >> 1;
2679 }
2680 
2681 /*
2682  * ==========================================================================
2683  * Generate and verify checksums
2684  * ==========================================================================
2685  */
2686 static int
2687 zio_checksum_generate(zio_t *zio)
2688 {
2689         blkptr_t *bp = zio->io_bp;
2690         enum zio_checksum checksum;
2691 
2692         if (bp == NULL) {
2693                 /*
2694                  * This is zio_write_phys().
2695                  * We're either generating a label checksum, or none at all.
2696                  */
2697                 checksum = zio->io_prop.zp_checksum;
2698 
2699                 if (checksum == ZIO_CHECKSUM_OFF)
2700                         return (ZIO_PIPELINE_CONTINUE);
2701 
2702                 ASSERT(checksum == ZIO_CHECKSUM_LABEL);
2703         } else {
2704                 if (BP_IS_GANG(bp) && zio->io_child_type == ZIO_CHILD_GANG) {
2705                         ASSERT(!IO_IS_ALLOCATING(zio));
2706                         checksum = ZIO_CHECKSUM_GANG_HEADER;
2707                 } else {
2708                         checksum = BP_GET_CHECKSUM(bp);
2709                 }
2710         }
2711 
2712         zio_checksum_compute(zio, checksum, zio->io_data, zio->io_size);
2713 
2714         return (ZIO_PIPELINE_CONTINUE);
2715 }
2716 
2717 static int
2718 zio_checksum_verify(zio_t *zio)
2719 {
2720         zio_bad_cksum_t info;
2721         blkptr_t *bp = zio->io_bp;
2722         int error;
2723 
2724         ASSERT(zio->io_vd != NULL);
2725 
2726         if (bp == NULL) {
2727                 /*
2728                  * This is zio_read_phys().
2729                  * We're either verifying a label checksum, or nothing at all.
2730                  */
2731                 if (zio->io_prop.zp_checksum == ZIO_CHECKSUM_OFF)
2732                         return (ZIO_PIPELINE_CONTINUE);
2733 
2734                 ASSERT(zio->io_prop.zp_checksum == ZIO_CHECKSUM_LABEL);
2735         }
2736 
2737         if ((error = zio_checksum_error(zio, &info)) != 0) {
2738                 zio->io_error = error;
2739                 if (!(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
2740                         zfs_ereport_start_checksum(zio->io_spa,
2741                             zio->io_vd, zio, zio->io_offset,
2742                             zio->io_size, NULL, &info);
2743                 }
2744         }
2745 
2746         return (ZIO_PIPELINE_CONTINUE);
2747 }
2748 
2749 /*
2750  * Called by RAID-Z to ensure we don't compute the checksum twice.
2751  */
2752 void
2753 zio_checksum_verified(zio_t *zio)
2754 {
2755         zio->io_pipeline &= ~ZIO_STAGE_CHECKSUM_VERIFY;
2756 }
2757 
2758 /*
2759  * ==========================================================================
2760  * Error rank.  Error are ranked in the order 0, ENXIO, ECKSUM, EIO, other.
2761  * An error of 0 indictes success.  ENXIO indicates whole-device failure,
2762  * which may be transient (e.g. unplugged) or permament.  ECKSUM and EIO
2763  * indicate errors that are specific to one I/O, and most likely permanent.
2764  * Any other error is presumed to be worse because we weren't expecting it.
2765  * ==========================================================================
2766  */
2767 int
2768 zio_worst_error(int e1, int e2)
2769 {
2770         static int zio_error_rank[] = { 0, ENXIO, ECKSUM, EIO };
2771         int r1, r2;
2772 
2773         for (r1 = 0; r1 < sizeof (zio_error_rank) / sizeof (int); r1++)
2774                 if (e1 == zio_error_rank[r1])
2775                         break;
2776 
2777         for (r2 = 0; r2 < sizeof (zio_error_rank) / sizeof (int); r2++)
2778                 if (e2 == zio_error_rank[r2])
2779                         break;
2780 
2781         return (r1 > r2 ? e1 : e2);
2782 }
2783 
2784 /*
2785  * ==========================================================================
2786  * I/O completion
2787  * ==========================================================================
2788  */
2789 static int
2790 zio_ready(zio_t *zio)
2791 {
2792         blkptr_t *bp = zio->io_bp;
2793         zio_t *pio, *pio_next;
2794 
2795         if (zio_wait_for_children(zio, ZIO_CHILD_GANG, ZIO_WAIT_READY) ||
2796             zio_wait_for_children(zio, ZIO_CHILD_DDT, ZIO_WAIT_READY))
2797                 return (ZIO_PIPELINE_STOP);
2798 
2799         if (zio->io_ready) {
2800                 ASSERT(IO_IS_ALLOCATING(zio));
2801                 ASSERT(bp->blk_birth == zio->io_txg || BP_IS_HOLE(bp) ||
2802                     (zio->io_flags & ZIO_FLAG_NOPWRITE));
2803                 ASSERT(zio->io_children[ZIO_CHILD_GANG][ZIO_WAIT_READY] == 0);
2804 
2805                 zio->io_ready(zio);
2806         }
2807 
2808         if (bp != NULL && bp != &zio->io_bp_copy)
2809                 zio->io_bp_copy = *bp;
2810 
2811         if (zio->io_error)
2812                 zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
2813 
2814         mutex_enter(&zio->io_lock);
2815         zio->io_state[ZIO_WAIT_READY] = 1;
2816         pio = zio_walk_parents(zio);
2817         mutex_exit(&zio->io_lock);
2818 
2819         /*
2820          * As we notify zio's parents, new parents could be added.
2821          * New parents go to the head of zio's io_parent_list, however,
2822          * so we will (correctly) not notify them.  The remainder of zio's
2823          * io_parent_list, from 'pio_next' onward, cannot change because
2824          * all parents must wait for us to be done before they can be done.
2825          */
2826         for (; pio != NULL; pio = pio_next) {
2827                 pio_next = zio_walk_parents(zio);
2828                 zio_notify_parent(pio, zio, ZIO_WAIT_READY);
2829         }
2830 
2831         if (zio->io_flags & ZIO_FLAG_NODATA) {
2832                 if (BP_IS_GANG(bp)) {
2833                         zio->io_flags &= ~ZIO_FLAG_NODATA;
2834                 } else {
2835                         ASSERT((uintptr_t)zio->io_data < SPA_MAXBLOCKSIZE);
2836                         zio->io_pipeline &= ~ZIO_VDEV_IO_STAGES;
2837                 }
2838         }
2839 
2840         if (zio_injection_enabled &&
2841             zio->io_spa->spa_syncing_txg == zio->io_txg)
2842                 zio_handle_ignored_writes(zio);
2843 
2844         return (ZIO_PIPELINE_CONTINUE);
2845 }
2846 
2847 static int
2848 zio_done(zio_t *zio)
2849 {
2850         spa_t *spa = zio->io_spa;
2851         zio_t *lio = zio->io_logical;
2852         blkptr_t *bp = zio->io_bp;
2853         vdev_t *vd = zio->io_vd;
2854         uint64_t psize = zio->io_size;
2855         zio_t *pio, *pio_next;
2856 
2857         /*
2858          * If our children haven't all completed,
2859          * wait for them and then repeat this pipeline stage.
2860          */
2861         if (zio_wait_for_children(zio, ZIO_CHILD_VDEV, ZIO_WAIT_DONE) ||
2862             zio_wait_for_children(zio, ZIO_CHILD_GANG, ZIO_WAIT_DONE) ||
2863             zio_wait_for_children(zio, ZIO_CHILD_DDT, ZIO_WAIT_DONE) ||
2864             zio_wait_for_children(zio, ZIO_CHILD_LOGICAL, ZIO_WAIT_DONE))
2865                 return (ZIO_PIPELINE_STOP);
2866 
2867         for (int c = 0; c < ZIO_CHILD_TYPES; c++)
2868                 for (int w = 0; w < ZIO_WAIT_TYPES; w++)
2869                         ASSERT(zio->io_children[c][w] == 0);
2870 
2871         if (bp != NULL) {
2872                 ASSERT(bp->blk_pad[0] == 0);
2873                 ASSERT(bp->blk_pad[1] == 0);
2874                 ASSERT(bcmp(bp, &zio->io_bp_copy, sizeof (blkptr_t)) == 0 ||
2875                     (bp == zio_unique_parent(zio)->io_bp));
2876                 if (zio->io_type == ZIO_TYPE_WRITE && !BP_IS_HOLE(bp) &&
2877                     zio->io_bp_override == NULL &&
2878                     !(zio->io_flags & ZIO_FLAG_IO_REPAIR)) {
2879                         ASSERT(!BP_SHOULD_BYTESWAP(bp));
2880                         ASSERT3U(zio->io_prop.zp_copies, <=, BP_GET_NDVAS(bp));
2881                         ASSERT(BP_COUNT_GANG(bp) == 0 ||
2882                             (BP_COUNT_GANG(bp) == BP_GET_NDVAS(bp)));
2883                 }
2884                 if (zio->io_flags & ZIO_FLAG_NOPWRITE)
2885                         VERIFY(BP_EQUAL(bp, &zio->io_bp_orig));
2886         }
2887 
2888         /*
2889          * If there were child vdev/gang/ddt errors, they apply to us now.
2890          */
2891         zio_inherit_child_errors(zio, ZIO_CHILD_VDEV);
2892         zio_inherit_child_errors(zio, ZIO_CHILD_GANG);
2893         zio_inherit_child_errors(zio, ZIO_CHILD_DDT);
2894 
2895         /*
2896          * If the I/O on the transformed data was successful, generate any
2897          * checksum reports now while we still have the transformed data.
2898          */
2899         if (zio->io_error == 0) {
2900                 while (zio->io_cksum_report != NULL) {
2901                         zio_cksum_report_t *zcr = zio->io_cksum_report;
2902                         uint64_t align = zcr->zcr_align;
2903                         uint64_t asize = P2ROUNDUP(psize, align);
2904                         char *abuf = zio->io_data;
2905 
2906                         if (asize != psize) {
2907                                 abuf = zio_buf_alloc(asize);
2908                                 bcopy(zio->io_data, abuf, psize);
2909                                 bzero(abuf + psize, asize - psize);
2910                         }
2911 
2912                         zio->io_cksum_report = zcr->zcr_next;
2913                         zcr->zcr_next = NULL;
2914                         zcr->zcr_finish(zcr, abuf);
2915                         zfs_ereport_free_checksum(zcr);
2916 
2917                         if (asize != psize)
2918                                 zio_buf_free(abuf, asize);
2919                 }
2920         }
2921 
2922         zio_pop_transforms(zio);        /* note: may set zio->io_error */
2923 
2924         vdev_stat_update(zio, psize);
2925 
2926         if (zio->io_error) {
2927                 /*
2928                  * If this I/O is attached to a particular vdev,
2929                  * generate an error message describing the I/O failure
2930                  * at the block level.  We ignore these errors if the
2931                  * device is currently unavailable.
2932                  */
2933                 if (zio->io_error != ECKSUM && vd != NULL && !vdev_is_dead(vd))
2934                         zfs_ereport_post(FM_EREPORT_ZFS_IO, spa, vd, zio, 0, 0);
2935 
2936                 if ((zio->io_error == EIO || !(zio->io_flags &
2937                     (ZIO_FLAG_SPECULATIVE | ZIO_FLAG_DONT_PROPAGATE))) &&
2938                     zio == lio) {
2939                         /*
2940                          * For logical I/O requests, tell the SPA to log the
2941                          * error and generate a logical data ereport.
2942                          */
2943                         spa_log_error(spa, zio);
2944                         zfs_ereport_post(FM_EREPORT_ZFS_DATA, spa, NULL, zio,
2945                             0, 0);
2946                 }
2947         }
2948 
2949         if (zio->io_error && zio == lio) {
2950                 /*
2951                  * Determine whether zio should be reexecuted.  This will
2952                  * propagate all the way to the root via zio_notify_parent().
2953                  */
2954                 ASSERT(vd == NULL && bp != NULL);
2955                 ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
2956 
2957                 if (IO_IS_ALLOCATING(zio) &&
2958                     !(zio->io_flags & ZIO_FLAG_CANFAIL)) {
2959                         if (zio->io_error != ENOSPC)
2960                                 zio->io_reexecute |= ZIO_REEXECUTE_NOW;
2961                         else
2962                                 zio->io_reexecute |= ZIO_REEXECUTE_SUSPEND;
2963                 }
2964 
2965                 if ((zio->io_type == ZIO_TYPE_READ ||
2966                     zio->io_type == ZIO_TYPE_FREE) &&
2967                     !(zio->io_flags & ZIO_FLAG_SCAN_THREAD) &&
2968                     zio->io_error == ENXIO &&
2969                     spa_load_state(spa) == SPA_LOAD_NONE &&
2970                     spa_get_failmode(spa) != ZIO_FAILURE_MODE_CONTINUE)
2971                         zio->io_reexecute |= ZIO_REEXECUTE_SUSPEND;
2972 
2973                 if (!(zio->io_flags & ZIO_FLAG_CANFAIL) && !zio->io_reexecute)
2974                         zio->io_reexecute |= ZIO_REEXECUTE_SUSPEND;
2975 
2976                 /*
2977                  * Here is a possibly good place to attempt to do
2978                  * either combinatorial reconstruction or error correction
2979                  * based on checksums.  It also might be a good place
2980                  * to send out preliminary ereports before we suspend
2981                  * processing.
2982                  */
2983         }
2984 
2985         /*
2986          * If there were logical child errors, they apply to us now.
2987          * We defer this until now to avoid conflating logical child
2988          * errors with errors that happened to the zio itself when
2989          * updating vdev stats and reporting FMA events above.
2990          */
2991         zio_inherit_child_errors(zio, ZIO_CHILD_LOGICAL);
2992 
2993         if ((zio->io_error || zio->io_reexecute) &&
2994             IO_IS_ALLOCATING(zio) && zio->io_gang_leader == zio &&
2995             !(zio->io_flags & (ZIO_FLAG_IO_REWRITE | ZIO_FLAG_NOPWRITE)))
2996                 zio_dva_unallocate(zio, zio->io_gang_tree, bp);
2997 
2998         zio_gang_tree_free(&zio->io_gang_tree);
2999 
3000         /*
3001          * Godfather I/Os should never suspend.
3002          */
3003         if ((zio->io_flags & ZIO_FLAG_GODFATHER) &&
3004             (zio->io_reexecute & ZIO_REEXECUTE_SUSPEND))
3005                 zio->io_reexecute = 0;
3006 
3007         if (zio->io_reexecute) {
3008                 /*
3009                  * This is a logical I/O that wants to reexecute.
3010                  *
3011                  * Reexecute is top-down.  When an i/o fails, if it's not
3012                  * the root, it simply notifies its parent and sticks around.
3013                  * The parent, seeing that it still has children in zio_done(),
3014                  * does the same.  This percolates all the way up to the root.
3015                  * The root i/o will reexecute or suspend the entire tree.
3016                  *
3017                  * This approach ensures that zio_reexecute() honors
3018                  * all the original i/o dependency relationships, e.g.
3019                  * parents not executing until children are ready.
3020                  */
3021                 ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
3022 
3023                 zio->io_gang_leader = NULL;
3024 
3025                 mutex_enter(&zio->io_lock);
3026                 zio->io_state[ZIO_WAIT_DONE] = 1;
3027                 mutex_exit(&zio->io_lock);
3028 
3029                 /*
3030                  * "The Godfather" I/O monitors its children but is
3031                  * not a true parent to them. It will track them through
3032                  * the pipeline but severs its ties whenever they get into
3033                  * trouble (e.g. suspended). This allows "The Godfather"
3034                  * I/O to return status without blocking.
3035                  */
3036                 for (pio = zio_walk_parents(zio); pio != NULL; pio = pio_next) {
3037                         zio_link_t *zl = zio->io_walk_link;
3038                         pio_next = zio_walk_parents(zio);
3039 
3040                         if ((pio->io_flags & ZIO_FLAG_GODFATHER) &&
3041                             (zio->io_reexecute & ZIO_REEXECUTE_SUSPEND)) {
3042                                 zio_remove_child(pio, zio, zl);
3043                                 zio_notify_parent(pio, zio, ZIO_WAIT_DONE);
3044                         }
3045                 }
3046 
3047                 if ((pio = zio_unique_parent(zio)) != NULL) {
3048                         /*
3049                          * We're not a root i/o, so there's nothing to do
3050                          * but notify our parent.  Don't propagate errors
3051                          * upward since we haven't permanently failed yet.
3052                          */
3053                         ASSERT(!(zio->io_flags & ZIO_FLAG_GODFATHER));
3054                         zio->io_flags |= ZIO_FLAG_DONT_PROPAGATE;
3055                         zio_notify_parent(pio, zio, ZIO_WAIT_DONE);
3056                 } else if (zio->io_reexecute & ZIO_REEXECUTE_SUSPEND) {
3057                         /*
3058                          * We'd fail again if we reexecuted now, so suspend
3059                          * until conditions improve (e.g. device comes online).
3060                          */
3061                         zio_suspend(spa, zio);
3062                 } else {
3063                         /*
3064                          * Reexecution is potentially a huge amount of work.
3065                          * Hand it off to the otherwise-unused claim taskq.
3066                          */
3067                         ASSERT(zio->io_tqent.tqent_next == NULL);
3068                         spa_taskq_dispatch_ent(spa, ZIO_TYPE_CLAIM,
3069                             ZIO_TASKQ_ISSUE, (task_func_t *)zio_reexecute, zio,
3070                             0, &zio->io_tqent);
3071                 }
3072                 return (ZIO_PIPELINE_STOP);
3073         }
3074 
3075         ASSERT(zio->io_child_count == 0);
3076         ASSERT(zio->io_reexecute == 0);
3077         ASSERT(zio->io_error == 0 || (zio->io_flags & ZIO_FLAG_CANFAIL));
3078 
3079         /*
3080          * Report any checksum errors, since the I/O is complete.
3081          */
3082         while (zio->io_cksum_report != NULL) {
3083                 zio_cksum_report_t *zcr = zio->io_cksum_report;
3084                 zio->io_cksum_report = zcr->zcr_next;
3085                 zcr->zcr_next = NULL;
3086                 zcr->zcr_finish(zcr, NULL);
3087                 zfs_ereport_free_checksum(zcr);
3088         }
3089 
3090         /*
3091          * It is the responsibility of the done callback to ensure that this
3092          * particular zio is no longer discoverable for adoption, and as
3093          * such, cannot acquire any new parents.
3094          */
3095         if (zio->io_done)
3096                 zio->io_done(zio);
3097 
3098         mutex_enter(&zio->io_lock);
3099         zio->io_state[ZIO_WAIT_DONE] = 1;
3100         mutex_exit(&zio->io_lock);
3101 
3102         for (pio = zio_walk_parents(zio); pio != NULL; pio = pio_next) {
3103                 zio_link_t *zl = zio->io_walk_link;
3104                 pio_next = zio_walk_parents(zio);
3105                 zio_remove_child(pio, zio, zl);
3106                 zio_notify_parent(pio, zio, ZIO_WAIT_DONE);
3107         }
3108 
3109         if (zio->io_waiter != NULL) {
3110                 mutex_enter(&zio->io_lock);
3111                 zio->io_executor = NULL;
3112                 cv_broadcast(&zio->io_cv);
3113                 mutex_exit(&zio->io_lock);
3114         } else {
3115                 zio_destroy(zio);
3116         }
3117 
3118         return (ZIO_PIPELINE_STOP);
3119 }
3120 
3121 /*
3122  * ==========================================================================
3123  * I/O pipeline definition
3124  * ==========================================================================
3125  */
3126 static zio_pipe_stage_t *zio_pipeline[] = {
3127         NULL,
3128         zio_read_bp_init,
3129         zio_free_bp_init,
3130         zio_issue_async,
3131         zio_write_bp_init,
3132         zio_checksum_generate,
3133         zio_nop_write,
3134         zio_ddt_read_start,
3135         zio_ddt_read_done,
3136         zio_ddt_write,
3137         zio_ddt_free,
3138         zio_gang_assemble,
3139         zio_gang_issue,
3140         zio_dva_allocate,
3141         zio_dva_free,
3142         zio_dva_claim,
3143         zio_ready,
3144         zio_vdev_io_start,
3145         zio_vdev_io_done,
3146         zio_vdev_io_assess,
3147         zio_checksum_verify,
3148         zio_done
3149 };
3150 
3151 /* dnp is the dnode for zb1->zb_object */
3152 boolean_t
3153 zbookmark_is_before(const dnode_phys_t *dnp, const zbookmark_t *zb1,
3154     const zbookmark_t *zb2)
3155 {
3156         uint64_t zb1nextL0, zb2thisobj;
3157 
3158         ASSERT(zb1->zb_objset == zb2->zb_objset);
3159         ASSERT(zb2->zb_level == 0);
3160 
3161         /*
3162          * A bookmark in the deadlist is considered to be after
3163          * everything else.
3164          */
3165         if (zb2->zb_object == DMU_DEADLIST_OBJECT)
3166                 return (B_TRUE);
3167 
3168         /* The objset_phys_t isn't before anything. */
3169         if (dnp == NULL)
3170                 return (B_FALSE);
3171 
3172         zb1nextL0 = (zb1->zb_blkid + 1) <<
3173             ((zb1->zb_level) * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT));
3174 
3175         zb2thisobj = zb2->zb_object ? zb2->zb_object :
3176             zb2->zb_blkid << (DNODE_BLOCK_SHIFT - DNODE_SHIFT);
3177 
3178         if (zb1->zb_object == DMU_META_DNODE_OBJECT) {
3179                 uint64_t nextobj = zb1nextL0 *
3180                     (dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT) >> DNODE_SHIFT;
3181                 return (nextobj <= zb2thisobj);
3182         }
3183 
3184         if (zb1->zb_object < zb2thisobj)
3185                 return (B_TRUE);
3186         if (zb1->zb_object > zb2thisobj)
3187                 return (B_FALSE);
3188         if (zb2->zb_object == DMU_META_DNODE_OBJECT)
3189                 return (B_FALSE);
3190         return (zb1nextL0 <= zb2->zb_blkid);
3191 }