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