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