1 /*
   2  * CDDL HEADER START
   3  *
   4  * The contents of this file are subject to the terms of the
   5  * Common Development and Distribution License (the "License").
   6  * You may not use this file except in compliance with the License.
   7  *
   8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
   9  * or http://www.opensolaris.org/os/licensing.
  10  * See the License for the specific language governing permissions
  11  * and limitations under the License.
  12  *
  13  * When distributing Covered Code, include this CDDL HEADER in each
  14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
  15  * If applicable, add the following below this CDDL HEADER, with the
  16  * fields enclosed by brackets "[]" replaced with your own identifying
  17  * information: Portions Copyright [yyyy] [name of copyright owner]
  18  *
  19  * CDDL HEADER END
  20  */
  21 
  22 /*
  23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
  24  * Copyright (c) 2011, 2018 by Delphix. All rights reserved.
  25  * Copyright 2017 Nexenta Systems, Inc.
  26  * Copyright (c) 2014 Integros [integros.com]
  27  * Copyright 2016 Toomas Soome <tsoome@me.com>
  28  * Copyright 2017 Joyent, Inc.
  29  * Copyright (c) 2017, Intel Corporation.
  30  */
  31 
  32 #include <sys/zfs_context.h>
  33 #include <sys/fm/fs/zfs.h>
  34 #include <sys/spa.h>
  35 #include <sys/spa_impl.h>
  36 #include <sys/bpobj.h>
  37 #include <sys/dmu.h>
  38 #include <sys/dmu_tx.h>
  39 #include <sys/dsl_dir.h>
  40 #include <sys/vdev_impl.h>
  41 #include <sys/uberblock_impl.h>
  42 #include <sys/metaslab.h>
  43 #include <sys/metaslab_impl.h>
  44 #include <sys/space_map.h>
  45 #include <sys/space_reftree.h>
  46 #include <sys/zio.h>
  47 #include <sys/zap.h>
  48 #include <sys/fs/zfs.h>
  49 #include <sys/arc.h>
  50 #include <sys/zil.h>
  51 #include <sys/dsl_scan.h>
  52 #include <sys/abd.h>
  53 #include <sys/vdev_initialize.h>
  54 
  55 /*
  56  * Virtual device management.
  57  */
  58 
  59 static vdev_ops_t *vdev_ops_table[] = {
  60         &vdev_root_ops,
  61         &vdev_raidz_ops,
  62         &vdev_mirror_ops,
  63         &vdev_replacing_ops,
  64         &vdev_spare_ops,
  65         &vdev_disk_ops,
  66         &vdev_file_ops,
  67         &vdev_missing_ops,
  68         &vdev_hole_ops,
  69         &vdev_indirect_ops,
  70         NULL
  71 };
  72 
  73 /* maximum scrub/resilver I/O queue per leaf vdev */
  74 int zfs_scrub_limit = 10;
  75 
  76 /* default target for number of metaslabs per top-level vdev */
  77 int zfs_vdev_default_ms_count = 200;
  78 
  79 /* minimum number of metaslabs per top-level vdev */
  80 int zfs_vdev_min_ms_count = 16;
  81 
  82 /* practical upper limit of total metaslabs per top-level vdev */
  83 int zfs_vdev_ms_count_limit = 1ULL << 17;
  84 
  85 /* lower limit for metaslab size (512M) */
  86 int zfs_vdev_default_ms_shift = 29;
  87 
  88 /* upper limit for metaslab size (16G) */
  89 int zfs_vdev_max_ms_shift = 34;
  90 
  91 boolean_t vdev_validate_skip = B_FALSE;
  92 
  93 /*
  94  * Since the DTL space map of a vdev is not expected to have a lot of
  95  * entries, we default its block size to 4K.
  96  */
  97 int vdev_dtl_sm_blksz = (1 << 12);
  98 
  99 /*
 100  * vdev-wide space maps that have lots of entries written to them at
 101  * the end of each transaction can benefit from a higher I/O bandwidth
 102  * (e.g. vdev_obsolete_sm), thus we default their block size to 128K.
 103  */
 104 int vdev_standard_sm_blksz = (1 << 17);
 105 
 106 int zfs_ashift_min;
 107 
 108 /*PRINTFLIKE2*/
 109 void
 110 vdev_dbgmsg(vdev_t *vd, const char *fmt, ...)
 111 {
 112         va_list adx;
 113         char buf[256];
 114 
 115         va_start(adx, fmt);
 116         (void) vsnprintf(buf, sizeof (buf), fmt, adx);
 117         va_end(adx);
 118 
 119         if (vd->vdev_path != NULL) {
 120                 zfs_dbgmsg("%s vdev '%s': %s", vd->vdev_ops->vdev_op_type,
 121                     vd->vdev_path, buf);
 122         } else {
 123                 zfs_dbgmsg("%s-%llu vdev (guid %llu): %s",
 124                     vd->vdev_ops->vdev_op_type,
 125                     (u_longlong_t)vd->vdev_id,
 126                     (u_longlong_t)vd->vdev_guid, buf);
 127         }
 128 }
 129 
 130 void
 131 vdev_dbgmsg_print_tree(vdev_t *vd, int indent)
 132 {
 133         char state[20];
 134 
 135         if (vd->vdev_ishole || vd->vdev_ops == &vdev_missing_ops) {
 136                 zfs_dbgmsg("%*svdev %u: %s", indent, "", vd->vdev_id,
 137                     vd->vdev_ops->vdev_op_type);
 138                 return;
 139         }
 140 
 141         switch (vd->vdev_state) {
 142         case VDEV_STATE_UNKNOWN:
 143                 (void) snprintf(state, sizeof (state), "unknown");
 144                 break;
 145         case VDEV_STATE_CLOSED:
 146                 (void) snprintf(state, sizeof (state), "closed");
 147                 break;
 148         case VDEV_STATE_OFFLINE:
 149                 (void) snprintf(state, sizeof (state), "offline");
 150                 break;
 151         case VDEV_STATE_REMOVED:
 152                 (void) snprintf(state, sizeof (state), "removed");
 153                 break;
 154         case VDEV_STATE_CANT_OPEN:
 155                 (void) snprintf(state, sizeof (state), "can't open");
 156                 break;
 157         case VDEV_STATE_FAULTED:
 158                 (void) snprintf(state, sizeof (state), "faulted");
 159                 break;
 160         case VDEV_STATE_DEGRADED:
 161                 (void) snprintf(state, sizeof (state), "degraded");
 162                 break;
 163         case VDEV_STATE_HEALTHY:
 164                 (void) snprintf(state, sizeof (state), "healthy");
 165                 break;
 166         default:
 167                 (void) snprintf(state, sizeof (state), "<state %u>",
 168                     (uint_t)vd->vdev_state);
 169         }
 170 
 171         zfs_dbgmsg("%*svdev %u: %s%s, guid: %llu, path: %s, %s", indent,
 172             "", (int)vd->vdev_id, vd->vdev_ops->vdev_op_type,
 173             vd->vdev_islog ? " (log)" : "",
 174             (u_longlong_t)vd->vdev_guid,
 175             vd->vdev_path ? vd->vdev_path : "N/A", state);
 176 
 177         for (uint64_t i = 0; i < vd->vdev_children; i++)
 178                 vdev_dbgmsg_print_tree(vd->vdev_child[i], indent + 2);
 179 }
 180 
 181 /*
 182  * Given a vdev type, return the appropriate ops vector.
 183  */
 184 static vdev_ops_t *
 185 vdev_getops(const char *type)
 186 {
 187         vdev_ops_t *ops, **opspp;
 188 
 189         for (opspp = vdev_ops_table; (ops = *opspp) != NULL; opspp++)
 190                 if (strcmp(ops->vdev_op_type, type) == 0)
 191                         break;
 192 
 193         return (ops);
 194 }
 195 
 196 /*
 197  * Derive the enumerated alloction bias from string input.
 198  * String origin is either the per-vdev zap or zpool(1M).
 199  */
 200 static vdev_alloc_bias_t
 201 vdev_derive_alloc_bias(const char *bias)
 202 {
 203         vdev_alloc_bias_t alloc_bias = VDEV_BIAS_NONE;
 204 
 205         if (strcmp(bias, VDEV_ALLOC_BIAS_LOG) == 0)
 206                 alloc_bias = VDEV_BIAS_LOG;
 207         else if (strcmp(bias, VDEV_ALLOC_BIAS_SPECIAL) == 0)
 208                 alloc_bias = VDEV_BIAS_SPECIAL;
 209         else if (strcmp(bias, VDEV_ALLOC_BIAS_DEDUP) == 0)
 210                 alloc_bias = VDEV_BIAS_DEDUP;
 211 
 212         return (alloc_bias);
 213 }
 214 
 215 /* ARGSUSED */
 216 void
 217 vdev_default_xlate(vdev_t *vd, const range_seg_t *in, range_seg_t *res)
 218 {
 219         res->rs_start = in->rs_start;
 220         res->rs_end = in->rs_end;
 221 }
 222 
 223 /*
 224  * Default asize function: return the MAX of psize with the asize of
 225  * all children.  This is what's used by anything other than RAID-Z.
 226  */
 227 uint64_t
 228 vdev_default_asize(vdev_t *vd, uint64_t psize)
 229 {
 230         uint64_t asize = P2ROUNDUP(psize, 1ULL << vd->vdev_top->vdev_ashift);
 231         uint64_t csize;
 232 
 233         for (int c = 0; c < vd->vdev_children; c++) {
 234                 csize = vdev_psize_to_asize(vd->vdev_child[c], psize);
 235                 asize = MAX(asize, csize);
 236         }
 237 
 238         return (asize);
 239 }
 240 
 241 /*
 242  * Get the minimum allocatable size. We define the allocatable size as
 243  * the vdev's asize rounded to the nearest metaslab. This allows us to
 244  * replace or attach devices which don't have the same physical size but
 245  * can still satisfy the same number of allocations.
 246  */
 247 uint64_t
 248 vdev_get_min_asize(vdev_t *vd)
 249 {
 250         vdev_t *pvd = vd->vdev_parent;
 251 
 252         /*
 253          * If our parent is NULL (inactive spare or cache) or is the root,
 254          * just return our own asize.
 255          */
 256         if (pvd == NULL)
 257                 return (vd->vdev_asize);
 258 
 259         /*
 260          * The top-level vdev just returns the allocatable size rounded
 261          * to the nearest metaslab.
 262          */
 263         if (vd == vd->vdev_top)
 264                 return (P2ALIGN(vd->vdev_asize, 1ULL << vd->vdev_ms_shift));
 265 
 266         /*
 267          * The allocatable space for a raidz vdev is N * sizeof(smallest child),
 268          * so each child must provide at least 1/Nth of its asize.
 269          */
 270         if (pvd->vdev_ops == &vdev_raidz_ops)
 271                 return ((pvd->vdev_min_asize + pvd->vdev_children - 1) /
 272                     pvd->vdev_children);
 273 
 274         return (pvd->vdev_min_asize);
 275 }
 276 
 277 void
 278 vdev_set_min_asize(vdev_t *vd)
 279 {
 280         vd->vdev_min_asize = vdev_get_min_asize(vd);
 281 
 282         for (int c = 0; c < vd->vdev_children; c++)
 283                 vdev_set_min_asize(vd->vdev_child[c]);
 284 }
 285 
 286 vdev_t *
 287 vdev_lookup_top(spa_t *spa, uint64_t vdev)
 288 {
 289         vdev_t *rvd = spa->spa_root_vdev;
 290 
 291         ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
 292 
 293         if (vdev < rvd->vdev_children) {
 294                 ASSERT(rvd->vdev_child[vdev] != NULL);
 295                 return (rvd->vdev_child[vdev]);
 296         }
 297 
 298         return (NULL);
 299 }
 300 
 301 vdev_t *
 302 vdev_lookup_by_guid(vdev_t *vd, uint64_t guid)
 303 {
 304         vdev_t *mvd;
 305 
 306         if (vd->vdev_guid == guid)
 307                 return (vd);
 308 
 309         for (int c = 0; c < vd->vdev_children; c++)
 310                 if ((mvd = vdev_lookup_by_guid(vd->vdev_child[c], guid)) !=
 311                     NULL)
 312                         return (mvd);
 313 
 314         return (NULL);
 315 }
 316 
 317 static int
 318 vdev_count_leaves_impl(vdev_t *vd)
 319 {
 320         int n = 0;
 321 
 322         if (vd->vdev_ops->vdev_op_leaf)
 323                 return (1);
 324 
 325         for (int c = 0; c < vd->vdev_children; c++)
 326                 n += vdev_count_leaves_impl(vd->vdev_child[c]);
 327 
 328         return (n);
 329 }
 330 
 331 int
 332 vdev_count_leaves(spa_t *spa)
 333 {
 334         return (vdev_count_leaves_impl(spa->spa_root_vdev));
 335 }
 336 
 337 void
 338 vdev_add_child(vdev_t *pvd, vdev_t *cvd)
 339 {
 340         size_t oldsize, newsize;
 341         uint64_t id = cvd->vdev_id;
 342         vdev_t **newchild;
 343         spa_t *spa = cvd->vdev_spa;
 344 
 345         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
 346         ASSERT(cvd->vdev_parent == NULL);
 347 
 348         cvd->vdev_parent = pvd;
 349 
 350         if (pvd == NULL)
 351                 return;
 352 
 353         ASSERT(id >= pvd->vdev_children || pvd->vdev_child[id] == NULL);
 354 
 355         oldsize = pvd->vdev_children * sizeof (vdev_t *);
 356         pvd->vdev_children = MAX(pvd->vdev_children, id + 1);
 357         newsize = pvd->vdev_children * sizeof (vdev_t *);
 358 
 359         newchild = kmem_zalloc(newsize, KM_SLEEP);
 360         if (pvd->vdev_child != NULL) {
 361                 bcopy(pvd->vdev_child, newchild, oldsize);
 362                 kmem_free(pvd->vdev_child, oldsize);
 363         }
 364 
 365         pvd->vdev_child = newchild;
 366         pvd->vdev_child[id] = cvd;
 367 
 368         cvd->vdev_top = (pvd->vdev_top ? pvd->vdev_top: cvd);
 369         ASSERT(cvd->vdev_top->vdev_parent->vdev_parent == NULL);
 370 
 371         /*
 372          * Walk up all ancestors to update guid sum.
 373          */
 374         for (; pvd != NULL; pvd = pvd->vdev_parent)
 375                 pvd->vdev_guid_sum += cvd->vdev_guid_sum;
 376 
 377         if (cvd->vdev_ops->vdev_op_leaf) {
 378                 list_insert_head(&cvd->vdev_spa->spa_leaf_list, cvd);
 379                 cvd->vdev_spa->spa_leaf_list_gen++;
 380         }
 381 }
 382 
 383 void
 384 vdev_remove_child(vdev_t *pvd, vdev_t *cvd)
 385 {
 386         int c;
 387         uint_t id = cvd->vdev_id;
 388 
 389         ASSERT(cvd->vdev_parent == pvd);
 390 
 391         if (pvd == NULL)
 392                 return;
 393 
 394         ASSERT(id < pvd->vdev_children);
 395         ASSERT(pvd->vdev_child[id] == cvd);
 396 
 397         pvd->vdev_child[id] = NULL;
 398         cvd->vdev_parent = NULL;
 399 
 400         for (c = 0; c < pvd->vdev_children; c++)
 401                 if (pvd->vdev_child[c])
 402                         break;
 403 
 404         if (c == pvd->vdev_children) {
 405                 kmem_free(pvd->vdev_child, c * sizeof (vdev_t *));
 406                 pvd->vdev_child = NULL;
 407                 pvd->vdev_children = 0;
 408         }
 409 
 410         if (cvd->vdev_ops->vdev_op_leaf) {
 411                 spa_t *spa = cvd->vdev_spa;
 412                 list_remove(&spa->spa_leaf_list, cvd);
 413                 spa->spa_leaf_list_gen++;
 414         }
 415 
 416         /*
 417          * Walk up all ancestors to update guid sum.
 418          */
 419         for (; pvd != NULL; pvd = pvd->vdev_parent)
 420                 pvd->vdev_guid_sum -= cvd->vdev_guid_sum;
 421 }
 422 
 423 /*
 424  * Remove any holes in the child array.
 425  */
 426 void
 427 vdev_compact_children(vdev_t *pvd)
 428 {
 429         vdev_t **newchild, *cvd;
 430         int oldc = pvd->vdev_children;
 431         int newc;
 432 
 433         ASSERT(spa_config_held(pvd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
 434 
 435         for (int c = newc = 0; c < oldc; c++)
 436                 if (pvd->vdev_child[c])
 437                         newc++;
 438 
 439         newchild = kmem_alloc(newc * sizeof (vdev_t *), KM_SLEEP);
 440 
 441         for (int c = newc = 0; c < oldc; c++) {
 442                 if ((cvd = pvd->vdev_child[c]) != NULL) {
 443                         newchild[newc] = cvd;
 444                         cvd->vdev_id = newc++;
 445                 }
 446         }
 447 
 448         kmem_free(pvd->vdev_child, oldc * sizeof (vdev_t *));
 449         pvd->vdev_child = newchild;
 450         pvd->vdev_children = newc;
 451 }
 452 
 453 /*
 454  * Allocate and minimally initialize a vdev_t.
 455  */
 456 vdev_t *
 457 vdev_alloc_common(spa_t *spa, uint_t id, uint64_t guid, vdev_ops_t *ops)
 458 {
 459         vdev_t *vd;
 460         vdev_indirect_config_t *vic;
 461 
 462         vd = kmem_zalloc(sizeof (vdev_t), KM_SLEEP);
 463         vic = &vd->vdev_indirect_config;
 464 
 465         if (spa->spa_root_vdev == NULL) {
 466                 ASSERT(ops == &vdev_root_ops);
 467                 spa->spa_root_vdev = vd;
 468                 spa->spa_load_guid = spa_generate_guid(NULL);
 469         }
 470 
 471         if (guid == 0 && ops != &vdev_hole_ops) {
 472                 if (spa->spa_root_vdev == vd) {
 473                         /*
 474                          * The root vdev's guid will also be the pool guid,
 475                          * which must be unique among all pools.
 476                          */
 477                         guid = spa_generate_guid(NULL);
 478                 } else {
 479                         /*
 480                          * Any other vdev's guid must be unique within the pool.
 481                          */
 482                         guid = spa_generate_guid(spa);
 483                 }
 484                 ASSERT(!spa_guid_exists(spa_guid(spa), guid));
 485         }
 486 
 487         vd->vdev_spa = spa;
 488         vd->vdev_id = id;
 489         vd->vdev_guid = guid;
 490         vd->vdev_guid_sum = guid;
 491         vd->vdev_ops = ops;
 492         vd->vdev_state = VDEV_STATE_CLOSED;
 493         vd->vdev_ishole = (ops == &vdev_hole_ops);
 494         vic->vic_prev_indirect_vdev = UINT64_MAX;
 495 
 496         rw_init(&vd->vdev_indirect_rwlock, NULL, RW_DEFAULT, NULL);
 497         mutex_init(&vd->vdev_obsolete_lock, NULL, MUTEX_DEFAULT, NULL);
 498         vd->vdev_obsolete_segments = range_tree_create(NULL, NULL);
 499 
 500         list_link_init(&vd->vdev_leaf_node);
 501         mutex_init(&vd->vdev_dtl_lock, NULL, MUTEX_DEFAULT, NULL);
 502         mutex_init(&vd->vdev_stat_lock, NULL, MUTEX_DEFAULT, NULL);
 503         mutex_init(&vd->vdev_probe_lock, NULL, MUTEX_DEFAULT, NULL);
 504         mutex_init(&vd->vdev_queue_lock, NULL, MUTEX_DEFAULT, NULL);
 505         mutex_init(&vd->vdev_initialize_lock, NULL, MUTEX_DEFAULT, NULL);
 506         mutex_init(&vd->vdev_initialize_io_lock, NULL, MUTEX_DEFAULT, NULL);
 507         cv_init(&vd->vdev_initialize_cv, NULL, CV_DEFAULT, NULL);
 508         cv_init(&vd->vdev_initialize_io_cv, NULL, CV_DEFAULT, NULL);
 509 
 510         for (int t = 0; t < DTL_TYPES; t++) {
 511                 vd->vdev_dtl[t] = range_tree_create(NULL, NULL);
 512         }
 513         txg_list_create(&vd->vdev_ms_list, spa,
 514             offsetof(struct metaslab, ms_txg_node));
 515         txg_list_create(&vd->vdev_dtl_list, spa,
 516             offsetof(struct vdev, vdev_dtl_node));
 517         vd->vdev_stat.vs_timestamp = gethrtime();
 518         vdev_queue_init(vd);
 519         vdev_cache_init(vd);
 520 
 521         return (vd);
 522 }
 523 
 524 /*
 525  * Allocate a new vdev.  The 'alloctype' is used to control whether we are
 526  * creating a new vdev or loading an existing one - the behavior is slightly
 527  * different for each case.
 528  */
 529 int
 530 vdev_alloc(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent, uint_t id,
 531     int alloctype)
 532 {
 533         vdev_ops_t *ops;
 534         char *type;
 535         uint64_t guid = 0, islog, nparity;
 536         vdev_t *vd;
 537         vdev_indirect_config_t *vic;
 538         vdev_alloc_bias_t alloc_bias = VDEV_BIAS_NONE;
 539         boolean_t top_level = (parent && !parent->vdev_parent);
 540 
 541         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
 542 
 543         if (nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) != 0)
 544                 return (SET_ERROR(EINVAL));
 545 
 546         if ((ops = vdev_getops(type)) == NULL)
 547                 return (SET_ERROR(EINVAL));
 548 
 549         /*
 550          * If this is a load, get the vdev guid from the nvlist.
 551          * Otherwise, vdev_alloc_common() will generate one for us.
 552          */
 553         if (alloctype == VDEV_ALLOC_LOAD) {
 554                 uint64_t label_id;
 555 
 556                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ID, &label_id) ||
 557                     label_id != id)
 558                         return (SET_ERROR(EINVAL));
 559 
 560                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
 561                         return (SET_ERROR(EINVAL));
 562         } else if (alloctype == VDEV_ALLOC_SPARE) {
 563                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
 564                         return (SET_ERROR(EINVAL));
 565         } else if (alloctype == VDEV_ALLOC_L2CACHE) {
 566                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
 567                         return (SET_ERROR(EINVAL));
 568         } else if (alloctype == VDEV_ALLOC_ROOTPOOL) {
 569                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
 570                         return (SET_ERROR(EINVAL));
 571         }
 572 
 573         /*
 574          * The first allocated vdev must be of type 'root'.
 575          */
 576         if (ops != &vdev_root_ops && spa->spa_root_vdev == NULL)
 577                 return (SET_ERROR(EINVAL));
 578 
 579         /*
 580          * Determine whether we're a log vdev.
 581          */
 582         islog = 0;
 583         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_LOG, &islog);
 584         if (islog && spa_version(spa) < SPA_VERSION_SLOGS)
 585                 return (SET_ERROR(ENOTSUP));
 586 
 587         if (ops == &vdev_hole_ops && spa_version(spa) < SPA_VERSION_HOLES)
 588                 return (SET_ERROR(ENOTSUP));
 589 
 590         /*
 591          * Set the nparity property for RAID-Z vdevs.
 592          */
 593         nparity = -1ULL;
 594         if (ops == &vdev_raidz_ops) {
 595                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NPARITY,
 596                     &nparity) == 0) {
 597                         if (nparity == 0 || nparity > VDEV_RAIDZ_MAXPARITY)
 598                                 return (SET_ERROR(EINVAL));
 599                         /*
 600                          * Previous versions could only support 1 or 2 parity
 601                          * device.
 602                          */
 603                         if (nparity > 1 &&
 604                             spa_version(spa) < SPA_VERSION_RAIDZ2)
 605                                 return (SET_ERROR(ENOTSUP));
 606                         if (nparity > 2 &&
 607                             spa_version(spa) < SPA_VERSION_RAIDZ3)
 608                                 return (SET_ERROR(ENOTSUP));
 609                 } else {
 610                         /*
 611                          * We require the parity to be specified for SPAs that
 612                          * support multiple parity levels.
 613                          */
 614                         if (spa_version(spa) >= SPA_VERSION_RAIDZ2)
 615                                 return (SET_ERROR(EINVAL));
 616                         /*
 617                          * Otherwise, we default to 1 parity device for RAID-Z.
 618                          */
 619                         nparity = 1;
 620                 }
 621         } else {
 622                 nparity = 0;
 623         }
 624         ASSERT(nparity != -1ULL);
 625 
 626         /*
 627          * If creating a top-level vdev, check for allocation classes input
 628          */
 629         if (top_level && alloctype == VDEV_ALLOC_ADD) {
 630                 char *bias;
 631 
 632                 if (nvlist_lookup_string(nv, ZPOOL_CONFIG_ALLOCATION_BIAS,
 633                     &bias) == 0) {
 634                         alloc_bias = vdev_derive_alloc_bias(bias);
 635 
 636                         /* spa_vdev_add() expects feature to be enabled */
 637                         if (spa->spa_load_state != SPA_LOAD_CREATE &&
 638                             !spa_feature_is_enabled(spa,
 639                             SPA_FEATURE_ALLOCATION_CLASSES)) {
 640                                 return (SET_ERROR(ENOTSUP));
 641                         }
 642                 }
 643         }
 644 
 645         vd = vdev_alloc_common(spa, id, guid, ops);
 646         vic = &vd->vdev_indirect_config;
 647 
 648         vd->vdev_islog = islog;
 649         vd->vdev_nparity = nparity;
 650         if (top_level && alloc_bias != VDEV_BIAS_NONE)
 651                 vd->vdev_alloc_bias = alloc_bias;
 652 
 653         if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &vd->vdev_path) == 0)
 654                 vd->vdev_path = spa_strdup(vd->vdev_path);
 655         if (nvlist_lookup_string(nv, ZPOOL_CONFIG_DEVID, &vd->vdev_devid) == 0)
 656                 vd->vdev_devid = spa_strdup(vd->vdev_devid);
 657         if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PHYS_PATH,
 658             &vd->vdev_physpath) == 0)
 659                 vd->vdev_physpath = spa_strdup(vd->vdev_physpath);
 660         if (nvlist_lookup_string(nv, ZPOOL_CONFIG_FRU, &vd->vdev_fru) == 0)
 661                 vd->vdev_fru = spa_strdup(vd->vdev_fru);
 662 
 663         /*
 664          * Set the whole_disk property.  If it's not specified, leave the value
 665          * as -1.
 666          */
 667         if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
 668             &vd->vdev_wholedisk) != 0)
 669                 vd->vdev_wholedisk = -1ULL;
 670 
 671         ASSERT0(vic->vic_mapping_object);
 672         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_INDIRECT_OBJECT,
 673             &vic->vic_mapping_object);
 674         ASSERT0(vic->vic_births_object);
 675         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_INDIRECT_BIRTHS,
 676             &vic->vic_births_object);
 677         ASSERT3U(vic->vic_prev_indirect_vdev, ==, UINT64_MAX);
 678         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_PREV_INDIRECT_VDEV,
 679             &vic->vic_prev_indirect_vdev);
 680 
 681         /*
 682          * Look for the 'not present' flag.  This will only be set if the device
 683          * was not present at the time of import.
 684          */
 685         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
 686             &vd->vdev_not_present);
 687 
 688         /*
 689          * Get the alignment requirement.
 690          */
 691         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ASHIFT, &vd->vdev_ashift);
 692 
 693         /*
 694          * Retrieve the vdev creation time.
 695          */
 696         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_CREATE_TXG,
 697             &vd->vdev_crtxg);
 698 
 699         /*
 700          * If we're a top-level vdev, try to load the allocation parameters.
 701          */
 702         if (top_level &&
 703             (alloctype == VDEV_ALLOC_LOAD || alloctype == VDEV_ALLOC_SPLIT)) {
 704                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_METASLAB_ARRAY,
 705                     &vd->vdev_ms_array);
 706                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_METASLAB_SHIFT,
 707                     &vd->vdev_ms_shift);
 708                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ASIZE,
 709                     &vd->vdev_asize);
 710                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVING,
 711                     &vd->vdev_removing);
 712                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_VDEV_TOP_ZAP,
 713                     &vd->vdev_top_zap);
 714         } else {
 715                 ASSERT0(vd->vdev_top_zap);
 716         }
 717 
 718         if (top_level && alloctype != VDEV_ALLOC_ATTACH) {
 719                 ASSERT(alloctype == VDEV_ALLOC_LOAD ||
 720                     alloctype == VDEV_ALLOC_ADD ||
 721                     alloctype == VDEV_ALLOC_SPLIT ||
 722                     alloctype == VDEV_ALLOC_ROOTPOOL);
 723                 /* Note: metaslab_group_create() is now deferred */
 724         }
 725 
 726         if (vd->vdev_ops->vdev_op_leaf &&
 727             (alloctype == VDEV_ALLOC_LOAD || alloctype == VDEV_ALLOC_SPLIT)) {
 728                 (void) nvlist_lookup_uint64(nv,
 729                     ZPOOL_CONFIG_VDEV_LEAF_ZAP, &vd->vdev_leaf_zap);
 730         } else {
 731                 ASSERT0(vd->vdev_leaf_zap);
 732         }
 733 
 734         /*
 735          * If we're a leaf vdev, try to load the DTL object and other state.
 736          */
 737 
 738         if (vd->vdev_ops->vdev_op_leaf &&
 739             (alloctype == VDEV_ALLOC_LOAD || alloctype == VDEV_ALLOC_L2CACHE ||
 740             alloctype == VDEV_ALLOC_ROOTPOOL)) {
 741                 if (alloctype == VDEV_ALLOC_LOAD) {
 742                         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_DTL,
 743                             &vd->vdev_dtl_object);
 744                         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_UNSPARE,
 745                             &vd->vdev_unspare);
 746                 }
 747 
 748                 if (alloctype == VDEV_ALLOC_ROOTPOOL) {
 749                         uint64_t spare = 0;
 750 
 751                         if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_SPARE,
 752                             &spare) == 0 && spare)
 753                                 spa_spare_add(vd);
 754                 }
 755 
 756                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_OFFLINE,
 757                     &vd->vdev_offline);
 758 
 759                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_RESILVER_TXG,
 760                     &vd->vdev_resilver_txg);
 761 
 762                 /*
 763                  * When importing a pool, we want to ignore the persistent fault
 764                  * state, as the diagnosis made on another system may not be
 765                  * valid in the current context.  Local vdevs will
 766                  * remain in the faulted state.
 767                  */
 768                 if (spa_load_state(spa) == SPA_LOAD_OPEN) {
 769                         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_FAULTED,
 770                             &vd->vdev_faulted);
 771                         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_DEGRADED,
 772                             &vd->vdev_degraded);
 773                         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVED,
 774                             &vd->vdev_removed);
 775 
 776                         if (vd->vdev_faulted || vd->vdev_degraded) {
 777                                 char *aux;
 778 
 779                                 vd->vdev_label_aux =
 780                                     VDEV_AUX_ERR_EXCEEDED;
 781                                 if (nvlist_lookup_string(nv,
 782                                     ZPOOL_CONFIG_AUX_STATE, &aux) == 0 &&
 783                                     strcmp(aux, "external") == 0)
 784                                         vd->vdev_label_aux = VDEV_AUX_EXTERNAL;
 785                         }
 786                 }
 787         }
 788 
 789         /*
 790          * Add ourselves to the parent's list of children.
 791          */
 792         vdev_add_child(parent, vd);
 793 
 794         *vdp = vd;
 795 
 796         return (0);
 797 }
 798 
 799 void
 800 vdev_free(vdev_t *vd)
 801 {
 802         spa_t *spa = vd->vdev_spa;
 803         ASSERT3P(vd->vdev_initialize_thread, ==, NULL);
 804 
 805         /*
 806          * vdev_free() implies closing the vdev first.  This is simpler than
 807          * trying to ensure complicated semantics for all callers.
 808          */
 809         vdev_close(vd);
 810 
 811         ASSERT(!list_link_active(&vd->vdev_config_dirty_node));
 812         ASSERT(!list_link_active(&vd->vdev_state_dirty_node));
 813 
 814         /*
 815          * Free all children.
 816          */
 817         for (int c = 0; c < vd->vdev_children; c++)
 818                 vdev_free(vd->vdev_child[c]);
 819 
 820         ASSERT(vd->vdev_child == NULL);
 821         ASSERT(vd->vdev_guid_sum == vd->vdev_guid);
 822         ASSERT(vd->vdev_initialize_thread == NULL);
 823 
 824         /*
 825          * Discard allocation state.
 826          */
 827         if (vd->vdev_mg != NULL) {
 828                 vdev_metaslab_fini(vd);
 829                 metaslab_group_destroy(vd->vdev_mg);
 830         }
 831 
 832         ASSERT0(vd->vdev_stat.vs_space);
 833         ASSERT0(vd->vdev_stat.vs_dspace);
 834         ASSERT0(vd->vdev_stat.vs_alloc);
 835 
 836         /*
 837          * Remove this vdev from its parent's child list.
 838          */
 839         vdev_remove_child(vd->vdev_parent, vd);
 840 
 841         ASSERT(vd->vdev_parent == NULL);
 842         ASSERT(!list_link_active(&vd->vdev_leaf_node));
 843 
 844         /*
 845          * Clean up vdev structure.
 846          */
 847         vdev_queue_fini(vd);
 848         vdev_cache_fini(vd);
 849 
 850         if (vd->vdev_path)
 851                 spa_strfree(vd->vdev_path);
 852         if (vd->vdev_devid)
 853                 spa_strfree(vd->vdev_devid);
 854         if (vd->vdev_physpath)
 855                 spa_strfree(vd->vdev_physpath);
 856         if (vd->vdev_fru)
 857                 spa_strfree(vd->vdev_fru);
 858 
 859         if (vd->vdev_isspare)
 860                 spa_spare_remove(vd);
 861         if (vd->vdev_isl2cache)
 862                 spa_l2cache_remove(vd);
 863 
 864         txg_list_destroy(&vd->vdev_ms_list);
 865         txg_list_destroy(&vd->vdev_dtl_list);
 866 
 867         mutex_enter(&vd->vdev_dtl_lock);
 868         space_map_close(vd->vdev_dtl_sm);
 869         for (int t = 0; t < DTL_TYPES; t++) {
 870                 range_tree_vacate(vd->vdev_dtl[t], NULL, NULL);
 871                 range_tree_destroy(vd->vdev_dtl[t]);
 872         }
 873         mutex_exit(&vd->vdev_dtl_lock);
 874 
 875         EQUIV(vd->vdev_indirect_births != NULL,
 876             vd->vdev_indirect_mapping != NULL);
 877         if (vd->vdev_indirect_births != NULL) {
 878                 vdev_indirect_mapping_close(vd->vdev_indirect_mapping);
 879                 vdev_indirect_births_close(vd->vdev_indirect_births);
 880         }
 881 
 882         if (vd->vdev_obsolete_sm != NULL) {
 883                 ASSERT(vd->vdev_removing ||
 884                     vd->vdev_ops == &vdev_indirect_ops);
 885                 space_map_close(vd->vdev_obsolete_sm);
 886                 vd->vdev_obsolete_sm = NULL;
 887         }
 888         range_tree_destroy(vd->vdev_obsolete_segments);
 889         rw_destroy(&vd->vdev_indirect_rwlock);
 890         mutex_destroy(&vd->vdev_obsolete_lock);
 891 
 892         mutex_destroy(&vd->vdev_queue_lock);
 893         mutex_destroy(&vd->vdev_dtl_lock);
 894         mutex_destroy(&vd->vdev_stat_lock);
 895         mutex_destroy(&vd->vdev_probe_lock);
 896         mutex_destroy(&vd->vdev_initialize_lock);
 897         mutex_destroy(&vd->vdev_initialize_io_lock);
 898         cv_destroy(&vd->vdev_initialize_io_cv);
 899         cv_destroy(&vd->vdev_initialize_cv);
 900 
 901         if (vd == spa->spa_root_vdev)
 902                 spa->spa_root_vdev = NULL;
 903 
 904         kmem_free(vd, sizeof (vdev_t));
 905 }
 906 
 907 /*
 908  * Transfer top-level vdev state from svd to tvd.
 909  */
 910 static void
 911 vdev_top_transfer(vdev_t *svd, vdev_t *tvd)
 912 {
 913         spa_t *spa = svd->vdev_spa;
 914         metaslab_t *msp;
 915         vdev_t *vd;
 916         int t;
 917 
 918         ASSERT(tvd == tvd->vdev_top);
 919 
 920         tvd->vdev_ms_array = svd->vdev_ms_array;
 921         tvd->vdev_ms_shift = svd->vdev_ms_shift;
 922         tvd->vdev_ms_count = svd->vdev_ms_count;
 923         tvd->vdev_top_zap = svd->vdev_top_zap;
 924 
 925         svd->vdev_ms_array = 0;
 926         svd->vdev_ms_shift = 0;
 927         svd->vdev_ms_count = 0;
 928         svd->vdev_top_zap = 0;
 929 
 930         if (tvd->vdev_mg)
 931                 ASSERT3P(tvd->vdev_mg, ==, svd->vdev_mg);
 932         tvd->vdev_mg = svd->vdev_mg;
 933         tvd->vdev_ms = svd->vdev_ms;
 934 
 935         svd->vdev_mg = NULL;
 936         svd->vdev_ms = NULL;
 937 
 938         if (tvd->vdev_mg != NULL)
 939                 tvd->vdev_mg->mg_vd = tvd;
 940 
 941         tvd->vdev_checkpoint_sm = svd->vdev_checkpoint_sm;
 942         svd->vdev_checkpoint_sm = NULL;
 943 
 944         tvd->vdev_alloc_bias = svd->vdev_alloc_bias;
 945         svd->vdev_alloc_bias = VDEV_BIAS_NONE;
 946 
 947         tvd->vdev_stat.vs_alloc = svd->vdev_stat.vs_alloc;
 948         tvd->vdev_stat.vs_space = svd->vdev_stat.vs_space;
 949         tvd->vdev_stat.vs_dspace = svd->vdev_stat.vs_dspace;
 950 
 951         svd->vdev_stat.vs_alloc = 0;
 952         svd->vdev_stat.vs_space = 0;
 953         svd->vdev_stat.vs_dspace = 0;
 954 
 955         /*
 956          * State which may be set on a top-level vdev that's in the
 957          * process of being removed.
 958          */
 959         ASSERT0(tvd->vdev_indirect_config.vic_births_object);
 960         ASSERT0(tvd->vdev_indirect_config.vic_mapping_object);
 961         ASSERT3U(tvd->vdev_indirect_config.vic_prev_indirect_vdev, ==, -1ULL);
 962         ASSERT3P(tvd->vdev_indirect_mapping, ==, NULL);
 963         ASSERT3P(tvd->vdev_indirect_births, ==, NULL);
 964         ASSERT3P(tvd->vdev_obsolete_sm, ==, NULL);
 965         ASSERT0(tvd->vdev_removing);
 966         tvd->vdev_removing = svd->vdev_removing;
 967         tvd->vdev_indirect_config = svd->vdev_indirect_config;
 968         tvd->vdev_indirect_mapping = svd->vdev_indirect_mapping;
 969         tvd->vdev_indirect_births = svd->vdev_indirect_births;
 970         range_tree_swap(&svd->vdev_obsolete_segments,
 971             &tvd->vdev_obsolete_segments);
 972         tvd->vdev_obsolete_sm = svd->vdev_obsolete_sm;
 973         svd->vdev_indirect_config.vic_mapping_object = 0;
 974         svd->vdev_indirect_config.vic_births_object = 0;
 975         svd->vdev_indirect_config.vic_prev_indirect_vdev = -1ULL;
 976         svd->vdev_indirect_mapping = NULL;
 977         svd->vdev_indirect_births = NULL;
 978         svd->vdev_obsolete_sm = NULL;
 979         svd->vdev_removing = 0;
 980 
 981         for (t = 0; t < TXG_SIZE; t++) {
 982                 while ((msp = txg_list_remove(&svd->vdev_ms_list, t)) != NULL)
 983                         (void) txg_list_add(&tvd->vdev_ms_list, msp, t);
 984                 while ((vd = txg_list_remove(&svd->vdev_dtl_list, t)) != NULL)
 985                         (void) txg_list_add(&tvd->vdev_dtl_list, vd, t);
 986                 if (txg_list_remove_this(&spa->spa_vdev_txg_list, svd, t))
 987                         (void) txg_list_add(&spa->spa_vdev_txg_list, tvd, t);
 988         }
 989 
 990         if (list_link_active(&svd->vdev_config_dirty_node)) {
 991                 vdev_config_clean(svd);
 992                 vdev_config_dirty(tvd);
 993         }
 994 
 995         if (list_link_active(&svd->vdev_state_dirty_node)) {
 996                 vdev_state_clean(svd);
 997                 vdev_state_dirty(tvd);
 998         }
 999 
1000         tvd->vdev_deflate_ratio = svd->vdev_deflate_ratio;
1001         svd->vdev_deflate_ratio = 0;
1002 
1003         tvd->vdev_islog = svd->vdev_islog;
1004         svd->vdev_islog = 0;
1005 }
1006 
1007 static void
1008 vdev_top_update(vdev_t *tvd, vdev_t *vd)
1009 {
1010         if (vd == NULL)
1011                 return;
1012 
1013         vd->vdev_top = tvd;
1014 
1015         for (int c = 0; c < vd->vdev_children; c++)
1016                 vdev_top_update(tvd, vd->vdev_child[c]);
1017 }
1018 
1019 /*
1020  * Add a mirror/replacing vdev above an existing vdev.
1021  */
1022 vdev_t *
1023 vdev_add_parent(vdev_t *cvd, vdev_ops_t *ops)
1024 {
1025         spa_t *spa = cvd->vdev_spa;
1026         vdev_t *pvd = cvd->vdev_parent;
1027         vdev_t *mvd;
1028 
1029         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1030 
1031         mvd = vdev_alloc_common(spa, cvd->vdev_id, 0, ops);
1032 
1033         mvd->vdev_asize = cvd->vdev_asize;
1034         mvd->vdev_min_asize = cvd->vdev_min_asize;
1035         mvd->vdev_max_asize = cvd->vdev_max_asize;
1036         mvd->vdev_psize = cvd->vdev_psize;
1037         mvd->vdev_ashift = cvd->vdev_ashift;
1038         mvd->vdev_state = cvd->vdev_state;
1039         mvd->vdev_crtxg = cvd->vdev_crtxg;
1040 
1041         vdev_remove_child(pvd, cvd);
1042         vdev_add_child(pvd, mvd);
1043         cvd->vdev_id = mvd->vdev_children;
1044         vdev_add_child(mvd, cvd);
1045         vdev_top_update(cvd->vdev_top, cvd->vdev_top);
1046 
1047         if (mvd == mvd->vdev_top)
1048                 vdev_top_transfer(cvd, mvd);
1049 
1050         return (mvd);
1051 }
1052 
1053 /*
1054  * Remove a 1-way mirror/replacing vdev from the tree.
1055  */
1056 void
1057 vdev_remove_parent(vdev_t *cvd)
1058 {
1059         vdev_t *mvd = cvd->vdev_parent;
1060         vdev_t *pvd = mvd->vdev_parent;
1061 
1062         ASSERT(spa_config_held(cvd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1063 
1064         ASSERT(mvd->vdev_children == 1);
1065         ASSERT(mvd->vdev_ops == &vdev_mirror_ops ||
1066             mvd->vdev_ops == &vdev_replacing_ops ||
1067             mvd->vdev_ops == &vdev_spare_ops);
1068         cvd->vdev_ashift = mvd->vdev_ashift;
1069 
1070         vdev_remove_child(mvd, cvd);
1071         vdev_remove_child(pvd, mvd);
1072 
1073         /*
1074          * If cvd will replace mvd as a top-level vdev, preserve mvd's guid.
1075          * Otherwise, we could have detached an offline device, and when we
1076          * go to import the pool we'll think we have two top-level vdevs,
1077          * instead of a different version of the same top-level vdev.
1078          */
1079         if (mvd->vdev_top == mvd) {
1080                 uint64_t guid_delta = mvd->vdev_guid - cvd->vdev_guid;
1081                 cvd->vdev_orig_guid = cvd->vdev_guid;
1082                 cvd->vdev_guid += guid_delta;
1083                 cvd->vdev_guid_sum += guid_delta;
1084         }
1085         cvd->vdev_id = mvd->vdev_id;
1086         vdev_add_child(pvd, cvd);
1087         vdev_top_update(cvd->vdev_top, cvd->vdev_top);
1088 
1089         if (cvd == cvd->vdev_top)
1090                 vdev_top_transfer(mvd, cvd);
1091 
1092         ASSERT(mvd->vdev_children == 0);
1093         vdev_free(mvd);
1094 }
1095 
1096 static void
1097 vdev_metaslab_group_create(vdev_t *vd)
1098 {
1099         spa_t *spa = vd->vdev_spa;
1100 
1101         /*
1102          * metaslab_group_create was delayed until allocation bias was available
1103          */
1104         if (vd->vdev_mg == NULL) {
1105                 metaslab_class_t *mc;
1106 
1107                 if (vd->vdev_islog && vd->vdev_alloc_bias == VDEV_BIAS_NONE)
1108                         vd->vdev_alloc_bias = VDEV_BIAS_LOG;
1109 
1110                 ASSERT3U(vd->vdev_islog, ==,
1111                     (vd->vdev_alloc_bias == VDEV_BIAS_LOG));
1112 
1113                 switch (vd->vdev_alloc_bias) {
1114                 case VDEV_BIAS_LOG:
1115                         mc = spa_log_class(spa);
1116                         break;
1117                 case VDEV_BIAS_SPECIAL:
1118                         mc = spa_special_class(spa);
1119                         break;
1120                 case VDEV_BIAS_DEDUP:
1121                         mc = spa_dedup_class(spa);
1122                         break;
1123                 default:
1124                         mc = spa_normal_class(spa);
1125                 }
1126 
1127                 vd->vdev_mg = metaslab_group_create(mc, vd,
1128                     spa->spa_alloc_count);
1129 
1130                 /*
1131                  * The spa ashift values currently only reflect the
1132                  * general vdev classes. Class destination is late
1133                  * binding so ashift checking had to wait until now
1134                  */
1135                 if (vd->vdev_top == vd && vd->vdev_ashift != 0 &&
1136                     mc == spa_normal_class(spa) && vd->vdev_aux == NULL) {
1137                         if (vd->vdev_ashift > spa->spa_max_ashift)
1138                                 spa->spa_max_ashift = vd->vdev_ashift;
1139                         if (vd->vdev_ashift < spa->spa_min_ashift)
1140                                 spa->spa_min_ashift = vd->vdev_ashift;
1141                 }
1142         }
1143 }
1144 
1145 int
1146 vdev_metaslab_init(vdev_t *vd, uint64_t txg)
1147 {
1148         spa_t *spa = vd->vdev_spa;
1149         objset_t *mos = spa->spa_meta_objset;
1150         uint64_t m;
1151         uint64_t oldc = vd->vdev_ms_count;
1152         uint64_t newc = vd->vdev_asize >> vd->vdev_ms_shift;
1153         metaslab_t **mspp;
1154         int error;
1155         boolean_t expanding = (oldc != 0);
1156 
1157         ASSERT(txg == 0 || spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1158 
1159         /*
1160          * This vdev is not being allocated from yet or is a hole.
1161          */
1162         if (vd->vdev_ms_shift == 0)
1163                 return (0);
1164 
1165         ASSERT(!vd->vdev_ishole);
1166 
1167         ASSERT(oldc <= newc);
1168 
1169         mspp = kmem_zalloc(newc * sizeof (*mspp), KM_SLEEP);
1170 
1171         if (expanding) {
1172                 bcopy(vd->vdev_ms, mspp, oldc * sizeof (*mspp));
1173                 kmem_free(vd->vdev_ms, oldc * sizeof (*mspp));
1174         }
1175 
1176         vd->vdev_ms = mspp;
1177         vd->vdev_ms_count = newc;
1178         for (m = oldc; m < newc; m++) {
1179                 uint64_t object = 0;
1180 
1181                 /*
1182                  * vdev_ms_array may be 0 if we are creating the "fake"
1183                  * metaslabs for an indirect vdev for zdb's leak detection.
1184                  * See zdb_leak_init().
1185                  */
1186                 if (txg == 0 && vd->vdev_ms_array != 0) {
1187                         error = dmu_read(mos, vd->vdev_ms_array,
1188                             m * sizeof (uint64_t), sizeof (uint64_t), &object,
1189                             DMU_READ_PREFETCH);
1190                         if (error != 0) {
1191                                 vdev_dbgmsg(vd, "unable to read the metaslab "
1192                                     "array [error=%d]", error);
1193                                 return (error);
1194                         }
1195                 }
1196 
1197 #ifndef _KERNEL
1198                 /*
1199                  * To accomodate zdb_leak_init() fake indirect
1200                  * metaslabs, we allocate a metaslab group for
1201                  * indirect vdevs which normally don't have one.
1202                  */
1203                 if (vd->vdev_mg == NULL) {
1204                         ASSERT0(vdev_is_concrete(vd));
1205                         vdev_metaslab_group_create(vd);
1206                 }
1207 #endif
1208                 error = metaslab_init(vd->vdev_mg, m, object, txg,
1209                     &(vd->vdev_ms[m]));
1210                 if (error != 0) {
1211                         vdev_dbgmsg(vd, "metaslab_init failed [error=%d]",
1212                             error);
1213                         return (error);
1214                 }
1215         }
1216 
1217         if (txg == 0)
1218                 spa_config_enter(spa, SCL_ALLOC, FTAG, RW_WRITER);
1219 
1220         /*
1221          * If the vdev is being removed we don't activate
1222          * the metaslabs since we want to ensure that no new
1223          * allocations are performed on this device.
1224          */
1225         if (!expanding && !vd->vdev_removing) {
1226                 metaslab_group_activate(vd->vdev_mg);
1227         }
1228 
1229         if (txg == 0)
1230                 spa_config_exit(spa, SCL_ALLOC, FTAG);
1231 
1232         return (0);
1233 }
1234 
1235 void
1236 vdev_metaslab_fini(vdev_t *vd)
1237 {
1238         if (vd->vdev_checkpoint_sm != NULL) {
1239                 ASSERT(spa_feature_is_active(vd->vdev_spa,
1240                     SPA_FEATURE_POOL_CHECKPOINT));
1241                 space_map_close(vd->vdev_checkpoint_sm);
1242                 /*
1243                  * Even though we close the space map, we need to set its
1244                  * pointer to NULL. The reason is that vdev_metaslab_fini()
1245                  * may be called multiple times for certain operations
1246                  * (i.e. when destroying a pool) so we need to ensure that
1247                  * this clause never executes twice. This logic is similar
1248                  * to the one used for the vdev_ms clause below.
1249                  */
1250                 vd->vdev_checkpoint_sm = NULL;
1251         }
1252 
1253         if (vd->vdev_ms != NULL) {
1254                 uint64_t count = vd->vdev_ms_count;
1255 
1256                 metaslab_group_passivate(vd->vdev_mg);
1257                 for (uint64_t m = 0; m < count; m++) {
1258                         metaslab_t *msp = vd->vdev_ms[m];
1259 
1260                         if (msp != NULL)
1261                                 metaslab_fini(msp);
1262                 }
1263                 kmem_free(vd->vdev_ms, count * sizeof (metaslab_t *));
1264                 vd->vdev_ms = NULL;
1265 
1266                 vd->vdev_ms_count = 0;
1267         }
1268         ASSERT0(vd->vdev_ms_count);
1269 }
1270 
1271 typedef struct vdev_probe_stats {
1272         boolean_t       vps_readable;
1273         boolean_t       vps_writeable;
1274         int             vps_flags;
1275 } vdev_probe_stats_t;
1276 
1277 static void
1278 vdev_probe_done(zio_t *zio)
1279 {
1280         spa_t *spa = zio->io_spa;
1281         vdev_t *vd = zio->io_vd;
1282         vdev_probe_stats_t *vps = zio->io_private;
1283 
1284         ASSERT(vd->vdev_probe_zio != NULL);
1285 
1286         if (zio->io_type == ZIO_TYPE_READ) {
1287                 if (zio->io_error == 0)
1288                         vps->vps_readable = 1;
1289                 if (zio->io_error == 0 && spa_writeable(spa)) {
1290                         zio_nowait(zio_write_phys(vd->vdev_probe_zio, vd,
1291                             zio->io_offset, zio->io_size, zio->io_abd,
1292                             ZIO_CHECKSUM_OFF, vdev_probe_done, vps,
1293                             ZIO_PRIORITY_SYNC_WRITE, vps->vps_flags, B_TRUE));
1294                 } else {
1295                         abd_free(zio->io_abd);
1296                 }
1297         } else if (zio->io_type == ZIO_TYPE_WRITE) {
1298                 if (zio->io_error == 0)
1299                         vps->vps_writeable = 1;
1300                 abd_free(zio->io_abd);
1301         } else if (zio->io_type == ZIO_TYPE_NULL) {
1302                 zio_t *pio;
1303 
1304                 vd->vdev_cant_read |= !vps->vps_readable;
1305                 vd->vdev_cant_write |= !vps->vps_writeable;
1306 
1307                 if (vdev_readable(vd) &&
1308                     (vdev_writeable(vd) || !spa_writeable(spa))) {
1309                         zio->io_error = 0;
1310                 } else {
1311                         ASSERT(zio->io_error != 0);
1312                         vdev_dbgmsg(vd, "failed probe");
1313                         zfs_ereport_post(FM_EREPORT_ZFS_PROBE_FAILURE,
1314                             spa, vd, NULL, 0, 0);
1315                         zio->io_error = SET_ERROR(ENXIO);
1316                 }
1317 
1318                 mutex_enter(&vd->vdev_probe_lock);
1319                 ASSERT(vd->vdev_probe_zio == zio);
1320                 vd->vdev_probe_zio = NULL;
1321                 mutex_exit(&vd->vdev_probe_lock);
1322 
1323                 zio_link_t *zl = NULL;
1324                 while ((pio = zio_walk_parents(zio, &zl)) != NULL)
1325                         if (!vdev_accessible(vd, pio))
1326                                 pio->io_error = SET_ERROR(ENXIO);
1327 
1328                 kmem_free(vps, sizeof (*vps));
1329         }
1330 }
1331 
1332 /*
1333  * Determine whether this device is accessible.
1334  *
1335  * Read and write to several known locations: the pad regions of each
1336  * vdev label but the first, which we leave alone in case it contains
1337  * a VTOC.
1338  */
1339 zio_t *
1340 vdev_probe(vdev_t *vd, zio_t *zio)
1341 {
1342         spa_t *spa = vd->vdev_spa;
1343         vdev_probe_stats_t *vps = NULL;
1344         zio_t *pio;
1345 
1346         ASSERT(vd->vdev_ops->vdev_op_leaf);
1347 
1348         /*
1349          * Don't probe the probe.
1350          */
1351         if (zio && (zio->io_flags & ZIO_FLAG_PROBE))
1352                 return (NULL);
1353 
1354         /*
1355          * To prevent 'probe storms' when a device fails, we create
1356          * just one probe i/o at a time.  All zios that want to probe
1357          * this vdev will become parents of the probe io.
1358          */
1359         mutex_enter(&vd->vdev_probe_lock);
1360 
1361         if ((pio = vd->vdev_probe_zio) == NULL) {
1362                 vps = kmem_zalloc(sizeof (*vps), KM_SLEEP);
1363 
1364                 vps->vps_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_PROBE |
1365                     ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_AGGREGATE |
1366                     ZIO_FLAG_TRYHARD;
1367 
1368                 if (spa_config_held(spa, SCL_ZIO, RW_WRITER)) {
1369                         /*
1370                          * vdev_cant_read and vdev_cant_write can only
1371                          * transition from TRUE to FALSE when we have the
1372                          * SCL_ZIO lock as writer; otherwise they can only
1373                          * transition from FALSE to TRUE.  This ensures that
1374                          * any zio looking at these values can assume that
1375                          * failures persist for the life of the I/O.  That's
1376                          * important because when a device has intermittent
1377                          * connectivity problems, we want to ensure that
1378                          * they're ascribed to the device (ENXIO) and not
1379                          * the zio (EIO).
1380                          *
1381                          * Since we hold SCL_ZIO as writer here, clear both
1382                          * values so the probe can reevaluate from first
1383                          * principles.
1384                          */
1385                         vps->vps_flags |= ZIO_FLAG_CONFIG_WRITER;
1386                         vd->vdev_cant_read = B_FALSE;
1387                         vd->vdev_cant_write = B_FALSE;
1388                 }
1389 
1390                 vd->vdev_probe_zio = pio = zio_null(NULL, spa, vd,
1391                     vdev_probe_done, vps,
1392                     vps->vps_flags | ZIO_FLAG_DONT_PROPAGATE);
1393 
1394                 /*
1395                  * We can't change the vdev state in this context, so we
1396                  * kick off an async task to do it on our behalf.
1397                  */
1398                 if (zio != NULL) {
1399                         vd->vdev_probe_wanted = B_TRUE;
1400                         spa_async_request(spa, SPA_ASYNC_PROBE);
1401                 }
1402         }
1403 
1404         if (zio != NULL)
1405                 zio_add_child(zio, pio);
1406 
1407         mutex_exit(&vd->vdev_probe_lock);
1408 
1409         if (vps == NULL) {
1410                 ASSERT(zio != NULL);
1411                 return (NULL);
1412         }
1413 
1414         for (int l = 1; l < VDEV_LABELS; l++) {
1415                 zio_nowait(zio_read_phys(pio, vd,
1416                     vdev_label_offset(vd->vdev_psize, l,
1417                     offsetof(vdev_label_t, vl_pad2)), VDEV_PAD_SIZE,
1418                     abd_alloc_for_io(VDEV_PAD_SIZE, B_TRUE),
1419                     ZIO_CHECKSUM_OFF, vdev_probe_done, vps,
1420                     ZIO_PRIORITY_SYNC_READ, vps->vps_flags, B_TRUE));
1421         }
1422 
1423         if (zio == NULL)
1424                 return (pio);
1425 
1426         zio_nowait(pio);
1427         return (NULL);
1428 }
1429 
1430 static void
1431 vdev_open_child(void *arg)
1432 {
1433         vdev_t *vd = arg;
1434 
1435         vd->vdev_open_thread = curthread;
1436         vd->vdev_open_error = vdev_open(vd);
1437         vd->vdev_open_thread = NULL;
1438 }
1439 
1440 boolean_t
1441 vdev_uses_zvols(vdev_t *vd)
1442 {
1443         if (vd->vdev_path && strncmp(vd->vdev_path, ZVOL_DIR,
1444             strlen(ZVOL_DIR)) == 0)
1445                 return (B_TRUE);
1446         for (int c = 0; c < vd->vdev_children; c++)
1447                 if (vdev_uses_zvols(vd->vdev_child[c]))
1448                         return (B_TRUE);
1449         return (B_FALSE);
1450 }
1451 
1452 void
1453 vdev_open_children(vdev_t *vd)
1454 {
1455         taskq_t *tq;
1456         int children = vd->vdev_children;
1457 
1458         /*
1459          * in order to handle pools on top of zvols, do the opens
1460          * in a single thread so that the same thread holds the
1461          * spa_namespace_lock
1462          */
1463         if (vdev_uses_zvols(vd)) {
1464                 for (int c = 0; c < children; c++)
1465                         vd->vdev_child[c]->vdev_open_error =
1466                             vdev_open(vd->vdev_child[c]);
1467                 return;
1468         }
1469         tq = taskq_create("vdev_open", children, minclsyspri,
1470             children, children, TASKQ_PREPOPULATE);
1471 
1472         for (int c = 0; c < children; c++)
1473                 VERIFY(taskq_dispatch(tq, vdev_open_child, vd->vdev_child[c],
1474                     TQ_SLEEP) != TASKQID_INVALID);
1475 
1476         taskq_destroy(tq);
1477 }
1478 
1479 /*
1480  * Compute the raidz-deflation ratio.  Note, we hard-code
1481  * in 128k (1 << 17) because it is the "typical" blocksize.
1482  * Even though SPA_MAXBLOCKSIZE changed, this algorithm can not change,
1483  * otherwise it would inconsistently account for existing bp's.
1484  */
1485 static void
1486 vdev_set_deflate_ratio(vdev_t *vd)
1487 {
1488         if (vd == vd->vdev_top && !vd->vdev_ishole && vd->vdev_ashift != 0) {
1489                 vd->vdev_deflate_ratio = (1 << 17) /
1490                     (vdev_psize_to_asize(vd, 1 << 17) >> SPA_MINBLOCKSHIFT);
1491         }
1492 }
1493 
1494 /*
1495  * Prepare a virtual device for access.
1496  */
1497 int
1498 vdev_open(vdev_t *vd)
1499 {
1500         spa_t *spa = vd->vdev_spa;
1501         int error;
1502         uint64_t osize = 0;
1503         uint64_t max_osize = 0;
1504         uint64_t asize, max_asize, psize;
1505         uint64_t ashift = 0;
1506 
1507         ASSERT(vd->vdev_open_thread == curthread ||
1508             spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
1509         ASSERT(vd->vdev_state == VDEV_STATE_CLOSED ||
1510             vd->vdev_state == VDEV_STATE_CANT_OPEN ||
1511             vd->vdev_state == VDEV_STATE_OFFLINE);
1512 
1513         vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
1514         vd->vdev_cant_read = B_FALSE;
1515         vd->vdev_cant_write = B_FALSE;
1516         vd->vdev_min_asize = vdev_get_min_asize(vd);
1517 
1518         /*
1519          * If this vdev is not removed, check its fault status.  If it's
1520          * faulted, bail out of the open.
1521          */
1522         if (!vd->vdev_removed && vd->vdev_faulted) {
1523                 ASSERT(vd->vdev_children == 0);
1524                 ASSERT(vd->vdev_label_aux == VDEV_AUX_ERR_EXCEEDED ||
1525                     vd->vdev_label_aux == VDEV_AUX_EXTERNAL);
1526                 vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
1527                     vd->vdev_label_aux);
1528                 return (SET_ERROR(ENXIO));
1529         } else if (vd->vdev_offline) {
1530                 ASSERT(vd->vdev_children == 0);
1531                 vdev_set_state(vd, B_TRUE, VDEV_STATE_OFFLINE, VDEV_AUX_NONE);
1532                 return (SET_ERROR(ENXIO));
1533         }
1534 
1535         error = vd->vdev_ops->vdev_op_open(vd, &osize, &max_osize, &ashift);
1536 
1537         /*
1538          * Reset the vdev_reopening flag so that we actually close
1539          * the vdev on error.
1540          */
1541         vd->vdev_reopening = B_FALSE;
1542         if (zio_injection_enabled && error == 0)
1543                 error = zio_handle_device_injection(vd, NULL, ENXIO);
1544 
1545         if (error) {
1546                 if (vd->vdev_removed &&
1547                     vd->vdev_stat.vs_aux != VDEV_AUX_OPEN_FAILED)
1548                         vd->vdev_removed = B_FALSE;
1549 
1550                 if (vd->vdev_stat.vs_aux == VDEV_AUX_CHILDREN_OFFLINE) {
1551                         vdev_set_state(vd, B_TRUE, VDEV_STATE_OFFLINE,
1552                             vd->vdev_stat.vs_aux);
1553                 } else {
1554                         vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1555                             vd->vdev_stat.vs_aux);
1556                 }
1557                 return (error);
1558         }
1559 
1560         vd->vdev_removed = B_FALSE;
1561 
1562         /*
1563          * Recheck the faulted flag now that we have confirmed that
1564          * the vdev is accessible.  If we're faulted, bail.
1565          */
1566         if (vd->vdev_faulted) {
1567                 ASSERT(vd->vdev_children == 0);
1568                 ASSERT(vd->vdev_label_aux == VDEV_AUX_ERR_EXCEEDED ||
1569                     vd->vdev_label_aux == VDEV_AUX_EXTERNAL);
1570                 vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
1571                     vd->vdev_label_aux);
1572                 return (SET_ERROR(ENXIO));
1573         }
1574 
1575         if (vd->vdev_degraded) {
1576                 ASSERT(vd->vdev_children == 0);
1577                 vdev_set_state(vd, B_TRUE, VDEV_STATE_DEGRADED,
1578                     VDEV_AUX_ERR_EXCEEDED);
1579         } else {
1580                 vdev_set_state(vd, B_TRUE, VDEV_STATE_HEALTHY, 0);
1581         }
1582 
1583         /*
1584          * For hole or missing vdevs we just return success.
1585          */
1586         if (vd->vdev_ishole || vd->vdev_ops == &vdev_missing_ops)
1587                 return (0);
1588 
1589         for (int c = 0; c < vd->vdev_children; c++) {
1590                 if (vd->vdev_child[c]->vdev_state != VDEV_STATE_HEALTHY) {
1591                         vdev_set_state(vd, B_TRUE, VDEV_STATE_DEGRADED,
1592                             VDEV_AUX_NONE);
1593                         break;
1594                 }
1595         }
1596 
1597         osize = P2ALIGN(osize, (uint64_t)sizeof (vdev_label_t));
1598         max_osize = P2ALIGN(max_osize, (uint64_t)sizeof (vdev_label_t));
1599 
1600         if (vd->vdev_children == 0) {
1601                 if (osize < SPA_MINDEVSIZE) {
1602                         vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1603                             VDEV_AUX_TOO_SMALL);
1604                         return (SET_ERROR(EOVERFLOW));
1605                 }
1606                 psize = osize;
1607                 asize = osize - (VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE);
1608                 max_asize = max_osize - (VDEV_LABEL_START_SIZE +
1609                     VDEV_LABEL_END_SIZE);
1610         } else {
1611                 if (vd->vdev_parent != NULL && osize < SPA_MINDEVSIZE -
1612                     (VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE)) {
1613                         vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1614                             VDEV_AUX_TOO_SMALL);
1615                         return (SET_ERROR(EOVERFLOW));
1616                 }
1617                 psize = 0;
1618                 asize = osize;
1619                 max_asize = max_osize;
1620         }
1621 
1622         vd->vdev_psize = psize;
1623 
1624         /*
1625          * Make sure the allocatable size hasn't shrunk too much.
1626          */
1627         if (asize < vd->vdev_min_asize) {
1628                 vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1629                     VDEV_AUX_BAD_LABEL);
1630                 return (SET_ERROR(EINVAL));
1631         }
1632 
1633         if (vd->vdev_asize == 0) {
1634                 /*
1635                  * This is the first-ever open, so use the computed values.
1636                  * For testing purposes, a higher ashift can be requested.
1637                  */
1638                 vd->vdev_asize = asize;
1639                 vd->vdev_max_asize = max_asize;
1640                 vd->vdev_ashift = MAX(ashift, vd->vdev_ashift);
1641                 vd->vdev_ashift = MAX(zfs_ashift_min, vd->vdev_ashift);
1642         } else {
1643                 /*
1644                  * Detect if the alignment requirement has increased.
1645                  * We don't want to make the pool unavailable, just
1646                  * issue a warning instead.
1647                  */
1648                 if (ashift > vd->vdev_top->vdev_ashift &&
1649                     vd->vdev_ops->vdev_op_leaf) {
1650                         cmn_err(CE_WARN,
1651                             "Disk, '%s', has a block alignment that is "
1652                             "larger than the pool's alignment\n",
1653                             vd->vdev_path);
1654                 }
1655                 vd->vdev_max_asize = max_asize;
1656         }
1657 
1658         /*
1659          * If all children are healthy we update asize if either:
1660          * The asize has increased, due to a device expansion caused by dynamic
1661          * LUN growth or vdev replacement, and automatic expansion is enabled;
1662          * making the additional space available.
1663          *
1664          * The asize has decreased, due to a device shrink usually caused by a
1665          * vdev replace with a smaller device. This ensures that calculations
1666          * based of max_asize and asize e.g. esize are always valid. It's safe
1667          * to do this as we've already validated that asize is greater than
1668          * vdev_min_asize.
1669          */
1670         if (vd->vdev_state == VDEV_STATE_HEALTHY &&
1671             ((asize > vd->vdev_asize &&
1672             (vd->vdev_expanding || spa->spa_autoexpand)) ||
1673             (asize < vd->vdev_asize)))
1674                 vd->vdev_asize = asize;
1675 
1676         vdev_set_min_asize(vd);
1677 
1678         /*
1679          * Ensure we can issue some IO before declaring the
1680          * vdev open for business.
1681          */
1682         if (vd->vdev_ops->vdev_op_leaf &&
1683             (error = zio_wait(vdev_probe(vd, NULL))) != 0) {
1684                 vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
1685                     VDEV_AUX_ERR_EXCEEDED);
1686                 return (error);
1687         }
1688 
1689         /*
1690          * Track the min and max ashift values for normal data devices.
1691          *
1692          * DJB - TBD these should perhaps be tracked per allocation class
1693          * (e.g. spa_min_ashift is used to round up post compression buffers)
1694          */
1695         if (vd->vdev_top == vd && vd->vdev_ashift != 0 &&
1696             vd->vdev_alloc_bias == VDEV_BIAS_NONE &&
1697             vd->vdev_aux == NULL) {
1698                 if (vd->vdev_ashift > spa->spa_max_ashift)
1699                         spa->spa_max_ashift = vd->vdev_ashift;
1700                 if (vd->vdev_ashift < spa->spa_min_ashift)
1701                         spa->spa_min_ashift = vd->vdev_ashift;
1702         }
1703 
1704         /*
1705          * If a leaf vdev has a DTL, and seems healthy, then kick off a
1706          * resilver.  But don't do this if we are doing a reopen for a scrub,
1707          * since this would just restart the scrub we are already doing.
1708          */
1709         if (vd->vdev_ops->vdev_op_leaf && !spa->spa_scrub_reopen &&
1710             vdev_resilver_needed(vd, NULL, NULL))
1711                 spa_async_request(spa, SPA_ASYNC_RESILVER);
1712 
1713         return (0);
1714 }
1715 
1716 /*
1717  * Called once the vdevs are all opened, this routine validates the label
1718  * contents. This needs to be done before vdev_load() so that we don't
1719  * inadvertently do repair I/Os to the wrong device.
1720  *
1721  * This function will only return failure if one of the vdevs indicates that it
1722  * has since been destroyed or exported.  This is only possible if
1723  * /etc/zfs/zpool.cache was readonly at the time.  Otherwise, the vdev state
1724  * will be updated but the function will return 0.
1725  */
1726 int
1727 vdev_validate(vdev_t *vd)
1728 {
1729         spa_t *spa = vd->vdev_spa;
1730         nvlist_t *label;
1731         uint64_t guid = 0, aux_guid = 0, top_guid;
1732         uint64_t state;
1733         nvlist_t *nvl;
1734         uint64_t txg;
1735 
1736         if (vdev_validate_skip)
1737                 return (0);
1738 
1739         for (uint64_t c = 0; c < vd->vdev_children; c++)
1740                 if (vdev_validate(vd->vdev_child[c]) != 0)
1741                         return (SET_ERROR(EBADF));
1742 
1743         /*
1744          * If the device has already failed, or was marked offline, don't do
1745          * any further validation.  Otherwise, label I/O will fail and we will
1746          * overwrite the previous state.
1747          */
1748         if (!vd->vdev_ops->vdev_op_leaf || !vdev_readable(vd))
1749                 return (0);
1750 
1751         /*
1752          * If we are performing an extreme rewind, we allow for a label that
1753          * was modified at a point after the current txg.
1754          * If config lock is not held do not check for the txg. spa_sync could
1755          * be updating the vdev's label before updating spa_last_synced_txg.
1756          */
1757         if (spa->spa_extreme_rewind || spa_last_synced_txg(spa) == 0 ||
1758             spa_config_held(spa, SCL_CONFIG, RW_WRITER) != SCL_CONFIG)
1759                 txg = UINT64_MAX;
1760         else
1761                 txg = spa_last_synced_txg(spa);
1762 
1763         if ((label = vdev_label_read_config(vd, txg)) == NULL) {
1764                 vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1765                     VDEV_AUX_BAD_LABEL);
1766                 vdev_dbgmsg(vd, "vdev_validate: failed reading config for "
1767                     "txg %llu", (u_longlong_t)txg);
1768                 return (0);
1769         }
1770 
1771         /*
1772          * Determine if this vdev has been split off into another
1773          * pool.  If so, then refuse to open it.
1774          */
1775         if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_SPLIT_GUID,
1776             &aux_guid) == 0 && aux_guid == spa_guid(spa)) {
1777                 vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1778                     VDEV_AUX_SPLIT_POOL);
1779                 nvlist_free(label);
1780                 vdev_dbgmsg(vd, "vdev_validate: vdev split into other pool");
1781                 return (0);
1782         }
1783 
1784         if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_GUID, &guid) != 0) {
1785                 vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1786                     VDEV_AUX_CORRUPT_DATA);
1787                 nvlist_free(label);
1788                 vdev_dbgmsg(vd, "vdev_validate: '%s' missing from label",
1789                     ZPOOL_CONFIG_POOL_GUID);
1790                 return (0);
1791         }
1792 
1793         /*
1794          * If config is not trusted then ignore the spa guid check. This is
1795          * necessary because if the machine crashed during a re-guid the new
1796          * guid might have been written to all of the vdev labels, but not the
1797          * cached config. The check will be performed again once we have the
1798          * trusted config from the MOS.
1799          */
1800         if (spa->spa_trust_config && guid != spa_guid(spa)) {
1801                 vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1802                     VDEV_AUX_CORRUPT_DATA);
1803                 nvlist_free(label);
1804                 vdev_dbgmsg(vd, "vdev_validate: vdev label pool_guid doesn't "
1805                     "match config (%llu != %llu)", (u_longlong_t)guid,
1806                     (u_longlong_t)spa_guid(spa));
1807                 return (0);
1808         }
1809 
1810         if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_VDEV_TREE, &nvl)
1811             != 0 || nvlist_lookup_uint64(nvl, ZPOOL_CONFIG_ORIG_GUID,
1812             &aux_guid) != 0)
1813                 aux_guid = 0;
1814 
1815         if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID, &guid) != 0) {
1816                 vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1817                     VDEV_AUX_CORRUPT_DATA);
1818                 nvlist_free(label);
1819                 vdev_dbgmsg(vd, "vdev_validate: '%s' missing from label",
1820                     ZPOOL_CONFIG_GUID);
1821                 return (0);
1822         }
1823 
1824         if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_TOP_GUID, &top_guid)
1825             != 0) {
1826                 vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1827                     VDEV_AUX_CORRUPT_DATA);
1828                 nvlist_free(label);
1829                 vdev_dbgmsg(vd, "vdev_validate: '%s' missing from label",
1830                     ZPOOL_CONFIG_TOP_GUID);
1831                 return (0);
1832         }
1833 
1834         /*
1835          * If this vdev just became a top-level vdev because its sibling was
1836          * detached, it will have adopted the parent's vdev guid -- but the
1837          * label may or may not be on disk yet. Fortunately, either version
1838          * of the label will have the same top guid, so if we're a top-level
1839          * vdev, we can safely compare to that instead.
1840          * However, if the config comes from a cachefile that failed to update
1841          * after the detach, a top-level vdev will appear as a non top-level
1842          * vdev in the config. Also relax the constraints if we perform an
1843          * extreme rewind.
1844          *
1845          * If we split this vdev off instead, then we also check the
1846          * original pool's guid. We don't want to consider the vdev
1847          * corrupt if it is partway through a split operation.
1848          */
1849         if (vd->vdev_guid != guid && vd->vdev_guid != aux_guid) {
1850                 boolean_t mismatch = B_FALSE;
1851                 if (spa->spa_trust_config && !spa->spa_extreme_rewind) {
1852                         if (vd != vd->vdev_top || vd->vdev_guid != top_guid)
1853                                 mismatch = B_TRUE;
1854                 } else {
1855                         if (vd->vdev_guid != top_guid &&
1856                             vd->vdev_top->vdev_guid != guid)
1857                                 mismatch = B_TRUE;
1858                 }
1859 
1860                 if (mismatch) {
1861                         vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1862                             VDEV_AUX_CORRUPT_DATA);
1863                         nvlist_free(label);
1864                         vdev_dbgmsg(vd, "vdev_validate: config guid "
1865                             "doesn't match label guid");
1866                         vdev_dbgmsg(vd, "CONFIG: guid %llu, top_guid %llu",
1867                             (u_longlong_t)vd->vdev_guid,
1868                             (u_longlong_t)vd->vdev_top->vdev_guid);
1869                         vdev_dbgmsg(vd, "LABEL: guid %llu, top_guid %llu, "
1870                             "aux_guid %llu", (u_longlong_t)guid,
1871                             (u_longlong_t)top_guid, (u_longlong_t)aux_guid);
1872                         return (0);
1873                 }
1874         }
1875 
1876         if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE,
1877             &state) != 0) {
1878                 vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1879                     VDEV_AUX_CORRUPT_DATA);
1880                 nvlist_free(label);
1881                 vdev_dbgmsg(vd, "vdev_validate: '%s' missing from label",
1882                     ZPOOL_CONFIG_POOL_STATE);
1883                 return (0);
1884         }
1885 
1886         nvlist_free(label);
1887 
1888         /*
1889          * If this is a verbatim import, no need to check the
1890          * state of the pool.
1891          */
1892         if (!(spa->spa_import_flags & ZFS_IMPORT_VERBATIM) &&
1893             spa_load_state(spa) == SPA_LOAD_OPEN &&
1894             state != POOL_STATE_ACTIVE) {
1895                 vdev_dbgmsg(vd, "vdev_validate: invalid pool state (%llu) "
1896                     "for spa %s", (u_longlong_t)state, spa->spa_name);
1897                 return (SET_ERROR(EBADF));
1898         }
1899 
1900         /*
1901          * If we were able to open and validate a vdev that was
1902          * previously marked permanently unavailable, clear that state
1903          * now.
1904          */
1905         if (vd->vdev_not_present)
1906                 vd->vdev_not_present = 0;
1907 
1908         return (0);
1909 }
1910 
1911 static void
1912 vdev_copy_path_impl(vdev_t *svd, vdev_t *dvd)
1913 {
1914         if (svd->vdev_path != NULL && dvd->vdev_path != NULL) {
1915                 if (strcmp(svd->vdev_path, dvd->vdev_path) != 0) {
1916                         zfs_dbgmsg("vdev_copy_path: vdev %llu: path changed "
1917                             "from '%s' to '%s'", (u_longlong_t)dvd->vdev_guid,
1918                             dvd->vdev_path, svd->vdev_path);
1919                         spa_strfree(dvd->vdev_path);
1920                         dvd->vdev_path = spa_strdup(svd->vdev_path);
1921                 }
1922         } else if (svd->vdev_path != NULL) {
1923                 dvd->vdev_path = spa_strdup(svd->vdev_path);
1924                 zfs_dbgmsg("vdev_copy_path: vdev %llu: path set to '%s'",
1925                     (u_longlong_t)dvd->vdev_guid, dvd->vdev_path);
1926         }
1927 }
1928 
1929 /*
1930  * Recursively copy vdev paths from one vdev to another. Source and destination
1931  * vdev trees must have same geometry otherwise return error. Intended to copy
1932  * paths from userland config into MOS config.
1933  */
1934 int
1935 vdev_copy_path_strict(vdev_t *svd, vdev_t *dvd)
1936 {
1937         if ((svd->vdev_ops == &vdev_missing_ops) ||
1938             (svd->vdev_ishole && dvd->vdev_ishole) ||
1939             (dvd->vdev_ops == &vdev_indirect_ops))
1940                 return (0);
1941 
1942         if (svd->vdev_ops != dvd->vdev_ops) {
1943                 vdev_dbgmsg(svd, "vdev_copy_path: vdev type mismatch: %s != %s",
1944                     svd->vdev_ops->vdev_op_type, dvd->vdev_ops->vdev_op_type);
1945                 return (SET_ERROR(EINVAL));
1946         }
1947 
1948         if (svd->vdev_guid != dvd->vdev_guid) {
1949                 vdev_dbgmsg(svd, "vdev_copy_path: guids mismatch (%llu != "
1950                     "%llu)", (u_longlong_t)svd->vdev_guid,
1951                     (u_longlong_t)dvd->vdev_guid);
1952                 return (SET_ERROR(EINVAL));
1953         }
1954 
1955         if (svd->vdev_children != dvd->vdev_children) {
1956                 vdev_dbgmsg(svd, "vdev_copy_path: children count mismatch: "
1957                     "%llu != %llu", (u_longlong_t)svd->vdev_children,
1958                     (u_longlong_t)dvd->vdev_children);
1959                 return (SET_ERROR(EINVAL));
1960         }
1961 
1962         for (uint64_t i = 0; i < svd->vdev_children; i++) {
1963                 int error = vdev_copy_path_strict(svd->vdev_child[i],
1964                     dvd->vdev_child[i]);
1965                 if (error != 0)
1966                         return (error);
1967         }
1968 
1969         if (svd->vdev_ops->vdev_op_leaf)
1970                 vdev_copy_path_impl(svd, dvd);
1971 
1972         return (0);
1973 }
1974 
1975 static void
1976 vdev_copy_path_search(vdev_t *stvd, vdev_t *dvd)
1977 {
1978         ASSERT(stvd->vdev_top == stvd);
1979         ASSERT3U(stvd->vdev_id, ==, dvd->vdev_top->vdev_id);
1980 
1981         for (uint64_t i = 0; i < dvd->vdev_children; i++) {
1982                 vdev_copy_path_search(stvd, dvd->vdev_child[i]);
1983         }
1984 
1985         if (!dvd->vdev_ops->vdev_op_leaf || !vdev_is_concrete(dvd))
1986                 return;
1987 
1988         /*
1989          * The idea here is that while a vdev can shift positions within
1990          * a top vdev (when replacing, attaching mirror, etc.) it cannot
1991          * step outside of it.
1992          */
1993         vdev_t *vd = vdev_lookup_by_guid(stvd, dvd->vdev_guid);
1994 
1995         if (vd == NULL || vd->vdev_ops != dvd->vdev_ops)
1996                 return;
1997 
1998         ASSERT(vd->vdev_ops->vdev_op_leaf);
1999 
2000         vdev_copy_path_impl(vd, dvd);
2001 }
2002 
2003 /*
2004  * Recursively copy vdev paths from one root vdev to another. Source and
2005  * destination vdev trees may differ in geometry. For each destination leaf
2006  * vdev, search a vdev with the same guid and top vdev id in the source.
2007  * Intended to copy paths from userland config into MOS config.
2008  */
2009 void
2010 vdev_copy_path_relaxed(vdev_t *srvd, vdev_t *drvd)
2011 {
2012         uint64_t children = MIN(srvd->vdev_children, drvd->vdev_children);
2013         ASSERT(srvd->vdev_ops == &vdev_root_ops);
2014         ASSERT(drvd->vdev_ops == &vdev_root_ops);
2015 
2016         for (uint64_t i = 0; i < children; i++) {
2017                 vdev_copy_path_search(srvd->vdev_child[i],
2018                     drvd->vdev_child[i]);
2019         }
2020 }
2021 
2022 /*
2023  * Close a virtual device.
2024  */
2025 void
2026 vdev_close(vdev_t *vd)
2027 {
2028         spa_t *spa = vd->vdev_spa;
2029         vdev_t *pvd = vd->vdev_parent;
2030 
2031         ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
2032 
2033         /*
2034          * If our parent is reopening, then we are as well, unless we are
2035          * going offline.
2036          */
2037         if (pvd != NULL && pvd->vdev_reopening)
2038                 vd->vdev_reopening = (pvd->vdev_reopening && !vd->vdev_offline);
2039 
2040         vd->vdev_ops->vdev_op_close(vd);
2041 
2042         vdev_cache_purge(vd);
2043 
2044         /*
2045          * We record the previous state before we close it, so that if we are
2046          * doing a reopen(), we don't generate FMA ereports if we notice that
2047          * it's still faulted.
2048          */
2049         vd->vdev_prevstate = vd->vdev_state;
2050 
2051         if (vd->vdev_offline)
2052                 vd->vdev_state = VDEV_STATE_OFFLINE;
2053         else
2054                 vd->vdev_state = VDEV_STATE_CLOSED;
2055         vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
2056 }
2057 
2058 void
2059 vdev_hold(vdev_t *vd)
2060 {
2061         spa_t *spa = vd->vdev_spa;
2062 
2063         ASSERT(spa_is_root(spa));
2064         if (spa->spa_state == POOL_STATE_UNINITIALIZED)
2065                 return;
2066 
2067         for (int c = 0; c < vd->vdev_children; c++)
2068                 vdev_hold(vd->vdev_child[c]);
2069 
2070         if (vd->vdev_ops->vdev_op_leaf)
2071                 vd->vdev_ops->vdev_op_hold(vd);
2072 }
2073 
2074 void
2075 vdev_rele(vdev_t *vd)
2076 {
2077         spa_t *spa = vd->vdev_spa;
2078 
2079         ASSERT(spa_is_root(spa));
2080         for (int c = 0; c < vd->vdev_children; c++)
2081                 vdev_rele(vd->vdev_child[c]);
2082 
2083         if (vd->vdev_ops->vdev_op_leaf)
2084                 vd->vdev_ops->vdev_op_rele(vd);
2085 }
2086 
2087 /*
2088  * Reopen all interior vdevs and any unopened leaves.  We don't actually
2089  * reopen leaf vdevs which had previously been opened as they might deadlock
2090  * on the spa_config_lock.  Instead we only obtain the leaf's physical size.
2091  * If the leaf has never been opened then open it, as usual.
2092  */
2093 void
2094 vdev_reopen(vdev_t *vd)
2095 {
2096         spa_t *spa = vd->vdev_spa;
2097 
2098         ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
2099 
2100         /* set the reopening flag unless we're taking the vdev offline */
2101         vd->vdev_reopening = !vd->vdev_offline;
2102         vdev_close(vd);
2103         (void) vdev_open(vd);
2104 
2105         /*
2106          * Call vdev_validate() here to make sure we have the same device.
2107          * Otherwise, a device with an invalid label could be successfully
2108          * opened in response to vdev_reopen().
2109          */
2110         if (vd->vdev_aux) {
2111                 (void) vdev_validate_aux(vd);
2112                 if (vdev_readable(vd) && vdev_writeable(vd) &&
2113                     vd->vdev_aux == &spa->spa_l2cache &&
2114                     !l2arc_vdev_present(vd))
2115                         l2arc_add_vdev(spa, vd);
2116         } else {
2117                 (void) vdev_validate(vd);
2118         }
2119 
2120         /*
2121          * Reassess parent vdev's health.
2122          */
2123         vdev_propagate_state(vd);
2124 }
2125 
2126 int
2127 vdev_create(vdev_t *vd, uint64_t txg, boolean_t isreplacing)
2128 {
2129         int error;
2130 
2131         /*
2132          * Normally, partial opens (e.g. of a mirror) are allowed.
2133          * For a create, however, we want to fail the request if
2134          * there are any components we can't open.
2135          */
2136         error = vdev_open(vd);
2137 
2138         if (error || vd->vdev_state != VDEV_STATE_HEALTHY) {
2139                 vdev_close(vd);
2140                 return (error ? error : ENXIO);
2141         }
2142 
2143         /*
2144          * Recursively load DTLs and initialize all labels.
2145          */
2146         if ((error = vdev_dtl_load(vd)) != 0 ||
2147             (error = vdev_label_init(vd, txg, isreplacing ?
2148             VDEV_LABEL_REPLACE : VDEV_LABEL_CREATE)) != 0) {
2149                 vdev_close(vd);
2150                 return (error);
2151         }
2152 
2153         return (0);
2154 }
2155 
2156 void
2157 vdev_metaslab_set_size(vdev_t *vd)
2158 {
2159         uint64_t asize = vd->vdev_asize;
2160         uint64_t ms_count = asize >> zfs_vdev_default_ms_shift;
2161         uint64_t ms_shift;
2162 
2163         /*
2164          * There are two dimensions to the metaslab sizing calculation:
2165          * the size of the metaslab and the count of metaslabs per vdev.
2166          *
2167          * The default values used below are a good balance between memory
2168          * usage (larger metaslab size means more memory needed for loaded
2169          * metaslabs; more metaslabs means more memory needed for the
2170          * metaslab_t structs), metaslab load time (larger metaslabs take
2171          * longer to load), and metaslab sync time (more metaslabs means
2172          * more time spent syncing all of them).
2173          *
2174          * In general, we aim for zfs_vdev_default_ms_count (200) metaslabs.
2175          * The range of the dimensions are as follows:
2176          *
2177          *      2^29 <= ms_size  <= 2^34
2178          *        16 <= ms_count <= 131,072
2179          *
2180          * On the lower end of vdev sizes, we aim for metaslabs sizes of
2181          * at least 512MB (2^29) to minimize fragmentation effects when
2182          * testing with smaller devices.  However, the count constraint
2183          * of at least 16 metaslabs will override this minimum size goal.
2184          *
2185          * On the upper end of vdev sizes, we aim for a maximum metaslab
2186          * size of 16GB.  However, we will cap the total count to 2^17
2187          * metaslabs to keep our memory footprint in check and let the
2188          * metaslab size grow from there if that limit is hit.
2189          *
2190          * The net effect of applying above constrains is summarized below.
2191          *
2192          *   vdev size      metaslab count
2193          *  --------------|-----------------
2194          *      < 8GB                ~16
2195          *  8GB   - 100GB       one per 512MB
2196          *  100GB - 3TB         ~200
2197          *  3TB   - 2PB         one per 16GB
2198          *      > 2PB                ~131,072
2199          *  --------------------------------
2200          *
2201          *  Finally, note that all of the above calculate the initial
2202          *  number of metaslabs. Expanding a top-level vdev will result
2203          *  in additional metaslabs being allocated making it possible
2204          *  to exceed the zfs_vdev_ms_count_limit.
2205          */
2206 
2207         if (ms_count < zfs_vdev_min_ms_count)
2208                 ms_shift = highbit64(asize / zfs_vdev_min_ms_count);
2209         else if (ms_count > zfs_vdev_default_ms_count)
2210                 ms_shift = highbit64(asize / zfs_vdev_default_ms_count);
2211         else
2212                 ms_shift = zfs_vdev_default_ms_shift;
2213 
2214         if (ms_shift < SPA_MAXBLOCKSHIFT) {
2215                 ms_shift = SPA_MAXBLOCKSHIFT;
2216         } else if (ms_shift > zfs_vdev_max_ms_shift) {
2217                 ms_shift = zfs_vdev_max_ms_shift;
2218                 /* cap the total count to constrain memory footprint */
2219                 if ((asize >> ms_shift) > zfs_vdev_ms_count_limit)
2220                         ms_shift = highbit64(asize / zfs_vdev_ms_count_limit);
2221         }
2222 
2223         vd->vdev_ms_shift = ms_shift;
2224         ASSERT3U(vd->vdev_ms_shift, >=, SPA_MAXBLOCKSHIFT);
2225 }
2226 
2227 void
2228 vdev_dirty(vdev_t *vd, int flags, void *arg, uint64_t txg)
2229 {
2230         ASSERT(vd == vd->vdev_top);
2231         /* indirect vdevs don't have metaslabs or dtls */
2232         ASSERT(vdev_is_concrete(vd) || flags == 0);
2233         ASSERT(ISP2(flags));
2234         ASSERT(spa_writeable(vd->vdev_spa));
2235 
2236         if (flags & VDD_METASLAB)
2237                 (void) txg_list_add(&vd->vdev_ms_list, arg, txg);
2238 
2239         if (flags & VDD_DTL)
2240                 (void) txg_list_add(&vd->vdev_dtl_list, arg, txg);
2241 
2242         (void) txg_list_add(&vd->vdev_spa->spa_vdev_txg_list, vd, txg);
2243 }
2244 
2245 void
2246 vdev_dirty_leaves(vdev_t *vd, int flags, uint64_t txg)
2247 {
2248         for (int c = 0; c < vd->vdev_children; c++)
2249                 vdev_dirty_leaves(vd->vdev_child[c], flags, txg);
2250 
2251         if (vd->vdev_ops->vdev_op_leaf)
2252                 vdev_dirty(vd->vdev_top, flags, vd, txg);
2253 }
2254 
2255 /*
2256  * DTLs.
2257  *
2258  * A vdev's DTL (dirty time log) is the set of transaction groups for which
2259  * the vdev has less than perfect replication.  There are four kinds of DTL:
2260  *
2261  * DTL_MISSING: txgs for which the vdev has no valid copies of the data
2262  *
2263  * DTL_PARTIAL: txgs for which data is available, but not fully replicated
2264  *
2265  * DTL_SCRUB: the txgs that could not be repaired by the last scrub; upon
2266  *      scrub completion, DTL_SCRUB replaces DTL_MISSING in the range of
2267  *      txgs that was scrubbed.
2268  *
2269  * DTL_OUTAGE: txgs which cannot currently be read, whether due to
2270  *      persistent errors or just some device being offline.
2271  *      Unlike the other three, the DTL_OUTAGE map is not generally
2272  *      maintained; it's only computed when needed, typically to
2273  *      determine whether a device can be detached.
2274  *
2275  * For leaf vdevs, DTL_MISSING and DTL_PARTIAL are identical: the device
2276  * either has the data or it doesn't.
2277  *
2278  * For interior vdevs such as mirror and RAID-Z the picture is more complex.
2279  * A vdev's DTL_PARTIAL is the union of its children's DTL_PARTIALs, because
2280  * if any child is less than fully replicated, then so is its parent.
2281  * A vdev's DTL_MISSING is a modified union of its children's DTL_MISSINGs,
2282  * comprising only those txgs which appear in 'maxfaults' or more children;
2283  * those are the txgs we don't have enough replication to read.  For example,
2284  * double-parity RAID-Z can tolerate up to two missing devices (maxfaults == 2);
2285  * thus, its DTL_MISSING consists of the set of txgs that appear in more than
2286  * two child DTL_MISSING maps.
2287  *
2288  * It should be clear from the above that to compute the DTLs and outage maps
2289  * for all vdevs, it suffices to know just the leaf vdevs' DTL_MISSING maps.
2290  * Therefore, that is all we keep on disk.  When loading the pool, or after
2291  * a configuration change, we generate all other DTLs from first principles.
2292  */
2293 void
2294 vdev_dtl_dirty(vdev_t *vd, vdev_dtl_type_t t, uint64_t txg, uint64_t size)
2295 {
2296         range_tree_t *rt = vd->vdev_dtl[t];
2297 
2298         ASSERT(t < DTL_TYPES);
2299         ASSERT(vd != vd->vdev_spa->spa_root_vdev);
2300         ASSERT(spa_writeable(vd->vdev_spa));
2301 
2302         mutex_enter(&vd->vdev_dtl_lock);
2303         if (!range_tree_contains(rt, txg, size))
2304                 range_tree_add(rt, txg, size);
2305         mutex_exit(&vd->vdev_dtl_lock);
2306 }
2307 
2308 boolean_t
2309 vdev_dtl_contains(vdev_t *vd, vdev_dtl_type_t t, uint64_t txg, uint64_t size)
2310 {
2311         range_tree_t *rt = vd->vdev_dtl[t];
2312         boolean_t dirty = B_FALSE;
2313 
2314         ASSERT(t < DTL_TYPES);
2315         ASSERT(vd != vd->vdev_spa->spa_root_vdev);
2316 
2317         /*
2318          * While we are loading the pool, the DTLs have not been loaded yet.
2319          * Ignore the DTLs and try all devices.  This avoids a recursive
2320          * mutex enter on the vdev_dtl_lock, and also makes us try hard
2321          * when loading the pool (relying on the checksum to ensure that
2322          * we get the right data -- note that we while loading, we are
2323          * only reading the MOS, which is always checksummed).
2324          */
2325         if (vd->vdev_spa->spa_load_state != SPA_LOAD_NONE)
2326                 return (B_FALSE);
2327 
2328         mutex_enter(&vd->vdev_dtl_lock);
2329         if (!range_tree_is_empty(rt))
2330                 dirty = range_tree_contains(rt, txg, size);
2331         mutex_exit(&vd->vdev_dtl_lock);
2332 
2333         return (dirty);
2334 }
2335 
2336 boolean_t
2337 vdev_dtl_empty(vdev_t *vd, vdev_dtl_type_t t)
2338 {
2339         range_tree_t *rt = vd->vdev_dtl[t];
2340         boolean_t empty;
2341 
2342         mutex_enter(&vd->vdev_dtl_lock);
2343         empty = range_tree_is_empty(rt);
2344         mutex_exit(&vd->vdev_dtl_lock);
2345 
2346         return (empty);
2347 }
2348 
2349 /*
2350  * Returns the lowest txg in the DTL range.
2351  */
2352 static uint64_t
2353 vdev_dtl_min(vdev_t *vd)
2354 {
2355         range_seg_t *rs;
2356 
2357         ASSERT(MUTEX_HELD(&vd->vdev_dtl_lock));
2358         ASSERT3U(range_tree_space(vd->vdev_dtl[DTL_MISSING]), !=, 0);
2359         ASSERT0(vd->vdev_children);
2360 
2361         rs = avl_first(&vd->vdev_dtl[DTL_MISSING]->rt_root);
2362         return (rs->rs_start - 1);
2363 }
2364 
2365 /*
2366  * Returns the highest txg in the DTL.
2367  */
2368 static uint64_t
2369 vdev_dtl_max(vdev_t *vd)
2370 {
2371         range_seg_t *rs;
2372 
2373         ASSERT(MUTEX_HELD(&vd->vdev_dtl_lock));
2374         ASSERT3U(range_tree_space(vd->vdev_dtl[DTL_MISSING]), !=, 0);
2375         ASSERT0(vd->vdev_children);
2376 
2377         rs = avl_last(&vd->vdev_dtl[DTL_MISSING]->rt_root);
2378         return (rs->rs_end);
2379 }
2380 
2381 /*
2382  * Determine if a resilvering vdev should remove any DTL entries from
2383  * its range. If the vdev was resilvering for the entire duration of the
2384  * scan then it should excise that range from its DTLs. Otherwise, this
2385  * vdev is considered partially resilvered and should leave its DTL
2386  * entries intact. The comment in vdev_dtl_reassess() describes how we
2387  * excise the DTLs.
2388  */
2389 static boolean_t
2390 vdev_dtl_should_excise(vdev_t *vd)
2391 {
2392         spa_t *spa = vd->vdev_spa;
2393         dsl_scan_t *scn = spa->spa_dsl_pool->dp_scan;
2394 
2395         ASSERT0(scn->scn_phys.scn_errors);
2396         ASSERT0(vd->vdev_children);
2397 
2398         if (vd->vdev_state < VDEV_STATE_DEGRADED)
2399                 return (B_FALSE);
2400 
2401         if (vd->vdev_resilver_txg == 0 ||
2402             range_tree_is_empty(vd->vdev_dtl[DTL_MISSING]))
2403                 return (B_TRUE);
2404 
2405         /*
2406          * When a resilver is initiated the scan will assign the scn_max_txg
2407          * value to the highest txg value that exists in all DTLs. If this
2408          * device's max DTL is not part of this scan (i.e. it is not in
2409          * the range (scn_min_txg, scn_max_txg] then it is not eligible
2410          * for excision.
2411          */
2412         if (vdev_dtl_max(vd) <= scn->scn_phys.scn_max_txg) {
2413                 ASSERT3U(scn->scn_phys.scn_min_txg, <=, vdev_dtl_min(vd));
2414                 ASSERT3U(scn->scn_phys.scn_min_txg, <, vd->vdev_resilver_txg);
2415                 ASSERT3U(vd->vdev_resilver_txg, <=, scn->scn_phys.scn_max_txg);
2416                 return (B_TRUE);
2417         }
2418         return (B_FALSE);
2419 }
2420 
2421 /*
2422  * Reassess DTLs after a config change or scrub completion.
2423  */
2424 void
2425 vdev_dtl_reassess(vdev_t *vd, uint64_t txg, uint64_t scrub_txg, int scrub_done)
2426 {
2427         spa_t *spa = vd->vdev_spa;
2428         avl_tree_t reftree;
2429         int minref;
2430 
2431         ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
2432 
2433         for (int c = 0; c < vd->vdev_children; c++)
2434                 vdev_dtl_reassess(vd->vdev_child[c], txg,
2435                     scrub_txg, scrub_done);
2436 
2437         if (vd == spa->spa_root_vdev || !vdev_is_concrete(vd) || vd->vdev_aux)
2438                 return;
2439 
2440         if (vd->vdev_ops->vdev_op_leaf) {
2441                 dsl_scan_t *scn = spa->spa_dsl_pool->dp_scan;
2442 
2443                 mutex_enter(&vd->vdev_dtl_lock);
2444 
2445                 /*
2446                  * If we've completed a scan cleanly then determine
2447                  * if this vdev should remove any DTLs. We only want to
2448                  * excise regions on vdevs that were available during
2449                  * the entire duration of this scan.
2450                  */
2451                 if (scrub_txg != 0 &&
2452                     (spa->spa_scrub_started ||
2453                     (scn != NULL && scn->scn_phys.scn_errors == 0)) &&
2454                     vdev_dtl_should_excise(vd)) {
2455                         /*
2456                          * We completed a scrub up to scrub_txg.  If we
2457                          * did it without rebooting, then the scrub dtl
2458                          * will be valid, so excise the old region and
2459                          * fold in the scrub dtl.  Otherwise, leave the
2460                          * dtl as-is if there was an error.
2461                          *
2462                          * There's little trick here: to excise the beginning
2463                          * of the DTL_MISSING map, we put it into a reference
2464                          * tree and then add a segment with refcnt -1 that
2465                          * covers the range [0, scrub_txg).  This means
2466                          * that each txg in that range has refcnt -1 or 0.
2467                          * We then add DTL_SCRUB with a refcnt of 2, so that
2468                          * entries in the range [0, scrub_txg) will have a
2469                          * positive refcnt -- either 1 or 2.  We then convert
2470                          * the reference tree into the new DTL_MISSING map.
2471                          */
2472                         space_reftree_create(&reftree);
2473                         space_reftree_add_map(&reftree,
2474                             vd->vdev_dtl[DTL_MISSING], 1);
2475                         space_reftree_add_seg(&reftree, 0, scrub_txg, -1);
2476                         space_reftree_add_map(&reftree,
2477                             vd->vdev_dtl[DTL_SCRUB], 2);
2478                         space_reftree_generate_map(&reftree,
2479                             vd->vdev_dtl[DTL_MISSING], 1);
2480                         space_reftree_destroy(&reftree);
2481                 }
2482                 range_tree_vacate(vd->vdev_dtl[DTL_PARTIAL], NULL, NULL);
2483                 range_tree_walk(vd->vdev_dtl[DTL_MISSING],
2484                     range_tree_add, vd->vdev_dtl[DTL_PARTIAL]);
2485                 if (scrub_done)
2486                         range_tree_vacate(vd->vdev_dtl[DTL_SCRUB], NULL, NULL);
2487                 range_tree_vacate(vd->vdev_dtl[DTL_OUTAGE], NULL, NULL);
2488                 if (!vdev_readable(vd))
2489                         range_tree_add(vd->vdev_dtl[DTL_OUTAGE], 0, -1ULL);
2490                 else
2491                         range_tree_walk(vd->vdev_dtl[DTL_MISSING],
2492                             range_tree_add, vd->vdev_dtl[DTL_OUTAGE]);
2493 
2494                 /*
2495                  * If the vdev was resilvering and no longer has any
2496                  * DTLs then reset its resilvering flag.
2497                  */
2498                 if (vd->vdev_resilver_txg != 0 &&
2499                     range_tree_is_empty(vd->vdev_dtl[DTL_MISSING]) &&
2500                     range_tree_is_empty(vd->vdev_dtl[DTL_OUTAGE]))
2501                         vd->vdev_resilver_txg = 0;
2502 
2503                 mutex_exit(&vd->vdev_dtl_lock);
2504 
2505                 if (txg != 0)
2506                         vdev_dirty(vd->vdev_top, VDD_DTL, vd, txg);
2507                 return;
2508         }
2509 
2510         mutex_enter(&vd->vdev_dtl_lock);
2511         for (int t = 0; t < DTL_TYPES; t++) {
2512                 /* account for child's outage in parent's missing map */
2513                 int s = (t == DTL_MISSING) ? DTL_OUTAGE: t;
2514                 if (t == DTL_SCRUB)
2515                         continue;                       /* leaf vdevs only */
2516                 if (t == DTL_PARTIAL)
2517                         minref = 1;                     /* i.e. non-zero */
2518                 else if (vd->vdev_nparity != 0)
2519                         minref = vd->vdev_nparity + 1;       /* RAID-Z */
2520                 else
2521                         minref = vd->vdev_children;  /* any kind of mirror */
2522                 space_reftree_create(&reftree);
2523                 for (int c = 0; c < vd->vdev_children; c++) {
2524                         vdev_t *cvd = vd->vdev_child[c];
2525                         mutex_enter(&cvd->vdev_dtl_lock);
2526                         space_reftree_add_map(&reftree, cvd->vdev_dtl[s], 1);
2527                         mutex_exit(&cvd->vdev_dtl_lock);
2528                 }
2529                 space_reftree_generate_map(&reftree, vd->vdev_dtl[t], minref);
2530                 space_reftree_destroy(&reftree);
2531         }
2532         mutex_exit(&vd->vdev_dtl_lock);
2533 }
2534 
2535 int
2536 vdev_dtl_load(vdev_t *vd)
2537 {
2538         spa_t *spa = vd->vdev_spa;
2539         objset_t *mos = spa->spa_meta_objset;
2540         int error = 0;
2541 
2542         if (vd->vdev_ops->vdev_op_leaf && vd->vdev_dtl_object != 0) {
2543                 ASSERT(vdev_is_concrete(vd));
2544 
2545                 error = space_map_open(&vd->vdev_dtl_sm, mos,
2546                     vd->vdev_dtl_object, 0, -1ULL, 0);
2547                 if (error)
2548                         return (error);
2549                 ASSERT(vd->vdev_dtl_sm != NULL);
2550 
2551                 mutex_enter(&vd->vdev_dtl_lock);
2552 
2553                 /*
2554                  * Now that we've opened the space_map we need to update
2555                  * the in-core DTL.
2556                  */
2557                 space_map_update(vd->vdev_dtl_sm);
2558 
2559                 error = space_map_load(vd->vdev_dtl_sm,
2560                     vd->vdev_dtl[DTL_MISSING], SM_ALLOC);
2561                 mutex_exit(&vd->vdev_dtl_lock);
2562 
2563                 return (error);
2564         }
2565 
2566         for (int c = 0; c < vd->vdev_children; c++) {
2567                 error = vdev_dtl_load(vd->vdev_child[c]);
2568                 if (error != 0)
2569                         break;
2570         }
2571 
2572         return (error);
2573 }
2574 
2575 static void
2576 vdev_zap_allocation_data(vdev_t *vd, dmu_tx_t *tx)
2577 {
2578         spa_t *spa = vd->vdev_spa;
2579         objset_t *mos = spa->spa_meta_objset;
2580         vdev_alloc_bias_t alloc_bias = vd->vdev_alloc_bias;
2581         const char *string;
2582 
2583         ASSERT(alloc_bias != VDEV_BIAS_NONE);
2584 
2585         string =
2586             (alloc_bias == VDEV_BIAS_LOG) ? VDEV_ALLOC_BIAS_LOG :
2587             (alloc_bias == VDEV_BIAS_SPECIAL) ? VDEV_ALLOC_BIAS_SPECIAL :
2588             (alloc_bias == VDEV_BIAS_DEDUP) ? VDEV_ALLOC_BIAS_DEDUP : NULL;
2589 
2590         ASSERT(string != NULL);
2591         VERIFY0(zap_add(mos, vd->vdev_top_zap, VDEV_TOP_ZAP_ALLOCATION_BIAS,
2592             1, strlen(string) + 1, string, tx));
2593 
2594         if (alloc_bias == VDEV_BIAS_SPECIAL || alloc_bias == VDEV_BIAS_DEDUP) {
2595                 spa_activate_allocation_classes(spa, tx);
2596         }
2597 }
2598 
2599 void
2600 vdev_destroy_unlink_zap(vdev_t *vd, uint64_t zapobj, dmu_tx_t *tx)
2601 {
2602         spa_t *spa = vd->vdev_spa;
2603 
2604         VERIFY0(zap_destroy(spa->spa_meta_objset, zapobj, tx));
2605         VERIFY0(zap_remove_int(spa->spa_meta_objset, spa->spa_all_vdev_zaps,
2606             zapobj, tx));
2607 }
2608 
2609 uint64_t
2610 vdev_create_link_zap(vdev_t *vd, dmu_tx_t *tx)
2611 {
2612         spa_t *spa = vd->vdev_spa;
2613         uint64_t zap = zap_create(spa->spa_meta_objset, DMU_OTN_ZAP_METADATA,
2614             DMU_OT_NONE, 0, tx);
2615 
2616         ASSERT(zap != 0);
2617         VERIFY0(zap_add_int(spa->spa_meta_objset, spa->spa_all_vdev_zaps,
2618             zap, tx));
2619 
2620         return (zap);
2621 }
2622 
2623 void
2624 vdev_construct_zaps(vdev_t *vd, dmu_tx_t *tx)
2625 {
2626         if (vd->vdev_ops != &vdev_hole_ops &&
2627             vd->vdev_ops != &vdev_missing_ops &&
2628             vd->vdev_ops != &vdev_root_ops &&
2629             !vd->vdev_top->vdev_removing) {
2630                 if (vd->vdev_ops->vdev_op_leaf && vd->vdev_leaf_zap == 0) {
2631                         vd->vdev_leaf_zap = vdev_create_link_zap(vd, tx);
2632                 }
2633                 if (vd == vd->vdev_top && vd->vdev_top_zap == 0) {
2634                         vd->vdev_top_zap = vdev_create_link_zap(vd, tx);
2635                         if (vd->vdev_alloc_bias != VDEV_BIAS_NONE)
2636                                 vdev_zap_allocation_data(vd, tx);
2637                 }
2638         }
2639 
2640         for (uint64_t i = 0; i < vd->vdev_children; i++) {
2641                 vdev_construct_zaps(vd->vdev_child[i], tx);
2642         }
2643 }
2644 
2645 void
2646 vdev_dtl_sync(vdev_t *vd, uint64_t txg)
2647 {
2648         spa_t *spa = vd->vdev_spa;
2649         range_tree_t *rt = vd->vdev_dtl[DTL_MISSING];
2650         objset_t *mos = spa->spa_meta_objset;
2651         range_tree_t *rtsync;
2652         dmu_tx_t *tx;
2653         uint64_t object = space_map_object(vd->vdev_dtl_sm);
2654 
2655         ASSERT(vdev_is_concrete(vd));
2656         ASSERT(vd->vdev_ops->vdev_op_leaf);
2657 
2658         tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
2659 
2660         if (vd->vdev_detached || vd->vdev_top->vdev_removing) {
2661                 mutex_enter(&vd->vdev_dtl_lock);
2662                 space_map_free(vd->vdev_dtl_sm, tx);
2663                 space_map_close(vd->vdev_dtl_sm);
2664                 vd->vdev_dtl_sm = NULL;
2665                 mutex_exit(&vd->vdev_dtl_lock);
2666 
2667                 /*
2668                  * We only destroy the leaf ZAP for detached leaves or for
2669                  * removed log devices. Removed data devices handle leaf ZAP
2670                  * cleanup later, once cancellation is no longer possible.
2671                  */
2672                 if (vd->vdev_leaf_zap != 0 && (vd->vdev_detached ||
2673                     vd->vdev_top->vdev_islog)) {
2674                         vdev_destroy_unlink_zap(vd, vd->vdev_leaf_zap, tx);
2675                         vd->vdev_leaf_zap = 0;
2676                 }
2677 
2678                 dmu_tx_commit(tx);
2679                 return;
2680         }
2681 
2682         if (vd->vdev_dtl_sm == NULL) {
2683                 uint64_t new_object;
2684 
2685                 new_object = space_map_alloc(mos, vdev_dtl_sm_blksz, tx);
2686                 VERIFY3U(new_object, !=, 0);
2687 
2688                 VERIFY0(space_map_open(&vd->vdev_dtl_sm, mos, new_object,
2689                     0, -1ULL, 0));
2690                 ASSERT(vd->vdev_dtl_sm != NULL);
2691         }
2692 
2693         rtsync = range_tree_create(NULL, NULL);
2694 
2695         mutex_enter(&vd->vdev_dtl_lock);
2696         range_tree_walk(rt, range_tree_add, rtsync);
2697         mutex_exit(&vd->vdev_dtl_lock);
2698 
2699         space_map_truncate(vd->vdev_dtl_sm, vdev_dtl_sm_blksz, tx);
2700         space_map_write(vd->vdev_dtl_sm, rtsync, SM_ALLOC, SM_NO_VDEVID, tx);
2701         range_tree_vacate(rtsync, NULL, NULL);
2702 
2703         range_tree_destroy(rtsync);
2704 
2705         /*
2706          * If the object for the space map has changed then dirty
2707          * the top level so that we update the config.
2708          */
2709         if (object != space_map_object(vd->vdev_dtl_sm)) {
2710                 vdev_dbgmsg(vd, "txg %llu, spa %s, DTL old object %llu, "
2711                     "new object %llu", (u_longlong_t)txg, spa_name(spa),
2712                     (u_longlong_t)object,
2713                     (u_longlong_t)space_map_object(vd->vdev_dtl_sm));
2714                 vdev_config_dirty(vd->vdev_top);
2715         }
2716 
2717         dmu_tx_commit(tx);
2718 
2719         mutex_enter(&vd->vdev_dtl_lock);
2720         space_map_update(vd->vdev_dtl_sm);
2721         mutex_exit(&vd->vdev_dtl_lock);
2722 }
2723 
2724 /*
2725  * Determine whether the specified vdev can be offlined/detached/removed
2726  * without losing data.
2727  */
2728 boolean_t
2729 vdev_dtl_required(vdev_t *vd)
2730 {
2731         spa_t *spa = vd->vdev_spa;
2732         vdev_t *tvd = vd->vdev_top;
2733         uint8_t cant_read = vd->vdev_cant_read;
2734         boolean_t required;
2735 
2736         ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
2737 
2738         if (vd == spa->spa_root_vdev || vd == tvd)
2739                 return (B_TRUE);
2740 
2741         /*
2742          * Temporarily mark the device as unreadable, and then determine
2743          * whether this results in any DTL outages in the top-level vdev.
2744          * If not, we can safely offline/detach/remove the device.
2745          */
2746         vd->vdev_cant_read = B_TRUE;
2747         vdev_dtl_reassess(tvd, 0, 0, B_FALSE);
2748         required = !vdev_dtl_empty(tvd, DTL_OUTAGE);
2749         vd->vdev_cant_read = cant_read;
2750         vdev_dtl_reassess(tvd, 0, 0, B_FALSE);
2751 
2752         if (!required && zio_injection_enabled)
2753                 required = !!zio_handle_device_injection(vd, NULL, ECHILD);
2754 
2755         return (required);
2756 }
2757 
2758 /*
2759  * Determine if resilver is needed, and if so the txg range.
2760  */
2761 boolean_t
2762 vdev_resilver_needed(vdev_t *vd, uint64_t *minp, uint64_t *maxp)
2763 {
2764         boolean_t needed = B_FALSE;
2765         uint64_t thismin = UINT64_MAX;
2766         uint64_t thismax = 0;
2767 
2768         if (vd->vdev_children == 0) {
2769                 mutex_enter(&vd->vdev_dtl_lock);
2770                 if (!range_tree_is_empty(vd->vdev_dtl[DTL_MISSING]) &&
2771                     vdev_writeable(vd)) {
2772 
2773                         thismin = vdev_dtl_min(vd);
2774                         thismax = vdev_dtl_max(vd);
2775                         needed = B_TRUE;
2776                 }
2777                 mutex_exit(&vd->vdev_dtl_lock);
2778         } else {
2779                 for (int c = 0; c < vd->vdev_children; c++) {
2780                         vdev_t *cvd = vd->vdev_child[c];
2781                         uint64_t cmin, cmax;
2782 
2783                         if (vdev_resilver_needed(cvd, &cmin, &cmax)) {
2784                                 thismin = MIN(thismin, cmin);
2785                                 thismax = MAX(thismax, cmax);
2786                                 needed = B_TRUE;
2787                         }
2788                 }
2789         }
2790 
2791         if (needed && minp) {
2792                 *minp = thismin;
2793                 *maxp = thismax;
2794         }
2795         return (needed);
2796 }
2797 
2798 /*
2799  * Gets the checkpoint space map object from the vdev's ZAP.
2800  * Returns the spacemap object, or 0 if it wasn't in the ZAP
2801  * or the ZAP doesn't exist yet.
2802  */
2803 int
2804 vdev_checkpoint_sm_object(vdev_t *vd)
2805 {
2806         ASSERT0(spa_config_held(vd->vdev_spa, SCL_ALL, RW_WRITER));
2807         if (vd->vdev_top_zap == 0) {
2808                 return (0);
2809         }
2810 
2811         uint64_t sm_obj = 0;
2812         int err = zap_lookup(spa_meta_objset(vd->vdev_spa), vd->vdev_top_zap,
2813             VDEV_TOP_ZAP_POOL_CHECKPOINT_SM, sizeof (uint64_t), 1, &sm_obj);
2814 
2815         ASSERT(err == 0 || err == ENOENT);
2816 
2817         return (sm_obj);
2818 }
2819 
2820 int
2821 vdev_load(vdev_t *vd)
2822 {
2823         int error = 0;
2824         /*
2825          * Recursively load all children.
2826          */
2827         for (int c = 0; c < vd->vdev_children; c++) {
2828                 error = vdev_load(vd->vdev_child[c]);
2829                 if (error != 0) {
2830                         return (error);
2831                 }
2832         }
2833 
2834         vdev_set_deflate_ratio(vd);
2835 
2836         /*
2837          * On spa_load path, grab the allocation bias from our zap
2838          */
2839         if (vd == vd->vdev_top && vd->vdev_top_zap != 0) {
2840                 spa_t *spa = vd->vdev_spa;
2841                 char bias_str[64];
2842 
2843                 if (zap_lookup(spa->spa_meta_objset, vd->vdev_top_zap,
2844                     VDEV_TOP_ZAP_ALLOCATION_BIAS, 1, sizeof (bias_str),
2845                     bias_str) == 0) {
2846                         ASSERT(vd->vdev_alloc_bias == VDEV_BIAS_NONE);
2847                         vd->vdev_alloc_bias = vdev_derive_alloc_bias(bias_str);
2848                 }
2849         }
2850 
2851         /*
2852          * If this is a top-level vdev, initialize its metaslabs.
2853          */
2854         if (vd == vd->vdev_top && vdev_is_concrete(vd)) {
2855                 vdev_metaslab_group_create(vd);
2856 
2857                 if (vd->vdev_ashift == 0 || vd->vdev_asize == 0) {
2858                         vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2859                             VDEV_AUX_CORRUPT_DATA);
2860                         vdev_dbgmsg(vd, "vdev_load: invalid size. ashift=%llu, "
2861                             "asize=%llu", (u_longlong_t)vd->vdev_ashift,
2862                             (u_longlong_t)vd->vdev_asize);
2863                         return (SET_ERROR(ENXIO));
2864                 } else if ((error = vdev_metaslab_init(vd, 0)) != 0) {
2865                         vdev_dbgmsg(vd, "vdev_load: metaslab_init failed "
2866                             "[error=%d]", error);
2867                         vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2868                             VDEV_AUX_CORRUPT_DATA);
2869                         return (error);
2870                 }
2871 
2872                 uint64_t checkpoint_sm_obj = vdev_checkpoint_sm_object(vd);
2873                 if (checkpoint_sm_obj != 0) {
2874                         objset_t *mos = spa_meta_objset(vd->vdev_spa);
2875                         ASSERT(vd->vdev_asize != 0);
2876                         ASSERT3P(vd->vdev_checkpoint_sm, ==, NULL);
2877 
2878                         if ((error = space_map_open(&vd->vdev_checkpoint_sm,
2879                             mos, checkpoint_sm_obj, 0, vd->vdev_asize,
2880                             vd->vdev_ashift))) {
2881                                 vdev_dbgmsg(vd, "vdev_load: space_map_open "
2882                                     "failed for checkpoint spacemap (obj %llu) "
2883                                     "[error=%d]",
2884                                     (u_longlong_t)checkpoint_sm_obj, error);
2885                                 return (error);
2886                         }
2887                         ASSERT3P(vd->vdev_checkpoint_sm, !=, NULL);
2888                         space_map_update(vd->vdev_checkpoint_sm);
2889 
2890                         /*
2891                          * Since the checkpoint_sm contains free entries
2892                          * exclusively we can use sm_alloc to indicate the
2893                          * culmulative checkpointed space that has been freed.
2894                          */
2895                         vd->vdev_stat.vs_checkpoint_space =
2896                             -vd->vdev_checkpoint_sm->sm_alloc;
2897                         vd->vdev_spa->spa_checkpoint_info.sci_dspace +=
2898                             vd->vdev_stat.vs_checkpoint_space;
2899                 }
2900         }
2901 
2902         /*
2903          * If this is a leaf vdev, load its DTL.
2904          */
2905         if (vd->vdev_ops->vdev_op_leaf && (error = vdev_dtl_load(vd)) != 0) {
2906                 vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2907                     VDEV_AUX_CORRUPT_DATA);
2908                 vdev_dbgmsg(vd, "vdev_load: vdev_dtl_load failed "
2909                     "[error=%d]", error);
2910                 return (error);
2911         }
2912 
2913         uint64_t obsolete_sm_object = vdev_obsolete_sm_object(vd);
2914         if (obsolete_sm_object != 0) {
2915                 objset_t *mos = vd->vdev_spa->spa_meta_objset;
2916                 ASSERT(vd->vdev_asize != 0);
2917                 ASSERT3P(vd->vdev_obsolete_sm, ==, NULL);
2918 
2919                 if ((error = space_map_open(&vd->vdev_obsolete_sm, mos,
2920                     obsolete_sm_object, 0, vd->vdev_asize, 0))) {
2921                         vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2922                             VDEV_AUX_CORRUPT_DATA);
2923                         vdev_dbgmsg(vd, "vdev_load: space_map_open failed for "
2924                             "obsolete spacemap (obj %llu) [error=%d]",
2925                             (u_longlong_t)obsolete_sm_object, error);
2926                         return (error);
2927                 }
2928                 space_map_update(vd->vdev_obsolete_sm);
2929         }
2930 
2931         return (0);
2932 }
2933 
2934 /*
2935  * The special vdev case is used for hot spares and l2cache devices.  Its
2936  * sole purpose it to set the vdev state for the associated vdev.  To do this,
2937  * we make sure that we can open the underlying device, then try to read the
2938  * label, and make sure that the label is sane and that it hasn't been
2939  * repurposed to another pool.
2940  */
2941 int
2942 vdev_validate_aux(vdev_t *vd)
2943 {
2944         nvlist_t *label;
2945         uint64_t guid, version;
2946         uint64_t state;
2947 
2948         if (!vdev_readable(vd))
2949                 return (0);
2950 
2951         if ((label = vdev_label_read_config(vd, -1ULL)) == NULL) {
2952                 vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
2953                     VDEV_AUX_CORRUPT_DATA);
2954                 return (-1);
2955         }
2956 
2957         if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_VERSION, &version) != 0 ||
2958             !SPA_VERSION_IS_SUPPORTED(version) ||
2959             nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID, &guid) != 0 ||
2960             guid != vd->vdev_guid ||
2961             nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE, &state) != 0) {
2962                 vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
2963                     VDEV_AUX_CORRUPT_DATA);
2964                 nvlist_free(label);
2965                 return (-1);
2966         }
2967 
2968         /*
2969          * We don't actually check the pool state here.  If it's in fact in
2970          * use by another pool, we update this fact on the fly when requested.
2971          */
2972         nvlist_free(label);
2973         return (0);
2974 }
2975 
2976 /*
2977  * Free the objects used to store this vdev's spacemaps, and the array
2978  * that points to them.
2979  */
2980 void
2981 vdev_destroy_spacemaps(vdev_t *vd, dmu_tx_t *tx)
2982 {
2983         if (vd->vdev_ms_array == 0)
2984                 return;
2985 
2986         objset_t *mos = vd->vdev_spa->spa_meta_objset;
2987         uint64_t array_count = vd->vdev_asize >> vd->vdev_ms_shift;
2988         size_t array_bytes = array_count * sizeof (uint64_t);
2989         uint64_t *smobj_array = kmem_alloc(array_bytes, KM_SLEEP);
2990         VERIFY0(dmu_read(mos, vd->vdev_ms_array, 0,
2991             array_bytes, smobj_array, 0));
2992 
2993         for (uint64_t i = 0; i < array_count; i++) {
2994                 uint64_t smobj = smobj_array[i];
2995                 if (smobj == 0)
2996                         continue;
2997 
2998                 space_map_free_obj(mos, smobj, tx);
2999         }
3000 
3001         kmem_free(smobj_array, array_bytes);
3002         VERIFY0(dmu_object_free(mos, vd->vdev_ms_array, tx));
3003         vd->vdev_ms_array = 0;
3004 }
3005 
3006 static void
3007 vdev_remove_empty_log(vdev_t *vd, uint64_t txg)
3008 {
3009         spa_t *spa = vd->vdev_spa;
3010 
3011         ASSERT(vd->vdev_islog);
3012         ASSERT(vd == vd->vdev_top);
3013         ASSERT3U(txg, ==, spa_syncing_txg(spa));
3014 
3015         if (vd->vdev_ms != NULL) {
3016                 metaslab_group_t *mg = vd->vdev_mg;
3017 
3018                 metaslab_group_histogram_verify(mg);
3019                 metaslab_class_histogram_verify(mg->mg_class);
3020 
3021                 for (int m = 0; m < vd->vdev_ms_count; m++) {
3022                         metaslab_t *msp = vd->vdev_ms[m];
3023 
3024                         if (msp == NULL || msp->ms_sm == NULL)
3025                                 continue;
3026 
3027                         mutex_enter(&msp->ms_lock);
3028                         /*
3029                          * If the metaslab was not loaded when the vdev
3030                          * was removed then the histogram accounting may
3031                          * not be accurate. Update the histogram information
3032                          * here so that we ensure that the metaslab group
3033                          * and metaslab class are up-to-date.
3034                          */
3035                         metaslab_group_histogram_remove(mg, msp);
3036 
3037                         VERIFY0(space_map_allocated(msp->ms_sm));
3038                         space_map_close(msp->ms_sm);
3039                         msp->ms_sm = NULL;
3040                         mutex_exit(&msp->ms_lock);
3041                 }
3042 
3043                 if (vd->vdev_checkpoint_sm != NULL) {
3044                         ASSERT(spa_has_checkpoint(spa));
3045                         space_map_close(vd->vdev_checkpoint_sm);
3046                         vd->vdev_checkpoint_sm = NULL;
3047                 }
3048 
3049                 metaslab_group_histogram_verify(mg);
3050                 metaslab_class_histogram_verify(mg->mg_class);
3051 
3052                 for (int i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++)
3053                         ASSERT0(mg->mg_histogram[i]);
3054         }
3055 
3056         dmu_tx_t *tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
3057 
3058         vdev_destroy_spacemaps(vd, tx);
3059         if (vd->vdev_top_zap != 0) {
3060                 vdev_destroy_unlink_zap(vd, vd->vdev_top_zap, tx);
3061                 vd->vdev_top_zap = 0;
3062         }
3063 
3064         dmu_tx_commit(tx);
3065 }
3066 
3067 void
3068 vdev_sync_done(vdev_t *vd, uint64_t txg)
3069 {
3070         metaslab_t *msp;
3071         boolean_t reassess = !txg_list_empty(&vd->vdev_ms_list, TXG_CLEAN(txg));
3072 
3073         ASSERT(vdev_is_concrete(vd));
3074 
3075         while ((msp = txg_list_remove(&vd->vdev_ms_list, TXG_CLEAN(txg)))
3076             != NULL)
3077                 metaslab_sync_done(msp, txg);
3078 
3079         if (reassess)
3080                 metaslab_sync_reassess(vd->vdev_mg);
3081 }
3082 
3083 void
3084 vdev_sync(vdev_t *vd, uint64_t txg)
3085 {
3086         spa_t *spa = vd->vdev_spa;
3087         vdev_t *lvd;
3088         metaslab_t *msp;
3089         dmu_tx_t *tx;
3090 
3091         if (range_tree_space(vd->vdev_obsolete_segments) > 0) {
3092                 dmu_tx_t *tx;
3093 
3094                 ASSERT(vd->vdev_removing ||
3095                     vd->vdev_ops == &vdev_indirect_ops);
3096 
3097                 tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
3098                 vdev_indirect_sync_obsolete(vd, tx);
3099                 dmu_tx_commit(tx);
3100 
3101                 /*
3102                  * If the vdev is indirect, it can't have dirty
3103                  * metaslabs or DTLs.
3104                  */
3105                 if (vd->vdev_ops == &vdev_indirect_ops) {
3106                         ASSERT(txg_list_empty(&vd->vdev_ms_list, txg));
3107                         ASSERT(txg_list_empty(&vd->vdev_dtl_list, txg));
3108                         return;
3109                 }
3110         }
3111 
3112         ASSERT(vdev_is_concrete(vd));
3113 
3114         if (vd->vdev_ms_array == 0 && vd->vdev_ms_shift != 0 &&
3115             !vd->vdev_removing) {
3116                 ASSERT(vd == vd->vdev_top);
3117                 ASSERT0(vd->vdev_indirect_config.vic_mapping_object);
3118                 tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
3119                 vd->vdev_ms_array = dmu_object_alloc(spa->spa_meta_objset,
3120                     DMU_OT_OBJECT_ARRAY, 0, DMU_OT_NONE, 0, tx);
3121                 ASSERT(vd->vdev_ms_array != 0);
3122                 vdev_config_dirty(vd);
3123                 dmu_tx_commit(tx);
3124         }
3125 
3126         while ((msp = txg_list_remove(&vd->vdev_ms_list, txg)) != NULL) {
3127                 metaslab_sync(msp, txg);
3128                 (void) txg_list_add(&vd->vdev_ms_list, msp, TXG_CLEAN(txg));
3129         }
3130 
3131         while ((lvd = txg_list_remove(&vd->vdev_dtl_list, txg)) != NULL)
3132                 vdev_dtl_sync(lvd, txg);
3133 
3134         /*
3135          * If this is an empty log device being removed, destroy the
3136          * metadata associated with it.
3137          */
3138         if (vd->vdev_islog && vd->vdev_stat.vs_alloc == 0 && vd->vdev_removing)
3139                 vdev_remove_empty_log(vd, txg);
3140 
3141         (void) txg_list_add(&spa->spa_vdev_txg_list, vd, TXG_CLEAN(txg));
3142 }
3143 
3144 uint64_t
3145 vdev_psize_to_asize(vdev_t *vd, uint64_t psize)
3146 {
3147         return (vd->vdev_ops->vdev_op_asize(vd, psize));
3148 }
3149 
3150 /*
3151  * Mark the given vdev faulted.  A faulted vdev behaves as if the device could
3152  * not be opened, and no I/O is attempted.
3153  */
3154 int
3155 vdev_fault(spa_t *spa, uint64_t guid, vdev_aux_t aux)
3156 {
3157         vdev_t *vd, *tvd;
3158 
3159         spa_vdev_state_enter(spa, SCL_NONE);
3160 
3161         if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
3162                 return (spa_vdev_state_exit(spa, NULL, ENODEV));
3163 
3164         if (!vd->vdev_ops->vdev_op_leaf)
3165                 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
3166 
3167         tvd = vd->vdev_top;
3168 
3169         /*
3170          * We don't directly use the aux state here, but if we do a
3171          * vdev_reopen(), we need this value to be present to remember why we
3172          * were faulted.
3173          */
3174         vd->vdev_label_aux = aux;
3175 
3176         /*
3177          * Faulted state takes precedence over degraded.
3178          */
3179         vd->vdev_delayed_close = B_FALSE;
3180         vd->vdev_faulted = 1ULL;
3181         vd->vdev_degraded = 0ULL;
3182         vdev_set_state(vd, B_FALSE, VDEV_STATE_FAULTED, aux);
3183 
3184         /*
3185          * If this device has the only valid copy of the data, then
3186          * back off and simply mark the vdev as degraded instead.
3187          */
3188         if (!tvd->vdev_islog && vd->vdev_aux == NULL && vdev_dtl_required(vd)) {
3189                 vd->vdev_degraded = 1ULL;
3190                 vd->vdev_faulted = 0ULL;
3191 
3192                 /*
3193                  * If we reopen the device and it's not dead, only then do we
3194                  * mark it degraded.
3195                  */
3196                 vdev_reopen(tvd);
3197 
3198                 if (vdev_readable(vd))
3199                         vdev_set_state(vd, B_FALSE, VDEV_STATE_DEGRADED, aux);
3200         }
3201 
3202         return (spa_vdev_state_exit(spa, vd, 0));
3203 }
3204 
3205 /*
3206  * Mark the given vdev degraded.  A degraded vdev is purely an indication to the
3207  * user that something is wrong.  The vdev continues to operate as normal as far
3208  * as I/O is concerned.
3209  */
3210 int
3211 vdev_degrade(spa_t *spa, uint64_t guid, vdev_aux_t aux)
3212 {
3213         vdev_t *vd;
3214 
3215         spa_vdev_state_enter(spa, SCL_NONE);
3216 
3217         if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
3218                 return (spa_vdev_state_exit(spa, NULL, ENODEV));
3219 
3220         if (!vd->vdev_ops->vdev_op_leaf)
3221                 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
3222 
3223         /*
3224          * If the vdev is already faulted, then don't do anything.
3225          */
3226         if (vd->vdev_faulted || vd->vdev_degraded)
3227                 return (spa_vdev_state_exit(spa, NULL, 0));
3228 
3229         vd->vdev_degraded = 1ULL;
3230         if (!vdev_is_dead(vd))
3231                 vdev_set_state(vd, B_FALSE, VDEV_STATE_DEGRADED,
3232                     aux);
3233 
3234         return (spa_vdev_state_exit(spa, vd, 0));
3235 }
3236 
3237 /*
3238  * Online the given vdev.
3239  *
3240  * If 'ZFS_ONLINE_UNSPARE' is set, it implies two things.  First, any attached
3241  * spare device should be detached when the device finishes resilvering.
3242  * Second, the online should be treated like a 'test' online case, so no FMA
3243  * events are generated if the device fails to open.
3244  */
3245 int
3246 vdev_online(spa_t *spa, uint64_t guid, uint64_t flags, vdev_state_t *newstate)
3247 {
3248         vdev_t *vd, *tvd, *pvd, *rvd = spa->spa_root_vdev;
3249         boolean_t wasoffline;
3250         vdev_state_t oldstate;
3251 
3252         spa_vdev_state_enter(spa, SCL_NONE);
3253 
3254         if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
3255                 return (spa_vdev_state_exit(spa, NULL, ENODEV));
3256 
3257         if (!vd->vdev_ops->vdev_op_leaf)
3258                 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
3259 
3260         wasoffline = (vd->vdev_offline || vd->vdev_tmpoffline);
3261         oldstate = vd->vdev_state;
3262 
3263         tvd = vd->vdev_top;
3264         vd->vdev_offline = B_FALSE;
3265         vd->vdev_tmpoffline = B_FALSE;
3266         vd->vdev_checkremove = !!(flags & ZFS_ONLINE_CHECKREMOVE);
3267         vd->vdev_forcefault = !!(flags & ZFS_ONLINE_FORCEFAULT);
3268 
3269         /* XXX - L2ARC 1.0 does not support expansion */
3270         if (!vd->vdev_aux) {
3271                 for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
3272                         pvd->vdev_expanding = !!(flags & ZFS_ONLINE_EXPAND);
3273         }
3274 
3275         vdev_reopen(tvd);
3276         vd->vdev_checkremove = vd->vdev_forcefault = B_FALSE;
3277 
3278         if (!vd->vdev_aux) {
3279                 for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
3280                         pvd->vdev_expanding = B_FALSE;
3281         }
3282 
3283         if (newstate)
3284                 *newstate = vd->vdev_state;
3285         if ((flags & ZFS_ONLINE_UNSPARE) &&
3286             !vdev_is_dead(vd) && vd->vdev_parent &&
3287             vd->vdev_parent->vdev_ops == &vdev_spare_ops &&
3288             vd->vdev_parent->vdev_child[0] == vd)
3289                 vd->vdev_unspare = B_TRUE;
3290 
3291         if ((flags & ZFS_ONLINE_EXPAND) || spa->spa_autoexpand) {
3292 
3293                 /* XXX - L2ARC 1.0 does not support expansion */
3294                 if (vd->vdev_aux)
3295                         return (spa_vdev_state_exit(spa, vd, ENOTSUP));
3296                 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
3297         }
3298 
3299         /* Restart initializing if necessary */
3300         mutex_enter(&vd->vdev_initialize_lock);
3301         if (vdev_writeable(vd) &&
3302             vd->vdev_initialize_thread == NULL &&
3303             vd->vdev_initialize_state == VDEV_INITIALIZE_ACTIVE) {
3304                 (void) vdev_initialize(vd);
3305         }
3306         mutex_exit(&vd->vdev_initialize_lock);
3307 
3308         if (wasoffline ||
3309             (oldstate < VDEV_STATE_DEGRADED &&
3310             vd->vdev_state >= VDEV_STATE_DEGRADED))
3311                 spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_ONLINE);
3312 
3313         return (spa_vdev_state_exit(spa, vd, 0));
3314 }
3315 
3316 static int
3317 vdev_offline_locked(spa_t *spa, uint64_t guid, uint64_t flags)
3318 {
3319         vdev_t *vd, *tvd;
3320         int error = 0;
3321         uint64_t generation;
3322         metaslab_group_t *mg;
3323 
3324 top:
3325         spa_vdev_state_enter(spa, SCL_ALLOC);
3326 
3327         if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
3328                 return (spa_vdev_state_exit(spa, NULL, ENODEV));
3329 
3330         if (!vd->vdev_ops->vdev_op_leaf)
3331                 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
3332 
3333         tvd = vd->vdev_top;
3334         mg = tvd->vdev_mg;
3335         generation = spa->spa_config_generation + 1;
3336 
3337         /*
3338          * If the device isn't already offline, try to offline it.
3339          */
3340         if (!vd->vdev_offline) {
3341                 /*
3342                  * If this device has the only valid copy of some data,
3343                  * don't allow it to be offlined. Log devices are always
3344                  * expendable.
3345                  */
3346                 if (!tvd->vdev_islog && vd->vdev_aux == NULL &&
3347                     vdev_dtl_required(vd))
3348                         return (spa_vdev_state_exit(spa, NULL, EBUSY));
3349 
3350                 /*
3351                  * If the top-level is a slog and it has had allocations
3352                  * then proceed.  We check that the vdev's metaslab group
3353                  * is not NULL since it's possible that we may have just
3354                  * added this vdev but not yet initialized its metaslabs.
3355                  */
3356                 if (tvd->vdev_islog && mg != NULL) {
3357                         /*
3358                          * Prevent any future allocations.
3359                          */
3360                         metaslab_group_passivate(mg);
3361                         (void) spa_vdev_state_exit(spa, vd, 0);
3362 
3363                         error = spa_reset_logs(spa);
3364 
3365                         /*
3366                          * If the log device was successfully reset but has
3367                          * checkpointed data, do not offline it.
3368                          */
3369                         if (error == 0 &&
3370                             tvd->vdev_checkpoint_sm != NULL) {
3371                                 ASSERT3U(tvd->vdev_checkpoint_sm->sm_alloc,
3372                                     !=, 0);
3373                                 error = ZFS_ERR_CHECKPOINT_EXISTS;
3374                         }
3375 
3376                         spa_vdev_state_enter(spa, SCL_ALLOC);
3377 
3378                         /*
3379                          * Check to see if the config has changed.
3380                          */
3381                         if (error || generation != spa->spa_config_generation) {
3382                                 metaslab_group_activate(mg);
3383                                 if (error)
3384                                         return (spa_vdev_state_exit(spa,
3385                                             vd, error));
3386                                 (void) spa_vdev_state_exit(spa, vd, 0);
3387                                 goto top;
3388                         }
3389                         ASSERT0(tvd->vdev_stat.vs_alloc);
3390                 }
3391 
3392                 /*
3393                  * Offline this device and reopen its top-level vdev.
3394                  * If the top-level vdev is a log device then just offline
3395                  * it. Otherwise, if this action results in the top-level
3396                  * vdev becoming unusable, undo it and fail the request.
3397                  */
3398                 vd->vdev_offline = B_TRUE;
3399                 vdev_reopen(tvd);
3400 
3401                 if (!tvd->vdev_islog && vd->vdev_aux == NULL &&
3402                     vdev_is_dead(tvd)) {
3403                         vd->vdev_offline = B_FALSE;
3404                         vdev_reopen(tvd);
3405                         return (spa_vdev_state_exit(spa, NULL, EBUSY));
3406                 }
3407 
3408                 /*
3409                  * Add the device back into the metaslab rotor so that
3410                  * once we online the device it's open for business.
3411                  */
3412                 if (tvd->vdev_islog && mg != NULL)
3413                         metaslab_group_activate(mg);
3414         }
3415 
3416         vd->vdev_tmpoffline = !!(flags & ZFS_OFFLINE_TEMPORARY);
3417 
3418         return (spa_vdev_state_exit(spa, vd, 0));
3419 }
3420 
3421 int
3422 vdev_offline(spa_t *spa, uint64_t guid, uint64_t flags)
3423 {
3424         int error;
3425 
3426         mutex_enter(&spa->spa_vdev_top_lock);
3427         error = vdev_offline_locked(spa, guid, flags);
3428         mutex_exit(&spa->spa_vdev_top_lock);
3429 
3430         return (error);
3431 }
3432 
3433 /*
3434  * Clear the error counts associated with this vdev.  Unlike vdev_online() and
3435  * vdev_offline(), we assume the spa config is locked.  We also clear all
3436  * children.  If 'vd' is NULL, then the user wants to clear all vdevs.
3437  */
3438 void
3439 vdev_clear(spa_t *spa, vdev_t *vd)
3440 {
3441         vdev_t *rvd = spa->spa_root_vdev;
3442 
3443         ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
3444 
3445         if (vd == NULL)
3446                 vd = rvd;
3447 
3448         vd->vdev_stat.vs_read_errors = 0;
3449         vd->vdev_stat.vs_write_errors = 0;
3450         vd->vdev_stat.vs_checksum_errors = 0;
3451 
3452         for (int c = 0; c < vd->vdev_children; c++)
3453                 vdev_clear(spa, vd->vdev_child[c]);
3454 
3455         /*
3456          * It makes no sense to "clear" an indirect vdev.
3457          */
3458         if (!vdev_is_concrete(vd))
3459                 return;
3460 
3461         /*
3462          * If we're in the FAULTED state or have experienced failed I/O, then
3463          * clear the persistent state and attempt to reopen the device.  We
3464          * also mark the vdev config dirty, so that the new faulted state is
3465          * written out to disk.
3466          */
3467         if (vd->vdev_faulted || vd->vdev_degraded ||
3468             !vdev_readable(vd) || !vdev_writeable(vd)) {
3469 
3470                 /*
3471                  * When reopening in reponse to a clear event, it may be due to
3472                  * a fmadm repair request.  In this case, if the device is
3473                  * still broken, we want to still post the ereport again.
3474                  */
3475                 vd->vdev_forcefault = B_TRUE;
3476 
3477                 vd->vdev_faulted = vd->vdev_degraded = 0ULL;
3478                 vd->vdev_cant_read = B_FALSE;
3479                 vd->vdev_cant_write = B_FALSE;
3480 
3481                 vdev_reopen(vd == rvd ? rvd : vd->vdev_top);
3482 
3483                 vd->vdev_forcefault = B_FALSE;
3484 
3485                 if (vd != rvd && vdev_writeable(vd->vdev_top))
3486                         vdev_state_dirty(vd->vdev_top);
3487 
3488                 if (vd->vdev_aux == NULL && !vdev_is_dead(vd))
3489                         spa_async_request(spa, SPA_ASYNC_RESILVER);
3490 
3491                 spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_CLEAR);
3492         }
3493 
3494         /*
3495          * When clearing a FMA-diagnosed fault, we always want to
3496          * unspare the device, as we assume that the original spare was
3497          * done in response to the FMA fault.
3498          */
3499         if (!vdev_is_dead(vd) && vd->vdev_parent != NULL &&
3500             vd->vdev_parent->vdev_ops == &vdev_spare_ops &&
3501             vd->vdev_parent->vdev_child[0] == vd)
3502                 vd->vdev_unspare = B_TRUE;
3503 }
3504 
3505 boolean_t
3506 vdev_is_dead(vdev_t *vd)
3507 {
3508         /*
3509          * Holes and missing devices are always considered "dead".
3510          * This simplifies the code since we don't have to check for
3511          * these types of devices in the various code paths.
3512          * Instead we rely on the fact that we skip over dead devices
3513          * before issuing I/O to them.
3514          */
3515         return (vd->vdev_state < VDEV_STATE_DEGRADED ||
3516             vd->vdev_ops == &vdev_hole_ops ||
3517             vd->vdev_ops == &vdev_missing_ops);
3518 }
3519 
3520 boolean_t
3521 vdev_readable(vdev_t *vd)
3522 {
3523         return (!vdev_is_dead(vd) && !vd->vdev_cant_read);
3524 }
3525 
3526 boolean_t
3527 vdev_writeable(vdev_t *vd)
3528 {
3529         return (!vdev_is_dead(vd) && !vd->vdev_cant_write &&
3530             vdev_is_concrete(vd));
3531 }
3532 
3533 boolean_t
3534 vdev_allocatable(vdev_t *vd)
3535 {
3536         uint64_t state = vd->vdev_state;
3537 
3538         /*
3539          * We currently allow allocations from vdevs which may be in the
3540          * process of reopening (i.e. VDEV_STATE_CLOSED). If the device
3541          * fails to reopen then we'll catch it later when we're holding
3542          * the proper locks.  Note that we have to get the vdev state
3543          * in a local variable because although it changes atomically,
3544          * we're asking two separate questions about it.
3545          */
3546         return (!(state < VDEV_STATE_DEGRADED && state != VDEV_STATE_CLOSED) &&
3547             !vd->vdev_cant_write && vdev_is_concrete(vd) &&
3548             vd->vdev_mg->mg_initialized);
3549 }
3550 
3551 boolean_t
3552 vdev_accessible(vdev_t *vd, zio_t *zio)
3553 {
3554         ASSERT(zio->io_vd == vd);
3555 
3556         if (vdev_is_dead(vd) || vd->vdev_remove_wanted)
3557                 return (B_FALSE);
3558 
3559         if (zio->io_type == ZIO_TYPE_READ)
3560                 return (!vd->vdev_cant_read);
3561 
3562         if (zio->io_type == ZIO_TYPE_WRITE)
3563                 return (!vd->vdev_cant_write);
3564 
3565         return (B_TRUE);
3566 }
3567 
3568 boolean_t
3569 vdev_is_spacemap_addressable(vdev_t *vd)
3570 {
3571         if (spa_feature_is_active(vd->vdev_spa, SPA_FEATURE_SPACEMAP_V2))
3572                 return (B_TRUE);
3573 
3574         /*
3575          * If double-word space map entries are not enabled we assume
3576          * 47 bits of the space map entry are dedicated to the entry's
3577          * offset (see SM_OFFSET_BITS in space_map.h). We then use that
3578          * to calculate the maximum address that can be described by a
3579          * space map entry for the given device.
3580          */
3581         uint64_t shift = vd->vdev_ashift + SM_OFFSET_BITS;
3582 
3583         if (shift >= 63) /* detect potential overflow */
3584                 return (B_TRUE);
3585 
3586         return (vd->vdev_asize < (1ULL << shift));
3587 }
3588 
3589 /*
3590  * Get statistics for the given vdev.
3591  */
3592 void
3593 vdev_get_stats(vdev_t *vd, vdev_stat_t *vs)
3594 {
3595         spa_t *spa = vd->vdev_spa;
3596         vdev_t *rvd = spa->spa_root_vdev;
3597         vdev_t *tvd = vd->vdev_top;
3598 
3599         ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
3600 
3601         mutex_enter(&vd->vdev_stat_lock);
3602         bcopy(&vd->vdev_stat, vs, sizeof (*vs));
3603         vs->vs_timestamp = gethrtime() - vs->vs_timestamp;
3604         vs->vs_state = vd->vdev_state;
3605         vs->vs_rsize = vdev_get_min_asize(vd);
3606         if (vd->vdev_ops->vdev_op_leaf) {
3607                 vs->vs_rsize += VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE;
3608                 /*
3609                  * Report intializing progress. Since we don't have the
3610                  * initializing locks held, this is only an estimate (although a
3611                  * fairly accurate one).
3612                  */
3613                 vs->vs_initialize_bytes_done = vd->vdev_initialize_bytes_done;
3614                 vs->vs_initialize_bytes_est = vd->vdev_initialize_bytes_est;
3615                 vs->vs_initialize_state = vd->vdev_initialize_state;
3616                 vs->vs_initialize_action_time = vd->vdev_initialize_action_time;
3617         }
3618         /*
3619          * Report expandable space on top-level, non-auxillary devices only.
3620          * The expandable space is reported in terms of metaslab sized units
3621          * since that determines how much space the pool can expand.
3622          */
3623         if (vd->vdev_aux == NULL && tvd != NULL) {
3624                 vs->vs_esize = P2ALIGN(vd->vdev_max_asize - vd->vdev_asize -
3625                     spa->spa_bootsize, 1ULL << tvd->vdev_ms_shift);
3626         }
3627         if (vd->vdev_aux == NULL && vd == vd->vdev_top &&
3628             vdev_is_concrete(vd)) {
3629                 vs->vs_fragmentation = (vd->vdev_mg != NULL) ?
3630                     vd->vdev_mg->mg_fragmentation : 0;
3631         }
3632 
3633         /*
3634          * If we're getting stats on the root vdev, aggregate the I/O counts
3635          * over all top-level vdevs (i.e. the direct children of the root).
3636          */
3637         if (vd == rvd) {
3638                 for (int c = 0; c < rvd->vdev_children; c++) {
3639                         vdev_t *cvd = rvd->vdev_child[c];
3640                         vdev_stat_t *cvs = &cvd->vdev_stat;
3641 
3642                         for (int t = 0; t < ZIO_TYPES; t++) {
3643                                 vs->vs_ops[t] += cvs->vs_ops[t];
3644                                 vs->vs_bytes[t] += cvs->vs_bytes[t];
3645                         }
3646                         cvs->vs_scan_removing = cvd->vdev_removing;
3647                 }
3648         }
3649         mutex_exit(&vd->vdev_stat_lock);
3650 }
3651 
3652 void
3653 vdev_clear_stats(vdev_t *vd)
3654 {
3655         mutex_enter(&vd->vdev_stat_lock);
3656         vd->vdev_stat.vs_space = 0;
3657         vd->vdev_stat.vs_dspace = 0;
3658         vd->vdev_stat.vs_alloc = 0;
3659         mutex_exit(&vd->vdev_stat_lock);
3660 }
3661 
3662 void
3663 vdev_scan_stat_init(vdev_t *vd)
3664 {
3665         vdev_stat_t *vs = &vd->vdev_stat;
3666 
3667         for (int c = 0; c < vd->vdev_children; c++)
3668                 vdev_scan_stat_init(vd->vdev_child[c]);
3669 
3670         mutex_enter(&vd->vdev_stat_lock);
3671         vs->vs_scan_processed = 0;
3672         mutex_exit(&vd->vdev_stat_lock);
3673 }
3674 
3675 void
3676 vdev_stat_update(zio_t *zio, uint64_t psize)
3677 {
3678         spa_t *spa = zio->io_spa;
3679         vdev_t *rvd = spa->spa_root_vdev;
3680         vdev_t *vd = zio->io_vd ? zio->io_vd : rvd;
3681         vdev_t *pvd;
3682         uint64_t txg = zio->io_txg;
3683         vdev_stat_t *vs = &vd->vdev_stat;
3684         zio_type_t type = zio->io_type;
3685         int flags = zio->io_flags;
3686 
3687         /*
3688          * If this i/o is a gang leader, it didn't do any actual work.
3689          */
3690         if (zio->io_gang_tree)
3691                 return;
3692 
3693         if (zio->io_error == 0) {
3694                 /*
3695                  * If this is a root i/o, don't count it -- we've already
3696                  * counted the top-level vdevs, and vdev_get_stats() will
3697                  * aggregate them when asked.  This reduces contention on
3698                  * the root vdev_stat_lock and implicitly handles blocks
3699                  * that compress away to holes, for which there is no i/o.
3700                  * (Holes never create vdev children, so all the counters
3701                  * remain zero, which is what we want.)
3702                  *
3703                  * Note: this only applies to successful i/o (io_error == 0)
3704                  * because unlike i/o counts, errors are not additive.
3705                  * When reading a ditto block, for example, failure of
3706                  * one top-level vdev does not imply a root-level error.
3707                  */
3708                 if (vd == rvd)
3709                         return;
3710 
3711                 ASSERT(vd == zio->io_vd);
3712 
3713                 if (flags & ZIO_FLAG_IO_BYPASS)
3714                         return;
3715 
3716                 mutex_enter(&vd->vdev_stat_lock);
3717 
3718                 if (flags & ZIO_FLAG_IO_REPAIR) {
3719                         if (flags & ZIO_FLAG_SCAN_THREAD) {
3720                                 dsl_scan_phys_t *scn_phys =
3721                                     &spa->spa_dsl_pool->dp_scan->scn_phys;
3722                                 uint64_t *processed = &scn_phys->scn_processed;
3723 
3724                                 /* XXX cleanup? */
3725                                 if (vd->vdev_ops->vdev_op_leaf)
3726                                         atomic_add_64(processed, psize);
3727                                 vs->vs_scan_processed += psize;
3728                         }
3729 
3730                         if (flags & ZIO_FLAG_SELF_HEAL)
3731                                 vs->vs_self_healed += psize;
3732                 }
3733 
3734                 vs->vs_ops[type]++;
3735                 vs->vs_bytes[type] += psize;
3736 
3737                 mutex_exit(&vd->vdev_stat_lock);
3738                 return;
3739         }
3740 
3741         if (flags & ZIO_FLAG_SPECULATIVE)
3742                 return;
3743 
3744         /*
3745          * If this is an I/O error that is going to be retried, then ignore the
3746          * error.  Otherwise, the user may interpret B_FAILFAST I/O errors as
3747          * hard errors, when in reality they can happen for any number of
3748          * innocuous reasons (bus resets, MPxIO link failure, etc).
3749          */
3750         if (zio->io_error == EIO &&
3751             !(zio->io_flags & ZIO_FLAG_IO_RETRY))
3752                 return;
3753 
3754         /*
3755          * Intent logs writes won't propagate their error to the root
3756          * I/O so don't mark these types of failures as pool-level
3757          * errors.
3758          */
3759         if (zio->io_vd == NULL && (zio->io_flags & ZIO_FLAG_DONT_PROPAGATE))
3760                 return;
3761 
3762         mutex_enter(&vd->vdev_stat_lock);
3763         if (type == ZIO_TYPE_READ && !vdev_is_dead(vd)) {
3764                 if (zio->io_error == ECKSUM)
3765                         vs->vs_checksum_errors++;
3766                 else
3767                         vs->vs_read_errors++;
3768         }
3769         if (type == ZIO_TYPE_WRITE && !vdev_is_dead(vd))
3770                 vs->vs_write_errors++;
3771         mutex_exit(&vd->vdev_stat_lock);
3772 
3773         if (spa->spa_load_state == SPA_LOAD_NONE &&
3774             type == ZIO_TYPE_WRITE && txg != 0 &&
3775             (!(flags & ZIO_FLAG_IO_REPAIR) ||
3776             (flags & ZIO_FLAG_SCAN_THREAD) ||
3777             spa->spa_claiming)) {
3778                 /*
3779                  * This is either a normal write (not a repair), or it's
3780                  * a repair induced by the scrub thread, or it's a repair
3781                  * made by zil_claim() during spa_load() in the first txg.
3782                  * In the normal case, we commit the DTL change in the same
3783                  * txg as the block was born.  In the scrub-induced repair
3784                  * case, we know that scrubs run in first-pass syncing context,
3785                  * so we commit the DTL change in spa_syncing_txg(spa).
3786                  * In the zil_claim() case, we commit in spa_first_txg(spa).
3787                  *
3788                  * We currently do not make DTL entries for failed spontaneous
3789                  * self-healing writes triggered by normal (non-scrubbing)
3790                  * reads, because we have no transactional context in which to
3791                  * do so -- and it's not clear that it'd be desirable anyway.
3792                  */
3793                 if (vd->vdev_ops->vdev_op_leaf) {
3794                         uint64_t commit_txg = txg;
3795                         if (flags & ZIO_FLAG_SCAN_THREAD) {
3796                                 ASSERT(flags & ZIO_FLAG_IO_REPAIR);
3797                                 ASSERT(spa_sync_pass(spa) == 1);
3798                                 vdev_dtl_dirty(vd, DTL_SCRUB, txg, 1);
3799                                 commit_txg = spa_syncing_txg(spa);
3800                         } else if (spa->spa_claiming) {
3801                                 ASSERT(flags & ZIO_FLAG_IO_REPAIR);
3802                                 commit_txg = spa_first_txg(spa);
3803                         }
3804                         ASSERT(commit_txg >= spa_syncing_txg(spa));
3805                         if (vdev_dtl_contains(vd, DTL_MISSING, txg, 1))
3806                                 return;
3807                         for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
3808                                 vdev_dtl_dirty(pvd, DTL_PARTIAL, txg, 1);
3809                         vdev_dirty(vd->vdev_top, VDD_DTL, vd, commit_txg);
3810                 }
3811                 if (vd != rvd)
3812                         vdev_dtl_dirty(vd, DTL_MISSING, txg, 1);
3813         }
3814 }
3815 
3816 int64_t
3817 vdev_deflated_space(vdev_t *vd, int64_t space)
3818 {
3819         ASSERT((space & (SPA_MINBLOCKSIZE-1)) == 0);
3820         ASSERT(vd->vdev_deflate_ratio != 0 || vd->vdev_isl2cache);
3821 
3822         return ((space >> SPA_MINBLOCKSHIFT) * vd->vdev_deflate_ratio);
3823 }
3824 
3825 /*
3826  * Update the in-core space usage stats for this vdev and the root vdev.
3827  */
3828 void
3829 vdev_space_update(vdev_t *vd, int64_t alloc_delta, int64_t defer_delta,
3830     int64_t space_delta)
3831 {
3832         int64_t dspace_delta;
3833         spa_t *spa = vd->vdev_spa;
3834         vdev_t *rvd = spa->spa_root_vdev;
3835 
3836         ASSERT(vd == vd->vdev_top);
3837 
3838         /*
3839          * Apply the inverse of the psize-to-asize (ie. RAID-Z) space-expansion
3840          * factor.  We must calculate this here and not at the root vdev
3841          * because the root vdev's psize-to-asize is simply the max of its
3842          * childrens', thus not accurate enough for us.
3843          */
3844         dspace_delta = vdev_deflated_space(vd, space_delta);
3845 
3846         mutex_enter(&vd->vdev_stat_lock);
3847         vd->vdev_stat.vs_alloc += alloc_delta;
3848         vd->vdev_stat.vs_space += space_delta;
3849         vd->vdev_stat.vs_dspace += dspace_delta;
3850         mutex_exit(&vd->vdev_stat_lock);
3851 
3852         /* every class but log contributes to root space stats */
3853         if (vd->vdev_mg != NULL && !vd->vdev_islog) {
3854                 mutex_enter(&rvd->vdev_stat_lock);
3855                 rvd->vdev_stat.vs_alloc += alloc_delta;
3856                 rvd->vdev_stat.vs_space += space_delta;
3857                 rvd->vdev_stat.vs_dspace += dspace_delta;
3858                 mutex_exit(&rvd->vdev_stat_lock);
3859         }
3860         /* Note: metaslab_class_space_update moved to metaslab_space_update */
3861 }
3862 
3863 /*
3864  * Mark a top-level vdev's config as dirty, placing it on the dirty list
3865  * so that it will be written out next time the vdev configuration is synced.
3866  * If the root vdev is specified (vdev_top == NULL), dirty all top-level vdevs.
3867  */
3868 void
3869 vdev_config_dirty(vdev_t *vd)
3870 {
3871         spa_t *spa = vd->vdev_spa;
3872         vdev_t *rvd = spa->spa_root_vdev;
3873         int c;
3874 
3875         ASSERT(spa_writeable(spa));
3876 
3877         /*
3878          * If this is an aux vdev (as with l2cache and spare devices), then we
3879          * update the vdev config manually and set the sync flag.
3880          */
3881         if (vd->vdev_aux != NULL) {
3882                 spa_aux_vdev_t *sav = vd->vdev_aux;
3883                 nvlist_t **aux;
3884                 uint_t naux;
3885 
3886                 for (c = 0; c < sav->sav_count; c++) {
3887                         if (sav->sav_vdevs[c] == vd)
3888                                 break;
3889                 }
3890 
3891                 if (c == sav->sav_count) {
3892                         /*
3893                          * We're being removed.  There's nothing more to do.
3894                          */
3895                         ASSERT(sav->sav_sync == B_TRUE);
3896                         return;
3897                 }
3898 
3899                 sav->sav_sync = B_TRUE;
3900 
3901                 if (nvlist_lookup_nvlist_array(sav->sav_config,
3902                     ZPOOL_CONFIG_L2CACHE, &aux, &naux) != 0) {
3903                         VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
3904                             ZPOOL_CONFIG_SPARES, &aux, &naux) == 0);
3905                 }
3906 
3907                 ASSERT(c < naux);
3908 
3909                 /*
3910                  * Setting the nvlist in the middle if the array is a little
3911                  * sketchy, but it will work.
3912                  */
3913                 nvlist_free(aux[c]);
3914                 aux[c] = vdev_config_generate(spa, vd, B_TRUE, 0);
3915 
3916                 return;
3917         }
3918 
3919         /*
3920          * The dirty list is protected by the SCL_CONFIG lock.  The caller
3921          * must either hold SCL_CONFIG as writer, or must be the sync thread
3922          * (which holds SCL_CONFIG as reader).  There's only one sync thread,
3923          * so this is sufficient to ensure mutual exclusion.
3924          */
3925         ASSERT(spa_config_held(spa, SCL_CONFIG, RW_WRITER) ||
3926             (dsl_pool_sync_context(spa_get_dsl(spa)) &&
3927             spa_config_held(spa, SCL_CONFIG, RW_READER)));
3928 
3929         if (vd == rvd) {
3930                 for (c = 0; c < rvd->vdev_children; c++)
3931                         vdev_config_dirty(rvd->vdev_child[c]);
3932         } else {
3933                 ASSERT(vd == vd->vdev_top);
3934 
3935                 if (!list_link_active(&vd->vdev_config_dirty_node) &&
3936                     vdev_is_concrete(vd)) {
3937                         list_insert_head(&spa->spa_config_dirty_list, vd);
3938                 }
3939         }
3940 }
3941 
3942 void
3943 vdev_config_clean(vdev_t *vd)
3944 {
3945         spa_t *spa = vd->vdev_spa;
3946 
3947         ASSERT(spa_config_held(spa, SCL_CONFIG, RW_WRITER) ||
3948             (dsl_pool_sync_context(spa_get_dsl(spa)) &&
3949             spa_config_held(spa, SCL_CONFIG, RW_READER)));
3950 
3951         ASSERT(list_link_active(&vd->vdev_config_dirty_node));
3952         list_remove(&spa->spa_config_dirty_list, vd);
3953 }
3954 
3955 /*
3956  * Mark a top-level vdev's state as dirty, so that the next pass of
3957  * spa_sync() can convert this into vdev_config_dirty().  We distinguish
3958  * the state changes from larger config changes because they require
3959  * much less locking, and are often needed for administrative actions.
3960  */
3961 void
3962 vdev_state_dirty(vdev_t *vd)
3963 {
3964         spa_t *spa = vd->vdev_spa;
3965 
3966         ASSERT(spa_writeable(spa));
3967         ASSERT(vd == vd->vdev_top);
3968 
3969         /*
3970          * The state list is protected by the SCL_STATE lock.  The caller
3971          * must either hold SCL_STATE as writer, or must be the sync thread
3972          * (which holds SCL_STATE as reader).  There's only one sync thread,
3973          * so this is sufficient to ensure mutual exclusion.
3974          */
3975         ASSERT(spa_config_held(spa, SCL_STATE, RW_WRITER) ||
3976             (dsl_pool_sync_context(spa_get_dsl(spa)) &&
3977             spa_config_held(spa, SCL_STATE, RW_READER)));
3978 
3979         if (!list_link_active(&vd->vdev_state_dirty_node) &&
3980             vdev_is_concrete(vd))
3981                 list_insert_head(&spa->spa_state_dirty_list, vd);
3982 }
3983 
3984 void
3985 vdev_state_clean(vdev_t *vd)
3986 {
3987         spa_t *spa = vd->vdev_spa;
3988 
3989         ASSERT(spa_config_held(spa, SCL_STATE, RW_WRITER) ||
3990             (dsl_pool_sync_context(spa_get_dsl(spa)) &&
3991             spa_config_held(spa, SCL_STATE, RW_READER)));
3992 
3993         ASSERT(list_link_active(&vd->vdev_state_dirty_node));
3994         list_remove(&spa->spa_state_dirty_list, vd);
3995 }
3996 
3997 /*
3998  * Propagate vdev state up from children to parent.
3999  */
4000 void
4001 vdev_propagate_state(vdev_t *vd)
4002 {
4003         spa_t *spa = vd->vdev_spa;
4004         vdev_t *rvd = spa->spa_root_vdev;
4005         int degraded = 0, faulted = 0;
4006         int corrupted = 0;
4007         vdev_t *child;
4008 
4009         if (vd->vdev_children > 0) {
4010                 for (int c = 0; c < vd->vdev_children; c++) {
4011                         child = vd->vdev_child[c];
4012 
4013                         /*
4014                          * Don't factor holes or indirect vdevs into the
4015                          * decision.
4016                          */
4017                         if (!vdev_is_concrete(child))
4018                                 continue;
4019 
4020                         if (!vdev_readable(child) ||
4021                             (!vdev_writeable(child) && spa_writeable(spa))) {
4022                                 /*
4023                                  * Root special: if there is a top-level log
4024                                  * device, treat the root vdev as if it were
4025                                  * degraded.
4026                                  */
4027                                 if (child->vdev_islog && vd == rvd)
4028                                         degraded++;
4029                                 else
4030                                         faulted++;
4031                         } else if (child->vdev_state <= VDEV_STATE_DEGRADED) {
4032                                 degraded++;
4033                         }
4034 
4035                         if (child->vdev_stat.vs_aux == VDEV_AUX_CORRUPT_DATA)
4036                                 corrupted++;
4037                 }
4038 
4039                 vd->vdev_ops->vdev_op_state_change(vd, faulted, degraded);
4040 
4041                 /*
4042                  * Root special: if there is a top-level vdev that cannot be
4043                  * opened due to corrupted metadata, then propagate the root
4044                  * vdev's aux state as 'corrupt' rather than 'insufficient
4045                  * replicas'.
4046                  */
4047                 if (corrupted && vd == rvd &&
4048                     rvd->vdev_state == VDEV_STATE_CANT_OPEN)
4049                         vdev_set_state(rvd, B_FALSE, VDEV_STATE_CANT_OPEN,
4050                             VDEV_AUX_CORRUPT_DATA);
4051         }
4052 
4053         if (vd->vdev_parent)
4054                 vdev_propagate_state(vd->vdev_parent);
4055 }
4056 
4057 /*
4058  * Set a vdev's state.  If this is during an open, we don't update the parent
4059  * state, because we're in the process of opening children depth-first.
4060  * Otherwise, we propagate the change to the parent.
4061  *
4062  * If this routine places a device in a faulted state, an appropriate ereport is
4063  * generated.
4064  */
4065 void
4066 vdev_set_state(vdev_t *vd, boolean_t isopen, vdev_state_t state, vdev_aux_t aux)
4067 {
4068         uint64_t save_state;
4069         spa_t *spa = vd->vdev_spa;
4070 
4071         if (state == vd->vdev_state) {
4072                 vd->vdev_stat.vs_aux = aux;
4073                 return;
4074         }
4075 
4076         save_state = vd->vdev_state;
4077 
4078         vd->vdev_state = state;
4079         vd->vdev_stat.vs_aux = aux;
4080 
4081         /*
4082          * If we are setting the vdev state to anything but an open state, then
4083          * always close the underlying device unless the device has requested
4084          * a delayed close (i.e. we're about to remove or fault the device).
4085          * Otherwise, we keep accessible but invalid devices open forever.
4086          * We don't call vdev_close() itself, because that implies some extra
4087          * checks (offline, etc) that we don't want here.  This is limited to
4088          * leaf devices, because otherwise closing the device will affect other
4089          * children.
4090          */
4091         if (!vd->vdev_delayed_close && vdev_is_dead(vd) &&
4092             vd->vdev_ops->vdev_op_leaf)
4093                 vd->vdev_ops->vdev_op_close(vd);
4094 
4095         /*
4096          * If we have brought this vdev back into service, we need
4097          * to notify fmd so that it can gracefully repair any outstanding
4098          * cases due to a missing device.  We do this in all cases, even those
4099          * that probably don't correlate to a repaired fault.  This is sure to
4100          * catch all cases, and we let the zfs-retire agent sort it out.  If
4101          * this is a transient state it's OK, as the retire agent will
4102          * double-check the state of the vdev before repairing it.
4103          */
4104         if (state == VDEV_STATE_HEALTHY && vd->vdev_ops->vdev_op_leaf &&
4105             vd->vdev_prevstate != state)
4106                 zfs_post_state_change(spa, vd);
4107 
4108         if (vd->vdev_removed &&
4109             state == VDEV_STATE_CANT_OPEN &&
4110             (aux == VDEV_AUX_OPEN_FAILED || vd->vdev_checkremove)) {
4111                 /*
4112                  * If the previous state is set to VDEV_STATE_REMOVED, then this
4113                  * device was previously marked removed and someone attempted to
4114                  * reopen it.  If this failed due to a nonexistent device, then
4115                  * keep the device in the REMOVED state.  We also let this be if
4116                  * it is one of our special test online cases, which is only
4117                  * attempting to online the device and shouldn't generate an FMA
4118                  * fault.
4119                  */
4120                 vd->vdev_state = VDEV_STATE_REMOVED;
4121                 vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
4122         } else if (state == VDEV_STATE_REMOVED) {
4123                 vd->vdev_removed = B_TRUE;
4124         } else if (state == VDEV_STATE_CANT_OPEN) {
4125                 /*
4126                  * If we fail to open a vdev during an import or recovery, we
4127                  * mark it as "not available", which signifies that it was
4128                  * never there to begin with.  Failure to open such a device
4129                  * is not considered an error.
4130                  */
4131                 if ((spa_load_state(spa) == SPA_LOAD_IMPORT ||
4132                     spa_load_state(spa) == SPA_LOAD_RECOVER) &&
4133                     vd->vdev_ops->vdev_op_leaf)
4134                         vd->vdev_not_present = 1;
4135 
4136                 /*
4137                  * Post the appropriate ereport.  If the 'prevstate' field is
4138                  * set to something other than VDEV_STATE_UNKNOWN, it indicates
4139                  * that this is part of a vdev_reopen().  In this case, we don't
4140                  * want to post the ereport if the device was already in the
4141                  * CANT_OPEN state beforehand.
4142                  *
4143                  * If the 'checkremove' flag is set, then this is an attempt to
4144                  * online the device in response to an insertion event.  If we
4145                  * hit this case, then we have detected an insertion event for a
4146                  * faulted or offline device that wasn't in the removed state.
4147                  * In this scenario, we don't post an ereport because we are
4148                  * about to replace the device, or attempt an online with
4149                  * vdev_forcefault, which will generate the fault for us.
4150                  */
4151                 if ((vd->vdev_prevstate != state || vd->vdev_forcefault) &&
4152                     !vd->vdev_not_present && !vd->vdev_checkremove &&
4153                     vd != spa->spa_root_vdev) {
4154                         const char *class;
4155 
4156                         switch (aux) {
4157                         case VDEV_AUX_OPEN_FAILED:
4158                                 class = FM_EREPORT_ZFS_DEVICE_OPEN_FAILED;
4159                                 break;
4160                         case VDEV_AUX_CORRUPT_DATA:
4161                                 class = FM_EREPORT_ZFS_DEVICE_CORRUPT_DATA;
4162                                 break;
4163                         case VDEV_AUX_NO_REPLICAS:
4164                                 class = FM_EREPORT_ZFS_DEVICE_NO_REPLICAS;
4165                                 break;
4166                         case VDEV_AUX_BAD_GUID_SUM:
4167                                 class = FM_EREPORT_ZFS_DEVICE_BAD_GUID_SUM;
4168                                 break;
4169                         case VDEV_AUX_TOO_SMALL:
4170                                 class = FM_EREPORT_ZFS_DEVICE_TOO_SMALL;
4171                                 break;
4172                         case VDEV_AUX_BAD_LABEL:
4173                                 class = FM_EREPORT_ZFS_DEVICE_BAD_LABEL;
4174                                 break;
4175                         default:
4176                                 class = FM_EREPORT_ZFS_DEVICE_UNKNOWN;
4177                         }
4178 
4179                         zfs_ereport_post(class, spa, vd, NULL, save_state, 0);
4180                 }
4181 
4182                 /* Erase any notion of persistent removed state */
4183                 vd->vdev_removed = B_FALSE;
4184         } else {
4185                 vd->vdev_removed = B_FALSE;
4186         }
4187 
4188         if (!isopen && vd->vdev_parent)
4189                 vdev_propagate_state(vd->vdev_parent);
4190 }
4191 
4192 boolean_t
4193 vdev_children_are_offline(vdev_t *vd)
4194 {
4195         ASSERT(!vd->vdev_ops->vdev_op_leaf);
4196 
4197         for (uint64_t i = 0; i < vd->vdev_children; i++) {
4198                 if (vd->vdev_child[i]->vdev_state != VDEV_STATE_OFFLINE)
4199                         return (B_FALSE);
4200         }
4201 
4202         return (B_TRUE);
4203 }
4204 
4205 /*
4206  * Check the vdev configuration to ensure that it's capable of supporting
4207  * a root pool. We do not support partial configuration.
4208  * In addition, only a single top-level vdev is allowed.
4209  */
4210 boolean_t
4211 vdev_is_bootable(vdev_t *vd)
4212 {
4213         if (!vd->vdev_ops->vdev_op_leaf) {
4214                 char *vdev_type = vd->vdev_ops->vdev_op_type;
4215 
4216                 if (strcmp(vdev_type, VDEV_TYPE_ROOT) == 0 &&
4217                     vd->vdev_children > 1) {
4218                         return (B_FALSE);
4219                 } else if (strcmp(vdev_type, VDEV_TYPE_MISSING) == 0 ||
4220                     strcmp(vdev_type, VDEV_TYPE_INDIRECT) == 0) {
4221                         return (B_FALSE);
4222                 }
4223         }
4224 
4225         for (int c = 0; c < vd->vdev_children; c++) {
4226                 if (!vdev_is_bootable(vd->vdev_child[c]))
4227                         return (B_FALSE);
4228         }
4229         return (B_TRUE);
4230 }
4231 
4232 boolean_t
4233 vdev_is_concrete(vdev_t *vd)
4234 {
4235         vdev_ops_t *ops = vd->vdev_ops;
4236         if (ops == &vdev_indirect_ops || ops == &vdev_hole_ops ||
4237             ops == &vdev_missing_ops || ops == &vdev_root_ops) {
4238                 return (B_FALSE);
4239         } else {
4240                 return (B_TRUE);
4241         }
4242 }
4243 
4244 /*
4245  * Determine if a log device has valid content.  If the vdev was
4246  * removed or faulted in the MOS config then we know that
4247  * the content on the log device has already been written to the pool.
4248  */
4249 boolean_t
4250 vdev_log_state_valid(vdev_t *vd)
4251 {
4252         if (vd->vdev_ops->vdev_op_leaf && !vd->vdev_faulted &&
4253             !vd->vdev_removed)
4254                 return (B_TRUE);
4255 
4256         for (int c = 0; c < vd->vdev_children; c++)
4257                 if (vdev_log_state_valid(vd->vdev_child[c]))
4258                         return (B_TRUE);
4259 
4260         return (B_FALSE);
4261 }
4262 
4263 /*
4264  * Expand a vdev if possible.
4265  */
4266 void
4267 vdev_expand(vdev_t *vd, uint64_t txg)
4268 {
4269         ASSERT(vd->vdev_top == vd);
4270         ASSERT(spa_config_held(vd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4271         ASSERT(vdev_is_concrete(vd));
4272 
4273         vdev_set_deflate_ratio(vd);
4274 
4275         if ((vd->vdev_asize >> vd->vdev_ms_shift) > vd->vdev_ms_count &&
4276             vdev_is_concrete(vd)) {
4277                 vdev_metaslab_group_create(vd);
4278                 VERIFY(vdev_metaslab_init(vd, txg) == 0);
4279                 vdev_config_dirty(vd);
4280         }
4281 }
4282 
4283 /*
4284  * Split a vdev.
4285  */
4286 void
4287 vdev_split(vdev_t *vd)
4288 {
4289         vdev_t *cvd, *pvd = vd->vdev_parent;
4290 
4291         vdev_remove_child(pvd, vd);
4292         vdev_compact_children(pvd);
4293 
4294         cvd = pvd->vdev_child[0];
4295         if (pvd->vdev_children == 1) {
4296                 vdev_remove_parent(cvd);
4297                 cvd->vdev_splitting = B_TRUE;
4298         }
4299         vdev_propagate_state(cvd);
4300 }
4301 
4302 void
4303 vdev_deadman(vdev_t *vd)
4304 {
4305         for (int c = 0; c < vd->vdev_children; c++) {
4306                 vdev_t *cvd = vd->vdev_child[c];
4307 
4308                 vdev_deadman(cvd);
4309         }
4310 
4311         if (vd->vdev_ops->vdev_op_leaf) {
4312                 vdev_queue_t *vq = &vd->vdev_queue;
4313 
4314                 mutex_enter(&vq->vq_lock);
4315                 if (avl_numnodes(&vq->vq_active_tree) > 0) {
4316                         spa_t *spa = vd->vdev_spa;
4317                         zio_t *fio;
4318                         uint64_t delta;
4319 
4320                         /*
4321                          * Look at the head of all the pending queues,
4322                          * if any I/O has been outstanding for longer than
4323                          * the spa_deadman_synctime we panic the system.
4324                          */
4325                         fio = avl_first(&vq->vq_active_tree);
4326                         delta = gethrtime() - fio->io_timestamp;
4327                         if (delta > spa_deadman_synctime(spa)) {
4328                                 vdev_dbgmsg(vd, "SLOW IO: zio timestamp "
4329                                     "%lluns, delta %lluns, last io %lluns",
4330                                     fio->io_timestamp, (u_longlong_t)delta,
4331                                     vq->vq_io_complete_ts);
4332                                 fm_panic("I/O to pool '%s' appears to be "
4333                                     "hung.", spa_name(spa));
4334                         }
4335                 }
4336                 mutex_exit(&vq->vq_lock);
4337         }
4338 }