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