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