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