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