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