4976 zfs should only avoid writing to a failing non-redundant top-level vdev
[unleashed.git] / usr / src / uts / common / fs / zfs / spa.c
blobc10cac1b2009ecdcb94a9b85ad2e9d91da451ba3
1 /*
2 * CDDL HEADER START
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.
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.
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]
19 * CDDL HEADER END
23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright (c) 2011, 2014 by Delphix. All rights reserved.
25 * Copyright (c) 2013, 2014, Nexenta Systems, Inc. All rights reserved.
29 * SPA: Storage Pool Allocator
31 * This file contains all the routines used when modifying on-disk SPA state.
32 * This includes opening, importing, destroying, exporting a pool, and syncing a
33 * pool.
36 #include <sys/zfs_context.h>
37 #include <sys/fm/fs/zfs.h>
38 #include <sys/spa_impl.h>
39 #include <sys/zio.h>
40 #include <sys/zio_checksum.h>
41 #include <sys/dmu.h>
42 #include <sys/dmu_tx.h>
43 #include <sys/zap.h>
44 #include <sys/zil.h>
45 #include <sys/ddt.h>
46 #include <sys/vdev_impl.h>
47 #include <sys/metaslab.h>
48 #include <sys/metaslab_impl.h>
49 #include <sys/uberblock_impl.h>
50 #include <sys/txg.h>
51 #include <sys/avl.h>
52 #include <sys/dmu_traverse.h>
53 #include <sys/dmu_objset.h>
54 #include <sys/unique.h>
55 #include <sys/dsl_pool.h>
56 #include <sys/dsl_dataset.h>
57 #include <sys/dsl_dir.h>
58 #include <sys/dsl_prop.h>
59 #include <sys/dsl_synctask.h>
60 #include <sys/fs/zfs.h>
61 #include <sys/arc.h>
62 #include <sys/callb.h>
63 #include <sys/systeminfo.h>
64 #include <sys/spa_boot.h>
65 #include <sys/zfs_ioctl.h>
66 #include <sys/dsl_scan.h>
67 #include <sys/zfeature.h>
68 #include <sys/dsl_destroy.h>
70 #ifdef _KERNEL
71 #include <sys/bootprops.h>
72 #include <sys/callb.h>
73 #include <sys/cpupart.h>
74 #include <sys/pool.h>
75 #include <sys/sysdc.h>
76 #include <sys/zone.h>
77 #endif /* _KERNEL */
79 #include "zfs_prop.h"
80 #include "zfs_comutil.h"
83 * The interval, in seconds, at which failed configuration cache file writes
84 * should be retried.
86 static int zfs_ccw_retry_interval = 300;
88 typedef enum zti_modes {
89 ZTI_MODE_FIXED, /* value is # of threads (min 1) */
90 ZTI_MODE_BATCH, /* cpu-intensive; value is ignored */
91 ZTI_MODE_NULL, /* don't create a taskq */
92 ZTI_NMODES
93 } zti_modes_t;
95 #define ZTI_P(n, q) { ZTI_MODE_FIXED, (n), (q) }
96 #define ZTI_BATCH { ZTI_MODE_BATCH, 0, 1 }
97 #define ZTI_NULL { ZTI_MODE_NULL, 0, 0 }
99 #define ZTI_N(n) ZTI_P(n, 1)
100 #define ZTI_ONE ZTI_N(1)
102 typedef struct zio_taskq_info {
103 zti_modes_t zti_mode;
104 uint_t zti_value;
105 uint_t zti_count;
106 } zio_taskq_info_t;
108 static const char *const zio_taskq_types[ZIO_TASKQ_TYPES] = {
109 "issue", "issue_high", "intr", "intr_high"
113 * This table defines the taskq settings for each ZFS I/O type. When
114 * initializing a pool, we use this table to create an appropriately sized
115 * taskq. Some operations are low volume and therefore have a small, static
116 * number of threads assigned to their taskqs using the ZTI_N(#) or ZTI_ONE
117 * macros. Other operations process a large amount of data; the ZTI_BATCH
118 * macro causes us to create a taskq oriented for throughput. Some operations
119 * are so high frequency and short-lived that the taskq itself can become a a
120 * point of lock contention. The ZTI_P(#, #) macro indicates that we need an
121 * additional degree of parallelism specified by the number of threads per-
122 * taskq and the number of taskqs; when dispatching an event in this case, the
123 * particular taskq is chosen at random.
125 * The different taskq priorities are to handle the different contexts (issue
126 * and interrupt) and then to reserve threads for ZIO_PRIORITY_NOW I/Os that
127 * need to be handled with minimum delay.
129 const zio_taskq_info_t zio_taskqs[ZIO_TYPES][ZIO_TASKQ_TYPES] = {
130 /* ISSUE ISSUE_HIGH INTR INTR_HIGH */
131 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* NULL */
132 { ZTI_N(8), ZTI_NULL, ZTI_P(12, 8), ZTI_NULL }, /* READ */
133 { ZTI_BATCH, ZTI_N(5), ZTI_N(8), ZTI_N(5) }, /* WRITE */
134 { ZTI_P(12, 8), ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* FREE */
135 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* CLAIM */
136 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* IOCTL */
139 static void spa_sync_version(void *arg, dmu_tx_t *tx);
140 static void spa_sync_props(void *arg, dmu_tx_t *tx);
141 static boolean_t spa_has_active_shared_spare(spa_t *spa);
142 static int spa_load_impl(spa_t *spa, uint64_t, nvlist_t *config,
143 spa_load_state_t state, spa_import_type_t type, boolean_t mosconfig,
144 char **ereport);
145 static void spa_vdev_resilver_done(spa_t *spa);
147 uint_t zio_taskq_batch_pct = 75; /* 1 thread per cpu in pset */
148 id_t zio_taskq_psrset_bind = PS_NONE;
149 boolean_t zio_taskq_sysdc = B_TRUE; /* use SDC scheduling class */
150 uint_t zio_taskq_basedc = 80; /* base duty cycle */
152 boolean_t spa_create_process = B_TRUE; /* no process ==> no sysdc */
153 extern int zfs_sync_pass_deferred_free;
156 * This (illegal) pool name is used when temporarily importing a spa_t in order
157 * to get the vdev stats associated with the imported devices.
159 #define TRYIMPORT_NAME "$import"
162 * ==========================================================================
163 * SPA properties routines
164 * ==========================================================================
168 * Add a (source=src, propname=propval) list to an nvlist.
170 static void
171 spa_prop_add_list(nvlist_t *nvl, zpool_prop_t prop, char *strval,
172 uint64_t intval, zprop_source_t src)
174 const char *propname = zpool_prop_to_name(prop);
175 nvlist_t *propval;
177 VERIFY(nvlist_alloc(&propval, NV_UNIQUE_NAME, KM_SLEEP) == 0);
178 VERIFY(nvlist_add_uint64(propval, ZPROP_SOURCE, src) == 0);
180 if (strval != NULL)
181 VERIFY(nvlist_add_string(propval, ZPROP_VALUE, strval) == 0);
182 else
183 VERIFY(nvlist_add_uint64(propval, ZPROP_VALUE, intval) == 0);
185 VERIFY(nvlist_add_nvlist(nvl, propname, propval) == 0);
186 nvlist_free(propval);
190 * Get property values from the spa configuration.
192 static void
193 spa_prop_get_config(spa_t *spa, nvlist_t **nvp)
195 vdev_t *rvd = spa->spa_root_vdev;
196 dsl_pool_t *pool = spa->spa_dsl_pool;
197 uint64_t size, alloc, cap, version;
198 zprop_source_t src = ZPROP_SRC_NONE;
199 spa_config_dirent_t *dp;
200 metaslab_class_t *mc = spa_normal_class(spa);
202 ASSERT(MUTEX_HELD(&spa->spa_props_lock));
204 if (rvd != NULL) {
205 alloc = metaslab_class_get_alloc(spa_normal_class(spa));
206 size = metaslab_class_get_space(spa_normal_class(spa));
207 spa_prop_add_list(*nvp, ZPOOL_PROP_NAME, spa_name(spa), 0, src);
208 spa_prop_add_list(*nvp, ZPOOL_PROP_SIZE, NULL, size, src);
209 spa_prop_add_list(*nvp, ZPOOL_PROP_ALLOCATED, NULL, alloc, src);
210 spa_prop_add_list(*nvp, ZPOOL_PROP_FREE, NULL,
211 size - alloc, src);
213 spa_prop_add_list(*nvp, ZPOOL_PROP_FRAGMENTATION, NULL,
214 metaslab_class_fragmentation(mc), src);
215 spa_prop_add_list(*nvp, ZPOOL_PROP_EXPANDSZ, NULL,
216 metaslab_class_expandable_space(mc), src);
217 spa_prop_add_list(*nvp, ZPOOL_PROP_READONLY, NULL,
218 (spa_mode(spa) == FREAD), src);
220 cap = (size == 0) ? 0 : (alloc * 100 / size);
221 spa_prop_add_list(*nvp, ZPOOL_PROP_CAPACITY, NULL, cap, src);
223 spa_prop_add_list(*nvp, ZPOOL_PROP_DEDUPRATIO, NULL,
224 ddt_get_pool_dedup_ratio(spa), src);
226 spa_prop_add_list(*nvp, ZPOOL_PROP_HEALTH, NULL,
227 rvd->vdev_state, src);
229 version = spa_version(spa);
230 if (version == zpool_prop_default_numeric(ZPOOL_PROP_VERSION))
231 src = ZPROP_SRC_DEFAULT;
232 else
233 src = ZPROP_SRC_LOCAL;
234 spa_prop_add_list(*nvp, ZPOOL_PROP_VERSION, NULL, version, src);
237 if (pool != NULL) {
239 * The $FREE directory was introduced in SPA_VERSION_DEADLISTS,
240 * when opening pools before this version freedir will be NULL.
242 if (pool->dp_free_dir != NULL) {
243 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING, NULL,
244 pool->dp_free_dir->dd_phys->dd_used_bytes, src);
245 } else {
246 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING,
247 NULL, 0, src);
250 if (pool->dp_leak_dir != NULL) {
251 spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED, NULL,
252 pool->dp_leak_dir->dd_phys->dd_used_bytes, src);
253 } else {
254 spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED,
255 NULL, 0, src);
259 spa_prop_add_list(*nvp, ZPOOL_PROP_GUID, NULL, spa_guid(spa), src);
261 if (spa->spa_comment != NULL) {
262 spa_prop_add_list(*nvp, ZPOOL_PROP_COMMENT, spa->spa_comment,
263 0, ZPROP_SRC_LOCAL);
266 if (spa->spa_root != NULL)
267 spa_prop_add_list(*nvp, ZPOOL_PROP_ALTROOT, spa->spa_root,
268 0, ZPROP_SRC_LOCAL);
270 if ((dp = list_head(&spa->spa_config_list)) != NULL) {
271 if (dp->scd_path == NULL) {
272 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
273 "none", 0, ZPROP_SRC_LOCAL);
274 } else if (strcmp(dp->scd_path, spa_config_path) != 0) {
275 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
276 dp->scd_path, 0, ZPROP_SRC_LOCAL);
282 * Get zpool property values.
285 spa_prop_get(spa_t *spa, nvlist_t **nvp)
287 objset_t *mos = spa->spa_meta_objset;
288 zap_cursor_t zc;
289 zap_attribute_t za;
290 int err;
292 VERIFY(nvlist_alloc(nvp, NV_UNIQUE_NAME, KM_SLEEP) == 0);
294 mutex_enter(&spa->spa_props_lock);
297 * Get properties from the spa config.
299 spa_prop_get_config(spa, nvp);
301 /* If no pool property object, no more prop to get. */
302 if (mos == NULL || spa->spa_pool_props_object == 0) {
303 mutex_exit(&spa->spa_props_lock);
304 return (0);
308 * Get properties from the MOS pool property object.
310 for (zap_cursor_init(&zc, mos, spa->spa_pool_props_object);
311 (err = zap_cursor_retrieve(&zc, &za)) == 0;
312 zap_cursor_advance(&zc)) {
313 uint64_t intval = 0;
314 char *strval = NULL;
315 zprop_source_t src = ZPROP_SRC_DEFAULT;
316 zpool_prop_t prop;
318 if ((prop = zpool_name_to_prop(za.za_name)) == ZPROP_INVAL)
319 continue;
321 switch (za.za_integer_length) {
322 case 8:
323 /* integer property */
324 if (za.za_first_integer !=
325 zpool_prop_default_numeric(prop))
326 src = ZPROP_SRC_LOCAL;
328 if (prop == ZPOOL_PROP_BOOTFS) {
329 dsl_pool_t *dp;
330 dsl_dataset_t *ds = NULL;
332 dp = spa_get_dsl(spa);
333 dsl_pool_config_enter(dp, FTAG);
334 if (err = dsl_dataset_hold_obj(dp,
335 za.za_first_integer, FTAG, &ds)) {
336 dsl_pool_config_exit(dp, FTAG);
337 break;
340 strval = kmem_alloc(
341 MAXNAMELEN + strlen(MOS_DIR_NAME) + 1,
342 KM_SLEEP);
343 dsl_dataset_name(ds, strval);
344 dsl_dataset_rele(ds, FTAG);
345 dsl_pool_config_exit(dp, FTAG);
346 } else {
347 strval = NULL;
348 intval = za.za_first_integer;
351 spa_prop_add_list(*nvp, prop, strval, intval, src);
353 if (strval != NULL)
354 kmem_free(strval,
355 MAXNAMELEN + strlen(MOS_DIR_NAME) + 1);
357 break;
359 case 1:
360 /* string property */
361 strval = kmem_alloc(za.za_num_integers, KM_SLEEP);
362 err = zap_lookup(mos, spa->spa_pool_props_object,
363 za.za_name, 1, za.za_num_integers, strval);
364 if (err) {
365 kmem_free(strval, za.za_num_integers);
366 break;
368 spa_prop_add_list(*nvp, prop, strval, 0, src);
369 kmem_free(strval, za.za_num_integers);
370 break;
372 default:
373 break;
376 zap_cursor_fini(&zc);
377 mutex_exit(&spa->spa_props_lock);
378 out:
379 if (err && err != ENOENT) {
380 nvlist_free(*nvp);
381 *nvp = NULL;
382 return (err);
385 return (0);
389 * Validate the given pool properties nvlist and modify the list
390 * for the property values to be set.
392 static int
393 spa_prop_validate(spa_t *spa, nvlist_t *props)
395 nvpair_t *elem;
396 int error = 0, reset_bootfs = 0;
397 uint64_t objnum = 0;
398 boolean_t has_feature = B_FALSE;
400 elem = NULL;
401 while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
402 uint64_t intval;
403 char *strval, *slash, *check, *fname;
404 const char *propname = nvpair_name(elem);
405 zpool_prop_t prop = zpool_name_to_prop(propname);
407 switch (prop) {
408 case ZPROP_INVAL:
409 if (!zpool_prop_feature(propname)) {
410 error = SET_ERROR(EINVAL);
411 break;
415 * Sanitize the input.
417 if (nvpair_type(elem) != DATA_TYPE_UINT64) {
418 error = SET_ERROR(EINVAL);
419 break;
422 if (nvpair_value_uint64(elem, &intval) != 0) {
423 error = SET_ERROR(EINVAL);
424 break;
427 if (intval != 0) {
428 error = SET_ERROR(EINVAL);
429 break;
432 fname = strchr(propname, '@') + 1;
433 if (zfeature_lookup_name(fname, NULL) != 0) {
434 error = SET_ERROR(EINVAL);
435 break;
438 has_feature = B_TRUE;
439 break;
441 case ZPOOL_PROP_VERSION:
442 error = nvpair_value_uint64(elem, &intval);
443 if (!error &&
444 (intval < spa_version(spa) ||
445 intval > SPA_VERSION_BEFORE_FEATURES ||
446 has_feature))
447 error = SET_ERROR(EINVAL);
448 break;
450 case ZPOOL_PROP_DELEGATION:
451 case ZPOOL_PROP_AUTOREPLACE:
452 case ZPOOL_PROP_LISTSNAPS:
453 case ZPOOL_PROP_AUTOEXPAND:
454 error = nvpair_value_uint64(elem, &intval);
455 if (!error && intval > 1)
456 error = SET_ERROR(EINVAL);
457 break;
459 case ZPOOL_PROP_BOOTFS:
461 * If the pool version is less than SPA_VERSION_BOOTFS,
462 * or the pool is still being created (version == 0),
463 * the bootfs property cannot be set.
465 if (spa_version(spa) < SPA_VERSION_BOOTFS) {
466 error = SET_ERROR(ENOTSUP);
467 break;
471 * Make sure the vdev config is bootable
473 if (!vdev_is_bootable(spa->spa_root_vdev)) {
474 error = SET_ERROR(ENOTSUP);
475 break;
478 reset_bootfs = 1;
480 error = nvpair_value_string(elem, &strval);
482 if (!error) {
483 objset_t *os;
484 uint64_t compress;
486 if (strval == NULL || strval[0] == '\0') {
487 objnum = zpool_prop_default_numeric(
488 ZPOOL_PROP_BOOTFS);
489 break;
492 if (error = dmu_objset_hold(strval, FTAG, &os))
493 break;
495 /* Must be ZPL and not gzip compressed. */
497 if (dmu_objset_type(os) != DMU_OST_ZFS) {
498 error = SET_ERROR(ENOTSUP);
499 } else if ((error =
500 dsl_prop_get_int_ds(dmu_objset_ds(os),
501 zfs_prop_to_name(ZFS_PROP_COMPRESSION),
502 &compress)) == 0 &&
503 !BOOTFS_COMPRESS_VALID(compress)) {
504 error = SET_ERROR(ENOTSUP);
505 } else {
506 objnum = dmu_objset_id(os);
508 dmu_objset_rele(os, FTAG);
510 break;
512 case ZPOOL_PROP_FAILUREMODE:
513 error = nvpair_value_uint64(elem, &intval);
514 if (!error && (intval < ZIO_FAILURE_MODE_WAIT ||
515 intval > ZIO_FAILURE_MODE_PANIC))
516 error = SET_ERROR(EINVAL);
519 * This is a special case which only occurs when
520 * the pool has completely failed. This allows
521 * the user to change the in-core failmode property
522 * without syncing it out to disk (I/Os might
523 * currently be blocked). We do this by returning
524 * EIO to the caller (spa_prop_set) to trick it
525 * into thinking we encountered a property validation
526 * error.
528 if (!error && spa_suspended(spa)) {
529 spa->spa_failmode = intval;
530 error = SET_ERROR(EIO);
532 break;
534 case ZPOOL_PROP_CACHEFILE:
535 if ((error = nvpair_value_string(elem, &strval)) != 0)
536 break;
538 if (strval[0] == '\0')
539 break;
541 if (strcmp(strval, "none") == 0)
542 break;
544 if (strval[0] != '/') {
545 error = SET_ERROR(EINVAL);
546 break;
549 slash = strrchr(strval, '/');
550 ASSERT(slash != NULL);
552 if (slash[1] == '\0' || strcmp(slash, "/.") == 0 ||
553 strcmp(slash, "/..") == 0)
554 error = SET_ERROR(EINVAL);
555 break;
557 case ZPOOL_PROP_COMMENT:
558 if ((error = nvpair_value_string(elem, &strval)) != 0)
559 break;
560 for (check = strval; *check != '\0'; check++) {
562 * The kernel doesn't have an easy isprint()
563 * check. For this kernel check, we merely
564 * check ASCII apart from DEL. Fix this if
565 * there is an easy-to-use kernel isprint().
567 if (*check >= 0x7f) {
568 error = SET_ERROR(EINVAL);
569 break;
571 check++;
573 if (strlen(strval) > ZPROP_MAX_COMMENT)
574 error = E2BIG;
575 break;
577 case ZPOOL_PROP_DEDUPDITTO:
578 if (spa_version(spa) < SPA_VERSION_DEDUP)
579 error = SET_ERROR(ENOTSUP);
580 else
581 error = nvpair_value_uint64(elem, &intval);
582 if (error == 0 &&
583 intval != 0 && intval < ZIO_DEDUPDITTO_MIN)
584 error = SET_ERROR(EINVAL);
585 break;
588 if (error)
589 break;
592 if (!error && reset_bootfs) {
593 error = nvlist_remove(props,
594 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), DATA_TYPE_STRING);
596 if (!error) {
597 error = nvlist_add_uint64(props,
598 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), objnum);
602 return (error);
605 void
606 spa_configfile_set(spa_t *spa, nvlist_t *nvp, boolean_t need_sync)
608 char *cachefile;
609 spa_config_dirent_t *dp;
611 if (nvlist_lookup_string(nvp, zpool_prop_to_name(ZPOOL_PROP_CACHEFILE),
612 &cachefile) != 0)
613 return;
615 dp = kmem_alloc(sizeof (spa_config_dirent_t),
616 KM_SLEEP);
618 if (cachefile[0] == '\0')
619 dp->scd_path = spa_strdup(spa_config_path);
620 else if (strcmp(cachefile, "none") == 0)
621 dp->scd_path = NULL;
622 else
623 dp->scd_path = spa_strdup(cachefile);
625 list_insert_head(&spa->spa_config_list, dp);
626 if (need_sync)
627 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
631 spa_prop_set(spa_t *spa, nvlist_t *nvp)
633 int error;
634 nvpair_t *elem = NULL;
635 boolean_t need_sync = B_FALSE;
637 if ((error = spa_prop_validate(spa, nvp)) != 0)
638 return (error);
640 while ((elem = nvlist_next_nvpair(nvp, elem)) != NULL) {
641 zpool_prop_t prop = zpool_name_to_prop(nvpair_name(elem));
643 if (prop == ZPOOL_PROP_CACHEFILE ||
644 prop == ZPOOL_PROP_ALTROOT ||
645 prop == ZPOOL_PROP_READONLY)
646 continue;
648 if (prop == ZPOOL_PROP_VERSION || prop == ZPROP_INVAL) {
649 uint64_t ver;
651 if (prop == ZPOOL_PROP_VERSION) {
652 VERIFY(nvpair_value_uint64(elem, &ver) == 0);
653 } else {
654 ASSERT(zpool_prop_feature(nvpair_name(elem)));
655 ver = SPA_VERSION_FEATURES;
656 need_sync = B_TRUE;
659 /* Save time if the version is already set. */
660 if (ver == spa_version(spa))
661 continue;
664 * In addition to the pool directory object, we might
665 * create the pool properties object, the features for
666 * read object, the features for write object, or the
667 * feature descriptions object.
669 error = dsl_sync_task(spa->spa_name, NULL,
670 spa_sync_version, &ver,
671 6, ZFS_SPACE_CHECK_RESERVED);
672 if (error)
673 return (error);
674 continue;
677 need_sync = B_TRUE;
678 break;
681 if (need_sync) {
682 return (dsl_sync_task(spa->spa_name, NULL, spa_sync_props,
683 nvp, 6, ZFS_SPACE_CHECK_RESERVED));
686 return (0);
690 * If the bootfs property value is dsobj, clear it.
692 void
693 spa_prop_clear_bootfs(spa_t *spa, uint64_t dsobj, dmu_tx_t *tx)
695 if (spa->spa_bootfs == dsobj && spa->spa_pool_props_object != 0) {
696 VERIFY(zap_remove(spa->spa_meta_objset,
697 spa->spa_pool_props_object,
698 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), tx) == 0);
699 spa->spa_bootfs = 0;
703 /*ARGSUSED*/
704 static int
705 spa_change_guid_check(void *arg, dmu_tx_t *tx)
707 uint64_t *newguid = arg;
708 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
709 vdev_t *rvd = spa->spa_root_vdev;
710 uint64_t vdev_state;
712 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
713 vdev_state = rvd->vdev_state;
714 spa_config_exit(spa, SCL_STATE, FTAG);
716 if (vdev_state != VDEV_STATE_HEALTHY)
717 return (SET_ERROR(ENXIO));
719 ASSERT3U(spa_guid(spa), !=, *newguid);
721 return (0);
724 static void
725 spa_change_guid_sync(void *arg, dmu_tx_t *tx)
727 uint64_t *newguid = arg;
728 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
729 uint64_t oldguid;
730 vdev_t *rvd = spa->spa_root_vdev;
732 oldguid = spa_guid(spa);
734 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
735 rvd->vdev_guid = *newguid;
736 rvd->vdev_guid_sum += (*newguid - oldguid);
737 vdev_config_dirty(rvd);
738 spa_config_exit(spa, SCL_STATE, FTAG);
740 spa_history_log_internal(spa, "guid change", tx, "old=%llu new=%llu",
741 oldguid, *newguid);
745 * Change the GUID for the pool. This is done so that we can later
746 * re-import a pool built from a clone of our own vdevs. We will modify
747 * the root vdev's guid, our own pool guid, and then mark all of our
748 * vdevs dirty. Note that we must make sure that all our vdevs are
749 * online when we do this, or else any vdevs that weren't present
750 * would be orphaned from our pool. We are also going to issue a
751 * sysevent to update any watchers.
754 spa_change_guid(spa_t *spa)
756 int error;
757 uint64_t guid;
759 mutex_enter(&spa->spa_vdev_top_lock);
760 mutex_enter(&spa_namespace_lock);
761 guid = spa_generate_guid(NULL);
763 error = dsl_sync_task(spa->spa_name, spa_change_guid_check,
764 spa_change_guid_sync, &guid, 5, ZFS_SPACE_CHECK_RESERVED);
766 if (error == 0) {
767 spa_config_sync(spa, B_FALSE, B_TRUE);
768 spa_event_notify(spa, NULL, ESC_ZFS_POOL_REGUID);
771 mutex_exit(&spa_namespace_lock);
772 mutex_exit(&spa->spa_vdev_top_lock);
774 return (error);
778 * ==========================================================================
779 * SPA state manipulation (open/create/destroy/import/export)
780 * ==========================================================================
783 static int
784 spa_error_entry_compare(const void *a, const void *b)
786 spa_error_entry_t *sa = (spa_error_entry_t *)a;
787 spa_error_entry_t *sb = (spa_error_entry_t *)b;
788 int ret;
790 ret = bcmp(&sa->se_bookmark, &sb->se_bookmark,
791 sizeof (zbookmark_phys_t));
793 if (ret < 0)
794 return (-1);
795 else if (ret > 0)
796 return (1);
797 else
798 return (0);
802 * Utility function which retrieves copies of the current logs and
803 * re-initializes them in the process.
805 void
806 spa_get_errlists(spa_t *spa, avl_tree_t *last, avl_tree_t *scrub)
808 ASSERT(MUTEX_HELD(&spa->spa_errlist_lock));
810 bcopy(&spa->spa_errlist_last, last, sizeof (avl_tree_t));
811 bcopy(&spa->spa_errlist_scrub, scrub, sizeof (avl_tree_t));
813 avl_create(&spa->spa_errlist_scrub,
814 spa_error_entry_compare, sizeof (spa_error_entry_t),
815 offsetof(spa_error_entry_t, se_avl));
816 avl_create(&spa->spa_errlist_last,
817 spa_error_entry_compare, sizeof (spa_error_entry_t),
818 offsetof(spa_error_entry_t, se_avl));
821 static void
822 spa_taskqs_init(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
824 const zio_taskq_info_t *ztip = &zio_taskqs[t][q];
825 enum zti_modes mode = ztip->zti_mode;
826 uint_t value = ztip->zti_value;
827 uint_t count = ztip->zti_count;
828 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
829 char name[32];
830 uint_t flags = 0;
831 boolean_t batch = B_FALSE;
833 if (mode == ZTI_MODE_NULL) {
834 tqs->stqs_count = 0;
835 tqs->stqs_taskq = NULL;
836 return;
839 ASSERT3U(count, >, 0);
841 tqs->stqs_count = count;
842 tqs->stqs_taskq = kmem_alloc(count * sizeof (taskq_t *), KM_SLEEP);
844 switch (mode) {
845 case ZTI_MODE_FIXED:
846 ASSERT3U(value, >=, 1);
847 value = MAX(value, 1);
848 break;
850 case ZTI_MODE_BATCH:
851 batch = B_TRUE;
852 flags |= TASKQ_THREADS_CPU_PCT;
853 value = zio_taskq_batch_pct;
854 break;
856 default:
857 panic("unrecognized mode for %s_%s taskq (%u:%u) in "
858 "spa_activate()",
859 zio_type_name[t], zio_taskq_types[q], mode, value);
860 break;
863 for (uint_t i = 0; i < count; i++) {
864 taskq_t *tq;
866 if (count > 1) {
867 (void) snprintf(name, sizeof (name), "%s_%s_%u",
868 zio_type_name[t], zio_taskq_types[q], i);
869 } else {
870 (void) snprintf(name, sizeof (name), "%s_%s",
871 zio_type_name[t], zio_taskq_types[q]);
874 if (zio_taskq_sysdc && spa->spa_proc != &p0) {
875 if (batch)
876 flags |= TASKQ_DC_BATCH;
878 tq = taskq_create_sysdc(name, value, 50, INT_MAX,
879 spa->spa_proc, zio_taskq_basedc, flags);
880 } else {
881 pri_t pri = maxclsyspri;
883 * The write issue taskq can be extremely CPU
884 * intensive. Run it at slightly lower priority
885 * than the other taskqs.
887 if (t == ZIO_TYPE_WRITE && q == ZIO_TASKQ_ISSUE)
888 pri--;
890 tq = taskq_create_proc(name, value, pri, 50,
891 INT_MAX, spa->spa_proc, flags);
894 tqs->stqs_taskq[i] = tq;
898 static void
899 spa_taskqs_fini(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
901 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
903 if (tqs->stqs_taskq == NULL) {
904 ASSERT0(tqs->stqs_count);
905 return;
908 for (uint_t i = 0; i < tqs->stqs_count; i++) {
909 ASSERT3P(tqs->stqs_taskq[i], !=, NULL);
910 taskq_destroy(tqs->stqs_taskq[i]);
913 kmem_free(tqs->stqs_taskq, tqs->stqs_count * sizeof (taskq_t *));
914 tqs->stqs_taskq = NULL;
918 * Dispatch a task to the appropriate taskq for the ZFS I/O type and priority.
919 * Note that a type may have multiple discrete taskqs to avoid lock contention
920 * on the taskq itself. In that case we choose which taskq at random by using
921 * the low bits of gethrtime().
923 void
924 spa_taskq_dispatch_ent(spa_t *spa, zio_type_t t, zio_taskq_type_t q,
925 task_func_t *func, void *arg, uint_t flags, taskq_ent_t *ent)
927 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
928 taskq_t *tq;
930 ASSERT3P(tqs->stqs_taskq, !=, NULL);
931 ASSERT3U(tqs->stqs_count, !=, 0);
933 if (tqs->stqs_count == 1) {
934 tq = tqs->stqs_taskq[0];
935 } else {
936 tq = tqs->stqs_taskq[gethrtime() % tqs->stqs_count];
939 taskq_dispatch_ent(tq, func, arg, flags, ent);
942 static void
943 spa_create_zio_taskqs(spa_t *spa)
945 for (int t = 0; t < ZIO_TYPES; t++) {
946 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
947 spa_taskqs_init(spa, t, q);
952 #ifdef _KERNEL
953 static void
954 spa_thread(void *arg)
956 callb_cpr_t cprinfo;
958 spa_t *spa = arg;
959 user_t *pu = PTOU(curproc);
961 CALLB_CPR_INIT(&cprinfo, &spa->spa_proc_lock, callb_generic_cpr,
962 spa->spa_name);
964 ASSERT(curproc != &p0);
965 (void) snprintf(pu->u_psargs, sizeof (pu->u_psargs),
966 "zpool-%s", spa->spa_name);
967 (void) strlcpy(pu->u_comm, pu->u_psargs, sizeof (pu->u_comm));
969 /* bind this thread to the requested psrset */
970 if (zio_taskq_psrset_bind != PS_NONE) {
971 pool_lock();
972 mutex_enter(&cpu_lock);
973 mutex_enter(&pidlock);
974 mutex_enter(&curproc->p_lock);
976 if (cpupart_bind_thread(curthread, zio_taskq_psrset_bind,
977 0, NULL, NULL) == 0) {
978 curthread->t_bind_pset = zio_taskq_psrset_bind;
979 } else {
980 cmn_err(CE_WARN,
981 "Couldn't bind process for zfs pool \"%s\" to "
982 "pset %d\n", spa->spa_name, zio_taskq_psrset_bind);
985 mutex_exit(&curproc->p_lock);
986 mutex_exit(&pidlock);
987 mutex_exit(&cpu_lock);
988 pool_unlock();
991 if (zio_taskq_sysdc) {
992 sysdc_thread_enter(curthread, 100, 0);
995 spa->spa_proc = curproc;
996 spa->spa_did = curthread->t_did;
998 spa_create_zio_taskqs(spa);
1000 mutex_enter(&spa->spa_proc_lock);
1001 ASSERT(spa->spa_proc_state == SPA_PROC_CREATED);
1003 spa->spa_proc_state = SPA_PROC_ACTIVE;
1004 cv_broadcast(&spa->spa_proc_cv);
1006 CALLB_CPR_SAFE_BEGIN(&cprinfo);
1007 while (spa->spa_proc_state == SPA_PROC_ACTIVE)
1008 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1009 CALLB_CPR_SAFE_END(&cprinfo, &spa->spa_proc_lock);
1011 ASSERT(spa->spa_proc_state == SPA_PROC_DEACTIVATE);
1012 spa->spa_proc_state = SPA_PROC_GONE;
1013 spa->spa_proc = &p0;
1014 cv_broadcast(&spa->spa_proc_cv);
1015 CALLB_CPR_EXIT(&cprinfo); /* drops spa_proc_lock */
1017 mutex_enter(&curproc->p_lock);
1018 lwp_exit();
1020 #endif
1023 * Activate an uninitialized pool.
1025 static void
1026 spa_activate(spa_t *spa, int mode)
1028 ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
1030 spa->spa_state = POOL_STATE_ACTIVE;
1031 spa->spa_mode = mode;
1033 spa->spa_normal_class = metaslab_class_create(spa, zfs_metaslab_ops);
1034 spa->spa_log_class = metaslab_class_create(spa, zfs_metaslab_ops);
1036 /* Try to create a covering process */
1037 mutex_enter(&spa->spa_proc_lock);
1038 ASSERT(spa->spa_proc_state == SPA_PROC_NONE);
1039 ASSERT(spa->spa_proc == &p0);
1040 spa->spa_did = 0;
1042 /* Only create a process if we're going to be around a while. */
1043 if (spa_create_process && strcmp(spa->spa_name, TRYIMPORT_NAME) != 0) {
1044 if (newproc(spa_thread, (caddr_t)spa, syscid, maxclsyspri,
1045 NULL, 0) == 0) {
1046 spa->spa_proc_state = SPA_PROC_CREATED;
1047 while (spa->spa_proc_state == SPA_PROC_CREATED) {
1048 cv_wait(&spa->spa_proc_cv,
1049 &spa->spa_proc_lock);
1051 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1052 ASSERT(spa->spa_proc != &p0);
1053 ASSERT(spa->spa_did != 0);
1054 } else {
1055 #ifdef _KERNEL
1056 cmn_err(CE_WARN,
1057 "Couldn't create process for zfs pool \"%s\"\n",
1058 spa->spa_name);
1059 #endif
1062 mutex_exit(&spa->spa_proc_lock);
1064 /* If we didn't create a process, we need to create our taskqs. */
1065 if (spa->spa_proc == &p0) {
1066 spa_create_zio_taskqs(spa);
1069 list_create(&spa->spa_config_dirty_list, sizeof (vdev_t),
1070 offsetof(vdev_t, vdev_config_dirty_node));
1071 list_create(&spa->spa_state_dirty_list, sizeof (vdev_t),
1072 offsetof(vdev_t, vdev_state_dirty_node));
1074 txg_list_create(&spa->spa_vdev_txg_list,
1075 offsetof(struct vdev, vdev_txg_node));
1077 avl_create(&spa->spa_errlist_scrub,
1078 spa_error_entry_compare, sizeof (spa_error_entry_t),
1079 offsetof(spa_error_entry_t, se_avl));
1080 avl_create(&spa->spa_errlist_last,
1081 spa_error_entry_compare, sizeof (spa_error_entry_t),
1082 offsetof(spa_error_entry_t, se_avl));
1086 * Opposite of spa_activate().
1088 static void
1089 spa_deactivate(spa_t *spa)
1091 ASSERT(spa->spa_sync_on == B_FALSE);
1092 ASSERT(spa->spa_dsl_pool == NULL);
1093 ASSERT(spa->spa_root_vdev == NULL);
1094 ASSERT(spa->spa_async_zio_root == NULL);
1095 ASSERT(spa->spa_state != POOL_STATE_UNINITIALIZED);
1097 txg_list_destroy(&spa->spa_vdev_txg_list);
1099 list_destroy(&spa->spa_config_dirty_list);
1100 list_destroy(&spa->spa_state_dirty_list);
1102 for (int t = 0; t < ZIO_TYPES; t++) {
1103 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1104 spa_taskqs_fini(spa, t, q);
1108 metaslab_class_destroy(spa->spa_normal_class);
1109 spa->spa_normal_class = NULL;
1111 metaslab_class_destroy(spa->spa_log_class);
1112 spa->spa_log_class = NULL;
1115 * If this was part of an import or the open otherwise failed, we may
1116 * still have errors left in the queues. Empty them just in case.
1118 spa_errlog_drain(spa);
1120 avl_destroy(&spa->spa_errlist_scrub);
1121 avl_destroy(&spa->spa_errlist_last);
1123 spa->spa_state = POOL_STATE_UNINITIALIZED;
1125 mutex_enter(&spa->spa_proc_lock);
1126 if (spa->spa_proc_state != SPA_PROC_NONE) {
1127 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1128 spa->spa_proc_state = SPA_PROC_DEACTIVATE;
1129 cv_broadcast(&spa->spa_proc_cv);
1130 while (spa->spa_proc_state == SPA_PROC_DEACTIVATE) {
1131 ASSERT(spa->spa_proc != &p0);
1132 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1134 ASSERT(spa->spa_proc_state == SPA_PROC_GONE);
1135 spa->spa_proc_state = SPA_PROC_NONE;
1137 ASSERT(spa->spa_proc == &p0);
1138 mutex_exit(&spa->spa_proc_lock);
1141 * We want to make sure spa_thread() has actually exited the ZFS
1142 * module, so that the module can't be unloaded out from underneath
1143 * it.
1145 if (spa->spa_did != 0) {
1146 thread_join(spa->spa_did);
1147 spa->spa_did = 0;
1152 * Verify a pool configuration, and construct the vdev tree appropriately. This
1153 * will create all the necessary vdevs in the appropriate layout, with each vdev
1154 * in the CLOSED state. This will prep the pool before open/creation/import.
1155 * All vdev validation is done by the vdev_alloc() routine.
1157 static int
1158 spa_config_parse(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent,
1159 uint_t id, int atype)
1161 nvlist_t **child;
1162 uint_t children;
1163 int error;
1165 if ((error = vdev_alloc(spa, vdp, nv, parent, id, atype)) != 0)
1166 return (error);
1168 if ((*vdp)->vdev_ops->vdev_op_leaf)
1169 return (0);
1171 error = nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1172 &child, &children);
1174 if (error == ENOENT)
1175 return (0);
1177 if (error) {
1178 vdev_free(*vdp);
1179 *vdp = NULL;
1180 return (SET_ERROR(EINVAL));
1183 for (int c = 0; c < children; c++) {
1184 vdev_t *vd;
1185 if ((error = spa_config_parse(spa, &vd, child[c], *vdp, c,
1186 atype)) != 0) {
1187 vdev_free(*vdp);
1188 *vdp = NULL;
1189 return (error);
1193 ASSERT(*vdp != NULL);
1195 return (0);
1199 * Opposite of spa_load().
1201 static void
1202 spa_unload(spa_t *spa)
1204 int i;
1206 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1209 * Stop async tasks.
1211 spa_async_suspend(spa);
1214 * Stop syncing.
1216 if (spa->spa_sync_on) {
1217 txg_sync_stop(spa->spa_dsl_pool);
1218 spa->spa_sync_on = B_FALSE;
1222 * Wait for any outstanding async I/O to complete.
1224 if (spa->spa_async_zio_root != NULL) {
1225 (void) zio_wait(spa->spa_async_zio_root);
1226 spa->spa_async_zio_root = NULL;
1229 bpobj_close(&spa->spa_deferred_bpobj);
1231 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1234 * Close all vdevs.
1236 if (spa->spa_root_vdev)
1237 vdev_free(spa->spa_root_vdev);
1238 ASSERT(spa->spa_root_vdev == NULL);
1241 * Close the dsl pool.
1243 if (spa->spa_dsl_pool) {
1244 dsl_pool_close(spa->spa_dsl_pool);
1245 spa->spa_dsl_pool = NULL;
1246 spa->spa_meta_objset = NULL;
1249 ddt_unload(spa);
1253 * Drop and purge level 2 cache
1255 spa_l2cache_drop(spa);
1257 for (i = 0; i < spa->spa_spares.sav_count; i++)
1258 vdev_free(spa->spa_spares.sav_vdevs[i]);
1259 if (spa->spa_spares.sav_vdevs) {
1260 kmem_free(spa->spa_spares.sav_vdevs,
1261 spa->spa_spares.sav_count * sizeof (void *));
1262 spa->spa_spares.sav_vdevs = NULL;
1264 if (spa->spa_spares.sav_config) {
1265 nvlist_free(spa->spa_spares.sav_config);
1266 spa->spa_spares.sav_config = NULL;
1268 spa->spa_spares.sav_count = 0;
1270 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
1271 vdev_clear_stats(spa->spa_l2cache.sav_vdevs[i]);
1272 vdev_free(spa->spa_l2cache.sav_vdevs[i]);
1274 if (spa->spa_l2cache.sav_vdevs) {
1275 kmem_free(spa->spa_l2cache.sav_vdevs,
1276 spa->spa_l2cache.sav_count * sizeof (void *));
1277 spa->spa_l2cache.sav_vdevs = NULL;
1279 if (spa->spa_l2cache.sav_config) {
1280 nvlist_free(spa->spa_l2cache.sav_config);
1281 spa->spa_l2cache.sav_config = NULL;
1283 spa->spa_l2cache.sav_count = 0;
1285 spa->spa_async_suspended = 0;
1287 if (spa->spa_comment != NULL) {
1288 spa_strfree(spa->spa_comment);
1289 spa->spa_comment = NULL;
1292 spa_config_exit(spa, SCL_ALL, FTAG);
1296 * Load (or re-load) the current list of vdevs describing the active spares for
1297 * this pool. When this is called, we have some form of basic information in
1298 * 'spa_spares.sav_config'. We parse this into vdevs, try to open them, and
1299 * then re-generate a more complete list including status information.
1301 static void
1302 spa_load_spares(spa_t *spa)
1304 nvlist_t **spares;
1305 uint_t nspares;
1306 int i;
1307 vdev_t *vd, *tvd;
1309 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1312 * First, close and free any existing spare vdevs.
1314 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1315 vd = spa->spa_spares.sav_vdevs[i];
1317 /* Undo the call to spa_activate() below */
1318 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1319 B_FALSE)) != NULL && tvd->vdev_isspare)
1320 spa_spare_remove(tvd);
1321 vdev_close(vd);
1322 vdev_free(vd);
1325 if (spa->spa_spares.sav_vdevs)
1326 kmem_free(spa->spa_spares.sav_vdevs,
1327 spa->spa_spares.sav_count * sizeof (void *));
1329 if (spa->spa_spares.sav_config == NULL)
1330 nspares = 0;
1331 else
1332 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
1333 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
1335 spa->spa_spares.sav_count = (int)nspares;
1336 spa->spa_spares.sav_vdevs = NULL;
1338 if (nspares == 0)
1339 return;
1342 * Construct the array of vdevs, opening them to get status in the
1343 * process. For each spare, there is potentially two different vdev_t
1344 * structures associated with it: one in the list of spares (used only
1345 * for basic validation purposes) and one in the active vdev
1346 * configuration (if it's spared in). During this phase we open and
1347 * validate each vdev on the spare list. If the vdev also exists in the
1348 * active configuration, then we also mark this vdev as an active spare.
1350 spa->spa_spares.sav_vdevs = kmem_alloc(nspares * sizeof (void *),
1351 KM_SLEEP);
1352 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1353 VERIFY(spa_config_parse(spa, &vd, spares[i], NULL, 0,
1354 VDEV_ALLOC_SPARE) == 0);
1355 ASSERT(vd != NULL);
1357 spa->spa_spares.sav_vdevs[i] = vd;
1359 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1360 B_FALSE)) != NULL) {
1361 if (!tvd->vdev_isspare)
1362 spa_spare_add(tvd);
1365 * We only mark the spare active if we were successfully
1366 * able to load the vdev. Otherwise, importing a pool
1367 * with a bad active spare would result in strange
1368 * behavior, because multiple pool would think the spare
1369 * is actively in use.
1371 * There is a vulnerability here to an equally bizarre
1372 * circumstance, where a dead active spare is later
1373 * brought back to life (onlined or otherwise). Given
1374 * the rarity of this scenario, and the extra complexity
1375 * it adds, we ignore the possibility.
1377 if (!vdev_is_dead(tvd))
1378 spa_spare_activate(tvd);
1381 vd->vdev_top = vd;
1382 vd->vdev_aux = &spa->spa_spares;
1384 if (vdev_open(vd) != 0)
1385 continue;
1387 if (vdev_validate_aux(vd) == 0)
1388 spa_spare_add(vd);
1392 * Recompute the stashed list of spares, with status information
1393 * this time.
1395 VERIFY(nvlist_remove(spa->spa_spares.sav_config, ZPOOL_CONFIG_SPARES,
1396 DATA_TYPE_NVLIST_ARRAY) == 0);
1398 spares = kmem_alloc(spa->spa_spares.sav_count * sizeof (void *),
1399 KM_SLEEP);
1400 for (i = 0; i < spa->spa_spares.sav_count; i++)
1401 spares[i] = vdev_config_generate(spa,
1402 spa->spa_spares.sav_vdevs[i], B_TRUE, VDEV_CONFIG_SPARE);
1403 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
1404 ZPOOL_CONFIG_SPARES, spares, spa->spa_spares.sav_count) == 0);
1405 for (i = 0; i < spa->spa_spares.sav_count; i++)
1406 nvlist_free(spares[i]);
1407 kmem_free(spares, spa->spa_spares.sav_count * sizeof (void *));
1411 * Load (or re-load) the current list of vdevs describing the active l2cache for
1412 * this pool. When this is called, we have some form of basic information in
1413 * 'spa_l2cache.sav_config'. We parse this into vdevs, try to open them, and
1414 * then re-generate a more complete list including status information.
1415 * Devices which are already active have their details maintained, and are
1416 * not re-opened.
1418 static void
1419 spa_load_l2cache(spa_t *spa)
1421 nvlist_t **l2cache;
1422 uint_t nl2cache;
1423 int i, j, oldnvdevs;
1424 uint64_t guid;
1425 vdev_t *vd, **oldvdevs, **newvdevs;
1426 spa_aux_vdev_t *sav = &spa->spa_l2cache;
1428 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1430 if (sav->sav_config != NULL) {
1431 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
1432 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
1433 newvdevs = kmem_alloc(nl2cache * sizeof (void *), KM_SLEEP);
1434 } else {
1435 nl2cache = 0;
1436 newvdevs = NULL;
1439 oldvdevs = sav->sav_vdevs;
1440 oldnvdevs = sav->sav_count;
1441 sav->sav_vdevs = NULL;
1442 sav->sav_count = 0;
1445 * Process new nvlist of vdevs.
1447 for (i = 0; i < nl2cache; i++) {
1448 VERIFY(nvlist_lookup_uint64(l2cache[i], ZPOOL_CONFIG_GUID,
1449 &guid) == 0);
1451 newvdevs[i] = NULL;
1452 for (j = 0; j < oldnvdevs; j++) {
1453 vd = oldvdevs[j];
1454 if (vd != NULL && guid == vd->vdev_guid) {
1456 * Retain previous vdev for add/remove ops.
1458 newvdevs[i] = vd;
1459 oldvdevs[j] = NULL;
1460 break;
1464 if (newvdevs[i] == NULL) {
1466 * Create new vdev
1468 VERIFY(spa_config_parse(spa, &vd, l2cache[i], NULL, 0,
1469 VDEV_ALLOC_L2CACHE) == 0);
1470 ASSERT(vd != NULL);
1471 newvdevs[i] = vd;
1474 * Commit this vdev as an l2cache device,
1475 * even if it fails to open.
1477 spa_l2cache_add(vd);
1479 vd->vdev_top = vd;
1480 vd->vdev_aux = sav;
1482 spa_l2cache_activate(vd);
1484 if (vdev_open(vd) != 0)
1485 continue;
1487 (void) vdev_validate_aux(vd);
1489 if (!vdev_is_dead(vd))
1490 l2arc_add_vdev(spa, vd);
1495 * Purge vdevs that were dropped
1497 for (i = 0; i < oldnvdevs; i++) {
1498 uint64_t pool;
1500 vd = oldvdevs[i];
1501 if (vd != NULL) {
1502 ASSERT(vd->vdev_isl2cache);
1504 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
1505 pool != 0ULL && l2arc_vdev_present(vd))
1506 l2arc_remove_vdev(vd);
1507 vdev_clear_stats(vd);
1508 vdev_free(vd);
1512 if (oldvdevs)
1513 kmem_free(oldvdevs, oldnvdevs * sizeof (void *));
1515 if (sav->sav_config == NULL)
1516 goto out;
1518 sav->sav_vdevs = newvdevs;
1519 sav->sav_count = (int)nl2cache;
1522 * Recompute the stashed list of l2cache devices, with status
1523 * information this time.
1525 VERIFY(nvlist_remove(sav->sav_config, ZPOOL_CONFIG_L2CACHE,
1526 DATA_TYPE_NVLIST_ARRAY) == 0);
1528 l2cache = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
1529 for (i = 0; i < sav->sav_count; i++)
1530 l2cache[i] = vdev_config_generate(spa,
1531 sav->sav_vdevs[i], B_TRUE, VDEV_CONFIG_L2CACHE);
1532 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
1533 ZPOOL_CONFIG_L2CACHE, l2cache, sav->sav_count) == 0);
1534 out:
1535 for (i = 0; i < sav->sav_count; i++)
1536 nvlist_free(l2cache[i]);
1537 if (sav->sav_count)
1538 kmem_free(l2cache, sav->sav_count * sizeof (void *));
1541 static int
1542 load_nvlist(spa_t *spa, uint64_t obj, nvlist_t **value)
1544 dmu_buf_t *db;
1545 char *packed = NULL;
1546 size_t nvsize = 0;
1547 int error;
1548 *value = NULL;
1550 VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
1551 nvsize = *(uint64_t *)db->db_data;
1552 dmu_buf_rele(db, FTAG);
1554 packed = kmem_alloc(nvsize, KM_SLEEP);
1555 error = dmu_read(spa->spa_meta_objset, obj, 0, nvsize, packed,
1556 DMU_READ_PREFETCH);
1557 if (error == 0)
1558 error = nvlist_unpack(packed, nvsize, value, 0);
1559 kmem_free(packed, nvsize);
1561 return (error);
1565 * Checks to see if the given vdev could not be opened, in which case we post a
1566 * sysevent to notify the autoreplace code that the device has been removed.
1568 static void
1569 spa_check_removed(vdev_t *vd)
1571 for (int c = 0; c < vd->vdev_children; c++)
1572 spa_check_removed(vd->vdev_child[c]);
1574 if (vd->vdev_ops->vdev_op_leaf && vdev_is_dead(vd) &&
1575 !vd->vdev_ishole) {
1576 zfs_post_autoreplace(vd->vdev_spa, vd);
1577 spa_event_notify(vd->vdev_spa, vd, ESC_ZFS_VDEV_CHECK);
1582 * Validate the current config against the MOS config
1584 static boolean_t
1585 spa_config_valid(spa_t *spa, nvlist_t *config)
1587 vdev_t *mrvd, *rvd = spa->spa_root_vdev;
1588 nvlist_t *nv;
1590 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nv) == 0);
1592 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1593 VERIFY(spa_config_parse(spa, &mrvd, nv, NULL, 0, VDEV_ALLOC_LOAD) == 0);
1595 ASSERT3U(rvd->vdev_children, ==, mrvd->vdev_children);
1598 * If we're doing a normal import, then build up any additional
1599 * diagnostic information about missing devices in this config.
1600 * We'll pass this up to the user for further processing.
1602 if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG)) {
1603 nvlist_t **child, *nv;
1604 uint64_t idx = 0;
1606 child = kmem_alloc(rvd->vdev_children * sizeof (nvlist_t **),
1607 KM_SLEEP);
1608 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1610 for (int c = 0; c < rvd->vdev_children; c++) {
1611 vdev_t *tvd = rvd->vdev_child[c];
1612 vdev_t *mtvd = mrvd->vdev_child[c];
1614 if (tvd->vdev_ops == &vdev_missing_ops &&
1615 mtvd->vdev_ops != &vdev_missing_ops &&
1616 mtvd->vdev_islog)
1617 child[idx++] = vdev_config_generate(spa, mtvd,
1618 B_FALSE, 0);
1621 if (idx) {
1622 VERIFY(nvlist_add_nvlist_array(nv,
1623 ZPOOL_CONFIG_CHILDREN, child, idx) == 0);
1624 VERIFY(nvlist_add_nvlist(spa->spa_load_info,
1625 ZPOOL_CONFIG_MISSING_DEVICES, nv) == 0);
1627 for (int i = 0; i < idx; i++)
1628 nvlist_free(child[i]);
1630 nvlist_free(nv);
1631 kmem_free(child, rvd->vdev_children * sizeof (char **));
1635 * Compare the root vdev tree with the information we have
1636 * from the MOS config (mrvd). Check each top-level vdev
1637 * with the corresponding MOS config top-level (mtvd).
1639 for (int c = 0; c < rvd->vdev_children; c++) {
1640 vdev_t *tvd = rvd->vdev_child[c];
1641 vdev_t *mtvd = mrvd->vdev_child[c];
1644 * Resolve any "missing" vdevs in the current configuration.
1645 * If we find that the MOS config has more accurate information
1646 * about the top-level vdev then use that vdev instead.
1648 if (tvd->vdev_ops == &vdev_missing_ops &&
1649 mtvd->vdev_ops != &vdev_missing_ops) {
1651 if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG))
1652 continue;
1655 * Device specific actions.
1657 if (mtvd->vdev_islog) {
1658 spa_set_log_state(spa, SPA_LOG_CLEAR);
1659 } else {
1661 * XXX - once we have 'readonly' pool
1662 * support we should be able to handle
1663 * missing data devices by transitioning
1664 * the pool to readonly.
1666 continue;
1670 * Swap the missing vdev with the data we were
1671 * able to obtain from the MOS config.
1673 vdev_remove_child(rvd, tvd);
1674 vdev_remove_child(mrvd, mtvd);
1676 vdev_add_child(rvd, mtvd);
1677 vdev_add_child(mrvd, tvd);
1679 spa_config_exit(spa, SCL_ALL, FTAG);
1680 vdev_load(mtvd);
1681 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1683 vdev_reopen(rvd);
1684 } else if (mtvd->vdev_islog) {
1686 * Load the slog device's state from the MOS config
1687 * since it's possible that the label does not
1688 * contain the most up-to-date information.
1690 vdev_load_log_state(tvd, mtvd);
1691 vdev_reopen(tvd);
1694 vdev_free(mrvd);
1695 spa_config_exit(spa, SCL_ALL, FTAG);
1698 * Ensure we were able to validate the config.
1700 return (rvd->vdev_guid_sum == spa->spa_uberblock.ub_guid_sum);
1704 * Check for missing log devices
1706 static boolean_t
1707 spa_check_logs(spa_t *spa)
1709 boolean_t rv = B_FALSE;
1711 switch (spa->spa_log_state) {
1712 case SPA_LOG_MISSING:
1713 /* need to recheck in case slog has been restored */
1714 case SPA_LOG_UNKNOWN:
1715 rv = (dmu_objset_find(spa->spa_name, zil_check_log_chain,
1716 NULL, DS_FIND_CHILDREN) != 0);
1717 if (rv)
1718 spa_set_log_state(spa, SPA_LOG_MISSING);
1719 break;
1721 return (rv);
1724 static boolean_t
1725 spa_passivate_log(spa_t *spa)
1727 vdev_t *rvd = spa->spa_root_vdev;
1728 boolean_t slog_found = B_FALSE;
1730 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1732 if (!spa_has_slogs(spa))
1733 return (B_FALSE);
1735 for (int c = 0; c < rvd->vdev_children; c++) {
1736 vdev_t *tvd = rvd->vdev_child[c];
1737 metaslab_group_t *mg = tvd->vdev_mg;
1739 if (tvd->vdev_islog) {
1740 metaslab_group_passivate(mg);
1741 slog_found = B_TRUE;
1745 return (slog_found);
1748 static void
1749 spa_activate_log(spa_t *spa)
1751 vdev_t *rvd = spa->spa_root_vdev;
1753 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1755 for (int c = 0; c < rvd->vdev_children; c++) {
1756 vdev_t *tvd = rvd->vdev_child[c];
1757 metaslab_group_t *mg = tvd->vdev_mg;
1759 if (tvd->vdev_islog)
1760 metaslab_group_activate(mg);
1765 spa_offline_log(spa_t *spa)
1767 int error;
1769 error = dmu_objset_find(spa_name(spa), zil_vdev_offline,
1770 NULL, DS_FIND_CHILDREN);
1771 if (error == 0) {
1773 * We successfully offlined the log device, sync out the
1774 * current txg so that the "stubby" block can be removed
1775 * by zil_sync().
1777 txg_wait_synced(spa->spa_dsl_pool, 0);
1779 return (error);
1782 static void
1783 spa_aux_check_removed(spa_aux_vdev_t *sav)
1785 for (int i = 0; i < sav->sav_count; i++)
1786 spa_check_removed(sav->sav_vdevs[i]);
1789 void
1790 spa_claim_notify(zio_t *zio)
1792 spa_t *spa = zio->io_spa;
1794 if (zio->io_error)
1795 return;
1797 mutex_enter(&spa->spa_props_lock); /* any mutex will do */
1798 if (spa->spa_claim_max_txg < zio->io_bp->blk_birth)
1799 spa->spa_claim_max_txg = zio->io_bp->blk_birth;
1800 mutex_exit(&spa->spa_props_lock);
1803 typedef struct spa_load_error {
1804 uint64_t sle_meta_count;
1805 uint64_t sle_data_count;
1806 } spa_load_error_t;
1808 static void
1809 spa_load_verify_done(zio_t *zio)
1811 blkptr_t *bp = zio->io_bp;
1812 spa_load_error_t *sle = zio->io_private;
1813 dmu_object_type_t type = BP_GET_TYPE(bp);
1814 int error = zio->io_error;
1815 spa_t *spa = zio->io_spa;
1817 if (error) {
1818 if ((BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type)) &&
1819 type != DMU_OT_INTENT_LOG)
1820 atomic_add_64(&sle->sle_meta_count, 1);
1821 else
1822 atomic_add_64(&sle->sle_data_count, 1);
1824 zio_data_buf_free(zio->io_data, zio->io_size);
1826 mutex_enter(&spa->spa_scrub_lock);
1827 spa->spa_scrub_inflight--;
1828 cv_broadcast(&spa->spa_scrub_io_cv);
1829 mutex_exit(&spa->spa_scrub_lock);
1833 * Maximum number of concurrent scrub i/os to create while verifying
1834 * a pool while importing it.
1836 int spa_load_verify_maxinflight = 10000;
1837 boolean_t spa_load_verify_metadata = B_TRUE;
1838 boolean_t spa_load_verify_data = B_TRUE;
1840 /*ARGSUSED*/
1841 static int
1842 spa_load_verify_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
1843 const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
1845 if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
1846 return (0);
1848 * Note: normally this routine will not be called if
1849 * spa_load_verify_metadata is not set. However, it may be useful
1850 * to manually set the flag after the traversal has begun.
1852 if (!spa_load_verify_metadata)
1853 return (0);
1854 if (BP_GET_BUFC_TYPE(bp) == ARC_BUFC_DATA && !spa_load_verify_data)
1855 return (0);
1857 zio_t *rio = arg;
1858 size_t size = BP_GET_PSIZE(bp);
1859 void *data = zio_data_buf_alloc(size);
1861 mutex_enter(&spa->spa_scrub_lock);
1862 while (spa->spa_scrub_inflight >= spa_load_verify_maxinflight)
1863 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
1864 spa->spa_scrub_inflight++;
1865 mutex_exit(&spa->spa_scrub_lock);
1867 zio_nowait(zio_read(rio, spa, bp, data, size,
1868 spa_load_verify_done, rio->io_private, ZIO_PRIORITY_SCRUB,
1869 ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CANFAIL |
1870 ZIO_FLAG_SCRUB | ZIO_FLAG_RAW, zb));
1871 return (0);
1874 static int
1875 spa_load_verify(spa_t *spa)
1877 zio_t *rio;
1878 spa_load_error_t sle = { 0 };
1879 zpool_rewind_policy_t policy;
1880 boolean_t verify_ok = B_FALSE;
1881 int error = 0;
1883 zpool_get_rewind_policy(spa->spa_config, &policy);
1885 if (policy.zrp_request & ZPOOL_NEVER_REWIND)
1886 return (0);
1888 rio = zio_root(spa, NULL, &sle,
1889 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
1891 if (spa_load_verify_metadata) {
1892 error = traverse_pool(spa, spa->spa_verify_min_txg,
1893 TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA,
1894 spa_load_verify_cb, rio);
1897 (void) zio_wait(rio);
1899 spa->spa_load_meta_errors = sle.sle_meta_count;
1900 spa->spa_load_data_errors = sle.sle_data_count;
1902 if (!error && sle.sle_meta_count <= policy.zrp_maxmeta &&
1903 sle.sle_data_count <= policy.zrp_maxdata) {
1904 int64_t loss = 0;
1906 verify_ok = B_TRUE;
1907 spa->spa_load_txg = spa->spa_uberblock.ub_txg;
1908 spa->spa_load_txg_ts = spa->spa_uberblock.ub_timestamp;
1910 loss = spa->spa_last_ubsync_txg_ts - spa->spa_load_txg_ts;
1911 VERIFY(nvlist_add_uint64(spa->spa_load_info,
1912 ZPOOL_CONFIG_LOAD_TIME, spa->spa_load_txg_ts) == 0);
1913 VERIFY(nvlist_add_int64(spa->spa_load_info,
1914 ZPOOL_CONFIG_REWIND_TIME, loss) == 0);
1915 VERIFY(nvlist_add_uint64(spa->spa_load_info,
1916 ZPOOL_CONFIG_LOAD_DATA_ERRORS, sle.sle_data_count) == 0);
1917 } else {
1918 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg;
1921 if (error) {
1922 if (error != ENXIO && error != EIO)
1923 error = SET_ERROR(EIO);
1924 return (error);
1927 return (verify_ok ? 0 : EIO);
1931 * Find a value in the pool props object.
1933 static void
1934 spa_prop_find(spa_t *spa, zpool_prop_t prop, uint64_t *val)
1936 (void) zap_lookup(spa->spa_meta_objset, spa->spa_pool_props_object,
1937 zpool_prop_to_name(prop), sizeof (uint64_t), 1, val);
1941 * Find a value in the pool directory object.
1943 static int
1944 spa_dir_prop(spa_t *spa, const char *name, uint64_t *val)
1946 return (zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
1947 name, sizeof (uint64_t), 1, val));
1950 static int
1951 spa_vdev_err(vdev_t *vdev, vdev_aux_t aux, int err)
1953 vdev_set_state(vdev, B_TRUE, VDEV_STATE_CANT_OPEN, aux);
1954 return (err);
1958 * Fix up config after a partly-completed split. This is done with the
1959 * ZPOOL_CONFIG_SPLIT nvlist. Both the splitting pool and the split-off
1960 * pool have that entry in their config, but only the splitting one contains
1961 * a list of all the guids of the vdevs that are being split off.
1963 * This function determines what to do with that list: either rejoin
1964 * all the disks to the pool, or complete the splitting process. To attempt
1965 * the rejoin, each disk that is offlined is marked online again, and
1966 * we do a reopen() call. If the vdev label for every disk that was
1967 * marked online indicates it was successfully split off (VDEV_AUX_SPLIT_POOL)
1968 * then we call vdev_split() on each disk, and complete the split.
1970 * Otherwise we leave the config alone, with all the vdevs in place in
1971 * the original pool.
1973 static void
1974 spa_try_repair(spa_t *spa, nvlist_t *config)
1976 uint_t extracted;
1977 uint64_t *glist;
1978 uint_t i, gcount;
1979 nvlist_t *nvl;
1980 vdev_t **vd;
1981 boolean_t attempt_reopen;
1983 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) != 0)
1984 return;
1986 /* check that the config is complete */
1987 if (nvlist_lookup_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
1988 &glist, &gcount) != 0)
1989 return;
1991 vd = kmem_zalloc(gcount * sizeof (vdev_t *), KM_SLEEP);
1993 /* attempt to online all the vdevs & validate */
1994 attempt_reopen = B_TRUE;
1995 for (i = 0; i < gcount; i++) {
1996 if (glist[i] == 0) /* vdev is hole */
1997 continue;
1999 vd[i] = spa_lookup_by_guid(spa, glist[i], B_FALSE);
2000 if (vd[i] == NULL) {
2002 * Don't bother attempting to reopen the disks;
2003 * just do the split.
2005 attempt_reopen = B_FALSE;
2006 } else {
2007 /* attempt to re-online it */
2008 vd[i]->vdev_offline = B_FALSE;
2012 if (attempt_reopen) {
2013 vdev_reopen(spa->spa_root_vdev);
2015 /* check each device to see what state it's in */
2016 for (extracted = 0, i = 0; i < gcount; i++) {
2017 if (vd[i] != NULL &&
2018 vd[i]->vdev_stat.vs_aux != VDEV_AUX_SPLIT_POOL)
2019 break;
2020 ++extracted;
2025 * If every disk has been moved to the new pool, or if we never
2026 * even attempted to look at them, then we split them off for
2027 * good.
2029 if (!attempt_reopen || gcount == extracted) {
2030 for (i = 0; i < gcount; i++)
2031 if (vd[i] != NULL)
2032 vdev_split(vd[i]);
2033 vdev_reopen(spa->spa_root_vdev);
2036 kmem_free(vd, gcount * sizeof (vdev_t *));
2039 static int
2040 spa_load(spa_t *spa, spa_load_state_t state, spa_import_type_t type,
2041 boolean_t mosconfig)
2043 nvlist_t *config = spa->spa_config;
2044 char *ereport = FM_EREPORT_ZFS_POOL;
2045 char *comment;
2046 int error;
2047 uint64_t pool_guid;
2048 nvlist_t *nvl;
2050 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid))
2051 return (SET_ERROR(EINVAL));
2053 ASSERT(spa->spa_comment == NULL);
2054 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2055 spa->spa_comment = spa_strdup(comment);
2058 * Versioning wasn't explicitly added to the label until later, so if
2059 * it's not present treat it as the initial version.
2061 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
2062 &spa->spa_ubsync.ub_version) != 0)
2063 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
2065 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
2066 &spa->spa_config_txg);
2068 if ((state == SPA_LOAD_IMPORT || state == SPA_LOAD_TRYIMPORT) &&
2069 spa_guid_exists(pool_guid, 0)) {
2070 error = SET_ERROR(EEXIST);
2071 } else {
2072 spa->spa_config_guid = pool_guid;
2074 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT,
2075 &nvl) == 0) {
2076 VERIFY(nvlist_dup(nvl, &spa->spa_config_splitting,
2077 KM_SLEEP) == 0);
2080 nvlist_free(spa->spa_load_info);
2081 spa->spa_load_info = fnvlist_alloc();
2083 gethrestime(&spa->spa_loaded_ts);
2084 error = spa_load_impl(spa, pool_guid, config, state, type,
2085 mosconfig, &ereport);
2088 spa->spa_minref = refcount_count(&spa->spa_refcount);
2089 if (error) {
2090 if (error != EEXIST) {
2091 spa->spa_loaded_ts.tv_sec = 0;
2092 spa->spa_loaded_ts.tv_nsec = 0;
2094 if (error != EBADF) {
2095 zfs_ereport_post(ereport, spa, NULL, NULL, 0, 0);
2098 spa->spa_load_state = error ? SPA_LOAD_ERROR : SPA_LOAD_NONE;
2099 spa->spa_ena = 0;
2101 return (error);
2105 * Load an existing storage pool, using the pool's builtin spa_config as a
2106 * source of configuration information.
2108 static int
2109 spa_load_impl(spa_t *spa, uint64_t pool_guid, nvlist_t *config,
2110 spa_load_state_t state, spa_import_type_t type, boolean_t mosconfig,
2111 char **ereport)
2113 int error = 0;
2114 nvlist_t *nvroot = NULL;
2115 nvlist_t *label;
2116 vdev_t *rvd;
2117 uberblock_t *ub = &spa->spa_uberblock;
2118 uint64_t children, config_cache_txg = spa->spa_config_txg;
2119 int orig_mode = spa->spa_mode;
2120 int parse;
2121 uint64_t obj;
2122 boolean_t missing_feat_write = B_FALSE;
2125 * If this is an untrusted config, access the pool in read-only mode.
2126 * This prevents things like resilvering recently removed devices.
2128 if (!mosconfig)
2129 spa->spa_mode = FREAD;
2131 ASSERT(MUTEX_HELD(&spa_namespace_lock));
2133 spa->spa_load_state = state;
2135 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvroot))
2136 return (SET_ERROR(EINVAL));
2138 parse = (type == SPA_IMPORT_EXISTING ?
2139 VDEV_ALLOC_LOAD : VDEV_ALLOC_SPLIT);
2142 * Create "The Godfather" zio to hold all async IOs
2144 spa->spa_async_zio_root = zio_root(spa, NULL, NULL,
2145 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE | ZIO_FLAG_GODFATHER);
2148 * Parse the configuration into a vdev tree. We explicitly set the
2149 * value that will be returned by spa_version() since parsing the
2150 * configuration requires knowing the version number.
2152 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2153 error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, parse);
2154 spa_config_exit(spa, SCL_ALL, FTAG);
2156 if (error != 0)
2157 return (error);
2159 ASSERT(spa->spa_root_vdev == rvd);
2161 if (type != SPA_IMPORT_ASSEMBLE) {
2162 ASSERT(spa_guid(spa) == pool_guid);
2166 * Try to open all vdevs, loading each label in the process.
2168 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2169 error = vdev_open(rvd);
2170 spa_config_exit(spa, SCL_ALL, FTAG);
2171 if (error != 0)
2172 return (error);
2175 * We need to validate the vdev labels against the configuration that
2176 * we have in hand, which is dependent on the setting of mosconfig. If
2177 * mosconfig is true then we're validating the vdev labels based on
2178 * that config. Otherwise, we're validating against the cached config
2179 * (zpool.cache) that was read when we loaded the zfs module, and then
2180 * later we will recursively call spa_load() and validate against
2181 * the vdev config.
2183 * If we're assembling a new pool that's been split off from an
2184 * existing pool, the labels haven't yet been updated so we skip
2185 * validation for now.
2187 if (type != SPA_IMPORT_ASSEMBLE) {
2188 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2189 error = vdev_validate(rvd, mosconfig);
2190 spa_config_exit(spa, SCL_ALL, FTAG);
2192 if (error != 0)
2193 return (error);
2195 if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN)
2196 return (SET_ERROR(ENXIO));
2200 * Find the best uberblock.
2202 vdev_uberblock_load(rvd, ub, &label);
2205 * If we weren't able to find a single valid uberblock, return failure.
2207 if (ub->ub_txg == 0) {
2208 nvlist_free(label);
2209 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, ENXIO));
2213 * If the pool has an unsupported version we can't open it.
2215 if (!SPA_VERSION_IS_SUPPORTED(ub->ub_version)) {
2216 nvlist_free(label);
2217 return (spa_vdev_err(rvd, VDEV_AUX_VERSION_NEWER, ENOTSUP));
2220 if (ub->ub_version >= SPA_VERSION_FEATURES) {
2221 nvlist_t *features;
2224 * If we weren't able to find what's necessary for reading the
2225 * MOS in the label, return failure.
2227 if (label == NULL || nvlist_lookup_nvlist(label,
2228 ZPOOL_CONFIG_FEATURES_FOR_READ, &features) != 0) {
2229 nvlist_free(label);
2230 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2231 ENXIO));
2235 * Update our in-core representation with the definitive values
2236 * from the label.
2238 nvlist_free(spa->spa_label_features);
2239 VERIFY(nvlist_dup(features, &spa->spa_label_features, 0) == 0);
2242 nvlist_free(label);
2245 * Look through entries in the label nvlist's features_for_read. If
2246 * there is a feature listed there which we don't understand then we
2247 * cannot open a pool.
2249 if (ub->ub_version >= SPA_VERSION_FEATURES) {
2250 nvlist_t *unsup_feat;
2252 VERIFY(nvlist_alloc(&unsup_feat, NV_UNIQUE_NAME, KM_SLEEP) ==
2255 for (nvpair_t *nvp = nvlist_next_nvpair(spa->spa_label_features,
2256 NULL); nvp != NULL;
2257 nvp = nvlist_next_nvpair(spa->spa_label_features, nvp)) {
2258 if (!zfeature_is_supported(nvpair_name(nvp))) {
2259 VERIFY(nvlist_add_string(unsup_feat,
2260 nvpair_name(nvp), "") == 0);
2264 if (!nvlist_empty(unsup_feat)) {
2265 VERIFY(nvlist_add_nvlist(spa->spa_load_info,
2266 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat) == 0);
2267 nvlist_free(unsup_feat);
2268 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
2269 ENOTSUP));
2272 nvlist_free(unsup_feat);
2276 * If the vdev guid sum doesn't match the uberblock, we have an
2277 * incomplete configuration. We first check to see if the pool
2278 * is aware of the complete config (i.e ZPOOL_CONFIG_VDEV_CHILDREN).
2279 * If it is, defer the vdev_guid_sum check till later so we
2280 * can handle missing vdevs.
2282 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VDEV_CHILDREN,
2283 &children) != 0 && mosconfig && type != SPA_IMPORT_ASSEMBLE &&
2284 rvd->vdev_guid_sum != ub->ub_guid_sum)
2285 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM, ENXIO));
2287 if (type != SPA_IMPORT_ASSEMBLE && spa->spa_config_splitting) {
2288 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2289 spa_try_repair(spa, config);
2290 spa_config_exit(spa, SCL_ALL, FTAG);
2291 nvlist_free(spa->spa_config_splitting);
2292 spa->spa_config_splitting = NULL;
2296 * Initialize internal SPA structures.
2298 spa->spa_state = POOL_STATE_ACTIVE;
2299 spa->spa_ubsync = spa->spa_uberblock;
2300 spa->spa_verify_min_txg = spa->spa_extreme_rewind ?
2301 TXG_INITIAL - 1 : spa_last_synced_txg(spa) - TXG_DEFER_SIZE - 1;
2302 spa->spa_first_txg = spa->spa_last_ubsync_txg ?
2303 spa->spa_last_ubsync_txg : spa_last_synced_txg(spa) + 1;
2304 spa->spa_claim_max_txg = spa->spa_first_txg;
2305 spa->spa_prev_software_version = ub->ub_software_version;
2307 error = dsl_pool_init(spa, spa->spa_first_txg, &spa->spa_dsl_pool);
2308 if (error)
2309 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2310 spa->spa_meta_objset = spa->spa_dsl_pool->dp_meta_objset;
2312 if (spa_dir_prop(spa, DMU_POOL_CONFIG, &spa->spa_config_object) != 0)
2313 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2315 if (spa_version(spa) >= SPA_VERSION_FEATURES) {
2316 boolean_t missing_feat_read = B_FALSE;
2317 nvlist_t *unsup_feat, *enabled_feat;
2319 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_READ,
2320 &spa->spa_feat_for_read_obj) != 0) {
2321 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2324 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_WRITE,
2325 &spa->spa_feat_for_write_obj) != 0) {
2326 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2329 if (spa_dir_prop(spa, DMU_POOL_FEATURE_DESCRIPTIONS,
2330 &spa->spa_feat_desc_obj) != 0) {
2331 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2334 enabled_feat = fnvlist_alloc();
2335 unsup_feat = fnvlist_alloc();
2337 if (!spa_features_check(spa, B_FALSE,
2338 unsup_feat, enabled_feat))
2339 missing_feat_read = B_TRUE;
2341 if (spa_writeable(spa) || state == SPA_LOAD_TRYIMPORT) {
2342 if (!spa_features_check(spa, B_TRUE,
2343 unsup_feat, enabled_feat)) {
2344 missing_feat_write = B_TRUE;
2348 fnvlist_add_nvlist(spa->spa_load_info,
2349 ZPOOL_CONFIG_ENABLED_FEAT, enabled_feat);
2351 if (!nvlist_empty(unsup_feat)) {
2352 fnvlist_add_nvlist(spa->spa_load_info,
2353 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat);
2356 fnvlist_free(enabled_feat);
2357 fnvlist_free(unsup_feat);
2359 if (!missing_feat_read) {
2360 fnvlist_add_boolean(spa->spa_load_info,
2361 ZPOOL_CONFIG_CAN_RDONLY);
2365 * If the state is SPA_LOAD_TRYIMPORT, our objective is
2366 * twofold: to determine whether the pool is available for
2367 * import in read-write mode and (if it is not) whether the
2368 * pool is available for import in read-only mode. If the pool
2369 * is available for import in read-write mode, it is displayed
2370 * as available in userland; if it is not available for import
2371 * in read-only mode, it is displayed as unavailable in
2372 * userland. If the pool is available for import in read-only
2373 * mode but not read-write mode, it is displayed as unavailable
2374 * in userland with a special note that the pool is actually
2375 * available for open in read-only mode.
2377 * As a result, if the state is SPA_LOAD_TRYIMPORT and we are
2378 * missing a feature for write, we must first determine whether
2379 * the pool can be opened read-only before returning to
2380 * userland in order to know whether to display the
2381 * abovementioned note.
2383 if (missing_feat_read || (missing_feat_write &&
2384 spa_writeable(spa))) {
2385 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
2386 ENOTSUP));
2390 * Load refcounts for ZFS features from disk into an in-memory
2391 * cache during SPA initialization.
2393 for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
2394 uint64_t refcount;
2396 error = feature_get_refcount_from_disk(spa,
2397 &spa_feature_table[i], &refcount);
2398 if (error == 0) {
2399 spa->spa_feat_refcount_cache[i] = refcount;
2400 } else if (error == ENOTSUP) {
2401 spa->spa_feat_refcount_cache[i] =
2402 SPA_FEATURE_DISABLED;
2403 } else {
2404 return (spa_vdev_err(rvd,
2405 VDEV_AUX_CORRUPT_DATA, EIO));
2410 if (spa_feature_is_active(spa, SPA_FEATURE_ENABLED_TXG)) {
2411 if (spa_dir_prop(spa, DMU_POOL_FEATURE_ENABLED_TXG,
2412 &spa->spa_feat_enabled_txg_obj) != 0)
2413 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2416 spa->spa_is_initializing = B_TRUE;
2417 error = dsl_pool_open(spa->spa_dsl_pool);
2418 spa->spa_is_initializing = B_FALSE;
2419 if (error != 0)
2420 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2422 if (!mosconfig) {
2423 uint64_t hostid;
2424 nvlist_t *policy = NULL, *nvconfig;
2426 if (load_nvlist(spa, spa->spa_config_object, &nvconfig) != 0)
2427 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2429 if (!spa_is_root(spa) && nvlist_lookup_uint64(nvconfig,
2430 ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
2431 char *hostname;
2432 unsigned long myhostid = 0;
2434 VERIFY(nvlist_lookup_string(nvconfig,
2435 ZPOOL_CONFIG_HOSTNAME, &hostname) == 0);
2437 #ifdef _KERNEL
2438 myhostid = zone_get_hostid(NULL);
2439 #else /* _KERNEL */
2441 * We're emulating the system's hostid in userland, so
2442 * we can't use zone_get_hostid().
2444 (void) ddi_strtoul(hw_serial, NULL, 10, &myhostid);
2445 #endif /* _KERNEL */
2446 if (hostid != 0 && myhostid != 0 &&
2447 hostid != myhostid) {
2448 nvlist_free(nvconfig);
2449 cmn_err(CE_WARN, "pool '%s' could not be "
2450 "loaded as it was last accessed by "
2451 "another system (host: %s hostid: 0x%lx). "
2452 "See: http://illumos.org/msg/ZFS-8000-EY",
2453 spa_name(spa), hostname,
2454 (unsigned long)hostid);
2455 return (SET_ERROR(EBADF));
2458 if (nvlist_lookup_nvlist(spa->spa_config,
2459 ZPOOL_REWIND_POLICY, &policy) == 0)
2460 VERIFY(nvlist_add_nvlist(nvconfig,
2461 ZPOOL_REWIND_POLICY, policy) == 0);
2463 spa_config_set(spa, nvconfig);
2464 spa_unload(spa);
2465 spa_deactivate(spa);
2466 spa_activate(spa, orig_mode);
2468 return (spa_load(spa, state, SPA_IMPORT_EXISTING, B_TRUE));
2471 if (spa_dir_prop(spa, DMU_POOL_SYNC_BPOBJ, &obj) != 0)
2472 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2473 error = bpobj_open(&spa->spa_deferred_bpobj, spa->spa_meta_objset, obj);
2474 if (error != 0)
2475 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2478 * Load the bit that tells us to use the new accounting function
2479 * (raid-z deflation). If we have an older pool, this will not
2480 * be present.
2482 error = spa_dir_prop(spa, DMU_POOL_DEFLATE, &spa->spa_deflate);
2483 if (error != 0 && error != ENOENT)
2484 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2486 error = spa_dir_prop(spa, DMU_POOL_CREATION_VERSION,
2487 &spa->spa_creation_version);
2488 if (error != 0 && error != ENOENT)
2489 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2492 * Load the persistent error log. If we have an older pool, this will
2493 * not be present.
2495 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_LAST, &spa->spa_errlog_last);
2496 if (error != 0 && error != ENOENT)
2497 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2499 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_SCRUB,
2500 &spa->spa_errlog_scrub);
2501 if (error != 0 && error != ENOENT)
2502 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2505 * Load the history object. If we have an older pool, this
2506 * will not be present.
2508 error = spa_dir_prop(spa, DMU_POOL_HISTORY, &spa->spa_history);
2509 if (error != 0 && error != ENOENT)
2510 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2513 * If we're assembling the pool from the split-off vdevs of
2514 * an existing pool, we don't want to attach the spares & cache
2515 * devices.
2519 * Load any hot spares for this pool.
2521 error = spa_dir_prop(spa, DMU_POOL_SPARES, &spa->spa_spares.sav_object);
2522 if (error != 0 && error != ENOENT)
2523 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2524 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
2525 ASSERT(spa_version(spa) >= SPA_VERSION_SPARES);
2526 if (load_nvlist(spa, spa->spa_spares.sav_object,
2527 &spa->spa_spares.sav_config) != 0)
2528 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2530 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2531 spa_load_spares(spa);
2532 spa_config_exit(spa, SCL_ALL, FTAG);
2533 } else if (error == 0) {
2534 spa->spa_spares.sav_sync = B_TRUE;
2538 * Load any level 2 ARC devices for this pool.
2540 error = spa_dir_prop(spa, DMU_POOL_L2CACHE,
2541 &spa->spa_l2cache.sav_object);
2542 if (error != 0 && error != ENOENT)
2543 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2544 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
2545 ASSERT(spa_version(spa) >= SPA_VERSION_L2CACHE);
2546 if (load_nvlist(spa, spa->spa_l2cache.sav_object,
2547 &spa->spa_l2cache.sav_config) != 0)
2548 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2550 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2551 spa_load_l2cache(spa);
2552 spa_config_exit(spa, SCL_ALL, FTAG);
2553 } else if (error == 0) {
2554 spa->spa_l2cache.sav_sync = B_TRUE;
2557 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
2559 error = spa_dir_prop(spa, DMU_POOL_PROPS, &spa->spa_pool_props_object);
2560 if (error && error != ENOENT)
2561 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2563 if (error == 0) {
2564 uint64_t autoreplace;
2566 spa_prop_find(spa, ZPOOL_PROP_BOOTFS, &spa->spa_bootfs);
2567 spa_prop_find(spa, ZPOOL_PROP_AUTOREPLACE, &autoreplace);
2568 spa_prop_find(spa, ZPOOL_PROP_DELEGATION, &spa->spa_delegation);
2569 spa_prop_find(spa, ZPOOL_PROP_FAILUREMODE, &spa->spa_failmode);
2570 spa_prop_find(spa, ZPOOL_PROP_AUTOEXPAND, &spa->spa_autoexpand);
2571 spa_prop_find(spa, ZPOOL_PROP_DEDUPDITTO,
2572 &spa->spa_dedup_ditto);
2574 spa->spa_autoreplace = (autoreplace != 0);
2578 * If the 'autoreplace' property is set, then post a resource notifying
2579 * the ZFS DE that it should not issue any faults for unopenable
2580 * devices. We also iterate over the vdevs, and post a sysevent for any
2581 * unopenable vdevs so that the normal autoreplace handler can take
2582 * over.
2584 if (spa->spa_autoreplace && state != SPA_LOAD_TRYIMPORT) {
2585 spa_check_removed(spa->spa_root_vdev);
2587 * For the import case, this is done in spa_import(), because
2588 * at this point we're using the spare definitions from
2589 * the MOS config, not necessarily from the userland config.
2591 if (state != SPA_LOAD_IMPORT) {
2592 spa_aux_check_removed(&spa->spa_spares);
2593 spa_aux_check_removed(&spa->spa_l2cache);
2598 * Load the vdev state for all toplevel vdevs.
2600 vdev_load(rvd);
2603 * Propagate the leaf DTLs we just loaded all the way up the tree.
2605 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2606 vdev_dtl_reassess(rvd, 0, 0, B_FALSE);
2607 spa_config_exit(spa, SCL_ALL, FTAG);
2610 * Load the DDTs (dedup tables).
2612 error = ddt_load(spa);
2613 if (error != 0)
2614 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2616 spa_update_dspace(spa);
2619 * Validate the config, using the MOS config to fill in any
2620 * information which might be missing. If we fail to validate
2621 * the config then declare the pool unfit for use. If we're
2622 * assembling a pool from a split, the log is not transferred
2623 * over.
2625 if (type != SPA_IMPORT_ASSEMBLE) {
2626 nvlist_t *nvconfig;
2628 if (load_nvlist(spa, spa->spa_config_object, &nvconfig) != 0)
2629 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2631 if (!spa_config_valid(spa, nvconfig)) {
2632 nvlist_free(nvconfig);
2633 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM,
2634 ENXIO));
2636 nvlist_free(nvconfig);
2639 * Now that we've validated the config, check the state of the
2640 * root vdev. If it can't be opened, it indicates one or
2641 * more toplevel vdevs are faulted.
2643 if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN)
2644 return (SET_ERROR(ENXIO));
2646 if (spa_check_logs(spa)) {
2647 *ereport = FM_EREPORT_ZFS_LOG_REPLAY;
2648 return (spa_vdev_err(rvd, VDEV_AUX_BAD_LOG, ENXIO));
2652 if (missing_feat_write) {
2653 ASSERT(state == SPA_LOAD_TRYIMPORT);
2656 * At this point, we know that we can open the pool in
2657 * read-only mode but not read-write mode. We now have enough
2658 * information and can return to userland.
2660 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT, ENOTSUP));
2664 * We've successfully opened the pool, verify that we're ready
2665 * to start pushing transactions.
2667 if (state != SPA_LOAD_TRYIMPORT) {
2668 if (error = spa_load_verify(spa))
2669 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2670 error));
2673 if (spa_writeable(spa) && (state == SPA_LOAD_RECOVER ||
2674 spa->spa_load_max_txg == UINT64_MAX)) {
2675 dmu_tx_t *tx;
2676 int need_update = B_FALSE;
2678 ASSERT(state != SPA_LOAD_TRYIMPORT);
2681 * Claim log blocks that haven't been committed yet.
2682 * This must all happen in a single txg.
2683 * Note: spa_claim_max_txg is updated by spa_claim_notify(),
2684 * invoked from zil_claim_log_block()'s i/o done callback.
2685 * Price of rollback is that we abandon the log.
2687 spa->spa_claiming = B_TRUE;
2689 tx = dmu_tx_create_assigned(spa_get_dsl(spa),
2690 spa_first_txg(spa));
2691 (void) dmu_objset_find(spa_name(spa),
2692 zil_claim, tx, DS_FIND_CHILDREN);
2693 dmu_tx_commit(tx);
2695 spa->spa_claiming = B_FALSE;
2697 spa_set_log_state(spa, SPA_LOG_GOOD);
2698 spa->spa_sync_on = B_TRUE;
2699 txg_sync_start(spa->spa_dsl_pool);
2702 * Wait for all claims to sync. We sync up to the highest
2703 * claimed log block birth time so that claimed log blocks
2704 * don't appear to be from the future. spa_claim_max_txg
2705 * will have been set for us by either zil_check_log_chain()
2706 * (invoked from spa_check_logs()) or zil_claim() above.
2708 txg_wait_synced(spa->spa_dsl_pool, spa->spa_claim_max_txg);
2711 * If the config cache is stale, or we have uninitialized
2712 * metaslabs (see spa_vdev_add()), then update the config.
2714 * If this is a verbatim import, trust the current
2715 * in-core spa_config and update the disk labels.
2717 if (config_cache_txg != spa->spa_config_txg ||
2718 state == SPA_LOAD_IMPORT ||
2719 state == SPA_LOAD_RECOVER ||
2720 (spa->spa_import_flags & ZFS_IMPORT_VERBATIM))
2721 need_update = B_TRUE;
2723 for (int c = 0; c < rvd->vdev_children; c++)
2724 if (rvd->vdev_child[c]->vdev_ms_array == 0)
2725 need_update = B_TRUE;
2728 * Update the config cache asychronously in case we're the
2729 * root pool, in which case the config cache isn't writable yet.
2731 if (need_update)
2732 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
2735 * Check all DTLs to see if anything needs resilvering.
2737 if (!dsl_scan_resilvering(spa->spa_dsl_pool) &&
2738 vdev_resilver_needed(rvd, NULL, NULL))
2739 spa_async_request(spa, SPA_ASYNC_RESILVER);
2742 * Log the fact that we booted up (so that we can detect if
2743 * we rebooted in the middle of an operation).
2745 spa_history_log_version(spa, "open");
2748 * Delete any inconsistent datasets.
2750 (void) dmu_objset_find(spa_name(spa),
2751 dsl_destroy_inconsistent, NULL, DS_FIND_CHILDREN);
2754 * Clean up any stale temporary dataset userrefs.
2756 dsl_pool_clean_tmp_userrefs(spa->spa_dsl_pool);
2759 return (0);
2762 static int
2763 spa_load_retry(spa_t *spa, spa_load_state_t state, int mosconfig)
2765 int mode = spa->spa_mode;
2767 spa_unload(spa);
2768 spa_deactivate(spa);
2770 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg - 1;
2772 spa_activate(spa, mode);
2773 spa_async_suspend(spa);
2775 return (spa_load(spa, state, SPA_IMPORT_EXISTING, mosconfig));
2779 * If spa_load() fails this function will try loading prior txg's. If
2780 * 'state' is SPA_LOAD_RECOVER and one of these loads succeeds the pool
2781 * will be rewound to that txg. If 'state' is not SPA_LOAD_RECOVER this
2782 * function will not rewind the pool and will return the same error as
2783 * spa_load().
2785 static int
2786 spa_load_best(spa_t *spa, spa_load_state_t state, int mosconfig,
2787 uint64_t max_request, int rewind_flags)
2789 nvlist_t *loadinfo = NULL;
2790 nvlist_t *config = NULL;
2791 int load_error, rewind_error;
2792 uint64_t safe_rewind_txg;
2793 uint64_t min_txg;
2795 if (spa->spa_load_txg && state == SPA_LOAD_RECOVER) {
2796 spa->spa_load_max_txg = spa->spa_load_txg;
2797 spa_set_log_state(spa, SPA_LOG_CLEAR);
2798 } else {
2799 spa->spa_load_max_txg = max_request;
2800 if (max_request != UINT64_MAX)
2801 spa->spa_extreme_rewind = B_TRUE;
2804 load_error = rewind_error = spa_load(spa, state, SPA_IMPORT_EXISTING,
2805 mosconfig);
2806 if (load_error == 0)
2807 return (0);
2809 if (spa->spa_root_vdev != NULL)
2810 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
2812 spa->spa_last_ubsync_txg = spa->spa_uberblock.ub_txg;
2813 spa->spa_last_ubsync_txg_ts = spa->spa_uberblock.ub_timestamp;
2815 if (rewind_flags & ZPOOL_NEVER_REWIND) {
2816 nvlist_free(config);
2817 return (load_error);
2820 if (state == SPA_LOAD_RECOVER) {
2821 /* Price of rolling back is discarding txgs, including log */
2822 spa_set_log_state(spa, SPA_LOG_CLEAR);
2823 } else {
2825 * If we aren't rolling back save the load info from our first
2826 * import attempt so that we can restore it after attempting
2827 * to rewind.
2829 loadinfo = spa->spa_load_info;
2830 spa->spa_load_info = fnvlist_alloc();
2833 spa->spa_load_max_txg = spa->spa_last_ubsync_txg;
2834 safe_rewind_txg = spa->spa_last_ubsync_txg - TXG_DEFER_SIZE;
2835 min_txg = (rewind_flags & ZPOOL_EXTREME_REWIND) ?
2836 TXG_INITIAL : safe_rewind_txg;
2839 * Continue as long as we're finding errors, we're still within
2840 * the acceptable rewind range, and we're still finding uberblocks
2842 while (rewind_error && spa->spa_uberblock.ub_txg >= min_txg &&
2843 spa->spa_uberblock.ub_txg <= spa->spa_load_max_txg) {
2844 if (spa->spa_load_max_txg < safe_rewind_txg)
2845 spa->spa_extreme_rewind = B_TRUE;
2846 rewind_error = spa_load_retry(spa, state, mosconfig);
2849 spa->spa_extreme_rewind = B_FALSE;
2850 spa->spa_load_max_txg = UINT64_MAX;
2852 if (config && (rewind_error || state != SPA_LOAD_RECOVER))
2853 spa_config_set(spa, config);
2855 if (state == SPA_LOAD_RECOVER) {
2856 ASSERT3P(loadinfo, ==, NULL);
2857 return (rewind_error);
2858 } else {
2859 /* Store the rewind info as part of the initial load info */
2860 fnvlist_add_nvlist(loadinfo, ZPOOL_CONFIG_REWIND_INFO,
2861 spa->spa_load_info);
2863 /* Restore the initial load info */
2864 fnvlist_free(spa->spa_load_info);
2865 spa->spa_load_info = loadinfo;
2867 return (load_error);
2872 * Pool Open/Import
2874 * The import case is identical to an open except that the configuration is sent
2875 * down from userland, instead of grabbed from the configuration cache. For the
2876 * case of an open, the pool configuration will exist in the
2877 * POOL_STATE_UNINITIALIZED state.
2879 * The stats information (gen/count/ustats) is used to gather vdev statistics at
2880 * the same time open the pool, without having to keep around the spa_t in some
2881 * ambiguous state.
2883 static int
2884 spa_open_common(const char *pool, spa_t **spapp, void *tag, nvlist_t *nvpolicy,
2885 nvlist_t **config)
2887 spa_t *spa;
2888 spa_load_state_t state = SPA_LOAD_OPEN;
2889 int error;
2890 int locked = B_FALSE;
2892 *spapp = NULL;
2895 * As disgusting as this is, we need to support recursive calls to this
2896 * function because dsl_dir_open() is called during spa_load(), and ends
2897 * up calling spa_open() again. The real fix is to figure out how to
2898 * avoid dsl_dir_open() calling this in the first place.
2900 if (mutex_owner(&spa_namespace_lock) != curthread) {
2901 mutex_enter(&spa_namespace_lock);
2902 locked = B_TRUE;
2905 if ((spa = spa_lookup(pool)) == NULL) {
2906 if (locked)
2907 mutex_exit(&spa_namespace_lock);
2908 return (SET_ERROR(ENOENT));
2911 if (spa->spa_state == POOL_STATE_UNINITIALIZED) {
2912 zpool_rewind_policy_t policy;
2914 zpool_get_rewind_policy(nvpolicy ? nvpolicy : spa->spa_config,
2915 &policy);
2916 if (policy.zrp_request & ZPOOL_DO_REWIND)
2917 state = SPA_LOAD_RECOVER;
2919 spa_activate(spa, spa_mode_global);
2921 if (state != SPA_LOAD_RECOVER)
2922 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
2924 error = spa_load_best(spa, state, B_FALSE, policy.zrp_txg,
2925 policy.zrp_request);
2927 if (error == EBADF) {
2929 * If vdev_validate() returns failure (indicated by
2930 * EBADF), it indicates that one of the vdevs indicates
2931 * that the pool has been exported or destroyed. If
2932 * this is the case, the config cache is out of sync and
2933 * we should remove the pool from the namespace.
2935 spa_unload(spa);
2936 spa_deactivate(spa);
2937 spa_config_sync(spa, B_TRUE, B_TRUE);
2938 spa_remove(spa);
2939 if (locked)
2940 mutex_exit(&spa_namespace_lock);
2941 return (SET_ERROR(ENOENT));
2944 if (error) {
2946 * We can't open the pool, but we still have useful
2947 * information: the state of each vdev after the
2948 * attempted vdev_open(). Return this to the user.
2950 if (config != NULL && spa->spa_config) {
2951 VERIFY(nvlist_dup(spa->spa_config, config,
2952 KM_SLEEP) == 0);
2953 VERIFY(nvlist_add_nvlist(*config,
2954 ZPOOL_CONFIG_LOAD_INFO,
2955 spa->spa_load_info) == 0);
2957 spa_unload(spa);
2958 spa_deactivate(spa);
2959 spa->spa_last_open_failed = error;
2960 if (locked)
2961 mutex_exit(&spa_namespace_lock);
2962 *spapp = NULL;
2963 return (error);
2967 spa_open_ref(spa, tag);
2969 if (config != NULL)
2970 *config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
2973 * If we've recovered the pool, pass back any information we
2974 * gathered while doing the load.
2976 if (state == SPA_LOAD_RECOVER) {
2977 VERIFY(nvlist_add_nvlist(*config, ZPOOL_CONFIG_LOAD_INFO,
2978 spa->spa_load_info) == 0);
2981 if (locked) {
2982 spa->spa_last_open_failed = 0;
2983 spa->spa_last_ubsync_txg = 0;
2984 spa->spa_load_txg = 0;
2985 mutex_exit(&spa_namespace_lock);
2988 *spapp = spa;
2990 return (0);
2994 spa_open_rewind(const char *name, spa_t **spapp, void *tag, nvlist_t *policy,
2995 nvlist_t **config)
2997 return (spa_open_common(name, spapp, tag, policy, config));
3001 spa_open(const char *name, spa_t **spapp, void *tag)
3003 return (spa_open_common(name, spapp, tag, NULL, NULL));
3007 * Lookup the given spa_t, incrementing the inject count in the process,
3008 * preventing it from being exported or destroyed.
3010 spa_t *
3011 spa_inject_addref(char *name)
3013 spa_t *spa;
3015 mutex_enter(&spa_namespace_lock);
3016 if ((spa = spa_lookup(name)) == NULL) {
3017 mutex_exit(&spa_namespace_lock);
3018 return (NULL);
3020 spa->spa_inject_ref++;
3021 mutex_exit(&spa_namespace_lock);
3023 return (spa);
3026 void
3027 spa_inject_delref(spa_t *spa)
3029 mutex_enter(&spa_namespace_lock);
3030 spa->spa_inject_ref--;
3031 mutex_exit(&spa_namespace_lock);
3035 * Add spares device information to the nvlist.
3037 static void
3038 spa_add_spares(spa_t *spa, nvlist_t *config)
3040 nvlist_t **spares;
3041 uint_t i, nspares;
3042 nvlist_t *nvroot;
3043 uint64_t guid;
3044 vdev_stat_t *vs;
3045 uint_t vsc;
3046 uint64_t pool;
3048 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
3050 if (spa->spa_spares.sav_count == 0)
3051 return;
3053 VERIFY(nvlist_lookup_nvlist(config,
3054 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
3055 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
3056 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
3057 if (nspares != 0) {
3058 VERIFY(nvlist_add_nvlist_array(nvroot,
3059 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
3060 VERIFY(nvlist_lookup_nvlist_array(nvroot,
3061 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
3064 * Go through and find any spares which have since been
3065 * repurposed as an active spare. If this is the case, update
3066 * their status appropriately.
3068 for (i = 0; i < nspares; i++) {
3069 VERIFY(nvlist_lookup_uint64(spares[i],
3070 ZPOOL_CONFIG_GUID, &guid) == 0);
3071 if (spa_spare_exists(guid, &pool, NULL) &&
3072 pool != 0ULL) {
3073 VERIFY(nvlist_lookup_uint64_array(
3074 spares[i], ZPOOL_CONFIG_VDEV_STATS,
3075 (uint64_t **)&vs, &vsc) == 0);
3076 vs->vs_state = VDEV_STATE_CANT_OPEN;
3077 vs->vs_aux = VDEV_AUX_SPARED;
3084 * Add l2cache device information to the nvlist, including vdev stats.
3086 static void
3087 spa_add_l2cache(spa_t *spa, nvlist_t *config)
3089 nvlist_t **l2cache;
3090 uint_t i, j, nl2cache;
3091 nvlist_t *nvroot;
3092 uint64_t guid;
3093 vdev_t *vd;
3094 vdev_stat_t *vs;
3095 uint_t vsc;
3097 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
3099 if (spa->spa_l2cache.sav_count == 0)
3100 return;
3102 VERIFY(nvlist_lookup_nvlist(config,
3103 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
3104 VERIFY(nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
3105 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
3106 if (nl2cache != 0) {
3107 VERIFY(nvlist_add_nvlist_array(nvroot,
3108 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
3109 VERIFY(nvlist_lookup_nvlist_array(nvroot,
3110 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
3113 * Update level 2 cache device stats.
3116 for (i = 0; i < nl2cache; i++) {
3117 VERIFY(nvlist_lookup_uint64(l2cache[i],
3118 ZPOOL_CONFIG_GUID, &guid) == 0);
3120 vd = NULL;
3121 for (j = 0; j < spa->spa_l2cache.sav_count; j++) {
3122 if (guid ==
3123 spa->spa_l2cache.sav_vdevs[j]->vdev_guid) {
3124 vd = spa->spa_l2cache.sav_vdevs[j];
3125 break;
3128 ASSERT(vd != NULL);
3130 VERIFY(nvlist_lookup_uint64_array(l2cache[i],
3131 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc)
3132 == 0);
3133 vdev_get_stats(vd, vs);
3138 static void
3139 spa_add_feature_stats(spa_t *spa, nvlist_t *config)
3141 nvlist_t *features;
3142 zap_cursor_t zc;
3143 zap_attribute_t za;
3145 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
3146 VERIFY(nvlist_alloc(&features, NV_UNIQUE_NAME, KM_SLEEP) == 0);
3148 if (spa->spa_feat_for_read_obj != 0) {
3149 for (zap_cursor_init(&zc, spa->spa_meta_objset,
3150 spa->spa_feat_for_read_obj);
3151 zap_cursor_retrieve(&zc, &za) == 0;
3152 zap_cursor_advance(&zc)) {
3153 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
3154 za.za_num_integers == 1);
3155 VERIFY3U(0, ==, nvlist_add_uint64(features, za.za_name,
3156 za.za_first_integer));
3158 zap_cursor_fini(&zc);
3161 if (spa->spa_feat_for_write_obj != 0) {
3162 for (zap_cursor_init(&zc, spa->spa_meta_objset,
3163 spa->spa_feat_for_write_obj);
3164 zap_cursor_retrieve(&zc, &za) == 0;
3165 zap_cursor_advance(&zc)) {
3166 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
3167 za.za_num_integers == 1);
3168 VERIFY3U(0, ==, nvlist_add_uint64(features, za.za_name,
3169 za.za_first_integer));
3171 zap_cursor_fini(&zc);
3174 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_FEATURE_STATS,
3175 features) == 0);
3176 nvlist_free(features);
3180 spa_get_stats(const char *name, nvlist_t **config,
3181 char *altroot, size_t buflen)
3183 int error;
3184 spa_t *spa;
3186 *config = NULL;
3187 error = spa_open_common(name, &spa, FTAG, NULL, config);
3189 if (spa != NULL) {
3191 * This still leaves a window of inconsistency where the spares
3192 * or l2cache devices could change and the config would be
3193 * self-inconsistent.
3195 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3197 if (*config != NULL) {
3198 uint64_t loadtimes[2];
3200 loadtimes[0] = spa->spa_loaded_ts.tv_sec;
3201 loadtimes[1] = spa->spa_loaded_ts.tv_nsec;
3202 VERIFY(nvlist_add_uint64_array(*config,
3203 ZPOOL_CONFIG_LOADED_TIME, loadtimes, 2) == 0);
3205 VERIFY(nvlist_add_uint64(*config,
3206 ZPOOL_CONFIG_ERRCOUNT,
3207 spa_get_errlog_size(spa)) == 0);
3209 if (spa_suspended(spa))
3210 VERIFY(nvlist_add_uint64(*config,
3211 ZPOOL_CONFIG_SUSPENDED,
3212 spa->spa_failmode) == 0);
3214 spa_add_spares(spa, *config);
3215 spa_add_l2cache(spa, *config);
3216 spa_add_feature_stats(spa, *config);
3221 * We want to get the alternate root even for faulted pools, so we cheat
3222 * and call spa_lookup() directly.
3224 if (altroot) {
3225 if (spa == NULL) {
3226 mutex_enter(&spa_namespace_lock);
3227 spa = spa_lookup(name);
3228 if (spa)
3229 spa_altroot(spa, altroot, buflen);
3230 else
3231 altroot[0] = '\0';
3232 spa = NULL;
3233 mutex_exit(&spa_namespace_lock);
3234 } else {
3235 spa_altroot(spa, altroot, buflen);
3239 if (spa != NULL) {
3240 spa_config_exit(spa, SCL_CONFIG, FTAG);
3241 spa_close(spa, FTAG);
3244 return (error);
3248 * Validate that the auxiliary device array is well formed. We must have an
3249 * array of nvlists, each which describes a valid leaf vdev. If this is an
3250 * import (mode is VDEV_ALLOC_SPARE), then we allow corrupted spares to be
3251 * specified, as long as they are well-formed.
3253 static int
3254 spa_validate_aux_devs(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode,
3255 spa_aux_vdev_t *sav, const char *config, uint64_t version,
3256 vdev_labeltype_t label)
3258 nvlist_t **dev;
3259 uint_t i, ndev;
3260 vdev_t *vd;
3261 int error;
3263 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
3266 * It's acceptable to have no devs specified.
3268 if (nvlist_lookup_nvlist_array(nvroot, config, &dev, &ndev) != 0)
3269 return (0);
3271 if (ndev == 0)
3272 return (SET_ERROR(EINVAL));
3275 * Make sure the pool is formatted with a version that supports this
3276 * device type.
3278 if (spa_version(spa) < version)
3279 return (SET_ERROR(ENOTSUP));
3282 * Set the pending device list so we correctly handle device in-use
3283 * checking.
3285 sav->sav_pending = dev;
3286 sav->sav_npending = ndev;
3288 for (i = 0; i < ndev; i++) {
3289 if ((error = spa_config_parse(spa, &vd, dev[i], NULL, 0,
3290 mode)) != 0)
3291 goto out;
3293 if (!vd->vdev_ops->vdev_op_leaf) {
3294 vdev_free(vd);
3295 error = SET_ERROR(EINVAL);
3296 goto out;
3300 * The L2ARC currently only supports disk devices in
3301 * kernel context. For user-level testing, we allow it.
3303 #ifdef _KERNEL
3304 if ((strcmp(config, ZPOOL_CONFIG_L2CACHE) == 0) &&
3305 strcmp(vd->vdev_ops->vdev_op_type, VDEV_TYPE_DISK) != 0) {
3306 error = SET_ERROR(ENOTBLK);
3307 vdev_free(vd);
3308 goto out;
3310 #endif
3311 vd->vdev_top = vd;
3313 if ((error = vdev_open(vd)) == 0 &&
3314 (error = vdev_label_init(vd, crtxg, label)) == 0) {
3315 VERIFY(nvlist_add_uint64(dev[i], ZPOOL_CONFIG_GUID,
3316 vd->vdev_guid) == 0);
3319 vdev_free(vd);
3321 if (error &&
3322 (mode != VDEV_ALLOC_SPARE && mode != VDEV_ALLOC_L2CACHE))
3323 goto out;
3324 else
3325 error = 0;
3328 out:
3329 sav->sav_pending = NULL;
3330 sav->sav_npending = 0;
3331 return (error);
3334 static int
3335 spa_validate_aux(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode)
3337 int error;
3339 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
3341 if ((error = spa_validate_aux_devs(spa, nvroot, crtxg, mode,
3342 &spa->spa_spares, ZPOOL_CONFIG_SPARES, SPA_VERSION_SPARES,
3343 VDEV_LABEL_SPARE)) != 0) {
3344 return (error);
3347 return (spa_validate_aux_devs(spa, nvroot, crtxg, mode,
3348 &spa->spa_l2cache, ZPOOL_CONFIG_L2CACHE, SPA_VERSION_L2CACHE,
3349 VDEV_LABEL_L2CACHE));
3352 static void
3353 spa_set_aux_vdevs(spa_aux_vdev_t *sav, nvlist_t **devs, int ndevs,
3354 const char *config)
3356 int i;
3358 if (sav->sav_config != NULL) {
3359 nvlist_t **olddevs;
3360 uint_t oldndevs;
3361 nvlist_t **newdevs;
3364 * Generate new dev list by concatentating with the
3365 * current dev list.
3367 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config, config,
3368 &olddevs, &oldndevs) == 0);
3370 newdevs = kmem_alloc(sizeof (void *) *
3371 (ndevs + oldndevs), KM_SLEEP);
3372 for (i = 0; i < oldndevs; i++)
3373 VERIFY(nvlist_dup(olddevs[i], &newdevs[i],
3374 KM_SLEEP) == 0);
3375 for (i = 0; i < ndevs; i++)
3376 VERIFY(nvlist_dup(devs[i], &newdevs[i + oldndevs],
3377 KM_SLEEP) == 0);
3379 VERIFY(nvlist_remove(sav->sav_config, config,
3380 DATA_TYPE_NVLIST_ARRAY) == 0);
3382 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
3383 config, newdevs, ndevs + oldndevs) == 0);
3384 for (i = 0; i < oldndevs + ndevs; i++)
3385 nvlist_free(newdevs[i]);
3386 kmem_free(newdevs, (oldndevs + ndevs) * sizeof (void *));
3387 } else {
3389 * Generate a new dev list.
3391 VERIFY(nvlist_alloc(&sav->sav_config, NV_UNIQUE_NAME,
3392 KM_SLEEP) == 0);
3393 VERIFY(nvlist_add_nvlist_array(sav->sav_config, config,
3394 devs, ndevs) == 0);
3399 * Stop and drop level 2 ARC devices
3401 void
3402 spa_l2cache_drop(spa_t *spa)
3404 vdev_t *vd;
3405 int i;
3406 spa_aux_vdev_t *sav = &spa->spa_l2cache;
3408 for (i = 0; i < sav->sav_count; i++) {
3409 uint64_t pool;
3411 vd = sav->sav_vdevs[i];
3412 ASSERT(vd != NULL);
3414 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
3415 pool != 0ULL && l2arc_vdev_present(vd))
3416 l2arc_remove_vdev(vd);
3421 * Pool Creation
3424 spa_create(const char *pool, nvlist_t *nvroot, nvlist_t *props,
3425 nvlist_t *zplprops)
3427 spa_t *spa;
3428 char *altroot = NULL;
3429 vdev_t *rvd;
3430 dsl_pool_t *dp;
3431 dmu_tx_t *tx;
3432 int error = 0;
3433 uint64_t txg = TXG_INITIAL;
3434 nvlist_t **spares, **l2cache;
3435 uint_t nspares, nl2cache;
3436 uint64_t version, obj;
3437 boolean_t has_features;
3440 * If this pool already exists, return failure.
3442 mutex_enter(&spa_namespace_lock);
3443 if (spa_lookup(pool) != NULL) {
3444 mutex_exit(&spa_namespace_lock);
3445 return (SET_ERROR(EEXIST));
3449 * Allocate a new spa_t structure.
3451 (void) nvlist_lookup_string(props,
3452 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
3453 spa = spa_add(pool, NULL, altroot);
3454 spa_activate(spa, spa_mode_global);
3456 if (props && (error = spa_prop_validate(spa, props))) {
3457 spa_deactivate(spa);
3458 spa_remove(spa);
3459 mutex_exit(&spa_namespace_lock);
3460 return (error);
3463 has_features = B_FALSE;
3464 for (nvpair_t *elem = nvlist_next_nvpair(props, NULL);
3465 elem != NULL; elem = nvlist_next_nvpair(props, elem)) {
3466 if (zpool_prop_feature(nvpair_name(elem)))
3467 has_features = B_TRUE;
3470 if (has_features || nvlist_lookup_uint64(props,
3471 zpool_prop_to_name(ZPOOL_PROP_VERSION), &version) != 0) {
3472 version = SPA_VERSION;
3474 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
3476 spa->spa_first_txg = txg;
3477 spa->spa_uberblock.ub_txg = txg - 1;
3478 spa->spa_uberblock.ub_version = version;
3479 spa->spa_ubsync = spa->spa_uberblock;
3482 * Create "The Godfather" zio to hold all async IOs
3484 spa->spa_async_zio_root = zio_root(spa, NULL, NULL,
3485 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE | ZIO_FLAG_GODFATHER);
3488 * Create the root vdev.
3490 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3492 error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, VDEV_ALLOC_ADD);
3494 ASSERT(error != 0 || rvd != NULL);
3495 ASSERT(error != 0 || spa->spa_root_vdev == rvd);
3497 if (error == 0 && !zfs_allocatable_devs(nvroot))
3498 error = SET_ERROR(EINVAL);
3500 if (error == 0 &&
3501 (error = vdev_create(rvd, txg, B_FALSE)) == 0 &&
3502 (error = spa_validate_aux(spa, nvroot, txg,
3503 VDEV_ALLOC_ADD)) == 0) {
3504 for (int c = 0; c < rvd->vdev_children; c++) {
3505 vdev_metaslab_set_size(rvd->vdev_child[c]);
3506 vdev_expand(rvd->vdev_child[c], txg);
3510 spa_config_exit(spa, SCL_ALL, FTAG);
3512 if (error != 0) {
3513 spa_unload(spa);
3514 spa_deactivate(spa);
3515 spa_remove(spa);
3516 mutex_exit(&spa_namespace_lock);
3517 return (error);
3521 * Get the list of spares, if specified.
3523 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
3524 &spares, &nspares) == 0) {
3525 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config, NV_UNIQUE_NAME,
3526 KM_SLEEP) == 0);
3527 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
3528 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
3529 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3530 spa_load_spares(spa);
3531 spa_config_exit(spa, SCL_ALL, FTAG);
3532 spa->spa_spares.sav_sync = B_TRUE;
3536 * Get the list of level 2 cache devices, if specified.
3538 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
3539 &l2cache, &nl2cache) == 0) {
3540 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
3541 NV_UNIQUE_NAME, KM_SLEEP) == 0);
3542 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
3543 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
3544 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3545 spa_load_l2cache(spa);
3546 spa_config_exit(spa, SCL_ALL, FTAG);
3547 spa->spa_l2cache.sav_sync = B_TRUE;
3550 spa->spa_is_initializing = B_TRUE;
3551 spa->spa_dsl_pool = dp = dsl_pool_create(spa, zplprops, txg);
3552 spa->spa_meta_objset = dp->dp_meta_objset;
3553 spa->spa_is_initializing = B_FALSE;
3556 * Create DDTs (dedup tables).
3558 ddt_create(spa);
3560 spa_update_dspace(spa);
3562 tx = dmu_tx_create_assigned(dp, txg);
3565 * Create the pool config object.
3567 spa->spa_config_object = dmu_object_alloc(spa->spa_meta_objset,
3568 DMU_OT_PACKED_NVLIST, SPA_CONFIG_BLOCKSIZE,
3569 DMU_OT_PACKED_NVLIST_SIZE, sizeof (uint64_t), tx);
3571 if (zap_add(spa->spa_meta_objset,
3572 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CONFIG,
3573 sizeof (uint64_t), 1, &spa->spa_config_object, tx) != 0) {
3574 cmn_err(CE_PANIC, "failed to add pool config");
3577 if (spa_version(spa) >= SPA_VERSION_FEATURES)
3578 spa_feature_create_zap_objects(spa, tx);
3580 if (zap_add(spa->spa_meta_objset,
3581 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CREATION_VERSION,
3582 sizeof (uint64_t), 1, &version, tx) != 0) {
3583 cmn_err(CE_PANIC, "failed to add pool version");
3586 /* Newly created pools with the right version are always deflated. */
3587 if (version >= SPA_VERSION_RAIDZ_DEFLATE) {
3588 spa->spa_deflate = TRUE;
3589 if (zap_add(spa->spa_meta_objset,
3590 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
3591 sizeof (uint64_t), 1, &spa->spa_deflate, tx) != 0) {
3592 cmn_err(CE_PANIC, "failed to add deflate");
3597 * Create the deferred-free bpobj. Turn off compression
3598 * because sync-to-convergence takes longer if the blocksize
3599 * keeps changing.
3601 obj = bpobj_alloc(spa->spa_meta_objset, 1 << 14, tx);
3602 dmu_object_set_compress(spa->spa_meta_objset, obj,
3603 ZIO_COMPRESS_OFF, tx);
3604 if (zap_add(spa->spa_meta_objset,
3605 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SYNC_BPOBJ,
3606 sizeof (uint64_t), 1, &obj, tx) != 0) {
3607 cmn_err(CE_PANIC, "failed to add bpobj");
3609 VERIFY3U(0, ==, bpobj_open(&spa->spa_deferred_bpobj,
3610 spa->spa_meta_objset, obj));
3613 * Create the pool's history object.
3615 if (version >= SPA_VERSION_ZPOOL_HISTORY)
3616 spa_history_create_obj(spa, tx);
3619 * Set pool properties.
3621 spa->spa_bootfs = zpool_prop_default_numeric(ZPOOL_PROP_BOOTFS);
3622 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
3623 spa->spa_failmode = zpool_prop_default_numeric(ZPOOL_PROP_FAILUREMODE);
3624 spa->spa_autoexpand = zpool_prop_default_numeric(ZPOOL_PROP_AUTOEXPAND);
3626 if (props != NULL) {
3627 spa_configfile_set(spa, props, B_FALSE);
3628 spa_sync_props(props, tx);
3631 dmu_tx_commit(tx);
3633 spa->spa_sync_on = B_TRUE;
3634 txg_sync_start(spa->spa_dsl_pool);
3637 * We explicitly wait for the first transaction to complete so that our
3638 * bean counters are appropriately updated.
3640 txg_wait_synced(spa->spa_dsl_pool, txg);
3642 spa_config_sync(spa, B_FALSE, B_TRUE);
3644 spa_history_log_version(spa, "create");
3646 spa->spa_minref = refcount_count(&spa->spa_refcount);
3648 mutex_exit(&spa_namespace_lock);
3650 return (0);
3653 #ifdef _KERNEL
3655 * Get the root pool information from the root disk, then import the root pool
3656 * during the system boot up time.
3658 extern int vdev_disk_read_rootlabel(char *, char *, nvlist_t **);
3660 static nvlist_t *
3661 spa_generate_rootconf(char *devpath, char *devid, uint64_t *guid)
3663 nvlist_t *config;
3664 nvlist_t *nvtop, *nvroot;
3665 uint64_t pgid;
3667 if (vdev_disk_read_rootlabel(devpath, devid, &config) != 0)
3668 return (NULL);
3671 * Add this top-level vdev to the child array.
3673 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3674 &nvtop) == 0);
3675 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
3676 &pgid) == 0);
3677 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID, guid) == 0);
3680 * Put this pool's top-level vdevs into a root vdev.
3682 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
3683 VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
3684 VDEV_TYPE_ROOT) == 0);
3685 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
3686 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
3687 VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
3688 &nvtop, 1) == 0);
3691 * Replace the existing vdev_tree with the new root vdev in
3692 * this pool's configuration (remove the old, add the new).
3694 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
3695 nvlist_free(nvroot);
3696 return (config);
3700 * Walk the vdev tree and see if we can find a device with "better"
3701 * configuration. A configuration is "better" if the label on that
3702 * device has a more recent txg.
3704 static void
3705 spa_alt_rootvdev(vdev_t *vd, vdev_t **avd, uint64_t *txg)
3707 for (int c = 0; c < vd->vdev_children; c++)
3708 spa_alt_rootvdev(vd->vdev_child[c], avd, txg);
3710 if (vd->vdev_ops->vdev_op_leaf) {
3711 nvlist_t *label;
3712 uint64_t label_txg;
3714 if (vdev_disk_read_rootlabel(vd->vdev_physpath, vd->vdev_devid,
3715 &label) != 0)
3716 return;
3718 VERIFY(nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_TXG,
3719 &label_txg) == 0);
3722 * Do we have a better boot device?
3724 if (label_txg > *txg) {
3725 *txg = label_txg;
3726 *avd = vd;
3728 nvlist_free(label);
3733 * Import a root pool.
3735 * For x86. devpath_list will consist of devid and/or physpath name of
3736 * the vdev (e.g. "id1,sd@SSEAGATE..." or "/pci@1f,0/ide@d/disk@0,0:a").
3737 * The GRUB "findroot" command will return the vdev we should boot.
3739 * For Sparc, devpath_list consists the physpath name of the booting device
3740 * no matter the rootpool is a single device pool or a mirrored pool.
3741 * e.g.
3742 * "/pci@1f,0/ide@d/disk@0,0:a"
3745 spa_import_rootpool(char *devpath, char *devid)
3747 spa_t *spa;
3748 vdev_t *rvd, *bvd, *avd = NULL;
3749 nvlist_t *config, *nvtop;
3750 uint64_t guid, txg;
3751 char *pname;
3752 int error;
3755 * Read the label from the boot device and generate a configuration.
3757 config = spa_generate_rootconf(devpath, devid, &guid);
3758 #if defined(_OBP) && defined(_KERNEL)
3759 if (config == NULL) {
3760 if (strstr(devpath, "/iscsi/ssd") != NULL) {
3761 /* iscsi boot */
3762 get_iscsi_bootpath_phy(devpath);
3763 config = spa_generate_rootconf(devpath, devid, &guid);
3766 #endif
3767 if (config == NULL) {
3768 cmn_err(CE_NOTE, "Cannot read the pool label from '%s'",
3769 devpath);
3770 return (SET_ERROR(EIO));
3773 VERIFY(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
3774 &pname) == 0);
3775 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg) == 0);
3777 mutex_enter(&spa_namespace_lock);
3778 if ((spa = spa_lookup(pname)) != NULL) {
3780 * Remove the existing root pool from the namespace so that we
3781 * can replace it with the correct config we just read in.
3783 spa_remove(spa);
3786 spa = spa_add(pname, config, NULL);
3787 spa->spa_is_root = B_TRUE;
3788 spa->spa_import_flags = ZFS_IMPORT_VERBATIM;
3791 * Build up a vdev tree based on the boot device's label config.
3793 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3794 &nvtop) == 0);
3795 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3796 error = spa_config_parse(spa, &rvd, nvtop, NULL, 0,
3797 VDEV_ALLOC_ROOTPOOL);
3798 spa_config_exit(spa, SCL_ALL, FTAG);
3799 if (error) {
3800 mutex_exit(&spa_namespace_lock);
3801 nvlist_free(config);
3802 cmn_err(CE_NOTE, "Can not parse the config for pool '%s'",
3803 pname);
3804 return (error);
3808 * Get the boot vdev.
3810 if ((bvd = vdev_lookup_by_guid(rvd, guid)) == NULL) {
3811 cmn_err(CE_NOTE, "Can not find the boot vdev for guid %llu",
3812 (u_longlong_t)guid);
3813 error = SET_ERROR(ENOENT);
3814 goto out;
3818 * Determine if there is a better boot device.
3820 avd = bvd;
3821 spa_alt_rootvdev(rvd, &avd, &txg);
3822 if (avd != bvd) {
3823 cmn_err(CE_NOTE, "The boot device is 'degraded'. Please "
3824 "try booting from '%s'", avd->vdev_path);
3825 error = SET_ERROR(EINVAL);
3826 goto out;
3830 * If the boot device is part of a spare vdev then ensure that
3831 * we're booting off the active spare.
3833 if (bvd->vdev_parent->vdev_ops == &vdev_spare_ops &&
3834 !bvd->vdev_isspare) {
3835 cmn_err(CE_NOTE, "The boot device is currently spared. Please "
3836 "try booting from '%s'",
3837 bvd->vdev_parent->
3838 vdev_child[bvd->vdev_parent->vdev_children - 1]->vdev_path);
3839 error = SET_ERROR(EINVAL);
3840 goto out;
3843 error = 0;
3844 out:
3845 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3846 vdev_free(rvd);
3847 spa_config_exit(spa, SCL_ALL, FTAG);
3848 mutex_exit(&spa_namespace_lock);
3850 nvlist_free(config);
3851 return (error);
3854 #endif
3857 * Import a non-root pool into the system.
3860 spa_import(const char *pool, nvlist_t *config, nvlist_t *props, uint64_t flags)
3862 spa_t *spa;
3863 char *altroot = NULL;
3864 spa_load_state_t state = SPA_LOAD_IMPORT;
3865 zpool_rewind_policy_t policy;
3866 uint64_t mode = spa_mode_global;
3867 uint64_t readonly = B_FALSE;
3868 int error;
3869 nvlist_t *nvroot;
3870 nvlist_t **spares, **l2cache;
3871 uint_t nspares, nl2cache;
3874 * If a pool with this name exists, return failure.
3876 mutex_enter(&spa_namespace_lock);
3877 if (spa_lookup(pool) != NULL) {
3878 mutex_exit(&spa_namespace_lock);
3879 return (SET_ERROR(EEXIST));
3883 * Create and initialize the spa structure.
3885 (void) nvlist_lookup_string(props,
3886 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
3887 (void) nvlist_lookup_uint64(props,
3888 zpool_prop_to_name(ZPOOL_PROP_READONLY), &readonly);
3889 if (readonly)
3890 mode = FREAD;
3891 spa = spa_add(pool, config, altroot);
3892 spa->spa_import_flags = flags;
3895 * Verbatim import - Take a pool and insert it into the namespace
3896 * as if it had been loaded at boot.
3898 if (spa->spa_import_flags & ZFS_IMPORT_VERBATIM) {
3899 if (props != NULL)
3900 spa_configfile_set(spa, props, B_FALSE);
3902 spa_config_sync(spa, B_FALSE, B_TRUE);
3904 mutex_exit(&spa_namespace_lock);
3905 return (0);
3908 spa_activate(spa, mode);
3911 * Don't start async tasks until we know everything is healthy.
3913 spa_async_suspend(spa);
3915 zpool_get_rewind_policy(config, &policy);
3916 if (policy.zrp_request & ZPOOL_DO_REWIND)
3917 state = SPA_LOAD_RECOVER;
3920 * Pass off the heavy lifting to spa_load(). Pass TRUE for mosconfig
3921 * because the user-supplied config is actually the one to trust when
3922 * doing an import.
3924 if (state != SPA_LOAD_RECOVER)
3925 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
3927 error = spa_load_best(spa, state, B_TRUE, policy.zrp_txg,
3928 policy.zrp_request);
3931 * Propagate anything learned while loading the pool and pass it
3932 * back to caller (i.e. rewind info, missing devices, etc).
3934 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
3935 spa->spa_load_info) == 0);
3937 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3939 * Toss any existing sparelist, as it doesn't have any validity
3940 * anymore, and conflicts with spa_has_spare().
3942 if (spa->spa_spares.sav_config) {
3943 nvlist_free(spa->spa_spares.sav_config);
3944 spa->spa_spares.sav_config = NULL;
3945 spa_load_spares(spa);
3947 if (spa->spa_l2cache.sav_config) {
3948 nvlist_free(spa->spa_l2cache.sav_config);
3949 spa->spa_l2cache.sav_config = NULL;
3950 spa_load_l2cache(spa);
3953 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3954 &nvroot) == 0);
3955 if (error == 0)
3956 error = spa_validate_aux(spa, nvroot, -1ULL,
3957 VDEV_ALLOC_SPARE);
3958 if (error == 0)
3959 error = spa_validate_aux(spa, nvroot, -1ULL,
3960 VDEV_ALLOC_L2CACHE);
3961 spa_config_exit(spa, SCL_ALL, FTAG);
3963 if (props != NULL)
3964 spa_configfile_set(spa, props, B_FALSE);
3966 if (error != 0 || (props && spa_writeable(spa) &&
3967 (error = spa_prop_set(spa, props)))) {
3968 spa_unload(spa);
3969 spa_deactivate(spa);
3970 spa_remove(spa);
3971 mutex_exit(&spa_namespace_lock);
3972 return (error);
3975 spa_async_resume(spa);
3978 * Override any spares and level 2 cache devices as specified by
3979 * the user, as these may have correct device names/devids, etc.
3981 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
3982 &spares, &nspares) == 0) {
3983 if (spa->spa_spares.sav_config)
3984 VERIFY(nvlist_remove(spa->spa_spares.sav_config,
3985 ZPOOL_CONFIG_SPARES, DATA_TYPE_NVLIST_ARRAY) == 0);
3986 else
3987 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config,
3988 NV_UNIQUE_NAME, KM_SLEEP) == 0);
3989 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
3990 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
3991 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3992 spa_load_spares(spa);
3993 spa_config_exit(spa, SCL_ALL, FTAG);
3994 spa->spa_spares.sav_sync = B_TRUE;
3996 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
3997 &l2cache, &nl2cache) == 0) {
3998 if (spa->spa_l2cache.sav_config)
3999 VERIFY(nvlist_remove(spa->spa_l2cache.sav_config,
4000 ZPOOL_CONFIG_L2CACHE, DATA_TYPE_NVLIST_ARRAY) == 0);
4001 else
4002 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
4003 NV_UNIQUE_NAME, KM_SLEEP) == 0);
4004 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
4005 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
4006 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4007 spa_load_l2cache(spa);
4008 spa_config_exit(spa, SCL_ALL, FTAG);
4009 spa->spa_l2cache.sav_sync = B_TRUE;
4013 * Check for any removed devices.
4015 if (spa->spa_autoreplace) {
4016 spa_aux_check_removed(&spa->spa_spares);
4017 spa_aux_check_removed(&spa->spa_l2cache);
4020 if (spa_writeable(spa)) {
4022 * Update the config cache to include the newly-imported pool.
4024 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
4028 * It's possible that the pool was expanded while it was exported.
4029 * We kick off an async task to handle this for us.
4031 spa_async_request(spa, SPA_ASYNC_AUTOEXPAND);
4033 mutex_exit(&spa_namespace_lock);
4034 spa_history_log_version(spa, "import");
4036 return (0);
4039 nvlist_t *
4040 spa_tryimport(nvlist_t *tryconfig)
4042 nvlist_t *config = NULL;
4043 char *poolname;
4044 spa_t *spa;
4045 uint64_t state;
4046 int error;
4048 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_POOL_NAME, &poolname))
4049 return (NULL);
4051 if (nvlist_lookup_uint64(tryconfig, ZPOOL_CONFIG_POOL_STATE, &state))
4052 return (NULL);
4055 * Create and initialize the spa structure.
4057 mutex_enter(&spa_namespace_lock);
4058 spa = spa_add(TRYIMPORT_NAME, tryconfig, NULL);
4059 spa_activate(spa, FREAD);
4062 * Pass off the heavy lifting to spa_load().
4063 * Pass TRUE for mosconfig because the user-supplied config
4064 * is actually the one to trust when doing an import.
4066 error = spa_load(spa, SPA_LOAD_TRYIMPORT, SPA_IMPORT_EXISTING, B_TRUE);
4069 * If 'tryconfig' was at least parsable, return the current config.
4071 if (spa->spa_root_vdev != NULL) {
4072 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4073 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME,
4074 poolname) == 0);
4075 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
4076 state) == 0);
4077 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
4078 spa->spa_uberblock.ub_timestamp) == 0);
4079 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
4080 spa->spa_load_info) == 0);
4083 * If the bootfs property exists on this pool then we
4084 * copy it out so that external consumers can tell which
4085 * pools are bootable.
4087 if ((!error || error == EEXIST) && spa->spa_bootfs) {
4088 char *tmpname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
4091 * We have to play games with the name since the
4092 * pool was opened as TRYIMPORT_NAME.
4094 if (dsl_dsobj_to_dsname(spa_name(spa),
4095 spa->spa_bootfs, tmpname) == 0) {
4096 char *cp;
4097 char *dsname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
4099 cp = strchr(tmpname, '/');
4100 if (cp == NULL) {
4101 (void) strlcpy(dsname, tmpname,
4102 MAXPATHLEN);
4103 } else {
4104 (void) snprintf(dsname, MAXPATHLEN,
4105 "%s/%s", poolname, ++cp);
4107 VERIFY(nvlist_add_string(config,
4108 ZPOOL_CONFIG_BOOTFS, dsname) == 0);
4109 kmem_free(dsname, MAXPATHLEN);
4111 kmem_free(tmpname, MAXPATHLEN);
4115 * Add the list of hot spares and level 2 cache devices.
4117 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4118 spa_add_spares(spa, config);
4119 spa_add_l2cache(spa, config);
4120 spa_config_exit(spa, SCL_CONFIG, FTAG);
4123 spa_unload(spa);
4124 spa_deactivate(spa);
4125 spa_remove(spa);
4126 mutex_exit(&spa_namespace_lock);
4128 return (config);
4132 * Pool export/destroy
4134 * The act of destroying or exporting a pool is very simple. We make sure there
4135 * is no more pending I/O and any references to the pool are gone. Then, we
4136 * update the pool state and sync all the labels to disk, removing the
4137 * configuration from the cache afterwards. If the 'hardforce' flag is set, then
4138 * we don't sync the labels or remove the configuration cache.
4140 static int
4141 spa_export_common(char *pool, int new_state, nvlist_t **oldconfig,
4142 boolean_t force, boolean_t hardforce)
4144 spa_t *spa;
4146 if (oldconfig)
4147 *oldconfig = NULL;
4149 if (!(spa_mode_global & FWRITE))
4150 return (SET_ERROR(EROFS));
4152 mutex_enter(&spa_namespace_lock);
4153 if ((spa = spa_lookup(pool)) == NULL) {
4154 mutex_exit(&spa_namespace_lock);
4155 return (SET_ERROR(ENOENT));
4159 * Put a hold on the pool, drop the namespace lock, stop async tasks,
4160 * reacquire the namespace lock, and see if we can export.
4162 spa_open_ref(spa, FTAG);
4163 mutex_exit(&spa_namespace_lock);
4164 spa_async_suspend(spa);
4165 mutex_enter(&spa_namespace_lock);
4166 spa_close(spa, FTAG);
4169 * The pool will be in core if it's openable,
4170 * in which case we can modify its state.
4172 if (spa->spa_state != POOL_STATE_UNINITIALIZED && spa->spa_sync_on) {
4174 * Objsets may be open only because they're dirty, so we
4175 * have to force it to sync before checking spa_refcnt.
4177 txg_wait_synced(spa->spa_dsl_pool, 0);
4180 * A pool cannot be exported or destroyed if there are active
4181 * references. If we are resetting a pool, allow references by
4182 * fault injection handlers.
4184 if (!spa_refcount_zero(spa) ||
4185 (spa->spa_inject_ref != 0 &&
4186 new_state != POOL_STATE_UNINITIALIZED)) {
4187 spa_async_resume(spa);
4188 mutex_exit(&spa_namespace_lock);
4189 return (SET_ERROR(EBUSY));
4193 * A pool cannot be exported if it has an active shared spare.
4194 * This is to prevent other pools stealing the active spare
4195 * from an exported pool. At user's own will, such pool can
4196 * be forcedly exported.
4198 if (!force && new_state == POOL_STATE_EXPORTED &&
4199 spa_has_active_shared_spare(spa)) {
4200 spa_async_resume(spa);
4201 mutex_exit(&spa_namespace_lock);
4202 return (SET_ERROR(EXDEV));
4206 * We want this to be reflected on every label,
4207 * so mark them all dirty. spa_unload() will do the
4208 * final sync that pushes these changes out.
4210 if (new_state != POOL_STATE_UNINITIALIZED && !hardforce) {
4211 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4212 spa->spa_state = new_state;
4213 spa->spa_final_txg = spa_last_synced_txg(spa) +
4214 TXG_DEFER_SIZE + 1;
4215 vdev_config_dirty(spa->spa_root_vdev);
4216 spa_config_exit(spa, SCL_ALL, FTAG);
4220 spa_event_notify(spa, NULL, ESC_ZFS_POOL_DESTROY);
4222 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
4223 spa_unload(spa);
4224 spa_deactivate(spa);
4227 if (oldconfig && spa->spa_config)
4228 VERIFY(nvlist_dup(spa->spa_config, oldconfig, 0) == 0);
4230 if (new_state != POOL_STATE_UNINITIALIZED) {
4231 if (!hardforce)
4232 spa_config_sync(spa, B_TRUE, B_TRUE);
4233 spa_remove(spa);
4235 mutex_exit(&spa_namespace_lock);
4237 return (0);
4241 * Destroy a storage pool.
4244 spa_destroy(char *pool)
4246 return (spa_export_common(pool, POOL_STATE_DESTROYED, NULL,
4247 B_FALSE, B_FALSE));
4251 * Export a storage pool.
4254 spa_export(char *pool, nvlist_t **oldconfig, boolean_t force,
4255 boolean_t hardforce)
4257 return (spa_export_common(pool, POOL_STATE_EXPORTED, oldconfig,
4258 force, hardforce));
4262 * Similar to spa_export(), this unloads the spa_t without actually removing it
4263 * from the namespace in any way.
4266 spa_reset(char *pool)
4268 return (spa_export_common(pool, POOL_STATE_UNINITIALIZED, NULL,
4269 B_FALSE, B_FALSE));
4273 * ==========================================================================
4274 * Device manipulation
4275 * ==========================================================================
4279 * Add a device to a storage pool.
4282 spa_vdev_add(spa_t *spa, nvlist_t *nvroot)
4284 uint64_t txg, id;
4285 int error;
4286 vdev_t *rvd = spa->spa_root_vdev;
4287 vdev_t *vd, *tvd;
4288 nvlist_t **spares, **l2cache;
4289 uint_t nspares, nl2cache;
4291 ASSERT(spa_writeable(spa));
4293 txg = spa_vdev_enter(spa);
4295 if ((error = spa_config_parse(spa, &vd, nvroot, NULL, 0,
4296 VDEV_ALLOC_ADD)) != 0)
4297 return (spa_vdev_exit(spa, NULL, txg, error));
4299 spa->spa_pending_vdev = vd; /* spa_vdev_exit() will clear this */
4301 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares,
4302 &nspares) != 0)
4303 nspares = 0;
4305 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE, &l2cache,
4306 &nl2cache) != 0)
4307 nl2cache = 0;
4309 if (vd->vdev_children == 0 && nspares == 0 && nl2cache == 0)
4310 return (spa_vdev_exit(spa, vd, txg, EINVAL));
4312 if (vd->vdev_children != 0 &&
4313 (error = vdev_create(vd, txg, B_FALSE)) != 0)
4314 return (spa_vdev_exit(spa, vd, txg, error));
4317 * We must validate the spares and l2cache devices after checking the
4318 * children. Otherwise, vdev_inuse() will blindly overwrite the spare.
4320 if ((error = spa_validate_aux(spa, nvroot, txg, VDEV_ALLOC_ADD)) != 0)
4321 return (spa_vdev_exit(spa, vd, txg, error));
4324 * Transfer each new top-level vdev from vd to rvd.
4326 for (int c = 0; c < vd->vdev_children; c++) {
4329 * Set the vdev id to the first hole, if one exists.
4331 for (id = 0; id < rvd->vdev_children; id++) {
4332 if (rvd->vdev_child[id]->vdev_ishole) {
4333 vdev_free(rvd->vdev_child[id]);
4334 break;
4337 tvd = vd->vdev_child[c];
4338 vdev_remove_child(vd, tvd);
4339 tvd->vdev_id = id;
4340 vdev_add_child(rvd, tvd);
4341 vdev_config_dirty(tvd);
4344 if (nspares != 0) {
4345 spa_set_aux_vdevs(&spa->spa_spares, spares, nspares,
4346 ZPOOL_CONFIG_SPARES);
4347 spa_load_spares(spa);
4348 spa->spa_spares.sav_sync = B_TRUE;
4351 if (nl2cache != 0) {
4352 spa_set_aux_vdevs(&spa->spa_l2cache, l2cache, nl2cache,
4353 ZPOOL_CONFIG_L2CACHE);
4354 spa_load_l2cache(spa);
4355 spa->spa_l2cache.sav_sync = B_TRUE;
4359 * We have to be careful when adding new vdevs to an existing pool.
4360 * If other threads start allocating from these vdevs before we
4361 * sync the config cache, and we lose power, then upon reboot we may
4362 * fail to open the pool because there are DVAs that the config cache
4363 * can't translate. Therefore, we first add the vdevs without
4364 * initializing metaslabs; sync the config cache (via spa_vdev_exit());
4365 * and then let spa_config_update() initialize the new metaslabs.
4367 * spa_load() checks for added-but-not-initialized vdevs, so that
4368 * if we lose power at any point in this sequence, the remaining
4369 * steps will be completed the next time we load the pool.
4371 (void) spa_vdev_exit(spa, vd, txg, 0);
4373 mutex_enter(&spa_namespace_lock);
4374 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
4375 mutex_exit(&spa_namespace_lock);
4377 return (0);
4381 * Attach a device to a mirror. The arguments are the path to any device
4382 * in the mirror, and the nvroot for the new device. If the path specifies
4383 * a device that is not mirrored, we automatically insert the mirror vdev.
4385 * If 'replacing' is specified, the new device is intended to replace the
4386 * existing device; in this case the two devices are made into their own
4387 * mirror using the 'replacing' vdev, which is functionally identical to
4388 * the mirror vdev (it actually reuses all the same ops) but has a few
4389 * extra rules: you can't attach to it after it's been created, and upon
4390 * completion of resilvering, the first disk (the one being replaced)
4391 * is automatically detached.
4394 spa_vdev_attach(spa_t *spa, uint64_t guid, nvlist_t *nvroot, int replacing)
4396 uint64_t txg, dtl_max_txg;
4397 vdev_t *rvd = spa->spa_root_vdev;
4398 vdev_t *oldvd, *newvd, *newrootvd, *pvd, *tvd;
4399 vdev_ops_t *pvops;
4400 char *oldvdpath, *newvdpath;
4401 int newvd_isspare;
4402 int error;
4404 ASSERT(spa_writeable(spa));
4406 txg = spa_vdev_enter(spa);
4408 oldvd = spa_lookup_by_guid(spa, guid, B_FALSE);
4410 if (oldvd == NULL)
4411 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
4413 if (!oldvd->vdev_ops->vdev_op_leaf)
4414 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
4416 pvd = oldvd->vdev_parent;
4418 if ((error = spa_config_parse(spa, &newrootvd, nvroot, NULL, 0,
4419 VDEV_ALLOC_ATTACH)) != 0)
4420 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
4422 if (newrootvd->vdev_children != 1)
4423 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
4425 newvd = newrootvd->vdev_child[0];
4427 if (!newvd->vdev_ops->vdev_op_leaf)
4428 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
4430 if ((error = vdev_create(newrootvd, txg, replacing)) != 0)
4431 return (spa_vdev_exit(spa, newrootvd, txg, error));
4434 * Spares can't replace logs
4436 if (oldvd->vdev_top->vdev_islog && newvd->vdev_isspare)
4437 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
4439 if (!replacing) {
4441 * For attach, the only allowable parent is a mirror or the root
4442 * vdev.
4444 if (pvd->vdev_ops != &vdev_mirror_ops &&
4445 pvd->vdev_ops != &vdev_root_ops)
4446 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
4448 pvops = &vdev_mirror_ops;
4449 } else {
4451 * Active hot spares can only be replaced by inactive hot
4452 * spares.
4454 if (pvd->vdev_ops == &vdev_spare_ops &&
4455 oldvd->vdev_isspare &&
4456 !spa_has_spare(spa, newvd->vdev_guid))
4457 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
4460 * If the source is a hot spare, and the parent isn't already a
4461 * spare, then we want to create a new hot spare. Otherwise, we
4462 * want to create a replacing vdev. The user is not allowed to
4463 * attach to a spared vdev child unless the 'isspare' state is
4464 * the same (spare replaces spare, non-spare replaces
4465 * non-spare).
4467 if (pvd->vdev_ops == &vdev_replacing_ops &&
4468 spa_version(spa) < SPA_VERSION_MULTI_REPLACE) {
4469 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
4470 } else if (pvd->vdev_ops == &vdev_spare_ops &&
4471 newvd->vdev_isspare != oldvd->vdev_isspare) {
4472 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
4475 if (newvd->vdev_isspare)
4476 pvops = &vdev_spare_ops;
4477 else
4478 pvops = &vdev_replacing_ops;
4482 * Make sure the new device is big enough.
4484 if (newvd->vdev_asize < vdev_get_min_asize(oldvd))
4485 return (spa_vdev_exit(spa, newrootvd, txg, EOVERFLOW));
4488 * The new device cannot have a higher alignment requirement
4489 * than the top-level vdev.
4491 if (newvd->vdev_ashift > oldvd->vdev_top->vdev_ashift)
4492 return (spa_vdev_exit(spa, newrootvd, txg, EDOM));
4495 * If this is an in-place replacement, update oldvd's path and devid
4496 * to make it distinguishable from newvd, and unopenable from now on.
4498 if (strcmp(oldvd->vdev_path, newvd->vdev_path) == 0) {
4499 spa_strfree(oldvd->vdev_path);
4500 oldvd->vdev_path = kmem_alloc(strlen(newvd->vdev_path) + 5,
4501 KM_SLEEP);
4502 (void) sprintf(oldvd->vdev_path, "%s/%s",
4503 newvd->vdev_path, "old");
4504 if (oldvd->vdev_devid != NULL) {
4505 spa_strfree(oldvd->vdev_devid);
4506 oldvd->vdev_devid = NULL;
4510 /* mark the device being resilvered */
4511 newvd->vdev_resilver_txg = txg;
4514 * If the parent is not a mirror, or if we're replacing, insert the new
4515 * mirror/replacing/spare vdev above oldvd.
4517 if (pvd->vdev_ops != pvops)
4518 pvd = vdev_add_parent(oldvd, pvops);
4520 ASSERT(pvd->vdev_top->vdev_parent == rvd);
4521 ASSERT(pvd->vdev_ops == pvops);
4522 ASSERT(oldvd->vdev_parent == pvd);
4525 * Extract the new device from its root and add it to pvd.
4527 vdev_remove_child(newrootvd, newvd);
4528 newvd->vdev_id = pvd->vdev_children;
4529 newvd->vdev_crtxg = oldvd->vdev_crtxg;
4530 vdev_add_child(pvd, newvd);
4532 tvd = newvd->vdev_top;
4533 ASSERT(pvd->vdev_top == tvd);
4534 ASSERT(tvd->vdev_parent == rvd);
4536 vdev_config_dirty(tvd);
4539 * Set newvd's DTL to [TXG_INITIAL, dtl_max_txg) so that we account
4540 * for any dmu_sync-ed blocks. It will propagate upward when
4541 * spa_vdev_exit() calls vdev_dtl_reassess().
4543 dtl_max_txg = txg + TXG_CONCURRENT_STATES;
4545 vdev_dtl_dirty(newvd, DTL_MISSING, TXG_INITIAL,
4546 dtl_max_txg - TXG_INITIAL);
4548 if (newvd->vdev_isspare) {
4549 spa_spare_activate(newvd);
4550 spa_event_notify(spa, newvd, ESC_ZFS_VDEV_SPARE);
4553 oldvdpath = spa_strdup(oldvd->vdev_path);
4554 newvdpath = spa_strdup(newvd->vdev_path);
4555 newvd_isspare = newvd->vdev_isspare;
4558 * Mark newvd's DTL dirty in this txg.
4560 vdev_dirty(tvd, VDD_DTL, newvd, txg);
4563 * Schedule the resilver to restart in the future. We do this to
4564 * ensure that dmu_sync-ed blocks have been stitched into the
4565 * respective datasets.
4567 dsl_resilver_restart(spa->spa_dsl_pool, dtl_max_txg);
4570 * Commit the config
4572 (void) spa_vdev_exit(spa, newrootvd, dtl_max_txg, 0);
4574 spa_history_log_internal(spa, "vdev attach", NULL,
4575 "%s vdev=%s %s vdev=%s",
4576 replacing && newvd_isspare ? "spare in" :
4577 replacing ? "replace" : "attach", newvdpath,
4578 replacing ? "for" : "to", oldvdpath);
4580 spa_strfree(oldvdpath);
4581 spa_strfree(newvdpath);
4583 if (spa->spa_bootfs)
4584 spa_event_notify(spa, newvd, ESC_ZFS_BOOTFS_VDEV_ATTACH);
4586 return (0);
4590 * Detach a device from a mirror or replacing vdev.
4592 * If 'replace_done' is specified, only detach if the parent
4593 * is a replacing vdev.
4596 spa_vdev_detach(spa_t *spa, uint64_t guid, uint64_t pguid, int replace_done)
4598 uint64_t txg;
4599 int error;
4600 vdev_t *rvd = spa->spa_root_vdev;
4601 vdev_t *vd, *pvd, *cvd, *tvd;
4602 boolean_t unspare = B_FALSE;
4603 uint64_t unspare_guid = 0;
4604 char *vdpath;
4606 ASSERT(spa_writeable(spa));
4608 txg = spa_vdev_enter(spa);
4610 vd = spa_lookup_by_guid(spa, guid, B_FALSE);
4612 if (vd == NULL)
4613 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
4615 if (!vd->vdev_ops->vdev_op_leaf)
4616 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
4618 pvd = vd->vdev_parent;
4621 * If the parent/child relationship is not as expected, don't do it.
4622 * Consider M(A,R(B,C)) -- that is, a mirror of A with a replacing
4623 * vdev that's replacing B with C. The user's intent in replacing
4624 * is to go from M(A,B) to M(A,C). If the user decides to cancel
4625 * the replace by detaching C, the expected behavior is to end up
4626 * M(A,B). But suppose that right after deciding to detach C,
4627 * the replacement of B completes. We would have M(A,C), and then
4628 * ask to detach C, which would leave us with just A -- not what
4629 * the user wanted. To prevent this, we make sure that the
4630 * parent/child relationship hasn't changed -- in this example,
4631 * that C's parent is still the replacing vdev R.
4633 if (pvd->vdev_guid != pguid && pguid != 0)
4634 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
4637 * Only 'replacing' or 'spare' vdevs can be replaced.
4639 if (replace_done && pvd->vdev_ops != &vdev_replacing_ops &&
4640 pvd->vdev_ops != &vdev_spare_ops)
4641 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
4643 ASSERT(pvd->vdev_ops != &vdev_spare_ops ||
4644 spa_version(spa) >= SPA_VERSION_SPARES);
4647 * Only mirror, replacing, and spare vdevs support detach.
4649 if (pvd->vdev_ops != &vdev_replacing_ops &&
4650 pvd->vdev_ops != &vdev_mirror_ops &&
4651 pvd->vdev_ops != &vdev_spare_ops)
4652 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
4655 * If this device has the only valid copy of some data,
4656 * we cannot safely detach it.
4658 if (vdev_dtl_required(vd))
4659 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
4661 ASSERT(pvd->vdev_children >= 2);
4664 * If we are detaching the second disk from a replacing vdev, then
4665 * check to see if we changed the original vdev's path to have "/old"
4666 * at the end in spa_vdev_attach(). If so, undo that change now.
4668 if (pvd->vdev_ops == &vdev_replacing_ops && vd->vdev_id > 0 &&
4669 vd->vdev_path != NULL) {
4670 size_t len = strlen(vd->vdev_path);
4672 for (int c = 0; c < pvd->vdev_children; c++) {
4673 cvd = pvd->vdev_child[c];
4675 if (cvd == vd || cvd->vdev_path == NULL)
4676 continue;
4678 if (strncmp(cvd->vdev_path, vd->vdev_path, len) == 0 &&
4679 strcmp(cvd->vdev_path + len, "/old") == 0) {
4680 spa_strfree(cvd->vdev_path);
4681 cvd->vdev_path = spa_strdup(vd->vdev_path);
4682 break;
4688 * If we are detaching the original disk from a spare, then it implies
4689 * that the spare should become a real disk, and be removed from the
4690 * active spare list for the pool.
4692 if (pvd->vdev_ops == &vdev_spare_ops &&
4693 vd->vdev_id == 0 &&
4694 pvd->vdev_child[pvd->vdev_children - 1]->vdev_isspare)
4695 unspare = B_TRUE;
4698 * Erase the disk labels so the disk can be used for other things.
4699 * This must be done after all other error cases are handled,
4700 * but before we disembowel vd (so we can still do I/O to it).
4701 * But if we can't do it, don't treat the error as fatal --
4702 * it may be that the unwritability of the disk is the reason
4703 * it's being detached!
4705 error = vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
4708 * Remove vd from its parent and compact the parent's children.
4710 vdev_remove_child(pvd, vd);
4711 vdev_compact_children(pvd);
4714 * Remember one of the remaining children so we can get tvd below.
4716 cvd = pvd->vdev_child[pvd->vdev_children - 1];
4719 * If we need to remove the remaining child from the list of hot spares,
4720 * do it now, marking the vdev as no longer a spare in the process.
4721 * We must do this before vdev_remove_parent(), because that can
4722 * change the GUID if it creates a new toplevel GUID. For a similar
4723 * reason, we must remove the spare now, in the same txg as the detach;
4724 * otherwise someone could attach a new sibling, change the GUID, and
4725 * the subsequent attempt to spa_vdev_remove(unspare_guid) would fail.
4727 if (unspare) {
4728 ASSERT(cvd->vdev_isspare);
4729 spa_spare_remove(cvd);
4730 unspare_guid = cvd->vdev_guid;
4731 (void) spa_vdev_remove(spa, unspare_guid, B_TRUE);
4732 cvd->vdev_unspare = B_TRUE;
4736 * If the parent mirror/replacing vdev only has one child,
4737 * the parent is no longer needed. Remove it from the tree.
4739 if (pvd->vdev_children == 1) {
4740 if (pvd->vdev_ops == &vdev_spare_ops)
4741 cvd->vdev_unspare = B_FALSE;
4742 vdev_remove_parent(cvd);
4747 * We don't set tvd until now because the parent we just removed
4748 * may have been the previous top-level vdev.
4750 tvd = cvd->vdev_top;
4751 ASSERT(tvd->vdev_parent == rvd);
4754 * Reevaluate the parent vdev state.
4756 vdev_propagate_state(cvd);
4759 * If the 'autoexpand' property is set on the pool then automatically
4760 * try to expand the size of the pool. For example if the device we
4761 * just detached was smaller than the others, it may be possible to
4762 * add metaslabs (i.e. grow the pool). We need to reopen the vdev
4763 * first so that we can obtain the updated sizes of the leaf vdevs.
4765 if (spa->spa_autoexpand) {
4766 vdev_reopen(tvd);
4767 vdev_expand(tvd, txg);
4770 vdev_config_dirty(tvd);
4773 * Mark vd's DTL as dirty in this txg. vdev_dtl_sync() will see that
4774 * vd->vdev_detached is set and free vd's DTL object in syncing context.
4775 * But first make sure we're not on any *other* txg's DTL list, to
4776 * prevent vd from being accessed after it's freed.
4778 vdpath = spa_strdup(vd->vdev_path);
4779 for (int t = 0; t < TXG_SIZE; t++)
4780 (void) txg_list_remove_this(&tvd->vdev_dtl_list, vd, t);
4781 vd->vdev_detached = B_TRUE;
4782 vdev_dirty(tvd, VDD_DTL, vd, txg);
4784 spa_event_notify(spa, vd, ESC_ZFS_VDEV_REMOVE);
4786 /* hang on to the spa before we release the lock */
4787 spa_open_ref(spa, FTAG);
4789 error = spa_vdev_exit(spa, vd, txg, 0);
4791 spa_history_log_internal(spa, "detach", NULL,
4792 "vdev=%s", vdpath);
4793 spa_strfree(vdpath);
4796 * If this was the removal of the original device in a hot spare vdev,
4797 * then we want to go through and remove the device from the hot spare
4798 * list of every other pool.
4800 if (unspare) {
4801 spa_t *altspa = NULL;
4803 mutex_enter(&spa_namespace_lock);
4804 while ((altspa = spa_next(altspa)) != NULL) {
4805 if (altspa->spa_state != POOL_STATE_ACTIVE ||
4806 altspa == spa)
4807 continue;
4809 spa_open_ref(altspa, FTAG);
4810 mutex_exit(&spa_namespace_lock);
4811 (void) spa_vdev_remove(altspa, unspare_guid, B_TRUE);
4812 mutex_enter(&spa_namespace_lock);
4813 spa_close(altspa, FTAG);
4815 mutex_exit(&spa_namespace_lock);
4817 /* search the rest of the vdevs for spares to remove */
4818 spa_vdev_resilver_done(spa);
4821 /* all done with the spa; OK to release */
4822 mutex_enter(&spa_namespace_lock);
4823 spa_close(spa, FTAG);
4824 mutex_exit(&spa_namespace_lock);
4826 return (error);
4830 * Split a set of devices from their mirrors, and create a new pool from them.
4833 spa_vdev_split_mirror(spa_t *spa, char *newname, nvlist_t *config,
4834 nvlist_t *props, boolean_t exp)
4836 int error = 0;
4837 uint64_t txg, *glist;
4838 spa_t *newspa;
4839 uint_t c, children, lastlog;
4840 nvlist_t **child, *nvl, *tmp;
4841 dmu_tx_t *tx;
4842 char *altroot = NULL;
4843 vdev_t *rvd, **vml = NULL; /* vdev modify list */
4844 boolean_t activate_slog;
4846 ASSERT(spa_writeable(spa));
4848 txg = spa_vdev_enter(spa);
4850 /* clear the log and flush everything up to now */
4851 activate_slog = spa_passivate_log(spa);
4852 (void) spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
4853 error = spa_offline_log(spa);
4854 txg = spa_vdev_config_enter(spa);
4856 if (activate_slog)
4857 spa_activate_log(spa);
4859 if (error != 0)
4860 return (spa_vdev_exit(spa, NULL, txg, error));
4862 /* check new spa name before going any further */
4863 if (spa_lookup(newname) != NULL)
4864 return (spa_vdev_exit(spa, NULL, txg, EEXIST));
4867 * scan through all the children to ensure they're all mirrors
4869 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvl) != 0 ||
4870 nvlist_lookup_nvlist_array(nvl, ZPOOL_CONFIG_CHILDREN, &child,
4871 &children) != 0)
4872 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
4874 /* first, check to ensure we've got the right child count */
4875 rvd = spa->spa_root_vdev;
4876 lastlog = 0;
4877 for (c = 0; c < rvd->vdev_children; c++) {
4878 vdev_t *vd = rvd->vdev_child[c];
4880 /* don't count the holes & logs as children */
4881 if (vd->vdev_islog || vd->vdev_ishole) {
4882 if (lastlog == 0)
4883 lastlog = c;
4884 continue;
4887 lastlog = 0;
4889 if (children != (lastlog != 0 ? lastlog : rvd->vdev_children))
4890 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
4892 /* next, ensure no spare or cache devices are part of the split */
4893 if (nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_SPARES, &tmp) == 0 ||
4894 nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_L2CACHE, &tmp) == 0)
4895 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
4897 vml = kmem_zalloc(children * sizeof (vdev_t *), KM_SLEEP);
4898 glist = kmem_zalloc(children * sizeof (uint64_t), KM_SLEEP);
4900 /* then, loop over each vdev and validate it */
4901 for (c = 0; c < children; c++) {
4902 uint64_t is_hole = 0;
4904 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
4905 &is_hole);
4907 if (is_hole != 0) {
4908 if (spa->spa_root_vdev->vdev_child[c]->vdev_ishole ||
4909 spa->spa_root_vdev->vdev_child[c]->vdev_islog) {
4910 continue;
4911 } else {
4912 error = SET_ERROR(EINVAL);
4913 break;
4917 /* which disk is going to be split? */
4918 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_GUID,
4919 &glist[c]) != 0) {
4920 error = SET_ERROR(EINVAL);
4921 break;
4924 /* look it up in the spa */
4925 vml[c] = spa_lookup_by_guid(spa, glist[c], B_FALSE);
4926 if (vml[c] == NULL) {
4927 error = SET_ERROR(ENODEV);
4928 break;
4931 /* make sure there's nothing stopping the split */
4932 if (vml[c]->vdev_parent->vdev_ops != &vdev_mirror_ops ||
4933 vml[c]->vdev_islog ||
4934 vml[c]->vdev_ishole ||
4935 vml[c]->vdev_isspare ||
4936 vml[c]->vdev_isl2cache ||
4937 !vdev_writeable(vml[c]) ||
4938 vml[c]->vdev_children != 0 ||
4939 vml[c]->vdev_state != VDEV_STATE_HEALTHY ||
4940 c != spa->spa_root_vdev->vdev_child[c]->vdev_id) {
4941 error = SET_ERROR(EINVAL);
4942 break;
4945 if (vdev_dtl_required(vml[c])) {
4946 error = SET_ERROR(EBUSY);
4947 break;
4950 /* we need certain info from the top level */
4951 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_ARRAY,
4952 vml[c]->vdev_top->vdev_ms_array) == 0);
4953 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_SHIFT,
4954 vml[c]->vdev_top->vdev_ms_shift) == 0);
4955 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASIZE,
4956 vml[c]->vdev_top->vdev_asize) == 0);
4957 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASHIFT,
4958 vml[c]->vdev_top->vdev_ashift) == 0);
4961 if (error != 0) {
4962 kmem_free(vml, children * sizeof (vdev_t *));
4963 kmem_free(glist, children * sizeof (uint64_t));
4964 return (spa_vdev_exit(spa, NULL, txg, error));
4967 /* stop writers from using the disks */
4968 for (c = 0; c < children; c++) {
4969 if (vml[c] != NULL)
4970 vml[c]->vdev_offline = B_TRUE;
4972 vdev_reopen(spa->spa_root_vdev);
4975 * Temporarily record the splitting vdevs in the spa config. This
4976 * will disappear once the config is regenerated.
4978 VERIFY(nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4979 VERIFY(nvlist_add_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
4980 glist, children) == 0);
4981 kmem_free(glist, children * sizeof (uint64_t));
4983 mutex_enter(&spa->spa_props_lock);
4984 VERIFY(nvlist_add_nvlist(spa->spa_config, ZPOOL_CONFIG_SPLIT,
4985 nvl) == 0);
4986 mutex_exit(&spa->spa_props_lock);
4987 spa->spa_config_splitting = nvl;
4988 vdev_config_dirty(spa->spa_root_vdev);
4990 /* configure and create the new pool */
4991 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME, newname) == 0);
4992 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
4993 exp ? POOL_STATE_EXPORTED : POOL_STATE_ACTIVE) == 0);
4994 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
4995 spa_version(spa)) == 0);
4996 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_TXG,
4997 spa->spa_config_txg) == 0);
4998 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_GUID,
4999 spa_generate_guid(NULL)) == 0);
5000 (void) nvlist_lookup_string(props,
5001 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
5003 /* add the new pool to the namespace */
5004 newspa = spa_add(newname, config, altroot);
5005 newspa->spa_config_txg = spa->spa_config_txg;
5006 spa_set_log_state(newspa, SPA_LOG_CLEAR);
5008 /* release the spa config lock, retaining the namespace lock */
5009 spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
5011 if (zio_injection_enabled)
5012 zio_handle_panic_injection(spa, FTAG, 1);
5014 spa_activate(newspa, spa_mode_global);
5015 spa_async_suspend(newspa);
5017 /* create the new pool from the disks of the original pool */
5018 error = spa_load(newspa, SPA_LOAD_IMPORT, SPA_IMPORT_ASSEMBLE, B_TRUE);
5019 if (error)
5020 goto out;
5022 /* if that worked, generate a real config for the new pool */
5023 if (newspa->spa_root_vdev != NULL) {
5024 VERIFY(nvlist_alloc(&newspa->spa_config_splitting,
5025 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5026 VERIFY(nvlist_add_uint64(newspa->spa_config_splitting,
5027 ZPOOL_CONFIG_SPLIT_GUID, spa_guid(spa)) == 0);
5028 spa_config_set(newspa, spa_config_generate(newspa, NULL, -1ULL,
5029 B_TRUE));
5032 /* set the props */
5033 if (props != NULL) {
5034 spa_configfile_set(newspa, props, B_FALSE);
5035 error = spa_prop_set(newspa, props);
5036 if (error)
5037 goto out;
5040 /* flush everything */
5041 txg = spa_vdev_config_enter(newspa);
5042 vdev_config_dirty(newspa->spa_root_vdev);
5043 (void) spa_vdev_config_exit(newspa, NULL, txg, 0, FTAG);
5045 if (zio_injection_enabled)
5046 zio_handle_panic_injection(spa, FTAG, 2);
5048 spa_async_resume(newspa);
5050 /* finally, update the original pool's config */
5051 txg = spa_vdev_config_enter(spa);
5052 tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
5053 error = dmu_tx_assign(tx, TXG_WAIT);
5054 if (error != 0)
5055 dmu_tx_abort(tx);
5056 for (c = 0; c < children; c++) {
5057 if (vml[c] != NULL) {
5058 vdev_split(vml[c]);
5059 if (error == 0)
5060 spa_history_log_internal(spa, "detach", tx,
5061 "vdev=%s", vml[c]->vdev_path);
5062 vdev_free(vml[c]);
5065 vdev_config_dirty(spa->spa_root_vdev);
5066 spa->spa_config_splitting = NULL;
5067 nvlist_free(nvl);
5068 if (error == 0)
5069 dmu_tx_commit(tx);
5070 (void) spa_vdev_exit(spa, NULL, txg, 0);
5072 if (zio_injection_enabled)
5073 zio_handle_panic_injection(spa, FTAG, 3);
5075 /* split is complete; log a history record */
5076 spa_history_log_internal(newspa, "split", NULL,
5077 "from pool %s", spa_name(spa));
5079 kmem_free(vml, children * sizeof (vdev_t *));
5081 /* if we're not going to mount the filesystems in userland, export */
5082 if (exp)
5083 error = spa_export_common(newname, POOL_STATE_EXPORTED, NULL,
5084 B_FALSE, B_FALSE);
5086 return (error);
5088 out:
5089 spa_unload(newspa);
5090 spa_deactivate(newspa);
5091 spa_remove(newspa);
5093 txg = spa_vdev_config_enter(spa);
5095 /* re-online all offlined disks */
5096 for (c = 0; c < children; c++) {
5097 if (vml[c] != NULL)
5098 vml[c]->vdev_offline = B_FALSE;
5100 vdev_reopen(spa->spa_root_vdev);
5102 nvlist_free(spa->spa_config_splitting);
5103 spa->spa_config_splitting = NULL;
5104 (void) spa_vdev_exit(spa, NULL, txg, error);
5106 kmem_free(vml, children * sizeof (vdev_t *));
5107 return (error);
5110 static nvlist_t *
5111 spa_nvlist_lookup_by_guid(nvlist_t **nvpp, int count, uint64_t target_guid)
5113 for (int i = 0; i < count; i++) {
5114 uint64_t guid;
5116 VERIFY(nvlist_lookup_uint64(nvpp[i], ZPOOL_CONFIG_GUID,
5117 &guid) == 0);
5119 if (guid == target_guid)
5120 return (nvpp[i]);
5123 return (NULL);
5126 static void
5127 spa_vdev_remove_aux(nvlist_t *config, char *name, nvlist_t **dev, int count,
5128 nvlist_t *dev_to_remove)
5130 nvlist_t **newdev = NULL;
5132 if (count > 1)
5133 newdev = kmem_alloc((count - 1) * sizeof (void *), KM_SLEEP);
5135 for (int i = 0, j = 0; i < count; i++) {
5136 if (dev[i] == dev_to_remove)
5137 continue;
5138 VERIFY(nvlist_dup(dev[i], &newdev[j++], KM_SLEEP) == 0);
5141 VERIFY(nvlist_remove(config, name, DATA_TYPE_NVLIST_ARRAY) == 0);
5142 VERIFY(nvlist_add_nvlist_array(config, name, newdev, count - 1) == 0);
5144 for (int i = 0; i < count - 1; i++)
5145 nvlist_free(newdev[i]);
5147 if (count > 1)
5148 kmem_free(newdev, (count - 1) * sizeof (void *));
5152 * Evacuate the device.
5154 static int
5155 spa_vdev_remove_evacuate(spa_t *spa, vdev_t *vd)
5157 uint64_t txg;
5158 int error = 0;
5160 ASSERT(MUTEX_HELD(&spa_namespace_lock));
5161 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
5162 ASSERT(vd == vd->vdev_top);
5165 * Evacuate the device. We don't hold the config lock as writer
5166 * since we need to do I/O but we do keep the
5167 * spa_namespace_lock held. Once this completes the device
5168 * should no longer have any blocks allocated on it.
5170 if (vd->vdev_islog) {
5171 if (vd->vdev_stat.vs_alloc != 0)
5172 error = spa_offline_log(spa);
5173 } else {
5174 error = SET_ERROR(ENOTSUP);
5177 if (error)
5178 return (error);
5181 * The evacuation succeeded. Remove any remaining MOS metadata
5182 * associated with this vdev, and wait for these changes to sync.
5184 ASSERT0(vd->vdev_stat.vs_alloc);
5185 txg = spa_vdev_config_enter(spa);
5186 vd->vdev_removing = B_TRUE;
5187 vdev_dirty_leaves(vd, VDD_DTL, txg);
5188 vdev_config_dirty(vd);
5189 spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
5191 return (0);
5195 * Complete the removal by cleaning up the namespace.
5197 static void
5198 spa_vdev_remove_from_namespace(spa_t *spa, vdev_t *vd)
5200 vdev_t *rvd = spa->spa_root_vdev;
5201 uint64_t id = vd->vdev_id;
5202 boolean_t last_vdev = (id == (rvd->vdev_children - 1));
5204 ASSERT(MUTEX_HELD(&spa_namespace_lock));
5205 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
5206 ASSERT(vd == vd->vdev_top);
5209 * Only remove any devices which are empty.
5211 if (vd->vdev_stat.vs_alloc != 0)
5212 return;
5214 (void) vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
5216 if (list_link_active(&vd->vdev_state_dirty_node))
5217 vdev_state_clean(vd);
5218 if (list_link_active(&vd->vdev_config_dirty_node))
5219 vdev_config_clean(vd);
5221 vdev_free(vd);
5223 if (last_vdev) {
5224 vdev_compact_children(rvd);
5225 } else {
5226 vd = vdev_alloc_common(spa, id, 0, &vdev_hole_ops);
5227 vdev_add_child(rvd, vd);
5229 vdev_config_dirty(rvd);
5232 * Reassess the health of our root vdev.
5234 vdev_reopen(rvd);
5238 * Remove a device from the pool -
5240 * Removing a device from the vdev namespace requires several steps
5241 * and can take a significant amount of time. As a result we use
5242 * the spa_vdev_config_[enter/exit] functions which allow us to
5243 * grab and release the spa_config_lock while still holding the namespace
5244 * lock. During each step the configuration is synced out.
5246 * Currently, this supports removing only hot spares, slogs, and level 2 ARC
5247 * devices.
5250 spa_vdev_remove(spa_t *spa, uint64_t guid, boolean_t unspare)
5252 vdev_t *vd;
5253 metaslab_group_t *mg;
5254 nvlist_t **spares, **l2cache, *nv;
5255 uint64_t txg = 0;
5256 uint_t nspares, nl2cache;
5257 int error = 0;
5258 boolean_t locked = MUTEX_HELD(&spa_namespace_lock);
5260 ASSERT(spa_writeable(spa));
5262 if (!locked)
5263 txg = spa_vdev_enter(spa);
5265 vd = spa_lookup_by_guid(spa, guid, B_FALSE);
5267 if (spa->spa_spares.sav_vdevs != NULL &&
5268 nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
5269 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0 &&
5270 (nv = spa_nvlist_lookup_by_guid(spares, nspares, guid)) != NULL) {
5272 * Only remove the hot spare if it's not currently in use
5273 * in this pool.
5275 if (vd == NULL || unspare) {
5276 spa_vdev_remove_aux(spa->spa_spares.sav_config,
5277 ZPOOL_CONFIG_SPARES, spares, nspares, nv);
5278 spa_load_spares(spa);
5279 spa->spa_spares.sav_sync = B_TRUE;
5280 } else {
5281 error = SET_ERROR(EBUSY);
5283 } else if (spa->spa_l2cache.sav_vdevs != NULL &&
5284 nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
5285 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0 &&
5286 (nv = spa_nvlist_lookup_by_guid(l2cache, nl2cache, guid)) != NULL) {
5288 * Cache devices can always be removed.
5290 spa_vdev_remove_aux(spa->spa_l2cache.sav_config,
5291 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache, nv);
5292 spa_load_l2cache(spa);
5293 spa->spa_l2cache.sav_sync = B_TRUE;
5294 } else if (vd != NULL && vd->vdev_islog) {
5295 ASSERT(!locked);
5296 ASSERT(vd == vd->vdev_top);
5298 mg = vd->vdev_mg;
5301 * Stop allocating from this vdev.
5303 metaslab_group_passivate(mg);
5306 * Wait for the youngest allocations and frees to sync,
5307 * and then wait for the deferral of those frees to finish.
5309 spa_vdev_config_exit(spa, NULL,
5310 txg + TXG_CONCURRENT_STATES + TXG_DEFER_SIZE, 0, FTAG);
5313 * Attempt to evacuate the vdev.
5315 error = spa_vdev_remove_evacuate(spa, vd);
5317 txg = spa_vdev_config_enter(spa);
5320 * If we couldn't evacuate the vdev, unwind.
5322 if (error) {
5323 metaslab_group_activate(mg);
5324 return (spa_vdev_exit(spa, NULL, txg, error));
5328 * Clean up the vdev namespace.
5330 spa_vdev_remove_from_namespace(spa, vd);
5332 } else if (vd != NULL) {
5334 * Normal vdevs cannot be removed (yet).
5336 error = SET_ERROR(ENOTSUP);
5337 } else {
5339 * There is no vdev of any kind with the specified guid.
5341 error = SET_ERROR(ENOENT);
5344 if (!locked)
5345 return (spa_vdev_exit(spa, NULL, txg, error));
5347 return (error);
5351 * Find any device that's done replacing, or a vdev marked 'unspare' that's
5352 * currently spared, so we can detach it.
5354 static vdev_t *
5355 spa_vdev_resilver_done_hunt(vdev_t *vd)
5357 vdev_t *newvd, *oldvd;
5359 for (int c = 0; c < vd->vdev_children; c++) {
5360 oldvd = spa_vdev_resilver_done_hunt(vd->vdev_child[c]);
5361 if (oldvd != NULL)
5362 return (oldvd);
5366 * Check for a completed replacement. We always consider the first
5367 * vdev in the list to be the oldest vdev, and the last one to be
5368 * the newest (see spa_vdev_attach() for how that works). In
5369 * the case where the newest vdev is faulted, we will not automatically
5370 * remove it after a resilver completes. This is OK as it will require
5371 * user intervention to determine which disk the admin wishes to keep.
5373 if (vd->vdev_ops == &vdev_replacing_ops) {
5374 ASSERT(vd->vdev_children > 1);
5376 newvd = vd->vdev_child[vd->vdev_children - 1];
5377 oldvd = vd->vdev_child[0];
5379 if (vdev_dtl_empty(newvd, DTL_MISSING) &&
5380 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
5381 !vdev_dtl_required(oldvd))
5382 return (oldvd);
5386 * Check for a completed resilver with the 'unspare' flag set.
5388 if (vd->vdev_ops == &vdev_spare_ops) {
5389 vdev_t *first = vd->vdev_child[0];
5390 vdev_t *last = vd->vdev_child[vd->vdev_children - 1];
5392 if (last->vdev_unspare) {
5393 oldvd = first;
5394 newvd = last;
5395 } else if (first->vdev_unspare) {
5396 oldvd = last;
5397 newvd = first;
5398 } else {
5399 oldvd = NULL;
5402 if (oldvd != NULL &&
5403 vdev_dtl_empty(newvd, DTL_MISSING) &&
5404 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
5405 !vdev_dtl_required(oldvd))
5406 return (oldvd);
5409 * If there are more than two spares attached to a disk,
5410 * and those spares are not required, then we want to
5411 * attempt to free them up now so that they can be used
5412 * by other pools. Once we're back down to a single
5413 * disk+spare, we stop removing them.
5415 if (vd->vdev_children > 2) {
5416 newvd = vd->vdev_child[1];
5418 if (newvd->vdev_isspare && last->vdev_isspare &&
5419 vdev_dtl_empty(last, DTL_MISSING) &&
5420 vdev_dtl_empty(last, DTL_OUTAGE) &&
5421 !vdev_dtl_required(newvd))
5422 return (newvd);
5426 return (NULL);
5429 static void
5430 spa_vdev_resilver_done(spa_t *spa)
5432 vdev_t *vd, *pvd, *ppvd;
5433 uint64_t guid, sguid, pguid, ppguid;
5435 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5437 while ((vd = spa_vdev_resilver_done_hunt(spa->spa_root_vdev)) != NULL) {
5438 pvd = vd->vdev_parent;
5439 ppvd = pvd->vdev_parent;
5440 guid = vd->vdev_guid;
5441 pguid = pvd->vdev_guid;
5442 ppguid = ppvd->vdev_guid;
5443 sguid = 0;
5445 * If we have just finished replacing a hot spared device, then
5446 * we need to detach the parent's first child (the original hot
5447 * spare) as well.
5449 if (ppvd->vdev_ops == &vdev_spare_ops && pvd->vdev_id == 0 &&
5450 ppvd->vdev_children == 2) {
5451 ASSERT(pvd->vdev_ops == &vdev_replacing_ops);
5452 sguid = ppvd->vdev_child[1]->vdev_guid;
5454 ASSERT(vd->vdev_resilver_txg == 0 || !vdev_dtl_required(vd));
5456 spa_config_exit(spa, SCL_ALL, FTAG);
5457 if (spa_vdev_detach(spa, guid, pguid, B_TRUE) != 0)
5458 return;
5459 if (sguid && spa_vdev_detach(spa, sguid, ppguid, B_TRUE) != 0)
5460 return;
5461 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5464 spa_config_exit(spa, SCL_ALL, FTAG);
5468 * Update the stored path or FRU for this vdev.
5471 spa_vdev_set_common(spa_t *spa, uint64_t guid, const char *value,
5472 boolean_t ispath)
5474 vdev_t *vd;
5475 boolean_t sync = B_FALSE;
5477 ASSERT(spa_writeable(spa));
5479 spa_vdev_state_enter(spa, SCL_ALL);
5481 if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
5482 return (spa_vdev_state_exit(spa, NULL, ENOENT));
5484 if (!vd->vdev_ops->vdev_op_leaf)
5485 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
5487 if (ispath) {
5488 if (strcmp(value, vd->vdev_path) != 0) {
5489 spa_strfree(vd->vdev_path);
5490 vd->vdev_path = spa_strdup(value);
5491 sync = B_TRUE;
5493 } else {
5494 if (vd->vdev_fru == NULL) {
5495 vd->vdev_fru = spa_strdup(value);
5496 sync = B_TRUE;
5497 } else if (strcmp(value, vd->vdev_fru) != 0) {
5498 spa_strfree(vd->vdev_fru);
5499 vd->vdev_fru = spa_strdup(value);
5500 sync = B_TRUE;
5504 return (spa_vdev_state_exit(spa, sync ? vd : NULL, 0));
5508 spa_vdev_setpath(spa_t *spa, uint64_t guid, const char *newpath)
5510 return (spa_vdev_set_common(spa, guid, newpath, B_TRUE));
5514 spa_vdev_setfru(spa_t *spa, uint64_t guid, const char *newfru)
5516 return (spa_vdev_set_common(spa, guid, newfru, B_FALSE));
5520 * ==========================================================================
5521 * SPA Scanning
5522 * ==========================================================================
5526 spa_scan_stop(spa_t *spa)
5528 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
5529 if (dsl_scan_resilvering(spa->spa_dsl_pool))
5530 return (SET_ERROR(EBUSY));
5531 return (dsl_scan_cancel(spa->spa_dsl_pool));
5535 spa_scan(spa_t *spa, pool_scan_func_t func)
5537 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
5539 if (func >= POOL_SCAN_FUNCS || func == POOL_SCAN_NONE)
5540 return (SET_ERROR(ENOTSUP));
5543 * If a resilver was requested, but there is no DTL on a
5544 * writeable leaf device, we have nothing to do.
5546 if (func == POOL_SCAN_RESILVER &&
5547 !vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL)) {
5548 spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
5549 return (0);
5552 return (dsl_scan(spa->spa_dsl_pool, func));
5556 * ==========================================================================
5557 * SPA async task processing
5558 * ==========================================================================
5561 static void
5562 spa_async_remove(spa_t *spa, vdev_t *vd)
5564 if (vd->vdev_remove_wanted) {
5565 vd->vdev_remove_wanted = B_FALSE;
5566 vd->vdev_delayed_close = B_FALSE;
5567 vdev_set_state(vd, B_FALSE, VDEV_STATE_REMOVED, VDEV_AUX_NONE);
5570 * We want to clear the stats, but we don't want to do a full
5571 * vdev_clear() as that will cause us to throw away
5572 * degraded/faulted state as well as attempt to reopen the
5573 * device, all of which is a waste.
5575 vd->vdev_stat.vs_read_errors = 0;
5576 vd->vdev_stat.vs_write_errors = 0;
5577 vd->vdev_stat.vs_checksum_errors = 0;
5579 vdev_state_dirty(vd->vdev_top);
5582 for (int c = 0; c < vd->vdev_children; c++)
5583 spa_async_remove(spa, vd->vdev_child[c]);
5586 static void
5587 spa_async_probe(spa_t *spa, vdev_t *vd)
5589 if (vd->vdev_probe_wanted) {
5590 vd->vdev_probe_wanted = B_FALSE;
5591 vdev_reopen(vd); /* vdev_open() does the actual probe */
5594 for (int c = 0; c < vd->vdev_children; c++)
5595 spa_async_probe(spa, vd->vdev_child[c]);
5598 static void
5599 spa_async_autoexpand(spa_t *spa, vdev_t *vd)
5601 sysevent_id_t eid;
5602 nvlist_t *attr;
5603 char *physpath;
5605 if (!spa->spa_autoexpand)
5606 return;
5608 for (int c = 0; c < vd->vdev_children; c++) {
5609 vdev_t *cvd = vd->vdev_child[c];
5610 spa_async_autoexpand(spa, cvd);
5613 if (!vd->vdev_ops->vdev_op_leaf || vd->vdev_physpath == NULL)
5614 return;
5616 physpath = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
5617 (void) snprintf(physpath, MAXPATHLEN, "/devices%s", vd->vdev_physpath);
5619 VERIFY(nvlist_alloc(&attr, NV_UNIQUE_NAME, KM_SLEEP) == 0);
5620 VERIFY(nvlist_add_string(attr, DEV_PHYS_PATH, physpath) == 0);
5622 (void) ddi_log_sysevent(zfs_dip, SUNW_VENDOR, EC_DEV_STATUS,
5623 ESC_DEV_DLE, attr, &eid, DDI_SLEEP);
5625 nvlist_free(attr);
5626 kmem_free(physpath, MAXPATHLEN);
5629 static void
5630 spa_async_thread(spa_t *spa)
5632 int tasks;
5634 ASSERT(spa->spa_sync_on);
5636 mutex_enter(&spa->spa_async_lock);
5637 tasks = spa->spa_async_tasks;
5638 spa->spa_async_tasks = 0;
5639 mutex_exit(&spa->spa_async_lock);
5642 * See if the config needs to be updated.
5644 if (tasks & SPA_ASYNC_CONFIG_UPDATE) {
5645 uint64_t old_space, new_space;
5647 mutex_enter(&spa_namespace_lock);
5648 old_space = metaslab_class_get_space(spa_normal_class(spa));
5649 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5650 new_space = metaslab_class_get_space(spa_normal_class(spa));
5651 mutex_exit(&spa_namespace_lock);
5654 * If the pool grew as a result of the config update,
5655 * then log an internal history event.
5657 if (new_space != old_space) {
5658 spa_history_log_internal(spa, "vdev online", NULL,
5659 "pool '%s' size: %llu(+%llu)",
5660 spa_name(spa), new_space, new_space - old_space);
5665 * See if any devices need to be marked REMOVED.
5667 if (tasks & SPA_ASYNC_REMOVE) {
5668 spa_vdev_state_enter(spa, SCL_NONE);
5669 spa_async_remove(spa, spa->spa_root_vdev);
5670 for (int i = 0; i < spa->spa_l2cache.sav_count; i++)
5671 spa_async_remove(spa, spa->spa_l2cache.sav_vdevs[i]);
5672 for (int i = 0; i < spa->spa_spares.sav_count; i++)
5673 spa_async_remove(spa, spa->spa_spares.sav_vdevs[i]);
5674 (void) spa_vdev_state_exit(spa, NULL, 0);
5677 if ((tasks & SPA_ASYNC_AUTOEXPAND) && !spa_suspended(spa)) {
5678 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
5679 spa_async_autoexpand(spa, spa->spa_root_vdev);
5680 spa_config_exit(spa, SCL_CONFIG, FTAG);
5684 * See if any devices need to be probed.
5686 if (tasks & SPA_ASYNC_PROBE) {
5687 spa_vdev_state_enter(spa, SCL_NONE);
5688 spa_async_probe(spa, spa->spa_root_vdev);
5689 (void) spa_vdev_state_exit(spa, NULL, 0);
5693 * If any devices are done replacing, detach them.
5695 if (tasks & SPA_ASYNC_RESILVER_DONE)
5696 spa_vdev_resilver_done(spa);
5699 * Kick off a resilver.
5701 if (tasks & SPA_ASYNC_RESILVER)
5702 dsl_resilver_restart(spa->spa_dsl_pool, 0);
5705 * Let the world know that we're done.
5707 mutex_enter(&spa->spa_async_lock);
5708 spa->spa_async_thread = NULL;
5709 cv_broadcast(&spa->spa_async_cv);
5710 mutex_exit(&spa->spa_async_lock);
5711 thread_exit();
5714 void
5715 spa_async_suspend(spa_t *spa)
5717 mutex_enter(&spa->spa_async_lock);
5718 spa->spa_async_suspended++;
5719 while (spa->spa_async_thread != NULL)
5720 cv_wait(&spa->spa_async_cv, &spa->spa_async_lock);
5721 mutex_exit(&spa->spa_async_lock);
5724 void
5725 spa_async_resume(spa_t *spa)
5727 mutex_enter(&spa->spa_async_lock);
5728 ASSERT(spa->spa_async_suspended != 0);
5729 spa->spa_async_suspended--;
5730 mutex_exit(&spa->spa_async_lock);
5733 static boolean_t
5734 spa_async_tasks_pending(spa_t *spa)
5736 uint_t non_config_tasks;
5737 uint_t config_task;
5738 boolean_t config_task_suspended;
5740 non_config_tasks = spa->spa_async_tasks & ~SPA_ASYNC_CONFIG_UPDATE;
5741 config_task = spa->spa_async_tasks & SPA_ASYNC_CONFIG_UPDATE;
5742 if (spa->spa_ccw_fail_time == 0) {
5743 config_task_suspended = B_FALSE;
5744 } else {
5745 config_task_suspended =
5746 (gethrtime() - spa->spa_ccw_fail_time) <
5747 (zfs_ccw_retry_interval * NANOSEC);
5750 return (non_config_tasks || (config_task && !config_task_suspended));
5753 static void
5754 spa_async_dispatch(spa_t *spa)
5756 mutex_enter(&spa->spa_async_lock);
5757 if (spa_async_tasks_pending(spa) &&
5758 !spa->spa_async_suspended &&
5759 spa->spa_async_thread == NULL &&
5760 rootdir != NULL)
5761 spa->spa_async_thread = thread_create(NULL, 0,
5762 spa_async_thread, spa, 0, &p0, TS_RUN, maxclsyspri);
5763 mutex_exit(&spa->spa_async_lock);
5766 void
5767 spa_async_request(spa_t *spa, int task)
5769 zfs_dbgmsg("spa=%s async request task=%u", spa->spa_name, task);
5770 mutex_enter(&spa->spa_async_lock);
5771 spa->spa_async_tasks |= task;
5772 mutex_exit(&spa->spa_async_lock);
5776 * ==========================================================================
5777 * SPA syncing routines
5778 * ==========================================================================
5781 static int
5782 bpobj_enqueue_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
5784 bpobj_t *bpo = arg;
5785 bpobj_enqueue(bpo, bp, tx);
5786 return (0);
5789 static int
5790 spa_free_sync_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
5792 zio_t *zio = arg;
5794 zio_nowait(zio_free_sync(zio, zio->io_spa, dmu_tx_get_txg(tx), bp,
5795 zio->io_flags));
5796 return (0);
5800 * Note: this simple function is not inlined to make it easier to dtrace the
5801 * amount of time spent syncing frees.
5803 static void
5804 spa_sync_frees(spa_t *spa, bplist_t *bpl, dmu_tx_t *tx)
5806 zio_t *zio = zio_root(spa, NULL, NULL, 0);
5807 bplist_iterate(bpl, spa_free_sync_cb, zio, tx);
5808 VERIFY(zio_wait(zio) == 0);
5812 * Note: this simple function is not inlined to make it easier to dtrace the
5813 * amount of time spent syncing deferred frees.
5815 static void
5816 spa_sync_deferred_frees(spa_t *spa, dmu_tx_t *tx)
5818 zio_t *zio = zio_root(spa, NULL, NULL, 0);
5819 VERIFY3U(bpobj_iterate(&spa->spa_deferred_bpobj,
5820 spa_free_sync_cb, zio, tx), ==, 0);
5821 VERIFY0(zio_wait(zio));
5825 static void
5826 spa_sync_nvlist(spa_t *spa, uint64_t obj, nvlist_t *nv, dmu_tx_t *tx)
5828 char *packed = NULL;
5829 size_t bufsize;
5830 size_t nvsize = 0;
5831 dmu_buf_t *db;
5833 VERIFY(nvlist_size(nv, &nvsize, NV_ENCODE_XDR) == 0);
5836 * Write full (SPA_CONFIG_BLOCKSIZE) blocks of configuration
5837 * information. This avoids the dmu_buf_will_dirty() path and
5838 * saves us a pre-read to get data we don't actually care about.
5840 bufsize = P2ROUNDUP((uint64_t)nvsize, SPA_CONFIG_BLOCKSIZE);
5841 packed = kmem_alloc(bufsize, KM_SLEEP);
5843 VERIFY(nvlist_pack(nv, &packed, &nvsize, NV_ENCODE_XDR,
5844 KM_SLEEP) == 0);
5845 bzero(packed + nvsize, bufsize - nvsize);
5847 dmu_write(spa->spa_meta_objset, obj, 0, bufsize, packed, tx);
5849 kmem_free(packed, bufsize);
5851 VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
5852 dmu_buf_will_dirty(db, tx);
5853 *(uint64_t *)db->db_data = nvsize;
5854 dmu_buf_rele(db, FTAG);
5857 static void
5858 spa_sync_aux_dev(spa_t *spa, spa_aux_vdev_t *sav, dmu_tx_t *tx,
5859 const char *config, const char *entry)
5861 nvlist_t *nvroot;
5862 nvlist_t **list;
5863 int i;
5865 if (!sav->sav_sync)
5866 return;
5869 * Update the MOS nvlist describing the list of available devices.
5870 * spa_validate_aux() will have already made sure this nvlist is
5871 * valid and the vdevs are labeled appropriately.
5873 if (sav->sav_object == 0) {
5874 sav->sav_object = dmu_object_alloc(spa->spa_meta_objset,
5875 DMU_OT_PACKED_NVLIST, 1 << 14, DMU_OT_PACKED_NVLIST_SIZE,
5876 sizeof (uint64_t), tx);
5877 VERIFY(zap_update(spa->spa_meta_objset,
5878 DMU_POOL_DIRECTORY_OBJECT, entry, sizeof (uint64_t), 1,
5879 &sav->sav_object, tx) == 0);
5882 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
5883 if (sav->sav_count == 0) {
5884 VERIFY(nvlist_add_nvlist_array(nvroot, config, NULL, 0) == 0);
5885 } else {
5886 list = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
5887 for (i = 0; i < sav->sav_count; i++)
5888 list[i] = vdev_config_generate(spa, sav->sav_vdevs[i],
5889 B_FALSE, VDEV_CONFIG_L2CACHE);
5890 VERIFY(nvlist_add_nvlist_array(nvroot, config, list,
5891 sav->sav_count) == 0);
5892 for (i = 0; i < sav->sav_count; i++)
5893 nvlist_free(list[i]);
5894 kmem_free(list, sav->sav_count * sizeof (void *));
5897 spa_sync_nvlist(spa, sav->sav_object, nvroot, tx);
5898 nvlist_free(nvroot);
5900 sav->sav_sync = B_FALSE;
5903 static void
5904 spa_sync_config_object(spa_t *spa, dmu_tx_t *tx)
5906 nvlist_t *config;
5908 if (list_is_empty(&spa->spa_config_dirty_list))
5909 return;
5911 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
5913 config = spa_config_generate(spa, spa->spa_root_vdev,
5914 dmu_tx_get_txg(tx), B_FALSE);
5917 * If we're upgrading the spa version then make sure that
5918 * the config object gets updated with the correct version.
5920 if (spa->spa_ubsync.ub_version < spa->spa_uberblock.ub_version)
5921 fnvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
5922 spa->spa_uberblock.ub_version);
5924 spa_config_exit(spa, SCL_STATE, FTAG);
5926 if (spa->spa_config_syncing)
5927 nvlist_free(spa->spa_config_syncing);
5928 spa->spa_config_syncing = config;
5930 spa_sync_nvlist(spa, spa->spa_config_object, config, tx);
5933 static void
5934 spa_sync_version(void *arg, dmu_tx_t *tx)
5936 uint64_t *versionp = arg;
5937 uint64_t version = *versionp;
5938 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
5941 * Setting the version is special cased when first creating the pool.
5943 ASSERT(tx->tx_txg != TXG_INITIAL);
5945 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
5946 ASSERT(version >= spa_version(spa));
5948 spa->spa_uberblock.ub_version = version;
5949 vdev_config_dirty(spa->spa_root_vdev);
5950 spa_history_log_internal(spa, "set", tx, "version=%lld", version);
5954 * Set zpool properties.
5956 static void
5957 spa_sync_props(void *arg, dmu_tx_t *tx)
5959 nvlist_t *nvp = arg;
5960 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
5961 objset_t *mos = spa->spa_meta_objset;
5962 nvpair_t *elem = NULL;
5964 mutex_enter(&spa->spa_props_lock);
5966 while ((elem = nvlist_next_nvpair(nvp, elem))) {
5967 uint64_t intval;
5968 char *strval, *fname;
5969 zpool_prop_t prop;
5970 const char *propname;
5971 zprop_type_t proptype;
5972 spa_feature_t fid;
5974 switch (prop = zpool_name_to_prop(nvpair_name(elem))) {
5975 case ZPROP_INVAL:
5977 * We checked this earlier in spa_prop_validate().
5979 ASSERT(zpool_prop_feature(nvpair_name(elem)));
5981 fname = strchr(nvpair_name(elem), '@') + 1;
5982 VERIFY0(zfeature_lookup_name(fname, &fid));
5984 spa_feature_enable(spa, fid, tx);
5985 spa_history_log_internal(spa, "set", tx,
5986 "%s=enabled", nvpair_name(elem));
5987 break;
5989 case ZPOOL_PROP_VERSION:
5990 intval = fnvpair_value_uint64(elem);
5992 * The version is synced seperatly before other
5993 * properties and should be correct by now.
5995 ASSERT3U(spa_version(spa), >=, intval);
5996 break;
5998 case ZPOOL_PROP_ALTROOT:
6000 * 'altroot' is a non-persistent property. It should
6001 * have been set temporarily at creation or import time.
6003 ASSERT(spa->spa_root != NULL);
6004 break;
6006 case ZPOOL_PROP_READONLY:
6007 case ZPOOL_PROP_CACHEFILE:
6009 * 'readonly' and 'cachefile' are also non-persisitent
6010 * properties.
6012 break;
6013 case ZPOOL_PROP_COMMENT:
6014 strval = fnvpair_value_string(elem);
6015 if (spa->spa_comment != NULL)
6016 spa_strfree(spa->spa_comment);
6017 spa->spa_comment = spa_strdup(strval);
6019 * We need to dirty the configuration on all the vdevs
6020 * so that their labels get updated. It's unnecessary
6021 * to do this for pool creation since the vdev's
6022 * configuratoin has already been dirtied.
6024 if (tx->tx_txg != TXG_INITIAL)
6025 vdev_config_dirty(spa->spa_root_vdev);
6026 spa_history_log_internal(spa, "set", tx,
6027 "%s=%s", nvpair_name(elem), strval);
6028 break;
6029 default:
6031 * Set pool property values in the poolprops mos object.
6033 if (spa->spa_pool_props_object == 0) {
6034 spa->spa_pool_props_object =
6035 zap_create_link(mos, DMU_OT_POOL_PROPS,
6036 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_PROPS,
6037 tx);
6040 /* normalize the property name */
6041 propname = zpool_prop_to_name(prop);
6042 proptype = zpool_prop_get_type(prop);
6044 if (nvpair_type(elem) == DATA_TYPE_STRING) {
6045 ASSERT(proptype == PROP_TYPE_STRING);
6046 strval = fnvpair_value_string(elem);
6047 VERIFY0(zap_update(mos,
6048 spa->spa_pool_props_object, propname,
6049 1, strlen(strval) + 1, strval, tx));
6050 spa_history_log_internal(spa, "set", tx,
6051 "%s=%s", nvpair_name(elem), strval);
6052 } else if (nvpair_type(elem) == DATA_TYPE_UINT64) {
6053 intval = fnvpair_value_uint64(elem);
6055 if (proptype == PROP_TYPE_INDEX) {
6056 const char *unused;
6057 VERIFY0(zpool_prop_index_to_string(
6058 prop, intval, &unused));
6060 VERIFY0(zap_update(mos,
6061 spa->spa_pool_props_object, propname,
6062 8, 1, &intval, tx));
6063 spa_history_log_internal(spa, "set", tx,
6064 "%s=%lld", nvpair_name(elem), intval);
6065 } else {
6066 ASSERT(0); /* not allowed */
6069 switch (prop) {
6070 case ZPOOL_PROP_DELEGATION:
6071 spa->spa_delegation = intval;
6072 break;
6073 case ZPOOL_PROP_BOOTFS:
6074 spa->spa_bootfs = intval;
6075 break;
6076 case ZPOOL_PROP_FAILUREMODE:
6077 spa->spa_failmode = intval;
6078 break;
6079 case ZPOOL_PROP_AUTOEXPAND:
6080 spa->spa_autoexpand = intval;
6081 if (tx->tx_txg != TXG_INITIAL)
6082 spa_async_request(spa,
6083 SPA_ASYNC_AUTOEXPAND);
6084 break;
6085 case ZPOOL_PROP_DEDUPDITTO:
6086 spa->spa_dedup_ditto = intval;
6087 break;
6088 default:
6089 break;
6095 mutex_exit(&spa->spa_props_lock);
6099 * Perform one-time upgrade on-disk changes. spa_version() does not
6100 * reflect the new version this txg, so there must be no changes this
6101 * txg to anything that the upgrade code depends on after it executes.
6102 * Therefore this must be called after dsl_pool_sync() does the sync
6103 * tasks.
6105 static void
6106 spa_sync_upgrades(spa_t *spa, dmu_tx_t *tx)
6108 dsl_pool_t *dp = spa->spa_dsl_pool;
6110 ASSERT(spa->spa_sync_pass == 1);
6112 rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
6114 if (spa->spa_ubsync.ub_version < SPA_VERSION_ORIGIN &&
6115 spa->spa_uberblock.ub_version >= SPA_VERSION_ORIGIN) {
6116 dsl_pool_create_origin(dp, tx);
6118 /* Keeping the origin open increases spa_minref */
6119 spa->spa_minref += 3;
6122 if (spa->spa_ubsync.ub_version < SPA_VERSION_NEXT_CLONES &&
6123 spa->spa_uberblock.ub_version >= SPA_VERSION_NEXT_CLONES) {
6124 dsl_pool_upgrade_clones(dp, tx);
6127 if (spa->spa_ubsync.ub_version < SPA_VERSION_DIR_CLONES &&
6128 spa->spa_uberblock.ub_version >= SPA_VERSION_DIR_CLONES) {
6129 dsl_pool_upgrade_dir_clones(dp, tx);
6131 /* Keeping the freedir open increases spa_minref */
6132 spa->spa_minref += 3;
6135 if (spa->spa_ubsync.ub_version < SPA_VERSION_FEATURES &&
6136 spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
6137 spa_feature_create_zap_objects(spa, tx);
6141 * LZ4_COMPRESS feature's behaviour was changed to activate_on_enable
6142 * when possibility to use lz4 compression for metadata was added
6143 * Old pools that have this feature enabled must be upgraded to have
6144 * this feature active
6146 if (spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
6147 boolean_t lz4_en = spa_feature_is_enabled(spa,
6148 SPA_FEATURE_LZ4_COMPRESS);
6149 boolean_t lz4_ac = spa_feature_is_active(spa,
6150 SPA_FEATURE_LZ4_COMPRESS);
6152 if (lz4_en && !lz4_ac)
6153 spa_feature_incr(spa, SPA_FEATURE_LZ4_COMPRESS, tx);
6155 rrw_exit(&dp->dp_config_rwlock, FTAG);
6159 * Sync the specified transaction group. New blocks may be dirtied as
6160 * part of the process, so we iterate until it converges.
6162 void
6163 spa_sync(spa_t *spa, uint64_t txg)
6165 dsl_pool_t *dp = spa->spa_dsl_pool;
6166 objset_t *mos = spa->spa_meta_objset;
6167 bplist_t *free_bpl = &spa->spa_free_bplist[txg & TXG_MASK];
6168 vdev_t *rvd = spa->spa_root_vdev;
6169 vdev_t *vd;
6170 dmu_tx_t *tx;
6171 int error;
6173 VERIFY(spa_writeable(spa));
6176 * Lock out configuration changes.
6178 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
6180 spa->spa_syncing_txg = txg;
6181 spa->spa_sync_pass = 0;
6184 * If there are any pending vdev state changes, convert them
6185 * into config changes that go out with this transaction group.
6187 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
6188 while (list_head(&spa->spa_state_dirty_list) != NULL) {
6190 * We need the write lock here because, for aux vdevs,
6191 * calling vdev_config_dirty() modifies sav_config.
6192 * This is ugly and will become unnecessary when we
6193 * eliminate the aux vdev wart by integrating all vdevs
6194 * into the root vdev tree.
6196 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6197 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_WRITER);
6198 while ((vd = list_head(&spa->spa_state_dirty_list)) != NULL) {
6199 vdev_state_clean(vd);
6200 vdev_config_dirty(vd);
6202 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6203 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
6205 spa_config_exit(spa, SCL_STATE, FTAG);
6207 tx = dmu_tx_create_assigned(dp, txg);
6209 spa->spa_sync_starttime = gethrtime();
6210 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid,
6211 spa->spa_sync_starttime + spa->spa_deadman_synctime));
6214 * If we are upgrading to SPA_VERSION_RAIDZ_DEFLATE this txg,
6215 * set spa_deflate if we have no raid-z vdevs.
6217 if (spa->spa_ubsync.ub_version < SPA_VERSION_RAIDZ_DEFLATE &&
6218 spa->spa_uberblock.ub_version >= SPA_VERSION_RAIDZ_DEFLATE) {
6219 int i;
6221 for (i = 0; i < rvd->vdev_children; i++) {
6222 vd = rvd->vdev_child[i];
6223 if (vd->vdev_deflate_ratio != SPA_MINBLOCKSIZE)
6224 break;
6226 if (i == rvd->vdev_children) {
6227 spa->spa_deflate = TRUE;
6228 VERIFY(0 == zap_add(spa->spa_meta_objset,
6229 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
6230 sizeof (uint64_t), 1, &spa->spa_deflate, tx));
6235 * If anything has changed in this txg, or if someone is waiting
6236 * for this txg to sync (eg, spa_vdev_remove()), push the
6237 * deferred frees from the previous txg. If not, leave them
6238 * alone so that we don't generate work on an otherwise idle
6239 * system.
6241 if (!txg_list_empty(&dp->dp_dirty_datasets, txg) ||
6242 !txg_list_empty(&dp->dp_dirty_dirs, txg) ||
6243 !txg_list_empty(&dp->dp_sync_tasks, txg) ||
6244 ((dsl_scan_active(dp->dp_scan) ||
6245 txg_sync_waiting(dp)) && !spa_shutting_down(spa))) {
6246 spa_sync_deferred_frees(spa, tx);
6250 * Iterate to convergence.
6252 do {
6253 int pass = ++spa->spa_sync_pass;
6255 spa_sync_config_object(spa, tx);
6256 spa_sync_aux_dev(spa, &spa->spa_spares, tx,
6257 ZPOOL_CONFIG_SPARES, DMU_POOL_SPARES);
6258 spa_sync_aux_dev(spa, &spa->spa_l2cache, tx,
6259 ZPOOL_CONFIG_L2CACHE, DMU_POOL_L2CACHE);
6260 spa_errlog_sync(spa, txg);
6261 dsl_pool_sync(dp, txg);
6263 if (pass < zfs_sync_pass_deferred_free) {
6264 spa_sync_frees(spa, free_bpl, tx);
6265 } else {
6266 bplist_iterate(free_bpl, bpobj_enqueue_cb,
6267 &spa->spa_deferred_bpobj, tx);
6270 ddt_sync(spa, txg);
6271 dsl_scan_sync(dp, tx);
6273 while (vd = txg_list_remove(&spa->spa_vdev_txg_list, txg))
6274 vdev_sync(vd, txg);
6276 if (pass == 1)
6277 spa_sync_upgrades(spa, tx);
6279 } while (dmu_objset_is_dirty(mos, txg));
6282 * Rewrite the vdev configuration (which includes the uberblock)
6283 * to commit the transaction group.
6285 * If there are no dirty vdevs, we sync the uberblock to a few
6286 * random top-level vdevs that are known to be visible in the
6287 * config cache (see spa_vdev_add() for a complete description).
6288 * If there *are* dirty vdevs, sync the uberblock to all vdevs.
6290 for (;;) {
6292 * We hold SCL_STATE to prevent vdev open/close/etc.
6293 * while we're attempting to write the vdev labels.
6295 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
6297 if (list_is_empty(&spa->spa_config_dirty_list)) {
6298 vdev_t *svd[SPA_DVAS_PER_BP];
6299 int svdcount = 0;
6300 int children = rvd->vdev_children;
6301 int c0 = spa_get_random(children);
6303 for (int c = 0; c < children; c++) {
6304 vd = rvd->vdev_child[(c0 + c) % children];
6305 if (vd->vdev_ms_array == 0 || vd->vdev_islog)
6306 continue;
6307 svd[svdcount++] = vd;
6308 if (svdcount == SPA_DVAS_PER_BP)
6309 break;
6311 error = vdev_config_sync(svd, svdcount, txg, B_FALSE);
6312 if (error != 0)
6313 error = vdev_config_sync(svd, svdcount, txg,
6314 B_TRUE);
6315 } else {
6316 error = vdev_config_sync(rvd->vdev_child,
6317 rvd->vdev_children, txg, B_FALSE);
6318 if (error != 0)
6319 error = vdev_config_sync(rvd->vdev_child,
6320 rvd->vdev_children, txg, B_TRUE);
6323 if (error == 0)
6324 spa->spa_last_synced_guid = rvd->vdev_guid;
6326 spa_config_exit(spa, SCL_STATE, FTAG);
6328 if (error == 0)
6329 break;
6330 zio_suspend(spa, NULL);
6331 zio_resume_wait(spa);
6333 dmu_tx_commit(tx);
6335 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid, CY_INFINITY));
6338 * Clear the dirty config list.
6340 while ((vd = list_head(&spa->spa_config_dirty_list)) != NULL)
6341 vdev_config_clean(vd);
6344 * Now that the new config has synced transactionally,
6345 * let it become visible to the config cache.
6347 if (spa->spa_config_syncing != NULL) {
6348 spa_config_set(spa, spa->spa_config_syncing);
6349 spa->spa_config_txg = txg;
6350 spa->spa_config_syncing = NULL;
6353 spa->spa_ubsync = spa->spa_uberblock;
6355 dsl_pool_sync_done(dp, txg);
6358 * Update usable space statistics.
6360 while (vd = txg_list_remove(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)))
6361 vdev_sync_done(vd, txg);
6363 spa_update_dspace(spa);
6366 * It had better be the case that we didn't dirty anything
6367 * since vdev_config_sync().
6369 ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
6370 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
6371 ASSERT(txg_list_empty(&spa->spa_vdev_txg_list, txg));
6373 spa->spa_sync_pass = 0;
6375 spa_config_exit(spa, SCL_CONFIG, FTAG);
6377 spa_handle_ignored_writes(spa);
6380 * If any async tasks have been requested, kick them off.
6382 spa_async_dispatch(spa);
6386 * Sync all pools. We don't want to hold the namespace lock across these
6387 * operations, so we take a reference on the spa_t and drop the lock during the
6388 * sync.
6390 void
6391 spa_sync_allpools(void)
6393 spa_t *spa = NULL;
6394 mutex_enter(&spa_namespace_lock);
6395 while ((spa = spa_next(spa)) != NULL) {
6396 if (spa_state(spa) != POOL_STATE_ACTIVE ||
6397 !spa_writeable(spa) || spa_suspended(spa))
6398 continue;
6399 spa_open_ref(spa, FTAG);
6400 mutex_exit(&spa_namespace_lock);
6401 txg_wait_synced(spa_get_dsl(spa), 0);
6402 mutex_enter(&spa_namespace_lock);
6403 spa_close(spa, FTAG);
6405 mutex_exit(&spa_namespace_lock);
6409 * ==========================================================================
6410 * Miscellaneous routines
6411 * ==========================================================================
6415 * Remove all pools in the system.
6417 void
6418 spa_evict_all(void)
6420 spa_t *spa;
6423 * Remove all cached state. All pools should be closed now,
6424 * so every spa in the AVL tree should be unreferenced.
6426 mutex_enter(&spa_namespace_lock);
6427 while ((spa = spa_next(NULL)) != NULL) {
6429 * Stop async tasks. The async thread may need to detach
6430 * a device that's been replaced, which requires grabbing
6431 * spa_namespace_lock, so we must drop it here.
6433 spa_open_ref(spa, FTAG);
6434 mutex_exit(&spa_namespace_lock);
6435 spa_async_suspend(spa);
6436 mutex_enter(&spa_namespace_lock);
6437 spa_close(spa, FTAG);
6439 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
6440 spa_unload(spa);
6441 spa_deactivate(spa);
6443 spa_remove(spa);
6445 mutex_exit(&spa_namespace_lock);
6448 vdev_t *
6449 spa_lookup_by_guid(spa_t *spa, uint64_t guid, boolean_t aux)
6451 vdev_t *vd;
6452 int i;
6454 if ((vd = vdev_lookup_by_guid(spa->spa_root_vdev, guid)) != NULL)
6455 return (vd);
6457 if (aux) {
6458 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
6459 vd = spa->spa_l2cache.sav_vdevs[i];
6460 if (vd->vdev_guid == guid)
6461 return (vd);
6464 for (i = 0; i < spa->spa_spares.sav_count; i++) {
6465 vd = spa->spa_spares.sav_vdevs[i];
6466 if (vd->vdev_guid == guid)
6467 return (vd);
6471 return (NULL);
6474 void
6475 spa_upgrade(spa_t *spa, uint64_t version)
6477 ASSERT(spa_writeable(spa));
6479 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6482 * This should only be called for a non-faulted pool, and since a
6483 * future version would result in an unopenable pool, this shouldn't be
6484 * possible.
6486 ASSERT(SPA_VERSION_IS_SUPPORTED(spa->spa_uberblock.ub_version));
6487 ASSERT3U(version, >=, spa->spa_uberblock.ub_version);
6489 spa->spa_uberblock.ub_version = version;
6490 vdev_config_dirty(spa->spa_root_vdev);
6492 spa_config_exit(spa, SCL_ALL, FTAG);
6494 txg_wait_synced(spa_get_dsl(spa), 0);
6497 boolean_t
6498 spa_has_spare(spa_t *spa, uint64_t guid)
6500 int i;
6501 uint64_t spareguid;
6502 spa_aux_vdev_t *sav = &spa->spa_spares;
6504 for (i = 0; i < sav->sav_count; i++)
6505 if (sav->sav_vdevs[i]->vdev_guid == guid)
6506 return (B_TRUE);
6508 for (i = 0; i < sav->sav_npending; i++) {
6509 if (nvlist_lookup_uint64(sav->sav_pending[i], ZPOOL_CONFIG_GUID,
6510 &spareguid) == 0 && spareguid == guid)
6511 return (B_TRUE);
6514 return (B_FALSE);
6518 * Check if a pool has an active shared spare device.
6519 * Note: reference count of an active spare is 2, as a spare and as a replace
6521 static boolean_t
6522 spa_has_active_shared_spare(spa_t *spa)
6524 int i, refcnt;
6525 uint64_t pool;
6526 spa_aux_vdev_t *sav = &spa->spa_spares;
6528 for (i = 0; i < sav->sav_count; i++) {
6529 if (spa_spare_exists(sav->sav_vdevs[i]->vdev_guid, &pool,
6530 &refcnt) && pool != 0ULL && pool == spa_guid(spa) &&
6531 refcnt > 2)
6532 return (B_TRUE);
6535 return (B_FALSE);
6539 * Post a sysevent corresponding to the given event. The 'name' must be one of
6540 * the event definitions in sys/sysevent/eventdefs.h. The payload will be
6541 * filled in from the spa and (optionally) the vdev. This doesn't do anything
6542 * in the userland libzpool, as we don't want consumers to misinterpret ztest
6543 * or zdb as real changes.
6545 void
6546 spa_event_notify(spa_t *spa, vdev_t *vd, const char *name)
6548 #ifdef _KERNEL
6549 sysevent_t *ev;
6550 sysevent_attr_list_t *attr = NULL;
6551 sysevent_value_t value;
6552 sysevent_id_t eid;
6554 ev = sysevent_alloc(EC_ZFS, (char *)name, SUNW_KERN_PUB "zfs",
6555 SE_SLEEP);
6557 value.value_type = SE_DATA_TYPE_STRING;
6558 value.value.sv_string = spa_name(spa);
6559 if (sysevent_add_attr(&attr, ZFS_EV_POOL_NAME, &value, SE_SLEEP) != 0)
6560 goto done;
6562 value.value_type = SE_DATA_TYPE_UINT64;
6563 value.value.sv_uint64 = spa_guid(spa);
6564 if (sysevent_add_attr(&attr, ZFS_EV_POOL_GUID, &value, SE_SLEEP) != 0)
6565 goto done;
6567 if (vd) {
6568 value.value_type = SE_DATA_TYPE_UINT64;
6569 value.value.sv_uint64 = vd->vdev_guid;
6570 if (sysevent_add_attr(&attr, ZFS_EV_VDEV_GUID, &value,
6571 SE_SLEEP) != 0)
6572 goto done;
6574 if (vd->vdev_path) {
6575 value.value_type = SE_DATA_TYPE_STRING;
6576 value.value.sv_string = vd->vdev_path;
6577 if (sysevent_add_attr(&attr, ZFS_EV_VDEV_PATH,
6578 &value, SE_SLEEP) != 0)
6579 goto done;
6583 if (sysevent_attach_attributes(ev, attr) != 0)
6584 goto done;
6585 attr = NULL;
6587 (void) log_sysevent(ev, SE_SLEEP, &eid);
6589 done:
6590 if (attr)
6591 sysevent_free_attr(attr);
6592 sysevent_free(ev);
6593 #endif