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