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