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