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