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