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 2013 Nexenta Systems, Inc. All rights reserved.
  25  * Copyright (c) 2011, 2015 by Delphix. All rights reserved.
  26  * Copyright 2017 Joyent, Inc.
  27  */
  28 
  29 #include <sys/spa.h>
  30 #include <sys/fm/fs/zfs.h>
  31 #include <sys/spa_impl.h>
  32 #include <sys/nvpair.h>
  33 #include <sys/uio.h>
  34 #include <sys/fs/zfs.h>
  35 #include <sys/vdev_impl.h>
  36 #include <sys/zfs_ioctl.h>
  37 #include <sys/utsname.h>
  38 #include <sys/systeminfo.h>
  39 #include <sys/sunddi.h>
  40 #include <sys/zfeature.h>
  41 #ifdef _KERNEL
  42 #include <sys/kobj.h>
  43 #include <sys/zone.h>
  44 #endif
  45 
  46 /*
  47  * Pool configuration repository.
  48  *
  49  * Pool configuration is stored as a packed nvlist on the filesystem.  By
  50  * default, all pools are stored in /etc/zfs/zpool.cache and loaded on boot
  51  * (when the ZFS module is loaded).  Pools can also have the 'cachefile'
  52  * property set that allows them to be stored in an alternate location until
  53  * the control of external software.
  54  *
  55  * For each cache file, we have a single nvlist which holds all the
  56  * configuration information.  When the module loads, we read this information
  57  * from /etc/zfs/zpool.cache and populate the SPA namespace.  This namespace is
  58  * maintained independently in spa.c.  Whenever the namespace is modified, or
  59  * the configuration of a pool is changed, we call spa_config_sync(), which
  60  * walks through all the active pools and writes the configuration to disk.
  61  */
  62 
  63 static uint64_t spa_config_generation = 1;
  64 
  65 /*
  66  * This can be overridden in userland to preserve an alternate namespace for
  67  * userland pools when doing testing.
  68  */
  69 const char *spa_config_path = ZPOOL_CACHE;
  70 
  71 /*
  72  * Called when the module is first loaded, this routine loads the configuration
  73  * file into the SPA namespace.  It does not actually open or load the pools; it
  74  * only populates the namespace.
  75  */
  76 void
  77 spa_config_load(void)
  78 {
  79         void *buf = NULL;
  80         nvlist_t *nvlist, *child;
  81         nvpair_t *nvpair;
  82         char *pathname;
  83         struct _buf *file;
  84         uint64_t fsize;
  85 
  86         /*
  87          * Open the configuration file.
  88          */
  89         pathname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
  90 
  91         (void) snprintf(pathname, MAXPATHLEN, "%s%s",
  92             (rootdir != NULL) ? "./" : "", spa_config_path);
  93 
  94         file = kobj_open_file(pathname);
  95 
  96         kmem_free(pathname, MAXPATHLEN);
  97 
  98         if (file == (struct _buf *)-1)
  99                 return;
 100 
 101         if (kobj_get_filesize(file, &fsize) != 0)
 102                 goto out;
 103 
 104         buf = kmem_alloc(fsize, KM_SLEEP);
 105 
 106         /*
 107          * Read the nvlist from the file.
 108          */
 109         if (kobj_read_file(file, buf, fsize, 0) < 0)
 110                 goto out;
 111 
 112         /*
 113          * Unpack the nvlist.
 114          */
 115         if (nvlist_unpack(buf, fsize, &nvlist, KM_SLEEP) != 0)
 116                 goto out;
 117 
 118         /*
 119          * Iterate over all elements in the nvlist, creating a new spa_t for
 120          * each one with the specified configuration.
 121          */
 122         mutex_enter(&spa_namespace_lock);
 123         nvpair = NULL;
 124         while ((nvpair = nvlist_next_nvpair(nvlist, nvpair)) != NULL) {
 125                 uint64_t guid = 0;
 126 
 127                 if (nvpair_type(nvpair) != DATA_TYPE_NVLIST)
 128                         continue;
 129 
 130                 child = fnvpair_value_nvlist(nvpair);
 131                 /* a zero guid means we simply will ignore the check later */
 132                 (void) nvlist_lookup_uint64(child, ZPOOL_CONFIG_POOL_GUID,
 133                     &guid);
 134 
 135                 if (spa_lookup(nvpair_name(nvpair)) != NULL ||
 136                     spa_config_guid_exists(guid)) {
 137                         continue;
 138                 }
 139                 (void) spa_add(nvpair_name(nvpair), child, NULL);
 140         }
 141         mutex_exit(&spa_namespace_lock);
 142 
 143         nvlist_free(nvlist);
 144 
 145 out:
 146         if (buf != NULL)
 147                 kmem_free(buf, fsize);
 148 
 149         kobj_close_file(file);
 150 }
 151 
 152 static int
 153 spa_config_write(spa_config_dirent_t *dp, nvlist_t *nvl)
 154 {
 155         size_t buflen;
 156         char *buf;
 157         vnode_t *vp;
 158         int oflags = FWRITE | FTRUNC | FCREAT | FOFFMAX;
 159         char *temp;
 160         int err;
 161 
 162         /*
 163          * If the nvlist is empty (NULL), then remove the old cachefile.
 164          */
 165         if (nvl == NULL) {
 166                 err = vn_remove(dp->scd_path, UIO_SYSSPACE, RMFILE);
 167                 return (err);
 168         }
 169 
 170         /*
 171          * Pack the configuration into a buffer.
 172          */
 173         buf = fnvlist_pack(nvl, &buflen);
 174         temp = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
 175 
 176         /*
 177          * Write the configuration to disk.  We need to do the traditional
 178          * 'write to temporary file, sync, move over original' to make sure we
 179          * always have a consistent view of the data.
 180          */
 181         (void) snprintf(temp, MAXPATHLEN, "%s.tmp", dp->scd_path);
 182 
 183         err = vn_open(temp, UIO_SYSSPACE, oflags, 0644, &vp, CRCREAT, 0);
 184         if (err == 0) {
 185                 err = vn_rdwr(UIO_WRITE, vp, buf, buflen, 0, UIO_SYSSPACE,
 186                     0, RLIM64_INFINITY, kcred, NULL);
 187                 if (err == 0)
 188                         err = VOP_FSYNC(vp, FSYNC, kcred, NULL);
 189                 if (err == 0)
 190                         err = vn_rename(temp, dp->scd_path, UIO_SYSSPACE);
 191                 (void) VOP_CLOSE(vp, oflags, 1, 0, kcred, NULL);
 192                 VN_RELE(vp);
 193         }
 194 
 195         (void) vn_remove(temp, UIO_SYSSPACE, RMFILE);
 196 
 197         fnvlist_pack_free(buf, buflen);
 198         kmem_free(temp, MAXPATHLEN);
 199         return (err);
 200 }
 201 
 202 /*
 203  * Synchronize pool configuration to disk.  This must be called with the
 204  * namespace lock held. Synchronizing the pool cache is typically done after
 205  * the configuration has been synced to the MOS. This exposes a window where
 206  * the MOS config will have been updated but the cache file has not. If
 207  * the system were to crash at that instant then the cached config may not
 208  * contain the correct information to open the pool and an explicity import
 209  * would be required.
 210  */
 211 void
 212 spa_config_sync(spa_t *target, boolean_t removing, boolean_t postsysevent)
 213 {
 214         spa_config_dirent_t *dp, *tdp;
 215         nvlist_t *nvl;
 216         boolean_t ccw_failure;
 217         int error;
 218 
 219         ASSERT(MUTEX_HELD(&spa_namespace_lock));
 220 
 221         if (rootdir == NULL || !(spa_mode_global & FWRITE))
 222                 return;
 223 
 224         /*
 225          * Iterate over all cachefiles for the pool, past or present.  When the
 226          * cachefile is changed, the new one is pushed onto this list, allowing
 227          * us to update previous cachefiles that no longer contain this pool.
 228          */
 229         ccw_failure = B_FALSE;
 230         for (dp = list_head(&target->spa_config_list); dp != NULL;
 231             dp = list_next(&target->spa_config_list, dp)) {
 232                 spa_t *spa = NULL;
 233                 if (dp->scd_path == NULL)
 234                         continue;
 235 
 236                 /*
 237                  * Iterate over all pools, adding any matching pools to 'nvl'.
 238                  */
 239                 nvl = NULL;
 240                 while ((spa = spa_next(spa)) != NULL) {
 241                         /*
 242                          * Skip over our own pool if we're about to remove
 243                          * ourselves from the spa namespace or any pool that
 244                          * is readonly. Since we cannot guarantee that a
 245                          * readonly pool would successfully import upon reboot,
 246                          * we don't allow them to be written to the cache file.
 247                          */
 248                         if ((spa == target && removing) ||
 249                             !spa_writeable(spa))
 250                                 continue;
 251 
 252                         mutex_enter(&spa->spa_props_lock);
 253                         tdp = list_head(&spa->spa_config_list);
 254                         if (spa->spa_config == NULL ||
 255                             tdp->scd_path == NULL ||
 256                             strcmp(tdp->scd_path, dp->scd_path) != 0) {
 257                                 mutex_exit(&spa->spa_props_lock);
 258                                 continue;
 259                         }
 260 
 261                         if (nvl == NULL)
 262                                 nvl = fnvlist_alloc();
 263 
 264                         fnvlist_add_nvlist(nvl, spa->spa_name,
 265                             spa->spa_config);
 266                         mutex_exit(&spa->spa_props_lock);
 267                 }
 268 
 269                 error = spa_config_write(dp, nvl);
 270                 if (error != 0)
 271                         ccw_failure = B_TRUE;
 272                 nvlist_free(nvl);
 273         }
 274 
 275         if (ccw_failure) {
 276                 /*
 277                  * Keep trying so that configuration data is
 278                  * written if/when any temporary filesystem
 279                  * resource issues are resolved.
 280                  */
 281                 if (target->spa_ccw_fail_time == 0) {
 282                         zfs_ereport_post(FM_EREPORT_ZFS_CONFIG_CACHE_WRITE,
 283                             target, NULL, NULL, 0, 0);
 284                 }
 285                 target->spa_ccw_fail_time = gethrtime();
 286                 spa_async_request(target, SPA_ASYNC_CONFIG_UPDATE);
 287         } else {
 288                 /*
 289                  * Do not rate limit future attempts to update
 290                  * the config cache.
 291                  */
 292                 target->spa_ccw_fail_time = 0;
 293         }
 294 
 295         /*
 296          * Remove any config entries older than the current one.
 297          */
 298         dp = list_head(&target->spa_config_list);
 299         while ((tdp = list_next(&target->spa_config_list, dp)) != NULL) {
 300                 list_remove(&target->spa_config_list, tdp);
 301                 if (tdp->scd_path != NULL)
 302                         spa_strfree(tdp->scd_path);
 303                 kmem_free(tdp, sizeof (spa_config_dirent_t));
 304         }
 305 
 306         spa_config_generation++;
 307 
 308         if (postsysevent)
 309                 spa_event_notify(target, NULL, NULL, ESC_ZFS_CONFIG_SYNC);
 310 }
 311 
 312 /*
 313  * Sigh.  Inside a local zone, we don't have access to /etc/zfs/zpool.cache,
 314  * and we don't want to allow the local zone to see all the pools anyway.
 315  * So we have to invent the ZFS_IOC_CONFIG ioctl to grab the configuration
 316  * information for all pool visible within the zone.
 317  */
 318 nvlist_t *
 319 spa_all_configs(uint64_t *generation)
 320 {
 321         nvlist_t *pools;
 322         spa_t *spa = NULL;
 323 
 324         if (*generation == spa_config_generation)
 325                 return (NULL);
 326 
 327         pools = fnvlist_alloc();
 328 
 329         mutex_enter(&spa_namespace_lock);
 330         while ((spa = spa_next(spa)) != NULL) {
 331                 if (INGLOBALZONE(curproc) ||
 332                     zone_dataset_visible(spa_name(spa), NULL)) {
 333                         mutex_enter(&spa->spa_props_lock);
 334                         fnvlist_add_nvlist(pools, spa_name(spa),
 335                             spa->spa_config);
 336                         mutex_exit(&spa->spa_props_lock);
 337                 }
 338         }
 339         *generation = spa_config_generation;
 340         mutex_exit(&spa_namespace_lock);
 341 
 342         return (pools);
 343 }
 344 
 345 void
 346 spa_config_set(spa_t *spa, nvlist_t *config)
 347 {
 348         mutex_enter(&spa->spa_props_lock);
 349         nvlist_free(spa->spa_config);
 350         spa->spa_config = config;
 351         mutex_exit(&spa->spa_props_lock);
 352 }
 353 
 354 /*
 355  * Generate the pool's configuration based on the current in-core state.
 356  *
 357  * We infer whether to generate a complete config or just one top-level config
 358  * based on whether vd is the root vdev.
 359  */
 360 nvlist_t *
 361 spa_config_generate(spa_t *spa, vdev_t *vd, uint64_t txg, int getstats)
 362 {
 363         nvlist_t *config, *nvroot;
 364         vdev_t *rvd = spa->spa_root_vdev;
 365         unsigned long hostid = 0;
 366         boolean_t locked = B_FALSE;
 367         uint64_t split_guid;
 368 
 369         if (vd == NULL) {
 370                 vd = rvd;
 371                 locked = B_TRUE;
 372                 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
 373         }
 374 
 375         ASSERT(spa_config_held(spa, SCL_CONFIG | SCL_STATE, RW_READER) ==
 376             (SCL_CONFIG | SCL_STATE));
 377 
 378         /*
 379          * If txg is -1, report the current value of spa->spa_config_txg.
 380          */
 381         if (txg == -1ULL)
 382                 txg = spa->spa_config_txg;
 383 
 384         config = fnvlist_alloc();
 385 
 386         fnvlist_add_uint64(config, ZPOOL_CONFIG_VERSION, spa_version(spa));
 387         fnvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME, spa_name(spa));
 388         fnvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE, spa_state(spa));
 389         fnvlist_add_uint64(config, ZPOOL_CONFIG_POOL_TXG, txg);
 390         fnvlist_add_uint64(config, ZPOOL_CONFIG_POOL_GUID, spa_guid(spa));
 391         if (spa->spa_comment != NULL) {
 392                 fnvlist_add_string(config, ZPOOL_CONFIG_COMMENT,
 393                     spa->spa_comment);
 394         }
 395 
 396 #ifdef  _KERNEL
 397         hostid = zone_get_hostid(NULL);
 398 #else   /* _KERNEL */
 399         /*
 400          * We're emulating the system's hostid in userland, so we can't use
 401          * zone_get_hostid().
 402          */
 403         (void) ddi_strtoul(hw_serial, NULL, 10, &hostid);
 404 #endif  /* _KERNEL */
 405         if (hostid != 0) {
 406                 fnvlist_add_uint64(config, ZPOOL_CONFIG_HOSTID, hostid);
 407         }
 408         fnvlist_add_string(config, ZPOOL_CONFIG_HOSTNAME, utsname.nodename);
 409 
 410         int config_gen_flags = 0;
 411         if (vd != rvd) {
 412                 fnvlist_add_uint64(config, ZPOOL_CONFIG_TOP_GUID,
 413                     vd->vdev_top->vdev_guid);
 414                 fnvlist_add_uint64(config, ZPOOL_CONFIG_GUID,
 415                     vd->vdev_guid);
 416                 if (vd->vdev_isspare) {
 417                         fnvlist_add_uint64(config,
 418                             ZPOOL_CONFIG_IS_SPARE, 1ULL);
 419                 }
 420                 if (vd->vdev_isspecial)
 421                         fnvlist_add_uint64(config,
 422                             ZPOOL_CONFIG_IS_SPECIAL, 1ULL);
 423                 if (vd->vdev_islog) {
 424                         fnvlist_add_uint64(config,
 425                             ZPOOL_CONFIG_IS_LOG, 1ULL);
 426                 }
 427                 vd = vd->vdev_top;           /* label contains top config */
 428         } else {
 429                 /*
 430                  * Only add the (potentially large) split information
 431                  * in the mos config, and not in the vdev labels
 432                  */
 433                 if (spa->spa_config_splitting != NULL)
 434                         fnvlist_add_nvlist(config, ZPOOL_CONFIG_SPLIT,
 435                             spa->spa_config_splitting);
 436                 fnvlist_add_boolean(config,
 437                     ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS);
 438 
 439                 config_gen_flags |= VDEV_CONFIG_MOS;
 440         }
 441 
 442         /*
 443          * Add the top-level config.  We even add this on pools which
 444          * don't support holes in the namespace.
 445          */
 446         vdev_top_config_generate(spa, config);
 447 
 448         /*
 449          * If we're splitting, record the original pool's guid.
 450          */
 451         if (spa->spa_config_splitting != NULL &&
 452             nvlist_lookup_uint64(spa->spa_config_splitting,
 453             ZPOOL_CONFIG_SPLIT_GUID, &split_guid) == 0) {
 454                 fnvlist_add_uint64(config, ZPOOL_CONFIG_SPLIT_GUID,
 455                     split_guid);
 456         }
 457 
 458         nvroot = vdev_config_generate(spa, vd, getstats, config_gen_flags);
 459         fnvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot);
 460         nvlist_free(nvroot);
 461 
 462         /* If we're getting stats, calculate trim progress from leaf vdevs. */
 463         if (getstats) {
 464                 uint64_t prog, rate, start_time, stop_time;
 465 
 466                 spa_get_trim_prog(spa, &prog, &rate, &start_time, &stop_time);
 467                 fnvlist_add_uint64(config, ZPOOL_CONFIG_TRIM_PROG, prog);
 468                 fnvlist_add_uint64(config, ZPOOL_CONFIG_TRIM_RATE, rate);
 469                 fnvlist_add_uint64(config, ZPOOL_CONFIG_TRIM_START_TIME,
 470                     start_time);
 471                 fnvlist_add_uint64(config, ZPOOL_CONFIG_TRIM_STOP_TIME,
 472                     stop_time);
 473         }
 474 
 475         /*
 476          * Store what's necessary for reading the MOS in the label.
 477          */
 478         fnvlist_add_nvlist(config, ZPOOL_CONFIG_FEATURES_FOR_READ,
 479             spa->spa_label_features);
 480 
 481         if (getstats && spa_load_state(spa) == SPA_LOAD_NONE) {
 482                 ddt_histogram_t *ddh;
 483                 ddt_stat_t *dds;
 484                 ddt_object_t *ddo;
 485 
 486                 ddh = kmem_zalloc(sizeof (ddt_histogram_t), KM_SLEEP);
 487                 ddt_get_dedup_histogram(spa, ddh);
 488                 fnvlist_add_uint64_array(config,
 489                     ZPOOL_CONFIG_DDT_HISTOGRAM,
 490                     (uint64_t *)ddh, sizeof (*ddh) / sizeof (uint64_t));
 491                 kmem_free(ddh, sizeof (ddt_histogram_t));
 492 
 493                 ddo = kmem_zalloc(sizeof (ddt_object_t), KM_SLEEP);
 494                 ddt_get_dedup_object_stats(spa, ddo);
 495                 fnvlist_add_uint64_array(config,
 496                     ZPOOL_CONFIG_DDT_OBJ_STATS,
 497                     (uint64_t *)ddo, sizeof (*ddo) / sizeof (uint64_t));
 498                 kmem_free(ddo, sizeof (ddt_object_t));
 499 
 500                 dds = kmem_zalloc(sizeof (ddt_stat_t), KM_SLEEP);
 501                 ddt_get_dedup_stats(spa, dds);
 502                 fnvlist_add_uint64_array(config,
 503                     ZPOOL_CONFIG_DDT_STATS,
 504                     (uint64_t *)dds, sizeof (*dds) / sizeof (uint64_t));
 505                 kmem_free(dds, sizeof (ddt_stat_t));
 506         }
 507 
 508         if (locked)
 509                 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
 510 
 511         return (config);
 512 }
 513 
 514 /*
 515  * Update all disk labels, generate a fresh config based on the current
 516  * in-core state, and sync the global config cache (do not sync the config
 517  * cache if this is a booting rootpool).
 518  */
 519 void
 520 spa_config_update(spa_t *spa, int what)
 521 {
 522         vdev_t *rvd = spa->spa_root_vdev;
 523         uint64_t txg;
 524         int c;
 525 
 526         ASSERT(MUTEX_HELD(&spa_namespace_lock));
 527 
 528         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
 529         txg = spa_last_synced_txg(spa) + 1;
 530         if (what == SPA_CONFIG_UPDATE_POOL) {
 531                 vdev_config_dirty(rvd);
 532         } else {
 533                 /*
 534                  * If we have top-level vdevs that were added but have
 535                  * not yet been prepared for allocation, do that now.
 536                  * (It's safe now because the config cache is up to date,
 537                  * so it will be able to translate the new DVAs.)
 538                  * See comments in spa_vdev_add() for full details.
 539                  */
 540                 for (c = 0; c < rvd->vdev_children; c++) {
 541                         vdev_t *tvd = rvd->vdev_child[c];
 542                         if (tvd->vdev_ms_array == 0)
 543                                 vdev_metaslab_set_size(tvd);
 544                         vdev_expand(tvd, txg);
 545                 }
 546         }
 547         spa_config_exit(spa, SCL_ALL, FTAG);
 548 
 549         /*
 550          * Wait for the mosconfig to be regenerated and synced.
 551          */
 552         txg_wait_synced(spa->spa_dsl_pool, txg);
 553 
 554         /*
 555          * Update the global config cache to reflect the new mosconfig.
 556          */
 557         if (!spa->spa_is_root)
 558                 spa_config_sync(spa, B_FALSE, what != SPA_CONFIG_UPDATE_POOL);
 559 
 560         if (what == SPA_CONFIG_UPDATE_POOL)
 561                 spa_config_update(spa, SPA_CONFIG_UPDATE_VDEVS);
 562 }