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