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