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