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