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