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