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