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