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