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