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