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