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 if (err && err != ENOENT) {
489 nvlist_free(*nvp);
490 *nvp = NULL;
491 return (err);
492 }
493
494 return (0);
495 }
496
497 /*
498 * Validate the given pool properties nvlist and modify the list
499 * for the property values to be set.
500 */
501 static int
spa_prop_validate(spa_t * spa,nvlist_t * props)502 spa_prop_validate(spa_t *spa, nvlist_t *props)
503 {
504 nvpair_t *elem;
505 int error = 0, reset_bootfs = 0;
506 uint64_t objnum = 0;
507 boolean_t has_feature = B_FALSE;
508
509 elem = NULL;
510 while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
511 uint64_t intval;
512 char *strval, *slash, *check, *fname;
513 const char *propname = nvpair_name(elem);
514 zpool_prop_t prop = zpool_name_to_prop(propname);
515
516 switch (prop) {
517 case ZPOOL_PROP_INVAL:
518 if (!zpool_prop_feature(propname)) {
519 error = SET_ERROR(EINVAL);
520 break;
521 }
522
523 /*
524 * Sanitize the input.
525 */
526 if (nvpair_type(elem) != DATA_TYPE_UINT64) {
527 error = SET_ERROR(EINVAL);
528 break;
529 }
530
531 if (nvpair_value_uint64(elem, &intval) != 0) {
532 error = SET_ERROR(EINVAL);
533 break;
534 }
535
536 if (intval != 0) {
537 error = SET_ERROR(EINVAL);
538 break;
539 }
540
541 fname = strchr(propname, '@') + 1;
542 if (zfeature_lookup_name(fname, NULL) != 0) {
543 error = SET_ERROR(EINVAL);
544 break;
545 }
546
547 has_feature = B_TRUE;
548 break;
549
550 case ZPOOL_PROP_VERSION:
551 error = nvpair_value_uint64(elem, &intval);
552 if (!error &&
553 (intval < spa_version(spa) ||
554 intval > SPA_VERSION_BEFORE_FEATURES ||
555 has_feature))
556 error = SET_ERROR(EINVAL);
557 break;
558
559 case ZPOOL_PROP_DELEGATION:
560 case ZPOOL_PROP_AUTOREPLACE:
561 case ZPOOL_PROP_LISTSNAPS:
562 case ZPOOL_PROP_AUTOEXPAND:
563 case ZPOOL_PROP_AUTOTRIM:
564 error = nvpair_value_uint64(elem, &intval);
565 if (!error && intval > 1)
566 error = SET_ERROR(EINVAL);
567 break;
568
569 case ZPOOL_PROP_MULTIHOST:
570 error = nvpair_value_uint64(elem, &intval);
571 if (!error && intval > 1)
572 error = SET_ERROR(EINVAL);
573
574 if (!error && !spa_get_hostid())
575 error = SET_ERROR(ENOTSUP);
576
577 break;
578
579 case ZPOOL_PROP_BOOTFS:
580 /*
581 * If the pool version is less than SPA_VERSION_BOOTFS,
582 * or the pool is still being created (version == 0),
583 * the bootfs property cannot be set.
584 */
585 if (spa_version(spa) < SPA_VERSION_BOOTFS) {
586 error = SET_ERROR(ENOTSUP);
587 break;
588 }
589
590 /*
591 * Make sure the vdev config is bootable
592 */
593 if (!vdev_is_bootable(spa->spa_root_vdev)) {
594 error = SET_ERROR(ENOTSUP);
595 break;
596 }
597
598 reset_bootfs = 1;
599
600 error = nvpair_value_string(elem, &strval);
601
602 if (!error) {
603 objset_t *os;
604 uint64_t propval;
605
606 if (strval == NULL || strval[0] == '\0') {
607 objnum = zpool_prop_default_numeric(
608 ZPOOL_PROP_BOOTFS);
609 break;
610 }
611
612 error = dmu_objset_hold(strval, FTAG, &os);
613 if (error != 0)
614 break;
615
616 /*
617 * Must be ZPL, and its property settings
618 * must be supported.
619 */
620
621 if (dmu_objset_type(os) != DMU_OST_ZFS) {
622 error = SET_ERROR(ENOTSUP);
623 } else if ((error =
624 dsl_prop_get_int_ds(dmu_objset_ds(os),
625 zfs_prop_to_name(ZFS_PROP_COMPRESSION),
626 &propval)) == 0 &&
627 !BOOTFS_COMPRESS_VALID(propval)) {
628 error = SET_ERROR(ENOTSUP);
629 } else {
630 objnum = dmu_objset_id(os);
631 }
632 dmu_objset_rele(os, FTAG);
633 }
634 break;
635
636 case ZPOOL_PROP_FAILUREMODE:
637 error = nvpair_value_uint64(elem, &intval);
638 if (!error && (intval < ZIO_FAILURE_MODE_WAIT ||
639 intval > ZIO_FAILURE_MODE_PANIC))
640 error = SET_ERROR(EINVAL);
641
642 /*
643 * This is a special case which only occurs when
644 * the pool has completely failed. This allows
645 * the user to change the in-core failmode property
646 * without syncing it out to disk (I/Os might
647 * currently be blocked). We do this by returning
648 * EIO to the caller (spa_prop_set) to trick it
649 * into thinking we encountered a property validation
650 * error.
651 */
652 if (!error && spa_suspended(spa)) {
653 spa->spa_failmode = intval;
654 error = SET_ERROR(EIO);
655 }
656 break;
657
658 case ZPOOL_PROP_CACHEFILE:
659 if ((error = nvpair_value_string(elem, &strval)) != 0)
660 break;
661
662 if (strval[0] == '\0')
663 break;
664
665 if (strcmp(strval, "none") == 0)
666 break;
667
668 if (strval[0] != '/') {
669 error = SET_ERROR(EINVAL);
670 break;
671 }
672
673 slash = strrchr(strval, '/');
674 ASSERT(slash != NULL);
675
676 if (slash[1] == '\0' || strcmp(slash, "/.") == 0 ||
677 strcmp(slash, "/..") == 0)
678 error = SET_ERROR(EINVAL);
679 break;
680
681 case ZPOOL_PROP_COMMENT:
682 if ((error = nvpair_value_string(elem, &strval)) != 0)
683 break;
684 for (check = strval; *check != '\0'; check++) {
685 /*
686 * The kernel doesn't have an easy isprint()
687 * check. For this kernel check, we merely
688 * check ASCII apart from DEL. Fix this if
689 * there is an easy-to-use kernel isprint().
690 */
691 if (*check >= 0x7f) {
692 error = SET_ERROR(EINVAL);
693 break;
694 }
695 }
696 if (strlen(strval) > ZPROP_MAX_COMMENT)
697 error = E2BIG;
698 break;
699
700 case ZPOOL_PROP_DEDUPDITTO:
701 if (spa_version(spa) < SPA_VERSION_DEDUP)
702 error = SET_ERROR(ENOTSUP);
703 else
704 error = nvpair_value_uint64(elem, &intval);
705 if (error == 0 &&
706 intval != 0 && intval < ZIO_DEDUPDITTO_MIN)
707 error = SET_ERROR(EINVAL);
708 break;
709 }
710
711 if (error)
712 break;
713 }
714
715 if (!error && reset_bootfs) {
716 error = nvlist_remove(props,
717 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), DATA_TYPE_STRING);
718
719 if (!error) {
720 error = nvlist_add_uint64(props,
721 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), objnum);
722 }
723 }
724
725 return (error);
726 }
727
728 void
spa_configfile_set(spa_t * spa,nvlist_t * nvp,boolean_t need_sync)729 spa_configfile_set(spa_t *spa, nvlist_t *nvp, boolean_t need_sync)
730 {
731 char *cachefile;
732 spa_config_dirent_t *dp;
733
734 if (nvlist_lookup_string(nvp, zpool_prop_to_name(ZPOOL_PROP_CACHEFILE),
735 &cachefile) != 0)
736 return;
737
738 dp = kmem_alloc(sizeof (spa_config_dirent_t),
739 KM_SLEEP);
740
741 if (cachefile[0] == '\0')
742 dp->scd_path = spa_strdup(spa_config_path);
743 else if (strcmp(cachefile, "none") == 0)
744 dp->scd_path = NULL;
745 else
746 dp->scd_path = spa_strdup(cachefile);
747
748 list_insert_head(&spa->spa_config_list, dp);
749 if (need_sync)
750 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
751 }
752
753 int
spa_prop_set(spa_t * spa,nvlist_t * nvp)754 spa_prop_set(spa_t *spa, nvlist_t *nvp)
755 {
756 int error;
757 nvpair_t *elem = NULL;
758 boolean_t need_sync = B_FALSE;
759
760 if ((error = spa_prop_validate(spa, nvp)) != 0)
761 return (error);
762
763 while ((elem = nvlist_next_nvpair(nvp, elem)) != NULL) {
764 zpool_prop_t prop = zpool_name_to_prop(nvpair_name(elem));
765
766 if (prop == ZPOOL_PROP_CACHEFILE ||
767 prop == ZPOOL_PROP_ALTROOT ||
768 prop == ZPOOL_PROP_READONLY)
769 continue;
770
771 if (prop == ZPOOL_PROP_VERSION || prop == ZPOOL_PROP_INVAL) {
772 uint64_t ver;
773
774 if (prop == ZPOOL_PROP_VERSION) {
775 VERIFY(nvpair_value_uint64(elem, &ver) == 0);
776 } else {
777 ASSERT(zpool_prop_feature(nvpair_name(elem)));
778 ver = SPA_VERSION_FEATURES;
779 need_sync = B_TRUE;
780 }
781
782 /* Save time if the version is already set. */
783 if (ver == spa_version(spa))
784 continue;
785
786 /*
787 * In addition to the pool directory object, we might
788 * create the pool properties object, the features for
789 * read object, the features for write object, or the
790 * feature descriptions object.
791 */
792 error = dsl_sync_task(spa->spa_name, NULL,
793 spa_sync_version, &ver,
794 6, ZFS_SPACE_CHECK_RESERVED);
795 if (error)
796 return (error);
797 continue;
798 }
799
800 need_sync = B_TRUE;
801 break;
802 }
803
804 if (need_sync) {
805 return (dsl_sync_task(spa->spa_name, NULL, spa_sync_props,
806 nvp, 6, ZFS_SPACE_CHECK_RESERVED));
807 }
808
809 return (0);
810 }
811
812 /*
813 * If the bootfs property value is dsobj, clear it.
814 */
815 void
spa_prop_clear_bootfs(spa_t * spa,uint64_t dsobj,dmu_tx_t * tx)816 spa_prop_clear_bootfs(spa_t *spa, uint64_t dsobj, dmu_tx_t *tx)
817 {
818 if (spa->spa_bootfs == dsobj && spa->spa_pool_props_object != 0) {
819 VERIFY(zap_remove(spa->spa_meta_objset,
820 spa->spa_pool_props_object,
821 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), tx) == 0);
822 spa->spa_bootfs = 0;
823 }
824 }
825
826 /*ARGSUSED*/
827 static int
spa_change_guid_check(void * arg,dmu_tx_t * tx)828 spa_change_guid_check(void *arg, dmu_tx_t *tx)
829 {
830 uint64_t *newguid = arg;
831 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
832 vdev_t *rvd = spa->spa_root_vdev;
833 uint64_t vdev_state;
834
835 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
836 int error = (spa_has_checkpoint(spa)) ?
837 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
838 return (SET_ERROR(error));
839 }
840
841 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
842 vdev_state = rvd->vdev_state;
843 spa_config_exit(spa, SCL_STATE, FTAG);
844
845 if (vdev_state != VDEV_STATE_HEALTHY)
846 return (SET_ERROR(ENXIO));
847
848 ASSERT3U(spa_guid(spa), !=, *newguid);
849
850 return (0);
851 }
852
853 static void
spa_change_guid_sync(void * arg,dmu_tx_t * tx)854 spa_change_guid_sync(void *arg, dmu_tx_t *tx)
855 {
856 uint64_t *newguid = arg;
857 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
858 uint64_t oldguid;
859 vdev_t *rvd = spa->spa_root_vdev;
860
861 oldguid = spa_guid(spa);
862
863 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
864 rvd->vdev_guid = *newguid;
865 rvd->vdev_guid_sum += (*newguid - oldguid);
866 vdev_config_dirty(rvd);
867 spa_config_exit(spa, SCL_STATE, FTAG);
868
869 spa_history_log_internal(spa, "guid change", tx, "old=%llu new=%llu",
870 oldguid, *newguid);
871 }
872
873 /*
874 * Change the GUID for the pool. This is done so that we can later
875 * re-import a pool built from a clone of our own vdevs. We will modify
876 * the root vdev's guid, our own pool guid, and then mark all of our
877 * vdevs dirty. Note that we must make sure that all our vdevs are
878 * online when we do this, or else any vdevs that weren't present
879 * would be orphaned from our pool. We are also going to issue a
880 * sysevent to update any watchers.
881 */
882 int
spa_change_guid(spa_t * spa)883 spa_change_guid(spa_t *spa)
884 {
885 int error;
886 uint64_t guid;
887
888 mutex_enter(&spa->spa_vdev_top_lock);
889 mutex_enter(&spa_namespace_lock);
890 guid = spa_generate_guid(NULL);
891
892 error = dsl_sync_task(spa->spa_name, spa_change_guid_check,
893 spa_change_guid_sync, &guid, 5, ZFS_SPACE_CHECK_RESERVED);
894
895 if (error == 0) {
896 spa_write_cachefile(spa, B_FALSE, B_TRUE);
897 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_REGUID);
898 }
899
900 mutex_exit(&spa_namespace_lock);
901 mutex_exit(&spa->spa_vdev_top_lock);
902
903 return (error);
904 }
905
906 /*
907 * ==========================================================================
908 * SPA state manipulation (open/create/destroy/import/export)
909 * ==========================================================================
910 */
911
912 static int
spa_error_entry_compare(const void * a,const void * b)913 spa_error_entry_compare(const void *a, const void *b)
914 {
915 const spa_error_entry_t *sa = (const spa_error_entry_t *)a;
916 const spa_error_entry_t *sb = (const spa_error_entry_t *)b;
917 int ret;
918
919 ret = memcmp(&sa->se_bookmark, &sb->se_bookmark,
920 sizeof (zbookmark_phys_t));
921
922 return (TREE_ISIGN(ret));
923 }
924
925 /*
926 * Utility function which retrieves copies of the current logs and
927 * re-initializes them in the process.
928 */
929 void
spa_get_errlists(spa_t * spa,avl_tree_t * last,avl_tree_t * scrub)930 spa_get_errlists(spa_t *spa, avl_tree_t *last, avl_tree_t *scrub)
931 {
932 ASSERT(MUTEX_HELD(&spa->spa_errlist_lock));
933
934 bcopy(&spa->spa_errlist_last, last, sizeof (avl_tree_t));
935 bcopy(&spa->spa_errlist_scrub, scrub, sizeof (avl_tree_t));
936
937 avl_create(&spa->spa_errlist_scrub,
938 spa_error_entry_compare, sizeof (spa_error_entry_t),
939 offsetof(spa_error_entry_t, se_avl));
940 avl_create(&spa->spa_errlist_last,
941 spa_error_entry_compare, sizeof (spa_error_entry_t),
942 offsetof(spa_error_entry_t, se_avl));
943 }
944
945 static void
spa_taskqs_init(spa_t * spa,zio_type_t t,zio_taskq_type_t q)946 spa_taskqs_init(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
947 {
948 const zio_taskq_info_t *ztip = &zio_taskqs[t][q];
949 enum zti_modes mode = ztip->zti_mode;
950 uint_t value = ztip->zti_value;
951 uint_t count = ztip->zti_count;
952 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
953 char name[32];
954 uint_t flags = 0;
955 boolean_t batch = B_FALSE;
956
957 if (mode == ZTI_MODE_NULL) {
958 tqs->stqs_count = 0;
959 tqs->stqs_taskq = NULL;
960 return;
961 }
962
963 ASSERT3U(count, >, 0);
964
965 tqs->stqs_count = count;
966 tqs->stqs_taskq = kmem_alloc(count * sizeof (taskq_t *), KM_SLEEP);
967
968 switch (mode) {
969 case ZTI_MODE_FIXED:
970 ASSERT3U(value, >=, 1);
971 value = MAX(value, 1);
972 break;
973
974 case ZTI_MODE_BATCH:
975 batch = B_TRUE;
976 flags |= TASKQ_THREADS_CPU_PCT;
977 value = zio_taskq_batch_pct;
978 break;
979
980 default:
981 panic("unrecognized mode for %s_%s taskq (%u:%u) in "
982 "spa_activate()",
983 zio_type_name[t], zio_taskq_types[q], mode, value);
984 break;
985 }
986
987 for (uint_t i = 0; i < count; i++) {
988 taskq_t *tq;
989
990 if (count > 1) {
991 (void) snprintf(name, sizeof (name), "%s_%s_%u",
992 zio_type_name[t], zio_taskq_types[q], i);
993 } else {
994 (void) snprintf(name, sizeof (name), "%s_%s",
995 zio_type_name[t], zio_taskq_types[q]);
996 }
997
998 if (zio_taskq_sysdc && spa->spa_proc != &p0) {
999 if (batch)
1000 flags |= TASKQ_DC_BATCH;
1001
1002 tq = taskq_create_sysdc(name, value, 50, INT_MAX,
1003 spa->spa_proc, zio_taskq_basedc, flags);
1004 } else {
1005 pri_t pri = maxclsyspri;
1006 /*
1007 * The write issue taskq can be extremely CPU
1008 * intensive. Run it at slightly lower priority
1009 * than the other taskqs.
1010 */
1011 if (t == ZIO_TYPE_WRITE && q == ZIO_TASKQ_ISSUE)
1012 pri--;
1013
1014 tq = taskq_create_proc(name, value, pri, 50,
1015 INT_MAX, spa->spa_proc, flags);
1016 }
1017
1018 tqs->stqs_taskq[i] = tq;
1019 }
1020 }
1021
1022 static void
spa_taskqs_fini(spa_t * spa,zio_type_t t,zio_taskq_type_t q)1023 spa_taskqs_fini(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
1024 {
1025 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1026
1027 if (tqs->stqs_taskq == NULL) {
1028 ASSERT0(tqs->stqs_count);
1029 return;
1030 }
1031
1032 for (uint_t i = 0; i < tqs->stqs_count; i++) {
1033 ASSERT3P(tqs->stqs_taskq[i], !=, NULL);
1034 taskq_destroy(tqs->stqs_taskq[i]);
1035 }
1036
1037 kmem_free(tqs->stqs_taskq, tqs->stqs_count * sizeof (taskq_t *));
1038 tqs->stqs_taskq = NULL;
1039 }
1040
1041 /*
1042 * Dispatch a task to the appropriate taskq for the ZFS I/O type and priority.
1043 * Note that a type may have multiple discrete taskqs to avoid lock contention
1044 * on the taskq itself. In that case we choose which taskq at random by using
1045 * the low bits of gethrtime().
1046 */
1047 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)1048 spa_taskq_dispatch_ent(spa_t *spa, zio_type_t t, zio_taskq_type_t q,
1049 task_func_t *func, void *arg, uint_t flags, taskq_ent_t *ent)
1050 {
1051 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1052 taskq_t *tq;
1053
1054 ASSERT3P(tqs->stqs_taskq, !=, NULL);
1055 ASSERT3U(tqs->stqs_count, !=, 0);
1056
1057 if (tqs->stqs_count == 1) {
1058 tq = tqs->stqs_taskq[0];
1059 } else {
1060 tq = tqs->stqs_taskq[gethrtime() % tqs->stqs_count];
1061 }
1062
1063 taskq_dispatch_ent(tq, func, arg, flags, ent);
1064 }
1065
1066 static void
spa_create_zio_taskqs(spa_t * spa)1067 spa_create_zio_taskqs(spa_t *spa)
1068 {
1069 for (int t = 0; t < ZIO_TYPES; t++) {
1070 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1071 spa_taskqs_init(spa, t, q);
1072 }
1073 }
1074 }
1075
1076 #ifdef _KERNEL
1077 static void
spa_thread(void * arg)1078 spa_thread(void *arg)
1079 {
1080 callb_cpr_t cprinfo;
1081 spa_t *spa = arg;
1082 char spa_id_readable[CB_MAXNAME + 1];
1083 user_t *pu = PTOU(curproc);
1084
1085 (void) snprintf(spa_id_readable, sizeof (spa_id_readable), "SPA:0x%p",
1086 spa);
1087
1088 CALLB_CPR_INIT(&cprinfo, &spa->spa_proc_lock, callb_generic_cpr,
1089 spa_id_readable);
1090
1091 ASSERT(curproc != &p0);
1092 (void) snprintf(pu->u_psargs, sizeof (pu->u_psargs),
1093 "zpool-%s", spa->spa_name);
1094 (void) strlcpy(pu->u_comm, pu->u_psargs, sizeof (pu->u_comm));
1095
1096 /* bind this thread to the requested psrset */
1097 if (zio_taskq_psrset_bind != PS_NONE) {
1098 pool_lock();
1099 mutex_enter(&cpu_lock);
1100 mutex_enter(&pidlock);
1101 mutex_enter(&curproc->p_lock);
1102
1103 if (cpupart_bind_thread(curthread, zio_taskq_psrset_bind,
1104 0, NULL, NULL) == 0) {
1105 curthread->t_bind_pset = zio_taskq_psrset_bind;
1106 } else {
1107 cmn_err(CE_WARN,
1108 "Couldn't bind process for zfs pool \"%s\" to "
1109 "pset %d\n", spa->spa_name, zio_taskq_psrset_bind);
1110 }
1111
1112 mutex_exit(&curproc->p_lock);
1113 mutex_exit(&pidlock);
1114 mutex_exit(&cpu_lock);
1115 pool_unlock();
1116 }
1117
1118 if (zio_taskq_sysdc) {
1119 sysdc_thread_enter(curthread, 100, 0);
1120 }
1121
1122 spa->spa_proc = curproc;
1123 spa->spa_did = curthread->t_did;
1124
1125 spa_create_zio_taskqs(spa);
1126
1127 mutex_enter(&spa->spa_proc_lock);
1128 ASSERT(spa->spa_proc_state == SPA_PROC_CREATED);
1129
1130 spa->spa_proc_state = SPA_PROC_ACTIVE;
1131 cv_broadcast(&spa->spa_proc_cv);
1132
1133 CALLB_CPR_SAFE_BEGIN(&cprinfo);
1134 while (spa->spa_proc_state == SPA_PROC_ACTIVE)
1135 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1136 CALLB_CPR_SAFE_END(&cprinfo, &spa->spa_proc_lock);
1137
1138 ASSERT(spa->spa_proc_state == SPA_PROC_DEACTIVATE);
1139 spa->spa_proc_state = SPA_PROC_GONE;
1140 spa->spa_proc = &p0;
1141 cv_broadcast(&spa->spa_proc_cv);
1142 CALLB_CPR_EXIT(&cprinfo); /* drops spa_proc_lock */
1143
1144 mutex_enter(&curproc->p_lock);
1145 lwp_exit();
1146 }
1147 #endif
1148
1149 /*
1150 * Activate an uninitialized pool.
1151 */
1152 static void
spa_activate(spa_t * spa,int mode)1153 spa_activate(spa_t *spa, int mode)
1154 {
1155 ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
1156
1157 spa->spa_state = POOL_STATE_ACTIVE;
1158 spa->spa_mode = mode;
1159
1160 spa->spa_normal_class = metaslab_class_create(spa, zfs_metaslab_ops);
1161 spa->spa_log_class = metaslab_class_create(spa, zfs_metaslab_ops);
1162 spa->spa_special_class = metaslab_class_create(spa, zfs_metaslab_ops);
1163 spa->spa_dedup_class = metaslab_class_create(spa, zfs_metaslab_ops);
1164
1165 /* Try to create a covering process */
1166 mutex_enter(&spa->spa_proc_lock);
1167 ASSERT(spa->spa_proc_state == SPA_PROC_NONE);
1168 ASSERT(spa->spa_proc == &p0);
1169 spa->spa_did = 0;
1170
1171 /* Only create a process if we're going to be around a while. */
1172 if (spa_create_process && strcmp(spa->spa_name, TRYIMPORT_NAME) != 0) {
1173 if (newproc(spa_thread, (caddr_t)spa, syscid, maxclsyspri,
1174 NULL, 0) == 0) {
1175 spa->spa_proc_state = SPA_PROC_CREATED;
1176 while (spa->spa_proc_state == SPA_PROC_CREATED) {
1177 cv_wait(&spa->spa_proc_cv,
1178 &spa->spa_proc_lock);
1179 }
1180 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1181 ASSERT(spa->spa_proc != &p0);
1182 ASSERT(spa->spa_did != 0);
1183 } else {
1184 #ifdef _KERNEL
1185 cmn_err(CE_WARN,
1186 "Couldn't create process for zfs pool \"%s\"\n",
1187 spa->spa_name);
1188 #endif
1189 }
1190 }
1191 mutex_exit(&spa->spa_proc_lock);
1192
1193 /* If we didn't create a process, we need to create our taskqs. */
1194 if (spa->spa_proc == &p0) {
1195 spa_create_zio_taskqs(spa);
1196 }
1197
1198 for (size_t i = 0; i < TXG_SIZE; i++) {
1199 spa->spa_txg_zio[i] = zio_root(spa, NULL, NULL,
1200 ZIO_FLAG_CANFAIL);
1201 }
1202
1203 list_create(&spa->spa_config_dirty_list, sizeof (vdev_t),
1204 offsetof(vdev_t, vdev_config_dirty_node));
1205 list_create(&spa->spa_evicting_os_list, sizeof (objset_t),
1206 offsetof(objset_t, os_evicting_node));
1207 list_create(&spa->spa_state_dirty_list, sizeof (vdev_t),
1208 offsetof(vdev_t, vdev_state_dirty_node));
1209
1210 txg_list_create(&spa->spa_vdev_txg_list, spa,
1211 offsetof(struct vdev, vdev_txg_node));
1212
1213 avl_create(&spa->spa_errlist_scrub,
1214 spa_error_entry_compare, sizeof (spa_error_entry_t),
1215 offsetof(spa_error_entry_t, se_avl));
1216 avl_create(&spa->spa_errlist_last,
1217 spa_error_entry_compare, sizeof (spa_error_entry_t),
1218 offsetof(spa_error_entry_t, se_avl));
1219
1220 spa_keystore_init(&spa->spa_keystore);
1221
1222 /*
1223 * The taskq to upgrade datasets in this pool. Currently used by
1224 * feature SPA_FEATURE_USEROBJ_ACCOUNTING/SPA_FEATURE_PROJECT_QUOTA.
1225 */
1226 spa->spa_upgrade_taskq = taskq_create("z_upgrade", boot_ncpus,
1227 minclsyspri, 1, INT_MAX, TASKQ_DYNAMIC);
1228 }
1229
1230 /*
1231 * Opposite of spa_activate().
1232 */
1233 static void
spa_deactivate(spa_t * spa)1234 spa_deactivate(spa_t *spa)
1235 {
1236 ASSERT(spa->spa_sync_on == B_FALSE);
1237 ASSERT(spa->spa_dsl_pool == NULL);
1238 ASSERT(spa->spa_root_vdev == NULL);
1239 ASSERT(spa->spa_async_zio_root == NULL);
1240 ASSERT(spa->spa_state != POOL_STATE_UNINITIALIZED);
1241
1242 spa_evicting_os_wait(spa);
1243
1244 if (spa->spa_upgrade_taskq) {
1245 taskq_destroy(spa->spa_upgrade_taskq);
1246 spa->spa_upgrade_taskq = NULL;
1247 }
1248
1249 txg_list_destroy(&spa->spa_vdev_txg_list);
1250
1251 list_destroy(&spa->spa_config_dirty_list);
1252 list_destroy(&spa->spa_evicting_os_list);
1253 list_destroy(&spa->spa_state_dirty_list);
1254
1255 for (int t = 0; t < ZIO_TYPES; t++) {
1256 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1257 spa_taskqs_fini(spa, t, q);
1258 }
1259 }
1260
1261 for (size_t i = 0; i < TXG_SIZE; i++) {
1262 ASSERT3P(spa->spa_txg_zio[i], !=, NULL);
1263 VERIFY0(zio_wait(spa->spa_txg_zio[i]));
1264 spa->spa_txg_zio[i] = NULL;
1265 }
1266
1267 metaslab_class_destroy(spa->spa_normal_class);
1268 spa->spa_normal_class = NULL;
1269
1270 metaslab_class_destroy(spa->spa_log_class);
1271 spa->spa_log_class = NULL;
1272
1273 metaslab_class_destroy(spa->spa_special_class);
1274 spa->spa_special_class = NULL;
1275
1276 metaslab_class_destroy(spa->spa_dedup_class);
1277 spa->spa_dedup_class = NULL;
1278
1279 /*
1280 * If this was part of an import or the open otherwise failed, we may
1281 * still have errors left in the queues. Empty them just in case.
1282 */
1283 spa_errlog_drain(spa);
1284 avl_destroy(&spa->spa_errlist_scrub);
1285 avl_destroy(&spa->spa_errlist_last);
1286
1287 spa_keystore_fini(&spa->spa_keystore);
1288
1289 spa->spa_state = POOL_STATE_UNINITIALIZED;
1290
1291 mutex_enter(&spa->spa_proc_lock);
1292 if (spa->spa_proc_state != SPA_PROC_NONE) {
1293 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1294 spa->spa_proc_state = SPA_PROC_DEACTIVATE;
1295 cv_broadcast(&spa->spa_proc_cv);
1296 while (spa->spa_proc_state == SPA_PROC_DEACTIVATE) {
1297 ASSERT(spa->spa_proc != &p0);
1298 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1299 }
1300 ASSERT(spa->spa_proc_state == SPA_PROC_GONE);
1301 spa->spa_proc_state = SPA_PROC_NONE;
1302 }
1303 ASSERT(spa->spa_proc == &p0);
1304 mutex_exit(&spa->spa_proc_lock);
1305
1306 /*
1307 * We want to make sure spa_thread() has actually exited the ZFS
1308 * module, so that the module can't be unloaded out from underneath
1309 * it.
1310 */
1311 if (spa->spa_did != 0) {
1312 thread_join(spa->spa_did);
1313 spa->spa_did = 0;
1314 }
1315 }
1316
1317 /*
1318 * Verify a pool configuration, and construct the vdev tree appropriately. This
1319 * will create all the necessary vdevs in the appropriate layout, with each vdev
1320 * in the CLOSED state. This will prep the pool before open/creation/import.
1321 * All vdev validation is done by the vdev_alloc() routine.
1322 */
1323 static int
spa_config_parse(spa_t * spa,vdev_t ** vdp,nvlist_t * nv,vdev_t * parent,uint_t id,int atype)1324 spa_config_parse(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent,
1325 uint_t id, int atype)
1326 {
1327 nvlist_t **child;
1328 uint_t children;
1329 int error;
1330
1331 if ((error = vdev_alloc(spa, vdp, nv, parent, id, atype)) != 0)
1332 return (error);
1333
1334 if ((*vdp)->vdev_ops->vdev_op_leaf)
1335 return (0);
1336
1337 error = nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1338 &child, &children);
1339
1340 if (error == ENOENT)
1341 return (0);
1342
1343 if (error) {
1344 vdev_free(*vdp);
1345 *vdp = NULL;
1346 return (SET_ERROR(EINVAL));
1347 }
1348
1349 for (int c = 0; c < children; c++) {
1350 vdev_t *vd;
1351 if ((error = spa_config_parse(spa, &vd, child[c], *vdp, c,
1352 atype)) != 0) {
1353 vdev_free(*vdp);
1354 *vdp = NULL;
1355 return (error);
1356 }
1357 }
1358
1359 ASSERT(*vdp != NULL);
1360
1361 return (0);
1362 }
1363
1364 static boolean_t
spa_should_flush_logs_on_unload(spa_t * spa)1365 spa_should_flush_logs_on_unload(spa_t *spa)
1366 {
1367 if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
1368 return (B_FALSE);
1369
1370 if (!spa_writeable(spa))
1371 return (B_FALSE);
1372
1373 if (!spa->spa_sync_on)
1374 return (B_FALSE);
1375
1376 if (spa_state(spa) != POOL_STATE_EXPORTED)
1377 return (B_FALSE);
1378
1379 if (zfs_keep_log_spacemaps_at_export)
1380 return (B_FALSE);
1381
1382 return (B_TRUE);
1383 }
1384
1385 /*
1386 * Opens a transaction that will set the flag that will instruct
1387 * spa_sync to attempt to flush all the metaslabs for that txg.
1388 */
1389 static void
spa_unload_log_sm_flush_all(spa_t * spa)1390 spa_unload_log_sm_flush_all(spa_t *spa)
1391 {
1392 dmu_tx_t *tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
1393
1394 VERIFY0(dmu_tx_assign(tx, TXG_WAIT));
1395
1396 ASSERT3U(spa->spa_log_flushall_txg, ==, 0);
1397 spa->spa_log_flushall_txg = dmu_tx_get_txg(tx);
1398
1399 dmu_tx_commit(tx);
1400 txg_wait_synced(spa_get_dsl(spa), spa->spa_log_flushall_txg);
1401 }
1402
1403 static void
spa_unload_log_sm_metadata(spa_t * spa)1404 spa_unload_log_sm_metadata(spa_t *spa)
1405 {
1406 void *cookie = NULL;
1407 spa_log_sm_t *sls;
1408
1409 while ((sls = avl_destroy_nodes(&spa->spa_sm_logs_by_txg,
1410 &cookie)) != NULL) {
1411 VERIFY0(sls->sls_mscount);
1412 kmem_free(sls, sizeof (spa_log_sm_t));
1413 }
1414
1415 for (log_summary_entry_t *e = list_head(&spa->spa_log_summary);
1416 e != NULL; e = list_head(&spa->spa_log_summary)) {
1417 VERIFY0(e->lse_mscount);
1418 list_remove(&spa->spa_log_summary, e);
1419 kmem_free(e, sizeof (log_summary_entry_t));
1420 }
1421
1422 spa->spa_unflushed_stats.sus_nblocks = 0;
1423 spa->spa_unflushed_stats.sus_memused = 0;
1424 spa->spa_unflushed_stats.sus_blocklimit = 0;
1425 }
1426
1427 /*
1428 * Opposite of spa_load().
1429 */
1430 static void
spa_unload(spa_t * spa)1431 spa_unload(spa_t *spa)
1432 {
1433 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1434 ASSERT(spa_state(spa) != POOL_STATE_UNINITIALIZED);
1435
1436 spa_import_progress_remove(spa);
1437 spa_load_note(spa, "UNLOADING");
1438
1439 spa_wake_waiters(spa);
1440
1441 /*
1442 * If the log space map feature is enabled and the pool is getting
1443 * exported (but not destroyed), we want to spend some time flushing
1444 * as many metaslabs as we can in an attempt to destroy log space
1445 * maps and save import time.
1446 */
1447 if (spa_should_flush_logs_on_unload(spa))
1448 spa_unload_log_sm_flush_all(spa);
1449
1450 /*
1451 * Stop async tasks.
1452 */
1453 spa_async_suspend(spa);
1454
1455 if (spa->spa_root_vdev) {
1456 vdev_t *root_vdev = spa->spa_root_vdev;
1457 vdev_initialize_stop_all(root_vdev, VDEV_INITIALIZE_ACTIVE);
1458 vdev_trim_stop_all(root_vdev, VDEV_TRIM_ACTIVE);
1459 vdev_autotrim_stop_all(spa);
1460 }
1461
1462 /*
1463 * Stop syncing.
1464 */
1465 if (spa->spa_sync_on) {
1466 txg_sync_stop(spa->spa_dsl_pool);
1467 spa->spa_sync_on = B_FALSE;
1468 }
1469
1470 /*
1471 * This ensures that there is no async metaslab prefetching
1472 * while we attempt to unload the spa.
1473 */
1474 if (spa->spa_root_vdev != NULL) {
1475 for (int c = 0; c < spa->spa_root_vdev->vdev_children; c++) {
1476 vdev_t *vc = spa->spa_root_vdev->vdev_child[c];
1477 if (vc->vdev_mg != NULL)
1478 taskq_wait(vc->vdev_mg->mg_taskq);
1479 }
1480 }
1481
1482 if (spa->spa_mmp.mmp_thread)
1483 mmp_thread_stop(spa);
1484
1485 /*
1486 * Wait for any outstanding async I/O to complete.
1487 */
1488 if (spa->spa_async_zio_root != NULL) {
1489 for (int i = 0; i < max_ncpus; i++)
1490 (void) zio_wait(spa->spa_async_zio_root[i]);
1491 kmem_free(spa->spa_async_zio_root, max_ncpus * sizeof (void *));
1492 spa->spa_async_zio_root = NULL;
1493 }
1494
1495 if (spa->spa_vdev_removal != NULL) {
1496 spa_vdev_removal_destroy(spa->spa_vdev_removal);
1497 spa->spa_vdev_removal = NULL;
1498 }
1499
1500 if (spa->spa_condense_zthr != NULL) {
1501 zthr_destroy(spa->spa_condense_zthr);
1502 spa->spa_condense_zthr = NULL;
1503 }
1504
1505 if (spa->spa_checkpoint_discard_zthr != NULL) {
1506 zthr_destroy(spa->spa_checkpoint_discard_zthr);
1507 spa->spa_checkpoint_discard_zthr = NULL;
1508 }
1509
1510 spa_condense_fini(spa);
1511
1512 bpobj_close(&spa->spa_deferred_bpobj);
1513
1514 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1515
1516 /*
1517 * Close all vdevs.
1518 */
1519 if (spa->spa_root_vdev)
1520 vdev_free(spa->spa_root_vdev);
1521 ASSERT(spa->spa_root_vdev == NULL);
1522
1523 /*
1524 * Close the dsl pool.
1525 */
1526 if (spa->spa_dsl_pool) {
1527 dsl_pool_close(spa->spa_dsl_pool);
1528 spa->spa_dsl_pool = NULL;
1529 spa->spa_meta_objset = NULL;
1530 }
1531
1532 ddt_unload(spa);
1533 spa_unload_log_sm_metadata(spa);
1534
1535 /*
1536 * Drop and purge level 2 cache
1537 */
1538 spa_l2cache_drop(spa);
1539
1540 for (int i = 0; i < spa->spa_spares.sav_count; i++)
1541 vdev_free(spa->spa_spares.sav_vdevs[i]);
1542 if (spa->spa_spares.sav_vdevs) {
1543 kmem_free(spa->spa_spares.sav_vdevs,
1544 spa->spa_spares.sav_count * sizeof (void *));
1545 spa->spa_spares.sav_vdevs = NULL;
1546 }
1547 if (spa->spa_spares.sav_config) {
1548 nvlist_free(spa->spa_spares.sav_config);
1549 spa->spa_spares.sav_config = NULL;
1550 }
1551 spa->spa_spares.sav_count = 0;
1552
1553 for (int i = 0; i < spa->spa_l2cache.sav_count; i++) {
1554 vdev_clear_stats(spa->spa_l2cache.sav_vdevs[i]);
1555 vdev_free(spa->spa_l2cache.sav_vdevs[i]);
1556 }
1557 if (spa->spa_l2cache.sav_vdevs) {
1558 kmem_free(spa->spa_l2cache.sav_vdevs,
1559 spa->spa_l2cache.sav_count * sizeof (void *));
1560 spa->spa_l2cache.sav_vdevs = NULL;
1561 }
1562 if (spa->spa_l2cache.sav_config) {
1563 nvlist_free(spa->spa_l2cache.sav_config);
1564 spa->spa_l2cache.sav_config = NULL;
1565 }
1566 spa->spa_l2cache.sav_count = 0;
1567
1568 spa->spa_async_suspended = 0;
1569
1570 spa->spa_indirect_vdevs_loaded = B_FALSE;
1571
1572 if (spa->spa_comment != NULL) {
1573 spa_strfree(spa->spa_comment);
1574 spa->spa_comment = NULL;
1575 }
1576
1577 spa_config_exit(spa, SCL_ALL, spa);
1578 }
1579
1580 /*
1581 * Load (or re-load) the current list of vdevs describing the active spares for
1582 * this pool. When this is called, we have some form of basic information in
1583 * 'spa_spares.sav_config'. We parse this into vdevs, try to open them, and
1584 * then re-generate a more complete list including status information.
1585 */
1586 void
spa_load_spares(spa_t * spa)1587 spa_load_spares(spa_t *spa)
1588 {
1589 nvlist_t **spares;
1590 uint_t nspares;
1591 int i;
1592 vdev_t *vd, *tvd;
1593
1594 #ifndef _KERNEL
1595 /*
1596 * zdb opens both the current state of the pool and the
1597 * checkpointed state (if present), with a different spa_t.
1598 *
1599 * As spare vdevs are shared among open pools, we skip loading
1600 * them when we load the checkpointed state of the pool.
1601 */
1602 if (!spa_writeable(spa))
1603 return;
1604 #endif
1605
1606 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1607
1608 /*
1609 * First, close and free any existing spare vdevs.
1610 */
1611 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1612 vd = spa->spa_spares.sav_vdevs[i];
1613
1614 /* Undo the call to spa_activate() below */
1615 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1616 B_FALSE)) != NULL && tvd->vdev_isspare)
1617 spa_spare_remove(tvd);
1618 vdev_close(vd);
1619 vdev_free(vd);
1620 }
1621
1622 if (spa->spa_spares.sav_vdevs)
1623 kmem_free(spa->spa_spares.sav_vdevs,
1624 spa->spa_spares.sav_count * sizeof (void *));
1625
1626 if (spa->spa_spares.sav_config == NULL)
1627 nspares = 0;
1628 else
1629 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
1630 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
1631
1632 spa->spa_spares.sav_count = (int)nspares;
1633 spa->spa_spares.sav_vdevs = NULL;
1634
1635 if (nspares == 0)
1636 return;
1637
1638 /*
1639 * Construct the array of vdevs, opening them to get status in the
1640 * process. For each spare, there is potentially two different vdev_t
1641 * structures associated with it: one in the list of spares (used only
1642 * for basic validation purposes) and one in the active vdev
1643 * configuration (if it's spared in). During this phase we open and
1644 * validate each vdev on the spare list. If the vdev also exists in the
1645 * active configuration, then we also mark this vdev as an active spare.
1646 */
1647 spa->spa_spares.sav_vdevs = kmem_alloc(nspares * sizeof (void *),
1648 KM_SLEEP);
1649 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1650 VERIFY(spa_config_parse(spa, &vd, spares[i], NULL, 0,
1651 VDEV_ALLOC_SPARE) == 0);
1652 ASSERT(vd != NULL);
1653
1654 spa->spa_spares.sav_vdevs[i] = vd;
1655
1656 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1657 B_FALSE)) != NULL) {
1658 if (!tvd->vdev_isspare)
1659 spa_spare_add(tvd);
1660
1661 /*
1662 * We only mark the spare active if we were successfully
1663 * able to load the vdev. Otherwise, importing a pool
1664 * with a bad active spare would result in strange
1665 * behavior, because multiple pool would think the spare
1666 * is actively in use.
1667 *
1668 * There is a vulnerability here to an equally bizarre
1669 * circumstance, where a dead active spare is later
1670 * brought back to life (onlined or otherwise). Given
1671 * the rarity of this scenario, and the extra complexity
1672 * it adds, we ignore the possibility.
1673 */
1674 if (!vdev_is_dead(tvd))
1675 spa_spare_activate(tvd);
1676 }
1677
1678 vd->vdev_top = vd;
1679 vd->vdev_aux = &spa->spa_spares;
1680
1681 if (vdev_open(vd) != 0)
1682 continue;
1683
1684 if (vdev_validate_aux(vd) == 0)
1685 spa_spare_add(vd);
1686 }
1687
1688 /*
1689 * Recompute the stashed list of spares, with status information
1690 * this time.
1691 */
1692 VERIFY(nvlist_remove(spa->spa_spares.sav_config, ZPOOL_CONFIG_SPARES,
1693 DATA_TYPE_NVLIST_ARRAY) == 0);
1694
1695 spares = kmem_alloc(spa->spa_spares.sav_count * sizeof (void *),
1696 KM_SLEEP);
1697 for (i = 0; i < spa->spa_spares.sav_count; i++)
1698 spares[i] = vdev_config_generate(spa,
1699 spa->spa_spares.sav_vdevs[i], B_TRUE, VDEV_CONFIG_SPARE);
1700 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
1701 ZPOOL_CONFIG_SPARES, spares, spa->spa_spares.sav_count) == 0);
1702 for (i = 0; i < spa->spa_spares.sav_count; i++)
1703 nvlist_free(spares[i]);
1704 kmem_free(spares, spa->spa_spares.sav_count * sizeof (void *));
1705 }
1706
1707 /*
1708 * Load (or re-load) the current list of vdevs describing the active l2cache for
1709 * this pool. When this is called, we have some form of basic information in
1710 * 'spa_l2cache.sav_config'. We parse this into vdevs, try to open them, and
1711 * then re-generate a more complete list including status information.
1712 * Devices which are already active have their details maintained, and are
1713 * not re-opened.
1714 */
1715 void
spa_load_l2cache(spa_t * spa)1716 spa_load_l2cache(spa_t *spa)
1717 {
1718 nvlist_t **l2cache;
1719 uint_t nl2cache;
1720 int i, j, oldnvdevs;
1721 uint64_t guid;
1722 vdev_t *vd, **oldvdevs, **newvdevs;
1723 spa_aux_vdev_t *sav = &spa->spa_l2cache;
1724
1725 #ifndef _KERNEL
1726 /*
1727 * zdb opens both the current state of the pool and the
1728 * checkpointed state (if present), with a different spa_t.
1729 *
1730 * As L2 caches are part of the ARC which is shared among open
1731 * pools, we skip loading them when we load the checkpointed
1732 * state of the pool.
1733 */
1734 if (!spa_writeable(spa))
1735 return;
1736 #endif
1737
1738 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1739
1740 nl2cache = 0;
1741 newvdevs = NULL;
1742 if (sav->sav_config != NULL) {
1743 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
1744 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
1745 if (nl2cache > 0) {
1746 newvdevs = kmem_alloc(
1747 nl2cache * sizeof (void *), KM_SLEEP);
1748 }
1749 }
1750
1751 oldvdevs = sav->sav_vdevs;
1752 oldnvdevs = sav->sav_count;
1753 sav->sav_vdevs = NULL;
1754 sav->sav_count = 0;
1755
1756 /*
1757 * Process new nvlist of vdevs.
1758 */
1759 for (i = 0; i < nl2cache; i++) {
1760 VERIFY(nvlist_lookup_uint64(l2cache[i], ZPOOL_CONFIG_GUID,
1761 &guid) == 0);
1762
1763 newvdevs[i] = NULL;
1764 for (j = 0; j < oldnvdevs; j++) {
1765 vd = oldvdevs[j];
1766 if (vd != NULL && guid == vd->vdev_guid) {
1767 /*
1768 * Retain previous vdev for add/remove ops.
1769 */
1770 newvdevs[i] = vd;
1771 oldvdevs[j] = NULL;
1772 break;
1773 }
1774 }
1775
1776 if (newvdevs[i] == NULL) {
1777 /*
1778 * Create new vdev
1779 */
1780 VERIFY(spa_config_parse(spa, &vd, l2cache[i], NULL, 0,
1781 VDEV_ALLOC_L2CACHE) == 0);
1782 ASSERT(vd != NULL);
1783 newvdevs[i] = vd;
1784
1785 /*
1786 * Commit this vdev as an l2cache device,
1787 * even if it fails to open.
1788 */
1789 spa_l2cache_add(vd);
1790
1791 vd->vdev_top = vd;
1792 vd->vdev_aux = sav;
1793
1794 spa_l2cache_activate(vd);
1795
1796 if (vdev_open(vd) != 0)
1797 continue;
1798
1799 (void) vdev_validate_aux(vd);
1800
1801 if (!vdev_is_dead(vd))
1802 l2arc_add_vdev(spa, vd);
1803 }
1804 }
1805
1806 /*
1807 * Purge vdevs that were dropped
1808 */
1809 for (i = 0; i < oldnvdevs; i++) {
1810 uint64_t pool;
1811
1812 vd = oldvdevs[i];
1813 if (vd != NULL) {
1814 ASSERT(vd->vdev_isl2cache);
1815
1816 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
1817 pool != 0ULL && l2arc_vdev_present(vd))
1818 l2arc_remove_vdev(vd);
1819 vdev_clear_stats(vd);
1820 vdev_free(vd);
1821 }
1822 }
1823
1824 if (oldvdevs)
1825 kmem_free(oldvdevs, oldnvdevs * sizeof (void *));
1826
1827 if (sav->sav_config == NULL)
1828 goto out;
1829
1830 sav->sav_vdevs = newvdevs;
1831 sav->sav_count = (int)nl2cache;
1832
1833 /*
1834 * Recompute the stashed list of l2cache devices, with status
1835 * information this time.
1836 */
1837 VERIFY(nvlist_remove(sav->sav_config, ZPOOL_CONFIG_L2CACHE,
1838 DATA_TYPE_NVLIST_ARRAY) == 0);
1839
1840 l2cache = NULL;
1841 if (sav->sav_count > 0) {
1842 l2cache = kmem_alloc(
1843 sav->sav_count * sizeof (void *), KM_SLEEP);
1844 }
1845 for (i = 0; i < sav->sav_count; i++)
1846 l2cache[i] = vdev_config_generate(spa,
1847 sav->sav_vdevs[i], B_TRUE, VDEV_CONFIG_L2CACHE);
1848 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
1849 ZPOOL_CONFIG_L2CACHE, l2cache, sav->sav_count) == 0);
1850 out:
1851 for (i = 0; i < sav->sav_count; i++)
1852 nvlist_free(l2cache[i]);
1853 if (sav->sav_count)
1854 kmem_free(l2cache, sav->sav_count * sizeof (void *));
1855 }
1856
1857 static int
load_nvlist(spa_t * spa,uint64_t obj,nvlist_t ** value)1858 load_nvlist(spa_t *spa, uint64_t obj, nvlist_t **value)
1859 {
1860 dmu_buf_t *db;
1861 char *packed = NULL;
1862 size_t nvsize = 0;
1863 int error;
1864 *value = NULL;
1865
1866 error = dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db);
1867 if (error != 0)
1868 return (error);
1869
1870 nvsize = *(uint64_t *)db->db_data;
1871 dmu_buf_rele(db, FTAG);
1872
1873 packed = kmem_alloc(nvsize, KM_SLEEP);
1874 error = dmu_read(spa->spa_meta_objset, obj, 0, nvsize, packed,
1875 DMU_READ_PREFETCH);
1876 if (error == 0)
1877 error = nvlist_unpack(packed, nvsize, value, 0);
1878 kmem_free(packed, nvsize);
1879
1880 return (error);
1881 }
1882
1883 /*
1884 * Concrete top-level vdevs that are not missing and are not logs. At every
1885 * spa_sync we write new uberblocks to at least SPA_SYNC_MIN_VDEVS core tvds.
1886 */
1887 static uint64_t
spa_healthy_core_tvds(spa_t * spa)1888 spa_healthy_core_tvds(spa_t *spa)
1889 {
1890 vdev_t *rvd = spa->spa_root_vdev;
1891 uint64_t tvds = 0;
1892
1893 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
1894 vdev_t *vd = rvd->vdev_child[i];
1895 if (vd->vdev_islog)
1896 continue;
1897 if (vdev_is_concrete(vd) && !vdev_is_dead(vd))
1898 tvds++;
1899 }
1900
1901 return (tvds);
1902 }
1903
1904 /*
1905 * Checks to see if the given vdev could not be opened, in which case we post a
1906 * sysevent to notify the autoreplace code that the device has been removed.
1907 */
1908 static void
spa_check_removed(vdev_t * vd)1909 spa_check_removed(vdev_t *vd)
1910 {
1911 for (uint64_t c = 0; c < vd->vdev_children; c++)
1912 spa_check_removed(vd->vdev_child[c]);
1913
1914 if (vd->vdev_ops->vdev_op_leaf && vdev_is_dead(vd) &&
1915 vdev_is_concrete(vd)) {
1916 zfs_post_autoreplace(vd->vdev_spa, vd);
1917 spa_event_notify(vd->vdev_spa, vd, NULL, ESC_ZFS_VDEV_CHECK);
1918 }
1919 }
1920
1921 static int
spa_check_for_missing_logs(spa_t * spa)1922 spa_check_for_missing_logs(spa_t *spa)
1923 {
1924 vdev_t *rvd = spa->spa_root_vdev;
1925
1926 /*
1927 * If we're doing a normal import, then build up any additional
1928 * diagnostic information about missing log devices.
1929 * We'll pass this up to the user for further processing.
1930 */
1931 if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG)) {
1932 nvlist_t **child, *nv;
1933 uint64_t idx = 0;
1934
1935 child = kmem_alloc(rvd->vdev_children * sizeof (nvlist_t **),
1936 KM_SLEEP);
1937 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1938
1939 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1940 vdev_t *tvd = rvd->vdev_child[c];
1941
1942 /*
1943 * We consider a device as missing only if it failed
1944 * to open (i.e. offline or faulted is not considered
1945 * as missing).
1946 */
1947 if (tvd->vdev_islog &&
1948 tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1949 child[idx++] = vdev_config_generate(spa, tvd,
1950 B_FALSE, VDEV_CONFIG_MISSING);
1951 }
1952 }
1953
1954 if (idx > 0) {
1955 fnvlist_add_nvlist_array(nv,
1956 ZPOOL_CONFIG_CHILDREN, child, idx);
1957 fnvlist_add_nvlist(spa->spa_load_info,
1958 ZPOOL_CONFIG_MISSING_DEVICES, nv);
1959
1960 for (uint64_t i = 0; i < idx; i++)
1961 nvlist_free(child[i]);
1962 }
1963 nvlist_free(nv);
1964 kmem_free(child, rvd->vdev_children * sizeof (char **));
1965
1966 if (idx > 0) {
1967 spa_load_failed(spa, "some log devices are missing");
1968 vdev_dbgmsg_print_tree(rvd, 2);
1969 return (SET_ERROR(ENXIO));
1970 }
1971 } else {
1972 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1973 vdev_t *tvd = rvd->vdev_child[c];
1974
1975 if (tvd->vdev_islog &&
1976 tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1977 spa_set_log_state(spa, SPA_LOG_CLEAR);
1978 spa_load_note(spa, "some log devices are "
1979 "missing, ZIL is dropped.");
1980 vdev_dbgmsg_print_tree(rvd, 2);
1981 break;
1982 }
1983 }
1984 }
1985
1986 return (0);
1987 }
1988
1989 /*
1990 * Check for missing log devices
1991 */
1992 static boolean_t
spa_check_logs(spa_t * spa)1993 spa_check_logs(spa_t *spa)
1994 {
1995 boolean_t rv = B_FALSE;
1996 dsl_pool_t *dp = spa_get_dsl(spa);
1997
1998 switch (spa->spa_log_state) {
1999 case SPA_LOG_MISSING:
2000 /* need to recheck in case slog has been restored */
2001 case SPA_LOG_UNKNOWN:
2002 rv = (dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
2003 zil_check_log_chain, NULL, DS_FIND_CHILDREN) != 0);
2004 if (rv)
2005 spa_set_log_state(spa, SPA_LOG_MISSING);
2006 break;
2007 }
2008 return (rv);
2009 }
2010
2011 static boolean_t
spa_passivate_log(spa_t * spa)2012 spa_passivate_log(spa_t *spa)
2013 {
2014 vdev_t *rvd = spa->spa_root_vdev;
2015 boolean_t slog_found = B_FALSE;
2016
2017 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
2018
2019 if (!spa_has_slogs(spa))
2020 return (B_FALSE);
2021
2022 for (int c = 0; c < rvd->vdev_children; c++) {
2023 vdev_t *tvd = rvd->vdev_child[c];
2024 metaslab_group_t *mg = tvd->vdev_mg;
2025
2026 if (tvd->vdev_islog) {
2027 metaslab_group_passivate(mg);
2028 slog_found = B_TRUE;
2029 }
2030 }
2031
2032 return (slog_found);
2033 }
2034
2035 static void
spa_activate_log(spa_t * spa)2036 spa_activate_log(spa_t *spa)
2037 {
2038 vdev_t *rvd = spa->spa_root_vdev;
2039
2040 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
2041
2042 for (int c = 0; c < rvd->vdev_children; c++) {
2043 vdev_t *tvd = rvd->vdev_child[c];
2044 metaslab_group_t *mg = tvd->vdev_mg;
2045
2046 if (tvd->vdev_islog)
2047 metaslab_group_activate(mg);
2048 }
2049 }
2050
2051 int
spa_reset_logs(spa_t * spa)2052 spa_reset_logs(spa_t *spa)
2053 {
2054 int error;
2055
2056 error = dmu_objset_find(spa_name(spa), zil_reset,
2057 NULL, DS_FIND_CHILDREN);
2058 if (error == 0) {
2059 /*
2060 * We successfully offlined the log device, sync out the
2061 * current txg so that the "stubby" block can be removed
2062 * by zil_sync().
2063 */
2064 txg_wait_synced(spa->spa_dsl_pool, 0);
2065 }
2066 return (error);
2067 }
2068
2069 static void
spa_aux_check_removed(spa_aux_vdev_t * sav)2070 spa_aux_check_removed(spa_aux_vdev_t *sav)
2071 {
2072 for (int i = 0; i < sav->sav_count; i++)
2073 spa_check_removed(sav->sav_vdevs[i]);
2074 }
2075
2076 void
spa_claim_notify(zio_t * zio)2077 spa_claim_notify(zio_t *zio)
2078 {
2079 spa_t *spa = zio->io_spa;
2080
2081 if (zio->io_error)
2082 return;
2083
2084 mutex_enter(&spa->spa_props_lock); /* any mutex will do */
2085 if (spa->spa_claim_max_txg < zio->io_bp->blk_birth)
2086 spa->spa_claim_max_txg = zio->io_bp->blk_birth;
2087 mutex_exit(&spa->spa_props_lock);
2088 }
2089
2090 typedef struct spa_load_error {
2091 uint64_t sle_meta_count;
2092 uint64_t sle_data_count;
2093 } spa_load_error_t;
2094
2095 static void
spa_load_verify_done(zio_t * zio)2096 spa_load_verify_done(zio_t *zio)
2097 {
2098 blkptr_t *bp = zio->io_bp;
2099 spa_load_error_t *sle = zio->io_private;
2100 dmu_object_type_t type = BP_GET_TYPE(bp);
2101 int error = zio->io_error;
2102 spa_t *spa = zio->io_spa;
2103
2104 abd_free(zio->io_abd);
2105 if (error) {
2106 if ((BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type)) &&
2107 type != DMU_OT_INTENT_LOG)
2108 atomic_inc_64(&sle->sle_meta_count);
2109 else
2110 atomic_inc_64(&sle->sle_data_count);
2111 }
2112
2113 mutex_enter(&spa->spa_scrub_lock);
2114 spa->spa_load_verify_ios--;
2115 cv_broadcast(&spa->spa_scrub_io_cv);
2116 mutex_exit(&spa->spa_scrub_lock);
2117 }
2118
2119 /*
2120 * Maximum number of concurrent scrub i/os to create while verifying
2121 * a pool while importing it.
2122 */
2123 int spa_load_verify_maxinflight = 10000;
2124 boolean_t spa_load_verify_metadata = B_TRUE;
2125 boolean_t spa_load_verify_data = B_TRUE;
2126
2127 /*ARGSUSED*/
2128 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)2129 spa_load_verify_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2130 const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
2131 {
2132 if (bp == NULL || BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2133 return (0);
2134 /*
2135 * Note: normally this routine will not be called if
2136 * spa_load_verify_metadata is not set. However, it may be useful
2137 * to manually set the flag after the traversal has begun.
2138 */
2139 if (!spa_load_verify_metadata)
2140 return (0);
2141 if (!BP_IS_METADATA(bp) && !spa_load_verify_data)
2142 return (0);
2143
2144 zio_t *rio = arg;
2145 size_t size = BP_GET_PSIZE(bp);
2146
2147 mutex_enter(&spa->spa_scrub_lock);
2148 while (spa->spa_load_verify_ios >= spa_load_verify_maxinflight)
2149 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
2150 spa->spa_load_verify_ios++;
2151 mutex_exit(&spa->spa_scrub_lock);
2152
2153 zio_nowait(zio_read(rio, spa, bp, abd_alloc_for_io(size, B_FALSE), size,
2154 spa_load_verify_done, rio->io_private, ZIO_PRIORITY_SCRUB,
2155 ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CANFAIL |
2156 ZIO_FLAG_SCRUB | ZIO_FLAG_RAW, zb));
2157 return (0);
2158 }
2159
2160 /* ARGSUSED */
2161 int
verify_dataset_name_len(dsl_pool_t * dp,dsl_dataset_t * ds,void * arg)2162 verify_dataset_name_len(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
2163 {
2164 if (dsl_dataset_namelen(ds) >= ZFS_MAX_DATASET_NAME_LEN)
2165 return (SET_ERROR(ENAMETOOLONG));
2166
2167 return (0);
2168 }
2169
2170 static int
spa_load_verify(spa_t * spa)2171 spa_load_verify(spa_t *spa)
2172 {
2173 zio_t *rio;
2174 spa_load_error_t sle = { 0 };
2175 zpool_load_policy_t policy;
2176 boolean_t verify_ok = B_FALSE;
2177 int error = 0;
2178
2179 zpool_get_load_policy(spa->spa_config, &policy);
2180
2181 if (policy.zlp_rewind & ZPOOL_NEVER_REWIND)
2182 return (0);
2183
2184 dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
2185 error = dmu_objset_find_dp(spa->spa_dsl_pool,
2186 spa->spa_dsl_pool->dp_root_dir_obj, verify_dataset_name_len, NULL,
2187 DS_FIND_CHILDREN);
2188 dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
2189 if (error != 0)
2190 return (error);
2191
2192 rio = zio_root(spa, NULL, &sle,
2193 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
2194
2195 if (spa_load_verify_metadata) {
2196 if (spa->spa_extreme_rewind) {
2197 spa_load_note(spa, "performing a complete scan of the "
2198 "pool since extreme rewind is on. This may take "
2199 "a very long time.\n (spa_load_verify_data=%u, "
2200 "spa_load_verify_metadata=%u)",
2201 spa_load_verify_data, spa_load_verify_metadata);
2202 }
2203 error = traverse_pool(spa, spa->spa_verify_min_txg,
2204 TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
2205 TRAVERSE_NO_DECRYPT, spa_load_verify_cb, rio);
2206 }
2207
2208 (void) zio_wait(rio);
2209
2210 spa->spa_load_meta_errors = sle.sle_meta_count;
2211 spa->spa_load_data_errors = sle.sle_data_count;
2212
2213 if (sle.sle_meta_count != 0 || sle.sle_data_count != 0) {
2214 spa_load_note(spa, "spa_load_verify found %llu metadata errors "
2215 "and %llu data errors", (u_longlong_t)sle.sle_meta_count,
2216 (u_longlong_t)sle.sle_data_count);
2217 }
2218
2219 if (spa_load_verify_dryrun ||
2220 (!error && sle.sle_meta_count <= policy.zlp_maxmeta &&
2221 sle.sle_data_count <= policy.zlp_maxdata)) {
2222 int64_t loss = 0;
2223
2224 verify_ok = B_TRUE;
2225 spa->spa_load_txg = spa->spa_uberblock.ub_txg;
2226 spa->spa_load_txg_ts = spa->spa_uberblock.ub_timestamp;
2227
2228 loss = spa->spa_last_ubsync_txg_ts - spa->spa_load_txg_ts;
2229 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2230 ZPOOL_CONFIG_LOAD_TIME, spa->spa_load_txg_ts) == 0);
2231 VERIFY(nvlist_add_int64(spa->spa_load_info,
2232 ZPOOL_CONFIG_REWIND_TIME, loss) == 0);
2233 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2234 ZPOOL_CONFIG_LOAD_DATA_ERRORS, sle.sle_data_count) == 0);
2235 } else {
2236 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg;
2237 }
2238
2239 if (spa_load_verify_dryrun)
2240 return (0);
2241
2242 if (error) {
2243 if (error != ENXIO && error != EIO)
2244 error = SET_ERROR(EIO);
2245 return (error);
2246 }
2247
2248 return (verify_ok ? 0 : EIO);
2249 }
2250
2251 /*
2252 * Find a value in the pool props object.
2253 */
2254 static void
spa_prop_find(spa_t * spa,zpool_prop_t prop,uint64_t * val)2255 spa_prop_find(spa_t *spa, zpool_prop_t prop, uint64_t *val)
2256 {
2257 (void) zap_lookup(spa->spa_meta_objset, spa->spa_pool_props_object,
2258 zpool_prop_to_name(prop), sizeof (uint64_t), 1, val);
2259 }
2260
2261 /*
2262 * Find a value in the pool directory object.
2263 */
2264 static int
spa_dir_prop(spa_t * spa,const char * name,uint64_t * val,boolean_t log_enoent)2265 spa_dir_prop(spa_t *spa, const char *name, uint64_t *val, boolean_t log_enoent)
2266 {
2267 int error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
2268 name, sizeof (uint64_t), 1, val);
2269
2270 if (error != 0 && (error != ENOENT || log_enoent)) {
2271 spa_load_failed(spa, "couldn't get '%s' value in MOS directory "
2272 "[error=%d]", name, error);
2273 }
2274
2275 return (error);
2276 }
2277
2278 static int
spa_vdev_err(vdev_t * vdev,vdev_aux_t aux,int err)2279 spa_vdev_err(vdev_t *vdev, vdev_aux_t aux, int err)
2280 {
2281 vdev_set_state(vdev, B_TRUE, VDEV_STATE_CANT_OPEN, aux);
2282 return (SET_ERROR(err));
2283 }
2284
2285 static void
spa_spawn_aux_threads(spa_t * spa)2286 spa_spawn_aux_threads(spa_t *spa)
2287 {
2288 ASSERT(spa_writeable(spa));
2289
2290 ASSERT(MUTEX_HELD(&spa_namespace_lock));
2291
2292 spa_start_indirect_condensing_thread(spa);
2293
2294 ASSERT3P(spa->spa_checkpoint_discard_zthr, ==, NULL);
2295 spa->spa_checkpoint_discard_zthr =
2296 zthr_create(spa_checkpoint_discard_thread_check,
2297 spa_checkpoint_discard_thread, spa);
2298 }
2299
2300 /*
2301 * Fix up config after a partly-completed split. This is done with the
2302 * ZPOOL_CONFIG_SPLIT nvlist. Both the splitting pool and the split-off
2303 * pool have that entry in their config, but only the splitting one contains
2304 * a list of all the guids of the vdevs that are being split off.
2305 *
2306 * This function determines what to do with that list: either rejoin
2307 * all the disks to the pool, or complete the splitting process. To attempt
2308 * the rejoin, each disk that is offlined is marked online again, and
2309 * we do a reopen() call. If the vdev label for every disk that was
2310 * marked online indicates it was successfully split off (VDEV_AUX_SPLIT_POOL)
2311 * then we call vdev_split() on each disk, and complete the split.
2312 *
2313 * Otherwise we leave the config alone, with all the vdevs in place in
2314 * the original pool.
2315 */
2316 static void
spa_try_repair(spa_t * spa,nvlist_t * config)2317 spa_try_repair(spa_t *spa, nvlist_t *config)
2318 {
2319 uint_t extracted;
2320 uint64_t *glist;
2321 uint_t i, gcount;
2322 nvlist_t *nvl;
2323 vdev_t **vd;
2324 boolean_t attempt_reopen;
2325
2326 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) != 0)
2327 return;
2328
2329 /* check that the config is complete */
2330 if (nvlist_lookup_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
2331 &glist, &gcount) != 0)
2332 return;
2333
2334 vd = kmem_zalloc(gcount * sizeof (vdev_t *), KM_SLEEP);
2335
2336 /* attempt to online all the vdevs & validate */
2337 attempt_reopen = B_TRUE;
2338 for (i = 0; i < gcount; i++) {
2339 if (glist[i] == 0) /* vdev is hole */
2340 continue;
2341
2342 vd[i] = spa_lookup_by_guid(spa, glist[i], B_FALSE);
2343 if (vd[i] == NULL) {
2344 /*
2345 * Don't bother attempting to reopen the disks;
2346 * just do the split.
2347 */
2348 attempt_reopen = B_FALSE;
2349 } else {
2350 /* attempt to re-online it */
2351 vd[i]->vdev_offline = B_FALSE;
2352 }
2353 }
2354
2355 if (attempt_reopen) {
2356 vdev_reopen(spa->spa_root_vdev);
2357
2358 /* check each device to see what state it's in */
2359 for (extracted = 0, i = 0; i < gcount; i++) {
2360 if (vd[i] != NULL &&
2361 vd[i]->vdev_stat.vs_aux != VDEV_AUX_SPLIT_POOL)
2362 break;
2363 ++extracted;
2364 }
2365 }
2366
2367 /*
2368 * If every disk has been moved to the new pool, or if we never
2369 * even attempted to look at them, then we split them off for
2370 * good.
2371 */
2372 if (!attempt_reopen || gcount == extracted) {
2373 for (i = 0; i < gcount; i++)
2374 if (vd[i] != NULL)
2375 vdev_split(vd[i]);
2376 vdev_reopen(spa->spa_root_vdev);
2377 }
2378
2379 kmem_free(vd, gcount * sizeof (vdev_t *));
2380 }
2381
2382 static int
spa_load(spa_t * spa,spa_load_state_t state,spa_import_type_t type)2383 spa_load(spa_t *spa, spa_load_state_t state, spa_import_type_t type)
2384 {
2385 char *ereport = FM_EREPORT_ZFS_POOL;
2386 int error;
2387
2388 spa->spa_load_state = state;
2389 (void) spa_import_progress_set_state(spa, spa_load_state(spa));
2390
2391 gethrestime(&spa->spa_loaded_ts);
2392 error = spa_load_impl(spa, type, &ereport);
2393
2394 /*
2395 * Don't count references from objsets that are already closed
2396 * and are making their way through the eviction process.
2397 */
2398 spa_evicting_os_wait(spa);
2399 spa->spa_minref = zfs_refcount_count(&spa->spa_refcount);
2400 if (error) {
2401 if (error != EEXIST) {
2402 spa->spa_loaded_ts.tv_sec = 0;
2403 spa->spa_loaded_ts.tv_nsec = 0;
2404 }
2405 if (error != EBADF) {
2406 (void) zfs_ereport_post(ereport, spa,
2407 NULL, NULL, NULL, 0, 0);
2408 }
2409 }
2410 spa->spa_load_state = error ? SPA_LOAD_ERROR : SPA_LOAD_NONE;
2411 spa->spa_ena = 0;
2412
2413 (void) spa_import_progress_set_state(spa, spa_load_state(spa));
2414
2415 return (error);
2416 }
2417
2418 /*
2419 * Count the number of per-vdev ZAPs associated with all of the vdevs in the
2420 * vdev tree rooted in the given vd, and ensure that each ZAP is present in the
2421 * spa's per-vdev ZAP list.
2422 */
2423 static uint64_t
vdev_count_verify_zaps(vdev_t * vd)2424 vdev_count_verify_zaps(vdev_t *vd)
2425 {
2426 spa_t *spa = vd->vdev_spa;
2427 uint64_t total = 0;
2428 if (vd->vdev_top_zap != 0) {
2429 total++;
2430 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2431 spa->spa_all_vdev_zaps, vd->vdev_top_zap));
2432 }
2433 if (vd->vdev_leaf_zap != 0) {
2434 total++;
2435 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2436 spa->spa_all_vdev_zaps, vd->vdev_leaf_zap));
2437 }
2438
2439 for (uint64_t i = 0; i < vd->vdev_children; i++) {
2440 total += vdev_count_verify_zaps(vd->vdev_child[i]);
2441 }
2442
2443 return (total);
2444 }
2445
2446 /*
2447 * Determine whether the activity check is required.
2448 */
2449 static boolean_t
spa_activity_check_required(spa_t * spa,uberblock_t * ub,nvlist_t * label,nvlist_t * config)2450 spa_activity_check_required(spa_t *spa, uberblock_t *ub, nvlist_t *label,
2451 nvlist_t *config)
2452 {
2453 uint64_t state = 0;
2454 uint64_t hostid = 0;
2455 uint64_t tryconfig_txg = 0;
2456 uint64_t tryconfig_timestamp = 0;
2457 uint16_t tryconfig_mmp_seq = 0;
2458 nvlist_t *nvinfo;
2459
2460 if (nvlist_exists(config, ZPOOL_CONFIG_LOAD_INFO)) {
2461 nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
2462 (void) nvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_MMP_TXG,
2463 &tryconfig_txg);
2464 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
2465 &tryconfig_timestamp);
2466 (void) nvlist_lookup_uint16(nvinfo, ZPOOL_CONFIG_MMP_SEQ,
2467 &tryconfig_mmp_seq);
2468 }
2469
2470 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE, &state);
2471
2472 /*
2473 * Disable the MMP activity check - This is used by zdb which
2474 * is intended to be used on potentially active pools.
2475 */
2476 if (spa->spa_import_flags & ZFS_IMPORT_SKIP_MMP)
2477 return (B_FALSE);
2478
2479 /*
2480 * Skip the activity check when the MMP feature is disabled.
2481 */
2482 if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay == 0)
2483 return (B_FALSE);
2484
2485 /*
2486 * If the tryconfig_ values are nonzero, they are the results of an
2487 * earlier tryimport. If they all match the uberblock we just found,
2488 * then the pool has not changed and we return false so we do not test
2489 * a second time.
2490 */
2491 if (tryconfig_txg && tryconfig_txg == ub->ub_txg &&
2492 tryconfig_timestamp && tryconfig_timestamp == ub->ub_timestamp &&
2493 tryconfig_mmp_seq && tryconfig_mmp_seq ==
2494 (MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0))
2495 return (B_FALSE);
2496
2497 /*
2498 * Allow the activity check to be skipped when importing the pool
2499 * on the same host which last imported it. Since the hostid from
2500 * configuration may be stale use the one read from the label.
2501 */
2502 if (nvlist_exists(label, ZPOOL_CONFIG_HOSTID))
2503 hostid = fnvlist_lookup_uint64(label, ZPOOL_CONFIG_HOSTID);
2504
2505 if (hostid == spa_get_hostid())
2506 return (B_FALSE);
2507
2508 /*
2509 * Skip the activity test when the pool was cleanly exported.
2510 */
2511 if (state != POOL_STATE_ACTIVE)
2512 return (B_FALSE);
2513
2514 return (B_TRUE);
2515 }
2516
2517 /*
2518 * Nanoseconds the activity check must watch for changes on-disk.
2519 */
2520 static uint64_t
spa_activity_check_duration(spa_t * spa,uberblock_t * ub)2521 spa_activity_check_duration(spa_t *spa, uberblock_t *ub)
2522 {
2523 uint64_t import_intervals = MAX(zfs_multihost_import_intervals, 1);
2524 uint64_t multihost_interval = MSEC2NSEC(
2525 MMP_INTERVAL_OK(zfs_multihost_interval));
2526 uint64_t import_delay = MAX(NANOSEC, import_intervals *
2527 multihost_interval);
2528
2529 /*
2530 * Local tunables determine a minimum duration except for the case
2531 * where we know when the remote host will suspend the pool if MMP
2532 * writes do not land.
2533 *
2534 * See Big Theory comment at the top of mmp.c for the reasoning behind
2535 * these cases and times.
2536 */
2537
2538 ASSERT(MMP_IMPORT_SAFETY_FACTOR >= 100);
2539
2540 if (MMP_INTERVAL_VALID(ub) && MMP_FAIL_INT_VALID(ub) &&
2541 MMP_FAIL_INT(ub) > 0) {
2542
2543 /* MMP on remote host will suspend pool after failed writes */
2544 import_delay = MMP_FAIL_INT(ub) * MSEC2NSEC(MMP_INTERVAL(ub)) *
2545 MMP_IMPORT_SAFETY_FACTOR / 100;
2546
2547 zfs_dbgmsg("fail_intvals>0 import_delay=%llu ub_mmp "
2548 "mmp_fails=%llu ub_mmp mmp_interval=%llu "
2549 "import_intervals=%u", import_delay, MMP_FAIL_INT(ub),
2550 MMP_INTERVAL(ub), import_intervals);
2551
2552 } else if (MMP_INTERVAL_VALID(ub) && MMP_FAIL_INT_VALID(ub) &&
2553 MMP_FAIL_INT(ub) == 0) {
2554
2555 /* MMP on remote host will never suspend pool */
2556 import_delay = MAX(import_delay, (MSEC2NSEC(MMP_INTERVAL(ub)) +
2557 ub->ub_mmp_delay) * import_intervals);
2558
2559 zfs_dbgmsg("fail_intvals=0 import_delay=%llu ub_mmp "
2560 "mmp_interval=%llu ub_mmp_delay=%llu "
2561 "import_intervals=%u", import_delay, MMP_INTERVAL(ub),
2562 ub->ub_mmp_delay, import_intervals);
2563
2564 } else if (MMP_VALID(ub)) {
2565 /*
2566 * zfs-0.7 compatability case
2567 */
2568
2569 import_delay = MAX(import_delay, (multihost_interval +
2570 ub->ub_mmp_delay) * import_intervals);
2571
2572 zfs_dbgmsg("import_delay=%llu ub_mmp_delay=%llu "
2573 "import_intervals=%u leaves=%u", import_delay,
2574 ub->ub_mmp_delay, import_intervals,
2575 vdev_count_leaves(spa));
2576 } else {
2577 /* Using local tunings is the only reasonable option */
2578 zfs_dbgmsg("pool last imported on non-MMP aware "
2579 "host using import_delay=%llu multihost_interval=%llu "
2580 "import_intervals=%u", import_delay, multihost_interval,
2581 import_intervals);
2582 }
2583
2584 return (import_delay);
2585 }
2586
2587 /*
2588 * Perform the import activity check. If the user canceled the import or
2589 * we detected activity then fail.
2590 */
2591 static int
spa_activity_check(spa_t * spa,uberblock_t * ub,nvlist_t * config)2592 spa_activity_check(spa_t *spa, uberblock_t *ub, nvlist_t *config)
2593 {
2594 uint64_t txg = ub->ub_txg;
2595 uint64_t timestamp = ub->ub_timestamp;
2596 uint64_t mmp_config = ub->ub_mmp_config;
2597 uint16_t mmp_seq = MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0;
2598 uint64_t import_delay;
2599 hrtime_t import_expire;
2600 nvlist_t *mmp_label = NULL;
2601 vdev_t *rvd = spa->spa_root_vdev;
2602 kcondvar_t cv;
2603 kmutex_t mtx;
2604 int error = 0;
2605
2606 cv_init(&cv, NULL, CV_DEFAULT, NULL);
2607 mutex_init(&mtx, NULL, MUTEX_DEFAULT, NULL);
2608 mutex_enter(&mtx);
2609
2610 /*
2611 * If ZPOOL_CONFIG_MMP_TXG is present an activity check was performed
2612 * during the earlier tryimport. If the txg recorded there is 0 then
2613 * the pool is known to be active on another host.
2614 *
2615 * Otherwise, the pool might be in use on another host. Check for
2616 * changes in the uberblocks on disk if necessary.
2617 */
2618 if (nvlist_exists(config, ZPOOL_CONFIG_LOAD_INFO)) {
2619 nvlist_t *nvinfo = fnvlist_lookup_nvlist(config,
2620 ZPOOL_CONFIG_LOAD_INFO);
2621
2622 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_TXG) &&
2623 fnvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_MMP_TXG) == 0) {
2624 vdev_uberblock_load(rvd, ub, &mmp_label);
2625 error = SET_ERROR(EREMOTEIO);
2626 goto out;
2627 }
2628 }
2629
2630 import_delay = spa_activity_check_duration(spa, ub);
2631
2632 /* Add a small random factor in case of simultaneous imports (0-25%) */
2633 import_delay += import_delay * spa_get_random(250) / 1000;
2634
2635 import_expire = gethrtime() + import_delay;
2636
2637 while (gethrtime() < import_expire) {
2638 (void) spa_import_progress_set_mmp_check(spa,
2639 NSEC2SEC(import_expire - gethrtime()));
2640
2641 vdev_uberblock_load(rvd, ub, &mmp_label);
2642
2643 if (txg != ub->ub_txg || timestamp != ub->ub_timestamp ||
2644 mmp_seq != (MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0)) {
2645 zfs_dbgmsg("multihost activity detected "
2646 "txg %llu ub_txg %llu "
2647 "timestamp %llu ub_timestamp %llu "
2648 "mmp_config %#llx ub_mmp_config %#llx",
2649 txg, ub->ub_txg, timestamp, ub->ub_timestamp,
2650 mmp_config, ub->ub_mmp_config);
2651
2652 error = SET_ERROR(EREMOTEIO);
2653 break;
2654 }
2655
2656 if (mmp_label) {
2657 nvlist_free(mmp_label);
2658 mmp_label = NULL;
2659 }
2660
2661 error = cv_timedwait_sig(&cv, &mtx, ddi_get_lbolt() + hz);
2662 if (error != -1) {
2663 error = SET_ERROR(EINTR);
2664 break;
2665 }
2666 error = 0;
2667 }
2668
2669 out:
2670 mutex_exit(&mtx);
2671 mutex_destroy(&mtx);
2672 cv_destroy(&cv);
2673
2674 /*
2675 * If the pool is determined to be active store the status in the
2676 * spa->spa_load_info nvlist. If the remote hostname or hostid are
2677 * available from configuration read from disk store them as well.
2678 * This allows 'zpool import' to generate a more useful message.
2679 *
2680 * ZPOOL_CONFIG_MMP_STATE - observed pool status (mandatory)
2681 * ZPOOL_CONFIG_MMP_HOSTNAME - hostname from the active pool
2682 * ZPOOL_CONFIG_MMP_HOSTID - hostid from the active pool
2683 */
2684 if (error == EREMOTEIO) {
2685 char *hostname = "<unknown>";
2686 uint64_t hostid = 0;
2687
2688 if (mmp_label) {
2689 if (nvlist_exists(mmp_label, ZPOOL_CONFIG_HOSTNAME)) {
2690 hostname = fnvlist_lookup_string(mmp_label,
2691 ZPOOL_CONFIG_HOSTNAME);
2692 fnvlist_add_string(spa->spa_load_info,
2693 ZPOOL_CONFIG_MMP_HOSTNAME, hostname);
2694 }
2695
2696 if (nvlist_exists(mmp_label, ZPOOL_CONFIG_HOSTID)) {
2697 hostid = fnvlist_lookup_uint64(mmp_label,
2698 ZPOOL_CONFIG_HOSTID);
2699 fnvlist_add_uint64(spa->spa_load_info,
2700 ZPOOL_CONFIG_MMP_HOSTID, hostid);
2701 }
2702 }
2703
2704 fnvlist_add_uint64(spa->spa_load_info,
2705 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_ACTIVE);
2706 fnvlist_add_uint64(spa->spa_load_info,
2707 ZPOOL_CONFIG_MMP_TXG, 0);
2708
2709 error = spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO);
2710 }
2711
2712 if (mmp_label)
2713 nvlist_free(mmp_label);
2714
2715 return (error);
2716 }
2717
2718 static int
spa_verify_host(spa_t * spa,nvlist_t * mos_config)2719 spa_verify_host(spa_t *spa, nvlist_t *mos_config)
2720 {
2721 uint64_t hostid;
2722 char *hostname;
2723 uint64_t myhostid = 0;
2724
2725 if (!spa_is_root(spa) && nvlist_lookup_uint64(mos_config,
2726 ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
2727 hostname = fnvlist_lookup_string(mos_config,
2728 ZPOOL_CONFIG_HOSTNAME);
2729
2730 myhostid = zone_get_hostid(NULL);
2731
2732 if (hostid != 0 && myhostid != 0 && hostid != myhostid) {
2733 cmn_err(CE_WARN, "pool '%s' could not be "
2734 "loaded as it was last accessed by "
2735 "another system (host: %s hostid: 0x%llx). "
2736 "See: http://illumos.org/msg/ZFS-8000-EY",
2737 spa_name(spa), hostname, (u_longlong_t)hostid);
2738 spa_load_failed(spa, "hostid verification failed: pool "
2739 "last accessed by host: %s (hostid: 0x%llx)",
2740 hostname, (u_longlong_t)hostid);
2741 return (SET_ERROR(EBADF));
2742 }
2743 }
2744
2745 return (0);
2746 }
2747
2748 static int
spa_ld_parse_config(spa_t * spa,spa_import_type_t type)2749 spa_ld_parse_config(spa_t *spa, spa_import_type_t type)
2750 {
2751 int error = 0;
2752 nvlist_t *nvtree, *nvl, *config = spa->spa_config;
2753 int parse;
2754 vdev_t *rvd;
2755 uint64_t pool_guid;
2756 char *comment;
2757
2758 /*
2759 * Versioning wasn't explicitly added to the label until later, so if
2760 * it's not present treat it as the initial version.
2761 */
2762 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
2763 &spa->spa_ubsync.ub_version) != 0)
2764 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
2765
2766 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid)) {
2767 spa_load_failed(spa, "invalid config provided: '%s' missing",
2768 ZPOOL_CONFIG_POOL_GUID);
2769 return (SET_ERROR(EINVAL));
2770 }
2771
2772 /*
2773 * If we are doing an import, ensure that the pool is not already
2774 * imported by checking if its pool guid already exists in the
2775 * spa namespace.
2776 *
2777 * The only case that we allow an already imported pool to be
2778 * imported again, is when the pool is checkpointed and we want to
2779 * look at its checkpointed state from userland tools like zdb.
2780 */
2781 #ifdef _KERNEL
2782 if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2783 spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2784 spa_guid_exists(pool_guid, 0)) {
2785 #else
2786 if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2787 spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2788 spa_guid_exists(pool_guid, 0) &&
2789 !spa_importing_readonly_checkpoint(spa)) {
2790 #endif
2791 spa_load_failed(spa, "a pool with guid %llu is already open",
2792 (u_longlong_t)pool_guid);
2793 return (SET_ERROR(EEXIST));
2794 }
2795
2796 spa->spa_config_guid = pool_guid;
2797
2798 nvlist_free(spa->spa_load_info);
2799 spa->spa_load_info = fnvlist_alloc();
2800
2801 ASSERT(spa->spa_comment == NULL);
2802 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2803 spa->spa_comment = spa_strdup(comment);
2804
2805 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
2806 &spa->spa_config_txg);
2807
2808 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) == 0)
2809 spa->spa_config_splitting = fnvlist_dup(nvl);
2810
2811 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvtree)) {
2812 spa_load_failed(spa, "invalid config provided: '%s' missing",
2813 ZPOOL_CONFIG_VDEV_TREE);
2814 return (SET_ERROR(EINVAL));
2815 }
2816
2817 /*
2818 * Create "The Godfather" zio to hold all async IOs
2819 */
2820 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
2821 KM_SLEEP);
2822 for (int i = 0; i < max_ncpus; i++) {
2823 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
2824 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2825 ZIO_FLAG_GODFATHER);
2826 }
2827
2828 /*
2829 * Parse the configuration into a vdev tree. We explicitly set the
2830 * value that will be returned by spa_version() since parsing the
2831 * configuration requires knowing the version number.
2832 */
2833 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2834 parse = (type == SPA_IMPORT_EXISTING ?
2835 VDEV_ALLOC_LOAD : VDEV_ALLOC_SPLIT);
2836 error = spa_config_parse(spa, &rvd, nvtree, NULL, 0, parse);
2837 spa_config_exit(spa, SCL_ALL, FTAG);
2838
2839 if (error != 0) {
2840 spa_load_failed(spa, "unable to parse config [error=%d]",
2841 error);
2842 return (error);
2843 }
2844
2845 ASSERT(spa->spa_root_vdev == rvd);
2846 ASSERT3U(spa->spa_min_ashift, >=, SPA_MINBLOCKSHIFT);
2847 ASSERT3U(spa->spa_max_ashift, <=, SPA_MAXBLOCKSHIFT);
2848
2849 if (type != SPA_IMPORT_ASSEMBLE) {
2850 ASSERT(spa_guid(spa) == pool_guid);
2851 }
2852
2853 return (0);
2854 }
2855
2856 /*
2857 * Recursively open all vdevs in the vdev tree. This function is called twice:
2858 * first with the untrusted config, then with the trusted config.
2859 */
2860 static int
2861 spa_ld_open_vdevs(spa_t *spa)
2862 {
2863 int error = 0;
2864
2865 /*
2866 * spa_missing_tvds_allowed defines how many top-level vdevs can be
2867 * missing/unopenable for the root vdev to be still considered openable.
2868 */
2869 if (spa->spa_trust_config) {
2870 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds;
2871 } else if (spa->spa_config_source == SPA_CONFIG_SRC_CACHEFILE) {
2872 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_cachefile;
2873 } else if (spa->spa_config_source == SPA_CONFIG_SRC_SCAN) {
2874 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_scan;
2875 } else {
2876 spa->spa_missing_tvds_allowed = 0;
2877 }
2878
2879 spa->spa_missing_tvds_allowed =
2880 MAX(zfs_max_missing_tvds, spa->spa_missing_tvds_allowed);
2881
2882 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2883 error = vdev_open(spa->spa_root_vdev);
2884 spa_config_exit(spa, SCL_ALL, FTAG);
2885
2886 if (spa->spa_missing_tvds != 0) {
2887 spa_load_note(spa, "vdev tree has %lld missing top-level "
2888 "vdevs.", (u_longlong_t)spa->spa_missing_tvds);
2889 if (spa->spa_trust_config && (spa->spa_mode & FWRITE)) {
2890 /*
2891 * Although theoretically we could allow users to open
2892 * incomplete pools in RW mode, we'd need to add a lot
2893 * of extra logic (e.g. adjust pool space to account
2894 * for missing vdevs).
2895 * This limitation also prevents users from accidentally
2896 * opening the pool in RW mode during data recovery and
2897 * damaging it further.
2898 */
2899 spa_load_note(spa, "pools with missing top-level "
2900 "vdevs can only be opened in read-only mode.");
2901 error = SET_ERROR(ENXIO);
2902 } else {
2903 spa_load_note(spa, "current settings allow for maximum "
2904 "%lld missing top-level vdevs at this stage.",
2905 (u_longlong_t)spa->spa_missing_tvds_allowed);
2906 }
2907 }
2908 if (error != 0) {
2909 spa_load_failed(spa, "unable to open vdev tree [error=%d]",
2910 error);
2911 }
2912 if (spa->spa_missing_tvds != 0 || error != 0)
2913 vdev_dbgmsg_print_tree(spa->spa_root_vdev, 2);
2914
2915 return (error);
2916 }
2917
2918 /*
2919 * We need to validate the vdev labels against the configuration that
2920 * we have in hand. This function is called twice: first with an untrusted
2921 * config, then with a trusted config. The validation is more strict when the
2922 * config is trusted.
2923 */
2924 static int
2925 spa_ld_validate_vdevs(spa_t *spa)
2926 {
2927 int error = 0;
2928 vdev_t *rvd = spa->spa_root_vdev;
2929
2930 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2931 error = vdev_validate(rvd);
2932 spa_config_exit(spa, SCL_ALL, FTAG);
2933
2934 if (error != 0) {
2935 spa_load_failed(spa, "vdev_validate failed [error=%d]", error);
2936 return (error);
2937 }
2938
2939 if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN) {
2940 spa_load_failed(spa, "cannot open vdev tree after invalidating "
2941 "some vdevs");
2942 vdev_dbgmsg_print_tree(rvd, 2);
2943 return (SET_ERROR(ENXIO));
2944 }
2945
2946 return (0);
2947 }
2948
2949 static void
2950 spa_ld_select_uberblock_done(spa_t *spa, uberblock_t *ub)
2951 {
2952 spa->spa_state = POOL_STATE_ACTIVE;
2953 spa->spa_ubsync = spa->spa_uberblock;
2954 spa->spa_verify_min_txg = spa->spa_extreme_rewind ?
2955 TXG_INITIAL - 1 : spa_last_synced_txg(spa) - TXG_DEFER_SIZE - 1;
2956 spa->spa_first_txg = spa->spa_last_ubsync_txg ?
2957 spa->spa_last_ubsync_txg : spa_last_synced_txg(spa) + 1;
2958 spa->spa_claim_max_txg = spa->spa_first_txg;
2959 spa->spa_prev_software_version = ub->ub_software_version;
2960 }
2961
2962 static int
2963 spa_ld_select_uberblock(spa_t *spa, spa_import_type_t type)
2964 {
2965 vdev_t *rvd = spa->spa_root_vdev;
2966 nvlist_t *label;
2967 uberblock_t *ub = &spa->spa_uberblock;
2968 boolean_t activity_check = B_FALSE;
2969
2970 /*
2971 * If we are opening the checkpointed state of the pool by
2972 * rewinding to it, at this point we will have written the
2973 * checkpointed uberblock to the vdev labels, so searching
2974 * the labels will find the right uberblock. However, if
2975 * we are opening the checkpointed state read-only, we have
2976 * not modified the labels. Therefore, we must ignore the
2977 * labels and continue using the spa_uberblock that was set
2978 * by spa_ld_checkpoint_rewind.
2979 *
2980 * Note that it would be fine to ignore the labels when
2981 * rewinding (opening writeable) as well. However, if we
2982 * crash just after writing the labels, we will end up
2983 * searching the labels. Doing so in the common case means
2984 * that this code path gets exercised normally, rather than
2985 * just in the edge case.
2986 */
2987 if (ub->ub_checkpoint_txg != 0 &&
2988 spa_importing_readonly_checkpoint(spa)) {
2989 spa_ld_select_uberblock_done(spa, ub);
2990 return (0);
2991 }
2992
2993 /*
2994 * Find the best uberblock.
2995 */
2996 vdev_uberblock_load(rvd, ub, &label);
2997
2998 /*
2999 * If we weren't able to find a single valid uberblock, return failure.
3000 */
3001 if (ub->ub_txg == 0) {
3002 nvlist_free(label);
3003 spa_load_failed(spa, "no valid uberblock found");
3004 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, ENXIO));
3005 }
3006
3007 if (spa->spa_load_max_txg != UINT64_MAX) {
3008 (void) spa_import_progress_set_max_txg(spa,
3009 (u_longlong_t)spa->spa_load_max_txg);
3010 }
3011 spa_load_note(spa, "using uberblock with txg=%llu",
3012 (u_longlong_t)ub->ub_txg);
3013
3014 /*
3015 * For pools which have the multihost property on determine if the
3016 * pool is truly inactive and can be safely imported. Prevent
3017 * hosts which don't have a hostid set from importing the pool.
3018 */
3019 activity_check = spa_activity_check_required(spa, ub, label,
3020 spa->spa_config);
3021 if (activity_check) {
3022 if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay &&
3023 spa_get_hostid() == 0) {
3024 nvlist_free(label);
3025 fnvlist_add_uint64(spa->spa_load_info,
3026 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_NO_HOSTID);
3027 return (spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO));
3028 }
3029
3030 int error = spa_activity_check(spa, ub, spa->spa_config);
3031 if (error) {
3032 nvlist_free(label);
3033 return (error);
3034 }
3035
3036 fnvlist_add_uint64(spa->spa_load_info,
3037 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_INACTIVE);
3038 fnvlist_add_uint64(spa->spa_load_info,
3039 ZPOOL_CONFIG_MMP_TXG, ub->ub_txg);
3040 fnvlist_add_uint16(spa->spa_load_info,
3041 ZPOOL_CONFIG_MMP_SEQ,
3042 (MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0));
3043 }
3044
3045 /*
3046 * If the pool has an unsupported version we can't open it.
3047 */
3048 if (!SPA_VERSION_IS_SUPPORTED(ub->ub_version)) {
3049 nvlist_free(label);
3050 spa_load_failed(spa, "version %llu is not supported",
3051 (u_longlong_t)ub->ub_version);
3052 return (spa_vdev_err(rvd, VDEV_AUX_VERSION_NEWER, ENOTSUP));
3053 }
3054
3055 if (ub->ub_version >= SPA_VERSION_FEATURES) {
3056 nvlist_t *features;
3057
3058 /*
3059 * If we weren't able to find what's necessary for reading the
3060 * MOS in the label, return failure.
3061 */
3062 if (label == NULL) {
3063 spa_load_failed(spa, "label config unavailable");
3064 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3065 ENXIO));
3066 }
3067
3068 if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_FEATURES_FOR_READ,
3069 &features) != 0) {
3070 nvlist_free(label);
3071 spa_load_failed(spa, "invalid label: '%s' missing",
3072 ZPOOL_CONFIG_FEATURES_FOR_READ);
3073 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3074 ENXIO));
3075 }
3076
3077 /*
3078 * Update our in-core representation with the definitive values
3079 * from the label.
3080 */
3081 nvlist_free(spa->spa_label_features);
3082 VERIFY(nvlist_dup(features, &spa->spa_label_features, 0) == 0);
3083 }
3084
3085 nvlist_free(label);
3086
3087 /*
3088 * Look through entries in the label nvlist's features_for_read. If
3089 * there is a feature listed there which we don't understand then we
3090 * cannot open a pool.
3091 */
3092 if (ub->ub_version >= SPA_VERSION_FEATURES) {
3093 nvlist_t *unsup_feat;
3094
3095 VERIFY(nvlist_alloc(&unsup_feat, NV_UNIQUE_NAME, KM_SLEEP) ==
3096 0);
3097
3098 for (nvpair_t *nvp = nvlist_next_nvpair(spa->spa_label_features,
3099 NULL); nvp != NULL;
3100 nvp = nvlist_next_nvpair(spa->spa_label_features, nvp)) {
3101 if (!zfeature_is_supported(nvpair_name(nvp))) {
3102 VERIFY(nvlist_add_string(unsup_feat,
3103 nvpair_name(nvp), "") == 0);
3104 }
3105 }
3106
3107 if (!nvlist_empty(unsup_feat)) {
3108 VERIFY(nvlist_add_nvlist(spa->spa_load_info,
3109 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat) == 0);
3110 nvlist_free(unsup_feat);
3111 spa_load_failed(spa, "some features are unsupported");
3112 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
3113 ENOTSUP));
3114 }
3115
3116 nvlist_free(unsup_feat);
3117 }
3118
3119 if (type != SPA_IMPORT_ASSEMBLE && spa->spa_config_splitting) {
3120 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3121 spa_try_repair(spa, spa->spa_config);
3122 spa_config_exit(spa, SCL_ALL, FTAG);
3123 nvlist_free(spa->spa_config_splitting);
3124 spa->spa_config_splitting = NULL;
3125 }
3126
3127 /*
3128 * Initialize internal SPA structures.
3129 */
3130 spa_ld_select_uberblock_done(spa, ub);
3131
3132 return (0);
3133 }
3134
3135 static int
3136 spa_ld_open_rootbp(spa_t *spa)
3137 {
3138 int error = 0;
3139 vdev_t *rvd = spa->spa_root_vdev;
3140
3141 error = dsl_pool_init(spa, spa->spa_first_txg, &spa->spa_dsl_pool);
3142 if (error != 0) {
3143 spa_load_failed(spa, "unable to open rootbp in dsl_pool_init "
3144 "[error=%d]", error);
3145 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3146 }
3147 spa->spa_meta_objset = spa->spa_dsl_pool->dp_meta_objset;
3148
3149 return (0);
3150 }
3151
3152 static int
3153 spa_ld_trusted_config(spa_t *spa, spa_import_type_t type,
3154 boolean_t reloading)
3155 {
3156 vdev_t *mrvd, *rvd = spa->spa_root_vdev;
3157 nvlist_t *nv, *mos_config, *policy;
3158 int error = 0, copy_error;
3159 uint64_t healthy_tvds, healthy_tvds_mos;
3160 uint64_t mos_config_txg;
3161
3162 if (spa_dir_prop(spa, DMU_POOL_CONFIG, &spa->spa_config_object, B_TRUE)
3163 != 0)
3164 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3165
3166 /*
3167 * If we're assembling a pool from a split, the config provided is
3168 * already trusted so there is nothing to do.
3169 */
3170 if (type == SPA_IMPORT_ASSEMBLE)
3171 return (0);
3172
3173 healthy_tvds = spa_healthy_core_tvds(spa);
3174
3175 if (load_nvlist(spa, spa->spa_config_object, &mos_config)
3176 != 0) {
3177 spa_load_failed(spa, "unable to retrieve MOS config");
3178 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3179 }
3180
3181 /*
3182 * If we are doing an open, pool owner wasn't verified yet, thus do
3183 * the verification here.
3184 */
3185 if (spa->spa_load_state == SPA_LOAD_OPEN) {
3186 error = spa_verify_host(spa, mos_config);
3187 if (error != 0) {
3188 nvlist_free(mos_config);
3189 return (error);
3190 }
3191 }
3192
3193 nv = fnvlist_lookup_nvlist(mos_config, ZPOOL_CONFIG_VDEV_TREE);
3194
3195 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3196
3197 /*
3198 * Build a new vdev tree from the trusted config
3199 */
3200 VERIFY(spa_config_parse(spa, &mrvd, nv, NULL, 0, VDEV_ALLOC_LOAD) == 0);
3201
3202 /*
3203 * Vdev paths in the MOS may be obsolete. If the untrusted config was
3204 * obtained by scanning /dev/dsk, then it will have the right vdev
3205 * paths. We update the trusted MOS config with this information.
3206 * We first try to copy the paths with vdev_copy_path_strict, which
3207 * succeeds only when both configs have exactly the same vdev tree.
3208 * If that fails, we fall back to a more flexible method that has a
3209 * best effort policy.
3210 */
3211 copy_error = vdev_copy_path_strict(rvd, mrvd);
3212 if (copy_error != 0 || spa_load_print_vdev_tree) {
3213 spa_load_note(spa, "provided vdev tree:");
3214 vdev_dbgmsg_print_tree(rvd, 2);
3215 spa_load_note(spa, "MOS vdev tree:");
3216 vdev_dbgmsg_print_tree(mrvd, 2);
3217 }
3218 if (copy_error != 0) {
3219 spa_load_note(spa, "vdev_copy_path_strict failed, falling "
3220 "back to vdev_copy_path_relaxed");
3221 vdev_copy_path_relaxed(rvd, mrvd);
3222 }
3223
3224 vdev_close(rvd);
3225 vdev_free(rvd);
3226 spa->spa_root_vdev = mrvd;
3227 rvd = mrvd;
3228 spa_config_exit(spa, SCL_ALL, FTAG);
3229
3230 /*
3231 * We will use spa_config if we decide to reload the spa or if spa_load
3232 * fails and we rewind. We must thus regenerate the config using the
3233 * MOS information with the updated paths. ZPOOL_LOAD_POLICY is used to
3234 * pass settings on how to load the pool and is not stored in the MOS.
3235 * We copy it over to our new, trusted config.
3236 */
3237 mos_config_txg = fnvlist_lookup_uint64(mos_config,
3238 ZPOOL_CONFIG_POOL_TXG);
3239 nvlist_free(mos_config);
3240 mos_config = spa_config_generate(spa, NULL, mos_config_txg, B_FALSE);
3241 if (nvlist_lookup_nvlist(spa->spa_config, ZPOOL_LOAD_POLICY,
3242 &policy) == 0)
3243 fnvlist_add_nvlist(mos_config, ZPOOL_LOAD_POLICY, policy);
3244 spa_config_set(spa, mos_config);
3245 spa->spa_config_source = SPA_CONFIG_SRC_MOS;
3246
3247 /*
3248 * Now that we got the config from the MOS, we should be more strict
3249 * in checking blkptrs and can make assumptions about the consistency
3250 * of the vdev tree. spa_trust_config must be set to true before opening
3251 * vdevs in order for them to be writeable.
3252 */
3253 spa->spa_trust_config = B_TRUE;
3254
3255 /*
3256 * Open and validate the new vdev tree
3257 */
3258 error = spa_ld_open_vdevs(spa);
3259 if (error != 0)
3260 return (error);
3261
3262 error = spa_ld_validate_vdevs(spa);
3263 if (error != 0)
3264 return (error);
3265
3266 if (copy_error != 0 || spa_load_print_vdev_tree) {
3267 spa_load_note(spa, "final vdev tree:");
3268 vdev_dbgmsg_print_tree(rvd, 2);
3269 }
3270
3271 if (spa->spa_load_state != SPA_LOAD_TRYIMPORT &&
3272 !spa->spa_extreme_rewind && zfs_max_missing_tvds == 0) {
3273 /*
3274 * Sanity check to make sure that we are indeed loading the
3275 * latest uberblock. If we missed SPA_SYNC_MIN_VDEVS tvds
3276 * in the config provided and they happened to be the only ones
3277 * to have the latest uberblock, we could involuntarily perform
3278 * an extreme rewind.
3279 */
3280 healthy_tvds_mos = spa_healthy_core_tvds(spa);
3281 if (healthy_tvds_mos - healthy_tvds >=
3282 SPA_SYNC_MIN_VDEVS) {
3283 spa_load_note(spa, "config provided misses too many "
3284 "top-level vdevs compared to MOS (%lld vs %lld). ",
3285 (u_longlong_t)healthy_tvds,
3286 (u_longlong_t)healthy_tvds_mos);
3287 spa_load_note(spa, "vdev tree:");
3288 vdev_dbgmsg_print_tree(rvd, 2);
3289 if (reloading) {
3290 spa_load_failed(spa, "config was already "
3291 "provided from MOS. Aborting.");
3292 return (spa_vdev_err(rvd,
3293 VDEV_AUX_CORRUPT_DATA, EIO));
3294 }
3295 spa_load_note(spa, "spa must be reloaded using MOS "
3296 "config");
3297 return (SET_ERROR(EAGAIN));
3298 }
3299 }
3300
3301 error = spa_check_for_missing_logs(spa);
3302 if (error != 0)
3303 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM, ENXIO));
3304
3305 if (rvd->vdev_guid_sum != spa->spa_uberblock.ub_guid_sum) {
3306 spa_load_failed(spa, "uberblock guid sum doesn't match MOS "
3307 "guid sum (%llu != %llu)",
3308 (u_longlong_t)spa->spa_uberblock.ub_guid_sum,
3309 (u_longlong_t)rvd->vdev_guid_sum);
3310 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM,
3311 ENXIO));
3312 }
3313
3314 return (0);
3315 }
3316
3317 static int
3318 spa_ld_open_indirect_vdev_metadata(spa_t *spa)
3319 {
3320 int error = 0;
3321 vdev_t *rvd = spa->spa_root_vdev;
3322
3323 /*
3324 * Everything that we read before spa_remove_init() must be stored
3325 * on concreted vdevs. Therefore we do this as early as possible.
3326 */
3327 error = spa_remove_init(spa);
3328 if (error != 0) {
3329 spa_load_failed(spa, "spa_remove_init failed [error=%d]",
3330 error);
3331 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3332 }
3333
3334 /*
3335 * Retrieve information needed to condense indirect vdev mappings.
3336 */
3337 error = spa_condense_init(spa);
3338 if (error != 0) {
3339 spa_load_failed(spa, "spa_condense_init failed [error=%d]",
3340 error);
3341 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3342 }
3343
3344 return (0);
3345 }
3346
3347 static int
3348 spa_ld_check_features(spa_t *spa, boolean_t *missing_feat_writep)
3349 {
3350 int error = 0;
3351 vdev_t *rvd = spa->spa_root_vdev;
3352
3353 if (spa_version(spa) >= SPA_VERSION_FEATURES) {
3354 boolean_t missing_feat_read = B_FALSE;
3355 nvlist_t *unsup_feat, *enabled_feat;
3356
3357 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_READ,
3358 &spa->spa_feat_for_read_obj, B_TRUE) != 0) {
3359 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3360 }
3361
3362 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_WRITE,
3363 &spa->spa_feat_for_write_obj, B_TRUE) != 0) {
3364 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3365 }
3366
3367 if (spa_dir_prop(spa, DMU_POOL_FEATURE_DESCRIPTIONS,
3368 &spa->spa_feat_desc_obj, B_TRUE) != 0) {
3369 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3370 }
3371
3372 enabled_feat = fnvlist_alloc();
3373 unsup_feat = fnvlist_alloc();
3374
3375 if (!spa_features_check(spa, B_FALSE,
3376 unsup_feat, enabled_feat))
3377 missing_feat_read = B_TRUE;
3378
3379 if (spa_writeable(spa) ||
3380 spa->spa_load_state == SPA_LOAD_TRYIMPORT) {
3381 if (!spa_features_check(spa, B_TRUE,
3382 unsup_feat, enabled_feat)) {
3383 *missing_feat_writep = B_TRUE;
3384 }
3385 }
3386
3387 fnvlist_add_nvlist(spa->spa_load_info,
3388 ZPOOL_CONFIG_ENABLED_FEAT, enabled_feat);
3389
3390 if (!nvlist_empty(unsup_feat)) {
3391 fnvlist_add_nvlist(spa->spa_load_info,
3392 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat);
3393 }
3394
3395 fnvlist_free(enabled_feat);
3396 fnvlist_free(unsup_feat);
3397
3398 if (!missing_feat_read) {
3399 fnvlist_add_boolean(spa->spa_load_info,
3400 ZPOOL_CONFIG_CAN_RDONLY);
3401 }
3402
3403 /*
3404 * If the state is SPA_LOAD_TRYIMPORT, our objective is
3405 * twofold: to determine whether the pool is available for
3406 * import in read-write mode and (if it is not) whether the
3407 * pool is available for import in read-only mode. If the pool
3408 * is available for import in read-write mode, it is displayed
3409 * as available in userland; if it is not available for import
3410 * in read-only mode, it is displayed as unavailable in
3411 * userland. If the pool is available for import in read-only
3412 * mode but not read-write mode, it is displayed as unavailable
3413 * in userland with a special note that the pool is actually
3414 * available for open in read-only mode.
3415 *
3416 * As a result, if the state is SPA_LOAD_TRYIMPORT and we are
3417 * missing a feature for write, we must first determine whether
3418 * the pool can be opened read-only before returning to
3419 * userland in order to know whether to display the
3420 * abovementioned note.
3421 */
3422 if (missing_feat_read || (*missing_feat_writep &&
3423 spa_writeable(spa))) {
3424 spa_load_failed(spa, "pool uses unsupported features");
3425 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
3426 ENOTSUP));
3427 }
3428
3429 /*
3430 * Load refcounts for ZFS features from disk into an in-memory
3431 * cache during SPA initialization.
3432 */
3433 for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
3434 uint64_t refcount;
3435
3436 error = feature_get_refcount_from_disk(spa,
3437 &spa_feature_table[i], &refcount);
3438 if (error == 0) {
3439 spa->spa_feat_refcount_cache[i] = refcount;
3440 } else if (error == ENOTSUP) {
3441 spa->spa_feat_refcount_cache[i] =
3442 SPA_FEATURE_DISABLED;
3443 } else {
3444 spa_load_failed(spa, "error getting refcount "
3445 "for feature %s [error=%d]",
3446 spa_feature_table[i].fi_guid, error);
3447 return (spa_vdev_err(rvd,
3448 VDEV_AUX_CORRUPT_DATA, EIO));
3449 }
3450 }
3451 }
3452
3453 if (spa_feature_is_active(spa, SPA_FEATURE_ENABLED_TXG)) {
3454 if (spa_dir_prop(spa, DMU_POOL_FEATURE_ENABLED_TXG,
3455 &spa->spa_feat_enabled_txg_obj, B_TRUE) != 0)
3456 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3457 }
3458
3459 /*
3460 * Encryption was added before bookmark_v2, even though bookmark_v2
3461 * is now a dependency. If this pool has encryption enabled without
3462 * bookmark_v2, trigger an errata message.
3463 */
3464 if (spa_feature_is_enabled(spa, SPA_FEATURE_ENCRYPTION) &&
3465 !spa_feature_is_enabled(spa, SPA_FEATURE_BOOKMARK_V2)) {
3466 spa->spa_errata = ZPOOL_ERRATA_ZOL_8308_ENCRYPTION;
3467 }
3468
3469 return (0);
3470 }
3471
3472 static int
3473 spa_ld_load_special_directories(spa_t *spa)
3474 {
3475 int error = 0;
3476 vdev_t *rvd = spa->spa_root_vdev;
3477
3478 spa->spa_is_initializing = B_TRUE;
3479 error = dsl_pool_open(spa->spa_dsl_pool);
3480 spa->spa_is_initializing = B_FALSE;
3481 if (error != 0) {
3482 spa_load_failed(spa, "dsl_pool_open failed [error=%d]", error);
3483 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3484 }
3485
3486 return (0);
3487 }
3488
3489 static int
3490 spa_ld_get_props(spa_t *spa)
3491 {
3492 int error = 0;
3493 uint64_t obj;
3494 vdev_t *rvd = spa->spa_root_vdev;
3495
3496 /* Grab the secret checksum salt from the MOS. */
3497 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3498 DMU_POOL_CHECKSUM_SALT, 1,
3499 sizeof (spa->spa_cksum_salt.zcs_bytes),
3500 spa->spa_cksum_salt.zcs_bytes);
3501 if (error == ENOENT) {
3502 /* Generate a new salt for subsequent use */
3503 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
3504 sizeof (spa->spa_cksum_salt.zcs_bytes));
3505 } else if (error != 0) {
3506 spa_load_failed(spa, "unable to retrieve checksum salt from "
3507 "MOS [error=%d]", error);
3508 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3509 }
3510
3511 if (spa_dir_prop(spa, DMU_POOL_SYNC_BPOBJ, &obj, B_TRUE) != 0)
3512 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3513 error = bpobj_open(&spa->spa_deferred_bpobj, spa->spa_meta_objset, obj);
3514 if (error != 0) {
3515 spa_load_failed(spa, "error opening deferred-frees bpobj "
3516 "[error=%d]", error);
3517 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3518 }
3519
3520 /*
3521 * Load the bit that tells us to use the new accounting function
3522 * (raid-z deflation). If we have an older pool, this will not
3523 * be present.
3524 */
3525 error = spa_dir_prop(spa, DMU_POOL_DEFLATE, &spa->spa_deflate, B_FALSE);
3526 if (error != 0 && error != ENOENT)
3527 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3528
3529 error = spa_dir_prop(spa, DMU_POOL_CREATION_VERSION,
3530 &spa->spa_creation_version, B_FALSE);
3531 if (error != 0 && error != ENOENT)
3532 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3533
3534 /*
3535 * Load the persistent error log. If we have an older pool, this will
3536 * not be present.
3537 */
3538 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_LAST, &spa->spa_errlog_last,
3539 B_FALSE);
3540 if (error != 0 && error != ENOENT)
3541 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3542
3543 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_SCRUB,
3544 &spa->spa_errlog_scrub, B_FALSE);
3545 if (error != 0 && error != ENOENT)
3546 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3547
3548 /*
3549 * Load the history object. If we have an older pool, this
3550 * will not be present.
3551 */
3552 error = spa_dir_prop(spa, DMU_POOL_HISTORY, &spa->spa_history, B_FALSE);
3553 if (error != 0 && error != ENOENT)
3554 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3555
3556 /*
3557 * Load the per-vdev ZAP map. If we have an older pool, this will not
3558 * be present; in this case, defer its creation to a later time to
3559 * avoid dirtying the MOS this early / out of sync context. See
3560 * spa_sync_config_object.
3561 */
3562
3563 /* The sentinel is only available in the MOS config. */
3564 nvlist_t *mos_config;
3565 if (load_nvlist(spa, spa->spa_config_object, &mos_config) != 0) {
3566 spa_load_failed(spa, "unable to retrieve MOS config");
3567 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3568 }
3569
3570 error = spa_dir_prop(spa, DMU_POOL_VDEV_ZAP_MAP,
3571 &spa->spa_all_vdev_zaps, B_FALSE);
3572
3573 if (error == ENOENT) {
3574 VERIFY(!nvlist_exists(mos_config,
3575 ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
3576 spa->spa_avz_action = AVZ_ACTION_INITIALIZE;
3577 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3578 } else if (error != 0) {
3579 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3580 } else if (!nvlist_exists(mos_config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS)) {
3581 /*
3582 * An older version of ZFS overwrote the sentinel value, so
3583 * we have orphaned per-vdev ZAPs in the MOS. Defer their
3584 * destruction to later; see spa_sync_config_object.
3585 */
3586 spa->spa_avz_action = AVZ_ACTION_DESTROY;
3587 /*
3588 * We're assuming that no vdevs have had their ZAPs created
3589 * before this. Better be sure of it.
3590 */
3591 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3592 }
3593 nvlist_free(mos_config);
3594
3595 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
3596
3597 error = spa_dir_prop(spa, DMU_POOL_PROPS, &spa->spa_pool_props_object,
3598 B_FALSE);
3599 if (error && error != ENOENT)
3600 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3601
3602 if (error == 0) {
3603 uint64_t autoreplace;
3604
3605 spa_prop_find(spa, ZPOOL_PROP_BOOTFS, &spa->spa_bootfs);
3606 spa_prop_find(spa, ZPOOL_PROP_AUTOREPLACE, &autoreplace);
3607 spa_prop_find(spa, ZPOOL_PROP_DELEGATION, &spa->spa_delegation);
3608 spa_prop_find(spa, ZPOOL_PROP_FAILUREMODE, &spa->spa_failmode);
3609 spa_prop_find(spa, ZPOOL_PROP_AUTOEXPAND, &spa->spa_autoexpand);
3610 spa_prop_find(spa, ZPOOL_PROP_BOOTSIZE, &spa->spa_bootsize);
3611 spa_prop_find(spa, ZPOOL_PROP_MULTIHOST, &spa->spa_multihost);
3612 spa_prop_find(spa, ZPOOL_PROP_DEDUPDITTO,
3613 &spa->spa_dedup_ditto);
3614 spa_prop_find(spa, ZPOOL_PROP_AUTOTRIM, &spa->spa_autotrim);
3615 spa->spa_autoreplace = (autoreplace != 0);
3616 }
3617
3618 /*
3619 * If we are importing a pool with missing top-level vdevs,
3620 * we enforce that the pool doesn't panic or get suspended on
3621 * error since the likelihood of missing data is extremely high.
3622 */
3623 if (spa->spa_missing_tvds > 0 &&
3624 spa->spa_failmode != ZIO_FAILURE_MODE_CONTINUE &&
3625 spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3626 spa_load_note(spa, "forcing failmode to 'continue' "
3627 "as some top level vdevs are missing");
3628 spa->spa_failmode = ZIO_FAILURE_MODE_CONTINUE;
3629 }
3630
3631 return (0);
3632 }
3633
3634 static int
3635 spa_ld_open_aux_vdevs(spa_t *spa, spa_import_type_t type)
3636 {
3637 int error = 0;
3638 vdev_t *rvd = spa->spa_root_vdev;
3639
3640 /*
3641 * If we're assembling the pool from the split-off vdevs of
3642 * an existing pool, we don't want to attach the spares & cache
3643 * devices.
3644 */
3645
3646 /*
3647 * Load any hot spares for this pool.
3648 */
3649 error = spa_dir_prop(spa, DMU_POOL_SPARES, &spa->spa_spares.sav_object,
3650 B_FALSE);
3651 if (error != 0 && error != ENOENT)
3652 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3653 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
3654 ASSERT(spa_version(spa) >= SPA_VERSION_SPARES);
3655 if (load_nvlist(spa, spa->spa_spares.sav_object,
3656 &spa->spa_spares.sav_config) != 0) {
3657 spa_load_failed(spa, "error loading spares nvlist");
3658 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3659 }
3660
3661 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3662 spa_load_spares(spa);
3663 spa_config_exit(spa, SCL_ALL, FTAG);
3664 } else if (error == 0) {
3665 spa->spa_spares.sav_sync = B_TRUE;
3666 }
3667
3668 /*
3669 * Load any level 2 ARC devices for this pool.
3670 */
3671 error = spa_dir_prop(spa, DMU_POOL_L2CACHE,
3672 &spa->spa_l2cache.sav_object, B_FALSE);
3673 if (error != 0 && error != ENOENT)
3674 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3675 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
3676 ASSERT(spa_version(spa) >= SPA_VERSION_L2CACHE);
3677 if (load_nvlist(spa, spa->spa_l2cache.sav_object,
3678 &spa->spa_l2cache.sav_config) != 0) {
3679 spa_load_failed(spa, "error loading l2cache nvlist");
3680 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3681 }
3682
3683 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3684 spa_load_l2cache(spa);
3685 spa_config_exit(spa, SCL_ALL, FTAG);
3686 } else if (error == 0) {
3687 spa->spa_l2cache.sav_sync = B_TRUE;
3688 }
3689
3690 return (0);
3691 }
3692
3693 static int
3694 spa_ld_load_vdev_metadata(spa_t *spa)
3695 {
3696 int error = 0;
3697 vdev_t *rvd = spa->spa_root_vdev;
3698
3699 /*
3700 * If the 'multihost' property is set, then never allow a pool to
3701 * be imported when the system hostid is zero. The exception to
3702 * this rule is zdb which is always allowed to access pools.
3703 */
3704 if (spa_multihost(spa) && spa_get_hostid() == 0 &&
3705 (spa->spa_import_flags & ZFS_IMPORT_SKIP_MMP) == 0) {
3706 fnvlist_add_uint64(spa->spa_load_info,
3707 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_NO_HOSTID);
3708 return (spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO));
3709 }
3710
3711 /*
3712 * If the 'autoreplace' property is set, then post a resource notifying
3713 * the ZFS DE that it should not issue any faults for unopenable
3714 * devices. We also iterate over the vdevs, and post a sysevent for any
3715 * unopenable vdevs so that the normal autoreplace handler can take
3716 * over.
3717 */
3718 if (spa->spa_autoreplace && spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3719 spa_check_removed(spa->spa_root_vdev);
3720 /*
3721 * For the import case, this is done in spa_import(), because
3722 * at this point we're using the spare definitions from
3723 * the MOS config, not necessarily from the userland config.
3724 */
3725 if (spa->spa_load_state != SPA_LOAD_IMPORT) {
3726 spa_aux_check_removed(&spa->spa_spares);
3727 spa_aux_check_removed(&spa->spa_l2cache);
3728 }
3729 }
3730
3731 /*
3732 * Load the vdev metadata such as metaslabs, DTLs, spacemap object, etc.
3733 */
3734 error = vdev_load(rvd);
3735 if (error != 0) {
3736 spa_load_failed(spa, "vdev_load failed [error=%d]", error);
3737 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3738 }
3739
3740 error = spa_ld_log_spacemaps(spa);
3741 if (error != 0) {
3742 spa_load_failed(spa, "spa_ld_log_sm_data failed [error=%d]",
3743 error);
3744 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3745 }
3746
3747 /*
3748 * Propagate the leaf DTLs we just loaded all the way up the vdev tree.
3749 */
3750 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3751 vdev_dtl_reassess(rvd, 0, 0, B_FALSE);
3752 spa_config_exit(spa, SCL_ALL, FTAG);
3753
3754 return (0);
3755 }
3756
3757 static int
3758 spa_ld_load_dedup_tables(spa_t *spa)
3759 {
3760 int error = 0;
3761 vdev_t *rvd = spa->spa_root_vdev;
3762
3763 error = ddt_load(spa);
3764 if (error != 0) {
3765 spa_load_failed(spa, "ddt_load failed [error=%d]", error);
3766 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3767 }
3768
3769 return (0);
3770 }
3771
3772 static int
3773 spa_ld_verify_logs(spa_t *spa, spa_import_type_t type, char **ereport)
3774 {
3775 vdev_t *rvd = spa->spa_root_vdev;
3776
3777 if (type != SPA_IMPORT_ASSEMBLE && spa_writeable(spa)) {
3778 boolean_t missing = spa_check_logs(spa);
3779 if (missing) {
3780 if (spa->spa_missing_tvds != 0) {
3781 spa_load_note(spa, "spa_check_logs failed "
3782 "so dropping the logs");
3783 } else {
3784 *ereport = FM_EREPORT_ZFS_LOG_REPLAY;
3785 spa_load_failed(spa, "spa_check_logs failed");
3786 return (spa_vdev_err(rvd, VDEV_AUX_BAD_LOG,
3787 ENXIO));
3788 }
3789 }
3790 }
3791
3792 return (0);
3793 }
3794
3795 static int
3796 spa_ld_verify_pool_data(spa_t *spa)
3797 {
3798 int error = 0;
3799 vdev_t *rvd = spa->spa_root_vdev;
3800
3801 /*
3802 * We've successfully opened the pool, verify that we're ready
3803 * to start pushing transactions.
3804 */
3805 if (spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3806 error = spa_load_verify(spa);
3807 if (error != 0) {
3808 spa_load_failed(spa, "spa_load_verify failed "
3809 "[error=%d]", error);
3810 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3811 error));
3812 }
3813 }
3814
3815 return (0);
3816 }
3817
3818 static void
3819 spa_ld_claim_log_blocks(spa_t *spa)
3820 {
3821 dmu_tx_t *tx;
3822 dsl_pool_t *dp = spa_get_dsl(spa);
3823
3824 /*
3825 * Claim log blocks that haven't been committed yet.
3826 * This must all happen in a single txg.
3827 * Note: spa_claim_max_txg is updated by spa_claim_notify(),
3828 * invoked from zil_claim_log_block()'s i/o done callback.
3829 * Price of rollback is that we abandon the log.
3830 */
3831 spa->spa_claiming = B_TRUE;
3832
3833 tx = dmu_tx_create_assigned(dp, spa_first_txg(spa));
3834 (void) dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
3835 zil_claim, tx, DS_FIND_CHILDREN);
3836 dmu_tx_commit(tx);
3837
3838 spa->spa_claiming = B_FALSE;
3839
3840 spa_set_log_state(spa, SPA_LOG_GOOD);
3841 }
3842
3843 static void
3844 spa_ld_check_for_config_update(spa_t *spa, uint64_t config_cache_txg,
3845 boolean_t update_config_cache)
3846 {
3847 vdev_t *rvd = spa->spa_root_vdev;
3848 int need_update = B_FALSE;
3849
3850 /*
3851 * If the config cache is stale, or we have uninitialized
3852 * metaslabs (see spa_vdev_add()), then update the config.
3853 *
3854 * If this is a verbatim import, trust the current
3855 * in-core spa_config and update the disk labels.
3856 */
3857 if (update_config_cache || config_cache_txg != spa->spa_config_txg ||
3858 spa->spa_load_state == SPA_LOAD_IMPORT ||
3859 spa->spa_load_state == SPA_LOAD_RECOVER ||
3860 (spa->spa_import_flags & ZFS_IMPORT_VERBATIM))
3861 need_update = B_TRUE;
3862
3863 for (int c = 0; c < rvd->vdev_children; c++)
3864 if (rvd->vdev_child[c]->vdev_ms_array == 0)
3865 need_update = B_TRUE;
3866
3867 /*
3868 * Update the config cache asychronously in case we're the
3869 * root pool, in which case the config cache isn't writable yet.
3870 */
3871 if (need_update)
3872 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
3873 }
3874
3875 static void
3876 spa_ld_prepare_for_reload(spa_t *spa)
3877 {
3878 int mode = spa->spa_mode;
3879 int async_suspended = spa->spa_async_suspended;
3880
3881 spa_unload(spa);
3882 spa_deactivate(spa);
3883 spa_activate(spa, mode);
3884
3885 /*
3886 * We save the value of spa_async_suspended as it gets reset to 0 by
3887 * spa_unload(). We want to restore it back to the original value before
3888 * returning as we might be calling spa_async_resume() later.
3889 */
3890 spa->spa_async_suspended = async_suspended;
3891 }
3892
3893 static int
3894 spa_ld_read_checkpoint_txg(spa_t *spa)
3895 {
3896 uberblock_t checkpoint;
3897 int error = 0;
3898
3899 ASSERT0(spa->spa_checkpoint_txg);
3900 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3901
3902 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3903 DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
3904 sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
3905
3906 if (error == ENOENT)
3907 return (0);
3908
3909 if (error != 0)
3910 return (error);
3911
3912 ASSERT3U(checkpoint.ub_txg, !=, 0);
3913 ASSERT3U(checkpoint.ub_checkpoint_txg, !=, 0);
3914 ASSERT3U(checkpoint.ub_timestamp, !=, 0);
3915 spa->spa_checkpoint_txg = checkpoint.ub_txg;
3916 spa->spa_checkpoint_info.sci_timestamp = checkpoint.ub_timestamp;
3917
3918 return (0);
3919 }
3920
3921 static int
3922 spa_ld_mos_init(spa_t *spa, spa_import_type_t type)
3923 {
3924 int error = 0;
3925
3926 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3927 ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
3928
3929 /*
3930 * Never trust the config that is provided unless we are assembling
3931 * a pool following a split.
3932 * This means don't trust blkptrs and the vdev tree in general. This
3933 * also effectively puts the spa in read-only mode since
3934 * spa_writeable() checks for spa_trust_config to be true.
3935 * We will later load a trusted config from the MOS.
3936 */
3937 if (type != SPA_IMPORT_ASSEMBLE)
3938 spa->spa_trust_config = B_FALSE;
3939
3940 /*
3941 * Parse the config provided to create a vdev tree.
3942 */
3943 error = spa_ld_parse_config(spa, type);
3944 if (error != 0)
3945 return (error);
3946
3947 spa_import_progress_add(spa);
3948
3949 /*
3950 * Now that we have the vdev tree, try to open each vdev. This involves
3951 * opening the underlying physical device, retrieving its geometry and
3952 * probing the vdev with a dummy I/O. The state of each vdev will be set
3953 * based on the success of those operations. After this we'll be ready
3954 * to read from the vdevs.
3955 */
3956 error = spa_ld_open_vdevs(spa);
3957 if (error != 0)
3958 return (error);
3959
3960 /*
3961 * Read the label of each vdev and make sure that the GUIDs stored
3962 * there match the GUIDs in the config provided.
3963 * If we're assembling a new pool that's been split off from an
3964 * existing pool, the labels haven't yet been updated so we skip
3965 * validation for now.
3966 */
3967 if (type != SPA_IMPORT_ASSEMBLE) {
3968 error = spa_ld_validate_vdevs(spa);
3969 if (error != 0)
3970 return (error);
3971 }
3972
3973 /*
3974 * Read all vdev labels to find the best uberblock (i.e. latest,
3975 * unless spa_load_max_txg is set) and store it in spa_uberblock. We
3976 * get the list of features required to read blkptrs in the MOS from
3977 * the vdev label with the best uberblock and verify that our version
3978 * of zfs supports them all.
3979 */
3980 error = spa_ld_select_uberblock(spa, type);
3981 if (error != 0)
3982 return (error);
3983
3984 /*
3985 * Pass that uberblock to the dsl_pool layer which will open the root
3986 * blkptr. This blkptr points to the latest version of the MOS and will
3987 * allow us to read its contents.
3988 */
3989 error = spa_ld_open_rootbp(spa);
3990 if (error != 0)
3991 return (error);
3992
3993 return (0);
3994 }
3995
3996 static int
3997 spa_ld_checkpoint_rewind(spa_t *spa)
3998 {
3999 uberblock_t checkpoint;
4000 int error = 0;
4001
4002 ASSERT(MUTEX_HELD(&spa_namespace_lock));
4003 ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
4004
4005 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
4006 DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
4007 sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
4008
4009 if (error != 0) {
4010 spa_load_failed(spa, "unable to retrieve checkpointed "
4011 "uberblock from the MOS config [error=%d]", error);
4012
4013 if (error == ENOENT)
4014 error = ZFS_ERR_NO_CHECKPOINT;
4015
4016 return (error);
4017 }
4018
4019 ASSERT3U(checkpoint.ub_txg, <, spa->spa_uberblock.ub_txg);
4020 ASSERT3U(checkpoint.ub_txg, ==, checkpoint.ub_checkpoint_txg);
4021
4022 /*
4023 * We need to update the txg and timestamp of the checkpointed
4024 * uberblock to be higher than the latest one. This ensures that
4025 * the checkpointed uberblock is selected if we were to close and
4026 * reopen the pool right after we've written it in the vdev labels.
4027 * (also see block comment in vdev_uberblock_compare)
4028 */
4029 checkpoint.ub_txg = spa->spa_uberblock.ub_txg + 1;
4030 checkpoint.ub_timestamp = gethrestime_sec();
4031
4032 /*
4033 * Set current uberblock to be the checkpointed uberblock.
4034 */
4035 spa->spa_uberblock = checkpoint;
4036
4037 /*
4038 * If we are doing a normal rewind, then the pool is open for
4039 * writing and we sync the "updated" checkpointed uberblock to
4040 * disk. Once this is done, we've basically rewound the whole
4041 * pool and there is no way back.
4042 *
4043 * There are cases when we don't want to attempt and sync the
4044 * checkpointed uberblock to disk because we are opening a
4045 * pool as read-only. Specifically, verifying the checkpointed
4046 * state with zdb, and importing the checkpointed state to get
4047 * a "preview" of its content.
4048 */
4049 if (spa_writeable(spa)) {
4050 vdev_t *rvd = spa->spa_root_vdev;
4051
4052 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4053 vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
4054 int svdcount = 0;
4055 int children = rvd->vdev_children;
4056 int c0 = spa_get_random(children);
4057
4058 for (int c = 0; c < children; c++) {
4059 vdev_t *vd = rvd->vdev_child[(c0 + c) % children];
4060
4061 /* Stop when revisiting the first vdev */
4062 if (c > 0 && svd[0] == vd)
4063 break;
4064
4065 if (vd->vdev_ms_array == 0 || vd->vdev_islog ||
4066 !vdev_is_concrete(vd))
4067 continue;
4068
4069 svd[svdcount++] = vd;
4070 if (svdcount == SPA_SYNC_MIN_VDEVS)
4071 break;
4072 }
4073 error = vdev_config_sync(svd, svdcount, spa->spa_first_txg);
4074 if (error == 0)
4075 spa->spa_last_synced_guid = rvd->vdev_guid;
4076 spa_config_exit(spa, SCL_ALL, FTAG);
4077
4078 if (error != 0) {
4079 spa_load_failed(spa, "failed to write checkpointed "
4080 "uberblock to the vdev labels [error=%d]", error);
4081 return (error);
4082 }
4083 }
4084
4085 return (0);
4086 }
4087
4088 static int
4089 spa_ld_mos_with_trusted_config(spa_t *spa, spa_import_type_t type,
4090 boolean_t *update_config_cache)
4091 {
4092 int error;
4093
4094 /*
4095 * Parse the config for pool, open and validate vdevs,
4096 * select an uberblock, and use that uberblock to open
4097 * the MOS.
4098 */
4099 error = spa_ld_mos_init(spa, type);
4100 if (error != 0)
4101 return (error);
4102
4103 /*
4104 * Retrieve the trusted config stored in the MOS and use it to create
4105 * a new, exact version of the vdev tree, then reopen all vdevs.
4106 */
4107 error = spa_ld_trusted_config(spa, type, B_FALSE);
4108 if (error == EAGAIN) {
4109 if (update_config_cache != NULL)
4110 *update_config_cache = B_TRUE;
4111
4112 /*
4113 * Redo the loading process with the trusted config if it is
4114 * too different from the untrusted config.
4115 */
4116 spa_ld_prepare_for_reload(spa);
4117 spa_load_note(spa, "RELOADING");
4118 error = spa_ld_mos_init(spa, type);
4119 if (error != 0)
4120 return (error);
4121
4122 error = spa_ld_trusted_config(spa, type, B_TRUE);
4123 if (error != 0)
4124 return (error);
4125
4126 } else if (error != 0) {
4127 return (error);
4128 }
4129
4130 return (0);
4131 }
4132
4133 /*
4134 * Load an existing storage pool, using the config provided. This config
4135 * describes which vdevs are part of the pool and is later validated against
4136 * partial configs present in each vdev's label and an entire copy of the
4137 * config stored in the MOS.
4138 */
4139 static int
4140 spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport)
4141 {
4142 int error = 0;
4143 boolean_t missing_feat_write = B_FALSE;
4144 boolean_t checkpoint_rewind =
4145 (spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
4146 boolean_t update_config_cache = B_FALSE;
4147
4148 ASSERT(MUTEX_HELD(&spa_namespace_lock));
4149 ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
4150
4151 spa_load_note(spa, "LOADING");
4152
4153 error = spa_ld_mos_with_trusted_config(spa, type, &update_config_cache);
4154 if (error != 0)
4155 return (error);
4156
4157 /*
4158 * If we are rewinding to the checkpoint then we need to repeat
4159 * everything we've done so far in this function but this time
4160 * selecting the checkpointed uberblock and using that to open
4161 * the MOS.
4162 */
4163 if (checkpoint_rewind) {
4164 /*
4165 * If we are rewinding to the checkpoint update config cache
4166 * anyway.
4167 */
4168 update_config_cache = B_TRUE;
4169
4170 /*
4171 * Extract the checkpointed uberblock from the current MOS
4172 * and use this as the pool's uberblock from now on. If the
4173 * pool is imported as writeable we also write the checkpoint
4174 * uberblock to the labels, making the rewind permanent.
4175 */
4176 error = spa_ld_checkpoint_rewind(spa);
4177 if (error != 0)
4178 return (error);
4179
4180 /*
4181 * Redo the loading process process again with the
4182 * checkpointed uberblock.
4183 */
4184 spa_ld_prepare_for_reload(spa);
4185 spa_load_note(spa, "LOADING checkpointed uberblock");
4186 error = spa_ld_mos_with_trusted_config(spa, type, NULL);
4187 if (error != 0)
4188 return (error);
4189 }
4190
4191 /*
4192 * Retrieve the checkpoint txg if the pool has a checkpoint.
4193 */
4194 error = spa_ld_read_checkpoint_txg(spa);
4195 if (error != 0)
4196 return (error);
4197
4198 /*
4199 * Retrieve the mapping of indirect vdevs. Those vdevs were removed
4200 * from the pool and their contents were re-mapped to other vdevs. Note
4201 * that everything that we read before this step must have been
4202 * rewritten on concrete vdevs after the last device removal was
4203 * initiated. Otherwise we could be reading from indirect vdevs before
4204 * we have loaded their mappings.
4205 */
4206 error = spa_ld_open_indirect_vdev_metadata(spa);
4207 if (error != 0)
4208 return (error);
4209
4210 /*
4211 * Retrieve the full list of active features from the MOS and check if
4212 * they are all supported.
4213 */
4214 error = spa_ld_check_features(spa, &missing_feat_write);
4215 if (error != 0)
4216 return (error);
4217
4218 /*
4219 * Load several special directories from the MOS needed by the dsl_pool
4220 * layer.
4221 */
4222 error = spa_ld_load_special_directories(spa);
4223 if (error != 0)
4224 return (error);
4225
4226 /*
4227 * Retrieve pool properties from the MOS.
4228 */
4229 error = spa_ld_get_props(spa);
4230 if (error != 0)
4231 return (error);
4232
4233 /*
4234 * Retrieve the list of auxiliary devices - cache devices and spares -
4235 * and open them.
4236 */
4237 error = spa_ld_open_aux_vdevs(spa, type);
4238 if (error != 0)
4239 return (error);
4240
4241 /*
4242 * Load the metadata for all vdevs. Also check if unopenable devices
4243 * should be autoreplaced.
4244 */
4245 error = spa_ld_load_vdev_metadata(spa);
4246 if (error != 0)
4247 return (error);
4248
4249 error = spa_ld_load_dedup_tables(spa);
4250 if (error != 0)
4251 return (error);
4252
4253 /*
4254 * Verify the logs now to make sure we don't have any unexpected errors
4255 * when we claim log blocks later.
4256 */
4257 error = spa_ld_verify_logs(spa, type, ereport);
4258 if (error != 0)
4259 return (error);
4260
4261 if (missing_feat_write) {
4262 ASSERT(spa->spa_load_state == SPA_LOAD_TRYIMPORT);
4263
4264 /*
4265 * At this point, we know that we can open the pool in
4266 * read-only mode but not read-write mode. We now have enough
4267 * information and can return to userland.
4268 */
4269 return (spa_vdev_err(spa->spa_root_vdev, VDEV_AUX_UNSUP_FEAT,
4270 ENOTSUP));
4271 }
4272
4273 /*
4274 * Traverse the last txgs to make sure the pool was left off in a safe
4275 * state. When performing an extreme rewind, we verify the whole pool,
4276 * which can take a very long time.
4277 */
4278 error = spa_ld_verify_pool_data(spa);
4279 if (error != 0)
4280 return (error);
4281
4282 /*
4283 * Calculate the deflated space for the pool. This must be done before
4284 * we write anything to the pool because we'd need to update the space
4285 * accounting using the deflated sizes.
4286 */
4287 spa_update_dspace(spa);
4288
4289 /*
4290 * We have now retrieved all the information we needed to open the
4291 * pool. If we are importing the pool in read-write mode, a few
4292 * additional steps must be performed to finish the import.
4293 */
4294 if (spa_writeable(spa) && (spa->spa_load_state == SPA_LOAD_RECOVER ||
4295 spa->spa_load_max_txg == UINT64_MAX)) {
4296 uint64_t config_cache_txg = spa->spa_config_txg;
4297
4298 ASSERT(spa->spa_load_state != SPA_LOAD_TRYIMPORT);
4299
4300 /*
4301 * In case of a checkpoint rewind, log the original txg
4302 * of the checkpointed uberblock.
4303 */
4304 if (checkpoint_rewind) {
4305 spa_history_log_internal(spa, "checkpoint rewind",
4306 NULL, "rewound state to txg=%llu",
4307 (u_longlong_t)spa->spa_uberblock.ub_checkpoint_txg);
4308 }
4309
4310 /*
4311 * Traverse the ZIL and claim all blocks.
4312 */
4313 spa_ld_claim_log_blocks(spa);
4314
4315 /*
4316 * Kick-off the syncing thread.
4317 */
4318 spa->spa_sync_on = B_TRUE;
4319 txg_sync_start(spa->spa_dsl_pool);
4320 mmp_thread_start(spa);
4321
4322 /*
4323 * Wait for all claims to sync. We sync up to the highest
4324 * claimed log block birth time so that claimed log blocks
4325 * don't appear to be from the future. spa_claim_max_txg
4326 * will have been set for us by ZIL traversal operations
4327 * performed above.
4328 */
4329 txg_wait_synced(spa->spa_dsl_pool, spa->spa_claim_max_txg);
4330
4331 /*
4332 * Check if we need to request an update of the config. On the
4333 * next sync, we would update the config stored in vdev labels
4334 * and the cachefile (by default /etc/zfs/zpool.cache).
4335 */
4336 spa_ld_check_for_config_update(spa, config_cache_txg,
4337 update_config_cache);
4338
4339 /*
4340 * Check all DTLs to see if anything needs resilvering.
4341 */
4342 if (!dsl_scan_resilvering(spa->spa_dsl_pool) &&
4343 vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL))
4344 spa_async_request(spa, SPA_ASYNC_RESILVER);
4345
4346 /*
4347 * Log the fact that we booted up (so that we can detect if
4348 * we rebooted in the middle of an operation).
4349 */
4350 spa_history_log_version(spa, "open");
4351
4352 spa_restart_removal(spa);
4353 spa_spawn_aux_threads(spa);
4354
4355 /*
4356 * Delete any inconsistent datasets.
4357 *
4358 * Note:
4359 * Since we may be issuing deletes for clones here,
4360 * we make sure to do so after we've spawned all the
4361 * auxiliary threads above (from which the livelist
4362 * deletion zthr is part of).
4363 */
4364 (void) dmu_objset_find(spa_name(spa),
4365 dsl_destroy_inconsistent, NULL, DS_FIND_CHILDREN);
4366
4367 /*
4368 * Clean up any stale temporary dataset userrefs.
4369 */
4370 dsl_pool_clean_tmp_userrefs(spa->spa_dsl_pool);
4371
4372 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4373 vdev_initialize_restart(spa->spa_root_vdev);
4374 vdev_trim_restart(spa->spa_root_vdev);
4375 vdev_autotrim_restart(spa);
4376 spa_config_exit(spa, SCL_CONFIG, FTAG);
4377 }
4378
4379 spa_import_progress_remove(spa);
4380 spa_async_request(spa, SPA_ASYNC_L2CACHE_REBUILD);
4381
4382 spa_load_note(spa, "LOADED");
4383
4384 return (0);
4385 }
4386
4387 static int
4388 spa_load_retry(spa_t *spa, spa_load_state_t state)
4389 {
4390 int mode = spa->spa_mode;
4391
4392 spa_unload(spa);
4393 spa_deactivate(spa);
4394
4395 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg - 1;
4396
4397 spa_activate(spa, mode);
4398 spa_async_suspend(spa);
4399
4400 spa_load_note(spa, "spa_load_retry: rewind, max txg: %llu",
4401 (u_longlong_t)spa->spa_load_max_txg);
4402
4403 return (spa_load(spa, state, SPA_IMPORT_EXISTING));
4404 }
4405
4406 /*
4407 * If spa_load() fails this function will try loading prior txg's. If
4408 * 'state' is SPA_LOAD_RECOVER and one of these loads succeeds the pool
4409 * will be rewound to that txg. If 'state' is not SPA_LOAD_RECOVER this
4410 * function will not rewind the pool and will return the same error as
4411 * spa_load().
4412 */
4413 static int
4414 spa_load_best(spa_t *spa, spa_load_state_t state, uint64_t max_request,
4415 int rewind_flags)
4416 {
4417 nvlist_t *loadinfo = NULL;
4418 nvlist_t *config = NULL;
4419 int load_error, rewind_error;
4420 uint64_t safe_rewind_txg;
4421 uint64_t min_txg;
4422
4423 if (spa->spa_load_txg && state == SPA_LOAD_RECOVER) {
4424 spa->spa_load_max_txg = spa->spa_load_txg;
4425 spa_set_log_state(spa, SPA_LOG_CLEAR);
4426 } else {
4427 spa->spa_load_max_txg = max_request;
4428 if (max_request != UINT64_MAX)
4429 spa->spa_extreme_rewind = B_TRUE;
4430 }
4431
4432 load_error = rewind_error = spa_load(spa, state, SPA_IMPORT_EXISTING);
4433 if (load_error == 0)
4434 return (0);
4435 if (load_error == ZFS_ERR_NO_CHECKPOINT) {
4436 /*
4437 * When attempting checkpoint-rewind on a pool with no
4438 * checkpoint, we should not attempt to load uberblocks
4439 * from previous txgs when spa_load fails.
4440 */
4441 ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
4442 spa_import_progress_remove(spa);
4443 return (load_error);
4444 }
4445
4446 if (spa->spa_root_vdev != NULL)
4447 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4448
4449 spa->spa_last_ubsync_txg = spa->spa_uberblock.ub_txg;
4450 spa->spa_last_ubsync_txg_ts = spa->spa_uberblock.ub_timestamp;
4451
4452 if (rewind_flags & ZPOOL_NEVER_REWIND) {
4453 nvlist_free(config);
4454 spa_import_progress_remove(spa);
4455 return (load_error);
4456 }
4457
4458 if (state == SPA_LOAD_RECOVER) {
4459 /* Price of rolling back is discarding txgs, including log */
4460 spa_set_log_state(spa, SPA_LOG_CLEAR);
4461 } else {
4462 /*
4463 * If we aren't rolling back save the load info from our first
4464 * import attempt so that we can restore it after attempting
4465 * to rewind.
4466 */
4467 loadinfo = spa->spa_load_info;
4468 spa->spa_load_info = fnvlist_alloc();
4469 }
4470
4471 spa->spa_load_max_txg = spa->spa_last_ubsync_txg;
4472 safe_rewind_txg = spa->spa_last_ubsync_txg - TXG_DEFER_SIZE;
4473 min_txg = (rewind_flags & ZPOOL_EXTREME_REWIND) ?
4474 TXG_INITIAL : safe_rewind_txg;
4475
4476 /*
4477 * Continue as long as we're finding errors, we're still within
4478 * the acceptable rewind range, and we're still finding uberblocks
4479 */
4480 while (rewind_error && spa->spa_uberblock.ub_txg >= min_txg &&
4481 spa->spa_uberblock.ub_txg <= spa->spa_load_max_txg) {
4482 if (spa->spa_load_max_txg < safe_rewind_txg)
4483 spa->spa_extreme_rewind = B_TRUE;
4484 rewind_error = spa_load_retry(spa, state);
4485 }
4486
4487 spa->spa_extreme_rewind = B_FALSE;
4488 spa->spa_load_max_txg = UINT64_MAX;
4489
4490 if (config && (rewind_error || state != SPA_LOAD_RECOVER))
4491 spa_config_set(spa, config);
4492 else
4493 nvlist_free(config);
4494
4495 if (state == SPA_LOAD_RECOVER) {
4496 ASSERT3P(loadinfo, ==, NULL);
4497 spa_import_progress_remove(spa);
4498 return (rewind_error);
4499 } else {
4500 /* Store the rewind info as part of the initial load info */
4501 fnvlist_add_nvlist(loadinfo, ZPOOL_CONFIG_REWIND_INFO,
4502 spa->spa_load_info);
4503
4504 /* Restore the initial load info */
4505 fnvlist_free(spa->spa_load_info);
4506 spa->spa_load_info = loadinfo;
4507
4508 spa_import_progress_remove(spa);
4509 return (load_error);
4510 }
4511 }
4512
4513 /*
4514 * Pool Open/Import
4515 *
4516 * The import case is identical to an open except that the configuration is sent
4517 * down from userland, instead of grabbed from the configuration cache. For the
4518 * case of an open, the pool configuration will exist in the
4519 * POOL_STATE_UNINITIALIZED state.
4520 *
4521 * The stats information (gen/count/ustats) is used to gather vdev statistics at
4522 * the same time open the pool, without having to keep around the spa_t in some
4523 * ambiguous state.
4524 */
4525 static int
4526 spa_open_common(const char *pool, spa_t **spapp, void *tag, nvlist_t *nvpolicy,
4527 nvlist_t **config)
4528 {
4529 spa_t *spa;
4530 spa_load_state_t state = SPA_LOAD_OPEN;
4531 int error;
4532 int locked = B_FALSE;
4533
4534 *spapp = NULL;
4535
4536 /*
4537 * As disgusting as this is, we need to support recursive calls to this
4538 * function because dsl_dir_open() is called during spa_load(), and ends
4539 * up calling spa_open() again. The real fix is to figure out how to
4540 * avoid dsl_dir_open() calling this in the first place.
4541 */
4542 if (mutex_owner(&spa_namespace_lock) != curthread) {
4543 mutex_enter(&spa_namespace_lock);
4544 locked = B_TRUE;
4545 }
4546
4547 if ((spa = spa_lookup(pool)) == NULL) {
4548 if (locked)
4549 mutex_exit(&spa_namespace_lock);
4550 return (SET_ERROR(ENOENT));
4551 }
4552
4553 if (spa->spa_state == POOL_STATE_UNINITIALIZED) {
4554 zpool_load_policy_t policy;
4555
4556 zpool_get_load_policy(nvpolicy ? nvpolicy : spa->spa_config,
4557 &policy);
4558 if (policy.zlp_rewind & ZPOOL_DO_REWIND)
4559 state = SPA_LOAD_RECOVER;
4560
4561 spa_activate(spa, spa_mode_global);
4562
4563 if (state != SPA_LOAD_RECOVER)
4564 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
4565 spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
4566
4567 zfs_dbgmsg("spa_open_common: opening %s", pool);
4568 error = spa_load_best(spa, state, policy.zlp_txg,
4569 policy.zlp_rewind);
4570
4571 if (error == EBADF) {
4572 /*
4573 * If vdev_validate() returns failure (indicated by
4574 * EBADF), it indicates that one of the vdevs indicates
4575 * that the pool has been exported or destroyed. If
4576 * this is the case, the config cache is out of sync and
4577 * we should remove the pool from the namespace.
4578 */
4579 spa_unload(spa);
4580 spa_deactivate(spa);
4581 spa_write_cachefile(spa, B_TRUE, B_TRUE);
4582 spa_remove(spa);
4583 if (locked)
4584 mutex_exit(&spa_namespace_lock);
4585 return (SET_ERROR(ENOENT));
4586 }
4587
4588 if (error) {
4589 /*
4590 * We can't open the pool, but we still have useful
4591 * information: the state of each vdev after the
4592 * attempted vdev_open(). Return this to the user.
4593 */
4594 if (config != NULL && spa->spa_config) {
4595 VERIFY(nvlist_dup(spa->spa_config, config,
4596 KM_SLEEP) == 0);
4597 VERIFY(nvlist_add_nvlist(*config,
4598 ZPOOL_CONFIG_LOAD_INFO,
4599 spa->spa_load_info) == 0);
4600 }
4601 spa_unload(spa);
4602 spa_deactivate(spa);
4603 spa->spa_last_open_failed = error;
4604 if (locked)
4605 mutex_exit(&spa_namespace_lock);
4606 *spapp = NULL;
4607 return (error);
4608 }
4609 }
4610
4611 spa_open_ref(spa, tag);
4612
4613 if (config != NULL)
4614 *config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4615
4616 /*
4617 * If we've recovered the pool, pass back any information we
4618 * gathered while doing the load.
4619 */
4620 if (state == SPA_LOAD_RECOVER) {
4621 VERIFY(nvlist_add_nvlist(*config, ZPOOL_CONFIG_LOAD_INFO,
4622 spa->spa_load_info) == 0);
4623 }
4624
4625 if (locked) {
4626 spa->spa_last_open_failed = 0;
4627 spa->spa_last_ubsync_txg = 0;
4628 spa->spa_load_txg = 0;
4629 mutex_exit(&spa_namespace_lock);
4630 }
4631
4632 *spapp = spa;
4633
4634 return (0);
4635 }
4636
4637 int
4638 spa_open_rewind(const char *name, spa_t **spapp, void *tag, nvlist_t *policy,
4639 nvlist_t **config)
4640 {
4641 return (spa_open_common(name, spapp, tag, policy, config));
4642 }
4643
4644 int
4645 spa_open(const char *name, spa_t **spapp, void *tag)
4646 {
4647 return (spa_open_common(name, spapp, tag, NULL, NULL));
4648 }
4649
4650 /*
4651 * Lookup the given spa_t, incrementing the inject count in the process,
4652 * preventing it from being exported or destroyed.
4653 */
4654 spa_t *
4655 spa_inject_addref(char *name)
4656 {
4657 spa_t *spa;
4658
4659 mutex_enter(&spa_namespace_lock);
4660 if ((spa = spa_lookup(name)) == NULL) {
4661 mutex_exit(&spa_namespace_lock);
4662 return (NULL);
4663 }
4664 spa->spa_inject_ref++;
4665 mutex_exit(&spa_namespace_lock);
4666
4667 return (spa);
4668 }
4669
4670 void
4671 spa_inject_delref(spa_t *spa)
4672 {
4673 mutex_enter(&spa_namespace_lock);
4674 spa->spa_inject_ref--;
4675 mutex_exit(&spa_namespace_lock);
4676 }
4677
4678 /*
4679 * Add spares device information to the nvlist.
4680 */
4681 static void
4682 spa_add_spares(spa_t *spa, nvlist_t *config)
4683 {
4684 nvlist_t **spares;
4685 uint_t i, nspares;
4686 nvlist_t *nvroot;
4687 uint64_t guid;
4688 vdev_stat_t *vs;
4689 uint_t vsc;
4690 uint64_t pool;
4691
4692 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4693
4694 if (spa->spa_spares.sav_count == 0)
4695 return;
4696
4697 VERIFY(nvlist_lookup_nvlist(config,
4698 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4699 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
4700 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
4701 if (nspares != 0) {
4702 VERIFY(nvlist_add_nvlist_array(nvroot,
4703 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
4704 VERIFY(nvlist_lookup_nvlist_array(nvroot,
4705 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
4706
4707 /*
4708 * Go through and find any spares which have since been
4709 * repurposed as an active spare. If this is the case, update
4710 * their status appropriately.
4711 */
4712 for (i = 0; i < nspares; i++) {
4713 VERIFY(nvlist_lookup_uint64(spares[i],
4714 ZPOOL_CONFIG_GUID, &guid) == 0);
4715 if (spa_spare_exists(guid, &pool, NULL) &&
4716 pool != 0ULL) {
4717 VERIFY(nvlist_lookup_uint64_array(
4718 spares[i], ZPOOL_CONFIG_VDEV_STATS,
4719 (uint64_t **)&vs, &vsc) == 0);
4720 vs->vs_state = VDEV_STATE_CANT_OPEN;
4721 vs->vs_aux = VDEV_AUX_SPARED;
4722 }
4723 }
4724 }
4725 }
4726
4727 /*
4728 * Add l2cache device information to the nvlist, including vdev stats.
4729 */
4730 static void
4731 spa_add_l2cache(spa_t *spa, nvlist_t *config)
4732 {
4733 nvlist_t **l2cache;
4734 uint_t i, j, nl2cache;
4735 nvlist_t *nvroot;
4736 uint64_t guid;
4737 vdev_t *vd;
4738 vdev_stat_t *vs;
4739 uint_t vsc;
4740
4741 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4742
4743 if (spa->spa_l2cache.sav_count == 0)
4744 return;
4745
4746 VERIFY(nvlist_lookup_nvlist(config,
4747 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4748 VERIFY(nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
4749 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4750 if (nl2cache != 0) {
4751 VERIFY(nvlist_add_nvlist_array(nvroot,
4752 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
4753 VERIFY(nvlist_lookup_nvlist_array(nvroot,
4754 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4755
4756 /*
4757 * Update level 2 cache device stats.
4758 */
4759
4760 for (i = 0; i < nl2cache; i++) {
4761 VERIFY(nvlist_lookup_uint64(l2cache[i],
4762 ZPOOL_CONFIG_GUID, &guid) == 0);
4763
4764 vd = NULL;
4765 for (j = 0; j < spa->spa_l2cache.sav_count; j++) {
4766 if (guid ==
4767 spa->spa_l2cache.sav_vdevs[j]->vdev_guid) {
4768 vd = spa->spa_l2cache.sav_vdevs[j];
4769 break;
4770 }
4771 }
4772 ASSERT(vd != NULL);
4773
4774 VERIFY(nvlist_lookup_uint64_array(l2cache[i],
4775 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc)
4776 == 0);
4777 vdev_get_stats(vd, vs);
4778 vdev_config_generate_stats(vd, l2cache[i]);
4779
4780 }
4781 }
4782 }
4783
4784 static void
4785 spa_add_feature_stats(spa_t *spa, nvlist_t *config)
4786 {
4787 nvlist_t *features;
4788 zap_cursor_t zc;
4789 zap_attribute_t za;
4790
4791 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4792 VERIFY(nvlist_alloc(&features, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4793
4794 if (spa->spa_feat_for_read_obj != 0) {
4795 for (zap_cursor_init(&zc, spa->spa_meta_objset,
4796 spa->spa_feat_for_read_obj);
4797 zap_cursor_retrieve(&zc, &za) == 0;
4798 zap_cursor_advance(&zc)) {
4799 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4800 za.za_num_integers == 1);
4801 VERIFY3U(0, ==, nvlist_add_uint64(features, za.za_name,
4802 za.za_first_integer));
4803 }
4804 zap_cursor_fini(&zc);
4805 }
4806
4807 if (spa->spa_feat_for_write_obj != 0) {
4808 for (zap_cursor_init(&zc, spa->spa_meta_objset,
4809 spa->spa_feat_for_write_obj);
4810 zap_cursor_retrieve(&zc, &za) == 0;
4811 zap_cursor_advance(&zc)) {
4812 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4813 za.za_num_integers == 1);
4814 VERIFY3U(0, ==, nvlist_add_uint64(features, za.za_name,
4815 za.za_first_integer));
4816 }
4817 zap_cursor_fini(&zc);
4818 }
4819
4820 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_FEATURE_STATS,
4821 features) == 0);
4822 nvlist_free(features);
4823 }
4824
4825 int
4826 spa_get_stats(const char *name, nvlist_t **config,
4827 char *altroot, size_t buflen)
4828 {
4829 int error;
4830 spa_t *spa;
4831
4832 *config = NULL;
4833 error = spa_open_common(name, &spa, FTAG, NULL, config);
4834
4835 if (spa != NULL) {
4836 /*
4837 * This still leaves a window of inconsistency where the spares
4838 * or l2cache devices could change and the config would be
4839 * self-inconsistent.
4840 */
4841 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4842
4843 if (*config != NULL) {
4844 uint64_t loadtimes[2];
4845
4846 loadtimes[0] = spa->spa_loaded_ts.tv_sec;
4847 loadtimes[1] = spa->spa_loaded_ts.tv_nsec;
4848 VERIFY(nvlist_add_uint64_array(*config,
4849 ZPOOL_CONFIG_LOADED_TIME, loadtimes, 2) == 0);
4850
4851 VERIFY(nvlist_add_uint64(*config,
4852 ZPOOL_CONFIG_ERRCOUNT,
4853 spa_get_errlog_size(spa)) == 0);
4854
4855 if (spa_suspended(spa)) {
4856 VERIFY(nvlist_add_uint64(*config,
4857 ZPOOL_CONFIG_SUSPENDED,
4858 spa->spa_failmode) == 0);
4859 VERIFY(nvlist_add_uint64(*config,
4860 ZPOOL_CONFIG_SUSPENDED_REASON,
4861 spa->spa_suspended) == 0);
4862 }
4863
4864 spa_add_spares(spa, *config);
4865 spa_add_l2cache(spa, *config);
4866 spa_add_feature_stats(spa, *config);
4867 }
4868 }
4869
4870 /*
4871 * We want to get the alternate root even for faulted pools, so we cheat
4872 * and call spa_lookup() directly.
4873 */
4874 if (altroot) {
4875 if (spa == NULL) {
4876 mutex_enter(&spa_namespace_lock);
4877 spa = spa_lookup(name);
4878 if (spa)
4879 spa_altroot(spa, altroot, buflen);
4880 else
4881 altroot[0] = '\0';
4882 spa = NULL;
4883 mutex_exit(&spa_namespace_lock);
4884 } else {
4885 spa_altroot(spa, altroot, buflen);
4886 }
4887 }
4888
4889 if (spa != NULL) {
4890 spa_config_exit(spa, SCL_CONFIG, FTAG);
4891 spa_close(spa, FTAG);
4892 }
4893
4894 return (error);
4895 }
4896
4897 /*
4898 * Validate that the auxiliary device array is well formed. We must have an
4899 * array of nvlists, each which describes a valid leaf vdev. If this is an
4900 * import (mode is VDEV_ALLOC_SPARE), then we allow corrupted spares to be
4901 * specified, as long as they are well-formed.
4902 */
4903 static int
4904 spa_validate_aux_devs(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode,
4905 spa_aux_vdev_t *sav, const char *config, uint64_t version,
4906 vdev_labeltype_t label)
4907 {
4908 nvlist_t **dev;
4909 uint_t i, ndev;
4910 vdev_t *vd;
4911 int error;
4912
4913 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4914
4915 /*
4916 * It's acceptable to have no devs specified.
4917 */
4918 if (nvlist_lookup_nvlist_array(nvroot, config, &dev, &ndev) != 0)
4919 return (0);
4920
4921 if (ndev == 0)
4922 return (SET_ERROR(EINVAL));
4923
4924 /*
4925 * Make sure the pool is formatted with a version that supports this
4926 * device type.
4927 */
4928 if (spa_version(spa) < version)
4929 return (SET_ERROR(ENOTSUP));
4930
4931 /*
4932 * Set the pending device list so we correctly handle device in-use
4933 * checking.
4934 */
4935 sav->sav_pending = dev;
4936 sav->sav_npending = ndev;
4937
4938 for (i = 0; i < ndev; i++) {
4939 if ((error = spa_config_parse(spa, &vd, dev[i], NULL, 0,
4940 mode)) != 0)
4941 goto out;
4942
4943 if (!vd->vdev_ops->vdev_op_leaf) {
4944 vdev_free(vd);
4945 error = SET_ERROR(EINVAL);
4946 goto out;
4947 }
4948
4949 vd->vdev_top = vd;
4950
4951 if ((error = vdev_open(vd)) == 0 &&
4952 (error = vdev_label_init(vd, crtxg, label)) == 0) {
4953 VERIFY(nvlist_add_uint64(dev[i], ZPOOL_CONFIG_GUID,
4954 vd->vdev_guid) == 0);
4955 }
4956
4957 vdev_free(vd);
4958
4959 if (error &&
4960 (mode != VDEV_ALLOC_SPARE && mode != VDEV_ALLOC_L2CACHE))
4961 goto out;
4962 else
4963 error = 0;
4964 }
4965
4966 out:
4967 sav->sav_pending = NULL;
4968 sav->sav_npending = 0;
4969 return (error);
4970 }
4971
4972 static int
4973 spa_validate_aux(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode)
4974 {
4975 int error;
4976
4977 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4978
4979 if ((error = spa_validate_aux_devs(spa, nvroot, crtxg, mode,
4980 &spa->spa_spares, ZPOOL_CONFIG_SPARES, SPA_VERSION_SPARES,
4981 VDEV_LABEL_SPARE)) != 0) {
4982 return (error);
4983 }
4984
4985 return (spa_validate_aux_devs(spa, nvroot, crtxg, mode,
4986 &spa->spa_l2cache, ZPOOL_CONFIG_L2CACHE, SPA_VERSION_L2CACHE,
4987 VDEV_LABEL_L2CACHE));
4988 }
4989
4990 static void
4991 spa_set_aux_vdevs(spa_aux_vdev_t *sav, nvlist_t **devs, int ndevs,
4992 const char *config)
4993 {
4994 int i;
4995
4996 if (sav->sav_config != NULL) {
4997 nvlist_t **olddevs;
4998 uint_t oldndevs;
4999 nvlist_t **newdevs;
5000
5001 /*
5002 * Generate new dev list by concatentating with the
5003 * current dev list.
5004 */
5005 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config, config,
5006 &olddevs, &oldndevs) == 0);
5007
5008 newdevs = kmem_alloc(sizeof (void *) *
5009 (ndevs + oldndevs), KM_SLEEP);
5010 for (i = 0; i < oldndevs; i++)
5011 VERIFY(nvlist_dup(olddevs[i], &newdevs[i],
5012 KM_SLEEP) == 0);
5013 for (i = 0; i < ndevs; i++)
5014 VERIFY(nvlist_dup(devs[i], &newdevs[i + oldndevs],
5015 KM_SLEEP) == 0);
5016
5017 VERIFY(nvlist_remove(sav->sav_config, config,
5018 DATA_TYPE_NVLIST_ARRAY) == 0);
5019
5020 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
5021 config, newdevs, ndevs + oldndevs) == 0);
5022 for (i = 0; i < oldndevs + ndevs; i++)
5023 nvlist_free(newdevs[i]);
5024 kmem_free(newdevs, (oldndevs + ndevs) * sizeof (void *));
5025 } else {
5026 /*
5027 * Generate a new dev list.
5028 */
5029 VERIFY(nvlist_alloc(&sav->sav_config, NV_UNIQUE_NAME,
5030 KM_SLEEP) == 0);
5031 VERIFY(nvlist_add_nvlist_array(sav->sav_config, config,
5032 devs, ndevs) == 0);
5033 }
5034 }
5035
5036 /*
5037 * Stop and drop level 2 ARC devices
5038 */
5039 void
5040 spa_l2cache_drop(spa_t *spa)
5041 {
5042 vdev_t *vd;
5043 int i;
5044 spa_aux_vdev_t *sav = &spa->spa_l2cache;
5045
5046 for (i = 0; i < sav->sav_count; i++) {
5047 uint64_t pool;
5048
5049 vd = sav->sav_vdevs[i];
5050 ASSERT(vd != NULL);
5051
5052 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
5053 pool != 0ULL && l2arc_vdev_present(vd))
5054 l2arc_remove_vdev(vd);
5055 }
5056 }
5057
5058 /*
5059 * Verify encryption parameters for spa creation. If we are encrypting, we must
5060 * have the encryption feature flag enabled.
5061 */
5062 static int
5063 spa_create_check_encryption_params(dsl_crypto_params_t *dcp,
5064 boolean_t has_encryption)
5065 {
5066 if (dcp->cp_crypt != ZIO_CRYPT_OFF &&
5067 dcp->cp_crypt != ZIO_CRYPT_INHERIT &&
5068 !has_encryption)
5069 return (SET_ERROR(ENOTSUP));
5070
5071 return (dmu_objset_create_crypt_check(NULL, dcp, NULL));
5072 }
5073
5074 /*
5075 * Pool Creation
5076 */
5077 int
5078 spa_create(const char *pool, nvlist_t *nvroot, nvlist_t *props,
5079 nvlist_t *zplprops, dsl_crypto_params_t *dcp)
5080 {
5081 spa_t *spa;
5082 char *altroot = NULL;
5083 vdev_t *rvd;
5084 dsl_pool_t *dp;
5085 dmu_tx_t *tx;
5086 int error = 0;
5087 uint64_t txg = TXG_INITIAL;
5088 nvlist_t **spares, **l2cache;
5089 uint_t nspares, nl2cache;
5090 uint64_t version, obj;
5091 boolean_t has_features;
5092 char *poolname;
5093 nvlist_t *nvl;
5094 boolean_t has_encryption;
5095 spa_feature_t feat;
5096 char *feat_name;
5097
5098 if (props == NULL ||
5099 nvlist_lookup_string(props,
5100 zpool_prop_to_name(ZPOOL_PROP_TNAME), &poolname) != 0)
5101 poolname = (char *)pool;
5102
5103 /*
5104 * If this pool already exists, return failure.
5105 */
5106 mutex_enter(&spa_namespace_lock);
5107 if (spa_lookup(poolname) != NULL) {
5108 mutex_exit(&spa_namespace_lock);
5109 return (SET_ERROR(EEXIST));
5110 }
5111
5112 /*
5113 * Allocate a new spa_t structure.
5114 */
5115 nvl = fnvlist_alloc();
5116 fnvlist_add_string(nvl, ZPOOL_CONFIG_POOL_NAME, pool);
5117 (void) nvlist_lookup_string(props,
5118 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
5119 spa = spa_add(poolname, nvl, altroot);
5120 fnvlist_free(nvl);
5121 spa_activate(spa, spa_mode_global);
5122
5123 if (props && (error = spa_prop_validate(spa, props))) {
5124 spa_deactivate(spa);
5125 spa_remove(spa);
5126 mutex_exit(&spa_namespace_lock);
5127 return (error);
5128 }
5129
5130 /*
5131 * Temporary pool names should never be written to disk.
5132 */
5133 if (poolname != pool)
5134 spa->spa_import_flags |= ZFS_IMPORT_TEMP_NAME;
5135
5136 has_features = B_FALSE;
5137 has_encryption = B_FALSE;
5138 for (nvpair_t *elem = nvlist_next_nvpair(props, NULL);
5139 elem != NULL; elem = nvlist_next_nvpair(props, elem)) {
5140 if (zpool_prop_feature(nvpair_name(elem))) {
5141 has_features = B_TRUE;
5142 feat_name = strchr(nvpair_name(elem), '@') + 1;
5143 VERIFY0(zfeature_lookup_name(feat_name, &feat));
5144 if (feat == SPA_FEATURE_ENCRYPTION)
5145 has_encryption = B_TRUE;
5146 }
5147 }
5148
5149 /* verify encryption params, if they were provided */
5150 if (dcp != NULL) {
5151 error = spa_create_check_encryption_params(dcp, has_encryption);
5152 if (error != 0) {
5153 spa_deactivate(spa);
5154 spa_remove(spa);
5155 mutex_exit(&spa_namespace_lock);
5156 return (error);
5157 }
5158 }
5159
5160 if (has_features || nvlist_lookup_uint64(props,
5161 zpool_prop_to_name(ZPOOL_PROP_VERSION), &version) != 0) {
5162 version = SPA_VERSION;
5163 }
5164 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
5165
5166 spa->spa_first_txg = txg;
5167 spa->spa_uberblock.ub_txg = txg - 1;
5168 spa->spa_uberblock.ub_version = version;
5169 spa->spa_ubsync = spa->spa_uberblock;
5170 spa->spa_load_state = SPA_LOAD_CREATE;
5171 spa->spa_removing_phys.sr_state = DSS_NONE;
5172 spa->spa_removing_phys.sr_removing_vdev = -1;
5173 spa->spa_removing_phys.sr_prev_indirect_vdev = -1;
5174 spa->spa_indirect_vdevs_loaded = B_TRUE;
5175
5176 /*
5177 * Create "The Godfather" zio to hold all async IOs
5178 */
5179 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
5180 KM_SLEEP);
5181 for (int i = 0; i < max_ncpus; i++) {
5182 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
5183 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
5184 ZIO_FLAG_GODFATHER);
5185 }
5186
5187 /*
5188 * Create the root vdev.
5189 */
5190 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5191
5192 error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, VDEV_ALLOC_ADD);
5193
5194 ASSERT(error != 0 || rvd != NULL);
5195 ASSERT(error != 0 || spa->spa_root_vdev == rvd);
5196
5197 if (error == 0 && !zfs_allocatable_devs(nvroot))
5198 error = SET_ERROR(EINVAL);
5199
5200 if (error == 0 &&
5201 (error = vdev_create(rvd, txg, B_FALSE)) == 0 &&
5202 (error = spa_validate_aux(spa, nvroot, txg,
5203 VDEV_ALLOC_ADD)) == 0) {
5204 /*
5205 * instantiate the metaslab groups (this will dirty the vdevs)
5206 * we can no longer error exit past this point
5207 */
5208 for (int c = 0; error == 0 && c < rvd->vdev_children; c++) {
5209 vdev_t *vd = rvd->vdev_child[c];
5210
5211 vdev_metaslab_set_size(vd);
5212 vdev_expand(vd, txg);
5213 }
5214 }
5215
5216 spa_config_exit(spa, SCL_ALL, FTAG);
5217
5218 if (error != 0) {
5219 spa_unload(spa);
5220 spa_deactivate(spa);
5221 spa_remove(spa);
5222 mutex_exit(&spa_namespace_lock);
5223 return (error);
5224 }
5225
5226 /*
5227 * Get the list of spares, if specified.
5228 */
5229 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
5230 &spares, &nspares) == 0) {
5231 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config, NV_UNIQUE_NAME,
5232 KM_SLEEP) == 0);
5233 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
5234 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
5235 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5236 spa_load_spares(spa);
5237 spa_config_exit(spa, SCL_ALL, FTAG);
5238 spa->spa_spares.sav_sync = B_TRUE;
5239 }
5240
5241 /*
5242 * Get the list of level 2 cache devices, if specified.
5243 */
5244 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
5245 &l2cache, &nl2cache) == 0) {
5246 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
5247 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5248 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
5249 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
5250 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5251 spa_load_l2cache(spa);
5252 spa_config_exit(spa, SCL_ALL, FTAG);
5253 spa->spa_l2cache.sav_sync = B_TRUE;
5254 }
5255
5256 spa->spa_is_initializing = B_TRUE;
5257 spa->spa_dsl_pool = dp = dsl_pool_create(spa, zplprops, dcp, txg);
5258 spa->spa_is_initializing = B_FALSE;
5259
5260 /*
5261 * Create DDTs (dedup tables).
5262 */
5263 ddt_create(spa);
5264
5265 spa_update_dspace(spa);
5266
5267 tx = dmu_tx_create_assigned(dp, txg);
5268
5269 /*
5270 * Create the pool config object.
5271 */
5272 spa->spa_config_object = dmu_object_alloc(spa->spa_meta_objset,
5273 DMU_OT_PACKED_NVLIST, SPA_CONFIG_BLOCKSIZE,
5274 DMU_OT_PACKED_NVLIST_SIZE, sizeof (uint64_t), tx);
5275
5276 if (zap_add(spa->spa_meta_objset,
5277 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CONFIG,
5278 sizeof (uint64_t), 1, &spa->spa_config_object, tx) != 0) {
5279 cmn_err(CE_PANIC, "failed to add pool config");
5280 }
5281
5282 if (zap_add(spa->spa_meta_objset,
5283 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CREATION_VERSION,
5284 sizeof (uint64_t), 1, &version, tx) != 0) {
5285 cmn_err(CE_PANIC, "failed to add pool version");
5286 }
5287
5288 /* Newly created pools with the right version are always deflated. */
5289 if (version >= SPA_VERSION_RAIDZ_DEFLATE) {
5290 spa->spa_deflate = TRUE;
5291 if (zap_add(spa->spa_meta_objset,
5292 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
5293 sizeof (uint64_t), 1, &spa->spa_deflate, tx) != 0) {
5294 cmn_err(CE_PANIC, "failed to add deflate");
5295 }
5296 }
5297
5298 /*
5299 * Create the deferred-free bpobj. Turn off compression
5300 * because sync-to-convergence takes longer if the blocksize
5301 * keeps changing.
5302 */
5303 obj = bpobj_alloc(spa->spa_meta_objset, 1 << 14, tx);
5304 dmu_object_set_compress(spa->spa_meta_objset, obj,
5305 ZIO_COMPRESS_OFF, tx);
5306 if (zap_add(spa->spa_meta_objset,
5307 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SYNC_BPOBJ,
5308 sizeof (uint64_t), 1, &obj, tx) != 0) {
5309 cmn_err(CE_PANIC, "failed to add bpobj");
5310 }
5311 VERIFY3U(0, ==, bpobj_open(&spa->spa_deferred_bpobj,
5312 spa->spa_meta_objset, obj));
5313
5314 /*
5315 * Create the pool's history object.
5316 */
5317 if (version >= SPA_VERSION_ZPOOL_HISTORY)
5318 spa_history_create_obj(spa, tx);
5319
5320 /*
5321 * Generate some random noise for salted checksums to operate on.
5322 */
5323 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
5324 sizeof (spa->spa_cksum_salt.zcs_bytes));
5325
5326 /*
5327 * Set pool properties.
5328 */
5329 spa->spa_bootfs = zpool_prop_default_numeric(ZPOOL_PROP_BOOTFS);
5330 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
5331 spa->spa_failmode = zpool_prop_default_numeric(ZPOOL_PROP_FAILUREMODE);
5332 spa->spa_autoexpand = zpool_prop_default_numeric(ZPOOL_PROP_AUTOEXPAND);
5333 spa->spa_multihost = zpool_prop_default_numeric(ZPOOL_PROP_MULTIHOST);
5334 spa->spa_autotrim = zpool_prop_default_numeric(ZPOOL_PROP_AUTOTRIM);
5335
5336 if (props != NULL) {
5337 spa_configfile_set(spa, props, B_FALSE);
5338 spa_sync_props(props, tx);
5339 }
5340
5341 dmu_tx_commit(tx);
5342
5343 spa->spa_sync_on = B_TRUE;
5344 txg_sync_start(spa->spa_dsl_pool);
5345 mmp_thread_start(spa);
5346
5347 /*
5348 * We explicitly wait for the first transaction to complete so that our
5349 * bean counters are appropriately updated.
5350 */
5351 txg_wait_synced(spa->spa_dsl_pool, txg);
5352
5353 spa_spawn_aux_threads(spa);
5354
5355 spa_write_cachefile(spa, B_FALSE, B_TRUE);
5356 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_CREATE);
5357
5358 spa_history_log_version(spa, "create");
5359
5360 /*
5361 * Don't count references from objsets that are already closed
5362 * and are making their way through the eviction process.
5363 */
5364 spa_evicting_os_wait(spa);
5365 spa->spa_minref = zfs_refcount_count(&spa->spa_refcount);
5366 spa->spa_load_state = SPA_LOAD_NONE;
5367
5368 mutex_exit(&spa_namespace_lock);
5369
5370 return (0);
5371 }
5372
5373 #ifdef _KERNEL
5374 /*
5375 * Get the root pool information from the root disk, then import the root pool
5376 * during the system boot up time.
5377 */
5378 static nvlist_t *
5379 spa_generate_rootconf(const char *devpath, const char *devid, uint64_t *guid,
5380 uint64_t pool_guid)
5381 {
5382 nvlist_t *config;
5383 nvlist_t *nvtop, *nvroot;
5384 uint64_t pgid;
5385
5386 if (vdev_disk_read_rootlabel(devpath, devid, &config) != 0)
5387 return (NULL);
5388
5389 /*
5390 * Add this top-level vdev to the child array.
5391 */
5392 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5393 &nvtop) == 0);
5394 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
5395 &pgid) == 0);
5396 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID, guid) == 0);
5397
5398 if (pool_guid != 0 && pool_guid != pgid) {
5399 /*
5400 * The boot loader provided a pool GUID, but it does not match
5401 * the one we found in the label. Return failure so that we
5402 * can fall back to the full device scan.
5403 */
5404 zfs_dbgmsg("spa_generate_rootconf: loader pool guid %llu != "
5405 "label pool guid %llu", (u_longlong_t)pool_guid,
5406 (u_longlong_t)pgid);
5407 nvlist_free(config);
5408 return (NULL);
5409 }
5410
5411 /*
5412 * Put this pool's top-level vdevs into a root vdev.
5413 */
5414 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
5415 VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
5416 VDEV_TYPE_ROOT) == 0);
5417 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
5418 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
5419 VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
5420 &nvtop, 1) == 0);
5421
5422 /*
5423 * Replace the existing vdev_tree with the new root vdev in
5424 * this pool's configuration (remove the old, add the new).
5425 */
5426 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
5427 nvlist_free(nvroot);
5428 return (config);
5429 }
5430
5431 /*
5432 * Walk the vdev tree and see if we can find a device with "better"
5433 * configuration. A configuration is "better" if the label on that
5434 * device has a more recent txg.
5435 */
5436 static void
5437 spa_alt_rootvdev(vdev_t *vd, vdev_t **avd, uint64_t *txg)
5438 {
5439 for (int c = 0; c < vd->vdev_children; c++)
5440 spa_alt_rootvdev(vd->vdev_child[c], avd, txg);
5441
5442 if (vd->vdev_ops->vdev_op_leaf) {
5443 nvlist_t *label;
5444 uint64_t label_txg;
5445
5446 if (vdev_disk_read_rootlabel(vd->vdev_physpath, vd->vdev_devid,
5447 &label) != 0)
5448 return;
5449
5450 VERIFY(nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_TXG,
5451 &label_txg) == 0);
5452
5453 /*
5454 * Do we have a better boot device?
5455 */
5456 if (label_txg > *txg) {
5457 *txg = label_txg;
5458 *avd = vd;
5459 }
5460 nvlist_free(label);
5461 }
5462 }
5463
5464 /*
5465 * Import a root pool.
5466 *
5467 * For x86. devpath_list will consist of devid and/or physpath name of
5468 * the vdev (e.g. "id1,sd@SSEAGATE..." or "/pci@1f,0/ide@d/disk@0,0:a").
5469 * The GRUB "findroot" command will return the vdev we should boot.
5470 *
5471 * For Sparc, devpath_list consists the physpath name of the booting device
5472 * no matter the rootpool is a single device pool or a mirrored pool.
5473 * e.g.
5474 * "/pci@1f,0/ide@d/disk@0,0:a"
5475 */
5476 int
5477 spa_import_rootpool(char *devpath, char *devid, uint64_t pool_guid,
5478 uint64_t vdev_guid)
5479 {
5480 spa_t *spa;
5481 vdev_t *rvd, *bvd, *avd = NULL;
5482 nvlist_t *config, *nvtop;
5483 uint64_t guid, txg;
5484 char *pname;
5485 int error;
5486 const char *altdevpath = NULL;
5487 const char *rdpath = NULL;
5488
5489 if ((rdpath = vdev_disk_preroot_force_path()) != NULL) {
5490 /*
5491 * We expect to import a single-vdev pool from a specific
5492 * device such as a ramdisk device. We don't care what the
5493 * pool label says.
5494 */
5495 config = spa_generate_rootconf(rdpath, NULL, &guid, 0);
5496 if (config != NULL) {
5497 goto configok;
5498 }
5499 cmn_err(CE_NOTE, "Cannot use root disk device '%s'", rdpath);
5500 return (SET_ERROR(EIO));
5501 }
5502
5503 /*
5504 * Read the label from the boot device and generate a configuration.
5505 */
5506 config = spa_generate_rootconf(devpath, devid, &guid, pool_guid);
5507 #if defined(_OBP) && defined(_KERNEL)
5508 if (config == NULL) {
5509 if (strstr(devpath, "/iscsi/ssd") != NULL) {
5510 /* iscsi boot */
5511 get_iscsi_bootpath_phy(devpath);
5512 config = spa_generate_rootconf(devpath, devid, &guid,
5513 pool_guid);
5514 }
5515 }
5516 #endif
5517
5518 /*
5519 * We were unable to import the pool using the /devices path or devid
5520 * provided by the boot loader. This may be the case if the boot
5521 * device has been connected to a different location in the system, or
5522 * if a new boot environment has changed the driver used to access the
5523 * boot device.
5524 *
5525 * Attempt an exhaustive scan of all visible block devices to see if we
5526 * can locate an alternative /devices path with a label that matches
5527 * the expected pool and vdev GUID.
5528 */
5529 if (config == NULL && (altdevpath =
5530 vdev_disk_preroot_lookup(pool_guid, vdev_guid)) != NULL) {
5531 cmn_err(CE_NOTE, "Original /devices path (%s) not available; "
5532 "ZFS is trying an alternate path (%s)", devpath,
5533 altdevpath);
5534 config = spa_generate_rootconf(altdevpath, NULL, &guid,
5535 pool_guid);
5536 }
5537
5538 if (config == NULL) {
5539 cmn_err(CE_NOTE, "Cannot read the pool label from '%s'",
5540 devpath);
5541 return (SET_ERROR(EIO));
5542 }
5543
5544 configok:
5545 VERIFY(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
5546 &pname) == 0);
5547 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg) == 0);
5548
5549 mutex_enter(&spa_namespace_lock);
5550 if ((spa = spa_lookup(pname)) != NULL) {
5551 /*
5552 * Remove the existing root pool from the namespace so that we
5553 * can replace it with the correct config we just read in.
5554 */
5555 spa_remove(spa);
5556 }
5557
5558 spa = spa_add(pname, config, NULL);
5559 spa->spa_is_root = B_TRUE;
5560 spa->spa_import_flags = ZFS_IMPORT_VERBATIM;
5561 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
5562 &spa->spa_ubsync.ub_version) != 0)
5563 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
5564
5565 /*
5566 * Build up a vdev tree based on the boot device's label config.
5567 */
5568 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5569 &nvtop) == 0);
5570 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5571 error = spa_config_parse(spa, &rvd, nvtop, NULL, 0,
5572 VDEV_ALLOC_ROOTPOOL);
5573 spa_config_exit(spa, SCL_ALL, FTAG);
5574 if (error) {
5575 mutex_exit(&spa_namespace_lock);
5576 nvlist_free(config);
5577 cmn_err(CE_NOTE, "Can not parse the config for pool '%s'",
5578 pname);
5579 return (error);
5580 }
5581
5582 /*
5583 * Get the boot vdev.
5584 */
5585 if ((bvd = vdev_lookup_by_guid(rvd, guid)) == NULL) {
5586 cmn_err(CE_NOTE, "Can not find the boot vdev for guid %llu",
5587 (u_longlong_t)guid);
5588 error = SET_ERROR(ENOENT);
5589 goto out;
5590 }
5591
5592 /*
5593 * Determine if there is a better boot device.
5594 */
5595 avd = bvd;
5596 spa_alt_rootvdev(rvd, &avd, &txg);
5597 if (avd != bvd) {
5598 cmn_err(CE_NOTE, "The boot device is 'degraded'. Please "
5599 "try booting from '%s'", avd->vdev_path);
5600 error = SET_ERROR(EINVAL);
5601 goto out;
5602 }
5603
5604 /*
5605 * If the boot device is part of a spare vdev then ensure that
5606 * we're booting off the active spare.
5607 */
5608 if (bvd->vdev_parent->vdev_ops == &vdev_spare_ops &&
5609 !bvd->vdev_isspare) {
5610 cmn_err(CE_NOTE, "The boot device is currently spared. Please "
5611 "try booting from '%s'",
5612 bvd->vdev_parent->
5613 vdev_child[bvd->vdev_parent->vdev_children - 1]->vdev_path);
5614 error = SET_ERROR(EINVAL);
5615 goto out;
5616 }
5617
5618 /*
5619 * The root disk may have been expanded while the system was offline.
5620 * Kick off an async task to check for and handle expansion.
5621 */
5622 spa_async_request(spa, SPA_ASYNC_AUTOEXPAND);
5623
5624 error = 0;
5625 out:
5626 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5627 vdev_free(rvd);
5628 spa_config_exit(spa, SCL_ALL, FTAG);
5629 mutex_exit(&spa_namespace_lock);
5630
5631 nvlist_free(config);
5632 return (error);
5633 }
5634
5635 #endif
5636
5637 /*
5638 * Import a non-root pool into the system.
5639 */
5640 int
5641 spa_import(const char *pool, nvlist_t *config, nvlist_t *props, uint64_t flags)
5642 {
5643 spa_t *spa;
5644 char *altroot = NULL;
5645 spa_load_state_t state = SPA_LOAD_IMPORT;
5646 zpool_load_policy_t policy;
5647 uint64_t mode = spa_mode_global;
5648 uint64_t readonly = B_FALSE;
5649 int error;
5650 nvlist_t *nvroot;
5651 nvlist_t **spares, **l2cache;
5652 uint_t nspares, nl2cache;
5653
5654 /*
5655 * If a pool with this name exists, return failure.
5656 */
5657 mutex_enter(&spa_namespace_lock);
5658 if (spa_lookup(pool) != NULL) {
5659 mutex_exit(&spa_namespace_lock);
5660 return (SET_ERROR(EEXIST));
5661 }
5662
5663 /*
5664 * Create and initialize the spa structure.
5665 */
5666 (void) nvlist_lookup_string(props,
5667 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
5668 (void) nvlist_lookup_uint64(props,
5669 zpool_prop_to_name(ZPOOL_PROP_READONLY), &readonly);
5670 if (readonly)
5671 mode = FREAD;
5672 spa = spa_add(pool, config, altroot);
5673 spa->spa_import_flags = flags;
5674
5675 /*
5676 * Verbatim import - Take a pool and insert it into the namespace
5677 * as if it had been loaded at boot.
5678 */
5679 if (spa->spa_import_flags & ZFS_IMPORT_VERBATIM) {
5680 if (props != NULL)
5681 spa_configfile_set(spa, props, B_FALSE);
5682
5683 spa_write_cachefile(spa, B_FALSE, B_TRUE);
5684 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
5685 zfs_dbgmsg("spa_import: verbatim import of %s", pool);
5686 mutex_exit(&spa_namespace_lock);
5687 return (0);
5688 }
5689
5690 spa_activate(spa, mode);
5691
5692 /*
5693 * Don't start async tasks until we know everything is healthy.
5694 */
5695 spa_async_suspend(spa);
5696
5697 zpool_get_load_policy(config, &policy);
5698 if (policy.zlp_rewind & ZPOOL_DO_REWIND)
5699 state = SPA_LOAD_RECOVER;
5700
5701 spa->spa_config_source = SPA_CONFIG_SRC_TRYIMPORT;
5702
5703 if (state != SPA_LOAD_RECOVER) {
5704 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
5705 zfs_dbgmsg("spa_import: importing %s", pool);
5706 } else {
5707 zfs_dbgmsg("spa_import: importing %s, max_txg=%lld "
5708 "(RECOVERY MODE)", pool, (longlong_t)policy.zlp_txg);
5709 }
5710 error = spa_load_best(spa, state, policy.zlp_txg, policy.zlp_rewind);
5711
5712 /*
5713 * Propagate anything learned while loading the pool and pass it
5714 * back to caller (i.e. rewind info, missing devices, etc).
5715 */
5716 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
5717 spa->spa_load_info) == 0);
5718
5719 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5720 /*
5721 * Toss any existing sparelist, as it doesn't have any validity
5722 * anymore, and conflicts with spa_has_spare().
5723 */
5724 if (spa->spa_spares.sav_config) {
5725 nvlist_free(spa->spa_spares.sav_config);
5726 spa->spa_spares.sav_config = NULL;
5727 spa_load_spares(spa);
5728 }
5729 if (spa->spa_l2cache.sav_config) {
5730 nvlist_free(spa->spa_l2cache.sav_config);
5731 spa->spa_l2cache.sav_config = NULL;
5732 spa_load_l2cache(spa);
5733 }
5734
5735 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5736 &nvroot) == 0);
5737 if (error == 0)
5738 error = spa_validate_aux(spa, nvroot, -1ULL,
5739 VDEV_ALLOC_SPARE);
5740 if (error == 0)
5741 error = spa_validate_aux(spa, nvroot, -1ULL,
5742 VDEV_ALLOC_L2CACHE);
5743 spa_config_exit(spa, SCL_ALL, FTAG);
5744
5745 if (props != NULL)
5746 spa_configfile_set(spa, props, B_FALSE);
5747
5748 if (error != 0 || (props && spa_writeable(spa) &&
5749 (error = spa_prop_set(spa, props)))) {
5750 spa_unload(spa);
5751 spa_deactivate(spa);
5752 spa_remove(spa);
5753 mutex_exit(&spa_namespace_lock);
5754 return (error);
5755 }
5756
5757 spa_async_resume(spa);
5758
5759 /*
5760 * Override any spares and level 2 cache devices as specified by
5761 * the user, as these may have correct device names/devids, etc.
5762 */
5763 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
5764 &spares, &nspares) == 0) {
5765 if (spa->spa_spares.sav_config)
5766 VERIFY(nvlist_remove(spa->spa_spares.sav_config,
5767 ZPOOL_CONFIG_SPARES, DATA_TYPE_NVLIST_ARRAY) == 0);
5768 else
5769 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config,
5770 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5771 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
5772 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
5773 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5774 spa_load_spares(spa);
5775 spa_config_exit(spa, SCL_ALL, FTAG);
5776 spa->spa_spares.sav_sync = B_TRUE;
5777 }
5778 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
5779 &l2cache, &nl2cache) == 0) {
5780 if (spa->spa_l2cache.sav_config)
5781 VERIFY(nvlist_remove(spa->spa_l2cache.sav_config,
5782 ZPOOL_CONFIG_L2CACHE, DATA_TYPE_NVLIST_ARRAY) == 0);
5783 else
5784 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
5785 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5786 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
5787 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
5788 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5789 spa_load_l2cache(spa);
5790 spa_config_exit(spa, SCL_ALL, FTAG);
5791 spa->spa_l2cache.sav_sync = B_TRUE;
5792 }
5793
5794 /*
5795 * Check for any removed devices.
5796 */
5797 if (spa->spa_autoreplace) {
5798 spa_aux_check_removed(&spa->spa_spares);
5799 spa_aux_check_removed(&spa->spa_l2cache);
5800 }
5801
5802 if (spa_writeable(spa)) {
5803 /*
5804 * Update the config cache to include the newly-imported pool.
5805 */
5806 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5807 }
5808
5809 /*
5810 * It's possible that the pool was expanded while it was exported.
5811 * We kick off an async task to handle this for us.
5812 */
5813 spa_async_request(spa, SPA_ASYNC_AUTOEXPAND);
5814
5815 spa_history_log_version(spa, "import");
5816
5817 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
5818
5819 mutex_exit(&spa_namespace_lock);
5820
5821 return (0);
5822 }
5823
5824 nvlist_t *
5825 spa_tryimport(nvlist_t *tryconfig)
5826 {
5827 nvlist_t *config = NULL;
5828 char *poolname, *cachefile;
5829 spa_t *spa;
5830 uint64_t state;
5831 int error;
5832 zpool_load_policy_t policy;
5833
5834 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_POOL_NAME, &poolname))
5835 return (NULL);
5836
5837 if (nvlist_lookup_uint64(tryconfig, ZPOOL_CONFIG_POOL_STATE, &state))
5838 return (NULL);
5839
5840 /*
5841 * Create and initialize the spa structure.
5842 */
5843 mutex_enter(&spa_namespace_lock);
5844 spa = spa_add(TRYIMPORT_NAME, tryconfig, NULL);
5845 spa_activate(spa, FREAD);
5846
5847 /*
5848 * Rewind pool if a max txg was provided.
5849 */
5850 zpool_get_load_policy(spa->spa_config, &policy);
5851 if (policy.zlp_txg != UINT64_MAX) {
5852 spa->spa_load_max_txg = policy.zlp_txg;
5853 spa->spa_extreme_rewind = B_TRUE;
5854 zfs_dbgmsg("spa_tryimport: importing %s, max_txg=%lld",
5855 poolname, (longlong_t)policy.zlp_txg);
5856 } else {
5857 zfs_dbgmsg("spa_tryimport: importing %s", poolname);
5858 }
5859
5860 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_CACHEFILE, &cachefile)
5861 == 0) {
5862 zfs_dbgmsg("spa_tryimport: using cachefile '%s'", cachefile);
5863 spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
5864 } else {
5865 spa->spa_config_source = SPA_CONFIG_SRC_SCAN;
5866 }
5867
5868 error = spa_load(spa, SPA_LOAD_TRYIMPORT, SPA_IMPORT_EXISTING);
5869
5870 /*
5871 * If 'tryconfig' was at least parsable, return the current config.
5872 */
5873 if (spa->spa_root_vdev != NULL) {
5874 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
5875 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME,
5876 poolname) == 0);
5877 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
5878 state) == 0);
5879 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
5880 spa->spa_uberblock.ub_timestamp) == 0);
5881 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
5882 spa->spa_load_info) == 0);
5883
5884 /*
5885 * If the bootfs property exists on this pool then we
5886 * copy it out so that external consumers can tell which
5887 * pools are bootable.
5888 */
5889 if ((!error || error == EEXIST) && spa->spa_bootfs) {
5890 char *tmpname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
5891
5892 /*
5893 * We have to play games with the name since the
5894 * pool was opened as TRYIMPORT_NAME.
5895 */
5896 if (dsl_dsobj_to_dsname(spa_name(spa),
5897 spa->spa_bootfs, tmpname) == 0) {
5898 char *cp;
5899 char *dsname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
5900
5901 cp = strchr(tmpname, '/');
5902 if (cp == NULL) {
5903 (void) strlcpy(dsname, tmpname,
5904 MAXPATHLEN);
5905 } else {
5906 (void) snprintf(dsname, MAXPATHLEN,
5907 "%s/%s", poolname, ++cp);
5908 }
5909 VERIFY(nvlist_add_string(config,
5910 ZPOOL_CONFIG_BOOTFS, dsname) == 0);
5911 kmem_free(dsname, MAXPATHLEN);
5912 }
5913 kmem_free(tmpname, MAXPATHLEN);
5914 }
5915
5916 /*
5917 * Add the list of hot spares and level 2 cache devices.
5918 */
5919 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
5920 spa_add_spares(spa, config);
5921 spa_add_l2cache(spa, config);
5922 spa_config_exit(spa, SCL_CONFIG, FTAG);
5923 }
5924
5925 spa_unload(spa);
5926 spa_deactivate(spa);
5927 spa_remove(spa);
5928 mutex_exit(&spa_namespace_lock);
5929
5930 return (config);
5931 }
5932
5933 /*
5934 * Pool export/destroy
5935 *
5936 * The act of destroying or exporting a pool is very simple. We make sure there
5937 * is no more pending I/O and any references to the pool are gone. Then, we
5938 * update the pool state and sync all the labels to disk, removing the
5939 * configuration from the cache afterwards. If the 'hardforce' flag is set, then
5940 * we don't sync the labels or remove the configuration cache.
5941 */
5942 static int
5943 spa_export_common(char *pool, int new_state, nvlist_t **oldconfig,
5944 boolean_t force, boolean_t hardforce)
5945 {
5946 spa_t *spa;
5947
5948 if (oldconfig)
5949 *oldconfig = NULL;
5950
5951 if (!(spa_mode_global & FWRITE))
5952 return (SET_ERROR(EROFS));
5953
5954 mutex_enter(&spa_namespace_lock);
5955 if ((spa = spa_lookup(pool)) == NULL) {
5956 mutex_exit(&spa_namespace_lock);
5957 return (SET_ERROR(ENOENT));
5958 }
5959
5960 /*
5961 * Put a hold on the pool, drop the namespace lock, stop async tasks,
5962 * reacquire the namespace lock, and see if we can export.
5963 */
5964 spa_open_ref(spa, FTAG);
5965 mutex_exit(&spa_namespace_lock);
5966 spa_async_suspend(spa);
5967 mutex_enter(&spa_namespace_lock);
5968 spa_close(spa, FTAG);
5969
5970 /*
5971 * The pool will be in core if it's openable,
5972 * in which case we can modify its state.
5973 */
5974 if (spa->spa_state != POOL_STATE_UNINITIALIZED && spa->spa_sync_on) {
5975
5976 /*
5977 * Objsets may be open only because they're dirty, so we
5978 * have to force it to sync before checking spa_refcnt.
5979 */
5980 txg_wait_synced(spa->spa_dsl_pool, 0);
5981 spa_evicting_os_wait(spa);
5982
5983 /*
5984 * A pool cannot be exported or destroyed if there are active
5985 * references. If we are resetting a pool, allow references by
5986 * fault injection handlers.
5987 */
5988 if (!spa_refcount_zero(spa) ||
5989 (spa->spa_inject_ref != 0 &&
5990 new_state != POOL_STATE_UNINITIALIZED)) {
5991 spa_async_resume(spa);
5992 mutex_exit(&spa_namespace_lock);
5993 return (SET_ERROR(EBUSY));
5994 }
5995
5996 /*
5997 * A pool cannot be exported if it has an active shared spare.
5998 * This is to prevent other pools stealing the active spare
5999 * from an exported pool. At user's own will, such pool can
6000 * be forcedly exported.
6001 */
6002 if (!force && new_state == POOL_STATE_EXPORTED &&
6003 spa_has_active_shared_spare(spa)) {
6004 spa_async_resume(spa);
6005 mutex_exit(&spa_namespace_lock);
6006 return (SET_ERROR(EXDEV));
6007 }
6008
6009 /*
6010 * We're about to export or destroy this pool. Make sure
6011 * we stop all initialization and trim activity here before
6012 * we set the spa_final_txg. This will ensure that all
6013 * dirty data resulting from the initialization is
6014 * committed to disk before we unload the pool.
6015 */
6016 if (spa->spa_root_vdev != NULL) {
6017 vdev_t *rvd = spa->spa_root_vdev;
6018 vdev_initialize_stop_all(rvd, VDEV_INITIALIZE_ACTIVE);
6019 vdev_trim_stop_all(rvd, VDEV_TRIM_ACTIVE);
6020 vdev_autotrim_stop_all(spa);
6021 }
6022
6023 /*
6024 * We want this to be reflected on every label,
6025 * so mark them all dirty. spa_unload() will do the
6026 * final sync that pushes these changes out.
6027 */
6028 if (new_state != POOL_STATE_UNINITIALIZED && !hardforce) {
6029 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6030 spa->spa_state = new_state;
6031 spa->spa_final_txg = spa_last_synced_txg(spa) +
6032 TXG_DEFER_SIZE + 1;
6033 vdev_config_dirty(spa->spa_root_vdev);
6034 spa_config_exit(spa, SCL_ALL, FTAG);
6035 }
6036 }
6037
6038 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_DESTROY);
6039
6040 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
6041 spa_unload(spa);
6042 spa_deactivate(spa);
6043 }
6044
6045 if (oldconfig && spa->spa_config)
6046 VERIFY(nvlist_dup(spa->spa_config, oldconfig, 0) == 0);
6047
6048 if (new_state != POOL_STATE_UNINITIALIZED) {
6049 if (!hardforce)
6050 spa_write_cachefile(spa, B_TRUE, B_TRUE);
6051 spa_remove(spa);
6052 }
6053 mutex_exit(&spa_namespace_lock);
6054
6055 return (0);
6056 }
6057
6058 /*
6059 * Destroy a storage pool.
6060 */
6061 int
6062 spa_destroy(char *pool)
6063 {
6064 return (spa_export_common(pool, POOL_STATE_DESTROYED, NULL,
6065 B_FALSE, B_FALSE));
6066 }
6067
6068 /*
6069 * Export a storage pool.
6070 */
6071 int
6072 spa_export(char *pool, nvlist_t **oldconfig, boolean_t force,
6073 boolean_t hardforce)
6074 {
6075 return (spa_export_common(pool, POOL_STATE_EXPORTED, oldconfig,
6076 force, hardforce));
6077 }
6078
6079 /*
6080 * Similar to spa_export(), this unloads the spa_t without actually removing it
6081 * from the namespace in any way.
6082 */
6083 int
6084 spa_reset(char *pool)
6085 {
6086 return (spa_export_common(pool, POOL_STATE_UNINITIALIZED, NULL,
6087 B_FALSE, B_FALSE));
6088 }
6089
6090 /*
6091 * ==========================================================================
6092 * Device manipulation
6093 * ==========================================================================
6094 */
6095
6096 /*
6097 * Add a device to a storage pool.
6098 */
6099 int
6100 spa_vdev_add(spa_t *spa, nvlist_t *nvroot)
6101 {
6102 uint64_t txg;
6103 int error;
6104 vdev_t *rvd = spa->spa_root_vdev;
6105 vdev_t *vd, *tvd;
6106 nvlist_t **spares, **l2cache;
6107 uint_t nspares, nl2cache;
6108
6109 ASSERT(spa_writeable(spa));
6110
6111 txg = spa_vdev_enter(spa);
6112
6113 if ((error = spa_config_parse(spa, &vd, nvroot, NULL, 0,
6114 VDEV_ALLOC_ADD)) != 0)
6115 return (spa_vdev_exit(spa, NULL, txg, error));
6116
6117 spa->spa_pending_vdev = vd; /* spa_vdev_exit() will clear this */
6118
6119 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares,
6120 &nspares) != 0)
6121 nspares = 0;
6122
6123 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE, &l2cache,
6124 &nl2cache) != 0)
6125 nl2cache = 0;
6126
6127 if (vd->vdev_children == 0 && nspares == 0 && nl2cache == 0)
6128 return (spa_vdev_exit(spa, vd, txg, EINVAL));
6129
6130 if (vd->vdev_children != 0 &&
6131 (error = vdev_create(vd, txg, B_FALSE)) != 0)
6132 return (spa_vdev_exit(spa, vd, txg, error));
6133
6134 /*
6135 * We must validate the spares and l2cache devices after checking the
6136 * children. Otherwise, vdev_inuse() will blindly overwrite the spare.
6137 */
6138 if ((error = spa_validate_aux(spa, nvroot, txg, VDEV_ALLOC_ADD)) != 0)
6139 return (spa_vdev_exit(spa, vd, txg, error));
6140
6141 /*
6142 * If we are in the middle of a device removal, we can only add
6143 * devices which match the existing devices in the pool.
6144 * If we are in the middle of a removal, or have some indirect
6145 * vdevs, we can not add raidz toplevels.
6146 */
6147 if (spa->spa_vdev_removal != NULL ||
6148 spa->spa_removing_phys.sr_prev_indirect_vdev != -1) {
6149 for (int c = 0; c < vd->vdev_children; c++) {
6150 tvd = vd->vdev_child[c];
6151 if (spa->spa_vdev_removal != NULL &&
6152 tvd->vdev_ashift != spa->spa_max_ashift) {
6153 return (spa_vdev_exit(spa, vd, txg, EINVAL));
6154 }
6155 /* Fail if top level vdev is raidz */
6156 if (tvd->vdev_ops == &vdev_raidz_ops) {
6157 return (spa_vdev_exit(spa, vd, txg, EINVAL));
6158 }
6159 /*
6160 * Need the top level mirror to be
6161 * a mirror of leaf vdevs only
6162 */
6163 if (tvd->vdev_ops == &vdev_mirror_ops) {
6164 for (uint64_t cid = 0;
6165 cid < tvd->vdev_children; cid++) {
6166 vdev_t *cvd = tvd->vdev_child[cid];
6167 if (!cvd->vdev_ops->vdev_op_leaf) {
6168 return (spa_vdev_exit(spa, vd,
6169 txg, EINVAL));
6170 }
6171 }
6172 }
6173 }
6174 }
6175
6176 for (int c = 0; c < vd->vdev_children; c++) {
6177 tvd = vd->vdev_child[c];
6178 vdev_remove_child(vd, tvd);
6179 tvd->vdev_id = rvd->vdev_children;
6180 vdev_add_child(rvd, tvd);
6181 vdev_config_dirty(tvd);
6182 }
6183
6184 if (nspares != 0) {
6185 spa_set_aux_vdevs(&spa->spa_spares, spares, nspares,
6186 ZPOOL_CONFIG_SPARES);
6187 spa_load_spares(spa);
6188 spa->spa_spares.sav_sync = B_TRUE;
6189 }
6190
6191 if (nl2cache != 0) {
6192 spa_set_aux_vdevs(&spa->spa_l2cache, l2cache, nl2cache,
6193 ZPOOL_CONFIG_L2CACHE);
6194 spa_load_l2cache(spa);
6195 spa->spa_l2cache.sav_sync = B_TRUE;
6196 }
6197
6198 /*
6199 * We have to be careful when adding new vdevs to an existing pool.
6200 * If other threads start allocating from these vdevs before we
6201 * sync the config cache, and we lose power, then upon reboot we may
6202 * fail to open the pool because there are DVAs that the config cache
6203 * can't translate. Therefore, we first add the vdevs without
6204 * initializing metaslabs; sync the config cache (via spa_vdev_exit());
6205 * and then let spa_config_update() initialize the new metaslabs.
6206 *
6207 * spa_load() checks for added-but-not-initialized vdevs, so that
6208 * if we lose power at any point in this sequence, the remaining
6209 * steps will be completed the next time we load the pool.
6210 */
6211 (void) spa_vdev_exit(spa, vd, txg, 0);
6212
6213 mutex_enter(&spa_namespace_lock);
6214 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
6215 spa_event_notify(spa, NULL, NULL, ESC_ZFS_VDEV_ADD);
6216 mutex_exit(&spa_namespace_lock);
6217
6218 return (0);
6219 }
6220
6221 /*
6222 * Attach a device to a mirror. The arguments are the path to any device
6223 * in the mirror, and the nvroot for the new device. If the path specifies
6224 * a device that is not mirrored, we automatically insert the mirror vdev.
6225 *
6226 * If 'replacing' is specified, the new device is intended to replace the
6227 * existing device; in this case the two devices are made into their own
6228 * mirror using the 'replacing' vdev, which is functionally identical to
6229 * the mirror vdev (it actually reuses all the same ops) but has a few
6230 * extra rules: you can't attach to it after it's been created, and upon
6231 * completion of resilvering, the first disk (the one being replaced)
6232 * is automatically detached.
6233 */
6234 int
6235 spa_vdev_attach(spa_t *spa, uint64_t guid, nvlist_t *nvroot, int replacing)
6236 {
6237 uint64_t txg, dtl_max_txg;
6238 vdev_t *rvd = spa->spa_root_vdev;
6239 vdev_t *oldvd, *newvd, *newrootvd, *pvd, *tvd;
6240 vdev_ops_t *pvops;
6241 char *oldvdpath, *newvdpath;
6242 int newvd_isspare;
6243 int error;
6244
6245 ASSERT(spa_writeable(spa));
6246
6247 txg = spa_vdev_enter(spa);
6248
6249 oldvd = spa_lookup_by_guid(spa, guid, B_FALSE);
6250
6251 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6252 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6253 error = (spa_has_checkpoint(spa)) ?
6254 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6255 return (spa_vdev_exit(spa, NULL, txg, error));
6256 }
6257
6258 if (spa->spa_vdev_removal != NULL)
6259 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6260
6261 if (oldvd == NULL)
6262 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
6263
6264 if (!oldvd->vdev_ops->vdev_op_leaf)
6265 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6266
6267 pvd = oldvd->vdev_parent;
6268
6269 if ((error = spa_config_parse(spa, &newrootvd, nvroot, NULL, 0,
6270 VDEV_ALLOC_ATTACH)) != 0)
6271 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6272
6273 if (newrootvd->vdev_children != 1)
6274 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
6275
6276 newvd = newrootvd->vdev_child[0];
6277
6278 if (!newvd->vdev_ops->vdev_op_leaf)
6279 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
6280
6281 if ((error = vdev_create(newrootvd, txg, replacing)) != 0)
6282 return (spa_vdev_exit(spa, newrootvd, txg, error));
6283
6284 /*
6285 * Spares can't replace logs
6286 */
6287 if (oldvd->vdev_top->vdev_islog && newvd->vdev_isspare)
6288 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6289
6290 if (!replacing) {
6291 /*
6292 * For attach, the only allowable parent is a mirror or the root
6293 * vdev.
6294 */
6295 if (pvd->vdev_ops != &vdev_mirror_ops &&
6296 pvd->vdev_ops != &vdev_root_ops)
6297 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6298
6299 pvops = &vdev_mirror_ops;
6300 } else {
6301 /*
6302 * Active hot spares can only be replaced by inactive hot
6303 * spares.
6304 */
6305 if (pvd->vdev_ops == &vdev_spare_ops &&
6306 oldvd->vdev_isspare &&
6307 !spa_has_spare(spa, newvd->vdev_guid))
6308 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6309
6310 /*
6311 * If the source is a hot spare, and the parent isn't already a
6312 * spare, then we want to create a new hot spare. Otherwise, we
6313 * want to create a replacing vdev. The user is not allowed to
6314 * attach to a spared vdev child unless the 'isspare' state is
6315 * the same (spare replaces spare, non-spare replaces
6316 * non-spare).
6317 */
6318 if (pvd->vdev_ops == &vdev_replacing_ops &&
6319 spa_version(spa) < SPA_VERSION_MULTI_REPLACE) {
6320 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6321 } else if (pvd->vdev_ops == &vdev_spare_ops &&
6322 newvd->vdev_isspare != oldvd->vdev_isspare) {
6323 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6324 }
6325
6326 if (newvd->vdev_isspare)
6327 pvops = &vdev_spare_ops;
6328 else
6329 pvops = &vdev_replacing_ops;
6330 }
6331
6332 /*
6333 * Make sure the new device is big enough.
6334 */
6335 if (newvd->vdev_asize < vdev_get_min_asize(oldvd))
6336 return (spa_vdev_exit(spa, newrootvd, txg, EOVERFLOW));
6337
6338 /*
6339 * The new device cannot have a higher alignment requirement
6340 * than the top-level vdev.
6341 */
6342 if (newvd->vdev_ashift > oldvd->vdev_top->vdev_ashift)
6343 return (spa_vdev_exit(spa, newrootvd, txg, EDOM));
6344
6345 /*
6346 * If this is an in-place replacement, update oldvd's path and devid
6347 * to make it distinguishable from newvd, and unopenable from now on.
6348 */
6349 if (strcmp(oldvd->vdev_path, newvd->vdev_path) == 0) {
6350 spa_strfree(oldvd->vdev_path);
6351 oldvd->vdev_path = kmem_alloc(strlen(newvd->vdev_path) + 5,
6352 KM_SLEEP);
6353 (void) sprintf(oldvd->vdev_path, "%s/%s",
6354 newvd->vdev_path, "old");
6355 if (oldvd->vdev_devid != NULL) {
6356 spa_strfree(oldvd->vdev_devid);
6357 oldvd->vdev_devid = NULL;
6358 }
6359 }
6360
6361 /* mark the device being resilvered */
6362 newvd->vdev_resilver_txg = txg;
6363
6364 /*
6365 * If the parent is not a mirror, or if we're replacing, insert the new
6366 * mirror/replacing/spare vdev above oldvd.
6367 */
6368 if (pvd->vdev_ops != pvops)
6369 pvd = vdev_add_parent(oldvd, pvops);
6370
6371 ASSERT(pvd->vdev_top->vdev_parent == rvd);
6372 ASSERT(pvd->vdev_ops == pvops);
6373 ASSERT(oldvd->vdev_parent == pvd);
6374
6375 /*
6376 * Extract the new device from its root and add it to pvd.
6377 */
6378 vdev_remove_child(newrootvd, newvd);
6379 newvd->vdev_id = pvd->vdev_children;
6380 newvd->vdev_crtxg = oldvd->vdev_crtxg;
6381 vdev_add_child(pvd, newvd);
6382
6383 tvd = newvd->vdev_top;
6384 ASSERT(pvd->vdev_top == tvd);
6385 ASSERT(tvd->vdev_parent == rvd);
6386
6387 vdev_config_dirty(tvd);
6388
6389 /*
6390 * Set newvd's DTL to [TXG_INITIAL, dtl_max_txg) so that we account
6391 * for any dmu_sync-ed blocks. It will propagate upward when
6392 * spa_vdev_exit() calls vdev_dtl_reassess().
6393 */
6394 dtl_max_txg = txg + TXG_CONCURRENT_STATES;
6395
6396 vdev_dtl_dirty(newvd, DTL_MISSING, TXG_INITIAL,
6397 dtl_max_txg - TXG_INITIAL);
6398
6399 if (newvd->vdev_isspare) {
6400 spa_spare_activate(newvd);
6401 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_SPARE);
6402 }
6403
6404 oldvdpath = spa_strdup(oldvd->vdev_path);
6405 newvdpath = spa_strdup(newvd->vdev_path);
6406 newvd_isspare = newvd->vdev_isspare;
6407
6408 /*
6409 * Mark newvd's DTL dirty in this txg.
6410 */
6411 vdev_dirty(tvd, VDD_DTL, newvd, txg);
6412
6413 /*
6414 * Schedule the resilver to restart in the future. We do this to
6415 * ensure that dmu_sync-ed blocks have been stitched into the
6416 * respective datasets. We do not do this if resilvers have been
6417 * deferred.
6418 */
6419 if (dsl_scan_resilvering(spa_get_dsl(spa)) &&
6420 spa_feature_is_enabled(spa, SPA_FEATURE_RESILVER_DEFER))
6421 vdev_defer_resilver(newvd);
6422 else
6423 dsl_scan_restart_resilver(spa->spa_dsl_pool, dtl_max_txg);
6424
6425 if (spa->spa_bootfs)
6426 spa_event_notify(spa, newvd, NULL, ESC_ZFS_BOOTFS_VDEV_ATTACH);
6427
6428 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_ATTACH);
6429
6430 /*
6431 * Commit the config
6432 */
6433 (void) spa_vdev_exit(spa, newrootvd, dtl_max_txg, 0);
6434
6435 spa_history_log_internal(spa, "vdev attach", NULL,
6436 "%s vdev=%s %s vdev=%s",
6437 replacing && newvd_isspare ? "spare in" :
6438 replacing ? "replace" : "attach", newvdpath,
6439 replacing ? "for" : "to", oldvdpath);
6440
6441 spa_strfree(oldvdpath);
6442 spa_strfree(newvdpath);
6443
6444 return (0);
6445 }
6446
6447 /*
6448 * Detach a device from a mirror or replacing vdev.
6449 *
6450 * If 'replace_done' is specified, only detach if the parent
6451 * is a replacing vdev.
6452 */
6453 int
6454 spa_vdev_detach(spa_t *spa, uint64_t guid, uint64_t pguid, int replace_done)
6455 {
6456 uint64_t txg;
6457 int error;
6458 vdev_t *rvd = spa->spa_root_vdev;
6459 vdev_t *vd, *pvd, *cvd, *tvd;
6460 boolean_t unspare = B_FALSE;
6461 uint64_t unspare_guid = 0;
6462 char *vdpath;
6463
6464 ASSERT(spa_writeable(spa));
6465
6466 txg = spa_vdev_enter(spa);
6467
6468 vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6469
6470 /*
6471 * Besides being called directly from the userland through the
6472 * ioctl interface, spa_vdev_detach() can be potentially called
6473 * at the end of spa_vdev_resilver_done().
6474 *
6475 * In the regular case, when we have a checkpoint this shouldn't
6476 * happen as we never empty the DTLs of a vdev during the scrub
6477 * [see comment in dsl_scan_done()]. Thus spa_vdev_resilvering_done()
6478 * should never get here when we have a checkpoint.
6479 *
6480 * That said, even in a case when we checkpoint the pool exactly
6481 * as spa_vdev_resilver_done() calls this function everything
6482 * should be fine as the resilver will return right away.
6483 */
6484 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6485 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6486 error = (spa_has_checkpoint(spa)) ?
6487 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6488 return (spa_vdev_exit(spa, NULL, txg, error));
6489 }
6490
6491 if (vd == NULL)
6492 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
6493
6494 if (!vd->vdev_ops->vdev_op_leaf)
6495 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6496
6497 pvd = vd->vdev_parent;
6498
6499 /*
6500 * If the parent/child relationship is not as expected, don't do it.
6501 * Consider M(A,R(B,C)) -- that is, a mirror of A with a replacing
6502 * vdev that's replacing B with C. The user's intent in replacing
6503 * is to go from M(A,B) to M(A,C). If the user decides to cancel
6504 * the replace by detaching C, the expected behavior is to end up
6505 * M(A,B). But suppose that right after deciding to detach C,
6506 * the replacement of B completes. We would have M(A,C), and then
6507 * ask to detach C, which would leave us with just A -- not what
6508 * the user wanted. To prevent this, we make sure that the
6509 * parent/child relationship hasn't changed -- in this example,
6510 * that C's parent is still the replacing vdev R.
6511 */
6512 if (pvd->vdev_guid != pguid && pguid != 0)
6513 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6514
6515 /*
6516 * Only 'replacing' or 'spare' vdevs can be replaced.
6517 */
6518 if (replace_done && pvd->vdev_ops != &vdev_replacing_ops &&
6519 pvd->vdev_ops != &vdev_spare_ops)
6520 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6521
6522 ASSERT(pvd->vdev_ops != &vdev_spare_ops ||
6523 spa_version(spa) >= SPA_VERSION_SPARES);
6524
6525 /*
6526 * Only mirror, replacing, and spare vdevs support detach.
6527 */
6528 if (pvd->vdev_ops != &vdev_replacing_ops &&
6529 pvd->vdev_ops != &vdev_mirror_ops &&
6530 pvd->vdev_ops != &vdev_spare_ops)
6531 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6532
6533 /*
6534 * If this device has the only valid copy of some data,
6535 * we cannot safely detach it.
6536 */
6537 if (vdev_dtl_required(vd))
6538 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6539
6540 ASSERT(pvd->vdev_children >= 2);
6541
6542 /*
6543 * If we are detaching the second disk from a replacing vdev, then
6544 * check to see if we changed the original vdev's path to have "/old"
6545 * at the end in spa_vdev_attach(). If so, undo that change now.
6546 */
6547 if (pvd->vdev_ops == &vdev_replacing_ops && vd->vdev_id > 0 &&
6548 vd->vdev_path != NULL) {
6549 size_t len = strlen(vd->vdev_path);
6550
6551 for (int c = 0; c < pvd->vdev_children; c++) {
6552 cvd = pvd->vdev_child[c];
6553
6554 if (cvd == vd || cvd->vdev_path == NULL)
6555 continue;
6556
6557 if (strncmp(cvd->vdev_path, vd->vdev_path, len) == 0 &&
6558 strcmp(cvd->vdev_path + len, "/old") == 0) {
6559 spa_strfree(cvd->vdev_path);
6560 cvd->vdev_path = spa_strdup(vd->vdev_path);
6561 break;
6562 }
6563 }
6564 }
6565
6566 /*
6567 * If we are detaching the original disk from a spare, then it implies
6568 * that the spare should become a real disk, and be removed from the
6569 * active spare list for the pool.
6570 */
6571 if (pvd->vdev_ops == &vdev_spare_ops &&
6572 vd->vdev_id == 0 &&
6573 pvd->vdev_child[pvd->vdev_children - 1]->vdev_isspare)
6574 unspare = B_TRUE;
6575
6576 /*
6577 * Erase the disk labels so the disk can be used for other things.
6578 * This must be done after all other error cases are handled,
6579 * but before we disembowel vd (so we can still do I/O to it).
6580 * But if we can't do it, don't treat the error as fatal --
6581 * it may be that the unwritability of the disk is the reason
6582 * it's being detached!
6583 */
6584 error = vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
6585
6586 /*
6587 * Remove vd from its parent and compact the parent's children.
6588 */
6589 vdev_remove_child(pvd, vd);
6590 vdev_compact_children(pvd);
6591
6592 /*
6593 * Remember one of the remaining children so we can get tvd below.
6594 */
6595 cvd = pvd->vdev_child[pvd->vdev_children - 1];
6596
6597 /*
6598 * If we need to remove the remaining child from the list of hot spares,
6599 * do it now, marking the vdev as no longer a spare in the process.
6600 * We must do this before vdev_remove_parent(), because that can
6601 * change the GUID if it creates a new toplevel GUID. For a similar
6602 * reason, we must remove the spare now, in the same txg as the detach;
6603 * otherwise someone could attach a new sibling, change the GUID, and
6604 * the subsequent attempt to spa_vdev_remove(unspare_guid) would fail.
6605 */
6606 if (unspare) {
6607 ASSERT(cvd->vdev_isspare);
6608 spa_spare_remove(cvd);
6609 unspare_guid = cvd->vdev_guid;
6610 (void) spa_vdev_remove(spa, unspare_guid, B_TRUE);
6611 cvd->vdev_unspare = B_TRUE;
6612 }
6613
6614 /*
6615 * If the parent mirror/replacing vdev only has one child,
6616 * the parent is no longer needed. Remove it from the tree.
6617 */
6618 if (pvd->vdev_children == 1) {
6619 if (pvd->vdev_ops == &vdev_spare_ops)
6620 cvd->vdev_unspare = B_FALSE;
6621 vdev_remove_parent(cvd);
6622 }
6623
6624 /*
6625 * We don't set tvd until now because the parent we just removed
6626 * may have been the previous top-level vdev.
6627 */
6628 tvd = cvd->vdev_top;
6629 ASSERT(tvd->vdev_parent == rvd);
6630
6631 /*
6632 * Reevaluate the parent vdev state.
6633 */
6634 vdev_propagate_state(cvd);
6635
6636 /*
6637 * If the 'autoexpand' property is set on the pool then automatically
6638 * try to expand the size of the pool. For example if the device we
6639 * just detached was smaller than the others, it may be possible to
6640 * add metaslabs (i.e. grow the pool). We need to reopen the vdev
6641 * first so that we can obtain the updated sizes of the leaf vdevs.
6642 */
6643 if (spa->spa_autoexpand) {
6644 vdev_reopen(tvd);
6645 vdev_expand(tvd, txg);
6646 }
6647
6648 vdev_config_dirty(tvd);
6649
6650 /*
6651 * Mark vd's DTL as dirty in this txg. vdev_dtl_sync() will see that
6652 * vd->vdev_detached is set and free vd's DTL object in syncing context.
6653 * But first make sure we're not on any *other* txg's DTL list, to
6654 * prevent vd from being accessed after it's freed.
6655 */
6656 vdpath = spa_strdup(vd->vdev_path);
6657 for (int t = 0; t < TXG_SIZE; t++)
6658 (void) txg_list_remove_this(&tvd->vdev_dtl_list, vd, t);
6659 vd->vdev_detached = B_TRUE;
6660 vdev_dirty(tvd, VDD_DTL, vd, txg);
6661
6662 spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE);
6663 spa_notify_waiters(spa);
6664
6665 /* hang on to the spa before we release the lock */
6666 spa_open_ref(spa, FTAG);
6667
6668 error = spa_vdev_exit(spa, vd, txg, 0);
6669
6670 spa_history_log_internal(spa, "detach", NULL,
6671 "vdev=%s", vdpath);
6672 spa_strfree(vdpath);
6673
6674 /*
6675 * If this was the removal of the original device in a hot spare vdev,
6676 * then we want to go through and remove the device from the hot spare
6677 * list of every other pool.
6678 */
6679 if (unspare) {
6680 spa_t *altspa = NULL;
6681
6682 mutex_enter(&spa_namespace_lock);
6683 while ((altspa = spa_next(altspa)) != NULL) {
6684 if (altspa->spa_state != POOL_STATE_ACTIVE ||
6685 altspa == spa)
6686 continue;
6687
6688 spa_open_ref(altspa, FTAG);
6689 mutex_exit(&spa_namespace_lock);
6690 (void) spa_vdev_remove(altspa, unspare_guid, B_TRUE);
6691 mutex_enter(&spa_namespace_lock);
6692 spa_close(altspa, FTAG);
6693 }
6694 mutex_exit(&spa_namespace_lock);
6695
6696 /* search the rest of the vdevs for spares to remove */
6697 spa_vdev_resilver_done(spa);
6698 }
6699
6700 /* all done with the spa; OK to release */
6701 mutex_enter(&spa_namespace_lock);
6702 spa_close(spa, FTAG);
6703 mutex_exit(&spa_namespace_lock);
6704
6705 return (error);
6706 }
6707
6708 static int
6709 spa_vdev_initialize_impl(spa_t *spa, uint64_t guid, uint64_t cmd_type,
6710 list_t *vd_list)
6711 {
6712 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6713
6714 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
6715
6716 /* Look up vdev and ensure it's a leaf. */
6717 vdev_t *vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6718 if (vd == NULL || vd->vdev_detached) {
6719 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6720 return (SET_ERROR(ENODEV));
6721 } else if (!vd->vdev_ops->vdev_op_leaf || !vdev_is_concrete(vd)) {
6722 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6723 return (SET_ERROR(EINVAL));
6724 } else if (!vdev_writeable(vd)) {
6725 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6726 return (SET_ERROR(EROFS));
6727 }
6728 mutex_enter(&vd->vdev_initialize_lock);
6729 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6730
6731 /*
6732 * When we activate an initialize action we check to see
6733 * if the vdev_initialize_thread is NULL. We do this instead
6734 * of using the vdev_initialize_state since there might be
6735 * a previous initialization process which has completed but
6736 * the thread is not exited.
6737 */
6738 if (cmd_type == POOL_INITIALIZE_START &&
6739 (vd->vdev_initialize_thread != NULL ||
6740 vd->vdev_top->vdev_removing)) {
6741 mutex_exit(&vd->vdev_initialize_lock);
6742 return (SET_ERROR(EBUSY));
6743 } else if (cmd_type == POOL_INITIALIZE_CANCEL &&
6744 (vd->vdev_initialize_state != VDEV_INITIALIZE_ACTIVE &&
6745 vd->vdev_initialize_state != VDEV_INITIALIZE_SUSPENDED)) {
6746 mutex_exit(&vd->vdev_initialize_lock);
6747 return (SET_ERROR(ESRCH));
6748 } else if (cmd_type == POOL_INITIALIZE_SUSPEND &&
6749 vd->vdev_initialize_state != VDEV_INITIALIZE_ACTIVE) {
6750 mutex_exit(&vd->vdev_initialize_lock);
6751 return (SET_ERROR(ESRCH));
6752 }
6753
6754 switch (cmd_type) {
6755 case POOL_INITIALIZE_START:
6756 vdev_initialize(vd);
6757 break;
6758 case POOL_INITIALIZE_CANCEL:
6759 vdev_initialize_stop(vd, VDEV_INITIALIZE_CANCELED, vd_list);
6760 break;
6761 case POOL_INITIALIZE_SUSPEND:
6762 vdev_initialize_stop(vd, VDEV_INITIALIZE_SUSPENDED, vd_list);
6763 break;
6764 default:
6765 panic("invalid cmd_type %llu", (unsigned long long)cmd_type);
6766 }
6767 mutex_exit(&vd->vdev_initialize_lock);
6768
6769 return (0);
6770 }
6771
6772 int
6773 spa_vdev_initialize(spa_t *spa, nvlist_t *nv, uint64_t cmd_type,
6774 nvlist_t *vdev_errlist)
6775 {
6776 int total_errors = 0;
6777 list_t vd_list;
6778
6779 list_create(&vd_list, sizeof (vdev_t),
6780 offsetof(vdev_t, vdev_initialize_node));
6781
6782 /*
6783 * We hold the namespace lock through the whole function
6784 * to prevent any changes to the pool while we're starting or
6785 * stopping initialization. The config and state locks are held so that
6786 * we can properly assess the vdev state before we commit to
6787 * the initializing operation.
6788 */
6789 mutex_enter(&spa_namespace_lock);
6790
6791 for (nvpair_t *pair = nvlist_next_nvpair(nv, NULL);
6792 pair != NULL; pair = nvlist_next_nvpair(nv, pair)) {
6793 uint64_t vdev_guid = fnvpair_value_uint64(pair);
6794
6795 int error = spa_vdev_initialize_impl(spa, vdev_guid, cmd_type,
6796 &vd_list);
6797 if (error != 0) {
6798 char guid_as_str[MAXNAMELEN];
6799
6800 (void) snprintf(guid_as_str, sizeof (guid_as_str),
6801 "%llu", (unsigned long long)vdev_guid);
6802 fnvlist_add_int64(vdev_errlist, guid_as_str, error);
6803 total_errors++;
6804 }
6805 }
6806
6807 /* Wait for all initialize threads to stop. */
6808 vdev_initialize_stop_wait(spa, &vd_list);
6809
6810 /* Sync out the initializing state */
6811 txg_wait_synced(spa->spa_dsl_pool, 0);
6812 mutex_exit(&spa_namespace_lock);
6813
6814 list_destroy(&vd_list);
6815
6816 return (total_errors);
6817 }
6818
6819 static int
6820 spa_vdev_trim_impl(spa_t *spa, uint64_t guid, uint64_t cmd_type,
6821 uint64_t rate, boolean_t partial, boolean_t secure, list_t *vd_list)
6822 {
6823 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6824
6825 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
6826
6827 /* Look up vdev and ensure it's a leaf. */
6828 vdev_t *vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6829 if (vd == NULL || vd->vdev_detached) {
6830 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6831 return (SET_ERROR(ENODEV));
6832 } else if (!vd->vdev_ops->vdev_op_leaf || !vdev_is_concrete(vd)) {
6833 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6834 return (SET_ERROR(EINVAL));
6835 } else if (!vdev_writeable(vd)) {
6836 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6837 return (SET_ERROR(EROFS));
6838 } else if (!vd->vdev_has_trim) {
6839 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6840 return (SET_ERROR(EOPNOTSUPP));
6841 } else if (secure && !vd->vdev_has_securetrim) {
6842 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6843 return (SET_ERROR(EOPNOTSUPP));
6844 }
6845 mutex_enter(&vd->vdev_trim_lock);
6846 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6847
6848 /*
6849 * When we activate a TRIM action we check to see if the
6850 * vdev_trim_thread is NULL. We do this instead of using the
6851 * vdev_trim_state since there might be a previous TRIM process
6852 * which has completed but the thread is not exited.
6853 */
6854 if (cmd_type == POOL_TRIM_START &&
6855 (vd->vdev_trim_thread != NULL || vd->vdev_top->vdev_removing)) {
6856 mutex_exit(&vd->vdev_trim_lock);
6857 return (SET_ERROR(EBUSY));
6858 } else if (cmd_type == POOL_TRIM_CANCEL &&
6859 (vd->vdev_trim_state != VDEV_TRIM_ACTIVE &&
6860 vd->vdev_trim_state != VDEV_TRIM_SUSPENDED)) {
6861 mutex_exit(&vd->vdev_trim_lock);
6862 return (SET_ERROR(ESRCH));
6863 } else if (cmd_type == POOL_TRIM_SUSPEND &&
6864 vd->vdev_trim_state != VDEV_TRIM_ACTIVE) {
6865 mutex_exit(&vd->vdev_trim_lock);
6866 return (SET_ERROR(ESRCH));
6867 }
6868
6869 switch (cmd_type) {
6870 case POOL_TRIM_START:
6871 vdev_trim(vd, rate, partial, secure);
6872 break;
6873 case POOL_TRIM_CANCEL:
6874 vdev_trim_stop(vd, VDEV_TRIM_CANCELED, vd_list);
6875 break;
6876 case POOL_TRIM_SUSPEND:
6877 vdev_trim_stop(vd, VDEV_TRIM_SUSPENDED, vd_list);
6878 break;
6879 default:
6880 panic("invalid cmd_type %llu", (unsigned long long)cmd_type);
6881 }
6882 mutex_exit(&vd->vdev_trim_lock);
6883
6884 return (0);
6885 }
6886
6887 /*
6888 * Initiates a manual TRIM for the requested vdevs. This kicks off individual
6889 * TRIM threads for each child vdev. These threads pass over all of the free
6890 * space in the vdev's metaslabs and issues TRIM commands for that space.
6891 */
6892 int
6893 spa_vdev_trim(spa_t *spa, nvlist_t *nv, uint64_t cmd_type, uint64_t rate,
6894 boolean_t partial, boolean_t secure, nvlist_t *vdev_errlist)
6895 {
6896 int total_errors = 0;
6897 list_t vd_list;
6898
6899 list_create(&vd_list, sizeof (vdev_t),
6900 offsetof(vdev_t, vdev_trim_node));
6901
6902 /*
6903 * We hold the namespace lock through the whole function
6904 * to prevent any changes to the pool while we're starting or
6905 * stopping TRIM. The config and state locks are held so that
6906 * we can properly assess the vdev state before we commit to
6907 * the TRIM operation.
6908 */
6909 mutex_enter(&spa_namespace_lock);
6910
6911 for (nvpair_t *pair = nvlist_next_nvpair(nv, NULL);
6912 pair != NULL; pair = nvlist_next_nvpair(nv, pair)) {
6913 uint64_t vdev_guid = fnvpair_value_uint64(pair);
6914
6915 int error = spa_vdev_trim_impl(spa, vdev_guid, cmd_type,
6916 rate, partial, secure, &vd_list);
6917 if (error != 0) {
6918 char guid_as_str[MAXNAMELEN];
6919
6920 (void) snprintf(guid_as_str, sizeof (guid_as_str),
6921 "%llu", (unsigned long long)vdev_guid);
6922 fnvlist_add_int64(vdev_errlist, guid_as_str, error);
6923 total_errors++;
6924 }
6925 }
6926
6927 /* Wait for all TRIM threads to stop. */
6928 vdev_trim_stop_wait(spa, &vd_list);
6929
6930 /* Sync out the TRIM state */
6931 txg_wait_synced(spa->spa_dsl_pool, 0);
6932 mutex_exit(&spa_namespace_lock);
6933
6934 list_destroy(&vd_list);
6935
6936 return (total_errors);
6937 }
6938
6939 /*
6940 * Split a set of devices from their mirrors, and create a new pool from them.
6941 */
6942 int
6943 spa_vdev_split_mirror(spa_t *spa, char *newname, nvlist_t *config,
6944 nvlist_t *props, boolean_t exp)
6945 {
6946 int error = 0;
6947 uint64_t txg, *glist;
6948 spa_t *newspa;
6949 uint_t c, children, lastlog;
6950 nvlist_t **child, *nvl, *tmp;
6951 dmu_tx_t *tx;
6952 char *altroot = NULL;
6953 vdev_t *rvd, **vml = NULL; /* vdev modify list */
6954 boolean_t activate_slog;
6955
6956 ASSERT(spa_writeable(spa));
6957
6958 txg = spa_vdev_enter(spa);
6959
6960 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6961 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6962 error = (spa_has_checkpoint(spa)) ?
6963 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6964 return (spa_vdev_exit(spa, NULL, txg, error));
6965 }
6966
6967 /* clear the log and flush everything up to now */
6968 activate_slog = spa_passivate_log(spa);
6969 (void) spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
6970 error = spa_reset_logs(spa);
6971 txg = spa_vdev_config_enter(spa);
6972
6973 if (activate_slog)
6974 spa_activate_log(spa);
6975
6976 if (error != 0)
6977 return (spa_vdev_exit(spa, NULL, txg, error));
6978
6979 /* check new spa name before going any further */
6980 if (spa_lookup(newname) != NULL)
6981 return (spa_vdev_exit(spa, NULL, txg, EEXIST));
6982
6983 /*
6984 * scan through all the children to ensure they're all mirrors
6985 */
6986 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvl) != 0 ||
6987 nvlist_lookup_nvlist_array(nvl, ZPOOL_CONFIG_CHILDREN, &child,
6988 &children) != 0)
6989 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6990
6991 /* first, check to ensure we've got the right child count */
6992 rvd = spa->spa_root_vdev;
6993 lastlog = 0;
6994 for (c = 0; c < rvd->vdev_children; c++) {
6995 vdev_t *vd = rvd->vdev_child[c];
6996
6997 /* don't count the holes & logs as children */
6998 if (vd->vdev_islog || !vdev_is_concrete(vd)) {
6999 if (lastlog == 0)
7000 lastlog = c;
7001 continue;
7002 }
7003
7004 lastlog = 0;
7005 }
7006 if (children != (lastlog != 0 ? lastlog : rvd->vdev_children))
7007 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
7008
7009 /* next, ensure no spare or cache devices are part of the split */
7010 if (nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_SPARES, &tmp) == 0 ||
7011 nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_L2CACHE, &tmp) == 0)
7012 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
7013
7014 vml = kmem_zalloc(children * sizeof (vdev_t *), KM_SLEEP);
7015 glist = kmem_zalloc(children * sizeof (uint64_t), KM_SLEEP);
7016
7017 /* then, loop over each vdev and validate it */
7018 for (c = 0; c < children; c++) {
7019 uint64_t is_hole = 0;
7020
7021 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
7022 &is_hole);
7023
7024 if (is_hole != 0) {
7025 if (spa->spa_root_vdev->vdev_child[c]->vdev_ishole ||
7026 spa->spa_root_vdev->vdev_child[c]->vdev_islog) {
7027 continue;
7028 } else {
7029 error = SET_ERROR(EINVAL);
7030 break;
7031 }
7032 }
7033
7034 /* which disk is going to be split? */
7035 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_GUID,
7036 &glist[c]) != 0) {
7037 error = SET_ERROR(EINVAL);
7038 break;
7039 }
7040
7041 /* look it up in the spa */
7042 vml[c] = spa_lookup_by_guid(spa, glist[c], B_FALSE);
7043 if (vml[c] == NULL) {
7044 error = SET_ERROR(ENODEV);
7045 break;
7046 }
7047
7048 /* make sure there's nothing stopping the split */
7049 if (vml[c]->vdev_parent->vdev_ops != &vdev_mirror_ops ||
7050 vml[c]->vdev_islog ||
7051 !vdev_is_concrete(vml[c]) ||
7052 vml[c]->vdev_isspare ||
7053 vml[c]->vdev_isl2cache ||
7054 !vdev_writeable(vml[c]) ||
7055 vml[c]->vdev_children != 0 ||
7056 vml[c]->vdev_state != VDEV_STATE_HEALTHY ||
7057 c != spa->spa_root_vdev->vdev_child[c]->vdev_id) {
7058 error = SET_ERROR(EINVAL);
7059 break;
7060 }
7061
7062 if (vdev_dtl_required(vml[c])) {
7063 error = SET_ERROR(EBUSY);
7064 break;
7065 }
7066
7067 /* we need certain info from the top level */
7068 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_ARRAY,
7069 vml[c]->vdev_top->vdev_ms_array) == 0);
7070 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_SHIFT,
7071 vml[c]->vdev_top->vdev_ms_shift) == 0);
7072 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASIZE,
7073 vml[c]->vdev_top->vdev_asize) == 0);
7074 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASHIFT,
7075 vml[c]->vdev_top->vdev_ashift) == 0);
7076
7077 /* transfer per-vdev ZAPs */
7078 ASSERT3U(vml[c]->vdev_leaf_zap, !=, 0);
7079 VERIFY0(nvlist_add_uint64(child[c],
7080 ZPOOL_CONFIG_VDEV_LEAF_ZAP, vml[c]->vdev_leaf_zap));
7081
7082 ASSERT3U(vml[c]->vdev_top->vdev_top_zap, !=, 0);
7083 VERIFY0(nvlist_add_uint64(child[c],
7084 ZPOOL_CONFIG_VDEV_TOP_ZAP,
7085 vml[c]->vdev_parent->vdev_top_zap));
7086 }
7087
7088 if (error != 0) {
7089 kmem_free(vml, children * sizeof (vdev_t *));
7090 kmem_free(glist, children * sizeof (uint64_t));
7091 return (spa_vdev_exit(spa, NULL, txg, error));
7092 }
7093
7094 /* stop writers from using the disks */
7095 for (c = 0; c < children; c++) {
7096 if (vml[c] != NULL)
7097 vml[c]->vdev_offline = B_TRUE;
7098 }
7099 vdev_reopen(spa->spa_root_vdev);
7100
7101 /*
7102 * Temporarily record the splitting vdevs in the spa config. This
7103 * will disappear once the config is regenerated.
7104 */
7105 VERIFY(nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
7106 VERIFY(nvlist_add_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
7107 glist, children) == 0);
7108 kmem_free(glist, children * sizeof (uint64_t));
7109
7110 mutex_enter(&spa->spa_props_lock);
7111 VERIFY(nvlist_add_nvlist(spa->spa_config, ZPOOL_CONFIG_SPLIT,
7112 nvl) == 0);
7113 mutex_exit(&spa->spa_props_lock);
7114 spa->spa_config_splitting = nvl;
7115 vdev_config_dirty(spa->spa_root_vdev);
7116
7117 /* configure and create the new pool */
7118 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME, newname) == 0);
7119 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
7120 exp ? POOL_STATE_EXPORTED : POOL_STATE_ACTIVE) == 0);
7121 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
7122 spa_version(spa)) == 0);
7123 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_TXG,
7124 spa->spa_config_txg) == 0);
7125 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_GUID,
7126 spa_generate_guid(NULL)) == 0);
7127 VERIFY0(nvlist_add_boolean(config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
7128 (void) nvlist_lookup_string(props,
7129 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
7130
7131 /* add the new pool to the namespace */
7132 newspa = spa_add(newname, config, altroot);
7133 newspa->spa_avz_action = AVZ_ACTION_REBUILD;
7134 newspa->spa_config_txg = spa->spa_config_txg;
7135 spa_set_log_state(newspa, SPA_LOG_CLEAR);
7136
7137 /* release the spa config lock, retaining the namespace lock */
7138 spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
7139
7140 if (zio_injection_enabled)
7141 zio_handle_panic_injection(spa, FTAG, 1);
7142
7143 spa_activate(newspa, spa_mode_global);
7144 spa_async_suspend(newspa);
7145
7146 /*
7147 * Temporarily stop the initializing and TRIM activity. We set the
7148 * state to ACTIVE so that we know to resume initializing or TRIM
7149 * once the split has completed.
7150 */
7151 list_t vd_initialize_list;
7152 list_create(&vd_initialize_list, sizeof (vdev_t),
7153 offsetof(vdev_t, vdev_initialize_node));
7154
7155 list_t vd_trim_list;
7156 list_create(&vd_trim_list, sizeof (vdev_t),
7157 offsetof(vdev_t, vdev_trim_node));
7158
7159 for (c = 0; c < children; c++) {
7160 if (vml[c] != NULL) {
7161 mutex_enter(&vml[c]->vdev_initialize_lock);
7162 vdev_initialize_stop(vml[c],
7163 VDEV_INITIALIZE_ACTIVE, &vd_initialize_list);
7164 mutex_exit(&vml[c]->vdev_initialize_lock);
7165
7166 mutex_enter(&vml[c]->vdev_trim_lock);
7167 vdev_trim_stop(vml[c], VDEV_TRIM_ACTIVE, &vd_trim_list);
7168 mutex_exit(&vml[c]->vdev_trim_lock);
7169 }
7170 }
7171
7172 vdev_initialize_stop_wait(spa, &vd_initialize_list);
7173 vdev_trim_stop_wait(spa, &vd_trim_list);
7174
7175 list_destroy(&vd_initialize_list);
7176 list_destroy(&vd_trim_list);
7177
7178 newspa->spa_config_source = SPA_CONFIG_SRC_SPLIT;
7179
7180 /* create the new pool from the disks of the original pool */
7181 error = spa_load(newspa, SPA_LOAD_IMPORT, SPA_IMPORT_ASSEMBLE);
7182 if (error)
7183 goto out;
7184
7185 /* if that worked, generate a real config for the new pool */
7186 if (newspa->spa_root_vdev != NULL) {
7187 VERIFY(nvlist_alloc(&newspa->spa_config_splitting,
7188 NV_UNIQUE_NAME, KM_SLEEP) == 0);
7189 VERIFY(nvlist_add_uint64(newspa->spa_config_splitting,
7190 ZPOOL_CONFIG_SPLIT_GUID, spa_guid(spa)) == 0);
7191 spa_config_set(newspa, spa_config_generate(newspa, NULL, -1ULL,
7192 B_TRUE));
7193 }
7194
7195 /* set the props */
7196 if (props != NULL) {
7197 spa_configfile_set(newspa, props, B_FALSE);
7198 error = spa_prop_set(newspa, props);
7199 if (error)
7200 goto out;
7201 }
7202
7203 /* flush everything */
7204 txg = spa_vdev_config_enter(newspa);
7205 vdev_config_dirty(newspa->spa_root_vdev);
7206 (void) spa_vdev_config_exit(newspa, NULL, txg, 0, FTAG);
7207
7208 if (zio_injection_enabled)
7209 zio_handle_panic_injection(spa, FTAG, 2);
7210
7211 spa_async_resume(newspa);
7212
7213 /* finally, update the original pool's config */
7214 txg = spa_vdev_config_enter(spa);
7215 tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
7216 error = dmu_tx_assign(tx, TXG_WAIT);
7217 if (error != 0)
7218 dmu_tx_abort(tx);
7219 for (c = 0; c < children; c++) {
7220 if (vml[c] != NULL) {
7221 vdev_split(vml[c]);
7222 if (error == 0)
7223 spa_history_log_internal(spa, "detach", tx,
7224 "vdev=%s", vml[c]->vdev_path);
7225
7226 vdev_free(vml[c]);
7227 }
7228 }
7229 spa->spa_avz_action = AVZ_ACTION_REBUILD;
7230 vdev_config_dirty(spa->spa_root_vdev);
7231 spa->spa_config_splitting = NULL;
7232 nvlist_free(nvl);
7233 if (error == 0)
7234 dmu_tx_commit(tx);
7235 (void) spa_vdev_exit(spa, NULL, txg, 0);
7236
7237 if (zio_injection_enabled)
7238 zio_handle_panic_injection(spa, FTAG, 3);
7239
7240 /* split is complete; log a history record */
7241 spa_history_log_internal(newspa, "split", NULL,
7242 "from pool %s", spa_name(spa));
7243
7244 kmem_free(vml, children * sizeof (vdev_t *));
7245
7246 /* if we're not going to mount the filesystems in userland, export */
7247 if (exp)
7248 error = spa_export_common(newname, POOL_STATE_EXPORTED, NULL,
7249 B_FALSE, B_FALSE);
7250
7251 return (error);
7252
7253 out:
7254 spa_unload(newspa);
7255 spa_deactivate(newspa);
7256 spa_remove(newspa);
7257
7258 txg = spa_vdev_config_enter(spa);
7259
7260 /* re-online all offlined disks */
7261 for (c = 0; c < children; c++) {
7262 if (vml[c] != NULL)
7263 vml[c]->vdev_offline = B_FALSE;
7264 }
7265
7266 /* restart initializing or trimming disks as necessary */
7267 spa_async_request(spa, SPA_ASYNC_INITIALIZE_RESTART);
7268 spa_async_request(spa, SPA_ASYNC_TRIM_RESTART);
7269 spa_async_request(spa, SPA_ASYNC_AUTOTRIM_RESTART);
7270
7271 vdev_reopen(spa->spa_root_vdev);
7272
7273 nvlist_free(spa->spa_config_splitting);
7274 spa->spa_config_splitting = NULL;
7275 (void) spa_vdev_exit(spa, NULL, txg, error);
7276
7277 kmem_free(vml, children * sizeof (vdev_t *));
7278 return (error);
7279 }
7280
7281 /*
7282 * Find any device that's done replacing, or a vdev marked 'unspare' that's
7283 * currently spared, so we can detach it.
7284 */
7285 static vdev_t *
7286 spa_vdev_resilver_done_hunt(vdev_t *vd)
7287 {
7288 vdev_t *newvd, *oldvd;
7289
7290 for (int c = 0; c < vd->vdev_children; c++) {
7291 oldvd = spa_vdev_resilver_done_hunt(vd->vdev_child[c]);
7292 if (oldvd != NULL)
7293 return (oldvd);
7294 }
7295
7296 /*
7297 * Check for a completed replacement. We always consider the first
7298 * vdev in the list to be the oldest vdev, and the last one to be
7299 * the newest (see spa_vdev_attach() for how that works). In
7300 * the case where the newest vdev is faulted, we will not automatically
7301 * remove it after a resilver completes. This is OK as it will require
7302 * user intervention to determine which disk the admin wishes to keep.
7303 */
7304 if (vd->vdev_ops == &vdev_replacing_ops) {
7305 ASSERT(vd->vdev_children > 1);
7306
7307 newvd = vd->vdev_child[vd->vdev_children - 1];
7308 oldvd = vd->vdev_child[0];
7309
7310 if (vdev_dtl_empty(newvd, DTL_MISSING) &&
7311 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
7312 !vdev_dtl_required(oldvd))
7313 return (oldvd);
7314 }
7315
7316 /*
7317 * Check for a completed resilver with the 'unspare' flag set.
7318 * Also potentially update faulted state.
7319 */
7320 if (vd->vdev_ops == &vdev_spare_ops) {
7321 vdev_t *first = vd->vdev_child[0];
7322 vdev_t *last = vd->vdev_child[vd->vdev_children - 1];
7323
7324 if (last->vdev_unspare) {
7325 oldvd = first;
7326 newvd = last;
7327 } else if (first->vdev_unspare) {
7328 oldvd = last;
7329 newvd = first;
7330 } else {
7331 oldvd = NULL;
7332 }
7333
7334 if (oldvd != NULL &&
7335 vdev_dtl_empty(newvd, DTL_MISSING) &&
7336 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
7337 !vdev_dtl_required(oldvd))
7338 return (oldvd);
7339
7340 vdev_propagate_state(vd);
7341
7342 /*
7343 * If there are more than two spares attached to a disk,
7344 * and those spares are not required, then we want to
7345 * attempt to free them up now so that they can be used
7346 * by other pools. Once we're back down to a single
7347 * disk+spare, we stop removing them.
7348 */
7349 if (vd->vdev_children > 2) {
7350 newvd = vd->vdev_child[1];
7351
7352 if (newvd->vdev_isspare && last->vdev_isspare &&
7353 vdev_dtl_empty(last, DTL_MISSING) &&
7354 vdev_dtl_empty(last, DTL_OUTAGE) &&
7355 !vdev_dtl_required(newvd))
7356 return (newvd);
7357 }
7358 }
7359
7360 return (NULL);
7361 }
7362
7363 static void
7364 spa_vdev_resilver_done(spa_t *spa)
7365 {
7366 vdev_t *vd, *pvd, *ppvd;
7367 uint64_t guid, sguid, pguid, ppguid;
7368
7369 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
7370
7371 while ((vd = spa_vdev_resilver_done_hunt(spa->spa_root_vdev)) != NULL) {
7372 pvd = vd->vdev_parent;
7373 ppvd = pvd->vdev_parent;
7374 guid = vd->vdev_guid;
7375 pguid = pvd->vdev_guid;
7376 ppguid = ppvd->vdev_guid;
7377 sguid = 0;
7378 /*
7379 * If we have just finished replacing a hot spared device, then
7380 * we need to detach the parent's first child (the original hot
7381 * spare) as well.
7382 */
7383 if (ppvd->vdev_ops == &vdev_spare_ops && pvd->vdev_id == 0 &&
7384 ppvd->vdev_children == 2) {
7385 ASSERT(pvd->vdev_ops == &vdev_replacing_ops);
7386 sguid = ppvd->vdev_child[1]->vdev_guid;
7387 }
7388 ASSERT(vd->vdev_resilver_txg == 0 || !vdev_dtl_required(vd));
7389
7390 spa_config_exit(spa, SCL_ALL, FTAG);
7391 if (spa_vdev_detach(spa, guid, pguid, B_TRUE) != 0)
7392 return;
7393 if (sguid && spa_vdev_detach(spa, sguid, ppguid, B_TRUE) != 0)
7394 return;
7395 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
7396 }
7397
7398 spa_config_exit(spa, SCL_ALL, FTAG);
7399 }
7400
7401 /*
7402 * Update the stored path or FRU for this vdev.
7403 */
7404 int
7405 spa_vdev_set_common(spa_t *spa, uint64_t guid, const char *value,
7406 boolean_t ispath)
7407 {
7408 vdev_t *vd;
7409 boolean_t sync = B_FALSE;
7410
7411 ASSERT(spa_writeable(spa));
7412
7413 spa_vdev_state_enter(spa, SCL_ALL);
7414
7415 if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
7416 return (spa_vdev_state_exit(spa, NULL, ENOENT));
7417
7418 if (!vd->vdev_ops->vdev_op_leaf)
7419 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
7420
7421 if (ispath) {
7422 if (strcmp(value, vd->vdev_path) != 0) {
7423 spa_strfree(vd->vdev_path);
7424 vd->vdev_path = spa_strdup(value);
7425 sync = B_TRUE;
7426 }
7427 } else {
7428 if (vd->vdev_fru == NULL) {
7429 vd->vdev_fru = spa_strdup(value);
7430 sync = B_TRUE;
7431 } else if (strcmp(value, vd->vdev_fru) != 0) {
7432 spa_strfree(vd->vdev_fru);
7433 vd->vdev_fru = spa_strdup(value);
7434 sync = B_TRUE;
7435 }
7436 }
7437
7438 return (spa_vdev_state_exit(spa, sync ? vd : NULL, 0));
7439 }
7440
7441 int
7442 spa_vdev_setpath(spa_t *spa, uint64_t guid, const char *newpath)
7443 {
7444 return (spa_vdev_set_common(spa, guid, newpath, B_TRUE));
7445 }
7446
7447 int
7448 spa_vdev_setfru(spa_t *spa, uint64_t guid, const char *newfru)
7449 {
7450 return (spa_vdev_set_common(spa, guid, newfru, B_FALSE));
7451 }
7452
7453 /*
7454 * ==========================================================================
7455 * SPA Scanning
7456 * ==========================================================================
7457 */
7458 int
7459 spa_scrub_pause_resume(spa_t *spa, pool_scrub_cmd_t cmd)
7460 {
7461 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7462
7463 if (dsl_scan_resilvering(spa->spa_dsl_pool))
7464 return (SET_ERROR(EBUSY));
7465
7466 return (dsl_scrub_set_pause_resume(spa->spa_dsl_pool, cmd));
7467 }
7468
7469 int
7470 spa_scan_stop(spa_t *spa)
7471 {
7472 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7473 if (dsl_scan_resilvering(spa->spa_dsl_pool))
7474 return (SET_ERROR(EBUSY));
7475 return (dsl_scan_cancel(spa->spa_dsl_pool));
7476 }
7477
7478 int
7479 spa_scan(spa_t *spa, pool_scan_func_t func)
7480 {
7481 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7482
7483 if (func >= POOL_SCAN_FUNCS || func == POOL_SCAN_NONE)
7484 return (SET_ERROR(ENOTSUP));
7485
7486 if (func == POOL_SCAN_RESILVER &&
7487 !spa_feature_is_enabled(spa, SPA_FEATURE_RESILVER_DEFER))
7488 return (SET_ERROR(ENOTSUP));
7489
7490 /*
7491 * If a resilver was requested, but there is no DTL on a
7492 * writeable leaf device, we have nothing to do.
7493 */
7494 if (func == POOL_SCAN_RESILVER &&
7495 !vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL)) {
7496 spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
7497 return (0);
7498 }
7499
7500 return (dsl_scan(spa->spa_dsl_pool, func));
7501 }
7502
7503 /*
7504 * ==========================================================================
7505 * SPA async task processing
7506 * ==========================================================================
7507 */
7508
7509 static void
7510 spa_async_remove(spa_t *spa, vdev_t *vd)
7511 {
7512 if (vd->vdev_remove_wanted) {
7513 vd->vdev_remove_wanted = B_FALSE;
7514 vd->vdev_delayed_close = B_FALSE;
7515 vdev_set_state(vd, B_FALSE, VDEV_STATE_REMOVED, VDEV_AUX_NONE);
7516
7517 /*
7518 * We want to clear the stats, but we don't want to do a full
7519 * vdev_clear() as that will cause us to throw away
7520 * degraded/faulted state as well as attempt to reopen the
7521 * device, all of which is a waste.
7522 */
7523 vd->vdev_stat.vs_read_errors = 0;
7524 vd->vdev_stat.vs_write_errors = 0;
7525 vd->vdev_stat.vs_checksum_errors = 0;
7526
7527 vdev_state_dirty(vd->vdev_top);
7528 }
7529
7530 for (int c = 0; c < vd->vdev_children; c++)
7531 spa_async_remove(spa, vd->vdev_child[c]);
7532 }
7533
7534 static void
7535 spa_async_probe(spa_t *spa, vdev_t *vd)
7536 {
7537 if (vd->vdev_probe_wanted) {
7538 vd->vdev_probe_wanted = B_FALSE;
7539 vdev_reopen(vd); /* vdev_open() does the actual probe */
7540 }
7541
7542 for (int c = 0; c < vd->vdev_children; c++)
7543 spa_async_probe(spa, vd->vdev_child[c]);
7544 }
7545
7546 static void
7547 spa_async_autoexpand(spa_t *spa, vdev_t *vd)
7548 {
7549 char *physpath;
7550
7551 if (!spa->spa_autoexpand)
7552 return;
7553
7554 for (int c = 0; c < vd->vdev_children; c++) {
7555 vdev_t *cvd = vd->vdev_child[c];
7556 spa_async_autoexpand(spa, cvd);
7557 }
7558
7559 if (!vd->vdev_ops->vdev_op_leaf || vd->vdev_physpath == NULL)
7560 return;
7561
7562 physpath = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
7563 (void) snprintf(physpath, MAXPATHLEN, "/devices%s", vd->vdev_physpath);
7564
7565 zfs_post_dle_sysevent(physpath);
7566
7567 kmem_free(physpath, MAXPATHLEN);
7568 }
7569
7570 static void
7571 spa_async_thread(void *arg)
7572 {
7573 spa_t *spa = (spa_t *)arg;
7574 dsl_pool_t *dp = spa->spa_dsl_pool;
7575 int tasks;
7576
7577 ASSERT(spa->spa_sync_on);
7578
7579 mutex_enter(&spa->spa_async_lock);
7580 tasks = spa->spa_async_tasks;
7581 spa->spa_async_tasks = 0;
7582 mutex_exit(&spa->spa_async_lock);
7583
7584 /*
7585 * See if the config needs to be updated.
7586 */
7587 if (tasks & SPA_ASYNC_CONFIG_UPDATE) {
7588 uint64_t old_space, new_space;
7589
7590 mutex_enter(&spa_namespace_lock);
7591 old_space = metaslab_class_get_space(spa_normal_class(spa));
7592 old_space += metaslab_class_get_space(spa_special_class(spa));
7593 old_space += metaslab_class_get_space(spa_dedup_class(spa));
7594
7595 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
7596
7597 new_space = metaslab_class_get_space(spa_normal_class(spa));
7598 new_space += metaslab_class_get_space(spa_special_class(spa));
7599 new_space += metaslab_class_get_space(spa_dedup_class(spa));
7600 mutex_exit(&spa_namespace_lock);
7601
7602 /*
7603 * If the pool grew as a result of the config update,
7604 * then log an internal history event.
7605 */
7606 if (new_space != old_space) {
7607 spa_history_log_internal(spa, "vdev online", NULL,
7608 "pool '%s' size: %llu(+%llu)",
7609 spa_name(spa), new_space, new_space - old_space);
7610 }
7611 }
7612
7613 /*
7614 * See if any devices need to be marked REMOVED.
7615 */
7616 if (tasks & SPA_ASYNC_REMOVE) {
7617 spa_vdev_state_enter(spa, SCL_NONE);
7618 spa_async_remove(spa, spa->spa_root_vdev);
7619 for (int i = 0; i < spa->spa_l2cache.sav_count; i++)
7620 spa_async_remove(spa, spa->spa_l2cache.sav_vdevs[i]);
7621 for (int i = 0; i < spa->spa_spares.sav_count; i++)
7622 spa_async_remove(spa, spa->spa_spares.sav_vdevs[i]);
7623 (void) spa_vdev_state_exit(spa, NULL, 0);
7624 }
7625
7626 if ((tasks & SPA_ASYNC_AUTOEXPAND) && !spa_suspended(spa)) {
7627 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7628 spa_async_autoexpand(spa, spa->spa_root_vdev);
7629 spa_config_exit(spa, SCL_CONFIG, FTAG);
7630 }
7631
7632 /*
7633 * See if any devices need to be probed.
7634 */
7635 if (tasks & SPA_ASYNC_PROBE) {
7636 spa_vdev_state_enter(spa, SCL_NONE);
7637 spa_async_probe(spa, spa->spa_root_vdev);
7638 for (int i = 0; i < spa->spa_spares.sav_count; i++)
7639 spa_async_probe(spa, spa->spa_spares.sav_vdevs[i]);
7640 (void) spa_vdev_state_exit(spa, NULL, 0);
7641 }
7642
7643 /*
7644 * If any devices are done replacing, detach them.
7645 */
7646 if (tasks & SPA_ASYNC_RESILVER_DONE)
7647 spa_vdev_resilver_done(spa);
7648
7649 /*
7650 * Kick off a resilver.
7651 */
7652 if (tasks & SPA_ASYNC_RESILVER &&
7653 (!dsl_scan_resilvering(dp) ||
7654 !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_RESILVER_DEFER)))
7655 dsl_scan_restart_resilver(dp, 0);
7656
7657 if (tasks & SPA_ASYNC_INITIALIZE_RESTART) {
7658 mutex_enter(&spa_namespace_lock);
7659 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7660 vdev_initialize_restart(spa->spa_root_vdev);
7661 spa_config_exit(spa, SCL_CONFIG, FTAG);
7662 mutex_exit(&spa_namespace_lock);
7663 }
7664
7665 if (tasks & SPA_ASYNC_TRIM_RESTART) {
7666 mutex_enter(&spa_namespace_lock);
7667 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7668 vdev_trim_restart(spa->spa_root_vdev);
7669 spa_config_exit(spa, SCL_CONFIG, FTAG);
7670 mutex_exit(&spa_namespace_lock);
7671 }
7672
7673 if (tasks & SPA_ASYNC_AUTOTRIM_RESTART) {
7674 mutex_enter(&spa_namespace_lock);
7675 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7676 vdev_autotrim_restart(spa);
7677 spa_config_exit(spa, SCL_CONFIG, FTAG);
7678 mutex_exit(&spa_namespace_lock);
7679 }
7680
7681 /*
7682 * Kick off L2 cache rebuilding.
7683 */
7684 if (tasks & SPA_ASYNC_L2CACHE_REBUILD) {
7685 mutex_enter(&spa_namespace_lock);
7686 spa_config_enter(spa, SCL_L2ARC, FTAG, RW_READER);
7687 l2arc_spa_rebuild_start(spa);
7688 spa_config_exit(spa, SCL_L2ARC, FTAG);
7689 mutex_exit(&spa_namespace_lock);
7690 }
7691
7692 /*
7693 * Let the world know that we're done.
7694 */
7695 mutex_enter(&spa->spa_async_lock);
7696 spa->spa_async_thread = NULL;
7697 cv_broadcast(&spa->spa_async_cv);
7698 mutex_exit(&spa->spa_async_lock);
7699 thread_exit();
7700 }
7701
7702 void
7703 spa_async_suspend(spa_t *spa)
7704 {
7705 mutex_enter(&spa->spa_async_lock);
7706 spa->spa_async_suspended++;
7707 while (spa->spa_async_thread != NULL)
7708 cv_wait(&spa->spa_async_cv, &spa->spa_async_lock);
7709 mutex_exit(&spa->spa_async_lock);
7710
7711 spa_vdev_remove_suspend(spa);
7712
7713 zthr_t *condense_thread = spa->spa_condense_zthr;
7714 if (condense_thread != NULL)
7715 zthr_cancel(condense_thread);
7716
7717 zthr_t *discard_thread = spa->spa_checkpoint_discard_zthr;
7718 if (discard_thread != NULL)
7719 zthr_cancel(discard_thread);
7720 }
7721
7722 void
7723 spa_async_resume(spa_t *spa)
7724 {
7725 mutex_enter(&spa->spa_async_lock);
7726 ASSERT(spa->spa_async_suspended != 0);
7727 spa->spa_async_suspended--;
7728 mutex_exit(&spa->spa_async_lock);
7729 spa_restart_removal(spa);
7730
7731 zthr_t *condense_thread = spa->spa_condense_zthr;
7732 if (condense_thread != NULL)
7733 zthr_resume(condense_thread);
7734
7735 zthr_t *discard_thread = spa->spa_checkpoint_discard_zthr;
7736 if (discard_thread != NULL)
7737 zthr_resume(discard_thread);
7738 }
7739
7740 static boolean_t
7741 spa_async_tasks_pending(spa_t *spa)
7742 {
7743 uint_t non_config_tasks;
7744 uint_t config_task;
7745 boolean_t config_task_suspended;
7746
7747 non_config_tasks = spa->spa_async_tasks & ~SPA_ASYNC_CONFIG_UPDATE;
7748 config_task = spa->spa_async_tasks & SPA_ASYNC_CONFIG_UPDATE;
7749 if (spa->spa_ccw_fail_time == 0) {
7750 config_task_suspended = B_FALSE;
7751 } else {
7752 config_task_suspended =
7753 (gethrtime() - spa->spa_ccw_fail_time) <
7754 (zfs_ccw_retry_interval * NANOSEC);
7755 }
7756
7757 return (non_config_tasks || (config_task && !config_task_suspended));
7758 }
7759
7760 static void
7761 spa_async_dispatch(spa_t *spa)
7762 {
7763 mutex_enter(&spa->spa_async_lock);
7764 if (spa_async_tasks_pending(spa) &&
7765 !spa->spa_async_suspended &&
7766 spa->spa_async_thread == NULL &&
7767 rootdir != NULL)
7768 spa->spa_async_thread = thread_create(NULL, 0,
7769 spa_async_thread, spa, 0, &p0, TS_RUN, maxclsyspri);
7770 mutex_exit(&spa->spa_async_lock);
7771 }
7772
7773 void
7774 spa_async_request(spa_t *spa, int task)
7775 {
7776 zfs_dbgmsg("spa=%s async request task=%u", spa->spa_name, task);
7777 mutex_enter(&spa->spa_async_lock);
7778 spa->spa_async_tasks |= task;
7779 mutex_exit(&spa->spa_async_lock);
7780 }
7781
7782 int
7783 spa_async_tasks(spa_t *spa)
7784 {
7785 return (spa->spa_async_tasks);
7786 }
7787
7788 /*
7789 * ==========================================================================
7790 * SPA syncing routines
7791 * ==========================================================================
7792 */
7793
7794 static int
7795 bpobj_enqueue_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
7796 {
7797 bpobj_t *bpo = arg;
7798 bpobj_enqueue(bpo, bp, tx);
7799 return (0);
7800 }
7801
7802 static int
7803 spa_free_sync_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
7804 {
7805 zio_t *zio = arg;
7806
7807 zio_nowait(zio_free_sync(zio, zio->io_spa, dmu_tx_get_txg(tx), bp,
7808 zio->io_flags));
7809 return (0);
7810 }
7811
7812 /*
7813 * Note: this simple function is not inlined to make it easier to dtrace the
7814 * amount of time spent syncing frees.
7815 */
7816 static void
7817 spa_sync_frees(spa_t *spa, bplist_t *bpl, dmu_tx_t *tx)
7818 {
7819 zio_t *zio = zio_root(spa, NULL, NULL, 0);
7820 bplist_iterate(bpl, spa_free_sync_cb, zio, tx);
7821 VERIFY(zio_wait(zio) == 0);
7822 }
7823
7824 /*
7825 * Note: this simple function is not inlined to make it easier to dtrace the
7826 * amount of time spent syncing deferred frees.
7827 */
7828 static void
7829 spa_sync_deferred_frees(spa_t *spa, dmu_tx_t *tx)
7830 {
7831 if (spa_sync_pass(spa) != 1)
7832 return;
7833
7834 /*
7835 * Note:
7836 * If the log space map feature is active, we stop deferring
7837 * frees to the next TXG and therefore running this function
7838 * would be considered a no-op as spa_deferred_bpobj should
7839 * not have any entries.
7840 *
7841 * That said we run this function anyway (instead of returning
7842 * immediately) for the edge-case scenario where we just
7843 * activated the log space map feature in this TXG but we have
7844 * deferred frees from the previous TXG.
7845 */
7846 zio_t *zio = zio_root(spa, NULL, NULL, 0);
7847 VERIFY3U(bpobj_iterate(&spa->spa_deferred_bpobj,
7848 spa_free_sync_cb, zio, tx), ==, 0);
7849 VERIFY0(zio_wait(zio));
7850 }
7851
7852
7853 static void
7854 spa_sync_nvlist(spa_t *spa, uint64_t obj, nvlist_t *nv, dmu_tx_t *tx)
7855 {
7856 char *packed = NULL;
7857 size_t bufsize;
7858 size_t nvsize = 0;
7859 dmu_buf_t *db;
7860
7861 VERIFY(nvlist_size(nv, &nvsize, NV_ENCODE_XDR) == 0);
7862
7863 /*
7864 * Write full (SPA_CONFIG_BLOCKSIZE) blocks of configuration
7865 * information. This avoids the dmu_buf_will_dirty() path and
7866 * saves us a pre-read to get data we don't actually care about.
7867 */
7868 bufsize = P2ROUNDUP((uint64_t)nvsize, SPA_CONFIG_BLOCKSIZE);
7869 packed = kmem_alloc(bufsize, KM_SLEEP);
7870
7871 VERIFY(nvlist_pack(nv, &packed, &nvsize, NV_ENCODE_XDR,
7872 KM_SLEEP) == 0);
7873 bzero(packed + nvsize, bufsize - nvsize);
7874
7875 dmu_write(spa->spa_meta_objset, obj, 0, bufsize, packed, tx);
7876
7877 kmem_free(packed, bufsize);
7878
7879 VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
7880 dmu_buf_will_dirty(db, tx);
7881 *(uint64_t *)db->db_data = nvsize;
7882 dmu_buf_rele(db, FTAG);
7883 }
7884
7885 static void
7886 spa_sync_aux_dev(spa_t *spa, spa_aux_vdev_t *sav, dmu_tx_t *tx,
7887 const char *config, const char *entry)
7888 {
7889 nvlist_t *nvroot;
7890 nvlist_t **list;
7891 int i;
7892
7893 if (!sav->sav_sync)
7894 return;
7895
7896 /*
7897 * Update the MOS nvlist describing the list of available devices.
7898 * spa_validate_aux() will have already made sure this nvlist is
7899 * valid and the vdevs are labeled appropriately.
7900 */
7901 if (sav->sav_object == 0) {
7902 sav->sav_object = dmu_object_alloc(spa->spa_meta_objset,
7903 DMU_OT_PACKED_NVLIST, 1 << 14, DMU_OT_PACKED_NVLIST_SIZE,
7904 sizeof (uint64_t), tx);
7905 VERIFY(zap_update(spa->spa_meta_objset,
7906 DMU_POOL_DIRECTORY_OBJECT, entry, sizeof (uint64_t), 1,
7907 &sav->sav_object, tx) == 0);
7908 }
7909
7910 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
7911 if (sav->sav_count == 0) {
7912 VERIFY(nvlist_add_nvlist_array(nvroot, config, NULL, 0) == 0);
7913 } else {
7914 list = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
7915 for (i = 0; i < sav->sav_count; i++)
7916 list[i] = vdev_config_generate(spa, sav->sav_vdevs[i],
7917 B_FALSE, VDEV_CONFIG_L2CACHE);
7918 VERIFY(nvlist_add_nvlist_array(nvroot, config, list,
7919 sav->sav_count) == 0);
7920 for (i = 0; i < sav->sav_count; i++)
7921 nvlist_free(list[i]);
7922 kmem_free(list, sav->sav_count * sizeof (void *));
7923 }
7924
7925 spa_sync_nvlist(spa, sav->sav_object, nvroot, tx);
7926 nvlist_free(nvroot);
7927
7928 sav->sav_sync = B_FALSE;
7929 }
7930
7931 /*
7932 * Rebuild spa's all-vdev ZAP from the vdev ZAPs indicated in each vdev_t.
7933 * The all-vdev ZAP must be empty.
7934 */
7935 static void
7936 spa_avz_build(vdev_t *vd, uint64_t avz, dmu_tx_t *tx)
7937 {
7938 spa_t *spa = vd->vdev_spa;
7939 if (vd->vdev_top_zap != 0) {
7940 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
7941 vd->vdev_top_zap, tx));
7942 }
7943 if (vd->vdev_leaf_zap != 0) {
7944 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
7945 vd->vdev_leaf_zap, tx));
7946 }
7947 for (uint64_t i = 0; i < vd->vdev_children; i++) {
7948 spa_avz_build(vd->vdev_child[i], avz, tx);
7949 }
7950 }
7951
7952 static void
7953 spa_sync_config_object(spa_t *spa, dmu_tx_t *tx)
7954 {
7955 nvlist_t *config;
7956
7957 /*
7958 * If the pool is being imported from a pre-per-vdev-ZAP version of ZFS,
7959 * its config may not be dirty but we still need to build per-vdev ZAPs.
7960 * Similarly, if the pool is being assembled (e.g. after a split), we
7961 * need to rebuild the AVZ although the config may not be dirty.
7962 */
7963 if (list_is_empty(&spa->spa_config_dirty_list) &&
7964 spa->spa_avz_action == AVZ_ACTION_NONE)
7965 return;
7966
7967 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7968
7969 ASSERT(spa->spa_avz_action == AVZ_ACTION_NONE ||
7970 spa->spa_avz_action == AVZ_ACTION_INITIALIZE ||
7971 spa->spa_all_vdev_zaps != 0);
7972
7973 if (spa->spa_avz_action == AVZ_ACTION_REBUILD) {
7974 /* Make and build the new AVZ */
7975 uint64_t new_avz = zap_create(spa->spa_meta_objset,
7976 DMU_OTN_ZAP_METADATA, DMU_OT_NONE, 0, tx);
7977 spa_avz_build(spa->spa_root_vdev, new_avz, tx);
7978
7979 /* Diff old AVZ with new one */
7980 zap_cursor_t zc;
7981 zap_attribute_t za;
7982
7983 for (zap_cursor_init(&zc, spa->spa_meta_objset,
7984 spa->spa_all_vdev_zaps);
7985 zap_cursor_retrieve(&zc, &za) == 0;
7986 zap_cursor_advance(&zc)) {
7987 uint64_t vdzap = za.za_first_integer;
7988 if (zap_lookup_int(spa->spa_meta_objset, new_avz,
7989 vdzap) == ENOENT) {
7990 /*
7991 * ZAP is listed in old AVZ but not in new one;
7992 * destroy it
7993 */
7994 VERIFY0(zap_destroy(spa->spa_meta_objset, vdzap,
7995 tx));
7996 }
7997 }
7998
7999 zap_cursor_fini(&zc);
8000
8001 /* Destroy the old AVZ */
8002 VERIFY0(zap_destroy(spa->spa_meta_objset,
8003 spa->spa_all_vdev_zaps, tx));
8004
8005 /* Replace the old AVZ in the dir obj with the new one */
8006 VERIFY0(zap_update(spa->spa_meta_objset,
8007 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP,
8008 sizeof (new_avz), 1, &new_avz, tx));
8009
8010 spa->spa_all_vdev_zaps = new_avz;
8011 } else if (spa->spa_avz_action == AVZ_ACTION_DESTROY) {
8012 zap_cursor_t zc;
8013 zap_attribute_t za;
8014
8015 /* Walk through the AVZ and destroy all listed ZAPs */
8016 for (zap_cursor_init(&zc, spa->spa_meta_objset,
8017 spa->spa_all_vdev_zaps);
8018 zap_cursor_retrieve(&zc, &za) == 0;
8019 zap_cursor_advance(&zc)) {
8020 uint64_t zap = za.za_first_integer;
8021 VERIFY0(zap_destroy(spa->spa_meta_objset, zap, tx));
8022 }
8023
8024 zap_cursor_fini(&zc);
8025
8026 /* Destroy and unlink the AVZ itself */
8027 VERIFY0(zap_destroy(spa->spa_meta_objset,
8028 spa->spa_all_vdev_zaps, tx));
8029 VERIFY0(zap_remove(spa->spa_meta_objset,
8030 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP, tx));
8031 spa->spa_all_vdev_zaps = 0;
8032 }
8033
8034 if (spa->spa_all_vdev_zaps == 0) {
8035 spa->spa_all_vdev_zaps = zap_create_link(spa->spa_meta_objset,
8036 DMU_OTN_ZAP_METADATA, DMU_POOL_DIRECTORY_OBJECT,
8037 DMU_POOL_VDEV_ZAP_MAP, tx);
8038 }
8039 spa->spa_avz_action = AVZ_ACTION_NONE;
8040
8041 /* Create ZAPs for vdevs that don't have them. */
8042 vdev_construct_zaps(spa->spa_root_vdev, tx);
8043
8044 config = spa_config_generate(spa, spa->spa_root_vdev,
8045 dmu_tx_get_txg(tx), B_FALSE);
8046
8047 /*
8048 * If we're upgrading the spa version then make sure that
8049 * the config object gets updated with the correct version.
8050 */
8051 if (spa->spa_ubsync.ub_version < spa->spa_uberblock.ub_version)
8052 fnvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
8053 spa->spa_uberblock.ub_version);
8054
8055 spa_config_exit(spa, SCL_STATE, FTAG);
8056
8057 nvlist_free(spa->spa_config_syncing);
8058 spa->spa_config_syncing = config;
8059
8060 spa_sync_nvlist(spa, spa->spa_config_object, config, tx);
8061 }
8062
8063 static void
8064 spa_sync_version(void *arg, dmu_tx_t *tx)
8065 {
8066 uint64_t *versionp = arg;
8067 uint64_t version = *versionp;
8068 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
8069
8070 /*
8071 * Setting the version is special cased when first creating the pool.
8072 */
8073 ASSERT(tx->tx_txg != TXG_INITIAL);
8074
8075 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
8076 ASSERT(version >= spa_version(spa));
8077
8078 spa->spa_uberblock.ub_version = version;
8079 vdev_config_dirty(spa->spa_root_vdev);
8080 spa_history_log_internal(spa, "set", tx, "version=%lld", version);
8081 }
8082
8083 /*
8084 * Set zpool properties.
8085 */
8086 static void
8087 spa_sync_props(void *arg, dmu_tx_t *tx)
8088 {
8089 nvlist_t *nvp = arg;
8090 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
8091 objset_t *mos = spa->spa_meta_objset;
8092 nvpair_t *elem = NULL;
8093
8094 mutex_enter(&spa->spa_props_lock);
8095
8096 while ((elem = nvlist_next_nvpair(nvp, elem))) {
8097 uint64_t intval;
8098 char *strval, *fname;
8099 zpool_prop_t prop;
8100 const char *propname;
8101 zprop_type_t proptype;
8102 spa_feature_t fid;
8103
8104 switch (prop = zpool_name_to_prop(nvpair_name(elem))) {
8105 case ZPOOL_PROP_INVAL:
8106 /*
8107 * We checked this earlier in spa_prop_validate().
8108 */
8109 ASSERT(zpool_prop_feature(nvpair_name(elem)));
8110
8111 fname = strchr(nvpair_name(elem), '@') + 1;
8112 VERIFY0(zfeature_lookup_name(fname, &fid));
8113
8114 spa_feature_enable(spa, fid, tx);
8115 spa_history_log_internal(spa, "set", tx,
8116 "%s=enabled", nvpair_name(elem));
8117 break;
8118
8119 case ZPOOL_PROP_VERSION:
8120 intval = fnvpair_value_uint64(elem);
8121 /*
8122 * The version is synced seperatly before other
8123 * properties and should be correct by now.
8124 */
8125 ASSERT3U(spa_version(spa), >=, intval);
8126 break;
8127
8128 case ZPOOL_PROP_ALTROOT:
8129 /*
8130 * 'altroot' is a non-persistent property. It should
8131 * have been set temporarily at creation or import time.
8132 */
8133 ASSERT(spa->spa_root != NULL);
8134 break;
8135
8136 case ZPOOL_PROP_READONLY:
8137 case ZPOOL_PROP_CACHEFILE:
8138 /*
8139 * 'readonly' and 'cachefile' are also non-persisitent
8140 * properties.
8141 */
8142 break;
8143 case ZPOOL_PROP_COMMENT:
8144 strval = fnvpair_value_string(elem);
8145 if (spa->spa_comment != NULL)
8146 spa_strfree(spa->spa_comment);
8147 spa->spa_comment = spa_strdup(strval);
8148 /*
8149 * We need to dirty the configuration on all the vdevs
8150 * so that their labels get updated. It's unnecessary
8151 * to do this for pool creation since the vdev's
8152 * configuratoin has already been dirtied.
8153 */
8154 if (tx->tx_txg != TXG_INITIAL)
8155 vdev_config_dirty(spa->spa_root_vdev);
8156 spa_history_log_internal(spa, "set", tx,
8157 "%s=%s", nvpair_name(elem), strval);
8158 break;
8159 default:
8160 /*
8161 * Set pool property values in the poolprops mos object.
8162 */
8163 if (spa->spa_pool_props_object == 0) {
8164 spa->spa_pool_props_object =
8165 zap_create_link(mos, DMU_OT_POOL_PROPS,
8166 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_PROPS,
8167 tx);
8168 }
8169
8170 /* normalize the property name */
8171 propname = zpool_prop_to_name(prop);
8172 proptype = zpool_prop_get_type(prop);
8173
8174 if (nvpair_type(elem) == DATA_TYPE_STRING) {
8175 ASSERT(proptype == PROP_TYPE_STRING);
8176 strval = fnvpair_value_string(elem);
8177 VERIFY0(zap_update(mos,
8178 spa->spa_pool_props_object, propname,
8179 1, strlen(strval) + 1, strval, tx));
8180 spa_history_log_internal(spa, "set", tx,
8181 "%s=%s", nvpair_name(elem), strval);
8182 } else if (nvpair_type(elem) == DATA_TYPE_UINT64) {
8183 intval = fnvpair_value_uint64(elem);
8184
8185 if (proptype == PROP_TYPE_INDEX) {
8186 const char *unused;
8187 VERIFY0(zpool_prop_index_to_string(
8188 prop, intval, &unused));
8189 }
8190 VERIFY0(zap_update(mos,
8191 spa->spa_pool_props_object, propname,
8192 8, 1, &intval, tx));
8193 spa_history_log_internal(spa, "set", tx,
8194 "%s=%lld", nvpair_name(elem), intval);
8195 } else {
8196 ASSERT(0); /* not allowed */
8197 }
8198
8199 switch (prop) {
8200 case ZPOOL_PROP_DELEGATION:
8201 spa->spa_delegation = intval;
8202 break;
8203 case ZPOOL_PROP_BOOTFS:
8204 spa->spa_bootfs = intval;
8205 break;
8206 case ZPOOL_PROP_FAILUREMODE:
8207 spa->spa_failmode = intval;
8208 break;
8209 case ZPOOL_PROP_AUTOTRIM:
8210 spa->spa_autotrim = intval;
8211 spa_async_request(spa,
8212 SPA_ASYNC_AUTOTRIM_RESTART);
8213 break;
8214 case ZPOOL_PROP_AUTOEXPAND:
8215 spa->spa_autoexpand = intval;
8216 if (tx->tx_txg != TXG_INITIAL)
8217 spa_async_request(spa,
8218 SPA_ASYNC_AUTOEXPAND);
8219 break;
8220 case ZPOOL_PROP_MULTIHOST:
8221 spa->spa_multihost = intval;
8222 break;
8223 case ZPOOL_PROP_DEDUPDITTO:
8224 spa->spa_dedup_ditto = intval;
8225 break;
8226 default:
8227 break;
8228 }
8229 }
8230
8231 }
8232
8233 mutex_exit(&spa->spa_props_lock);
8234 }
8235
8236 /*
8237 * Perform one-time upgrade on-disk changes. spa_version() does not
8238 * reflect the new version this txg, so there must be no changes this
8239 * txg to anything that the upgrade code depends on after it executes.
8240 * Therefore this must be called after dsl_pool_sync() does the sync
8241 * tasks.
8242 */
8243 static void
8244 spa_sync_upgrades(spa_t *spa, dmu_tx_t *tx)
8245 {
8246 if (spa_sync_pass(spa) != 1)
8247 return;
8248
8249 dsl_pool_t *dp = spa->spa_dsl_pool;
8250 rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
8251
8252 if (spa->spa_ubsync.ub_version < SPA_VERSION_ORIGIN &&
8253 spa->spa_uberblock.ub_version >= SPA_VERSION_ORIGIN) {
8254 dsl_pool_create_origin(dp, tx);
8255
8256 /* Keeping the origin open increases spa_minref */
8257 spa->spa_minref += 3;
8258 }
8259
8260 if (spa->spa_ubsync.ub_version < SPA_VERSION_NEXT_CLONES &&
8261 spa->spa_uberblock.ub_version >= SPA_VERSION_NEXT_CLONES) {
8262 dsl_pool_upgrade_clones(dp, tx);
8263 }
8264
8265 if (spa->spa_ubsync.ub_version < SPA_VERSION_DIR_CLONES &&
8266 spa->spa_uberblock.ub_version >= SPA_VERSION_DIR_CLONES) {
8267 dsl_pool_upgrade_dir_clones(dp, tx);
8268
8269 /* Keeping the freedir open increases spa_minref */
8270 spa->spa_minref += 3;
8271 }
8272
8273 if (spa->spa_ubsync.ub_version < SPA_VERSION_FEATURES &&
8274 spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
8275 spa_feature_create_zap_objects(spa, tx);
8276 }
8277
8278 /*
8279 * LZ4_COMPRESS feature's behaviour was changed to activate_on_enable
8280 * when possibility to use lz4 compression for metadata was added
8281 * Old pools that have this feature enabled must be upgraded to have
8282 * this feature active
8283 */
8284 if (spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
8285 boolean_t lz4_en = spa_feature_is_enabled(spa,
8286 SPA_FEATURE_LZ4_COMPRESS);
8287 boolean_t lz4_ac = spa_feature_is_active(spa,
8288 SPA_FEATURE_LZ4_COMPRESS);
8289
8290 if (lz4_en && !lz4_ac)
8291 spa_feature_incr(spa, SPA_FEATURE_LZ4_COMPRESS, tx);
8292 }
8293
8294 /*
8295 * If we haven't written the salt, do so now. Note that the
8296 * feature may not be activated yet, but that's fine since
8297 * the presence of this ZAP entry is backwards compatible.
8298 */
8299 if (zap_contains(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
8300 DMU_POOL_CHECKSUM_SALT) == ENOENT) {
8301 VERIFY0(zap_add(spa->spa_meta_objset,
8302 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CHECKSUM_SALT, 1,
8303 sizeof (spa->spa_cksum_salt.zcs_bytes),
8304 spa->spa_cksum_salt.zcs_bytes, tx));
8305 }
8306
8307 rrw_exit(&dp->dp_config_rwlock, FTAG);
8308 }
8309
8310 static void
8311 vdev_indirect_state_sync_verify(vdev_t *vd)
8312 {
8313 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
8314 vdev_indirect_births_t *vib = vd->vdev_indirect_births;
8315
8316 if (vd->vdev_ops == &vdev_indirect_ops) {
8317 ASSERT(vim != NULL);
8318 ASSERT(vib != NULL);
8319 }
8320
8321 if (vdev_obsolete_sm_object(vd) != 0) {
8322 ASSERT(vd->vdev_obsolete_sm != NULL);
8323 ASSERT(vd->vdev_removing ||
8324 vd->vdev_ops == &vdev_indirect_ops);
8325 ASSERT(vdev_indirect_mapping_num_entries(vim) > 0);
8326 ASSERT(vdev_indirect_mapping_bytes_mapped(vim) > 0);
8327
8328 ASSERT3U(vdev_obsolete_sm_object(vd), ==,
8329 space_map_object(vd->vdev_obsolete_sm));
8330 ASSERT3U(vdev_indirect_mapping_bytes_mapped(vim), >=,
8331 space_map_allocated(vd->vdev_obsolete_sm));
8332 }
8333 ASSERT(vd->vdev_obsolete_segments != NULL);
8334
8335 /*
8336 * Since frees / remaps to an indirect vdev can only
8337 * happen in syncing context, the obsolete segments
8338 * tree must be empty when we start syncing.
8339 */
8340 ASSERT0(range_tree_space(vd->vdev_obsolete_segments));
8341 }
8342
8343 /*
8344 * Set the top-level vdev's max queue depth. Evaluate each top-level's
8345 * async write queue depth in case it changed. The max queue depth will
8346 * not change in the middle of syncing out this txg.
8347 */
8348 static void
8349 spa_sync_adjust_vdev_max_queue_depth(spa_t *spa)
8350 {
8351 ASSERT(spa_writeable(spa));
8352
8353 vdev_t *rvd = spa->spa_root_vdev;
8354 uint32_t max_queue_depth = zfs_vdev_async_write_max_active *
8355 zfs_vdev_queue_depth_pct / 100;
8356 metaslab_class_t *normal = spa_normal_class(spa);
8357 metaslab_class_t *special = spa_special_class(spa);
8358 metaslab_class_t *dedup = spa_dedup_class(spa);
8359
8360 uint64_t slots_per_allocator = 0;
8361 for (int c = 0; c < rvd->vdev_children; c++) {
8362 vdev_t *tvd = rvd->vdev_child[c];
8363
8364 metaslab_group_t *mg = tvd->vdev_mg;
8365 if (mg == NULL || !metaslab_group_initialized(mg))
8366 continue;
8367
8368 metaslab_class_t *mc = mg->mg_class;
8369 if (mc != normal && mc != special && mc != dedup)
8370 continue;
8371
8372 /*
8373 * It is safe to do a lock-free check here because only async
8374 * allocations look at mg_max_alloc_queue_depth, and async
8375 * allocations all happen from spa_sync().
8376 */
8377 for (int i = 0; i < spa->spa_alloc_count; i++)
8378 ASSERT0(zfs_refcount_count(
8379 &(mg->mg_alloc_queue_depth[i])));
8380 mg->mg_max_alloc_queue_depth = max_queue_depth;
8381
8382 for (int i = 0; i < spa->spa_alloc_count; i++) {
8383 mg->mg_cur_max_alloc_queue_depth[i] =
8384 zfs_vdev_def_queue_depth;
8385 }
8386 slots_per_allocator += zfs_vdev_def_queue_depth;
8387 }
8388
8389 for (int i = 0; i < spa->spa_alloc_count; i++) {
8390 ASSERT0(zfs_refcount_count(&normal->mc_alloc_slots[i]));
8391 ASSERT0(zfs_refcount_count(&special->mc_alloc_slots[i]));
8392 ASSERT0(zfs_refcount_count(&dedup->mc_alloc_slots[i]));
8393 normal->mc_alloc_max_slots[i] = slots_per_allocator;
8394 special->mc_alloc_max_slots[i] = slots_per_allocator;
8395 dedup->mc_alloc_max_slots[i] = slots_per_allocator;
8396 }
8397 normal->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
8398 special->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
8399 dedup->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
8400 }
8401
8402 static void
8403 spa_sync_condense_indirect(spa_t *spa, dmu_tx_t *tx)
8404 {
8405 ASSERT(spa_writeable(spa));
8406
8407 vdev_t *rvd = spa->spa_root_vdev;
8408 for (int c = 0; c < rvd->vdev_children; c++) {
8409 vdev_t *vd = rvd->vdev_child[c];
8410 vdev_indirect_state_sync_verify(vd);
8411
8412 if (vdev_indirect_should_condense(vd)) {
8413 spa_condense_indirect_start_sync(vd, tx);
8414 break;
8415 }
8416 }
8417 }
8418
8419 static void
8420 spa_sync_iterate_to_convergence(spa_t *spa, dmu_tx_t *tx)
8421 {
8422 objset_t *mos = spa->spa_meta_objset;
8423 dsl_pool_t *dp = spa->spa_dsl_pool;
8424 uint64_t txg = tx->tx_txg;
8425 bplist_t *free_bpl = &spa->spa_free_bplist[txg & TXG_MASK];
8426
8427 do {
8428 int pass = ++spa->spa_sync_pass;
8429
8430 spa_sync_config_object(spa, tx);
8431 spa_sync_aux_dev(spa, &spa->spa_spares, tx,
8432 ZPOOL_CONFIG_SPARES, DMU_POOL_SPARES);
8433 spa_sync_aux_dev(spa, &spa->spa_l2cache, tx,
8434 ZPOOL_CONFIG_L2CACHE, DMU_POOL_L2CACHE);
8435 spa_errlog_sync(spa, txg);
8436 dsl_pool_sync(dp, txg);
8437
8438 if (pass < zfs_sync_pass_deferred_free ||
8439 spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP)) {
8440 /*
8441 * If the log space map feature is active we don't
8442 * care about deferred frees and the deferred bpobj
8443 * as the log space map should effectively have the
8444 * same results (i.e. appending only to one object).
8445 */
8446 spa_sync_frees(spa, free_bpl, tx);
8447 } else {
8448 /*
8449 * We can not defer frees in pass 1, because
8450 * we sync the deferred frees later in pass 1.
8451 */
8452 ASSERT3U(pass, >, 1);
8453 bplist_iterate(free_bpl, bpobj_enqueue_cb,
8454 &spa->spa_deferred_bpobj, tx);
8455 }
8456
8457 ddt_sync(spa, txg);
8458 dsl_scan_sync(dp, tx);
8459 svr_sync(spa, tx);
8460 spa_sync_upgrades(spa, tx);
8461
8462 spa_flush_metaslabs(spa, tx);
8463
8464 vdev_t *vd = NULL;
8465 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, txg))
8466 != NULL)
8467 vdev_sync(vd, txg);
8468
8469 /*
8470 * Note: We need to check if the MOS is dirty because we could
8471 * have marked the MOS dirty without updating the uberblock
8472 * (e.g. if we have sync tasks but no dirty user data). We need
8473 * to check the uberblock's rootbp because it is updated if we
8474 * have synced out dirty data (though in this case the MOS will
8475 * most likely also be dirty due to second order effects, we
8476 * don't want to rely on that here).
8477 */
8478 if (pass == 1 &&
8479 spa->spa_uberblock.ub_rootbp.blk_birth < txg &&
8480 !dmu_objset_is_dirty(mos, txg)) {
8481 /*
8482 * Nothing changed on the first pass, therefore this
8483 * TXG is a no-op. Avoid syncing deferred frees, so
8484 * that we can keep this TXG as a no-op.
8485 */
8486 ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
8487 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
8488 ASSERT(txg_list_empty(&dp->dp_sync_tasks, txg));
8489 ASSERT(txg_list_empty(&dp->dp_early_sync_tasks, txg));
8490 break;
8491 }
8492
8493 spa_sync_deferred_frees(spa, tx);
8494 } while (dmu_objset_is_dirty(mos, txg));
8495 }
8496
8497 /*
8498 * Rewrite the vdev configuration (which includes the uberblock) to
8499 * commit the transaction group.
8500 *
8501 * If there are no dirty vdevs, we sync the uberblock to a few random
8502 * top-level vdevs that are known to be visible in the config cache
8503 * (see spa_vdev_add() for a complete description). If there *are* dirty
8504 * vdevs, sync the uberblock to all vdevs.
8505 */
8506 static void
8507 spa_sync_rewrite_vdev_config(spa_t *spa, dmu_tx_t *tx)
8508 {
8509 vdev_t *rvd = spa->spa_root_vdev;
8510 uint64_t txg = tx->tx_txg;
8511
8512 for (;;) {
8513 int error = 0;
8514
8515 /*
8516 * We hold SCL_STATE to prevent vdev open/close/etc.
8517 * while we're attempting to write the vdev labels.
8518 */
8519 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8520
8521 if (list_is_empty(&spa->spa_config_dirty_list)) {
8522 vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
8523 int svdcount = 0;
8524 int children = rvd->vdev_children;
8525 int c0 = spa_get_random(children);
8526
8527 for (int c = 0; c < children; c++) {
8528 vdev_t *vd =
8529 rvd->vdev_child[(c0 + c) % children];
8530
8531 /* Stop when revisiting the first vdev */
8532 if (c > 0 && svd[0] == vd)
8533 break;
8534
8535 if (vd->vdev_ms_array == 0 ||
8536 vd->vdev_islog ||
8537 !vdev_is_concrete(vd))
8538 continue;
8539
8540 svd[svdcount++] = vd;
8541 if (svdcount == SPA_SYNC_MIN_VDEVS)
8542 break;
8543 }
8544 error = vdev_config_sync(svd, svdcount, txg);
8545 } else {
8546 error = vdev_config_sync(rvd->vdev_child,
8547 rvd->vdev_children, txg);
8548 }
8549
8550 if (error == 0)
8551 spa->spa_last_synced_guid = rvd->vdev_guid;
8552
8553 spa_config_exit(spa, SCL_STATE, FTAG);
8554
8555 if (error == 0)
8556 break;
8557 zio_suspend(spa, NULL, ZIO_SUSPEND_IOERR);
8558 zio_resume_wait(spa);
8559 }
8560 }
8561
8562 /*
8563 * Sync the specified transaction group. New blocks may be dirtied as
8564 * part of the process, so we iterate until it converges.
8565 */
8566 void
8567 spa_sync(spa_t *spa, uint64_t txg)
8568 {
8569 vdev_t *vd = NULL;
8570
8571 VERIFY(spa_writeable(spa));
8572
8573 /*
8574 * Wait for i/os issued in open context that need to complete
8575 * before this txg syncs.
8576 */
8577 (void) zio_wait(spa->spa_txg_zio[txg & TXG_MASK]);
8578 spa->spa_txg_zio[txg & TXG_MASK] = zio_root(spa, NULL, NULL,
8579 ZIO_FLAG_CANFAIL);
8580
8581 /*
8582 * Lock out configuration changes.
8583 */
8584 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
8585
8586 spa->spa_syncing_txg = txg;
8587 spa->spa_sync_pass = 0;
8588
8589 for (int i = 0; i < spa->spa_alloc_count; i++) {
8590 mutex_enter(&spa->spa_alloc_locks[i]);
8591 VERIFY0(avl_numnodes(&spa->spa_alloc_trees[i]));
8592 mutex_exit(&spa->spa_alloc_locks[i]);
8593 }
8594
8595 /*
8596 * If there are any pending vdev state changes, convert them
8597 * into config changes that go out with this transaction group.
8598 */
8599 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8600 while (list_head(&spa->spa_state_dirty_list) != NULL) {
8601 /*
8602 * We need the write lock here because, for aux vdevs,
8603 * calling vdev_config_dirty() modifies sav_config.
8604 * This is ugly and will become unnecessary when we
8605 * eliminate the aux vdev wart by integrating all vdevs
8606 * into the root vdev tree.
8607 */
8608 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
8609 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_WRITER);
8610 while ((vd = list_head(&spa->spa_state_dirty_list)) != NULL) {
8611 vdev_state_clean(vd);
8612 vdev_config_dirty(vd);
8613 }
8614 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
8615 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
8616 }
8617 spa_config_exit(spa, SCL_STATE, FTAG);
8618
8619 dsl_pool_t *dp = spa->spa_dsl_pool;
8620 dmu_tx_t *tx = dmu_tx_create_assigned(dp, txg);
8621
8622 spa->spa_sync_starttime = gethrtime();
8623 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid,
8624 spa->spa_sync_starttime + spa->spa_deadman_synctime));
8625
8626 /*
8627 * If we are upgrading to SPA_VERSION_RAIDZ_DEFLATE this txg,
8628 * set spa_deflate if we have no raid-z vdevs.
8629 */
8630 if (spa->spa_ubsync.ub_version < SPA_VERSION_RAIDZ_DEFLATE &&
8631 spa->spa_uberblock.ub_version >= SPA_VERSION_RAIDZ_DEFLATE) {
8632 vdev_t *rvd = spa->spa_root_vdev;
8633
8634 int i;
8635 for (i = 0; i < rvd->vdev_children; i++) {
8636 vd = rvd->vdev_child[i];
8637 if (vd->vdev_deflate_ratio != SPA_MINBLOCKSIZE)
8638 break;
8639 }
8640 if (i == rvd->vdev_children) {
8641 spa->spa_deflate = TRUE;
8642 VERIFY0(zap_add(spa->spa_meta_objset,
8643 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
8644 sizeof (uint64_t), 1, &spa->spa_deflate, tx));
8645 }
8646 }
8647
8648 spa_sync_adjust_vdev_max_queue_depth(spa);
8649
8650 spa_sync_condense_indirect(spa, tx);
8651
8652 spa_sync_iterate_to_convergence(spa, tx);
8653
8654 #ifdef ZFS_DEBUG
8655 if (!list_is_empty(&spa->spa_config_dirty_list)) {
8656 /*
8657 * Make sure that the number of ZAPs for all the vdevs matches
8658 * the number of ZAPs in the per-vdev ZAP list. This only gets
8659 * called if the config is dirty; otherwise there may be
8660 * outstanding AVZ operations that weren't completed in
8661 * spa_sync_config_object.
8662 */
8663 uint64_t all_vdev_zap_entry_count;
8664 ASSERT0(zap_count(spa->spa_meta_objset,
8665 spa->spa_all_vdev_zaps, &all_vdev_zap_entry_count));
8666 ASSERT3U(vdev_count_verify_zaps(spa->spa_root_vdev), ==,
8667 all_vdev_zap_entry_count);
8668 }
8669 #endif
8670
8671 if (spa->spa_vdev_removal != NULL) {
8672 ASSERT0(spa->spa_vdev_removal->svr_bytes_done[txg & TXG_MASK]);
8673 }
8674
8675 spa_sync_rewrite_vdev_config(spa, tx);
8676 dmu_tx_commit(tx);
8677
8678 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid, CY_INFINITY));
8679
8680 /*
8681 * Clear the dirty config list.
8682 */
8683 while ((vd = list_head(&spa->spa_config_dirty_list)) != NULL)
8684 vdev_config_clean(vd);
8685
8686 /*
8687 * Now that the new config has synced transactionally,
8688 * let it become visible to the config cache.
8689 */
8690 if (spa->spa_config_syncing != NULL) {
8691 spa_config_set(spa, spa->spa_config_syncing);
8692 spa->spa_config_txg = txg;
8693 spa->spa_config_syncing = NULL;
8694 }
8695
8696 dsl_pool_sync_done(dp, txg);
8697
8698 for (int i = 0; i < spa->spa_alloc_count; i++) {
8699 mutex_enter(&spa->spa_alloc_locks[i]);
8700 VERIFY0(avl_numnodes(&spa->spa_alloc_trees[i]));
8701 mutex_exit(&spa->spa_alloc_locks[i]);
8702 }
8703
8704 /*
8705 * Update usable space statistics.
8706 */
8707 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)))
8708 != NULL)
8709 vdev_sync_done(vd, txg);
8710
8711 metaslab_class_evict_old(spa->spa_normal_class, txg);
8712 metaslab_class_evict_old(spa->spa_log_class, txg);
8713
8714 spa_sync_close_syncing_log_sm(spa);
8715
8716 spa_update_dspace(spa);
8717
8718 /*
8719 * It had better be the case that we didn't dirty anything
8720 * since vdev_config_sync().
8721 */
8722 ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
8723 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
8724 ASSERT(txg_list_empty(&spa->spa_vdev_txg_list, txg));
8725
8726 while (zfs_pause_spa_sync)
8727 delay(1);
8728
8729 spa->spa_sync_pass = 0;
8730
8731 /*
8732 * Update the last synced uberblock here. We want to do this at
8733 * the end of spa_sync() so that consumers of spa_last_synced_txg()
8734 * will be guaranteed that all the processing associated with
8735 * that txg has been completed.
8736 */
8737 spa->spa_ubsync = spa->spa_uberblock;
8738 spa_config_exit(spa, SCL_CONFIG, FTAG);
8739
8740 spa_handle_ignored_writes(spa);
8741
8742 /* Mark unused spares as needing a health check. */
8743 if (spa_spare_poll_interval_seconds != 0 &&
8744 NSEC2SEC(gethrtime() - spa->spa_spares_last_polled) >
8745 spa_spare_poll_interval_seconds) {
8746 spa_spare_poll(spa);
8747 spa->spa_spares_last_polled = gethrtime();
8748 }
8749
8750 /*
8751 * If any async tasks have been requested, kick them off.
8752 */
8753 spa_async_dispatch(spa);
8754 }
8755
8756 /*
8757 * Sync all pools. We don't want to hold the namespace lock across these
8758 * operations, so we take a reference on the spa_t and drop the lock during the
8759 * sync.
8760 */
8761 void
8762 spa_sync_allpools(void)
8763 {
8764 spa_t *spa = NULL;
8765 mutex_enter(&spa_namespace_lock);
8766 while ((spa = spa_next(spa)) != NULL) {
8767 if (spa_state(spa) != POOL_STATE_ACTIVE ||
8768 !spa_writeable(spa) || spa_suspended(spa))
8769 continue;
8770 spa_open_ref(spa, FTAG);
8771 mutex_exit(&spa_namespace_lock);
8772 txg_wait_synced(spa_get_dsl(spa), 0);
8773 mutex_enter(&spa_namespace_lock);
8774 spa_close(spa, FTAG);
8775 }
8776 mutex_exit(&spa_namespace_lock);
8777 }
8778
8779 /*
8780 * ==========================================================================
8781 * Miscellaneous routines
8782 * ==========================================================================
8783 */
8784
8785 /*
8786 * Remove all pools in the system.
8787 */
8788 void
8789 spa_evict_all(void)
8790 {
8791 spa_t *spa;
8792
8793 /*
8794 * Remove all cached state. All pools should be closed now,
8795 * so every spa in the AVL tree should be unreferenced.
8796 */
8797 mutex_enter(&spa_namespace_lock);
8798 while ((spa = spa_next(NULL)) != NULL) {
8799 /*
8800 * Stop async tasks. The async thread may need to detach
8801 * a device that's been replaced, which requires grabbing
8802 * spa_namespace_lock, so we must drop it here.
8803 */
8804 spa_open_ref(spa, FTAG);
8805 mutex_exit(&spa_namespace_lock);
8806 spa_async_suspend(spa);
8807 mutex_enter(&spa_namespace_lock);
8808 spa_close(spa, FTAG);
8809
8810 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
8811 spa_unload(spa);
8812 spa_deactivate(spa);
8813 }
8814 spa_remove(spa);
8815 }
8816 mutex_exit(&spa_namespace_lock);
8817 }
8818
8819 vdev_t *
8820 spa_lookup_by_guid(spa_t *spa, uint64_t guid, boolean_t aux)
8821 {
8822 vdev_t *vd;
8823 int i;
8824
8825 if ((vd = vdev_lookup_by_guid(spa->spa_root_vdev, guid)) != NULL)
8826 return (vd);
8827
8828 if (aux) {
8829 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
8830 vd = spa->spa_l2cache.sav_vdevs[i];
8831 if (vd->vdev_guid == guid)
8832 return (vd);
8833 }
8834
8835 for (i = 0; i < spa->spa_spares.sav_count; i++) {
8836 vd = spa->spa_spares.sav_vdevs[i];
8837 if (vd->vdev_guid == guid)
8838 return (vd);
8839 }
8840 }
8841
8842 return (NULL);
8843 }
8844
8845 void
8846 spa_upgrade(spa_t *spa, uint64_t version)
8847 {
8848 ASSERT(spa_writeable(spa));
8849
8850 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
8851
8852 /*
8853 * This should only be called for a non-faulted pool, and since a
8854 * future version would result in an unopenable pool, this shouldn't be
8855 * possible.
8856 */
8857 ASSERT(SPA_VERSION_IS_SUPPORTED(spa->spa_uberblock.ub_version));
8858 ASSERT3U(version, >=, spa->spa_uberblock.ub_version);
8859
8860 spa->spa_uberblock.ub_version = version;
8861 vdev_config_dirty(spa->spa_root_vdev);
8862
8863 spa_config_exit(spa, SCL_ALL, FTAG);
8864
8865 txg_wait_synced(spa_get_dsl(spa), 0);
8866 }
8867
8868 boolean_t
8869 spa_has_spare(spa_t *spa, uint64_t guid)
8870 {
8871 int i;
8872 uint64_t spareguid;
8873 spa_aux_vdev_t *sav = &spa->spa_spares;
8874
8875 for (i = 0; i < sav->sav_count; i++)
8876 if (sav->sav_vdevs[i]->vdev_guid == guid)
8877 return (B_TRUE);
8878
8879 for (i = 0; i < sav->sav_npending; i++) {
8880 if (nvlist_lookup_uint64(sav->sav_pending[i], ZPOOL_CONFIG_GUID,
8881 &spareguid) == 0 && spareguid == guid)
8882 return (B_TRUE);
8883 }
8884
8885 return (B_FALSE);
8886 }
8887
8888 /*
8889 * Check if a pool has an active shared spare device.
8890 * Note: reference count of an active spare is 2, as a spare and as a replace
8891 */
8892 static boolean_t
8893 spa_has_active_shared_spare(spa_t *spa)
8894 {
8895 int i, refcnt;
8896 uint64_t pool;
8897 spa_aux_vdev_t *sav = &spa->spa_spares;
8898
8899 for (i = 0; i < sav->sav_count; i++) {
8900 if (spa_spare_exists(sav->sav_vdevs[i]->vdev_guid, &pool,
8901 &refcnt) && pool != 0ULL && pool == spa_guid(spa) &&
8902 refcnt > 2)
8903 return (B_TRUE);
8904 }
8905
8906 return (B_FALSE);
8907 }
8908
8909 uint64_t
8910 spa_total_metaslabs(spa_t *spa)
8911 {
8912 vdev_t *rvd = spa->spa_root_vdev;
8913 uint64_t m = 0;
8914
8915 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
8916 vdev_t *vd = rvd->vdev_child[c];
8917 if (!vdev_is_concrete(vd))
8918 continue;
8919 m += vd->vdev_ms_count;
8920 }
8921 return (m);
8922 }
8923
8924 /*
8925 * Notify any waiting threads that some activity has switched from being in-
8926 * progress to not-in-progress so that the thread can wake up and determine
8927 * whether it is finished waiting.
8928 */
8929 void
8930 spa_notify_waiters(spa_t *spa)
8931 {
8932 /*
8933 * Acquiring spa_activities_lock here prevents the cv_broadcast from
8934 * happening between the waiting thread's check and cv_wait.
8935 */
8936 mutex_enter(&spa->spa_activities_lock);
8937 cv_broadcast(&spa->spa_activities_cv);
8938 mutex_exit(&spa->spa_activities_lock);
8939 }
8940
8941 /*
8942 * Notify any waiting threads that the pool is exporting, and then block until
8943 * they are finished using the spa_t.
8944 */
8945 void
8946 spa_wake_waiters(spa_t *spa)
8947 {
8948 mutex_enter(&spa->spa_activities_lock);
8949 spa->spa_waiters_cancel = B_TRUE;
8950 cv_broadcast(&spa->spa_activities_cv);
8951 while (spa->spa_waiters != 0)
8952 cv_wait(&spa->spa_waiters_cv, &spa->spa_activities_lock);
8953 spa->spa_waiters_cancel = B_FALSE;
8954 mutex_exit(&spa->spa_activities_lock);
8955 }
8956
8957 /* Whether the vdev or any of its descendants is initializing. */
8958 static boolean_t
8959 spa_vdev_initializing_impl(vdev_t *vd)
8960 {
8961 spa_t *spa = vd->vdev_spa;
8962 boolean_t initializing;
8963
8964 ASSERT(spa_config_held(spa, SCL_CONFIG | SCL_STATE, RW_READER));
8965 ASSERT(MUTEX_HELD(&spa->spa_activities_lock));
8966
8967 mutex_exit(&spa->spa_activities_lock);
8968 mutex_enter(&vd->vdev_initialize_lock);
8969 mutex_enter(&spa->spa_activities_lock);
8970
8971 initializing = (vd->vdev_initialize_state == VDEV_INITIALIZE_ACTIVE);
8972 mutex_exit(&vd->vdev_initialize_lock);
8973
8974 if (initializing)
8975 return (B_TRUE);
8976
8977 for (int i = 0; i < vd->vdev_children; i++) {
8978 if (spa_vdev_initializing_impl(vd->vdev_child[i]))
8979 return (B_TRUE);
8980 }
8981
8982 return (B_FALSE);
8983 }
8984
8985 /*
8986 * If use_guid is true, this checks whether the vdev specified by guid is
8987 * being initialized. Otherwise, it checks whether any vdev in the pool is being
8988 * initialized. The caller must hold the config lock and spa_activities_lock.
8989 */
8990 static int
8991 spa_vdev_initializing(spa_t *spa, boolean_t use_guid, uint64_t guid,
8992 boolean_t *in_progress)
8993 {
8994 mutex_exit(&spa->spa_activities_lock);
8995 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
8996 mutex_enter(&spa->spa_activities_lock);
8997
8998 vdev_t *vd;
8999 if (use_guid) {
9000 vd = spa_lookup_by_guid(spa, guid, B_FALSE);
9001 if (vd == NULL || !vd->vdev_ops->vdev_op_leaf) {
9002 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
9003 return (EINVAL);
9004 }
9005 } else {
9006 vd = spa->spa_root_vdev;
9007 }
9008
9009 *in_progress = spa_vdev_initializing_impl(vd);
9010
9011 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
9012 return (0);
9013 }
9014
9015 /*
9016 * Locking for waiting threads
9017 * ---------------------------
9018 *
9019 * Waiting threads need a way to check whether a given activity is in progress,
9020 * and then, if it is, wait for it to complete. Each activity will have some
9021 * in-memory representation of the relevant on-disk state which can be used to
9022 * determine whether or not the activity is in progress. The in-memory state and
9023 * the locking used to protect it will be different for each activity, and may
9024 * not be suitable for use with a cvar (e.g., some state is protected by the
9025 * config lock). To allow waiting threads to wait without any races, another
9026 * lock, spa_activities_lock, is used.
9027 *
9028 * When the state is checked, both the activity-specific lock (if there is one)
9029 * and spa_activities_lock are held. In some cases, the activity-specific lock
9030 * is acquired explicitly (e.g. the config lock). In others, the locking is
9031 * internal to some check (e.g. bpobj_is_empty). After checking, the waiting
9032 * thread releases the activity-specific lock and, if the activity is in
9033 * progress, then cv_waits using spa_activities_lock.
9034 *
9035 * The waiting thread is woken when another thread, one completing some
9036 * activity, updates the state of the activity and then calls
9037 * spa_notify_waiters, which will cv_broadcast. This 'completing' thread only
9038 * needs to hold its activity-specific lock when updating the state, and this
9039 * lock can (but doesn't have to) be dropped before calling spa_notify_waiters.
9040 *
9041 * Because spa_notify_waiters acquires spa_activities_lock before broadcasting,
9042 * and because it is held when the waiting thread checks the state of the
9043 * activity, it can never be the case that the completing thread both updates
9044 * the activity state and cv_broadcasts in between the waiting thread's check
9045 * and cv_wait. Thus, a waiting thread can never miss a wakeup.
9046 *
9047 * In order to prevent deadlock, when the waiting thread does its check, in some
9048 * cases it will temporarily drop spa_activities_lock in order to acquire the
9049 * activity-specific lock. The order in which spa_activities_lock and the
9050 * activity specific lock are acquired in the waiting thread is determined by
9051 * the order in which they are acquired in the completing thread; if the
9052 * completing thread calls spa_notify_waiters with the activity-specific lock
9053 * held, then the waiting thread must also acquire the activity-specific lock
9054 * first.
9055 */
9056
9057 static int
9058 spa_activity_in_progress(spa_t *spa, zpool_wait_activity_t activity,
9059 boolean_t use_tag, uint64_t tag, boolean_t *in_progress)
9060 {
9061 int error = 0;
9062
9063 ASSERT(MUTEX_HELD(&spa->spa_activities_lock));
9064
9065 switch (activity) {
9066 case ZPOOL_WAIT_CKPT_DISCARD:
9067 *in_progress =
9068 (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT) &&
9069 zap_contains(spa_meta_objset(spa),
9070 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_ZPOOL_CHECKPOINT) ==
9071 ENOENT);
9072 break;
9073 case ZPOOL_WAIT_FREE:
9074 *in_progress = ((spa_version(spa) >= SPA_VERSION_DEADLISTS &&
9075 !bpobj_is_empty(&spa->spa_dsl_pool->dp_free_bpobj)) ||
9076 spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY));
9077 break;
9078 case ZPOOL_WAIT_INITIALIZE:
9079 error = spa_vdev_initializing(spa, use_tag, tag, in_progress);
9080 break;
9081 case ZPOOL_WAIT_REPLACE:
9082 mutex_exit(&spa->spa_activities_lock);
9083 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
9084 mutex_enter(&spa->spa_activities_lock);
9085
9086 *in_progress = vdev_replace_in_progress(spa->spa_root_vdev);
9087 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
9088 break;
9089 case ZPOOL_WAIT_REMOVE:
9090 *in_progress = (spa->spa_removing_phys.sr_state ==
9091 DSS_SCANNING);
9092 break;
9093 case ZPOOL_WAIT_RESILVER:
9094 case ZPOOL_WAIT_SCRUB:
9095 {
9096 boolean_t scanning, paused, is_scrub;
9097 dsl_scan_t *scn = spa->spa_dsl_pool->dp_scan;
9098
9099 is_scrub = (scn->scn_phys.scn_func == POOL_SCAN_SCRUB);
9100 scanning = (scn->scn_phys.scn_state == DSS_SCANNING);
9101 paused = dsl_scan_is_paused_scrub(scn);
9102 *in_progress = (scanning && !paused &&
9103 is_scrub == (activity == ZPOOL_WAIT_SCRUB));
9104 break;
9105 }
9106 default:
9107 panic("unrecognized value for activity %d", activity);
9108 }
9109
9110 return (error);
9111 }
9112
9113 static int
9114 spa_wait_common(const char *pool, zpool_wait_activity_t activity,
9115 boolean_t use_tag, uint64_t tag, boolean_t *waited)
9116 {
9117 /*
9118 * The tag is used to distinguish between instances of an activity.
9119 * 'initialize' is the only activity that we use this for. The other
9120 * activities can only have a single instance in progress in a pool at
9121 * one time, making the tag unnecessary.
9122 *
9123 * There can be multiple devices being replaced at once, but since they
9124 * all finish once resilvering finishes, we don't bother keeping track
9125 * of them individually, we just wait for them all to finish.
9126 */
9127 if (use_tag && activity != ZPOOL_WAIT_INITIALIZE)
9128 return (EINVAL);
9129
9130 if (activity < 0 || activity >= ZPOOL_WAIT_NUM_ACTIVITIES)
9131 return (EINVAL);
9132
9133 spa_t *spa;
9134 int error = spa_open(pool, &spa, FTAG);
9135 if (error != 0)
9136 return (error);
9137
9138 /*
9139 * Increment the spa's waiter count so that we can call spa_close and
9140 * still ensure that the spa_t doesn't get freed before this thread is
9141 * finished with it when the pool is exported. We want to call spa_close
9142 * before we start waiting because otherwise the additional ref would
9143 * prevent the pool from being exported or destroyed throughout the
9144 * potentially long wait.
9145 */
9146 mutex_enter(&spa->spa_activities_lock);
9147 spa->spa_waiters++;
9148 spa_close(spa, FTAG);
9149
9150 *waited = B_FALSE;
9151 for (;;) {
9152 boolean_t in_progress;
9153 error = spa_activity_in_progress(spa, activity, use_tag, tag,
9154 &in_progress);
9155
9156 if (!in_progress || spa->spa_waiters_cancel || error)
9157 break;
9158
9159 *waited = B_TRUE;
9160
9161 if (cv_wait_sig(&spa->spa_activities_cv,
9162 &spa->spa_activities_lock) == 0) {
9163 error = EINTR;
9164 break;
9165 }
9166 }
9167
9168 spa->spa_waiters--;
9169 cv_signal(&spa->spa_waiters_cv);
9170 mutex_exit(&spa->spa_activities_lock);
9171
9172 return (error);
9173 }
9174
9175 /*
9176 * Wait for a particular instance of the specified activity to complete, where
9177 * the instance is identified by 'tag'
9178 */
9179 int
9180 spa_wait_tag(const char *pool, zpool_wait_activity_t activity, uint64_t tag,
9181 boolean_t *waited)
9182 {
9183 return (spa_wait_common(pool, activity, B_TRUE, tag, waited));
9184 }
9185
9186 /*
9187 * Wait for all instances of the specified activity complete
9188 */
9189 int
9190 spa_wait(const char *pool, zpool_wait_activity_t activity, boolean_t *waited)
9191 {
9192
9193 return (spa_wait_common(pool, activity, B_FALSE, 0, waited));
9194 }
9195
9196 sysevent_t *
9197 spa_event_create(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
9198 {
9199 sysevent_t *ev = NULL;
9200 #ifdef _KERNEL
9201 sysevent_attr_list_t *attr = NULL;
9202 sysevent_value_t value;
9203
9204 ev = sysevent_alloc(EC_ZFS, (char *)name, SUNW_KERN_PUB "zfs",
9205 SE_SLEEP);
9206 ASSERT(ev != NULL);
9207
9208 value.value_type = SE_DATA_TYPE_STRING;
9209 value.value.sv_string = spa_name(spa);
9210 if (sysevent_add_attr(&attr, ZFS_EV_POOL_NAME, &value, SE_SLEEP) != 0)
9211 goto done;
9212
9213 value.value_type = SE_DATA_TYPE_UINT64;
9214 value.value.sv_uint64 = spa_guid(spa);
9215 if (sysevent_add_attr(&attr, ZFS_EV_POOL_GUID, &value, SE_SLEEP) != 0)
9216 goto done;
9217
9218 if (vd) {
9219 value.value_type = SE_DATA_TYPE_UINT64;
9220 value.value.sv_uint64 = vd->vdev_guid;
9221 if (sysevent_add_attr(&attr, ZFS_EV_VDEV_GUID, &value,
9222 SE_SLEEP) != 0)
9223 goto done;
9224
9225 if (vd->vdev_path) {
9226 value.value_type = SE_DATA_TYPE_STRING;
9227 value.value.sv_string = vd->vdev_path;
9228 if (sysevent_add_attr(&attr, ZFS_EV_VDEV_PATH,
9229 &value, SE_SLEEP) != 0)
9230 goto done;
9231 }
9232 }
9233
9234 if (hist_nvl != NULL) {
9235 fnvlist_merge((nvlist_t *)attr, hist_nvl);
9236 }
9237
9238 if (sysevent_attach_attributes(ev, attr) != 0)
9239 goto done;
9240 attr = NULL;
9241
9242 done:
9243 if (attr)
9244 sysevent_free_attr(attr);
9245
9246 #endif
9247 return (ev);
9248 }
9249
9250 void
9251 spa_event_post(sysevent_t *ev)
9252 {
9253 #ifdef _KERNEL
9254 sysevent_id_t eid;
9255
9256 (void) log_sysevent(ev, SE_SLEEP, &eid);
9257 sysevent_free(ev);
9258 #endif
9259 }
9260
9261 void
9262 spa_event_discard(sysevent_t *ev)
9263 {
9264 #ifdef _KERNEL
9265 sysevent_free(ev);
9266 #endif
9267 }
9268
9269 /*
9270 * Post a sysevent corresponding to the given event. The 'name' must be one of
9271 * the event definitions in sys/sysevent/eventdefs.h. The payload will be
9272 * filled in from the spa and (optionally) the vdev and history nvl. This
9273 * doesn't do anything in the userland libzpool, as we don't want consumers to
9274 * misinterpret ztest or zdb as real changes.
9275 */
9276 void
9277 spa_event_notify(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
9278 {
9279 spa_event_post(spa_event_create(spa, vd, hist_nvl, name));
9280 }
9281