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