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