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