]> git.proxmox.com Git - mirror_zfs.git/blame - module/zfs/spa.c
Minimize aggsum_compare(&arc_size, arc_c) calls.
[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{
fcff0f35 2122 if (bp == NULL || BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
dea377c0
MA
2123 return (0);
2124 /*
2125 * Note: normally this routine will not be called if
2126 * spa_load_verify_metadata is not set. However, it may be useful
2127 * to manually set the flag after the traversal has begun.
2128 */
2129 if (!spa_load_verify_metadata)
2130 return (0);
a6255b7f 2131 if (!BP_IS_METADATA(bp) && !spa_load_verify_data)
dea377c0
MA
2132 return (0);
2133
1c27024e
DB
2134 zio_t *rio = arg;
2135 size_t size = BP_GET_PSIZE(bp);
dea377c0
MA
2136
2137 mutex_enter(&spa->spa_scrub_lock);
d4a72f23 2138 while (spa->spa_load_verify_ios >= spa_load_verify_maxinflight)
dea377c0 2139 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
d4a72f23 2140 spa->spa_load_verify_ios++;
dea377c0
MA
2141 mutex_exit(&spa->spa_scrub_lock);
2142
a6255b7f 2143 zio_nowait(zio_read(rio, spa, bp, abd_alloc_for_io(size, B_FALSE), size,
dea377c0
MA
2144 spa_load_verify_done, rio->io_private, ZIO_PRIORITY_SCRUB,
2145 ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CANFAIL |
2146 ZIO_FLAG_SCRUB | ZIO_FLAG_RAW, zb));
428870ff
BB
2147 return (0);
2148}
34dc7c2f 2149
d1d19c78
PD
2150/* ARGSUSED */
2151int
2152verify_dataset_name_len(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
2153{
2154 if (dsl_dataset_namelen(ds) >= ZFS_MAX_DATASET_NAME_LEN)
2155 return (SET_ERROR(ENAMETOOLONG));
2156
2157 return (0);
2158}
2159
428870ff
BB
2160static int
2161spa_load_verify(spa_t *spa)
2162{
2163 zio_t *rio;
2164 spa_load_error_t sle = { 0 };
8a393be3 2165 zpool_load_policy_t policy;
428870ff 2166 boolean_t verify_ok = B_FALSE;
dea377c0 2167 int error = 0;
34dc7c2f 2168
8a393be3 2169 zpool_get_load_policy(spa->spa_config, &policy);
34dc7c2f 2170
8a393be3 2171 if (policy.zlp_rewind & ZPOOL_NEVER_REWIND)
428870ff 2172 return (0);
34dc7c2f 2173
d1d19c78
PD
2174 dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
2175 error = dmu_objset_find_dp(spa->spa_dsl_pool,
2176 spa->spa_dsl_pool->dp_root_dir_obj, verify_dataset_name_len, NULL,
2177 DS_FIND_CHILDREN);
2178 dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
2179 if (error != 0)
2180 return (error);
2181
428870ff
BB
2182 rio = zio_root(spa, NULL, &sle,
2183 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
34dc7c2f 2184
dea377c0 2185 if (spa_load_verify_metadata) {
4a0ee12a
PZ
2186 if (spa->spa_extreme_rewind) {
2187 spa_load_note(spa, "performing a complete scan of the "
2188 "pool since extreme rewind is on. This may take "
2189 "a very long time.\n (spa_load_verify_data=%u, "
2190 "spa_load_verify_metadata=%u)",
2191 spa_load_verify_data, spa_load_verify_metadata);
2192 }
dea377c0 2193 error = traverse_pool(spa, spa->spa_verify_min_txg,
b5256303
TC
2194 TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
2195 TRAVERSE_NO_DECRYPT, spa_load_verify_cb, rio);
dea377c0 2196 }
428870ff
BB
2197
2198 (void) zio_wait(rio);
2199
2200 spa->spa_load_meta_errors = sle.sle_meta_count;
2201 spa->spa_load_data_errors = sle.sle_data_count;
2202
afd2f7b7
PZ
2203 if (sle.sle_meta_count != 0 || sle.sle_data_count != 0) {
2204 spa_load_note(spa, "spa_load_verify found %llu metadata errors "
2205 "and %llu data errors", (u_longlong_t)sle.sle_meta_count,
2206 (u_longlong_t)sle.sle_data_count);
2207 }
2208
2209 if (spa_load_verify_dryrun ||
8a393be3
PZ
2210 (!error && sle.sle_meta_count <= policy.zlp_maxmeta &&
2211 sle.sle_data_count <= policy.zlp_maxdata)) {
572e2857
BB
2212 int64_t loss = 0;
2213
428870ff
BB
2214 verify_ok = B_TRUE;
2215 spa->spa_load_txg = spa->spa_uberblock.ub_txg;
2216 spa->spa_load_txg_ts = spa->spa_uberblock.ub_timestamp;
572e2857
BB
2217
2218 loss = spa->spa_last_ubsync_txg_ts - spa->spa_load_txg_ts;
2219 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2220 ZPOOL_CONFIG_LOAD_TIME, spa->spa_load_txg_ts) == 0);
2221 VERIFY(nvlist_add_int64(spa->spa_load_info,
2222 ZPOOL_CONFIG_REWIND_TIME, loss) == 0);
2223 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2224 ZPOOL_CONFIG_LOAD_DATA_ERRORS, sle.sle_data_count) == 0);
428870ff
BB
2225 } else {
2226 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg;
2227 }
2228
afd2f7b7
PZ
2229 if (spa_load_verify_dryrun)
2230 return (0);
2231
428870ff
BB
2232 if (error) {
2233 if (error != ENXIO && error != EIO)
2e528b49 2234 error = SET_ERROR(EIO);
428870ff
BB
2235 return (error);
2236 }
2237
2238 return (verify_ok ? 0 : EIO);
2239}
2240
2241/*
2242 * Find a value in the pool props object.
2243 */
2244static void
2245spa_prop_find(spa_t *spa, zpool_prop_t prop, uint64_t *val)
2246{
2247 (void) zap_lookup(spa->spa_meta_objset, spa->spa_pool_props_object,
2248 zpool_prop_to_name(prop), sizeof (uint64_t), 1, val);
2249}
2250
2251/*
2252 * Find a value in the pool directory object.
2253 */
2254static int
4a0ee12a 2255spa_dir_prop(spa_t *spa, const char *name, uint64_t *val, boolean_t log_enoent)
428870ff 2256{
4a0ee12a
PZ
2257 int error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
2258 name, sizeof (uint64_t), 1, val);
2259
2260 if (error != 0 && (error != ENOENT || log_enoent)) {
2261 spa_load_failed(spa, "couldn't get '%s' value in MOS directory "
2262 "[error=%d]", name, error);
2263 }
2264
2265 return (error);
428870ff
BB
2266}
2267
2268static int
2269spa_vdev_err(vdev_t *vdev, vdev_aux_t aux, int err)
2270{
2271 vdev_set_state(vdev, B_TRUE, VDEV_STATE_CANT_OPEN, aux);
a1d477c2 2272 return (SET_ERROR(err));
428870ff
BB
2273}
2274
9d5b5245
SD
2275static void
2276spa_spawn_aux_threads(spa_t *spa)
2277{
2278 ASSERT(spa_writeable(spa));
2279
2280 ASSERT(MUTEX_HELD(&spa_namespace_lock));
2281
2282 spa_start_indirect_condensing_thread(spa);
d2734cce
SD
2283
2284 ASSERT3P(spa->spa_checkpoint_discard_zthr, ==, NULL);
2285 spa->spa_checkpoint_discard_zthr =
2286 zthr_create(spa_checkpoint_discard_thread_check,
2287 spa_checkpoint_discard_thread, spa);
9d5b5245
SD
2288}
2289
428870ff
BB
2290/*
2291 * Fix up config after a partly-completed split. This is done with the
2292 * ZPOOL_CONFIG_SPLIT nvlist. Both the splitting pool and the split-off
2293 * pool have that entry in their config, but only the splitting one contains
2294 * a list of all the guids of the vdevs that are being split off.
2295 *
2296 * This function determines what to do with that list: either rejoin
2297 * all the disks to the pool, or complete the splitting process. To attempt
2298 * the rejoin, each disk that is offlined is marked online again, and
2299 * we do a reopen() call. If the vdev label for every disk that was
2300 * marked online indicates it was successfully split off (VDEV_AUX_SPLIT_POOL)
2301 * then we call vdev_split() on each disk, and complete the split.
2302 *
2303 * Otherwise we leave the config alone, with all the vdevs in place in
2304 * the original pool.
2305 */
2306static void
2307spa_try_repair(spa_t *spa, nvlist_t *config)
2308{
2309 uint_t extracted;
2310 uint64_t *glist;
2311 uint_t i, gcount;
2312 nvlist_t *nvl;
2313 vdev_t **vd;
2314 boolean_t attempt_reopen;
2315
2316 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) != 0)
2317 return;
2318
2319 /* check that the config is complete */
2320 if (nvlist_lookup_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
2321 &glist, &gcount) != 0)
2322 return;
2323
79c76d5b 2324 vd = kmem_zalloc(gcount * sizeof (vdev_t *), KM_SLEEP);
428870ff
BB
2325
2326 /* attempt to online all the vdevs & validate */
2327 attempt_reopen = B_TRUE;
2328 for (i = 0; i < gcount; i++) {
2329 if (glist[i] == 0) /* vdev is hole */
2330 continue;
2331
2332 vd[i] = spa_lookup_by_guid(spa, glist[i], B_FALSE);
2333 if (vd[i] == NULL) {
2334 /*
2335 * Don't bother attempting to reopen the disks;
2336 * just do the split.
2337 */
2338 attempt_reopen = B_FALSE;
2339 } else {
2340 /* attempt to re-online it */
2341 vd[i]->vdev_offline = B_FALSE;
2342 }
2343 }
2344
2345 if (attempt_reopen) {
2346 vdev_reopen(spa->spa_root_vdev);
2347
2348 /* check each device to see what state it's in */
2349 for (extracted = 0, i = 0; i < gcount; i++) {
2350 if (vd[i] != NULL &&
2351 vd[i]->vdev_stat.vs_aux != VDEV_AUX_SPLIT_POOL)
2352 break;
2353 ++extracted;
2354 }
2355 }
2356
2357 /*
2358 * If every disk has been moved to the new pool, or if we never
2359 * even attempted to look at them, then we split them off for
2360 * good.
2361 */
2362 if (!attempt_reopen || gcount == extracted) {
2363 for (i = 0; i < gcount; i++)
2364 if (vd[i] != NULL)
2365 vdev_split(vd[i]);
2366 vdev_reopen(spa->spa_root_vdev);
2367 }
2368
2369 kmem_free(vd, gcount * sizeof (vdev_t *));
2370}
2371
2372static int
6cb8e530 2373spa_load(spa_t *spa, spa_load_state_t state, spa_import_type_t type)
428870ff 2374{
428870ff
BB
2375 char *ereport = FM_EREPORT_ZFS_POOL;
2376 int error;
428870ff 2377
6cb8e530 2378 spa->spa_load_state = state;
ca95f70d
OF
2379 (void) spa_import_progress_set_state(spa_guid(spa),
2380 spa_load_state(spa));
9ae529ec 2381
6cb8e530 2382 gethrestime(&spa->spa_loaded_ts);
d2734cce 2383 error = spa_load_impl(spa, type, &ereport);
428870ff 2384
0c66c32d
JG
2385 /*
2386 * Don't count references from objsets that are already closed
2387 * and are making their way through the eviction process.
2388 */
2389 spa_evicting_os_wait(spa);
424fd7c3 2390 spa->spa_minref = zfs_refcount_count(&spa->spa_refcount);
572e2857
BB
2391 if (error) {
2392 if (error != EEXIST) {
2393 spa->spa_loaded_ts.tv_sec = 0;
2394 spa->spa_loaded_ts.tv_nsec = 0;
2395 }
2396 if (error != EBADF) {
b5256303 2397 zfs_ereport_post(ereport, spa, NULL, NULL, NULL, 0, 0);
572e2857
BB
2398 }
2399 }
428870ff
BB
2400 spa->spa_load_state = error ? SPA_LOAD_ERROR : SPA_LOAD_NONE;
2401 spa->spa_ena = 0;
2402
ca95f70d
OF
2403 (void) spa_import_progress_set_state(spa_guid(spa),
2404 spa_load_state(spa));
2405
428870ff
BB
2406 return (error);
2407}
2408
33cf67cd 2409#ifdef ZFS_DEBUG
e0ab3ab5
JS
2410/*
2411 * Count the number of per-vdev ZAPs associated with all of the vdevs in the
2412 * vdev tree rooted in the given vd, and ensure that each ZAP is present in the
2413 * spa's per-vdev ZAP list.
2414 */
2415static uint64_t
2416vdev_count_verify_zaps(vdev_t *vd)
2417{
2418 spa_t *spa = vd->vdev_spa;
2419 uint64_t total = 0;
e0ab3ab5
JS
2420
2421 if (vd->vdev_top_zap != 0) {
2422 total++;
2423 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2424 spa->spa_all_vdev_zaps, vd->vdev_top_zap));
2425 }
2426 if (vd->vdev_leaf_zap != 0) {
2427 total++;
2428 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2429 spa->spa_all_vdev_zaps, vd->vdev_leaf_zap));
2430 }
2431
1c27024e 2432 for (uint64_t i = 0; i < vd->vdev_children; i++) {
e0ab3ab5
JS
2433 total += vdev_count_verify_zaps(vd->vdev_child[i]);
2434 }
2435
2436 return (total);
2437}
33cf67cd 2438#endif
e0ab3ab5 2439
379ca9cf
OF
2440/*
2441 * Determine whether the activity check is required.
2442 */
2443static boolean_t
bbffb59e
BB
2444spa_activity_check_required(spa_t *spa, uberblock_t *ub, nvlist_t *label,
2445 nvlist_t *config)
379ca9cf
OF
2446{
2447 uint64_t state = 0;
2448 uint64_t hostid = 0;
2449 uint64_t tryconfig_txg = 0;
2450 uint64_t tryconfig_timestamp = 0;
060f0226 2451 uint16_t tryconfig_mmp_seq = 0;
379ca9cf
OF
2452 nvlist_t *nvinfo;
2453
2454 if (nvlist_exists(config, ZPOOL_CONFIG_LOAD_INFO)) {
2455 nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
2456 (void) nvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_MMP_TXG,
2457 &tryconfig_txg);
2458 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
2459 &tryconfig_timestamp);
060f0226
OF
2460 (void) nvlist_lookup_uint16(nvinfo, ZPOOL_CONFIG_MMP_SEQ,
2461 &tryconfig_mmp_seq);
379ca9cf
OF
2462 }
2463
2464 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE, &state);
379ca9cf
OF
2465
2466 /*
2467 * Disable the MMP activity check - This is used by zdb which
2468 * is intended to be used on potentially active pools.
2469 */
2470 if (spa->spa_import_flags & ZFS_IMPORT_SKIP_MMP)
2471 return (B_FALSE);
2472
2473 /*
2474 * Skip the activity check when the MMP feature is disabled.
2475 */
2476 if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay == 0)
2477 return (B_FALSE);
ca95f70d 2478
379ca9cf 2479 /*
060f0226
OF
2480 * If the tryconfig_ values are nonzero, they are the results of an
2481 * earlier tryimport. If they all match the uberblock we just found,
2482 * then the pool has not changed and we return false so we do not test
2483 * a second time.
379ca9cf
OF
2484 */
2485 if (tryconfig_txg && tryconfig_txg == ub->ub_txg &&
060f0226
OF
2486 tryconfig_timestamp && tryconfig_timestamp == ub->ub_timestamp &&
2487 tryconfig_mmp_seq && tryconfig_mmp_seq ==
2488 (MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0))
379ca9cf
OF
2489 return (B_FALSE);
2490
2491 /*
2492 * Allow the activity check to be skipped when importing the pool
bbffb59e
BB
2493 * on the same host which last imported it. Since the hostid from
2494 * configuration may be stale use the one read from the label.
379ca9cf 2495 */
bbffb59e
BB
2496 if (nvlist_exists(label, ZPOOL_CONFIG_HOSTID))
2497 hostid = fnvlist_lookup_uint64(label, ZPOOL_CONFIG_HOSTID);
2498
379ca9cf
OF
2499 if (hostid == spa_get_hostid())
2500 return (B_FALSE);
2501
2502 /*
2503 * Skip the activity test when the pool was cleanly exported.
2504 */
2505 if (state != POOL_STATE_ACTIVE)
2506 return (B_FALSE);
2507
2508 return (B_TRUE);
2509}
2510
060f0226
OF
2511/*
2512 * Nanoseconds the activity check must watch for changes on-disk.
2513 */
2514static uint64_t
2515spa_activity_check_duration(spa_t *spa, uberblock_t *ub)
2516{
2517 uint64_t import_intervals = MAX(zfs_multihost_import_intervals, 1);
2518 uint64_t multihost_interval = MSEC2NSEC(
2519 MMP_INTERVAL_OK(zfs_multihost_interval));
2520 uint64_t import_delay = MAX(NANOSEC, import_intervals *
2521 multihost_interval);
2522
2523 /*
2524 * Local tunables determine a minimum duration except for the case
2525 * where we know when the remote host will suspend the pool if MMP
2526 * writes do not land.
2527 *
2528 * See Big Theory comment at the top of mmp.c for the reasoning behind
2529 * these cases and times.
2530 */
2531
2532 ASSERT(MMP_IMPORT_SAFETY_FACTOR >= 100);
2533
2534 if (MMP_INTERVAL_VALID(ub) && MMP_FAIL_INT_VALID(ub) &&
2535 MMP_FAIL_INT(ub) > 0) {
2536
2537 /* MMP on remote host will suspend pool after failed writes */
2538 import_delay = MMP_FAIL_INT(ub) * MSEC2NSEC(MMP_INTERVAL(ub)) *
2539 MMP_IMPORT_SAFETY_FACTOR / 100;
2540
2541 zfs_dbgmsg("fail_intvals>0 import_delay=%llu ub_mmp "
2542 "mmp_fails=%llu ub_mmp mmp_interval=%llu "
2543 "import_intervals=%u", import_delay, MMP_FAIL_INT(ub),
2544 MMP_INTERVAL(ub), import_intervals);
2545
2546 } else if (MMP_INTERVAL_VALID(ub) && MMP_FAIL_INT_VALID(ub) &&
2547 MMP_FAIL_INT(ub) == 0) {
2548
2549 /* MMP on remote host will never suspend pool */
2550 import_delay = MAX(import_delay, (MSEC2NSEC(MMP_INTERVAL(ub)) +
2551 ub->ub_mmp_delay) * import_intervals);
2552
2553 zfs_dbgmsg("fail_intvals=0 import_delay=%llu ub_mmp "
2554 "mmp_interval=%llu ub_mmp_delay=%llu "
2555 "import_intervals=%u", import_delay, MMP_INTERVAL(ub),
2556 ub->ub_mmp_delay, import_intervals);
2557
2558 } else if (MMP_VALID(ub)) {
2559 /*
2560 * zfs-0.7 compatability case
2561 */
2562
2563 import_delay = MAX(import_delay, (multihost_interval +
2564 ub->ub_mmp_delay) * import_intervals);
2565
2566 zfs_dbgmsg("import_delay=%llu ub_mmp_delay=%llu "
2567 "import_intervals=%u leaves=%u", import_delay,
2568 ub->ub_mmp_delay, import_intervals,
2569 vdev_count_leaves(spa));
2570 } else {
2571 /* Using local tunings is the only reasonable option */
2572 zfs_dbgmsg("pool last imported on non-MMP aware "
2573 "host using import_delay=%llu multihost_interval=%llu "
2574 "import_intervals=%u", import_delay, multihost_interval,
2575 import_intervals);
2576 }
2577
2578 return (import_delay);
2579}
2580
379ca9cf
OF
2581/*
2582 * Perform the import activity check. If the user canceled the import or
2583 * we detected activity then fail.
2584 */
2585static int
2586spa_activity_check(spa_t *spa, uberblock_t *ub, nvlist_t *config)
2587{
379ca9cf
OF
2588 uint64_t txg = ub->ub_txg;
2589 uint64_t timestamp = ub->ub_timestamp;
060f0226
OF
2590 uint64_t mmp_config = ub->ub_mmp_config;
2591 uint16_t mmp_seq = MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0;
2592 uint64_t import_delay;
379ca9cf
OF
2593 hrtime_t import_expire;
2594 nvlist_t *mmp_label = NULL;
2595 vdev_t *rvd = spa->spa_root_vdev;
2596 kcondvar_t cv;
2597 kmutex_t mtx;
2598 int error = 0;
2599
2600 cv_init(&cv, NULL, CV_DEFAULT, NULL);
2601 mutex_init(&mtx, NULL, MUTEX_DEFAULT, NULL);
2602 mutex_enter(&mtx);
2603
2604 /*
2605 * If ZPOOL_CONFIG_MMP_TXG is present an activity check was performed
2606 * during the earlier tryimport. If the txg recorded there is 0 then
2607 * the pool is known to be active on another host.
2608 *
060f0226 2609 * Otherwise, the pool might be in use on another host. Check for
379ca9cf
OF
2610 * changes in the uberblocks on disk if necessary.
2611 */
2612 if (nvlist_exists(config, ZPOOL_CONFIG_LOAD_INFO)) {
2613 nvlist_t *nvinfo = fnvlist_lookup_nvlist(config,
2614 ZPOOL_CONFIG_LOAD_INFO);
2615
2616 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_TXG) &&
2617 fnvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_MMP_TXG) == 0) {
2618 vdev_uberblock_load(rvd, ub, &mmp_label);
2619 error = SET_ERROR(EREMOTEIO);
2620 goto out;
2621 }
2622 }
2623
060f0226 2624 import_delay = spa_activity_check_duration(spa, ub);
533ea041 2625
379ca9cf 2626 /* Add a small random factor in case of simultaneous imports (0-25%) */
ca95f70d
OF
2627 import_delay += import_delay * spa_get_random(250) / 1000;
2628
2629 import_expire = gethrtime() + import_delay;
379ca9cf
OF
2630
2631 while (gethrtime() < import_expire) {
ca95f70d
OF
2632 (void) spa_import_progress_set_mmp_check(spa_guid(spa),
2633 NSEC2SEC(import_expire - gethrtime()));
2634
379ca9cf
OF
2635 vdev_uberblock_load(rvd, ub, &mmp_label);
2636
060f0226
OF
2637 if (txg != ub->ub_txg || timestamp != ub->ub_timestamp ||
2638 mmp_seq != (MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0)) {
2639 zfs_dbgmsg("multihost activity detected "
2640 "txg %llu ub_txg %llu "
2641 "timestamp %llu ub_timestamp %llu "
2642 "mmp_config %#llx ub_mmp_config %#llx",
2643 txg, ub->ub_txg, timestamp, ub->ub_timestamp,
2644 mmp_config, ub->ub_mmp_config);
2645
379ca9cf
OF
2646 error = SET_ERROR(EREMOTEIO);
2647 break;
2648 }
2649
2650 if (mmp_label) {
2651 nvlist_free(mmp_label);
2652 mmp_label = NULL;
2653 }
2654
2655 error = cv_timedwait_sig(&cv, &mtx, ddi_get_lbolt() + hz);
2656 if (error != -1) {
2657 error = SET_ERROR(EINTR);
2658 break;
2659 }
2660 error = 0;
2661 }
2662
2663out:
2664 mutex_exit(&mtx);
2665 mutex_destroy(&mtx);
2666 cv_destroy(&cv);
2667
2668 /*
2669 * If the pool is determined to be active store the status in the
2670 * spa->spa_load_info nvlist. If the remote hostname or hostid are
2671 * available from configuration read from disk store them as well.
2672 * This allows 'zpool import' to generate a more useful message.
2673 *
2674 * ZPOOL_CONFIG_MMP_STATE - observed pool status (mandatory)
2675 * ZPOOL_CONFIG_MMP_HOSTNAME - hostname from the active pool
2676 * ZPOOL_CONFIG_MMP_HOSTID - hostid from the active pool
2677 */
2678 if (error == EREMOTEIO) {
2679 char *hostname = "<unknown>";
2680 uint64_t hostid = 0;
2681
2682 if (mmp_label) {
2683 if (nvlist_exists(mmp_label, ZPOOL_CONFIG_HOSTNAME)) {
2684 hostname = fnvlist_lookup_string(mmp_label,
2685 ZPOOL_CONFIG_HOSTNAME);
2686 fnvlist_add_string(spa->spa_load_info,
2687 ZPOOL_CONFIG_MMP_HOSTNAME, hostname);
2688 }
2689
2690 if (nvlist_exists(mmp_label, ZPOOL_CONFIG_HOSTID)) {
2691 hostid = fnvlist_lookup_uint64(mmp_label,
2692 ZPOOL_CONFIG_HOSTID);
2693 fnvlist_add_uint64(spa->spa_load_info,
2694 ZPOOL_CONFIG_MMP_HOSTID, hostid);
2695 }
2696 }
2697
2698 fnvlist_add_uint64(spa->spa_load_info,
2699 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_ACTIVE);
2700 fnvlist_add_uint64(spa->spa_load_info,
2701 ZPOOL_CONFIG_MMP_TXG, 0);
2702
2703 error = spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO);
2704 }
2705
2706 if (mmp_label)
2707 nvlist_free(mmp_label);
2708
2709 return (error);
2710}
2711
9eb7b46e 2712static int
6cb8e530
PZ
2713spa_verify_host(spa_t *spa, nvlist_t *mos_config)
2714{
2715 uint64_t hostid;
2716 char *hostname;
2717 uint64_t myhostid = 0;
2718
2719 if (!spa_is_root(spa) && nvlist_lookup_uint64(mos_config,
2720 ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
2721 hostname = fnvlist_lookup_string(mos_config,
2722 ZPOOL_CONFIG_HOSTNAME);
2723
2724 myhostid = zone_get_hostid(NULL);
2725
2726 if (hostid != 0 && myhostid != 0 && hostid != myhostid) {
2727 cmn_err(CE_WARN, "pool '%s' could not be "
2728 "loaded as it was last accessed by "
2729 "another system (host: %s hostid: 0x%llx). "
2730 "See: http://illumos.org/msg/ZFS-8000-EY",
2731 spa_name(spa), hostname, (u_longlong_t)hostid);
2732 spa_load_failed(spa, "hostid verification failed: pool "
2733 "last accessed by host: %s (hostid: 0x%llx)",
2734 hostname, (u_longlong_t)hostid);
2735 return (SET_ERROR(EBADF));
2736 }
2737 }
2738
2739 return (0);
2740}
2741
2742static int
2743spa_ld_parse_config(spa_t *spa, spa_import_type_t type)
428870ff
BB
2744{
2745 int error = 0;
6cb8e530 2746 nvlist_t *nvtree, *nvl, *config = spa->spa_config;
1c27024e 2747 int parse;
9eb7b46e 2748 vdev_t *rvd;
6cb8e530
PZ
2749 uint64_t pool_guid;
2750 char *comment;
2751
2752 /*
2753 * Versioning wasn't explicitly added to the label until later, so if
2754 * it's not present treat it as the initial version.
2755 */
2756 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
2757 &spa->spa_ubsync.ub_version) != 0)
2758 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
2759
2760 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid)) {
2761 spa_load_failed(spa, "invalid config provided: '%s' missing",
2762 ZPOOL_CONFIG_POOL_GUID);
2763 return (SET_ERROR(EINVAL));
2764 }
2765
d2734cce
SD
2766 /*
2767 * If we are doing an import, ensure that the pool is not already
2768 * imported by checking if its pool guid already exists in the
2769 * spa namespace.
2770 *
2771 * The only case that we allow an already imported pool to be
2772 * imported again, is when the pool is checkpointed and we want to
2773 * look at its checkpointed state from userland tools like zdb.
2774 */
2775#ifdef _KERNEL
2776 if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2777 spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2778 spa_guid_exists(pool_guid, 0)) {
2779#else
2780 if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2781 spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2782 spa_guid_exists(pool_guid, 0) &&
2783 !spa_importing_readonly_checkpoint(spa)) {
2784#endif
6cb8e530
PZ
2785 spa_load_failed(spa, "a pool with guid %llu is already open",
2786 (u_longlong_t)pool_guid);
2787 return (SET_ERROR(EEXIST));
2788 }
2789
2790 spa->spa_config_guid = pool_guid;
2791
2792 nvlist_free(spa->spa_load_info);
2793 spa->spa_load_info = fnvlist_alloc();
2794
2795 ASSERT(spa->spa_comment == NULL);
2796 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2797 spa->spa_comment = spa_strdup(comment);
2798
2799 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
2800 &spa->spa_config_txg);
2801
2802 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) == 0)
2803 spa->spa_config_splitting = fnvlist_dup(nvl);
428870ff 2804
4a0ee12a
PZ
2805 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvtree)) {
2806 spa_load_failed(spa, "invalid config provided: '%s' missing",
2807 ZPOOL_CONFIG_VDEV_TREE);
2e528b49 2808 return (SET_ERROR(EINVAL));
4a0ee12a 2809 }
428870ff 2810
428870ff
BB
2811 /*
2812 * Create "The Godfather" zio to hold all async IOs
2813 */
e022864d
MA
2814 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
2815 KM_SLEEP);
1c27024e 2816 for (int i = 0; i < max_ncpus; i++) {
e022864d
MA
2817 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
2818 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2819 ZIO_FLAG_GODFATHER);
2820 }
428870ff
BB
2821
2822 /*
2823 * Parse the configuration into a vdev tree. We explicitly set the
2824 * value that will be returned by spa_version() since parsing the
2825 * configuration requires knowing the version number.
2826 */
2827 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6cb8e530
PZ
2828 parse = (type == SPA_IMPORT_EXISTING ?
2829 VDEV_ALLOC_LOAD : VDEV_ALLOC_SPLIT);
9eb7b46e 2830 error = spa_config_parse(spa, &rvd, nvtree, NULL, 0, parse);
428870ff
BB
2831 spa_config_exit(spa, SCL_ALL, FTAG);
2832
4a0ee12a
PZ
2833 if (error != 0) {
2834 spa_load_failed(spa, "unable to parse config [error=%d]",
2835 error);
428870ff 2836 return (error);
4a0ee12a 2837 }
428870ff
BB
2838
2839 ASSERT(spa->spa_root_vdev == rvd);
c3520e7f
MA
2840 ASSERT3U(spa->spa_min_ashift, >=, SPA_MINBLOCKSHIFT);
2841 ASSERT3U(spa->spa_max_ashift, <=, SPA_MAXBLOCKSHIFT);
428870ff
BB
2842
2843 if (type != SPA_IMPORT_ASSEMBLE) {
2844 ASSERT(spa_guid(spa) == pool_guid);
2845 }
2846
9eb7b46e
PZ
2847 return (0);
2848}
2849
6cb8e530
PZ
2850/*
2851 * Recursively open all vdevs in the vdev tree. This function is called twice:
2852 * first with the untrusted config, then with the trusted config.
2853 */
9eb7b46e
PZ
2854static int
2855spa_ld_open_vdevs(spa_t *spa)
2856{
2857 int error = 0;
2858
6cb8e530
PZ
2859 /*
2860 * spa_missing_tvds_allowed defines how many top-level vdevs can be
2861 * missing/unopenable for the root vdev to be still considered openable.
2862 */
2863 if (spa->spa_trust_config) {
2864 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds;
2865 } else if (spa->spa_config_source == SPA_CONFIG_SRC_CACHEFILE) {
2866 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_cachefile;
2867 } else if (spa->spa_config_source == SPA_CONFIG_SRC_SCAN) {
2868 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_scan;
2869 } else {
2870 spa->spa_missing_tvds_allowed = 0;
2871 }
2872
2873 spa->spa_missing_tvds_allowed =
2874 MAX(zfs_max_missing_tvds, spa->spa_missing_tvds_allowed);
2875
428870ff 2876 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
9eb7b46e 2877 error = vdev_open(spa->spa_root_vdev);
428870ff 2878 spa_config_exit(spa, SCL_ALL, FTAG);
6cb8e530
PZ
2879
2880 if (spa->spa_missing_tvds != 0) {
2881 spa_load_note(spa, "vdev tree has %lld missing top-level "
2882 "vdevs.", (u_longlong_t)spa->spa_missing_tvds);
2883 if (spa->spa_trust_config && (spa->spa_mode & FWRITE)) {
2884 /*
2885 * Although theoretically we could allow users to open
2886 * incomplete pools in RW mode, we'd need to add a lot
2887 * of extra logic (e.g. adjust pool space to account
2888 * for missing vdevs).
2889 * This limitation also prevents users from accidentally
2890 * opening the pool in RW mode during data recovery and
2891 * damaging it further.
2892 */
2893 spa_load_note(spa, "pools with missing top-level "
2894 "vdevs can only be opened in read-only mode.");
2895 error = SET_ERROR(ENXIO);
2896 } else {
2897 spa_load_note(spa, "current settings allow for maximum "
2898 "%lld missing top-level vdevs at this stage.",
2899 (u_longlong_t)spa->spa_missing_tvds_allowed);
2900 }
2901 }
4a0ee12a
PZ
2902 if (error != 0) {
2903 spa_load_failed(spa, "unable to open vdev tree [error=%d]",
2904 error);
2905 }
6cb8e530
PZ
2906 if (spa->spa_missing_tvds != 0 || error != 0)
2907 vdev_dbgmsg_print_tree(spa->spa_root_vdev, 2);
9eb7b46e
PZ
2908
2909 return (error);
2910}
2911
6cb8e530
PZ
2912/*
2913 * We need to validate the vdev labels against the configuration that
2914 * we have in hand. This function is called twice: first with an untrusted
2915 * config, then with a trusted config. The validation is more strict when the
2916 * config is trusted.
2917 */
9eb7b46e 2918static int
6cb8e530 2919spa_ld_validate_vdevs(spa_t *spa)
9eb7b46e
PZ
2920{
2921 int error = 0;
2922 vdev_t *rvd = spa->spa_root_vdev;
428870ff 2923
6cb8e530
PZ
2924 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2925 error = vdev_validate(rvd);
2926 spa_config_exit(spa, SCL_ALL, FTAG);
428870ff 2927
6cb8e530
PZ
2928 if (error != 0) {
2929 spa_load_failed(spa, "vdev_validate failed [error=%d]", error);
2930 return (error);
2931 }
428870ff 2932
6cb8e530
PZ
2933 if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN) {
2934 spa_load_failed(spa, "cannot open vdev tree after invalidating "
2935 "some vdevs");
2936 vdev_dbgmsg_print_tree(rvd, 2);
2937 return (SET_ERROR(ENXIO));
428870ff
BB
2938 }
2939
9eb7b46e
PZ
2940 return (0);
2941}
2942
d2734cce
SD
2943static void
2944spa_ld_select_uberblock_done(spa_t *spa, uberblock_t *ub)
2945{
2946 spa->spa_state = POOL_STATE_ACTIVE;
2947 spa->spa_ubsync = spa->spa_uberblock;
2948 spa->spa_verify_min_txg = spa->spa_extreme_rewind ?
2949 TXG_INITIAL - 1 : spa_last_synced_txg(spa) - TXG_DEFER_SIZE - 1;
2950 spa->spa_first_txg = spa->spa_last_ubsync_txg ?
2951 spa->spa_last_ubsync_txg : spa_last_synced_txg(spa) + 1;
2952 spa->spa_claim_max_txg = spa->spa_first_txg;
2953 spa->spa_prev_software_version = ub->ub_software_version;
2954}
2955
9eb7b46e 2956static int
6cb8e530 2957spa_ld_select_uberblock(spa_t *spa, spa_import_type_t type)
9eb7b46e
PZ
2958{
2959 vdev_t *rvd = spa->spa_root_vdev;
2960 nvlist_t *label;
2961 uberblock_t *ub = &spa->spa_uberblock;
9eb7b46e
PZ
2962 boolean_t activity_check = B_FALSE;
2963
d2734cce
SD
2964 /*
2965 * If we are opening the checkpointed state of the pool by
2966 * rewinding to it, at this point we will have written the
2967 * checkpointed uberblock to the vdev labels, so searching
2968 * the labels will find the right uberblock. However, if
2969 * we are opening the checkpointed state read-only, we have
2970 * not modified the labels. Therefore, we must ignore the
2971 * labels and continue using the spa_uberblock that was set
2972 * by spa_ld_checkpoint_rewind.
2973 *
2974 * Note that it would be fine to ignore the labels when
2975 * rewinding (opening writeable) as well. However, if we
2976 * crash just after writing the labels, we will end up
2977 * searching the labels. Doing so in the common case means
2978 * that this code path gets exercised normally, rather than
2979 * just in the edge case.
2980 */
2981 if (ub->ub_checkpoint_txg != 0 &&
2982 spa_importing_readonly_checkpoint(spa)) {
2983 spa_ld_select_uberblock_done(spa, ub);
2984 return (0);
2985 }
2986
428870ff
BB
2987 /*
2988 * Find the best uberblock.
2989 */
9ae529ec 2990 vdev_uberblock_load(rvd, ub, &label);
428870ff
BB
2991
2992 /*
2993 * If we weren't able to find a single valid uberblock, return failure.
2994 */
9ae529ec
CS
2995 if (ub->ub_txg == 0) {
2996 nvlist_free(label);
4a0ee12a 2997 spa_load_failed(spa, "no valid uberblock found");
428870ff 2998 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, ENXIO));
9ae529ec 2999 }
428870ff 3000
ca95f70d
OF
3001 if (spa->spa_load_max_txg != UINT64_MAX) {
3002 (void) spa_import_progress_set_max_txg(spa_guid(spa),
3003 (u_longlong_t)spa->spa_load_max_txg);
3004 }
4a0ee12a
PZ
3005 spa_load_note(spa, "using uberblock with txg=%llu",
3006 (u_longlong_t)ub->ub_txg);
3007
3008
379ca9cf
OF
3009 /*
3010 * For pools which have the multihost property on determine if the
3011 * pool is truly inactive and can be safely imported. Prevent
3012 * hosts which don't have a hostid set from importing the pool.
3013 */
6cb8e530
PZ
3014 activity_check = spa_activity_check_required(spa, ub, label,
3015 spa->spa_config);
379ca9cf 3016 if (activity_check) {
379ca9cf
OF
3017 if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay &&
3018 spa_get_hostid() == 0) {
3019 nvlist_free(label);
3020 fnvlist_add_uint64(spa->spa_load_info,
3021 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_NO_HOSTID);
3022 return (spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO));
3023 }
3024
6cb8e530 3025 int error = spa_activity_check(spa, ub, spa->spa_config);
e889f0f5
OF
3026 if (error) {
3027 nvlist_free(label);
3028 return (error);
3029 }
3030
379ca9cf
OF
3031 fnvlist_add_uint64(spa->spa_load_info,
3032 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_INACTIVE);
3033 fnvlist_add_uint64(spa->spa_load_info,
3034 ZPOOL_CONFIG_MMP_TXG, ub->ub_txg);
060f0226
OF
3035 fnvlist_add_uint16(spa->spa_load_info,
3036 ZPOOL_CONFIG_MMP_SEQ,
3037 (MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0));
379ca9cf
OF
3038 }
3039
428870ff 3040 /*
9ae529ec 3041 * If the pool has an unsupported version we can't open it.
428870ff 3042 */
9ae529ec
CS
3043 if (!SPA_VERSION_IS_SUPPORTED(ub->ub_version)) {
3044 nvlist_free(label);
4a0ee12a
PZ
3045 spa_load_failed(spa, "version %llu is not supported",
3046 (u_longlong_t)ub->ub_version);
428870ff 3047 return (spa_vdev_err(rvd, VDEV_AUX_VERSION_NEWER, ENOTSUP));
9ae529ec
CS
3048 }
3049
3050 if (ub->ub_version >= SPA_VERSION_FEATURES) {
3051 nvlist_t *features;
3052
3053 /*
3054 * If we weren't able to find what's necessary for reading the
3055 * MOS in the label, return failure.
3056 */
4a0ee12a
PZ
3057 if (label == NULL) {
3058 spa_load_failed(spa, "label config unavailable");
3059 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3060 ENXIO));
3061 }
3062
3063 if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_FEATURES_FOR_READ,
3064 &features) != 0) {
9ae529ec 3065 nvlist_free(label);
4a0ee12a
PZ
3066 spa_load_failed(spa, "invalid label: '%s' missing",
3067 ZPOOL_CONFIG_FEATURES_FOR_READ);
9ae529ec
CS
3068 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3069 ENXIO));
3070 }
3071
3072 /*
3073 * Update our in-core representation with the definitive values
3074 * from the label.
3075 */
3076 nvlist_free(spa->spa_label_features);
3077 VERIFY(nvlist_dup(features, &spa->spa_label_features, 0) == 0);
3078 }
3079
3080 nvlist_free(label);
3081
3082 /*
3083 * Look through entries in the label nvlist's features_for_read. If
3084 * there is a feature listed there which we don't understand then we
3085 * cannot open a pool.
3086 */
3087 if (ub->ub_version >= SPA_VERSION_FEATURES) {
3088 nvlist_t *unsup_feat;
9ae529ec
CS
3089
3090 VERIFY(nvlist_alloc(&unsup_feat, NV_UNIQUE_NAME, KM_SLEEP) ==
3091 0);
3092
1c27024e
DB
3093 for (nvpair_t *nvp = nvlist_next_nvpair(spa->spa_label_features,
3094 NULL); nvp != NULL;
9ae529ec
CS
3095 nvp = nvlist_next_nvpair(spa->spa_label_features, nvp)) {
3096 if (!zfeature_is_supported(nvpair_name(nvp))) {
3097 VERIFY(nvlist_add_string(unsup_feat,
3098 nvpair_name(nvp), "") == 0);
3099 }
3100 }
3101
3102 if (!nvlist_empty(unsup_feat)) {
3103 VERIFY(nvlist_add_nvlist(spa->spa_load_info,
3104 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat) == 0);
3105 nvlist_free(unsup_feat);
4a0ee12a 3106 spa_load_failed(spa, "some features are unsupported");
9ae529ec
CS
3107 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
3108 ENOTSUP));
3109 }
3110
3111 nvlist_free(unsup_feat);
3112 }
428870ff 3113
428870ff
BB
3114 if (type != SPA_IMPORT_ASSEMBLE && spa->spa_config_splitting) {
3115 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6cb8e530 3116 spa_try_repair(spa, spa->spa_config);
428870ff
BB
3117 spa_config_exit(spa, SCL_ALL, FTAG);
3118 nvlist_free(spa->spa_config_splitting);
3119 spa->spa_config_splitting = NULL;
3120 }
3121
3122 /*
3123 * Initialize internal SPA structures.
3124 */
d2734cce 3125 spa_ld_select_uberblock_done(spa, ub);
428870ff 3126
9eb7b46e
PZ
3127 return (0);
3128}
3129
3130static int
3131spa_ld_open_rootbp(spa_t *spa)
3132{
3133 int error = 0;
3134 vdev_t *rvd = spa->spa_root_vdev;
a1d477c2 3135
9ae529ec 3136 error = dsl_pool_init(spa, spa->spa_first_txg, &spa->spa_dsl_pool);
4a0ee12a
PZ
3137 if (error != 0) {
3138 spa_load_failed(spa, "unable to open rootbp in dsl_pool_init "
3139 "[error=%d]", error);
428870ff 3140 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4a0ee12a 3141 }
428870ff
BB
3142 spa->spa_meta_objset = spa->spa_dsl_pool->dp_meta_objset;
3143
9eb7b46e
PZ
3144 return (0);
3145}
3146
3147static int
d2734cce 3148spa_ld_trusted_config(spa_t *spa, spa_import_type_t type,
6cb8e530 3149 boolean_t reloading)
9eb7b46e 3150{
6cb8e530
PZ
3151 vdev_t *mrvd, *rvd = spa->spa_root_vdev;
3152 nvlist_t *nv, *mos_config, *policy;
3153 int error = 0, copy_error;
3154 uint64_t healthy_tvds, healthy_tvds_mos;
3155 uint64_t mos_config_txg;
9eb7b46e 3156
4a0ee12a
PZ
3157 if (spa_dir_prop(spa, DMU_POOL_CONFIG, &spa->spa_config_object, B_TRUE)
3158 != 0)
428870ff
BB
3159 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3160
a1d477c2 3161 /*
6cb8e530
PZ
3162 * If we're assembling a pool from a split, the config provided is
3163 * already trusted so there is nothing to do.
a1d477c2 3164 */
6cb8e530
PZ
3165 if (type == SPA_IMPORT_ASSEMBLE)
3166 return (0);
3167
3168 healthy_tvds = spa_healthy_core_tvds(spa);
a1d477c2 3169
6cb8e530
PZ
3170 if (load_nvlist(spa, spa->spa_config_object, &mos_config)
3171 != 0) {
3172 spa_load_failed(spa, "unable to retrieve MOS config");
3173 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3174 }
3175
3176 /*
3177 * If we are doing an open, pool owner wasn't verified yet, thus do
3178 * the verification here.
3179 */
3180 if (spa->spa_load_state == SPA_LOAD_OPEN) {
3181 error = spa_verify_host(spa, mos_config);
3182 if (error != 0) {
a1d477c2 3183 nvlist_free(mos_config);
6cb8e530 3184 return (error);
a1d477c2 3185 }
6cb8e530
PZ
3186 }
3187
3188 nv = fnvlist_lookup_nvlist(mos_config, ZPOOL_CONFIG_VDEV_TREE);
a1d477c2 3189
6cb8e530
PZ
3190 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3191
3192 /*
3193 * Build a new vdev tree from the trusted config
3194 */
3195 VERIFY(spa_config_parse(spa, &mrvd, nv, NULL, 0, VDEV_ALLOC_LOAD) == 0);
3196
3197 /*
3198 * Vdev paths in the MOS may be obsolete. If the untrusted config was
3199 * obtained by scanning /dev/dsk, then it will have the right vdev
3200 * paths. We update the trusted MOS config with this information.
3201 * We first try to copy the paths with vdev_copy_path_strict, which
3202 * succeeds only when both configs have exactly the same vdev tree.
3203 * If that fails, we fall back to a more flexible method that has a
3204 * best effort policy.
3205 */
3206 copy_error = vdev_copy_path_strict(rvd, mrvd);
3207 if (copy_error != 0 || spa_load_print_vdev_tree) {
3208 spa_load_note(spa, "provided vdev tree:");
3209 vdev_dbgmsg_print_tree(rvd, 2);
3210 spa_load_note(spa, "MOS vdev tree:");
3211 vdev_dbgmsg_print_tree(mrvd, 2);
3212 }
3213 if (copy_error != 0) {
3214 spa_load_note(spa, "vdev_copy_path_strict failed, falling "
3215 "back to vdev_copy_path_relaxed");
3216 vdev_copy_path_relaxed(rvd, mrvd);
3217 }
3218
3219 vdev_close(rvd);
3220 vdev_free(rvd);
3221 spa->spa_root_vdev = mrvd;
3222 rvd = mrvd;
3223 spa_config_exit(spa, SCL_ALL, FTAG);
3224
3225 /*
3226 * We will use spa_config if we decide to reload the spa or if spa_load
3227 * fails and we rewind. We must thus regenerate the config using the
8a393be3
PZ
3228 * MOS information with the updated paths. ZPOOL_LOAD_POLICY is used to
3229 * pass settings on how to load the pool and is not stored in the MOS.
3230 * We copy it over to our new, trusted config.
6cb8e530
PZ
3231 */
3232 mos_config_txg = fnvlist_lookup_uint64(mos_config,
3233 ZPOOL_CONFIG_POOL_TXG);
3234 nvlist_free(mos_config);
3235 mos_config = spa_config_generate(spa, NULL, mos_config_txg, B_FALSE);
8a393be3 3236 if (nvlist_lookup_nvlist(spa->spa_config, ZPOOL_LOAD_POLICY,
6cb8e530 3237 &policy) == 0)
8a393be3 3238 fnvlist_add_nvlist(mos_config, ZPOOL_LOAD_POLICY, policy);
6cb8e530
PZ
3239 spa_config_set(spa, mos_config);
3240 spa->spa_config_source = SPA_CONFIG_SRC_MOS;
3241
3242 /*
3243 * Now that we got the config from the MOS, we should be more strict
3244 * in checking blkptrs and can make assumptions about the consistency
3245 * of the vdev tree. spa_trust_config must be set to true before opening
3246 * vdevs in order for them to be writeable.
3247 */
3248 spa->spa_trust_config = B_TRUE;
3249
3250 /*
3251 * Open and validate the new vdev tree
3252 */
3253 error = spa_ld_open_vdevs(spa);
3254 if (error != 0)
3255 return (error);
3256
3257 error = spa_ld_validate_vdevs(spa);
3258 if (error != 0)
3259 return (error);
3260
3261 if (copy_error != 0 || spa_load_print_vdev_tree) {
3262 spa_load_note(spa, "final vdev tree:");
3263 vdev_dbgmsg_print_tree(rvd, 2);
3264 }
3265
3266 if (spa->spa_load_state != SPA_LOAD_TRYIMPORT &&
3267 !spa->spa_extreme_rewind && zfs_max_missing_tvds == 0) {
a1d477c2 3268 /*
6cb8e530
PZ
3269 * Sanity check to make sure that we are indeed loading the
3270 * latest uberblock. If we missed SPA_SYNC_MIN_VDEVS tvds
3271 * in the config provided and they happened to be the only ones
3272 * to have the latest uberblock, we could involuntarily perform
3273 * an extreme rewind.
a1d477c2 3274 */
6cb8e530
PZ
3275 healthy_tvds_mos = spa_healthy_core_tvds(spa);
3276 if (healthy_tvds_mos - healthy_tvds >=
3277 SPA_SYNC_MIN_VDEVS) {
3278 spa_load_note(spa, "config provided misses too many "
3279 "top-level vdevs compared to MOS (%lld vs %lld). ",
3280 (u_longlong_t)healthy_tvds,
3281 (u_longlong_t)healthy_tvds_mos);
3282 spa_load_note(spa, "vdev tree:");
3283 vdev_dbgmsg_print_tree(rvd, 2);
3284 if (reloading) {
3285 spa_load_failed(spa, "config was already "
3286 "provided from MOS. Aborting.");
3287 return (spa_vdev_err(rvd,
3288 VDEV_AUX_CORRUPT_DATA, EIO));
3289 }
3290 spa_load_note(spa, "spa must be reloaded using MOS "
3291 "config");
3292 return (SET_ERROR(EAGAIN));
4a0ee12a 3293 }
a1d477c2
MA
3294 }
3295
6cb8e530
PZ
3296 error = spa_check_for_missing_logs(spa);
3297 if (error != 0)
3298 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM, ENXIO));
3299
3300 if (rvd->vdev_guid_sum != spa->spa_uberblock.ub_guid_sum) {
3301 spa_load_failed(spa, "uberblock guid sum doesn't match MOS "
3302 "guid sum (%llu != %llu)",
3303 (u_longlong_t)spa->spa_uberblock.ub_guid_sum,
3304 (u_longlong_t)rvd->vdev_guid_sum);
3305 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM,
3306 ENXIO));
3307 }
3308
9eb7b46e
PZ
3309 return (0);
3310}
3311
3312static int
3313spa_ld_open_indirect_vdev_metadata(spa_t *spa)
3314{
3315 int error = 0;
3316 vdev_t *rvd = spa->spa_root_vdev;
3317
a1d477c2
MA
3318 /*
3319 * Everything that we read before spa_remove_init() must be stored
3320 * on concreted vdevs. Therefore we do this as early as possible.
3321 */
4a0ee12a
PZ
3322 error = spa_remove_init(spa);
3323 if (error != 0) {
3324 spa_load_failed(spa, "spa_remove_init failed [error=%d]",
3325 error);
a1d477c2 3326 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4a0ee12a 3327 }
a1d477c2 3328
9eb7b46e
PZ
3329 /*
3330 * Retrieve information needed to condense indirect vdev mappings.
3331 */
3332 error = spa_condense_init(spa);
3333 if (error != 0) {
4a0ee12a
PZ
3334 spa_load_failed(spa, "spa_condense_init failed [error=%d]",
3335 error);
9eb7b46e
PZ
3336 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3337 }
3338
3339 return (0);
3340}
3341
3342static int
4a0ee12a 3343spa_ld_check_features(spa_t *spa, boolean_t *missing_feat_writep)
9eb7b46e
PZ
3344{
3345 int error = 0;
3346 vdev_t *rvd = spa->spa_root_vdev;
3347
9ae529ec
CS
3348 if (spa_version(spa) >= SPA_VERSION_FEATURES) {
3349 boolean_t missing_feat_read = B_FALSE;
b9b24bb4 3350 nvlist_t *unsup_feat, *enabled_feat;
9ae529ec
CS
3351
3352 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_READ,
4a0ee12a 3353 &spa->spa_feat_for_read_obj, B_TRUE) != 0) {
9ae529ec
CS
3354 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3355 }
3356
3357 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_WRITE,
4a0ee12a 3358 &spa->spa_feat_for_write_obj, B_TRUE) != 0) {
9ae529ec
CS
3359 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3360 }
3361
3362 if (spa_dir_prop(spa, DMU_POOL_FEATURE_DESCRIPTIONS,
4a0ee12a 3363 &spa->spa_feat_desc_obj, B_TRUE) != 0) {
9ae529ec
CS
3364 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3365 }
3366
b9b24bb4
CS
3367 enabled_feat = fnvlist_alloc();
3368 unsup_feat = fnvlist_alloc();
9ae529ec 3369
fa86b5db 3370 if (!spa_features_check(spa, B_FALSE,
b9b24bb4 3371 unsup_feat, enabled_feat))
9ae529ec
CS
3372 missing_feat_read = B_TRUE;
3373
4a0ee12a
PZ
3374 if (spa_writeable(spa) ||
3375 spa->spa_load_state == SPA_LOAD_TRYIMPORT) {
fa86b5db 3376 if (!spa_features_check(spa, B_TRUE,
b9b24bb4 3377 unsup_feat, enabled_feat)) {
9eb7b46e 3378 *missing_feat_writep = B_TRUE;
b9b24bb4 3379 }
9ae529ec
CS
3380 }
3381
b9b24bb4
CS
3382 fnvlist_add_nvlist(spa->spa_load_info,
3383 ZPOOL_CONFIG_ENABLED_FEAT, enabled_feat);
3384
9ae529ec 3385 if (!nvlist_empty(unsup_feat)) {
b9b24bb4
CS
3386 fnvlist_add_nvlist(spa->spa_load_info,
3387 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat);
9ae529ec
CS
3388 }
3389
b9b24bb4
CS
3390 fnvlist_free(enabled_feat);
3391 fnvlist_free(unsup_feat);
9ae529ec
CS
3392
3393 if (!missing_feat_read) {
3394 fnvlist_add_boolean(spa->spa_load_info,
3395 ZPOOL_CONFIG_CAN_RDONLY);
3396 }
3397
3398 /*
3399 * If the state is SPA_LOAD_TRYIMPORT, our objective is
3400 * twofold: to determine whether the pool is available for
3401 * import in read-write mode and (if it is not) whether the
3402 * pool is available for import in read-only mode. If the pool
3403 * is available for import in read-write mode, it is displayed
3404 * as available in userland; if it is not available for import
3405 * in read-only mode, it is displayed as unavailable in
3406 * userland. If the pool is available for import in read-only
3407 * mode but not read-write mode, it is displayed as unavailable
3408 * in userland with a special note that the pool is actually
3409 * available for open in read-only mode.
3410 *
3411 * As a result, if the state is SPA_LOAD_TRYIMPORT and we are
3412 * missing a feature for write, we must first determine whether
3413 * the pool can be opened read-only before returning to
3414 * userland in order to know whether to display the
3415 * abovementioned note.
3416 */
9eb7b46e 3417 if (missing_feat_read || (*missing_feat_writep &&
9ae529ec 3418 spa_writeable(spa))) {
4a0ee12a 3419 spa_load_failed(spa, "pool uses unsupported features");
9ae529ec
CS
3420 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
3421 ENOTSUP));
3422 }
b0bc7a84
MG
3423
3424 /*
3425 * Load refcounts for ZFS features from disk into an in-memory
3426 * cache during SPA initialization.
3427 */
1c27024e 3428 for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
b0bc7a84
MG
3429 uint64_t refcount;
3430
3431 error = feature_get_refcount_from_disk(spa,
3432 &spa_feature_table[i], &refcount);
3433 if (error == 0) {
3434 spa->spa_feat_refcount_cache[i] = refcount;
3435 } else if (error == ENOTSUP) {
3436 spa->spa_feat_refcount_cache[i] =
3437 SPA_FEATURE_DISABLED;
3438 } else {
4a0ee12a
PZ
3439 spa_load_failed(spa, "error getting refcount "
3440 "for feature %s [error=%d]",
3441 spa_feature_table[i].fi_guid, error);
b0bc7a84
MG
3442 return (spa_vdev_err(rvd,
3443 VDEV_AUX_CORRUPT_DATA, EIO));
3444 }
3445 }
3446 }
3447
3448 if (spa_feature_is_active(spa, SPA_FEATURE_ENABLED_TXG)) {
3449 if (spa_dir_prop(spa, DMU_POOL_FEATURE_ENABLED_TXG,
4a0ee12a 3450 &spa->spa_feat_enabled_txg_obj, B_TRUE) != 0)
b0bc7a84 3451 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
9ae529ec
CS
3452 }
3453
f00ab3f2
TC
3454 /*
3455 * Encryption was added before bookmark_v2, even though bookmark_v2
3456 * is now a dependency. If this pool has encryption enabled without
3457 * bookmark_v2, trigger an errata message.
3458 */
3459 if (spa_feature_is_enabled(spa, SPA_FEATURE_ENCRYPTION) &&
3460 !spa_feature_is_enabled(spa, SPA_FEATURE_BOOKMARK_V2)) {
3461 spa->spa_errata = ZPOOL_ERRATA_ZOL_8308_ENCRYPTION;
3462 }
3463
9eb7b46e
PZ
3464 return (0);
3465}
3466
3467static int
3468spa_ld_load_special_directories(spa_t *spa)
3469{
3470 int error = 0;
3471 vdev_t *rvd = spa->spa_root_vdev;
3472
9ae529ec
CS
3473 spa->spa_is_initializing = B_TRUE;
3474 error = dsl_pool_open(spa->spa_dsl_pool);
3475 spa->spa_is_initializing = B_FALSE;
4a0ee12a
PZ
3476 if (error != 0) {
3477 spa_load_failed(spa, "dsl_pool_open failed [error=%d]", error);
9ae529ec 3478 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4a0ee12a 3479 }
9ae529ec 3480
9eb7b46e
PZ
3481 return (0);
3482}
428870ff 3483
9eb7b46e
PZ
3484static int
3485spa_ld_get_props(spa_t *spa)
3486{
3487 int error = 0;
3488 uint64_t obj;
3489 vdev_t *rvd = spa->spa_root_vdev;
34dc7c2f 3490
3c67d83a
TH
3491 /* Grab the checksum salt from the MOS. */
3492 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3493 DMU_POOL_CHECKSUM_SALT, 1,
3494 sizeof (spa->spa_cksum_salt.zcs_bytes),
3495 spa->spa_cksum_salt.zcs_bytes);
3496 if (error == ENOENT) {
3497 /* Generate a new salt for subsequent use */
3498 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
3499 sizeof (spa->spa_cksum_salt.zcs_bytes));
3500 } else if (error != 0) {
4a0ee12a
PZ
3501 spa_load_failed(spa, "unable to retrieve checksum salt from "
3502 "MOS [error=%d]", error);
3c67d83a
TH
3503 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3504 }
3505
4a0ee12a 3506 if (spa_dir_prop(spa, DMU_POOL_SYNC_BPOBJ, &obj, B_TRUE) != 0)
428870ff
BB
3507 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3508 error = bpobj_open(&spa->spa_deferred_bpobj, spa->spa_meta_objset, obj);
4a0ee12a
PZ
3509 if (error != 0) {
3510 spa_load_failed(spa, "error opening deferred-frees bpobj "
3511 "[error=%d]", error);
428870ff 3512 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4a0ee12a 3513 }
34dc7c2f
BB
3514
3515 /*
3516 * Load the bit that tells us to use the new accounting function
3517 * (raid-z deflation). If we have an older pool, this will not
3518 * be present.
3519 */
4a0ee12a 3520 error = spa_dir_prop(spa, DMU_POOL_DEFLATE, &spa->spa_deflate, B_FALSE);
428870ff
BB
3521 if (error != 0 && error != ENOENT)
3522 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3523
3524 error = spa_dir_prop(spa, DMU_POOL_CREATION_VERSION,
4a0ee12a 3525 &spa->spa_creation_version, B_FALSE);
428870ff
BB
3526 if (error != 0 && error != ENOENT)
3527 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
34dc7c2f
BB
3528
3529 /*
3530 * Load the persistent error log. If we have an older pool, this will
3531 * not be present.
3532 */
4a0ee12a
PZ
3533 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_LAST, &spa->spa_errlog_last,
3534 B_FALSE);
428870ff
BB
3535 if (error != 0 && error != ENOENT)
3536 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
34dc7c2f 3537
428870ff 3538 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_SCRUB,
4a0ee12a 3539 &spa->spa_errlog_scrub, B_FALSE);
428870ff
BB
3540 if (error != 0 && error != ENOENT)
3541 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
34dc7c2f
BB
3542
3543 /*
3544 * Load the history object. If we have an older pool, this
3545 * will not be present.
3546 */
4a0ee12a 3547 error = spa_dir_prop(spa, DMU_POOL_HISTORY, &spa->spa_history, B_FALSE);
428870ff
BB
3548 if (error != 0 && error != ENOENT)
3549 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3550
e0ab3ab5
JS
3551 /*
3552 * Load the per-vdev ZAP map. If we have an older pool, this will not
3553 * be present; in this case, defer its creation to a later time to
3554 * avoid dirtying the MOS this early / out of sync context. See
3555 * spa_sync_config_object.
3556 */
3557
3558 /* The sentinel is only available in the MOS config. */
1c27024e 3559 nvlist_t *mos_config;
4a0ee12a
PZ
3560 if (load_nvlist(spa, spa->spa_config_object, &mos_config) != 0) {
3561 spa_load_failed(spa, "unable to retrieve MOS config");
e0ab3ab5 3562 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4a0ee12a 3563 }
e0ab3ab5
JS
3564
3565 error = spa_dir_prop(spa, DMU_POOL_VDEV_ZAP_MAP,
4a0ee12a 3566 &spa->spa_all_vdev_zaps, B_FALSE);
e0ab3ab5 3567
38640550
DB
3568 if (error == ENOENT) {
3569 VERIFY(!nvlist_exists(mos_config,
3570 ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
3571 spa->spa_avz_action = AVZ_ACTION_INITIALIZE;
3572 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3573 } else if (error != 0) {
e0ab3ab5 3574 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
38640550 3575 } else if (!nvlist_exists(mos_config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS)) {
e0ab3ab5
JS
3576 /*
3577 * An older version of ZFS overwrote the sentinel value, so
3578 * we have orphaned per-vdev ZAPs in the MOS. Defer their
3579 * destruction to later; see spa_sync_config_object.
3580 */
3581 spa->spa_avz_action = AVZ_ACTION_DESTROY;
3582 /*
3583 * We're assuming that no vdevs have had their ZAPs created
3584 * before this. Better be sure of it.
3585 */
3586 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3587 }
3588 nvlist_free(mos_config);
3589
9eb7b46e
PZ
3590 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
3591
4a0ee12a
PZ
3592 error = spa_dir_prop(spa, DMU_POOL_PROPS, &spa->spa_pool_props_object,
3593 B_FALSE);
9eb7b46e
PZ
3594 if (error && error != ENOENT)
3595 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3596
3597 if (error == 0) {
3598 uint64_t autoreplace;
3599
3600 spa_prop_find(spa, ZPOOL_PROP_BOOTFS, &spa->spa_bootfs);
3601 spa_prop_find(spa, ZPOOL_PROP_AUTOREPLACE, &autoreplace);
3602 spa_prop_find(spa, ZPOOL_PROP_DELEGATION, &spa->spa_delegation);
3603 spa_prop_find(spa, ZPOOL_PROP_FAILUREMODE, &spa->spa_failmode);
3604 spa_prop_find(spa, ZPOOL_PROP_AUTOEXPAND, &spa->spa_autoexpand);
c02c1bec 3605 spa_prop_find(spa, ZPOOL_PROP_MULTIHOST, &spa->spa_multihost);
9eb7b46e
PZ
3606 spa_prop_find(spa, ZPOOL_PROP_DEDUPDITTO,
3607 &spa->spa_dedup_ditto);
1b939560 3608 spa_prop_find(spa, ZPOOL_PROP_AUTOTRIM, &spa->spa_autotrim);
9eb7b46e
PZ
3609 spa->spa_autoreplace = (autoreplace != 0);
3610 }
3611
6cb8e530
PZ
3612 /*
3613 * If we are importing a pool with missing top-level vdevs,
3614 * we enforce that the pool doesn't panic or get suspended on
3615 * error since the likelihood of missing data is extremely high.
3616 */
3617 if (spa->spa_missing_tvds > 0 &&
3618 spa->spa_failmode != ZIO_FAILURE_MODE_CONTINUE &&
3619 spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3620 spa_load_note(spa, "forcing failmode to 'continue' "
3621 "as some top level vdevs are missing");
3622 spa->spa_failmode = ZIO_FAILURE_MODE_CONTINUE;
3623 }
3624
9eb7b46e
PZ
3625 return (0);
3626}
3627
3628static int
3629spa_ld_open_aux_vdevs(spa_t *spa, spa_import_type_t type)
3630{
3631 int error = 0;
3632 vdev_t *rvd = spa->spa_root_vdev;
3633
428870ff
BB
3634 /*
3635 * If we're assembling the pool from the split-off vdevs of
3636 * an existing pool, we don't want to attach the spares & cache
3637 * devices.
3638 */
34dc7c2f
BB
3639
3640 /*
3641 * Load any hot spares for this pool.
3642 */
4a0ee12a
PZ
3643 error = spa_dir_prop(spa, DMU_POOL_SPARES, &spa->spa_spares.sav_object,
3644 B_FALSE);
428870ff
BB
3645 if (error != 0 && error != ENOENT)
3646 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3647 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
34dc7c2f
BB
3648 ASSERT(spa_version(spa) >= SPA_VERSION_SPARES);
3649 if (load_nvlist(spa, spa->spa_spares.sav_object,
4a0ee12a
PZ
3650 &spa->spa_spares.sav_config) != 0) {
3651 spa_load_failed(spa, "error loading spares nvlist");
428870ff 3652 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4a0ee12a 3653 }
34dc7c2f 3654
b128c09f 3655 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 3656 spa_load_spares(spa);
b128c09f 3657 spa_config_exit(spa, SCL_ALL, FTAG);
428870ff
BB
3658 } else if (error == 0) {
3659 spa->spa_spares.sav_sync = B_TRUE;
34dc7c2f
BB
3660 }
3661
3662 /*
3663 * Load any level 2 ARC devices for this pool.
3664 */
428870ff 3665 error = spa_dir_prop(spa, DMU_POOL_L2CACHE,
4a0ee12a 3666 &spa->spa_l2cache.sav_object, B_FALSE);
428870ff
BB
3667 if (error != 0 && error != ENOENT)
3668 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3669 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
34dc7c2f
BB
3670 ASSERT(spa_version(spa) >= SPA_VERSION_L2CACHE);
3671 if (load_nvlist(spa, spa->spa_l2cache.sav_object,
4a0ee12a
PZ
3672 &spa->spa_l2cache.sav_config) != 0) {
3673 spa_load_failed(spa, "error loading l2cache nvlist");
428870ff 3674 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4a0ee12a 3675 }
34dc7c2f 3676
b128c09f 3677 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 3678 spa_load_l2cache(spa);
b128c09f 3679 spa_config_exit(spa, SCL_ALL, FTAG);
428870ff
BB
3680 } else if (error == 0) {
3681 spa->spa_l2cache.sav_sync = B_TRUE;
b128c09f
BB
3682 }
3683
9eb7b46e
PZ
3684 return (0);
3685}
428870ff 3686
9eb7b46e 3687static int
4a0ee12a 3688spa_ld_load_vdev_metadata(spa_t *spa)
9eb7b46e
PZ
3689{
3690 int error = 0;
3691 vdev_t *rvd = spa->spa_root_vdev;
34dc7c2f 3692
379ca9cf
OF
3693 /*
3694 * If the 'multihost' property is set, then never allow a pool to
3695 * be imported when the system hostid is zero. The exception to
3696 * this rule is zdb which is always allowed to access pools.
3697 */
3698 if (spa_multihost(spa) && spa_get_hostid() == 0 &&
3699 (spa->spa_import_flags & ZFS_IMPORT_SKIP_MMP) == 0) {
3700 fnvlist_add_uint64(spa->spa_load_info,
3701 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_NO_HOSTID);
3702 return (spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO));
3703 }
3704
34dc7c2f
BB
3705 /*
3706 * If the 'autoreplace' property is set, then post a resource notifying
3707 * the ZFS DE that it should not issue any faults for unopenable
3708 * devices. We also iterate over the vdevs, and post a sysevent for any
3709 * unopenable vdevs so that the normal autoreplace handler can take
3710 * over.
3711 */
4a0ee12a 3712 if (spa->spa_autoreplace && spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
34dc7c2f 3713 spa_check_removed(spa->spa_root_vdev);
428870ff
BB
3714 /*
3715 * For the import case, this is done in spa_import(), because
3716 * at this point we're using the spare definitions from
3717 * the MOS config, not necessarily from the userland config.
3718 */
4a0ee12a 3719 if (spa->spa_load_state != SPA_LOAD_IMPORT) {
428870ff
BB
3720 spa_aux_check_removed(&spa->spa_spares);
3721 spa_aux_check_removed(&spa->spa_l2cache);
3722 }
3723 }
34dc7c2f
BB
3724
3725 /*
9eb7b46e 3726 * Load the vdev metadata such as metaslabs, DTLs, spacemap object, etc.
34dc7c2f 3727 */
a1d477c2
MA
3728 error = vdev_load(rvd);
3729 if (error != 0) {
4a0ee12a 3730 spa_load_failed(spa, "vdev_load failed [error=%d]", error);
a1d477c2
MA
3731 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3732 }
3733
34dc7c2f 3734 /*
9eb7b46e 3735 * Propagate the leaf DTLs we just loaded all the way up the vdev tree.
34dc7c2f 3736 */
b128c09f 3737 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 3738 vdev_dtl_reassess(rvd, 0, 0, B_FALSE);
b128c09f 3739 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f 3740
9eb7b46e
PZ
3741 return (0);
3742}
3743
3744static int
3745spa_ld_load_dedup_tables(spa_t *spa)
3746{
3747 int error = 0;
3748 vdev_t *rvd = spa->spa_root_vdev;
3749
428870ff 3750 error = ddt_load(spa);
4a0ee12a
PZ
3751 if (error != 0) {
3752 spa_load_failed(spa, "ddt_load failed [error=%d]", error);
428870ff 3753 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4a0ee12a 3754 }
428870ff 3755
9eb7b46e
PZ
3756 return (0);
3757}
3758
3759static int
3760spa_ld_verify_logs(spa_t *spa, spa_import_type_t type, char **ereport)
3761{
3762 vdev_t *rvd = spa->spa_root_vdev;
428870ff 3763
4a0ee12a
PZ
3764 if (type != SPA_IMPORT_ASSEMBLE && spa_writeable(spa)) {
3765 boolean_t missing = spa_check_logs(spa);
3766 if (missing) {
6cb8e530
PZ
3767 if (spa->spa_missing_tvds != 0) {
3768 spa_load_note(spa, "spa_check_logs failed "
3769 "so dropping the logs");
3770 } else {
3771 *ereport = FM_EREPORT_ZFS_LOG_REPLAY;
3772 spa_load_failed(spa, "spa_check_logs failed");
3773 return (spa_vdev_err(rvd, VDEV_AUX_BAD_LOG,
3774 ENXIO));
3775 }
4a0ee12a 3776 }
428870ff
BB
3777 }
3778
9eb7b46e
PZ
3779 return (0);
3780}
3781
3782static int
4a0ee12a 3783spa_ld_verify_pool_data(spa_t *spa)
9eb7b46e
PZ
3784{
3785 int error = 0;
3786 vdev_t *rvd = spa->spa_root_vdev;
3787
3788 /*
3789 * We've successfully opened the pool, verify that we're ready
3790 * to start pushing transactions.
3791 */
4a0ee12a 3792 if (spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
9eb7b46e
PZ
3793 error = spa_load_verify(spa);
3794 if (error != 0) {
4a0ee12a
PZ
3795 spa_load_failed(spa, "spa_load_verify failed "
3796 "[error=%d]", error);
9eb7b46e
PZ
3797 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3798 error));
3799 }
3800 }
3801
3802 return (0);
3803}
3804
3805static void
3806spa_ld_claim_log_blocks(spa_t *spa)
3807{
3808 dmu_tx_t *tx;
3809 dsl_pool_t *dp = spa_get_dsl(spa);
3810
3811 /*
3812 * Claim log blocks that haven't been committed yet.
3813 * This must all happen in a single txg.
3814 * Note: spa_claim_max_txg is updated by spa_claim_notify(),
3815 * invoked from zil_claim_log_block()'s i/o done callback.
3816 * Price of rollback is that we abandon the log.
3817 */
3818 spa->spa_claiming = B_TRUE;
3819
3820 tx = dmu_tx_create_assigned(dp, spa_first_txg(spa));
3821 (void) dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
3822 zil_claim, tx, DS_FIND_CHILDREN);
3823 dmu_tx_commit(tx);
3824
3825 spa->spa_claiming = B_FALSE;
3826
3827 spa_set_log_state(spa, SPA_LOG_GOOD);
3828}
3829
3830static void
6cb8e530 3831spa_ld_check_for_config_update(spa_t *spa, uint64_t config_cache_txg,
d2734cce 3832 boolean_t update_config_cache)
9eb7b46e
PZ
3833{
3834 vdev_t *rvd = spa->spa_root_vdev;
3835 int need_update = B_FALSE;
3836
3837 /*
3838 * If the config cache is stale, or we have uninitialized
3839 * metaslabs (see spa_vdev_add()), then update the config.
3840 *
3841 * If this is a verbatim import, trust the current
3842 * in-core spa_config and update the disk labels.
3843 */
d2734cce 3844 if (update_config_cache || config_cache_txg != spa->spa_config_txg ||
4a0ee12a
PZ
3845 spa->spa_load_state == SPA_LOAD_IMPORT ||
3846 spa->spa_load_state == SPA_LOAD_RECOVER ||
9eb7b46e
PZ
3847 (spa->spa_import_flags & ZFS_IMPORT_VERBATIM))
3848 need_update = B_TRUE;
3849
3850 for (int c = 0; c < rvd->vdev_children; c++)
3851 if (rvd->vdev_child[c]->vdev_ms_array == 0)
3852 need_update = B_TRUE;
3853
3854 /*
3855 * Update the config cache asychronously in case we're the
3856 * root pool, in which case the config cache isn't writable yet.
3857 */
3858 if (need_update)
3859 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
3860}
3861
6cb8e530
PZ
3862static void
3863spa_ld_prepare_for_reload(spa_t *spa)
3864{
3865 int mode = spa->spa_mode;
3866 int async_suspended = spa->spa_async_suspended;
3867
3868 spa_unload(spa);
3869 spa_deactivate(spa);
3870 spa_activate(spa, mode);
3871
3872 /*
3873 * We save the value of spa_async_suspended as it gets reset to 0 by
3874 * spa_unload(). We want to restore it back to the original value before
3875 * returning as we might be calling spa_async_resume() later.
3876 */
3877 spa->spa_async_suspended = async_suspended;
3878}
3879
9eb7b46e 3880static int
d2734cce
SD
3881spa_ld_read_checkpoint_txg(spa_t *spa)
3882{
3883 uberblock_t checkpoint;
3884 int error = 0;
3885
3886 ASSERT0(spa->spa_checkpoint_txg);
3887 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3888
3889 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3890 DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
3891 sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
3892
3893 if (error == ENOENT)
3894 return (0);
3895
3896 if (error != 0)
3897 return (error);
3898
3899 ASSERT3U(checkpoint.ub_txg, !=, 0);
3900 ASSERT3U(checkpoint.ub_checkpoint_txg, !=, 0);
3901 ASSERT3U(checkpoint.ub_timestamp, !=, 0);
3902 spa->spa_checkpoint_txg = checkpoint.ub_txg;
3903 spa->spa_checkpoint_info.sci_timestamp = checkpoint.ub_timestamp;
3904
3905 return (0);
3906}
3907
3908static int
3909spa_ld_mos_init(spa_t *spa, spa_import_type_t type)
9eb7b46e
PZ
3910{
3911 int error = 0;
9eb7b46e 3912
4a0ee12a 3913 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6cb8e530 3914 ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
4a0ee12a 3915
9eb7b46e 3916 /*
6cb8e530
PZ
3917 * Never trust the config that is provided unless we are assembling
3918 * a pool following a split.
3919 * This means don't trust blkptrs and the vdev tree in general. This
3920 * also effectively puts the spa in read-only mode since
3921 * spa_writeable() checks for spa_trust_config to be true.
3922 * We will later load a trusted config from the MOS.
9eb7b46e 3923 */
6cb8e530
PZ
3924 if (type != SPA_IMPORT_ASSEMBLE)
3925 spa->spa_trust_config = B_FALSE;
3926
9eb7b46e
PZ
3927 /*
3928 * Parse the config provided to create a vdev tree.
3929 */
6cb8e530 3930 error = spa_ld_parse_config(spa, type);
9eb7b46e
PZ
3931 if (error != 0)
3932 return (error);
3933
ca95f70d
OF
3934 spa_import_progress_add(spa);
3935
9eb7b46e
PZ
3936 /*
3937 * Now that we have the vdev tree, try to open each vdev. This involves
3938 * opening the underlying physical device, retrieving its geometry and
3939 * probing the vdev with a dummy I/O. The state of each vdev will be set
3940 * based on the success of those operations. After this we'll be ready
3941 * to read from the vdevs.
3942 */
3943 error = spa_ld_open_vdevs(spa);
3944 if (error != 0)
3945 return (error);
3946
3947 /*
3948 * Read the label of each vdev and make sure that the GUIDs stored
3949 * there match the GUIDs in the config provided.
6cb8e530
PZ
3950 * If we're assembling a new pool that's been split off from an
3951 * existing pool, the labels haven't yet been updated so we skip
3952 * validation for now.
9eb7b46e 3953 */
6cb8e530
PZ
3954 if (type != SPA_IMPORT_ASSEMBLE) {
3955 error = spa_ld_validate_vdevs(spa);
3956 if (error != 0)
3957 return (error);
3958 }
9eb7b46e
PZ
3959
3960 /*
d2734cce
SD
3961 * Read all vdev labels to find the best uberblock (i.e. latest,
3962 * unless spa_load_max_txg is set) and store it in spa_uberblock. We
3963 * get the list of features required to read blkptrs in the MOS from
3964 * the vdev label with the best uberblock and verify that our version
3965 * of zfs supports them all.
9eb7b46e 3966 */
6cb8e530 3967 error = spa_ld_select_uberblock(spa, type);
9eb7b46e
PZ
3968 if (error != 0)
3969 return (error);
3970
3971 /*
3972 * Pass that uberblock to the dsl_pool layer which will open the root
3973 * blkptr. This blkptr points to the latest version of the MOS and will
3974 * allow us to read its contents.
3975 */
3976 error = spa_ld_open_rootbp(spa);
3977 if (error != 0)
3978 return (error);
3979
d2734cce
SD
3980 return (0);
3981}
3982
3983static int
3984spa_ld_checkpoint_rewind(spa_t *spa)
3985{
3986 uberblock_t checkpoint;
3987 int error = 0;
3988
3989 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3990 ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
3991
3992 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3993 DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
3994 sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
3995
3996 if (error != 0) {
3997 spa_load_failed(spa, "unable to retrieve checkpointed "
3998 "uberblock from the MOS config [error=%d]", error);
3999
4000 if (error == ENOENT)
4001 error = ZFS_ERR_NO_CHECKPOINT;
4002
4003 return (error);
4004 }
4005
4006 ASSERT3U(checkpoint.ub_txg, <, spa->spa_uberblock.ub_txg);
4007 ASSERT3U(checkpoint.ub_txg, ==, checkpoint.ub_checkpoint_txg);
4008
4009 /*
4010 * We need to update the txg and timestamp of the checkpointed
4011 * uberblock to be higher than the latest one. This ensures that
4012 * the checkpointed uberblock is selected if we were to close and
4013 * reopen the pool right after we've written it in the vdev labels.
4014 * (also see block comment in vdev_uberblock_compare)
4015 */
4016 checkpoint.ub_txg = spa->spa_uberblock.ub_txg + 1;
4017 checkpoint.ub_timestamp = gethrestime_sec();
4018
4019 /*
4020 * Set current uberblock to be the checkpointed uberblock.
4021 */
4022 spa->spa_uberblock = checkpoint;
4023
4024 /*
4025 * If we are doing a normal rewind, then the pool is open for
4026 * writing and we sync the "updated" checkpointed uberblock to
4027 * disk. Once this is done, we've basically rewound the whole
4028 * pool and there is no way back.
4029 *
4030 * There are cases when we don't want to attempt and sync the
4031 * checkpointed uberblock to disk because we are opening a
4032 * pool as read-only. Specifically, verifying the checkpointed
4033 * state with zdb, and importing the checkpointed state to get
4034 * a "preview" of its content.
4035 */
4036 if (spa_writeable(spa)) {
4037 vdev_t *rvd = spa->spa_root_vdev;
4038
4039 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4040 vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
4041 int svdcount = 0;
4042 int children = rvd->vdev_children;
4043 int c0 = spa_get_random(children);
4044
4045 for (int c = 0; c < children; c++) {
4046 vdev_t *vd = rvd->vdev_child[(c0 + c) % children];
4047
4048 /* Stop when revisiting the first vdev */
4049 if (c > 0 && svd[0] == vd)
4050 break;
4051
4052 if (vd->vdev_ms_array == 0 || vd->vdev_islog ||
4053 !vdev_is_concrete(vd))
4054 continue;
4055
4056 svd[svdcount++] = vd;
4057 if (svdcount == SPA_SYNC_MIN_VDEVS)
4058 break;
4059 }
4060 error = vdev_config_sync(svd, svdcount, spa->spa_first_txg);
4061 if (error == 0)
4062 spa->spa_last_synced_guid = rvd->vdev_guid;
4063 spa_config_exit(spa, SCL_ALL, FTAG);
4064
4065 if (error != 0) {
4066 spa_load_failed(spa, "failed to write checkpointed "
4067 "uberblock to the vdev labels [error=%d]", error);
4068 return (error);
4069 }
4070 }
4071
4072 return (0);
4073}
4074
4075static int
4076spa_ld_mos_with_trusted_config(spa_t *spa, spa_import_type_t type,
4077 boolean_t *update_config_cache)
4078{
4079 int error;
4080
4081 /*
4082 * Parse the config for pool, open and validate vdevs,
4083 * select an uberblock, and use that uberblock to open
4084 * the MOS.
4085 */
4086 error = spa_ld_mos_init(spa, type);
4087 if (error != 0)
4088 return (error);
4089
9eb7b46e 4090 /*
6cb8e530
PZ
4091 * Retrieve the trusted config stored in the MOS and use it to create
4092 * a new, exact version of the vdev tree, then reopen all vdevs.
9eb7b46e 4093 */
d2734cce 4094 error = spa_ld_trusted_config(spa, type, B_FALSE);
6cb8e530 4095 if (error == EAGAIN) {
d2734cce
SD
4096 if (update_config_cache != NULL)
4097 *update_config_cache = B_TRUE;
4098
6cb8e530
PZ
4099 /*
4100 * Redo the loading process with the trusted config if it is
4101 * too different from the untrusted config.
4102 */
4103 spa_ld_prepare_for_reload(spa);
d2734cce
SD
4104 spa_load_note(spa, "RELOADING");
4105 error = spa_ld_mos_init(spa, type);
4106 if (error != 0)
4107 return (error);
4108
4109 error = spa_ld_trusted_config(spa, type, B_TRUE);
4110 if (error != 0)
4111 return (error);
4112
6cb8e530 4113 } else if (error != 0) {
9eb7b46e 4114 return (error);
6cb8e530 4115 }
9eb7b46e 4116
d2734cce
SD
4117 return (0);
4118}
4119
4120/*
4121 * Load an existing storage pool, using the config provided. This config
4122 * describes which vdevs are part of the pool and is later validated against
4123 * partial configs present in each vdev's label and an entire copy of the
4124 * config stored in the MOS.
4125 */
4126static int
4127spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport)
4128{
4129 int error = 0;
4130 boolean_t missing_feat_write = B_FALSE;
4131 boolean_t checkpoint_rewind =
4132 (spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
4133 boolean_t update_config_cache = B_FALSE;
4134
4135 ASSERT(MUTEX_HELD(&spa_namespace_lock));
4136 ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
4137
4138 spa_load_note(spa, "LOADING");
4139
4140 error = spa_ld_mos_with_trusted_config(spa, type, &update_config_cache);
4141 if (error != 0)
4142 return (error);
4143
4144 /*
4145 * If we are rewinding to the checkpoint then we need to repeat
4146 * everything we've done so far in this function but this time
4147 * selecting the checkpointed uberblock and using that to open
4148 * the MOS.
4149 */
4150 if (checkpoint_rewind) {
4151 /*
4152 * If we are rewinding to the checkpoint update config cache
4153 * anyway.
4154 */
4155 update_config_cache = B_TRUE;
4156
4157 /*
4158 * Extract the checkpointed uberblock from the current MOS
4159 * and use this as the pool's uberblock from now on. If the
4160 * pool is imported as writeable we also write the checkpoint
4161 * uberblock to the labels, making the rewind permanent.
4162 */
4163 error = spa_ld_checkpoint_rewind(spa);
4164 if (error != 0)
4165 return (error);
4166
4167 /*
4168 * Redo the loading process process again with the
4169 * checkpointed uberblock.
4170 */
4171 spa_ld_prepare_for_reload(spa);
4172 spa_load_note(spa, "LOADING checkpointed uberblock");
4173 error = spa_ld_mos_with_trusted_config(spa, type, NULL);
4174 if (error != 0)
4175 return (error);
4176 }
4177
4178 /*
4179 * Retrieve the checkpoint txg if the pool has a checkpoint.
4180 */
4181 error = spa_ld_read_checkpoint_txg(spa);
4182 if (error != 0)
4183 return (error);
4184
9eb7b46e
PZ
4185 /*
4186 * Retrieve the mapping of indirect vdevs. Those vdevs were removed
4187 * from the pool and their contents were re-mapped to other vdevs. Note
4188 * that everything that we read before this step must have been
4189 * rewritten on concrete vdevs after the last device removal was
4190 * initiated. Otherwise we could be reading from indirect vdevs before
4191 * we have loaded their mappings.
4192 */
4193 error = spa_ld_open_indirect_vdev_metadata(spa);
4194 if (error != 0)
4195 return (error);
4196
4197 /*
4198 * Retrieve the full list of active features from the MOS and check if
4199 * they are all supported.
4200 */
4a0ee12a 4201 error = spa_ld_check_features(spa, &missing_feat_write);
9eb7b46e
PZ
4202 if (error != 0)
4203 return (error);
4204
4205 /*
4206 * Load several special directories from the MOS needed by the dsl_pool
4207 * layer.
4208 */
4209 error = spa_ld_load_special_directories(spa);
4210 if (error != 0)
4211 return (error);
4212
9eb7b46e
PZ
4213 /*
4214 * Retrieve pool properties from the MOS.
4215 */
4216 error = spa_ld_get_props(spa);
4217 if (error != 0)
4218 return (error);
4219
4220 /*
4221 * Retrieve the list of auxiliary devices - cache devices and spares -
4222 * and open them.
4223 */
4224 error = spa_ld_open_aux_vdevs(spa, type);
4225 if (error != 0)
4226 return (error);
4227
4228 /*
4229 * Load the metadata for all vdevs. Also check if unopenable devices
4230 * should be autoreplaced.
4231 */
4a0ee12a 4232 error = spa_ld_load_vdev_metadata(spa);
9eb7b46e
PZ
4233 if (error != 0)
4234 return (error);
4235
4236 error = spa_ld_load_dedup_tables(spa);
4237 if (error != 0)
4238 return (error);
4239
4240 /*
4241 * Verify the logs now to make sure we don't have any unexpected errors
4242 * when we claim log blocks later.
4243 */
4244 error = spa_ld_verify_logs(spa, type, ereport);
4245 if (error != 0)
4246 return (error);
4247
9ae529ec 4248 if (missing_feat_write) {
6cb8e530 4249 ASSERT(spa->spa_load_state == SPA_LOAD_TRYIMPORT);
9ae529ec
CS
4250
4251 /*
4252 * At this point, we know that we can open the pool in
4253 * read-only mode but not read-write mode. We now have enough
4254 * information and can return to userland.
4255 */
9eb7b46e
PZ
4256 return (spa_vdev_err(spa->spa_root_vdev, VDEV_AUX_UNSUP_FEAT,
4257 ENOTSUP));
9ae529ec
CS
4258 }
4259
572e2857 4260 /*
9eb7b46e
PZ
4261 * Traverse the last txgs to make sure the pool was left off in a safe
4262 * state. When performing an extreme rewind, we verify the whole pool,
4263 * which can take a very long time.
572e2857 4264 */
4a0ee12a 4265 error = spa_ld_verify_pool_data(spa);
9eb7b46e
PZ
4266 if (error != 0)
4267 return (error);
572e2857 4268
9eb7b46e
PZ
4269 /*
4270 * Calculate the deflated space for the pool. This must be done before
4271 * we write anything to the pool because we'd need to update the space
4272 * accounting using the deflated sizes.
4273 */
4274 spa_update_dspace(spa);
4275
4276 /*
4277 * We have now retrieved all the information we needed to open the
4278 * pool. If we are importing the pool in read-write mode, a few
4279 * additional steps must be performed to finish the import.
4280 */
6cb8e530 4281 if (spa_writeable(spa) && (spa->spa_load_state == SPA_LOAD_RECOVER ||
428870ff 4282 spa->spa_load_max_txg == UINT64_MAX)) {
6cb8e530
PZ
4283 uint64_t config_cache_txg = spa->spa_config_txg;
4284
4285 ASSERT(spa->spa_load_state != SPA_LOAD_TRYIMPORT);
34dc7c2f 4286
d2734cce
SD
4287 /*
4288 * In case of a checkpoint rewind, log the original txg
4289 * of the checkpointed uberblock.
4290 */
4291 if (checkpoint_rewind) {
4292 spa_history_log_internal(spa, "checkpoint rewind",
4293 NULL, "rewound state to txg=%llu",
4294 (u_longlong_t)spa->spa_uberblock.ub_checkpoint_txg);
4295 }
4296
34dc7c2f 4297 /*
9eb7b46e 4298 * Traverse the ZIL and claim all blocks.
34dc7c2f 4299 */
9eb7b46e 4300 spa_ld_claim_log_blocks(spa);
428870ff 4301
9eb7b46e
PZ
4302 /*
4303 * Kick-off the syncing thread.
4304 */
34dc7c2f
BB
4305 spa->spa_sync_on = B_TRUE;
4306 txg_sync_start(spa->spa_dsl_pool);
379ca9cf 4307 mmp_thread_start(spa);
34dc7c2f
BB
4308
4309 /*
428870ff
BB
4310 * Wait for all claims to sync. We sync up to the highest
4311 * claimed log block birth time so that claimed log blocks
4312 * don't appear to be from the future. spa_claim_max_txg
9eb7b46e
PZ
4313 * will have been set for us by ZIL traversal operations
4314 * performed above.
34dc7c2f 4315 */
428870ff 4316 txg_wait_synced(spa->spa_dsl_pool, spa->spa_claim_max_txg);
34dc7c2f
BB
4317
4318 /*
9eb7b46e
PZ
4319 * Check if we need to request an update of the config. On the
4320 * next sync, we would update the config stored in vdev labels
4321 * and the cachefile (by default /etc/zfs/zpool.cache).
34dc7c2f 4322 */
6cb8e530 4323 spa_ld_check_for_config_update(spa, config_cache_txg,
d2734cce 4324 update_config_cache);
fb5f0bc8
BB
4325
4326 /*
4327 * Check all DTLs to see if anything needs resilvering.
4328 */
428870ff 4329 if (!dsl_scan_resilvering(spa->spa_dsl_pool) &&
9eb7b46e 4330 vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL))
fb5f0bc8 4331 spa_async_request(spa, SPA_ASYNC_RESILVER);
428870ff 4332
6f1ffb06
MA
4333 /*
4334 * Log the fact that we booted up (so that we can detect if
4335 * we rebooted in the middle of an operation).
4336 */
d5e024cb 4337 spa_history_log_version(spa, "open", NULL);
6f1ffb06 4338
9b2266e3
SD
4339 spa_restart_removal(spa);
4340 spa_spawn_aux_threads(spa);
4341
428870ff
BB
4342 /*
4343 * Delete any inconsistent datasets.
9b2266e3
SD
4344 *
4345 * Note:
4346 * Since we may be issuing deletes for clones here,
4347 * we make sure to do so after we've spawned all the
4348 * auxiliary threads above (from which the livelist
4349 * deletion zthr is part of).
428870ff
BB
4350 */
4351 (void) dmu_objset_find(spa_name(spa),
4352 dsl_destroy_inconsistent, NULL, DS_FIND_CHILDREN);
4353
4354 /*
4355 * Clean up any stale temporary dataset userrefs.
4356 */
4357 dsl_pool_clean_tmp_userrefs(spa->spa_dsl_pool);
a1d477c2 4358
619f0976
GW
4359 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4360 vdev_initialize_restart(spa->spa_root_vdev);
1b939560
BB
4361 vdev_trim_restart(spa->spa_root_vdev);
4362 vdev_autotrim_restart(spa);
619f0976 4363 spa_config_exit(spa, SCL_CONFIG, FTAG);
34dc7c2f
BB
4364 }
4365
ca95f70d 4366 spa_import_progress_remove(spa_guid(spa));
4a0ee12a
PZ
4367 spa_load_note(spa, "LOADED");
4368
428870ff
BB
4369 return (0);
4370}
34dc7c2f 4371
428870ff 4372static int
6cb8e530 4373spa_load_retry(spa_t *spa, spa_load_state_t state)
428870ff 4374{
572e2857
BB
4375 int mode = spa->spa_mode;
4376
428870ff
BB
4377 spa_unload(spa);
4378 spa_deactivate(spa);
4379
dea377c0 4380 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg - 1;
428870ff 4381
572e2857 4382 spa_activate(spa, mode);
428870ff
BB
4383 spa_async_suspend(spa);
4384
4a0ee12a
PZ
4385 spa_load_note(spa, "spa_load_retry: rewind, max txg: %llu",
4386 (u_longlong_t)spa->spa_load_max_txg);
4387
6cb8e530 4388 return (spa_load(spa, state, SPA_IMPORT_EXISTING));
428870ff
BB
4389}
4390
9ae529ec
CS
4391/*
4392 * If spa_load() fails this function will try loading prior txg's. If
4393 * 'state' is SPA_LOAD_RECOVER and one of these loads succeeds the pool
4394 * will be rewound to that txg. If 'state' is not SPA_LOAD_RECOVER this
4395 * function will not rewind the pool and will return the same error as
4396 * spa_load().
4397 */
428870ff 4398static int
6cb8e530
PZ
4399spa_load_best(spa_t *spa, spa_load_state_t state, uint64_t max_request,
4400 int rewind_flags)
428870ff 4401{
9ae529ec 4402 nvlist_t *loadinfo = NULL;
428870ff
BB
4403 nvlist_t *config = NULL;
4404 int load_error, rewind_error;
4405 uint64_t safe_rewind_txg;
4406 uint64_t min_txg;
4407
4408 if (spa->spa_load_txg && state == SPA_LOAD_RECOVER) {
4409 spa->spa_load_max_txg = spa->spa_load_txg;
4410 spa_set_log_state(spa, SPA_LOG_CLEAR);
4411 } else {
4412 spa->spa_load_max_txg = max_request;
dea377c0
MA
4413 if (max_request != UINT64_MAX)
4414 spa->spa_extreme_rewind = B_TRUE;
428870ff
BB
4415 }
4416
6cb8e530 4417 load_error = rewind_error = spa_load(spa, state, SPA_IMPORT_EXISTING);
428870ff
BB
4418 if (load_error == 0)
4419 return (0);
d2734cce
SD
4420 if (load_error == ZFS_ERR_NO_CHECKPOINT) {
4421 /*
4422 * When attempting checkpoint-rewind on a pool with no
4423 * checkpoint, we should not attempt to load uberblocks
4424 * from previous txgs when spa_load fails.
4425 */
4426 ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
ca95f70d 4427 spa_import_progress_remove(spa_guid(spa));
d2734cce
SD
4428 return (load_error);
4429 }
428870ff
BB
4430
4431 if (spa->spa_root_vdev != NULL)
4432 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4433
4434 spa->spa_last_ubsync_txg = spa->spa_uberblock.ub_txg;
4435 spa->spa_last_ubsync_txg_ts = spa->spa_uberblock.ub_timestamp;
4436
4437 if (rewind_flags & ZPOOL_NEVER_REWIND) {
4438 nvlist_free(config);
ca95f70d 4439 spa_import_progress_remove(spa_guid(spa));
428870ff
BB
4440 return (load_error);
4441 }
4442
9ae529ec
CS
4443 if (state == SPA_LOAD_RECOVER) {
4444 /* Price of rolling back is discarding txgs, including log */
428870ff 4445 spa_set_log_state(spa, SPA_LOG_CLEAR);
9ae529ec
CS
4446 } else {
4447 /*
4448 * If we aren't rolling back save the load info from our first
4449 * import attempt so that we can restore it after attempting
4450 * to rewind.
4451 */
4452 loadinfo = spa->spa_load_info;
4453 spa->spa_load_info = fnvlist_alloc();
4454 }
428870ff
BB
4455
4456 spa->spa_load_max_txg = spa->spa_last_ubsync_txg;
4457 safe_rewind_txg = spa->spa_last_ubsync_txg - TXG_DEFER_SIZE;
4458 min_txg = (rewind_flags & ZPOOL_EXTREME_REWIND) ?
4459 TXG_INITIAL : safe_rewind_txg;
4460
4461 /*
4462 * Continue as long as we're finding errors, we're still within
4463 * the acceptable rewind range, and we're still finding uberblocks
4464 */
4465 while (rewind_error && spa->spa_uberblock.ub_txg >= min_txg &&
4466 spa->spa_uberblock.ub_txg <= spa->spa_load_max_txg) {
4467 if (spa->spa_load_max_txg < safe_rewind_txg)
4468 spa->spa_extreme_rewind = B_TRUE;
6cb8e530 4469 rewind_error = spa_load_retry(spa, state);
428870ff
BB
4470 }
4471
428870ff
BB
4472 spa->spa_extreme_rewind = B_FALSE;
4473 spa->spa_load_max_txg = UINT64_MAX;
4474
4475 if (config && (rewind_error || state != SPA_LOAD_RECOVER))
4476 spa_config_set(spa, config);
ee6370a7 4477 else
4478 nvlist_free(config);
428870ff 4479
9ae529ec
CS
4480 if (state == SPA_LOAD_RECOVER) {
4481 ASSERT3P(loadinfo, ==, NULL);
ca95f70d 4482 spa_import_progress_remove(spa_guid(spa));
9ae529ec
CS
4483 return (rewind_error);
4484 } else {
4485 /* Store the rewind info as part of the initial load info */
4486 fnvlist_add_nvlist(loadinfo, ZPOOL_CONFIG_REWIND_INFO,
4487 spa->spa_load_info);
4488
4489 /* Restore the initial load info */
4490 fnvlist_free(spa->spa_load_info);
4491 spa->spa_load_info = loadinfo;
4492
ca95f70d 4493 spa_import_progress_remove(spa_guid(spa));
9ae529ec
CS
4494 return (load_error);
4495 }
34dc7c2f
BB
4496}
4497
4498/*
4499 * Pool Open/Import
4500 *
4501 * The import case is identical to an open except that the configuration is sent
4502 * down from userland, instead of grabbed from the configuration cache. For the
4503 * case of an open, the pool configuration will exist in the
4504 * POOL_STATE_UNINITIALIZED state.
4505 *
4506 * The stats information (gen/count/ustats) is used to gather vdev statistics at
4507 * the same time open the pool, without having to keep around the spa_t in some
4508 * ambiguous state.
4509 */
4510static int
428870ff
BB
4511spa_open_common(const char *pool, spa_t **spapp, void *tag, nvlist_t *nvpolicy,
4512 nvlist_t **config)
34dc7c2f
BB
4513{
4514 spa_t *spa;
572e2857 4515 spa_load_state_t state = SPA_LOAD_OPEN;
34dc7c2f 4516 int error;
34dc7c2f 4517 int locked = B_FALSE;
526af785 4518 int firstopen = B_FALSE;
34dc7c2f
BB
4519
4520 *spapp = NULL;
4521
4522 /*
4523 * As disgusting as this is, we need to support recursive calls to this
4524 * function because dsl_dir_open() is called during spa_load(), and ends
4525 * up calling spa_open() again. The real fix is to figure out how to
4526 * avoid dsl_dir_open() calling this in the first place.
4527 */
c25b8f99 4528 if (MUTEX_NOT_HELD(&spa_namespace_lock)) {
34dc7c2f
BB
4529 mutex_enter(&spa_namespace_lock);
4530 locked = B_TRUE;
4531 }
4532
4533 if ((spa = spa_lookup(pool)) == NULL) {
4534 if (locked)
4535 mutex_exit(&spa_namespace_lock);
2e528b49 4536 return (SET_ERROR(ENOENT));
34dc7c2f 4537 }
428870ff 4538
34dc7c2f 4539 if (spa->spa_state == POOL_STATE_UNINITIALIZED) {
8a393be3 4540 zpool_load_policy_t policy;
428870ff 4541
526af785
PJD
4542 firstopen = B_TRUE;
4543
8a393be3 4544 zpool_get_load_policy(nvpolicy ? nvpolicy : spa->spa_config,
428870ff 4545 &policy);
8a393be3 4546 if (policy.zlp_rewind & ZPOOL_DO_REWIND)
428870ff 4547 state = SPA_LOAD_RECOVER;
34dc7c2f 4548
fb5f0bc8 4549 spa_activate(spa, spa_mode_global);
34dc7c2f 4550
428870ff
BB
4551 if (state != SPA_LOAD_RECOVER)
4552 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
6cb8e530 4553 spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
428870ff 4554
4a0ee12a 4555 zfs_dbgmsg("spa_open_common: opening %s", pool);
8a393be3
PZ
4556 error = spa_load_best(spa, state, policy.zlp_txg,
4557 policy.zlp_rewind);
34dc7c2f
BB
4558
4559 if (error == EBADF) {
4560 /*
4561 * If vdev_validate() returns failure (indicated by
4562 * EBADF), it indicates that one of the vdevs indicates
4563 * that the pool has been exported or destroyed. If
4564 * this is the case, the config cache is out of sync and
4565 * we should remove the pool from the namespace.
4566 */
34dc7c2f
BB
4567 spa_unload(spa);
4568 spa_deactivate(spa);
a1d477c2 4569 spa_write_cachefile(spa, B_TRUE, B_TRUE);
34dc7c2f 4570 spa_remove(spa);
34dc7c2f
BB
4571 if (locked)
4572 mutex_exit(&spa_namespace_lock);
2e528b49 4573 return (SET_ERROR(ENOENT));
34dc7c2f
BB
4574 }
4575
4576 if (error) {
4577 /*
4578 * We can't open the pool, but we still have useful
4579 * information: the state of each vdev after the
4580 * attempted vdev_open(). Return this to the user.
4581 */
572e2857 4582 if (config != NULL && spa->spa_config) {
428870ff 4583 VERIFY(nvlist_dup(spa->spa_config, config,
79c76d5b 4584 KM_SLEEP) == 0);
572e2857
BB
4585 VERIFY(nvlist_add_nvlist(*config,
4586 ZPOOL_CONFIG_LOAD_INFO,
4587 spa->spa_load_info) == 0);
4588 }
34dc7c2f
BB
4589 spa_unload(spa);
4590 spa_deactivate(spa);
428870ff 4591 spa->spa_last_open_failed = error;
34dc7c2f
BB
4592 if (locked)
4593 mutex_exit(&spa_namespace_lock);
4594 *spapp = NULL;
4595 return (error);
34dc7c2f 4596 }
34dc7c2f
BB
4597 }
4598
4599 spa_open_ref(spa, tag);
4600
b128c09f 4601 if (config != NULL)
34dc7c2f 4602 *config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
34dc7c2f 4603
572e2857
BB
4604 /*
4605 * If we've recovered the pool, pass back any information we
4606 * gathered while doing the load.
4607 */
4608 if (state == SPA_LOAD_RECOVER) {
4609 VERIFY(nvlist_add_nvlist(*config, ZPOOL_CONFIG_LOAD_INFO,
4610 spa->spa_load_info) == 0);
4611 }
4612
428870ff
BB
4613 if (locked) {
4614 spa->spa_last_open_failed = 0;
4615 spa->spa_last_ubsync_txg = 0;
4616 spa->spa_load_txg = 0;
4617 mutex_exit(&spa_namespace_lock);
4618 }
4619
526af785 4620 if (firstopen)
a0bd735a 4621 zvol_create_minors(spa, spa_name(spa), B_TRUE);
526af785 4622
428870ff
BB
4623 *spapp = spa;
4624
34dc7c2f
BB
4625 return (0);
4626}
4627
428870ff
BB
4628int
4629spa_open_rewind(const char *name, spa_t **spapp, void *tag, nvlist_t *policy,
4630 nvlist_t **config)
4631{
4632 return (spa_open_common(name, spapp, tag, policy, config));
4633}
4634
34dc7c2f
BB
4635int
4636spa_open(const char *name, spa_t **spapp, void *tag)
4637{
428870ff 4638 return (spa_open_common(name, spapp, tag, NULL, NULL));
34dc7c2f
BB
4639}
4640
4641/*
4642 * Lookup the given spa_t, incrementing the inject count in the process,
4643 * preventing it from being exported or destroyed.
4644 */
4645spa_t *
4646spa_inject_addref(char *name)
4647{
4648 spa_t *spa;
4649
4650 mutex_enter(&spa_namespace_lock);
4651 if ((spa = spa_lookup(name)) == NULL) {
4652 mutex_exit(&spa_namespace_lock);
4653 return (NULL);
4654 }
4655 spa->spa_inject_ref++;
4656 mutex_exit(&spa_namespace_lock);
4657
4658 return (spa);
4659}
4660
4661void
4662spa_inject_delref(spa_t *spa)
4663{
4664 mutex_enter(&spa_namespace_lock);
4665 spa->spa_inject_ref--;
4666 mutex_exit(&spa_namespace_lock);
4667}
4668
4669/*
4670 * Add spares device information to the nvlist.
4671 */
4672static void
4673spa_add_spares(spa_t *spa, nvlist_t *config)
4674{
4675 nvlist_t **spares;
4676 uint_t i, nspares;
4677 nvlist_t *nvroot;
4678 uint64_t guid;
4679 vdev_stat_t *vs;
4680 uint_t vsc;
4681 uint64_t pool;
4682
9babb374
BB
4683 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4684
34dc7c2f
BB
4685 if (spa->spa_spares.sav_count == 0)
4686 return;
4687
4688 VERIFY(nvlist_lookup_nvlist(config,
4689 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4690 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
4691 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
4692 if (nspares != 0) {
4693 VERIFY(nvlist_add_nvlist_array(nvroot,
4694 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
4695 VERIFY(nvlist_lookup_nvlist_array(nvroot,
4696 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
4697
4698 /*
4699 * Go through and find any spares which have since been
4700 * repurposed as an active spare. If this is the case, update
4701 * their status appropriately.
4702 */
4703 for (i = 0; i < nspares; i++) {
4704 VERIFY(nvlist_lookup_uint64(spares[i],
4705 ZPOOL_CONFIG_GUID, &guid) == 0);
b128c09f
BB
4706 if (spa_spare_exists(guid, &pool, NULL) &&
4707 pool != 0ULL) {
34dc7c2f 4708 VERIFY(nvlist_lookup_uint64_array(
428870ff 4709 spares[i], ZPOOL_CONFIG_VDEV_STATS,
34dc7c2f
BB
4710 (uint64_t **)&vs, &vsc) == 0);
4711 vs->vs_state = VDEV_STATE_CANT_OPEN;
4712 vs->vs_aux = VDEV_AUX_SPARED;
4713 }
4714 }
4715 }
4716}
4717
4718/*
4719 * Add l2cache device information to the nvlist, including vdev stats.
4720 */
4721static void
4722spa_add_l2cache(spa_t *spa, nvlist_t *config)
4723{
4724 nvlist_t **l2cache;
4725 uint_t i, j, nl2cache;
4726 nvlist_t *nvroot;
4727 uint64_t guid;
4728 vdev_t *vd;
4729 vdev_stat_t *vs;
4730 uint_t vsc;
4731
9babb374
BB
4732 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4733
34dc7c2f
BB
4734 if (spa->spa_l2cache.sav_count == 0)
4735 return;
4736
34dc7c2f
BB
4737 VERIFY(nvlist_lookup_nvlist(config,
4738 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4739 VERIFY(nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
4740 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4741 if (nl2cache != 0) {
4742 VERIFY(nvlist_add_nvlist_array(nvroot,
4743 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
4744 VERIFY(nvlist_lookup_nvlist_array(nvroot,
4745 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4746
4747 /*
4748 * Update level 2 cache device stats.
4749 */
4750
4751 for (i = 0; i < nl2cache; i++) {
4752 VERIFY(nvlist_lookup_uint64(l2cache[i],
4753 ZPOOL_CONFIG_GUID, &guid) == 0);
4754
4755 vd = NULL;
4756 for (j = 0; j < spa->spa_l2cache.sav_count; j++) {
4757 if (guid ==
4758 spa->spa_l2cache.sav_vdevs[j]->vdev_guid) {
4759 vd = spa->spa_l2cache.sav_vdevs[j];
4760 break;
4761 }
4762 }
4763 ASSERT(vd != NULL);
4764
4765 VERIFY(nvlist_lookup_uint64_array(l2cache[i],
428870ff
BB
4766 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc)
4767 == 0);
34dc7c2f 4768 vdev_get_stats(vd, vs);
193a37cb
TH
4769 vdev_config_generate_stats(vd, l2cache[i]);
4770
34dc7c2f
BB
4771 }
4772 }
34dc7c2f
BB
4773}
4774
9ae529ec 4775static void
417104bd 4776spa_feature_stats_from_disk(spa_t *spa, nvlist_t *features)
9ae529ec 4777{
9ae529ec
CS
4778 zap_cursor_t zc;
4779 zap_attribute_t za;
4780
9ae529ec
CS
4781 if (spa->spa_feat_for_read_obj != 0) {
4782 for (zap_cursor_init(&zc, spa->spa_meta_objset,
4783 spa->spa_feat_for_read_obj);
4784 zap_cursor_retrieve(&zc, &za) == 0;
4785 zap_cursor_advance(&zc)) {
4786 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4787 za.za_num_integers == 1);
417104bd 4788 VERIFY0(nvlist_add_uint64(features, za.za_name,
9ae529ec
CS
4789 za.za_first_integer));
4790 }
4791 zap_cursor_fini(&zc);
4792 }
4793
4794 if (spa->spa_feat_for_write_obj != 0) {
4795 for (zap_cursor_init(&zc, spa->spa_meta_objset,
4796 spa->spa_feat_for_write_obj);
4797 zap_cursor_retrieve(&zc, &za) == 0;
4798 zap_cursor_advance(&zc)) {
4799 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4800 za.za_num_integers == 1);
417104bd 4801 VERIFY0(nvlist_add_uint64(features, za.za_name,
9ae529ec
CS
4802 za.za_first_integer));
4803 }
4804 zap_cursor_fini(&zc);
4805 }
417104bd
NB
4806}
4807
4808static void
4809spa_feature_stats_from_cache(spa_t *spa, nvlist_t *features)
4810{
4811 int i;
4812
4813 for (i = 0; i < SPA_FEATURES; i++) {
4814 zfeature_info_t feature = spa_feature_table[i];
4815 uint64_t refcount;
4816
4817 if (feature_get_refcount(spa, &feature, &refcount) != 0)
4818 continue;
4819
4820 VERIFY0(nvlist_add_uint64(features, feature.fi_guid, refcount));
4821 }
4822}
4823
4824/*
4825 * Store a list of pool features and their reference counts in the
4826 * config.
4827 *
4828 * The first time this is called on a spa, allocate a new nvlist, fetch
4829 * the pool features and reference counts from disk, then save the list
4830 * in the spa. In subsequent calls on the same spa use the saved nvlist
4831 * and refresh its values from the cached reference counts. This
4832 * ensures we don't block here on I/O on a suspended pool so 'zpool
4833 * clear' can resume the pool.
4834 */
4835static void
4836spa_add_feature_stats(spa_t *spa, nvlist_t *config)
4837{
4eb30c68 4838 nvlist_t *features;
417104bd
NB
4839
4840 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4841
4eb30c68
NB
4842 mutex_enter(&spa->spa_feat_stats_lock);
4843 features = spa->spa_feat_stats;
4844
417104bd
NB
4845 if (features != NULL) {
4846 spa_feature_stats_from_cache(spa, features);
4847 } else {
4848 VERIFY0(nvlist_alloc(&features, NV_UNIQUE_NAME, KM_SLEEP));
4849 spa->spa_feat_stats = features;
4850 spa_feature_stats_from_disk(spa, features);
4851 }
9ae529ec 4852
417104bd
NB
4853 VERIFY0(nvlist_add_nvlist(config, ZPOOL_CONFIG_FEATURE_STATS,
4854 features));
4eb30c68
NB
4855
4856 mutex_exit(&spa->spa_feat_stats_lock);
9ae529ec
CS
4857}
4858
34dc7c2f 4859int
9ae529ec
CS
4860spa_get_stats(const char *name, nvlist_t **config,
4861 char *altroot, size_t buflen)
34dc7c2f
BB
4862{
4863 int error;
4864 spa_t *spa;
4865
4866 *config = NULL;
428870ff 4867 error = spa_open_common(name, &spa, FTAG, NULL, config);
34dc7c2f 4868
9babb374
BB
4869 if (spa != NULL) {
4870 /*
4871 * This still leaves a window of inconsistency where the spares
4872 * or l2cache devices could change and the config would be
4873 * self-inconsistent.
4874 */
4875 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
34dc7c2f 4876
9babb374 4877 if (*config != NULL) {
572e2857
BB
4878 uint64_t loadtimes[2];
4879
4880 loadtimes[0] = spa->spa_loaded_ts.tv_sec;
4881 loadtimes[1] = spa->spa_loaded_ts.tv_nsec;
4882 VERIFY(nvlist_add_uint64_array(*config,
4883 ZPOOL_CONFIG_LOADED_TIME, loadtimes, 2) == 0);
4884
b128c09f 4885 VERIFY(nvlist_add_uint64(*config,
9babb374
BB
4886 ZPOOL_CONFIG_ERRCOUNT,
4887 spa_get_errlog_size(spa)) == 0);
4888
cec3a0a1 4889 if (spa_suspended(spa)) {
9babb374
BB
4890 VERIFY(nvlist_add_uint64(*config,
4891 ZPOOL_CONFIG_SUSPENDED,
4892 spa->spa_failmode) == 0);
cec3a0a1
OF
4893 VERIFY(nvlist_add_uint64(*config,
4894 ZPOOL_CONFIG_SUSPENDED_REASON,
4895 spa->spa_suspended) == 0);
4896 }
b128c09f 4897
9babb374
BB
4898 spa_add_spares(spa, *config);
4899 spa_add_l2cache(spa, *config);
9ae529ec 4900 spa_add_feature_stats(spa, *config);
9babb374 4901 }
34dc7c2f
BB
4902 }
4903
4904 /*
4905 * We want to get the alternate root even for faulted pools, so we cheat
4906 * and call spa_lookup() directly.
4907 */
4908 if (altroot) {
4909 if (spa == NULL) {
4910 mutex_enter(&spa_namespace_lock);
4911 spa = spa_lookup(name);
4912 if (spa)
4913 spa_altroot(spa, altroot, buflen);
4914 else
4915 altroot[0] = '\0';
4916 spa = NULL;
4917 mutex_exit(&spa_namespace_lock);
4918 } else {
4919 spa_altroot(spa, altroot, buflen);
4920 }
4921 }
4922
9babb374
BB
4923 if (spa != NULL) {
4924 spa_config_exit(spa, SCL_CONFIG, FTAG);
34dc7c2f 4925 spa_close(spa, FTAG);
9babb374 4926 }
34dc7c2f
BB
4927
4928 return (error);
4929}
4930
4931/*
4932 * Validate that the auxiliary device array is well formed. We must have an
4933 * array of nvlists, each which describes a valid leaf vdev. If this is an
4934 * import (mode is VDEV_ALLOC_SPARE), then we allow corrupted spares to be
4935 * specified, as long as they are well-formed.
4936 */
4937static int
4938spa_validate_aux_devs(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode,
4939 spa_aux_vdev_t *sav, const char *config, uint64_t version,
4940 vdev_labeltype_t label)
4941{
4942 nvlist_t **dev;
4943 uint_t i, ndev;
4944 vdev_t *vd;
4945 int error;
4946
b128c09f
BB
4947 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4948
34dc7c2f
BB
4949 /*
4950 * It's acceptable to have no devs specified.
4951 */
4952 if (nvlist_lookup_nvlist_array(nvroot, config, &dev, &ndev) != 0)
4953 return (0);
4954
4955 if (ndev == 0)
2e528b49 4956 return (SET_ERROR(EINVAL));
34dc7c2f
BB
4957
4958 /*
4959 * Make sure the pool is formatted with a version that supports this
4960 * device type.
4961 */
4962 if (spa_version(spa) < version)
2e528b49 4963 return (SET_ERROR(ENOTSUP));
34dc7c2f
BB
4964
4965 /*
4966 * Set the pending device list so we correctly handle device in-use
4967 * checking.
4968 */
4969 sav->sav_pending = dev;
4970 sav->sav_npending = ndev;
4971
4972 for (i = 0; i < ndev; i++) {
4973 if ((error = spa_config_parse(spa, &vd, dev[i], NULL, 0,
4974 mode)) != 0)
4975 goto out;
4976
4977 if (!vd->vdev_ops->vdev_op_leaf) {
4978 vdev_free(vd);
2e528b49 4979 error = SET_ERROR(EINVAL);
34dc7c2f
BB
4980 goto out;
4981 }
4982
34dc7c2f
BB
4983 vd->vdev_top = vd;
4984
4985 if ((error = vdev_open(vd)) == 0 &&
4986 (error = vdev_label_init(vd, crtxg, label)) == 0) {
4987 VERIFY(nvlist_add_uint64(dev[i], ZPOOL_CONFIG_GUID,
4988 vd->vdev_guid) == 0);
4989 }
4990
4991 vdev_free(vd);
4992
4993 if (error &&
4994 (mode != VDEV_ALLOC_SPARE && mode != VDEV_ALLOC_L2CACHE))
4995 goto out;
4996 else
4997 error = 0;
4998 }
4999
5000out:
5001 sav->sav_pending = NULL;
5002 sav->sav_npending = 0;
5003 return (error);
5004}
5005
5006static int
5007spa_validate_aux(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode)
5008{
5009 int error;
5010
b128c09f
BB
5011 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
5012
34dc7c2f
BB
5013 if ((error = spa_validate_aux_devs(spa, nvroot, crtxg, mode,
5014 &spa->spa_spares, ZPOOL_CONFIG_SPARES, SPA_VERSION_SPARES,
5015 VDEV_LABEL_SPARE)) != 0) {
5016 return (error);
5017 }
5018
5019 return (spa_validate_aux_devs(spa, nvroot, crtxg, mode,
5020 &spa->spa_l2cache, ZPOOL_CONFIG_L2CACHE, SPA_VERSION_L2CACHE,
5021 VDEV_LABEL_L2CACHE));
5022}
5023
5024static void
5025spa_set_aux_vdevs(spa_aux_vdev_t *sav, nvlist_t **devs, int ndevs,
5026 const char *config)
5027{
5028 int i;
5029
5030 if (sav->sav_config != NULL) {
5031 nvlist_t **olddevs;
5032 uint_t oldndevs;
5033 nvlist_t **newdevs;
5034
5035 /*
4e33ba4c 5036 * Generate new dev list by concatenating with the
34dc7c2f
BB
5037 * current dev list.
5038 */
5039 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config, config,
5040 &olddevs, &oldndevs) == 0);
5041
5042 newdevs = kmem_alloc(sizeof (void *) *
79c76d5b 5043 (ndevs + oldndevs), KM_SLEEP);
34dc7c2f
BB
5044 for (i = 0; i < oldndevs; i++)
5045 VERIFY(nvlist_dup(olddevs[i], &newdevs[i],
79c76d5b 5046 KM_SLEEP) == 0);
34dc7c2f
BB
5047 for (i = 0; i < ndevs; i++)
5048 VERIFY(nvlist_dup(devs[i], &newdevs[i + oldndevs],
79c76d5b 5049 KM_SLEEP) == 0);
34dc7c2f
BB
5050
5051 VERIFY(nvlist_remove(sav->sav_config, config,
5052 DATA_TYPE_NVLIST_ARRAY) == 0);
5053
5054 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
5055 config, newdevs, ndevs + oldndevs) == 0);
5056 for (i = 0; i < oldndevs + ndevs; i++)
5057 nvlist_free(newdevs[i]);
5058 kmem_free(newdevs, (oldndevs + ndevs) * sizeof (void *));
5059 } else {
5060 /*
5061 * Generate a new dev list.
5062 */
5063 VERIFY(nvlist_alloc(&sav->sav_config, NV_UNIQUE_NAME,
79c76d5b 5064 KM_SLEEP) == 0);
34dc7c2f
BB
5065 VERIFY(nvlist_add_nvlist_array(sav->sav_config, config,
5066 devs, ndevs) == 0);
5067 }
5068}
5069
5070/*
5071 * Stop and drop level 2 ARC devices
5072 */
5073void
5074spa_l2cache_drop(spa_t *spa)
5075{
5076 vdev_t *vd;
5077 int i;
5078 spa_aux_vdev_t *sav = &spa->spa_l2cache;
5079
5080 for (i = 0; i < sav->sav_count; i++) {
5081 uint64_t pool;
5082
5083 vd = sav->sav_vdevs[i];
5084 ASSERT(vd != NULL);
5085
fb5f0bc8
BB
5086 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
5087 pool != 0ULL && l2arc_vdev_present(vd))
34dc7c2f 5088 l2arc_remove_vdev(vd);
34dc7c2f
BB
5089 }
5090}
5091
b5256303
TC
5092/*
5093 * Verify encryption parameters for spa creation. If we are encrypting, we must
5094 * have the encryption feature flag enabled.
5095 */
5096static int
5097spa_create_check_encryption_params(dsl_crypto_params_t *dcp,
5098 boolean_t has_encryption)
5099{
5100 if (dcp->cp_crypt != ZIO_CRYPT_OFF &&
5101 dcp->cp_crypt != ZIO_CRYPT_INHERIT &&
5102 !has_encryption)
5103 return (SET_ERROR(ENOTSUP));
5104
1fff937a 5105 return (dmu_objset_create_crypt_check(NULL, dcp, NULL));
b5256303
TC
5106}
5107
34dc7c2f
BB
5108/*
5109 * Pool Creation
5110 */
5111int
5112spa_create(const char *pool, nvlist_t *nvroot, nvlist_t *props,
b5256303 5113 nvlist_t *zplprops, dsl_crypto_params_t *dcp)
34dc7c2f
BB
5114{
5115 spa_t *spa;
5116 char *altroot = NULL;
5117 vdev_t *rvd;
5118 dsl_pool_t *dp;
5119 dmu_tx_t *tx;
9babb374 5120 int error = 0;
34dc7c2f
BB
5121 uint64_t txg = TXG_INITIAL;
5122 nvlist_t **spares, **l2cache;
5123 uint_t nspares, nl2cache;
52ce99dd 5124 uint64_t version, obj;
9ae529ec 5125 boolean_t has_features;
b5256303
TC
5126 boolean_t has_encryption;
5127 spa_feature_t feat;
5128 char *feat_name;
83e9986f
RY
5129 char *poolname;
5130 nvlist_t *nvl;
5131
cc99f275
DB
5132 if (props == NULL ||
5133 nvlist_lookup_string(props, "tname", &poolname) != 0)
83e9986f 5134 poolname = (char *)pool;
34dc7c2f
BB
5135
5136 /*
5137 * If this pool already exists, return failure.
5138 */
5139 mutex_enter(&spa_namespace_lock);
83e9986f 5140 if (spa_lookup(poolname) != NULL) {
34dc7c2f 5141 mutex_exit(&spa_namespace_lock);
2e528b49 5142 return (SET_ERROR(EEXIST));
34dc7c2f
BB
5143 }
5144
5145 /*
5146 * Allocate a new spa_t structure.
5147 */
83e9986f
RY
5148 nvl = fnvlist_alloc();
5149 fnvlist_add_string(nvl, ZPOOL_CONFIG_POOL_NAME, pool);
34dc7c2f
BB
5150 (void) nvlist_lookup_string(props,
5151 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
83e9986f
RY
5152 spa = spa_add(poolname, nvl, altroot);
5153 fnvlist_free(nvl);
fb5f0bc8 5154 spa_activate(spa, spa_mode_global);
34dc7c2f 5155
34dc7c2f 5156 if (props && (error = spa_prop_validate(spa, props))) {
34dc7c2f
BB
5157 spa_deactivate(spa);
5158 spa_remove(spa);
b128c09f 5159 mutex_exit(&spa_namespace_lock);
34dc7c2f
BB
5160 return (error);
5161 }
5162
83e9986f
RY
5163 /*
5164 * Temporary pool names should never be written to disk.
5165 */
5166 if (poolname != pool)
5167 spa->spa_import_flags |= ZFS_IMPORT_TEMP_NAME;
5168
9ae529ec 5169 has_features = B_FALSE;
b5256303 5170 has_encryption = B_FALSE;
1c27024e 5171 for (nvpair_t *elem = nvlist_next_nvpair(props, NULL);
9ae529ec 5172 elem != NULL; elem = nvlist_next_nvpair(props, elem)) {
b5256303 5173 if (zpool_prop_feature(nvpair_name(elem))) {
9ae529ec 5174 has_features = B_TRUE;
b5256303
TC
5175
5176 feat_name = strchr(nvpair_name(elem), '@') + 1;
5177 VERIFY0(zfeature_lookup_name(feat_name, &feat));
5178 if (feat == SPA_FEATURE_ENCRYPTION)
5179 has_encryption = B_TRUE;
5180 }
5181 }
5182
5183 /* verify encryption params, if they were provided */
5184 if (dcp != NULL) {
5185 error = spa_create_check_encryption_params(dcp, has_encryption);
5186 if (error != 0) {
5187 spa_deactivate(spa);
5188 spa_remove(spa);
5189 mutex_exit(&spa_namespace_lock);
5190 return (error);
5191 }
9ae529ec
CS
5192 }
5193
5194 if (has_features || nvlist_lookup_uint64(props,
5195 zpool_prop_to_name(ZPOOL_PROP_VERSION), &version) != 0) {
34dc7c2f 5196 version = SPA_VERSION;
9ae529ec
CS
5197 }
5198 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
428870ff
BB
5199
5200 spa->spa_first_txg = txg;
5201 spa->spa_uberblock.ub_txg = txg - 1;
34dc7c2f
BB
5202 spa->spa_uberblock.ub_version = version;
5203 spa->spa_ubsync = spa->spa_uberblock;
3dfb57a3 5204 spa->spa_load_state = SPA_LOAD_CREATE;
a1d477c2
MA
5205 spa->spa_removing_phys.sr_state = DSS_NONE;
5206 spa->spa_removing_phys.sr_removing_vdev = -1;
5207 spa->spa_removing_phys.sr_prev_indirect_vdev = -1;
944a3724 5208 spa->spa_indirect_vdevs_loaded = B_TRUE;
34dc7c2f 5209
9babb374
BB
5210 /*
5211 * Create "The Godfather" zio to hold all async IOs
5212 */
e022864d
MA
5213 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
5214 KM_SLEEP);
1c27024e 5215 for (int i = 0; i < max_ncpus; i++) {
e022864d
MA
5216 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
5217 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
5218 ZIO_FLAG_GODFATHER);
5219 }
9babb374 5220
34dc7c2f
BB
5221 /*
5222 * Create the root vdev.
5223 */
b128c09f 5224 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f
BB
5225
5226 error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, VDEV_ALLOC_ADD);
5227
5228 ASSERT(error != 0 || rvd != NULL);
5229 ASSERT(error != 0 || spa->spa_root_vdev == rvd);
5230
5231 if (error == 0 && !zfs_allocatable_devs(nvroot))
2e528b49 5232 error = SET_ERROR(EINVAL);
34dc7c2f
BB
5233
5234 if (error == 0 &&
5235 (error = vdev_create(rvd, txg, B_FALSE)) == 0 &&
5236 (error = spa_validate_aux(spa, nvroot, txg,
5237 VDEV_ALLOC_ADD)) == 0) {
cc99f275
DB
5238 /*
5239 * instantiate the metaslab groups (this will dirty the vdevs)
5240 * we can no longer error exit past this point
5241 */
5242 for (int c = 0; error == 0 && c < rvd->vdev_children; c++) {
5243 vdev_t *vd = rvd->vdev_child[c];
5244
5245 vdev_metaslab_set_size(vd);
5246 vdev_expand(vd, txg);
9babb374 5247 }
34dc7c2f
BB
5248 }
5249
b128c09f 5250 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
5251
5252 if (error != 0) {
5253 spa_unload(spa);
5254 spa_deactivate(spa);
5255 spa_remove(spa);
5256 mutex_exit(&spa_namespace_lock);
5257 return (error);
5258 }
5259
5260 /*
5261 * Get the list of spares, if specified.
5262 */
5263 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
5264 &spares, &nspares) == 0) {
5265 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config, NV_UNIQUE_NAME,
79c76d5b 5266 KM_SLEEP) == 0);
34dc7c2f
BB
5267 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
5268 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
b128c09f 5269 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 5270 spa_load_spares(spa);
b128c09f 5271 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
5272 spa->spa_spares.sav_sync = B_TRUE;
5273 }
5274
5275 /*
5276 * Get the list of level 2 cache devices, if specified.
5277 */
5278 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
5279 &l2cache, &nl2cache) == 0) {
5280 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
79c76d5b 5281 NV_UNIQUE_NAME, KM_SLEEP) == 0);
34dc7c2f
BB
5282 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
5283 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
b128c09f 5284 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 5285 spa_load_l2cache(spa);
b128c09f 5286 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
5287 spa->spa_l2cache.sav_sync = B_TRUE;
5288 }
5289
9ae529ec 5290 spa->spa_is_initializing = B_TRUE;
b5256303 5291 spa->spa_dsl_pool = dp = dsl_pool_create(spa, zplprops, dcp, txg);
9ae529ec 5292 spa->spa_is_initializing = B_FALSE;
34dc7c2f 5293
428870ff
BB
5294 /*
5295 * Create DDTs (dedup tables).
5296 */
5297 ddt_create(spa);
5298
5299 spa_update_dspace(spa);
5300
34dc7c2f
BB
5301 tx = dmu_tx_create_assigned(dp, txg);
5302
d5e024cb
BB
5303 /*
5304 * Create the pool's history object.
5305 */
5306 if (version >= SPA_VERSION_ZPOOL_HISTORY && !spa->spa_history)
5307 spa_history_create_obj(spa, tx);
5308
5309 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_CREATE);
5310 spa_history_log_version(spa, "create", tx);
5311
34dc7c2f
BB
5312 /*
5313 * Create the pool config object.
5314 */
5315 spa->spa_config_object = dmu_object_alloc(spa->spa_meta_objset,
b128c09f 5316 DMU_OT_PACKED_NVLIST, SPA_CONFIG_BLOCKSIZE,
34dc7c2f
BB
5317 DMU_OT_PACKED_NVLIST_SIZE, sizeof (uint64_t), tx);
5318
5319 if (zap_add(spa->spa_meta_objset,
5320 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CONFIG,
5321 sizeof (uint64_t), 1, &spa->spa_config_object, tx) != 0) {
5322 cmn_err(CE_PANIC, "failed to add pool config");
5323 }
5324
428870ff
BB
5325 if (zap_add(spa->spa_meta_objset,
5326 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CREATION_VERSION,
5327 sizeof (uint64_t), 1, &version, tx) != 0) {
5328 cmn_err(CE_PANIC, "failed to add pool version");
5329 }
5330
34dc7c2f
BB
5331 /* Newly created pools with the right version are always deflated. */
5332 if (version >= SPA_VERSION_RAIDZ_DEFLATE) {
5333 spa->spa_deflate = TRUE;
5334 if (zap_add(spa->spa_meta_objset,
5335 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
5336 sizeof (uint64_t), 1, &spa->spa_deflate, tx) != 0) {
5337 cmn_err(CE_PANIC, "failed to add deflate");
5338 }
5339 }
5340
5341 /*
428870ff 5342 * Create the deferred-free bpobj. Turn off compression
34dc7c2f
BB
5343 * because sync-to-convergence takes longer if the blocksize
5344 * keeps changing.
5345 */
428870ff
BB
5346 obj = bpobj_alloc(spa->spa_meta_objset, 1 << 14, tx);
5347 dmu_object_set_compress(spa->spa_meta_objset, obj,
34dc7c2f 5348 ZIO_COMPRESS_OFF, tx);
34dc7c2f 5349 if (zap_add(spa->spa_meta_objset,
428870ff
BB
5350 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SYNC_BPOBJ,
5351 sizeof (uint64_t), 1, &obj, tx) != 0) {
5352 cmn_err(CE_PANIC, "failed to add bpobj");
34dc7c2f 5353 }
428870ff
BB
5354 VERIFY3U(0, ==, bpobj_open(&spa->spa_deferred_bpobj,
5355 spa->spa_meta_objset, obj));
34dc7c2f 5356
3c67d83a
TH
5357 /*
5358 * Generate some random noise for salted checksums to operate on.
5359 */
5360 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
5361 sizeof (spa->spa_cksum_salt.zcs_bytes));
5362
34dc7c2f
BB
5363 /*
5364 * Set pool properties.
5365 */
5366 spa->spa_bootfs = zpool_prop_default_numeric(ZPOOL_PROP_BOOTFS);
5367 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
5368 spa->spa_failmode = zpool_prop_default_numeric(ZPOOL_PROP_FAILUREMODE);
9babb374 5369 spa->spa_autoexpand = zpool_prop_default_numeric(ZPOOL_PROP_AUTOEXPAND);
379ca9cf 5370 spa->spa_multihost = zpool_prop_default_numeric(ZPOOL_PROP_MULTIHOST);
1b939560 5371 spa->spa_autotrim = zpool_prop_default_numeric(ZPOOL_PROP_AUTOTRIM);
428870ff 5372
d164b209
BB
5373 if (props != NULL) {
5374 spa_configfile_set(spa, props, B_FALSE);
13fe0198 5375 spa_sync_props(props, tx);
d164b209 5376 }
34dc7c2f
BB
5377
5378 dmu_tx_commit(tx);
5379
5380 spa->spa_sync_on = B_TRUE;
b5256303 5381 txg_sync_start(dp);
379ca9cf 5382 mmp_thread_start(spa);
b5256303 5383 txg_wait_synced(dp, txg);
34dc7c2f 5384
9d5b5245
SD
5385 spa_spawn_aux_threads(spa);
5386
a1d477c2 5387 spa_write_cachefile(spa, B_FALSE, B_TRUE);
34dc7c2f 5388
0c66c32d
JG
5389 /*
5390 * Don't count references from objsets that are already closed
5391 * and are making their way through the eviction process.
5392 */
5393 spa_evicting_os_wait(spa);
424fd7c3 5394 spa->spa_minref = zfs_refcount_count(&spa->spa_refcount);
3dfb57a3 5395 spa->spa_load_state = SPA_LOAD_NONE;
b128c09f 5396
d164b209
BB
5397 mutex_exit(&spa_namespace_lock);
5398
34dc7c2f
BB
5399 return (0);
5400}
5401
9babb374
BB
5402/*
5403 * Import a non-root pool into the system.
5404 */
5405int
13fe0198 5406spa_import(char *pool, nvlist_t *config, nvlist_t *props, uint64_t flags)
34dc7c2f
BB
5407{
5408 spa_t *spa;
5409 char *altroot = NULL;
428870ff 5410 spa_load_state_t state = SPA_LOAD_IMPORT;
8a393be3 5411 zpool_load_policy_t policy;
572e2857
BB
5412 uint64_t mode = spa_mode_global;
5413 uint64_t readonly = B_FALSE;
9babb374 5414 int error;
34dc7c2f
BB
5415 nvlist_t *nvroot;
5416 nvlist_t **spares, **l2cache;
5417 uint_t nspares, nl2cache;
34dc7c2f
BB
5418
5419 /*
5420 * If a pool with this name exists, return failure.
5421 */
5422 mutex_enter(&spa_namespace_lock);
428870ff 5423 if (spa_lookup(pool) != NULL) {
9babb374 5424 mutex_exit(&spa_namespace_lock);
2e528b49 5425 return (SET_ERROR(EEXIST));
34dc7c2f
BB
5426 }
5427
5428 /*
5429 * Create and initialize the spa structure.
5430 */
5431 (void) nvlist_lookup_string(props,
5432 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
572e2857
BB
5433 (void) nvlist_lookup_uint64(props,
5434 zpool_prop_to_name(ZPOOL_PROP_READONLY), &readonly);
5435 if (readonly)
5436 mode = FREAD;
428870ff 5437 spa = spa_add(pool, config, altroot);
572e2857
BB
5438 spa->spa_import_flags = flags;
5439
5440 /*
5441 * Verbatim import - Take a pool and insert it into the namespace
5442 * as if it had been loaded at boot.
5443 */
5444 if (spa->spa_import_flags & ZFS_IMPORT_VERBATIM) {
5445 if (props != NULL)
5446 spa_configfile_set(spa, props, B_FALSE);
5447
a1d477c2 5448 spa_write_cachefile(spa, B_FALSE, B_TRUE);
12fa0466 5449 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
4a0ee12a 5450 zfs_dbgmsg("spa_import: verbatim import of %s", pool);
572e2857 5451 mutex_exit(&spa_namespace_lock);
572e2857
BB
5452 return (0);
5453 }
5454
5455 spa_activate(spa, mode);
34dc7c2f 5456
9babb374
BB
5457 /*
5458 * Don't start async tasks until we know everything is healthy.
5459 */
5460 spa_async_suspend(spa);
b128c09f 5461
8a393be3
PZ
5462 zpool_get_load_policy(config, &policy);
5463 if (policy.zlp_rewind & ZPOOL_DO_REWIND)
572e2857
BB
5464 state = SPA_LOAD_RECOVER;
5465
6cb8e530 5466 spa->spa_config_source = SPA_CONFIG_SRC_TRYIMPORT;
572e2857 5467
6cb8e530
PZ
5468 if (state != SPA_LOAD_RECOVER) {
5469 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
5470 zfs_dbgmsg("spa_import: importing %s", pool);
5471 } else {
5472 zfs_dbgmsg("spa_import: importing %s, max_txg=%lld "
8a393be3 5473 "(RECOVERY MODE)", pool, (longlong_t)policy.zlp_txg);
6cb8e530 5474 }
8a393be3 5475 error = spa_load_best(spa, state, policy.zlp_txg, policy.zlp_rewind);
428870ff
BB
5476
5477 /*
572e2857
BB
5478 * Propagate anything learned while loading the pool and pass it
5479 * back to caller (i.e. rewind info, missing devices, etc).
428870ff 5480 */
572e2857
BB
5481 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
5482 spa->spa_load_info) == 0);
34dc7c2f 5483
b128c09f 5484 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 5485 /*
9babb374
BB
5486 * Toss any existing sparelist, as it doesn't have any validity
5487 * anymore, and conflicts with spa_has_spare().
34dc7c2f 5488 */
9babb374 5489 if (spa->spa_spares.sav_config) {
34dc7c2f
BB
5490 nvlist_free(spa->spa_spares.sav_config);
5491 spa->spa_spares.sav_config = NULL;
5492 spa_load_spares(spa);
5493 }
9babb374 5494 if (spa->spa_l2cache.sav_config) {
34dc7c2f
BB
5495 nvlist_free(spa->spa_l2cache.sav_config);
5496 spa->spa_l2cache.sav_config = NULL;
5497 spa_load_l2cache(spa);
5498 }
5499
5500 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5501 &nvroot) == 0);
b128c09f 5502 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f 5503
d164b209
BB
5504 if (props != NULL)
5505 spa_configfile_set(spa, props, B_FALSE);
5506
fb5f0bc8
BB
5507 if (error != 0 || (props && spa_writeable(spa) &&
5508 (error = spa_prop_set(spa, props)))) {
9babb374
BB
5509 spa_unload(spa);
5510 spa_deactivate(spa);
5511 spa_remove(spa);
34dc7c2f
BB
5512 mutex_exit(&spa_namespace_lock);
5513 return (error);
5514 }
5515
572e2857
BB
5516 spa_async_resume(spa);
5517
34dc7c2f
BB
5518 /*
5519 * Override any spares and level 2 cache devices as specified by
5520 * the user, as these may have correct device names/devids, etc.
5521 */
5522 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
5523 &spares, &nspares) == 0) {
5524 if (spa->spa_spares.sav_config)
5525 VERIFY(nvlist_remove(spa->spa_spares.sav_config,
5526 ZPOOL_CONFIG_SPARES, DATA_TYPE_NVLIST_ARRAY) == 0);
5527 else
5528 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config,
79c76d5b 5529 NV_UNIQUE_NAME, KM_SLEEP) == 0);
34dc7c2f
BB
5530 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
5531 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
b128c09f 5532 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 5533 spa_load_spares(spa);
b128c09f 5534 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
5535 spa->spa_spares.sav_sync = B_TRUE;
5536 }
5537 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
5538 &l2cache, &nl2cache) == 0) {
5539 if (spa->spa_l2cache.sav_config)
5540 VERIFY(nvlist_remove(spa->spa_l2cache.sav_config,
5541 ZPOOL_CONFIG_L2CACHE, DATA_TYPE_NVLIST_ARRAY) == 0);
5542 else
5543 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
79c76d5b 5544 NV_UNIQUE_NAME, KM_SLEEP) == 0);
34dc7c2f
BB
5545 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
5546 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
b128c09f 5547 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 5548 spa_load_l2cache(spa);
b128c09f 5549 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
5550 spa->spa_l2cache.sav_sync = B_TRUE;
5551 }
5552
428870ff
BB
5553 /*
5554 * Check for any removed devices.
5555 */
5556 if (spa->spa_autoreplace) {
5557 spa_aux_check_removed(&spa->spa_spares);
5558 spa_aux_check_removed(&spa->spa_l2cache);
5559 }
5560
fb5f0bc8 5561 if (spa_writeable(spa)) {
b128c09f
BB
5562 /*
5563 * Update the config cache to include the newly-imported pool.
5564 */
45d1cae3 5565 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
b128c09f 5566 }
34dc7c2f 5567
34dc7c2f 5568 /*
9babb374
BB
5569 * It's possible that the pool was expanded while it was exported.
5570 * We kick off an async task to handle this for us.
34dc7c2f 5571 */
9babb374 5572 spa_async_request(spa, SPA_ASYNC_AUTOEXPAND);
b128c09f 5573
d5e024cb 5574 spa_history_log_version(spa, "import", NULL);
fb390aaf 5575
12fa0466 5576 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
fb390aaf 5577
a0bd735a 5578 zvol_create_minors(spa, pool, B_TRUE);
526af785 5579
fb390aaf
HR
5580 mutex_exit(&spa_namespace_lock);
5581
b128c09f
BB
5582 return (0);
5583}
5584
34dc7c2f
BB
5585nvlist_t *
5586spa_tryimport(nvlist_t *tryconfig)
5587{
5588 nvlist_t *config = NULL;
6cb8e530 5589 char *poolname, *cachefile;
34dc7c2f
BB
5590 spa_t *spa;
5591 uint64_t state;
d164b209 5592 int error;
8a393be3 5593 zpool_load_policy_t policy;
34dc7c2f
BB
5594
5595 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_POOL_NAME, &poolname))
5596 return (NULL);
5597
5598 if (nvlist_lookup_uint64(tryconfig, ZPOOL_CONFIG_POOL_STATE, &state))
5599 return (NULL);
5600
5601 /*
5602 * Create and initialize the spa structure.
5603 */
5604 mutex_enter(&spa_namespace_lock);
428870ff 5605 spa = spa_add(TRYIMPORT_NAME, tryconfig, NULL);
fb5f0bc8 5606 spa_activate(spa, FREAD);
34dc7c2f
BB
5607
5608 /*
8a393be3 5609 * Rewind pool if a max txg was provided.
34dc7c2f 5610 */
8a393be3
PZ
5611 zpool_get_load_policy(spa->spa_config, &policy);
5612 if (policy.zlp_txg != UINT64_MAX) {
5613 spa->spa_load_max_txg = policy.zlp_txg;
6cb8e530
PZ
5614 spa->spa_extreme_rewind = B_TRUE;
5615 zfs_dbgmsg("spa_tryimport: importing %s, max_txg=%lld",
8a393be3 5616 poolname, (longlong_t)policy.zlp_txg);
6cb8e530
PZ
5617 } else {
5618 zfs_dbgmsg("spa_tryimport: importing %s", poolname);
5619 }
5620
5621 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_CACHEFILE, &cachefile)
5622 == 0) {
5623 zfs_dbgmsg("spa_tryimport: using cachefile '%s'", cachefile);
5624 spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
5625 } else {
5626 spa->spa_config_source = SPA_CONFIG_SRC_SCAN;
5627 }
5628
5629 error = spa_load(spa, SPA_LOAD_TRYIMPORT, SPA_IMPORT_EXISTING);
34dc7c2f
BB
5630
5631 /*
5632 * If 'tryconfig' was at least parsable, return the current config.
5633 */
5634 if (spa->spa_root_vdev != NULL) {
34dc7c2f 5635 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
34dc7c2f
BB
5636 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME,
5637 poolname) == 0);
5638 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
5639 state) == 0);
5640 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
5641 spa->spa_uberblock.ub_timestamp) == 0);
9ae529ec
CS
5642 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
5643 spa->spa_load_info) == 0);
ffe9d382
BB
5644 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_ERRATA,
5645 spa->spa_errata) == 0);
34dc7c2f
BB
5646
5647 /*
5648 * If the bootfs property exists on this pool then we
5649 * copy it out so that external consumers can tell which
5650 * pools are bootable.
5651 */
d164b209 5652 if ((!error || error == EEXIST) && spa->spa_bootfs) {
79c76d5b 5653 char *tmpname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
34dc7c2f
BB
5654
5655 /*
5656 * We have to play games with the name since the
5657 * pool was opened as TRYIMPORT_NAME.
5658 */
b128c09f 5659 if (dsl_dsobj_to_dsname(spa_name(spa),
34dc7c2f
BB
5660 spa->spa_bootfs, tmpname) == 0) {
5661 char *cp;
d1d7e268
MK
5662 char *dsname;
5663
79c76d5b 5664 dsname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
34dc7c2f
BB
5665
5666 cp = strchr(tmpname, '/');
5667 if (cp == NULL) {
5668 (void) strlcpy(dsname, tmpname,
5669 MAXPATHLEN);
5670 } else {
5671 (void) snprintf(dsname, MAXPATHLEN,
5672 "%s/%s", poolname, ++cp);
5673 }
5674 VERIFY(nvlist_add_string(config,
5675 ZPOOL_CONFIG_BOOTFS, dsname) == 0);
5676 kmem_free(dsname, MAXPATHLEN);
5677 }
5678 kmem_free(tmpname, MAXPATHLEN);
5679 }
5680
5681 /*
5682 * Add the list of hot spares and level 2 cache devices.
5683 */
9babb374 5684 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
34dc7c2f
BB
5685 spa_add_spares(spa, config);
5686 spa_add_l2cache(spa, config);
9babb374 5687 spa_config_exit(spa, SCL_CONFIG, FTAG);
34dc7c2f
BB
5688 }
5689
5690 spa_unload(spa);
5691 spa_deactivate(spa);
5692 spa_remove(spa);
5693 mutex_exit(&spa_namespace_lock);
5694
5695 return (config);
5696}
5697
5698/*
5699 * Pool export/destroy
5700 *
5701 * The act of destroying or exporting a pool is very simple. We make sure there
5702 * is no more pending I/O and any references to the pool are gone. Then, we
5703 * update the pool state and sync all the labels to disk, removing the
fb5f0bc8
BB
5704 * configuration from the cache afterwards. If the 'hardforce' flag is set, then
5705 * we don't sync the labels or remove the configuration cache.
34dc7c2f
BB
5706 */
5707static int
b128c09f 5708spa_export_common(char *pool, int new_state, nvlist_t **oldconfig,
fb5f0bc8 5709 boolean_t force, boolean_t hardforce)
34dc7c2f
BB
5710{
5711 spa_t *spa;
5712
5713 if (oldconfig)
5714 *oldconfig = NULL;
5715
fb5f0bc8 5716 if (!(spa_mode_global & FWRITE))
2e528b49 5717 return (SET_ERROR(EROFS));
34dc7c2f
BB
5718
5719 mutex_enter(&spa_namespace_lock);
5720 if ((spa = spa_lookup(pool)) == NULL) {
5721 mutex_exit(&spa_namespace_lock);
2e528b49 5722 return (SET_ERROR(ENOENT));
34dc7c2f
BB
5723 }
5724
5725 /*
5726 * Put a hold on the pool, drop the namespace lock, stop async tasks,
5727 * reacquire the namespace lock, and see if we can export.
5728 */
5729 spa_open_ref(spa, FTAG);
5730 mutex_exit(&spa_namespace_lock);
5731 spa_async_suspend(spa);
a0bd735a
BP
5732 if (spa->spa_zvol_taskq) {
5733 zvol_remove_minors(spa, spa_name(spa), B_TRUE);
5734 taskq_wait(spa->spa_zvol_taskq);
5735 }
34dc7c2f
BB
5736 mutex_enter(&spa_namespace_lock);
5737 spa_close(spa, FTAG);
5738
d14cfd83
IH
5739 if (spa->spa_state == POOL_STATE_UNINITIALIZED)
5740 goto export_spa;
34dc7c2f 5741 /*
d14cfd83
IH
5742 * The pool will be in core if it's openable, in which case we can
5743 * modify its state. Objsets may be open only because they're dirty,
5744 * so we have to force it to sync before checking spa_refcnt.
34dc7c2f 5745 */
0c66c32d 5746 if (spa->spa_sync_on) {
34dc7c2f 5747 txg_wait_synced(spa->spa_dsl_pool, 0);
0c66c32d
JG
5748 spa_evicting_os_wait(spa);
5749 }
34dc7c2f 5750
d14cfd83
IH
5751 /*
5752 * A pool cannot be exported or destroyed if there are active
5753 * references. If we are resetting a pool, allow references by
5754 * fault injection handlers.
5755 */
5756 if (!spa_refcount_zero(spa) ||
5757 (spa->spa_inject_ref != 0 &&
5758 new_state != POOL_STATE_UNINITIALIZED)) {
5759 spa_async_resume(spa);
5760 mutex_exit(&spa_namespace_lock);
5761 return (SET_ERROR(EBUSY));
5762 }
34dc7c2f 5763
d14cfd83 5764 if (spa->spa_sync_on) {
b128c09f
BB
5765 /*
5766 * A pool cannot be exported if it has an active shared spare.
5767 * This is to prevent other pools stealing the active spare
5768 * from an exported pool. At user's own will, such pool can
5769 * be forcedly exported.
5770 */
5771 if (!force && new_state == POOL_STATE_EXPORTED &&
5772 spa_has_active_shared_spare(spa)) {
5773 spa_async_resume(spa);
5774 mutex_exit(&spa_namespace_lock);
2e528b49 5775 return (SET_ERROR(EXDEV));
b128c09f 5776 }
34dc7c2f 5777
619f0976
GW
5778 /*
5779 * We're about to export or destroy this pool. Make sure
1b939560
BB
5780 * we stop all initialization and trim activity here before
5781 * we set the spa_final_txg. This will ensure that all
619f0976
GW
5782 * dirty data resulting from the initialization is
5783 * committed to disk before we unload the pool.
5784 */
5785 if (spa->spa_root_vdev != NULL) {
1b939560
BB
5786 vdev_t *rvd = spa->spa_root_vdev;
5787 vdev_initialize_stop_all(rvd, VDEV_INITIALIZE_ACTIVE);
5788 vdev_trim_stop_all(rvd, VDEV_TRIM_ACTIVE);
5789 vdev_autotrim_stop_all(spa);
619f0976
GW
5790 }
5791
34dc7c2f
BB
5792 /*
5793 * We want this to be reflected on every label,
5794 * so mark them all dirty. spa_unload() will do the
5795 * final sync that pushes these changes out.
5796 */
fb5f0bc8 5797 if (new_state != POOL_STATE_UNINITIALIZED && !hardforce) {
b128c09f 5798 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 5799 spa->spa_state = new_state;
428870ff
BB
5800 spa->spa_final_txg = spa_last_synced_txg(spa) +
5801 TXG_DEFER_SIZE + 1;
34dc7c2f 5802 vdev_config_dirty(spa->spa_root_vdev);
b128c09f 5803 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
5804 }
5805 }
5806
d14cfd83 5807export_spa:
d5e024cb
BB
5808 if (new_state == POOL_STATE_DESTROYED)
5809 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_DESTROY);
5810 else if (new_state == POOL_STATE_EXPORTED)
5811 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_EXPORT);
34dc7c2f
BB
5812
5813 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
5814 spa_unload(spa);
5815 spa_deactivate(spa);
5816 }
5817
5818 if (oldconfig && spa->spa_config)
5819 VERIFY(nvlist_dup(spa->spa_config, oldconfig, 0) == 0);
5820
5821 if (new_state != POOL_STATE_UNINITIALIZED) {
fb5f0bc8 5822 if (!hardforce)
a1d477c2 5823 spa_write_cachefile(spa, B_TRUE, B_TRUE);
34dc7c2f 5824 spa_remove(spa);
34dc7c2f
BB
5825 }
5826 mutex_exit(&spa_namespace_lock);
5827
5828 return (0);
5829}
5830
5831/*
5832 * Destroy a storage pool.
5833 */
5834int
5835spa_destroy(char *pool)
5836{
fb5f0bc8
BB
5837 return (spa_export_common(pool, POOL_STATE_DESTROYED, NULL,
5838 B_FALSE, B_FALSE));
34dc7c2f
BB
5839}
5840
5841/*
5842 * Export a storage pool.
5843 */
5844int
fb5f0bc8
BB
5845spa_export(char *pool, nvlist_t **oldconfig, boolean_t force,
5846 boolean_t hardforce)
34dc7c2f 5847{
fb5f0bc8
BB
5848 return (spa_export_common(pool, POOL_STATE_EXPORTED, oldconfig,
5849 force, hardforce));
34dc7c2f
BB
5850}
5851
5852/*
5853 * Similar to spa_export(), this unloads the spa_t without actually removing it
5854 * from the namespace in any way.
5855 */
5856int
5857spa_reset(char *pool)
5858{
b128c09f 5859 return (spa_export_common(pool, POOL_STATE_UNINITIALIZED, NULL,
fb5f0bc8 5860 B_FALSE, B_FALSE));
34dc7c2f
BB
5861}
5862
34dc7c2f
BB
5863/*
5864 * ==========================================================================
5865 * Device manipulation
5866 * ==========================================================================
5867 */
5868
5869/*
5870 * Add a device to a storage pool.
5871 */
5872int
5873spa_vdev_add(spa_t *spa, nvlist_t *nvroot)
5874{
428870ff 5875 uint64_t txg, id;
fb5f0bc8 5876 int error;
34dc7c2f
BB
5877 vdev_t *rvd = spa->spa_root_vdev;
5878 vdev_t *vd, *tvd;
5879 nvlist_t **spares, **l2cache;
5880 uint_t nspares, nl2cache;
5881
572e2857
BB
5882 ASSERT(spa_writeable(spa));
5883
34dc7c2f
BB
5884 txg = spa_vdev_enter(spa);
5885
5886 if ((error = spa_config_parse(spa, &vd, nvroot, NULL, 0,
5887 VDEV_ALLOC_ADD)) != 0)
5888 return (spa_vdev_exit(spa, NULL, txg, error));
5889
b128c09f 5890 spa->spa_pending_vdev = vd; /* spa_vdev_exit() will clear this */
34dc7c2f
BB
5891
5892 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares,
5893 &nspares) != 0)
5894 nspares = 0;
5895
5896 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE, &l2cache,
5897 &nl2cache) != 0)
5898 nl2cache = 0;
5899
b128c09f 5900 if (vd->vdev_children == 0 && nspares == 0 && nl2cache == 0)
34dc7c2f 5901 return (spa_vdev_exit(spa, vd, txg, EINVAL));
34dc7c2f 5902
b128c09f
BB
5903 if (vd->vdev_children != 0 &&
5904 (error = vdev_create(vd, txg, B_FALSE)) != 0)
5905 return (spa_vdev_exit(spa, vd, txg, error));
34dc7c2f
BB
5906
5907 /*
5908 * We must validate the spares and l2cache devices after checking the
5909 * children. Otherwise, vdev_inuse() will blindly overwrite the spare.
5910 */
b128c09f 5911 if ((error = spa_validate_aux(spa, nvroot, txg, VDEV_ALLOC_ADD)) != 0)
34dc7c2f 5912 return (spa_vdev_exit(spa, vd, txg, error));
34dc7c2f
BB
5913
5914 /*
a1d477c2
MA
5915 * If we are in the middle of a device removal, we can only add
5916 * devices which match the existing devices in the pool.
5917 * If we are in the middle of a removal, or have some indirect
5918 * vdevs, we can not add raidz toplevels.
34dc7c2f 5919 */
a1d477c2
MA
5920 if (spa->spa_vdev_removal != NULL ||
5921 spa->spa_removing_phys.sr_prev_indirect_vdev != -1) {
5922 for (int c = 0; c < vd->vdev_children; c++) {
5923 tvd = vd->vdev_child[c];
5924 if (spa->spa_vdev_removal != NULL &&
9e052db4 5925 tvd->vdev_ashift != spa->spa_max_ashift) {
a1d477c2
MA
5926 return (spa_vdev_exit(spa, vd, txg, EINVAL));
5927 }
5928 /* Fail if top level vdev is raidz */
5929 if (tvd->vdev_ops == &vdev_raidz_ops) {
5930 return (spa_vdev_exit(spa, vd, txg, EINVAL));
5931 }
5932 /*
5933 * Need the top level mirror to be
5934 * a mirror of leaf vdevs only
5935 */
5936 if (tvd->vdev_ops == &vdev_mirror_ops) {
5937 for (uint64_t cid = 0;
5938 cid < tvd->vdev_children; cid++) {
5939 vdev_t *cvd = tvd->vdev_child[cid];
5940 if (!cvd->vdev_ops->vdev_op_leaf) {
5941 return (spa_vdev_exit(spa, vd,
5942 txg, EINVAL));
5943 }
5944 }
5945 }
5946 }
5947 }
5948
1c27024e 5949 for (int c = 0; c < vd->vdev_children; c++) {
428870ff
BB
5950
5951 /*
5952 * Set the vdev id to the first hole, if one exists.
5953 */
5954 for (id = 0; id < rvd->vdev_children; id++) {
5955 if (rvd->vdev_child[id]->vdev_ishole) {
5956 vdev_free(rvd->vdev_child[id]);
5957 break;
5958 }
5959 }
34dc7c2f
BB
5960 tvd = vd->vdev_child[c];
5961 vdev_remove_child(vd, tvd);
428870ff 5962 tvd->vdev_id = id;
34dc7c2f
BB
5963 vdev_add_child(rvd, tvd);
5964 vdev_config_dirty(tvd);
5965 }
5966
5967 if (nspares != 0) {
5968 spa_set_aux_vdevs(&spa->spa_spares, spares, nspares,
5969 ZPOOL_CONFIG_SPARES);
5970 spa_load_spares(spa);
5971 spa->spa_spares.sav_sync = B_TRUE;
5972 }
5973
5974 if (nl2cache != 0) {
5975 spa_set_aux_vdevs(&spa->spa_l2cache, l2cache, nl2cache,
5976 ZPOOL_CONFIG_L2CACHE);
5977 spa_load_l2cache(spa);
5978 spa->spa_l2cache.sav_sync = B_TRUE;
5979 }
5980
5981 /*
5982 * We have to be careful when adding new vdevs to an existing pool.
5983 * If other threads start allocating from these vdevs before we
5984 * sync the config cache, and we lose power, then upon reboot we may
5985 * fail to open the pool because there are DVAs that the config cache
5986 * can't translate. Therefore, we first add the vdevs without
5987 * initializing metaslabs; sync the config cache (via spa_vdev_exit());
5988 * and then let spa_config_update() initialize the new metaslabs.
5989 *
5990 * spa_load() checks for added-but-not-initialized vdevs, so that
5991 * if we lose power at any point in this sequence, the remaining
5992 * steps will be completed the next time we load the pool.
5993 */
5994 (void) spa_vdev_exit(spa, vd, txg, 0);
5995
5996 mutex_enter(&spa_namespace_lock);
5997 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
12fa0466 5998 spa_event_notify(spa, NULL, NULL, ESC_ZFS_VDEV_ADD);
34dc7c2f
BB
5999 mutex_exit(&spa_namespace_lock);
6000
6001 return (0);
6002}
6003
6004/*
6005 * Attach a device to a mirror. The arguments are the path to any device
6006 * in the mirror, and the nvroot for the new device. If the path specifies
6007 * a device that is not mirrored, we automatically insert the mirror vdev.
6008 *
6009 * If 'replacing' is specified, the new device is intended to replace the
6010 * existing device; in this case the two devices are made into their own
6011 * mirror using the 'replacing' vdev, which is functionally identical to
6012 * the mirror vdev (it actually reuses all the same ops) but has a few
6013 * extra rules: you can't attach to it after it's been created, and upon
6014 * completion of resilvering, the first disk (the one being replaced)
6015 * is automatically detached.
6016 */
6017int
6018spa_vdev_attach(spa_t *spa, uint64_t guid, nvlist_t *nvroot, int replacing)
6019{
428870ff 6020 uint64_t txg, dtl_max_txg;
1c27024e 6021 ASSERTV(vdev_t *rvd = spa->spa_root_vdev);
34dc7c2f
BB
6022 vdev_t *oldvd, *newvd, *newrootvd, *pvd, *tvd;
6023 vdev_ops_t *pvops;
b128c09f
BB
6024 char *oldvdpath, *newvdpath;
6025 int newvd_isspare;
6026 int error;
34dc7c2f 6027
572e2857
BB
6028 ASSERT(spa_writeable(spa));
6029
34dc7c2f
BB
6030 txg = spa_vdev_enter(spa);
6031
b128c09f 6032 oldvd = spa_lookup_by_guid(spa, guid, B_FALSE);
34dc7c2f 6033
d2734cce
SD
6034 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6035 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6036 error = (spa_has_checkpoint(spa)) ?
6037 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6038 return (spa_vdev_exit(spa, NULL, txg, error));
6039 }
6040
9e052db4 6041 if (spa->spa_vdev_removal != NULL)
a1d477c2 6042 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
a1d477c2 6043
34dc7c2f
BB
6044 if (oldvd == NULL)
6045 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
6046
6047 if (!oldvd->vdev_ops->vdev_op_leaf)
6048 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6049
6050 pvd = oldvd->vdev_parent;
6051
6052 if ((error = spa_config_parse(spa, &newrootvd, nvroot, NULL, 0,
5ffb9d1d 6053 VDEV_ALLOC_ATTACH)) != 0)
34dc7c2f
BB
6054 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6055
6056 if (newrootvd->vdev_children != 1)
6057 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
6058
6059 newvd = newrootvd->vdev_child[0];
6060
6061 if (!newvd->vdev_ops->vdev_op_leaf)
6062 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
6063
6064 if ((error = vdev_create(newrootvd, txg, replacing)) != 0)
6065 return (spa_vdev_exit(spa, newrootvd, txg, error));
6066
6067 /*
6068 * Spares can't replace logs
6069 */
b128c09f 6070 if (oldvd->vdev_top->vdev_islog && newvd->vdev_isspare)
34dc7c2f
BB
6071 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6072
6073 if (!replacing) {
6074 /*
6075 * For attach, the only allowable parent is a mirror or the root
6076 * vdev.
6077 */
6078 if (pvd->vdev_ops != &vdev_mirror_ops &&
6079 pvd->vdev_ops != &vdev_root_ops)
6080 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6081
6082 pvops = &vdev_mirror_ops;
6083 } else {
6084 /*
6085 * Active hot spares can only be replaced by inactive hot
6086 * spares.
6087 */
6088 if (pvd->vdev_ops == &vdev_spare_ops &&
572e2857 6089 oldvd->vdev_isspare &&
34dc7c2f
BB
6090 !spa_has_spare(spa, newvd->vdev_guid))
6091 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6092
6093 /*
6094 * If the source is a hot spare, and the parent isn't already a
6095 * spare, then we want to create a new hot spare. Otherwise, we
6096 * want to create a replacing vdev. The user is not allowed to
6097 * attach to a spared vdev child unless the 'isspare' state is
6098 * the same (spare replaces spare, non-spare replaces
6099 * non-spare).
6100 */
572e2857
BB
6101 if (pvd->vdev_ops == &vdev_replacing_ops &&
6102 spa_version(spa) < SPA_VERSION_MULTI_REPLACE) {
34dc7c2f 6103 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
572e2857
BB
6104 } else if (pvd->vdev_ops == &vdev_spare_ops &&
6105 newvd->vdev_isspare != oldvd->vdev_isspare) {
34dc7c2f 6106 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
572e2857
BB
6107 }
6108
6109 if (newvd->vdev_isspare)
34dc7c2f
BB
6110 pvops = &vdev_spare_ops;
6111 else
6112 pvops = &vdev_replacing_ops;
6113 }
6114
6115 /*
9babb374 6116 * Make sure the new device is big enough.
34dc7c2f 6117 */
9babb374 6118 if (newvd->vdev_asize < vdev_get_min_asize(oldvd))
34dc7c2f
BB
6119 return (spa_vdev_exit(spa, newrootvd, txg, EOVERFLOW));
6120
6121 /*
6122 * The new device cannot have a higher alignment requirement
6123 * than the top-level vdev.
6124 */
6125 if (newvd->vdev_ashift > oldvd->vdev_top->vdev_ashift)
6126 return (spa_vdev_exit(spa, newrootvd, txg, EDOM));
6127
6128 /*
6129 * If this is an in-place replacement, update oldvd's path and devid
6130 * to make it distinguishable from newvd, and unopenable from now on.
6131 */
6132 if (strcmp(oldvd->vdev_path, newvd->vdev_path) == 0) {
6133 spa_strfree(oldvd->vdev_path);
6134 oldvd->vdev_path = kmem_alloc(strlen(newvd->vdev_path) + 5,
79c76d5b 6135 KM_SLEEP);
34dc7c2f
BB
6136 (void) sprintf(oldvd->vdev_path, "%s/%s",
6137 newvd->vdev_path, "old");
6138 if (oldvd->vdev_devid != NULL) {
6139 spa_strfree(oldvd->vdev_devid);
6140 oldvd->vdev_devid = NULL;
6141 }
6142 }
6143
572e2857 6144 /* mark the device being resilvered */
5d1f7fb6 6145 newvd->vdev_resilver_txg = txg;
572e2857 6146
34dc7c2f
BB
6147 /*
6148 * If the parent is not a mirror, or if we're replacing, insert the new
6149 * mirror/replacing/spare vdev above oldvd.
6150 */
6151 if (pvd->vdev_ops != pvops)
6152 pvd = vdev_add_parent(oldvd, pvops);
6153
6154 ASSERT(pvd->vdev_top->vdev_parent == rvd);
6155 ASSERT(pvd->vdev_ops == pvops);
6156 ASSERT(oldvd->vdev_parent == pvd);
6157
6158 /*
6159 * Extract the new device from its root and add it to pvd.
6160 */
6161 vdev_remove_child(newrootvd, newvd);
6162 newvd->vdev_id = pvd->vdev_children;
428870ff 6163 newvd->vdev_crtxg = oldvd->vdev_crtxg;
34dc7c2f
BB
6164 vdev_add_child(pvd, newvd);
6165
6d82f98c
IH
6166 /*
6167 * Reevaluate the parent vdev state.
6168 */
6169 vdev_propagate_state(pvd);
6170
34dc7c2f
BB
6171 tvd = newvd->vdev_top;
6172 ASSERT(pvd->vdev_top == tvd);
6173 ASSERT(tvd->vdev_parent == rvd);
6174
6175 vdev_config_dirty(tvd);
6176
6177 /*
428870ff
BB
6178 * Set newvd's DTL to [TXG_INITIAL, dtl_max_txg) so that we account
6179 * for any dmu_sync-ed blocks. It will propagate upward when
6180 * spa_vdev_exit() calls vdev_dtl_reassess().
34dc7c2f 6181 */
428870ff 6182 dtl_max_txg = txg + TXG_CONCURRENT_STATES;
34dc7c2f 6183
428870ff
BB
6184 vdev_dtl_dirty(newvd, DTL_MISSING, TXG_INITIAL,
6185 dtl_max_txg - TXG_INITIAL);
34dc7c2f 6186
9babb374 6187 if (newvd->vdev_isspare) {
34dc7c2f 6188 spa_spare_activate(newvd);
12fa0466 6189 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_SPARE);
9babb374
BB
6190 }
6191
b128c09f
BB
6192 oldvdpath = spa_strdup(oldvd->vdev_path);
6193 newvdpath = spa_strdup(newvd->vdev_path);
6194 newvd_isspare = newvd->vdev_isspare;
34dc7c2f
BB
6195
6196 /*
6197 * Mark newvd's DTL dirty in this txg.
6198 */
6199 vdev_dirty(tvd, VDD_DTL, newvd, txg);
6200
428870ff 6201 /*
93cf2076
GW
6202 * Schedule the resilver to restart in the future. We do this to
6203 * ensure that dmu_sync-ed blocks have been stitched into the
80a91e74
TC
6204 * respective datasets. We do not do this if resilvers have been
6205 * deferred.
428870ff 6206 */
80a91e74
TC
6207 if (dsl_scan_resilvering(spa_get_dsl(spa)) &&
6208 spa_feature_is_enabled(spa, SPA_FEATURE_RESILVER_DEFER))
6209 vdev_set_deferred_resilver(spa, newvd);
6210 else
6211 dsl_resilver_restart(spa->spa_dsl_pool, dtl_max_txg);
428870ff 6212
fb390aaf 6213 if (spa->spa_bootfs)
12fa0466 6214 spa_event_notify(spa, newvd, NULL, ESC_ZFS_BOOTFS_VDEV_ATTACH);
fb390aaf 6215
12fa0466 6216 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_ATTACH);
fb390aaf 6217
428870ff
BB
6218 /*
6219 * Commit the config
6220 */
6221 (void) spa_vdev_exit(spa, newrootvd, dtl_max_txg, 0);
34dc7c2f 6222
6f1ffb06 6223 spa_history_log_internal(spa, "vdev attach", NULL,
428870ff 6224 "%s vdev=%s %s vdev=%s",
45d1cae3
BB
6225 replacing && newvd_isspare ? "spare in" :
6226 replacing ? "replace" : "attach", newvdpath,
6227 replacing ? "for" : "to", oldvdpath);
b128c09f
BB
6228
6229 spa_strfree(oldvdpath);
6230 spa_strfree(newvdpath);
6231
34dc7c2f
BB
6232 return (0);
6233}
6234
6235/*
6236 * Detach a device from a mirror or replacing vdev.
d3cc8b15 6237 *
34dc7c2f
BB
6238 * If 'replace_done' is specified, only detach if the parent
6239 * is a replacing vdev.
6240 */
6241int
fb5f0bc8 6242spa_vdev_detach(spa_t *spa, uint64_t guid, uint64_t pguid, int replace_done)
34dc7c2f
BB
6243{
6244 uint64_t txg;
fb5f0bc8 6245 int error;
1c27024e 6246 ASSERTV(vdev_t *rvd = spa->spa_root_vdev);
34dc7c2f
BB
6247 vdev_t *vd, *pvd, *cvd, *tvd;
6248 boolean_t unspare = B_FALSE;
d4ed6673 6249 uint64_t unspare_guid = 0;
428870ff 6250 char *vdpath;
1c27024e 6251
572e2857
BB
6252 ASSERT(spa_writeable(spa));
6253
34dc7c2f
BB
6254 txg = spa_vdev_enter(spa);
6255
b128c09f 6256 vd = spa_lookup_by_guid(spa, guid, B_FALSE);
34dc7c2f 6257
d2734cce
SD
6258 /*
6259 * Besides being called directly from the userland through the
6260 * ioctl interface, spa_vdev_detach() can be potentially called
6261 * at the end of spa_vdev_resilver_done().
6262 *
6263 * In the regular case, when we have a checkpoint this shouldn't
6264 * happen as we never empty the DTLs of a vdev during the scrub
6265 * [see comment in dsl_scan_done()]. Thus spa_vdev_resilvering_done()
6266 * should never get here when we have a checkpoint.
6267 *
6268 * That said, even in a case when we checkpoint the pool exactly
6269 * as spa_vdev_resilver_done() calls this function everything
6270 * should be fine as the resilver will return right away.
6271 */
6272 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6273 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6274 error = (spa_has_checkpoint(spa)) ?
6275 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6276 return (spa_vdev_exit(spa, NULL, txg, error));
6277 }
6278
34dc7c2f
BB
6279 if (vd == NULL)
6280 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
6281
6282 if (!vd->vdev_ops->vdev_op_leaf)
6283 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6284
6285 pvd = vd->vdev_parent;
6286
fb5f0bc8
BB
6287 /*
6288 * If the parent/child relationship is not as expected, don't do it.
6289 * Consider M(A,R(B,C)) -- that is, a mirror of A with a replacing
6290 * vdev that's replacing B with C. The user's intent in replacing
6291 * is to go from M(A,B) to M(A,C). If the user decides to cancel
6292 * the replace by detaching C, the expected behavior is to end up
6293 * M(A,B). But suppose that right after deciding to detach C,
6294 * the replacement of B completes. We would have M(A,C), and then
6295 * ask to detach C, which would leave us with just A -- not what
6296 * the user wanted. To prevent this, we make sure that the
6297 * parent/child relationship hasn't changed -- in this example,
6298 * that C's parent is still the replacing vdev R.
6299 */
6300 if (pvd->vdev_guid != pguid && pguid != 0)
6301 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6302
34dc7c2f 6303 /*
572e2857 6304 * Only 'replacing' or 'spare' vdevs can be replaced.
34dc7c2f 6305 */
572e2857
BB
6306 if (replace_done && pvd->vdev_ops != &vdev_replacing_ops &&
6307 pvd->vdev_ops != &vdev_spare_ops)
6308 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
34dc7c2f
BB
6309
6310 ASSERT(pvd->vdev_ops != &vdev_spare_ops ||
6311 spa_version(spa) >= SPA_VERSION_SPARES);
6312
6313 /*
6314 * Only mirror, replacing, and spare vdevs support detach.
6315 */
6316 if (pvd->vdev_ops != &vdev_replacing_ops &&
6317 pvd->vdev_ops != &vdev_mirror_ops &&
6318 pvd->vdev_ops != &vdev_spare_ops)
6319 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6320
6321 /*
fb5f0bc8
BB
6322 * If this device has the only valid copy of some data,
6323 * we cannot safely detach it.
34dc7c2f 6324 */
fb5f0bc8 6325 if (vdev_dtl_required(vd))
34dc7c2f
BB
6326 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6327
fb5f0bc8 6328 ASSERT(pvd->vdev_children >= 2);
34dc7c2f 6329
b128c09f
BB
6330 /*
6331 * If we are detaching the second disk from a replacing vdev, then
6332 * check to see if we changed the original vdev's path to have "/old"
6333 * at the end in spa_vdev_attach(). If so, undo that change now.
6334 */
572e2857
BB
6335 if (pvd->vdev_ops == &vdev_replacing_ops && vd->vdev_id > 0 &&
6336 vd->vdev_path != NULL) {
6337 size_t len = strlen(vd->vdev_path);
6338
1c27024e 6339 for (int c = 0; c < pvd->vdev_children; c++) {
572e2857
BB
6340 cvd = pvd->vdev_child[c];
6341
6342 if (cvd == vd || cvd->vdev_path == NULL)
6343 continue;
6344
6345 if (strncmp(cvd->vdev_path, vd->vdev_path, len) == 0 &&
6346 strcmp(cvd->vdev_path + len, "/old") == 0) {
6347 spa_strfree(cvd->vdev_path);
6348 cvd->vdev_path = spa_strdup(vd->vdev_path);
6349 break;
6350 }
b128c09f
BB
6351 }
6352 }
6353
34dc7c2f
BB
6354 /*
6355 * If we are detaching the original disk from a spare, then it implies
6356 * that the spare should become a real disk, and be removed from the
6357 * active spare list for the pool.
6358 */
6359 if (pvd->vdev_ops == &vdev_spare_ops &&
572e2857
BB
6360 vd->vdev_id == 0 &&
6361 pvd->vdev_child[pvd->vdev_children - 1]->vdev_isspare)
34dc7c2f
BB
6362 unspare = B_TRUE;
6363
6364 /*
6365 * Erase the disk labels so the disk can be used for other things.
6366 * This must be done after all other error cases are handled,
6367 * but before we disembowel vd (so we can still do I/O to it).
6368 * But if we can't do it, don't treat the error as fatal --
6369 * it may be that the unwritability of the disk is the reason
6370 * it's being detached!
6371 */
6372 error = vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
6373
6374 /*
6375 * Remove vd from its parent and compact the parent's children.
6376 */
6377 vdev_remove_child(pvd, vd);
6378 vdev_compact_children(pvd);
6379
6380 /*
6381 * Remember one of the remaining children so we can get tvd below.
6382 */
572e2857 6383 cvd = pvd->vdev_child[pvd->vdev_children - 1];
34dc7c2f
BB
6384
6385 /*
6386 * If we need to remove the remaining child from the list of hot spares,
fb5f0bc8
BB
6387 * do it now, marking the vdev as no longer a spare in the process.
6388 * We must do this before vdev_remove_parent(), because that can
6389 * change the GUID if it creates a new toplevel GUID. For a similar
6390 * reason, we must remove the spare now, in the same txg as the detach;
6391 * otherwise someone could attach a new sibling, change the GUID, and
6392 * the subsequent attempt to spa_vdev_remove(unspare_guid) would fail.
34dc7c2f
BB
6393 */
6394 if (unspare) {
6395 ASSERT(cvd->vdev_isspare);
6396 spa_spare_remove(cvd);
6397 unspare_guid = cvd->vdev_guid;
fb5f0bc8 6398 (void) spa_vdev_remove(spa, unspare_guid, B_TRUE);
572e2857 6399 cvd->vdev_unspare = B_TRUE;
34dc7c2f
BB
6400 }
6401
428870ff
BB
6402 /*
6403 * If the parent mirror/replacing vdev only has one child,
6404 * the parent is no longer needed. Remove it from the tree.
6405 */
572e2857
BB
6406 if (pvd->vdev_children == 1) {
6407 if (pvd->vdev_ops == &vdev_spare_ops)
6408 cvd->vdev_unspare = B_FALSE;
428870ff 6409 vdev_remove_parent(cvd);
572e2857
BB
6410 }
6411
428870ff
BB
6412 /*
6413 * We don't set tvd until now because the parent we just removed
6414 * may have been the previous top-level vdev.
6415 */
6416 tvd = cvd->vdev_top;
6417 ASSERT(tvd->vdev_parent == rvd);
6418
6419 /*
6420 * Reevaluate the parent vdev state.
6421 */
6422 vdev_propagate_state(cvd);
6423
6424 /*
6425 * If the 'autoexpand' property is set on the pool then automatically
6426 * try to expand the size of the pool. For example if the device we
6427 * just detached was smaller than the others, it may be possible to
6428 * add metaslabs (i.e. grow the pool). We need to reopen the vdev
6429 * first so that we can obtain the updated sizes of the leaf vdevs.
6430 */
6431 if (spa->spa_autoexpand) {
6432 vdev_reopen(tvd);
6433 vdev_expand(tvd, txg);
6434 }
6435
6436 vdev_config_dirty(tvd);
6437
6438 /*
6439 * Mark vd's DTL as dirty in this txg. vdev_dtl_sync() will see that
6440 * vd->vdev_detached is set and free vd's DTL object in syncing context.
6441 * But first make sure we're not on any *other* txg's DTL list, to
6442 * prevent vd from being accessed after it's freed.
6443 */
b6ca6193 6444 vdpath = spa_strdup(vd->vdev_path ? vd->vdev_path : "none");
1c27024e 6445 for (int t = 0; t < TXG_SIZE; t++)
428870ff
BB
6446 (void) txg_list_remove_this(&tvd->vdev_dtl_list, vd, t);
6447 vd->vdev_detached = B_TRUE;
6448 vdev_dirty(tvd, VDD_DTL, vd, txg);
6449
12fa0466 6450 spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE);
428870ff 6451
572e2857
BB
6452 /* hang on to the spa before we release the lock */
6453 spa_open_ref(spa, FTAG);
6454
428870ff
BB
6455 error = spa_vdev_exit(spa, vd, txg, 0);
6456
6f1ffb06 6457 spa_history_log_internal(spa, "detach", NULL,
428870ff
BB
6458 "vdev=%s", vdpath);
6459 spa_strfree(vdpath);
6460
6461 /*
6462 * If this was the removal of the original device in a hot spare vdev,
6463 * then we want to go through and remove the device from the hot spare
6464 * list of every other pool.
6465 */
6466 if (unspare) {
572e2857
BB
6467 spa_t *altspa = NULL;
6468
428870ff 6469 mutex_enter(&spa_namespace_lock);
572e2857
BB
6470 while ((altspa = spa_next(altspa)) != NULL) {
6471 if (altspa->spa_state != POOL_STATE_ACTIVE ||
6472 altspa == spa)
428870ff 6473 continue;
572e2857
BB
6474
6475 spa_open_ref(altspa, FTAG);
428870ff 6476 mutex_exit(&spa_namespace_lock);
572e2857 6477 (void) spa_vdev_remove(altspa, unspare_guid, B_TRUE);
428870ff 6478 mutex_enter(&spa_namespace_lock);
572e2857 6479 spa_close(altspa, FTAG);
428870ff
BB
6480 }
6481 mutex_exit(&spa_namespace_lock);
572e2857
BB
6482
6483 /* search the rest of the vdevs for spares to remove */
6484 spa_vdev_resilver_done(spa);
428870ff
BB
6485 }
6486
572e2857
BB
6487 /* all done with the spa; OK to release */
6488 mutex_enter(&spa_namespace_lock);
6489 spa_close(spa, FTAG);
6490 mutex_exit(&spa_namespace_lock);
6491
428870ff
BB
6492 return (error);
6493}
6494
c10d37dd
GW
6495static int
6496spa_vdev_initialize_impl(spa_t *spa, uint64_t guid, uint64_t cmd_type,
6497 list_t *vd_list)
619f0976 6498{
c10d37dd
GW
6499 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6500
619f0976
GW
6501 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
6502
6503 /* Look up vdev and ensure it's a leaf. */
6504 vdev_t *vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6505 if (vd == NULL || vd->vdev_detached) {
6506 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
619f0976
GW
6507 return (SET_ERROR(ENODEV));
6508 } else if (!vd->vdev_ops->vdev_op_leaf || !vdev_is_concrete(vd)) {
6509 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
619f0976
GW
6510 return (SET_ERROR(EINVAL));
6511 } else if (!vdev_writeable(vd)) {
6512 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
619f0976
GW
6513 return (SET_ERROR(EROFS));
6514 }
6515 mutex_enter(&vd->vdev_initialize_lock);
6516 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6517
6518 /*
6519 * When we activate an initialize action we check to see
6520 * if the vdev_initialize_thread is NULL. We do this instead
6521 * of using the vdev_initialize_state since there might be
6522 * a previous initialization process which has completed but
6523 * the thread is not exited.
6524 */
1b939560 6525 if (cmd_type == POOL_INITIALIZE_START &&
619f0976
GW
6526 (vd->vdev_initialize_thread != NULL ||
6527 vd->vdev_top->vdev_removing)) {
6528 mutex_exit(&vd->vdev_initialize_lock);
619f0976
GW
6529 return (SET_ERROR(EBUSY));
6530 } else if (cmd_type == POOL_INITIALIZE_CANCEL &&
6531 (vd->vdev_initialize_state != VDEV_INITIALIZE_ACTIVE &&
6532 vd->vdev_initialize_state != VDEV_INITIALIZE_SUSPENDED)) {
6533 mutex_exit(&vd->vdev_initialize_lock);
619f0976
GW
6534 return (SET_ERROR(ESRCH));
6535 } else if (cmd_type == POOL_INITIALIZE_SUSPEND &&
6536 vd->vdev_initialize_state != VDEV_INITIALIZE_ACTIVE) {
6537 mutex_exit(&vd->vdev_initialize_lock);
619f0976
GW
6538 return (SET_ERROR(ESRCH));
6539 }
6540
6541 switch (cmd_type) {
1b939560 6542 case POOL_INITIALIZE_START:
619f0976
GW
6543 vdev_initialize(vd);
6544 break;
6545 case POOL_INITIALIZE_CANCEL:
c10d37dd 6546 vdev_initialize_stop(vd, VDEV_INITIALIZE_CANCELED, vd_list);
619f0976
GW
6547 break;
6548 case POOL_INITIALIZE_SUSPEND:
c10d37dd 6549 vdev_initialize_stop(vd, VDEV_INITIALIZE_SUSPENDED, vd_list);
619f0976
GW
6550 break;
6551 default:
6552 panic("invalid cmd_type %llu", (unsigned long long)cmd_type);
6553 }
6554 mutex_exit(&vd->vdev_initialize_lock);
6555
c10d37dd
GW
6556 return (0);
6557}
6558
6559int
6560spa_vdev_initialize(spa_t *spa, nvlist_t *nv, uint64_t cmd_type,
6561 nvlist_t *vdev_errlist)
6562{
6563 int total_errors = 0;
6564 list_t vd_list;
6565
6566 list_create(&vd_list, sizeof (vdev_t),
6567 offsetof(vdev_t, vdev_initialize_node));
6568
6569 /*
6570 * We hold the namespace lock through the whole function
6571 * to prevent any changes to the pool while we're starting or
6572 * stopping initialization. The config and state locks are held so that
6573 * we can properly assess the vdev state before we commit to
6574 * the initializing operation.
6575 */
6576 mutex_enter(&spa_namespace_lock);
6577
6578 for (nvpair_t *pair = nvlist_next_nvpair(nv, NULL);
6579 pair != NULL; pair = nvlist_next_nvpair(nv, pair)) {
6580 uint64_t vdev_guid = fnvpair_value_uint64(pair);
6581
6582 int error = spa_vdev_initialize_impl(spa, vdev_guid, cmd_type,
6583 &vd_list);
6584 if (error != 0) {
6585 char guid_as_str[MAXNAMELEN];
6586
6587 (void) snprintf(guid_as_str, sizeof (guid_as_str),
6588 "%llu", (unsigned long long)vdev_guid);
6589 fnvlist_add_int64(vdev_errlist, guid_as_str, error);
6590 total_errors++;
6591 }
6592 }
6593
6594 /* Wait for all initialize threads to stop. */
6595 vdev_initialize_stop_wait(spa, &vd_list);
6596
619f0976
GW
6597 /* Sync out the initializing state */
6598 txg_wait_synced(spa->spa_dsl_pool, 0);
6599 mutex_exit(&spa_namespace_lock);
6600
c10d37dd 6601 list_destroy(&vd_list);
619f0976 6602
c10d37dd
GW
6603 return (total_errors);
6604}
619f0976 6605
1b939560
BB
6606static int
6607spa_vdev_trim_impl(spa_t *spa, uint64_t guid, uint64_t cmd_type,
6608 uint64_t rate, boolean_t partial, boolean_t secure, list_t *vd_list)
6609{
6610 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6611
6612 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
6613
6614 /* Look up vdev and ensure it's a leaf. */
6615 vdev_t *vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6616 if (vd == NULL || vd->vdev_detached) {
6617 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6618 return (SET_ERROR(ENODEV));
6619 } else if (!vd->vdev_ops->vdev_op_leaf || !vdev_is_concrete(vd)) {
6620 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6621 return (SET_ERROR(EINVAL));
6622 } else if (!vdev_writeable(vd)) {
6623 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6624 return (SET_ERROR(EROFS));
6625 } else if (!vd->vdev_has_trim) {
6626 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6627 return (SET_ERROR(EOPNOTSUPP));
6628 } else if (secure && !vd->vdev_has_securetrim) {
6629 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6630 return (SET_ERROR(EOPNOTSUPP));
6631 }
6632 mutex_enter(&vd->vdev_trim_lock);
6633 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6634
6635 /*
6636 * When we activate a TRIM action we check to see if the
6637 * vdev_trim_thread is NULL. We do this instead of using the
6638 * vdev_trim_state since there might be a previous TRIM process
6639 * which has completed but the thread is not exited.
6640 */
6641 if (cmd_type == POOL_TRIM_START &&
6642 (vd->vdev_trim_thread != NULL || vd->vdev_top->vdev_removing)) {
6643 mutex_exit(&vd->vdev_trim_lock);
6644 return (SET_ERROR(EBUSY));
6645 } else if (cmd_type == POOL_TRIM_CANCEL &&
6646 (vd->vdev_trim_state != VDEV_TRIM_ACTIVE &&
6647 vd->vdev_trim_state != VDEV_TRIM_SUSPENDED)) {
6648 mutex_exit(&vd->vdev_trim_lock);
6649 return (SET_ERROR(ESRCH));
6650 } else if (cmd_type == POOL_TRIM_SUSPEND &&
6651 vd->vdev_trim_state != VDEV_TRIM_ACTIVE) {
6652 mutex_exit(&vd->vdev_trim_lock);
6653 return (SET_ERROR(ESRCH));
6654 }
6655
6656 switch (cmd_type) {
6657 case POOL_TRIM_START:
6658 vdev_trim(vd, rate, partial, secure);
6659 break;
6660 case POOL_TRIM_CANCEL:
6661 vdev_trim_stop(vd, VDEV_TRIM_CANCELED, vd_list);
6662 break;
6663 case POOL_TRIM_SUSPEND:
6664 vdev_trim_stop(vd, VDEV_TRIM_SUSPENDED, vd_list);
6665 break;
6666 default:
6667 panic("invalid cmd_type %llu", (unsigned long long)cmd_type);
6668 }
6669 mutex_exit(&vd->vdev_trim_lock);
6670
6671 return (0);
6672}
6673
6674/*
6675 * Initiates a manual TRIM for the requested vdevs. This kicks off individual
6676 * TRIM threads for each child vdev. These threads pass over all of the free
6677 * space in the vdev's metaslabs and issues TRIM commands for that space.
6678 */
6679int
6680spa_vdev_trim(spa_t *spa, nvlist_t *nv, uint64_t cmd_type, uint64_t rate,
6681 boolean_t partial, boolean_t secure, nvlist_t *vdev_errlist)
6682{
6683 int total_errors = 0;
6684 list_t vd_list;
6685
6686 list_create(&vd_list, sizeof (vdev_t),
6687 offsetof(vdev_t, vdev_trim_node));
6688
6689 /*
6690 * We hold the namespace lock through the whole function
6691 * to prevent any changes to the pool while we're starting or
6692 * stopping TRIM. The config and state locks are held so that
6693 * we can properly assess the vdev state before we commit to
6694 * the TRIM operation.
6695 */
6696 mutex_enter(&spa_namespace_lock);
6697
6698 for (nvpair_t *pair = nvlist_next_nvpair(nv, NULL);
6699 pair != NULL; pair = nvlist_next_nvpair(nv, pair)) {
6700 uint64_t vdev_guid = fnvpair_value_uint64(pair);
6701
6702 int error = spa_vdev_trim_impl(spa, vdev_guid, cmd_type,
6703 rate, partial, secure, &vd_list);
6704 if (error != 0) {
6705 char guid_as_str[MAXNAMELEN];
6706
6707 (void) snprintf(guid_as_str, sizeof (guid_as_str),
6708 "%llu", (unsigned long long)vdev_guid);
6709 fnvlist_add_int64(vdev_errlist, guid_as_str, error);
6710 total_errors++;
6711 }
6712 }
6713
6714 /* Wait for all TRIM threads to stop. */
6715 vdev_trim_stop_wait(spa, &vd_list);
6716
6717 /* Sync out the TRIM state */
6718 txg_wait_synced(spa->spa_dsl_pool, 0);
6719 mutex_exit(&spa_namespace_lock);
6720
6721 list_destroy(&vd_list);
6722
6723 return (total_errors);
6724}
6725
428870ff
BB
6726/*
6727 * Split a set of devices from their mirrors, and create a new pool from them.
6728 */
6729int
6730spa_vdev_split_mirror(spa_t *spa, char *newname, nvlist_t *config,
6731 nvlist_t *props, boolean_t exp)
6732{
6733 int error = 0;
6734 uint64_t txg, *glist;
6735 spa_t *newspa;
6736 uint_t c, children, lastlog;
6737 nvlist_t **child, *nvl, *tmp;
6738 dmu_tx_t *tx;
6739 char *altroot = NULL;
6740 vdev_t *rvd, **vml = NULL; /* vdev modify list */
6741 boolean_t activate_slog;
6742
572e2857 6743 ASSERT(spa_writeable(spa));
428870ff
BB
6744
6745 txg = spa_vdev_enter(spa);
6746
d2734cce
SD
6747 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6748 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6749 error = (spa_has_checkpoint(spa)) ?
6750 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6751 return (spa_vdev_exit(spa, NULL, txg, error));
6752 }
6753
428870ff
BB
6754 /* clear the log and flush everything up to now */
6755 activate_slog = spa_passivate_log(spa);
6756 (void) spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
a1d477c2 6757 error = spa_reset_logs(spa);
428870ff
BB
6758 txg = spa_vdev_config_enter(spa);
6759
6760 if (activate_slog)
6761 spa_activate_log(spa);
6762
6763 if (error != 0)
6764 return (spa_vdev_exit(spa, NULL, txg, error));
6765
6766 /* check new spa name before going any further */
6767 if (spa_lookup(newname) != NULL)
6768 return (spa_vdev_exit(spa, NULL, txg, EEXIST));
6769
6770 /*
6771 * scan through all the children to ensure they're all mirrors
6772 */
6773 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvl) != 0 ||
6774 nvlist_lookup_nvlist_array(nvl, ZPOOL_CONFIG_CHILDREN, &child,
6775 &children) != 0)
6776 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6777
6778 /* first, check to ensure we've got the right child count */
6779 rvd = spa->spa_root_vdev;
6780 lastlog = 0;
6781 for (c = 0; c < rvd->vdev_children; c++) {
6782 vdev_t *vd = rvd->vdev_child[c];
6783
6784 /* don't count the holes & logs as children */
a1d477c2 6785 if (vd->vdev_islog || !vdev_is_concrete(vd)) {
428870ff
BB
6786 if (lastlog == 0)
6787 lastlog = c;
6788 continue;
6789 }
6790
6791 lastlog = 0;
6792 }
6793 if (children != (lastlog != 0 ? lastlog : rvd->vdev_children))
6794 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6795
6796 /* next, ensure no spare or cache devices are part of the split */
6797 if (nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_SPARES, &tmp) == 0 ||
6798 nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_L2CACHE, &tmp) == 0)
6799 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6800
79c76d5b
BB
6801 vml = kmem_zalloc(children * sizeof (vdev_t *), KM_SLEEP);
6802 glist = kmem_zalloc(children * sizeof (uint64_t), KM_SLEEP);
428870ff
BB
6803
6804 /* then, loop over each vdev and validate it */
6805 for (c = 0; c < children; c++) {
6806 uint64_t is_hole = 0;
6807
6808 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
6809 &is_hole);
6810
6811 if (is_hole != 0) {
6812 if (spa->spa_root_vdev->vdev_child[c]->vdev_ishole ||
6813 spa->spa_root_vdev->vdev_child[c]->vdev_islog) {
6814 continue;
6815 } else {
2e528b49 6816 error = SET_ERROR(EINVAL);
428870ff
BB
6817 break;
6818 }
6819 }
6820
6821 /* which disk is going to be split? */
6822 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_GUID,
6823 &glist[c]) != 0) {
2e528b49 6824 error = SET_ERROR(EINVAL);
428870ff
BB
6825 break;
6826 }
6827
6828 /* look it up in the spa */
6829 vml[c] = spa_lookup_by_guid(spa, glist[c], B_FALSE);
6830 if (vml[c] == NULL) {
2e528b49 6831 error = SET_ERROR(ENODEV);
428870ff
BB
6832 break;
6833 }
6834
6835 /* make sure there's nothing stopping the split */
6836 if (vml[c]->vdev_parent->vdev_ops != &vdev_mirror_ops ||
6837 vml[c]->vdev_islog ||
a1d477c2 6838 !vdev_is_concrete(vml[c]) ||
428870ff
BB
6839 vml[c]->vdev_isspare ||
6840 vml[c]->vdev_isl2cache ||
6841 !vdev_writeable(vml[c]) ||
6842 vml[c]->vdev_children != 0 ||
6843 vml[c]->vdev_state != VDEV_STATE_HEALTHY ||
6844 c != spa->spa_root_vdev->vdev_child[c]->vdev_id) {
2e528b49 6845 error = SET_ERROR(EINVAL);
428870ff
BB
6846 break;
6847 }
6848
733b5722
RS
6849 if (vdev_dtl_required(vml[c]) ||
6850 vdev_resilver_needed(vml[c], NULL, NULL)) {
2e528b49 6851 error = SET_ERROR(EBUSY);
428870ff
BB
6852 break;
6853 }
6854
6855 /* we need certain info from the top level */
6856 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_ARRAY,
6857 vml[c]->vdev_top->vdev_ms_array) == 0);
6858 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_SHIFT,
6859 vml[c]->vdev_top->vdev_ms_shift) == 0);
6860 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASIZE,
6861 vml[c]->vdev_top->vdev_asize) == 0);
6862 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASHIFT,
6863 vml[c]->vdev_top->vdev_ashift) == 0);
e0ab3ab5
JS
6864
6865 /* transfer per-vdev ZAPs */
6866 ASSERT3U(vml[c]->vdev_leaf_zap, !=, 0);
6867 VERIFY0(nvlist_add_uint64(child[c],
6868 ZPOOL_CONFIG_VDEV_LEAF_ZAP, vml[c]->vdev_leaf_zap));
6869
6870 ASSERT3U(vml[c]->vdev_top->vdev_top_zap, !=, 0);
6871 VERIFY0(nvlist_add_uint64(child[c],
6872 ZPOOL_CONFIG_VDEV_TOP_ZAP,
6873 vml[c]->vdev_parent->vdev_top_zap));
428870ff
BB
6874 }
6875
6876 if (error != 0) {
6877 kmem_free(vml, children * sizeof (vdev_t *));
6878 kmem_free(glist, children * sizeof (uint64_t));
6879 return (spa_vdev_exit(spa, NULL, txg, error));
6880 }
6881
6882 /* stop writers from using the disks */
6883 for (c = 0; c < children; c++) {
6884 if (vml[c] != NULL)
6885 vml[c]->vdev_offline = B_TRUE;
6886 }
6887 vdev_reopen(spa->spa_root_vdev);
34dc7c2f
BB
6888
6889 /*
428870ff
BB
6890 * Temporarily record the splitting vdevs in the spa config. This
6891 * will disappear once the config is regenerated.
34dc7c2f 6892 */
79c76d5b 6893 VERIFY(nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
428870ff
BB
6894 VERIFY(nvlist_add_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
6895 glist, children) == 0);
6896 kmem_free(glist, children * sizeof (uint64_t));
34dc7c2f 6897
428870ff
BB
6898 mutex_enter(&spa->spa_props_lock);
6899 VERIFY(nvlist_add_nvlist(spa->spa_config, ZPOOL_CONFIG_SPLIT,
6900 nvl) == 0);
6901 mutex_exit(&spa->spa_props_lock);
6902 spa->spa_config_splitting = nvl;
6903 vdev_config_dirty(spa->spa_root_vdev);
6904
6905 /* configure and create the new pool */
6906 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME, newname) == 0);
6907 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
6908 exp ? POOL_STATE_EXPORTED : POOL_STATE_ACTIVE) == 0);
6909 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
6910 spa_version(spa)) == 0);
6911 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_TXG,
6912 spa->spa_config_txg) == 0);
6913 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_GUID,
6914 spa_generate_guid(NULL)) == 0);
e0ab3ab5 6915 VERIFY0(nvlist_add_boolean(config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
428870ff
BB
6916 (void) nvlist_lookup_string(props,
6917 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
34dc7c2f 6918
428870ff
BB
6919 /* add the new pool to the namespace */
6920 newspa = spa_add(newname, config, altroot);
e0ab3ab5 6921 newspa->spa_avz_action = AVZ_ACTION_REBUILD;
428870ff
BB
6922 newspa->spa_config_txg = spa->spa_config_txg;
6923 spa_set_log_state(newspa, SPA_LOG_CLEAR);
6924
6925 /* release the spa config lock, retaining the namespace lock */
6926 spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
6927
6928 if (zio_injection_enabled)
6929 zio_handle_panic_injection(spa, FTAG, 1);
6930
6931 spa_activate(newspa, spa_mode_global);
6932 spa_async_suspend(newspa);
6933
c10d37dd 6934 /*
1b939560
BB
6935 * Temporarily stop the initializing and TRIM activity. We set the
6936 * state to ACTIVE so that we know to resume initializing or TRIM
6937 * once the split has completed.
c10d37dd 6938 */
1b939560
BB
6939 list_t vd_initialize_list;
6940 list_create(&vd_initialize_list, sizeof (vdev_t),
c10d37dd
GW
6941 offsetof(vdev_t, vdev_initialize_node));
6942
1b939560
BB
6943 list_t vd_trim_list;
6944 list_create(&vd_trim_list, sizeof (vdev_t),
6945 offsetof(vdev_t, vdev_trim_node));
6946
619f0976
GW
6947 for (c = 0; c < children; c++) {
6948 if (vml[c] != NULL) {
619f0976 6949 mutex_enter(&vml[c]->vdev_initialize_lock);
1b939560
BB
6950 vdev_initialize_stop(vml[c],
6951 VDEV_INITIALIZE_ACTIVE, &vd_initialize_list);
619f0976 6952 mutex_exit(&vml[c]->vdev_initialize_lock);
1b939560
BB
6953
6954 mutex_enter(&vml[c]->vdev_trim_lock);
6955 vdev_trim_stop(vml[c], VDEV_TRIM_ACTIVE, &vd_trim_list);
6956 mutex_exit(&vml[c]->vdev_trim_lock);
619f0976
GW
6957 }
6958 }
1b939560
BB
6959
6960 vdev_initialize_stop_wait(spa, &vd_initialize_list);
6961 vdev_trim_stop_wait(spa, &vd_trim_list);
6962
6963 list_destroy(&vd_initialize_list);
6964 list_destroy(&vd_trim_list);
619f0976 6965
6cb8e530
PZ
6966 newspa->spa_config_source = SPA_CONFIG_SRC_SPLIT;
6967
428870ff 6968 /* create the new pool from the disks of the original pool */
6cb8e530 6969 error = spa_load(newspa, SPA_LOAD_IMPORT, SPA_IMPORT_ASSEMBLE);
428870ff
BB
6970 if (error)
6971 goto out;
6972
6973 /* if that worked, generate a real config for the new pool */
6974 if (newspa->spa_root_vdev != NULL) {
6975 VERIFY(nvlist_alloc(&newspa->spa_config_splitting,
79c76d5b 6976 NV_UNIQUE_NAME, KM_SLEEP) == 0);
428870ff
BB
6977 VERIFY(nvlist_add_uint64(newspa->spa_config_splitting,
6978 ZPOOL_CONFIG_SPLIT_GUID, spa_guid(spa)) == 0);
6979 spa_config_set(newspa, spa_config_generate(newspa, NULL, -1ULL,
6980 B_TRUE));
9babb374 6981 }
34dc7c2f 6982
428870ff
BB
6983 /* set the props */
6984 if (props != NULL) {
6985 spa_configfile_set(newspa, props, B_FALSE);
6986 error = spa_prop_set(newspa, props);
6987 if (error)
6988 goto out;
6989 }
34dc7c2f 6990
428870ff
BB
6991 /* flush everything */
6992 txg = spa_vdev_config_enter(newspa);
6993 vdev_config_dirty(newspa->spa_root_vdev);
6994 (void) spa_vdev_config_exit(newspa, NULL, txg, 0, FTAG);
34dc7c2f 6995
428870ff
BB
6996 if (zio_injection_enabled)
6997 zio_handle_panic_injection(spa, FTAG, 2);
34dc7c2f 6998
428870ff 6999 spa_async_resume(newspa);
34dc7c2f 7000
428870ff
BB
7001 /* finally, update the original pool's config */
7002 txg = spa_vdev_config_enter(spa);
7003 tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
7004 error = dmu_tx_assign(tx, TXG_WAIT);
7005 if (error != 0)
7006 dmu_tx_abort(tx);
7007 for (c = 0; c < children; c++) {
7008 if (vml[c] != NULL) {
234234ca
RS
7009 vdev_t *tvd = vml[c]->vdev_top;
7010
7011 /*
7012 * Need to be sure the detachable VDEV is not
7013 * on any *other* txg's DTL list to prevent it
7014 * from being accessed after it's freed.
7015 */
7016 for (int t = 0; t < TXG_SIZE; t++) {
7017 (void) txg_list_remove_this(
7018 &tvd->vdev_dtl_list, vml[c], t);
7019 }
7020
428870ff
BB
7021 vdev_split(vml[c]);
7022 if (error == 0)
6f1ffb06
MA
7023 spa_history_log_internal(spa, "detach", tx,
7024 "vdev=%s", vml[c]->vdev_path);
e0ab3ab5 7025
428870ff 7026 vdev_free(vml[c]);
34dc7c2f 7027 }
34dc7c2f 7028 }
e0ab3ab5 7029 spa->spa_avz_action = AVZ_ACTION_REBUILD;
428870ff
BB
7030 vdev_config_dirty(spa->spa_root_vdev);
7031 spa->spa_config_splitting = NULL;
7032 nvlist_free(nvl);
7033 if (error == 0)
7034 dmu_tx_commit(tx);
7035 (void) spa_vdev_exit(spa, NULL, txg, 0);
7036
7037 if (zio_injection_enabled)
7038 zio_handle_panic_injection(spa, FTAG, 3);
7039
7040 /* split is complete; log a history record */
6f1ffb06
MA
7041 spa_history_log_internal(newspa, "split", NULL,
7042 "from pool %s", spa_name(spa));
428870ff
BB
7043
7044 kmem_free(vml, children * sizeof (vdev_t *));
7045
7046 /* if we're not going to mount the filesystems in userland, export */
7047 if (exp)
7048 error = spa_export_common(newname, POOL_STATE_EXPORTED, NULL,
7049 B_FALSE, B_FALSE);
7050
7051 return (error);
7052
7053out:
7054 spa_unload(newspa);
7055 spa_deactivate(newspa);
7056 spa_remove(newspa);
7057
7058 txg = spa_vdev_config_enter(spa);
7059
7060 /* re-online all offlined disks */
7061 for (c = 0; c < children; c++) {
7062 if (vml[c] != NULL)
7063 vml[c]->vdev_offline = B_FALSE;
7064 }
619f0976 7065
1b939560 7066 /* restart initializing or trimming disks as necessary */
619f0976 7067 spa_async_request(spa, SPA_ASYNC_INITIALIZE_RESTART);
1b939560
BB
7068 spa_async_request(spa, SPA_ASYNC_TRIM_RESTART);
7069 spa_async_request(spa, SPA_ASYNC_AUTOTRIM_RESTART);
619f0976 7070
428870ff
BB
7071 vdev_reopen(spa->spa_root_vdev);
7072
7073 nvlist_free(spa->spa_config_splitting);
7074 spa->spa_config_splitting = NULL;
7075 (void) spa_vdev_exit(spa, NULL, txg, error);
34dc7c2f 7076
428870ff 7077 kmem_free(vml, children * sizeof (vdev_t *));
34dc7c2f
BB
7078 return (error);
7079}
7080
34dc7c2f
BB
7081/*
7082 * Find any device that's done replacing, or a vdev marked 'unspare' that's
d3cc8b15 7083 * currently spared, so we can detach it.
34dc7c2f
BB
7084 */
7085static vdev_t *
7086spa_vdev_resilver_done_hunt(vdev_t *vd)
7087{
7088 vdev_t *newvd, *oldvd;
34dc7c2f 7089
1c27024e 7090 for (int c = 0; c < vd->vdev_children; c++) {
34dc7c2f
BB
7091 oldvd = spa_vdev_resilver_done_hunt(vd->vdev_child[c]);
7092 if (oldvd != NULL)
7093 return (oldvd);
7094 }
7095
7096 /*
572e2857
BB
7097 * Check for a completed replacement. We always consider the first
7098 * vdev in the list to be the oldest vdev, and the last one to be
7099 * the newest (see spa_vdev_attach() for how that works). In
7100 * the case where the newest vdev is faulted, we will not automatically
7101 * remove it after a resilver completes. This is OK as it will require
7102 * user intervention to determine which disk the admin wishes to keep.
34dc7c2f 7103 */
572e2857
BB
7104 if (vd->vdev_ops == &vdev_replacing_ops) {
7105 ASSERT(vd->vdev_children > 1);
7106
7107 newvd = vd->vdev_child[vd->vdev_children - 1];
34dc7c2f 7108 oldvd = vd->vdev_child[0];
34dc7c2f 7109
fb5f0bc8 7110 if (vdev_dtl_empty(newvd, DTL_MISSING) &&
428870ff 7111 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
fb5f0bc8 7112 !vdev_dtl_required(oldvd))
34dc7c2f 7113 return (oldvd);
34dc7c2f
BB
7114 }
7115
7116 /*
7117 * Check for a completed resilver with the 'unspare' flag set.
f65fbee1 7118 * Also potentially update faulted state.
34dc7c2f 7119 */
572e2857
BB
7120 if (vd->vdev_ops == &vdev_spare_ops) {
7121 vdev_t *first = vd->vdev_child[0];
7122 vdev_t *last = vd->vdev_child[vd->vdev_children - 1];
7123
7124 if (last->vdev_unspare) {
7125 oldvd = first;
7126 newvd = last;
7127 } else if (first->vdev_unspare) {
7128 oldvd = last;
7129 newvd = first;
7130 } else {
7131 oldvd = NULL;
7132 }
34dc7c2f 7133
572e2857 7134 if (oldvd != NULL &&
fb5f0bc8 7135 vdev_dtl_empty(newvd, DTL_MISSING) &&
428870ff 7136 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
572e2857 7137 !vdev_dtl_required(oldvd))
34dc7c2f 7138 return (oldvd);
572e2857 7139
f65fbee1
JJ
7140 vdev_propagate_state(vd);
7141
572e2857
BB
7142 /*
7143 * If there are more than two spares attached to a disk,
7144 * and those spares are not required, then we want to
7145 * attempt to free them up now so that they can be used
7146 * by other pools. Once we're back down to a single
7147 * disk+spare, we stop removing them.
7148 */
7149 if (vd->vdev_children > 2) {
7150 newvd = vd->vdev_child[1];
7151
7152 if (newvd->vdev_isspare && last->vdev_isspare &&
7153 vdev_dtl_empty(last, DTL_MISSING) &&
7154 vdev_dtl_empty(last, DTL_OUTAGE) &&
7155 !vdev_dtl_required(newvd))
7156 return (newvd);
34dc7c2f 7157 }
34dc7c2f
BB
7158 }
7159
7160 return (NULL);
7161}
7162
7163static void
7164spa_vdev_resilver_done(spa_t *spa)
7165{
fb5f0bc8
BB
7166 vdev_t *vd, *pvd, *ppvd;
7167 uint64_t guid, sguid, pguid, ppguid;
34dc7c2f 7168
fb5f0bc8 7169 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f
BB
7170
7171 while ((vd = spa_vdev_resilver_done_hunt(spa->spa_root_vdev)) != NULL) {
fb5f0bc8
BB
7172 pvd = vd->vdev_parent;
7173 ppvd = pvd->vdev_parent;
34dc7c2f 7174 guid = vd->vdev_guid;
fb5f0bc8
BB
7175 pguid = pvd->vdev_guid;
7176 ppguid = ppvd->vdev_guid;
7177 sguid = 0;
34dc7c2f
BB
7178 /*
7179 * If we have just finished replacing a hot spared device, then
7180 * we need to detach the parent's first child (the original hot
7181 * spare) as well.
7182 */
572e2857
BB
7183 if (ppvd->vdev_ops == &vdev_spare_ops && pvd->vdev_id == 0 &&
7184 ppvd->vdev_children == 2) {
34dc7c2f 7185 ASSERT(pvd->vdev_ops == &vdev_replacing_ops);
fb5f0bc8 7186 sguid = ppvd->vdev_child[1]->vdev_guid;
34dc7c2f 7187 }
5d1f7fb6
GW
7188 ASSERT(vd->vdev_resilver_txg == 0 || !vdev_dtl_required(vd));
7189
fb5f0bc8
BB
7190 spa_config_exit(spa, SCL_ALL, FTAG);
7191 if (spa_vdev_detach(spa, guid, pguid, B_TRUE) != 0)
34dc7c2f 7192 return;
fb5f0bc8 7193 if (sguid && spa_vdev_detach(spa, sguid, ppguid, B_TRUE) != 0)
34dc7c2f 7194 return;
fb5f0bc8 7195 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f
BB
7196 }
7197
fb5f0bc8 7198 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
7199}
7200
7201/*
428870ff 7202 * Update the stored path or FRU for this vdev.
34dc7c2f
BB
7203 */
7204int
9babb374
BB
7205spa_vdev_set_common(spa_t *spa, uint64_t guid, const char *value,
7206 boolean_t ispath)
34dc7c2f 7207{
b128c09f 7208 vdev_t *vd;
428870ff 7209 boolean_t sync = B_FALSE;
34dc7c2f 7210
572e2857
BB
7211 ASSERT(spa_writeable(spa));
7212
428870ff 7213 spa_vdev_state_enter(spa, SCL_ALL);
34dc7c2f 7214
9babb374 7215 if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
428870ff 7216 return (spa_vdev_state_exit(spa, NULL, ENOENT));
34dc7c2f
BB
7217
7218 if (!vd->vdev_ops->vdev_op_leaf)
428870ff 7219 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
34dc7c2f 7220
9babb374 7221 if (ispath) {
428870ff
BB
7222 if (strcmp(value, vd->vdev_path) != 0) {
7223 spa_strfree(vd->vdev_path);
7224 vd->vdev_path = spa_strdup(value);
7225 sync = B_TRUE;
7226 }
9babb374 7227 } else {
428870ff
BB
7228 if (vd->vdev_fru == NULL) {
7229 vd->vdev_fru = spa_strdup(value);
7230 sync = B_TRUE;
7231 } else if (strcmp(value, vd->vdev_fru) != 0) {
9babb374 7232 spa_strfree(vd->vdev_fru);
428870ff
BB
7233 vd->vdev_fru = spa_strdup(value);
7234 sync = B_TRUE;
7235 }
9babb374 7236 }
34dc7c2f 7237
428870ff 7238 return (spa_vdev_state_exit(spa, sync ? vd : NULL, 0));
34dc7c2f
BB
7239}
7240
9babb374
BB
7241int
7242spa_vdev_setpath(spa_t *spa, uint64_t guid, const char *newpath)
7243{
7244 return (spa_vdev_set_common(spa, guid, newpath, B_TRUE));
7245}
7246
7247int
7248spa_vdev_setfru(spa_t *spa, uint64_t guid, const char *newfru)
7249{
7250 return (spa_vdev_set_common(spa, guid, newfru, B_FALSE));
7251}
7252
34dc7c2f
BB
7253/*
7254 * ==========================================================================
428870ff 7255 * SPA Scanning
34dc7c2f
BB
7256 * ==========================================================================
7257 */
0ea05c64
AP
7258int
7259spa_scrub_pause_resume(spa_t *spa, pool_scrub_cmd_t cmd)
7260{
7261 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7262
7263 if (dsl_scan_resilvering(spa->spa_dsl_pool))
7264 return (SET_ERROR(EBUSY));
7265
7266 return (dsl_scrub_set_pause_resume(spa->spa_dsl_pool, cmd));
7267}
34dc7c2f 7268
34dc7c2f 7269int
428870ff
BB
7270spa_scan_stop(spa_t *spa)
7271{
7272 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7273 if (dsl_scan_resilvering(spa->spa_dsl_pool))
2e528b49 7274 return (SET_ERROR(EBUSY));
428870ff
BB
7275 return (dsl_scan_cancel(spa->spa_dsl_pool));
7276}
7277
7278int
7279spa_scan(spa_t *spa, pool_scan_func_t func)
34dc7c2f 7280{
b128c09f 7281 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
34dc7c2f 7282
428870ff 7283 if (func >= POOL_SCAN_FUNCS || func == POOL_SCAN_NONE)
2e528b49 7284 return (SET_ERROR(ENOTSUP));
34dc7c2f 7285
fa241660
TC
7286 if (func == POOL_SCAN_RESILVER &&
7287 !spa_feature_is_enabled(spa, SPA_FEATURE_RESILVER_DEFER))
7288 return (SET_ERROR(ENOTSUP));
7289
34dc7c2f 7290 /*
b128c09f
BB
7291 * If a resilver was requested, but there is no DTL on a
7292 * writeable leaf device, we have nothing to do.
34dc7c2f 7293 */
428870ff 7294 if (func == POOL_SCAN_RESILVER &&
b128c09f
BB
7295 !vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL)) {
7296 spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
34dc7c2f
BB
7297 return (0);
7298 }
7299
428870ff 7300 return (dsl_scan(spa->spa_dsl_pool, func));
34dc7c2f
BB
7301}
7302
7303/*
7304 * ==========================================================================
7305 * SPA async task processing
7306 * ==========================================================================
7307 */
7308
7309static void
7310spa_async_remove(spa_t *spa, vdev_t *vd)
7311{
b128c09f 7312 if (vd->vdev_remove_wanted) {
428870ff
BB
7313 vd->vdev_remove_wanted = B_FALSE;
7314 vd->vdev_delayed_close = B_FALSE;
b128c09f 7315 vdev_set_state(vd, B_FALSE, VDEV_STATE_REMOVED, VDEV_AUX_NONE);
428870ff
BB
7316
7317 /*
7318 * We want to clear the stats, but we don't want to do a full
7319 * vdev_clear() as that will cause us to throw away
7320 * degraded/faulted state as well as attempt to reopen the
7321 * device, all of which is a waste.
7322 */
7323 vd->vdev_stat.vs_read_errors = 0;
7324 vd->vdev_stat.vs_write_errors = 0;
7325 vd->vdev_stat.vs_checksum_errors = 0;
7326
b128c09f
BB
7327 vdev_state_dirty(vd->vdev_top);
7328 }
34dc7c2f 7329
1c27024e 7330 for (int c = 0; c < vd->vdev_children; c++)
b128c09f
BB
7331 spa_async_remove(spa, vd->vdev_child[c]);
7332}
7333
7334static void
7335spa_async_probe(spa_t *spa, vdev_t *vd)
7336{
7337 if (vd->vdev_probe_wanted) {
428870ff 7338 vd->vdev_probe_wanted = B_FALSE;
b128c09f 7339 vdev_reopen(vd); /* vdev_open() does the actual probe */
34dc7c2f 7340 }
b128c09f 7341
1c27024e 7342 for (int c = 0; c < vd->vdev_children; c++)
b128c09f 7343 spa_async_probe(spa, vd->vdev_child[c]);
34dc7c2f
BB
7344}
7345
9babb374
BB
7346static void
7347spa_async_autoexpand(spa_t *spa, vdev_t *vd)
7348{
9babb374
BB
7349 if (!spa->spa_autoexpand)
7350 return;
7351
1c27024e 7352 for (int c = 0; c < vd->vdev_children; c++) {
9babb374
BB
7353 vdev_t *cvd = vd->vdev_child[c];
7354 spa_async_autoexpand(spa, cvd);
7355 }
7356
7357 if (!vd->vdev_ops->vdev_op_leaf || vd->vdev_physpath == NULL)
7358 return;
7359
12fa0466 7360 spa_event_notify(vd->vdev_spa, vd, NULL, ESC_ZFS_VDEV_AUTOEXPAND);
9babb374
BB
7361}
7362
34dc7c2f 7363static void
c25b8f99 7364spa_async_thread(void *arg)
34dc7c2f 7365{
c25b8f99 7366 spa_t *spa = (spa_t *)arg;
80a91e74 7367 dsl_pool_t *dp = spa->spa_dsl_pool;
867959b5 7368 int tasks;
34dc7c2f
BB
7369
7370 ASSERT(spa->spa_sync_on);
7371
7372 mutex_enter(&spa->spa_async_lock);
7373 tasks = spa->spa_async_tasks;
7374 spa->spa_async_tasks = 0;
7375 mutex_exit(&spa->spa_async_lock);
7376
7377 /*
7378 * See if the config needs to be updated.
7379 */
7380 if (tasks & SPA_ASYNC_CONFIG_UPDATE) {
428870ff 7381 uint64_t old_space, new_space;
9babb374 7382
34dc7c2f 7383 mutex_enter(&spa_namespace_lock);
428870ff 7384 old_space = metaslab_class_get_space(spa_normal_class(spa));
cc99f275
DB
7385 old_space += metaslab_class_get_space(spa_special_class(spa));
7386 old_space += metaslab_class_get_space(spa_dedup_class(spa));
7387
34dc7c2f 7388 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
cc99f275 7389
428870ff 7390 new_space = metaslab_class_get_space(spa_normal_class(spa));
cc99f275
DB
7391 new_space += metaslab_class_get_space(spa_special_class(spa));
7392 new_space += metaslab_class_get_space(spa_dedup_class(spa));
34dc7c2f 7393 mutex_exit(&spa_namespace_lock);
9babb374
BB
7394
7395 /*
7396 * If the pool grew as a result of the config update,
7397 * then log an internal history event.
7398 */
428870ff 7399 if (new_space != old_space) {
6f1ffb06 7400 spa_history_log_internal(spa, "vdev online", NULL,
45d1cae3 7401 "pool '%s' size: %llu(+%llu)",
428870ff 7402 spa_name(spa), new_space, new_space - old_space);
9babb374 7403 }
34dc7c2f
BB
7404 }
7405
7406 /*
7407 * See if any devices need to be marked REMOVED.
34dc7c2f 7408 */
b128c09f 7409 if (tasks & SPA_ASYNC_REMOVE) {
428870ff 7410 spa_vdev_state_enter(spa, SCL_NONE);
34dc7c2f 7411 spa_async_remove(spa, spa->spa_root_vdev);
867959b5 7412 for (int i = 0; i < spa->spa_l2cache.sav_count; i++)
b128c09f 7413 spa_async_remove(spa, spa->spa_l2cache.sav_vdevs[i]);
867959b5 7414 for (int i = 0; i < spa->spa_spares.sav_count; i++)
b128c09f
BB
7415 spa_async_remove(spa, spa->spa_spares.sav_vdevs[i]);
7416 (void) spa_vdev_state_exit(spa, NULL, 0);
34dc7c2f
BB
7417 }
7418
9babb374
BB
7419 if ((tasks & SPA_ASYNC_AUTOEXPAND) && !spa_suspended(spa)) {
7420 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7421 spa_async_autoexpand(spa, spa->spa_root_vdev);
7422 spa_config_exit(spa, SCL_CONFIG, FTAG);
7423 }
7424
34dc7c2f 7425 /*
b128c09f 7426 * See if any devices need to be probed.
34dc7c2f 7427 */
b128c09f 7428 if (tasks & SPA_ASYNC_PROBE) {
428870ff 7429 spa_vdev_state_enter(spa, SCL_NONE);
b128c09f
BB
7430 spa_async_probe(spa, spa->spa_root_vdev);
7431 (void) spa_vdev_state_exit(spa, NULL, 0);
7432 }
34dc7c2f
BB
7433
7434 /*
b128c09f 7435 * If any devices are done replacing, detach them.
34dc7c2f 7436 */
b128c09f
BB
7437 if (tasks & SPA_ASYNC_RESILVER_DONE)
7438 spa_vdev_resilver_done(spa);
34dc7c2f
BB
7439
7440 /*
7441 * Kick off a resilver.
7442 */
80a91e74
TC
7443 if (tasks & SPA_ASYNC_RESILVER &&
7444 (!dsl_scan_resilvering(dp) ||
7445 !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_RESILVER_DEFER)))
7446 dsl_resilver_restart(dp, 0);
34dc7c2f 7447
619f0976
GW
7448 if (tasks & SPA_ASYNC_INITIALIZE_RESTART) {
7449 mutex_enter(&spa_namespace_lock);
7450 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7451 vdev_initialize_restart(spa->spa_root_vdev);
7452 spa_config_exit(spa, SCL_CONFIG, FTAG);
7453 mutex_exit(&spa_namespace_lock);
7454 }
7455
1b939560
BB
7456 if (tasks & SPA_ASYNC_TRIM_RESTART) {
7457 mutex_enter(&spa_namespace_lock);
7458 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7459 vdev_trim_restart(spa->spa_root_vdev);
7460 spa_config_exit(spa, SCL_CONFIG, FTAG);
7461 mutex_exit(&spa_namespace_lock);
7462 }
7463
7464 if (tasks & SPA_ASYNC_AUTOTRIM_RESTART) {
7465 mutex_enter(&spa_namespace_lock);
7466 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7467 vdev_autotrim_restart(spa);
7468 spa_config_exit(spa, SCL_CONFIG, FTAG);
7469 mutex_exit(&spa_namespace_lock);
7470 }
7471
34dc7c2f
BB
7472 /*
7473 * Let the world know that we're done.
7474 */
7475 mutex_enter(&spa->spa_async_lock);
7476 spa->spa_async_thread = NULL;
7477 cv_broadcast(&spa->spa_async_cv);
7478 mutex_exit(&spa->spa_async_lock);
7479 thread_exit();
7480}
7481
7482void
7483spa_async_suspend(spa_t *spa)
7484{
7485 mutex_enter(&spa->spa_async_lock);
7486 spa->spa_async_suspended++;
9d5b5245 7487 while (spa->spa_async_thread != NULL)
34dc7c2f
BB
7488 cv_wait(&spa->spa_async_cv, &spa->spa_async_lock);
7489 mutex_exit(&spa->spa_async_lock);
a1d477c2
MA
7490
7491 spa_vdev_remove_suspend(spa);
9d5b5245
SD
7492
7493 zthr_t *condense_thread = spa->spa_condense_zthr;
61c3391a
SD
7494 if (condense_thread != NULL)
7495 zthr_cancel(condense_thread);
d2734cce
SD
7496
7497 zthr_t *discard_thread = spa->spa_checkpoint_discard_zthr;
61c3391a
SD
7498 if (discard_thread != NULL)
7499 zthr_cancel(discard_thread);
34dc7c2f
BB
7500}
7501
7502void
7503spa_async_resume(spa_t *spa)
7504{
7505 mutex_enter(&spa->spa_async_lock);
7506 ASSERT(spa->spa_async_suspended != 0);
7507 spa->spa_async_suspended--;
7508 mutex_exit(&spa->spa_async_lock);
a1d477c2 7509 spa_restart_removal(spa);
9d5b5245
SD
7510
7511 zthr_t *condense_thread = spa->spa_condense_zthr;
61c3391a 7512 if (condense_thread != NULL)
9d5b5245 7513 zthr_resume(condense_thread);
d2734cce
SD
7514
7515 zthr_t *discard_thread = spa->spa_checkpoint_discard_zthr;
61c3391a 7516 if (discard_thread != NULL)
d2734cce 7517 zthr_resume(discard_thread);
34dc7c2f
BB
7518}
7519
e6cfd633
WA
7520static boolean_t
7521spa_async_tasks_pending(spa_t *spa)
7522{
7523 uint_t non_config_tasks;
7524 uint_t config_task;
7525 boolean_t config_task_suspended;
7526
7527 non_config_tasks = spa->spa_async_tasks & ~SPA_ASYNC_CONFIG_UPDATE;
7528 config_task = spa->spa_async_tasks & SPA_ASYNC_CONFIG_UPDATE;
7529 if (spa->spa_ccw_fail_time == 0) {
7530 config_task_suspended = B_FALSE;
7531 } else {
7532 config_task_suspended =
7533 (gethrtime() - spa->spa_ccw_fail_time) <
05852b34 7534 ((hrtime_t)zfs_ccw_retry_interval * NANOSEC);
e6cfd633
WA
7535 }
7536
7537 return (non_config_tasks || (config_task && !config_task_suspended));
7538}
7539
34dc7c2f
BB
7540static void
7541spa_async_dispatch(spa_t *spa)
7542{
7543 mutex_enter(&spa->spa_async_lock);
e6cfd633
WA
7544 if (spa_async_tasks_pending(spa) &&
7545 !spa->spa_async_suspended &&
34dc7c2f 7546 spa->spa_async_thread == NULL &&
e6cfd633 7547 rootdir != NULL)
34dc7c2f
BB
7548 spa->spa_async_thread = thread_create(NULL, 0,
7549 spa_async_thread, spa, 0, &p0, TS_RUN, maxclsyspri);
7550 mutex_exit(&spa->spa_async_lock);
7551}
7552
7553void
7554spa_async_request(spa_t *spa, int task)
7555{
428870ff 7556 zfs_dbgmsg("spa=%s async request task=%u", spa->spa_name, task);
34dc7c2f
BB
7557 mutex_enter(&spa->spa_async_lock);
7558 spa->spa_async_tasks |= task;
7559 mutex_exit(&spa->spa_async_lock);
7560}
7561
7562/*
7563 * ==========================================================================
7564 * SPA syncing routines
7565 * ==========================================================================
7566 */
7567
428870ff
BB
7568static int
7569bpobj_enqueue_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
34dc7c2f 7570{
428870ff
BB
7571 bpobj_t *bpo = arg;
7572 bpobj_enqueue(bpo, bp, tx);
7573 return (0);
7574}
34dc7c2f 7575
428870ff
BB
7576static int
7577spa_free_sync_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
7578{
7579 zio_t *zio = arg;
34dc7c2f 7580
428870ff
BB
7581 zio_nowait(zio_free_sync(zio, zio->io_spa, dmu_tx_get_txg(tx), bp,
7582 zio->io_flags));
7583 return (0);
34dc7c2f
BB
7584}
7585
e8b96c60
MA
7586/*
7587 * Note: this simple function is not inlined to make it easier to dtrace the
7588 * amount of time spent syncing frees.
7589 */
7590static void
7591spa_sync_frees(spa_t *spa, bplist_t *bpl, dmu_tx_t *tx)
7592{
7593 zio_t *zio = zio_root(spa, NULL, NULL, 0);
7594 bplist_iterate(bpl, spa_free_sync_cb, zio, tx);
7595 VERIFY(zio_wait(zio) == 0);
7596}
7597
7598/*
7599 * Note: this simple function is not inlined to make it easier to dtrace the
7600 * amount of time spent syncing deferred frees.
7601 */
7602static void
7603spa_sync_deferred_frees(spa_t *spa, dmu_tx_t *tx)
7604{
8dc2197b
SD
7605 if (spa_sync_pass(spa) != 1)
7606 return;
7607
e8b96c60
MA
7608 zio_t *zio = zio_root(spa, NULL, NULL, 0);
7609 VERIFY3U(bpobj_iterate(&spa->spa_deferred_bpobj,
7610 spa_free_sync_cb, zio, tx), ==, 0);
7611 VERIFY0(zio_wait(zio));
7612}
7613
34dc7c2f
BB
7614static void
7615spa_sync_nvlist(spa_t *spa, uint64_t obj, nvlist_t *nv, dmu_tx_t *tx)
7616{
7617 char *packed = NULL;
b128c09f 7618 size_t bufsize;
34dc7c2f
BB
7619 size_t nvsize = 0;
7620 dmu_buf_t *db;
7621
7622 VERIFY(nvlist_size(nv, &nvsize, NV_ENCODE_XDR) == 0);
7623
b128c09f
BB
7624 /*
7625 * Write full (SPA_CONFIG_BLOCKSIZE) blocks of configuration
b0bc7a84 7626 * information. This avoids the dmu_buf_will_dirty() path and
b128c09f
BB
7627 * saves us a pre-read to get data we don't actually care about.
7628 */
9ae529ec 7629 bufsize = P2ROUNDUP((uint64_t)nvsize, SPA_CONFIG_BLOCKSIZE);
79c76d5b 7630 packed = vmem_alloc(bufsize, KM_SLEEP);
34dc7c2f
BB
7631
7632 VERIFY(nvlist_pack(nv, &packed, &nvsize, NV_ENCODE_XDR,
79c76d5b 7633 KM_SLEEP) == 0);
b128c09f 7634 bzero(packed + nvsize, bufsize - nvsize);
34dc7c2f 7635
b128c09f 7636 dmu_write(spa->spa_meta_objset, obj, 0, bufsize, packed, tx);
34dc7c2f 7637
00b46022 7638 vmem_free(packed, bufsize);
34dc7c2f
BB
7639
7640 VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
7641 dmu_buf_will_dirty(db, tx);
7642 *(uint64_t *)db->db_data = nvsize;
7643 dmu_buf_rele(db, FTAG);
7644}
7645
7646static void
7647spa_sync_aux_dev(spa_t *spa, spa_aux_vdev_t *sav, dmu_tx_t *tx,
7648 const char *config, const char *entry)
7649{
7650 nvlist_t *nvroot;
7651 nvlist_t **list;
7652 int i;
7653
7654 if (!sav->sav_sync)
7655 return;
7656
7657 /*
7658 * Update the MOS nvlist describing the list of available devices.
7659 * spa_validate_aux() will have already made sure this nvlist is
7660 * valid and the vdevs are labeled appropriately.
7661 */
7662 if (sav->sav_object == 0) {
7663 sav->sav_object = dmu_object_alloc(spa->spa_meta_objset,
7664 DMU_OT_PACKED_NVLIST, 1 << 14, DMU_OT_PACKED_NVLIST_SIZE,
7665 sizeof (uint64_t), tx);
7666 VERIFY(zap_update(spa->spa_meta_objset,
7667 DMU_POOL_DIRECTORY_OBJECT, entry, sizeof (uint64_t), 1,
7668 &sav->sav_object, tx) == 0);
7669 }
7670
79c76d5b 7671 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
34dc7c2f
BB
7672 if (sav->sav_count == 0) {
7673 VERIFY(nvlist_add_nvlist_array(nvroot, config, NULL, 0) == 0);
7674 } else {
79c76d5b 7675 list = kmem_alloc(sav->sav_count*sizeof (void *), KM_SLEEP);
34dc7c2f
BB
7676 for (i = 0; i < sav->sav_count; i++)
7677 list[i] = vdev_config_generate(spa, sav->sav_vdevs[i],
428870ff 7678 B_FALSE, VDEV_CONFIG_L2CACHE);
34dc7c2f
BB
7679 VERIFY(nvlist_add_nvlist_array(nvroot, config, list,
7680 sav->sav_count) == 0);
7681 for (i = 0; i < sav->sav_count; i++)
7682 nvlist_free(list[i]);
7683 kmem_free(list, sav->sav_count * sizeof (void *));
7684 }
7685
7686 spa_sync_nvlist(spa, sav->sav_object, nvroot, tx);
7687 nvlist_free(nvroot);
7688
7689 sav->sav_sync = B_FALSE;
7690}
7691
e0ab3ab5
JS
7692/*
7693 * Rebuild spa's all-vdev ZAP from the vdev ZAPs indicated in each vdev_t.
7694 * The all-vdev ZAP must be empty.
7695 */
7696static void
7697spa_avz_build(vdev_t *vd, uint64_t avz, dmu_tx_t *tx)
7698{
7699 spa_t *spa = vd->vdev_spa;
e0ab3ab5
JS
7700
7701 if (vd->vdev_top_zap != 0) {
7702 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
7703 vd->vdev_top_zap, tx));
7704 }
7705 if (vd->vdev_leaf_zap != 0) {
7706 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
7707 vd->vdev_leaf_zap, tx));
7708 }
1c27024e 7709 for (uint64_t i = 0; i < vd->vdev_children; i++) {
e0ab3ab5
JS
7710 spa_avz_build(vd->vdev_child[i], avz, tx);
7711 }
7712}
7713
34dc7c2f
BB
7714static void
7715spa_sync_config_object(spa_t *spa, dmu_tx_t *tx)
7716{
7717 nvlist_t *config;
7718
e0ab3ab5
JS
7719 /*
7720 * If the pool is being imported from a pre-per-vdev-ZAP version of ZFS,
7721 * its config may not be dirty but we still need to build per-vdev ZAPs.
7722 * Similarly, if the pool is being assembled (e.g. after a split), we
7723 * need to rebuild the AVZ although the config may not be dirty.
7724 */
7725 if (list_is_empty(&spa->spa_config_dirty_list) &&
7726 spa->spa_avz_action == AVZ_ACTION_NONE)
34dc7c2f
BB
7727 return;
7728
b128c09f
BB
7729 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7730
e0ab3ab5 7731 ASSERT(spa->spa_avz_action == AVZ_ACTION_NONE ||
38640550 7732 spa->spa_avz_action == AVZ_ACTION_INITIALIZE ||
e0ab3ab5
JS
7733 spa->spa_all_vdev_zaps != 0);
7734
7735 if (spa->spa_avz_action == AVZ_ACTION_REBUILD) {
e0ab3ab5
JS
7736 /* Make and build the new AVZ */
7737 uint64_t new_avz = zap_create(spa->spa_meta_objset,
7738 DMU_OTN_ZAP_METADATA, DMU_OT_NONE, 0, tx);
7739 spa_avz_build(spa->spa_root_vdev, new_avz, tx);
7740
7741 /* Diff old AVZ with new one */
1c27024e
DB
7742 zap_cursor_t zc;
7743 zap_attribute_t za;
7744
e0ab3ab5
JS
7745 for (zap_cursor_init(&zc, spa->spa_meta_objset,
7746 spa->spa_all_vdev_zaps);
7747 zap_cursor_retrieve(&zc, &za) == 0;
7748 zap_cursor_advance(&zc)) {
7749 uint64_t vdzap = za.za_first_integer;
7750 if (zap_lookup_int(spa->spa_meta_objset, new_avz,
7751 vdzap) == ENOENT) {
7752 /*
7753 * ZAP is listed in old AVZ but not in new one;
7754 * destroy it
7755 */
7756 VERIFY0(zap_destroy(spa->spa_meta_objset, vdzap,
7757 tx));
7758 }
7759 }
7760
7761 zap_cursor_fini(&zc);
7762
7763 /* Destroy the old AVZ */
7764 VERIFY0(zap_destroy(spa->spa_meta_objset,
7765 spa->spa_all_vdev_zaps, tx));
7766
7767 /* Replace the old AVZ in the dir obj with the new one */
7768 VERIFY0(zap_update(spa->spa_meta_objset,
7769 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP,
7770 sizeof (new_avz), 1, &new_avz, tx));
7771
7772 spa->spa_all_vdev_zaps = new_avz;
7773 } else if (spa->spa_avz_action == AVZ_ACTION_DESTROY) {
7774 zap_cursor_t zc;
7775 zap_attribute_t za;
7776
7777 /* Walk through the AVZ and destroy all listed ZAPs */
7778 for (zap_cursor_init(&zc, spa->spa_meta_objset,
7779 spa->spa_all_vdev_zaps);
7780 zap_cursor_retrieve(&zc, &za) == 0;
7781 zap_cursor_advance(&zc)) {
7782 uint64_t zap = za.za_first_integer;
7783 VERIFY0(zap_destroy(spa->spa_meta_objset, zap, tx));
7784 }
7785
7786 zap_cursor_fini(&zc);
7787
7788 /* Destroy and unlink the AVZ itself */
7789 VERIFY0(zap_destroy(spa->spa_meta_objset,
7790 spa->spa_all_vdev_zaps, tx));
7791 VERIFY0(zap_remove(spa->spa_meta_objset,
7792 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP, tx));
7793 spa->spa_all_vdev_zaps = 0;
7794 }
7795
7796 if (spa->spa_all_vdev_zaps == 0) {
7797 spa->spa_all_vdev_zaps = zap_create_link(spa->spa_meta_objset,
7798 DMU_OTN_ZAP_METADATA, DMU_POOL_DIRECTORY_OBJECT,
7799 DMU_POOL_VDEV_ZAP_MAP, tx);
7800 }
7801 spa->spa_avz_action = AVZ_ACTION_NONE;
7802
7803 /* Create ZAPs for vdevs that don't have them. */
7804 vdev_construct_zaps(spa->spa_root_vdev, tx);
7805
b128c09f
BB
7806 config = spa_config_generate(spa, spa->spa_root_vdev,
7807 dmu_tx_get_txg(tx), B_FALSE);
7808
ea0b2538
GW
7809 /*
7810 * If we're upgrading the spa version then make sure that
7811 * the config object gets updated with the correct version.
7812 */
7813 if (spa->spa_ubsync.ub_version < spa->spa_uberblock.ub_version)
7814 fnvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
7815 spa->spa_uberblock.ub_version);
7816
b128c09f 7817 spa_config_exit(spa, SCL_STATE, FTAG);
34dc7c2f 7818
8a5fc748 7819 nvlist_free(spa->spa_config_syncing);
34dc7c2f
BB
7820 spa->spa_config_syncing = config;
7821
7822 spa_sync_nvlist(spa, spa->spa_config_object, config, tx);
7823}
7824
9ae529ec 7825static void
13fe0198 7826spa_sync_version(void *arg, dmu_tx_t *tx)
9ae529ec 7827{
13fe0198
MA
7828 uint64_t *versionp = arg;
7829 uint64_t version = *versionp;
7830 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
9ae529ec
CS
7831
7832 /*
7833 * Setting the version is special cased when first creating the pool.
7834 */
7835 ASSERT(tx->tx_txg != TXG_INITIAL);
7836
8dca0a9a 7837 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
9ae529ec
CS
7838 ASSERT(version >= spa_version(spa));
7839
7840 spa->spa_uberblock.ub_version = version;
7841 vdev_config_dirty(spa->spa_root_vdev);
6f1ffb06 7842 spa_history_log_internal(spa, "set", tx, "version=%lld", version);
9ae529ec
CS
7843}
7844
34dc7c2f
BB
7845/*
7846 * Set zpool properties.
7847 */
7848static void
13fe0198 7849spa_sync_props(void *arg, dmu_tx_t *tx)
34dc7c2f 7850{
13fe0198
MA
7851 nvlist_t *nvp = arg;
7852 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
34dc7c2f 7853 objset_t *mos = spa->spa_meta_objset;
9ae529ec 7854 nvpair_t *elem = NULL;
b128c09f
BB
7855
7856 mutex_enter(&spa->spa_props_lock);
34dc7c2f 7857
34dc7c2f 7858 while ((elem = nvlist_next_nvpair(nvp, elem))) {
9ae529ec
CS
7859 uint64_t intval;
7860 char *strval, *fname;
7861 zpool_prop_t prop;
7862 const char *propname;
7863 zprop_type_t proptype;
fa86b5db 7864 spa_feature_t fid;
9ae529ec 7865
31864e3d
BB
7866 switch (prop = zpool_name_to_prop(nvpair_name(elem))) {
7867 case ZPOOL_PROP_INVAL:
9ae529ec
CS
7868 /*
7869 * We checked this earlier in spa_prop_validate().
7870 */
7871 ASSERT(zpool_prop_feature(nvpair_name(elem)));
7872
7873 fname = strchr(nvpair_name(elem), '@') + 1;
fa86b5db 7874 VERIFY0(zfeature_lookup_name(fname, &fid));
9ae529ec 7875
fa86b5db 7876 spa_feature_enable(spa, fid, tx);
6f1ffb06
MA
7877 spa_history_log_internal(spa, "set", tx,
7878 "%s=enabled", nvpair_name(elem));
9ae529ec
CS
7879 break;
7880
34dc7c2f 7881 case ZPOOL_PROP_VERSION:
93cf2076 7882 intval = fnvpair_value_uint64(elem);
34dc7c2f 7883 /*
4e33ba4c 7884 * The version is synced separately before other
9ae529ec 7885 * properties and should be correct by now.
34dc7c2f 7886 */
9ae529ec 7887 ASSERT3U(spa_version(spa), >=, intval);
34dc7c2f
BB
7888 break;
7889
7890 case ZPOOL_PROP_ALTROOT:
7891 /*
7892 * 'altroot' is a non-persistent property. It should
7893 * have been set temporarily at creation or import time.
7894 */
7895 ASSERT(spa->spa_root != NULL);
7896 break;
7897
572e2857 7898 case ZPOOL_PROP_READONLY:
34dc7c2f
BB
7899 case ZPOOL_PROP_CACHEFILE:
7900 /*
572e2857
BB
7901 * 'readonly' and 'cachefile' are also non-persisitent
7902 * properties.
34dc7c2f 7903 */
34dc7c2f 7904 break;
d96eb2b1 7905 case ZPOOL_PROP_COMMENT:
93cf2076 7906 strval = fnvpair_value_string(elem);
d96eb2b1
DM
7907 if (spa->spa_comment != NULL)
7908 spa_strfree(spa->spa_comment);
7909 spa->spa_comment = spa_strdup(strval);
7910 /*
7911 * We need to dirty the configuration on all the vdevs
7912 * so that their labels get updated. It's unnecessary
7913 * to do this for pool creation since the vdev's
4e33ba4c 7914 * configuration has already been dirtied.
d96eb2b1
DM
7915 */
7916 if (tx->tx_txg != TXG_INITIAL)
7917 vdev_config_dirty(spa->spa_root_vdev);
6f1ffb06
MA
7918 spa_history_log_internal(spa, "set", tx,
7919 "%s=%s", nvpair_name(elem), strval);
d96eb2b1 7920 break;
34dc7c2f
BB
7921 default:
7922 /*
7923 * Set pool property values in the poolprops mos object.
7924 */
34dc7c2f 7925 if (spa->spa_pool_props_object == 0) {
9ae529ec
CS
7926 spa->spa_pool_props_object =
7927 zap_create_link(mos, DMU_OT_POOL_PROPS,
34dc7c2f 7928 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_PROPS,
9ae529ec 7929 tx);
34dc7c2f 7930 }
34dc7c2f
BB
7931
7932 /* normalize the property name */
7933 propname = zpool_prop_to_name(prop);
7934 proptype = zpool_prop_get_type(prop);
7935
7936 if (nvpair_type(elem) == DATA_TYPE_STRING) {
7937 ASSERT(proptype == PROP_TYPE_STRING);
93cf2076
GW
7938 strval = fnvpair_value_string(elem);
7939 VERIFY0(zap_update(mos,
34dc7c2f 7940 spa->spa_pool_props_object, propname,
93cf2076 7941 1, strlen(strval) + 1, strval, tx));
6f1ffb06
MA
7942 spa_history_log_internal(spa, "set", tx,
7943 "%s=%s", nvpair_name(elem), strval);
34dc7c2f 7944 } else if (nvpair_type(elem) == DATA_TYPE_UINT64) {
93cf2076 7945 intval = fnvpair_value_uint64(elem);
34dc7c2f
BB
7946
7947 if (proptype == PROP_TYPE_INDEX) {
7948 const char *unused;
93cf2076
GW
7949 VERIFY0(zpool_prop_index_to_string(
7950 prop, intval, &unused));
34dc7c2f 7951 }
93cf2076 7952 VERIFY0(zap_update(mos,
34dc7c2f 7953 spa->spa_pool_props_object, propname,
93cf2076 7954 8, 1, &intval, tx));
6f1ffb06
MA
7955 spa_history_log_internal(spa, "set", tx,
7956 "%s=%lld", nvpair_name(elem), intval);
34dc7c2f
BB
7957 } else {
7958 ASSERT(0); /* not allowed */
7959 }
7960
7961 switch (prop) {
7962 case ZPOOL_PROP_DELEGATION:
7963 spa->spa_delegation = intval;
7964 break;
7965 case ZPOOL_PROP_BOOTFS:
7966 spa->spa_bootfs = intval;
7967 break;
7968 case ZPOOL_PROP_FAILUREMODE:
7969 spa->spa_failmode = intval;
7970 break;
1b939560
BB
7971 case ZPOOL_PROP_AUTOTRIM:
7972 spa->spa_autotrim = intval;
7973 spa_async_request(spa,
7974 SPA_ASYNC_AUTOTRIM_RESTART);
7975 break;
9babb374
BB
7976 case ZPOOL_PROP_AUTOEXPAND:
7977 spa->spa_autoexpand = intval;
428870ff
BB
7978 if (tx->tx_txg != TXG_INITIAL)
7979 spa_async_request(spa,
7980 SPA_ASYNC_AUTOEXPAND);
7981 break;
379ca9cf
OF
7982 case ZPOOL_PROP_MULTIHOST:
7983 spa->spa_multihost = intval;
7984 break;
428870ff
BB
7985 case ZPOOL_PROP_DEDUPDITTO:
7986 spa->spa_dedup_ditto = intval;
9babb374 7987 break;
34dc7c2f
BB
7988 default:
7989 break;
7990 }
7991 }
7992
34dc7c2f 7993 }
b128c09f
BB
7994
7995 mutex_exit(&spa->spa_props_lock);
34dc7c2f
BB
7996}
7997
428870ff
BB
7998/*
7999 * Perform one-time upgrade on-disk changes. spa_version() does not
8000 * reflect the new version this txg, so there must be no changes this
8001 * txg to anything that the upgrade code depends on after it executes.
8002 * Therefore this must be called after dsl_pool_sync() does the sync
8003 * tasks.
8004 */
8005static void
8006spa_sync_upgrades(spa_t *spa, dmu_tx_t *tx)
8007{
8dc2197b
SD
8008 if (spa_sync_pass(spa) != 1)
8009 return;
428870ff 8010
8dc2197b 8011 dsl_pool_t *dp = spa->spa_dsl_pool;
13fe0198
MA
8012 rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
8013
428870ff
BB
8014 if (spa->spa_ubsync.ub_version < SPA_VERSION_ORIGIN &&
8015 spa->spa_uberblock.ub_version >= SPA_VERSION_ORIGIN) {
8016 dsl_pool_create_origin(dp, tx);
8017
8018 /* Keeping the origin open increases spa_minref */
8019 spa->spa_minref += 3;
8020 }
8021
8022 if (spa->spa_ubsync.ub_version < SPA_VERSION_NEXT_CLONES &&
8023 spa->spa_uberblock.ub_version >= SPA_VERSION_NEXT_CLONES) {
8024 dsl_pool_upgrade_clones(dp, tx);
8025 }
8026
8027 if (spa->spa_ubsync.ub_version < SPA_VERSION_DIR_CLONES &&
8028 spa->spa_uberblock.ub_version >= SPA_VERSION_DIR_CLONES) {
8029 dsl_pool_upgrade_dir_clones(dp, tx);
8030
8031 /* Keeping the freedir open increases spa_minref */
8032 spa->spa_minref += 3;
8033 }
9ae529ec
CS
8034
8035 if (spa->spa_ubsync.ub_version < SPA_VERSION_FEATURES &&
8036 spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
8037 spa_feature_create_zap_objects(spa, tx);
8038 }
62bdd5eb
DL
8039
8040 /*
8041 * LZ4_COMPRESS feature's behaviour was changed to activate_on_enable
8042 * when possibility to use lz4 compression for metadata was added
8043 * Old pools that have this feature enabled must be upgraded to have
8044 * this feature active
8045 */
8046 if (spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
8047 boolean_t lz4_en = spa_feature_is_enabled(spa,
8048 SPA_FEATURE_LZ4_COMPRESS);
8049 boolean_t lz4_ac = spa_feature_is_active(spa,
8050 SPA_FEATURE_LZ4_COMPRESS);
8051
8052 if (lz4_en && !lz4_ac)
8053 spa_feature_incr(spa, SPA_FEATURE_LZ4_COMPRESS, tx);
8054 }
3c67d83a
TH
8055
8056 /*
8057 * If we haven't written the salt, do so now. Note that the
8058 * feature may not be activated yet, but that's fine since
8059 * the presence of this ZAP entry is backwards compatible.
8060 */
8061 if (zap_contains(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
8062 DMU_POOL_CHECKSUM_SALT) == ENOENT) {
8063 VERIFY0(zap_add(spa->spa_meta_objset,
8064 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CHECKSUM_SALT, 1,
8065 sizeof (spa->spa_cksum_salt.zcs_bytes),
8066 spa->spa_cksum_salt.zcs_bytes, tx));
8067 }
8068
13fe0198 8069 rrw_exit(&dp->dp_config_rwlock, FTAG);
428870ff
BB
8070}
8071
a1d477c2
MA
8072static void
8073vdev_indirect_state_sync_verify(vdev_t *vd)
8074{
8075 ASSERTV(vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping);
8076 ASSERTV(vdev_indirect_births_t *vib = vd->vdev_indirect_births);
8077
8078 if (vd->vdev_ops == &vdev_indirect_ops) {
8079 ASSERT(vim != NULL);
8080 ASSERT(vib != NULL);
8081 }
8082
27f80e85
BB
8083 uint64_t obsolete_sm_object = 0;
8084 ASSERT0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
8085 if (obsolete_sm_object != 0) {
a1d477c2
MA
8086 ASSERT(vd->vdev_obsolete_sm != NULL);
8087 ASSERT(vd->vdev_removing ||
8088 vd->vdev_ops == &vdev_indirect_ops);
8089 ASSERT(vdev_indirect_mapping_num_entries(vim) > 0);
8090 ASSERT(vdev_indirect_mapping_bytes_mapped(vim) > 0);
27f80e85 8091 ASSERT3U(obsolete_sm_object, ==,
a1d477c2
MA
8092 space_map_object(vd->vdev_obsolete_sm));
8093 ASSERT3U(vdev_indirect_mapping_bytes_mapped(vim), >=,
8094 space_map_allocated(vd->vdev_obsolete_sm));
8095 }
8096 ASSERT(vd->vdev_obsolete_segments != NULL);
8097
8098 /*
8099 * Since frees / remaps to an indirect vdev can only
8100 * happen in syncing context, the obsolete segments
8101 * tree must be empty when we start syncing.
8102 */
8103 ASSERT0(range_tree_space(vd->vdev_obsolete_segments));
8104}
8105
34dc7c2f 8106/*
8dc2197b
SD
8107 * Set the top-level vdev's max queue depth. Evaluate each top-level's
8108 * async write queue depth in case it changed. The max queue depth will
8109 * not change in the middle of syncing out this txg.
34dc7c2f 8110 */
8dc2197b
SD
8111static void
8112spa_sync_adjust_vdev_max_queue_depth(spa_t *spa)
34dc7c2f 8113{
8dc2197b
SD
8114 ASSERT(spa_writeable(spa));
8115
34dc7c2f 8116 vdev_t *rvd = spa->spa_root_vdev;
3dfb57a3
DB
8117 uint32_t max_queue_depth = zfs_vdev_async_write_max_active *
8118 zfs_vdev_queue_depth_pct / 100;
8dc2197b
SD
8119 metaslab_class_t *normal = spa_normal_class(spa);
8120 metaslab_class_t *special = spa_special_class(spa);
8121 metaslab_class_t *dedup = spa_dedup_class(spa);
34dc7c2f 8122
492f64e9 8123 uint64_t slots_per_allocator = 0;
1c27024e 8124 for (int c = 0; c < rvd->vdev_children; c++) {
3dfb57a3 8125 vdev_t *tvd = rvd->vdev_child[c];
cc99f275 8126
8dc2197b 8127 metaslab_group_t *mg = tvd->vdev_mg;
cc99f275
DB
8128 if (mg == NULL || !metaslab_group_initialized(mg))
8129 continue;
3dfb57a3 8130
8dc2197b 8131 metaslab_class_t *mc = mg->mg_class;
cc99f275 8132 if (mc != normal && mc != special && mc != dedup)
3dfb57a3
DB
8133 continue;
8134
8135 /*
8136 * It is safe to do a lock-free check here because only async
8137 * allocations look at mg_max_alloc_queue_depth, and async
8138 * allocations all happen from spa_sync().
8139 */
492f64e9 8140 for (int i = 0; i < spa->spa_alloc_count; i++)
424fd7c3
TS
8141 ASSERT0(zfs_refcount_count(
8142 &(mg->mg_alloc_queue_depth[i])));
3dfb57a3 8143 mg->mg_max_alloc_queue_depth = max_queue_depth;
492f64e9
PD
8144
8145 for (int i = 0; i < spa->spa_alloc_count; i++) {
8146 mg->mg_cur_max_alloc_queue_depth[i] =
8147 zfs_vdev_def_queue_depth;
8148 }
8149 slots_per_allocator += zfs_vdev_def_queue_depth;
3dfb57a3 8150 }
cc99f275 8151
492f64e9 8152 for (int i = 0; i < spa->spa_alloc_count; i++) {
424fd7c3
TS
8153 ASSERT0(zfs_refcount_count(&normal->mc_alloc_slots[i]));
8154 ASSERT0(zfs_refcount_count(&special->mc_alloc_slots[i]));
8155 ASSERT0(zfs_refcount_count(&dedup->mc_alloc_slots[i]));
cc99f275
DB
8156 normal->mc_alloc_max_slots[i] = slots_per_allocator;
8157 special->mc_alloc_max_slots[i] = slots_per_allocator;
8158 dedup->mc_alloc_max_slots[i] = slots_per_allocator;
8159 }
8160 normal->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
8161 special->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
8162 dedup->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
8dc2197b
SD
8163}
8164
8165static void
8166spa_sync_condense_indirect(spa_t *spa, dmu_tx_t *tx)
8167{
8168 ASSERT(spa_writeable(spa));
3dfb57a3 8169
8dc2197b 8170 vdev_t *rvd = spa->spa_root_vdev;
a1d477c2
MA
8171 for (int c = 0; c < rvd->vdev_children; c++) {
8172 vdev_t *vd = rvd->vdev_child[c];
8173 vdev_indirect_state_sync_verify(vd);
8174
8175 if (vdev_indirect_should_condense(vd)) {
8176 spa_condense_indirect_start_sync(vd, tx);
8177 break;
8178 }
8179 }
8dc2197b
SD
8180}
8181
8182static void
8183spa_sync_iterate_to_convergence(spa_t *spa, dmu_tx_t *tx)
8184{
8185 objset_t *mos = spa->spa_meta_objset;
8186 dsl_pool_t *dp = spa->spa_dsl_pool;
8187 uint64_t txg = tx->tx_txg;
8188 bplist_t *free_bpl = &spa->spa_free_bplist[txg & TXG_MASK];
a1d477c2 8189
34dc7c2f 8190 do {
428870ff 8191 int pass = ++spa->spa_sync_pass;
34dc7c2f
BB
8192
8193 spa_sync_config_object(spa, tx);
8194 spa_sync_aux_dev(spa, &spa->spa_spares, tx,
8195 ZPOOL_CONFIG_SPARES, DMU_POOL_SPARES);
8196 spa_sync_aux_dev(spa, &spa->spa_l2cache, tx,
8197 ZPOOL_CONFIG_L2CACHE, DMU_POOL_L2CACHE);
8198 spa_errlog_sync(spa, txg);
8199 dsl_pool_sync(dp, txg);
8200
55d85d5a 8201 if (pass < zfs_sync_pass_deferred_free) {
e8b96c60 8202 spa_sync_frees(spa, free_bpl, tx);
428870ff 8203 } else {
905edb40
MA
8204 /*
8205 * We can not defer frees in pass 1, because
8206 * we sync the deferred frees later in pass 1.
8207 */
8208 ASSERT3U(pass, >, 1);
428870ff 8209 bplist_iterate(free_bpl, bpobj_enqueue_cb,
e8b96c60 8210 &spa->spa_deferred_bpobj, tx);
34dc7c2f
BB
8211 }
8212
428870ff
BB
8213 ddt_sync(spa, txg);
8214 dsl_scan_sync(dp, tx);
8dc2197b
SD
8215 svr_sync(spa, tx);
8216 spa_sync_upgrades(spa, tx);
34dc7c2f 8217
8dc2197b 8218 vdev_t *vd = NULL;
a1d477c2
MA
8219 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, txg))
8220 != NULL)
428870ff
BB
8221 vdev_sync(vd, txg);
8222
8dc2197b
SD
8223 /*
8224 * Note: We need to check if the MOS is dirty because we could
8225 * have marked the MOS dirty without updating the uberblock
8226 * (e.g. if we have sync tasks but no dirty user data). We need
8227 * to check the uberblock's rootbp because it is updated if we
8228 * have synced out dirty data (though in this case the MOS will
8229 * most likely also be dirty due to second order effects, we
8230 * don't want to rely on that here).
8231 */
8232 if (pass == 1 &&
8233 spa->spa_uberblock.ub_rootbp.blk_birth < txg &&
8234 !dmu_objset_is_dirty(mos, txg)) {
905edb40 8235 /*
8dc2197b
SD
8236 * Nothing changed on the first pass, therefore this
8237 * TXG is a no-op. Avoid syncing deferred frees, so
8238 * that we can keep this TXG as a no-op.
905edb40 8239 */
8dc2197b
SD
8240 ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
8241 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
8242 ASSERT(txg_list_empty(&dp->dp_sync_tasks, txg));
8243 ASSERT(txg_list_empty(&dp->dp_early_sync_tasks, txg));
8244 break;
905edb40 8245 }
34dc7c2f 8246
8dc2197b 8247 spa_sync_deferred_frees(spa, tx);
428870ff 8248 } while (dmu_objset_is_dirty(mos, txg));
8dc2197b 8249}
34dc7c2f 8250
8dc2197b
SD
8251/*
8252 * Rewrite the vdev configuration (which includes the uberblock) to
8253 * commit the transaction group.
8254 *
8255 * If there are no dirty vdevs, we sync the uberblock to a few random
8256 * top-level vdevs that are known to be visible in the config cache
8257 * (see spa_vdev_add() for a complete description). If there *are* dirty
8258 * vdevs, sync the uberblock to all vdevs.
8259 */
8260static void
8261spa_sync_rewrite_vdev_config(spa_t *spa, dmu_tx_t *tx)
8262{
8263 vdev_t *rvd = spa->spa_root_vdev;
8264 uint64_t txg = tx->tx_txg;
a1d477c2 8265
b128c09f 8266 for (;;) {
8dc2197b
SD
8267 int error = 0;
8268
b128c09f
BB
8269 /*
8270 * We hold SCL_STATE to prevent vdev open/close/etc.
8271 * while we're attempting to write the vdev labels.
8272 */
8273 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8274
8275 if (list_is_empty(&spa->spa_config_dirty_list)) {
d2734cce 8276 vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
b128c09f
BB
8277 int svdcount = 0;
8278 int children = rvd->vdev_children;
8279 int c0 = spa_get_random(children);
b128c09f 8280
1c27024e 8281 for (int c = 0; c < children; c++) {
8dc2197b
SD
8282 vdev_t *vd =
8283 rvd->vdev_child[(c0 + c) % children];
d2734cce
SD
8284
8285 /* Stop when revisiting the first vdev */
8286 if (c > 0 && svd[0] == vd)
8287 break;
8288
8dc2197b
SD
8289 if (vd->vdev_ms_array == 0 ||
8290 vd->vdev_islog ||
a1d477c2 8291 !vdev_is_concrete(vd))
b128c09f 8292 continue;
d2734cce 8293
b128c09f 8294 svd[svdcount++] = vd;
6cb8e530 8295 if (svdcount == SPA_SYNC_MIN_VDEVS)
b128c09f
BB
8296 break;
8297 }
b6fcb792 8298 error = vdev_config_sync(svd, svdcount, txg);
b128c09f
BB
8299 } else {
8300 error = vdev_config_sync(rvd->vdev_child,
b6fcb792 8301 rvd->vdev_children, txg);
34dc7c2f 8302 }
34dc7c2f 8303
3bc7e0fb
GW
8304 if (error == 0)
8305 spa->spa_last_synced_guid = rvd->vdev_guid;
8306
b128c09f
BB
8307 spa_config_exit(spa, SCL_STATE, FTAG);
8308
8309 if (error == 0)
8310 break;
cec3a0a1 8311 zio_suspend(spa, NULL, ZIO_SUSPEND_IOERR);
b128c09f
BB
8312 zio_resume_wait(spa);
8313 }
8dc2197b
SD
8314}
8315
8316/*
8317 * Sync the specified transaction group. New blocks may be dirtied as
8318 * part of the process, so we iterate until it converges.
8319 */
8320void
8321spa_sync(spa_t *spa, uint64_t txg)
8322{
8323 vdev_t *vd = NULL;
8324
8325 VERIFY(spa_writeable(spa));
8326
8327 /*
8328 * Wait for i/os issued in open context that need to complete
8329 * before this txg syncs.
8330 */
8331 (void) zio_wait(spa->spa_txg_zio[txg & TXG_MASK]);
8332 spa->spa_txg_zio[txg & TXG_MASK] = zio_root(spa, NULL, NULL,
8333 ZIO_FLAG_CANFAIL);
8334
8335 /*
8336 * Lock out configuration changes.
8337 */
8338 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
8339
8340 spa->spa_syncing_txg = txg;
8341 spa->spa_sync_pass = 0;
8342
8343 for (int i = 0; i < spa->spa_alloc_count; i++) {
8344 mutex_enter(&spa->spa_alloc_locks[i]);
8345 VERIFY0(avl_numnodes(&spa->spa_alloc_trees[i]));
8346 mutex_exit(&spa->spa_alloc_locks[i]);
8347 }
8348
8349 /*
8350 * If there are any pending vdev state changes, convert them
8351 * into config changes that go out with this transaction group.
8352 */
8353 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8354 while (list_head(&spa->spa_state_dirty_list) != NULL) {
8355 /*
8356 * We need the write lock here because, for aux vdevs,
8357 * calling vdev_config_dirty() modifies sav_config.
8358 * This is ugly and will become unnecessary when we
8359 * eliminate the aux vdev wart by integrating all vdevs
8360 * into the root vdev tree.
8361 */
8362 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
8363 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_WRITER);
8364 while ((vd = list_head(&spa->spa_state_dirty_list)) != NULL) {
8365 vdev_state_clean(vd);
8366 vdev_config_dirty(vd);
8367 }
8368 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
8369 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
8370 }
8371 spa_config_exit(spa, SCL_STATE, FTAG);
8372
8373 dsl_pool_t *dp = spa->spa_dsl_pool;
8374 dmu_tx_t *tx = dmu_tx_create_assigned(dp, txg);
8375
8376 spa->spa_sync_starttime = gethrtime();
8377 taskq_cancel_id(system_delay_taskq, spa->spa_deadman_tqid);
8378 spa->spa_deadman_tqid = taskq_dispatch_delay(system_delay_taskq,
8379 spa_deadman, spa, TQ_SLEEP, ddi_get_lbolt() +
8380 NSEC_TO_TICK(spa->spa_deadman_synctime));
8381
8382 /*
8383 * If we are upgrading to SPA_VERSION_RAIDZ_DEFLATE this txg,
8384 * set spa_deflate if we have no raid-z vdevs.
8385 */
8386 if (spa->spa_ubsync.ub_version < SPA_VERSION_RAIDZ_DEFLATE &&
8387 spa->spa_uberblock.ub_version >= SPA_VERSION_RAIDZ_DEFLATE) {
8388 vdev_t *rvd = spa->spa_root_vdev;
8389
8390 int i;
8391 for (i = 0; i < rvd->vdev_children; i++) {
8392 vd = rvd->vdev_child[i];
8393 if (vd->vdev_deflate_ratio != SPA_MINBLOCKSIZE)
8394 break;
8395 }
8396 if (i == rvd->vdev_children) {
8397 spa->spa_deflate = TRUE;
8398 VERIFY0(zap_add(spa->spa_meta_objset,
8399 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
8400 sizeof (uint64_t), 1, &spa->spa_deflate, tx));
8401 }
8402 }
8403
8404 spa_sync_adjust_vdev_max_queue_depth(spa);
8405
8406 spa_sync_condense_indirect(spa, tx);
8407
8408 spa_sync_iterate_to_convergence(spa, tx);
8409
8410#ifdef ZFS_DEBUG
8411 if (!list_is_empty(&spa->spa_config_dirty_list)) {
8412 /*
8413 * Make sure that the number of ZAPs for all the vdevs matches
8414 * the number of ZAPs in the per-vdev ZAP list. This only gets
8415 * called if the config is dirty; otherwise there may be
8416 * outstanding AVZ operations that weren't completed in
8417 * spa_sync_config_object.
8418 */
8419 uint64_t all_vdev_zap_entry_count;
8420 ASSERT0(zap_count(spa->spa_meta_objset,
8421 spa->spa_all_vdev_zaps, &all_vdev_zap_entry_count));
8422 ASSERT3U(vdev_count_verify_zaps(spa->spa_root_vdev), ==,
8423 all_vdev_zap_entry_count);
8424 }
8425#endif
8426
8427 if (spa->spa_vdev_removal != NULL) {
8428 ASSERT0(spa->spa_vdev_removal->svr_bytes_done[txg & TXG_MASK]);
8429 }
8430
8431 spa_sync_rewrite_vdev_config(spa, tx);
34dc7c2f
BB
8432 dmu_tx_commit(tx);
8433
57ddcda1 8434 taskq_cancel_id(system_delay_taskq, spa->spa_deadman_tqid);
cc92e9d0
GW
8435 spa->spa_deadman_tqid = 0;
8436
34dc7c2f
BB
8437 /*
8438 * Clear the dirty config list.
8439 */
b128c09f 8440 while ((vd = list_head(&spa->spa_config_dirty_list)) != NULL)
34dc7c2f
BB
8441 vdev_config_clean(vd);
8442
8443 /*
8444 * Now that the new config has synced transactionally,
8445 * let it become visible to the config cache.
8446 */
8447 if (spa->spa_config_syncing != NULL) {
8448 spa_config_set(spa, spa->spa_config_syncing);
8449 spa->spa_config_txg = txg;
8450 spa->spa_config_syncing = NULL;
8451 }
8452
428870ff 8453 dsl_pool_sync_done(dp, txg);
34dc7c2f 8454
492f64e9
PD
8455 for (int i = 0; i < spa->spa_alloc_count; i++) {
8456 mutex_enter(&spa->spa_alloc_locks[i]);
8457 VERIFY0(avl_numnodes(&spa->spa_alloc_trees[i]));
8458 mutex_exit(&spa->spa_alloc_locks[i]);
8459 }
3dfb57a3 8460
34dc7c2f
BB
8461 /*
8462 * Update usable space statistics.
8463 */
619f0976
GW
8464 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)))
8465 != NULL)
34dc7c2f
BB
8466 vdev_sync_done(vd, txg);
8467
428870ff
BB
8468 spa_update_dspace(spa);
8469
34dc7c2f
BB
8470 /*
8471 * It had better be the case that we didn't dirty anything
8472 * since vdev_config_sync().
8473 */
8474 ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
8475 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
8476 ASSERT(txg_list_empty(&spa->spa_vdev_txg_list, txg));
428870ff 8477
d2734cce
SD
8478 while (zfs_pause_spa_sync)
8479 delay(1);
8480
428870ff 8481 spa->spa_sync_pass = 0;
34dc7c2f 8482
55922e73
GW
8483 /*
8484 * Update the last synced uberblock here. We want to do this at
8485 * the end of spa_sync() so that consumers of spa_last_synced_txg()
8486 * will be guaranteed that all the processing associated with
8487 * that txg has been completed.
8488 */
8489 spa->spa_ubsync = spa->spa_uberblock;
b128c09f 8490 spa_config_exit(spa, SCL_CONFIG, FTAG);
34dc7c2f 8491
428870ff
BB
8492 spa_handle_ignored_writes(spa);
8493
34dc7c2f
BB
8494 /*
8495 * If any async tasks have been requested, kick them off.
8496 */
8497 spa_async_dispatch(spa);
8498}
8499
8500/*
8501 * Sync all pools. We don't want to hold the namespace lock across these
8502 * operations, so we take a reference on the spa_t and drop the lock during the
8503 * sync.
8504 */
8505void
8506spa_sync_allpools(void)
8507{
8508 spa_t *spa = NULL;
8509 mutex_enter(&spa_namespace_lock);
8510 while ((spa = spa_next(spa)) != NULL) {
572e2857
BB
8511 if (spa_state(spa) != POOL_STATE_ACTIVE ||
8512 !spa_writeable(spa) || spa_suspended(spa))
34dc7c2f
BB
8513 continue;
8514 spa_open_ref(spa, FTAG);
8515 mutex_exit(&spa_namespace_lock);
8516 txg_wait_synced(spa_get_dsl(spa), 0);
8517 mutex_enter(&spa_namespace_lock);
8518 spa_close(spa, FTAG);
8519 }
8520 mutex_exit(&spa_namespace_lock);
8521}
8522
8523/*
8524 * ==========================================================================
8525 * Miscellaneous routines
8526 * ==========================================================================
8527 */
8528
8529/*
8530 * Remove all pools in the system.
8531 */
8532void
8533spa_evict_all(void)
8534{
8535 spa_t *spa;
8536
8537 /*
8538 * Remove all cached state. All pools should be closed now,
8539 * so every spa in the AVL tree should be unreferenced.
8540 */
8541 mutex_enter(&spa_namespace_lock);
8542 while ((spa = spa_next(NULL)) != NULL) {
8543 /*
8544 * Stop async tasks. The async thread may need to detach
8545 * a device that's been replaced, which requires grabbing
8546 * spa_namespace_lock, so we must drop it here.
8547 */
8548 spa_open_ref(spa, FTAG);
8549 mutex_exit(&spa_namespace_lock);
8550 spa_async_suspend(spa);
8551 mutex_enter(&spa_namespace_lock);
34dc7c2f
BB
8552 spa_close(spa, FTAG);
8553
8554 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
8555 spa_unload(spa);
8556 spa_deactivate(spa);
8557 }
8558 spa_remove(spa);
8559 }
8560 mutex_exit(&spa_namespace_lock);
8561}
8562
8563vdev_t *
9babb374 8564spa_lookup_by_guid(spa_t *spa, uint64_t guid, boolean_t aux)
34dc7c2f 8565{
b128c09f
BB
8566 vdev_t *vd;
8567 int i;
8568
8569 if ((vd = vdev_lookup_by_guid(spa->spa_root_vdev, guid)) != NULL)
8570 return (vd);
8571
9babb374 8572 if (aux) {
b128c09f
BB
8573 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
8574 vd = spa->spa_l2cache.sav_vdevs[i];
9babb374
BB
8575 if (vd->vdev_guid == guid)
8576 return (vd);
8577 }
8578
8579 for (i = 0; i < spa->spa_spares.sav_count; i++) {
8580 vd = spa->spa_spares.sav_vdevs[i];
b128c09f
BB
8581 if (vd->vdev_guid == guid)
8582 return (vd);
8583 }
8584 }
8585
8586 return (NULL);
34dc7c2f
BB
8587}
8588
8589void
8590spa_upgrade(spa_t *spa, uint64_t version)
8591{
572e2857
BB
8592 ASSERT(spa_writeable(spa));
8593
b128c09f 8594 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f
BB
8595
8596 /*
8597 * This should only be called for a non-faulted pool, and since a
8598 * future version would result in an unopenable pool, this shouldn't be
8599 * possible.
8600 */
8dca0a9a 8601 ASSERT(SPA_VERSION_IS_SUPPORTED(spa->spa_uberblock.ub_version));
9b67f605 8602 ASSERT3U(version, >=, spa->spa_uberblock.ub_version);
34dc7c2f
BB
8603
8604 spa->spa_uberblock.ub_version = version;
8605 vdev_config_dirty(spa->spa_root_vdev);
8606
b128c09f 8607 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
8608
8609 txg_wait_synced(spa_get_dsl(spa), 0);
8610}
8611
8612boolean_t
8613spa_has_spare(spa_t *spa, uint64_t guid)
8614{
8615 int i;
8616 uint64_t spareguid;
8617 spa_aux_vdev_t *sav = &spa->spa_spares;
8618
8619 for (i = 0; i < sav->sav_count; i++)
8620 if (sav->sav_vdevs[i]->vdev_guid == guid)
8621 return (B_TRUE);
8622
8623 for (i = 0; i < sav->sav_npending; i++) {
8624 if (nvlist_lookup_uint64(sav->sav_pending[i], ZPOOL_CONFIG_GUID,
8625 &spareguid) == 0 && spareguid == guid)
8626 return (B_TRUE);
8627 }
8628
8629 return (B_FALSE);
8630}
8631
b128c09f
BB
8632/*
8633 * Check if a pool has an active shared spare device.
8634 * Note: reference count of an active spare is 2, as a spare and as a replace
8635 */
8636static boolean_t
8637spa_has_active_shared_spare(spa_t *spa)
8638{
8639 int i, refcnt;
8640 uint64_t pool;
8641 spa_aux_vdev_t *sav = &spa->spa_spares;
8642
8643 for (i = 0; i < sav->sav_count; i++) {
8644 if (spa_spare_exists(sav->sav_vdevs[i]->vdev_guid, &pool,
8645 &refcnt) && pool != 0ULL && pool == spa_guid(spa) &&
8646 refcnt > 2)
8647 return (B_TRUE);
8648 }
8649
8650 return (B_FALSE);
8651}
8652
a1d477c2 8653sysevent_t *
12fa0466
DE
8654spa_event_create(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
8655{
8656 sysevent_t *ev = NULL;
8657#ifdef _KERNEL
8658 nvlist_t *resource;
8659
8660 resource = zfs_event_create(spa, vd, FM_SYSEVENT_CLASS, name, hist_nvl);
8661 if (resource) {
8662 ev = kmem_alloc(sizeof (sysevent_t), KM_SLEEP);
8663 ev->resource = resource;
8664 }
8665#endif
8666 return (ev);
8667}
8668
a1d477c2 8669void
12fa0466
DE
8670spa_event_post(sysevent_t *ev)
8671{
8672#ifdef _KERNEL
8673 if (ev) {
8674 zfs_zevent_post(ev->resource, NULL, zfs_zevent_post_cb);
8675 kmem_free(ev, sizeof (*ev));
8676 }
8677#endif
8678}
8679
34dc7c2f 8680/*
fb390aaf
HR
8681 * Post a zevent corresponding to the given sysevent. The 'name' must be one
8682 * of the event definitions in sys/sysevent/eventdefs.h. The payload will be
34dc7c2f
BB
8683 * filled in from the spa and (optionally) the vdev. This doesn't do anything
8684 * in the userland libzpool, as we don't want consumers to misinterpret ztest
8685 * or zdb as real changes.
8686 */
8687void
12fa0466 8688spa_event_notify(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
34dc7c2f 8689{
12fa0466 8690 spa_event_post(spa_event_create(spa, vd, hist_nvl, name));
34dc7c2f 8691}
c28b2279 8692
93ce2b4c 8693#if defined(_KERNEL)
c28b2279
BB
8694/* state manipulation functions */
8695EXPORT_SYMBOL(spa_open);
8696EXPORT_SYMBOL(spa_open_rewind);
8697EXPORT_SYMBOL(spa_get_stats);
8698EXPORT_SYMBOL(spa_create);
c28b2279
BB
8699EXPORT_SYMBOL(spa_import);
8700EXPORT_SYMBOL(spa_tryimport);
8701EXPORT_SYMBOL(spa_destroy);
8702EXPORT_SYMBOL(spa_export);
8703EXPORT_SYMBOL(spa_reset);
8704EXPORT_SYMBOL(spa_async_request);
8705EXPORT_SYMBOL(spa_async_suspend);
8706EXPORT_SYMBOL(spa_async_resume);
8707EXPORT_SYMBOL(spa_inject_addref);
8708EXPORT_SYMBOL(spa_inject_delref);
8709EXPORT_SYMBOL(spa_scan_stat_init);
8710EXPORT_SYMBOL(spa_scan_get_stats);
8711
8712/* device maniion */
8713EXPORT_SYMBOL(spa_vdev_add);
8714EXPORT_SYMBOL(spa_vdev_attach);
8715EXPORT_SYMBOL(spa_vdev_detach);
c28b2279
BB
8716EXPORT_SYMBOL(spa_vdev_setpath);
8717EXPORT_SYMBOL(spa_vdev_setfru);
8718EXPORT_SYMBOL(spa_vdev_split_mirror);
8719
8720/* spare statech is global across all pools) */
8721EXPORT_SYMBOL(spa_spare_add);
8722EXPORT_SYMBOL(spa_spare_remove);
8723EXPORT_SYMBOL(spa_spare_exists);
8724EXPORT_SYMBOL(spa_spare_activate);
8725
8726/* L2ARC statech is global across all pools) */
8727EXPORT_SYMBOL(spa_l2cache_add);
8728EXPORT_SYMBOL(spa_l2cache_remove);
8729EXPORT_SYMBOL(spa_l2cache_exists);
8730EXPORT_SYMBOL(spa_l2cache_activate);
8731EXPORT_SYMBOL(spa_l2cache_drop);
8732
8733/* scanning */
8734EXPORT_SYMBOL(spa_scan);
8735EXPORT_SYMBOL(spa_scan_stop);
8736
8737/* spa syncing */
8738EXPORT_SYMBOL(spa_sync); /* only for DMU use */
8739EXPORT_SYMBOL(spa_sync_allpools);
8740
8741/* properties */
8742EXPORT_SYMBOL(spa_prop_set);
8743EXPORT_SYMBOL(spa_prop_get);
8744EXPORT_SYMBOL(spa_prop_clear_bootfs);
8745
8746/* asynchronous event notification */
8747EXPORT_SYMBOL(spa_event_notify);
8748#endif
dea377c0 8749
93ce2b4c 8750#if defined(_KERNEL)
dea377c0
MA
8751module_param(spa_load_verify_maxinflight, int, 0644);
8752MODULE_PARM_DESC(spa_load_verify_maxinflight,
8753 "Max concurrent traversal I/Os while verifying pool during import -X");
8754
8755module_param(spa_load_verify_metadata, int, 0644);
8756MODULE_PARM_DESC(spa_load_verify_metadata,
8757 "Set to traverse metadata on pool import");
8758
8759module_param(spa_load_verify_data, int, 0644);
8760MODULE_PARM_DESC(spa_load_verify_data,
8761 "Set to traverse data on pool import");
dcb6bed1 8762
6cb8e530
PZ
8763module_param(spa_load_print_vdev_tree, int, 0644);
8764MODULE_PARM_DESC(spa_load_print_vdev_tree,
8765 "Print vdev tree to zfs_dbgmsg during pool import");
8766
02730c33 8767/* CSTYLED */
dcb6bed1
D
8768module_param(zio_taskq_batch_pct, uint, 0444);
8769MODULE_PARM_DESC(zio_taskq_batch_pct,
8770 "Percentage of CPUs to run an IO worker thread");
8771
6cb8e530
PZ
8772/* BEGIN CSTYLED */
8773module_param(zfs_max_missing_tvds, ulong, 0644);
8774MODULE_PARM_DESC(zfs_max_missing_tvds,
8775 "Allow importing pool with up to this number of missing top-level vdevs"
8776 " (in read-only mode)");
8777/* END CSTYLED */
8778
dea377c0 8779#endif