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