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