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