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