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