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