]> git.proxmox.com Git - mirror_zfs.git/blobdiff - module/zfs/vdev.c
Pool allocation classes
[mirror_zfs.git] / module / zfs / vdev.c
index 0dea0b4e456bf5742543a77d6384542df7df1475..dfe4443680227a46c683ae5063035950d66e0037 100644 (file)
 
 /*
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2011, 2015 by Delphix. All rights reserved.
+ * Copyright (c) 2011, 2018 by Delphix. All rights reserved.
  * Copyright 2017 Nexenta Systems, Inc.
  * Copyright (c) 2014 Integros [integros.com]
  * Copyright 2016 Toomas Soome <tsoome@me.com>
  * Copyright 2017 Joyent, Inc.
+ * Copyright (c) 2017, Intel Corporation.
  */
 
 #include <sys/zfs_context.h>
 #include <sys/zvol.h>
 #include <sys/zfs_ratelimit.h>
 
+/* target number of metaslabs per top-level vdev */
+int vdev_max_ms_count = 200;
+
+/* minimum number of metaslabs per top-level vdev */
+int vdev_min_ms_count = 16;
+
+/* practical upper limit of total metaslabs per top-level vdev */
+int vdev_ms_count_limit = 1ULL << 17;
+
+/* lower limit for metaslab size (512M) */
+int vdev_default_ms_shift = 29;
+
+/* upper limit for metaslab size (256G) */
+int vdev_max_ms_shift = 38;
+
+int vdev_validate_skip = B_FALSE;
+
 /*
- * When a vdev is added, it will be divided into approximately (but no
- * more than) this number of metaslabs.
+ * Since the DTL space map of a vdev is not expected to have a lot of
+ * entries, we default its block size to 4K.
  */
-int metaslabs_per_vdev = 200;
+int vdev_dtl_sm_blksz = (1 << 12);
 
 /*
  * Rate limit delay events to this many IO delays per second.
@@ -74,6 +92,86 @@ unsigned int zfs_checksums_per_second = 20;
  */
 int zfs_scan_ignore_errors = 0;
 
+/*
+ * vdev-wide space maps that have lots of entries written to them at
+ * the end of each transaction can benefit from a higher I/O bandwidth
+ * (e.g. vdev_obsolete_sm), thus we default their block size to 128K.
+ */
+int vdev_standard_sm_blksz = (1 << 17);
+
+/*PRINTFLIKE2*/
+void
+vdev_dbgmsg(vdev_t *vd, const char *fmt, ...)
+{
+       va_list adx;
+       char buf[256];
+
+       va_start(adx, fmt);
+       (void) vsnprintf(buf, sizeof (buf), fmt, adx);
+       va_end(adx);
+
+       if (vd->vdev_path != NULL) {
+               zfs_dbgmsg("%s vdev '%s': %s", vd->vdev_ops->vdev_op_type,
+                   vd->vdev_path, buf);
+       } else {
+               zfs_dbgmsg("%s-%llu vdev (guid %llu): %s",
+                   vd->vdev_ops->vdev_op_type,
+                   (u_longlong_t)vd->vdev_id,
+                   (u_longlong_t)vd->vdev_guid, buf);
+       }
+}
+
+void
+vdev_dbgmsg_print_tree(vdev_t *vd, int indent)
+{
+       char state[20];
+
+       if (vd->vdev_ishole || vd->vdev_ops == &vdev_missing_ops) {
+               zfs_dbgmsg("%*svdev %u: %s", indent, "", vd->vdev_id,
+                   vd->vdev_ops->vdev_op_type);
+               return;
+       }
+
+       switch (vd->vdev_state) {
+       case VDEV_STATE_UNKNOWN:
+               (void) snprintf(state, sizeof (state), "unknown");
+               break;
+       case VDEV_STATE_CLOSED:
+               (void) snprintf(state, sizeof (state), "closed");
+               break;
+       case VDEV_STATE_OFFLINE:
+               (void) snprintf(state, sizeof (state), "offline");
+               break;
+       case VDEV_STATE_REMOVED:
+               (void) snprintf(state, sizeof (state), "removed");
+               break;
+       case VDEV_STATE_CANT_OPEN:
+               (void) snprintf(state, sizeof (state), "can't open");
+               break;
+       case VDEV_STATE_FAULTED:
+               (void) snprintf(state, sizeof (state), "faulted");
+               break;
+       case VDEV_STATE_DEGRADED:
+               (void) snprintf(state, sizeof (state), "degraded");
+               break;
+       case VDEV_STATE_HEALTHY:
+               (void) snprintf(state, sizeof (state), "healthy");
+               break;
+       default:
+               (void) snprintf(state, sizeof (state), "<state %u>",
+                   (uint_t)vd->vdev_state);
+       }
+
+       zfs_dbgmsg("%*svdev %u: %s%s, guid: %llu, path: %s, %s", indent,
+           "", (int)vd->vdev_id, vd->vdev_ops->vdev_op_type,
+           vd->vdev_islog ? " (log)" : "",
+           (u_longlong_t)vd->vdev_guid,
+           vd->vdev_path ? vd->vdev_path : "N/A", state);
+
+       for (uint64_t i = 0; i < vd->vdev_children; i++)
+               vdev_dbgmsg_print_tree(vd->vdev_child[i], indent + 2);
+}
+
 /*
  * Virtual device management.
  */
@@ -107,6 +205,25 @@ vdev_getops(const char *type)
        return (ops);
 }
 
+/*
+ * Derive the enumerated alloction bias from string input.
+ * String origin is either the per-vdev zap or zpool(1M).
+ */
+static vdev_alloc_bias_t
+vdev_derive_alloc_bias(const char *bias)
+{
+       vdev_alloc_bias_t alloc_bias = VDEV_BIAS_NONE;
+
+       if (strcmp(bias, VDEV_ALLOC_BIAS_LOG) == 0)
+               alloc_bias = VDEV_BIAS_LOG;
+       else if (strcmp(bias, VDEV_ALLOC_BIAS_SPECIAL) == 0)
+               alloc_bias = VDEV_BIAS_SPECIAL;
+       else if (strcmp(bias, VDEV_ALLOC_BIAS_DEDUP) == 0)
+               alloc_bias = VDEV_BIAS_DEDUP;
+
+       return (alloc_bias);
+}
+
 /*
  * Default asize function: return the MAX of psize with the asize of
  * all children.  This is what's used by anything other than RAID-Z.
@@ -431,6 +548,8 @@ vdev_alloc(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent, uint_t id,
        vdev_indirect_config_t *vic;
        char *tmp = NULL;
        int rc;
+       vdev_alloc_bias_t alloc_bias = VDEV_BIAS_NONE;
+       boolean_t top_level = (parent && !parent->vdev_parent);
 
        ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
 
@@ -517,11 +636,32 @@ vdev_alloc(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent, uint_t id,
        }
        ASSERT(nparity != -1ULL);
 
+       /*
+        * If creating a top-level vdev, check for allocation classes input
+        */
+       if (top_level && alloctype == VDEV_ALLOC_ADD) {
+               char *bias;
+
+               if (nvlist_lookup_string(nv, ZPOOL_CONFIG_ALLOCATION_BIAS,
+                   &bias) == 0) {
+                       alloc_bias = vdev_derive_alloc_bias(bias);
+
+                       /* spa_vdev_add() expects feature to be enabled */
+                       if (spa->spa_load_state != SPA_LOAD_CREATE &&
+                           !spa_feature_is_enabled(spa,
+                           SPA_FEATURE_ALLOCATION_CLASSES)) {
+                               return (SET_ERROR(ENOTSUP));
+                       }
+               }
+       }
+
        vd = vdev_alloc_common(spa, id, guid, ops);
        vic = &vd->vdev_indirect_config;
 
        vd->vdev_islog = islog;
        vd->vdev_nparity = nparity;
+       if (top_level && alloc_bias != VDEV_BIAS_NONE)
+               vd->vdev_alloc_bias = alloc_bias;
 
        if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &vd->vdev_path) == 0)
                vd->vdev_path = spa_strdup(vd->vdev_path);
@@ -590,7 +730,7 @@ vdev_alloc(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent, uint_t id,
        /*
         * If we're a top-level vdev, try to load the allocation parameters.
         */
-       if (parent && !parent->vdev_parent &&
+       if (top_level &&
            (alloctype == VDEV_ALLOC_LOAD || alloctype == VDEV_ALLOC_SPLIT)) {
                (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_METASLAB_ARRAY,
                    &vd->vdev_ms_array);
@@ -606,13 +746,12 @@ vdev_alloc(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent, uint_t id,
                ASSERT0(vd->vdev_top_zap);
        }
 
-       if (parent && !parent->vdev_parent && alloctype != VDEV_ALLOC_ATTACH) {
+       if (top_level && alloctype != VDEV_ALLOC_ATTACH) {
                ASSERT(alloctype == VDEV_ALLOC_LOAD ||
                    alloctype == VDEV_ALLOC_ADD ||
                    alloctype == VDEV_ALLOC_SPLIT ||
                    alloctype == VDEV_ALLOC_ROOTPOOL);
-               vd->vdev_mg = metaslab_group_create(islog ?
-                   spa_log_class(spa) : spa_normal_class(spa), vd);
+               /* Note: metaslab_group_create() is now deferred */
        }
 
        if (vd->vdev_ops->vdev_op_leaf &&
@@ -679,6 +818,8 @@ vdev_alloc(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent, uint_t id,
                                    ZPOOL_CONFIG_AUX_STATE, &aux) == 0 &&
                                    strcmp(aux, "external") == 0)
                                        vd->vdev_label_aux = VDEV_AUX_EXTERNAL;
+                               else
+                                       vd->vdev_faulted = 0ULL;
                        }
                }
        }
@@ -849,6 +990,12 @@ vdev_top_transfer(vdev_t *svd, vdev_t *tvd)
        if (tvd->vdev_mg != NULL)
                tvd->vdev_mg->mg_vd = tvd;
 
+       tvd->vdev_checkpoint_sm = svd->vdev_checkpoint_sm;
+       svd->vdev_checkpoint_sm = NULL;
+
+       tvd->vdev_alloc_bias = svd->vdev_alloc_bias;
+       svd->vdev_alloc_bias = VDEV_BIAS_NONE;
+
        tvd->vdev_stat.vs_alloc = svd->vdev_stat.vs_alloc;
        tvd->vdev_stat.vs_space = svd->vdev_stat.vs_space;
        tvd->vdev_stat.vs_dspace = svd->vdev_stat.vs_dspace;
@@ -1011,6 +1158,55 @@ vdev_remove_parent(vdev_t *cvd)
        vdev_free(mvd);
 }
 
+static void
+vdev_metaslab_group_create(vdev_t *vd)
+{
+       spa_t *spa = vd->vdev_spa;
+
+       /*
+        * metaslab_group_create was delayed until allocation bias was available
+        */
+       if (vd->vdev_mg == NULL) {
+               metaslab_class_t *mc;
+
+               if (vd->vdev_islog && vd->vdev_alloc_bias == VDEV_BIAS_NONE)
+                       vd->vdev_alloc_bias = VDEV_BIAS_LOG;
+
+               ASSERT3U(vd->vdev_islog, ==,
+                   (vd->vdev_alloc_bias == VDEV_BIAS_LOG));
+
+               switch (vd->vdev_alloc_bias) {
+               case VDEV_BIAS_LOG:
+                       mc = spa_log_class(spa);
+                       break;
+               case VDEV_BIAS_SPECIAL:
+                       mc = spa_special_class(spa);
+                       break;
+               case VDEV_BIAS_DEDUP:
+                       mc = spa_dedup_class(spa);
+                       break;
+               default:
+                       mc = spa_normal_class(spa);
+               }
+
+               vd->vdev_mg = metaslab_group_create(mc, vd,
+                   spa->spa_alloc_count);
+
+               /*
+                * The spa ashift values currently only reflect the
+                * general vdev classes. Class destination is late
+                * binding so ashift checking had to wait until now
+                */
+               if (vd->vdev_top == vd && vd->vdev_ashift != 0 &&
+                   mc == spa_normal_class(spa) && vd->vdev_aux == NULL) {
+                       if (vd->vdev_ashift > spa->spa_max_ashift)
+                               spa->spa_max_ashift = vd->vdev_ashift;
+                       if (vd->vdev_ashift < spa->spa_min_ashift)
+                               spa->spa_min_ashift = vd->vdev_ashift;
+               }
+       }
+}
+
 int
 vdev_metaslab_init(vdev_t *vd, uint64_t txg)
 {
@@ -1021,6 +1217,7 @@ vdev_metaslab_init(vdev_t *vd, uint64_t txg)
        uint64_t newc = vd->vdev_asize >> vd->vdev_ms_shift;
        metaslab_t **mspp;
        int error;
+       boolean_t expanding = (oldc != 0);
 
        ASSERT(txg == 0 || spa_config_held(spa, SCL_ALLOC, RW_WRITER));
 
@@ -1036,14 +1233,13 @@ vdev_metaslab_init(vdev_t *vd, uint64_t txg)
 
        mspp = vmem_zalloc(newc * sizeof (*mspp), KM_SLEEP);
 
-       if (oldc != 0) {
+       if (expanding) {
                bcopy(vd->vdev_ms, mspp, oldc * sizeof (*mspp));
                vmem_free(vd->vdev_ms, oldc * sizeof (*mspp));
        }
 
        vd->vdev_ms = mspp;
        vd->vdev_ms_count = newc;
-
        for (m = oldc; m < newc; m++) {
                uint64_t object = 0;
 
@@ -1056,14 +1252,31 @@ vdev_metaslab_init(vdev_t *vd, uint64_t txg)
                        error = dmu_read(mos, vd->vdev_ms_array,
                            m * sizeof (uint64_t), sizeof (uint64_t), &object,
                            DMU_READ_PREFETCH);
-                       if (error)
+                       if (error != 0) {
+                               vdev_dbgmsg(vd, "unable to read the metaslab "
+                                   "array [error=%d]", error);
                                return (error);
+                       }
                }
 
+#ifndef _KERNEL
+               /*
+                * To accomodate zdb_leak_init() fake indirect
+                * metaslabs, we allocate a metaslab group for
+                * indirect vdevs which normally don't have one.
+                */
+               if (vd->vdev_mg == NULL) {
+                       ASSERT0(vdev_is_concrete(vd));
+                       vdev_metaslab_group_create(vd);
+               }
+#endif
                error = metaslab_init(vd->vdev_mg, m, object, txg,
                    &(vd->vdev_ms[m]));
-               if (error)
+               if (error != 0) {
+                       vdev_dbgmsg(vd, "metaslab_init failed [error=%d]",
+                           error);
                        return (error);
+               }
        }
 
        if (txg == 0)
@@ -1074,8 +1287,9 @@ vdev_metaslab_init(vdev_t *vd, uint64_t txg)
         * the metaslabs since we want to ensure that no new
         * allocations are performed on this device.
         */
-       if (oldc == 0 && !vd->vdev_removing)
+       if (!expanding && !vd->vdev_removing) {
                metaslab_group_activate(vd->vdev_mg);
+       }
 
        if (txg == 0)
                spa_config_exit(spa, SCL_ALLOC, FTAG);
@@ -1086,6 +1300,21 @@ vdev_metaslab_init(vdev_t *vd, uint64_t txg)
 void
 vdev_metaslab_fini(vdev_t *vd)
 {
+       if (vd->vdev_checkpoint_sm != NULL) {
+               ASSERT(spa_feature_is_active(vd->vdev_spa,
+                   SPA_FEATURE_POOL_CHECKPOINT));
+               space_map_close(vd->vdev_checkpoint_sm);
+               /*
+                * Even though we close the space map, we need to set its
+                * pointer to NULL. The reason is that vdev_metaslab_fini()
+                * may be called multiple times for certain operations
+                * (i.e. when destroying a pool) so we need to ensure that
+                * this clause never executes twice. This logic is similar
+                * to the one used for the vdev_ms clause below.
+                */
+               vd->vdev_checkpoint_sm = NULL;
+       }
+
        if (vd->vdev_ms != NULL) {
                uint64_t count = vd->vdev_ms_count;
 
@@ -1147,8 +1376,7 @@ vdev_probe_done(zio_t *zio)
                        zio->io_error = 0;
                } else {
                        ASSERT(zio->io_error != 0);
-                       zfs_dbgmsg("failed probe on vdev %llu",
-                           (longlong_t)vd->vdev_id);
+                       vdev_dbgmsg(vd, "failed probe");
                        zfs_ereport_post(FM_EREPORT_ZFS_PROBE_FAILURE,
                            spa, vd, NULL, NULL, 0, 0);
                        zio->io_error = SET_ERROR(ENXIO);
@@ -1397,8 +1625,13 @@ vdev_open(vdev_t *vd)
                    vd->vdev_stat.vs_aux != VDEV_AUX_OPEN_FAILED)
                        vd->vdev_removed = B_FALSE;
 
-               vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
-                   vd->vdev_stat.vs_aux);
+               if (vd->vdev_stat.vs_aux == VDEV_AUX_CHILDREN_OFFLINE) {
+                       vdev_set_state(vd, B_TRUE, VDEV_STATE_OFFLINE,
+                           vd->vdev_stat.vs_aux);
+               } else {
+                       vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
+                           vd->vdev_stat.vs_aux);
+               }
                return (error);
        }
 
@@ -1544,19 +1777,15 @@ vdev_open(vdev_t *vd)
                return (error);
        }
 
-       if (vd->vdev_top == vd && vd->vdev_ashift != 0 &&
-           !vd->vdev_isl2cache && !vd->vdev_islog) {
-               if (vd->vdev_ashift > spa->spa_max_ashift)
-                       spa->spa_max_ashift = vd->vdev_ashift;
-               if (vd->vdev_ashift < spa->spa_min_ashift)
-                       spa->spa_min_ashift = vd->vdev_ashift;
-       }
-
        /*
         * Track the min and max ashift values for normal data devices.
+        *
+        * DJB - TBD these should perhaps be tracked per allocation class
+        * (e.g. spa_min_ashift is used to round up post compression buffers)
         */
        if (vd->vdev_top == vd && vd->vdev_ashift != 0 &&
-           !vd->vdev_islog && vd->vdev_aux == NULL) {
+           vd->vdev_alloc_bias == VDEV_BIAS_NONE &&
+           vd->vdev_aux == NULL) {
                if (vd->vdev_ashift > spa->spa_max_ashift)
                        spa->spa_max_ashift = vd->vdev_ashift;
                if (vd->vdev_ashift < spa->spa_min_ashift)
@@ -1577,29 +1806,29 @@ vdev_open(vdev_t *vd)
 
 /*
  * Called once the vdevs are all opened, this routine validates the label
- * contents.  This needs to be done before vdev_load() so that we don't
+ * contents. This needs to be done before vdev_load() so that we don't
  * inadvertently do repair I/Os to the wrong device.
  *
- * If 'strict' is false ignore the spa guid check. This is necessary because
- * if the machine crashed during a re-guid the new guid might have been written
- * to all of the vdev labels, but not the cached config. The strict check
- * will be performed when the pool is opened again using the mos config.
- *
  * This function will only return failure if one of the vdevs indicates that it
  * has since been destroyed or exported.  This is only possible if
  * /etc/zfs/zpool.cache was readonly at the time.  Otherwise, the vdev state
  * will be updated but the function will return 0.
  */
 int
-vdev_validate(vdev_t *vd, boolean_t strict)
+vdev_validate(vdev_t *vd)
 {
        spa_t *spa = vd->vdev_spa;
        nvlist_t *label;
-       uint64_t guid = 0, top_guid;
+       uint64_t guid = 0, aux_guid = 0, top_guid;
        uint64_t state;
+       nvlist_t *nvl;
+       uint64_t txg;
 
-       for (int c = 0; c < vd->vdev_children; c++)
-               if (vdev_validate(vd->vdev_child[c], strict) != 0)
+       if (vdev_validate_skip)
+               return (0);
+
+       for (uint64_t c = 0; c < vd->vdev_children; c++)
+               if (vdev_validate(vd->vdev_child[c]) != 0)
                        return (SET_ERROR(EBADF));
 
        /*
@@ -1607,99 +1836,280 @@ vdev_validate(vdev_t *vd, boolean_t strict)
         * any further validation.  Otherwise, label I/O will fail and we will
         * overwrite the previous state.
         */
-       if (vd->vdev_ops->vdev_op_leaf && vdev_readable(vd)) {
-               uint64_t aux_guid = 0;
-               nvlist_t *nvl;
-               uint64_t txg = spa_last_synced_txg(spa) != 0 ?
-                   spa_last_synced_txg(spa) : -1ULL;
+       if (!vd->vdev_ops->vdev_op_leaf || !vdev_readable(vd))
+               return (0);
 
-               if ((label = vdev_label_read_config(vd, txg)) == NULL) {
-                       vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
-                           VDEV_AUX_BAD_LABEL);
-                       return (0);
-               }
+       /*
+        * If we are performing an extreme rewind, we allow for a label that
+        * was modified at a point after the current txg.
+        * If config lock is not held do not check for the txg. spa_sync could
+        * be updating the vdev's label before updating spa_last_synced_txg.
+        */
+       if (spa->spa_extreme_rewind || spa_last_synced_txg(spa) == 0 ||
+           spa_config_held(spa, SCL_CONFIG, RW_WRITER) != SCL_CONFIG)
+               txg = UINT64_MAX;
+       else
+               txg = spa_last_synced_txg(spa);
 
-               /*
-                * Determine if this vdev has been split off into another
-                * pool.  If so, then refuse to open it.
-                */
-               if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_SPLIT_GUID,
-                   &aux_guid) == 0 && aux_guid == spa_guid(spa)) {
-                       vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
-                           VDEV_AUX_SPLIT_POOL);
-                       nvlist_free(label);
-                       return (0);
-               }
+       if ((label = vdev_label_read_config(vd, txg)) == NULL) {
+               vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
+                   VDEV_AUX_BAD_LABEL);
+               vdev_dbgmsg(vd, "vdev_validate: failed reading config for "
+                   "txg %llu", (u_longlong_t)txg);
+               return (0);
+       }
 
-               if (strict && (nvlist_lookup_uint64(label,
-                   ZPOOL_CONFIG_POOL_GUID, &guid) != 0 ||
-                   guid != spa_guid(spa))) {
-                       vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
-                           VDEV_AUX_CORRUPT_DATA);
-                       nvlist_free(label);
-                       return (0);
-               }
+       /*
+        * Determine if this vdev has been split off into another
+        * pool.  If so, then refuse to open it.
+        */
+       if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_SPLIT_GUID,
+           &aux_guid) == 0 && aux_guid == spa_guid(spa)) {
+               vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
+                   VDEV_AUX_SPLIT_POOL);
+               nvlist_free(label);
+               vdev_dbgmsg(vd, "vdev_validate: vdev split into other pool");
+               return (0);
+       }
 
-               if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_VDEV_TREE, &nvl)
-                   != 0 || nvlist_lookup_uint64(nvl, ZPOOL_CONFIG_ORIG_GUID,
-                   &aux_guid) != 0)
-                       aux_guid = 0;
+       if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_GUID, &guid) != 0) {
+               vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
+                   VDEV_AUX_CORRUPT_DATA);
+               nvlist_free(label);
+               vdev_dbgmsg(vd, "vdev_validate: '%s' missing from label",
+                   ZPOOL_CONFIG_POOL_GUID);
+               return (0);
+       }
 
-               /*
-                * If this vdev just became a top-level vdev because its
-                * sibling was detached, it will have adopted the parent's
-                * vdev guid -- but the label may or may not be on disk yet.
-                * Fortunately, either version of the label will have the
-                * same top guid, so if we're a top-level vdev, we can
-                * safely compare to that instead.
-                *
-                * If we split this vdev off instead, then we also check the
-                * original pool's guid.  We don't want to consider the vdev
-                * corrupt if it is partway through a split operation.
-                */
-               if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID,
-                   &guid) != 0 ||
-                   nvlist_lookup_uint64(label, ZPOOL_CONFIG_TOP_GUID,
-                   &top_guid) != 0 ||
-                   ((vd->vdev_guid != guid && vd->vdev_guid != aux_guid) &&
-                   (vd->vdev_guid != top_guid || vd != vd->vdev_top))) {
-                       vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
-                           VDEV_AUX_CORRUPT_DATA);
-                       nvlist_free(label);
-                       return (0);
+       /*
+        * If config is not trusted then ignore the spa guid check. This is
+        * necessary because if the machine crashed during a re-guid the new
+        * guid might have been written to all of the vdev labels, but not the
+        * cached config. The check will be performed again once we have the
+        * trusted config from the MOS.
+        */
+       if (spa->spa_trust_config && guid != spa_guid(spa)) {
+               vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
+                   VDEV_AUX_CORRUPT_DATA);
+               nvlist_free(label);
+               vdev_dbgmsg(vd, "vdev_validate: vdev label pool_guid doesn't "
+                   "match config (%llu != %llu)", (u_longlong_t)guid,
+                   (u_longlong_t)spa_guid(spa));
+               return (0);
+       }
+
+       if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_VDEV_TREE, &nvl)
+           != 0 || nvlist_lookup_uint64(nvl, ZPOOL_CONFIG_ORIG_GUID,
+           &aux_guid) != 0)
+               aux_guid = 0;
+
+       if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID, &guid) != 0) {
+               vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
+                   VDEV_AUX_CORRUPT_DATA);
+               nvlist_free(label);
+               vdev_dbgmsg(vd, "vdev_validate: '%s' missing from label",
+                   ZPOOL_CONFIG_GUID);
+               return (0);
+       }
+
+       if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_TOP_GUID, &top_guid)
+           != 0) {
+               vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
+                   VDEV_AUX_CORRUPT_DATA);
+               nvlist_free(label);
+               vdev_dbgmsg(vd, "vdev_validate: '%s' missing from label",
+                   ZPOOL_CONFIG_TOP_GUID);
+               return (0);
+       }
+
+       /*
+        * If this vdev just became a top-level vdev because its sibling was
+        * detached, it will have adopted the parent's vdev guid -- but the
+        * label may or may not be on disk yet. Fortunately, either version
+        * of the label will have the same top guid, so if we're a top-level
+        * vdev, we can safely compare to that instead.
+        * However, if the config comes from a cachefile that failed to update
+        * after the detach, a top-level vdev will appear as a non top-level
+        * vdev in the config. Also relax the constraints if we perform an
+        * extreme rewind.
+        *
+        * If we split this vdev off instead, then we also check the
+        * original pool's guid. We don't want to consider the vdev
+        * corrupt if it is partway through a split operation.
+        */
+       if (vd->vdev_guid != guid && vd->vdev_guid != aux_guid) {
+               boolean_t mismatch = B_FALSE;
+               if (spa->spa_trust_config && !spa->spa_extreme_rewind) {
+                       if (vd != vd->vdev_top || vd->vdev_guid != top_guid)
+                               mismatch = B_TRUE;
+               } else {
+                       if (vd->vdev_guid != top_guid &&
+                           vd->vdev_top->vdev_guid != guid)
+                               mismatch = B_TRUE;
                }
 
-               if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE,
-                   &state) != 0) {
+               if (mismatch) {
                        vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
                            VDEV_AUX_CORRUPT_DATA);
                        nvlist_free(label);
+                       vdev_dbgmsg(vd, "vdev_validate: config guid "
+                           "doesn't match label guid");
+                       vdev_dbgmsg(vd, "CONFIG: guid %llu, top_guid %llu",
+                           (u_longlong_t)vd->vdev_guid,
+                           (u_longlong_t)vd->vdev_top->vdev_guid);
+                       vdev_dbgmsg(vd, "LABEL: guid %llu, top_guid %llu, "
+                           "aux_guid %llu", (u_longlong_t)guid,
+                           (u_longlong_t)top_guid, (u_longlong_t)aux_guid);
                        return (0);
                }
+       }
 
+       if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE,
+           &state) != 0) {
+               vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
+                   VDEV_AUX_CORRUPT_DATA);
                nvlist_free(label);
+               vdev_dbgmsg(vd, "vdev_validate: '%s' missing from label",
+                   ZPOOL_CONFIG_POOL_STATE);
+               return (0);
+       }
 
-               /*
-                * If this is a verbatim import, no need to check the
-                * state of the pool.
-                */
-               if (!(spa->spa_import_flags & ZFS_IMPORT_VERBATIM) &&
-                   spa_load_state(spa) == SPA_LOAD_OPEN &&
-                   state != POOL_STATE_ACTIVE)
-                       return (SET_ERROR(EBADF));
+       nvlist_free(label);
 
-               /*
-                * If we were able to open and validate a vdev that was
-                * previously marked permanently unavailable, clear that state
-                * now.
-                */
-               if (vd->vdev_not_present)
-                       vd->vdev_not_present = 0;
+       /*
+        * If this is a verbatim import, no need to check the
+        * state of the pool.
+        */
+       if (!(spa->spa_import_flags & ZFS_IMPORT_VERBATIM) &&
+           spa_load_state(spa) == SPA_LOAD_OPEN &&
+           state != POOL_STATE_ACTIVE) {
+               vdev_dbgmsg(vd, "vdev_validate: invalid pool state (%llu) "
+                   "for spa %s", (u_longlong_t)state, spa->spa_name);
+               return (SET_ERROR(EBADF));
+       }
+
+       /*
+        * If we were able to open and validate a vdev that was
+        * previously marked permanently unavailable, clear that state
+        * now.
+        */
+       if (vd->vdev_not_present)
+               vd->vdev_not_present = 0;
+
+       return (0);
+}
+
+static void
+vdev_copy_path_impl(vdev_t *svd, vdev_t *dvd)
+{
+       if (svd->vdev_path != NULL && dvd->vdev_path != NULL) {
+               if (strcmp(svd->vdev_path, dvd->vdev_path) != 0) {
+                       zfs_dbgmsg("vdev_copy_path: vdev %llu: path changed "
+                           "from '%s' to '%s'", (u_longlong_t)dvd->vdev_guid,
+                           dvd->vdev_path, svd->vdev_path);
+                       spa_strfree(dvd->vdev_path);
+                       dvd->vdev_path = spa_strdup(svd->vdev_path);
+               }
+       } else if (svd->vdev_path != NULL) {
+               dvd->vdev_path = spa_strdup(svd->vdev_path);
+               zfs_dbgmsg("vdev_copy_path: vdev %llu: path set to '%s'",
+                   (u_longlong_t)dvd->vdev_guid, dvd->vdev_path);
+       }
+}
+
+/*
+ * Recursively copy vdev paths from one vdev to another. Source and destination
+ * vdev trees must have same geometry otherwise return error. Intended to copy
+ * paths from userland config into MOS config.
+ */
+int
+vdev_copy_path_strict(vdev_t *svd, vdev_t *dvd)
+{
+       if ((svd->vdev_ops == &vdev_missing_ops) ||
+           (svd->vdev_ishole && dvd->vdev_ishole) ||
+           (dvd->vdev_ops == &vdev_indirect_ops))
+               return (0);
+
+       if (svd->vdev_ops != dvd->vdev_ops) {
+               vdev_dbgmsg(svd, "vdev_copy_path: vdev type mismatch: %s != %s",
+                   svd->vdev_ops->vdev_op_type, dvd->vdev_ops->vdev_op_type);
+               return (SET_ERROR(EINVAL));
+       }
+
+       if (svd->vdev_guid != dvd->vdev_guid) {
+               vdev_dbgmsg(svd, "vdev_copy_path: guids mismatch (%llu != "
+                   "%llu)", (u_longlong_t)svd->vdev_guid,
+                   (u_longlong_t)dvd->vdev_guid);
+               return (SET_ERROR(EINVAL));
+       }
+
+       if (svd->vdev_children != dvd->vdev_children) {
+               vdev_dbgmsg(svd, "vdev_copy_path: children count mismatch: "
+                   "%llu != %llu", (u_longlong_t)svd->vdev_children,
+                   (u_longlong_t)dvd->vdev_children);
+               return (SET_ERROR(EINVAL));
+       }
+
+       for (uint64_t i = 0; i < svd->vdev_children; i++) {
+               int error = vdev_copy_path_strict(svd->vdev_child[i],
+                   dvd->vdev_child[i]);
+               if (error != 0)
+                       return (error);
        }
 
+       if (svd->vdev_ops->vdev_op_leaf)
+               vdev_copy_path_impl(svd, dvd);
+
        return (0);
 }
 
+static void
+vdev_copy_path_search(vdev_t *stvd, vdev_t *dvd)
+{
+       ASSERT(stvd->vdev_top == stvd);
+       ASSERT3U(stvd->vdev_id, ==, dvd->vdev_top->vdev_id);
+
+       for (uint64_t i = 0; i < dvd->vdev_children; i++) {
+               vdev_copy_path_search(stvd, dvd->vdev_child[i]);
+       }
+
+       if (!dvd->vdev_ops->vdev_op_leaf || !vdev_is_concrete(dvd))
+               return;
+
+       /*
+        * The idea here is that while a vdev can shift positions within
+        * a top vdev (when replacing, attaching mirror, etc.) it cannot
+        * step outside of it.
+        */
+       vdev_t *vd = vdev_lookup_by_guid(stvd, dvd->vdev_guid);
+
+       if (vd == NULL || vd->vdev_ops != dvd->vdev_ops)
+               return;
+
+       ASSERT(vd->vdev_ops->vdev_op_leaf);
+
+       vdev_copy_path_impl(vd, dvd);
+}
+
+/*
+ * Recursively copy vdev paths from one root vdev to another. Source and
+ * destination vdev trees may differ in geometry. For each destination leaf
+ * vdev, search a vdev with the same guid and top vdev id in the source.
+ * Intended to copy paths from userland config into MOS config.
+ */
+void
+vdev_copy_path_relaxed(vdev_t *srvd, vdev_t *drvd)
+{
+       uint64_t children = MIN(srvd->vdev_children, drvd->vdev_children);
+       ASSERT(srvd->vdev_ops == &vdev_root_ops);
+       ASSERT(drvd->vdev_ops == &vdev_root_ops);
+
+       for (uint64_t i = 0; i < children; i++) {
+               vdev_copy_path_search(srvd->vdev_child[i],
+                   drvd->vdev_child[i]);
+       }
+}
+
 /*
  * Close a virtual device.
  */
@@ -1793,7 +2203,7 @@ vdev_reopen(vdev_t *vd)
                    !l2arc_vdev_present(vd))
                        l2arc_add_vdev(spa, vd);
        } else {
-               (void) vdev_validate(vd, B_TRUE);
+               (void) vdev_validate(vd);
        }
 
        /*
@@ -1835,11 +2245,58 @@ vdev_create(vdev_t *vd, uint64_t txg, boolean_t isreplacing)
 void
 vdev_metaslab_set_size(vdev_t *vd)
 {
+       uint64_t asize = vd->vdev_asize;
+       uint64_t ms_count = asize >> vdev_default_ms_shift;
+       uint64_t ms_shift;
+
        /*
-        * Aim for roughly metaslabs_per_vdev (default 200) metaslabs per vdev.
+        * There are two dimensions to the metaslab sizing calculation:
+        * the size of the metaslab and the count of metaslabs per vdev.
+        * In general, we aim for vdev_max_ms_count (200) metaslabs. The
+        * range of the dimensions are as follows:
+        *
+        *      2^29 <= ms_size  <= 2^38
+        *        16 <= ms_count <= 131,072
+        *
+        * On the lower end of vdev sizes, we aim for metaslabs sizes of
+        * at least 512MB (2^29) to minimize fragmentation effects when
+        * testing with smaller devices.  However, the count constraint
+        * of at least 16 metaslabs will override this minimum size goal.
+        *
+        * On the upper end of vdev sizes, we aim for a maximum metaslab
+        * size of 256GB.  However, we will cap the total count to 2^17
+        * metaslabs to keep our memory footprint in check.
+        *
+        * The net effect of applying above constrains is summarized below.
+        *
+        *      vdev size       metaslab count
+        *      -------------|-----------------
+        *      < 8GB           ~16
+        *      8GB - 100GB     one per 512MB
+        *      100GB - 50TB    ~200
+        *      50TB - 32PB     one per 256GB
+        *      > 32PB          ~131,072
+        *      -------------------------------
         */
-       vd->vdev_ms_shift = highbit64(vd->vdev_asize / metaslabs_per_vdev);
-       vd->vdev_ms_shift = MAX(vd->vdev_ms_shift, SPA_MAXBLOCKSHIFT);
+
+       if (ms_count < vdev_min_ms_count)
+               ms_shift = highbit64(asize / vdev_min_ms_count);
+       else if (ms_count > vdev_max_ms_count)
+               ms_shift = highbit64(asize / vdev_max_ms_count);
+       else
+               ms_shift = vdev_default_ms_shift;
+
+       if (ms_shift < SPA_MAXBLOCKSHIFT) {
+               ms_shift = SPA_MAXBLOCKSHIFT;
+       } else if (ms_shift > vdev_max_ms_shift) {
+               ms_shift = vdev_max_ms_shift;
+               /* cap the total count to constrain memory footprint */
+               if ((asize >> ms_shift) > vdev_ms_count_limit)
+                       ms_shift = highbit64(asize / vdev_ms_count_limit);
+       }
+
+       vd->vdev_ms_shift = ms_shift;
+       ASSERT3U(vd->vdev_ms_shift, >=, SPA_MAXBLOCKSHIFT);
 }
 
 void
@@ -1944,7 +2401,7 @@ vdev_dtl_contains(vdev_t *vd, vdev_dtl_type_t t, uint64_t txg, uint64_t size)
                return (B_FALSE);
 
        mutex_enter(&vd->vdev_dtl_lock);
-       if (range_tree_space(rt) != 0)
+       if (!range_tree_is_empty(rt))
                dirty = range_tree_contains(rt, txg, size);
        mutex_exit(&vd->vdev_dtl_lock);
 
@@ -1958,7 +2415,7 @@ vdev_dtl_empty(vdev_t *vd, vdev_dtl_type_t t)
        boolean_t empty;
 
        mutex_enter(&vd->vdev_dtl_lock);
-       empty = (range_tree_space(rt) == 0);
+       empty = range_tree_is_empty(rt);
        mutex_exit(&vd->vdev_dtl_lock);
 
        return (empty);
@@ -2032,7 +2489,7 @@ vdev_dtl_should_excise(vdev_t *vd)
                return (B_FALSE);
 
        if (vd->vdev_resilver_txg == 0 ||
-           range_tree_space(vd->vdev_dtl[DTL_MISSING]) == 0)
+           range_tree_is_empty(vd->vdev_dtl[DTL_MISSING]))
                return (B_TRUE);
 
        /*
@@ -2136,8 +2593,8 @@ vdev_dtl_reassess(vdev_t *vd, uint64_t txg, uint64_t scrub_txg, int scrub_done)
                 * the top level so that we persist the change.
                 */
                if (vd->vdev_resilver_txg != 0 &&
-                   range_tree_space(vd->vdev_dtl[DTL_MISSING]) == 0 &&
-                   range_tree_space(vd->vdev_dtl[DTL_OUTAGE]) == 0) {
+                   range_tree_is_empty(vd->vdev_dtl[DTL_MISSING]) &&
+                   range_tree_is_empty(vd->vdev_dtl[DTL_OUTAGE])) {
                        vd->vdev_resilver_txg = 0;
                        vdev_config_dirty(vd->vdev_top);
                }
@@ -2214,6 +2671,30 @@ vdev_dtl_load(vdev_t *vd)
        return (error);
 }
 
+static void
+vdev_zap_allocation_data(vdev_t *vd, dmu_tx_t *tx)
+{
+       spa_t *spa = vd->vdev_spa;
+       objset_t *mos = spa->spa_meta_objset;
+       vdev_alloc_bias_t alloc_bias = vd->vdev_alloc_bias;
+       const char *string;
+
+       ASSERT(alloc_bias != VDEV_BIAS_NONE);
+
+       string =
+           (alloc_bias == VDEV_BIAS_LOG) ? VDEV_ALLOC_BIAS_LOG :
+           (alloc_bias == VDEV_BIAS_SPECIAL) ? VDEV_ALLOC_BIAS_SPECIAL :
+           (alloc_bias == VDEV_BIAS_DEDUP) ? VDEV_ALLOC_BIAS_DEDUP : NULL;
+
+       ASSERT(string != NULL);
+       VERIFY0(zap_add(mos, vd->vdev_top_zap, VDEV_TOP_ZAP_ALLOCATION_BIAS,
+           1, strlen(string) + 1, string, tx));
+
+       if (alloc_bias == VDEV_BIAS_SPECIAL || alloc_bias == VDEV_BIAS_DEDUP) {
+               spa_activate_allocation_classes(spa, tx);
+       }
+}
+
 void
 vdev_destroy_unlink_zap(vdev_t *vd, uint64_t zapobj, dmu_tx_t *tx)
 {
@@ -2250,8 +2731,11 @@ vdev_construct_zaps(vdev_t *vd, dmu_tx_t *tx)
                }
                if (vd == vd->vdev_top && vd->vdev_top_zap == 0) {
                        vd->vdev_top_zap = vdev_create_link_zap(vd, tx);
+                       if (vd->vdev_alloc_bias != VDEV_BIAS_NONE)
+                               vdev_zap_allocation_data(vd, tx);
                }
        }
+
        for (uint64_t i = 0; i < vd->vdev_children; i++) {
                vdev_construct_zaps(vd->vdev_child[i], tx);
        }
@@ -2297,7 +2781,7 @@ vdev_dtl_sync(vdev_t *vd, uint64_t txg)
        if (vd->vdev_dtl_sm == NULL) {
                uint64_t new_object;
 
-               new_object = space_map_alloc(mos, tx);
+               new_object = space_map_alloc(mos, vdev_dtl_sm_blksz, tx);
                VERIFY3U(new_object, !=, 0);
 
                VERIFY0(space_map_open(&vd->vdev_dtl_sm, mos, new_object,
@@ -2311,8 +2795,8 @@ vdev_dtl_sync(vdev_t *vd, uint64_t txg)
        range_tree_walk(rt, range_tree_add, rtsync);
        mutex_exit(&vd->vdev_dtl_lock);
 
-       space_map_truncate(vd->vdev_dtl_sm, tx);
-       space_map_write(vd->vdev_dtl_sm, rtsync, SM_ALLOC, tx);
+       space_map_truncate(vd->vdev_dtl_sm, vdev_dtl_sm_blksz, tx);
+       space_map_write(vd->vdev_dtl_sm, rtsync, SM_ALLOC, SM_NO_VDEVID, tx);
        range_tree_vacate(rtsync, NULL, NULL);
 
        range_tree_destroy(rtsync);
@@ -2322,9 +2806,10 @@ vdev_dtl_sync(vdev_t *vd, uint64_t txg)
         * the top level so that we update the config.
         */
        if (object != space_map_object(vd->vdev_dtl_sm)) {
-               zfs_dbgmsg("txg %llu, spa %s, DTL old object %llu, "
-                   "new object %llu", txg, spa_name(spa), object,
-                   space_map_object(vd->vdev_dtl_sm));
+               vdev_dbgmsg(vd, "txg %llu, spa %s, DTL old object %llu, "
+                   "new object %llu", (u_longlong_t)txg, spa_name(spa),
+                   (u_longlong_t)object,
+                   (u_longlong_t)space_map_object(vd->vdev_dtl_sm));
                vdev_config_dirty(vd->vdev_top);
        }
 
@@ -2381,7 +2866,7 @@ vdev_resilver_needed(vdev_t *vd, uint64_t *minp, uint64_t *maxp)
 
        if (vd->vdev_children == 0) {
                mutex_enter(&vd->vdev_dtl_lock);
-               if (range_tree_space(vd->vdev_dtl[DTL_MISSING]) != 0 &&
+               if (!range_tree_is_empty(vd->vdev_dtl[DTL_MISSING]) &&
                    vdev_writeable(vd)) {
 
                        thismin = vdev_dtl_min(vd);
@@ -2409,6 +2894,33 @@ vdev_resilver_needed(vdev_t *vd, uint64_t *minp, uint64_t *maxp)
        return (needed);
 }
 
+/*
+ * Gets the checkpoint space map object from the vdev's ZAP.
+ * Returns the spacemap object, or 0 if it wasn't in the ZAP,
+ * the ZAP doesn't exist yet, or the ZAP is damaged.
+ */
+int
+vdev_checkpoint_sm_object(vdev_t *vd)
+{
+       ASSERT0(spa_config_held(vd->vdev_spa, SCL_ALL, RW_WRITER));
+       if (vd->vdev_top_zap == 0) {
+               return (0);
+       }
+
+       uint64_t sm_obj = 0;
+       int err = zap_lookup(spa_meta_objset(vd->vdev_spa), vd->vdev_top_zap,
+           VDEV_TOP_ZAP_POOL_CHECKPOINT_SM, sizeof (uint64_t), 1, &sm_obj);
+
+       if (err != 0 && err != ENOENT) {
+               vdev_dbgmsg(vd, "vdev_load: vdev_checkpoint_sm_objset "
+                   "failed to retrieve checkpoint space map object from "
+                   "vdev ZAP [error=%d]", err);
+               ASSERT3S(err, ==, ECKSUM);
+       }
+
+       return (sm_obj);
+}
+
 int
 vdev_load(vdev_t *vd)
 {
@@ -2426,19 +2938,70 @@ vdev_load(vdev_t *vd)
 
        vdev_set_deflate_ratio(vd);
 
+       /*
+        * On spa_load path, grab the allocation bias from our zap
+        */
+       if (vd == vd->vdev_top && vd->vdev_top_zap != 0) {
+               spa_t *spa = vd->vdev_spa;
+               char bias_str[64];
+
+               if (zap_lookup(spa->spa_meta_objset, vd->vdev_top_zap,
+                   VDEV_TOP_ZAP_ALLOCATION_BIAS, 1, sizeof (bias_str),
+                   bias_str) == 0) {
+                       ASSERT(vd->vdev_alloc_bias == VDEV_BIAS_NONE);
+                       vd->vdev_alloc_bias = vdev_derive_alloc_bias(bias_str);
+               }
+       }
+
        /*
         * If this is a top-level vdev, initialize its metaslabs.
         */
        if (vd == vd->vdev_top && vdev_is_concrete(vd)) {
+               vdev_metaslab_group_create(vd);
+
                if (vd->vdev_ashift == 0 || vd->vdev_asize == 0) {
                        vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
                            VDEV_AUX_CORRUPT_DATA);
+                       vdev_dbgmsg(vd, "vdev_load: invalid size. ashift=%llu, "
+                           "asize=%llu", (u_longlong_t)vd->vdev_ashift,
+                           (u_longlong_t)vd->vdev_asize);
                        return (SET_ERROR(ENXIO));
                } else if ((error = vdev_metaslab_init(vd, 0)) != 0) {
+                       vdev_dbgmsg(vd, "vdev_load: metaslab_init failed "
+                           "[error=%d]", error);
                        vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
                            VDEV_AUX_CORRUPT_DATA);
                        return (error);
                }
+
+               uint64_t checkpoint_sm_obj = vdev_checkpoint_sm_object(vd);
+               if (checkpoint_sm_obj != 0) {
+                       objset_t *mos = spa_meta_objset(vd->vdev_spa);
+                       ASSERT(vd->vdev_asize != 0);
+                       ASSERT3P(vd->vdev_checkpoint_sm, ==, NULL);
+
+                       if ((error = space_map_open(&vd->vdev_checkpoint_sm,
+                           mos, checkpoint_sm_obj, 0, vd->vdev_asize,
+                           vd->vdev_ashift))) {
+                               vdev_dbgmsg(vd, "vdev_load: space_map_open "
+                                   "failed for checkpoint spacemap (obj %llu) "
+                                   "[error=%d]",
+                                   (u_longlong_t)checkpoint_sm_obj, error);
+                               return (error);
+                       }
+                       ASSERT3P(vd->vdev_checkpoint_sm, !=, NULL);
+                       space_map_update(vd->vdev_checkpoint_sm);
+
+                       /*
+                        * Since the checkpoint_sm contains free entries
+                        * exclusively we can use sm_alloc to indicate the
+                        * culmulative checkpointed space that has been freed.
+                        */
+                       vd->vdev_stat.vs_checkpoint_space =
+                           -vd->vdev_checkpoint_sm->sm_alloc;
+                       vd->vdev_spa->spa_checkpoint_info.sci_dspace +=
+                           vd->vdev_stat.vs_checkpoint_space;
+               }
        }
 
        /*
@@ -2447,6 +3010,8 @@ vdev_load(vdev_t *vd)
        if (vd->vdev_ops->vdev_op_leaf && (error = vdev_dtl_load(vd)) != 0) {
                vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
                    VDEV_AUX_CORRUPT_DATA);
+               vdev_dbgmsg(vd, "vdev_load: vdev_dtl_load failed "
+                   "[error=%d]", error);
                return (error);
        }
 
@@ -2454,12 +3019,15 @@ vdev_load(vdev_t *vd)
        if (obsolete_sm_object != 0) {
                objset_t *mos = vd->vdev_spa->spa_meta_objset;
                ASSERT(vd->vdev_asize != 0);
-               ASSERT(vd->vdev_obsolete_sm == NULL);
+               ASSERT3P(vd->vdev_obsolete_sm, ==, NULL);
 
                if ((error = space_map_open(&vd->vdev_obsolete_sm, mos,
                    obsolete_sm_object, 0, vd->vdev_asize, 0))) {
                        vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
                            VDEV_AUX_CORRUPT_DATA);
+                       vdev_dbgmsg(vd, "vdev_load: space_map_open failed for "
+                           "obsolete spacemap (obj %llu) [error=%d]",
+                           (u_longlong_t)obsolete_sm_object, error);
                        return (error);
                }
                space_map_update(vd->vdev_obsolete_sm);
@@ -2577,8 +3145,15 @@ vdev_remove_empty(vdev_t *vd, uint64_t txg)
                        mutex_exit(&msp->ms_lock);
                }
 
+               if (vd->vdev_checkpoint_sm != NULL) {
+                       ASSERT(spa_has_checkpoint(spa));
+                       space_map_close(vd->vdev_checkpoint_sm);
+                       vd->vdev_checkpoint_sm = NULL;
+               }
+
                metaslab_group_histogram_verify(mg);
                metaslab_class_histogram_verify(mg->mg_class);
+
                for (int i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++)
                        ASSERT0(mg->mg_histogram[i]);
        }
@@ -2826,7 +3401,8 @@ vdev_online(spa_t *spa, uint64_t guid, uint64_t flags, vdev_state_t *newstate)
        /* XXX - L2ARC 1.0 does not support expansion */
        if (!vd->vdev_aux) {
                for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
-                       pvd->vdev_expanding = !!(flags & ZFS_ONLINE_EXPAND);
+                       pvd->vdev_expanding = !!((flags & ZFS_ONLINE_EXPAND) ||
+                           spa->spa_autoexpand);
        }
 
        vdev_reopen(tvd);
@@ -2910,6 +3486,17 @@ top:
 
                        error = spa_reset_logs(spa);
 
+                       /*
+                        * If the log device was successfully reset but has
+                        * checkpointed data, do not offline it.
+                        */
+                       if (error == 0 &&
+                           tvd->vdev_checkpoint_sm != NULL) {
+                               ASSERT3U(tvd->vdev_checkpoint_sm->sm_alloc,
+                                   !=, 0);
+                               error = ZFS_ERR_CHECKPOINT_EXISTS;
+                       }
+
                        spa_vdev_state_enter(spa, SCL_ALLOC);
 
                        /*
@@ -3148,6 +3735,23 @@ vdev_get_child_stat_ex(vdev_t *cvd, vdev_stat_ex_t *vsx, vdev_stat_ex_t *cvsx)
 
 }
 
+boolean_t
+vdev_is_spacemap_addressable(vdev_t *vd)
+{
+       /*
+        * Assuming 47 bits of the space map entry dedicated for the entry's
+        * offset (see description in space_map.h), we calculate the maximum
+        * address that can be described by a space map entry for the given
+        * device.
+        */
+       uint64_t shift = vd->vdev_ashift + 47;
+
+       if (shift >= 63) /* detect potential overflow */
+               return (B_TRUE);
+
+       return (vd->vdev_asize < (1ULL << shift));
+}
+
 /*
  * Get statistics for the given vdev.
  */
@@ -3222,10 +3826,10 @@ vdev_get_stats_ex(vdev_t *vd, vdev_stat_t *vs, vdev_stat_ex_t *vsx)
                            vd->vdev_max_asize - vd->vdev_asize,
                            1ULL << tvd->vdev_ms_shift);
                }
-               vs->vs_esize = vd->vdev_max_asize - vd->vdev_asize;
                if (vd->vdev_aux == NULL && vd == vd->vdev_top &&
                    vdev_is_concrete(vd)) {
-                       vs->vs_fragmentation = vd->vdev_mg->mg_fragmentation;
+                       vs->vs_fragmentation = (vd->vdev_mg != NULL) ?
+                           vd->vdev_mg->mg_fragmentation : 0;
                }
        }
 
@@ -3430,19 +4034,25 @@ vdev_stat_update(zio_t *zio, uint64_t psize)
        }
 }
 
+int64_t
+vdev_deflated_space(vdev_t *vd, int64_t space)
+{
+       ASSERT((space & (SPA_MINBLOCKSIZE-1)) == 0);
+       ASSERT(vd->vdev_deflate_ratio != 0 || vd->vdev_isl2cache);
+
+       return ((space >> SPA_MINBLOCKSHIFT) * vd->vdev_deflate_ratio);
+}
+
 /*
- * Update the in-core space usage stats for this vdev, its metaslab class,
- * and the root vdev.
+ * Update the in-core space usage stats for this vdev and the root vdev.
  */
 void
 vdev_space_update(vdev_t *vd, int64_t alloc_delta, int64_t defer_delta,
     int64_t space_delta)
 {
-       int64_t dspace_delta = space_delta;
+       int64_t dspace_delta;
        spa_t *spa = vd->vdev_spa;
        vdev_t *rvd = spa->spa_root_vdev;
-       metaslab_group_t *mg = vd->vdev_mg;
-       metaslab_class_t *mc = mg ? mg->mg_class : NULL;
 
        ASSERT(vd == vd->vdev_top);
 
@@ -3452,10 +4062,7 @@ vdev_space_update(vdev_t *vd, int64_t alloc_delta, int64_t defer_delta,
         * because the root vdev's psize-to-asize is simply the max of its
         * childrens', thus not accurate enough for us.
         */
-       ASSERT((dspace_delta & (SPA_MINBLOCKSIZE-1)) == 0);
-       ASSERT(vd->vdev_deflate_ratio != 0 || vd->vdev_isl2cache);
-       dspace_delta = (dspace_delta >> SPA_MINBLOCKSHIFT) *
-           vd->vdev_deflate_ratio;
+       dspace_delta = vdev_deflated_space(vd, space_delta);
 
        mutex_enter(&vd->vdev_stat_lock);
        vd->vdev_stat.vs_alloc += alloc_delta;
@@ -3463,21 +4070,15 @@ vdev_space_update(vdev_t *vd, int64_t alloc_delta, int64_t defer_delta,
        vd->vdev_stat.vs_dspace += dspace_delta;
        mutex_exit(&vd->vdev_stat_lock);
 
-       if (mc == spa_normal_class(spa)) {
+       /* every class but log contributes to root space stats */
+       if (vd->vdev_mg != NULL && !vd->vdev_islog) {
                mutex_enter(&rvd->vdev_stat_lock);
                rvd->vdev_stat.vs_alloc += alloc_delta;
                rvd->vdev_stat.vs_space += space_delta;
                rvd->vdev_stat.vs_dspace += dspace_delta;
                mutex_exit(&rvd->vdev_stat_lock);
        }
-
-       if (mc != NULL) {
-               ASSERT(rvd == vd->vdev_parent);
-               ASSERT(vd->vdev_ms_count != 0);
-
-               metaslab_class_space_update(mc,
-                   alloc_delta, defer_delta, space_delta, dspace_delta);
-       }
+       /* Note: metaslab_class_space_update moved to metaslab_space_update */
 }
 
 /*
@@ -3827,6 +4428,19 @@ vdev_set_state(vdev_t *vd, boolean_t isopen, vdev_state_t state, vdev_aux_t aux)
                vdev_propagate_state(vd->vdev_parent);
 }
 
+boolean_t
+vdev_children_are_offline(vdev_t *vd)
+{
+       ASSERT(!vd->vdev_ops->vdev_op_leaf);
+
+       for (uint64_t i = 0; i < vd->vdev_children; i++) {
+               if (vd->vdev_child[i]->vdev_state != VDEV_STATE_OFFLINE)
+                       return (B_FALSE);
+       }
+
+       return (B_TRUE);
+}
+
 /*
  * Check the vdev configuration to ensure that it's capable of supporting
  * a root pool. We do not support partial configuration.
@@ -3862,34 +4476,6 @@ vdev_is_concrete(vdev_t *vd)
        }
 }
 
-/*
- * Load the state from the original vdev tree (ovd) which
- * we've retrieved from the MOS config object. If the original
- * vdev was offline or faulted then we transfer that state to the
- * device in the current vdev tree (nvd).
- */
-void
-vdev_load_log_state(vdev_t *nvd, vdev_t *ovd)
-{
-       ASSERT(nvd->vdev_top->vdev_islog);
-       ASSERT(spa_config_held(nvd->vdev_spa,
-           SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
-       ASSERT3U(nvd->vdev_guid, ==, ovd->vdev_guid);
-
-       for (int c = 0; c < nvd->vdev_children; c++)
-               vdev_load_log_state(nvd->vdev_child[c], ovd->vdev_child[c]);
-
-       if (nvd->vdev_ops->vdev_op_leaf) {
-               /*
-                * Restore the persistent vdev state
-                */
-               nvd->vdev_offline = ovd->vdev_offline;
-               nvd->vdev_faulted = ovd->vdev_faulted;
-               nvd->vdev_degraded = ovd->vdev_degraded;
-               nvd->vdev_removed = ovd->vdev_removed;
-       }
-}
-
 /*
  * Determine if a log device has valid content.  If the vdev was
  * removed or faulted in the MOS config then we know that
@@ -3917,11 +4503,13 @@ vdev_expand(vdev_t *vd, uint64_t txg)
 {
        ASSERT(vd->vdev_top == vd);
        ASSERT(spa_config_held(vd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
+       ASSERT(vdev_is_concrete(vd));
 
        vdev_set_deflate_ratio(vd);
 
        if ((vd->vdev_asize >> vd->vdev_ms_shift) > vd->vdev_ms_count &&
            vdev_is_concrete(vd)) {
+               vdev_metaslab_group_create(vd);
                VERIFY(vdev_metaslab_init(vd, txg) == 0);
                vdev_config_dirty(vd);
        }
@@ -3981,17 +4569,24 @@ vdev_deadman(vdev_t *vd, char *tag)
        }
 }
 
-#if defined(_KERNEL) && defined(HAVE_SPL)
+#if defined(_KERNEL)
 EXPORT_SYMBOL(vdev_fault);
 EXPORT_SYMBOL(vdev_degrade);
 EXPORT_SYMBOL(vdev_online);
 EXPORT_SYMBOL(vdev_offline);
 EXPORT_SYMBOL(vdev_clear);
 /* BEGIN CSTYLED */
-module_param(metaslabs_per_vdev, int, 0644);
-MODULE_PARM_DESC(metaslabs_per_vdev,
-       "Divide added vdev into approximately (but no more than) this number "
-       "of metaslabs");
+module_param(vdev_max_ms_count, int, 0644);
+MODULE_PARM_DESC(vdev_max_ms_count,
+       "Target number of metaslabs per top-level vdev");
+
+module_param(vdev_min_ms_count, int, 0644);
+MODULE_PARM_DESC(vdev_min_ms_count,
+       "Minimum number of metaslabs per top-level vdev");
+
+module_param(vdev_ms_count_limit, int, 0644);
+MODULE_PARM_DESC(vdev_ms_count_limit,
+       "Practical upper limit of total metaslabs per top-level vdev");
 
 module_param(zfs_delays_per_second, uint, 0644);
 MODULE_PARM_DESC(zfs_delays_per_second, "Rate limit delay events to this many "
@@ -4005,5 +4600,9 @@ module_param(zfs_checksums_per_second, uint, 0644);
 module_param(zfs_scan_ignore_errors, int, 0644);
 MODULE_PARM_DESC(zfs_scan_ignore_errors,
        "Ignore errors during resilver/scrub");
+
+module_param(vdev_validate_skip, int, 0644);
+MODULE_PARM_DESC(vdev_validate_skip,
+       "Bypass vdev_validate()");
 /* END CSTYLED */
 #endif