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