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