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