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