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