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