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