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