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