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