]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa.c
MFC r211931:
[FreeBSD/stable/8.git] / sys / cddl / contrib / opensolaris / uts / common / fs / zfs / spa.c
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26
27 /*
28  * This file contains all the routines used when modifying on-disk SPA state.
29  * This includes opening, importing, destroying, exporting a pool, and syncing a
30  * pool.
31  */
32
33 #include <sys/zfs_context.h>
34 #include <sys/fm/fs/zfs.h>
35 #include <sys/spa_impl.h>
36 #include <sys/zio.h>
37 #include <sys/zio_checksum.h>
38 #include <sys/zio_compress.h>
39 #include <sys/dmu.h>
40 #include <sys/dmu_tx.h>
41 #include <sys/zap.h>
42 #include <sys/zil.h>
43 #include <sys/vdev_impl.h>
44 #include <sys/metaslab.h>
45 #include <sys/uberblock_impl.h>
46 #include <sys/txg.h>
47 #include <sys/avl.h>
48 #include <sys/dmu_traverse.h>
49 #include <sys/dmu_objset.h>
50 #include <sys/unique.h>
51 #include <sys/dsl_pool.h>
52 #include <sys/dsl_dataset.h>
53 #include <sys/dsl_dir.h>
54 #include <sys/dsl_prop.h>
55 #include <sys/dsl_synctask.h>
56 #include <sys/fs/zfs.h>
57 #include <sys/arc.h>
58 #include <sys/callb.h>
59 #include <sys/sunddi.h>
60 #include <sys/spa_boot.h>
61
62 #include "zfs_prop.h"
63 #include "zfs_comutil.h"
64
65 /* Check hostid on import? */
66 static int check_hostid = 1;
67
68 SYSCTL_DECL(_vfs_zfs);
69 TUNABLE_INT("vfs.zfs.check_hostid", &check_hostid);
70 SYSCTL_INT(_vfs_zfs, OID_AUTO, check_hostid, CTLFLAG_RW, &check_hostid, 0,
71     "Check hostid on import?");
72
73 enum zti_modes {
74         zti_mode_fixed,                 /* value is # of threads (min 1) */
75         zti_mode_online_percent,        /* value is % of online CPUs */
76         zti_mode_tune,                  /* fill from zio_taskq_tune_* */
77         zti_mode_null,                  /* don't create a taskq */
78         zti_nmodes
79 };
80
81 #define ZTI_FIX(n)      { zti_mode_fixed, (n) }
82 #define ZTI_PCT(n)      { zti_mode_online_percent, (n) }
83 #define ZTI_TUNE        { zti_mode_tune, 0 }
84 #define ZTI_NULL        { zti_mode_null, 0 }
85
86 #define ZTI_ONE         ZTI_FIX(1)
87
88 typedef struct zio_taskq_info {
89         enum zti_modes zti_mode;
90         uint_t zti_value;
91 } zio_taskq_info_t;
92
93 static const char *const zio_taskq_types[ZIO_TASKQ_TYPES] = {
94                 "issue", "issue_high", "intr", "intr_high"
95 };
96
97 /*
98  * Define the taskq threads for the following I/O types:
99  *      NULL, READ, WRITE, FREE, CLAIM, and IOCTL
100  */
101 const zio_taskq_info_t zio_taskqs[ZIO_TYPES][ZIO_TASKQ_TYPES] = {
102         /* ISSUE        ISSUE_HIGH      INTR            INTR_HIGH */
103         { ZTI_ONE,      ZTI_NULL,       ZTI_ONE,        ZTI_NULL },
104         { ZTI_FIX(8),   ZTI_NULL,       ZTI_TUNE,       ZTI_NULL },
105         { ZTI_TUNE,     ZTI_FIX(5),     ZTI_FIX(8),     ZTI_FIX(5) },
106         { ZTI_ONE,      ZTI_NULL,       ZTI_ONE,        ZTI_NULL },
107         { ZTI_ONE,      ZTI_NULL,       ZTI_ONE,        ZTI_NULL },
108         { ZTI_ONE,      ZTI_NULL,       ZTI_ONE,        ZTI_NULL },
109 };
110
111 enum zti_modes zio_taskq_tune_mode = zti_mode_online_percent;
112 uint_t zio_taskq_tune_value = 80;       /* #threads = 80% of # online CPUs */
113
114 static void spa_sync_props(void *arg1, void *arg2, cred_t *cr, dmu_tx_t *tx);
115 static boolean_t spa_has_active_shared_spare(spa_t *spa);
116
117 /*
118  * ==========================================================================
119  * SPA properties routines
120  * ==========================================================================
121  */
122
123 /*
124  * Add a (source=src, propname=propval) list to an nvlist.
125  */
126 static void
127 spa_prop_add_list(nvlist_t *nvl, zpool_prop_t prop, char *strval,
128     uint64_t intval, zprop_source_t src)
129 {
130         const char *propname = zpool_prop_to_name(prop);
131         nvlist_t *propval;
132
133         VERIFY(nvlist_alloc(&propval, NV_UNIQUE_NAME, KM_SLEEP) == 0);
134         VERIFY(nvlist_add_uint64(propval, ZPROP_SOURCE, src) == 0);
135
136         if (strval != NULL)
137                 VERIFY(nvlist_add_string(propval, ZPROP_VALUE, strval) == 0);
138         else
139                 VERIFY(nvlist_add_uint64(propval, ZPROP_VALUE, intval) == 0);
140
141         VERIFY(nvlist_add_nvlist(nvl, propname, propval) == 0);
142         nvlist_free(propval);
143 }
144
145 /*
146  * Get property values from the spa configuration.
147  */
148 static void
149 spa_prop_get_config(spa_t *spa, nvlist_t **nvp)
150 {
151         uint64_t size;
152         uint64_t used;
153         uint64_t cap, version;
154         zprop_source_t src = ZPROP_SRC_NONE;
155         spa_config_dirent_t *dp;
156
157         ASSERT(MUTEX_HELD(&spa->spa_props_lock));
158
159         if (spa->spa_root_vdev != NULL) {
160                 size = spa_get_space(spa);
161                 used = spa_get_alloc(spa);
162                 spa_prop_add_list(*nvp, ZPOOL_PROP_NAME, spa_name(spa), 0, src);
163                 spa_prop_add_list(*nvp, ZPOOL_PROP_SIZE, NULL, size, src);
164                 spa_prop_add_list(*nvp, ZPOOL_PROP_USED, NULL, used, src);
165                 spa_prop_add_list(*nvp, ZPOOL_PROP_AVAILABLE, NULL,
166                     size - used, src);
167
168                 cap = (size == 0) ? 0 : (used * 100 / size);
169                 spa_prop_add_list(*nvp, ZPOOL_PROP_CAPACITY, NULL, cap, src);
170
171                 spa_prop_add_list(*nvp, ZPOOL_PROP_HEALTH, NULL,
172                     spa->spa_root_vdev->vdev_state, src);
173
174                 version = spa_version(spa);
175                 if (version == zpool_prop_default_numeric(ZPOOL_PROP_VERSION))
176                         src = ZPROP_SRC_DEFAULT;
177                 else
178                         src = ZPROP_SRC_LOCAL;
179                 spa_prop_add_list(*nvp, ZPOOL_PROP_VERSION, NULL, version, src);
180         }
181
182         spa_prop_add_list(*nvp, ZPOOL_PROP_GUID, NULL, spa_guid(spa), src);
183
184         if (spa->spa_root != NULL)
185                 spa_prop_add_list(*nvp, ZPOOL_PROP_ALTROOT, spa->spa_root,
186                     0, ZPROP_SRC_LOCAL);
187
188         if ((dp = list_head(&spa->spa_config_list)) != NULL) {
189                 if (dp->scd_path == NULL) {
190                         spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
191                             "none", 0, ZPROP_SRC_LOCAL);
192                 } else if (strcmp(dp->scd_path, spa_config_path) != 0) {
193                         spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
194                             dp->scd_path, 0, ZPROP_SRC_LOCAL);
195                 }
196         }
197 }
198
199 /*
200  * Get zpool property values.
201  */
202 int
203 spa_prop_get(spa_t *spa, nvlist_t **nvp)
204 {
205         zap_cursor_t zc;
206         zap_attribute_t za;
207         objset_t *mos = spa->spa_meta_objset;
208         int err;
209
210         VERIFY(nvlist_alloc(nvp, NV_UNIQUE_NAME, KM_SLEEP) == 0);
211
212         mutex_enter(&spa->spa_props_lock);
213
214         /*
215          * Get properties from the spa config.
216          */
217         spa_prop_get_config(spa, nvp);
218
219         /* If no pool property object, no more prop to get. */
220         if (spa->spa_pool_props_object == 0) {
221                 mutex_exit(&spa->spa_props_lock);
222                 return (0);
223         }
224
225         /*
226          * Get properties from the MOS pool property object.
227          */
228         for (zap_cursor_init(&zc, mos, spa->spa_pool_props_object);
229             (err = zap_cursor_retrieve(&zc, &za)) == 0;
230             zap_cursor_advance(&zc)) {
231                 uint64_t intval = 0;
232                 char *strval = NULL;
233                 zprop_source_t src = ZPROP_SRC_DEFAULT;
234                 zpool_prop_t prop;
235
236                 if ((prop = zpool_name_to_prop(za.za_name)) == ZPROP_INVAL)
237                         continue;
238
239                 switch (za.za_integer_length) {
240                 case 8:
241                         /* integer property */
242                         if (za.za_first_integer !=
243                             zpool_prop_default_numeric(prop))
244                                 src = ZPROP_SRC_LOCAL;
245
246                         if (prop == ZPOOL_PROP_BOOTFS) {
247                                 dsl_pool_t *dp;
248                                 dsl_dataset_t *ds = NULL;
249
250                                 dp = spa_get_dsl(spa);
251                                 rw_enter(&dp->dp_config_rwlock, RW_READER);
252                                 if (err = dsl_dataset_hold_obj(dp,
253                                     za.za_first_integer, FTAG, &ds)) {
254                                         rw_exit(&dp->dp_config_rwlock);
255                                         break;
256                                 }
257
258                                 strval = kmem_alloc(
259                                     MAXNAMELEN + strlen(MOS_DIR_NAME) + 1,
260                                     KM_SLEEP);
261                                 dsl_dataset_name(ds, strval);
262                                 dsl_dataset_rele(ds, FTAG);
263                                 rw_exit(&dp->dp_config_rwlock);
264                         } else {
265                                 strval = NULL;
266                                 intval = za.za_first_integer;
267                         }
268
269                         spa_prop_add_list(*nvp, prop, strval, intval, src);
270
271                         if (strval != NULL)
272                                 kmem_free(strval,
273                                     MAXNAMELEN + strlen(MOS_DIR_NAME) + 1);
274
275                         break;
276
277                 case 1:
278                         /* string property */
279                         strval = kmem_alloc(za.za_num_integers, KM_SLEEP);
280                         err = zap_lookup(mos, spa->spa_pool_props_object,
281                             za.za_name, 1, za.za_num_integers, strval);
282                         if (err) {
283                                 kmem_free(strval, za.za_num_integers);
284                                 break;
285                         }
286                         spa_prop_add_list(*nvp, prop, strval, 0, src);
287                         kmem_free(strval, za.za_num_integers);
288                         break;
289
290                 default:
291                         break;
292                 }
293         }
294         zap_cursor_fini(&zc);
295         mutex_exit(&spa->spa_props_lock);
296 out:
297         if (err && err != ENOENT) {
298                 nvlist_free(*nvp);
299                 *nvp = NULL;
300                 return (err);
301         }
302
303         return (0);
304 }
305
306 /*
307  * Validate the given pool properties nvlist and modify the list
308  * for the property values to be set.
309  */
310 static int
311 spa_prop_validate(spa_t *spa, nvlist_t *props)
312 {
313         nvpair_t *elem;
314         int error = 0, reset_bootfs = 0;
315         uint64_t objnum;
316
317         elem = NULL;
318         while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
319                 zpool_prop_t prop;
320                 char *propname, *strval;
321                 uint64_t intval;
322                 objset_t *os;
323                 char *slash;
324
325                 propname = nvpair_name(elem);
326
327                 if ((prop = zpool_name_to_prop(propname)) == ZPROP_INVAL)
328                         return (EINVAL);
329
330                 switch (prop) {
331                 case ZPOOL_PROP_VERSION:
332                         error = nvpair_value_uint64(elem, &intval);
333                         if (!error &&
334                             (intval < spa_version(spa) || intval > SPA_VERSION))
335                                 error = EINVAL;
336                         break;
337
338                 case ZPOOL_PROP_DELEGATION:
339                 case ZPOOL_PROP_AUTOREPLACE:
340                 case ZPOOL_PROP_LISTSNAPS:
341                         error = nvpair_value_uint64(elem, &intval);
342                         if (!error && intval > 1)
343                                 error = EINVAL;
344                         break;
345
346                 case ZPOOL_PROP_BOOTFS:
347                         /*
348                          * If the pool version is less than SPA_VERSION_BOOTFS,
349                          * or the pool is still being created (version == 0),
350                          * the bootfs property cannot be set.
351                          */
352                         if (spa_version(spa) < SPA_VERSION_BOOTFS) {
353                                 error = ENOTSUP;
354                                 break;
355                         }
356
357                         /*
358                          * Make sure the vdev config is bootable
359                          */
360                         if (!vdev_is_bootable(spa->spa_root_vdev)) {
361                                 error = ENOTSUP;
362                                 break;
363                         }
364
365                         reset_bootfs = 1;
366
367                         error = nvpair_value_string(elem, &strval);
368
369                         if (!error) {
370                                 uint64_t compress;
371
372                                 if (strval == NULL || strval[0] == '\0') {
373                                         objnum = zpool_prop_default_numeric(
374                                             ZPOOL_PROP_BOOTFS);
375                                         break;
376                                 }
377
378                                 if (error = dmu_objset_open(strval, DMU_OST_ZFS,
379                                     DS_MODE_USER | DS_MODE_READONLY, &os))
380                                         break;
381
382                                 /* We don't support gzip bootable datasets */
383                                 if ((error = dsl_prop_get_integer(strval,
384                                     zfs_prop_to_name(ZFS_PROP_COMPRESSION),
385                                     &compress, NULL)) == 0 &&
386                                     !BOOTFS_COMPRESS_VALID(compress)) {
387                                         error = ENOTSUP;
388                                 } else {
389                                         objnum = dmu_objset_id(os);
390                                 }
391                                 dmu_objset_close(os);
392                         }
393                         break;
394
395                 case ZPOOL_PROP_FAILUREMODE:
396                         error = nvpair_value_uint64(elem, &intval);
397                         if (!error && (intval < ZIO_FAILURE_MODE_WAIT ||
398                             intval > ZIO_FAILURE_MODE_PANIC))
399                                 error = EINVAL;
400
401                         /*
402                          * This is a special case which only occurs when
403                          * the pool has completely failed. This allows
404                          * the user to change the in-core failmode property
405                          * without syncing it out to disk (I/Os might
406                          * currently be blocked). We do this by returning
407                          * EIO to the caller (spa_prop_set) to trick it
408                          * into thinking we encountered a property validation
409                          * error.
410                          */
411                         if (!error && spa_suspended(spa)) {
412                                 spa->spa_failmode = intval;
413                                 error = EIO;
414                         }
415                         break;
416
417                 case ZPOOL_PROP_CACHEFILE:
418                         if ((error = nvpair_value_string(elem, &strval)) != 0)
419                                 break;
420
421                         if (strval[0] == '\0')
422                                 break;
423
424                         if (strcmp(strval, "none") == 0)
425                                 break;
426
427                         if (strval[0] != '/') {
428                                 error = EINVAL;
429                                 break;
430                         }
431
432                         slash = strrchr(strval, '/');
433                         ASSERT(slash != NULL);
434
435                         if (slash[1] == '\0' || strcmp(slash, "/.") == 0 ||
436                             strcmp(slash, "/..") == 0)
437                                 error = EINVAL;
438                         break;
439                 }
440
441                 if (error)
442                         break;
443         }
444
445         if (!error && reset_bootfs) {
446                 error = nvlist_remove(props,
447                     zpool_prop_to_name(ZPOOL_PROP_BOOTFS), DATA_TYPE_STRING);
448
449                 if (!error) {
450                         error = nvlist_add_uint64(props,
451                             zpool_prop_to_name(ZPOOL_PROP_BOOTFS), objnum);
452                 }
453         }
454
455         return (error);
456 }
457
458 void
459 spa_configfile_set(spa_t *spa, nvlist_t *nvp, boolean_t need_sync)
460 {
461         char *cachefile;
462         spa_config_dirent_t *dp;
463
464         if (nvlist_lookup_string(nvp, zpool_prop_to_name(ZPOOL_PROP_CACHEFILE),
465             &cachefile) != 0)
466                 return;
467
468         dp = kmem_alloc(sizeof (spa_config_dirent_t),
469             KM_SLEEP);
470
471         if (cachefile[0] == '\0')
472                 dp->scd_path = spa_strdup(spa_config_path);
473         else if (strcmp(cachefile, "none") == 0)
474                 dp->scd_path = NULL;
475         else
476                 dp->scd_path = spa_strdup(cachefile);
477
478         list_insert_head(&spa->spa_config_list, dp);
479         if (need_sync)
480                 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
481 }
482
483 int
484 spa_prop_set(spa_t *spa, nvlist_t *nvp)
485 {
486         int error;
487         nvpair_t *elem;
488         boolean_t need_sync = B_FALSE;
489         zpool_prop_t prop;
490
491         if ((error = spa_prop_validate(spa, nvp)) != 0)
492                 return (error);
493
494         elem = NULL;
495         while ((elem = nvlist_next_nvpair(nvp, elem)) != NULL) {
496                 if ((prop = zpool_name_to_prop(
497                     nvpair_name(elem))) == ZPROP_INVAL)
498                         return (EINVAL);
499
500                 if (prop == ZPOOL_PROP_CACHEFILE || prop == ZPOOL_PROP_ALTROOT)
501                         continue;
502
503                 need_sync = B_TRUE;
504                 break;
505         }
506
507         if (need_sync)
508                 return (dsl_sync_task_do(spa_get_dsl(spa), NULL, spa_sync_props,
509                     spa, nvp, 3));
510         else
511                 return (0);
512 }
513
514 /*
515  * If the bootfs property value is dsobj, clear it.
516  */
517 void
518 spa_prop_clear_bootfs(spa_t *spa, uint64_t dsobj, dmu_tx_t *tx)
519 {
520         if (spa->spa_bootfs == dsobj && spa->spa_pool_props_object != 0) {
521                 VERIFY(zap_remove(spa->spa_meta_objset,
522                     spa->spa_pool_props_object,
523                     zpool_prop_to_name(ZPOOL_PROP_BOOTFS), tx) == 0);
524                 spa->spa_bootfs = 0;
525         }
526 }
527
528 /*
529  * ==========================================================================
530  * SPA state manipulation (open/create/destroy/import/export)
531  * ==========================================================================
532  */
533
534 static int
535 spa_error_entry_compare(const void *a, const void *b)
536 {
537         spa_error_entry_t *sa = (spa_error_entry_t *)a;
538         spa_error_entry_t *sb = (spa_error_entry_t *)b;
539         int ret;
540
541         ret = bcmp(&sa->se_bookmark, &sb->se_bookmark,
542             sizeof (zbookmark_t));
543
544         if (ret < 0)
545                 return (-1);
546         else if (ret > 0)
547                 return (1);
548         else
549                 return (0);
550 }
551
552 /*
553  * Utility function which retrieves copies of the current logs and
554  * re-initializes them in the process.
555  */
556 void
557 spa_get_errlists(spa_t *spa, avl_tree_t *last, avl_tree_t *scrub)
558 {
559         ASSERT(MUTEX_HELD(&spa->spa_errlist_lock));
560
561         bcopy(&spa->spa_errlist_last, last, sizeof (avl_tree_t));
562         bcopy(&spa->spa_errlist_scrub, scrub, sizeof (avl_tree_t));
563
564         avl_create(&spa->spa_errlist_scrub,
565             spa_error_entry_compare, sizeof (spa_error_entry_t),
566             offsetof(spa_error_entry_t, se_avl));
567         avl_create(&spa->spa_errlist_last,
568             spa_error_entry_compare, sizeof (spa_error_entry_t),
569             offsetof(spa_error_entry_t, se_avl));
570 }
571
572 /*
573  * Activate an uninitialized pool.
574  */
575 static void
576 spa_activate(spa_t *spa, int mode)
577 {
578         ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
579
580         spa->spa_state = POOL_STATE_ACTIVE;
581         spa->spa_mode = mode;
582
583         spa->spa_normal_class = metaslab_class_create(zfs_metaslab_ops);
584         spa->spa_log_class = metaslab_class_create(zfs_metaslab_ops);
585
586         for (int t = 0; t < ZIO_TYPES; t++) {
587                 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
588                         const zio_taskq_info_t *ztip = &zio_taskqs[t][q];
589                         enum zti_modes mode = ztip->zti_mode;
590                         uint_t value = ztip->zti_value;
591                         char name[32];
592
593                         (void) snprintf(name, sizeof (name),
594                             "%s_%s", zio_type_name[t], zio_taskq_types[q]);
595
596                         if (mode == zti_mode_tune) {
597                                 mode = zio_taskq_tune_mode;
598                                 value = zio_taskq_tune_value;
599                                 if (mode == zti_mode_tune)
600                                         mode = zti_mode_online_percent;
601                         }
602
603                         switch (mode) {
604                         case zti_mode_fixed:
605                                 ASSERT3U(value, >=, 1);
606                                 value = MAX(value, 1);
607
608                                 spa->spa_zio_taskq[t][q] = taskq_create(name,
609                                     value, maxclsyspri, 50, INT_MAX,
610                                     TASKQ_PREPOPULATE);
611                                 break;
612
613                         case zti_mode_online_percent:
614                                 spa->spa_zio_taskq[t][q] = taskq_create(name,
615                                     value, maxclsyspri, 50, INT_MAX,
616                                     TASKQ_PREPOPULATE | TASKQ_THREADS_CPU_PCT);
617                                 break;
618
619                         case zti_mode_null:
620                                 spa->spa_zio_taskq[t][q] = NULL;
621                                 break;
622
623                         case zti_mode_tune:
624                         default:
625                                 panic("unrecognized mode for "
626                                     "zio_taskqs[%u]->zti_nthreads[%u] (%u:%u) "
627                                     "in spa_activate()",
628                                     t, q, mode, value);
629                                 break;
630                         }
631                 }
632         }
633
634         list_create(&spa->spa_config_dirty_list, sizeof (vdev_t),
635             offsetof(vdev_t, vdev_config_dirty_node));
636         list_create(&spa->spa_state_dirty_list, sizeof (vdev_t),
637             offsetof(vdev_t, vdev_state_dirty_node));
638
639         txg_list_create(&spa->spa_vdev_txg_list,
640             offsetof(struct vdev, vdev_txg_node));
641
642         avl_create(&spa->spa_errlist_scrub,
643             spa_error_entry_compare, sizeof (spa_error_entry_t),
644             offsetof(spa_error_entry_t, se_avl));
645         avl_create(&spa->spa_errlist_last,
646             spa_error_entry_compare, sizeof (spa_error_entry_t),
647             offsetof(spa_error_entry_t, se_avl));
648 }
649
650 /*
651  * Opposite of spa_activate().
652  */
653 static void
654 spa_deactivate(spa_t *spa)
655 {
656         ASSERT(spa->spa_sync_on == B_FALSE);
657         ASSERT(spa->spa_dsl_pool == NULL);
658         ASSERT(spa->spa_root_vdev == NULL);
659         ASSERT(spa->spa_async_zio_root == NULL);
660         ASSERT(spa->spa_state != POOL_STATE_UNINITIALIZED);
661
662         txg_list_destroy(&spa->spa_vdev_txg_list);
663
664         list_destroy(&spa->spa_config_dirty_list);
665         list_destroy(&spa->spa_state_dirty_list);
666
667         for (int t = 0; t < ZIO_TYPES; t++) {
668                 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
669                         if (spa->spa_zio_taskq[t][q] != NULL)
670                                 taskq_destroy(spa->spa_zio_taskq[t][q]);
671                         spa->spa_zio_taskq[t][q] = NULL;
672                 }
673         }
674
675         metaslab_class_destroy(spa->spa_normal_class);
676         spa->spa_normal_class = NULL;
677
678         metaslab_class_destroy(spa->spa_log_class);
679         spa->spa_log_class = NULL;
680
681         /*
682          * If this was part of an import or the open otherwise failed, we may
683          * still have errors left in the queues.  Empty them just in case.
684          */
685         spa_errlog_drain(spa);
686
687         avl_destroy(&spa->spa_errlist_scrub);
688         avl_destroy(&spa->spa_errlist_last);
689
690         spa->spa_state = POOL_STATE_UNINITIALIZED;
691 }
692
693 /*
694  * Verify a pool configuration, and construct the vdev tree appropriately.  This
695  * will create all the necessary vdevs in the appropriate layout, with each vdev
696  * in the CLOSED state.  This will prep the pool before open/creation/import.
697  * All vdev validation is done by the vdev_alloc() routine.
698  */
699 static int
700 spa_config_parse(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent,
701     uint_t id, int atype)
702 {
703         nvlist_t **child;
704         uint_t c, children;
705         int error;
706
707         if ((error = vdev_alloc(spa, vdp, nv, parent, id, atype)) != 0)
708                 return (error);
709
710         if ((*vdp)->vdev_ops->vdev_op_leaf)
711                 return (0);
712
713         error = nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
714             &child, &children);
715
716         if (error == ENOENT)
717                 return (0);
718
719         if (error) {
720                 vdev_free(*vdp);
721                 *vdp = NULL;
722                 return (EINVAL);
723         }
724
725         for (c = 0; c < children; c++) {
726                 vdev_t *vd;
727                 if ((error = spa_config_parse(spa, &vd, child[c], *vdp, c,
728                     atype)) != 0) {
729                         vdev_free(*vdp);
730                         *vdp = NULL;
731                         return (error);
732                 }
733         }
734
735         ASSERT(*vdp != NULL);
736
737         return (0);
738 }
739
740 /*
741  * Opposite of spa_load().
742  */
743 static void
744 spa_unload(spa_t *spa)
745 {
746         int i;
747
748         ASSERT(MUTEX_HELD(&spa_namespace_lock));
749
750         /*
751          * Stop async tasks.
752          */
753         spa_async_suspend(spa);
754
755         /*
756          * Stop syncing.
757          */
758         if (spa->spa_sync_on) {
759                 txg_sync_stop(spa->spa_dsl_pool);
760                 spa->spa_sync_on = B_FALSE;
761         }
762
763         /*
764          * Wait for any outstanding async I/O to complete.
765          */
766         if (spa->spa_async_zio_root != NULL) {
767                 (void) zio_wait(spa->spa_async_zio_root);
768                 spa->spa_async_zio_root = NULL;
769         }
770
771         /*
772          * Close the dsl pool.
773          */
774         if (spa->spa_dsl_pool) {
775                 dsl_pool_close(spa->spa_dsl_pool);
776                 spa->spa_dsl_pool = NULL;
777         }
778
779         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
780
781         /*
782          * Drop and purge level 2 cache
783          */
784         spa_l2cache_drop(spa);
785
786         /*
787          * Close all vdevs.
788          */
789         if (spa->spa_root_vdev)
790                 vdev_free(spa->spa_root_vdev);
791         ASSERT(spa->spa_root_vdev == NULL);
792
793         for (i = 0; i < spa->spa_spares.sav_count; i++)
794                 vdev_free(spa->spa_spares.sav_vdevs[i]);
795         if (spa->spa_spares.sav_vdevs) {
796                 kmem_free(spa->spa_spares.sav_vdevs,
797                     spa->spa_spares.sav_count * sizeof (void *));
798                 spa->spa_spares.sav_vdevs = NULL;
799         }
800         if (spa->spa_spares.sav_config) {
801                 nvlist_free(spa->spa_spares.sav_config);
802                 spa->spa_spares.sav_config = NULL;
803         }
804         spa->spa_spares.sav_count = 0;
805
806         for (i = 0; i < spa->spa_l2cache.sav_count; i++)
807                 vdev_free(spa->spa_l2cache.sav_vdevs[i]);
808         if (spa->spa_l2cache.sav_vdevs) {
809                 kmem_free(spa->spa_l2cache.sav_vdevs,
810                     spa->spa_l2cache.sav_count * sizeof (void *));
811                 spa->spa_l2cache.sav_vdevs = NULL;
812         }
813         if (spa->spa_l2cache.sav_config) {
814                 nvlist_free(spa->spa_l2cache.sav_config);
815                 spa->spa_l2cache.sav_config = NULL;
816         }
817         spa->spa_l2cache.sav_count = 0;
818
819         spa->spa_async_suspended = 0;
820
821         spa_config_exit(spa, SCL_ALL, FTAG);
822 }
823
824 /*
825  * Load (or re-load) the current list of vdevs describing the active spares for
826  * this pool.  When this is called, we have some form of basic information in
827  * 'spa_spares.sav_config'.  We parse this into vdevs, try to open them, and
828  * then re-generate a more complete list including status information.
829  */
830 static void
831 spa_load_spares(spa_t *spa)
832 {
833         nvlist_t **spares;
834         uint_t nspares;
835         int i;
836         vdev_t *vd, *tvd;
837
838         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
839
840         /*
841          * First, close and free any existing spare vdevs.
842          */
843         for (i = 0; i < spa->spa_spares.sav_count; i++) {
844                 vd = spa->spa_spares.sav_vdevs[i];
845
846                 /* Undo the call to spa_activate() below */
847                 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
848                     B_FALSE)) != NULL && tvd->vdev_isspare)
849                         spa_spare_remove(tvd);
850                 vdev_close(vd);
851                 vdev_free(vd);
852         }
853
854         if (spa->spa_spares.sav_vdevs)
855                 kmem_free(spa->spa_spares.sav_vdevs,
856                     spa->spa_spares.sav_count * sizeof (void *));
857
858         if (spa->spa_spares.sav_config == NULL)
859                 nspares = 0;
860         else
861                 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
862                     ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
863
864         spa->spa_spares.sav_count = (int)nspares;
865         spa->spa_spares.sav_vdevs = NULL;
866
867         if (nspares == 0)
868                 return;
869
870         /*
871          * Construct the array of vdevs, opening them to get status in the
872          * process.   For each spare, there is potentially two different vdev_t
873          * structures associated with it: one in the list of spares (used only
874          * for basic validation purposes) and one in the active vdev
875          * configuration (if it's spared in).  During this phase we open and
876          * validate each vdev on the spare list.  If the vdev also exists in the
877          * active configuration, then we also mark this vdev as an active spare.
878          */
879         spa->spa_spares.sav_vdevs = kmem_alloc(nspares * sizeof (void *),
880             KM_SLEEP);
881         for (i = 0; i < spa->spa_spares.sav_count; i++) {
882                 VERIFY(spa_config_parse(spa, &vd, spares[i], NULL, 0,
883                     VDEV_ALLOC_SPARE) == 0);
884                 ASSERT(vd != NULL);
885
886                 spa->spa_spares.sav_vdevs[i] = vd;
887
888                 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
889                     B_FALSE)) != NULL) {
890                         if (!tvd->vdev_isspare)
891                                 spa_spare_add(tvd);
892
893                         /*
894                          * We only mark the spare active if we were successfully
895                          * able to load the vdev.  Otherwise, importing a pool
896                          * with a bad active spare would result in strange
897                          * behavior, because multiple pool would think the spare
898                          * is actively in use.
899                          *
900                          * There is a vulnerability here to an equally bizarre
901                          * circumstance, where a dead active spare is later
902                          * brought back to life (onlined or otherwise).  Given
903                          * the rarity of this scenario, and the extra complexity
904                          * it adds, we ignore the possibility.
905                          */
906                         if (!vdev_is_dead(tvd))
907                                 spa_spare_activate(tvd);
908                 }
909
910                 vd->vdev_top = vd;
911                 vd->vdev_aux = &spa->spa_spares;
912
913                 if (vdev_open(vd) != 0)
914                         continue;
915
916                 if (vdev_validate_aux(vd) == 0)
917                         spa_spare_add(vd);
918         }
919
920         /*
921          * Recompute the stashed list of spares, with status information
922          * this time.
923          */
924         VERIFY(nvlist_remove(spa->spa_spares.sav_config, ZPOOL_CONFIG_SPARES,
925             DATA_TYPE_NVLIST_ARRAY) == 0);
926
927         spares = kmem_alloc(spa->spa_spares.sav_count * sizeof (void *),
928             KM_SLEEP);
929         for (i = 0; i < spa->spa_spares.sav_count; i++)
930                 spares[i] = vdev_config_generate(spa,
931                     spa->spa_spares.sav_vdevs[i], B_TRUE, B_TRUE, B_FALSE);
932         VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
933             ZPOOL_CONFIG_SPARES, spares, spa->spa_spares.sav_count) == 0);
934         for (i = 0; i < spa->spa_spares.sav_count; i++)
935                 nvlist_free(spares[i]);
936         kmem_free(spares, spa->spa_spares.sav_count * sizeof (void *));
937 }
938
939 /*
940  * Load (or re-load) the current list of vdevs describing the active l2cache for
941  * this pool.  When this is called, we have some form of basic information in
942  * 'spa_l2cache.sav_config'.  We parse this into vdevs, try to open them, and
943  * then re-generate a more complete list including status information.
944  * Devices which are already active have their details maintained, and are
945  * not re-opened.
946  */
947 static void
948 spa_load_l2cache(spa_t *spa)
949 {
950         nvlist_t **l2cache;
951         uint_t nl2cache;
952         int i, j, oldnvdevs;
953         uint64_t guid, size;
954         vdev_t *vd, **oldvdevs, **newvdevs;
955         spa_aux_vdev_t *sav = &spa->spa_l2cache;
956
957         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
958
959         if (sav->sav_config != NULL) {
960                 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
961                     ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
962                 newvdevs = kmem_alloc(nl2cache * sizeof (void *), KM_SLEEP);
963         } else {
964                 nl2cache = 0;
965         }
966
967         oldvdevs = sav->sav_vdevs;
968         oldnvdevs = sav->sav_count;
969         sav->sav_vdevs = NULL;
970         sav->sav_count = 0;
971
972         /*
973          * Process new nvlist of vdevs.
974          */
975         for (i = 0; i < nl2cache; i++) {
976                 VERIFY(nvlist_lookup_uint64(l2cache[i], ZPOOL_CONFIG_GUID,
977                     &guid) == 0);
978
979                 newvdevs[i] = NULL;
980                 for (j = 0; j < oldnvdevs; j++) {
981                         vd = oldvdevs[j];
982                         if (vd != NULL && guid == vd->vdev_guid) {
983                                 /*
984                                  * Retain previous vdev for add/remove ops.
985                                  */
986                                 newvdevs[i] = vd;
987                                 oldvdevs[j] = NULL;
988                                 break;
989                         }
990                 }
991
992                 if (newvdevs[i] == NULL) {
993                         /*
994                          * Create new vdev
995                          */
996                         VERIFY(spa_config_parse(spa, &vd, l2cache[i], NULL, 0,
997                             VDEV_ALLOC_L2CACHE) == 0);
998                         ASSERT(vd != NULL);
999                         newvdevs[i] = vd;
1000
1001                         /*
1002                          * Commit this vdev as an l2cache device,
1003                          * even if it fails to open.
1004                          */
1005                         spa_l2cache_add(vd);
1006
1007                         vd->vdev_top = vd;
1008                         vd->vdev_aux = sav;
1009
1010                         spa_l2cache_activate(vd);
1011
1012                         if (vdev_open(vd) != 0)
1013                                 continue;
1014
1015                         (void) vdev_validate_aux(vd);
1016
1017                         if (!vdev_is_dead(vd)) {
1018                                 size = vdev_get_rsize(vd);
1019                                 l2arc_add_vdev(spa, vd,
1020                                     VDEV_LABEL_START_SIZE,
1021                                     size - VDEV_LABEL_START_SIZE);
1022                         }
1023                 }
1024         }
1025
1026         /*
1027          * Purge vdevs that were dropped
1028          */
1029         for (i = 0; i < oldnvdevs; i++) {
1030                 uint64_t pool;
1031
1032                 vd = oldvdevs[i];
1033                 if (vd != NULL) {
1034                         if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
1035                             pool != 0ULL && l2arc_vdev_present(vd))
1036                                 l2arc_remove_vdev(vd);
1037                         (void) vdev_close(vd);
1038                         spa_l2cache_remove(vd);
1039                 }
1040         }
1041
1042         if (oldvdevs)
1043                 kmem_free(oldvdevs, oldnvdevs * sizeof (void *));
1044
1045         if (sav->sav_config == NULL)
1046                 goto out;
1047
1048         sav->sav_vdevs = newvdevs;
1049         sav->sav_count = (int)nl2cache;
1050
1051         /*
1052          * Recompute the stashed list of l2cache devices, with status
1053          * information this time.
1054          */
1055         VERIFY(nvlist_remove(sav->sav_config, ZPOOL_CONFIG_L2CACHE,
1056             DATA_TYPE_NVLIST_ARRAY) == 0);
1057
1058         l2cache = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
1059         for (i = 0; i < sav->sav_count; i++)
1060                 l2cache[i] = vdev_config_generate(spa,
1061                     sav->sav_vdevs[i], B_TRUE, B_FALSE, B_TRUE);
1062         VERIFY(nvlist_add_nvlist_array(sav->sav_config,
1063             ZPOOL_CONFIG_L2CACHE, l2cache, sav->sav_count) == 0);
1064 out:
1065         for (i = 0; i < sav->sav_count; i++)
1066                 nvlist_free(l2cache[i]);
1067         if (sav->sav_count)
1068                 kmem_free(l2cache, sav->sav_count * sizeof (void *));
1069 }
1070
1071 static int
1072 load_nvlist(spa_t *spa, uint64_t obj, nvlist_t **value)
1073 {
1074         dmu_buf_t *db;
1075         char *packed = NULL;
1076         size_t nvsize = 0;
1077         int error;
1078         *value = NULL;
1079
1080         VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
1081         nvsize = *(uint64_t *)db->db_data;
1082         dmu_buf_rele(db, FTAG);
1083
1084         packed = kmem_alloc(nvsize, KM_SLEEP);
1085         error = dmu_read(spa->spa_meta_objset, obj, 0, nvsize, packed,
1086             DMU_READ_PREFETCH);
1087         if (error == 0)
1088                 error = nvlist_unpack(packed, nvsize, value, 0);
1089         kmem_free(packed, nvsize);
1090
1091         return (error);
1092 }
1093
1094 /*
1095  * Checks to see if the given vdev could not be opened, in which case we post a
1096  * sysevent to notify the autoreplace code that the device has been removed.
1097  */
1098 static void
1099 spa_check_removed(vdev_t *vd)
1100 {
1101         int c;
1102
1103         for (c = 0; c < vd->vdev_children; c++)
1104                 spa_check_removed(vd->vdev_child[c]);
1105
1106         if (vd->vdev_ops->vdev_op_leaf && vdev_is_dead(vd)) {
1107                 zfs_post_autoreplace(vd->vdev_spa, vd);
1108                 spa_event_notify(vd->vdev_spa, vd, ESC_ZFS_VDEV_CHECK);
1109         }
1110 }
1111
1112 /*
1113  * Check for missing log devices
1114  */
1115 int
1116 spa_check_logs(spa_t *spa)
1117 {
1118         switch (spa->spa_log_state) {
1119         case SPA_LOG_MISSING:
1120                 /* need to recheck in case slog has been restored */
1121         case SPA_LOG_UNKNOWN:
1122                 if (dmu_objset_find(spa->spa_name, zil_check_log_chain, NULL,
1123                     DS_FIND_CHILDREN)) {
1124                         spa->spa_log_state = SPA_LOG_MISSING;
1125                         return (1);
1126                 }
1127                 break;
1128
1129         case SPA_LOG_CLEAR:
1130                 (void) dmu_objset_find(spa->spa_name, zil_clear_log_chain, NULL,
1131                     DS_FIND_CHILDREN);
1132                 break;
1133         }
1134         spa->spa_log_state = SPA_LOG_GOOD;
1135         return (0);
1136 }
1137
1138 /*
1139  * Load an existing storage pool, using the pool's builtin spa_config as a
1140  * source of configuration information.
1141  */
1142 static int
1143 spa_load(spa_t *spa, nvlist_t *config, spa_load_state_t state, int mosconfig)
1144 {
1145         int error = 0;
1146         nvlist_t *nvroot = NULL;
1147         vdev_t *rvd;
1148         uberblock_t *ub = &spa->spa_uberblock;
1149         uint64_t config_cache_txg = spa->spa_config_txg;
1150         uint64_t pool_guid;
1151         uint64_t version;
1152         uint64_t autoreplace = 0;
1153         int orig_mode = spa->spa_mode;
1154         char *ereport = FM_EREPORT_ZFS_POOL;
1155
1156         /*
1157          * If this is an untrusted config, access the pool in read-only mode.
1158          * This prevents things like resilvering recently removed devices.
1159          */
1160         if (!mosconfig)
1161                 spa->spa_mode = FREAD;
1162
1163         ASSERT(MUTEX_HELD(&spa_namespace_lock));
1164
1165         spa->spa_load_state = state;
1166
1167         if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvroot) ||
1168             nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid)) {
1169                 error = EINVAL;
1170                 goto out;
1171         }
1172
1173         /*
1174          * Versioning wasn't explicitly added to the label until later, so if
1175          * it's not present treat it as the initial version.
1176          */
1177         if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION, &version) != 0)
1178                 version = SPA_VERSION_INITIAL;
1179
1180         (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
1181             &spa->spa_config_txg);
1182
1183         if ((state == SPA_LOAD_IMPORT || state == SPA_LOAD_TRYIMPORT) &&
1184             spa_guid_exists(pool_guid, 0)) {
1185                 error = EEXIST;
1186                 goto out;
1187         }
1188
1189         spa->spa_load_guid = pool_guid;
1190
1191         /*
1192          * Create "The Godfather" zio to hold all async IOs
1193          */
1194         spa->spa_async_zio_root = zio_root(spa, NULL, NULL,
1195             ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE | ZIO_FLAG_GODFATHER);
1196
1197         /*
1198          * Parse the configuration into a vdev tree.  We explicitly set the
1199          * value that will be returned by spa_version() since parsing the
1200          * configuration requires knowing the version number.
1201          */
1202         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1203         spa->spa_ubsync.ub_version = version;
1204         error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, VDEV_ALLOC_LOAD);
1205         spa_config_exit(spa, SCL_ALL, FTAG);
1206
1207         if (error != 0)
1208                 goto out;
1209
1210         ASSERT(spa->spa_root_vdev == rvd);
1211         ASSERT(spa_guid(spa) == pool_guid);
1212
1213         /*
1214          * Try to open all vdevs, loading each label in the process.
1215          */
1216         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1217         error = vdev_open(rvd);
1218         spa_config_exit(spa, SCL_ALL, FTAG);
1219         if (error != 0)
1220                 goto out;
1221
1222         /*
1223          * We need to validate the vdev labels against the configuration that
1224          * we have in hand, which is dependent on the setting of mosconfig. If
1225          * mosconfig is true then we're validating the vdev labels based on
1226          * that config. Otherwise, we're validating against the cached config
1227          * (zpool.cache) that was read when we loaded the zfs module, and then
1228          * later we will recursively call spa_load() and validate against
1229          * the vdev config.
1230          */
1231         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1232         error = vdev_validate(rvd);
1233         spa_config_exit(spa, SCL_ALL, FTAG);
1234         if (error != 0)
1235                 goto out;
1236
1237         if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN) {
1238                 error = ENXIO;
1239                 goto out;
1240         }
1241
1242         /*
1243          * Find the best uberblock.
1244          */
1245         vdev_uberblock_load(NULL, rvd, ub);
1246
1247         /*
1248          * If we weren't able to find a single valid uberblock, return failure.
1249          */
1250         if (ub->ub_txg == 0) {
1251                 vdev_set_state(rvd, B_TRUE, VDEV_STATE_CANT_OPEN,
1252                     VDEV_AUX_CORRUPT_DATA);
1253                 error = ENXIO;
1254                 goto out;
1255         }
1256
1257         /*
1258          * If the pool is newer than the code, we can't open it.
1259          */
1260         if (ub->ub_version > SPA_VERSION) {
1261                 vdev_set_state(rvd, B_TRUE, VDEV_STATE_CANT_OPEN,
1262                     VDEV_AUX_VERSION_NEWER);
1263                 error = ENOTSUP;
1264                 goto out;
1265         }
1266
1267         /*
1268          * If the vdev guid sum doesn't match the uberblock, we have an
1269          * incomplete configuration.
1270          */
1271         if (rvd->vdev_guid_sum != ub->ub_guid_sum && mosconfig) {
1272                 vdev_set_state(rvd, B_TRUE, VDEV_STATE_CANT_OPEN,
1273                     VDEV_AUX_BAD_GUID_SUM);
1274                 error = ENXIO;
1275                 goto out;
1276         }
1277
1278         /*
1279          * Initialize internal SPA structures.
1280          */
1281         spa->spa_state = POOL_STATE_ACTIVE;
1282         spa->spa_ubsync = spa->spa_uberblock;
1283         spa->spa_first_txg = spa_last_synced_txg(spa) + 1;
1284         error = dsl_pool_open(spa, spa->spa_first_txg, &spa->spa_dsl_pool);
1285         if (error) {
1286                 vdev_set_state(rvd, B_TRUE, VDEV_STATE_CANT_OPEN,
1287                     VDEV_AUX_CORRUPT_DATA);
1288                 goto out;
1289         }
1290         spa->spa_meta_objset = spa->spa_dsl_pool->dp_meta_objset;
1291
1292         if (zap_lookup(spa->spa_meta_objset,
1293             DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CONFIG,
1294             sizeof (uint64_t), 1, &spa->spa_config_object) != 0) {
1295                 vdev_set_state(rvd, B_TRUE, VDEV_STATE_CANT_OPEN,
1296                     VDEV_AUX_CORRUPT_DATA);
1297                 error = EIO;
1298                 goto out;
1299         }
1300
1301         if (!mosconfig) {
1302                 nvlist_t *newconfig;
1303                 uint64_t hostid;
1304
1305                 if (load_nvlist(spa, spa->spa_config_object, &newconfig) != 0) {
1306                         vdev_set_state(rvd, B_TRUE, VDEV_STATE_CANT_OPEN,
1307                             VDEV_AUX_CORRUPT_DATA);
1308                         error = EIO;
1309                         goto out;
1310                 }
1311
1312                 if (!spa_is_root(spa) && nvlist_lookup_uint64(newconfig,
1313                     ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
1314                         char *hostname;
1315                         unsigned long myhostid = 0;
1316
1317                         VERIFY(nvlist_lookup_string(newconfig,
1318                             ZPOOL_CONFIG_HOSTNAME, &hostname) == 0);
1319
1320                         (void) ddi_strtoul(hw_serial, NULL, 10, &myhostid);
1321                         if (check_hostid && hostid != 0 && myhostid != 0 &&
1322                             (unsigned long)hostid != myhostid) {
1323                                 cmn_err(CE_WARN, "pool '%s' could not be "
1324                                     "loaded as it was last accessed by "
1325                                     "another system (host: %s hostid: 0x%lx). "
1326                                     "See: http://www.sun.com/msg/ZFS-8000-EY",
1327                                     spa_name(spa), hostname,
1328                                     (unsigned long)hostid);
1329                                 error = EBADF;
1330                                 goto out;
1331                         }
1332                 }
1333
1334                 spa_config_set(spa, newconfig);
1335                 spa_unload(spa);
1336                 spa_deactivate(spa);
1337                 spa_activate(spa, orig_mode);
1338
1339                 return (spa_load(spa, newconfig, state, B_TRUE));
1340         }
1341
1342         if (zap_lookup(spa->spa_meta_objset,
1343             DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SYNC_BPLIST,
1344             sizeof (uint64_t), 1, &spa->spa_sync_bplist_obj) != 0) {
1345                 vdev_set_state(rvd, B_TRUE, VDEV_STATE_CANT_OPEN,
1346                     VDEV_AUX_CORRUPT_DATA);
1347                 error = EIO;
1348                 goto out;
1349         }
1350
1351         /*
1352          * Load the bit that tells us to use the new accounting function
1353          * (raid-z deflation).  If we have an older pool, this will not
1354          * be present.
1355          */
1356         error = zap_lookup(spa->spa_meta_objset,
1357             DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
1358             sizeof (uint64_t), 1, &spa->spa_deflate);
1359         if (error != 0 && error != ENOENT) {
1360                 vdev_set_state(rvd, B_TRUE, VDEV_STATE_CANT_OPEN,
1361                     VDEV_AUX_CORRUPT_DATA);
1362                 error = EIO;
1363                 goto out;
1364         }
1365
1366         /*
1367          * Load the persistent error log.  If we have an older pool, this will
1368          * not be present.
1369          */
1370         error = zap_lookup(spa->spa_meta_objset,
1371             DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_ERRLOG_LAST,
1372             sizeof (uint64_t), 1, &spa->spa_errlog_last);
1373         if (error != 0 && error != ENOENT) {
1374                 vdev_set_state(rvd, B_TRUE, VDEV_STATE_CANT_OPEN,
1375                     VDEV_AUX_CORRUPT_DATA);
1376                 error = EIO;
1377                 goto out;
1378         }
1379
1380         error = zap_lookup(spa->spa_meta_objset,
1381             DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_ERRLOG_SCRUB,
1382             sizeof (uint64_t), 1, &spa->spa_errlog_scrub);
1383         if (error != 0 && error != ENOENT) {
1384                 vdev_set_state(rvd, B_TRUE, VDEV_STATE_CANT_OPEN,
1385                     VDEV_AUX_CORRUPT_DATA);
1386                 error = EIO;
1387                 goto out;
1388         }
1389
1390         /*
1391          * Load the history object.  If we have an older pool, this
1392          * will not be present.
1393          */
1394         error = zap_lookup(spa->spa_meta_objset,
1395             DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_HISTORY,
1396             sizeof (uint64_t), 1, &spa->spa_history);
1397         if (error != 0 && error != ENOENT) {
1398                 vdev_set_state(rvd, B_TRUE, VDEV_STATE_CANT_OPEN,
1399                     VDEV_AUX_CORRUPT_DATA);
1400                 error = EIO;
1401                 goto out;
1402         }
1403
1404         /*
1405          * Load any hot spares for this pool.
1406          */
1407         error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
1408             DMU_POOL_SPARES, sizeof (uint64_t), 1, &spa->spa_spares.sav_object);
1409         if (error != 0 && error != ENOENT) {
1410                 vdev_set_state(rvd, B_TRUE, VDEV_STATE_CANT_OPEN,
1411                     VDEV_AUX_CORRUPT_DATA);
1412                 error = EIO;
1413                 goto out;
1414         }
1415         if (error == 0) {
1416                 ASSERT(spa_version(spa) >= SPA_VERSION_SPARES);
1417                 if (load_nvlist(spa, spa->spa_spares.sav_object,
1418                     &spa->spa_spares.sav_config) != 0) {
1419                         vdev_set_state(rvd, B_TRUE, VDEV_STATE_CANT_OPEN,
1420                             VDEV_AUX_CORRUPT_DATA);
1421                         error = EIO;
1422                         goto out;
1423                 }
1424
1425                 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1426                 spa_load_spares(spa);
1427                 spa_config_exit(spa, SCL_ALL, FTAG);
1428         }
1429
1430         /*
1431          * Load any level 2 ARC devices for this pool.
1432          */
1433         error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
1434             DMU_POOL_L2CACHE, sizeof (uint64_t), 1,
1435             &spa->spa_l2cache.sav_object);
1436         if (error != 0 && error != ENOENT) {
1437                 vdev_set_state(rvd, B_TRUE, VDEV_STATE_CANT_OPEN,
1438                     VDEV_AUX_CORRUPT_DATA);
1439                 error = EIO;
1440                 goto out;
1441         }
1442         if (error == 0) {
1443                 ASSERT(spa_version(spa) >= SPA_VERSION_L2CACHE);
1444                 if (load_nvlist(spa, spa->spa_l2cache.sav_object,
1445                     &spa->spa_l2cache.sav_config) != 0) {
1446                         vdev_set_state(rvd, B_TRUE,
1447                             VDEV_STATE_CANT_OPEN,
1448                             VDEV_AUX_CORRUPT_DATA);
1449                         error = EIO;
1450                         goto out;
1451                 }
1452
1453                 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1454                 spa_load_l2cache(spa);
1455                 spa_config_exit(spa, SCL_ALL, FTAG);
1456         }
1457
1458         if (spa_check_logs(spa)) {
1459                 vdev_set_state(rvd, B_TRUE, VDEV_STATE_CANT_OPEN,
1460                     VDEV_AUX_BAD_LOG);
1461                 error = ENXIO;
1462                 ereport = FM_EREPORT_ZFS_LOG_REPLAY;
1463                 goto out;
1464         }
1465
1466
1467         spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
1468
1469         error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
1470             DMU_POOL_PROPS, sizeof (uint64_t), 1, &spa->spa_pool_props_object);
1471
1472         if (error && error != ENOENT) {
1473                 vdev_set_state(rvd, B_TRUE, VDEV_STATE_CANT_OPEN,
1474                     VDEV_AUX_CORRUPT_DATA);
1475                 error = EIO;
1476                 goto out;
1477         }
1478
1479         if (error == 0) {
1480                 (void) zap_lookup(spa->spa_meta_objset,
1481                     spa->spa_pool_props_object,
1482                     zpool_prop_to_name(ZPOOL_PROP_BOOTFS),
1483                     sizeof (uint64_t), 1, &spa->spa_bootfs);
1484                 (void) zap_lookup(spa->spa_meta_objset,
1485                     spa->spa_pool_props_object,
1486                     zpool_prop_to_name(ZPOOL_PROP_AUTOREPLACE),
1487                     sizeof (uint64_t), 1, &autoreplace);
1488                 (void) zap_lookup(spa->spa_meta_objset,
1489                     spa->spa_pool_props_object,
1490                     zpool_prop_to_name(ZPOOL_PROP_DELEGATION),
1491                     sizeof (uint64_t), 1, &spa->spa_delegation);
1492                 (void) zap_lookup(spa->spa_meta_objset,
1493                     spa->spa_pool_props_object,
1494                     zpool_prop_to_name(ZPOOL_PROP_FAILUREMODE),
1495                     sizeof (uint64_t), 1, &spa->spa_failmode);
1496         }
1497
1498         /*
1499          * If the 'autoreplace' property is set, then post a resource notifying
1500          * the ZFS DE that it should not issue any faults for unopenable
1501          * devices.  We also iterate over the vdevs, and post a sysevent for any
1502          * unopenable vdevs so that the normal autoreplace handler can take
1503          * over.
1504          */
1505         if (autoreplace && state != SPA_LOAD_TRYIMPORT)
1506                 spa_check_removed(spa->spa_root_vdev);
1507
1508         /*
1509          * Load the vdev state for all toplevel vdevs.
1510          */
1511         vdev_load(rvd);
1512
1513         /*
1514          * Propagate the leaf DTLs we just loaded all the way up the tree.
1515          */
1516         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1517         vdev_dtl_reassess(rvd, 0, 0, B_FALSE);
1518         spa_config_exit(spa, SCL_ALL, FTAG);
1519
1520         /*
1521          * Check the state of the root vdev.  If it can't be opened, it
1522          * indicates one or more toplevel vdevs are faulted.
1523          */
1524         if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN) {
1525                 error = ENXIO;
1526                 goto out;
1527         }
1528
1529         if (spa_writeable(spa)) {
1530                 dmu_tx_t *tx;
1531                 int need_update = B_FALSE;
1532
1533                 ASSERT(state != SPA_LOAD_TRYIMPORT);
1534
1535                 /*
1536                  * Claim log blocks that haven't been committed yet.
1537                  * This must all happen in a single txg.
1538                  */
1539                 tx = dmu_tx_create_assigned(spa_get_dsl(spa),
1540                     spa_first_txg(spa));
1541                 (void) dmu_objset_find(spa_name(spa),
1542                     zil_claim, tx, DS_FIND_CHILDREN);
1543                 dmu_tx_commit(tx);
1544
1545                 spa->spa_sync_on = B_TRUE;
1546                 txg_sync_start(spa->spa_dsl_pool);
1547
1548                 /*
1549                  * Wait for all claims to sync.
1550                  */
1551                 txg_wait_synced(spa->spa_dsl_pool, 0);
1552
1553                 /*
1554                  * If the config cache is stale, or we have uninitialized
1555                  * metaslabs (see spa_vdev_add()), then update the config.
1556                  *
1557                  * If spa_load_verbatim is true, trust the current
1558                  * in-core spa_config and update the disk labels.
1559                  */
1560                 if (config_cache_txg != spa->spa_config_txg ||
1561                     state == SPA_LOAD_IMPORT || spa->spa_load_verbatim)
1562                         need_update = B_TRUE;
1563
1564                 for (int c = 0; c < rvd->vdev_children; c++)
1565                         if (rvd->vdev_child[c]->vdev_ms_array == 0)
1566                                 need_update = B_TRUE;
1567
1568                 /*
1569                  * Update the config cache asychronously in case we're the
1570                  * root pool, in which case the config cache isn't writable yet.
1571                  */
1572                 if (need_update)
1573                         spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
1574         }
1575
1576         error = 0;
1577 out:
1578         spa->spa_minref = refcount_count(&spa->spa_refcount);
1579         if (error && error != EBADF)
1580                 zfs_ereport_post(ereport, spa, NULL, NULL, 0, 0);
1581         spa->spa_load_state = SPA_LOAD_NONE;
1582         spa->spa_ena = 0;
1583
1584         return (error);
1585 }
1586
1587 /*
1588  * Pool Open/Import
1589  *
1590  * The import case is identical to an open except that the configuration is sent
1591  * down from userland, instead of grabbed from the configuration cache.  For the
1592  * case of an open, the pool configuration will exist in the
1593  * POOL_STATE_UNINITIALIZED state.
1594  *
1595  * The stats information (gen/count/ustats) is used to gather vdev statistics at
1596  * the same time open the pool, without having to keep around the spa_t in some
1597  * ambiguous state.
1598  */
1599 static int
1600 spa_open_common(const char *pool, spa_t **spapp, void *tag, nvlist_t **config)
1601 {
1602         spa_t *spa;
1603         int error;
1604         int locked = B_FALSE;
1605
1606         *spapp = NULL;
1607
1608         /*
1609          * As disgusting as this is, we need to support recursive calls to this
1610          * function because dsl_dir_open() is called during spa_load(), and ends
1611          * up calling spa_open() again.  The real fix is to figure out how to
1612          * avoid dsl_dir_open() calling this in the first place.
1613          */
1614         if (mutex_owner(&spa_namespace_lock) != curthread) {
1615                 mutex_enter(&spa_namespace_lock);
1616                 locked = B_TRUE;
1617         }
1618
1619         if ((spa = spa_lookup(pool)) == NULL) {
1620                 if (locked)
1621                         mutex_exit(&spa_namespace_lock);
1622                 return (ENOENT);
1623         }
1624         if (spa->spa_state == POOL_STATE_UNINITIALIZED) {
1625
1626                 spa_activate(spa, spa_mode_global);
1627
1628                 error = spa_load(spa, spa->spa_config, SPA_LOAD_OPEN, B_FALSE);
1629
1630                 if (error == EBADF) {
1631                         /*
1632                          * If vdev_validate() returns failure (indicated by
1633                          * EBADF), it indicates that one of the vdevs indicates
1634                          * that the pool has been exported or destroyed.  If
1635                          * this is the case, the config cache is out of sync and
1636                          * we should remove the pool from the namespace.
1637                          */
1638                         spa_unload(spa);
1639                         spa_deactivate(spa);
1640                         spa_config_sync(spa, B_TRUE, B_TRUE);
1641                         spa_remove(spa);
1642                         if (locked)
1643                                 mutex_exit(&spa_namespace_lock);
1644                         return (ENOENT);
1645                 }
1646
1647                 if (error) {
1648                         /*
1649                          * We can't open the pool, but we still have useful
1650                          * information: the state of each vdev after the
1651                          * attempted vdev_open().  Return this to the user.
1652                          */
1653                         if (config != NULL && spa->spa_root_vdev != NULL)
1654                                 *config = spa_config_generate(spa, NULL, -1ULL,
1655                                     B_TRUE);
1656                         spa_unload(spa);
1657                         spa_deactivate(spa);
1658                         spa->spa_last_open_failed = B_TRUE;
1659                         if (locked)
1660                                 mutex_exit(&spa_namespace_lock);
1661                         *spapp = NULL;
1662                         return (error);
1663                 } else {
1664                         spa->spa_last_open_failed = B_FALSE;
1665                 }
1666         }
1667
1668         spa_open_ref(spa, tag);
1669
1670         if (locked)
1671                 mutex_exit(&spa_namespace_lock);
1672
1673         *spapp = spa;
1674
1675         if (config != NULL)
1676                 *config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
1677
1678         return (0);
1679 }
1680
1681 int
1682 spa_open(const char *name, spa_t **spapp, void *tag)
1683 {
1684         return (spa_open_common(name, spapp, tag, NULL));
1685 }
1686
1687 /*
1688  * Lookup the given spa_t, incrementing the inject count in the process,
1689  * preventing it from being exported or destroyed.
1690  */
1691 spa_t *
1692 spa_inject_addref(char *name)
1693 {
1694         spa_t *spa;
1695
1696         mutex_enter(&spa_namespace_lock);
1697         if ((spa = spa_lookup(name)) == NULL) {
1698                 mutex_exit(&spa_namespace_lock);
1699                 return (NULL);
1700         }
1701         spa->spa_inject_ref++;
1702         mutex_exit(&spa_namespace_lock);
1703
1704         return (spa);
1705 }
1706
1707 void
1708 spa_inject_delref(spa_t *spa)
1709 {
1710         mutex_enter(&spa_namespace_lock);
1711         spa->spa_inject_ref--;
1712         mutex_exit(&spa_namespace_lock);
1713 }
1714
1715 /*
1716  * Add spares device information to the nvlist.
1717  */
1718 static void
1719 spa_add_spares(spa_t *spa, nvlist_t *config)
1720 {
1721         nvlist_t **spares;
1722         uint_t i, nspares;
1723         nvlist_t *nvroot;
1724         uint64_t guid;
1725         vdev_stat_t *vs;
1726         uint_t vsc;
1727         uint64_t pool;
1728
1729         ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
1730
1731         if (spa->spa_spares.sav_count == 0)
1732                 return;
1733
1734         VERIFY(nvlist_lookup_nvlist(config,
1735             ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
1736         VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
1737             ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
1738         if (nspares != 0) {
1739                 VERIFY(nvlist_add_nvlist_array(nvroot,
1740                     ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
1741                 VERIFY(nvlist_lookup_nvlist_array(nvroot,
1742                     ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
1743
1744                 /*
1745                  * Go through and find any spares which have since been
1746                  * repurposed as an active spare.  If this is the case, update
1747                  * their status appropriately.
1748                  */
1749                 for (i = 0; i < nspares; i++) {
1750                         VERIFY(nvlist_lookup_uint64(spares[i],
1751                             ZPOOL_CONFIG_GUID, &guid) == 0);
1752                         if (spa_spare_exists(guid, &pool, NULL) &&
1753                             pool != 0ULL) {
1754                                 VERIFY(nvlist_lookup_uint64_array(
1755                                     spares[i], ZPOOL_CONFIG_STATS,
1756                                     (uint64_t **)&vs, &vsc) == 0);
1757                                 vs->vs_state = VDEV_STATE_CANT_OPEN;
1758                                 vs->vs_aux = VDEV_AUX_SPARED;
1759                         }
1760                 }
1761         }
1762 }
1763
1764 /*
1765  * Add l2cache device information to the nvlist, including vdev stats.
1766  */
1767 static void
1768 spa_add_l2cache(spa_t *spa, nvlist_t *config)
1769 {
1770         nvlist_t **l2cache;
1771         uint_t i, j, nl2cache;
1772         nvlist_t *nvroot;
1773         uint64_t guid;
1774         vdev_t *vd;
1775         vdev_stat_t *vs;
1776         uint_t vsc;
1777
1778         ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
1779
1780         if (spa->spa_l2cache.sav_count == 0)
1781                 return;
1782
1783         VERIFY(nvlist_lookup_nvlist(config,
1784             ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
1785         VERIFY(nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
1786             ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
1787         if (nl2cache != 0) {
1788                 VERIFY(nvlist_add_nvlist_array(nvroot,
1789                     ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
1790                 VERIFY(nvlist_lookup_nvlist_array(nvroot,
1791                     ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
1792
1793                 /*
1794                  * Update level 2 cache device stats.
1795                  */
1796
1797                 for (i = 0; i < nl2cache; i++) {
1798                         VERIFY(nvlist_lookup_uint64(l2cache[i],
1799                             ZPOOL_CONFIG_GUID, &guid) == 0);
1800
1801                         vd = NULL;
1802                         for (j = 0; j < spa->spa_l2cache.sav_count; j++) {
1803                                 if (guid ==
1804                                     spa->spa_l2cache.sav_vdevs[j]->vdev_guid) {
1805                                         vd = spa->spa_l2cache.sav_vdevs[j];
1806                                         break;
1807                                 }
1808                         }
1809                         ASSERT(vd != NULL);
1810
1811                         VERIFY(nvlist_lookup_uint64_array(l2cache[i],
1812                             ZPOOL_CONFIG_STATS, (uint64_t **)&vs, &vsc) == 0);
1813                         vdev_get_stats(vd, vs);
1814                 }
1815         }
1816 }
1817
1818 int
1819 spa_get_stats(const char *name, nvlist_t **config, char *altroot, size_t buflen)
1820 {
1821         int error;
1822         spa_t *spa;
1823
1824         *config = NULL;
1825         error = spa_open_common(name, &spa, FTAG, config);
1826
1827         if (spa != NULL) {
1828                 /*
1829                  * This still leaves a window of inconsistency where the spares
1830                  * or l2cache devices could change and the config would be
1831                  * self-inconsistent.
1832                  */
1833                 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
1834
1835                 if (*config != NULL) {
1836                         VERIFY(nvlist_add_uint64(*config,
1837                             ZPOOL_CONFIG_ERRCOUNT,
1838                             spa_get_errlog_size(spa)) == 0);
1839
1840                         if (spa_suspended(spa))
1841                                 VERIFY(nvlist_add_uint64(*config,
1842                                     ZPOOL_CONFIG_SUSPENDED,
1843                                     spa->spa_failmode) == 0);
1844
1845                         spa_add_spares(spa, *config);
1846                         spa_add_l2cache(spa, *config);
1847                 }
1848         }
1849
1850         /*
1851          * We want to get the alternate root even for faulted pools, so we cheat
1852          * and call spa_lookup() directly.
1853          */
1854         if (altroot) {
1855                 if (spa == NULL) {
1856                         mutex_enter(&spa_namespace_lock);
1857                         spa = spa_lookup(name);
1858                         if (spa)
1859                                 spa_altroot(spa, altroot, buflen);
1860                         else
1861                                 altroot[0] = '\0';
1862                         spa = NULL;
1863                         mutex_exit(&spa_namespace_lock);
1864                 } else {
1865                         spa_altroot(spa, altroot, buflen);
1866                 }
1867         }
1868
1869         if (spa != NULL) {
1870                 spa_config_exit(spa, SCL_CONFIG, FTAG);
1871                 spa_close(spa, FTAG);
1872         }
1873
1874         return (error);
1875 }
1876
1877 /*
1878  * Validate that the auxiliary device array is well formed.  We must have an
1879  * array of nvlists, each which describes a valid leaf vdev.  If this is an
1880  * import (mode is VDEV_ALLOC_SPARE), then we allow corrupted spares to be
1881  * specified, as long as they are well-formed.
1882  */
1883 static int
1884 spa_validate_aux_devs(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode,
1885     spa_aux_vdev_t *sav, const char *config, uint64_t version,
1886     vdev_labeltype_t label)
1887 {
1888         nvlist_t **dev;
1889         uint_t i, ndev;
1890         vdev_t *vd;
1891         int error;
1892
1893         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1894
1895         /*
1896          * It's acceptable to have no devs specified.
1897          */
1898         if (nvlist_lookup_nvlist_array(nvroot, config, &dev, &ndev) != 0)
1899                 return (0);
1900
1901         if (ndev == 0)
1902                 return (EINVAL);
1903
1904         /*
1905          * Make sure the pool is formatted with a version that supports this
1906          * device type.
1907          */
1908         if (spa_version(spa) < version)
1909                 return (ENOTSUP);
1910
1911         /*
1912          * Set the pending device list so we correctly handle device in-use
1913          * checking.
1914          */
1915         sav->sav_pending = dev;
1916         sav->sav_npending = ndev;
1917
1918         for (i = 0; i < ndev; i++) {
1919                 if ((error = spa_config_parse(spa, &vd, dev[i], NULL, 0,
1920                     mode)) != 0)
1921                         goto out;
1922
1923                 if (!vd->vdev_ops->vdev_op_leaf) {
1924                         vdev_free(vd);
1925                         error = EINVAL;
1926                         goto out;
1927                 }
1928
1929                 /*
1930                  * The L2ARC currently only supports disk devices in
1931                  * kernel context.  For user-level testing, we allow it.
1932                  */
1933 #ifdef _KERNEL
1934                 if ((strcmp(config, ZPOOL_CONFIG_L2CACHE) == 0) &&
1935                     strcmp(vd->vdev_ops->vdev_op_type, VDEV_TYPE_DISK) != 0) {
1936                         error = ENOTBLK;
1937                         goto out;
1938                 }
1939 #endif
1940                 vd->vdev_top = vd;
1941
1942                 if ((error = vdev_open(vd)) == 0 &&
1943                     (error = vdev_label_init(vd, crtxg, label)) == 0) {
1944                         VERIFY(nvlist_add_uint64(dev[i], ZPOOL_CONFIG_GUID,
1945                             vd->vdev_guid) == 0);
1946                 }
1947
1948                 vdev_free(vd);
1949
1950                 if (error &&
1951                     (mode != VDEV_ALLOC_SPARE && mode != VDEV_ALLOC_L2CACHE))
1952                         goto out;
1953                 else
1954                         error = 0;
1955         }
1956
1957 out:
1958         sav->sav_pending = NULL;
1959         sav->sav_npending = 0;
1960         return (error);
1961 }
1962
1963 static int
1964 spa_validate_aux(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode)
1965 {
1966         int error;
1967
1968         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1969
1970         if ((error = spa_validate_aux_devs(spa, nvroot, crtxg, mode,
1971             &spa->spa_spares, ZPOOL_CONFIG_SPARES, SPA_VERSION_SPARES,
1972             VDEV_LABEL_SPARE)) != 0) {
1973                 return (error);
1974         }
1975
1976         return (spa_validate_aux_devs(spa, nvroot, crtxg, mode,
1977             &spa->spa_l2cache, ZPOOL_CONFIG_L2CACHE, SPA_VERSION_L2CACHE,
1978             VDEV_LABEL_L2CACHE));
1979 }
1980
1981 static void
1982 spa_set_aux_vdevs(spa_aux_vdev_t *sav, nvlist_t **devs, int ndevs,
1983     const char *config)
1984 {
1985         int i;
1986
1987         if (sav->sav_config != NULL) {
1988                 nvlist_t **olddevs;
1989                 uint_t oldndevs;
1990                 nvlist_t **newdevs;
1991
1992                 /*
1993                  * Generate new dev list by concatentating with the
1994                  * current dev list.
1995                  */
1996                 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config, config,
1997                     &olddevs, &oldndevs) == 0);
1998
1999                 newdevs = kmem_alloc(sizeof (void *) *
2000                     (ndevs + oldndevs), KM_SLEEP);
2001                 for (i = 0; i < oldndevs; i++)
2002                         VERIFY(nvlist_dup(olddevs[i], &newdevs[i],
2003                             KM_SLEEP) == 0);
2004                 for (i = 0; i < ndevs; i++)
2005                         VERIFY(nvlist_dup(devs[i], &newdevs[i + oldndevs],
2006                             KM_SLEEP) == 0);
2007
2008                 VERIFY(nvlist_remove(sav->sav_config, config,
2009                     DATA_TYPE_NVLIST_ARRAY) == 0);
2010
2011                 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
2012                     config, newdevs, ndevs + oldndevs) == 0);
2013                 for (i = 0; i < oldndevs + ndevs; i++)
2014                         nvlist_free(newdevs[i]);
2015                 kmem_free(newdevs, (oldndevs + ndevs) * sizeof (void *));
2016         } else {
2017                 /*
2018                  * Generate a new dev list.
2019                  */
2020                 VERIFY(nvlist_alloc(&sav->sav_config, NV_UNIQUE_NAME,
2021                     KM_SLEEP) == 0);
2022                 VERIFY(nvlist_add_nvlist_array(sav->sav_config, config,
2023                     devs, ndevs) == 0);
2024         }
2025 }
2026
2027 /*
2028  * Stop and drop level 2 ARC devices
2029  */
2030 void
2031 spa_l2cache_drop(spa_t *spa)
2032 {
2033         vdev_t *vd;
2034         int i;
2035         spa_aux_vdev_t *sav = &spa->spa_l2cache;
2036
2037         for (i = 0; i < sav->sav_count; i++) {
2038                 uint64_t pool;
2039
2040                 vd = sav->sav_vdevs[i];
2041                 ASSERT(vd != NULL);
2042
2043                 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
2044                     pool != 0ULL && l2arc_vdev_present(vd))
2045                         l2arc_remove_vdev(vd);
2046                 if (vd->vdev_isl2cache)
2047                         spa_l2cache_remove(vd);
2048                 vdev_clear_stats(vd);
2049                 (void) vdev_close(vd);
2050         }
2051 }
2052
2053 /*
2054  * Pool Creation
2055  */
2056 int
2057 spa_create(const char *pool, nvlist_t *nvroot, nvlist_t *props,
2058     const char *history_str, nvlist_t *zplprops)
2059 {
2060         spa_t *spa;
2061         char *altroot = NULL;
2062         vdev_t *rvd;
2063         dsl_pool_t *dp;
2064         dmu_tx_t *tx;
2065         int c, error = 0;
2066         uint64_t txg = TXG_INITIAL;
2067         nvlist_t **spares, **l2cache;
2068         uint_t nspares, nl2cache;
2069         uint64_t version;
2070
2071         /*
2072          * If this pool already exists, return failure.
2073          */
2074         mutex_enter(&spa_namespace_lock);
2075         if (spa_lookup(pool) != NULL) {
2076                 mutex_exit(&spa_namespace_lock);
2077                 return (EEXIST);
2078         }
2079
2080         /*
2081          * Allocate a new spa_t structure.
2082          */
2083         (void) nvlist_lookup_string(props,
2084             zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
2085         spa = spa_add(pool, altroot);
2086         spa_activate(spa, spa_mode_global);
2087
2088         spa->spa_uberblock.ub_txg = txg - 1;
2089
2090         if (props && (error = spa_prop_validate(spa, props))) {
2091                 spa_deactivate(spa);
2092                 spa_remove(spa);
2093                 mutex_exit(&spa_namespace_lock);
2094                 return (error);
2095         }
2096
2097         if (nvlist_lookup_uint64(props, zpool_prop_to_name(ZPOOL_PROP_VERSION),
2098             &version) != 0)
2099                 version = SPA_VERSION;
2100         ASSERT(version <= SPA_VERSION);
2101         spa->spa_uberblock.ub_version = version;
2102         spa->spa_ubsync = spa->spa_uberblock;
2103
2104         /*
2105          * Create "The Godfather" zio to hold all async IOs
2106          */
2107         spa->spa_async_zio_root = zio_root(spa, NULL, NULL,
2108             ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE | ZIO_FLAG_GODFATHER);
2109
2110         /*
2111          * Create the root vdev.
2112          */
2113         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2114
2115         error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, VDEV_ALLOC_ADD);
2116
2117         ASSERT(error != 0 || rvd != NULL);
2118         ASSERT(error != 0 || spa->spa_root_vdev == rvd);
2119
2120         if (error == 0 && !zfs_allocatable_devs(nvroot))
2121                 error = EINVAL;
2122
2123         if (error == 0 &&
2124             (error = vdev_create(rvd, txg, B_FALSE)) == 0 &&
2125             (error = spa_validate_aux(spa, nvroot, txg,
2126             VDEV_ALLOC_ADD)) == 0) {
2127                 for (c = 0; c < rvd->vdev_children; c++)
2128                         vdev_init(rvd->vdev_child[c], txg);
2129                 vdev_config_dirty(rvd);
2130         }
2131
2132         spa_config_exit(spa, SCL_ALL, FTAG);
2133
2134         if (error != 0) {
2135                 spa_unload(spa);
2136                 spa_deactivate(spa);
2137                 spa_remove(spa);
2138                 mutex_exit(&spa_namespace_lock);
2139                 return (error);
2140         }
2141
2142         /*
2143          * Get the list of spares, if specified.
2144          */
2145         if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
2146             &spares, &nspares) == 0) {
2147                 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config, NV_UNIQUE_NAME,
2148                     KM_SLEEP) == 0);
2149                 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
2150                     ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
2151                 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2152                 spa_load_spares(spa);
2153                 spa_config_exit(spa, SCL_ALL, FTAG);
2154                 spa->spa_spares.sav_sync = B_TRUE;
2155         }
2156
2157         /*
2158          * Get the list of level 2 cache devices, if specified.
2159          */
2160         if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
2161             &l2cache, &nl2cache) == 0) {
2162                 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
2163                     NV_UNIQUE_NAME, KM_SLEEP) == 0);
2164                 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
2165                     ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
2166                 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2167                 spa_load_l2cache(spa);
2168                 spa_config_exit(spa, SCL_ALL, FTAG);
2169                 spa->spa_l2cache.sav_sync = B_TRUE;
2170         }
2171
2172         spa->spa_dsl_pool = dp = dsl_pool_create(spa, zplprops, txg);
2173         spa->spa_meta_objset = dp->dp_meta_objset;
2174
2175         tx = dmu_tx_create_assigned(dp, txg);
2176
2177         /*
2178          * Create the pool config object.
2179          */
2180         spa->spa_config_object = dmu_object_alloc(spa->spa_meta_objset,
2181             DMU_OT_PACKED_NVLIST, SPA_CONFIG_BLOCKSIZE,
2182             DMU_OT_PACKED_NVLIST_SIZE, sizeof (uint64_t), tx);
2183
2184         if (zap_add(spa->spa_meta_objset,
2185             DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CONFIG,
2186             sizeof (uint64_t), 1, &spa->spa_config_object, tx) != 0) {
2187                 cmn_err(CE_PANIC, "failed to add pool config");
2188         }
2189
2190         /* Newly created pools with the right version are always deflated. */
2191         if (version >= SPA_VERSION_RAIDZ_DEFLATE) {
2192                 spa->spa_deflate = TRUE;
2193                 if (zap_add(spa->spa_meta_objset,
2194                     DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
2195                     sizeof (uint64_t), 1, &spa->spa_deflate, tx) != 0) {
2196                         cmn_err(CE_PANIC, "failed to add deflate");
2197                 }
2198         }
2199
2200         /*
2201          * Create the deferred-free bplist object.  Turn off compression
2202          * because sync-to-convergence takes longer if the blocksize
2203          * keeps changing.
2204          */
2205         spa->spa_sync_bplist_obj = bplist_create(spa->spa_meta_objset,
2206             1 << 14, tx);
2207         dmu_object_set_compress(spa->spa_meta_objset, spa->spa_sync_bplist_obj,
2208             ZIO_COMPRESS_OFF, tx);
2209
2210         if (zap_add(spa->spa_meta_objset,
2211             DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SYNC_BPLIST,
2212             sizeof (uint64_t), 1, &spa->spa_sync_bplist_obj, tx) != 0) {
2213                 cmn_err(CE_PANIC, "failed to add bplist");
2214         }
2215
2216         /*
2217          * Create the pool's history object.
2218          */
2219         if (version >= SPA_VERSION_ZPOOL_HISTORY)
2220                 spa_history_create_obj(spa, tx);
2221
2222         /*
2223          * Set pool properties.
2224          */
2225         spa->spa_bootfs = zpool_prop_default_numeric(ZPOOL_PROP_BOOTFS);
2226         spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
2227         spa->spa_failmode = zpool_prop_default_numeric(ZPOOL_PROP_FAILUREMODE);
2228         if (props != NULL) {
2229                 spa_configfile_set(spa, props, B_FALSE);
2230                 spa_sync_props(spa, props, CRED(), tx);
2231         }
2232
2233         dmu_tx_commit(tx);
2234
2235         spa->spa_sync_on = B_TRUE;
2236         txg_sync_start(spa->spa_dsl_pool);
2237
2238         /*
2239          * We explicitly wait for the first transaction to complete so that our
2240          * bean counters are appropriately updated.
2241          */
2242         txg_wait_synced(spa->spa_dsl_pool, txg);
2243
2244         spa_config_sync(spa, B_FALSE, B_TRUE);
2245
2246         if (version >= SPA_VERSION_ZPOOL_HISTORY && history_str != NULL)
2247                 (void) spa_history_log(spa, history_str, LOG_CMD_POOL_CREATE);
2248
2249         spa->spa_minref = refcount_count(&spa->spa_refcount);
2250
2251         mutex_exit(&spa_namespace_lock);
2252
2253         return (0);
2254 }
2255
2256 #ifdef sun
2257 #ifdef _KERNEL
2258 /*
2259  * Build a "root" vdev for a top level vdev read in from a rootpool
2260  * device label.
2261  */
2262 static void
2263 spa_build_rootpool_config(nvlist_t *config)
2264 {
2265         nvlist_t *nvtop, *nvroot;
2266         uint64_t pgid;
2267
2268         /*
2269          * Add this top-level vdev to the child array.
2270          */
2271         VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvtop)
2272             == 0);
2273         VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pgid)
2274             == 0);
2275
2276         /*
2277          * Put this pool's top-level vdevs into a root vdev.
2278          */
2279         VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2280         VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE, VDEV_TYPE_ROOT)
2281             == 0);
2282         VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
2283         VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
2284         VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
2285             &nvtop, 1) == 0);
2286
2287         /*
2288          * Replace the existing vdev_tree with the new root vdev in
2289          * this pool's configuration (remove the old, add the new).
2290          */
2291         VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
2292         nvlist_free(nvroot);
2293 }
2294
2295 /*
2296  * Get the root pool information from the root disk, then import the root pool
2297  * during the system boot up time.
2298  */
2299 extern int vdev_disk_read_rootlabel(char *, char *, nvlist_t **);
2300
2301 int
2302 spa_check_rootconf(char *devpath, char *devid, nvlist_t **bestconf,
2303     uint64_t *besttxg)
2304 {
2305         nvlist_t *config;
2306         uint64_t txg;
2307         int error;
2308
2309         if (error = vdev_disk_read_rootlabel(devpath, devid, &config))
2310                 return (error);
2311
2312         VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg) == 0);
2313
2314         if (bestconf != NULL)
2315                 *bestconf = config;
2316         else
2317                 nvlist_free(config);
2318         *besttxg = txg;
2319         return (0);
2320 }
2321
2322 boolean_t
2323 spa_rootdev_validate(nvlist_t *nv)
2324 {
2325         uint64_t ival;
2326
2327         if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_OFFLINE, &ival) == 0 ||
2328             nvlist_lookup_uint64(nv, ZPOOL_CONFIG_FAULTED, &ival) == 0 ||
2329             nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVED, &ival) == 0)
2330                 return (B_FALSE);
2331
2332         return (B_TRUE);
2333 }
2334
2335
2336 /*
2337  * Given the boot device's physical path or devid, check if the device
2338  * is in a valid state.  If so, return the configuration from the vdev
2339  * label.
2340  */
2341 int
2342 spa_get_rootconf(char *devpath, char *devid, nvlist_t **bestconf)
2343 {
2344         nvlist_t *conf = NULL;
2345         uint64_t txg = 0;
2346         nvlist_t *nvtop, **child;
2347         char *type;
2348         char *bootpath = NULL;
2349         uint_t children, c;
2350         char *tmp;
2351         int error;
2352
2353         if (devpath && ((tmp = strchr(devpath, ' ')) != NULL))
2354                 *tmp = '\0';
2355         if (error = spa_check_rootconf(devpath, devid, &conf, &txg)) {
2356                 cmn_err(CE_NOTE, "error reading device label");
2357                 return (error);
2358         }
2359         if (txg == 0) {
2360                 cmn_err(CE_NOTE, "this device is detached");
2361                 nvlist_free(conf);
2362                 return (EINVAL);
2363         }
2364
2365         VERIFY(nvlist_lookup_nvlist(conf, ZPOOL_CONFIG_VDEV_TREE,
2366             &nvtop) == 0);
2367         VERIFY(nvlist_lookup_string(nvtop, ZPOOL_CONFIG_TYPE, &type) == 0);
2368
2369         if (strcmp(type, VDEV_TYPE_DISK) == 0) {
2370                 if (spa_rootdev_validate(nvtop)) {
2371                         goto out;
2372                 } else {
2373                         nvlist_free(conf);
2374                         return (EINVAL);
2375                 }
2376         }
2377
2378         ASSERT(strcmp(type, VDEV_TYPE_MIRROR) == 0);
2379
2380         VERIFY(nvlist_lookup_nvlist_array(nvtop, ZPOOL_CONFIG_CHILDREN,
2381             &child, &children) == 0);
2382
2383         /*
2384          * Go thru vdevs in the mirror to see if the given device
2385          * has the most recent txg. Only the device with the most
2386          * recent txg has valid information and should be booted.
2387          */
2388         for (c = 0; c < children; c++) {
2389                 char *cdevid, *cpath;
2390                 uint64_t tmptxg;
2391
2392                 cpath = NULL;
2393                 cdevid = NULL;
2394                 if (nvlist_lookup_string(child[c], ZPOOL_CONFIG_PHYS_PATH,
2395                     &cpath) != 0 && nvlist_lookup_string(child[c],
2396                     ZPOOL_CONFIG_DEVID, &cdevid) != 0)
2397                         return (EINVAL);
2398                 if ((spa_check_rootconf(cpath, cdevid, NULL,
2399                     &tmptxg) == 0) && (tmptxg > txg)) {
2400                         txg = tmptxg;
2401                         VERIFY(nvlist_lookup_string(child[c],
2402                             ZPOOL_CONFIG_PATH, &bootpath) == 0);
2403                 }
2404         }
2405
2406         /* Does the best device match the one we've booted from? */
2407         if (bootpath) {
2408                 cmn_err(CE_NOTE, "try booting from '%s'", bootpath);
2409                 return (EINVAL);
2410         }
2411 out:
2412         *bestconf = conf;
2413         return (0);
2414 }
2415
2416 /*
2417  * Import a root pool.
2418  *
2419  * For x86. devpath_list will consist of devid and/or physpath name of
2420  * the vdev (e.g. "id1,sd@SSEAGATE..." or "/pci@1f,0/ide@d/disk@0,0:a").
2421  * The GRUB "findroot" command will return the vdev we should boot.
2422  *
2423  * For Sparc, devpath_list consists the physpath name of the booting device
2424  * no matter the rootpool is a single device pool or a mirrored pool.
2425  * e.g.
2426  *      "/pci@1f,0/ide@d/disk@0,0:a"
2427  */
2428 int
2429 spa_import_rootpool(char *devpath, char *devid)
2430 {
2431         nvlist_t *conf = NULL;
2432         char *pname;
2433         int error;
2434         spa_t *spa;
2435
2436         /*
2437          * Get the vdev pathname and configuation from the most
2438          * recently updated vdev (highest txg).
2439          */
2440         if (error = spa_get_rootconf(devpath, devid, &conf))
2441                 goto msg_out;
2442
2443         /*
2444          * Add type "root" vdev to the config.
2445          */
2446         spa_build_rootpool_config(conf);
2447
2448         VERIFY(nvlist_lookup_string(conf, ZPOOL_CONFIG_POOL_NAME, &pname) == 0);
2449
2450         mutex_enter(&spa_namespace_lock);
2451         if ((spa = spa_lookup(pname)) != NULL) {
2452                 /*
2453                  * Remove the existing root pool from the namespace so that we
2454                  * can replace it with the correct config we just read in.
2455                  */
2456                 spa_remove(spa);
2457         }
2458
2459         spa = spa_add(pname, NULL);
2460         spa->spa_is_root = B_TRUE;
2461         spa->spa_load_verbatim = B_TRUE;
2462
2463         VERIFY(nvlist_dup(conf, &spa->spa_config, 0) == 0);
2464         mutex_exit(&spa_namespace_lock);
2465
2466         nvlist_free(conf);
2467         return (0);
2468
2469 msg_out:
2470         cmn_err(CE_NOTE, "\n"
2471             "  ***************************************************  \n"
2472             "  *  This device is not bootable!                   *  \n"
2473             "  *  It is either offlined or detached or faulted.  *  \n"
2474             "  *  Please try to boot from a different device.    *  \n"
2475             "  ***************************************************  ");
2476
2477         return (error);
2478 }
2479 #endif
2480 #endif  /* sun */
2481
2482 /*
2483  * Take a pool and insert it into the namespace as if it had been loaded at
2484  * boot.
2485  */
2486 int
2487 spa_import_verbatim(const char *pool, nvlist_t *config, nvlist_t *props)
2488 {
2489         spa_t *spa;
2490         char *altroot = NULL;
2491
2492         mutex_enter(&spa_namespace_lock);
2493         if (spa_lookup(pool) != NULL) {
2494                 mutex_exit(&spa_namespace_lock);
2495                 return (EEXIST);
2496         }
2497
2498         (void) nvlist_lookup_string(props,
2499             zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
2500         spa = spa_add(pool, altroot);
2501
2502         spa->spa_load_verbatim = B_TRUE;
2503
2504         VERIFY(nvlist_dup(config, &spa->spa_config, 0) == 0);
2505
2506         if (props != NULL)
2507                 spa_configfile_set(spa, props, B_FALSE);
2508
2509         spa_config_sync(spa, B_FALSE, B_TRUE);
2510
2511         mutex_exit(&spa_namespace_lock);
2512
2513         return (0);
2514 }
2515
2516 /*
2517  * Import a non-root pool into the system.
2518  */
2519 int
2520 spa_import(const char *pool, nvlist_t *config, nvlist_t *props)
2521 {
2522         spa_t *spa;
2523         char *altroot = NULL;
2524         int error;
2525         nvlist_t *nvroot;
2526         nvlist_t **spares, **l2cache;
2527         uint_t nspares, nl2cache;
2528
2529         /*
2530          * If a pool with this name exists, return failure.
2531          */
2532         mutex_enter(&spa_namespace_lock);
2533         if ((spa = spa_lookup(pool)) != NULL) {
2534                 mutex_exit(&spa_namespace_lock);
2535                 return (EEXIST);
2536         }
2537
2538         /*
2539          * Create and initialize the spa structure.
2540          */
2541         (void) nvlist_lookup_string(props,
2542             zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
2543         spa = spa_add(pool, altroot);
2544         spa_activate(spa, spa_mode_global);
2545
2546         /*
2547          * Don't start async tasks until we know everything is healthy.
2548          */
2549         spa_async_suspend(spa);
2550
2551         /*
2552          * Pass off the heavy lifting to spa_load().  Pass TRUE for mosconfig
2553          * because the user-supplied config is actually the one to trust when
2554          * doing an import.
2555          */
2556         error = spa_load(spa, config, SPA_LOAD_IMPORT, B_TRUE);
2557
2558         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2559         /*
2560          * Toss any existing sparelist, as it doesn't have any validity
2561          * anymore, and conflicts with spa_has_spare().
2562          */
2563         if (spa->spa_spares.sav_config) {
2564                 nvlist_free(spa->spa_spares.sav_config);
2565                 spa->spa_spares.sav_config = NULL;
2566                 spa_load_spares(spa);
2567         }
2568         if (spa->spa_l2cache.sav_config) {
2569                 nvlist_free(spa->spa_l2cache.sav_config);
2570                 spa->spa_l2cache.sav_config = NULL;
2571                 spa_load_l2cache(spa);
2572         }
2573
2574         VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2575             &nvroot) == 0);
2576         if (error == 0)
2577                 error = spa_validate_aux(spa, nvroot, -1ULL,
2578                     VDEV_ALLOC_SPARE);
2579         if (error == 0)
2580                 error = spa_validate_aux(spa, nvroot, -1ULL,
2581                     VDEV_ALLOC_L2CACHE);
2582         spa_config_exit(spa, SCL_ALL, FTAG);
2583
2584         if (props != NULL)
2585                 spa_configfile_set(spa, props, B_FALSE);
2586
2587         if (error != 0 || (props && spa_writeable(spa) &&
2588             (error = spa_prop_set(spa, props)))) {
2589                 spa_unload(spa);
2590                 spa_deactivate(spa);
2591                 spa_remove(spa);
2592                 mutex_exit(&spa_namespace_lock);
2593                 return (error);
2594         }
2595
2596         spa_async_resume(spa);
2597
2598         /*
2599          * Override any spares and level 2 cache devices as specified by
2600          * the user, as these may have correct device names/devids, etc.
2601          */
2602         if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
2603             &spares, &nspares) == 0) {
2604                 if (spa->spa_spares.sav_config)
2605                         VERIFY(nvlist_remove(spa->spa_spares.sav_config,
2606                             ZPOOL_CONFIG_SPARES, DATA_TYPE_NVLIST_ARRAY) == 0);
2607                 else
2608                         VERIFY(nvlist_alloc(&spa->spa_spares.sav_config,
2609                             NV_UNIQUE_NAME, KM_SLEEP) == 0);
2610                 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
2611                     ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
2612                 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2613                 spa_load_spares(spa);
2614                 spa_config_exit(spa, SCL_ALL, FTAG);
2615                 spa->spa_spares.sav_sync = B_TRUE;
2616         }
2617         if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
2618             &l2cache, &nl2cache) == 0) {
2619                 if (spa->spa_l2cache.sav_config)
2620                         VERIFY(nvlist_remove(spa->spa_l2cache.sav_config,
2621                             ZPOOL_CONFIG_L2CACHE, DATA_TYPE_NVLIST_ARRAY) == 0);
2622                 else
2623                         VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
2624                             NV_UNIQUE_NAME, KM_SLEEP) == 0);
2625                 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
2626                     ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
2627                 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2628                 spa_load_l2cache(spa);
2629                 spa_config_exit(spa, SCL_ALL, FTAG);
2630                 spa->spa_l2cache.sav_sync = B_TRUE;
2631         }
2632
2633         if (spa_writeable(spa)) {
2634                 /*
2635                  * Update the config cache to include the newly-imported pool.
2636                  */
2637                 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
2638         }
2639
2640         mutex_exit(&spa_namespace_lock);
2641
2642         return (0);
2643 }
2644
2645 /*
2646  * This (illegal) pool name is used when temporarily importing a spa_t in order
2647  * to get the vdev stats associated with the imported devices.
2648  */
2649 #define TRYIMPORT_NAME  "$import"
2650
2651 nvlist_t *
2652 spa_tryimport(nvlist_t *tryconfig)
2653 {
2654         nvlist_t *config = NULL;
2655         char *poolname;
2656         spa_t *spa;
2657         uint64_t state;
2658         int error;
2659
2660         if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_POOL_NAME, &poolname))
2661                 return (NULL);
2662
2663         if (nvlist_lookup_uint64(tryconfig, ZPOOL_CONFIG_POOL_STATE, &state))
2664                 return (NULL);
2665
2666         /*
2667          * Create and initialize the spa structure.
2668          */
2669         mutex_enter(&spa_namespace_lock);
2670         spa = spa_add(TRYIMPORT_NAME, NULL);
2671         spa_activate(spa, FREAD);
2672
2673         /*
2674          * Pass off the heavy lifting to spa_load().
2675          * Pass TRUE for mosconfig because the user-supplied config
2676          * is actually the one to trust when doing an import.
2677          */
2678         error = spa_load(spa, tryconfig, SPA_LOAD_TRYIMPORT, B_TRUE);
2679
2680         /*
2681          * If 'tryconfig' was at least parsable, return the current config.
2682          */
2683         if (spa->spa_root_vdev != NULL) {
2684                 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
2685                 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME,
2686                     poolname) == 0);
2687                 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
2688                     state) == 0);
2689                 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
2690                     spa->spa_uberblock.ub_timestamp) == 0);
2691
2692                 /*
2693                  * If the bootfs property exists on this pool then we
2694                  * copy it out so that external consumers can tell which
2695                  * pools are bootable.
2696                  */
2697                 if ((!error || error == EEXIST) && spa->spa_bootfs) {
2698                         char *tmpname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
2699
2700                         /*
2701                          * We have to play games with the name since the
2702                          * pool was opened as TRYIMPORT_NAME.
2703                          */
2704                         if (dsl_dsobj_to_dsname(spa_name(spa),
2705                             spa->spa_bootfs, tmpname) == 0) {
2706                                 char *cp;
2707                                 char *dsname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
2708
2709                                 cp = strchr(tmpname, '/');
2710                                 if (cp == NULL) {
2711                                         (void) strlcpy(dsname, tmpname,
2712                                             MAXPATHLEN);
2713                                 } else {
2714                                         (void) snprintf(dsname, MAXPATHLEN,
2715                                             "%s/%s", poolname, ++cp);
2716                                 }
2717                                 VERIFY(nvlist_add_string(config,
2718                                     ZPOOL_CONFIG_BOOTFS, dsname) == 0);
2719                                 kmem_free(dsname, MAXPATHLEN);
2720                         }
2721                         kmem_free(tmpname, MAXPATHLEN);
2722                 }
2723
2724                 /*
2725                  * Add the list of hot spares and level 2 cache devices.
2726                  */
2727                 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
2728                 spa_add_spares(spa, config);
2729                 spa_add_l2cache(spa, config);
2730                 spa_config_exit(spa, SCL_CONFIG, FTAG);
2731         }
2732
2733         spa_unload(spa);
2734         spa_deactivate(spa);
2735         spa_remove(spa);
2736         mutex_exit(&spa_namespace_lock);
2737
2738         return (config);
2739 }
2740
2741 /*
2742  * Pool export/destroy
2743  *
2744  * The act of destroying or exporting a pool is very simple.  We make sure there
2745  * is no more pending I/O and any references to the pool are gone.  Then, we
2746  * update the pool state and sync all the labels to disk, removing the
2747  * configuration from the cache afterwards. If the 'hardforce' flag is set, then
2748  * we don't sync the labels or remove the configuration cache.
2749  */
2750 static int
2751 spa_export_common(char *pool, int new_state, nvlist_t **oldconfig,
2752     boolean_t force, boolean_t hardforce)
2753 {
2754         spa_t *spa;
2755
2756         if (oldconfig)
2757                 *oldconfig = NULL;
2758
2759         if (!(spa_mode_global & FWRITE))
2760                 return (EROFS);
2761
2762         mutex_enter(&spa_namespace_lock);
2763         if ((spa = spa_lookup(pool)) == NULL) {
2764                 mutex_exit(&spa_namespace_lock);
2765                 return (ENOENT);
2766         }
2767
2768         /*
2769          * Put a hold on the pool, drop the namespace lock, stop async tasks,
2770          * reacquire the namespace lock, and see if we can export.
2771          */
2772         spa_open_ref(spa, FTAG);
2773         mutex_exit(&spa_namespace_lock);
2774         spa_async_suspend(spa);
2775         mutex_enter(&spa_namespace_lock);
2776         spa_close(spa, FTAG);
2777
2778         /*
2779          * The pool will be in core if it's openable,
2780          * in which case we can modify its state.
2781          */
2782         if (spa->spa_state != POOL_STATE_UNINITIALIZED && spa->spa_sync_on) {
2783                 /*
2784                  * Objsets may be open only because they're dirty, so we
2785                  * have to force it to sync before checking spa_refcnt.
2786                  */
2787                 txg_wait_synced(spa->spa_dsl_pool, 0);
2788
2789                 /*
2790                  * A pool cannot be exported or destroyed if there are active
2791                  * references.  If we are resetting a pool, allow references by
2792                  * fault injection handlers.
2793                  */
2794                 if (!spa_refcount_zero(spa) ||
2795                     (spa->spa_inject_ref != 0 &&
2796                     new_state != POOL_STATE_UNINITIALIZED)) {
2797                         spa_async_resume(spa);
2798                         mutex_exit(&spa_namespace_lock);
2799                         return (EBUSY);
2800                 }
2801
2802                 /*
2803                  * A pool cannot be exported if it has an active shared spare.
2804                  * This is to prevent other pools stealing the active spare
2805                  * from an exported pool. At user's own will, such pool can
2806                  * be forcedly exported.
2807                  */
2808                 if (!force && new_state == POOL_STATE_EXPORTED &&
2809                     spa_has_active_shared_spare(spa)) {
2810                         spa_async_resume(spa);
2811                         mutex_exit(&spa_namespace_lock);
2812                         return (EXDEV);
2813                 }
2814
2815                 /*
2816                  * We want this to be reflected on every label,
2817                  * so mark them all dirty.  spa_unload() will do the
2818                  * final sync that pushes these changes out.
2819                  */
2820                 if (new_state != POOL_STATE_UNINITIALIZED && !hardforce) {
2821                         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2822                         spa->spa_state = new_state;
2823                         spa->spa_final_txg = spa_last_synced_txg(spa) + 1;
2824                         vdev_config_dirty(spa->spa_root_vdev);
2825                         spa_config_exit(spa, SCL_ALL, FTAG);
2826                 }
2827         }
2828
2829         spa_event_notify(spa, NULL, ESC_ZFS_POOL_DESTROY);
2830
2831         if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
2832                 spa_unload(spa);
2833                 spa_deactivate(spa);
2834         }
2835
2836         if (oldconfig && spa->spa_config)
2837                 VERIFY(nvlist_dup(spa->spa_config, oldconfig, 0) == 0);
2838
2839         if (new_state != POOL_STATE_UNINITIALIZED) {
2840                 if (!hardforce)
2841                         spa_config_sync(spa, B_TRUE, B_TRUE);
2842                 spa_remove(spa);
2843         }
2844         mutex_exit(&spa_namespace_lock);
2845
2846         return (0);
2847 }
2848
2849 /*
2850  * Destroy a storage pool.
2851  */
2852 int
2853 spa_destroy(char *pool)
2854 {
2855         return (spa_export_common(pool, POOL_STATE_DESTROYED, NULL,
2856             B_FALSE, B_FALSE));
2857 }
2858
2859 /*
2860  * Export a storage pool.
2861  */
2862 int
2863 spa_export(char *pool, nvlist_t **oldconfig, boolean_t force,
2864     boolean_t hardforce)
2865 {
2866         return (spa_export_common(pool, POOL_STATE_EXPORTED, oldconfig,
2867             force, hardforce));
2868 }
2869
2870 /*
2871  * Similar to spa_export(), this unloads the spa_t without actually removing it
2872  * from the namespace in any way.
2873  */
2874 int
2875 spa_reset(char *pool)
2876 {
2877         return (spa_export_common(pool, POOL_STATE_UNINITIALIZED, NULL,
2878             B_FALSE, B_FALSE));
2879 }
2880
2881 /*
2882  * ==========================================================================
2883  * Device manipulation
2884  * ==========================================================================
2885  */
2886
2887 /*
2888  * Add a device to a storage pool.
2889  */
2890 int
2891 spa_vdev_add(spa_t *spa, nvlist_t *nvroot)
2892 {
2893         uint64_t txg;
2894         int error;
2895         vdev_t *rvd = spa->spa_root_vdev;
2896         vdev_t *vd, *tvd;
2897         nvlist_t **spares, **l2cache;
2898         uint_t nspares, nl2cache;
2899
2900         txg = spa_vdev_enter(spa);
2901
2902         if ((error = spa_config_parse(spa, &vd, nvroot, NULL, 0,
2903             VDEV_ALLOC_ADD)) != 0)
2904                 return (spa_vdev_exit(spa, NULL, txg, error));
2905
2906         spa->spa_pending_vdev = vd;     /* spa_vdev_exit() will clear this */
2907
2908         if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares,
2909             &nspares) != 0)
2910                 nspares = 0;
2911
2912         if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE, &l2cache,
2913             &nl2cache) != 0)
2914                 nl2cache = 0;
2915
2916         if (vd->vdev_children == 0 && nspares == 0 && nl2cache == 0)
2917                 return (spa_vdev_exit(spa, vd, txg, EINVAL));
2918
2919         if (vd->vdev_children != 0 &&
2920             (error = vdev_create(vd, txg, B_FALSE)) != 0)
2921                 return (spa_vdev_exit(spa, vd, txg, error));
2922
2923         /*
2924          * We must validate the spares and l2cache devices after checking the
2925          * children.  Otherwise, vdev_inuse() will blindly overwrite the spare.
2926          */
2927         if ((error = spa_validate_aux(spa, nvroot, txg, VDEV_ALLOC_ADD)) != 0)
2928                 return (spa_vdev_exit(spa, vd, txg, error));
2929
2930         /*
2931          * Transfer each new top-level vdev from vd to rvd.
2932          */
2933         for (int c = 0; c < vd->vdev_children; c++) {
2934                 tvd = vd->vdev_child[c];
2935                 vdev_remove_child(vd, tvd);
2936                 tvd->vdev_id = rvd->vdev_children;
2937                 vdev_add_child(rvd, tvd);
2938                 vdev_config_dirty(tvd);
2939         }
2940
2941         if (nspares != 0) {
2942                 spa_set_aux_vdevs(&spa->spa_spares, spares, nspares,
2943                     ZPOOL_CONFIG_SPARES);
2944                 spa_load_spares(spa);
2945                 spa->spa_spares.sav_sync = B_TRUE;
2946         }
2947
2948         if (nl2cache != 0) {
2949                 spa_set_aux_vdevs(&spa->spa_l2cache, l2cache, nl2cache,
2950                     ZPOOL_CONFIG_L2CACHE);
2951                 spa_load_l2cache(spa);
2952                 spa->spa_l2cache.sav_sync = B_TRUE;
2953         }
2954
2955         /*
2956          * We have to be careful when adding new vdevs to an existing pool.
2957          * If other threads start allocating from these vdevs before we
2958          * sync the config cache, and we lose power, then upon reboot we may
2959          * fail to open the pool because there are DVAs that the config cache
2960          * can't translate.  Therefore, we first add the vdevs without
2961          * initializing metaslabs; sync the config cache (via spa_vdev_exit());
2962          * and then let spa_config_update() initialize the new metaslabs.
2963          *
2964          * spa_load() checks for added-but-not-initialized vdevs, so that
2965          * if we lose power at any point in this sequence, the remaining
2966          * steps will be completed the next time we load the pool.
2967          */
2968         (void) spa_vdev_exit(spa, vd, txg, 0);
2969
2970         mutex_enter(&spa_namespace_lock);
2971         spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
2972         mutex_exit(&spa_namespace_lock);
2973
2974         return (0);
2975 }
2976
2977 /*
2978  * Attach a device to a mirror.  The arguments are the path to any device
2979  * in the mirror, and the nvroot for the new device.  If the path specifies
2980  * a device that is not mirrored, we automatically insert the mirror vdev.
2981  *
2982  * If 'replacing' is specified, the new device is intended to replace the
2983  * existing device; in this case the two devices are made into their own
2984  * mirror using the 'replacing' vdev, which is functionally identical to
2985  * the mirror vdev (it actually reuses all the same ops) but has a few
2986  * extra rules: you can't attach to it after it's been created, and upon
2987  * completion of resilvering, the first disk (the one being replaced)
2988  * is automatically detached.
2989  */
2990 int
2991 spa_vdev_attach(spa_t *spa, uint64_t guid, nvlist_t *nvroot, int replacing)
2992 {
2993         uint64_t txg, open_txg;
2994         vdev_t *rvd = spa->spa_root_vdev;
2995         vdev_t *oldvd, *newvd, *newrootvd, *pvd, *tvd;
2996         vdev_ops_t *pvops;
2997         dmu_tx_t *tx;
2998         char *oldvdpath, *newvdpath;
2999         int newvd_isspare;
3000         int error;
3001
3002         txg = spa_vdev_enter(spa);
3003
3004         oldvd = spa_lookup_by_guid(spa, guid, B_FALSE);
3005
3006         if (oldvd == NULL)
3007                 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
3008
3009         if (!oldvd->vdev_ops->vdev_op_leaf)
3010                 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
3011
3012         pvd = oldvd->vdev_parent;
3013
3014         if ((error = spa_config_parse(spa, &newrootvd, nvroot, NULL, 0,
3015             VDEV_ALLOC_ADD)) != 0)
3016                 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
3017
3018         if (newrootvd->vdev_children != 1)
3019                 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
3020
3021         newvd = newrootvd->vdev_child[0];
3022
3023         if (!newvd->vdev_ops->vdev_op_leaf)
3024                 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
3025
3026         if ((error = vdev_create(newrootvd, txg, replacing)) != 0)
3027                 return (spa_vdev_exit(spa, newrootvd, txg, error));
3028
3029         /*
3030          * Spares can't replace logs
3031          */
3032         if (oldvd->vdev_top->vdev_islog && newvd->vdev_isspare)
3033                 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
3034
3035         if (!replacing) {
3036                 /*
3037                  * For attach, the only allowable parent is a mirror or the root
3038                  * vdev.
3039                  */
3040                 if (pvd->vdev_ops != &vdev_mirror_ops &&
3041                     pvd->vdev_ops != &vdev_root_ops)
3042                         return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
3043
3044                 pvops = &vdev_mirror_ops;
3045         } else {
3046                 /*
3047                  * Active hot spares can only be replaced by inactive hot
3048                  * spares.
3049                  */
3050                 if (pvd->vdev_ops == &vdev_spare_ops &&
3051                     pvd->vdev_child[1] == oldvd &&
3052                     !spa_has_spare(spa, newvd->vdev_guid))
3053                         return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
3054
3055                 /*
3056                  * If the source is a hot spare, and the parent isn't already a
3057                  * spare, then we want to create a new hot spare.  Otherwise, we
3058                  * want to create a replacing vdev.  The user is not allowed to
3059                  * attach to a spared vdev child unless the 'isspare' state is
3060                  * the same (spare replaces spare, non-spare replaces
3061                  * non-spare).
3062                  */
3063                 if (pvd->vdev_ops == &vdev_replacing_ops)
3064                         return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
3065                 else if (pvd->vdev_ops == &vdev_spare_ops &&
3066                     newvd->vdev_isspare != oldvd->vdev_isspare)
3067                         return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
3068                 else if (pvd->vdev_ops != &vdev_spare_ops &&
3069                     newvd->vdev_isspare)
3070                         pvops = &vdev_spare_ops;
3071                 else
3072                         pvops = &vdev_replacing_ops;
3073         }
3074
3075         /*
3076          * Compare the new device size with the replaceable/attachable
3077          * device size.
3078          */
3079         if (newvd->vdev_psize < vdev_get_rsize(oldvd))
3080                 return (spa_vdev_exit(spa, newrootvd, txg, EOVERFLOW));
3081
3082         /*
3083          * The new device cannot have a higher alignment requirement
3084          * than the top-level vdev.
3085          */
3086         if (newvd->vdev_ashift > oldvd->vdev_top->vdev_ashift)
3087                 return (spa_vdev_exit(spa, newrootvd, txg, EDOM));
3088
3089         /*
3090          * If this is an in-place replacement, update oldvd's path and devid
3091          * to make it distinguishable from newvd, and unopenable from now on.
3092          */
3093         if (strcmp(oldvd->vdev_path, newvd->vdev_path) == 0) {
3094                 spa_strfree(oldvd->vdev_path);
3095                 oldvd->vdev_path = kmem_alloc(strlen(newvd->vdev_path) + 5,
3096                     KM_SLEEP);
3097                 (void) sprintf(oldvd->vdev_path, "%s/%s",
3098                     newvd->vdev_path, "old");
3099                 if (oldvd->vdev_devid != NULL) {
3100                         spa_strfree(oldvd->vdev_devid);
3101                         oldvd->vdev_devid = NULL;
3102                 }
3103         }
3104
3105         /*
3106          * If the parent is not a mirror, or if we're replacing, insert the new
3107          * mirror/replacing/spare vdev above oldvd.
3108          */
3109         if (pvd->vdev_ops != pvops)
3110                 pvd = vdev_add_parent(oldvd, pvops);
3111
3112         ASSERT(pvd->vdev_top->vdev_parent == rvd);
3113         ASSERT(pvd->vdev_ops == pvops);
3114         ASSERT(oldvd->vdev_parent == pvd);
3115
3116         /*
3117          * Extract the new device from its root and add it to pvd.
3118          */
3119         vdev_remove_child(newrootvd, newvd);
3120         newvd->vdev_id = pvd->vdev_children;
3121         vdev_add_child(pvd, newvd);
3122
3123         /*
3124          * If newvd is smaller than oldvd, but larger than its rsize,
3125          * the addition of newvd may have decreased our parent's asize.
3126          */
3127         pvd->vdev_asize = MIN(pvd->vdev_asize, newvd->vdev_asize);
3128
3129         tvd = newvd->vdev_top;
3130         ASSERT(pvd->vdev_top == tvd);
3131         ASSERT(tvd->vdev_parent == rvd);
3132
3133         vdev_config_dirty(tvd);
3134
3135         /*
3136          * Set newvd's DTL to [TXG_INITIAL, open_txg].  It will propagate
3137          * upward when spa_vdev_exit() calls vdev_dtl_reassess().
3138          */
3139         open_txg = txg + TXG_CONCURRENT_STATES - 1;
3140
3141         vdev_dtl_dirty(newvd, DTL_MISSING,
3142             TXG_INITIAL, open_txg - TXG_INITIAL + 1);
3143
3144         if (newvd->vdev_isspare) {
3145                 spa_spare_activate(newvd);
3146                 spa_event_notify(spa, newvd, ESC_ZFS_VDEV_SPARE);
3147         }
3148
3149         oldvdpath = spa_strdup(oldvd->vdev_path);
3150         newvdpath = spa_strdup(newvd->vdev_path);
3151         newvd_isspare = newvd->vdev_isspare;
3152
3153         /*
3154          * Mark newvd's DTL dirty in this txg.
3155          */
3156         vdev_dirty(tvd, VDD_DTL, newvd, txg);
3157
3158         (void) spa_vdev_exit(spa, newrootvd, open_txg, 0);
3159
3160         tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
3161         if (dmu_tx_assign(tx, TXG_WAIT) == 0) {
3162                 spa_history_internal_log(LOG_POOL_VDEV_ATTACH, spa, tx,
3163                     CRED(),  "%s vdev=%s %s vdev=%s",
3164                     replacing && newvd_isspare ? "spare in" :
3165                     replacing ? "replace" : "attach", newvdpath,
3166                     replacing ? "for" : "to", oldvdpath);
3167                 dmu_tx_commit(tx);
3168         } else {
3169                 dmu_tx_abort(tx);
3170         }
3171
3172         spa_strfree(oldvdpath);
3173         spa_strfree(newvdpath);
3174
3175         /*
3176          * Kick off a resilver to update newvd.
3177          */
3178         VERIFY3U(spa_scrub(spa, POOL_SCRUB_RESILVER), ==, 0);
3179
3180         return (0);
3181 }
3182
3183 /*
3184  * Detach a device from a mirror or replacing vdev.
3185  * If 'replace_done' is specified, only detach if the parent
3186  * is a replacing vdev.
3187  */
3188 int
3189 spa_vdev_detach(spa_t *spa, uint64_t guid, uint64_t pguid, int replace_done)
3190 {
3191         uint64_t txg;
3192         int error;
3193         vdev_t *rvd = spa->spa_root_vdev;
3194         vdev_t *vd, *pvd, *cvd, *tvd;
3195         boolean_t unspare = B_FALSE;
3196         uint64_t unspare_guid;
3197         size_t len;
3198
3199         txg = spa_vdev_enter(spa);
3200
3201         vd = spa_lookup_by_guid(spa, guid, B_FALSE);
3202
3203         if (vd == NULL)
3204                 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
3205
3206         if (!vd->vdev_ops->vdev_op_leaf)
3207                 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
3208
3209         pvd = vd->vdev_parent;
3210
3211         /*
3212          * If the parent/child relationship is not as expected, don't do it.
3213          * Consider M(A,R(B,C)) -- that is, a mirror of A with a replacing
3214          * vdev that's replacing B with C.  The user's intent in replacing
3215          * is to go from M(A,B) to M(A,C).  If the user decides to cancel
3216          * the replace by detaching C, the expected behavior is to end up
3217          * M(A,B).  But suppose that right after deciding to detach C,
3218          * the replacement of B completes.  We would have M(A,C), and then
3219          * ask to detach C, which would leave us with just A -- not what
3220          * the user wanted.  To prevent this, we make sure that the
3221          * parent/child relationship hasn't changed -- in this example,
3222          * that C's parent is still the replacing vdev R.
3223          */
3224         if (pvd->vdev_guid != pguid && pguid != 0)
3225                 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
3226
3227         /*
3228          * If replace_done is specified, only remove this device if it's
3229          * the first child of a replacing vdev.  For the 'spare' vdev, either
3230          * disk can be removed.
3231          */
3232         if (replace_done) {
3233                 if (pvd->vdev_ops == &vdev_replacing_ops) {
3234                         if (vd->vdev_id != 0)
3235                                 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
3236                 } else if (pvd->vdev_ops != &vdev_spare_ops) {
3237                         return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
3238                 }
3239         }
3240
3241         ASSERT(pvd->vdev_ops != &vdev_spare_ops ||
3242             spa_version(spa) >= SPA_VERSION_SPARES);
3243
3244         /*
3245          * Only mirror, replacing, and spare vdevs support detach.
3246          */
3247         if (pvd->vdev_ops != &vdev_replacing_ops &&
3248             pvd->vdev_ops != &vdev_mirror_ops &&
3249             pvd->vdev_ops != &vdev_spare_ops)
3250                 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
3251
3252         /*
3253          * If this device has the only valid copy of some data,
3254          * we cannot safely detach it.
3255          */
3256         if (vdev_dtl_required(vd))
3257                 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
3258
3259         ASSERT(pvd->vdev_children >= 2);
3260
3261         /*
3262          * If we are detaching the second disk from a replacing vdev, then
3263          * check to see if we changed the original vdev's path to have "/old"
3264          * at the end in spa_vdev_attach().  If so, undo that change now.
3265          */
3266         if (pvd->vdev_ops == &vdev_replacing_ops && vd->vdev_id == 1 &&
3267             pvd->vdev_child[0]->vdev_path != NULL &&
3268             pvd->vdev_child[1]->vdev_path != NULL) {
3269                 ASSERT(pvd->vdev_child[1] == vd);
3270                 cvd = pvd->vdev_child[0];
3271                 len = strlen(vd->vdev_path);
3272                 if (strncmp(cvd->vdev_path, vd->vdev_path, len) == 0 &&
3273                     strcmp(cvd->vdev_path + len, "/old") == 0) {
3274                         spa_strfree(cvd->vdev_path);
3275                         cvd->vdev_path = spa_strdup(vd->vdev_path);
3276                 }
3277         }
3278
3279         /*
3280          * If we are detaching the original disk from a spare, then it implies
3281          * that the spare should become a real disk, and be removed from the
3282          * active spare list for the pool.
3283          */
3284         if (pvd->vdev_ops == &vdev_spare_ops &&
3285             vd->vdev_id == 0 && pvd->vdev_child[1]->vdev_isspare)
3286                 unspare = B_TRUE;
3287
3288         /*
3289          * Erase the disk labels so the disk can be used for other things.
3290          * This must be done after all other error cases are handled,
3291          * but before we disembowel vd (so we can still do I/O to it).
3292          * But if we can't do it, don't treat the error as fatal --
3293          * it may be that the unwritability of the disk is the reason
3294          * it's being detached!
3295          */
3296         error = vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
3297
3298         /*
3299          * Remove vd from its parent and compact the parent's children.
3300          */
3301         vdev_remove_child(pvd, vd);
3302         vdev_compact_children(pvd);
3303
3304         /*
3305          * Remember one of the remaining children so we can get tvd below.
3306          */
3307         cvd = pvd->vdev_child[0];
3308
3309         /*
3310          * If we need to remove the remaining child from the list of hot spares,
3311          * do it now, marking the vdev as no longer a spare in the process.
3312          * We must do this before vdev_remove_parent(), because that can
3313          * change the GUID if it creates a new toplevel GUID.  For a similar
3314          * reason, we must remove the spare now, in the same txg as the detach;
3315          * otherwise someone could attach a new sibling, change the GUID, and
3316          * the subsequent attempt to spa_vdev_remove(unspare_guid) would fail.
3317          */
3318         if (unspare) {
3319                 ASSERT(cvd->vdev_isspare);
3320                 spa_spare_remove(cvd);
3321                 unspare_guid = cvd->vdev_guid;
3322                 (void) spa_vdev_remove(spa, unspare_guid, B_TRUE);
3323         }
3324
3325         /*
3326          * If the parent mirror/replacing vdev only has one child,
3327          * the parent is no longer needed.  Remove it from the tree.
3328          */
3329         if (pvd->vdev_children == 1)
3330                 vdev_remove_parent(cvd);
3331
3332         /*
3333          * We don't set tvd until now because the parent we just removed
3334          * may have been the previous top-level vdev.
3335          */
3336         tvd = cvd->vdev_top;
3337         ASSERT(tvd->vdev_parent == rvd);
3338
3339         /*
3340          * Reevaluate the parent vdev state.
3341          */
3342         vdev_propagate_state(cvd);
3343
3344         /*
3345          * If the device we just detached was smaller than the others, it may be
3346          * possible to add metaslabs (i.e. grow the pool).  vdev_metaslab_init()
3347          * can't fail because the existing metaslabs are already in core, so
3348          * there's nothing to read from disk.
3349          */
3350         VERIFY(vdev_metaslab_init(tvd, txg) == 0);
3351
3352         vdev_config_dirty(tvd);
3353
3354         /*
3355          * Mark vd's DTL as dirty in this txg.  vdev_dtl_sync() will see that
3356          * vd->vdev_detached is set and free vd's DTL object in syncing context.
3357          * But first make sure we're not on any *other* txg's DTL list, to
3358          * prevent vd from being accessed after it's freed.
3359          */
3360         for (int t = 0; t < TXG_SIZE; t++)
3361                 (void) txg_list_remove_this(&tvd->vdev_dtl_list, vd, t);
3362         vd->vdev_detached = B_TRUE;
3363         vdev_dirty(tvd, VDD_DTL, vd, txg);
3364
3365         spa_event_notify(spa, vd, ESC_ZFS_VDEV_REMOVE);
3366
3367         error = spa_vdev_exit(spa, vd, txg, 0);
3368
3369         /*
3370          * If this was the removal of the original device in a hot spare vdev,
3371          * then we want to go through and remove the device from the hot spare
3372          * list of every other pool.
3373          */
3374         if (unspare) {
3375                 spa_t *myspa = spa;
3376                 spa = NULL;
3377                 mutex_enter(&spa_namespace_lock);
3378                 while ((spa = spa_next(spa)) != NULL) {
3379                         if (spa->spa_state != POOL_STATE_ACTIVE)
3380                                 continue;
3381                         if (spa == myspa)
3382                                 continue;
3383                         spa_open_ref(spa, FTAG);
3384                         mutex_exit(&spa_namespace_lock);
3385                         (void) spa_vdev_remove(spa, unspare_guid, B_TRUE);
3386                         mutex_enter(&spa_namespace_lock);
3387                         spa_close(spa, FTAG);
3388                 }
3389                 mutex_exit(&spa_namespace_lock);
3390         }
3391
3392         return (error);
3393 }
3394
3395 static nvlist_t *
3396 spa_nvlist_lookup_by_guid(nvlist_t **nvpp, int count, uint64_t target_guid)
3397 {
3398         for (int i = 0; i < count; i++) {
3399                 uint64_t guid;
3400
3401                 VERIFY(nvlist_lookup_uint64(nvpp[i], ZPOOL_CONFIG_GUID,
3402                     &guid) == 0);
3403
3404                 if (guid == target_guid)
3405                         return (nvpp[i]);
3406         }
3407
3408         return (NULL);
3409 }
3410
3411 static void
3412 spa_vdev_remove_aux(nvlist_t *config, char *name, nvlist_t **dev, int count,
3413         nvlist_t *dev_to_remove)
3414 {
3415         nvlist_t **newdev = NULL;
3416
3417         if (count > 1)
3418                 newdev = kmem_alloc((count - 1) * sizeof (void *), KM_SLEEP);
3419
3420         for (int i = 0, j = 0; i < count; i++) {
3421                 if (dev[i] == dev_to_remove)
3422                         continue;
3423                 VERIFY(nvlist_dup(dev[i], &newdev[j++], KM_SLEEP) == 0);
3424         }
3425
3426         VERIFY(nvlist_remove(config, name, DATA_TYPE_NVLIST_ARRAY) == 0);
3427         VERIFY(nvlist_add_nvlist_array(config, name, newdev, count - 1) == 0);
3428
3429         for (int i = 0; i < count - 1; i++)
3430                 nvlist_free(newdev[i]);
3431
3432         if (count > 1)
3433                 kmem_free(newdev, (count - 1) * sizeof (void *));
3434 }
3435
3436 /*
3437  * Remove a device from the pool.  Currently, this supports removing only hot
3438  * spares and level 2 ARC devices.
3439  */
3440 int
3441 spa_vdev_remove(spa_t *spa, uint64_t guid, boolean_t unspare)
3442 {
3443         vdev_t *vd;
3444         nvlist_t **spares, **l2cache, *nv;
3445         uint_t nspares, nl2cache;
3446         uint64_t txg = 0;
3447         int error = 0;
3448         boolean_t locked = MUTEX_HELD(&spa_namespace_lock);
3449
3450         if (!locked)
3451                 txg = spa_vdev_enter(spa);
3452
3453         vd = spa_lookup_by_guid(spa, guid, B_FALSE);
3454
3455         if (spa->spa_spares.sav_vdevs != NULL &&
3456             nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
3457             ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0 &&
3458             (nv = spa_nvlist_lookup_by_guid(spares, nspares, guid)) != NULL) {
3459                 /*
3460                  * Only remove the hot spare if it's not currently in use
3461                  * in this pool.
3462                  */
3463                 if (vd == NULL || unspare) {
3464                         spa_vdev_remove_aux(spa->spa_spares.sav_config,
3465                             ZPOOL_CONFIG_SPARES, spares, nspares, nv);
3466                         spa_load_spares(spa);
3467                         spa->spa_spares.sav_sync = B_TRUE;
3468                 } else {
3469                         error = EBUSY;
3470                 }
3471         } else if (spa->spa_l2cache.sav_vdevs != NULL &&
3472             nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
3473             ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0 &&
3474             (nv = spa_nvlist_lookup_by_guid(l2cache, nl2cache, guid)) != NULL) {
3475                 /*
3476                  * Cache devices can always be removed.
3477                  */
3478                 spa_vdev_remove_aux(spa->spa_l2cache.sav_config,
3479                     ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache, nv);
3480                 spa_load_l2cache(spa);
3481                 spa->spa_l2cache.sav_sync = B_TRUE;
3482         } else if (vd != NULL) {
3483                 /*
3484                  * Normal vdevs cannot be removed (yet).
3485                  */
3486                 error = ENOTSUP;
3487         } else {
3488                 /*
3489                  * There is no vdev of any kind with the specified guid.
3490                  */
3491                 error = ENOENT;
3492         }
3493
3494         if (!locked)
3495                 return (spa_vdev_exit(spa, NULL, txg, error));
3496
3497         return (error);
3498 }
3499
3500 /*
3501  * Find any device that's done replacing, or a vdev marked 'unspare' that's
3502  * current spared, so we can detach it.
3503  */
3504 static vdev_t *
3505 spa_vdev_resilver_done_hunt(vdev_t *vd)
3506 {
3507         vdev_t *newvd, *oldvd;
3508         int c;
3509
3510         for (c = 0; c < vd->vdev_children; c++) {
3511                 oldvd = spa_vdev_resilver_done_hunt(vd->vdev_child[c]);
3512                 if (oldvd != NULL)
3513                         return (oldvd);
3514         }
3515
3516         /*
3517          * Check for a completed replacement.
3518          */
3519         if (vd->vdev_ops == &vdev_replacing_ops && vd->vdev_children == 2) {
3520                 oldvd = vd->vdev_child[0];
3521                 newvd = vd->vdev_child[1];
3522
3523                 if (vdev_dtl_empty(newvd, DTL_MISSING) &&
3524                     !vdev_dtl_required(oldvd))
3525                         return (oldvd);
3526         }
3527
3528         /*
3529          * Check for a completed resilver with the 'unspare' flag set.
3530          */
3531         if (vd->vdev_ops == &vdev_spare_ops && vd->vdev_children == 2) {
3532                 newvd = vd->vdev_child[0];
3533                 oldvd = vd->vdev_child[1];
3534
3535                 if (newvd->vdev_unspare &&
3536                     vdev_dtl_empty(newvd, DTL_MISSING) &&
3537                     !vdev_dtl_required(oldvd)) {
3538                         newvd->vdev_unspare = 0;
3539                         return (oldvd);
3540                 }
3541         }
3542
3543         return (NULL);
3544 }
3545
3546 static void
3547 spa_vdev_resilver_done(spa_t *spa)
3548 {
3549         vdev_t *vd, *pvd, *ppvd;
3550         uint64_t guid, sguid, pguid, ppguid;
3551
3552         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3553
3554         while ((vd = spa_vdev_resilver_done_hunt(spa->spa_root_vdev)) != NULL) {
3555                 pvd = vd->vdev_parent;
3556                 ppvd = pvd->vdev_parent;
3557                 guid = vd->vdev_guid;
3558                 pguid = pvd->vdev_guid;
3559                 ppguid = ppvd->vdev_guid;
3560                 sguid = 0;
3561                 /*
3562                  * If we have just finished replacing a hot spared device, then
3563                  * we need to detach the parent's first child (the original hot
3564                  * spare) as well.
3565                  */
3566                 if (ppvd->vdev_ops == &vdev_spare_ops && pvd->vdev_id == 0) {
3567                         ASSERT(pvd->vdev_ops == &vdev_replacing_ops);
3568                         ASSERT(ppvd->vdev_children == 2);
3569                         sguid = ppvd->vdev_child[1]->vdev_guid;
3570                 }
3571                 spa_config_exit(spa, SCL_ALL, FTAG);
3572                 if (spa_vdev_detach(spa, guid, pguid, B_TRUE) != 0)
3573                         return;
3574                 if (sguid && spa_vdev_detach(spa, sguid, ppguid, B_TRUE) != 0)
3575                         return;
3576                 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3577         }
3578
3579         spa_config_exit(spa, SCL_ALL, FTAG);
3580 }
3581
3582 /*
3583  * Update the stored path or FRU for this vdev.  Dirty the vdev configuration,
3584  * relying on spa_vdev_enter/exit() to synchronize the labels and cache.
3585  */
3586 int
3587 spa_vdev_set_common(spa_t *spa, uint64_t guid, const char *value,
3588     boolean_t ispath)
3589 {
3590         vdev_t *vd;
3591         uint64_t txg;
3592
3593         txg = spa_vdev_enter(spa);
3594
3595         if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
3596                 return (spa_vdev_exit(spa, NULL, txg, ENOENT));
3597
3598         if (!vd->vdev_ops->vdev_op_leaf)
3599                 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
3600
3601         if (ispath) {
3602                 spa_strfree(vd->vdev_path);
3603                 vd->vdev_path = spa_strdup(value);
3604         } else {
3605                 if (vd->vdev_fru != NULL)
3606                         spa_strfree(vd->vdev_fru);
3607                 vd->vdev_fru = spa_strdup(value);
3608         }
3609
3610         vdev_config_dirty(vd->vdev_top);
3611
3612         return (spa_vdev_exit(spa, NULL, txg, 0));
3613 }
3614
3615 int
3616 spa_vdev_setpath(spa_t *spa, uint64_t guid, const char *newpath)
3617 {
3618         return (spa_vdev_set_common(spa, guid, newpath, B_TRUE));
3619 }
3620
3621 int
3622 spa_vdev_setfru(spa_t *spa, uint64_t guid, const char *newfru)
3623 {
3624         return (spa_vdev_set_common(spa, guid, newfru, B_FALSE));
3625 }
3626
3627 /*
3628  * ==========================================================================
3629  * SPA Scrubbing
3630  * ==========================================================================
3631  */
3632
3633 int
3634 spa_scrub(spa_t *spa, pool_scrub_type_t type)
3635 {
3636         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
3637
3638         if ((uint_t)type >= POOL_SCRUB_TYPES)
3639                 return (ENOTSUP);
3640
3641         /*
3642          * If a resilver was requested, but there is no DTL on a
3643          * writeable leaf device, we have nothing to do.
3644          */
3645         if (type == POOL_SCRUB_RESILVER &&
3646             !vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL)) {
3647                 spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
3648                 return (0);
3649         }
3650
3651         if (type == POOL_SCRUB_EVERYTHING &&
3652             spa->spa_dsl_pool->dp_scrub_func != SCRUB_FUNC_NONE &&
3653             spa->spa_dsl_pool->dp_scrub_isresilver)
3654                 return (EBUSY);
3655
3656         if (type == POOL_SCRUB_EVERYTHING || type == POOL_SCRUB_RESILVER) {
3657                 return (dsl_pool_scrub_clean(spa->spa_dsl_pool));
3658         } else if (type == POOL_SCRUB_NONE) {
3659                 return (dsl_pool_scrub_cancel(spa->spa_dsl_pool));
3660         } else {
3661                 return (EINVAL);
3662         }
3663 }
3664
3665 /*
3666  * ==========================================================================
3667  * SPA async task processing
3668  * ==========================================================================
3669  */
3670
3671 static void
3672 spa_async_remove(spa_t *spa, vdev_t *vd)
3673 {
3674         if (vd->vdev_remove_wanted) {
3675                 vd->vdev_remove_wanted = 0;
3676                 vdev_set_state(vd, B_FALSE, VDEV_STATE_REMOVED, VDEV_AUX_NONE);
3677
3678                 /*
3679                  * We want to clear the stats, but we don't want to do a full
3680                  * vdev_clear() as that will cause us to throw away
3681                  * degraded/faulted state as well as attempt to reopen the
3682                  * device, all of which is a waste.
3683                  */
3684                 vd->vdev_stat.vs_read_errors = 0;
3685                 vd->vdev_stat.vs_write_errors = 0;
3686                 vd->vdev_stat.vs_checksum_errors = 0;
3687
3688                 vdev_state_dirty(vd->vdev_top);
3689         }
3690
3691         for (int c = 0; c < vd->vdev_children; c++)
3692                 spa_async_remove(spa, vd->vdev_child[c]);
3693 }
3694
3695 static void
3696 spa_async_probe(spa_t *spa, vdev_t *vd)
3697 {
3698         if (vd->vdev_probe_wanted) {
3699                 vd->vdev_probe_wanted = 0;
3700                 vdev_reopen(vd);        /* vdev_open() does the actual probe */
3701         }
3702
3703         for (int c = 0; c < vd->vdev_children; c++)
3704                 spa_async_probe(spa, vd->vdev_child[c]);
3705 }
3706
3707 static void
3708 spa_async_thread(void *arg)
3709 {
3710         spa_t *spa = arg;
3711         int tasks;
3712
3713         ASSERT(spa->spa_sync_on);
3714
3715         mutex_enter(&spa->spa_async_lock);
3716         tasks = spa->spa_async_tasks;
3717         spa->spa_async_tasks = 0;
3718         mutex_exit(&spa->spa_async_lock);
3719
3720         /*
3721          * See if the config needs to be updated.
3722          */
3723         if (tasks & SPA_ASYNC_CONFIG_UPDATE) {
3724                 mutex_enter(&spa_namespace_lock);
3725                 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
3726                 mutex_exit(&spa_namespace_lock);
3727         }
3728
3729         /*
3730          * See if any devices need to be marked REMOVED.
3731          */
3732         if (tasks & SPA_ASYNC_REMOVE) {
3733                 spa_vdev_state_enter(spa);
3734                 spa_async_remove(spa, spa->spa_root_vdev);
3735                 for (int i = 0; i < spa->spa_l2cache.sav_count; i++)
3736                         spa_async_remove(spa, spa->spa_l2cache.sav_vdevs[i]);
3737                 for (int i = 0; i < spa->spa_spares.sav_count; i++)
3738                         spa_async_remove(spa, spa->spa_spares.sav_vdevs[i]);
3739                 (void) spa_vdev_state_exit(spa, NULL, 0);
3740         }
3741
3742         /*
3743          * See if any devices need to be probed.
3744          */
3745         if (tasks & SPA_ASYNC_PROBE) {
3746                 spa_vdev_state_enter(spa);
3747                 spa_async_probe(spa, spa->spa_root_vdev);
3748                 (void) spa_vdev_state_exit(spa, NULL, 0);
3749         }
3750
3751         /*
3752          * If any devices are done replacing, detach them.
3753          */
3754         if (tasks & SPA_ASYNC_RESILVER_DONE)
3755                 spa_vdev_resilver_done(spa);
3756
3757         /*
3758          * Kick off a resilver.
3759          */
3760         if (tasks & SPA_ASYNC_RESILVER)
3761                 VERIFY(spa_scrub(spa, POOL_SCRUB_RESILVER) == 0);
3762
3763         /*
3764          * Let the world know that we're done.
3765          */
3766         mutex_enter(&spa->spa_async_lock);
3767         spa->spa_async_thread = NULL;
3768         cv_broadcast(&spa->spa_async_cv);
3769         mutex_exit(&spa->spa_async_lock);
3770         thread_exit();
3771 }
3772
3773 void
3774 spa_async_suspend(spa_t *spa)
3775 {
3776         mutex_enter(&spa->spa_async_lock);
3777         spa->spa_async_suspended++;
3778         while (spa->spa_async_thread != NULL)
3779                 cv_wait(&spa->spa_async_cv, &spa->spa_async_lock);
3780         mutex_exit(&spa->spa_async_lock);
3781 }
3782
3783 void
3784 spa_async_resume(spa_t *spa)
3785 {
3786         mutex_enter(&spa->spa_async_lock);
3787         ASSERT(spa->spa_async_suspended != 0);
3788         spa->spa_async_suspended--;
3789         mutex_exit(&spa->spa_async_lock);
3790 }
3791
3792 static void
3793 spa_async_dispatch(spa_t *spa)
3794 {
3795         mutex_enter(&spa->spa_async_lock);
3796         if (spa->spa_async_tasks && !spa->spa_async_suspended &&
3797             spa->spa_async_thread == NULL &&
3798             rootdir != NULL && !vn_is_readonly(rootdir))
3799                 spa->spa_async_thread = thread_create(NULL, 0,
3800                     spa_async_thread, spa, 0, &p0, TS_RUN, maxclsyspri);
3801         mutex_exit(&spa->spa_async_lock);
3802 }
3803
3804 void
3805 spa_async_request(spa_t *spa, int task)
3806 {
3807         mutex_enter(&spa->spa_async_lock);
3808         spa->spa_async_tasks |= task;
3809         mutex_exit(&spa->spa_async_lock);
3810 }
3811
3812 /*
3813  * ==========================================================================
3814  * SPA syncing routines
3815  * ==========================================================================
3816  */
3817
3818 static void
3819 spa_sync_deferred_frees(spa_t *spa, uint64_t txg)
3820 {
3821         bplist_t *bpl = &spa->spa_sync_bplist;
3822         dmu_tx_t *tx;
3823         blkptr_t blk;
3824         uint64_t itor = 0;
3825         zio_t *zio;
3826         int error;
3827         uint8_t c = 1;
3828
3829         zio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
3830
3831         while (bplist_iterate(bpl, &itor, &blk) == 0) {
3832                 ASSERT(blk.blk_birth < txg);
3833                 zio_nowait(zio_free(zio, spa, txg, &blk, NULL, NULL,
3834                     ZIO_FLAG_MUSTSUCCEED));
3835         }
3836
3837         error = zio_wait(zio);
3838         ASSERT3U(error, ==, 0);
3839
3840         tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
3841         bplist_vacate(bpl, tx);
3842
3843         /*
3844          * Pre-dirty the first block so we sync to convergence faster.
3845          * (Usually only the first block is needed.)
3846          */
3847         dmu_write(spa->spa_meta_objset, spa->spa_sync_bplist_obj, 0, 1, &c, tx);
3848         dmu_tx_commit(tx);
3849 }
3850
3851 static void
3852 spa_sync_nvlist(spa_t *spa, uint64_t obj, nvlist_t *nv, dmu_tx_t *tx)
3853 {
3854         char *packed = NULL;
3855         size_t bufsize;
3856         size_t nvsize = 0;
3857         dmu_buf_t *db;
3858
3859         VERIFY(nvlist_size(nv, &nvsize, NV_ENCODE_XDR) == 0);
3860
3861         /*
3862          * Write full (SPA_CONFIG_BLOCKSIZE) blocks of configuration
3863          * information.  This avoids the dbuf_will_dirty() path and
3864          * saves us a pre-read to get data we don't actually care about.
3865          */
3866         bufsize = P2ROUNDUP(nvsize, SPA_CONFIG_BLOCKSIZE);
3867         packed = kmem_alloc(bufsize, KM_SLEEP);
3868
3869         VERIFY(nvlist_pack(nv, &packed, &nvsize, NV_ENCODE_XDR,
3870             KM_SLEEP) == 0);
3871         bzero(packed + nvsize, bufsize - nvsize);
3872
3873         dmu_write(spa->spa_meta_objset, obj, 0, bufsize, packed, tx);
3874
3875         kmem_free(packed, bufsize);
3876
3877         VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
3878         dmu_buf_will_dirty(db, tx);
3879         *(uint64_t *)db->db_data = nvsize;
3880         dmu_buf_rele(db, FTAG);
3881 }
3882
3883 static void
3884 spa_sync_aux_dev(spa_t *spa, spa_aux_vdev_t *sav, dmu_tx_t *tx,
3885     const char *config, const char *entry)
3886 {
3887         nvlist_t *nvroot;
3888         nvlist_t **list;
3889         int i;
3890
3891         if (!sav->sav_sync)
3892                 return;
3893
3894         /*
3895          * Update the MOS nvlist describing the list of available devices.
3896          * spa_validate_aux() will have already made sure this nvlist is
3897          * valid and the vdevs are labeled appropriately.
3898          */
3899         if (sav->sav_object == 0) {
3900                 sav->sav_object = dmu_object_alloc(spa->spa_meta_objset,
3901                     DMU_OT_PACKED_NVLIST, 1 << 14, DMU_OT_PACKED_NVLIST_SIZE,
3902                     sizeof (uint64_t), tx);
3903                 VERIFY(zap_update(spa->spa_meta_objset,
3904                     DMU_POOL_DIRECTORY_OBJECT, entry, sizeof (uint64_t), 1,
3905                     &sav->sav_object, tx) == 0);
3906         }
3907
3908         VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
3909         if (sav->sav_count == 0) {
3910                 VERIFY(nvlist_add_nvlist_array(nvroot, config, NULL, 0) == 0);
3911         } else {
3912                 list = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
3913                 for (i = 0; i < sav->sav_count; i++)
3914                         list[i] = vdev_config_generate(spa, sav->sav_vdevs[i],
3915                             B_FALSE, B_FALSE, B_TRUE);
3916                 VERIFY(nvlist_add_nvlist_array(nvroot, config, list,
3917                     sav->sav_count) == 0);
3918                 for (i = 0; i < sav->sav_count; i++)
3919                         nvlist_free(list[i]);
3920                 kmem_free(list, sav->sav_count * sizeof (void *));
3921         }
3922
3923         spa_sync_nvlist(spa, sav->sav_object, nvroot, tx);
3924         nvlist_free(nvroot);
3925
3926         sav->sav_sync = B_FALSE;
3927 }
3928
3929 static void
3930 spa_sync_config_object(spa_t *spa, dmu_tx_t *tx)
3931 {
3932         nvlist_t *config;
3933
3934         if (list_is_empty(&spa->spa_config_dirty_list))
3935                 return;
3936
3937         spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
3938
3939         config = spa_config_generate(spa, spa->spa_root_vdev,
3940             dmu_tx_get_txg(tx), B_FALSE);
3941
3942         spa_config_exit(spa, SCL_STATE, FTAG);
3943
3944         if (spa->spa_config_syncing)
3945                 nvlist_free(spa->spa_config_syncing);
3946         spa->spa_config_syncing = config;
3947
3948         spa_sync_nvlist(spa, spa->spa_config_object, config, tx);
3949 }
3950
3951 /*
3952  * Set zpool properties.
3953  */
3954 static void
3955 spa_sync_props(void *arg1, void *arg2, cred_t *cr, dmu_tx_t *tx)
3956 {
3957         spa_t *spa = arg1;
3958         objset_t *mos = spa->spa_meta_objset;
3959         nvlist_t *nvp = arg2;
3960         nvpair_t *elem;
3961         uint64_t intval;
3962         char *strval;
3963         zpool_prop_t prop;
3964         const char *propname;
3965         zprop_type_t proptype;
3966
3967         mutex_enter(&spa->spa_props_lock);
3968
3969         elem = NULL;
3970         while ((elem = nvlist_next_nvpair(nvp, elem))) {
3971                 switch (prop = zpool_name_to_prop(nvpair_name(elem))) {
3972                 case ZPOOL_PROP_VERSION:
3973                         /*
3974                          * Only set version for non-zpool-creation cases
3975                          * (set/import). spa_create() needs special care
3976                          * for version setting.
3977                          */
3978                         if (tx->tx_txg != TXG_INITIAL) {
3979                                 VERIFY(nvpair_value_uint64(elem,
3980                                     &intval) == 0);
3981                                 ASSERT(intval <= SPA_VERSION);
3982                                 ASSERT(intval >= spa_version(spa));
3983                                 spa->spa_uberblock.ub_version = intval;
3984                                 vdev_config_dirty(spa->spa_root_vdev);
3985                         }
3986                         break;
3987
3988                 case ZPOOL_PROP_ALTROOT:
3989                         /*
3990                          * 'altroot' is a non-persistent property. It should
3991                          * have been set temporarily at creation or import time.
3992                          */
3993                         ASSERT(spa->spa_root != NULL);
3994                         break;
3995
3996                 case ZPOOL_PROP_CACHEFILE:
3997                         /*
3998                          * 'cachefile' is also a non-persisitent property.
3999                          */
4000                         break;
4001                 default:
4002                         /*
4003                          * Set pool property values in the poolprops mos object.
4004                          */
4005                         if (spa->spa_pool_props_object == 0) {
4006                                 objset_t *mos = spa->spa_meta_objset;
4007
4008                                 VERIFY((spa->spa_pool_props_object =
4009                                     zap_create(mos, DMU_OT_POOL_PROPS,
4010                                     DMU_OT_NONE, 0, tx)) > 0);
4011
4012                                 VERIFY(zap_update(mos,
4013                                     DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_PROPS,
4014                                     8, 1, &spa->spa_pool_props_object, tx)
4015                                     == 0);
4016                         }
4017
4018                         /* normalize the property name */
4019                         propname = zpool_prop_to_name(prop);
4020                         proptype = zpool_prop_get_type(prop);
4021
4022                         if (nvpair_type(elem) == DATA_TYPE_STRING) {
4023                                 ASSERT(proptype == PROP_TYPE_STRING);
4024                                 VERIFY(nvpair_value_string(elem, &strval) == 0);
4025                                 VERIFY(zap_update(mos,
4026                                     spa->spa_pool_props_object, propname,
4027                                     1, strlen(strval) + 1, strval, tx) == 0);
4028
4029                         } else if (nvpair_type(elem) == DATA_TYPE_UINT64) {
4030                                 VERIFY(nvpair_value_uint64(elem, &intval) == 0);
4031
4032                                 if (proptype == PROP_TYPE_INDEX) {
4033                                         const char *unused;
4034                                         VERIFY(zpool_prop_index_to_string(
4035                                             prop, intval, &unused) == 0);
4036                                 }
4037                                 VERIFY(zap_update(mos,
4038                                     spa->spa_pool_props_object, propname,
4039                                     8, 1, &intval, tx) == 0);
4040                         } else {
4041                                 ASSERT(0); /* not allowed */
4042                         }
4043
4044                         switch (prop) {
4045                         case ZPOOL_PROP_DELEGATION:
4046                                 spa->spa_delegation = intval;
4047                                 break;
4048                         case ZPOOL_PROP_BOOTFS:
4049                                 spa->spa_bootfs = intval;
4050                                 break;
4051                         case ZPOOL_PROP_FAILUREMODE:
4052                                 spa->spa_failmode = intval;
4053                                 break;
4054                         default:
4055                                 break;
4056                         }
4057                 }
4058
4059                 /* log internal history if this is not a zpool create */
4060                 if (spa_version(spa) >= SPA_VERSION_ZPOOL_HISTORY &&
4061                     tx->tx_txg != TXG_INITIAL) {
4062                         spa_history_internal_log(LOG_POOL_PROPSET,
4063                             spa, tx, cr, "%s %lld %s",
4064                             nvpair_name(elem), intval, spa_name(spa));
4065                 }
4066         }
4067
4068         mutex_exit(&spa->spa_props_lock);
4069 }
4070
4071 /*
4072  * Sync the specified transaction group.  New blocks may be dirtied as
4073  * part of the process, so we iterate until it converges.
4074  */
4075 void
4076 spa_sync(spa_t *spa, uint64_t txg)
4077 {
4078         dsl_pool_t *dp = spa->spa_dsl_pool;
4079         objset_t *mos = spa->spa_meta_objset;
4080         bplist_t *bpl = &spa->spa_sync_bplist;
4081         vdev_t *rvd = spa->spa_root_vdev;
4082         vdev_t *vd;
4083         dmu_tx_t *tx;
4084         int dirty_vdevs;
4085         int error;
4086
4087         /*
4088          * Lock out configuration changes.
4089          */
4090         spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4091
4092         spa->spa_syncing_txg = txg;
4093         spa->spa_sync_pass = 0;
4094
4095         /*
4096          * If there are any pending vdev state changes, convert them
4097          * into config changes that go out with this transaction group.
4098          */
4099         spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
4100         while (list_head(&spa->spa_state_dirty_list) != NULL) {
4101                 /*
4102                  * We need the write lock here because, for aux vdevs,
4103                  * calling vdev_config_dirty() modifies sav_config.
4104                  * This is ugly and will become unnecessary when we
4105                  * eliminate the aux vdev wart by integrating all vdevs
4106                  * into the root vdev tree.
4107                  */
4108                 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
4109                 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_WRITER);
4110                 while ((vd = list_head(&spa->spa_state_dirty_list)) != NULL) {
4111                         vdev_state_clean(vd);
4112                         vdev_config_dirty(vd);
4113                 }
4114                 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
4115                 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
4116         }
4117         spa_config_exit(spa, SCL_STATE, FTAG);
4118
4119         VERIFY(0 == bplist_open(bpl, mos, spa->spa_sync_bplist_obj));
4120
4121         tx = dmu_tx_create_assigned(dp, txg);
4122
4123         /*
4124          * If we are upgrading to SPA_VERSION_RAIDZ_DEFLATE this txg,
4125          * set spa_deflate if we have no raid-z vdevs.
4126          */
4127         if (spa->spa_ubsync.ub_version < SPA_VERSION_RAIDZ_DEFLATE &&
4128             spa->spa_uberblock.ub_version >= SPA_VERSION_RAIDZ_DEFLATE) {
4129                 int i;
4130
4131                 for (i = 0; i < rvd->vdev_children; i++) {
4132                         vd = rvd->vdev_child[i];
4133                         if (vd->vdev_deflate_ratio != SPA_MINBLOCKSIZE)
4134                                 break;
4135                 }
4136                 if (i == rvd->vdev_children) {
4137                         spa->spa_deflate = TRUE;
4138                         VERIFY(0 == zap_add(spa->spa_meta_objset,
4139                             DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
4140                             sizeof (uint64_t), 1, &spa->spa_deflate, tx));
4141                 }
4142         }
4143
4144         if (spa->spa_ubsync.ub_version < SPA_VERSION_ORIGIN &&
4145             spa->spa_uberblock.ub_version >= SPA_VERSION_ORIGIN) {
4146                 dsl_pool_create_origin(dp, tx);
4147
4148                 /* Keeping the origin open increases spa_minref */
4149                 spa->spa_minref += 3;
4150         }
4151
4152         if (spa->spa_ubsync.ub_version < SPA_VERSION_NEXT_CLONES &&
4153             spa->spa_uberblock.ub_version >= SPA_VERSION_NEXT_CLONES) {
4154                 dsl_pool_upgrade_clones(dp, tx);
4155         }
4156
4157         /*
4158          * If anything has changed in this txg, push the deferred frees
4159          * from the previous txg.  If not, leave them alone so that we
4160          * don't generate work on an otherwise idle system.
4161          */
4162         if (!txg_list_empty(&dp->dp_dirty_datasets, txg) ||
4163             !txg_list_empty(&dp->dp_dirty_dirs, txg) ||
4164             !txg_list_empty(&dp->dp_sync_tasks, txg))
4165                 spa_sync_deferred_frees(spa, txg);
4166
4167         /*
4168          * Iterate to convergence.
4169          */
4170         do {
4171                 spa->spa_sync_pass++;
4172
4173                 spa_sync_config_object(spa, tx);
4174                 spa_sync_aux_dev(spa, &spa->spa_spares, tx,
4175                     ZPOOL_CONFIG_SPARES, DMU_POOL_SPARES);
4176                 spa_sync_aux_dev(spa, &spa->spa_l2cache, tx,
4177                     ZPOOL_CONFIG_L2CACHE, DMU_POOL_L2CACHE);
4178                 spa_errlog_sync(spa, txg);
4179                 dsl_pool_sync(dp, txg);
4180
4181                 dirty_vdevs = 0;
4182                 while (vd = txg_list_remove(&spa->spa_vdev_txg_list, txg)) {
4183                         vdev_sync(vd, txg);
4184                         dirty_vdevs++;
4185                 }
4186
4187                 bplist_sync(bpl, tx);
4188         } while (dirty_vdevs);
4189
4190         bplist_close(bpl);
4191
4192         dprintf("txg %llu passes %d\n", txg, spa->spa_sync_pass);
4193
4194         /*
4195          * Rewrite the vdev configuration (which includes the uberblock)
4196          * to commit the transaction group.
4197          *
4198          * If there are no dirty vdevs, we sync the uberblock to a few
4199          * random top-level vdevs that are known to be visible in the
4200          * config cache (see spa_vdev_add() for a complete description).
4201          * If there *are* dirty vdevs, sync the uberblock to all vdevs.
4202          */
4203         for (;;) {
4204                 /*
4205                  * We hold SCL_STATE to prevent vdev open/close/etc.
4206                  * while we're attempting to write the vdev labels.
4207                  */
4208                 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
4209
4210                 if (list_is_empty(&spa->spa_config_dirty_list)) {
4211                         vdev_t *svd[SPA_DVAS_PER_BP];
4212                         int svdcount = 0;
4213                         int children = rvd->vdev_children;
4214                         int c0 = spa_get_random(children);
4215                         int c;
4216
4217                         for (c = 0; c < children; c++) {
4218                                 vd = rvd->vdev_child[(c0 + c) % children];
4219                                 if (vd->vdev_ms_array == 0 || vd->vdev_islog)
4220                                         continue;
4221                                 svd[svdcount++] = vd;
4222                                 if (svdcount == SPA_DVAS_PER_BP)
4223                                         break;
4224                         }
4225                         error = vdev_config_sync(svd, svdcount, txg);
4226                 } else {
4227                         error = vdev_config_sync(rvd->vdev_child,
4228                             rvd->vdev_children, txg);
4229                 }
4230
4231                 spa_config_exit(spa, SCL_STATE, FTAG);
4232
4233                 if (error == 0)
4234                         break;
4235                 zio_suspend(spa, NULL);
4236                 zio_resume_wait(spa);
4237         }
4238         dmu_tx_commit(tx);
4239
4240         /*
4241          * Clear the dirty config list.
4242          */
4243         while ((vd = list_head(&spa->spa_config_dirty_list)) != NULL)
4244                 vdev_config_clean(vd);
4245
4246         /*
4247          * Now that the new config has synced transactionally,
4248          * let it become visible to the config cache.
4249          */
4250         if (spa->spa_config_syncing != NULL) {
4251                 spa_config_set(spa, spa->spa_config_syncing);
4252                 spa->spa_config_txg = txg;
4253                 spa->spa_config_syncing = NULL;
4254         }
4255
4256         spa->spa_ubsync = spa->spa_uberblock;
4257
4258         /*
4259          * Clean up the ZIL records for the synced txg.
4260          */
4261         dsl_pool_zil_clean(dp);
4262
4263         /*
4264          * Update usable space statistics.
4265          */
4266         while (vd = txg_list_remove(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)))
4267                 vdev_sync_done(vd, txg);
4268
4269         /*
4270          * It had better be the case that we didn't dirty anything
4271          * since vdev_config_sync().
4272          */
4273         ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
4274         ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
4275         ASSERT(txg_list_empty(&spa->spa_vdev_txg_list, txg));
4276         ASSERT(bpl->bpl_queue == NULL);
4277
4278         spa_config_exit(spa, SCL_CONFIG, FTAG);
4279
4280         /*
4281          * If any async tasks have been requested, kick them off.
4282          */
4283         spa_async_dispatch(spa);
4284 }
4285
4286 /*
4287  * Sync all pools.  We don't want to hold the namespace lock across these
4288  * operations, so we take a reference on the spa_t and drop the lock during the
4289  * sync.
4290  */
4291 void
4292 spa_sync_allpools(void)
4293 {
4294         spa_t *spa = NULL;
4295         mutex_enter(&spa_namespace_lock);
4296         while ((spa = spa_next(spa)) != NULL) {
4297                 if (spa_state(spa) != POOL_STATE_ACTIVE || spa_suspended(spa))
4298                         continue;
4299                 spa_open_ref(spa, FTAG);
4300                 mutex_exit(&spa_namespace_lock);
4301                 txg_wait_synced(spa_get_dsl(spa), 0);
4302                 mutex_enter(&spa_namespace_lock);
4303                 spa_close(spa, FTAG);
4304         }
4305         mutex_exit(&spa_namespace_lock);
4306 }
4307
4308 /*
4309  * ==========================================================================
4310  * Miscellaneous routines
4311  * ==========================================================================
4312  */
4313
4314 /*
4315  * Remove all pools in the system.
4316  */
4317 void
4318 spa_evict_all(void)
4319 {
4320         spa_t *spa;
4321
4322         /*
4323          * Remove all cached state.  All pools should be closed now,
4324          * so every spa in the AVL tree should be unreferenced.
4325          */
4326         mutex_enter(&spa_namespace_lock);
4327         while ((spa = spa_next(NULL)) != NULL) {
4328                 /*
4329                  * Stop async tasks.  The async thread may need to detach
4330                  * a device that's been replaced, which requires grabbing
4331                  * spa_namespace_lock, so we must drop it here.
4332                  */
4333                 spa_open_ref(spa, FTAG);
4334                 mutex_exit(&spa_namespace_lock);
4335                 spa_async_suspend(spa);
4336                 mutex_enter(&spa_namespace_lock);
4337                 spa_close(spa, FTAG);
4338
4339                 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
4340                         spa_unload(spa);
4341                         spa_deactivate(spa);
4342                 }
4343                 spa_remove(spa);
4344         }
4345         mutex_exit(&spa_namespace_lock);
4346 }
4347
4348 vdev_t *
4349 spa_lookup_by_guid(spa_t *spa, uint64_t guid, boolean_t aux)
4350 {
4351         vdev_t *vd;
4352         int i;
4353
4354         if ((vd = vdev_lookup_by_guid(spa->spa_root_vdev, guid)) != NULL)
4355                 return (vd);
4356
4357         if (aux) {
4358                 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
4359                         vd = spa->spa_l2cache.sav_vdevs[i];
4360                         if (vd->vdev_guid == guid)
4361                                 return (vd);
4362                 }
4363
4364                 for (i = 0; i < spa->spa_spares.sav_count; i++) {
4365                         vd = spa->spa_spares.sav_vdevs[i];
4366                         if (vd->vdev_guid == guid)
4367                                 return (vd);
4368                 }
4369         }
4370
4371         return (NULL);
4372 }
4373
4374 void
4375 spa_upgrade(spa_t *spa, uint64_t version)
4376 {
4377         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4378
4379         /*
4380          * This should only be called for a non-faulted pool, and since a
4381          * future version would result in an unopenable pool, this shouldn't be
4382          * possible.
4383          */
4384         ASSERT(spa->spa_uberblock.ub_version <= SPA_VERSION);
4385         ASSERT(version >= spa->spa_uberblock.ub_version);
4386
4387         spa->spa_uberblock.ub_version = version;
4388         vdev_config_dirty(spa->spa_root_vdev);
4389
4390         spa_config_exit(spa, SCL_ALL, FTAG);
4391
4392         txg_wait_synced(spa_get_dsl(spa), 0);
4393 }
4394
4395 boolean_t
4396 spa_has_spare(spa_t *spa, uint64_t guid)
4397 {
4398         int i;
4399         uint64_t spareguid;
4400         spa_aux_vdev_t *sav = &spa->spa_spares;
4401
4402         for (i = 0; i < sav->sav_count; i++)
4403                 if (sav->sav_vdevs[i]->vdev_guid == guid)
4404                         return (B_TRUE);
4405
4406         for (i = 0; i < sav->sav_npending; i++) {
4407                 if (nvlist_lookup_uint64(sav->sav_pending[i], ZPOOL_CONFIG_GUID,
4408                     &spareguid) == 0 && spareguid == guid)
4409                         return (B_TRUE);
4410         }
4411
4412         return (B_FALSE);
4413 }
4414
4415 /*
4416  * Check if a pool has an active shared spare device.
4417  * Note: reference count of an active spare is 2, as a spare and as a replace
4418  */
4419 static boolean_t
4420 spa_has_active_shared_spare(spa_t *spa)
4421 {
4422         int i, refcnt;
4423         uint64_t pool;
4424         spa_aux_vdev_t *sav = &spa->spa_spares;
4425
4426         for (i = 0; i < sav->sav_count; i++) {
4427                 if (spa_spare_exists(sav->sav_vdevs[i]->vdev_guid, &pool,
4428                     &refcnt) && pool != 0ULL && pool == spa_guid(spa) &&
4429                     refcnt > 2)
4430                         return (B_TRUE);
4431         }
4432
4433         return (B_FALSE);
4434 }
4435
4436 /*
4437  * Post a sysevent corresponding to the given event.  The 'name' must be one of
4438  * the event definitions in sys/sysevent/eventdefs.h.  The payload will be
4439  * filled in from the spa and (optionally) the vdev.  This doesn't do anything
4440  * in the userland libzpool, as we don't want consumers to misinterpret ztest
4441  * or zdb as real changes.
4442  */
4443 void
4444 spa_event_notify(spa_t *spa, vdev_t *vd, const char *name)
4445 {
4446 #if 0
4447 #ifdef _KERNEL
4448         sysevent_t              *ev;
4449         sysevent_attr_list_t    *attr = NULL;
4450         sysevent_value_t        value;
4451         sysevent_id_t           eid;
4452
4453         ev = sysevent_alloc(EC_ZFS, (char *)name, SUNW_KERN_PUB "zfs",
4454             SE_SLEEP);
4455
4456         value.value_type = SE_DATA_TYPE_STRING;
4457         value.value.sv_string = spa_name(spa);
4458         if (sysevent_add_attr(&attr, ZFS_EV_POOL_NAME, &value, SE_SLEEP) != 0)
4459                 goto done;
4460
4461         value.value_type = SE_DATA_TYPE_UINT64;
4462         value.value.sv_uint64 = spa_guid(spa);
4463         if (sysevent_add_attr(&attr, ZFS_EV_POOL_GUID, &value, SE_SLEEP) != 0)
4464                 goto done;
4465
4466         if (vd) {
4467                 value.value_type = SE_DATA_TYPE_UINT64;
4468                 value.value.sv_uint64 = vd->vdev_guid;
4469                 if (sysevent_add_attr(&attr, ZFS_EV_VDEV_GUID, &value,
4470                     SE_SLEEP) != 0)
4471                         goto done;
4472
4473                 if (vd->vdev_path) {
4474                         value.value_type = SE_DATA_TYPE_STRING;
4475                         value.value.sv_string = vd->vdev_path;
4476                         if (sysevent_add_attr(&attr, ZFS_EV_VDEV_PATH,
4477                             &value, SE_SLEEP) != 0)
4478                                 goto done;
4479                 }
4480         }
4481
4482         if (sysevent_attach_attributes(ev, attr) != 0)
4483                 goto done;
4484         attr = NULL;
4485
4486         (void) log_sysevent(ev, SE_SLEEP, &eid);
4487
4488 done:
4489         if (attr)
4490                 sysevent_free_attr(attr);
4491         sysevent_free(ev);
4492 #endif
4493 #endif
4494 }