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