]> git.proxmox.com Git - mirror_zfs.git/blame - module/zfs/spa.c
OpenZFS 9290 - device removal reduces redundancy of mirrors
[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.
4747a7d3 24 * Copyright (c) 2011, 2017 by Delphix. All rights reserved.
fb390aaf 25 * Copyright (c) 2015, Nexenta Systems, Inc. All rights reserved.
62bdd5eb 26 * Copyright (c) 2013, 2014, Nexenta Systems, Inc. All rights reserved.
0c66c32d 27 * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
3c67d83a 28 * Copyright 2013 Saso Kiselkov. All rights reserved.
e550644f
BB
29 * Copyright (c) 2014 Integros [integros.com]
30 * Copyright 2016 Toomas Soome <tsoome@me.com>
a0bd735a 31 * Copyright (c) 2016 Actifio, Inc. All rights reserved.
0ea05c64 32 * Copyright (c) 2017 Datto Inc.
12fa0466 33 * Copyright 2017 Joyent, Inc.
a38718a6 34 */
34dc7c2f 35
34dc7c2f 36/*
e49f1e20
WA
37 * SPA: Storage Pool Allocator
38 *
34dc7c2f
BB
39 * This file contains all the routines used when modifying on-disk SPA state.
40 * This includes opening, importing, destroying, exporting a pool, and syncing a
41 * pool.
42 */
43
44#include <sys/zfs_context.h>
45#include <sys/fm/fs/zfs.h>
46#include <sys/spa_impl.h>
47#include <sys/zio.h>
48#include <sys/zio_checksum.h>
34dc7c2f
BB
49#include <sys/dmu.h>
50#include <sys/dmu_tx.h>
51#include <sys/zap.h>
52#include <sys/zil.h>
428870ff 53#include <sys/ddt.h>
34dc7c2f 54#include <sys/vdev_impl.h>
a1d477c2
MA
55#include <sys/vdev_removal.h>
56#include <sys/vdev_indirect_mapping.h>
57#include <sys/vdev_indirect_births.h>
c28b2279 58#include <sys/vdev_disk.h>
34dc7c2f 59#include <sys/metaslab.h>
428870ff 60#include <sys/metaslab_impl.h>
379ca9cf 61#include <sys/mmp.h>
34dc7c2f
BB
62#include <sys/uberblock_impl.h>
63#include <sys/txg.h>
64#include <sys/avl.h>
a1d477c2 65#include <sys/bpobj.h>
34dc7c2f
BB
66#include <sys/dmu_traverse.h>
67#include <sys/dmu_objset.h>
68#include <sys/unique.h>
69#include <sys/dsl_pool.h>
70#include <sys/dsl_dataset.h>
71#include <sys/dsl_dir.h>
72#include <sys/dsl_prop.h>
73#include <sys/dsl_synctask.h>
74#include <sys/fs/zfs.h>
75#include <sys/arc.h>
76#include <sys/callb.h>
77#include <sys/systeminfo.h>
34dc7c2f 78#include <sys/spa_boot.h>
9babb374 79#include <sys/zfs_ioctl.h>
428870ff 80#include <sys/dsl_scan.h>
9ae529ec 81#include <sys/zfeature.h>
13fe0198 82#include <sys/dsl_destroy.h>
526af785 83#include <sys/zvol.h>
34dc7c2f 84
d164b209 85#ifdef _KERNEL
12fa0466
DE
86#include <sys/fm/protocol.h>
87#include <sys/fm/util.h>
428870ff
BB
88#include <sys/bootprops.h>
89#include <sys/callb.h>
90#include <sys/cpupart.h>
91#include <sys/pool.h>
92#include <sys/sysdc.h>
d164b209
BB
93#include <sys/zone.h>
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
137 * are so high frequency and short-lived that the taskq itself can become a a
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 */
9babb374
BB
155};
156
13fe0198
MA
157static void spa_sync_version(void *arg, dmu_tx_t *tx);
158static void spa_sync_props(void *arg, dmu_tx_t *tx);
b128c09f 159static boolean_t spa_has_active_shared_spare(spa_t *spa);
bf701a83 160static inline int spa_load_impl(spa_t *spa, uint64_t, nvlist_t *config,
a1d477c2 161 spa_load_state_t state, spa_import_type_t type, boolean_t trust_config,
428870ff 162 char **ereport);
572e2857 163static void spa_vdev_resilver_done(spa_t *spa);
428870ff 164
e8b96c60 165uint_t zio_taskq_batch_pct = 75; /* 1 thread per cpu in pset */
428870ff
BB
166id_t zio_taskq_psrset_bind = PS_NONE;
167boolean_t zio_taskq_sysdc = B_TRUE; /* use SDC scheduling class */
168uint_t zio_taskq_basedc = 80; /* base duty cycle */
169
170boolean_t spa_create_process = B_TRUE; /* no process ==> no sysdc */
171
172/*
173 * This (illegal) pool name is used when temporarily importing a spa_t in order
174 * to get the vdev stats associated with the imported devices.
175 */
176#define TRYIMPORT_NAME "$import"
34dc7c2f
BB
177
178/*
179 * ==========================================================================
180 * SPA properties routines
181 * ==========================================================================
182 */
183
184/*
185 * Add a (source=src, propname=propval) list to an nvlist.
186 */
187static void
188spa_prop_add_list(nvlist_t *nvl, zpool_prop_t prop, char *strval,
189 uint64_t intval, zprop_source_t src)
190{
191 const char *propname = zpool_prop_to_name(prop);
192 nvlist_t *propval;
193
79c76d5b 194 VERIFY(nvlist_alloc(&propval, NV_UNIQUE_NAME, KM_SLEEP) == 0);
34dc7c2f
BB
195 VERIFY(nvlist_add_uint64(propval, ZPROP_SOURCE, src) == 0);
196
197 if (strval != NULL)
198 VERIFY(nvlist_add_string(propval, ZPROP_VALUE, strval) == 0);
199 else
200 VERIFY(nvlist_add_uint64(propval, ZPROP_VALUE, intval) == 0);
201
202 VERIFY(nvlist_add_nvlist(nvl, propname, propval) == 0);
203 nvlist_free(propval);
204}
205
206/*
207 * Get property values from the spa configuration.
208 */
209static void
210spa_prop_get_config(spa_t *spa, nvlist_t **nvp)
211{
1bd201e7 212 vdev_t *rvd = spa->spa_root_vdev;
9ae529ec 213 dsl_pool_t *pool = spa->spa_dsl_pool;
f3a7f661 214 uint64_t size, alloc, cap, version;
82ab6848 215 const zprop_source_t src = ZPROP_SRC_NONE;
b128c09f 216 spa_config_dirent_t *dp;
f3a7f661 217 metaslab_class_t *mc = spa_normal_class(spa);
b128c09f
BB
218
219 ASSERT(MUTEX_HELD(&spa->spa_props_lock));
34dc7c2f 220
1bd201e7 221 if (rvd != NULL) {
428870ff
BB
222 alloc = metaslab_class_get_alloc(spa_normal_class(spa));
223 size = metaslab_class_get_space(spa_normal_class(spa));
d164b209
BB
224 spa_prop_add_list(*nvp, ZPOOL_PROP_NAME, spa_name(spa), 0, src);
225 spa_prop_add_list(*nvp, ZPOOL_PROP_SIZE, NULL, size, src);
428870ff
BB
226 spa_prop_add_list(*nvp, ZPOOL_PROP_ALLOCATED, NULL, alloc, src);
227 spa_prop_add_list(*nvp, ZPOOL_PROP_FREE, NULL,
228 size - alloc, src);
1bd201e7 229
f3a7f661
GW
230 spa_prop_add_list(*nvp, ZPOOL_PROP_FRAGMENTATION, NULL,
231 metaslab_class_fragmentation(mc), src);
232 spa_prop_add_list(*nvp, ZPOOL_PROP_EXPANDSZ, NULL,
233 metaslab_class_expandable_space(mc), src);
572e2857
BB
234 spa_prop_add_list(*nvp, ZPOOL_PROP_READONLY, NULL,
235 (spa_mode(spa) == FREAD), src);
d164b209 236
428870ff 237 cap = (size == 0) ? 0 : (alloc * 100 / size);
d164b209
BB
238 spa_prop_add_list(*nvp, ZPOOL_PROP_CAPACITY, NULL, cap, src);
239
428870ff
BB
240 spa_prop_add_list(*nvp, ZPOOL_PROP_DEDUPRATIO, NULL,
241 ddt_get_pool_dedup_ratio(spa), src);
242
d164b209 243 spa_prop_add_list(*nvp, ZPOOL_PROP_HEALTH, NULL,
1bd201e7 244 rvd->vdev_state, src);
d164b209
BB
245
246 version = spa_version(spa);
82ab6848
HM
247 if (version == zpool_prop_default_numeric(ZPOOL_PROP_VERSION)) {
248 spa_prop_add_list(*nvp, ZPOOL_PROP_VERSION, NULL,
249 version, ZPROP_SRC_DEFAULT);
250 } else {
251 spa_prop_add_list(*nvp, ZPOOL_PROP_VERSION, NULL,
252 version, ZPROP_SRC_LOCAL);
253 }
d164b209 254 }
34dc7c2f 255
9ae529ec 256 if (pool != NULL) {
9ae529ec
CS
257 /*
258 * The $FREE directory was introduced in SPA_VERSION_DEADLISTS,
259 * when opening pools before this version freedir will be NULL.
260 */
fbeddd60 261 if (pool->dp_free_dir != NULL) {
9ae529ec 262 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING, NULL,
d683ddbb
JG
263 dsl_dir_phys(pool->dp_free_dir)->dd_used_bytes,
264 src);
9ae529ec
CS
265 } else {
266 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING,
267 NULL, 0, src);
268 }
fbeddd60
MA
269
270 if (pool->dp_leak_dir != NULL) {
271 spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED, NULL,
d683ddbb
JG
272 dsl_dir_phys(pool->dp_leak_dir)->dd_used_bytes,
273 src);
fbeddd60
MA
274 } else {
275 spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED,
276 NULL, 0, src);
277 }
9ae529ec
CS
278 }
279
34dc7c2f 280 spa_prop_add_list(*nvp, ZPOOL_PROP_GUID, NULL, spa_guid(spa), src);
34dc7c2f 281
d96eb2b1
DM
282 if (spa->spa_comment != NULL) {
283 spa_prop_add_list(*nvp, ZPOOL_PROP_COMMENT, spa->spa_comment,
284 0, ZPROP_SRC_LOCAL);
285 }
286
34dc7c2f
BB
287 if (spa->spa_root != NULL)
288 spa_prop_add_list(*nvp, ZPOOL_PROP_ALTROOT, spa->spa_root,
289 0, ZPROP_SRC_LOCAL);
290
f1512ee6
MA
291 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS)) {
292 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
293 MIN(zfs_max_recordsize, SPA_MAXBLOCKSIZE), ZPROP_SRC_NONE);
294 } else {
295 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
296 SPA_OLD_MAXBLOCKSIZE, ZPROP_SRC_NONE);
297 }
298
50c957f7
NB
299 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_DNODE)) {
300 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXDNODESIZE, NULL,
301 DNODE_MAX_SIZE, ZPROP_SRC_NONE);
302 } else {
303 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXDNODESIZE, NULL,
304 DNODE_MIN_SIZE, ZPROP_SRC_NONE);
305 }
306
b128c09f
BB
307 if ((dp = list_head(&spa->spa_config_list)) != NULL) {
308 if (dp->scd_path == NULL) {
34dc7c2f 309 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
b128c09f
BB
310 "none", 0, ZPROP_SRC_LOCAL);
311 } else if (strcmp(dp->scd_path, spa_config_path) != 0) {
34dc7c2f 312 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
b128c09f 313 dp->scd_path, 0, ZPROP_SRC_LOCAL);
34dc7c2f
BB
314 }
315 }
316}
317
318/*
319 * Get zpool property values.
320 */
321int
322spa_prop_get(spa_t *spa, nvlist_t **nvp)
323{
428870ff 324 objset_t *mos = spa->spa_meta_objset;
34dc7c2f
BB
325 zap_cursor_t zc;
326 zap_attribute_t za;
34dc7c2f
BB
327 int err;
328
79c76d5b 329 err = nvlist_alloc(nvp, NV_UNIQUE_NAME, KM_SLEEP);
c28b2279 330 if (err)
d1d7e268 331 return (err);
34dc7c2f 332
b128c09f
BB
333 mutex_enter(&spa->spa_props_lock);
334
34dc7c2f
BB
335 /*
336 * Get properties from the spa config.
337 */
338 spa_prop_get_config(spa, nvp);
339
34dc7c2f 340 /* If no pool property object, no more prop to get. */
428870ff 341 if (mos == NULL || spa->spa_pool_props_object == 0) {
34dc7c2f 342 mutex_exit(&spa->spa_props_lock);
c28b2279 343 goto out;
34dc7c2f
BB
344 }
345
346 /*
347 * Get properties from the MOS pool property object.
348 */
349 for (zap_cursor_init(&zc, mos, spa->spa_pool_props_object);
350 (err = zap_cursor_retrieve(&zc, &za)) == 0;
351 zap_cursor_advance(&zc)) {
352 uint64_t intval = 0;
353 char *strval = NULL;
354 zprop_source_t src = ZPROP_SRC_DEFAULT;
355 zpool_prop_t prop;
356
31864e3d 357 if ((prop = zpool_name_to_prop(za.za_name)) == ZPOOL_PROP_INVAL)
34dc7c2f
BB
358 continue;
359
360 switch (za.za_integer_length) {
361 case 8:
362 /* integer property */
363 if (za.za_first_integer !=
364 zpool_prop_default_numeric(prop))
365 src = ZPROP_SRC_LOCAL;
366
367 if (prop == ZPOOL_PROP_BOOTFS) {
368 dsl_pool_t *dp;
369 dsl_dataset_t *ds = NULL;
370
371 dp = spa_get_dsl(spa);
13fe0198 372 dsl_pool_config_enter(dp, FTAG);
c65aa5b2
BB
373 if ((err = dsl_dataset_hold_obj(dp,
374 za.za_first_integer, FTAG, &ds))) {
13fe0198 375 dsl_pool_config_exit(dp, FTAG);
34dc7c2f
BB
376 break;
377 }
378
eca7b760 379 strval = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN,
79c76d5b 380 KM_SLEEP);
34dc7c2f 381 dsl_dataset_name(ds, strval);
b128c09f 382 dsl_dataset_rele(ds, FTAG);
13fe0198 383 dsl_pool_config_exit(dp, FTAG);
34dc7c2f
BB
384 } else {
385 strval = NULL;
386 intval = za.za_first_integer;
387 }
388
389 spa_prop_add_list(*nvp, prop, strval, intval, src);
390
391 if (strval != NULL)
eca7b760 392 kmem_free(strval, ZFS_MAX_DATASET_NAME_LEN);
34dc7c2f
BB
393
394 break;
395
396 case 1:
397 /* string property */
79c76d5b 398 strval = kmem_alloc(za.za_num_integers, KM_SLEEP);
34dc7c2f
BB
399 err = zap_lookup(mos, spa->spa_pool_props_object,
400 za.za_name, 1, za.za_num_integers, strval);
401 if (err) {
402 kmem_free(strval, za.za_num_integers);
403 break;
404 }
405 spa_prop_add_list(*nvp, prop, strval, 0, src);
406 kmem_free(strval, za.za_num_integers);
407 break;
408
409 default:
410 break;
411 }
412 }
413 zap_cursor_fini(&zc);
414 mutex_exit(&spa->spa_props_lock);
415out:
416 if (err && err != ENOENT) {
417 nvlist_free(*nvp);
418 *nvp = NULL;
419 return (err);
420 }
421
422 return (0);
423}
424
425/*
426 * Validate the given pool properties nvlist and modify the list
427 * for the property values to be set.
428 */
429static int
430spa_prop_validate(spa_t *spa, nvlist_t *props)
431{
432 nvpair_t *elem;
433 int error = 0, reset_bootfs = 0;
d4ed6673 434 uint64_t objnum = 0;
9ae529ec 435 boolean_t has_feature = B_FALSE;
34dc7c2f
BB
436
437 elem = NULL;
438 while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
34dc7c2f 439 uint64_t intval;
9ae529ec
CS
440 char *strval, *slash, *check, *fname;
441 const char *propname = nvpair_name(elem);
442 zpool_prop_t prop = zpool_name_to_prop(propname);
443
31864e3d
BB
444 switch (prop) {
445 case ZPOOL_PROP_INVAL:
9ae529ec 446 if (!zpool_prop_feature(propname)) {
2e528b49 447 error = SET_ERROR(EINVAL);
9ae529ec
CS
448 break;
449 }
450
451 /*
452 * Sanitize the input.
453 */
454 if (nvpair_type(elem) != DATA_TYPE_UINT64) {
2e528b49 455 error = SET_ERROR(EINVAL);
9ae529ec
CS
456 break;
457 }
458
459 if (nvpair_value_uint64(elem, &intval) != 0) {
2e528b49 460 error = SET_ERROR(EINVAL);
9ae529ec
CS
461 break;
462 }
34dc7c2f 463
9ae529ec 464 if (intval != 0) {
2e528b49 465 error = SET_ERROR(EINVAL);
9ae529ec
CS
466 break;
467 }
34dc7c2f 468
9ae529ec
CS
469 fname = strchr(propname, '@') + 1;
470 if (zfeature_lookup_name(fname, NULL) != 0) {
2e528b49 471 error = SET_ERROR(EINVAL);
9ae529ec
CS
472 break;
473 }
474
475 has_feature = B_TRUE;
476 break;
34dc7c2f 477
34dc7c2f
BB
478 case ZPOOL_PROP_VERSION:
479 error = nvpair_value_uint64(elem, &intval);
480 if (!error &&
9ae529ec
CS
481 (intval < spa_version(spa) ||
482 intval > SPA_VERSION_BEFORE_FEATURES ||
483 has_feature))
2e528b49 484 error = SET_ERROR(EINVAL);
34dc7c2f
BB
485 break;
486
487 case ZPOOL_PROP_DELEGATION:
488 case ZPOOL_PROP_AUTOREPLACE:
b128c09f 489 case ZPOOL_PROP_LISTSNAPS:
9babb374 490 case ZPOOL_PROP_AUTOEXPAND:
34dc7c2f
BB
491 error = nvpair_value_uint64(elem, &intval);
492 if (!error && intval > 1)
2e528b49 493 error = SET_ERROR(EINVAL);
34dc7c2f
BB
494 break;
495
379ca9cf
OF
496 case ZPOOL_PROP_MULTIHOST:
497 error = nvpair_value_uint64(elem, &intval);
498 if (!error && intval > 1)
499 error = SET_ERROR(EINVAL);
500
501 if (!error && !spa_get_hostid())
502 error = SET_ERROR(ENOTSUP);
503
504 break;
505
34dc7c2f 506 case ZPOOL_PROP_BOOTFS:
9babb374
BB
507 /*
508 * If the pool version is less than SPA_VERSION_BOOTFS,
509 * or the pool is still being created (version == 0),
510 * the bootfs property cannot be set.
511 */
34dc7c2f 512 if (spa_version(spa) < SPA_VERSION_BOOTFS) {
2e528b49 513 error = SET_ERROR(ENOTSUP);
34dc7c2f
BB
514 break;
515 }
516
517 /*
b128c09f 518 * Make sure the vdev config is bootable
34dc7c2f 519 */
b128c09f 520 if (!vdev_is_bootable(spa->spa_root_vdev)) {
2e528b49 521 error = SET_ERROR(ENOTSUP);
34dc7c2f
BB
522 break;
523 }
524
525 reset_bootfs = 1;
526
527 error = nvpair_value_string(elem, &strval);
528
529 if (!error) {
9ae529ec 530 objset_t *os;
f1512ee6 531 uint64_t propval;
b128c09f 532
34dc7c2f
BB
533 if (strval == NULL || strval[0] == '\0') {
534 objnum = zpool_prop_default_numeric(
535 ZPOOL_PROP_BOOTFS);
536 break;
537 }
538
d1d7e268
MK
539 error = dmu_objset_hold(strval, FTAG, &os);
540 if (error)
34dc7c2f 541 break;
b128c09f 542
f1512ee6
MA
543 /*
544 * Must be ZPL, and its property settings
545 * must be supported by GRUB (compression
50c957f7
NB
546 * is not gzip, and large blocks or large
547 * dnodes are not used).
f1512ee6 548 */
428870ff
BB
549
550 if (dmu_objset_type(os) != DMU_OST_ZFS) {
2e528b49 551 error = SET_ERROR(ENOTSUP);
13fe0198
MA
552 } else if ((error =
553 dsl_prop_get_int_ds(dmu_objset_ds(os),
b128c09f 554 zfs_prop_to_name(ZFS_PROP_COMPRESSION),
f1512ee6
MA
555 &propval)) == 0 &&
556 !BOOTFS_COMPRESS_VALID(propval)) {
557 error = SET_ERROR(ENOTSUP);
50c957f7
NB
558 } else if ((error =
559 dsl_prop_get_int_ds(dmu_objset_ds(os),
560 zfs_prop_to_name(ZFS_PROP_DNODESIZE),
561 &propval)) == 0 &&
562 propval != ZFS_DNSIZE_LEGACY) {
563 error = SET_ERROR(ENOTSUP);
b128c09f
BB
564 } else {
565 objnum = dmu_objset_id(os);
566 }
428870ff 567 dmu_objset_rele(os, FTAG);
34dc7c2f
BB
568 }
569 break;
b128c09f 570
34dc7c2f
BB
571 case ZPOOL_PROP_FAILUREMODE:
572 error = nvpair_value_uint64(elem, &intval);
3bfd95d5 573 if (!error && intval > ZIO_FAILURE_MODE_PANIC)
2e528b49 574 error = SET_ERROR(EINVAL);
34dc7c2f
BB
575
576 /*
577 * This is a special case which only occurs when
578 * the pool has completely failed. This allows
579 * the user to change the in-core failmode property
580 * without syncing it out to disk (I/Os might
581 * currently be blocked). We do this by returning
582 * EIO to the caller (spa_prop_set) to trick it
583 * into thinking we encountered a property validation
584 * error.
585 */
b128c09f 586 if (!error && spa_suspended(spa)) {
34dc7c2f 587 spa->spa_failmode = intval;
2e528b49 588 error = SET_ERROR(EIO);
34dc7c2f
BB
589 }
590 break;
591
592 case ZPOOL_PROP_CACHEFILE:
593 if ((error = nvpair_value_string(elem, &strval)) != 0)
594 break;
595
596 if (strval[0] == '\0')
597 break;
598
599 if (strcmp(strval, "none") == 0)
600 break;
601
602 if (strval[0] != '/') {
2e528b49 603 error = SET_ERROR(EINVAL);
34dc7c2f
BB
604 break;
605 }
606
607 slash = strrchr(strval, '/');
608 ASSERT(slash != NULL);
609
610 if (slash[1] == '\0' || strcmp(slash, "/.") == 0 ||
611 strcmp(slash, "/..") == 0)
2e528b49 612 error = SET_ERROR(EINVAL);
34dc7c2f 613 break;
428870ff 614
d96eb2b1
DM
615 case ZPOOL_PROP_COMMENT:
616 if ((error = nvpair_value_string(elem, &strval)) != 0)
617 break;
618 for (check = strval; *check != '\0'; check++) {
619 if (!isprint(*check)) {
2e528b49 620 error = SET_ERROR(EINVAL);
d96eb2b1
DM
621 break;
622 }
d96eb2b1
DM
623 }
624 if (strlen(strval) > ZPROP_MAX_COMMENT)
2e528b49 625 error = SET_ERROR(E2BIG);
d96eb2b1
DM
626 break;
627
428870ff
BB
628 case ZPOOL_PROP_DEDUPDITTO:
629 if (spa_version(spa) < SPA_VERSION_DEDUP)
2e528b49 630 error = SET_ERROR(ENOTSUP);
428870ff
BB
631 else
632 error = nvpair_value_uint64(elem, &intval);
633 if (error == 0 &&
634 intval != 0 && intval < ZIO_DEDUPDITTO_MIN)
2e528b49 635 error = SET_ERROR(EINVAL);
428870ff 636 break;
e75c13c3
BB
637
638 default:
639 break;
34dc7c2f
BB
640 }
641
642 if (error)
643 break;
644 }
645
646 if (!error && reset_bootfs) {
647 error = nvlist_remove(props,
648 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), DATA_TYPE_STRING);
649
650 if (!error) {
651 error = nvlist_add_uint64(props,
652 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), objnum);
653 }
654 }
655
656 return (error);
657}
658
d164b209
BB
659void
660spa_configfile_set(spa_t *spa, nvlist_t *nvp, boolean_t need_sync)
661{
662 char *cachefile;
663 spa_config_dirent_t *dp;
664
665 if (nvlist_lookup_string(nvp, zpool_prop_to_name(ZPOOL_PROP_CACHEFILE),
666 &cachefile) != 0)
667 return;
668
669 dp = kmem_alloc(sizeof (spa_config_dirent_t),
79c76d5b 670 KM_SLEEP);
d164b209
BB
671
672 if (cachefile[0] == '\0')
673 dp->scd_path = spa_strdup(spa_config_path);
674 else if (strcmp(cachefile, "none") == 0)
675 dp->scd_path = NULL;
676 else
677 dp->scd_path = spa_strdup(cachefile);
678
679 list_insert_head(&spa->spa_config_list, dp);
680 if (need_sync)
681 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
682}
683
34dc7c2f
BB
684int
685spa_prop_set(spa_t *spa, nvlist_t *nvp)
686{
687 int error;
9ae529ec 688 nvpair_t *elem = NULL;
d164b209 689 boolean_t need_sync = B_FALSE;
34dc7c2f
BB
690
691 if ((error = spa_prop_validate(spa, nvp)) != 0)
692 return (error);
693
d164b209 694 while ((elem = nvlist_next_nvpair(nvp, elem)) != NULL) {
9ae529ec 695 zpool_prop_t prop = zpool_name_to_prop(nvpair_name(elem));
d164b209 696
572e2857
BB
697 if (prop == ZPOOL_PROP_CACHEFILE ||
698 prop == ZPOOL_PROP_ALTROOT ||
699 prop == ZPOOL_PROP_READONLY)
d164b209
BB
700 continue;
701
31864e3d 702 if (prop == ZPOOL_PROP_VERSION || prop == ZPOOL_PROP_INVAL) {
9ae529ec
CS
703 uint64_t ver;
704
705 if (prop == ZPOOL_PROP_VERSION) {
706 VERIFY(nvpair_value_uint64(elem, &ver) == 0);
707 } else {
708 ASSERT(zpool_prop_feature(nvpair_name(elem)));
709 ver = SPA_VERSION_FEATURES;
710 need_sync = B_TRUE;
711 }
712
713 /* Save time if the version is already set. */
714 if (ver == spa_version(spa))
715 continue;
716
717 /*
718 * In addition to the pool directory object, we might
719 * create the pool properties object, the features for
720 * read object, the features for write object, or the
721 * feature descriptions object.
722 */
13fe0198 723 error = dsl_sync_task(spa->spa_name, NULL,
3d45fdd6
MA
724 spa_sync_version, &ver,
725 6, ZFS_SPACE_CHECK_RESERVED);
9ae529ec
CS
726 if (error)
727 return (error);
728 continue;
729 }
730
d164b209
BB
731 need_sync = B_TRUE;
732 break;
733 }
734
9ae529ec 735 if (need_sync) {
13fe0198 736 return (dsl_sync_task(spa->spa_name, NULL, spa_sync_props,
3d45fdd6 737 nvp, 6, ZFS_SPACE_CHECK_RESERVED));
9ae529ec
CS
738 }
739
740 return (0);
34dc7c2f
BB
741}
742
743/*
744 * If the bootfs property value is dsobj, clear it.
745 */
746void
747spa_prop_clear_bootfs(spa_t *spa, uint64_t dsobj, dmu_tx_t *tx)
748{
749 if (spa->spa_bootfs == dsobj && spa->spa_pool_props_object != 0) {
750 VERIFY(zap_remove(spa->spa_meta_objset,
751 spa->spa_pool_props_object,
752 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), tx) == 0);
753 spa->spa_bootfs = 0;
754 }
755}
756
3bc7e0fb
GW
757/*ARGSUSED*/
758static int
13fe0198 759spa_change_guid_check(void *arg, dmu_tx_t *tx)
3bc7e0fb 760{
1c27024e 761 ASSERTV(uint64_t *newguid = arg);
13fe0198 762 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
3bc7e0fb
GW
763 vdev_t *rvd = spa->spa_root_vdev;
764 uint64_t vdev_state;
3bc7e0fb
GW
765
766 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
767 vdev_state = rvd->vdev_state;
768 spa_config_exit(spa, SCL_STATE, FTAG);
769
770 if (vdev_state != VDEV_STATE_HEALTHY)
2e528b49 771 return (SET_ERROR(ENXIO));
3bc7e0fb
GW
772
773 ASSERT3U(spa_guid(spa), !=, *newguid);
774
775 return (0);
776}
777
778static void
13fe0198 779spa_change_guid_sync(void *arg, dmu_tx_t *tx)
3bc7e0fb 780{
13fe0198
MA
781 uint64_t *newguid = arg;
782 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
3bc7e0fb
GW
783 uint64_t oldguid;
784 vdev_t *rvd = spa->spa_root_vdev;
785
786 oldguid = spa_guid(spa);
787
788 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
789 rvd->vdev_guid = *newguid;
790 rvd->vdev_guid_sum += (*newguid - oldguid);
791 vdev_config_dirty(rvd);
792 spa_config_exit(spa, SCL_STATE, FTAG);
793
6f1ffb06
MA
794 spa_history_log_internal(spa, "guid change", tx, "old=%llu new=%llu",
795 oldguid, *newguid);
3bc7e0fb
GW
796}
797
3541dc6d
GA
798/*
799 * Change the GUID for the pool. This is done so that we can later
800 * re-import a pool built from a clone of our own vdevs. We will modify
801 * the root vdev's guid, our own pool guid, and then mark all of our
802 * vdevs dirty. Note that we must make sure that all our vdevs are
803 * online when we do this, or else any vdevs that weren't present
804 * would be orphaned from our pool. We are also going to issue a
805 * sysevent to update any watchers.
806 */
807int
808spa_change_guid(spa_t *spa)
809{
3bc7e0fb
GW
810 int error;
811 uint64_t guid;
3541dc6d 812
621dd7bb 813 mutex_enter(&spa->spa_vdev_top_lock);
3bc7e0fb
GW
814 mutex_enter(&spa_namespace_lock);
815 guid = spa_generate_guid(NULL);
3541dc6d 816
13fe0198 817 error = dsl_sync_task(spa->spa_name, spa_change_guid_check,
3d45fdd6 818 spa_change_guid_sync, &guid, 5, ZFS_SPACE_CHECK_RESERVED);
3541dc6d 819
3bc7e0fb 820 if (error == 0) {
a1d477c2 821 spa_write_cachefile(spa, B_FALSE, B_TRUE);
12fa0466 822 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_REGUID);
3bc7e0fb 823 }
3541dc6d 824
3bc7e0fb 825 mutex_exit(&spa_namespace_lock);
621dd7bb 826 mutex_exit(&spa->spa_vdev_top_lock);
3541dc6d 827
3bc7e0fb 828 return (error);
3541dc6d
GA
829}
830
34dc7c2f
BB
831/*
832 * ==========================================================================
833 * SPA state manipulation (open/create/destroy/import/export)
834 * ==========================================================================
835 */
836
837static int
838spa_error_entry_compare(const void *a, const void *b)
839{
ee36c709
GN
840 const spa_error_entry_t *sa = (const spa_error_entry_t *)a;
841 const spa_error_entry_t *sb = (const spa_error_entry_t *)b;
34dc7c2f
BB
842 int ret;
843
ee36c709 844 ret = memcmp(&sa->se_bookmark, &sb->se_bookmark,
5dbd68a3 845 sizeof (zbookmark_phys_t));
34dc7c2f 846
ee36c709 847 return (AVL_ISIGN(ret));
34dc7c2f
BB
848}
849
850/*
851 * Utility function which retrieves copies of the current logs and
852 * re-initializes them in the process.
853 */
854void
855spa_get_errlists(spa_t *spa, avl_tree_t *last, avl_tree_t *scrub)
856{
857 ASSERT(MUTEX_HELD(&spa->spa_errlist_lock));
858
859 bcopy(&spa->spa_errlist_last, last, sizeof (avl_tree_t));
860 bcopy(&spa->spa_errlist_scrub, scrub, sizeof (avl_tree_t));
861
862 avl_create(&spa->spa_errlist_scrub,
863 spa_error_entry_compare, sizeof (spa_error_entry_t),
864 offsetof(spa_error_entry_t, se_avl));
865 avl_create(&spa->spa_errlist_last,
866 spa_error_entry_compare, sizeof (spa_error_entry_t),
867 offsetof(spa_error_entry_t, se_avl));
868}
869
7ef5e54e
AL
870static void
871spa_taskqs_init(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
34dc7c2f 872{
7ef5e54e
AL
873 const zio_taskq_info_t *ztip = &zio_taskqs[t][q];
874 enum zti_modes mode = ztip->zti_mode;
875 uint_t value = ztip->zti_value;
876 uint_t count = ztip->zti_count;
877 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
878 char name[32];
1c27024e 879 uint_t flags = 0;
428870ff 880 boolean_t batch = B_FALSE;
34dc7c2f 881
7ef5e54e
AL
882 if (mode == ZTI_MODE_NULL) {
883 tqs->stqs_count = 0;
884 tqs->stqs_taskq = NULL;
885 return;
886 }
428870ff 887
7ef5e54e 888 ASSERT3U(count, >, 0);
428870ff 889
7ef5e54e
AL
890 tqs->stqs_count = count;
891 tqs->stqs_taskq = kmem_alloc(count * sizeof (taskq_t *), KM_SLEEP);
428870ff 892
e8b96c60
MA
893 switch (mode) {
894 case ZTI_MODE_FIXED:
895 ASSERT3U(value, >=, 1);
896 value = MAX(value, 1);
d33931a8 897 flags |= TASKQ_DYNAMIC;
e8b96c60 898 break;
7ef5e54e 899
e8b96c60
MA
900 case ZTI_MODE_BATCH:
901 batch = B_TRUE;
902 flags |= TASKQ_THREADS_CPU_PCT;
dcb6bed1 903 value = MIN(zio_taskq_batch_pct, 100);
e8b96c60 904 break;
7ef5e54e 905
e8b96c60
MA
906 default:
907 panic("unrecognized mode for %s_%s taskq (%u:%u) in "
908 "spa_activate()",
909 zio_type_name[t], zio_taskq_types[q], mode, value);
910 break;
911 }
7ef5e54e 912
1c27024e 913 for (uint_t i = 0; i < count; i++) {
e8b96c60 914 taskq_t *tq;
7ef5e54e
AL
915
916 if (count > 1) {
917 (void) snprintf(name, sizeof (name), "%s_%s_%u",
918 zio_type_name[t], zio_taskq_types[q], i);
919 } else {
920 (void) snprintf(name, sizeof (name), "%s_%s",
921 zio_type_name[t], zio_taskq_types[q]);
922 }
923
924 if (zio_taskq_sysdc && spa->spa_proc != &p0) {
925 if (batch)
926 flags |= TASKQ_DC_BATCH;
927
928 tq = taskq_create_sysdc(name, value, 50, INT_MAX,
929 spa->spa_proc, zio_taskq_basedc, flags);
930 } else {
e8b96c60
MA
931 pri_t pri = maxclsyspri;
932 /*
933 * The write issue taskq can be extremely CPU
1229323d
BB
934 * intensive. Run it at slightly less important
935 * priority than the other taskqs. Under Linux this
936 * means incrementing the priority value on platforms
937 * like illumos it should be decremented.
e8b96c60
MA
938 */
939 if (t == ZIO_TYPE_WRITE && q == ZIO_TASKQ_ISSUE)
1229323d 940 pri++;
e8b96c60
MA
941
942 tq = taskq_create_proc(name, value, pri, 50,
7ef5e54e
AL
943 INT_MAX, spa->spa_proc, flags);
944 }
945
946 tqs->stqs_taskq[i] = tq;
947 }
948}
949
950static void
951spa_taskqs_fini(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
952{
953 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
7ef5e54e
AL
954
955 if (tqs->stqs_taskq == NULL) {
956 ASSERT3U(tqs->stqs_count, ==, 0);
957 return;
958 }
959
1c27024e 960 for (uint_t i = 0; i < tqs->stqs_count; i++) {
7ef5e54e
AL
961 ASSERT3P(tqs->stqs_taskq[i], !=, NULL);
962 taskq_destroy(tqs->stqs_taskq[i]);
428870ff 963 }
34dc7c2f 964
7ef5e54e
AL
965 kmem_free(tqs->stqs_taskq, tqs->stqs_count * sizeof (taskq_t *));
966 tqs->stqs_taskq = NULL;
967}
34dc7c2f 968
7ef5e54e
AL
969/*
970 * Dispatch a task to the appropriate taskq for the ZFS I/O type and priority.
971 * Note that a type may have multiple discrete taskqs to avoid lock contention
972 * on the taskq itself. In that case we choose which taskq at random by using
973 * the low bits of gethrtime().
974 */
975void
976spa_taskq_dispatch_ent(spa_t *spa, zio_type_t t, zio_taskq_type_t q,
977 task_func_t *func, void *arg, uint_t flags, taskq_ent_t *ent)
978{
979 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
980 taskq_t *tq;
981
982 ASSERT3P(tqs->stqs_taskq, !=, NULL);
983 ASSERT3U(tqs->stqs_count, !=, 0);
984
985 if (tqs->stqs_count == 1) {
986 tq = tqs->stqs_taskq[0];
987 } else {
c12936b1 988 tq = tqs->stqs_taskq[((uint64_t)gethrtime()) % tqs->stqs_count];
428870ff 989 }
7ef5e54e
AL
990
991 taskq_dispatch_ent(tq, func, arg, flags, ent);
428870ff
BB
992}
993
044baf00
BB
994/*
995 * Same as spa_taskq_dispatch_ent() but block on the task until completion.
996 */
997void
998spa_taskq_dispatch_sync(spa_t *spa, zio_type_t t, zio_taskq_type_t q,
999 task_func_t *func, void *arg, uint_t flags)
1000{
1001 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1002 taskq_t *tq;
1003 taskqid_t id;
1004
1005 ASSERT3P(tqs->stqs_taskq, !=, NULL);
1006 ASSERT3U(tqs->stqs_count, !=, 0);
1007
1008 if (tqs->stqs_count == 1) {
1009 tq = tqs->stqs_taskq[0];
1010 } else {
c12936b1 1011 tq = tqs->stqs_taskq[((uint64_t)gethrtime()) % tqs->stqs_count];
044baf00
BB
1012 }
1013
1014 id = taskq_dispatch(tq, func, arg, flags);
1015 if (id)
1016 taskq_wait_id(tq, id);
1017}
1018
428870ff
BB
1019static void
1020spa_create_zio_taskqs(spa_t *spa)
1021{
1c27024e
DB
1022 for (int t = 0; t < ZIO_TYPES; t++) {
1023 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
7ef5e54e 1024 spa_taskqs_init(spa, t, q);
428870ff
BB
1025 }
1026 }
1027}
9babb374 1028
c25b8f99
BB
1029/*
1030 * Disabled until spa_thread() can be adapted for Linux.
1031 */
1032#undef HAVE_SPA_THREAD
1033
7b89a549 1034#if defined(_KERNEL) && defined(HAVE_SPA_THREAD)
428870ff
BB
1035static void
1036spa_thread(void *arg)
1037{
1038 callb_cpr_t cprinfo;
9babb374 1039
428870ff
BB
1040 spa_t *spa = arg;
1041 user_t *pu = PTOU(curproc);
9babb374 1042
428870ff
BB
1043 CALLB_CPR_INIT(&cprinfo, &spa->spa_proc_lock, callb_generic_cpr,
1044 spa->spa_name);
9babb374 1045
428870ff
BB
1046 ASSERT(curproc != &p0);
1047 (void) snprintf(pu->u_psargs, sizeof (pu->u_psargs),
1048 "zpool-%s", spa->spa_name);
1049 (void) strlcpy(pu->u_comm, pu->u_psargs, sizeof (pu->u_comm));
1050
1051 /* bind this thread to the requested psrset */
1052 if (zio_taskq_psrset_bind != PS_NONE) {
1053 pool_lock();
1054 mutex_enter(&cpu_lock);
1055 mutex_enter(&pidlock);
1056 mutex_enter(&curproc->p_lock);
1057
1058 if (cpupart_bind_thread(curthread, zio_taskq_psrset_bind,
1059 0, NULL, NULL) == 0) {
1060 curthread->t_bind_pset = zio_taskq_psrset_bind;
1061 } else {
1062 cmn_err(CE_WARN,
1063 "Couldn't bind process for zfs pool \"%s\" to "
1064 "pset %d\n", spa->spa_name, zio_taskq_psrset_bind);
1065 }
1066
1067 mutex_exit(&curproc->p_lock);
1068 mutex_exit(&pidlock);
1069 mutex_exit(&cpu_lock);
1070 pool_unlock();
1071 }
1072
1073 if (zio_taskq_sysdc) {
1074 sysdc_thread_enter(curthread, 100, 0);
1075 }
1076
1077 spa->spa_proc = curproc;
1078 spa->spa_did = curthread->t_did;
1079
1080 spa_create_zio_taskqs(spa);
1081
1082 mutex_enter(&spa->spa_proc_lock);
1083 ASSERT(spa->spa_proc_state == SPA_PROC_CREATED);
1084
1085 spa->spa_proc_state = SPA_PROC_ACTIVE;
1086 cv_broadcast(&spa->spa_proc_cv);
1087
1088 CALLB_CPR_SAFE_BEGIN(&cprinfo);
1089 while (spa->spa_proc_state == SPA_PROC_ACTIVE)
1090 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1091 CALLB_CPR_SAFE_END(&cprinfo, &spa->spa_proc_lock);
1092
1093 ASSERT(spa->spa_proc_state == SPA_PROC_DEACTIVATE);
1094 spa->spa_proc_state = SPA_PROC_GONE;
1095 spa->spa_proc = &p0;
1096 cv_broadcast(&spa->spa_proc_cv);
1097 CALLB_CPR_EXIT(&cprinfo); /* drops spa_proc_lock */
1098
1099 mutex_enter(&curproc->p_lock);
1100 lwp_exit();
1101}
1102#endif
1103
1104/*
1105 * Activate an uninitialized pool.
1106 */
1107static void
1108spa_activate(spa_t *spa, int mode)
1109{
1110 ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
1111
1112 spa->spa_state = POOL_STATE_ACTIVE;
1113 spa->spa_mode = mode;
1114
1115 spa->spa_normal_class = metaslab_class_create(spa, zfs_metaslab_ops);
1116 spa->spa_log_class = metaslab_class_create(spa, zfs_metaslab_ops);
1117
1118 /* Try to create a covering process */
1119 mutex_enter(&spa->spa_proc_lock);
1120 ASSERT(spa->spa_proc_state == SPA_PROC_NONE);
1121 ASSERT(spa->spa_proc == &p0);
1122 spa->spa_did = 0;
1123
7b89a549 1124#ifdef HAVE_SPA_THREAD
428870ff
BB
1125 /* Only create a process if we're going to be around a while. */
1126 if (spa_create_process && strcmp(spa->spa_name, TRYIMPORT_NAME) != 0) {
1127 if (newproc(spa_thread, (caddr_t)spa, syscid, maxclsyspri,
1128 NULL, 0) == 0) {
1129 spa->spa_proc_state = SPA_PROC_CREATED;
1130 while (spa->spa_proc_state == SPA_PROC_CREATED) {
1131 cv_wait(&spa->spa_proc_cv,
1132 &spa->spa_proc_lock);
9babb374 1133 }
428870ff
BB
1134 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1135 ASSERT(spa->spa_proc != &p0);
1136 ASSERT(spa->spa_did != 0);
1137 } else {
1138#ifdef _KERNEL
1139 cmn_err(CE_WARN,
1140 "Couldn't create process for zfs pool \"%s\"\n",
1141 spa->spa_name);
1142#endif
b128c09f 1143 }
34dc7c2f 1144 }
7b89a549 1145#endif /* HAVE_SPA_THREAD */
428870ff
BB
1146 mutex_exit(&spa->spa_proc_lock);
1147
1148 /* If we didn't create a process, we need to create our taskqs. */
1149 if (spa->spa_proc == &p0) {
1150 spa_create_zio_taskqs(spa);
1151 }
34dc7c2f 1152
a1d477c2
MA
1153 for (size_t i = 0; i < TXG_SIZE; i++)
1154 spa->spa_txg_zio[i] = zio_root(spa, NULL, NULL, 0);
1155
b128c09f
BB
1156 list_create(&spa->spa_config_dirty_list, sizeof (vdev_t),
1157 offsetof(vdev_t, vdev_config_dirty_node));
0c66c32d
JG
1158 list_create(&spa->spa_evicting_os_list, sizeof (objset_t),
1159 offsetof(objset_t, os_evicting_node));
b128c09f
BB
1160 list_create(&spa->spa_state_dirty_list, sizeof (vdev_t),
1161 offsetof(vdev_t, vdev_state_dirty_node));
34dc7c2f 1162
4747a7d3 1163 txg_list_create(&spa->spa_vdev_txg_list, spa,
34dc7c2f
BB
1164 offsetof(struct vdev, vdev_txg_node));
1165
1166 avl_create(&spa->spa_errlist_scrub,
1167 spa_error_entry_compare, sizeof (spa_error_entry_t),
1168 offsetof(spa_error_entry_t, se_avl));
1169 avl_create(&spa->spa_errlist_last,
1170 spa_error_entry_compare, sizeof (spa_error_entry_t),
1171 offsetof(spa_error_entry_t, se_avl));
a0bd735a 1172
b5256303
TC
1173 spa_keystore_init(&spa->spa_keystore);
1174
a0bd735a
BP
1175 /*
1176 * This taskq is used to perform zvol-minor-related tasks
1177 * asynchronously. This has several advantages, including easy
1178 * resolution of various deadlocks (zfsonlinux bug #3681).
1179 *
1180 * The taskq must be single threaded to ensure tasks are always
1181 * processed in the order in which they were dispatched.
1182 *
1183 * A taskq per pool allows one to keep the pools independent.
1184 * This way if one pool is suspended, it will not impact another.
1185 *
1186 * The preferred location to dispatch a zvol minor task is a sync
1187 * task. In this context, there is easy access to the spa_t and minimal
1188 * error handling is required because the sync task must succeed.
1189 */
1190 spa->spa_zvol_taskq = taskq_create("z_zvol", 1, defclsyspri,
1191 1, INT_MAX, 0);
1de321e6 1192
77d8a0f1 1193 /*
1194 * Taskq dedicated to prefetcher threads: this is used to prevent the
1195 * pool traverse code from monopolizing the global (and limited)
1196 * system_taskq by inappropriately scheduling long running tasks on it.
1197 */
1198 spa->spa_prefetch_taskq = taskq_create("z_prefetch", boot_ncpus,
1199 defclsyspri, 1, INT_MAX, TASKQ_DYNAMIC);
1200
1de321e6
JX
1201 /*
1202 * The taskq to upgrade datasets in this pool. Currently used by
9c5167d1 1203 * feature SPA_FEATURE_USEROBJ_ACCOUNTING/SPA_FEATURE_PROJECT_QUOTA.
1de321e6
JX
1204 */
1205 spa->spa_upgrade_taskq = taskq_create("z_upgrade", boot_ncpus,
1206 defclsyspri, 1, INT_MAX, TASKQ_DYNAMIC);
34dc7c2f
BB
1207}
1208
1209/*
1210 * Opposite of spa_activate().
1211 */
1212static void
1213spa_deactivate(spa_t *spa)
1214{
34dc7c2f
BB
1215 ASSERT(spa->spa_sync_on == B_FALSE);
1216 ASSERT(spa->spa_dsl_pool == NULL);
1217 ASSERT(spa->spa_root_vdev == NULL);
9babb374 1218 ASSERT(spa->spa_async_zio_root == NULL);
34dc7c2f
BB
1219 ASSERT(spa->spa_state != POOL_STATE_UNINITIALIZED);
1220
0c66c32d
JG
1221 spa_evicting_os_wait(spa);
1222
a0bd735a
BP
1223 if (spa->spa_zvol_taskq) {
1224 taskq_destroy(spa->spa_zvol_taskq);
1225 spa->spa_zvol_taskq = NULL;
1226 }
1227
77d8a0f1 1228 if (spa->spa_prefetch_taskq) {
1229 taskq_destroy(spa->spa_prefetch_taskq);
1230 spa->spa_prefetch_taskq = NULL;
1231 }
1232
1de321e6
JX
1233 if (spa->spa_upgrade_taskq) {
1234 taskq_destroy(spa->spa_upgrade_taskq);
1235 spa->spa_upgrade_taskq = NULL;
1236 }
1237
34dc7c2f
BB
1238 txg_list_destroy(&spa->spa_vdev_txg_list);
1239
b128c09f 1240 list_destroy(&spa->spa_config_dirty_list);
0c66c32d 1241 list_destroy(&spa->spa_evicting_os_list);
b128c09f 1242 list_destroy(&spa->spa_state_dirty_list);
34dc7c2f 1243
57ddcda1 1244 taskq_cancel_id(system_delay_taskq, spa->spa_deadman_tqid);
cc92e9d0 1245
1c27024e
DB
1246 for (int t = 0; t < ZIO_TYPES; t++) {
1247 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
7ef5e54e 1248 spa_taskqs_fini(spa, t, q);
b128c09f 1249 }
34dc7c2f
BB
1250 }
1251
a1d477c2
MA
1252 for (size_t i = 0; i < TXG_SIZE; i++) {
1253 ASSERT3P(spa->spa_txg_zio[i], !=, NULL);
1254 VERIFY0(zio_wait(spa->spa_txg_zio[i]));
1255 spa->spa_txg_zio[i] = NULL;
1256 }
1257
34dc7c2f
BB
1258 metaslab_class_destroy(spa->spa_normal_class);
1259 spa->spa_normal_class = NULL;
1260
1261 metaslab_class_destroy(spa->spa_log_class);
1262 spa->spa_log_class = NULL;
1263
1264 /*
1265 * If this was part of an import or the open otherwise failed, we may
1266 * still have errors left in the queues. Empty them just in case.
1267 */
1268 spa_errlog_drain(spa);
34dc7c2f
BB
1269 avl_destroy(&spa->spa_errlist_scrub);
1270 avl_destroy(&spa->spa_errlist_last);
1271
b5256303
TC
1272 spa_keystore_fini(&spa->spa_keystore);
1273
34dc7c2f 1274 spa->spa_state = POOL_STATE_UNINITIALIZED;
428870ff
BB
1275
1276 mutex_enter(&spa->spa_proc_lock);
1277 if (spa->spa_proc_state != SPA_PROC_NONE) {
1278 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1279 spa->spa_proc_state = SPA_PROC_DEACTIVATE;
1280 cv_broadcast(&spa->spa_proc_cv);
1281 while (spa->spa_proc_state == SPA_PROC_DEACTIVATE) {
1282 ASSERT(spa->spa_proc != &p0);
1283 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1284 }
1285 ASSERT(spa->spa_proc_state == SPA_PROC_GONE);
1286 spa->spa_proc_state = SPA_PROC_NONE;
1287 }
1288 ASSERT(spa->spa_proc == &p0);
1289 mutex_exit(&spa->spa_proc_lock);
1290
1291 /*
1292 * We want to make sure spa_thread() has actually exited the ZFS
1293 * module, so that the module can't be unloaded out from underneath
1294 * it.
1295 */
1296 if (spa->spa_did != 0) {
1297 thread_join(spa->spa_did);
1298 spa->spa_did = 0;
1299 }
34dc7c2f
BB
1300}
1301
1302/*
1303 * Verify a pool configuration, and construct the vdev tree appropriately. This
1304 * will create all the necessary vdevs in the appropriate layout, with each vdev
1305 * in the CLOSED state. This will prep the pool before open/creation/import.
1306 * All vdev validation is done by the vdev_alloc() routine.
1307 */
1308static int
1309spa_config_parse(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent,
1310 uint_t id, int atype)
1311{
1312 nvlist_t **child;
9babb374 1313 uint_t children;
34dc7c2f
BB
1314 int error;
1315
1316 if ((error = vdev_alloc(spa, vdp, nv, parent, id, atype)) != 0)
1317 return (error);
1318
1319 if ((*vdp)->vdev_ops->vdev_op_leaf)
1320 return (0);
1321
b128c09f
BB
1322 error = nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1323 &child, &children);
1324
1325 if (error == ENOENT)
1326 return (0);
1327
1328 if (error) {
34dc7c2f
BB
1329 vdev_free(*vdp);
1330 *vdp = NULL;
2e528b49 1331 return (SET_ERROR(EINVAL));
34dc7c2f
BB
1332 }
1333
1c27024e 1334 for (int c = 0; c < children; c++) {
34dc7c2f
BB
1335 vdev_t *vd;
1336 if ((error = spa_config_parse(spa, &vd, child[c], *vdp, c,
1337 atype)) != 0) {
1338 vdev_free(*vdp);
1339 *vdp = NULL;
1340 return (error);
1341 }
1342 }
1343
1344 ASSERT(*vdp != NULL);
1345
1346 return (0);
1347}
1348
1349/*
1350 * Opposite of spa_load().
1351 */
1352static void
1353spa_unload(spa_t *spa)
1354{
1c27024e 1355 int i;
34dc7c2f 1356
b128c09f
BB
1357 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1358
34dc7c2f
BB
1359 /*
1360 * Stop async tasks.
1361 */
1362 spa_async_suspend(spa);
1363
1364 /*
1365 * Stop syncing.
1366 */
1367 if (spa->spa_sync_on) {
1368 txg_sync_stop(spa->spa_dsl_pool);
1369 spa->spa_sync_on = B_FALSE;
1370 }
1371
4e21fd06
DB
1372 /*
1373 * Even though vdev_free() also calls vdev_metaslab_fini, we need
1374 * to call it earlier, before we wait for async i/o to complete.
1375 * This ensures that there is no async metaslab prefetching, by
1376 * calling taskq_wait(mg_taskq).
1377 */
1378 if (spa->spa_root_vdev != NULL) {
1379 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1c27024e 1380 for (int c = 0; c < spa->spa_root_vdev->vdev_children; c++)
4e21fd06
DB
1381 vdev_metaslab_fini(spa->spa_root_vdev->vdev_child[c]);
1382 spa_config_exit(spa, SCL_ALL, FTAG);
1383 }
1384
379ca9cf
OF
1385 if (spa->spa_mmp.mmp_thread)
1386 mmp_thread_stop(spa);
1387
34dc7c2f 1388 /*
b128c09f 1389 * Wait for any outstanding async I/O to complete.
34dc7c2f 1390 */
9babb374 1391 if (spa->spa_async_zio_root != NULL) {
1c27024e 1392 for (int i = 0; i < max_ncpus; i++)
e022864d
MA
1393 (void) zio_wait(spa->spa_async_zio_root[i]);
1394 kmem_free(spa->spa_async_zio_root, max_ncpus * sizeof (void *));
9babb374
BB
1395 spa->spa_async_zio_root = NULL;
1396 }
34dc7c2f 1397
a1d477c2
MA
1398 if (spa->spa_vdev_removal != NULL) {
1399 spa_vdev_removal_destroy(spa->spa_vdev_removal);
1400 spa->spa_vdev_removal = NULL;
1401 }
1402
1403 spa_condense_fini(spa);
1404
428870ff
BB
1405 bpobj_close(&spa->spa_deferred_bpobj);
1406
93cf2076
GW
1407 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1408
1409 /*
1410 * Close all vdevs.
1411 */
1412 if (spa->spa_root_vdev)
1413 vdev_free(spa->spa_root_vdev);
1414 ASSERT(spa->spa_root_vdev == NULL);
1415
34dc7c2f
BB
1416 /*
1417 * Close the dsl pool.
1418 */
1419 if (spa->spa_dsl_pool) {
1420 dsl_pool_close(spa->spa_dsl_pool);
1421 spa->spa_dsl_pool = NULL;
428870ff 1422 spa->spa_meta_objset = NULL;
34dc7c2f
BB
1423 }
1424
428870ff
BB
1425 ddt_unload(spa);
1426
fb5f0bc8
BB
1427 /*
1428 * Drop and purge level 2 cache
1429 */
1430 spa_l2cache_drop(spa);
1431
34dc7c2f
BB
1432 for (i = 0; i < spa->spa_spares.sav_count; i++)
1433 vdev_free(spa->spa_spares.sav_vdevs[i]);
1434 if (spa->spa_spares.sav_vdevs) {
1435 kmem_free(spa->spa_spares.sav_vdevs,
1436 spa->spa_spares.sav_count * sizeof (void *));
1437 spa->spa_spares.sav_vdevs = NULL;
1438 }
1439 if (spa->spa_spares.sav_config) {
1440 nvlist_free(spa->spa_spares.sav_config);
1441 spa->spa_spares.sav_config = NULL;
1442 }
b128c09f 1443 spa->spa_spares.sav_count = 0;
34dc7c2f 1444
5ffb9d1d
GW
1445 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
1446 vdev_clear_stats(spa->spa_l2cache.sav_vdevs[i]);
34dc7c2f 1447 vdev_free(spa->spa_l2cache.sav_vdevs[i]);
5ffb9d1d 1448 }
34dc7c2f
BB
1449 if (spa->spa_l2cache.sav_vdevs) {
1450 kmem_free(spa->spa_l2cache.sav_vdevs,
1451 spa->spa_l2cache.sav_count * sizeof (void *));
1452 spa->spa_l2cache.sav_vdevs = NULL;
1453 }
1454 if (spa->spa_l2cache.sav_config) {
1455 nvlist_free(spa->spa_l2cache.sav_config);
1456 spa->spa_l2cache.sav_config = NULL;
1457 }
b128c09f 1458 spa->spa_l2cache.sav_count = 0;
34dc7c2f
BB
1459
1460 spa->spa_async_suspended = 0;
fb5f0bc8 1461
a1d477c2
MA
1462 spa->spa_indirect_vdevs_loaded = B_FALSE;
1463
d96eb2b1
DM
1464 if (spa->spa_comment != NULL) {
1465 spa_strfree(spa->spa_comment);
1466 spa->spa_comment = NULL;
1467 }
1468
fb5f0bc8 1469 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
1470}
1471
1472/*
1473 * Load (or re-load) the current list of vdevs describing the active spares for
1474 * this pool. When this is called, we have some form of basic information in
1475 * 'spa_spares.sav_config'. We parse this into vdevs, try to open them, and
1476 * then re-generate a more complete list including status information.
1477 */
a1d477c2 1478void
34dc7c2f
BB
1479spa_load_spares(spa_t *spa)
1480{
1481 nvlist_t **spares;
1482 uint_t nspares;
1483 int i;
1484 vdev_t *vd, *tvd;
1485
b128c09f
BB
1486 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1487
34dc7c2f
BB
1488 /*
1489 * First, close and free any existing spare vdevs.
1490 */
1491 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1492 vd = spa->spa_spares.sav_vdevs[i];
1493
1494 /* Undo the call to spa_activate() below */
b128c09f
BB
1495 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1496 B_FALSE)) != NULL && tvd->vdev_isspare)
34dc7c2f
BB
1497 spa_spare_remove(tvd);
1498 vdev_close(vd);
1499 vdev_free(vd);
1500 }
1501
1502 if (spa->spa_spares.sav_vdevs)
1503 kmem_free(spa->spa_spares.sav_vdevs,
1504 spa->spa_spares.sav_count * sizeof (void *));
1505
1506 if (spa->spa_spares.sav_config == NULL)
1507 nspares = 0;
1508 else
1509 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
1510 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
1511
1512 spa->spa_spares.sav_count = (int)nspares;
1513 spa->spa_spares.sav_vdevs = NULL;
1514
1515 if (nspares == 0)
1516 return;
1517
1518 /*
1519 * Construct the array of vdevs, opening them to get status in the
1520 * process. For each spare, there is potentially two different vdev_t
1521 * structures associated with it: one in the list of spares (used only
1522 * for basic validation purposes) and one in the active vdev
1523 * configuration (if it's spared in). During this phase we open and
1524 * validate each vdev on the spare list. If the vdev also exists in the
1525 * active configuration, then we also mark this vdev as an active spare.
1526 */
904ea276 1527 spa->spa_spares.sav_vdevs = kmem_zalloc(nspares * sizeof (void *),
79c76d5b 1528 KM_SLEEP);
34dc7c2f
BB
1529 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1530 VERIFY(spa_config_parse(spa, &vd, spares[i], NULL, 0,
1531 VDEV_ALLOC_SPARE) == 0);
1532 ASSERT(vd != NULL);
1533
1534 spa->spa_spares.sav_vdevs[i] = vd;
1535
b128c09f
BB
1536 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1537 B_FALSE)) != NULL) {
34dc7c2f
BB
1538 if (!tvd->vdev_isspare)
1539 spa_spare_add(tvd);
1540
1541 /*
1542 * We only mark the spare active if we were successfully
1543 * able to load the vdev. Otherwise, importing a pool
1544 * with a bad active spare would result in strange
1545 * behavior, because multiple pool would think the spare
1546 * is actively in use.
1547 *
1548 * There is a vulnerability here to an equally bizarre
1549 * circumstance, where a dead active spare is later
1550 * brought back to life (onlined or otherwise). Given
1551 * the rarity of this scenario, and the extra complexity
1552 * it adds, we ignore the possibility.
1553 */
1554 if (!vdev_is_dead(tvd))
1555 spa_spare_activate(tvd);
1556 }
1557
b128c09f 1558 vd->vdev_top = vd;
9babb374 1559 vd->vdev_aux = &spa->spa_spares;
b128c09f 1560
34dc7c2f
BB
1561 if (vdev_open(vd) != 0)
1562 continue;
1563
34dc7c2f
BB
1564 if (vdev_validate_aux(vd) == 0)
1565 spa_spare_add(vd);
1566 }
1567
1568 /*
1569 * Recompute the stashed list of spares, with status information
1570 * this time.
1571 */
1572 VERIFY(nvlist_remove(spa->spa_spares.sav_config, ZPOOL_CONFIG_SPARES,
1573 DATA_TYPE_NVLIST_ARRAY) == 0);
1574
1575 spares = kmem_alloc(spa->spa_spares.sav_count * sizeof (void *),
79c76d5b 1576 KM_SLEEP);
34dc7c2f
BB
1577 for (i = 0; i < spa->spa_spares.sav_count; i++)
1578 spares[i] = vdev_config_generate(spa,
428870ff 1579 spa->spa_spares.sav_vdevs[i], B_TRUE, VDEV_CONFIG_SPARE);
34dc7c2f
BB
1580 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
1581 ZPOOL_CONFIG_SPARES, spares, spa->spa_spares.sav_count) == 0);
1582 for (i = 0; i < spa->spa_spares.sav_count; i++)
1583 nvlist_free(spares[i]);
1584 kmem_free(spares, spa->spa_spares.sav_count * sizeof (void *));
1585}
1586
1587/*
1588 * Load (or re-load) the current list of vdevs describing the active l2cache for
1589 * this pool. When this is called, we have some form of basic information in
1590 * 'spa_l2cache.sav_config'. We parse this into vdevs, try to open them, and
1591 * then re-generate a more complete list including status information.
1592 * Devices which are already active have their details maintained, and are
1593 * not re-opened.
1594 */
a1d477c2 1595void
34dc7c2f
BB
1596spa_load_l2cache(spa_t *spa)
1597{
460f239e 1598 nvlist_t **l2cache = NULL;
34dc7c2f
BB
1599 uint_t nl2cache;
1600 int i, j, oldnvdevs;
9babb374 1601 uint64_t guid;
a117a6d6 1602 vdev_t *vd, **oldvdevs, **newvdevs;
34dc7c2f
BB
1603 spa_aux_vdev_t *sav = &spa->spa_l2cache;
1604
b128c09f
BB
1605 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1606
34dc7c2f
BB
1607 oldvdevs = sav->sav_vdevs;
1608 oldnvdevs = sav->sav_count;
1609 sav->sav_vdevs = NULL;
1610 sav->sav_count = 0;
1611
67d60824
NB
1612 if (sav->sav_config == NULL) {
1613 nl2cache = 0;
1614 newvdevs = NULL;
1615 goto out;
1616 }
1617
1618 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
1619 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
1620 newvdevs = kmem_alloc(nl2cache * sizeof (void *), KM_SLEEP);
1621
34dc7c2f
BB
1622 /*
1623 * Process new nvlist of vdevs.
1624 */
1625 for (i = 0; i < nl2cache; i++) {
1626 VERIFY(nvlist_lookup_uint64(l2cache[i], ZPOOL_CONFIG_GUID,
1627 &guid) == 0);
1628
1629 newvdevs[i] = NULL;
1630 for (j = 0; j < oldnvdevs; j++) {
1631 vd = oldvdevs[j];
1632 if (vd != NULL && guid == vd->vdev_guid) {
1633 /*
1634 * Retain previous vdev for add/remove ops.
1635 */
1636 newvdevs[i] = vd;
1637 oldvdevs[j] = NULL;
1638 break;
1639 }
1640 }
1641
1642 if (newvdevs[i] == NULL) {
1643 /*
1644 * Create new vdev
1645 */
1646 VERIFY(spa_config_parse(spa, &vd, l2cache[i], NULL, 0,
1647 VDEV_ALLOC_L2CACHE) == 0);
1648 ASSERT(vd != NULL);
1649 newvdevs[i] = vd;
1650
1651 /*
1652 * Commit this vdev as an l2cache device,
1653 * even if it fails to open.
1654 */
1655 spa_l2cache_add(vd);
1656
b128c09f
BB
1657 vd->vdev_top = vd;
1658 vd->vdev_aux = sav;
1659
1660 spa_l2cache_activate(vd);
1661
34dc7c2f
BB
1662 if (vdev_open(vd) != 0)
1663 continue;
1664
34dc7c2f
BB
1665 (void) vdev_validate_aux(vd);
1666
9babb374
BB
1667 if (!vdev_is_dead(vd))
1668 l2arc_add_vdev(spa, vd);
34dc7c2f
BB
1669 }
1670 }
1671
67d60824
NB
1672 sav->sav_vdevs = newvdevs;
1673 sav->sav_count = (int)nl2cache;
1674
1675 /*
1676 * Recompute the stashed list of l2cache devices, with status
1677 * information this time.
1678 */
1679 VERIFY(nvlist_remove(sav->sav_config, ZPOOL_CONFIG_L2CACHE,
1680 DATA_TYPE_NVLIST_ARRAY) == 0);
1681
460f239e
D
1682 if (sav->sav_count > 0)
1683 l2cache = kmem_alloc(sav->sav_count * sizeof (void *),
1684 KM_SLEEP);
67d60824
NB
1685 for (i = 0; i < sav->sav_count; i++)
1686 l2cache[i] = vdev_config_generate(spa,
1687 sav->sav_vdevs[i], B_TRUE, VDEV_CONFIG_L2CACHE);
1688 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
1689 ZPOOL_CONFIG_L2CACHE, l2cache, sav->sav_count) == 0);
1690
1691out:
34dc7c2f
BB
1692 /*
1693 * Purge vdevs that were dropped
1694 */
1695 for (i = 0; i < oldnvdevs; i++) {
1696 uint64_t pool;
1697
1698 vd = oldvdevs[i];
1699 if (vd != NULL) {
5ffb9d1d
GW
1700 ASSERT(vd->vdev_isl2cache);
1701
fb5f0bc8
BB
1702 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
1703 pool != 0ULL && l2arc_vdev_present(vd))
34dc7c2f 1704 l2arc_remove_vdev(vd);
5ffb9d1d
GW
1705 vdev_clear_stats(vd);
1706 vdev_free(vd);
34dc7c2f
BB
1707 }
1708 }
1709
1710 if (oldvdevs)
1711 kmem_free(oldvdevs, oldnvdevs * sizeof (void *));
1712
34dc7c2f
BB
1713 for (i = 0; i < sav->sav_count; i++)
1714 nvlist_free(l2cache[i]);
1715 if (sav->sav_count)
1716 kmem_free(l2cache, sav->sav_count * sizeof (void *));
1717}
1718
1719static int
1720load_nvlist(spa_t *spa, uint64_t obj, nvlist_t **value)
1721{
1722 dmu_buf_t *db;
1723 char *packed = NULL;
1724 size_t nvsize = 0;
1725 int error;
1726 *value = NULL;
1727
c3275b56
BB
1728 error = dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db);
1729 if (error)
1730 return (error);
1731
34dc7c2f
BB
1732 nvsize = *(uint64_t *)db->db_data;
1733 dmu_buf_rele(db, FTAG);
1734
77aef6f6 1735 packed = vmem_alloc(nvsize, KM_SLEEP);
9babb374
BB
1736 error = dmu_read(spa->spa_meta_objset, obj, 0, nvsize, packed,
1737 DMU_READ_PREFETCH);
34dc7c2f
BB
1738 if (error == 0)
1739 error = nvlist_unpack(packed, nvsize, value, 0);
77aef6f6 1740 vmem_free(packed, nvsize);
34dc7c2f
BB
1741
1742 return (error);
1743}
1744
1745/*
1746 * Checks to see if the given vdev could not be opened, in which case we post a
1747 * sysevent to notify the autoreplace code that the device has been removed.
1748 */
1749static void
1750spa_check_removed(vdev_t *vd)
1751{
1c27024e 1752 for (int c = 0; c < vd->vdev_children; c++)
34dc7c2f
BB
1753 spa_check_removed(vd->vdev_child[c]);
1754
7011fb60 1755 if (vd->vdev_ops->vdev_op_leaf && vdev_is_dead(vd) &&
a1d477c2 1756 vdev_is_concrete(vd)) {
fb390aaf 1757 zfs_post_autoreplace(vd->vdev_spa, vd);
12fa0466 1758 spa_event_notify(vd->vdev_spa, vd, NULL, ESC_ZFS_VDEV_CHECK);
34dc7c2f
BB
1759 }
1760}
1761
e0ab3ab5
JS
1762static void
1763spa_config_valid_zaps(vdev_t *vd, vdev_t *mvd)
1764{
e0ab3ab5
JS
1765 ASSERT3U(vd->vdev_children, ==, mvd->vdev_children);
1766
1767 vd->vdev_top_zap = mvd->vdev_top_zap;
1768 vd->vdev_leaf_zap = mvd->vdev_leaf_zap;
1769
1c27024e 1770 for (uint64_t i = 0; i < vd->vdev_children; i++) {
e0ab3ab5
JS
1771 spa_config_valid_zaps(vd->vdev_child[i], mvd->vdev_child[i]);
1772 }
1773}
1774
9babb374 1775/*
572e2857 1776 * Validate the current config against the MOS config
9babb374 1777 */
572e2857
BB
1778static boolean_t
1779spa_config_valid(spa_t *spa, nvlist_t *config)
9babb374 1780{
572e2857
BB
1781 vdev_t *mrvd, *rvd = spa->spa_root_vdev;
1782 nvlist_t *nv;
1783
1784 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nv) == 0);
1785
1786 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1787 VERIFY(spa_config_parse(spa, &mrvd, nv, NULL, 0, VDEV_ALLOC_LOAD) == 0);
1788
1789 ASSERT3U(rvd->vdev_children, ==, mrvd->vdev_children);
9babb374 1790
428870ff 1791 /*
572e2857
BB
1792 * If we're doing a normal import, then build up any additional
1793 * diagnostic information about missing devices in this config.
1794 * We'll pass this up to the user for further processing.
428870ff 1795 */
572e2857
BB
1796 if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG)) {
1797 nvlist_t **child, *nv;
1798 uint64_t idx = 0;
1799
160987b5 1800 child = kmem_alloc(rvd->vdev_children * sizeof (nvlist_t *),
79c76d5b
BB
1801 KM_SLEEP);
1802 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
572e2857 1803
1c27024e 1804 for (int c = 0; c < rvd->vdev_children; c++) {
572e2857
BB
1805 vdev_t *tvd = rvd->vdev_child[c];
1806 vdev_t *mtvd = mrvd->vdev_child[c];
1807
1808 if (tvd->vdev_ops == &vdev_missing_ops &&
1809 mtvd->vdev_ops != &vdev_missing_ops &&
1810 mtvd->vdev_islog)
1811 child[idx++] = vdev_config_generate(spa, mtvd,
1812 B_FALSE, 0);
1813 }
9babb374 1814
572e2857
BB
1815 if (idx) {
1816 VERIFY(nvlist_add_nvlist_array(nv,
1817 ZPOOL_CONFIG_CHILDREN, child, idx) == 0);
1818 VERIFY(nvlist_add_nvlist(spa->spa_load_info,
1819 ZPOOL_CONFIG_MISSING_DEVICES, nv) == 0);
1820
1c27024e 1821 for (int i = 0; i < idx; i++)
572e2857
BB
1822 nvlist_free(child[i]);
1823 }
1824 nvlist_free(nv);
1825 kmem_free(child, rvd->vdev_children * sizeof (char **));
1826 }
1827
1828 /*
1829 * Compare the root vdev tree with the information we have
1830 * from the MOS config (mrvd). Check each top-level vdev
1831 * with the corresponding MOS config top-level (mtvd).
1832 */
1c27024e 1833 for (int c = 0; c < rvd->vdev_children; c++) {
572e2857
BB
1834 vdev_t *tvd = rvd->vdev_child[c];
1835 vdev_t *mtvd = mrvd->vdev_child[c];
1836
1837 /*
1838 * Resolve any "missing" vdevs in the current configuration.
a1d477c2 1839 * Also trust the MOS config about any "indirect" vdevs.
572e2857
BB
1840 * If we find that the MOS config has more accurate information
1841 * about the top-level vdev then use that vdev instead.
1842 */
a1d477c2
MA
1843 if ((tvd->vdev_ops == &vdev_missing_ops &&
1844 mtvd->vdev_ops != &vdev_missing_ops) ||
1845 (mtvd->vdev_ops == &vdev_indirect_ops &&
1846 tvd->vdev_ops != &vdev_indirect_ops)) {
572e2857
BB
1847
1848 /*
1849 * Device specific actions.
1850 */
1851 if (mtvd->vdev_islog) {
a1d477c2
MA
1852 if (!(spa->spa_import_flags &
1853 ZFS_IMPORT_MISSING_LOG)) {
1854 continue;
1855 }
1856
572e2857 1857 spa_set_log_state(spa, SPA_LOG_CLEAR);
a1d477c2 1858 } else if (mtvd->vdev_ops != &vdev_indirect_ops) {
572e2857
BB
1859 continue;
1860 }
1861
1862 /*
1863 * Swap the missing vdev with the data we were
1864 * able to obtain from the MOS config.
1865 */
1866 vdev_remove_child(rvd, tvd);
1867 vdev_remove_child(mrvd, mtvd);
1868
1869 vdev_add_child(rvd, mtvd);
1870 vdev_add_child(mrvd, tvd);
1871
572e2857 1872 vdev_reopen(rvd);
e0ab3ab5
JS
1873 } else {
1874 if (mtvd->vdev_islog) {
1875 /*
1876 * Load the slog device's state from the MOS
1877 * config since it's possible that the label
1878 * does not contain the most up-to-date
1879 * information.
1880 */
1881 vdev_load_log_state(tvd, mtvd);
1882 vdev_reopen(tvd);
1883 }
1884
572e2857 1885 /*
e0ab3ab5 1886 * Per-vdev ZAP info is stored exclusively in the MOS.
572e2857 1887 */
e0ab3ab5 1888 spa_config_valid_zaps(tvd, mtvd);
572e2857 1889 }
a1d477c2
MA
1890
1891 /*
1892 * Never trust this info from userland; always use what's
1893 * in the MOS. This prevents it from getting out of sync
1894 * with the rest of the info in the MOS.
1895 */
1896 tvd->vdev_removing = mtvd->vdev_removing;
1897 tvd->vdev_indirect_config = mtvd->vdev_indirect_config;
9babb374 1898 }
e0ab3ab5 1899
572e2857 1900 vdev_free(mrvd);
428870ff 1901 spa_config_exit(spa, SCL_ALL, FTAG);
572e2857
BB
1902
1903 /*
1904 * Ensure we were able to validate the config.
1905 */
1906 return (rvd->vdev_guid_sum == spa->spa_uberblock.ub_guid_sum);
9babb374
BB
1907}
1908
b128c09f
BB
1909/*
1910 * Check for missing log devices
1911 */
13fe0198 1912static boolean_t
b128c09f
BB
1913spa_check_logs(spa_t *spa)
1914{
13fe0198 1915 boolean_t rv = B_FALSE;
9c43027b 1916 dsl_pool_t *dp = spa_get_dsl(spa);
13fe0198 1917
b128c09f 1918 switch (spa->spa_log_state) {
e75c13c3
BB
1919 default:
1920 break;
b128c09f
BB
1921 case SPA_LOG_MISSING:
1922 /* need to recheck in case slog has been restored */
1923 case SPA_LOG_UNKNOWN:
9c43027b
AJ
1924 rv = (dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
1925 zil_check_log_chain, NULL, DS_FIND_CHILDREN) != 0);
13fe0198 1926 if (rv)
428870ff 1927 spa_set_log_state(spa, SPA_LOG_MISSING);
b128c09f 1928 break;
b128c09f 1929 }
13fe0198 1930 return (rv);
b128c09f
BB
1931}
1932
428870ff
BB
1933static boolean_t
1934spa_passivate_log(spa_t *spa)
34dc7c2f 1935{
428870ff
BB
1936 vdev_t *rvd = spa->spa_root_vdev;
1937 boolean_t slog_found = B_FALSE;
b128c09f 1938
428870ff 1939 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
fb5f0bc8 1940
428870ff
BB
1941 if (!spa_has_slogs(spa))
1942 return (B_FALSE);
34dc7c2f 1943
1c27024e 1944 for (int c = 0; c < rvd->vdev_children; c++) {
428870ff
BB
1945 vdev_t *tvd = rvd->vdev_child[c];
1946 metaslab_group_t *mg = tvd->vdev_mg;
34dc7c2f 1947
428870ff
BB
1948 if (tvd->vdev_islog) {
1949 metaslab_group_passivate(mg);
1950 slog_found = B_TRUE;
1951 }
34dc7c2f
BB
1952 }
1953
428870ff
BB
1954 return (slog_found);
1955}
34dc7c2f 1956
428870ff
BB
1957static void
1958spa_activate_log(spa_t *spa)
1959{
1960 vdev_t *rvd = spa->spa_root_vdev;
34dc7c2f 1961
428870ff
BB
1962 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1963
1c27024e 1964 for (int c = 0; c < rvd->vdev_children; c++) {
428870ff
BB
1965 vdev_t *tvd = rvd->vdev_child[c];
1966 metaslab_group_t *mg = tvd->vdev_mg;
1967
1968 if (tvd->vdev_islog)
1969 metaslab_group_activate(mg);
34dc7c2f 1970 }
428870ff 1971}
34dc7c2f 1972
428870ff 1973int
a1d477c2 1974spa_reset_logs(spa_t *spa)
428870ff 1975{
13fe0198 1976 int error;
9babb374 1977
a1d477c2 1978 error = dmu_objset_find(spa_name(spa), zil_reset,
13fe0198
MA
1979 NULL, DS_FIND_CHILDREN);
1980 if (error == 0) {
428870ff
BB
1981 /*
1982 * We successfully offlined the log device, sync out the
1983 * current txg so that the "stubby" block can be removed
1984 * by zil_sync().
1985 */
1986 txg_wait_synced(spa->spa_dsl_pool, 0);
1987 }
1988 return (error);
1989}
34dc7c2f 1990
428870ff
BB
1991static void
1992spa_aux_check_removed(spa_aux_vdev_t *sav)
1993{
1c27024e 1994 for (int i = 0; i < sav->sav_count; i++)
428870ff
BB
1995 spa_check_removed(sav->sav_vdevs[i]);
1996}
34dc7c2f 1997
428870ff
BB
1998void
1999spa_claim_notify(zio_t *zio)
2000{
2001 spa_t *spa = zio->io_spa;
34dc7c2f 2002
428870ff
BB
2003 if (zio->io_error)
2004 return;
34dc7c2f 2005
428870ff
BB
2006 mutex_enter(&spa->spa_props_lock); /* any mutex will do */
2007 if (spa->spa_claim_max_txg < zio->io_bp->blk_birth)
2008 spa->spa_claim_max_txg = zio->io_bp->blk_birth;
2009 mutex_exit(&spa->spa_props_lock);
2010}
34dc7c2f 2011
428870ff
BB
2012typedef struct spa_load_error {
2013 uint64_t sle_meta_count;
2014 uint64_t sle_data_count;
2015} spa_load_error_t;
34dc7c2f 2016
428870ff
BB
2017static void
2018spa_load_verify_done(zio_t *zio)
2019{
2020 blkptr_t *bp = zio->io_bp;
2021 spa_load_error_t *sle = zio->io_private;
2022 dmu_object_type_t type = BP_GET_TYPE(bp);
2023 int error = zio->io_error;
dea377c0 2024 spa_t *spa = zio->io_spa;
34dc7c2f 2025
a6255b7f 2026 abd_free(zio->io_abd);
428870ff 2027 if (error) {
9ae529ec 2028 if ((BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type)) &&
428870ff 2029 type != DMU_OT_INTENT_LOG)
bc89ac84 2030 atomic_inc_64(&sle->sle_meta_count);
428870ff 2031 else
bc89ac84 2032 atomic_inc_64(&sle->sle_data_count);
34dc7c2f 2033 }
dea377c0
MA
2034
2035 mutex_enter(&spa->spa_scrub_lock);
d4a72f23 2036 spa->spa_load_verify_ios--;
dea377c0
MA
2037 cv_broadcast(&spa->spa_scrub_io_cv);
2038 mutex_exit(&spa->spa_scrub_lock);
428870ff 2039}
34dc7c2f 2040
dea377c0
MA
2041/*
2042 * Maximum number of concurrent scrub i/os to create while verifying
2043 * a pool while importing it.
2044 */
2045int spa_load_verify_maxinflight = 10000;
2046int spa_load_verify_metadata = B_TRUE;
2047int spa_load_verify_data = B_TRUE;
2048
428870ff
BB
2049/*ARGSUSED*/
2050static int
2051spa_load_verify_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
5dbd68a3 2052 const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
428870ff 2053{
fcff0f35 2054 if (bp == NULL || BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
dea377c0
MA
2055 return (0);
2056 /*
2057 * Note: normally this routine will not be called if
2058 * spa_load_verify_metadata is not set. However, it may be useful
2059 * to manually set the flag after the traversal has begun.
2060 */
2061 if (!spa_load_verify_metadata)
2062 return (0);
a6255b7f 2063 if (!BP_IS_METADATA(bp) && !spa_load_verify_data)
dea377c0
MA
2064 return (0);
2065
1c27024e
DB
2066 zio_t *rio = arg;
2067 size_t size = BP_GET_PSIZE(bp);
dea377c0
MA
2068
2069 mutex_enter(&spa->spa_scrub_lock);
d4a72f23 2070 while (spa->spa_load_verify_ios >= spa_load_verify_maxinflight)
dea377c0 2071 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
d4a72f23 2072 spa->spa_load_verify_ios++;
dea377c0
MA
2073 mutex_exit(&spa->spa_scrub_lock);
2074
a6255b7f 2075 zio_nowait(zio_read(rio, spa, bp, abd_alloc_for_io(size, B_FALSE), size,
dea377c0
MA
2076 spa_load_verify_done, rio->io_private, ZIO_PRIORITY_SCRUB,
2077 ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CANFAIL |
2078 ZIO_FLAG_SCRUB | ZIO_FLAG_RAW, zb));
428870ff
BB
2079 return (0);
2080}
34dc7c2f 2081
d1d19c78
PD
2082/* ARGSUSED */
2083int
2084verify_dataset_name_len(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
2085{
2086 if (dsl_dataset_namelen(ds) >= ZFS_MAX_DATASET_NAME_LEN)
2087 return (SET_ERROR(ENAMETOOLONG));
2088
2089 return (0);
2090}
2091
428870ff
BB
2092static int
2093spa_load_verify(spa_t *spa)
2094{
2095 zio_t *rio;
2096 spa_load_error_t sle = { 0 };
2097 zpool_rewind_policy_t policy;
2098 boolean_t verify_ok = B_FALSE;
dea377c0 2099 int error = 0;
34dc7c2f 2100
428870ff 2101 zpool_get_rewind_policy(spa->spa_config, &policy);
34dc7c2f 2102
428870ff
BB
2103 if (policy.zrp_request & ZPOOL_NEVER_REWIND)
2104 return (0);
34dc7c2f 2105
d1d19c78
PD
2106 dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
2107 error = dmu_objset_find_dp(spa->spa_dsl_pool,
2108 spa->spa_dsl_pool->dp_root_dir_obj, verify_dataset_name_len, NULL,
2109 DS_FIND_CHILDREN);
2110 dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
2111 if (error != 0)
2112 return (error);
2113
428870ff
BB
2114 rio = zio_root(spa, NULL, &sle,
2115 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
34dc7c2f 2116
dea377c0
MA
2117 if (spa_load_verify_metadata) {
2118 error = traverse_pool(spa, spa->spa_verify_min_txg,
b5256303
TC
2119 TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
2120 TRAVERSE_NO_DECRYPT, spa_load_verify_cb, rio);
dea377c0 2121 }
428870ff
BB
2122
2123 (void) zio_wait(rio);
2124
2125 spa->spa_load_meta_errors = sle.sle_meta_count;
2126 spa->spa_load_data_errors = sle.sle_data_count;
2127
2128 if (!error && sle.sle_meta_count <= policy.zrp_maxmeta &&
2129 sle.sle_data_count <= policy.zrp_maxdata) {
572e2857
BB
2130 int64_t loss = 0;
2131
428870ff
BB
2132 verify_ok = B_TRUE;
2133 spa->spa_load_txg = spa->spa_uberblock.ub_txg;
2134 spa->spa_load_txg_ts = spa->spa_uberblock.ub_timestamp;
572e2857
BB
2135
2136 loss = spa->spa_last_ubsync_txg_ts - spa->spa_load_txg_ts;
2137 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2138 ZPOOL_CONFIG_LOAD_TIME, spa->spa_load_txg_ts) == 0);
2139 VERIFY(nvlist_add_int64(spa->spa_load_info,
2140 ZPOOL_CONFIG_REWIND_TIME, loss) == 0);
2141 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2142 ZPOOL_CONFIG_LOAD_DATA_ERRORS, sle.sle_data_count) == 0);
428870ff
BB
2143 } else {
2144 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg;
2145 }
2146
2147 if (error) {
2148 if (error != ENXIO && error != EIO)
2e528b49 2149 error = SET_ERROR(EIO);
428870ff
BB
2150 return (error);
2151 }
2152
2153 return (verify_ok ? 0 : EIO);
2154}
2155
2156/*
2157 * Find a value in the pool props object.
2158 */
2159static void
2160spa_prop_find(spa_t *spa, zpool_prop_t prop, uint64_t *val)
2161{
2162 (void) zap_lookup(spa->spa_meta_objset, spa->spa_pool_props_object,
2163 zpool_prop_to_name(prop), sizeof (uint64_t), 1, val);
2164}
2165
2166/*
2167 * Find a value in the pool directory object.
2168 */
2169static int
2170spa_dir_prop(spa_t *spa, const char *name, uint64_t *val)
2171{
2172 return (zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
2173 name, sizeof (uint64_t), 1, val));
2174}
2175
2176static int
2177spa_vdev_err(vdev_t *vdev, vdev_aux_t aux, int err)
2178{
2179 vdev_set_state(vdev, B_TRUE, VDEV_STATE_CANT_OPEN, aux);
a1d477c2 2180 return (SET_ERROR(err));
428870ff
BB
2181}
2182
2183/*
2184 * Fix up config after a partly-completed split. This is done with the
2185 * ZPOOL_CONFIG_SPLIT nvlist. Both the splitting pool and the split-off
2186 * pool have that entry in their config, but only the splitting one contains
2187 * a list of all the guids of the vdevs that are being split off.
2188 *
2189 * This function determines what to do with that list: either rejoin
2190 * all the disks to the pool, or complete the splitting process. To attempt
2191 * the rejoin, each disk that is offlined is marked online again, and
2192 * we do a reopen() call. If the vdev label for every disk that was
2193 * marked online indicates it was successfully split off (VDEV_AUX_SPLIT_POOL)
2194 * then we call vdev_split() on each disk, and complete the split.
2195 *
2196 * Otherwise we leave the config alone, with all the vdevs in place in
2197 * the original pool.
2198 */
2199static void
2200spa_try_repair(spa_t *spa, nvlist_t *config)
2201{
2202 uint_t extracted;
2203 uint64_t *glist;
2204 uint_t i, gcount;
2205 nvlist_t *nvl;
2206 vdev_t **vd;
2207 boolean_t attempt_reopen;
2208
2209 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) != 0)
2210 return;
2211
2212 /* check that the config is complete */
2213 if (nvlist_lookup_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
2214 &glist, &gcount) != 0)
2215 return;
2216
79c76d5b 2217 vd = kmem_zalloc(gcount * sizeof (vdev_t *), KM_SLEEP);
428870ff
BB
2218
2219 /* attempt to online all the vdevs & validate */
2220 attempt_reopen = B_TRUE;
2221 for (i = 0; i < gcount; i++) {
2222 if (glist[i] == 0) /* vdev is hole */
2223 continue;
2224
2225 vd[i] = spa_lookup_by_guid(spa, glist[i], B_FALSE);
2226 if (vd[i] == NULL) {
2227 /*
2228 * Don't bother attempting to reopen the disks;
2229 * just do the split.
2230 */
2231 attempt_reopen = B_FALSE;
2232 } else {
2233 /* attempt to re-online it */
2234 vd[i]->vdev_offline = B_FALSE;
2235 }
2236 }
2237
2238 if (attempt_reopen) {
2239 vdev_reopen(spa->spa_root_vdev);
2240
2241 /* check each device to see what state it's in */
2242 for (extracted = 0, i = 0; i < gcount; i++) {
2243 if (vd[i] != NULL &&
2244 vd[i]->vdev_stat.vs_aux != VDEV_AUX_SPLIT_POOL)
2245 break;
2246 ++extracted;
2247 }
2248 }
2249
2250 /*
2251 * If every disk has been moved to the new pool, or if we never
2252 * even attempted to look at them, then we split them off for
2253 * good.
2254 */
2255 if (!attempt_reopen || gcount == extracted) {
2256 for (i = 0; i < gcount; i++)
2257 if (vd[i] != NULL)
2258 vdev_split(vd[i]);
2259 vdev_reopen(spa->spa_root_vdev);
2260 }
2261
2262 kmem_free(vd, gcount * sizeof (vdev_t *));
2263}
2264
2265static int
2266spa_load(spa_t *spa, spa_load_state_t state, spa_import_type_t type,
2267 boolean_t mosconfig)
2268{
2269 nvlist_t *config = spa->spa_config;
2270 char *ereport = FM_EREPORT_ZFS_POOL;
d96eb2b1 2271 char *comment;
428870ff
BB
2272 int error;
2273 uint64_t pool_guid;
2274 nvlist_t *nvl;
2275
2276 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid))
2e528b49 2277 return (SET_ERROR(EINVAL));
428870ff 2278
d96eb2b1
DM
2279 ASSERT(spa->spa_comment == NULL);
2280 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2281 spa->spa_comment = spa_strdup(comment);
2282
428870ff
BB
2283 /*
2284 * Versioning wasn't explicitly added to the label until later, so if
2285 * it's not present treat it as the initial version.
2286 */
2287 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
2288 &spa->spa_ubsync.ub_version) != 0)
2289 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
2290
2291 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
2292 &spa->spa_config_txg);
2293
2294 if ((state == SPA_LOAD_IMPORT || state == SPA_LOAD_TRYIMPORT) &&
2295 spa_guid_exists(pool_guid, 0)) {
2e528b49 2296 error = SET_ERROR(EEXIST);
428870ff 2297 } else {
3541dc6d 2298 spa->spa_config_guid = pool_guid;
428870ff
BB
2299
2300 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT,
2301 &nvl) == 0) {
2302 VERIFY(nvlist_dup(nvl, &spa->spa_config_splitting,
79c76d5b 2303 KM_SLEEP) == 0);
428870ff
BB
2304 }
2305
9ae529ec
CS
2306 nvlist_free(spa->spa_load_info);
2307 spa->spa_load_info = fnvlist_alloc();
2308
572e2857 2309 gethrestime(&spa->spa_loaded_ts);
428870ff
BB
2310 error = spa_load_impl(spa, pool_guid, config, state, type,
2311 mosconfig, &ereport);
2312 }
2313
0c66c32d
JG
2314 /*
2315 * Don't count references from objsets that are already closed
2316 * and are making their way through the eviction process.
2317 */
2318 spa_evicting_os_wait(spa);
428870ff 2319 spa->spa_minref = refcount_count(&spa->spa_refcount);
572e2857
BB
2320 if (error) {
2321 if (error != EEXIST) {
2322 spa->spa_loaded_ts.tv_sec = 0;
2323 spa->spa_loaded_ts.tv_nsec = 0;
2324 }
2325 if (error != EBADF) {
b5256303 2326 zfs_ereport_post(ereport, spa, NULL, NULL, NULL, 0, 0);
572e2857
BB
2327 }
2328 }
428870ff
BB
2329 spa->spa_load_state = error ? SPA_LOAD_ERROR : SPA_LOAD_NONE;
2330 spa->spa_ena = 0;
2331
2332 return (error);
2333}
2334
33cf67cd 2335#ifdef ZFS_DEBUG
e0ab3ab5
JS
2336/*
2337 * Count the number of per-vdev ZAPs associated with all of the vdevs in the
2338 * vdev tree rooted in the given vd, and ensure that each ZAP is present in the
2339 * spa's per-vdev ZAP list.
2340 */
2341static uint64_t
2342vdev_count_verify_zaps(vdev_t *vd)
2343{
2344 spa_t *spa = vd->vdev_spa;
2345 uint64_t total = 0;
e0ab3ab5
JS
2346
2347 if (vd->vdev_top_zap != 0) {
2348 total++;
2349 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2350 spa->spa_all_vdev_zaps, vd->vdev_top_zap));
2351 }
2352 if (vd->vdev_leaf_zap != 0) {
2353 total++;
2354 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2355 spa->spa_all_vdev_zaps, vd->vdev_leaf_zap));
2356 }
2357
1c27024e 2358 for (uint64_t i = 0; i < vd->vdev_children; i++) {
e0ab3ab5
JS
2359 total += vdev_count_verify_zaps(vd->vdev_child[i]);
2360 }
2361
2362 return (total);
2363}
33cf67cd 2364#endif
e0ab3ab5 2365
379ca9cf
OF
2366/*
2367 * Determine whether the activity check is required.
2368 */
2369static boolean_t
bbffb59e
BB
2370spa_activity_check_required(spa_t *spa, uberblock_t *ub, nvlist_t *label,
2371 nvlist_t *config)
379ca9cf
OF
2372{
2373 uint64_t state = 0;
2374 uint64_t hostid = 0;
2375 uint64_t tryconfig_txg = 0;
2376 uint64_t tryconfig_timestamp = 0;
2377 nvlist_t *nvinfo;
2378
2379 if (nvlist_exists(config, ZPOOL_CONFIG_LOAD_INFO)) {
2380 nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
2381 (void) nvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_MMP_TXG,
2382 &tryconfig_txg);
2383 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
2384 &tryconfig_timestamp);
2385 }
2386
2387 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE, &state);
379ca9cf
OF
2388
2389 /*
2390 * Disable the MMP activity check - This is used by zdb which
2391 * is intended to be used on potentially active pools.
2392 */
2393 if (spa->spa_import_flags & ZFS_IMPORT_SKIP_MMP)
2394 return (B_FALSE);
2395
2396 /*
2397 * Skip the activity check when the MMP feature is disabled.
2398 */
2399 if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay == 0)
2400 return (B_FALSE);
2401 /*
2402 * If the tryconfig_* values are nonzero, they are the results of an
2403 * earlier tryimport. If they match the uberblock we just found, then
2404 * the pool has not changed and we return false so we do not test a
2405 * second time.
2406 */
2407 if (tryconfig_txg && tryconfig_txg == ub->ub_txg &&
2408 tryconfig_timestamp && tryconfig_timestamp == ub->ub_timestamp)
2409 return (B_FALSE);
2410
2411 /*
2412 * Allow the activity check to be skipped when importing the pool
bbffb59e
BB
2413 * on the same host which last imported it. Since the hostid from
2414 * configuration may be stale use the one read from the label.
379ca9cf 2415 */
bbffb59e
BB
2416 if (nvlist_exists(label, ZPOOL_CONFIG_HOSTID))
2417 hostid = fnvlist_lookup_uint64(label, ZPOOL_CONFIG_HOSTID);
2418
379ca9cf
OF
2419 if (hostid == spa_get_hostid())
2420 return (B_FALSE);
2421
2422 /*
2423 * Skip the activity test when the pool was cleanly exported.
2424 */
2425 if (state != POOL_STATE_ACTIVE)
2426 return (B_FALSE);
2427
2428 return (B_TRUE);
2429}
2430
2431/*
2432 * Perform the import activity check. If the user canceled the import or
2433 * we detected activity then fail.
2434 */
2435static int
2436spa_activity_check(spa_t *spa, uberblock_t *ub, nvlist_t *config)
2437{
2438 uint64_t import_intervals = MAX(zfs_multihost_import_intervals, 1);
2439 uint64_t txg = ub->ub_txg;
2440 uint64_t timestamp = ub->ub_timestamp;
2441 uint64_t import_delay = NANOSEC;
2442 hrtime_t import_expire;
2443 nvlist_t *mmp_label = NULL;
2444 vdev_t *rvd = spa->spa_root_vdev;
2445 kcondvar_t cv;
2446 kmutex_t mtx;
2447 int error = 0;
2448
2449 cv_init(&cv, NULL, CV_DEFAULT, NULL);
2450 mutex_init(&mtx, NULL, MUTEX_DEFAULT, NULL);
2451 mutex_enter(&mtx);
2452
2453 /*
2454 * If ZPOOL_CONFIG_MMP_TXG is present an activity check was performed
2455 * during the earlier tryimport. If the txg recorded there is 0 then
2456 * the pool is known to be active on another host.
2457 *
2458 * Otherwise, the pool might be in use on another node. Check for
2459 * changes in the uberblocks on disk if necessary.
2460 */
2461 if (nvlist_exists(config, ZPOOL_CONFIG_LOAD_INFO)) {
2462 nvlist_t *nvinfo = fnvlist_lookup_nvlist(config,
2463 ZPOOL_CONFIG_LOAD_INFO);
2464
2465 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_TXG) &&
2466 fnvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_MMP_TXG) == 0) {
2467 vdev_uberblock_load(rvd, ub, &mmp_label);
2468 error = SET_ERROR(EREMOTEIO);
2469 goto out;
2470 }
2471 }
2472
2473 /*
2474 * Preferentially use the zfs_multihost_interval from the node which
2475 * last imported the pool. This value is stored in an MMP uberblock as.
2476 *
2477 * ub_mmp_delay * vdev_count_leaves() == zfs_multihost_interval
2478 */
2479 if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay)
2480 import_delay = MAX(import_delay, import_intervals *
802ae562 2481 ub->ub_mmp_delay * MAX(vdev_count_leaves(spa), 1));
379ca9cf
OF
2482
2483 /* Apply a floor using the local default values. */
2484 import_delay = MAX(import_delay, import_intervals *
2485 MSEC2NSEC(MAX(zfs_multihost_interval, MMP_MIN_INTERVAL)));
2486
533ea041
OF
2487 zfs_dbgmsg("import_delay=%llu ub_mmp_delay=%llu import_intervals=%u "
2488 "leaves=%u", import_delay, ub->ub_mmp_delay, import_intervals,
2489 vdev_count_leaves(spa));
2490
379ca9cf
OF
2491 /* Add a small random factor in case of simultaneous imports (0-25%) */
2492 import_expire = gethrtime() + import_delay +
2493 (import_delay * spa_get_random(250) / 1000);
2494
2495 while (gethrtime() < import_expire) {
2496 vdev_uberblock_load(rvd, ub, &mmp_label);
2497
2498 if (txg != ub->ub_txg || timestamp != ub->ub_timestamp) {
2499 error = SET_ERROR(EREMOTEIO);
2500 break;
2501 }
2502
2503 if (mmp_label) {
2504 nvlist_free(mmp_label);
2505 mmp_label = NULL;
2506 }
2507
2508 error = cv_timedwait_sig(&cv, &mtx, ddi_get_lbolt() + hz);
2509 if (error != -1) {
2510 error = SET_ERROR(EINTR);
2511 break;
2512 }
2513 error = 0;
2514 }
2515
2516out:
2517 mutex_exit(&mtx);
2518 mutex_destroy(&mtx);
2519 cv_destroy(&cv);
2520
2521 /*
2522 * If the pool is determined to be active store the status in the
2523 * spa->spa_load_info nvlist. If the remote hostname or hostid are
2524 * available from configuration read from disk store them as well.
2525 * This allows 'zpool import' to generate a more useful message.
2526 *
2527 * ZPOOL_CONFIG_MMP_STATE - observed pool status (mandatory)
2528 * ZPOOL_CONFIG_MMP_HOSTNAME - hostname from the active pool
2529 * ZPOOL_CONFIG_MMP_HOSTID - hostid from the active pool
2530 */
2531 if (error == EREMOTEIO) {
2532 char *hostname = "<unknown>";
2533 uint64_t hostid = 0;
2534
2535 if (mmp_label) {
2536 if (nvlist_exists(mmp_label, ZPOOL_CONFIG_HOSTNAME)) {
2537 hostname = fnvlist_lookup_string(mmp_label,
2538 ZPOOL_CONFIG_HOSTNAME);
2539 fnvlist_add_string(spa->spa_load_info,
2540 ZPOOL_CONFIG_MMP_HOSTNAME, hostname);
2541 }
2542
2543 if (nvlist_exists(mmp_label, ZPOOL_CONFIG_HOSTID)) {
2544 hostid = fnvlist_lookup_uint64(mmp_label,
2545 ZPOOL_CONFIG_HOSTID);
2546 fnvlist_add_uint64(spa->spa_load_info,
2547 ZPOOL_CONFIG_MMP_HOSTID, hostid);
2548 }
2549 }
2550
2551 fnvlist_add_uint64(spa->spa_load_info,
2552 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_ACTIVE);
2553 fnvlist_add_uint64(spa->spa_load_info,
2554 ZPOOL_CONFIG_MMP_TXG, 0);
2555
2556 error = spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO);
2557 }
2558
2559 if (mmp_label)
2560 nvlist_free(mmp_label);
2561
2562 return (error);
2563}
2564
428870ff
BB
2565/*
2566 * Load an existing storage pool, using the pool's builtin spa_config as a
2567 * source of configuration information.
2568 */
bf701a83
BB
2569__attribute__((always_inline))
2570static inline int
428870ff 2571spa_load_impl(spa_t *spa, uint64_t pool_guid, nvlist_t *config,
a1d477c2 2572 spa_load_state_t state, spa_import_type_t type, boolean_t trust_config,
428870ff
BB
2573 char **ereport)
2574{
2575 int error = 0;
2576 nvlist_t *nvroot = NULL;
9ae529ec 2577 nvlist_t *label;
428870ff
BB
2578 vdev_t *rvd;
2579 uberblock_t *ub = &spa->spa_uberblock;
572e2857 2580 uint64_t children, config_cache_txg = spa->spa_config_txg;
428870ff 2581 int orig_mode = spa->spa_mode;
1c27024e 2582 int parse;
428870ff 2583 uint64_t obj;
9ae529ec 2584 boolean_t missing_feat_write = B_FALSE;
379ca9cf 2585 boolean_t activity_check = B_FALSE;
428870ff
BB
2586
2587 /*
2588 * If this is an untrusted config, access the pool in read-only mode.
2589 * This prevents things like resilvering recently removed devices.
2590 */
a1d477c2 2591 if (!trust_config)
428870ff
BB
2592 spa->spa_mode = FREAD;
2593
2594 ASSERT(MUTEX_HELD(&spa_namespace_lock));
2595
2596 spa->spa_load_state = state;
2597
2598 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvroot))
2e528b49 2599 return (SET_ERROR(EINVAL));
428870ff
BB
2600
2601 parse = (type == SPA_IMPORT_EXISTING ?
2602 VDEV_ALLOC_LOAD : VDEV_ALLOC_SPLIT);
2603
2604 /*
2605 * Create "The Godfather" zio to hold all async IOs
2606 */
e022864d
MA
2607 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
2608 KM_SLEEP);
1c27024e 2609 for (int i = 0; i < max_ncpus; i++) {
e022864d
MA
2610 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
2611 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2612 ZIO_FLAG_GODFATHER);
2613 }
428870ff
BB
2614
2615 /*
2616 * Parse the configuration into a vdev tree. We explicitly set the
2617 * value that will be returned by spa_version() since parsing the
2618 * configuration requires knowing the version number.
2619 */
2620 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2621 error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, parse);
2622 spa_config_exit(spa, SCL_ALL, FTAG);
2623
2624 if (error != 0)
2625 return (error);
2626
2627 ASSERT(spa->spa_root_vdev == rvd);
c3520e7f
MA
2628 ASSERT3U(spa->spa_min_ashift, >=, SPA_MINBLOCKSHIFT);
2629 ASSERT3U(spa->spa_max_ashift, <=, SPA_MAXBLOCKSHIFT);
428870ff
BB
2630
2631 if (type != SPA_IMPORT_ASSEMBLE) {
2632 ASSERT(spa_guid(spa) == pool_guid);
2633 }
2634
2635 /*
2636 * Try to open all vdevs, loading each label in the process.
2637 */
2638 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2639 error = vdev_open(rvd);
2640 spa_config_exit(spa, SCL_ALL, FTAG);
2641 if (error != 0)
2642 return (error);
2643
2644 /*
2645 * We need to validate the vdev labels against the configuration that
2646 * we have in hand, which is dependent on the setting of mosconfig. If
2647 * mosconfig is true then we're validating the vdev labels based on
2648 * that config. Otherwise, we're validating against the cached config
2649 * (zpool.cache) that was read when we loaded the zfs module, and then
2650 * later we will recursively call spa_load() and validate against
2651 * the vdev config.
2652 *
2653 * If we're assembling a new pool that's been split off from an
2654 * existing pool, the labels haven't yet been updated so we skip
2655 * validation for now.
2656 */
2657 if (type != SPA_IMPORT_ASSEMBLE) {
2658 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
a1d477c2 2659 error = vdev_validate(rvd, trust_config);
428870ff
BB
2660 spa_config_exit(spa, SCL_ALL, FTAG);
2661
2662 if (error != 0)
2663 return (error);
2664
2665 if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN)
2e528b49 2666 return (SET_ERROR(ENXIO));
428870ff
BB
2667 }
2668
2669 /*
2670 * Find the best uberblock.
2671 */
9ae529ec 2672 vdev_uberblock_load(rvd, ub, &label);
428870ff
BB
2673
2674 /*
2675 * If we weren't able to find a single valid uberblock, return failure.
2676 */
9ae529ec
CS
2677 if (ub->ub_txg == 0) {
2678 nvlist_free(label);
428870ff 2679 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, ENXIO));
9ae529ec 2680 }
428870ff 2681
379ca9cf
OF
2682 /*
2683 * For pools which have the multihost property on determine if the
2684 * pool is truly inactive and can be safely imported. Prevent
2685 * hosts which don't have a hostid set from importing the pool.
2686 */
bbffb59e 2687 activity_check = spa_activity_check_required(spa, ub, label, config);
379ca9cf 2688 if (activity_check) {
379ca9cf
OF
2689 if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay &&
2690 spa_get_hostid() == 0) {
2691 nvlist_free(label);
2692 fnvlist_add_uint64(spa->spa_load_info,
2693 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_NO_HOSTID);
2694 return (spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO));
2695 }
2696
e889f0f5
OF
2697 error = spa_activity_check(spa, ub, config);
2698 if (error) {
2699 nvlist_free(label);
2700 return (error);
2701 }
2702
379ca9cf
OF
2703 fnvlist_add_uint64(spa->spa_load_info,
2704 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_INACTIVE);
2705 fnvlist_add_uint64(spa->spa_load_info,
2706 ZPOOL_CONFIG_MMP_TXG, ub->ub_txg);
2707 }
2708
428870ff 2709 /*
9ae529ec 2710 * If the pool has an unsupported version we can't open it.
428870ff 2711 */
9ae529ec
CS
2712 if (!SPA_VERSION_IS_SUPPORTED(ub->ub_version)) {
2713 nvlist_free(label);
428870ff 2714 return (spa_vdev_err(rvd, VDEV_AUX_VERSION_NEWER, ENOTSUP));
9ae529ec
CS
2715 }
2716
2717 if (ub->ub_version >= SPA_VERSION_FEATURES) {
2718 nvlist_t *features;
2719
2720 /*
2721 * If we weren't able to find what's necessary for reading the
2722 * MOS in the label, return failure.
2723 */
2724 if (label == NULL || nvlist_lookup_nvlist(label,
2725 ZPOOL_CONFIG_FEATURES_FOR_READ, &features) != 0) {
2726 nvlist_free(label);
2727 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2728 ENXIO));
2729 }
2730
2731 /*
2732 * Update our in-core representation with the definitive values
2733 * from the label.
2734 */
2735 nvlist_free(spa->spa_label_features);
2736 VERIFY(nvlist_dup(features, &spa->spa_label_features, 0) == 0);
2737 }
2738
2739 nvlist_free(label);
2740
2741 /*
2742 * Look through entries in the label nvlist's features_for_read. If
2743 * there is a feature listed there which we don't understand then we
2744 * cannot open a pool.
2745 */
2746 if (ub->ub_version >= SPA_VERSION_FEATURES) {
2747 nvlist_t *unsup_feat;
9ae529ec
CS
2748
2749 VERIFY(nvlist_alloc(&unsup_feat, NV_UNIQUE_NAME, KM_SLEEP) ==
2750 0);
2751
1c27024e
DB
2752 for (nvpair_t *nvp = nvlist_next_nvpair(spa->spa_label_features,
2753 NULL); nvp != NULL;
9ae529ec
CS
2754 nvp = nvlist_next_nvpair(spa->spa_label_features, nvp)) {
2755 if (!zfeature_is_supported(nvpair_name(nvp))) {
2756 VERIFY(nvlist_add_string(unsup_feat,
2757 nvpair_name(nvp), "") == 0);
2758 }
2759 }
2760
2761 if (!nvlist_empty(unsup_feat)) {
2762 VERIFY(nvlist_add_nvlist(spa->spa_load_info,
2763 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat) == 0);
2764 nvlist_free(unsup_feat);
2765 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
2766 ENOTSUP));
2767 }
2768
2769 nvlist_free(unsup_feat);
2770 }
428870ff
BB
2771
2772 /*
2773 * If the vdev guid sum doesn't match the uberblock, we have an
572e2857
BB
2774 * incomplete configuration. We first check to see if the pool
2775 * is aware of the complete config (i.e ZPOOL_CONFIG_VDEV_CHILDREN).
2776 * If it is, defer the vdev_guid_sum check till later so we
2777 * can handle missing vdevs.
428870ff 2778 */
572e2857 2779 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VDEV_CHILDREN,
a1d477c2 2780 &children) != 0 && trust_config && type != SPA_IMPORT_ASSEMBLE &&
428870ff
BB
2781 rvd->vdev_guid_sum != ub->ub_guid_sum)
2782 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM, ENXIO));
2783
2784 if (type != SPA_IMPORT_ASSEMBLE && spa->spa_config_splitting) {
2785 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2786 spa_try_repair(spa, config);
2787 spa_config_exit(spa, SCL_ALL, FTAG);
2788 nvlist_free(spa->spa_config_splitting);
2789 spa->spa_config_splitting = NULL;
2790 }
2791
2792 /*
2793 * Initialize internal SPA structures.
2794 */
2795 spa->spa_state = POOL_STATE_ACTIVE;
2796 spa->spa_ubsync = spa->spa_uberblock;
2797 spa->spa_verify_min_txg = spa->spa_extreme_rewind ?
2798 TXG_INITIAL - 1 : spa_last_synced_txg(spa) - TXG_DEFER_SIZE - 1;
2799 spa->spa_first_txg = spa->spa_last_ubsync_txg ?
2800 spa->spa_last_ubsync_txg : spa_last_synced_txg(spa) + 1;
2801 spa->spa_claim_max_txg = spa->spa_first_txg;
2802 spa->spa_prev_software_version = ub->ub_software_version;
2803
a1d477c2
MA
2804 /*
2805 * Everything that we read before we do spa_remove_init() must
2806 * have been rewritten after the last device removal was initiated.
2807 * Otherwise we could be reading from indirect vdevs before
2808 * we have loaded their mappings.
2809 */
2810
9ae529ec 2811 error = dsl_pool_init(spa, spa->spa_first_txg, &spa->spa_dsl_pool);
428870ff
BB
2812 if (error)
2813 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2814 spa->spa_meta_objset = spa->spa_dsl_pool->dp_meta_objset;
2815
2816 if (spa_dir_prop(spa, DMU_POOL_CONFIG, &spa->spa_config_object) != 0)
2817 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2818
a1d477c2
MA
2819 /*
2820 * Validate the config, using the MOS config to fill in any
2821 * information which might be missing. If we fail to validate
2822 * the config then declare the pool unfit for use. If we're
2823 * assembling a pool from a split, the log is not transferred
2824 * over.
2825 */
2826 if (type != SPA_IMPORT_ASSEMBLE) {
2827 nvlist_t *mos_config;
2828 if (load_nvlist(spa, spa->spa_config_object, &mos_config) != 0)
2829 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2830
2831 if (!spa_config_valid(spa, mos_config)) {
2832 nvlist_free(mos_config);
2833 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM,
2834 ENXIO));
2835 }
2836 nvlist_free(mos_config);
2837
2838 /*
2839 * Now that we've validated the config, check the state of the
2840 * root vdev. If it can't be opened, it indicates one or
2841 * more toplevel vdevs are faulted.
2842 */
2843 if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN)
2844 return (SET_ERROR(ENXIO));
2845 }
2846
2847 /*
2848 * Everything that we read before spa_remove_init() must be stored
2849 * on concreted vdevs. Therefore we do this as early as possible.
2850 */
2851 if (spa_remove_init(spa) != 0)
2852 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2853
9ae529ec
CS
2854 if (spa_version(spa) >= SPA_VERSION_FEATURES) {
2855 boolean_t missing_feat_read = B_FALSE;
b9b24bb4 2856 nvlist_t *unsup_feat, *enabled_feat;
9ae529ec
CS
2857
2858 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_READ,
2859 &spa->spa_feat_for_read_obj) != 0) {
2860 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2861 }
2862
2863 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_WRITE,
2864 &spa->spa_feat_for_write_obj) != 0) {
2865 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2866 }
2867
2868 if (spa_dir_prop(spa, DMU_POOL_FEATURE_DESCRIPTIONS,
2869 &spa->spa_feat_desc_obj) != 0) {
2870 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2871 }
2872
b9b24bb4
CS
2873 enabled_feat = fnvlist_alloc();
2874 unsup_feat = fnvlist_alloc();
9ae529ec 2875
fa86b5db 2876 if (!spa_features_check(spa, B_FALSE,
b9b24bb4 2877 unsup_feat, enabled_feat))
9ae529ec
CS
2878 missing_feat_read = B_TRUE;
2879
2880 if (spa_writeable(spa) || state == SPA_LOAD_TRYIMPORT) {
fa86b5db 2881 if (!spa_features_check(spa, B_TRUE,
b9b24bb4 2882 unsup_feat, enabled_feat)) {
9ae529ec 2883 missing_feat_write = B_TRUE;
b9b24bb4 2884 }
9ae529ec
CS
2885 }
2886
b9b24bb4
CS
2887 fnvlist_add_nvlist(spa->spa_load_info,
2888 ZPOOL_CONFIG_ENABLED_FEAT, enabled_feat);
2889
9ae529ec 2890 if (!nvlist_empty(unsup_feat)) {
b9b24bb4
CS
2891 fnvlist_add_nvlist(spa->spa_load_info,
2892 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat);
9ae529ec
CS
2893 }
2894
b9b24bb4
CS
2895 fnvlist_free(enabled_feat);
2896 fnvlist_free(unsup_feat);
9ae529ec
CS
2897
2898 if (!missing_feat_read) {
2899 fnvlist_add_boolean(spa->spa_load_info,
2900 ZPOOL_CONFIG_CAN_RDONLY);
2901 }
2902
2903 /*
2904 * If the state is SPA_LOAD_TRYIMPORT, our objective is
2905 * twofold: to determine whether the pool is available for
2906 * import in read-write mode and (if it is not) whether the
2907 * pool is available for import in read-only mode. If the pool
2908 * is available for import in read-write mode, it is displayed
2909 * as available in userland; if it is not available for import
2910 * in read-only mode, it is displayed as unavailable in
2911 * userland. If the pool is available for import in read-only
2912 * mode but not read-write mode, it is displayed as unavailable
2913 * in userland with a special note that the pool is actually
2914 * available for open in read-only mode.
2915 *
2916 * As a result, if the state is SPA_LOAD_TRYIMPORT and we are
2917 * missing a feature for write, we must first determine whether
2918 * the pool can be opened read-only before returning to
2919 * userland in order to know whether to display the
2920 * abovementioned note.
2921 */
2922 if (missing_feat_read || (missing_feat_write &&
2923 spa_writeable(spa))) {
2924 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
2925 ENOTSUP));
2926 }
b0bc7a84
MG
2927
2928 /*
2929 * Load refcounts for ZFS features from disk into an in-memory
2930 * cache during SPA initialization.
2931 */
1c27024e 2932 for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
b0bc7a84
MG
2933 uint64_t refcount;
2934
2935 error = feature_get_refcount_from_disk(spa,
2936 &spa_feature_table[i], &refcount);
2937 if (error == 0) {
2938 spa->spa_feat_refcount_cache[i] = refcount;
2939 } else if (error == ENOTSUP) {
2940 spa->spa_feat_refcount_cache[i] =
2941 SPA_FEATURE_DISABLED;
2942 } else {
2943 return (spa_vdev_err(rvd,
2944 VDEV_AUX_CORRUPT_DATA, EIO));
2945 }
2946 }
2947 }
2948
2949 if (spa_feature_is_active(spa, SPA_FEATURE_ENABLED_TXG)) {
2950 if (spa_dir_prop(spa, DMU_POOL_FEATURE_ENABLED_TXG,
9b67f605 2951 &spa->spa_feat_enabled_txg_obj) != 0)
b0bc7a84 2952 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
9ae529ec
CS
2953 }
2954
2955 spa->spa_is_initializing = B_TRUE;
2956 error = dsl_pool_open(spa->spa_dsl_pool);
2957 spa->spa_is_initializing = B_FALSE;
2958 if (error != 0)
2959 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2960
a1d477c2 2961 if (!trust_config) {
428870ff 2962 uint64_t hostid;
a1d477c2
MA
2963 nvlist_t *policy = NULL;
2964 nvlist_t *mos_config;
428870ff 2965
a1d477c2 2966 if (load_nvlist(spa, spa->spa_config_object, &mos_config) != 0)
428870ff
BB
2967 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2968
a1d477c2 2969 if (!spa_is_root(spa) && nvlist_lookup_uint64(mos_config,
b128c09f 2970 ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
34dc7c2f
BB
2971 char *hostname;
2972 unsigned long myhostid = 0;
2973
a1d477c2 2974 VERIFY(nvlist_lookup_string(mos_config,
34dc7c2f
BB
2975 ZPOOL_CONFIG_HOSTNAME, &hostname) == 0);
2976
379ca9cf
OF
2977 myhostid = spa_get_hostid();
2978 if (hostid && myhostid && hostid != myhostid) {
a1d477c2 2979 nvlist_free(mos_config);
2e528b49 2980 return (SET_ERROR(EBADF));
34dc7c2f
BB
2981 }
2982 }
428870ff
BB
2983 if (nvlist_lookup_nvlist(spa->spa_config,
2984 ZPOOL_REWIND_POLICY, &policy) == 0)
a1d477c2 2985 VERIFY(nvlist_add_nvlist(mos_config,
428870ff 2986 ZPOOL_REWIND_POLICY, policy) == 0);
34dc7c2f 2987
a1d477c2 2988 spa_config_set(spa, mos_config);
34dc7c2f
BB
2989 spa_unload(spa);
2990 spa_deactivate(spa);
fb5f0bc8 2991 spa_activate(spa, orig_mode);
34dc7c2f 2992
428870ff 2993 return (spa_load(spa, state, SPA_IMPORT_EXISTING, B_TRUE));
34dc7c2f
BB
2994 }
2995
3c67d83a
TH
2996 /* Grab the checksum salt from the MOS. */
2997 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
2998 DMU_POOL_CHECKSUM_SALT, 1,
2999 sizeof (spa->spa_cksum_salt.zcs_bytes),
3000 spa->spa_cksum_salt.zcs_bytes);
3001 if (error == ENOENT) {
3002 /* Generate a new salt for subsequent use */
3003 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
3004 sizeof (spa->spa_cksum_salt.zcs_bytes));
3005 } else if (error != 0) {
3006 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3007 }
3008
428870ff
BB
3009 if (spa_dir_prop(spa, DMU_POOL_SYNC_BPOBJ, &obj) != 0)
3010 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3011 error = bpobj_open(&spa->spa_deferred_bpobj, spa->spa_meta_objset, obj);
3012 if (error != 0)
3013 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
34dc7c2f
BB
3014
3015 /*
3016 * Load the bit that tells us to use the new accounting function
3017 * (raid-z deflation). If we have an older pool, this will not
3018 * be present.
3019 */
428870ff
BB
3020 error = spa_dir_prop(spa, DMU_POOL_DEFLATE, &spa->spa_deflate);
3021 if (error != 0 && error != ENOENT)
3022 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3023
3024 error = spa_dir_prop(spa, DMU_POOL_CREATION_VERSION,
3025 &spa->spa_creation_version);
3026 if (error != 0 && error != ENOENT)
3027 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
34dc7c2f
BB
3028
3029 /*
3030 * Load the persistent error log. If we have an older pool, this will
3031 * not be present.
3032 */
428870ff
BB
3033 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_LAST, &spa->spa_errlog_last);
3034 if (error != 0 && error != ENOENT)
3035 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
34dc7c2f 3036
428870ff
BB
3037 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_SCRUB,
3038 &spa->spa_errlog_scrub);
3039 if (error != 0 && error != ENOENT)
3040 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
34dc7c2f
BB
3041
3042 /*
3043 * Load the history object. If we have an older pool, this
3044 * will not be present.
3045 */
428870ff
BB
3046 error = spa_dir_prop(spa, DMU_POOL_HISTORY, &spa->spa_history);
3047 if (error != 0 && error != ENOENT)
3048 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3049
e0ab3ab5
JS
3050 /*
3051 * Load the per-vdev ZAP map. If we have an older pool, this will not
3052 * be present; in this case, defer its creation to a later time to
3053 * avoid dirtying the MOS this early / out of sync context. See
3054 * spa_sync_config_object.
3055 */
3056
3057 /* The sentinel is only available in the MOS config. */
1c27024e 3058 nvlist_t *mos_config;
e0ab3ab5
JS
3059 if (load_nvlist(spa, spa->spa_config_object, &mos_config) != 0)
3060 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3061
3062 error = spa_dir_prop(spa, DMU_POOL_VDEV_ZAP_MAP,
3063 &spa->spa_all_vdev_zaps);
3064
38640550
DB
3065 if (error == ENOENT) {
3066 VERIFY(!nvlist_exists(mos_config,
3067 ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
3068 spa->spa_avz_action = AVZ_ACTION_INITIALIZE;
3069 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3070 } else if (error != 0) {
e0ab3ab5 3071 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
38640550 3072 } else if (!nvlist_exists(mos_config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS)) {
e0ab3ab5
JS
3073 /*
3074 * An older version of ZFS overwrote the sentinel value, so
3075 * we have orphaned per-vdev ZAPs in the MOS. Defer their
3076 * destruction to later; see spa_sync_config_object.
3077 */
3078 spa->spa_avz_action = AVZ_ACTION_DESTROY;
3079 /*
3080 * We're assuming that no vdevs have had their ZAPs created
3081 * before this. Better be sure of it.
3082 */
3083 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3084 }
3085 nvlist_free(mos_config);
3086
428870ff
BB
3087 /*
3088 * If we're assembling the pool from the split-off vdevs of
3089 * an existing pool, we don't want to attach the spares & cache
3090 * devices.
3091 */
34dc7c2f
BB
3092
3093 /*
3094 * Load any hot spares for this pool.
3095 */
428870ff
BB
3096 error = spa_dir_prop(spa, DMU_POOL_SPARES, &spa->spa_spares.sav_object);
3097 if (error != 0 && error != ENOENT)
3098 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3099 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
34dc7c2f
BB
3100 ASSERT(spa_version(spa) >= SPA_VERSION_SPARES);
3101 if (load_nvlist(spa, spa->spa_spares.sav_object,
428870ff
BB
3102 &spa->spa_spares.sav_config) != 0)
3103 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
34dc7c2f 3104
b128c09f 3105 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 3106 spa_load_spares(spa);
b128c09f 3107 spa_config_exit(spa, SCL_ALL, FTAG);
428870ff
BB
3108 } else if (error == 0) {
3109 spa->spa_spares.sav_sync = B_TRUE;
34dc7c2f
BB
3110 }
3111
3112 /*
3113 * Load any level 2 ARC devices for this pool.
3114 */
428870ff 3115 error = spa_dir_prop(spa, DMU_POOL_L2CACHE,
34dc7c2f 3116 &spa->spa_l2cache.sav_object);
428870ff
BB
3117 if (error != 0 && error != ENOENT)
3118 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3119 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
34dc7c2f
BB
3120 ASSERT(spa_version(spa) >= SPA_VERSION_L2CACHE);
3121 if (load_nvlist(spa, spa->spa_l2cache.sav_object,
428870ff
BB
3122 &spa->spa_l2cache.sav_config) != 0)
3123 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
34dc7c2f 3124
b128c09f 3125 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 3126 spa_load_l2cache(spa);
b128c09f 3127 spa_config_exit(spa, SCL_ALL, FTAG);
428870ff
BB
3128 } else if (error == 0) {
3129 spa->spa_l2cache.sav_sync = B_TRUE;
b128c09f
BB
3130 }
3131
34dc7c2f
BB
3132 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
3133
428870ff
BB
3134 error = spa_dir_prop(spa, DMU_POOL_PROPS, &spa->spa_pool_props_object);
3135 if (error && error != ENOENT)
3136 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
34dc7c2f
BB
3137
3138 if (error == 0) {
2dbedf54 3139 uint64_t autoreplace = 0;
428870ff
BB
3140
3141 spa_prop_find(spa, ZPOOL_PROP_BOOTFS, &spa->spa_bootfs);
3142 spa_prop_find(spa, ZPOOL_PROP_AUTOREPLACE, &autoreplace);
3143 spa_prop_find(spa, ZPOOL_PROP_DELEGATION, &spa->spa_delegation);
3144 spa_prop_find(spa, ZPOOL_PROP_FAILUREMODE, &spa->spa_failmode);
3145 spa_prop_find(spa, ZPOOL_PROP_AUTOEXPAND, &spa->spa_autoexpand);
379ca9cf 3146 spa_prop_find(spa, ZPOOL_PROP_MULTIHOST, &spa->spa_multihost);
428870ff
BB
3147 spa_prop_find(spa, ZPOOL_PROP_DEDUPDITTO,
3148 &spa->spa_dedup_ditto);
3149
3150 spa->spa_autoreplace = (autoreplace != 0);
34dc7c2f
BB
3151 }
3152
379ca9cf
OF
3153 /*
3154 * If the 'multihost' property is set, then never allow a pool to
3155 * be imported when the system hostid is zero. The exception to
3156 * this rule is zdb which is always allowed to access pools.
3157 */
3158 if (spa_multihost(spa) && spa_get_hostid() == 0 &&
3159 (spa->spa_import_flags & ZFS_IMPORT_SKIP_MMP) == 0) {
3160 fnvlist_add_uint64(spa->spa_load_info,
3161 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_NO_HOSTID);
3162 return (spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO));
3163 }
3164
34dc7c2f
BB
3165 /*
3166 * If the 'autoreplace' property is set, then post a resource notifying
3167 * the ZFS DE that it should not issue any faults for unopenable
3168 * devices. We also iterate over the vdevs, and post a sysevent for any
3169 * unopenable vdevs so that the normal autoreplace handler can take
3170 * over.
3171 */
428870ff 3172 if (spa->spa_autoreplace && state != SPA_LOAD_TRYIMPORT) {
34dc7c2f 3173 spa_check_removed(spa->spa_root_vdev);
428870ff
BB
3174 /*
3175 * For the import case, this is done in spa_import(), because
3176 * at this point we're using the spare definitions from
3177 * the MOS config, not necessarily from the userland config.
3178 */
3179 if (state != SPA_LOAD_IMPORT) {
3180 spa_aux_check_removed(&spa->spa_spares);
3181 spa_aux_check_removed(&spa->spa_l2cache);
3182 }
3183 }
34dc7c2f
BB
3184
3185 /*
3186 * Load the vdev state for all toplevel vdevs.
3187 */
a1d477c2
MA
3188 error = vdev_load(rvd);
3189 if (error != 0) {
3190 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3191 }
3192
3193 error = spa_condense_init(spa);
3194 if (error != 0) {
3195 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3196 }
34dc7c2f
BB
3197
3198 /*
3199 * Propagate the leaf DTLs we just loaded all the way up the tree.
3200 */
b128c09f 3201 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 3202 vdev_dtl_reassess(rvd, 0, 0, B_FALSE);
b128c09f 3203 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f 3204
428870ff
BB
3205 /*
3206 * Load the DDTs (dedup tables).
3207 */
3208 error = ddt_load(spa);
3209 if (error != 0)
3210 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3211
3212 spa_update_dspace(spa);
3213
a1d477c2
MA
3214 if (type != SPA_IMPORT_ASSEMBLE && spa_writeable(spa) &&
3215 spa_check_logs(spa)) {
3216 *ereport = FM_EREPORT_ZFS_LOG_REPLAY;
3217 return (spa_vdev_err(rvd, VDEV_AUX_BAD_LOG, ENXIO));
428870ff
BB
3218 }
3219
9ae529ec
CS
3220 if (missing_feat_write) {
3221 ASSERT(state == SPA_LOAD_TRYIMPORT);
3222
3223 /*
3224 * At this point, we know that we can open the pool in
3225 * read-only mode but not read-write mode. We now have enough
3226 * information and can return to userland.
3227 */
3228 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT, ENOTSUP));
3229 }
3230
572e2857
BB
3231 /*
3232 * We've successfully opened the pool, verify that we're ready
3233 * to start pushing transactions.
3234 */
3235 if (state != SPA_LOAD_TRYIMPORT) {
c65aa5b2 3236 if ((error = spa_load_verify(spa)))
572e2857
BB
3237 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3238 error));
3239 }
3240
428870ff
BB
3241 if (spa_writeable(spa) && (state == SPA_LOAD_RECOVER ||
3242 spa->spa_load_max_txg == UINT64_MAX)) {
34dc7c2f
BB
3243 dmu_tx_t *tx;
3244 int need_update = B_FALSE;
9c43027b 3245 dsl_pool_t *dp = spa_get_dsl(spa);
fb5f0bc8 3246
a1d477c2
MA
3247 /*
3248 * We must check this before we start the sync thread, because
3249 * we only want to start a condense thread for condense
3250 * operations that were in progress when the pool was
3251 * imported. Once we start syncing, spa_sync() could
3252 * initiate a condense (and start a thread for it). In
3253 * that case it would be wrong to start a second
3254 * condense thread.
3255 */
3256 boolean_t condense_in_progress =
3257 (spa->spa_condensing_indirect != NULL);
3258
fb5f0bc8 3259 ASSERT(state != SPA_LOAD_TRYIMPORT);
34dc7c2f
BB
3260
3261 /*
3262 * Claim log blocks that haven't been committed yet.
3263 * This must all happen in a single txg.
428870ff
BB
3264 * Note: spa_claim_max_txg is updated by spa_claim_notify(),
3265 * invoked from zil_claim_log_block()'s i/o done callback.
3266 * Price of rollback is that we abandon the log.
34dc7c2f 3267 */
428870ff
BB
3268 spa->spa_claiming = B_TRUE;
3269
9c43027b
AJ
3270 tx = dmu_tx_create_assigned(dp, spa_first_txg(spa));
3271 (void) dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
34dc7c2f
BB
3272 zil_claim, tx, DS_FIND_CHILDREN);
3273 dmu_tx_commit(tx);
3274
428870ff
BB
3275 spa->spa_claiming = B_FALSE;
3276
3277 spa_set_log_state(spa, SPA_LOG_GOOD);
34dc7c2f
BB
3278 spa->spa_sync_on = B_TRUE;
3279 txg_sync_start(spa->spa_dsl_pool);
379ca9cf 3280 mmp_thread_start(spa);
34dc7c2f
BB
3281
3282 /*
428870ff
BB
3283 * Wait for all claims to sync. We sync up to the highest
3284 * claimed log block birth time so that claimed log blocks
3285 * don't appear to be from the future. spa_claim_max_txg
3286 * will have been set for us by either zil_check_log_chain()
3287 * (invoked from spa_check_logs()) or zil_claim() above.
34dc7c2f 3288 */
428870ff 3289 txg_wait_synced(spa->spa_dsl_pool, spa->spa_claim_max_txg);
34dc7c2f
BB
3290
3291 /*
3292 * If the config cache is stale, or we have uninitialized
3293 * metaslabs (see spa_vdev_add()), then update the config.
45d1cae3 3294 *
572e2857 3295 * If this is a verbatim import, trust the current
45d1cae3 3296 * in-core spa_config and update the disk labels.
34dc7c2f
BB
3297 */
3298 if (config_cache_txg != spa->spa_config_txg ||
572e2857
BB
3299 state == SPA_LOAD_IMPORT ||
3300 state == SPA_LOAD_RECOVER ||
3301 (spa->spa_import_flags & ZFS_IMPORT_VERBATIM))
34dc7c2f
BB
3302 need_update = B_TRUE;
3303
1c27024e 3304 for (int c = 0; c < rvd->vdev_children; c++)
34dc7c2f
BB
3305 if (rvd->vdev_child[c]->vdev_ms_array == 0)
3306 need_update = B_TRUE;
3307
3308 /*
3309 * Update the config cache asychronously in case we're the
3310 * root pool, in which case the config cache isn't writable yet.
3311 */
3312 if (need_update)
3313 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
fb5f0bc8
BB
3314
3315 /*
3316 * Check all DTLs to see if anything needs resilvering.
3317 */
428870ff
BB
3318 if (!dsl_scan_resilvering(spa->spa_dsl_pool) &&
3319 vdev_resilver_needed(rvd, NULL, NULL))
fb5f0bc8 3320 spa_async_request(spa, SPA_ASYNC_RESILVER);
428870ff 3321
6f1ffb06
MA
3322 /*
3323 * Log the fact that we booted up (so that we can detect if
3324 * we rebooted in the middle of an operation).
3325 */
d5e024cb 3326 spa_history_log_version(spa, "open", NULL);
6f1ffb06 3327
428870ff
BB
3328 /*
3329 * Delete any inconsistent datasets.
3330 */
3331 (void) dmu_objset_find(spa_name(spa),
3332 dsl_destroy_inconsistent, NULL, DS_FIND_CHILDREN);
3333
3334 /*
3335 * Clean up any stale temporary dataset userrefs.
3336 */
3337 dsl_pool_clean_tmp_userrefs(spa->spa_dsl_pool);
a1d477c2
MA
3338
3339 /*
3340 * Note: unlike condensing, we don't need an analogous
3341 * "removal_in_progress" dance because no other thread
3342 * can start a removal while we hold the spa_namespace_lock.
3343 */
3344 spa_restart_removal(spa);
3345
3346 if (condense_in_progress)
3347 spa_condense_indirect_restart(spa);
34dc7c2f
BB
3348 }
3349
428870ff
BB
3350 return (0);
3351}
34dc7c2f 3352
428870ff
BB
3353static int
3354spa_load_retry(spa_t *spa, spa_load_state_t state, int mosconfig)
3355{
572e2857
BB
3356 int mode = spa->spa_mode;
3357
428870ff
BB
3358 spa_unload(spa);
3359 spa_deactivate(spa);
3360
dea377c0 3361 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg - 1;
428870ff 3362
572e2857 3363 spa_activate(spa, mode);
428870ff
BB
3364 spa_async_suspend(spa);
3365
3366 return (spa_load(spa, state, SPA_IMPORT_EXISTING, mosconfig));
3367}
3368
9ae529ec
CS
3369/*
3370 * If spa_load() fails this function will try loading prior txg's. If
3371 * 'state' is SPA_LOAD_RECOVER and one of these loads succeeds the pool
3372 * will be rewound to that txg. If 'state' is not SPA_LOAD_RECOVER this
3373 * function will not rewind the pool and will return the same error as
3374 * spa_load().
3375 */
428870ff
BB
3376static int
3377spa_load_best(spa_t *spa, spa_load_state_t state, int mosconfig,
3378 uint64_t max_request, int rewind_flags)
3379{
9ae529ec 3380 nvlist_t *loadinfo = NULL;
428870ff
BB
3381 nvlist_t *config = NULL;
3382 int load_error, rewind_error;
3383 uint64_t safe_rewind_txg;
3384 uint64_t min_txg;
3385
3386 if (spa->spa_load_txg && state == SPA_LOAD_RECOVER) {
3387 spa->spa_load_max_txg = spa->spa_load_txg;
3388 spa_set_log_state(spa, SPA_LOG_CLEAR);
3389 } else {
3390 spa->spa_load_max_txg = max_request;
dea377c0
MA
3391 if (max_request != UINT64_MAX)
3392 spa->spa_extreme_rewind = B_TRUE;
428870ff
BB
3393 }
3394
3395 load_error = rewind_error = spa_load(spa, state, SPA_IMPORT_EXISTING,
3396 mosconfig);
3397 if (load_error == 0)
3398 return (0);
3399
3400 if (spa->spa_root_vdev != NULL)
3401 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
3402
3403 spa->spa_last_ubsync_txg = spa->spa_uberblock.ub_txg;
3404 spa->spa_last_ubsync_txg_ts = spa->spa_uberblock.ub_timestamp;
3405
3406 if (rewind_flags & ZPOOL_NEVER_REWIND) {
3407 nvlist_free(config);
3408 return (load_error);
3409 }
3410
9ae529ec
CS
3411 if (state == SPA_LOAD_RECOVER) {
3412 /* Price of rolling back is discarding txgs, including log */
428870ff 3413 spa_set_log_state(spa, SPA_LOG_CLEAR);
9ae529ec
CS
3414 } else {
3415 /*
3416 * If we aren't rolling back save the load info from our first
3417 * import attempt so that we can restore it after attempting
3418 * to rewind.
3419 */
3420 loadinfo = spa->spa_load_info;
3421 spa->spa_load_info = fnvlist_alloc();
3422 }
428870ff
BB
3423
3424 spa->spa_load_max_txg = spa->spa_last_ubsync_txg;
3425 safe_rewind_txg = spa->spa_last_ubsync_txg - TXG_DEFER_SIZE;
3426 min_txg = (rewind_flags & ZPOOL_EXTREME_REWIND) ?
3427 TXG_INITIAL : safe_rewind_txg;
3428
3429 /*
3430 * Continue as long as we're finding errors, we're still within
3431 * the acceptable rewind range, and we're still finding uberblocks
3432 */
3433 while (rewind_error && spa->spa_uberblock.ub_txg >= min_txg &&
3434 spa->spa_uberblock.ub_txg <= spa->spa_load_max_txg) {
3435 if (spa->spa_load_max_txg < safe_rewind_txg)
3436 spa->spa_extreme_rewind = B_TRUE;
3437 rewind_error = spa_load_retry(spa, state, mosconfig);
3438 }
3439
428870ff
BB
3440 spa->spa_extreme_rewind = B_FALSE;
3441 spa->spa_load_max_txg = UINT64_MAX;
3442
3443 if (config && (rewind_error || state != SPA_LOAD_RECOVER))
3444 spa_config_set(spa, config);
ee6370a7 3445 else
3446 nvlist_free(config);
428870ff 3447
9ae529ec
CS
3448 if (state == SPA_LOAD_RECOVER) {
3449 ASSERT3P(loadinfo, ==, NULL);
3450 return (rewind_error);
3451 } else {
3452 /* Store the rewind info as part of the initial load info */
3453 fnvlist_add_nvlist(loadinfo, ZPOOL_CONFIG_REWIND_INFO,
3454 spa->spa_load_info);
3455
3456 /* Restore the initial load info */
3457 fnvlist_free(spa->spa_load_info);
3458 spa->spa_load_info = loadinfo;
3459
3460 return (load_error);
3461 }
34dc7c2f
BB
3462}
3463
3464/*
3465 * Pool Open/Import
3466 *
3467 * The import case is identical to an open except that the configuration is sent
3468 * down from userland, instead of grabbed from the configuration cache. For the
3469 * case of an open, the pool configuration will exist in the
3470 * POOL_STATE_UNINITIALIZED state.
3471 *
3472 * The stats information (gen/count/ustats) is used to gather vdev statistics at
3473 * the same time open the pool, without having to keep around the spa_t in some
3474 * ambiguous state.
3475 */
3476static int
428870ff
BB
3477spa_open_common(const char *pool, spa_t **spapp, void *tag, nvlist_t *nvpolicy,
3478 nvlist_t **config)
34dc7c2f
BB
3479{
3480 spa_t *spa;
572e2857 3481 spa_load_state_t state = SPA_LOAD_OPEN;
34dc7c2f 3482 int error;
34dc7c2f 3483 int locked = B_FALSE;
526af785 3484 int firstopen = B_FALSE;
34dc7c2f
BB
3485
3486 *spapp = NULL;
3487
3488 /*
3489 * As disgusting as this is, we need to support recursive calls to this
3490 * function because dsl_dir_open() is called during spa_load(), and ends
3491 * up calling spa_open() again. The real fix is to figure out how to
3492 * avoid dsl_dir_open() calling this in the first place.
3493 */
c25b8f99 3494 if (MUTEX_NOT_HELD(&spa_namespace_lock)) {
34dc7c2f
BB
3495 mutex_enter(&spa_namespace_lock);
3496 locked = B_TRUE;
3497 }
3498
3499 if ((spa = spa_lookup(pool)) == NULL) {
3500 if (locked)
3501 mutex_exit(&spa_namespace_lock);
2e528b49 3502 return (SET_ERROR(ENOENT));
34dc7c2f 3503 }
428870ff 3504
34dc7c2f 3505 if (spa->spa_state == POOL_STATE_UNINITIALIZED) {
428870ff
BB
3506 zpool_rewind_policy_t policy;
3507
526af785
PJD
3508 firstopen = B_TRUE;
3509
428870ff
BB
3510 zpool_get_rewind_policy(nvpolicy ? nvpolicy : spa->spa_config,
3511 &policy);
3512 if (policy.zrp_request & ZPOOL_DO_REWIND)
3513 state = SPA_LOAD_RECOVER;
34dc7c2f 3514
fb5f0bc8 3515 spa_activate(spa, spa_mode_global);
34dc7c2f 3516
428870ff
BB
3517 if (state != SPA_LOAD_RECOVER)
3518 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
3519
3520 error = spa_load_best(spa, state, B_FALSE, policy.zrp_txg,
3521 policy.zrp_request);
34dc7c2f
BB
3522
3523 if (error == EBADF) {
3524 /*
3525 * If vdev_validate() returns failure (indicated by
3526 * EBADF), it indicates that one of the vdevs indicates
3527 * that the pool has been exported or destroyed. If
3528 * this is the case, the config cache is out of sync and
3529 * we should remove the pool from the namespace.
3530 */
34dc7c2f
BB
3531 spa_unload(spa);
3532 spa_deactivate(spa);
a1d477c2 3533 spa_write_cachefile(spa, B_TRUE, B_TRUE);
34dc7c2f 3534 spa_remove(spa);
34dc7c2f
BB
3535 if (locked)
3536 mutex_exit(&spa_namespace_lock);
2e528b49 3537 return (SET_ERROR(ENOENT));
34dc7c2f
BB
3538 }
3539
3540 if (error) {
3541 /*
3542 * We can't open the pool, but we still have useful
3543 * information: the state of each vdev after the
3544 * attempted vdev_open(). Return this to the user.
3545 */
572e2857 3546 if (config != NULL && spa->spa_config) {
428870ff 3547 VERIFY(nvlist_dup(spa->spa_config, config,
79c76d5b 3548 KM_SLEEP) == 0);
572e2857
BB
3549 VERIFY(nvlist_add_nvlist(*config,
3550 ZPOOL_CONFIG_LOAD_INFO,
3551 spa->spa_load_info) == 0);
3552 }
34dc7c2f
BB
3553 spa_unload(spa);
3554 spa_deactivate(spa);
428870ff 3555 spa->spa_last_open_failed = error;
34dc7c2f
BB
3556 if (locked)
3557 mutex_exit(&spa_namespace_lock);
3558 *spapp = NULL;
3559 return (error);
34dc7c2f 3560 }
34dc7c2f
BB
3561 }
3562
3563 spa_open_ref(spa, tag);
3564
b128c09f 3565 if (config != NULL)
34dc7c2f 3566 *config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
34dc7c2f 3567
572e2857
BB
3568 /*
3569 * If we've recovered the pool, pass back any information we
3570 * gathered while doing the load.
3571 */
3572 if (state == SPA_LOAD_RECOVER) {
3573 VERIFY(nvlist_add_nvlist(*config, ZPOOL_CONFIG_LOAD_INFO,
3574 spa->spa_load_info) == 0);
3575 }
3576
428870ff
BB
3577 if (locked) {
3578 spa->spa_last_open_failed = 0;
3579 spa->spa_last_ubsync_txg = 0;
3580 spa->spa_load_txg = 0;
3581 mutex_exit(&spa_namespace_lock);
3582 }
3583
526af785 3584 if (firstopen)
a0bd735a 3585 zvol_create_minors(spa, spa_name(spa), B_TRUE);
526af785 3586
428870ff
BB
3587 *spapp = spa;
3588
34dc7c2f
BB
3589 return (0);
3590}
3591
428870ff
BB
3592int
3593spa_open_rewind(const char *name, spa_t **spapp, void *tag, nvlist_t *policy,
3594 nvlist_t **config)
3595{
3596 return (spa_open_common(name, spapp, tag, policy, config));
3597}
3598
34dc7c2f
BB
3599int
3600spa_open(const char *name, spa_t **spapp, void *tag)
3601{
428870ff 3602 return (spa_open_common(name, spapp, tag, NULL, NULL));
34dc7c2f
BB
3603}
3604
3605/*
3606 * Lookup the given spa_t, incrementing the inject count in the process,
3607 * preventing it from being exported or destroyed.
3608 */
3609spa_t *
3610spa_inject_addref(char *name)
3611{
3612 spa_t *spa;
3613
3614 mutex_enter(&spa_namespace_lock);
3615 if ((spa = spa_lookup(name)) == NULL) {
3616 mutex_exit(&spa_namespace_lock);
3617 return (NULL);
3618 }
3619 spa->spa_inject_ref++;
3620 mutex_exit(&spa_namespace_lock);
3621
3622 return (spa);
3623}
3624
3625void
3626spa_inject_delref(spa_t *spa)
3627{
3628 mutex_enter(&spa_namespace_lock);
3629 spa->spa_inject_ref--;
3630 mutex_exit(&spa_namespace_lock);
3631}
3632
3633/*
3634 * Add spares device information to the nvlist.
3635 */
3636static void
3637spa_add_spares(spa_t *spa, nvlist_t *config)
3638{
3639 nvlist_t **spares;
3640 uint_t i, nspares;
3641 nvlist_t *nvroot;
3642 uint64_t guid;
3643 vdev_stat_t *vs;
3644 uint_t vsc;
3645 uint64_t pool;
3646
9babb374
BB
3647 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
3648
34dc7c2f
BB
3649 if (spa->spa_spares.sav_count == 0)
3650 return;
3651
3652 VERIFY(nvlist_lookup_nvlist(config,
3653 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
3654 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
3655 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
3656 if (nspares != 0) {
3657 VERIFY(nvlist_add_nvlist_array(nvroot,
3658 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
3659 VERIFY(nvlist_lookup_nvlist_array(nvroot,
3660 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
3661
3662 /*
3663 * Go through and find any spares which have since been
3664 * repurposed as an active spare. If this is the case, update
3665 * their status appropriately.
3666 */
3667 for (i = 0; i < nspares; i++) {
3668 VERIFY(nvlist_lookup_uint64(spares[i],
3669 ZPOOL_CONFIG_GUID, &guid) == 0);
b128c09f
BB
3670 if (spa_spare_exists(guid, &pool, NULL) &&
3671 pool != 0ULL) {
34dc7c2f 3672 VERIFY(nvlist_lookup_uint64_array(
428870ff 3673 spares[i], ZPOOL_CONFIG_VDEV_STATS,
34dc7c2f
BB
3674 (uint64_t **)&vs, &vsc) == 0);
3675 vs->vs_state = VDEV_STATE_CANT_OPEN;
3676 vs->vs_aux = VDEV_AUX_SPARED;
3677 }
3678 }
3679 }
3680}
3681
3682/*
3683 * Add l2cache device information to the nvlist, including vdev stats.
3684 */
3685static void
3686spa_add_l2cache(spa_t *spa, nvlist_t *config)
3687{
3688 nvlist_t **l2cache;
3689 uint_t i, j, nl2cache;
3690 nvlist_t *nvroot;
3691 uint64_t guid;
3692 vdev_t *vd;
3693 vdev_stat_t *vs;
3694 uint_t vsc;
3695
9babb374
BB
3696 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
3697
34dc7c2f
BB
3698 if (spa->spa_l2cache.sav_count == 0)
3699 return;
3700
34dc7c2f
BB
3701 VERIFY(nvlist_lookup_nvlist(config,
3702 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
3703 VERIFY(nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
3704 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
3705 if (nl2cache != 0) {
3706 VERIFY(nvlist_add_nvlist_array(nvroot,
3707 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
3708 VERIFY(nvlist_lookup_nvlist_array(nvroot,
3709 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
3710
3711 /*
3712 * Update level 2 cache device stats.
3713 */
3714
3715 for (i = 0; i < nl2cache; i++) {
3716 VERIFY(nvlist_lookup_uint64(l2cache[i],
3717 ZPOOL_CONFIG_GUID, &guid) == 0);
3718
3719 vd = NULL;
3720 for (j = 0; j < spa->spa_l2cache.sav_count; j++) {
3721 if (guid ==
3722 spa->spa_l2cache.sav_vdevs[j]->vdev_guid) {
3723 vd = spa->spa_l2cache.sav_vdevs[j];
3724 break;
3725 }
3726 }
3727 ASSERT(vd != NULL);
3728
3729 VERIFY(nvlist_lookup_uint64_array(l2cache[i],
428870ff
BB
3730 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc)
3731 == 0);
34dc7c2f 3732 vdev_get_stats(vd, vs);
193a37cb
TH
3733 vdev_config_generate_stats(vd, l2cache[i]);
3734
34dc7c2f
BB
3735 }
3736 }
34dc7c2f
BB
3737}
3738
9ae529ec 3739static void
417104bd 3740spa_feature_stats_from_disk(spa_t *spa, nvlist_t *features)
9ae529ec 3741{
9ae529ec
CS
3742 zap_cursor_t zc;
3743 zap_attribute_t za;
3744
9ae529ec
CS
3745 if (spa->spa_feat_for_read_obj != 0) {
3746 for (zap_cursor_init(&zc, spa->spa_meta_objset,
3747 spa->spa_feat_for_read_obj);
3748 zap_cursor_retrieve(&zc, &za) == 0;
3749 zap_cursor_advance(&zc)) {
3750 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
3751 za.za_num_integers == 1);
417104bd 3752 VERIFY0(nvlist_add_uint64(features, za.za_name,
9ae529ec
CS
3753 za.za_first_integer));
3754 }
3755 zap_cursor_fini(&zc);
3756 }
3757
3758 if (spa->spa_feat_for_write_obj != 0) {
3759 for (zap_cursor_init(&zc, spa->spa_meta_objset,
3760 spa->spa_feat_for_write_obj);
3761 zap_cursor_retrieve(&zc, &za) == 0;
3762 zap_cursor_advance(&zc)) {
3763 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
3764 za.za_num_integers == 1);
417104bd 3765 VERIFY0(nvlist_add_uint64(features, za.za_name,
9ae529ec
CS
3766 za.za_first_integer));
3767 }
3768 zap_cursor_fini(&zc);
3769 }
417104bd
NB
3770}
3771
3772static void
3773spa_feature_stats_from_cache(spa_t *spa, nvlist_t *features)
3774{
3775 int i;
3776
3777 for (i = 0; i < SPA_FEATURES; i++) {
3778 zfeature_info_t feature = spa_feature_table[i];
3779 uint64_t refcount;
3780
3781 if (feature_get_refcount(spa, &feature, &refcount) != 0)
3782 continue;
3783
3784 VERIFY0(nvlist_add_uint64(features, feature.fi_guid, refcount));
3785 }
3786}
3787
3788/*
3789 * Store a list of pool features and their reference counts in the
3790 * config.
3791 *
3792 * The first time this is called on a spa, allocate a new nvlist, fetch
3793 * the pool features and reference counts from disk, then save the list
3794 * in the spa. In subsequent calls on the same spa use the saved nvlist
3795 * and refresh its values from the cached reference counts. This
3796 * ensures we don't block here on I/O on a suspended pool so 'zpool
3797 * clear' can resume the pool.
3798 */
3799static void
3800spa_add_feature_stats(spa_t *spa, nvlist_t *config)
3801{
4eb30c68 3802 nvlist_t *features;
417104bd
NB
3803
3804 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
3805
4eb30c68
NB
3806 mutex_enter(&spa->spa_feat_stats_lock);
3807 features = spa->spa_feat_stats;
3808
417104bd
NB
3809 if (features != NULL) {
3810 spa_feature_stats_from_cache(spa, features);
3811 } else {
3812 VERIFY0(nvlist_alloc(&features, NV_UNIQUE_NAME, KM_SLEEP));
3813 spa->spa_feat_stats = features;
3814 spa_feature_stats_from_disk(spa, features);
3815 }
9ae529ec 3816
417104bd
NB
3817 VERIFY0(nvlist_add_nvlist(config, ZPOOL_CONFIG_FEATURE_STATS,
3818 features));
4eb30c68
NB
3819
3820 mutex_exit(&spa->spa_feat_stats_lock);
9ae529ec
CS
3821}
3822
34dc7c2f 3823int
9ae529ec
CS
3824spa_get_stats(const char *name, nvlist_t **config,
3825 char *altroot, size_t buflen)
34dc7c2f
BB
3826{
3827 int error;
3828 spa_t *spa;
3829
3830 *config = NULL;
428870ff 3831 error = spa_open_common(name, &spa, FTAG, NULL, config);
34dc7c2f 3832
9babb374
BB
3833 if (spa != NULL) {
3834 /*
3835 * This still leaves a window of inconsistency where the spares
3836 * or l2cache devices could change and the config would be
3837 * self-inconsistent.
3838 */
3839 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
34dc7c2f 3840
9babb374 3841 if (*config != NULL) {
572e2857
BB
3842 uint64_t loadtimes[2];
3843
3844 loadtimes[0] = spa->spa_loaded_ts.tv_sec;
3845 loadtimes[1] = spa->spa_loaded_ts.tv_nsec;
3846 VERIFY(nvlist_add_uint64_array(*config,
3847 ZPOOL_CONFIG_LOADED_TIME, loadtimes, 2) == 0);
3848
b128c09f 3849 VERIFY(nvlist_add_uint64(*config,
9babb374
BB
3850 ZPOOL_CONFIG_ERRCOUNT,
3851 spa_get_errlog_size(spa)) == 0);
3852
cec3a0a1 3853 if (spa_suspended(spa)) {
9babb374
BB
3854 VERIFY(nvlist_add_uint64(*config,
3855 ZPOOL_CONFIG_SUSPENDED,
3856 spa->spa_failmode) == 0);
cec3a0a1
OF
3857 VERIFY(nvlist_add_uint64(*config,
3858 ZPOOL_CONFIG_SUSPENDED_REASON,
3859 spa->spa_suspended) == 0);
3860 }
b128c09f 3861
9babb374
BB
3862 spa_add_spares(spa, *config);
3863 spa_add_l2cache(spa, *config);
9ae529ec 3864 spa_add_feature_stats(spa, *config);
9babb374 3865 }
34dc7c2f
BB
3866 }
3867
3868 /*
3869 * We want to get the alternate root even for faulted pools, so we cheat
3870 * and call spa_lookup() directly.
3871 */
3872 if (altroot) {
3873 if (spa == NULL) {
3874 mutex_enter(&spa_namespace_lock);
3875 spa = spa_lookup(name);
3876 if (spa)
3877 spa_altroot(spa, altroot, buflen);
3878 else
3879 altroot[0] = '\0';
3880 spa = NULL;
3881 mutex_exit(&spa_namespace_lock);
3882 } else {
3883 spa_altroot(spa, altroot, buflen);
3884 }
3885 }
3886
9babb374
BB
3887 if (spa != NULL) {
3888 spa_config_exit(spa, SCL_CONFIG, FTAG);
34dc7c2f 3889 spa_close(spa, FTAG);
9babb374 3890 }
34dc7c2f
BB
3891
3892 return (error);
3893}
3894
3895/*
3896 * Validate that the auxiliary device array is well formed. We must have an
3897 * array of nvlists, each which describes a valid leaf vdev. If this is an
3898 * import (mode is VDEV_ALLOC_SPARE), then we allow corrupted spares to be
3899 * specified, as long as they are well-formed.
3900 */
3901static int
3902spa_validate_aux_devs(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode,
3903 spa_aux_vdev_t *sav, const char *config, uint64_t version,
3904 vdev_labeltype_t label)
3905{
3906 nvlist_t **dev;
3907 uint_t i, ndev;
3908 vdev_t *vd;
3909 int error;
3910
b128c09f
BB
3911 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
3912
34dc7c2f
BB
3913 /*
3914 * It's acceptable to have no devs specified.
3915 */
3916 if (nvlist_lookup_nvlist_array(nvroot, config, &dev, &ndev) != 0)
3917 return (0);
3918
3919 if (ndev == 0)
2e528b49 3920 return (SET_ERROR(EINVAL));
34dc7c2f
BB
3921
3922 /*
3923 * Make sure the pool is formatted with a version that supports this
3924 * device type.
3925 */
3926 if (spa_version(spa) < version)
2e528b49 3927 return (SET_ERROR(ENOTSUP));
34dc7c2f
BB
3928
3929 /*
3930 * Set the pending device list so we correctly handle device in-use
3931 * checking.
3932 */
3933 sav->sav_pending = dev;
3934 sav->sav_npending = ndev;
3935
3936 for (i = 0; i < ndev; i++) {
3937 if ((error = spa_config_parse(spa, &vd, dev[i], NULL, 0,
3938 mode)) != 0)
3939 goto out;
3940
3941 if (!vd->vdev_ops->vdev_op_leaf) {
3942 vdev_free(vd);
2e528b49 3943 error = SET_ERROR(EINVAL);
34dc7c2f
BB
3944 goto out;
3945 }
3946
34dc7c2f
BB
3947 vd->vdev_top = vd;
3948
3949 if ((error = vdev_open(vd)) == 0 &&
3950 (error = vdev_label_init(vd, crtxg, label)) == 0) {
3951 VERIFY(nvlist_add_uint64(dev[i], ZPOOL_CONFIG_GUID,
3952 vd->vdev_guid) == 0);
3953 }
3954
3955 vdev_free(vd);
3956
3957 if (error &&
3958 (mode != VDEV_ALLOC_SPARE && mode != VDEV_ALLOC_L2CACHE))
3959 goto out;
3960 else
3961 error = 0;
3962 }
3963
3964out:
3965 sav->sav_pending = NULL;
3966 sav->sav_npending = 0;
3967 return (error);
3968}
3969
3970static int
3971spa_validate_aux(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode)
3972{
3973 int error;
3974
b128c09f
BB
3975 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
3976
34dc7c2f
BB
3977 if ((error = spa_validate_aux_devs(spa, nvroot, crtxg, mode,
3978 &spa->spa_spares, ZPOOL_CONFIG_SPARES, SPA_VERSION_SPARES,
3979 VDEV_LABEL_SPARE)) != 0) {
3980 return (error);
3981 }
3982
3983 return (spa_validate_aux_devs(spa, nvroot, crtxg, mode,
3984 &spa->spa_l2cache, ZPOOL_CONFIG_L2CACHE, SPA_VERSION_L2CACHE,
3985 VDEV_LABEL_L2CACHE));
3986}
3987
3988static void
3989spa_set_aux_vdevs(spa_aux_vdev_t *sav, nvlist_t **devs, int ndevs,
3990 const char *config)
3991{
3992 int i;
3993
3994 if (sav->sav_config != NULL) {
3995 nvlist_t **olddevs;
3996 uint_t oldndevs;
3997 nvlist_t **newdevs;
3998
3999 /*
4e33ba4c 4000 * Generate new dev list by concatenating with the
34dc7c2f
BB
4001 * current dev list.
4002 */
4003 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config, config,
4004 &olddevs, &oldndevs) == 0);
4005
4006 newdevs = kmem_alloc(sizeof (void *) *
79c76d5b 4007 (ndevs + oldndevs), KM_SLEEP);
34dc7c2f
BB
4008 for (i = 0; i < oldndevs; i++)
4009 VERIFY(nvlist_dup(olddevs[i], &newdevs[i],
79c76d5b 4010 KM_SLEEP) == 0);
34dc7c2f
BB
4011 for (i = 0; i < ndevs; i++)
4012 VERIFY(nvlist_dup(devs[i], &newdevs[i + oldndevs],
79c76d5b 4013 KM_SLEEP) == 0);
34dc7c2f
BB
4014
4015 VERIFY(nvlist_remove(sav->sav_config, config,
4016 DATA_TYPE_NVLIST_ARRAY) == 0);
4017
4018 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
4019 config, newdevs, ndevs + oldndevs) == 0);
4020 for (i = 0; i < oldndevs + ndevs; i++)
4021 nvlist_free(newdevs[i]);
4022 kmem_free(newdevs, (oldndevs + ndevs) * sizeof (void *));
4023 } else {
4024 /*
4025 * Generate a new dev list.
4026 */
4027 VERIFY(nvlist_alloc(&sav->sav_config, NV_UNIQUE_NAME,
79c76d5b 4028 KM_SLEEP) == 0);
34dc7c2f
BB
4029 VERIFY(nvlist_add_nvlist_array(sav->sav_config, config,
4030 devs, ndevs) == 0);
4031 }
4032}
4033
4034/*
4035 * Stop and drop level 2 ARC devices
4036 */
4037void
4038spa_l2cache_drop(spa_t *spa)
4039{
4040 vdev_t *vd;
4041 int i;
4042 spa_aux_vdev_t *sav = &spa->spa_l2cache;
4043
4044 for (i = 0; i < sav->sav_count; i++) {
4045 uint64_t pool;
4046
4047 vd = sav->sav_vdevs[i];
4048 ASSERT(vd != NULL);
4049
fb5f0bc8
BB
4050 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
4051 pool != 0ULL && l2arc_vdev_present(vd))
34dc7c2f 4052 l2arc_remove_vdev(vd);
34dc7c2f
BB
4053 }
4054}
4055
b5256303
TC
4056/*
4057 * Verify encryption parameters for spa creation. If we are encrypting, we must
4058 * have the encryption feature flag enabled.
4059 */
4060static int
4061spa_create_check_encryption_params(dsl_crypto_params_t *dcp,
4062 boolean_t has_encryption)
4063{
4064 if (dcp->cp_crypt != ZIO_CRYPT_OFF &&
4065 dcp->cp_crypt != ZIO_CRYPT_INHERIT &&
4066 !has_encryption)
4067 return (SET_ERROR(ENOTSUP));
4068
4069 return (dmu_objset_create_crypt_check(NULL, dcp));
4070}
4071
34dc7c2f
BB
4072/*
4073 * Pool Creation
4074 */
4075int
4076spa_create(const char *pool, nvlist_t *nvroot, nvlist_t *props,
b5256303 4077 nvlist_t *zplprops, dsl_crypto_params_t *dcp)
34dc7c2f
BB
4078{
4079 spa_t *spa;
4080 char *altroot = NULL;
4081 vdev_t *rvd;
4082 dsl_pool_t *dp;
4083 dmu_tx_t *tx;
9babb374 4084 int error = 0;
34dc7c2f
BB
4085 uint64_t txg = TXG_INITIAL;
4086 nvlist_t **spares, **l2cache;
4087 uint_t nspares, nl2cache;
b5256303 4088 uint64_t version, obj, root_dsobj = 0;
9ae529ec 4089 boolean_t has_features;
b5256303
TC
4090 boolean_t has_encryption;
4091 spa_feature_t feat;
4092 char *feat_name;
83e9986f
RY
4093 char *poolname;
4094 nvlist_t *nvl;
4095
4096 if (nvlist_lookup_string(props, "tname", &poolname) != 0)
4097 poolname = (char *)pool;
34dc7c2f
BB
4098
4099 /*
4100 * If this pool already exists, return failure.
4101 */
4102 mutex_enter(&spa_namespace_lock);
83e9986f 4103 if (spa_lookup(poolname) != NULL) {
34dc7c2f 4104 mutex_exit(&spa_namespace_lock);
2e528b49 4105 return (SET_ERROR(EEXIST));
34dc7c2f
BB
4106 }
4107
4108 /*
4109 * Allocate a new spa_t structure.
4110 */
83e9986f
RY
4111 nvl = fnvlist_alloc();
4112 fnvlist_add_string(nvl, ZPOOL_CONFIG_POOL_NAME, pool);
34dc7c2f
BB
4113 (void) nvlist_lookup_string(props,
4114 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
83e9986f
RY
4115 spa = spa_add(poolname, nvl, altroot);
4116 fnvlist_free(nvl);
fb5f0bc8 4117 spa_activate(spa, spa_mode_global);
34dc7c2f 4118
34dc7c2f 4119 if (props && (error = spa_prop_validate(spa, props))) {
34dc7c2f
BB
4120 spa_deactivate(spa);
4121 spa_remove(spa);
b128c09f 4122 mutex_exit(&spa_namespace_lock);
34dc7c2f
BB
4123 return (error);
4124 }
4125
83e9986f
RY
4126 /*
4127 * Temporary pool names should never be written to disk.
4128 */
4129 if (poolname != pool)
4130 spa->spa_import_flags |= ZFS_IMPORT_TEMP_NAME;
4131
9ae529ec 4132 has_features = B_FALSE;
b5256303 4133 has_encryption = B_FALSE;
1c27024e 4134 for (nvpair_t *elem = nvlist_next_nvpair(props, NULL);
9ae529ec 4135 elem != NULL; elem = nvlist_next_nvpair(props, elem)) {
b5256303 4136 if (zpool_prop_feature(nvpair_name(elem))) {
9ae529ec 4137 has_features = B_TRUE;
b5256303
TC
4138
4139 feat_name = strchr(nvpair_name(elem), '@') + 1;
4140 VERIFY0(zfeature_lookup_name(feat_name, &feat));
4141 if (feat == SPA_FEATURE_ENCRYPTION)
4142 has_encryption = B_TRUE;
4143 }
4144 }
4145
4146 /* verify encryption params, if they were provided */
4147 if (dcp != NULL) {
4148 error = spa_create_check_encryption_params(dcp, has_encryption);
4149 if (error != 0) {
4150 spa_deactivate(spa);
4151 spa_remove(spa);
4152 mutex_exit(&spa_namespace_lock);
4153 return (error);
4154 }
9ae529ec
CS
4155 }
4156
4157 if (has_features || nvlist_lookup_uint64(props,
4158 zpool_prop_to_name(ZPOOL_PROP_VERSION), &version) != 0) {
34dc7c2f 4159 version = SPA_VERSION;
9ae529ec
CS
4160 }
4161 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
428870ff
BB
4162
4163 spa->spa_first_txg = txg;
4164 spa->spa_uberblock.ub_txg = txg - 1;
34dc7c2f
BB
4165 spa->spa_uberblock.ub_version = version;
4166 spa->spa_ubsync = spa->spa_uberblock;
3dfb57a3 4167 spa->spa_load_state = SPA_LOAD_CREATE;
a1d477c2
MA
4168 spa->spa_removing_phys.sr_state = DSS_NONE;
4169 spa->spa_removing_phys.sr_removing_vdev = -1;
4170 spa->spa_removing_phys.sr_prev_indirect_vdev = -1;
34dc7c2f 4171
9babb374
BB
4172 /*
4173 * Create "The Godfather" zio to hold all async IOs
4174 */
e022864d
MA
4175 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
4176 KM_SLEEP);
1c27024e 4177 for (int i = 0; i < max_ncpus; i++) {
e022864d
MA
4178 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
4179 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
4180 ZIO_FLAG_GODFATHER);
4181 }
9babb374 4182
34dc7c2f
BB
4183 /*
4184 * Create the root vdev.
4185 */
b128c09f 4186 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f
BB
4187
4188 error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, VDEV_ALLOC_ADD);
4189
4190 ASSERT(error != 0 || rvd != NULL);
4191 ASSERT(error != 0 || spa->spa_root_vdev == rvd);
4192
4193 if (error == 0 && !zfs_allocatable_devs(nvroot))
2e528b49 4194 error = SET_ERROR(EINVAL);
34dc7c2f
BB
4195
4196 if (error == 0 &&
4197 (error = vdev_create(rvd, txg, B_FALSE)) == 0 &&
4198 (error = spa_validate_aux(spa, nvroot, txg,
4199 VDEV_ALLOC_ADD)) == 0) {
1c27024e 4200 for (int c = 0; c < rvd->vdev_children; c++) {
9babb374
BB
4201 vdev_metaslab_set_size(rvd->vdev_child[c]);
4202 vdev_expand(rvd->vdev_child[c], txg);
4203 }
34dc7c2f
BB
4204 }
4205
b128c09f 4206 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
4207
4208 if (error != 0) {
4209 spa_unload(spa);
4210 spa_deactivate(spa);
4211 spa_remove(spa);
4212 mutex_exit(&spa_namespace_lock);
4213 return (error);
4214 }
4215
4216 /*
4217 * Get the list of spares, if specified.
4218 */
4219 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
4220 &spares, &nspares) == 0) {
4221 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config, NV_UNIQUE_NAME,
79c76d5b 4222 KM_SLEEP) == 0);
34dc7c2f
BB
4223 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
4224 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
b128c09f 4225 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 4226 spa_load_spares(spa);
b128c09f 4227 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
4228 spa->spa_spares.sav_sync = B_TRUE;
4229 }
4230
4231 /*
4232 * Get the list of level 2 cache devices, if specified.
4233 */
4234 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
4235 &l2cache, &nl2cache) == 0) {
4236 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
79c76d5b 4237 NV_UNIQUE_NAME, KM_SLEEP) == 0);
34dc7c2f
BB
4238 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
4239 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
b128c09f 4240 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 4241 spa_load_l2cache(spa);
b128c09f 4242 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
4243 spa->spa_l2cache.sav_sync = B_TRUE;
4244 }
4245
9ae529ec 4246 spa->spa_is_initializing = B_TRUE;
b5256303 4247 spa->spa_dsl_pool = dp = dsl_pool_create(spa, zplprops, dcp, txg);
9ae529ec 4248 spa->spa_is_initializing = B_FALSE;
34dc7c2f 4249
428870ff
BB
4250 /*
4251 * Create DDTs (dedup tables).
4252 */
4253 ddt_create(spa);
4254
4255 spa_update_dspace(spa);
4256
34dc7c2f
BB
4257 tx = dmu_tx_create_assigned(dp, txg);
4258
d5e024cb
BB
4259 /*
4260 * Create the pool's history object.
4261 */
4262 if (version >= SPA_VERSION_ZPOOL_HISTORY && !spa->spa_history)
4263 spa_history_create_obj(spa, tx);
4264
4265 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_CREATE);
4266 spa_history_log_version(spa, "create", tx);
4267
34dc7c2f
BB
4268 /*
4269 * Create the pool config object.
4270 */
4271 spa->spa_config_object = dmu_object_alloc(spa->spa_meta_objset,
b128c09f 4272 DMU_OT_PACKED_NVLIST, SPA_CONFIG_BLOCKSIZE,
34dc7c2f
BB
4273 DMU_OT_PACKED_NVLIST_SIZE, sizeof (uint64_t), tx);
4274
4275 if (zap_add(spa->spa_meta_objset,
4276 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CONFIG,
4277 sizeof (uint64_t), 1, &spa->spa_config_object, tx) != 0) {
4278 cmn_err(CE_PANIC, "failed to add pool config");
4279 }
4280
428870ff
BB
4281 if (zap_add(spa->spa_meta_objset,
4282 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CREATION_VERSION,
4283 sizeof (uint64_t), 1, &version, tx) != 0) {
4284 cmn_err(CE_PANIC, "failed to add pool version");
4285 }
4286
34dc7c2f
BB
4287 /* Newly created pools with the right version are always deflated. */
4288 if (version >= SPA_VERSION_RAIDZ_DEFLATE) {
4289 spa->spa_deflate = TRUE;
4290 if (zap_add(spa->spa_meta_objset,
4291 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
4292 sizeof (uint64_t), 1, &spa->spa_deflate, tx) != 0) {
4293 cmn_err(CE_PANIC, "failed to add deflate");
4294 }
4295 }
4296
4297 /*
428870ff 4298 * Create the deferred-free bpobj. Turn off compression
34dc7c2f
BB
4299 * because sync-to-convergence takes longer if the blocksize
4300 * keeps changing.
4301 */
428870ff
BB
4302 obj = bpobj_alloc(spa->spa_meta_objset, 1 << 14, tx);
4303 dmu_object_set_compress(spa->spa_meta_objset, obj,
34dc7c2f 4304 ZIO_COMPRESS_OFF, tx);
34dc7c2f 4305 if (zap_add(spa->spa_meta_objset,
428870ff
BB
4306 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SYNC_BPOBJ,
4307 sizeof (uint64_t), 1, &obj, tx) != 0) {
4308 cmn_err(CE_PANIC, "failed to add bpobj");
34dc7c2f 4309 }
428870ff
BB
4310 VERIFY3U(0, ==, bpobj_open(&spa->spa_deferred_bpobj,
4311 spa->spa_meta_objset, obj));
34dc7c2f 4312
3c67d83a
TH
4313 /*
4314 * Generate some random noise for salted checksums to operate on.
4315 */
4316 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
4317 sizeof (spa->spa_cksum_salt.zcs_bytes));
4318
34dc7c2f
BB
4319 /*
4320 * Set pool properties.
4321 */
4322 spa->spa_bootfs = zpool_prop_default_numeric(ZPOOL_PROP_BOOTFS);
4323 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
4324 spa->spa_failmode = zpool_prop_default_numeric(ZPOOL_PROP_FAILUREMODE);
9babb374 4325 spa->spa_autoexpand = zpool_prop_default_numeric(ZPOOL_PROP_AUTOEXPAND);
379ca9cf 4326 spa->spa_multihost = zpool_prop_default_numeric(ZPOOL_PROP_MULTIHOST);
428870ff 4327
d164b209
BB
4328 if (props != NULL) {
4329 spa_configfile_set(spa, props, B_FALSE);
13fe0198 4330 spa_sync_props(props, tx);
d164b209 4331 }
34dc7c2f
BB
4332
4333 dmu_tx_commit(tx);
4334
b5256303
TC
4335 /*
4336 * If the root dataset is encrypted we will need to create key mappings
4337 * for the zio layer before we start to write any data to disk and hold
4338 * them until after the first txg has been synced. Waiting for the first
4339 * transaction to complete also ensures that our bean counters are
4340 * appropriately updated.
4341 */
4342 if (dp->dp_root_dir->dd_crypto_obj != 0) {
4343 root_dsobj = dsl_dir_phys(dp->dp_root_dir)->dd_head_dataset_obj;
4344 VERIFY0(spa_keystore_create_mapping_impl(spa, root_dsobj,
4345 dp->dp_root_dir, FTAG));
4346 }
4347
34dc7c2f 4348 spa->spa_sync_on = B_TRUE;
b5256303 4349 txg_sync_start(dp);
379ca9cf 4350 mmp_thread_start(spa);
b5256303 4351 txg_wait_synced(dp, txg);
34dc7c2f 4352
b5256303
TC
4353 if (dp->dp_root_dir->dd_crypto_obj != 0)
4354 VERIFY0(spa_keystore_remove_mapping(spa, root_dsobj, FTAG));
34dc7c2f 4355
a1d477c2 4356 spa_write_cachefile(spa, B_FALSE, B_TRUE);
34dc7c2f 4357
0c66c32d
JG
4358 /*
4359 * Don't count references from objsets that are already closed
4360 * and are making their way through the eviction process.
4361 */
4362 spa_evicting_os_wait(spa);
b128c09f 4363 spa->spa_minref = refcount_count(&spa->spa_refcount);
3dfb57a3 4364 spa->spa_load_state = SPA_LOAD_NONE;
b128c09f 4365
d164b209
BB
4366 mutex_exit(&spa_namespace_lock);
4367
34dc7c2f
BB
4368 return (0);
4369}
4370
9babb374
BB
4371/*
4372 * Import a non-root pool into the system.
4373 */
4374int
13fe0198 4375spa_import(char *pool, nvlist_t *config, nvlist_t *props, uint64_t flags)
34dc7c2f
BB
4376{
4377 spa_t *spa;
4378 char *altroot = NULL;
428870ff
BB
4379 spa_load_state_t state = SPA_LOAD_IMPORT;
4380 zpool_rewind_policy_t policy;
572e2857
BB
4381 uint64_t mode = spa_mode_global;
4382 uint64_t readonly = B_FALSE;
9babb374 4383 int error;
34dc7c2f
BB
4384 nvlist_t *nvroot;
4385 nvlist_t **spares, **l2cache;
4386 uint_t nspares, nl2cache;
34dc7c2f
BB
4387
4388 /*
4389 * If a pool with this name exists, return failure.
4390 */
4391 mutex_enter(&spa_namespace_lock);
428870ff 4392 if (spa_lookup(pool) != NULL) {
9babb374 4393 mutex_exit(&spa_namespace_lock);
2e528b49 4394 return (SET_ERROR(EEXIST));
34dc7c2f
BB
4395 }
4396
4397 /*
4398 * Create and initialize the spa structure.
4399 */
4400 (void) nvlist_lookup_string(props,
4401 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
572e2857
BB
4402 (void) nvlist_lookup_uint64(props,
4403 zpool_prop_to_name(ZPOOL_PROP_READONLY), &readonly);
4404 if (readonly)
4405 mode = FREAD;
428870ff 4406 spa = spa_add(pool, config, altroot);
572e2857
BB
4407 spa->spa_import_flags = flags;
4408
4409 /*
4410 * Verbatim import - Take a pool and insert it into the namespace
4411 * as if it had been loaded at boot.
4412 */
4413 if (spa->spa_import_flags & ZFS_IMPORT_VERBATIM) {
4414 if (props != NULL)
4415 spa_configfile_set(spa, props, B_FALSE);
4416
a1d477c2 4417 spa_write_cachefile(spa, B_FALSE, B_TRUE);
12fa0466 4418 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
572e2857
BB
4419
4420 mutex_exit(&spa_namespace_lock);
572e2857
BB
4421 return (0);
4422 }
4423
4424 spa_activate(spa, mode);
34dc7c2f 4425
9babb374
BB
4426 /*
4427 * Don't start async tasks until we know everything is healthy.
4428 */
4429 spa_async_suspend(spa);
b128c09f 4430
572e2857
BB
4431 zpool_get_rewind_policy(config, &policy);
4432 if (policy.zrp_request & ZPOOL_DO_REWIND)
4433 state = SPA_LOAD_RECOVER;
4434
34dc7c2f 4435 /*
9babb374
BB
4436 * Pass off the heavy lifting to spa_load(). Pass TRUE for mosconfig
4437 * because the user-supplied config is actually the one to trust when
b128c09f 4438 * doing an import.
34dc7c2f 4439 */
428870ff
BB
4440 if (state != SPA_LOAD_RECOVER)
4441 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
572e2857 4442
428870ff
BB
4443 error = spa_load_best(spa, state, B_TRUE, policy.zrp_txg,
4444 policy.zrp_request);
4445
4446 /*
572e2857
BB
4447 * Propagate anything learned while loading the pool and pass it
4448 * back to caller (i.e. rewind info, missing devices, etc).
428870ff 4449 */
572e2857
BB
4450 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
4451 spa->spa_load_info) == 0);
34dc7c2f 4452
b128c09f 4453 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 4454 /*
9babb374
BB
4455 * Toss any existing sparelist, as it doesn't have any validity
4456 * anymore, and conflicts with spa_has_spare().
34dc7c2f 4457 */
9babb374 4458 if (spa->spa_spares.sav_config) {
34dc7c2f
BB
4459 nvlist_free(spa->spa_spares.sav_config);
4460 spa->spa_spares.sav_config = NULL;
4461 spa_load_spares(spa);
4462 }
9babb374 4463 if (spa->spa_l2cache.sav_config) {
34dc7c2f
BB
4464 nvlist_free(spa->spa_l2cache.sav_config);
4465 spa->spa_l2cache.sav_config = NULL;
4466 spa_load_l2cache(spa);
4467 }
4468
4469 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
4470 &nvroot) == 0);
b128c09f 4471 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f 4472
d164b209
BB
4473 if (props != NULL)
4474 spa_configfile_set(spa, props, B_FALSE);
4475
fb5f0bc8
BB
4476 if (error != 0 || (props && spa_writeable(spa) &&
4477 (error = spa_prop_set(spa, props)))) {
9babb374
BB
4478 spa_unload(spa);
4479 spa_deactivate(spa);
4480 spa_remove(spa);
34dc7c2f
BB
4481 mutex_exit(&spa_namespace_lock);
4482 return (error);
4483 }
4484
572e2857
BB
4485 spa_async_resume(spa);
4486
34dc7c2f
BB
4487 /*
4488 * Override any spares and level 2 cache devices as specified by
4489 * the user, as these may have correct device names/devids, etc.
4490 */
4491 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
4492 &spares, &nspares) == 0) {
4493 if (spa->spa_spares.sav_config)
4494 VERIFY(nvlist_remove(spa->spa_spares.sav_config,
4495 ZPOOL_CONFIG_SPARES, DATA_TYPE_NVLIST_ARRAY) == 0);
4496 else
4497 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config,
79c76d5b 4498 NV_UNIQUE_NAME, KM_SLEEP) == 0);
34dc7c2f
BB
4499 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
4500 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
b128c09f 4501 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 4502 spa_load_spares(spa);
b128c09f 4503 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
4504 spa->spa_spares.sav_sync = B_TRUE;
4505 }
4506 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
4507 &l2cache, &nl2cache) == 0) {
4508 if (spa->spa_l2cache.sav_config)
4509 VERIFY(nvlist_remove(spa->spa_l2cache.sav_config,
4510 ZPOOL_CONFIG_L2CACHE, DATA_TYPE_NVLIST_ARRAY) == 0);
4511 else
4512 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
79c76d5b 4513 NV_UNIQUE_NAME, KM_SLEEP) == 0);
34dc7c2f
BB
4514 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
4515 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
b128c09f 4516 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 4517 spa_load_l2cache(spa);
b128c09f 4518 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
4519 spa->spa_l2cache.sav_sync = B_TRUE;
4520 }
4521
428870ff
BB
4522 /*
4523 * Check for any removed devices.
4524 */
4525 if (spa->spa_autoreplace) {
4526 spa_aux_check_removed(&spa->spa_spares);
4527 spa_aux_check_removed(&spa->spa_l2cache);
4528 }
4529
fb5f0bc8 4530 if (spa_writeable(spa)) {
b128c09f
BB
4531 /*
4532 * Update the config cache to include the newly-imported pool.
4533 */
45d1cae3 4534 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
b128c09f 4535 }
34dc7c2f 4536
34dc7c2f 4537 /*
9babb374
BB
4538 * It's possible that the pool was expanded while it was exported.
4539 * We kick off an async task to handle this for us.
34dc7c2f 4540 */
9babb374 4541 spa_async_request(spa, SPA_ASYNC_AUTOEXPAND);
b128c09f 4542
d5e024cb 4543 spa_history_log_version(spa, "import", NULL);
fb390aaf 4544
12fa0466 4545 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
fb390aaf 4546
a0bd735a 4547 zvol_create_minors(spa, pool, B_TRUE);
526af785 4548
fb390aaf
HR
4549 mutex_exit(&spa_namespace_lock);
4550
b128c09f
BB
4551 return (0);
4552}
4553
34dc7c2f
BB
4554nvlist_t *
4555spa_tryimport(nvlist_t *tryconfig)
4556{
4557 nvlist_t *config = NULL;
4558 char *poolname;
4559 spa_t *spa;
4560 uint64_t state;
d164b209 4561 int error;
34dc7c2f
BB
4562
4563 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_POOL_NAME, &poolname))
4564 return (NULL);
4565
4566 if (nvlist_lookup_uint64(tryconfig, ZPOOL_CONFIG_POOL_STATE, &state))
4567 return (NULL);
4568
4569 /*
4570 * Create and initialize the spa structure.
4571 */
4572 mutex_enter(&spa_namespace_lock);
428870ff 4573 spa = spa_add(TRYIMPORT_NAME, tryconfig, NULL);
fb5f0bc8 4574 spa_activate(spa, FREAD);
34dc7c2f
BB
4575
4576 /*
4577 * Pass off the heavy lifting to spa_load().
4578 * Pass TRUE for mosconfig because the user-supplied config
4579 * is actually the one to trust when doing an import.
4580 */
428870ff 4581 error = spa_load(spa, SPA_LOAD_TRYIMPORT, SPA_IMPORT_EXISTING, B_TRUE);
34dc7c2f
BB
4582
4583 /*
4584 * If 'tryconfig' was at least parsable, return the current config.
4585 */
4586 if (spa->spa_root_vdev != NULL) {
34dc7c2f 4587 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
34dc7c2f
BB
4588 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME,
4589 poolname) == 0);
4590 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
4591 state) == 0);
4592 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
4593 spa->spa_uberblock.ub_timestamp) == 0);
9ae529ec
CS
4594 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
4595 spa->spa_load_info) == 0);
ffe9d382
BB
4596 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_ERRATA,
4597 spa->spa_errata) == 0);
34dc7c2f
BB
4598
4599 /*
4600 * If the bootfs property exists on this pool then we
4601 * copy it out so that external consumers can tell which
4602 * pools are bootable.
4603 */
d164b209 4604 if ((!error || error == EEXIST) && spa->spa_bootfs) {
79c76d5b 4605 char *tmpname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
34dc7c2f
BB
4606
4607 /*
4608 * We have to play games with the name since the
4609 * pool was opened as TRYIMPORT_NAME.
4610 */
b128c09f 4611 if (dsl_dsobj_to_dsname(spa_name(spa),
34dc7c2f
BB
4612 spa->spa_bootfs, tmpname) == 0) {
4613 char *cp;
d1d7e268
MK
4614 char *dsname;
4615
79c76d5b 4616 dsname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
34dc7c2f
BB
4617
4618 cp = strchr(tmpname, '/');
4619 if (cp == NULL) {
4620 (void) strlcpy(dsname, tmpname,
4621 MAXPATHLEN);
4622 } else {
4623 (void) snprintf(dsname, MAXPATHLEN,
4624 "%s/%s", poolname, ++cp);
4625 }
4626 VERIFY(nvlist_add_string(config,
4627 ZPOOL_CONFIG_BOOTFS, dsname) == 0);
4628 kmem_free(dsname, MAXPATHLEN);
4629 }
4630 kmem_free(tmpname, MAXPATHLEN);
4631 }
4632
4633 /*
4634 * Add the list of hot spares and level 2 cache devices.
4635 */
9babb374 4636 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
34dc7c2f
BB
4637 spa_add_spares(spa, config);
4638 spa_add_l2cache(spa, config);
9babb374 4639 spa_config_exit(spa, SCL_CONFIG, FTAG);
34dc7c2f
BB
4640 }
4641
4642 spa_unload(spa);
4643 spa_deactivate(spa);
4644 spa_remove(spa);
4645 mutex_exit(&spa_namespace_lock);
4646
4647 return (config);
4648}
4649
4650/*
4651 * Pool export/destroy
4652 *
4653 * The act of destroying or exporting a pool is very simple. We make sure there
4654 * is no more pending I/O and any references to the pool are gone. Then, we
4655 * update the pool state and sync all the labels to disk, removing the
fb5f0bc8
BB
4656 * configuration from the cache afterwards. If the 'hardforce' flag is set, then
4657 * we don't sync the labels or remove the configuration cache.
34dc7c2f
BB
4658 */
4659static int
b128c09f 4660spa_export_common(char *pool, int new_state, nvlist_t **oldconfig,
fb5f0bc8 4661 boolean_t force, boolean_t hardforce)
34dc7c2f
BB
4662{
4663 spa_t *spa;
4664
4665 if (oldconfig)
4666 *oldconfig = NULL;
4667
fb5f0bc8 4668 if (!(spa_mode_global & FWRITE))
2e528b49 4669 return (SET_ERROR(EROFS));
34dc7c2f
BB
4670
4671 mutex_enter(&spa_namespace_lock);
4672 if ((spa = spa_lookup(pool)) == NULL) {
4673 mutex_exit(&spa_namespace_lock);
2e528b49 4674 return (SET_ERROR(ENOENT));
34dc7c2f
BB
4675 }
4676
4677 /*
4678 * Put a hold on the pool, drop the namespace lock, stop async tasks,
4679 * reacquire the namespace lock, and see if we can export.
4680 */
4681 spa_open_ref(spa, FTAG);
4682 mutex_exit(&spa_namespace_lock);
4683 spa_async_suspend(spa);
a0bd735a
BP
4684 if (spa->spa_zvol_taskq) {
4685 zvol_remove_minors(spa, spa_name(spa), B_TRUE);
4686 taskq_wait(spa->spa_zvol_taskq);
4687 }
34dc7c2f
BB
4688 mutex_enter(&spa_namespace_lock);
4689 spa_close(spa, FTAG);
4690
d14cfd83
IH
4691 if (spa->spa_state == POOL_STATE_UNINITIALIZED)
4692 goto export_spa;
34dc7c2f 4693 /*
d14cfd83
IH
4694 * The pool will be in core if it's openable, in which case we can
4695 * modify its state. Objsets may be open only because they're dirty,
4696 * so we have to force it to sync before checking spa_refcnt.
34dc7c2f 4697 */
0c66c32d 4698 if (spa->spa_sync_on) {
34dc7c2f 4699 txg_wait_synced(spa->spa_dsl_pool, 0);
0c66c32d
JG
4700 spa_evicting_os_wait(spa);
4701 }
34dc7c2f 4702
d14cfd83
IH
4703 /*
4704 * A pool cannot be exported or destroyed if there are active
4705 * references. If we are resetting a pool, allow references by
4706 * fault injection handlers.
4707 */
4708 if (!spa_refcount_zero(spa) ||
4709 (spa->spa_inject_ref != 0 &&
4710 new_state != POOL_STATE_UNINITIALIZED)) {
4711 spa_async_resume(spa);
4712 mutex_exit(&spa_namespace_lock);
4713 return (SET_ERROR(EBUSY));
4714 }
34dc7c2f 4715
d14cfd83 4716 if (spa->spa_sync_on) {
b128c09f
BB
4717 /*
4718 * A pool cannot be exported if it has an active shared spare.
4719 * This is to prevent other pools stealing the active spare
4720 * from an exported pool. At user's own will, such pool can
4721 * be forcedly exported.
4722 */
4723 if (!force && new_state == POOL_STATE_EXPORTED &&
4724 spa_has_active_shared_spare(spa)) {
4725 spa_async_resume(spa);
4726 mutex_exit(&spa_namespace_lock);
2e528b49 4727 return (SET_ERROR(EXDEV));
b128c09f 4728 }
34dc7c2f
BB
4729
4730 /*
4731 * We want this to be reflected on every label,
4732 * so mark them all dirty. spa_unload() will do the
4733 * final sync that pushes these changes out.
4734 */
fb5f0bc8 4735 if (new_state != POOL_STATE_UNINITIALIZED && !hardforce) {
b128c09f 4736 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 4737 spa->spa_state = new_state;
428870ff
BB
4738 spa->spa_final_txg = spa_last_synced_txg(spa) +
4739 TXG_DEFER_SIZE + 1;
34dc7c2f 4740 vdev_config_dirty(spa->spa_root_vdev);
b128c09f 4741 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
4742 }
4743 }
4744
d14cfd83 4745export_spa:
d5e024cb
BB
4746 if (new_state == POOL_STATE_DESTROYED)
4747 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_DESTROY);
4748 else if (new_state == POOL_STATE_EXPORTED)
4749 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_EXPORT);
34dc7c2f
BB
4750
4751 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
4752 spa_unload(spa);
4753 spa_deactivate(spa);
4754 }
4755
4756 if (oldconfig && spa->spa_config)
4757 VERIFY(nvlist_dup(spa->spa_config, oldconfig, 0) == 0);
4758
4759 if (new_state != POOL_STATE_UNINITIALIZED) {
fb5f0bc8 4760 if (!hardforce)
a1d477c2 4761 spa_write_cachefile(spa, B_TRUE, B_TRUE);
34dc7c2f 4762 spa_remove(spa);
34dc7c2f
BB
4763 }
4764 mutex_exit(&spa_namespace_lock);
4765
4766 return (0);
4767}
4768
4769/*
4770 * Destroy a storage pool.
4771 */
4772int
4773spa_destroy(char *pool)
4774{
fb5f0bc8
BB
4775 return (spa_export_common(pool, POOL_STATE_DESTROYED, NULL,
4776 B_FALSE, B_FALSE));
34dc7c2f
BB
4777}
4778
4779/*
4780 * Export a storage pool.
4781 */
4782int
fb5f0bc8
BB
4783spa_export(char *pool, nvlist_t **oldconfig, boolean_t force,
4784 boolean_t hardforce)
34dc7c2f 4785{
fb5f0bc8
BB
4786 return (spa_export_common(pool, POOL_STATE_EXPORTED, oldconfig,
4787 force, hardforce));
34dc7c2f
BB
4788}
4789
4790/*
4791 * Similar to spa_export(), this unloads the spa_t without actually removing it
4792 * from the namespace in any way.
4793 */
4794int
4795spa_reset(char *pool)
4796{
b128c09f 4797 return (spa_export_common(pool, POOL_STATE_UNINITIALIZED, NULL,
fb5f0bc8 4798 B_FALSE, B_FALSE));
34dc7c2f
BB
4799}
4800
34dc7c2f
BB
4801/*
4802 * ==========================================================================
4803 * Device manipulation
4804 * ==========================================================================
4805 */
4806
4807/*
4808 * Add a device to a storage pool.
4809 */
4810int
4811spa_vdev_add(spa_t *spa, nvlist_t *nvroot)
4812{
428870ff 4813 uint64_t txg, id;
fb5f0bc8 4814 int error;
34dc7c2f
BB
4815 vdev_t *rvd = spa->spa_root_vdev;
4816 vdev_t *vd, *tvd;
4817 nvlist_t **spares, **l2cache;
4818 uint_t nspares, nl2cache;
4819
572e2857
BB
4820 ASSERT(spa_writeable(spa));
4821
34dc7c2f
BB
4822 txg = spa_vdev_enter(spa);
4823
4824 if ((error = spa_config_parse(spa, &vd, nvroot, NULL, 0,
4825 VDEV_ALLOC_ADD)) != 0)
4826 return (spa_vdev_exit(spa, NULL, txg, error));
4827
b128c09f 4828 spa->spa_pending_vdev = vd; /* spa_vdev_exit() will clear this */
34dc7c2f
BB
4829
4830 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares,
4831 &nspares) != 0)
4832 nspares = 0;
4833
4834 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE, &l2cache,
4835 &nl2cache) != 0)
4836 nl2cache = 0;
4837
b128c09f 4838 if (vd->vdev_children == 0 && nspares == 0 && nl2cache == 0)
34dc7c2f 4839 return (spa_vdev_exit(spa, vd, txg, EINVAL));
34dc7c2f 4840
b128c09f
BB
4841 if (vd->vdev_children != 0 &&
4842 (error = vdev_create(vd, txg, B_FALSE)) != 0)
4843 return (spa_vdev_exit(spa, vd, txg, error));
34dc7c2f
BB
4844
4845 /*
4846 * We must validate the spares and l2cache devices after checking the
4847 * children. Otherwise, vdev_inuse() will blindly overwrite the spare.
4848 */
b128c09f 4849 if ((error = spa_validate_aux(spa, nvroot, txg, VDEV_ALLOC_ADD)) != 0)
34dc7c2f 4850 return (spa_vdev_exit(spa, vd, txg, error));
34dc7c2f
BB
4851
4852 /*
a1d477c2
MA
4853 * If we are in the middle of a device removal, we can only add
4854 * devices which match the existing devices in the pool.
4855 * If we are in the middle of a removal, or have some indirect
4856 * vdevs, we can not add raidz toplevels.
34dc7c2f 4857 */
a1d477c2
MA
4858 if (spa->spa_vdev_removal != NULL ||
4859 spa->spa_removing_phys.sr_prev_indirect_vdev != -1) {
4860 for (int c = 0; c < vd->vdev_children; c++) {
4861 tvd = vd->vdev_child[c];
4862 if (spa->spa_vdev_removal != NULL &&
9e052db4 4863 tvd->vdev_ashift != spa->spa_max_ashift) {
a1d477c2
MA
4864 return (spa_vdev_exit(spa, vd, txg, EINVAL));
4865 }
4866 /* Fail if top level vdev is raidz */
4867 if (tvd->vdev_ops == &vdev_raidz_ops) {
4868 return (spa_vdev_exit(spa, vd, txg, EINVAL));
4869 }
4870 /*
4871 * Need the top level mirror to be
4872 * a mirror of leaf vdevs only
4873 */
4874 if (tvd->vdev_ops == &vdev_mirror_ops) {
4875 for (uint64_t cid = 0;
4876 cid < tvd->vdev_children; cid++) {
4877 vdev_t *cvd = tvd->vdev_child[cid];
4878 if (!cvd->vdev_ops->vdev_op_leaf) {
4879 return (spa_vdev_exit(spa, vd,
4880 txg, EINVAL));
4881 }
4882 }
4883 }
4884 }
4885 }
4886
1c27024e 4887 for (int c = 0; c < vd->vdev_children; c++) {
428870ff
BB
4888
4889 /*
4890 * Set the vdev id to the first hole, if one exists.
4891 */
4892 for (id = 0; id < rvd->vdev_children; id++) {
4893 if (rvd->vdev_child[id]->vdev_ishole) {
4894 vdev_free(rvd->vdev_child[id]);
4895 break;
4896 }
4897 }
34dc7c2f
BB
4898 tvd = vd->vdev_child[c];
4899 vdev_remove_child(vd, tvd);
428870ff 4900 tvd->vdev_id = id;
34dc7c2f
BB
4901 vdev_add_child(rvd, tvd);
4902 vdev_config_dirty(tvd);
4903 }
4904
4905 if (nspares != 0) {
4906 spa_set_aux_vdevs(&spa->spa_spares, spares, nspares,
4907 ZPOOL_CONFIG_SPARES);
4908 spa_load_spares(spa);
4909 spa->spa_spares.sav_sync = B_TRUE;
4910 }
4911
4912 if (nl2cache != 0) {
4913 spa_set_aux_vdevs(&spa->spa_l2cache, l2cache, nl2cache,
4914 ZPOOL_CONFIG_L2CACHE);
4915 spa_load_l2cache(spa);
4916 spa->spa_l2cache.sav_sync = B_TRUE;
4917 }
4918
4919 /*
4920 * We have to be careful when adding new vdevs to an existing pool.
4921 * If other threads start allocating from these vdevs before we
4922 * sync the config cache, and we lose power, then upon reboot we may
4923 * fail to open the pool because there are DVAs that the config cache
4924 * can't translate. Therefore, we first add the vdevs without
4925 * initializing metaslabs; sync the config cache (via spa_vdev_exit());
4926 * and then let spa_config_update() initialize the new metaslabs.
4927 *
4928 * spa_load() checks for added-but-not-initialized vdevs, so that
4929 * if we lose power at any point in this sequence, the remaining
4930 * steps will be completed the next time we load the pool.
4931 */
4932 (void) spa_vdev_exit(spa, vd, txg, 0);
4933
4934 mutex_enter(&spa_namespace_lock);
4935 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
12fa0466 4936 spa_event_notify(spa, NULL, NULL, ESC_ZFS_VDEV_ADD);
34dc7c2f
BB
4937 mutex_exit(&spa_namespace_lock);
4938
4939 return (0);
4940}
4941
4942/*
4943 * Attach a device to a mirror. The arguments are the path to any device
4944 * in the mirror, and the nvroot for the new device. If the path specifies
4945 * a device that is not mirrored, we automatically insert the mirror vdev.
4946 *
4947 * If 'replacing' is specified, the new device is intended to replace the
4948 * existing device; in this case the two devices are made into their own
4949 * mirror using the 'replacing' vdev, which is functionally identical to
4950 * the mirror vdev (it actually reuses all the same ops) but has a few
4951 * extra rules: you can't attach to it after it's been created, and upon
4952 * completion of resilvering, the first disk (the one being replaced)
4953 * is automatically detached.
4954 */
4955int
4956spa_vdev_attach(spa_t *spa, uint64_t guid, nvlist_t *nvroot, int replacing)
4957{
428870ff 4958 uint64_t txg, dtl_max_txg;
1c27024e 4959 ASSERTV(vdev_t *rvd = spa->spa_root_vdev);
34dc7c2f
BB
4960 vdev_t *oldvd, *newvd, *newrootvd, *pvd, *tvd;
4961 vdev_ops_t *pvops;
b128c09f
BB
4962 char *oldvdpath, *newvdpath;
4963 int newvd_isspare;
4964 int error;
34dc7c2f 4965
572e2857
BB
4966 ASSERT(spa_writeable(spa));
4967
34dc7c2f
BB
4968 txg = spa_vdev_enter(spa);
4969
b128c09f 4970 oldvd = spa_lookup_by_guid(spa, guid, B_FALSE);
34dc7c2f 4971
9e052db4 4972 if (spa->spa_vdev_removal != NULL)
a1d477c2 4973 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
a1d477c2 4974
34dc7c2f
BB
4975 if (oldvd == NULL)
4976 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
4977
4978 if (!oldvd->vdev_ops->vdev_op_leaf)
4979 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
4980
4981 pvd = oldvd->vdev_parent;
4982
4983 if ((error = spa_config_parse(spa, &newrootvd, nvroot, NULL, 0,
5ffb9d1d 4984 VDEV_ALLOC_ATTACH)) != 0)
34dc7c2f
BB
4985 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
4986
4987 if (newrootvd->vdev_children != 1)
4988 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
4989
4990 newvd = newrootvd->vdev_child[0];
4991
4992 if (!newvd->vdev_ops->vdev_op_leaf)
4993 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
4994
4995 if ((error = vdev_create(newrootvd, txg, replacing)) != 0)
4996 return (spa_vdev_exit(spa, newrootvd, txg, error));
4997
4998 /*
4999 * Spares can't replace logs
5000 */
b128c09f 5001 if (oldvd->vdev_top->vdev_islog && newvd->vdev_isspare)
34dc7c2f
BB
5002 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
5003
5004 if (!replacing) {
5005 /*
5006 * For attach, the only allowable parent is a mirror or the root
5007 * vdev.
5008 */
5009 if (pvd->vdev_ops != &vdev_mirror_ops &&
5010 pvd->vdev_ops != &vdev_root_ops)
5011 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
5012
5013 pvops = &vdev_mirror_ops;
5014 } else {
5015 /*
5016 * Active hot spares can only be replaced by inactive hot
5017 * spares.
5018 */
5019 if (pvd->vdev_ops == &vdev_spare_ops &&
572e2857 5020 oldvd->vdev_isspare &&
34dc7c2f
BB
5021 !spa_has_spare(spa, newvd->vdev_guid))
5022 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
5023
5024 /*
5025 * If the source is a hot spare, and the parent isn't already a
5026 * spare, then we want to create a new hot spare. Otherwise, we
5027 * want to create a replacing vdev. The user is not allowed to
5028 * attach to a spared vdev child unless the 'isspare' state is
5029 * the same (spare replaces spare, non-spare replaces
5030 * non-spare).
5031 */
572e2857
BB
5032 if (pvd->vdev_ops == &vdev_replacing_ops &&
5033 spa_version(spa) < SPA_VERSION_MULTI_REPLACE) {
34dc7c2f 5034 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
572e2857
BB
5035 } else if (pvd->vdev_ops == &vdev_spare_ops &&
5036 newvd->vdev_isspare != oldvd->vdev_isspare) {
34dc7c2f 5037 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
572e2857
BB
5038 }
5039
5040 if (newvd->vdev_isspare)
34dc7c2f
BB
5041 pvops = &vdev_spare_ops;
5042 else
5043 pvops = &vdev_replacing_ops;
5044 }
5045
5046 /*
9babb374 5047 * Make sure the new device is big enough.
34dc7c2f 5048 */
9babb374 5049 if (newvd->vdev_asize < vdev_get_min_asize(oldvd))
34dc7c2f
BB
5050 return (spa_vdev_exit(spa, newrootvd, txg, EOVERFLOW));
5051
5052 /*
5053 * The new device cannot have a higher alignment requirement
5054 * than the top-level vdev.
5055 */
5056 if (newvd->vdev_ashift > oldvd->vdev_top->vdev_ashift)
5057 return (spa_vdev_exit(spa, newrootvd, txg, EDOM));
5058
5059 /*
5060 * If this is an in-place replacement, update oldvd's path and devid
5061 * to make it distinguishable from newvd, and unopenable from now on.
5062 */
5063 if (strcmp(oldvd->vdev_path, newvd->vdev_path) == 0) {
5064 spa_strfree(oldvd->vdev_path);
5065 oldvd->vdev_path = kmem_alloc(strlen(newvd->vdev_path) + 5,
79c76d5b 5066 KM_SLEEP);
34dc7c2f
BB
5067 (void) sprintf(oldvd->vdev_path, "%s/%s",
5068 newvd->vdev_path, "old");
5069 if (oldvd->vdev_devid != NULL) {
5070 spa_strfree(oldvd->vdev_devid);
5071 oldvd->vdev_devid = NULL;
5072 }
5073 }
5074
572e2857 5075 /* mark the device being resilvered */
5d1f7fb6 5076 newvd->vdev_resilver_txg = txg;
572e2857 5077
34dc7c2f
BB
5078 /*
5079 * If the parent is not a mirror, or if we're replacing, insert the new
5080 * mirror/replacing/spare vdev above oldvd.
5081 */
5082 if (pvd->vdev_ops != pvops)
5083 pvd = vdev_add_parent(oldvd, pvops);
5084
5085 ASSERT(pvd->vdev_top->vdev_parent == rvd);
5086 ASSERT(pvd->vdev_ops == pvops);
5087 ASSERT(oldvd->vdev_parent == pvd);
5088
5089 /*
5090 * Extract the new device from its root and add it to pvd.
5091 */
5092 vdev_remove_child(newrootvd, newvd);
5093 newvd->vdev_id = pvd->vdev_children;
428870ff 5094 newvd->vdev_crtxg = oldvd->vdev_crtxg;
34dc7c2f
BB
5095 vdev_add_child(pvd, newvd);
5096
6d82f98c
IH
5097 /*
5098 * Reevaluate the parent vdev state.
5099 */
5100 vdev_propagate_state(pvd);
5101
34dc7c2f
BB
5102 tvd = newvd->vdev_top;
5103 ASSERT(pvd->vdev_top == tvd);
5104 ASSERT(tvd->vdev_parent == rvd);
5105
5106 vdev_config_dirty(tvd);
5107
5108 /*
428870ff
BB
5109 * Set newvd's DTL to [TXG_INITIAL, dtl_max_txg) so that we account
5110 * for any dmu_sync-ed blocks. It will propagate upward when
5111 * spa_vdev_exit() calls vdev_dtl_reassess().
34dc7c2f 5112 */
428870ff 5113 dtl_max_txg = txg + TXG_CONCURRENT_STATES;
34dc7c2f 5114
428870ff
BB
5115 vdev_dtl_dirty(newvd, DTL_MISSING, TXG_INITIAL,
5116 dtl_max_txg - TXG_INITIAL);
34dc7c2f 5117
9babb374 5118 if (newvd->vdev_isspare) {
34dc7c2f 5119 spa_spare_activate(newvd);
12fa0466 5120 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_SPARE);
9babb374
BB
5121 }
5122
b128c09f
BB
5123 oldvdpath = spa_strdup(oldvd->vdev_path);
5124 newvdpath = spa_strdup(newvd->vdev_path);
5125 newvd_isspare = newvd->vdev_isspare;
34dc7c2f
BB
5126
5127 /*
5128 * Mark newvd's DTL dirty in this txg.
5129 */
5130 vdev_dirty(tvd, VDD_DTL, newvd, txg);
5131
428870ff 5132 /*
93cf2076
GW
5133 * Schedule the resilver to restart in the future. We do this to
5134 * ensure that dmu_sync-ed blocks have been stitched into the
5135 * respective datasets.
428870ff
BB
5136 */
5137 dsl_resilver_restart(spa->spa_dsl_pool, dtl_max_txg);
5138
fb390aaf 5139 if (spa->spa_bootfs)
12fa0466 5140 spa_event_notify(spa, newvd, NULL, ESC_ZFS_BOOTFS_VDEV_ATTACH);
fb390aaf 5141
12fa0466 5142 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_ATTACH);
fb390aaf 5143
428870ff
BB
5144 /*
5145 * Commit the config
5146 */
5147 (void) spa_vdev_exit(spa, newrootvd, dtl_max_txg, 0);
34dc7c2f 5148
6f1ffb06 5149 spa_history_log_internal(spa, "vdev attach", NULL,
428870ff 5150 "%s vdev=%s %s vdev=%s",
45d1cae3
BB
5151 replacing && newvd_isspare ? "spare in" :
5152 replacing ? "replace" : "attach", newvdpath,
5153 replacing ? "for" : "to", oldvdpath);
b128c09f
BB
5154
5155 spa_strfree(oldvdpath);
5156 spa_strfree(newvdpath);
5157
34dc7c2f
BB
5158 return (0);
5159}
5160
5161/*
5162 * Detach a device from a mirror or replacing vdev.
d3cc8b15 5163 *
34dc7c2f
BB
5164 * If 'replace_done' is specified, only detach if the parent
5165 * is a replacing vdev.
5166 */
5167int
fb5f0bc8 5168spa_vdev_detach(spa_t *spa, uint64_t guid, uint64_t pguid, int replace_done)
34dc7c2f
BB
5169{
5170 uint64_t txg;
fb5f0bc8 5171 int error;
1c27024e 5172 ASSERTV(vdev_t *rvd = spa->spa_root_vdev);
34dc7c2f
BB
5173 vdev_t *vd, *pvd, *cvd, *tvd;
5174 boolean_t unspare = B_FALSE;
d4ed6673 5175 uint64_t unspare_guid = 0;
428870ff 5176 char *vdpath;
1c27024e 5177
572e2857
BB
5178 ASSERT(spa_writeable(spa));
5179
34dc7c2f
BB
5180 txg = spa_vdev_enter(spa);
5181
b128c09f 5182 vd = spa_lookup_by_guid(spa, guid, B_FALSE);
34dc7c2f
BB
5183
5184 if (vd == NULL)
5185 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
5186
5187 if (!vd->vdev_ops->vdev_op_leaf)
5188 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
5189
5190 pvd = vd->vdev_parent;
5191
fb5f0bc8
BB
5192 /*
5193 * If the parent/child relationship is not as expected, don't do it.
5194 * Consider M(A,R(B,C)) -- that is, a mirror of A with a replacing
5195 * vdev that's replacing B with C. The user's intent in replacing
5196 * is to go from M(A,B) to M(A,C). If the user decides to cancel
5197 * the replace by detaching C, the expected behavior is to end up
5198 * M(A,B). But suppose that right after deciding to detach C,
5199 * the replacement of B completes. We would have M(A,C), and then
5200 * ask to detach C, which would leave us with just A -- not what
5201 * the user wanted. To prevent this, we make sure that the
5202 * parent/child relationship hasn't changed -- in this example,
5203 * that C's parent is still the replacing vdev R.
5204 */
5205 if (pvd->vdev_guid != pguid && pguid != 0)
5206 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
5207
34dc7c2f 5208 /*
572e2857 5209 * Only 'replacing' or 'spare' vdevs can be replaced.
34dc7c2f 5210 */
572e2857
BB
5211 if (replace_done && pvd->vdev_ops != &vdev_replacing_ops &&
5212 pvd->vdev_ops != &vdev_spare_ops)
5213 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
34dc7c2f
BB
5214
5215 ASSERT(pvd->vdev_ops != &vdev_spare_ops ||
5216 spa_version(spa) >= SPA_VERSION_SPARES);
5217
5218 /*
5219 * Only mirror, replacing, and spare vdevs support detach.
5220 */
5221 if (pvd->vdev_ops != &vdev_replacing_ops &&
5222 pvd->vdev_ops != &vdev_mirror_ops &&
5223 pvd->vdev_ops != &vdev_spare_ops)
5224 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
5225
5226 /*
fb5f0bc8
BB
5227 * If this device has the only valid copy of some data,
5228 * we cannot safely detach it.
34dc7c2f 5229 */
fb5f0bc8 5230 if (vdev_dtl_required(vd))
34dc7c2f
BB
5231 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
5232
fb5f0bc8 5233 ASSERT(pvd->vdev_children >= 2);
34dc7c2f 5234
b128c09f
BB
5235 /*
5236 * If we are detaching the second disk from a replacing vdev, then
5237 * check to see if we changed the original vdev's path to have "/old"
5238 * at the end in spa_vdev_attach(). If so, undo that change now.
5239 */
572e2857
BB
5240 if (pvd->vdev_ops == &vdev_replacing_ops && vd->vdev_id > 0 &&
5241 vd->vdev_path != NULL) {
5242 size_t len = strlen(vd->vdev_path);
5243
1c27024e 5244 for (int c = 0; c < pvd->vdev_children; c++) {
572e2857
BB
5245 cvd = pvd->vdev_child[c];
5246
5247 if (cvd == vd || cvd->vdev_path == NULL)
5248 continue;
5249
5250 if (strncmp(cvd->vdev_path, vd->vdev_path, len) == 0 &&
5251 strcmp(cvd->vdev_path + len, "/old") == 0) {
5252 spa_strfree(cvd->vdev_path);
5253 cvd->vdev_path = spa_strdup(vd->vdev_path);
5254 break;
5255 }
b128c09f
BB
5256 }
5257 }
5258
34dc7c2f
BB
5259 /*
5260 * If we are detaching the original disk from a spare, then it implies
5261 * that the spare should become a real disk, and be removed from the
5262 * active spare list for the pool.
5263 */
5264 if (pvd->vdev_ops == &vdev_spare_ops &&
572e2857
BB
5265 vd->vdev_id == 0 &&
5266 pvd->vdev_child[pvd->vdev_children - 1]->vdev_isspare)
34dc7c2f
BB
5267 unspare = B_TRUE;
5268
5269 /*
5270 * Erase the disk labels so the disk can be used for other things.
5271 * This must be done after all other error cases are handled,
5272 * but before we disembowel vd (so we can still do I/O to it).
5273 * But if we can't do it, don't treat the error as fatal --
5274 * it may be that the unwritability of the disk is the reason
5275 * it's being detached!
5276 */
5277 error = vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
5278
5279 /*
5280 * Remove vd from its parent and compact the parent's children.
5281 */
5282 vdev_remove_child(pvd, vd);
5283 vdev_compact_children(pvd);
5284
5285 /*
5286 * Remember one of the remaining children so we can get tvd below.
5287 */
572e2857 5288 cvd = pvd->vdev_child[pvd->vdev_children - 1];
34dc7c2f
BB
5289
5290 /*
5291 * If we need to remove the remaining child from the list of hot spares,
fb5f0bc8
BB
5292 * do it now, marking the vdev as no longer a spare in the process.
5293 * We must do this before vdev_remove_parent(), because that can
5294 * change the GUID if it creates a new toplevel GUID. For a similar
5295 * reason, we must remove the spare now, in the same txg as the detach;
5296 * otherwise someone could attach a new sibling, change the GUID, and
5297 * the subsequent attempt to spa_vdev_remove(unspare_guid) would fail.
34dc7c2f
BB
5298 */
5299 if (unspare) {
5300 ASSERT(cvd->vdev_isspare);
5301 spa_spare_remove(cvd);
5302 unspare_guid = cvd->vdev_guid;
fb5f0bc8 5303 (void) spa_vdev_remove(spa, unspare_guid, B_TRUE);
572e2857 5304 cvd->vdev_unspare = B_TRUE;
34dc7c2f
BB
5305 }
5306
428870ff
BB
5307 /*
5308 * If the parent mirror/replacing vdev only has one child,
5309 * the parent is no longer needed. Remove it from the tree.
5310 */
572e2857
BB
5311 if (pvd->vdev_children == 1) {
5312 if (pvd->vdev_ops == &vdev_spare_ops)
5313 cvd->vdev_unspare = B_FALSE;
428870ff 5314 vdev_remove_parent(cvd);
572e2857
BB
5315 }
5316
428870ff
BB
5317
5318 /*
5319 * We don't set tvd until now because the parent we just removed
5320 * may have been the previous top-level vdev.
5321 */
5322 tvd = cvd->vdev_top;
5323 ASSERT(tvd->vdev_parent == rvd);
5324
5325 /*
5326 * Reevaluate the parent vdev state.
5327 */
5328 vdev_propagate_state(cvd);
5329
5330 /*
5331 * If the 'autoexpand' property is set on the pool then automatically
5332 * try to expand the size of the pool. For example if the device we
5333 * just detached was smaller than the others, it may be possible to
5334 * add metaslabs (i.e. grow the pool). We need to reopen the vdev
5335 * first so that we can obtain the updated sizes of the leaf vdevs.
5336 */
5337 if (spa->spa_autoexpand) {
5338 vdev_reopen(tvd);
5339 vdev_expand(tvd, txg);
5340 }
5341
5342 vdev_config_dirty(tvd);
5343
5344 /*
5345 * Mark vd's DTL as dirty in this txg. vdev_dtl_sync() will see that
5346 * vd->vdev_detached is set and free vd's DTL object in syncing context.
5347 * But first make sure we're not on any *other* txg's DTL list, to
5348 * prevent vd from being accessed after it's freed.
5349 */
b6ca6193 5350 vdpath = spa_strdup(vd->vdev_path ? vd->vdev_path : "none");
1c27024e 5351 for (int t = 0; t < TXG_SIZE; t++)
428870ff
BB
5352 (void) txg_list_remove_this(&tvd->vdev_dtl_list, vd, t);
5353 vd->vdev_detached = B_TRUE;
5354 vdev_dirty(tvd, VDD_DTL, vd, txg);
5355
12fa0466 5356 spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE);
428870ff 5357
572e2857
BB
5358 /* hang on to the spa before we release the lock */
5359 spa_open_ref(spa, FTAG);
5360
428870ff
BB
5361 error = spa_vdev_exit(spa, vd, txg, 0);
5362
6f1ffb06 5363 spa_history_log_internal(spa, "detach", NULL,
428870ff
BB
5364 "vdev=%s", vdpath);
5365 spa_strfree(vdpath);
5366
5367 /*
5368 * If this was the removal of the original device in a hot spare vdev,
5369 * then we want to go through and remove the device from the hot spare
5370 * list of every other pool.
5371 */
5372 if (unspare) {
572e2857
BB
5373 spa_t *altspa = NULL;
5374
428870ff 5375 mutex_enter(&spa_namespace_lock);
572e2857
BB
5376 while ((altspa = spa_next(altspa)) != NULL) {
5377 if (altspa->spa_state != POOL_STATE_ACTIVE ||
5378 altspa == spa)
428870ff 5379 continue;
572e2857
BB
5380
5381 spa_open_ref(altspa, FTAG);
428870ff 5382 mutex_exit(&spa_namespace_lock);
572e2857 5383 (void) spa_vdev_remove(altspa, unspare_guid, B_TRUE);
428870ff 5384 mutex_enter(&spa_namespace_lock);
572e2857 5385 spa_close(altspa, FTAG);
428870ff
BB
5386 }
5387 mutex_exit(&spa_namespace_lock);
572e2857
BB
5388
5389 /* search the rest of the vdevs for spares to remove */
5390 spa_vdev_resilver_done(spa);
428870ff
BB
5391 }
5392
572e2857
BB
5393 /* all done with the spa; OK to release */
5394 mutex_enter(&spa_namespace_lock);
5395 spa_close(spa, FTAG);
5396 mutex_exit(&spa_namespace_lock);
5397
428870ff
BB
5398 return (error);
5399}
5400
5401/*
5402 * Split a set of devices from their mirrors, and create a new pool from them.
5403 */
5404int
5405spa_vdev_split_mirror(spa_t *spa, char *newname, nvlist_t *config,
5406 nvlist_t *props, boolean_t exp)
5407{
5408 int error = 0;
5409 uint64_t txg, *glist;
5410 spa_t *newspa;
5411 uint_t c, children, lastlog;
5412 nvlist_t **child, *nvl, *tmp;
5413 dmu_tx_t *tx;
5414 char *altroot = NULL;
5415 vdev_t *rvd, **vml = NULL; /* vdev modify list */
5416 boolean_t activate_slog;
5417
572e2857 5418 ASSERT(spa_writeable(spa));
428870ff
BB
5419
5420 txg = spa_vdev_enter(spa);
5421
5422 /* clear the log and flush everything up to now */
5423 activate_slog = spa_passivate_log(spa);
5424 (void) spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
a1d477c2 5425 error = spa_reset_logs(spa);
428870ff
BB
5426 txg = spa_vdev_config_enter(spa);
5427
5428 if (activate_slog)
5429 spa_activate_log(spa);
5430
5431 if (error != 0)
5432 return (spa_vdev_exit(spa, NULL, txg, error));
5433
5434 /* check new spa name before going any further */
5435 if (spa_lookup(newname) != NULL)
5436 return (spa_vdev_exit(spa, NULL, txg, EEXIST));
5437
5438 /*
5439 * scan through all the children to ensure they're all mirrors
5440 */
5441 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvl) != 0 ||
5442 nvlist_lookup_nvlist_array(nvl, ZPOOL_CONFIG_CHILDREN, &child,
5443 &children) != 0)
5444 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
5445
5446 /* first, check to ensure we've got the right child count */
5447 rvd = spa->spa_root_vdev;
5448 lastlog = 0;
5449 for (c = 0; c < rvd->vdev_children; c++) {
5450 vdev_t *vd = rvd->vdev_child[c];
5451
5452 /* don't count the holes & logs as children */
a1d477c2 5453 if (vd->vdev_islog || !vdev_is_concrete(vd)) {
428870ff
BB
5454 if (lastlog == 0)
5455 lastlog = c;
5456 continue;
5457 }
5458
5459 lastlog = 0;
5460 }
5461 if (children != (lastlog != 0 ? lastlog : rvd->vdev_children))
5462 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
5463
5464 /* next, ensure no spare or cache devices are part of the split */
5465 if (nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_SPARES, &tmp) == 0 ||
5466 nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_L2CACHE, &tmp) == 0)
5467 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
5468
79c76d5b
BB
5469 vml = kmem_zalloc(children * sizeof (vdev_t *), KM_SLEEP);
5470 glist = kmem_zalloc(children * sizeof (uint64_t), KM_SLEEP);
428870ff
BB
5471
5472 /* then, loop over each vdev and validate it */
5473 for (c = 0; c < children; c++) {
5474 uint64_t is_hole = 0;
5475
5476 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
5477 &is_hole);
5478
5479 if (is_hole != 0) {
5480 if (spa->spa_root_vdev->vdev_child[c]->vdev_ishole ||
5481 spa->spa_root_vdev->vdev_child[c]->vdev_islog) {
5482 continue;
5483 } else {
2e528b49 5484 error = SET_ERROR(EINVAL);
428870ff
BB
5485 break;
5486 }
5487 }
5488
5489 /* which disk is going to be split? */
5490 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_GUID,
5491 &glist[c]) != 0) {
2e528b49 5492 error = SET_ERROR(EINVAL);
428870ff
BB
5493 break;
5494 }
5495
5496 /* look it up in the spa */
5497 vml[c] = spa_lookup_by_guid(spa, glist[c], B_FALSE);
5498 if (vml[c] == NULL) {
2e528b49 5499 error = SET_ERROR(ENODEV);
428870ff
BB
5500 break;
5501 }
5502
5503 /* make sure there's nothing stopping the split */
5504 if (vml[c]->vdev_parent->vdev_ops != &vdev_mirror_ops ||
5505 vml[c]->vdev_islog ||
a1d477c2 5506 !vdev_is_concrete(vml[c]) ||
428870ff
BB
5507 vml[c]->vdev_isspare ||
5508 vml[c]->vdev_isl2cache ||
5509 !vdev_writeable(vml[c]) ||
5510 vml[c]->vdev_children != 0 ||
5511 vml[c]->vdev_state != VDEV_STATE_HEALTHY ||
5512 c != spa->spa_root_vdev->vdev_child[c]->vdev_id) {
2e528b49 5513 error = SET_ERROR(EINVAL);
428870ff
BB
5514 break;
5515 }
5516
5517 if (vdev_dtl_required(vml[c])) {
2e528b49 5518 error = SET_ERROR(EBUSY);
428870ff
BB
5519 break;
5520 }
5521
5522 /* we need certain info from the top level */
5523 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_ARRAY,
5524 vml[c]->vdev_top->vdev_ms_array) == 0);
5525 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_SHIFT,
5526 vml[c]->vdev_top->vdev_ms_shift) == 0);
5527 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASIZE,
5528 vml[c]->vdev_top->vdev_asize) == 0);
5529 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASHIFT,
5530 vml[c]->vdev_top->vdev_ashift) == 0);
e0ab3ab5
JS
5531
5532 /* transfer per-vdev ZAPs */
5533 ASSERT3U(vml[c]->vdev_leaf_zap, !=, 0);
5534 VERIFY0(nvlist_add_uint64(child[c],
5535 ZPOOL_CONFIG_VDEV_LEAF_ZAP, vml[c]->vdev_leaf_zap));
5536
5537 ASSERT3U(vml[c]->vdev_top->vdev_top_zap, !=, 0);
5538 VERIFY0(nvlist_add_uint64(child[c],
5539 ZPOOL_CONFIG_VDEV_TOP_ZAP,
5540 vml[c]->vdev_parent->vdev_top_zap));
428870ff
BB
5541 }
5542
5543 if (error != 0) {
5544 kmem_free(vml, children * sizeof (vdev_t *));
5545 kmem_free(glist, children * sizeof (uint64_t));
5546 return (spa_vdev_exit(spa, NULL, txg, error));
5547 }
5548
5549 /* stop writers from using the disks */
5550 for (c = 0; c < children; c++) {
5551 if (vml[c] != NULL)
5552 vml[c]->vdev_offline = B_TRUE;
5553 }
5554 vdev_reopen(spa->spa_root_vdev);
34dc7c2f
BB
5555
5556 /*
428870ff
BB
5557 * Temporarily record the splitting vdevs in the spa config. This
5558 * will disappear once the config is regenerated.
34dc7c2f 5559 */
79c76d5b 5560 VERIFY(nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
428870ff
BB
5561 VERIFY(nvlist_add_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
5562 glist, children) == 0);
5563 kmem_free(glist, children * sizeof (uint64_t));
34dc7c2f 5564
428870ff
BB
5565 mutex_enter(&spa->spa_props_lock);
5566 VERIFY(nvlist_add_nvlist(spa->spa_config, ZPOOL_CONFIG_SPLIT,
5567 nvl) == 0);
5568 mutex_exit(&spa->spa_props_lock);
5569 spa->spa_config_splitting = nvl;
5570 vdev_config_dirty(spa->spa_root_vdev);
5571
5572 /* configure and create the new pool */
5573 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME, newname) == 0);
5574 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
5575 exp ? POOL_STATE_EXPORTED : POOL_STATE_ACTIVE) == 0);
5576 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
5577 spa_version(spa)) == 0);
5578 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_TXG,
5579 spa->spa_config_txg) == 0);
5580 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_GUID,
5581 spa_generate_guid(NULL)) == 0);
e0ab3ab5 5582 VERIFY0(nvlist_add_boolean(config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
428870ff
BB
5583 (void) nvlist_lookup_string(props,
5584 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
34dc7c2f 5585
428870ff
BB
5586 /* add the new pool to the namespace */
5587 newspa = spa_add(newname, config, altroot);
e0ab3ab5 5588 newspa->spa_avz_action = AVZ_ACTION_REBUILD;
428870ff
BB
5589 newspa->spa_config_txg = spa->spa_config_txg;
5590 spa_set_log_state(newspa, SPA_LOG_CLEAR);
5591
5592 /* release the spa config lock, retaining the namespace lock */
5593 spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
5594
5595 if (zio_injection_enabled)
5596 zio_handle_panic_injection(spa, FTAG, 1);
5597
5598 spa_activate(newspa, spa_mode_global);
5599 spa_async_suspend(newspa);
5600
5601 /* create the new pool from the disks of the original pool */
5602 error = spa_load(newspa, SPA_LOAD_IMPORT, SPA_IMPORT_ASSEMBLE, B_TRUE);
5603 if (error)
5604 goto out;
5605
5606 /* if that worked, generate a real config for the new pool */
5607 if (newspa->spa_root_vdev != NULL) {
5608 VERIFY(nvlist_alloc(&newspa->spa_config_splitting,
79c76d5b 5609 NV_UNIQUE_NAME, KM_SLEEP) == 0);
428870ff
BB
5610 VERIFY(nvlist_add_uint64(newspa->spa_config_splitting,
5611 ZPOOL_CONFIG_SPLIT_GUID, spa_guid(spa)) == 0);
5612 spa_config_set(newspa, spa_config_generate(newspa, NULL, -1ULL,
5613 B_TRUE));
9babb374 5614 }
34dc7c2f 5615
428870ff
BB
5616 /* set the props */
5617 if (props != NULL) {
5618 spa_configfile_set(newspa, props, B_FALSE);
5619 error = spa_prop_set(newspa, props);
5620 if (error)
5621 goto out;
5622 }
34dc7c2f 5623
428870ff
BB
5624 /* flush everything */
5625 txg = spa_vdev_config_enter(newspa);
5626 vdev_config_dirty(newspa->spa_root_vdev);
5627 (void) spa_vdev_config_exit(newspa, NULL, txg, 0, FTAG);
34dc7c2f 5628
428870ff
BB
5629 if (zio_injection_enabled)
5630 zio_handle_panic_injection(spa, FTAG, 2);
34dc7c2f 5631
428870ff 5632 spa_async_resume(newspa);
34dc7c2f 5633
428870ff
BB
5634 /* finally, update the original pool's config */
5635 txg = spa_vdev_config_enter(spa);
5636 tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
5637 error = dmu_tx_assign(tx, TXG_WAIT);
5638 if (error != 0)
5639 dmu_tx_abort(tx);
5640 for (c = 0; c < children; c++) {
5641 if (vml[c] != NULL) {
5642 vdev_split(vml[c]);
5643 if (error == 0)
6f1ffb06
MA
5644 spa_history_log_internal(spa, "detach", tx,
5645 "vdev=%s", vml[c]->vdev_path);
e0ab3ab5 5646
428870ff 5647 vdev_free(vml[c]);
34dc7c2f 5648 }
34dc7c2f 5649 }
e0ab3ab5 5650 spa->spa_avz_action = AVZ_ACTION_REBUILD;
428870ff
BB
5651 vdev_config_dirty(spa->spa_root_vdev);
5652 spa->spa_config_splitting = NULL;
5653 nvlist_free(nvl);
5654 if (error == 0)
5655 dmu_tx_commit(tx);
5656 (void) spa_vdev_exit(spa, NULL, txg, 0);
5657
5658 if (zio_injection_enabled)
5659 zio_handle_panic_injection(spa, FTAG, 3);
5660
5661 /* split is complete; log a history record */
6f1ffb06
MA
5662 spa_history_log_internal(newspa, "split", NULL,
5663 "from pool %s", spa_name(spa));
428870ff
BB
5664
5665 kmem_free(vml, children * sizeof (vdev_t *));
5666
5667 /* if we're not going to mount the filesystems in userland, export */
5668 if (exp)
5669 error = spa_export_common(newname, POOL_STATE_EXPORTED, NULL,
5670 B_FALSE, B_FALSE);
5671
5672 return (error);
5673
5674out:
5675 spa_unload(newspa);
5676 spa_deactivate(newspa);
5677 spa_remove(newspa);
5678
5679 txg = spa_vdev_config_enter(spa);
5680
5681 /* re-online all offlined disks */
5682 for (c = 0; c < children; c++) {
5683 if (vml[c] != NULL)
5684 vml[c]->vdev_offline = B_FALSE;
5685 }
5686 vdev_reopen(spa->spa_root_vdev);
5687
5688 nvlist_free(spa->spa_config_splitting);
5689 spa->spa_config_splitting = NULL;
5690 (void) spa_vdev_exit(spa, NULL, txg, error);
34dc7c2f 5691
428870ff 5692 kmem_free(vml, children * sizeof (vdev_t *));
34dc7c2f
BB
5693 return (error);
5694}
5695
34dc7c2f
BB
5696/*
5697 * Find any device that's done replacing, or a vdev marked 'unspare' that's
d3cc8b15 5698 * currently spared, so we can detach it.
34dc7c2f
BB
5699 */
5700static vdev_t *
5701spa_vdev_resilver_done_hunt(vdev_t *vd)
5702{
5703 vdev_t *newvd, *oldvd;
34dc7c2f 5704
1c27024e 5705 for (int c = 0; c < vd->vdev_children; c++) {
34dc7c2f
BB
5706 oldvd = spa_vdev_resilver_done_hunt(vd->vdev_child[c]);
5707 if (oldvd != NULL)
5708 return (oldvd);
5709 }
5710
5711 /*
572e2857
BB
5712 * Check for a completed replacement. We always consider the first
5713 * vdev in the list to be the oldest vdev, and the last one to be
5714 * the newest (see spa_vdev_attach() for how that works). In
5715 * the case where the newest vdev is faulted, we will not automatically
5716 * remove it after a resilver completes. This is OK as it will require
5717 * user intervention to determine which disk the admin wishes to keep.
34dc7c2f 5718 */
572e2857
BB
5719 if (vd->vdev_ops == &vdev_replacing_ops) {
5720 ASSERT(vd->vdev_children > 1);
5721
5722 newvd = vd->vdev_child[vd->vdev_children - 1];
34dc7c2f 5723 oldvd = vd->vdev_child[0];
34dc7c2f 5724
fb5f0bc8 5725 if (vdev_dtl_empty(newvd, DTL_MISSING) &&
428870ff 5726 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
fb5f0bc8 5727 !vdev_dtl_required(oldvd))
34dc7c2f 5728 return (oldvd);
34dc7c2f
BB
5729 }
5730
5731 /*
5732 * Check for a completed resilver with the 'unspare' flag set.
5733 */
572e2857
BB
5734 if (vd->vdev_ops == &vdev_spare_ops) {
5735 vdev_t *first = vd->vdev_child[0];
5736 vdev_t *last = vd->vdev_child[vd->vdev_children - 1];
5737
5738 if (last->vdev_unspare) {
5739 oldvd = first;
5740 newvd = last;
5741 } else if (first->vdev_unspare) {
5742 oldvd = last;
5743 newvd = first;
5744 } else {
5745 oldvd = NULL;
5746 }
34dc7c2f 5747
572e2857 5748 if (oldvd != NULL &&
fb5f0bc8 5749 vdev_dtl_empty(newvd, DTL_MISSING) &&
428870ff 5750 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
572e2857 5751 !vdev_dtl_required(oldvd))
34dc7c2f 5752 return (oldvd);
572e2857
BB
5753
5754 /*
5755 * If there are more than two spares attached to a disk,
5756 * and those spares are not required, then we want to
5757 * attempt to free them up now so that they can be used
5758 * by other pools. Once we're back down to a single
5759 * disk+spare, we stop removing them.
5760 */
5761 if (vd->vdev_children > 2) {
5762 newvd = vd->vdev_child[1];
5763
5764 if (newvd->vdev_isspare && last->vdev_isspare &&
5765 vdev_dtl_empty(last, DTL_MISSING) &&
5766 vdev_dtl_empty(last, DTL_OUTAGE) &&
5767 !vdev_dtl_required(newvd))
5768 return (newvd);
34dc7c2f 5769 }
34dc7c2f
BB
5770 }
5771
5772 return (NULL);
5773}
5774
5775static void
5776spa_vdev_resilver_done(spa_t *spa)
5777{
fb5f0bc8
BB
5778 vdev_t *vd, *pvd, *ppvd;
5779 uint64_t guid, sguid, pguid, ppguid;
34dc7c2f 5780
fb5f0bc8 5781 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f
BB
5782
5783 while ((vd = spa_vdev_resilver_done_hunt(spa->spa_root_vdev)) != NULL) {
fb5f0bc8
BB
5784 pvd = vd->vdev_parent;
5785 ppvd = pvd->vdev_parent;
34dc7c2f 5786 guid = vd->vdev_guid;
fb5f0bc8
BB
5787 pguid = pvd->vdev_guid;
5788 ppguid = ppvd->vdev_guid;
5789 sguid = 0;
34dc7c2f
BB
5790 /*
5791 * If we have just finished replacing a hot spared device, then
5792 * we need to detach the parent's first child (the original hot
5793 * spare) as well.
5794 */
572e2857
BB
5795 if (ppvd->vdev_ops == &vdev_spare_ops && pvd->vdev_id == 0 &&
5796 ppvd->vdev_children == 2) {
34dc7c2f 5797 ASSERT(pvd->vdev_ops == &vdev_replacing_ops);
fb5f0bc8 5798 sguid = ppvd->vdev_child[1]->vdev_guid;
34dc7c2f 5799 }
5d1f7fb6
GW
5800 ASSERT(vd->vdev_resilver_txg == 0 || !vdev_dtl_required(vd));
5801
fb5f0bc8
BB
5802 spa_config_exit(spa, SCL_ALL, FTAG);
5803 if (spa_vdev_detach(spa, guid, pguid, B_TRUE) != 0)
34dc7c2f 5804 return;
fb5f0bc8 5805 if (sguid && spa_vdev_detach(spa, sguid, ppguid, B_TRUE) != 0)
34dc7c2f 5806 return;
fb5f0bc8 5807 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f
BB
5808 }
5809
fb5f0bc8 5810 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
5811}
5812
5813/*
428870ff 5814 * Update the stored path or FRU for this vdev.
34dc7c2f
BB
5815 */
5816int
9babb374
BB
5817spa_vdev_set_common(spa_t *spa, uint64_t guid, const char *value,
5818 boolean_t ispath)
34dc7c2f 5819{
b128c09f 5820 vdev_t *vd;
428870ff 5821 boolean_t sync = B_FALSE;
34dc7c2f 5822
572e2857
BB
5823 ASSERT(spa_writeable(spa));
5824
428870ff 5825 spa_vdev_state_enter(spa, SCL_ALL);
34dc7c2f 5826
9babb374 5827 if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
428870ff 5828 return (spa_vdev_state_exit(spa, NULL, ENOENT));
34dc7c2f
BB
5829
5830 if (!vd->vdev_ops->vdev_op_leaf)
428870ff 5831 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
34dc7c2f 5832
9babb374 5833 if (ispath) {
428870ff
BB
5834 if (strcmp(value, vd->vdev_path) != 0) {
5835 spa_strfree(vd->vdev_path);
5836 vd->vdev_path = spa_strdup(value);
5837 sync = B_TRUE;
5838 }
9babb374 5839 } else {
428870ff
BB
5840 if (vd->vdev_fru == NULL) {
5841 vd->vdev_fru = spa_strdup(value);
5842 sync = B_TRUE;
5843 } else if (strcmp(value, vd->vdev_fru) != 0) {
9babb374 5844 spa_strfree(vd->vdev_fru);
428870ff
BB
5845 vd->vdev_fru = spa_strdup(value);
5846 sync = B_TRUE;
5847 }
9babb374 5848 }
34dc7c2f 5849
428870ff 5850 return (spa_vdev_state_exit(spa, sync ? vd : NULL, 0));
34dc7c2f
BB
5851}
5852
9babb374
BB
5853int
5854spa_vdev_setpath(spa_t *spa, uint64_t guid, const char *newpath)
5855{
5856 return (spa_vdev_set_common(spa, guid, newpath, B_TRUE));
5857}
5858
5859int
5860spa_vdev_setfru(spa_t *spa, uint64_t guid, const char *newfru)
5861{
5862 return (spa_vdev_set_common(spa, guid, newfru, B_FALSE));
5863}
5864
34dc7c2f
BB
5865/*
5866 * ==========================================================================
428870ff 5867 * SPA Scanning
34dc7c2f
BB
5868 * ==========================================================================
5869 */
0ea05c64
AP
5870int
5871spa_scrub_pause_resume(spa_t *spa, pool_scrub_cmd_t cmd)
5872{
5873 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
5874
5875 if (dsl_scan_resilvering(spa->spa_dsl_pool))
5876 return (SET_ERROR(EBUSY));
5877
5878 return (dsl_scrub_set_pause_resume(spa->spa_dsl_pool, cmd));
5879}
34dc7c2f 5880
34dc7c2f 5881int
428870ff
BB
5882spa_scan_stop(spa_t *spa)
5883{
5884 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
5885 if (dsl_scan_resilvering(spa->spa_dsl_pool))
2e528b49 5886 return (SET_ERROR(EBUSY));
428870ff
BB
5887 return (dsl_scan_cancel(spa->spa_dsl_pool));
5888}
5889
5890int
5891spa_scan(spa_t *spa, pool_scan_func_t func)
34dc7c2f 5892{
b128c09f 5893 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
34dc7c2f 5894
428870ff 5895 if (func >= POOL_SCAN_FUNCS || func == POOL_SCAN_NONE)
2e528b49 5896 return (SET_ERROR(ENOTSUP));
34dc7c2f 5897
34dc7c2f 5898 /*
b128c09f
BB
5899 * If a resilver was requested, but there is no DTL on a
5900 * writeable leaf device, we have nothing to do.
34dc7c2f 5901 */
428870ff 5902 if (func == POOL_SCAN_RESILVER &&
b128c09f
BB
5903 !vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL)) {
5904 spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
34dc7c2f
BB
5905 return (0);
5906 }
5907
428870ff 5908 return (dsl_scan(spa->spa_dsl_pool, func));
34dc7c2f
BB
5909}
5910
5911/*
5912 * ==========================================================================
5913 * SPA async task processing
5914 * ==========================================================================
5915 */
5916
5917static void
5918spa_async_remove(spa_t *spa, vdev_t *vd)
5919{
b128c09f 5920 if (vd->vdev_remove_wanted) {
428870ff
BB
5921 vd->vdev_remove_wanted = B_FALSE;
5922 vd->vdev_delayed_close = B_FALSE;
b128c09f 5923 vdev_set_state(vd, B_FALSE, VDEV_STATE_REMOVED, VDEV_AUX_NONE);
428870ff
BB
5924
5925 /*
5926 * We want to clear the stats, but we don't want to do a full
5927 * vdev_clear() as that will cause us to throw away
5928 * degraded/faulted state as well as attempt to reopen the
5929 * device, all of which is a waste.
5930 */
5931 vd->vdev_stat.vs_read_errors = 0;
5932 vd->vdev_stat.vs_write_errors = 0;
5933 vd->vdev_stat.vs_checksum_errors = 0;
5934
b128c09f
BB
5935 vdev_state_dirty(vd->vdev_top);
5936 }
34dc7c2f 5937
1c27024e 5938 for (int c = 0; c < vd->vdev_children; c++)
b128c09f
BB
5939 spa_async_remove(spa, vd->vdev_child[c]);
5940}
5941
5942static void
5943spa_async_probe(spa_t *spa, vdev_t *vd)
5944{
5945 if (vd->vdev_probe_wanted) {
428870ff 5946 vd->vdev_probe_wanted = B_FALSE;
b128c09f 5947 vdev_reopen(vd); /* vdev_open() does the actual probe */
34dc7c2f 5948 }
b128c09f 5949
1c27024e 5950 for (int c = 0; c < vd->vdev_children; c++)
b128c09f 5951 spa_async_probe(spa, vd->vdev_child[c]);
34dc7c2f
BB
5952}
5953
9babb374
BB
5954static void
5955spa_async_autoexpand(spa_t *spa, vdev_t *vd)
5956{
9babb374
BB
5957 if (!spa->spa_autoexpand)
5958 return;
5959
1c27024e 5960 for (int c = 0; c < vd->vdev_children; c++) {
9babb374
BB
5961 vdev_t *cvd = vd->vdev_child[c];
5962 spa_async_autoexpand(spa, cvd);
5963 }
5964
5965 if (!vd->vdev_ops->vdev_op_leaf || vd->vdev_physpath == NULL)
5966 return;
5967
12fa0466 5968 spa_event_notify(vd->vdev_spa, vd, NULL, ESC_ZFS_VDEV_AUTOEXPAND);
9babb374
BB
5969}
5970
34dc7c2f 5971static void
c25b8f99 5972spa_async_thread(void *arg)
34dc7c2f 5973{
c25b8f99 5974 spa_t *spa = (spa_t *)arg;
867959b5 5975 int tasks;
34dc7c2f
BB
5976
5977 ASSERT(spa->spa_sync_on);
5978
5979 mutex_enter(&spa->spa_async_lock);
5980 tasks = spa->spa_async_tasks;
5981 spa->spa_async_tasks = 0;
5982 mutex_exit(&spa->spa_async_lock);
5983
5984 /*
5985 * See if the config needs to be updated.
5986 */
5987 if (tasks & SPA_ASYNC_CONFIG_UPDATE) {
428870ff 5988 uint64_t old_space, new_space;
9babb374 5989
34dc7c2f 5990 mutex_enter(&spa_namespace_lock);
428870ff 5991 old_space = metaslab_class_get_space(spa_normal_class(spa));
34dc7c2f 5992 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
428870ff 5993 new_space = metaslab_class_get_space(spa_normal_class(spa));
34dc7c2f 5994 mutex_exit(&spa_namespace_lock);
9babb374
BB
5995
5996 /*
5997 * If the pool grew as a result of the config update,
5998 * then log an internal history event.
5999 */
428870ff 6000 if (new_space != old_space) {
6f1ffb06 6001 spa_history_log_internal(spa, "vdev online", NULL,
45d1cae3 6002 "pool '%s' size: %llu(+%llu)",
428870ff 6003 spa_name(spa), new_space, new_space - old_space);
9babb374 6004 }
34dc7c2f
BB
6005 }
6006
6007 /*
6008 * See if any devices need to be marked REMOVED.
34dc7c2f 6009 */
b128c09f 6010 if (tasks & SPA_ASYNC_REMOVE) {
428870ff 6011 spa_vdev_state_enter(spa, SCL_NONE);
34dc7c2f 6012 spa_async_remove(spa, spa->spa_root_vdev);
867959b5 6013 for (int i = 0; i < spa->spa_l2cache.sav_count; i++)
b128c09f 6014 spa_async_remove(spa, spa->spa_l2cache.sav_vdevs[i]);
867959b5 6015 for (int i = 0; i < spa->spa_spares.sav_count; i++)
b128c09f
BB
6016 spa_async_remove(spa, spa->spa_spares.sav_vdevs[i]);
6017 (void) spa_vdev_state_exit(spa, NULL, 0);
34dc7c2f
BB
6018 }
6019
9babb374
BB
6020 if ((tasks & SPA_ASYNC_AUTOEXPAND) && !spa_suspended(spa)) {
6021 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
6022 spa_async_autoexpand(spa, spa->spa_root_vdev);
6023 spa_config_exit(spa, SCL_CONFIG, FTAG);
6024 }
6025
34dc7c2f 6026 /*
b128c09f 6027 * See if any devices need to be probed.
34dc7c2f 6028 */
b128c09f 6029 if (tasks & SPA_ASYNC_PROBE) {
428870ff 6030 spa_vdev_state_enter(spa, SCL_NONE);
b128c09f
BB
6031 spa_async_probe(spa, spa->spa_root_vdev);
6032 (void) spa_vdev_state_exit(spa, NULL, 0);
6033 }
34dc7c2f
BB
6034
6035 /*
b128c09f 6036 * If any devices are done replacing, detach them.
34dc7c2f 6037 */
b128c09f
BB
6038 if (tasks & SPA_ASYNC_RESILVER_DONE)
6039 spa_vdev_resilver_done(spa);
34dc7c2f
BB
6040
6041 /*
6042 * Kick off a resilver.
6043 */
b128c09f 6044 if (tasks & SPA_ASYNC_RESILVER)
428870ff 6045 dsl_resilver_restart(spa->spa_dsl_pool, 0);
34dc7c2f
BB
6046
6047 /*
6048 * Let the world know that we're done.
6049 */
6050 mutex_enter(&spa->spa_async_lock);
6051 spa->spa_async_thread = NULL;
6052 cv_broadcast(&spa->spa_async_cv);
6053 mutex_exit(&spa->spa_async_lock);
6054 thread_exit();
6055}
6056
6057void
6058spa_async_suspend(spa_t *spa)
6059{
6060 mutex_enter(&spa->spa_async_lock);
6061 spa->spa_async_suspended++;
a1d477c2
MA
6062 while (spa->spa_async_thread != NULL ||
6063 spa->spa_condense_thread != NULL)
34dc7c2f
BB
6064 cv_wait(&spa->spa_async_cv, &spa->spa_async_lock);
6065 mutex_exit(&spa->spa_async_lock);
a1d477c2
MA
6066
6067 spa_vdev_remove_suspend(spa);
34dc7c2f
BB
6068}
6069
6070void
6071spa_async_resume(spa_t *spa)
6072{
6073 mutex_enter(&spa->spa_async_lock);
6074 ASSERT(spa->spa_async_suspended != 0);
6075 spa->spa_async_suspended--;
6076 mutex_exit(&spa->spa_async_lock);
a1d477c2 6077 spa_restart_removal(spa);
34dc7c2f
BB
6078}
6079
e6cfd633
WA
6080static boolean_t
6081spa_async_tasks_pending(spa_t *spa)
6082{
6083 uint_t non_config_tasks;
6084 uint_t config_task;
6085 boolean_t config_task_suspended;
6086
6087 non_config_tasks = spa->spa_async_tasks & ~SPA_ASYNC_CONFIG_UPDATE;
6088 config_task = spa->spa_async_tasks & SPA_ASYNC_CONFIG_UPDATE;
6089 if (spa->spa_ccw_fail_time == 0) {
6090 config_task_suspended = B_FALSE;
6091 } else {
6092 config_task_suspended =
6093 (gethrtime() - spa->spa_ccw_fail_time) <
05852b34 6094 ((hrtime_t)zfs_ccw_retry_interval * NANOSEC);
e6cfd633
WA
6095 }
6096
6097 return (non_config_tasks || (config_task && !config_task_suspended));
6098}
6099
34dc7c2f
BB
6100static void
6101spa_async_dispatch(spa_t *spa)
6102{
6103 mutex_enter(&spa->spa_async_lock);
e6cfd633
WA
6104 if (spa_async_tasks_pending(spa) &&
6105 !spa->spa_async_suspended &&
34dc7c2f 6106 spa->spa_async_thread == NULL &&
e6cfd633 6107 rootdir != NULL)
34dc7c2f
BB
6108 spa->spa_async_thread = thread_create(NULL, 0,
6109 spa_async_thread, spa, 0, &p0, TS_RUN, maxclsyspri);
6110 mutex_exit(&spa->spa_async_lock);
6111}
6112
6113void
6114spa_async_request(spa_t *spa, int task)
6115{
428870ff 6116 zfs_dbgmsg("spa=%s async request task=%u", spa->spa_name, task);
34dc7c2f
BB
6117 mutex_enter(&spa->spa_async_lock);
6118 spa->spa_async_tasks |= task;
6119 mutex_exit(&spa->spa_async_lock);
6120}
6121
6122/*
6123 * ==========================================================================
6124 * SPA syncing routines
6125 * ==========================================================================
6126 */
6127
428870ff
BB
6128static int
6129bpobj_enqueue_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
34dc7c2f 6130{
428870ff
BB
6131 bpobj_t *bpo = arg;
6132 bpobj_enqueue(bpo, bp, tx);
6133 return (0);
6134}
34dc7c2f 6135
428870ff
BB
6136static int
6137spa_free_sync_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
6138{
6139 zio_t *zio = arg;
34dc7c2f 6140
428870ff
BB
6141 zio_nowait(zio_free_sync(zio, zio->io_spa, dmu_tx_get_txg(tx), bp,
6142 zio->io_flags));
6143 return (0);
34dc7c2f
BB
6144}
6145
e8b96c60
MA
6146/*
6147 * Note: this simple function is not inlined to make it easier to dtrace the
6148 * amount of time spent syncing frees.
6149 */
6150static void
6151spa_sync_frees(spa_t *spa, bplist_t *bpl, dmu_tx_t *tx)
6152{
6153 zio_t *zio = zio_root(spa, NULL, NULL, 0);
6154 bplist_iterate(bpl, spa_free_sync_cb, zio, tx);
6155 VERIFY(zio_wait(zio) == 0);
6156}
6157
6158/*
6159 * Note: this simple function is not inlined to make it easier to dtrace the
6160 * amount of time spent syncing deferred frees.
6161 */
6162static void
6163spa_sync_deferred_frees(spa_t *spa, dmu_tx_t *tx)
6164{
6165 zio_t *zio = zio_root(spa, NULL, NULL, 0);
6166 VERIFY3U(bpobj_iterate(&spa->spa_deferred_bpobj,
6167 spa_free_sync_cb, zio, tx), ==, 0);
6168 VERIFY0(zio_wait(zio));
6169}
6170
34dc7c2f
BB
6171static void
6172spa_sync_nvlist(spa_t *spa, uint64_t obj, nvlist_t *nv, dmu_tx_t *tx)
6173{
6174 char *packed = NULL;
b128c09f 6175 size_t bufsize;
34dc7c2f
BB
6176 size_t nvsize = 0;
6177 dmu_buf_t *db;
6178
6179 VERIFY(nvlist_size(nv, &nvsize, NV_ENCODE_XDR) == 0);
6180
b128c09f
BB
6181 /*
6182 * Write full (SPA_CONFIG_BLOCKSIZE) blocks of configuration
b0bc7a84 6183 * information. This avoids the dmu_buf_will_dirty() path and
b128c09f
BB
6184 * saves us a pre-read to get data we don't actually care about.
6185 */
9ae529ec 6186 bufsize = P2ROUNDUP((uint64_t)nvsize, SPA_CONFIG_BLOCKSIZE);
79c76d5b 6187 packed = vmem_alloc(bufsize, KM_SLEEP);
34dc7c2f
BB
6188
6189 VERIFY(nvlist_pack(nv, &packed, &nvsize, NV_ENCODE_XDR,
79c76d5b 6190 KM_SLEEP) == 0);
b128c09f 6191 bzero(packed + nvsize, bufsize - nvsize);
34dc7c2f 6192
b128c09f 6193 dmu_write(spa->spa_meta_objset, obj, 0, bufsize, packed, tx);
34dc7c2f 6194
00b46022 6195 vmem_free(packed, bufsize);
34dc7c2f
BB
6196
6197 VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
6198 dmu_buf_will_dirty(db, tx);
6199 *(uint64_t *)db->db_data = nvsize;
6200 dmu_buf_rele(db, FTAG);
6201}
6202
6203static void
6204spa_sync_aux_dev(spa_t *spa, spa_aux_vdev_t *sav, dmu_tx_t *tx,
6205 const char *config, const char *entry)
6206{
6207 nvlist_t *nvroot;
6208 nvlist_t **list;
6209 int i;
6210
6211 if (!sav->sav_sync)
6212 return;
6213
6214 /*
6215 * Update the MOS nvlist describing the list of available devices.
6216 * spa_validate_aux() will have already made sure this nvlist is
6217 * valid and the vdevs are labeled appropriately.
6218 */
6219 if (sav->sav_object == 0) {
6220 sav->sav_object = dmu_object_alloc(spa->spa_meta_objset,
6221 DMU_OT_PACKED_NVLIST, 1 << 14, DMU_OT_PACKED_NVLIST_SIZE,
6222 sizeof (uint64_t), tx);
6223 VERIFY(zap_update(spa->spa_meta_objset,
6224 DMU_POOL_DIRECTORY_OBJECT, entry, sizeof (uint64_t), 1,
6225 &sav->sav_object, tx) == 0);
6226 }
6227
79c76d5b 6228 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
34dc7c2f
BB
6229 if (sav->sav_count == 0) {
6230 VERIFY(nvlist_add_nvlist_array(nvroot, config, NULL, 0) == 0);
6231 } else {
79c76d5b 6232 list = kmem_alloc(sav->sav_count*sizeof (void *), KM_SLEEP);
34dc7c2f
BB
6233 for (i = 0; i < sav->sav_count; i++)
6234 list[i] = vdev_config_generate(spa, sav->sav_vdevs[i],
428870ff 6235 B_FALSE, VDEV_CONFIG_L2CACHE);
34dc7c2f
BB
6236 VERIFY(nvlist_add_nvlist_array(nvroot, config, list,
6237 sav->sav_count) == 0);
6238 for (i = 0; i < sav->sav_count; i++)
6239 nvlist_free(list[i]);
6240 kmem_free(list, sav->sav_count * sizeof (void *));
6241 }
6242
6243 spa_sync_nvlist(spa, sav->sav_object, nvroot, tx);
6244 nvlist_free(nvroot);
6245
6246 sav->sav_sync = B_FALSE;
6247}
6248
e0ab3ab5
JS
6249/*
6250 * Rebuild spa's all-vdev ZAP from the vdev ZAPs indicated in each vdev_t.
6251 * The all-vdev ZAP must be empty.
6252 */
6253static void
6254spa_avz_build(vdev_t *vd, uint64_t avz, dmu_tx_t *tx)
6255{
6256 spa_t *spa = vd->vdev_spa;
e0ab3ab5
JS
6257
6258 if (vd->vdev_top_zap != 0) {
6259 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
6260 vd->vdev_top_zap, tx));
6261 }
6262 if (vd->vdev_leaf_zap != 0) {
6263 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
6264 vd->vdev_leaf_zap, tx));
6265 }
1c27024e 6266 for (uint64_t i = 0; i < vd->vdev_children; i++) {
e0ab3ab5
JS
6267 spa_avz_build(vd->vdev_child[i], avz, tx);
6268 }
6269}
6270
34dc7c2f
BB
6271static void
6272spa_sync_config_object(spa_t *spa, dmu_tx_t *tx)
6273{
6274 nvlist_t *config;
6275
e0ab3ab5
JS
6276 /*
6277 * If the pool is being imported from a pre-per-vdev-ZAP version of ZFS,
6278 * its config may not be dirty but we still need to build per-vdev ZAPs.
6279 * Similarly, if the pool is being assembled (e.g. after a split), we
6280 * need to rebuild the AVZ although the config may not be dirty.
6281 */
6282 if (list_is_empty(&spa->spa_config_dirty_list) &&
6283 spa->spa_avz_action == AVZ_ACTION_NONE)
34dc7c2f
BB
6284 return;
6285
b128c09f
BB
6286 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
6287
e0ab3ab5 6288 ASSERT(spa->spa_avz_action == AVZ_ACTION_NONE ||
38640550 6289 spa->spa_avz_action == AVZ_ACTION_INITIALIZE ||
e0ab3ab5
JS
6290 spa->spa_all_vdev_zaps != 0);
6291
6292 if (spa->spa_avz_action == AVZ_ACTION_REBUILD) {
e0ab3ab5
JS
6293 /* Make and build the new AVZ */
6294 uint64_t new_avz = zap_create(spa->spa_meta_objset,
6295 DMU_OTN_ZAP_METADATA, DMU_OT_NONE, 0, tx);
6296 spa_avz_build(spa->spa_root_vdev, new_avz, tx);
6297
6298 /* Diff old AVZ with new one */
1c27024e
DB
6299 zap_cursor_t zc;
6300 zap_attribute_t za;
6301
e0ab3ab5
JS
6302 for (zap_cursor_init(&zc, spa->spa_meta_objset,
6303 spa->spa_all_vdev_zaps);
6304 zap_cursor_retrieve(&zc, &za) == 0;
6305 zap_cursor_advance(&zc)) {
6306 uint64_t vdzap = za.za_first_integer;
6307 if (zap_lookup_int(spa->spa_meta_objset, new_avz,
6308 vdzap) == ENOENT) {
6309 /*
6310 * ZAP is listed in old AVZ but not in new one;
6311 * destroy it
6312 */
6313 VERIFY0(zap_destroy(spa->spa_meta_objset, vdzap,
6314 tx));
6315 }
6316 }
6317
6318 zap_cursor_fini(&zc);
6319
6320 /* Destroy the old AVZ */
6321 VERIFY0(zap_destroy(spa->spa_meta_objset,
6322 spa->spa_all_vdev_zaps, tx));
6323
6324 /* Replace the old AVZ in the dir obj with the new one */
6325 VERIFY0(zap_update(spa->spa_meta_objset,
6326 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP,
6327 sizeof (new_avz), 1, &new_avz, tx));
6328
6329 spa->spa_all_vdev_zaps = new_avz;
6330 } else if (spa->spa_avz_action == AVZ_ACTION_DESTROY) {
6331 zap_cursor_t zc;
6332 zap_attribute_t za;
6333
6334 /* Walk through the AVZ and destroy all listed ZAPs */
6335 for (zap_cursor_init(&zc, spa->spa_meta_objset,
6336 spa->spa_all_vdev_zaps);
6337 zap_cursor_retrieve(&zc, &za) == 0;
6338 zap_cursor_advance(&zc)) {
6339 uint64_t zap = za.za_first_integer;
6340 VERIFY0(zap_destroy(spa->spa_meta_objset, zap, tx));
6341 }
6342
6343 zap_cursor_fini(&zc);
6344
6345 /* Destroy and unlink the AVZ itself */
6346 VERIFY0(zap_destroy(spa->spa_meta_objset,
6347 spa->spa_all_vdev_zaps, tx));
6348 VERIFY0(zap_remove(spa->spa_meta_objset,
6349 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP, tx));
6350 spa->spa_all_vdev_zaps = 0;
6351 }
6352
6353 if (spa->spa_all_vdev_zaps == 0) {
6354 spa->spa_all_vdev_zaps = zap_create_link(spa->spa_meta_objset,
6355 DMU_OTN_ZAP_METADATA, DMU_POOL_DIRECTORY_OBJECT,
6356 DMU_POOL_VDEV_ZAP_MAP, tx);
6357 }
6358 spa->spa_avz_action = AVZ_ACTION_NONE;
6359
6360 /* Create ZAPs for vdevs that don't have them. */
6361 vdev_construct_zaps(spa->spa_root_vdev, tx);
6362
b128c09f
BB
6363 config = spa_config_generate(spa, spa->spa_root_vdev,
6364 dmu_tx_get_txg(tx), B_FALSE);
6365
ea0b2538
GW
6366 /*
6367 * If we're upgrading the spa version then make sure that
6368 * the config object gets updated with the correct version.
6369 */
6370 if (spa->spa_ubsync.ub_version < spa->spa_uberblock.ub_version)
6371 fnvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
6372 spa->spa_uberblock.ub_version);
6373
b128c09f 6374 spa_config_exit(spa, SCL_STATE, FTAG);
34dc7c2f 6375
8a5fc748 6376 nvlist_free(spa->spa_config_syncing);
34dc7c2f
BB
6377 spa->spa_config_syncing = config;
6378
6379 spa_sync_nvlist(spa, spa->spa_config_object, config, tx);
6380}
6381
9ae529ec 6382static void
13fe0198 6383spa_sync_version(void *arg, dmu_tx_t *tx)
9ae529ec 6384{
13fe0198
MA
6385 uint64_t *versionp = arg;
6386 uint64_t version = *versionp;
6387 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
9ae529ec
CS
6388
6389 /*
6390 * Setting the version is special cased when first creating the pool.
6391 */
6392 ASSERT(tx->tx_txg != TXG_INITIAL);
6393
8dca0a9a 6394 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
9ae529ec
CS
6395 ASSERT(version >= spa_version(spa));
6396
6397 spa->spa_uberblock.ub_version = version;
6398 vdev_config_dirty(spa->spa_root_vdev);
6f1ffb06 6399 spa_history_log_internal(spa, "set", tx, "version=%lld", version);
9ae529ec
CS
6400}
6401
34dc7c2f
BB
6402/*
6403 * Set zpool properties.
6404 */
6405static void
13fe0198 6406spa_sync_props(void *arg, dmu_tx_t *tx)
34dc7c2f 6407{
13fe0198
MA
6408 nvlist_t *nvp = arg;
6409 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
34dc7c2f 6410 objset_t *mos = spa->spa_meta_objset;
9ae529ec 6411 nvpair_t *elem = NULL;
b128c09f
BB
6412
6413 mutex_enter(&spa->spa_props_lock);
34dc7c2f 6414
34dc7c2f 6415 while ((elem = nvlist_next_nvpair(nvp, elem))) {
9ae529ec
CS
6416 uint64_t intval;
6417 char *strval, *fname;
6418 zpool_prop_t prop;
6419 const char *propname;
6420 zprop_type_t proptype;
fa86b5db 6421 spa_feature_t fid;
9ae529ec 6422
31864e3d
BB
6423 switch (prop = zpool_name_to_prop(nvpair_name(elem))) {
6424 case ZPOOL_PROP_INVAL:
9ae529ec
CS
6425 /*
6426 * We checked this earlier in spa_prop_validate().
6427 */
6428 ASSERT(zpool_prop_feature(nvpair_name(elem)));
6429
6430 fname = strchr(nvpair_name(elem), '@') + 1;
fa86b5db 6431 VERIFY0(zfeature_lookup_name(fname, &fid));
9ae529ec 6432
fa86b5db 6433 spa_feature_enable(spa, fid, tx);
6f1ffb06
MA
6434 spa_history_log_internal(spa, "set", tx,
6435 "%s=enabled", nvpair_name(elem));
9ae529ec
CS
6436 break;
6437
34dc7c2f 6438 case ZPOOL_PROP_VERSION:
93cf2076 6439 intval = fnvpair_value_uint64(elem);
34dc7c2f 6440 /*
4e33ba4c 6441 * The version is synced separately before other
9ae529ec 6442 * properties and should be correct by now.
34dc7c2f 6443 */
9ae529ec 6444 ASSERT3U(spa_version(spa), >=, intval);
34dc7c2f
BB
6445 break;
6446
6447 case ZPOOL_PROP_ALTROOT:
6448 /*
6449 * 'altroot' is a non-persistent property. It should
6450 * have been set temporarily at creation or import time.
6451 */
6452 ASSERT(spa->spa_root != NULL);
6453 break;
6454
572e2857 6455 case ZPOOL_PROP_READONLY:
34dc7c2f
BB
6456 case ZPOOL_PROP_CACHEFILE:
6457 /*
572e2857
BB
6458 * 'readonly' and 'cachefile' are also non-persisitent
6459 * properties.
34dc7c2f 6460 */
34dc7c2f 6461 break;
d96eb2b1 6462 case ZPOOL_PROP_COMMENT:
93cf2076 6463 strval = fnvpair_value_string(elem);
d96eb2b1
DM
6464 if (spa->spa_comment != NULL)
6465 spa_strfree(spa->spa_comment);
6466 spa->spa_comment = spa_strdup(strval);
6467 /*
6468 * We need to dirty the configuration on all the vdevs
6469 * so that their labels get updated. It's unnecessary
6470 * to do this for pool creation since the vdev's
4e33ba4c 6471 * configuration has already been dirtied.
d96eb2b1
DM
6472 */
6473 if (tx->tx_txg != TXG_INITIAL)
6474 vdev_config_dirty(spa->spa_root_vdev);
6f1ffb06
MA
6475 spa_history_log_internal(spa, "set", tx,
6476 "%s=%s", nvpair_name(elem), strval);
d96eb2b1 6477 break;
34dc7c2f
BB
6478 default:
6479 /*
6480 * Set pool property values in the poolprops mos object.
6481 */
34dc7c2f 6482 if (spa->spa_pool_props_object == 0) {
9ae529ec
CS
6483 spa->spa_pool_props_object =
6484 zap_create_link(mos, DMU_OT_POOL_PROPS,
34dc7c2f 6485 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_PROPS,
9ae529ec 6486 tx);
34dc7c2f 6487 }
34dc7c2f
BB
6488
6489 /* normalize the property name */
6490 propname = zpool_prop_to_name(prop);
6491 proptype = zpool_prop_get_type(prop);
6492
6493 if (nvpair_type(elem) == DATA_TYPE_STRING) {
6494 ASSERT(proptype == PROP_TYPE_STRING);
93cf2076
GW
6495 strval = fnvpair_value_string(elem);
6496 VERIFY0(zap_update(mos,
34dc7c2f 6497 spa->spa_pool_props_object, propname,
93cf2076 6498 1, strlen(strval) + 1, strval, tx));
6f1ffb06
MA
6499 spa_history_log_internal(spa, "set", tx,
6500 "%s=%s", nvpair_name(elem), strval);
34dc7c2f 6501 } else if (nvpair_type(elem) == DATA_TYPE_UINT64) {
93cf2076 6502 intval = fnvpair_value_uint64(elem);
34dc7c2f
BB
6503
6504 if (proptype == PROP_TYPE_INDEX) {
6505 const char *unused;
93cf2076
GW
6506 VERIFY0(zpool_prop_index_to_string(
6507 prop, intval, &unused));
34dc7c2f 6508 }
93cf2076 6509 VERIFY0(zap_update(mos,
34dc7c2f 6510 spa->spa_pool_props_object, propname,
93cf2076 6511 8, 1, &intval, tx));
6f1ffb06
MA
6512 spa_history_log_internal(spa, "set", tx,
6513 "%s=%lld", nvpair_name(elem), intval);
34dc7c2f
BB
6514 } else {
6515 ASSERT(0); /* not allowed */
6516 }
6517
6518 switch (prop) {
6519 case ZPOOL_PROP_DELEGATION:
6520 spa->spa_delegation = intval;
6521 break;
6522 case ZPOOL_PROP_BOOTFS:
6523 spa->spa_bootfs = intval;
6524 break;
6525 case ZPOOL_PROP_FAILUREMODE:
6526 spa->spa_failmode = intval;
6527 break;
9babb374
BB
6528 case ZPOOL_PROP_AUTOEXPAND:
6529 spa->spa_autoexpand = intval;
428870ff
BB
6530 if (tx->tx_txg != TXG_INITIAL)
6531 spa_async_request(spa,
6532 SPA_ASYNC_AUTOEXPAND);
6533 break;
379ca9cf
OF
6534 case ZPOOL_PROP_MULTIHOST:
6535 spa->spa_multihost = intval;
6536 break;
428870ff
BB
6537 case ZPOOL_PROP_DEDUPDITTO:
6538 spa->spa_dedup_ditto = intval;
9babb374 6539 break;
34dc7c2f
BB
6540 default:
6541 break;
6542 }
6543 }
6544
34dc7c2f 6545 }
b128c09f
BB
6546
6547 mutex_exit(&spa->spa_props_lock);
34dc7c2f
BB
6548}
6549
428870ff
BB
6550/*
6551 * Perform one-time upgrade on-disk changes. spa_version() does not
6552 * reflect the new version this txg, so there must be no changes this
6553 * txg to anything that the upgrade code depends on after it executes.
6554 * Therefore this must be called after dsl_pool_sync() does the sync
6555 * tasks.
6556 */
6557static void
6558spa_sync_upgrades(spa_t *spa, dmu_tx_t *tx)
6559{
6560 dsl_pool_t *dp = spa->spa_dsl_pool;
6561
6562 ASSERT(spa->spa_sync_pass == 1);
6563
13fe0198
MA
6564 rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
6565
428870ff
BB
6566 if (spa->spa_ubsync.ub_version < SPA_VERSION_ORIGIN &&
6567 spa->spa_uberblock.ub_version >= SPA_VERSION_ORIGIN) {
6568 dsl_pool_create_origin(dp, tx);
6569
6570 /* Keeping the origin open increases spa_minref */
6571 spa->spa_minref += 3;
6572 }
6573
6574 if (spa->spa_ubsync.ub_version < SPA_VERSION_NEXT_CLONES &&
6575 spa->spa_uberblock.ub_version >= SPA_VERSION_NEXT_CLONES) {
6576 dsl_pool_upgrade_clones(dp, tx);
6577 }
6578
6579 if (spa->spa_ubsync.ub_version < SPA_VERSION_DIR_CLONES &&
6580 spa->spa_uberblock.ub_version >= SPA_VERSION_DIR_CLONES) {
6581 dsl_pool_upgrade_dir_clones(dp, tx);
6582
6583 /* Keeping the freedir open increases spa_minref */
6584 spa->spa_minref += 3;
6585 }
9ae529ec
CS
6586
6587 if (spa->spa_ubsync.ub_version < SPA_VERSION_FEATURES &&
6588 spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
6589 spa_feature_create_zap_objects(spa, tx);
6590 }
62bdd5eb
DL
6591
6592 /*
6593 * LZ4_COMPRESS feature's behaviour was changed to activate_on_enable
6594 * when possibility to use lz4 compression for metadata was added
6595 * Old pools that have this feature enabled must be upgraded to have
6596 * this feature active
6597 */
6598 if (spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
6599 boolean_t lz4_en = spa_feature_is_enabled(spa,
6600 SPA_FEATURE_LZ4_COMPRESS);
6601 boolean_t lz4_ac = spa_feature_is_active(spa,
6602 SPA_FEATURE_LZ4_COMPRESS);
6603
6604 if (lz4_en && !lz4_ac)
6605 spa_feature_incr(spa, SPA_FEATURE_LZ4_COMPRESS, tx);
6606 }
3c67d83a
TH
6607
6608 /*
6609 * If we haven't written the salt, do so now. Note that the
6610 * feature may not be activated yet, but that's fine since
6611 * the presence of this ZAP entry is backwards compatible.
6612 */
6613 if (zap_contains(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
6614 DMU_POOL_CHECKSUM_SALT) == ENOENT) {
6615 VERIFY0(zap_add(spa->spa_meta_objset,
6616 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CHECKSUM_SALT, 1,
6617 sizeof (spa->spa_cksum_salt.zcs_bytes),
6618 spa->spa_cksum_salt.zcs_bytes, tx));
6619 }
6620
13fe0198 6621 rrw_exit(&dp->dp_config_rwlock, FTAG);
428870ff
BB
6622}
6623
a1d477c2
MA
6624static void
6625vdev_indirect_state_sync_verify(vdev_t *vd)
6626{
6627 ASSERTV(vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping);
6628 ASSERTV(vdev_indirect_births_t *vib = vd->vdev_indirect_births);
6629
6630 if (vd->vdev_ops == &vdev_indirect_ops) {
6631 ASSERT(vim != NULL);
6632 ASSERT(vib != NULL);
6633 }
6634
6635 if (vdev_obsolete_sm_object(vd) != 0) {
6636 ASSERT(vd->vdev_obsolete_sm != NULL);
6637 ASSERT(vd->vdev_removing ||
6638 vd->vdev_ops == &vdev_indirect_ops);
6639 ASSERT(vdev_indirect_mapping_num_entries(vim) > 0);
6640 ASSERT(vdev_indirect_mapping_bytes_mapped(vim) > 0);
6641
6642 ASSERT3U(vdev_obsolete_sm_object(vd), ==,
6643 space_map_object(vd->vdev_obsolete_sm));
6644 ASSERT3U(vdev_indirect_mapping_bytes_mapped(vim), >=,
6645 space_map_allocated(vd->vdev_obsolete_sm));
6646 }
6647 ASSERT(vd->vdev_obsolete_segments != NULL);
6648
6649 /*
6650 * Since frees / remaps to an indirect vdev can only
6651 * happen in syncing context, the obsolete segments
6652 * tree must be empty when we start syncing.
6653 */
6654 ASSERT0(range_tree_space(vd->vdev_obsolete_segments));
6655}
6656
34dc7c2f
BB
6657/*
6658 * Sync the specified transaction group. New blocks may be dirtied as
6659 * part of the process, so we iterate until it converges.
6660 */
6661void
6662spa_sync(spa_t *spa, uint64_t txg)
6663{
6664 dsl_pool_t *dp = spa->spa_dsl_pool;
6665 objset_t *mos = spa->spa_meta_objset;
428870ff 6666 bplist_t *free_bpl = &spa->spa_free_bplist[txg & TXG_MASK];
34dc7c2f
BB
6667 vdev_t *rvd = spa->spa_root_vdev;
6668 vdev_t *vd;
34dc7c2f 6669 dmu_tx_t *tx;
b128c09f 6670 int error;
3dfb57a3
DB
6671 uint32_t max_queue_depth = zfs_vdev_async_write_max_active *
6672 zfs_vdev_queue_depth_pct / 100;
34dc7c2f 6673
572e2857
BB
6674 VERIFY(spa_writeable(spa));
6675
a1d477c2
MA
6676 /*
6677 * Wait for i/os issued in open context that need to complete
6678 * before this txg syncs.
6679 */
6680 VERIFY0(zio_wait(spa->spa_txg_zio[txg & TXG_MASK]));
6681 spa->spa_txg_zio[txg & TXG_MASK] = zio_root(spa, NULL, NULL, 0);
6682
34dc7c2f
BB
6683 /*
6684 * Lock out configuration changes.
6685 */
b128c09f 6686 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
34dc7c2f
BB
6687
6688 spa->spa_syncing_txg = txg;
6689 spa->spa_sync_pass = 0;
6690
3dfb57a3
DB
6691 mutex_enter(&spa->spa_alloc_lock);
6692 VERIFY0(avl_numnodes(&spa->spa_alloc_tree));
6693 mutex_exit(&spa->spa_alloc_lock);
6694
b128c09f
BB
6695 /*
6696 * If there are any pending vdev state changes, convert them
6697 * into config changes that go out with this transaction group.
6698 */
6699 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
fb5f0bc8
BB
6700 while (list_head(&spa->spa_state_dirty_list) != NULL) {
6701 /*
6702 * We need the write lock here because, for aux vdevs,
6703 * calling vdev_config_dirty() modifies sav_config.
6704 * This is ugly and will become unnecessary when we
6705 * eliminate the aux vdev wart by integrating all vdevs
6706 * into the root vdev tree.
6707 */
6708 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6709 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_WRITER);
6710 while ((vd = list_head(&spa->spa_state_dirty_list)) != NULL) {
6711 vdev_state_clean(vd);
6712 vdev_config_dirty(vd);
6713 }
6714 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6715 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
b128c09f
BB
6716 }
6717 spa_config_exit(spa, SCL_STATE, FTAG);
6718
34dc7c2f
BB
6719 tx = dmu_tx_create_assigned(dp, txg);
6720
cc92e9d0 6721 spa->spa_sync_starttime = gethrtime();
57ddcda1
CC
6722 taskq_cancel_id(system_delay_taskq, spa->spa_deadman_tqid);
6723 spa->spa_deadman_tqid = taskq_dispatch_delay(system_delay_taskq,
79c76d5b 6724 spa_deadman, spa, TQ_SLEEP, ddi_get_lbolt() +
cc92e9d0
GW
6725 NSEC_TO_TICK(spa->spa_deadman_synctime));
6726
34dc7c2f
BB
6727 /*
6728 * If we are upgrading to SPA_VERSION_RAIDZ_DEFLATE this txg,
6729 * set spa_deflate if we have no raid-z vdevs.
6730 */
6731 if (spa->spa_ubsync.ub_version < SPA_VERSION_RAIDZ_DEFLATE &&
6732 spa->spa_uberblock.ub_version >= SPA_VERSION_RAIDZ_DEFLATE) {
6733 int i;
6734
6735 for (i = 0; i < rvd->vdev_children; i++) {
6736 vd = rvd->vdev_child[i];
6737 if (vd->vdev_deflate_ratio != SPA_MINBLOCKSIZE)
6738 break;
6739 }
6740 if (i == rvd->vdev_children) {
6741 spa->spa_deflate = TRUE;
6742 VERIFY(0 == zap_add(spa->spa_meta_objset,
6743 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
6744 sizeof (uint64_t), 1, &spa->spa_deflate, tx));
6745 }
6746 }
6747
3dfb57a3
DB
6748 /*
6749 * Set the top-level vdev's max queue depth. Evaluate each
6750 * top-level's async write queue depth in case it changed.
6751 * The max queue depth will not change in the middle of syncing
6752 * out this txg.
6753 */
1c27024e
DB
6754 uint64_t queue_depth_total = 0;
6755 for (int c = 0; c < rvd->vdev_children; c++) {
3dfb57a3
DB
6756 vdev_t *tvd = rvd->vdev_child[c];
6757 metaslab_group_t *mg = tvd->vdev_mg;
6758
6759 if (mg == NULL || mg->mg_class != spa_normal_class(spa) ||
6760 !metaslab_group_initialized(mg))
6761 continue;
6762
6763 /*
6764 * It is safe to do a lock-free check here because only async
6765 * allocations look at mg_max_alloc_queue_depth, and async
6766 * allocations all happen from spa_sync().
6767 */
6768 ASSERT0(refcount_count(&mg->mg_alloc_queue_depth));
6769 mg->mg_max_alloc_queue_depth = max_queue_depth;
6770 queue_depth_total += mg->mg_max_alloc_queue_depth;
6771 }
1c27024e 6772 metaslab_class_t *mc = spa_normal_class(spa);
3dfb57a3
DB
6773 ASSERT0(refcount_count(&mc->mc_alloc_slots));
6774 mc->mc_alloc_max_slots = queue_depth_total;
6775 mc->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
6776
6777 ASSERT3U(mc->mc_alloc_max_slots, <=,
6778 max_queue_depth * rvd->vdev_children);
6779
a1d477c2
MA
6780 for (int c = 0; c < rvd->vdev_children; c++) {
6781 vdev_t *vd = rvd->vdev_child[c];
6782 vdev_indirect_state_sync_verify(vd);
6783
6784 if (vdev_indirect_should_condense(vd)) {
6785 spa_condense_indirect_start_sync(vd, tx);
6786 break;
6787 }
6788 }
6789
34dc7c2f
BB
6790 /*
6791 * Iterate to convergence.
6792 */
6793 do {
428870ff 6794 int pass = ++spa->spa_sync_pass;
34dc7c2f
BB
6795
6796 spa_sync_config_object(spa, tx);
6797 spa_sync_aux_dev(spa, &spa->spa_spares, tx,
6798 ZPOOL_CONFIG_SPARES, DMU_POOL_SPARES);
6799 spa_sync_aux_dev(spa, &spa->spa_l2cache, tx,
6800 ZPOOL_CONFIG_L2CACHE, DMU_POOL_L2CACHE);
6801 spa_errlog_sync(spa, txg);
6802 dsl_pool_sync(dp, txg);
6803
55d85d5a 6804 if (pass < zfs_sync_pass_deferred_free) {
e8b96c60 6805 spa_sync_frees(spa, free_bpl, tx);
428870ff 6806 } else {
905edb40
MA
6807 /*
6808 * We can not defer frees in pass 1, because
6809 * we sync the deferred frees later in pass 1.
6810 */
6811 ASSERT3U(pass, >, 1);
428870ff 6812 bplist_iterate(free_bpl, bpobj_enqueue_cb,
e8b96c60 6813 &spa->spa_deferred_bpobj, tx);
34dc7c2f
BB
6814 }
6815
428870ff
BB
6816 ddt_sync(spa, txg);
6817 dsl_scan_sync(dp, tx);
34dc7c2f 6818
a1d477c2
MA
6819 if (spa->spa_vdev_removal != NULL)
6820 svr_sync(spa, tx);
6821
6822 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, txg))
6823 != NULL)
428870ff
BB
6824 vdev_sync(vd, txg);
6825
905edb40 6826 if (pass == 1) {
428870ff 6827 spa_sync_upgrades(spa, tx);
905edb40
MA
6828 ASSERT3U(txg, >=,
6829 spa->spa_uberblock.ub_rootbp.blk_birth);
6830 /*
6831 * Note: We need to check if the MOS is dirty
6832 * because we could have marked the MOS dirty
6833 * without updating the uberblock (e.g. if we
6834 * have sync tasks but no dirty user data). We
6835 * need to check the uberblock's rootbp because
6836 * it is updated if we have synced out dirty
6837 * data (though in this case the MOS will most
6838 * likely also be dirty due to second order
6839 * effects, we don't want to rely on that here).
6840 */
6841 if (spa->spa_uberblock.ub_rootbp.blk_birth < txg &&
6842 !dmu_objset_is_dirty(mos, txg)) {
6843 /*
6844 * Nothing changed on the first pass,
6845 * therefore this TXG is a no-op. Avoid
6846 * syncing deferred frees, so that we
6847 * can keep this TXG as a no-op.
6848 */
6849 ASSERT(txg_list_empty(&dp->dp_dirty_datasets,
6850 txg));
6851 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
6852 ASSERT(txg_list_empty(&dp->dp_sync_tasks, txg));
6853 break;
6854 }
6855 spa_sync_deferred_frees(spa, tx);
6856 }
34dc7c2f 6857
428870ff 6858 } while (dmu_objset_is_dirty(mos, txg));
34dc7c2f 6859
33cf67cd 6860#ifdef ZFS_DEBUG
e0ab3ab5
JS
6861 if (!list_is_empty(&spa->spa_config_dirty_list)) {
6862 /*
6863 * Make sure that the number of ZAPs for all the vdevs matches
6864 * the number of ZAPs in the per-vdev ZAP list. This only gets
6865 * called if the config is dirty; otherwise there may be
6866 * outstanding AVZ operations that weren't completed in
6867 * spa_sync_config_object.
6868 */
6869 uint64_t all_vdev_zap_entry_count;
6870 ASSERT0(zap_count(spa->spa_meta_objset,
6871 spa->spa_all_vdev_zaps, &all_vdev_zap_entry_count));
6872 ASSERT3U(vdev_count_verify_zaps(spa->spa_root_vdev), ==,
6873 all_vdev_zap_entry_count);
6874 }
33cf67cd 6875#endif
e0ab3ab5 6876
a1d477c2
MA
6877 if (spa->spa_vdev_removal != NULL) {
6878 ASSERT0(spa->spa_vdev_removal->svr_bytes_done[txg & TXG_MASK]);
6879 }
6880
34dc7c2f
BB
6881 /*
6882 * Rewrite the vdev configuration (which includes the uberblock)
6883 * to commit the transaction group.
6884 *
6885 * If there are no dirty vdevs, we sync the uberblock to a few
6886 * random top-level vdevs that are known to be visible in the
b128c09f
BB
6887 * config cache (see spa_vdev_add() for a complete description).
6888 * If there *are* dirty vdevs, sync the uberblock to all vdevs.
34dc7c2f 6889 */
b128c09f
BB
6890 for (;;) {
6891 /*
6892 * We hold SCL_STATE to prevent vdev open/close/etc.
6893 * while we're attempting to write the vdev labels.
6894 */
6895 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
6896
6897 if (list_is_empty(&spa->spa_config_dirty_list)) {
6898 vdev_t *svd[SPA_DVAS_PER_BP];
6899 int svdcount = 0;
6900 int children = rvd->vdev_children;
6901 int c0 = spa_get_random(children);
b128c09f 6902
1c27024e 6903 for (int c = 0; c < children; c++) {
b128c09f 6904 vd = rvd->vdev_child[(c0 + c) % children];
a1d477c2
MA
6905 if (vd->vdev_ms_array == 0 || vd->vdev_islog ||
6906 !vdev_is_concrete(vd))
b128c09f
BB
6907 continue;
6908 svd[svdcount++] = vd;
6909 if (svdcount == SPA_DVAS_PER_BP)
6910 break;
6911 }
b6fcb792 6912 error = vdev_config_sync(svd, svdcount, txg);
b128c09f
BB
6913 } else {
6914 error = vdev_config_sync(rvd->vdev_child,
b6fcb792 6915 rvd->vdev_children, txg);
34dc7c2f 6916 }
34dc7c2f 6917
3bc7e0fb
GW
6918 if (error == 0)
6919 spa->spa_last_synced_guid = rvd->vdev_guid;
6920
b128c09f
BB
6921 spa_config_exit(spa, SCL_STATE, FTAG);
6922
6923 if (error == 0)
6924 break;
cec3a0a1 6925 zio_suspend(spa, NULL, ZIO_SUSPEND_IOERR);
b128c09f
BB
6926 zio_resume_wait(spa);
6927 }
34dc7c2f
BB
6928 dmu_tx_commit(tx);
6929
57ddcda1 6930 taskq_cancel_id(system_delay_taskq, spa->spa_deadman_tqid);
cc92e9d0
GW
6931 spa->spa_deadman_tqid = 0;
6932
34dc7c2f
BB
6933 /*
6934 * Clear the dirty config list.
6935 */
b128c09f 6936 while ((vd = list_head(&spa->spa_config_dirty_list)) != NULL)
34dc7c2f
BB
6937 vdev_config_clean(vd);
6938
6939 /*
6940 * Now that the new config has synced transactionally,
6941 * let it become visible to the config cache.
6942 */
6943 if (spa->spa_config_syncing != NULL) {
6944 spa_config_set(spa, spa->spa_config_syncing);
6945 spa->spa_config_txg = txg;
6946 spa->spa_config_syncing = NULL;
6947 }
6948
428870ff 6949 dsl_pool_sync_done(dp, txg);
34dc7c2f 6950
3dfb57a3
DB
6951 mutex_enter(&spa->spa_alloc_lock);
6952 VERIFY0(avl_numnodes(&spa->spa_alloc_tree));
6953 mutex_exit(&spa->spa_alloc_lock);
6954
34dc7c2f
BB
6955 /*
6956 * Update usable space statistics.
6957 */
c65aa5b2 6958 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, TXG_CLEAN(txg))))
34dc7c2f
BB
6959 vdev_sync_done(vd, txg);
6960
428870ff
BB
6961 spa_update_dspace(spa);
6962
34dc7c2f
BB
6963 /*
6964 * It had better be the case that we didn't dirty anything
6965 * since vdev_config_sync().
6966 */
6967 ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
6968 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
6969 ASSERT(txg_list_empty(&spa->spa_vdev_txg_list, txg));
428870ff
BB
6970
6971 spa->spa_sync_pass = 0;
34dc7c2f 6972
55922e73
GW
6973 /*
6974 * Update the last synced uberblock here. We want to do this at
6975 * the end of spa_sync() so that consumers of spa_last_synced_txg()
6976 * will be guaranteed that all the processing associated with
6977 * that txg has been completed.
6978 */
6979 spa->spa_ubsync = spa->spa_uberblock;
b128c09f 6980 spa_config_exit(spa, SCL_CONFIG, FTAG);
34dc7c2f 6981
428870ff
BB
6982 spa_handle_ignored_writes(spa);
6983
34dc7c2f
BB
6984 /*
6985 * If any async tasks have been requested, kick them off.
6986 */
6987 spa_async_dispatch(spa);
6988}
6989
6990/*
6991 * Sync all pools. We don't want to hold the namespace lock across these
6992 * operations, so we take a reference on the spa_t and drop the lock during the
6993 * sync.
6994 */
6995void
6996spa_sync_allpools(void)
6997{
6998 spa_t *spa = NULL;
6999 mutex_enter(&spa_namespace_lock);
7000 while ((spa = spa_next(spa)) != NULL) {
572e2857
BB
7001 if (spa_state(spa) != POOL_STATE_ACTIVE ||
7002 !spa_writeable(spa) || spa_suspended(spa))
34dc7c2f
BB
7003 continue;
7004 spa_open_ref(spa, FTAG);
7005 mutex_exit(&spa_namespace_lock);
7006 txg_wait_synced(spa_get_dsl(spa), 0);
7007 mutex_enter(&spa_namespace_lock);
7008 spa_close(spa, FTAG);
7009 }
7010 mutex_exit(&spa_namespace_lock);
7011}
7012
7013/*
7014 * ==========================================================================
7015 * Miscellaneous routines
7016 * ==========================================================================
7017 */
7018
7019/*
7020 * Remove all pools in the system.
7021 */
7022void
7023spa_evict_all(void)
7024{
7025 spa_t *spa;
7026
7027 /*
7028 * Remove all cached state. All pools should be closed now,
7029 * so every spa in the AVL tree should be unreferenced.
7030 */
7031 mutex_enter(&spa_namespace_lock);
7032 while ((spa = spa_next(NULL)) != NULL) {
7033 /*
7034 * Stop async tasks. The async thread may need to detach
7035 * a device that's been replaced, which requires grabbing
7036 * spa_namespace_lock, so we must drop it here.
7037 */
7038 spa_open_ref(spa, FTAG);
7039 mutex_exit(&spa_namespace_lock);
7040 spa_async_suspend(spa);
7041 mutex_enter(&spa_namespace_lock);
34dc7c2f
BB
7042 spa_close(spa, FTAG);
7043
7044 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
7045 spa_unload(spa);
7046 spa_deactivate(spa);
7047 }
7048 spa_remove(spa);
7049 }
7050 mutex_exit(&spa_namespace_lock);
7051}
7052
7053vdev_t *
9babb374 7054spa_lookup_by_guid(spa_t *spa, uint64_t guid, boolean_t aux)
34dc7c2f 7055{
b128c09f
BB
7056 vdev_t *vd;
7057 int i;
7058
7059 if ((vd = vdev_lookup_by_guid(spa->spa_root_vdev, guid)) != NULL)
7060 return (vd);
7061
9babb374 7062 if (aux) {
b128c09f
BB
7063 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
7064 vd = spa->spa_l2cache.sav_vdevs[i];
9babb374
BB
7065 if (vd->vdev_guid == guid)
7066 return (vd);
7067 }
7068
7069 for (i = 0; i < spa->spa_spares.sav_count; i++) {
7070 vd = spa->spa_spares.sav_vdevs[i];
b128c09f
BB
7071 if (vd->vdev_guid == guid)
7072 return (vd);
7073 }
7074 }
7075
7076 return (NULL);
34dc7c2f
BB
7077}
7078
7079void
7080spa_upgrade(spa_t *spa, uint64_t version)
7081{
572e2857
BB
7082 ASSERT(spa_writeable(spa));
7083
b128c09f 7084 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f
BB
7085
7086 /*
7087 * This should only be called for a non-faulted pool, and since a
7088 * future version would result in an unopenable pool, this shouldn't be
7089 * possible.
7090 */
8dca0a9a 7091 ASSERT(SPA_VERSION_IS_SUPPORTED(spa->spa_uberblock.ub_version));
9b67f605 7092 ASSERT3U(version, >=, spa->spa_uberblock.ub_version);
34dc7c2f
BB
7093
7094 spa->spa_uberblock.ub_version = version;
7095 vdev_config_dirty(spa->spa_root_vdev);
7096
b128c09f 7097 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
7098
7099 txg_wait_synced(spa_get_dsl(spa), 0);
7100}
7101
7102boolean_t
7103spa_has_spare(spa_t *spa, uint64_t guid)
7104{
7105 int i;
7106 uint64_t spareguid;
7107 spa_aux_vdev_t *sav = &spa->spa_spares;
7108
7109 for (i = 0; i < sav->sav_count; i++)
7110 if (sav->sav_vdevs[i]->vdev_guid == guid)
7111 return (B_TRUE);
7112
7113 for (i = 0; i < sav->sav_npending; i++) {
7114 if (nvlist_lookup_uint64(sav->sav_pending[i], ZPOOL_CONFIG_GUID,
7115 &spareguid) == 0 && spareguid == guid)
7116 return (B_TRUE);
7117 }
7118
7119 return (B_FALSE);
7120}
7121
b128c09f
BB
7122/*
7123 * Check if a pool has an active shared spare device.
7124 * Note: reference count of an active spare is 2, as a spare and as a replace
7125 */
7126static boolean_t
7127spa_has_active_shared_spare(spa_t *spa)
7128{
7129 int i, refcnt;
7130 uint64_t pool;
7131 spa_aux_vdev_t *sav = &spa->spa_spares;
7132
7133 for (i = 0; i < sav->sav_count; i++) {
7134 if (spa_spare_exists(sav->sav_vdevs[i]->vdev_guid, &pool,
7135 &refcnt) && pool != 0ULL && pool == spa_guid(spa) &&
7136 refcnt > 2)
7137 return (B_TRUE);
7138 }
7139
7140 return (B_FALSE);
7141}
7142
a1d477c2 7143sysevent_t *
12fa0466
DE
7144spa_event_create(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
7145{
7146 sysevent_t *ev = NULL;
7147#ifdef _KERNEL
7148 nvlist_t *resource;
7149
7150 resource = zfs_event_create(spa, vd, FM_SYSEVENT_CLASS, name, hist_nvl);
7151 if (resource) {
7152 ev = kmem_alloc(sizeof (sysevent_t), KM_SLEEP);
7153 ev->resource = resource;
7154 }
7155#endif
7156 return (ev);
7157}
7158
a1d477c2 7159void
12fa0466
DE
7160spa_event_post(sysevent_t *ev)
7161{
7162#ifdef _KERNEL
7163 if (ev) {
7164 zfs_zevent_post(ev->resource, NULL, zfs_zevent_post_cb);
7165 kmem_free(ev, sizeof (*ev));
7166 }
7167#endif
7168}
7169
34dc7c2f 7170/*
fb390aaf
HR
7171 * Post a zevent corresponding to the given sysevent. The 'name' must be one
7172 * of the event definitions in sys/sysevent/eventdefs.h. The payload will be
34dc7c2f
BB
7173 * filled in from the spa and (optionally) the vdev. This doesn't do anything
7174 * in the userland libzpool, as we don't want consumers to misinterpret ztest
7175 * or zdb as real changes.
7176 */
7177void
12fa0466 7178spa_event_notify(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
34dc7c2f 7179{
12fa0466 7180 spa_event_post(spa_event_create(spa, vd, hist_nvl, name));
34dc7c2f 7181}
c28b2279
BB
7182
7183#if defined(_KERNEL) && defined(HAVE_SPL)
7184/* state manipulation functions */
7185EXPORT_SYMBOL(spa_open);
7186EXPORT_SYMBOL(spa_open_rewind);
7187EXPORT_SYMBOL(spa_get_stats);
7188EXPORT_SYMBOL(spa_create);
c28b2279
BB
7189EXPORT_SYMBOL(spa_import);
7190EXPORT_SYMBOL(spa_tryimport);
7191EXPORT_SYMBOL(spa_destroy);
7192EXPORT_SYMBOL(spa_export);
7193EXPORT_SYMBOL(spa_reset);
7194EXPORT_SYMBOL(spa_async_request);
7195EXPORT_SYMBOL(spa_async_suspend);
7196EXPORT_SYMBOL(spa_async_resume);
7197EXPORT_SYMBOL(spa_inject_addref);
7198EXPORT_SYMBOL(spa_inject_delref);
7199EXPORT_SYMBOL(spa_scan_stat_init);
7200EXPORT_SYMBOL(spa_scan_get_stats);
7201
7202/* device maniion */
7203EXPORT_SYMBOL(spa_vdev_add);
7204EXPORT_SYMBOL(spa_vdev_attach);
7205EXPORT_SYMBOL(spa_vdev_detach);
c28b2279
BB
7206EXPORT_SYMBOL(spa_vdev_setpath);
7207EXPORT_SYMBOL(spa_vdev_setfru);
7208EXPORT_SYMBOL(spa_vdev_split_mirror);
7209
7210/* spare statech is global across all pools) */
7211EXPORT_SYMBOL(spa_spare_add);
7212EXPORT_SYMBOL(spa_spare_remove);
7213EXPORT_SYMBOL(spa_spare_exists);
7214EXPORT_SYMBOL(spa_spare_activate);
7215
7216/* L2ARC statech is global across all pools) */
7217EXPORT_SYMBOL(spa_l2cache_add);
7218EXPORT_SYMBOL(spa_l2cache_remove);
7219EXPORT_SYMBOL(spa_l2cache_exists);
7220EXPORT_SYMBOL(spa_l2cache_activate);
7221EXPORT_SYMBOL(spa_l2cache_drop);
7222
7223/* scanning */
7224EXPORT_SYMBOL(spa_scan);
7225EXPORT_SYMBOL(spa_scan_stop);
7226
7227/* spa syncing */
7228EXPORT_SYMBOL(spa_sync); /* only for DMU use */
7229EXPORT_SYMBOL(spa_sync_allpools);
7230
7231/* properties */
7232EXPORT_SYMBOL(spa_prop_set);
7233EXPORT_SYMBOL(spa_prop_get);
7234EXPORT_SYMBOL(spa_prop_clear_bootfs);
7235
7236/* asynchronous event notification */
7237EXPORT_SYMBOL(spa_event_notify);
7238#endif
dea377c0
MA
7239
7240#if defined(_KERNEL) && defined(HAVE_SPL)
7241module_param(spa_load_verify_maxinflight, int, 0644);
7242MODULE_PARM_DESC(spa_load_verify_maxinflight,
7243 "Max concurrent traversal I/Os while verifying pool during import -X");
7244
7245module_param(spa_load_verify_metadata, int, 0644);
7246MODULE_PARM_DESC(spa_load_verify_metadata,
7247 "Set to traverse metadata on pool import");
7248
7249module_param(spa_load_verify_data, int, 0644);
7250MODULE_PARM_DESC(spa_load_verify_data,
7251 "Set to traverse data on pool import");
dcb6bed1 7252
02730c33 7253/* CSTYLED */
dcb6bed1
D
7254module_param(zio_taskq_batch_pct, uint, 0444);
7255MODULE_PARM_DESC(zio_taskq_batch_pct,
7256 "Percentage of CPUs to run an IO worker thread");
7257
dea377c0 7258#endif