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