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