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