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