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