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