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, 2015 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  */
  30 
  31 #include <sys/zfs_context.h>
  32 #include <sys/fm/fs/zfs.h>
  33 #include <sys/spa.h>
  34 #include <sys/spa_impl.h>
  35 #include <sys/dmu.h>
  36 #include <sys/dmu_tx.h>
  37 #include <sys/vdev_impl.h>
  38 #include <sys/uberblock_impl.h>
  39 #include <sys/metaslab.h>
  40 #include <sys/metaslab_impl.h>
  41 #include <sys/space_map.h>
  42 #include <sys/space_reftree.h>
  43 #include <sys/zio.h>
  44 #include <sys/zap.h>
  45 #include <sys/fs/zfs.h>
  46 #include <sys/arc.h>
  47 #include <sys/zil.h>
  48 #include <sys/dsl_scan.h>
  49 #include <sys/abd.h>
  50 
  51 /*
  52  * Virtual device management.
  53  */
  54 
  55 static vdev_ops_t *vdev_ops_table[] = {
  56         &vdev_root_ops,
  57         &vdev_raidz_ops,
  58         &vdev_mirror_ops,
  59         &vdev_replacing_ops,
  60         &vdev_spare_ops,
  61         &vdev_disk_ops,
  62         &vdev_file_ops,
  63         &vdev_missing_ops,
  64         &vdev_hole_ops,
  65         NULL
  66 };
  67 
  68 /* maximum scrub/resilver I/O queue per leaf vdev */
  69 int zfs_scrub_limit = 10;
  70 
  71 /*
  72  * When a vdev is added, it will be divided into approximately (but no
  73  * more than) this number of metaslabs.
  74  */
  75 int metaslabs_per_vdev = 200;
  76 
  77 /*
  78  * Given a vdev type, return the appropriate ops vector.
  79  */
  80 static vdev_ops_t *
  81 vdev_getops(const char *type)
  82 {
  83         vdev_ops_t *ops, **opspp;
  84 
  85         for (opspp = vdev_ops_table; (ops = *opspp) != NULL; opspp++)
  86                 if (strcmp(ops->vdev_op_type, type) == 0)
  87                         break;
  88 
  89         return (ops);
  90 }
  91 
  92 /*
  93  * Default asize function: return the MAX of psize with the asize of
  94  * all children.  This is what's used by anything other than RAID-Z.
  95  */
  96 uint64_t
  97 vdev_default_asize(vdev_t *vd, uint64_t psize)
  98 {
  99         uint64_t asize = P2ROUNDUP(psize, 1ULL << vd->vdev_top->vdev_ashift);
 100         uint64_t csize;
 101 
 102         for (int c = 0; c < vd->vdev_children; c++) {
 103                 csize = vdev_psize_to_asize(vd->vdev_child[c], psize);
 104                 asize = MAX(asize, csize);
 105         }
 106 
 107         return (asize);
 108 }
 109 
 110 /*
 111  * Get the minimum allocatable size. We define the allocatable size as
 112  * the vdev's asize rounded to the nearest metaslab. This allows us to
 113  * replace or attach devices which don't have the same physical size but
 114  * can still satisfy the same number of allocations.
 115  */
 116 uint64_t
 117 vdev_get_min_asize(vdev_t *vd)
 118 {
 119         vdev_t *pvd = vd->vdev_parent;
 120 
 121         /*
 122          * If our parent is NULL (inactive spare or cache) or is the root,
 123          * just return our own asize.
 124          */
 125         if (pvd == NULL)
 126                 return (vd->vdev_asize);
 127 
 128         /*
 129          * The top-level vdev just returns the allocatable size rounded
 130          * to the nearest metaslab.
 131          */
 132         if (vd == vd->vdev_top)
 133                 return (P2ALIGN(vd->vdev_asize, 1ULL << vd->vdev_ms_shift));
 134 
 135         /*
 136          * The allocatable space for a raidz vdev is N * sizeof(smallest child),
 137          * so each child must provide at least 1/Nth of its asize.
 138          */
 139         if (pvd->vdev_ops == &vdev_raidz_ops)
 140                 return ((pvd->vdev_min_asize + pvd->vdev_children - 1) /
 141                     pvd->vdev_children);
 142 
 143         return (pvd->vdev_min_asize);
 144 }
 145 
 146 void
 147 vdev_set_min_asize(vdev_t *vd)
 148 {
 149         vd->vdev_min_asize = vdev_get_min_asize(vd);
 150 
 151         for (int c = 0; c < vd->vdev_children; c++)
 152                 vdev_set_min_asize(vd->vdev_child[c]);
 153 }
 154 
 155 vdev_t *
 156 vdev_lookup_top(spa_t *spa, uint64_t vdev)
 157 {
 158         vdev_t *rvd = spa->spa_root_vdev;
 159 
 160         ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
 161 
 162         if (vdev < rvd->vdev_children) {
 163                 ASSERT(rvd->vdev_child[vdev] != NULL);
 164                 return (rvd->vdev_child[vdev]);
 165         }
 166 
 167         return (NULL);
 168 }
 169 
 170 vdev_t *
 171 vdev_lookup_by_guid(vdev_t *vd, uint64_t guid)
 172 {
 173         vdev_t *mvd;
 174 
 175         if (vd->vdev_guid == guid)
 176                 return (vd);
 177 
 178         for (int c = 0; c < vd->vdev_children; c++)
 179                 if ((mvd = vdev_lookup_by_guid(vd->vdev_child[c], guid)) !=
 180                     NULL)
 181                         return (mvd);
 182 
 183         return (NULL);
 184 }
 185 
 186 static int
 187 vdev_count_leaves_impl(vdev_t *vd)
 188 {
 189         int n = 0;
 190 
 191         if (vd->vdev_ops->vdev_op_leaf)
 192                 return (1);
 193 
 194         for (int c = 0; c < vd->vdev_children; c++)
 195                 n += vdev_count_leaves_impl(vd->vdev_child[c]);
 196 
 197         return (n);
 198 }
 199 
 200 int
 201 vdev_count_leaves(spa_t *spa)
 202 {
 203         return (vdev_count_leaves_impl(spa->spa_root_vdev));
 204 }
 205 
 206 void
 207 vdev_add_child(vdev_t *pvd, vdev_t *cvd)
 208 {
 209         size_t oldsize, newsize;
 210         uint64_t id = cvd->vdev_id;
 211         vdev_t **newchild;
 212         spa_t *spa = cvd->vdev_spa;
 213 
 214         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
 215         ASSERT(cvd->vdev_parent == NULL);
 216 
 217         cvd->vdev_parent = pvd;
 218 
 219         if (pvd == NULL)
 220                 return;
 221 
 222         ASSERT(id >= pvd->vdev_children || pvd->vdev_child[id] == NULL);
 223 
 224         oldsize = pvd->vdev_children * sizeof (vdev_t *);
 225         pvd->vdev_children = MAX(pvd->vdev_children, id + 1);
 226         newsize = pvd->vdev_children * sizeof (vdev_t *);
 227 
 228         newchild = kmem_zalloc(newsize, KM_SLEEP);
 229         if (pvd->vdev_child != NULL) {
 230                 bcopy(pvd->vdev_child, newchild, oldsize);
 231                 kmem_free(pvd->vdev_child, oldsize);
 232         }
 233 
 234         pvd->vdev_child = newchild;
 235         pvd->vdev_child[id] = cvd;
 236 
 237         cvd->vdev_top = (pvd->vdev_top ? pvd->vdev_top: cvd);
 238         ASSERT(cvd->vdev_top->vdev_parent->vdev_parent == NULL);
 239 
 240         /*
 241          * Walk up all ancestors to update guid sum.
 242          */
 243         for (; pvd != NULL; pvd = pvd->vdev_parent)
 244                 pvd->vdev_guid_sum += cvd->vdev_guid_sum;
 245 }
 246 
 247 void
 248 vdev_remove_child(vdev_t *pvd, vdev_t *cvd)
 249 {
 250         int c;
 251         uint_t id = cvd->vdev_id;
 252 
 253         ASSERT(cvd->vdev_parent == pvd);
 254 
 255         if (pvd == NULL)
 256                 return;
 257 
 258         ASSERT(id < pvd->vdev_children);
 259         ASSERT(pvd->vdev_child[id] == cvd);
 260 
 261         pvd->vdev_child[id] = NULL;
 262         cvd->vdev_parent = NULL;
 263 
 264         for (c = 0; c < pvd->vdev_children; c++)
 265                 if (pvd->vdev_child[c])
 266                         break;
 267 
 268         if (c == pvd->vdev_children) {
 269                 kmem_free(pvd->vdev_child, c * sizeof (vdev_t *));
 270                 pvd->vdev_child = NULL;
 271                 pvd->vdev_children = 0;
 272         }
 273 
 274         /*
 275          * Walk up all ancestors to update guid sum.
 276          */
 277         for (; pvd != NULL; pvd = pvd->vdev_parent)
 278                 pvd->vdev_guid_sum -= cvd->vdev_guid_sum;
 279 }
 280 
 281 /*
 282  * Remove any holes in the child array.
 283  */
 284 void
 285 vdev_compact_children(vdev_t *pvd)
 286 {
 287         vdev_t **newchild, *cvd;
 288         int oldc = pvd->vdev_children;
 289         int newc;
 290 
 291         ASSERT(spa_config_held(pvd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
 292 
 293         for (int c = newc = 0; c < oldc; c++)
 294                 if (pvd->vdev_child[c])
 295                         newc++;
 296 
 297         newchild = kmem_alloc(newc * sizeof (vdev_t *), KM_SLEEP);
 298 
 299         for (int c = newc = 0; c < oldc; c++) {
 300                 if ((cvd = pvd->vdev_child[c]) != NULL) {
 301                         newchild[newc] = cvd;
 302                         cvd->vdev_id = newc++;
 303                 }
 304         }
 305 
 306         kmem_free(pvd->vdev_child, oldc * sizeof (vdev_t *));
 307         pvd->vdev_child = newchild;
 308         pvd->vdev_children = newc;
 309 }
 310 
 311 /*
 312  * Allocate and minimally initialize a vdev_t.
 313  */
 314 vdev_t *
 315 vdev_alloc_common(spa_t *spa, uint_t id, uint64_t guid, vdev_ops_t *ops)
 316 {
 317         vdev_t *vd;
 318 
 319         vd = kmem_zalloc(sizeof (vdev_t), KM_SLEEP);
 320 
 321         if (spa->spa_root_vdev == NULL) {
 322                 ASSERT(ops == &vdev_root_ops);
 323                 spa->spa_root_vdev = vd;
 324                 spa->spa_load_guid = spa_generate_guid(NULL);
 325         }
 326 
 327         if (guid == 0 && ops != &vdev_hole_ops) {
 328                 if (spa->spa_root_vdev == vd) {
 329                         /*
 330                          * The root vdev's guid will also be the pool guid,
 331                          * which must be unique among all pools.
 332                          */
 333                         guid = spa_generate_guid(NULL);
 334                 } else {
 335                         /*
 336                          * Any other vdev's guid must be unique within the pool.
 337                          */
 338                         guid = spa_generate_guid(spa);
 339                 }
 340                 ASSERT(!spa_guid_exists(spa_guid(spa), guid));
 341         }
 342 
 343         vd->vdev_spa = spa;
 344         vd->vdev_id = id;
 345         vd->vdev_guid = guid;
 346         vd->vdev_guid_sum = guid;
 347         vd->vdev_ops = ops;
 348         vd->vdev_state = VDEV_STATE_CLOSED;
 349         vd->vdev_ishole = (ops == &vdev_hole_ops);
 350 
 351         mutex_init(&vd->vdev_dtl_lock, NULL, MUTEX_DEFAULT, NULL);
 352         mutex_init(&vd->vdev_stat_lock, NULL, MUTEX_DEFAULT, NULL);
 353         mutex_init(&vd->vdev_probe_lock, NULL, MUTEX_DEFAULT, NULL);
 354         mutex_init(&vd->vdev_queue_lock, NULL, MUTEX_DEFAULT, NULL);
 355         for (int t = 0; t < DTL_TYPES; t++) {
 356                 vd->vdev_dtl[t] = range_tree_create(NULL, NULL,
 357                     &vd->vdev_dtl_lock);
 358         }
 359         txg_list_create(&vd->vdev_ms_list, spa,
 360             offsetof(struct metaslab, ms_txg_node));
 361         txg_list_create(&vd->vdev_dtl_list, spa,
 362             offsetof(struct vdev, vdev_dtl_node));
 363         vd->vdev_stat.vs_timestamp = gethrtime();
 364         vdev_queue_init(vd);
 365         vdev_cache_init(vd);
 366 
 367         return (vd);
 368 }
 369 
 370 /*
 371  * Allocate a new vdev.  The 'alloctype' is used to control whether we are
 372  * creating a new vdev or loading an existing one - the behavior is slightly
 373  * different for each case.
 374  */
 375 int
 376 vdev_alloc(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent, uint_t id,
 377     int alloctype)
 378 {
 379         vdev_ops_t *ops;
 380         char *type;
 381         uint64_t guid = 0, islog, nparity;
 382         vdev_t *vd;
 383 
 384         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
 385 
 386         if (nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) != 0)
 387                 return (SET_ERROR(EINVAL));
 388 
 389         if ((ops = vdev_getops(type)) == NULL)
 390                 return (SET_ERROR(EINVAL));
 391 
 392         /*
 393          * If this is a load, get the vdev guid from the nvlist.
 394          * Otherwise, vdev_alloc_common() will generate one for us.
 395          */
 396         if (alloctype == VDEV_ALLOC_LOAD) {
 397                 uint64_t label_id;
 398 
 399                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ID, &label_id) ||
 400                     label_id != id)
 401                         return (SET_ERROR(EINVAL));
 402 
 403                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
 404                         return (SET_ERROR(EINVAL));
 405         } else if (alloctype == VDEV_ALLOC_SPARE) {
 406                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
 407                         return (SET_ERROR(EINVAL));
 408         } else if (alloctype == VDEV_ALLOC_L2CACHE) {
 409                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
 410                         return (SET_ERROR(EINVAL));
 411         } else if (alloctype == VDEV_ALLOC_ROOTPOOL) {
 412                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
 413                         return (SET_ERROR(EINVAL));
 414         }
 415 
 416         /*
 417          * The first allocated vdev must be of type 'root'.
 418          */
 419         if (ops != &vdev_root_ops && spa->spa_root_vdev == NULL)
 420                 return (SET_ERROR(EINVAL));
 421 
 422         /*
 423          * Determine whether we're a log vdev.
 424          */
 425         islog = 0;
 426         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_LOG, &islog);
 427         if (islog && spa_version(spa) < SPA_VERSION_SLOGS)
 428                 return (SET_ERROR(ENOTSUP));
 429 
 430         if (ops == &vdev_hole_ops && spa_version(spa) < SPA_VERSION_HOLES)
 431                 return (SET_ERROR(ENOTSUP));
 432 
 433         /*
 434          * Set the nparity property for RAID-Z vdevs.
 435          */
 436         nparity = -1ULL;
 437         if (ops == &vdev_raidz_ops) {
 438                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NPARITY,
 439                     &nparity) == 0) {
 440                         if (nparity == 0 || nparity > VDEV_RAIDZ_MAXPARITY)
 441                                 return (SET_ERROR(EINVAL));
 442                         /*
 443                          * Previous versions could only support 1 or 2 parity
 444                          * device.
 445                          */
 446                         if (nparity > 1 &&
 447                             spa_version(spa) < SPA_VERSION_RAIDZ2)
 448                                 return (SET_ERROR(ENOTSUP));
 449                         if (nparity > 2 &&
 450                             spa_version(spa) < SPA_VERSION_RAIDZ3)
 451                                 return (SET_ERROR(ENOTSUP));
 452                 } else {
 453                         /*
 454                          * We require the parity to be specified for SPAs that
 455                          * support multiple parity levels.
 456                          */
 457                         if (spa_version(spa) >= SPA_VERSION_RAIDZ2)
 458                                 return (SET_ERROR(EINVAL));
 459                         /*
 460                          * Otherwise, we default to 1 parity device for RAID-Z.
 461                          */
 462                         nparity = 1;
 463                 }
 464         } else {
 465                 nparity = 0;
 466         }
 467         ASSERT(nparity != -1ULL);
 468 
 469         vd = vdev_alloc_common(spa, id, guid, ops);
 470 
 471         vd->vdev_islog = islog;
 472         vd->vdev_nparity = nparity;
 473 
 474         if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &vd->vdev_path) == 0)
 475                 vd->vdev_path = spa_strdup(vd->vdev_path);
 476         if (nvlist_lookup_string(nv, ZPOOL_CONFIG_DEVID, &vd->vdev_devid) == 0)
 477                 vd->vdev_devid = spa_strdup(vd->vdev_devid);
 478         if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PHYS_PATH,
 479             &vd->vdev_physpath) == 0)
 480                 vd->vdev_physpath = spa_strdup(vd->vdev_physpath);
 481         if (nvlist_lookup_string(nv, ZPOOL_CONFIG_FRU, &vd->vdev_fru) == 0)
 482                 vd->vdev_fru = spa_strdup(vd->vdev_fru);
 483 
 484         /*
 485          * Set the whole_disk property.  If it's not specified, leave the value
 486          * as -1.
 487          */
 488         if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
 489             &vd->vdev_wholedisk) != 0)
 490                 vd->vdev_wholedisk = -1ULL;
 491 
 492         /*
 493          * Look for the 'not present' flag.  This will only be set if the device
 494          * was not present at the time of import.
 495          */
 496         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
 497             &vd->vdev_not_present);
 498 
 499         /*
 500          * Get the alignment requirement.
 501          */
 502         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ASHIFT, &vd->vdev_ashift);
 503 
 504         /*
 505          * Retrieve the vdev creation time.
 506          */
 507         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_CREATE_TXG,
 508             &vd->vdev_crtxg);
 509 
 510         /*
 511          * If we're a top-level vdev, try to load the allocation parameters.
 512          */
 513         if (parent && !parent->vdev_parent &&
 514             (alloctype == VDEV_ALLOC_LOAD || alloctype == VDEV_ALLOC_SPLIT)) {
 515                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_METASLAB_ARRAY,
 516                     &vd->vdev_ms_array);
 517                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_METASLAB_SHIFT,
 518                     &vd->vdev_ms_shift);
 519                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ASIZE,
 520                     &vd->vdev_asize);
 521                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVING,
 522                     &vd->vdev_removing);
 523                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_VDEV_TOP_ZAP,
 524                     &vd->vdev_top_zap);
 525         } else {
 526                 ASSERT0(vd->vdev_top_zap);
 527         }
 528 
 529         if (parent && !parent->vdev_parent && alloctype != VDEV_ALLOC_ATTACH) {
 530                 ASSERT(alloctype == VDEV_ALLOC_LOAD ||
 531                     alloctype == VDEV_ALLOC_ADD ||
 532                     alloctype == VDEV_ALLOC_SPLIT ||
 533                     alloctype == VDEV_ALLOC_ROOTPOOL);
 534                 vd->vdev_mg = metaslab_group_create(islog ?
 535                     spa_log_class(spa) : spa_normal_class(spa), vd);
 536         }
 537 
 538         if (vd->vdev_ops->vdev_op_leaf &&
 539             (alloctype == VDEV_ALLOC_LOAD || alloctype == VDEV_ALLOC_SPLIT)) {
 540                 (void) nvlist_lookup_uint64(nv,
 541                     ZPOOL_CONFIG_VDEV_LEAF_ZAP, &vd->vdev_leaf_zap);
 542         } else {
 543                 ASSERT0(vd->vdev_leaf_zap);
 544         }
 545 
 546         /*
 547          * If we're a leaf vdev, try to load the DTL object and other state.
 548          */
 549 
 550         if (vd->vdev_ops->vdev_op_leaf &&
 551             (alloctype == VDEV_ALLOC_LOAD || alloctype == VDEV_ALLOC_L2CACHE ||
 552             alloctype == VDEV_ALLOC_ROOTPOOL)) {
 553                 if (alloctype == VDEV_ALLOC_LOAD) {
 554                         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_DTL,
 555                             &vd->vdev_dtl_object);
 556                         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_UNSPARE,
 557                             &vd->vdev_unspare);
 558                 }
 559 
 560                 if (alloctype == VDEV_ALLOC_ROOTPOOL) {
 561                         uint64_t spare = 0;
 562 
 563                         if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_SPARE,
 564                             &spare) == 0 && spare)
 565                                 spa_spare_add(vd);
 566                 }
 567 
 568                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_OFFLINE,
 569                     &vd->vdev_offline);
 570 
 571                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_RESILVER_TXG,
 572                     &vd->vdev_resilver_txg);
 573 
 574                 /*
 575                  * When importing a pool, we want to ignore the persistent fault
 576                  * state, as the diagnosis made on another system may not be
 577                  * valid in the current context.  Local vdevs will
 578                  * remain in the faulted state.
 579                  */
 580                 if (spa_load_state(spa) == SPA_LOAD_OPEN) {
 581                         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_FAULTED,
 582                             &vd->vdev_faulted);
 583                         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_DEGRADED,
 584                             &vd->vdev_degraded);
 585                         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVED,
 586                             &vd->vdev_removed);
 587 
 588                         if (vd->vdev_faulted || vd->vdev_degraded) {
 589                                 char *aux;
 590 
 591                                 vd->vdev_label_aux =
 592                                     VDEV_AUX_ERR_EXCEEDED;
 593                                 if (nvlist_lookup_string(nv,
 594                                     ZPOOL_CONFIG_AUX_STATE, &aux) == 0 &&
 595                                     strcmp(aux, "external") == 0)
 596                                         vd->vdev_label_aux = VDEV_AUX_EXTERNAL;
 597                         }
 598                 }
 599         }
 600 
 601         /*
 602          * Add ourselves to the parent's list of children.
 603          */
 604         vdev_add_child(parent, vd);
 605 
 606         *vdp = vd;
 607 
 608         return (0);
 609 }
 610 
 611 void
 612 vdev_free(vdev_t *vd)
 613 {
 614         spa_t *spa = vd->vdev_spa;
 615 
 616         /*
 617          * vdev_free() implies closing the vdev first.  This is simpler than
 618          * trying to ensure complicated semantics for all callers.
 619          */
 620         vdev_close(vd);
 621 
 622         ASSERT(!list_link_active(&vd->vdev_config_dirty_node));
 623         ASSERT(!list_link_active(&vd->vdev_state_dirty_node));
 624 
 625         /*
 626          * Free all children.
 627          */
 628         for (int c = 0; c < vd->vdev_children; c++)
 629                 vdev_free(vd->vdev_child[c]);
 630 
 631         ASSERT(vd->vdev_child == NULL);
 632         ASSERT(vd->vdev_guid_sum == vd->vdev_guid);
 633 
 634         /*
 635          * Discard allocation state.
 636          */
 637         if (vd->vdev_mg != NULL) {
 638                 vdev_metaslab_fini(vd);
 639                 metaslab_group_destroy(vd->vdev_mg);
 640         }
 641 
 642         ASSERT0(vd->vdev_stat.vs_space);
 643         ASSERT0(vd->vdev_stat.vs_dspace);
 644         ASSERT0(vd->vdev_stat.vs_alloc);
 645 
 646         /*
 647          * Remove this vdev from its parent's child list.
 648          */
 649         vdev_remove_child(vd->vdev_parent, vd);
 650 
 651         ASSERT(vd->vdev_parent == NULL);
 652 
 653         /*
 654          * Clean up vdev structure.
 655          */
 656         vdev_queue_fini(vd);
 657         vdev_cache_fini(vd);
 658 
 659         if (vd->vdev_path)
 660                 spa_strfree(vd->vdev_path);
 661         if (vd->vdev_devid)
 662                 spa_strfree(vd->vdev_devid);
 663         if (vd->vdev_physpath)
 664                 spa_strfree(vd->vdev_physpath);
 665         if (vd->vdev_fru)
 666                 spa_strfree(vd->vdev_fru);
 667 
 668         if (vd->vdev_isspare)
 669                 spa_spare_remove(vd);
 670         if (vd->vdev_isl2cache)
 671                 spa_l2cache_remove(vd);
 672 
 673         txg_list_destroy(&vd->vdev_ms_list);
 674         txg_list_destroy(&vd->vdev_dtl_list);
 675 
 676         mutex_enter(&vd->vdev_dtl_lock);
 677         space_map_close(vd->vdev_dtl_sm);
 678         for (int t = 0; t < DTL_TYPES; t++) {
 679                 range_tree_vacate(vd->vdev_dtl[t], NULL, NULL);
 680                 range_tree_destroy(vd->vdev_dtl[t]);
 681         }
 682         mutex_exit(&vd->vdev_dtl_lock);
 683 
 684         mutex_destroy(&vd->vdev_queue_lock);
 685         mutex_destroy(&vd->vdev_dtl_lock);
 686         mutex_destroy(&vd->vdev_stat_lock);
 687         mutex_destroy(&vd->vdev_probe_lock);
 688 
 689         if (vd == spa->spa_root_vdev)
 690                 spa->spa_root_vdev = NULL;
 691 
 692         kmem_free(vd, sizeof (vdev_t));
 693 }
 694 
 695 /*
 696  * Transfer top-level vdev state from svd to tvd.
 697  */
 698 static void
 699 vdev_top_transfer(vdev_t *svd, vdev_t *tvd)
 700 {
 701         spa_t *spa = svd->vdev_spa;
 702         metaslab_t *msp;
 703         vdev_t *vd;
 704         int t;
 705 
 706         ASSERT(tvd == tvd->vdev_top);
 707 
 708         tvd->vdev_ms_array = svd->vdev_ms_array;
 709         tvd->vdev_ms_shift = svd->vdev_ms_shift;
 710         tvd->vdev_ms_count = svd->vdev_ms_count;
 711         tvd->vdev_top_zap = svd->vdev_top_zap;
 712 
 713         svd->vdev_ms_array = 0;
 714         svd->vdev_ms_shift = 0;
 715         svd->vdev_ms_count = 0;
 716         svd->vdev_top_zap = 0;
 717 
 718         if (tvd->vdev_mg)
 719                 ASSERT3P(tvd->vdev_mg, ==, svd->vdev_mg);
 720         tvd->vdev_mg = svd->vdev_mg;
 721         tvd->vdev_ms = svd->vdev_ms;
 722 
 723         svd->vdev_mg = NULL;
 724         svd->vdev_ms = NULL;
 725 
 726         if (tvd->vdev_mg != NULL)
 727                 tvd->vdev_mg->mg_vd = tvd;
 728 
 729         tvd->vdev_stat.vs_alloc = svd->vdev_stat.vs_alloc;
 730         tvd->vdev_stat.vs_space = svd->vdev_stat.vs_space;
 731         tvd->vdev_stat.vs_dspace = svd->vdev_stat.vs_dspace;
 732 
 733         svd->vdev_stat.vs_alloc = 0;
 734         svd->vdev_stat.vs_space = 0;
 735         svd->vdev_stat.vs_dspace = 0;
 736 
 737         for (t = 0; t < TXG_SIZE; t++) {
 738                 while ((msp = txg_list_remove(&svd->vdev_ms_list, t)) != NULL)
 739                         (void) txg_list_add(&tvd->vdev_ms_list, msp, t);
 740                 while ((vd = txg_list_remove(&svd->vdev_dtl_list, t)) != NULL)
 741                         (void) txg_list_add(&tvd->vdev_dtl_list, vd, t);
 742                 if (txg_list_remove_this(&spa->spa_vdev_txg_list, svd, t))
 743                         (void) txg_list_add(&spa->spa_vdev_txg_list, tvd, t);
 744         }
 745 
 746         if (list_link_active(&svd->vdev_config_dirty_node)) {
 747                 vdev_config_clean(svd);
 748                 vdev_config_dirty(tvd);
 749         }
 750 
 751         if (list_link_active(&svd->vdev_state_dirty_node)) {
 752                 vdev_state_clean(svd);
 753                 vdev_state_dirty(tvd);
 754         }
 755 
 756         tvd->vdev_deflate_ratio = svd->vdev_deflate_ratio;
 757         svd->vdev_deflate_ratio = 0;
 758 
 759         tvd->vdev_islog = svd->vdev_islog;
 760         svd->vdev_islog = 0;
 761 }
 762 
 763 static void
 764 vdev_top_update(vdev_t *tvd, vdev_t *vd)
 765 {
 766         if (vd == NULL)
 767                 return;
 768 
 769         vd->vdev_top = tvd;
 770 
 771         for (int c = 0; c < vd->vdev_children; c++)
 772                 vdev_top_update(tvd, vd->vdev_child[c]);
 773 }
 774 
 775 /*
 776  * Add a mirror/replacing vdev above an existing vdev.
 777  */
 778 vdev_t *
 779 vdev_add_parent(vdev_t *cvd, vdev_ops_t *ops)
 780 {
 781         spa_t *spa = cvd->vdev_spa;
 782         vdev_t *pvd = cvd->vdev_parent;
 783         vdev_t *mvd;
 784 
 785         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
 786 
 787         mvd = vdev_alloc_common(spa, cvd->vdev_id, 0, ops);
 788 
 789         mvd->vdev_asize = cvd->vdev_asize;
 790         mvd->vdev_min_asize = cvd->vdev_min_asize;
 791         mvd->vdev_max_asize = cvd->vdev_max_asize;
 792         mvd->vdev_ashift = cvd->vdev_ashift;
 793         mvd->vdev_state = cvd->vdev_state;
 794         mvd->vdev_crtxg = cvd->vdev_crtxg;
 795 
 796         vdev_remove_child(pvd, cvd);
 797         vdev_add_child(pvd, mvd);
 798         cvd->vdev_id = mvd->vdev_children;
 799         vdev_add_child(mvd, cvd);
 800         vdev_top_update(cvd->vdev_top, cvd->vdev_top);
 801 
 802         if (mvd == mvd->vdev_top)
 803                 vdev_top_transfer(cvd, mvd);
 804 
 805         return (mvd);
 806 }
 807 
 808 /*
 809  * Remove a 1-way mirror/replacing vdev from the tree.
 810  */
 811 void
 812 vdev_remove_parent(vdev_t *cvd)
 813 {
 814         vdev_t *mvd = cvd->vdev_parent;
 815         vdev_t *pvd = mvd->vdev_parent;
 816 
 817         ASSERT(spa_config_held(cvd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
 818 
 819         ASSERT(mvd->vdev_children == 1);
 820         ASSERT(mvd->vdev_ops == &vdev_mirror_ops ||
 821             mvd->vdev_ops == &vdev_replacing_ops ||
 822             mvd->vdev_ops == &vdev_spare_ops);
 823         cvd->vdev_ashift = mvd->vdev_ashift;
 824 
 825         vdev_remove_child(mvd, cvd);
 826         vdev_remove_child(pvd, mvd);
 827 
 828         /*
 829          * If cvd will replace mvd as a top-level vdev, preserve mvd's guid.
 830          * Otherwise, we could have detached an offline device, and when we
 831          * go to import the pool we'll think we have two top-level vdevs,
 832          * instead of a different version of the same top-level vdev.
 833          */
 834         if (mvd->vdev_top == mvd) {
 835                 uint64_t guid_delta = mvd->vdev_guid - cvd->vdev_guid;
 836                 cvd->vdev_orig_guid = cvd->vdev_guid;
 837                 cvd->vdev_guid += guid_delta;
 838                 cvd->vdev_guid_sum += guid_delta;
 839         }
 840         cvd->vdev_id = mvd->vdev_id;
 841         vdev_add_child(pvd, cvd);
 842         vdev_top_update(cvd->vdev_top, cvd->vdev_top);
 843 
 844         if (cvd == cvd->vdev_top)
 845                 vdev_top_transfer(mvd, cvd);
 846 
 847         ASSERT(mvd->vdev_children == 0);
 848         vdev_free(mvd);
 849 }
 850 
 851 int
 852 vdev_metaslab_init(vdev_t *vd, uint64_t txg)
 853 {
 854         spa_t *spa = vd->vdev_spa;
 855         objset_t *mos = spa->spa_meta_objset;
 856         uint64_t m;
 857         uint64_t oldc = vd->vdev_ms_count;
 858         uint64_t newc = vd->vdev_asize >> vd->vdev_ms_shift;
 859         metaslab_t **mspp;
 860         int error;
 861 
 862         ASSERT(txg == 0 || spa_config_held(spa, SCL_ALLOC, RW_WRITER));
 863 
 864         /*
 865          * This vdev is not being allocated from yet or is a hole.
 866          */
 867         if (vd->vdev_ms_shift == 0)
 868                 return (0);
 869 
 870         ASSERT(!vd->vdev_ishole);
 871 
 872         /*
 873          * Compute the raidz-deflation ratio.  Note, we hard-code
 874          * in 128k (1 << 17) because it is the "typical" blocksize.
 875          * Even though SPA_MAXBLOCKSIZE changed, this algorithm can not change,
 876          * otherwise it would inconsistently account for existing bp's.
 877          */
 878         vd->vdev_deflate_ratio = (1 << 17) /
 879             (vdev_psize_to_asize(vd, 1 << 17) >> SPA_MINBLOCKSHIFT);
 880 
 881         ASSERT(oldc <= newc);
 882 
 883         mspp = kmem_zalloc(newc * sizeof (*mspp), KM_SLEEP);
 884 
 885         if (oldc != 0) {
 886                 bcopy(vd->vdev_ms, mspp, oldc * sizeof (*mspp));
 887                 kmem_free(vd->vdev_ms, oldc * sizeof (*mspp));
 888         }
 889 
 890         vd->vdev_ms = mspp;
 891         vd->vdev_ms_count = newc;
 892 
 893         for (m = oldc; m < newc; m++) {
 894                 uint64_t object = 0;
 895 
 896                 if (txg == 0) {
 897                         error = dmu_read(mos, vd->vdev_ms_array,
 898                             m * sizeof (uint64_t), sizeof (uint64_t), &object,
 899                             DMU_READ_PREFETCH);
 900                         if (error)
 901                                 return (error);
 902                 }
 903 
 904                 error = metaslab_init(vd->vdev_mg, m, object, txg,
 905                     &(vd->vdev_ms[m]));
 906                 if (error)
 907                         return (error);
 908         }
 909 
 910         if (txg == 0)
 911                 spa_config_enter(spa, SCL_ALLOC, FTAG, RW_WRITER);
 912 
 913         /*
 914          * If the vdev is being removed we don't activate
 915          * the metaslabs since we want to ensure that no new
 916          * allocations are performed on this device.
 917          */
 918         if (oldc == 0 && !vd->vdev_removing)
 919                 metaslab_group_activate(vd->vdev_mg);
 920 
 921         if (txg == 0)
 922                 spa_config_exit(spa, SCL_ALLOC, FTAG);
 923 
 924         return (0);
 925 }
 926 
 927 void
 928 vdev_metaslab_fini(vdev_t *vd)
 929 {
 930         uint64_t m;
 931         uint64_t count = vd->vdev_ms_count;
 932 
 933         if (vd->vdev_ms != NULL) {
 934                 metaslab_group_passivate(vd->vdev_mg);
 935                 for (m = 0; m < count; m++) {
 936                         metaslab_t *msp = vd->vdev_ms[m];
 937 
 938                         if (msp != NULL)
 939                                 metaslab_fini(msp);
 940                 }
 941                 kmem_free(vd->vdev_ms, count * sizeof (metaslab_t *));
 942                 vd->vdev_ms = NULL;
 943         }
 944 }
 945 
 946 typedef struct vdev_probe_stats {
 947         boolean_t       vps_readable;
 948         boolean_t       vps_writeable;
 949         int             vps_flags;
 950 } vdev_probe_stats_t;
 951 
 952 static void
 953 vdev_probe_done(zio_t *zio)
 954 {
 955         spa_t *spa = zio->io_spa;
 956         vdev_t *vd = zio->io_vd;
 957         vdev_probe_stats_t *vps = zio->io_private;
 958 
 959         ASSERT(vd->vdev_probe_zio != NULL);
 960 
 961         if (zio->io_type == ZIO_TYPE_READ) {
 962                 if (zio->io_error == 0)
 963                         vps->vps_readable = 1;
 964                 if (zio->io_error == 0 && spa_writeable(spa)) {
 965                         zio_nowait(zio_write_phys(vd->vdev_probe_zio, vd,
 966                             zio->io_offset, zio->io_size, zio->io_abd,
 967                             ZIO_CHECKSUM_OFF, vdev_probe_done, vps,
 968                             ZIO_PRIORITY_SYNC_WRITE, vps->vps_flags, B_TRUE));
 969                 } else {
 970                         abd_free(zio->io_abd);
 971                 }
 972         } else if (zio->io_type == ZIO_TYPE_WRITE) {
 973                 if (zio->io_error == 0)
 974                         vps->vps_writeable = 1;
 975                 abd_free(zio->io_abd);
 976         } else if (zio->io_type == ZIO_TYPE_NULL) {
 977                 zio_t *pio;
 978 
 979                 vd->vdev_cant_read |= !vps->vps_readable;
 980                 vd->vdev_cant_write |= !vps->vps_writeable;
 981 
 982                 if (vdev_readable(vd) &&
 983                     (vdev_writeable(vd) || !spa_writeable(spa))) {
 984                         zio->io_error = 0;
 985                 } else {
 986                         ASSERT(zio->io_error != 0);
 987                         zfs_ereport_post(FM_EREPORT_ZFS_PROBE_FAILURE,
 988                             spa, vd, NULL, 0, 0);
 989                         zio->io_error = SET_ERROR(ENXIO);
 990                 }
 991 
 992                 mutex_enter(&vd->vdev_probe_lock);
 993                 ASSERT(vd->vdev_probe_zio == zio);
 994                 vd->vdev_probe_zio = NULL;
 995                 mutex_exit(&vd->vdev_probe_lock);
 996 
 997                 zio_link_t *zl = NULL;
 998                 while ((pio = zio_walk_parents(zio, &zl)) != NULL)
 999                         if (!vdev_accessible(vd, pio))
1000                                 pio->io_error = SET_ERROR(ENXIO);
1001 
1002                 kmem_free(vps, sizeof (*vps));
1003         }
1004 }
1005 
1006 /*
1007  * Determine whether this device is accessible.
1008  *
1009  * Read and write to several known locations: the pad regions of each
1010  * vdev label but the first, which we leave alone in case it contains
1011  * a VTOC.
1012  */
1013 zio_t *
1014 vdev_probe(vdev_t *vd, zio_t *zio)
1015 {
1016         spa_t *spa = vd->vdev_spa;
1017         vdev_probe_stats_t *vps = NULL;
1018         zio_t *pio;
1019 
1020         ASSERT(vd->vdev_ops->vdev_op_leaf);
1021 
1022         /*
1023          * Don't probe the probe.
1024          */
1025         if (zio && (zio->io_flags & ZIO_FLAG_PROBE))
1026                 return (NULL);
1027 
1028         /*
1029          * To prevent 'probe storms' when a device fails, we create
1030          * just one probe i/o at a time.  All zios that want to probe
1031          * this vdev will become parents of the probe io.
1032          */
1033         mutex_enter(&vd->vdev_probe_lock);
1034 
1035         if ((pio = vd->vdev_probe_zio) == NULL) {
1036                 vps = kmem_zalloc(sizeof (*vps), KM_SLEEP);
1037 
1038                 vps->vps_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_PROBE |
1039                     ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_AGGREGATE |
1040                     ZIO_FLAG_TRYHARD;
1041 
1042                 if (spa_config_held(spa, SCL_ZIO, RW_WRITER)) {
1043                         /*
1044                          * vdev_cant_read and vdev_cant_write can only
1045                          * transition from TRUE to FALSE when we have the
1046                          * SCL_ZIO lock as writer; otherwise they can only
1047                          * transition from FALSE to TRUE.  This ensures that
1048                          * any zio looking at these values can assume that
1049                          * failures persist for the life of the I/O.  That's
1050                          * important because when a device has intermittent
1051                          * connectivity problems, we want to ensure that
1052                          * they're ascribed to the device (ENXIO) and not
1053                          * the zio (EIO).
1054                          *
1055                          * Since we hold SCL_ZIO as writer here, clear both
1056                          * values so the probe can reevaluate from first
1057                          * principles.
1058                          */
1059                         vps->vps_flags |= ZIO_FLAG_CONFIG_WRITER;
1060                         vd->vdev_cant_read = B_FALSE;
1061                         vd->vdev_cant_write = B_FALSE;
1062                 }
1063 
1064                 vd->vdev_probe_zio = pio = zio_null(NULL, spa, vd,
1065                     vdev_probe_done, vps,
1066                     vps->vps_flags | ZIO_FLAG_DONT_PROPAGATE);
1067 
1068                 /*
1069                  * We can't change the vdev state in this context, so we
1070                  * kick off an async task to do it on our behalf.
1071                  */
1072                 if (zio != NULL) {
1073                         vd->vdev_probe_wanted = B_TRUE;
1074                         spa_async_request(spa, SPA_ASYNC_PROBE);
1075                 }
1076         }
1077 
1078         if (zio != NULL)
1079                 zio_add_child(zio, pio);
1080 
1081         mutex_exit(&vd->vdev_probe_lock);
1082 
1083         if (vps == NULL) {
1084                 ASSERT(zio != NULL);
1085                 return (NULL);
1086         }
1087 
1088         for (int l = 1; l < VDEV_LABELS; l++) {
1089                 zio_nowait(zio_read_phys(pio, vd,
1090                     vdev_label_offset(vd->vdev_psize, l,
1091                     offsetof(vdev_label_t, vl_pad2)), VDEV_PAD_SIZE,
1092                     abd_alloc_for_io(VDEV_PAD_SIZE, B_TRUE),
1093                     ZIO_CHECKSUM_OFF, vdev_probe_done, vps,
1094                     ZIO_PRIORITY_SYNC_READ, vps->vps_flags, B_TRUE));
1095         }
1096 
1097         if (zio == NULL)
1098                 return (pio);
1099 
1100         zio_nowait(pio);
1101         return (NULL);
1102 }
1103 
1104 static void
1105 vdev_open_child(void *arg)
1106 {
1107         vdev_t *vd = arg;
1108 
1109         vd->vdev_open_thread = curthread;
1110         vd->vdev_open_error = vdev_open(vd);
1111         vd->vdev_open_thread = NULL;
1112         vd->vdev_parent->vdev_nonrot &= vd->vdev_nonrot;
1113 }
1114 
1115 boolean_t
1116 vdev_uses_zvols(vdev_t *vd)
1117 {
1118         if (vd->vdev_path && strncmp(vd->vdev_path, ZVOL_DIR,
1119             strlen(ZVOL_DIR)) == 0)
1120                 return (B_TRUE);
1121         for (int c = 0; c < vd->vdev_children; c++)
1122                 if (vdev_uses_zvols(vd->vdev_child[c]))
1123                         return (B_TRUE);
1124         return (B_FALSE);
1125 }
1126 
1127 void
1128 vdev_open_children(vdev_t *vd)
1129 {
1130         taskq_t *tq;
1131         int children = vd->vdev_children;
1132 
1133         vd->vdev_nonrot = B_TRUE;
1134 
1135         /*
1136          * in order to handle pools on top of zvols, do the opens
1137          * in a single thread so that the same thread holds the
1138          * spa_namespace_lock
1139          */
1140         if (vdev_uses_zvols(vd)) {
1141                 for (int c = 0; c < children; c++) {
1142                         vd->vdev_child[c]->vdev_open_error =
1143                             vdev_open(vd->vdev_child[c]);
1144                         vd->vdev_nonrot &= vd->vdev_child[c]->vdev_nonrot;
1145                 }
1146                 return;
1147         }
1148         tq = taskq_create("vdev_open", children, minclsyspri,
1149             children, children, TASKQ_PREPOPULATE);
1150 
1151         for (int c = 0; c < children; c++)
1152                 VERIFY(taskq_dispatch(tq, vdev_open_child, vd->vdev_child[c],
1153                     TQ_SLEEP) != NULL);
1154 
1155         taskq_destroy(tq);
1156 
1157         for (int c = 0; c < children; c++)
1158                 vd->vdev_nonrot &= vd->vdev_child[c]->vdev_nonrot;
1159 }
1160 
1161 /*
1162  * Prepare a virtual device for access.
1163  */
1164 int
1165 vdev_open(vdev_t *vd)
1166 {
1167         spa_t *spa = vd->vdev_spa;
1168         int error;
1169         uint64_t osize = 0;
1170         uint64_t max_osize = 0;
1171         uint64_t asize, max_asize, psize;
1172         uint64_t ashift = 0;
1173 
1174         ASSERT(vd->vdev_open_thread == curthread ||
1175             spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
1176         ASSERT(vd->vdev_state == VDEV_STATE_CLOSED ||
1177             vd->vdev_state == VDEV_STATE_CANT_OPEN ||
1178             vd->vdev_state == VDEV_STATE_OFFLINE);
1179 
1180         vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
1181         vd->vdev_cant_read = B_FALSE;
1182         vd->vdev_cant_write = B_FALSE;
1183         vd->vdev_min_asize = vdev_get_min_asize(vd);
1184 
1185         /*
1186          * If this vdev is not removed, check its fault status.  If it's
1187          * faulted, bail out of the open.
1188          */
1189         if (!vd->vdev_removed && vd->vdev_faulted) {
1190                 ASSERT(vd->vdev_children == 0);
1191                 ASSERT(vd->vdev_label_aux == VDEV_AUX_ERR_EXCEEDED ||
1192                     vd->vdev_label_aux == VDEV_AUX_EXTERNAL);
1193                 vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
1194                     vd->vdev_label_aux);
1195                 return (SET_ERROR(ENXIO));
1196         } else if (vd->vdev_offline) {
1197                 ASSERT(vd->vdev_children == 0);
1198                 vdev_set_state(vd, B_TRUE, VDEV_STATE_OFFLINE, VDEV_AUX_NONE);
1199                 return (SET_ERROR(ENXIO));
1200         }
1201 
1202         error = vd->vdev_ops->vdev_op_open(vd, &osize, &max_osize, &ashift);
1203 
1204         /*
1205          * Reset the vdev_reopening flag so that we actually close
1206          * the vdev on error.
1207          */
1208         vd->vdev_reopening = B_FALSE;
1209         if (zio_injection_enabled && error == 0)
1210                 error = zio_handle_device_injection(vd, NULL, ENXIO);
1211 
1212         if (error) {
1213                 if (vd->vdev_removed &&
1214                     vd->vdev_stat.vs_aux != VDEV_AUX_OPEN_FAILED)
1215                         vd->vdev_removed = B_FALSE;
1216 
1217                 vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1218                     vd->vdev_stat.vs_aux);
1219                 return (error);
1220         }
1221 
1222         vd->vdev_removed = B_FALSE;
1223 
1224         /*
1225          * Recheck the faulted flag now that we have confirmed that
1226          * the vdev is accessible.  If we're faulted, bail.
1227          */
1228         if (vd->vdev_faulted) {
1229                 ASSERT(vd->vdev_children == 0);
1230                 ASSERT(vd->vdev_label_aux == VDEV_AUX_ERR_EXCEEDED ||
1231                     vd->vdev_label_aux == VDEV_AUX_EXTERNAL);
1232                 vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
1233                     vd->vdev_label_aux);
1234                 return (SET_ERROR(ENXIO));
1235         }
1236 
1237         if (vd->vdev_degraded) {
1238                 ASSERT(vd->vdev_children == 0);
1239                 vdev_set_state(vd, B_TRUE, VDEV_STATE_DEGRADED,
1240                     VDEV_AUX_ERR_EXCEEDED);
1241         } else {
1242                 vdev_set_state(vd, B_TRUE, VDEV_STATE_HEALTHY, 0);
1243         }
1244 
1245         /*
1246          * For hole or missing vdevs we just return success.
1247          */
1248         if (vd->vdev_ishole || vd->vdev_ops == &vdev_missing_ops)
1249                 return (0);
1250 
1251         for (int c = 0; c < vd->vdev_children; c++) {
1252                 if (vd->vdev_child[c]->vdev_state != VDEV_STATE_HEALTHY) {
1253                         vdev_set_state(vd, B_TRUE, VDEV_STATE_DEGRADED,
1254                             VDEV_AUX_NONE);
1255                         break;
1256                 }
1257         }
1258 
1259         osize = P2ALIGN(osize, (uint64_t)sizeof (vdev_label_t));
1260         max_osize = P2ALIGN(max_osize, (uint64_t)sizeof (vdev_label_t));
1261 
1262         if (vd->vdev_children == 0) {
1263                 if (osize < SPA_MINDEVSIZE) {
1264                         vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1265                             VDEV_AUX_TOO_SMALL);
1266                         return (SET_ERROR(EOVERFLOW));
1267                 }
1268                 psize = osize;
1269                 asize = osize - (VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE);
1270                 max_asize = max_osize - (VDEV_LABEL_START_SIZE +
1271                     VDEV_LABEL_END_SIZE);
1272         } else {
1273                 if (vd->vdev_parent != NULL && osize < SPA_MINDEVSIZE -
1274                     (VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE)) {
1275                         vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1276                             VDEV_AUX_TOO_SMALL);
1277                         return (SET_ERROR(EOVERFLOW));
1278                 }
1279                 psize = 0;
1280                 asize = osize;
1281                 max_asize = max_osize;
1282         }
1283 
1284         vd->vdev_psize = psize;
1285 
1286         /*
1287          * Make sure the allocatable size hasn't shrunk too much.
1288          */
1289         if (asize < vd->vdev_min_asize) {
1290                 vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1291                     VDEV_AUX_BAD_LABEL);
1292                 return (SET_ERROR(EINVAL));
1293         }
1294 
1295         if (vd->vdev_asize == 0) {
1296                 /*
1297                  * This is the first-ever open, so use the computed values.
1298                  * For testing purposes, a higher ashift can be requested.
1299                  */
1300                 vd->vdev_asize = asize;
1301                 vd->vdev_max_asize = max_asize;
1302                 vd->vdev_ashift = MAX(ashift, vd->vdev_ashift);
1303         } else {
1304                 /*
1305                  * Detect if the alignment requirement has increased.
1306                  * We don't want to make the pool unavailable, just
1307                  * issue a warning instead.
1308                  */
1309                 if (ashift > vd->vdev_top->vdev_ashift &&
1310                     vd->vdev_ops->vdev_op_leaf) {
1311                         cmn_err(CE_WARN,
1312                             "Disk, '%s', has a block alignment that is "
1313                             "larger than the pool's alignment\n",
1314                             vd->vdev_path);
1315                 }
1316                 vd->vdev_max_asize = max_asize;
1317         }
1318 
1319         /*
1320          * If all children are healthy we update asize if either:
1321          * The asize has increased, due to a device expansion caused by dynamic
1322          * LUN growth or vdev replacement, and automatic expansion is enabled;
1323          * making the additional space available.
1324          *
1325          * The asize has decreased, due to a device shrink usually caused by a
1326          * vdev replace with a smaller device. This ensures that calculations
1327          * based of max_asize and asize e.g. esize are always valid. It's safe
1328          * to do this as we've already validated that asize is greater than
1329          * vdev_min_asize.
1330          */
1331         if (vd->vdev_state == VDEV_STATE_HEALTHY &&
1332             ((asize > vd->vdev_asize &&
1333             (vd->vdev_expanding || spa->spa_autoexpand)) ||
1334             (asize < vd->vdev_asize)))
1335                 vd->vdev_asize = asize;
1336 
1337         vdev_set_min_asize(vd);
1338 
1339         /*
1340          * Ensure we can issue some IO before declaring the
1341          * vdev open for business.
1342          */
1343         if (vd->vdev_ops->vdev_op_leaf &&
1344             (error = zio_wait(vdev_probe(vd, NULL))) != 0) {
1345                 vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
1346                     VDEV_AUX_ERR_EXCEEDED);
1347                 return (error);
1348         }
1349 
1350         /*
1351          * Track the min and max ashift values for normal data devices.
1352          */
1353         if (vd->vdev_top == vd && vd->vdev_ashift != 0 &&
1354             !vd->vdev_islog && vd->vdev_aux == NULL) {
1355                 if (vd->vdev_ashift > spa->spa_max_ashift)
1356                         spa->spa_max_ashift = vd->vdev_ashift;
1357                 if (vd->vdev_ashift < spa->spa_min_ashift)
1358                         spa->spa_min_ashift = vd->vdev_ashift;
1359         }
1360 
1361         /*
1362          * If a leaf vdev has a DTL, and seems healthy, then kick off a
1363          * resilver.  But don't do this if we are doing a reopen for a scrub,
1364          * since this would just restart the scrub we are already doing.
1365          */
1366         if (vd->vdev_ops->vdev_op_leaf && !spa->spa_scrub_reopen &&
1367             vdev_resilver_needed(vd, NULL, NULL))
1368                 spa_async_request(spa, SPA_ASYNC_RESILVER);
1369 
1370         return (0);
1371 }
1372 
1373 /*
1374  * Called once the vdevs are all opened, this routine validates the label
1375  * contents.  This needs to be done before vdev_load() so that we don't
1376  * inadvertently do repair I/Os to the wrong device.
1377  *
1378  * If 'strict' is false ignore the spa guid check. This is necessary because
1379  * if the machine crashed during a re-guid the new guid might have been written
1380  * to all of the vdev labels, but not the cached config. The strict check
1381  * will be performed when the pool is opened again using the mos config.
1382  *
1383  * This function will only return failure if one of the vdevs indicates that it
1384  * has since been destroyed or exported.  This is only possible if
1385  * /etc/zfs/zpool.cache was readonly at the time.  Otherwise, the vdev state
1386  * will be updated but the function will return 0.
1387  */
1388 int
1389 vdev_validate(vdev_t *vd, boolean_t strict)
1390 {
1391         spa_t *spa = vd->vdev_spa;
1392         nvlist_t *label;
1393         uint64_t guid = 0, top_guid;
1394         uint64_t state;
1395 
1396         for (int c = 0; c < vd->vdev_children; c++)
1397                 if (vdev_validate(vd->vdev_child[c], strict) != 0)
1398                         return (SET_ERROR(EBADF));
1399 
1400         /*
1401          * If the device has already failed, or was marked offline, don't do
1402          * any further validation.  Otherwise, label I/O will fail and we will
1403          * overwrite the previous state.
1404          */
1405         if (vd->vdev_ops->vdev_op_leaf && vdev_readable(vd)) {
1406                 uint64_t aux_guid = 0;
1407                 nvlist_t *nvl;
1408                 uint64_t txg = spa_last_synced_txg(spa) != 0 ?
1409                     spa_last_synced_txg(spa) : -1ULL;
1410 
1411                 if ((label = vdev_label_read_config(vd, txg)) == NULL) {
1412                         vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1413                             VDEV_AUX_BAD_LABEL);
1414                         return (0);
1415                 }
1416 
1417                 /*
1418                  * Determine if this vdev has been split off into another
1419                  * pool.  If so, then refuse to open it.
1420                  */
1421                 if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_SPLIT_GUID,
1422                     &aux_guid) == 0 && aux_guid == spa_guid(spa)) {
1423                         vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1424                             VDEV_AUX_SPLIT_POOL);
1425                         nvlist_free(label);
1426                         return (0);
1427                 }
1428 
1429                 if (strict && (nvlist_lookup_uint64(label,
1430                     ZPOOL_CONFIG_POOL_GUID, &guid) != 0 ||
1431                     guid != spa_guid(spa))) {
1432                         vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1433                             VDEV_AUX_CORRUPT_DATA);
1434                         nvlist_free(label);
1435                         return (0);
1436                 }
1437 
1438                 if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_VDEV_TREE, &nvl)
1439                     != 0 || nvlist_lookup_uint64(nvl, ZPOOL_CONFIG_ORIG_GUID,
1440                     &aux_guid) != 0)
1441                         aux_guid = 0;
1442 
1443                 /*
1444                  * If this vdev just became a top-level vdev because its
1445                  * sibling was detached, it will have adopted the parent's
1446                  * vdev guid -- but the label may or may not be on disk yet.
1447                  * Fortunately, either version of the label will have the
1448                  * same top guid, so if we're a top-level vdev, we can
1449                  * safely compare to that instead.
1450                  *
1451                  * If we split this vdev off instead, then we also check the
1452                  * original pool's guid.  We don't want to consider the vdev
1453                  * corrupt if it is partway through a split operation.
1454                  */
1455                 if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID,
1456                     &guid) != 0 ||
1457                     nvlist_lookup_uint64(label, ZPOOL_CONFIG_TOP_GUID,
1458                     &top_guid) != 0 ||
1459                     ((vd->vdev_guid != guid && vd->vdev_guid != aux_guid) &&
1460                     (vd->vdev_guid != top_guid || vd != vd->vdev_top))) {
1461                         vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1462                             VDEV_AUX_CORRUPT_DATA);
1463                         nvlist_free(label);
1464                         return (0);
1465                 }
1466 
1467                 if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE,
1468                     &state) != 0) {
1469                         vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1470                             VDEV_AUX_CORRUPT_DATA);
1471                         nvlist_free(label);
1472                         return (0);
1473                 }
1474 
1475                 nvlist_free(label);
1476 
1477                 /*
1478                  * If this is a verbatim import, no need to check the
1479                  * state of the pool.
1480                  */
1481                 if (!(spa->spa_import_flags & ZFS_IMPORT_VERBATIM) &&
1482                     spa_load_state(spa) == SPA_LOAD_OPEN &&
1483                     state != POOL_STATE_ACTIVE)
1484                         return (SET_ERROR(EBADF));
1485 
1486                 /*
1487                  * If we were able to open and validate a vdev that was
1488                  * previously marked permanently unavailable, clear that state
1489                  * now.
1490                  */
1491                 if (vd->vdev_not_present)
1492                         vd->vdev_not_present = 0;
1493         }
1494 
1495         return (0);
1496 }
1497 
1498 /*
1499  * Close a virtual device.
1500  */
1501 void
1502 vdev_close(vdev_t *vd)
1503 {
1504         spa_t *spa = vd->vdev_spa;
1505         vdev_t *pvd = vd->vdev_parent;
1506 
1507         ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
1508 
1509         /*
1510          * If our parent is reopening, then we are as well, unless we are
1511          * going offline.
1512          */
1513         if (pvd != NULL && pvd->vdev_reopening)
1514                 vd->vdev_reopening = (pvd->vdev_reopening && !vd->vdev_offline);
1515 
1516         vd->vdev_ops->vdev_op_close(vd);
1517 
1518         vdev_cache_purge(vd);
1519 
1520         /*
1521          * We record the previous state before we close it, so that if we are
1522          * doing a reopen(), we don't generate FMA ereports if we notice that
1523          * it's still faulted.
1524          */
1525         vd->vdev_prevstate = vd->vdev_state;
1526 
1527         if (vd->vdev_offline)
1528                 vd->vdev_state = VDEV_STATE_OFFLINE;
1529         else
1530                 vd->vdev_state = VDEV_STATE_CLOSED;
1531         vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
1532 }
1533 
1534 void
1535 vdev_hold(vdev_t *vd)
1536 {
1537         spa_t *spa = vd->vdev_spa;
1538 
1539         ASSERT(spa_is_root(spa));
1540         if (spa->spa_state == POOL_STATE_UNINITIALIZED)
1541                 return;
1542 
1543         for (int c = 0; c < vd->vdev_children; c++)
1544                 vdev_hold(vd->vdev_child[c]);
1545 
1546         if (vd->vdev_ops->vdev_op_leaf)
1547                 vd->vdev_ops->vdev_op_hold(vd);
1548 }
1549 
1550 void
1551 vdev_rele(vdev_t *vd)
1552 {
1553         spa_t *spa = vd->vdev_spa;
1554 
1555         ASSERT(spa_is_root(spa));
1556         for (int c = 0; c < vd->vdev_children; c++)
1557                 vdev_rele(vd->vdev_child[c]);
1558 
1559         if (vd->vdev_ops->vdev_op_leaf)
1560                 vd->vdev_ops->vdev_op_rele(vd);
1561 }
1562 
1563 /*
1564  * Reopen all interior vdevs and any unopened leaves.  We don't actually
1565  * reopen leaf vdevs which had previously been opened as they might deadlock
1566  * on the spa_config_lock.  Instead we only obtain the leaf's physical size.
1567  * If the leaf has never been opened then open it, as usual.
1568  */
1569 void
1570 vdev_reopen(vdev_t *vd)
1571 {
1572         spa_t *spa = vd->vdev_spa;
1573 
1574         ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
1575 
1576         /* set the reopening flag unless we're taking the vdev offline */
1577         vd->vdev_reopening = !vd->vdev_offline;
1578         vdev_close(vd);
1579         (void) vdev_open(vd);
1580 
1581         /*
1582          * Call vdev_validate() here to make sure we have the same device.
1583          * Otherwise, a device with an invalid label could be successfully
1584          * opened in response to vdev_reopen().
1585          */
1586         if (vd->vdev_aux) {
1587                 (void) vdev_validate_aux(vd);
1588                 if (vdev_readable(vd) && vdev_writeable(vd) &&
1589                     vd->vdev_aux == &spa->spa_l2cache &&
1590                     !l2arc_vdev_present(vd))
1591                         l2arc_add_vdev(spa, vd);
1592         } else {
1593                 (void) vdev_validate(vd, B_TRUE);
1594         }
1595 
1596         /*
1597          * Reassess parent vdev's health.
1598          */
1599         vdev_propagate_state(vd);
1600 }
1601 
1602 int
1603 vdev_create(vdev_t *vd, uint64_t txg, boolean_t isreplacing)
1604 {
1605         int error;
1606 
1607         /*
1608          * Normally, partial opens (e.g. of a mirror) are allowed.
1609          * For a create, however, we want to fail the request if
1610          * there are any components we can't open.
1611          */
1612         error = vdev_open(vd);
1613 
1614         if (error || vd->vdev_state != VDEV_STATE_HEALTHY) {
1615                 vdev_close(vd);
1616                 return (error ? error : ENXIO);
1617         }
1618 
1619         /*
1620          * Recursively load DTLs and initialize all labels.
1621          */
1622         if ((error = vdev_dtl_load(vd)) != 0 ||
1623             (error = vdev_label_init(vd, txg, isreplacing ?
1624             VDEV_LABEL_REPLACE : VDEV_LABEL_CREATE)) != 0) {
1625                 vdev_close(vd);
1626                 return (error);
1627         }
1628 
1629         return (0);
1630 }
1631 
1632 void
1633 vdev_metaslab_set_size(vdev_t *vd)
1634 {
1635         /*
1636          * Aim for roughly metaslabs_per_vdev (default 200) metaslabs per vdev.
1637          */
1638         vd->vdev_ms_shift = highbit64(vd->vdev_asize / metaslabs_per_vdev);
1639         vd->vdev_ms_shift = MAX(vd->vdev_ms_shift, SPA_MAXBLOCKSHIFT);
1640 }
1641 
1642 void
1643 vdev_dirty(vdev_t *vd, int flags, void *arg, uint64_t txg)
1644 {
1645         ASSERT(vd == vd->vdev_top);
1646         ASSERT(!vd->vdev_ishole);
1647         ASSERT(ISP2(flags));
1648         ASSERT(spa_writeable(vd->vdev_spa));
1649 
1650         if (flags & VDD_METASLAB)
1651                 (void) txg_list_add(&vd->vdev_ms_list, arg, txg);
1652 
1653         if (flags & VDD_DTL)
1654                 (void) txg_list_add(&vd->vdev_dtl_list, arg, txg);
1655 
1656         (void) txg_list_add(&vd->vdev_spa->spa_vdev_txg_list, vd, txg);
1657 }
1658 
1659 void
1660 vdev_dirty_leaves(vdev_t *vd, int flags, uint64_t txg)
1661 {
1662         for (int c = 0; c < vd->vdev_children; c++)
1663                 vdev_dirty_leaves(vd->vdev_child[c], flags, txg);
1664 
1665         if (vd->vdev_ops->vdev_op_leaf)
1666                 vdev_dirty(vd->vdev_top, flags, vd, txg);
1667 }
1668 
1669 /*
1670  * DTLs.
1671  *
1672  * A vdev's DTL (dirty time log) is the set of transaction groups for which
1673  * the vdev has less than perfect replication.  There are four kinds of DTL:
1674  *
1675  * DTL_MISSING: txgs for which the vdev has no valid copies of the data
1676  *
1677  * DTL_PARTIAL: txgs for which data is available, but not fully replicated
1678  *
1679  * DTL_SCRUB: the txgs that could not be repaired by the last scrub; upon
1680  *      scrub completion, DTL_SCRUB replaces DTL_MISSING in the range of
1681  *      txgs that was scrubbed.
1682  *
1683  * DTL_OUTAGE: txgs which cannot currently be read, whether due to
1684  *      persistent errors or just some device being offline.
1685  *      Unlike the other three, the DTL_OUTAGE map is not generally
1686  *      maintained; it's only computed when needed, typically to
1687  *      determine whether a device can be detached.
1688  *
1689  * For leaf vdevs, DTL_MISSING and DTL_PARTIAL are identical: the device
1690  * either has the data or it doesn't.
1691  *
1692  * For interior vdevs such as mirror and RAID-Z the picture is more complex.
1693  * A vdev's DTL_PARTIAL is the union of its children's DTL_PARTIALs, because
1694  * if any child is less than fully replicated, then so is its parent.
1695  * A vdev's DTL_MISSING is a modified union of its children's DTL_MISSINGs,
1696  * comprising only those txgs which appear in 'maxfaults' or more children;
1697  * those are the txgs we don't have enough replication to read.  For example,
1698  * double-parity RAID-Z can tolerate up to two missing devices (maxfaults == 2);
1699  * thus, its DTL_MISSING consists of the set of txgs that appear in more than
1700  * two child DTL_MISSING maps.
1701  *
1702  * It should be clear from the above that to compute the DTLs and outage maps
1703  * for all vdevs, it suffices to know just the leaf vdevs' DTL_MISSING maps.
1704  * Therefore, that is all we keep on disk.  When loading the pool, or after
1705  * a configuration change, we generate all other DTLs from first principles.
1706  */
1707 void
1708 vdev_dtl_dirty(vdev_t *vd, vdev_dtl_type_t t, uint64_t txg, uint64_t size)
1709 {
1710         range_tree_t *rt = vd->vdev_dtl[t];
1711 
1712         ASSERT(t < DTL_TYPES);
1713         ASSERT(vd != vd->vdev_spa->spa_root_vdev);
1714         ASSERT(spa_writeable(vd->vdev_spa));
1715 
1716         mutex_enter(rt->rt_lock);
1717         if (!range_tree_contains(rt, txg, size))
1718                 range_tree_add(rt, txg, size);
1719         mutex_exit(rt->rt_lock);
1720 }
1721 
1722 boolean_t
1723 vdev_dtl_contains(vdev_t *vd, vdev_dtl_type_t t, uint64_t txg, uint64_t size)
1724 {
1725         range_tree_t *rt = vd->vdev_dtl[t];
1726         boolean_t dirty = B_FALSE;
1727 
1728         ASSERT(t < DTL_TYPES);
1729         ASSERT(vd != vd->vdev_spa->spa_root_vdev);
1730 
1731         mutex_enter(rt->rt_lock);
1732         if (range_tree_space(rt) != 0)
1733                 dirty = range_tree_contains(rt, txg, size);
1734         mutex_exit(rt->rt_lock);
1735 
1736         return (dirty);
1737 }
1738 
1739 boolean_t
1740 vdev_dtl_empty(vdev_t *vd, vdev_dtl_type_t t)
1741 {
1742         range_tree_t *rt = vd->vdev_dtl[t];
1743         boolean_t empty;
1744 
1745         mutex_enter(rt->rt_lock);
1746         empty = (range_tree_space(rt) == 0);
1747         mutex_exit(rt->rt_lock);
1748 
1749         return (empty);
1750 }
1751 
1752 /*
1753  * Returns the lowest txg in the DTL range.
1754  */
1755 static uint64_t
1756 vdev_dtl_min(vdev_t *vd)
1757 {
1758         range_seg_t *rs;
1759 
1760         ASSERT(MUTEX_HELD(&vd->vdev_dtl_lock));
1761         ASSERT3U(range_tree_space(vd->vdev_dtl[DTL_MISSING]), !=, 0);
1762         ASSERT0(vd->vdev_children);
1763 
1764         rs = avl_first(&vd->vdev_dtl[DTL_MISSING]->rt_root);
1765         return (rs->rs_start - 1);
1766 }
1767 
1768 /*
1769  * Returns the highest txg in the DTL.
1770  */
1771 static uint64_t
1772 vdev_dtl_max(vdev_t *vd)
1773 {
1774         range_seg_t *rs;
1775 
1776         ASSERT(MUTEX_HELD(&vd->vdev_dtl_lock));
1777         ASSERT3U(range_tree_space(vd->vdev_dtl[DTL_MISSING]), !=, 0);
1778         ASSERT0(vd->vdev_children);
1779 
1780         rs = avl_last(&vd->vdev_dtl[DTL_MISSING]->rt_root);
1781         return (rs->rs_end);
1782 }
1783 
1784 /*
1785  * Determine if a resilvering vdev should remove any DTL entries from
1786  * its range. If the vdev was resilvering for the entire duration of the
1787  * scan then it should excise that range from its DTLs. Otherwise, this
1788  * vdev is considered partially resilvered and should leave its DTL
1789  * entries intact. The comment in vdev_dtl_reassess() describes how we
1790  * excise the DTLs.
1791  */
1792 static boolean_t
1793 vdev_dtl_should_excise(vdev_t *vd)
1794 {
1795         spa_t *spa = vd->vdev_spa;
1796         dsl_scan_t *scn = spa->spa_dsl_pool->dp_scan;
1797 
1798         ASSERT0(scn->scn_phys.scn_errors);
1799         ASSERT0(vd->vdev_children);
1800 
1801         if (vd->vdev_state < VDEV_STATE_DEGRADED)
1802                 return (B_FALSE);
1803 
1804         if (vd->vdev_resilver_txg == 0 ||
1805             range_tree_space(vd->vdev_dtl[DTL_MISSING]) == 0)
1806                 return (B_TRUE);
1807 
1808         /*
1809          * When a resilver is initiated the scan will assign the scn_max_txg
1810          * value to the highest txg value that exists in all DTLs. If this
1811          * device's max DTL is not part of this scan (i.e. it is not in
1812          * the range (scn_min_txg, scn_max_txg] then it is not eligible
1813          * for excision.
1814          */
1815         if (vdev_dtl_max(vd) <= scn->scn_phys.scn_max_txg) {
1816                 ASSERT3U(scn->scn_phys.scn_min_txg, <=, vdev_dtl_min(vd));
1817                 ASSERT3U(scn->scn_phys.scn_min_txg, <, vd->vdev_resilver_txg);
1818                 ASSERT3U(vd->vdev_resilver_txg, <=, scn->scn_phys.scn_max_txg);
1819                 return (B_TRUE);
1820         }
1821         return (B_FALSE);
1822 }
1823 
1824 /*
1825  * Reassess DTLs after a config change or scrub completion.
1826  */
1827 void
1828 vdev_dtl_reassess(vdev_t *vd, uint64_t txg, uint64_t scrub_txg, int scrub_done)
1829 {
1830         spa_t *spa = vd->vdev_spa;
1831         avl_tree_t reftree;
1832         int minref;
1833 
1834         ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
1835 
1836         for (int c = 0; c < vd->vdev_children; c++)
1837                 vdev_dtl_reassess(vd->vdev_child[c], txg,
1838                     scrub_txg, scrub_done);
1839 
1840         if (vd == spa->spa_root_vdev || vd->vdev_ishole || vd->vdev_aux)
1841                 return;
1842 
1843         if (vd->vdev_ops->vdev_op_leaf) {
1844                 dsl_scan_t *scn = spa->spa_dsl_pool->dp_scan;
1845 
1846                 mutex_enter(&vd->vdev_dtl_lock);
1847 
1848                 /*
1849                  * If we've completed a scan cleanly then determine
1850                  * if this vdev should remove any DTLs. We only want to
1851                  * excise regions on vdevs that were available during
1852                  * the entire duration of this scan.
1853                  */
1854                 if (scrub_txg != 0 &&
1855                     (spa->spa_scrub_started ||
1856                     (scn != NULL && scn->scn_phys.scn_errors == 0)) &&
1857                     vdev_dtl_should_excise(vd)) {
1858                         /*
1859                          * We completed a scrub up to scrub_txg.  If we
1860                          * did it without rebooting, then the scrub dtl
1861                          * will be valid, so excise the old region and
1862                          * fold in the scrub dtl.  Otherwise, leave the
1863                          * dtl as-is if there was an error.
1864                          *
1865                          * There's little trick here: to excise the beginning
1866                          * of the DTL_MISSING map, we put it into a reference
1867                          * tree and then add a segment with refcnt -1 that
1868                          * covers the range [0, scrub_txg).  This means
1869                          * that each txg in that range has refcnt -1 or 0.
1870                          * We then add DTL_SCRUB with a refcnt of 2, so that
1871                          * entries in the range [0, scrub_txg) will have a
1872                          * positive refcnt -- either 1 or 2.  We then convert
1873                          * the reference tree into the new DTL_MISSING map.
1874                          */
1875                         space_reftree_create(&reftree);
1876                         space_reftree_add_map(&reftree,
1877                             vd->vdev_dtl[DTL_MISSING], 1);
1878                         space_reftree_add_seg(&reftree, 0, scrub_txg, -1);
1879                         space_reftree_add_map(&reftree,
1880                             vd->vdev_dtl[DTL_SCRUB], 2);
1881                         space_reftree_generate_map(&reftree,
1882                             vd->vdev_dtl[DTL_MISSING], 1);
1883                         space_reftree_destroy(&reftree);
1884                 }
1885                 range_tree_vacate(vd->vdev_dtl[DTL_PARTIAL], NULL, NULL);
1886                 range_tree_walk(vd->vdev_dtl[DTL_MISSING],
1887                     range_tree_add, vd->vdev_dtl[DTL_PARTIAL]);
1888                 if (scrub_done)
1889                         range_tree_vacate(vd->vdev_dtl[DTL_SCRUB], NULL, NULL);
1890                 range_tree_vacate(vd->vdev_dtl[DTL_OUTAGE], NULL, NULL);
1891                 if (!vdev_readable(vd))
1892                         range_tree_add(vd->vdev_dtl[DTL_OUTAGE], 0, -1ULL);
1893                 else
1894                         range_tree_walk(vd->vdev_dtl[DTL_MISSING],
1895                             range_tree_add, vd->vdev_dtl[DTL_OUTAGE]);
1896 
1897                 /*
1898                  * If the vdev was resilvering and no longer has any
1899                  * DTLs then reset its resilvering flag.
1900                  */
1901                 if (vd->vdev_resilver_txg != 0 &&
1902                     range_tree_space(vd->vdev_dtl[DTL_MISSING]) == 0 &&
1903                     range_tree_space(vd->vdev_dtl[DTL_OUTAGE]) == 0)
1904                         vd->vdev_resilver_txg = 0;
1905 
1906                 mutex_exit(&vd->vdev_dtl_lock);
1907 
1908                 if (txg != 0)
1909                         vdev_dirty(vd->vdev_top, VDD_DTL, vd, txg);
1910                 return;
1911         }
1912 
1913         mutex_enter(&vd->vdev_dtl_lock);
1914         for (int t = 0; t < DTL_TYPES; t++) {
1915                 /* account for child's outage in parent's missing map */
1916                 int s = (t == DTL_MISSING) ? DTL_OUTAGE: t;
1917                 if (t == DTL_SCRUB)
1918                         continue;                       /* leaf vdevs only */
1919                 if (t == DTL_PARTIAL)
1920                         minref = 1;                     /* i.e. non-zero */
1921                 else if (vd->vdev_nparity != 0)
1922                         minref = vd->vdev_nparity + 1;       /* RAID-Z */
1923                 else
1924                         minref = vd->vdev_children;  /* any kind of mirror */
1925                 space_reftree_create(&reftree);
1926                 for (int c = 0; c < vd->vdev_children; c++) {
1927                         vdev_t *cvd = vd->vdev_child[c];
1928                         mutex_enter(&cvd->vdev_dtl_lock);
1929                         space_reftree_add_map(&reftree, cvd->vdev_dtl[s], 1);
1930                         mutex_exit(&cvd->vdev_dtl_lock);
1931                 }
1932                 space_reftree_generate_map(&reftree, vd->vdev_dtl[t], minref);
1933                 space_reftree_destroy(&reftree);
1934         }
1935         mutex_exit(&vd->vdev_dtl_lock);
1936 }
1937 
1938 int
1939 vdev_dtl_load(vdev_t *vd)
1940 {
1941         spa_t *spa = vd->vdev_spa;
1942         objset_t *mos = spa->spa_meta_objset;
1943         int error = 0;
1944 
1945         if (vd->vdev_ops->vdev_op_leaf && vd->vdev_dtl_object != 0) {
1946                 ASSERT(!vd->vdev_ishole);
1947 
1948                 error = space_map_open(&vd->vdev_dtl_sm, mos,
1949                     vd->vdev_dtl_object, 0, -1ULL, 0, &vd->vdev_dtl_lock);
1950                 if (error)
1951                         return (error);
1952                 ASSERT(vd->vdev_dtl_sm != NULL);
1953 
1954                 mutex_enter(&vd->vdev_dtl_lock);
1955 
1956                 /*
1957                  * Now that we've opened the space_map we need to update
1958                  * the in-core DTL.
1959                  */
1960                 space_map_update(vd->vdev_dtl_sm);
1961 
1962                 error = space_map_load(vd->vdev_dtl_sm,
1963                     vd->vdev_dtl[DTL_MISSING], SM_ALLOC);
1964                 mutex_exit(&vd->vdev_dtl_lock);
1965 
1966                 return (error);
1967         }
1968 
1969         for (int c = 0; c < vd->vdev_children; c++) {
1970                 error = vdev_dtl_load(vd->vdev_child[c]);
1971                 if (error != 0)
1972                         break;
1973         }
1974 
1975         return (error);
1976 }
1977 
1978 void
1979 vdev_destroy_unlink_zap(vdev_t *vd, uint64_t zapobj, dmu_tx_t *tx)
1980 {
1981         spa_t *spa = vd->vdev_spa;
1982 
1983         VERIFY0(zap_destroy(spa->spa_meta_objset, zapobj, tx));
1984         VERIFY0(zap_remove_int(spa->spa_meta_objset, spa->spa_all_vdev_zaps,
1985             zapobj, tx));
1986 }
1987 
1988 uint64_t
1989 vdev_create_link_zap(vdev_t *vd, dmu_tx_t *tx)
1990 {
1991         spa_t *spa = vd->vdev_spa;
1992         uint64_t zap = zap_create(spa->spa_meta_objset, DMU_OTN_ZAP_METADATA,
1993             DMU_OT_NONE, 0, tx);
1994 
1995         ASSERT(zap != 0);
1996         VERIFY0(zap_add_int(spa->spa_meta_objset, spa->spa_all_vdev_zaps,
1997             zap, tx));
1998 
1999         return (zap);
2000 }
2001 
2002 void
2003 vdev_construct_zaps(vdev_t *vd, dmu_tx_t *tx)
2004 {
2005         if (vd->vdev_ops != &vdev_hole_ops &&
2006             vd->vdev_ops != &vdev_missing_ops &&
2007             vd->vdev_ops != &vdev_root_ops &&
2008             !vd->vdev_top->vdev_removing) {
2009                 if (vd->vdev_ops->vdev_op_leaf && vd->vdev_leaf_zap == 0) {
2010                         vd->vdev_leaf_zap = vdev_create_link_zap(vd, tx);
2011                 }
2012                 if (vd == vd->vdev_top && vd->vdev_top_zap == 0) {
2013                         vd->vdev_top_zap = vdev_create_link_zap(vd, tx);
2014                 }
2015         }
2016         for (uint64_t i = 0; i < vd->vdev_children; i++) {
2017                 vdev_construct_zaps(vd->vdev_child[i], tx);
2018         }
2019 }
2020 
2021 void
2022 vdev_dtl_sync(vdev_t *vd, uint64_t txg)
2023 {
2024         spa_t *spa = vd->vdev_spa;
2025         range_tree_t *rt = vd->vdev_dtl[DTL_MISSING];
2026         objset_t *mos = spa->spa_meta_objset;
2027         range_tree_t *rtsync;
2028         kmutex_t rtlock;
2029         dmu_tx_t *tx;
2030         uint64_t object = space_map_object(vd->vdev_dtl_sm);
2031 
2032         ASSERT(!vd->vdev_ishole);
2033         ASSERT(vd->vdev_ops->vdev_op_leaf);
2034 
2035         tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
2036 
2037         if (vd->vdev_detached || vd->vdev_top->vdev_removing) {
2038                 mutex_enter(&vd->vdev_dtl_lock);
2039                 space_map_free(vd->vdev_dtl_sm, tx);
2040                 space_map_close(vd->vdev_dtl_sm);
2041                 vd->vdev_dtl_sm = NULL;
2042                 mutex_exit(&vd->vdev_dtl_lock);
2043 
2044                 /*
2045                  * We only destroy the leaf ZAP for detached leaves or for
2046                  * removed log devices. Removed data devices handle leaf ZAP
2047                  * cleanup later, once cancellation is no longer possible.
2048                  */
2049                 if (vd->vdev_leaf_zap != 0 && (vd->vdev_detached ||
2050                     vd->vdev_top->vdev_islog)) {
2051                         vdev_destroy_unlink_zap(vd, vd->vdev_leaf_zap, tx);
2052                         vd->vdev_leaf_zap = 0;
2053                 }
2054 
2055                 dmu_tx_commit(tx);
2056                 return;
2057         }
2058 
2059         if (vd->vdev_dtl_sm == NULL) {
2060                 uint64_t new_object;
2061 
2062                 new_object = space_map_alloc(mos, tx);
2063                 VERIFY3U(new_object, !=, 0);
2064 
2065                 VERIFY0(space_map_open(&vd->vdev_dtl_sm, mos, new_object,
2066                     0, -1ULL, 0, &vd->vdev_dtl_lock));
2067                 ASSERT(vd->vdev_dtl_sm != NULL);
2068         }
2069 
2070         mutex_init(&rtlock, NULL, MUTEX_DEFAULT, NULL);
2071 
2072         rtsync = range_tree_create(NULL, NULL, &rtlock);
2073 
2074         mutex_enter(&rtlock);
2075 
2076         mutex_enter(&vd->vdev_dtl_lock);
2077         range_tree_walk(rt, range_tree_add, rtsync);
2078         mutex_exit(&vd->vdev_dtl_lock);
2079 
2080         space_map_truncate(vd->vdev_dtl_sm, tx);
2081         space_map_write(vd->vdev_dtl_sm, rtsync, SM_ALLOC, tx);
2082         range_tree_vacate(rtsync, NULL, NULL);
2083 
2084         range_tree_destroy(rtsync);
2085 
2086         mutex_exit(&rtlock);
2087         mutex_destroy(&rtlock);
2088 
2089         /*
2090          * If the object for the space map has changed then dirty
2091          * the top level so that we update the config.
2092          */
2093         if (object != space_map_object(vd->vdev_dtl_sm)) {
2094                 zfs_dbgmsg("txg %llu, spa %s, DTL old object %llu, "
2095                     "new object %llu", txg, spa_name(spa), object,
2096                     space_map_object(vd->vdev_dtl_sm));
2097                 vdev_config_dirty(vd->vdev_top);
2098         }
2099 
2100         dmu_tx_commit(tx);
2101 
2102         mutex_enter(&vd->vdev_dtl_lock);
2103         space_map_update(vd->vdev_dtl_sm);
2104         mutex_exit(&vd->vdev_dtl_lock);
2105 }
2106 
2107 /*
2108  * Determine whether the specified vdev can be offlined/detached/removed
2109  * without losing data.
2110  */
2111 boolean_t
2112 vdev_dtl_required(vdev_t *vd)
2113 {
2114         spa_t *spa = vd->vdev_spa;
2115         vdev_t *tvd = vd->vdev_top;
2116         uint8_t cant_read = vd->vdev_cant_read;
2117         boolean_t required;
2118 
2119         ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
2120 
2121         if (vd == spa->spa_root_vdev || vd == tvd)
2122                 return (B_TRUE);
2123 
2124         /*
2125          * Temporarily mark the device as unreadable, and then determine
2126          * whether this results in any DTL outages in the top-level vdev.
2127          * If not, we can safely offline/detach/remove the device.
2128          */
2129         vd->vdev_cant_read = B_TRUE;
2130         vdev_dtl_reassess(tvd, 0, 0, B_FALSE);
2131         required = !vdev_dtl_empty(tvd, DTL_OUTAGE);
2132         vd->vdev_cant_read = cant_read;
2133         vdev_dtl_reassess(tvd, 0, 0, B_FALSE);
2134 
2135         if (!required && zio_injection_enabled)
2136                 required = !!zio_handle_device_injection(vd, NULL, ECHILD);
2137 
2138         return (required);
2139 }
2140 
2141 /*
2142  * Determine if resilver is needed, and if so the txg range.
2143  */
2144 boolean_t
2145 vdev_resilver_needed(vdev_t *vd, uint64_t *minp, uint64_t *maxp)
2146 {
2147         boolean_t needed = B_FALSE;
2148         uint64_t thismin = UINT64_MAX;
2149         uint64_t thismax = 0;
2150 
2151         if (vd->vdev_children == 0) {
2152                 mutex_enter(&vd->vdev_dtl_lock);
2153                 if (range_tree_space(vd->vdev_dtl[DTL_MISSING]) != 0 &&
2154                     vdev_writeable(vd)) {
2155 
2156                         thismin = vdev_dtl_min(vd);
2157                         thismax = vdev_dtl_max(vd);
2158                         needed = B_TRUE;
2159                 }
2160                 mutex_exit(&vd->vdev_dtl_lock);
2161         } else {
2162                 for (int c = 0; c < vd->vdev_children; c++) {
2163                         vdev_t *cvd = vd->vdev_child[c];
2164                         uint64_t cmin, cmax;
2165 
2166                         if (vdev_resilver_needed(cvd, &cmin, &cmax)) {
2167                                 thismin = MIN(thismin, cmin);
2168                                 thismax = MAX(thismax, cmax);
2169                                 needed = B_TRUE;
2170                         }
2171                 }
2172         }
2173 
2174         if (needed && minp) {
2175                 *minp = thismin;
2176                 *maxp = thismax;
2177         }
2178         return (needed);
2179 }
2180 
2181 void
2182 vdev_load(vdev_t *vd)
2183 {
2184         /*
2185          * Recursively load all children.
2186          */
2187         for (int c = 0; c < vd->vdev_children; c++)
2188                 vdev_load(vd->vdev_child[c]);
2189 
2190         /*
2191          * If this is a top-level vdev, initialize its metaslabs.
2192          */
2193         if (vd == vd->vdev_top && !vd->vdev_ishole &&
2194             (vd->vdev_ashift == 0 || vd->vdev_asize == 0 ||
2195             vdev_metaslab_init(vd, 0) != 0))
2196                 vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2197                     VDEV_AUX_CORRUPT_DATA);
2198 
2199         /*
2200          * If this is a leaf vdev, load its DTL.
2201          */
2202         if (vd->vdev_ops->vdev_op_leaf && vdev_dtl_load(vd) != 0)
2203                 vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2204                     VDEV_AUX_CORRUPT_DATA);
2205 }
2206 
2207 /*
2208  * The special vdev case is used for hot spares and l2cache devices.  Its
2209  * sole purpose it to set the vdev state for the associated vdev.  To do this,
2210  * we make sure that we can open the underlying device, then try to read the
2211  * label, and make sure that the label is sane and that it hasn't been
2212  * repurposed to another pool.
2213  */
2214 int
2215 vdev_validate_aux(vdev_t *vd)
2216 {
2217         nvlist_t *label;
2218         uint64_t guid, version;
2219         uint64_t state;
2220 
2221         if (!vdev_readable(vd))
2222                 return (0);
2223 
2224         if ((label = vdev_label_read_config(vd, -1ULL)) == NULL) {
2225                 vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
2226                     VDEV_AUX_CORRUPT_DATA);
2227                 return (-1);
2228         }
2229 
2230         if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_VERSION, &version) != 0 ||
2231             !SPA_VERSION_IS_SUPPORTED(version) ||
2232             nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID, &guid) != 0 ||
2233             guid != vd->vdev_guid ||
2234             nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE, &state) != 0) {
2235                 vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
2236                     VDEV_AUX_CORRUPT_DATA);
2237                 nvlist_free(label);
2238                 return (-1);
2239         }
2240 
2241         /*
2242          * We don't actually check the pool state here.  If it's in fact in
2243          * use by another pool, we update this fact on the fly when requested.
2244          */
2245         nvlist_free(label);
2246         return (0);
2247 }
2248 
2249 void
2250 vdev_remove(vdev_t *vd, uint64_t txg)
2251 {
2252         spa_t *spa = vd->vdev_spa;
2253         objset_t *mos = spa->spa_meta_objset;
2254         dmu_tx_t *tx;
2255 
2256         tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
2257         ASSERT(vd == vd->vdev_top);
2258         ASSERT3U(txg, ==, spa_syncing_txg(spa));
2259 
2260         if (vd->vdev_ms != NULL) {
2261                 metaslab_group_t *mg = vd->vdev_mg;
2262 
2263                 metaslab_group_histogram_verify(mg);
2264                 metaslab_class_histogram_verify(mg->mg_class);
2265 
2266                 for (int m = 0; m < vd->vdev_ms_count; m++) {
2267                         metaslab_t *msp = vd->vdev_ms[m];
2268 
2269                         if (msp == NULL || msp->ms_sm == NULL)
2270                                 continue;
2271 
2272                         mutex_enter(&msp->ms_lock);
2273                         /*
2274                          * If the metaslab was not loaded when the vdev
2275                          * was removed then the histogram accounting may
2276                          * not be accurate. Update the histogram information
2277                          * here so that we ensure that the metaslab group
2278                          * and metaslab class are up-to-date.
2279                          */
2280                         metaslab_group_histogram_remove(mg, msp);
2281 
2282                         VERIFY0(space_map_allocated(msp->ms_sm));
2283                         space_map_free(msp->ms_sm, tx);
2284                         space_map_close(msp->ms_sm);
2285                         msp->ms_sm = NULL;
2286                         mutex_exit(&msp->ms_lock);
2287                 }
2288 
2289                 metaslab_group_histogram_verify(mg);
2290                 metaslab_class_histogram_verify(mg->mg_class);
2291                 for (int i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++)
2292                         ASSERT0(mg->mg_histogram[i]);
2293 
2294         }
2295 
2296         if (vd->vdev_ms_array) {
2297                 (void) dmu_object_free(mos, vd->vdev_ms_array, tx);
2298                 vd->vdev_ms_array = 0;
2299         }
2300 
2301         if (vd->vdev_islog && vd->vdev_top_zap != 0) {
2302                 vdev_destroy_unlink_zap(vd, vd->vdev_top_zap, tx);
2303                 vd->vdev_top_zap = 0;
2304         }
2305         dmu_tx_commit(tx);
2306 }
2307 
2308 void
2309 vdev_sync_done(vdev_t *vd, uint64_t txg)
2310 {
2311         metaslab_t *msp;
2312         boolean_t reassess = !txg_list_empty(&vd->vdev_ms_list, TXG_CLEAN(txg));
2313 
2314         ASSERT(!vd->vdev_ishole);
2315 
2316         while (msp = txg_list_remove(&vd->vdev_ms_list, TXG_CLEAN(txg)))
2317                 metaslab_sync_done(msp, txg);
2318 
2319         if (reassess)
2320                 metaslab_sync_reassess(vd->vdev_mg);
2321 }
2322 
2323 void
2324 vdev_sync(vdev_t *vd, uint64_t txg)
2325 {
2326         spa_t *spa = vd->vdev_spa;
2327         vdev_t *lvd;
2328         metaslab_t *msp;
2329         dmu_tx_t *tx;
2330 
2331         ASSERT(!vd->vdev_ishole);
2332 
2333         if (vd->vdev_ms_array == 0 && vd->vdev_ms_shift != 0) {
2334                 ASSERT(vd == vd->vdev_top);
2335                 tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
2336                 vd->vdev_ms_array = dmu_object_alloc(spa->spa_meta_objset,
2337                     DMU_OT_OBJECT_ARRAY, 0, DMU_OT_NONE, 0, tx);
2338                 ASSERT(vd->vdev_ms_array != 0);
2339                 vdev_config_dirty(vd);
2340                 dmu_tx_commit(tx);
2341         }
2342 
2343         /*
2344          * Remove the metadata associated with this vdev once it's empty.
2345          */
2346         if (vd->vdev_stat.vs_alloc == 0 && vd->vdev_removing)
2347                 vdev_remove(vd, txg);
2348 
2349         while ((msp = txg_list_remove(&vd->vdev_ms_list, txg)) != NULL) {
2350                 metaslab_sync(msp, txg);
2351                 (void) txg_list_add(&vd->vdev_ms_list, msp, TXG_CLEAN(txg));
2352         }
2353 
2354         while ((lvd = txg_list_remove(&vd->vdev_dtl_list, txg)) != NULL)
2355                 vdev_dtl_sync(lvd, txg);
2356 
2357         (void) txg_list_add(&spa->spa_vdev_txg_list, vd, TXG_CLEAN(txg));
2358 }
2359 
2360 uint64_t
2361 vdev_psize_to_asize(vdev_t *vd, uint64_t psize)
2362 {
2363         return (vd->vdev_ops->vdev_op_asize(vd, psize));
2364 }
2365 
2366 /*
2367  * Mark the given vdev faulted.  A faulted vdev behaves as if the device could
2368  * not be opened, and no I/O is attempted.
2369  */
2370 int
2371 vdev_fault(spa_t *spa, uint64_t guid, vdev_aux_t aux)
2372 {
2373         vdev_t *vd, *tvd;
2374 
2375         spa_vdev_state_enter(spa, SCL_NONE);
2376 
2377         if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
2378                 return (spa_vdev_state_exit(spa, NULL, ENODEV));
2379 
2380         if (!vd->vdev_ops->vdev_op_leaf)
2381                 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
2382 
2383         tvd = vd->vdev_top;
2384 
2385         /*
2386          * We don't directly use the aux state here, but if we do a
2387          * vdev_reopen(), we need this value to be present to remember why we
2388          * were faulted.
2389          */
2390         vd->vdev_label_aux = aux;
2391 
2392         /*
2393          * Faulted state takes precedence over degraded.
2394          */
2395         vd->vdev_delayed_close = B_FALSE;
2396         vd->vdev_faulted = 1ULL;
2397         vd->vdev_degraded = 0ULL;
2398         vdev_set_state(vd, B_FALSE, VDEV_STATE_FAULTED, aux);
2399 
2400         /*
2401          * If this device has the only valid copy of the data, then
2402          * back off and simply mark the vdev as degraded instead.
2403          */
2404         if (!tvd->vdev_islog && vd->vdev_aux == NULL && vdev_dtl_required(vd)) {
2405                 vd->vdev_degraded = 1ULL;
2406                 vd->vdev_faulted = 0ULL;
2407 
2408                 /*
2409                  * If we reopen the device and it's not dead, only then do we
2410                  * mark it degraded.
2411                  */
2412                 vdev_reopen(tvd);
2413 
2414                 if (vdev_readable(vd))
2415                         vdev_set_state(vd, B_FALSE, VDEV_STATE_DEGRADED, aux);
2416         }
2417 
2418         return (spa_vdev_state_exit(spa, vd, 0));
2419 }
2420 
2421 /*
2422  * Mark the given vdev degraded.  A degraded vdev is purely an indication to the
2423  * user that something is wrong.  The vdev continues to operate as normal as far
2424  * as I/O is concerned.
2425  */
2426 int
2427 vdev_degrade(spa_t *spa, uint64_t guid, vdev_aux_t aux)
2428 {
2429         vdev_t *vd;
2430 
2431         spa_vdev_state_enter(spa, SCL_NONE);
2432 
2433         if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
2434                 return (spa_vdev_state_exit(spa, NULL, ENODEV));
2435 
2436         if (!vd->vdev_ops->vdev_op_leaf)
2437                 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
2438 
2439         /*
2440          * If the vdev is already faulted, then don't do anything.
2441          */
2442         if (vd->vdev_faulted || vd->vdev_degraded)
2443                 return (spa_vdev_state_exit(spa, NULL, 0));
2444 
2445         vd->vdev_degraded = 1ULL;
2446         if (!vdev_is_dead(vd))
2447                 vdev_set_state(vd, B_FALSE, VDEV_STATE_DEGRADED,
2448                     aux);
2449 
2450         return (spa_vdev_state_exit(spa, vd, 0));
2451 }
2452 
2453 /*
2454  * Online the given vdev.
2455  *
2456  * If 'ZFS_ONLINE_UNSPARE' is set, it implies two things.  First, any attached
2457  * spare device should be detached when the device finishes resilvering.
2458  * Second, the online should be treated like a 'test' online case, so no FMA
2459  * events are generated if the device fails to open.
2460  */
2461 int
2462 vdev_online(spa_t *spa, uint64_t guid, uint64_t flags, vdev_state_t *newstate)
2463 {
2464         vdev_t *vd, *tvd, *pvd, *rvd = spa->spa_root_vdev;
2465         boolean_t wasoffline;
2466         vdev_state_t oldstate;
2467 
2468         spa_vdev_state_enter(spa, SCL_NONE);
2469 
2470         if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
2471                 return (spa_vdev_state_exit(spa, NULL, ENODEV));
2472 
2473         if (!vd->vdev_ops->vdev_op_leaf)
2474                 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
2475 
2476         wasoffline = (vd->vdev_offline || vd->vdev_tmpoffline);
2477         oldstate = vd->vdev_state;
2478 
2479         tvd = vd->vdev_top;
2480         vd->vdev_offline = B_FALSE;
2481         vd->vdev_tmpoffline = B_FALSE;
2482         vd->vdev_checkremove = !!(flags & ZFS_ONLINE_CHECKREMOVE);
2483         vd->vdev_forcefault = !!(flags & ZFS_ONLINE_FORCEFAULT);
2484 
2485         /* XXX - L2ARC 1.0 does not support expansion */
2486         if (!vd->vdev_aux) {
2487                 for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
2488                         pvd->vdev_expanding = !!(flags & ZFS_ONLINE_EXPAND);
2489         }
2490 
2491         vdev_reopen(tvd);
2492         vd->vdev_checkremove = vd->vdev_forcefault = B_FALSE;
2493 
2494         if (!vd->vdev_aux) {
2495                 for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
2496                         pvd->vdev_expanding = B_FALSE;
2497         }
2498 
2499         if (newstate)
2500                 *newstate = vd->vdev_state;
2501         if ((flags & ZFS_ONLINE_UNSPARE) &&
2502             !vdev_is_dead(vd) && vd->vdev_parent &&
2503             vd->vdev_parent->vdev_ops == &vdev_spare_ops &&
2504             vd->vdev_parent->vdev_child[0] == vd)
2505                 vd->vdev_unspare = B_TRUE;
2506 
2507         if ((flags & ZFS_ONLINE_EXPAND) || spa->spa_autoexpand) {
2508 
2509                 /* XXX - L2ARC 1.0 does not support expansion */
2510                 if (vd->vdev_aux)
2511                         return (spa_vdev_state_exit(spa, vd, ENOTSUP));
2512                 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
2513         }
2514 
2515         if (wasoffline ||
2516             (oldstate < VDEV_STATE_DEGRADED &&
2517             vd->vdev_state >= VDEV_STATE_DEGRADED))
2518                 spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_ONLINE);
2519 
2520         return (spa_vdev_state_exit(spa, vd, 0));
2521 }
2522 
2523 static int
2524 vdev_offline_locked(spa_t *spa, uint64_t guid, uint64_t flags)
2525 {
2526         vdev_t *vd, *tvd;
2527         int error = 0;
2528         uint64_t generation;
2529         metaslab_group_t *mg;
2530 
2531 top:
2532         spa_vdev_state_enter(spa, SCL_ALLOC);
2533 
2534         if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
2535                 return (spa_vdev_state_exit(spa, NULL, ENODEV));
2536 
2537         if (!vd->vdev_ops->vdev_op_leaf)
2538                 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
2539 
2540         tvd = vd->vdev_top;
2541         mg = tvd->vdev_mg;
2542         generation = spa->spa_config_generation + 1;
2543 
2544         /*
2545          * If the device isn't already offline, try to offline it.
2546          */
2547         if (!vd->vdev_offline) {
2548                 /*
2549                  * If this device has the only valid copy of some data,
2550                  * don't allow it to be offlined. Log devices are always
2551                  * expendable.
2552                  */
2553                 if (!tvd->vdev_islog && vd->vdev_aux == NULL &&
2554                     vdev_dtl_required(vd))
2555                         return (spa_vdev_state_exit(spa, NULL, EBUSY));
2556 
2557                 /*
2558                  * If the top-level is a slog and it has had allocations
2559                  * then proceed.  We check that the vdev's metaslab group
2560                  * is not NULL since it's possible that we may have just
2561                  * added this vdev but not yet initialized its metaslabs.
2562                  */
2563                 if (tvd->vdev_islog && mg != NULL) {
2564                         /*
2565                          * Prevent any future allocations.
2566                          */
2567                         metaslab_group_passivate(mg);
2568                         (void) spa_vdev_state_exit(spa, vd, 0);
2569 
2570                         error = spa_offline_log(spa);
2571 
2572                         spa_vdev_state_enter(spa, SCL_ALLOC);
2573 
2574                         /*
2575                          * Check to see if the config has changed.
2576                          */
2577                         if (error || generation != spa->spa_config_generation) {
2578                                 metaslab_group_activate(mg);
2579                                 if (error)
2580                                         return (spa_vdev_state_exit(spa,
2581                                             vd, error));
2582                                 (void) spa_vdev_state_exit(spa, vd, 0);
2583                                 goto top;
2584                         }
2585                         ASSERT0(tvd->vdev_stat.vs_alloc);
2586                 }
2587 
2588                 /*
2589                  * Offline this device and reopen its top-level vdev.
2590                  * If the top-level vdev is a log device then just offline
2591                  * it. Otherwise, if this action results in the top-level
2592                  * vdev becoming unusable, undo it and fail the request.
2593                  */
2594                 vd->vdev_offline = B_TRUE;
2595                 vdev_reopen(tvd);
2596 
2597                 if (!tvd->vdev_islog && vd->vdev_aux == NULL &&
2598                     vdev_is_dead(tvd)) {
2599                         vd->vdev_offline = B_FALSE;
2600                         vdev_reopen(tvd);
2601                         return (spa_vdev_state_exit(spa, NULL, EBUSY));
2602                 }
2603 
2604                 /*
2605                  * Add the device back into the metaslab rotor so that
2606                  * once we online the device it's open for business.
2607                  */
2608                 if (tvd->vdev_islog && mg != NULL)
2609                         metaslab_group_activate(mg);
2610         }
2611 
2612         vd->vdev_tmpoffline = !!(flags & ZFS_OFFLINE_TEMPORARY);
2613 
2614         return (spa_vdev_state_exit(spa, vd, 0));
2615 }
2616 
2617 int
2618 vdev_offline(spa_t *spa, uint64_t guid, uint64_t flags)
2619 {
2620         int error;
2621 
2622         mutex_enter(&spa->spa_vdev_top_lock);
2623         error = vdev_offline_locked(spa, guid, flags);
2624         mutex_exit(&spa->spa_vdev_top_lock);
2625 
2626         return (error);
2627 }
2628 
2629 /*
2630  * Clear the error counts associated with this vdev.  Unlike vdev_online() and
2631  * vdev_offline(), we assume the spa config is locked.  We also clear all
2632  * children.  If 'vd' is NULL, then the user wants to clear all vdevs.
2633  */
2634 void
2635 vdev_clear(spa_t *spa, vdev_t *vd)
2636 {
2637         vdev_t *rvd = spa->spa_root_vdev;
2638 
2639         ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
2640 
2641         if (vd == NULL)
2642                 vd = rvd;
2643 
2644         vd->vdev_stat.vs_read_errors = 0;
2645         vd->vdev_stat.vs_write_errors = 0;
2646         vd->vdev_stat.vs_checksum_errors = 0;
2647 
2648         for (int c = 0; c < vd->vdev_children; c++)
2649                 vdev_clear(spa, vd->vdev_child[c]);
2650 
2651         /*
2652          * If we're in the FAULTED state or have experienced failed I/O, then
2653          * clear the persistent state and attempt to reopen the device.  We
2654          * also mark the vdev config dirty, so that the new faulted state is
2655          * written out to disk.
2656          */
2657         if (vd->vdev_faulted || vd->vdev_degraded ||
2658             !vdev_readable(vd) || !vdev_writeable(vd)) {
2659 
2660                 /*
2661                  * When reopening in reponse to a clear event, it may be due to
2662                  * a fmadm repair request.  In this case, if the device is
2663                  * still broken, we want to still post the ereport again.
2664                  */
2665                 vd->vdev_forcefault = B_TRUE;
2666 
2667                 vd->vdev_faulted = vd->vdev_degraded = 0ULL;
2668                 vd->vdev_cant_read = B_FALSE;
2669                 vd->vdev_cant_write = B_FALSE;
2670 
2671                 vdev_reopen(vd == rvd ? rvd : vd->vdev_top);
2672 
2673                 vd->vdev_forcefault = B_FALSE;
2674 
2675                 if (vd != rvd && vdev_writeable(vd->vdev_top))
2676                         vdev_state_dirty(vd->vdev_top);
2677 
2678                 if (vd->vdev_aux == NULL && !vdev_is_dead(vd))
2679                         spa_async_request(spa, SPA_ASYNC_RESILVER);
2680 
2681                 spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_CLEAR);
2682         }
2683 
2684         /*
2685          * When clearing a FMA-diagnosed fault, we always want to
2686          * unspare the device, as we assume that the original spare was
2687          * done in response to the FMA fault.
2688          */
2689         if (!vdev_is_dead(vd) && vd->vdev_parent != NULL &&
2690             vd->vdev_parent->vdev_ops == &vdev_spare_ops &&
2691             vd->vdev_parent->vdev_child[0] == vd)
2692                 vd->vdev_unspare = B_TRUE;
2693 }
2694 
2695 boolean_t
2696 vdev_is_dead(vdev_t *vd)
2697 {
2698         /*
2699          * Holes and missing devices are always considered "dead".
2700          * This simplifies the code since we don't have to check for
2701          * these types of devices in the various code paths.
2702          * Instead we rely on the fact that we skip over dead devices
2703          * before issuing I/O to them.
2704          */
2705         return (vd->vdev_state < VDEV_STATE_DEGRADED || vd->vdev_ishole ||
2706             vd->vdev_ops == &vdev_missing_ops);
2707 }
2708 
2709 boolean_t
2710 vdev_readable(vdev_t *vd)
2711 {
2712         return (!vdev_is_dead(vd) && !vd->vdev_cant_read);
2713 }
2714 
2715 boolean_t
2716 vdev_writeable(vdev_t *vd)
2717 {
2718         return (!vdev_is_dead(vd) && !vd->vdev_cant_write);
2719 }
2720 
2721 boolean_t
2722 vdev_allocatable(vdev_t *vd)
2723 {
2724         uint64_t state = vd->vdev_state;
2725 
2726         /*
2727          * We currently allow allocations from vdevs which may be in the
2728          * process of reopening (i.e. VDEV_STATE_CLOSED). If the device
2729          * fails to reopen then we'll catch it later when we're holding
2730          * the proper locks.  Note that we have to get the vdev state
2731          * in a local variable because although it changes atomically,
2732          * we're asking two separate questions about it.
2733          */
2734         return (!(state < VDEV_STATE_DEGRADED && state != VDEV_STATE_CLOSED) &&
2735             !vd->vdev_cant_write && !vd->vdev_ishole &&
2736             vd->vdev_mg->mg_initialized);
2737 }
2738 
2739 boolean_t
2740 vdev_accessible(vdev_t *vd, zio_t *zio)
2741 {
2742         ASSERT(zio->io_vd == vd);
2743 
2744         if (vdev_is_dead(vd) || vd->vdev_remove_wanted)
2745                 return (B_FALSE);
2746 
2747         if (zio->io_type == ZIO_TYPE_READ)
2748                 return (!vd->vdev_cant_read);
2749 
2750         if (zio->io_type == ZIO_TYPE_WRITE)
2751                 return (!vd->vdev_cant_write);
2752 
2753         return (B_TRUE);
2754 }
2755 
2756 /*
2757  * Get statistics for the given vdev.
2758  */
2759 void
2760 vdev_get_stats(vdev_t *vd, vdev_stat_t *vs)
2761 {
2762         spa_t *spa = vd->vdev_spa;
2763         vdev_t *rvd = spa->spa_root_vdev;
2764         vdev_t *tvd = vd->vdev_top;
2765 
2766         ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
2767 
2768         mutex_enter(&vd->vdev_stat_lock);
2769         bcopy(&vd->vdev_stat, vs, sizeof (*vs));
2770         vs->vs_timestamp = gethrtime() - vs->vs_timestamp;
2771         vs->vs_state = vd->vdev_state;
2772         vs->vs_rsize = vdev_get_min_asize(vd);
2773         if (vd->vdev_ops->vdev_op_leaf)
2774                 vs->vs_rsize += VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE;
2775         /*
2776          * Report expandable space on top-level, non-auxillary devices only.
2777          * The expandable space is reported in terms of metaslab sized units
2778          * since that determines how much space the pool can expand.
2779          */
2780         if (vd->vdev_aux == NULL && tvd != NULL) {
2781                 vs->vs_esize = P2ALIGN(vd->vdev_max_asize - vd->vdev_asize -
2782                     spa->spa_bootsize, 1ULL << tvd->vdev_ms_shift);
2783         }
2784         if (vd->vdev_aux == NULL && vd == vd->vdev_top && !vd->vdev_ishole) {
2785                 vs->vs_fragmentation = vd->vdev_mg->mg_fragmentation;
2786         }
2787 
2788         /*
2789          * If we're getting stats on the root vdev, aggregate the I/O counts
2790          * over all top-level vdevs (i.e. the direct children of the root).
2791          */
2792         if (vd == rvd) {
2793                 for (int c = 0; c < rvd->vdev_children; c++) {
2794                         vdev_t *cvd = rvd->vdev_child[c];
2795                         vdev_stat_t *cvs = &cvd->vdev_stat;
2796 
2797                         for (int t = 0; t < ZIO_TYPES; t++) {
2798                                 vs->vs_ops[t] += cvs->vs_ops[t];
2799                                 vs->vs_bytes[t] += cvs->vs_bytes[t];
2800                         }
2801                         cvs->vs_scan_removing = cvd->vdev_removing;
2802                 }
2803         }
2804         mutex_exit(&vd->vdev_stat_lock);
2805 }
2806 
2807 void
2808 vdev_clear_stats(vdev_t *vd)
2809 {
2810         mutex_enter(&vd->vdev_stat_lock);
2811         vd->vdev_stat.vs_space = 0;
2812         vd->vdev_stat.vs_dspace = 0;
2813         vd->vdev_stat.vs_alloc = 0;
2814         mutex_exit(&vd->vdev_stat_lock);
2815 }
2816 
2817 void
2818 vdev_scan_stat_init(vdev_t *vd)
2819 {
2820         vdev_stat_t *vs = &vd->vdev_stat;
2821 
2822         for (int c = 0; c < vd->vdev_children; c++)
2823                 vdev_scan_stat_init(vd->vdev_child[c]);
2824 
2825         mutex_enter(&vd->vdev_stat_lock);
2826         vs->vs_scan_processed = 0;
2827         mutex_exit(&vd->vdev_stat_lock);
2828 }
2829 
2830 void
2831 vdev_stat_update(zio_t *zio, uint64_t psize)
2832 {
2833         spa_t *spa = zio->io_spa;
2834         vdev_t *rvd = spa->spa_root_vdev;
2835         vdev_t *vd = zio->io_vd ? zio->io_vd : rvd;
2836         vdev_t *pvd;
2837         uint64_t txg = zio->io_txg;
2838         vdev_stat_t *vs = &vd->vdev_stat;
2839         zio_type_t type = zio->io_type;
2840         int flags = zio->io_flags;
2841 
2842         /*
2843          * If this i/o is a gang leader, it didn't do any actual work.
2844          */
2845         if (zio->io_gang_tree)
2846                 return;
2847 
2848         if (zio->io_error == 0) {
2849                 /*
2850                  * If this is a root i/o, don't count it -- we've already
2851                  * counted the top-level vdevs, and vdev_get_stats() will
2852                  * aggregate them when asked.  This reduces contention on
2853                  * the root vdev_stat_lock and implicitly handles blocks
2854                  * that compress away to holes, for which there is no i/o.
2855                  * (Holes never create vdev children, so all the counters
2856                  * remain zero, which is what we want.)
2857                  *
2858                  * Note: this only applies to successful i/o (io_error == 0)
2859                  * because unlike i/o counts, errors are not additive.
2860                  * When reading a ditto block, for example, failure of
2861                  * one top-level vdev does not imply a root-level error.
2862                  */
2863                 if (vd == rvd)
2864                         return;
2865 
2866                 ASSERT(vd == zio->io_vd);
2867 
2868                 if (flags & ZIO_FLAG_IO_BYPASS)
2869                         return;
2870 
2871                 mutex_enter(&vd->vdev_stat_lock);
2872 
2873                 if (flags & ZIO_FLAG_IO_REPAIR) {
2874                         if (flags & ZIO_FLAG_SCAN_THREAD) {
2875                                 dsl_scan_phys_t *scn_phys =
2876                                     &spa->spa_dsl_pool->dp_scan->scn_phys;
2877                                 uint64_t *processed = &scn_phys->scn_processed;
2878 
2879                                 /* XXX cleanup? */
2880                                 if (vd->vdev_ops->vdev_op_leaf)
2881                                         atomic_add_64(processed, psize);
2882                                 vs->vs_scan_processed += psize;
2883                         }
2884 
2885                         if (flags & ZIO_FLAG_SELF_HEAL)
2886                                 vs->vs_self_healed += psize;
2887                 }
2888 
2889                 vs->vs_ops[type]++;
2890                 vs->vs_bytes[type] += psize;
2891 
2892                 mutex_exit(&vd->vdev_stat_lock);
2893                 return;
2894         }
2895 
2896         if (flags & ZIO_FLAG_SPECULATIVE)
2897                 return;
2898 
2899         /*
2900          * If this is an I/O error that is going to be retried, then ignore the
2901          * error.  Otherwise, the user may interpret B_FAILFAST I/O errors as
2902          * hard errors, when in reality they can happen for any number of
2903          * innocuous reasons (bus resets, MPxIO link failure, etc).
2904          */
2905         if (zio->io_error == EIO &&
2906             !(zio->io_flags & ZIO_FLAG_IO_RETRY))
2907                 return;
2908 
2909         /*
2910          * Intent logs writes won't propagate their error to the root
2911          * I/O so don't mark these types of failures as pool-level
2912          * errors.
2913          */
2914         if (zio->io_vd == NULL && (zio->io_flags & ZIO_FLAG_DONT_PROPAGATE))
2915                 return;
2916 
2917         mutex_enter(&vd->vdev_stat_lock);
2918         if (type == ZIO_TYPE_READ && !vdev_is_dead(vd)) {
2919                 if (zio->io_error == ECKSUM)
2920                         vs->vs_checksum_errors++;
2921                 else
2922                         vs->vs_read_errors++;
2923         }
2924         if (type == ZIO_TYPE_WRITE && !vdev_is_dead(vd))
2925                 vs->vs_write_errors++;
2926         mutex_exit(&vd->vdev_stat_lock);
2927 
2928         if (type == ZIO_TYPE_WRITE && txg != 0 &&
2929             (!(flags & ZIO_FLAG_IO_REPAIR) ||
2930             (flags & ZIO_FLAG_SCAN_THREAD) ||
2931             spa->spa_claiming)) {
2932                 /*
2933                  * This is either a normal write (not a repair), or it's
2934                  * a repair induced by the scrub thread, or it's a repair
2935                  * made by zil_claim() during spa_load() in the first txg.
2936                  * In the normal case, we commit the DTL change in the same
2937                  * txg as the block was born.  In the scrub-induced repair
2938                  * case, we know that scrubs run in first-pass syncing context,
2939                  * so we commit the DTL change in spa_syncing_txg(spa).
2940                  * In the zil_claim() case, we commit in spa_first_txg(spa).
2941                  *
2942                  * We currently do not make DTL entries for failed spontaneous
2943                  * self-healing writes triggered by normal (non-scrubbing)
2944                  * reads, because we have no transactional context in which to
2945                  * do so -- and it's not clear that it'd be desirable anyway.
2946                  */
2947                 if (vd->vdev_ops->vdev_op_leaf) {
2948                         uint64_t commit_txg = txg;
2949                         if (flags & ZIO_FLAG_SCAN_THREAD) {
2950                                 ASSERT(flags & ZIO_FLAG_IO_REPAIR);
2951                                 ASSERT(spa_sync_pass(spa) == 1);
2952                                 vdev_dtl_dirty(vd, DTL_SCRUB, txg, 1);
2953                                 commit_txg = spa_syncing_txg(spa);
2954                         } else if (spa->spa_claiming) {
2955                                 ASSERT(flags & ZIO_FLAG_IO_REPAIR);
2956                                 commit_txg = spa_first_txg(spa);
2957                         }
2958                         ASSERT(commit_txg >= spa_syncing_txg(spa));
2959                         if (vdev_dtl_contains(vd, DTL_MISSING, txg, 1))
2960                                 return;
2961                         for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
2962                                 vdev_dtl_dirty(pvd, DTL_PARTIAL, txg, 1);
2963                         vdev_dirty(vd->vdev_top, VDD_DTL, vd, commit_txg);
2964                 }
2965                 if (vd != rvd)
2966                         vdev_dtl_dirty(vd, DTL_MISSING, txg, 1);
2967         }
2968 }
2969 
2970 /*
2971  * Update the in-core space usage stats for this vdev, its metaslab class,
2972  * and the root vdev.
2973  */
2974 void
2975 vdev_space_update(vdev_t *vd, int64_t alloc_delta, int64_t defer_delta,
2976     int64_t space_delta)
2977 {
2978         int64_t dspace_delta = space_delta;
2979         spa_t *spa = vd->vdev_spa;
2980         vdev_t *rvd = spa->spa_root_vdev;
2981         metaslab_group_t *mg = vd->vdev_mg;
2982         metaslab_class_t *mc = mg ? mg->mg_class : NULL;
2983 
2984         ASSERT(vd == vd->vdev_top);
2985 
2986         /*
2987          * Apply the inverse of the psize-to-asize (ie. RAID-Z) space-expansion
2988          * factor.  We must calculate this here and not at the root vdev
2989          * because the root vdev's psize-to-asize is simply the max of its
2990          * childrens', thus not accurate enough for us.
2991          */
2992         ASSERT((dspace_delta & (SPA_MINBLOCKSIZE-1)) == 0);
2993         ASSERT(vd->vdev_deflate_ratio != 0 || vd->vdev_isl2cache);
2994         dspace_delta = (dspace_delta >> SPA_MINBLOCKSHIFT) *
2995             vd->vdev_deflate_ratio;
2996 
2997         mutex_enter(&vd->vdev_stat_lock);
2998         vd->vdev_stat.vs_alloc += alloc_delta;
2999         vd->vdev_stat.vs_space += space_delta;
3000         vd->vdev_stat.vs_dspace += dspace_delta;
3001         mutex_exit(&vd->vdev_stat_lock);
3002 
3003         if (mc == spa_normal_class(spa)) {
3004                 mutex_enter(&rvd->vdev_stat_lock);
3005                 rvd->vdev_stat.vs_alloc += alloc_delta;
3006                 rvd->vdev_stat.vs_space += space_delta;
3007                 rvd->vdev_stat.vs_dspace += dspace_delta;
3008                 mutex_exit(&rvd->vdev_stat_lock);
3009         }
3010 
3011         if (mc != NULL) {
3012                 ASSERT(rvd == vd->vdev_parent);
3013                 ASSERT(vd->vdev_ms_count != 0);
3014 
3015                 metaslab_class_space_update(mc,
3016                     alloc_delta, defer_delta, space_delta, dspace_delta);
3017         }
3018 }
3019 
3020 /*
3021  * Mark a top-level vdev's config as dirty, placing it on the dirty list
3022  * so that it will be written out next time the vdev configuration is synced.
3023  * If the root vdev is specified (vdev_top == NULL), dirty all top-level vdevs.
3024  */
3025 void
3026 vdev_config_dirty(vdev_t *vd)
3027 {
3028         spa_t *spa = vd->vdev_spa;
3029         vdev_t *rvd = spa->spa_root_vdev;
3030         int c;
3031 
3032         ASSERT(spa_writeable(spa));
3033 
3034         /*
3035          * If this is an aux vdev (as with l2cache and spare devices), then we
3036          * update the vdev config manually and set the sync flag.
3037          */
3038         if (vd->vdev_aux != NULL) {
3039                 spa_aux_vdev_t *sav = vd->vdev_aux;
3040                 nvlist_t **aux;
3041                 uint_t naux;
3042 
3043                 for (c = 0; c < sav->sav_count; c++) {
3044                         if (sav->sav_vdevs[c] == vd)
3045                                 break;
3046                 }
3047 
3048                 if (c == sav->sav_count) {
3049                         /*
3050                          * We're being removed.  There's nothing more to do.
3051                          */
3052                         ASSERT(sav->sav_sync == B_TRUE);
3053                         return;
3054                 }
3055 
3056                 sav->sav_sync = B_TRUE;
3057 
3058                 if (nvlist_lookup_nvlist_array(sav->sav_config,
3059                     ZPOOL_CONFIG_L2CACHE, &aux, &naux) != 0) {
3060                         VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
3061                             ZPOOL_CONFIG_SPARES, &aux, &naux) == 0);
3062                 }
3063 
3064                 ASSERT(c < naux);
3065 
3066                 /*
3067                  * Setting the nvlist in the middle if the array is a little
3068                  * sketchy, but it will work.
3069                  */
3070                 nvlist_free(aux[c]);
3071                 aux[c] = vdev_config_generate(spa, vd, B_TRUE, 0);
3072 
3073                 return;
3074         }
3075 
3076         /*
3077          * The dirty list is protected by the SCL_CONFIG lock.  The caller
3078          * must either hold SCL_CONFIG as writer, or must be the sync thread
3079          * (which holds SCL_CONFIG as reader).  There's only one sync thread,
3080          * so this is sufficient to ensure mutual exclusion.
3081          */
3082         ASSERT(spa_config_held(spa, SCL_CONFIG, RW_WRITER) ||
3083             (dsl_pool_sync_context(spa_get_dsl(spa)) &&
3084             spa_config_held(spa, SCL_CONFIG, RW_READER)));
3085 
3086         if (vd == rvd) {
3087                 for (c = 0; c < rvd->vdev_children; c++)
3088                         vdev_config_dirty(rvd->vdev_child[c]);
3089         } else {
3090                 ASSERT(vd == vd->vdev_top);
3091 
3092                 if (!list_link_active(&vd->vdev_config_dirty_node) &&
3093                     !vd->vdev_ishole)
3094                         list_insert_head(&spa->spa_config_dirty_list, vd);
3095         }
3096 }
3097 
3098 void
3099 vdev_config_clean(vdev_t *vd)
3100 {
3101         spa_t *spa = vd->vdev_spa;
3102 
3103         ASSERT(spa_config_held(spa, SCL_CONFIG, RW_WRITER) ||
3104             (dsl_pool_sync_context(spa_get_dsl(spa)) &&
3105             spa_config_held(spa, SCL_CONFIG, RW_READER)));
3106 
3107         ASSERT(list_link_active(&vd->vdev_config_dirty_node));
3108         list_remove(&spa->spa_config_dirty_list, vd);
3109 }
3110 
3111 /*
3112  * Mark a top-level vdev's state as dirty, so that the next pass of
3113  * spa_sync() can convert this into vdev_config_dirty().  We distinguish
3114  * the state changes from larger config changes because they require
3115  * much less locking, and are often needed for administrative actions.
3116  */
3117 void
3118 vdev_state_dirty(vdev_t *vd)
3119 {
3120         spa_t *spa = vd->vdev_spa;
3121 
3122         ASSERT(spa_writeable(spa));
3123         ASSERT(vd == vd->vdev_top);
3124 
3125         /*
3126          * The state list is protected by the SCL_STATE lock.  The caller
3127          * must either hold SCL_STATE as writer, or must be the sync thread
3128          * (which holds SCL_STATE as reader).  There's only one sync thread,
3129          * so this is sufficient to ensure mutual exclusion.
3130          */
3131         ASSERT(spa_config_held(spa, SCL_STATE, RW_WRITER) ||
3132             (dsl_pool_sync_context(spa_get_dsl(spa)) &&
3133             spa_config_held(spa, SCL_STATE, RW_READER)));
3134 
3135         if (!list_link_active(&vd->vdev_state_dirty_node) && !vd->vdev_ishole)
3136                 list_insert_head(&spa->spa_state_dirty_list, vd);
3137 }
3138 
3139 void
3140 vdev_state_clean(vdev_t *vd)
3141 {
3142         spa_t *spa = vd->vdev_spa;
3143 
3144         ASSERT(spa_config_held(spa, SCL_STATE, RW_WRITER) ||
3145             (dsl_pool_sync_context(spa_get_dsl(spa)) &&
3146             spa_config_held(spa, SCL_STATE, RW_READER)));
3147 
3148         ASSERT(list_link_active(&vd->vdev_state_dirty_node));
3149         list_remove(&spa->spa_state_dirty_list, vd);
3150 }
3151 
3152 /*
3153  * Propagate vdev state up from children to parent.
3154  */
3155 void
3156 vdev_propagate_state(vdev_t *vd)
3157 {
3158         spa_t *spa = vd->vdev_spa;
3159         vdev_t *rvd = spa->spa_root_vdev;
3160         int degraded = 0, faulted = 0;
3161         int corrupted = 0;
3162         vdev_t *child;
3163 
3164         if (vd->vdev_children > 0) {
3165                 for (int c = 0; c < vd->vdev_children; c++) {
3166                         child = vd->vdev_child[c];
3167 
3168                         /*
3169                          * Don't factor holes into the decision.
3170                          */
3171                         if (child->vdev_ishole)
3172                                 continue;
3173 
3174                         if (!vdev_readable(child) ||
3175                             (!vdev_writeable(child) && spa_writeable(spa))) {
3176                                 /*
3177                                  * Root special: if there is a top-level log
3178                                  * device, treat the root vdev as if it were
3179                                  * degraded.
3180                                  */
3181                                 if (child->vdev_islog && vd == rvd)
3182                                         degraded++;
3183                                 else
3184                                         faulted++;
3185                         } else if (child->vdev_state <= VDEV_STATE_DEGRADED) {
3186                                 degraded++;
3187                         }
3188 
3189                         if (child->vdev_stat.vs_aux == VDEV_AUX_CORRUPT_DATA)
3190                                 corrupted++;
3191                 }
3192 
3193                 vd->vdev_ops->vdev_op_state_change(vd, faulted, degraded);
3194 
3195                 /*
3196                  * Root special: if there is a top-level vdev that cannot be
3197                  * opened due to corrupted metadata, then propagate the root
3198                  * vdev's aux state as 'corrupt' rather than 'insufficient
3199                  * replicas'.
3200                  */
3201                 if (corrupted && vd == rvd &&
3202                     rvd->vdev_state == VDEV_STATE_CANT_OPEN)
3203                         vdev_set_state(rvd, B_FALSE, VDEV_STATE_CANT_OPEN,
3204                             VDEV_AUX_CORRUPT_DATA);
3205         }
3206 
3207         if (vd->vdev_parent)
3208                 vdev_propagate_state(vd->vdev_parent);
3209 }
3210 
3211 /*
3212  * Set a vdev's state.  If this is during an open, we don't update the parent
3213  * state, because we're in the process of opening children depth-first.
3214  * Otherwise, we propagate the change to the parent.
3215  *
3216  * If this routine places a device in a faulted state, an appropriate ereport is
3217  * generated.
3218  */
3219 void
3220 vdev_set_state(vdev_t *vd, boolean_t isopen, vdev_state_t state, vdev_aux_t aux)
3221 {
3222         uint64_t save_state;
3223         spa_t *spa = vd->vdev_spa;
3224 
3225         if (state == vd->vdev_state) {
3226                 vd->vdev_stat.vs_aux = aux;
3227                 return;
3228         }
3229 
3230         save_state = vd->vdev_state;
3231 
3232         vd->vdev_state = state;
3233         vd->vdev_stat.vs_aux = aux;
3234 
3235         /*
3236          * If we are setting the vdev state to anything but an open state, then
3237          * always close the underlying device unless the device has requested
3238          * a delayed close (i.e. we're about to remove or fault the device).
3239          * Otherwise, we keep accessible but invalid devices open forever.
3240          * We don't call vdev_close() itself, because that implies some extra
3241          * checks (offline, etc) that we don't want here.  This is limited to
3242          * leaf devices, because otherwise closing the device will affect other
3243          * children.
3244          */
3245         if (!vd->vdev_delayed_close && vdev_is_dead(vd) &&
3246             vd->vdev_ops->vdev_op_leaf)
3247                 vd->vdev_ops->vdev_op_close(vd);
3248 
3249         /*
3250          * If we have brought this vdev back into service, we need
3251          * to notify fmd so that it can gracefully repair any outstanding
3252          * cases due to a missing device.  We do this in all cases, even those
3253          * that probably don't correlate to a repaired fault.  This is sure to
3254          * catch all cases, and we let the zfs-retire agent sort it out.  If
3255          * this is a transient state it's OK, as the retire agent will
3256          * double-check the state of the vdev before repairing it.
3257          */
3258         if (state == VDEV_STATE_HEALTHY && vd->vdev_ops->vdev_op_leaf &&
3259             vd->vdev_prevstate != state)
3260                 zfs_post_state_change(spa, vd);
3261 
3262         if (vd->vdev_removed &&
3263             state == VDEV_STATE_CANT_OPEN &&
3264             (aux == VDEV_AUX_OPEN_FAILED || vd->vdev_checkremove)) {
3265                 /*
3266                  * If the previous state is set to VDEV_STATE_REMOVED, then this
3267                  * device was previously marked removed and someone attempted to
3268                  * reopen it.  If this failed due to a nonexistent device, then
3269                  * keep the device in the REMOVED state.  We also let this be if
3270                  * it is one of our special test online cases, which is only
3271                  * attempting to online the device and shouldn't generate an FMA
3272                  * fault.
3273                  */
3274                 vd->vdev_state = VDEV_STATE_REMOVED;
3275                 vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
3276         } else if (state == VDEV_STATE_REMOVED) {
3277                 vd->vdev_removed = B_TRUE;
3278         } else if (state == VDEV_STATE_CANT_OPEN) {
3279                 /*
3280                  * If we fail to open a vdev during an import or recovery, we
3281                  * mark it as "not available", which signifies that it was
3282                  * never there to begin with.  Failure to open such a device
3283                  * is not considered an error.
3284                  */
3285                 if ((spa_load_state(spa) == SPA_LOAD_IMPORT ||
3286                     spa_load_state(spa) == SPA_LOAD_RECOVER) &&
3287                     vd->vdev_ops->vdev_op_leaf)
3288                         vd->vdev_not_present = 1;
3289 
3290                 /*
3291                  * Post the appropriate ereport.  If the 'prevstate' field is
3292                  * set to something other than VDEV_STATE_UNKNOWN, it indicates
3293                  * that this is part of a vdev_reopen().  In this case, we don't
3294                  * want to post the ereport if the device was already in the
3295                  * CANT_OPEN state beforehand.
3296                  *
3297                  * If the 'checkremove' flag is set, then this is an attempt to
3298                  * online the device in response to an insertion event.  If we
3299                  * hit this case, then we have detected an insertion event for a
3300                  * faulted or offline device that wasn't in the removed state.
3301                  * In this scenario, we don't post an ereport because we are
3302                  * about to replace the device, or attempt an online with
3303                  * vdev_forcefault, which will generate the fault for us.
3304                  */
3305                 if ((vd->vdev_prevstate != state || vd->vdev_forcefault) &&
3306                     !vd->vdev_not_present && !vd->vdev_checkremove &&
3307                     vd != spa->spa_root_vdev) {
3308                         const char *class;
3309 
3310                         switch (aux) {
3311                         case VDEV_AUX_OPEN_FAILED:
3312                                 class = FM_EREPORT_ZFS_DEVICE_OPEN_FAILED;
3313                                 break;
3314                         case VDEV_AUX_CORRUPT_DATA:
3315                                 class = FM_EREPORT_ZFS_DEVICE_CORRUPT_DATA;
3316                                 break;
3317                         case VDEV_AUX_NO_REPLICAS:
3318                                 class = FM_EREPORT_ZFS_DEVICE_NO_REPLICAS;
3319                                 break;
3320                         case VDEV_AUX_BAD_GUID_SUM:
3321                                 class = FM_EREPORT_ZFS_DEVICE_BAD_GUID_SUM;
3322                                 break;
3323                         case VDEV_AUX_TOO_SMALL:
3324                                 class = FM_EREPORT_ZFS_DEVICE_TOO_SMALL;
3325                                 break;
3326                         case VDEV_AUX_BAD_LABEL:
3327                                 class = FM_EREPORT_ZFS_DEVICE_BAD_LABEL;
3328                                 break;
3329                         default:
3330                                 class = FM_EREPORT_ZFS_DEVICE_UNKNOWN;
3331                         }
3332 
3333                         zfs_ereport_post(class, spa, vd, NULL, save_state, 0);
3334                 }
3335 
3336                 /* Erase any notion of persistent removed state */
3337                 vd->vdev_removed = B_FALSE;
3338         } else {
3339                 vd->vdev_removed = B_FALSE;
3340         }
3341 
3342         if (!isopen && vd->vdev_parent)
3343                 vdev_propagate_state(vd->vdev_parent);
3344 }
3345 
3346 /*
3347  * Check the vdev configuration to ensure that it's capable of supporting
3348  * a root pool. We do not support partial configuration.
3349  * In addition, only a single top-level vdev is allowed.
3350  */
3351 boolean_t
3352 vdev_is_bootable(vdev_t *vd)
3353 {
3354         if (!vd->vdev_ops->vdev_op_leaf) {
3355                 char *vdev_type = vd->vdev_ops->vdev_op_type;
3356 
3357                 if (strcmp(vdev_type, VDEV_TYPE_ROOT) == 0 &&
3358                     vd->vdev_children > 1) {
3359                         return (B_FALSE);
3360                 } else if (strcmp(vdev_type, VDEV_TYPE_MISSING) == 0) {
3361                         return (B_FALSE);
3362                 }
3363         }
3364 
3365         for (int c = 0; c < vd->vdev_children; c++) {
3366                 if (!vdev_is_bootable(vd->vdev_child[c]))
3367                         return (B_FALSE);
3368         }
3369         return (B_TRUE);
3370 }
3371 
3372 /*
3373  * Load the state from the original vdev tree (ovd) which
3374  * we've retrieved from the MOS config object. If the original
3375  * vdev was offline or faulted then we transfer that state to the
3376  * device in the current vdev tree (nvd).
3377  */
3378 void
3379 vdev_load_log_state(vdev_t *nvd, vdev_t *ovd)
3380 {
3381         spa_t *spa = nvd->vdev_spa;
3382 
3383         ASSERT(nvd->vdev_top->vdev_islog);
3384         ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
3385         ASSERT3U(nvd->vdev_guid, ==, ovd->vdev_guid);
3386 
3387         for (int c = 0; c < nvd->vdev_children; c++)
3388                 vdev_load_log_state(nvd->vdev_child[c], ovd->vdev_child[c]);
3389 
3390         if (nvd->vdev_ops->vdev_op_leaf) {
3391                 /*
3392                  * Restore the persistent vdev state
3393                  */
3394                 nvd->vdev_offline = ovd->vdev_offline;
3395                 nvd->vdev_faulted = ovd->vdev_faulted;
3396                 nvd->vdev_degraded = ovd->vdev_degraded;
3397                 nvd->vdev_removed = ovd->vdev_removed;
3398         }
3399 }
3400 
3401 /*
3402  * Determine if a log device has valid content.  If the vdev was
3403  * removed or faulted in the MOS config then we know that
3404  * the content on the log device has already been written to the pool.
3405  */
3406 boolean_t
3407 vdev_log_state_valid(vdev_t *vd)
3408 {
3409         if (vd->vdev_ops->vdev_op_leaf && !vd->vdev_faulted &&
3410             !vd->vdev_removed)
3411                 return (B_TRUE);
3412 
3413         for (int c = 0; c < vd->vdev_children; c++)
3414                 if (vdev_log_state_valid(vd->vdev_child[c]))
3415                         return (B_TRUE);
3416 
3417         return (B_FALSE);
3418 }
3419 
3420 /*
3421  * Expand a vdev if possible.
3422  */
3423 void
3424 vdev_expand(vdev_t *vd, uint64_t txg)
3425 {
3426         ASSERT(vd->vdev_top == vd);
3427         ASSERT(spa_config_held(vd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
3428 
3429         if ((vd->vdev_asize >> vd->vdev_ms_shift) > vd->vdev_ms_count) {
3430                 VERIFY(vdev_metaslab_init(vd, txg) == 0);
3431                 vdev_config_dirty(vd);
3432         }
3433 }
3434 
3435 /*
3436  * Split a vdev.
3437  */
3438 void
3439 vdev_split(vdev_t *vd)
3440 {
3441         vdev_t *cvd, *pvd = vd->vdev_parent;
3442 
3443         vdev_remove_child(pvd, vd);
3444         vdev_compact_children(pvd);
3445 
3446         cvd = pvd->vdev_child[0];
3447         if (pvd->vdev_children == 1) {
3448                 vdev_remove_parent(cvd);
3449                 cvd->vdev_splitting = B_TRUE;
3450         }
3451         vdev_propagate_state(cvd);
3452 }
3453 
3454 void
3455 vdev_deadman(vdev_t *vd)
3456 {
3457         for (int c = 0; c < vd->vdev_children; c++) {
3458                 vdev_t *cvd = vd->vdev_child[c];
3459 
3460                 vdev_deadman(cvd);
3461         }
3462 
3463         if (vd->vdev_ops->vdev_op_leaf) {
3464                 vdev_queue_t *vq = &vd->vdev_queue;
3465 
3466                 mutex_enter(&vq->vq_lock);
3467                 if (avl_numnodes(&vq->vq_active_tree) > 0) {
3468                         spa_t *spa = vd->vdev_spa;
3469                         zio_t *fio;
3470                         uint64_t delta;
3471 
3472                         /*
3473                          * Look at the head of all the pending queues,
3474                          * if any I/O has been outstanding for longer than
3475                          * the spa_deadman_synctime we panic the system.
3476                          */
3477                         fio = avl_first(&vq->vq_active_tree);
3478                         delta = gethrtime() - fio->io_timestamp;
3479                         if (delta > spa_deadman_synctime(spa)) {
3480                                 zfs_dbgmsg("SLOW IO: zio timestamp %lluns, "
3481                                     "delta %lluns, last io %lluns",
3482                                     fio->io_timestamp, delta,
3483                                     vq->vq_io_complete_ts);
3484                                 fm_panic("I/O to pool '%s' appears to be "
3485                                     "hung.", spa_name(spa));
3486                         }
3487                 }
3488                 mutex_exit(&vq->vq_lock);
3489         }
3490 }