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