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