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