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