]> git.proxmox.com Git - mirror_zfs.git/blame - module/zfs/spa.c
Report pool suspended due to MMP
[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
31864e3d 356 if ((prop = zpool_name_to_prop(za.za_name)) == ZPOOL_PROP_INVAL)
34dc7c2f
BB
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
31864e3d
BB
443 switch (prop) {
444 case ZPOOL_PROP_INVAL:
9ae529ec 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
31864e3d 701 if (prop == ZPOOL_PROP_VERSION || prop == ZPOOL_PROP_INVAL) {
9ae529ec
CS
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
9c5167d1 1191 * feature SPA_FEATURE_USEROBJ_ACCOUNTING/SPA_FEATURE_PROJECT_QUOTA.
1de321e6
JX
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{
460f239e 1566 nvlist_t **l2cache = NULL;
34dc7c2f
BB
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
460f239e
D
1650 if (sav->sav_count > 0)
1651 l2cache = kmem_alloc(sav->sav_count * sizeof (void *),
1652 KM_SLEEP);
67d60824
NB
1653 for (i = 0; i < sav->sav_count; i++)
1654 l2cache[i] = vdev_config_generate(spa,
1655 sav->sav_vdevs[i], B_TRUE, VDEV_CONFIG_L2CACHE);
1656 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
1657 ZPOOL_CONFIG_L2CACHE, l2cache, sav->sav_count) == 0);
1658
1659out:
34dc7c2f
BB
1660 /*
1661 * Purge vdevs that were dropped
1662 */
1663 for (i = 0; i < oldnvdevs; i++) {
1664 uint64_t pool;
1665
1666 vd = oldvdevs[i];
1667 if (vd != NULL) {
5ffb9d1d
GW
1668 ASSERT(vd->vdev_isl2cache);
1669
fb5f0bc8
BB
1670 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
1671 pool != 0ULL && l2arc_vdev_present(vd))
34dc7c2f 1672 l2arc_remove_vdev(vd);
5ffb9d1d
GW
1673 vdev_clear_stats(vd);
1674 vdev_free(vd);
34dc7c2f
BB
1675 }
1676 }
1677
1678 if (oldvdevs)
1679 kmem_free(oldvdevs, oldnvdevs * sizeof (void *));
1680
34dc7c2f
BB
1681 for (i = 0; i < sav->sav_count; i++)
1682 nvlist_free(l2cache[i]);
1683 if (sav->sav_count)
1684 kmem_free(l2cache, sav->sav_count * sizeof (void *));
1685}
1686
1687static int
1688load_nvlist(spa_t *spa, uint64_t obj, nvlist_t **value)
1689{
1690 dmu_buf_t *db;
1691 char *packed = NULL;
1692 size_t nvsize = 0;
1693 int error;
1694 *value = NULL;
1695
c3275b56
BB
1696 error = dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db);
1697 if (error)
1698 return (error);
1699
34dc7c2f
BB
1700 nvsize = *(uint64_t *)db->db_data;
1701 dmu_buf_rele(db, FTAG);
1702
77aef6f6 1703 packed = vmem_alloc(nvsize, KM_SLEEP);
9babb374
BB
1704 error = dmu_read(spa->spa_meta_objset, obj, 0, nvsize, packed,
1705 DMU_READ_PREFETCH);
34dc7c2f
BB
1706 if (error == 0)
1707 error = nvlist_unpack(packed, nvsize, value, 0);
77aef6f6 1708 vmem_free(packed, nvsize);
34dc7c2f
BB
1709
1710 return (error);
1711}
1712
1713/*
1714 * Checks to see if the given vdev could not be opened, in which case we post a
1715 * sysevent to notify the autoreplace code that the device has been removed.
1716 */
1717static void
1718spa_check_removed(vdev_t *vd)
1719{
1c27024e 1720 for (int c = 0; c < vd->vdev_children; c++)
34dc7c2f
BB
1721 spa_check_removed(vd->vdev_child[c]);
1722
7011fb60
YP
1723 if (vd->vdev_ops->vdev_op_leaf && vdev_is_dead(vd) &&
1724 !vd->vdev_ishole) {
fb390aaf 1725 zfs_post_autoreplace(vd->vdev_spa, vd);
12fa0466 1726 spa_event_notify(vd->vdev_spa, vd, NULL, ESC_ZFS_VDEV_CHECK);
34dc7c2f
BB
1727 }
1728}
1729
e0ab3ab5
JS
1730static void
1731spa_config_valid_zaps(vdev_t *vd, vdev_t *mvd)
1732{
e0ab3ab5
JS
1733 ASSERT3U(vd->vdev_children, ==, mvd->vdev_children);
1734
1735 vd->vdev_top_zap = mvd->vdev_top_zap;
1736 vd->vdev_leaf_zap = mvd->vdev_leaf_zap;
1737
1c27024e 1738 for (uint64_t i = 0; i < vd->vdev_children; i++) {
e0ab3ab5
JS
1739 spa_config_valid_zaps(vd->vdev_child[i], mvd->vdev_child[i]);
1740 }
1741}
1742
9babb374 1743/*
572e2857 1744 * Validate the current config against the MOS config
9babb374 1745 */
572e2857
BB
1746static boolean_t
1747spa_config_valid(spa_t *spa, nvlist_t *config)
9babb374 1748{
572e2857
BB
1749 vdev_t *mrvd, *rvd = spa->spa_root_vdev;
1750 nvlist_t *nv;
1751
1752 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nv) == 0);
1753
1754 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1755 VERIFY(spa_config_parse(spa, &mrvd, nv, NULL, 0, VDEV_ALLOC_LOAD) == 0);
1756
1757 ASSERT3U(rvd->vdev_children, ==, mrvd->vdev_children);
9babb374 1758
428870ff 1759 /*
572e2857
BB
1760 * If we're doing a normal import, then build up any additional
1761 * diagnostic information about missing devices in this config.
1762 * We'll pass this up to the user for further processing.
428870ff 1763 */
572e2857
BB
1764 if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG)) {
1765 nvlist_t **child, *nv;
1766 uint64_t idx = 0;
1767
160987b5 1768 child = kmem_alloc(rvd->vdev_children * sizeof (nvlist_t *),
79c76d5b
BB
1769 KM_SLEEP);
1770 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
572e2857 1771
1c27024e 1772 for (int c = 0; c < rvd->vdev_children; c++) {
572e2857
BB
1773 vdev_t *tvd = rvd->vdev_child[c];
1774 vdev_t *mtvd = mrvd->vdev_child[c];
1775
1776 if (tvd->vdev_ops == &vdev_missing_ops &&
1777 mtvd->vdev_ops != &vdev_missing_ops &&
1778 mtvd->vdev_islog)
1779 child[idx++] = vdev_config_generate(spa, mtvd,
1780 B_FALSE, 0);
1781 }
9babb374 1782
572e2857
BB
1783 if (idx) {
1784 VERIFY(nvlist_add_nvlist_array(nv,
1785 ZPOOL_CONFIG_CHILDREN, child, idx) == 0);
1786 VERIFY(nvlist_add_nvlist(spa->spa_load_info,
1787 ZPOOL_CONFIG_MISSING_DEVICES, nv) == 0);
1788
1c27024e 1789 for (int i = 0; i < idx; i++)
572e2857
BB
1790 nvlist_free(child[i]);
1791 }
1792 nvlist_free(nv);
1793 kmem_free(child, rvd->vdev_children * sizeof (char **));
1794 }
1795
1796 /*
1797 * Compare the root vdev tree with the information we have
1798 * from the MOS config (mrvd). Check each top-level vdev
1799 * with the corresponding MOS config top-level (mtvd).
1800 */
1c27024e 1801 for (int c = 0; c < rvd->vdev_children; c++) {
572e2857
BB
1802 vdev_t *tvd = rvd->vdev_child[c];
1803 vdev_t *mtvd = mrvd->vdev_child[c];
1804
1805 /*
1806 * Resolve any "missing" vdevs in the current configuration.
1807 * If we find that the MOS config has more accurate information
1808 * about the top-level vdev then use that vdev instead.
1809 */
1810 if (tvd->vdev_ops == &vdev_missing_ops &&
1811 mtvd->vdev_ops != &vdev_missing_ops) {
1812
1813 if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG))
1814 continue;
1815
1816 /*
1817 * Device specific actions.
1818 */
1819 if (mtvd->vdev_islog) {
1820 spa_set_log_state(spa, SPA_LOG_CLEAR);
1821 } else {
1822 /*
1823 * XXX - once we have 'readonly' pool
1824 * support we should be able to handle
1825 * missing data devices by transitioning
1826 * the pool to readonly.
1827 */
1828 continue;
1829 }
1830
1831 /*
1832 * Swap the missing vdev with the data we were
1833 * able to obtain from the MOS config.
1834 */
1835 vdev_remove_child(rvd, tvd);
1836 vdev_remove_child(mrvd, mtvd);
1837
1838 vdev_add_child(rvd, mtvd);
1839 vdev_add_child(mrvd, tvd);
1840
1841 spa_config_exit(spa, SCL_ALL, FTAG);
1842 vdev_load(mtvd);
1843 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1844
1845 vdev_reopen(rvd);
e0ab3ab5
JS
1846 } else {
1847 if (mtvd->vdev_islog) {
1848 /*
1849 * Load the slog device's state from the MOS
1850 * config since it's possible that the label
1851 * does not contain the most up-to-date
1852 * information.
1853 */
1854 vdev_load_log_state(tvd, mtvd);
1855 vdev_reopen(tvd);
1856 }
1857
572e2857 1858 /*
e0ab3ab5 1859 * Per-vdev ZAP info is stored exclusively in the MOS.
572e2857 1860 */
e0ab3ab5 1861 spa_config_valid_zaps(tvd, mtvd);
572e2857 1862 }
9babb374 1863 }
e0ab3ab5 1864
572e2857 1865 vdev_free(mrvd);
428870ff 1866 spa_config_exit(spa, SCL_ALL, FTAG);
572e2857
BB
1867
1868 /*
1869 * Ensure we were able to validate the config.
1870 */
1871 return (rvd->vdev_guid_sum == spa->spa_uberblock.ub_guid_sum);
9babb374
BB
1872}
1873
b128c09f
BB
1874/*
1875 * Check for missing log devices
1876 */
13fe0198 1877static boolean_t
b128c09f
BB
1878spa_check_logs(spa_t *spa)
1879{
13fe0198 1880 boolean_t rv = B_FALSE;
9c43027b 1881 dsl_pool_t *dp = spa_get_dsl(spa);
13fe0198 1882
b128c09f 1883 switch (spa->spa_log_state) {
e75c13c3
BB
1884 default:
1885 break;
b128c09f
BB
1886 case SPA_LOG_MISSING:
1887 /* need to recheck in case slog has been restored */
1888 case SPA_LOG_UNKNOWN:
9c43027b
AJ
1889 rv = (dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
1890 zil_check_log_chain, NULL, DS_FIND_CHILDREN) != 0);
13fe0198 1891 if (rv)
428870ff 1892 spa_set_log_state(spa, SPA_LOG_MISSING);
b128c09f 1893 break;
b128c09f 1894 }
13fe0198 1895 return (rv);
b128c09f
BB
1896}
1897
428870ff
BB
1898static boolean_t
1899spa_passivate_log(spa_t *spa)
34dc7c2f 1900{
428870ff
BB
1901 vdev_t *rvd = spa->spa_root_vdev;
1902 boolean_t slog_found = B_FALSE;
b128c09f 1903
428870ff 1904 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
fb5f0bc8 1905
428870ff
BB
1906 if (!spa_has_slogs(spa))
1907 return (B_FALSE);
34dc7c2f 1908
1c27024e 1909 for (int c = 0; c < rvd->vdev_children; c++) {
428870ff
BB
1910 vdev_t *tvd = rvd->vdev_child[c];
1911 metaslab_group_t *mg = tvd->vdev_mg;
34dc7c2f 1912
428870ff
BB
1913 if (tvd->vdev_islog) {
1914 metaslab_group_passivate(mg);
1915 slog_found = B_TRUE;
1916 }
34dc7c2f
BB
1917 }
1918
428870ff
BB
1919 return (slog_found);
1920}
34dc7c2f 1921
428870ff
BB
1922static void
1923spa_activate_log(spa_t *spa)
1924{
1925 vdev_t *rvd = spa->spa_root_vdev;
34dc7c2f 1926
428870ff
BB
1927 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1928
1c27024e 1929 for (int c = 0; c < rvd->vdev_children; c++) {
428870ff
BB
1930 vdev_t *tvd = rvd->vdev_child[c];
1931 metaslab_group_t *mg = tvd->vdev_mg;
1932
1933 if (tvd->vdev_islog)
1934 metaslab_group_activate(mg);
34dc7c2f 1935 }
428870ff 1936}
34dc7c2f 1937
428870ff
BB
1938int
1939spa_offline_log(spa_t *spa)
1940{
13fe0198 1941 int error;
9babb374 1942
13fe0198
MA
1943 error = dmu_objset_find(spa_name(spa), zil_vdev_offline,
1944 NULL, DS_FIND_CHILDREN);
1945 if (error == 0) {
428870ff
BB
1946 /*
1947 * We successfully offlined the log device, sync out the
1948 * current txg so that the "stubby" block can be removed
1949 * by zil_sync().
1950 */
1951 txg_wait_synced(spa->spa_dsl_pool, 0);
1952 }
1953 return (error);
1954}
34dc7c2f 1955
428870ff
BB
1956static void
1957spa_aux_check_removed(spa_aux_vdev_t *sav)
1958{
1c27024e 1959 for (int i = 0; i < sav->sav_count; i++)
428870ff
BB
1960 spa_check_removed(sav->sav_vdevs[i]);
1961}
34dc7c2f 1962
428870ff
BB
1963void
1964spa_claim_notify(zio_t *zio)
1965{
1966 spa_t *spa = zio->io_spa;
34dc7c2f 1967
428870ff
BB
1968 if (zio->io_error)
1969 return;
34dc7c2f 1970
428870ff
BB
1971 mutex_enter(&spa->spa_props_lock); /* any mutex will do */
1972 if (spa->spa_claim_max_txg < zio->io_bp->blk_birth)
1973 spa->spa_claim_max_txg = zio->io_bp->blk_birth;
1974 mutex_exit(&spa->spa_props_lock);
1975}
34dc7c2f 1976
428870ff
BB
1977typedef struct spa_load_error {
1978 uint64_t sle_meta_count;
1979 uint64_t sle_data_count;
1980} spa_load_error_t;
34dc7c2f 1981
428870ff
BB
1982static void
1983spa_load_verify_done(zio_t *zio)
1984{
1985 blkptr_t *bp = zio->io_bp;
1986 spa_load_error_t *sle = zio->io_private;
1987 dmu_object_type_t type = BP_GET_TYPE(bp);
1988 int error = zio->io_error;
dea377c0 1989 spa_t *spa = zio->io_spa;
34dc7c2f 1990
a6255b7f 1991 abd_free(zio->io_abd);
428870ff 1992 if (error) {
9ae529ec 1993 if ((BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type)) &&
428870ff 1994 type != DMU_OT_INTENT_LOG)
bc89ac84 1995 atomic_inc_64(&sle->sle_meta_count);
428870ff 1996 else
bc89ac84 1997 atomic_inc_64(&sle->sle_data_count);
34dc7c2f 1998 }
dea377c0
MA
1999
2000 mutex_enter(&spa->spa_scrub_lock);
d4a72f23 2001 spa->spa_load_verify_ios--;
dea377c0
MA
2002 cv_broadcast(&spa->spa_scrub_io_cv);
2003 mutex_exit(&spa->spa_scrub_lock);
428870ff 2004}
34dc7c2f 2005
dea377c0
MA
2006/*
2007 * Maximum number of concurrent scrub i/os to create while verifying
2008 * a pool while importing it.
2009 */
2010int spa_load_verify_maxinflight = 10000;
2011int spa_load_verify_metadata = B_TRUE;
2012int spa_load_verify_data = B_TRUE;
2013
428870ff
BB
2014/*ARGSUSED*/
2015static int
2016spa_load_verify_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
5dbd68a3 2017 const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
428870ff 2018{
fcff0f35 2019 if (bp == NULL || BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
dea377c0
MA
2020 return (0);
2021 /*
2022 * Note: normally this routine will not be called if
2023 * spa_load_verify_metadata is not set. However, it may be useful
2024 * to manually set the flag after the traversal has begun.
2025 */
2026 if (!spa_load_verify_metadata)
2027 return (0);
a6255b7f 2028 if (!BP_IS_METADATA(bp) && !spa_load_verify_data)
dea377c0
MA
2029 return (0);
2030
1c27024e
DB
2031 zio_t *rio = arg;
2032 size_t size = BP_GET_PSIZE(bp);
dea377c0
MA
2033
2034 mutex_enter(&spa->spa_scrub_lock);
d4a72f23 2035 while (spa->spa_load_verify_ios >= spa_load_verify_maxinflight)
dea377c0 2036 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
d4a72f23 2037 spa->spa_load_verify_ios++;
dea377c0
MA
2038 mutex_exit(&spa->spa_scrub_lock);
2039
a6255b7f 2040 zio_nowait(zio_read(rio, spa, bp, abd_alloc_for_io(size, B_FALSE), size,
dea377c0
MA
2041 spa_load_verify_done, rio->io_private, ZIO_PRIORITY_SCRUB,
2042 ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CANFAIL |
2043 ZIO_FLAG_SCRUB | ZIO_FLAG_RAW, zb));
428870ff
BB
2044 return (0);
2045}
34dc7c2f 2046
d1d19c78
PD
2047/* ARGSUSED */
2048int
2049verify_dataset_name_len(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
2050{
2051 if (dsl_dataset_namelen(ds) >= ZFS_MAX_DATASET_NAME_LEN)
2052 return (SET_ERROR(ENAMETOOLONG));
2053
2054 return (0);
2055}
2056
428870ff
BB
2057static int
2058spa_load_verify(spa_t *spa)
2059{
2060 zio_t *rio;
2061 spa_load_error_t sle = { 0 };
2062 zpool_rewind_policy_t policy;
2063 boolean_t verify_ok = B_FALSE;
dea377c0 2064 int error = 0;
34dc7c2f 2065
428870ff 2066 zpool_get_rewind_policy(spa->spa_config, &policy);
34dc7c2f 2067
428870ff
BB
2068 if (policy.zrp_request & ZPOOL_NEVER_REWIND)
2069 return (0);
34dc7c2f 2070
d1d19c78
PD
2071 dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
2072 error = dmu_objset_find_dp(spa->spa_dsl_pool,
2073 spa->spa_dsl_pool->dp_root_dir_obj, verify_dataset_name_len, NULL,
2074 DS_FIND_CHILDREN);
2075 dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
2076 if (error != 0)
2077 return (error);
2078
428870ff
BB
2079 rio = zio_root(spa, NULL, &sle,
2080 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
34dc7c2f 2081
dea377c0
MA
2082 if (spa_load_verify_metadata) {
2083 error = traverse_pool(spa, spa->spa_verify_min_txg,
b5256303
TC
2084 TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
2085 TRAVERSE_NO_DECRYPT, spa_load_verify_cb, rio);
dea377c0 2086 }
428870ff
BB
2087
2088 (void) zio_wait(rio);
2089
2090 spa->spa_load_meta_errors = sle.sle_meta_count;
2091 spa->spa_load_data_errors = sle.sle_data_count;
2092
2093 if (!error && sle.sle_meta_count <= policy.zrp_maxmeta &&
2094 sle.sle_data_count <= policy.zrp_maxdata) {
572e2857
BB
2095 int64_t loss = 0;
2096
428870ff
BB
2097 verify_ok = B_TRUE;
2098 spa->spa_load_txg = spa->spa_uberblock.ub_txg;
2099 spa->spa_load_txg_ts = spa->spa_uberblock.ub_timestamp;
572e2857
BB
2100
2101 loss = spa->spa_last_ubsync_txg_ts - spa->spa_load_txg_ts;
2102 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2103 ZPOOL_CONFIG_LOAD_TIME, spa->spa_load_txg_ts) == 0);
2104 VERIFY(nvlist_add_int64(spa->spa_load_info,
2105 ZPOOL_CONFIG_REWIND_TIME, loss) == 0);
2106 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2107 ZPOOL_CONFIG_LOAD_DATA_ERRORS, sle.sle_data_count) == 0);
428870ff
BB
2108 } else {
2109 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg;
2110 }
2111
2112 if (error) {
2113 if (error != ENXIO && error != EIO)
2e528b49 2114 error = SET_ERROR(EIO);
428870ff
BB
2115 return (error);
2116 }
2117
2118 return (verify_ok ? 0 : EIO);
2119}
2120
2121/*
2122 * Find a value in the pool props object.
2123 */
2124static void
2125spa_prop_find(spa_t *spa, zpool_prop_t prop, uint64_t *val)
2126{
2127 (void) zap_lookup(spa->spa_meta_objset, spa->spa_pool_props_object,
2128 zpool_prop_to_name(prop), sizeof (uint64_t), 1, val);
2129}
2130
2131/*
2132 * Find a value in the pool directory object.
2133 */
2134static int
2135spa_dir_prop(spa_t *spa, const char *name, uint64_t *val)
2136{
2137 return (zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
2138 name, sizeof (uint64_t), 1, val));
2139}
2140
2141static int
2142spa_vdev_err(vdev_t *vdev, vdev_aux_t aux, int err)
2143{
2144 vdev_set_state(vdev, B_TRUE, VDEV_STATE_CANT_OPEN, aux);
2145 return (err);
2146}
2147
2148/*
2149 * Fix up config after a partly-completed split. This is done with the
2150 * ZPOOL_CONFIG_SPLIT nvlist. Both the splitting pool and the split-off
2151 * pool have that entry in their config, but only the splitting one contains
2152 * a list of all the guids of the vdevs that are being split off.
2153 *
2154 * This function determines what to do with that list: either rejoin
2155 * all the disks to the pool, or complete the splitting process. To attempt
2156 * the rejoin, each disk that is offlined is marked online again, and
2157 * we do a reopen() call. If the vdev label for every disk that was
2158 * marked online indicates it was successfully split off (VDEV_AUX_SPLIT_POOL)
2159 * then we call vdev_split() on each disk, and complete the split.
2160 *
2161 * Otherwise we leave the config alone, with all the vdevs in place in
2162 * the original pool.
2163 */
2164static void
2165spa_try_repair(spa_t *spa, nvlist_t *config)
2166{
2167 uint_t extracted;
2168 uint64_t *glist;
2169 uint_t i, gcount;
2170 nvlist_t *nvl;
2171 vdev_t **vd;
2172 boolean_t attempt_reopen;
2173
2174 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) != 0)
2175 return;
2176
2177 /* check that the config is complete */
2178 if (nvlist_lookup_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
2179 &glist, &gcount) != 0)
2180 return;
2181
79c76d5b 2182 vd = kmem_zalloc(gcount * sizeof (vdev_t *), KM_SLEEP);
428870ff
BB
2183
2184 /* attempt to online all the vdevs & validate */
2185 attempt_reopen = B_TRUE;
2186 for (i = 0; i < gcount; i++) {
2187 if (glist[i] == 0) /* vdev is hole */
2188 continue;
2189
2190 vd[i] = spa_lookup_by_guid(spa, glist[i], B_FALSE);
2191 if (vd[i] == NULL) {
2192 /*
2193 * Don't bother attempting to reopen the disks;
2194 * just do the split.
2195 */
2196 attempt_reopen = B_FALSE;
2197 } else {
2198 /* attempt to re-online it */
2199 vd[i]->vdev_offline = B_FALSE;
2200 }
2201 }
2202
2203 if (attempt_reopen) {
2204 vdev_reopen(spa->spa_root_vdev);
2205
2206 /* check each device to see what state it's in */
2207 for (extracted = 0, i = 0; i < gcount; i++) {
2208 if (vd[i] != NULL &&
2209 vd[i]->vdev_stat.vs_aux != VDEV_AUX_SPLIT_POOL)
2210 break;
2211 ++extracted;
2212 }
2213 }
2214
2215 /*
2216 * If every disk has been moved to the new pool, or if we never
2217 * even attempted to look at them, then we split them off for
2218 * good.
2219 */
2220 if (!attempt_reopen || gcount == extracted) {
2221 for (i = 0; i < gcount; i++)
2222 if (vd[i] != NULL)
2223 vdev_split(vd[i]);
2224 vdev_reopen(spa->spa_root_vdev);
2225 }
2226
2227 kmem_free(vd, gcount * sizeof (vdev_t *));
2228}
2229
2230static int
2231spa_load(spa_t *spa, spa_load_state_t state, spa_import_type_t type,
2232 boolean_t mosconfig)
2233{
2234 nvlist_t *config = spa->spa_config;
2235 char *ereport = FM_EREPORT_ZFS_POOL;
d96eb2b1 2236 char *comment;
428870ff
BB
2237 int error;
2238 uint64_t pool_guid;
2239 nvlist_t *nvl;
2240
2241 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid))
2e528b49 2242 return (SET_ERROR(EINVAL));
428870ff 2243
d96eb2b1
DM
2244 ASSERT(spa->spa_comment == NULL);
2245 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2246 spa->spa_comment = spa_strdup(comment);
2247
428870ff
BB
2248 /*
2249 * Versioning wasn't explicitly added to the label until later, so if
2250 * it's not present treat it as the initial version.
2251 */
2252 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
2253 &spa->spa_ubsync.ub_version) != 0)
2254 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
2255
2256 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
2257 &spa->spa_config_txg);
2258
2259 if ((state == SPA_LOAD_IMPORT || state == SPA_LOAD_TRYIMPORT) &&
2260 spa_guid_exists(pool_guid, 0)) {
2e528b49 2261 error = SET_ERROR(EEXIST);
428870ff 2262 } else {
3541dc6d 2263 spa->spa_config_guid = pool_guid;
428870ff
BB
2264
2265 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT,
2266 &nvl) == 0) {
2267 VERIFY(nvlist_dup(nvl, &spa->spa_config_splitting,
79c76d5b 2268 KM_SLEEP) == 0);
428870ff
BB
2269 }
2270
9ae529ec
CS
2271 nvlist_free(spa->spa_load_info);
2272 spa->spa_load_info = fnvlist_alloc();
2273
572e2857 2274 gethrestime(&spa->spa_loaded_ts);
428870ff
BB
2275 error = spa_load_impl(spa, pool_guid, config, state, type,
2276 mosconfig, &ereport);
2277 }
2278
0c66c32d
JG
2279 /*
2280 * Don't count references from objsets that are already closed
2281 * and are making their way through the eviction process.
2282 */
2283 spa_evicting_os_wait(spa);
428870ff 2284 spa->spa_minref = refcount_count(&spa->spa_refcount);
572e2857
BB
2285 if (error) {
2286 if (error != EEXIST) {
2287 spa->spa_loaded_ts.tv_sec = 0;
2288 spa->spa_loaded_ts.tv_nsec = 0;
2289 }
2290 if (error != EBADF) {
b5256303 2291 zfs_ereport_post(ereport, spa, NULL, NULL, NULL, 0, 0);
572e2857
BB
2292 }
2293 }
428870ff
BB
2294 spa->spa_load_state = error ? SPA_LOAD_ERROR : SPA_LOAD_NONE;
2295 spa->spa_ena = 0;
2296
2297 return (error);
2298}
2299
33cf67cd 2300#ifdef ZFS_DEBUG
e0ab3ab5
JS
2301/*
2302 * Count the number of per-vdev ZAPs associated with all of the vdevs in the
2303 * vdev tree rooted in the given vd, and ensure that each ZAP is present in the
2304 * spa's per-vdev ZAP list.
2305 */
2306static uint64_t
2307vdev_count_verify_zaps(vdev_t *vd)
2308{
2309 spa_t *spa = vd->vdev_spa;
2310 uint64_t total = 0;
e0ab3ab5
JS
2311
2312 if (vd->vdev_top_zap != 0) {
2313 total++;
2314 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2315 spa->spa_all_vdev_zaps, vd->vdev_top_zap));
2316 }
2317 if (vd->vdev_leaf_zap != 0) {
2318 total++;
2319 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2320 spa->spa_all_vdev_zaps, vd->vdev_leaf_zap));
2321 }
2322
1c27024e 2323 for (uint64_t i = 0; i < vd->vdev_children; i++) {
e0ab3ab5
JS
2324 total += vdev_count_verify_zaps(vd->vdev_child[i]);
2325 }
2326
2327 return (total);
2328}
33cf67cd 2329#endif
e0ab3ab5 2330
379ca9cf
OF
2331/*
2332 * Determine whether the activity check is required.
2333 */
2334static boolean_t
bbffb59e
BB
2335spa_activity_check_required(spa_t *spa, uberblock_t *ub, nvlist_t *label,
2336 nvlist_t *config)
379ca9cf
OF
2337{
2338 uint64_t state = 0;
2339 uint64_t hostid = 0;
2340 uint64_t tryconfig_txg = 0;
2341 uint64_t tryconfig_timestamp = 0;
2342 nvlist_t *nvinfo;
2343
2344 if (nvlist_exists(config, ZPOOL_CONFIG_LOAD_INFO)) {
2345 nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
2346 (void) nvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_MMP_TXG,
2347 &tryconfig_txg);
2348 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
2349 &tryconfig_timestamp);
2350 }
2351
2352 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE, &state);
379ca9cf
OF
2353
2354 /*
2355 * Disable the MMP activity check - This is used by zdb which
2356 * is intended to be used on potentially active pools.
2357 */
2358 if (spa->spa_import_flags & ZFS_IMPORT_SKIP_MMP)
2359 return (B_FALSE);
2360
2361 /*
2362 * Skip the activity check when the MMP feature is disabled.
2363 */
2364 if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay == 0)
2365 return (B_FALSE);
2366 /*
2367 * If the tryconfig_* values are nonzero, they are the results of an
2368 * earlier tryimport. If they match the uberblock we just found, then
2369 * the pool has not changed and we return false so we do not test a
2370 * second time.
2371 */
2372 if (tryconfig_txg && tryconfig_txg == ub->ub_txg &&
2373 tryconfig_timestamp && tryconfig_timestamp == ub->ub_timestamp)
2374 return (B_FALSE);
2375
2376 /*
2377 * Allow the activity check to be skipped when importing the pool
bbffb59e
BB
2378 * on the same host which last imported it. Since the hostid from
2379 * configuration may be stale use the one read from the label.
379ca9cf 2380 */
bbffb59e
BB
2381 if (nvlist_exists(label, ZPOOL_CONFIG_HOSTID))
2382 hostid = fnvlist_lookup_uint64(label, ZPOOL_CONFIG_HOSTID);
2383
379ca9cf
OF
2384 if (hostid == spa_get_hostid())
2385 return (B_FALSE);
2386
2387 /*
2388 * Skip the activity test when the pool was cleanly exported.
2389 */
2390 if (state != POOL_STATE_ACTIVE)
2391 return (B_FALSE);
2392
2393 return (B_TRUE);
2394}
2395
2396/*
2397 * Perform the import activity check. If the user canceled the import or
2398 * we detected activity then fail.
2399 */
2400static int
2401spa_activity_check(spa_t *spa, uberblock_t *ub, nvlist_t *config)
2402{
2403 uint64_t import_intervals = MAX(zfs_multihost_import_intervals, 1);
2404 uint64_t txg = ub->ub_txg;
2405 uint64_t timestamp = ub->ub_timestamp;
2406 uint64_t import_delay = NANOSEC;
2407 hrtime_t import_expire;
2408 nvlist_t *mmp_label = NULL;
2409 vdev_t *rvd = spa->spa_root_vdev;
2410 kcondvar_t cv;
2411 kmutex_t mtx;
2412 int error = 0;
2413
2414 cv_init(&cv, NULL, CV_DEFAULT, NULL);
2415 mutex_init(&mtx, NULL, MUTEX_DEFAULT, NULL);
2416 mutex_enter(&mtx);
2417
2418 /*
2419 * If ZPOOL_CONFIG_MMP_TXG is present an activity check was performed
2420 * during the earlier tryimport. If the txg recorded there is 0 then
2421 * the pool is known to be active on another host.
2422 *
2423 * Otherwise, the pool might be in use on another node. Check for
2424 * changes in the uberblocks on disk if necessary.
2425 */
2426 if (nvlist_exists(config, ZPOOL_CONFIG_LOAD_INFO)) {
2427 nvlist_t *nvinfo = fnvlist_lookup_nvlist(config,
2428 ZPOOL_CONFIG_LOAD_INFO);
2429
2430 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_TXG) &&
2431 fnvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_MMP_TXG) == 0) {
2432 vdev_uberblock_load(rvd, ub, &mmp_label);
2433 error = SET_ERROR(EREMOTEIO);
2434 goto out;
2435 }
2436 }
2437
2438 /*
2439 * Preferentially use the zfs_multihost_interval from the node which
2440 * last imported the pool. This value is stored in an MMP uberblock as.
2441 *
2442 * ub_mmp_delay * vdev_count_leaves() == zfs_multihost_interval
2443 */
2444 if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay)
2445 import_delay = MAX(import_delay, import_intervals *
802ae562 2446 ub->ub_mmp_delay * MAX(vdev_count_leaves(spa), 1));
379ca9cf
OF
2447
2448 /* Apply a floor using the local default values. */
2449 import_delay = MAX(import_delay, import_intervals *
2450 MSEC2NSEC(MAX(zfs_multihost_interval, MMP_MIN_INTERVAL)));
2451
2452 /* Add a small random factor in case of simultaneous imports (0-25%) */
2453 import_expire = gethrtime() + import_delay +
2454 (import_delay * spa_get_random(250) / 1000);
2455
2456 while (gethrtime() < import_expire) {
2457 vdev_uberblock_load(rvd, ub, &mmp_label);
2458
2459 if (txg != ub->ub_txg || timestamp != ub->ub_timestamp) {
2460 error = SET_ERROR(EREMOTEIO);
2461 break;
2462 }
2463
2464 if (mmp_label) {
2465 nvlist_free(mmp_label);
2466 mmp_label = NULL;
2467 }
2468
2469 error = cv_timedwait_sig(&cv, &mtx, ddi_get_lbolt() + hz);
2470 if (error != -1) {
2471 error = SET_ERROR(EINTR);
2472 break;
2473 }
2474 error = 0;
2475 }
2476
2477out:
2478 mutex_exit(&mtx);
2479 mutex_destroy(&mtx);
2480 cv_destroy(&cv);
2481
2482 /*
2483 * If the pool is determined to be active store the status in the
2484 * spa->spa_load_info nvlist. If the remote hostname or hostid are
2485 * available from configuration read from disk store them as well.
2486 * This allows 'zpool import' to generate a more useful message.
2487 *
2488 * ZPOOL_CONFIG_MMP_STATE - observed pool status (mandatory)
2489 * ZPOOL_CONFIG_MMP_HOSTNAME - hostname from the active pool
2490 * ZPOOL_CONFIG_MMP_HOSTID - hostid from the active pool
2491 */
2492 if (error == EREMOTEIO) {
2493 char *hostname = "<unknown>";
2494 uint64_t hostid = 0;
2495
2496 if (mmp_label) {
2497 if (nvlist_exists(mmp_label, ZPOOL_CONFIG_HOSTNAME)) {
2498 hostname = fnvlist_lookup_string(mmp_label,
2499 ZPOOL_CONFIG_HOSTNAME);
2500 fnvlist_add_string(spa->spa_load_info,
2501 ZPOOL_CONFIG_MMP_HOSTNAME, hostname);
2502 }
2503
2504 if (nvlist_exists(mmp_label, ZPOOL_CONFIG_HOSTID)) {
2505 hostid = fnvlist_lookup_uint64(mmp_label,
2506 ZPOOL_CONFIG_HOSTID);
2507 fnvlist_add_uint64(spa->spa_load_info,
2508 ZPOOL_CONFIG_MMP_HOSTID, hostid);
2509 }
2510 }
2511
2512 fnvlist_add_uint64(spa->spa_load_info,
2513 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_ACTIVE);
2514 fnvlist_add_uint64(spa->spa_load_info,
2515 ZPOOL_CONFIG_MMP_TXG, 0);
2516
2517 error = spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO);
2518 }
2519
2520 if (mmp_label)
2521 nvlist_free(mmp_label);
2522
2523 return (error);
2524}
2525
428870ff
BB
2526/*
2527 * Load an existing storage pool, using the pool's builtin spa_config as a
2528 * source of configuration information.
2529 */
bf701a83
BB
2530__attribute__((always_inline))
2531static inline int
428870ff
BB
2532spa_load_impl(spa_t *spa, uint64_t pool_guid, nvlist_t *config,
2533 spa_load_state_t state, spa_import_type_t type, boolean_t mosconfig,
2534 char **ereport)
2535{
2536 int error = 0;
2537 nvlist_t *nvroot = NULL;
9ae529ec 2538 nvlist_t *label;
428870ff
BB
2539 vdev_t *rvd;
2540 uberblock_t *ub = &spa->spa_uberblock;
572e2857 2541 uint64_t children, config_cache_txg = spa->spa_config_txg;
428870ff 2542 int orig_mode = spa->spa_mode;
1c27024e 2543 int parse;
428870ff 2544 uint64_t obj;
9ae529ec 2545 boolean_t missing_feat_write = B_FALSE;
379ca9cf 2546 boolean_t activity_check = B_FALSE;
428870ff
BB
2547
2548 /*
2549 * If this is an untrusted config, access the pool in read-only mode.
2550 * This prevents things like resilvering recently removed devices.
2551 */
2552 if (!mosconfig)
2553 spa->spa_mode = FREAD;
2554
2555 ASSERT(MUTEX_HELD(&spa_namespace_lock));
2556
2557 spa->spa_load_state = state;
2558
2559 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvroot))
2e528b49 2560 return (SET_ERROR(EINVAL));
428870ff
BB
2561
2562 parse = (type == SPA_IMPORT_EXISTING ?
2563 VDEV_ALLOC_LOAD : VDEV_ALLOC_SPLIT);
2564
2565 /*
2566 * Create "The Godfather" zio to hold all async IOs
2567 */
e022864d
MA
2568 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
2569 KM_SLEEP);
1c27024e 2570 for (int i = 0; i < max_ncpus; i++) {
e022864d
MA
2571 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
2572 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2573 ZIO_FLAG_GODFATHER);
2574 }
428870ff
BB
2575
2576 /*
2577 * Parse the configuration into a vdev tree. We explicitly set the
2578 * value that will be returned by spa_version() since parsing the
2579 * configuration requires knowing the version number.
2580 */
2581 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2582 error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, parse);
2583 spa_config_exit(spa, SCL_ALL, FTAG);
2584
2585 if (error != 0)
2586 return (error);
2587
2588 ASSERT(spa->spa_root_vdev == rvd);
c3520e7f
MA
2589 ASSERT3U(spa->spa_min_ashift, >=, SPA_MINBLOCKSHIFT);
2590 ASSERT3U(spa->spa_max_ashift, <=, SPA_MAXBLOCKSHIFT);
428870ff
BB
2591
2592 if (type != SPA_IMPORT_ASSEMBLE) {
2593 ASSERT(spa_guid(spa) == pool_guid);
2594 }
2595
2596 /*
2597 * Try to open all vdevs, loading each label in the process.
2598 */
2599 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2600 error = vdev_open(rvd);
2601 spa_config_exit(spa, SCL_ALL, FTAG);
2602 if (error != 0)
2603 return (error);
2604
2605 /*
2606 * We need to validate the vdev labels against the configuration that
2607 * we have in hand, which is dependent on the setting of mosconfig. If
2608 * mosconfig is true then we're validating the vdev labels based on
2609 * that config. Otherwise, we're validating against the cached config
2610 * (zpool.cache) that was read when we loaded the zfs module, and then
2611 * later we will recursively call spa_load() and validate against
2612 * the vdev config.
2613 *
2614 * If we're assembling a new pool that's been split off from an
2615 * existing pool, the labels haven't yet been updated so we skip
2616 * validation for now.
2617 */
2618 if (type != SPA_IMPORT_ASSEMBLE) {
2619 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
c7f2d69d 2620 error = vdev_validate(rvd, mosconfig);
428870ff
BB
2621 spa_config_exit(spa, SCL_ALL, FTAG);
2622
2623 if (error != 0)
2624 return (error);
2625
2626 if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN)
2e528b49 2627 return (SET_ERROR(ENXIO));
428870ff
BB
2628 }
2629
2630 /*
2631 * Find the best uberblock.
2632 */
9ae529ec 2633 vdev_uberblock_load(rvd, ub, &label);
428870ff
BB
2634
2635 /*
2636 * If we weren't able to find a single valid uberblock, return failure.
2637 */
9ae529ec
CS
2638 if (ub->ub_txg == 0) {
2639 nvlist_free(label);
428870ff 2640 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, ENXIO));
9ae529ec 2641 }
428870ff 2642
379ca9cf
OF
2643 /*
2644 * For pools which have the multihost property on determine if the
2645 * pool is truly inactive and can be safely imported. Prevent
2646 * hosts which don't have a hostid set from importing the pool.
2647 */
bbffb59e 2648 activity_check = spa_activity_check_required(spa, ub, label, config);
379ca9cf 2649 if (activity_check) {
379ca9cf
OF
2650 if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay &&
2651 spa_get_hostid() == 0) {
2652 nvlist_free(label);
2653 fnvlist_add_uint64(spa->spa_load_info,
2654 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_NO_HOSTID);
2655 return (spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO));
2656 }
2657
e889f0f5
OF
2658 error = spa_activity_check(spa, ub, config);
2659 if (error) {
2660 nvlist_free(label);
2661 return (error);
2662 }
2663
379ca9cf
OF
2664 fnvlist_add_uint64(spa->spa_load_info,
2665 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_INACTIVE);
2666 fnvlist_add_uint64(spa->spa_load_info,
2667 ZPOOL_CONFIG_MMP_TXG, ub->ub_txg);
2668 }
2669
428870ff 2670 /*
9ae529ec 2671 * If the pool has an unsupported version we can't open it.
428870ff 2672 */
9ae529ec
CS
2673 if (!SPA_VERSION_IS_SUPPORTED(ub->ub_version)) {
2674 nvlist_free(label);
428870ff 2675 return (spa_vdev_err(rvd, VDEV_AUX_VERSION_NEWER, ENOTSUP));
9ae529ec
CS
2676 }
2677
2678 if (ub->ub_version >= SPA_VERSION_FEATURES) {
2679 nvlist_t *features;
2680
2681 /*
2682 * If we weren't able to find what's necessary for reading the
2683 * MOS in the label, return failure.
2684 */
2685 if (label == NULL || nvlist_lookup_nvlist(label,
2686 ZPOOL_CONFIG_FEATURES_FOR_READ, &features) != 0) {
2687 nvlist_free(label);
2688 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2689 ENXIO));
2690 }
2691
2692 /*
2693 * Update our in-core representation with the definitive values
2694 * from the label.
2695 */
2696 nvlist_free(spa->spa_label_features);
2697 VERIFY(nvlist_dup(features, &spa->spa_label_features, 0) == 0);
2698 }
2699
2700 nvlist_free(label);
2701
2702 /*
2703 * Look through entries in the label nvlist's features_for_read. If
2704 * there is a feature listed there which we don't understand then we
2705 * cannot open a pool.
2706 */
2707 if (ub->ub_version >= SPA_VERSION_FEATURES) {
2708 nvlist_t *unsup_feat;
9ae529ec
CS
2709
2710 VERIFY(nvlist_alloc(&unsup_feat, NV_UNIQUE_NAME, KM_SLEEP) ==
2711 0);
2712
1c27024e
DB
2713 for (nvpair_t *nvp = nvlist_next_nvpair(spa->spa_label_features,
2714 NULL); nvp != NULL;
9ae529ec
CS
2715 nvp = nvlist_next_nvpair(spa->spa_label_features, nvp)) {
2716 if (!zfeature_is_supported(nvpair_name(nvp))) {
2717 VERIFY(nvlist_add_string(unsup_feat,
2718 nvpair_name(nvp), "") == 0);
2719 }
2720 }
2721
2722 if (!nvlist_empty(unsup_feat)) {
2723 VERIFY(nvlist_add_nvlist(spa->spa_load_info,
2724 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat) == 0);
2725 nvlist_free(unsup_feat);
2726 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
2727 ENOTSUP));
2728 }
2729
2730 nvlist_free(unsup_feat);
2731 }
428870ff
BB
2732
2733 /*
2734 * If the vdev guid sum doesn't match the uberblock, we have an
572e2857
BB
2735 * incomplete configuration. We first check to see if the pool
2736 * is aware of the complete config (i.e ZPOOL_CONFIG_VDEV_CHILDREN).
2737 * If it is, defer the vdev_guid_sum check till later so we
2738 * can handle missing vdevs.
428870ff 2739 */
572e2857
BB
2740 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VDEV_CHILDREN,
2741 &children) != 0 && mosconfig && type != SPA_IMPORT_ASSEMBLE &&
428870ff
BB
2742 rvd->vdev_guid_sum != ub->ub_guid_sum)
2743 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM, ENXIO));
2744
2745 if (type != SPA_IMPORT_ASSEMBLE && spa->spa_config_splitting) {
2746 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2747 spa_try_repair(spa, config);
2748 spa_config_exit(spa, SCL_ALL, FTAG);
2749 nvlist_free(spa->spa_config_splitting);
2750 spa->spa_config_splitting = NULL;
2751 }
2752
2753 /*
2754 * Initialize internal SPA structures.
2755 */
2756 spa->spa_state = POOL_STATE_ACTIVE;
2757 spa->spa_ubsync = spa->spa_uberblock;
2758 spa->spa_verify_min_txg = spa->spa_extreme_rewind ?
2759 TXG_INITIAL - 1 : spa_last_synced_txg(spa) - TXG_DEFER_SIZE - 1;
2760 spa->spa_first_txg = spa->spa_last_ubsync_txg ?
2761 spa->spa_last_ubsync_txg : spa_last_synced_txg(spa) + 1;
2762 spa->spa_claim_max_txg = spa->spa_first_txg;
2763 spa->spa_prev_software_version = ub->ub_software_version;
2764
9ae529ec 2765 error = dsl_pool_init(spa, spa->spa_first_txg, &spa->spa_dsl_pool);
428870ff
BB
2766 if (error)
2767 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2768 spa->spa_meta_objset = spa->spa_dsl_pool->dp_meta_objset;
2769
2770 if (spa_dir_prop(spa, DMU_POOL_CONFIG, &spa->spa_config_object) != 0)
2771 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2772
9ae529ec
CS
2773 if (spa_version(spa) >= SPA_VERSION_FEATURES) {
2774 boolean_t missing_feat_read = B_FALSE;
b9b24bb4 2775 nvlist_t *unsup_feat, *enabled_feat;
9ae529ec
CS
2776
2777 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_READ,
2778 &spa->spa_feat_for_read_obj) != 0) {
2779 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2780 }
2781
2782 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_WRITE,
2783 &spa->spa_feat_for_write_obj) != 0) {
2784 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2785 }
2786
2787 if (spa_dir_prop(spa, DMU_POOL_FEATURE_DESCRIPTIONS,
2788 &spa->spa_feat_desc_obj) != 0) {
2789 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2790 }
2791
b9b24bb4
CS
2792 enabled_feat = fnvlist_alloc();
2793 unsup_feat = fnvlist_alloc();
9ae529ec 2794
fa86b5db 2795 if (!spa_features_check(spa, B_FALSE,
b9b24bb4 2796 unsup_feat, enabled_feat))
9ae529ec
CS
2797 missing_feat_read = B_TRUE;
2798
2799 if (spa_writeable(spa) || state == SPA_LOAD_TRYIMPORT) {
fa86b5db 2800 if (!spa_features_check(spa, B_TRUE,
b9b24bb4 2801 unsup_feat, enabled_feat)) {
9ae529ec 2802 missing_feat_write = B_TRUE;
b9b24bb4 2803 }
9ae529ec
CS
2804 }
2805
b9b24bb4
CS
2806 fnvlist_add_nvlist(spa->spa_load_info,
2807 ZPOOL_CONFIG_ENABLED_FEAT, enabled_feat);
2808
9ae529ec 2809 if (!nvlist_empty(unsup_feat)) {
b9b24bb4
CS
2810 fnvlist_add_nvlist(spa->spa_load_info,
2811 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat);
9ae529ec
CS
2812 }
2813
b9b24bb4
CS
2814 fnvlist_free(enabled_feat);
2815 fnvlist_free(unsup_feat);
9ae529ec
CS
2816
2817 if (!missing_feat_read) {
2818 fnvlist_add_boolean(spa->spa_load_info,
2819 ZPOOL_CONFIG_CAN_RDONLY);
2820 }
2821
2822 /*
2823 * If the state is SPA_LOAD_TRYIMPORT, our objective is
2824 * twofold: to determine whether the pool is available for
2825 * import in read-write mode and (if it is not) whether the
2826 * pool is available for import in read-only mode. If the pool
2827 * is available for import in read-write mode, it is displayed
2828 * as available in userland; if it is not available for import
2829 * in read-only mode, it is displayed as unavailable in
2830 * userland. If the pool is available for import in read-only
2831 * mode but not read-write mode, it is displayed as unavailable
2832 * in userland with a special note that the pool is actually
2833 * available for open in read-only mode.
2834 *
2835 * As a result, if the state is SPA_LOAD_TRYIMPORT and we are
2836 * missing a feature for write, we must first determine whether
2837 * the pool can be opened read-only before returning to
2838 * userland in order to know whether to display the
2839 * abovementioned note.
2840 */
2841 if (missing_feat_read || (missing_feat_write &&
2842 spa_writeable(spa))) {
2843 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
2844 ENOTSUP));
2845 }
b0bc7a84
MG
2846
2847 /*
2848 * Load refcounts for ZFS features from disk into an in-memory
2849 * cache during SPA initialization.
2850 */
1c27024e 2851 for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
b0bc7a84
MG
2852 uint64_t refcount;
2853
2854 error = feature_get_refcount_from_disk(spa,
2855 &spa_feature_table[i], &refcount);
2856 if (error == 0) {
2857 spa->spa_feat_refcount_cache[i] = refcount;
2858 } else if (error == ENOTSUP) {
2859 spa->spa_feat_refcount_cache[i] =
2860 SPA_FEATURE_DISABLED;
2861 } else {
2862 return (spa_vdev_err(rvd,
2863 VDEV_AUX_CORRUPT_DATA, EIO));
2864 }
2865 }
2866 }
2867
2868 if (spa_feature_is_active(spa, SPA_FEATURE_ENABLED_TXG)) {
2869 if (spa_dir_prop(spa, DMU_POOL_FEATURE_ENABLED_TXG,
9b67f605 2870 &spa->spa_feat_enabled_txg_obj) != 0)
b0bc7a84 2871 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
9ae529ec
CS
2872 }
2873
2874 spa->spa_is_initializing = B_TRUE;
2875 error = dsl_pool_open(spa->spa_dsl_pool);
2876 spa->spa_is_initializing = B_FALSE;
2877 if (error != 0)
2878 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2879
428870ff
BB
2880 if (!mosconfig) {
2881 uint64_t hostid;
2882 nvlist_t *policy = NULL, *nvconfig;
2883
2884 if (load_nvlist(spa, spa->spa_config_object, &nvconfig) != 0)
2885 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2886
2887 if (!spa_is_root(spa) && nvlist_lookup_uint64(nvconfig,
b128c09f 2888 ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
34dc7c2f
BB
2889 char *hostname;
2890 unsigned long myhostid = 0;
2891
428870ff 2892 VERIFY(nvlist_lookup_string(nvconfig,
34dc7c2f
BB
2893 ZPOOL_CONFIG_HOSTNAME, &hostname) == 0);
2894
379ca9cf
OF
2895 myhostid = spa_get_hostid();
2896 if (hostid && myhostid && hostid != myhostid) {
428870ff 2897 nvlist_free(nvconfig);
2e528b49 2898 return (SET_ERROR(EBADF));
34dc7c2f
BB
2899 }
2900 }
428870ff
BB
2901 if (nvlist_lookup_nvlist(spa->spa_config,
2902 ZPOOL_REWIND_POLICY, &policy) == 0)
2903 VERIFY(nvlist_add_nvlist(nvconfig,
2904 ZPOOL_REWIND_POLICY, policy) == 0);
34dc7c2f 2905
428870ff 2906 spa_config_set(spa, nvconfig);
34dc7c2f
BB
2907 spa_unload(spa);
2908 spa_deactivate(spa);
fb5f0bc8 2909 spa_activate(spa, orig_mode);
34dc7c2f 2910
428870ff 2911 return (spa_load(spa, state, SPA_IMPORT_EXISTING, B_TRUE));
34dc7c2f
BB
2912 }
2913
3c67d83a
TH
2914 /* Grab the checksum salt from the MOS. */
2915 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
2916 DMU_POOL_CHECKSUM_SALT, 1,
2917 sizeof (spa->spa_cksum_salt.zcs_bytes),
2918 spa->spa_cksum_salt.zcs_bytes);
2919 if (error == ENOENT) {
2920 /* Generate a new salt for subsequent use */
2921 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
2922 sizeof (spa->spa_cksum_salt.zcs_bytes));
2923 } else if (error != 0) {
2924 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2925 }
2926
428870ff
BB
2927 if (spa_dir_prop(spa, DMU_POOL_SYNC_BPOBJ, &obj) != 0)
2928 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2929 error = bpobj_open(&spa->spa_deferred_bpobj, spa->spa_meta_objset, obj);
2930 if (error != 0)
2931 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
34dc7c2f
BB
2932
2933 /*
2934 * Load the bit that tells us to use the new accounting function
2935 * (raid-z deflation). If we have an older pool, this will not
2936 * be present.
2937 */
428870ff
BB
2938 error = spa_dir_prop(spa, DMU_POOL_DEFLATE, &spa->spa_deflate);
2939 if (error != 0 && error != ENOENT)
2940 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2941
2942 error = spa_dir_prop(spa, DMU_POOL_CREATION_VERSION,
2943 &spa->spa_creation_version);
2944 if (error != 0 && error != ENOENT)
2945 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
34dc7c2f
BB
2946
2947 /*
2948 * Load the persistent error log. If we have an older pool, this will
2949 * not be present.
2950 */
428870ff
BB
2951 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_LAST, &spa->spa_errlog_last);
2952 if (error != 0 && error != ENOENT)
2953 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
34dc7c2f 2954
428870ff
BB
2955 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_SCRUB,
2956 &spa->spa_errlog_scrub);
2957 if (error != 0 && error != ENOENT)
2958 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
34dc7c2f
BB
2959
2960 /*
2961 * Load the history object. If we have an older pool, this
2962 * will not be present.
2963 */
428870ff
BB
2964 error = spa_dir_prop(spa, DMU_POOL_HISTORY, &spa->spa_history);
2965 if (error != 0 && error != ENOENT)
2966 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2967
e0ab3ab5
JS
2968 /*
2969 * Load the per-vdev ZAP map. If we have an older pool, this will not
2970 * be present; in this case, defer its creation to a later time to
2971 * avoid dirtying the MOS this early / out of sync context. See
2972 * spa_sync_config_object.
2973 */
2974
2975 /* The sentinel is only available in the MOS config. */
1c27024e 2976 nvlist_t *mos_config;
e0ab3ab5
JS
2977 if (load_nvlist(spa, spa->spa_config_object, &mos_config) != 0)
2978 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2979
2980 error = spa_dir_prop(spa, DMU_POOL_VDEV_ZAP_MAP,
2981 &spa->spa_all_vdev_zaps);
2982
38640550
DB
2983 if (error == ENOENT) {
2984 VERIFY(!nvlist_exists(mos_config,
2985 ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
2986 spa->spa_avz_action = AVZ_ACTION_INITIALIZE;
2987 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
2988 } else if (error != 0) {
e0ab3ab5 2989 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
38640550 2990 } else if (!nvlist_exists(mos_config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS)) {
e0ab3ab5
JS
2991 /*
2992 * An older version of ZFS overwrote the sentinel value, so
2993 * we have orphaned per-vdev ZAPs in the MOS. Defer their
2994 * destruction to later; see spa_sync_config_object.
2995 */
2996 spa->spa_avz_action = AVZ_ACTION_DESTROY;
2997 /*
2998 * We're assuming that no vdevs have had their ZAPs created
2999 * before this. Better be sure of it.
3000 */
3001 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3002 }
3003 nvlist_free(mos_config);
3004
428870ff
BB
3005 /*
3006 * If we're assembling the pool from the split-off vdevs of
3007 * an existing pool, we don't want to attach the spares & cache
3008 * devices.
3009 */
34dc7c2f
BB
3010
3011 /*
3012 * Load any hot spares for this pool.
3013 */
428870ff
BB
3014 error = spa_dir_prop(spa, DMU_POOL_SPARES, &spa->spa_spares.sav_object);
3015 if (error != 0 && error != ENOENT)
3016 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3017 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
34dc7c2f
BB
3018 ASSERT(spa_version(spa) >= SPA_VERSION_SPARES);
3019 if (load_nvlist(spa, spa->spa_spares.sav_object,
428870ff
BB
3020 &spa->spa_spares.sav_config) != 0)
3021 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
34dc7c2f 3022
b128c09f 3023 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 3024 spa_load_spares(spa);
b128c09f 3025 spa_config_exit(spa, SCL_ALL, FTAG);
428870ff
BB
3026 } else if (error == 0) {
3027 spa->spa_spares.sav_sync = B_TRUE;
34dc7c2f
BB
3028 }
3029
3030 /*
3031 * Load any level 2 ARC devices for this pool.
3032 */
428870ff 3033 error = spa_dir_prop(spa, DMU_POOL_L2CACHE,
34dc7c2f 3034 &spa->spa_l2cache.sav_object);
428870ff
BB
3035 if (error != 0 && error != ENOENT)
3036 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3037 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
34dc7c2f
BB
3038 ASSERT(spa_version(spa) >= SPA_VERSION_L2CACHE);
3039 if (load_nvlist(spa, spa->spa_l2cache.sav_object,
428870ff
BB
3040 &spa->spa_l2cache.sav_config) != 0)
3041 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
34dc7c2f 3042
b128c09f 3043 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 3044 spa_load_l2cache(spa);
b128c09f 3045 spa_config_exit(spa, SCL_ALL, FTAG);
428870ff
BB
3046 } else if (error == 0) {
3047 spa->spa_l2cache.sav_sync = B_TRUE;
b128c09f
BB
3048 }
3049
34dc7c2f
BB
3050 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
3051
428870ff
BB
3052 error = spa_dir_prop(spa, DMU_POOL_PROPS, &spa->spa_pool_props_object);
3053 if (error && error != ENOENT)
3054 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
34dc7c2f
BB
3055
3056 if (error == 0) {
2dbedf54 3057 uint64_t autoreplace = 0;
428870ff
BB
3058
3059 spa_prop_find(spa, ZPOOL_PROP_BOOTFS, &spa->spa_bootfs);
3060 spa_prop_find(spa, ZPOOL_PROP_AUTOREPLACE, &autoreplace);
3061 spa_prop_find(spa, ZPOOL_PROP_DELEGATION, &spa->spa_delegation);
3062 spa_prop_find(spa, ZPOOL_PROP_FAILUREMODE, &spa->spa_failmode);
3063 spa_prop_find(spa, ZPOOL_PROP_AUTOEXPAND, &spa->spa_autoexpand);
379ca9cf 3064 spa_prop_find(spa, ZPOOL_PROP_MULTIHOST, &spa->spa_multihost);
428870ff
BB
3065 spa_prop_find(spa, ZPOOL_PROP_DEDUPDITTO,
3066 &spa->spa_dedup_ditto);
3067
3068 spa->spa_autoreplace = (autoreplace != 0);
34dc7c2f
BB
3069 }
3070
379ca9cf
OF
3071 /*
3072 * If the 'multihost' property is set, then never allow a pool to
3073 * be imported when the system hostid is zero. The exception to
3074 * this rule is zdb which is always allowed to access pools.
3075 */
3076 if (spa_multihost(spa) && spa_get_hostid() == 0 &&
3077 (spa->spa_import_flags & ZFS_IMPORT_SKIP_MMP) == 0) {
3078 fnvlist_add_uint64(spa->spa_load_info,
3079 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_NO_HOSTID);
3080 return (spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO));
3081 }
3082
34dc7c2f
BB
3083 /*
3084 * If the 'autoreplace' property is set, then post a resource notifying
3085 * the ZFS DE that it should not issue any faults for unopenable
3086 * devices. We also iterate over the vdevs, and post a sysevent for any
3087 * unopenable vdevs so that the normal autoreplace handler can take
3088 * over.
3089 */
428870ff 3090 if (spa->spa_autoreplace && state != SPA_LOAD_TRYIMPORT) {
34dc7c2f 3091 spa_check_removed(spa->spa_root_vdev);
428870ff
BB
3092 /*
3093 * For the import case, this is done in spa_import(), because
3094 * at this point we're using the spare definitions from
3095 * the MOS config, not necessarily from the userland config.
3096 */
3097 if (state != SPA_LOAD_IMPORT) {
3098 spa_aux_check_removed(&spa->spa_spares);
3099 spa_aux_check_removed(&spa->spa_l2cache);
3100 }
3101 }
34dc7c2f
BB
3102
3103 /*
3104 * Load the vdev state for all toplevel vdevs.
3105 */
3106 vdev_load(rvd);
3107
3108 /*
3109 * Propagate the leaf DTLs we just loaded all the way up the tree.
3110 */
b128c09f 3111 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 3112 vdev_dtl_reassess(rvd, 0, 0, B_FALSE);
b128c09f 3113 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f 3114
428870ff
BB
3115 /*
3116 * Load the DDTs (dedup tables).
3117 */
3118 error = ddt_load(spa);
3119 if (error != 0)
3120 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3121
3122 spa_update_dspace(spa);
3123
428870ff 3124 /*
572e2857
BB
3125 * Validate the config, using the MOS config to fill in any
3126 * information which might be missing. If we fail to validate
3127 * the config then declare the pool unfit for use. If we're
3128 * assembling a pool from a split, the log is not transferred
3129 * over.
428870ff
BB
3130 */
3131 if (type != SPA_IMPORT_ASSEMBLE) {
3132 nvlist_t *nvconfig;
3133
3134 if (load_nvlist(spa, spa->spa_config_object, &nvconfig) != 0)
3135 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3136
572e2857
BB
3137 if (!spa_config_valid(spa, nvconfig)) {
3138 nvlist_free(nvconfig);
3139 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM,
3140 ENXIO));
3141 }
428870ff
BB
3142 nvlist_free(nvconfig);
3143
572e2857 3144 /*
9ae529ec 3145 * Now that we've validated the config, check the state of the
572e2857
BB
3146 * root vdev. If it can't be opened, it indicates one or
3147 * more toplevel vdevs are faulted.
3148 */
3149 if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN)
2e528b49 3150 return (SET_ERROR(ENXIO));
572e2857 3151
36c6ffb6 3152 if (spa_writeable(spa) && spa_check_logs(spa)) {
428870ff
BB
3153 *ereport = FM_EREPORT_ZFS_LOG_REPLAY;
3154 return (spa_vdev_err(rvd, VDEV_AUX_BAD_LOG, ENXIO));
3155 }
3156 }
3157
9ae529ec
CS
3158 if (missing_feat_write) {
3159 ASSERT(state == SPA_LOAD_TRYIMPORT);
3160
3161 /*
3162 * At this point, we know that we can open the pool in
3163 * read-only mode but not read-write mode. We now have enough
3164 * information and can return to userland.
3165 */
3166 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT, ENOTSUP));
3167 }
3168
572e2857
BB
3169 /*
3170 * We've successfully opened the pool, verify that we're ready
3171 * to start pushing transactions.
3172 */
3173 if (state != SPA_LOAD_TRYIMPORT) {
c65aa5b2 3174 if ((error = spa_load_verify(spa)))
572e2857
BB
3175 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3176 error));
3177 }
3178
428870ff
BB
3179 if (spa_writeable(spa) && (state == SPA_LOAD_RECOVER ||
3180 spa->spa_load_max_txg == UINT64_MAX)) {
34dc7c2f
BB
3181 dmu_tx_t *tx;
3182 int need_update = B_FALSE;
9c43027b 3183 dsl_pool_t *dp = spa_get_dsl(spa);
fb5f0bc8
BB
3184
3185 ASSERT(state != SPA_LOAD_TRYIMPORT);
34dc7c2f
BB
3186
3187 /*
3188 * Claim log blocks that haven't been committed yet.
3189 * This must all happen in a single txg.
428870ff
BB
3190 * Note: spa_claim_max_txg is updated by spa_claim_notify(),
3191 * invoked from zil_claim_log_block()'s i/o done callback.
3192 * Price of rollback is that we abandon the log.
34dc7c2f 3193 */
428870ff
BB
3194 spa->spa_claiming = B_TRUE;
3195
9c43027b
AJ
3196 tx = dmu_tx_create_assigned(dp, spa_first_txg(spa));
3197 (void) dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
34dc7c2f
BB
3198 zil_claim, tx, DS_FIND_CHILDREN);
3199 dmu_tx_commit(tx);
3200
428870ff
BB
3201 spa->spa_claiming = B_FALSE;
3202
3203 spa_set_log_state(spa, SPA_LOG_GOOD);
34dc7c2f
BB
3204 spa->spa_sync_on = B_TRUE;
3205 txg_sync_start(spa->spa_dsl_pool);
379ca9cf 3206 mmp_thread_start(spa);
34dc7c2f
BB
3207
3208 /*
428870ff
BB
3209 * Wait for all claims to sync. We sync up to the highest
3210 * claimed log block birth time so that claimed log blocks
3211 * don't appear to be from the future. spa_claim_max_txg
3212 * will have been set for us by either zil_check_log_chain()
3213 * (invoked from spa_check_logs()) or zil_claim() above.
34dc7c2f 3214 */
428870ff 3215 txg_wait_synced(spa->spa_dsl_pool, spa->spa_claim_max_txg);
34dc7c2f
BB
3216
3217 /*
3218 * If the config cache is stale, or we have uninitialized
3219 * metaslabs (see spa_vdev_add()), then update the config.
45d1cae3 3220 *
572e2857 3221 * If this is a verbatim import, trust the current
45d1cae3 3222 * in-core spa_config and update the disk labels.
34dc7c2f
BB
3223 */
3224 if (config_cache_txg != spa->spa_config_txg ||
572e2857
BB
3225 state == SPA_LOAD_IMPORT ||
3226 state == SPA_LOAD_RECOVER ||
3227 (spa->spa_import_flags & ZFS_IMPORT_VERBATIM))
34dc7c2f
BB
3228 need_update = B_TRUE;
3229
1c27024e 3230 for (int c = 0; c < rvd->vdev_children; c++)
34dc7c2f
BB
3231 if (rvd->vdev_child[c]->vdev_ms_array == 0)
3232 need_update = B_TRUE;
3233
3234 /*
3235 * Update the config cache asychronously in case we're the
3236 * root pool, in which case the config cache isn't writable yet.
3237 */
3238 if (need_update)
3239 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
fb5f0bc8
BB
3240
3241 /*
3242 * Check all DTLs to see if anything needs resilvering.
3243 */
428870ff
BB
3244 if (!dsl_scan_resilvering(spa->spa_dsl_pool) &&
3245 vdev_resilver_needed(rvd, NULL, NULL))
fb5f0bc8 3246 spa_async_request(spa, SPA_ASYNC_RESILVER);
428870ff 3247
6f1ffb06
MA
3248 /*
3249 * Log the fact that we booted up (so that we can detect if
3250 * we rebooted in the middle of an operation).
3251 */
d5e024cb 3252 spa_history_log_version(spa, "open", NULL);
6f1ffb06 3253
428870ff
BB
3254 /*
3255 * Delete any inconsistent datasets.
3256 */
3257 (void) dmu_objset_find(spa_name(spa),
3258 dsl_destroy_inconsistent, NULL, DS_FIND_CHILDREN);
3259
3260 /*
3261 * Clean up any stale temporary dataset userrefs.
3262 */
3263 dsl_pool_clean_tmp_userrefs(spa->spa_dsl_pool);
34dc7c2f
BB
3264 }
3265
428870ff
BB
3266 return (0);
3267}
34dc7c2f 3268
428870ff
BB
3269static int
3270spa_load_retry(spa_t *spa, spa_load_state_t state, int mosconfig)
3271{
572e2857
BB
3272 int mode = spa->spa_mode;
3273
428870ff
BB
3274 spa_unload(spa);
3275 spa_deactivate(spa);
3276
dea377c0 3277 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg - 1;
428870ff 3278
572e2857 3279 spa_activate(spa, mode);
428870ff
BB
3280 spa_async_suspend(spa);
3281
3282 return (spa_load(spa, state, SPA_IMPORT_EXISTING, mosconfig));
3283}
3284
9ae529ec
CS
3285/*
3286 * If spa_load() fails this function will try loading prior txg's. If
3287 * 'state' is SPA_LOAD_RECOVER and one of these loads succeeds the pool
3288 * will be rewound to that txg. If 'state' is not SPA_LOAD_RECOVER this
3289 * function will not rewind the pool and will return the same error as
3290 * spa_load().
3291 */
428870ff
BB
3292static int
3293spa_load_best(spa_t *spa, spa_load_state_t state, int mosconfig,
3294 uint64_t max_request, int rewind_flags)
3295{
9ae529ec 3296 nvlist_t *loadinfo = NULL;
428870ff
BB
3297 nvlist_t *config = NULL;
3298 int load_error, rewind_error;
3299 uint64_t safe_rewind_txg;
3300 uint64_t min_txg;
3301
3302 if (spa->spa_load_txg && state == SPA_LOAD_RECOVER) {
3303 spa->spa_load_max_txg = spa->spa_load_txg;
3304 spa_set_log_state(spa, SPA_LOG_CLEAR);
3305 } else {
3306 spa->spa_load_max_txg = max_request;
dea377c0
MA
3307 if (max_request != UINT64_MAX)
3308 spa->spa_extreme_rewind = B_TRUE;
428870ff
BB
3309 }
3310
3311 load_error = rewind_error = spa_load(spa, state, SPA_IMPORT_EXISTING,
3312 mosconfig);
3313 if (load_error == 0)
3314 return (0);
3315
3316 if (spa->spa_root_vdev != NULL)
3317 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
3318
3319 spa->spa_last_ubsync_txg = spa->spa_uberblock.ub_txg;
3320 spa->spa_last_ubsync_txg_ts = spa->spa_uberblock.ub_timestamp;
3321
3322 if (rewind_flags & ZPOOL_NEVER_REWIND) {
3323 nvlist_free(config);
3324 return (load_error);
3325 }
3326
9ae529ec
CS
3327 if (state == SPA_LOAD_RECOVER) {
3328 /* Price of rolling back is discarding txgs, including log */
428870ff 3329 spa_set_log_state(spa, SPA_LOG_CLEAR);
9ae529ec
CS
3330 } else {
3331 /*
3332 * If we aren't rolling back save the load info from our first
3333 * import attempt so that we can restore it after attempting
3334 * to rewind.
3335 */
3336 loadinfo = spa->spa_load_info;
3337 spa->spa_load_info = fnvlist_alloc();
3338 }
428870ff
BB
3339
3340 spa->spa_load_max_txg = spa->spa_last_ubsync_txg;
3341 safe_rewind_txg = spa->spa_last_ubsync_txg - TXG_DEFER_SIZE;
3342 min_txg = (rewind_flags & ZPOOL_EXTREME_REWIND) ?
3343 TXG_INITIAL : safe_rewind_txg;
3344
3345 /*
3346 * Continue as long as we're finding errors, we're still within
3347 * the acceptable rewind range, and we're still finding uberblocks
3348 */
3349 while (rewind_error && spa->spa_uberblock.ub_txg >= min_txg &&
3350 spa->spa_uberblock.ub_txg <= spa->spa_load_max_txg) {
3351 if (spa->spa_load_max_txg < safe_rewind_txg)
3352 spa->spa_extreme_rewind = B_TRUE;
3353 rewind_error = spa_load_retry(spa, state, mosconfig);
3354 }
3355
428870ff
BB
3356 spa->spa_extreme_rewind = B_FALSE;
3357 spa->spa_load_max_txg = UINT64_MAX;
3358
3359 if (config && (rewind_error || state != SPA_LOAD_RECOVER))
3360 spa_config_set(spa, config);
ee6370a7 3361 else
3362 nvlist_free(config);
428870ff 3363
9ae529ec
CS
3364 if (state == SPA_LOAD_RECOVER) {
3365 ASSERT3P(loadinfo, ==, NULL);
3366 return (rewind_error);
3367 } else {
3368 /* Store the rewind info as part of the initial load info */
3369 fnvlist_add_nvlist(loadinfo, ZPOOL_CONFIG_REWIND_INFO,
3370 spa->spa_load_info);
3371
3372 /* Restore the initial load info */
3373 fnvlist_free(spa->spa_load_info);
3374 spa->spa_load_info = loadinfo;
3375
3376 return (load_error);
3377 }
34dc7c2f
BB
3378}
3379
3380/*
3381 * Pool Open/Import
3382 *
3383 * The import case is identical to an open except that the configuration is sent
3384 * down from userland, instead of grabbed from the configuration cache. For the
3385 * case of an open, the pool configuration will exist in the
3386 * POOL_STATE_UNINITIALIZED state.
3387 *
3388 * The stats information (gen/count/ustats) is used to gather vdev statistics at
3389 * the same time open the pool, without having to keep around the spa_t in some
3390 * ambiguous state.
3391 */
3392static int
428870ff
BB
3393spa_open_common(const char *pool, spa_t **spapp, void *tag, nvlist_t *nvpolicy,
3394 nvlist_t **config)
34dc7c2f
BB
3395{
3396 spa_t *spa;
572e2857 3397 spa_load_state_t state = SPA_LOAD_OPEN;
34dc7c2f 3398 int error;
34dc7c2f 3399 int locked = B_FALSE;
526af785 3400 int firstopen = B_FALSE;
34dc7c2f
BB
3401
3402 *spapp = NULL;
3403
3404 /*
3405 * As disgusting as this is, we need to support recursive calls to this
3406 * function because dsl_dir_open() is called during spa_load(), and ends
3407 * up calling spa_open() again. The real fix is to figure out how to
3408 * avoid dsl_dir_open() calling this in the first place.
3409 */
c25b8f99 3410 if (MUTEX_NOT_HELD(&spa_namespace_lock)) {
34dc7c2f
BB
3411 mutex_enter(&spa_namespace_lock);
3412 locked = B_TRUE;
3413 }
3414
3415 if ((spa = spa_lookup(pool)) == NULL) {
3416 if (locked)
3417 mutex_exit(&spa_namespace_lock);
2e528b49 3418 return (SET_ERROR(ENOENT));
34dc7c2f 3419 }
428870ff 3420
34dc7c2f 3421 if (spa->spa_state == POOL_STATE_UNINITIALIZED) {
428870ff
BB
3422 zpool_rewind_policy_t policy;
3423
526af785
PJD
3424 firstopen = B_TRUE;
3425
428870ff
BB
3426 zpool_get_rewind_policy(nvpolicy ? nvpolicy : spa->spa_config,
3427 &policy);
3428 if (policy.zrp_request & ZPOOL_DO_REWIND)
3429 state = SPA_LOAD_RECOVER;
34dc7c2f 3430
fb5f0bc8 3431 spa_activate(spa, spa_mode_global);
34dc7c2f 3432
428870ff
BB
3433 if (state != SPA_LOAD_RECOVER)
3434 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
3435
3436 error = spa_load_best(spa, state, B_FALSE, policy.zrp_txg,
3437 policy.zrp_request);
34dc7c2f
BB
3438
3439 if (error == EBADF) {
3440 /*
3441 * If vdev_validate() returns failure (indicated by
3442 * EBADF), it indicates that one of the vdevs indicates
3443 * that the pool has been exported or destroyed. If
3444 * this is the case, the config cache is out of sync and
3445 * we should remove the pool from the namespace.
3446 */
34dc7c2f
BB
3447 spa_unload(spa);
3448 spa_deactivate(spa);
b128c09f 3449 spa_config_sync(spa, B_TRUE, B_TRUE);
34dc7c2f 3450 spa_remove(spa);
34dc7c2f
BB
3451 if (locked)
3452 mutex_exit(&spa_namespace_lock);
2e528b49 3453 return (SET_ERROR(ENOENT));
34dc7c2f
BB
3454 }
3455
3456 if (error) {
3457 /*
3458 * We can't open the pool, but we still have useful
3459 * information: the state of each vdev after the
3460 * attempted vdev_open(). Return this to the user.
3461 */
572e2857 3462 if (config != NULL && spa->spa_config) {
428870ff 3463 VERIFY(nvlist_dup(spa->spa_config, config,
79c76d5b 3464 KM_SLEEP) == 0);
572e2857
BB
3465 VERIFY(nvlist_add_nvlist(*config,
3466 ZPOOL_CONFIG_LOAD_INFO,
3467 spa->spa_load_info) == 0);
3468 }
34dc7c2f
BB
3469 spa_unload(spa);
3470 spa_deactivate(spa);
428870ff 3471 spa->spa_last_open_failed = error;
34dc7c2f
BB
3472 if (locked)
3473 mutex_exit(&spa_namespace_lock);
3474 *spapp = NULL;
3475 return (error);
34dc7c2f 3476 }
34dc7c2f
BB
3477 }
3478
3479 spa_open_ref(spa, tag);
3480
b128c09f 3481 if (config != NULL)
34dc7c2f 3482 *config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
34dc7c2f 3483
572e2857
BB
3484 /*
3485 * If we've recovered the pool, pass back any information we
3486 * gathered while doing the load.
3487 */
3488 if (state == SPA_LOAD_RECOVER) {
3489 VERIFY(nvlist_add_nvlist(*config, ZPOOL_CONFIG_LOAD_INFO,
3490 spa->spa_load_info) == 0);
3491 }
3492
428870ff
BB
3493 if (locked) {
3494 spa->spa_last_open_failed = 0;
3495 spa->spa_last_ubsync_txg = 0;
3496 spa->spa_load_txg = 0;
3497 mutex_exit(&spa_namespace_lock);
3498 }
3499
526af785 3500 if (firstopen)
a0bd735a 3501 zvol_create_minors(spa, spa_name(spa), B_TRUE);
526af785 3502
428870ff
BB
3503 *spapp = spa;
3504
34dc7c2f
BB
3505 return (0);
3506}
3507
428870ff
BB
3508int
3509spa_open_rewind(const char *name, spa_t **spapp, void *tag, nvlist_t *policy,
3510 nvlist_t **config)
3511{
3512 return (spa_open_common(name, spapp, tag, policy, config));
3513}
3514
34dc7c2f
BB
3515int
3516spa_open(const char *name, spa_t **spapp, void *tag)
3517{
428870ff 3518 return (spa_open_common(name, spapp, tag, NULL, NULL));
34dc7c2f
BB
3519}
3520
3521/*
3522 * Lookup the given spa_t, incrementing the inject count in the process,
3523 * preventing it from being exported or destroyed.
3524 */
3525spa_t *
3526spa_inject_addref(char *name)
3527{
3528 spa_t *spa;
3529
3530 mutex_enter(&spa_namespace_lock);
3531 if ((spa = spa_lookup(name)) == NULL) {
3532 mutex_exit(&spa_namespace_lock);
3533 return (NULL);
3534 }
3535 spa->spa_inject_ref++;
3536 mutex_exit(&spa_namespace_lock);
3537
3538 return (spa);
3539}
3540
3541void
3542spa_inject_delref(spa_t *spa)
3543{
3544 mutex_enter(&spa_namespace_lock);
3545 spa->spa_inject_ref--;
3546 mutex_exit(&spa_namespace_lock);
3547}
3548
3549/*
3550 * Add spares device information to the nvlist.
3551 */
3552static void
3553spa_add_spares(spa_t *spa, nvlist_t *config)
3554{
3555 nvlist_t **spares;
3556 uint_t i, nspares;
3557 nvlist_t *nvroot;
3558 uint64_t guid;
3559 vdev_stat_t *vs;
3560 uint_t vsc;
3561 uint64_t pool;
3562
9babb374
BB
3563 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
3564
34dc7c2f
BB
3565 if (spa->spa_spares.sav_count == 0)
3566 return;
3567
3568 VERIFY(nvlist_lookup_nvlist(config,
3569 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
3570 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
3571 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
3572 if (nspares != 0) {
3573 VERIFY(nvlist_add_nvlist_array(nvroot,
3574 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
3575 VERIFY(nvlist_lookup_nvlist_array(nvroot,
3576 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
3577
3578 /*
3579 * Go through and find any spares which have since been
3580 * repurposed as an active spare. If this is the case, update
3581 * their status appropriately.
3582 */
3583 for (i = 0; i < nspares; i++) {
3584 VERIFY(nvlist_lookup_uint64(spares[i],
3585 ZPOOL_CONFIG_GUID, &guid) == 0);
b128c09f
BB
3586 if (spa_spare_exists(guid, &pool, NULL) &&
3587 pool != 0ULL) {
34dc7c2f 3588 VERIFY(nvlist_lookup_uint64_array(
428870ff 3589 spares[i], ZPOOL_CONFIG_VDEV_STATS,
34dc7c2f
BB
3590 (uint64_t **)&vs, &vsc) == 0);
3591 vs->vs_state = VDEV_STATE_CANT_OPEN;
3592 vs->vs_aux = VDEV_AUX_SPARED;
3593 }
3594 }
3595 }
3596}
3597
3598/*
3599 * Add l2cache device information to the nvlist, including vdev stats.
3600 */
3601static void
3602spa_add_l2cache(spa_t *spa, nvlist_t *config)
3603{
3604 nvlist_t **l2cache;
3605 uint_t i, j, nl2cache;
3606 nvlist_t *nvroot;
3607 uint64_t guid;
3608 vdev_t *vd;
3609 vdev_stat_t *vs;
3610 uint_t vsc;
3611
9babb374
BB
3612 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
3613
34dc7c2f
BB
3614 if (spa->spa_l2cache.sav_count == 0)
3615 return;
3616
34dc7c2f
BB
3617 VERIFY(nvlist_lookup_nvlist(config,
3618 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
3619 VERIFY(nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
3620 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
3621 if (nl2cache != 0) {
3622 VERIFY(nvlist_add_nvlist_array(nvroot,
3623 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
3624 VERIFY(nvlist_lookup_nvlist_array(nvroot,
3625 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
3626
3627 /*
3628 * Update level 2 cache device stats.
3629 */
3630
3631 for (i = 0; i < nl2cache; i++) {
3632 VERIFY(nvlist_lookup_uint64(l2cache[i],
3633 ZPOOL_CONFIG_GUID, &guid) == 0);
3634
3635 vd = NULL;
3636 for (j = 0; j < spa->spa_l2cache.sav_count; j++) {
3637 if (guid ==
3638 spa->spa_l2cache.sav_vdevs[j]->vdev_guid) {
3639 vd = spa->spa_l2cache.sav_vdevs[j];
3640 break;
3641 }
3642 }
3643 ASSERT(vd != NULL);
3644
3645 VERIFY(nvlist_lookup_uint64_array(l2cache[i],
428870ff
BB
3646 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc)
3647 == 0);
34dc7c2f 3648 vdev_get_stats(vd, vs);
193a37cb
TH
3649 vdev_config_generate_stats(vd, l2cache[i]);
3650
34dc7c2f
BB
3651 }
3652 }
34dc7c2f
BB
3653}
3654
9ae529ec 3655static void
417104bd 3656spa_feature_stats_from_disk(spa_t *spa, nvlist_t *features)
9ae529ec 3657{
9ae529ec
CS
3658 zap_cursor_t zc;
3659 zap_attribute_t za;
3660
9ae529ec
CS
3661 if (spa->spa_feat_for_read_obj != 0) {
3662 for (zap_cursor_init(&zc, spa->spa_meta_objset,
3663 spa->spa_feat_for_read_obj);
3664 zap_cursor_retrieve(&zc, &za) == 0;
3665 zap_cursor_advance(&zc)) {
3666 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
3667 za.za_num_integers == 1);
417104bd 3668 VERIFY0(nvlist_add_uint64(features, za.za_name,
9ae529ec
CS
3669 za.za_first_integer));
3670 }
3671 zap_cursor_fini(&zc);
3672 }
3673
3674 if (spa->spa_feat_for_write_obj != 0) {
3675 for (zap_cursor_init(&zc, spa->spa_meta_objset,
3676 spa->spa_feat_for_write_obj);
3677 zap_cursor_retrieve(&zc, &za) == 0;
3678 zap_cursor_advance(&zc)) {
3679 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
3680 za.za_num_integers == 1);
417104bd 3681 VERIFY0(nvlist_add_uint64(features, za.za_name,
9ae529ec
CS
3682 za.za_first_integer));
3683 }
3684 zap_cursor_fini(&zc);
3685 }
417104bd
NB
3686}
3687
3688static void
3689spa_feature_stats_from_cache(spa_t *spa, nvlist_t *features)
3690{
3691 int i;
3692
3693 for (i = 0; i < SPA_FEATURES; i++) {
3694 zfeature_info_t feature = spa_feature_table[i];
3695 uint64_t refcount;
3696
3697 if (feature_get_refcount(spa, &feature, &refcount) != 0)
3698 continue;
3699
3700 VERIFY0(nvlist_add_uint64(features, feature.fi_guid, refcount));
3701 }
3702}
3703
3704/*
3705 * Store a list of pool features and their reference counts in the
3706 * config.
3707 *
3708 * The first time this is called on a spa, allocate a new nvlist, fetch
3709 * the pool features and reference counts from disk, then save the list
3710 * in the spa. In subsequent calls on the same spa use the saved nvlist
3711 * and refresh its values from the cached reference counts. This
3712 * ensures we don't block here on I/O on a suspended pool so 'zpool
3713 * clear' can resume the pool.
3714 */
3715static void
3716spa_add_feature_stats(spa_t *spa, nvlist_t *config)
3717{
4eb30c68 3718 nvlist_t *features;
417104bd
NB
3719
3720 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
3721
4eb30c68
NB
3722 mutex_enter(&spa->spa_feat_stats_lock);
3723 features = spa->spa_feat_stats;
3724
417104bd
NB
3725 if (features != NULL) {
3726 spa_feature_stats_from_cache(spa, features);
3727 } else {
3728 VERIFY0(nvlist_alloc(&features, NV_UNIQUE_NAME, KM_SLEEP));
3729 spa->spa_feat_stats = features;
3730 spa_feature_stats_from_disk(spa, features);
3731 }
9ae529ec 3732
417104bd
NB
3733 VERIFY0(nvlist_add_nvlist(config, ZPOOL_CONFIG_FEATURE_STATS,
3734 features));
4eb30c68
NB
3735
3736 mutex_exit(&spa->spa_feat_stats_lock);
9ae529ec
CS
3737}
3738
34dc7c2f 3739int
9ae529ec
CS
3740spa_get_stats(const char *name, nvlist_t **config,
3741 char *altroot, size_t buflen)
34dc7c2f
BB
3742{
3743 int error;
3744 spa_t *spa;
3745
3746 *config = NULL;
428870ff 3747 error = spa_open_common(name, &spa, FTAG, NULL, config);
34dc7c2f 3748
9babb374
BB
3749 if (spa != NULL) {
3750 /*
3751 * This still leaves a window of inconsistency where the spares
3752 * or l2cache devices could change and the config would be
3753 * self-inconsistent.
3754 */
3755 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
34dc7c2f 3756
9babb374 3757 if (*config != NULL) {
572e2857
BB
3758 uint64_t loadtimes[2];
3759
3760 loadtimes[0] = spa->spa_loaded_ts.tv_sec;
3761 loadtimes[1] = spa->spa_loaded_ts.tv_nsec;
3762 VERIFY(nvlist_add_uint64_array(*config,
3763 ZPOOL_CONFIG_LOADED_TIME, loadtimes, 2) == 0);
3764
b128c09f 3765 VERIFY(nvlist_add_uint64(*config,
9babb374
BB
3766 ZPOOL_CONFIG_ERRCOUNT,
3767 spa_get_errlog_size(spa)) == 0);
3768
cec3a0a1 3769 if (spa_suspended(spa)) {
9babb374
BB
3770 VERIFY(nvlist_add_uint64(*config,
3771 ZPOOL_CONFIG_SUSPENDED,
3772 spa->spa_failmode) == 0);
cec3a0a1
OF
3773 VERIFY(nvlist_add_uint64(*config,
3774 ZPOOL_CONFIG_SUSPENDED_REASON,
3775 spa->spa_suspended) == 0);
3776 }
b128c09f 3777
9babb374
BB
3778 spa_add_spares(spa, *config);
3779 spa_add_l2cache(spa, *config);
9ae529ec 3780 spa_add_feature_stats(spa, *config);
9babb374 3781 }
34dc7c2f
BB
3782 }
3783
3784 /*
3785 * We want to get the alternate root even for faulted pools, so we cheat
3786 * and call spa_lookup() directly.
3787 */
3788 if (altroot) {
3789 if (spa == NULL) {
3790 mutex_enter(&spa_namespace_lock);
3791 spa = spa_lookup(name);
3792 if (spa)
3793 spa_altroot(spa, altroot, buflen);
3794 else
3795 altroot[0] = '\0';
3796 spa = NULL;
3797 mutex_exit(&spa_namespace_lock);
3798 } else {
3799 spa_altroot(spa, altroot, buflen);
3800 }
3801 }
3802
9babb374
BB
3803 if (spa != NULL) {
3804 spa_config_exit(spa, SCL_CONFIG, FTAG);
34dc7c2f 3805 spa_close(spa, FTAG);
9babb374 3806 }
34dc7c2f
BB
3807
3808 return (error);
3809}
3810
3811/*
3812 * Validate that the auxiliary device array is well formed. We must have an
3813 * array of nvlists, each which describes a valid leaf vdev. If this is an
3814 * import (mode is VDEV_ALLOC_SPARE), then we allow corrupted spares to be
3815 * specified, as long as they are well-formed.
3816 */
3817static int
3818spa_validate_aux_devs(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode,
3819 spa_aux_vdev_t *sav, const char *config, uint64_t version,
3820 vdev_labeltype_t label)
3821{
3822 nvlist_t **dev;
3823 uint_t i, ndev;
3824 vdev_t *vd;
3825 int error;
3826
b128c09f
BB
3827 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
3828
34dc7c2f
BB
3829 /*
3830 * It's acceptable to have no devs specified.
3831 */
3832 if (nvlist_lookup_nvlist_array(nvroot, config, &dev, &ndev) != 0)
3833 return (0);
3834
3835 if (ndev == 0)
2e528b49 3836 return (SET_ERROR(EINVAL));
34dc7c2f
BB
3837
3838 /*
3839 * Make sure the pool is formatted with a version that supports this
3840 * device type.
3841 */
3842 if (spa_version(spa) < version)
2e528b49 3843 return (SET_ERROR(ENOTSUP));
34dc7c2f
BB
3844
3845 /*
3846 * Set the pending device list so we correctly handle device in-use
3847 * checking.
3848 */
3849 sav->sav_pending = dev;
3850 sav->sav_npending = ndev;
3851
3852 for (i = 0; i < ndev; i++) {
3853 if ((error = spa_config_parse(spa, &vd, dev[i], NULL, 0,
3854 mode)) != 0)
3855 goto out;
3856
3857 if (!vd->vdev_ops->vdev_op_leaf) {
3858 vdev_free(vd);
2e528b49 3859 error = SET_ERROR(EINVAL);
34dc7c2f
BB
3860 goto out;
3861 }
3862
34dc7c2f
BB
3863 vd->vdev_top = vd;
3864
3865 if ((error = vdev_open(vd)) == 0 &&
3866 (error = vdev_label_init(vd, crtxg, label)) == 0) {
3867 VERIFY(nvlist_add_uint64(dev[i], ZPOOL_CONFIG_GUID,
3868 vd->vdev_guid) == 0);
3869 }
3870
3871 vdev_free(vd);
3872
3873 if (error &&
3874 (mode != VDEV_ALLOC_SPARE && mode != VDEV_ALLOC_L2CACHE))
3875 goto out;
3876 else
3877 error = 0;
3878 }
3879
3880out:
3881 sav->sav_pending = NULL;
3882 sav->sav_npending = 0;
3883 return (error);
3884}
3885
3886static int
3887spa_validate_aux(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode)
3888{
3889 int error;
3890
b128c09f
BB
3891 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
3892
34dc7c2f
BB
3893 if ((error = spa_validate_aux_devs(spa, nvroot, crtxg, mode,
3894 &spa->spa_spares, ZPOOL_CONFIG_SPARES, SPA_VERSION_SPARES,
3895 VDEV_LABEL_SPARE)) != 0) {
3896 return (error);
3897 }
3898
3899 return (spa_validate_aux_devs(spa, nvroot, crtxg, mode,
3900 &spa->spa_l2cache, ZPOOL_CONFIG_L2CACHE, SPA_VERSION_L2CACHE,
3901 VDEV_LABEL_L2CACHE));
3902}
3903
3904static void
3905spa_set_aux_vdevs(spa_aux_vdev_t *sav, nvlist_t **devs, int ndevs,
3906 const char *config)
3907{
3908 int i;
3909
3910 if (sav->sav_config != NULL) {
3911 nvlist_t **olddevs;
3912 uint_t oldndevs;
3913 nvlist_t **newdevs;
3914
3915 /*
4e33ba4c 3916 * Generate new dev list by concatenating with the
34dc7c2f
BB
3917 * current dev list.
3918 */
3919 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config, config,
3920 &olddevs, &oldndevs) == 0);
3921
3922 newdevs = kmem_alloc(sizeof (void *) *
79c76d5b 3923 (ndevs + oldndevs), KM_SLEEP);
34dc7c2f
BB
3924 for (i = 0; i < oldndevs; i++)
3925 VERIFY(nvlist_dup(olddevs[i], &newdevs[i],
79c76d5b 3926 KM_SLEEP) == 0);
34dc7c2f
BB
3927 for (i = 0; i < ndevs; i++)
3928 VERIFY(nvlist_dup(devs[i], &newdevs[i + oldndevs],
79c76d5b 3929 KM_SLEEP) == 0);
34dc7c2f
BB
3930
3931 VERIFY(nvlist_remove(sav->sav_config, config,
3932 DATA_TYPE_NVLIST_ARRAY) == 0);
3933
3934 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
3935 config, newdevs, ndevs + oldndevs) == 0);
3936 for (i = 0; i < oldndevs + ndevs; i++)
3937 nvlist_free(newdevs[i]);
3938 kmem_free(newdevs, (oldndevs + ndevs) * sizeof (void *));
3939 } else {
3940 /*
3941 * Generate a new dev list.
3942 */
3943 VERIFY(nvlist_alloc(&sav->sav_config, NV_UNIQUE_NAME,
79c76d5b 3944 KM_SLEEP) == 0);
34dc7c2f
BB
3945 VERIFY(nvlist_add_nvlist_array(sav->sav_config, config,
3946 devs, ndevs) == 0);
3947 }
3948}
3949
3950/*
3951 * Stop and drop level 2 ARC devices
3952 */
3953void
3954spa_l2cache_drop(spa_t *spa)
3955{
3956 vdev_t *vd;
3957 int i;
3958 spa_aux_vdev_t *sav = &spa->spa_l2cache;
3959
3960 for (i = 0; i < sav->sav_count; i++) {
3961 uint64_t pool;
3962
3963 vd = sav->sav_vdevs[i];
3964 ASSERT(vd != NULL);
3965
fb5f0bc8
BB
3966 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
3967 pool != 0ULL && l2arc_vdev_present(vd))
34dc7c2f 3968 l2arc_remove_vdev(vd);
34dc7c2f
BB
3969 }
3970}
3971
b5256303
TC
3972/*
3973 * Verify encryption parameters for spa creation. If we are encrypting, we must
3974 * have the encryption feature flag enabled.
3975 */
3976static int
3977spa_create_check_encryption_params(dsl_crypto_params_t *dcp,
3978 boolean_t has_encryption)
3979{
3980 if (dcp->cp_crypt != ZIO_CRYPT_OFF &&
3981 dcp->cp_crypt != ZIO_CRYPT_INHERIT &&
3982 !has_encryption)
3983 return (SET_ERROR(ENOTSUP));
3984
3985 return (dmu_objset_create_crypt_check(NULL, dcp));
3986}
3987
34dc7c2f
BB
3988/*
3989 * Pool Creation
3990 */
3991int
3992spa_create(const char *pool, nvlist_t *nvroot, nvlist_t *props,
b5256303 3993 nvlist_t *zplprops, dsl_crypto_params_t *dcp)
34dc7c2f
BB
3994{
3995 spa_t *spa;
3996 char *altroot = NULL;
3997 vdev_t *rvd;
3998 dsl_pool_t *dp;
3999 dmu_tx_t *tx;
9babb374 4000 int error = 0;
34dc7c2f
BB
4001 uint64_t txg = TXG_INITIAL;
4002 nvlist_t **spares, **l2cache;
4003 uint_t nspares, nl2cache;
b5256303 4004 uint64_t version, obj, root_dsobj = 0;
9ae529ec 4005 boolean_t has_features;
b5256303
TC
4006 boolean_t has_encryption;
4007 spa_feature_t feat;
4008 char *feat_name;
83e9986f
RY
4009 char *poolname;
4010 nvlist_t *nvl;
4011
4012 if (nvlist_lookup_string(props, "tname", &poolname) != 0)
4013 poolname = (char *)pool;
34dc7c2f
BB
4014
4015 /*
4016 * If this pool already exists, return failure.
4017 */
4018 mutex_enter(&spa_namespace_lock);
83e9986f 4019 if (spa_lookup(poolname) != NULL) {
34dc7c2f 4020 mutex_exit(&spa_namespace_lock);
2e528b49 4021 return (SET_ERROR(EEXIST));
34dc7c2f
BB
4022 }
4023
4024 /*
4025 * Allocate a new spa_t structure.
4026 */
83e9986f
RY
4027 nvl = fnvlist_alloc();
4028 fnvlist_add_string(nvl, ZPOOL_CONFIG_POOL_NAME, pool);
34dc7c2f
BB
4029 (void) nvlist_lookup_string(props,
4030 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
83e9986f
RY
4031 spa = spa_add(poolname, nvl, altroot);
4032 fnvlist_free(nvl);
fb5f0bc8 4033 spa_activate(spa, spa_mode_global);
34dc7c2f 4034
34dc7c2f 4035 if (props && (error = spa_prop_validate(spa, props))) {
34dc7c2f
BB
4036 spa_deactivate(spa);
4037 spa_remove(spa);
b128c09f 4038 mutex_exit(&spa_namespace_lock);
34dc7c2f
BB
4039 return (error);
4040 }
4041
83e9986f
RY
4042 /*
4043 * Temporary pool names should never be written to disk.
4044 */
4045 if (poolname != pool)
4046 spa->spa_import_flags |= ZFS_IMPORT_TEMP_NAME;
4047
9ae529ec 4048 has_features = B_FALSE;
b5256303 4049 has_encryption = B_FALSE;
1c27024e 4050 for (nvpair_t *elem = nvlist_next_nvpair(props, NULL);
9ae529ec 4051 elem != NULL; elem = nvlist_next_nvpair(props, elem)) {
b5256303 4052 if (zpool_prop_feature(nvpair_name(elem))) {
9ae529ec 4053 has_features = B_TRUE;
b5256303
TC
4054
4055 feat_name = strchr(nvpair_name(elem), '@') + 1;
4056 VERIFY0(zfeature_lookup_name(feat_name, &feat));
4057 if (feat == SPA_FEATURE_ENCRYPTION)
4058 has_encryption = B_TRUE;
4059 }
4060 }
4061
4062 /* verify encryption params, if they were provided */
4063 if (dcp != NULL) {
4064 error = spa_create_check_encryption_params(dcp, has_encryption);
4065 if (error != 0) {
4066 spa_deactivate(spa);
4067 spa_remove(spa);
4068 mutex_exit(&spa_namespace_lock);
4069 return (error);
4070 }
9ae529ec
CS
4071 }
4072
4073 if (has_features || nvlist_lookup_uint64(props,
4074 zpool_prop_to_name(ZPOOL_PROP_VERSION), &version) != 0) {
34dc7c2f 4075 version = SPA_VERSION;
9ae529ec
CS
4076 }
4077 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
428870ff
BB
4078
4079 spa->spa_first_txg = txg;
4080 spa->spa_uberblock.ub_txg = txg - 1;
34dc7c2f
BB
4081 spa->spa_uberblock.ub_version = version;
4082 spa->spa_ubsync = spa->spa_uberblock;
3dfb57a3 4083 spa->spa_load_state = SPA_LOAD_CREATE;
34dc7c2f 4084
9babb374
BB
4085 /*
4086 * Create "The Godfather" zio to hold all async IOs
4087 */
e022864d
MA
4088 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
4089 KM_SLEEP);
1c27024e 4090 for (int i = 0; i < max_ncpus; i++) {
e022864d
MA
4091 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
4092 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
4093 ZIO_FLAG_GODFATHER);
4094 }
9babb374 4095
34dc7c2f
BB
4096 /*
4097 * Create the root vdev.
4098 */
b128c09f 4099 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f
BB
4100
4101 error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, VDEV_ALLOC_ADD);
4102
4103 ASSERT(error != 0 || rvd != NULL);
4104 ASSERT(error != 0 || spa->spa_root_vdev == rvd);
4105
4106 if (error == 0 && !zfs_allocatable_devs(nvroot))
2e528b49 4107 error = SET_ERROR(EINVAL);
34dc7c2f
BB
4108
4109 if (error == 0 &&
4110 (error = vdev_create(rvd, txg, B_FALSE)) == 0 &&
4111 (error = spa_validate_aux(spa, nvroot, txg,
4112 VDEV_ALLOC_ADD)) == 0) {
1c27024e 4113 for (int c = 0; c < rvd->vdev_children; c++) {
9babb374
BB
4114 vdev_metaslab_set_size(rvd->vdev_child[c]);
4115 vdev_expand(rvd->vdev_child[c], txg);
4116 }
34dc7c2f
BB
4117 }
4118
b128c09f 4119 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
4120
4121 if (error != 0) {
4122 spa_unload(spa);
4123 spa_deactivate(spa);
4124 spa_remove(spa);
4125 mutex_exit(&spa_namespace_lock);
4126 return (error);
4127 }
4128
4129 /*
4130 * Get the list of spares, if specified.
4131 */
4132 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
4133 &spares, &nspares) == 0) {
4134 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config, NV_UNIQUE_NAME,
79c76d5b 4135 KM_SLEEP) == 0);
34dc7c2f
BB
4136 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
4137 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
b128c09f 4138 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 4139 spa_load_spares(spa);
b128c09f 4140 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
4141 spa->spa_spares.sav_sync = B_TRUE;
4142 }
4143
4144 /*
4145 * Get the list of level 2 cache devices, if specified.
4146 */
4147 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
4148 &l2cache, &nl2cache) == 0) {
4149 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
79c76d5b 4150 NV_UNIQUE_NAME, KM_SLEEP) == 0);
34dc7c2f
BB
4151 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
4152 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
b128c09f 4153 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 4154 spa_load_l2cache(spa);
b128c09f 4155 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
4156 spa->spa_l2cache.sav_sync = B_TRUE;
4157 }
4158
9ae529ec 4159 spa->spa_is_initializing = B_TRUE;
b5256303 4160 spa->spa_dsl_pool = dp = dsl_pool_create(spa, zplprops, dcp, txg);
9ae529ec 4161 spa->spa_is_initializing = B_FALSE;
34dc7c2f 4162
428870ff
BB
4163 /*
4164 * Create DDTs (dedup tables).
4165 */
4166 ddt_create(spa);
4167
4168 spa_update_dspace(spa);
4169
34dc7c2f
BB
4170 tx = dmu_tx_create_assigned(dp, txg);
4171
d5e024cb
BB
4172 /*
4173 * Create the pool's history object.
4174 */
4175 if (version >= SPA_VERSION_ZPOOL_HISTORY && !spa->spa_history)
4176 spa_history_create_obj(spa, tx);
4177
4178 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_CREATE);
4179 spa_history_log_version(spa, "create", tx);
4180
34dc7c2f
BB
4181 /*
4182 * Create the pool config object.
4183 */
4184 spa->spa_config_object = dmu_object_alloc(spa->spa_meta_objset,
b128c09f 4185 DMU_OT_PACKED_NVLIST, SPA_CONFIG_BLOCKSIZE,
34dc7c2f
BB
4186 DMU_OT_PACKED_NVLIST_SIZE, sizeof (uint64_t), tx);
4187
4188 if (zap_add(spa->spa_meta_objset,
4189 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CONFIG,
4190 sizeof (uint64_t), 1, &spa->spa_config_object, tx) != 0) {
4191 cmn_err(CE_PANIC, "failed to add pool config");
4192 }
4193
428870ff
BB
4194 if (zap_add(spa->spa_meta_objset,
4195 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CREATION_VERSION,
4196 sizeof (uint64_t), 1, &version, tx) != 0) {
4197 cmn_err(CE_PANIC, "failed to add pool version");
4198 }
4199
34dc7c2f
BB
4200 /* Newly created pools with the right version are always deflated. */
4201 if (version >= SPA_VERSION_RAIDZ_DEFLATE) {
4202 spa->spa_deflate = TRUE;
4203 if (zap_add(spa->spa_meta_objset,
4204 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
4205 sizeof (uint64_t), 1, &spa->spa_deflate, tx) != 0) {
4206 cmn_err(CE_PANIC, "failed to add deflate");
4207 }
4208 }
4209
4210 /*
428870ff 4211 * Create the deferred-free bpobj. Turn off compression
34dc7c2f
BB
4212 * because sync-to-convergence takes longer if the blocksize
4213 * keeps changing.
4214 */
428870ff
BB
4215 obj = bpobj_alloc(spa->spa_meta_objset, 1 << 14, tx);
4216 dmu_object_set_compress(spa->spa_meta_objset, obj,
34dc7c2f 4217 ZIO_COMPRESS_OFF, tx);
34dc7c2f 4218 if (zap_add(spa->spa_meta_objset,
428870ff
BB
4219 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SYNC_BPOBJ,
4220 sizeof (uint64_t), 1, &obj, tx) != 0) {
4221 cmn_err(CE_PANIC, "failed to add bpobj");
34dc7c2f 4222 }
428870ff
BB
4223 VERIFY3U(0, ==, bpobj_open(&spa->spa_deferred_bpobj,
4224 spa->spa_meta_objset, obj));
34dc7c2f 4225
3c67d83a
TH
4226 /*
4227 * Generate some random noise for salted checksums to operate on.
4228 */
4229 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
4230 sizeof (spa->spa_cksum_salt.zcs_bytes));
4231
34dc7c2f
BB
4232 /*
4233 * Set pool properties.
4234 */
4235 spa->spa_bootfs = zpool_prop_default_numeric(ZPOOL_PROP_BOOTFS);
4236 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
4237 spa->spa_failmode = zpool_prop_default_numeric(ZPOOL_PROP_FAILUREMODE);
9babb374 4238 spa->spa_autoexpand = zpool_prop_default_numeric(ZPOOL_PROP_AUTOEXPAND);
379ca9cf 4239 spa->spa_multihost = zpool_prop_default_numeric(ZPOOL_PROP_MULTIHOST);
428870ff 4240
d164b209
BB
4241 if (props != NULL) {
4242 spa_configfile_set(spa, props, B_FALSE);
13fe0198 4243 spa_sync_props(props, tx);
d164b209 4244 }
34dc7c2f
BB
4245
4246 dmu_tx_commit(tx);
4247
b5256303
TC
4248 /*
4249 * If the root dataset is encrypted we will need to create key mappings
4250 * for the zio layer before we start to write any data to disk and hold
4251 * them until after the first txg has been synced. Waiting for the first
4252 * transaction to complete also ensures that our bean counters are
4253 * appropriately updated.
4254 */
4255 if (dp->dp_root_dir->dd_crypto_obj != 0) {
4256 root_dsobj = dsl_dir_phys(dp->dp_root_dir)->dd_head_dataset_obj;
4257 VERIFY0(spa_keystore_create_mapping_impl(spa, root_dsobj,
4258 dp->dp_root_dir, FTAG));
4259 }
4260
34dc7c2f 4261 spa->spa_sync_on = B_TRUE;
b5256303 4262 txg_sync_start(dp);
379ca9cf 4263 mmp_thread_start(spa);
b5256303 4264 txg_wait_synced(dp, txg);
34dc7c2f 4265
b5256303
TC
4266 if (dp->dp_root_dir->dd_crypto_obj != 0)
4267 VERIFY0(spa_keystore_remove_mapping(spa, root_dsobj, FTAG));
34dc7c2f 4268
b128c09f 4269 spa_config_sync(spa, B_FALSE, B_TRUE);
34dc7c2f 4270
0c66c32d
JG
4271 /*
4272 * Don't count references from objsets that are already closed
4273 * and are making their way through the eviction process.
4274 */
4275 spa_evicting_os_wait(spa);
b128c09f 4276 spa->spa_minref = refcount_count(&spa->spa_refcount);
3dfb57a3 4277 spa->spa_load_state = SPA_LOAD_NONE;
b128c09f 4278
d164b209
BB
4279 mutex_exit(&spa_namespace_lock);
4280
34dc7c2f
BB
4281 return (0);
4282}
4283
9babb374
BB
4284/*
4285 * Import a non-root pool into the system.
4286 */
4287int
13fe0198 4288spa_import(char *pool, nvlist_t *config, nvlist_t *props, uint64_t flags)
34dc7c2f
BB
4289{
4290 spa_t *spa;
4291 char *altroot = NULL;
428870ff
BB
4292 spa_load_state_t state = SPA_LOAD_IMPORT;
4293 zpool_rewind_policy_t policy;
572e2857
BB
4294 uint64_t mode = spa_mode_global;
4295 uint64_t readonly = B_FALSE;
9babb374 4296 int error;
34dc7c2f
BB
4297 nvlist_t *nvroot;
4298 nvlist_t **spares, **l2cache;
4299 uint_t nspares, nl2cache;
34dc7c2f
BB
4300
4301 /*
4302 * If a pool with this name exists, return failure.
4303 */
4304 mutex_enter(&spa_namespace_lock);
428870ff 4305 if (spa_lookup(pool) != NULL) {
9babb374 4306 mutex_exit(&spa_namespace_lock);
2e528b49 4307 return (SET_ERROR(EEXIST));
34dc7c2f
BB
4308 }
4309
4310 /*
4311 * Create and initialize the spa structure.
4312 */
4313 (void) nvlist_lookup_string(props,
4314 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
572e2857
BB
4315 (void) nvlist_lookup_uint64(props,
4316 zpool_prop_to_name(ZPOOL_PROP_READONLY), &readonly);
4317 if (readonly)
4318 mode = FREAD;
428870ff 4319 spa = spa_add(pool, config, altroot);
572e2857
BB
4320 spa->spa_import_flags = flags;
4321
4322 /*
4323 * Verbatim import - Take a pool and insert it into the namespace
4324 * as if it had been loaded at boot.
4325 */
4326 if (spa->spa_import_flags & ZFS_IMPORT_VERBATIM) {
4327 if (props != NULL)
4328 spa_configfile_set(spa, props, B_FALSE);
4329
4330 spa_config_sync(spa, B_FALSE, B_TRUE);
12fa0466 4331 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
572e2857
BB
4332
4333 mutex_exit(&spa_namespace_lock);
572e2857
BB
4334 return (0);
4335 }
4336
4337 spa_activate(spa, mode);
34dc7c2f 4338
9babb374
BB
4339 /*
4340 * Don't start async tasks until we know everything is healthy.
4341 */
4342 spa_async_suspend(spa);
b128c09f 4343
572e2857
BB
4344 zpool_get_rewind_policy(config, &policy);
4345 if (policy.zrp_request & ZPOOL_DO_REWIND)
4346 state = SPA_LOAD_RECOVER;
4347
34dc7c2f 4348 /*
9babb374
BB
4349 * Pass off the heavy lifting to spa_load(). Pass TRUE for mosconfig
4350 * because the user-supplied config is actually the one to trust when
b128c09f 4351 * doing an import.
34dc7c2f 4352 */
428870ff
BB
4353 if (state != SPA_LOAD_RECOVER)
4354 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
572e2857 4355
428870ff
BB
4356 error = spa_load_best(spa, state, B_TRUE, policy.zrp_txg,
4357 policy.zrp_request);
4358
4359 /*
572e2857
BB
4360 * Propagate anything learned while loading the pool and pass it
4361 * back to caller (i.e. rewind info, missing devices, etc).
428870ff 4362 */
572e2857
BB
4363 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
4364 spa->spa_load_info) == 0);
34dc7c2f 4365
b128c09f 4366 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 4367 /*
9babb374
BB
4368 * Toss any existing sparelist, as it doesn't have any validity
4369 * anymore, and conflicts with spa_has_spare().
34dc7c2f 4370 */
9babb374 4371 if (spa->spa_spares.sav_config) {
34dc7c2f
BB
4372 nvlist_free(spa->spa_spares.sav_config);
4373 spa->spa_spares.sav_config = NULL;
4374 spa_load_spares(spa);
4375 }
9babb374 4376 if (spa->spa_l2cache.sav_config) {
34dc7c2f
BB
4377 nvlist_free(spa->spa_l2cache.sav_config);
4378 spa->spa_l2cache.sav_config = NULL;
4379 spa_load_l2cache(spa);
4380 }
4381
4382 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
4383 &nvroot) == 0);
b128c09f 4384 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f 4385
d164b209
BB
4386 if (props != NULL)
4387 spa_configfile_set(spa, props, B_FALSE);
4388
fb5f0bc8
BB
4389 if (error != 0 || (props && spa_writeable(spa) &&
4390 (error = spa_prop_set(spa, props)))) {
9babb374
BB
4391 spa_unload(spa);
4392 spa_deactivate(spa);
4393 spa_remove(spa);
34dc7c2f
BB
4394 mutex_exit(&spa_namespace_lock);
4395 return (error);
4396 }
4397
572e2857
BB
4398 spa_async_resume(spa);
4399
34dc7c2f
BB
4400 /*
4401 * Override any spares and level 2 cache devices as specified by
4402 * the user, as these may have correct device names/devids, etc.
4403 */
4404 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
4405 &spares, &nspares) == 0) {
4406 if (spa->spa_spares.sav_config)
4407 VERIFY(nvlist_remove(spa->spa_spares.sav_config,
4408 ZPOOL_CONFIG_SPARES, DATA_TYPE_NVLIST_ARRAY) == 0);
4409 else
4410 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config,
79c76d5b 4411 NV_UNIQUE_NAME, KM_SLEEP) == 0);
34dc7c2f
BB
4412 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
4413 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
b128c09f 4414 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 4415 spa_load_spares(spa);
b128c09f 4416 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
4417 spa->spa_spares.sav_sync = B_TRUE;
4418 }
4419 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
4420 &l2cache, &nl2cache) == 0) {
4421 if (spa->spa_l2cache.sav_config)
4422 VERIFY(nvlist_remove(spa->spa_l2cache.sav_config,
4423 ZPOOL_CONFIG_L2CACHE, DATA_TYPE_NVLIST_ARRAY) == 0);
4424 else
4425 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
79c76d5b 4426 NV_UNIQUE_NAME, KM_SLEEP) == 0);
34dc7c2f
BB
4427 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
4428 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
b128c09f 4429 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 4430 spa_load_l2cache(spa);
b128c09f 4431 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
4432 spa->spa_l2cache.sav_sync = B_TRUE;
4433 }
4434
428870ff
BB
4435 /*
4436 * Check for any removed devices.
4437 */
4438 if (spa->spa_autoreplace) {
4439 spa_aux_check_removed(&spa->spa_spares);
4440 spa_aux_check_removed(&spa->spa_l2cache);
4441 }
4442
fb5f0bc8 4443 if (spa_writeable(spa)) {
b128c09f
BB
4444 /*
4445 * Update the config cache to include the newly-imported pool.
4446 */
45d1cae3 4447 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
b128c09f 4448 }
34dc7c2f 4449
34dc7c2f 4450 /*
9babb374
BB
4451 * It's possible that the pool was expanded while it was exported.
4452 * We kick off an async task to handle this for us.
34dc7c2f 4453 */
9babb374 4454 spa_async_request(spa, SPA_ASYNC_AUTOEXPAND);
b128c09f 4455
d5e024cb 4456 spa_history_log_version(spa, "import", NULL);
fb390aaf 4457
12fa0466 4458 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
fb390aaf 4459
a0bd735a 4460 zvol_create_minors(spa, pool, B_TRUE);
526af785 4461
fb390aaf
HR
4462 mutex_exit(&spa_namespace_lock);
4463
b128c09f
BB
4464 return (0);
4465}
4466
34dc7c2f
BB
4467nvlist_t *
4468spa_tryimport(nvlist_t *tryconfig)
4469{
4470 nvlist_t *config = NULL;
4471 char *poolname;
4472 spa_t *spa;
4473 uint64_t state;
d164b209 4474 int error;
34dc7c2f
BB
4475
4476 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_POOL_NAME, &poolname))
4477 return (NULL);
4478
4479 if (nvlist_lookup_uint64(tryconfig, ZPOOL_CONFIG_POOL_STATE, &state))
4480 return (NULL);
4481
4482 /*
4483 * Create and initialize the spa structure.
4484 */
4485 mutex_enter(&spa_namespace_lock);
428870ff 4486 spa = spa_add(TRYIMPORT_NAME, tryconfig, NULL);
fb5f0bc8 4487 spa_activate(spa, FREAD);
34dc7c2f
BB
4488
4489 /*
4490 * Pass off the heavy lifting to spa_load().
4491 * Pass TRUE for mosconfig because the user-supplied config
4492 * is actually the one to trust when doing an import.
4493 */
428870ff 4494 error = spa_load(spa, SPA_LOAD_TRYIMPORT, SPA_IMPORT_EXISTING, B_TRUE);
34dc7c2f
BB
4495
4496 /*
4497 * If 'tryconfig' was at least parsable, return the current config.
4498 */
4499 if (spa->spa_root_vdev != NULL) {
34dc7c2f 4500 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
34dc7c2f
BB
4501 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME,
4502 poolname) == 0);
4503 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
4504 state) == 0);
4505 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
4506 spa->spa_uberblock.ub_timestamp) == 0);
9ae529ec
CS
4507 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
4508 spa->spa_load_info) == 0);
ffe9d382
BB
4509 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_ERRATA,
4510 spa->spa_errata) == 0);
34dc7c2f
BB
4511
4512 /*
4513 * If the bootfs property exists on this pool then we
4514 * copy it out so that external consumers can tell which
4515 * pools are bootable.
4516 */
d164b209 4517 if ((!error || error == EEXIST) && spa->spa_bootfs) {
79c76d5b 4518 char *tmpname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
34dc7c2f
BB
4519
4520 /*
4521 * We have to play games with the name since the
4522 * pool was opened as TRYIMPORT_NAME.
4523 */
b128c09f 4524 if (dsl_dsobj_to_dsname(spa_name(spa),
34dc7c2f
BB
4525 spa->spa_bootfs, tmpname) == 0) {
4526 char *cp;
d1d7e268
MK
4527 char *dsname;
4528
79c76d5b 4529 dsname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
34dc7c2f
BB
4530
4531 cp = strchr(tmpname, '/');
4532 if (cp == NULL) {
4533 (void) strlcpy(dsname, tmpname,
4534 MAXPATHLEN);
4535 } else {
4536 (void) snprintf(dsname, MAXPATHLEN,
4537 "%s/%s", poolname, ++cp);
4538 }
4539 VERIFY(nvlist_add_string(config,
4540 ZPOOL_CONFIG_BOOTFS, dsname) == 0);
4541 kmem_free(dsname, MAXPATHLEN);
4542 }
4543 kmem_free(tmpname, MAXPATHLEN);
4544 }
4545
4546 /*
4547 * Add the list of hot spares and level 2 cache devices.
4548 */
9babb374 4549 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
34dc7c2f
BB
4550 spa_add_spares(spa, config);
4551 spa_add_l2cache(spa, config);
9babb374 4552 spa_config_exit(spa, SCL_CONFIG, FTAG);
34dc7c2f
BB
4553 }
4554
4555 spa_unload(spa);
4556 spa_deactivate(spa);
4557 spa_remove(spa);
4558 mutex_exit(&spa_namespace_lock);
4559
4560 return (config);
4561}
4562
4563/*
4564 * Pool export/destroy
4565 *
4566 * The act of destroying or exporting a pool is very simple. We make sure there
4567 * is no more pending I/O and any references to the pool are gone. Then, we
4568 * update the pool state and sync all the labels to disk, removing the
fb5f0bc8
BB
4569 * configuration from the cache afterwards. If the 'hardforce' flag is set, then
4570 * we don't sync the labels or remove the configuration cache.
34dc7c2f
BB
4571 */
4572static int
b128c09f 4573spa_export_common(char *pool, int new_state, nvlist_t **oldconfig,
fb5f0bc8 4574 boolean_t force, boolean_t hardforce)
34dc7c2f
BB
4575{
4576 spa_t *spa;
4577
4578 if (oldconfig)
4579 *oldconfig = NULL;
4580
fb5f0bc8 4581 if (!(spa_mode_global & FWRITE))
2e528b49 4582 return (SET_ERROR(EROFS));
34dc7c2f
BB
4583
4584 mutex_enter(&spa_namespace_lock);
4585 if ((spa = spa_lookup(pool)) == NULL) {
4586 mutex_exit(&spa_namespace_lock);
2e528b49 4587 return (SET_ERROR(ENOENT));
34dc7c2f
BB
4588 }
4589
4590 /*
4591 * Put a hold on the pool, drop the namespace lock, stop async tasks,
4592 * reacquire the namespace lock, and see if we can export.
4593 */
4594 spa_open_ref(spa, FTAG);
4595 mutex_exit(&spa_namespace_lock);
4596 spa_async_suspend(spa);
a0bd735a
BP
4597 if (spa->spa_zvol_taskq) {
4598 zvol_remove_minors(spa, spa_name(spa), B_TRUE);
4599 taskq_wait(spa->spa_zvol_taskq);
4600 }
34dc7c2f
BB
4601 mutex_enter(&spa_namespace_lock);
4602 spa_close(spa, FTAG);
4603
d14cfd83
IH
4604 if (spa->spa_state == POOL_STATE_UNINITIALIZED)
4605 goto export_spa;
34dc7c2f 4606 /*
d14cfd83
IH
4607 * The pool will be in core if it's openable, in which case we can
4608 * modify its state. Objsets may be open only because they're dirty,
4609 * so we have to force it to sync before checking spa_refcnt.
34dc7c2f 4610 */
0c66c32d 4611 if (spa->spa_sync_on) {
34dc7c2f 4612 txg_wait_synced(spa->spa_dsl_pool, 0);
0c66c32d
JG
4613 spa_evicting_os_wait(spa);
4614 }
34dc7c2f 4615
d14cfd83
IH
4616 /*
4617 * A pool cannot be exported or destroyed if there are active
4618 * references. If we are resetting a pool, allow references by
4619 * fault injection handlers.
4620 */
4621 if (!spa_refcount_zero(spa) ||
4622 (spa->spa_inject_ref != 0 &&
4623 new_state != POOL_STATE_UNINITIALIZED)) {
4624 spa_async_resume(spa);
4625 mutex_exit(&spa_namespace_lock);
4626 return (SET_ERROR(EBUSY));
4627 }
34dc7c2f 4628
d14cfd83 4629 if (spa->spa_sync_on) {
b128c09f
BB
4630 /*
4631 * A pool cannot be exported if it has an active shared spare.
4632 * This is to prevent other pools stealing the active spare
4633 * from an exported pool. At user's own will, such pool can
4634 * be forcedly exported.
4635 */
4636 if (!force && new_state == POOL_STATE_EXPORTED &&
4637 spa_has_active_shared_spare(spa)) {
4638 spa_async_resume(spa);
4639 mutex_exit(&spa_namespace_lock);
2e528b49 4640 return (SET_ERROR(EXDEV));
b128c09f 4641 }
34dc7c2f
BB
4642
4643 /*
4644 * We want this to be reflected on every label,
4645 * so mark them all dirty. spa_unload() will do the
4646 * final sync that pushes these changes out.
4647 */
fb5f0bc8 4648 if (new_state != POOL_STATE_UNINITIALIZED && !hardforce) {
b128c09f 4649 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f 4650 spa->spa_state = new_state;
428870ff
BB
4651 spa->spa_final_txg = spa_last_synced_txg(spa) +
4652 TXG_DEFER_SIZE + 1;
34dc7c2f 4653 vdev_config_dirty(spa->spa_root_vdev);
b128c09f 4654 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
4655 }
4656 }
4657
d14cfd83 4658export_spa:
d5e024cb
BB
4659 if (new_state == POOL_STATE_DESTROYED)
4660 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_DESTROY);
4661 else if (new_state == POOL_STATE_EXPORTED)
4662 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_EXPORT);
34dc7c2f
BB
4663
4664 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
4665 spa_unload(spa);
4666 spa_deactivate(spa);
4667 }
4668
4669 if (oldconfig && spa->spa_config)
4670 VERIFY(nvlist_dup(spa->spa_config, oldconfig, 0) == 0);
4671
4672 if (new_state != POOL_STATE_UNINITIALIZED) {
fb5f0bc8
BB
4673 if (!hardforce)
4674 spa_config_sync(spa, B_TRUE, B_TRUE);
34dc7c2f 4675 spa_remove(spa);
34dc7c2f
BB
4676 }
4677 mutex_exit(&spa_namespace_lock);
4678
4679 return (0);
4680}
4681
4682/*
4683 * Destroy a storage pool.
4684 */
4685int
4686spa_destroy(char *pool)
4687{
fb5f0bc8
BB
4688 return (spa_export_common(pool, POOL_STATE_DESTROYED, NULL,
4689 B_FALSE, B_FALSE));
34dc7c2f
BB
4690}
4691
4692/*
4693 * Export a storage pool.
4694 */
4695int
fb5f0bc8
BB
4696spa_export(char *pool, nvlist_t **oldconfig, boolean_t force,
4697 boolean_t hardforce)
34dc7c2f 4698{
fb5f0bc8
BB
4699 return (spa_export_common(pool, POOL_STATE_EXPORTED, oldconfig,
4700 force, hardforce));
34dc7c2f
BB
4701}
4702
4703/*
4704 * Similar to spa_export(), this unloads the spa_t without actually removing it
4705 * from the namespace in any way.
4706 */
4707int
4708spa_reset(char *pool)
4709{
b128c09f 4710 return (spa_export_common(pool, POOL_STATE_UNINITIALIZED, NULL,
fb5f0bc8 4711 B_FALSE, B_FALSE));
34dc7c2f
BB
4712}
4713
34dc7c2f
BB
4714/*
4715 * ==========================================================================
4716 * Device manipulation
4717 * ==========================================================================
4718 */
4719
4720/*
4721 * Add a device to a storage pool.
4722 */
4723int
4724spa_vdev_add(spa_t *spa, nvlist_t *nvroot)
4725{
428870ff 4726 uint64_t txg, id;
fb5f0bc8 4727 int error;
34dc7c2f
BB
4728 vdev_t *rvd = spa->spa_root_vdev;
4729 vdev_t *vd, *tvd;
4730 nvlist_t **spares, **l2cache;
4731 uint_t nspares, nl2cache;
4732
572e2857
BB
4733 ASSERT(spa_writeable(spa));
4734
34dc7c2f
BB
4735 txg = spa_vdev_enter(spa);
4736
4737 if ((error = spa_config_parse(spa, &vd, nvroot, NULL, 0,
4738 VDEV_ALLOC_ADD)) != 0)
4739 return (spa_vdev_exit(spa, NULL, txg, error));
4740
b128c09f 4741 spa->spa_pending_vdev = vd; /* spa_vdev_exit() will clear this */
34dc7c2f
BB
4742
4743 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares,
4744 &nspares) != 0)
4745 nspares = 0;
4746
4747 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE, &l2cache,
4748 &nl2cache) != 0)
4749 nl2cache = 0;
4750
b128c09f 4751 if (vd->vdev_children == 0 && nspares == 0 && nl2cache == 0)
34dc7c2f 4752 return (spa_vdev_exit(spa, vd, txg, EINVAL));
34dc7c2f 4753
b128c09f
BB
4754 if (vd->vdev_children != 0 &&
4755 (error = vdev_create(vd, txg, B_FALSE)) != 0)
4756 return (spa_vdev_exit(spa, vd, txg, error));
34dc7c2f
BB
4757
4758 /*
4759 * We must validate the spares and l2cache devices after checking the
4760 * children. Otherwise, vdev_inuse() will blindly overwrite the spare.
4761 */
b128c09f 4762 if ((error = spa_validate_aux(spa, nvroot, txg, VDEV_ALLOC_ADD)) != 0)
34dc7c2f 4763 return (spa_vdev_exit(spa, vd, txg, error));
34dc7c2f
BB
4764
4765 /*
4766 * Transfer each new top-level vdev from vd to rvd.
4767 */
1c27024e 4768 for (int c = 0; c < vd->vdev_children; c++) {
428870ff
BB
4769
4770 /*
4771 * Set the vdev id to the first hole, if one exists.
4772 */
4773 for (id = 0; id < rvd->vdev_children; id++) {
4774 if (rvd->vdev_child[id]->vdev_ishole) {
4775 vdev_free(rvd->vdev_child[id]);
4776 break;
4777 }
4778 }
34dc7c2f
BB
4779 tvd = vd->vdev_child[c];
4780 vdev_remove_child(vd, tvd);
428870ff 4781 tvd->vdev_id = id;
34dc7c2f
BB
4782 vdev_add_child(rvd, tvd);
4783 vdev_config_dirty(tvd);
4784 }
4785
4786 if (nspares != 0) {
4787 spa_set_aux_vdevs(&spa->spa_spares, spares, nspares,
4788 ZPOOL_CONFIG_SPARES);
4789 spa_load_spares(spa);
4790 spa->spa_spares.sav_sync = B_TRUE;
4791 }
4792
4793 if (nl2cache != 0) {
4794 spa_set_aux_vdevs(&spa->spa_l2cache, l2cache, nl2cache,
4795 ZPOOL_CONFIG_L2CACHE);
4796 spa_load_l2cache(spa);
4797 spa->spa_l2cache.sav_sync = B_TRUE;
4798 }
4799
4800 /*
4801 * We have to be careful when adding new vdevs to an existing pool.
4802 * If other threads start allocating from these vdevs before we
4803 * sync the config cache, and we lose power, then upon reboot we may
4804 * fail to open the pool because there are DVAs that the config cache
4805 * can't translate. Therefore, we first add the vdevs without
4806 * initializing metaslabs; sync the config cache (via spa_vdev_exit());
4807 * and then let spa_config_update() initialize the new metaslabs.
4808 *
4809 * spa_load() checks for added-but-not-initialized vdevs, so that
4810 * if we lose power at any point in this sequence, the remaining
4811 * steps will be completed the next time we load the pool.
4812 */
4813 (void) spa_vdev_exit(spa, vd, txg, 0);
4814
4815 mutex_enter(&spa_namespace_lock);
4816 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
12fa0466 4817 spa_event_notify(spa, NULL, NULL, ESC_ZFS_VDEV_ADD);
34dc7c2f
BB
4818 mutex_exit(&spa_namespace_lock);
4819
4820 return (0);
4821}
4822
4823/*
4824 * Attach a device to a mirror. The arguments are the path to any device
4825 * in the mirror, and the nvroot for the new device. If the path specifies
4826 * a device that is not mirrored, we automatically insert the mirror vdev.
4827 *
4828 * If 'replacing' is specified, the new device is intended to replace the
4829 * existing device; in this case the two devices are made into their own
4830 * mirror using the 'replacing' vdev, which is functionally identical to
4831 * the mirror vdev (it actually reuses all the same ops) but has a few
4832 * extra rules: you can't attach to it after it's been created, and upon
4833 * completion of resilvering, the first disk (the one being replaced)
4834 * is automatically detached.
4835 */
4836int
4837spa_vdev_attach(spa_t *spa, uint64_t guid, nvlist_t *nvroot, int replacing)
4838{
428870ff 4839 uint64_t txg, dtl_max_txg;
1c27024e 4840 ASSERTV(vdev_t *rvd = spa->spa_root_vdev);
34dc7c2f
BB
4841 vdev_t *oldvd, *newvd, *newrootvd, *pvd, *tvd;
4842 vdev_ops_t *pvops;
b128c09f
BB
4843 char *oldvdpath, *newvdpath;
4844 int newvd_isspare;
4845 int error;
34dc7c2f 4846
572e2857
BB
4847 ASSERT(spa_writeable(spa));
4848
34dc7c2f
BB
4849 txg = spa_vdev_enter(spa);
4850
b128c09f 4851 oldvd = spa_lookup_by_guid(spa, guid, B_FALSE);
34dc7c2f
BB
4852
4853 if (oldvd == NULL)
4854 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
4855
4856 if (!oldvd->vdev_ops->vdev_op_leaf)
4857 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
4858
4859 pvd = oldvd->vdev_parent;
4860
4861 if ((error = spa_config_parse(spa, &newrootvd, nvroot, NULL, 0,
5ffb9d1d 4862 VDEV_ALLOC_ATTACH)) != 0)
34dc7c2f
BB
4863 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
4864
4865 if (newrootvd->vdev_children != 1)
4866 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
4867
4868 newvd = newrootvd->vdev_child[0];
4869
4870 if (!newvd->vdev_ops->vdev_op_leaf)
4871 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
4872
4873 if ((error = vdev_create(newrootvd, txg, replacing)) != 0)
4874 return (spa_vdev_exit(spa, newrootvd, txg, error));
4875
4876 /*
4877 * Spares can't replace logs
4878 */
b128c09f 4879 if (oldvd->vdev_top->vdev_islog && newvd->vdev_isspare)
34dc7c2f
BB
4880 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
4881
4882 if (!replacing) {
4883 /*
4884 * For attach, the only allowable parent is a mirror or the root
4885 * vdev.
4886 */
4887 if (pvd->vdev_ops != &vdev_mirror_ops &&
4888 pvd->vdev_ops != &vdev_root_ops)
4889 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
4890
4891 pvops = &vdev_mirror_ops;
4892 } else {
4893 /*
4894 * Active hot spares can only be replaced by inactive hot
4895 * spares.
4896 */
4897 if (pvd->vdev_ops == &vdev_spare_ops &&
572e2857 4898 oldvd->vdev_isspare &&
34dc7c2f
BB
4899 !spa_has_spare(spa, newvd->vdev_guid))
4900 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
4901
4902 /*
4903 * If the source is a hot spare, and the parent isn't already a
4904 * spare, then we want to create a new hot spare. Otherwise, we
4905 * want to create a replacing vdev. The user is not allowed to
4906 * attach to a spared vdev child unless the 'isspare' state is
4907 * the same (spare replaces spare, non-spare replaces
4908 * non-spare).
4909 */
572e2857
BB
4910 if (pvd->vdev_ops == &vdev_replacing_ops &&
4911 spa_version(spa) < SPA_VERSION_MULTI_REPLACE) {
34dc7c2f 4912 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
572e2857
BB
4913 } else if (pvd->vdev_ops == &vdev_spare_ops &&
4914 newvd->vdev_isspare != oldvd->vdev_isspare) {
34dc7c2f 4915 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
572e2857
BB
4916 }
4917
4918 if (newvd->vdev_isspare)
34dc7c2f
BB
4919 pvops = &vdev_spare_ops;
4920 else
4921 pvops = &vdev_replacing_ops;
4922 }
4923
4924 /*
9babb374 4925 * Make sure the new device is big enough.
34dc7c2f 4926 */
9babb374 4927 if (newvd->vdev_asize < vdev_get_min_asize(oldvd))
34dc7c2f
BB
4928 return (spa_vdev_exit(spa, newrootvd, txg, EOVERFLOW));
4929
4930 /*
4931 * The new device cannot have a higher alignment requirement
4932 * than the top-level vdev.
4933 */
4934 if (newvd->vdev_ashift > oldvd->vdev_top->vdev_ashift)
4935 return (spa_vdev_exit(spa, newrootvd, txg, EDOM));
4936
4937 /*
4938 * If this is an in-place replacement, update oldvd's path and devid
4939 * to make it distinguishable from newvd, and unopenable from now on.
4940 */
4941 if (strcmp(oldvd->vdev_path, newvd->vdev_path) == 0) {
4942 spa_strfree(oldvd->vdev_path);
4943 oldvd->vdev_path = kmem_alloc(strlen(newvd->vdev_path) + 5,
79c76d5b 4944 KM_SLEEP);
34dc7c2f
BB
4945 (void) sprintf(oldvd->vdev_path, "%s/%s",
4946 newvd->vdev_path, "old");
4947 if (oldvd->vdev_devid != NULL) {
4948 spa_strfree(oldvd->vdev_devid);
4949 oldvd->vdev_devid = NULL;
4950 }
4951 }
4952
572e2857 4953 /* mark the device being resilvered */
5d1f7fb6 4954 newvd->vdev_resilver_txg = txg;
572e2857 4955
34dc7c2f
BB
4956 /*
4957 * If the parent is not a mirror, or if we're replacing, insert the new
4958 * mirror/replacing/spare vdev above oldvd.
4959 */
4960 if (pvd->vdev_ops != pvops)
4961 pvd = vdev_add_parent(oldvd, pvops);
4962
4963 ASSERT(pvd->vdev_top->vdev_parent == rvd);
4964 ASSERT(pvd->vdev_ops == pvops);
4965 ASSERT(oldvd->vdev_parent == pvd);
4966
4967 /*
4968 * Extract the new device from its root and add it to pvd.
4969 */
4970 vdev_remove_child(newrootvd, newvd);
4971 newvd->vdev_id = pvd->vdev_children;
428870ff 4972 newvd->vdev_crtxg = oldvd->vdev_crtxg;
34dc7c2f
BB
4973 vdev_add_child(pvd, newvd);
4974
6d82f98c
IH
4975 /*
4976 * Reevaluate the parent vdev state.
4977 */
4978 vdev_propagate_state(pvd);
4979
34dc7c2f
BB
4980 tvd = newvd->vdev_top;
4981 ASSERT(pvd->vdev_top == tvd);
4982 ASSERT(tvd->vdev_parent == rvd);
4983
4984 vdev_config_dirty(tvd);
4985
4986 /*
428870ff
BB
4987 * Set newvd's DTL to [TXG_INITIAL, dtl_max_txg) so that we account
4988 * for any dmu_sync-ed blocks. It will propagate upward when
4989 * spa_vdev_exit() calls vdev_dtl_reassess().
34dc7c2f 4990 */
428870ff 4991 dtl_max_txg = txg + TXG_CONCURRENT_STATES;
34dc7c2f 4992
428870ff
BB
4993 vdev_dtl_dirty(newvd, DTL_MISSING, TXG_INITIAL,
4994 dtl_max_txg - TXG_INITIAL);
34dc7c2f 4995
9babb374 4996 if (newvd->vdev_isspare) {
34dc7c2f 4997 spa_spare_activate(newvd);
12fa0466 4998 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_SPARE);
9babb374
BB
4999 }
5000
b128c09f
BB
5001 oldvdpath = spa_strdup(oldvd->vdev_path);
5002 newvdpath = spa_strdup(newvd->vdev_path);
5003 newvd_isspare = newvd->vdev_isspare;
34dc7c2f
BB
5004
5005 /*
5006 * Mark newvd's DTL dirty in this txg.
5007 */
5008 vdev_dirty(tvd, VDD_DTL, newvd, txg);
5009
428870ff 5010 /*
93cf2076
GW
5011 * Schedule the resilver to restart in the future. We do this to
5012 * ensure that dmu_sync-ed blocks have been stitched into the
5013 * respective datasets.
428870ff
BB
5014 */
5015 dsl_resilver_restart(spa->spa_dsl_pool, dtl_max_txg);
5016
fb390aaf 5017 if (spa->spa_bootfs)
12fa0466 5018 spa_event_notify(spa, newvd, NULL, ESC_ZFS_BOOTFS_VDEV_ATTACH);
fb390aaf 5019
12fa0466 5020 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_ATTACH);
fb390aaf 5021
428870ff
BB
5022 /*
5023 * Commit the config
5024 */
5025 (void) spa_vdev_exit(spa, newrootvd, dtl_max_txg, 0);
34dc7c2f 5026
6f1ffb06 5027 spa_history_log_internal(spa, "vdev attach", NULL,
428870ff 5028 "%s vdev=%s %s vdev=%s",
45d1cae3
BB
5029 replacing && newvd_isspare ? "spare in" :
5030 replacing ? "replace" : "attach", newvdpath,
5031 replacing ? "for" : "to", oldvdpath);
b128c09f
BB
5032
5033 spa_strfree(oldvdpath);
5034 spa_strfree(newvdpath);
5035
34dc7c2f
BB
5036 return (0);
5037}
5038
5039/*
5040 * Detach a device from a mirror or replacing vdev.
d3cc8b15 5041 *
34dc7c2f
BB
5042 * If 'replace_done' is specified, only detach if the parent
5043 * is a replacing vdev.
5044 */
5045int
fb5f0bc8 5046spa_vdev_detach(spa_t *spa, uint64_t guid, uint64_t pguid, int replace_done)
34dc7c2f
BB
5047{
5048 uint64_t txg;
fb5f0bc8 5049 int error;
1c27024e 5050 ASSERTV(vdev_t *rvd = spa->spa_root_vdev);
34dc7c2f
BB
5051 vdev_t *vd, *pvd, *cvd, *tvd;
5052 boolean_t unspare = B_FALSE;
d4ed6673 5053 uint64_t unspare_guid = 0;
428870ff 5054 char *vdpath;
1c27024e 5055
572e2857
BB
5056 ASSERT(spa_writeable(spa));
5057
34dc7c2f
BB
5058 txg = spa_vdev_enter(spa);
5059
b128c09f 5060 vd = spa_lookup_by_guid(spa, guid, B_FALSE);
34dc7c2f
BB
5061
5062 if (vd == NULL)
5063 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
5064
5065 if (!vd->vdev_ops->vdev_op_leaf)
5066 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
5067
5068 pvd = vd->vdev_parent;
5069
fb5f0bc8
BB
5070 /*
5071 * If the parent/child relationship is not as expected, don't do it.
5072 * Consider M(A,R(B,C)) -- that is, a mirror of A with a replacing
5073 * vdev that's replacing B with C. The user's intent in replacing
5074 * is to go from M(A,B) to M(A,C). If the user decides to cancel
5075 * the replace by detaching C, the expected behavior is to end up
5076 * M(A,B). But suppose that right after deciding to detach C,
5077 * the replacement of B completes. We would have M(A,C), and then
5078 * ask to detach C, which would leave us with just A -- not what
5079 * the user wanted. To prevent this, we make sure that the
5080 * parent/child relationship hasn't changed -- in this example,
5081 * that C's parent is still the replacing vdev R.
5082 */
5083 if (pvd->vdev_guid != pguid && pguid != 0)
5084 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
5085
34dc7c2f 5086 /*
572e2857 5087 * Only 'replacing' or 'spare' vdevs can be replaced.
34dc7c2f 5088 */
572e2857
BB
5089 if (replace_done && pvd->vdev_ops != &vdev_replacing_ops &&
5090 pvd->vdev_ops != &vdev_spare_ops)
5091 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
34dc7c2f
BB
5092
5093 ASSERT(pvd->vdev_ops != &vdev_spare_ops ||
5094 spa_version(spa) >= SPA_VERSION_SPARES);
5095
5096 /*
5097 * Only mirror, replacing, and spare vdevs support detach.
5098 */
5099 if (pvd->vdev_ops != &vdev_replacing_ops &&
5100 pvd->vdev_ops != &vdev_mirror_ops &&
5101 pvd->vdev_ops != &vdev_spare_ops)
5102 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
5103
5104 /*
fb5f0bc8
BB
5105 * If this device has the only valid copy of some data,
5106 * we cannot safely detach it.
34dc7c2f 5107 */
fb5f0bc8 5108 if (vdev_dtl_required(vd))
34dc7c2f
BB
5109 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
5110
fb5f0bc8 5111 ASSERT(pvd->vdev_children >= 2);
34dc7c2f 5112
b128c09f
BB
5113 /*
5114 * If we are detaching the second disk from a replacing vdev, then
5115 * check to see if we changed the original vdev's path to have "/old"
5116 * at the end in spa_vdev_attach(). If so, undo that change now.
5117 */
572e2857
BB
5118 if (pvd->vdev_ops == &vdev_replacing_ops && vd->vdev_id > 0 &&
5119 vd->vdev_path != NULL) {
5120 size_t len = strlen(vd->vdev_path);
5121
1c27024e 5122 for (int c = 0; c < pvd->vdev_children; c++) {
572e2857
BB
5123 cvd = pvd->vdev_child[c];
5124
5125 if (cvd == vd || cvd->vdev_path == NULL)
5126 continue;
5127
5128 if (strncmp(cvd->vdev_path, vd->vdev_path, len) == 0 &&
5129 strcmp(cvd->vdev_path + len, "/old") == 0) {
5130 spa_strfree(cvd->vdev_path);
5131 cvd->vdev_path = spa_strdup(vd->vdev_path);
5132 break;
5133 }
b128c09f
BB
5134 }
5135 }
5136
34dc7c2f
BB
5137 /*
5138 * If we are detaching the original disk from a spare, then it implies
5139 * that the spare should become a real disk, and be removed from the
5140 * active spare list for the pool.
5141 */
5142 if (pvd->vdev_ops == &vdev_spare_ops &&
572e2857
BB
5143 vd->vdev_id == 0 &&
5144 pvd->vdev_child[pvd->vdev_children - 1]->vdev_isspare)
34dc7c2f
BB
5145 unspare = B_TRUE;
5146
5147 /*
5148 * Erase the disk labels so the disk can be used for other things.
5149 * This must be done after all other error cases are handled,
5150 * but before we disembowel vd (so we can still do I/O to it).
5151 * But if we can't do it, don't treat the error as fatal --
5152 * it may be that the unwritability of the disk is the reason
5153 * it's being detached!
5154 */
5155 error = vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
5156
5157 /*
5158 * Remove vd from its parent and compact the parent's children.
5159 */
5160 vdev_remove_child(pvd, vd);
5161 vdev_compact_children(pvd);
5162
5163 /*
5164 * Remember one of the remaining children so we can get tvd below.
5165 */
572e2857 5166 cvd = pvd->vdev_child[pvd->vdev_children - 1];
34dc7c2f
BB
5167
5168 /*
5169 * If we need to remove the remaining child from the list of hot spares,
fb5f0bc8
BB
5170 * do it now, marking the vdev as no longer a spare in the process.
5171 * We must do this before vdev_remove_parent(), because that can
5172 * change the GUID if it creates a new toplevel GUID. For a similar
5173 * reason, we must remove the spare now, in the same txg as the detach;
5174 * otherwise someone could attach a new sibling, change the GUID, and
5175 * the subsequent attempt to spa_vdev_remove(unspare_guid) would fail.
34dc7c2f
BB
5176 */
5177 if (unspare) {
5178 ASSERT(cvd->vdev_isspare);
5179 spa_spare_remove(cvd);
5180 unspare_guid = cvd->vdev_guid;
fb5f0bc8 5181 (void) spa_vdev_remove(spa, unspare_guid, B_TRUE);
572e2857 5182 cvd->vdev_unspare = B_TRUE;
34dc7c2f
BB
5183 }
5184
428870ff
BB
5185 /*
5186 * If the parent mirror/replacing vdev only has one child,
5187 * the parent is no longer needed. Remove it from the tree.
5188 */
572e2857
BB
5189 if (pvd->vdev_children == 1) {
5190 if (pvd->vdev_ops == &vdev_spare_ops)
5191 cvd->vdev_unspare = B_FALSE;
428870ff 5192 vdev_remove_parent(cvd);
572e2857
BB
5193 }
5194
428870ff
BB
5195
5196 /*
5197 * We don't set tvd until now because the parent we just removed
5198 * may have been the previous top-level vdev.
5199 */
5200 tvd = cvd->vdev_top;
5201 ASSERT(tvd->vdev_parent == rvd);
5202
5203 /*
5204 * Reevaluate the parent vdev state.
5205 */
5206 vdev_propagate_state(cvd);
5207
5208 /*
5209 * If the 'autoexpand' property is set on the pool then automatically
5210 * try to expand the size of the pool. For example if the device we
5211 * just detached was smaller than the others, it may be possible to
5212 * add metaslabs (i.e. grow the pool). We need to reopen the vdev
5213 * first so that we can obtain the updated sizes of the leaf vdevs.
5214 */
5215 if (spa->spa_autoexpand) {
5216 vdev_reopen(tvd);
5217 vdev_expand(tvd, txg);
5218 }
5219
5220 vdev_config_dirty(tvd);
5221
5222 /*
5223 * Mark vd's DTL as dirty in this txg. vdev_dtl_sync() will see that
5224 * vd->vdev_detached is set and free vd's DTL object in syncing context.
5225 * But first make sure we're not on any *other* txg's DTL list, to
5226 * prevent vd from being accessed after it's freed.
5227 */
b6ca6193 5228 vdpath = spa_strdup(vd->vdev_path ? vd->vdev_path : "none");
1c27024e 5229 for (int t = 0; t < TXG_SIZE; t++)
428870ff
BB
5230 (void) txg_list_remove_this(&tvd->vdev_dtl_list, vd, t);
5231 vd->vdev_detached = B_TRUE;
5232 vdev_dirty(tvd, VDD_DTL, vd, txg);
5233
12fa0466 5234 spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE);
428870ff 5235
572e2857
BB
5236 /* hang on to the spa before we release the lock */
5237 spa_open_ref(spa, FTAG);
5238
428870ff
BB
5239 error = spa_vdev_exit(spa, vd, txg, 0);
5240
6f1ffb06 5241 spa_history_log_internal(spa, "detach", NULL,
428870ff
BB
5242 "vdev=%s", vdpath);
5243 spa_strfree(vdpath);
5244
5245 /*
5246 * If this was the removal of the original device in a hot spare vdev,
5247 * then we want to go through and remove the device from the hot spare
5248 * list of every other pool.
5249 */
5250 if (unspare) {
572e2857
BB
5251 spa_t *altspa = NULL;
5252
428870ff 5253 mutex_enter(&spa_namespace_lock);
572e2857
BB
5254 while ((altspa = spa_next(altspa)) != NULL) {
5255 if (altspa->spa_state != POOL_STATE_ACTIVE ||
5256 altspa == spa)
428870ff 5257 continue;
572e2857
BB
5258
5259 spa_open_ref(altspa, FTAG);
428870ff 5260 mutex_exit(&spa_namespace_lock);
572e2857 5261 (void) spa_vdev_remove(altspa, unspare_guid, B_TRUE);
428870ff 5262 mutex_enter(&spa_namespace_lock);
572e2857 5263 spa_close(altspa, FTAG);
428870ff
BB
5264 }
5265 mutex_exit(&spa_namespace_lock);
572e2857
BB
5266
5267 /* search the rest of the vdevs for spares to remove */
5268 spa_vdev_resilver_done(spa);
428870ff
BB
5269 }
5270
572e2857
BB
5271 /* all done with the spa; OK to release */
5272 mutex_enter(&spa_namespace_lock);
5273 spa_close(spa, FTAG);
5274 mutex_exit(&spa_namespace_lock);
5275
428870ff
BB
5276 return (error);
5277}
5278
5279/*
5280 * Split a set of devices from their mirrors, and create a new pool from them.
5281 */
5282int
5283spa_vdev_split_mirror(spa_t *spa, char *newname, nvlist_t *config,
5284 nvlist_t *props, boolean_t exp)
5285{
5286 int error = 0;
5287 uint64_t txg, *glist;
5288 spa_t *newspa;
5289 uint_t c, children, lastlog;
5290 nvlist_t **child, *nvl, *tmp;
5291 dmu_tx_t *tx;
5292 char *altroot = NULL;
5293 vdev_t *rvd, **vml = NULL; /* vdev modify list */
5294 boolean_t activate_slog;
5295
572e2857 5296 ASSERT(spa_writeable(spa));
428870ff
BB
5297
5298 txg = spa_vdev_enter(spa);
5299
5300 /* clear the log and flush everything up to now */
5301 activate_slog = spa_passivate_log(spa);
5302 (void) spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
5303 error = spa_offline_log(spa);
5304 txg = spa_vdev_config_enter(spa);
5305
5306 if (activate_slog)
5307 spa_activate_log(spa);
5308
5309 if (error != 0)
5310 return (spa_vdev_exit(spa, NULL, txg, error));
5311
5312 /* check new spa name before going any further */
5313 if (spa_lookup(newname) != NULL)
5314 return (spa_vdev_exit(spa, NULL, txg, EEXIST));
5315
5316 /*
5317 * scan through all the children to ensure they're all mirrors
5318 */
5319 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvl) != 0 ||
5320 nvlist_lookup_nvlist_array(nvl, ZPOOL_CONFIG_CHILDREN, &child,
5321 &children) != 0)
5322 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
5323
5324 /* first, check to ensure we've got the right child count */
5325 rvd = spa->spa_root_vdev;
5326 lastlog = 0;
5327 for (c = 0; c < rvd->vdev_children; c++) {
5328 vdev_t *vd = rvd->vdev_child[c];
5329
5330 /* don't count the holes & logs as children */
5331 if (vd->vdev_islog || vd->vdev_ishole) {
5332 if (lastlog == 0)
5333 lastlog = c;
5334 continue;
5335 }
5336
5337 lastlog = 0;
5338 }
5339 if (children != (lastlog != 0 ? lastlog : rvd->vdev_children))
5340 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
5341
5342 /* next, ensure no spare or cache devices are part of the split */
5343 if (nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_SPARES, &tmp) == 0 ||
5344 nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_L2CACHE, &tmp) == 0)
5345 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
5346
79c76d5b
BB
5347 vml = kmem_zalloc(children * sizeof (vdev_t *), KM_SLEEP);
5348 glist = kmem_zalloc(children * sizeof (uint64_t), KM_SLEEP);
428870ff
BB
5349
5350 /* then, loop over each vdev and validate it */
5351 for (c = 0; c < children; c++) {
5352 uint64_t is_hole = 0;
5353
5354 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
5355 &is_hole);
5356
5357 if (is_hole != 0) {
5358 if (spa->spa_root_vdev->vdev_child[c]->vdev_ishole ||
5359 spa->spa_root_vdev->vdev_child[c]->vdev_islog) {
5360 continue;
5361 } else {
2e528b49 5362 error = SET_ERROR(EINVAL);
428870ff
BB
5363 break;
5364 }
5365 }
5366
5367 /* which disk is going to be split? */
5368 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_GUID,
5369 &glist[c]) != 0) {
2e528b49 5370 error = SET_ERROR(EINVAL);
428870ff
BB
5371 break;
5372 }
5373
5374 /* look it up in the spa */
5375 vml[c] = spa_lookup_by_guid(spa, glist[c], B_FALSE);
5376 if (vml[c] == NULL) {
2e528b49 5377 error = SET_ERROR(ENODEV);
428870ff
BB
5378 break;
5379 }
5380
5381 /* make sure there's nothing stopping the split */
5382 if (vml[c]->vdev_parent->vdev_ops != &vdev_mirror_ops ||
5383 vml[c]->vdev_islog ||
5384 vml[c]->vdev_ishole ||
5385 vml[c]->vdev_isspare ||
5386 vml[c]->vdev_isl2cache ||
5387 !vdev_writeable(vml[c]) ||
5388 vml[c]->vdev_children != 0 ||
5389 vml[c]->vdev_state != VDEV_STATE_HEALTHY ||
5390 c != spa->spa_root_vdev->vdev_child[c]->vdev_id) {
2e528b49 5391 error = SET_ERROR(EINVAL);
428870ff
BB
5392 break;
5393 }
5394
5395 if (vdev_dtl_required(vml[c])) {
2e528b49 5396 error = SET_ERROR(EBUSY);
428870ff
BB
5397 break;
5398 }
5399
5400 /* we need certain info from the top level */
5401 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_ARRAY,
5402 vml[c]->vdev_top->vdev_ms_array) == 0);
5403 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_SHIFT,
5404 vml[c]->vdev_top->vdev_ms_shift) == 0);
5405 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASIZE,
5406 vml[c]->vdev_top->vdev_asize) == 0);
5407 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASHIFT,
5408 vml[c]->vdev_top->vdev_ashift) == 0);
e0ab3ab5
JS
5409
5410 /* transfer per-vdev ZAPs */
5411 ASSERT3U(vml[c]->vdev_leaf_zap, !=, 0);
5412 VERIFY0(nvlist_add_uint64(child[c],
5413 ZPOOL_CONFIG_VDEV_LEAF_ZAP, vml[c]->vdev_leaf_zap));
5414
5415 ASSERT3U(vml[c]->vdev_top->vdev_top_zap, !=, 0);
5416 VERIFY0(nvlist_add_uint64(child[c],
5417 ZPOOL_CONFIG_VDEV_TOP_ZAP,
5418 vml[c]->vdev_parent->vdev_top_zap));
428870ff
BB
5419 }
5420
5421 if (error != 0) {
5422 kmem_free(vml, children * sizeof (vdev_t *));
5423 kmem_free(glist, children * sizeof (uint64_t));
5424 return (spa_vdev_exit(spa, NULL, txg, error));
5425 }
5426
5427 /* stop writers from using the disks */
5428 for (c = 0; c < children; c++) {
5429 if (vml[c] != NULL)
5430 vml[c]->vdev_offline = B_TRUE;
5431 }
5432 vdev_reopen(spa->spa_root_vdev);
34dc7c2f
BB
5433
5434 /*
428870ff
BB
5435 * Temporarily record the splitting vdevs in the spa config. This
5436 * will disappear once the config is regenerated.
34dc7c2f 5437 */
79c76d5b 5438 VERIFY(nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
428870ff
BB
5439 VERIFY(nvlist_add_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
5440 glist, children) == 0);
5441 kmem_free(glist, children * sizeof (uint64_t));
34dc7c2f 5442
428870ff
BB
5443 mutex_enter(&spa->spa_props_lock);
5444 VERIFY(nvlist_add_nvlist(spa->spa_config, ZPOOL_CONFIG_SPLIT,
5445 nvl) == 0);
5446 mutex_exit(&spa->spa_props_lock);
5447 spa->spa_config_splitting = nvl;
5448 vdev_config_dirty(spa->spa_root_vdev);
5449
5450 /* configure and create the new pool */
5451 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME, newname) == 0);
5452 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
5453 exp ? POOL_STATE_EXPORTED : POOL_STATE_ACTIVE) == 0);
5454 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
5455 spa_version(spa)) == 0);
5456 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_TXG,
5457 spa->spa_config_txg) == 0);
5458 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_GUID,
5459 spa_generate_guid(NULL)) == 0);
e0ab3ab5 5460 VERIFY0(nvlist_add_boolean(config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
428870ff
BB
5461 (void) nvlist_lookup_string(props,
5462 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
34dc7c2f 5463
428870ff
BB
5464 /* add the new pool to the namespace */
5465 newspa = spa_add(newname, config, altroot);
e0ab3ab5 5466 newspa->spa_avz_action = AVZ_ACTION_REBUILD;
428870ff
BB
5467 newspa->spa_config_txg = spa->spa_config_txg;
5468 spa_set_log_state(newspa, SPA_LOG_CLEAR);
5469
5470 /* release the spa config lock, retaining the namespace lock */
5471 spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
5472
5473 if (zio_injection_enabled)
5474 zio_handle_panic_injection(spa, FTAG, 1);
5475
5476 spa_activate(newspa, spa_mode_global);
5477 spa_async_suspend(newspa);
5478
5479 /* create the new pool from the disks of the original pool */
5480 error = spa_load(newspa, SPA_LOAD_IMPORT, SPA_IMPORT_ASSEMBLE, B_TRUE);
5481 if (error)
5482 goto out;
5483
5484 /* if that worked, generate a real config for the new pool */
5485 if (newspa->spa_root_vdev != NULL) {
5486 VERIFY(nvlist_alloc(&newspa->spa_config_splitting,
79c76d5b 5487 NV_UNIQUE_NAME, KM_SLEEP) == 0);
428870ff
BB
5488 VERIFY(nvlist_add_uint64(newspa->spa_config_splitting,
5489 ZPOOL_CONFIG_SPLIT_GUID, spa_guid(spa)) == 0);
5490 spa_config_set(newspa, spa_config_generate(newspa, NULL, -1ULL,
5491 B_TRUE));
9babb374 5492 }
34dc7c2f 5493
428870ff
BB
5494 /* set the props */
5495 if (props != NULL) {
5496 spa_configfile_set(newspa, props, B_FALSE);
5497 error = spa_prop_set(newspa, props);
5498 if (error)
5499 goto out;
5500 }
34dc7c2f 5501
428870ff
BB
5502 /* flush everything */
5503 txg = spa_vdev_config_enter(newspa);
5504 vdev_config_dirty(newspa->spa_root_vdev);
5505 (void) spa_vdev_config_exit(newspa, NULL, txg, 0, FTAG);
34dc7c2f 5506
428870ff
BB
5507 if (zio_injection_enabled)
5508 zio_handle_panic_injection(spa, FTAG, 2);
34dc7c2f 5509
428870ff 5510 spa_async_resume(newspa);
34dc7c2f 5511
428870ff
BB
5512 /* finally, update the original pool's config */
5513 txg = spa_vdev_config_enter(spa);
5514 tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
5515 error = dmu_tx_assign(tx, TXG_WAIT);
5516 if (error != 0)
5517 dmu_tx_abort(tx);
5518 for (c = 0; c < children; c++) {
5519 if (vml[c] != NULL) {
5520 vdev_split(vml[c]);
5521 if (error == 0)
6f1ffb06
MA
5522 spa_history_log_internal(spa, "detach", tx,
5523 "vdev=%s", vml[c]->vdev_path);
e0ab3ab5 5524
428870ff 5525 vdev_free(vml[c]);
34dc7c2f 5526 }
34dc7c2f 5527 }
e0ab3ab5 5528 spa->spa_avz_action = AVZ_ACTION_REBUILD;
428870ff
BB
5529 vdev_config_dirty(spa->spa_root_vdev);
5530 spa->spa_config_splitting = NULL;
5531 nvlist_free(nvl);
5532 if (error == 0)
5533 dmu_tx_commit(tx);
5534 (void) spa_vdev_exit(spa, NULL, txg, 0);
5535
5536 if (zio_injection_enabled)
5537 zio_handle_panic_injection(spa, FTAG, 3);
5538
5539 /* split is complete; log a history record */
6f1ffb06
MA
5540 spa_history_log_internal(newspa, "split", NULL,
5541 "from pool %s", spa_name(spa));
428870ff
BB
5542
5543 kmem_free(vml, children * sizeof (vdev_t *));
5544
5545 /* if we're not going to mount the filesystems in userland, export */
5546 if (exp)
5547 error = spa_export_common(newname, POOL_STATE_EXPORTED, NULL,
5548 B_FALSE, B_FALSE);
5549
5550 return (error);
5551
5552out:
5553 spa_unload(newspa);
5554 spa_deactivate(newspa);
5555 spa_remove(newspa);
5556
5557 txg = spa_vdev_config_enter(spa);
5558
5559 /* re-online all offlined disks */
5560 for (c = 0; c < children; c++) {
5561 if (vml[c] != NULL)
5562 vml[c]->vdev_offline = B_FALSE;
5563 }
5564 vdev_reopen(spa->spa_root_vdev);
5565
5566 nvlist_free(spa->spa_config_splitting);
5567 spa->spa_config_splitting = NULL;
5568 (void) spa_vdev_exit(spa, NULL, txg, error);
34dc7c2f 5569
428870ff 5570 kmem_free(vml, children * sizeof (vdev_t *));
34dc7c2f
BB
5571 return (error);
5572}
5573
b128c09f
BB
5574static nvlist_t *
5575spa_nvlist_lookup_by_guid(nvlist_t **nvpp, int count, uint64_t target_guid)
34dc7c2f 5576{
1c27024e 5577 for (int i = 0; i < count; i++) {
b128c09f 5578 uint64_t guid;
34dc7c2f 5579
b128c09f
BB
5580 VERIFY(nvlist_lookup_uint64(nvpp[i], ZPOOL_CONFIG_GUID,
5581 &guid) == 0);
34dc7c2f 5582
b128c09f
BB
5583 if (guid == target_guid)
5584 return (nvpp[i]);
34dc7c2f
BB
5585 }
5586
b128c09f 5587 return (NULL);
34dc7c2f
BB
5588}
5589
b128c09f
BB
5590static void
5591spa_vdev_remove_aux(nvlist_t *config, char *name, nvlist_t **dev, int count,
3dfb57a3 5592 nvlist_t *dev_to_remove)
34dc7c2f 5593{
b128c09f 5594 nvlist_t **newdev = NULL;
34dc7c2f 5595
b128c09f 5596 if (count > 1)
79c76d5b 5597 newdev = kmem_alloc((count - 1) * sizeof (void *), KM_SLEEP);
34dc7c2f 5598
1c27024e 5599 for (int i = 0, j = 0; i < count; i++) {
b128c09f
BB
5600 if (dev[i] == dev_to_remove)
5601 continue;
79c76d5b 5602 VERIFY(nvlist_dup(dev[i], &newdev[j++], KM_SLEEP) == 0);
34dc7c2f
BB
5603 }
5604
b128c09f
BB
5605 VERIFY(nvlist_remove(config, name, DATA_TYPE_NVLIST_ARRAY) == 0);
5606 VERIFY(nvlist_add_nvlist_array(config, name, newdev, count - 1) == 0);
34dc7c2f 5607
1c27024e 5608 for (int i = 0; i < count - 1; i++)
b128c09f 5609 nvlist_free(newdev[i]);
34dc7c2f 5610
b128c09f
BB
5611 if (count > 1)
5612 kmem_free(newdev, (count - 1) * sizeof (void *));
34dc7c2f
BB
5613}
5614
428870ff
BB
5615/*
5616 * Evacuate the device.
5617 */
5618static int
5619spa_vdev_remove_evacuate(spa_t *spa, vdev_t *vd)
5620{
5621 uint64_t txg;
5622 int error = 0;
5623
5624 ASSERT(MUTEX_HELD(&spa_namespace_lock));
5625 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
5626 ASSERT(vd == vd->vdev_top);
5627
5628 /*
5629 * Evacuate the device. We don't hold the config lock as writer
5630 * since we need to do I/O but we do keep the
5631 * spa_namespace_lock held. Once this completes the device
5632 * should no longer have any blocks allocated on it.
5633 */
5634 if (vd->vdev_islog) {
5635 if (vd->vdev_stat.vs_alloc != 0)
5636 error = spa_offline_log(spa);
5637 } else {
2e528b49 5638 error = SET_ERROR(ENOTSUP);
428870ff
BB
5639 }
5640
5641 if (error)
5642 return (error);
5643
5644 /*
5645 * The evacuation succeeded. Remove any remaining MOS metadata
5646 * associated with this vdev, and wait for these changes to sync.
5647 */
c99c9001 5648 ASSERT0(vd->vdev_stat.vs_alloc);
428870ff
BB
5649 txg = spa_vdev_config_enter(spa);
5650 vd->vdev_removing = B_TRUE;
93cf2076 5651 vdev_dirty_leaves(vd, VDD_DTL, txg);
428870ff
BB
5652 vdev_config_dirty(vd);
5653 spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
5654
5655 return (0);
5656}
5657
5658/*
5659 * Complete the removal by cleaning up the namespace.
5660 */
5661static void
5662spa_vdev_remove_from_namespace(spa_t *spa, vdev_t *vd)
5663{
5664 vdev_t *rvd = spa->spa_root_vdev;
5665 uint64_t id = vd->vdev_id;
5666 boolean_t last_vdev = (id == (rvd->vdev_children - 1));
5667
5668 ASSERT(MUTEX_HELD(&spa_namespace_lock));
5669 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
5670 ASSERT(vd == vd->vdev_top);
5671
5672 /*
5673 * Only remove any devices which are empty.
5674 */
5675 if (vd->vdev_stat.vs_alloc != 0)
5676 return;
5677
5678 (void) vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
5679
5680 if (list_link_active(&vd->vdev_state_dirty_node))
5681 vdev_state_clean(vd);
5682 if (list_link_active(&vd->vdev_config_dirty_node))
5683 vdev_config_clean(vd);
5684
5685 vdev_free(vd);
5686
5687 if (last_vdev) {
5688 vdev_compact_children(rvd);
5689 } else {
5690 vd = vdev_alloc_common(spa, id, 0, &vdev_hole_ops);
5691 vdev_add_child(rvd, vd);
5692 }
5693 vdev_config_dirty(rvd);
5694
5695 /*
5696 * Reassess the health of our root vdev.
5697 */
5698 vdev_reopen(rvd);
5699}
5700
5701/*
5702 * Remove a device from the pool -
5703 *
5704 * Removing a device from the vdev namespace requires several steps
5705 * and can take a significant amount of time. As a result we use
5706 * the spa_vdev_config_[enter/exit] functions which allow us to
5707 * grab and release the spa_config_lock while still holding the namespace
5708 * lock. During each step the configuration is synced out.
d3cc8b15
WA
5709 *
5710 * Currently, this supports removing only hot spares, slogs, and level 2 ARC
5711 * devices.
34dc7c2f
BB
5712 */
5713int
5714spa_vdev_remove(spa_t *spa, uint64_t guid, boolean_t unspare)
5715{
5716 vdev_t *vd;
12fa0466 5717 sysevent_t *ev = NULL;
428870ff 5718 metaslab_group_t *mg;
b128c09f 5719 nvlist_t **spares, **l2cache, *nv;
fb5f0bc8 5720 uint64_t txg = 0;
428870ff 5721 uint_t nspares, nl2cache;
34dc7c2f 5722 int error = 0;
fb5f0bc8 5723 boolean_t locked = MUTEX_HELD(&spa_namespace_lock);
34dc7c2f 5724
572e2857
BB
5725 ASSERT(spa_writeable(spa));
5726
fb5f0bc8
BB
5727 if (!locked)
5728 txg = spa_vdev_enter(spa);
34dc7c2f 5729
b128c09f 5730 vd = spa_lookup_by_guid(spa, guid, B_FALSE);
34dc7c2f
BB
5731
5732 if (spa->spa_spares.sav_vdevs != NULL &&
34dc7c2f 5733 nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
b128c09f
BB
5734 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0 &&
5735 (nv = spa_nvlist_lookup_by_guid(spares, nspares, guid)) != NULL) {
5736 /*
5737 * Only remove the hot spare if it's not currently in use
5738 * in this pool.
5739 */
5740 if (vd == NULL || unspare) {
6325e48f
GM
5741 if (vd == NULL)
5742 vd = spa_lookup_by_guid(spa, guid, B_TRUE);
12fa0466
DE
5743 ev = spa_event_create(spa, vd, NULL,
5744 ESC_ZFS_VDEV_REMOVE_AUX);
b128c09f
BB
5745 spa_vdev_remove_aux(spa->spa_spares.sav_config,
5746 ZPOOL_CONFIG_SPARES, spares, nspares, nv);
5747 spa_load_spares(spa);
5748 spa->spa_spares.sav_sync = B_TRUE;
5749 } else {
2e528b49 5750 error = SET_ERROR(EBUSY);
b128c09f
BB
5751 }
5752 } else if (spa->spa_l2cache.sav_vdevs != NULL &&
34dc7c2f 5753 nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
b128c09f
BB
5754 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0 &&
5755 (nv = spa_nvlist_lookup_by_guid(l2cache, nl2cache, guid)) != NULL) {
5756 /*
5757 * Cache devices can always be removed.
5758 */
6325e48f 5759 vd = spa_lookup_by_guid(spa, guid, B_TRUE);
12fa0466 5760 ev = spa_event_create(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE_AUX);
b128c09f
BB
5761 spa_vdev_remove_aux(spa->spa_l2cache.sav_config,
5762 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache, nv);
34dc7c2f
BB
5763 spa_load_l2cache(spa);
5764 spa->spa_l2cache.sav_sync = B_TRUE;
428870ff
BB
5765 } else if (vd != NULL && vd->vdev_islog) {
5766 ASSERT(!locked);
5767 ASSERT(vd == vd->vdev_top);
5768
428870ff
BB
5769 mg = vd->vdev_mg;
5770
5771 /*
5772 * Stop allocating from this vdev.
5773 */
5774 metaslab_group_passivate(mg);
5775
5776 /*
5777 * Wait for the youngest allocations and frees to sync,
5778 * and then wait for the deferral of those frees to finish.
5779 */
5780 spa_vdev_config_exit(spa, NULL,
5781 txg + TXG_CONCURRENT_STATES + TXG_DEFER_SIZE, 0, FTAG);
5782
5783 /*
5784 * Attempt to evacuate the vdev.
5785 */
5786 error = spa_vdev_remove_evacuate(spa, vd);
5787
5788 txg = spa_vdev_config_enter(spa);
5789
5790 /*
5791 * If we couldn't evacuate the vdev, unwind.
5792 */
5793 if (error) {
5794 metaslab_group_activate(mg);
5795 return (spa_vdev_exit(spa, NULL, txg, error));
5796 }
5797
5798 /*
5799 * Clean up the vdev namespace.
5800 */
12fa0466 5801 ev = spa_event_create(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE_DEV);
428870ff
BB
5802 spa_vdev_remove_from_namespace(spa, vd);
5803
b128c09f
BB
5804 } else if (vd != NULL) {
5805 /*
5806 * Normal vdevs cannot be removed (yet).
5807 */
2e528b49 5808 error = SET_ERROR(ENOTSUP);
b128c09f
BB
5809 } else {
5810 /*
5811 * There is no vdev of any kind with the specified guid.
5812 */
2e528b49 5813 error = SET_ERROR(ENOENT);
34dc7c2f
BB
5814 }
5815
fb5f0bc8 5816 if (!locked)
e2da829c 5817 error = spa_vdev_exit(spa, NULL, txg, error);
fb5f0bc8 5818
12fa0466
DE
5819 if (ev)
5820 spa_event_post(ev);
5821
fb5f0bc8 5822 return (error);
34dc7c2f
BB
5823}
5824
5825/*
5826 * Find any device that's done replacing, or a vdev marked 'unspare' that's
d3cc8b15 5827 * currently spared, so we can detach it.
34dc7c2f
BB
5828 */
5829static vdev_t *
5830spa_vdev_resilver_done_hunt(vdev_t *vd)
5831{
5832 vdev_t *newvd, *oldvd;
34dc7c2f 5833
1c27024e 5834 for (int c = 0; c < vd->vdev_children; c++) {
34dc7c2f
BB
5835 oldvd = spa_vdev_resilver_done_hunt(vd->vdev_child[c]);
5836 if (oldvd != NULL)
5837 return (oldvd);
5838 }
5839
5840 /*
572e2857
BB
5841 * Check for a completed replacement. We always consider the first
5842 * vdev in the list to be the oldest vdev, and the last one to be
5843 * the newest (see spa_vdev_attach() for how that works). In
5844 * the case where the newest vdev is faulted, we will not automatically
5845 * remove it after a resilver completes. This is OK as it will require
5846 * user intervention to determine which disk the admin wishes to keep.
34dc7c2f 5847 */
572e2857
BB
5848 if (vd->vdev_ops == &vdev_replacing_ops) {
5849 ASSERT(vd->vdev_children > 1);
5850
5851 newvd = vd->vdev_child[vd->vdev_children - 1];
34dc7c2f 5852 oldvd = vd->vdev_child[0];
34dc7c2f 5853
fb5f0bc8 5854 if (vdev_dtl_empty(newvd, DTL_MISSING) &&
428870ff 5855 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
fb5f0bc8 5856 !vdev_dtl_required(oldvd))
34dc7c2f 5857 return (oldvd);
34dc7c2f
BB
5858 }
5859
5860 /*
5861 * Check for a completed resilver with the 'unspare' flag set.
5862 */
572e2857
BB
5863 if (vd->vdev_ops == &vdev_spare_ops) {
5864 vdev_t *first = vd->vdev_child[0];
5865 vdev_t *last = vd->vdev_child[vd->vdev_children - 1];
5866
5867 if (last->vdev_unspare) {
5868 oldvd = first;
5869 newvd = last;
5870 } else if (first->vdev_unspare) {
5871 oldvd = last;
5872 newvd = first;
5873 } else {
5874 oldvd = NULL;
5875 }
34dc7c2f 5876
572e2857 5877 if (oldvd != NULL &&
fb5f0bc8 5878 vdev_dtl_empty(newvd, DTL_MISSING) &&
428870ff 5879 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
572e2857 5880 !vdev_dtl_required(oldvd))
34dc7c2f 5881 return (oldvd);
572e2857
BB
5882
5883 /*
5884 * If there are more than two spares attached to a disk,
5885 * and those spares are not required, then we want to
5886 * attempt to free them up now so that they can be used
5887 * by other pools. Once we're back down to a single
5888 * disk+spare, we stop removing them.
5889 */
5890 if (vd->vdev_children > 2) {
5891 newvd = vd->vdev_child[1];
5892
5893 if (newvd->vdev_isspare && last->vdev_isspare &&
5894 vdev_dtl_empty(last, DTL_MISSING) &&
5895 vdev_dtl_empty(last, DTL_OUTAGE) &&
5896 !vdev_dtl_required(newvd))
5897 return (newvd);
34dc7c2f 5898 }
34dc7c2f
BB
5899 }
5900
5901 return (NULL);
5902}
5903
5904static void
5905spa_vdev_resilver_done(spa_t *spa)
5906{
fb5f0bc8
BB
5907 vdev_t *vd, *pvd, *ppvd;
5908 uint64_t guid, sguid, pguid, ppguid;
34dc7c2f 5909
fb5f0bc8 5910 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f
BB
5911
5912 while ((vd = spa_vdev_resilver_done_hunt(spa->spa_root_vdev)) != NULL) {
fb5f0bc8
BB
5913 pvd = vd->vdev_parent;
5914 ppvd = pvd->vdev_parent;
34dc7c2f 5915 guid = vd->vdev_guid;
fb5f0bc8
BB
5916 pguid = pvd->vdev_guid;
5917 ppguid = ppvd->vdev_guid;
5918 sguid = 0;
34dc7c2f
BB
5919 /*
5920 * If we have just finished replacing a hot spared device, then
5921 * we need to detach the parent's first child (the original hot
5922 * spare) as well.
5923 */
572e2857
BB
5924 if (ppvd->vdev_ops == &vdev_spare_ops && pvd->vdev_id == 0 &&
5925 ppvd->vdev_children == 2) {
34dc7c2f 5926 ASSERT(pvd->vdev_ops == &vdev_replacing_ops);
fb5f0bc8 5927 sguid = ppvd->vdev_child[1]->vdev_guid;
34dc7c2f 5928 }
5d1f7fb6
GW
5929 ASSERT(vd->vdev_resilver_txg == 0 || !vdev_dtl_required(vd));
5930
fb5f0bc8
BB
5931 spa_config_exit(spa, SCL_ALL, FTAG);
5932 if (spa_vdev_detach(spa, guid, pguid, B_TRUE) != 0)
34dc7c2f 5933 return;
fb5f0bc8 5934 if (sguid && spa_vdev_detach(spa, sguid, ppguid, B_TRUE) != 0)
34dc7c2f 5935 return;
fb5f0bc8 5936 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f
BB
5937 }
5938
fb5f0bc8 5939 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
5940}
5941
5942/*
428870ff 5943 * Update the stored path or FRU for this vdev.
34dc7c2f
BB
5944 */
5945int
9babb374
BB
5946spa_vdev_set_common(spa_t *spa, uint64_t guid, const char *value,
5947 boolean_t ispath)
34dc7c2f 5948{
b128c09f 5949 vdev_t *vd;
428870ff 5950 boolean_t sync = B_FALSE;
34dc7c2f 5951
572e2857
BB
5952 ASSERT(spa_writeable(spa));
5953
428870ff 5954 spa_vdev_state_enter(spa, SCL_ALL);
34dc7c2f 5955
9babb374 5956 if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
428870ff 5957 return (spa_vdev_state_exit(spa, NULL, ENOENT));
34dc7c2f
BB
5958
5959 if (!vd->vdev_ops->vdev_op_leaf)
428870ff 5960 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
34dc7c2f 5961
9babb374 5962 if (ispath) {
428870ff
BB
5963 if (strcmp(value, vd->vdev_path) != 0) {
5964 spa_strfree(vd->vdev_path);
5965 vd->vdev_path = spa_strdup(value);
5966 sync = B_TRUE;
5967 }
9babb374 5968 } else {
428870ff
BB
5969 if (vd->vdev_fru == NULL) {
5970 vd->vdev_fru = spa_strdup(value);
5971 sync = B_TRUE;
5972 } else if (strcmp(value, vd->vdev_fru) != 0) {
9babb374 5973 spa_strfree(vd->vdev_fru);
428870ff
BB
5974 vd->vdev_fru = spa_strdup(value);
5975 sync = B_TRUE;
5976 }
9babb374 5977 }
34dc7c2f 5978
428870ff 5979 return (spa_vdev_state_exit(spa, sync ? vd : NULL, 0));
34dc7c2f
BB
5980}
5981
9babb374
BB
5982int
5983spa_vdev_setpath(spa_t *spa, uint64_t guid, const char *newpath)
5984{
5985 return (spa_vdev_set_common(spa, guid, newpath, B_TRUE));
5986}
5987
5988int
5989spa_vdev_setfru(spa_t *spa, uint64_t guid, const char *newfru)
5990{
5991 return (spa_vdev_set_common(spa, guid, newfru, B_FALSE));
5992}
5993
34dc7c2f
BB
5994/*
5995 * ==========================================================================
428870ff 5996 * SPA Scanning
34dc7c2f
BB
5997 * ==========================================================================
5998 */
0ea05c64
AP
5999int
6000spa_scrub_pause_resume(spa_t *spa, pool_scrub_cmd_t cmd)
6001{
6002 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
6003
6004 if (dsl_scan_resilvering(spa->spa_dsl_pool))
6005 return (SET_ERROR(EBUSY));
6006
6007 return (dsl_scrub_set_pause_resume(spa->spa_dsl_pool, cmd));
6008}
34dc7c2f 6009
34dc7c2f 6010int
428870ff
BB
6011spa_scan_stop(spa_t *spa)
6012{
6013 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
6014 if (dsl_scan_resilvering(spa->spa_dsl_pool))
2e528b49 6015 return (SET_ERROR(EBUSY));
428870ff
BB
6016 return (dsl_scan_cancel(spa->spa_dsl_pool));
6017}
6018
6019int
6020spa_scan(spa_t *spa, pool_scan_func_t func)
34dc7c2f 6021{
b128c09f 6022 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
34dc7c2f 6023
428870ff 6024 if (func >= POOL_SCAN_FUNCS || func == POOL_SCAN_NONE)
2e528b49 6025 return (SET_ERROR(ENOTSUP));
34dc7c2f 6026
34dc7c2f 6027 /*
b128c09f
BB
6028 * If a resilver was requested, but there is no DTL on a
6029 * writeable leaf device, we have nothing to do.
34dc7c2f 6030 */
428870ff 6031 if (func == POOL_SCAN_RESILVER &&
b128c09f
BB
6032 !vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL)) {
6033 spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
34dc7c2f
BB
6034 return (0);
6035 }
6036
428870ff 6037 return (dsl_scan(spa->spa_dsl_pool, func));
34dc7c2f
BB
6038}
6039
6040/*
6041 * ==========================================================================
6042 * SPA async task processing
6043 * ==========================================================================
6044 */
6045
6046static void
6047spa_async_remove(spa_t *spa, vdev_t *vd)
6048{
b128c09f 6049 if (vd->vdev_remove_wanted) {
428870ff
BB
6050 vd->vdev_remove_wanted = B_FALSE;
6051 vd->vdev_delayed_close = B_FALSE;
b128c09f 6052 vdev_set_state(vd, B_FALSE, VDEV_STATE_REMOVED, VDEV_AUX_NONE);
428870ff
BB
6053
6054 /*
6055 * We want to clear the stats, but we don't want to do a full
6056 * vdev_clear() as that will cause us to throw away
6057 * degraded/faulted state as well as attempt to reopen the
6058 * device, all of which is a waste.
6059 */
6060 vd->vdev_stat.vs_read_errors = 0;
6061 vd->vdev_stat.vs_write_errors = 0;
6062 vd->vdev_stat.vs_checksum_errors = 0;
6063
b128c09f
BB
6064 vdev_state_dirty(vd->vdev_top);
6065 }
34dc7c2f 6066
1c27024e 6067 for (int c = 0; c < vd->vdev_children; c++)
b128c09f
BB
6068 spa_async_remove(spa, vd->vdev_child[c]);
6069}
6070
6071static void
6072spa_async_probe(spa_t *spa, vdev_t *vd)
6073{
6074 if (vd->vdev_probe_wanted) {
428870ff 6075 vd->vdev_probe_wanted = B_FALSE;
b128c09f 6076 vdev_reopen(vd); /* vdev_open() does the actual probe */
34dc7c2f 6077 }
b128c09f 6078
1c27024e 6079 for (int c = 0; c < vd->vdev_children; c++)
b128c09f 6080 spa_async_probe(spa, vd->vdev_child[c]);
34dc7c2f
BB
6081}
6082
9babb374
BB
6083static void
6084spa_async_autoexpand(spa_t *spa, vdev_t *vd)
6085{
9babb374
BB
6086 if (!spa->spa_autoexpand)
6087 return;
6088
1c27024e 6089 for (int c = 0; c < vd->vdev_children; c++) {
9babb374
BB
6090 vdev_t *cvd = vd->vdev_child[c];
6091 spa_async_autoexpand(spa, cvd);
6092 }
6093
6094 if (!vd->vdev_ops->vdev_op_leaf || vd->vdev_physpath == NULL)
6095 return;
6096
12fa0466 6097 spa_event_notify(vd->vdev_spa, vd, NULL, ESC_ZFS_VDEV_AUTOEXPAND);
9babb374
BB
6098}
6099
34dc7c2f 6100static void
c25b8f99 6101spa_async_thread(void *arg)
34dc7c2f 6102{
c25b8f99 6103 spa_t *spa = (spa_t *)arg;
867959b5 6104 int tasks;
34dc7c2f
BB
6105
6106 ASSERT(spa->spa_sync_on);
6107
6108 mutex_enter(&spa->spa_async_lock);
6109 tasks = spa->spa_async_tasks;
6110 spa->spa_async_tasks = 0;
6111 mutex_exit(&spa->spa_async_lock);
6112
6113 /*
6114 * See if the config needs to be updated.
6115 */
6116 if (tasks & SPA_ASYNC_CONFIG_UPDATE) {
428870ff 6117 uint64_t old_space, new_space;
9babb374 6118
34dc7c2f 6119 mutex_enter(&spa_namespace_lock);
428870ff 6120 old_space = metaslab_class_get_space(spa_normal_class(spa));
34dc7c2f 6121 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
428870ff 6122 new_space = metaslab_class_get_space(spa_normal_class(spa));
34dc7c2f 6123 mutex_exit(&spa_namespace_lock);
9babb374
BB
6124
6125 /*
6126 * If the pool grew as a result of the config update,
6127 * then log an internal history event.
6128 */
428870ff 6129 if (new_space != old_space) {
6f1ffb06 6130 spa_history_log_internal(spa, "vdev online", NULL,
45d1cae3 6131 "pool '%s' size: %llu(+%llu)",
428870ff 6132 spa_name(spa), new_space, new_space - old_space);
9babb374 6133 }
34dc7c2f
BB
6134 }
6135
6136 /*
6137 * See if any devices need to be marked REMOVED.
34dc7c2f 6138 */
b128c09f 6139 if (tasks & SPA_ASYNC_REMOVE) {
428870ff 6140 spa_vdev_state_enter(spa, SCL_NONE);
34dc7c2f 6141 spa_async_remove(spa, spa->spa_root_vdev);
867959b5 6142 for (int i = 0; i < spa->spa_l2cache.sav_count; i++)
b128c09f 6143 spa_async_remove(spa, spa->spa_l2cache.sav_vdevs[i]);
867959b5 6144 for (int i = 0; i < spa->spa_spares.sav_count; i++)
b128c09f
BB
6145 spa_async_remove(spa, spa->spa_spares.sav_vdevs[i]);
6146 (void) spa_vdev_state_exit(spa, NULL, 0);
34dc7c2f
BB
6147 }
6148
9babb374
BB
6149 if ((tasks & SPA_ASYNC_AUTOEXPAND) && !spa_suspended(spa)) {
6150 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
6151 spa_async_autoexpand(spa, spa->spa_root_vdev);
6152 spa_config_exit(spa, SCL_CONFIG, FTAG);
6153 }
6154
34dc7c2f 6155 /*
b128c09f 6156 * See if any devices need to be probed.
34dc7c2f 6157 */
b128c09f 6158 if (tasks & SPA_ASYNC_PROBE) {
428870ff 6159 spa_vdev_state_enter(spa, SCL_NONE);
b128c09f
BB
6160 spa_async_probe(spa, spa->spa_root_vdev);
6161 (void) spa_vdev_state_exit(spa, NULL, 0);
6162 }
34dc7c2f
BB
6163
6164 /*
b128c09f 6165 * If any devices are done replacing, detach them.
34dc7c2f 6166 */
b128c09f
BB
6167 if (tasks & SPA_ASYNC_RESILVER_DONE)
6168 spa_vdev_resilver_done(spa);
34dc7c2f
BB
6169
6170 /*
6171 * Kick off a resilver.
6172 */
b128c09f 6173 if (tasks & SPA_ASYNC_RESILVER)
428870ff 6174 dsl_resilver_restart(spa->spa_dsl_pool, 0);
34dc7c2f
BB
6175
6176 /*
6177 * Let the world know that we're done.
6178 */
6179 mutex_enter(&spa->spa_async_lock);
6180 spa->spa_async_thread = NULL;
6181 cv_broadcast(&spa->spa_async_cv);
6182 mutex_exit(&spa->spa_async_lock);
6183 thread_exit();
6184}
6185
6186void
6187spa_async_suspend(spa_t *spa)
6188{
6189 mutex_enter(&spa->spa_async_lock);
6190 spa->spa_async_suspended++;
6191 while (spa->spa_async_thread != NULL)
6192 cv_wait(&spa->spa_async_cv, &spa->spa_async_lock);
6193 mutex_exit(&spa->spa_async_lock);
6194}
6195
6196void
6197spa_async_resume(spa_t *spa)
6198{
6199 mutex_enter(&spa->spa_async_lock);
6200 ASSERT(spa->spa_async_suspended != 0);
6201 spa->spa_async_suspended--;
6202 mutex_exit(&spa->spa_async_lock);
6203}
6204
e6cfd633
WA
6205static boolean_t
6206spa_async_tasks_pending(spa_t *spa)
6207{
6208 uint_t non_config_tasks;
6209 uint_t config_task;
6210 boolean_t config_task_suspended;
6211
6212 non_config_tasks = spa->spa_async_tasks & ~SPA_ASYNC_CONFIG_UPDATE;
6213 config_task = spa->spa_async_tasks & SPA_ASYNC_CONFIG_UPDATE;
6214 if (spa->spa_ccw_fail_time == 0) {
6215 config_task_suspended = B_FALSE;
6216 } else {
6217 config_task_suspended =
6218 (gethrtime() - spa->spa_ccw_fail_time) <
05852b34 6219 ((hrtime_t)zfs_ccw_retry_interval * NANOSEC);
e6cfd633
WA
6220 }
6221
6222 return (non_config_tasks || (config_task && !config_task_suspended));
6223}
6224
34dc7c2f
BB
6225static void
6226spa_async_dispatch(spa_t *spa)
6227{
6228 mutex_enter(&spa->spa_async_lock);
e6cfd633
WA
6229 if (spa_async_tasks_pending(spa) &&
6230 !spa->spa_async_suspended &&
34dc7c2f 6231 spa->spa_async_thread == NULL &&
e6cfd633 6232 rootdir != NULL)
34dc7c2f
BB
6233 spa->spa_async_thread = thread_create(NULL, 0,
6234 spa_async_thread, spa, 0, &p0, TS_RUN, maxclsyspri);
6235 mutex_exit(&spa->spa_async_lock);
6236}
6237
6238void
6239spa_async_request(spa_t *spa, int task)
6240{
428870ff 6241 zfs_dbgmsg("spa=%s async request task=%u", spa->spa_name, task);
34dc7c2f
BB
6242 mutex_enter(&spa->spa_async_lock);
6243 spa->spa_async_tasks |= task;
6244 mutex_exit(&spa->spa_async_lock);
6245}
6246
6247/*
6248 * ==========================================================================
6249 * SPA syncing routines
6250 * ==========================================================================
6251 */
6252
428870ff
BB
6253static int
6254bpobj_enqueue_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
34dc7c2f 6255{
428870ff
BB
6256 bpobj_t *bpo = arg;
6257 bpobj_enqueue(bpo, bp, tx);
6258 return (0);
6259}
34dc7c2f 6260
428870ff
BB
6261static int
6262spa_free_sync_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
6263{
6264 zio_t *zio = arg;
34dc7c2f 6265
428870ff
BB
6266 zio_nowait(zio_free_sync(zio, zio->io_spa, dmu_tx_get_txg(tx), bp,
6267 zio->io_flags));
6268 return (0);
34dc7c2f
BB
6269}
6270
e8b96c60
MA
6271/*
6272 * Note: this simple function is not inlined to make it easier to dtrace the
6273 * amount of time spent syncing frees.
6274 */
6275static void
6276spa_sync_frees(spa_t *spa, bplist_t *bpl, dmu_tx_t *tx)
6277{
6278 zio_t *zio = zio_root(spa, NULL, NULL, 0);
6279 bplist_iterate(bpl, spa_free_sync_cb, zio, tx);
6280 VERIFY(zio_wait(zio) == 0);
6281}
6282
6283/*
6284 * Note: this simple function is not inlined to make it easier to dtrace the
6285 * amount of time spent syncing deferred frees.
6286 */
6287static void
6288spa_sync_deferred_frees(spa_t *spa, dmu_tx_t *tx)
6289{
6290 zio_t *zio = zio_root(spa, NULL, NULL, 0);
6291 VERIFY3U(bpobj_iterate(&spa->spa_deferred_bpobj,
6292 spa_free_sync_cb, zio, tx), ==, 0);
6293 VERIFY0(zio_wait(zio));
6294}
6295
34dc7c2f
BB
6296static void
6297spa_sync_nvlist(spa_t *spa, uint64_t obj, nvlist_t *nv, dmu_tx_t *tx)
6298{
6299 char *packed = NULL;
b128c09f 6300 size_t bufsize;
34dc7c2f
BB
6301 size_t nvsize = 0;
6302 dmu_buf_t *db;
6303
6304 VERIFY(nvlist_size(nv, &nvsize, NV_ENCODE_XDR) == 0);
6305
b128c09f
BB
6306 /*
6307 * Write full (SPA_CONFIG_BLOCKSIZE) blocks of configuration
b0bc7a84 6308 * information. This avoids the dmu_buf_will_dirty() path and
b128c09f
BB
6309 * saves us a pre-read to get data we don't actually care about.
6310 */
9ae529ec 6311 bufsize = P2ROUNDUP((uint64_t)nvsize, SPA_CONFIG_BLOCKSIZE);
79c76d5b 6312 packed = vmem_alloc(bufsize, KM_SLEEP);
34dc7c2f
BB
6313
6314 VERIFY(nvlist_pack(nv, &packed, &nvsize, NV_ENCODE_XDR,
79c76d5b 6315 KM_SLEEP) == 0);
b128c09f 6316 bzero(packed + nvsize, bufsize - nvsize);
34dc7c2f 6317
b128c09f 6318 dmu_write(spa->spa_meta_objset, obj, 0, bufsize, packed, tx);
34dc7c2f 6319
00b46022 6320 vmem_free(packed, bufsize);
34dc7c2f
BB
6321
6322 VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
6323 dmu_buf_will_dirty(db, tx);
6324 *(uint64_t *)db->db_data = nvsize;
6325 dmu_buf_rele(db, FTAG);
6326}
6327
6328static void
6329spa_sync_aux_dev(spa_t *spa, spa_aux_vdev_t *sav, dmu_tx_t *tx,
6330 const char *config, const char *entry)
6331{
6332 nvlist_t *nvroot;
6333 nvlist_t **list;
6334 int i;
6335
6336 if (!sav->sav_sync)
6337 return;
6338
6339 /*
6340 * Update the MOS nvlist describing the list of available devices.
6341 * spa_validate_aux() will have already made sure this nvlist is
6342 * valid and the vdevs are labeled appropriately.
6343 */
6344 if (sav->sav_object == 0) {
6345 sav->sav_object = dmu_object_alloc(spa->spa_meta_objset,
6346 DMU_OT_PACKED_NVLIST, 1 << 14, DMU_OT_PACKED_NVLIST_SIZE,
6347 sizeof (uint64_t), tx);
6348 VERIFY(zap_update(spa->spa_meta_objset,
6349 DMU_POOL_DIRECTORY_OBJECT, entry, sizeof (uint64_t), 1,
6350 &sav->sav_object, tx) == 0);
6351 }
6352
79c76d5b 6353 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
34dc7c2f
BB
6354 if (sav->sav_count == 0) {
6355 VERIFY(nvlist_add_nvlist_array(nvroot, config, NULL, 0) == 0);
6356 } else {
79c76d5b 6357 list = kmem_alloc(sav->sav_count*sizeof (void *), KM_SLEEP);
34dc7c2f
BB
6358 for (i = 0; i < sav->sav_count; i++)
6359 list[i] = vdev_config_generate(spa, sav->sav_vdevs[i],
428870ff 6360 B_FALSE, VDEV_CONFIG_L2CACHE);
34dc7c2f
BB
6361 VERIFY(nvlist_add_nvlist_array(nvroot, config, list,
6362 sav->sav_count) == 0);
6363 for (i = 0; i < sav->sav_count; i++)
6364 nvlist_free(list[i]);
6365 kmem_free(list, sav->sav_count * sizeof (void *));
6366 }
6367
6368 spa_sync_nvlist(spa, sav->sav_object, nvroot, tx);
6369 nvlist_free(nvroot);
6370
6371 sav->sav_sync = B_FALSE;
6372}
6373
e0ab3ab5
JS
6374/*
6375 * Rebuild spa's all-vdev ZAP from the vdev ZAPs indicated in each vdev_t.
6376 * The all-vdev ZAP must be empty.
6377 */
6378static void
6379spa_avz_build(vdev_t *vd, uint64_t avz, dmu_tx_t *tx)
6380{
6381 spa_t *spa = vd->vdev_spa;
e0ab3ab5
JS
6382
6383 if (vd->vdev_top_zap != 0) {
6384 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
6385 vd->vdev_top_zap, tx));
6386 }
6387 if (vd->vdev_leaf_zap != 0) {
6388 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
6389 vd->vdev_leaf_zap, tx));
6390 }
1c27024e 6391 for (uint64_t i = 0; i < vd->vdev_children; i++) {
e0ab3ab5
JS
6392 spa_avz_build(vd->vdev_child[i], avz, tx);
6393 }
6394}
6395
34dc7c2f
BB
6396static void
6397spa_sync_config_object(spa_t *spa, dmu_tx_t *tx)
6398{
6399 nvlist_t *config;
6400
e0ab3ab5
JS
6401 /*
6402 * If the pool is being imported from a pre-per-vdev-ZAP version of ZFS,
6403 * its config may not be dirty but we still need to build per-vdev ZAPs.
6404 * Similarly, if the pool is being assembled (e.g. after a split), we
6405 * need to rebuild the AVZ although the config may not be dirty.
6406 */
6407 if (list_is_empty(&spa->spa_config_dirty_list) &&
6408 spa->spa_avz_action == AVZ_ACTION_NONE)
34dc7c2f
BB
6409 return;
6410
b128c09f
BB
6411 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
6412
e0ab3ab5 6413 ASSERT(spa->spa_avz_action == AVZ_ACTION_NONE ||
38640550 6414 spa->spa_avz_action == AVZ_ACTION_INITIALIZE ||
e0ab3ab5
JS
6415 spa->spa_all_vdev_zaps != 0);
6416
6417 if (spa->spa_avz_action == AVZ_ACTION_REBUILD) {
e0ab3ab5
JS
6418 /* Make and build the new AVZ */
6419 uint64_t new_avz = zap_create(spa->spa_meta_objset,
6420 DMU_OTN_ZAP_METADATA, DMU_OT_NONE, 0, tx);
6421 spa_avz_build(spa->spa_root_vdev, new_avz, tx);
6422
6423 /* Diff old AVZ with new one */
1c27024e
DB
6424 zap_cursor_t zc;
6425 zap_attribute_t za;
6426
e0ab3ab5
JS
6427 for (zap_cursor_init(&zc, spa->spa_meta_objset,
6428 spa->spa_all_vdev_zaps);
6429 zap_cursor_retrieve(&zc, &za) == 0;
6430 zap_cursor_advance(&zc)) {
6431 uint64_t vdzap = za.za_first_integer;
6432 if (zap_lookup_int(spa->spa_meta_objset, new_avz,
6433 vdzap) == ENOENT) {
6434 /*
6435 * ZAP is listed in old AVZ but not in new one;
6436 * destroy it
6437 */
6438 VERIFY0(zap_destroy(spa->spa_meta_objset, vdzap,
6439 tx));
6440 }
6441 }
6442
6443 zap_cursor_fini(&zc);
6444
6445 /* Destroy the old AVZ */
6446 VERIFY0(zap_destroy(spa->spa_meta_objset,
6447 spa->spa_all_vdev_zaps, tx));
6448
6449 /* Replace the old AVZ in the dir obj with the new one */
6450 VERIFY0(zap_update(spa->spa_meta_objset,
6451 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP,
6452 sizeof (new_avz), 1, &new_avz, tx));
6453
6454 spa->spa_all_vdev_zaps = new_avz;
6455 } else if (spa->spa_avz_action == AVZ_ACTION_DESTROY) {
6456 zap_cursor_t zc;
6457 zap_attribute_t za;
6458
6459 /* Walk through the AVZ and destroy all listed ZAPs */
6460 for (zap_cursor_init(&zc, spa->spa_meta_objset,
6461 spa->spa_all_vdev_zaps);
6462 zap_cursor_retrieve(&zc, &za) == 0;
6463 zap_cursor_advance(&zc)) {
6464 uint64_t zap = za.za_first_integer;
6465 VERIFY0(zap_destroy(spa->spa_meta_objset, zap, tx));
6466 }
6467
6468 zap_cursor_fini(&zc);
6469
6470 /* Destroy and unlink the AVZ itself */
6471 VERIFY0(zap_destroy(spa->spa_meta_objset,
6472 spa->spa_all_vdev_zaps, tx));
6473 VERIFY0(zap_remove(spa->spa_meta_objset,
6474 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP, tx));
6475 spa->spa_all_vdev_zaps = 0;
6476 }
6477
6478 if (spa->spa_all_vdev_zaps == 0) {
6479 spa->spa_all_vdev_zaps = zap_create_link(spa->spa_meta_objset,
6480 DMU_OTN_ZAP_METADATA, DMU_POOL_DIRECTORY_OBJECT,
6481 DMU_POOL_VDEV_ZAP_MAP, tx);
6482 }
6483 spa->spa_avz_action = AVZ_ACTION_NONE;
6484
6485 /* Create ZAPs for vdevs that don't have them. */
6486 vdev_construct_zaps(spa->spa_root_vdev, tx);
6487
b128c09f
BB
6488 config = spa_config_generate(spa, spa->spa_root_vdev,
6489 dmu_tx_get_txg(tx), B_FALSE);
6490
ea0b2538
GW
6491 /*
6492 * If we're upgrading the spa version then make sure that
6493 * the config object gets updated with the correct version.
6494 */
6495 if (spa->spa_ubsync.ub_version < spa->spa_uberblock.ub_version)
6496 fnvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
6497 spa->spa_uberblock.ub_version);
6498
b128c09f 6499 spa_config_exit(spa, SCL_STATE, FTAG);
34dc7c2f 6500
8a5fc748 6501 nvlist_free(spa->spa_config_syncing);
34dc7c2f
BB
6502 spa->spa_config_syncing = config;
6503
6504 spa_sync_nvlist(spa, spa->spa_config_object, config, tx);
6505}
6506
9ae529ec 6507static void
13fe0198 6508spa_sync_version(void *arg, dmu_tx_t *tx)
9ae529ec 6509{
13fe0198
MA
6510 uint64_t *versionp = arg;
6511 uint64_t version = *versionp;
6512 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
9ae529ec
CS
6513
6514 /*
6515 * Setting the version is special cased when first creating the pool.
6516 */
6517 ASSERT(tx->tx_txg != TXG_INITIAL);
6518
8dca0a9a 6519 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
9ae529ec
CS
6520 ASSERT(version >= spa_version(spa));
6521
6522 spa->spa_uberblock.ub_version = version;
6523 vdev_config_dirty(spa->spa_root_vdev);
6f1ffb06 6524 spa_history_log_internal(spa, "set", tx, "version=%lld", version);
9ae529ec
CS
6525}
6526
34dc7c2f
BB
6527/*
6528 * Set zpool properties.
6529 */
6530static void
13fe0198 6531spa_sync_props(void *arg, dmu_tx_t *tx)
34dc7c2f 6532{
13fe0198
MA
6533 nvlist_t *nvp = arg;
6534 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
34dc7c2f 6535 objset_t *mos = spa->spa_meta_objset;
9ae529ec 6536 nvpair_t *elem = NULL;
b128c09f
BB
6537
6538 mutex_enter(&spa->spa_props_lock);
34dc7c2f 6539
34dc7c2f 6540 while ((elem = nvlist_next_nvpair(nvp, elem))) {
9ae529ec
CS
6541 uint64_t intval;
6542 char *strval, *fname;
6543 zpool_prop_t prop;
6544 const char *propname;
6545 zprop_type_t proptype;
fa86b5db 6546 spa_feature_t fid;
9ae529ec 6547
31864e3d
BB
6548 switch (prop = zpool_name_to_prop(nvpair_name(elem))) {
6549 case ZPOOL_PROP_INVAL:
9ae529ec
CS
6550 /*
6551 * We checked this earlier in spa_prop_validate().
6552 */
6553 ASSERT(zpool_prop_feature(nvpair_name(elem)));
6554
6555 fname = strchr(nvpair_name(elem), '@') + 1;
fa86b5db 6556 VERIFY0(zfeature_lookup_name(fname, &fid));
9ae529ec 6557
fa86b5db 6558 spa_feature_enable(spa, fid, tx);
6f1ffb06
MA
6559 spa_history_log_internal(spa, "set", tx,
6560 "%s=enabled", nvpair_name(elem));
9ae529ec
CS
6561 break;
6562
34dc7c2f 6563 case ZPOOL_PROP_VERSION:
93cf2076 6564 intval = fnvpair_value_uint64(elem);
34dc7c2f 6565 /*
4e33ba4c 6566 * The version is synced separately before other
9ae529ec 6567 * properties and should be correct by now.
34dc7c2f 6568 */
9ae529ec 6569 ASSERT3U(spa_version(spa), >=, intval);
34dc7c2f
BB
6570 break;
6571
6572 case ZPOOL_PROP_ALTROOT:
6573 /*
6574 * 'altroot' is a non-persistent property. It should
6575 * have been set temporarily at creation or import time.
6576 */
6577 ASSERT(spa->spa_root != NULL);
6578 break;
6579
572e2857 6580 case ZPOOL_PROP_READONLY:
34dc7c2f
BB
6581 case ZPOOL_PROP_CACHEFILE:
6582 /*
572e2857
BB
6583 * 'readonly' and 'cachefile' are also non-persisitent
6584 * properties.
34dc7c2f 6585 */
34dc7c2f 6586 break;
d96eb2b1 6587 case ZPOOL_PROP_COMMENT:
93cf2076 6588 strval = fnvpair_value_string(elem);
d96eb2b1
DM
6589 if (spa->spa_comment != NULL)
6590 spa_strfree(spa->spa_comment);
6591 spa->spa_comment = spa_strdup(strval);
6592 /*
6593 * We need to dirty the configuration on all the vdevs
6594 * so that their labels get updated. It's unnecessary
6595 * to do this for pool creation since the vdev's
4e33ba4c 6596 * configuration has already been dirtied.
d96eb2b1
DM
6597 */
6598 if (tx->tx_txg != TXG_INITIAL)
6599 vdev_config_dirty(spa->spa_root_vdev);
6f1ffb06
MA
6600 spa_history_log_internal(spa, "set", tx,
6601 "%s=%s", nvpair_name(elem), strval);
d96eb2b1 6602 break;
34dc7c2f
BB
6603 default:
6604 /*
6605 * Set pool property values in the poolprops mos object.
6606 */
34dc7c2f 6607 if (spa->spa_pool_props_object == 0) {
9ae529ec
CS
6608 spa->spa_pool_props_object =
6609 zap_create_link(mos, DMU_OT_POOL_PROPS,
34dc7c2f 6610 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_PROPS,
9ae529ec 6611 tx);
34dc7c2f 6612 }
34dc7c2f
BB
6613
6614 /* normalize the property name */
6615 propname = zpool_prop_to_name(prop);
6616 proptype = zpool_prop_get_type(prop);
6617
6618 if (nvpair_type(elem) == DATA_TYPE_STRING) {
6619 ASSERT(proptype == PROP_TYPE_STRING);
93cf2076
GW
6620 strval = fnvpair_value_string(elem);
6621 VERIFY0(zap_update(mos,
34dc7c2f 6622 spa->spa_pool_props_object, propname,
93cf2076 6623 1, strlen(strval) + 1, strval, tx));
6f1ffb06
MA
6624 spa_history_log_internal(spa, "set", tx,
6625 "%s=%s", nvpair_name(elem), strval);
34dc7c2f 6626 } else if (nvpair_type(elem) == DATA_TYPE_UINT64) {
93cf2076 6627 intval = fnvpair_value_uint64(elem);
34dc7c2f
BB
6628
6629 if (proptype == PROP_TYPE_INDEX) {
6630 const char *unused;
93cf2076
GW
6631 VERIFY0(zpool_prop_index_to_string(
6632 prop, intval, &unused));
34dc7c2f 6633 }
93cf2076 6634 VERIFY0(zap_update(mos,
34dc7c2f 6635 spa->spa_pool_props_object, propname,
93cf2076 6636 8, 1, &intval, tx));
6f1ffb06
MA
6637 spa_history_log_internal(spa, "set", tx,
6638 "%s=%lld", nvpair_name(elem), intval);
34dc7c2f
BB
6639 } else {
6640 ASSERT(0); /* not allowed */
6641 }
6642
6643 switch (prop) {
6644 case ZPOOL_PROP_DELEGATION:
6645 spa->spa_delegation = intval;
6646 break;
6647 case ZPOOL_PROP_BOOTFS:
6648 spa->spa_bootfs = intval;
6649 break;
6650 case ZPOOL_PROP_FAILUREMODE:
6651 spa->spa_failmode = intval;
6652 break;
9babb374
BB
6653 case ZPOOL_PROP_AUTOEXPAND:
6654 spa->spa_autoexpand = intval;
428870ff
BB
6655 if (tx->tx_txg != TXG_INITIAL)
6656 spa_async_request(spa,
6657 SPA_ASYNC_AUTOEXPAND);
6658 break;
379ca9cf
OF
6659 case ZPOOL_PROP_MULTIHOST:
6660 spa->spa_multihost = intval;
6661 break;
428870ff
BB
6662 case ZPOOL_PROP_DEDUPDITTO:
6663 spa->spa_dedup_ditto = intval;
9babb374 6664 break;
34dc7c2f
BB
6665 default:
6666 break;
6667 }
6668 }
6669
34dc7c2f 6670 }
b128c09f
BB
6671
6672 mutex_exit(&spa->spa_props_lock);
34dc7c2f
BB
6673}
6674
428870ff
BB
6675/*
6676 * Perform one-time upgrade on-disk changes. spa_version() does not
6677 * reflect the new version this txg, so there must be no changes this
6678 * txg to anything that the upgrade code depends on after it executes.
6679 * Therefore this must be called after dsl_pool_sync() does the sync
6680 * tasks.
6681 */
6682static void
6683spa_sync_upgrades(spa_t *spa, dmu_tx_t *tx)
6684{
6685 dsl_pool_t *dp = spa->spa_dsl_pool;
6686
6687 ASSERT(spa->spa_sync_pass == 1);
6688
13fe0198
MA
6689 rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
6690
428870ff
BB
6691 if (spa->spa_ubsync.ub_version < SPA_VERSION_ORIGIN &&
6692 spa->spa_uberblock.ub_version >= SPA_VERSION_ORIGIN) {
6693 dsl_pool_create_origin(dp, tx);
6694
6695 /* Keeping the origin open increases spa_minref */
6696 spa->spa_minref += 3;
6697 }
6698
6699 if (spa->spa_ubsync.ub_version < SPA_VERSION_NEXT_CLONES &&
6700 spa->spa_uberblock.ub_version >= SPA_VERSION_NEXT_CLONES) {
6701 dsl_pool_upgrade_clones(dp, tx);
6702 }
6703
6704 if (spa->spa_ubsync.ub_version < SPA_VERSION_DIR_CLONES &&
6705 spa->spa_uberblock.ub_version >= SPA_VERSION_DIR_CLONES) {
6706 dsl_pool_upgrade_dir_clones(dp, tx);
6707
6708 /* Keeping the freedir open increases spa_minref */
6709 spa->spa_minref += 3;
6710 }
9ae529ec
CS
6711
6712 if (spa->spa_ubsync.ub_version < SPA_VERSION_FEATURES &&
6713 spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
6714 spa_feature_create_zap_objects(spa, tx);
6715 }
62bdd5eb
DL
6716
6717 /*
6718 * LZ4_COMPRESS feature's behaviour was changed to activate_on_enable
6719 * when possibility to use lz4 compression for metadata was added
6720 * Old pools that have this feature enabled must be upgraded to have
6721 * this feature active
6722 */
6723 if (spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
6724 boolean_t lz4_en = spa_feature_is_enabled(spa,
6725 SPA_FEATURE_LZ4_COMPRESS);
6726 boolean_t lz4_ac = spa_feature_is_active(spa,
6727 SPA_FEATURE_LZ4_COMPRESS);
6728
6729 if (lz4_en && !lz4_ac)
6730 spa_feature_incr(spa, SPA_FEATURE_LZ4_COMPRESS, tx);
6731 }
3c67d83a
TH
6732
6733 /*
6734 * If we haven't written the salt, do so now. Note that the
6735 * feature may not be activated yet, but that's fine since
6736 * the presence of this ZAP entry is backwards compatible.
6737 */
6738 if (zap_contains(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
6739 DMU_POOL_CHECKSUM_SALT) == ENOENT) {
6740 VERIFY0(zap_add(spa->spa_meta_objset,
6741 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CHECKSUM_SALT, 1,
6742 sizeof (spa->spa_cksum_salt.zcs_bytes),
6743 spa->spa_cksum_salt.zcs_bytes, tx));
6744 }
6745
13fe0198 6746 rrw_exit(&dp->dp_config_rwlock, FTAG);
428870ff
BB
6747}
6748
34dc7c2f
BB
6749/*
6750 * Sync the specified transaction group. New blocks may be dirtied as
6751 * part of the process, so we iterate until it converges.
6752 */
6753void
6754spa_sync(spa_t *spa, uint64_t txg)
6755{
6756 dsl_pool_t *dp = spa->spa_dsl_pool;
6757 objset_t *mos = spa->spa_meta_objset;
428870ff 6758 bplist_t *free_bpl = &spa->spa_free_bplist[txg & TXG_MASK];
34dc7c2f
BB
6759 vdev_t *rvd = spa->spa_root_vdev;
6760 vdev_t *vd;
34dc7c2f 6761 dmu_tx_t *tx;
b128c09f 6762 int error;
3dfb57a3
DB
6763 uint32_t max_queue_depth = zfs_vdev_async_write_max_active *
6764 zfs_vdev_queue_depth_pct / 100;
34dc7c2f 6765
572e2857
BB
6766 VERIFY(spa_writeable(spa));
6767
34dc7c2f
BB
6768 /*
6769 * Lock out configuration changes.
6770 */
b128c09f 6771 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
34dc7c2f
BB
6772
6773 spa->spa_syncing_txg = txg;
6774 spa->spa_sync_pass = 0;
6775
3dfb57a3
DB
6776 mutex_enter(&spa->spa_alloc_lock);
6777 VERIFY0(avl_numnodes(&spa->spa_alloc_tree));
6778 mutex_exit(&spa->spa_alloc_lock);
6779
b128c09f
BB
6780 /*
6781 * If there are any pending vdev state changes, convert them
6782 * into config changes that go out with this transaction group.
6783 */
6784 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
fb5f0bc8
BB
6785 while (list_head(&spa->spa_state_dirty_list) != NULL) {
6786 /*
6787 * We need the write lock here because, for aux vdevs,
6788 * calling vdev_config_dirty() modifies sav_config.
6789 * This is ugly and will become unnecessary when we
6790 * eliminate the aux vdev wart by integrating all vdevs
6791 * into the root vdev tree.
6792 */
6793 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6794 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_WRITER);
6795 while ((vd = list_head(&spa->spa_state_dirty_list)) != NULL) {
6796 vdev_state_clean(vd);
6797 vdev_config_dirty(vd);
6798 }
6799 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6800 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
b128c09f
BB
6801 }
6802 spa_config_exit(spa, SCL_STATE, FTAG);
6803
34dc7c2f
BB
6804 tx = dmu_tx_create_assigned(dp, txg);
6805
cc92e9d0 6806 spa->spa_sync_starttime = gethrtime();
57ddcda1
CC
6807 taskq_cancel_id(system_delay_taskq, spa->spa_deadman_tqid);
6808 spa->spa_deadman_tqid = taskq_dispatch_delay(system_delay_taskq,
79c76d5b 6809 spa_deadman, spa, TQ_SLEEP, ddi_get_lbolt() +
cc92e9d0
GW
6810 NSEC_TO_TICK(spa->spa_deadman_synctime));
6811
34dc7c2f
BB
6812 /*
6813 * If we are upgrading to SPA_VERSION_RAIDZ_DEFLATE this txg,
6814 * set spa_deflate if we have no raid-z vdevs.
6815 */
6816 if (spa->spa_ubsync.ub_version < SPA_VERSION_RAIDZ_DEFLATE &&
6817 spa->spa_uberblock.ub_version >= SPA_VERSION_RAIDZ_DEFLATE) {
6818 int i;
6819
6820 for (i = 0; i < rvd->vdev_children; i++) {
6821 vd = rvd->vdev_child[i];
6822 if (vd->vdev_deflate_ratio != SPA_MINBLOCKSIZE)
6823 break;
6824 }
6825 if (i == rvd->vdev_children) {
6826 spa->spa_deflate = TRUE;
6827 VERIFY(0 == zap_add(spa->spa_meta_objset,
6828 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
6829 sizeof (uint64_t), 1, &spa->spa_deflate, tx));
6830 }
6831 }
6832
3dfb57a3
DB
6833 /*
6834 * Set the top-level vdev's max queue depth. Evaluate each
6835 * top-level's async write queue depth in case it changed.
6836 * The max queue depth will not change in the middle of syncing
6837 * out this txg.
6838 */
1c27024e
DB
6839 uint64_t queue_depth_total = 0;
6840 for (int c = 0; c < rvd->vdev_children; c++) {
3dfb57a3
DB
6841 vdev_t *tvd = rvd->vdev_child[c];
6842 metaslab_group_t *mg = tvd->vdev_mg;
6843
6844 if (mg == NULL || mg->mg_class != spa_normal_class(spa) ||
6845 !metaslab_group_initialized(mg))
6846 continue;
6847
6848 /*
6849 * It is safe to do a lock-free check here because only async
6850 * allocations look at mg_max_alloc_queue_depth, and async
6851 * allocations all happen from spa_sync().
6852 */
6853 ASSERT0(refcount_count(&mg->mg_alloc_queue_depth));
6854 mg->mg_max_alloc_queue_depth = max_queue_depth;
6855 queue_depth_total += mg->mg_max_alloc_queue_depth;
6856 }
1c27024e 6857 metaslab_class_t *mc = spa_normal_class(spa);
3dfb57a3
DB
6858 ASSERT0(refcount_count(&mc->mc_alloc_slots));
6859 mc->mc_alloc_max_slots = queue_depth_total;
6860 mc->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
6861
6862 ASSERT3U(mc->mc_alloc_max_slots, <=,
6863 max_queue_depth * rvd->vdev_children);
6864
34dc7c2f
BB
6865 /*
6866 * Iterate to convergence.
6867 */
6868 do {
428870ff 6869 int pass = ++spa->spa_sync_pass;
34dc7c2f
BB
6870
6871 spa_sync_config_object(spa, tx);
6872 spa_sync_aux_dev(spa, &spa->spa_spares, tx,
6873 ZPOOL_CONFIG_SPARES, DMU_POOL_SPARES);
6874 spa_sync_aux_dev(spa, &spa->spa_l2cache, tx,
6875 ZPOOL_CONFIG_L2CACHE, DMU_POOL_L2CACHE);
6876 spa_errlog_sync(spa, txg);
6877 dsl_pool_sync(dp, txg);
6878
55d85d5a 6879 if (pass < zfs_sync_pass_deferred_free) {
e8b96c60 6880 spa_sync_frees(spa, free_bpl, tx);
428870ff 6881 } else {
905edb40
MA
6882 /*
6883 * We can not defer frees in pass 1, because
6884 * we sync the deferred frees later in pass 1.
6885 */
6886 ASSERT3U(pass, >, 1);
428870ff 6887 bplist_iterate(free_bpl, bpobj_enqueue_cb,
e8b96c60 6888 &spa->spa_deferred_bpobj, tx);
34dc7c2f
BB
6889 }
6890
428870ff
BB
6891 ddt_sync(spa, txg);
6892 dsl_scan_sync(dp, tx);
34dc7c2f 6893
c65aa5b2 6894 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, txg)))
428870ff
BB
6895 vdev_sync(vd, txg);
6896
905edb40 6897 if (pass == 1) {
428870ff 6898 spa_sync_upgrades(spa, tx);
905edb40
MA
6899 ASSERT3U(txg, >=,
6900 spa->spa_uberblock.ub_rootbp.blk_birth);
6901 /*
6902 * Note: We need to check if the MOS is dirty
6903 * because we could have marked the MOS dirty
6904 * without updating the uberblock (e.g. if we
6905 * have sync tasks but no dirty user data). We
6906 * need to check the uberblock's rootbp because
6907 * it is updated if we have synced out dirty
6908 * data (though in this case the MOS will most
6909 * likely also be dirty due to second order
6910 * effects, we don't want to rely on that here).
6911 */
6912 if (spa->spa_uberblock.ub_rootbp.blk_birth < txg &&
6913 !dmu_objset_is_dirty(mos, txg)) {
6914 /*
6915 * Nothing changed on the first pass,
6916 * therefore this TXG is a no-op. Avoid
6917 * syncing deferred frees, so that we
6918 * can keep this TXG as a no-op.
6919 */
6920 ASSERT(txg_list_empty(&dp->dp_dirty_datasets,
6921 txg));
6922 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
6923 ASSERT(txg_list_empty(&dp->dp_sync_tasks, txg));
6924 break;
6925 }
6926 spa_sync_deferred_frees(spa, tx);
6927 }
34dc7c2f 6928
428870ff 6929 } while (dmu_objset_is_dirty(mos, txg));
34dc7c2f 6930
33cf67cd 6931#ifdef ZFS_DEBUG
e0ab3ab5
JS
6932 if (!list_is_empty(&spa->spa_config_dirty_list)) {
6933 /*
6934 * Make sure that the number of ZAPs for all the vdevs matches
6935 * the number of ZAPs in the per-vdev ZAP list. This only gets
6936 * called if the config is dirty; otherwise there may be
6937 * outstanding AVZ operations that weren't completed in
6938 * spa_sync_config_object.
6939 */
6940 uint64_t all_vdev_zap_entry_count;
6941 ASSERT0(zap_count(spa->spa_meta_objset,
6942 spa->spa_all_vdev_zaps, &all_vdev_zap_entry_count));
6943 ASSERT3U(vdev_count_verify_zaps(spa->spa_root_vdev), ==,
6944 all_vdev_zap_entry_count);
6945 }
33cf67cd 6946#endif
e0ab3ab5 6947
34dc7c2f
BB
6948 /*
6949 * Rewrite the vdev configuration (which includes the uberblock)
6950 * to commit the transaction group.
6951 *
6952 * If there are no dirty vdevs, we sync the uberblock to a few
6953 * random top-level vdevs that are known to be visible in the
b128c09f
BB
6954 * config cache (see spa_vdev_add() for a complete description).
6955 * If there *are* dirty vdevs, sync the uberblock to all vdevs.
34dc7c2f 6956 */
b128c09f
BB
6957 for (;;) {
6958 /*
6959 * We hold SCL_STATE to prevent vdev open/close/etc.
6960 * while we're attempting to write the vdev labels.
6961 */
6962 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
6963
6964 if (list_is_empty(&spa->spa_config_dirty_list)) {
6965 vdev_t *svd[SPA_DVAS_PER_BP];
6966 int svdcount = 0;
6967 int children = rvd->vdev_children;
6968 int c0 = spa_get_random(children);
b128c09f 6969
1c27024e 6970 for (int c = 0; c < children; c++) {
b128c09f
BB
6971 vd = rvd->vdev_child[(c0 + c) % children];
6972 if (vd->vdev_ms_array == 0 || vd->vdev_islog)
6973 continue;
6974 svd[svdcount++] = vd;
6975 if (svdcount == SPA_DVAS_PER_BP)
6976 break;
6977 }
b6fcb792 6978 error = vdev_config_sync(svd, svdcount, txg);
b128c09f
BB
6979 } else {
6980 error = vdev_config_sync(rvd->vdev_child,
b6fcb792 6981 rvd->vdev_children, txg);
34dc7c2f 6982 }
34dc7c2f 6983
3bc7e0fb
GW
6984 if (error == 0)
6985 spa->spa_last_synced_guid = rvd->vdev_guid;
6986
b128c09f
BB
6987 spa_config_exit(spa, SCL_STATE, FTAG);
6988
6989 if (error == 0)
6990 break;
cec3a0a1 6991 zio_suspend(spa, NULL, ZIO_SUSPEND_IOERR);
b128c09f
BB
6992 zio_resume_wait(spa);
6993 }
34dc7c2f
BB
6994 dmu_tx_commit(tx);
6995
57ddcda1 6996 taskq_cancel_id(system_delay_taskq, spa->spa_deadman_tqid);
cc92e9d0
GW
6997 spa->spa_deadman_tqid = 0;
6998
34dc7c2f
BB
6999 /*
7000 * Clear the dirty config list.
7001 */
b128c09f 7002 while ((vd = list_head(&spa->spa_config_dirty_list)) != NULL)
34dc7c2f
BB
7003 vdev_config_clean(vd);
7004
7005 /*
7006 * Now that the new config has synced transactionally,
7007 * let it become visible to the config cache.
7008 */
7009 if (spa->spa_config_syncing != NULL) {
7010 spa_config_set(spa, spa->spa_config_syncing);
7011 spa->spa_config_txg = txg;
7012 spa->spa_config_syncing = NULL;
7013 }
7014
428870ff 7015 dsl_pool_sync_done(dp, txg);
34dc7c2f 7016
3dfb57a3
DB
7017 mutex_enter(&spa->spa_alloc_lock);
7018 VERIFY0(avl_numnodes(&spa->spa_alloc_tree));
7019 mutex_exit(&spa->spa_alloc_lock);
7020
34dc7c2f
BB
7021 /*
7022 * Update usable space statistics.
7023 */
c65aa5b2 7024 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, TXG_CLEAN(txg))))
34dc7c2f
BB
7025 vdev_sync_done(vd, txg);
7026
428870ff
BB
7027 spa_update_dspace(spa);
7028
34dc7c2f
BB
7029 /*
7030 * It had better be the case that we didn't dirty anything
7031 * since vdev_config_sync().
7032 */
7033 ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
7034 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
7035 ASSERT(txg_list_empty(&spa->spa_vdev_txg_list, txg));
428870ff
BB
7036
7037 spa->spa_sync_pass = 0;
34dc7c2f 7038
55922e73
GW
7039 /*
7040 * Update the last synced uberblock here. We want to do this at
7041 * the end of spa_sync() so that consumers of spa_last_synced_txg()
7042 * will be guaranteed that all the processing associated with
7043 * that txg has been completed.
7044 */
7045 spa->spa_ubsync = spa->spa_uberblock;
b128c09f 7046 spa_config_exit(spa, SCL_CONFIG, FTAG);
34dc7c2f 7047
428870ff
BB
7048 spa_handle_ignored_writes(spa);
7049
34dc7c2f
BB
7050 /*
7051 * If any async tasks have been requested, kick them off.
7052 */
7053 spa_async_dispatch(spa);
7054}
7055
7056/*
7057 * Sync all pools. We don't want to hold the namespace lock across these
7058 * operations, so we take a reference on the spa_t and drop the lock during the
7059 * sync.
7060 */
7061void
7062spa_sync_allpools(void)
7063{
7064 spa_t *spa = NULL;
7065 mutex_enter(&spa_namespace_lock);
7066 while ((spa = spa_next(spa)) != NULL) {
572e2857
BB
7067 if (spa_state(spa) != POOL_STATE_ACTIVE ||
7068 !spa_writeable(spa) || spa_suspended(spa))
34dc7c2f
BB
7069 continue;
7070 spa_open_ref(spa, FTAG);
7071 mutex_exit(&spa_namespace_lock);
7072 txg_wait_synced(spa_get_dsl(spa), 0);
7073 mutex_enter(&spa_namespace_lock);
7074 spa_close(spa, FTAG);
7075 }
7076 mutex_exit(&spa_namespace_lock);
7077}
7078
7079/*
7080 * ==========================================================================
7081 * Miscellaneous routines
7082 * ==========================================================================
7083 */
7084
7085/*
7086 * Remove all pools in the system.
7087 */
7088void
7089spa_evict_all(void)
7090{
7091 spa_t *spa;
7092
7093 /*
7094 * Remove all cached state. All pools should be closed now,
7095 * so every spa in the AVL tree should be unreferenced.
7096 */
7097 mutex_enter(&spa_namespace_lock);
7098 while ((spa = spa_next(NULL)) != NULL) {
7099 /*
7100 * Stop async tasks. The async thread may need to detach
7101 * a device that's been replaced, which requires grabbing
7102 * spa_namespace_lock, so we must drop it here.
7103 */
7104 spa_open_ref(spa, FTAG);
7105 mutex_exit(&spa_namespace_lock);
7106 spa_async_suspend(spa);
7107 mutex_enter(&spa_namespace_lock);
34dc7c2f
BB
7108 spa_close(spa, FTAG);
7109
7110 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
7111 spa_unload(spa);
7112 spa_deactivate(spa);
7113 }
7114 spa_remove(spa);
7115 }
7116 mutex_exit(&spa_namespace_lock);
7117}
7118
7119vdev_t *
9babb374 7120spa_lookup_by_guid(spa_t *spa, uint64_t guid, boolean_t aux)
34dc7c2f 7121{
b128c09f
BB
7122 vdev_t *vd;
7123 int i;
7124
7125 if ((vd = vdev_lookup_by_guid(spa->spa_root_vdev, guid)) != NULL)
7126 return (vd);
7127
9babb374 7128 if (aux) {
b128c09f
BB
7129 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
7130 vd = spa->spa_l2cache.sav_vdevs[i];
9babb374
BB
7131 if (vd->vdev_guid == guid)
7132 return (vd);
7133 }
7134
7135 for (i = 0; i < spa->spa_spares.sav_count; i++) {
7136 vd = spa->spa_spares.sav_vdevs[i];
b128c09f
BB
7137 if (vd->vdev_guid == guid)
7138 return (vd);
7139 }
7140 }
7141
7142 return (NULL);
34dc7c2f
BB
7143}
7144
7145void
7146spa_upgrade(spa_t *spa, uint64_t version)
7147{
572e2857
BB
7148 ASSERT(spa_writeable(spa));
7149
b128c09f 7150 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
34dc7c2f
BB
7151
7152 /*
7153 * This should only be called for a non-faulted pool, and since a
7154 * future version would result in an unopenable pool, this shouldn't be
7155 * possible.
7156 */
8dca0a9a 7157 ASSERT(SPA_VERSION_IS_SUPPORTED(spa->spa_uberblock.ub_version));
9b67f605 7158 ASSERT3U(version, >=, spa->spa_uberblock.ub_version);
34dc7c2f
BB
7159
7160 spa->spa_uberblock.ub_version = version;
7161 vdev_config_dirty(spa->spa_root_vdev);
7162
b128c09f 7163 spa_config_exit(spa, SCL_ALL, FTAG);
34dc7c2f
BB
7164
7165 txg_wait_synced(spa_get_dsl(spa), 0);
7166}
7167
7168boolean_t
7169spa_has_spare(spa_t *spa, uint64_t guid)
7170{
7171 int i;
7172 uint64_t spareguid;
7173 spa_aux_vdev_t *sav = &spa->spa_spares;
7174
7175 for (i = 0; i < sav->sav_count; i++)
7176 if (sav->sav_vdevs[i]->vdev_guid == guid)
7177 return (B_TRUE);
7178
7179 for (i = 0; i < sav->sav_npending; i++) {
7180 if (nvlist_lookup_uint64(sav->sav_pending[i], ZPOOL_CONFIG_GUID,
7181 &spareguid) == 0 && spareguid == guid)
7182 return (B_TRUE);
7183 }
7184
7185 return (B_FALSE);
7186}
7187
b128c09f
BB
7188/*
7189 * Check if a pool has an active shared spare device.
7190 * Note: reference count of an active spare is 2, as a spare and as a replace
7191 */
7192static boolean_t
7193spa_has_active_shared_spare(spa_t *spa)
7194{
7195 int i, refcnt;
7196 uint64_t pool;
7197 spa_aux_vdev_t *sav = &spa->spa_spares;
7198
7199 for (i = 0; i < sav->sav_count; i++) {
7200 if (spa_spare_exists(sav->sav_vdevs[i]->vdev_guid, &pool,
7201 &refcnt) && pool != 0ULL && pool == spa_guid(spa) &&
7202 refcnt > 2)
7203 return (B_TRUE);
7204 }
7205
7206 return (B_FALSE);
7207}
7208
12fa0466
DE
7209static sysevent_t *
7210spa_event_create(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
7211{
7212 sysevent_t *ev = NULL;
7213#ifdef _KERNEL
7214 nvlist_t *resource;
7215
7216 resource = zfs_event_create(spa, vd, FM_SYSEVENT_CLASS, name, hist_nvl);
7217 if (resource) {
7218 ev = kmem_alloc(sizeof (sysevent_t), KM_SLEEP);
7219 ev->resource = resource;
7220 }
7221#endif
7222 return (ev);
7223}
7224
7225static void
7226spa_event_post(sysevent_t *ev)
7227{
7228#ifdef _KERNEL
7229 if (ev) {
7230 zfs_zevent_post(ev->resource, NULL, zfs_zevent_post_cb);
7231 kmem_free(ev, sizeof (*ev));
7232 }
7233#endif
7234}
7235
34dc7c2f 7236/*
fb390aaf
HR
7237 * Post a zevent corresponding to the given sysevent. The 'name' must be one
7238 * of the event definitions in sys/sysevent/eventdefs.h. The payload will be
34dc7c2f
BB
7239 * filled in from the spa and (optionally) the vdev. This doesn't do anything
7240 * in the userland libzpool, as we don't want consumers to misinterpret ztest
7241 * or zdb as real changes.
7242 */
7243void
12fa0466 7244spa_event_notify(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
34dc7c2f 7245{
12fa0466 7246 spa_event_post(spa_event_create(spa, vd, hist_nvl, name));
34dc7c2f 7247}
c28b2279
BB
7248
7249#if defined(_KERNEL) && defined(HAVE_SPL)
7250/* state manipulation functions */
7251EXPORT_SYMBOL(spa_open);
7252EXPORT_SYMBOL(spa_open_rewind);
7253EXPORT_SYMBOL(spa_get_stats);
7254EXPORT_SYMBOL(spa_create);
c28b2279
BB
7255EXPORT_SYMBOL(spa_import);
7256EXPORT_SYMBOL(spa_tryimport);
7257EXPORT_SYMBOL(spa_destroy);
7258EXPORT_SYMBOL(spa_export);
7259EXPORT_SYMBOL(spa_reset);
7260EXPORT_SYMBOL(spa_async_request);
7261EXPORT_SYMBOL(spa_async_suspend);
7262EXPORT_SYMBOL(spa_async_resume);
7263EXPORT_SYMBOL(spa_inject_addref);
7264EXPORT_SYMBOL(spa_inject_delref);
7265EXPORT_SYMBOL(spa_scan_stat_init);
7266EXPORT_SYMBOL(spa_scan_get_stats);
7267
7268/* device maniion */
7269EXPORT_SYMBOL(spa_vdev_add);
7270EXPORT_SYMBOL(spa_vdev_attach);
7271EXPORT_SYMBOL(spa_vdev_detach);
7272EXPORT_SYMBOL(spa_vdev_remove);
7273EXPORT_SYMBOL(spa_vdev_setpath);
7274EXPORT_SYMBOL(spa_vdev_setfru);
7275EXPORT_SYMBOL(spa_vdev_split_mirror);
7276
7277/* spare statech is global across all pools) */
7278EXPORT_SYMBOL(spa_spare_add);
7279EXPORT_SYMBOL(spa_spare_remove);
7280EXPORT_SYMBOL(spa_spare_exists);
7281EXPORT_SYMBOL(spa_spare_activate);
7282
7283/* L2ARC statech is global across all pools) */
7284EXPORT_SYMBOL(spa_l2cache_add);
7285EXPORT_SYMBOL(spa_l2cache_remove);
7286EXPORT_SYMBOL(spa_l2cache_exists);
7287EXPORT_SYMBOL(spa_l2cache_activate);
7288EXPORT_SYMBOL(spa_l2cache_drop);
7289
7290/* scanning */
7291EXPORT_SYMBOL(spa_scan);
7292EXPORT_SYMBOL(spa_scan_stop);
7293
7294/* spa syncing */
7295EXPORT_SYMBOL(spa_sync); /* only for DMU use */
7296EXPORT_SYMBOL(spa_sync_allpools);
7297
7298/* properties */
7299EXPORT_SYMBOL(spa_prop_set);
7300EXPORT_SYMBOL(spa_prop_get);
7301EXPORT_SYMBOL(spa_prop_clear_bootfs);
7302
7303/* asynchronous event notification */
7304EXPORT_SYMBOL(spa_event_notify);
7305#endif
dea377c0
MA
7306
7307#if defined(_KERNEL) && defined(HAVE_SPL)
7308module_param(spa_load_verify_maxinflight, int, 0644);
7309MODULE_PARM_DESC(spa_load_verify_maxinflight,
7310 "Max concurrent traversal I/Os while verifying pool during import -X");
7311
7312module_param(spa_load_verify_metadata, int, 0644);
7313MODULE_PARM_DESC(spa_load_verify_metadata,
7314 "Set to traverse metadata on pool import");
7315
7316module_param(spa_load_verify_data, int, 0644);
7317MODULE_PARM_DESC(spa_load_verify_data,
7318 "Set to traverse data on pool import");
dcb6bed1 7319
02730c33 7320/* CSTYLED */
dcb6bed1
D
7321module_param(zio_taskq_batch_pct, uint, 0444);
7322MODULE_PARM_DESC(zio_taskq_batch_pct,
7323 "Percentage of CPUs to run an IO worker thread");
7324
dea377c0 7325#endif