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