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