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