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