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