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