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