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) 2012, 2015 by Delphix. All rights reserved.
  25  * Copyright 2016 Nexenta Systems, Inc.  All rights reserved.
  26  */
  27 
  28 /*
  29  * Virtual Device Labels
  30  * ---------------------
  31  *
  32  * The vdev label serves several distinct purposes:
  33  *
  34  *      1. Uniquely identify this device as part of a ZFS pool and confirm its
  35  *         identity within the pool.
  36  *
  37  *      2. Verify that all the devices given in a configuration are present
  38  *         within the pool.
  39  *
  40  *      3. Determine the uberblock for the pool.
  41  *
  42  *      4. In case of an import operation, determine the configuration of the
  43  *         toplevel vdev of which it is a part.
  44  *
  45  *      5. If an import operation cannot find all the devices in the pool,
  46  *         provide enough information to the administrator to determine which
  47  *         devices are missing.
  48  *
  49  * It is important to note that while the kernel is responsible for writing the
  50  * label, it only consumes the information in the first three cases.  The
  51  * latter information is only consumed in userland when determining the
  52  * configuration to import a pool.
  53  *
  54  *
  55  * Label Organization
  56  * ------------------
  57  *
  58  * Before describing the contents of the label, it's important to understand how
  59  * the labels are written and updated with respect to the uberblock.
  60  *
  61  * When the pool configuration is altered, either because it was newly created
  62  * or a device was added, we want to update all the labels such that we can deal
  63  * with fatal failure at any point.  To this end, each disk has two labels which
  64  * are updated before and after the uberblock is synced.  Assuming we have
  65  * labels and an uberblock with the following transaction groups:
  66  *
  67  *              L1          UB          L2
  68  *           +------+    +------+    +------+
  69  *           |      |    |      |    |      |
  70  *           | t10  |    | t10  |    | t10  |
  71  *           |      |    |      |    |      |
  72  *           +------+    +------+    +------+
  73  *
  74  * In this stable state, the labels and the uberblock were all updated within
  75  * the same transaction group (10).  Each label is mirrored and checksummed, so
  76  * that we can detect when we fail partway through writing the label.
  77  *
  78  * In order to identify which labels are valid, the labels are written in the
  79  * following manner:
  80  *
  81  *      1. For each vdev, update 'L1' to the new label
  82  *      2. Update the uberblock
  83  *      3. For each vdev, update 'L2' to the new label
  84  *
  85  * Given arbitrary failure, we can determine the correct label to use based on
  86  * the transaction group.  If we fail after updating L1 but before updating the
  87  * UB, we will notice that L1's transaction group is greater than the uberblock,
  88  * so L2 must be valid.  If we fail after writing the uberblock but before
  89  * writing L2, we will notice that L2's transaction group is less than L1, and
  90  * therefore L1 is valid.
  91  *
  92  * Another added complexity is that not every label is updated when the config
  93  * is synced.  If we add a single device, we do not want to have to re-write
  94  * every label for every device in the pool.  This means that both L1 and L2 may
  95  * be older than the pool uberblock, because the necessary information is stored
  96  * on another vdev.
  97  *
  98  *
  99  * On-disk Format
 100  * --------------
 101  *
 102  * The vdev label consists of two distinct parts, and is wrapped within the
 103  * vdev_label_t structure.  The label includes 8k of padding to permit legacy
 104  * VTOC disk labels, but is otherwise ignored.
 105  *
 106  * The first half of the label is a packed nvlist which contains pool wide
 107  * properties, per-vdev properties, and configuration information.  It is
 108  * described in more detail below.
 109  *
 110  * The latter half of the label consists of a redundant array of uberblocks.
 111  * These uberblocks are updated whenever a transaction group is committed,
 112  * or when the configuration is updated.  When a pool is loaded, we scan each
 113  * vdev for the 'best' uberblock.
 114  *
 115  *
 116  * Configuration Information
 117  * -------------------------
 118  *
 119  * The nvlist describing the pool and vdev contains the following elements:
 120  *
 121  *      version         ZFS on-disk version
 122  *      name            Pool name
 123  *      state           Pool state
 124  *      txg             Transaction group in which this label was written
 125  *      pool_guid       Unique identifier for this pool
 126  *      vdev_tree       An nvlist describing vdev tree.
 127  *      features_for_read
 128  *                      An nvlist of the features necessary for reading the MOS.
 129  *
 130  * Each leaf device label also contains the following:
 131  *
 132  *      top_guid        Unique ID for top-level vdev in which this is contained
 133  *      guid            Unique ID for the leaf vdev
 134  *
 135  * The 'vs' configuration follows the format described in 'spa_config.c'.
 136  */
 137 
 138 #include <sys/zfs_context.h>
 139 #include <sys/spa.h>
 140 #include <sys/spa_impl.h>
 141 #include <sys/dmu.h>
 142 #include <sys/zap.h>
 143 #include <sys/vdev.h>
 144 #include <sys/vdev_impl.h>
 145 #include <sys/uberblock_impl.h>
 146 #include <sys/metaslab.h>
 147 #include <sys/zio.h>
 148 #include <sys/dsl_scan.h>
 149 #include <sys/abd.h>
 150 #include <sys/fs/zfs.h>
 151 
 152 /*
 153  * Basic routines to read and write from a vdev label.
 154  * Used throughout the rest of this file.
 155  */
 156 uint64_t
 157 vdev_label_offset(uint64_t psize, int l, uint64_t offset)
 158 {
 159         ASSERT(offset < sizeof (vdev_label_t));
 160         ASSERT(P2PHASE_TYPED(psize, sizeof (vdev_label_t), uint64_t) == 0);
 161 
 162         return (offset + l * sizeof (vdev_label_t) + (l < VDEV_LABELS / 2 ?
 163             0 : psize - VDEV_LABELS * sizeof (vdev_label_t)));
 164 }
 165 
 166 /*
 167  * Returns back the vdev label associated with the passed in offset.
 168  */
 169 int
 170 vdev_label_number(uint64_t psize, uint64_t offset)
 171 {
 172         int l;
 173 
 174         if (offset >= psize - VDEV_LABEL_END_SIZE) {
 175                 offset -= psize - VDEV_LABEL_END_SIZE;
 176                 offset += (VDEV_LABELS / 2) * sizeof (vdev_label_t);
 177         }
 178         l = offset / sizeof (vdev_label_t);
 179         return (l < VDEV_LABELS ? l : -1);
 180 }
 181 
 182 static void
 183 vdev_label_read(zio_t *zio, vdev_t *vd, int l, abd_t *buf, uint64_t offset,
 184     uint64_t size, zio_done_func_t *done, void *private, int flags)
 185 {
 186         ASSERT(spa_config_held(zio->io_spa, SCL_STATE_ALL, RW_WRITER) ==
 187             SCL_STATE_ALL);
 188         ASSERT(flags & ZIO_FLAG_CONFIG_WRITER);
 189 
 190         zio_nowait(zio_read_phys(zio, vd,
 191             vdev_label_offset(vd->vdev_psize, l, offset),
 192             size, buf, ZIO_CHECKSUM_LABEL, done, private,
 193             ZIO_PRIORITY_SYNC_READ, flags, B_TRUE));
 194 }
 195 
 196 static void
 197 vdev_label_write(zio_t *zio, vdev_t *vd, int l, abd_t *buf, uint64_t offset,
 198     uint64_t size, zio_done_func_t *done, void *private, int flags)
 199 {
 200         ASSERT(spa_config_held(zio->io_spa, SCL_ALL, RW_WRITER) == SCL_ALL ||
 201             (spa_config_held(zio->io_spa, SCL_CONFIG | SCL_STATE, RW_READER) ==
 202             (SCL_CONFIG | SCL_STATE) &&
 203             dsl_pool_sync_context(spa_get_dsl(zio->io_spa))));
 204         ASSERT(flags & ZIO_FLAG_CONFIG_WRITER);
 205 
 206         zio_nowait(zio_write_phys(zio, vd,
 207             vdev_label_offset(vd->vdev_psize, l, offset),
 208             size, buf, ZIO_CHECKSUM_LABEL, done, private,
 209             ZIO_PRIORITY_SYNC_WRITE, flags, B_TRUE));
 210 }
 211 
 212 /*
 213  * Generate the nvlist representing this vdev's config.
 214  */
 215 nvlist_t *
 216 vdev_config_generate(spa_t *spa, vdev_t *vd, boolean_t getstats,
 217     vdev_config_flag_t flags)
 218 {
 219         nvlist_t *nv = NULL;
 220 
 221         nv = fnvlist_alloc();
 222 
 223         fnvlist_add_string(nv, ZPOOL_CONFIG_TYPE, vd->vdev_ops->vdev_op_type);
 224         if (!(flags & (VDEV_CONFIG_SPARE | VDEV_CONFIG_L2CACHE)))
 225                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_ID, vd->vdev_id);
 226         fnvlist_add_uint64(nv, ZPOOL_CONFIG_GUID, vd->vdev_guid);
 227 
 228         if (vd->vdev_path != NULL)
 229                 fnvlist_add_string(nv, ZPOOL_CONFIG_PATH, vd->vdev_path);
 230 
 231         if (vd->vdev_devid != NULL)
 232                 fnvlist_add_string(nv, ZPOOL_CONFIG_DEVID, vd->vdev_devid);
 233 
 234         if (vd->vdev_physpath != NULL)
 235                 fnvlist_add_string(nv, ZPOOL_CONFIG_PHYS_PATH,
 236                     vd->vdev_physpath);
 237 
 238         if (vd->vdev_fru != NULL)
 239                 fnvlist_add_string(nv, ZPOOL_CONFIG_FRU, vd->vdev_fru);
 240 
 241         if (vd->vdev_nparity != 0) {
 242                 ASSERT(strcmp(vd->vdev_ops->vdev_op_type,
 243                     VDEV_TYPE_RAIDZ) == 0);
 244 
 245                 /*
 246                  * Make sure someone hasn't managed to sneak a fancy new vdev
 247                  * into a crufty old storage pool.
 248                  */
 249                 ASSERT(vd->vdev_nparity == 1 ||
 250                     (vd->vdev_nparity <= 2 &&
 251                     spa_version(spa) >= SPA_VERSION_RAIDZ2) ||
 252                     (vd->vdev_nparity <= 3 &&
 253                     spa_version(spa) >= SPA_VERSION_RAIDZ3));
 254 
 255                 /*
 256                  * Note that we'll add the nparity tag even on storage pools
 257                  * that only support a single parity device -- older software
 258                  * will just ignore it.
 259                  */
 260                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_NPARITY, vd->vdev_nparity);
 261         }
 262 
 263         if (vd->vdev_wholedisk != -1ULL)
 264                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
 265                     vd->vdev_wholedisk);
 266 
 267         if (vd->vdev_not_present)
 268                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT, 1);
 269 
 270         if (vd->vdev_isspare)
 271                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_IS_SPARE, 1);
 272 
 273         if (!(flags & (VDEV_CONFIG_SPARE | VDEV_CONFIG_L2CACHE)) &&
 274             vd == vd->vdev_top) {
 275                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_METASLAB_ARRAY,
 276                     vd->vdev_ms_array);
 277                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_METASLAB_SHIFT,
 278                     vd->vdev_ms_shift);
 279                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_ASHIFT, vd->vdev_ashift);
 280                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_ASIZE,
 281                     vd->vdev_asize);
 282                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_IS_LOG, vd->vdev_islog);
 283                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_IS_SPECIAL,
 284                     vd->vdev_isspecial);
 285                 if (vd->vdev_removing)
 286                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_REMOVING,
 287                             vd->vdev_removing);
 288         }
 289 
 290         if (flags & VDEV_CONFIG_L2CACHE)
 291                 /* indicate that we support L2ARC persistency */
 292                 VERIFY(nvlist_add_boolean_value(nv,
 293                     ZPOOL_CONFIG_L2CACHE_PERSISTENT, B_TRUE) == 0);
 294 
 295         fnvlist_add_boolean_value(nv, ZPOOL_CONFIG_IS_SSD, vd->vdev_is_ssd);
 296 
 297         if (vd->vdev_dtl_sm != NULL) {
 298                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_DTL,
 299                     space_map_object(vd->vdev_dtl_sm));
 300         }
 301 
 302         if (vd->vdev_crtxg)
 303                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_CREATE_TXG, vd->vdev_crtxg);
 304 
 305         if (flags & VDEV_CONFIG_MOS) {
 306                 if (vd->vdev_leaf_zap != 0) {
 307                         ASSERT(vd->vdev_ops->vdev_op_leaf);
 308                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_VDEV_LEAF_ZAP,
 309                             vd->vdev_leaf_zap);
 310                 }
 311 
 312                 if (vd->vdev_top_zap != 0) {
 313                         ASSERT(vd == vd->vdev_top);
 314                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_VDEV_TOP_ZAP,
 315                             vd->vdev_top_zap);
 316                 }
 317         }
 318 
 319         if (getstats) {
 320                 vdev_stat_t vs;
 321                 pool_scan_stat_t ps;
 322 
 323                 vdev_get_stats(vd, &vs);
 324                 fnvlist_add_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
 325                     (uint64_t *)&vs, sizeof (vs) / sizeof (uint64_t));
 326 
 327                 /* provide either current or previous scan information */
 328                 if (spa_scan_get_stats(spa, &ps) == 0) {
 329                         fnvlist_add_uint64_array(nv,
 330                             ZPOOL_CONFIG_SCAN_STATS, (uint64_t *)&ps,
 331                             sizeof (pool_scan_stat_t) / sizeof (uint64_t));
 332                 }
 333         }
 334 
 335         if (!vd->vdev_ops->vdev_op_leaf) {
 336                 nvlist_t **child;
 337                 int c, idx;
 338 
 339                 ASSERT(!vd->vdev_ishole);
 340 
 341                 child = kmem_alloc(vd->vdev_children * sizeof (nvlist_t *),
 342                     KM_SLEEP);
 343 
 344                 for (c = 0, idx = 0; c < vd->vdev_children; c++) {
 345                         vdev_t *cvd = vd->vdev_child[c];
 346 
 347                         /*
 348                          * If we're generating an nvlist of removing
 349                          * vdevs then skip over any device which is
 350                          * not being removed.
 351                          */
 352                         if ((flags & VDEV_CONFIG_REMOVING) &&
 353                             !cvd->vdev_removing)
 354                                 continue;
 355 
 356                         child[idx++] = vdev_config_generate(spa, cvd,
 357                             getstats, flags);
 358                 }
 359 
 360                 if (idx) {
 361                         fnvlist_add_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
 362                             child, idx);
 363                 }
 364 
 365                 for (c = 0; c < idx; c++)
 366                         nvlist_free(child[c]);
 367 
 368                 kmem_free(child, vd->vdev_children * sizeof (nvlist_t *));
 369 
 370         } else {
 371                 const char *aux = NULL;
 372 
 373                 if (vd->vdev_offline && !vd->vdev_tmpoffline)
 374                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_OFFLINE, B_TRUE);
 375                 if (vd->vdev_resilver_txg != 0)
 376                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_RESILVER_TXG,
 377                             vd->vdev_resilver_txg);
 378                 if (vd->vdev_faulted)
 379                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_FAULTED, B_TRUE);
 380                 if (vd->vdev_degraded)
 381                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_DEGRADED, B_TRUE);
 382                 if (vd->vdev_removed)
 383                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_REMOVED, B_TRUE);
 384                 if (vd->vdev_unspare)
 385                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_UNSPARE, B_TRUE);
 386                 if (vd->vdev_ishole)
 387                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_IS_HOLE, B_TRUE);
 388 
 389                 switch (vd->vdev_stat.vs_aux) {
 390                 case VDEV_AUX_ERR_EXCEEDED:
 391                         aux = "err_exceeded";
 392                         break;
 393 
 394                 case VDEV_AUX_EXTERNAL:
 395                         aux = "external";
 396                         break;
 397                 }
 398 
 399                 if (aux != NULL)
 400                         fnvlist_add_string(nv, ZPOOL_CONFIG_AUX_STATE, aux);
 401 
 402                 if (vd->vdev_splitting && vd->vdev_orig_guid != 0LL) {
 403                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_ORIG_GUID,
 404                             vd->vdev_orig_guid);
 405                 }
 406 
 407                 /* grab per-leaf-vdev trim stats */
 408                 if (getstats) {
 409                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_TRIM_PROG,
 410                             vd->vdev_trim_prog);
 411                 }
 412         }
 413 
 414         return (nv);
 415 }
 416 
 417 /*
 418  * Generate a view of the top-level vdevs.  If we currently have holes
 419  * in the namespace, then generate an array which contains a list of holey
 420  * vdevs.  Additionally, add the number of top-level children that currently
 421  * exist.
 422  */
 423 void
 424 vdev_top_config_generate(spa_t *spa, nvlist_t *config)
 425 {
 426         vdev_t *rvd = spa->spa_root_vdev;
 427         uint64_t *array;
 428         uint_t c, idx;
 429 
 430         array = kmem_alloc(rvd->vdev_children * sizeof (uint64_t), KM_SLEEP);
 431 
 432         for (c = 0, idx = 0; c < rvd->vdev_children; c++) {
 433                 vdev_t *tvd = rvd->vdev_child[c];
 434 
 435                 if (tvd->vdev_ishole)
 436                         array[idx++] = c;
 437         }
 438 
 439         if (idx) {
 440                 VERIFY(nvlist_add_uint64_array(config, ZPOOL_CONFIG_HOLE_ARRAY,
 441                     array, idx) == 0);
 442         }
 443 
 444         VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_VDEV_CHILDREN,
 445             rvd->vdev_children) == 0);
 446 
 447         kmem_free(array, rvd->vdev_children * sizeof (uint64_t));
 448 }
 449 
 450 /*
 451  * Returns the configuration from the label of the given vdev. For vdevs
 452  * which don't have a txg value stored on their label (i.e. spares/cache)
 453  * or have not been completely initialized (txg = 0) just return
 454  * the configuration from the first valid label we find. Otherwise,
 455  * find the most up-to-date label that does not exceed the specified
 456  * 'txg' value.
 457  */
 458 nvlist_t *
 459 vdev_label_read_config(vdev_t *vd, uint64_t txg)
 460 {
 461         spa_t *spa = vd->vdev_spa;
 462         nvlist_t *config = NULL;
 463         vdev_phys_t *vp;
 464         abd_t *vp_abd;
 465         zio_t *zio;
 466         uint64_t best_txg = 0;
 467         int error = 0;
 468         int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL |
 469             ZIO_FLAG_SPECULATIVE;
 470 
 471         ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
 472 
 473         if (!vdev_readable(vd))
 474                 return (NULL);
 475 
 476         vp_abd = abd_alloc_linear(sizeof (vdev_phys_t), B_TRUE);
 477         vp = abd_to_buf(vp_abd);
 478 
 479 retry:
 480         for (int l = 0; l < VDEV_LABELS; l++) {
 481                 nvlist_t *label = NULL;
 482 
 483                 zio = zio_root(spa, NULL, NULL, flags);
 484 
 485                 vdev_label_read(zio, vd, l, vp_abd,
 486                     offsetof(vdev_label_t, vl_vdev_phys),
 487                     sizeof (vdev_phys_t), NULL, NULL, flags);
 488 
 489                 if (zio_wait(zio) == 0 &&
 490                     nvlist_unpack(vp->vp_nvlist, sizeof (vp->vp_nvlist),
 491                     &label, 0) == 0) {
 492                         uint64_t label_txg = 0;
 493 
 494                         /*
 495                          * Auxiliary vdevs won't have txg values in their
 496                          * labels and newly added vdevs may not have been
 497                          * completely initialized so just return the
 498                          * configuration from the first valid label we
 499                          * encounter.
 500                          */
 501                         error = nvlist_lookup_uint64(label,
 502                             ZPOOL_CONFIG_POOL_TXG, &label_txg);
 503                         if ((error || label_txg == 0) && !config) {
 504                                 config = label;
 505                                 break;
 506                         } else if (label_txg <= txg && label_txg > best_txg) {
 507                                 best_txg = label_txg;
 508                                 nvlist_free(config);
 509                                 config = fnvlist_dup(label);
 510                         }
 511                 }
 512 
 513                 if (label != NULL) {
 514                         nvlist_free(label);
 515                         label = NULL;
 516                 }
 517         }
 518 
 519         if (config == NULL && !(flags & ZIO_FLAG_TRYHARD)) {
 520                 flags |= ZIO_FLAG_TRYHARD;
 521                 goto retry;
 522         }
 523 
 524         abd_free(vp_abd);
 525 
 526         return (config);
 527 }
 528 
 529 /*
 530  * Determine if a device is in use.  The 'spare_guid' parameter will be filled
 531  * in with the device guid if this spare is active elsewhere on the system.
 532  */
 533 static boolean_t
 534 vdev_inuse(vdev_t *vd, uint64_t crtxg, vdev_labeltype_t reason,
 535     uint64_t *spare_guid, uint64_t *l2cache_guid)
 536 {
 537         spa_t *spa = vd->vdev_spa;
 538         uint64_t state, pool_guid, device_guid, txg, spare_pool;
 539         uint64_t vdtxg = 0;
 540         nvlist_t *label;
 541 
 542         if (spare_guid)
 543                 *spare_guid = 0ULL;
 544         if (l2cache_guid)
 545                 *l2cache_guid = 0ULL;
 546 
 547         /*
 548          * Read the label, if any, and perform some basic sanity checks.
 549          */
 550         if ((label = vdev_label_read_config(vd, -1ULL)) == NULL)
 551                 return (B_FALSE);
 552 
 553         (void) nvlist_lookup_uint64(label, ZPOOL_CONFIG_CREATE_TXG,
 554             &vdtxg);
 555 
 556         if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE,
 557             &state) != 0 ||
 558             nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID,
 559             &device_guid) != 0) {
 560                 nvlist_free(label);
 561                 return (B_FALSE);
 562         }
 563 
 564         if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
 565             (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_GUID,
 566             &pool_guid) != 0 ||
 567             nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_TXG,
 568             &txg) != 0)) {
 569                 nvlist_free(label);
 570                 return (B_FALSE);
 571         }
 572 
 573         nvlist_free(label);
 574 
 575         /*
 576          * Check to see if this device indeed belongs to the pool it claims to
 577          * be a part of.  The only way this is allowed is if the device is a hot
 578          * spare (which we check for later on).
 579          */
 580         if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
 581             !spa_guid_exists(pool_guid, device_guid) &&
 582             !spa_spare_exists(device_guid, NULL, NULL) &&
 583             !spa_l2cache_exists(device_guid, NULL))
 584                 return (B_FALSE);
 585 
 586         /*
 587          * If the transaction group is zero, then this an initialized (but
 588          * unused) label.  This is only an error if the create transaction
 589          * on-disk is the same as the one we're using now, in which case the
 590          * user has attempted to add the same vdev multiple times in the same
 591          * transaction.
 592          */
 593         if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
 594             txg == 0 && vdtxg == crtxg)
 595                 return (B_TRUE);
 596 
 597         /*
 598          * Check to see if this is a spare device.  We do an explicit check for
 599          * spa_has_spare() here because it may be on our pending list of spares
 600          * to add.  We also check if it is an l2cache device.
 601          */
 602         if (spa_spare_exists(device_guid, &spare_pool, NULL) ||
 603             spa_has_spare(spa, device_guid)) {
 604                 if (spare_guid)
 605                         *spare_guid = device_guid;
 606 
 607                 switch (reason) {
 608                 case VDEV_LABEL_CREATE:
 609                 case VDEV_LABEL_L2CACHE:
 610                         return (B_TRUE);
 611 
 612                 case VDEV_LABEL_REPLACE:
 613                         return (!spa_has_spare(spa, device_guid) ||
 614                             spare_pool != 0ULL);
 615 
 616                 case VDEV_LABEL_SPARE:
 617                         return (spa_has_spare(spa, device_guid));
 618                 }
 619         }
 620 
 621         /*
 622          * Check to see if this is an l2cache device.
 623          */
 624         if (spa_l2cache_exists(device_guid, NULL))
 625                 return (B_TRUE);
 626 
 627         /*
 628          * We can't rely on a pool's state if it's been imported
 629          * read-only.  Instead we look to see if the pools is marked
 630          * read-only in the namespace and set the state to active.
 631          */
 632         if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
 633             (spa = spa_by_guid(pool_guid, device_guid)) != NULL &&
 634             spa_mode(spa) == FREAD)
 635                 state = POOL_STATE_ACTIVE;
 636 
 637         /*
 638          * If the device is marked ACTIVE, then this device is in use by another
 639          * pool on the system.
 640          */
 641         return (state == POOL_STATE_ACTIVE);
 642 }
 643 
 644 /*
 645  * Initialize a vdev label.  We check to make sure each leaf device is not in
 646  * use, and writable.  We put down an initial label which we will later
 647  * overwrite with a complete label.  Note that it's important to do this
 648  * sequentially, not in parallel, so that we catch cases of multiple use of the
 649  * same leaf vdev in the vdev we're creating -- e.g. mirroring a disk with
 650  * itself.
 651  */
 652 int
 653 vdev_label_init(vdev_t *vd, uint64_t crtxg, vdev_labeltype_t reason)
 654 {
 655         spa_t *spa = vd->vdev_spa;
 656         nvlist_t *label;
 657         vdev_phys_t *vp;
 658         abd_t *vp_abd;
 659         abd_t *pad2;
 660         uberblock_t *ub;
 661         abd_t *ub_abd;
 662         zio_t *zio;
 663         char *buf;
 664         size_t buflen;
 665         int error;
 666         uint64_t spare_guid, l2cache_guid;
 667         int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL;
 668 
 669         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
 670 
 671         for (int c = 0; c < vd->vdev_children; c++)
 672                 if ((error = vdev_label_init(vd->vdev_child[c],
 673                     crtxg, reason)) != 0)
 674                         return (error);
 675 
 676         /* Track the creation time for this vdev */
 677         vd->vdev_crtxg = crtxg;
 678 
 679         if (!vd->vdev_ops->vdev_op_leaf || !spa_writeable(spa))
 680                 return (0);
 681 
 682         /*
 683          * Dead vdevs cannot be initialized.
 684          */
 685         if (vdev_is_dead(vd))
 686                 return (SET_ERROR(EIO));
 687 
 688         /*
 689          * Determine if the vdev is in use.
 690          */
 691         if (reason != VDEV_LABEL_REMOVE && reason != VDEV_LABEL_SPLIT &&
 692             vdev_inuse(vd, crtxg, reason, &spare_guid, &l2cache_guid))
 693                 return (SET_ERROR(EBUSY));
 694 
 695         /*
 696          * If this is a request to add or replace a spare or l2cache device
 697          * that is in use elsewhere on the system, then we must update the
 698          * guid (which was initialized to a random value) to reflect the
 699          * actual GUID (which is shared between multiple pools).
 700          */
 701         if (reason != VDEV_LABEL_REMOVE && reason != VDEV_LABEL_L2CACHE &&
 702             spare_guid != 0ULL) {
 703                 uint64_t guid_delta = spare_guid - vd->vdev_guid;
 704 
 705                 vd->vdev_guid += guid_delta;
 706 
 707                 for (vdev_t *pvd = vd; pvd != NULL; pvd = pvd->vdev_parent)
 708                         pvd->vdev_guid_sum += guid_delta;
 709 
 710                 /*
 711                  * If this is a replacement, then we want to fallthrough to the
 712                  * rest of the code.  If we're adding a spare, then it's already
 713                  * labeled appropriately and we can just return.
 714                  */
 715                 if (reason == VDEV_LABEL_SPARE)
 716                         return (0);
 717                 ASSERT(reason == VDEV_LABEL_REPLACE ||
 718                     reason == VDEV_LABEL_SPLIT);
 719         }
 720 
 721         if (reason != VDEV_LABEL_REMOVE && reason != VDEV_LABEL_SPARE &&
 722             l2cache_guid != 0ULL) {
 723                 uint64_t guid_delta = l2cache_guid - vd->vdev_guid;
 724 
 725                 vd->vdev_guid += guid_delta;
 726 
 727                 for (vdev_t *pvd = vd; pvd != NULL; pvd = pvd->vdev_parent)
 728                         pvd->vdev_guid_sum += guid_delta;
 729 
 730                 /*
 731                  * If this is a replacement, then we want to fallthrough to the
 732                  * rest of the code.  If we're adding an l2cache, then it's
 733                  * already labeled appropriately and we can just return.
 734                  */
 735                 if (reason == VDEV_LABEL_L2CACHE)
 736                         return (0);
 737                 ASSERT(reason == VDEV_LABEL_REPLACE);
 738         }
 739 
 740         /*
 741          * Initialize its label.
 742          */
 743         vp_abd = abd_alloc_linear(sizeof (vdev_phys_t), B_TRUE);
 744         abd_zero(vp_abd, sizeof (vdev_phys_t));
 745         vp = abd_to_buf(vp_abd);
 746 
 747         /*
 748          * Generate a label describing the pool and our top-level vdev.
 749          * We mark it as being from txg 0 to indicate that it's not
 750          * really part of an active pool just yet.  The labels will
 751          * be written again with a meaningful txg by spa_sync().
 752          */
 753         if (reason == VDEV_LABEL_SPARE ||
 754             (reason == VDEV_LABEL_REMOVE && vd->vdev_isspare)) {
 755                 /*
 756                  * For inactive hot spares, we generate a special label that
 757                  * identifies as a mutually shared hot spare.  We write the
 758                  * label if we are adding a hot spare, or if we are removing an
 759                  * active hot spare (in which case we want to revert the
 760                  * labels).
 761                  */
 762                 VERIFY(nvlist_alloc(&label, NV_UNIQUE_NAME, KM_SLEEP) == 0);
 763 
 764                 VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_VERSION,
 765                     spa_version(spa)) == 0);
 766                 VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_POOL_STATE,
 767                     POOL_STATE_SPARE) == 0);
 768                 VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_GUID,
 769                     vd->vdev_guid) == 0);
 770         } else if (reason == VDEV_LABEL_L2CACHE ||
 771             (reason == VDEV_LABEL_REMOVE && vd->vdev_isl2cache)) {
 772                 /*
 773                  * For level 2 ARC devices, add a special label.
 774                  */
 775                 VERIFY(nvlist_alloc(&label, NV_UNIQUE_NAME, KM_SLEEP) == 0);
 776 
 777                 VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_VERSION,
 778                     spa_version(spa)) == 0);
 779                 VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_POOL_STATE,
 780                     POOL_STATE_L2CACHE) == 0);
 781                 VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_GUID,
 782                     vd->vdev_guid) == 0);
 783         } else {
 784                 uint64_t txg = 0ULL;
 785 
 786                 if (reason == VDEV_LABEL_SPLIT)
 787                         txg = spa->spa_uberblock.ub_txg;
 788                 label = spa_config_generate(spa, vd, txg, B_FALSE);
 789 
 790                 /*
 791                  * Add our creation time.  This allows us to detect multiple
 792                  * vdev uses as described above, and automatically expires if we
 793                  * fail.
 794                  */
 795                 VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_CREATE_TXG,
 796                     crtxg) == 0);
 797         }
 798 
 799         buf = vp->vp_nvlist;
 800         buflen = sizeof (vp->vp_nvlist);
 801 
 802         error = nvlist_pack(label, &buf, &buflen, NV_ENCODE_XDR, KM_SLEEP);
 803         if (error != 0) {
 804                 nvlist_free(label);
 805                 abd_free(vp_abd);
 806                 /* EFAULT means nvlist_pack ran out of room */
 807                 return (error == EFAULT ? ENAMETOOLONG : EINVAL);
 808         }
 809 
 810         /*
 811          * Initialize uberblock template.
 812          */
 813         ub_abd = abd_alloc_linear(VDEV_UBERBLOCK_RING, B_TRUE);
 814         abd_zero(ub_abd, VDEV_UBERBLOCK_RING);
 815         abd_copy_from_buf(ub_abd, &spa->spa_uberblock, sizeof (uberblock_t));
 816         ub = abd_to_buf(ub_abd);
 817         ub->ub_txg = 0;
 818 
 819         /* Initialize the 2nd padding area. */
 820         pad2 = abd_alloc_for_io(VDEV_PAD_SIZE, B_TRUE);
 821         abd_zero(pad2, VDEV_PAD_SIZE);
 822 
 823         /*
 824          * Write everything in parallel.
 825          */
 826 retry:
 827         zio = zio_root(spa, NULL, NULL, flags);
 828 
 829         for (int l = 0; l < VDEV_LABELS; l++) {
 830 
 831                 vdev_label_write(zio, vd, l, vp_abd,
 832                     offsetof(vdev_label_t, vl_vdev_phys),
 833                     sizeof (vdev_phys_t), NULL, NULL, flags);
 834 
 835                 /*
 836                  * Skip the 1st padding area.
 837                  * Zero out the 2nd padding area where it might have
 838                  * left over data from previous filesystem format.
 839                  */
 840                 vdev_label_write(zio, vd, l, pad2,
 841                     offsetof(vdev_label_t, vl_pad2),
 842                     VDEV_PAD_SIZE, NULL, NULL, flags);
 843 
 844                 vdev_label_write(zio, vd, l, ub_abd,
 845                     offsetof(vdev_label_t, vl_uberblock),
 846                     VDEV_UBERBLOCK_RING, NULL, NULL, flags);
 847         }
 848 
 849         error = zio_wait(zio);
 850 
 851         if (error != 0 && !(flags & ZIO_FLAG_TRYHARD)) {
 852                 flags |= ZIO_FLAG_TRYHARD;
 853                 goto retry;
 854         }
 855 
 856         nvlist_free(label);
 857         abd_free(pad2);
 858         abd_free(ub_abd);
 859         abd_free(vp_abd);
 860 
 861         /*
 862          * If this vdev hasn't been previously identified as a spare, then we
 863          * mark it as such only if a) we are labeling it as a spare, or b) it
 864          * exists as a spare elsewhere in the system.  Do the same for
 865          * level 2 ARC devices.
 866          */
 867         if (error == 0 && !vd->vdev_isspare &&
 868             (reason == VDEV_LABEL_SPARE ||
 869             spa_spare_exists(vd->vdev_guid, NULL, NULL)))
 870                 spa_spare_add(vd);
 871 
 872         if (error == 0 && !vd->vdev_isl2cache &&
 873             (reason == VDEV_LABEL_L2CACHE ||
 874             spa_l2cache_exists(vd->vdev_guid, NULL)))
 875                 spa_l2cache_add(vd);
 876 
 877         return (error);
 878 }
 879 
 880 /*
 881  * ==========================================================================
 882  * uberblock load/sync
 883  * ==========================================================================
 884  */
 885 
 886 /*
 887  * Consider the following situation: txg is safely synced to disk.  We've
 888  * written the first uberblock for txg + 1, and then we lose power.  When we
 889  * come back up, we fail to see the uberblock for txg + 1 because, say,
 890  * it was on a mirrored device and the replica to which we wrote txg + 1
 891  * is now offline.  If we then make some changes and sync txg + 1, and then
 892  * the missing replica comes back, then for a few seconds we'll have two
 893  * conflicting uberblocks on disk with the same txg.  The solution is simple:
 894  * among uberblocks with equal txg, choose the one with the latest timestamp.
 895  */
 896 static int
 897 vdev_uberblock_compare(uberblock_t *ub1, uberblock_t *ub2)
 898 {
 899         if (ub1->ub_txg < ub2->ub_txg)
 900                 return (-1);
 901         if (ub1->ub_txg > ub2->ub_txg)
 902                 return (1);
 903 
 904         if (ub1->ub_timestamp < ub2->ub_timestamp)
 905                 return (-1);
 906         if (ub1->ub_timestamp > ub2->ub_timestamp)
 907                 return (1);
 908 
 909         return (0);
 910 }
 911 
 912 struct ubl_cbdata {
 913         uberblock_t     *ubl_ubbest;    /* Best uberblock */
 914         vdev_t          *ubl_vd;        /* vdev associated with the above */
 915 };
 916 
 917 static void
 918 vdev_uberblock_load_done(zio_t *zio)
 919 {
 920         vdev_t *vd = zio->io_vd;
 921         spa_t *spa = zio->io_spa;
 922         zio_t *rio = zio->io_private;
 923         uberblock_t *ub = abd_to_buf(zio->io_abd);
 924         struct ubl_cbdata *cbp = rio->io_private;
 925 
 926         ASSERT3U(zio->io_size, ==, VDEV_UBERBLOCK_SIZE(vd));
 927 
 928         if (zio->io_error == 0 && uberblock_verify(ub) == 0) {
 929                 mutex_enter(&rio->io_lock);
 930                 if (ub->ub_txg <= spa->spa_load_max_txg &&
 931                     vdev_uberblock_compare(ub, cbp->ubl_ubbest) > 0) {
 932                         /*
 933                          * Keep track of the vdev in which this uberblock
 934                          * was found. We will use this information later
 935                          * to obtain the config nvlist associated with
 936                          * this uberblock.
 937                          */
 938                         *cbp->ubl_ubbest = *ub;
 939                         cbp->ubl_vd = vd;
 940                 }
 941                 mutex_exit(&rio->io_lock);
 942         }
 943 
 944         abd_free(zio->io_abd);
 945 }
 946 
 947 static void
 948 vdev_uberblock_load_impl(zio_t *zio, vdev_t *vd, int flags,
 949     struct ubl_cbdata *cbp)
 950 {
 951         for (int c = 0; c < vd->vdev_children; c++)
 952                 vdev_uberblock_load_impl(zio, vd->vdev_child[c], flags, cbp);
 953 
 954         if (vd->vdev_ops->vdev_op_leaf && vdev_readable(vd)) {
 955                 for (int l = 0; l < VDEV_LABELS; l++) {
 956                         for (int n = 0; n < VDEV_UBERBLOCK_COUNT(vd); n++) {
 957                                 vdev_label_read(zio, vd, l,
 958                                     abd_alloc_linear(VDEV_UBERBLOCK_SIZE(vd),
 959                                     B_TRUE), VDEV_UBERBLOCK_OFFSET(vd, n),
 960                                     VDEV_UBERBLOCK_SIZE(vd),
 961                                     vdev_uberblock_load_done, zio, flags);
 962                         }
 963                 }
 964         }
 965 }
 966 
 967 /*
 968  * Reads the 'best' uberblock from disk along with its associated
 969  * configuration. First, we read the uberblock array of each label of each
 970  * vdev, keeping track of the uberblock with the highest txg in each array.
 971  * Then, we read the configuration from the same vdev as the best uberblock.
 972  */
 973 void
 974 vdev_uberblock_load(vdev_t *rvd, uberblock_t *ub, nvlist_t **config)
 975 {
 976         zio_t *zio;
 977         spa_t *spa = rvd->vdev_spa;
 978         struct ubl_cbdata cb;
 979         int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL |
 980             ZIO_FLAG_SPECULATIVE | ZIO_FLAG_TRYHARD;
 981 
 982         ASSERT(ub);
 983         ASSERT(config);
 984 
 985         bzero(ub, sizeof (uberblock_t));
 986         *config = NULL;
 987 
 988         cb.ubl_ubbest = ub;
 989         cb.ubl_vd = NULL;
 990 
 991         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
 992         zio = zio_root(spa, NULL, &cb, flags);
 993         vdev_uberblock_load_impl(zio, rvd, flags, &cb);
 994         (void) zio_wait(zio);
 995 
 996         /*
 997          * It's possible that the best uberblock was discovered on a label
 998          * that has a configuration which was written in a future txg.
 999          * Search all labels on this vdev to find the configuration that
1000          * matches the txg for our uberblock.
1001          */
1002         if (cb.ubl_vd != NULL)
1003                 *config = vdev_label_read_config(cb.ubl_vd, ub->ub_txg);
1004         spa_config_exit(spa, SCL_ALL, FTAG);
1005 }
1006 
1007 /*
1008  * On success, increment root zio's count of good writes.
1009  * We only get credit for writes to known-visible vdevs; see spa_vdev_add().
1010  */
1011 static void
1012 vdev_uberblock_sync_done(zio_t *zio)
1013 {
1014         uint64_t *good_writes = zio->io_private;
1015 
1016         if (zio->io_error == 0 && zio->io_vd->vdev_top->vdev_ms_array != 0)
1017                 atomic_inc_64(good_writes);
1018 }
1019 
1020 /*
1021  * Write the uberblock to all labels of all leaves of the specified vdev.
1022  */
1023 static void
1024 vdev_uberblock_sync(zio_t *zio, uberblock_t *ub, vdev_t *vd, int flags)
1025 {
1026         for (int c = 0; c < vd->vdev_children; c++)
1027                 vdev_uberblock_sync(zio, ub, vd->vdev_child[c], flags);
1028 
1029         if (!vd->vdev_ops->vdev_op_leaf)
1030                 return;
1031 
1032         if (!vdev_writeable(vd))
1033                 return;
1034 
1035         int n = ub->ub_txg & (VDEV_UBERBLOCK_COUNT(vd) - 1);
1036 
1037         /* Copy the uberblock_t into the ABD */
1038         abd_t *ub_abd = abd_alloc_for_io(VDEV_UBERBLOCK_SIZE(vd), B_TRUE);
1039         abd_zero(ub_abd, VDEV_UBERBLOCK_SIZE(vd));
1040         abd_copy_from_buf(ub_abd, ub, sizeof (uberblock_t));
1041 
1042         for (int l = 0; l < VDEV_LABELS; l++)
1043                 vdev_label_write(zio, vd, l, ub_abd,
1044                     VDEV_UBERBLOCK_OFFSET(vd, n), VDEV_UBERBLOCK_SIZE(vd),
1045                     vdev_uberblock_sync_done, zio->io_private,
1046                     flags | ZIO_FLAG_DONT_PROPAGATE);
1047 
1048         abd_free(ub_abd);
1049 }
1050 
1051 /* Sync the uberblocks to all vdevs in svd[] */
1052 int
1053 vdev_uberblock_sync_list(vdev_t **svd, int svdcount, uberblock_t *ub, int flags)
1054 {
1055         spa_t *spa = svd[0]->vdev_spa;
1056         zio_t *zio;
1057         uint64_t good_writes = 0;
1058 
1059         zio = zio_root(spa, NULL, &good_writes, flags);
1060 
1061         for (int v = 0; v < svdcount; v++)
1062                 vdev_uberblock_sync(zio, ub, svd[v], flags);
1063 
1064         (void) zio_wait(zio);
1065 
1066         /*
1067          * Flush the uberblocks to disk.  This ensures that the odd labels
1068          * are no longer needed (because the new uberblocks and the even
1069          * labels are safely on disk), so it is safe to overwrite them.
1070          */
1071         zio = zio_root(spa, NULL, NULL, flags);
1072 
1073         for (int v = 0; v < svdcount; v++)
1074                 zio_flush(zio, svd[v]);
1075 
1076         (void) zio_wait(zio);
1077 
1078         return (good_writes >= 1 ? 0 : EIO);
1079 }
1080 
1081 /*
1082  * On success, increment the count of good writes for our top-level vdev.
1083  */
1084 static void
1085 vdev_label_sync_done(zio_t *zio)
1086 {
1087         uint64_t *good_writes = zio->io_private;
1088 
1089         if (zio->io_error == 0)
1090                 atomic_inc_64(good_writes);
1091 }
1092 
1093 /*
1094  * If there weren't enough good writes, indicate failure to the parent.
1095  */
1096 static void
1097 vdev_label_sync_top_done(zio_t *zio)
1098 {
1099         uint64_t *good_writes = zio->io_private;
1100 
1101         if (*good_writes == 0)
1102                 zio->io_error = SET_ERROR(EIO);
1103 
1104         kmem_free(good_writes, sizeof (uint64_t));
1105 }
1106 
1107 /*
1108  * We ignore errors for log and cache devices, simply free the private data.
1109  */
1110 static void
1111 vdev_label_sync_ignore_done(zio_t *zio)
1112 {
1113         kmem_free(zio->io_private, sizeof (uint64_t));
1114 }
1115 
1116 /*
1117  * Write all even or odd labels to all leaves of the specified vdev.
1118  */
1119 static void
1120 vdev_label_sync(zio_t *zio, vdev_t *vd, int l, uint64_t txg, int flags)
1121 {
1122         nvlist_t *label;
1123         vdev_phys_t *vp;
1124         abd_t *vp_abd;
1125         char *buf;
1126         size_t buflen;
1127 
1128         for (int c = 0; c < vd->vdev_children; c++)
1129                 vdev_label_sync(zio, vd->vdev_child[c], l, txg, flags);
1130 
1131         if (!vd->vdev_ops->vdev_op_leaf)
1132                 return;
1133 
1134         if (!vdev_writeable(vd))
1135                 return;
1136 
1137         /*
1138          * Generate a label describing the top-level config to which we belong.
1139          */
1140         label = spa_config_generate(vd->vdev_spa, vd, txg, B_FALSE);
1141 
1142         vp_abd = abd_alloc_linear(sizeof (vdev_phys_t), B_TRUE);
1143         abd_zero(vp_abd, sizeof (vdev_phys_t));
1144         vp = abd_to_buf(vp_abd);
1145 
1146         buf = vp->vp_nvlist;
1147         buflen = sizeof (vp->vp_nvlist);
1148 
1149         if (nvlist_pack(label, &buf, &buflen, NV_ENCODE_XDR, KM_SLEEP) == 0) {
1150                 for (; l < VDEV_LABELS; l += 2) {
1151                         vdev_label_write(zio, vd, l, vp_abd,
1152                             offsetof(vdev_label_t, vl_vdev_phys),
1153                             sizeof (vdev_phys_t),
1154                             vdev_label_sync_done, zio->io_private,
1155                             flags | ZIO_FLAG_DONT_PROPAGATE);
1156                 }
1157         }
1158 
1159         abd_free(vp_abd);
1160         nvlist_free(label);
1161 }
1162 
1163 int
1164 vdev_label_sync_list(spa_t *spa, int l, uint64_t txg, int flags)
1165 {
1166         list_t *dl = &spa->spa_config_dirty_list;
1167         vdev_t *vd;
1168         zio_t *zio;
1169         int error;
1170 
1171         /*
1172          * Write the new labels to disk.
1173          */
1174         zio = zio_root(spa, NULL, NULL, flags);
1175 
1176         for (vd = list_head(dl); vd != NULL; vd = list_next(dl, vd)) {
1177                 uint64_t *good_writes = kmem_zalloc(sizeof (uint64_t),
1178                     KM_SLEEP);
1179 
1180                 ASSERT(!vd->vdev_ishole);
1181 
1182                 zio_t *vio = zio_null(zio, spa, NULL,
1183                     (vd->vdev_islog || vd->vdev_aux != NULL) ?
1184                     vdev_label_sync_ignore_done : vdev_label_sync_top_done,
1185                     good_writes, flags);
1186                 vdev_label_sync(vio, vd, l, txg, flags);
1187                 zio_nowait(vio);
1188         }
1189 
1190         error = zio_wait(zio);
1191 
1192         /*
1193          * Flush the new labels to disk.
1194          */
1195         zio = zio_root(spa, NULL, NULL, flags);
1196 
1197         for (vd = list_head(dl); vd != NULL; vd = list_next(dl, vd))
1198                 zio_flush(zio, vd);
1199 
1200         (void) zio_wait(zio);
1201 
1202         return (error);
1203 }
1204 
1205 /*
1206  * Sync the uberblock and any changes to the vdev configuration.
1207  *
1208  * The order of operations is carefully crafted to ensure that
1209  * if the system panics or loses power at any time, the state on disk
1210  * is still transactionally consistent.  The in-line comments below
1211  * describe the failure semantics at each stage.
1212  *
1213  * Moreover, vdev_config_sync() is designed to be idempotent: if it fails
1214  * at any time, you can just call it again, and it will resume its work.
1215  */
1216 int
1217 vdev_config_sync(vdev_t **svd, int svdcount, uint64_t txg)
1218 {
1219         spa_t *spa = svd[0]->vdev_spa;
1220         uberblock_t *ub = &spa->spa_uberblock;
1221         vdev_t *vd;
1222         zio_t *zio;
1223         int error = 0;
1224         int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL;
1225 
1226 retry:
1227         /*
1228          * Normally, we don't want to try too hard to write every label and
1229          * uberblock.  If there is a flaky disk, we don't want the rest of the
1230          * sync process to block while we retry.  But if we can't write a
1231          * single label out, we should retry with ZIO_FLAG_TRYHARD before
1232          * bailing out and declaring the pool faulted.
1233          */
1234         if (error != 0) {
1235                 if ((flags & ZIO_FLAG_TRYHARD) != 0)
1236                         return (error);
1237                 flags |= ZIO_FLAG_TRYHARD;
1238         }
1239 
1240         ASSERT(ub->ub_txg <= txg);
1241 
1242         /*
1243          * If this isn't a resync due to I/O errors,
1244          * and nothing changed in this transaction group,
1245          * and the vdev configuration hasn't changed,
1246          * then there's nothing to do.
1247          */
1248         if (ub->ub_txg < txg &&
1249             uberblock_update(ub, spa->spa_root_vdev, txg) == B_FALSE &&
1250             list_is_empty(&spa->spa_config_dirty_list))
1251                 return (0);
1252 
1253         if (txg > spa_freeze_txg(spa))
1254                 return (0);
1255 
1256         ASSERT(txg <= spa->spa_final_txg);
1257 
1258         /*
1259          * Flush the write cache of every disk that's been written to
1260          * in this transaction group.  This ensures that all blocks
1261          * written in this txg will be committed to stable storage
1262          * before any uberblock that references them.
1263          */
1264         zio = zio_root(spa, NULL, NULL, flags);
1265 
1266         for (vd = txg_list_head(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)); vd;
1267             vd = txg_list_next(&spa->spa_vdev_txg_list, vd, TXG_CLEAN(txg)))
1268                 zio_flush(zio, vd);
1269 
1270         (void) zio_wait(zio);
1271 
1272         /*
1273          * Sync out the even labels (L0, L2) for every dirty vdev.  If the
1274          * system dies in the middle of this process, that's OK: all of the
1275          * even labels that made it to disk will be newer than any uberblock,
1276          * and will therefore be considered invalid.  The odd labels (L1, L3),
1277          * which have not yet been touched, will still be valid.  We flush
1278          * the new labels to disk to ensure that all even-label updates
1279          * are committed to stable storage before the uberblock update.
1280          */
1281         if ((error = vdev_label_sync_list(spa, 0, txg, flags)) != 0)
1282                 goto retry;
1283 
1284         /*
1285          * Sync the uberblocks to all vdevs in svd[].
1286          * If the system dies in the middle of this step, there are two cases
1287          * to consider, and the on-disk state is consistent either way:
1288          *
1289          * (1)  If none of the new uberblocks made it to disk, then the
1290          *      previous uberblock will be the newest, and the odd labels
1291          *      (which had not yet been touched) will be valid with respect
1292          *      to that uberblock.
1293          *
1294          * (2)  If one or more new uberblocks made it to disk, then they
1295          *      will be the newest, and the even labels (which had all
1296          *      been successfully committed) will be valid with respect
1297          *      to the new uberblocks.
1298          */
1299         if ((error = vdev_uberblock_sync_list(svd, svdcount, ub, flags)) != 0)
1300                 goto retry;
1301 
1302         /*
1303          * Sync out odd labels for every dirty vdev.  If the system dies
1304          * in the middle of this process, the even labels and the new
1305          * uberblocks will suffice to open the pool.  The next time
1306          * the pool is opened, the first thing we'll do -- before any
1307          * user data is modified -- is mark every vdev dirty so that
1308          * all labels will be brought up to date.  We flush the new labels
1309          * to disk to ensure that all odd-label updates are committed to
1310          * stable storage before the next transaction group begins.
1311          */
1312         if ((error = vdev_label_sync_list(spa, 1, txg, flags)) != 0)
1313                 goto retry;
1314 
1315         return (0);
1316 }