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