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