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