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