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