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