3498 panic in arc_read(): !refcount_is_zero(&pbuf->b_hdr->b_refcnt)
[unleashed.git] / usr / src / uts / common / fs / zfs / spa.c
blob333bbeea9303ccdb07be7040f8ce8c57fa4672d4
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 2011 Nexenta Systems, Inc. All rights reserved.
25 * Copyright (c) 2012 by Delphix. All rights reserved.
29 * This file contains all the routines used when modifying on-disk SPA state.
30 * This includes opening, importing, destroying, exporting a pool, and syncing a
31 * pool.
34 #include <sys/zfs_context.h>
35 #include <sys/fm/fs/zfs.h>
36 #include <sys/spa_impl.h>
37 #include <sys/zio.h>
38 #include <sys/zio_checksum.h>
39 #include <sys/dmu.h>
40 #include <sys/dmu_tx.h>
41 #include <sys/zap.h>
42 #include <sys/zil.h>
43 #include <sys/ddt.h>
44 #include <sys/vdev_impl.h>
45 #include <sys/metaslab.h>
46 #include <sys/metaslab_impl.h>
47 #include <sys/uberblock_impl.h>
48 #include <sys/txg.h>
49 #include <sys/avl.h>
50 #include <sys/dmu_traverse.h>
51 #include <sys/dmu_objset.h>
52 #include <sys/unique.h>
53 #include <sys/dsl_pool.h>
54 #include <sys/dsl_dataset.h>
55 #include <sys/dsl_dir.h>
56 #include <sys/dsl_prop.h>
57 #include <sys/dsl_synctask.h>
58 #include <sys/fs/zfs.h>
59 #include <sys/arc.h>
60 #include <sys/callb.h>
61 #include <sys/systeminfo.h>
62 #include <sys/spa_boot.h>
63 #include <sys/zfs_ioctl.h>
64 #include <sys/dsl_scan.h>
65 #include <sys/zfeature.h>
67 #ifdef _KERNEL
68 #include <sys/bootprops.h>
69 #include <sys/callb.h>
70 #include <sys/cpupart.h>
71 #include <sys/pool.h>
72 #include <sys/sysdc.h>
73 #include <sys/zone.h>
74 #endif /* _KERNEL */
76 #include "zfs_prop.h"
77 #include "zfs_comutil.h"
79 typedef enum zti_modes {
80 zti_mode_fixed, /* value is # of threads (min 1) */
81 zti_mode_online_percent, /* value is % of online CPUs */
82 zti_mode_batch, /* cpu-intensive; value is ignored */
83 zti_mode_null, /* don't create a taskq */
84 zti_nmodes
85 } zti_modes_t;
87 #define ZTI_FIX(n) { zti_mode_fixed, (n) }
88 #define ZTI_PCT(n) { zti_mode_online_percent, (n) }
89 #define ZTI_BATCH { zti_mode_batch, 0 }
90 #define ZTI_NULL { zti_mode_null, 0 }
92 #define ZTI_ONE ZTI_FIX(1)
94 typedef struct zio_taskq_info {
95 enum zti_modes zti_mode;
96 uint_t zti_value;
97 } zio_taskq_info_t;
99 static const char *const zio_taskq_types[ZIO_TASKQ_TYPES] = {
100 "issue", "issue_high", "intr", "intr_high"
104 * Define the taskq threads for the following I/O types:
105 * NULL, READ, WRITE, FREE, CLAIM, and IOCTL
107 const zio_taskq_info_t zio_taskqs[ZIO_TYPES][ZIO_TASKQ_TYPES] = {
108 /* ISSUE ISSUE_HIGH INTR INTR_HIGH */
109 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL },
110 { ZTI_FIX(8), ZTI_NULL, ZTI_BATCH, ZTI_NULL },
111 { ZTI_BATCH, ZTI_FIX(5), ZTI_FIX(8), ZTI_FIX(5) },
112 { ZTI_FIX(100), ZTI_NULL, ZTI_ONE, ZTI_NULL },
113 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL },
114 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL },
117 static dsl_syncfunc_t spa_sync_version;
118 static dsl_syncfunc_t spa_sync_props;
119 static dsl_checkfunc_t spa_change_guid_check;
120 static dsl_syncfunc_t spa_change_guid_sync;
121 static boolean_t spa_has_active_shared_spare(spa_t *spa);
122 static int spa_load_impl(spa_t *spa, uint64_t, nvlist_t *config,
123 spa_load_state_t state, spa_import_type_t type, boolean_t mosconfig,
124 char **ereport);
125 static void spa_vdev_resilver_done(spa_t *spa);
127 uint_t zio_taskq_batch_pct = 100; /* 1 thread per cpu in pset */
128 id_t zio_taskq_psrset_bind = PS_NONE;
129 boolean_t zio_taskq_sysdc = B_TRUE; /* use SDC scheduling class */
130 uint_t zio_taskq_basedc = 80; /* base duty cycle */
132 boolean_t spa_create_process = B_TRUE; /* no process ==> no sysdc */
133 extern int zfs_sync_pass_deferred_free;
136 * This (illegal) pool name is used when temporarily importing a spa_t in order
137 * to get the vdev stats associated with the imported devices.
139 #define TRYIMPORT_NAME "$import"
142 * ==========================================================================
143 * SPA properties routines
144 * ==========================================================================
148 * Add a (source=src, propname=propval) list to an nvlist.
150 static void
151 spa_prop_add_list(nvlist_t *nvl, zpool_prop_t prop, char *strval,
152 uint64_t intval, zprop_source_t src)
154 const char *propname = zpool_prop_to_name(prop);
155 nvlist_t *propval;
157 VERIFY(nvlist_alloc(&propval, NV_UNIQUE_NAME, KM_SLEEP) == 0);
158 VERIFY(nvlist_add_uint64(propval, ZPROP_SOURCE, src) == 0);
160 if (strval != NULL)
161 VERIFY(nvlist_add_string(propval, ZPROP_VALUE, strval) == 0);
162 else
163 VERIFY(nvlist_add_uint64(propval, ZPROP_VALUE, intval) == 0);
165 VERIFY(nvlist_add_nvlist(nvl, propname, propval) == 0);
166 nvlist_free(propval);
170 * Get property values from the spa configuration.
172 static void
173 spa_prop_get_config(spa_t *spa, nvlist_t **nvp)
175 vdev_t *rvd = spa->spa_root_vdev;
176 dsl_pool_t *pool = spa->spa_dsl_pool;
177 uint64_t size;
178 uint64_t alloc;
179 uint64_t space;
180 uint64_t cap, version;
181 zprop_source_t src = ZPROP_SRC_NONE;
182 spa_config_dirent_t *dp;
184 ASSERT(MUTEX_HELD(&spa->spa_props_lock));
186 if (rvd != NULL) {
187 alloc = metaslab_class_get_alloc(spa_normal_class(spa));
188 size = metaslab_class_get_space(spa_normal_class(spa));
189 spa_prop_add_list(*nvp, ZPOOL_PROP_NAME, spa_name(spa), 0, src);
190 spa_prop_add_list(*nvp, ZPOOL_PROP_SIZE, NULL, size, src);
191 spa_prop_add_list(*nvp, ZPOOL_PROP_ALLOCATED, NULL, alloc, src);
192 spa_prop_add_list(*nvp, ZPOOL_PROP_FREE, NULL,
193 size - alloc, src);
195 space = 0;
196 for (int c = 0; c < rvd->vdev_children; c++) {
197 vdev_t *tvd = rvd->vdev_child[c];
198 space += tvd->vdev_max_asize - tvd->vdev_asize;
200 spa_prop_add_list(*nvp, ZPOOL_PROP_EXPANDSZ, NULL, space,
201 src);
203 spa_prop_add_list(*nvp, ZPOOL_PROP_READONLY, NULL,
204 (spa_mode(spa) == FREAD), src);
206 cap = (size == 0) ? 0 : (alloc * 100 / size);
207 spa_prop_add_list(*nvp, ZPOOL_PROP_CAPACITY, NULL, cap, src);
209 spa_prop_add_list(*nvp, ZPOOL_PROP_DEDUPRATIO, NULL,
210 ddt_get_pool_dedup_ratio(spa), src);
212 spa_prop_add_list(*nvp, ZPOOL_PROP_HEALTH, NULL,
213 rvd->vdev_state, src);
215 version = spa_version(spa);
216 if (version == zpool_prop_default_numeric(ZPOOL_PROP_VERSION))
217 src = ZPROP_SRC_DEFAULT;
218 else
219 src = ZPROP_SRC_LOCAL;
220 spa_prop_add_list(*nvp, ZPOOL_PROP_VERSION, NULL, version, src);
223 if (pool != NULL) {
224 dsl_dir_t *freedir = pool->dp_free_dir;
227 * The $FREE directory was introduced in SPA_VERSION_DEADLISTS,
228 * when opening pools before this version freedir will be NULL.
230 if (freedir != NULL) {
231 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING, NULL,
232 freedir->dd_phys->dd_used_bytes, src);
233 } else {
234 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING,
235 NULL, 0, src);
239 spa_prop_add_list(*nvp, ZPOOL_PROP_GUID, NULL, spa_guid(spa), src);
241 if (spa->spa_comment != NULL) {
242 spa_prop_add_list(*nvp, ZPOOL_PROP_COMMENT, spa->spa_comment,
243 0, ZPROP_SRC_LOCAL);
246 if (spa->spa_root != NULL)
247 spa_prop_add_list(*nvp, ZPOOL_PROP_ALTROOT, spa->spa_root,
248 0, ZPROP_SRC_LOCAL);
250 if ((dp = list_head(&spa->spa_config_list)) != NULL) {
251 if (dp->scd_path == NULL) {
252 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
253 "none", 0, ZPROP_SRC_LOCAL);
254 } else if (strcmp(dp->scd_path, spa_config_path) != 0) {
255 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
256 dp->scd_path, 0, ZPROP_SRC_LOCAL);
262 * Get zpool property values.
265 spa_prop_get(spa_t *spa, nvlist_t **nvp)
267 objset_t *mos = spa->spa_meta_objset;
268 zap_cursor_t zc;
269 zap_attribute_t za;
270 int err;
272 VERIFY(nvlist_alloc(nvp, NV_UNIQUE_NAME, KM_SLEEP) == 0);
274 mutex_enter(&spa->spa_props_lock);
277 * Get properties from the spa config.
279 spa_prop_get_config(spa, nvp);
281 /* If no pool property object, no more prop to get. */
282 if (mos == NULL || spa->spa_pool_props_object == 0) {
283 mutex_exit(&spa->spa_props_lock);
284 return (0);
288 * Get properties from the MOS pool property object.
290 for (zap_cursor_init(&zc, mos, spa->spa_pool_props_object);
291 (err = zap_cursor_retrieve(&zc, &za)) == 0;
292 zap_cursor_advance(&zc)) {
293 uint64_t intval = 0;
294 char *strval = NULL;
295 zprop_source_t src = ZPROP_SRC_DEFAULT;
296 zpool_prop_t prop;
298 if ((prop = zpool_name_to_prop(za.za_name)) == ZPROP_INVAL)
299 continue;
301 switch (za.za_integer_length) {
302 case 8:
303 /* integer property */
304 if (za.za_first_integer !=
305 zpool_prop_default_numeric(prop))
306 src = ZPROP_SRC_LOCAL;
308 if (prop == ZPOOL_PROP_BOOTFS) {
309 dsl_pool_t *dp;
310 dsl_dataset_t *ds = NULL;
312 dp = spa_get_dsl(spa);
313 rw_enter(&dp->dp_config_rwlock, RW_READER);
314 if (err = dsl_dataset_hold_obj(dp,
315 za.za_first_integer, FTAG, &ds)) {
316 rw_exit(&dp->dp_config_rwlock);
317 break;
320 strval = kmem_alloc(
321 MAXNAMELEN + strlen(MOS_DIR_NAME) + 1,
322 KM_SLEEP);
323 dsl_dataset_name(ds, strval);
324 dsl_dataset_rele(ds, FTAG);
325 rw_exit(&dp->dp_config_rwlock);
326 } else {
327 strval = NULL;
328 intval = za.za_first_integer;
331 spa_prop_add_list(*nvp, prop, strval, intval, src);
333 if (strval != NULL)
334 kmem_free(strval,
335 MAXNAMELEN + strlen(MOS_DIR_NAME) + 1);
337 break;
339 case 1:
340 /* string property */
341 strval = kmem_alloc(za.za_num_integers, KM_SLEEP);
342 err = zap_lookup(mos, spa->spa_pool_props_object,
343 za.za_name, 1, za.za_num_integers, strval);
344 if (err) {
345 kmem_free(strval, za.za_num_integers);
346 break;
348 spa_prop_add_list(*nvp, prop, strval, 0, src);
349 kmem_free(strval, za.za_num_integers);
350 break;
352 default:
353 break;
356 zap_cursor_fini(&zc);
357 mutex_exit(&spa->spa_props_lock);
358 out:
359 if (err && err != ENOENT) {
360 nvlist_free(*nvp);
361 *nvp = NULL;
362 return (err);
365 return (0);
369 * Validate the given pool properties nvlist and modify the list
370 * for the property values to be set.
372 static int
373 spa_prop_validate(spa_t *spa, nvlist_t *props)
375 nvpair_t *elem;
376 int error = 0, reset_bootfs = 0;
377 uint64_t objnum;
378 boolean_t has_feature = B_FALSE;
380 elem = NULL;
381 while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
382 uint64_t intval;
383 char *strval, *slash, *check, *fname;
384 const char *propname = nvpair_name(elem);
385 zpool_prop_t prop = zpool_name_to_prop(propname);
387 switch (prop) {
388 case ZPROP_INVAL:
389 if (!zpool_prop_feature(propname)) {
390 error = EINVAL;
391 break;
395 * Sanitize the input.
397 if (nvpair_type(elem) != DATA_TYPE_UINT64) {
398 error = EINVAL;
399 break;
402 if (nvpair_value_uint64(elem, &intval) != 0) {
403 error = EINVAL;
404 break;
407 if (intval != 0) {
408 error = EINVAL;
409 break;
412 fname = strchr(propname, '@') + 1;
413 if (zfeature_lookup_name(fname, NULL) != 0) {
414 error = EINVAL;
415 break;
418 has_feature = B_TRUE;
419 break;
421 case ZPOOL_PROP_VERSION:
422 error = nvpair_value_uint64(elem, &intval);
423 if (!error &&
424 (intval < spa_version(spa) ||
425 intval > SPA_VERSION_BEFORE_FEATURES ||
426 has_feature))
427 error = EINVAL;
428 break;
430 case ZPOOL_PROP_DELEGATION:
431 case ZPOOL_PROP_AUTOREPLACE:
432 case ZPOOL_PROP_LISTSNAPS:
433 case ZPOOL_PROP_AUTOEXPAND:
434 error = nvpair_value_uint64(elem, &intval);
435 if (!error && intval > 1)
436 error = EINVAL;
437 break;
439 case ZPOOL_PROP_BOOTFS:
441 * If the pool version is less than SPA_VERSION_BOOTFS,
442 * or the pool is still being created (version == 0),
443 * the bootfs property cannot be set.
445 if (spa_version(spa) < SPA_VERSION_BOOTFS) {
446 error = ENOTSUP;
447 break;
451 * Make sure the vdev config is bootable
453 if (!vdev_is_bootable(spa->spa_root_vdev)) {
454 error = ENOTSUP;
455 break;
458 reset_bootfs = 1;
460 error = nvpair_value_string(elem, &strval);
462 if (!error) {
463 objset_t *os;
464 uint64_t compress;
466 if (strval == NULL || strval[0] == '\0') {
467 objnum = zpool_prop_default_numeric(
468 ZPOOL_PROP_BOOTFS);
469 break;
472 if (error = dmu_objset_hold(strval, FTAG, &os))
473 break;
475 /* Must be ZPL and not gzip compressed. */
477 if (dmu_objset_type(os) != DMU_OST_ZFS) {
478 error = ENOTSUP;
479 } else if ((error = dsl_prop_get_integer(strval,
480 zfs_prop_to_name(ZFS_PROP_COMPRESSION),
481 &compress, NULL)) == 0 &&
482 !BOOTFS_COMPRESS_VALID(compress)) {
483 error = ENOTSUP;
484 } else {
485 objnum = dmu_objset_id(os);
487 dmu_objset_rele(os, FTAG);
489 break;
491 case ZPOOL_PROP_FAILUREMODE:
492 error = nvpair_value_uint64(elem, &intval);
493 if (!error && (intval < ZIO_FAILURE_MODE_WAIT ||
494 intval > ZIO_FAILURE_MODE_PANIC))
495 error = EINVAL;
498 * This is a special case which only occurs when
499 * the pool has completely failed. This allows
500 * the user to change the in-core failmode property
501 * without syncing it out to disk (I/Os might
502 * currently be blocked). We do this by returning
503 * EIO to the caller (spa_prop_set) to trick it
504 * into thinking we encountered a property validation
505 * error.
507 if (!error && spa_suspended(spa)) {
508 spa->spa_failmode = intval;
509 error = EIO;
511 break;
513 case ZPOOL_PROP_CACHEFILE:
514 if ((error = nvpair_value_string(elem, &strval)) != 0)
515 break;
517 if (strval[0] == '\0')
518 break;
520 if (strcmp(strval, "none") == 0)
521 break;
523 if (strval[0] != '/') {
524 error = EINVAL;
525 break;
528 slash = strrchr(strval, '/');
529 ASSERT(slash != NULL);
531 if (slash[1] == '\0' || strcmp(slash, "/.") == 0 ||
532 strcmp(slash, "/..") == 0)
533 error = EINVAL;
534 break;
536 case ZPOOL_PROP_COMMENT:
537 if ((error = nvpair_value_string(elem, &strval)) != 0)
538 break;
539 for (check = strval; *check != '\0'; check++) {
541 * The kernel doesn't have an easy isprint()
542 * check. For this kernel check, we merely
543 * check ASCII apart from DEL. Fix this if
544 * there is an easy-to-use kernel isprint().
546 if (*check >= 0x7f) {
547 error = EINVAL;
548 break;
550 check++;
552 if (strlen(strval) > ZPROP_MAX_COMMENT)
553 error = E2BIG;
554 break;
556 case ZPOOL_PROP_DEDUPDITTO:
557 if (spa_version(spa) < SPA_VERSION_DEDUP)
558 error = ENOTSUP;
559 else
560 error = nvpair_value_uint64(elem, &intval);
561 if (error == 0 &&
562 intval != 0 && intval < ZIO_DEDUPDITTO_MIN)
563 error = EINVAL;
564 break;
567 if (error)
568 break;
571 if (!error && reset_bootfs) {
572 error = nvlist_remove(props,
573 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), DATA_TYPE_STRING);
575 if (!error) {
576 error = nvlist_add_uint64(props,
577 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), objnum);
581 return (error);
584 void
585 spa_configfile_set(spa_t *spa, nvlist_t *nvp, boolean_t need_sync)
587 char *cachefile;
588 spa_config_dirent_t *dp;
590 if (nvlist_lookup_string(nvp, zpool_prop_to_name(ZPOOL_PROP_CACHEFILE),
591 &cachefile) != 0)
592 return;
594 dp = kmem_alloc(sizeof (spa_config_dirent_t),
595 KM_SLEEP);
597 if (cachefile[0] == '\0')
598 dp->scd_path = spa_strdup(spa_config_path);
599 else if (strcmp(cachefile, "none") == 0)
600 dp->scd_path = NULL;
601 else
602 dp->scd_path = spa_strdup(cachefile);
604 list_insert_head(&spa->spa_config_list, dp);
605 if (need_sync)
606 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
610 spa_prop_set(spa_t *spa, nvlist_t *nvp)
612 int error;
613 nvpair_t *elem = NULL;
614 boolean_t need_sync = B_FALSE;
616 if ((error = spa_prop_validate(spa, nvp)) != 0)
617 return (error);
619 while ((elem = nvlist_next_nvpair(nvp, elem)) != NULL) {
620 zpool_prop_t prop = zpool_name_to_prop(nvpair_name(elem));
622 if (prop == ZPOOL_PROP_CACHEFILE ||
623 prop == ZPOOL_PROP_ALTROOT ||
624 prop == ZPOOL_PROP_READONLY)
625 continue;
627 if (prop == ZPOOL_PROP_VERSION || prop == ZPROP_INVAL) {
628 uint64_t ver;
630 if (prop == ZPOOL_PROP_VERSION) {
631 VERIFY(nvpair_value_uint64(elem, &ver) == 0);
632 } else {
633 ASSERT(zpool_prop_feature(nvpair_name(elem)));
634 ver = SPA_VERSION_FEATURES;
635 need_sync = B_TRUE;
638 /* Save time if the version is already set. */
639 if (ver == spa_version(spa))
640 continue;
643 * In addition to the pool directory object, we might
644 * create the pool properties object, the features for
645 * read object, the features for write object, or the
646 * feature descriptions object.
648 error = dsl_sync_task_do(spa_get_dsl(spa), NULL,
649 spa_sync_version, spa, &ver, 6);
650 if (error)
651 return (error);
652 continue;
655 need_sync = B_TRUE;
656 break;
659 if (need_sync) {
660 return (dsl_sync_task_do(spa_get_dsl(spa), NULL, spa_sync_props,
661 spa, nvp, 6));
664 return (0);
668 * If the bootfs property value is dsobj, clear it.
670 void
671 spa_prop_clear_bootfs(spa_t *spa, uint64_t dsobj, dmu_tx_t *tx)
673 if (spa->spa_bootfs == dsobj && spa->spa_pool_props_object != 0) {
674 VERIFY(zap_remove(spa->spa_meta_objset,
675 spa->spa_pool_props_object,
676 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), tx) == 0);
677 spa->spa_bootfs = 0;
681 /*ARGSUSED*/
682 static int
683 spa_change_guid_check(void *arg1, void *arg2, dmu_tx_t *tx)
685 spa_t *spa = arg1;
686 uint64_t *newguid = arg2;
687 vdev_t *rvd = spa->spa_root_vdev;
688 uint64_t vdev_state;
690 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
691 vdev_state = rvd->vdev_state;
692 spa_config_exit(spa, SCL_STATE, FTAG);
694 if (vdev_state != VDEV_STATE_HEALTHY)
695 return (ENXIO);
697 ASSERT3U(spa_guid(spa), !=, *newguid);
699 return (0);
702 static void
703 spa_change_guid_sync(void *arg1, void *arg2, dmu_tx_t *tx)
705 spa_t *spa = arg1;
706 uint64_t *newguid = arg2;
707 uint64_t oldguid;
708 vdev_t *rvd = spa->spa_root_vdev;
710 oldguid = spa_guid(spa);
712 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
713 rvd->vdev_guid = *newguid;
714 rvd->vdev_guid_sum += (*newguid - oldguid);
715 vdev_config_dirty(rvd);
716 spa_config_exit(spa, SCL_STATE, FTAG);
718 spa_history_log_internal(spa, "guid change", tx, "old=%lld new=%lld",
719 oldguid, *newguid);
723 * Change the GUID for the pool. This is done so that we can later
724 * re-import a pool built from a clone of our own vdevs. We will modify
725 * the root vdev's guid, our own pool guid, and then mark all of our
726 * vdevs dirty. Note that we must make sure that all our vdevs are
727 * online when we do this, or else any vdevs that weren't present
728 * would be orphaned from our pool. We are also going to issue a
729 * sysevent to update any watchers.
732 spa_change_guid(spa_t *spa)
734 int error;
735 uint64_t guid;
737 mutex_enter(&spa_namespace_lock);
738 guid = spa_generate_guid(NULL);
740 error = dsl_sync_task_do(spa_get_dsl(spa), spa_change_guid_check,
741 spa_change_guid_sync, spa, &guid, 5);
743 if (error == 0) {
744 spa_config_sync(spa, B_FALSE, B_TRUE);
745 spa_event_notify(spa, NULL, ESC_ZFS_POOL_REGUID);
748 mutex_exit(&spa_namespace_lock);
750 return (error);
754 * ==========================================================================
755 * SPA state manipulation (open/create/destroy/import/export)
756 * ==========================================================================
759 static int
760 spa_error_entry_compare(const void *a, const void *b)
762 spa_error_entry_t *sa = (spa_error_entry_t *)a;
763 spa_error_entry_t *sb = (spa_error_entry_t *)b;
764 int ret;
766 ret = bcmp(&sa->se_bookmark, &sb->se_bookmark,
767 sizeof (zbookmark_t));
769 if (ret < 0)
770 return (-1);
771 else if (ret > 0)
772 return (1);
773 else
774 return (0);
778 * Utility function which retrieves copies of the current logs and
779 * re-initializes them in the process.
781 void
782 spa_get_errlists(spa_t *spa, avl_tree_t *last, avl_tree_t *scrub)
784 ASSERT(MUTEX_HELD(&spa->spa_errlist_lock));
786 bcopy(&spa->spa_errlist_last, last, sizeof (avl_tree_t));
787 bcopy(&spa->spa_errlist_scrub, scrub, sizeof (avl_tree_t));
789 avl_create(&spa->spa_errlist_scrub,
790 spa_error_entry_compare, sizeof (spa_error_entry_t),
791 offsetof(spa_error_entry_t, se_avl));
792 avl_create(&spa->spa_errlist_last,
793 spa_error_entry_compare, sizeof (spa_error_entry_t),
794 offsetof(spa_error_entry_t, se_avl));
797 static taskq_t *
798 spa_taskq_create(spa_t *spa, const char *name, enum zti_modes mode,
799 uint_t value)
801 uint_t flags = 0;
802 boolean_t batch = B_FALSE;
804 switch (mode) {
805 case zti_mode_null:
806 return (NULL); /* no taskq needed */
808 case zti_mode_fixed:
809 ASSERT3U(value, >=, 1);
810 value = MAX(value, 1);
811 break;
813 case zti_mode_batch:
814 batch = B_TRUE;
815 flags |= TASKQ_THREADS_CPU_PCT;
816 value = zio_taskq_batch_pct;
817 break;
819 case zti_mode_online_percent:
820 flags |= TASKQ_THREADS_CPU_PCT;
821 break;
823 default:
824 panic("unrecognized mode for %s taskq (%u:%u) in "
825 "spa_activate()",
826 name, mode, value);
827 break;
830 if (zio_taskq_sysdc && spa->spa_proc != &p0) {
831 if (batch)
832 flags |= TASKQ_DC_BATCH;
834 return (taskq_create_sysdc(name, value, 50, INT_MAX,
835 spa->spa_proc, zio_taskq_basedc, flags));
837 return (taskq_create_proc(name, value, maxclsyspri, 50, INT_MAX,
838 spa->spa_proc, flags));
841 static void
842 spa_create_zio_taskqs(spa_t *spa)
844 for (int t = 0; t < ZIO_TYPES; t++) {
845 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
846 const zio_taskq_info_t *ztip = &zio_taskqs[t][q];
847 enum zti_modes mode = ztip->zti_mode;
848 uint_t value = ztip->zti_value;
849 char name[32];
851 (void) snprintf(name, sizeof (name),
852 "%s_%s", zio_type_name[t], zio_taskq_types[q]);
854 spa->spa_zio_taskq[t][q] =
855 spa_taskq_create(spa, name, mode, value);
860 #ifdef _KERNEL
861 static void
862 spa_thread(void *arg)
864 callb_cpr_t cprinfo;
866 spa_t *spa = arg;
867 user_t *pu = PTOU(curproc);
869 CALLB_CPR_INIT(&cprinfo, &spa->spa_proc_lock, callb_generic_cpr,
870 spa->spa_name);
872 ASSERT(curproc != &p0);
873 (void) snprintf(pu->u_psargs, sizeof (pu->u_psargs),
874 "zpool-%s", spa->spa_name);
875 (void) strlcpy(pu->u_comm, pu->u_psargs, sizeof (pu->u_comm));
877 /* bind this thread to the requested psrset */
878 if (zio_taskq_psrset_bind != PS_NONE) {
879 pool_lock();
880 mutex_enter(&cpu_lock);
881 mutex_enter(&pidlock);
882 mutex_enter(&curproc->p_lock);
884 if (cpupart_bind_thread(curthread, zio_taskq_psrset_bind,
885 0, NULL, NULL) == 0) {
886 curthread->t_bind_pset = zio_taskq_psrset_bind;
887 } else {
888 cmn_err(CE_WARN,
889 "Couldn't bind process for zfs pool \"%s\" to "
890 "pset %d\n", spa->spa_name, zio_taskq_psrset_bind);
893 mutex_exit(&curproc->p_lock);
894 mutex_exit(&pidlock);
895 mutex_exit(&cpu_lock);
896 pool_unlock();
899 if (zio_taskq_sysdc) {
900 sysdc_thread_enter(curthread, 100, 0);
903 spa->spa_proc = curproc;
904 spa->spa_did = curthread->t_did;
906 spa_create_zio_taskqs(spa);
908 mutex_enter(&spa->spa_proc_lock);
909 ASSERT(spa->spa_proc_state == SPA_PROC_CREATED);
911 spa->spa_proc_state = SPA_PROC_ACTIVE;
912 cv_broadcast(&spa->spa_proc_cv);
914 CALLB_CPR_SAFE_BEGIN(&cprinfo);
915 while (spa->spa_proc_state == SPA_PROC_ACTIVE)
916 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
917 CALLB_CPR_SAFE_END(&cprinfo, &spa->spa_proc_lock);
919 ASSERT(spa->spa_proc_state == SPA_PROC_DEACTIVATE);
920 spa->spa_proc_state = SPA_PROC_GONE;
921 spa->spa_proc = &p0;
922 cv_broadcast(&spa->spa_proc_cv);
923 CALLB_CPR_EXIT(&cprinfo); /* drops spa_proc_lock */
925 mutex_enter(&curproc->p_lock);
926 lwp_exit();
928 #endif
931 * Activate an uninitialized pool.
933 static void
934 spa_activate(spa_t *spa, int mode)
936 ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
938 spa->spa_state = POOL_STATE_ACTIVE;
939 spa->spa_mode = mode;
941 spa->spa_normal_class = metaslab_class_create(spa, zfs_metaslab_ops);
942 spa->spa_log_class = metaslab_class_create(spa, zfs_metaslab_ops);
944 /* Try to create a covering process */
945 mutex_enter(&spa->spa_proc_lock);
946 ASSERT(spa->spa_proc_state == SPA_PROC_NONE);
947 ASSERT(spa->spa_proc == &p0);
948 spa->spa_did = 0;
950 /* Only create a process if we're going to be around a while. */
951 if (spa_create_process && strcmp(spa->spa_name, TRYIMPORT_NAME) != 0) {
952 if (newproc(spa_thread, (caddr_t)spa, syscid, maxclsyspri,
953 NULL, 0) == 0) {
954 spa->spa_proc_state = SPA_PROC_CREATED;
955 while (spa->spa_proc_state == SPA_PROC_CREATED) {
956 cv_wait(&spa->spa_proc_cv,
957 &spa->spa_proc_lock);
959 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
960 ASSERT(spa->spa_proc != &p0);
961 ASSERT(spa->spa_did != 0);
962 } else {
963 #ifdef _KERNEL
964 cmn_err(CE_WARN,
965 "Couldn't create process for zfs pool \"%s\"\n",
966 spa->spa_name);
967 #endif
970 mutex_exit(&spa->spa_proc_lock);
972 /* If we didn't create a process, we need to create our taskqs. */
973 if (spa->spa_proc == &p0) {
974 spa_create_zio_taskqs(spa);
977 list_create(&spa->spa_config_dirty_list, sizeof (vdev_t),
978 offsetof(vdev_t, vdev_config_dirty_node));
979 list_create(&spa->spa_state_dirty_list, sizeof (vdev_t),
980 offsetof(vdev_t, vdev_state_dirty_node));
982 txg_list_create(&spa->spa_vdev_txg_list,
983 offsetof(struct vdev, vdev_txg_node));
985 avl_create(&spa->spa_errlist_scrub,
986 spa_error_entry_compare, sizeof (spa_error_entry_t),
987 offsetof(spa_error_entry_t, se_avl));
988 avl_create(&spa->spa_errlist_last,
989 spa_error_entry_compare, sizeof (spa_error_entry_t),
990 offsetof(spa_error_entry_t, se_avl));
994 * Opposite of spa_activate().
996 static void
997 spa_deactivate(spa_t *spa)
999 ASSERT(spa->spa_sync_on == B_FALSE);
1000 ASSERT(spa->spa_dsl_pool == NULL);
1001 ASSERT(spa->spa_root_vdev == NULL);
1002 ASSERT(spa->spa_async_zio_root == NULL);
1003 ASSERT(spa->spa_state != POOL_STATE_UNINITIALIZED);
1005 txg_list_destroy(&spa->spa_vdev_txg_list);
1007 list_destroy(&spa->spa_config_dirty_list);
1008 list_destroy(&spa->spa_state_dirty_list);
1010 for (int t = 0; t < ZIO_TYPES; t++) {
1011 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1012 if (spa->spa_zio_taskq[t][q] != NULL)
1013 taskq_destroy(spa->spa_zio_taskq[t][q]);
1014 spa->spa_zio_taskq[t][q] = NULL;
1018 metaslab_class_destroy(spa->spa_normal_class);
1019 spa->spa_normal_class = NULL;
1021 metaslab_class_destroy(spa->spa_log_class);
1022 spa->spa_log_class = NULL;
1025 * If this was part of an import or the open otherwise failed, we may
1026 * still have errors left in the queues. Empty them just in case.
1028 spa_errlog_drain(spa);
1030 avl_destroy(&spa->spa_errlist_scrub);
1031 avl_destroy(&spa->spa_errlist_last);
1033 spa->spa_state = POOL_STATE_UNINITIALIZED;
1035 mutex_enter(&spa->spa_proc_lock);
1036 if (spa->spa_proc_state != SPA_PROC_NONE) {
1037 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1038 spa->spa_proc_state = SPA_PROC_DEACTIVATE;
1039 cv_broadcast(&spa->spa_proc_cv);
1040 while (spa->spa_proc_state == SPA_PROC_DEACTIVATE) {
1041 ASSERT(spa->spa_proc != &p0);
1042 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1044 ASSERT(spa->spa_proc_state == SPA_PROC_GONE);
1045 spa->spa_proc_state = SPA_PROC_NONE;
1047 ASSERT(spa->spa_proc == &p0);
1048 mutex_exit(&spa->spa_proc_lock);
1051 * We want to make sure spa_thread() has actually exited the ZFS
1052 * module, so that the module can't be unloaded out from underneath
1053 * it.
1055 if (spa->spa_did != 0) {
1056 thread_join(spa->spa_did);
1057 spa->spa_did = 0;
1062 * Verify a pool configuration, and construct the vdev tree appropriately. This
1063 * will create all the necessary vdevs in the appropriate layout, with each vdev
1064 * in the CLOSED state. This will prep the pool before open/creation/import.
1065 * All vdev validation is done by the vdev_alloc() routine.
1067 static int
1068 spa_config_parse(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent,
1069 uint_t id, int atype)
1071 nvlist_t **child;
1072 uint_t children;
1073 int error;
1075 if ((error = vdev_alloc(spa, vdp, nv, parent, id, atype)) != 0)
1076 return (error);
1078 if ((*vdp)->vdev_ops->vdev_op_leaf)
1079 return (0);
1081 error = nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1082 &child, &children);
1084 if (error == ENOENT)
1085 return (0);
1087 if (error) {
1088 vdev_free(*vdp);
1089 *vdp = NULL;
1090 return (EINVAL);
1093 for (int c = 0; c < children; c++) {
1094 vdev_t *vd;
1095 if ((error = spa_config_parse(spa, &vd, child[c], *vdp, c,
1096 atype)) != 0) {
1097 vdev_free(*vdp);
1098 *vdp = NULL;
1099 return (error);
1103 ASSERT(*vdp != NULL);
1105 return (0);
1109 * Opposite of spa_load().
1111 static void
1112 spa_unload(spa_t *spa)
1114 int i;
1116 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1119 * Stop async tasks.
1121 spa_async_suspend(spa);
1124 * Stop syncing.
1126 if (spa->spa_sync_on) {
1127 txg_sync_stop(spa->spa_dsl_pool);
1128 spa->spa_sync_on = B_FALSE;
1132 * Wait for any outstanding async I/O to complete.
1134 if (spa->spa_async_zio_root != NULL) {
1135 (void) zio_wait(spa->spa_async_zio_root);
1136 spa->spa_async_zio_root = NULL;
1139 bpobj_close(&spa->spa_deferred_bpobj);
1142 * Close the dsl pool.
1144 if (spa->spa_dsl_pool) {
1145 dsl_pool_close(spa->spa_dsl_pool);
1146 spa->spa_dsl_pool = NULL;
1147 spa->spa_meta_objset = NULL;
1150 ddt_unload(spa);
1152 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1155 * Drop and purge level 2 cache
1157 spa_l2cache_drop(spa);
1160 * Close all vdevs.
1162 if (spa->spa_root_vdev)
1163 vdev_free(spa->spa_root_vdev);
1164 ASSERT(spa->spa_root_vdev == NULL);
1166 for (i = 0; i < spa->spa_spares.sav_count; i++)
1167 vdev_free(spa->spa_spares.sav_vdevs[i]);
1168 if (spa->spa_spares.sav_vdevs) {
1169 kmem_free(spa->spa_spares.sav_vdevs,
1170 spa->spa_spares.sav_count * sizeof (void *));
1171 spa->spa_spares.sav_vdevs = NULL;
1173 if (spa->spa_spares.sav_config) {
1174 nvlist_free(spa->spa_spares.sav_config);
1175 spa->spa_spares.sav_config = NULL;
1177 spa->spa_spares.sav_count = 0;
1179 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
1180 vdev_clear_stats(spa->spa_l2cache.sav_vdevs[i]);
1181 vdev_free(spa->spa_l2cache.sav_vdevs[i]);
1183 if (spa->spa_l2cache.sav_vdevs) {
1184 kmem_free(spa->spa_l2cache.sav_vdevs,
1185 spa->spa_l2cache.sav_count * sizeof (void *));
1186 spa->spa_l2cache.sav_vdevs = NULL;
1188 if (spa->spa_l2cache.sav_config) {
1189 nvlist_free(spa->spa_l2cache.sav_config);
1190 spa->spa_l2cache.sav_config = NULL;
1192 spa->spa_l2cache.sav_count = 0;
1194 spa->spa_async_suspended = 0;
1196 if (spa->spa_comment != NULL) {
1197 spa_strfree(spa->spa_comment);
1198 spa->spa_comment = NULL;
1201 spa_config_exit(spa, SCL_ALL, FTAG);
1205 * Load (or re-load) the current list of vdevs describing the active spares for
1206 * this pool. When this is called, we have some form of basic information in
1207 * 'spa_spares.sav_config'. We parse this into vdevs, try to open them, and
1208 * then re-generate a more complete list including status information.
1210 static void
1211 spa_load_spares(spa_t *spa)
1213 nvlist_t **spares;
1214 uint_t nspares;
1215 int i;
1216 vdev_t *vd, *tvd;
1218 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1221 * First, close and free any existing spare vdevs.
1223 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1224 vd = spa->spa_spares.sav_vdevs[i];
1226 /* Undo the call to spa_activate() below */
1227 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1228 B_FALSE)) != NULL && tvd->vdev_isspare)
1229 spa_spare_remove(tvd);
1230 vdev_close(vd);
1231 vdev_free(vd);
1234 if (spa->spa_spares.sav_vdevs)
1235 kmem_free(spa->spa_spares.sav_vdevs,
1236 spa->spa_spares.sav_count * sizeof (void *));
1238 if (spa->spa_spares.sav_config == NULL)
1239 nspares = 0;
1240 else
1241 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
1242 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
1244 spa->spa_spares.sav_count = (int)nspares;
1245 spa->spa_spares.sav_vdevs = NULL;
1247 if (nspares == 0)
1248 return;
1251 * Construct the array of vdevs, opening them to get status in the
1252 * process. For each spare, there is potentially two different vdev_t
1253 * structures associated with it: one in the list of spares (used only
1254 * for basic validation purposes) and one in the active vdev
1255 * configuration (if it's spared in). During this phase we open and
1256 * validate each vdev on the spare list. If the vdev also exists in the
1257 * active configuration, then we also mark this vdev as an active spare.
1259 spa->spa_spares.sav_vdevs = kmem_alloc(nspares * sizeof (void *),
1260 KM_SLEEP);
1261 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1262 VERIFY(spa_config_parse(spa, &vd, spares[i], NULL, 0,
1263 VDEV_ALLOC_SPARE) == 0);
1264 ASSERT(vd != NULL);
1266 spa->spa_spares.sav_vdevs[i] = vd;
1268 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1269 B_FALSE)) != NULL) {
1270 if (!tvd->vdev_isspare)
1271 spa_spare_add(tvd);
1274 * We only mark the spare active if we were successfully
1275 * able to load the vdev. Otherwise, importing a pool
1276 * with a bad active spare would result in strange
1277 * behavior, because multiple pool would think the spare
1278 * is actively in use.
1280 * There is a vulnerability here to an equally bizarre
1281 * circumstance, where a dead active spare is later
1282 * brought back to life (onlined or otherwise). Given
1283 * the rarity of this scenario, and the extra complexity
1284 * it adds, we ignore the possibility.
1286 if (!vdev_is_dead(tvd))
1287 spa_spare_activate(tvd);
1290 vd->vdev_top = vd;
1291 vd->vdev_aux = &spa->spa_spares;
1293 if (vdev_open(vd) != 0)
1294 continue;
1296 if (vdev_validate_aux(vd) == 0)
1297 spa_spare_add(vd);
1301 * Recompute the stashed list of spares, with status information
1302 * this time.
1304 VERIFY(nvlist_remove(spa->spa_spares.sav_config, ZPOOL_CONFIG_SPARES,
1305 DATA_TYPE_NVLIST_ARRAY) == 0);
1307 spares = kmem_alloc(spa->spa_spares.sav_count * sizeof (void *),
1308 KM_SLEEP);
1309 for (i = 0; i < spa->spa_spares.sav_count; i++)
1310 spares[i] = vdev_config_generate(spa,
1311 spa->spa_spares.sav_vdevs[i], B_TRUE, VDEV_CONFIG_SPARE);
1312 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
1313 ZPOOL_CONFIG_SPARES, spares, spa->spa_spares.sav_count) == 0);
1314 for (i = 0; i < spa->spa_spares.sav_count; i++)
1315 nvlist_free(spares[i]);
1316 kmem_free(spares, spa->spa_spares.sav_count * sizeof (void *));
1320 * Load (or re-load) the current list of vdevs describing the active l2cache for
1321 * this pool. When this is called, we have some form of basic information in
1322 * 'spa_l2cache.sav_config'. We parse this into vdevs, try to open them, and
1323 * then re-generate a more complete list including status information.
1324 * Devices which are already active have their details maintained, and are
1325 * not re-opened.
1327 static void
1328 spa_load_l2cache(spa_t *spa)
1330 nvlist_t **l2cache;
1331 uint_t nl2cache;
1332 int i, j, oldnvdevs;
1333 uint64_t guid;
1334 vdev_t *vd, **oldvdevs, **newvdevs;
1335 spa_aux_vdev_t *sav = &spa->spa_l2cache;
1337 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1339 if (sav->sav_config != NULL) {
1340 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
1341 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
1342 newvdevs = kmem_alloc(nl2cache * sizeof (void *), KM_SLEEP);
1343 } else {
1344 nl2cache = 0;
1347 oldvdevs = sav->sav_vdevs;
1348 oldnvdevs = sav->sav_count;
1349 sav->sav_vdevs = NULL;
1350 sav->sav_count = 0;
1353 * Process new nvlist of vdevs.
1355 for (i = 0; i < nl2cache; i++) {
1356 VERIFY(nvlist_lookup_uint64(l2cache[i], ZPOOL_CONFIG_GUID,
1357 &guid) == 0);
1359 newvdevs[i] = NULL;
1360 for (j = 0; j < oldnvdevs; j++) {
1361 vd = oldvdevs[j];
1362 if (vd != NULL && guid == vd->vdev_guid) {
1364 * Retain previous vdev for add/remove ops.
1366 newvdevs[i] = vd;
1367 oldvdevs[j] = NULL;
1368 break;
1372 if (newvdevs[i] == NULL) {
1374 * Create new vdev
1376 VERIFY(spa_config_parse(spa, &vd, l2cache[i], NULL, 0,
1377 VDEV_ALLOC_L2CACHE) == 0);
1378 ASSERT(vd != NULL);
1379 newvdevs[i] = vd;
1382 * Commit this vdev as an l2cache device,
1383 * even if it fails to open.
1385 spa_l2cache_add(vd);
1387 vd->vdev_top = vd;
1388 vd->vdev_aux = sav;
1390 spa_l2cache_activate(vd);
1392 if (vdev_open(vd) != 0)
1393 continue;
1395 (void) vdev_validate_aux(vd);
1397 if (!vdev_is_dead(vd))
1398 l2arc_add_vdev(spa, vd);
1403 * Purge vdevs that were dropped
1405 for (i = 0; i < oldnvdevs; i++) {
1406 uint64_t pool;
1408 vd = oldvdevs[i];
1409 if (vd != NULL) {
1410 ASSERT(vd->vdev_isl2cache);
1412 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
1413 pool != 0ULL && l2arc_vdev_present(vd))
1414 l2arc_remove_vdev(vd);
1415 vdev_clear_stats(vd);
1416 vdev_free(vd);
1420 if (oldvdevs)
1421 kmem_free(oldvdevs, oldnvdevs * sizeof (void *));
1423 if (sav->sav_config == NULL)
1424 goto out;
1426 sav->sav_vdevs = newvdevs;
1427 sav->sav_count = (int)nl2cache;
1430 * Recompute the stashed list of l2cache devices, with status
1431 * information this time.
1433 VERIFY(nvlist_remove(sav->sav_config, ZPOOL_CONFIG_L2CACHE,
1434 DATA_TYPE_NVLIST_ARRAY) == 0);
1436 l2cache = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
1437 for (i = 0; i < sav->sav_count; i++)
1438 l2cache[i] = vdev_config_generate(spa,
1439 sav->sav_vdevs[i], B_TRUE, VDEV_CONFIG_L2CACHE);
1440 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
1441 ZPOOL_CONFIG_L2CACHE, l2cache, sav->sav_count) == 0);
1442 out:
1443 for (i = 0; i < sav->sav_count; i++)
1444 nvlist_free(l2cache[i]);
1445 if (sav->sav_count)
1446 kmem_free(l2cache, sav->sav_count * sizeof (void *));
1449 static int
1450 load_nvlist(spa_t *spa, uint64_t obj, nvlist_t **value)
1452 dmu_buf_t *db;
1453 char *packed = NULL;
1454 size_t nvsize = 0;
1455 int error;
1456 *value = NULL;
1458 VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
1459 nvsize = *(uint64_t *)db->db_data;
1460 dmu_buf_rele(db, FTAG);
1462 packed = kmem_alloc(nvsize, KM_SLEEP);
1463 error = dmu_read(spa->spa_meta_objset, obj, 0, nvsize, packed,
1464 DMU_READ_PREFETCH);
1465 if (error == 0)
1466 error = nvlist_unpack(packed, nvsize, value, 0);
1467 kmem_free(packed, nvsize);
1469 return (error);
1473 * Checks to see if the given vdev could not be opened, in which case we post a
1474 * sysevent to notify the autoreplace code that the device has been removed.
1476 static void
1477 spa_check_removed(vdev_t *vd)
1479 for (int c = 0; c < vd->vdev_children; c++)
1480 spa_check_removed(vd->vdev_child[c]);
1482 if (vd->vdev_ops->vdev_op_leaf && vdev_is_dead(vd)) {
1483 zfs_post_autoreplace(vd->vdev_spa, vd);
1484 spa_event_notify(vd->vdev_spa, vd, ESC_ZFS_VDEV_CHECK);
1489 * Validate the current config against the MOS config
1491 static boolean_t
1492 spa_config_valid(spa_t *spa, nvlist_t *config)
1494 vdev_t *mrvd, *rvd = spa->spa_root_vdev;
1495 nvlist_t *nv;
1497 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nv) == 0);
1499 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1500 VERIFY(spa_config_parse(spa, &mrvd, nv, NULL, 0, VDEV_ALLOC_LOAD) == 0);
1502 ASSERT3U(rvd->vdev_children, ==, mrvd->vdev_children);
1505 * If we're doing a normal import, then build up any additional
1506 * diagnostic information about missing devices in this config.
1507 * We'll pass this up to the user for further processing.
1509 if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG)) {
1510 nvlist_t **child, *nv;
1511 uint64_t idx = 0;
1513 child = kmem_alloc(rvd->vdev_children * sizeof (nvlist_t **),
1514 KM_SLEEP);
1515 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1517 for (int c = 0; c < rvd->vdev_children; c++) {
1518 vdev_t *tvd = rvd->vdev_child[c];
1519 vdev_t *mtvd = mrvd->vdev_child[c];
1521 if (tvd->vdev_ops == &vdev_missing_ops &&
1522 mtvd->vdev_ops != &vdev_missing_ops &&
1523 mtvd->vdev_islog)
1524 child[idx++] = vdev_config_generate(spa, mtvd,
1525 B_FALSE, 0);
1528 if (idx) {
1529 VERIFY(nvlist_add_nvlist_array(nv,
1530 ZPOOL_CONFIG_CHILDREN, child, idx) == 0);
1531 VERIFY(nvlist_add_nvlist(spa->spa_load_info,
1532 ZPOOL_CONFIG_MISSING_DEVICES, nv) == 0);
1534 for (int i = 0; i < idx; i++)
1535 nvlist_free(child[i]);
1537 nvlist_free(nv);
1538 kmem_free(child, rvd->vdev_children * sizeof (char **));
1542 * Compare the root vdev tree with the information we have
1543 * from the MOS config (mrvd). Check each top-level vdev
1544 * with the corresponding MOS config top-level (mtvd).
1546 for (int c = 0; c < rvd->vdev_children; c++) {
1547 vdev_t *tvd = rvd->vdev_child[c];
1548 vdev_t *mtvd = mrvd->vdev_child[c];
1551 * Resolve any "missing" vdevs in the current configuration.
1552 * If we find that the MOS config has more accurate information
1553 * about the top-level vdev then use that vdev instead.
1555 if (tvd->vdev_ops == &vdev_missing_ops &&
1556 mtvd->vdev_ops != &vdev_missing_ops) {
1558 if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG))
1559 continue;
1562 * Device specific actions.
1564 if (mtvd->vdev_islog) {
1565 spa_set_log_state(spa, SPA_LOG_CLEAR);
1566 } else {
1568 * XXX - once we have 'readonly' pool
1569 * support we should be able to handle
1570 * missing data devices by transitioning
1571 * the pool to readonly.
1573 continue;
1577 * Swap the missing vdev with the data we were
1578 * able to obtain from the MOS config.
1580 vdev_remove_child(rvd, tvd);
1581 vdev_remove_child(mrvd, mtvd);
1583 vdev_add_child(rvd, mtvd);
1584 vdev_add_child(mrvd, tvd);
1586 spa_config_exit(spa, SCL_ALL, FTAG);
1587 vdev_load(mtvd);
1588 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1590 vdev_reopen(rvd);
1591 } else if (mtvd->vdev_islog) {
1593 * Load the slog device's state from the MOS config
1594 * since it's possible that the label does not
1595 * contain the most up-to-date information.
1597 vdev_load_log_state(tvd, mtvd);
1598 vdev_reopen(tvd);
1601 vdev_free(mrvd);
1602 spa_config_exit(spa, SCL_ALL, FTAG);
1605 * Ensure we were able to validate the config.
1607 return (rvd->vdev_guid_sum == spa->spa_uberblock.ub_guid_sum);
1611 * Check for missing log devices
1613 static int
1614 spa_check_logs(spa_t *spa)
1616 switch (spa->spa_log_state) {
1617 case SPA_LOG_MISSING:
1618 /* need to recheck in case slog has been restored */
1619 case SPA_LOG_UNKNOWN:
1620 if (dmu_objset_find(spa->spa_name, zil_check_log_chain, NULL,
1621 DS_FIND_CHILDREN)) {
1622 spa_set_log_state(spa, SPA_LOG_MISSING);
1623 return (1);
1625 break;
1627 return (0);
1630 static boolean_t
1631 spa_passivate_log(spa_t *spa)
1633 vdev_t *rvd = spa->spa_root_vdev;
1634 boolean_t slog_found = B_FALSE;
1636 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1638 if (!spa_has_slogs(spa))
1639 return (B_FALSE);
1641 for (int c = 0; c < rvd->vdev_children; c++) {
1642 vdev_t *tvd = rvd->vdev_child[c];
1643 metaslab_group_t *mg = tvd->vdev_mg;
1645 if (tvd->vdev_islog) {
1646 metaslab_group_passivate(mg);
1647 slog_found = B_TRUE;
1651 return (slog_found);
1654 static void
1655 spa_activate_log(spa_t *spa)
1657 vdev_t *rvd = spa->spa_root_vdev;
1659 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1661 for (int c = 0; c < rvd->vdev_children; c++) {
1662 vdev_t *tvd = rvd->vdev_child[c];
1663 metaslab_group_t *mg = tvd->vdev_mg;
1665 if (tvd->vdev_islog)
1666 metaslab_group_activate(mg);
1671 spa_offline_log(spa_t *spa)
1673 int error = 0;
1675 if ((error = dmu_objset_find(spa_name(spa), zil_vdev_offline,
1676 NULL, DS_FIND_CHILDREN)) == 0) {
1679 * We successfully offlined the log device, sync out the
1680 * current txg so that the "stubby" block can be removed
1681 * by zil_sync().
1683 txg_wait_synced(spa->spa_dsl_pool, 0);
1685 return (error);
1688 static void
1689 spa_aux_check_removed(spa_aux_vdev_t *sav)
1691 for (int i = 0; i < sav->sav_count; i++)
1692 spa_check_removed(sav->sav_vdevs[i]);
1695 void
1696 spa_claim_notify(zio_t *zio)
1698 spa_t *spa = zio->io_spa;
1700 if (zio->io_error)
1701 return;
1703 mutex_enter(&spa->spa_props_lock); /* any mutex will do */
1704 if (spa->spa_claim_max_txg < zio->io_bp->blk_birth)
1705 spa->spa_claim_max_txg = zio->io_bp->blk_birth;
1706 mutex_exit(&spa->spa_props_lock);
1709 typedef struct spa_load_error {
1710 uint64_t sle_meta_count;
1711 uint64_t sle_data_count;
1712 } spa_load_error_t;
1714 static void
1715 spa_load_verify_done(zio_t *zio)
1717 blkptr_t *bp = zio->io_bp;
1718 spa_load_error_t *sle = zio->io_private;
1719 dmu_object_type_t type = BP_GET_TYPE(bp);
1720 int error = zio->io_error;
1722 if (error) {
1723 if ((BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type)) &&
1724 type != DMU_OT_INTENT_LOG)
1725 atomic_add_64(&sle->sle_meta_count, 1);
1726 else
1727 atomic_add_64(&sle->sle_data_count, 1);
1729 zio_data_buf_free(zio->io_data, zio->io_size);
1732 /*ARGSUSED*/
1733 static int
1734 spa_load_verify_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
1735 const zbookmark_t *zb, const dnode_phys_t *dnp, void *arg)
1737 if (bp != NULL) {
1738 zio_t *rio = arg;
1739 size_t size = BP_GET_PSIZE(bp);
1740 void *data = zio_data_buf_alloc(size);
1742 zio_nowait(zio_read(rio, spa, bp, data, size,
1743 spa_load_verify_done, rio->io_private, ZIO_PRIORITY_SCRUB,
1744 ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CANFAIL |
1745 ZIO_FLAG_SCRUB | ZIO_FLAG_RAW, zb));
1747 return (0);
1750 static int
1751 spa_load_verify(spa_t *spa)
1753 zio_t *rio;
1754 spa_load_error_t sle = { 0 };
1755 zpool_rewind_policy_t policy;
1756 boolean_t verify_ok = B_FALSE;
1757 int error;
1759 zpool_get_rewind_policy(spa->spa_config, &policy);
1761 if (policy.zrp_request & ZPOOL_NEVER_REWIND)
1762 return (0);
1764 rio = zio_root(spa, NULL, &sle,
1765 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
1767 error = traverse_pool(spa, spa->spa_verify_min_txg,
1768 TRAVERSE_PRE | TRAVERSE_PREFETCH, spa_load_verify_cb, rio);
1770 (void) zio_wait(rio);
1772 spa->spa_load_meta_errors = sle.sle_meta_count;
1773 spa->spa_load_data_errors = sle.sle_data_count;
1775 if (!error && sle.sle_meta_count <= policy.zrp_maxmeta &&
1776 sle.sle_data_count <= policy.zrp_maxdata) {
1777 int64_t loss = 0;
1779 verify_ok = B_TRUE;
1780 spa->spa_load_txg = spa->spa_uberblock.ub_txg;
1781 spa->spa_load_txg_ts = spa->spa_uberblock.ub_timestamp;
1783 loss = spa->spa_last_ubsync_txg_ts - spa->spa_load_txg_ts;
1784 VERIFY(nvlist_add_uint64(spa->spa_load_info,
1785 ZPOOL_CONFIG_LOAD_TIME, spa->spa_load_txg_ts) == 0);
1786 VERIFY(nvlist_add_int64(spa->spa_load_info,
1787 ZPOOL_CONFIG_REWIND_TIME, loss) == 0);
1788 VERIFY(nvlist_add_uint64(spa->spa_load_info,
1789 ZPOOL_CONFIG_LOAD_DATA_ERRORS, sle.sle_data_count) == 0);
1790 } else {
1791 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg;
1794 if (error) {
1795 if (error != ENXIO && error != EIO)
1796 error = EIO;
1797 return (error);
1800 return (verify_ok ? 0 : EIO);
1804 * Find a value in the pool props object.
1806 static void
1807 spa_prop_find(spa_t *spa, zpool_prop_t prop, uint64_t *val)
1809 (void) zap_lookup(spa->spa_meta_objset, spa->spa_pool_props_object,
1810 zpool_prop_to_name(prop), sizeof (uint64_t), 1, val);
1814 * Find a value in the pool directory object.
1816 static int
1817 spa_dir_prop(spa_t *spa, const char *name, uint64_t *val)
1819 return (zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
1820 name, sizeof (uint64_t), 1, val));
1823 static int
1824 spa_vdev_err(vdev_t *vdev, vdev_aux_t aux, int err)
1826 vdev_set_state(vdev, B_TRUE, VDEV_STATE_CANT_OPEN, aux);
1827 return (err);
1831 * Fix up config after a partly-completed split. This is done with the
1832 * ZPOOL_CONFIG_SPLIT nvlist. Both the splitting pool and the split-off
1833 * pool have that entry in their config, but only the splitting one contains
1834 * a list of all the guids of the vdevs that are being split off.
1836 * This function determines what to do with that list: either rejoin
1837 * all the disks to the pool, or complete the splitting process. To attempt
1838 * the rejoin, each disk that is offlined is marked online again, and
1839 * we do a reopen() call. If the vdev label for every disk that was
1840 * marked online indicates it was successfully split off (VDEV_AUX_SPLIT_POOL)
1841 * then we call vdev_split() on each disk, and complete the split.
1843 * Otherwise we leave the config alone, with all the vdevs in place in
1844 * the original pool.
1846 static void
1847 spa_try_repair(spa_t *spa, nvlist_t *config)
1849 uint_t extracted;
1850 uint64_t *glist;
1851 uint_t i, gcount;
1852 nvlist_t *nvl;
1853 vdev_t **vd;
1854 boolean_t attempt_reopen;
1856 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) != 0)
1857 return;
1859 /* check that the config is complete */
1860 if (nvlist_lookup_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
1861 &glist, &gcount) != 0)
1862 return;
1864 vd = kmem_zalloc(gcount * sizeof (vdev_t *), KM_SLEEP);
1866 /* attempt to online all the vdevs & validate */
1867 attempt_reopen = B_TRUE;
1868 for (i = 0; i < gcount; i++) {
1869 if (glist[i] == 0) /* vdev is hole */
1870 continue;
1872 vd[i] = spa_lookup_by_guid(spa, glist[i], B_FALSE);
1873 if (vd[i] == NULL) {
1875 * Don't bother attempting to reopen the disks;
1876 * just do the split.
1878 attempt_reopen = B_FALSE;
1879 } else {
1880 /* attempt to re-online it */
1881 vd[i]->vdev_offline = B_FALSE;
1885 if (attempt_reopen) {
1886 vdev_reopen(spa->spa_root_vdev);
1888 /* check each device to see what state it's in */
1889 for (extracted = 0, i = 0; i < gcount; i++) {
1890 if (vd[i] != NULL &&
1891 vd[i]->vdev_stat.vs_aux != VDEV_AUX_SPLIT_POOL)
1892 break;
1893 ++extracted;
1898 * If every disk has been moved to the new pool, or if we never
1899 * even attempted to look at them, then we split them off for
1900 * good.
1902 if (!attempt_reopen || gcount == extracted) {
1903 for (i = 0; i < gcount; i++)
1904 if (vd[i] != NULL)
1905 vdev_split(vd[i]);
1906 vdev_reopen(spa->spa_root_vdev);
1909 kmem_free(vd, gcount * sizeof (vdev_t *));
1912 static int
1913 spa_load(spa_t *spa, spa_load_state_t state, spa_import_type_t type,
1914 boolean_t mosconfig)
1916 nvlist_t *config = spa->spa_config;
1917 char *ereport = FM_EREPORT_ZFS_POOL;
1918 char *comment;
1919 int error;
1920 uint64_t pool_guid;
1921 nvlist_t *nvl;
1923 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid))
1924 return (EINVAL);
1926 ASSERT(spa->spa_comment == NULL);
1927 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
1928 spa->spa_comment = spa_strdup(comment);
1931 * Versioning wasn't explicitly added to the label until later, so if
1932 * it's not present treat it as the initial version.
1934 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
1935 &spa->spa_ubsync.ub_version) != 0)
1936 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
1938 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
1939 &spa->spa_config_txg);
1941 if ((state == SPA_LOAD_IMPORT || state == SPA_LOAD_TRYIMPORT) &&
1942 spa_guid_exists(pool_guid, 0)) {
1943 error = EEXIST;
1944 } else {
1945 spa->spa_config_guid = pool_guid;
1947 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT,
1948 &nvl) == 0) {
1949 VERIFY(nvlist_dup(nvl, &spa->spa_config_splitting,
1950 KM_SLEEP) == 0);
1953 nvlist_free(spa->spa_load_info);
1954 spa->spa_load_info = fnvlist_alloc();
1956 gethrestime(&spa->spa_loaded_ts);
1957 error = spa_load_impl(spa, pool_guid, config, state, type,
1958 mosconfig, &ereport);
1961 spa->spa_minref = refcount_count(&spa->spa_refcount);
1962 if (error) {
1963 if (error != EEXIST) {
1964 spa->spa_loaded_ts.tv_sec = 0;
1965 spa->spa_loaded_ts.tv_nsec = 0;
1967 if (error != EBADF) {
1968 zfs_ereport_post(ereport, spa, NULL, NULL, 0, 0);
1971 spa->spa_load_state = error ? SPA_LOAD_ERROR : SPA_LOAD_NONE;
1972 spa->spa_ena = 0;
1974 return (error);
1978 * Load an existing storage pool, using the pool's builtin spa_config as a
1979 * source of configuration information.
1981 static int
1982 spa_load_impl(spa_t *spa, uint64_t pool_guid, nvlist_t *config,
1983 spa_load_state_t state, spa_import_type_t type, boolean_t mosconfig,
1984 char **ereport)
1986 int error = 0;
1987 nvlist_t *nvroot = NULL;
1988 nvlist_t *label;
1989 vdev_t *rvd;
1990 uberblock_t *ub = &spa->spa_uberblock;
1991 uint64_t children, config_cache_txg = spa->spa_config_txg;
1992 int orig_mode = spa->spa_mode;
1993 int parse;
1994 uint64_t obj;
1995 boolean_t missing_feat_write = B_FALSE;
1998 * If this is an untrusted config, access the pool in read-only mode.
1999 * This prevents things like resilvering recently removed devices.
2001 if (!mosconfig)
2002 spa->spa_mode = FREAD;
2004 ASSERT(MUTEX_HELD(&spa_namespace_lock));
2006 spa->spa_load_state = state;
2008 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvroot))
2009 return (EINVAL);
2011 parse = (type == SPA_IMPORT_EXISTING ?
2012 VDEV_ALLOC_LOAD : VDEV_ALLOC_SPLIT);
2015 * Create "The Godfather" zio to hold all async IOs
2017 spa->spa_async_zio_root = zio_root(spa, NULL, NULL,
2018 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE | ZIO_FLAG_GODFATHER);
2021 * Parse the configuration into a vdev tree. We explicitly set the
2022 * value that will be returned by spa_version() since parsing the
2023 * configuration requires knowing the version number.
2025 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2026 error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, parse);
2027 spa_config_exit(spa, SCL_ALL, FTAG);
2029 if (error != 0)
2030 return (error);
2032 ASSERT(spa->spa_root_vdev == rvd);
2034 if (type != SPA_IMPORT_ASSEMBLE) {
2035 ASSERT(spa_guid(spa) == pool_guid);
2039 * Try to open all vdevs, loading each label in the process.
2041 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2042 error = vdev_open(rvd);
2043 spa_config_exit(spa, SCL_ALL, FTAG);
2044 if (error != 0)
2045 return (error);
2048 * We need to validate the vdev labels against the configuration that
2049 * we have in hand, which is dependent on the setting of mosconfig. If
2050 * mosconfig is true then we're validating the vdev labels based on
2051 * that config. Otherwise, we're validating against the cached config
2052 * (zpool.cache) that was read when we loaded the zfs module, and then
2053 * later we will recursively call spa_load() and validate against
2054 * the vdev config.
2056 * If we're assembling a new pool that's been split off from an
2057 * existing pool, the labels haven't yet been updated so we skip
2058 * validation for now.
2060 if (type != SPA_IMPORT_ASSEMBLE) {
2061 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2062 error = vdev_validate(rvd, mosconfig);
2063 spa_config_exit(spa, SCL_ALL, FTAG);
2065 if (error != 0)
2066 return (error);
2068 if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN)
2069 return (ENXIO);
2073 * Find the best uberblock.
2075 vdev_uberblock_load(rvd, ub, &label);
2078 * If we weren't able to find a single valid uberblock, return failure.
2080 if (ub->ub_txg == 0) {
2081 nvlist_free(label);
2082 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, ENXIO));
2086 * If the pool has an unsupported version we can't open it.
2088 if (!SPA_VERSION_IS_SUPPORTED(ub->ub_version)) {
2089 nvlist_free(label);
2090 return (spa_vdev_err(rvd, VDEV_AUX_VERSION_NEWER, ENOTSUP));
2093 if (ub->ub_version >= SPA_VERSION_FEATURES) {
2094 nvlist_t *features;
2097 * If we weren't able to find what's necessary for reading the
2098 * MOS in the label, return failure.
2100 if (label == NULL || nvlist_lookup_nvlist(label,
2101 ZPOOL_CONFIG_FEATURES_FOR_READ, &features) != 0) {
2102 nvlist_free(label);
2103 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2104 ENXIO));
2108 * Update our in-core representation with the definitive values
2109 * from the label.
2111 nvlist_free(spa->spa_label_features);
2112 VERIFY(nvlist_dup(features, &spa->spa_label_features, 0) == 0);
2115 nvlist_free(label);
2118 * Look through entries in the label nvlist's features_for_read. If
2119 * there is a feature listed there which we don't understand then we
2120 * cannot open a pool.
2122 if (ub->ub_version >= SPA_VERSION_FEATURES) {
2123 nvlist_t *unsup_feat;
2125 VERIFY(nvlist_alloc(&unsup_feat, NV_UNIQUE_NAME, KM_SLEEP) ==
2128 for (nvpair_t *nvp = nvlist_next_nvpair(spa->spa_label_features,
2129 NULL); nvp != NULL;
2130 nvp = nvlist_next_nvpair(spa->spa_label_features, nvp)) {
2131 if (!zfeature_is_supported(nvpair_name(nvp))) {
2132 VERIFY(nvlist_add_string(unsup_feat,
2133 nvpair_name(nvp), "") == 0);
2137 if (!nvlist_empty(unsup_feat)) {
2138 VERIFY(nvlist_add_nvlist(spa->spa_load_info,
2139 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat) == 0);
2140 nvlist_free(unsup_feat);
2141 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
2142 ENOTSUP));
2145 nvlist_free(unsup_feat);
2149 * If the vdev guid sum doesn't match the uberblock, we have an
2150 * incomplete configuration. We first check to see if the pool
2151 * is aware of the complete config (i.e ZPOOL_CONFIG_VDEV_CHILDREN).
2152 * If it is, defer the vdev_guid_sum check till later so we
2153 * can handle missing vdevs.
2155 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VDEV_CHILDREN,
2156 &children) != 0 && mosconfig && type != SPA_IMPORT_ASSEMBLE &&
2157 rvd->vdev_guid_sum != ub->ub_guid_sum)
2158 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM, ENXIO));
2160 if (type != SPA_IMPORT_ASSEMBLE && spa->spa_config_splitting) {
2161 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2162 spa_try_repair(spa, config);
2163 spa_config_exit(spa, SCL_ALL, FTAG);
2164 nvlist_free(spa->spa_config_splitting);
2165 spa->spa_config_splitting = NULL;
2169 * Initialize internal SPA structures.
2171 spa->spa_state = POOL_STATE_ACTIVE;
2172 spa->spa_ubsync = spa->spa_uberblock;
2173 spa->spa_verify_min_txg = spa->spa_extreme_rewind ?
2174 TXG_INITIAL - 1 : spa_last_synced_txg(spa) - TXG_DEFER_SIZE - 1;
2175 spa->spa_first_txg = spa->spa_last_ubsync_txg ?
2176 spa->spa_last_ubsync_txg : spa_last_synced_txg(spa) + 1;
2177 spa->spa_claim_max_txg = spa->spa_first_txg;
2178 spa->spa_prev_software_version = ub->ub_software_version;
2180 error = dsl_pool_init(spa, spa->spa_first_txg, &spa->spa_dsl_pool);
2181 if (error)
2182 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2183 spa->spa_meta_objset = spa->spa_dsl_pool->dp_meta_objset;
2185 if (spa_dir_prop(spa, DMU_POOL_CONFIG, &spa->spa_config_object) != 0)
2186 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2188 if (spa_version(spa) >= SPA_VERSION_FEATURES) {
2189 boolean_t missing_feat_read = B_FALSE;
2190 nvlist_t *unsup_feat, *enabled_feat;
2192 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_READ,
2193 &spa->spa_feat_for_read_obj) != 0) {
2194 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2197 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_WRITE,
2198 &spa->spa_feat_for_write_obj) != 0) {
2199 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2202 if (spa_dir_prop(spa, DMU_POOL_FEATURE_DESCRIPTIONS,
2203 &spa->spa_feat_desc_obj) != 0) {
2204 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2207 enabled_feat = fnvlist_alloc();
2208 unsup_feat = fnvlist_alloc();
2210 if (!feature_is_supported(spa->spa_meta_objset,
2211 spa->spa_feat_for_read_obj, spa->spa_feat_desc_obj,
2212 unsup_feat, enabled_feat))
2213 missing_feat_read = B_TRUE;
2215 if (spa_writeable(spa) || state == SPA_LOAD_TRYIMPORT) {
2216 if (!feature_is_supported(spa->spa_meta_objset,
2217 spa->spa_feat_for_write_obj, spa->spa_feat_desc_obj,
2218 unsup_feat, enabled_feat)) {
2219 missing_feat_write = B_TRUE;
2223 fnvlist_add_nvlist(spa->spa_load_info,
2224 ZPOOL_CONFIG_ENABLED_FEAT, enabled_feat);
2226 if (!nvlist_empty(unsup_feat)) {
2227 fnvlist_add_nvlist(spa->spa_load_info,
2228 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat);
2231 fnvlist_free(enabled_feat);
2232 fnvlist_free(unsup_feat);
2234 if (!missing_feat_read) {
2235 fnvlist_add_boolean(spa->spa_load_info,
2236 ZPOOL_CONFIG_CAN_RDONLY);
2240 * If the state is SPA_LOAD_TRYIMPORT, our objective is
2241 * twofold: to determine whether the pool is available for
2242 * import in read-write mode and (if it is not) whether the
2243 * pool is available for import in read-only mode. If the pool
2244 * is available for import in read-write mode, it is displayed
2245 * as available in userland; if it is not available for import
2246 * in read-only mode, it is displayed as unavailable in
2247 * userland. If the pool is available for import in read-only
2248 * mode but not read-write mode, it is displayed as unavailable
2249 * in userland with a special note that the pool is actually
2250 * available for open in read-only mode.
2252 * As a result, if the state is SPA_LOAD_TRYIMPORT and we are
2253 * missing a feature for write, we must first determine whether
2254 * the pool can be opened read-only before returning to
2255 * userland in order to know whether to display the
2256 * abovementioned note.
2258 if (missing_feat_read || (missing_feat_write &&
2259 spa_writeable(spa))) {
2260 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
2261 ENOTSUP));
2265 spa->spa_is_initializing = B_TRUE;
2266 error = dsl_pool_open(spa->spa_dsl_pool);
2267 spa->spa_is_initializing = B_FALSE;
2268 if (error != 0)
2269 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2271 if (!mosconfig) {
2272 uint64_t hostid;
2273 nvlist_t *policy = NULL, *nvconfig;
2275 if (load_nvlist(spa, spa->spa_config_object, &nvconfig) != 0)
2276 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2278 if (!spa_is_root(spa) && nvlist_lookup_uint64(nvconfig,
2279 ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
2280 char *hostname;
2281 unsigned long myhostid = 0;
2283 VERIFY(nvlist_lookup_string(nvconfig,
2284 ZPOOL_CONFIG_HOSTNAME, &hostname) == 0);
2286 #ifdef _KERNEL
2287 myhostid = zone_get_hostid(NULL);
2288 #else /* _KERNEL */
2290 * We're emulating the system's hostid in userland, so
2291 * we can't use zone_get_hostid().
2293 (void) ddi_strtoul(hw_serial, NULL, 10, &myhostid);
2294 #endif /* _KERNEL */
2295 if (hostid != 0 && myhostid != 0 &&
2296 hostid != myhostid) {
2297 nvlist_free(nvconfig);
2298 cmn_err(CE_WARN, "pool '%s' could not be "
2299 "loaded as it was last accessed by "
2300 "another system (host: %s hostid: 0x%lx). "
2301 "See: http://illumos.org/msg/ZFS-8000-EY",
2302 spa_name(spa), hostname,
2303 (unsigned long)hostid);
2304 return (EBADF);
2307 if (nvlist_lookup_nvlist(spa->spa_config,
2308 ZPOOL_REWIND_POLICY, &policy) == 0)
2309 VERIFY(nvlist_add_nvlist(nvconfig,
2310 ZPOOL_REWIND_POLICY, policy) == 0);
2312 spa_config_set(spa, nvconfig);
2313 spa_unload(spa);
2314 spa_deactivate(spa);
2315 spa_activate(spa, orig_mode);
2317 return (spa_load(spa, state, SPA_IMPORT_EXISTING, B_TRUE));
2320 if (spa_dir_prop(spa, DMU_POOL_SYNC_BPOBJ, &obj) != 0)
2321 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2322 error = bpobj_open(&spa->spa_deferred_bpobj, spa->spa_meta_objset, obj);
2323 if (error != 0)
2324 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2327 * Load the bit that tells us to use the new accounting function
2328 * (raid-z deflation). If we have an older pool, this will not
2329 * be present.
2331 error = spa_dir_prop(spa, DMU_POOL_DEFLATE, &spa->spa_deflate);
2332 if (error != 0 && error != ENOENT)
2333 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2335 error = spa_dir_prop(spa, DMU_POOL_CREATION_VERSION,
2336 &spa->spa_creation_version);
2337 if (error != 0 && error != ENOENT)
2338 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2341 * Load the persistent error log. If we have an older pool, this will
2342 * not be present.
2344 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_LAST, &spa->spa_errlog_last);
2345 if (error != 0 && error != ENOENT)
2346 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2348 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_SCRUB,
2349 &spa->spa_errlog_scrub);
2350 if (error != 0 && error != ENOENT)
2351 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2354 * Load the history object. If we have an older pool, this
2355 * will not be present.
2357 error = spa_dir_prop(spa, DMU_POOL_HISTORY, &spa->spa_history);
2358 if (error != 0 && error != ENOENT)
2359 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2362 * If we're assembling the pool from the split-off vdevs of
2363 * an existing pool, we don't want to attach the spares & cache
2364 * devices.
2368 * Load any hot spares for this pool.
2370 error = spa_dir_prop(spa, DMU_POOL_SPARES, &spa->spa_spares.sav_object);
2371 if (error != 0 && error != ENOENT)
2372 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2373 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
2374 ASSERT(spa_version(spa) >= SPA_VERSION_SPARES);
2375 if (load_nvlist(spa, spa->spa_spares.sav_object,
2376 &spa->spa_spares.sav_config) != 0)
2377 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2379 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2380 spa_load_spares(spa);
2381 spa_config_exit(spa, SCL_ALL, FTAG);
2382 } else if (error == 0) {
2383 spa->spa_spares.sav_sync = B_TRUE;
2387 * Load any level 2 ARC devices for this pool.
2389 error = spa_dir_prop(spa, DMU_POOL_L2CACHE,
2390 &spa->spa_l2cache.sav_object);
2391 if (error != 0 && error != ENOENT)
2392 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2393 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
2394 ASSERT(spa_version(spa) >= SPA_VERSION_L2CACHE);
2395 if (load_nvlist(spa, spa->spa_l2cache.sav_object,
2396 &spa->spa_l2cache.sav_config) != 0)
2397 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2399 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2400 spa_load_l2cache(spa);
2401 spa_config_exit(spa, SCL_ALL, FTAG);
2402 } else if (error == 0) {
2403 spa->spa_l2cache.sav_sync = B_TRUE;
2406 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
2408 error = spa_dir_prop(spa, DMU_POOL_PROPS, &spa->spa_pool_props_object);
2409 if (error && error != ENOENT)
2410 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2412 if (error == 0) {
2413 uint64_t autoreplace;
2415 spa_prop_find(spa, ZPOOL_PROP_BOOTFS, &spa->spa_bootfs);
2416 spa_prop_find(spa, ZPOOL_PROP_AUTOREPLACE, &autoreplace);
2417 spa_prop_find(spa, ZPOOL_PROP_DELEGATION, &spa->spa_delegation);
2418 spa_prop_find(spa, ZPOOL_PROP_FAILUREMODE, &spa->spa_failmode);
2419 spa_prop_find(spa, ZPOOL_PROP_AUTOEXPAND, &spa->spa_autoexpand);
2420 spa_prop_find(spa, ZPOOL_PROP_DEDUPDITTO,
2421 &spa->spa_dedup_ditto);
2423 spa->spa_autoreplace = (autoreplace != 0);
2427 * If the 'autoreplace' property is set, then post a resource notifying
2428 * the ZFS DE that it should not issue any faults for unopenable
2429 * devices. We also iterate over the vdevs, and post a sysevent for any
2430 * unopenable vdevs so that the normal autoreplace handler can take
2431 * over.
2433 if (spa->spa_autoreplace && state != SPA_LOAD_TRYIMPORT) {
2434 spa_check_removed(spa->spa_root_vdev);
2436 * For the import case, this is done in spa_import(), because
2437 * at this point we're using the spare definitions from
2438 * the MOS config, not necessarily from the userland config.
2440 if (state != SPA_LOAD_IMPORT) {
2441 spa_aux_check_removed(&spa->spa_spares);
2442 spa_aux_check_removed(&spa->spa_l2cache);
2447 * Load the vdev state for all toplevel vdevs.
2449 vdev_load(rvd);
2452 * Propagate the leaf DTLs we just loaded all the way up the tree.
2454 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2455 vdev_dtl_reassess(rvd, 0, 0, B_FALSE);
2456 spa_config_exit(spa, SCL_ALL, FTAG);
2459 * Load the DDTs (dedup tables).
2461 error = ddt_load(spa);
2462 if (error != 0)
2463 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2465 spa_update_dspace(spa);
2468 * Validate the config, using the MOS config to fill in any
2469 * information which might be missing. If we fail to validate
2470 * the config then declare the pool unfit for use. If we're
2471 * assembling a pool from a split, the log is not transferred
2472 * over.
2474 if (type != SPA_IMPORT_ASSEMBLE) {
2475 nvlist_t *nvconfig;
2477 if (load_nvlist(spa, spa->spa_config_object, &nvconfig) != 0)
2478 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2480 if (!spa_config_valid(spa, nvconfig)) {
2481 nvlist_free(nvconfig);
2482 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM,
2483 ENXIO));
2485 nvlist_free(nvconfig);
2488 * Now that we've validated the config, check the state of the
2489 * root vdev. If it can't be opened, it indicates one or
2490 * more toplevel vdevs are faulted.
2492 if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN)
2493 return (ENXIO);
2495 if (spa_check_logs(spa)) {
2496 *ereport = FM_EREPORT_ZFS_LOG_REPLAY;
2497 return (spa_vdev_err(rvd, VDEV_AUX_BAD_LOG, ENXIO));
2501 if (missing_feat_write) {
2502 ASSERT(state == SPA_LOAD_TRYIMPORT);
2505 * At this point, we know that we can open the pool in
2506 * read-only mode but not read-write mode. We now have enough
2507 * information and can return to userland.
2509 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT, ENOTSUP));
2513 * We've successfully opened the pool, verify that we're ready
2514 * to start pushing transactions.
2516 if (state != SPA_LOAD_TRYIMPORT) {
2517 if (error = spa_load_verify(spa))
2518 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2519 error));
2522 if (spa_writeable(spa) && (state == SPA_LOAD_RECOVER ||
2523 spa->spa_load_max_txg == UINT64_MAX)) {
2524 dmu_tx_t *tx;
2525 int need_update = B_FALSE;
2527 ASSERT(state != SPA_LOAD_TRYIMPORT);
2530 * Claim log blocks that haven't been committed yet.
2531 * This must all happen in a single txg.
2532 * Note: spa_claim_max_txg is updated by spa_claim_notify(),
2533 * invoked from zil_claim_log_block()'s i/o done callback.
2534 * Price of rollback is that we abandon the log.
2536 spa->spa_claiming = B_TRUE;
2538 tx = dmu_tx_create_assigned(spa_get_dsl(spa),
2539 spa_first_txg(spa));
2540 (void) dmu_objset_find(spa_name(spa),
2541 zil_claim, tx, DS_FIND_CHILDREN);
2542 dmu_tx_commit(tx);
2544 spa->spa_claiming = B_FALSE;
2546 spa_set_log_state(spa, SPA_LOG_GOOD);
2547 spa->spa_sync_on = B_TRUE;
2548 txg_sync_start(spa->spa_dsl_pool);
2551 * Wait for all claims to sync. We sync up to the highest
2552 * claimed log block birth time so that claimed log blocks
2553 * don't appear to be from the future. spa_claim_max_txg
2554 * will have been set for us by either zil_check_log_chain()
2555 * (invoked from spa_check_logs()) or zil_claim() above.
2557 txg_wait_synced(spa->spa_dsl_pool, spa->spa_claim_max_txg);
2560 * If the config cache is stale, or we have uninitialized
2561 * metaslabs (see spa_vdev_add()), then update the config.
2563 * If this is a verbatim import, trust the current
2564 * in-core spa_config and update the disk labels.
2566 if (config_cache_txg != spa->spa_config_txg ||
2567 state == SPA_LOAD_IMPORT ||
2568 state == SPA_LOAD_RECOVER ||
2569 (spa->spa_import_flags & ZFS_IMPORT_VERBATIM))
2570 need_update = B_TRUE;
2572 for (int c = 0; c < rvd->vdev_children; c++)
2573 if (rvd->vdev_child[c]->vdev_ms_array == 0)
2574 need_update = B_TRUE;
2577 * Update the config cache asychronously in case we're the
2578 * root pool, in which case the config cache isn't writable yet.
2580 if (need_update)
2581 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
2584 * Check all DTLs to see if anything needs resilvering.
2586 if (!dsl_scan_resilvering(spa->spa_dsl_pool) &&
2587 vdev_resilver_needed(rvd, NULL, NULL))
2588 spa_async_request(spa, SPA_ASYNC_RESILVER);
2591 * Log the fact that we booted up (so that we can detect if
2592 * we rebooted in the middle of an operation).
2594 spa_history_log_version(spa, "open");
2597 * Delete any inconsistent datasets.
2599 (void) dmu_objset_find(spa_name(spa),
2600 dsl_destroy_inconsistent, NULL, DS_FIND_CHILDREN);
2603 * Clean up any stale temporary dataset userrefs.
2605 dsl_pool_clean_tmp_userrefs(spa->spa_dsl_pool);
2608 return (0);
2611 static int
2612 spa_load_retry(spa_t *spa, spa_load_state_t state, int mosconfig)
2614 int mode = spa->spa_mode;
2616 spa_unload(spa);
2617 spa_deactivate(spa);
2619 spa->spa_load_max_txg--;
2621 spa_activate(spa, mode);
2622 spa_async_suspend(spa);
2624 return (spa_load(spa, state, SPA_IMPORT_EXISTING, mosconfig));
2628 * If spa_load() fails this function will try loading prior txg's. If
2629 * 'state' is SPA_LOAD_RECOVER and one of these loads succeeds the pool
2630 * will be rewound to that txg. If 'state' is not SPA_LOAD_RECOVER this
2631 * function will not rewind the pool and will return the same error as
2632 * spa_load().
2634 static int
2635 spa_load_best(spa_t *spa, spa_load_state_t state, int mosconfig,
2636 uint64_t max_request, int rewind_flags)
2638 nvlist_t *loadinfo = NULL;
2639 nvlist_t *config = NULL;
2640 int load_error, rewind_error;
2641 uint64_t safe_rewind_txg;
2642 uint64_t min_txg;
2644 if (spa->spa_load_txg && state == SPA_LOAD_RECOVER) {
2645 spa->spa_load_max_txg = spa->spa_load_txg;
2646 spa_set_log_state(spa, SPA_LOG_CLEAR);
2647 } else {
2648 spa->spa_load_max_txg = max_request;
2651 load_error = rewind_error = spa_load(spa, state, SPA_IMPORT_EXISTING,
2652 mosconfig);
2653 if (load_error == 0)
2654 return (0);
2656 if (spa->spa_root_vdev != NULL)
2657 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
2659 spa->spa_last_ubsync_txg = spa->spa_uberblock.ub_txg;
2660 spa->spa_last_ubsync_txg_ts = spa->spa_uberblock.ub_timestamp;
2662 if (rewind_flags & ZPOOL_NEVER_REWIND) {
2663 nvlist_free(config);
2664 return (load_error);
2667 if (state == SPA_LOAD_RECOVER) {
2668 /* Price of rolling back is discarding txgs, including log */
2669 spa_set_log_state(spa, SPA_LOG_CLEAR);
2670 } else {
2672 * If we aren't rolling back save the load info from our first
2673 * import attempt so that we can restore it after attempting
2674 * to rewind.
2676 loadinfo = spa->spa_load_info;
2677 spa->spa_load_info = fnvlist_alloc();
2680 spa->spa_load_max_txg = spa->spa_last_ubsync_txg;
2681 safe_rewind_txg = spa->spa_last_ubsync_txg - TXG_DEFER_SIZE;
2682 min_txg = (rewind_flags & ZPOOL_EXTREME_REWIND) ?
2683 TXG_INITIAL : safe_rewind_txg;
2686 * Continue as long as we're finding errors, we're still within
2687 * the acceptable rewind range, and we're still finding uberblocks
2689 while (rewind_error && spa->spa_uberblock.ub_txg >= min_txg &&
2690 spa->spa_uberblock.ub_txg <= spa->spa_load_max_txg) {
2691 if (spa->spa_load_max_txg < safe_rewind_txg)
2692 spa->spa_extreme_rewind = B_TRUE;
2693 rewind_error = spa_load_retry(spa, state, mosconfig);
2696 spa->spa_extreme_rewind = B_FALSE;
2697 spa->spa_load_max_txg = UINT64_MAX;
2699 if (config && (rewind_error || state != SPA_LOAD_RECOVER))
2700 spa_config_set(spa, config);
2702 if (state == SPA_LOAD_RECOVER) {
2703 ASSERT3P(loadinfo, ==, NULL);
2704 return (rewind_error);
2705 } else {
2706 /* Store the rewind info as part of the initial load info */
2707 fnvlist_add_nvlist(loadinfo, ZPOOL_CONFIG_REWIND_INFO,
2708 spa->spa_load_info);
2710 /* Restore the initial load info */
2711 fnvlist_free(spa->spa_load_info);
2712 spa->spa_load_info = loadinfo;
2714 return (load_error);
2719 * Pool Open/Import
2721 * The import case is identical to an open except that the configuration is sent
2722 * down from userland, instead of grabbed from the configuration cache. For the
2723 * case of an open, the pool configuration will exist in the
2724 * POOL_STATE_UNINITIALIZED state.
2726 * The stats information (gen/count/ustats) is used to gather vdev statistics at
2727 * the same time open the pool, without having to keep around the spa_t in some
2728 * ambiguous state.
2730 static int
2731 spa_open_common(const char *pool, spa_t **spapp, void *tag, nvlist_t *nvpolicy,
2732 nvlist_t **config)
2734 spa_t *spa;
2735 spa_load_state_t state = SPA_LOAD_OPEN;
2736 int error;
2737 int locked = B_FALSE;
2739 *spapp = NULL;
2742 * As disgusting as this is, we need to support recursive calls to this
2743 * function because dsl_dir_open() is called during spa_load(), and ends
2744 * up calling spa_open() again. The real fix is to figure out how to
2745 * avoid dsl_dir_open() calling this in the first place.
2747 if (mutex_owner(&spa_namespace_lock) != curthread) {
2748 mutex_enter(&spa_namespace_lock);
2749 locked = B_TRUE;
2752 if ((spa = spa_lookup(pool)) == NULL) {
2753 if (locked)
2754 mutex_exit(&spa_namespace_lock);
2755 return (ENOENT);
2758 if (spa->spa_state == POOL_STATE_UNINITIALIZED) {
2759 zpool_rewind_policy_t policy;
2761 zpool_get_rewind_policy(nvpolicy ? nvpolicy : spa->spa_config,
2762 &policy);
2763 if (policy.zrp_request & ZPOOL_DO_REWIND)
2764 state = SPA_LOAD_RECOVER;
2766 spa_activate(spa, spa_mode_global);
2768 if (state != SPA_LOAD_RECOVER)
2769 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
2771 error = spa_load_best(spa, state, B_FALSE, policy.zrp_txg,
2772 policy.zrp_request);
2774 if (error == EBADF) {
2776 * If vdev_validate() returns failure (indicated by
2777 * EBADF), it indicates that one of the vdevs indicates
2778 * that the pool has been exported or destroyed. If
2779 * this is the case, the config cache is out of sync and
2780 * we should remove the pool from the namespace.
2782 spa_unload(spa);
2783 spa_deactivate(spa);
2784 spa_config_sync(spa, B_TRUE, B_TRUE);
2785 spa_remove(spa);
2786 if (locked)
2787 mutex_exit(&spa_namespace_lock);
2788 return (ENOENT);
2791 if (error) {
2793 * We can't open the pool, but we still have useful
2794 * information: the state of each vdev after the
2795 * attempted vdev_open(). Return this to the user.
2797 if (config != NULL && spa->spa_config) {
2798 VERIFY(nvlist_dup(spa->spa_config, config,
2799 KM_SLEEP) == 0);
2800 VERIFY(nvlist_add_nvlist(*config,
2801 ZPOOL_CONFIG_LOAD_INFO,
2802 spa->spa_load_info) == 0);
2804 spa_unload(spa);
2805 spa_deactivate(spa);
2806 spa->spa_last_open_failed = error;
2807 if (locked)
2808 mutex_exit(&spa_namespace_lock);
2809 *spapp = NULL;
2810 return (error);
2814 spa_open_ref(spa, tag);
2816 if (config != NULL)
2817 *config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
2820 * If we've recovered the pool, pass back any information we
2821 * gathered while doing the load.
2823 if (state == SPA_LOAD_RECOVER) {
2824 VERIFY(nvlist_add_nvlist(*config, ZPOOL_CONFIG_LOAD_INFO,
2825 spa->spa_load_info) == 0);
2828 if (locked) {
2829 spa->spa_last_open_failed = 0;
2830 spa->spa_last_ubsync_txg = 0;
2831 spa->spa_load_txg = 0;
2832 mutex_exit(&spa_namespace_lock);
2835 *spapp = spa;
2837 return (0);
2841 spa_open_rewind(const char *name, spa_t **spapp, void *tag, nvlist_t *policy,
2842 nvlist_t **config)
2844 return (spa_open_common(name, spapp, tag, policy, config));
2848 spa_open(const char *name, spa_t **spapp, void *tag)
2850 return (spa_open_common(name, spapp, tag, NULL, NULL));
2854 * Lookup the given spa_t, incrementing the inject count in the process,
2855 * preventing it from being exported or destroyed.
2857 spa_t *
2858 spa_inject_addref(char *name)
2860 spa_t *spa;
2862 mutex_enter(&spa_namespace_lock);
2863 if ((spa = spa_lookup(name)) == NULL) {
2864 mutex_exit(&spa_namespace_lock);
2865 return (NULL);
2867 spa->spa_inject_ref++;
2868 mutex_exit(&spa_namespace_lock);
2870 return (spa);
2873 void
2874 spa_inject_delref(spa_t *spa)
2876 mutex_enter(&spa_namespace_lock);
2877 spa->spa_inject_ref--;
2878 mutex_exit(&spa_namespace_lock);
2882 * Add spares device information to the nvlist.
2884 static void
2885 spa_add_spares(spa_t *spa, nvlist_t *config)
2887 nvlist_t **spares;
2888 uint_t i, nspares;
2889 nvlist_t *nvroot;
2890 uint64_t guid;
2891 vdev_stat_t *vs;
2892 uint_t vsc;
2893 uint64_t pool;
2895 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
2897 if (spa->spa_spares.sav_count == 0)
2898 return;
2900 VERIFY(nvlist_lookup_nvlist(config,
2901 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
2902 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
2903 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
2904 if (nspares != 0) {
2905 VERIFY(nvlist_add_nvlist_array(nvroot,
2906 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
2907 VERIFY(nvlist_lookup_nvlist_array(nvroot,
2908 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
2911 * Go through and find any spares which have since been
2912 * repurposed as an active spare. If this is the case, update
2913 * their status appropriately.
2915 for (i = 0; i < nspares; i++) {
2916 VERIFY(nvlist_lookup_uint64(spares[i],
2917 ZPOOL_CONFIG_GUID, &guid) == 0);
2918 if (spa_spare_exists(guid, &pool, NULL) &&
2919 pool != 0ULL) {
2920 VERIFY(nvlist_lookup_uint64_array(
2921 spares[i], ZPOOL_CONFIG_VDEV_STATS,
2922 (uint64_t **)&vs, &vsc) == 0);
2923 vs->vs_state = VDEV_STATE_CANT_OPEN;
2924 vs->vs_aux = VDEV_AUX_SPARED;
2931 * Add l2cache device information to the nvlist, including vdev stats.
2933 static void
2934 spa_add_l2cache(spa_t *spa, nvlist_t *config)
2936 nvlist_t **l2cache;
2937 uint_t i, j, nl2cache;
2938 nvlist_t *nvroot;
2939 uint64_t guid;
2940 vdev_t *vd;
2941 vdev_stat_t *vs;
2942 uint_t vsc;
2944 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
2946 if (spa->spa_l2cache.sav_count == 0)
2947 return;
2949 VERIFY(nvlist_lookup_nvlist(config,
2950 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
2951 VERIFY(nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
2952 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
2953 if (nl2cache != 0) {
2954 VERIFY(nvlist_add_nvlist_array(nvroot,
2955 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
2956 VERIFY(nvlist_lookup_nvlist_array(nvroot,
2957 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
2960 * Update level 2 cache device stats.
2963 for (i = 0; i < nl2cache; i++) {
2964 VERIFY(nvlist_lookup_uint64(l2cache[i],
2965 ZPOOL_CONFIG_GUID, &guid) == 0);
2967 vd = NULL;
2968 for (j = 0; j < spa->spa_l2cache.sav_count; j++) {
2969 if (guid ==
2970 spa->spa_l2cache.sav_vdevs[j]->vdev_guid) {
2971 vd = spa->spa_l2cache.sav_vdevs[j];
2972 break;
2975 ASSERT(vd != NULL);
2977 VERIFY(nvlist_lookup_uint64_array(l2cache[i],
2978 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc)
2979 == 0);
2980 vdev_get_stats(vd, vs);
2985 static void
2986 spa_add_feature_stats(spa_t *spa, nvlist_t *config)
2988 nvlist_t *features;
2989 zap_cursor_t zc;
2990 zap_attribute_t za;
2992 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
2993 VERIFY(nvlist_alloc(&features, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2995 if (spa->spa_feat_for_read_obj != 0) {
2996 for (zap_cursor_init(&zc, spa->spa_meta_objset,
2997 spa->spa_feat_for_read_obj);
2998 zap_cursor_retrieve(&zc, &za) == 0;
2999 zap_cursor_advance(&zc)) {
3000 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
3001 za.za_num_integers == 1);
3002 VERIFY3U(0, ==, nvlist_add_uint64(features, za.za_name,
3003 za.za_first_integer));
3005 zap_cursor_fini(&zc);
3008 if (spa->spa_feat_for_write_obj != 0) {
3009 for (zap_cursor_init(&zc, spa->spa_meta_objset,
3010 spa->spa_feat_for_write_obj);
3011 zap_cursor_retrieve(&zc, &za) == 0;
3012 zap_cursor_advance(&zc)) {
3013 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
3014 za.za_num_integers == 1);
3015 VERIFY3U(0, ==, nvlist_add_uint64(features, za.za_name,
3016 za.za_first_integer));
3018 zap_cursor_fini(&zc);
3021 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_FEATURE_STATS,
3022 features) == 0);
3023 nvlist_free(features);
3027 spa_get_stats(const char *name, nvlist_t **config,
3028 char *altroot, size_t buflen)
3030 int error;
3031 spa_t *spa;
3033 *config = NULL;
3034 error = spa_open_common(name, &spa, FTAG, NULL, config);
3036 if (spa != NULL) {
3038 * This still leaves a window of inconsistency where the spares
3039 * or l2cache devices could change and the config would be
3040 * self-inconsistent.
3042 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3044 if (*config != NULL) {
3045 uint64_t loadtimes[2];
3047 loadtimes[0] = spa->spa_loaded_ts.tv_sec;
3048 loadtimes[1] = spa->spa_loaded_ts.tv_nsec;
3049 VERIFY(nvlist_add_uint64_array(*config,
3050 ZPOOL_CONFIG_LOADED_TIME, loadtimes, 2) == 0);
3052 VERIFY(nvlist_add_uint64(*config,
3053 ZPOOL_CONFIG_ERRCOUNT,
3054 spa_get_errlog_size(spa)) == 0);
3056 if (spa_suspended(spa))
3057 VERIFY(nvlist_add_uint64(*config,
3058 ZPOOL_CONFIG_SUSPENDED,
3059 spa->spa_failmode) == 0);
3061 spa_add_spares(spa, *config);
3062 spa_add_l2cache(spa, *config);
3063 spa_add_feature_stats(spa, *config);
3068 * We want to get the alternate root even for faulted pools, so we cheat
3069 * and call spa_lookup() directly.
3071 if (altroot) {
3072 if (spa == NULL) {
3073 mutex_enter(&spa_namespace_lock);
3074 spa = spa_lookup(name);
3075 if (spa)
3076 spa_altroot(spa, altroot, buflen);
3077 else
3078 altroot[0] = '\0';
3079 spa = NULL;
3080 mutex_exit(&spa_namespace_lock);
3081 } else {
3082 spa_altroot(spa, altroot, buflen);
3086 if (spa != NULL) {
3087 spa_config_exit(spa, SCL_CONFIG, FTAG);
3088 spa_close(spa, FTAG);
3091 return (error);
3095 * Validate that the auxiliary device array is well formed. We must have an
3096 * array of nvlists, each which describes a valid leaf vdev. If this is an
3097 * import (mode is VDEV_ALLOC_SPARE), then we allow corrupted spares to be
3098 * specified, as long as they are well-formed.
3100 static int
3101 spa_validate_aux_devs(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode,
3102 spa_aux_vdev_t *sav, const char *config, uint64_t version,
3103 vdev_labeltype_t label)
3105 nvlist_t **dev;
3106 uint_t i, ndev;
3107 vdev_t *vd;
3108 int error;
3110 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
3113 * It's acceptable to have no devs specified.
3115 if (nvlist_lookup_nvlist_array(nvroot, config, &dev, &ndev) != 0)
3116 return (0);
3118 if (ndev == 0)
3119 return (EINVAL);
3122 * Make sure the pool is formatted with a version that supports this
3123 * device type.
3125 if (spa_version(spa) < version)
3126 return (ENOTSUP);
3129 * Set the pending device list so we correctly handle device in-use
3130 * checking.
3132 sav->sav_pending = dev;
3133 sav->sav_npending = ndev;
3135 for (i = 0; i < ndev; i++) {
3136 if ((error = spa_config_parse(spa, &vd, dev[i], NULL, 0,
3137 mode)) != 0)
3138 goto out;
3140 if (!vd->vdev_ops->vdev_op_leaf) {
3141 vdev_free(vd);
3142 error = EINVAL;
3143 goto out;
3147 * The L2ARC currently only supports disk devices in
3148 * kernel context. For user-level testing, we allow it.
3150 #ifdef _KERNEL
3151 if ((strcmp(config, ZPOOL_CONFIG_L2CACHE) == 0) &&
3152 strcmp(vd->vdev_ops->vdev_op_type, VDEV_TYPE_DISK) != 0) {
3153 error = ENOTBLK;
3154 vdev_free(vd);
3155 goto out;
3157 #endif
3158 vd->vdev_top = vd;
3160 if ((error = vdev_open(vd)) == 0 &&
3161 (error = vdev_label_init(vd, crtxg, label)) == 0) {
3162 VERIFY(nvlist_add_uint64(dev[i], ZPOOL_CONFIG_GUID,
3163 vd->vdev_guid) == 0);
3166 vdev_free(vd);
3168 if (error &&
3169 (mode != VDEV_ALLOC_SPARE && mode != VDEV_ALLOC_L2CACHE))
3170 goto out;
3171 else
3172 error = 0;
3175 out:
3176 sav->sav_pending = NULL;
3177 sav->sav_npending = 0;
3178 return (error);
3181 static int
3182 spa_validate_aux(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode)
3184 int error;
3186 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
3188 if ((error = spa_validate_aux_devs(spa, nvroot, crtxg, mode,
3189 &spa->spa_spares, ZPOOL_CONFIG_SPARES, SPA_VERSION_SPARES,
3190 VDEV_LABEL_SPARE)) != 0) {
3191 return (error);
3194 return (spa_validate_aux_devs(spa, nvroot, crtxg, mode,
3195 &spa->spa_l2cache, ZPOOL_CONFIG_L2CACHE, SPA_VERSION_L2CACHE,
3196 VDEV_LABEL_L2CACHE));
3199 static void
3200 spa_set_aux_vdevs(spa_aux_vdev_t *sav, nvlist_t **devs, int ndevs,
3201 const char *config)
3203 int i;
3205 if (sav->sav_config != NULL) {
3206 nvlist_t **olddevs;
3207 uint_t oldndevs;
3208 nvlist_t **newdevs;
3211 * Generate new dev list by concatentating with the
3212 * current dev list.
3214 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config, config,
3215 &olddevs, &oldndevs) == 0);
3217 newdevs = kmem_alloc(sizeof (void *) *
3218 (ndevs + oldndevs), KM_SLEEP);
3219 for (i = 0; i < oldndevs; i++)
3220 VERIFY(nvlist_dup(olddevs[i], &newdevs[i],
3221 KM_SLEEP) == 0);
3222 for (i = 0; i < ndevs; i++)
3223 VERIFY(nvlist_dup(devs[i], &newdevs[i + oldndevs],
3224 KM_SLEEP) == 0);
3226 VERIFY(nvlist_remove(sav->sav_config, config,
3227 DATA_TYPE_NVLIST_ARRAY) == 0);
3229 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
3230 config, newdevs, ndevs + oldndevs) == 0);
3231 for (i = 0; i < oldndevs + ndevs; i++)
3232 nvlist_free(newdevs[i]);
3233 kmem_free(newdevs, (oldndevs + ndevs) * sizeof (void *));
3234 } else {
3236 * Generate a new dev list.
3238 VERIFY(nvlist_alloc(&sav->sav_config, NV_UNIQUE_NAME,
3239 KM_SLEEP) == 0);
3240 VERIFY(nvlist_add_nvlist_array(sav->sav_config, config,
3241 devs, ndevs) == 0);
3246 * Stop and drop level 2 ARC devices
3248 void
3249 spa_l2cache_drop(spa_t *spa)
3251 vdev_t *vd;
3252 int i;
3253 spa_aux_vdev_t *sav = &spa->spa_l2cache;
3255 for (i = 0; i < sav->sav_count; i++) {
3256 uint64_t pool;
3258 vd = sav->sav_vdevs[i];
3259 ASSERT(vd != NULL);
3261 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
3262 pool != 0ULL && l2arc_vdev_present(vd))
3263 l2arc_remove_vdev(vd);
3268 * Pool Creation
3271 spa_create(const char *pool, nvlist_t *nvroot, nvlist_t *props,
3272 nvlist_t *zplprops)
3274 spa_t *spa;
3275 char *altroot = NULL;
3276 vdev_t *rvd;
3277 dsl_pool_t *dp;
3278 dmu_tx_t *tx;
3279 int error = 0;
3280 uint64_t txg = TXG_INITIAL;
3281 nvlist_t **spares, **l2cache;
3282 uint_t nspares, nl2cache;
3283 uint64_t version, obj;
3284 boolean_t has_features;
3287 * If this pool already exists, return failure.
3289 mutex_enter(&spa_namespace_lock);
3290 if (spa_lookup(pool) != NULL) {
3291 mutex_exit(&spa_namespace_lock);
3292 return (EEXIST);
3296 * Allocate a new spa_t structure.
3298 (void) nvlist_lookup_string(props,
3299 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
3300 spa = spa_add(pool, NULL, altroot);
3301 spa_activate(spa, spa_mode_global);
3303 if (props && (error = spa_prop_validate(spa, props))) {
3304 spa_deactivate(spa);
3305 spa_remove(spa);
3306 mutex_exit(&spa_namespace_lock);
3307 return (error);
3310 has_features = B_FALSE;
3311 for (nvpair_t *elem = nvlist_next_nvpair(props, NULL);
3312 elem != NULL; elem = nvlist_next_nvpair(props, elem)) {
3313 if (zpool_prop_feature(nvpair_name(elem)))
3314 has_features = B_TRUE;
3317 if (has_features || nvlist_lookup_uint64(props,
3318 zpool_prop_to_name(ZPOOL_PROP_VERSION), &version) != 0) {
3319 version = SPA_VERSION;
3321 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
3323 spa->spa_first_txg = txg;
3324 spa->spa_uberblock.ub_txg = txg - 1;
3325 spa->spa_uberblock.ub_version = version;
3326 spa->spa_ubsync = spa->spa_uberblock;
3329 * Create "The Godfather" zio to hold all async IOs
3331 spa->spa_async_zio_root = zio_root(spa, NULL, NULL,
3332 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE | ZIO_FLAG_GODFATHER);
3335 * Create the root vdev.
3337 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3339 error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, VDEV_ALLOC_ADD);
3341 ASSERT(error != 0 || rvd != NULL);
3342 ASSERT(error != 0 || spa->spa_root_vdev == rvd);
3344 if (error == 0 && !zfs_allocatable_devs(nvroot))
3345 error = EINVAL;
3347 if (error == 0 &&
3348 (error = vdev_create(rvd, txg, B_FALSE)) == 0 &&
3349 (error = spa_validate_aux(spa, nvroot, txg,
3350 VDEV_ALLOC_ADD)) == 0) {
3351 for (int c = 0; c < rvd->vdev_children; c++) {
3352 vdev_metaslab_set_size(rvd->vdev_child[c]);
3353 vdev_expand(rvd->vdev_child[c], txg);
3357 spa_config_exit(spa, SCL_ALL, FTAG);
3359 if (error != 0) {
3360 spa_unload(spa);
3361 spa_deactivate(spa);
3362 spa_remove(spa);
3363 mutex_exit(&spa_namespace_lock);
3364 return (error);
3368 * Get the list of spares, if specified.
3370 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
3371 &spares, &nspares) == 0) {
3372 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config, NV_UNIQUE_NAME,
3373 KM_SLEEP) == 0);
3374 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
3375 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
3376 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3377 spa_load_spares(spa);
3378 spa_config_exit(spa, SCL_ALL, FTAG);
3379 spa->spa_spares.sav_sync = B_TRUE;
3383 * Get the list of level 2 cache devices, if specified.
3385 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
3386 &l2cache, &nl2cache) == 0) {
3387 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
3388 NV_UNIQUE_NAME, KM_SLEEP) == 0);
3389 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
3390 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
3391 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3392 spa_load_l2cache(spa);
3393 spa_config_exit(spa, SCL_ALL, FTAG);
3394 spa->spa_l2cache.sav_sync = B_TRUE;
3397 spa->spa_is_initializing = B_TRUE;
3398 spa->spa_dsl_pool = dp = dsl_pool_create(spa, zplprops, txg);
3399 spa->spa_meta_objset = dp->dp_meta_objset;
3400 spa->spa_is_initializing = B_FALSE;
3403 * Create DDTs (dedup tables).
3405 ddt_create(spa);
3407 spa_update_dspace(spa);
3409 tx = dmu_tx_create_assigned(dp, txg);
3412 * Create the pool config object.
3414 spa->spa_config_object = dmu_object_alloc(spa->spa_meta_objset,
3415 DMU_OT_PACKED_NVLIST, SPA_CONFIG_BLOCKSIZE,
3416 DMU_OT_PACKED_NVLIST_SIZE, sizeof (uint64_t), tx);
3418 if (zap_add(spa->spa_meta_objset,
3419 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CONFIG,
3420 sizeof (uint64_t), 1, &spa->spa_config_object, tx) != 0) {
3421 cmn_err(CE_PANIC, "failed to add pool config");
3424 if (spa_version(spa) >= SPA_VERSION_FEATURES)
3425 spa_feature_create_zap_objects(spa, tx);
3427 if (zap_add(spa->spa_meta_objset,
3428 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CREATION_VERSION,
3429 sizeof (uint64_t), 1, &version, tx) != 0) {
3430 cmn_err(CE_PANIC, "failed to add pool version");
3433 /* Newly created pools with the right version are always deflated. */
3434 if (version >= SPA_VERSION_RAIDZ_DEFLATE) {
3435 spa->spa_deflate = TRUE;
3436 if (zap_add(spa->spa_meta_objset,
3437 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
3438 sizeof (uint64_t), 1, &spa->spa_deflate, tx) != 0) {
3439 cmn_err(CE_PANIC, "failed to add deflate");
3444 * Create the deferred-free bpobj. Turn off compression
3445 * because sync-to-convergence takes longer if the blocksize
3446 * keeps changing.
3448 obj = bpobj_alloc(spa->spa_meta_objset, 1 << 14, tx);
3449 dmu_object_set_compress(spa->spa_meta_objset, obj,
3450 ZIO_COMPRESS_OFF, tx);
3451 if (zap_add(spa->spa_meta_objset,
3452 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SYNC_BPOBJ,
3453 sizeof (uint64_t), 1, &obj, tx) != 0) {
3454 cmn_err(CE_PANIC, "failed to add bpobj");
3456 VERIFY3U(0, ==, bpobj_open(&spa->spa_deferred_bpobj,
3457 spa->spa_meta_objset, obj));
3460 * Create the pool's history object.
3462 if (version >= SPA_VERSION_ZPOOL_HISTORY)
3463 spa_history_create_obj(spa, tx);
3466 * Set pool properties.
3468 spa->spa_bootfs = zpool_prop_default_numeric(ZPOOL_PROP_BOOTFS);
3469 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
3470 spa->spa_failmode = zpool_prop_default_numeric(ZPOOL_PROP_FAILUREMODE);
3471 spa->spa_autoexpand = zpool_prop_default_numeric(ZPOOL_PROP_AUTOEXPAND);
3473 if (props != NULL) {
3474 spa_configfile_set(spa, props, B_FALSE);
3475 spa_sync_props(spa, props, tx);
3478 dmu_tx_commit(tx);
3480 spa->spa_sync_on = B_TRUE;
3481 txg_sync_start(spa->spa_dsl_pool);
3484 * We explicitly wait for the first transaction to complete so that our
3485 * bean counters are appropriately updated.
3487 txg_wait_synced(spa->spa_dsl_pool, txg);
3489 spa_config_sync(spa, B_FALSE, B_TRUE);
3491 spa_history_log_version(spa, "create");
3493 spa->spa_minref = refcount_count(&spa->spa_refcount);
3495 mutex_exit(&spa_namespace_lock);
3497 return (0);
3500 #ifdef _KERNEL
3502 * Get the root pool information from the root disk, then import the root pool
3503 * during the system boot up time.
3505 extern int vdev_disk_read_rootlabel(char *, char *, nvlist_t **);
3507 static nvlist_t *
3508 spa_generate_rootconf(char *devpath, char *devid, uint64_t *guid)
3510 nvlist_t *config;
3511 nvlist_t *nvtop, *nvroot;
3512 uint64_t pgid;
3514 if (vdev_disk_read_rootlabel(devpath, devid, &config) != 0)
3515 return (NULL);
3518 * Add this top-level vdev to the child array.
3520 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3521 &nvtop) == 0);
3522 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
3523 &pgid) == 0);
3524 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID, guid) == 0);
3527 * Put this pool's top-level vdevs into a root vdev.
3529 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
3530 VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
3531 VDEV_TYPE_ROOT) == 0);
3532 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
3533 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
3534 VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
3535 &nvtop, 1) == 0);
3538 * Replace the existing vdev_tree with the new root vdev in
3539 * this pool's configuration (remove the old, add the new).
3541 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
3542 nvlist_free(nvroot);
3543 return (config);
3547 * Walk the vdev tree and see if we can find a device with "better"
3548 * configuration. A configuration is "better" if the label on that
3549 * device has a more recent txg.
3551 static void
3552 spa_alt_rootvdev(vdev_t *vd, vdev_t **avd, uint64_t *txg)
3554 for (int c = 0; c < vd->vdev_children; c++)
3555 spa_alt_rootvdev(vd->vdev_child[c], avd, txg);
3557 if (vd->vdev_ops->vdev_op_leaf) {
3558 nvlist_t *label;
3559 uint64_t label_txg;
3561 if (vdev_disk_read_rootlabel(vd->vdev_physpath, vd->vdev_devid,
3562 &label) != 0)
3563 return;
3565 VERIFY(nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_TXG,
3566 &label_txg) == 0);
3569 * Do we have a better boot device?
3571 if (label_txg > *txg) {
3572 *txg = label_txg;
3573 *avd = vd;
3575 nvlist_free(label);
3580 * Import a root pool.
3582 * For x86. devpath_list will consist of devid and/or physpath name of
3583 * the vdev (e.g. "id1,sd@SSEAGATE..." or "/pci@1f,0/ide@d/disk@0,0:a").
3584 * The GRUB "findroot" command will return the vdev we should boot.
3586 * For Sparc, devpath_list consists the physpath name of the booting device
3587 * no matter the rootpool is a single device pool or a mirrored pool.
3588 * e.g.
3589 * "/pci@1f,0/ide@d/disk@0,0:a"
3592 spa_import_rootpool(char *devpath, char *devid)
3594 spa_t *spa;
3595 vdev_t *rvd, *bvd, *avd = NULL;
3596 nvlist_t *config, *nvtop;
3597 uint64_t guid, txg;
3598 char *pname;
3599 int error;
3602 * Read the label from the boot device and generate a configuration.
3604 config = spa_generate_rootconf(devpath, devid, &guid);
3605 #if defined(_OBP) && defined(_KERNEL)
3606 if (config == NULL) {
3607 if (strstr(devpath, "/iscsi/ssd") != NULL) {
3608 /* iscsi boot */
3609 get_iscsi_bootpath_phy(devpath);
3610 config = spa_generate_rootconf(devpath, devid, &guid);
3613 #endif
3614 if (config == NULL) {
3615 cmn_err(CE_NOTE, "Cannot read the pool label from '%s'",
3616 devpath);
3617 return (EIO);
3620 VERIFY(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
3621 &pname) == 0);
3622 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg) == 0);
3624 mutex_enter(&spa_namespace_lock);
3625 if ((spa = spa_lookup(pname)) != NULL) {
3627 * Remove the existing root pool from the namespace so that we
3628 * can replace it with the correct config we just read in.
3630 spa_remove(spa);
3633 spa = spa_add(pname, config, NULL);
3634 spa->spa_is_root = B_TRUE;
3635 spa->spa_import_flags = ZFS_IMPORT_VERBATIM;
3638 * Build up a vdev tree based on the boot device's label config.
3640 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3641 &nvtop) == 0);
3642 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3643 error = spa_config_parse(spa, &rvd, nvtop, NULL, 0,
3644 VDEV_ALLOC_ROOTPOOL);
3645 spa_config_exit(spa, SCL_ALL, FTAG);
3646 if (error) {
3647 mutex_exit(&spa_namespace_lock);
3648 nvlist_free(config);
3649 cmn_err(CE_NOTE, "Can not parse the config for pool '%s'",
3650 pname);
3651 return (error);
3655 * Get the boot vdev.
3657 if ((bvd = vdev_lookup_by_guid(rvd, guid)) == NULL) {
3658 cmn_err(CE_NOTE, "Can not find the boot vdev for guid %llu",
3659 (u_longlong_t)guid);
3660 error = ENOENT;
3661 goto out;
3665 * Determine if there is a better boot device.
3667 avd = bvd;
3668 spa_alt_rootvdev(rvd, &avd, &txg);
3669 if (avd != bvd) {
3670 cmn_err(CE_NOTE, "The boot device is 'degraded'. Please "
3671 "try booting from '%s'", avd->vdev_path);
3672 error = EINVAL;
3673 goto out;
3677 * If the boot device is part of a spare vdev then ensure that
3678 * we're booting off the active spare.
3680 if (bvd->vdev_parent->vdev_ops == &vdev_spare_ops &&
3681 !bvd->vdev_isspare) {
3682 cmn_err(CE_NOTE, "The boot device is currently spared. Please "
3683 "try booting from '%s'",
3684 bvd->vdev_parent->
3685 vdev_child[bvd->vdev_parent->vdev_children - 1]->vdev_path);
3686 error = EINVAL;
3687 goto out;
3690 error = 0;
3691 out:
3692 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3693 vdev_free(rvd);
3694 spa_config_exit(spa, SCL_ALL, FTAG);
3695 mutex_exit(&spa_namespace_lock);
3697 nvlist_free(config);
3698 return (error);
3701 #endif
3704 * Import a non-root pool into the system.
3707 spa_import(const char *pool, nvlist_t *config, nvlist_t *props, uint64_t flags)
3709 spa_t *spa;
3710 char *altroot = NULL;
3711 spa_load_state_t state = SPA_LOAD_IMPORT;
3712 zpool_rewind_policy_t policy;
3713 uint64_t mode = spa_mode_global;
3714 uint64_t readonly = B_FALSE;
3715 int error;
3716 nvlist_t *nvroot;
3717 nvlist_t **spares, **l2cache;
3718 uint_t nspares, nl2cache;
3721 * If a pool with this name exists, return failure.
3723 mutex_enter(&spa_namespace_lock);
3724 if (spa_lookup(pool) != NULL) {
3725 mutex_exit(&spa_namespace_lock);
3726 return (EEXIST);
3730 * Create and initialize the spa structure.
3732 (void) nvlist_lookup_string(props,
3733 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
3734 (void) nvlist_lookup_uint64(props,
3735 zpool_prop_to_name(ZPOOL_PROP_READONLY), &readonly);
3736 if (readonly)
3737 mode = FREAD;
3738 spa = spa_add(pool, config, altroot);
3739 spa->spa_import_flags = flags;
3742 * Verbatim import - Take a pool and insert it into the namespace
3743 * as if it had been loaded at boot.
3745 if (spa->spa_import_flags & ZFS_IMPORT_VERBATIM) {
3746 if (props != NULL)
3747 spa_configfile_set(spa, props, B_FALSE);
3749 spa_config_sync(spa, B_FALSE, B_TRUE);
3751 mutex_exit(&spa_namespace_lock);
3752 spa_history_log_version(spa, "import");
3754 return (0);
3757 spa_activate(spa, mode);
3760 * Don't start async tasks until we know everything is healthy.
3762 spa_async_suspend(spa);
3764 zpool_get_rewind_policy(config, &policy);
3765 if (policy.zrp_request & ZPOOL_DO_REWIND)
3766 state = SPA_LOAD_RECOVER;
3769 * Pass off the heavy lifting to spa_load(). Pass TRUE for mosconfig
3770 * because the user-supplied config is actually the one to trust when
3771 * doing an import.
3773 if (state != SPA_LOAD_RECOVER)
3774 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
3776 error = spa_load_best(spa, state, B_TRUE, policy.zrp_txg,
3777 policy.zrp_request);
3780 * Propagate anything learned while loading the pool and pass it
3781 * back to caller (i.e. rewind info, missing devices, etc).
3783 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
3784 spa->spa_load_info) == 0);
3786 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3788 * Toss any existing sparelist, as it doesn't have any validity
3789 * anymore, and conflicts with spa_has_spare().
3791 if (spa->spa_spares.sav_config) {
3792 nvlist_free(spa->spa_spares.sav_config);
3793 spa->spa_spares.sav_config = NULL;
3794 spa_load_spares(spa);
3796 if (spa->spa_l2cache.sav_config) {
3797 nvlist_free(spa->spa_l2cache.sav_config);
3798 spa->spa_l2cache.sav_config = NULL;
3799 spa_load_l2cache(spa);
3802 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3803 &nvroot) == 0);
3804 if (error == 0)
3805 error = spa_validate_aux(spa, nvroot, -1ULL,
3806 VDEV_ALLOC_SPARE);
3807 if (error == 0)
3808 error = spa_validate_aux(spa, nvroot, -1ULL,
3809 VDEV_ALLOC_L2CACHE);
3810 spa_config_exit(spa, SCL_ALL, FTAG);
3812 if (props != NULL)
3813 spa_configfile_set(spa, props, B_FALSE);
3815 if (error != 0 || (props && spa_writeable(spa) &&
3816 (error = spa_prop_set(spa, props)))) {
3817 spa_unload(spa);
3818 spa_deactivate(spa);
3819 spa_remove(spa);
3820 mutex_exit(&spa_namespace_lock);
3821 return (error);
3824 spa_async_resume(spa);
3827 * Override any spares and level 2 cache devices as specified by
3828 * the user, as these may have correct device names/devids, etc.
3830 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
3831 &spares, &nspares) == 0) {
3832 if (spa->spa_spares.sav_config)
3833 VERIFY(nvlist_remove(spa->spa_spares.sav_config,
3834 ZPOOL_CONFIG_SPARES, DATA_TYPE_NVLIST_ARRAY) == 0);
3835 else
3836 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config,
3837 NV_UNIQUE_NAME, KM_SLEEP) == 0);
3838 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
3839 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
3840 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3841 spa_load_spares(spa);
3842 spa_config_exit(spa, SCL_ALL, FTAG);
3843 spa->spa_spares.sav_sync = B_TRUE;
3845 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
3846 &l2cache, &nl2cache) == 0) {
3847 if (spa->spa_l2cache.sav_config)
3848 VERIFY(nvlist_remove(spa->spa_l2cache.sav_config,
3849 ZPOOL_CONFIG_L2CACHE, DATA_TYPE_NVLIST_ARRAY) == 0);
3850 else
3851 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
3852 NV_UNIQUE_NAME, KM_SLEEP) == 0);
3853 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
3854 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
3855 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3856 spa_load_l2cache(spa);
3857 spa_config_exit(spa, SCL_ALL, FTAG);
3858 spa->spa_l2cache.sav_sync = B_TRUE;
3862 * Check for any removed devices.
3864 if (spa->spa_autoreplace) {
3865 spa_aux_check_removed(&spa->spa_spares);
3866 spa_aux_check_removed(&spa->spa_l2cache);
3869 if (spa_writeable(spa)) {
3871 * Update the config cache to include the newly-imported pool.
3873 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
3877 * It's possible that the pool was expanded while it was exported.
3878 * We kick off an async task to handle this for us.
3880 spa_async_request(spa, SPA_ASYNC_AUTOEXPAND);
3882 mutex_exit(&spa_namespace_lock);
3883 spa_history_log_version(spa, "import");
3885 return (0);
3888 nvlist_t *
3889 spa_tryimport(nvlist_t *tryconfig)
3891 nvlist_t *config = NULL;
3892 char *poolname;
3893 spa_t *spa;
3894 uint64_t state;
3895 int error;
3897 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_POOL_NAME, &poolname))
3898 return (NULL);
3900 if (nvlist_lookup_uint64(tryconfig, ZPOOL_CONFIG_POOL_STATE, &state))
3901 return (NULL);
3904 * Create and initialize the spa structure.
3906 mutex_enter(&spa_namespace_lock);
3907 spa = spa_add(TRYIMPORT_NAME, tryconfig, NULL);
3908 spa_activate(spa, FREAD);
3911 * Pass off the heavy lifting to spa_load().
3912 * Pass TRUE for mosconfig because the user-supplied config
3913 * is actually the one to trust when doing an import.
3915 error = spa_load(spa, SPA_LOAD_TRYIMPORT, SPA_IMPORT_EXISTING, B_TRUE);
3918 * If 'tryconfig' was at least parsable, return the current config.
3920 if (spa->spa_root_vdev != NULL) {
3921 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
3922 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME,
3923 poolname) == 0);
3924 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
3925 state) == 0);
3926 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
3927 spa->spa_uberblock.ub_timestamp) == 0);
3928 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
3929 spa->spa_load_info) == 0);
3932 * If the bootfs property exists on this pool then we
3933 * copy it out so that external consumers can tell which
3934 * pools are bootable.
3936 if ((!error || error == EEXIST) && spa->spa_bootfs) {
3937 char *tmpname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
3940 * We have to play games with the name since the
3941 * pool was opened as TRYIMPORT_NAME.
3943 if (dsl_dsobj_to_dsname(spa_name(spa),
3944 spa->spa_bootfs, tmpname) == 0) {
3945 char *cp;
3946 char *dsname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
3948 cp = strchr(tmpname, '/');
3949 if (cp == NULL) {
3950 (void) strlcpy(dsname, tmpname,
3951 MAXPATHLEN);
3952 } else {
3953 (void) snprintf(dsname, MAXPATHLEN,
3954 "%s/%s", poolname, ++cp);
3956 VERIFY(nvlist_add_string(config,
3957 ZPOOL_CONFIG_BOOTFS, dsname) == 0);
3958 kmem_free(dsname, MAXPATHLEN);
3960 kmem_free(tmpname, MAXPATHLEN);
3964 * Add the list of hot spares and level 2 cache devices.
3966 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3967 spa_add_spares(spa, config);
3968 spa_add_l2cache(spa, config);
3969 spa_config_exit(spa, SCL_CONFIG, FTAG);
3972 spa_unload(spa);
3973 spa_deactivate(spa);
3974 spa_remove(spa);
3975 mutex_exit(&spa_namespace_lock);
3977 return (config);
3981 * Pool export/destroy
3983 * The act of destroying or exporting a pool is very simple. We make sure there
3984 * is no more pending I/O and any references to the pool are gone. Then, we
3985 * update the pool state and sync all the labels to disk, removing the
3986 * configuration from the cache afterwards. If the 'hardforce' flag is set, then
3987 * we don't sync the labels or remove the configuration cache.
3989 static int
3990 spa_export_common(char *pool, int new_state, nvlist_t **oldconfig,
3991 boolean_t force, boolean_t hardforce)
3993 spa_t *spa;
3995 if (oldconfig)
3996 *oldconfig = NULL;
3998 if (!(spa_mode_global & FWRITE))
3999 return (EROFS);
4001 mutex_enter(&spa_namespace_lock);
4002 if ((spa = spa_lookup(pool)) == NULL) {
4003 mutex_exit(&spa_namespace_lock);
4004 return (ENOENT);
4008 * Put a hold on the pool, drop the namespace lock, stop async tasks,
4009 * reacquire the namespace lock, and see if we can export.
4011 spa_open_ref(spa, FTAG);
4012 mutex_exit(&spa_namespace_lock);
4013 spa_async_suspend(spa);
4014 mutex_enter(&spa_namespace_lock);
4015 spa_close(spa, FTAG);
4018 * The pool will be in core if it's openable,
4019 * in which case we can modify its state.
4021 if (spa->spa_state != POOL_STATE_UNINITIALIZED && spa->spa_sync_on) {
4023 * Objsets may be open only because they're dirty, so we
4024 * have to force it to sync before checking spa_refcnt.
4026 txg_wait_synced(spa->spa_dsl_pool, 0);
4029 * A pool cannot be exported or destroyed if there are active
4030 * references. If we are resetting a pool, allow references by
4031 * fault injection handlers.
4033 if (!spa_refcount_zero(spa) ||
4034 (spa->spa_inject_ref != 0 &&
4035 new_state != POOL_STATE_UNINITIALIZED)) {
4036 spa_async_resume(spa);
4037 mutex_exit(&spa_namespace_lock);
4038 return (EBUSY);
4042 * A pool cannot be exported if it has an active shared spare.
4043 * This is to prevent other pools stealing the active spare
4044 * from an exported pool. At user's own will, such pool can
4045 * be forcedly exported.
4047 if (!force && new_state == POOL_STATE_EXPORTED &&
4048 spa_has_active_shared_spare(spa)) {
4049 spa_async_resume(spa);
4050 mutex_exit(&spa_namespace_lock);
4051 return (EXDEV);
4055 * We want this to be reflected on every label,
4056 * so mark them all dirty. spa_unload() will do the
4057 * final sync that pushes these changes out.
4059 if (new_state != POOL_STATE_UNINITIALIZED && !hardforce) {
4060 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4061 spa->spa_state = new_state;
4062 spa->spa_final_txg = spa_last_synced_txg(spa) +
4063 TXG_DEFER_SIZE + 1;
4064 vdev_config_dirty(spa->spa_root_vdev);
4065 spa_config_exit(spa, SCL_ALL, FTAG);
4069 spa_event_notify(spa, NULL, ESC_ZFS_POOL_DESTROY);
4071 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
4072 spa_unload(spa);
4073 spa_deactivate(spa);
4076 if (oldconfig && spa->spa_config)
4077 VERIFY(nvlist_dup(spa->spa_config, oldconfig, 0) == 0);
4079 if (new_state != POOL_STATE_UNINITIALIZED) {
4080 if (!hardforce)
4081 spa_config_sync(spa, B_TRUE, B_TRUE);
4082 spa_remove(spa);
4084 mutex_exit(&spa_namespace_lock);
4086 return (0);
4090 * Destroy a storage pool.
4093 spa_destroy(char *pool)
4095 return (spa_export_common(pool, POOL_STATE_DESTROYED, NULL,
4096 B_FALSE, B_FALSE));
4100 * Export a storage pool.
4103 spa_export(char *pool, nvlist_t **oldconfig, boolean_t force,
4104 boolean_t hardforce)
4106 return (spa_export_common(pool, POOL_STATE_EXPORTED, oldconfig,
4107 force, hardforce));
4111 * Similar to spa_export(), this unloads the spa_t without actually removing it
4112 * from the namespace in any way.
4115 spa_reset(char *pool)
4117 return (spa_export_common(pool, POOL_STATE_UNINITIALIZED, NULL,
4118 B_FALSE, B_FALSE));
4122 * ==========================================================================
4123 * Device manipulation
4124 * ==========================================================================
4128 * Add a device to a storage pool.
4131 spa_vdev_add(spa_t *spa, nvlist_t *nvroot)
4133 uint64_t txg, id;
4134 int error;
4135 vdev_t *rvd = spa->spa_root_vdev;
4136 vdev_t *vd, *tvd;
4137 nvlist_t **spares, **l2cache;
4138 uint_t nspares, nl2cache;
4140 ASSERT(spa_writeable(spa));
4142 txg = spa_vdev_enter(spa);
4144 if ((error = spa_config_parse(spa, &vd, nvroot, NULL, 0,
4145 VDEV_ALLOC_ADD)) != 0)
4146 return (spa_vdev_exit(spa, NULL, txg, error));
4148 spa->spa_pending_vdev = vd; /* spa_vdev_exit() will clear this */
4150 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares,
4151 &nspares) != 0)
4152 nspares = 0;
4154 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE, &l2cache,
4155 &nl2cache) != 0)
4156 nl2cache = 0;
4158 if (vd->vdev_children == 0 && nspares == 0 && nl2cache == 0)
4159 return (spa_vdev_exit(spa, vd, txg, EINVAL));
4161 if (vd->vdev_children != 0 &&
4162 (error = vdev_create(vd, txg, B_FALSE)) != 0)
4163 return (spa_vdev_exit(spa, vd, txg, error));
4166 * We must validate the spares and l2cache devices after checking the
4167 * children. Otherwise, vdev_inuse() will blindly overwrite the spare.
4169 if ((error = spa_validate_aux(spa, nvroot, txg, VDEV_ALLOC_ADD)) != 0)
4170 return (spa_vdev_exit(spa, vd, txg, error));
4173 * Transfer each new top-level vdev from vd to rvd.
4175 for (int c = 0; c < vd->vdev_children; c++) {
4178 * Set the vdev id to the first hole, if one exists.
4180 for (id = 0; id < rvd->vdev_children; id++) {
4181 if (rvd->vdev_child[id]->vdev_ishole) {
4182 vdev_free(rvd->vdev_child[id]);
4183 break;
4186 tvd = vd->vdev_child[c];
4187 vdev_remove_child(vd, tvd);
4188 tvd->vdev_id = id;
4189 vdev_add_child(rvd, tvd);
4190 vdev_config_dirty(tvd);
4193 if (nspares != 0) {
4194 spa_set_aux_vdevs(&spa->spa_spares, spares, nspares,
4195 ZPOOL_CONFIG_SPARES);
4196 spa_load_spares(spa);
4197 spa->spa_spares.sav_sync = B_TRUE;
4200 if (nl2cache != 0) {
4201 spa_set_aux_vdevs(&spa->spa_l2cache, l2cache, nl2cache,
4202 ZPOOL_CONFIG_L2CACHE);
4203 spa_load_l2cache(spa);
4204 spa->spa_l2cache.sav_sync = B_TRUE;
4208 * We have to be careful when adding new vdevs to an existing pool.
4209 * If other threads start allocating from these vdevs before we
4210 * sync the config cache, and we lose power, then upon reboot we may
4211 * fail to open the pool because there are DVAs that the config cache
4212 * can't translate. Therefore, we first add the vdevs without
4213 * initializing metaslabs; sync the config cache (via spa_vdev_exit());
4214 * and then let spa_config_update() initialize the new metaslabs.
4216 * spa_load() checks for added-but-not-initialized vdevs, so that
4217 * if we lose power at any point in this sequence, the remaining
4218 * steps will be completed the next time we load the pool.
4220 (void) spa_vdev_exit(spa, vd, txg, 0);
4222 mutex_enter(&spa_namespace_lock);
4223 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
4224 mutex_exit(&spa_namespace_lock);
4226 return (0);
4230 * Attach a device to a mirror. The arguments are the path to any device
4231 * in the mirror, and the nvroot for the new device. If the path specifies
4232 * a device that is not mirrored, we automatically insert the mirror vdev.
4234 * If 'replacing' is specified, the new device is intended to replace the
4235 * existing device; in this case the two devices are made into their own
4236 * mirror using the 'replacing' vdev, which is functionally identical to
4237 * the mirror vdev (it actually reuses all the same ops) but has a few
4238 * extra rules: you can't attach to it after it's been created, and upon
4239 * completion of resilvering, the first disk (the one being replaced)
4240 * is automatically detached.
4243 spa_vdev_attach(spa_t *spa, uint64_t guid, nvlist_t *nvroot, int replacing)
4245 uint64_t txg, dtl_max_txg;
4246 vdev_t *rvd = spa->spa_root_vdev;
4247 vdev_t *oldvd, *newvd, *newrootvd, *pvd, *tvd;
4248 vdev_ops_t *pvops;
4249 char *oldvdpath, *newvdpath;
4250 int newvd_isspare;
4251 int error;
4253 ASSERT(spa_writeable(spa));
4255 txg = spa_vdev_enter(spa);
4257 oldvd = spa_lookup_by_guid(spa, guid, B_FALSE);
4259 if (oldvd == NULL)
4260 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
4262 if (!oldvd->vdev_ops->vdev_op_leaf)
4263 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
4265 pvd = oldvd->vdev_parent;
4267 if ((error = spa_config_parse(spa, &newrootvd, nvroot, NULL, 0,
4268 VDEV_ALLOC_ATTACH)) != 0)
4269 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
4271 if (newrootvd->vdev_children != 1)
4272 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
4274 newvd = newrootvd->vdev_child[0];
4276 if (!newvd->vdev_ops->vdev_op_leaf)
4277 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
4279 if ((error = vdev_create(newrootvd, txg, replacing)) != 0)
4280 return (spa_vdev_exit(spa, newrootvd, txg, error));
4283 * Spares can't replace logs
4285 if (oldvd->vdev_top->vdev_islog && newvd->vdev_isspare)
4286 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
4288 if (!replacing) {
4290 * For attach, the only allowable parent is a mirror or the root
4291 * vdev.
4293 if (pvd->vdev_ops != &vdev_mirror_ops &&
4294 pvd->vdev_ops != &vdev_root_ops)
4295 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
4297 pvops = &vdev_mirror_ops;
4298 } else {
4300 * Active hot spares can only be replaced by inactive hot
4301 * spares.
4303 if (pvd->vdev_ops == &vdev_spare_ops &&
4304 oldvd->vdev_isspare &&
4305 !spa_has_spare(spa, newvd->vdev_guid))
4306 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
4309 * If the source is a hot spare, and the parent isn't already a
4310 * spare, then we want to create a new hot spare. Otherwise, we
4311 * want to create a replacing vdev. The user is not allowed to
4312 * attach to a spared vdev child unless the 'isspare' state is
4313 * the same (spare replaces spare, non-spare replaces
4314 * non-spare).
4316 if (pvd->vdev_ops == &vdev_replacing_ops &&
4317 spa_version(spa) < SPA_VERSION_MULTI_REPLACE) {
4318 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
4319 } else if (pvd->vdev_ops == &vdev_spare_ops &&
4320 newvd->vdev_isspare != oldvd->vdev_isspare) {
4321 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
4324 if (newvd->vdev_isspare)
4325 pvops = &vdev_spare_ops;
4326 else
4327 pvops = &vdev_replacing_ops;
4331 * Make sure the new device is big enough.
4333 if (newvd->vdev_asize < vdev_get_min_asize(oldvd))
4334 return (spa_vdev_exit(spa, newrootvd, txg, EOVERFLOW));
4337 * The new device cannot have a higher alignment requirement
4338 * than the top-level vdev.
4340 if (newvd->vdev_ashift > oldvd->vdev_top->vdev_ashift)
4341 return (spa_vdev_exit(spa, newrootvd, txg, EDOM));
4344 * If this is an in-place replacement, update oldvd's path and devid
4345 * to make it distinguishable from newvd, and unopenable from now on.
4347 if (strcmp(oldvd->vdev_path, newvd->vdev_path) == 0) {
4348 spa_strfree(oldvd->vdev_path);
4349 oldvd->vdev_path = kmem_alloc(strlen(newvd->vdev_path) + 5,
4350 KM_SLEEP);
4351 (void) sprintf(oldvd->vdev_path, "%s/%s",
4352 newvd->vdev_path, "old");
4353 if (oldvd->vdev_devid != NULL) {
4354 spa_strfree(oldvd->vdev_devid);
4355 oldvd->vdev_devid = NULL;
4359 /* mark the device being resilvered */
4360 newvd->vdev_resilvering = B_TRUE;
4363 * If the parent is not a mirror, or if we're replacing, insert the new
4364 * mirror/replacing/spare vdev above oldvd.
4366 if (pvd->vdev_ops != pvops)
4367 pvd = vdev_add_parent(oldvd, pvops);
4369 ASSERT(pvd->vdev_top->vdev_parent == rvd);
4370 ASSERT(pvd->vdev_ops == pvops);
4371 ASSERT(oldvd->vdev_parent == pvd);
4374 * Extract the new device from its root and add it to pvd.
4376 vdev_remove_child(newrootvd, newvd);
4377 newvd->vdev_id = pvd->vdev_children;
4378 newvd->vdev_crtxg = oldvd->vdev_crtxg;
4379 vdev_add_child(pvd, newvd);
4381 tvd = newvd->vdev_top;
4382 ASSERT(pvd->vdev_top == tvd);
4383 ASSERT(tvd->vdev_parent == rvd);
4385 vdev_config_dirty(tvd);
4388 * Set newvd's DTL to [TXG_INITIAL, dtl_max_txg) so that we account
4389 * for any dmu_sync-ed blocks. It will propagate upward when
4390 * spa_vdev_exit() calls vdev_dtl_reassess().
4392 dtl_max_txg = txg + TXG_CONCURRENT_STATES;
4394 vdev_dtl_dirty(newvd, DTL_MISSING, TXG_INITIAL,
4395 dtl_max_txg - TXG_INITIAL);
4397 if (newvd->vdev_isspare) {
4398 spa_spare_activate(newvd);
4399 spa_event_notify(spa, newvd, ESC_ZFS_VDEV_SPARE);
4402 oldvdpath = spa_strdup(oldvd->vdev_path);
4403 newvdpath = spa_strdup(newvd->vdev_path);
4404 newvd_isspare = newvd->vdev_isspare;
4407 * Mark newvd's DTL dirty in this txg.
4409 vdev_dirty(tvd, VDD_DTL, newvd, txg);
4412 * Restart the resilver
4414 dsl_resilver_restart(spa->spa_dsl_pool, dtl_max_txg);
4417 * Commit the config
4419 (void) spa_vdev_exit(spa, newrootvd, dtl_max_txg, 0);
4421 spa_history_log_internal(spa, "vdev attach", NULL,
4422 "%s vdev=%s %s vdev=%s",
4423 replacing && newvd_isspare ? "spare in" :
4424 replacing ? "replace" : "attach", newvdpath,
4425 replacing ? "for" : "to", oldvdpath);
4427 spa_strfree(oldvdpath);
4428 spa_strfree(newvdpath);
4430 if (spa->spa_bootfs)
4431 spa_event_notify(spa, newvd, ESC_ZFS_BOOTFS_VDEV_ATTACH);
4433 return (0);
4437 * Detach a device from a mirror or replacing vdev.
4438 * If 'replace_done' is specified, only detach if the parent
4439 * is a replacing vdev.
4442 spa_vdev_detach(spa_t *spa, uint64_t guid, uint64_t pguid, int replace_done)
4444 uint64_t txg;
4445 int error;
4446 vdev_t *rvd = spa->spa_root_vdev;
4447 vdev_t *vd, *pvd, *cvd, *tvd;
4448 boolean_t unspare = B_FALSE;
4449 uint64_t unspare_guid;
4450 char *vdpath;
4452 ASSERT(spa_writeable(spa));
4454 txg = spa_vdev_enter(spa);
4456 vd = spa_lookup_by_guid(spa, guid, B_FALSE);
4458 if (vd == NULL)
4459 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
4461 if (!vd->vdev_ops->vdev_op_leaf)
4462 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
4464 pvd = vd->vdev_parent;
4467 * If the parent/child relationship is not as expected, don't do it.
4468 * Consider M(A,R(B,C)) -- that is, a mirror of A with a replacing
4469 * vdev that's replacing B with C. The user's intent in replacing
4470 * is to go from M(A,B) to M(A,C). If the user decides to cancel
4471 * the replace by detaching C, the expected behavior is to end up
4472 * M(A,B). But suppose that right after deciding to detach C,
4473 * the replacement of B completes. We would have M(A,C), and then
4474 * ask to detach C, which would leave us with just A -- not what
4475 * the user wanted. To prevent this, we make sure that the
4476 * parent/child relationship hasn't changed -- in this example,
4477 * that C's parent is still the replacing vdev R.
4479 if (pvd->vdev_guid != pguid && pguid != 0)
4480 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
4483 * Only 'replacing' or 'spare' vdevs can be replaced.
4485 if (replace_done && pvd->vdev_ops != &vdev_replacing_ops &&
4486 pvd->vdev_ops != &vdev_spare_ops)
4487 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
4489 ASSERT(pvd->vdev_ops != &vdev_spare_ops ||
4490 spa_version(spa) >= SPA_VERSION_SPARES);
4493 * Only mirror, replacing, and spare vdevs support detach.
4495 if (pvd->vdev_ops != &vdev_replacing_ops &&
4496 pvd->vdev_ops != &vdev_mirror_ops &&
4497 pvd->vdev_ops != &vdev_spare_ops)
4498 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
4501 * If this device has the only valid copy of some data,
4502 * we cannot safely detach it.
4504 if (vdev_dtl_required(vd))
4505 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
4507 ASSERT(pvd->vdev_children >= 2);
4510 * If we are detaching the second disk from a replacing vdev, then
4511 * check to see if we changed the original vdev's path to have "/old"
4512 * at the end in spa_vdev_attach(). If so, undo that change now.
4514 if (pvd->vdev_ops == &vdev_replacing_ops && vd->vdev_id > 0 &&
4515 vd->vdev_path != NULL) {
4516 size_t len = strlen(vd->vdev_path);
4518 for (int c = 0; c < pvd->vdev_children; c++) {
4519 cvd = pvd->vdev_child[c];
4521 if (cvd == vd || cvd->vdev_path == NULL)
4522 continue;
4524 if (strncmp(cvd->vdev_path, vd->vdev_path, len) == 0 &&
4525 strcmp(cvd->vdev_path + len, "/old") == 0) {
4526 spa_strfree(cvd->vdev_path);
4527 cvd->vdev_path = spa_strdup(vd->vdev_path);
4528 break;
4534 * If we are detaching the original disk from a spare, then it implies
4535 * that the spare should become a real disk, and be removed from the
4536 * active spare list for the pool.
4538 if (pvd->vdev_ops == &vdev_spare_ops &&
4539 vd->vdev_id == 0 &&
4540 pvd->vdev_child[pvd->vdev_children - 1]->vdev_isspare)
4541 unspare = B_TRUE;
4544 * Erase the disk labels so the disk can be used for other things.
4545 * This must be done after all other error cases are handled,
4546 * but before we disembowel vd (so we can still do I/O to it).
4547 * But if we can't do it, don't treat the error as fatal --
4548 * it may be that the unwritability of the disk is the reason
4549 * it's being detached!
4551 error = vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
4554 * Remove vd from its parent and compact the parent's children.
4556 vdev_remove_child(pvd, vd);
4557 vdev_compact_children(pvd);
4560 * Remember one of the remaining children so we can get tvd below.
4562 cvd = pvd->vdev_child[pvd->vdev_children - 1];
4565 * If we need to remove the remaining child from the list of hot spares,
4566 * do it now, marking the vdev as no longer a spare in the process.
4567 * We must do this before vdev_remove_parent(), because that can
4568 * change the GUID if it creates a new toplevel GUID. For a similar
4569 * reason, we must remove the spare now, in the same txg as the detach;
4570 * otherwise someone could attach a new sibling, change the GUID, and
4571 * the subsequent attempt to spa_vdev_remove(unspare_guid) would fail.
4573 if (unspare) {
4574 ASSERT(cvd->vdev_isspare);
4575 spa_spare_remove(cvd);
4576 unspare_guid = cvd->vdev_guid;
4577 (void) spa_vdev_remove(spa, unspare_guid, B_TRUE);
4578 cvd->vdev_unspare = B_TRUE;
4582 * If the parent mirror/replacing vdev only has one child,
4583 * the parent is no longer needed. Remove it from the tree.
4585 if (pvd->vdev_children == 1) {
4586 if (pvd->vdev_ops == &vdev_spare_ops)
4587 cvd->vdev_unspare = B_FALSE;
4588 vdev_remove_parent(cvd);
4589 cvd->vdev_resilvering = B_FALSE;
4594 * We don't set tvd until now because the parent we just removed
4595 * may have been the previous top-level vdev.
4597 tvd = cvd->vdev_top;
4598 ASSERT(tvd->vdev_parent == rvd);
4601 * Reevaluate the parent vdev state.
4603 vdev_propagate_state(cvd);
4606 * If the 'autoexpand' property is set on the pool then automatically
4607 * try to expand the size of the pool. For example if the device we
4608 * just detached was smaller than the others, it may be possible to
4609 * add metaslabs (i.e. grow the pool). We need to reopen the vdev
4610 * first so that we can obtain the updated sizes of the leaf vdevs.
4612 if (spa->spa_autoexpand) {
4613 vdev_reopen(tvd);
4614 vdev_expand(tvd, txg);
4617 vdev_config_dirty(tvd);
4620 * Mark vd's DTL as dirty in this txg. vdev_dtl_sync() will see that
4621 * vd->vdev_detached is set and free vd's DTL object in syncing context.
4622 * But first make sure we're not on any *other* txg's DTL list, to
4623 * prevent vd from being accessed after it's freed.
4625 vdpath = spa_strdup(vd->vdev_path);
4626 for (int t = 0; t < TXG_SIZE; t++)
4627 (void) txg_list_remove_this(&tvd->vdev_dtl_list, vd, t);
4628 vd->vdev_detached = B_TRUE;
4629 vdev_dirty(tvd, VDD_DTL, vd, txg);
4631 spa_event_notify(spa, vd, ESC_ZFS_VDEV_REMOVE);
4633 /* hang on to the spa before we release the lock */
4634 spa_open_ref(spa, FTAG);
4636 error = spa_vdev_exit(spa, vd, txg, 0);
4638 spa_history_log_internal(spa, "detach", NULL,
4639 "vdev=%s", vdpath);
4640 spa_strfree(vdpath);
4643 * If this was the removal of the original device in a hot spare vdev,
4644 * then we want to go through and remove the device from the hot spare
4645 * list of every other pool.
4647 if (unspare) {
4648 spa_t *altspa = NULL;
4650 mutex_enter(&spa_namespace_lock);
4651 while ((altspa = spa_next(altspa)) != NULL) {
4652 if (altspa->spa_state != POOL_STATE_ACTIVE ||
4653 altspa == spa)
4654 continue;
4656 spa_open_ref(altspa, FTAG);
4657 mutex_exit(&spa_namespace_lock);
4658 (void) spa_vdev_remove(altspa, unspare_guid, B_TRUE);
4659 mutex_enter(&spa_namespace_lock);
4660 spa_close(altspa, FTAG);
4662 mutex_exit(&spa_namespace_lock);
4664 /* search the rest of the vdevs for spares to remove */
4665 spa_vdev_resilver_done(spa);
4668 /* all done with the spa; OK to release */
4669 mutex_enter(&spa_namespace_lock);
4670 spa_close(spa, FTAG);
4671 mutex_exit(&spa_namespace_lock);
4673 return (error);
4677 * Split a set of devices from their mirrors, and create a new pool from them.
4680 spa_vdev_split_mirror(spa_t *spa, char *newname, nvlist_t *config,
4681 nvlist_t *props, boolean_t exp)
4683 int error = 0;
4684 uint64_t txg, *glist;
4685 spa_t *newspa;
4686 uint_t c, children, lastlog;
4687 nvlist_t **child, *nvl, *tmp;
4688 dmu_tx_t *tx;
4689 char *altroot = NULL;
4690 vdev_t *rvd, **vml = NULL; /* vdev modify list */
4691 boolean_t activate_slog;
4693 ASSERT(spa_writeable(spa));
4695 txg = spa_vdev_enter(spa);
4697 /* clear the log and flush everything up to now */
4698 activate_slog = spa_passivate_log(spa);
4699 (void) spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
4700 error = spa_offline_log(spa);
4701 txg = spa_vdev_config_enter(spa);
4703 if (activate_slog)
4704 spa_activate_log(spa);
4706 if (error != 0)
4707 return (spa_vdev_exit(spa, NULL, txg, error));
4709 /* check new spa name before going any further */
4710 if (spa_lookup(newname) != NULL)
4711 return (spa_vdev_exit(spa, NULL, txg, EEXIST));
4714 * scan through all the children to ensure they're all mirrors
4716 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvl) != 0 ||
4717 nvlist_lookup_nvlist_array(nvl, ZPOOL_CONFIG_CHILDREN, &child,
4718 &children) != 0)
4719 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
4721 /* first, check to ensure we've got the right child count */
4722 rvd = spa->spa_root_vdev;
4723 lastlog = 0;
4724 for (c = 0; c < rvd->vdev_children; c++) {
4725 vdev_t *vd = rvd->vdev_child[c];
4727 /* don't count the holes & logs as children */
4728 if (vd->vdev_islog || vd->vdev_ishole) {
4729 if (lastlog == 0)
4730 lastlog = c;
4731 continue;
4734 lastlog = 0;
4736 if (children != (lastlog != 0 ? lastlog : rvd->vdev_children))
4737 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
4739 /* next, ensure no spare or cache devices are part of the split */
4740 if (nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_SPARES, &tmp) == 0 ||
4741 nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_L2CACHE, &tmp) == 0)
4742 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
4744 vml = kmem_zalloc(children * sizeof (vdev_t *), KM_SLEEP);
4745 glist = kmem_zalloc(children * sizeof (uint64_t), KM_SLEEP);
4747 /* then, loop over each vdev and validate it */
4748 for (c = 0; c < children; c++) {
4749 uint64_t is_hole = 0;
4751 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
4752 &is_hole);
4754 if (is_hole != 0) {
4755 if (spa->spa_root_vdev->vdev_child[c]->vdev_ishole ||
4756 spa->spa_root_vdev->vdev_child[c]->vdev_islog) {
4757 continue;
4758 } else {
4759 error = EINVAL;
4760 break;
4764 /* which disk is going to be split? */
4765 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_GUID,
4766 &glist[c]) != 0) {
4767 error = EINVAL;
4768 break;
4771 /* look it up in the spa */
4772 vml[c] = spa_lookup_by_guid(spa, glist[c], B_FALSE);
4773 if (vml[c] == NULL) {
4774 error = ENODEV;
4775 break;
4778 /* make sure there's nothing stopping the split */
4779 if (vml[c]->vdev_parent->vdev_ops != &vdev_mirror_ops ||
4780 vml[c]->vdev_islog ||
4781 vml[c]->vdev_ishole ||
4782 vml[c]->vdev_isspare ||
4783 vml[c]->vdev_isl2cache ||
4784 !vdev_writeable(vml[c]) ||
4785 vml[c]->vdev_children != 0 ||
4786 vml[c]->vdev_state != VDEV_STATE_HEALTHY ||
4787 c != spa->spa_root_vdev->vdev_child[c]->vdev_id) {
4788 error = EINVAL;
4789 break;
4792 if (vdev_dtl_required(vml[c])) {
4793 error = EBUSY;
4794 break;
4797 /* we need certain info from the top level */
4798 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_ARRAY,
4799 vml[c]->vdev_top->vdev_ms_array) == 0);
4800 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_SHIFT,
4801 vml[c]->vdev_top->vdev_ms_shift) == 0);
4802 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASIZE,
4803 vml[c]->vdev_top->vdev_asize) == 0);
4804 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASHIFT,
4805 vml[c]->vdev_top->vdev_ashift) == 0);
4808 if (error != 0) {
4809 kmem_free(vml, children * sizeof (vdev_t *));
4810 kmem_free(glist, children * sizeof (uint64_t));
4811 return (spa_vdev_exit(spa, NULL, txg, error));
4814 /* stop writers from using the disks */
4815 for (c = 0; c < children; c++) {
4816 if (vml[c] != NULL)
4817 vml[c]->vdev_offline = B_TRUE;
4819 vdev_reopen(spa->spa_root_vdev);
4822 * Temporarily record the splitting vdevs in the spa config. This
4823 * will disappear once the config is regenerated.
4825 VERIFY(nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4826 VERIFY(nvlist_add_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
4827 glist, children) == 0);
4828 kmem_free(glist, children * sizeof (uint64_t));
4830 mutex_enter(&spa->spa_props_lock);
4831 VERIFY(nvlist_add_nvlist(spa->spa_config, ZPOOL_CONFIG_SPLIT,
4832 nvl) == 0);
4833 mutex_exit(&spa->spa_props_lock);
4834 spa->spa_config_splitting = nvl;
4835 vdev_config_dirty(spa->spa_root_vdev);
4837 /* configure and create the new pool */
4838 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME, newname) == 0);
4839 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
4840 exp ? POOL_STATE_EXPORTED : POOL_STATE_ACTIVE) == 0);
4841 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
4842 spa_version(spa)) == 0);
4843 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_TXG,
4844 spa->spa_config_txg) == 0);
4845 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_GUID,
4846 spa_generate_guid(NULL)) == 0);
4847 (void) nvlist_lookup_string(props,
4848 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
4850 /* add the new pool to the namespace */
4851 newspa = spa_add(newname, config, altroot);
4852 newspa->spa_config_txg = spa->spa_config_txg;
4853 spa_set_log_state(newspa, SPA_LOG_CLEAR);
4855 /* release the spa config lock, retaining the namespace lock */
4856 spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
4858 if (zio_injection_enabled)
4859 zio_handle_panic_injection(spa, FTAG, 1);
4861 spa_activate(newspa, spa_mode_global);
4862 spa_async_suspend(newspa);
4864 /* create the new pool from the disks of the original pool */
4865 error = spa_load(newspa, SPA_LOAD_IMPORT, SPA_IMPORT_ASSEMBLE, B_TRUE);
4866 if (error)
4867 goto out;
4869 /* if that worked, generate a real config for the new pool */
4870 if (newspa->spa_root_vdev != NULL) {
4871 VERIFY(nvlist_alloc(&newspa->spa_config_splitting,
4872 NV_UNIQUE_NAME, KM_SLEEP) == 0);
4873 VERIFY(nvlist_add_uint64(newspa->spa_config_splitting,
4874 ZPOOL_CONFIG_SPLIT_GUID, spa_guid(spa)) == 0);
4875 spa_config_set(newspa, spa_config_generate(newspa, NULL, -1ULL,
4876 B_TRUE));
4879 /* set the props */
4880 if (props != NULL) {
4881 spa_configfile_set(newspa, props, B_FALSE);
4882 error = spa_prop_set(newspa, props);
4883 if (error)
4884 goto out;
4887 /* flush everything */
4888 txg = spa_vdev_config_enter(newspa);
4889 vdev_config_dirty(newspa->spa_root_vdev);
4890 (void) spa_vdev_config_exit(newspa, NULL, txg, 0, FTAG);
4892 if (zio_injection_enabled)
4893 zio_handle_panic_injection(spa, FTAG, 2);
4895 spa_async_resume(newspa);
4897 /* finally, update the original pool's config */
4898 txg = spa_vdev_config_enter(spa);
4899 tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
4900 error = dmu_tx_assign(tx, TXG_WAIT);
4901 if (error != 0)
4902 dmu_tx_abort(tx);
4903 for (c = 0; c < children; c++) {
4904 if (vml[c] != NULL) {
4905 vdev_split(vml[c]);
4906 if (error == 0)
4907 spa_history_log_internal(spa, "detach", tx,
4908 "vdev=%s", vml[c]->vdev_path);
4909 vdev_free(vml[c]);
4912 vdev_config_dirty(spa->spa_root_vdev);
4913 spa->spa_config_splitting = NULL;
4914 nvlist_free(nvl);
4915 if (error == 0)
4916 dmu_tx_commit(tx);
4917 (void) spa_vdev_exit(spa, NULL, txg, 0);
4919 if (zio_injection_enabled)
4920 zio_handle_panic_injection(spa, FTAG, 3);
4922 /* split is complete; log a history record */
4923 spa_history_log_internal(newspa, "split", NULL,
4924 "from pool %s", spa_name(spa));
4926 kmem_free(vml, children * sizeof (vdev_t *));
4928 /* if we're not going to mount the filesystems in userland, export */
4929 if (exp)
4930 error = spa_export_common(newname, POOL_STATE_EXPORTED, NULL,
4931 B_FALSE, B_FALSE);
4933 return (error);
4935 out:
4936 spa_unload(newspa);
4937 spa_deactivate(newspa);
4938 spa_remove(newspa);
4940 txg = spa_vdev_config_enter(spa);
4942 /* re-online all offlined disks */
4943 for (c = 0; c < children; c++) {
4944 if (vml[c] != NULL)
4945 vml[c]->vdev_offline = B_FALSE;
4947 vdev_reopen(spa->spa_root_vdev);
4949 nvlist_free(spa->spa_config_splitting);
4950 spa->spa_config_splitting = NULL;
4951 (void) spa_vdev_exit(spa, NULL, txg, error);
4953 kmem_free(vml, children * sizeof (vdev_t *));
4954 return (error);
4957 static nvlist_t *
4958 spa_nvlist_lookup_by_guid(nvlist_t **nvpp, int count, uint64_t target_guid)
4960 for (int i = 0; i < count; i++) {
4961 uint64_t guid;
4963 VERIFY(nvlist_lookup_uint64(nvpp[i], ZPOOL_CONFIG_GUID,
4964 &guid) == 0);
4966 if (guid == target_guid)
4967 return (nvpp[i]);
4970 return (NULL);
4973 static void
4974 spa_vdev_remove_aux(nvlist_t *config, char *name, nvlist_t **dev, int count,
4975 nvlist_t *dev_to_remove)
4977 nvlist_t **newdev = NULL;
4979 if (count > 1)
4980 newdev = kmem_alloc((count - 1) * sizeof (void *), KM_SLEEP);
4982 for (int i = 0, j = 0; i < count; i++) {
4983 if (dev[i] == dev_to_remove)
4984 continue;
4985 VERIFY(nvlist_dup(dev[i], &newdev[j++], KM_SLEEP) == 0);
4988 VERIFY(nvlist_remove(config, name, DATA_TYPE_NVLIST_ARRAY) == 0);
4989 VERIFY(nvlist_add_nvlist_array(config, name, newdev, count - 1) == 0);
4991 for (int i = 0; i < count - 1; i++)
4992 nvlist_free(newdev[i]);
4994 if (count > 1)
4995 kmem_free(newdev, (count - 1) * sizeof (void *));
4999 * Evacuate the device.
5001 static int
5002 spa_vdev_remove_evacuate(spa_t *spa, vdev_t *vd)
5004 uint64_t txg;
5005 int error = 0;
5007 ASSERT(MUTEX_HELD(&spa_namespace_lock));
5008 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
5009 ASSERT(vd == vd->vdev_top);
5012 * Evacuate the device. We don't hold the config lock as writer
5013 * since we need to do I/O but we do keep the
5014 * spa_namespace_lock held. Once this completes the device
5015 * should no longer have any blocks allocated on it.
5017 if (vd->vdev_islog) {
5018 if (vd->vdev_stat.vs_alloc != 0)
5019 error = spa_offline_log(spa);
5020 } else {
5021 error = ENOTSUP;
5024 if (error)
5025 return (error);
5028 * The evacuation succeeded. Remove any remaining MOS metadata
5029 * associated with this vdev, and wait for these changes to sync.
5031 ASSERT0(vd->vdev_stat.vs_alloc);
5032 txg = spa_vdev_config_enter(spa);
5033 vd->vdev_removing = B_TRUE;
5034 vdev_dirty(vd, 0, NULL, txg);
5035 vdev_config_dirty(vd);
5036 spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
5038 return (0);
5042 * Complete the removal by cleaning up the namespace.
5044 static void
5045 spa_vdev_remove_from_namespace(spa_t *spa, vdev_t *vd)
5047 vdev_t *rvd = spa->spa_root_vdev;
5048 uint64_t id = vd->vdev_id;
5049 boolean_t last_vdev = (id == (rvd->vdev_children - 1));
5051 ASSERT(MUTEX_HELD(&spa_namespace_lock));
5052 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
5053 ASSERT(vd == vd->vdev_top);
5056 * Only remove any devices which are empty.
5058 if (vd->vdev_stat.vs_alloc != 0)
5059 return;
5061 (void) vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
5063 if (list_link_active(&vd->vdev_state_dirty_node))
5064 vdev_state_clean(vd);
5065 if (list_link_active(&vd->vdev_config_dirty_node))
5066 vdev_config_clean(vd);
5068 vdev_free(vd);
5070 if (last_vdev) {
5071 vdev_compact_children(rvd);
5072 } else {
5073 vd = vdev_alloc_common(spa, id, 0, &vdev_hole_ops);
5074 vdev_add_child(rvd, vd);
5076 vdev_config_dirty(rvd);
5079 * Reassess the health of our root vdev.
5081 vdev_reopen(rvd);
5085 * Remove a device from the pool -
5087 * Removing a device from the vdev namespace requires several steps
5088 * and can take a significant amount of time. As a result we use
5089 * the spa_vdev_config_[enter/exit] functions which allow us to
5090 * grab and release the spa_config_lock while still holding the namespace
5091 * lock. During each step the configuration is synced out.
5095 * Remove a device from the pool. Currently, this supports removing only hot
5096 * spares, slogs, and level 2 ARC devices.
5099 spa_vdev_remove(spa_t *spa, uint64_t guid, boolean_t unspare)
5101 vdev_t *vd;
5102 metaslab_group_t *mg;
5103 nvlist_t **spares, **l2cache, *nv;
5104 uint64_t txg = 0;
5105 uint_t nspares, nl2cache;
5106 int error = 0;
5107 boolean_t locked = MUTEX_HELD(&spa_namespace_lock);
5109 ASSERT(spa_writeable(spa));
5111 if (!locked)
5112 txg = spa_vdev_enter(spa);
5114 vd = spa_lookup_by_guid(spa, guid, B_FALSE);
5116 if (spa->spa_spares.sav_vdevs != NULL &&
5117 nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
5118 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0 &&
5119 (nv = spa_nvlist_lookup_by_guid(spares, nspares, guid)) != NULL) {
5121 * Only remove the hot spare if it's not currently in use
5122 * in this pool.
5124 if (vd == NULL || unspare) {
5125 spa_vdev_remove_aux(spa->spa_spares.sav_config,
5126 ZPOOL_CONFIG_SPARES, spares, nspares, nv);
5127 spa_load_spares(spa);
5128 spa->spa_spares.sav_sync = B_TRUE;
5129 } else {
5130 error = EBUSY;
5132 } else if (spa->spa_l2cache.sav_vdevs != NULL &&
5133 nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
5134 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0 &&
5135 (nv = spa_nvlist_lookup_by_guid(l2cache, nl2cache, guid)) != NULL) {
5137 * Cache devices can always be removed.
5139 spa_vdev_remove_aux(spa->spa_l2cache.sav_config,
5140 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache, nv);
5141 spa_load_l2cache(spa);
5142 spa->spa_l2cache.sav_sync = B_TRUE;
5143 } else if (vd != NULL && vd->vdev_islog) {
5144 ASSERT(!locked);
5145 ASSERT(vd == vd->vdev_top);
5148 * XXX - Once we have bp-rewrite this should
5149 * become the common case.
5152 mg = vd->vdev_mg;
5155 * Stop allocating from this vdev.
5157 metaslab_group_passivate(mg);
5160 * Wait for the youngest allocations and frees to sync,
5161 * and then wait for the deferral of those frees to finish.
5163 spa_vdev_config_exit(spa, NULL,
5164 txg + TXG_CONCURRENT_STATES + TXG_DEFER_SIZE, 0, FTAG);
5167 * Attempt to evacuate the vdev.
5169 error = spa_vdev_remove_evacuate(spa, vd);
5171 txg = spa_vdev_config_enter(spa);
5174 * If we couldn't evacuate the vdev, unwind.
5176 if (error) {
5177 metaslab_group_activate(mg);
5178 return (spa_vdev_exit(spa, NULL, txg, error));
5182 * Clean up the vdev namespace.
5184 spa_vdev_remove_from_namespace(spa, vd);
5186 } else if (vd != NULL) {
5188 * Normal vdevs cannot be removed (yet).
5190 error = ENOTSUP;
5191 } else {
5193 * There is no vdev of any kind with the specified guid.
5195 error = ENOENT;
5198 if (!locked)
5199 return (spa_vdev_exit(spa, NULL, txg, error));
5201 return (error);
5205 * Find any device that's done replacing, or a vdev marked 'unspare' that's
5206 * current spared, so we can detach it.
5208 static vdev_t *
5209 spa_vdev_resilver_done_hunt(vdev_t *vd)
5211 vdev_t *newvd, *oldvd;
5213 for (int c = 0; c < vd->vdev_children; c++) {
5214 oldvd = spa_vdev_resilver_done_hunt(vd->vdev_child[c]);
5215 if (oldvd != NULL)
5216 return (oldvd);
5220 * Check for a completed replacement. We always consider the first
5221 * vdev in the list to be the oldest vdev, and the last one to be
5222 * the newest (see spa_vdev_attach() for how that works). In
5223 * the case where the newest vdev is faulted, we will not automatically
5224 * remove it after a resilver completes. This is OK as it will require
5225 * user intervention to determine which disk the admin wishes to keep.
5227 if (vd->vdev_ops == &vdev_replacing_ops) {
5228 ASSERT(vd->vdev_children > 1);
5230 newvd = vd->vdev_child[vd->vdev_children - 1];
5231 oldvd = vd->vdev_child[0];
5233 if (vdev_dtl_empty(newvd, DTL_MISSING) &&
5234 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
5235 !vdev_dtl_required(oldvd))
5236 return (oldvd);
5240 * Check for a completed resilver with the 'unspare' flag set.
5242 if (vd->vdev_ops == &vdev_spare_ops) {
5243 vdev_t *first = vd->vdev_child[0];
5244 vdev_t *last = vd->vdev_child[vd->vdev_children - 1];
5246 if (last->vdev_unspare) {
5247 oldvd = first;
5248 newvd = last;
5249 } else if (first->vdev_unspare) {
5250 oldvd = last;
5251 newvd = first;
5252 } else {
5253 oldvd = NULL;
5256 if (oldvd != NULL &&
5257 vdev_dtl_empty(newvd, DTL_MISSING) &&
5258 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
5259 !vdev_dtl_required(oldvd))
5260 return (oldvd);
5263 * If there are more than two spares attached to a disk,
5264 * and those spares are not required, then we want to
5265 * attempt to free them up now so that they can be used
5266 * by other pools. Once we're back down to a single
5267 * disk+spare, we stop removing them.
5269 if (vd->vdev_children > 2) {
5270 newvd = vd->vdev_child[1];
5272 if (newvd->vdev_isspare && last->vdev_isspare &&
5273 vdev_dtl_empty(last, DTL_MISSING) &&
5274 vdev_dtl_empty(last, DTL_OUTAGE) &&
5275 !vdev_dtl_required(newvd))
5276 return (newvd);
5280 return (NULL);
5283 static void
5284 spa_vdev_resilver_done(spa_t *spa)
5286 vdev_t *vd, *pvd, *ppvd;
5287 uint64_t guid, sguid, pguid, ppguid;
5289 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5291 while ((vd = spa_vdev_resilver_done_hunt(spa->spa_root_vdev)) != NULL) {
5292 pvd = vd->vdev_parent;
5293 ppvd = pvd->vdev_parent;
5294 guid = vd->vdev_guid;
5295 pguid = pvd->vdev_guid;
5296 ppguid = ppvd->vdev_guid;
5297 sguid = 0;
5299 * If we have just finished replacing a hot spared device, then
5300 * we need to detach the parent's first child (the original hot
5301 * spare) as well.
5303 if (ppvd->vdev_ops == &vdev_spare_ops && pvd->vdev_id == 0 &&
5304 ppvd->vdev_children == 2) {
5305 ASSERT(pvd->vdev_ops == &vdev_replacing_ops);
5306 sguid = ppvd->vdev_child[1]->vdev_guid;
5308 spa_config_exit(spa, SCL_ALL, FTAG);
5309 if (spa_vdev_detach(spa, guid, pguid, B_TRUE) != 0)
5310 return;
5311 if (sguid && spa_vdev_detach(spa, sguid, ppguid, B_TRUE) != 0)
5312 return;
5313 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5316 spa_config_exit(spa, SCL_ALL, FTAG);
5320 * Update the stored path or FRU for this vdev.
5323 spa_vdev_set_common(spa_t *spa, uint64_t guid, const char *value,
5324 boolean_t ispath)
5326 vdev_t *vd;
5327 boolean_t sync = B_FALSE;
5329 ASSERT(spa_writeable(spa));
5331 spa_vdev_state_enter(spa, SCL_ALL);
5333 if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
5334 return (spa_vdev_state_exit(spa, NULL, ENOENT));
5336 if (!vd->vdev_ops->vdev_op_leaf)
5337 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
5339 if (ispath) {
5340 if (strcmp(value, vd->vdev_path) != 0) {
5341 spa_strfree(vd->vdev_path);
5342 vd->vdev_path = spa_strdup(value);
5343 sync = B_TRUE;
5345 } else {
5346 if (vd->vdev_fru == NULL) {
5347 vd->vdev_fru = spa_strdup(value);
5348 sync = B_TRUE;
5349 } else if (strcmp(value, vd->vdev_fru) != 0) {
5350 spa_strfree(vd->vdev_fru);
5351 vd->vdev_fru = spa_strdup(value);
5352 sync = B_TRUE;
5356 return (spa_vdev_state_exit(spa, sync ? vd : NULL, 0));
5360 spa_vdev_setpath(spa_t *spa, uint64_t guid, const char *newpath)
5362 return (spa_vdev_set_common(spa, guid, newpath, B_TRUE));
5366 spa_vdev_setfru(spa_t *spa, uint64_t guid, const char *newfru)
5368 return (spa_vdev_set_common(spa, guid, newfru, B_FALSE));
5372 * ==========================================================================
5373 * SPA Scanning
5374 * ==========================================================================
5378 spa_scan_stop(spa_t *spa)
5380 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
5381 if (dsl_scan_resilvering(spa->spa_dsl_pool))
5382 return (EBUSY);
5383 return (dsl_scan_cancel(spa->spa_dsl_pool));
5387 spa_scan(spa_t *spa, pool_scan_func_t func)
5389 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
5391 if (func >= POOL_SCAN_FUNCS || func == POOL_SCAN_NONE)
5392 return (ENOTSUP);
5395 * If a resilver was requested, but there is no DTL on a
5396 * writeable leaf device, we have nothing to do.
5398 if (func == POOL_SCAN_RESILVER &&
5399 !vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL)) {
5400 spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
5401 return (0);
5404 return (dsl_scan(spa->spa_dsl_pool, func));
5408 * ==========================================================================
5409 * SPA async task processing
5410 * ==========================================================================
5413 static void
5414 spa_async_remove(spa_t *spa, vdev_t *vd)
5416 if (vd->vdev_remove_wanted) {
5417 vd->vdev_remove_wanted = B_FALSE;
5418 vd->vdev_delayed_close = B_FALSE;
5419 vdev_set_state(vd, B_FALSE, VDEV_STATE_REMOVED, VDEV_AUX_NONE);
5422 * We want to clear the stats, but we don't want to do a full
5423 * vdev_clear() as that will cause us to throw away
5424 * degraded/faulted state as well as attempt to reopen the
5425 * device, all of which is a waste.
5427 vd->vdev_stat.vs_read_errors = 0;
5428 vd->vdev_stat.vs_write_errors = 0;
5429 vd->vdev_stat.vs_checksum_errors = 0;
5431 vdev_state_dirty(vd->vdev_top);
5434 for (int c = 0; c < vd->vdev_children; c++)
5435 spa_async_remove(spa, vd->vdev_child[c]);
5438 static void
5439 spa_async_probe(spa_t *spa, vdev_t *vd)
5441 if (vd->vdev_probe_wanted) {
5442 vd->vdev_probe_wanted = B_FALSE;
5443 vdev_reopen(vd); /* vdev_open() does the actual probe */
5446 for (int c = 0; c < vd->vdev_children; c++)
5447 spa_async_probe(spa, vd->vdev_child[c]);
5450 static void
5451 spa_async_autoexpand(spa_t *spa, vdev_t *vd)
5453 sysevent_id_t eid;
5454 nvlist_t *attr;
5455 char *physpath;
5457 if (!spa->spa_autoexpand)
5458 return;
5460 for (int c = 0; c < vd->vdev_children; c++) {
5461 vdev_t *cvd = vd->vdev_child[c];
5462 spa_async_autoexpand(spa, cvd);
5465 if (!vd->vdev_ops->vdev_op_leaf || vd->vdev_physpath == NULL)
5466 return;
5468 physpath = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
5469 (void) snprintf(physpath, MAXPATHLEN, "/devices%s", vd->vdev_physpath);
5471 VERIFY(nvlist_alloc(&attr, NV_UNIQUE_NAME, KM_SLEEP) == 0);
5472 VERIFY(nvlist_add_string(attr, DEV_PHYS_PATH, physpath) == 0);
5474 (void) ddi_log_sysevent(zfs_dip, SUNW_VENDOR, EC_DEV_STATUS,
5475 ESC_DEV_DLE, attr, &eid, DDI_SLEEP);
5477 nvlist_free(attr);
5478 kmem_free(physpath, MAXPATHLEN);
5481 static void
5482 spa_async_thread(spa_t *spa)
5484 int tasks;
5486 ASSERT(spa->spa_sync_on);
5488 mutex_enter(&spa->spa_async_lock);
5489 tasks = spa->spa_async_tasks;
5490 spa->spa_async_tasks = 0;
5491 mutex_exit(&spa->spa_async_lock);
5494 * See if the config needs to be updated.
5496 if (tasks & SPA_ASYNC_CONFIG_UPDATE) {
5497 uint64_t old_space, new_space;
5499 mutex_enter(&spa_namespace_lock);
5500 old_space = metaslab_class_get_space(spa_normal_class(spa));
5501 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5502 new_space = metaslab_class_get_space(spa_normal_class(spa));
5503 mutex_exit(&spa_namespace_lock);
5506 * If the pool grew as a result of the config update,
5507 * then log an internal history event.
5509 if (new_space != old_space) {
5510 spa_history_log_internal(spa, "vdev online", NULL,
5511 "pool '%s' size: %llu(+%llu)",
5512 spa_name(spa), new_space, new_space - old_space);
5517 * See if any devices need to be marked REMOVED.
5519 if (tasks & SPA_ASYNC_REMOVE) {
5520 spa_vdev_state_enter(spa, SCL_NONE);
5521 spa_async_remove(spa, spa->spa_root_vdev);
5522 for (int i = 0; i < spa->spa_l2cache.sav_count; i++)
5523 spa_async_remove(spa, spa->spa_l2cache.sav_vdevs[i]);
5524 for (int i = 0; i < spa->spa_spares.sav_count; i++)
5525 spa_async_remove(spa, spa->spa_spares.sav_vdevs[i]);
5526 (void) spa_vdev_state_exit(spa, NULL, 0);
5529 if ((tasks & SPA_ASYNC_AUTOEXPAND) && !spa_suspended(spa)) {
5530 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
5531 spa_async_autoexpand(spa, spa->spa_root_vdev);
5532 spa_config_exit(spa, SCL_CONFIG, FTAG);
5536 * See if any devices need to be probed.
5538 if (tasks & SPA_ASYNC_PROBE) {
5539 spa_vdev_state_enter(spa, SCL_NONE);
5540 spa_async_probe(spa, spa->spa_root_vdev);
5541 (void) spa_vdev_state_exit(spa, NULL, 0);
5545 * If any devices are done replacing, detach them.
5547 if (tasks & SPA_ASYNC_RESILVER_DONE)
5548 spa_vdev_resilver_done(spa);
5551 * Kick off a resilver.
5553 if (tasks & SPA_ASYNC_RESILVER)
5554 dsl_resilver_restart(spa->spa_dsl_pool, 0);
5557 * Let the world know that we're done.
5559 mutex_enter(&spa->spa_async_lock);
5560 spa->spa_async_thread = NULL;
5561 cv_broadcast(&spa->spa_async_cv);
5562 mutex_exit(&spa->spa_async_lock);
5563 thread_exit();
5566 void
5567 spa_async_suspend(spa_t *spa)
5569 mutex_enter(&spa->spa_async_lock);
5570 spa->spa_async_suspended++;
5571 while (spa->spa_async_thread != NULL)
5572 cv_wait(&spa->spa_async_cv, &spa->spa_async_lock);
5573 mutex_exit(&spa->spa_async_lock);
5576 void
5577 spa_async_resume(spa_t *spa)
5579 mutex_enter(&spa->spa_async_lock);
5580 ASSERT(spa->spa_async_suspended != 0);
5581 spa->spa_async_suspended--;
5582 mutex_exit(&spa->spa_async_lock);
5585 static void
5586 spa_async_dispatch(spa_t *spa)
5588 mutex_enter(&spa->spa_async_lock);
5589 if (spa->spa_async_tasks && !spa->spa_async_suspended &&
5590 spa->spa_async_thread == NULL &&
5591 rootdir != NULL && !vn_is_readonly(rootdir))
5592 spa->spa_async_thread = thread_create(NULL, 0,
5593 spa_async_thread, spa, 0, &p0, TS_RUN, maxclsyspri);
5594 mutex_exit(&spa->spa_async_lock);
5597 void
5598 spa_async_request(spa_t *spa, int task)
5600 zfs_dbgmsg("spa=%s async request task=%u", spa->spa_name, task);
5601 mutex_enter(&spa->spa_async_lock);
5602 spa->spa_async_tasks |= task;
5603 mutex_exit(&spa->spa_async_lock);
5607 * ==========================================================================
5608 * SPA syncing routines
5609 * ==========================================================================
5612 static int
5613 bpobj_enqueue_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
5615 bpobj_t *bpo = arg;
5616 bpobj_enqueue(bpo, bp, tx);
5617 return (0);
5620 static int
5621 spa_free_sync_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
5623 zio_t *zio = arg;
5625 zio_nowait(zio_free_sync(zio, zio->io_spa, dmu_tx_get_txg(tx), bp,
5626 zio->io_flags));
5627 return (0);
5630 static void
5631 spa_sync_nvlist(spa_t *spa, uint64_t obj, nvlist_t *nv, dmu_tx_t *tx)
5633 char *packed = NULL;
5634 size_t bufsize;
5635 size_t nvsize = 0;
5636 dmu_buf_t *db;
5638 VERIFY(nvlist_size(nv, &nvsize, NV_ENCODE_XDR) == 0);
5641 * Write full (SPA_CONFIG_BLOCKSIZE) blocks of configuration
5642 * information. This avoids the dbuf_will_dirty() path and
5643 * saves us a pre-read to get data we don't actually care about.
5645 bufsize = P2ROUNDUP((uint64_t)nvsize, SPA_CONFIG_BLOCKSIZE);
5646 packed = kmem_alloc(bufsize, KM_SLEEP);
5648 VERIFY(nvlist_pack(nv, &packed, &nvsize, NV_ENCODE_XDR,
5649 KM_SLEEP) == 0);
5650 bzero(packed + nvsize, bufsize - nvsize);
5652 dmu_write(spa->spa_meta_objset, obj, 0, bufsize, packed, tx);
5654 kmem_free(packed, bufsize);
5656 VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
5657 dmu_buf_will_dirty(db, tx);
5658 *(uint64_t *)db->db_data = nvsize;
5659 dmu_buf_rele(db, FTAG);
5662 static void
5663 spa_sync_aux_dev(spa_t *spa, spa_aux_vdev_t *sav, dmu_tx_t *tx,
5664 const char *config, const char *entry)
5666 nvlist_t *nvroot;
5667 nvlist_t **list;
5668 int i;
5670 if (!sav->sav_sync)
5671 return;
5674 * Update the MOS nvlist describing the list of available devices.
5675 * spa_validate_aux() will have already made sure this nvlist is
5676 * valid and the vdevs are labeled appropriately.
5678 if (sav->sav_object == 0) {
5679 sav->sav_object = dmu_object_alloc(spa->spa_meta_objset,
5680 DMU_OT_PACKED_NVLIST, 1 << 14, DMU_OT_PACKED_NVLIST_SIZE,
5681 sizeof (uint64_t), tx);
5682 VERIFY(zap_update(spa->spa_meta_objset,
5683 DMU_POOL_DIRECTORY_OBJECT, entry, sizeof (uint64_t), 1,
5684 &sav->sav_object, tx) == 0);
5687 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
5688 if (sav->sav_count == 0) {
5689 VERIFY(nvlist_add_nvlist_array(nvroot, config, NULL, 0) == 0);
5690 } else {
5691 list = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
5692 for (i = 0; i < sav->sav_count; i++)
5693 list[i] = vdev_config_generate(spa, sav->sav_vdevs[i],
5694 B_FALSE, VDEV_CONFIG_L2CACHE);
5695 VERIFY(nvlist_add_nvlist_array(nvroot, config, list,
5696 sav->sav_count) == 0);
5697 for (i = 0; i < sav->sav_count; i++)
5698 nvlist_free(list[i]);
5699 kmem_free(list, sav->sav_count * sizeof (void *));
5702 spa_sync_nvlist(spa, sav->sav_object, nvroot, tx);
5703 nvlist_free(nvroot);
5705 sav->sav_sync = B_FALSE;
5708 static void
5709 spa_sync_config_object(spa_t *spa, dmu_tx_t *tx)
5711 nvlist_t *config;
5713 if (list_is_empty(&spa->spa_config_dirty_list))
5714 return;
5716 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
5718 config = spa_config_generate(spa, spa->spa_root_vdev,
5719 dmu_tx_get_txg(tx), B_FALSE);
5722 * If we're upgrading the spa version then make sure that
5723 * the config object gets updated with the correct version.
5725 if (spa->spa_ubsync.ub_version < spa->spa_uberblock.ub_version)
5726 fnvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
5727 spa->spa_uberblock.ub_version);
5729 spa_config_exit(spa, SCL_STATE, FTAG);
5731 if (spa->spa_config_syncing)
5732 nvlist_free(spa->spa_config_syncing);
5733 spa->spa_config_syncing = config;
5735 spa_sync_nvlist(spa, spa->spa_config_object, config, tx);
5738 static void
5739 spa_sync_version(void *arg1, void *arg2, dmu_tx_t *tx)
5741 spa_t *spa = arg1;
5742 uint64_t version = *(uint64_t *)arg2;
5745 * Setting the version is special cased when first creating the pool.
5747 ASSERT(tx->tx_txg != TXG_INITIAL);
5749 ASSERT(version <= SPA_VERSION);
5750 ASSERT(version >= spa_version(spa));
5752 spa->spa_uberblock.ub_version = version;
5753 vdev_config_dirty(spa->spa_root_vdev);
5754 spa_history_log_internal(spa, "set", tx, "version=%lld", version);
5758 * Set zpool properties.
5760 static void
5761 spa_sync_props(void *arg1, void *arg2, dmu_tx_t *tx)
5763 spa_t *spa = arg1;
5764 objset_t *mos = spa->spa_meta_objset;
5765 nvlist_t *nvp = arg2;
5766 nvpair_t *elem = NULL;
5768 mutex_enter(&spa->spa_props_lock);
5770 while ((elem = nvlist_next_nvpair(nvp, elem))) {
5771 uint64_t intval;
5772 char *strval, *fname;
5773 zpool_prop_t prop;
5774 const char *propname;
5775 zprop_type_t proptype;
5776 zfeature_info_t *feature;
5778 switch (prop = zpool_name_to_prop(nvpair_name(elem))) {
5779 case ZPROP_INVAL:
5781 * We checked this earlier in spa_prop_validate().
5783 ASSERT(zpool_prop_feature(nvpair_name(elem)));
5785 fname = strchr(nvpair_name(elem), '@') + 1;
5786 VERIFY3U(0, ==, zfeature_lookup_name(fname, &feature));
5788 spa_feature_enable(spa, feature, tx);
5789 spa_history_log_internal(spa, "set", tx,
5790 "%s=enabled", nvpair_name(elem));
5791 break;
5793 case ZPOOL_PROP_VERSION:
5794 VERIFY(nvpair_value_uint64(elem, &intval) == 0);
5796 * The version is synced seperatly before other
5797 * properties and should be correct by now.
5799 ASSERT3U(spa_version(spa), >=, intval);
5800 break;
5802 case ZPOOL_PROP_ALTROOT:
5804 * 'altroot' is a non-persistent property. It should
5805 * have been set temporarily at creation or import time.
5807 ASSERT(spa->spa_root != NULL);
5808 break;
5810 case ZPOOL_PROP_READONLY:
5811 case ZPOOL_PROP_CACHEFILE:
5813 * 'readonly' and 'cachefile' are also non-persisitent
5814 * properties.
5816 break;
5817 case ZPOOL_PROP_COMMENT:
5818 VERIFY(nvpair_value_string(elem, &strval) == 0);
5819 if (spa->spa_comment != NULL)
5820 spa_strfree(spa->spa_comment);
5821 spa->spa_comment = spa_strdup(strval);
5823 * We need to dirty the configuration on all the vdevs
5824 * so that their labels get updated. It's unnecessary
5825 * to do this for pool creation since the vdev's
5826 * configuratoin has already been dirtied.
5828 if (tx->tx_txg != TXG_INITIAL)
5829 vdev_config_dirty(spa->spa_root_vdev);
5830 spa_history_log_internal(spa, "set", tx,
5831 "%s=%s", nvpair_name(elem), strval);
5832 break;
5833 default:
5835 * Set pool property values in the poolprops mos object.
5837 if (spa->spa_pool_props_object == 0) {
5838 spa->spa_pool_props_object =
5839 zap_create_link(mos, DMU_OT_POOL_PROPS,
5840 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_PROPS,
5841 tx);
5844 /* normalize the property name */
5845 propname = zpool_prop_to_name(prop);
5846 proptype = zpool_prop_get_type(prop);
5848 if (nvpair_type(elem) == DATA_TYPE_STRING) {
5849 ASSERT(proptype == PROP_TYPE_STRING);
5850 VERIFY(nvpair_value_string(elem, &strval) == 0);
5851 VERIFY(zap_update(mos,
5852 spa->spa_pool_props_object, propname,
5853 1, strlen(strval) + 1, strval, tx) == 0);
5854 spa_history_log_internal(spa, "set", tx,
5855 "%s=%s", nvpair_name(elem), strval);
5856 } else if (nvpair_type(elem) == DATA_TYPE_UINT64) {
5857 VERIFY(nvpair_value_uint64(elem, &intval) == 0);
5859 if (proptype == PROP_TYPE_INDEX) {
5860 const char *unused;
5861 VERIFY(zpool_prop_index_to_string(
5862 prop, intval, &unused) == 0);
5864 VERIFY(zap_update(mos,
5865 spa->spa_pool_props_object, propname,
5866 8, 1, &intval, tx) == 0);
5867 spa_history_log_internal(spa, "set", tx,
5868 "%s=%lld", nvpair_name(elem), intval);
5869 } else {
5870 ASSERT(0); /* not allowed */
5873 switch (prop) {
5874 case ZPOOL_PROP_DELEGATION:
5875 spa->spa_delegation = intval;
5876 break;
5877 case ZPOOL_PROP_BOOTFS:
5878 spa->spa_bootfs = intval;
5879 break;
5880 case ZPOOL_PROP_FAILUREMODE:
5881 spa->spa_failmode = intval;
5882 break;
5883 case ZPOOL_PROP_AUTOEXPAND:
5884 spa->spa_autoexpand = intval;
5885 if (tx->tx_txg != TXG_INITIAL)
5886 spa_async_request(spa,
5887 SPA_ASYNC_AUTOEXPAND);
5888 break;
5889 case ZPOOL_PROP_DEDUPDITTO:
5890 spa->spa_dedup_ditto = intval;
5891 break;
5892 default:
5893 break;
5899 mutex_exit(&spa->spa_props_lock);
5903 * Perform one-time upgrade on-disk changes. spa_version() does not
5904 * reflect the new version this txg, so there must be no changes this
5905 * txg to anything that the upgrade code depends on after it executes.
5906 * Therefore this must be called after dsl_pool_sync() does the sync
5907 * tasks.
5909 static void
5910 spa_sync_upgrades(spa_t *spa, dmu_tx_t *tx)
5912 dsl_pool_t *dp = spa->spa_dsl_pool;
5914 ASSERT(spa->spa_sync_pass == 1);
5916 if (spa->spa_ubsync.ub_version < SPA_VERSION_ORIGIN &&
5917 spa->spa_uberblock.ub_version >= SPA_VERSION_ORIGIN) {
5918 dsl_pool_create_origin(dp, tx);
5920 /* Keeping the origin open increases spa_minref */
5921 spa->spa_minref += 3;
5924 if (spa->spa_ubsync.ub_version < SPA_VERSION_NEXT_CLONES &&
5925 spa->spa_uberblock.ub_version >= SPA_VERSION_NEXT_CLONES) {
5926 dsl_pool_upgrade_clones(dp, tx);
5929 if (spa->spa_ubsync.ub_version < SPA_VERSION_DIR_CLONES &&
5930 spa->spa_uberblock.ub_version >= SPA_VERSION_DIR_CLONES) {
5931 dsl_pool_upgrade_dir_clones(dp, tx);
5933 /* Keeping the freedir open increases spa_minref */
5934 spa->spa_minref += 3;
5937 if (spa->spa_ubsync.ub_version < SPA_VERSION_FEATURES &&
5938 spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
5939 spa_feature_create_zap_objects(spa, tx);
5944 * Sync the specified transaction group. New blocks may be dirtied as
5945 * part of the process, so we iterate until it converges.
5947 void
5948 spa_sync(spa_t *spa, uint64_t txg)
5950 dsl_pool_t *dp = spa->spa_dsl_pool;
5951 objset_t *mos = spa->spa_meta_objset;
5952 bpobj_t *defer_bpo = &spa->spa_deferred_bpobj;
5953 bplist_t *free_bpl = &spa->spa_free_bplist[txg & TXG_MASK];
5954 vdev_t *rvd = spa->spa_root_vdev;
5955 vdev_t *vd;
5956 dmu_tx_t *tx;
5957 int error;
5959 VERIFY(spa_writeable(spa));
5962 * Lock out configuration changes.
5964 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
5966 spa->spa_syncing_txg = txg;
5967 spa->spa_sync_pass = 0;
5970 * If there are any pending vdev state changes, convert them
5971 * into config changes that go out with this transaction group.
5973 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
5974 while (list_head(&spa->spa_state_dirty_list) != NULL) {
5976 * We need the write lock here because, for aux vdevs,
5977 * calling vdev_config_dirty() modifies sav_config.
5978 * This is ugly and will become unnecessary when we
5979 * eliminate the aux vdev wart by integrating all vdevs
5980 * into the root vdev tree.
5982 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
5983 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_WRITER);
5984 while ((vd = list_head(&spa->spa_state_dirty_list)) != NULL) {
5985 vdev_state_clean(vd);
5986 vdev_config_dirty(vd);
5988 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
5989 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
5991 spa_config_exit(spa, SCL_STATE, FTAG);
5993 tx = dmu_tx_create_assigned(dp, txg);
5995 spa->spa_sync_starttime = gethrtime();
5996 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid,
5997 spa->spa_sync_starttime + spa->spa_deadman_synctime));
6000 * If we are upgrading to SPA_VERSION_RAIDZ_DEFLATE this txg,
6001 * set spa_deflate if we have no raid-z vdevs.
6003 if (spa->spa_ubsync.ub_version < SPA_VERSION_RAIDZ_DEFLATE &&
6004 spa->spa_uberblock.ub_version >= SPA_VERSION_RAIDZ_DEFLATE) {
6005 int i;
6007 for (i = 0; i < rvd->vdev_children; i++) {
6008 vd = rvd->vdev_child[i];
6009 if (vd->vdev_deflate_ratio != SPA_MINBLOCKSIZE)
6010 break;
6012 if (i == rvd->vdev_children) {
6013 spa->spa_deflate = TRUE;
6014 VERIFY(0 == zap_add(spa->spa_meta_objset,
6015 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
6016 sizeof (uint64_t), 1, &spa->spa_deflate, tx));
6021 * If anything has changed in this txg, or if someone is waiting
6022 * for this txg to sync (eg, spa_vdev_remove()), push the
6023 * deferred frees from the previous txg. If not, leave them
6024 * alone so that we don't generate work on an otherwise idle
6025 * system.
6027 if (!txg_list_empty(&dp->dp_dirty_datasets, txg) ||
6028 !txg_list_empty(&dp->dp_dirty_dirs, txg) ||
6029 !txg_list_empty(&dp->dp_sync_tasks, txg) ||
6030 ((dsl_scan_active(dp->dp_scan) ||
6031 txg_sync_waiting(dp)) && !spa_shutting_down(spa))) {
6032 zio_t *zio = zio_root(spa, NULL, NULL, 0);
6033 VERIFY3U(bpobj_iterate(defer_bpo,
6034 spa_free_sync_cb, zio, tx), ==, 0);
6035 VERIFY0(zio_wait(zio));
6039 * Iterate to convergence.
6041 do {
6042 int pass = ++spa->spa_sync_pass;
6044 spa_sync_config_object(spa, tx);
6045 spa_sync_aux_dev(spa, &spa->spa_spares, tx,
6046 ZPOOL_CONFIG_SPARES, DMU_POOL_SPARES);
6047 spa_sync_aux_dev(spa, &spa->spa_l2cache, tx,
6048 ZPOOL_CONFIG_L2CACHE, DMU_POOL_L2CACHE);
6049 spa_errlog_sync(spa, txg);
6050 dsl_pool_sync(dp, txg);
6052 if (pass < zfs_sync_pass_deferred_free) {
6053 zio_t *zio = zio_root(spa, NULL, NULL, 0);
6054 bplist_iterate(free_bpl, spa_free_sync_cb,
6055 zio, tx);
6056 VERIFY(zio_wait(zio) == 0);
6057 } else {
6058 bplist_iterate(free_bpl, bpobj_enqueue_cb,
6059 defer_bpo, tx);
6062 ddt_sync(spa, txg);
6063 dsl_scan_sync(dp, tx);
6065 while (vd = txg_list_remove(&spa->spa_vdev_txg_list, txg))
6066 vdev_sync(vd, txg);
6068 if (pass == 1)
6069 spa_sync_upgrades(spa, tx);
6071 } while (dmu_objset_is_dirty(mos, txg));
6074 * Rewrite the vdev configuration (which includes the uberblock)
6075 * to commit the transaction group.
6077 * If there are no dirty vdevs, we sync the uberblock to a few
6078 * random top-level vdevs that are known to be visible in the
6079 * config cache (see spa_vdev_add() for a complete description).
6080 * If there *are* dirty vdevs, sync the uberblock to all vdevs.
6082 for (;;) {
6084 * We hold SCL_STATE to prevent vdev open/close/etc.
6085 * while we're attempting to write the vdev labels.
6087 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
6089 if (list_is_empty(&spa->spa_config_dirty_list)) {
6090 vdev_t *svd[SPA_DVAS_PER_BP];
6091 int svdcount = 0;
6092 int children = rvd->vdev_children;
6093 int c0 = spa_get_random(children);
6095 for (int c = 0; c < children; c++) {
6096 vd = rvd->vdev_child[(c0 + c) % children];
6097 if (vd->vdev_ms_array == 0 || vd->vdev_islog)
6098 continue;
6099 svd[svdcount++] = vd;
6100 if (svdcount == SPA_DVAS_PER_BP)
6101 break;
6103 error = vdev_config_sync(svd, svdcount, txg, B_FALSE);
6104 if (error != 0)
6105 error = vdev_config_sync(svd, svdcount, txg,
6106 B_TRUE);
6107 } else {
6108 error = vdev_config_sync(rvd->vdev_child,
6109 rvd->vdev_children, txg, B_FALSE);
6110 if (error != 0)
6111 error = vdev_config_sync(rvd->vdev_child,
6112 rvd->vdev_children, txg, B_TRUE);
6115 if (error == 0)
6116 spa->spa_last_synced_guid = rvd->vdev_guid;
6118 spa_config_exit(spa, SCL_STATE, FTAG);
6120 if (error == 0)
6121 break;
6122 zio_suspend(spa, NULL);
6123 zio_resume_wait(spa);
6125 dmu_tx_commit(tx);
6127 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid, CY_INFINITY));
6130 * Clear the dirty config list.
6132 while ((vd = list_head(&spa->spa_config_dirty_list)) != NULL)
6133 vdev_config_clean(vd);
6136 * Now that the new config has synced transactionally,
6137 * let it become visible to the config cache.
6139 if (spa->spa_config_syncing != NULL) {
6140 spa_config_set(spa, spa->spa_config_syncing);
6141 spa->spa_config_txg = txg;
6142 spa->spa_config_syncing = NULL;
6145 spa->spa_ubsync = spa->spa_uberblock;
6147 dsl_pool_sync_done(dp, txg);
6150 * Update usable space statistics.
6152 while (vd = txg_list_remove(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)))
6153 vdev_sync_done(vd, txg);
6155 spa_update_dspace(spa);
6158 * It had better be the case that we didn't dirty anything
6159 * since vdev_config_sync().
6161 ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
6162 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
6163 ASSERT(txg_list_empty(&spa->spa_vdev_txg_list, txg));
6165 spa->spa_sync_pass = 0;
6167 spa_config_exit(spa, SCL_CONFIG, FTAG);
6169 spa_handle_ignored_writes(spa);
6172 * If any async tasks have been requested, kick them off.
6174 spa_async_dispatch(spa);
6178 * Sync all pools. We don't want to hold the namespace lock across these
6179 * operations, so we take a reference on the spa_t and drop the lock during the
6180 * sync.
6182 void
6183 spa_sync_allpools(void)
6185 spa_t *spa = NULL;
6186 mutex_enter(&spa_namespace_lock);
6187 while ((spa = spa_next(spa)) != NULL) {
6188 if (spa_state(spa) != POOL_STATE_ACTIVE ||
6189 !spa_writeable(spa) || spa_suspended(spa))
6190 continue;
6191 spa_open_ref(spa, FTAG);
6192 mutex_exit(&spa_namespace_lock);
6193 txg_wait_synced(spa_get_dsl(spa), 0);
6194 mutex_enter(&spa_namespace_lock);
6195 spa_close(spa, FTAG);
6197 mutex_exit(&spa_namespace_lock);
6201 * ==========================================================================
6202 * Miscellaneous routines
6203 * ==========================================================================
6207 * Remove all pools in the system.
6209 void
6210 spa_evict_all(void)
6212 spa_t *spa;
6215 * Remove all cached state. All pools should be closed now,
6216 * so every spa in the AVL tree should be unreferenced.
6218 mutex_enter(&spa_namespace_lock);
6219 while ((spa = spa_next(NULL)) != NULL) {
6221 * Stop async tasks. The async thread may need to detach
6222 * a device that's been replaced, which requires grabbing
6223 * spa_namespace_lock, so we must drop it here.
6225 spa_open_ref(spa, FTAG);
6226 mutex_exit(&spa_namespace_lock);
6227 spa_async_suspend(spa);
6228 mutex_enter(&spa_namespace_lock);
6229 spa_close(spa, FTAG);
6231 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
6232 spa_unload(spa);
6233 spa_deactivate(spa);
6235 spa_remove(spa);
6237 mutex_exit(&spa_namespace_lock);
6240 vdev_t *
6241 spa_lookup_by_guid(spa_t *spa, uint64_t guid, boolean_t aux)
6243 vdev_t *vd;
6244 int i;
6246 if ((vd = vdev_lookup_by_guid(spa->spa_root_vdev, guid)) != NULL)
6247 return (vd);
6249 if (aux) {
6250 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
6251 vd = spa->spa_l2cache.sav_vdevs[i];
6252 if (vd->vdev_guid == guid)
6253 return (vd);
6256 for (i = 0; i < spa->spa_spares.sav_count; i++) {
6257 vd = spa->spa_spares.sav_vdevs[i];
6258 if (vd->vdev_guid == guid)
6259 return (vd);
6263 return (NULL);
6266 void
6267 spa_upgrade(spa_t *spa, uint64_t version)
6269 ASSERT(spa_writeable(spa));
6271 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6274 * This should only be called for a non-faulted pool, and since a
6275 * future version would result in an unopenable pool, this shouldn't be
6276 * possible.
6278 ASSERT(spa->spa_uberblock.ub_version <= SPA_VERSION);
6279 ASSERT(version >= spa->spa_uberblock.ub_version);
6281 spa->spa_uberblock.ub_version = version;
6282 vdev_config_dirty(spa->spa_root_vdev);
6284 spa_config_exit(spa, SCL_ALL, FTAG);
6286 txg_wait_synced(spa_get_dsl(spa), 0);
6289 boolean_t
6290 spa_has_spare(spa_t *spa, uint64_t guid)
6292 int i;
6293 uint64_t spareguid;
6294 spa_aux_vdev_t *sav = &spa->spa_spares;
6296 for (i = 0; i < sav->sav_count; i++)
6297 if (sav->sav_vdevs[i]->vdev_guid == guid)
6298 return (B_TRUE);
6300 for (i = 0; i < sav->sav_npending; i++) {
6301 if (nvlist_lookup_uint64(sav->sav_pending[i], ZPOOL_CONFIG_GUID,
6302 &spareguid) == 0 && spareguid == guid)
6303 return (B_TRUE);
6306 return (B_FALSE);
6310 * Check if a pool has an active shared spare device.
6311 * Note: reference count of an active spare is 2, as a spare and as a replace
6313 static boolean_t
6314 spa_has_active_shared_spare(spa_t *spa)
6316 int i, refcnt;
6317 uint64_t pool;
6318 spa_aux_vdev_t *sav = &spa->spa_spares;
6320 for (i = 0; i < sav->sav_count; i++) {
6321 if (spa_spare_exists(sav->sav_vdevs[i]->vdev_guid, &pool,
6322 &refcnt) && pool != 0ULL && pool == spa_guid(spa) &&
6323 refcnt > 2)
6324 return (B_TRUE);
6327 return (B_FALSE);
6331 * Post a sysevent corresponding to the given event. The 'name' must be one of
6332 * the event definitions in sys/sysevent/eventdefs.h. The payload will be
6333 * filled in from the spa and (optionally) the vdev. This doesn't do anything
6334 * in the userland libzpool, as we don't want consumers to misinterpret ztest
6335 * or zdb as real changes.
6337 void
6338 spa_event_notify(spa_t *spa, vdev_t *vd, const char *name)
6340 #ifdef _KERNEL
6341 sysevent_t *ev;
6342 sysevent_attr_list_t *attr = NULL;
6343 sysevent_value_t value;
6344 sysevent_id_t eid;
6346 ev = sysevent_alloc(EC_ZFS, (char *)name, SUNW_KERN_PUB "zfs",
6347 SE_SLEEP);
6349 value.value_type = SE_DATA_TYPE_STRING;
6350 value.value.sv_string = spa_name(spa);
6351 if (sysevent_add_attr(&attr, ZFS_EV_POOL_NAME, &value, SE_SLEEP) != 0)
6352 goto done;
6354 value.value_type = SE_DATA_TYPE_UINT64;
6355 value.value.sv_uint64 = spa_guid(spa);
6356 if (sysevent_add_attr(&attr, ZFS_EV_POOL_GUID, &value, SE_SLEEP) != 0)
6357 goto done;
6359 if (vd) {
6360 value.value_type = SE_DATA_TYPE_UINT64;
6361 value.value.sv_uint64 = vd->vdev_guid;
6362 if (sysevent_add_attr(&attr, ZFS_EV_VDEV_GUID, &value,
6363 SE_SLEEP) != 0)
6364 goto done;
6366 if (vd->vdev_path) {
6367 value.value_type = SE_DATA_TYPE_STRING;
6368 value.value.sv_string = vd->vdev_path;
6369 if (sysevent_add_attr(&attr, ZFS_EV_VDEV_PATH,
6370 &value, SE_SLEEP) != 0)
6371 goto done;
6375 if (sysevent_attach_attributes(ev, attr) != 0)
6376 goto done;
6377 attr = NULL;
6379 (void) log_sysevent(ev, SE_SLEEP, &eid);
6381 done:
6382 if (attr)
6383 sysevent_free_attr(attr);
6384 sysevent_free(ev);
6385 #endif