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