1 /*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21
22 /*
23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright (c) 2011, 2019 by Delphix. All rights reserved.
25 * Copyright (c) 2015, Nexenta Systems, Inc. All rights reserved.
26 * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
27 * Copyright 2013 Saso Kiselkov. All rights reserved.
28 * Copyright (c) 2014 Integros [integros.com]
29 * Copyright 2016 Toomas Soome <tsoome@me.com>
30 * Copyright (c) 2017, 2019, Datto Inc. All rights reserved.
31 * Copyright 2019 Joyent, Inc.
32 * Copyright (c) 2017, Intel Corporation.
33 * Copyright 2020 Joshua M. Clulow <josh@sysmgr.org>
34 * Copyright 2021 OmniOS Community Edition (OmniOSce) Association.
35 * Copyright 2022 Oxide Computer Company
36 * Copyright 2023 MNX Cloud, Inc.
37 */
38
39 /*
40 * SPA: Storage Pool Allocator
41 *
42 * This file contains all the routines used when modifying on-disk SPA state.
43 * This includes opening, importing, destroying, exporting a pool, and syncing a
44 * pool.
45 */
46
47 #include <sys/zfs_context.h>
48 #include <sys/fm/fs/zfs.h>
49 #include <sys/spa_impl.h>
50 #include <sys/zio.h>
51 #include <sys/zio_checksum.h>
52 #include <sys/dmu.h>
53 #include <sys/dmu_tx.h>
54 #include <sys/zap.h>
55 #include <sys/zil.h>
56 #include <sys/ddt.h>
57 #include <sys/vdev_impl.h>
58 #include <sys/vdev_removal.h>
59 #include <sys/vdev_indirect_mapping.h>
60 #include <sys/vdev_indirect_births.h>
61 #include <sys/vdev_initialize.h>
62 #include <sys/vdev_trim.h>
63 #include <sys/metaslab.h>
64 #include <sys/metaslab_impl.h>
65 #include <sys/mmp.h>
66 #include <sys/uberblock_impl.h>
67 #include <sys/txg.h>
68 #include <sys/avl.h>
69 #include <sys/bpobj.h>
70 #include <sys/dmu_traverse.h>
71 #include <sys/dmu_objset.h>
72 #include <sys/unique.h>
73 #include <sys/dsl_pool.h>
74 #include <sys/dsl_dataset.h>
75 #include <sys/dsl_dir.h>
76 #include <sys/dsl_prop.h>
77 #include <sys/dsl_synctask.h>
78 #include <sys/fs/zfs.h>
79 #include <sys/arc.h>
80 #include <sys/callb.h>
81 #include <sys/systeminfo.h>
82 #include <sys/spa_boot.h>
83 #include <sys/zfs_ioctl.h>
84 #include <sys/dsl_scan.h>
85 #include <sys/zfeature.h>
86 #include <sys/dsl_destroy.h>
87 #include <sys/abd.h>
88
89 #ifdef _KERNEL
90 #include <sys/bootprops.h>
91 #include <sys/callb.h>
92 #include <sys/cpupart.h>
93 #include <sys/pool.h>
94 #include <sys/sysdc.h>
95 #include <sys/zone.h>
96 #endif /* _KERNEL */
97
98 #include "zfs_prop.h"
99 #include "zfs_comutil.h"
100
101 /*
102 * The interval, in seconds, at which failed configuration cache file writes
103 * should be retried.
104 */
105 int zfs_ccw_retry_interval = 300;
106
107 typedef enum zti_modes {
108 ZTI_MODE_FIXED, /* value is # of threads (min 1) */
109 ZTI_MODE_BATCH, /* cpu-intensive; value is ignored */
110 ZTI_MODE_NULL, /* don't create a taskq */
111 ZTI_NMODES
112 } zti_modes_t;
113
114 #define ZTI_P(n, q) { ZTI_MODE_FIXED, (n), (q) }
115 #define ZTI_BATCH { ZTI_MODE_BATCH, 0, 1 }
116 #define ZTI_NULL { ZTI_MODE_NULL, 0, 0 }
117
118 #define ZTI_N(n) ZTI_P(n, 1)
119 #define ZTI_ONE ZTI_N(1)
120
121 typedef struct zio_taskq_info {
122 zti_modes_t zti_mode;
123 uint_t zti_value;
124 uint_t zti_count;
125 } zio_taskq_info_t;
126
127 static const char *const zio_taskq_types[ZIO_TASKQ_TYPES] = {
128 "issue", "issue_high", "intr", "intr_high"
129 };
130
131 /*
132 * This table defines the taskq settings for each ZFS I/O type. When
133 * initializing a pool, we use this table to create an appropriately sized
134 * taskq. Some operations are low volume and therefore have a small, static
135 * number of threads assigned to their taskqs using the ZTI_N(#) or ZTI_ONE
136 * macros. Other operations process a large amount of data; the ZTI_BATCH
137 * macro causes us to create a taskq oriented for throughput. Some operations
138 * are so high frequency and short-lived that the taskq itself can become a
139 * point of lock contention. The ZTI_P(#, #) macro indicates that we need an
140 * additional degree of parallelism specified by the number of threads per-
141 * taskq and the number of taskqs; when dispatching an event in this case, the
142 * particular taskq is chosen at random.
143 *
144 * The different taskq priorities are to handle the different contexts (issue
145 * and interrupt) and then to reserve threads for ZIO_PRIORITY_NOW I/Os that
146 * need to be handled with minimum delay.
147 */
148 const zio_taskq_info_t zio_taskqs[ZIO_TYPES][ZIO_TASKQ_TYPES] = {
149 /* ISSUE ISSUE_HIGH INTR INTR_HIGH */
150 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* NULL */
151 { ZTI_N(8), ZTI_NULL, ZTI_P(12, 8), ZTI_NULL }, /* READ */
152 { ZTI_BATCH, ZTI_N(5), ZTI_N(8), ZTI_N(5) }, /* WRITE */
153 { ZTI_P(12, 8), ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* FREE */
154 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* CLAIM */
155 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* IOCTL */
156 { ZTI_N(4), ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* TRIM */
157 };
158
159 static void spa_sync_version(void *arg, dmu_tx_t *tx);
160 static void spa_sync_props(void *arg, dmu_tx_t *tx);
161 static boolean_t spa_has_active_shared_spare(spa_t *spa);
162 static int spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport);
163 static void spa_vdev_resilver_done(spa_t *spa);
164
165 uint_t zio_taskq_batch_pct = 75; /* 1 thread per cpu in pset */
166 id_t zio_taskq_psrset_bind = PS_NONE;
167 boolean_t zio_taskq_sysdc = B_TRUE; /* use SDC scheduling class */
168 uint_t zio_taskq_basedc = 80; /* base duty cycle */
169
170 boolean_t spa_create_process = B_TRUE; /* no process ==> no sysdc */
171 extern int zfs_sync_pass_deferred_free;
172
173 /*
174 * Report any spa_load_verify errors found, but do not fail spa_load.
175 * This is used by zdb to analyze non-idle pools.
176 */
177 boolean_t spa_load_verify_dryrun = B_FALSE;
178
179 /*
180 * This (illegal) pool name is used when temporarily importing a spa_t in order
181 * to get the vdev stats associated with the imported devices.
182 */
183 #define TRYIMPORT_NAME "$import"
184
185 /*
186 * For debugging purposes: print out vdev tree during pool import.
187 */
188 boolean_t spa_load_print_vdev_tree = B_FALSE;
189
190 /*
191 * A non-zero value for zfs_max_missing_tvds means that we allow importing
192 * pools with missing top-level vdevs. This is strictly intended for advanced
193 * pool recovery cases since missing data is almost inevitable. Pools with
194 * missing devices can only be imported read-only for safety reasons, and their
195 * fail-mode will be automatically set to "continue".
196 *
197 * With 1 missing vdev we should be able to import the pool and mount all
198 * datasets. User data that was not modified after the missing device has been
199 * added should be recoverable. This means that snapshots created prior to the
200 * addition of that device should be completely intact.
201 *
202 * With 2 missing vdevs, some datasets may fail to mount since there are
203 * dataset statistics that are stored as regular metadata. Some data might be
204 * recoverable if those vdevs were added recently.
205 *
206 * With 3 or more missing vdevs, the pool is severely damaged and MOS entries
207 * may be missing entirely. Chances of data recovery are very low. Note that
208 * there are also risks of performing an inadvertent rewind as we might be
209 * missing all the vdevs with the latest uberblocks.
210 */
211 uint64_t zfs_max_missing_tvds = 0;
212
213 /*
214 * The parameters below are similar to zfs_max_missing_tvds but are only
215 * intended for a preliminary open of the pool with an untrusted config which
216 * might be incomplete or out-dated.
217 *
218 * We are more tolerant for pools opened from a cachefile since we could have
219 * an out-dated cachefile where a device removal was not registered.
220 * We could have set the limit arbitrarily high but in the case where devices
221 * are really missing we would want to return the proper error codes; we chose
222 * SPA_DVAS_PER_BP - 1 so that some copies of the MOS would still be available
223 * and we get a chance to retrieve the trusted config.
224 */
225 uint64_t zfs_max_missing_tvds_cachefile = SPA_DVAS_PER_BP - 1;
226
227 /*
228 * In the case where config was assembled by scanning device paths (/dev/dsks
229 * by default) we are less tolerant since all the existing devices should have
230 * been detected and we want spa_load to return the right error codes.
231 */
232 uint64_t zfs_max_missing_tvds_scan = 0;
233
234 /*
235 * Interval in seconds at which to poll spare vdevs for health.
236 * Setting this to zero disables spare polling.
237 * Set to three hours by default.
238 */
239 uint_t spa_spare_poll_interval_seconds = 60 * 60 * 3;
240
241 /*
242 * Debugging aid that pauses spa_sync() towards the end.
243 */
244 boolean_t zfs_pause_spa_sync = B_FALSE;
245
246 /*
247 * ==========================================================================
248 * SPA properties routines
249 * ==========================================================================
250 */
251
252 /*
253 * Add a (source=src, propname=propval) list to an nvlist.
254 */
255 static void
spa_prop_add_list(nvlist_t * nvl,zpool_prop_t prop,char * strval,uint64_t intval,zprop_source_t src)256 spa_prop_add_list(nvlist_t *nvl, zpool_prop_t prop, char *strval,
257 uint64_t intval, zprop_source_t src)
258 {
259 const char *propname = zpool_prop_to_name(prop);
260 nvlist_t *propval;
261
262 VERIFY(nvlist_alloc(&propval, NV_UNIQUE_NAME, KM_SLEEP) == 0);
263 VERIFY(nvlist_add_uint64(propval, ZPROP_SOURCE, src) == 0);
264
265 if (strval != NULL)
266 VERIFY(nvlist_add_string(propval, ZPROP_VALUE, strval) == 0);
267 else
268 VERIFY(nvlist_add_uint64(propval, ZPROP_VALUE, intval) == 0);
269
270 VERIFY(nvlist_add_nvlist(nvl, propname, propval) == 0);
271 nvlist_free(propval);
272 }
273
274 /*
275 * Get property values from the spa configuration.
276 */
277 static void
spa_prop_get_config(spa_t * spa,nvlist_t ** nvp)278 spa_prop_get_config(spa_t *spa, nvlist_t **nvp)
279 {
280 vdev_t *rvd = spa->spa_root_vdev;
281 dsl_pool_t *pool = spa->spa_dsl_pool;
282 uint64_t size, alloc, cap, version;
283 zprop_source_t src = ZPROP_SRC_NONE;
284 spa_config_dirent_t *dp;
285 metaslab_class_t *mc = spa_normal_class(spa);
286
287 ASSERT(MUTEX_HELD(&spa->spa_props_lock));
288
289 if (rvd != NULL) {
290 alloc = metaslab_class_get_alloc(mc);
291 alloc += metaslab_class_get_alloc(spa_special_class(spa));
292 alloc += metaslab_class_get_alloc(spa_dedup_class(spa));
293
294 size = metaslab_class_get_space(mc);
295 size += metaslab_class_get_space(spa_special_class(spa));
296 size += metaslab_class_get_space(spa_dedup_class(spa));
297
298 spa_prop_add_list(*nvp, ZPOOL_PROP_NAME, spa_name(spa), 0, src);
299 spa_prop_add_list(*nvp, ZPOOL_PROP_SIZE, NULL, size, src);
300 spa_prop_add_list(*nvp, ZPOOL_PROP_ALLOCATED, NULL, alloc, src);
301 spa_prop_add_list(*nvp, ZPOOL_PROP_FREE, NULL,
302 size - alloc, src);
303 spa_prop_add_list(*nvp, ZPOOL_PROP_CHECKPOINT, NULL,
304 spa->spa_checkpoint_info.sci_dspace, src);
305
306 spa_prop_add_list(*nvp, ZPOOL_PROP_FRAGMENTATION, NULL,
307 metaslab_class_fragmentation(mc), src);
308 spa_prop_add_list(*nvp, ZPOOL_PROP_EXPANDSZ, NULL,
309 metaslab_class_expandable_space(mc), src);
310 spa_prop_add_list(*nvp, ZPOOL_PROP_READONLY, NULL,
311 (spa_mode(spa) == FREAD), src);
312
313 cap = (size == 0) ? 0 : (alloc * 100 / size);
314 spa_prop_add_list(*nvp, ZPOOL_PROP_CAPACITY, NULL, cap, src);
315
316 spa_prop_add_list(*nvp, ZPOOL_PROP_DEDUPRATIO, NULL,
317 ddt_get_pool_dedup_ratio(spa), src);
318
319 spa_prop_add_list(*nvp, ZPOOL_PROP_HEALTH, NULL,
320 rvd->vdev_state, src);
321
322 version = spa_version(spa);
323 if (version == zpool_prop_default_numeric(ZPOOL_PROP_VERSION))
324 src = ZPROP_SRC_DEFAULT;
325 else
326 src = ZPROP_SRC_LOCAL;
327 spa_prop_add_list(*nvp, ZPOOL_PROP_VERSION, NULL, version, src);
328 }
329
330 if (pool != NULL) {
331 /*
332 * The $FREE directory was introduced in SPA_VERSION_DEADLISTS,
333 * when opening pools before this version freedir will be NULL.
334 */
335 if (pool->dp_free_dir != NULL) {
336 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING, NULL,
337 dsl_dir_phys(pool->dp_free_dir)->dd_used_bytes,
338 src);
339 } else {
340 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING,
341 NULL, 0, src);
342 }
343
344 if (pool->dp_leak_dir != NULL) {
345 spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED, NULL,
346 dsl_dir_phys(pool->dp_leak_dir)->dd_used_bytes,
347 src);
348 } else {
349 spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED,
350 NULL, 0, src);
351 }
352 }
353
354 spa_prop_add_list(*nvp, ZPOOL_PROP_GUID, NULL, spa_guid(spa), src);
355
356 if (spa->spa_comment != NULL) {
357 spa_prop_add_list(*nvp, ZPOOL_PROP_COMMENT, spa->spa_comment,
358 0, ZPROP_SRC_LOCAL);
359 }
360
361 if (spa->spa_root != NULL)
362 spa_prop_add_list(*nvp, ZPOOL_PROP_ALTROOT, spa->spa_root,
363 0, ZPROP_SRC_LOCAL);
364
365 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS)) {
366 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
367 MIN(zfs_max_recordsize, SPA_MAXBLOCKSIZE), ZPROP_SRC_NONE);
368 } else {
369 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
370 SPA_OLD_MAXBLOCKSIZE, ZPROP_SRC_NONE);
371 }
372
373 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_DNODE)) {
374 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXDNODESIZE, NULL,
375 DNODE_MAX_SIZE, ZPROP_SRC_NONE);
376 } else {
377 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXDNODESIZE, NULL,
378 DNODE_MIN_SIZE, ZPROP_SRC_NONE);
379 }
380
381 if ((dp = list_head(&spa->spa_config_list)) != NULL) {
382 if (dp->scd_path == NULL) {
383 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
384 "none", 0, ZPROP_SRC_LOCAL);
385 } else if (strcmp(dp->scd_path, spa_config_path) != 0) {
386 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
387 dp->scd_path, 0, ZPROP_SRC_LOCAL);
388 }
389 }
390 }
391
392 /*
393 * Get zpool property values.
394 */
395 int
spa_prop_get(spa_t * spa,nvlist_t ** nvp)396 spa_prop_get(spa_t *spa, nvlist_t **nvp)
397 {
398 objset_t *mos = spa->spa_meta_objset;
399 zap_cursor_t zc;
400 zap_attribute_t za;
401 int err;
402
403 VERIFY(nvlist_alloc(nvp, NV_UNIQUE_NAME, KM_SLEEP) == 0);
404
405 mutex_enter(&spa->spa_props_lock);
406
407 /*
408 * Get properties from the spa config.
409 */
410 spa_prop_get_config(spa, nvp);
411
412 /* If no pool property object, no more prop to get. */
413 if (mos == NULL || spa->spa_pool_props_object == 0) {
414 mutex_exit(&spa->spa_props_lock);
415 return (0);
416 }
417
418 /*
419 * Get properties from the MOS pool property object.
420 */
421 for (zap_cursor_init(&zc, mos, spa->spa_pool_props_object);
422 (err = zap_cursor_retrieve(&zc, &za)) == 0;
423 zap_cursor_advance(&zc)) {
424 uint64_t intval = 0;
425 char *strval = NULL;
426 zprop_source_t src = ZPROP_SRC_DEFAULT;
427 zpool_prop_t prop;
428
429 if ((prop = zpool_name_to_prop(za.za_name)) == ZPOOL_PROP_INVAL)
430 continue;
431
432 switch (za.za_integer_length) {
433 case 8:
434 /* integer property */
435 if (za.za_first_integer !=
436 zpool_prop_default_numeric(prop))
437 src = ZPROP_SRC_LOCAL;
438
439 if (prop == ZPOOL_PROP_BOOTFS) {
440 dsl_pool_t *dp;
441 dsl_dataset_t *ds = NULL;
442
443 dp = spa_get_dsl(spa);
444 dsl_pool_config_enter(dp, FTAG);
445 err = dsl_dataset_hold_obj(dp,
446 za.za_first_integer, FTAG, &ds);
447 if (err != 0) {
448 dsl_pool_config_exit(dp, FTAG);
449 break;
450 }
451
452 strval = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN,
453 KM_SLEEP);
454 dsl_dataset_name(ds, strval);
455 dsl_dataset_rele(ds, FTAG);
456 dsl_pool_config_exit(dp, FTAG);
457 } else {
458 strval = NULL;
459 intval = za.za_first_integer;
460 }
461
462 spa_prop_add_list(*nvp, prop, strval, intval, src);
463
464 if (strval != NULL)
465 kmem_free(strval, ZFS_MAX_DATASET_NAME_LEN);
466
467 break;
468
469 case 1:
470 /* string property */
471 strval = kmem_alloc(za.za_num_integers, KM_SLEEP);
472 err = zap_lookup(mos, spa->spa_pool_props_object,
473 za.za_name, 1, za.za_num_integers, strval);
474 if (err) {
475 kmem_free(strval, za.za_num_integers);
476 break;
477 }
478 spa_prop_add_list(*nvp, prop, strval, 0, src);
479 kmem_free(strval, za.za_num_integers);
480 break;
481
482 default:
483 break;
484 }
485 }
486 zap_cursor_fini(&zc);
487 mutex_exit(&spa->spa_props_lock);
488 out:
489 if (err && err != ENOENT) {
490 nvlist_free(*nvp);
491 *nvp = NULL;
492 return (err);
493 }
494
495 return (0);
496 }
497
498 /*
499 * Validate the given pool properties nvlist and modify the list
500 * for the property values to be set.
501 */
502 static int
spa_prop_validate(spa_t * spa,nvlist_t * props)503 spa_prop_validate(spa_t *spa, nvlist_t *props)
504 {
505 nvpair_t *elem;
506 int error = 0, reset_bootfs = 0;
507 uint64_t objnum = 0;
508 boolean_t has_feature = B_FALSE;
509
510 elem = NULL;
511 while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
512 uint64_t intval;
513 char *strval, *slash, *check, *fname;
514 const char *propname = nvpair_name(elem);
515 zpool_prop_t prop = zpool_name_to_prop(propname);
516
517 switch (prop) {
518 case ZPOOL_PROP_INVAL:
519 if (!zpool_prop_feature(propname)) {
520 error = SET_ERROR(EINVAL);
521 break;
522 }
523
524 /*
525 * Sanitize the input.
526 */
527 if (nvpair_type(elem) != DATA_TYPE_UINT64) {
528 error = SET_ERROR(EINVAL);
529 break;
530 }
531
532 if (nvpair_value_uint64(elem, &intval) != 0) {
533 error = SET_ERROR(EINVAL);
534 break;
535 }
536
537 if (intval != 0) {
538 error = SET_ERROR(EINVAL);
539 break;
540 }
541
542 fname = strchr(propname, '@') + 1;
543 if (zfeature_lookup_name(fname, NULL) != 0) {
544 error = SET_ERROR(EINVAL);
545 break;
546 }
547
548 has_feature = B_TRUE;
549 break;
550
551 case ZPOOL_PROP_VERSION:
552 error = nvpair_value_uint64(elem, &intval);
553 if (!error &&
554 (intval < spa_version(spa) ||
555 intval > SPA_VERSION_BEFORE_FEATURES ||
556 has_feature))
557 error = SET_ERROR(EINVAL);
558 break;
559
560 case ZPOOL_PROP_DELEGATION:
561 case ZPOOL_PROP_AUTOREPLACE:
562 case ZPOOL_PROP_LISTSNAPS:
563 case ZPOOL_PROP_AUTOEXPAND:
564 case ZPOOL_PROP_AUTOTRIM:
565 error = nvpair_value_uint64(elem, &intval);
566 if (!error && intval > 1)
567 error = SET_ERROR(EINVAL);
568 break;
569
570 case ZPOOL_PROP_MULTIHOST:
571 error = nvpair_value_uint64(elem, &intval);
572 if (!error && intval > 1)
573 error = SET_ERROR(EINVAL);
574
575 if (!error && !spa_get_hostid())
576 error = SET_ERROR(ENOTSUP);
577
578 break;
579
580 case ZPOOL_PROP_BOOTFS:
581 /*
582 * If the pool version is less than SPA_VERSION_BOOTFS,
583 * or the pool is still being created (version == 0),
584 * the bootfs property cannot be set.
585 */
586 if (spa_version(spa) < SPA_VERSION_BOOTFS) {
587 error = SET_ERROR(ENOTSUP);
588 break;
589 }
590
591 /*
592 * Make sure the vdev config is bootable
593 */
594 if (!vdev_is_bootable(spa->spa_root_vdev)) {
595 error = SET_ERROR(ENOTSUP);
596 break;
597 }
598
599 reset_bootfs = 1;
600
601 error = nvpair_value_string(elem, &strval);
602
603 if (!error) {
604 objset_t *os;
605 uint64_t propval;
606
607 if (strval == NULL || strval[0] == '\0') {
608 objnum = zpool_prop_default_numeric(
609 ZPOOL_PROP_BOOTFS);
610 break;
611 }
612
613 error = dmu_objset_hold(strval, FTAG, &os);
614 if (error != 0)
615 break;
616
617 /*
618 * Must be ZPL, and its property settings
619 * must be supported.
620 */
621
622 if (dmu_objset_type(os) != DMU_OST_ZFS) {
623 error = SET_ERROR(ENOTSUP);
624 } else if ((error =
625 dsl_prop_get_int_ds(dmu_objset_ds(os),
626 zfs_prop_to_name(ZFS_PROP_COMPRESSION),
627 &propval)) == 0 &&
628 !BOOTFS_COMPRESS_VALID(propval)) {
629 error = SET_ERROR(ENOTSUP);
630 } else {
631 objnum = dmu_objset_id(os);
632 }
633 dmu_objset_rele(os, FTAG);
634 }
635 break;
636
637 case ZPOOL_PROP_FAILUREMODE:
638 error = nvpair_value_uint64(elem, &intval);
639 if (!error && (intval < ZIO_FAILURE_MODE_WAIT ||
640 intval > ZIO_FAILURE_MODE_PANIC))
641 error = SET_ERROR(EINVAL);
642
643 /*
644 * This is a special case which only occurs when
645 * the pool has completely failed. This allows
646 * the user to change the in-core failmode property
647 * without syncing it out to disk (I/Os might
648 * currently be blocked). We do this by returning
649 * EIO to the caller (spa_prop_set) to trick it
650 * into thinking we encountered a property validation
651 * error.
652 */
653 if (!error && spa_suspended(spa)) {
654 spa->spa_failmode = intval;
655 error = SET_ERROR(EIO);
656 }
657 break;
658
659 case ZPOOL_PROP_CACHEFILE:
660 if ((error = nvpair_value_string(elem, &strval)) != 0)
661 break;
662
663 if (strval[0] == '\0')
664 break;
665
666 if (strcmp(strval, "none") == 0)
667 break;
668
669 if (strval[0] != '/') {
670 error = SET_ERROR(EINVAL);
671 break;
672 }
673
674 slash = strrchr(strval, '/');
675 ASSERT(slash != NULL);
676
677 if (slash[1] == '\0' || strcmp(slash, "/.") == 0 ||
678 strcmp(slash, "/..") == 0)
679 error = SET_ERROR(EINVAL);
680 break;
681
682 case ZPOOL_PROP_COMMENT:
683 if ((error = nvpair_value_string(elem, &strval)) != 0)
684 break;
685 for (check = strval; *check != '\0'; check++) {
686 /*
687 * The kernel doesn't have an easy isprint()
688 * check. For this kernel check, we merely
689 * check ASCII apart from DEL. Fix this if
690 * there is an easy-to-use kernel isprint().
691 */
692 if (*check >= 0x7f) {
693 error = SET_ERROR(EINVAL);
694 break;
695 }
696 }
697 if (strlen(strval) > ZPROP_MAX_COMMENT)
698 error = E2BIG;
699 break;
700
701 case ZPOOL_PROP_DEDUPDITTO:
702 if (spa_version(spa) < SPA_VERSION_DEDUP)
703 error = SET_ERROR(ENOTSUP);
704 else
705 error = nvpair_value_uint64(elem, &intval);
706 if (error == 0 &&
707 intval != 0 && intval < ZIO_DEDUPDITTO_MIN)
708 error = SET_ERROR(EINVAL);
709 break;
710 }
711
712 if (error)
713 break;
714 }
715
716 if (!error && reset_bootfs) {
717 error = nvlist_remove(props,
718 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), DATA_TYPE_STRING);
719
720 if (!error) {
721 error = nvlist_add_uint64(props,
722 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), objnum);
723 }
724 }
725
726 return (error);
727 }
728
729 void
spa_configfile_set(spa_t * spa,nvlist_t * nvp,boolean_t need_sync)730 spa_configfile_set(spa_t *spa, nvlist_t *nvp, boolean_t need_sync)
731 {
732 char *cachefile;
733 spa_config_dirent_t *dp;
734
735 if (nvlist_lookup_string(nvp, zpool_prop_to_name(ZPOOL_PROP_CACHEFILE),
736 &cachefile) != 0)
737 return;
738
739 dp = kmem_alloc(sizeof (spa_config_dirent_t),
740 KM_SLEEP);
741
742 if (cachefile[0] == '\0')
743 dp->scd_path = spa_strdup(spa_config_path);
744 else if (strcmp(cachefile, "none") == 0)
745 dp->scd_path = NULL;
746 else
747 dp->scd_path = spa_strdup(cachefile);
748
749 list_insert_head(&spa->spa_config_list, dp);
750 if (need_sync)
751 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
752 }
753
754 int
spa_prop_set(spa_t * spa,nvlist_t * nvp)755 spa_prop_set(spa_t *spa, nvlist_t *nvp)
756 {
757 int error;
758 nvpair_t *elem = NULL;
759 boolean_t need_sync = B_FALSE;
760
761 if ((error = spa_prop_validate(spa, nvp)) != 0)
762 return (error);
763
764 while ((elem = nvlist_next_nvpair(nvp, elem)) != NULL) {
765 zpool_prop_t prop = zpool_name_to_prop(nvpair_name(elem));
766
767 if (prop == ZPOOL_PROP_CACHEFILE ||
768 prop == ZPOOL_PROP_ALTROOT ||
769 prop == ZPOOL_PROP_READONLY)
770 continue;
771
772 if (prop == ZPOOL_PROP_VERSION || prop == ZPOOL_PROP_INVAL) {
773 uint64_t ver;
774
775 if (prop == ZPOOL_PROP_VERSION) {
776 VERIFY(nvpair_value_uint64(elem, &ver) == 0);
777 } else {
778 ASSERT(zpool_prop_feature(nvpair_name(elem)));
779 ver = SPA_VERSION_FEATURES;
780 need_sync = B_TRUE;
781 }
782
783 /* Save time if the version is already set. */
784 if (ver == spa_version(spa))
785 continue;
786
787 /*
788 * In addition to the pool directory object, we might
789 * create the pool properties object, the features for
790 * read object, the features for write object, or the
791 * feature descriptions object.
792 */
793 error = dsl_sync_task(spa->spa_name, NULL,
794 spa_sync_version, &ver,
795 6, ZFS_SPACE_CHECK_RESERVED);
796 if (error)
797 return (error);
798 continue;
799 }
800
801 need_sync = B_TRUE;
802 break;
803 }
804
805 if (need_sync) {
806 return (dsl_sync_task(spa->spa_name, NULL, spa_sync_props,
807 nvp, 6, ZFS_SPACE_CHECK_RESERVED));
808 }
809
810 return (0);
811 }
812
813 /*
814 * If the bootfs property value is dsobj, clear it.
815 */
816 void
spa_prop_clear_bootfs(spa_t * spa,uint64_t dsobj,dmu_tx_t * tx)817 spa_prop_clear_bootfs(spa_t *spa, uint64_t dsobj, dmu_tx_t *tx)
818 {
819 if (spa->spa_bootfs == dsobj && spa->spa_pool_props_object != 0) {
820 VERIFY(zap_remove(spa->spa_meta_objset,
821 spa->spa_pool_props_object,
822 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), tx) == 0);
823 spa->spa_bootfs = 0;
824 }
825 }
826
827 /*ARGSUSED*/
828 static int
spa_change_guid_check(void * arg,dmu_tx_t * tx)829 spa_change_guid_check(void *arg, dmu_tx_t *tx)
830 {
831 uint64_t *newguid = arg;
832 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
833 vdev_t *rvd = spa->spa_root_vdev;
834 uint64_t vdev_state;
835
836 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
837 int error = (spa_has_checkpoint(spa)) ?
838 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
839 return (SET_ERROR(error));
840 }
841
842 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
843 vdev_state = rvd->vdev_state;
844 spa_config_exit(spa, SCL_STATE, FTAG);
845
846 if (vdev_state != VDEV_STATE_HEALTHY)
847 return (SET_ERROR(ENXIO));
848
849 ASSERT3U(spa_guid(spa), !=, *newguid);
850
851 return (0);
852 }
853
854 static void
spa_change_guid_sync(void * arg,dmu_tx_t * tx)855 spa_change_guid_sync(void *arg, dmu_tx_t *tx)
856 {
857 uint64_t *newguid = arg;
858 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
859 uint64_t oldguid;
860 vdev_t *rvd = spa->spa_root_vdev;
861
862 oldguid = spa_guid(spa);
863
864 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
865 rvd->vdev_guid = *newguid;
866 rvd->vdev_guid_sum += (*newguid - oldguid);
867 vdev_config_dirty(rvd);
868 spa_config_exit(spa, SCL_STATE, FTAG);
869
870 spa_history_log_internal(spa, "guid change", tx, "old=%llu new=%llu",
871 oldguid, *newguid);
872 }
873
874 /*
875 * Change the GUID for the pool. This is done so that we can later
876 * re-import a pool built from a clone of our own vdevs. We will modify
877 * the root vdev's guid, our own pool guid, and then mark all of our
878 * vdevs dirty. Note that we must make sure that all our vdevs are
879 * online when we do this, or else any vdevs that weren't present
880 * would be orphaned from our pool. We are also going to issue a
881 * sysevent to update any watchers.
882 */
883 int
spa_change_guid(spa_t * spa)884 spa_change_guid(spa_t *spa)
885 {
886 int error;
887 uint64_t guid;
888
889 mutex_enter(&spa->spa_vdev_top_lock);
890 mutex_enter(&spa_namespace_lock);
891 guid = spa_generate_guid(NULL);
892
893 error = dsl_sync_task(spa->spa_name, spa_change_guid_check,
894 spa_change_guid_sync, &guid, 5, ZFS_SPACE_CHECK_RESERVED);
895
896 if (error == 0) {
897 spa_write_cachefile(spa, B_FALSE, B_TRUE);
898 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_REGUID);
899 }
900
901 mutex_exit(&spa_namespace_lock);
902 mutex_exit(&spa->spa_vdev_top_lock);
903
904 return (error);
905 }
906
907 /*
908 * ==========================================================================
909 * SPA state manipulation (open/create/destroy/import/export)
910 * ==========================================================================
911 */
912
913 static int
spa_error_entry_compare(const void * a,const void * b)914 spa_error_entry_compare(const void *a, const void *b)
915 {
916 const spa_error_entry_t *sa = (const spa_error_entry_t *)a;
917 const spa_error_entry_t *sb = (const spa_error_entry_t *)b;
918 int ret;
919
920 ret = memcmp(&sa->se_bookmark, &sb->se_bookmark,
921 sizeof (zbookmark_phys_t));
922
923 return (TREE_ISIGN(ret));
924 }
925
926 /*
927 * Utility function which retrieves copies of the current logs and
928 * re-initializes them in the process.
929 */
930 void
spa_get_errlists(spa_t * spa,avl_tree_t * last,avl_tree_t * scrub)931 spa_get_errlists(spa_t *spa, avl_tree_t *last, avl_tree_t *scrub)
932 {
933 ASSERT(MUTEX_HELD(&spa->spa_errlist_lock));
934
935 bcopy(&spa->spa_errlist_last, last, sizeof (avl_tree_t));
936 bcopy(&spa->spa_errlist_scrub, scrub, sizeof (avl_tree_t));
937
938 avl_create(&spa->spa_errlist_scrub,
939 spa_error_entry_compare, sizeof (spa_error_entry_t),
940 offsetof(spa_error_entry_t, se_avl));
941 avl_create(&spa->spa_errlist_last,
942 spa_error_entry_compare, sizeof (spa_error_entry_t),
943 offsetof(spa_error_entry_t, se_avl));
944 }
945
946 static void
spa_taskqs_init(spa_t * spa,zio_type_t t,zio_taskq_type_t q)947 spa_taskqs_init(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
948 {
949 const zio_taskq_info_t *ztip = &zio_taskqs[t][q];
950 enum zti_modes mode = ztip->zti_mode;
951 uint_t value = ztip->zti_value;
952 uint_t count = ztip->zti_count;
953 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
954 char name[32];
955 uint_t flags = 0;
956 boolean_t batch = B_FALSE;
957
958 if (mode == ZTI_MODE_NULL) {
959 tqs->stqs_count = 0;
960 tqs->stqs_taskq = NULL;
961 return;
962 }
963
964 ASSERT3U(count, >, 0);
965
966 tqs->stqs_count = count;
967 tqs->stqs_taskq = kmem_alloc(count * sizeof (taskq_t *), KM_SLEEP);
968
969 switch (mode) {
970 case ZTI_MODE_FIXED:
971 ASSERT3U(value, >=, 1);
972 value = MAX(value, 1);
973 break;
974
975 case ZTI_MODE_BATCH:
976 batch = B_TRUE;
977 flags |= TASKQ_THREADS_CPU_PCT;
978 value = zio_taskq_batch_pct;
979 break;
980
981 default:
982 panic("unrecognized mode for %s_%s taskq (%u:%u) in "
983 "spa_activate()",
984 zio_type_name[t], zio_taskq_types[q], mode, value);
985 break;
986 }
987
988 for (uint_t i = 0; i < count; i++) {
989 taskq_t *tq;
990
991 if (count > 1) {
992 (void) snprintf(name, sizeof (name), "%s_%s_%u",
993 zio_type_name[t], zio_taskq_types[q], i);
994 } else {
995 (void) snprintf(name, sizeof (name), "%s_%s",
996 zio_type_name[t], zio_taskq_types[q]);
997 }
998
999 if (zio_taskq_sysdc && spa->spa_proc != &p0) {
1000 if (batch)
1001 flags |= TASKQ_DC_BATCH;
1002
1003 tq = taskq_create_sysdc(name, value, 50, INT_MAX,
1004 spa->spa_proc, zio_taskq_basedc, flags);
1005 } else {
1006 pri_t pri = maxclsyspri;
1007 /*
1008 * The write issue taskq can be extremely CPU
1009 * intensive. Run it at slightly lower priority
1010 * than the other taskqs.
1011 */
1012 if (t == ZIO_TYPE_WRITE && q == ZIO_TASKQ_ISSUE)
1013 pri--;
1014
1015 tq = taskq_create_proc(name, value, pri, 50,
1016 INT_MAX, spa->spa_proc, flags);
1017 }
1018
1019 tqs->stqs_taskq[i] = tq;
1020 }
1021 }
1022
1023 static void
spa_taskqs_fini(spa_t * spa,zio_type_t t,zio_taskq_type_t q)1024 spa_taskqs_fini(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
1025 {
1026 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1027
1028 if (tqs->stqs_taskq == NULL) {
1029 ASSERT0(tqs->stqs_count);
1030 return;
1031 }
1032
1033 for (uint_t i = 0; i < tqs->stqs_count; i++) {
1034 ASSERT3P(tqs->stqs_taskq[i], !=, NULL);
1035 taskq_destroy(tqs->stqs_taskq[i]);
1036 }
1037
1038 kmem_free(tqs->stqs_taskq, tqs->stqs_count * sizeof (taskq_t *));
1039 tqs->stqs_taskq = NULL;
1040 }
1041
1042 /*
1043 * Dispatch a task to the appropriate taskq for the ZFS I/O type and priority.
1044 * Note that a type may have multiple discrete taskqs to avoid lock contention
1045 * on the taskq itself. In that case we choose which taskq at random by using
1046 * the low bits of gethrtime().
1047 */
1048 void
spa_taskq_dispatch_ent(spa_t * spa,zio_type_t t,zio_taskq_type_t q,task_func_t * func,void * arg,uint_t flags,taskq_ent_t * ent)1049 spa_taskq_dispatch_ent(spa_t *spa, zio_type_t t, zio_taskq_type_t q,
1050 task_func_t *func, void *arg, uint_t flags, taskq_ent_t *ent)
1051 {
1052 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1053 taskq_t *tq;
1054
1055 ASSERT3P(tqs->stqs_taskq, !=, NULL);
1056 ASSERT3U(tqs->stqs_count, !=, 0);
1057
1058 if (tqs->stqs_count == 1) {
1059 tq = tqs->stqs_taskq[0];
1060 } else {
1061 tq = tqs->stqs_taskq[gethrtime() % tqs->stqs_count];
1062 }
1063
1064 taskq_dispatch_ent(tq, func, arg, flags, ent);
1065 }
1066
1067 static void
spa_create_zio_taskqs(spa_t * spa)1068 spa_create_zio_taskqs(spa_t *spa)
1069 {
1070 for (int t = 0; t < ZIO_TYPES; t++) {
1071 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1072 spa_taskqs_init(spa, t, q);
1073 }
1074 }
1075 }
1076
1077 #ifdef _KERNEL
1078 static void
spa_thread(void * arg)1079 spa_thread(void *arg)
1080 {
1081 callb_cpr_t cprinfo;
1082 spa_t *spa = arg;
1083 char spa_id_readable[CB_MAXNAME + 1];
1084 user_t *pu = PTOU(curproc);
1085
1086 (void) snprintf(spa_id_readable, sizeof (spa_id_readable), "SPA:0x%p",
1087 spa);
1088
1089 CALLB_CPR_INIT(&cprinfo, &spa->spa_proc_lock, callb_generic_cpr,
1090 spa_id_readable);
1091
1092 ASSERT(curproc != &p0);
1093 (void) snprintf(pu->u_psargs, sizeof (pu->u_psargs),
1094 "zpool-%s", spa->spa_name);
1095 (void) strlcpy(pu->u_comm, pu->u_psargs, sizeof (pu->u_comm));
1096
1097 /* bind this thread to the requested psrset */
1098 if (zio_taskq_psrset_bind != PS_NONE) {
1099 pool_lock();
1100 mutex_enter(&cpu_lock);
1101 mutex_enter(&pidlock);
1102 mutex_enter(&curproc->p_lock);
1103
1104 if (cpupart_bind_thread(curthread, zio_taskq_psrset_bind,
1105 0, NULL, NULL) == 0) {
1106 curthread->t_bind_pset = zio_taskq_psrset_bind;
1107 } else {
1108 cmn_err(CE_WARN,
1109 "Couldn't bind process for zfs pool \"%s\" to "
1110 "pset %d\n", spa->spa_name, zio_taskq_psrset_bind);
1111 }
1112
1113 mutex_exit(&curproc->p_lock);
1114 mutex_exit(&pidlock);
1115 mutex_exit(&cpu_lock);
1116 pool_unlock();
1117 }
1118
1119 if (zio_taskq_sysdc) {
1120 sysdc_thread_enter(curthread, 100, 0);
1121 }
1122
1123 spa->spa_proc = curproc;
1124 spa->spa_did = curthread->t_did;
1125
1126 spa_create_zio_taskqs(spa);
1127
1128 mutex_enter(&spa->spa_proc_lock);
1129 ASSERT(spa->spa_proc_state == SPA_PROC_CREATED);
1130
1131 spa->spa_proc_state = SPA_PROC_ACTIVE;
1132 cv_broadcast(&spa->spa_proc_cv);
1133
1134 CALLB_CPR_SAFE_BEGIN(&cprinfo);
1135 while (spa->spa_proc_state == SPA_PROC_ACTIVE)
1136 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1137 CALLB_CPR_SAFE_END(&cprinfo, &spa->spa_proc_lock);
1138
1139 ASSERT(spa->spa_proc_state == SPA_PROC_DEACTIVATE);
1140 spa->spa_proc_state = SPA_PROC_GONE;
1141 spa->spa_proc = &p0;
1142 cv_broadcast(&spa->spa_proc_cv);
1143 CALLB_CPR_EXIT(&cprinfo); /* drops spa_proc_lock */
1144
1145 mutex_enter(&curproc->p_lock);
1146 lwp_exit();
1147 }
1148 #endif
1149
1150 /*
1151 * Activate an uninitialized pool.
1152 */
1153 static void
spa_activate(spa_t * spa,int mode)1154 spa_activate(spa_t *spa, int mode)
1155 {
1156 ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
1157
1158 spa->spa_state = POOL_STATE_ACTIVE;
1159 spa->spa_mode = mode;
1160
1161 spa->spa_normal_class = metaslab_class_create(spa, zfs_metaslab_ops);
1162 spa->spa_log_class = metaslab_class_create(spa, zfs_metaslab_ops);
1163 spa->spa_special_class = metaslab_class_create(spa, zfs_metaslab_ops);
1164 spa->spa_dedup_class = metaslab_class_create(spa, zfs_metaslab_ops);
1165
1166 /* Try to create a covering process */
1167 mutex_enter(&spa->spa_proc_lock);
1168 ASSERT(spa->spa_proc_state == SPA_PROC_NONE);
1169 ASSERT(spa->spa_proc == &p0);
1170 spa->spa_did = 0;
1171
1172 /* Only create a process if we're going to be around a while. */
1173 if (spa_create_process && strcmp(spa->spa_name, TRYIMPORT_NAME) != 0) {
1174 if (newproc(spa_thread, (caddr_t)spa, syscid, maxclsyspri,
1175 NULL, 0) == 0) {
1176 spa->spa_proc_state = SPA_PROC_CREATED;
1177 while (spa->spa_proc_state == SPA_PROC_CREATED) {
1178 cv_wait(&spa->spa_proc_cv,
1179 &spa->spa_proc_lock);
1180 }
1181 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1182 ASSERT(spa->spa_proc != &p0);
1183 ASSERT(spa->spa_did != 0);
1184 } else {
1185 #ifdef _KERNEL
1186 cmn_err(CE_WARN,
1187 "Couldn't create process for zfs pool \"%s\"\n",
1188 spa->spa_name);
1189 #endif
1190 }
1191 }
1192 mutex_exit(&spa->spa_proc_lock);
1193
1194 /* If we didn't create a process, we need to create our taskqs. */
1195 if (spa->spa_proc == &p0) {
1196 spa_create_zio_taskqs(spa);
1197 }
1198
1199 for (size_t i = 0; i < TXG_SIZE; i++) {
1200 spa->spa_txg_zio[i] = zio_root(spa, NULL, NULL,
1201 ZIO_FLAG_CANFAIL);
1202 }
1203
1204 list_create(&spa->spa_config_dirty_list, sizeof (vdev_t),
1205 offsetof(vdev_t, vdev_config_dirty_node));
1206 list_create(&spa->spa_evicting_os_list, sizeof (objset_t),
1207 offsetof(objset_t, os_evicting_node));
1208 list_create(&spa->spa_state_dirty_list, sizeof (vdev_t),
1209 offsetof(vdev_t, vdev_state_dirty_node));
1210
1211 txg_list_create(&spa->spa_vdev_txg_list, spa,
1212 offsetof(struct vdev, vdev_txg_node));
1213
1214 avl_create(&spa->spa_errlist_scrub,
1215 spa_error_entry_compare, sizeof (spa_error_entry_t),
1216 offsetof(spa_error_entry_t, se_avl));
1217 avl_create(&spa->spa_errlist_last,
1218 spa_error_entry_compare, sizeof (spa_error_entry_t),
1219 offsetof(spa_error_entry_t, se_avl));
1220
1221 spa_keystore_init(&spa->spa_keystore);
1222
1223 /*
1224 * The taskq to upgrade datasets in this pool. Currently used by
1225 * feature SPA_FEATURE_USEROBJ_ACCOUNTING/SPA_FEATURE_PROJECT_QUOTA.
1226 */
1227 spa->spa_upgrade_taskq = taskq_create("z_upgrade", boot_ncpus,
1228 minclsyspri, 1, INT_MAX, TASKQ_DYNAMIC);
1229 }
1230
1231 /*
1232 * Opposite of spa_activate().
1233 */
1234 static void
spa_deactivate(spa_t * spa)1235 spa_deactivate(spa_t *spa)
1236 {
1237 ASSERT(spa->spa_sync_on == B_FALSE);
1238 ASSERT(spa->spa_dsl_pool == NULL);
1239 ASSERT(spa->spa_root_vdev == NULL);
1240 ASSERT(spa->spa_async_zio_root == NULL);
1241 ASSERT(spa->spa_state != POOL_STATE_UNINITIALIZED);
1242
1243 spa_evicting_os_wait(spa);
1244
1245 if (spa->spa_upgrade_taskq) {
1246 taskq_destroy(spa->spa_upgrade_taskq);
1247 spa->spa_upgrade_taskq = NULL;
1248 }
1249
1250 txg_list_destroy(&spa->spa_vdev_txg_list);
1251
1252 list_destroy(&spa->spa_config_dirty_list);
1253 list_destroy(&spa->spa_evicting_os_list);
1254 list_destroy(&spa->spa_state_dirty_list);
1255
1256 for (int t = 0; t < ZIO_TYPES; t++) {
1257 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1258 spa_taskqs_fini(spa, t, q);
1259 }
1260 }
1261
1262 for (size_t i = 0; i < TXG_SIZE; i++) {
1263 ASSERT3P(spa->spa_txg_zio[i], !=, NULL);
1264 VERIFY0(zio_wait(spa->spa_txg_zio[i]));
1265 spa->spa_txg_zio[i] = NULL;
1266 }
1267
1268 metaslab_class_destroy(spa->spa_normal_class);
1269 spa->spa_normal_class = NULL;
1270
1271 metaslab_class_destroy(spa->spa_log_class);
1272 spa->spa_log_class = NULL;
1273
1274 metaslab_class_destroy(spa->spa_special_class);
1275 spa->spa_special_class = NULL;
1276
1277 metaslab_class_destroy(spa->spa_dedup_class);
1278 spa->spa_dedup_class = NULL;
1279
1280 /*
1281 * If this was part of an import or the open otherwise failed, we may
1282 * still have errors left in the queues. Empty them just in case.
1283 */
1284 spa_errlog_drain(spa);
1285 avl_destroy(&spa->spa_errlist_scrub);
1286 avl_destroy(&spa->spa_errlist_last);
1287
1288 spa_keystore_fini(&spa->spa_keystore);
1289
1290 spa->spa_state = POOL_STATE_UNINITIALIZED;
1291
1292 mutex_enter(&spa->spa_proc_lock);
1293 if (spa->spa_proc_state != SPA_PROC_NONE) {
1294 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1295 spa->spa_proc_state = SPA_PROC_DEACTIVATE;
1296 cv_broadcast(&spa->spa_proc_cv);
1297 while (spa->spa_proc_state == SPA_PROC_DEACTIVATE) {
1298 ASSERT(spa->spa_proc != &p0);
1299 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1300 }
1301 ASSERT(spa->spa_proc_state == SPA_PROC_GONE);
1302 spa->spa_proc_state = SPA_PROC_NONE;
1303 }
1304 ASSERT(spa->spa_proc == &p0);
1305 mutex_exit(&spa->spa_proc_lock);
1306
1307 /*
1308 * We want to make sure spa_thread() has actually exited the ZFS
1309 * module, so that the module can't be unloaded out from underneath
1310 * it.
1311 */
1312 if (spa->spa_did != 0) {
1313 thread_join(spa->spa_did);
1314 spa->spa_did = 0;
1315 }
1316 }
1317
1318 /*
1319 * Verify a pool configuration, and construct the vdev tree appropriately. This
1320 * will create all the necessary vdevs in the appropriate layout, with each vdev
1321 * in the CLOSED state. This will prep the pool before open/creation/import.
1322 * All vdev validation is done by the vdev_alloc() routine.
1323 */
1324 static int
spa_config_parse(spa_t * spa,vdev_t ** vdp,nvlist_t * nv,vdev_t * parent,uint_t id,int atype)1325 spa_config_parse(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent,
1326 uint_t id, int atype)
1327 {
1328 nvlist_t **child;
1329 uint_t children;
1330 int error;
1331
1332 if ((error = vdev_alloc(spa, vdp, nv, parent, id, atype)) != 0)
1333 return (error);
1334
1335 if ((*vdp)->vdev_ops->vdev_op_leaf)
1336 return (0);
1337
1338 error = nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1339 &child, &children);
1340
1341 if (error == ENOENT)
1342 return (0);
1343
1344 if (error) {
1345 vdev_free(*vdp);
1346 *vdp = NULL;
1347 return (SET_ERROR(EINVAL));
1348 }
1349
1350 for (int c = 0; c < children; c++) {
1351 vdev_t *vd;
1352 if ((error = spa_config_parse(spa, &vd, child[c], *vdp, c,
1353 atype)) != 0) {
1354 vdev_free(*vdp);
1355 *vdp = NULL;
1356 return (error);
1357 }
1358 }
1359
1360 ASSERT(*vdp != NULL);
1361
1362 return (0);
1363 }
1364
1365 static boolean_t
spa_should_flush_logs_on_unload(spa_t * spa)1366 spa_should_flush_logs_on_unload(spa_t *spa)
1367 {
1368 if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
1369 return (B_FALSE);
1370
1371 if (!spa_writeable(spa))
1372 return (B_FALSE);
1373
1374 if (!spa->spa_sync_on)
1375 return (B_FALSE);
1376
1377 if (spa_state(spa) != POOL_STATE_EXPORTED)
1378 return (B_FALSE);
1379
1380 if (zfs_keep_log_spacemaps_at_export)
1381 return (B_FALSE);
1382
1383 return (B_TRUE);
1384 }
1385
1386 /*
1387 * Opens a transaction that will set the flag that will instruct
1388 * spa_sync to attempt to flush all the metaslabs for that txg.
1389 */
1390 static void
spa_unload_log_sm_flush_all(spa_t * spa)1391 spa_unload_log_sm_flush_all(spa_t *spa)
1392 {
1393 dmu_tx_t *tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
1394
1395 VERIFY0(dmu_tx_assign(tx, TXG_WAIT));
1396
1397 ASSERT3U(spa->spa_log_flushall_txg, ==, 0);
1398 spa->spa_log_flushall_txg = dmu_tx_get_txg(tx);
1399
1400 dmu_tx_commit(tx);
1401 txg_wait_synced(spa_get_dsl(spa), spa->spa_log_flushall_txg);
1402 }
1403
1404 static void
spa_unload_log_sm_metadata(spa_t * spa)1405 spa_unload_log_sm_metadata(spa_t *spa)
1406 {
1407 void *cookie = NULL;
1408 spa_log_sm_t *sls;
1409
1410 while ((sls = avl_destroy_nodes(&spa->spa_sm_logs_by_txg,
1411 &cookie)) != NULL) {
1412 VERIFY0(sls->sls_mscount);
1413 kmem_free(sls, sizeof (spa_log_sm_t));
1414 }
1415
1416 for (log_summary_entry_t *e = list_head(&spa->spa_log_summary);
1417 e != NULL; e = list_head(&spa->spa_log_summary)) {
1418 VERIFY0(e->lse_mscount);
1419 list_remove(&spa->spa_log_summary, e);
1420 kmem_free(e, sizeof (log_summary_entry_t));
1421 }
1422
1423 spa->spa_unflushed_stats.sus_nblocks = 0;
1424 spa->spa_unflushed_stats.sus_memused = 0;
1425 spa->spa_unflushed_stats.sus_blocklimit = 0;
1426 }
1427
1428 /*
1429 * Opposite of spa_load().
1430 */
1431 static void
spa_unload(spa_t * spa)1432 spa_unload(spa_t *spa)
1433 {
1434 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1435 ASSERT(spa_state(spa) != POOL_STATE_UNINITIALIZED);
1436
1437 spa_import_progress_remove(spa);
1438 spa_load_note(spa, "UNLOADING");
1439
1440 /*
1441 * If the log space map feature is enabled and the pool is getting
1442 * exported (but not destroyed), we want to spend some time flushing
1443 * as many metaslabs as we can in an attempt to destroy log space
1444 * maps and save import time.
1445 */
1446 if (spa_should_flush_logs_on_unload(spa))
1447 spa_unload_log_sm_flush_all(spa);
1448
1449 /*
1450 * Stop async tasks.
1451 */
1452 spa_async_suspend(spa);
1453
1454 if (spa->spa_root_vdev) {
1455 vdev_t *root_vdev = spa->spa_root_vdev;
1456 vdev_initialize_stop_all(root_vdev, VDEV_INITIALIZE_ACTIVE);
1457 vdev_trim_stop_all(root_vdev, VDEV_TRIM_ACTIVE);
1458 vdev_autotrim_stop_all(spa);
1459 }
1460
1461 /*
1462 * Stop syncing.
1463 */
1464 if (spa->spa_sync_on) {
1465 txg_sync_stop(spa->spa_dsl_pool);
1466 spa->spa_sync_on = B_FALSE;
1467 }
1468
1469 /*
1470 * This ensures that there is no async metaslab prefetching
1471 * while we attempt to unload the spa.
1472 */
1473 if (spa->spa_root_vdev != NULL) {
1474 for (int c = 0; c < spa->spa_root_vdev->vdev_children; c++) {
1475 vdev_t *vc = spa->spa_root_vdev->vdev_child[c];
1476 if (vc->vdev_mg != NULL)
1477 taskq_wait(vc->vdev_mg->mg_taskq);
1478 }
1479 }
1480
1481 if (spa->spa_mmp.mmp_thread)
1482 mmp_thread_stop(spa);
1483
1484 /*
1485 * Wait for any outstanding async I/O to complete.
1486 */
1487 if (spa->spa_async_zio_root != NULL) {
1488 for (int i = 0; i < max_ncpus; i++)
1489 (void) zio_wait(spa->spa_async_zio_root[i]);
1490 kmem_free(spa->spa_async_zio_root, max_ncpus * sizeof (void *));
1491 spa->spa_async_zio_root = NULL;
1492 }
1493
1494 if (spa->spa_vdev_removal != NULL) {
1495 spa_vdev_removal_destroy(spa->spa_vdev_removal);
1496 spa->spa_vdev_removal = NULL;
1497 }
1498
1499 if (spa->spa_condense_zthr != NULL) {
1500 zthr_destroy(spa->spa_condense_zthr);
1501 spa->spa_condense_zthr = NULL;
1502 }
1503
1504 if (spa->spa_checkpoint_discard_zthr != NULL) {
1505 zthr_destroy(spa->spa_checkpoint_discard_zthr);
1506 spa->spa_checkpoint_discard_zthr = NULL;
1507 }
1508
1509 spa_condense_fini(spa);
1510
1511 bpobj_close(&spa->spa_deferred_bpobj);
1512
1513 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1514
1515 /*
1516 * Close all vdevs.
1517 */
1518 if (spa->spa_root_vdev)
1519 vdev_free(spa->spa_root_vdev);
1520 ASSERT(spa->spa_root_vdev == NULL);
1521
1522 /*
1523 * Close the dsl pool.
1524 */
1525 if (spa->spa_dsl_pool) {
1526 dsl_pool_close(spa->spa_dsl_pool);
1527 spa->spa_dsl_pool = NULL;
1528 spa->spa_meta_objset = NULL;
1529 }
1530
1531 ddt_unload(spa);
1532 spa_unload_log_sm_metadata(spa);
1533
1534 /*
1535 * Drop and purge level 2 cache
1536 */
1537 spa_l2cache_drop(spa);
1538
1539 for (int i = 0; i < spa->spa_spares.sav_count; i++)
1540 vdev_free(spa->spa_spares.sav_vdevs[i]);
1541 if (spa->spa_spares.sav_vdevs) {
1542 kmem_free(spa->spa_spares.sav_vdevs,
1543 spa->spa_spares.sav_count * sizeof (void *));
1544 spa->spa_spares.sav_vdevs = NULL;
1545 }
1546 if (spa->spa_spares.sav_config) {
1547 nvlist_free(spa->spa_spares.sav_config);
1548 spa->spa_spares.sav_config = NULL;
1549 }
1550 spa->spa_spares.sav_count = 0;
1551
1552 for (int i = 0; i < spa->spa_l2cache.sav_count; i++) {
1553 vdev_clear_stats(spa->spa_l2cache.sav_vdevs[i]);
1554 vdev_free(spa->spa_l2cache.sav_vdevs[i]);
1555 }
1556 if (spa->spa_l2cache.sav_vdevs) {
1557 kmem_free(spa->spa_l2cache.sav_vdevs,
1558 spa->spa_l2cache.sav_count * sizeof (void *));
1559 spa->spa_l2cache.sav_vdevs = NULL;
1560 }
1561 if (spa->spa_l2cache.sav_config) {
1562 nvlist_free(spa->spa_l2cache.sav_config);
1563 spa->spa_l2cache.sav_config = NULL;
1564 }
1565 spa->spa_l2cache.sav_count = 0;
1566
1567 spa->spa_async_suspended = 0;
1568
1569 spa->spa_indirect_vdevs_loaded = B_FALSE;
1570
1571 if (spa->spa_comment != NULL) {
1572 spa_strfree(spa->spa_comment);
1573 spa->spa_comment = NULL;
1574 }
1575
1576 spa_config_exit(spa, SCL_ALL, spa);
1577 }
1578
1579 /*
1580 * Load (or re-load) the current list of vdevs describing the active spares for
1581 * this pool. When this is called, we have some form of basic information in
1582 * 'spa_spares.sav_config'. We parse this into vdevs, try to open them, and
1583 * then re-generate a more complete list including status information.
1584 */
1585 void
spa_load_spares(spa_t * spa)1586 spa_load_spares(spa_t *spa)
1587 {
1588 nvlist_t **spares;
1589 uint_t nspares;
1590 int i;
1591 vdev_t *vd, *tvd;
1592
1593 #ifndef _KERNEL
1594 /*
1595 * zdb opens both the current state of the pool and the
1596 * checkpointed state (if present), with a different spa_t.
1597 *
1598 * As spare vdevs are shared among open pools, we skip loading
1599 * them when we load the checkpointed state of the pool.
1600 */
1601 if (!spa_writeable(spa))
1602 return;
1603 #endif
1604
1605 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1606
1607 /*
1608 * First, close and free any existing spare vdevs.
1609 */
1610 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1611 vd = spa->spa_spares.sav_vdevs[i];
1612
1613 /* Undo the call to spa_activate() below */
1614 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1615 B_FALSE)) != NULL && tvd->vdev_isspare)
1616 spa_spare_remove(tvd);
1617 vdev_close(vd);
1618 vdev_free(vd);
1619 }
1620
1621 if (spa->spa_spares.sav_vdevs)
1622 kmem_free(spa->spa_spares.sav_vdevs,
1623 spa->spa_spares.sav_count * sizeof (void *));
1624
1625 if (spa->spa_spares.sav_config == NULL)
1626 nspares = 0;
1627 else
1628 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
1629 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
1630
1631 spa->spa_spares.sav_count = (int)nspares;
1632 spa->spa_spares.sav_vdevs = NULL;
1633
1634 if (nspares == 0)
1635 return;
1636
1637 /*
1638 * Construct the array of vdevs, opening them to get status in the
1639 * process. For each spare, there is potentially two different vdev_t
1640 * structures associated with it: one in the list of spares (used only
1641 * for basic validation purposes) and one in the active vdev
1642 * configuration (if it's spared in). During this phase we open and
1643 * validate each vdev on the spare list. If the vdev also exists in the
1644 * active configuration, then we also mark this vdev as an active spare.
1645 */
1646 spa->spa_spares.sav_vdevs = kmem_alloc(nspares * sizeof (void *),
1647 KM_SLEEP);
1648 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1649 VERIFY(spa_config_parse(spa, &vd, spares[i], NULL, 0,
1650 VDEV_ALLOC_SPARE) == 0);
1651 ASSERT(vd != NULL);
1652
1653 spa->spa_spares.sav_vdevs[i] = vd;
1654
1655 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1656 B_FALSE)) != NULL) {
1657 if (!tvd->vdev_isspare)
1658 spa_spare_add(tvd);
1659
1660 /*
1661 * We only mark the spare active if we were successfully
1662 * able to load the vdev. Otherwise, importing a pool
1663 * with a bad active spare would result in strange
1664 * behavior, because multiple pool would think the spare
1665 * is actively in use.
1666 *
1667 * There is a vulnerability here to an equally bizarre
1668 * circumstance, where a dead active spare is later
1669 * brought back to life (onlined or otherwise). Given
1670 * the rarity of this scenario, and the extra complexity
1671 * it adds, we ignore the possibility.
1672 */
1673 if (!vdev_is_dead(tvd))
1674 spa_spare_activate(tvd);
1675 }
1676
1677 vd->vdev_top = vd;
1678 vd->vdev_aux = &spa->spa_spares;
1679
1680 if (vdev_open(vd) != 0)
1681 continue;
1682
1683 if (vdev_validate_aux(vd) == 0)
1684 spa_spare_add(vd);
1685 }
1686
1687 /*
1688 * Recompute the stashed list of spares, with status information
1689 * this time.
1690 */
1691 VERIFY(nvlist_remove(spa->spa_spares.sav_config, ZPOOL_CONFIG_SPARES,
1692 DATA_TYPE_NVLIST_ARRAY) == 0);
1693
1694 spares = kmem_alloc(spa->spa_spares.sav_count * sizeof (void *),
1695 KM_SLEEP);
1696 for (i = 0; i < spa->spa_spares.sav_count; i++)
1697 spares[i] = vdev_config_generate(spa,
1698 spa->spa_spares.sav_vdevs[i], B_TRUE, VDEV_CONFIG_SPARE);
1699 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
1700 ZPOOL_CONFIG_SPARES, spares, spa->spa_spares.sav_count) == 0);
1701 for (i = 0; i < spa->spa_spares.sav_count; i++)
1702 nvlist_free(spares[i]);
1703 kmem_free(spares, spa->spa_spares.sav_count * sizeof (void *));
1704 }
1705
1706 /*
1707 * Load (or re-load) the current list of vdevs describing the active l2cache for
1708 * this pool. When this is called, we have some form of basic information in
1709 * 'spa_l2cache.sav_config'. We parse this into vdevs, try to open them, and
1710 * then re-generate a more complete list including status information.
1711 * Devices which are already active have their details maintained, and are
1712 * not re-opened.
1713 */
1714 void
spa_load_l2cache(spa_t * spa)1715 spa_load_l2cache(spa_t *spa)
1716 {
1717 nvlist_t **l2cache;
1718 uint_t nl2cache;
1719 int i, j, oldnvdevs;
1720 uint64_t guid;
1721 vdev_t *vd, **oldvdevs, **newvdevs;
1722 spa_aux_vdev_t *sav = &spa->spa_l2cache;
1723
1724 #ifndef _KERNEL
1725 /*
1726 * zdb opens both the current state of the pool and the
1727 * checkpointed state (if present), with a different spa_t.
1728 *
1729 * As L2 caches are part of the ARC which is shared among open
1730 * pools, we skip loading them when we load the checkpointed
1731 * state of the pool.
1732 */
1733 if (!spa_writeable(spa))
1734 return;
1735 #endif
1736
1737 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1738
1739 nl2cache = 0;
1740 newvdevs = NULL;
1741 if (sav->sav_config != NULL) {
1742 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
1743 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
1744 if (nl2cache > 0) {
1745 newvdevs = kmem_alloc(
1746 nl2cache * sizeof (void *), KM_SLEEP);
1747 }
1748 }
1749
1750 oldvdevs = sav->sav_vdevs;
1751 oldnvdevs = sav->sav_count;
1752 sav->sav_vdevs = NULL;
1753 sav->sav_count = 0;
1754
1755 /*
1756 * Process new nvlist of vdevs.
1757 */
1758 for (i = 0; i < nl2cache; i++) {
1759 VERIFY(nvlist_lookup_uint64(l2cache[i], ZPOOL_CONFIG_GUID,
1760 &guid) == 0);
1761
1762 newvdevs[i] = NULL;
1763 for (j = 0; j < oldnvdevs; j++) {
1764 vd = oldvdevs[j];
1765 if (vd != NULL && guid == vd->vdev_guid) {
1766 /*
1767 * Retain previous vdev for add/remove ops.
1768 */
1769 newvdevs[i] = vd;
1770 oldvdevs[j] = NULL;
1771 break;
1772 }
1773 }
1774
1775 if (newvdevs[i] == NULL) {
1776 /*
1777 * Create new vdev
1778 */
1779 VERIFY(spa_config_parse(spa, &vd, l2cache[i], NULL, 0,
1780 VDEV_ALLOC_L2CACHE) == 0);
1781 ASSERT(vd != NULL);
1782 newvdevs[i] = vd;
1783
1784 /*
1785 * Commit this vdev as an l2cache device,
1786 * even if it fails to open.
1787 */
1788 spa_l2cache_add(vd);
1789
1790 vd->vdev_top = vd;
1791 vd->vdev_aux = sav;
1792
1793 spa_l2cache_activate(vd);
1794
1795 if (vdev_open(vd) != 0)
1796 continue;
1797
1798 (void) vdev_validate_aux(vd);
1799
1800 if (!vdev_is_dead(vd))
1801 l2arc_add_vdev(spa, vd);
1802 }
1803 }
1804
1805 /*
1806 * Purge vdevs that were dropped
1807 */
1808 for (i = 0; i < oldnvdevs; i++) {
1809 uint64_t pool;
1810
1811 vd = oldvdevs[i];
1812 if (vd != NULL) {
1813 ASSERT(vd->vdev_isl2cache);
1814
1815 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
1816 pool != 0ULL && l2arc_vdev_present(vd))
1817 l2arc_remove_vdev(vd);
1818 vdev_clear_stats(vd);
1819 vdev_free(vd);
1820 }
1821 }
1822
1823 if (oldvdevs)
1824 kmem_free(oldvdevs, oldnvdevs * sizeof (void *));
1825
1826 if (sav->sav_config == NULL)
1827 goto out;
1828
1829 sav->sav_vdevs = newvdevs;
1830 sav->sav_count = (int)nl2cache;
1831
1832 /*
1833 * Recompute the stashed list of l2cache devices, with status
1834 * information this time.
1835 */
1836 VERIFY(nvlist_remove(sav->sav_config, ZPOOL_CONFIG_L2CACHE,
1837 DATA_TYPE_NVLIST_ARRAY) == 0);
1838
1839 l2cache = NULL;
1840 if (sav->sav_count > 0) {
1841 l2cache = kmem_alloc(
1842 sav->sav_count * sizeof (void *), KM_SLEEP);
1843 }
1844 for (i = 0; i < sav->sav_count; i++)
1845 l2cache[i] = vdev_config_generate(spa,
1846 sav->sav_vdevs[i], B_TRUE, VDEV_CONFIG_L2CACHE);
1847 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
1848 ZPOOL_CONFIG_L2CACHE, l2cache, sav->sav_count) == 0);
1849 out:
1850 for (i = 0; i < sav->sav_count; i++)
1851 nvlist_free(l2cache[i]);
1852 if (sav->sav_count)
1853 kmem_free(l2cache, sav->sav_count * sizeof (void *));
1854 }
1855
1856 static int
load_nvlist(spa_t * spa,uint64_t obj,nvlist_t ** value)1857 load_nvlist(spa_t *spa, uint64_t obj, nvlist_t **value)
1858 {
1859 dmu_buf_t *db;
1860 char *packed = NULL;
1861 size_t nvsize = 0;
1862 int error;
1863 *value = NULL;
1864
1865 error = dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db);
1866 if (error != 0)
1867 return (error);
1868
1869 nvsize = *(uint64_t *)db->db_data;
1870 dmu_buf_rele(db, FTAG);
1871
1872 packed = kmem_alloc(nvsize, KM_SLEEP);
1873 error = dmu_read(spa->spa_meta_objset, obj, 0, nvsize, packed,
1874 DMU_READ_PREFETCH);
1875 if (error == 0)
1876 error = nvlist_unpack(packed, nvsize, value, 0);
1877 kmem_free(packed, nvsize);
1878
1879 return (error);
1880 }
1881
1882 /*
1883 * Concrete top-level vdevs that are not missing and are not logs. At every
1884 * spa_sync we write new uberblocks to at least SPA_SYNC_MIN_VDEVS core tvds.
1885 */
1886 static uint64_t
spa_healthy_core_tvds(spa_t * spa)1887 spa_healthy_core_tvds(spa_t *spa)
1888 {
1889 vdev_t *rvd = spa->spa_root_vdev;
1890 uint64_t tvds = 0;
1891
1892 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
1893 vdev_t *vd = rvd->vdev_child[i];
1894 if (vd->vdev_islog)
1895 continue;
1896 if (vdev_is_concrete(vd) && !vdev_is_dead(vd))
1897 tvds++;
1898 }
1899
1900 return (tvds);
1901 }
1902
1903 /*
1904 * Checks to see if the given vdev could not be opened, in which case we post a
1905 * sysevent to notify the autoreplace code that the device has been removed.
1906 */
1907 static void
spa_check_removed(vdev_t * vd)1908 spa_check_removed(vdev_t *vd)
1909 {
1910 for (uint64_t c = 0; c < vd->vdev_children; c++)
1911 spa_check_removed(vd->vdev_child[c]);
1912
1913 if (vd->vdev_ops->vdev_op_leaf && vdev_is_dead(vd) &&
1914 vdev_is_concrete(vd)) {
1915 zfs_post_autoreplace(vd->vdev_spa, vd);
1916 spa_event_notify(vd->vdev_spa, vd, NULL, ESC_ZFS_VDEV_CHECK);
1917 }
1918 }
1919
1920 static int
spa_check_for_missing_logs(spa_t * spa)1921 spa_check_for_missing_logs(spa_t *spa)
1922 {
1923 vdev_t *rvd = spa->spa_root_vdev;
1924
1925 /*
1926 * If we're doing a normal import, then build up any additional
1927 * diagnostic information about missing log devices.
1928 * We'll pass this up to the user for further processing.
1929 */
1930 if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG)) {
1931 nvlist_t **child, *nv;
1932 uint64_t idx = 0;
1933
1934 child = kmem_alloc(rvd->vdev_children * sizeof (nvlist_t **),
1935 KM_SLEEP);
1936 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1937
1938 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1939 vdev_t *tvd = rvd->vdev_child[c];
1940
1941 /*
1942 * We consider a device as missing only if it failed
1943 * to open (i.e. offline or faulted is not considered
1944 * as missing).
1945 */
1946 if (tvd->vdev_islog &&
1947 tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1948 child[idx++] = vdev_config_generate(spa, tvd,
1949 B_FALSE, VDEV_CONFIG_MISSING);
1950 }
1951 }
1952
1953 if (idx > 0) {
1954 fnvlist_add_nvlist_array(nv,
1955 ZPOOL_CONFIG_CHILDREN, child, idx);
1956 fnvlist_add_nvlist(spa->spa_load_info,
1957 ZPOOL_CONFIG_MISSING_DEVICES, nv);
1958
1959 for (uint64_t i = 0; i < idx; i++)
1960 nvlist_free(child[i]);
1961 }
1962 nvlist_free(nv);
1963 kmem_free(child, rvd->vdev_children * sizeof (char **));
1964
1965 if (idx > 0) {
1966 spa_load_failed(spa, "some log devices are missing");
1967 vdev_dbgmsg_print_tree(rvd, 2);
1968 return (SET_ERROR(ENXIO));
1969 }
1970 } else {
1971 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1972 vdev_t *tvd = rvd->vdev_child[c];
1973
1974 if (tvd->vdev_islog &&
1975 tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1976 spa_set_log_state(spa, SPA_LOG_CLEAR);
1977 spa_load_note(spa, "some log devices are "
1978 "missing, ZIL is dropped.");
1979 vdev_dbgmsg_print_tree(rvd, 2);
1980 break;
1981 }
1982 }
1983 }
1984
1985 return (0);
1986 }
1987
1988 /*
1989 * Check for missing log devices
1990 */
1991 static boolean_t
spa_check_logs(spa_t * spa)1992 spa_check_logs(spa_t *spa)
1993 {
1994 boolean_t rv = B_FALSE;
1995 dsl_pool_t *dp = spa_get_dsl(spa);
1996
1997 switch (spa->spa_log_state) {
1998 case SPA_LOG_MISSING:
1999 /* need to recheck in case slog has been restored */
2000 case SPA_LOG_UNKNOWN:
2001 rv = (dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
2002 zil_check_log_chain, NULL, DS_FIND_CHILDREN) != 0);
2003 if (rv)
2004 spa_set_log_state(spa, SPA_LOG_MISSING);
2005 break;
2006 }
2007 return (rv);
2008 }
2009
2010 static boolean_t
spa_passivate_log(spa_t * spa)2011 spa_passivate_log(spa_t *spa)
2012 {
2013 vdev_t *rvd = spa->spa_root_vdev;
2014 boolean_t slog_found = B_FALSE;
2015
2016 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
2017
2018 if (!spa_has_slogs(spa))
2019 return (B_FALSE);
2020
2021 for (int c = 0; c < rvd->vdev_children; c++) {
2022 vdev_t *tvd = rvd->vdev_child[c];
2023 metaslab_group_t *mg = tvd->vdev_mg;
2024
2025 if (tvd->vdev_islog) {
2026 metaslab_group_passivate(mg);
2027 slog_found = B_TRUE;
2028 }
2029 }
2030
2031 return (slog_found);
2032 }
2033
2034 static void
spa_activate_log(spa_t * spa)2035 spa_activate_log(spa_t *spa)
2036 {
2037 vdev_t *rvd = spa->spa_root_vdev;
2038
2039 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
2040
2041 for (int c = 0; c < rvd->vdev_children; c++) {
2042 vdev_t *tvd = rvd->vdev_child[c];
2043 metaslab_group_t *mg = tvd->vdev_mg;
2044
2045 if (tvd->vdev_islog)
2046 metaslab_group_activate(mg);
2047 }
2048 }
2049
2050 int
spa_reset_logs(spa_t * spa)2051 spa_reset_logs(spa_t *spa)
2052 {
2053 int error;
2054
2055 error = dmu_objset_find(spa_name(spa), zil_reset,
2056 NULL, DS_FIND_CHILDREN);
2057 if (error == 0) {
2058 /*
2059 * We successfully offlined the log device, sync out the
2060 * current txg so that the "stubby" block can be removed
2061 * by zil_sync().
2062 */
2063 txg_wait_synced(spa->spa_dsl_pool, 0);
2064 }
2065 return (error);
2066 }
2067
2068 static void
spa_aux_check_removed(spa_aux_vdev_t * sav)2069 spa_aux_check_removed(spa_aux_vdev_t *sav)
2070 {
2071 for (int i = 0; i < sav->sav_count; i++)
2072 spa_check_removed(sav->sav_vdevs[i]);
2073 }
2074
2075 void
spa_claim_notify(zio_t * zio)2076 spa_claim_notify(zio_t *zio)
2077 {
2078 spa_t *spa = zio->io_spa;
2079
2080 if (zio->io_error)
2081 return;
2082
2083 mutex_enter(&spa->spa_props_lock); /* any mutex will do */
2084 if (spa->spa_claim_max_txg < zio->io_bp->blk_birth)
2085 spa->spa_claim_max_txg = zio->io_bp->blk_birth;
2086 mutex_exit(&spa->spa_props_lock);
2087 }
2088
2089 typedef struct spa_load_error {
2090 uint64_t sle_meta_count;
2091 uint64_t sle_data_count;
2092 } spa_load_error_t;
2093
2094 static void
spa_load_verify_done(zio_t * zio)2095 spa_load_verify_done(zio_t *zio)
2096 {
2097 blkptr_t *bp = zio->io_bp;
2098 spa_load_error_t *sle = zio->io_private;
2099 dmu_object_type_t type = BP_GET_TYPE(bp);
2100 int error = zio->io_error;
2101 spa_t *spa = zio->io_spa;
2102
2103 abd_free(zio->io_abd);
2104 if (error) {
2105 if ((BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type)) &&
2106 type != DMU_OT_INTENT_LOG)
2107 atomic_inc_64(&sle->sle_meta_count);
2108 else
2109 atomic_inc_64(&sle->sle_data_count);
2110 }
2111
2112 mutex_enter(&spa->spa_scrub_lock);
2113 spa->spa_load_verify_ios--;
2114 cv_broadcast(&spa->spa_scrub_io_cv);
2115 mutex_exit(&spa->spa_scrub_lock);
2116 }
2117
2118 /*
2119 * Maximum number of concurrent scrub i/os to create while verifying
2120 * a pool while importing it.
2121 */
2122 int spa_load_verify_maxinflight = 10000;
2123 boolean_t spa_load_verify_metadata = B_TRUE;
2124 boolean_t spa_load_verify_data = B_TRUE;
2125
2126 /*ARGSUSED*/
2127 static int
spa_load_verify_cb(spa_t * spa,zilog_t * zilog,const blkptr_t * bp,const zbookmark_phys_t * zb,const dnode_phys_t * dnp,void * arg)2128 spa_load_verify_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2129 const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
2130 {
2131 if (bp == NULL || BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2132 return (0);
2133 /*
2134 * Note: normally this routine will not be called if
2135 * spa_load_verify_metadata is not set. However, it may be useful
2136 * to manually set the flag after the traversal has begun.
2137 */
2138 if (!spa_load_verify_metadata)
2139 return (0);
2140 if (!BP_IS_METADATA(bp) && !spa_load_verify_data)
2141 return (0);
2142
2143 zio_t *rio = arg;
2144 size_t size = BP_GET_PSIZE(bp);
2145
2146 mutex_enter(&spa->spa_scrub_lock);
2147 while (spa->spa_load_verify_ios >= spa_load_verify_maxinflight)
2148 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
2149 spa->spa_load_verify_ios++;
2150 mutex_exit(&spa->spa_scrub_lock);
2151
2152 zio_nowait(zio_read(rio, spa, bp, abd_alloc_for_io(size, B_FALSE), size,
2153 spa_load_verify_done, rio->io_private, ZIO_PRIORITY_SCRUB,
2154 ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CANFAIL |
2155 ZIO_FLAG_SCRUB | ZIO_FLAG_RAW, zb));
2156 return (0);
2157 }
2158
2159 /* ARGSUSED */
2160 int
verify_dataset_name_len(dsl_pool_t * dp,dsl_dataset_t * ds,void * arg)2161 verify_dataset_name_len(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
2162 {
2163 if (dsl_dataset_namelen(ds) >= ZFS_MAX_DATASET_NAME_LEN)
2164 return (SET_ERROR(ENAMETOOLONG));
2165
2166 return (0);
2167 }
2168
2169 static int
spa_load_verify(spa_t * spa)2170 spa_load_verify(spa_t *spa)
2171 {
2172 zio_t *rio;
2173 spa_load_error_t sle = { 0 };
2174 zpool_load_policy_t policy;
2175 boolean_t verify_ok = B_FALSE;
2176 int error = 0;
2177
2178 zpool_get_load_policy(spa->spa_config, &policy);
2179
2180 if (policy.zlp_rewind & ZPOOL_NEVER_REWIND)
2181 return (0);
2182
2183 dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
2184 error = dmu_objset_find_dp(spa->spa_dsl_pool,
2185 spa->spa_dsl_pool->dp_root_dir_obj, verify_dataset_name_len, NULL,
2186 DS_FIND_CHILDREN);
2187 dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
2188 if (error != 0)
2189 return (error);
2190
2191 rio = zio_root(spa, NULL, &sle,
2192 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
2193
2194 if (spa_load_verify_metadata) {
2195 if (spa->spa_extreme_rewind) {
2196 spa_load_note(spa, "performing a complete scan of the "
2197 "pool since extreme rewind is on. This may take "
2198 "a very long time.\n (spa_load_verify_data=%u, "
2199 "spa_load_verify_metadata=%u)",
2200 spa_load_verify_data, spa_load_verify_metadata);
2201 }
2202 error = traverse_pool(spa, spa->spa_verify_min_txg,
2203 TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
2204 TRAVERSE_NO_DECRYPT, spa_load_verify_cb, rio);
2205 }
2206
2207 (void) zio_wait(rio);
2208
2209 spa->spa_load_meta_errors = sle.sle_meta_count;
2210 spa->spa_load_data_errors = sle.sle_data_count;
2211
2212 if (sle.sle_meta_count != 0 || sle.sle_data_count != 0) {
2213 spa_load_note(spa, "spa_load_verify found %llu metadata errors "
2214 "and %llu data errors", (u_longlong_t)sle.sle_meta_count,
2215 (u_longlong_t)sle.sle_data_count);
2216 }
2217
2218 if (spa_load_verify_dryrun ||
2219 (!error && sle.sle_meta_count <= policy.zlp_maxmeta &&
2220 sle.sle_data_count <= policy.zlp_maxdata)) {
2221 int64_t loss = 0;
2222
2223 verify_ok = B_TRUE;
2224 spa->spa_load_txg = spa->spa_uberblock.ub_txg;
2225 spa->spa_load_txg_ts = spa->spa_uberblock.ub_timestamp;
2226
2227 loss = spa->spa_last_ubsync_txg_ts - spa->spa_load_txg_ts;
2228 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2229 ZPOOL_CONFIG_LOAD_TIME, spa->spa_load_txg_ts) == 0);
2230 VERIFY(nvlist_add_int64(spa->spa_load_info,
2231 ZPOOL_CONFIG_REWIND_TIME, loss) == 0);
2232 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2233 ZPOOL_CONFIG_LOAD_DATA_ERRORS, sle.sle_data_count) == 0);
2234 } else {
2235 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg;
2236 }
2237
2238 if (spa_load_verify_dryrun)
2239 return (0);
2240
2241 if (error) {
2242 if (error != ENXIO && error != EIO)
2243 error = SET_ERROR(EIO);
2244 return (error);
2245 }
2246
2247 return (verify_ok ? 0 : EIO);
2248 }
2249
2250 /*
2251 * Find a value in the pool props object.
2252 */
2253 static void
spa_prop_find(spa_t * spa,zpool_prop_t prop,uint64_t * val)2254 spa_prop_find(spa_t *spa, zpool_prop_t prop, uint64_t *val)
2255 {
2256 (void) zap_lookup(spa->spa_meta_objset, spa->spa_pool_props_object,
2257 zpool_prop_to_name(prop), sizeof (uint64_t), 1, val);
2258 }
2259
2260 /*
2261 * Find a value in the pool directory object.
2262 */
2263 static int
spa_dir_prop(spa_t * spa,const char * name,uint64_t * val,boolean_t log_enoent)2264 spa_dir_prop(spa_t *spa, const char *name, uint64_t *val, boolean_t log_enoent)
2265 {
2266 int error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
2267 name, sizeof (uint64_t), 1, val);
2268
2269 if (error != 0 && (error != ENOENT || log_enoent)) {
2270 spa_load_failed(spa, "couldn't get '%s' value in MOS directory "
2271 "[error=%d]", name, error);
2272 }
2273
2274 return (error);
2275 }
2276
2277 static int
spa_vdev_err(vdev_t * vdev,vdev_aux_t aux,int err)2278 spa_vdev_err(vdev_t *vdev, vdev_aux_t aux, int err)
2279 {
2280 vdev_set_state(vdev, B_TRUE, VDEV_STATE_CANT_OPEN, aux);
2281 return (SET_ERROR(err));
2282 }
2283
2284 static void
spa_spawn_aux_threads(spa_t * spa)2285 spa_spawn_aux_threads(spa_t *spa)
2286 {
2287 ASSERT(spa_writeable(spa));
2288
2289 ASSERT(MUTEX_HELD(&spa_namespace_lock));
2290
2291 spa_start_indirect_condensing_thread(spa);
2292
2293 ASSERT3P(spa->spa_checkpoint_discard_zthr, ==, NULL);
2294 spa->spa_checkpoint_discard_zthr =
2295 zthr_create(spa_checkpoint_discard_thread_check,
2296 spa_checkpoint_discard_thread, spa);
2297 }
2298
2299 /*
2300 * Fix up config after a partly-completed split. This is done with the
2301 * ZPOOL_CONFIG_SPLIT nvlist. Both the splitting pool and the split-off
2302 * pool have that entry in their config, but only the splitting one contains
2303 * a list of all the guids of the vdevs that are being split off.
2304 *
2305 * This function determines what to do with that list: either rejoin
2306 * all the disks to the pool, or complete the splitting process. To attempt
2307 * the rejoin, each disk that is offlined is marked online again, and
2308 * we do a reopen() call. If the vdev label for every disk that was
2309 * marked online indicates it was successfully split off (VDEV_AUX_SPLIT_POOL)
2310 * then we call vdev_split() on each disk, and complete the split.
2311 *
2312 * Otherwise we leave the config alone, with all the vdevs in place in
2313 * the original pool.
2314 */
2315 static void
spa_try_repair(spa_t * spa,nvlist_t * config)2316 spa_try_repair(spa_t *spa, nvlist_t *config)
2317 {
2318 uint_t extracted;
2319 uint64_t *glist;
2320 uint_t i, gcount;
2321 nvlist_t *nvl;
2322 vdev_t **vd;
2323 boolean_t attempt_reopen;
2324
2325 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) != 0)
2326 return;
2327
2328 /* check that the config is complete */
2329 if (nvlist_lookup_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
2330 &glist, &gcount) != 0)
2331 return;
2332
2333 vd = kmem_zalloc(gcount * sizeof (vdev_t *), KM_SLEEP);
2334
2335 /* attempt to online all the vdevs & validate */
2336 attempt_reopen = B_TRUE;
2337 for (i = 0; i < gcount; i++) {
2338 if (glist[i] == 0) /* vdev is hole */
2339 continue;
2340
2341 vd[i] = spa_lookup_by_guid(spa, glist[i], B_FALSE);
2342 if (vd[i] == NULL) {
2343 /*
2344 * Don't bother attempting to reopen the disks;
2345 * just do the split.
2346 */
2347 attempt_reopen = B_FALSE;
2348 } else {
2349 /* attempt to re-online it */
2350 vd[i]->vdev_offline = B_FALSE;
2351 }
2352 }
2353
2354 if (attempt_reopen) {
2355 vdev_reopen(spa->spa_root_vdev);
2356
2357 /* check each device to see what state it's in */
2358 for (extracted = 0, i = 0; i < gcount; i++) {
2359 if (vd[i] != NULL &&
2360 vd[i]->vdev_stat.vs_aux != VDEV_AUX_SPLIT_POOL)
2361 break;
2362 ++extracted;
2363 }
2364 }
2365
2366 /*
2367 * If every disk has been moved to the new pool, or if we never
2368 * even attempted to look at them, then we split them off for
2369 * good.
2370 */
2371 if (!attempt_reopen || gcount == extracted) {
2372 for (i = 0; i < gcount; i++)
2373 if (vd[i] != NULL)
2374 vdev_split(vd[i]);
2375 vdev_reopen(spa->spa_root_vdev);
2376 }
2377
2378 kmem_free(vd, gcount * sizeof (vdev_t *));
2379 }
2380
2381 static int
spa_load(spa_t * spa,spa_load_state_t state,spa_import_type_t type)2382 spa_load(spa_t *spa, spa_load_state_t state, spa_import_type_t type)
2383 {
2384 char *ereport = FM_EREPORT_ZFS_POOL;
2385 int error;
2386
2387 spa->spa_load_state = state;
2388 (void) spa_import_progress_set_state(spa, spa_load_state(spa));
2389
2390 gethrestime(&spa->spa_loaded_ts);
2391 error = spa_load_impl(spa, type, &ereport);
2392
2393 /*
2394 * Don't count references from objsets that are already closed
2395 * and are making their way through the eviction process.
2396 */
2397 spa_evicting_os_wait(spa);
2398 spa->spa_minref = zfs_refcount_count(&spa->spa_refcount);
2399 if (error) {
2400 if (error != EEXIST) {
2401 spa->spa_loaded_ts.tv_sec = 0;
2402 spa->spa_loaded_ts.tv_nsec = 0;
2403 }
2404 if (error != EBADF) {
2405 (void) zfs_ereport_post(ereport, spa,
2406 NULL, NULL, NULL, 0, 0);
2407 }
2408 }
2409 spa->spa_load_state = error ? SPA_LOAD_ERROR : SPA_LOAD_NONE;
2410 spa->spa_ena = 0;
2411
2412 (void) spa_import_progress_set_state(spa, spa_load_state(spa));
2413
2414 return (error);
2415 }
2416
2417 /*
2418 * Count the number of per-vdev ZAPs associated with all of the vdevs in the
2419 * vdev tree rooted in the given vd, and ensure that each ZAP is present in the
2420 * spa's per-vdev ZAP list.
2421 */
2422 static uint64_t
vdev_count_verify_zaps(vdev_t * vd)2423 vdev_count_verify_zaps(vdev_t *vd)
2424 {
2425 spa_t *spa = vd->vdev_spa;
2426 uint64_t total = 0;
2427 if (vd->vdev_top_zap != 0) {
2428 total++;
2429 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2430 spa->spa_all_vdev_zaps, vd->vdev_top_zap));
2431 }
2432 if (vd->vdev_leaf_zap != 0) {
2433 total++;
2434 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2435 spa->spa_all_vdev_zaps, vd->vdev_leaf_zap));
2436 }
2437
2438 for (uint64_t i = 0; i < vd->vdev_children; i++) {
2439 total += vdev_count_verify_zaps(vd->vdev_child[i]);
2440 }
2441
2442 return (total);
2443 }
2444
2445 /*
2446 * Determine whether the activity check is required.
2447 */
2448 static boolean_t
spa_activity_check_required(spa_t * spa,uberblock_t * ub,nvlist_t * label,nvlist_t * config)2449 spa_activity_check_required(spa_t *spa, uberblock_t *ub, nvlist_t *label,
2450 nvlist_t *config)
2451 {
2452 uint64_t state = 0;
2453 uint64_t hostid = 0;
2454 uint64_t tryconfig_txg = 0;
2455 uint64_t tryconfig_timestamp = 0;
2456 uint16_t tryconfig_mmp_seq = 0;
2457 nvlist_t *nvinfo;
2458
2459 if (nvlist_exists(config, ZPOOL_CONFIG_LOAD_INFO)) {
2460 nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
2461 (void) nvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_MMP_TXG,
2462 &tryconfig_txg);
2463 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
2464 &tryconfig_timestamp);
2465 (void) nvlist_lookup_uint16(nvinfo, ZPOOL_CONFIG_MMP_SEQ,
2466 &tryconfig_mmp_seq);
2467 }
2468
2469 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE, &state);
2470
2471 /*
2472 * Disable the MMP activity check - This is used by zdb which
2473 * is intended to be used on potentially active pools.
2474 */
2475 if (spa->spa_import_flags & ZFS_IMPORT_SKIP_MMP)
2476 return (B_FALSE);
2477
2478 /*
2479 * Skip the activity check when the MMP feature is disabled.
2480 */
2481 if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay == 0)
2482 return (B_FALSE);
2483
2484 /*
2485 * If the tryconfig_ values are nonzero, they are the results of an
2486 * earlier tryimport. If they all match the uberblock we just found,
2487 * then the pool has not changed and we return false so we do not test
2488 * a second time.
2489 */
2490 if (tryconfig_txg && tryconfig_txg == ub->ub_txg &&
2491 tryconfig_timestamp && tryconfig_timestamp == ub->ub_timestamp &&
2492 tryconfig_mmp_seq && tryconfig_mmp_seq ==
2493 (MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0))
2494 return (B_FALSE);
2495
2496 /*
2497 * Allow the activity check to be skipped when importing the pool
2498 * on the same host which last imported it. Since the hostid from
2499 * configuration may be stale use the one read from the label.
2500 */
2501 if (nvlist_exists(label, ZPOOL_CONFIG_HOSTID))
2502 hostid = fnvlist_lookup_uint64(label, ZPOOL_CONFIG_HOSTID);
2503
2504 if (hostid == spa_get_hostid())
2505 return (B_FALSE);
2506
2507 /*
2508 * Skip the activity test when the pool was cleanly exported.
2509 */
2510 if (state != POOL_STATE_ACTIVE)
2511 return (B_FALSE);
2512
2513 return (B_TRUE);
2514 }
2515
2516 /*
2517 * Nanoseconds the activity check must watch for changes on-disk.
2518 */
2519 static uint64_t
spa_activity_check_duration(spa_t * spa,uberblock_t * ub)2520 spa_activity_check_duration(spa_t *spa, uberblock_t *ub)
2521 {
2522 uint64_t import_intervals = MAX(zfs_multihost_import_intervals, 1);
2523 uint64_t multihost_interval = MSEC2NSEC(
2524 MMP_INTERVAL_OK(zfs_multihost_interval));
2525 uint64_t import_delay = MAX(NANOSEC, import_intervals *
2526 multihost_interval);
2527
2528 /*
2529 * Local tunables determine a minimum duration except for the case
2530 * where we know when the remote host will suspend the pool if MMP
2531 * writes do not land.
2532 *
2533 * See Big Theory comment at the top of mmp.c for the reasoning behind
2534 * these cases and times.
2535 */
2536
2537 ASSERT(MMP_IMPORT_SAFETY_FACTOR >= 100);
2538
2539 if (MMP_INTERVAL_VALID(ub) && MMP_FAIL_INT_VALID(ub) &&
2540 MMP_FAIL_INT(ub) > 0) {
2541
2542 /* MMP on remote host will suspend pool after failed writes */
2543 import_delay = MMP_FAIL_INT(ub) * MSEC2NSEC(MMP_INTERVAL(ub)) *
2544 MMP_IMPORT_SAFETY_FACTOR / 100;
2545
2546 zfs_dbgmsg("fail_intvals>0 import_delay=%llu ub_mmp "
2547 "mmp_fails=%llu ub_mmp mmp_interval=%llu "
2548 "import_intervals=%u", import_delay, MMP_FAIL_INT(ub),
2549 MMP_INTERVAL(ub), import_intervals);
2550
2551 } else if (MMP_INTERVAL_VALID(ub) && MMP_FAIL_INT_VALID(ub) &&
2552 MMP_FAIL_INT(ub) == 0) {
2553
2554 /* MMP on remote host will never suspend pool */
2555 import_delay = MAX(import_delay, (MSEC2NSEC(MMP_INTERVAL(ub)) +
2556 ub->ub_mmp_delay) * import_intervals);
2557
2558 zfs_dbgmsg("fail_intvals=0 import_delay=%llu ub_mmp "
2559 "mmp_interval=%llu ub_mmp_delay=%llu "
2560 "import_intervals=%u", import_delay, MMP_INTERVAL(ub),
2561 ub->ub_mmp_delay, import_intervals);
2562
2563 } else if (MMP_VALID(ub)) {
2564 /*
2565 * zfs-0.7 compatability case
2566 */
2567
2568 import_delay = MAX(import_delay, (multihost_interval +
2569 ub->ub_mmp_delay) * import_intervals);
2570
2571 zfs_dbgmsg("import_delay=%llu ub_mmp_delay=%llu "
2572 "import_intervals=%u leaves=%u", import_delay,
2573 ub->ub_mmp_delay, import_intervals,
2574 vdev_count_leaves(spa));
2575 } else {
2576 /* Using local tunings is the only reasonable option */
2577 zfs_dbgmsg("pool last imported on non-MMP aware "
2578 "host using import_delay=%llu multihost_interval=%llu "
2579 "import_intervals=%u", import_delay, multihost_interval,
2580 import_intervals);
2581 }
2582
2583 return (import_delay);
2584 }
2585
2586 /*
2587 * Perform the import activity check. If the user canceled the import or
2588 * we detected activity then fail.
2589 */
2590 static int
spa_activity_check(spa_t * spa,uberblock_t * ub,nvlist_t * config)2591 spa_activity_check(spa_t *spa, uberblock_t *ub, nvlist_t *config)
2592 {
2593 uint64_t txg = ub->ub_txg;
2594 uint64_t timestamp = ub->ub_timestamp;
2595 uint64_t mmp_config = ub->ub_mmp_config;
2596 uint16_t mmp_seq = MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0;
2597 uint64_t import_delay;
2598 hrtime_t import_expire;
2599 nvlist_t *mmp_label = NULL;
2600 vdev_t *rvd = spa->spa_root_vdev;
2601 kcondvar_t cv;
2602 kmutex_t mtx;
2603 int error = 0;
2604
2605 cv_init(&cv, NULL, CV_DEFAULT, NULL);
2606 mutex_init(&mtx, NULL, MUTEX_DEFAULT, NULL);
2607 mutex_enter(&mtx);
2608
2609 /*
2610 * If ZPOOL_CONFIG_MMP_TXG is present an activity check was performed
2611 * during the earlier tryimport. If the txg recorded there is 0 then
2612 * the pool is known to be active on another host.
2613 *
2614 * Otherwise, the pool might be in use on another host. Check for
2615 * changes in the uberblocks on disk if necessary.
2616 */
2617 if (nvlist_exists(config, ZPOOL_CONFIG_LOAD_INFO)) {
2618 nvlist_t *nvinfo = fnvlist_lookup_nvlist(config,
2619 ZPOOL_CONFIG_LOAD_INFO);
2620
2621 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_TXG) &&
2622 fnvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_MMP_TXG) == 0) {
2623 vdev_uberblock_load(rvd, ub, &mmp_label);
2624 error = SET_ERROR(EREMOTEIO);
2625 goto out;
2626 }
2627 }
2628
2629 import_delay = spa_activity_check_duration(spa, ub);
2630
2631 /* Add a small random factor in case of simultaneous imports (0-25%) */
2632 import_delay += import_delay * spa_get_random(250) / 1000;
2633
2634 import_expire = gethrtime() + import_delay;
2635
2636 while (gethrtime() < import_expire) {
2637 (void) spa_import_progress_set_mmp_check(spa,
2638 NSEC2SEC(import_expire - gethrtime()));
2639
2640 vdev_uberblock_load(rvd, ub, &mmp_label);
2641
2642 if (txg != ub->ub_txg || timestamp != ub->ub_timestamp ||
2643 mmp_seq != (MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0)) {
2644 zfs_dbgmsg("multihost activity detected "
2645 "txg %llu ub_txg %llu "
2646 "timestamp %llu ub_timestamp %llu "
2647 "mmp_config %#llx ub_mmp_config %#llx",
2648 txg, ub->ub_txg, timestamp, ub->ub_timestamp,
2649 mmp_config, ub->ub_mmp_config);
2650
2651 error = SET_ERROR(EREMOTEIO);
2652 break;
2653 }
2654
2655 if (mmp_label) {
2656 nvlist_free(mmp_label);
2657 mmp_label = NULL;
2658 }
2659
2660 error = cv_timedwait_sig(&cv, &mtx, ddi_get_lbolt() + hz);
2661 if (error != -1) {
2662 error = SET_ERROR(EINTR);
2663 break;
2664 }
2665 error = 0;
2666 }
2667
2668 out:
2669 mutex_exit(&mtx);
2670 mutex_destroy(&mtx);
2671 cv_destroy(&cv);
2672
2673 /*
2674 * If the pool is determined to be active store the status in the
2675 * spa->spa_load_info nvlist. If the remote hostname or hostid are
2676 * available from configuration read from disk store them as well.
2677 * This allows 'zpool import' to generate a more useful message.
2678 *
2679 * ZPOOL_CONFIG_MMP_STATE - observed pool status (mandatory)
2680 * ZPOOL_CONFIG_MMP_HOSTNAME - hostname from the active pool
2681 * ZPOOL_CONFIG_MMP_HOSTID - hostid from the active pool
2682 */
2683 if (error == EREMOTEIO) {
2684 char *hostname = "<unknown>";
2685 uint64_t hostid = 0;
2686
2687 if (mmp_label) {
2688 if (nvlist_exists(mmp_label, ZPOOL_CONFIG_HOSTNAME)) {
2689 hostname = fnvlist_lookup_string(mmp_label,
2690 ZPOOL_CONFIG_HOSTNAME);
2691 fnvlist_add_string(spa->spa_load_info,
2692 ZPOOL_CONFIG_MMP_HOSTNAME, hostname);
2693 }
2694
2695 if (nvlist_exists(mmp_label, ZPOOL_CONFIG_HOSTID)) {
2696 hostid = fnvlist_lookup_uint64(mmp_label,
2697 ZPOOL_CONFIG_HOSTID);
2698 fnvlist_add_uint64(spa->spa_load_info,
2699 ZPOOL_CONFIG_MMP_HOSTID, hostid);
2700 }
2701 }
2702
2703 fnvlist_add_uint64(spa->spa_load_info,
2704 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_ACTIVE);
2705 fnvlist_add_uint64(spa->spa_load_info,
2706 ZPOOL_CONFIG_MMP_TXG, 0);
2707
2708 error = spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO);
2709 }
2710
2711 if (mmp_label)
2712 nvlist_free(mmp_label);
2713
2714 return (error);
2715 }
2716
2717 static int
spa_verify_host(spa_t * spa,nvlist_t * mos_config)2718 spa_verify_host(spa_t *spa, nvlist_t *mos_config)
2719 {
2720 uint64_t hostid;
2721 char *hostname;
2722 uint64_t myhostid = 0;
2723
2724 if (!spa_is_root(spa) && nvlist_lookup_uint64(mos_config,
2725 ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
2726 hostname = fnvlist_lookup_string(mos_config,
2727 ZPOOL_CONFIG_HOSTNAME);
2728
2729 myhostid = zone_get_hostid(NULL);
2730
2731 if (hostid != 0 && myhostid != 0 && hostid != myhostid) {
2732 cmn_err(CE_WARN, "pool '%s' could not be "
2733 "loaded as it was last accessed by "
2734 "another system (host: %s hostid: 0x%llx). "
2735 "See: http://illumos.org/msg/ZFS-8000-EY",
2736 spa_name(spa), hostname, (u_longlong_t)hostid);
2737 spa_load_failed(spa, "hostid verification failed: pool "
2738 "last accessed by host: %s (hostid: 0x%llx)",
2739 hostname, (u_longlong_t)hostid);
2740 return (SET_ERROR(EBADF));
2741 }
2742 }
2743
2744 return (0);
2745 }
2746
2747 static int
spa_ld_parse_config(spa_t * spa,spa_import_type_t type)2748 spa_ld_parse_config(spa_t *spa, spa_import_type_t type)
2749 {
2750 int error = 0;
2751 nvlist_t *nvtree, *nvl, *config = spa->spa_config;
2752 int parse;
2753 vdev_t *rvd;
2754 uint64_t pool_guid;
2755 char *comment;
2756
2757 /*
2758 * Versioning wasn't explicitly added to the label until later, so if
2759 * it's not present treat it as the initial version.
2760 */
2761 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
2762 &spa->spa_ubsync.ub_version) != 0)
2763 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
2764
2765 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid)) {
2766 spa_load_failed(spa, "invalid config provided: '%s' missing",
2767 ZPOOL_CONFIG_POOL_GUID);
2768 return (SET_ERROR(EINVAL));
2769 }
2770
2771 /*
2772 * If we are doing an import, ensure that the pool is not already
2773 * imported by checking if its pool guid already exists in the
2774 * spa namespace.
2775 *
2776 * The only case that we allow an already imported pool to be
2777 * imported again, is when the pool is checkpointed and we want to
2778 * look at its checkpointed state from userland tools like zdb.
2779 */
2780 #ifdef _KERNEL
2781 if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2782 spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2783 spa_guid_exists(pool_guid, 0)) {
2784 #else
2785 if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2786 spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2787 spa_guid_exists(pool_guid, 0) &&
2788 !spa_importing_readonly_checkpoint(spa)) {
2789 #endif
2790 spa_load_failed(spa, "a pool with guid %llu is already open",
2791 (u_longlong_t)pool_guid);
2792 return (SET_ERROR(EEXIST));
2793 }
2794
2795 spa->spa_config_guid = pool_guid;
2796
2797 nvlist_free(spa->spa_load_info);
2798 spa->spa_load_info = fnvlist_alloc();
2799
2800 ASSERT(spa->spa_comment == NULL);
2801 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2802 spa->spa_comment = spa_strdup(comment);
2803
2804 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
2805 &spa->spa_config_txg);
2806
2807 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) == 0)
2808 spa->spa_config_splitting = fnvlist_dup(nvl);
2809
2810 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvtree)) {
2811 spa_load_failed(spa, "invalid config provided: '%s' missing",
2812 ZPOOL_CONFIG_VDEV_TREE);
2813 return (SET_ERROR(EINVAL));
2814 }
2815
2816 /*
2817 * Create "The Godfather" zio to hold all async IOs
2818 */
2819 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
2820 KM_SLEEP);
2821 for (int i = 0; i < max_ncpus; i++) {
2822 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
2823 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2824 ZIO_FLAG_GODFATHER);
2825 }
2826
2827 /*
2828 * Parse the configuration into a vdev tree. We explicitly set the
2829 * value that will be returned by spa_version() since parsing the
2830 * configuration requires knowing the version number.
2831 */
2832 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2833 parse = (type == SPA_IMPORT_EXISTING ?
2834 VDEV_ALLOC_LOAD : VDEV_ALLOC_SPLIT);
2835 error = spa_config_parse(spa, &rvd, nvtree, NULL, 0, parse);
2836 spa_config_exit(spa, SCL_ALL, FTAG);
2837
2838 if (error != 0) {
2839 spa_load_failed(spa, "unable to parse config [error=%d]",
2840 error);
2841 return (error);
2842 }
2843
2844 ASSERT(spa->spa_root_vdev == rvd);
2845 ASSERT3U(spa->spa_min_ashift, >=, SPA_MINBLOCKSHIFT);
2846 ASSERT3U(spa->spa_max_ashift, <=, SPA_MAXBLOCKSHIFT);
2847
2848 if (type != SPA_IMPORT_ASSEMBLE) {
2849 ASSERT(spa_guid(spa) == pool_guid);
2850 }
2851
2852 return (0);
2853 }
2854
2855 /*
2856 * Recursively open all vdevs in the vdev tree. This function is called twice:
2857 * first with the untrusted config, then with the trusted config.
2858 */
2859 static int
2860 spa_ld_open_vdevs(spa_t *spa)
2861 {
2862 int error = 0;
2863
2864 /*
2865 * spa_missing_tvds_allowed defines how many top-level vdevs can be
2866 * missing/unopenable for the root vdev to be still considered openable.
2867 */
2868 if (spa->spa_trust_config) {
2869 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds;
2870 } else if (spa->spa_config_source == SPA_CONFIG_SRC_CACHEFILE) {
2871 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_cachefile;
2872 } else if (spa->spa_config_source == SPA_CONFIG_SRC_SCAN) {
2873 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_scan;
2874 } else {
2875 spa->spa_missing_tvds_allowed = 0;
2876 }
2877
2878 spa->spa_missing_tvds_allowed =
2879 MAX(zfs_max_missing_tvds, spa->spa_missing_tvds_allowed);
2880
2881 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2882 error = vdev_open(spa->spa_root_vdev);
2883 spa_config_exit(spa, SCL_ALL, FTAG);
2884
2885 if (spa->spa_missing_tvds != 0) {
2886 spa_load_note(spa, "vdev tree has %lld missing top-level "
2887 "vdevs.", (u_longlong_t)spa->spa_missing_tvds);
2888 if (spa->spa_trust_config && (spa->spa_mode & FWRITE)) {
2889 /*
2890 * Although theoretically we could allow users to open
2891 * incomplete pools in RW mode, we'd need to add a lot
2892 * of extra logic (e.g. adjust pool space to account
2893 * for missing vdevs).
2894 * This limitation also prevents users from accidentally
2895 * opening the pool in RW mode during data recovery and
2896 * damaging it further.
2897 */
2898 spa_load_note(spa, "pools with missing top-level "
2899 "vdevs can only be opened in read-only mode.");
2900 error = SET_ERROR(ENXIO);
2901 } else {
2902 spa_load_note(spa, "current settings allow for maximum "
2903 "%lld missing top-level vdevs at this stage.",
2904 (u_longlong_t)spa->spa_missing_tvds_allowed);
2905 }
2906 }
2907 if (error != 0) {
2908 spa_load_failed(spa, "unable to open vdev tree [error=%d]",
2909 error);
2910 }
2911 if (spa->spa_missing_tvds != 0 || error != 0)
2912 vdev_dbgmsg_print_tree(spa->spa_root_vdev, 2);
2913
2914 return (error);
2915 }
2916
2917 /*
2918 * We need to validate the vdev labels against the configuration that
2919 * we have in hand. This function is called twice: first with an untrusted
2920 * config, then with a trusted config. The validation is more strict when the
2921 * config is trusted.
2922 */
2923 static int
2924 spa_ld_validate_vdevs(spa_t *spa)
2925 {
2926 int error = 0;
2927 vdev_t *rvd = spa->spa_root_vdev;
2928
2929 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2930 error = vdev_validate(rvd);
2931 spa_config_exit(spa, SCL_ALL, FTAG);
2932
2933 if (error != 0) {
2934 spa_load_failed(spa, "vdev_validate failed [error=%d]", error);
2935 return (error);
2936 }
2937
2938 if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN) {
2939 spa_load_failed(spa, "cannot open vdev tree after invalidating "
2940 "some vdevs");
2941 vdev_dbgmsg_print_tree(rvd, 2);
2942 return (SET_ERROR(ENXIO));
2943 }
2944
2945 return (0);
2946 }
2947
2948 static void
2949 spa_ld_select_uberblock_done(spa_t *spa, uberblock_t *ub)
2950 {
2951 spa->spa_state = POOL_STATE_ACTIVE;
2952 spa->spa_ubsync = spa->spa_uberblock;
2953 spa->spa_verify_min_txg = spa->spa_extreme_rewind ?
2954 TXG_INITIAL - 1 : spa_last_synced_txg(spa) - TXG_DEFER_SIZE - 1;
2955 spa->spa_first_txg = spa->spa_last_ubsync_txg ?
2956 spa->spa_last_ubsync_txg : spa_last_synced_txg(spa) + 1;
2957 spa->spa_claim_max_txg = spa->spa_first_txg;
2958 spa->spa_prev_software_version = ub->ub_software_version;
2959 }
2960
2961 static int
2962 spa_ld_select_uberblock(spa_t *spa, spa_import_type_t type)
2963 {
2964 vdev_t *rvd = spa->spa_root_vdev;
2965 nvlist_t *label;
2966 uberblock_t *ub = &spa->spa_uberblock;
2967 boolean_t activity_check = B_FALSE;
2968
2969 /*
2970 * If we are opening the checkpointed state of the pool by
2971 * rewinding to it, at this point we will have written the
2972 * checkpointed uberblock to the vdev labels, so searching
2973 * the labels will find the right uberblock. However, if
2974 * we are opening the checkpointed state read-only, we have
2975 * not modified the labels. Therefore, we must ignore the
2976 * labels and continue using the spa_uberblock that was set
2977 * by spa_ld_checkpoint_rewind.
2978 *
2979 * Note that it would be fine to ignore the labels when
2980 * rewinding (opening writeable) as well. However, if we
2981 * crash just after writing the labels, we will end up
2982 * searching the labels. Doing so in the common case means
2983 * that this code path gets exercised normally, rather than
2984 * just in the edge case.
2985 */
2986 if (ub->ub_checkpoint_txg != 0 &&
2987 spa_importing_readonly_checkpoint(spa)) {
2988 spa_ld_select_uberblock_done(spa, ub);
2989 return (0);
2990 }
2991
2992 /*
2993 * Find the best uberblock.
2994 */
2995 vdev_uberblock_load(rvd, ub, &label);
2996
2997 /*
2998 * If we weren't able to find a single valid uberblock, return failure.
2999 */
3000 if (ub->ub_txg == 0) {
3001 nvlist_free(label);
3002 spa_load_failed(spa, "no valid uberblock found");
3003 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, ENXIO));
3004 }
3005
3006 if (spa->spa_load_max_txg != UINT64_MAX) {
3007 (void) spa_import_progress_set_max_txg(spa,
3008 (u_longlong_t)spa->spa_load_max_txg);
3009 }
3010 spa_load_note(spa, "using uberblock with txg=%llu",
3011 (u_longlong_t)ub->ub_txg);
3012
3013 /*
3014 * For pools which have the multihost property on determine if the
3015 * pool is truly inactive and can be safely imported. Prevent
3016 * hosts which don't have a hostid set from importing the pool.
3017 */
3018 activity_check = spa_activity_check_required(spa, ub, label,
3019 spa->spa_config);
3020 if (activity_check) {
3021 if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay &&
3022 spa_get_hostid() == 0) {
3023 nvlist_free(label);
3024 fnvlist_add_uint64(spa->spa_load_info,
3025 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_NO_HOSTID);
3026 return (spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO));
3027 }
3028
3029 int error = spa_activity_check(spa, ub, spa->spa_config);
3030 if (error) {
3031 nvlist_free(label);
3032 return (error);
3033 }
3034
3035 fnvlist_add_uint64(spa->spa_load_info,
3036 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_INACTIVE);
3037 fnvlist_add_uint64(spa->spa_load_info,
3038 ZPOOL_CONFIG_MMP_TXG, ub->ub_txg);
3039 fnvlist_add_uint16(spa->spa_load_info,
3040 ZPOOL_CONFIG_MMP_SEQ,
3041 (MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0));
3042 }
3043
3044 /*
3045 * If the pool has an unsupported version we can't open it.
3046 */
3047 if (!SPA_VERSION_IS_SUPPORTED(ub->ub_version)) {
3048 nvlist_free(label);
3049 spa_load_failed(spa, "version %llu is not supported",
3050 (u_longlong_t)ub->ub_version);
3051 return (spa_vdev_err(rvd, VDEV_AUX_VERSION_NEWER, ENOTSUP));
3052 }
3053
3054 if (ub->ub_version >= SPA_VERSION_FEATURES) {
3055 nvlist_t *features;
3056
3057 /*
3058 * If we weren't able to find what's necessary for reading the
3059 * MOS in the label, return failure.
3060 */
3061 if (label == NULL) {
3062 spa_load_failed(spa, "label config unavailable");
3063 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3064 ENXIO));
3065 }
3066
3067 if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_FEATURES_FOR_READ,
3068 &features) != 0) {
3069 nvlist_free(label);
3070 spa_load_failed(spa, "invalid label: '%s' missing",
3071 ZPOOL_CONFIG_FEATURES_FOR_READ);
3072 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3073 ENXIO));
3074 }
3075
3076 /*
3077 * Update our in-core representation with the definitive values
3078 * from the label.
3079 */
3080 nvlist_free(spa->spa_label_features);
3081 VERIFY(nvlist_dup(features, &spa->spa_label_features, 0) == 0);
3082 }
3083
3084 nvlist_free(label);
3085
3086 /*
3087 * Look through entries in the label nvlist's features_for_read. If
3088 * there is a feature listed there which we don't understand then we
3089 * cannot open a pool.
3090 */
3091 if (ub->ub_version >= SPA_VERSION_FEATURES) {
3092 nvlist_t *unsup_feat;
3093
3094 VERIFY(nvlist_alloc(&unsup_feat, NV_UNIQUE_NAME, KM_SLEEP) ==
3095 0);
3096
3097 for (nvpair_t *nvp = nvlist_next_nvpair(spa->spa_label_features,
3098 NULL); nvp != NULL;
3099 nvp = nvlist_next_nvpair(spa->spa_label_features, nvp)) {
3100 if (!zfeature_is_supported(nvpair_name(nvp))) {
3101 VERIFY(nvlist_add_string(unsup_feat,
3102 nvpair_name(nvp), "") == 0);
3103 }
3104 }
3105
3106 if (!nvlist_empty(unsup_feat)) {
3107 VERIFY(nvlist_add_nvlist(spa->spa_load_info,
3108 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat) == 0);
3109 nvlist_free(unsup_feat);
3110 spa_load_failed(spa, "some features are unsupported");
3111 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
3112 ENOTSUP));
3113 }
3114
3115 nvlist_free(unsup_feat);
3116 }
3117
3118 if (type != SPA_IMPORT_ASSEMBLE && spa->spa_config_splitting) {
3119 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3120 spa_try_repair(spa, spa->spa_config);
3121 spa_config_exit(spa, SCL_ALL, FTAG);
3122 nvlist_free(spa->spa_config_splitting);
3123 spa->spa_config_splitting = NULL;
3124 }
3125
3126 /*
3127 * Initialize internal SPA structures.
3128 */
3129 spa_ld_select_uberblock_done(spa, ub);
3130
3131 return (0);
3132 }
3133
3134 static int
3135 spa_ld_open_rootbp(spa_t *spa)
3136 {
3137 int error = 0;
3138 vdev_t *rvd = spa->spa_root_vdev;
3139
3140 error = dsl_pool_init(spa, spa->spa_first_txg, &spa->spa_dsl_pool);
3141 if (error != 0) {
3142 spa_load_failed(spa, "unable to open rootbp in dsl_pool_init "
3143 "[error=%d]", error);
3144 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3145 }
3146 spa->spa_meta_objset = spa->spa_dsl_pool->dp_meta_objset;
3147
3148 return (0);
3149 }
3150
3151 static int
3152 spa_ld_trusted_config(spa_t *spa, spa_import_type_t type,
3153 boolean_t reloading)
3154 {
3155 vdev_t *mrvd, *rvd = spa->spa_root_vdev;
3156 nvlist_t *nv, *mos_config, *policy;
3157 int error = 0, copy_error;
3158 uint64_t healthy_tvds, healthy_tvds_mos;
3159 uint64_t mos_config_txg;
3160
3161 if (spa_dir_prop(spa, DMU_POOL_CONFIG, &spa->spa_config_object, B_TRUE)
3162 != 0)
3163 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3164
3165 /*
3166 * If we're assembling a pool from a split, the config provided is
3167 * already trusted so there is nothing to do.
3168 */
3169 if (type == SPA_IMPORT_ASSEMBLE)
3170 return (0);
3171
3172 healthy_tvds = spa_healthy_core_tvds(spa);
3173
3174 if (load_nvlist(spa, spa->spa_config_object, &mos_config)
3175 != 0) {
3176 spa_load_failed(spa, "unable to retrieve MOS config");
3177 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3178 }
3179
3180 /*
3181 * If we are doing an open, pool owner wasn't verified yet, thus do
3182 * the verification here.
3183 */
3184 if (spa->spa_load_state == SPA_LOAD_OPEN) {
3185 error = spa_verify_host(spa, mos_config);
3186 if (error != 0) {
3187 nvlist_free(mos_config);
3188 return (error);
3189 }
3190 }
3191
3192 nv = fnvlist_lookup_nvlist(mos_config, ZPOOL_CONFIG_VDEV_TREE);
3193
3194 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3195
3196 /*
3197 * Build a new vdev tree from the trusted config
3198 */
3199 VERIFY(spa_config_parse(spa, &mrvd, nv, NULL, 0, VDEV_ALLOC_LOAD) == 0);
3200
3201 /*
3202 * Vdev paths in the MOS may be obsolete. If the untrusted config was
3203 * obtained by scanning /dev/dsk, then it will have the right vdev
3204 * paths. We update the trusted MOS config with this information.
3205 * We first try to copy the paths with vdev_copy_path_strict, which
3206 * succeeds only when both configs have exactly the same vdev tree.
3207 * If that fails, we fall back to a more flexible method that has a
3208 * best effort policy.
3209 */
3210 copy_error = vdev_copy_path_strict(rvd, mrvd);
3211 if (copy_error != 0 || spa_load_print_vdev_tree) {
3212 spa_load_note(spa, "provided vdev tree:");
3213 vdev_dbgmsg_print_tree(rvd, 2);
3214 spa_load_note(spa, "MOS vdev tree:");
3215 vdev_dbgmsg_print_tree(mrvd, 2);
3216 }
3217 if (copy_error != 0) {
3218 spa_load_note(spa, "vdev_copy_path_strict failed, falling "
3219 "back to vdev_copy_path_relaxed");
3220 vdev_copy_path_relaxed(rvd, mrvd);
3221 }
3222
3223 vdev_close(rvd);
3224 vdev_free(rvd);
3225 spa->spa_root_vdev = mrvd;
3226 rvd = mrvd;
3227 spa_config_exit(spa, SCL_ALL, FTAG);
3228
3229 /*
3230 * We will use spa_config if we decide to reload the spa or if spa_load
3231 * fails and we rewind. We must thus regenerate the config using the
3232 * MOS information with the updated paths. ZPOOL_LOAD_POLICY is used to
3233 * pass settings on how to load the pool and is not stored in the MOS.
3234 * We copy it over to our new, trusted config.
3235 */
3236 mos_config_txg = fnvlist_lookup_uint64(mos_config,
3237 ZPOOL_CONFIG_POOL_TXG);
3238 nvlist_free(mos_config);
3239 mos_config = spa_config_generate(spa, NULL, mos_config_txg, B_FALSE);
3240 if (nvlist_lookup_nvlist(spa->spa_config, ZPOOL_LOAD_POLICY,
3241 &policy) == 0)
3242 fnvlist_add_nvlist(mos_config, ZPOOL_LOAD_POLICY, policy);
3243