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