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