xref: /freebsd/sys/contrib/openzfs/module/zfs/spa_config.c (revision 36c970ed985ff3dd5443db4bf2aa58799028512c)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * CDDL HEADER START
4  *
5  * The contents of this file are subject to the terms of the
6  * Common Development and Distribution License (the "License").
7  * You may not use this file except in compliance with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or https://opensource.org/licenses/CDDL-1.0.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 
23 /*
24  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
25  * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
26  * Copyright (c) 2011, 2020 by Delphix. All rights reserved.
27  * Copyright 2017 Joyent, Inc.
28  * Copyright (c) 2021, Colm Buckley <colm@tuatha.org>
29  */
30 
31 #include <sys/spa.h>
32 #include <sys/file.h>
33 #include <sys/fm/fs/zfs.h>
34 #include <sys/spa_impl.h>
35 #include <sys/nvpair.h>
36 #include <sys/fs/zfs.h>
37 #include <sys/vdev_impl.h>
38 #include <sys/zfs_ioctl.h>
39 #include <sys/systeminfo.h>
40 #include <sys/sunddi.h>
41 #include <sys/zfeature.h>
42 #include <sys/zfs_file.h>
43 #include <sys/zfs_context.h>
44 #ifdef _KERNEL
45 #include <sys/zone.h>
46 #endif
47 
48 /*
49  * Pool configuration repository.
50  *
51  * Pool configuration is stored as a packed nvlist on the filesystem.  When
52  * pools are imported they are added to the /etc/zfs/zpool.cache file and
53  * removed from it when exported.  For each cache file, we have a single nvlist
54  * which holds all the configuration information.  Pools can also have the
55  * 'cachefile' property set which allows this config to be stored in an
56  * alternate location under the control of external software.
57  *
58  * The kernel independantly maintains an AVL tree of imported pools.  See the
59  * "SPA locking" comment in spa.c.  Whenever a pool configuration is modified
60  * we call spa_write_cachefile() which walks through all the active pools and
61  * writes the updated configuration to to /etc/zfs/zpool.cache file.
62  */
63 
64 static uint64_t spa_config_generation = 1;
65 
66 /*
67  * This can be overridden in userland to preserve an alternate namespace for
68  * userland pools when doing testing.
69  */
70 char *spa_config_path = (char *)ZPOOL_CACHE;
71 
72 static int
spa_config_remove(spa_config_dirent_t * dp)73 spa_config_remove(spa_config_dirent_t *dp)
74 {
75 	int error = 0;
76 
77 	/*
78 	 * Remove the cache file.  If zfs_file_unlink() in not supported by the
79 	 * platform fallback to truncating the file which is functionally
80 	 * equivalent.
81 	 */
82 	error = zfs_file_unlink(dp->scd_path);
83 	if (error == EOPNOTSUPP) {
84 		int flags = O_RDWR | O_TRUNC;
85 		zfs_file_t *fp;
86 
87 		error = zfs_file_open(dp->scd_path, flags, 0644, &fp);
88 		if (error == 0) {
89 			(void) zfs_file_fsync(fp, O_SYNC);
90 			(void) zfs_file_close(fp);
91 		}
92 	}
93 
94 	return (error);
95 }
96 
97 static int
spa_config_write(spa_config_dirent_t * dp,nvlist_t * nvl)98 spa_config_write(spa_config_dirent_t *dp, nvlist_t *nvl)
99 {
100 	size_t buflen;
101 	char *buf;
102 	int oflags = O_RDWR | O_TRUNC | O_CREAT | O_LARGEFILE;
103 	char *temp;
104 	int err;
105 	zfs_file_t *fp;
106 
107 	/*
108 	 * If the nvlist is empty (NULL), then remove the old cachefile.
109 	 */
110 	if (nvl == NULL) {
111 		err = spa_config_remove(dp);
112 		if (err == ENOENT)
113 			err = 0;
114 
115 		return (err);
116 	}
117 
118 	/*
119 	 * Pack the configuration into a buffer.
120 	 */
121 	buf = fnvlist_pack(nvl, &buflen);
122 	temp = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
123 
124 	/*
125 	 * Write the configuration to disk.  Due to the complexity involved
126 	 * in performing a rename and remove from within the kernel the file
127 	 * is instead truncated and overwritten in place.  This way we always
128 	 * have a consistent view of the data or a zero length file.
129 	 */
130 	err = zfs_file_open(dp->scd_path, oflags, 0644, &fp);
131 	if (err == 0) {
132 		err = zfs_file_write(fp, buf, buflen, NULL);
133 		if (err == 0)
134 			err = zfs_file_fsync(fp, O_SYNC);
135 
136 		zfs_file_close(fp);
137 		if (err)
138 			(void) spa_config_remove(dp);
139 	}
140 	fnvlist_pack_free(buf, buflen);
141 	kmem_free(temp, MAXPATHLEN);
142 	return (err);
143 }
144 
145 /*
146  * Synchronize pool configuration to disk.  This must be called with the
147  * namespace lock held. Synchronizing the pool cache is typically done after
148  * the configuration has been synced to the MOS. This exposes a window where
149  * the MOS config will have been updated but the cache file has not. If
150  * the system were to crash at that instant then the cached config may not
151  * contain the correct information to open the pool and an explicit import
152  * would be required.
153  */
154 void
spa_write_cachefile(spa_t * target,boolean_t removing,boolean_t postsysevent,boolean_t postblkidevent)155 spa_write_cachefile(spa_t *target, boolean_t removing, boolean_t postsysevent,
156     boolean_t postblkidevent)
157 {
158 	spa_config_dirent_t *dp, *tdp;
159 	nvlist_t *nvl;
160 	const char *pool_name;
161 	boolean_t ccw_failure;
162 	int error = 0;
163 
164 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
165 
166 	if (!(spa_mode_global & SPA_MODE_WRITE))
167 		return;
168 
169 	/*
170 	 * Iterate over all cachefiles for the pool, past or present.  When the
171 	 * cachefile is changed, the new one is pushed onto this list, allowing
172 	 * us to update previous cachefiles that no longer contain this pool.
173 	 */
174 	ccw_failure = B_FALSE;
175 	for (dp = list_head(&target->spa_config_list); dp != NULL;
176 	    dp = list_next(&target->spa_config_list, dp)) {
177 		spa_t *spa = NULL;
178 		if (dp->scd_path == NULL)
179 			continue;
180 
181 		/*
182 		 * Iterate over all pools, adding any matching pools to 'nvl'.
183 		 */
184 		nvl = NULL;
185 		while ((spa = spa_next(spa)) != NULL) {
186 			/*
187 			 * Skip over our own pool if we're about to remove
188 			 * ourselves from the spa namespace or any pool that
189 			 * is readonly. Since we cannot guarantee that a
190 			 * readonly pool would successfully import upon reboot,
191 			 * we don't allow them to be written to the cache file.
192 			 */
193 			if ((spa == target && removing) ||
194 			    !spa_writeable(spa))
195 				continue;
196 
197 			mutex_enter(&spa->spa_props_lock);
198 			tdp = list_head(&spa->spa_config_list);
199 			if (spa->spa_config == NULL ||
200 			    tdp == NULL ||
201 			    tdp->scd_path == NULL ||
202 			    strcmp(tdp->scd_path, dp->scd_path) != 0) {
203 				mutex_exit(&spa->spa_props_lock);
204 				continue;
205 			}
206 
207 			if (nvl == NULL)
208 				nvl = fnvlist_alloc();
209 
210 			if (spa->spa_import_flags & ZFS_IMPORT_TEMP_NAME)
211 				pool_name = fnvlist_lookup_string(
212 				    spa->spa_config, ZPOOL_CONFIG_POOL_NAME);
213 			else
214 				pool_name = spa_name(spa);
215 
216 			fnvlist_add_nvlist(nvl, pool_name, spa->spa_config);
217 			mutex_exit(&spa->spa_props_lock);
218 		}
219 
220 		error = spa_config_write(dp, nvl);
221 		if (error != 0)
222 			ccw_failure = B_TRUE;
223 		nvlist_free(nvl);
224 	}
225 
226 	if (ccw_failure) {
227 		/*
228 		 * Keep trying so that configuration data is
229 		 * written if/when any temporary filesystem
230 		 * resource issues are resolved.
231 		 */
232 		if (target->spa_ccw_fail_time == 0) {
233 			(void) zfs_ereport_post(
234 			    FM_EREPORT_ZFS_CONFIG_CACHE_WRITE,
235 			    target, NULL, NULL, NULL, 0);
236 		}
237 		target->spa_ccw_fail_time = gethrtime();
238 		spa_async_request(target, SPA_ASYNC_CONFIG_UPDATE);
239 	} else {
240 		/*
241 		 * Do not rate limit future attempts to update
242 		 * the config cache.
243 		 */
244 		target->spa_ccw_fail_time = 0;
245 	}
246 
247 	/*
248 	 * Remove any config entries older than the current one.
249 	 */
250 	dp = list_head(&target->spa_config_list);
251 	while ((tdp = list_next(&target->spa_config_list, dp)) != NULL) {
252 		list_remove(&target->spa_config_list, tdp);
253 		if (tdp->scd_path != NULL)
254 			spa_strfree(tdp->scd_path);
255 		kmem_free(tdp, sizeof (spa_config_dirent_t));
256 	}
257 
258 	spa_config_generation++;
259 
260 	if (postsysevent)
261 		spa_event_notify(target, NULL, NULL, ESC_ZFS_CONFIG_SYNC);
262 
263 	/*
264 	 * Post udev event to sync blkid information if the pool is created
265 	 * or a new vdev is added to the pool.
266 	 */
267 	if ((target->spa_root_vdev) && postblkidevent) {
268 		vdev_post_kobj_evt(target->spa_root_vdev);
269 		for (int i = 0; i < target->spa_l2cache.sav_count; i++)
270 			vdev_post_kobj_evt(target->spa_l2cache.sav_vdevs[i]);
271 		for (int i = 0; i < target->spa_spares.sav_count; i++)
272 			vdev_post_kobj_evt(target->spa_spares.sav_vdevs[i]);
273 	}
274 }
275 
276 /*
277  * Sigh.  Inside a local zone, we don't have access to /etc/zfs/zpool.cache,
278  * and we don't want to allow the local zone to see all the pools anyway.
279  * So we have to invent the ZFS_IOC_CONFIG ioctl to grab the configuration
280  * information for all pool visible within the zone.
281  */
282 int
spa_all_configs(uint64_t * generation,nvlist_t ** pools)283 spa_all_configs(uint64_t *generation, nvlist_t **pools)
284 {
285 	spa_t *spa = NULL;
286 
287 	if (*generation == spa_config_generation)
288 		return (SET_ERROR(EEXIST));
289 
290 	int error = mutex_enter_interruptible(&spa_namespace_lock);
291 	if (error)
292 		return (SET_ERROR(EINTR));
293 
294 	*pools = fnvlist_alloc();
295 	while ((spa = spa_next(spa)) != NULL) {
296 		if (INGLOBALZONE(curproc) ||
297 		    zone_dataset_visible(spa_name(spa), NULL)) {
298 			mutex_enter(&spa->spa_props_lock);
299 			fnvlist_add_nvlist(*pools, spa_name(spa),
300 			    spa->spa_config);
301 			mutex_exit(&spa->spa_props_lock);
302 		}
303 	}
304 	*generation = spa_config_generation;
305 	mutex_exit(&spa_namespace_lock);
306 
307 	return (0);
308 }
309 
310 void
spa_config_set(spa_t * spa,nvlist_t * config)311 spa_config_set(spa_t *spa, nvlist_t *config)
312 {
313 	mutex_enter(&spa->spa_props_lock);
314 	if (spa->spa_config != NULL && spa->spa_config != config)
315 		nvlist_free(spa->spa_config);
316 	spa->spa_config = config;
317 	mutex_exit(&spa->spa_props_lock);
318 }
319 
320 /*
321  * Generate the pool's configuration based on the current in-core state.
322  *
323  * We infer whether to generate a complete config or just one top-level config
324  * based on whether vd is the root vdev.
325  */
326 nvlist_t *
spa_config_generate(spa_t * spa,vdev_t * vd,uint64_t txg,int getstats)327 spa_config_generate(spa_t *spa, vdev_t *vd, uint64_t txg, int getstats)
328 {
329 	nvlist_t *config, *nvroot;
330 	vdev_t *rvd = spa->spa_root_vdev;
331 	unsigned long hostid = 0;
332 	boolean_t locked = B_FALSE;
333 	uint64_t split_guid;
334 	const char *pool_name;
335 
336 	if (vd == NULL) {
337 		vd = rvd;
338 		locked = B_TRUE;
339 		spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
340 	}
341 
342 	ASSERT(spa_config_held(spa, SCL_CONFIG | SCL_STATE, RW_READER) ==
343 	    (SCL_CONFIG | SCL_STATE));
344 
345 	/*
346 	 * If txg is -1, report the current value of spa->spa_config_txg.
347 	 */
348 	if (txg == -1ULL)
349 		txg = spa->spa_config_txg;
350 
351 	/*
352 	 * Originally, users had to handle spa namespace collisions by either
353 	 * exporting the already imported pool or by specifying a new name for
354 	 * the pool with a conflicting name. In the case of root pools from
355 	 * virtual guests, neither approach to collision resolution is
356 	 * reasonable. This is addressed by extending the new name syntax with
357 	 * an option to specify that the new name is temporary. When specified,
358 	 * ZFS_IMPORT_TEMP_NAME will be set in spa->spa_import_flags to tell us
359 	 * to use the previous name, which we do below.
360 	 */
361 	if (spa->spa_import_flags & ZFS_IMPORT_TEMP_NAME) {
362 		VERIFY0(nvlist_lookup_string(spa->spa_config,
363 		    ZPOOL_CONFIG_POOL_NAME, &pool_name));
364 	} else
365 		pool_name = spa_name(spa);
366 
367 	config = fnvlist_alloc();
368 
369 	fnvlist_add_uint64(config, ZPOOL_CONFIG_VERSION, spa_version(spa));
370 	fnvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME, pool_name);
371 	fnvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE, spa_state(spa));
372 	fnvlist_add_uint64(config, ZPOOL_CONFIG_POOL_TXG, txg);
373 	fnvlist_add_uint64(config, ZPOOL_CONFIG_POOL_GUID, spa_guid(spa));
374 	fnvlist_add_uint64(config, ZPOOL_CONFIG_ERRATA, spa->spa_errata);
375 	fnvlist_add_uint64(config, ZPOOL_CONFIG_MIN_ALLOC, spa->spa_min_alloc);
376 	fnvlist_add_uint64(config, ZPOOL_CONFIG_MAX_ALLOC, spa->spa_max_alloc);
377 	if (spa->spa_comment != NULL)
378 		fnvlist_add_string(config, ZPOOL_CONFIG_COMMENT,
379 		    spa->spa_comment);
380 	if (spa->spa_compatibility != NULL)
381 		fnvlist_add_string(config, ZPOOL_CONFIG_COMPATIBILITY,
382 		    spa->spa_compatibility);
383 
384 	hostid = spa_get_hostid(spa);
385 	if (hostid != 0)
386 		fnvlist_add_uint64(config, ZPOOL_CONFIG_HOSTID, hostid);
387 	fnvlist_add_string(config, ZPOOL_CONFIG_HOSTNAME, utsname()->nodename);
388 
389 	int config_gen_flags = 0;
390 	if (vd != rvd) {
391 		fnvlist_add_uint64(config, ZPOOL_CONFIG_TOP_GUID,
392 		    vd->vdev_top->vdev_guid);
393 		fnvlist_add_uint64(config, ZPOOL_CONFIG_GUID,
394 		    vd->vdev_guid);
395 		if (vd->vdev_isspare)
396 			fnvlist_add_uint64(config,
397 			    ZPOOL_CONFIG_IS_SPARE, 1ULL);
398 		if (vd->vdev_islog)
399 			fnvlist_add_uint64(config,
400 			    ZPOOL_CONFIG_IS_LOG, 1ULL);
401 		vd = vd->vdev_top;		/* label contains top config */
402 	} else {
403 		/*
404 		 * Only add the (potentially large) split information
405 		 * in the mos config, and not in the vdev labels
406 		 */
407 		if (spa->spa_config_splitting != NULL)
408 			fnvlist_add_nvlist(config, ZPOOL_CONFIG_SPLIT,
409 			    spa->spa_config_splitting);
410 
411 		fnvlist_add_boolean(config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS);
412 
413 		config_gen_flags |= VDEV_CONFIG_MOS;
414 	}
415 
416 	/*
417 	 * Add the top-level config.  We even add this on pools which
418 	 * don't support holes in the namespace.
419 	 */
420 	vdev_top_config_generate(spa, config);
421 
422 	/*
423 	 * If we're splitting, record the original pool's guid.
424 	 */
425 	if (spa->spa_config_splitting != NULL &&
426 	    nvlist_lookup_uint64(spa->spa_config_splitting,
427 	    ZPOOL_CONFIG_SPLIT_GUID, &split_guid) == 0) {
428 		fnvlist_add_uint64(config, ZPOOL_CONFIG_SPLIT_GUID, split_guid);
429 	}
430 
431 	nvroot = vdev_config_generate(spa, vd, getstats, config_gen_flags);
432 	fnvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot);
433 	nvlist_free(nvroot);
434 
435 	/*
436 	 * Store what's necessary for reading the MOS in the label.
437 	 */
438 	fnvlist_add_nvlist(config, ZPOOL_CONFIG_FEATURES_FOR_READ,
439 	    spa->spa_label_features);
440 
441 	if (getstats && spa_load_state(spa) == SPA_LOAD_NONE) {
442 		ddt_histogram_t *ddh;
443 		ddt_stat_t *dds;
444 		ddt_object_t *ddo;
445 
446 		ddh = kmem_zalloc(sizeof (ddt_histogram_t), KM_SLEEP);
447 		ddt_get_dedup_histogram(spa, ddh);
448 		fnvlist_add_uint64_array(config,
449 		    ZPOOL_CONFIG_DDT_HISTOGRAM,
450 		    (uint64_t *)ddh, sizeof (*ddh) / sizeof (uint64_t));
451 		kmem_free(ddh, sizeof (ddt_histogram_t));
452 
453 		ddo = kmem_zalloc(sizeof (ddt_object_t), KM_SLEEP);
454 		ddt_get_dedup_object_stats(spa, ddo);
455 		fnvlist_add_uint64_array(config,
456 		    ZPOOL_CONFIG_DDT_OBJ_STATS,
457 		    (uint64_t *)ddo, sizeof (*ddo) / sizeof (uint64_t));
458 		kmem_free(ddo, sizeof (ddt_object_t));
459 
460 		dds = kmem_zalloc(sizeof (ddt_stat_t), KM_SLEEP);
461 		ddt_get_dedup_stats(spa, dds);
462 		fnvlist_add_uint64_array(config,
463 		    ZPOOL_CONFIG_DDT_STATS,
464 		    (uint64_t *)dds, sizeof (*dds) / sizeof (uint64_t));
465 		kmem_free(dds, sizeof (ddt_stat_t));
466 	}
467 
468 	if (locked)
469 		spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
470 
471 	return (config);
472 }
473 
474 /*
475  * Update all disk labels, generate a fresh config based on the current
476  * in-core state, and sync the global config cache (do not sync the config
477  * cache if this is a booting rootpool).
478  */
479 void
spa_config_update(spa_t * spa,int what)480 spa_config_update(spa_t *spa, int what)
481 {
482 	vdev_t *rvd = spa->spa_root_vdev;
483 	uint64_t txg;
484 	int c;
485 
486 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
487 
488 	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
489 	txg = spa_last_synced_txg(spa) + 1;
490 	if (what == SPA_CONFIG_UPDATE_POOL) {
491 		vdev_config_dirty(rvd);
492 	} else {
493 		/*
494 		 * If we have top-level vdevs that were added but have
495 		 * not yet been prepared for allocation, do that now.
496 		 * (It's safe now because the config cache is up to date,
497 		 * so it will be able to translate the new DVAs.)
498 		 * See comments in spa_vdev_add() for full details.
499 		 */
500 		for (c = 0; c < rvd->vdev_children; c++) {
501 			vdev_t *tvd = rvd->vdev_child[c];
502 
503 			/*
504 			 * Explicitly skip vdevs that are indirect or
505 			 * log vdevs that are being removed. The reason
506 			 * is that both of those can have vdev_ms_array
507 			 * set to 0 and we wouldn't want to change their
508 			 * metaslab size nor call vdev_expand() on them.
509 			 */
510 			if (!vdev_is_concrete(tvd) ||
511 			    (tvd->vdev_islog && tvd->vdev_removing))
512 				continue;
513 
514 			if (tvd->vdev_ms_array == 0)
515 				vdev_metaslab_set_size(tvd);
516 			vdev_expand(tvd, txg);
517 		}
518 	}
519 	spa_config_exit(spa, SCL_ALL, FTAG);
520 
521 	/*
522 	 * Wait for the mosconfig to be regenerated and synced.
523 	 */
524 	txg_wait_synced(spa->spa_dsl_pool, txg);
525 
526 	/*
527 	 * Update the global config cache to reflect the new mosconfig.
528 	 */
529 	if (!spa->spa_is_root) {
530 		spa_write_cachefile(spa, B_FALSE,
531 		    what != SPA_CONFIG_UPDATE_POOL,
532 		    what != SPA_CONFIG_UPDATE_POOL);
533 	}
534 
535 	if (what == SPA_CONFIG_UPDATE_POOL)
536 		spa_config_update(spa, SPA_CONFIG_UPDATE_VDEVS);
537 }
538 
539 EXPORT_SYMBOL(spa_all_configs);
540 EXPORT_SYMBOL(spa_config_set);
541 EXPORT_SYMBOL(spa_config_generate);
542 EXPORT_SYMBOL(spa_config_update);
543 
544 #ifdef __linux__
545 /* string sysctls require a char array on FreeBSD */
546 ZFS_MODULE_PARAM(zfs_spa, spa_, config_path, STRING, ZMOD_RD,
547 	"SPA config file (/etc/zfs/zpool.cache)");
548 #endif
549