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