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