]> git.proxmox.com Git - mirror_zfs.git/blob - module/zfs/spa.c
Race condition between spa async threads and export
[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 if (spa->spa_is_exporting) {
5794 /* the pool is being exported by another thread */
5795 mutex_exit(&spa_namespace_lock);
5796 return (SET_ERROR(ZFS_ERR_EXPORT_IN_PROGRESS));
5797 }
5798 spa->spa_is_exporting = B_TRUE;
5799
5800 /*
5801 * Put a hold on the pool, drop the namespace lock, stop async tasks,
5802 * reacquire the namespace lock, and see if we can export.
5803 */
5804 spa_open_ref(spa, FTAG);
5805 mutex_exit(&spa_namespace_lock);
5806 spa_async_suspend(spa);
5807 if (spa->spa_zvol_taskq) {
5808 zvol_remove_minors(spa, spa_name(spa), B_TRUE);
5809 taskq_wait(spa->spa_zvol_taskq);
5810 }
5811 mutex_enter(&spa_namespace_lock);
5812 spa_close(spa, FTAG);
5813
5814 if (spa->spa_state == POOL_STATE_UNINITIALIZED)
5815 goto export_spa;
5816 /*
5817 * The pool will be in core if it's openable, in which case we can
5818 * modify its state. Objsets may be open only because they're dirty,
5819 * so we have to force it to sync before checking spa_refcnt.
5820 */
5821 if (spa->spa_sync_on) {
5822 txg_wait_synced(spa->spa_dsl_pool, 0);
5823 spa_evicting_os_wait(spa);
5824 }
5825
5826 /*
5827 * A pool cannot be exported or destroyed if there are active
5828 * references. If we are resetting a pool, allow references by
5829 * fault injection handlers.
5830 */
5831 if (!spa_refcount_zero(spa) ||
5832 (spa->spa_inject_ref != 0 &&
5833 new_state != POOL_STATE_UNINITIALIZED)) {
5834 spa_async_resume(spa);
5835 spa->spa_is_exporting = B_FALSE;
5836 mutex_exit(&spa_namespace_lock);
5837 return (SET_ERROR(EBUSY));
5838 }
5839
5840 if (spa->spa_sync_on) {
5841 /*
5842 * A pool cannot be exported if it has an active shared spare.
5843 * This is to prevent other pools stealing the active spare
5844 * from an exported pool. At user's own will, such pool can
5845 * be forcedly exported.
5846 */
5847 if (!force && new_state == POOL_STATE_EXPORTED &&
5848 spa_has_active_shared_spare(spa)) {
5849 spa_async_resume(spa);
5850 spa->spa_is_exporting = B_FALSE;
5851 mutex_exit(&spa_namespace_lock);
5852 return (SET_ERROR(EXDEV));
5853 }
5854
5855 /*
5856 * We're about to export or destroy this pool. Make sure
5857 * we stop all initialization and trim activity here before
5858 * we set the spa_final_txg. This will ensure that all
5859 * dirty data resulting from the initialization is
5860 * committed to disk before we unload the pool.
5861 */
5862 if (spa->spa_root_vdev != NULL) {
5863 vdev_t *rvd = spa->spa_root_vdev;
5864 vdev_initialize_stop_all(rvd, VDEV_INITIALIZE_ACTIVE);
5865 vdev_trim_stop_all(rvd, VDEV_TRIM_ACTIVE);
5866 vdev_autotrim_stop_all(spa);
5867 }
5868
5869 /*
5870 * We want this to be reflected on every label,
5871 * so mark them all dirty. spa_unload() will do the
5872 * final sync that pushes these changes out.
5873 */
5874 if (new_state != POOL_STATE_UNINITIALIZED && !hardforce) {
5875 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5876 spa->spa_state = new_state;
5877 spa->spa_final_txg = spa_last_synced_txg(spa) +
5878 TXG_DEFER_SIZE + 1;
5879 vdev_config_dirty(spa->spa_root_vdev);
5880 spa_config_exit(spa, SCL_ALL, FTAG);
5881 }
5882 }
5883
5884 export_spa:
5885 if (new_state == POOL_STATE_DESTROYED)
5886 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_DESTROY);
5887 else if (new_state == POOL_STATE_EXPORTED)
5888 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_EXPORT);
5889
5890 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
5891 spa_unload(spa);
5892 spa_deactivate(spa);
5893 }
5894
5895 if (oldconfig && spa->spa_config)
5896 VERIFY(nvlist_dup(spa->spa_config, oldconfig, 0) == 0);
5897
5898 if (new_state != POOL_STATE_UNINITIALIZED) {
5899 if (!hardforce)
5900 spa_write_cachefile(spa, B_TRUE, B_TRUE);
5901 spa_remove(spa);
5902 } else {
5903 /*
5904 * If spa_remove() is not called for this spa_t and
5905 * there is any possibility that it can be reused,
5906 * we make sure to reset the exporting flag.
5907 */
5908 spa->spa_is_exporting = B_FALSE;
5909 }
5910
5911 mutex_exit(&spa_namespace_lock);
5912 return (0);
5913 }
5914
5915 /*
5916 * Destroy a storage pool.
5917 */
5918 int
5919 spa_destroy(char *pool)
5920 {
5921 return (spa_export_common(pool, POOL_STATE_DESTROYED, NULL,
5922 B_FALSE, B_FALSE));
5923 }
5924
5925 /*
5926 * Export a storage pool.
5927 */
5928 int
5929 spa_export(char *pool, nvlist_t **oldconfig, boolean_t force,
5930 boolean_t hardforce)
5931 {
5932 return (spa_export_common(pool, POOL_STATE_EXPORTED, oldconfig,
5933 force, hardforce));
5934 }
5935
5936 /*
5937 * Similar to spa_export(), this unloads the spa_t without actually removing it
5938 * from the namespace in any way.
5939 */
5940 int
5941 spa_reset(char *pool)
5942 {
5943 return (spa_export_common(pool, POOL_STATE_UNINITIALIZED, NULL,
5944 B_FALSE, B_FALSE));
5945 }
5946
5947 /*
5948 * ==========================================================================
5949 * Device manipulation
5950 * ==========================================================================
5951 */
5952
5953 /*
5954 * Add a device to a storage pool.
5955 */
5956 int
5957 spa_vdev_add(spa_t *spa, nvlist_t *nvroot)
5958 {
5959 uint64_t txg;
5960 int error;
5961 vdev_t *rvd = spa->spa_root_vdev;
5962 vdev_t *vd, *tvd;
5963 nvlist_t **spares, **l2cache;
5964 uint_t nspares, nl2cache;
5965
5966 ASSERT(spa_writeable(spa));
5967
5968 txg = spa_vdev_enter(spa);
5969
5970 if ((error = spa_config_parse(spa, &vd, nvroot, NULL, 0,
5971 VDEV_ALLOC_ADD)) != 0)
5972 return (spa_vdev_exit(spa, NULL, txg, error));
5973
5974 spa->spa_pending_vdev = vd; /* spa_vdev_exit() will clear this */
5975
5976 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares,
5977 &nspares) != 0)
5978 nspares = 0;
5979
5980 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE, &l2cache,
5981 &nl2cache) != 0)
5982 nl2cache = 0;
5983
5984 if (vd->vdev_children == 0 && nspares == 0 && nl2cache == 0)
5985 return (spa_vdev_exit(spa, vd, txg, EINVAL));
5986
5987 if (vd->vdev_children != 0 &&
5988 (error = vdev_create(vd, txg, B_FALSE)) != 0)
5989 return (spa_vdev_exit(spa, vd, txg, error));
5990
5991 /*
5992 * We must validate the spares and l2cache devices after checking the
5993 * children. Otherwise, vdev_inuse() will blindly overwrite the spare.
5994 */
5995 if ((error = spa_validate_aux(spa, nvroot, txg, VDEV_ALLOC_ADD)) != 0)
5996 return (spa_vdev_exit(spa, vd, txg, error));
5997
5998 /*
5999 * If we are in the middle of a device removal, we can only add
6000 * devices which match the existing devices in the pool.
6001 * If we are in the middle of a removal, or have some indirect
6002 * vdevs, we can not add raidz toplevels.
6003 */
6004 if (spa->spa_vdev_removal != NULL ||
6005 spa->spa_removing_phys.sr_prev_indirect_vdev != -1) {
6006 for (int c = 0; c < vd->vdev_children; c++) {
6007 tvd = vd->vdev_child[c];
6008 if (spa->spa_vdev_removal != NULL &&
6009 tvd->vdev_ashift != spa->spa_max_ashift) {
6010 return (spa_vdev_exit(spa, vd, txg, EINVAL));
6011 }
6012 /* Fail if top level vdev is raidz */
6013 if (tvd->vdev_ops == &vdev_raidz_ops) {
6014 return (spa_vdev_exit(spa, vd, txg, EINVAL));
6015 }
6016 /*
6017 * Need the top level mirror to be
6018 * a mirror of leaf vdevs only
6019 */
6020 if (tvd->vdev_ops == &vdev_mirror_ops) {
6021 for (uint64_t cid = 0;
6022 cid < tvd->vdev_children; cid++) {
6023 vdev_t *cvd = tvd->vdev_child[cid];
6024 if (!cvd->vdev_ops->vdev_op_leaf) {
6025 return (spa_vdev_exit(spa, vd,
6026 txg, EINVAL));
6027 }
6028 }
6029 }
6030 }
6031 }
6032
6033 for (int c = 0; c < vd->vdev_children; c++) {
6034 tvd = vd->vdev_child[c];
6035 vdev_remove_child(vd, tvd);
6036 tvd->vdev_id = rvd->vdev_children;
6037 vdev_add_child(rvd, tvd);
6038 vdev_config_dirty(tvd);
6039 }
6040
6041 if (nspares != 0) {
6042 spa_set_aux_vdevs(&spa->spa_spares, spares, nspares,
6043 ZPOOL_CONFIG_SPARES);
6044 spa_load_spares(spa);
6045 spa->spa_spares.sav_sync = B_TRUE;
6046 }
6047
6048 if (nl2cache != 0) {
6049 spa_set_aux_vdevs(&spa->spa_l2cache, l2cache, nl2cache,
6050 ZPOOL_CONFIG_L2CACHE);
6051 spa_load_l2cache(spa);
6052 spa->spa_l2cache.sav_sync = B_TRUE;
6053 }
6054
6055 /*
6056 * We have to be careful when adding new vdevs to an existing pool.
6057 * If other threads start allocating from these vdevs before we
6058 * sync the config cache, and we lose power, then upon reboot we may
6059 * fail to open the pool because there are DVAs that the config cache
6060 * can't translate. Therefore, we first add the vdevs without
6061 * initializing metaslabs; sync the config cache (via spa_vdev_exit());
6062 * and then let spa_config_update() initialize the new metaslabs.
6063 *
6064 * spa_load() checks for added-but-not-initialized vdevs, so that
6065 * if we lose power at any point in this sequence, the remaining
6066 * steps will be completed the next time we load the pool.
6067 */
6068 (void) spa_vdev_exit(spa, vd, txg, 0);
6069
6070 mutex_enter(&spa_namespace_lock);
6071 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
6072 spa_event_notify(spa, NULL, NULL, ESC_ZFS_VDEV_ADD);
6073 mutex_exit(&spa_namespace_lock);
6074
6075 return (0);
6076 }
6077
6078 /*
6079 * Attach a device to a mirror. The arguments are the path to any device
6080 * in the mirror, and the nvroot for the new device. If the path specifies
6081 * a device that is not mirrored, we automatically insert the mirror vdev.
6082 *
6083 * If 'replacing' is specified, the new device is intended to replace the
6084 * existing device; in this case the two devices are made into their own
6085 * mirror using the 'replacing' vdev, which is functionally identical to
6086 * the mirror vdev (it actually reuses all the same ops) but has a few
6087 * extra rules: you can't attach to it after it's been created, and upon
6088 * completion of resilvering, the first disk (the one being replaced)
6089 * is automatically detached.
6090 */
6091 int
6092 spa_vdev_attach(spa_t *spa, uint64_t guid, nvlist_t *nvroot, int replacing)
6093 {
6094 uint64_t txg, dtl_max_txg;
6095 ASSERTV(vdev_t *rvd = spa->spa_root_vdev);
6096 vdev_t *oldvd, *newvd, *newrootvd, *pvd, *tvd;
6097 vdev_ops_t *pvops;
6098 char *oldvdpath, *newvdpath;
6099 int newvd_isspare;
6100 int error;
6101
6102 ASSERT(spa_writeable(spa));
6103
6104 txg = spa_vdev_enter(spa);
6105
6106 oldvd = spa_lookup_by_guid(spa, guid, B_FALSE);
6107
6108 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6109 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6110 error = (spa_has_checkpoint(spa)) ?
6111 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6112 return (spa_vdev_exit(spa, NULL, txg, error));
6113 }
6114
6115 if (spa->spa_vdev_removal != NULL)
6116 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6117
6118 if (oldvd == NULL)
6119 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
6120
6121 if (!oldvd->vdev_ops->vdev_op_leaf)
6122 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6123
6124 pvd = oldvd->vdev_parent;
6125
6126 if ((error = spa_config_parse(spa, &newrootvd, nvroot, NULL, 0,
6127 VDEV_ALLOC_ATTACH)) != 0)
6128 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6129
6130 if (newrootvd->vdev_children != 1)
6131 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
6132
6133 newvd = newrootvd->vdev_child[0];
6134
6135 if (!newvd->vdev_ops->vdev_op_leaf)
6136 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
6137
6138 if ((error = vdev_create(newrootvd, txg, replacing)) != 0)
6139 return (spa_vdev_exit(spa, newrootvd, txg, error));
6140
6141 /*
6142 * Spares can't replace logs
6143 */
6144 if (oldvd->vdev_top->vdev_islog && newvd->vdev_isspare)
6145 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6146
6147 if (!replacing) {
6148 /*
6149 * For attach, the only allowable parent is a mirror or the root
6150 * vdev.
6151 */
6152 if (pvd->vdev_ops != &vdev_mirror_ops &&
6153 pvd->vdev_ops != &vdev_root_ops)
6154 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6155
6156 pvops = &vdev_mirror_ops;
6157 } else {
6158 /*
6159 * Active hot spares can only be replaced by inactive hot
6160 * spares.
6161 */
6162 if (pvd->vdev_ops == &vdev_spare_ops &&
6163 oldvd->vdev_isspare &&
6164 !spa_has_spare(spa, newvd->vdev_guid))
6165 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6166
6167 /*
6168 * If the source is a hot spare, and the parent isn't already a
6169 * spare, then we want to create a new hot spare. Otherwise, we
6170 * want to create a replacing vdev. The user is not allowed to
6171 * attach to a spared vdev child unless the 'isspare' state is
6172 * the same (spare replaces spare, non-spare replaces
6173 * non-spare).
6174 */
6175 if (pvd->vdev_ops == &vdev_replacing_ops &&
6176 spa_version(spa) < SPA_VERSION_MULTI_REPLACE) {
6177 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6178 } else if (pvd->vdev_ops == &vdev_spare_ops &&
6179 newvd->vdev_isspare != oldvd->vdev_isspare) {
6180 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6181 }
6182
6183 if (newvd->vdev_isspare)
6184 pvops = &vdev_spare_ops;
6185 else
6186 pvops = &vdev_replacing_ops;
6187 }
6188
6189 /*
6190 * Make sure the new device is big enough.
6191 */
6192 if (newvd->vdev_asize < vdev_get_min_asize(oldvd))
6193 return (spa_vdev_exit(spa, newrootvd, txg, EOVERFLOW));
6194
6195 /*
6196 * The new device cannot have a higher alignment requirement
6197 * than the top-level vdev.
6198 */
6199 if (newvd->vdev_ashift > oldvd->vdev_top->vdev_ashift)
6200 return (spa_vdev_exit(spa, newrootvd, txg, EDOM));
6201
6202 /*
6203 * If this is an in-place replacement, update oldvd's path and devid
6204 * to make it distinguishable from newvd, and unopenable from now on.
6205 */
6206 if (strcmp(oldvd->vdev_path, newvd->vdev_path) == 0) {
6207 spa_strfree(oldvd->vdev_path);
6208 oldvd->vdev_path = kmem_alloc(strlen(newvd->vdev_path) + 5,
6209 KM_SLEEP);
6210 (void) sprintf(oldvd->vdev_path, "%s/%s",
6211 newvd->vdev_path, "old");
6212 if (oldvd->vdev_devid != NULL) {
6213 spa_strfree(oldvd->vdev_devid);
6214 oldvd->vdev_devid = NULL;
6215 }
6216 }
6217
6218 /* mark the device being resilvered */
6219 newvd->vdev_resilver_txg = txg;
6220
6221 /*
6222 * If the parent is not a mirror, or if we're replacing, insert the new
6223 * mirror/replacing/spare vdev above oldvd.
6224 */
6225 if (pvd->vdev_ops != pvops)
6226 pvd = vdev_add_parent(oldvd, pvops);
6227
6228 ASSERT(pvd->vdev_top->vdev_parent == rvd);
6229 ASSERT(pvd->vdev_ops == pvops);
6230 ASSERT(oldvd->vdev_parent == pvd);
6231
6232 /*
6233 * Extract the new device from its root and add it to pvd.
6234 */
6235 vdev_remove_child(newrootvd, newvd);
6236 newvd->vdev_id = pvd->vdev_children;
6237 newvd->vdev_crtxg = oldvd->vdev_crtxg;
6238 vdev_add_child(pvd, newvd);
6239
6240 /*
6241 * Reevaluate the parent vdev state.
6242 */
6243 vdev_propagate_state(pvd);
6244
6245 tvd = newvd->vdev_top;
6246 ASSERT(pvd->vdev_top == tvd);
6247 ASSERT(tvd->vdev_parent == rvd);
6248
6249 vdev_config_dirty(tvd);
6250
6251 /*
6252 * Set newvd's DTL to [TXG_INITIAL, dtl_max_txg) so that we account
6253 * for any dmu_sync-ed blocks. It will propagate upward when
6254 * spa_vdev_exit() calls vdev_dtl_reassess().
6255 */
6256 dtl_max_txg = txg + TXG_CONCURRENT_STATES;
6257
6258 vdev_dtl_dirty(newvd, DTL_MISSING, TXG_INITIAL,
6259 dtl_max_txg - TXG_INITIAL);
6260
6261 if (newvd->vdev_isspare) {
6262 spa_spare_activate(newvd);
6263 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_SPARE);
6264 }
6265
6266 oldvdpath = spa_strdup(oldvd->vdev_path);
6267 newvdpath = spa_strdup(newvd->vdev_path);
6268 newvd_isspare = newvd->vdev_isspare;
6269
6270 /*
6271 * Mark newvd's DTL dirty in this txg.
6272 */
6273 vdev_dirty(tvd, VDD_DTL, newvd, txg);
6274
6275 /*
6276 * Schedule the resilver to restart in the future. We do this to
6277 * ensure that dmu_sync-ed blocks have been stitched into the
6278 * respective datasets. We do not do this if resilvers have been
6279 * deferred.
6280 */
6281 if (dsl_scan_resilvering(spa_get_dsl(spa)) &&
6282 spa_feature_is_enabled(spa, SPA_FEATURE_RESILVER_DEFER))
6283 vdev_set_deferred_resilver(spa, newvd);
6284 else
6285 dsl_resilver_restart(spa->spa_dsl_pool, dtl_max_txg);
6286
6287 if (spa->spa_bootfs)
6288 spa_event_notify(spa, newvd, NULL, ESC_ZFS_BOOTFS_VDEV_ATTACH);
6289
6290 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_ATTACH);
6291
6292 /*
6293 * Commit the config
6294 */
6295 (void) spa_vdev_exit(spa, newrootvd, dtl_max_txg, 0);
6296
6297 spa_history_log_internal(spa, "vdev attach", NULL,
6298 "%s vdev=%s %s vdev=%s",
6299 replacing && newvd_isspare ? "spare in" :
6300 replacing ? "replace" : "attach", newvdpath,
6301 replacing ? "for" : "to", oldvdpath);
6302
6303 spa_strfree(oldvdpath);
6304 spa_strfree(newvdpath);
6305
6306 return (0);
6307 }
6308
6309 /*
6310 * Detach a device from a mirror or replacing vdev.
6311 *
6312 * If 'replace_done' is specified, only detach if the parent
6313 * is a replacing vdev.
6314 */
6315 int
6316 spa_vdev_detach(spa_t *spa, uint64_t guid, uint64_t pguid, int replace_done)
6317 {
6318 uint64_t txg;
6319 int error;
6320 ASSERTV(vdev_t *rvd = spa->spa_root_vdev);
6321 vdev_t *vd, *pvd, *cvd, *tvd;
6322 boolean_t unspare = B_FALSE;
6323 uint64_t unspare_guid = 0;
6324 char *vdpath;
6325
6326 ASSERT(spa_writeable(spa));
6327
6328 txg = spa_vdev_enter(spa);
6329
6330 vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6331
6332 /*
6333 * Besides being called directly from the userland through the
6334 * ioctl interface, spa_vdev_detach() can be potentially called
6335 * at the end of spa_vdev_resilver_done().
6336 *
6337 * In the regular case, when we have a checkpoint this shouldn't
6338 * happen as we never empty the DTLs of a vdev during the scrub
6339 * [see comment in dsl_scan_done()]. Thus spa_vdev_resilvering_done()
6340 * should never get here when we have a checkpoint.
6341 *
6342 * That said, even in a case when we checkpoint the pool exactly
6343 * as spa_vdev_resilver_done() calls this function everything
6344 * should be fine as the resilver will return right away.
6345 */
6346 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6347 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6348 error = (spa_has_checkpoint(spa)) ?
6349 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6350 return (spa_vdev_exit(spa, NULL, txg, error));
6351 }
6352
6353 if (vd == NULL)
6354 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
6355
6356 if (!vd->vdev_ops->vdev_op_leaf)
6357 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6358
6359 pvd = vd->vdev_parent;
6360
6361 /*
6362 * If the parent/child relationship is not as expected, don't do it.
6363 * Consider M(A,R(B,C)) -- that is, a mirror of A with a replacing
6364 * vdev that's replacing B with C. The user's intent in replacing
6365 * is to go from M(A,B) to M(A,C). If the user decides to cancel
6366 * the replace by detaching C, the expected behavior is to end up
6367 * M(A,B). But suppose that right after deciding to detach C,
6368 * the replacement of B completes. We would have M(A,C), and then
6369 * ask to detach C, which would leave us with just A -- not what
6370 * the user wanted. To prevent this, we make sure that the
6371 * parent/child relationship hasn't changed -- in this example,
6372 * that C's parent is still the replacing vdev R.
6373 */
6374 if (pvd->vdev_guid != pguid && pguid != 0)
6375 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6376
6377 /*
6378 * Only 'replacing' or 'spare' vdevs can be replaced.
6379 */
6380 if (replace_done && pvd->vdev_ops != &vdev_replacing_ops &&
6381 pvd->vdev_ops != &vdev_spare_ops)
6382 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6383
6384 ASSERT(pvd->vdev_ops != &vdev_spare_ops ||
6385 spa_version(spa) >= SPA_VERSION_SPARES);
6386
6387 /*
6388 * Only mirror, replacing, and spare vdevs support detach.
6389 */
6390 if (pvd->vdev_ops != &vdev_replacing_ops &&
6391 pvd->vdev_ops != &vdev_mirror_ops &&
6392 pvd->vdev_ops != &vdev_spare_ops)
6393 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6394
6395 /*
6396 * If this device has the only valid copy of some data,
6397 * we cannot safely detach it.
6398 */
6399 if (vdev_dtl_required(vd))
6400 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6401
6402 ASSERT(pvd->vdev_children >= 2);
6403
6404 /*
6405 * If we are detaching the second disk from a replacing vdev, then
6406 * check to see if we changed the original vdev's path to have "/old"
6407 * at the end in spa_vdev_attach(). If so, undo that change now.
6408 */
6409 if (pvd->vdev_ops == &vdev_replacing_ops && vd->vdev_id > 0 &&
6410 vd->vdev_path != NULL) {
6411 size_t len = strlen(vd->vdev_path);
6412
6413 for (int c = 0; c < pvd->vdev_children; c++) {
6414 cvd = pvd->vdev_child[c];
6415
6416 if (cvd == vd || cvd->vdev_path == NULL)
6417 continue;
6418
6419 if (strncmp(cvd->vdev_path, vd->vdev_path, len) == 0 &&
6420 strcmp(cvd->vdev_path + len, "/old") == 0) {
6421 spa_strfree(cvd->vdev_path);
6422 cvd->vdev_path = spa_strdup(vd->vdev_path);
6423 break;
6424 }
6425 }
6426 }
6427
6428 /*
6429 * If we are detaching the original disk from a spare, then it implies
6430 * that the spare should become a real disk, and be removed from the
6431 * active spare list for the pool.
6432 */
6433 if (pvd->vdev_ops == &vdev_spare_ops &&
6434 vd->vdev_id == 0 &&
6435 pvd->vdev_child[pvd->vdev_children - 1]->vdev_isspare)
6436 unspare = B_TRUE;
6437
6438 /*
6439 * Erase the disk labels so the disk can be used for other things.
6440 * This must be done after all other error cases are handled,
6441 * but before we disembowel vd (so we can still do I/O to it).
6442 * But if we can't do it, don't treat the error as fatal --
6443 * it may be that the unwritability of the disk is the reason
6444 * it's being detached!
6445 */
6446 error = vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
6447
6448 /*
6449 * Remove vd from its parent and compact the parent's children.
6450 */
6451 vdev_remove_child(pvd, vd);
6452 vdev_compact_children(pvd);
6453
6454 /*
6455 * Remember one of the remaining children so we can get tvd below.
6456 */
6457 cvd = pvd->vdev_child[pvd->vdev_children - 1];
6458
6459 /*
6460 * If we need to remove the remaining child from the list of hot spares,
6461 * do it now, marking the vdev as no longer a spare in the process.
6462 * We must do this before vdev_remove_parent(), because that can
6463 * change the GUID if it creates a new toplevel GUID. For a similar
6464 * reason, we must remove the spare now, in the same txg as the detach;
6465 * otherwise someone could attach a new sibling, change the GUID, and
6466 * the subsequent attempt to spa_vdev_remove(unspare_guid) would fail.
6467 */
6468 if (unspare) {
6469 ASSERT(cvd->vdev_isspare);
6470 spa_spare_remove(cvd);
6471 unspare_guid = cvd->vdev_guid;
6472 (void) spa_vdev_remove(spa, unspare_guid, B_TRUE);
6473 cvd->vdev_unspare = B_TRUE;
6474 }
6475
6476 /*
6477 * If the parent mirror/replacing vdev only has one child,
6478 * the parent is no longer needed. Remove it from the tree.
6479 */
6480 if (pvd->vdev_children == 1) {
6481 if (pvd->vdev_ops == &vdev_spare_ops)
6482 cvd->vdev_unspare = B_FALSE;
6483 vdev_remove_parent(cvd);
6484 }
6485
6486 /*
6487 * We don't set tvd until now because the parent we just removed
6488 * may have been the previous top-level vdev.
6489 */
6490 tvd = cvd->vdev_top;
6491 ASSERT(tvd->vdev_parent == rvd);
6492
6493 /*
6494 * Reevaluate the parent vdev state.
6495 */
6496 vdev_propagate_state(cvd);
6497
6498 /*
6499 * If the 'autoexpand' property is set on the pool then automatically
6500 * try to expand the size of the pool. For example if the device we
6501 * just detached was smaller than the others, it may be possible to
6502 * add metaslabs (i.e. grow the pool). We need to reopen the vdev
6503 * first so that we can obtain the updated sizes of the leaf vdevs.
6504 */
6505 if (spa->spa_autoexpand) {
6506 vdev_reopen(tvd);
6507 vdev_expand(tvd, txg);
6508 }
6509
6510 vdev_config_dirty(tvd);
6511
6512 /*
6513 * Mark vd's DTL as dirty in this txg. vdev_dtl_sync() will see that
6514 * vd->vdev_detached is set and free vd's DTL object in syncing context.
6515 * But first make sure we're not on any *other* txg's DTL list, to
6516 * prevent vd from being accessed after it's freed.
6517 */
6518 vdpath = spa_strdup(vd->vdev_path ? vd->vdev_path : "none");
6519 for (int t = 0; t < TXG_SIZE; t++)
6520 (void) txg_list_remove_this(&tvd->vdev_dtl_list, vd, t);
6521 vd->vdev_detached = B_TRUE;
6522 vdev_dirty(tvd, VDD_DTL, vd, txg);
6523
6524 spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE);
6525
6526 /* hang on to the spa before we release the lock */
6527 spa_open_ref(spa, FTAG);
6528
6529 error = spa_vdev_exit(spa, vd, txg, 0);
6530
6531 spa_history_log_internal(spa, "detach", NULL,
6532 "vdev=%s", vdpath);
6533 spa_strfree(vdpath);
6534
6535 /*
6536 * If this was the removal of the original device in a hot spare vdev,
6537 * then we want to go through and remove the device from the hot spare
6538 * list of every other pool.
6539 */
6540 if (unspare) {
6541 spa_t *altspa = NULL;
6542
6543 mutex_enter(&spa_namespace_lock);
6544 while ((altspa = spa_next(altspa)) != NULL) {
6545 if (altspa->spa_state != POOL_STATE_ACTIVE ||
6546 altspa == spa)
6547 continue;
6548
6549 spa_open_ref(altspa, FTAG);
6550 mutex_exit(&spa_namespace_lock);
6551 (void) spa_vdev_remove(altspa, unspare_guid, B_TRUE);
6552 mutex_enter(&spa_namespace_lock);
6553 spa_close(altspa, FTAG);
6554 }
6555 mutex_exit(&spa_namespace_lock);
6556
6557 /* search the rest of the vdevs for spares to remove */
6558 spa_vdev_resilver_done(spa);
6559 }
6560
6561 /* all done with the spa; OK to release */
6562 mutex_enter(&spa_namespace_lock);
6563 spa_close(spa, FTAG);
6564 mutex_exit(&spa_namespace_lock);
6565
6566 return (error);
6567 }
6568
6569 static int
6570 spa_vdev_initialize_impl(spa_t *spa, uint64_t guid, uint64_t cmd_type,
6571 list_t *vd_list)
6572 {
6573 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6574
6575 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
6576
6577 /* Look up vdev and ensure it's a leaf. */
6578 vdev_t *vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6579 if (vd == NULL || vd->vdev_detached) {
6580 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6581 return (SET_ERROR(ENODEV));
6582 } else if (!vd->vdev_ops->vdev_op_leaf || !vdev_is_concrete(vd)) {
6583 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6584 return (SET_ERROR(EINVAL));
6585 } else if (!vdev_writeable(vd)) {
6586 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6587 return (SET_ERROR(EROFS));
6588 }
6589 mutex_enter(&vd->vdev_initialize_lock);
6590 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6591
6592 /*
6593 * When we activate an initialize action we check to see
6594 * if the vdev_initialize_thread is NULL. We do this instead
6595 * of using the vdev_initialize_state since there might be
6596 * a previous initialization process which has completed but
6597 * the thread is not exited.
6598 */
6599 if (cmd_type == POOL_INITIALIZE_START &&
6600 (vd->vdev_initialize_thread != NULL ||
6601 vd->vdev_top->vdev_removing)) {
6602 mutex_exit(&vd->vdev_initialize_lock);
6603 return (SET_ERROR(EBUSY));
6604 } else if (cmd_type == POOL_INITIALIZE_CANCEL &&
6605 (vd->vdev_initialize_state != VDEV_INITIALIZE_ACTIVE &&
6606 vd->vdev_initialize_state != VDEV_INITIALIZE_SUSPENDED)) {
6607 mutex_exit(&vd->vdev_initialize_lock);
6608 return (SET_ERROR(ESRCH));
6609 } else if (cmd_type == POOL_INITIALIZE_SUSPEND &&
6610 vd->vdev_initialize_state != VDEV_INITIALIZE_ACTIVE) {
6611 mutex_exit(&vd->vdev_initialize_lock);
6612 return (SET_ERROR(ESRCH));
6613 }
6614
6615 switch (cmd_type) {
6616 case POOL_INITIALIZE_START:
6617 vdev_initialize(vd);
6618 break;
6619 case POOL_INITIALIZE_CANCEL:
6620 vdev_initialize_stop(vd, VDEV_INITIALIZE_CANCELED, vd_list);
6621 break;
6622 case POOL_INITIALIZE_SUSPEND:
6623 vdev_initialize_stop(vd, VDEV_INITIALIZE_SUSPENDED, vd_list);
6624 break;
6625 default:
6626 panic("invalid cmd_type %llu", (unsigned long long)cmd_type);
6627 }
6628 mutex_exit(&vd->vdev_initialize_lock);
6629
6630 return (0);
6631 }
6632
6633 int
6634 spa_vdev_initialize(spa_t *spa, nvlist_t *nv, uint64_t cmd_type,
6635 nvlist_t *vdev_errlist)
6636 {
6637 int total_errors = 0;
6638 list_t vd_list;
6639
6640 list_create(&vd_list, sizeof (vdev_t),
6641 offsetof(vdev_t, vdev_initialize_node));
6642
6643 /*
6644 * We hold the namespace lock through the whole function
6645 * to prevent any changes to the pool while we're starting or
6646 * stopping initialization. The config and state locks are held so that
6647 * we can properly assess the vdev state before we commit to
6648 * the initializing operation.
6649 */
6650 mutex_enter(&spa_namespace_lock);
6651
6652 for (nvpair_t *pair = nvlist_next_nvpair(nv, NULL);
6653 pair != NULL; pair = nvlist_next_nvpair(nv, pair)) {
6654 uint64_t vdev_guid = fnvpair_value_uint64(pair);
6655
6656 int error = spa_vdev_initialize_impl(spa, vdev_guid, cmd_type,
6657 &vd_list);
6658 if (error != 0) {
6659 char guid_as_str[MAXNAMELEN];
6660
6661 (void) snprintf(guid_as_str, sizeof (guid_as_str),
6662 "%llu", (unsigned long long)vdev_guid);
6663 fnvlist_add_int64(vdev_errlist, guid_as_str, error);
6664 total_errors++;
6665 }
6666 }
6667
6668 /* Wait for all initialize threads to stop. */
6669 vdev_initialize_stop_wait(spa, &vd_list);
6670
6671 /* Sync out the initializing state */
6672 txg_wait_synced(spa->spa_dsl_pool, 0);
6673 mutex_exit(&spa_namespace_lock);
6674
6675 list_destroy(&vd_list);
6676
6677 return (total_errors);
6678 }
6679
6680 static int
6681 spa_vdev_trim_impl(spa_t *spa, uint64_t guid, uint64_t cmd_type,
6682 uint64_t rate, boolean_t partial, boolean_t secure, list_t *vd_list)
6683 {
6684 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6685
6686 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
6687
6688 /* Look up vdev and ensure it's a leaf. */
6689 vdev_t *vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6690 if (vd == NULL || vd->vdev_detached) {
6691 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6692 return (SET_ERROR(ENODEV));
6693 } else if (!vd->vdev_ops->vdev_op_leaf || !vdev_is_concrete(vd)) {
6694 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6695 return (SET_ERROR(EINVAL));
6696 } else if (!vdev_writeable(vd)) {
6697 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6698 return (SET_ERROR(EROFS));
6699 } else if (!vd->vdev_has_trim) {
6700 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6701 return (SET_ERROR(EOPNOTSUPP));
6702 } else if (secure && !vd->vdev_has_securetrim) {
6703 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6704 return (SET_ERROR(EOPNOTSUPP));
6705 }
6706 mutex_enter(&vd->vdev_trim_lock);
6707 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6708
6709 /*
6710 * When we activate a TRIM action we check to see if the
6711 * vdev_trim_thread is NULL. We do this instead of using the
6712 * vdev_trim_state since there might be a previous TRIM process
6713 * which has completed but the thread is not exited.
6714 */
6715 if (cmd_type == POOL_TRIM_START &&
6716 (vd->vdev_trim_thread != NULL || vd->vdev_top->vdev_removing)) {
6717 mutex_exit(&vd->vdev_trim_lock);
6718 return (SET_ERROR(EBUSY));
6719 } else if (cmd_type == POOL_TRIM_CANCEL &&
6720 (vd->vdev_trim_state != VDEV_TRIM_ACTIVE &&
6721 vd->vdev_trim_state != VDEV_TRIM_SUSPENDED)) {
6722 mutex_exit(&vd->vdev_trim_lock);
6723 return (SET_ERROR(ESRCH));
6724 } else if (cmd_type == POOL_TRIM_SUSPEND &&
6725 vd->vdev_trim_state != VDEV_TRIM_ACTIVE) {
6726 mutex_exit(&vd->vdev_trim_lock);
6727 return (SET_ERROR(ESRCH));
6728 }
6729
6730 switch (cmd_type) {
6731 case POOL_TRIM_START:
6732 vdev_trim(vd, rate, partial, secure);
6733 break;
6734 case POOL_TRIM_CANCEL:
6735 vdev_trim_stop(vd, VDEV_TRIM_CANCELED, vd_list);
6736 break;
6737 case POOL_TRIM_SUSPEND:
6738 vdev_trim_stop(vd, VDEV_TRIM_SUSPENDED, vd_list);
6739 break;
6740 default:
6741 panic("invalid cmd_type %llu", (unsigned long long)cmd_type);
6742 }
6743 mutex_exit(&vd->vdev_trim_lock);
6744
6745 return (0);
6746 }
6747
6748 /*
6749 * Initiates a manual TRIM for the requested vdevs. This kicks off individual
6750 * TRIM threads for each child vdev. These threads pass over all of the free
6751 * space in the vdev's metaslabs and issues TRIM commands for that space.
6752 */
6753 int
6754 spa_vdev_trim(spa_t *spa, nvlist_t *nv, uint64_t cmd_type, uint64_t rate,
6755 boolean_t partial, boolean_t secure, nvlist_t *vdev_errlist)
6756 {
6757 int total_errors = 0;
6758 list_t vd_list;
6759
6760 list_create(&vd_list, sizeof (vdev_t),
6761 offsetof(vdev_t, vdev_trim_node));
6762
6763 /*
6764 * We hold the namespace lock through the whole function
6765 * to prevent any changes to the pool while we're starting or
6766 * stopping TRIM. The config and state locks are held so that
6767 * we can properly assess the vdev state before we commit to
6768 * the TRIM operation.
6769 */
6770 mutex_enter(&spa_namespace_lock);
6771
6772 for (nvpair_t *pair = nvlist_next_nvpair(nv, NULL);
6773 pair != NULL; pair = nvlist_next_nvpair(nv, pair)) {
6774 uint64_t vdev_guid = fnvpair_value_uint64(pair);
6775
6776 int error = spa_vdev_trim_impl(spa, vdev_guid, cmd_type,
6777 rate, partial, secure, &vd_list);
6778 if (error != 0) {
6779 char guid_as_str[MAXNAMELEN];
6780
6781 (void) snprintf(guid_as_str, sizeof (guid_as_str),
6782 "%llu", (unsigned long long)vdev_guid);
6783 fnvlist_add_int64(vdev_errlist, guid_as_str, error);
6784 total_errors++;
6785 }
6786 }
6787
6788 /* Wait for all TRIM threads to stop. */
6789 vdev_trim_stop_wait(spa, &vd_list);
6790
6791 /* Sync out the TRIM state */
6792 txg_wait_synced(spa->spa_dsl_pool, 0);
6793 mutex_exit(&spa_namespace_lock);
6794
6795 list_destroy(&vd_list);
6796
6797 return (total_errors);
6798 }
6799
6800 /*
6801 * Split a set of devices from their mirrors, and create a new pool from them.
6802 */
6803 int
6804 spa_vdev_split_mirror(spa_t *spa, char *newname, nvlist_t *config,
6805 nvlist_t *props, boolean_t exp)
6806 {
6807 int error = 0;
6808 uint64_t txg, *glist;
6809 spa_t *newspa;
6810 uint_t c, children, lastlog;
6811 nvlist_t **child, *nvl, *tmp;
6812 dmu_tx_t *tx;
6813 char *altroot = NULL;
6814 vdev_t *rvd, **vml = NULL; /* vdev modify list */
6815 boolean_t activate_slog;
6816
6817 ASSERT(spa_writeable(spa));
6818
6819 txg = spa_vdev_enter(spa);
6820
6821 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6822 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6823 error = (spa_has_checkpoint(spa)) ?
6824 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6825 return (spa_vdev_exit(spa, NULL, txg, error));
6826 }
6827
6828 /* clear the log and flush everything up to now */
6829 activate_slog = spa_passivate_log(spa);
6830 (void) spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
6831 error = spa_reset_logs(spa);
6832 txg = spa_vdev_config_enter(spa);
6833
6834 if (activate_slog)
6835 spa_activate_log(spa);
6836
6837 if (error != 0)
6838 return (spa_vdev_exit(spa, NULL, txg, error));
6839
6840 /* check new spa name before going any further */
6841 if (spa_lookup(newname) != NULL)
6842 return (spa_vdev_exit(spa, NULL, txg, EEXIST));
6843
6844 /*
6845 * scan through all the children to ensure they're all mirrors
6846 */
6847 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvl) != 0 ||
6848 nvlist_lookup_nvlist_array(nvl, ZPOOL_CONFIG_CHILDREN, &child,
6849 &children) != 0)
6850 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6851
6852 /* first, check to ensure we've got the right child count */
6853 rvd = spa->spa_root_vdev;
6854 lastlog = 0;
6855 for (c = 0; c < rvd->vdev_children; c++) {
6856 vdev_t *vd = rvd->vdev_child[c];
6857
6858 /* don't count the holes & logs as children */
6859 if (vd->vdev_islog || !vdev_is_concrete(vd)) {
6860 if (lastlog == 0)
6861 lastlog = c;
6862 continue;
6863 }
6864
6865 lastlog = 0;
6866 }
6867 if (children != (lastlog != 0 ? lastlog : rvd->vdev_children))
6868 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6869
6870 /* next, ensure no spare or cache devices are part of the split */
6871 if (nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_SPARES, &tmp) == 0 ||
6872 nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_L2CACHE, &tmp) == 0)
6873 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6874
6875 vml = kmem_zalloc(children * sizeof (vdev_t *), KM_SLEEP);
6876 glist = kmem_zalloc(children * sizeof (uint64_t), KM_SLEEP);
6877
6878 /* then, loop over each vdev and validate it */
6879 for (c = 0; c < children; c++) {
6880 uint64_t is_hole = 0;
6881
6882 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
6883 &is_hole);
6884
6885 if (is_hole != 0) {
6886 if (spa->spa_root_vdev->vdev_child[c]->vdev_ishole ||
6887 spa->spa_root_vdev->vdev_child[c]->vdev_islog) {
6888 continue;
6889 } else {
6890 error = SET_ERROR(EINVAL);
6891 break;
6892 }
6893 }
6894
6895 /* which disk is going to be split? */
6896 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_GUID,
6897 &glist[c]) != 0) {
6898 error = SET_ERROR(EINVAL);
6899 break;
6900 }
6901
6902 /* look it up in the spa */
6903 vml[c] = spa_lookup_by_guid(spa, glist[c], B_FALSE);
6904 if (vml[c] == NULL) {
6905 error = SET_ERROR(ENODEV);
6906 break;
6907 }
6908
6909 /* make sure there's nothing stopping the split */
6910 if (vml[c]->vdev_parent->vdev_ops != &vdev_mirror_ops ||
6911 vml[c]->vdev_islog ||
6912 !vdev_is_concrete(vml[c]) ||
6913 vml[c]->vdev_isspare ||
6914 vml[c]->vdev_isl2cache ||
6915 !vdev_writeable(vml[c]) ||
6916 vml[c]->vdev_children != 0 ||
6917 vml[c]->vdev_state != VDEV_STATE_HEALTHY ||
6918 c != spa->spa_root_vdev->vdev_child[c]->vdev_id) {
6919 error = SET_ERROR(EINVAL);
6920 break;
6921 }
6922
6923 if (vdev_dtl_required(vml[c]) ||
6924 vdev_resilver_needed(vml[c], NULL, NULL)) {
6925 error = SET_ERROR(EBUSY);
6926 break;
6927 }
6928
6929 /* we need certain info from the top level */
6930 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_ARRAY,
6931 vml[c]->vdev_top->vdev_ms_array) == 0);
6932 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_SHIFT,
6933 vml[c]->vdev_top->vdev_ms_shift) == 0);
6934 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASIZE,
6935 vml[c]->vdev_top->vdev_asize) == 0);
6936 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASHIFT,
6937 vml[c]->vdev_top->vdev_ashift) == 0);
6938
6939 /* transfer per-vdev ZAPs */
6940 ASSERT3U(vml[c]->vdev_leaf_zap, !=, 0);
6941 VERIFY0(nvlist_add_uint64(child[c],
6942 ZPOOL_CONFIG_VDEV_LEAF_ZAP, vml[c]->vdev_leaf_zap));
6943
6944 ASSERT3U(vml[c]->vdev_top->vdev_top_zap, !=, 0);
6945 VERIFY0(nvlist_add_uint64(child[c],
6946 ZPOOL_CONFIG_VDEV_TOP_ZAP,
6947 vml[c]->vdev_parent->vdev_top_zap));
6948 }
6949
6950 if (error != 0) {
6951 kmem_free(vml, children * sizeof (vdev_t *));
6952 kmem_free(glist, children * sizeof (uint64_t));
6953 return (spa_vdev_exit(spa, NULL, txg, error));
6954 }
6955
6956 /* stop writers from using the disks */
6957 for (c = 0; c < children; c++) {
6958 if (vml[c] != NULL)
6959 vml[c]->vdev_offline = B_TRUE;
6960 }
6961 vdev_reopen(spa->spa_root_vdev);
6962
6963 /*
6964 * Temporarily record the splitting vdevs in the spa config. This
6965 * will disappear once the config is regenerated.
6966 */
6967 VERIFY(nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
6968 VERIFY(nvlist_add_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
6969 glist, children) == 0);
6970 kmem_free(glist, children * sizeof (uint64_t));
6971
6972 mutex_enter(&spa->spa_props_lock);
6973 VERIFY(nvlist_add_nvlist(spa->spa_config, ZPOOL_CONFIG_SPLIT,
6974 nvl) == 0);
6975 mutex_exit(&spa->spa_props_lock);
6976 spa->spa_config_splitting = nvl;
6977 vdev_config_dirty(spa->spa_root_vdev);
6978
6979 /* configure and create the new pool */
6980 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME, newname) == 0);
6981 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
6982 exp ? POOL_STATE_EXPORTED : POOL_STATE_ACTIVE) == 0);
6983 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
6984 spa_version(spa)) == 0);
6985 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_TXG,
6986 spa->spa_config_txg) == 0);
6987 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_GUID,
6988 spa_generate_guid(NULL)) == 0);
6989 VERIFY0(nvlist_add_boolean(config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
6990 (void) nvlist_lookup_string(props,
6991 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
6992
6993 /* add the new pool to the namespace */
6994 newspa = spa_add(newname, config, altroot);
6995 newspa->spa_avz_action = AVZ_ACTION_REBUILD;
6996 newspa->spa_config_txg = spa->spa_config_txg;
6997 spa_set_log_state(newspa, SPA_LOG_CLEAR);
6998
6999 /* release the spa config lock, retaining the namespace lock */
7000 spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
7001
7002 if (zio_injection_enabled)
7003 zio_handle_panic_injection(spa, FTAG, 1);
7004
7005 spa_activate(newspa, spa_mode_global);
7006 spa_async_suspend(newspa);
7007
7008 /*
7009 * Temporarily stop the initializing and TRIM activity. We set the
7010 * state to ACTIVE so that we know to resume initializing or TRIM
7011 * once the split has completed.
7012 */
7013 list_t vd_initialize_list;
7014 list_create(&vd_initialize_list, sizeof (vdev_t),
7015 offsetof(vdev_t, vdev_initialize_node));
7016
7017 list_t vd_trim_list;
7018 list_create(&vd_trim_list, sizeof (vdev_t),
7019 offsetof(vdev_t, vdev_trim_node));
7020
7021 for (c = 0; c < children; c++) {
7022 if (vml[c] != NULL) {
7023 mutex_enter(&vml[c]->vdev_initialize_lock);
7024 vdev_initialize_stop(vml[c],
7025 VDEV_INITIALIZE_ACTIVE, &vd_initialize_list);
7026 mutex_exit(&vml[c]->vdev_initialize_lock);
7027
7028 mutex_enter(&vml[c]->vdev_trim_lock);
7029 vdev_trim_stop(vml[c], VDEV_TRIM_ACTIVE, &vd_trim_list);
7030 mutex_exit(&vml[c]->vdev_trim_lock);
7031 }
7032 }
7033
7034 vdev_initialize_stop_wait(spa, &vd_initialize_list);
7035 vdev_trim_stop_wait(spa, &vd_trim_list);
7036
7037 list_destroy(&vd_initialize_list);
7038 list_destroy(&vd_trim_list);
7039
7040 newspa->spa_config_source = SPA_CONFIG_SRC_SPLIT;
7041
7042 /* create the new pool from the disks of the original pool */
7043 error = spa_load(newspa, SPA_LOAD_IMPORT, SPA_IMPORT_ASSEMBLE);
7044 if (error)
7045 goto out;
7046
7047 /* if that worked, generate a real config for the new pool */
7048 if (newspa->spa_root_vdev != NULL) {
7049 VERIFY(nvlist_alloc(&newspa->spa_config_splitting,
7050 NV_UNIQUE_NAME, KM_SLEEP) == 0);
7051 VERIFY(nvlist_add_uint64(newspa->spa_config_splitting,
7052 ZPOOL_CONFIG_SPLIT_GUID, spa_guid(spa)) == 0);
7053 spa_config_set(newspa, spa_config_generate(newspa, NULL, -1ULL,
7054 B_TRUE));
7055 }
7056
7057 /* set the props */
7058 if (props != NULL) {
7059 spa_configfile_set(newspa, props, B_FALSE);
7060 error = spa_prop_set(newspa, props);
7061 if (error)
7062 goto out;
7063 }
7064
7065 /* flush everything */
7066 txg = spa_vdev_config_enter(newspa);
7067 vdev_config_dirty(newspa->spa_root_vdev);
7068 (void) spa_vdev_config_exit(newspa, NULL, txg, 0, FTAG);
7069
7070 if (zio_injection_enabled)
7071 zio_handle_panic_injection(spa, FTAG, 2);
7072
7073 spa_async_resume(newspa);
7074
7075 /* finally, update the original pool's config */
7076 txg = spa_vdev_config_enter(spa);
7077 tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
7078 error = dmu_tx_assign(tx, TXG_WAIT);
7079 if (error != 0)
7080 dmu_tx_abort(tx);
7081 for (c = 0; c < children; c++) {
7082 if (vml[c] != NULL) {
7083 vdev_t *tvd = vml[c]->vdev_top;
7084
7085 /*
7086 * Need to be sure the detachable VDEV is not
7087 * on any *other* txg's DTL list to prevent it
7088 * from being accessed after it's freed.
7089 */
7090 for (int t = 0; t < TXG_SIZE; t++) {
7091 (void) txg_list_remove_this(
7092 &tvd->vdev_dtl_list, vml[c], t);
7093 }
7094
7095 vdev_split(vml[c]);
7096 if (error == 0)
7097 spa_history_log_internal(spa, "detach", tx,
7098 "vdev=%s", vml[c]->vdev_path);
7099
7100 vdev_free(vml[c]);
7101 }
7102 }
7103 spa->spa_avz_action = AVZ_ACTION_REBUILD;
7104 vdev_config_dirty(spa->spa_root_vdev);
7105 spa->spa_config_splitting = NULL;
7106 nvlist_free(nvl);
7107 if (error == 0)
7108 dmu_tx_commit(tx);
7109 (void) spa_vdev_exit(spa, NULL, txg, 0);
7110
7111 if (zio_injection_enabled)
7112 zio_handle_panic_injection(spa, FTAG, 3);
7113
7114 /* split is complete; log a history record */
7115 spa_history_log_internal(newspa, "split", NULL,
7116 "from pool %s", spa_name(spa));
7117
7118 kmem_free(vml, children * sizeof (vdev_t *));
7119
7120 /* if we're not going to mount the filesystems in userland, export */
7121 if (exp)
7122 error = spa_export_common(newname, POOL_STATE_EXPORTED, NULL,
7123 B_FALSE, B_FALSE);
7124
7125 return (error);
7126
7127 out:
7128 spa_unload(newspa);
7129 spa_deactivate(newspa);
7130 spa_remove(newspa);
7131
7132 txg = spa_vdev_config_enter(spa);
7133
7134 /* re-online all offlined disks */
7135 for (c = 0; c < children; c++) {
7136 if (vml[c] != NULL)
7137 vml[c]->vdev_offline = B_FALSE;
7138 }
7139
7140 /* restart initializing or trimming disks as necessary */
7141 spa_async_request(spa, SPA_ASYNC_INITIALIZE_RESTART);
7142 spa_async_request(spa, SPA_ASYNC_TRIM_RESTART);
7143 spa_async_request(spa, SPA_ASYNC_AUTOTRIM_RESTART);
7144
7145 vdev_reopen(spa->spa_root_vdev);
7146
7147 nvlist_free(spa->spa_config_splitting);
7148 spa->spa_config_splitting = NULL;
7149 (void) spa_vdev_exit(spa, NULL, txg, error);
7150
7151 kmem_free(vml, children * sizeof (vdev_t *));
7152 return (error);
7153 }
7154
7155 /*
7156 * Find any device that's done replacing, or a vdev marked 'unspare' that's
7157 * currently spared, so we can detach it.
7158 */
7159 static vdev_t *
7160 spa_vdev_resilver_done_hunt(vdev_t *vd)
7161 {
7162 vdev_t *newvd, *oldvd;
7163
7164 for (int c = 0; c < vd->vdev_children; c++) {
7165 oldvd = spa_vdev_resilver_done_hunt(vd->vdev_child[c]);
7166 if (oldvd != NULL)
7167 return (oldvd);
7168 }
7169
7170 /*
7171 * Check for a completed replacement. We always consider the first
7172 * vdev in the list to be the oldest vdev, and the last one to be
7173 * the newest (see spa_vdev_attach() for how that works). In
7174 * the case where the newest vdev is faulted, we will not automatically
7175 * remove it after a resilver completes. This is OK as it will require
7176 * user intervention to determine which disk the admin wishes to keep.
7177 */
7178 if (vd->vdev_ops == &vdev_replacing_ops) {
7179 ASSERT(vd->vdev_children > 1);
7180
7181 newvd = vd->vdev_child[vd->vdev_children - 1];
7182 oldvd = vd->vdev_child[0];
7183
7184 if (vdev_dtl_empty(newvd, DTL_MISSING) &&
7185 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
7186 !vdev_dtl_required(oldvd))
7187 return (oldvd);
7188 }
7189
7190 /*
7191 * Check for a completed resilver with the 'unspare' flag set.
7192 * Also potentially update faulted state.
7193 */
7194 if (vd->vdev_ops == &vdev_spare_ops) {
7195 vdev_t *first = vd->vdev_child[0];
7196 vdev_t *last = vd->vdev_child[vd->vdev_children - 1];
7197
7198 if (last->vdev_unspare) {
7199 oldvd = first;
7200 newvd = last;
7201 } else if (first->vdev_unspare) {
7202 oldvd = last;
7203 newvd = first;
7204 } else {
7205 oldvd = NULL;
7206 }
7207
7208 if (oldvd != NULL &&
7209 vdev_dtl_empty(newvd, DTL_MISSING) &&
7210 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
7211 !vdev_dtl_required(oldvd))
7212 return (oldvd);
7213
7214 vdev_propagate_state(vd);
7215
7216 /*
7217 * If there are more than two spares attached to a disk,
7218 * and those spares are not required, then we want to
7219 * attempt to free them up now so that they can be used
7220 * by other pools. Once we're back down to a single
7221 * disk+spare, we stop removing them.
7222 */
7223 if (vd->vdev_children > 2) {
7224 newvd = vd->vdev_child[1];
7225
7226 if (newvd->vdev_isspare && last->vdev_isspare &&
7227 vdev_dtl_empty(last, DTL_MISSING) &&
7228 vdev_dtl_empty(last, DTL_OUTAGE) &&
7229 !vdev_dtl_required(newvd))
7230 return (newvd);
7231 }
7232 }
7233
7234 return (NULL);
7235 }
7236
7237 static void
7238 spa_vdev_resilver_done(spa_t *spa)
7239 {
7240 vdev_t *vd, *pvd, *ppvd;
7241 uint64_t guid, sguid, pguid, ppguid;
7242
7243 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
7244
7245 while ((vd = spa_vdev_resilver_done_hunt(spa->spa_root_vdev)) != NULL) {
7246 pvd = vd->vdev_parent;
7247 ppvd = pvd->vdev_parent;
7248 guid = vd->vdev_guid;
7249 pguid = pvd->vdev_guid;
7250 ppguid = ppvd->vdev_guid;
7251 sguid = 0;
7252 /*
7253 * If we have just finished replacing a hot spared device, then
7254 * we need to detach the parent's first child (the original hot
7255 * spare) as well.
7256 */
7257 if (ppvd->vdev_ops == &vdev_spare_ops && pvd->vdev_id == 0 &&
7258 ppvd->vdev_children == 2) {
7259 ASSERT(pvd->vdev_ops == &vdev_replacing_ops);
7260 sguid = ppvd->vdev_child[1]->vdev_guid;
7261 }
7262 ASSERT(vd->vdev_resilver_txg == 0 || !vdev_dtl_required(vd));
7263
7264 spa_config_exit(spa, SCL_ALL, FTAG);
7265 if (spa_vdev_detach(spa, guid, pguid, B_TRUE) != 0)
7266 return;
7267 if (sguid && spa_vdev_detach(spa, sguid, ppguid, B_TRUE) != 0)
7268 return;
7269 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
7270 }
7271
7272 spa_config_exit(spa, SCL_ALL, FTAG);
7273 }
7274
7275 /*
7276 * Update the stored path or FRU for this vdev.
7277 */
7278 int
7279 spa_vdev_set_common(spa_t *spa, uint64_t guid, const char *value,
7280 boolean_t ispath)
7281 {
7282 vdev_t *vd;
7283 boolean_t sync = B_FALSE;
7284
7285 ASSERT(spa_writeable(spa));
7286
7287 spa_vdev_state_enter(spa, SCL_ALL);
7288
7289 if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
7290 return (spa_vdev_state_exit(spa, NULL, ENOENT));
7291
7292 if (!vd->vdev_ops->vdev_op_leaf)
7293 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
7294
7295 if (ispath) {
7296 if (strcmp(value, vd->vdev_path) != 0) {
7297 spa_strfree(vd->vdev_path);
7298 vd->vdev_path = spa_strdup(value);
7299 sync = B_TRUE;
7300 }
7301 } else {
7302 if (vd->vdev_fru == NULL) {
7303 vd->vdev_fru = spa_strdup(value);
7304 sync = B_TRUE;
7305 } else if (strcmp(value, vd->vdev_fru) != 0) {
7306 spa_strfree(vd->vdev_fru);
7307 vd->vdev_fru = spa_strdup(value);
7308 sync = B_TRUE;
7309 }
7310 }
7311
7312 return (spa_vdev_state_exit(spa, sync ? vd : NULL, 0));
7313 }
7314
7315 int
7316 spa_vdev_setpath(spa_t *spa, uint64_t guid, const char *newpath)
7317 {
7318 return (spa_vdev_set_common(spa, guid, newpath, B_TRUE));
7319 }
7320
7321 int
7322 spa_vdev_setfru(spa_t *spa, uint64_t guid, const char *newfru)
7323 {
7324 return (spa_vdev_set_common(spa, guid, newfru, B_FALSE));
7325 }
7326
7327 /*
7328 * ==========================================================================
7329 * SPA Scanning
7330 * ==========================================================================
7331 */
7332 int
7333 spa_scrub_pause_resume(spa_t *spa, pool_scrub_cmd_t cmd)
7334 {
7335 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7336
7337 if (dsl_scan_resilvering(spa->spa_dsl_pool))
7338 return (SET_ERROR(EBUSY));
7339
7340 return (dsl_scrub_set_pause_resume(spa->spa_dsl_pool, cmd));
7341 }
7342
7343 int
7344 spa_scan_stop(spa_t *spa)
7345 {
7346 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7347 if (dsl_scan_resilvering(spa->spa_dsl_pool))
7348 return (SET_ERROR(EBUSY));
7349 return (dsl_scan_cancel(spa->spa_dsl_pool));
7350 }
7351
7352 int
7353 spa_scan(spa_t *spa, pool_scan_func_t func)
7354 {
7355 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7356
7357 if (func >= POOL_SCAN_FUNCS || func == POOL_SCAN_NONE)
7358 return (SET_ERROR(ENOTSUP));
7359
7360 if (func == POOL_SCAN_RESILVER &&
7361 !spa_feature_is_enabled(spa, SPA_FEATURE_RESILVER_DEFER))
7362 return (SET_ERROR(ENOTSUP));
7363
7364 /*
7365 * If a resilver was requested, but there is no DTL on a
7366 * writeable leaf device, we have nothing to do.
7367 */
7368 if (func == POOL_SCAN_RESILVER &&
7369 !vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL)) {
7370 spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
7371 return (0);
7372 }
7373
7374 return (dsl_scan(spa->spa_dsl_pool, func));
7375 }
7376
7377 /*
7378 * ==========================================================================
7379 * SPA async task processing
7380 * ==========================================================================
7381 */
7382
7383 static void
7384 spa_async_remove(spa_t *spa, vdev_t *vd)
7385 {
7386 if (vd->vdev_remove_wanted) {
7387 vd->vdev_remove_wanted = B_FALSE;
7388 vd->vdev_delayed_close = B_FALSE;
7389 vdev_set_state(vd, B_FALSE, VDEV_STATE_REMOVED, VDEV_AUX_NONE);
7390
7391 /*
7392 * We want to clear the stats, but we don't want to do a full
7393 * vdev_clear() as that will cause us to throw away
7394 * degraded/faulted state as well as attempt to reopen the
7395 * device, all of which is a waste.
7396 */
7397 vd->vdev_stat.vs_read_errors = 0;
7398 vd->vdev_stat.vs_write_errors = 0;
7399 vd->vdev_stat.vs_checksum_errors = 0;
7400
7401 vdev_state_dirty(vd->vdev_top);
7402 }
7403
7404 for (int c = 0; c < vd->vdev_children; c++)
7405 spa_async_remove(spa, vd->vdev_child[c]);
7406 }
7407
7408 static void
7409 spa_async_probe(spa_t *spa, vdev_t *vd)
7410 {
7411 if (vd->vdev_probe_wanted) {
7412 vd->vdev_probe_wanted = B_FALSE;
7413 vdev_reopen(vd); /* vdev_open() does the actual probe */
7414 }
7415
7416 for (int c = 0; c < vd->vdev_children; c++)
7417 spa_async_probe(spa, vd->vdev_child[c]);
7418 }
7419
7420 static void
7421 spa_async_autoexpand(spa_t *spa, vdev_t *vd)
7422 {
7423 if (!spa->spa_autoexpand)
7424 return;
7425
7426 for (int c = 0; c < vd->vdev_children; c++) {
7427 vdev_t *cvd = vd->vdev_child[c];
7428 spa_async_autoexpand(spa, cvd);
7429 }
7430
7431 if (!vd->vdev_ops->vdev_op_leaf || vd->vdev_physpath == NULL)
7432 return;
7433
7434 spa_event_notify(vd->vdev_spa, vd, NULL, ESC_ZFS_VDEV_AUTOEXPAND);
7435 }
7436
7437 static void
7438 spa_async_thread(void *arg)
7439 {
7440 spa_t *spa = (spa_t *)arg;
7441 dsl_pool_t *dp = spa->spa_dsl_pool;
7442 int tasks;
7443
7444 ASSERT(spa->spa_sync_on);
7445
7446 mutex_enter(&spa->spa_async_lock);
7447 tasks = spa->spa_async_tasks;
7448 spa->spa_async_tasks = 0;
7449 mutex_exit(&spa->spa_async_lock);
7450
7451 /*
7452 * See if the config needs to be updated.
7453 */
7454 if (tasks & SPA_ASYNC_CONFIG_UPDATE) {
7455 uint64_t old_space, new_space;
7456
7457 mutex_enter(&spa_namespace_lock);
7458 old_space = metaslab_class_get_space(spa_normal_class(spa));
7459 old_space += metaslab_class_get_space(spa_special_class(spa));
7460 old_space += metaslab_class_get_space(spa_dedup_class(spa));
7461
7462 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
7463
7464 new_space = metaslab_class_get_space(spa_normal_class(spa));
7465 new_space += metaslab_class_get_space(spa_special_class(spa));
7466 new_space += metaslab_class_get_space(spa_dedup_class(spa));
7467 mutex_exit(&spa_namespace_lock);
7468
7469 /*
7470 * If the pool grew as a result of the config update,
7471 * then log an internal history event.
7472 */
7473 if (new_space != old_space) {
7474 spa_history_log_internal(spa, "vdev online", NULL,
7475 "pool '%s' size: %llu(+%llu)",
7476 spa_name(spa), new_space, new_space - old_space);
7477 }
7478 }
7479
7480 /*
7481 * See if any devices need to be marked REMOVED.
7482 */
7483 if (tasks & SPA_ASYNC_REMOVE) {
7484 spa_vdev_state_enter(spa, SCL_NONE);
7485 spa_async_remove(spa, spa->spa_root_vdev);
7486 for (int i = 0; i < spa->spa_l2cache.sav_count; i++)
7487 spa_async_remove(spa, spa->spa_l2cache.sav_vdevs[i]);
7488 for (int i = 0; i < spa->spa_spares.sav_count; i++)
7489 spa_async_remove(spa, spa->spa_spares.sav_vdevs[i]);
7490 (void) spa_vdev_state_exit(spa, NULL, 0);
7491 }
7492
7493 if ((tasks & SPA_ASYNC_AUTOEXPAND) && !spa_suspended(spa)) {
7494 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7495 spa_async_autoexpand(spa, spa->spa_root_vdev);
7496 spa_config_exit(spa, SCL_CONFIG, FTAG);
7497 }
7498
7499 /*
7500 * See if any devices need to be probed.
7501 */
7502 if (tasks & SPA_ASYNC_PROBE) {
7503 spa_vdev_state_enter(spa, SCL_NONE);
7504 spa_async_probe(spa, spa->spa_root_vdev);
7505 (void) spa_vdev_state_exit(spa, NULL, 0);
7506 }
7507
7508 /*
7509 * If any devices are done replacing, detach them.
7510 */
7511 if (tasks & SPA_ASYNC_RESILVER_DONE)
7512 spa_vdev_resilver_done(spa);
7513
7514 /*
7515 * Kick off a resilver.
7516 */
7517 if (tasks & SPA_ASYNC_RESILVER &&
7518 (!dsl_scan_resilvering(dp) ||
7519 !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_RESILVER_DEFER)))
7520 dsl_resilver_restart(dp, 0);
7521
7522 if (tasks & SPA_ASYNC_INITIALIZE_RESTART) {
7523 mutex_enter(&spa_namespace_lock);
7524 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7525 vdev_initialize_restart(spa->spa_root_vdev);
7526 spa_config_exit(spa, SCL_CONFIG, FTAG);
7527 mutex_exit(&spa_namespace_lock);
7528 }
7529
7530 if (tasks & SPA_ASYNC_TRIM_RESTART) {
7531 mutex_enter(&spa_namespace_lock);
7532 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7533 vdev_trim_restart(spa->spa_root_vdev);
7534 spa_config_exit(spa, SCL_CONFIG, FTAG);
7535 mutex_exit(&spa_namespace_lock);
7536 }
7537
7538 if (tasks & SPA_ASYNC_AUTOTRIM_RESTART) {
7539 mutex_enter(&spa_namespace_lock);
7540 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7541 vdev_autotrim_restart(spa);
7542 spa_config_exit(spa, SCL_CONFIG, FTAG);
7543 mutex_exit(&spa_namespace_lock);
7544 }
7545
7546 /*
7547 * Let the world know that we're done.
7548 */
7549 mutex_enter(&spa->spa_async_lock);
7550 spa->spa_async_thread = NULL;
7551 cv_broadcast(&spa->spa_async_cv);
7552 mutex_exit(&spa->spa_async_lock);
7553 thread_exit();
7554 }
7555
7556 void
7557 spa_async_suspend(spa_t *spa)
7558 {
7559 mutex_enter(&spa->spa_async_lock);
7560 spa->spa_async_suspended++;
7561 while (spa->spa_async_thread != NULL)
7562 cv_wait(&spa->spa_async_cv, &spa->spa_async_lock);
7563 mutex_exit(&spa->spa_async_lock);
7564
7565 spa_vdev_remove_suspend(spa);
7566
7567 zthr_t *condense_thread = spa->spa_condense_zthr;
7568 if (condense_thread != NULL)
7569 zthr_cancel(condense_thread);
7570
7571 zthr_t *discard_thread = spa->spa_checkpoint_discard_zthr;
7572 if (discard_thread != NULL)
7573 zthr_cancel(discard_thread);
7574 }
7575
7576 void
7577 spa_async_resume(spa_t *spa)
7578 {
7579 mutex_enter(&spa->spa_async_lock);
7580 ASSERT(spa->spa_async_suspended != 0);
7581 spa->spa_async_suspended--;
7582 mutex_exit(&spa->spa_async_lock);
7583 spa_restart_removal(spa);
7584
7585 zthr_t *condense_thread = spa->spa_condense_zthr;
7586 if (condense_thread != NULL)
7587 zthr_resume(condense_thread);
7588
7589 zthr_t *discard_thread = spa->spa_checkpoint_discard_zthr;
7590 if (discard_thread != NULL)
7591 zthr_resume(discard_thread);
7592 }
7593
7594 static boolean_t
7595 spa_async_tasks_pending(spa_t *spa)
7596 {
7597 uint_t non_config_tasks;
7598 uint_t config_task;
7599 boolean_t config_task_suspended;
7600
7601 non_config_tasks = spa->spa_async_tasks & ~SPA_ASYNC_CONFIG_UPDATE;
7602 config_task = spa->spa_async_tasks & SPA_ASYNC_CONFIG_UPDATE;
7603 if (spa->spa_ccw_fail_time == 0) {
7604 config_task_suspended = B_FALSE;
7605 } else {
7606 config_task_suspended =
7607 (gethrtime() - spa->spa_ccw_fail_time) <
7608 ((hrtime_t)zfs_ccw_retry_interval * NANOSEC);
7609 }
7610
7611 return (non_config_tasks || (config_task && !config_task_suspended));
7612 }
7613
7614 static void
7615 spa_async_dispatch(spa_t *spa)
7616 {
7617 mutex_enter(&spa->spa_async_lock);
7618 if (spa_async_tasks_pending(spa) &&
7619 !spa->spa_async_suspended &&
7620 spa->spa_async_thread == NULL &&
7621 rootdir != NULL)
7622 spa->spa_async_thread = thread_create(NULL, 0,
7623 spa_async_thread, spa, 0, &p0, TS_RUN, maxclsyspri);
7624 mutex_exit(&spa->spa_async_lock);
7625 }
7626
7627 void
7628 spa_async_request(spa_t *spa, int task)
7629 {
7630 zfs_dbgmsg("spa=%s async request task=%u", spa->spa_name, task);
7631 mutex_enter(&spa->spa_async_lock);
7632 spa->spa_async_tasks |= task;
7633 mutex_exit(&spa->spa_async_lock);
7634 }
7635
7636 /*
7637 * ==========================================================================
7638 * SPA syncing routines
7639 * ==========================================================================
7640 */
7641
7642 static int
7643 bpobj_enqueue_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
7644 {
7645 bpobj_t *bpo = arg;
7646 bpobj_enqueue(bpo, bp, tx);
7647 return (0);
7648 }
7649
7650 static int
7651 spa_free_sync_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
7652 {
7653 zio_t *zio = arg;
7654
7655 zio_nowait(zio_free_sync(zio, zio->io_spa, dmu_tx_get_txg(tx), bp,
7656 zio->io_flags));
7657 return (0);
7658 }
7659
7660 /*
7661 * Note: this simple function is not inlined to make it easier to dtrace the
7662 * amount of time spent syncing frees.
7663 */
7664 static void
7665 spa_sync_frees(spa_t *spa, bplist_t *bpl, dmu_tx_t *tx)
7666 {
7667 zio_t *zio = zio_root(spa, NULL, NULL, 0);
7668 bplist_iterate(bpl, spa_free_sync_cb, zio, tx);
7669 VERIFY(zio_wait(zio) == 0);
7670 }
7671
7672 /*
7673 * Note: this simple function is not inlined to make it easier to dtrace the
7674 * amount of time spent syncing deferred frees.
7675 */
7676 static void
7677 spa_sync_deferred_frees(spa_t *spa, dmu_tx_t *tx)
7678 {
7679 if (spa_sync_pass(spa) != 1)
7680 return;
7681
7682 /*
7683 * Note:
7684 * If the log space map feature is active, we stop deferring
7685 * frees to the next TXG and therefore running this function
7686 * would be considered a no-op as spa_deferred_bpobj should
7687 * not have any entries.
7688 *
7689 * That said we run this function anyway (instead of returning
7690 * immediately) for the edge-case scenario where we just
7691 * activated the log space map feature in this TXG but we have
7692 * deferred frees from the previous TXG.
7693 */
7694 zio_t *zio = zio_root(spa, NULL, NULL, 0);
7695 VERIFY3U(bpobj_iterate(&spa->spa_deferred_bpobj,
7696 spa_free_sync_cb, zio, tx), ==, 0);
7697 VERIFY0(zio_wait(zio));
7698 }
7699
7700 static void
7701 spa_sync_nvlist(spa_t *spa, uint64_t obj, nvlist_t *nv, dmu_tx_t *tx)
7702 {
7703 char *packed = NULL;
7704 size_t bufsize;
7705 size_t nvsize = 0;
7706 dmu_buf_t *db;
7707
7708 VERIFY(nvlist_size(nv, &nvsize, NV_ENCODE_XDR) == 0);
7709
7710 /*
7711 * Write full (SPA_CONFIG_BLOCKSIZE) blocks of configuration
7712 * information. This avoids the dmu_buf_will_dirty() path and
7713 * saves us a pre-read to get data we don't actually care about.
7714 */
7715 bufsize = P2ROUNDUP((uint64_t)nvsize, SPA_CONFIG_BLOCKSIZE);
7716 packed = vmem_alloc(bufsize, KM_SLEEP);
7717
7718 VERIFY(nvlist_pack(nv, &packed, &nvsize, NV_ENCODE_XDR,
7719 KM_SLEEP) == 0);
7720 bzero(packed + nvsize, bufsize - nvsize);
7721
7722 dmu_write(spa->spa_meta_objset, obj, 0, bufsize, packed, tx);
7723
7724 vmem_free(packed, bufsize);
7725
7726 VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
7727 dmu_buf_will_dirty(db, tx);
7728 *(uint64_t *)db->db_data = nvsize;
7729 dmu_buf_rele(db, FTAG);
7730 }
7731
7732 static void
7733 spa_sync_aux_dev(spa_t *spa, spa_aux_vdev_t *sav, dmu_tx_t *tx,
7734 const char *config, const char *entry)
7735 {
7736 nvlist_t *nvroot;
7737 nvlist_t **list;
7738 int i;
7739
7740 if (!sav->sav_sync)
7741 return;
7742
7743 /*
7744 * Update the MOS nvlist describing the list of available devices.
7745 * spa_validate_aux() will have already made sure this nvlist is
7746 * valid and the vdevs are labeled appropriately.
7747 */
7748 if (sav->sav_object == 0) {
7749 sav->sav_object = dmu_object_alloc(spa->spa_meta_objset,
7750 DMU_OT_PACKED_NVLIST, 1 << 14, DMU_OT_PACKED_NVLIST_SIZE,
7751 sizeof (uint64_t), tx);
7752 VERIFY(zap_update(spa->spa_meta_objset,
7753 DMU_POOL_DIRECTORY_OBJECT, entry, sizeof (uint64_t), 1,
7754 &sav->sav_object, tx) == 0);
7755 }
7756
7757 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
7758 if (sav->sav_count == 0) {
7759 VERIFY(nvlist_add_nvlist_array(nvroot, config, NULL, 0) == 0);
7760 } else {
7761 list = kmem_alloc(sav->sav_count*sizeof (void *), KM_SLEEP);
7762 for (i = 0; i < sav->sav_count; i++)
7763 list[i] = vdev_config_generate(spa, sav->sav_vdevs[i],
7764 B_FALSE, VDEV_CONFIG_L2CACHE);
7765 VERIFY(nvlist_add_nvlist_array(nvroot, config, list,
7766 sav->sav_count) == 0);
7767 for (i = 0; i < sav->sav_count; i++)
7768 nvlist_free(list[i]);
7769 kmem_free(list, sav->sav_count * sizeof (void *));
7770 }
7771
7772 spa_sync_nvlist(spa, sav->sav_object, nvroot, tx);
7773 nvlist_free(nvroot);
7774
7775 sav->sav_sync = B_FALSE;
7776 }
7777
7778 /*
7779 * Rebuild spa's all-vdev ZAP from the vdev ZAPs indicated in each vdev_t.
7780 * The all-vdev ZAP must be empty.
7781 */
7782 static void
7783 spa_avz_build(vdev_t *vd, uint64_t avz, dmu_tx_t *tx)
7784 {
7785 spa_t *spa = vd->vdev_spa;
7786
7787 if (vd->vdev_top_zap != 0) {
7788 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
7789 vd->vdev_top_zap, tx));
7790 }
7791 if (vd->vdev_leaf_zap != 0) {
7792 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
7793 vd->vdev_leaf_zap, tx));
7794 }
7795 for (uint64_t i = 0; i < vd->vdev_children; i++) {
7796 spa_avz_build(vd->vdev_child[i], avz, tx);
7797 }
7798 }
7799
7800 static void
7801 spa_sync_config_object(spa_t *spa, dmu_tx_t *tx)
7802 {
7803 nvlist_t *config;
7804
7805 /*
7806 * If the pool is being imported from a pre-per-vdev-ZAP version of ZFS,
7807 * its config may not be dirty but we still need to build per-vdev ZAPs.
7808 * Similarly, if the pool is being assembled (e.g. after a split), we
7809 * need to rebuild the AVZ although the config may not be dirty.
7810 */
7811 if (list_is_empty(&spa->spa_config_dirty_list) &&
7812 spa->spa_avz_action == AVZ_ACTION_NONE)
7813 return;
7814
7815 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7816
7817 ASSERT(spa->spa_avz_action == AVZ_ACTION_NONE ||
7818 spa->spa_avz_action == AVZ_ACTION_INITIALIZE ||
7819 spa->spa_all_vdev_zaps != 0);
7820
7821 if (spa->spa_avz_action == AVZ_ACTION_REBUILD) {
7822 /* Make and build the new AVZ */
7823 uint64_t new_avz = zap_create(spa->spa_meta_objset,
7824 DMU_OTN_ZAP_METADATA, DMU_OT_NONE, 0, tx);
7825 spa_avz_build(spa->spa_root_vdev, new_avz, tx);
7826
7827 /* Diff old AVZ with new one */
7828 zap_cursor_t zc;
7829 zap_attribute_t za;
7830
7831 for (zap_cursor_init(&zc, spa->spa_meta_objset,
7832 spa->spa_all_vdev_zaps);
7833 zap_cursor_retrieve(&zc, &za) == 0;
7834 zap_cursor_advance(&zc)) {
7835 uint64_t vdzap = za.za_first_integer;
7836 if (zap_lookup_int(spa->spa_meta_objset, new_avz,
7837 vdzap) == ENOENT) {
7838 /*
7839 * ZAP is listed in old AVZ but not in new one;
7840 * destroy it
7841 */
7842 VERIFY0(zap_destroy(spa->spa_meta_objset, vdzap,
7843 tx));
7844 }
7845 }
7846
7847 zap_cursor_fini(&zc);
7848
7849 /* Destroy the old AVZ */
7850 VERIFY0(zap_destroy(spa->spa_meta_objset,
7851 spa->spa_all_vdev_zaps, tx));
7852
7853 /* Replace the old AVZ in the dir obj with the new one */
7854 VERIFY0(zap_update(spa->spa_meta_objset,
7855 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP,
7856 sizeof (new_avz), 1, &new_avz, tx));
7857
7858 spa->spa_all_vdev_zaps = new_avz;
7859 } else if (spa->spa_avz_action == AVZ_ACTION_DESTROY) {
7860 zap_cursor_t zc;
7861 zap_attribute_t za;
7862
7863 /* Walk through the AVZ and destroy all listed ZAPs */
7864 for (zap_cursor_init(&zc, spa->spa_meta_objset,
7865 spa->spa_all_vdev_zaps);
7866 zap_cursor_retrieve(&zc, &za) == 0;
7867 zap_cursor_advance(&zc)) {
7868 uint64_t zap = za.za_first_integer;
7869 VERIFY0(zap_destroy(spa->spa_meta_objset, zap, tx));
7870 }
7871
7872 zap_cursor_fini(&zc);
7873
7874 /* Destroy and unlink the AVZ itself */
7875 VERIFY0(zap_destroy(spa->spa_meta_objset,
7876 spa->spa_all_vdev_zaps, tx));
7877 VERIFY0(zap_remove(spa->spa_meta_objset,
7878 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP, tx));
7879 spa->spa_all_vdev_zaps = 0;
7880 }
7881
7882 if (spa->spa_all_vdev_zaps == 0) {
7883 spa->spa_all_vdev_zaps = zap_create_link(spa->spa_meta_objset,
7884 DMU_OTN_ZAP_METADATA, DMU_POOL_DIRECTORY_OBJECT,
7885 DMU_POOL_VDEV_ZAP_MAP, tx);
7886 }
7887 spa->spa_avz_action = AVZ_ACTION_NONE;
7888
7889 /* Create ZAPs for vdevs that don't have them. */
7890 vdev_construct_zaps(spa->spa_root_vdev, tx);
7891
7892 config = spa_config_generate(spa, spa->spa_root_vdev,
7893 dmu_tx_get_txg(tx), B_FALSE);
7894
7895 /*
7896 * If we're upgrading the spa version then make sure that
7897 * the config object gets updated with the correct version.
7898 */
7899 if (spa->spa_ubsync.ub_version < spa->spa_uberblock.ub_version)
7900 fnvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
7901 spa->spa_uberblock.ub_version);
7902
7903 spa_config_exit(spa, SCL_STATE, FTAG);
7904
7905 nvlist_free(spa->spa_config_syncing);
7906 spa->spa_config_syncing = config;
7907
7908 spa_sync_nvlist(spa, spa->spa_config_object, config, tx);
7909 }
7910
7911 static void
7912 spa_sync_version(void *arg, dmu_tx_t *tx)
7913 {
7914 uint64_t *versionp = arg;
7915 uint64_t version = *versionp;
7916 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
7917
7918 /*
7919 * Setting the version is special cased when first creating the pool.
7920 */
7921 ASSERT(tx->tx_txg != TXG_INITIAL);
7922
7923 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
7924 ASSERT(version >= spa_version(spa));
7925
7926 spa->spa_uberblock.ub_version = version;
7927 vdev_config_dirty(spa->spa_root_vdev);
7928 spa_history_log_internal(spa, "set", tx, "version=%lld", version);
7929 }
7930
7931 /*
7932 * Set zpool properties.
7933 */
7934 static void
7935 spa_sync_props(void *arg, dmu_tx_t *tx)
7936 {
7937 nvlist_t *nvp = arg;
7938 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
7939 objset_t *mos = spa->spa_meta_objset;
7940 nvpair_t *elem = NULL;
7941
7942 mutex_enter(&spa->spa_props_lock);
7943
7944 while ((elem = nvlist_next_nvpair(nvp, elem))) {
7945 uint64_t intval;
7946 char *strval, *fname;
7947 zpool_prop_t prop;
7948 const char *propname;
7949 zprop_type_t proptype;
7950 spa_feature_t fid;
7951
7952 switch (prop = zpool_name_to_prop(nvpair_name(elem))) {
7953 case ZPOOL_PROP_INVAL:
7954 /*
7955 * We checked this earlier in spa_prop_validate().
7956 */
7957 ASSERT(zpool_prop_feature(nvpair_name(elem)));
7958
7959 fname = strchr(nvpair_name(elem), '@') + 1;
7960 VERIFY0(zfeature_lookup_name(fname, &fid));
7961
7962 spa_feature_enable(spa, fid, tx);
7963 spa_history_log_internal(spa, "set", tx,
7964 "%s=enabled", nvpair_name(elem));
7965 break;
7966
7967 case ZPOOL_PROP_VERSION:
7968 intval = fnvpair_value_uint64(elem);
7969 /*
7970 * The version is synced separately before other
7971 * properties and should be correct by now.
7972 */
7973 ASSERT3U(spa_version(spa), >=, intval);
7974 break;
7975
7976 case ZPOOL_PROP_ALTROOT:
7977 /*
7978 * 'altroot' is a non-persistent property. It should
7979 * have been set temporarily at creation or import time.
7980 */
7981 ASSERT(spa->spa_root != NULL);
7982 break;
7983
7984 case ZPOOL_PROP_READONLY:
7985 case ZPOOL_PROP_CACHEFILE:
7986 /*
7987 * 'readonly' and 'cachefile' are also non-persisitent
7988 * properties.
7989 */
7990 break;
7991 case ZPOOL_PROP_COMMENT:
7992 strval = fnvpair_value_string(elem);
7993 if (spa->spa_comment != NULL)
7994 spa_strfree(spa->spa_comment);
7995 spa->spa_comment = spa_strdup(strval);
7996 /*
7997 * We need to dirty the configuration on all the vdevs
7998 * so that their labels get updated. It's unnecessary
7999 * to do this for pool creation since the vdev's
8000 * configuration has already been dirtied.
8001 */
8002 if (tx->tx_txg != TXG_INITIAL)
8003 vdev_config_dirty(spa->spa_root_vdev);
8004 spa_history_log_internal(spa, "set", tx,
8005 "%s=%s", nvpair_name(elem), strval);
8006 break;
8007 default:
8008 /*
8009 * Set pool property values in the poolprops mos object.
8010 */
8011 if (spa->spa_pool_props_object == 0) {
8012 spa->spa_pool_props_object =
8013 zap_create_link(mos, DMU_OT_POOL_PROPS,
8014 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_PROPS,
8015 tx);
8016 }
8017
8018 /* normalize the property name */
8019 propname = zpool_prop_to_name(prop);
8020 proptype = zpool_prop_get_type(prop);
8021
8022 if (nvpair_type(elem) == DATA_TYPE_STRING) {
8023 ASSERT(proptype == PROP_TYPE_STRING);
8024 strval = fnvpair_value_string(elem);
8025 VERIFY0(zap_update(mos,
8026 spa->spa_pool_props_object, propname,
8027 1, strlen(strval) + 1, strval, tx));
8028 spa_history_log_internal(spa, "set", tx,
8029 "%s=%s", nvpair_name(elem), strval);
8030 } else if (nvpair_type(elem) == DATA_TYPE_UINT64) {
8031 intval = fnvpair_value_uint64(elem);
8032
8033 if (proptype == PROP_TYPE_INDEX) {
8034 const char *unused;
8035 VERIFY0(zpool_prop_index_to_string(
8036 prop, intval, &unused));
8037 }
8038 VERIFY0(zap_update(mos,
8039 spa->spa_pool_props_object, propname,
8040 8, 1, &intval, tx));
8041 spa_history_log_internal(spa, "set", tx,
8042 "%s=%lld", nvpair_name(elem), intval);
8043 } else {
8044 ASSERT(0); /* not allowed */
8045 }
8046
8047 switch (prop) {
8048 case ZPOOL_PROP_DELEGATION:
8049 spa->spa_delegation = intval;
8050 break;
8051 case ZPOOL_PROP_BOOTFS:
8052 spa->spa_bootfs = intval;
8053 break;
8054 case ZPOOL_PROP_FAILUREMODE:
8055 spa->spa_failmode = intval;
8056 break;
8057 case ZPOOL_PROP_AUTOTRIM:
8058 spa->spa_autotrim = intval;
8059 spa_async_request(spa,
8060 SPA_ASYNC_AUTOTRIM_RESTART);
8061 break;
8062 case ZPOOL_PROP_AUTOEXPAND:
8063 spa->spa_autoexpand = intval;
8064 if (tx->tx_txg != TXG_INITIAL)
8065 spa_async_request(spa,
8066 SPA_ASYNC_AUTOEXPAND);
8067 break;
8068 case ZPOOL_PROP_MULTIHOST:
8069 spa->spa_multihost = intval;
8070 break;
8071 default:
8072 break;
8073 }
8074 }
8075
8076 }
8077
8078 mutex_exit(&spa->spa_props_lock);
8079 }
8080
8081 /*
8082 * Perform one-time upgrade on-disk changes. spa_version() does not
8083 * reflect the new version this txg, so there must be no changes this
8084 * txg to anything that the upgrade code depends on after it executes.
8085 * Therefore this must be called after dsl_pool_sync() does the sync
8086 * tasks.
8087 */
8088 static void
8089 spa_sync_upgrades(spa_t *spa, dmu_tx_t *tx)
8090 {
8091 if (spa_sync_pass(spa) != 1)
8092 return;
8093
8094 dsl_pool_t *dp = spa->spa_dsl_pool;
8095 rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
8096
8097 if (spa->spa_ubsync.ub_version < SPA_VERSION_ORIGIN &&
8098 spa->spa_uberblock.ub_version >= SPA_VERSION_ORIGIN) {
8099 dsl_pool_create_origin(dp, tx);
8100
8101 /* Keeping the origin open increases spa_minref */
8102 spa->spa_minref += 3;
8103 }
8104
8105 if (spa->spa_ubsync.ub_version < SPA_VERSION_NEXT_CLONES &&
8106 spa->spa_uberblock.ub_version >= SPA_VERSION_NEXT_CLONES) {
8107 dsl_pool_upgrade_clones(dp, tx);
8108 }
8109
8110 if (spa->spa_ubsync.ub_version < SPA_VERSION_DIR_CLONES &&
8111 spa->spa_uberblock.ub_version >= SPA_VERSION_DIR_CLONES) {
8112 dsl_pool_upgrade_dir_clones(dp, tx);
8113
8114 /* Keeping the freedir open increases spa_minref */
8115 spa->spa_minref += 3;
8116 }
8117
8118 if (spa->spa_ubsync.ub_version < SPA_VERSION_FEATURES &&
8119 spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
8120 spa_feature_create_zap_objects(spa, tx);
8121 }
8122
8123 /*
8124 * LZ4_COMPRESS feature's behaviour was changed to activate_on_enable
8125 * when possibility to use lz4 compression for metadata was added
8126 * Old pools that have this feature enabled must be upgraded to have
8127 * this feature active
8128 */
8129 if (spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
8130 boolean_t lz4_en = spa_feature_is_enabled(spa,
8131 SPA_FEATURE_LZ4_COMPRESS);
8132 boolean_t lz4_ac = spa_feature_is_active(spa,
8133 SPA_FEATURE_LZ4_COMPRESS);
8134
8135 if (lz4_en && !lz4_ac)
8136 spa_feature_incr(spa, SPA_FEATURE_LZ4_COMPRESS, tx);
8137 }
8138
8139 /*
8140 * If we haven't written the salt, do so now. Note that the
8141 * feature may not be activated yet, but that's fine since
8142 * the presence of this ZAP entry is backwards compatible.
8143 */
8144 if (zap_contains(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
8145 DMU_POOL_CHECKSUM_SALT) == ENOENT) {
8146 VERIFY0(zap_add(spa->spa_meta_objset,
8147 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CHECKSUM_SALT, 1,
8148 sizeof (spa->spa_cksum_salt.zcs_bytes),
8149 spa->spa_cksum_salt.zcs_bytes, tx));
8150 }
8151
8152 rrw_exit(&dp->dp_config_rwlock, FTAG);
8153 }
8154
8155 static void
8156 vdev_indirect_state_sync_verify(vdev_t *vd)
8157 {
8158 ASSERTV(vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping);
8159 ASSERTV(vdev_indirect_births_t *vib = vd->vdev_indirect_births);
8160
8161 if (vd->vdev_ops == &vdev_indirect_ops) {
8162 ASSERT(vim != NULL);
8163 ASSERT(vib != NULL);
8164 }
8165
8166 uint64_t obsolete_sm_object = 0;
8167 ASSERT0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
8168 if (obsolete_sm_object != 0) {
8169 ASSERT(vd->vdev_obsolete_sm != NULL);
8170 ASSERT(vd->vdev_removing ||
8171 vd->vdev_ops == &vdev_indirect_ops);
8172 ASSERT(vdev_indirect_mapping_num_entries(vim) > 0);
8173 ASSERT(vdev_indirect_mapping_bytes_mapped(vim) > 0);
8174 ASSERT3U(obsolete_sm_object, ==,
8175 space_map_object(vd->vdev_obsolete_sm));
8176 ASSERT3U(vdev_indirect_mapping_bytes_mapped(vim), >=,
8177 space_map_allocated(vd->vdev_obsolete_sm));
8178 }
8179 ASSERT(vd->vdev_obsolete_segments != NULL);
8180
8181 /*
8182 * Since frees / remaps to an indirect vdev can only
8183 * happen in syncing context, the obsolete segments
8184 * tree must be empty when we start syncing.
8185 */
8186 ASSERT0(range_tree_space(vd->vdev_obsolete_segments));
8187 }
8188
8189 /*
8190 * Set the top-level vdev's max queue depth. Evaluate each top-level's
8191 * async write queue depth in case it changed. The max queue depth will
8192 * not change in the middle of syncing out this txg.
8193 */
8194 static void
8195 spa_sync_adjust_vdev_max_queue_depth(spa_t *spa)
8196 {
8197 ASSERT(spa_writeable(spa));
8198
8199 vdev_t *rvd = spa->spa_root_vdev;
8200 uint32_t max_queue_depth = zfs_vdev_async_write_max_active *
8201 zfs_vdev_queue_depth_pct / 100;
8202 metaslab_class_t *normal = spa_normal_class(spa);
8203 metaslab_class_t *special = spa_special_class(spa);
8204 metaslab_class_t *dedup = spa_dedup_class(spa);
8205
8206 uint64_t slots_per_allocator = 0;
8207 for (int c = 0; c < rvd->vdev_children; c++) {
8208 vdev_t *tvd = rvd->vdev_child[c];
8209
8210 metaslab_group_t *mg = tvd->vdev_mg;
8211 if (mg == NULL || !metaslab_group_initialized(mg))
8212 continue;
8213
8214 metaslab_class_t *mc = mg->mg_class;
8215 if (mc != normal && mc != special && mc != dedup)
8216 continue;
8217
8218 /*
8219 * It is safe to do a lock-free check here because only async
8220 * allocations look at mg_max_alloc_queue_depth, and async
8221 * allocations all happen from spa_sync().
8222 */
8223 for (int i = 0; i < spa->spa_alloc_count; i++)
8224 ASSERT0(zfs_refcount_count(
8225 &(mg->mg_alloc_queue_depth[i])));
8226 mg->mg_max_alloc_queue_depth = max_queue_depth;
8227
8228 for (int i = 0; i < spa->spa_alloc_count; i++) {
8229 mg->mg_cur_max_alloc_queue_depth[i] =
8230 zfs_vdev_def_queue_depth;
8231 }
8232 slots_per_allocator += zfs_vdev_def_queue_depth;
8233 }
8234
8235 for (int i = 0; i < spa->spa_alloc_count; i++) {
8236 ASSERT0(zfs_refcount_count(&normal->mc_alloc_slots[i]));
8237 ASSERT0(zfs_refcount_count(&special->mc_alloc_slots[i]));
8238 ASSERT0(zfs_refcount_count(&dedup->mc_alloc_slots[i]));
8239 normal->mc_alloc_max_slots[i] = slots_per_allocator;
8240 special->mc_alloc_max_slots[i] = slots_per_allocator;
8241 dedup->mc_alloc_max_slots[i] = slots_per_allocator;
8242 }
8243 normal->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
8244 special->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
8245 dedup->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
8246 }
8247
8248 static void
8249 spa_sync_condense_indirect(spa_t *spa, dmu_tx_t *tx)
8250 {
8251 ASSERT(spa_writeable(spa));
8252
8253 vdev_t *rvd = spa->spa_root_vdev;
8254 for (int c = 0; c < rvd->vdev_children; c++) {
8255 vdev_t *vd = rvd->vdev_child[c];
8256 vdev_indirect_state_sync_verify(vd);
8257
8258 if (vdev_indirect_should_condense(vd)) {
8259 spa_condense_indirect_start_sync(vd, tx);
8260 break;
8261 }
8262 }
8263 }
8264
8265 static void
8266 spa_sync_iterate_to_convergence(spa_t *spa, dmu_tx_t *tx)
8267 {
8268 objset_t *mos = spa->spa_meta_objset;
8269 dsl_pool_t *dp = spa->spa_dsl_pool;
8270 uint64_t txg = tx->tx_txg;
8271 bplist_t *free_bpl = &spa->spa_free_bplist[txg & TXG_MASK];
8272
8273 do {
8274 int pass = ++spa->spa_sync_pass;
8275
8276 spa_sync_config_object(spa, tx);
8277 spa_sync_aux_dev(spa, &spa->spa_spares, tx,
8278 ZPOOL_CONFIG_SPARES, DMU_POOL_SPARES);
8279 spa_sync_aux_dev(spa, &spa->spa_l2cache, tx,
8280 ZPOOL_CONFIG_L2CACHE, DMU_POOL_L2CACHE);
8281 spa_errlog_sync(spa, txg);
8282 dsl_pool_sync(dp, txg);
8283
8284 if (pass < zfs_sync_pass_deferred_free ||
8285 spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP)) {
8286 /*
8287 * If the log space map feature is active we don't
8288 * care about deferred frees and the deferred bpobj
8289 * as the log space map should effectively have the
8290 * same results (i.e. appending only to one object).
8291 */
8292 spa_sync_frees(spa, free_bpl, tx);
8293 } else {
8294 /*
8295 * We can not defer frees in pass 1, because
8296 * we sync the deferred frees later in pass 1.
8297 */
8298 ASSERT3U(pass, >, 1);
8299 bplist_iterate(free_bpl, bpobj_enqueue_cb,
8300 &spa->spa_deferred_bpobj, tx);
8301 }
8302
8303 ddt_sync(spa, txg);
8304 dsl_scan_sync(dp, tx);
8305 svr_sync(spa, tx);
8306 spa_sync_upgrades(spa, tx);
8307
8308 spa_flush_metaslabs(spa, tx);
8309
8310 vdev_t *vd = NULL;
8311 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, txg))
8312 != NULL)
8313 vdev_sync(vd, txg);
8314
8315 /*
8316 * Note: We need to check if the MOS is dirty because we could
8317 * have marked the MOS dirty without updating the uberblock
8318 * (e.g. if we have sync tasks but no dirty user data). We need
8319 * to check the uberblock's rootbp because it is updated if we
8320 * have synced out dirty data (though in this case the MOS will
8321 * most likely also be dirty due to second order effects, we
8322 * don't want to rely on that here).
8323 */
8324 if (pass == 1 &&
8325 spa->spa_uberblock.ub_rootbp.blk_birth < txg &&
8326 !dmu_objset_is_dirty(mos, txg)) {
8327 /*
8328 * Nothing changed on the first pass, therefore this
8329 * TXG is a no-op. Avoid syncing deferred frees, so
8330 * that we can keep this TXG as a no-op.
8331 */
8332 ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
8333 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
8334 ASSERT(txg_list_empty(&dp->dp_sync_tasks, txg));
8335 ASSERT(txg_list_empty(&dp->dp_early_sync_tasks, txg));
8336 break;
8337 }
8338
8339 spa_sync_deferred_frees(spa, tx);
8340 } while (dmu_objset_is_dirty(mos, txg));
8341 }
8342
8343 /*
8344 * Rewrite the vdev configuration (which includes the uberblock) to
8345 * commit the transaction group.
8346 *
8347 * If there are no dirty vdevs, we sync the uberblock to a few random
8348 * top-level vdevs that are known to be visible in the config cache
8349 * (see spa_vdev_add() for a complete description). If there *are* dirty
8350 * vdevs, sync the uberblock to all vdevs.
8351 */
8352 static void
8353 spa_sync_rewrite_vdev_config(spa_t *spa, dmu_tx_t *tx)
8354 {
8355 vdev_t *rvd = spa->spa_root_vdev;
8356 uint64_t txg = tx->tx_txg;
8357
8358 for (;;) {
8359 int error = 0;
8360
8361 /*
8362 * We hold SCL_STATE to prevent vdev open/close/etc.
8363 * while we're attempting to write the vdev labels.
8364 */
8365 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8366
8367 if (list_is_empty(&spa->spa_config_dirty_list)) {
8368 vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
8369 int svdcount = 0;
8370 int children = rvd->vdev_children;
8371 int c0 = spa_get_random(children);
8372
8373 for (int c = 0; c < children; c++) {
8374 vdev_t *vd =
8375 rvd->vdev_child[(c0 + c) % children];
8376
8377 /* Stop when revisiting the first vdev */
8378 if (c > 0 && svd[0] == vd)
8379 break;
8380
8381 if (vd->vdev_ms_array == 0 ||
8382 vd->vdev_islog ||
8383 !vdev_is_concrete(vd))
8384 continue;
8385
8386 svd[svdcount++] = vd;
8387 if (svdcount == SPA_SYNC_MIN_VDEVS)
8388 break;
8389 }
8390 error = vdev_config_sync(svd, svdcount, txg);
8391 } else {
8392 error = vdev_config_sync(rvd->vdev_child,
8393 rvd->vdev_children, txg);
8394 }
8395
8396 if (error == 0)
8397 spa->spa_last_synced_guid = rvd->vdev_guid;
8398
8399 spa_config_exit(spa, SCL_STATE, FTAG);
8400
8401 if (error == 0)
8402 break;
8403 zio_suspend(spa, NULL, ZIO_SUSPEND_IOERR);
8404 zio_resume_wait(spa);
8405 }
8406 }
8407
8408 /*
8409 * Sync the specified transaction group. New blocks may be dirtied as
8410 * part of the process, so we iterate until it converges.
8411 */
8412 void
8413 spa_sync(spa_t *spa, uint64_t txg)
8414 {
8415 vdev_t *vd = NULL;
8416
8417 VERIFY(spa_writeable(spa));
8418
8419 /*
8420 * Wait for i/os issued in open context that need to complete
8421 * before this txg syncs.
8422 */
8423 (void) zio_wait(spa->spa_txg_zio[txg & TXG_MASK]);
8424 spa->spa_txg_zio[txg & TXG_MASK] = zio_root(spa, NULL, NULL,
8425 ZIO_FLAG_CANFAIL);
8426
8427 /*
8428 * Lock out configuration changes.
8429 */
8430 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
8431
8432 spa->spa_syncing_txg = txg;
8433 spa->spa_sync_pass = 0;
8434
8435 for (int i = 0; i < spa->spa_alloc_count; i++) {
8436 mutex_enter(&spa->spa_alloc_locks[i]);
8437 VERIFY0(avl_numnodes(&spa->spa_alloc_trees[i]));
8438 mutex_exit(&spa->spa_alloc_locks[i]);
8439 }
8440
8441 /*
8442 * If there are any pending vdev state changes, convert them
8443 * into config changes that go out with this transaction group.
8444 */
8445 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8446 while (list_head(&spa->spa_state_dirty_list) != NULL) {
8447 /*
8448 * We need the write lock here because, for aux vdevs,
8449 * calling vdev_config_dirty() modifies sav_config.
8450 * This is ugly and will become unnecessary when we
8451 * eliminate the aux vdev wart by integrating all vdevs
8452 * into the root vdev tree.
8453 */
8454 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
8455 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_WRITER);
8456 while ((vd = list_head(&spa->spa_state_dirty_list)) != NULL) {
8457 vdev_state_clean(vd);
8458 vdev_config_dirty(vd);
8459 }
8460 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
8461 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
8462 }
8463 spa_config_exit(spa, SCL_STATE, FTAG);
8464
8465 dsl_pool_t *dp = spa->spa_dsl_pool;
8466 dmu_tx_t *tx = dmu_tx_create_assigned(dp, txg);
8467
8468 spa->spa_sync_starttime = gethrtime();
8469 taskq_cancel_id(system_delay_taskq, spa->spa_deadman_tqid);
8470 spa->spa_deadman_tqid = taskq_dispatch_delay(system_delay_taskq,
8471 spa_deadman, spa, TQ_SLEEP, ddi_get_lbolt() +
8472 NSEC_TO_TICK(spa->spa_deadman_synctime));
8473
8474 /*
8475 * If we are upgrading to SPA_VERSION_RAIDZ_DEFLATE this txg,
8476 * set spa_deflate if we have no raid-z vdevs.
8477 */
8478 if (spa->spa_ubsync.ub_version < SPA_VERSION_RAIDZ_DEFLATE &&
8479 spa->spa_uberblock.ub_version >= SPA_VERSION_RAIDZ_DEFLATE) {
8480 vdev_t *rvd = spa->spa_root_vdev;
8481
8482 int i;
8483 for (i = 0; i < rvd->vdev_children; i++) {
8484 vd = rvd->vdev_child[i];
8485 if (vd->vdev_deflate_ratio != SPA_MINBLOCKSIZE)
8486 break;
8487 }
8488 if (i == rvd->vdev_children) {
8489 spa->spa_deflate = TRUE;
8490 VERIFY0(zap_add(spa->spa_meta_objset,
8491 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
8492 sizeof (uint64_t), 1, &spa->spa_deflate, tx));
8493 }
8494 }
8495
8496 spa_sync_adjust_vdev_max_queue_depth(spa);
8497
8498 spa_sync_condense_indirect(spa, tx);
8499
8500 spa_sync_iterate_to_convergence(spa, tx);
8501
8502 #ifdef ZFS_DEBUG
8503 if (!list_is_empty(&spa->spa_config_dirty_list)) {
8504 /*
8505 * Make sure that the number of ZAPs for all the vdevs matches
8506 * the number of ZAPs in the per-vdev ZAP list. This only gets
8507 * called if the config is dirty; otherwise there may be
8508 * outstanding AVZ operations that weren't completed in
8509 * spa_sync_config_object.
8510 */
8511 uint64_t all_vdev_zap_entry_count;
8512 ASSERT0(zap_count(spa->spa_meta_objset,
8513 spa->spa_all_vdev_zaps, &all_vdev_zap_entry_count));
8514 ASSERT3U(vdev_count_verify_zaps(spa->spa_root_vdev), ==,
8515 all_vdev_zap_entry_count);
8516 }
8517 #endif
8518
8519 if (spa->spa_vdev_removal != NULL) {
8520 ASSERT0(spa->spa_vdev_removal->svr_bytes_done[txg & TXG_MASK]);
8521 }
8522
8523 spa_sync_rewrite_vdev_config(spa, tx);
8524 dmu_tx_commit(tx);
8525
8526 taskq_cancel_id(system_delay_taskq, spa->spa_deadman_tqid);
8527 spa->spa_deadman_tqid = 0;
8528
8529 /*
8530 * Clear the dirty config list.
8531 */
8532 while ((vd = list_head(&spa->spa_config_dirty_list)) != NULL)
8533 vdev_config_clean(vd);
8534
8535 /*
8536 * Now that the new config has synced transactionally,
8537 * let it become visible to the config cache.
8538 */
8539 if (spa->spa_config_syncing != NULL) {
8540 spa_config_set(spa, spa->spa_config_syncing);
8541 spa->spa_config_txg = txg;
8542 spa->spa_config_syncing = NULL;
8543 }
8544
8545 dsl_pool_sync_done(dp, txg);
8546
8547 for (int i = 0; i < spa->spa_alloc_count; i++) {
8548 mutex_enter(&spa->spa_alloc_locks[i]);
8549 VERIFY0(avl_numnodes(&spa->spa_alloc_trees[i]));
8550 mutex_exit(&spa->spa_alloc_locks[i]);
8551 }
8552
8553 /*
8554 * Update usable space statistics.
8555 */
8556 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)))
8557 != NULL)
8558 vdev_sync_done(vd, txg);
8559 spa_sync_close_syncing_log_sm(spa);
8560
8561 spa_update_dspace(spa);
8562
8563 /*
8564 * It had better be the case that we didn't dirty anything
8565 * since vdev_config_sync().
8566 */
8567 ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
8568 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
8569 ASSERT(txg_list_empty(&spa->spa_vdev_txg_list, txg));
8570
8571 while (zfs_pause_spa_sync)
8572 delay(1);
8573
8574 spa->spa_sync_pass = 0;
8575
8576 /*
8577 * Update the last synced uberblock here. We want to do this at
8578 * the end of spa_sync() so that consumers of spa_last_synced_txg()
8579 * will be guaranteed that all the processing associated with
8580 * that txg has been completed.
8581 */
8582 spa->spa_ubsync = spa->spa_uberblock;
8583 spa_config_exit(spa, SCL_CONFIG, FTAG);
8584
8585 spa_handle_ignored_writes(spa);
8586
8587 /*
8588 * If any async tasks have been requested, kick them off.
8589 */
8590 spa_async_dispatch(spa);
8591 }
8592
8593 /*
8594 * Sync all pools. We don't want to hold the namespace lock across these
8595 * operations, so we take a reference on the spa_t and drop the lock during the
8596 * sync.
8597 */
8598 void
8599 spa_sync_allpools(void)
8600 {
8601 spa_t *spa = NULL;
8602 mutex_enter(&spa_namespace_lock);
8603 while ((spa = spa_next(spa)) != NULL) {
8604 if (spa_state(spa) != POOL_STATE_ACTIVE ||
8605 !spa_writeable(spa) || spa_suspended(spa))
8606 continue;
8607 spa_open_ref(spa, FTAG);
8608 mutex_exit(&spa_namespace_lock);
8609 txg_wait_synced(spa_get_dsl(spa), 0);
8610 mutex_enter(&spa_namespace_lock);
8611 spa_close(spa, FTAG);
8612 }
8613 mutex_exit(&spa_namespace_lock);
8614 }
8615
8616 /*
8617 * ==========================================================================
8618 * Miscellaneous routines
8619 * ==========================================================================
8620 */
8621
8622 /*
8623 * Remove all pools in the system.
8624 */
8625 void
8626 spa_evict_all(void)
8627 {
8628 spa_t *spa;
8629
8630 /*
8631 * Remove all cached state. All pools should be closed now,
8632 * so every spa in the AVL tree should be unreferenced.
8633 */
8634 mutex_enter(&spa_namespace_lock);
8635 while ((spa = spa_next(NULL)) != NULL) {
8636 /*
8637 * Stop async tasks. The async thread may need to detach
8638 * a device that's been replaced, which requires grabbing
8639 * spa_namespace_lock, so we must drop it here.
8640 */
8641 spa_open_ref(spa, FTAG);
8642 mutex_exit(&spa_namespace_lock);
8643 spa_async_suspend(spa);
8644 mutex_enter(&spa_namespace_lock);
8645 spa_close(spa, FTAG);
8646
8647 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
8648 spa_unload(spa);
8649 spa_deactivate(spa);
8650 }
8651 spa_remove(spa);
8652 }
8653 mutex_exit(&spa_namespace_lock);
8654 }
8655
8656 vdev_t *
8657 spa_lookup_by_guid(spa_t *spa, uint64_t guid, boolean_t aux)
8658 {
8659 vdev_t *vd;
8660 int i;
8661
8662 if ((vd = vdev_lookup_by_guid(spa->spa_root_vdev, guid)) != NULL)
8663 return (vd);
8664
8665 if (aux) {
8666 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
8667 vd = spa->spa_l2cache.sav_vdevs[i];
8668 if (vd->vdev_guid == guid)
8669 return (vd);
8670 }
8671
8672 for (i = 0; i < spa->spa_spares.sav_count; i++) {
8673 vd = spa->spa_spares.sav_vdevs[i];
8674 if (vd->vdev_guid == guid)
8675 return (vd);
8676 }
8677 }
8678
8679 return (NULL);
8680 }
8681
8682 void
8683 spa_upgrade(spa_t *spa, uint64_t version)
8684 {
8685 ASSERT(spa_writeable(spa));
8686
8687 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
8688
8689 /*
8690 * This should only be called for a non-faulted pool, and since a
8691 * future version would result in an unopenable pool, this shouldn't be
8692 * possible.
8693 */
8694 ASSERT(SPA_VERSION_IS_SUPPORTED(spa->spa_uberblock.ub_version));
8695 ASSERT3U(version, >=, spa->spa_uberblock.ub_version);
8696
8697 spa->spa_uberblock.ub_version = version;
8698 vdev_config_dirty(spa->spa_root_vdev);
8699
8700 spa_config_exit(spa, SCL_ALL, FTAG);
8701
8702 txg_wait_synced(spa_get_dsl(spa), 0);
8703 }
8704
8705 boolean_t
8706 spa_has_spare(spa_t *spa, uint64_t guid)
8707 {
8708 int i;
8709 uint64_t spareguid;
8710 spa_aux_vdev_t *sav = &spa->spa_spares;
8711
8712 for (i = 0; i < sav->sav_count; i++)
8713 if (sav->sav_vdevs[i]->vdev_guid == guid)
8714 return (B_TRUE);
8715
8716 for (i = 0; i < sav->sav_npending; i++) {
8717 if (nvlist_lookup_uint64(sav->sav_pending[i], ZPOOL_CONFIG_GUID,
8718 &spareguid) == 0 && spareguid == guid)
8719 return (B_TRUE);
8720 }
8721
8722 return (B_FALSE);
8723 }
8724
8725 /*
8726 * Check if a pool has an active shared spare device.
8727 * Note: reference count of an active spare is 2, as a spare and as a replace
8728 */
8729 static boolean_t
8730 spa_has_active_shared_spare(spa_t *spa)
8731 {
8732 int i, refcnt;
8733 uint64_t pool;
8734 spa_aux_vdev_t *sav = &spa->spa_spares;
8735
8736 for (i = 0; i < sav->sav_count; i++) {
8737 if (spa_spare_exists(sav->sav_vdevs[i]->vdev_guid, &pool,
8738 &refcnt) && pool != 0ULL && pool == spa_guid(spa) &&
8739 refcnt > 2)
8740 return (B_TRUE);
8741 }
8742
8743 return (B_FALSE);
8744 }
8745
8746 uint64_t
8747 spa_total_metaslabs(spa_t *spa)
8748 {
8749 vdev_t *rvd = spa->spa_root_vdev;
8750
8751 uint64_t m = 0;
8752 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
8753 vdev_t *vd = rvd->vdev_child[c];
8754 if (!vdev_is_concrete(vd))
8755 continue;
8756 m += vd->vdev_ms_count;
8757 }
8758 return (m);
8759 }
8760
8761 sysevent_t *
8762 spa_event_create(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
8763 {
8764 sysevent_t *ev = NULL;
8765 #ifdef _KERNEL
8766 nvlist_t *resource;
8767
8768 resource = zfs_event_create(spa, vd, FM_SYSEVENT_CLASS, name, hist_nvl);
8769 if (resource) {
8770 ev = kmem_alloc(sizeof (sysevent_t), KM_SLEEP);
8771 ev->resource = resource;
8772 }
8773 #endif
8774 return (ev);
8775 }
8776
8777 void
8778 spa_event_post(sysevent_t *ev)
8779 {
8780 #ifdef _KERNEL
8781 if (ev) {
8782 zfs_zevent_post(ev->resource, NULL, zfs_zevent_post_cb);
8783 kmem_free(ev, sizeof (*ev));
8784 }
8785 #endif
8786 }
8787
8788 /*
8789 * Post a zevent corresponding to the given sysevent. The 'name' must be one
8790 * of the event definitions in sys/sysevent/eventdefs.h. The payload will be
8791 * filled in from the spa and (optionally) the vdev. This doesn't do anything
8792 * in the userland libzpool, as we don't want consumers to misinterpret ztest
8793 * or zdb as real changes.
8794 */
8795 void
8796 spa_event_notify(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
8797 {
8798 spa_event_post(spa_event_create(spa, vd, hist_nvl, name));
8799 }
8800
8801 #if defined(_KERNEL)
8802 /* state manipulation functions */
8803 EXPORT_SYMBOL(spa_open);
8804 EXPORT_SYMBOL(spa_open_rewind);
8805 EXPORT_SYMBOL(spa_get_stats);
8806 EXPORT_SYMBOL(spa_create);
8807 EXPORT_SYMBOL(spa_import);
8808 EXPORT_SYMBOL(spa_tryimport);
8809 EXPORT_SYMBOL(spa_destroy);
8810 EXPORT_SYMBOL(spa_export);
8811 EXPORT_SYMBOL(spa_reset);
8812 EXPORT_SYMBOL(spa_async_request);
8813 EXPORT_SYMBOL(spa_async_suspend);
8814 EXPORT_SYMBOL(spa_async_resume);
8815 EXPORT_SYMBOL(spa_inject_addref);
8816 EXPORT_SYMBOL(spa_inject_delref);
8817 EXPORT_SYMBOL(spa_scan_stat_init);
8818 EXPORT_SYMBOL(spa_scan_get_stats);
8819
8820 /* device maniion */
8821 EXPORT_SYMBOL(spa_vdev_add);
8822 EXPORT_SYMBOL(spa_vdev_attach);
8823 EXPORT_SYMBOL(spa_vdev_detach);
8824 EXPORT_SYMBOL(spa_vdev_setpath);
8825 EXPORT_SYMBOL(spa_vdev_setfru);
8826 EXPORT_SYMBOL(spa_vdev_split_mirror);
8827
8828 /* spare statech is global across all pools) */
8829 EXPORT_SYMBOL(spa_spare_add);
8830 EXPORT_SYMBOL(spa_spare_remove);
8831 EXPORT_SYMBOL(spa_spare_exists);
8832 EXPORT_SYMBOL(spa_spare_activate);
8833
8834 /* L2ARC statech is global across all pools) */
8835 EXPORT_SYMBOL(spa_l2cache_add);
8836 EXPORT_SYMBOL(spa_l2cache_remove);
8837 EXPORT_SYMBOL(spa_l2cache_exists);
8838 EXPORT_SYMBOL(spa_l2cache_activate);
8839 EXPORT_SYMBOL(spa_l2cache_drop);
8840
8841 /* scanning */
8842 EXPORT_SYMBOL(spa_scan);
8843 EXPORT_SYMBOL(spa_scan_stop);
8844
8845 /* spa syncing */
8846 EXPORT_SYMBOL(spa_sync); /* only for DMU use */
8847 EXPORT_SYMBOL(spa_sync_allpools);
8848
8849 /* properties */
8850 EXPORT_SYMBOL(spa_prop_set);
8851 EXPORT_SYMBOL(spa_prop_get);
8852 EXPORT_SYMBOL(spa_prop_clear_bootfs);
8853
8854 /* asynchronous event notification */
8855 EXPORT_SYMBOL(spa_event_notify);
8856 #endif
8857
8858 #if defined(_KERNEL)
8859 module_param(spa_load_verify_maxinflight, int, 0644);
8860 MODULE_PARM_DESC(spa_load_verify_maxinflight,
8861 "Max concurrent traversal I/Os while verifying pool during import -X");
8862
8863 module_param(spa_load_verify_metadata, int, 0644);
8864 MODULE_PARM_DESC(spa_load_verify_metadata,
8865 "Set to traverse metadata on pool import");
8866
8867 module_param(spa_load_verify_data, int, 0644);
8868 MODULE_PARM_DESC(spa_load_verify_data,
8869 "Set to traverse data on pool import");
8870
8871 module_param(spa_load_print_vdev_tree, int, 0644);
8872 MODULE_PARM_DESC(spa_load_print_vdev_tree,
8873 "Print vdev tree to zfs_dbgmsg during pool import");
8874
8875 /* CSTYLED */
8876 module_param(zio_taskq_batch_pct, uint, 0444);
8877 MODULE_PARM_DESC(zio_taskq_batch_pct,
8878 "Percentage of CPUs to run an IO worker thread");
8879
8880 /* BEGIN CSTYLED */
8881 module_param(zfs_max_missing_tvds, ulong, 0644);
8882 MODULE_PARM_DESC(zfs_max_missing_tvds,
8883 "Allow importing pool with up to this number of missing top-level vdevs"
8884 " (in read-only mode)");
8885 /* END CSTYLED */
8886
8887 #endif