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