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