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