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