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