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