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