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