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