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