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