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) 2013 by Delphix. All rights reserved.
  25  * Copyright 2013 Nexenta Systems, Inc.  All rights reserved.
  26  */
  27 
  28 /*
  29  * This file contains all the routines used when modifying on-disk SPA state.
  30  * This includes opening, importing, destroying, exporting a pool, and syncing a
  31  * pool.
  32  */
  33 
  34 #include <sys/zfs_context.h>
  35 #include <sys/fm/fs/zfs.h>
  36 #include <sys/spa_impl.h>
  37 #include <sys/zio.h>
  38 #include <sys/zio_checksum.h>
  39 #include <sys/dmu.h>
  40 #include <sys/dmu_tx.h>
  41 #include <sys/zap.h>
  42 #include <sys/zil.h>
  43 #include <sys/ddt.h>
  44 #include <sys/vdev_impl.h>
  45 #include <sys/metaslab.h>
  46 #include <sys/metaslab_impl.h>
  47 #include <sys/uberblock_impl.h>
  48 #include <sys/txg.h>
  49 #include <sys/avl.h>
  50 #include <sys/dmu_traverse.h>
  51 #include <sys/dmu_objset.h>
  52 #include <sys/unique.h>
  53 #include <sys/dsl_pool.h>
  54 #include <sys/dsl_dataset.h>
  55 #include <sys/dsl_dir.h>
  56 #include <sys/dsl_prop.h>
  57 #include <sys/dsl_synctask.h>
  58 #include <sys/fs/zfs.h>
  59 #include <sys/arc.h>
  60 #include <sys/callb.h>
  61 #include <sys/systeminfo.h>
  62 #include <sys/spa_boot.h>
  63 #include <sys/zfs_ioctl.h>
  64 #include <sys/dsl_scan.h>
  65 #include <sys/zfeature.h>
  66 #include <sys/dsl_destroy.h>
  67 
  68 #ifdef  _KERNEL
  69 #include <sys/bootprops.h>
  70 #include <sys/callb.h>
  71 #include <sys/cpupart.h>
  72 #include <sys/pool.h>
  73 #include <sys/sysdc.h>
  74 #include <sys/zone.h>
  75 #endif  /* _KERNEL */
  76 
  77 #include "zfs_prop.h"
  78 #include "zfs_comutil.h"
  79 
  80 typedef enum zti_modes {
  81         ZTI_MODE_FIXED,                 /* value is # of threads (min 1) */
  82         ZTI_MODE_ONLINE_PERCENT,        /* value is % of online CPUs */
  83         ZTI_MODE_BATCH,                 /* cpu-intensive; value is ignored */
  84         ZTI_MODE_NULL,                  /* don't create a taskq */
  85         ZTI_NMODES
  86 } zti_modes_t;
  87 
  88 #define ZTI_P(n, q)     { ZTI_MODE_FIXED, (n), (q) }
  89 #define ZTI_PCT(n)      { ZTI_MODE_ONLINE_PERCENT, (n), 1 }
  90 #define ZTI_BATCH       { ZTI_MODE_BATCH, 0, 1 }
  91 #define ZTI_NULL        { ZTI_MODE_NULL, 0, 0 }
  92 
  93 #define ZTI_N(n)        ZTI_P(n, 1)
  94 #define ZTI_ONE         ZTI_N(1)
  95 
  96 typedef struct zio_taskq_info {
  97         zti_modes_t zti_mode;
  98         uint_t zti_value;
  99         uint_t zti_count;
 100 } zio_taskq_info_t;
 101 
 102 static const char *const zio_taskq_types[ZIO_TASKQ_TYPES] = {
 103         "issue", "issue_high", "intr", "intr_high"
 104 };
 105 
 106 /*
 107  * This table defines the taskq settings for each ZFS I/O type. When
 108  * initializing a pool, we use this table to create an appropriately sized
 109  * taskq. Some operations are low volume and therefore have a small, static
 110  * number of threads assigned to their taskqs using the ZTI_N(#) or ZTI_ONE
 111  * macros. Other operations process a large amount of data; the ZTI_BATCH
 112  * macro causes us to create a taskq oriented for throughput. Some operations
 113  * are so high frequency and short-lived that the taskq itself can become a a
 114  * point of lock contention. The ZTI_P(#, #) macro indicates that we need an
 115  * additional degree of parallelism specified by the number of threads per-
 116  * taskq and the number of taskqs; when dispatching an event in this case, the
 117  * particular taskq is chosen at random.
 118  *
 119  * The different taskq priorities are to handle the different contexts (issue
 120  * and interrupt) and then to reserve threads for ZIO_PRIORITY_NOW I/Os that
 121  * need to be handled with minimum delay.
 122  */
 123 const zio_taskq_info_t zio_taskqs[ZIO_TYPES][ZIO_TASKQ_TYPES] = {
 124         /* ISSUE        ISSUE_HIGH      INTR            INTR_HIGH */
 125         { ZTI_ONE,      ZTI_NULL,       ZTI_ONE,        ZTI_NULL }, /* NULL */
 126         { ZTI_N(8),     ZTI_NULL,       ZTI_BATCH,      ZTI_NULL }, /* READ */
 127         { ZTI_BATCH,    ZTI_N(5),       ZTI_N(8),       ZTI_N(5) }, /* WRITE */
 128         { ZTI_P(12, 8), ZTI_NULL,       ZTI_ONE,        ZTI_NULL }, /* FREE */
 129         { ZTI_ONE,      ZTI_NULL,       ZTI_ONE,        ZTI_NULL }, /* CLAIM */
 130         { ZTI_ONE,      ZTI_NULL,       ZTI_ONE,        ZTI_NULL }, /* IOCTL */
 131 };
 132 
 133 static void spa_sync_version(void *arg, dmu_tx_t *tx);
 134 static void spa_sync_props(void *arg, dmu_tx_t *tx);
 135 static boolean_t spa_has_active_shared_spare(spa_t *spa);
 136 static int spa_load_impl(spa_t *spa, uint64_t, nvlist_t *config,
 137     spa_load_state_t state, spa_import_type_t type, boolean_t mosconfig,
 138     char **ereport);
 139 static void spa_vdev_resilver_done(spa_t *spa);
 140 
 141 uint_t          zio_taskq_batch_pct = 100;      /* 1 thread per cpu in pset */
 142 id_t            zio_taskq_psrset_bind = PS_NONE;
 143 boolean_t       zio_taskq_sysdc = B_TRUE;       /* use SDC scheduling class */
 144 uint_t          zio_taskq_basedc = 80;          /* base duty cycle */
 145 
 146 boolean_t       spa_create_process = B_TRUE;    /* no process ==> no sysdc */
 147 extern int      zfs_sync_pass_deferred_free;
 148 
 149 /*
 150  * This (illegal) pool name is used when temporarily importing a spa_t in order
 151  * to get the vdev stats associated with the imported devices.
 152  */
 153 #define TRYIMPORT_NAME  "$import"
 154 
 155 /*
 156  * ==========================================================================
 157  * SPA properties routines
 158  * ==========================================================================
 159  */
 160 
 161 /*
 162  * Add a (source=src, propname=propval) list to an nvlist.
 163  */
 164 static void
 165 spa_prop_add_list(nvlist_t *nvl, zpool_prop_t prop, char *strval,
 166     uint64_t intval, zprop_source_t src)
 167 {
 168         const char *propname = zpool_prop_to_name(prop);
 169         nvlist_t *propval;
 170 
 171         VERIFY(nvlist_alloc(&propval, NV_UNIQUE_NAME, KM_SLEEP) == 0);
 172         VERIFY(nvlist_add_uint64(propval, ZPROP_SOURCE, src) == 0);
 173 
 174         if (strval != NULL)
 175                 VERIFY(nvlist_add_string(propval, ZPROP_VALUE, strval) == 0);
 176         else
 177                 VERIFY(nvlist_add_uint64(propval, ZPROP_VALUE, intval) == 0);
 178 
 179         VERIFY(nvlist_add_nvlist(nvl, propname, propval) == 0);
 180         nvlist_free(propval);
 181 }
 182 
 183 /*
 184  * Get property values from the spa configuration.
 185  */
 186 static void
 187 spa_prop_get_config(spa_t *spa, nvlist_t **nvp)
 188 {
 189         vdev_t *rvd = spa->spa_root_vdev;
 190         dsl_pool_t *pool = spa->spa_dsl_pool;
 191         uint64_t size;
 192         uint64_t alloc;
 193         uint64_t space;
 194         uint64_t cap, version;
 195         zprop_source_t src = ZPROP_SRC_NONE;
 196         spa_config_dirent_t *dp;
 197 
 198         ASSERT(MUTEX_HELD(&spa->spa_props_lock));
 199 
 200         if (rvd != NULL) {
 201                 alloc = metaslab_class_get_alloc(spa_normal_class(spa));
 202                 size = metaslab_class_get_space(spa_normal_class(spa));
 203                 spa_prop_add_list(*nvp, ZPOOL_PROP_NAME, spa_name(spa), 0, src);
 204                 spa_prop_add_list(*nvp, ZPOOL_PROP_SIZE, NULL, size, src);
 205                 spa_prop_add_list(*nvp, ZPOOL_PROP_ALLOCATED, NULL, alloc, src);
 206                 spa_prop_add_list(*nvp, ZPOOL_PROP_FREE, NULL,
 207                     size - alloc, src);
 208 
 209                 space = 0;
 210                 for (int c = 0; c < rvd->vdev_children; c++) {
 211                         vdev_t *tvd = rvd->vdev_child[c];
 212                         space += tvd->vdev_max_asize - tvd->vdev_asize;
 213                 }
 214                 spa_prop_add_list(*nvp, ZPOOL_PROP_EXPANDSZ, NULL, space,
 215                     src);
 216 
 217                 spa_prop_add_list(*nvp, ZPOOL_PROP_READONLY, NULL,
 218                     (spa_mode(spa) == FREAD), src);
 219 
 220                 cap = (size == 0) ? 0 : (alloc * 100 / size);
 221                 spa_prop_add_list(*nvp, ZPOOL_PROP_CAPACITY, NULL, cap, src);
 222 
 223                 spa_prop_add_list(*nvp, ZPOOL_PROP_DEDUPRATIO, NULL,
 224                     ddt_get_pool_dedup_ratio(spa), src);
 225 
 226                 spa_prop_add_list(*nvp, ZPOOL_PROP_HEALTH, NULL,
 227                     rvd->vdev_state, src);
 228 
 229                 version = spa_version(spa);
 230                 if (version == zpool_prop_default_numeric(ZPOOL_PROP_VERSION))
 231                         src = ZPROP_SRC_DEFAULT;
 232                 else
 233                         src = ZPROP_SRC_LOCAL;
 234                 spa_prop_add_list(*nvp, ZPOOL_PROP_VERSION, NULL, version, src);
 235         }
 236 
 237         if (pool != NULL) {
 238                 dsl_dir_t *freedir = pool->dp_free_dir;
 239 
 240                 /*
 241                  * The $FREE directory was introduced in SPA_VERSION_DEADLISTS,
 242                  * when opening pools before this version freedir will be NULL.
 243                  */
 244                 if (freedir != NULL) {
 245                         spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING, NULL,
 246                             freedir->dd_phys->dd_used_bytes, src);
 247                 } else {
 248                         spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING,
 249                             NULL, 0, src);
 250                 }
 251         }
 252 
 253         spa_prop_add_list(*nvp, ZPOOL_PROP_GUID, NULL, spa_guid(spa), src);
 254 
 255         if (spa->spa_comment != NULL) {
 256                 spa_prop_add_list(*nvp, ZPOOL_PROP_COMMENT, spa->spa_comment,
 257                     0, ZPROP_SRC_LOCAL);
 258         }
 259 
 260         if (spa->spa_root != NULL)
 261                 spa_prop_add_list(*nvp, ZPOOL_PROP_ALTROOT, spa->spa_root,
 262                     0, ZPROP_SRC_LOCAL);
 263 
 264         if ((dp = list_head(&spa->spa_config_list)) != NULL) {
 265                 if (dp->scd_path == NULL) {
 266                         spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
 267                             "none", 0, ZPROP_SRC_LOCAL);
 268                 } else if (strcmp(dp->scd_path, spa_config_path) != 0) {
 269                         spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
 270                             dp->scd_path, 0, ZPROP_SRC_LOCAL);
 271                 }
 272         }
 273 }
 274 
 275 /*
 276  * Get zpool property values.
 277  */
 278 int
 279 spa_prop_get(spa_t *spa, nvlist_t **nvp)
 280 {
 281         objset_t *mos = spa->spa_meta_objset;
 282         zap_cursor_t zc;
 283         zap_attribute_t za;
 284         int err;
 285 
 286         VERIFY(nvlist_alloc(nvp, NV_UNIQUE_NAME, KM_SLEEP) == 0);
 287 
 288         mutex_enter(&spa->spa_props_lock);
 289 
 290         /*
 291          * Get properties from the spa config.
 292          */
 293         spa_prop_get_config(spa, nvp);
 294 
 295         /* If no pool property object, no more prop to get. */
 296         if (mos == NULL || spa->spa_pool_props_object == 0) {
 297                 mutex_exit(&spa->spa_props_lock);
 298                 return (0);
 299         }
 300 
 301         /*
 302          * Get properties from the MOS pool property object.
 303          */
 304         for (zap_cursor_init(&zc, mos, spa->spa_pool_props_object);
 305             (err = zap_cursor_retrieve(&zc, &za)) == 0;
 306             zap_cursor_advance(&zc)) {
 307                 uint64_t intval = 0;
 308                 char *strval = NULL;
 309                 zprop_source_t src = ZPROP_SRC_DEFAULT;
 310                 zpool_prop_t prop;
 311 
 312                 if ((prop = zpool_name_to_prop(za.za_name)) == ZPROP_INVAL)
 313                         continue;
 314 
 315                 switch (za.za_integer_length) {
 316                 case 8:
 317                         /* integer property */
 318                         if (za.za_first_integer !=
 319                             zpool_prop_default_numeric(prop))
 320                                 src = ZPROP_SRC_LOCAL;
 321 
 322                         if (prop == ZPOOL_PROP_BOOTFS) {
 323                                 dsl_pool_t *dp;
 324                                 dsl_dataset_t *ds = NULL;
 325 
 326                                 dp = spa_get_dsl(spa);
 327                                 dsl_pool_config_enter(dp, FTAG);
 328                                 if (err = dsl_dataset_hold_obj(dp,
 329                                     za.za_first_integer, FTAG, &ds)) {
 330                                         dsl_pool_config_exit(dp, FTAG);
 331                                         break;
 332                                 }
 333 
 334                                 strval = kmem_alloc(
 335                                     MAXNAMELEN + strlen(MOS_DIR_NAME) + 1,
 336                                     KM_SLEEP);
 337                                 dsl_dataset_name(ds, strval);
 338                                 dsl_dataset_rele(ds, FTAG);
 339                                 dsl_pool_config_exit(dp, FTAG);
 340                         } else {
 341                                 strval = NULL;
 342                                 intval = za.za_first_integer;
 343                         }
 344 
 345                         spa_prop_add_list(*nvp, prop, strval, intval, src);
 346 
 347                         if (strval != NULL)
 348                                 kmem_free(strval,
 349                                     MAXNAMELEN + strlen(MOS_DIR_NAME) + 1);
 350 
 351                         break;
 352 
 353                 case 1:
 354                         /* string property */
 355                         strval = kmem_alloc(za.za_num_integers, KM_SLEEP);
 356                         err = zap_lookup(mos, spa->spa_pool_props_object,
 357                             za.za_name, 1, za.za_num_integers, strval);
 358                         if (err) {
 359                                 kmem_free(strval, za.za_num_integers);
 360                                 break;
 361                         }
 362                         spa_prop_add_list(*nvp, prop, strval, 0, src);
 363                         kmem_free(strval, za.za_num_integers);
 364                         break;
 365 
 366                 default:
 367                         break;
 368                 }
 369         }
 370         zap_cursor_fini(&zc);
 371         mutex_exit(&spa->spa_props_lock);
 372 out:
 373         if (err && err != ENOENT) {
 374                 nvlist_free(*nvp);
 375                 *nvp = NULL;
 376                 return (err);
 377         }
 378 
 379         return (0);
 380 }
 381 
 382 /*
 383  * Validate the given pool properties nvlist and modify the list
 384  * for the property values to be set.
 385  */
 386 static int
 387 spa_prop_validate(spa_t *spa, nvlist_t *props)
 388 {
 389         nvpair_t *elem;
 390         int error = 0, reset_bootfs = 0;
 391         uint64_t objnum = 0;
 392         boolean_t has_feature = B_FALSE;
 393 
 394         elem = NULL;
 395         while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
 396                 uint64_t intval;
 397                 char *strval, *slash, *check, *fname;
 398                 const char *propname = nvpair_name(elem);
 399                 zpool_prop_t prop = zpool_name_to_prop(propname);
 400 
 401                 switch (prop) {
 402                 case ZPROP_INVAL:
 403                         if (!zpool_prop_feature(propname)) {
 404                                 error = SET_ERROR(EINVAL);
 405                                 break;
 406                         }
 407 
 408                         /*
 409                          * Sanitize the input.
 410                          */
 411                         if (nvpair_type(elem) != DATA_TYPE_UINT64) {
 412                                 error = SET_ERROR(EINVAL);
 413                                 break;
 414                         }
 415 
 416                         if (nvpair_value_uint64(elem, &intval) != 0) {
 417                                 error = SET_ERROR(EINVAL);
 418                                 break;
 419                         }
 420 
 421                         if (intval != 0) {
 422                                 error = SET_ERROR(EINVAL);
 423                                 break;
 424                         }
 425 
 426                         fname = strchr(propname, '@') + 1;
 427                         if (zfeature_lookup_name(fname, NULL) != 0) {
 428                                 error = SET_ERROR(EINVAL);
 429                                 break;
 430                         }
 431 
 432                         has_feature = B_TRUE;
 433                         break;
 434 
 435                 case ZPOOL_PROP_VERSION:
 436                         error = nvpair_value_uint64(elem, &intval);
 437                         if (!error &&
 438                             (intval < spa_version(spa) ||
 439                             intval > SPA_VERSION_BEFORE_FEATURES ||
 440                             has_feature))
 441                                 error = SET_ERROR(EINVAL);
 442                         break;
 443 
 444                 case ZPOOL_PROP_DELEGATION:
 445                 case ZPOOL_PROP_AUTOREPLACE:
 446                 case ZPOOL_PROP_LISTSNAPS:
 447                 case ZPOOL_PROP_AUTOEXPAND:
 448                         error = nvpair_value_uint64(elem, &intval);
 449                         if (!error && intval > 1)
 450                                 error = SET_ERROR(EINVAL);
 451                         break;
 452 
 453                 case ZPOOL_PROP_BOOTFS:
 454                         /*
 455                          * If the pool version is less than SPA_VERSION_BOOTFS,
 456                          * or the pool is still being created (version == 0),
 457                          * the bootfs property cannot be set.
 458                          */
 459                         if (spa_version(spa) < SPA_VERSION_BOOTFS) {
 460                                 error = SET_ERROR(ENOTSUP);
 461                                 break;
 462                         }
 463 
 464                         /*
 465                          * Make sure the vdev config is bootable
 466                          */
 467                         if (!vdev_is_bootable(spa->spa_root_vdev)) {
 468                                 error = SET_ERROR(ENOTSUP);
 469                                 break;
 470                         }
 471 
 472                         reset_bootfs = 1;
 473 
 474                         error = nvpair_value_string(elem, &strval);
 475 
 476                         if (!error) {
 477                                 objset_t *os;
 478                                 uint64_t compress;
 479 
 480                                 if (strval == NULL || strval[0] == '\0') {
 481                                         objnum = zpool_prop_default_numeric(
 482                                             ZPOOL_PROP_BOOTFS);
 483                                         break;
 484                                 }
 485 
 486                                 if (error = dmu_objset_hold(strval, FTAG, &os))
 487                                         break;
 488 
 489                                 /* Must be ZPL and not gzip compressed. */
 490 
 491                                 if (dmu_objset_type(os) != DMU_OST_ZFS) {
 492                                         error = SET_ERROR(ENOTSUP);
 493                                 } else if ((error =
 494                                     dsl_prop_get_int_ds(dmu_objset_ds(os),
 495                                     zfs_prop_to_name(ZFS_PROP_COMPRESSION),
 496                                     &compress)) == 0 &&
 497                                     !BOOTFS_COMPRESS_VALID(compress)) {
 498                                         error = SET_ERROR(ENOTSUP);
 499                                 } else {
 500                                         objnum = dmu_objset_id(os);
 501                                 }
 502                                 dmu_objset_rele(os, FTAG);
 503                         }
 504                         break;
 505 
 506                 case ZPOOL_PROP_FAILUREMODE:
 507                         error = nvpair_value_uint64(elem, &intval);
 508                         if (!error && (intval < ZIO_FAILURE_MODE_WAIT ||
 509                             intval > ZIO_FAILURE_MODE_PANIC))
 510                                 error = SET_ERROR(EINVAL);
 511 
 512                         /*
 513                          * This is a special case which only occurs when
 514                          * the pool has completely failed. This allows
 515                          * the user to change the in-core failmode property
 516                          * without syncing it out to disk (I/Os might
 517                          * currently be blocked). We do this by returning
 518                          * EIO to the caller (spa_prop_set) to trick it
 519                          * into thinking we encountered a property validation
 520                          * error.
 521                          */
 522                         if (!error && spa_suspended(spa)) {
 523                                 spa->spa_failmode = intval;
 524                                 error = SET_ERROR(EIO);
 525                         }
 526                         break;
 527 
 528                 case ZPOOL_PROP_CACHEFILE:
 529                         if ((error = nvpair_value_string(elem, &strval)) != 0)
 530                                 break;
 531 
 532                         if (strval[0] == '\0')
 533                                 break;
 534 
 535                         if (strcmp(strval, "none") == 0)
 536                                 break;
 537 
 538                         if (strval[0] != '/') {
 539                                 error = SET_ERROR(EINVAL);
 540                                 break;
 541                         }
 542 
 543                         slash = strrchr(strval, '/');
 544                         ASSERT(slash != NULL);
 545 
 546                         if (slash[1] == '\0' || strcmp(slash, "/.") == 0 ||
 547                             strcmp(slash, "/..") == 0)
 548                                 error = SET_ERROR(EINVAL);
 549                         break;
 550 
 551                 case ZPOOL_PROP_COMMENT:
 552                         if ((error = nvpair_value_string(elem, &strval)) != 0)
 553                                 break;
 554                         for (check = strval; *check != '\0'; check++) {
 555                                 /*
 556                                  * The kernel doesn't have an easy isprint()
 557                                  * check.  For this kernel check, we merely
 558                                  * check ASCII apart from DEL.  Fix this if
 559                                  * there is an easy-to-use kernel isprint().
 560                                  */
 561                                 if (*check >= 0x7f) {
 562                                         error = SET_ERROR(EINVAL);
 563                                         break;
 564                                 }
 565                                 check++;
 566                         }
 567                         if (strlen(strval) > ZPROP_MAX_COMMENT)
 568                                 error = E2BIG;
 569                         break;
 570 
 571                 case ZPOOL_PROP_DEDUPDITTO:
 572                         if (spa_version(spa) < SPA_VERSION_DEDUP)
 573                                 error = SET_ERROR(ENOTSUP);
 574                         else
 575                                 error = nvpair_value_uint64(elem, &intval);
 576                         if (error == 0 &&
 577                             intval != 0 && intval < ZIO_DEDUPDITTO_MIN)
 578                                 error = SET_ERROR(EINVAL);
 579                         break;
 580                 }
 581 
 582                 if (error)
 583                         break;
 584         }
 585 
 586         if (!error && reset_bootfs) {
 587                 error = nvlist_remove(props,
 588                     zpool_prop_to_name(ZPOOL_PROP_BOOTFS), DATA_TYPE_STRING);
 589 
 590                 if (!error) {
 591                         error = nvlist_add_uint64(props,
 592                             zpool_prop_to_name(ZPOOL_PROP_BOOTFS), objnum);
 593                 }
 594         }
 595 
 596         return (error);
 597 }
 598 
 599 void
 600 spa_configfile_set(spa_t *spa, nvlist_t *nvp, boolean_t need_sync)
 601 {
 602         char *cachefile;
 603         spa_config_dirent_t *dp;
 604 
 605         if (nvlist_lookup_string(nvp, zpool_prop_to_name(ZPOOL_PROP_CACHEFILE),
 606             &cachefile) != 0)
 607                 return;
 608 
 609         dp = kmem_alloc(sizeof (spa_config_dirent_t),
 610             KM_SLEEP);
 611 
 612         if (cachefile[0] == '\0')
 613                 dp->scd_path = spa_strdup(spa_config_path);
 614         else if (strcmp(cachefile, "none") == 0)
 615                 dp->scd_path = NULL;
 616         else
 617                 dp->scd_path = spa_strdup(cachefile);
 618 
 619         list_insert_head(&spa->spa_config_list, dp);
 620         if (need_sync)
 621                 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
 622 }
 623 
 624 int
 625 spa_prop_set(spa_t *spa, nvlist_t *nvp)
 626 {
 627         int error;
 628         nvpair_t *elem = NULL;
 629         boolean_t need_sync = B_FALSE;
 630 
 631         if ((error = spa_prop_validate(spa, nvp)) != 0)
 632                 return (error);
 633 
 634         while ((elem = nvlist_next_nvpair(nvp, elem)) != NULL) {
 635                 zpool_prop_t prop = zpool_name_to_prop(nvpair_name(elem));
 636 
 637                 if (prop == ZPOOL_PROP_CACHEFILE ||
 638                     prop == ZPOOL_PROP_ALTROOT ||
 639                     prop == ZPOOL_PROP_READONLY)
 640                         continue;
 641 
 642                 if (prop == ZPOOL_PROP_VERSION || prop == ZPROP_INVAL) {
 643                         uint64_t ver;
 644 
 645                         if (prop == ZPOOL_PROP_VERSION) {
 646                                 VERIFY(nvpair_value_uint64(elem, &ver) == 0);
 647                         } else {
 648                                 ASSERT(zpool_prop_feature(nvpair_name(elem)));
 649                                 ver = SPA_VERSION_FEATURES;
 650                                 need_sync = B_TRUE;
 651                         }
 652 
 653                         /* Save time if the version is already set. */
 654                         if (ver == spa_version(spa))
 655                                 continue;
 656 
 657                         /*
 658                          * In addition to the pool directory object, we might
 659                          * create the pool properties object, the features for
 660                          * read object, the features for write object, or the
 661                          * feature descriptions object.
 662                          */
 663                         error = dsl_sync_task(spa->spa_name, NULL,
 664                             spa_sync_version, &ver, 6);
 665                         if (error)
 666                                 return (error);
 667                         continue;
 668                 }
 669 
 670                 need_sync = B_TRUE;
 671                 break;
 672         }
 673 
 674         if (need_sync) {
 675                 return (dsl_sync_task(spa->spa_name, NULL, spa_sync_props,
 676                     nvp, 6));
 677         }
 678 
 679         return (0);
 680 }
 681 
 682 /*
 683  * If the bootfs property value is dsobj, clear it.
 684  */
 685 void
 686 spa_prop_clear_bootfs(spa_t *spa, uint64_t dsobj, dmu_tx_t *tx)
 687 {
 688         if (spa->spa_bootfs == dsobj && spa->spa_pool_props_object != 0) {
 689                 VERIFY(zap_remove(spa->spa_meta_objset,
 690                     spa->spa_pool_props_object,
 691                     zpool_prop_to_name(ZPOOL_PROP_BOOTFS), tx) == 0);
 692                 spa->spa_bootfs = 0;
 693         }
 694 }
 695 
 696 /*ARGSUSED*/
 697 static int
 698 spa_change_guid_check(void *arg, dmu_tx_t *tx)
 699 {
 700         uint64_t *newguid = arg;
 701         spa_t *spa = dmu_tx_pool(tx)->dp_spa;
 702         vdev_t *rvd = spa->spa_root_vdev;
 703         uint64_t vdev_state;
 704 
 705         spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
 706         vdev_state = rvd->vdev_state;
 707         spa_config_exit(spa, SCL_STATE, FTAG);
 708 
 709         if (vdev_state != VDEV_STATE_HEALTHY)
 710                 return (SET_ERROR(ENXIO));
 711 
 712         ASSERT3U(spa_guid(spa), !=, *newguid);
 713 
 714         return (0);
 715 }
 716 
 717 static void
 718 spa_change_guid_sync(void *arg, dmu_tx_t *tx)
 719 {
 720         uint64_t *newguid = arg;
 721         spa_t *spa = dmu_tx_pool(tx)->dp_spa;
 722         uint64_t oldguid;
 723         vdev_t *rvd = spa->spa_root_vdev;
 724 
 725         oldguid = spa_guid(spa);
 726 
 727         spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
 728         rvd->vdev_guid = *newguid;
 729         rvd->vdev_guid_sum += (*newguid - oldguid);
 730         vdev_config_dirty(rvd);
 731         spa_config_exit(spa, SCL_STATE, FTAG);
 732 
 733         spa_history_log_internal(spa, "guid change", tx, "old=%llu new=%llu",
 734             oldguid, *newguid);
 735 }
 736 
 737 /*
 738  * Change the GUID for the pool.  This is done so that we can later
 739  * re-import a pool built from a clone of our own vdevs.  We will modify
 740  * the root vdev's guid, our own pool guid, and then mark all of our
 741  * vdevs dirty.  Note that we must make sure that all our vdevs are
 742  * online when we do this, or else any vdevs that weren't present
 743  * would be orphaned from our pool.  We are also going to issue a
 744  * sysevent to update any watchers.
 745  */
 746 int
 747 spa_change_guid(spa_t *spa)
 748 {
 749         int error;
 750         uint64_t guid;
 751 
 752         mutex_enter(&spa_namespace_lock);
 753         guid = spa_generate_guid(NULL);
 754 
 755         error = dsl_sync_task(spa->spa_name, spa_change_guid_check,
 756             spa_change_guid_sync, &guid, 5);
 757 
 758         if (error == 0) {
 759                 spa_config_sync(spa, B_FALSE, B_TRUE);
 760                 spa_event_notify(spa, NULL, ESC_ZFS_POOL_REGUID);
 761         }
 762 
 763         mutex_exit(&spa_namespace_lock);
 764 
 765         return (error);
 766 }
 767 
 768 /*
 769  * ==========================================================================
 770  * SPA state manipulation (open/create/destroy/import/export)
 771  * ==========================================================================
 772  */
 773 
 774 static int
 775 spa_error_entry_compare(const void *a, const void *b)
 776 {
 777         spa_error_entry_t *sa = (spa_error_entry_t *)a;
 778         spa_error_entry_t *sb = (spa_error_entry_t *)b;
 779         int ret;
 780 
 781         ret = bcmp(&sa->se_bookmark, &sb->se_bookmark,
 782             sizeof (zbookmark_t));
 783 
 784         if (ret < 0)
 785                 return (-1);
 786         else if (ret > 0)
 787                 return (1);
 788         else
 789                 return (0);
 790 }
 791 
 792 /*
 793  * Utility function which retrieves copies of the current logs and
 794  * re-initializes them in the process.
 795  */
 796 void
 797 spa_get_errlists(spa_t *spa, avl_tree_t *last, avl_tree_t *scrub)
 798 {
 799         ASSERT(MUTEX_HELD(&spa->spa_errlist_lock));
 800 
 801         bcopy(&spa->spa_errlist_last, last, sizeof (avl_tree_t));
 802         bcopy(&spa->spa_errlist_scrub, scrub, sizeof (avl_tree_t));
 803 
 804         avl_create(&spa->spa_errlist_scrub,
 805             spa_error_entry_compare, sizeof (spa_error_entry_t),
 806             offsetof(spa_error_entry_t, se_avl));
 807         avl_create(&spa->spa_errlist_last,
 808             spa_error_entry_compare, sizeof (spa_error_entry_t),
 809             offsetof(spa_error_entry_t, se_avl));
 810 }
 811 
 812 static void
 813 spa_taskqs_init(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
 814 {
 815         const zio_taskq_info_t *ztip = &zio_taskqs[t][q];
 816         enum zti_modes mode = ztip->zti_mode;
 817         uint_t value = ztip->zti_value;
 818         uint_t count = ztip->zti_count;
 819         spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
 820         char name[32];
 821         uint_t flags = 0;
 822         boolean_t batch = B_FALSE;
 823 
 824         if (mode == ZTI_MODE_NULL) {
 825                 tqs->stqs_count = 0;
 826                 tqs->stqs_taskq = NULL;
 827                 return;
 828         }
 829 
 830         ASSERT3U(count, >, 0);
 831 
 832         tqs->stqs_count = count;
 833         tqs->stqs_taskq = kmem_alloc(count * sizeof (taskq_t *), KM_SLEEP);
 834 
 835         for (uint_t i = 0; i < count; i++) {
 836                 taskq_t *tq;
 837 
 838                 switch (mode) {
 839                 case ZTI_MODE_FIXED:
 840                         ASSERT3U(value, >=, 1);
 841                         value = MAX(value, 1);
 842                         break;
 843 
 844                 case ZTI_MODE_BATCH:
 845                         batch = B_TRUE;
 846                         flags |= TASKQ_THREADS_CPU_PCT;
 847                         value = zio_taskq_batch_pct;
 848                         break;
 849 
 850                 case ZTI_MODE_ONLINE_PERCENT:
 851                         flags |= TASKQ_THREADS_CPU_PCT;
 852                         break;
 853 
 854                 default:
 855                         panic("unrecognized mode for %s_%s taskq (%u:%u) in "
 856                             "spa_activate()",
 857                             zio_type_name[t], zio_taskq_types[q], mode, value);
 858                         break;
 859                 }
 860 
 861                 if (count > 1) {
 862                         (void) snprintf(name, sizeof (name), "%s_%s_%u",
 863                             zio_type_name[t], zio_taskq_types[q], i);
 864                 } else {
 865                         (void) snprintf(name, sizeof (name), "%s_%s",
 866                             zio_type_name[t], zio_taskq_types[q]);
 867                 }
 868 
 869                 if (zio_taskq_sysdc && spa->spa_proc != &p0) {
 870                         if (batch)
 871                                 flags |= TASKQ_DC_BATCH;
 872 
 873                         tq = taskq_create_sysdc(name, value, 50, INT_MAX,
 874                             spa->spa_proc, zio_taskq_basedc, flags);
 875                 } else {
 876                         tq = taskq_create_proc(name, value, maxclsyspri, 50,
 877                             INT_MAX, spa->spa_proc, flags);
 878                 }
 879 
 880                 tqs->stqs_taskq[i] = tq;
 881         }
 882 }
 883 
 884 static void
 885 spa_taskqs_fini(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
 886 {
 887         spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
 888 
 889         if (tqs->stqs_taskq == NULL) {
 890                 ASSERT0(tqs->stqs_count);
 891                 return;
 892         }
 893 
 894         for (uint_t i = 0; i < tqs->stqs_count; i++) {
 895                 ASSERT3P(tqs->stqs_taskq[i], !=, NULL);
 896                 taskq_destroy(tqs->stqs_taskq[i]);
 897         }
 898 
 899         kmem_free(tqs->stqs_taskq, tqs->stqs_count * sizeof (taskq_t *));
 900         tqs->stqs_taskq = NULL;
 901 }
 902 
 903 /*
 904  * Dispatch a task to the appropriate taskq for the ZFS I/O type and priority.
 905  * Note that a type may have multiple discrete taskqs to avoid lock contention
 906  * on the taskq itself. In that case we choose which taskq at random by using
 907  * the low bits of gethrtime().
 908  */
 909 void
 910 spa_taskq_dispatch_ent(spa_t *spa, zio_type_t t, zio_taskq_type_t q,
 911     task_func_t *func, void *arg, uint_t flags, taskq_ent_t *ent)
 912 {
 913         spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
 914         taskq_t *tq;
 915 
 916         ASSERT3P(tqs->stqs_taskq, !=, NULL);
 917         ASSERT3U(tqs->stqs_count, !=, 0);
 918 
 919         if (tqs->stqs_count == 1) {
 920                 tq = tqs->stqs_taskq[0];
 921         } else {
 922                 tq = tqs->stqs_taskq[gethrtime() % tqs->stqs_count];
 923         }
 924 
 925         taskq_dispatch_ent(tq, func, arg, flags, ent);
 926 }
 927 
 928 static void
 929 spa_create_zio_taskqs(spa_t *spa)
 930 {
 931         for (int t = 0; t < ZIO_TYPES; t++) {
 932                 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
 933                         spa_taskqs_init(spa, t, q);
 934                 }
 935         }
 936 }
 937 
 938 #ifdef _KERNEL
 939 static void
 940 spa_thread(void *arg)
 941 {
 942         callb_cpr_t cprinfo;
 943 
 944         spa_t *spa = arg;
 945         user_t *pu = PTOU(curproc);
 946 
 947         CALLB_CPR_INIT(&cprinfo, &spa->spa_proc_lock, callb_generic_cpr,
 948             spa->spa_name);
 949 
 950         ASSERT(curproc != &p0);
 951         (void) snprintf(pu->u_psargs, sizeof (pu->u_psargs),
 952             "zpool-%s", spa->spa_name);
 953         (void) strlcpy(pu->u_comm, pu->u_psargs, sizeof (pu->u_comm));
 954 
 955         /* bind this thread to the requested psrset */
 956         if (zio_taskq_psrset_bind != PS_NONE) {
 957                 pool_lock();
 958                 mutex_enter(&cpu_lock);
 959                 mutex_enter(&pidlock);
 960                 mutex_enter(&curproc->p_lock);
 961 
 962                 if (cpupart_bind_thread(curthread, zio_taskq_psrset_bind,
 963                     0, NULL, NULL) == 0)  {
 964                         curthread->t_bind_pset = zio_taskq_psrset_bind;
 965                 } else {
 966                         cmn_err(CE_WARN,
 967                             "Couldn't bind process for zfs pool \"%s\" to "
 968                             "pset %d\n", spa->spa_name, zio_taskq_psrset_bind);
 969                 }
 970 
 971                 mutex_exit(&curproc->p_lock);
 972                 mutex_exit(&pidlock);
 973                 mutex_exit(&cpu_lock);
 974                 pool_unlock();
 975         }
 976 
 977         if (zio_taskq_sysdc) {
 978                 sysdc_thread_enter(curthread, 100, 0);
 979         }
 980 
 981         spa->spa_proc = curproc;
 982         spa->spa_did = curthread->t_did;
 983 
 984         spa_create_zio_taskqs(spa);
 985 
 986         mutex_enter(&spa->spa_proc_lock);
 987         ASSERT(spa->spa_proc_state == SPA_PROC_CREATED);
 988 
 989         spa->spa_proc_state = SPA_PROC_ACTIVE;
 990         cv_broadcast(&spa->spa_proc_cv);
 991 
 992         CALLB_CPR_SAFE_BEGIN(&cprinfo);
 993         while (spa->spa_proc_state == SPA_PROC_ACTIVE)
 994                 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
 995         CALLB_CPR_SAFE_END(&cprinfo, &spa->spa_proc_lock);
 996 
 997         ASSERT(spa->spa_proc_state == SPA_PROC_DEACTIVATE);
 998         spa->spa_proc_state = SPA_PROC_GONE;
 999         spa->spa_proc = &p0;
1000         cv_broadcast(&spa->spa_proc_cv);
1001         CALLB_CPR_EXIT(&cprinfo);   /* drops spa_proc_lock */
1002 
1003         mutex_enter(&curproc->p_lock);
1004         lwp_exit();
1005 }
1006 #endif
1007 
1008 /*
1009  * Activate an uninitialized pool.
1010  */
1011 static void
1012 spa_activate(spa_t *spa, int mode)
1013 {
1014         ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
1015 
1016         spa->spa_state = POOL_STATE_ACTIVE;
1017         spa->spa_mode = mode;
1018 
1019         spa->spa_normal_class = metaslab_class_create(spa, zfs_metaslab_ops);
1020         spa->spa_log_class = metaslab_class_create(spa, zfs_metaslab_ops);
1021 
1022         /* Try to create a covering process */
1023         mutex_enter(&spa->spa_proc_lock);
1024         ASSERT(spa->spa_proc_state == SPA_PROC_NONE);
1025         ASSERT(spa->spa_proc == &p0);
1026         spa->spa_did = 0;
1027 
1028         /* Only create a process if we're going to be around a while. */
1029         if (spa_create_process && strcmp(spa->spa_name, TRYIMPORT_NAME) != 0) {
1030                 if (newproc(spa_thread, (caddr_t)spa, syscid, maxclsyspri,
1031                     NULL, 0) == 0) {
1032                         spa->spa_proc_state = SPA_PROC_CREATED;
1033                         while (spa->spa_proc_state == SPA_PROC_CREATED) {
1034                                 cv_wait(&spa->spa_proc_cv,
1035                                     &spa->spa_proc_lock);
1036                         }
1037                         ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1038                         ASSERT(spa->spa_proc != &p0);
1039                         ASSERT(spa->spa_did != 0);
1040                 } else {
1041 #ifdef _KERNEL
1042                         cmn_err(CE_WARN,
1043                             "Couldn't create process for zfs pool \"%s\"\n",
1044                             spa->spa_name);
1045 #endif
1046                 }
1047         }
1048         mutex_exit(&spa->spa_proc_lock);
1049 
1050         /* If we didn't create a process, we need to create our taskqs. */
1051         if (spa->spa_proc == &p0) {
1052                 spa_create_zio_taskqs(spa);
1053         }
1054 
1055         list_create(&spa->spa_config_dirty_list, sizeof (vdev_t),
1056             offsetof(vdev_t, vdev_config_dirty_node));
1057         list_create(&spa->spa_state_dirty_list, sizeof (vdev_t),
1058             offsetof(vdev_t, vdev_state_dirty_node));
1059 
1060         txg_list_create(&spa->spa_vdev_txg_list,
1061             offsetof(struct vdev, vdev_txg_node));
1062 
1063         avl_create(&spa->spa_errlist_scrub,
1064             spa_error_entry_compare, sizeof (spa_error_entry_t),
1065             offsetof(spa_error_entry_t, se_avl));
1066         avl_create(&spa->spa_errlist_last,
1067             spa_error_entry_compare, sizeof (spa_error_entry_t),
1068             offsetof(spa_error_entry_t, se_avl));
1069 }
1070 
1071 /*
1072  * Opposite of spa_activate().
1073  */
1074 static void
1075 spa_deactivate(spa_t *spa)
1076 {
1077         ASSERT(spa->spa_sync_on == B_FALSE);
1078         ASSERT(spa->spa_dsl_pool == NULL);
1079         ASSERT(spa->spa_root_vdev == NULL);
1080         ASSERT(spa->spa_async_zio_root == NULL);
1081         ASSERT(spa->spa_state != POOL_STATE_UNINITIALIZED);
1082 
1083         txg_list_destroy(&spa->spa_vdev_txg_list);
1084 
1085         list_destroy(&spa->spa_config_dirty_list);
1086         list_destroy(&spa->spa_state_dirty_list);
1087 
1088         for (int t = 0; t < ZIO_TYPES; t++) {
1089                 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1090                         spa_taskqs_fini(spa, t, q);
1091                 }
1092         }
1093 
1094         metaslab_class_destroy(spa->spa_normal_class);
1095         spa->spa_normal_class = NULL;
1096 
1097         metaslab_class_destroy(spa->spa_log_class);
1098         spa->spa_log_class = NULL;
1099 
1100         /*
1101          * If this was part of an import or the open otherwise failed, we may
1102          * still have errors left in the queues.  Empty them just in case.
1103          */
1104         spa_errlog_drain(spa);
1105 
1106         avl_destroy(&spa->spa_errlist_scrub);
1107         avl_destroy(&spa->spa_errlist_last);
1108 
1109         spa->spa_state = POOL_STATE_UNINITIALIZED;
1110 
1111         mutex_enter(&spa->spa_proc_lock);
1112         if (spa->spa_proc_state != SPA_PROC_NONE) {
1113                 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1114                 spa->spa_proc_state = SPA_PROC_DEACTIVATE;
1115                 cv_broadcast(&spa->spa_proc_cv);
1116                 while (spa->spa_proc_state == SPA_PROC_DEACTIVATE) {
1117                         ASSERT(spa->spa_proc != &p0);
1118                         cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1119                 }
1120                 ASSERT(spa->spa_proc_state == SPA_PROC_GONE);
1121                 spa->spa_proc_state = SPA_PROC_NONE;
1122         }
1123         ASSERT(spa->spa_proc == &p0);
1124         mutex_exit(&spa->spa_proc_lock);
1125 
1126         /*
1127          * We want to make sure spa_thread() has actually exited the ZFS
1128          * module, so that the module can't be unloaded out from underneath
1129          * it.
1130          */
1131         if (spa->spa_did != 0) {
1132                 thread_join(spa->spa_did);
1133                 spa->spa_did = 0;
1134         }
1135 }
1136 
1137 /*
1138  * Verify a pool configuration, and construct the vdev tree appropriately.  This
1139  * will create all the necessary vdevs in the appropriate layout, with each vdev
1140  * in the CLOSED state.  This will prep the pool before open/creation/import.
1141  * All vdev validation is done by the vdev_alloc() routine.
1142  */
1143 static int
1144 spa_config_parse(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent,
1145     uint_t id, int atype)
1146 {
1147         nvlist_t **child;
1148         uint_t children;
1149         int error;
1150 
1151         if ((error = vdev_alloc(spa, vdp, nv, parent, id, atype)) != 0)
1152                 return (error);
1153 
1154         if ((*vdp)->vdev_ops->vdev_op_leaf)
1155                 return (0);
1156 
1157         error = nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1158             &child, &children);
1159 
1160         if (error == ENOENT)
1161                 return (0);
1162 
1163         if (error) {
1164                 vdev_free(*vdp);
1165                 *vdp = NULL;
1166                 return (SET_ERROR(EINVAL));
1167         }
1168 
1169         for (int c = 0; c < children; c++) {
1170                 vdev_t *vd;
1171                 if ((error = spa_config_parse(spa, &vd, child[c], *vdp, c,
1172                     atype)) != 0) {
1173                         vdev_free(*vdp);
1174                         *vdp = NULL;
1175                         return (error);
1176                 }
1177         }
1178 
1179         ASSERT(*vdp != NULL);
1180 
1181         return (0);
1182 }
1183 
1184 /*
1185  * Opposite of spa_load().
1186  */
1187 static void
1188 spa_unload(spa_t *spa)
1189 {
1190         int i;
1191 
1192         ASSERT(MUTEX_HELD(&spa_namespace_lock));
1193 
1194         /*
1195          * Stop async tasks.
1196          */
1197         spa_async_suspend(spa);
1198 
1199         /*
1200          * Stop syncing.
1201          */
1202         if (spa->spa_sync_on) {
1203                 txg_sync_stop(spa->spa_dsl_pool);
1204                 spa->spa_sync_on = B_FALSE;
1205         }
1206 
1207         /*
1208          * Wait for any outstanding async I/O to complete.
1209          */
1210         if (spa->spa_async_zio_root != NULL) {
1211                 (void) zio_wait(spa->spa_async_zio_root);
1212                 spa->spa_async_zio_root = NULL;
1213         }
1214 
1215         bpobj_close(&spa->spa_deferred_bpobj);
1216 
1217         /*
1218          * Close the dsl pool.
1219          */
1220         if (spa->spa_dsl_pool) {
1221                 dsl_pool_close(spa->spa_dsl_pool);
1222                 spa->spa_dsl_pool = NULL;
1223                 spa->spa_meta_objset = NULL;
1224         }
1225 
1226         ddt_unload(spa);
1227 
1228         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1229 
1230         /*
1231          * Drop and purge level 2 cache
1232          */
1233         spa_l2cache_drop(spa);
1234 
1235         /*
1236          * Close all vdevs.
1237          */
1238         if (spa->spa_root_vdev)
1239                 vdev_free(spa->spa_root_vdev);
1240         ASSERT(spa->spa_root_vdev == NULL);
1241 
1242         for (i = 0; i < spa->spa_spares.sav_count; i++)
1243                 vdev_free(spa->spa_spares.sav_vdevs[i]);
1244         if (spa->spa_spares.sav_vdevs) {
1245                 kmem_free(spa->spa_spares.sav_vdevs,
1246                     spa->spa_spares.sav_count * sizeof (void *));
1247                 spa->spa_spares.sav_vdevs = NULL;
1248         }
1249         if (spa->spa_spares.sav_config) {
1250                 nvlist_free(spa->spa_spares.sav_config);
1251                 spa->spa_spares.sav_config = NULL;
1252         }
1253         spa->spa_spares.sav_count = 0;
1254 
1255         for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
1256                 vdev_clear_stats(spa->spa_l2cache.sav_vdevs[i]);
1257                 vdev_free(spa->spa_l2cache.sav_vdevs[i]);
1258         }
1259         if (spa->spa_l2cache.sav_vdevs) {
1260                 kmem_free(spa->spa_l2cache.sav_vdevs,
1261                     spa->spa_l2cache.sav_count * sizeof (void *));
1262                 spa->spa_l2cache.sav_vdevs = NULL;
1263         }
1264         if (spa->spa_l2cache.sav_config) {
1265                 nvlist_free(spa->spa_l2cache.sav_config);
1266                 spa->spa_l2cache.sav_config = NULL;
1267         }
1268         spa->spa_l2cache.sav_count = 0;
1269 
1270         spa->spa_async_suspended = 0;
1271 
1272         if (spa->spa_comment != NULL) {
1273                 spa_strfree(spa->spa_comment);
1274                 spa->spa_comment = NULL;
1275         }
1276 
1277         spa_config_exit(spa, SCL_ALL, FTAG);
1278 }
1279 
1280 /*
1281  * Load (or re-load) the current list of vdevs describing the active spares for
1282  * this pool.  When this is called, we have some form of basic information in
1283  * 'spa_spares.sav_config'.  We parse this into vdevs, try to open them, and
1284  * then re-generate a more complete list including status information.
1285  */
1286 static void
1287 spa_load_spares(spa_t *spa)
1288 {
1289         nvlist_t **spares;
1290         uint_t nspares;
1291         int i;
1292         vdev_t *vd, *tvd;
1293 
1294         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1295 
1296         /*
1297          * First, close and free any existing spare vdevs.
1298          */
1299         for (i = 0; i < spa->spa_spares.sav_count; i++) {
1300                 vd = spa->spa_spares.sav_vdevs[i];
1301 
1302                 /* Undo the call to spa_activate() below */
1303                 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1304                     B_FALSE)) != NULL && tvd->vdev_isspare)
1305                         spa_spare_remove(tvd);
1306                 vdev_close(vd);
1307                 vdev_free(vd);
1308         }
1309 
1310         if (spa->spa_spares.sav_vdevs)
1311                 kmem_free(spa->spa_spares.sav_vdevs,
1312                     spa->spa_spares.sav_count * sizeof (void *));
1313 
1314         if (spa->spa_spares.sav_config == NULL)
1315                 nspares = 0;
1316         else
1317                 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
1318                     ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
1319 
1320         spa->spa_spares.sav_count = (int)nspares;
1321         spa->spa_spares.sav_vdevs = NULL;
1322 
1323         if (nspares == 0)
1324                 return;
1325 
1326         /*
1327          * Construct the array of vdevs, opening them to get status in the
1328          * process.   For each spare, there is potentially two different vdev_t
1329          * structures associated with it: one in the list of spares (used only
1330          * for basic validation purposes) and one in the active vdev
1331          * configuration (if it's spared in).  During this phase we open and
1332          * validate each vdev on the spare list.  If the vdev also exists in the
1333          * active configuration, then we also mark this vdev as an active spare.
1334          */
1335         spa->spa_spares.sav_vdevs = kmem_alloc(nspares * sizeof (void *),
1336             KM_SLEEP);
1337         for (i = 0; i < spa->spa_spares.sav_count; i++) {
1338                 VERIFY(spa_config_parse(spa, &vd, spares[i], NULL, 0,
1339                     VDEV_ALLOC_SPARE) == 0);
1340                 ASSERT(vd != NULL);
1341 
1342                 spa->spa_spares.sav_vdevs[i] = vd;
1343 
1344                 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1345                     B_FALSE)) != NULL) {
1346                         if (!tvd->vdev_isspare)
1347                                 spa_spare_add(tvd);
1348 
1349                         /*
1350                          * We only mark the spare active if we were successfully
1351                          * able to load the vdev.  Otherwise, importing a pool
1352                          * with a bad active spare would result in strange
1353                          * behavior, because multiple pool would think the spare
1354                          * is actively in use.
1355                          *
1356                          * There is a vulnerability here to an equally bizarre
1357                          * circumstance, where a dead active spare is later
1358                          * brought back to life (onlined or otherwise).  Given
1359                          * the rarity of this scenario, and the extra complexity
1360                          * it adds, we ignore the possibility.
1361                          */
1362                         if (!vdev_is_dead(tvd))
1363                                 spa_spare_activate(tvd);
1364                 }
1365 
1366                 vd->vdev_top = vd;
1367                 vd->vdev_aux = &spa->spa_spares;
1368 
1369                 if (vdev_open(vd) != 0)
1370                         continue;
1371 
1372                 if (vdev_validate_aux(vd) == 0)
1373                         spa_spare_add(vd);
1374         }
1375 
1376         /*
1377          * Recompute the stashed list of spares, with status information
1378          * this time.
1379          */
1380         VERIFY(nvlist_remove(spa->spa_spares.sav_config, ZPOOL_CONFIG_SPARES,
1381             DATA_TYPE_NVLIST_ARRAY) == 0);
1382 
1383         spares = kmem_alloc(spa->spa_spares.sav_count * sizeof (void *),
1384             KM_SLEEP);
1385         for (i = 0; i < spa->spa_spares.sav_count; i++)
1386                 spares[i] = vdev_config_generate(spa,
1387                     spa->spa_spares.sav_vdevs[i], B_TRUE, VDEV_CONFIG_SPARE);
1388         VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
1389             ZPOOL_CONFIG_SPARES, spares, spa->spa_spares.sav_count) == 0);
1390         for (i = 0; i < spa->spa_spares.sav_count; i++)
1391                 nvlist_free(spares[i]);
1392         kmem_free(spares, spa->spa_spares.sav_count * sizeof (void *));
1393 }
1394 
1395 /*
1396  * Load (or re-load) the current list of vdevs describing the active l2cache for
1397  * this pool.  When this is called, we have some form of basic information in
1398  * 'spa_l2cache.sav_config'.  We parse this into vdevs, try to open them, and
1399  * then re-generate a more complete list including status information.
1400  * Devices which are already active have their details maintained, and are
1401  * not re-opened.
1402  */
1403 static void
1404 spa_load_l2cache(spa_t *spa)
1405 {
1406         nvlist_t **l2cache;
1407         uint_t nl2cache;
1408         int i, j, oldnvdevs;
1409         uint64_t guid;
1410         vdev_t *vd, **oldvdevs, **newvdevs;
1411         spa_aux_vdev_t *sav = &spa->spa_l2cache;
1412 
1413         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1414 
1415         if (sav->sav_config != NULL) {
1416                 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
1417                     ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
1418                 newvdevs = kmem_alloc(nl2cache * sizeof (void *), KM_SLEEP);
1419         } else {
1420                 nl2cache = 0;
1421                 newvdevs = NULL;
1422         }
1423 
1424         oldvdevs = sav->sav_vdevs;
1425         oldnvdevs = sav->sav_count;
1426         sav->sav_vdevs = NULL;
1427         sav->sav_count = 0;
1428 
1429         /*
1430          * Process new nvlist of vdevs.
1431          */
1432         for (i = 0; i < nl2cache; i++) {
1433                 VERIFY(nvlist_lookup_uint64(l2cache[i], ZPOOL_CONFIG_GUID,
1434                     &guid) == 0);
1435 
1436                 newvdevs[i] = NULL;
1437                 for (j = 0; j < oldnvdevs; j++) {
1438                         vd = oldvdevs[j];
1439                         if (vd != NULL && guid == vd->vdev_guid) {
1440                                 /*
1441                                  * Retain previous vdev for add/remove ops.
1442                                  */
1443                                 newvdevs[i] = vd;
1444                                 oldvdevs[j] = NULL;
1445                                 break;
1446                         }
1447                 }
1448 
1449                 if (newvdevs[i] == NULL) {
1450                         /*
1451                          * Create new vdev
1452                          */
1453                         VERIFY(spa_config_parse(spa, &vd, l2cache[i], NULL, 0,
1454                             VDEV_ALLOC_L2CACHE) == 0);
1455                         ASSERT(vd != NULL);
1456                         newvdevs[i] = vd;
1457 
1458                         /*
1459                          * Commit this vdev as an l2cache device,
1460                          * even if it fails to open.
1461                          */
1462                         spa_l2cache_add(vd);
1463 
1464                         vd->vdev_top = vd;
1465                         vd->vdev_aux = sav;
1466 
1467                         spa_l2cache_activate(vd);
1468 
1469                         if (vdev_open(vd) != 0)
1470                                 continue;
1471 
1472                         (void) vdev_validate_aux(vd);
1473 
1474                         if (!vdev_is_dead(vd))
1475                                 l2arc_add_vdev(spa, vd);
1476                 }
1477         }
1478 
1479         /*
1480          * Purge vdevs that were dropped
1481          */
1482         for (i = 0; i < oldnvdevs; i++) {
1483                 uint64_t pool;
1484 
1485                 vd = oldvdevs[i];
1486                 if (vd != NULL) {
1487                         ASSERT(vd->vdev_isl2cache);
1488 
1489                         if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
1490                             pool != 0ULL && l2arc_vdev_present(vd))
1491                                 l2arc_remove_vdev(vd);
1492                         vdev_clear_stats(vd);
1493                         vdev_free(vd);
1494                 }
1495         }
1496 
1497         if (oldvdevs)
1498                 kmem_free(oldvdevs, oldnvdevs * sizeof (void *));
1499 
1500         if (sav->sav_config == NULL)
1501                 goto out;
1502 
1503         sav->sav_vdevs = newvdevs;
1504         sav->sav_count = (int)nl2cache;
1505 
1506         /*
1507          * Recompute the stashed list of l2cache devices, with status
1508          * information this time.
1509          */
1510         VERIFY(nvlist_remove(sav->sav_config, ZPOOL_CONFIG_L2CACHE,
1511             DATA_TYPE_NVLIST_ARRAY) == 0);
1512 
1513         l2cache = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
1514         for (i = 0; i < sav->sav_count; i++)
1515                 l2cache[i] = vdev_config_generate(spa,
1516                     sav->sav_vdevs[i], B_TRUE, VDEV_CONFIG_L2CACHE);
1517         VERIFY(nvlist_add_nvlist_array(sav->sav_config,
1518             ZPOOL_CONFIG_L2CACHE, l2cache, sav->sav_count) == 0);
1519 out:
1520         for (i = 0; i < sav->sav_count; i++)
1521                 nvlist_free(l2cache[i]);
1522         if (sav->sav_count)
1523                 kmem_free(l2cache, sav->sav_count * sizeof (void *));
1524 }
1525 
1526 static int
1527 load_nvlist(spa_t *spa, uint64_t obj, nvlist_t **value)
1528 {
1529         dmu_buf_t *db;
1530         char *packed = NULL;
1531         size_t nvsize = 0;
1532         int error;
1533         *value = NULL;
1534 
1535         VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
1536         nvsize = *(uint64_t *)db->db_data;
1537         dmu_buf_rele(db, FTAG);
1538 
1539         packed = kmem_alloc(nvsize, KM_SLEEP);
1540         error = dmu_read(spa->spa_meta_objset, obj, 0, nvsize, packed,
1541             DMU_READ_PREFETCH);
1542         if (error == 0)
1543                 error = nvlist_unpack(packed, nvsize, value, 0);
1544         kmem_free(packed, nvsize);
1545 
1546         return (error);
1547 }
1548 
1549 /*
1550  * Checks to see if the given vdev could not be opened, in which case we post a
1551  * sysevent to notify the autoreplace code that the device has been removed.
1552  */
1553 static void
1554 spa_check_removed(vdev_t *vd)
1555 {
1556         for (int c = 0; c < vd->vdev_children; c++)
1557                 spa_check_removed(vd->vdev_child[c]);
1558 
1559         if (vd->vdev_ops->vdev_op_leaf && vdev_is_dead(vd) &&
1560             !vd->vdev_ishole) {
1561                 zfs_post_autoreplace(vd->vdev_spa, vd);
1562                 spa_event_notify(vd->vdev_spa, vd, ESC_ZFS_VDEV_CHECK);
1563         }
1564 }
1565 
1566 /*
1567  * Validate the current config against the MOS config
1568  */
1569 static boolean_t
1570 spa_config_valid(spa_t *spa, nvlist_t *config)
1571 {
1572         vdev_t *mrvd, *rvd = spa->spa_root_vdev;
1573         nvlist_t *nv;
1574 
1575         VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nv) == 0);
1576 
1577         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1578         VERIFY(spa_config_parse(spa, &mrvd, nv, NULL, 0, VDEV_ALLOC_LOAD) == 0);
1579 
1580         ASSERT3U(rvd->vdev_children, ==, mrvd->vdev_children);
1581 
1582         /*
1583          * If we're doing a normal import, then build up any additional
1584          * diagnostic information about missing devices in this config.
1585          * We'll pass this up to the user for further processing.
1586          */
1587         if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG)) {
1588                 nvlist_t **child, *nv;
1589                 uint64_t idx = 0;
1590 
1591                 child = kmem_alloc(rvd->vdev_children * sizeof (nvlist_t **),
1592                     KM_SLEEP);
1593                 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1594 
1595                 for (int c = 0; c < rvd->vdev_children; c++) {
1596                         vdev_t *tvd = rvd->vdev_child[c];
1597                         vdev_t *mtvd  = mrvd->vdev_child[c];
1598 
1599                         if (tvd->vdev_ops == &vdev_missing_ops &&
1600                             mtvd->vdev_ops != &vdev_missing_ops &&
1601                             mtvd->vdev_islog)
1602                                 child[idx++] = vdev_config_generate(spa, mtvd,
1603                                     B_FALSE, 0);
1604                 }
1605 
1606                 if (idx) {
1607                         VERIFY(nvlist_add_nvlist_array(nv,
1608                             ZPOOL_CONFIG_CHILDREN, child, idx) == 0);
1609                         VERIFY(nvlist_add_nvlist(spa->spa_load_info,
1610                             ZPOOL_CONFIG_MISSING_DEVICES, nv) == 0);
1611 
1612                         for (int i = 0; i < idx; i++)
1613                                 nvlist_free(child[i]);
1614                 }
1615                 nvlist_free(nv);
1616                 kmem_free(child, rvd->vdev_children * sizeof (char **));
1617         }
1618 
1619         /*
1620          * Compare the root vdev tree with the information we have
1621          * from the MOS config (mrvd). Check each top-level vdev
1622          * with the corresponding MOS config top-level (mtvd).
1623          */
1624         for (int c = 0; c < rvd->vdev_children; c++) {
1625                 vdev_t *tvd = rvd->vdev_child[c];
1626                 vdev_t *mtvd  = mrvd->vdev_child[c];
1627 
1628                 /*
1629                  * Resolve any "missing" vdevs in the current configuration.
1630                  * If we find that the MOS config has more accurate information
1631                  * about the top-level vdev then use that vdev instead.
1632                  */
1633                 if (tvd->vdev_ops == &vdev_missing_ops &&
1634                     mtvd->vdev_ops != &vdev_missing_ops) {
1635 
1636                         if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG))
1637                                 continue;
1638 
1639                         /*
1640                          * Device specific actions.
1641                          */
1642                         if (mtvd->vdev_islog) {
1643                                 spa_set_log_state(spa, SPA_LOG_CLEAR);
1644                         } else {
1645                                 /*
1646                                  * XXX - once we have 'readonly' pool
1647                                  * support we should be able to handle
1648                                  * missing data devices by transitioning
1649                                  * the pool to readonly.
1650                                  */
1651                                 continue;
1652                         }
1653 
1654                         /*
1655                          * Swap the missing vdev with the data we were
1656                          * able to obtain from the MOS config.
1657                          */
1658                         vdev_remove_child(rvd, tvd);
1659                         vdev_remove_child(mrvd, mtvd);
1660 
1661                         vdev_add_child(rvd, mtvd);
1662                         vdev_add_child(mrvd, tvd);
1663 
1664                         spa_config_exit(spa, SCL_ALL, FTAG);
1665                         vdev_load(mtvd);
1666                         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1667 
1668                         vdev_reopen(rvd);
1669                 } else if (mtvd->vdev_islog) {
1670                         /*
1671                          * Load the slog device's state from the MOS config
1672                          * since it's possible that the label does not
1673                          * contain the most up-to-date information.
1674                          */
1675                         vdev_load_log_state(tvd, mtvd);
1676                         vdev_reopen(tvd);
1677                 }
1678         }
1679         vdev_free(mrvd);
1680         spa_config_exit(spa, SCL_ALL, FTAG);
1681 
1682         /*
1683          * Ensure we were able to validate the config.
1684          */
1685         return (rvd->vdev_guid_sum == spa->spa_uberblock.ub_guid_sum);
1686 }
1687 
1688 /*
1689  * Check for missing log devices
1690  */
1691 static boolean_t
1692 spa_check_logs(spa_t *spa)
1693 {
1694         boolean_t rv = B_FALSE;
1695 
1696         switch (spa->spa_log_state) {
1697         case SPA_LOG_MISSING:
1698                 /* need to recheck in case slog has been restored */
1699         case SPA_LOG_UNKNOWN:
1700                 rv = (dmu_objset_find(spa->spa_name, zil_check_log_chain,
1701                     NULL, DS_FIND_CHILDREN) != 0);
1702                 if (rv)
1703                         spa_set_log_state(spa, SPA_LOG_MISSING);
1704                 break;
1705         }
1706         return (rv);
1707 }
1708 
1709 static boolean_t
1710 spa_passivate_log(spa_t *spa)
1711 {
1712         vdev_t *rvd = spa->spa_root_vdev;
1713         boolean_t slog_found = B_FALSE;
1714 
1715         ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1716 
1717         if (!spa_has_slogs(spa))
1718                 return (B_FALSE);
1719 
1720         for (int c = 0; c < rvd->vdev_children; c++) {
1721                 vdev_t *tvd = rvd->vdev_child[c];
1722                 metaslab_group_t *mg = tvd->vdev_mg;
1723 
1724                 if (tvd->vdev_islog) {
1725                         metaslab_group_passivate(mg);
1726                         slog_found = B_TRUE;
1727                 }
1728         }
1729 
1730         return (slog_found);
1731 }
1732 
1733 static void
1734 spa_activate_log(spa_t *spa)
1735 {
1736         vdev_t *rvd = spa->spa_root_vdev;
1737 
1738         ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1739 
1740         for (int c = 0; c < rvd->vdev_children; c++) {
1741                 vdev_t *tvd = rvd->vdev_child[c];
1742                 metaslab_group_t *mg = tvd->vdev_mg;
1743 
1744                 if (tvd->vdev_islog)
1745                         metaslab_group_activate(mg);
1746         }
1747 }
1748 
1749 int
1750 spa_offline_log(spa_t *spa)
1751 {
1752         int error;
1753 
1754         error = dmu_objset_find(spa_name(spa), zil_vdev_offline,
1755             NULL, DS_FIND_CHILDREN);
1756         if (error == 0) {
1757                 /*
1758                  * We successfully offlined the log device, sync out the
1759                  * current txg so that the "stubby" block can be removed
1760                  * by zil_sync().
1761                  */
1762                 txg_wait_synced(spa->spa_dsl_pool, 0);
1763         }
1764         return (error);
1765 }
1766 
1767 static void
1768 spa_aux_check_removed(spa_aux_vdev_t *sav)
1769 {
1770         for (int i = 0; i < sav->sav_count; i++)
1771                 spa_check_removed(sav->sav_vdevs[i]);
1772 }
1773 
1774 void
1775 spa_claim_notify(zio_t *zio)
1776 {
1777         spa_t *spa = zio->io_spa;
1778 
1779         if (zio->io_error)
1780                 return;
1781 
1782         mutex_enter(&spa->spa_props_lock);       /* any mutex will do */
1783         if (spa->spa_claim_max_txg < zio->io_bp->blk_birth)
1784                 spa->spa_claim_max_txg = zio->io_bp->blk_birth;
1785         mutex_exit(&spa->spa_props_lock);
1786 }
1787 
1788 typedef struct spa_load_error {
1789         uint64_t        sle_meta_count;
1790         uint64_t        sle_data_count;
1791 } spa_load_error_t;
1792 
1793 static void
1794 spa_load_verify_done(zio_t *zio)
1795 {
1796         blkptr_t *bp = zio->io_bp;
1797         spa_load_error_t *sle = zio->io_private;
1798         dmu_object_type_t type = BP_GET_TYPE(bp);
1799         int error = zio->io_error;
1800 
1801         if (error) {
1802                 if ((BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type)) &&
1803                     type != DMU_OT_INTENT_LOG)
1804                         atomic_add_64(&sle->sle_meta_count, 1);
1805                 else
1806                         atomic_add_64(&sle->sle_data_count, 1);
1807         }
1808         zio_data_buf_free(zio->io_data, zio->io_size);
1809 }
1810 
1811 /*ARGSUSED*/
1812 static int
1813 spa_load_verify_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
1814     const zbookmark_t *zb, const dnode_phys_t *dnp, void *arg)
1815 {
1816         if (bp != NULL) {
1817                 zio_t *rio = arg;
1818                 size_t size = BP_GET_PSIZE(bp);
1819                 void *data = zio_data_buf_alloc(size);
1820 
1821                 zio_nowait(zio_read(rio, spa, bp, data, size,
1822                     spa_load_verify_done, rio->io_private, ZIO_PRIORITY_SCRUB,
1823                     ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CANFAIL |
1824                     ZIO_FLAG_SCRUB | ZIO_FLAG_RAW, zb));
1825         }
1826         return (0);
1827 }
1828 
1829 static int
1830 spa_load_verify(spa_t *spa)
1831 {
1832         zio_t *rio;
1833         spa_load_error_t sle = { 0 };
1834         zpool_rewind_policy_t policy;
1835         boolean_t verify_ok = B_FALSE;
1836         int error;
1837 
1838         zpool_get_rewind_policy(spa->spa_config, &policy);
1839 
1840         if (policy.zrp_request & ZPOOL_NEVER_REWIND)
1841                 return (0);
1842 
1843         rio = zio_root(spa, NULL, &sle,
1844             ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
1845 
1846         error = traverse_pool(spa, spa->spa_verify_min_txg,
1847             TRAVERSE_PRE | TRAVERSE_PREFETCH, spa_load_verify_cb, rio);
1848 
1849         (void) zio_wait(rio);
1850 
1851         spa->spa_load_meta_errors = sle.sle_meta_count;
1852         spa->spa_load_data_errors = sle.sle_data_count;
1853 
1854         if (!error && sle.sle_meta_count <= policy.zrp_maxmeta &&
1855             sle.sle_data_count <= policy.zrp_maxdata) {
1856                 int64_t loss = 0;
1857 
1858                 verify_ok = B_TRUE;
1859                 spa->spa_load_txg = spa->spa_uberblock.ub_txg;
1860                 spa->spa_load_txg_ts = spa->spa_uberblock.ub_timestamp;
1861 
1862                 loss = spa->spa_last_ubsync_txg_ts - spa->spa_load_txg_ts;
1863                 VERIFY(nvlist_add_uint64(spa->spa_load_info,
1864                     ZPOOL_CONFIG_LOAD_TIME, spa->spa_load_txg_ts) == 0);
1865                 VERIFY(nvlist_add_int64(spa->spa_load_info,
1866                     ZPOOL_CONFIG_REWIND_TIME, loss) == 0);
1867                 VERIFY(nvlist_add_uint64(spa->spa_load_info,
1868                     ZPOOL_CONFIG_LOAD_DATA_ERRORS, sle.sle_data_count) == 0);
1869         } else {
1870                 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg;
1871         }
1872 
1873         if (error) {
1874                 if (error != ENXIO && error != EIO)
1875                         error = SET_ERROR(EIO);
1876                 return (error);
1877         }
1878 
1879         return (verify_ok ? 0 : EIO);
1880 }
1881 
1882 /*
1883  * Find a value in the pool props object.
1884  */
1885 static void
1886 spa_prop_find(spa_t *spa, zpool_prop_t prop, uint64_t *val)
1887 {
1888         (void) zap_lookup(spa->spa_meta_objset, spa->spa_pool_props_object,
1889             zpool_prop_to_name(prop), sizeof (uint64_t), 1, val);
1890 }
1891 
1892 /*
1893  * Find a value in the pool directory object.
1894  */
1895 static int
1896 spa_dir_prop(spa_t *spa, const char *name, uint64_t *val)
1897 {
1898         return (zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
1899             name, sizeof (uint64_t), 1, val));
1900 }
1901 
1902 static int
1903 spa_vdev_err(vdev_t *vdev, vdev_aux_t aux, int err)
1904 {
1905         vdev_set_state(vdev, B_TRUE, VDEV_STATE_CANT_OPEN, aux);
1906         return (err);
1907 }
1908 
1909 /*
1910  * Fix up config after a partly-completed split.  This is done with the
1911  * ZPOOL_CONFIG_SPLIT nvlist.  Both the splitting pool and the split-off
1912  * pool have that entry in their config, but only the splitting one contains
1913  * a list of all the guids of the vdevs that are being split off.
1914  *
1915  * This function determines what to do with that list: either rejoin
1916  * all the disks to the pool, or complete the splitting process.  To attempt
1917  * the rejoin, each disk that is offlined is marked online again, and
1918  * we do a reopen() call.  If the vdev label for every disk that was
1919  * marked online indicates it was successfully split off (VDEV_AUX_SPLIT_POOL)
1920  * then we call vdev_split() on each disk, and complete the split.
1921  *
1922  * Otherwise we leave the config alone, with all the vdevs in place in
1923  * the original pool.
1924  */
1925 static void
1926 spa_try_repair(spa_t *spa, nvlist_t *config)
1927 {
1928         uint_t extracted;
1929         uint64_t *glist;
1930         uint_t i, gcount;
1931         nvlist_t *nvl;
1932         vdev_t **vd;
1933         boolean_t attempt_reopen;
1934 
1935         if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) != 0)
1936                 return;
1937 
1938         /* check that the config is complete */
1939         if (nvlist_lookup_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
1940             &glist, &gcount) != 0)
1941                 return;
1942 
1943         vd = kmem_zalloc(gcount * sizeof (vdev_t *), KM_SLEEP);
1944 
1945         /* attempt to online all the vdevs & validate */
1946         attempt_reopen = B_TRUE;
1947         for (i = 0; i < gcount; i++) {
1948                 if (glist[i] == 0)      /* vdev is hole */
1949                         continue;
1950 
1951                 vd[i] = spa_lookup_by_guid(spa, glist[i], B_FALSE);
1952                 if (vd[i] == NULL) {
1953                         /*
1954                          * Don't bother attempting to reopen the disks;
1955                          * just do the split.
1956                          */
1957                         attempt_reopen = B_FALSE;
1958                 } else {
1959                         /* attempt to re-online it */
1960                         vd[i]->vdev_offline = B_FALSE;
1961                 }
1962         }
1963 
1964         if (attempt_reopen) {
1965                 vdev_reopen(spa->spa_root_vdev);
1966 
1967                 /* check each device to see what state it's in */
1968                 for (extracted = 0, i = 0; i < gcount; i++) {
1969                         if (vd[i] != NULL &&
1970                             vd[i]->vdev_stat.vs_aux != VDEV_AUX_SPLIT_POOL)
1971                                 break;
1972                         ++extracted;
1973                 }
1974         }
1975 
1976         /*
1977          * If every disk has been moved to the new pool, or if we never
1978          * even attempted to look at them, then we split them off for
1979          * good.
1980          */
1981         if (!attempt_reopen || gcount == extracted) {
1982                 for (i = 0; i < gcount; i++)
1983                         if (vd[i] != NULL)
1984                                 vdev_split(vd[i]);
1985                 vdev_reopen(spa->spa_root_vdev);
1986         }
1987 
1988         kmem_free(vd, gcount * sizeof (vdev_t *));
1989 }
1990 
1991 static int
1992 spa_load(spa_t *spa, spa_load_state_t state, spa_import_type_t type,
1993     boolean_t mosconfig)
1994 {
1995         nvlist_t *config = spa->spa_config;
1996         char *ereport = FM_EREPORT_ZFS_POOL;
1997         char *comment;
1998         int error;
1999         uint64_t pool_guid;
2000         nvlist_t *nvl;
2001 
2002         if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid))
2003                 return (SET_ERROR(EINVAL));
2004 
2005         ASSERT(spa->spa_comment == NULL);
2006         if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2007                 spa->spa_comment = spa_strdup(comment);
2008 
2009         /*
2010          * Versioning wasn't explicitly added to the label until later, so if
2011          * it's not present treat it as the initial version.
2012          */
2013         if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
2014             &spa->spa_ubsync.ub_version) != 0)
2015                 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
2016 
2017         (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
2018             &spa->spa_config_txg);
2019 
2020         if ((state == SPA_LOAD_IMPORT || state == SPA_LOAD_TRYIMPORT) &&
2021             spa_guid_exists(pool_guid, 0)) {
2022                 error = SET_ERROR(EEXIST);
2023         } else {
2024                 spa->spa_config_guid = pool_guid;
2025 
2026                 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT,
2027                     &nvl) == 0) {
2028                         VERIFY(nvlist_dup(nvl, &spa->spa_config_splitting,
2029                             KM_SLEEP) == 0);
2030                 }
2031 
2032                 nvlist_free(spa->spa_load_info);
2033                 spa->spa_load_info = fnvlist_alloc();
2034 
2035                 gethrestime(&spa->spa_loaded_ts);
2036                 error = spa_load_impl(spa, pool_guid, config, state, type,
2037                     mosconfig, &ereport);
2038         }
2039 
2040         spa->spa_minref = refcount_count(&spa->spa_refcount);
2041         if (error) {
2042                 if (error != EEXIST) {
2043                         spa->spa_loaded_ts.tv_sec = 0;
2044                         spa->spa_loaded_ts.tv_nsec = 0;
2045                 }
2046                 if (error != EBADF) {
2047                         zfs_ereport_post(ereport, spa, NULL, NULL, 0, 0);
2048                 }
2049         }
2050         spa->spa_load_state = error ? SPA_LOAD_ERROR : SPA_LOAD_NONE;
2051         spa->spa_ena = 0;
2052 
2053         return (error);
2054 }
2055 
2056 /*
2057  * Load an existing storage pool, using the pool's builtin spa_config as a
2058  * source of configuration information.
2059  */
2060 static int
2061 spa_load_impl(spa_t *spa, uint64_t pool_guid, nvlist_t *config,
2062     spa_load_state_t state, spa_import_type_t type, boolean_t mosconfig,
2063     char **ereport)
2064 {
2065         int error = 0;
2066         nvlist_t *nvroot = NULL;
2067         nvlist_t *label;
2068         vdev_t *rvd;
2069         uberblock_t *ub = &spa->spa_uberblock;
2070         uint64_t children, config_cache_txg = spa->spa_config_txg;
2071         int orig_mode = spa->spa_mode;
2072         int parse;
2073         uint64_t obj;
2074         boolean_t missing_feat_write = B_FALSE;
2075 
2076         /*
2077          * If this is an untrusted config, access the pool in read-only mode.
2078          * This prevents things like resilvering recently removed devices.
2079          */
2080         if (!mosconfig)
2081                 spa->spa_mode = FREAD;
2082 
2083         ASSERT(MUTEX_HELD(&spa_namespace_lock));
2084 
2085         spa->spa_load_state = state;
2086 
2087         if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvroot))
2088                 return (SET_ERROR(EINVAL));
2089 
2090         parse = (type == SPA_IMPORT_EXISTING ?
2091             VDEV_ALLOC_LOAD : VDEV_ALLOC_SPLIT);
2092 
2093         /*
2094          * Create "The Godfather" zio to hold all async IOs
2095          */
2096         spa->spa_async_zio_root = zio_root(spa, NULL, NULL,
2097             ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE | ZIO_FLAG_GODFATHER);
2098 
2099         /*
2100          * Parse the configuration into a vdev tree.  We explicitly set the
2101          * value that will be returned by spa_version() since parsing the
2102          * configuration requires knowing the version number.
2103          */
2104         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2105         error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, parse);
2106         spa_config_exit(spa, SCL_ALL, FTAG);
2107 
2108         if (error != 0)
2109                 return (error);
2110 
2111         ASSERT(spa->spa_root_vdev == rvd);
2112 
2113         if (type != SPA_IMPORT_ASSEMBLE) {
2114                 ASSERT(spa_guid(spa) == pool_guid);
2115         }
2116 
2117         /*
2118          * Try to open all vdevs, loading each label in the process.
2119          */
2120         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2121         error = vdev_open(rvd);
2122         spa_config_exit(spa, SCL_ALL, FTAG);
2123         if (error != 0)
2124                 return (error);
2125 
2126         /*
2127          * We need to validate the vdev labels against the configuration that
2128          * we have in hand, which is dependent on the setting of mosconfig. If
2129          * mosconfig is true then we're validating the vdev labels based on
2130          * that config.  Otherwise, we're validating against the cached config
2131          * (zpool.cache) that was read when we loaded the zfs module, and then
2132          * later we will recursively call spa_load() and validate against
2133          * the vdev config.
2134          *
2135          * If we're assembling a new pool that's been split off from an
2136          * existing pool, the labels haven't yet been updated so we skip
2137          * validation for now.
2138          */
2139         if (type != SPA_IMPORT_ASSEMBLE) {
2140                 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2141                 error = vdev_validate(rvd, mosconfig);
2142                 spa_config_exit(spa, SCL_ALL, FTAG);
2143 
2144                 if (error != 0)
2145                         return (error);
2146 
2147                 if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN)
2148                         return (SET_ERROR(ENXIO));
2149         }
2150 
2151         /*
2152          * Find the best uberblock.
2153          */
2154         vdev_uberblock_load(rvd, ub, &label);
2155 
2156         /*
2157          * If we weren't able to find a single valid uberblock, return failure.
2158          */
2159         if (ub->ub_txg == 0) {
2160                 nvlist_free(label);
2161                 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, ENXIO));
2162         }
2163 
2164         /*
2165          * If the pool has an unsupported version we can't open it.
2166          */
2167         if (!SPA_VERSION_IS_SUPPORTED(ub->ub_version)) {
2168                 nvlist_free(label);
2169                 return (spa_vdev_err(rvd, VDEV_AUX_VERSION_NEWER, ENOTSUP));
2170         }
2171 
2172         if (ub->ub_version >= SPA_VERSION_FEATURES) {
2173                 nvlist_t *features;
2174 
2175                 /*
2176                  * If we weren't able to find what's necessary for reading the
2177                  * MOS in the label, return failure.
2178                  */
2179                 if (label == NULL || nvlist_lookup_nvlist(label,
2180                     ZPOOL_CONFIG_FEATURES_FOR_READ, &features) != 0) {
2181                         nvlist_free(label);
2182                         return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2183                             ENXIO));
2184                 }
2185 
2186                 /*
2187                  * Update our in-core representation with the definitive values
2188                  * from the label.
2189                  */
2190                 nvlist_free(spa->spa_label_features);
2191                 VERIFY(nvlist_dup(features, &spa->spa_label_features, 0) == 0);
2192         }
2193 
2194         nvlist_free(label);
2195 
2196         /*
2197          * Look through entries in the label nvlist's features_for_read. If
2198          * there is a feature listed there which we don't understand then we
2199          * cannot open a pool.
2200          */
2201         if (ub->ub_version >= SPA_VERSION_FEATURES) {
2202                 nvlist_t *unsup_feat;
2203 
2204                 VERIFY(nvlist_alloc(&unsup_feat, NV_UNIQUE_NAME, KM_SLEEP) ==
2205                     0);
2206 
2207                 for (nvpair_t *nvp = nvlist_next_nvpair(spa->spa_label_features,
2208                     NULL); nvp != NULL;
2209                     nvp = nvlist_next_nvpair(spa->spa_label_features, nvp)) {
2210                         if (!zfeature_is_supported(nvpair_name(nvp))) {
2211                                 VERIFY(nvlist_add_string(unsup_feat,
2212                                     nvpair_name(nvp), "") == 0);
2213                         }
2214                 }
2215 
2216                 if (!nvlist_empty(unsup_feat)) {
2217                         VERIFY(nvlist_add_nvlist(spa->spa_load_info,
2218                             ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat) == 0);
2219                         nvlist_free(unsup_feat);
2220                         return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
2221                             ENOTSUP));
2222                 }
2223 
2224                 nvlist_free(unsup_feat);
2225         }
2226 
2227         /*
2228          * If the vdev guid sum doesn't match the uberblock, we have an
2229          * incomplete configuration.  We first check to see if the pool
2230          * is aware of the complete config (i.e ZPOOL_CONFIG_VDEV_CHILDREN).
2231          * If it is, defer the vdev_guid_sum check till later so we
2232          * can handle missing vdevs.
2233          */
2234         if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VDEV_CHILDREN,
2235             &children) != 0 && mosconfig && type != SPA_IMPORT_ASSEMBLE &&
2236             rvd->vdev_guid_sum != ub->ub_guid_sum)
2237                 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM, ENXIO));
2238 
2239         if (type != SPA_IMPORT_ASSEMBLE && spa->spa_config_splitting) {
2240                 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2241                 spa_try_repair(spa, config);
2242                 spa_config_exit(spa, SCL_ALL, FTAG);
2243                 nvlist_free(spa->spa_config_splitting);
2244                 spa->spa_config_splitting = NULL;
2245         }
2246 
2247         /*
2248          * Initialize internal SPA structures.
2249          */
2250         spa->spa_state = POOL_STATE_ACTIVE;
2251         spa->spa_ubsync = spa->spa_uberblock;
2252         spa->spa_verify_min_txg = spa->spa_extreme_rewind ?
2253             TXG_INITIAL - 1 : spa_last_synced_txg(spa) - TXG_DEFER_SIZE - 1;
2254         spa->spa_first_txg = spa->spa_last_ubsync_txg ?
2255             spa->spa_last_ubsync_txg : spa_last_synced_txg(spa) + 1;
2256         spa->spa_claim_max_txg = spa->spa_first_txg;
2257         spa->spa_prev_software_version = ub->ub_software_version;
2258 
2259         error = dsl_pool_init(spa, spa->spa_first_txg, &spa->spa_dsl_pool);
2260         if (error)
2261                 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2262         spa->spa_meta_objset = spa->spa_dsl_pool->dp_meta_objset;
2263 
2264         if (spa_dir_prop(spa, DMU_POOL_CONFIG, &spa->spa_config_object) != 0)
2265                 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2266 
2267         if (spa_version(spa) >= SPA_VERSION_FEATURES) {
2268                 boolean_t missing_feat_read = B_FALSE;
2269                 nvlist_t *unsup_feat, *enabled_feat;
2270 
2271                 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_READ,
2272                     &spa->spa_feat_for_read_obj) != 0) {
2273                         return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2274                 }
2275 
2276                 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_WRITE,
2277                     &spa->spa_feat_for_write_obj) != 0) {
2278                         return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2279                 }
2280 
2281                 if (spa_dir_prop(spa, DMU_POOL_FEATURE_DESCRIPTIONS,
2282                     &spa->spa_feat_desc_obj) != 0) {
2283                         return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2284                 }
2285 
2286                 enabled_feat = fnvlist_alloc();
2287                 unsup_feat = fnvlist_alloc();
2288 
2289                 if (!feature_is_supported(spa->spa_meta_objset,
2290                     spa->spa_feat_for_read_obj, spa->spa_feat_desc_obj,
2291                     unsup_feat, enabled_feat))
2292                         missing_feat_read = B_TRUE;
2293 
2294                 if (spa_writeable(spa) || state == SPA_LOAD_TRYIMPORT) {
2295                         if (!feature_is_supported(spa->spa_meta_objset,
2296                             spa->spa_feat_for_write_obj, spa->spa_feat_desc_obj,
2297                             unsup_feat, enabled_feat)) {
2298                                 missing_feat_write = B_TRUE;
2299                         }
2300                 }
2301 
2302                 fnvlist_add_nvlist(spa->spa_load_info,
2303                     ZPOOL_CONFIG_ENABLED_FEAT, enabled_feat);
2304 
2305                 if (!nvlist_empty(unsup_feat)) {
2306                         fnvlist_add_nvlist(spa->spa_load_info,
2307                             ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat);
2308                 }
2309 
2310                 fnvlist_free(enabled_feat);
2311                 fnvlist_free(unsup_feat);
2312 
2313                 if (!missing_feat_read) {
2314                         fnvlist_add_boolean(spa->spa_load_info,
2315                             ZPOOL_CONFIG_CAN_RDONLY);
2316                 }
2317 
2318                 /*
2319                  * If the state is SPA_LOAD_TRYIMPORT, our objective is
2320                  * twofold: to determine whether the pool is available for
2321                  * import in read-write mode and (if it is not) whether the
2322                  * pool is available for import in read-only mode. If the pool
2323                  * is available for import in read-write mode, it is displayed
2324                  * as available in userland; if it is not available for import
2325                  * in read-only mode, it is displayed as unavailable in
2326                  * userland. If the pool is available for import in read-only
2327                  * mode but not read-write mode, it is displayed as unavailable
2328                  * in userland with a special note that the pool is actually
2329                  * available for open in read-only mode.
2330                  *
2331                  * As a result, if the state is SPA_LOAD_TRYIMPORT and we are
2332                  * missing a feature for write, we must first determine whether
2333                  * the pool can be opened read-only before returning to
2334                  * userland in order to know whether to display the
2335                  * abovementioned note.
2336                  */
2337                 if (missing_feat_read || (missing_feat_write &&
2338                     spa_writeable(spa))) {
2339                         return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
2340                             ENOTSUP));
2341                 }
2342         }
2343 
2344         spa->spa_is_initializing = B_TRUE;
2345         error = dsl_pool_open(spa->spa_dsl_pool);
2346         spa->spa_is_initializing = B_FALSE;
2347         if (error != 0)
2348                 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2349 
2350         if (!mosconfig) {
2351                 uint64_t hostid;
2352                 nvlist_t *policy = NULL, *nvconfig;
2353 
2354                 if (load_nvlist(spa, spa->spa_config_object, &nvconfig) != 0)
2355                         return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2356 
2357                 if (!spa_is_root(spa) && nvlist_lookup_uint64(nvconfig,
2358                     ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
2359                         char *hostname;
2360                         unsigned long myhostid = 0;
2361 
2362                         VERIFY(nvlist_lookup_string(nvconfig,
2363                             ZPOOL_CONFIG_HOSTNAME, &hostname) == 0);
2364 
2365 #ifdef  _KERNEL
2366                         myhostid = zone_get_hostid(NULL);
2367 #else   /* _KERNEL */
2368                         /*
2369                          * We're emulating the system's hostid in userland, so
2370                          * we can't use zone_get_hostid().
2371                          */
2372                         (void) ddi_strtoul(hw_serial, NULL, 10, &myhostid);
2373 #endif  /* _KERNEL */
2374                         if (hostid != 0 && myhostid != 0 &&
2375                             hostid != myhostid) {
2376                                 nvlist_free(nvconfig);
2377                                 cmn_err(CE_WARN, "pool '%s' could not be "
2378                                     "loaded as it was last accessed by "
2379                                     "another system (host: %s hostid: 0x%lx). "
2380                                     "See: http://illumos.org/msg/ZFS-8000-EY",
2381                                     spa_name(spa), hostname,
2382                                     (unsigned long)hostid);
2383                                 return (SET_ERROR(EBADF));
2384                         }
2385                 }
2386                 if (nvlist_lookup_nvlist(spa->spa_config,
2387                     ZPOOL_REWIND_POLICY, &policy) == 0)
2388                         VERIFY(nvlist_add_nvlist(nvconfig,
2389                             ZPOOL_REWIND_POLICY, policy) == 0);
2390 
2391                 spa_config_set(spa, nvconfig);
2392                 spa_unload(spa);
2393                 spa_deactivate(spa);
2394                 spa_activate(spa, orig_mode);
2395 
2396                 return (spa_load(spa, state, SPA_IMPORT_EXISTING, B_TRUE));
2397         }
2398 
2399         if (spa_dir_prop(spa, DMU_POOL_SYNC_BPOBJ, &obj) != 0)
2400                 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2401         error = bpobj_open(&spa->spa_deferred_bpobj, spa->spa_meta_objset, obj);
2402         if (error != 0)
2403                 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2404 
2405         /*
2406          * Load the bit that tells us to use the new accounting function
2407          * (raid-z deflation).  If we have an older pool, this will not
2408          * be present.
2409          */
2410         error = spa_dir_prop(spa, DMU_POOL_DEFLATE, &spa->spa_deflate);
2411         if (error != 0 && error != ENOENT)
2412                 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2413 
2414         error = spa_dir_prop(spa, DMU_POOL_CREATION_VERSION,
2415             &spa->spa_creation_version);
2416         if (error != 0 && error != ENOENT)
2417                 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2418 
2419         /*
2420          * Load the persistent error log.  If we have an older pool, this will
2421          * not be present.
2422          */
2423         error = spa_dir_prop(spa, DMU_POOL_ERRLOG_LAST, &spa->spa_errlog_last);
2424         if (error != 0 && error != ENOENT)
2425                 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2426 
2427         error = spa_dir_prop(spa, DMU_POOL_ERRLOG_SCRUB,
2428             &spa->spa_errlog_scrub);
2429         if (error != 0 && error != ENOENT)
2430                 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2431 
2432         /*
2433          * Load the history object.  If we have an older pool, this
2434          * will not be present.
2435          */
2436         error = spa_dir_prop(spa, DMU_POOL_HISTORY, &spa->spa_history);
2437         if (error != 0 && error != ENOENT)
2438                 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2439 
2440         /*
2441          * If we're assembling the pool from the split-off vdevs of
2442          * an existing pool, we don't want to attach the spares & cache
2443          * devices.
2444          */
2445 
2446         /*
2447          * Load any hot spares for this pool.
2448          */
2449         error = spa_dir_prop(spa, DMU_POOL_SPARES, &spa->spa_spares.sav_object);
2450         if (error != 0 && error != ENOENT)
2451                 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2452         if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
2453                 ASSERT(spa_version(spa) >= SPA_VERSION_SPARES);
2454                 if (load_nvlist(spa, spa->spa_spares.sav_object,
2455                     &spa->spa_spares.sav_config) != 0)
2456                         return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2457 
2458                 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2459                 spa_load_spares(spa);
2460                 spa_config_exit(spa, SCL_ALL, FTAG);
2461         } else if (error == 0) {
2462                 spa->spa_spares.sav_sync = B_TRUE;
2463         }
2464 
2465         /*
2466          * Load any level 2 ARC devices for this pool.
2467          */
2468         error = spa_dir_prop(spa, DMU_POOL_L2CACHE,
2469             &spa->spa_l2cache.sav_object);
2470         if (error != 0 && error != ENOENT)
2471                 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2472         if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
2473                 ASSERT(spa_version(spa) >= SPA_VERSION_L2CACHE);
2474                 if (load_nvlist(spa, spa->spa_l2cache.sav_object,
2475                     &spa->spa_l2cache.sav_config) != 0)
2476                         return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2477 
2478                 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2479                 spa_load_l2cache(spa);
2480                 spa_config_exit(spa, SCL_ALL, FTAG);
2481         } else if (error == 0) {
2482                 spa->spa_l2cache.sav_sync = B_TRUE;
2483         }
2484 
2485         spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
2486 
2487         error = spa_dir_prop(spa, DMU_POOL_PROPS, &spa->spa_pool_props_object);
2488         if (error && error != ENOENT)
2489                 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2490 
2491         if (error == 0) {
2492                 uint64_t autoreplace;
2493 
2494                 spa_prop_find(spa, ZPOOL_PROP_BOOTFS, &spa->spa_bootfs);
2495                 spa_prop_find(spa, ZPOOL_PROP_AUTOREPLACE, &autoreplace);
2496                 spa_prop_find(spa, ZPOOL_PROP_DELEGATION, &spa->spa_delegation);
2497                 spa_prop_find(spa, ZPOOL_PROP_FAILUREMODE, &spa->spa_failmode);
2498                 spa_prop_find(spa, ZPOOL_PROP_AUTOEXPAND, &spa->spa_autoexpand);
2499                 spa_prop_find(spa, ZPOOL_PROP_DEDUPDITTO,
2500                     &spa->spa_dedup_ditto);
2501 
2502                 spa->spa_autoreplace = (autoreplace != 0);
2503         }
2504 
2505         /*
2506          * If the 'autoreplace' property is set, then post a resource notifying
2507          * the ZFS DE that it should not issue any faults for unopenable
2508          * devices.  We also iterate over the vdevs, and post a sysevent for any
2509          * unopenable vdevs so that the normal autoreplace handler can take
2510          * over.
2511          */
2512         if (spa->spa_autoreplace && state != SPA_LOAD_TRYIMPORT) {
2513                 spa_check_removed(spa->spa_root_vdev);
2514                 /*
2515                  * For the import case, this is done in spa_import(), because
2516                  * at this point we're using the spare definitions from
2517                  * the MOS config, not necessarily from the userland config.
2518                  */
2519                 if (state != SPA_LOAD_IMPORT) {
2520                         spa_aux_check_removed(&spa->spa_spares);
2521                         spa_aux_check_removed(&spa->spa_l2cache);
2522                 }
2523         }
2524 
2525         /*
2526          * Load the vdev state for all toplevel vdevs.
2527          */
2528         vdev_load(rvd);
2529 
2530         /*
2531          * Propagate the leaf DTLs we just loaded all the way up the tree.
2532          */
2533         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2534         vdev_dtl_reassess(rvd, 0, 0, B_FALSE);
2535         spa_config_exit(spa, SCL_ALL, FTAG);
2536 
2537         /*
2538          * Load the DDTs (dedup tables).
2539          */
2540         error = ddt_load(spa);
2541         if (error != 0)
2542                 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2543 
2544         spa_update_dspace(spa);
2545 
2546         /*
2547          * Validate the config, using the MOS config to fill in any
2548          * information which might be missing.  If we fail to validate
2549          * the config then declare the pool unfit for use. If we're
2550          * assembling a pool from a split, the log is not transferred
2551          * over.
2552          */
2553         if (type != SPA_IMPORT_ASSEMBLE) {
2554                 nvlist_t *nvconfig;
2555 
2556                 if (load_nvlist(spa, spa->spa_config_object, &nvconfig) != 0)
2557                         return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2558 
2559                 if (!spa_config_valid(spa, nvconfig)) {
2560                         nvlist_free(nvconfig);
2561                         return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM,
2562                             ENXIO));
2563                 }
2564                 nvlist_free(nvconfig);
2565 
2566                 /*
2567                  * Now that we've validated the config, check the state of the
2568                  * root vdev.  If it can't be opened, it indicates one or
2569                  * more toplevel vdevs are faulted.
2570                  */
2571                 if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN)
2572                         return (SET_ERROR(ENXIO));
2573 
2574                 if (spa_check_logs(spa)) {
2575                         *ereport = FM_EREPORT_ZFS_LOG_REPLAY;
2576                         return (spa_vdev_err(rvd, VDEV_AUX_BAD_LOG, ENXIO));
2577                 }
2578         }
2579 
2580         if (missing_feat_write) {
2581                 ASSERT(state == SPA_LOAD_TRYIMPORT);
2582 
2583                 /*
2584                  * At this point, we know that we can open the pool in
2585                  * read-only mode but not read-write mode. We now have enough
2586                  * information and can return to userland.
2587                  */
2588                 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT, ENOTSUP));
2589         }
2590 
2591         /*
2592          * We've successfully opened the pool, verify that we're ready
2593          * to start pushing transactions.
2594          */
2595         if (state != SPA_LOAD_TRYIMPORT) {
2596                 if (error = spa_load_verify(spa))
2597                         return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2598                             error));
2599         }
2600 
2601         if (spa_writeable(spa) && (state == SPA_LOAD_RECOVER ||
2602             spa->spa_load_max_txg == UINT64_MAX)) {
2603                 dmu_tx_t *tx;
2604                 int need_update = B_FALSE;
2605 
2606                 ASSERT(state != SPA_LOAD_TRYIMPORT);
2607 
2608                 /*
2609                  * Claim log blocks that haven't been committed yet.
2610                  * This must all happen in a single txg.
2611                  * Note: spa_claim_max_txg is updated by spa_claim_notify(),
2612                  * invoked from zil_claim_log_block()'s i/o done callback.
2613                  * Price of rollback is that we abandon the log.
2614                  */
2615                 spa->spa_claiming = B_TRUE;
2616 
2617                 tx = dmu_tx_create_assigned(spa_get_dsl(spa),
2618                     spa_first_txg(spa));
2619                 (void) dmu_objset_find(spa_name(spa),
2620                     zil_claim, tx, DS_FIND_CHILDREN);
2621                 dmu_tx_commit(tx);
2622 
2623                 spa->spa_claiming = B_FALSE;
2624 
2625                 spa_set_log_state(spa, SPA_LOG_GOOD);
2626                 spa->spa_sync_on = B_TRUE;
2627                 txg_sync_start(spa->spa_dsl_pool);
2628 
2629                 /*
2630                  * Wait for all claims to sync.  We sync up to the highest
2631                  * claimed log block birth time so that claimed log blocks
2632                  * don't appear to be from the future.  spa_claim_max_txg
2633                  * will have been set for us by either zil_check_log_chain()
2634                  * (invoked from spa_check_logs()) or zil_claim() above.
2635                  */
2636                 txg_wait_synced(spa->spa_dsl_pool, spa->spa_claim_max_txg);
2637 
2638                 /*
2639                  * If the config cache is stale, or we have uninitialized
2640                  * metaslabs (see spa_vdev_add()), then update the config.
2641                  *
2642                  * If this is a verbatim import, trust the current
2643                  * in-core spa_config and update the disk labels.
2644                  */
2645                 if (config_cache_txg != spa->spa_config_txg ||
2646                     state == SPA_LOAD_IMPORT ||
2647                     state == SPA_LOAD_RECOVER ||
2648                     (spa->spa_import_flags & ZFS_IMPORT_VERBATIM))
2649                         need_update = B_TRUE;
2650 
2651                 for (int c = 0; c < rvd->vdev_children; c++)
2652                         if (rvd->vdev_child[c]->vdev_ms_array == 0)
2653                                 need_update = B_TRUE;
2654 
2655                 /*
2656                  * Update the config cache asychronously in case we're the
2657                  * root pool, in which case the config cache isn't writable yet.
2658                  */
2659                 if (need_update)
2660                         spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
2661 
2662                 /*
2663                  * Check all DTLs to see if anything needs resilvering.
2664                  */
2665                 if (!dsl_scan_resilvering(spa->spa_dsl_pool) &&
2666                     vdev_resilver_needed(rvd, NULL, NULL))
2667                         spa_async_request(spa, SPA_ASYNC_RESILVER);
2668 
2669                 /*
2670                  * Log the fact that we booted up (so that we can detect if
2671                  * we rebooted in the middle of an operation).
2672                  */
2673                 spa_history_log_version(spa, "open");
2674 
2675                 /*
2676                  * Delete any inconsistent datasets.
2677                  */
2678                 (void) dmu_objset_find(spa_name(spa),
2679                     dsl_destroy_inconsistent, NULL, DS_FIND_CHILDREN);
2680 
2681                 /*
2682                  * Clean up any stale temporary dataset userrefs.
2683                  */
2684                 dsl_pool_clean_tmp_userrefs(spa->spa_dsl_pool);
2685         }
2686 
2687         return (0);
2688 }
2689 
2690 static int
2691 spa_load_retry(spa_t *spa, spa_load_state_t state, int mosconfig)
2692 {
2693         int mode = spa->spa_mode;
2694 
2695         spa_unload(spa);
2696         spa_deactivate(spa);
2697 
2698         spa->spa_load_max_txg--;
2699 
2700         spa_activate(spa, mode);
2701         spa_async_suspend(spa);
2702 
2703         return (spa_load(spa, state, SPA_IMPORT_EXISTING, mosconfig));
2704 }
2705 
2706 /*
2707  * If spa_load() fails this function will try loading prior txg's. If
2708  * 'state' is SPA_LOAD_RECOVER and one of these loads succeeds the pool
2709  * will be rewound to that txg. If 'state' is not SPA_LOAD_RECOVER this
2710  * function will not rewind the pool and will return the same error as
2711  * spa_load().
2712  */
2713 static int
2714 spa_load_best(spa_t *spa, spa_load_state_t state, int mosconfig,
2715     uint64_t max_request, int rewind_flags)
2716 {
2717         nvlist_t *loadinfo = NULL;
2718         nvlist_t *config = NULL;
2719         int load_error, rewind_error;
2720         uint64_t safe_rewind_txg;
2721         uint64_t min_txg;
2722 
2723         if (spa->spa_load_txg && state == SPA_LOAD_RECOVER) {
2724                 spa->spa_load_max_txg = spa->spa_load_txg;
2725                 spa_set_log_state(spa, SPA_LOG_CLEAR);
2726         } else {
2727                 spa->spa_load_max_txg = max_request;
2728         }
2729 
2730         load_error = rewind_error = spa_load(spa, state, SPA_IMPORT_EXISTING,
2731             mosconfig);
2732         if (load_error == 0)
2733                 return (0);
2734 
2735         if (spa->spa_root_vdev != NULL)
2736                 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
2737 
2738         spa->spa_last_ubsync_txg = spa->spa_uberblock.ub_txg;
2739         spa->spa_last_ubsync_txg_ts = spa->spa_uberblock.ub_timestamp;
2740 
2741         if (rewind_flags & ZPOOL_NEVER_REWIND) {
2742                 nvlist_free(config);
2743                 return (load_error);
2744         }
2745 
2746         if (state == SPA_LOAD_RECOVER) {
2747                 /* Price of rolling back is discarding txgs, including log */
2748                 spa_set_log_state(spa, SPA_LOG_CLEAR);
2749         } else {
2750                 /*
2751                  * If we aren't rolling back save the load info from our first
2752                  * import attempt so that we can restore it after attempting
2753                  * to rewind.
2754                  */
2755                 loadinfo = spa->spa_load_info;
2756                 spa->spa_load_info = fnvlist_alloc();
2757         }
2758 
2759         spa->spa_load_max_txg = spa->spa_last_ubsync_txg;
2760         safe_rewind_txg = spa->spa_last_ubsync_txg - TXG_DEFER_SIZE;
2761         min_txg = (rewind_flags & ZPOOL_EXTREME_REWIND) ?
2762             TXG_INITIAL : safe_rewind_txg;
2763 
2764         /*
2765          * Continue as long as we're finding errors, we're still within
2766          * the acceptable rewind range, and we're still finding uberblocks
2767          */
2768         while (rewind_error && spa->spa_uberblock.ub_txg >= min_txg &&
2769             spa->spa_uberblock.ub_txg <= spa->spa_load_max_txg) {
2770                 if (spa->spa_load_max_txg < safe_rewind_txg)
2771                         spa->spa_extreme_rewind = B_TRUE;
2772                 rewind_error = spa_load_retry(spa, state, mosconfig);
2773         }
2774 
2775         spa->spa_extreme_rewind = B_FALSE;
2776         spa->spa_load_max_txg = UINT64_MAX;
2777 
2778         if (config && (rewind_error || state != SPA_LOAD_RECOVER))
2779                 spa_config_set(spa, config);
2780 
2781         if (state == SPA_LOAD_RECOVER) {
2782                 ASSERT3P(loadinfo, ==, NULL);
2783                 return (rewind_error);
2784         } else {
2785                 /* Store the rewind info as part of the initial load info */
2786                 fnvlist_add_nvlist(loadinfo, ZPOOL_CONFIG_REWIND_INFO,
2787                     spa->spa_load_info);
2788 
2789                 /* Restore the initial load info */
2790                 fnvlist_free(spa->spa_load_info);
2791                 spa->spa_load_info = loadinfo;
2792 
2793                 return (load_error);
2794         }
2795 }
2796 
2797 /*
2798  * Pool Open/Import
2799  *
2800  * The import case is identical to an open except that the configuration is sent
2801  * down from userland, instead of grabbed from the configuration cache.  For the
2802  * case of an open, the pool configuration will exist in the
2803  * POOL_STATE_UNINITIALIZED state.
2804  *
2805  * The stats information (gen/count/ustats) is used to gather vdev statistics at
2806  * the same time open the pool, without having to keep around the spa_t in some
2807  * ambiguous state.
2808  */
2809 static int
2810 spa_open_common(const char *pool, spa_t **spapp, void *tag, nvlist_t *nvpolicy,
2811     nvlist_t **config)
2812 {
2813         spa_t *spa;
2814         spa_load_state_t state = SPA_LOAD_OPEN;
2815         int error;
2816         int locked = B_FALSE;
2817 
2818         *spapp = NULL;
2819 
2820         /*
2821          * As disgusting as this is, we need to support recursive calls to this
2822          * function because dsl_dir_open() is called during spa_load(), and ends
2823          * up calling spa_open() again.  The real fix is to figure out how to
2824          * avoid dsl_dir_open() calling this in the first place.
2825          */
2826         if (mutex_owner(&spa_namespace_lock) != curthread) {
2827                 mutex_enter(&spa_namespace_lock);
2828                 locked = B_TRUE;
2829         }
2830 
2831         if ((spa = spa_lookup(pool)) == NULL) {
2832                 if (locked)
2833                         mutex_exit(&spa_namespace_lock);
2834                 return (SET_ERROR(ENOENT));
2835         }
2836 
2837         if (spa->spa_state == POOL_STATE_UNINITIALIZED) {
2838                 zpool_rewind_policy_t policy;
2839 
2840                 zpool_get_rewind_policy(nvpolicy ? nvpolicy : spa->spa_config,
2841                     &policy);
2842                 if (policy.zrp_request & ZPOOL_DO_REWIND)
2843                         state = SPA_LOAD_RECOVER;
2844 
2845                 spa_activate(spa, spa_mode_global);
2846 
2847                 if (state != SPA_LOAD_RECOVER)
2848                         spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
2849 
2850                 error = spa_load_best(spa, state, B_FALSE, policy.zrp_txg,
2851                     policy.zrp_request);
2852 
2853                 if (error == EBADF) {
2854                         /*
2855                          * If vdev_validate() returns failure (indicated by
2856                          * EBADF), it indicates that one of the vdevs indicates
2857                          * that the pool has been exported or destroyed.  If
2858                          * this is the case, the config cache is out of sync and
2859                          * we should remove the pool from the namespace.
2860                          */
2861                         spa_unload(spa);
2862                         spa_deactivate(spa);
2863                         spa_config_sync(spa, B_TRUE, B_TRUE);
2864                         spa_remove(spa);
2865                         if (locked)
2866                                 mutex_exit(&spa_namespace_lock);
2867                         return (SET_ERROR(ENOENT));
2868                 }
2869 
2870                 if (error) {
2871                         /*
2872                          * We can't open the pool, but we still have useful
2873                          * information: the state of each vdev after the
2874                          * attempted vdev_open().  Return this to the user.
2875                          */
2876                         if (config != NULL && spa->spa_config) {
2877                                 VERIFY(nvlist_dup(spa->spa_config, config,
2878                                     KM_SLEEP) == 0);
2879                                 VERIFY(nvlist_add_nvlist(*config,
2880                                     ZPOOL_CONFIG_LOAD_INFO,
2881                                     spa->spa_load_info) == 0);
2882                         }
2883                         spa_unload(spa);
2884                         spa_deactivate(spa);
2885                         spa->spa_last_open_failed = error;
2886                         if (locked)
2887                                 mutex_exit(&spa_namespace_lock);
2888                         *spapp = NULL;
2889                         return (error);
2890                 }
2891         }
2892 
2893         spa_open_ref(spa, tag);
2894 
2895         if (config != NULL)
2896                 *config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
2897 
2898         /*
2899          * If we've recovered the pool, pass back any information we
2900          * gathered while doing the load.
2901          */
2902         if (state == SPA_LOAD_RECOVER) {
2903                 VERIFY(nvlist_add_nvlist(*config, ZPOOL_CONFIG_LOAD_INFO,
2904                     spa->spa_load_info) == 0);
2905         }
2906 
2907         if (locked) {
2908                 spa->spa_last_open_failed = 0;
2909                 spa->spa_last_ubsync_txg = 0;
2910                 spa->spa_load_txg = 0;
2911                 mutex_exit(&spa_namespace_lock);
2912         }
2913 
2914         *spapp = spa;
2915 
2916         return (0);
2917 }
2918 
2919 int
2920 spa_open_rewind(const char *name, spa_t **spapp, void *tag, nvlist_t *policy,
2921     nvlist_t **config)
2922 {
2923         return (spa_open_common(name, spapp, tag, policy, config));
2924 }
2925 
2926 int
2927 spa_open(const char *name, spa_t **spapp, void *tag)
2928 {
2929         return (spa_open_common(name, spapp, tag, NULL, NULL));
2930 }
2931 
2932 /*
2933  * Lookup the given spa_t, incrementing the inject count in the process,
2934  * preventing it from being exported or destroyed.
2935  */
2936 spa_t *
2937 spa_inject_addref(char *name)
2938 {
2939         spa_t *spa;
2940 
2941         mutex_enter(&spa_namespace_lock);
2942         if ((spa = spa_lookup(name)) == NULL) {
2943                 mutex_exit(&spa_namespace_lock);
2944                 return (NULL);
2945         }
2946         spa->spa_inject_ref++;
2947         mutex_exit(&spa_namespace_lock);
2948 
2949         return (spa);
2950 }
2951 
2952 void
2953 spa_inject_delref(spa_t *spa)
2954 {
2955         mutex_enter(&spa_namespace_lock);
2956         spa->spa_inject_ref--;
2957         mutex_exit(&spa_namespace_lock);
2958 }
2959 
2960 /*
2961  * Add spares device information to the nvlist.
2962  */
2963 static void
2964 spa_add_spares(spa_t *spa, nvlist_t *config)
2965 {
2966         nvlist_t **spares;
2967         uint_t i, nspares;
2968         nvlist_t *nvroot;
2969         uint64_t guid;
2970         vdev_stat_t *vs;
2971         uint_t vsc;
2972         uint64_t pool;
2973 
2974         ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
2975 
2976         if (spa->spa_spares.sav_count == 0)
2977                 return;
2978 
2979         VERIFY(nvlist_lookup_nvlist(config,
2980             ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
2981         VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
2982             ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
2983         if (nspares != 0) {
2984                 VERIFY(nvlist_add_nvlist_array(nvroot,
2985                     ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
2986                 VERIFY(nvlist_lookup_nvlist_array(nvroot,
2987                     ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
2988 
2989                 /*
2990                  * Go through and find any spares which have since been
2991                  * repurposed as an active spare.  If this is the case, update
2992                  * their status appropriately.
2993                  */
2994                 for (i = 0; i < nspares; i++) {
2995                         VERIFY(nvlist_lookup_uint64(spares[i],
2996                             ZPOOL_CONFIG_GUID, &guid) == 0);
2997                         if (spa_spare_exists(guid, &pool, NULL) &&
2998                             pool != 0ULL) {
2999                                 VERIFY(nvlist_lookup_uint64_array(
3000                                     spares[i], ZPOOL_CONFIG_VDEV_STATS,
3001                                     (uint64_t **)&vs, &vsc) == 0);
3002                                 vs->vs_state = VDEV_STATE_CANT_OPEN;
3003                                 vs->vs_aux = VDEV_AUX_SPARED;
3004                         }
3005                 }
3006         }
3007 }
3008 
3009 /*
3010  * Add l2cache device information to the nvlist, including vdev stats.
3011  */
3012 static void
3013 spa_add_l2cache(spa_t *spa, nvlist_t *config)
3014 {
3015         nvlist_t **l2cache;
3016         uint_t i, j, nl2cache;
3017         nvlist_t *nvroot;
3018         uint64_t guid;
3019         vdev_t *vd;
3020         vdev_stat_t *vs;
3021         uint_t vsc;
3022 
3023         ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
3024 
3025         if (spa->spa_l2cache.sav_count == 0)
3026                 return;
3027 
3028         VERIFY(nvlist_lookup_nvlist(config,
3029             ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
3030         VERIFY(nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
3031             ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
3032         if (nl2cache != 0) {
3033                 VERIFY(nvlist_add_nvlist_array(nvroot,
3034                     ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
3035                 VERIFY(nvlist_lookup_nvlist_array(nvroot,
3036                     ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
3037 
3038                 /*
3039                  * Update level 2 cache device stats.
3040                  */
3041 
3042                 for (i = 0; i < nl2cache; i++) {
3043                         VERIFY(nvlist_lookup_uint64(l2cache[i],
3044                             ZPOOL_CONFIG_GUID, &guid) == 0);
3045 
3046                         vd = NULL;
3047                         for (j = 0; j < spa->spa_l2cache.sav_count; j++) {
3048                                 if (guid ==
3049                                     spa->spa_l2cache.sav_vdevs[j]->vdev_guid) {
3050                                         vd = spa->spa_l2cache.sav_vdevs[j];
3051                                         break;
3052                                 }
3053                         }
3054                         ASSERT(vd != NULL);
3055 
3056                         VERIFY(nvlist_lookup_uint64_array(l2cache[i],
3057                             ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc)
3058                             == 0);
3059                         vdev_get_stats(vd, vs);
3060                 }
3061         }
3062 }
3063 
3064 static void
3065 spa_add_feature_stats(spa_t *spa, nvlist_t *config)
3066 {
3067         nvlist_t *features;
3068         zap_cursor_t zc;
3069         zap_attribute_t za;
3070 
3071         ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
3072         VERIFY(nvlist_alloc(&features, NV_UNIQUE_NAME, KM_SLEEP) == 0);
3073 
3074         if (spa->spa_feat_for_read_obj != 0) {
3075                 for (zap_cursor_init(&zc, spa->spa_meta_objset,
3076                     spa->spa_feat_for_read_obj);
3077                     zap_cursor_retrieve(&zc, &za) == 0;
3078                     zap_cursor_advance(&zc)) {
3079                         ASSERT(za.za_integer_length == sizeof (uint64_t) &&
3080                             za.za_num_integers == 1);
3081                         VERIFY3U(0, ==, nvlist_add_uint64(features, za.za_name,
3082                             za.za_first_integer));
3083                 }
3084                 zap_cursor_fini(&zc);
3085         }
3086 
3087         if (spa->spa_feat_for_write_obj != 0) {
3088                 for (zap_cursor_init(&zc, spa->spa_meta_objset,
3089                     spa->spa_feat_for_write_obj);
3090                     zap_cursor_retrieve(&zc, &za) == 0;
3091                     zap_cursor_advance(&zc)) {
3092                         ASSERT(za.za_integer_length == sizeof (uint64_t) &&
3093                             za.za_num_integers == 1);
3094                         VERIFY3U(0, ==, nvlist_add_uint64(features, za.za_name,
3095                             za.za_first_integer));
3096                 }
3097                 zap_cursor_fini(&zc);
3098         }
3099 
3100         VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_FEATURE_STATS,
3101             features) == 0);
3102         nvlist_free(features);
3103 }
3104 
3105 int
3106 spa_get_stats(const char *name, nvlist_t **config,
3107     char *altroot, size_t buflen)
3108 {
3109         int error;
3110         spa_t *spa;
3111 
3112         *config = NULL;
3113         error = spa_open_common(name, &spa, FTAG, NULL, config);
3114 
3115         if (spa != NULL) {
3116                 /*
3117                  * This still leaves a window of inconsistency where the spares
3118                  * or l2cache devices could change and the config would be
3119                  * self-inconsistent.
3120                  */
3121                 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3122 
3123                 if (*config != NULL) {
3124                         uint64_t loadtimes[2];
3125 
3126                         loadtimes[0] = spa->spa_loaded_ts.tv_sec;
3127                         loadtimes[1] = spa->spa_loaded_ts.tv_nsec;
3128                         VERIFY(nvlist_add_uint64_array(*config,
3129                             ZPOOL_CONFIG_LOADED_TIME, loadtimes, 2) == 0);
3130 
3131                         VERIFY(nvlist_add_uint64(*config,
3132                             ZPOOL_CONFIG_ERRCOUNT,
3133                             spa_get_errlog_size(spa)) == 0);
3134 
3135                         if (spa_suspended(spa))
3136                                 VERIFY(nvlist_add_uint64(*config,
3137                                     ZPOOL_CONFIG_SUSPENDED,
3138                                     spa->spa_failmode) == 0);
3139 
3140                         spa_add_spares(spa, *config);
3141                         spa_add_l2cache(spa, *config);
3142                         spa_add_feature_stats(spa, *config);
3143                 }
3144         }
3145 
3146         /*
3147          * We want to get the alternate root even for faulted pools, so we cheat
3148          * and call spa_lookup() directly.
3149          */
3150         if (altroot) {
3151                 if (spa == NULL) {
3152                         mutex_enter(&spa_namespace_lock);
3153                         spa = spa_lookup(name);
3154                         if (spa)
3155                                 spa_altroot(spa, altroot, buflen);
3156                         else
3157                                 altroot[0] = '\0';
3158                         spa = NULL;
3159                         mutex_exit(&spa_namespace_lock);
3160                 } else {
3161                         spa_altroot(spa, altroot, buflen);
3162                 }
3163         }
3164 
3165         if (spa != NULL) {
3166                 spa_config_exit(spa, SCL_CONFIG, FTAG);
3167                 spa_close(spa, FTAG);
3168         }
3169 
3170         return (error);
3171 }
3172 
3173 /*
3174  * Validate that the auxiliary device array is well formed.  We must have an
3175  * array of nvlists, each which describes a valid leaf vdev.  If this is an
3176  * import (mode is VDEV_ALLOC_SPARE), then we allow corrupted spares to be
3177  * specified, as long as they are well-formed.
3178  */
3179 static int
3180 spa_validate_aux_devs(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode,
3181     spa_aux_vdev_t *sav, const char *config, uint64_t version,
3182     vdev_labeltype_t label)
3183 {
3184         nvlist_t **dev;
3185         uint_t i, ndev;
3186         vdev_t *vd;
3187         int error;
3188 
3189         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
3190 
3191         /*
3192          * It's acceptable to have no devs specified.
3193          */
3194         if (nvlist_lookup_nvlist_array(nvroot, config, &dev, &ndev) != 0)
3195                 return (0);
3196 
3197         if (ndev == 0)
3198                 return (SET_ERROR(EINVAL));
3199 
3200         /*
3201          * Make sure the pool is formatted with a version that supports this
3202          * device type.
3203          */
3204         if (spa_version(spa) < version)
3205                 return (SET_ERROR(ENOTSUP));
3206 
3207         /*
3208          * Set the pending device list so we correctly handle device in-use
3209          * checking.
3210          */
3211         sav->sav_pending = dev;
3212         sav->sav_npending = ndev;
3213 
3214         for (i = 0; i < ndev; i++) {
3215                 if ((error = spa_config_parse(spa, &vd, dev[i], NULL, 0,
3216                     mode)) != 0)
3217                         goto out;
3218 
3219                 if (!vd->vdev_ops->vdev_op_leaf) {
3220                         vdev_free(vd);
3221                         error = SET_ERROR(EINVAL);
3222                         goto out;
3223                 }
3224 
3225                 /*
3226                  * The L2ARC currently only supports disk devices in
3227                  * kernel context.  For user-level testing, we allow it.
3228                  */
3229 #ifdef _KERNEL
3230                 if ((strcmp(config, ZPOOL_CONFIG_L2CACHE) == 0) &&
3231                     strcmp(vd->vdev_ops->vdev_op_type, VDEV_TYPE_DISK) != 0) {
3232                         error = SET_ERROR(ENOTBLK);
3233                         vdev_free(vd);
3234                         goto out;
3235                 }
3236 #endif
3237                 vd->vdev_top = vd;
3238 
3239                 if ((error = vdev_open(vd)) == 0 &&
3240                     (error = vdev_label_init(vd, crtxg, label)) == 0) {
3241                         VERIFY(nvlist_add_uint64(dev[i], ZPOOL_CONFIG_GUID,
3242                             vd->vdev_guid) == 0);
3243                 }
3244 
3245                 vdev_free(vd);
3246 
3247                 if (error &&
3248                     (mode != VDEV_ALLOC_SPARE && mode != VDEV_ALLOC_L2CACHE))
3249                         goto out;
3250                 else
3251                         error = 0;
3252         }
3253 
3254 out:
3255         sav->sav_pending = NULL;
3256         sav->sav_npending = 0;
3257         return (error);
3258 }
3259 
3260 static int
3261 spa_validate_aux(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode)
3262 {
3263         int error;
3264 
3265         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
3266 
3267         if ((error = spa_validate_aux_devs(spa, nvroot, crtxg, mode,
3268             &spa->spa_spares, ZPOOL_CONFIG_SPARES, SPA_VERSION_SPARES,
3269             VDEV_LABEL_SPARE)) != 0) {
3270                 return (error);
3271         }
3272 
3273         return (spa_validate_aux_devs(spa, nvroot, crtxg, mode,
3274             &spa->spa_l2cache, ZPOOL_CONFIG_L2CACHE, SPA_VERSION_L2CACHE,
3275             VDEV_LABEL_L2CACHE));
3276 }
3277 
3278 static void
3279 spa_set_aux_vdevs(spa_aux_vdev_t *sav, nvlist_t **devs, int ndevs,
3280     const char *config)
3281 {
3282         int i;
3283 
3284         if (sav->sav_config != NULL) {
3285                 nvlist_t **olddevs;
3286                 uint_t oldndevs;
3287                 nvlist_t **newdevs;
3288 
3289                 /*
3290                  * Generate new dev list by concatentating with the
3291                  * current dev list.
3292                  */
3293                 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config, config,
3294                     &olddevs, &oldndevs) == 0);
3295 
3296                 newdevs = kmem_alloc(sizeof (void *) *
3297                     (ndevs + oldndevs), KM_SLEEP);
3298                 for (i = 0; i < oldndevs; i++)
3299                         VERIFY(nvlist_dup(olddevs[i], &newdevs[i],
3300                             KM_SLEEP) == 0);
3301                 for (i = 0; i < ndevs; i++)
3302                         VERIFY(nvlist_dup(devs[i], &newdevs[i + oldndevs],
3303                             KM_SLEEP) == 0);
3304 
3305                 VERIFY(nvlist_remove(sav->sav_config, config,
3306                     DATA_TYPE_NVLIST_ARRAY) == 0);
3307 
3308                 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
3309                     config, newdevs, ndevs + oldndevs) == 0);
3310                 for (i = 0; i < oldndevs + ndevs; i++)
3311                         nvlist_free(newdevs[i]);
3312                 kmem_free(newdevs, (oldndevs + ndevs) * sizeof (void *));
3313         } else {
3314                 /*
3315                  * Generate a new dev list.
3316                  */
3317                 VERIFY(nvlist_alloc(&sav->sav_config, NV_UNIQUE_NAME,
3318                     KM_SLEEP) == 0);
3319                 VERIFY(nvlist_add_nvlist_array(sav->sav_config, config,
3320                     devs, ndevs) == 0);
3321         }
3322 }
3323 
3324 /*
3325  * Stop and drop level 2 ARC devices
3326  */
3327 void
3328 spa_l2cache_drop(spa_t *spa)
3329 {
3330         vdev_t *vd;
3331         int i;
3332         spa_aux_vdev_t *sav = &spa->spa_l2cache;
3333 
3334         for (i = 0; i < sav->sav_count; i++) {
3335                 uint64_t pool;
3336 
3337                 vd = sav->sav_vdevs[i];
3338                 ASSERT(vd != NULL);
3339 
3340                 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
3341                     pool != 0ULL && l2arc_vdev_present(vd))
3342                         l2arc_remove_vdev(vd);
3343         }
3344 }
3345 
3346 /*
3347  * Pool Creation
3348  */
3349 int
3350 spa_create(const char *pool, nvlist_t *nvroot, nvlist_t *props,
3351     nvlist_t *zplprops)
3352 {
3353         spa_t *spa;
3354         char *altroot = NULL;
3355         vdev_t *rvd;
3356         dsl_pool_t *dp;
3357         dmu_tx_t *tx;
3358         int error = 0;
3359         uint64_t txg = TXG_INITIAL;
3360         nvlist_t **spares, **l2cache;
3361         uint_t nspares, nl2cache;
3362         uint64_t version, obj;
3363         boolean_t has_features;
3364 
3365         /*
3366          * If this pool already exists, return failure.
3367          */
3368         mutex_enter(&spa_namespace_lock);
3369         if (spa_lookup(pool) != NULL) {
3370                 mutex_exit(&spa_namespace_lock);
3371                 return (SET_ERROR(EEXIST));
3372         }
3373 
3374         /*
3375          * Allocate a new spa_t structure.
3376          */
3377         (void) nvlist_lookup_string(props,
3378             zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
3379         spa = spa_add(pool, NULL, altroot);
3380         spa_activate(spa, spa_mode_global);
3381 
3382         if (props && (error = spa_prop_validate(spa, props))) {
3383                 spa_deactivate(spa);
3384                 spa_remove(spa);
3385                 mutex_exit(&spa_namespace_lock);
3386                 return (error);
3387         }
3388 
3389         has_features = B_FALSE;
3390         for (nvpair_t *elem = nvlist_next_nvpair(props, NULL);
3391             elem != NULL; elem = nvlist_next_nvpair(props, elem)) {
3392                 if (zpool_prop_feature(nvpair_name(elem)))
3393                         has_features = B_TRUE;
3394         }
3395 
3396         if (has_features || nvlist_lookup_uint64(props,
3397             zpool_prop_to_name(ZPOOL_PROP_VERSION), &version) != 0) {
3398                 version = SPA_VERSION;
3399         }
3400         ASSERT(SPA_VERSION_IS_SUPPORTED(version));
3401 
3402         spa->spa_first_txg = txg;
3403         spa->spa_uberblock.ub_txg = txg - 1;
3404         spa->spa_uberblock.ub_version = version;
3405         spa->spa_ubsync = spa->spa_uberblock;
3406 
3407         /*
3408          * Create "The Godfather" zio to hold all async IOs
3409          */
3410         spa->spa_async_zio_root = zio_root(spa, NULL, NULL,
3411             ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE | ZIO_FLAG_GODFATHER);
3412 
3413         /*
3414          * Create the root vdev.
3415          */
3416         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3417 
3418         error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, VDEV_ALLOC_ADD);
3419 
3420         ASSERT(error != 0 || rvd != NULL);
3421         ASSERT(error != 0 || spa->spa_root_vdev == rvd);
3422 
3423         if (error == 0 && !zfs_allocatable_devs(nvroot))
3424                 error = SET_ERROR(EINVAL);
3425 
3426         if (error == 0 &&
3427             (error = vdev_create(rvd, txg, B_FALSE)) == 0 &&
3428             (error = spa_validate_aux(spa, nvroot, txg,
3429             VDEV_ALLOC_ADD)) == 0) {
3430                 for (int c = 0; c < rvd->vdev_children; c++) {
3431                         vdev_metaslab_set_size(rvd->vdev_child[c]);
3432                         vdev_expand(rvd->vdev_child[c], txg);
3433                 }
3434         }
3435 
3436         spa_config_exit(spa, SCL_ALL, FTAG);
3437 
3438         if (error != 0) {
3439                 spa_unload(spa);
3440                 spa_deactivate(spa);
3441                 spa_remove(spa);
3442                 mutex_exit(&spa_namespace_lock);
3443                 return (error);
3444         }
3445 
3446         /*
3447          * Get the list of spares, if specified.
3448          */
3449         if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
3450             &spares, &nspares) == 0) {
3451                 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config, NV_UNIQUE_NAME,
3452                     KM_SLEEP) == 0);
3453                 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
3454                     ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
3455                 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3456                 spa_load_spares(spa);
3457                 spa_config_exit(spa, SCL_ALL, FTAG);
3458                 spa->spa_spares.sav_sync = B_TRUE;
3459         }
3460 
3461         /*
3462          * Get the list of level 2 cache devices, if specified.
3463          */
3464         if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
3465             &l2cache, &nl2cache) == 0) {
3466                 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
3467                     NV_UNIQUE_NAME, KM_SLEEP) == 0);
3468                 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
3469                     ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
3470                 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3471                 spa_load_l2cache(spa);
3472                 spa_config_exit(spa, SCL_ALL, FTAG);
3473                 spa->spa_l2cache.sav_sync = B_TRUE;
3474         }
3475 
3476         spa->spa_is_initializing = B_TRUE;
3477         spa->spa_dsl_pool = dp = dsl_pool_create(spa, zplprops, txg);
3478         spa->spa_meta_objset = dp->dp_meta_objset;
3479         spa->spa_is_initializing = B_FALSE;
3480 
3481         /*
3482          * Create DDTs (dedup tables).
3483          */
3484         ddt_create(spa);
3485 
3486         spa_update_dspace(spa);
3487 
3488         tx = dmu_tx_create_assigned(dp, txg);
3489 
3490         /*
3491          * Create the pool config object.
3492          */
3493         spa->spa_config_object = dmu_object_alloc(spa->spa_meta_objset,
3494             DMU_OT_PACKED_NVLIST, SPA_CONFIG_BLOCKSIZE,
3495             DMU_OT_PACKED_NVLIST_SIZE, sizeof (uint64_t), tx);
3496 
3497         if (zap_add(spa->spa_meta_objset,
3498             DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CONFIG,
3499             sizeof (uint64_t), 1, &spa->spa_config_object, tx) != 0) {
3500                 cmn_err(CE_PANIC, "failed to add pool config");
3501         }
3502 
3503         if (spa_version(spa) >= SPA_VERSION_FEATURES)
3504                 spa_feature_create_zap_objects(spa, tx);
3505 
3506         if (zap_add(spa->spa_meta_objset,
3507             DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CREATION_VERSION,
3508             sizeof (uint64_t), 1, &version, tx) != 0) {
3509                 cmn_err(CE_PANIC, "failed to add pool version");
3510         }
3511 
3512         /* Newly created pools with the right version are always deflated. */
3513         if (version >= SPA_VERSION_RAIDZ_DEFLATE) {
3514                 spa->spa_deflate = TRUE;
3515                 if (zap_add(spa->spa_meta_objset,
3516                     DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
3517                     sizeof (uint64_t), 1, &spa->spa_deflate, tx) != 0) {
3518                         cmn_err(CE_PANIC, "failed to add deflate");
3519                 }
3520         }
3521 
3522         /*
3523          * Create the deferred-free bpobj.  Turn off compression
3524          * because sync-to-convergence takes longer if the blocksize
3525          * keeps changing.
3526          */
3527         obj = bpobj_alloc(spa->spa_meta_objset, 1 << 14, tx);
3528         dmu_object_set_compress(spa->spa_meta_objset, obj,
3529             ZIO_COMPRESS_OFF, tx);
3530         if (zap_add(spa->spa_meta_objset,
3531             DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SYNC_BPOBJ,
3532             sizeof (uint64_t), 1, &obj, tx) != 0) {
3533                 cmn_err(CE_PANIC, "failed to add bpobj");
3534         }
3535         VERIFY3U(0, ==, bpobj_open(&spa->spa_deferred_bpobj,
3536             spa->spa_meta_objset, obj));
3537 
3538         /*
3539          * Create the pool's history object.
3540          */
3541         if (version >= SPA_VERSION_ZPOOL_HISTORY)
3542                 spa_history_create_obj(spa, tx);
3543 
3544         /*
3545          * Set pool properties.
3546          */
3547         spa->spa_bootfs = zpool_prop_default_numeric(ZPOOL_PROP_BOOTFS);
3548         spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
3549         spa->spa_failmode = zpool_prop_default_numeric(ZPOOL_PROP_FAILUREMODE);
3550         spa->spa_autoexpand = zpool_prop_default_numeric(ZPOOL_PROP_AUTOEXPAND);
3551 
3552         if (props != NULL) {
3553                 spa_configfile_set(spa, props, B_FALSE);
3554                 spa_sync_props(props, tx);
3555         }
3556 
3557         dmu_tx_commit(tx);
3558 
3559         spa->spa_sync_on = B_TRUE;
3560         txg_sync_start(spa->spa_dsl_pool);
3561 
3562         /*
3563          * We explicitly wait for the first transaction to complete so that our
3564          * bean counters are appropriately updated.
3565          */
3566         txg_wait_synced(spa->spa_dsl_pool, txg);
3567 
3568         spa_config_sync(spa, B_FALSE, B_TRUE);
3569 
3570         spa_history_log_version(spa, "create");
3571 
3572         spa->spa_minref = refcount_count(&spa->spa_refcount);
3573 
3574         mutex_exit(&spa_namespace_lock);
3575 
3576         return (0);
3577 }
3578 
3579 #ifdef _KERNEL
3580 /*
3581  * Get the root pool information from the root disk, then import the root pool
3582  * during the system boot up time.
3583  */
3584 extern int vdev_disk_read_rootlabel(char *, char *, nvlist_t **);
3585 
3586 static nvlist_t *
3587 spa_generate_rootconf(char *devpath, char *devid, uint64_t *guid)
3588 {
3589         nvlist_t *config;
3590         nvlist_t *nvtop, *nvroot;
3591         uint64_t pgid;
3592 
3593         if (vdev_disk_read_rootlabel(devpath, devid, &config) != 0)
3594                 return (NULL);
3595 
3596         /*
3597          * Add this top-level vdev to the child array.
3598          */
3599         VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3600             &nvtop) == 0);
3601         VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
3602             &pgid) == 0);
3603         VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID, guid) == 0);
3604 
3605         /*
3606          * Put this pool's top-level vdevs into a root vdev.
3607          */
3608         VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
3609         VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
3610             VDEV_TYPE_ROOT) == 0);
3611         VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
3612         VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
3613         VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
3614             &nvtop, 1) == 0);
3615 
3616         /*
3617          * Replace the existing vdev_tree with the new root vdev in
3618          * this pool's configuration (remove the old, add the new).
3619          */
3620         VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
3621         nvlist_free(nvroot);
3622         return (config);
3623 }
3624 
3625 /*
3626  * Walk the vdev tree and see if we can find a device with "better"
3627  * configuration. A configuration is "better" if the label on that
3628  * device has a more recent txg.
3629  */
3630 static void
3631 spa_alt_rootvdev(vdev_t *vd, vdev_t **avd, uint64_t *txg)
3632 {
3633         for (int c = 0; c < vd->vdev_children; c++)
3634                 spa_alt_rootvdev(vd->vdev_child[c], avd, txg);
3635 
3636         if (vd->vdev_ops->vdev_op_leaf) {
3637                 nvlist_t *label;
3638                 uint64_t label_txg;
3639 
3640                 if (vdev_disk_read_rootlabel(vd->vdev_physpath, vd->vdev_devid,
3641                     &label) != 0)
3642                         return;
3643 
3644                 VERIFY(nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_TXG,
3645                     &label_txg) == 0);
3646 
3647                 /*
3648                  * Do we have a better boot device?
3649                  */
3650                 if (label_txg > *txg) {
3651                         *txg = label_txg;
3652                         *avd = vd;
3653                 }
3654                 nvlist_free(label);
3655         }
3656 }
3657 
3658 /*
3659  * Import a root pool.
3660  *
3661  * For x86. devpath_list will consist of devid and/or physpath name of
3662  * the vdev (e.g. "id1,sd@SSEAGATE..." or "/pci@1f,0/ide@d/disk@0,0:a").
3663  * The GRUB "findroot" command will return the vdev we should boot.
3664  *
3665  * For Sparc, devpath_list consists the physpath name of the booting device
3666  * no matter the rootpool is a single device pool or a mirrored pool.
3667  * e.g.
3668  *      "/pci@1f,0/ide@d/disk@0,0:a"
3669  */
3670 int
3671 spa_import_rootpool(char *devpath, char *devid)
3672 {
3673         spa_t *spa;
3674         vdev_t *rvd, *bvd, *avd = NULL;
3675         nvlist_t *config, *nvtop;
3676         uint64_t guid, txg;
3677         char *pname;
3678         int error;
3679 
3680         /*
3681          * Read the label from the boot device and generate a configuration.
3682          */
3683         config = spa_generate_rootconf(devpath, devid, &guid);
3684 #if defined(_OBP) && defined(_KERNEL)
3685         if (config == NULL) {
3686                 if (strstr(devpath, "/iscsi/ssd") != NULL) {
3687                         /* iscsi boot */
3688                         get_iscsi_bootpath_phy(devpath);
3689                         config = spa_generate_rootconf(devpath, devid, &guid);
3690                 }
3691         }
3692 #endif
3693         if (config == NULL) {
3694                 cmn_err(CE_NOTE, "Cannot read the pool label from '%s'",
3695                     devpath);
3696                 return (SET_ERROR(EIO));
3697         }
3698 
3699         VERIFY(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
3700             &pname) == 0);
3701         VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg) == 0);
3702 
3703         mutex_enter(&spa_namespace_lock);
3704         if ((spa = spa_lookup(pname)) != NULL) {
3705                 /*
3706                  * Remove the existing root pool from the namespace so that we
3707                  * can replace it with the correct config we just read in.
3708                  */
3709                 spa_remove(spa);
3710         }
3711 
3712         spa = spa_add(pname, config, NULL);
3713         spa->spa_is_root = B_TRUE;
3714         spa->spa_import_flags = ZFS_IMPORT_VERBATIM;
3715 
3716         /*
3717          * Build up a vdev tree based on the boot device's label config.
3718          */
3719         VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3720             &nvtop) == 0);
3721         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3722         error = spa_config_parse(spa, &rvd, nvtop, NULL, 0,
3723             VDEV_ALLOC_ROOTPOOL);
3724         spa_config_exit(spa, SCL_ALL, FTAG);
3725         if (error) {
3726                 mutex_exit(&spa_namespace_lock);
3727                 nvlist_free(config);
3728                 cmn_err(CE_NOTE, "Can not parse the config for pool '%s'",
3729                     pname);
3730                 return (error);
3731         }
3732 
3733         /*
3734          * Get the boot vdev.
3735          */
3736         if ((bvd = vdev_lookup_by_guid(rvd, guid)) == NULL) {
3737                 cmn_err(CE_NOTE, "Can not find the boot vdev for guid %llu",
3738                     (u_longlong_t)guid);
3739                 error = SET_ERROR(ENOENT);
3740                 goto out;
3741         }
3742 
3743         /*
3744          * Determine if there is a better boot device.
3745          */
3746         avd = bvd;
3747         spa_alt_rootvdev(rvd, &avd, &txg);
3748         if (avd != bvd) {
3749                 cmn_err(CE_NOTE, "The boot device is 'degraded'. Please "
3750                     "try booting from '%s'", avd->vdev_path);
3751                 error = SET_ERROR(EINVAL);
3752                 goto out;
3753         }
3754 
3755         /*
3756          * If the boot device is part of a spare vdev then ensure that
3757          * we're booting off the active spare.
3758          */
3759         if (bvd->vdev_parent->vdev_ops == &vdev_spare_ops &&
3760             !bvd->vdev_isspare) {
3761                 cmn_err(CE_NOTE, "The boot device is currently spared. Please "
3762                     "try booting from '%s'",
3763                     bvd->vdev_parent->
3764                     vdev_child[bvd->vdev_parent->vdev_children - 1]->vdev_path);
3765                 error = SET_ERROR(EINVAL);
3766                 goto out;
3767         }
3768 
3769         error = 0;
3770 out:
3771         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3772         vdev_free(rvd);
3773         spa_config_exit(spa, SCL_ALL, FTAG);
3774         mutex_exit(&spa_namespace_lock);
3775 
3776         nvlist_free(config);
3777         return (error);
3778 }
3779 
3780 #endif
3781 
3782 /*
3783  * Import a non-root pool into the system.
3784  */
3785 int
3786 spa_import(const char *pool, nvlist_t *config, nvlist_t *props, uint64_t flags)
3787 {
3788         spa_t *spa;
3789         char *altroot = NULL;
3790         spa_load_state_t state = SPA_LOAD_IMPORT;
3791         zpool_rewind_policy_t policy;
3792         uint64_t mode = spa_mode_global;
3793         uint64_t readonly = B_FALSE;
3794         int error;
3795         nvlist_t *nvroot;
3796         nvlist_t **spares, **l2cache;
3797         uint_t nspares, nl2cache;
3798 
3799         /*
3800          * If a pool with this name exists, return failure.
3801          */
3802         mutex_enter(&spa_namespace_lock);
3803         if (spa_lookup(pool) != NULL) {
3804                 mutex_exit(&spa_namespace_lock);
3805                 return (SET_ERROR(EEXIST));
3806         }
3807 
3808         /*
3809          * Create and initialize the spa structure.
3810          */
3811         (void) nvlist_lookup_string(props,
3812             zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
3813         (void) nvlist_lookup_uint64(props,
3814             zpool_prop_to_name(ZPOOL_PROP_READONLY), &readonly);
3815         if (readonly)
3816                 mode = FREAD;
3817         spa = spa_add(pool, config, altroot);
3818         spa->spa_import_flags = flags;
3819 
3820         /*
3821          * Verbatim import - Take a pool and insert it into the namespace
3822          * as if it had been loaded at boot.
3823          */
3824         if (spa->spa_import_flags & ZFS_IMPORT_VERBATIM) {
3825                 if (props != NULL)
3826                         spa_configfile_set(spa, props, B_FALSE);
3827 
3828                 spa_config_sync(spa, B_FALSE, B_TRUE);
3829 
3830                 mutex_exit(&spa_namespace_lock);
3831                 spa_history_log_version(spa, "import");
3832 
3833                 return (0);
3834         }
3835 
3836         spa_activate(spa, mode);
3837 
3838         /*
3839          * Don't start async tasks until we know everything is healthy.
3840          */
3841         spa_async_suspend(spa);
3842 
3843         zpool_get_rewind_policy(config, &policy);
3844         if (policy.zrp_request & ZPOOL_DO_REWIND)
3845                 state = SPA_LOAD_RECOVER;
3846 
3847         /*
3848          * Pass off the heavy lifting to spa_load().  Pass TRUE for mosconfig
3849          * because the user-supplied config is actually the one to trust when
3850          * doing an import.
3851          */
3852         if (state != SPA_LOAD_RECOVER)
3853                 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
3854 
3855         error = spa_load_best(spa, state, B_TRUE, policy.zrp_txg,
3856             policy.zrp_request);
3857 
3858         /*
3859          * Propagate anything learned while loading the pool and pass it
3860          * back to caller (i.e. rewind info, missing devices, etc).
3861          */
3862         VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
3863             spa->spa_load_info) == 0);
3864 
3865         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3866         /*
3867          * Toss any existing sparelist, as it doesn't have any validity
3868          * anymore, and conflicts with spa_has_spare().
3869          */
3870         if (spa->spa_spares.sav_config) {
3871                 nvlist_free(spa->spa_spares.sav_config);
3872                 spa->spa_spares.sav_config = NULL;
3873                 spa_load_spares(spa);
3874         }
3875         if (spa->spa_l2cache.sav_config) {
3876                 nvlist_free(spa->spa_l2cache.sav_config);
3877                 spa->spa_l2cache.sav_config = NULL;
3878                 spa_load_l2cache(spa);
3879         }
3880 
3881         VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3882             &nvroot) == 0);
3883         if (error == 0)
3884                 error = spa_validate_aux(spa, nvroot, -1ULL,
3885                     VDEV_ALLOC_SPARE);
3886         if (error == 0)
3887                 error = spa_validate_aux(spa, nvroot, -1ULL,
3888                     VDEV_ALLOC_L2CACHE);
3889         spa_config_exit(spa, SCL_ALL, FTAG);
3890 
3891         if (props != NULL)
3892                 spa_configfile_set(spa, props, B_FALSE);
3893 
3894         if (error != 0 || (props && spa_writeable(spa) &&
3895             (error = spa_prop_set(spa, props)))) {
3896                 spa_unload(spa);
3897                 spa_deactivate(spa);
3898                 spa_remove(spa);
3899                 mutex_exit(&spa_namespace_lock);
3900                 return (error);
3901         }
3902 
3903         spa_async_resume(spa);
3904 
3905         /*
3906          * Override any spares and level 2 cache devices as specified by
3907          * the user, as these may have correct device names/devids, etc.
3908          */
3909         if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
3910             &spares, &nspares) == 0) {
3911                 if (spa->spa_spares.sav_config)
3912                         VERIFY(nvlist_remove(spa->spa_spares.sav_config,
3913                             ZPOOL_CONFIG_SPARES, DATA_TYPE_NVLIST_ARRAY) == 0);
3914                 else
3915                         VERIFY(nvlist_alloc(&spa->spa_spares.sav_config,
3916                             NV_UNIQUE_NAME, KM_SLEEP) == 0);
3917                 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
3918                     ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
3919                 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3920                 spa_load_spares(spa);
3921                 spa_config_exit(spa, SCL_ALL, FTAG);
3922                 spa->spa_spares.sav_sync = B_TRUE;
3923         }
3924         if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
3925             &l2cache, &nl2cache) == 0) {
3926                 if (spa->spa_l2cache.sav_config)
3927                         VERIFY(nvlist_remove(spa->spa_l2cache.sav_config,
3928                             ZPOOL_CONFIG_L2CACHE, DATA_TYPE_NVLIST_ARRAY) == 0);
3929                 else
3930                         VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
3931                             NV_UNIQUE_NAME, KM_SLEEP) == 0);
3932                 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
3933                     ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
3934                 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3935                 spa_load_l2cache(spa);
3936                 spa_config_exit(spa, SCL_ALL, FTAG);
3937                 spa->spa_l2cache.sav_sync = B_TRUE;
3938         }
3939 
3940         /*
3941          * Check for any removed devices.
3942          */
3943         if (spa->spa_autoreplace) {
3944                 spa_aux_check_removed(&spa->spa_spares);
3945                 spa_aux_check_removed(&spa->spa_l2cache);
3946         }
3947 
3948         if (spa_writeable(spa)) {
3949                 /*
3950                  * Update the config cache to include the newly-imported pool.
3951                  */
3952                 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
3953         }
3954 
3955         /*
3956          * It's possible that the pool was expanded while it was exported.
3957          * We kick off an async task to handle this for us.
3958          */
3959         spa_async_request(spa, SPA_ASYNC_AUTOEXPAND);
3960 
3961         mutex_exit(&spa_namespace_lock);
3962         spa_history_log_version(spa, "import");
3963 
3964         return (0);
3965 }
3966 
3967 nvlist_t *
3968 spa_tryimport(nvlist_t *tryconfig)
3969 {
3970         nvlist_t *config = NULL;
3971         char *poolname;
3972         spa_t *spa;
3973         uint64_t state;
3974         int error;
3975 
3976         if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_POOL_NAME, &poolname))
3977                 return (NULL);
3978 
3979         if (nvlist_lookup_uint64(tryconfig, ZPOOL_CONFIG_POOL_STATE, &state))
3980                 return (NULL);
3981 
3982         /*
3983          * Create and initialize the spa structure.
3984          */
3985         mutex_enter(&spa_namespace_lock);
3986         spa = spa_add(TRYIMPORT_NAME, tryconfig, NULL);
3987         spa_activate(spa, FREAD);
3988 
3989         /*
3990          * Pass off the heavy lifting to spa_load().
3991          * Pass TRUE for mosconfig because the user-supplied config
3992          * is actually the one to trust when doing an import.
3993          */
3994         error = spa_load(spa, SPA_LOAD_TRYIMPORT, SPA_IMPORT_EXISTING, B_TRUE);
3995 
3996         /*
3997          * If 'tryconfig' was at least parsable, return the current config.
3998          */
3999         if (spa->spa_root_vdev != NULL) {
4000                 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4001                 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME,
4002                     poolname) == 0);
4003                 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
4004                     state) == 0);
4005                 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
4006                     spa->spa_uberblock.ub_timestamp) == 0);
4007                 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
4008                     spa->spa_load_info) == 0);
4009 
4010                 /*
4011                  * If the bootfs property exists on this pool then we
4012                  * copy it out so that external consumers can tell which
4013                  * pools are bootable.
4014                  */
4015                 if ((!error || error == EEXIST) && spa->spa_bootfs) {
4016                         char *tmpname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
4017 
4018                         /*
4019                          * We have to play games with the name since the
4020                          * pool was opened as TRYIMPORT_NAME.
4021                          */
4022                         if (dsl_dsobj_to_dsname(spa_name(spa),
4023                             spa->spa_bootfs, tmpname) == 0) {
4024                                 char *cp;
4025                                 char *dsname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
4026 
4027                                 cp = strchr(tmpname, '/');
4028                                 if (cp == NULL) {
4029                                         (void) strlcpy(dsname, tmpname,
4030                                             MAXPATHLEN);
4031                                 } else {
4032                                         (void) snprintf(dsname, MAXPATHLEN,
4033                                             "%s/%s", poolname, ++cp);
4034                                 }
4035                                 VERIFY(nvlist_add_string(config,
4036                                     ZPOOL_CONFIG_BOOTFS, dsname) == 0);
4037                                 kmem_free(dsname, MAXPATHLEN);
4038                         }
4039                         kmem_free(tmpname, MAXPATHLEN);
4040                 }
4041 
4042                 /*
4043                  * Add the list of hot spares and level 2 cache devices.
4044                  */
4045                 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4046                 spa_add_spares(spa, config);
4047                 spa_add_l2cache(spa, config);
4048                 spa_config_exit(spa, SCL_CONFIG, FTAG);
4049         }
4050 
4051         spa_unload(spa);
4052         spa_deactivate(spa);
4053         spa_remove(spa);
4054         mutex_exit(&spa_namespace_lock);
4055 
4056         return (config);
4057 }
4058 
4059 /*
4060  * Pool export/destroy
4061  *
4062  * The act of destroying or exporting a pool is very simple.  We make sure there
4063  * is no more pending I/O and any references to the pool are gone.  Then, we
4064  * update the pool state and sync all the labels to disk, removing the
4065  * configuration from the cache afterwards. If the 'hardforce' flag is set, then
4066  * we don't sync the labels or remove the configuration cache.
4067  */
4068 static int
4069 spa_export_common(char *pool, int new_state, nvlist_t **oldconfig,
4070     boolean_t force, boolean_t hardforce)
4071 {
4072         spa_t *spa;
4073 
4074         if (oldconfig)
4075                 *oldconfig = NULL;
4076 
4077         if (!(spa_mode_global & FWRITE))
4078                 return (SET_ERROR(EROFS));
4079 
4080         mutex_enter(&spa_namespace_lock);
4081         if ((spa = spa_lookup(pool)) == NULL) {
4082                 mutex_exit(&spa_namespace_lock);
4083                 return (SET_ERROR(ENOENT));
4084         }
4085 
4086         /*
4087          * Put a hold on the pool, drop the namespace lock, stop async tasks,
4088          * reacquire the namespace lock, and see if we can export.
4089          */
4090         spa_open_ref(spa, FTAG);
4091         mutex_exit(&spa_namespace_lock);
4092         spa_async_suspend(spa);
4093         mutex_enter(&spa_namespace_lock);
4094         spa_close(spa, FTAG);
4095 
4096         /*
4097          * The pool will be in core if it's openable,
4098          * in which case we can modify its state.
4099          */
4100         if (spa->spa_state != POOL_STATE_UNINITIALIZED && spa->spa_sync_on) {
4101                 /*
4102                  * Objsets may be open only because they're dirty, so we
4103                  * have to force it to sync before checking spa_refcnt.
4104                  */
4105                 txg_wait_synced(spa->spa_dsl_pool, 0);
4106 
4107                 /*
4108                  * A pool cannot be exported or destroyed if there are active
4109                  * references.  If we are resetting a pool, allow references by
4110                  * fault injection handlers.
4111                  */
4112                 if (!spa_refcount_zero(spa) ||
4113                     (spa->spa_inject_ref != 0 &&
4114                     new_state != POOL_STATE_UNINITIALIZED)) {
4115                         spa_async_resume(spa);
4116                         mutex_exit(&spa_namespace_lock);
4117                         return (SET_ERROR(EBUSY));
4118                 }
4119 
4120                 /*
4121                  * A pool cannot be exported if it has an active shared spare.
4122                  * This is to prevent other pools stealing the active spare
4123                  * from an exported pool. At user's own will, such pool can
4124                  * be forcedly exported.
4125                  */
4126                 if (!force && new_state == POOL_STATE_EXPORTED &&
4127                     spa_has_active_shared_spare(spa)) {
4128                         spa_async_resume(spa);
4129                         mutex_exit(&spa_namespace_lock);
4130                         return (SET_ERROR(EXDEV));
4131                 }
4132 
4133                 /*
4134                  * We want this to be reflected on every label,
4135                  * so mark them all dirty.  spa_unload() will do the
4136                  * final sync that pushes these changes out.
4137                  */
4138                 if (new_state != POOL_STATE_UNINITIALIZED && !hardforce) {
4139                         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4140                         spa->spa_state = new_state;
4141                         spa->spa_final_txg = spa_last_synced_txg(spa) +
4142                             TXG_DEFER_SIZE + 1;
4143                         vdev_config_dirty(spa->spa_root_vdev);
4144                         spa_config_exit(spa, SCL_ALL, FTAG);
4145                 }
4146         }
4147 
4148         spa_event_notify(spa, NULL, ESC_ZFS_POOL_DESTROY);
4149 
4150         if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
4151                 spa_unload(spa);
4152                 spa_deactivate(spa);
4153         }
4154 
4155         if (oldconfig && spa->spa_config)
4156                 VERIFY(nvlist_dup(spa->spa_config, oldconfig, 0) == 0);
4157 
4158         if (new_state != POOL_STATE_UNINITIALIZED) {
4159                 if (!hardforce)
4160                         spa_config_sync(spa, B_TRUE, B_TRUE);
4161                 spa_remove(spa);
4162         }
4163         mutex_exit(&spa_namespace_lock);
4164 
4165         return (0);
4166 }
4167 
4168 /*
4169  * Destroy a storage pool.
4170  */
4171 int
4172 spa_destroy(char *pool)
4173 {
4174         return (spa_export_common(pool, POOL_STATE_DESTROYED, NULL,
4175             B_FALSE, B_FALSE));
4176 }
4177 
4178 /*
4179  * Export a storage pool.
4180  */
4181 int
4182 spa_export(char *pool, nvlist_t **oldconfig, boolean_t force,
4183     boolean_t hardforce)
4184 {
4185         return (spa_export_common(pool, POOL_STATE_EXPORTED, oldconfig,
4186             force, hardforce));
4187 }
4188 
4189 /*
4190  * Similar to spa_export(), this unloads the spa_t without actually removing it
4191  * from the namespace in any way.
4192  */
4193 int
4194 spa_reset(char *pool)
4195 {
4196         return (spa_export_common(pool, POOL_STATE_UNINITIALIZED, NULL,
4197             B_FALSE, B_FALSE));
4198 }
4199 
4200 /*
4201  * ==========================================================================
4202  * Device manipulation
4203  * ==========================================================================
4204  */
4205 
4206 /*
4207  * Add a device to a storage pool.
4208  */
4209 int
4210 spa_vdev_add(spa_t *spa, nvlist_t *nvroot)
4211 {
4212         uint64_t txg, id;
4213         int error;
4214         vdev_t *rvd = spa->spa_root_vdev;
4215         vdev_t *vd, *tvd;
4216         nvlist_t **spares, **l2cache;
4217         uint_t nspares, nl2cache;
4218 
4219         ASSERT(spa_writeable(spa));
4220 
4221         txg = spa_vdev_enter(spa);
4222 
4223         if ((error = spa_config_parse(spa, &vd, nvroot, NULL, 0,
4224             VDEV_ALLOC_ADD)) != 0)
4225                 return (spa_vdev_exit(spa, NULL, txg, error));
4226 
4227         spa->spa_pending_vdev = vd;  /* spa_vdev_exit() will clear this */
4228 
4229         if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares,
4230             &nspares) != 0)
4231                 nspares = 0;
4232 
4233         if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE, &l2cache,
4234             &nl2cache) != 0)
4235                 nl2cache = 0;
4236 
4237         if (vd->vdev_children == 0 && nspares == 0 && nl2cache == 0)
4238                 return (spa_vdev_exit(spa, vd, txg, EINVAL));
4239 
4240         if (vd->vdev_children != 0 &&
4241             (error = vdev_create(vd, txg, B_FALSE)) != 0)
4242                 return (spa_vdev_exit(spa, vd, txg, error));
4243 
4244         /*
4245          * We must validate the spares and l2cache devices after checking the
4246          * children.  Otherwise, vdev_inuse() will blindly overwrite the spare.
4247          */
4248         if ((error = spa_validate_aux(spa, nvroot, txg, VDEV_ALLOC_ADD)) != 0)
4249                 return (spa_vdev_exit(spa, vd, txg, error));
4250 
4251         /*
4252          * Transfer each new top-level vdev from vd to rvd.
4253          */
4254         for (int c = 0; c < vd->vdev_children; c++) {
4255 
4256                 /*
4257                  * Set the vdev id to the first hole, if one exists.
4258                  */
4259                 for (id = 0; id < rvd->vdev_children; id++) {
4260                         if (rvd->vdev_child[id]->vdev_ishole) {
4261                                 vdev_free(rvd->vdev_child[id]);
4262                                 break;
4263                         }
4264                 }
4265                 tvd = vd->vdev_child[c];
4266                 vdev_remove_child(vd, tvd);
4267                 tvd->vdev_id = id;
4268                 vdev_add_child(rvd, tvd);
4269                 vdev_config_dirty(tvd);
4270         }
4271 
4272         if (nspares != 0) {
4273                 spa_set_aux_vdevs(&spa->spa_spares, spares, nspares,
4274                     ZPOOL_CONFIG_SPARES);
4275                 spa_load_spares(spa);
4276                 spa->spa_spares.sav_sync = B_TRUE;
4277         }
4278 
4279         if (nl2cache != 0) {
4280                 spa_set_aux_vdevs(&spa->spa_l2cache, l2cache, nl2cache,
4281                     ZPOOL_CONFIG_L2CACHE);
4282                 spa_load_l2cache(spa);
4283                 spa->spa_l2cache.sav_sync = B_TRUE;
4284         }
4285 
4286         /*
4287          * We have to be careful when adding new vdevs to an existing pool.
4288          * If other threads start allocating from these vdevs before we
4289          * sync the config cache, and we lose power, then upon reboot we may
4290          * fail to open the pool because there are DVAs that the config cache
4291          * can't translate.  Therefore, we first add the vdevs without
4292          * initializing metaslabs; sync the config cache (via spa_vdev_exit());
4293          * and then let spa_config_update() initialize the new metaslabs.
4294          *
4295          * spa_load() checks for added-but-not-initialized vdevs, so that
4296          * if we lose power at any point in this sequence, the remaining
4297          * steps will be completed the next time we load the pool.
4298          */
4299         (void) spa_vdev_exit(spa, vd, txg, 0);
4300 
4301         mutex_enter(&spa_namespace_lock);
4302         spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
4303         mutex_exit(&spa_namespace_lock);
4304 
4305         return (0);
4306 }
4307 
4308 /*
4309  * Attach a device to a mirror.  The arguments are the path to any device
4310  * in the mirror, and the nvroot for the new device.  If the path specifies
4311  * a device that is not mirrored, we automatically insert the mirror vdev.
4312  *
4313  * If 'replacing' is specified, the new device is intended to replace the
4314  * existing device; in this case the two devices are made into their own
4315  * mirror using the 'replacing' vdev, which is functionally identical to
4316  * the mirror vdev (it actually reuses all the same ops) but has a few
4317  * extra rules: you can't attach to it after it's been created, and upon
4318  * completion of resilvering, the first disk (the one being replaced)
4319  * is automatically detached.
4320  */
4321 int
4322 spa_vdev_attach(spa_t *spa, uint64_t guid, nvlist_t *nvroot, int replacing)
4323 {
4324         uint64_t txg, dtl_max_txg;
4325         vdev_t *rvd = spa->spa_root_vdev;
4326         vdev_t *oldvd, *newvd, *newrootvd, *pvd, *tvd;
4327         vdev_ops_t *pvops;
4328         char *oldvdpath, *newvdpath;
4329         int newvd_isspare;
4330         int error;
4331 
4332         ASSERT(spa_writeable(spa));
4333 
4334         txg = spa_vdev_enter(spa);
4335 
4336         oldvd = spa_lookup_by_guid(spa, guid, B_FALSE);
4337 
4338         if (oldvd == NULL)
4339                 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
4340 
4341         if (!oldvd->vdev_ops->vdev_op_leaf)
4342                 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
4343 
4344         pvd = oldvd->vdev_parent;
4345 
4346         if ((error = spa_config_parse(spa, &newrootvd, nvroot, NULL, 0,
4347             VDEV_ALLOC_ATTACH)) != 0)
4348                 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
4349 
4350         if (newrootvd->vdev_children != 1)
4351                 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
4352 
4353         newvd = newrootvd->vdev_child[0];
4354 
4355         if (!newvd->vdev_ops->vdev_op_leaf)
4356                 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
4357 
4358         if ((error = vdev_create(newrootvd, txg, replacing)) != 0)
4359                 return (spa_vdev_exit(spa, newrootvd, txg, error));
4360 
4361         /*
4362          * Spares can't replace logs
4363          */
4364         if (oldvd->vdev_top->vdev_islog && newvd->vdev_isspare)
4365                 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
4366 
4367         if (!replacing) {
4368                 /*
4369                  * For attach, the only allowable parent is a mirror or the root
4370                  * vdev.
4371                  */
4372                 if (pvd->vdev_ops != &vdev_mirror_ops &&
4373                     pvd->vdev_ops != &vdev_root_ops)
4374                         return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
4375 
4376                 pvops = &vdev_mirror_ops;
4377         } else {
4378                 /*
4379                  * Active hot spares can only be replaced by inactive hot
4380                  * spares.
4381                  */
4382                 if (pvd->vdev_ops == &vdev_spare_ops &&
4383                     oldvd->vdev_isspare &&
4384                     !spa_has_spare(spa, newvd->vdev_guid))
4385                         return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
4386 
4387                 /*
4388                  * If the source is a hot spare, and the parent isn't already a
4389                  * spare, then we want to create a new hot spare.  Otherwise, we
4390                  * want to create a replacing vdev.  The user is not allowed to
4391                  * attach to a spared vdev child unless the 'isspare' state is
4392                  * the same (spare replaces spare, non-spare replaces
4393                  * non-spare).
4394                  */
4395                 if (pvd->vdev_ops == &vdev_replacing_ops &&
4396                     spa_version(spa) < SPA_VERSION_MULTI_REPLACE) {
4397                         return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
4398                 } else if (pvd->vdev_ops == &vdev_spare_ops &&
4399                     newvd->vdev_isspare != oldvd->vdev_isspare) {
4400                         return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
4401                 }
4402 
4403                 if (newvd->vdev_isspare)
4404                         pvops = &vdev_spare_ops;
4405                 else
4406                         pvops = &vdev_replacing_ops;
4407         }
4408 
4409         /*
4410          * Make sure the new device is big enough.
4411          */
4412         if (newvd->vdev_asize < vdev_get_min_asize(oldvd))
4413                 return (spa_vdev_exit(spa, newrootvd, txg, EOVERFLOW));
4414 
4415         /*
4416          * The new device cannot have a higher alignment requirement
4417          * than the top-level vdev.
4418          */
4419         if (newvd->vdev_ashift > oldvd->vdev_top->vdev_ashift)
4420                 return (spa_vdev_exit(spa, newrootvd, txg, EDOM));
4421 
4422         /*
4423          * If this is an in-place replacement, update oldvd's path and devid
4424          * to make it distinguishable from newvd, and unopenable from now on.
4425          */
4426         if (strcmp(oldvd->vdev_path, newvd->vdev_path) == 0) {
4427                 spa_strfree(oldvd->vdev_path);
4428                 oldvd->vdev_path = kmem_alloc(strlen(newvd->vdev_path) + 5,
4429                     KM_SLEEP);
4430                 (void) sprintf(oldvd->vdev_path, "%s/%s",
4431                     newvd->vdev_path, "old");
4432                 if (oldvd->vdev_devid != NULL) {
4433                         spa_strfree(oldvd->vdev_devid);
4434                         oldvd->vdev_devid = NULL;
4435                 }
4436         }
4437 
4438         /* mark the device being resilvered */
4439         newvd->vdev_resilvering = B_TRUE;
4440 
4441         /*
4442          * If the parent is not a mirror, or if we're replacing, insert the new
4443          * mirror/replacing/spare vdev above oldvd.
4444          */
4445         if (pvd->vdev_ops != pvops)
4446                 pvd = vdev_add_parent(oldvd, pvops);
4447 
4448         ASSERT(pvd->vdev_top->vdev_parent == rvd);
4449         ASSERT(pvd->vdev_ops == pvops);
4450         ASSERT(oldvd->vdev_parent == pvd);
4451 
4452         /*
4453          * Extract the new device from its root and add it to pvd.
4454          */
4455         vdev_remove_child(newrootvd, newvd);
4456         newvd->vdev_id = pvd->vdev_children;
4457         newvd->vdev_crtxg = oldvd->vdev_crtxg;
4458         vdev_add_child(pvd, newvd);
4459 
4460         tvd = newvd->vdev_top;
4461         ASSERT(pvd->vdev_top == tvd);
4462         ASSERT(tvd->vdev_parent == rvd);
4463 
4464         vdev_config_dirty(tvd);
4465 
4466         /*
4467          * Set newvd's DTL to [TXG_INITIAL, dtl_max_txg) so that we account
4468          * for any dmu_sync-ed blocks.  It will propagate upward when
4469          * spa_vdev_exit() calls vdev_dtl_reassess().
4470          */
4471         dtl_max_txg = txg + TXG_CONCURRENT_STATES;
4472 
4473         vdev_dtl_dirty(newvd, DTL_MISSING, TXG_INITIAL,
4474             dtl_max_txg - TXG_INITIAL);
4475 
4476         if (newvd->vdev_isspare) {
4477                 spa_spare_activate(newvd);
4478                 spa_event_notify(spa, newvd, ESC_ZFS_VDEV_SPARE);
4479         }
4480 
4481         oldvdpath = spa_strdup(oldvd->vdev_path);
4482         newvdpath = spa_strdup(newvd->vdev_path);
4483         newvd_isspare = newvd->vdev_isspare;
4484 
4485         /*
4486          * Mark newvd's DTL dirty in this txg.
4487          */
4488         vdev_dirty(tvd, VDD_DTL, newvd, txg);
4489 
4490         /*
4491          * Restart the resilver
4492          */
4493         dsl_resilver_restart(spa->spa_dsl_pool, dtl_max_txg);
4494 
4495         /*
4496          * Commit the config
4497          */
4498         (void) spa_vdev_exit(spa, newrootvd, dtl_max_txg, 0);
4499 
4500         spa_history_log_internal(spa, "vdev attach", NULL,
4501             "%s vdev=%s %s vdev=%s",
4502             replacing && newvd_isspare ? "spare in" :
4503             replacing ? "replace" : "attach", newvdpath,
4504             replacing ? "for" : "to", oldvdpath);
4505 
4506         spa_strfree(oldvdpath);
4507         spa_strfree(newvdpath);
4508 
4509         if (spa->spa_bootfs)
4510                 spa_event_notify(spa, newvd, ESC_ZFS_BOOTFS_VDEV_ATTACH);
4511 
4512         return (0);
4513 }
4514 
4515 /*
4516  * Detach a device from a mirror or replacing vdev.
4517  * If 'replace_done' is specified, only detach if the parent
4518  * is a replacing vdev.
4519  */
4520 int
4521 spa_vdev_detach(spa_t *spa, uint64_t guid, uint64_t pguid, int replace_done)
4522 {
4523         uint64_t txg;
4524         int error;
4525         vdev_t *rvd = spa->spa_root_vdev;
4526         vdev_t *vd, *pvd, *cvd, *tvd;
4527         boolean_t unspare = B_FALSE;
4528         uint64_t unspare_guid = 0;
4529         char *vdpath;
4530 
4531         ASSERT(spa_writeable(spa));
4532 
4533         txg = spa_vdev_enter(spa);
4534 
4535         vd = spa_lookup_by_guid(spa, guid, B_FALSE);
4536 
4537         if (vd == NULL)
4538                 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
4539 
4540         if (!vd->vdev_ops->vdev_op_leaf)
4541                 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
4542 
4543         pvd = vd->vdev_parent;
4544 
4545         /*
4546          * If the parent/child relationship is not as expected, don't do it.
4547          * Consider M(A,R(B,C)) -- that is, a mirror of A with a replacing
4548          * vdev that's replacing B with C.  The user's intent in replacing
4549          * is to go from M(A,B) to M(A,C).  If the user decides to cancel
4550          * the replace by detaching C, the expected behavior is to end up
4551          * M(A,B).  But suppose that right after deciding to detach C,
4552          * the replacement of B completes.  We would have M(A,C), and then
4553          * ask to detach C, which would leave us with just A -- not what
4554          * the user wanted.  To prevent this, we make sure that the
4555          * parent/child relationship hasn't changed -- in this example,
4556          * that C's parent is still the replacing vdev R.
4557          */
4558         if (pvd->vdev_guid != pguid && pguid != 0)
4559                 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
4560 
4561         /*
4562          * Only 'replacing' or 'spare' vdevs can be replaced.
4563          */
4564         if (replace_done && pvd->vdev_ops != &vdev_replacing_ops &&
4565             pvd->vdev_ops != &vdev_spare_ops)
4566                 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
4567 
4568         ASSERT(pvd->vdev_ops != &vdev_spare_ops ||
4569             spa_version(spa) >= SPA_VERSION_SPARES);
4570 
4571         /*
4572          * Only mirror, replacing, and spare vdevs support detach.
4573          */
4574         if (pvd->vdev_ops != &vdev_replacing_ops &&
4575             pvd->vdev_ops != &vdev_mirror_ops &&
4576             pvd->vdev_ops != &vdev_spare_ops)
4577                 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
4578 
4579         /*
4580          * If this device has the only valid copy of some data,
4581          * we cannot safely detach it.
4582          */
4583         if (vdev_dtl_required(vd))
4584                 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
4585 
4586         ASSERT(pvd->vdev_children >= 2);
4587 
4588         /*
4589          * If we are detaching the second disk from a replacing vdev, then
4590          * check to see if we changed the original vdev's path to have "/old"
4591          * at the end in spa_vdev_attach().  If so, undo that change now.
4592          */
4593         if (pvd->vdev_ops == &vdev_replacing_ops && vd->vdev_id > 0 &&
4594             vd->vdev_path != NULL) {
4595                 size_t len = strlen(vd->vdev_path);
4596 
4597                 for (int c = 0; c < pvd->vdev_children; c++) {
4598                         cvd = pvd->vdev_child[c];
4599 
4600                         if (cvd == vd || cvd->vdev_path == NULL)
4601                                 continue;
4602 
4603                         if (strncmp(cvd->vdev_path, vd->vdev_path, len) == 0 &&
4604                             strcmp(cvd->vdev_path + len, "/old") == 0) {
4605                                 spa_strfree(cvd->vdev_path);
4606                                 cvd->vdev_path = spa_strdup(vd->vdev_path);
4607                                 break;
4608                         }
4609                 }
4610         }
4611 
4612         /*
4613          * If we are detaching the original disk from a spare, then it implies
4614          * that the spare should become a real disk, and be removed from the
4615          * active spare list for the pool.
4616          */
4617         if (pvd->vdev_ops == &vdev_spare_ops &&
4618             vd->vdev_id == 0 &&
4619             pvd->vdev_child[pvd->vdev_children - 1]->vdev_isspare)
4620                 unspare = B_TRUE;
4621 
4622         /*
4623          * Erase the disk labels so the disk can be used for other things.
4624          * This must be done after all other error cases are handled,
4625          * but before we disembowel vd (so we can still do I/O to it).
4626          * But if we can't do it, don't treat the error as fatal --
4627          * it may be that the unwritability of the disk is the reason
4628          * it's being detached!
4629          */
4630         error = vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
4631 
4632         /*
4633          * Remove vd from its parent and compact the parent's children.
4634          */
4635         vdev_remove_child(pvd, vd);
4636         vdev_compact_children(pvd);
4637 
4638         /*
4639          * Remember one of the remaining children so we can get tvd below.
4640          */
4641         cvd = pvd->vdev_child[pvd->vdev_children - 1];
4642 
4643         /*
4644          * If we need to remove the remaining child from the list of hot spares,
4645          * do it now, marking the vdev as no longer a spare in the process.
4646          * We must do this before vdev_remove_parent(), because that can
4647          * change the GUID if it creates a new toplevel GUID.  For a similar
4648          * reason, we must remove the spare now, in the same txg as the detach;
4649          * otherwise someone could attach a new sibling, change the GUID, and
4650          * the subsequent attempt to spa_vdev_remove(unspare_guid) would fail.
4651          */
4652         if (unspare) {
4653                 ASSERT(cvd->vdev_isspare);
4654                 spa_spare_remove(cvd);
4655                 unspare_guid = cvd->vdev_guid;
4656                 (void) spa_vdev_remove(spa, unspare_guid, B_TRUE);
4657                 cvd->vdev_unspare = B_TRUE;
4658         }
4659 
4660         /*
4661          * If the parent mirror/replacing vdev only has one child,
4662          * the parent is no longer needed.  Remove it from the tree.
4663          */
4664         if (pvd->vdev_children == 1) {
4665                 if (pvd->vdev_ops == &vdev_spare_ops)
4666                         cvd->vdev_unspare = B_FALSE;
4667                 vdev_remove_parent(cvd);
4668                 cvd->vdev_resilvering = B_FALSE;
4669         }
4670 
4671 
4672         /*
4673          * We don't set tvd until now because the parent we just removed
4674          * may have been the previous top-level vdev.
4675          */
4676         tvd = cvd->vdev_top;
4677         ASSERT(tvd->vdev_parent == rvd);
4678 
4679         /*
4680          * Reevaluate the parent vdev state.
4681          */
4682         vdev_propagate_state(cvd);
4683 
4684         /*
4685          * If the 'autoexpand' property is set on the pool then automatically
4686          * try to expand the size of the pool. For example if the device we
4687          * just detached was smaller than the others, it may be possible to
4688          * add metaslabs (i.e. grow the pool). We need to reopen the vdev
4689          * first so that we can obtain the updated sizes of the leaf vdevs.
4690          */
4691         if (spa->spa_autoexpand) {
4692                 vdev_reopen(tvd);
4693                 vdev_expand(tvd, txg);
4694         }
4695 
4696         vdev_config_dirty(tvd);
4697 
4698         /*
4699          * Mark vd's DTL as dirty in this txg.  vdev_dtl_sync() will see that
4700          * vd->vdev_detached is set and free vd's DTL object in syncing context.
4701          * But first make sure we're not on any *other* txg's DTL list, to
4702          * prevent vd from being accessed after it's freed.
4703          */
4704         vdpath = spa_strdup(vd->vdev_path);
4705         for (int t = 0; t < TXG_SIZE; t++)
4706                 (void) txg_list_remove_this(&tvd->vdev_dtl_list, vd, t);
4707         vd->vdev_detached = B_TRUE;
4708         vdev_dirty(tvd, VDD_DTL, vd, txg);
4709 
4710         spa_event_notify(spa, vd, ESC_ZFS_VDEV_REMOVE);
4711 
4712         /* hang on to the spa before we release the lock */
4713         spa_open_ref(spa, FTAG);
4714 
4715         error = spa_vdev_exit(spa, vd, txg, 0);
4716 
4717         spa_history_log_internal(spa, "detach", NULL,
4718             "vdev=%s", vdpath);
4719         spa_strfree(vdpath);
4720 
4721         /*
4722          * If this was the removal of the original device in a hot spare vdev,
4723          * then we want to go through and remove the device from the hot spare
4724          * list of every other pool.
4725          */
4726         if (unspare) {
4727                 spa_t *altspa = NULL;
4728 
4729                 mutex_enter(&spa_namespace_lock);
4730                 while ((altspa = spa_next(altspa)) != NULL) {
4731                         if (altspa->spa_state != POOL_STATE_ACTIVE ||
4732                             altspa == spa)
4733                                 continue;
4734 
4735                         spa_open_ref(altspa, FTAG);
4736                         mutex_exit(&spa_namespace_lock);
4737                         (void) spa_vdev_remove(altspa, unspare_guid, B_TRUE);
4738                         mutex_enter(&spa_namespace_lock);
4739                         spa_close(altspa, FTAG);
4740                 }
4741                 mutex_exit(&spa_namespace_lock);
4742 
4743                 /* search the rest of the vdevs for spares to remove */
4744                 spa_vdev_resilver_done(spa);
4745         }
4746 
4747         /* all done with the spa; OK to release */
4748         mutex_enter(&spa_namespace_lock);
4749         spa_close(spa, FTAG);
4750         mutex_exit(&spa_namespace_lock);
4751 
4752         return (error);
4753 }
4754 
4755 /*
4756  * Split a set of devices from their mirrors, and create a new pool from them.
4757  */
4758 int
4759 spa_vdev_split_mirror(spa_t *spa, char *newname, nvlist_t *config,
4760     nvlist_t *props, boolean_t exp)
4761 {
4762         int error = 0;
4763         uint64_t txg, *glist;
4764         spa_t *newspa;
4765         uint_t c, children, lastlog;
4766         nvlist_t **child, *nvl, *tmp;
4767         dmu_tx_t *tx;
4768         char *altroot = NULL;
4769         vdev_t *rvd, **vml = NULL;                      /* vdev modify list */
4770         boolean_t activate_slog;
4771 
4772         ASSERT(spa_writeable(spa));
4773 
4774         txg = spa_vdev_enter(spa);
4775 
4776         /* clear the log and flush everything up to now */
4777         activate_slog = spa_passivate_log(spa);
4778         (void) spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
4779         error = spa_offline_log(spa);
4780         txg = spa_vdev_config_enter(spa);
4781 
4782         if (activate_slog)
4783                 spa_activate_log(spa);
4784 
4785         if (error != 0)
4786                 return (spa_vdev_exit(spa, NULL, txg, error));
4787 
4788         /* check new spa name before going any further */
4789         if (spa_lookup(newname) != NULL)
4790                 return (spa_vdev_exit(spa, NULL, txg, EEXIST));
4791 
4792         /*
4793          * scan through all the children to ensure they're all mirrors
4794          */
4795         if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvl) != 0 ||
4796             nvlist_lookup_nvlist_array(nvl, ZPOOL_CONFIG_CHILDREN, &child,
4797             &children) != 0)
4798                 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
4799 
4800         /* first, check to ensure we've got the right child count */
4801         rvd = spa->spa_root_vdev;
4802         lastlog = 0;
4803         for (c = 0; c < rvd->vdev_children; c++) {
4804                 vdev_t *vd = rvd->vdev_child[c];
4805 
4806                 /* don't count the holes & logs as children */
4807                 if (vd->vdev_islog || vd->vdev_ishole) {
4808                         if (lastlog == 0)
4809                                 lastlog = c;
4810                         continue;
4811                 }
4812 
4813                 lastlog = 0;
4814         }
4815         if (children != (lastlog != 0 ? lastlog : rvd->vdev_children))
4816                 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
4817 
4818         /* next, ensure no spare or cache devices are part of the split */
4819         if (nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_SPARES, &tmp) == 0 ||
4820             nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_L2CACHE, &tmp) == 0)
4821                 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
4822 
4823         vml = kmem_zalloc(children * sizeof (vdev_t *), KM_SLEEP);
4824         glist = kmem_zalloc(children * sizeof (uint64_t), KM_SLEEP);
4825 
4826         /* then, loop over each vdev and validate it */
4827         for (c = 0; c < children; c++) {
4828                 uint64_t is_hole = 0;
4829 
4830                 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
4831                     &is_hole);
4832 
4833                 if (is_hole != 0) {
4834                         if (spa->spa_root_vdev->vdev_child[c]->vdev_ishole ||
4835                             spa->spa_root_vdev->vdev_child[c]->vdev_islog) {
4836                                 continue;
4837                         } else {
4838                                 error = SET_ERROR(EINVAL);
4839                                 break;
4840                         }
4841                 }
4842 
4843                 /* which disk is going to be split? */
4844                 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_GUID,
4845                     &glist[c]) != 0) {
4846                         error = SET_ERROR(EINVAL);
4847                         break;
4848                 }
4849 
4850                 /* look it up in the spa */
4851                 vml[c] = spa_lookup_by_guid(spa, glist[c], B_FALSE);
4852                 if (vml[c] == NULL) {
4853                         error = SET_ERROR(ENODEV);
4854                         break;
4855                 }
4856 
4857                 /* make sure there's nothing stopping the split */
4858                 if (vml[c]->vdev_parent->vdev_ops != &vdev_mirror_ops ||
4859                     vml[c]->vdev_islog ||
4860                     vml[c]->vdev_ishole ||
4861                     vml[c]->vdev_isspare ||
4862                     vml[c]->vdev_isl2cache ||
4863                     !vdev_writeable(vml[c]) ||
4864                     vml[c]->vdev_children != 0 ||
4865                     vml[c]->vdev_state != VDEV_STATE_HEALTHY ||
4866                     c != spa->spa_root_vdev->vdev_child[c]->vdev_id) {
4867                         error = SET_ERROR(EINVAL);
4868                         break;
4869                 }
4870 
4871                 if (vdev_dtl_required(vml[c])) {
4872                         error = SET_ERROR(EBUSY);
4873                         break;
4874                 }
4875 
4876                 /* we need certain info from the top level */
4877                 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_ARRAY,
4878                     vml[c]->vdev_top->vdev_ms_array) == 0);
4879                 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_SHIFT,
4880                     vml[c]->vdev_top->vdev_ms_shift) == 0);
4881                 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASIZE,
4882                     vml[c]->vdev_top->vdev_asize) == 0);
4883                 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASHIFT,
4884                     vml[c]->vdev_top->vdev_ashift) == 0);
4885         }
4886 
4887         if (error != 0) {
4888                 kmem_free(vml, children * sizeof (vdev_t *));
4889                 kmem_free(glist, children * sizeof (uint64_t));
4890                 return (spa_vdev_exit(spa, NULL, txg, error));
4891         }
4892 
4893         /* stop writers from using the disks */
4894         for (c = 0; c < children; c++) {
4895                 if (vml[c] != NULL)
4896                         vml[c]->vdev_offline = B_TRUE;
4897         }
4898         vdev_reopen(spa->spa_root_vdev);
4899 
4900         /*
4901          * Temporarily record the splitting vdevs in the spa config.  This
4902          * will disappear once the config is regenerated.
4903          */
4904         VERIFY(nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4905         VERIFY(nvlist_add_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
4906             glist, children) == 0);
4907         kmem_free(glist, children * sizeof (uint64_t));
4908 
4909         mutex_enter(&spa->spa_props_lock);
4910         VERIFY(nvlist_add_nvlist(spa->spa_config, ZPOOL_CONFIG_SPLIT,
4911             nvl) == 0);
4912         mutex_exit(&spa->spa_props_lock);
4913         spa->spa_config_splitting = nvl;
4914         vdev_config_dirty(spa->spa_root_vdev);
4915 
4916         /* configure and create the new pool */
4917         VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME, newname) == 0);
4918         VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
4919             exp ? POOL_STATE_EXPORTED : POOL_STATE_ACTIVE) == 0);
4920         VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
4921             spa_version(spa)) == 0);
4922         VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_TXG,
4923             spa->spa_config_txg) == 0);
4924         VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_GUID,
4925             spa_generate_guid(NULL)) == 0);
4926         (void) nvlist_lookup_string(props,
4927             zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
4928 
4929         /* add the new pool to the namespace */
4930         newspa = spa_add(newname, config, altroot);
4931         newspa->spa_config_txg = spa->spa_config_txg;
4932         spa_set_log_state(newspa, SPA_LOG_CLEAR);
4933 
4934         /* release the spa config lock, retaining the namespace lock */
4935         spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
4936 
4937         if (zio_injection_enabled)
4938                 zio_handle_panic_injection(spa, FTAG, 1);
4939 
4940         spa_activate(newspa, spa_mode_global);
4941         spa_async_suspend(newspa);
4942 
4943         /* create the new pool from the disks of the original pool */
4944         error = spa_load(newspa, SPA_LOAD_IMPORT, SPA_IMPORT_ASSEMBLE, B_TRUE);
4945         if (error)
4946                 goto out;
4947 
4948         /* if that worked, generate a real config for the new pool */
4949         if (newspa->spa_root_vdev != NULL) {
4950                 VERIFY(nvlist_alloc(&newspa->spa_config_splitting,
4951                     NV_UNIQUE_NAME, KM_SLEEP) == 0);
4952                 VERIFY(nvlist_add_uint64(newspa->spa_config_splitting,
4953                     ZPOOL_CONFIG_SPLIT_GUID, spa_guid(spa)) == 0);
4954                 spa_config_set(newspa, spa_config_generate(newspa, NULL, -1ULL,
4955                     B_TRUE));
4956         }
4957 
4958         /* set the props */
4959         if (props != NULL) {
4960                 spa_configfile_set(newspa, props, B_FALSE);
4961                 error = spa_prop_set(newspa, props);
4962                 if (error)
4963                         goto out;
4964         }
4965 
4966         /* flush everything */
4967         txg = spa_vdev_config_enter(newspa);
4968         vdev_config_dirty(newspa->spa_root_vdev);
4969         (void) spa_vdev_config_exit(newspa, NULL, txg, 0, FTAG);
4970 
4971         if (zio_injection_enabled)
4972                 zio_handle_panic_injection(spa, FTAG, 2);
4973 
4974         spa_async_resume(newspa);
4975 
4976         /* finally, update the original pool's config */
4977         txg = spa_vdev_config_enter(spa);
4978         tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
4979         error = dmu_tx_assign(tx, TXG_WAIT);
4980         if (error != 0)
4981                 dmu_tx_abort(tx);
4982         for (c = 0; c < children; c++) {
4983                 if (vml[c] != NULL) {
4984                         vdev_split(vml[c]);
4985                         if (error == 0)
4986                                 spa_history_log_internal(spa, "detach", tx,
4987                                     "vdev=%s", vml[c]->vdev_path);
4988                         vdev_free(vml[c]);
4989                 }
4990         }
4991         vdev_config_dirty(spa->spa_root_vdev);
4992         spa->spa_config_splitting = NULL;
4993         nvlist_free(nvl);
4994         if (error == 0)
4995                 dmu_tx_commit(tx);
4996         (void) spa_vdev_exit(spa, NULL, txg, 0);
4997 
4998         if (zio_injection_enabled)
4999                 zio_handle_panic_injection(spa, FTAG, 3);
5000 
5001         /* split is complete; log a history record */
5002         spa_history_log_internal(newspa, "split", NULL,
5003             "from pool %s", spa_name(spa));
5004 
5005         kmem_free(vml, children * sizeof (vdev_t *));
5006 
5007         /* if we're not going to mount the filesystems in userland, export */
5008         if (exp)
5009                 error = spa_export_common(newname, POOL_STATE_EXPORTED, NULL,
5010                     B_FALSE, B_FALSE);
5011 
5012         return (error);
5013 
5014 out:
5015         spa_unload(newspa);
5016         spa_deactivate(newspa);
5017         spa_remove(newspa);
5018 
5019         txg = spa_vdev_config_enter(spa);
5020 
5021         /* re-online all offlined disks */
5022         for (c = 0; c < children; c++) {
5023                 if (vml[c] != NULL)
5024                         vml[c]->vdev_offline = B_FALSE;
5025         }
5026         vdev_reopen(spa->spa_root_vdev);
5027 
5028         nvlist_free(spa->spa_config_splitting);
5029         spa->spa_config_splitting = NULL;
5030         (void) spa_vdev_exit(spa, NULL, txg, error);
5031 
5032         kmem_free(vml, children * sizeof (vdev_t *));
5033         return (error);
5034 }
5035 
5036 static nvlist_t *
5037 spa_nvlist_lookup_by_guid(nvlist_t **nvpp, int count, uint64_t target_guid)
5038 {
5039         for (int i = 0; i < count; i++) {
5040                 uint64_t guid;
5041 
5042                 VERIFY(nvlist_lookup_uint64(nvpp[i], ZPOOL_CONFIG_GUID,
5043                     &guid) == 0);
5044 
5045                 if (guid == target_guid)
5046                         return (nvpp[i]);
5047         }
5048 
5049         return (NULL);
5050 }
5051 
5052 static void
5053 spa_vdev_remove_aux(nvlist_t *config, char *name, nvlist_t **dev, int count,
5054         nvlist_t *dev_to_remove)
5055 {
5056         nvlist_t **newdev = NULL;
5057 
5058         if (count > 1)
5059                 newdev = kmem_alloc((count - 1) * sizeof (void *), KM_SLEEP);
5060 
5061         for (int i = 0, j = 0; i < count; i++) {
5062                 if (dev[i] == dev_to_remove)
5063                         continue;
5064                 VERIFY(nvlist_dup(dev[i], &newdev[j++], KM_SLEEP) == 0);
5065         }
5066 
5067         VERIFY(nvlist_remove(config, name, DATA_TYPE_NVLIST_ARRAY) == 0);
5068         VERIFY(nvlist_add_nvlist_array(config, name, newdev, count - 1) == 0);
5069 
5070         for (int i = 0; i < count - 1; i++)
5071                 nvlist_free(newdev[i]);
5072 
5073         if (count > 1)
5074                 kmem_free(newdev, (count - 1) * sizeof (void *));
5075 }
5076 
5077 /*
5078  * Evacuate the device.
5079  */
5080 static int
5081 spa_vdev_remove_evacuate(spa_t *spa, vdev_t *vd)
5082 {
5083         uint64_t txg;
5084         int error = 0;
5085 
5086         ASSERT(MUTEX_HELD(&spa_namespace_lock));
5087         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
5088         ASSERT(vd == vd->vdev_top);
5089 
5090         /*
5091          * Evacuate the device.  We don't hold the config lock as writer
5092          * since we need to do I/O but we do keep the
5093          * spa_namespace_lock held.  Once this completes the device
5094          * should no longer have any blocks allocated on it.
5095          */
5096         if (vd->vdev_islog) {
5097                 if (vd->vdev_stat.vs_alloc != 0)
5098                         error = spa_offline_log(spa);
5099         } else {
5100                 error = SET_ERROR(ENOTSUP);
5101         }
5102 
5103         if (error)
5104                 return (error);
5105 
5106         /*
5107          * The evacuation succeeded.  Remove any remaining MOS metadata
5108          * associated with this vdev, and wait for these changes to sync.
5109          */
5110         ASSERT0(vd->vdev_stat.vs_alloc);
5111         txg = spa_vdev_config_enter(spa);
5112         vd->vdev_removing = B_TRUE;
5113         vdev_dirty(vd, 0, NULL, txg);
5114         vdev_config_dirty(vd);
5115         spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
5116 
5117         return (0);
5118 }
5119 
5120 /*
5121  * Complete the removal by cleaning up the namespace.
5122  */
5123 static void
5124 spa_vdev_remove_from_namespace(spa_t *spa, vdev_t *vd)
5125 {
5126         vdev_t *rvd = spa->spa_root_vdev;
5127         uint64_t id = vd->vdev_id;
5128         boolean_t last_vdev = (id == (rvd->vdev_children - 1));
5129 
5130         ASSERT(MUTEX_HELD(&spa_namespace_lock));
5131         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
5132         ASSERT(vd == vd->vdev_top);
5133 
5134         /*
5135          * Only remove any devices which are empty.
5136          */
5137         if (vd->vdev_stat.vs_alloc != 0)
5138                 return;
5139 
5140         (void) vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
5141 
5142         if (list_link_active(&vd->vdev_state_dirty_node))
5143                 vdev_state_clean(vd);
5144         if (list_link_active(&vd->vdev_config_dirty_node))
5145                 vdev_config_clean(vd);
5146 
5147         vdev_free(vd);
5148 
5149         if (last_vdev) {
5150                 vdev_compact_children(rvd);
5151         } else {
5152                 vd = vdev_alloc_common(spa, id, 0, &vdev_hole_ops);
5153                 vdev_add_child(rvd, vd);
5154         }
5155         vdev_config_dirty(rvd);
5156 
5157         /*
5158          * Reassess the health of our root vdev.
5159          */
5160         vdev_reopen(rvd);
5161 }
5162 
5163 /*
5164  * Remove a device from the pool -
5165  *
5166  * Removing a device from the vdev namespace requires several steps
5167  * and can take a significant amount of time.  As a result we use
5168  * the spa_vdev_config_[enter/exit] functions which allow us to
5169  * grab and release the spa_config_lock while still holding the namespace
5170  * lock.  During each step the configuration is synced out.
5171  */
5172 
5173 /*
5174  * Remove a device from the pool.  Currently, this supports removing only hot
5175  * spares, slogs, and level 2 ARC devices.
5176  */
5177 int
5178 spa_vdev_remove(spa_t *spa, uint64_t guid, boolean_t unspare)
5179 {
5180         vdev_t *vd;
5181         metaslab_group_t *mg;
5182         nvlist_t **spares, **l2cache, *nv;
5183         uint64_t txg = 0;
5184         uint_t nspares, nl2cache;
5185         int error = 0;
5186         boolean_t locked = MUTEX_HELD(&spa_namespace_lock);
5187 
5188         ASSERT(spa_writeable(spa));
5189 
5190         if (!locked)
5191                 txg = spa_vdev_enter(spa);
5192 
5193         vd = spa_lookup_by_guid(spa, guid, B_FALSE);
5194 
5195         if (spa->spa_spares.sav_vdevs != NULL &&
5196             nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
5197             ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0 &&
5198             (nv = spa_nvlist_lookup_by_guid(spares, nspares, guid)) != NULL) {
5199                 /*
5200                  * Only remove the hot spare if it's not currently in use
5201                  * in this pool.
5202                  */
5203                 if (vd == NULL || unspare) {
5204                         spa_vdev_remove_aux(spa->spa_spares.sav_config,
5205                             ZPOOL_CONFIG_SPARES, spares, nspares, nv);
5206                         spa_load_spares(spa);
5207                         spa->spa_spares.sav_sync = B_TRUE;
5208                 } else {
5209                         error = SET_ERROR(EBUSY);
5210                 }
5211         } else if (spa->spa_l2cache.sav_vdevs != NULL &&
5212             nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
5213             ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0 &&
5214             (nv = spa_nvlist_lookup_by_guid(l2cache, nl2cache, guid)) != NULL) {
5215                 /*
5216                  * Cache devices can always be removed.
5217                  */
5218                 spa_vdev_remove_aux(spa->spa_l2cache.sav_config,
5219                     ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache, nv);
5220                 spa_load_l2cache(spa);
5221                 spa->spa_l2cache.sav_sync = B_TRUE;
5222         } else if (vd != NULL && vd->vdev_islog) {
5223                 ASSERT(!locked);
5224                 ASSERT(vd == vd->vdev_top);
5225 
5226                 /*
5227                  * XXX - Once we have bp-rewrite this should
5228                  * become the common case.
5229                  */
5230 
5231                 mg = vd->vdev_mg;
5232 
5233                 /*
5234                  * Stop allocating from this vdev.
5235                  */
5236                 metaslab_group_passivate(mg);
5237 
5238                 /*
5239                  * Wait for the youngest allocations and frees to sync,
5240                  * and then wait for the deferral of those frees to finish.
5241                  */
5242                 spa_vdev_config_exit(spa, NULL,
5243                     txg + TXG_CONCURRENT_STATES + TXG_DEFER_SIZE, 0, FTAG);
5244 
5245                 /*
5246                  * Attempt to evacuate the vdev.
5247                  */
5248                 error = spa_vdev_remove_evacuate(spa, vd);
5249 
5250                 txg = spa_vdev_config_enter(spa);
5251 
5252                 /*
5253                  * If we couldn't evacuate the vdev, unwind.
5254                  */
5255                 if (error) {
5256                         metaslab_group_activate(mg);
5257                         return (spa_vdev_exit(spa, NULL, txg, error));
5258                 }
5259 
5260                 /*
5261                  * Clean up the vdev namespace.
5262                  */
5263                 spa_vdev_remove_from_namespace(spa, vd);
5264 
5265         } else if (vd != NULL) {
5266                 /*
5267                  * Normal vdevs cannot be removed (yet).
5268                  */
5269                 error = SET_ERROR(ENOTSUP);
5270         } else {
5271                 /*
5272                  * There is no vdev of any kind with the specified guid.
5273                  */
5274                 error = SET_ERROR(ENOENT);
5275         }
5276 
5277         if (!locked)
5278                 return (spa_vdev_exit(spa, NULL, txg, error));
5279 
5280         return (error);
5281 }
5282 
5283 /*
5284  * Find any device that's done replacing, or a vdev marked 'unspare' that's
5285  * current spared, so we can detach it.
5286  */
5287 static vdev_t *
5288 spa_vdev_resilver_done_hunt(vdev_t *vd)
5289 {
5290         vdev_t *newvd, *oldvd;
5291 
5292         for (int c = 0; c < vd->vdev_children; c++) {
5293                 oldvd = spa_vdev_resilver_done_hunt(vd->vdev_child[c]);
5294                 if (oldvd != NULL)
5295                         return (oldvd);
5296         }
5297 
5298         /*
5299          * Check for a completed replacement.  We always consider the first
5300          * vdev in the list to be the oldest vdev, and the last one to be
5301          * the newest (see spa_vdev_attach() for how that works).  In
5302          * the case where the newest vdev is faulted, we will not automatically
5303          * remove it after a resilver completes.  This is OK as it will require
5304          * user intervention to determine which disk the admin wishes to keep.
5305          */
5306         if (vd->vdev_ops == &vdev_replacing_ops) {
5307                 ASSERT(vd->vdev_children > 1);
5308 
5309                 newvd = vd->vdev_child[vd->vdev_children - 1];
5310                 oldvd = vd->vdev_child[0];
5311 
5312                 if (vdev_dtl_empty(newvd, DTL_MISSING) &&
5313                     vdev_dtl_empty(newvd, DTL_OUTAGE) &&
5314                     !vdev_dtl_required(oldvd))
5315                         return (oldvd);
5316         }
5317 
5318         /*
5319          * Check for a completed resilver with the 'unspare' flag set.
5320          */
5321         if (vd->vdev_ops == &vdev_spare_ops) {
5322                 vdev_t *first = vd->vdev_child[0];
5323                 vdev_t *last = vd->vdev_child[vd->vdev_children - 1];
5324 
5325                 if (last->vdev_unspare) {
5326                         oldvd = first;
5327                         newvd = last;
5328                 } else if (first->vdev_unspare) {
5329                         oldvd = last;
5330                         newvd = first;
5331                 } else {
5332                         oldvd = NULL;
5333                 }
5334 
5335                 if (oldvd != NULL &&
5336                     vdev_dtl_empty(newvd, DTL_MISSING) &&
5337                     vdev_dtl_empty(newvd, DTL_OUTAGE) &&
5338                     !vdev_dtl_required(oldvd))
5339                         return (oldvd);
5340 
5341                 /*
5342                  * If there are more than two spares attached to a disk,
5343                  * and those spares are not required, then we want to
5344                  * attempt to free them up now so that they can be used
5345                  * by other pools.  Once we're back down to a single
5346                  * disk+spare, we stop removing them.
5347                  */
5348                 if (vd->vdev_children > 2) {
5349                         newvd = vd->vdev_child[1];
5350 
5351                         if (newvd->vdev_isspare && last->vdev_isspare &&
5352                             vdev_dtl_empty(last, DTL_MISSING) &&
5353                             vdev_dtl_empty(last, DTL_OUTAGE) &&
5354                             !vdev_dtl_required(newvd))
5355                                 return (newvd);
5356                 }
5357         }
5358 
5359         return (NULL);
5360 }
5361 
5362 static void
5363 spa_vdev_resilver_done(spa_t *spa)
5364 {
5365         vdev_t *vd, *pvd, *ppvd;
5366         uint64_t guid, sguid, pguid, ppguid;
5367 
5368         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5369 
5370         while ((vd = spa_vdev_resilver_done_hunt(spa->spa_root_vdev)) != NULL) {
5371                 pvd = vd->vdev_parent;
5372                 ppvd = pvd->vdev_parent;
5373                 guid = vd->vdev_guid;
5374                 pguid = pvd->vdev_guid;
5375                 ppguid = ppvd->vdev_guid;
5376                 sguid = 0;
5377                 /*
5378                  * If we have just finished replacing a hot spared device, then
5379                  * we need to detach the parent's first child (the original hot
5380                  * spare) as well.
5381                  */
5382                 if (ppvd->vdev_ops == &vdev_spare_ops && pvd->vdev_id == 0 &&
5383                     ppvd->vdev_children == 2) {
5384                         ASSERT(pvd->vdev_ops == &vdev_replacing_ops);
5385                         sguid = ppvd->vdev_child[1]->vdev_guid;
5386                 }
5387                 spa_config_exit(spa, SCL_ALL, FTAG);
5388                 if (spa_vdev_detach(spa, guid, pguid, B_TRUE) != 0)
5389                         return;
5390                 if (sguid && spa_vdev_detach(spa, sguid, ppguid, B_TRUE) != 0)
5391                         return;
5392                 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5393         }
5394 
5395         spa_config_exit(spa, SCL_ALL, FTAG);
5396 }
5397 
5398 /*
5399  * Update the stored path or FRU for this vdev.
5400  */
5401 int
5402 spa_vdev_set_common(spa_t *spa, uint64_t guid, const char *value,
5403     boolean_t ispath)
5404 {
5405         vdev_t *vd;
5406         boolean_t sync = B_FALSE;
5407 
5408         ASSERT(spa_writeable(spa));
5409 
5410         spa_vdev_state_enter(spa, SCL_ALL);
5411 
5412         if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
5413                 return (spa_vdev_state_exit(spa, NULL, ENOENT));
5414 
5415         if (!vd->vdev_ops->vdev_op_leaf)
5416                 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
5417 
5418         if (ispath) {
5419                 if (strcmp(value, vd->vdev_path) != 0) {
5420                         spa_strfree(vd->vdev_path);
5421                         vd->vdev_path = spa_strdup(value);
5422                         sync = B_TRUE;
5423                 }
5424         } else {
5425                 if (vd->vdev_fru == NULL) {
5426                         vd->vdev_fru = spa_strdup(value);
5427                         sync = B_TRUE;
5428                 } else if (strcmp(value, vd->vdev_fru) != 0) {
5429                         spa_strfree(vd->vdev_fru);
5430                         vd->vdev_fru = spa_strdup(value);
5431                         sync = B_TRUE;
5432                 }
5433         }
5434 
5435         return (spa_vdev_state_exit(spa, sync ? vd : NULL, 0));
5436 }
5437 
5438 int
5439 spa_vdev_setpath(spa_t *spa, uint64_t guid, const char *newpath)
5440 {
5441         return (spa_vdev_set_common(spa, guid, newpath, B_TRUE));
5442 }
5443 
5444 int
5445 spa_vdev_setfru(spa_t *spa, uint64_t guid, const char *newfru)
5446 {
5447         return (spa_vdev_set_common(spa, guid, newfru, B_FALSE));
5448 }
5449 
5450 /*
5451  * ==========================================================================
5452  * SPA Scanning
5453  * ==========================================================================
5454  */
5455 
5456 int
5457 spa_scan_stop(spa_t *spa)
5458 {
5459         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
5460         if (dsl_scan_resilvering(spa->spa_dsl_pool))
5461                 return (SET_ERROR(EBUSY));
5462         return (dsl_scan_cancel(spa->spa_dsl_pool));
5463 }
5464 
5465 int
5466 spa_scan(spa_t *spa, pool_scan_func_t func)
5467 {
5468         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
5469 
5470         if (func >= POOL_SCAN_FUNCS || func == POOL_SCAN_NONE)
5471                 return (SET_ERROR(ENOTSUP));
5472 
5473         /*
5474          * If a resilver was requested, but there is no DTL on a
5475          * writeable leaf device, we have nothing to do.
5476          */
5477         if (func == POOL_SCAN_RESILVER &&
5478             !vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL)) {
5479                 spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
5480                 return (0);
5481         }
5482 
5483         return (dsl_scan(spa->spa_dsl_pool, func));
5484 }
5485 
5486 /*
5487  * ==========================================================================
5488  * SPA async task processing
5489  * ==========================================================================
5490  */
5491 
5492 static void
5493 spa_async_remove(spa_t *spa, vdev_t *vd)
5494 {
5495         if (vd->vdev_remove_wanted) {
5496                 vd->vdev_remove_wanted = B_FALSE;
5497                 vd->vdev_delayed_close = B_FALSE;
5498                 vdev_set_state(vd, B_FALSE, VDEV_STATE_REMOVED, VDEV_AUX_NONE);
5499 
5500                 /*
5501                  * We want to clear the stats, but we don't want to do a full
5502                  * vdev_clear() as that will cause us to throw away
5503                  * degraded/faulted state as well as attempt to reopen the
5504                  * device, all of which is a waste.
5505                  */
5506                 vd->vdev_stat.vs_read_errors = 0;
5507                 vd->vdev_stat.vs_write_errors = 0;
5508                 vd->vdev_stat.vs_checksum_errors = 0;
5509 
5510                 vdev_state_dirty(vd->vdev_top);
5511         }
5512 
5513         for (int c = 0; c < vd->vdev_children; c++)
5514                 spa_async_remove(spa, vd->vdev_child[c]);
5515 }
5516 
5517 static void
5518 spa_async_probe(spa_t *spa, vdev_t *vd)
5519 {
5520         if (vd->vdev_probe_wanted) {
5521                 vd->vdev_probe_wanted = B_FALSE;
5522                 vdev_reopen(vd);        /* vdev_open() does the actual probe */
5523         }
5524 
5525         for (int c = 0; c < vd->vdev_children; c++)
5526                 spa_async_probe(spa, vd->vdev_child[c]);
5527 }
5528 
5529 static void
5530 spa_async_autoexpand(spa_t *spa, vdev_t *vd)
5531 {
5532         sysevent_id_t eid;
5533         nvlist_t *attr;
5534         char *physpath;
5535 
5536         if (!spa->spa_autoexpand)
5537                 return;
5538 
5539         for (int c = 0; c < vd->vdev_children; c++) {
5540                 vdev_t *cvd = vd->vdev_child[c];
5541                 spa_async_autoexpand(spa, cvd);
5542         }
5543 
5544         if (!vd->vdev_ops->vdev_op_leaf || vd->vdev_physpath == NULL)
5545                 return;
5546 
5547         physpath = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
5548         (void) snprintf(physpath, MAXPATHLEN, "/devices%s", vd->vdev_physpath);
5549 
5550         VERIFY(nvlist_alloc(&attr, NV_UNIQUE_NAME, KM_SLEEP) == 0);
5551         VERIFY(nvlist_add_string(attr, DEV_PHYS_PATH, physpath) == 0);
5552 
5553         (void) ddi_log_sysevent(zfs_dip, SUNW_VENDOR, EC_DEV_STATUS,
5554             ESC_DEV_DLE, attr, &eid, DDI_SLEEP);
5555 
5556         nvlist_free(attr);
5557         kmem_free(physpath, MAXPATHLEN);
5558 }
5559 
5560 static void
5561 spa_async_thread(spa_t *spa)
5562 {
5563         int tasks;
5564 
5565         ASSERT(spa->spa_sync_on);
5566 
5567         mutex_enter(&spa->spa_async_lock);
5568         tasks = spa->spa_async_tasks;
5569         spa->spa_async_tasks = 0;
5570         mutex_exit(&spa->spa_async_lock);
5571 
5572         /*
5573          * See if the config needs to be updated.
5574          */
5575         if (tasks & SPA_ASYNC_CONFIG_UPDATE) {
5576                 uint64_t old_space, new_space;
5577 
5578                 mutex_enter(&spa_namespace_lock);
5579                 old_space = metaslab_class_get_space(spa_normal_class(spa));
5580                 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5581                 new_space = metaslab_class_get_space(spa_normal_class(spa));
5582                 mutex_exit(&spa_namespace_lock);
5583 
5584                 /*
5585                  * If the pool grew as a result of the config update,
5586                  * then log an internal history event.
5587                  */
5588                 if (new_space != old_space) {
5589                         spa_history_log_internal(spa, "vdev online", NULL,
5590                             "pool '%s' size: %llu(+%llu)",
5591                             spa_name(spa), new_space, new_space - old_space);
5592                 }
5593         }
5594 
5595         /*
5596          * See if any devices need to be marked REMOVED.
5597          */
5598         if (tasks & SPA_ASYNC_REMOVE) {
5599                 spa_vdev_state_enter(spa, SCL_NONE);
5600                 spa_async_remove(spa, spa->spa_root_vdev);
5601                 for (int i = 0; i < spa->spa_l2cache.sav_count; i++)
5602                         spa_async_remove(spa, spa->spa_l2cache.sav_vdevs[i]);
5603                 for (int i = 0; i < spa->spa_spares.sav_count; i++)
5604                         spa_async_remove(spa, spa->spa_spares.sav_vdevs[i]);
5605                 (void) spa_vdev_state_exit(spa, NULL, 0);
5606         }
5607 
5608         if ((tasks & SPA_ASYNC_AUTOEXPAND) && !spa_suspended(spa)) {
5609                 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
5610                 spa_async_autoexpand(spa, spa->spa_root_vdev);
5611                 spa_config_exit(spa, SCL_CONFIG, FTAG);
5612         }
5613 
5614         /*
5615          * See if any devices need to be probed.
5616          */
5617         if (tasks & SPA_ASYNC_PROBE) {
5618                 spa_vdev_state_enter(spa, SCL_NONE);
5619                 spa_async_probe(spa, spa->spa_root_vdev);
5620                 (void) spa_vdev_state_exit(spa, NULL, 0);
5621         }
5622 
5623         /*
5624          * If any devices are done replacing, detach them.
5625          */
5626         if (tasks & SPA_ASYNC_RESILVER_DONE)
5627                 spa_vdev_resilver_done(spa);
5628 
5629         /*
5630          * Kick off a resilver.
5631          */
5632         if (tasks & SPA_ASYNC_RESILVER)
5633                 dsl_resilver_restart(spa->spa_dsl_pool, 0);
5634 
5635         /*
5636          * Let the world know that we're done.
5637          */
5638         mutex_enter(&spa->spa_async_lock);
5639         spa->spa_async_thread = NULL;
5640         cv_broadcast(&spa->spa_async_cv);
5641         mutex_exit(&spa->spa_async_lock);
5642         thread_exit();
5643 }
5644 
5645 void
5646 spa_async_suspend(spa_t *spa)
5647 {
5648         mutex_enter(&spa->spa_async_lock);
5649         spa->spa_async_suspended++;
5650         while (spa->spa_async_thread != NULL)
5651                 cv_wait(&spa->spa_async_cv, &spa->spa_async_lock);
5652         mutex_exit(&spa->spa_async_lock);
5653 }
5654 
5655 void
5656 spa_async_resume(spa_t *spa)
5657 {
5658         mutex_enter(&spa->spa_async_lock);
5659         ASSERT(spa->spa_async_suspended != 0);
5660         spa->spa_async_suspended--;
5661         mutex_exit(&spa->spa_async_lock);
5662 }
5663 
5664 static void
5665 spa_async_dispatch(spa_t *spa)
5666 {
5667         mutex_enter(&spa->spa_async_lock);
5668         if (spa->spa_async_tasks && !spa->spa_async_suspended &&
5669             spa->spa_async_thread == NULL &&
5670             rootdir != NULL && !vn_is_readonly(rootdir))
5671                 spa->spa_async_thread = thread_create(NULL, 0,
5672                     spa_async_thread, spa, 0, &p0, TS_RUN, maxclsyspri);
5673         mutex_exit(&spa->spa_async_lock);
5674 }
5675 
5676 void
5677 spa_async_request(spa_t *spa, int task)
5678 {
5679         zfs_dbgmsg("spa=%s async request task=%u", spa->spa_name, task);
5680         mutex_enter(&spa->spa_async_lock);
5681         spa->spa_async_tasks |= task;
5682         mutex_exit(&spa->spa_async_lock);
5683 }
5684 
5685 /*
5686  * ==========================================================================
5687  * SPA syncing routines
5688  * ==========================================================================
5689  */
5690 
5691 static int
5692 bpobj_enqueue_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
5693 {
5694         bpobj_t *bpo = arg;
5695         bpobj_enqueue(bpo, bp, tx);
5696         return (0);
5697 }
5698 
5699 static int
5700 spa_free_sync_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
5701 {
5702         zio_t *zio = arg;
5703 
5704         zio_nowait(zio_free_sync(zio, zio->io_spa, dmu_tx_get_txg(tx), bp,
5705             zio->io_flags));
5706         return (0);
5707 }
5708 
5709 static void
5710 spa_sync_nvlist(spa_t *spa, uint64_t obj, nvlist_t *nv, dmu_tx_t *tx)
5711 {
5712         char *packed = NULL;
5713         size_t bufsize;
5714         size_t nvsize = 0;
5715         dmu_buf_t *db;
5716 
5717         VERIFY(nvlist_size(nv, &nvsize, NV_ENCODE_XDR) == 0);
5718 
5719         /*
5720          * Write full (SPA_CONFIG_BLOCKSIZE) blocks of configuration
5721          * information.  This avoids the dbuf_will_dirty() path and
5722          * saves us a pre-read to get data we don't actually care about.
5723          */
5724         bufsize = P2ROUNDUP((uint64_t)nvsize, SPA_CONFIG_BLOCKSIZE);
5725         packed = kmem_alloc(bufsize, KM_SLEEP);
5726 
5727         VERIFY(nvlist_pack(nv, &packed, &nvsize, NV_ENCODE_XDR,
5728             KM_SLEEP) == 0);
5729         bzero(packed + nvsize, bufsize - nvsize);
5730 
5731         dmu_write(spa->spa_meta_objset, obj, 0, bufsize, packed, tx);
5732 
5733         kmem_free(packed, bufsize);
5734 
5735         VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
5736         dmu_buf_will_dirty(db, tx);
5737         *(uint64_t *)db->db_data = nvsize;
5738         dmu_buf_rele(db, FTAG);
5739 }
5740 
5741 static void
5742 spa_sync_aux_dev(spa_t *spa, spa_aux_vdev_t *sav, dmu_tx_t *tx,
5743     const char *config, const char *entry)
5744 {
5745         nvlist_t *nvroot;
5746         nvlist_t **list;
5747         int i;
5748 
5749         if (!sav->sav_sync)
5750                 return;
5751 
5752         /*
5753          * Update the MOS nvlist describing the list of available devices.
5754          * spa_validate_aux() will have already made sure this nvlist is
5755          * valid and the vdevs are labeled appropriately.
5756          */
5757         if (sav->sav_object == 0) {
5758                 sav->sav_object = dmu_object_alloc(spa->spa_meta_objset,
5759                     DMU_OT_PACKED_NVLIST, 1 << 14, DMU_OT_PACKED_NVLIST_SIZE,
5760                     sizeof (uint64_t), tx);
5761                 VERIFY(zap_update(spa->spa_meta_objset,
5762                     DMU_POOL_DIRECTORY_OBJECT, entry, sizeof (uint64_t), 1,
5763                     &sav->sav_object, tx) == 0);
5764         }
5765 
5766         VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
5767         if (sav->sav_count == 0) {
5768                 VERIFY(nvlist_add_nvlist_array(nvroot, config, NULL, 0) == 0);
5769         } else {
5770                 list = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
5771                 for (i = 0; i < sav->sav_count; i++)
5772                         list[i] = vdev_config_generate(spa, sav->sav_vdevs[i],
5773                             B_FALSE, VDEV_CONFIG_L2CACHE);
5774                 VERIFY(nvlist_add_nvlist_array(nvroot, config, list,
5775                     sav->sav_count) == 0);
5776                 for (i = 0; i < sav->sav_count; i++)
5777                         nvlist_free(list[i]);
5778                 kmem_free(list, sav->sav_count * sizeof (void *));
5779         }
5780 
5781         spa_sync_nvlist(spa, sav->sav_object, nvroot, tx);
5782         nvlist_free(nvroot);
5783 
5784         sav->sav_sync = B_FALSE;
5785 }
5786 
5787 static void
5788 spa_sync_config_object(spa_t *spa, dmu_tx_t *tx)
5789 {
5790         nvlist_t *config;
5791 
5792         if (list_is_empty(&spa->spa_config_dirty_list))
5793                 return;
5794 
5795         spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
5796 
5797         config = spa_config_generate(spa, spa->spa_root_vdev,
5798             dmu_tx_get_txg(tx), B_FALSE);
5799 
5800         /*
5801          * If we're upgrading the spa version then make sure that
5802          * the config object gets updated with the correct version.
5803          */
5804         if (spa->spa_ubsync.ub_version < spa->spa_uberblock.ub_version)
5805                 fnvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
5806                     spa->spa_uberblock.ub_version);
5807 
5808         spa_config_exit(spa, SCL_STATE, FTAG);
5809 
5810         if (spa->spa_config_syncing)
5811                 nvlist_free(spa->spa_config_syncing);
5812         spa->spa_config_syncing = config;
5813 
5814         spa_sync_nvlist(spa, spa->spa_config_object, config, tx);
5815 }
5816 
5817 static void
5818 spa_sync_version(void *arg, dmu_tx_t *tx)
5819 {
5820         uint64_t *versionp = arg;
5821         uint64_t version = *versionp;
5822         spa_t *spa = dmu_tx_pool(tx)->dp_spa;
5823 
5824         /*
5825          * Setting the version is special cased when first creating the pool.
5826          */
5827         ASSERT(tx->tx_txg != TXG_INITIAL);
5828 
5829         ASSERT(SPA_VERSION_IS_SUPPORTED(version));
5830         ASSERT(version >= spa_version(spa));
5831 
5832         spa->spa_uberblock.ub_version = version;
5833         vdev_config_dirty(spa->spa_root_vdev);
5834         spa_history_log_internal(spa, "set", tx, "version=%lld", version);
5835 }
5836 
5837 /*
5838  * Set zpool properties.
5839  */
5840 static void
5841 spa_sync_props(void *arg, dmu_tx_t *tx)
5842 {
5843         nvlist_t *nvp = arg;
5844         spa_t *spa = dmu_tx_pool(tx)->dp_spa;
5845         objset_t *mos = spa->spa_meta_objset;
5846         nvpair_t *elem = NULL;
5847 
5848         mutex_enter(&spa->spa_props_lock);
5849 
5850         while ((elem = nvlist_next_nvpair(nvp, elem))) {
5851                 uint64_t intval;
5852                 char *strval, *fname;
5853                 zpool_prop_t prop;
5854                 const char *propname;
5855                 zprop_type_t proptype;
5856                 zfeature_info_t *feature;
5857 
5858                 switch (prop = zpool_name_to_prop(nvpair_name(elem))) {
5859                 case ZPROP_INVAL:
5860                         /*
5861                          * We checked this earlier in spa_prop_validate().
5862                          */
5863                         ASSERT(zpool_prop_feature(nvpair_name(elem)));
5864 
5865                         fname = strchr(nvpair_name(elem), '@') + 1;
5866                         VERIFY3U(0, ==, zfeature_lookup_name(fname, &feature));
5867 
5868                         spa_feature_enable(spa, feature, tx);
5869                         spa_history_log_internal(spa, "set", tx,
5870                             "%s=enabled", nvpair_name(elem));
5871                         break;
5872 
5873                 case ZPOOL_PROP_VERSION:
5874                         VERIFY(nvpair_value_uint64(elem, &intval) == 0);
5875                         /*
5876                          * The version is synced seperatly before other
5877                          * properties and should be correct by now.
5878                          */
5879                         ASSERT3U(spa_version(spa), >=, intval);
5880                         break;
5881 
5882                 case ZPOOL_PROP_ALTROOT:
5883                         /*
5884                          * 'altroot' is a non-persistent property. It should
5885                          * have been set temporarily at creation or import time.
5886                          */
5887                         ASSERT(spa->spa_root != NULL);
5888                         break;
5889 
5890                 case ZPOOL_PROP_READONLY:
5891                 case ZPOOL_PROP_CACHEFILE:
5892                         /*
5893                          * 'readonly' and 'cachefile' are also non-persisitent
5894                          * properties.
5895                          */
5896                         break;
5897                 case ZPOOL_PROP_COMMENT:
5898                         VERIFY(nvpair_value_string(elem, &strval) == 0);
5899                         if (spa->spa_comment != NULL)
5900                                 spa_strfree(spa->spa_comment);
5901                         spa->spa_comment = spa_strdup(strval);
5902                         /*
5903                          * We need to dirty the configuration on all the vdevs
5904                          * so that their labels get updated.  It's unnecessary
5905                          * to do this for pool creation since the vdev's
5906                          * configuratoin has already been dirtied.
5907                          */
5908                         if (tx->tx_txg != TXG_INITIAL)
5909                                 vdev_config_dirty(spa->spa_root_vdev);
5910                         spa_history_log_internal(spa, "set", tx,
5911                             "%s=%s", nvpair_name(elem), strval);
5912                         break;
5913                 default:
5914                         /*
5915                          * Set pool property values in the poolprops mos object.
5916                          */
5917                         if (spa->spa_pool_props_object == 0) {
5918                                 spa->spa_pool_props_object =
5919                                     zap_create_link(mos, DMU_OT_POOL_PROPS,
5920                                     DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_PROPS,
5921                                     tx);
5922                         }
5923 
5924                         /* normalize the property name */
5925                         propname = zpool_prop_to_name(prop);
5926                         proptype = zpool_prop_get_type(prop);
5927 
5928                         if (nvpair_type(elem) == DATA_TYPE_STRING) {
5929                                 ASSERT(proptype == PROP_TYPE_STRING);
5930                                 VERIFY(nvpair_value_string(elem, &strval) == 0);
5931                                 VERIFY(zap_update(mos,
5932                                     spa->spa_pool_props_object, propname,
5933                                     1, strlen(strval) + 1, strval, tx) == 0);
5934                                 spa_history_log_internal(spa, "set", tx,
5935                                     "%s=%s", nvpair_name(elem), strval);
5936                         } else if (nvpair_type(elem) == DATA_TYPE_UINT64) {
5937                                 VERIFY(nvpair_value_uint64(elem, &intval) == 0);
5938 
5939                                 if (proptype == PROP_TYPE_INDEX) {
5940                                         const char *unused;
5941                                         VERIFY(zpool_prop_index_to_string(
5942                                             prop, intval, &unused) == 0);
5943                                 }
5944                                 VERIFY(zap_update(mos,
5945                                     spa->spa_pool_props_object, propname,
5946                                     8, 1, &intval, tx) == 0);
5947                                 spa_history_log_internal(spa, "set", tx,
5948                                     "%s=%lld", nvpair_name(elem), intval);
5949                         } else {
5950                                 ASSERT(0); /* not allowed */
5951                         }
5952 
5953                         switch (prop) {
5954                         case ZPOOL_PROP_DELEGATION:
5955                                 spa->spa_delegation = intval;
5956                                 break;
5957                         case ZPOOL_PROP_BOOTFS:
5958                                 spa->spa_bootfs = intval;
5959                                 break;
5960                         case ZPOOL_PROP_FAILUREMODE:
5961                                 spa->spa_failmode = intval;
5962                                 break;
5963                         case ZPOOL_PROP_AUTOEXPAND:
5964                                 spa->spa_autoexpand = intval;
5965                                 if (tx->tx_txg != TXG_INITIAL)
5966                                         spa_async_request(spa,
5967                                             SPA_ASYNC_AUTOEXPAND);
5968                                 break;
5969                         case ZPOOL_PROP_DEDUPDITTO:
5970                                 spa->spa_dedup_ditto = intval;
5971                                 break;
5972                         default:
5973                                 break;
5974                         }
5975                 }
5976 
5977         }
5978 
5979         mutex_exit(&spa->spa_props_lock);
5980 }
5981 
5982 /*
5983  * Perform one-time upgrade on-disk changes.  spa_version() does not
5984  * reflect the new version this txg, so there must be no changes this
5985  * txg to anything that the upgrade code depends on after it executes.
5986  * Therefore this must be called after dsl_pool_sync() does the sync
5987  * tasks.
5988  */
5989 static void
5990 spa_sync_upgrades(spa_t *spa, dmu_tx_t *tx)
5991 {
5992         dsl_pool_t *dp = spa->spa_dsl_pool;
5993 
5994         ASSERT(spa->spa_sync_pass == 1);
5995 
5996         rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
5997 
5998         if (spa->spa_ubsync.ub_version < SPA_VERSION_ORIGIN &&
5999             spa->spa_uberblock.ub_version >= SPA_VERSION_ORIGIN) {
6000                 dsl_pool_create_origin(dp, tx);
6001 
6002                 /* Keeping the origin open increases spa_minref */
6003                 spa->spa_minref += 3;
6004         }
6005 
6006         if (spa->spa_ubsync.ub_version < SPA_VERSION_NEXT_CLONES &&
6007             spa->spa_uberblock.ub_version >= SPA_VERSION_NEXT_CLONES) {
6008                 dsl_pool_upgrade_clones(dp, tx);
6009         }
6010 
6011         if (spa->spa_ubsync.ub_version < SPA_VERSION_DIR_CLONES &&
6012             spa->spa_uberblock.ub_version >= SPA_VERSION_DIR_CLONES) {
6013                 dsl_pool_upgrade_dir_clones(dp, tx);
6014 
6015                 /* Keeping the freedir open increases spa_minref */
6016                 spa->spa_minref += 3;
6017         }
6018 
6019         if (spa->spa_ubsync.ub_version < SPA_VERSION_FEATURES &&
6020             spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
6021                 spa_feature_create_zap_objects(spa, tx);
6022         }
6023         rrw_exit(&dp->dp_config_rwlock, FTAG);
6024 }
6025 
6026 /*
6027  * Sync the specified transaction group.  New blocks may be dirtied as
6028  * part of the process, so we iterate until it converges.
6029  */
6030 void
6031 spa_sync(spa_t *spa, uint64_t txg)
6032 {
6033         dsl_pool_t *dp = spa->spa_dsl_pool;
6034         objset_t *mos = spa->spa_meta_objset;
6035         bpobj_t *defer_bpo = &spa->spa_deferred_bpobj;
6036         bplist_t *free_bpl = &spa->spa_free_bplist[txg & TXG_MASK];
6037         vdev_t *rvd = spa->spa_root_vdev;
6038         vdev_t *vd;
6039         dmu_tx_t *tx;
6040         int error;
6041 
6042         VERIFY(spa_writeable(spa));
6043 
6044         /*
6045          * Lock out configuration changes.
6046          */
6047         spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
6048 
6049         spa->spa_syncing_txg = txg;
6050         spa->spa_sync_pass = 0;
6051 
6052         /*
6053          * If there are any pending vdev state changes, convert them
6054          * into config changes that go out with this transaction group.
6055          */
6056         spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
6057         while (list_head(&spa->spa_state_dirty_list) != NULL) {
6058                 /*
6059                  * We need the write lock here because, for aux vdevs,
6060                  * calling vdev_config_dirty() modifies sav_config.
6061                  * This is ugly and will become unnecessary when we
6062                  * eliminate the aux vdev wart by integrating all vdevs
6063                  * into the root vdev tree.
6064                  */
6065                 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6066                 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_WRITER);
6067                 while ((vd = list_head(&spa->spa_state_dirty_list)) != NULL) {
6068                         vdev_state_clean(vd);
6069                         vdev_config_dirty(vd);
6070                 }
6071                 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6072                 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
6073         }
6074         spa_config_exit(spa, SCL_STATE, FTAG);
6075 
6076         tx = dmu_tx_create_assigned(dp, txg);
6077 
6078         spa->spa_sync_starttime = gethrtime();
6079         VERIFY(cyclic_reprogram(spa->spa_deadman_cycid,
6080             spa->spa_sync_starttime + spa->spa_deadman_synctime));
6081 
6082         /*
6083          * If we are upgrading to SPA_VERSION_RAIDZ_DEFLATE this txg,
6084          * set spa_deflate if we have no raid-z vdevs.
6085          */
6086         if (spa->spa_ubsync.ub_version < SPA_VERSION_RAIDZ_DEFLATE &&
6087             spa->spa_uberblock.ub_version >= SPA_VERSION_RAIDZ_DEFLATE) {
6088                 int i;
6089 
6090                 for (i = 0; i < rvd->vdev_children; i++) {
6091                         vd = rvd->vdev_child[i];
6092                         if (vd->vdev_deflate_ratio != SPA_MINBLOCKSIZE)
6093                                 break;
6094                 }
6095                 if (i == rvd->vdev_children) {
6096                         spa->spa_deflate = TRUE;
6097                         VERIFY(0 == zap_add(spa->spa_meta_objset,
6098                             DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
6099                             sizeof (uint64_t), 1, &spa->spa_deflate, tx));
6100                 }
6101         }
6102 
6103         /*
6104          * If anything has changed in this txg, or if someone is waiting
6105          * for this txg to sync (eg, spa_vdev_remove()), push the
6106          * deferred frees from the previous txg.  If not, leave them
6107          * alone so that we don't generate work on an otherwise idle
6108          * system.
6109          */
6110         if (!txg_list_empty(&dp->dp_dirty_datasets, txg) ||
6111             !txg_list_empty(&dp->dp_dirty_dirs, txg) ||
6112             !txg_list_empty(&dp->dp_sync_tasks, txg) ||
6113             ((dsl_scan_active(dp->dp_scan) ||
6114             txg_sync_waiting(dp)) && !spa_shutting_down(spa))) {
6115                 zio_t *zio = zio_root(spa, NULL, NULL, 0);
6116                 VERIFY3U(bpobj_iterate(defer_bpo,
6117                     spa_free_sync_cb, zio, tx), ==, 0);
6118                 VERIFY0(zio_wait(zio));
6119         }
6120 
6121         /*
6122          * Iterate to convergence.
6123          */
6124         do {
6125                 int pass = ++spa->spa_sync_pass;
6126 
6127                 spa_sync_config_object(spa, tx);
6128                 spa_sync_aux_dev(spa, &spa->spa_spares, tx,
6129                     ZPOOL_CONFIG_SPARES, DMU_POOL_SPARES);
6130                 spa_sync_aux_dev(spa, &spa->spa_l2cache, tx,
6131                     ZPOOL_CONFIG_L2CACHE, DMU_POOL_L2CACHE);
6132                 spa_errlog_sync(spa, txg);
6133                 dsl_pool_sync(dp, txg);
6134 
6135                 if (pass < zfs_sync_pass_deferred_free) {
6136                         zio_t *zio = zio_root(spa, NULL, NULL, 0);
6137                         bplist_iterate(free_bpl, spa_free_sync_cb,
6138                             zio, tx);
6139                         VERIFY(zio_wait(zio) == 0);
6140                 } else {
6141                         bplist_iterate(free_bpl, bpobj_enqueue_cb,
6142                             defer_bpo, tx);
6143                 }
6144 
6145                 ddt_sync(spa, txg);
6146                 dsl_scan_sync(dp, tx);
6147 
6148                 while (vd = txg_list_remove(&spa->spa_vdev_txg_list, txg))
6149                         vdev_sync(vd, txg);
6150 
6151                 if (pass == 1)
6152                         spa_sync_upgrades(spa, tx);
6153 
6154         } while (dmu_objset_is_dirty(mos, txg));
6155 
6156         /*
6157          * Rewrite the vdev configuration (which includes the uberblock)
6158          * to commit the transaction group.
6159          *
6160          * If there are no dirty vdevs, we sync the uberblock to a few
6161          * random top-level vdevs that are known to be visible in the
6162          * config cache (see spa_vdev_add() for a complete description).
6163          * If there *are* dirty vdevs, sync the uberblock to all vdevs.
6164          */
6165         for (;;) {
6166                 /*
6167                  * We hold SCL_STATE to prevent vdev open/close/etc.
6168                  * while we're attempting to write the vdev labels.
6169                  */
6170                 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
6171 
6172                 if (list_is_empty(&spa->spa_config_dirty_list)) {
6173                         vdev_t *svd[SPA_DVAS_PER_BP];
6174                         int svdcount = 0;
6175                         int children = rvd->vdev_children;
6176                         int c0 = spa_get_random(children);
6177 
6178                         for (int c = 0; c < children; c++) {
6179                                 vd = rvd->vdev_child[(c0 + c) % children];
6180                                 if (vd->vdev_ms_array == 0 || vd->vdev_islog)
6181                                         continue;
6182                                 svd[svdcount++] = vd;
6183                                 if (svdcount == SPA_DVAS_PER_BP)
6184                                         break;
6185                         }
6186                         error = vdev_config_sync(svd, svdcount, txg, B_FALSE);
6187                         if (error != 0)
6188                                 error = vdev_config_sync(svd, svdcount, txg,
6189                                     B_TRUE);
6190                 } else {
6191                         error = vdev_config_sync(rvd->vdev_child,
6192                             rvd->vdev_children, txg, B_FALSE);
6193                         if (error != 0)
6194                                 error = vdev_config_sync(rvd->vdev_child,
6195                                     rvd->vdev_children, txg, B_TRUE);
6196                 }
6197 
6198                 if (error == 0)
6199                         spa->spa_last_synced_guid = rvd->vdev_guid;
6200 
6201                 spa_config_exit(spa, SCL_STATE, FTAG);
6202 
6203                 if (error == 0)
6204                         break;
6205                 zio_suspend(spa, NULL);
6206                 zio_resume_wait(spa);
6207         }
6208         dmu_tx_commit(tx);
6209 
6210         VERIFY(cyclic_reprogram(spa->spa_deadman_cycid, CY_INFINITY));
6211 
6212         /*
6213          * Clear the dirty config list.
6214          */
6215         while ((vd = list_head(&spa->spa_config_dirty_list)) != NULL)
6216                 vdev_config_clean(vd);
6217 
6218         /*
6219          * Now that the new config has synced transactionally,
6220          * let it become visible to the config cache.
6221          */
6222         if (spa->spa_config_syncing != NULL) {
6223                 spa_config_set(spa, spa->spa_config_syncing);
6224                 spa->spa_config_txg = txg;
6225                 spa->spa_config_syncing = NULL;
6226         }
6227 
6228         spa->spa_ubsync = spa->spa_uberblock;
6229 
6230         dsl_pool_sync_done(dp, txg);
6231 
6232         /*
6233          * Update usable space statistics.
6234          */
6235         while (vd = txg_list_remove(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)))
6236                 vdev_sync_done(vd, txg);
6237 
6238         spa_update_dspace(spa);
6239 
6240         /*
6241          * It had better be the case that we didn't dirty anything
6242          * since vdev_config_sync().
6243          */
6244         ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
6245         ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
6246         ASSERT(txg_list_empty(&spa->spa_vdev_txg_list, txg));
6247 
6248         spa->spa_sync_pass = 0;
6249 
6250         spa_config_exit(spa, SCL_CONFIG, FTAG);
6251 
6252         spa_handle_ignored_writes(spa);
6253 
6254         /*
6255          * If any async tasks have been requested, kick them off.
6256          */
6257         spa_async_dispatch(spa);
6258 }
6259 
6260 /*
6261  * Sync all pools.  We don't want to hold the namespace lock across these
6262  * operations, so we take a reference on the spa_t and drop the lock during the
6263  * sync.
6264  */
6265 void
6266 spa_sync_allpools(void)
6267 {
6268         spa_t *spa = NULL;
6269         mutex_enter(&spa_namespace_lock);
6270         while ((spa = spa_next(spa)) != NULL) {
6271                 if (spa_state(spa) != POOL_STATE_ACTIVE ||
6272                     !spa_writeable(spa) || spa_suspended(spa))
6273                         continue;
6274                 spa_open_ref(spa, FTAG);
6275                 mutex_exit(&spa_namespace_lock);
6276                 txg_wait_synced(spa_get_dsl(spa), 0);
6277                 mutex_enter(&spa_namespace_lock);
6278                 spa_close(spa, FTAG);
6279         }
6280         mutex_exit(&spa_namespace_lock);
6281 }
6282 
6283 /*
6284  * ==========================================================================
6285  * Miscellaneous routines
6286  * ==========================================================================
6287  */
6288 
6289 /*
6290  * Remove all pools in the system.
6291  */
6292 void
6293 spa_evict_all(void)
6294 {
6295         spa_t *spa;
6296 
6297         /*
6298          * Remove all cached state.  All pools should be closed now,
6299          * so every spa in the AVL tree should be unreferenced.
6300          */
6301         mutex_enter(&spa_namespace_lock);
6302         while ((spa = spa_next(NULL)) != NULL) {
6303                 /*
6304                  * Stop async tasks.  The async thread may need to detach
6305                  * a device that's been replaced, which requires grabbing
6306                  * spa_namespace_lock, so we must drop it here.
6307                  */
6308                 spa_open_ref(spa, FTAG);
6309                 mutex_exit(&spa_namespace_lock);
6310                 spa_async_suspend(spa);
6311                 mutex_enter(&spa_namespace_lock);
6312                 spa_close(spa, FTAG);
6313 
6314                 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
6315                         spa_unload(spa);
6316                         spa_deactivate(spa);
6317                 }
6318                 spa_remove(spa);
6319         }
6320         mutex_exit(&spa_namespace_lock);
6321 }
6322 
6323 vdev_t *
6324 spa_lookup_by_guid(spa_t *spa, uint64_t guid, boolean_t aux)
6325 {
6326         vdev_t *vd;
6327         int i;
6328 
6329         if ((vd = vdev_lookup_by_guid(spa->spa_root_vdev, guid)) != NULL)
6330                 return (vd);
6331 
6332         if (aux) {
6333                 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
6334                         vd = spa->spa_l2cache.sav_vdevs[i];
6335                         if (vd->vdev_guid == guid)
6336                                 return (vd);
6337                 }
6338 
6339                 for (i = 0; i < spa->spa_spares.sav_count; i++) {
6340                         vd = spa->spa_spares.sav_vdevs[i];
6341                         if (vd->vdev_guid == guid)
6342                                 return (vd);
6343                 }
6344         }
6345 
6346         return (NULL);
6347 }
6348 
6349 void
6350 spa_upgrade(spa_t *spa, uint64_t version)
6351 {
6352         ASSERT(spa_writeable(spa));
6353 
6354         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6355 
6356         /*
6357          * This should only be called for a non-faulted pool, and since a
6358          * future version would result in an unopenable pool, this shouldn't be
6359          * possible.
6360          */
6361         ASSERT(SPA_VERSION_IS_SUPPORTED(spa->spa_uberblock.ub_version));
6362         ASSERT(version >= spa->spa_uberblock.ub_version);
6363 
6364         spa->spa_uberblock.ub_version = version;
6365         vdev_config_dirty(spa->spa_root_vdev);
6366 
6367         spa_config_exit(spa, SCL_ALL, FTAG);
6368 
6369         txg_wait_synced(spa_get_dsl(spa), 0);
6370 }
6371 
6372 boolean_t
6373 spa_has_spare(spa_t *spa, uint64_t guid)
6374 {
6375         int i;
6376         uint64_t spareguid;
6377         spa_aux_vdev_t *sav = &spa->spa_spares;
6378 
6379         for (i = 0; i < sav->sav_count; i++)
6380                 if (sav->sav_vdevs[i]->vdev_guid == guid)
6381                         return (B_TRUE);
6382 
6383         for (i = 0; i < sav->sav_npending; i++) {
6384                 if (nvlist_lookup_uint64(sav->sav_pending[i], ZPOOL_CONFIG_GUID,
6385                     &spareguid) == 0 && spareguid == guid)
6386                         return (B_TRUE);
6387         }
6388 
6389         return (B_FALSE);
6390 }
6391 
6392 /*
6393  * Check if a pool has an active shared spare device.
6394  * Note: reference count of an active spare is 2, as a spare and as a replace
6395  */
6396 static boolean_t
6397 spa_has_active_shared_spare(spa_t *spa)
6398 {
6399         int i, refcnt;
6400         uint64_t pool;
6401         spa_aux_vdev_t *sav = &spa->spa_spares;
6402 
6403         for (i = 0; i < sav->sav_count; i++) {
6404                 if (spa_spare_exists(sav->sav_vdevs[i]->vdev_guid, &pool,
6405                     &refcnt) && pool != 0ULL && pool == spa_guid(spa) &&
6406                     refcnt > 2)
6407                         return (B_TRUE);
6408         }
6409 
6410         return (B_FALSE);
6411 }
6412 
6413 /*
6414  * Post a sysevent corresponding to the given event.  The 'name' must be one of
6415  * the event definitions in sys/sysevent/eventdefs.h.  The payload will be
6416  * filled in from the spa and (optionally) the vdev.  This doesn't do anything
6417  * in the userland libzpool, as we don't want consumers to misinterpret ztest
6418  * or zdb as real changes.
6419  */
6420 void
6421 spa_event_notify(spa_t *spa, vdev_t *vd, const char *name)
6422 {
6423 #ifdef _KERNEL
6424         sysevent_t              *ev;
6425         sysevent_attr_list_t    *attr = NULL;
6426         sysevent_value_t        value;
6427         sysevent_id_t           eid;
6428 
6429         ev = sysevent_alloc(EC_ZFS, (char *)name, SUNW_KERN_PUB "zfs",
6430             SE_SLEEP);
6431 
6432         value.value_type = SE_DATA_TYPE_STRING;
6433         value.value.sv_string = spa_name(spa);
6434         if (sysevent_add_attr(&attr, ZFS_EV_POOL_NAME, &value, SE_SLEEP) != 0)
6435                 goto done;
6436 
6437         value.value_type = SE_DATA_TYPE_UINT64;
6438         value.value.sv_uint64 = spa_guid(spa);
6439         if (sysevent_add_attr(&attr, ZFS_EV_POOL_GUID, &value, SE_SLEEP) != 0)
6440                 goto done;
6441 
6442         if (vd) {
6443                 value.value_type = SE_DATA_TYPE_UINT64;
6444                 value.value.sv_uint64 = vd->vdev_guid;
6445                 if (sysevent_add_attr(&attr, ZFS_EV_VDEV_GUID, &value,
6446                     SE_SLEEP) != 0)
6447                         goto done;
6448 
6449                 if (vd->vdev_path) {
6450                         value.value_type = SE_DATA_TYPE_STRING;
6451                         value.value.sv_string = vd->vdev_path;
6452                         if (sysevent_add_attr(&attr, ZFS_EV_VDEV_PATH,
6453                             &value, SE_SLEEP) != 0)
6454                                 goto done;
6455                 }
6456         }
6457 
6458         if (sysevent_attach_attributes(ev, attr) != 0)
6459                 goto done;
6460         attr = NULL;
6461 
6462         (void) log_sysevent(ev, SE_SLEEP, &eid);
6463 
6464 done:
6465         if (attr)
6466                 sysevent_free_attr(attr);
6467         sysevent_free(ev);
6468 #endif
6469 }