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