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