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