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