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