1 /* 2 * CDDL HEADER START 3 * 4 * The contents of this file are subject to the terms of the 5 * Common Development and Distribution License (the "License"). 6 * You may not use this file except in compliance with the License. 7 * 8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE 9 * or http://www.opensolaris.org/os/licensing. 10 * See the License for the specific language governing permissions 11 * and limitations under the License. 12 * 13 * When distributing Covered Code, include this CDDL HEADER in each 14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE. 15 * If applicable, add the following below this CDDL HEADER, with the 16 * fields enclosed by brackets "[]" replaced with your own identifying 17 * information: Portions Copyright [yyyy] [name of copyright owner] 18 * 19 * CDDL HEADER END 20 */ 21 /* 22 * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved. 23 * Copyright (c) 2011, 2018 by Delphix. All rights reserved. 24 * Copyright 2016 Gary Mills 25 * Copyright (c) 2011, 2017 by Delphix. All rights reserved. 26 * Copyright 2017 Joyent, Inc. 27 * Copyright (c) 2017 Datto Inc. 28 */ 29 30 #include <sys/dsl_scan.h> 31 #include <sys/dsl_pool.h> 32 #include <sys/dsl_dataset.h> 33 #include <sys/dsl_prop.h> 34 #include <sys/dsl_dir.h> 35 #include <sys/dsl_synctask.h> 36 #include <sys/dnode.h> 37 #include <sys/dmu_tx.h> 38 #include <sys/dmu_objset.h> 39 #include <sys/arc.h> 40 #include <sys/zap.h> 41 #include <sys/zio.h> 42 #include <sys/zfs_context.h> 43 #include <sys/fs/zfs.h> 44 #include <sys/zfs_znode.h> 45 #include <sys/spa_impl.h> 46 #include <sys/vdev_impl.h> 47 #include <sys/zil_impl.h> 48 #include <sys/zio_checksum.h> 49 #include <sys/ddt.h> 50 #include <sys/sa.h> 51 #include <sys/sa_impl.h> 52 #include <sys/zfeature.h> 53 #include <sys/abd.h> 54 #include <sys/range_tree.h> 55 #ifdef _KERNEL 56 #include <sys/zfs_vfsops.h> 57 #endif 58 59 /* 60 * Grand theory statement on scan queue sorting 61 * 62 * Scanning is implemented by recursively traversing all indirection levels 63 * in an object and reading all blocks referenced from said objects. This 64 * results in us approximately traversing the object from lowest logical 65 * offset to the highest. For best performance, we would want the logical 66 * blocks to be physically contiguous. However, this is frequently not the 67 * case with pools given the allocation patterns of copy-on-write filesystems. 68 * So instead, we put the I/Os into a reordering queue and issue them in a 69 * way that will most benefit physical disks (LBA-order). 70 * 71 * Queue management: 72 * 73 * Ideally, we would want to scan all metadata and queue up all block I/O 74 * prior to starting to issue it, because that allows us to do an optimal 75 * sorting job. This can however consume large amounts of memory. Therefore 76 * we continuously monitor the size of the queues and constrain them to 5% 77 * (zfs_scan_mem_lim_fact) of physmem. If the queues grow larger than this 78 * limit, we clear out a few of the largest extents at the head of the queues 79 * to make room for more scanning. Hopefully, these extents will be fairly 80 * large and contiguous, allowing us to approach sequential I/O throughput 81 * even without a fully sorted tree. 82 * 83 * Metadata scanning takes place in dsl_scan_visit(), which is called from 84 * dsl_scan_sync() every spa_sync(). If we have either fully scanned all 85 * metadata on the pool, or we need to make room in memory because our 86 * queues are too large, dsl_scan_visit() is postponed and 87 * scan_io_queues_run() is called from dsl_scan_sync() instead. This implies 88 * that metadata scanning and queued I/O issuing are mutually exclusive. This 89 * allows us to provide maximum sequential I/O throughput for the majority of 90 * I/O's issued since sequential I/O performance is significantly negatively 91 * impacted if it is interleaved with random I/O. 92 * 93 * Implementation Notes 94 * 95 * One side effect of the queued scanning algorithm is that the scanning code 96 * needs to be notified whenever a block is freed. This is needed to allow 97 * the scanning code to remove these I/Os from the issuing queue. Additionally, 98 * we do not attempt to queue gang blocks to be issued sequentially since this 99 * is very hard to do and would have an extremely limited performance benefit. 100 * Instead, we simply issue gang I/Os as soon as we find them using the legacy 101 * algorithm. 102 * 103 * Backwards compatibility 104 * 105 * This new algorithm is backwards compatible with the legacy on-disk data 106 * structures (and therefore does not require a new feature flag). 107 * Periodically during scanning (see zfs_scan_checkpoint_intval), the scan 108 * will stop scanning metadata (in logical order) and wait for all outstanding 109 * sorted I/O to complete. Once this is done, we write out a checkpoint 110 * bookmark, indicating that we have scanned everything logically before it. 111 * If the pool is imported on a machine without the new sorting algorithm, 112 * the scan simply resumes from the last checkpoint using the legacy algorithm. 113 */ 114 115 typedef int (scan_cb_t)(dsl_pool_t *, const blkptr_t *, 116 const zbookmark_phys_t *); 117 118 static scan_cb_t dsl_scan_scrub_cb; 119 120 static int scan_ds_queue_compare(const void *a, const void *b); 121 static int scan_prefetch_queue_compare(const void *a, const void *b); 122 static void scan_ds_queue_clear(dsl_scan_t *scn); 123 static boolean_t scan_ds_queue_contains(dsl_scan_t *scn, uint64_t dsobj, 124 uint64_t *txg); 125 static void scan_ds_queue_insert(dsl_scan_t *scn, uint64_t dsobj, uint64_t txg); 126 static void scan_ds_queue_remove(dsl_scan_t *scn, uint64_t dsobj); 127 static void scan_ds_queue_sync(dsl_scan_t *scn, dmu_tx_t *tx); 128 129 extern int zfs_vdev_async_write_active_min_dirty_percent; 130 131 /* 132 * By default zfs will check to ensure it is not over the hard memory 133 * limit before each txg. If finer-grained control of this is needed 134 * this value can be set to 1 to enable checking before scanning each 135 * block. 136 */ 137 int zfs_scan_strict_mem_lim = B_FALSE; 138 139 /* 140 * Maximum number of parallelly executing I/Os per top-level vdev. 141 * Tune with care. Very high settings (hundreds) are known to trigger 142 * some firmware bugs and resets on certain SSDs. 143 */ 144 int zfs_top_maxinflight = 32; /* maximum I/Os per top-level */ 145 unsigned int zfs_resilver_delay = 2; /* number of ticks to delay resilver */ 146 unsigned int zfs_scrub_delay = 4; /* number of ticks to delay scrub */ 147 unsigned int zfs_scan_idle = 50; /* idle window in clock ticks */ 148 149 /* 150 * Maximum number of parallelly executed bytes per leaf vdev. We attempt 151 * to strike a balance here between keeping the vdev queues full of I/Os 152 * at all times and not overflowing the queues to cause long latency, 153 * which would cause long txg sync times. No matter what, we will not 154 * overload the drives with I/O, since that is protected by 155 * zfs_vdev_scrub_max_active. 156 */ 157 unsigned long zfs_scan_vdev_limit = 4 << 20; 158 159 int zfs_scan_issue_strategy = 0; 160 int zfs_scan_legacy = B_FALSE; /* don't queue & sort zios, go direct */ 161 uint64_t zfs_scan_max_ext_gap = 2 << 20; /* in bytes */ 162 163 unsigned int zfs_scan_checkpoint_intval = 7200; /* seconds */ 164 #define ZFS_SCAN_CHECKPOINT_INTVAL SEC_TO_TICK(zfs_scan_checkpoint_intval) 165 166 /* 167 * fill_weight is non-tunable at runtime, so we copy it at module init from 168 * zfs_scan_fill_weight. Runtime adjustments to zfs_scan_fill_weight would 169 * break queue sorting. 170 */ 171 uint64_t zfs_scan_fill_weight = 3; 172 static uint64_t fill_weight; 173 174 /* See dsl_scan_should_clear() for details on the memory limit tunables */ 175 uint64_t zfs_scan_mem_lim_min = 16 << 20; /* bytes */ 176 uint64_t zfs_scan_mem_lim_soft_max = 128 << 20; /* bytes */ 177 int zfs_scan_mem_lim_fact = 20; /* fraction of physmem */ 178 int zfs_scan_mem_lim_soft_fact = 20; /* fraction of mem lim above */ 179 180 unsigned int zfs_scrub_min_time_ms = 1000; /* min millisecs to scrub per txg */ 181 unsigned int zfs_free_min_time_ms = 1000; /* min millisecs to free per txg */ 182 /* min millisecs to obsolete per txg */ 183 unsigned int zfs_obsolete_min_time_ms = 500; 184 /* min millisecs to resilver per txg */ 185 unsigned int zfs_resilver_min_time_ms = 3000; 186 int zfs_scan_suspend_progress = 0; /* set to prevent scans from progressing */ 187 boolean_t zfs_no_scrub_io = B_FALSE; /* set to disable scrub i/o */ 188 boolean_t zfs_no_scrub_prefetch = B_FALSE; /* set to disable scrub prefetch */ 189 enum ddt_class zfs_scrub_ddt_class_max = DDT_CLASS_DUPLICATE; 190 /* max number of blocks to free in a single TXG */ 191 uint64_t zfs_async_block_max_blocks = UINT64_MAX; 192 193 int zfs_resilver_disable_defer = 0; /* set to disable resilver deferring */ 194 195 /* 196 * We wait a few txgs after importing a pool to begin scanning so that 197 * the import / mounting code isn't held up by scrub / resilver IO. 198 * Unfortunately, it is a bit difficult to determine exactly how long 199 * this will take since userspace will trigger fs mounts asynchronously 200 * and the kernel will create zvol minors asynchronously. As a result, 201 * the value provided here is a bit arbitrary, but represents a 202 * reasonable estimate of how many txgs it will take to finish fully 203 * importing a pool 204 */ 205 #define SCAN_IMPORT_WAIT_TXGS 5 206 207 208 #define DSL_SCAN_IS_SCRUB_RESILVER(scn) \ 209 ((scn)->scn_phys.scn_func == POOL_SCAN_SCRUB || \ 210 (scn)->scn_phys.scn_func == POOL_SCAN_RESILVER) 211 212 extern int zfs_txg_timeout; 213 214 /* 215 * Enable/disable the processing of the free_bpobj object. 216 */ 217 boolean_t zfs_free_bpobj_enabled = B_TRUE; 218 219 /* the order has to match pool_scan_type */ 220 static scan_cb_t *scan_funcs[POOL_SCAN_FUNCS] = { 221 NULL, 222 dsl_scan_scrub_cb, /* POOL_SCAN_SCRUB */ 223 dsl_scan_scrub_cb, /* POOL_SCAN_RESILVER */ 224 }; 225 226 /* In core node for the scn->scn_queue. Represents a dataset to be scanned */ 227 typedef struct { 228 uint64_t sds_dsobj; 229 uint64_t sds_txg; 230 avl_node_t sds_node; 231 } scan_ds_t; 232 233 /* 234 * This controls what conditions are placed on dsl_scan_sync_state(): 235 * SYNC_OPTIONAL) write out scn_phys iff scn_bytes_pending == 0 236 * SYNC_MANDATORY) write out scn_phys always. scn_bytes_pending must be 0. 237 * SYNC_CACHED) if scn_bytes_pending == 0, write out scn_phys. Otherwise 238 * write out the scn_phys_cached version. 239 * See dsl_scan_sync_state for details. 240 */ 241 typedef enum { 242 SYNC_OPTIONAL, 243 SYNC_MANDATORY, 244 SYNC_CACHED 245 } state_sync_type_t; 246 247 /* 248 * This struct represents the minimum information needed to reconstruct a 249 * zio for sequential scanning. This is useful because many of these will 250 * accumulate in the sequential IO queues before being issued, so saving 251 * memory matters here. 252 */ 253 typedef struct scan_io { 254 /* fields from blkptr_t */ 255 uint64_t sio_blk_prop; 256 uint64_t sio_phys_birth; 257 uint64_t sio_birth; 258 zio_cksum_t sio_cksum; 259 uint32_t sio_nr_dvas; 260 261 /* fields from zio_t */ 262 uint32_t sio_flags; 263 zbookmark_phys_t sio_zb; 264 265 /* members for queue sorting */ 266 union { 267 avl_node_t sio_addr_node; /* link into issuing queue */ 268 list_node_t sio_list_node; /* link for issuing to disk */ 269 } sio_nodes; 270 271 /* 272 * There may be up to SPA_DVAS_PER_BP DVAs here from the bp, 273 * depending on how many were in the original bp. Only the 274 * first DVA is really used for sorting and issuing purposes. 275 * The other DVAs (if provided) simply exist so that the zio 276 * layer can find additional copies to repair from in the 277 * event of an error. This array must go at the end of the 278 * struct to allow this for the variable number of elements. 279 */ 280 dva_t sio_dva[0]; 281 } scan_io_t; 282 283 #define SIO_SET_OFFSET(sio, x) DVA_SET_OFFSET(&(sio)->sio_dva[0], x) 284 #define SIO_SET_ASIZE(sio, x) DVA_SET_ASIZE(&(sio)->sio_dva[0], x) 285 #define SIO_GET_OFFSET(sio) DVA_GET_OFFSET(&(sio)->sio_dva[0]) 286 #define SIO_GET_ASIZE(sio) DVA_GET_ASIZE(&(sio)->sio_dva[0]) 287 #define SIO_GET_END_OFFSET(sio) \ 288 (SIO_GET_OFFSET(sio) + SIO_GET_ASIZE(sio)) 289 #define SIO_GET_MUSED(sio) \ 290 (sizeof (scan_io_t) + ((sio)->sio_nr_dvas * sizeof (dva_t))) 291 292 struct dsl_scan_io_queue { 293 dsl_scan_t *q_scn; /* associated dsl_scan_t */ 294 vdev_t *q_vd; /* top-level vdev that this queue represents */ 295 296 /* trees used for sorting I/Os and extents of I/Os */ 297 range_tree_t *q_exts_by_addr; 298 avl_tree_t q_exts_by_size; 299 avl_tree_t q_sios_by_addr; 300 uint64_t q_sio_memused; 301 302 /* members for zio rate limiting */ 303 uint64_t q_maxinflight_bytes; 304 uint64_t q_inflight_bytes; 305 kcondvar_t q_zio_cv; /* used under vd->vdev_scan_io_queue_lock */ 306 307 /* per txg statistics */ 308 uint64_t q_total_seg_size_this_txg; 309 uint64_t q_segs_this_txg; 310 uint64_t q_total_zio_size_this_txg; 311 uint64_t q_zios_this_txg; 312 }; 313 314 /* private data for dsl_scan_prefetch_cb() */ 315 typedef struct scan_prefetch_ctx { 316 zfs_refcount_t spc_refcnt; /* refcount for memory management */ 317 dsl_scan_t *spc_scn; /* dsl_scan_t for the pool */ 318 boolean_t spc_root; /* is this prefetch for an objset? */ 319 uint8_t spc_indblkshift; /* dn_indblkshift of current dnode */ 320 uint16_t spc_datablkszsec; /* dn_idatablkszsec of current dnode */ 321 } scan_prefetch_ctx_t; 322 323 /* private data for dsl_scan_prefetch() */ 324 typedef struct scan_prefetch_issue_ctx { 325 avl_node_t spic_avl_node; /* link into scn->scn_prefetch_queue */ 326 scan_prefetch_ctx_t *spic_spc; /* spc for the callback */ 327 blkptr_t spic_bp; /* bp to prefetch */ 328 zbookmark_phys_t spic_zb; /* bookmark to prefetch */ 329 } scan_prefetch_issue_ctx_t; 330 331 static void scan_exec_io(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags, 332 const zbookmark_phys_t *zb, dsl_scan_io_queue_t *queue); 333 static void scan_io_queue_insert_impl(dsl_scan_io_queue_t *queue, 334 scan_io_t *sio); 335 336 static dsl_scan_io_queue_t *scan_io_queue_create(vdev_t *vd); 337 static void scan_io_queues_destroy(dsl_scan_t *scn); 338 339 static kmem_cache_t *sio_cache[SPA_DVAS_PER_BP]; 340 341 /* sio->sio_nr_dvas must be set so we know which cache to free from */ 342 static void 343 sio_free(scan_io_t *sio) 344 { 345 ASSERT3U(sio->sio_nr_dvas, >, 0); 346 ASSERT3U(sio->sio_nr_dvas, <=, SPA_DVAS_PER_BP); 347 348 kmem_cache_free(sio_cache[sio->sio_nr_dvas - 1], sio); 349 } 350 351 /* It is up to the caller to set sio->sio_nr_dvas for freeing */ 352 static scan_io_t * 353 sio_alloc(unsigned short nr_dvas) 354 { 355 ASSERT3U(nr_dvas, >, 0); 356 ASSERT3U(nr_dvas, <=, SPA_DVAS_PER_BP); 357 358 return (kmem_cache_alloc(sio_cache[nr_dvas - 1], KM_SLEEP)); 359 } 360 361 void 362 scan_init(void) 363 { 364 /* 365 * This is used in ext_size_compare() to weight segments 366 * based on how sparse they are. This cannot be changed 367 * mid-scan and the tree comparison functions don't currently 368 * have a mechansim for passing additional context to the 369 * compare functions. Thus we store this value globally and 370 * we only allow it to be set at module intiailization time 371 */ 372 fill_weight = zfs_scan_fill_weight; 373 374 for (int i = 0; i < SPA_DVAS_PER_BP; i++) { 375 char name[36]; 376 377 (void) sprintf(name, "sio_cache_%d", i); 378 sio_cache[i] = kmem_cache_create(name, 379 (sizeof (scan_io_t) + ((i + 1) * sizeof (dva_t))), 380 0, NULL, NULL, NULL, NULL, NULL, 0); 381 } 382 } 383 384 void 385 scan_fini(void) 386 { 387 for (int i = 0; i < SPA_DVAS_PER_BP; i++) { 388 kmem_cache_destroy(sio_cache[i]); 389 } 390 } 391 392 static inline boolean_t 393 dsl_scan_is_running(const dsl_scan_t *scn) 394 { 395 return (scn->scn_phys.scn_state == DSS_SCANNING); 396 } 397 398 boolean_t 399 dsl_scan_resilvering(dsl_pool_t *dp) 400 { 401 return (dsl_scan_is_running(dp->dp_scan) && 402 dp->dp_scan->scn_phys.scn_func == POOL_SCAN_RESILVER); 403 } 404 405 static inline void 406 sio2bp(const scan_io_t *sio, blkptr_t *bp) 407 { 408 bzero(bp, sizeof (*bp)); 409 bp->blk_prop = sio->sio_blk_prop; 410 bp->blk_phys_birth = sio->sio_phys_birth; 411 bp->blk_birth = sio->sio_birth; 412 bp->blk_fill = 1; /* we always only work with data pointers */ 413 bp->blk_cksum = sio->sio_cksum; 414 415 ASSERT3U(sio->sio_nr_dvas, >, 0); 416 ASSERT3U(sio->sio_nr_dvas, <=, SPA_DVAS_PER_BP); 417 418 bcopy(sio->sio_dva, bp->blk_dva, sio->sio_nr_dvas * sizeof (dva_t)); 419 } 420 421 static inline void 422 bp2sio(const blkptr_t *bp, scan_io_t *sio, int dva_i) 423 { 424 sio->sio_blk_prop = bp->blk_prop; 425 sio->sio_phys_birth = bp->blk_phys_birth; 426 sio->sio_birth = bp->blk_birth; 427 sio->sio_cksum = bp->blk_cksum; 428 sio->sio_nr_dvas = BP_GET_NDVAS(bp); 429 430 /* 431 * Copy the DVAs to the sio. We need all copies of the block so 432 * that the self healing code can use the alternate copies if the 433 * first is corrupted. We want the DVA at index dva_i to be first 434 * in the sio since this is the primary one that we want to issue. 435 */ 436 for (int i = 0, j = dva_i; i < sio->sio_nr_dvas; i++, j++) { 437 sio->sio_dva[i] = bp->blk_dva[j % sio->sio_nr_dvas]; 438 } 439 } 440 441 int 442 dsl_scan_init(dsl_pool_t *dp, uint64_t txg) 443 { 444 int err; 445 dsl_scan_t *scn; 446 spa_t *spa = dp->dp_spa; 447 uint64_t f; 448 449 scn = dp->dp_scan = kmem_zalloc(sizeof (dsl_scan_t), KM_SLEEP); 450 scn->scn_dp = dp; 451 452 /* 453 * It's possible that we're resuming a scan after a reboot so 454 * make sure that the scan_async_destroying flag is initialized 455 * appropriately. 456 */ 457 ASSERT(!scn->scn_async_destroying); 458 scn->scn_async_destroying = spa_feature_is_active(dp->dp_spa, 459 SPA_FEATURE_ASYNC_DESTROY); 460 461 avl_create(&scn->scn_queue, scan_ds_queue_compare, sizeof (scan_ds_t), 462 offsetof(scan_ds_t, sds_node)); 463 avl_create(&scn->scn_prefetch_queue, scan_prefetch_queue_compare, 464 sizeof (scan_prefetch_issue_ctx_t), 465 offsetof(scan_prefetch_issue_ctx_t, spic_avl_node)); 466 467 err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT, 468 "scrub_func", sizeof (uint64_t), 1, &f); 469 if (err == 0) { 470 /* 471 * There was an old-style scrub in progress. Restart a 472 * new-style scrub from the beginning. 473 */ 474 scn->scn_restart_txg = txg; 475 zfs_dbgmsg("old-style scrub was in progress; " 476 "restarting new-style scrub in txg %llu", 477 (longlong_t)scn->scn_restart_txg); 478 479 /* 480 * Load the queue obj from the old location so that it 481 * can be freed by dsl_scan_done(). 482 */ 483 (void) zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT, 484 "scrub_queue", sizeof (uint64_t), 1, 485 &scn->scn_phys.scn_queue_obj); 486 } else { 487 err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT, 488 DMU_POOL_SCAN, sizeof (uint64_t), SCAN_PHYS_NUMINTS, 489 &scn->scn_phys); 490 if (err == ENOENT) 491 return (0); 492 else if (err) 493 return (err); 494 495 /* 496 * We might be restarting after a reboot, so jump the issued 497 * counter to how far we've scanned. We know we're consistent 498 * up to here. 499 */ 500 scn->scn_issued_before_pass = scn->scn_phys.scn_examined; 501 502 if (dsl_scan_is_running(scn) && 503 spa_prev_software_version(dp->dp_spa) < SPA_VERSION_SCAN) { 504 /* 505 * A new-type scrub was in progress on an old 506 * pool, and the pool was accessed by old 507 * software. Restart from the beginning, since 508 * the old software may have changed the pool in 509 * the meantime. 510 */ 511 scn->scn_restart_txg = txg; 512 zfs_dbgmsg("new-style scrub was modified " 513 "by old software; restarting in txg %llu", 514 (longlong_t)scn->scn_restart_txg); 515 } 516 } 517 518 bcopy(&scn->scn_phys, &scn->scn_phys_cached, sizeof (scn->scn_phys)); 519 520 /* reload the queue into the in-core state */ 521 if (scn->scn_phys.scn_queue_obj != 0) { 522 zap_cursor_t zc; 523 zap_attribute_t za; 524 525 for (zap_cursor_init(&zc, dp->dp_meta_objset, 526 scn->scn_phys.scn_queue_obj); 527 zap_cursor_retrieve(&zc, &za) == 0; 528 (void) zap_cursor_advance(&zc)) { 529 scan_ds_queue_insert(scn, 530 zfs_strtonum(za.za_name, NULL), 531 za.za_first_integer); 532 } 533 zap_cursor_fini(&zc); 534 } 535 536 spa_scan_stat_init(spa); 537 return (0); 538 } 539 540 void 541 dsl_scan_fini(dsl_pool_t *dp) 542 { 543 if (dp->dp_scan != NULL) { 544 dsl_scan_t *scn = dp->dp_scan; 545 546 if (scn->scn_taskq != NULL) 547 taskq_destroy(scn->scn_taskq); 548 scan_ds_queue_clear(scn); 549 avl_destroy(&scn->scn_queue); 550 avl_destroy(&scn->scn_prefetch_queue); 551 552 kmem_free(dp->dp_scan, sizeof (dsl_scan_t)); 553 dp->dp_scan = NULL; 554 } 555 } 556 557 static boolean_t 558 dsl_scan_restarting(dsl_scan_t *scn, dmu_tx_t *tx) 559 { 560 return (scn->scn_restart_txg != 0 && 561 scn->scn_restart_txg <= tx->tx_txg); 562 } 563 564 boolean_t 565 dsl_scan_scrubbing(const dsl_pool_t *dp) 566 { 567 dsl_scan_phys_t *scn_phys = &dp->dp_scan->scn_phys; 568 569 return (scn_phys->scn_state == DSS_SCANNING && 570 scn_phys->scn_func == POOL_SCAN_SCRUB); 571 } 572 573 boolean_t 574 dsl_scan_is_paused_scrub(const dsl_scan_t *scn) 575 { 576 return (dsl_scan_scrubbing(scn->scn_dp) && 577 scn->scn_phys.scn_flags & DSF_SCRUB_PAUSED); 578 } 579 580 /* 581 * Writes out a persistent dsl_scan_phys_t record to the pool directory. 582 * Because we can be running in the block sorting algorithm, we do not always 583 * want to write out the record, only when it is "safe" to do so. This safety 584 * condition is achieved by making sure that the sorting queues are empty 585 * (scn_bytes_pending == 0). When this condition is not true, the sync'd state 586 * is inconsistent with how much actual scanning progress has been made. The 587 * kind of sync to be performed is specified by the sync_type argument. If the 588 * sync is optional, we only sync if the queues are empty. If the sync is 589 * mandatory, we do a hard ASSERT to make sure that the queues are empty. The 590 * third possible state is a "cached" sync. This is done in response to: 591 * 1) The dataset that was in the last sync'd dsl_scan_phys_t having been 592 * destroyed, so we wouldn't be able to restart scanning from it. 593 * 2) The snapshot that was in the last sync'd dsl_scan_phys_t having been 594 * superseded by a newer snapshot. 595 * 3) The dataset that was in the last sync'd dsl_scan_phys_t having been 596 * swapped with its clone. 597 * In all cases, a cached sync simply rewrites the last record we've written, 598 * just slightly modified. For the modifications that are performed to the 599 * last written dsl_scan_phys_t, see dsl_scan_ds_destroyed, 600 * dsl_scan_ds_snapshotted and dsl_scan_ds_clone_swapped. 601 */ 602 static void 603 dsl_scan_sync_state(dsl_scan_t *scn, dmu_tx_t *tx, state_sync_type_t sync_type) 604 { 605 int i; 606 spa_t *spa = scn->scn_dp->dp_spa; 607 608 ASSERT(sync_type != SYNC_MANDATORY || scn->scn_bytes_pending == 0); 609 if (scn->scn_bytes_pending == 0) { 610 for (i = 0; i < spa->spa_root_vdev->vdev_children; i++) { 611 vdev_t *vd = spa->spa_root_vdev->vdev_child[i]; 612 dsl_scan_io_queue_t *q = vd->vdev_scan_io_queue; 613 614 if (q == NULL) 615 continue; 616 617 mutex_enter(&vd->vdev_scan_io_queue_lock); 618 ASSERT3P(avl_first(&q->q_sios_by_addr), ==, NULL); 619 ASSERT3P(avl_first(&q->q_exts_by_size), ==, NULL); 620 ASSERT3P(range_tree_first(q->q_exts_by_addr), ==, NULL); 621 mutex_exit(&vd->vdev_scan_io_queue_lock); 622 } 623 624 if (scn->scn_phys.scn_queue_obj != 0) 625 scan_ds_queue_sync(scn, tx); 626 VERIFY0(zap_update(scn->scn_dp->dp_meta_objset, 627 DMU_POOL_DIRECTORY_OBJECT, 628 DMU_POOL_SCAN, sizeof (uint64_t), SCAN_PHYS_NUMINTS, 629 &scn->scn_phys, tx)); 630 bcopy(&scn->scn_phys, &scn->scn_phys_cached, 631 sizeof (scn->scn_phys)); 632 633 if (scn->scn_checkpointing) 634 zfs_dbgmsg("finish scan checkpoint"); 635 636 scn->scn_checkpointing = B_FALSE; 637 scn->scn_last_checkpoint = ddi_get_lbolt(); 638 } else if (sync_type == SYNC_CACHED) { 639 VERIFY0(zap_update(scn->scn_dp->dp_meta_objset, 640 DMU_POOL_DIRECTORY_OBJECT, 641 DMU_POOL_SCAN, sizeof (uint64_t), SCAN_PHYS_NUMINTS, 642 &scn->scn_phys_cached, tx)); 643 } 644 } 645 646 /* ARGSUSED */ 647 static int 648 dsl_scan_setup_check(void *arg, dmu_tx_t *tx) 649 { 650 dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan; 651 652 if (dsl_scan_is_running(scn)) 653 return (SET_ERROR(EBUSY)); 654 655 return (0); 656 } 657 658 static void 659 dsl_scan_setup_sync(void *arg, dmu_tx_t *tx) 660 { 661 dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan; 662 pool_scan_func_t *funcp = arg; 663 dmu_object_type_t ot = 0; 664 dsl_pool_t *dp = scn->scn_dp; 665 spa_t *spa = dp->dp_spa; 666 667 ASSERT(!dsl_scan_is_running(scn)); 668 ASSERT(*funcp > POOL_SCAN_NONE && *funcp < POOL_SCAN_FUNCS); 669 bzero(&scn->scn_phys, sizeof (scn->scn_phys)); 670 scn->scn_phys.scn_func = *funcp; 671 scn->scn_phys.scn_state = DSS_SCANNING; 672 scn->scn_phys.scn_min_txg = 0; 673 scn->scn_phys.scn_max_txg = tx->tx_txg; 674 scn->scn_phys.scn_ddt_class_max = DDT_CLASSES - 1; /* the entire DDT */ 675 scn->scn_phys.scn_start_time = gethrestime_sec(); 676 scn->scn_phys.scn_errors = 0; 677 scn->scn_phys.scn_to_examine = spa->spa_root_vdev->vdev_stat.vs_alloc; 678 scn->scn_issued_before_pass = 0; 679 scn->scn_restart_txg = 0; 680 scn->scn_done_txg = 0; 681 scn->scn_last_checkpoint = 0; 682 scn->scn_checkpointing = B_FALSE; 683 spa_scan_stat_init(spa); 684 685 if (DSL_SCAN_IS_SCRUB_RESILVER(scn)) { 686 scn->scn_phys.scn_ddt_class_max = zfs_scrub_ddt_class_max; 687 688 /* rewrite all disk labels */ 689 vdev_config_dirty(spa->spa_root_vdev); 690 691 if (vdev_resilver_needed(spa->spa_root_vdev, 692 &scn->scn_phys.scn_min_txg, &scn->scn_phys.scn_max_txg)) { 693 spa_event_notify(spa, NULL, NULL, 694 ESC_ZFS_RESILVER_START); 695 } else { 696 spa_event_notify(spa, NULL, NULL, ESC_ZFS_SCRUB_START); 697 } 698 699 spa->spa_scrub_started = B_TRUE; 700 /* 701 * If this is an incremental scrub, limit the DDT scrub phase 702 * to just the auto-ditto class (for correctness); the rest 703 * of the scrub should go faster using top-down pruning. 704 */ 705 if (scn->scn_phys.scn_min_txg > TXG_INITIAL) 706 scn->scn_phys.scn_ddt_class_max = DDT_CLASS_DITTO; 707 708 } 709 710 /* back to the generic stuff */ 711 712 if (dp->dp_blkstats == NULL) { 713 dp->dp_blkstats = 714 kmem_alloc(sizeof (zfs_all_blkstats_t), KM_SLEEP); 715 mutex_init(&dp->dp_blkstats->zab_lock, NULL, 716 MUTEX_DEFAULT, NULL); 717 } 718 bzero(&dp->dp_blkstats->zab_type, sizeof (dp->dp_blkstats->zab_type)); 719 720 if (spa_version(spa) < SPA_VERSION_DSL_SCRUB) 721 ot = DMU_OT_ZAP_OTHER; 722 723 scn->scn_phys.scn_queue_obj = zap_create(dp->dp_meta_objset, 724 ot ? ot : DMU_OT_SCAN_QUEUE, DMU_OT_NONE, 0, tx); 725 726 bcopy(&scn->scn_phys, &scn->scn_phys_cached, sizeof (scn->scn_phys)); 727 728 dsl_scan_sync_state(scn, tx, SYNC_MANDATORY); 729 730 spa_history_log_internal(spa, "scan setup", tx, 731 "func=%u mintxg=%llu maxtxg=%llu", 732 *funcp, scn->scn_phys.scn_min_txg, scn->scn_phys.scn_max_txg); 733 } 734 735 /* 736 * Called by the ZFS_IOC_POOL_SCAN ioctl to start a scrub or resilver. 737 * Can also be called to resume a paused scrub. 738 */ 739 int 740 dsl_scan(dsl_pool_t *dp, pool_scan_func_t func) 741 { 742 spa_t *spa = dp->dp_spa; 743 dsl_scan_t *scn = dp->dp_scan; 744 745 /* 746 * Purge all vdev caches and probe all devices. We do this here 747 * rather than in sync context because this requires a writer lock 748 * on the spa_config lock, which we can't do from sync context. The 749 * spa_scrub_reopen flag indicates that vdev_open() should not 750 * attempt to start another scrub. 751 */ 752 spa_vdev_state_enter(spa, SCL_NONE); 753 spa->spa_scrub_reopen = B_TRUE; 754 vdev_reopen(spa->spa_root_vdev); 755 spa->spa_scrub_reopen = B_FALSE; 756 (void) spa_vdev_state_exit(spa, NULL, 0); 757 758 if (func == POOL_SCAN_RESILVER) { 759 dsl_resilver_restart(spa->spa_dsl_pool, 0); 760 return (0); 761 } 762 763 if (func == POOL_SCAN_SCRUB && dsl_scan_is_paused_scrub(scn)) { 764 /* got scrub start cmd, resume paused scrub */ 765 int err = dsl_scrub_set_pause_resume(scn->scn_dp, 766 POOL_SCRUB_NORMAL); 767 if (err == 0) { 768 spa_event_notify(spa, NULL, NULL, ESC_ZFS_SCRUB_RESUME); 769 return (ECANCELED); 770 } 771 return (SET_ERROR(err)); 772 } 773 774 return (dsl_sync_task(spa_name(spa), dsl_scan_setup_check, 775 dsl_scan_setup_sync, &func, 0, ZFS_SPACE_CHECK_EXTRA_RESERVED)); 776 } 777 778 /* 779 * Sets the resilver defer flag to B_FALSE on all leaf devs under vd. Returns 780 * B_TRUE if we have devices that need to be resilvered and are available to 781 * accept resilver I/Os. 782 */ 783 static boolean_t 784 dsl_scan_clear_deferred(vdev_t *vd, dmu_tx_t *tx) 785 { 786 boolean_t resilver_needed = B_FALSE; 787 spa_t *spa = vd->vdev_spa; 788 789 for (int c = 0; c < vd->vdev_children; c++) { 790 resilver_needed |= 791 dsl_scan_clear_deferred(vd->vdev_child[c], tx); 792 } 793 794 if (vd == spa->spa_root_vdev && 795 spa_feature_is_active(spa, SPA_FEATURE_RESILVER_DEFER)) { 796 spa_feature_decr(spa, SPA_FEATURE_RESILVER_DEFER, tx); 797 vdev_config_dirty(vd); 798 spa->spa_resilver_deferred = B_FALSE; 799 return (resilver_needed); 800 } 801 802 if (!vdev_is_concrete(vd) || vd->vdev_aux || 803 !vd->vdev_ops->vdev_op_leaf) 804 return (resilver_needed); 805 806 if (vd->vdev_resilver_deferred) 807 vd->vdev_resilver_deferred = B_FALSE; 808 809 return (!vdev_is_dead(vd) && !vd->vdev_offline && 810 vdev_resilver_needed(vd, NULL, NULL)); 811 } 812 813 /* ARGSUSED */ 814 static void 815 dsl_scan_done(dsl_scan_t *scn, boolean_t complete, dmu_tx_t *tx) 816 { 817 static const char *old_names[] = { 818 "scrub_bookmark", 819 "scrub_ddt_bookmark", 820 "scrub_ddt_class_max", 821 "scrub_queue", 822 "scrub_min_txg", 823 "scrub_max_txg", 824 "scrub_func", 825 "scrub_errors", 826 NULL 827 }; 828 829 dsl_pool_t *dp = scn->scn_dp; 830 spa_t *spa = dp->dp_spa; 831 int i; 832 833 /* Remove any remnants of an old-style scrub. */ 834 for (i = 0; old_names[i]; i++) { 835 (void) zap_remove(dp->dp_meta_objset, 836 DMU_POOL_DIRECTORY_OBJECT, old_names[i], tx); 837 } 838 839 if (scn->scn_phys.scn_queue_obj != 0) { 840 VERIFY0(dmu_object_free(dp->dp_meta_objset, 841 scn->scn_phys.scn_queue_obj, tx)); 842 scn->scn_phys.scn_queue_obj = 0; 843 } 844 scan_ds_queue_clear(scn); 845 846 scn->scn_phys.scn_flags &= ~DSF_SCRUB_PAUSED; 847 848 /* 849 * If we were "restarted" from a stopped state, don't bother 850 * with anything else. 851 */ 852 if (!dsl_scan_is_running(scn)) { 853 ASSERT(!scn->scn_is_sorted); 854 return; 855 } 856 857 if (scn->scn_is_sorted) { 858 scan_io_queues_destroy(scn); 859 scn->scn_is_sorted = B_FALSE; 860 861 if (scn->scn_taskq != NULL) { 862 taskq_destroy(scn->scn_taskq); 863 scn->scn_taskq = NULL; 864 } 865 } 866 867 scn->scn_phys.scn_state = complete ? DSS_FINISHED : DSS_CANCELED; 868 869 if (dsl_scan_restarting(scn, tx)) 870 spa_history_log_internal(spa, "scan aborted, restarting", tx, 871 "errors=%llu", spa_get_errlog_size(spa)); 872 else if (!complete) 873 spa_history_log_internal(spa, "scan cancelled", tx, 874 "errors=%llu", spa_get_errlog_size(spa)); 875 else 876 spa_history_log_internal(spa, "scan done", tx, 877 "errors=%llu", spa_get_errlog_size(spa)); 878 879 if (DSL_SCAN_IS_SCRUB_RESILVER(scn)) { 880 spa->spa_scrub_started = B_FALSE; 881 spa->spa_scrub_active = B_FALSE; 882 883 /* 884 * If the scrub/resilver completed, update all DTLs to 885 * reflect this. Whether it succeeded or not, vacate 886 * all temporary scrub DTLs. 887 * 888 * As the scrub does not currently support traversing 889 * data that have been freed but are part of a checkpoint, 890 * we don't mark the scrub as done in the DTLs as faults 891 * may still exist in those vdevs. 892 */ 893 if (complete && 894 !spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) { 895 vdev_dtl_reassess(spa->spa_root_vdev, tx->tx_txg, 896 scn->scn_phys.scn_max_txg, B_TRUE); 897 898 spa_event_notify(spa, NULL, NULL, 899 scn->scn_phys.scn_min_txg ? 900 ESC_ZFS_RESILVER_FINISH : ESC_ZFS_SCRUB_FINISH); 901 } else { 902 vdev_dtl_reassess(spa->spa_root_vdev, tx->tx_txg, 903 0, B_TRUE); 904 } 905 spa_errlog_rotate(spa); 906 907 /* 908 * We may have finished replacing a device. 909 * Let the async thread assess this and handle the detach. 910 */ 911 spa_async_request(spa, SPA_ASYNC_RESILVER_DONE); 912 913 /* 914 * Clear any deferred_resilver flags in the config. 915 * If there are drives that need resilvering, kick 916 * off an asynchronous request to start resilver. 917 * dsl_scan_clear_deferred() may update the config 918 * before the resilver can restart. In the event of 919 * a crash during this period, the spa loading code 920 * will find the drives that need to be resilvered 921 * when the machine reboots and start the resilver then. 922 */ 923 boolean_t resilver_needed = 924 dsl_scan_clear_deferred(spa->spa_root_vdev, tx); 925 if (resilver_needed) { 926 spa_history_log_internal(spa, 927 "starting deferred resilver", tx, 928 "errors=%llu", spa_get_errlog_size(spa)); 929 spa_async_request(spa, SPA_ASYNC_RESILVER); 930 } 931 } 932 933 scn->scn_phys.scn_end_time = gethrestime_sec(); 934 935 ASSERT(!dsl_scan_is_running(scn)); 936 } 937 938 /* ARGSUSED */ 939 static int 940 dsl_scan_cancel_check(void *arg, dmu_tx_t *tx) 941 { 942 dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan; 943 944 if (!dsl_scan_is_running(scn)) 945 return (SET_ERROR(ENOENT)); 946 return (0); 947 } 948 949 /* ARGSUSED */ 950 static void 951 dsl_scan_cancel_sync(void *arg, dmu_tx_t *tx) 952 { 953 dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan; 954 955 dsl_scan_done(scn, B_FALSE, tx); 956 dsl_scan_sync_state(scn, tx, SYNC_MANDATORY); 957 spa_event_notify(scn->scn_dp->dp_spa, NULL, NULL, ESC_ZFS_SCRUB_ABORT); 958 } 959 960 int 961 dsl_scan_cancel(dsl_pool_t *dp) 962 { 963 return (dsl_sync_task(spa_name(dp->dp_spa), dsl_scan_cancel_check, 964 dsl_scan_cancel_sync, NULL, 3, ZFS_SPACE_CHECK_RESERVED)); 965 } 966 967 static int 968 dsl_scrub_pause_resume_check(void *arg, dmu_tx_t *tx) 969 { 970 pool_scrub_cmd_t *cmd = arg; 971 dsl_pool_t *dp = dmu_tx_pool(tx); 972 dsl_scan_t *scn = dp->dp_scan; 973 974 if (*cmd == POOL_SCRUB_PAUSE) { 975 /* can't pause a scrub when there is no in-progress scrub */ 976 if (!dsl_scan_scrubbing(dp)) 977 return (SET_ERROR(ENOENT)); 978 979 /* can't pause a paused scrub */ 980 if (dsl_scan_is_paused_scrub(scn)) 981 return (SET_ERROR(EBUSY)); 982 } else if (*cmd != POOL_SCRUB_NORMAL) { 983 return (SET_ERROR(ENOTSUP)); 984 } 985 986 return (0); 987 } 988 989 static void 990 dsl_scrub_pause_resume_sync(void *arg, dmu_tx_t *tx) 991 { 992 pool_scrub_cmd_t *cmd = arg; 993 dsl_pool_t *dp = dmu_tx_pool(tx); 994 spa_t *spa = dp->dp_spa; 995 dsl_scan_t *scn = dp->dp_scan; 996 997 if (*cmd == POOL_SCRUB_PAUSE) { 998 /* can't pause a scrub when there is no in-progress scrub */ 999 spa->spa_scan_pass_scrub_pause = gethrestime_sec(); 1000 scn->scn_phys.scn_flags |= DSF_SCRUB_PAUSED; 1001 scn->scn_phys_cached.scn_flags |= DSF_SCRUB_PAUSED; 1002 dsl_scan_sync_state(scn, tx, SYNC_CACHED); 1003 spa_event_notify(spa, NULL, NULL, ESC_ZFS_SCRUB_PAUSED); 1004 } else { 1005 ASSERT3U(*cmd, ==, POOL_SCRUB_NORMAL); 1006 if (dsl_scan_is_paused_scrub(scn)) { 1007 /* 1008 * We need to keep track of how much time we spend 1009 * paused per pass so that we can adjust the scrub rate 1010 * shown in the output of 'zpool status' 1011 */ 1012 spa->spa_scan_pass_scrub_spent_paused += 1013 gethrestime_sec() - spa->spa_scan_pass_scrub_pause; 1014 spa->spa_scan_pass_scrub_pause = 0; 1015 scn->scn_phys.scn_flags &= ~DSF_SCRUB_PAUSED; 1016 scn->scn_phys_cached.scn_flags &= ~DSF_SCRUB_PAUSED; 1017 dsl_scan_sync_state(scn, tx, SYNC_CACHED); 1018 } 1019 } 1020 } 1021 1022 /* 1023 * Set scrub pause/resume state if it makes sense to do so 1024 */ 1025 int 1026 dsl_scrub_set_pause_resume(const dsl_pool_t *dp, pool_scrub_cmd_t cmd) 1027 { 1028 return (dsl_sync_task(spa_name(dp->dp_spa), 1029 dsl_scrub_pause_resume_check, dsl_scrub_pause_resume_sync, &cmd, 3, 1030 ZFS_SPACE_CHECK_RESERVED)); 1031 } 1032 1033 1034 /* start a new scan, or restart an existing one. */ 1035 void 1036 dsl_resilver_restart(dsl_pool_t *dp, uint64_t txg) 1037 { 1038 if (txg == 0) { 1039 dmu_tx_t *tx; 1040 tx = dmu_tx_create_dd(dp->dp_mos_dir); 1041 VERIFY(0 == dmu_tx_assign(tx, TXG_WAIT)); 1042 1043 txg = dmu_tx_get_txg(tx); 1044 dp->dp_scan->scn_restart_txg = txg; 1045 dmu_tx_commit(tx); 1046 } else { 1047 dp->dp_scan->scn_restart_txg = txg; 1048 } 1049 zfs_dbgmsg("restarting resilver txg=%llu", txg); 1050 } 1051 1052 void 1053 dsl_free(dsl_pool_t *dp, uint64_t txg, const blkptr_t *bp) 1054 { 1055 zio_free(dp->dp_spa, txg, bp); 1056 } 1057 1058 void 1059 dsl_free_sync(zio_t *pio, dsl_pool_t *dp, uint64_t txg, const blkptr_t *bpp) 1060 { 1061 ASSERT(dsl_pool_sync_context(dp)); 1062 zio_nowait(zio_free_sync(pio, dp->dp_spa, txg, bpp, pio->io_flags)); 1063 } 1064 1065 static int 1066 scan_ds_queue_compare(const void *a, const void *b) 1067 { 1068 const scan_ds_t *sds_a = a, *sds_b = b; 1069 1070 if (sds_a->sds_dsobj < sds_b->sds_dsobj) 1071 return (-1); 1072 if (sds_a->sds_dsobj == sds_b->sds_dsobj) 1073 return (0); 1074 return (1); 1075 } 1076 1077 static void 1078 scan_ds_queue_clear(dsl_scan_t *scn) 1079 { 1080 void *cookie = NULL; 1081 scan_ds_t *sds; 1082 while ((sds = avl_destroy_nodes(&scn->scn_queue, &cookie)) != NULL) { 1083 kmem_free(sds, sizeof (*sds)); 1084 } 1085 } 1086 1087 static boolean_t 1088 scan_ds_queue_contains(dsl_scan_t *scn, uint64_t dsobj, uint64_t *txg) 1089 { 1090 scan_ds_t srch, *sds; 1091 1092 srch.sds_dsobj = dsobj; 1093 sds = avl_find(&scn->scn_queue, &srch, NULL); 1094 if (sds != NULL && txg != NULL) 1095 *txg = sds->sds_txg; 1096 return (sds != NULL); 1097 } 1098 1099 static void 1100 scan_ds_queue_insert(dsl_scan_t *scn, uint64_t dsobj, uint64_t txg) 1101 { 1102 scan_ds_t *sds; 1103 avl_index_t where; 1104 1105 sds = kmem_zalloc(sizeof (*sds), KM_SLEEP); 1106 sds->sds_dsobj = dsobj; 1107 sds->sds_txg = txg; 1108 1109 VERIFY3P(avl_find(&scn->scn_queue, sds, &where), ==, NULL); 1110 avl_insert(&scn->scn_queue, sds, where); 1111 } 1112 1113 static void 1114 scan_ds_queue_remove(dsl_scan_t *scn, uint64_t dsobj) 1115 { 1116 scan_ds_t srch, *sds; 1117 1118 srch.sds_dsobj = dsobj; 1119 1120 sds = avl_find(&scn->scn_queue, &srch, NULL); 1121 VERIFY(sds != NULL); 1122 avl_remove(&scn->scn_queue, sds); 1123 kmem_free(sds, sizeof (*sds)); 1124 } 1125 1126 static void 1127 scan_ds_queue_sync(dsl_scan_t *scn, dmu_tx_t *tx) 1128 { 1129 dsl_pool_t *dp = scn->scn_dp; 1130 spa_t *spa = dp->dp_spa; 1131 dmu_object_type_t ot = (spa_version(spa) >= SPA_VERSION_DSL_SCRUB) ? 1132 DMU_OT_SCAN_QUEUE : DMU_OT_ZAP_OTHER; 1133 1134 ASSERT0(scn->scn_bytes_pending); 1135 ASSERT(scn->scn_phys.scn_queue_obj != 0); 1136 1137 VERIFY0(dmu_object_free(dp->dp_meta_objset, 1138 scn->scn_phys.scn_queue_obj, tx)); 1139 scn->scn_phys.scn_queue_obj = zap_create(dp->dp_meta_objset, ot, 1140 DMU_OT_NONE, 0, tx); 1141 for (scan_ds_t *sds = avl_first(&scn->scn_queue); 1142 sds != NULL; sds = AVL_NEXT(&scn->scn_queue, sds)) { 1143 VERIFY0(zap_add_int_key(dp->dp_meta_objset, 1144 scn->scn_phys.scn_queue_obj, sds->sds_dsobj, 1145 sds->sds_txg, tx)); 1146 } 1147 } 1148 1149 /* 1150 * Computes the memory limit state that we're currently in. A sorted scan 1151 * needs quite a bit of memory to hold the sorting queue, so we need to 1152 * reasonably constrain the size so it doesn't impact overall system 1153 * performance. We compute two limits: 1154 * 1) Hard memory limit: if the amount of memory used by the sorting 1155 * queues on a pool gets above this value, we stop the metadata 1156 * scanning portion and start issuing the queued up and sorted 1157 * I/Os to reduce memory usage. 1158 * This limit is calculated as a fraction of physmem (by default 5%). 1159 * We constrain the lower bound of the hard limit to an absolute 1160 * minimum of zfs_scan_mem_lim_min (default: 16 MiB). We also constrain 1161 * the upper bound to 5% of the total pool size - no chance we'll 1162 * ever need that much memory, but just to keep the value in check. 1163 * 2) Soft memory limit: once we hit the hard memory limit, we start 1164 * issuing I/O to reduce queue memory usage, but we don't want to 1165 * completely empty out the queues, since we might be able to find I/Os 1166 * that will fill in the gaps of our non-sequential IOs at some point 1167 * in the future. So we stop the issuing of I/Os once the amount of 1168 * memory used drops below the soft limit (at which point we stop issuing 1169 * I/O and start scanning metadata again). 1170 * 1171 * This limit is calculated by subtracting a fraction of the hard 1172 * limit from the hard limit. By default this fraction is 5%, so 1173 * the soft limit is 95% of the hard limit. We cap the size of the 1174 * difference between the hard and soft limits at an absolute 1175 * maximum of zfs_scan_mem_lim_soft_max (default: 128 MiB) - this is 1176 * sufficient to not cause too frequent switching between the 1177 * metadata scan and I/O issue (even at 2k recordsize, 128 MiB's 1178 * worth of queues is about 1.2 GiB of on-pool data, so scanning 1179 * that should take at least a decent fraction of a second). 1180 */ 1181 static boolean_t 1182 dsl_scan_should_clear(dsl_scan_t *scn) 1183 { 1184 vdev_t *rvd = scn->scn_dp->dp_spa->spa_root_vdev; 1185 uint64_t mlim_hard, mlim_soft, mused; 1186 uint64_t alloc = metaslab_class_get_alloc(spa_normal_class( 1187 scn->scn_dp->dp_spa)); 1188 1189 mlim_hard = MAX((physmem / zfs_scan_mem_lim_fact) * PAGESIZE, 1190 zfs_scan_mem_lim_min); 1191 mlim_hard = MIN(mlim_hard, alloc / 20); 1192 mlim_soft = mlim_hard - MIN(mlim_hard / zfs_scan_mem_lim_soft_fact, 1193 zfs_scan_mem_lim_soft_max); 1194 mused = 0; 1195 for (uint64_t i = 0; i < rvd->vdev_children; i++) { 1196 vdev_t *tvd = rvd->vdev_child[i]; 1197 dsl_scan_io_queue_t *queue; 1198 1199 mutex_enter(&tvd->vdev_scan_io_queue_lock); 1200 queue = tvd->vdev_scan_io_queue; 1201 if (queue != NULL) { 1202 /* # extents in exts_by_size = # in exts_by_addr */ 1203 mused += avl_numnodes(&queue->q_exts_by_size) * 1204 sizeof (range_seg_t) + queue->q_sio_memused; 1205 } 1206 mutex_exit(&tvd->vdev_scan_io_queue_lock); 1207 } 1208 1209 dprintf("current scan memory usage: %llu bytes\n", (longlong_t)mused); 1210 1211 if (mused == 0) 1212 ASSERT0(scn->scn_bytes_pending); 1213 1214 /* 1215 * If we are above our hard limit, we need to clear out memory. 1216 * If we are below our soft limit, we need to accumulate sequential IOs. 1217 * Otherwise, we should keep doing whatever we are currently doing. 1218 */ 1219 if (mused >= mlim_hard) 1220 return (B_TRUE); 1221 else if (mused < mlim_soft) 1222 return (B_FALSE); 1223 else 1224 return (scn->scn_clearing); 1225 } 1226 1227 static boolean_t 1228 dsl_scan_check_suspend(dsl_scan_t *scn, const zbookmark_phys_t *zb) 1229 { 1230 /* we never skip user/group accounting objects */ 1231 if (zb && (int64_t)zb->zb_object < 0) 1232 return (B_FALSE); 1233 1234 if (scn->scn_suspending) 1235 return (B_TRUE); /* we're already suspending */ 1236 1237 if (!ZB_IS_ZERO(&scn->scn_phys.scn_bookmark)) 1238 return (B_FALSE); /* we're resuming */ 1239 1240 /* We only know how to resume from level-0 blocks. */ 1241 if (zb && zb->zb_level != 0) 1242 return (B_FALSE); 1243 1244 /* 1245 * We suspend if: 1246 * - we have scanned for at least the minimum time (default 1 sec 1247 * for scrub, 3 sec for resilver), and either we have sufficient 1248 * dirty data that we are starting to write more quickly 1249 * (default 30%), or someone is explicitly waiting for this txg 1250 * to complete. 1251 * or 1252 * - the spa is shutting down because this pool is being exported 1253 * or the machine is rebooting. 1254 * or 1255 * - the scan queue has reached its memory use limit 1256 */ 1257 hrtime_t curr_time_ns = gethrtime(); 1258 uint64_t scan_time_ns = curr_time_ns - scn->scn_sync_start_time; 1259 uint64_t sync_time_ns = curr_time_ns - 1260 scn->scn_dp->dp_spa->spa_sync_starttime; 1261 1262 int dirty_pct = scn->scn_dp->dp_dirty_total * 100 / zfs_dirty_data_max; 1263 int mintime = (scn->scn_phys.scn_func == POOL_SCAN_RESILVER) ? 1264 zfs_resilver_min_time_ms : zfs_scrub_min_time_ms; 1265 1266 if ((NSEC2MSEC(scan_time_ns) > mintime && 1267 (dirty_pct >= zfs_vdev_async_write_active_min_dirty_percent || 1268 txg_sync_waiting(scn->scn_dp) || 1269 NSEC2SEC(sync_time_ns) >= zfs_txg_timeout)) || 1270 spa_shutting_down(scn->scn_dp->dp_spa) || 1271 (zfs_scan_strict_mem_lim && dsl_scan_should_clear(scn))) { 1272 if (zb) { 1273 dprintf("suspending at bookmark %llx/%llx/%llx/%llx\n", 1274 (longlong_t)zb->zb_objset, 1275 (longlong_t)zb->zb_object, 1276 (longlong_t)zb->zb_level, 1277 (longlong_t)zb->zb_blkid); 1278 scn->scn_phys.scn_bookmark = *zb; 1279 } else { 1280 dsl_scan_phys_t *scnp = &scn->scn_phys; 1281 1282 dprintf("suspending at DDT bookmark " 1283 "%llx/%llx/%llx/%llx\n", 1284 (longlong_t)scnp->scn_ddt_bookmark.ddb_class, 1285 (longlong_t)scnp->scn_ddt_bookmark.ddb_type, 1286 (longlong_t)scnp->scn_ddt_bookmark.ddb_checksum, 1287 (longlong_t)scnp->scn_ddt_bookmark.ddb_cursor); 1288 } 1289 scn->scn_suspending = B_TRUE; 1290 return (B_TRUE); 1291 } 1292 return (B_FALSE); 1293 } 1294 1295 typedef struct zil_scan_arg { 1296 dsl_pool_t *zsa_dp; 1297 zil_header_t *zsa_zh; 1298 } zil_scan_arg_t; 1299 1300 /* ARGSUSED */ 1301 static int 1302 dsl_scan_zil_block(zilog_t *zilog, blkptr_t *bp, void *arg, uint64_t claim_txg) 1303 { 1304 zil_scan_arg_t *zsa = arg; 1305 dsl_pool_t *dp = zsa->zsa_dp; 1306 dsl_scan_t *scn = dp->dp_scan; 1307 zil_header_t *zh = zsa->zsa_zh; 1308 zbookmark_phys_t zb; 1309 1310 if (BP_IS_HOLE(bp) || bp->blk_birth <= scn->scn_phys.scn_cur_min_txg) 1311 return (0); 1312 1313 /* 1314 * One block ("stubby") can be allocated a long time ago; we 1315 * want to visit that one because it has been allocated 1316 * (on-disk) even if it hasn't been claimed (even though for 1317 * scrub there's nothing to do to it). 1318 */ 1319 if (claim_txg == 0 && bp->blk_birth >= spa_min_claim_txg(dp->dp_spa)) 1320 return (0); 1321 1322 SET_BOOKMARK(&zb, zh->zh_log.blk_cksum.zc_word[ZIL_ZC_OBJSET], 1323 ZB_ZIL_OBJECT, ZB_ZIL_LEVEL, bp->blk_cksum.zc_word[ZIL_ZC_SEQ]); 1324 1325 VERIFY(0 == scan_funcs[scn->scn_phys.scn_func](dp, bp, &zb)); 1326 return (0); 1327 } 1328 1329 /* ARGSUSED */ 1330 static int 1331 dsl_scan_zil_record(zilog_t *zilog, lr_t *lrc, void *arg, uint64_t claim_txg) 1332 { 1333 if (lrc->lrc_txtype == TX_WRITE) { 1334 zil_scan_arg_t *zsa = arg; 1335 dsl_pool_t *dp = zsa->zsa_dp; 1336 dsl_scan_t *scn = dp->dp_scan; 1337 zil_header_t *zh = zsa->zsa_zh; 1338 lr_write_t *lr = (lr_write_t *)lrc; 1339 blkptr_t *bp = &lr->lr_blkptr; 1340 zbookmark_phys_t zb; 1341 1342 if (BP_IS_HOLE(bp) || 1343 bp->blk_birth <= scn->scn_phys.scn_cur_min_txg) 1344 return (0); 1345 1346 /* 1347 * birth can be < claim_txg if this record's txg is 1348 * already txg sync'ed (but this log block contains 1349 * other records that are not synced) 1350 */ 1351 if (claim_txg == 0 || bp->blk_birth < claim_txg) 1352 return (0); 1353 1354 SET_BOOKMARK(&zb, zh->zh_log.blk_cksum.zc_word[ZIL_ZC_OBJSET], 1355 lr->lr_foid, ZB_ZIL_LEVEL, 1356 lr->lr_offset / BP_GET_LSIZE(bp)); 1357 1358 VERIFY(0 == scan_funcs[scn->scn_phys.scn_func](dp, bp, &zb)); 1359 } 1360 return (0); 1361 } 1362 1363 static void 1364 dsl_scan_zil(dsl_pool_t *dp, zil_header_t *zh) 1365 { 1366 uint64_t claim_txg = zh->zh_claim_txg; 1367 zil_scan_arg_t zsa = { dp, zh }; 1368 zilog_t *zilog; 1369 1370 ASSERT(spa_writeable(dp->dp_spa)); 1371 1372 /* 1373 * We only want to visit blocks that have been claimed 1374 * but not yet replayed. 1375 */ 1376 if (claim_txg == 0) 1377 return; 1378 1379 zilog = zil_alloc(dp->dp_meta_objset, zh); 1380 1381 (void) zil_parse(zilog, dsl_scan_zil_block, dsl_scan_zil_record, &zsa, 1382 claim_txg); 1383 1384 zil_free(zilog); 1385 } 1386 1387 /* 1388 * We compare scan_prefetch_issue_ctx_t's based on their bookmarks. The idea 1389 * here is to sort the AVL tree by the order each block will be needed. 1390 */ 1391 static int 1392 scan_prefetch_queue_compare(const void *a, const void *b) 1393 { 1394 const scan_prefetch_issue_ctx_t *spic_a = a, *spic_b = b; 1395 const scan_prefetch_ctx_t *spc_a = spic_a->spic_spc; 1396 const scan_prefetch_ctx_t *spc_b = spic_b->spic_spc; 1397 1398 return (zbookmark_compare(spc_a->spc_datablkszsec, 1399 spc_a->spc_indblkshift, spc_b->spc_datablkszsec, 1400 spc_b->spc_indblkshift, &spic_a->spic_zb, &spic_b->spic_zb)); 1401 } 1402 1403 static void 1404 scan_prefetch_ctx_rele(scan_prefetch_ctx_t *spc, void *tag) 1405 { 1406 if (zfs_refcount_remove(&spc->spc_refcnt, tag) == 0) { 1407 zfs_refcount_destroy(&spc->spc_refcnt); 1408 kmem_free(spc, sizeof (scan_prefetch_ctx_t)); 1409 } 1410 } 1411 1412 static scan_prefetch_ctx_t * 1413 scan_prefetch_ctx_create(dsl_scan_t *scn, dnode_phys_t *dnp, void *tag) 1414 { 1415 scan_prefetch_ctx_t *spc; 1416 1417 spc = kmem_alloc(sizeof (scan_prefetch_ctx_t), KM_SLEEP); 1418 zfs_refcount_create(&spc->spc_refcnt); 1419 zfs_refcount_add(&spc->spc_refcnt, tag); 1420 spc->spc_scn = scn; 1421 if (dnp != NULL) { 1422 spc->spc_datablkszsec = dnp->dn_datablkszsec; 1423 spc->spc_indblkshift = dnp->dn_indblkshift; 1424 spc->spc_root = B_FALSE; 1425 } else { 1426 spc->spc_datablkszsec = 0; 1427 spc->spc_indblkshift = 0; 1428 spc->spc_root = B_TRUE; 1429 } 1430 1431 return (spc); 1432 } 1433 1434 static void 1435 scan_prefetch_ctx_add_ref(scan_prefetch_ctx_t *spc, void *tag) 1436 { 1437 zfs_refcount_add(&spc->spc_refcnt, tag); 1438 } 1439 1440 static boolean_t 1441 dsl_scan_check_prefetch_resume(scan_prefetch_ctx_t *spc, 1442 const zbookmark_phys_t *zb) 1443 { 1444 zbookmark_phys_t *last_zb = &spc->spc_scn->scn_prefetch_bookmark; 1445 dnode_phys_t tmp_dnp; 1446 dnode_phys_t *dnp = (spc->spc_root) ? NULL : &tmp_dnp; 1447 1448 if (zb->zb_objset != last_zb->zb_objset) 1449 return (B_TRUE); 1450 if ((int64_t)zb->zb_object < 0) 1451 return (B_FALSE); 1452 1453 tmp_dnp.dn_datablkszsec = spc->spc_datablkszsec; 1454 tmp_dnp.dn_indblkshift = spc->spc_indblkshift; 1455 1456 if (zbookmark_subtree_completed(dnp, zb, last_zb)) 1457 return (B_TRUE); 1458 1459 return (B_FALSE); 1460 } 1461 1462 static void 1463 dsl_scan_prefetch(scan_prefetch_ctx_t *spc, blkptr_t *bp, zbookmark_phys_t *zb) 1464 { 1465 avl_index_t idx; 1466 dsl_scan_t *scn = spc->spc_scn; 1467 spa_t *spa = scn->scn_dp->dp_spa; 1468 scan_prefetch_issue_ctx_t *spic; 1469 1470 if (zfs_no_scrub_prefetch) 1471 return; 1472 1473 if (BP_IS_HOLE(bp) || bp->blk_birth <= scn->scn_phys.scn_cur_min_txg || 1474 (BP_GET_LEVEL(bp) == 0 && BP_GET_TYPE(bp) != DMU_OT_DNODE && 1475 BP_GET_TYPE(bp) != DMU_OT_OBJSET)) 1476 return; 1477 1478 if (dsl_scan_check_prefetch_resume(spc, zb)) 1479 return; 1480 1481 scan_prefetch_ctx_add_ref(spc, scn); 1482 spic = kmem_alloc(sizeof (scan_prefetch_issue_ctx_t), KM_SLEEP); 1483 spic->spic_spc = spc; 1484 spic->spic_bp = *bp; 1485 spic->spic_zb = *zb; 1486 1487 /* 1488 * Add the IO to the queue of blocks to prefetch. This allows us to 1489 * prioritize blocks that we will need first for the main traversal 1490 * thread. 1491 */ 1492 mutex_enter(&spa->spa_scrub_lock); 1493 if (avl_find(&scn->scn_prefetch_queue, spic, &idx) != NULL) { 1494 /* this block is already queued for prefetch */ 1495 kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t)); 1496 scan_prefetch_ctx_rele(spc, scn); 1497 mutex_exit(&spa->spa_scrub_lock); 1498 return; 1499 } 1500 1501 avl_insert(&scn->scn_prefetch_queue, spic, idx); 1502 cv_broadcast(&spa->spa_scrub_io_cv); 1503 mutex_exit(&spa->spa_scrub_lock); 1504 } 1505 1506 static void 1507 dsl_scan_prefetch_dnode(dsl_scan_t *scn, dnode_phys_t *dnp, 1508 uint64_t objset, uint64_t object) 1509 { 1510 int i; 1511 zbookmark_phys_t zb; 1512 scan_prefetch_ctx_t *spc; 1513 1514 if (dnp->dn_nblkptr == 0 && !(dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR)) 1515 return; 1516 1517 SET_BOOKMARK(&zb, objset, object, 0, 0); 1518 1519 spc = scan_prefetch_ctx_create(scn, dnp, FTAG); 1520 1521 for (i = 0; i < dnp->dn_nblkptr; i++) { 1522 zb.zb_level = BP_GET_LEVEL(&dnp->dn_blkptr[i]); 1523 zb.zb_blkid = i; 1524 dsl_scan_prefetch(spc, &dnp->dn_blkptr[i], &zb); 1525 } 1526 1527 if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) { 1528 zb.zb_level = 0; 1529 zb.zb_blkid = DMU_SPILL_BLKID; 1530 dsl_scan_prefetch(spc, &dnp->dn_spill, &zb); 1531 } 1532 1533 scan_prefetch_ctx_rele(spc, FTAG); 1534 } 1535 1536 void 1537 dsl_scan_prefetch_cb(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp, 1538 arc_buf_t *buf, void *private) 1539 { 1540 scan_prefetch_ctx_t *spc = private; 1541 dsl_scan_t *scn = spc->spc_scn; 1542 spa_t *spa = scn->scn_dp->dp_spa; 1543 1544 /* broadcast that the IO has completed for rate limitting purposes */ 1545 mutex_enter(&spa->spa_scrub_lock); 1546 ASSERT3U(spa->spa_scrub_inflight, >=, BP_GET_PSIZE(bp)); 1547 spa->spa_scrub_inflight -= BP_GET_PSIZE(bp); 1548 cv_broadcast(&spa->spa_scrub_io_cv); 1549 mutex_exit(&spa->spa_scrub_lock); 1550 1551 /* if there was an error or we are done prefetching, just cleanup */ 1552 if (buf == NULL || scn->scn_suspending) 1553 goto out; 1554 1555 if (BP_GET_LEVEL(bp) > 0) { 1556 int i; 1557 blkptr_t *cbp; 1558 int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT; 1559 zbookmark_phys_t czb; 1560 1561 for (i = 0, cbp = buf->b_data; i < epb; i++, cbp++) { 1562 SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object, 1563 zb->zb_level - 1, zb->zb_blkid * epb + i); 1564 dsl_scan_prefetch(spc, cbp, &czb); 1565 } 1566 } else if (BP_GET_TYPE(bp) == DMU_OT_DNODE) { 1567 dnode_phys_t *cdnp = buf->b_data; 1568 int i; 1569 int epb = BP_GET_LSIZE(bp) >> DNODE_SHIFT; 1570 1571 for (i = 0, cdnp = buf->b_data; i < epb; 1572 i += cdnp->dn_extra_slots + 1, 1573 cdnp += cdnp->dn_extra_slots + 1) { 1574 dsl_scan_prefetch_dnode(scn, cdnp, 1575 zb->zb_objset, zb->zb_blkid * epb + i); 1576 } 1577 } else if (BP_GET_TYPE(bp) == DMU_OT_OBJSET) { 1578 objset_phys_t *osp = buf->b_data; 1579 1580 dsl_scan_prefetch_dnode(scn, &osp->os_meta_dnode, 1581 zb->zb_objset, DMU_META_DNODE_OBJECT); 1582 1583 if (OBJSET_BUF_HAS_USERUSED(buf)) { 1584 dsl_scan_prefetch_dnode(scn, 1585 &osp->os_groupused_dnode, zb->zb_objset, 1586 DMU_GROUPUSED_OBJECT); 1587 dsl_scan_prefetch_dnode(scn, 1588 &osp->os_userused_dnode, zb->zb_objset, 1589 DMU_USERUSED_OBJECT); 1590 } 1591 } 1592 1593 out: 1594 if (buf != NULL) 1595 arc_buf_destroy(buf, private); 1596 scan_prefetch_ctx_rele(spc, scn); 1597 } 1598 1599 /* ARGSUSED */ 1600 static void 1601 dsl_scan_prefetch_thread(void *arg) 1602 { 1603 dsl_scan_t *scn = arg; 1604 spa_t *spa = scn->scn_dp->dp_spa; 1605 vdev_t *rvd = spa->spa_root_vdev; 1606 uint64_t maxinflight = rvd->vdev_children * zfs_top_maxinflight; 1607 scan_prefetch_issue_ctx_t *spic; 1608 1609 /* loop until we are told to stop */ 1610 while (!scn->scn_prefetch_stop) { 1611 arc_flags_t flags = ARC_FLAG_NOWAIT | 1612 ARC_FLAG_PRESCIENT_PREFETCH | ARC_FLAG_PREFETCH; 1613 int zio_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCAN_THREAD; 1614 1615 mutex_enter(&spa->spa_scrub_lock); 1616 1617 /* 1618 * Wait until we have an IO to issue and are not above our 1619 * maximum in flight limit. 1620 */ 1621 while (!scn->scn_prefetch_stop && 1622 (avl_numnodes(&scn->scn_prefetch_queue) == 0 || 1623 spa->spa_scrub_inflight >= scn->scn_maxinflight_bytes)) { 1624 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock); 1625 } 1626 1627 /* recheck if we should stop since we waited for the cv */ 1628 if (scn->scn_prefetch_stop) { 1629 mutex_exit(&spa->spa_scrub_lock); 1630 break; 1631 } 1632 1633 /* remove the prefetch IO from the tree */ 1634 spic = avl_first(&scn->scn_prefetch_queue); 1635 spa->spa_scrub_inflight += BP_GET_PSIZE(&spic->spic_bp); 1636 avl_remove(&scn->scn_prefetch_queue, spic); 1637 1638 mutex_exit(&spa->spa_scrub_lock); 1639 1640 /* issue the prefetch asynchronously */ 1641 (void) arc_read(scn->scn_zio_root, scn->scn_dp->dp_spa, 1642 &spic->spic_bp, dsl_scan_prefetch_cb, spic->spic_spc, 1643 ZIO_PRIORITY_SCRUB, zio_flags, &flags, &spic->spic_zb); 1644 1645 kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t)); 1646 } 1647 1648 ASSERT(scn->scn_prefetch_stop); 1649 1650 /* free any prefetches we didn't get to complete */ 1651 mutex_enter(&spa->spa_scrub_lock); 1652 while ((spic = avl_first(&scn->scn_prefetch_queue)) != NULL) { 1653 avl_remove(&scn->scn_prefetch_queue, spic); 1654 scan_prefetch_ctx_rele(spic->spic_spc, scn); 1655 kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t)); 1656 } 1657 ASSERT0(avl_numnodes(&scn->scn_prefetch_queue)); 1658 mutex_exit(&spa->spa_scrub_lock); 1659 } 1660 1661 static boolean_t 1662 dsl_scan_check_resume(dsl_scan_t *scn, const dnode_phys_t *dnp, 1663 const zbookmark_phys_t *zb) 1664 { 1665 /* 1666 * We never skip over user/group accounting objects (obj<0) 1667 */ 1668 if (!ZB_IS_ZERO(&scn->scn_phys.scn_bookmark) && 1669 (int64_t)zb->zb_object >= 0) { 1670 /* 1671 * If we already visited this bp & everything below (in 1672 * a prior txg sync), don't bother doing it again. 1673 */ 1674 if (zbookmark_subtree_completed(dnp, zb, 1675 &scn->scn_phys.scn_bookmark)) 1676 return (B_TRUE); 1677 1678 /* 1679 * If we found the block we're trying to resume from, or 1680 * we went past it to a different object, zero it out to 1681 * indicate that it's OK to start checking for suspending 1682 * again. 1683 */ 1684 if (bcmp(zb, &scn->scn_phys.scn_bookmark, sizeof (*zb)) == 0 || 1685 zb->zb_object > scn->scn_phys.scn_bookmark.zb_object) { 1686 dprintf("resuming at %llx/%llx/%llx/%llx\n", 1687 (longlong_t)zb->zb_objset, 1688 (longlong_t)zb->zb_object, 1689 (longlong_t)zb->zb_level, 1690 (longlong_t)zb->zb_blkid); 1691 bzero(&scn->scn_phys.scn_bookmark, sizeof (*zb)); 1692 } 1693 } 1694 return (B_FALSE); 1695 } 1696 1697 static void dsl_scan_visitbp(blkptr_t *bp, const zbookmark_phys_t *zb, 1698 dnode_phys_t *dnp, dsl_dataset_t *ds, dsl_scan_t *scn, 1699 dmu_objset_type_t ostype, dmu_tx_t *tx); 1700 static void dsl_scan_visitdnode( 1701 dsl_scan_t *, dsl_dataset_t *ds, dmu_objset_type_t ostype, 1702 dnode_phys_t *dnp, uint64_t object, dmu_tx_t *tx); 1703 1704 /* 1705 * Return nonzero on i/o error. 1706 * Return new buf to write out in *bufp. 1707 */ 1708 static int 1709 dsl_scan_recurse(dsl_scan_t *scn, dsl_dataset_t *ds, dmu_objset_type_t ostype, 1710 dnode_phys_t *dnp, const blkptr_t *bp, 1711 const zbookmark_phys_t *zb, dmu_tx_t *tx) 1712 { 1713 dsl_pool_t *dp = scn->scn_dp; 1714 int zio_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCAN_THREAD; 1715 int err; 1716 1717 if (BP_GET_LEVEL(bp) > 0) { 1718 arc_flags_t flags = ARC_FLAG_WAIT; 1719 int i; 1720 blkptr_t *cbp; 1721 int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT; 1722 arc_buf_t *buf; 1723 1724 err = arc_read(NULL, dp->dp_spa, bp, arc_getbuf_func, &buf, 1725 ZIO_PRIORITY_SCRUB, zio_flags, &flags, zb); 1726 if (err) { 1727 scn->scn_phys.scn_errors++; 1728 return (err); 1729 } 1730 for (i = 0, cbp = buf->b_data; i < epb; i++, cbp++) { 1731 zbookmark_phys_t czb; 1732 1733 SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object, 1734 zb->zb_level - 1, 1735 zb->zb_blkid * epb + i); 1736 dsl_scan_visitbp(cbp, &czb, dnp, 1737 ds, scn, ostype, tx); 1738 } 1739 arc_buf_destroy(buf, &buf); 1740 } else if (BP_GET_TYPE(bp) == DMU_OT_DNODE) { 1741 arc_flags_t flags = ARC_FLAG_WAIT; 1742 dnode_phys_t *cdnp; 1743 int i; 1744 int epb = BP_GET_LSIZE(bp) >> DNODE_SHIFT; 1745 arc_buf_t *buf; 1746 1747 err = arc_read(NULL, dp->dp_spa, bp, arc_getbuf_func, &buf, 1748 ZIO_PRIORITY_SCRUB, zio_flags, &flags, zb); 1749 if (err) { 1750 scn->scn_phys.scn_errors++; 1751 return (err); 1752 } 1753 for (i = 0, cdnp = buf->b_data; i < epb; 1754 i += cdnp->dn_extra_slots + 1, 1755 cdnp += cdnp->dn_extra_slots + 1) { 1756 dsl_scan_visitdnode(scn, ds, ostype, 1757 cdnp, zb->zb_blkid * epb + i, tx); 1758 } 1759 1760 arc_buf_destroy(buf, &buf); 1761 } else if (BP_GET_TYPE(bp) == DMU_OT_OBJSET) { 1762 arc_flags_t flags = ARC_FLAG_WAIT; 1763 objset_phys_t *osp; 1764 arc_buf_t *buf; 1765 1766 err = arc_read(NULL, dp->dp_spa, bp, arc_getbuf_func, &buf, 1767 ZIO_PRIORITY_SCRUB, zio_flags, &flags, zb); 1768 if (err) { 1769 scn->scn_phys.scn_errors++; 1770 return (err); 1771 } 1772 1773 osp = buf->b_data; 1774 1775 dsl_scan_visitdnode(scn, ds, osp->os_type, 1776 &osp->os_meta_dnode, DMU_META_DNODE_OBJECT, tx); 1777 1778 if (OBJSET_BUF_HAS_USERUSED(buf)) { 1779 /* 1780 * We also always visit user/group accounting 1781 * objects, and never skip them, even if we are 1782 * suspending. This is necessary so that the space 1783 * deltas from this txg get integrated. 1784 */ 1785 dsl_scan_visitdnode(scn, ds, osp->os_type, 1786 &osp->os_groupused_dnode, 1787 DMU_GROUPUSED_OBJECT, tx); 1788 dsl_scan_visitdnode(scn, ds, osp->os_type, 1789 &osp->os_userused_dnode, 1790 DMU_USERUSED_OBJECT, tx); 1791 } 1792 arc_buf_destroy(buf, &buf); 1793 } 1794 1795 return (0); 1796 } 1797 1798 static void 1799 dsl_scan_visitdnode(dsl_scan_t *scn, dsl_dataset_t *ds, 1800 dmu_objset_type_t ostype, dnode_phys_t *dnp, 1801 uint64_t object, dmu_tx_t *tx) 1802 { 1803 int j; 1804 1805 for (j = 0; j < dnp->dn_nblkptr; j++) { 1806 zbookmark_phys_t czb; 1807 1808 SET_BOOKMARK(&czb, ds ? ds->ds_object : 0, object, 1809 dnp->dn_nlevels - 1, j); 1810 dsl_scan_visitbp(&dnp->dn_blkptr[j], 1811 &czb, dnp, ds, scn, ostype, tx); 1812 } 1813 1814 if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) { 1815 zbookmark_phys_t czb; 1816 SET_BOOKMARK(&czb, ds ? ds->ds_object : 0, object, 1817 0, DMU_SPILL_BLKID); 1818 dsl_scan_visitbp(DN_SPILL_BLKPTR(dnp), 1819 &czb, dnp, ds, scn, ostype, tx); 1820 } 1821 } 1822 1823 /* 1824 * The arguments are in this order because mdb can only print the 1825 * first 5; we want them to be useful. 1826 */ 1827 static void 1828 dsl_scan_visitbp(blkptr_t *bp, const zbookmark_phys_t *zb, 1829 dnode_phys_t *dnp, dsl_dataset_t *ds, dsl_scan_t *scn, 1830 dmu_objset_type_t ostype, dmu_tx_t *tx) 1831 { 1832 dsl_pool_t *dp = scn->scn_dp; 1833 blkptr_t *bp_toread = NULL; 1834 1835 if (dsl_scan_check_suspend(scn, zb)) 1836 return; 1837 1838 if (dsl_scan_check_resume(scn, dnp, zb)) 1839 return; 1840 1841 scn->scn_visited_this_txg++; 1842 1843 /* 1844 * This debugging is commented out to conserve stack space. This 1845 * function is called recursively and the debugging addes several 1846 * bytes to the stack for each call. It can be commented back in 1847 * if required to debug an issue in dsl_scan_visitbp(). 1848 * 1849 * dprintf_bp(bp, 1850 * "visiting ds=%p/%llu zb=%llx/%llx/%llx/%llx bp=%p", 1851 * ds, ds ? ds->ds_object : 0, 1852 * zb->zb_objset, zb->zb_object, zb->zb_level, zb->zb_blkid, 1853 * bp); 1854 */ 1855 1856 if (BP_IS_HOLE(bp)) { 1857 scn->scn_holes_this_txg++; 1858 return; 1859 } 1860 1861 if (bp->blk_birth <= scn->scn_phys.scn_cur_min_txg) { 1862 scn->scn_lt_min_this_txg++; 1863 return; 1864 } 1865 1866 bp_toread = kmem_alloc(sizeof (blkptr_t), KM_SLEEP); 1867 *bp_toread = *bp; 1868 1869 if (dsl_scan_recurse(scn, ds, ostype, dnp, bp_toread, zb, tx) != 0) 1870 goto out; 1871 1872 /* 1873 * If dsl_scan_ddt() has already visited this block, it will have 1874 * already done any translations or scrubbing, so don't call the 1875 * callback again. 1876 */ 1877 if (ddt_class_contains(dp->dp_spa, 1878 scn->scn_phys.scn_ddt_class_max, bp)) { 1879 scn->scn_ddt_contained_this_txg++; 1880 goto out; 1881 } 1882 1883 /* 1884 * If this block is from the future (after cur_max_txg), then we 1885 * are doing this on behalf of a deleted snapshot, and we will 1886 * revisit the future block on the next pass of this dataset. 1887 * Don't scan it now unless we need to because something 1888 * under it was modified. 1889 */ 1890 if (BP_PHYSICAL_BIRTH(bp) > scn->scn_phys.scn_cur_max_txg) { 1891 scn->scn_gt_max_this_txg++; 1892 goto out; 1893 } 1894 1895 scan_funcs[scn->scn_phys.scn_func](dp, bp, zb); 1896 1897 out: 1898 kmem_free(bp_toread, sizeof (blkptr_t)); 1899 } 1900 1901 static void 1902 dsl_scan_visit_rootbp(dsl_scan_t *scn, dsl_dataset_t *ds, blkptr_t *bp, 1903 dmu_tx_t *tx) 1904 { 1905 zbookmark_phys_t zb; 1906 scan_prefetch_ctx_t *spc; 1907 1908 SET_BOOKMARK(&zb, ds ? ds->ds_object : DMU_META_OBJSET, 1909 ZB_ROOT_OBJECT, ZB_ROOT_LEVEL, ZB_ROOT_BLKID); 1910 1911 if (ZB_IS_ZERO(&scn->scn_phys.scn_bookmark)) { 1912 SET_BOOKMARK(&scn->scn_prefetch_bookmark, 1913 zb.zb_objset, 0, 0, 0); 1914 } else { 1915 scn->scn_prefetch_bookmark = scn->scn_phys.scn_bookmark; 1916 } 1917 1918 scn->scn_objsets_visited_this_txg++; 1919 1920 spc = scan_prefetch_ctx_create(scn, NULL, FTAG); 1921 dsl_scan_prefetch(spc, bp, &zb); 1922 scan_prefetch_ctx_rele(spc, FTAG); 1923 1924 dsl_scan_visitbp(bp, &zb, NULL, ds, scn, DMU_OST_NONE, tx); 1925 1926 dprintf_ds(ds, "finished scan%s", ""); 1927 } 1928 1929 static void 1930 ds_destroyed_scn_phys(dsl_dataset_t *ds, dsl_scan_phys_t *scn_phys) 1931 { 1932 if (scn_phys->scn_bookmark.zb_objset == ds->ds_object) { 1933 if (ds->ds_is_snapshot) { 1934 /* 1935 * Note: 1936 * - scn_cur_{min,max}_txg stays the same. 1937 * - Setting the flag is not really necessary if 1938 * scn_cur_max_txg == scn_max_txg, because there 1939 * is nothing after this snapshot that we care 1940 * about. However, we set it anyway and then 1941 * ignore it when we retraverse it in 1942 * dsl_scan_visitds(). 1943 */ 1944 scn_phys->scn_bookmark.zb_objset = 1945 dsl_dataset_phys(ds)->ds_next_snap_obj; 1946 zfs_dbgmsg("destroying ds %llu; currently traversing; " 1947 "reset zb_objset to %llu", 1948 (u_longlong_t)ds->ds_object, 1949 (u_longlong_t)dsl_dataset_phys(ds)-> 1950 ds_next_snap_obj); 1951 scn_phys->scn_flags |= DSF_VISIT_DS_AGAIN; 1952 } else { 1953 SET_BOOKMARK(&scn_phys->scn_bookmark, 1954 ZB_DESTROYED_OBJSET, 0, 0, 0); 1955 zfs_dbgmsg("destroying ds %llu; currently traversing; " 1956 "reset bookmark to -1,0,0,0", 1957 (u_longlong_t)ds->ds_object); 1958 } 1959 } 1960 } 1961 1962 /* 1963 * Invoked when a dataset is destroyed. We need to make sure that: 1964 * 1965 * 1) If it is the dataset that was currently being scanned, we write 1966 * a new dsl_scan_phys_t and marking the objset reference in it 1967 * as destroyed. 1968 * 2) Remove it from the work queue, if it was present. 1969 * 1970 * If the dataset was actually a snapshot, instead of marking the dataset 1971 * as destroyed, we instead substitute the next snapshot in line. 1972 */ 1973 void 1974 dsl_scan_ds_destroyed(dsl_dataset_t *ds, dmu_tx_t *tx) 1975 { 1976 dsl_pool_t *dp = ds->ds_dir->dd_pool; 1977 dsl_scan_t *scn = dp->dp_scan; 1978 uint64_t mintxg; 1979 1980 if (!dsl_scan_is_running(scn)) 1981 return; 1982 1983 ds_destroyed_scn_phys(ds, &scn->scn_phys); 1984 ds_destroyed_scn_phys(ds, &scn->scn_phys_cached); 1985 1986 if (scan_ds_queue_contains(scn, ds->ds_object, &mintxg)) { 1987 scan_ds_queue_remove(scn, ds->ds_object); 1988 if (ds->ds_is_snapshot) 1989 scan_ds_queue_insert(scn, 1990 dsl_dataset_phys(ds)->ds_next_snap_obj, mintxg); 1991 } 1992 1993 if (zap_lookup_int_key(dp->dp_meta_objset, scn->scn_phys.scn_queue_obj, 1994 ds->ds_object, &mintxg) == 0) { 1995 ASSERT3U(dsl_dataset_phys(ds)->ds_num_children, <=, 1); 1996 VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset, 1997 scn->scn_phys.scn_queue_obj, ds->ds_object, tx)); 1998 if (ds->ds_is_snapshot) { 1999 /* 2000 * We keep the same mintxg; it could be > 2001 * ds_creation_txg if the previous snapshot was 2002 * deleted too. 2003 */ 2004 VERIFY(zap_add_int_key(dp->dp_meta_objset, 2005 scn->scn_phys.scn_queue_obj, 2006 dsl_dataset_phys(ds)->ds_next_snap_obj, 2007 mintxg, tx) == 0); 2008 zfs_dbgmsg("destroying ds %llu; in queue; " 2009 "replacing with %llu", 2010 (u_longlong_t)ds->ds_object, 2011 (u_longlong_t)dsl_dataset_phys(ds)-> 2012 ds_next_snap_obj); 2013 } else { 2014 zfs_dbgmsg("destroying ds %llu; in queue; removing", 2015 (u_longlong_t)ds->ds_object); 2016 } 2017 } 2018 2019 /* 2020 * dsl_scan_sync() should be called after this, and should sync 2021 * out our changed state, but just to be safe, do it here. 2022 */ 2023 dsl_scan_sync_state(scn, tx, SYNC_CACHED); 2024 } 2025 2026 static void 2027 ds_snapshotted_bookmark(dsl_dataset_t *ds, zbookmark_phys_t *scn_bookmark) 2028 { 2029 if (scn_bookmark->zb_objset == ds->ds_object) { 2030 scn_bookmark->zb_objset = 2031 dsl_dataset_phys(ds)->ds_prev_snap_obj; 2032 zfs_dbgmsg("snapshotting ds %llu; currently traversing; " 2033 "reset zb_objset to %llu", 2034 (u_longlong_t)ds->ds_object, 2035 (u_longlong_t)dsl_dataset_phys(ds)->ds_prev_snap_obj); 2036 } 2037 } 2038 2039 /* 2040 * Called when a dataset is snapshotted. If we were currently traversing 2041 * this snapshot, we reset our bookmark to point at the newly created 2042 * snapshot. We also modify our work queue to remove the old snapshot and 2043 * replace with the new one. 2044 */ 2045 void 2046 dsl_scan_ds_snapshotted(dsl_dataset_t *ds, dmu_tx_t *tx) 2047 { 2048 dsl_pool_t *dp = ds->ds_dir->dd_pool; 2049 dsl_scan_t *scn = dp->dp_scan; 2050 uint64_t mintxg; 2051 2052 if (!dsl_scan_is_running(scn)) 2053 return; 2054 2055 ASSERT(dsl_dataset_phys(ds)->ds_prev_snap_obj != 0); 2056 2057 ds_snapshotted_bookmark(ds, &scn->scn_phys.scn_bookmark); 2058 ds_snapshotted_bookmark(ds, &scn->scn_phys_cached.scn_bookmark); 2059 2060 if (scan_ds_queue_contains(scn, ds->ds_object, &mintxg)) { 2061 scan_ds_queue_remove(scn, ds->ds_object); 2062 scan_ds_queue_insert(scn, 2063 dsl_dataset_phys(ds)->ds_prev_snap_obj, mintxg); 2064 } 2065 2066 if (zap_lookup_int_key(dp->dp_meta_objset, scn->scn_phys.scn_queue_obj, 2067 ds->ds_object, &mintxg) == 0) { 2068 VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset, 2069 scn->scn_phys.scn_queue_obj, ds->ds_object, tx)); 2070 VERIFY(zap_add_int_key(dp->dp_meta_objset, 2071 scn->scn_phys.scn_queue_obj, 2072 dsl_dataset_phys(ds)->ds_prev_snap_obj, mintxg, tx) == 0); 2073 zfs_dbgmsg("snapshotting ds %llu; in queue; " 2074 "replacing with %llu", 2075 (u_longlong_t)ds->ds_object, 2076 (u_longlong_t)dsl_dataset_phys(ds)->ds_prev_snap_obj); 2077 } 2078 2079 dsl_scan_sync_state(scn, tx, SYNC_CACHED); 2080 } 2081 2082 static void 2083 ds_clone_swapped_bookmark(dsl_dataset_t *ds1, dsl_dataset_t *ds2, 2084 zbookmark_phys_t *scn_bookmark) 2085 { 2086 if (scn_bookmark->zb_objset == ds1->ds_object) { 2087 scn_bookmark->zb_objset = ds2->ds_object; 2088 zfs_dbgmsg("clone_swap ds %llu; currently traversing; " 2089 "reset zb_objset to %llu", 2090 (u_longlong_t)ds1->ds_object, 2091 (u_longlong_t)ds2->ds_object); 2092 } else if (scn_bookmark->zb_objset == ds2->ds_object) { 2093 scn_bookmark->zb_objset = ds1->ds_object; 2094 zfs_dbgmsg("clone_swap ds %llu; currently traversing; " 2095 "reset zb_objset to %llu", 2096 (u_longlong_t)ds2->ds_object, 2097 (u_longlong_t)ds1->ds_object); 2098 } 2099 } 2100 2101 /* 2102 * Called when a parent dataset and its clone are swapped. If we were 2103 * currently traversing the dataset, we need to switch to traversing the 2104 * newly promoted parent. 2105 */ 2106 void 2107 dsl_scan_ds_clone_swapped(dsl_dataset_t *ds1, dsl_dataset_t *ds2, dmu_tx_t *tx) 2108 { 2109 dsl_pool_t *dp = ds1->ds_dir->dd_pool; 2110 dsl_scan_t *scn = dp->dp_scan; 2111 uint64_t mintxg; 2112 2113 if (!dsl_scan_is_running(scn)) 2114 return; 2115 2116 ds_clone_swapped_bookmark(ds1, ds2, &scn->scn_phys.scn_bookmark); 2117 ds_clone_swapped_bookmark(ds1, ds2, &scn->scn_phys_cached.scn_bookmark); 2118 2119 if (scan_ds_queue_contains(scn, ds1->ds_object, &mintxg)) { 2120 scan_ds_queue_remove(scn, ds1->ds_object); 2121 scan_ds_queue_insert(scn, ds2->ds_object, mintxg); 2122 } 2123 if (scan_ds_queue_contains(scn, ds2->ds_object, &mintxg)) { 2124 scan_ds_queue_remove(scn, ds2->ds_object); 2125 scan_ds_queue_insert(scn, ds1->ds_object, mintxg); 2126 } 2127 2128 if (zap_lookup_int_key(dp->dp_meta_objset, scn->scn_phys.scn_queue_obj, 2129 ds1->ds_object, &mintxg) == 0) { 2130 int err; 2131 ASSERT3U(mintxg, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg); 2132 ASSERT3U(mintxg, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg); 2133 VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset, 2134 scn->scn_phys.scn_queue_obj, ds1->ds_object, tx)); 2135 err = zap_add_int_key(dp->dp_meta_objset, 2136 scn->scn_phys.scn_queue_obj, ds2->ds_object, mintxg, tx); 2137 VERIFY(err == 0 || err == EEXIST); 2138 if (err == EEXIST) { 2139 /* Both were there to begin with */ 2140 VERIFY(0 == zap_add_int_key(dp->dp_meta_objset, 2141 scn->scn_phys.scn_queue_obj, 2142 ds1->ds_object, mintxg, tx)); 2143 } 2144 zfs_dbgmsg("clone_swap ds %llu; in queue; " 2145 "replacing with %llu", 2146 (u_longlong_t)ds1->ds_object, 2147 (u_longlong_t)ds2->ds_object); 2148 } 2149 if (zap_lookup_int_key(dp->dp_meta_objset, scn->scn_phys.scn_queue_obj, 2150 ds2->ds_object, &mintxg) == 0) { 2151 ASSERT3U(mintxg, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg); 2152 ASSERT3U(mintxg, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg); 2153 VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset, 2154 scn->scn_phys.scn_queue_obj, ds2->ds_object, tx)); 2155 VERIFY(0 == zap_add_int_key(dp->dp_meta_objset, 2156 scn->scn_phys.scn_queue_obj, ds1->ds_object, mintxg, tx)); 2157 zfs_dbgmsg("clone_swap ds %llu; in queue; " 2158 "replacing with %llu", 2159 (u_longlong_t)ds2->ds_object, 2160 (u_longlong_t)ds1->ds_object); 2161 } 2162 2163 dsl_scan_sync_state(scn, tx, SYNC_CACHED); 2164 } 2165 2166 /* ARGSUSED */ 2167 static int 2168 enqueue_clones_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg) 2169 { 2170 uint64_t originobj = *(uint64_t *)arg; 2171 dsl_dataset_t *ds; 2172 int err; 2173 dsl_scan_t *scn = dp->dp_scan; 2174 2175 if (dsl_dir_phys(hds->ds_dir)->dd_origin_obj != originobj) 2176 return (0); 2177 2178 err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds); 2179 if (err) 2180 return (err); 2181 2182 while (dsl_dataset_phys(ds)->ds_prev_snap_obj != originobj) { 2183 dsl_dataset_t *prev; 2184 err = dsl_dataset_hold_obj(dp, 2185 dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev); 2186 2187 dsl_dataset_rele(ds, FTAG); 2188 if (err) 2189 return (err); 2190 ds = prev; 2191 } 2192 scan_ds_queue_insert(scn, ds->ds_object, 2193 dsl_dataset_phys(ds)->ds_prev_snap_txg); 2194 dsl_dataset_rele(ds, FTAG); 2195 return (0); 2196 } 2197 2198 static void 2199 dsl_scan_visitds(dsl_scan_t *scn, uint64_t dsobj, dmu_tx_t *tx) 2200 { 2201 dsl_pool_t *dp = scn->scn_dp; 2202 dsl_dataset_t *ds; 2203 2204 VERIFY3U(0, ==, dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds)); 2205 2206 if (scn->scn_phys.scn_cur_min_txg >= 2207 scn->scn_phys.scn_max_txg) { 2208 /* 2209 * This can happen if this snapshot was created after the 2210 * scan started, and we already completed a previous snapshot 2211 * that was created after the scan started. This snapshot 2212 * only references blocks with: 2213 * 2214 * birth < our ds_creation_txg 2215 * cur_min_txg is no less than ds_creation_txg. 2216 * We have already visited these blocks. 2217 * or 2218 * birth > scn_max_txg 2219 * The scan requested not to visit these blocks. 2220 * 2221 * Subsequent snapshots (and clones) can reference our 2222 * blocks, or blocks with even higher birth times. 2223 * Therefore we do not need to visit them either, 2224 * so we do not add them to the work queue. 2225 * 2226 * Note that checking for cur_min_txg >= cur_max_txg 2227 * is not sufficient, because in that case we may need to 2228 * visit subsequent snapshots. This happens when min_txg > 0, 2229 * which raises cur_min_txg. In this case we will visit 2230 * this dataset but skip all of its blocks, because the 2231 * rootbp's birth time is < cur_min_txg. Then we will 2232 * add the next snapshots/clones to the work queue. 2233 */ 2234 char *dsname = kmem_alloc(MAXNAMELEN, KM_SLEEP); 2235 dsl_dataset_name(ds, dsname); 2236 zfs_dbgmsg("scanning dataset %llu (%s) is unnecessary because " 2237 "cur_min_txg (%llu) >= max_txg (%llu)", 2238 (longlong_t)dsobj, dsname, 2239 (longlong_t)scn->scn_phys.scn_cur_min_txg, 2240 (longlong_t)scn->scn_phys.scn_max_txg); 2241 kmem_free(dsname, MAXNAMELEN); 2242 2243 goto out; 2244 } 2245 2246 /* 2247 * Only the ZIL in the head (non-snapshot) is valid. Even though 2248 * snapshots can have ZIL block pointers (which may be the same 2249 * BP as in the head), they must be ignored. In addition, $ORIGIN 2250 * doesn't have a objset (i.e. its ds_bp is a hole) so we don't 2251 * need to look for a ZIL in it either. So we traverse the ZIL here, 2252 * rather than in scan_recurse(), because the regular snapshot 2253 * block-sharing rules don't apply to it. 2254 */ 2255 if (DSL_SCAN_IS_SCRUB_RESILVER(scn) && !dsl_dataset_is_snapshot(ds) && 2256 (dp->dp_origin_snap == NULL || 2257 ds->ds_dir != dp->dp_origin_snap->ds_dir)) { 2258 objset_t *os; 2259 if (dmu_objset_from_ds(ds, &os) != 0) { 2260 goto out; 2261 } 2262 dsl_scan_zil(dp, &os->os_zil_header); 2263 } 2264 2265 /* 2266 * Iterate over the bps in this ds. 2267 */ 2268 dmu_buf_will_dirty(ds->ds_dbuf, tx); 2269 rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG); 2270 dsl_scan_visit_rootbp(scn, ds, &dsl_dataset_phys(ds)->ds_bp, tx); 2271 rrw_exit(&ds->ds_bp_rwlock, FTAG); 2272 2273 char *dsname = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP); 2274 dsl_dataset_name(ds, dsname); 2275 zfs_dbgmsg("scanned dataset %llu (%s) with min=%llu max=%llu; " 2276 "suspending=%u", 2277 (longlong_t)dsobj, dsname, 2278 (longlong_t)scn->scn_phys.scn_cur_min_txg, 2279 (longlong_t)scn->scn_phys.scn_cur_max_txg, 2280 (int)scn->scn_suspending); 2281 kmem_free(dsname, ZFS_MAX_DATASET_NAME_LEN); 2282 2283 if (scn->scn_suspending) 2284 goto out; 2285 2286 /* 2287 * We've finished this pass over this dataset. 2288 */ 2289 2290 /* 2291 * If we did not completely visit this dataset, do another pass. 2292 */ 2293 if (scn->scn_phys.scn_flags & DSF_VISIT_DS_AGAIN) { 2294 zfs_dbgmsg("incomplete pass; visiting again"); 2295 scn->scn_phys.scn_flags &= ~DSF_VISIT_DS_AGAIN; 2296 scan_ds_queue_insert(scn, ds->ds_object, 2297 scn->scn_phys.scn_cur_max_txg); 2298 goto out; 2299 } 2300 2301 /* 2302 * Add descendent datasets to work queue. 2303 */ 2304 if (dsl_dataset_phys(ds)->ds_next_snap_obj != 0) { 2305 scan_ds_queue_insert(scn, 2306 dsl_dataset_phys(ds)->ds_next_snap_obj, 2307 dsl_dataset_phys(ds)->ds_creation_txg); 2308 } 2309 if (dsl_dataset_phys(ds)->ds_num_children > 1) { 2310 boolean_t usenext = B_FALSE; 2311 if (dsl_dataset_phys(ds)->ds_next_clones_obj != 0) { 2312 uint64_t count; 2313 /* 2314 * A bug in a previous version of the code could 2315 * cause upgrade_clones_cb() to not set 2316 * ds_next_snap_obj when it should, leading to a 2317 * missing entry. Therefore we can only use the 2318 * next_clones_obj when its count is correct. 2319 */ 2320 int err = zap_count(dp->dp_meta_objset, 2321 dsl_dataset_phys(ds)->ds_next_clones_obj, &count); 2322 if (err == 0 && 2323 count == dsl_dataset_phys(ds)->ds_num_children - 1) 2324 usenext = B_TRUE; 2325 } 2326 2327 if (usenext) { 2328 zap_cursor_t zc; 2329 zap_attribute_t za; 2330 for (zap_cursor_init(&zc, dp->dp_meta_objset, 2331 dsl_dataset_phys(ds)->ds_next_clones_obj); 2332 zap_cursor_retrieve(&zc, &za) == 0; 2333 (void) zap_cursor_advance(&zc)) { 2334 scan_ds_queue_insert(scn, 2335 zfs_strtonum(za.za_name, NULL), 2336 dsl_dataset_phys(ds)->ds_creation_txg); 2337 } 2338 zap_cursor_fini(&zc); 2339 } else { 2340 VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj, 2341 enqueue_clones_cb, &ds->ds_object, 2342 DS_FIND_CHILDREN)); 2343 } 2344 } 2345 2346 out: 2347 dsl_dataset_rele(ds, FTAG); 2348 } 2349 2350 /* ARGSUSED */ 2351 static int 2352 enqueue_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg) 2353 { 2354 dsl_dataset_t *ds; 2355 int err; 2356 dsl_scan_t *scn = dp->dp_scan; 2357 2358 err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds); 2359 if (err) 2360 return (err); 2361 2362 while (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) { 2363 dsl_dataset_t *prev; 2364 err = dsl_dataset_hold_obj(dp, 2365 dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev); 2366 if (err) { 2367 dsl_dataset_rele(ds, FTAG); 2368 return (err); 2369 } 2370 2371 /* 2372 * If this is a clone, we don't need to worry about it for now. 2373 */ 2374 if (dsl_dataset_phys(prev)->ds_next_snap_obj != ds->ds_object) { 2375 dsl_dataset_rele(ds, FTAG); 2376 dsl_dataset_rele(prev, FTAG); 2377 return (0); 2378 } 2379 dsl_dataset_rele(ds, FTAG); 2380 ds = prev; 2381 } 2382 2383 scan_ds_queue_insert(scn, ds->ds_object, 2384 dsl_dataset_phys(ds)->ds_prev_snap_txg); 2385 dsl_dataset_rele(ds, FTAG); 2386 return (0); 2387 } 2388 2389 /* ARGSUSED */ 2390 void 2391 dsl_scan_ddt_entry(dsl_scan_t *scn, enum zio_checksum checksum, 2392 ddt_entry_t *dde, dmu_tx_t *tx) 2393 { 2394 const ddt_key_t *ddk = &dde->dde_key; 2395 ddt_phys_t *ddp = dde->dde_phys; 2396 blkptr_t bp; 2397 zbookmark_phys_t zb = { 0 }; 2398 int p; 2399 2400 if (scn->scn_phys.scn_state != DSS_SCANNING) 2401 return; 2402 2403 /* 2404 * This function is special because it is the only thing 2405 * that can add scan_io_t's to the vdev scan queues from 2406 * outside dsl_scan_sync(). For the most part this is ok 2407 * as long as it is called from within syncing context. 2408 * However, dsl_scan_sync() expects that no new sio's will 2409 * be added between when all the work for a scan is done 2410 * and the next txg when the scan is actually marked as 2411 * completed. This check ensures we do not issue new sio's 2412 * during this period. 2413 */ 2414 if (scn->scn_done_txg != 0) 2415 return; 2416 2417 for (p = 0; p < DDT_PHYS_TYPES; p++, ddp++) { 2418 if (ddp->ddp_phys_birth == 0 || 2419 ddp->ddp_phys_birth > scn->scn_phys.scn_max_txg) 2420 continue; 2421 ddt_bp_create(checksum, ddk, ddp, &bp); 2422 2423 scn->scn_visited_this_txg++; 2424 scan_funcs[scn->scn_phys.scn_func](scn->scn_dp, &bp, &zb); 2425 } 2426 } 2427 2428 /* 2429 * Scrub/dedup interaction. 2430 * 2431 * If there are N references to a deduped block, we don't want to scrub it 2432 * N times -- ideally, we should scrub it exactly once. 2433 * 2434 * We leverage the fact that the dde's replication class (enum ddt_class) 2435 * is ordered from highest replication class (DDT_CLASS_DITTO) to lowest 2436 * (DDT_CLASS_UNIQUE) so that we may walk the DDT in that order. 2437 * 2438 * To prevent excess scrubbing, the scrub begins by walking the DDT 2439 * to find all blocks with refcnt > 1, and scrubs each of these once. 2440 * Since there are two replication classes which contain blocks with 2441 * refcnt > 1, we scrub the highest replication class (DDT_CLASS_DITTO) first. 2442 * Finally the top-down scrub begins, only visiting blocks with refcnt == 1. 2443 * 2444 * There would be nothing more to say if a block's refcnt couldn't change 2445 * during a scrub, but of course it can so we must account for changes 2446 * in a block's replication class. 2447 * 2448 * Here's an example of what can occur: 2449 * 2450 * If a block has refcnt > 1 during the DDT scrub phase, but has refcnt == 1 2451 * when visited during the top-down scrub phase, it will be scrubbed twice. 2452 * This negates our scrub optimization, but is otherwise harmless. 2453 * 2454 * If a block has refcnt == 1 during the DDT scrub phase, but has refcnt > 1 2455 * on each visit during the top-down scrub phase, it will never be scrubbed. 2456 * To catch this, ddt_sync_entry() notifies the scrub code whenever a block's 2457 * reference class transitions to a higher level (i.e DDT_CLASS_UNIQUE to 2458 * DDT_CLASS_DUPLICATE); if it transitions from refcnt == 1 to refcnt > 1 2459 * while a scrub is in progress, it scrubs the block right then. 2460 */ 2461 static void 2462 dsl_scan_ddt(dsl_scan_t *scn, dmu_tx_t *tx) 2463 { 2464 ddt_bookmark_t *ddb = &scn->scn_phys.scn_ddt_bookmark; 2465 ddt_entry_t dde = { 0 }; 2466 int error; 2467 uint64_t n = 0; 2468 2469 while ((error = ddt_walk(scn->scn_dp->dp_spa, ddb, &dde)) == 0) { 2470 ddt_t *ddt; 2471 2472 if (ddb->ddb_class > scn->scn_phys.scn_ddt_class_max) 2473 break; 2474 dprintf("visiting ddb=%llu/%llu/%llu/%llx\n", 2475 (longlong_t)ddb->ddb_class, 2476 (longlong_t)ddb->ddb_type, 2477 (longlong_t)ddb->ddb_checksum, 2478 (longlong_t)ddb->ddb_cursor); 2479 2480 /* There should be no pending changes to the dedup table */ 2481 ddt = scn->scn_dp->dp_spa->spa_ddt[ddb->ddb_checksum]; 2482 ASSERT(avl_first(&ddt->ddt_tree) == NULL); 2483 2484 dsl_scan_ddt_entry(scn, ddb->ddb_checksum, &dde, tx); 2485 n++; 2486 2487 if (dsl_scan_check_suspend(scn, NULL)) 2488 break; 2489 } 2490 2491 zfs_dbgmsg("scanned %llu ddt entries with class_max = %u; " 2492 "suspending=%u", (longlong_t)n, 2493 (int)scn->scn_phys.scn_ddt_class_max, (int)scn->scn_suspending); 2494 2495 ASSERT(error == 0 || error == ENOENT); 2496 ASSERT(error != ENOENT || 2497 ddb->ddb_class > scn->scn_phys.scn_ddt_class_max); 2498 } 2499 2500 static uint64_t 2501 dsl_scan_ds_maxtxg(dsl_dataset_t *ds) 2502 { 2503 uint64_t smt = ds->ds_dir->dd_pool->dp_scan->scn_phys.scn_max_txg; 2504 if (ds->ds_is_snapshot) 2505 return (MIN(smt, dsl_dataset_phys(ds)->ds_creation_txg)); 2506 return (smt); 2507 } 2508 2509 static void 2510 dsl_scan_visit(dsl_scan_t *scn, dmu_tx_t *tx) 2511 { 2512 scan_ds_t *sds; 2513 dsl_pool_t *dp = scn->scn_dp; 2514 2515 if (scn->scn_phys.scn_ddt_bookmark.ddb_class <= 2516 scn->scn_phys.scn_ddt_class_max) { 2517 scn->scn_phys.scn_cur_min_txg = scn->scn_phys.scn_min_txg; 2518 scn->scn_phys.scn_cur_max_txg = scn->scn_phys.scn_max_txg; 2519 dsl_scan_ddt(scn, tx); 2520 if (scn->scn_suspending) 2521 return; 2522 } 2523 2524 if (scn->scn_phys.scn_bookmark.zb_objset == DMU_META_OBJSET) { 2525 /* First do the MOS & ORIGIN */ 2526 2527 scn->scn_phys.scn_cur_min_txg = scn->scn_phys.scn_min_txg; 2528 scn->scn_phys.scn_cur_max_txg = scn->scn_phys.scn_max_txg; 2529 dsl_scan_visit_rootbp(scn, NULL, 2530 &dp->dp_meta_rootbp, tx); 2531 spa_set_rootblkptr(dp->dp_spa, &dp->dp_meta_rootbp); 2532 if (scn->scn_suspending) 2533 return; 2534 2535 if (spa_version(dp->dp_spa) < SPA_VERSION_DSL_SCRUB) { 2536 VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj, 2537 enqueue_cb, NULL, DS_FIND_CHILDREN)); 2538 } else { 2539 dsl_scan_visitds(scn, 2540 dp->dp_origin_snap->ds_object, tx); 2541 } 2542 ASSERT(!scn->scn_suspending); 2543 } else if (scn->scn_phys.scn_bookmark.zb_objset != 2544 ZB_DESTROYED_OBJSET) { 2545 uint64_t dsobj = scn->scn_phys.scn_bookmark.zb_objset; 2546 /* 2547 * If we were suspended, continue from here. Note if the 2548 * ds we were suspended on was deleted, the zb_objset may 2549 * be -1, so we will skip this and find a new objset 2550 * below. 2551 */ 2552 dsl_scan_visitds(scn, dsobj, tx); 2553 if (scn->scn_suspending) 2554 return; 2555 } 2556 2557 /* 2558 * In case we suspended right at the end of the ds, zero the 2559 * bookmark so we don't think that we're still trying to resume. 2560 */ 2561 bzero(&scn->scn_phys.scn_bookmark, sizeof (zbookmark_phys_t)); 2562 2563 /* 2564 * Keep pulling things out of the dataset avl queue. Updates to the 2565 * persistent zap-object-as-queue happen only at checkpoints. 2566 */ 2567 while ((sds = avl_first(&scn->scn_queue)) != NULL) { 2568 dsl_dataset_t *ds; 2569 uint64_t dsobj = sds->sds_dsobj; 2570 uint64_t txg = sds->sds_txg; 2571 2572 /* dequeue and free the ds from the queue */ 2573 scan_ds_queue_remove(scn, dsobj); 2574 sds = NULL; /* must not be touched after removal */ 2575 2576 /* Set up min / max txg */ 2577 VERIFY3U(0, ==, dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds)); 2578 if (txg != 0) { 2579 scn->scn_phys.scn_cur_min_txg = 2580 MAX(scn->scn_phys.scn_min_txg, txg); 2581 } else { 2582 scn->scn_phys.scn_cur_min_txg = 2583 MAX(scn->scn_phys.scn_min_txg, 2584 dsl_dataset_phys(ds)->ds_prev_snap_txg); 2585 } 2586 scn->scn_phys.scn_cur_max_txg = dsl_scan_ds_maxtxg(ds); 2587 dsl_dataset_rele(ds, FTAG); 2588 2589 dsl_scan_visitds(scn, dsobj, tx); 2590 if (scn->scn_suspending) 2591 return; 2592 } 2593 /* No more objsets to fetch, we're done */ 2594 scn->scn_phys.scn_bookmark.zb_objset = ZB_DESTROYED_OBJSET; 2595 ASSERT0(scn->scn_suspending); 2596 } 2597 2598 static uint64_t 2599 dsl_scan_count_leaves(vdev_t *vd) 2600 { 2601 uint64_t i, leaves = 0; 2602 2603 /* we only count leaves that belong to the main pool and are readable */ 2604 if (vd->vdev_islog || vd->vdev_isspare || 2605 vd->vdev_isl2cache || !vdev_readable(vd)) 2606 return (0); 2607 2608 if (vd->vdev_ops->vdev_op_leaf) 2609 return (1); 2610 2611 for (i = 0; i < vd->vdev_children; i++) { 2612 leaves += dsl_scan_count_leaves(vd->vdev_child[i]); 2613 } 2614 2615 return (leaves); 2616 } 2617 2618 2619 static void 2620 scan_io_queues_update_zio_stats(dsl_scan_io_queue_t *q, const blkptr_t *bp) 2621 { 2622 int i; 2623 uint64_t cur_size = 0; 2624 2625 for (i = 0; i < BP_GET_NDVAS(bp); i++) { 2626 cur_size += DVA_GET_ASIZE(&bp->blk_dva[i]); 2627 } 2628 2629 q->q_total_zio_size_this_txg += cur_size; 2630 q->q_zios_this_txg++; 2631 } 2632 2633 static void 2634 scan_io_queues_update_seg_stats(dsl_scan_io_queue_t *q, uint64_t start, 2635 uint64_t end) 2636 { 2637 q->q_total_seg_size_this_txg += end - start; 2638 q->q_segs_this_txg++; 2639 } 2640 2641 static boolean_t 2642 scan_io_queue_check_suspend(dsl_scan_t *scn) 2643 { 2644 /* See comment in dsl_scan_check_suspend() */ 2645 uint64_t curr_time_ns = gethrtime(); 2646 uint64_t scan_time_ns = curr_time_ns - scn->scn_sync_start_time; 2647 uint64_t sync_time_ns = curr_time_ns - 2648 scn->scn_dp->dp_spa->spa_sync_starttime; 2649 int dirty_pct = scn->scn_dp->dp_dirty_total * 100 / zfs_dirty_data_max; 2650 int mintime = (scn->scn_phys.scn_func == POOL_SCAN_RESILVER) ? 2651 zfs_resilver_min_time_ms : zfs_scrub_min_time_ms; 2652 2653 return ((NSEC2MSEC(scan_time_ns) > mintime && 2654 (dirty_pct >= zfs_vdev_async_write_active_min_dirty_percent || 2655 txg_sync_waiting(scn->scn_dp) || 2656 NSEC2SEC(sync_time_ns) >= zfs_txg_timeout)) || 2657 spa_shutting_down(scn->scn_dp->dp_spa)); 2658 } 2659 2660 /* 2661 * Given a list of scan_io_t's in io_list, this issues the io's out to 2662 * disk. This consumes the io_list and frees the scan_io_t's. This is 2663 * called when emptying queues, either when we're up against the memory 2664 * limit or when we have finished scanning. Returns B_TRUE if we stopped 2665 * processing the list before we finished. Any zios that were not issued 2666 * will remain in the io_list. 2667 */ 2668 static boolean_t 2669 scan_io_queue_issue(dsl_scan_io_queue_t *queue, list_t *io_list) 2670 { 2671 dsl_scan_t *scn = queue->q_scn; 2672 scan_io_t *sio; 2673 int64_t bytes_issued = 0; 2674 boolean_t suspended = B_FALSE; 2675 2676 while ((sio = list_head(io_list)) != NULL) { 2677 blkptr_t bp; 2678 2679 if (scan_io_queue_check_suspend(scn)) { 2680 suspended = B_TRUE; 2681 break; 2682 } 2683 2684 sio2bp(sio, &bp); 2685 bytes_issued += SIO_GET_ASIZE(sio); 2686 scan_exec_io(scn->scn_dp, &bp, sio->sio_flags, 2687 &sio->sio_zb, queue); 2688 (void) list_remove_head(io_list); 2689 scan_io_queues_update_zio_stats(queue, &bp); 2690 sio_free(sio); 2691 } 2692 2693 atomic_add_64(&scn->scn_bytes_pending, -bytes_issued); 2694 2695 return (suspended); 2696 } 2697 2698 /* 2699 * Given a range_seg_t (extent) and a list, this function passes over a 2700 * scan queue and gathers up the appropriate ios which fit into that 2701 * scan seg (starting from lowest LBA). At the end, we remove the segment 2702 * from the q_exts_by_addr range tree. 2703 */ 2704 static boolean_t 2705 scan_io_queue_gather(dsl_scan_io_queue_t *queue, range_seg_t *rs, list_t *list) 2706 { 2707 scan_io_t *srch_sio, *sio, *next_sio; 2708 avl_index_t idx; 2709 uint_t num_sios = 0; 2710 int64_t bytes_issued = 0; 2711 2712 ASSERT(rs != NULL); 2713 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock)); 2714 2715 srch_sio = sio_alloc(1); 2716 srch_sio->sio_nr_dvas = 1; 2717 SIO_SET_OFFSET(srch_sio, rs->rs_start); 2718 2719 /* 2720 * The exact start of the extent might not contain any matching zios, 2721 * so if that's the case, examine the next one in the tree. 2722 */ 2723 sio = avl_find(&queue->q_sios_by_addr, srch_sio, &idx); 2724 sio_free(srch_sio); 2725 2726 if (sio == NULL) 2727 sio = avl_nearest(&queue->q_sios_by_addr, idx, AVL_AFTER); 2728 2729 while (sio != NULL && 2730 SIO_GET_OFFSET(sio) < rs->rs_end && num_sios <= 32) { 2731 ASSERT3U(SIO_GET_OFFSET(sio), >=, rs->rs_start); 2732 ASSERT3U(SIO_GET_END_OFFSET(sio), <=, rs->rs_end); 2733 2734 next_sio = AVL_NEXT(&queue->q_sios_by_addr, sio); 2735 avl_remove(&queue->q_sios_by_addr, sio); 2736 queue->q_sio_memused -= SIO_GET_MUSED(sio); 2737 2738 bytes_issued += SIO_GET_ASIZE(sio); 2739 num_sios++; 2740 list_insert_tail(list, sio); 2741 sio = next_sio; 2742 } 2743 2744 /* 2745 * We limit the number of sios we process at once to 32 to avoid 2746 * biting off more than we can chew. If we didn't take everything 2747 * in the segment we update it to reflect the work we were able to 2748 * complete. Otherwise, we remove it from the range tree entirely. 2749 */ 2750 if (sio != NULL && SIO_GET_OFFSET(sio) < rs->rs_end) { 2751 range_tree_adjust_fill(queue->q_exts_by_addr, rs, 2752 -bytes_issued); 2753 range_tree_resize_segment(queue->q_exts_by_addr, rs, 2754 SIO_GET_OFFSET(sio), rs->rs_end - SIO_GET_OFFSET(sio)); 2755 2756 return (B_TRUE); 2757 } else { 2758 range_tree_remove(queue->q_exts_by_addr, rs->rs_start, 2759 rs->rs_end - rs->rs_start); 2760 return (B_FALSE); 2761 } 2762 } 2763 2764 2765 /* 2766 * This is called from the queue emptying thread and selects the next 2767 * extent from which we are to issue io's. The behavior of this function 2768 * depends on the state of the scan, the current memory consumption and 2769 * whether or not we are performing a scan shutdown. 2770 * 1) We select extents in an elevator algorithm (LBA-order) if the scan 2771 * needs to perform a checkpoint 2772 * 2) We select the largest available extent if we are up against the 2773 * memory limit. 2774 * 3) Otherwise we don't select any extents. 2775 */ 2776 static const range_seg_t * 2777 scan_io_queue_fetch_ext(dsl_scan_io_queue_t *queue) 2778 { 2779 dsl_scan_t *scn = queue->q_scn; 2780 2781 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock)); 2782 ASSERT(scn->scn_is_sorted); 2783 2784 /* handle tunable overrides */ 2785 if (scn->scn_checkpointing || scn->scn_clearing) { 2786 if (zfs_scan_issue_strategy == 1) { 2787 return (range_tree_first(queue->q_exts_by_addr)); 2788 } else if (zfs_scan_issue_strategy == 2) { 2789 return (avl_first(&queue->q_exts_by_size)); 2790 } 2791 } 2792 2793 /* 2794 * During normal clearing, we want to issue our largest segments 2795 * first, keeping IO as sequential as possible, and leaving the 2796 * smaller extents for later with the hope that they might eventually 2797 * grow to larger sequential segments. However, when the scan is 2798 * checkpointing, no new extents will be added to the sorting queue, 2799 * so the way we are sorted now is as good as it will ever get. 2800 * In this case, we instead switch to issuing extents in LBA order. 2801 */ 2802 if (scn->scn_checkpointing) { 2803 return (range_tree_first(queue->q_exts_by_addr)); 2804 } else if (scn->scn_clearing) { 2805 return (avl_first(&queue->q_exts_by_size)); 2806 } else { 2807 return (NULL); 2808 } 2809 } 2810 2811 static void 2812 scan_io_queues_run_one(void *arg) 2813 { 2814 dsl_scan_io_queue_t *queue = arg; 2815 kmutex_t *q_lock = &queue->q_vd->vdev_scan_io_queue_lock; 2816 boolean_t suspended = B_FALSE; 2817 range_seg_t *rs = NULL; 2818 scan_io_t *sio = NULL; 2819 list_t sio_list; 2820 uint64_t bytes_per_leaf = zfs_scan_vdev_limit; 2821 uint64_t nr_leaves = dsl_scan_count_leaves(queue->q_vd); 2822 2823 ASSERT(queue->q_scn->scn_is_sorted); 2824 2825 list_create(&sio_list, sizeof (scan_io_t), 2826 offsetof(scan_io_t, sio_nodes.sio_list_node)); 2827 mutex_enter(q_lock); 2828 2829 /* calculate maximum in-flight bytes for this txg (min 1MB) */ 2830 queue->q_maxinflight_bytes = 2831 MAX(nr_leaves * bytes_per_leaf, 1ULL << 20); 2832 2833 /* reset per-queue scan statistics for this txg */ 2834 queue->q_total_seg_size_this_txg = 0; 2835 queue->q_segs_this_txg = 0; 2836 queue->q_total_zio_size_this_txg = 0; 2837 queue->q_zios_this_txg = 0; 2838 2839 /* loop until we have run out of time or sios */ 2840 while ((rs = (range_seg_t *)scan_io_queue_fetch_ext(queue)) != NULL) { 2841 uint64_t seg_start = 0, seg_end = 0; 2842 boolean_t more_left = B_TRUE; 2843 2844 ASSERT(list_is_empty(&sio_list)); 2845 2846 /* loop while we still have sios left to process in this rs */ 2847 while (more_left) { 2848 scan_io_t *first_sio, *last_sio; 2849 2850 /* 2851 * We have selected which extent needs to be 2852 * processed next. Gather up the corresponding sios. 2853 */ 2854 more_left = scan_io_queue_gather(queue, rs, &sio_list); 2855 ASSERT(!list_is_empty(&sio_list)); 2856 first_sio = list_head(&sio_list); 2857 last_sio = list_tail(&sio_list); 2858 2859 seg_end = SIO_GET_END_OFFSET(last_sio); 2860 if (seg_start == 0) 2861 seg_start = SIO_GET_OFFSET(first_sio); 2862 2863 /* 2864 * Issuing sios can take a long time so drop the 2865 * queue lock. The sio queue won't be updated by 2866 * other threads since we're in syncing context so 2867 * we can be sure that our trees will remain exactly 2868 * as we left them. 2869 */ 2870 mutex_exit(q_lock); 2871 suspended = scan_io_queue_issue(queue, &sio_list); 2872 mutex_enter(q_lock); 2873 2874 if (suspended) 2875 break; 2876 } 2877 /* update statistics for debugging purposes */ 2878 scan_io_queues_update_seg_stats(queue, seg_start, seg_end); 2879 2880 if (suspended) 2881 break; 2882 } 2883 2884 2885 /* 2886 * If we were suspended in the middle of processing, 2887 * requeue any unfinished sios and exit. 2888 */ 2889 while ((sio = list_head(&sio_list)) != NULL) { 2890 list_remove(&sio_list, sio); 2891 scan_io_queue_insert_impl(queue, sio); 2892 } 2893 2894 mutex_exit(q_lock); 2895 list_destroy(&sio_list); 2896 } 2897 2898 /* 2899 * Performs an emptying run on all scan queues in the pool. This just 2900 * punches out one thread per top-level vdev, each of which processes 2901 * only that vdev's scan queue. We can parallelize the I/O here because 2902 * we know that each queue's io's only affect its own top-level vdev. 2903 * 2904 * This function waits for the queue runs to complete, and must be 2905 * called from dsl_scan_sync (or in general, syncing context). 2906 */ 2907 static void 2908 scan_io_queues_run(dsl_scan_t *scn) 2909 { 2910 spa_t *spa = scn->scn_dp->dp_spa; 2911 2912 ASSERT(scn->scn_is_sorted); 2913 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER)); 2914 2915 if (scn->scn_bytes_pending == 0) 2916 return; 2917 2918 if (scn->scn_taskq == NULL) { 2919 char *tq_name = kmem_zalloc(ZFS_MAX_DATASET_NAME_LEN + 16, 2920 KM_SLEEP); 2921 int nthreads = spa->spa_root_vdev->vdev_children; 2922 2923 /* 2924 * We need to make this taskq *always* execute as many 2925 * threads in parallel as we have top-level vdevs and no 2926 * less, otherwise strange serialization of the calls to 2927 * scan_io_queues_run_one can occur during spa_sync runs 2928 * and that significantly impacts performance. 2929 */ 2930 (void) snprintf(tq_name, ZFS_MAX_DATASET_NAME_LEN + 16, 2931 "dsl_scan_tq_%s", spa->spa_name); 2932 scn->scn_taskq = taskq_create(tq_name, nthreads, minclsyspri, 2933 nthreads, nthreads, TASKQ_PREPOPULATE); 2934 kmem_free(tq_name, ZFS_MAX_DATASET_NAME_LEN + 16); 2935 } 2936 2937 for (uint64_t i = 0; i < spa->spa_root_vdev->vdev_children; i++) { 2938 vdev_t *vd = spa->spa_root_vdev->vdev_child[i]; 2939 2940 mutex_enter(&vd->vdev_scan_io_queue_lock); 2941 if (vd->vdev_scan_io_queue != NULL) { 2942 VERIFY(taskq_dispatch(scn->scn_taskq, 2943 scan_io_queues_run_one, vd->vdev_scan_io_queue, 2944 TQ_SLEEP) != TASKQID_INVALID); 2945 } 2946 mutex_exit(&vd->vdev_scan_io_queue_lock); 2947 } 2948 2949 /* 2950 * Wait for the queues to finish issuing thir IOs for this run 2951 * before we return. There may still be IOs in flight at this 2952 * point. 2953 */ 2954 taskq_wait(scn->scn_taskq); 2955 } 2956 2957 static boolean_t 2958 dsl_scan_async_block_should_pause(dsl_scan_t *scn) 2959 { 2960 uint64_t elapsed_nanosecs; 2961 2962 if (zfs_recover) 2963 return (B_FALSE); 2964 2965 if (scn->scn_visited_this_txg >= zfs_async_block_max_blocks) 2966 return (B_TRUE); 2967 2968 elapsed_nanosecs = gethrtime() - scn->scn_sync_start_time; 2969 return (elapsed_nanosecs / NANOSEC > zfs_txg_timeout || 2970 (NSEC2MSEC(elapsed_nanosecs) > scn->scn_async_block_min_time_ms && 2971 txg_sync_waiting(scn->scn_dp)) || 2972 spa_shutting_down(scn->scn_dp->dp_spa)); 2973 } 2974 2975 static int 2976 dsl_scan_free_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx) 2977 { 2978 dsl_scan_t *scn = arg; 2979 2980 if (!scn->scn_is_bptree || 2981 (BP_GET_LEVEL(bp) == 0 && BP_GET_TYPE(bp) != DMU_OT_OBJSET)) { 2982 if (dsl_scan_async_block_should_pause(scn)) 2983 return (SET_ERROR(ERESTART)); 2984 } 2985 2986 zio_nowait(zio_free_sync(scn->scn_zio_root, scn->scn_dp->dp_spa, 2987 dmu_tx_get_txg(tx), bp, 0)); 2988 dsl_dir_diduse_space(tx->tx_pool->dp_free_dir, DD_USED_HEAD, 2989 -bp_get_dsize_sync(scn->scn_dp->dp_spa, bp), 2990 -BP_GET_PSIZE(bp), -BP_GET_UCSIZE(bp), tx); 2991 scn->scn_visited_this_txg++; 2992 return (0); 2993 } 2994 2995 static void 2996 dsl_scan_update_stats(dsl_scan_t *scn) 2997 { 2998 spa_t *spa = scn->scn_dp->dp_spa; 2999 uint64_t i; 3000 uint64_t seg_size_total = 0, zio_size_total = 0; 3001 uint64_t seg_count_total = 0, zio_count_total = 0; 3002 3003 for (i = 0; i < spa->spa_root_vdev->vdev_children; i++) { 3004 vdev_t *vd = spa->spa_root_vdev->vdev_child[i]; 3005 dsl_scan_io_queue_t *queue = vd->vdev_scan_io_queue; 3006 3007 if (queue == NULL) 3008 continue; 3009 3010 seg_size_total += queue->q_total_seg_size_this_txg; 3011 zio_size_total += queue->q_total_zio_size_this_txg; 3012 seg_count_total += queue->q_segs_this_txg; 3013 zio_count_total += queue->q_zios_this_txg; 3014 } 3015 3016 if (seg_count_total == 0 || zio_count_total == 0) { 3017 scn->scn_avg_seg_size_this_txg = 0; 3018 scn->scn_avg_zio_size_this_txg = 0; 3019 scn->scn_segs_this_txg = 0; 3020 scn->scn_zios_this_txg = 0; 3021 return; 3022 } 3023 3024 scn->scn_avg_seg_size_this_txg = seg_size_total / seg_count_total; 3025 scn->scn_avg_zio_size_this_txg = zio_size_total / zio_count_total; 3026 scn->scn_segs_this_txg = seg_count_total; 3027 scn->scn_zios_this_txg = zio_count_total; 3028 } 3029 3030 static int 3031 dsl_scan_obsolete_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx) 3032 { 3033 dsl_scan_t *scn = arg; 3034 const dva_t *dva = &bp->blk_dva[0]; 3035 3036 if (dsl_scan_async_block_should_pause(scn)) 3037 return (SET_ERROR(ERESTART)); 3038 3039 spa_vdev_indirect_mark_obsolete(scn->scn_dp->dp_spa, 3040 DVA_GET_VDEV(dva), DVA_GET_OFFSET(dva), 3041 DVA_GET_ASIZE(dva), tx); 3042 scn->scn_visited_this_txg++; 3043 return (0); 3044 } 3045 3046 boolean_t 3047 dsl_scan_active(dsl_scan_t *scn) 3048 { 3049 spa_t *spa = scn->scn_dp->dp_spa; 3050 uint64_t used = 0, comp, uncomp; 3051 3052 if (spa->spa_load_state != SPA_LOAD_NONE) 3053 return (B_FALSE); 3054 if (spa_shutting_down(spa)) 3055 return (B_FALSE); 3056 if ((dsl_scan_is_running(scn) && !dsl_scan_is_paused_scrub(scn)) || 3057 (scn->scn_async_destroying && !scn->scn_async_stalled)) 3058 return (B_TRUE); 3059 3060 if (spa_version(scn->scn_dp->dp_spa) >= SPA_VERSION_DEADLISTS) { 3061 (void) bpobj_space(&scn->scn_dp->dp_free_bpobj, 3062 &used, &comp, &uncomp); 3063 } 3064 return (used != 0); 3065 } 3066 3067 static boolean_t 3068 dsl_scan_check_deferred(vdev_t *vd) 3069 { 3070 boolean_t need_resilver = B_FALSE; 3071 3072 for (int c = 0; c < vd->vdev_children; c++) { 3073 need_resilver |= 3074 dsl_scan_check_deferred(vd->vdev_child[c]); 3075 } 3076 3077 if (!vdev_is_concrete(vd) || vd->vdev_aux || 3078 !vd->vdev_ops->vdev_op_leaf) 3079 return (need_resilver); 3080 3081 if (!vd->vdev_resilver_deferred) 3082 need_resilver = B_TRUE; 3083 3084 return (need_resilver); 3085 } 3086 3087 static boolean_t 3088 dsl_scan_need_resilver(spa_t *spa, const dva_t *dva, size_t psize, 3089 uint64_t phys_birth) 3090 { 3091 vdev_t *vd; 3092 3093 vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva)); 3094 3095 if (vd->vdev_ops == &vdev_indirect_ops) { 3096 /* 3097 * The indirect vdev can point to multiple 3098 * vdevs. For simplicity, always create 3099 * the resilver zio_t. zio_vdev_io_start() 3100 * will bypass the child resilver i/o's if 3101 * they are on vdevs that don't have DTL's. 3102 */ 3103 return (B_TRUE); 3104 } 3105 3106 if (DVA_GET_GANG(dva)) { 3107 /* 3108 * Gang members may be spread across multiple 3109 * vdevs, so the best estimate we have is the 3110 * scrub range, which has already been checked. 3111 * XXX -- it would be better to change our 3112 * allocation policy to ensure that all 3113 * gang members reside on the same vdev. 3114 */ 3115 return (B_TRUE); 3116 } 3117 3118 /* 3119 * Check if the txg falls within the range which must be 3120 * resilvered. DVAs outside this range can always be skipped. 3121 */ 3122 if (!vdev_dtl_contains(vd, DTL_PARTIAL, phys_birth, 1)) 3123 return (B_FALSE); 3124 3125 /* 3126 * Check if the top-level vdev must resilver this offset. 3127 * When the offset does not intersect with a dirty leaf DTL 3128 * then it may be possible to skip the resilver IO. The psize 3129 * is provided instead of asize to simplify the check for RAIDZ. 3130 */ 3131 if (!vdev_dtl_need_resilver(vd, DVA_GET_OFFSET(dva), psize)) 3132 return (B_FALSE); 3133 3134 /* 3135 * Check that this top-level vdev has a device under it which 3136 * is resilvering and is not deferred. 3137 */ 3138 if (!dsl_scan_check_deferred(vd)) 3139 return (B_FALSE); 3140 3141 return (B_TRUE); 3142 } 3143 3144 static int 3145 dsl_process_async_destroys(dsl_pool_t *dp, dmu_tx_t *tx) 3146 { 3147 int err = 0; 3148 dsl_scan_t *scn = dp->dp_scan; 3149 spa_t *spa = dp->dp_spa; 3150 3151 if (spa_suspend_async_destroy(spa)) 3152 return (0); 3153 3154 if (zfs_free_bpobj_enabled && 3155 spa_version(spa) >= SPA_VERSION_DEADLISTS) { 3156 scn->scn_is_bptree = B_FALSE; 3157 scn->scn_async_block_min_time_ms = zfs_free_min_time_ms; 3158 scn->scn_zio_root = zio_root(spa, NULL, 3159 NULL, ZIO_FLAG_MUSTSUCCEED); 3160 err = bpobj_iterate(&dp->dp_free_bpobj, 3161 dsl_scan_free_block_cb, scn, tx); 3162 VERIFY0(zio_wait(scn->scn_zio_root)); 3163 scn->scn_zio_root = NULL; 3164 3165 if (err != 0 && err != ERESTART) 3166 zfs_panic_recover("error %u from bpobj_iterate()", err); 3167 } 3168 3169 if (err == 0 && spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) { 3170 ASSERT(scn->scn_async_destroying); 3171 scn->scn_is_bptree = B_TRUE; 3172 scn->scn_zio_root = zio_root(spa, NULL, 3173 NULL, ZIO_FLAG_MUSTSUCCEED); 3174 err = bptree_iterate(dp->dp_meta_objset, 3175 dp->dp_bptree_obj, B_TRUE, dsl_scan_free_block_cb, scn, tx); 3176 VERIFY0(zio_wait(scn->scn_zio_root)); 3177 scn->scn_zio_root = NULL; 3178 3179 if (err == EIO || err == ECKSUM) { 3180 err = 0; 3181 } else if (err != 0 && err != ERESTART) { 3182 zfs_panic_recover("error %u from " 3183 "traverse_dataset_destroyed()", err); 3184 } 3185 3186 if (bptree_is_empty(dp->dp_meta_objset, dp->dp_bptree_obj)) { 3187 /* finished; deactivate async destroy feature */ 3188 spa_feature_decr(spa, SPA_FEATURE_ASYNC_DESTROY, tx); 3189 ASSERT(!spa_feature_is_active(spa, 3190 SPA_FEATURE_ASYNC_DESTROY)); 3191 VERIFY0(zap_remove(dp->dp_meta_objset, 3192 DMU_POOL_DIRECTORY_OBJECT, 3193 DMU_POOL_BPTREE_OBJ, tx)); 3194 VERIFY0(bptree_free(dp->dp_meta_objset, 3195 dp->dp_bptree_obj, tx)); 3196 dp->dp_bptree_obj = 0; 3197 scn->scn_async_destroying = B_FALSE; 3198 scn->scn_async_stalled = B_FALSE; 3199 } else { 3200 /* 3201 * If we didn't make progress, mark the async 3202 * destroy as stalled, so that we will not initiate 3203 * a spa_sync() on its behalf. Note that we only 3204 * check this if we are not finished, because if the 3205 * bptree had no blocks for us to visit, we can 3206 * finish without "making progress". 3207 */ 3208 scn->scn_async_stalled = 3209 (scn->scn_visited_this_txg == 0); 3210 } 3211 } 3212 if (scn->scn_visited_this_txg) { 3213 zfs_dbgmsg("freed %llu blocks in %llums from " 3214 "free_bpobj/bptree txg %llu; err=%d", 3215 (longlong_t)scn->scn_visited_this_txg, 3216 (longlong_t) 3217 NSEC2MSEC(gethrtime() - scn->scn_sync_start_time), 3218 (longlong_t)tx->tx_txg, err); 3219 scn->scn_visited_this_txg = 0; 3220 3221 /* 3222 * Write out changes to the DDT that may be required as a 3223 * result of the blocks freed. This ensures that the DDT 3224 * is clean when a scrub/resilver runs. 3225 */ 3226 ddt_sync(spa, tx->tx_txg); 3227 } 3228 if (err != 0) 3229 return (err); 3230 if (dp->dp_free_dir != NULL && !scn->scn_async_destroying && 3231 zfs_free_leak_on_eio && 3232 (dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes != 0 || 3233 dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes != 0 || 3234 dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes != 0)) { 3235 /* 3236 * We have finished background destroying, but there is still 3237 * some space left in the dp_free_dir. Transfer this leaked 3238 * space to the dp_leak_dir. 3239 */ 3240 if (dp->dp_leak_dir == NULL) { 3241 rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG); 3242 (void) dsl_dir_create_sync(dp, dp->dp_root_dir, 3243 LEAK_DIR_NAME, tx); 3244 VERIFY0(dsl_pool_open_special_dir(dp, 3245 LEAK_DIR_NAME, &dp->dp_leak_dir)); 3246 rrw_exit(&dp->dp_config_rwlock, FTAG); 3247 } 3248 dsl_dir_diduse_space(dp->dp_leak_dir, DD_USED_HEAD, 3249 dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes, 3250 dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes, 3251 dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes, tx); 3252 dsl_dir_diduse_space(dp->dp_free_dir, DD_USED_HEAD, 3253 -dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes, 3254 -dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes, 3255 -dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes, tx); 3256 } 3257 3258 if (dp->dp_free_dir != NULL && !scn->scn_async_destroying) { 3259 /* finished; verify that space accounting went to zero */ 3260 ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes); 3261 ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes); 3262 ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes); 3263 } 3264 3265 EQUIV(bpobj_is_open(&dp->dp_obsolete_bpobj), 3266 0 == zap_contains(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT, 3267 DMU_POOL_OBSOLETE_BPOBJ)); 3268 if (err == 0 && bpobj_is_open(&dp->dp_obsolete_bpobj)) { 3269 ASSERT(spa_feature_is_active(dp->dp_spa, 3270 SPA_FEATURE_OBSOLETE_COUNTS)); 3271 3272 scn->scn_is_bptree = B_FALSE; 3273 scn->scn_async_block_min_time_ms = zfs_obsolete_min_time_ms; 3274 err = bpobj_iterate(&dp->dp_obsolete_bpobj, 3275 dsl_scan_obsolete_block_cb, scn, tx); 3276 if (err != 0 && err != ERESTART) 3277 zfs_panic_recover("error %u from bpobj_iterate()", err); 3278 3279 if (bpobj_is_empty(&dp->dp_obsolete_bpobj)) 3280 dsl_pool_destroy_obsolete_bpobj(dp, tx); 3281 } 3282 3283 return (0); 3284 } 3285 3286 /* 3287 * This is the primary entry point for scans that is called from syncing 3288 * context. Scans must happen entirely during syncing context so that we 3289 * cna guarantee that blocks we are currently scanning will not change out 3290 * from under us. While a scan is active, this funciton controls how quickly 3291 * transaction groups proceed, instead of the normal handling provided by 3292 * txg_sync_thread(). 3293 */ 3294 void 3295 dsl_scan_sync(dsl_pool_t *dp, dmu_tx_t *tx) 3296 { 3297 dsl_scan_t *scn = dp->dp_scan; 3298 spa_t *spa = dp->dp_spa; 3299 int err = 0; 3300 state_sync_type_t sync_type = SYNC_OPTIONAL; 3301 3302 if (spa->spa_resilver_deferred && 3303 !spa_feature_is_active(dp->dp_spa, SPA_FEATURE_RESILVER_DEFER)) 3304 spa_feature_incr(spa, SPA_FEATURE_RESILVER_DEFER, tx); 3305 3306 /* 3307 * Check for scn_restart_txg before checking spa_load_state, so 3308 * that we can restart an old-style scan while the pool is being 3309 * imported (see dsl_scan_init). We also restart scans if there 3310 * is a deferred resilver and the user has manually disabled 3311 * deferred resilvers via the tunable. 3312 */ 3313 if (dsl_scan_restarting(scn, tx) || 3314 (spa->spa_resilver_deferred && zfs_resilver_disable_defer)) { 3315 pool_scan_func_t func = POOL_SCAN_SCRUB; 3316 dsl_scan_done(scn, B_FALSE, tx); 3317 if (vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL)) 3318 func = POOL_SCAN_RESILVER; 3319 zfs_dbgmsg("restarting scan func=%u txg=%llu", 3320 func, (longlong_t)tx->tx_txg); 3321 dsl_scan_setup_sync(&func, tx); 3322 } 3323 3324 /* 3325 * Only process scans in sync pass 1. 3326 */ 3327 if (spa_sync_pass(dp->dp_spa) > 1) 3328 return; 3329 3330 /* 3331 * If the spa is shutting down, then stop scanning. This will 3332 * ensure that the scan does not dirty any new data during the 3333 * shutdown phase. 3334 */ 3335 if (spa_shutting_down(spa)) 3336 return; 3337 3338 /* 3339 * If the scan is inactive due to a stalled async destroy, try again. 3340 */ 3341 if (!scn->scn_async_stalled && !dsl_scan_active(scn)) 3342 return; 3343 3344 /* reset scan statistics */ 3345 scn->scn_visited_this_txg = 0; 3346 scn->scn_holes_this_txg = 0; 3347 scn->scn_lt_min_this_txg = 0; 3348 scn->scn_gt_max_this_txg = 0; 3349 scn->scn_ddt_contained_this_txg = 0; 3350 scn->scn_objsets_visited_this_txg = 0; 3351 scn->scn_avg_seg_size_this_txg = 0; 3352 scn->scn_segs_this_txg = 0; 3353 scn->scn_avg_zio_size_this_txg = 0; 3354 scn->scn_zios_this_txg = 0; 3355 scn->scn_suspending = B_FALSE; 3356 scn->scn_sync_start_time = gethrtime(); 3357 spa->spa_scrub_active = B_TRUE; 3358 3359 /* 3360 * First process the async destroys. If we pause, don't do 3361 * any scrubbing or resilvering. This ensures that there are no 3362 * async destroys while we are scanning, so the scan code doesn't 3363 * have to worry about traversing it. It is also faster to free the 3364 * blocks than to scrub them. 3365 */ 3366 err = dsl_process_async_destroys(dp, tx); 3367 if (err != 0) 3368 return; 3369 3370 if (!dsl_scan_is_running(scn) || dsl_scan_is_paused_scrub(scn)) 3371 return; 3372 3373 /* 3374 * Wait a few txgs after importing to begin scanning so that 3375 * we can get the pool imported quickly. 3376 */ 3377 if (spa->spa_syncing_txg < spa->spa_first_txg + SCAN_IMPORT_WAIT_TXGS) 3378 return; 3379 3380 /* 3381 * zfs_scan_suspend_progress can be set to disable scan progress. 3382 * We don't want to spin the txg_sync thread, so we add a delay 3383 * here to simulate the time spent doing a scan. This is mostly 3384 * useful for testing and debugging. 3385 */ 3386 if (zfs_scan_suspend_progress) { 3387 uint64_t scan_time_ns = gethrtime() - scn->scn_sync_start_time; 3388 int mintime = (scn->scn_phys.scn_func == POOL_SCAN_RESILVER) ? 3389 zfs_resilver_min_time_ms : zfs_scrub_min_time_ms; 3390 3391 while (zfs_scan_suspend_progress && 3392 !txg_sync_waiting(scn->scn_dp) && 3393 !spa_shutting_down(scn->scn_dp->dp_spa) && 3394 NSEC2MSEC(scan_time_ns) < mintime) { 3395 delay(hz); 3396 scan_time_ns = gethrtime() - scn->scn_sync_start_time; 3397 } 3398 return; 3399 } 3400 3401 /* 3402 * It is possible to switch from unsorted to sorted at any time, 3403 * but afterwards the scan will remain sorted unless reloaded from 3404 * a checkpoint after a reboot. 3405 */ 3406 if (!zfs_scan_legacy) { 3407 scn->scn_is_sorted = B_TRUE; 3408 if (scn->scn_last_checkpoint == 0) 3409 scn->scn_last_checkpoint = ddi_get_lbolt(); 3410 } 3411 3412 /* 3413 * For sorted scans, determine what kind of work we will be doing 3414 * this txg based on our memory limitations and whether or not we 3415 * need to perform a checkpoint. 3416 */ 3417 if (scn->scn_is_sorted) { 3418 /* 3419 * If we are over our checkpoint interval, set scn_clearing 3420 * so that we can begin checkpointing immediately. The 3421 * checkpoint allows us to save a consisent bookmark 3422 * representing how much data we have scrubbed so far. 3423 * Otherwise, use the memory limit to determine if we should 3424 * scan for metadata or start issue scrub IOs. We accumulate 3425 * metadata until we hit our hard memory limit at which point 3426 * we issue scrub IOs until we are at our soft memory limit. 3427 */ 3428 if (scn->scn_checkpointing || 3429 ddi_get_lbolt() - scn->scn_last_checkpoint > 3430 SEC_TO_TICK(zfs_scan_checkpoint_intval)) { 3431 if (!scn->scn_checkpointing) 3432 zfs_dbgmsg("begin scan checkpoint"); 3433 3434 scn->scn_checkpointing = B_TRUE; 3435 scn->scn_clearing = B_TRUE; 3436 } else { 3437 boolean_t should_clear = dsl_scan_should_clear(scn); 3438 if (should_clear && !scn->scn_clearing) { 3439 zfs_dbgmsg("begin scan clearing"); 3440 scn->scn_clearing = B_TRUE; 3441 } else if (!should_clear && scn->scn_clearing) { 3442 zfs_dbgmsg("finish scan clearing"); 3443 scn->scn_clearing = B_FALSE; 3444 } 3445 } 3446 } else { 3447 ASSERT0(scn->scn_checkpointing); 3448 ASSERT0(scn->scn_clearing); 3449 } 3450 3451 if (!scn->scn_clearing && scn->scn_done_txg == 0) { 3452 /* Need to scan metadata for more blocks to scrub */ 3453 dsl_scan_phys_t *scnp = &scn->scn_phys; 3454 taskqid_t prefetch_tqid; 3455 uint64_t bytes_per_leaf = zfs_scan_vdev_limit; 3456 uint64_t nr_leaves = dsl_scan_count_leaves(spa->spa_root_vdev); 3457 3458 /* 3459 * Calculate the max number of in-flight bytes for pool-wide 3460 * scanning operations (minimum 1MB). Limits for the issuing 3461 * phase are done per top-level vdev and are handled separately. 3462 */ 3463 scn->scn_maxinflight_bytes = 3464 MAX(nr_leaves * bytes_per_leaf, 1ULL << 20); 3465 3466 if (scnp->scn_ddt_bookmark.ddb_class <= 3467 scnp->scn_ddt_class_max) { 3468 ASSERT(ZB_IS_ZERO(&scnp->scn_bookmark)); 3469 zfs_dbgmsg("doing scan sync txg %llu; " 3470 "ddt bm=%llu/%llu/%llu/%llx", 3471 (longlong_t)tx->tx_txg, 3472 (longlong_t)scnp->scn_ddt_bookmark.ddb_class, 3473 (longlong_t)scnp->scn_ddt_bookmark.ddb_type, 3474 (longlong_t)scnp->scn_ddt_bookmark.ddb_checksum, 3475 (longlong_t)scnp->scn_ddt_bookmark.ddb_cursor); 3476 } else { 3477 zfs_dbgmsg("doing scan sync txg %llu; " 3478 "bm=%llu/%llu/%llu/%llu", 3479 (longlong_t)tx->tx_txg, 3480 (longlong_t)scnp->scn_bookmark.zb_objset, 3481 (longlong_t)scnp->scn_bookmark.zb_object, 3482 (longlong_t)scnp->scn_bookmark.zb_level, 3483 (longlong_t)scnp->scn_bookmark.zb_blkid); 3484 } 3485 3486 scn->scn_zio_root = zio_root(dp->dp_spa, NULL, 3487 NULL, ZIO_FLAG_CANFAIL); 3488 3489 scn->scn_prefetch_stop = B_FALSE; 3490 prefetch_tqid = taskq_dispatch(dp->dp_sync_taskq, 3491 dsl_scan_prefetch_thread, scn, TQ_SLEEP); 3492 ASSERT(prefetch_tqid != TASKQID_INVALID); 3493 3494 dsl_pool_config_enter(dp, FTAG); 3495 dsl_scan_visit(scn, tx); 3496 dsl_pool_config_exit(dp, FTAG); 3497 3498 mutex_enter(&dp->dp_spa->spa_scrub_lock); 3499 scn->scn_prefetch_stop = B_TRUE; 3500 cv_broadcast(&spa->spa_scrub_io_cv); 3501 mutex_exit(&dp->dp_spa->spa_scrub_lock); 3502 3503 taskq_wait_id(dp->dp_sync_taskq, prefetch_tqid); 3504 (void) zio_wait(scn->scn_zio_root); 3505 scn->scn_zio_root = NULL; 3506 3507 zfs_dbgmsg("scan visited %llu blocks in %llums " 3508 "(%llu os's, %llu holes, %llu < mintxg, " 3509 "%llu in ddt, %llu > maxtxg)", 3510 (longlong_t)scn->scn_visited_this_txg, 3511 (longlong_t)NSEC2MSEC(gethrtime() - 3512 scn->scn_sync_start_time), 3513 (longlong_t)scn->scn_objsets_visited_this_txg, 3514 (longlong_t)scn->scn_holes_this_txg, 3515 (longlong_t)scn->scn_lt_min_this_txg, 3516 (longlong_t)scn->scn_ddt_contained_this_txg, 3517 (longlong_t)scn->scn_gt_max_this_txg); 3518 3519 if (!scn->scn_suspending) { 3520 ASSERT0(avl_numnodes(&scn->scn_queue)); 3521 scn->scn_done_txg = tx->tx_txg + 1; 3522 if (scn->scn_is_sorted) { 3523 scn->scn_checkpointing = B_TRUE; 3524 scn->scn_clearing = B_TRUE; 3525 } 3526 zfs_dbgmsg("scan complete txg %llu", 3527 (longlong_t)tx->tx_txg); 3528 } 3529 } else if (scn->scn_is_sorted && scn->scn_bytes_pending != 0) { 3530 ASSERT(scn->scn_clearing); 3531 3532 /* need to issue scrubbing IOs from per-vdev queues */ 3533 scn->scn_zio_root = zio_root(dp->dp_spa, NULL, 3534 NULL, ZIO_FLAG_CANFAIL); 3535 scan_io_queues_run(scn); 3536 (void) zio_wait(scn->scn_zio_root); 3537 scn->scn_zio_root = NULL; 3538 3539 /* calculate and dprintf the current memory usage */ 3540 (void) dsl_scan_should_clear(scn); 3541 dsl_scan_update_stats(scn); 3542 3543 zfs_dbgmsg("scrubbed %llu blocks (%llu segs) in %llums " 3544 "(avg_block_size = %llu, avg_seg_size = %llu)", 3545 (longlong_t)scn->scn_zios_this_txg, 3546 (longlong_t)scn->scn_segs_this_txg, 3547 (longlong_t)NSEC2MSEC(gethrtime() - 3548 scn->scn_sync_start_time), 3549 (longlong_t)scn->scn_avg_zio_size_this_txg, 3550 (longlong_t)scn->scn_avg_seg_size_this_txg); 3551 } else if (scn->scn_done_txg != 0 && scn->scn_done_txg <= tx->tx_txg) { 3552 /* Finished with everything. Mark the scrub as complete */ 3553 zfs_dbgmsg("scan issuing complete txg %llu", 3554 (longlong_t)tx->tx_txg); 3555 ASSERT3U(scn->scn_done_txg, !=, 0); 3556 ASSERT0(spa->spa_scrub_inflight); 3557 ASSERT0(scn->scn_bytes_pending); 3558 dsl_scan_done(scn, B_TRUE, tx); 3559 sync_type = SYNC_MANDATORY; 3560 } 3561 3562 dsl_scan_sync_state(scn, tx, sync_type); 3563 } 3564 3565 static void 3566 count_block(dsl_scan_t *scn, zfs_all_blkstats_t *zab, const blkptr_t *bp) 3567 { 3568 int i; 3569 3570 /* 3571 * Don't count embedded bp's, since we already did the work of 3572 * scanning these when we scanned the containing block. 3573 */ 3574 if (BP_IS_EMBEDDED(bp)) 3575 return; 3576 3577 /* 3578 * Update the spa's stats on how many bytes we have issued. 3579 * Sequential scrubs create a zio for each DVA of the bp. Each 3580 * of these will include all DVAs for repair purposes, but the 3581 * zio code will only try the first one unless there is an issue. 3582 * Therefore, we should only count the first DVA for these IOs. 3583 */ 3584 if (scn->scn_is_sorted) { 3585 atomic_add_64(&scn->scn_dp->dp_spa->spa_scan_pass_issued, 3586 DVA_GET_ASIZE(&bp->blk_dva[0])); 3587 } else { 3588 spa_t *spa = scn->scn_dp->dp_spa; 3589 3590 for (i = 0; i < BP_GET_NDVAS(bp); i++) { 3591 atomic_add_64(&spa->spa_scan_pass_issued, 3592 DVA_GET_ASIZE(&bp->blk_dva[i])); 3593 } 3594 } 3595 3596 /* 3597 * If we resume after a reboot, zab will be NULL; don't record 3598 * incomplete stats in that case. 3599 */ 3600 if (zab == NULL) 3601 return; 3602 3603 mutex_enter(&zab->zab_lock); 3604 3605 for (i = 0; i < 4; i++) { 3606 int l = (i < 2) ? BP_GET_LEVEL(bp) : DN_MAX_LEVELS; 3607 int t = (i & 1) ? BP_GET_TYPE(bp) : DMU_OT_TOTAL; 3608 if (t & DMU_OT_NEWTYPE) 3609 t = DMU_OT_OTHER; 3610 zfs_blkstat_t *zb = &zab->zab_type[l][t]; 3611 int equal; 3612 3613 zb->zb_count++; 3614 zb->zb_asize += BP_GET_ASIZE(bp); 3615 zb->zb_lsize += BP_GET_LSIZE(bp); 3616 zb->zb_psize += BP_GET_PSIZE(bp); 3617 zb->zb_gangs += BP_COUNT_GANG(bp); 3618 3619 switch (BP_GET_NDVAS(bp)) { 3620 case 2: 3621 if (DVA_GET_VDEV(&bp->blk_dva[0]) == 3622 DVA_GET_VDEV(&bp->blk_dva[1])) 3623 zb->zb_ditto_2_of_2_samevdev++; 3624 break; 3625 case 3: 3626 equal = (DVA_GET_VDEV(&bp->blk_dva[0]) == 3627 DVA_GET_VDEV(&bp->blk_dva[1])) + 3628 (DVA_GET_VDEV(&bp->blk_dva[0]) == 3629 DVA_GET_VDEV(&bp->blk_dva[2])) + 3630 (DVA_GET_VDEV(&bp->blk_dva[1]) == 3631 DVA_GET_VDEV(&bp->blk_dva[2])); 3632 if (equal == 1) 3633 zb->zb_ditto_2_of_3_samevdev++; 3634 else if (equal == 3) 3635 zb->zb_ditto_3_of_3_samevdev++; 3636 break; 3637 } 3638 } 3639 3640 mutex_exit(&zab->zab_lock); 3641 } 3642 3643 static void 3644 scan_io_queue_insert_impl(dsl_scan_io_queue_t *queue, scan_io_t *sio) 3645 { 3646 avl_index_t idx; 3647 int64_t asize = SIO_GET_ASIZE(sio); 3648 dsl_scan_t *scn = queue->q_scn; 3649 3650 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock)); 3651 3652 if (avl_find(&queue->q_sios_by_addr, sio, &idx) != NULL) { 3653 /* block is already scheduled for reading */ 3654 atomic_add_64(&scn->scn_bytes_pending, -asize); 3655 sio_free(sio); 3656 return; 3657 } 3658 avl_insert(&queue->q_sios_by_addr, sio, idx); 3659 queue->q_sio_memused += SIO_GET_MUSED(sio); 3660 range_tree_add(queue->q_exts_by_addr, SIO_GET_OFFSET(sio), asize); 3661 } 3662 3663 /* 3664 * Given all the info we got from our metadata scanning process, we 3665 * construct a scan_io_t and insert it into the scan sorting queue. The 3666 * I/O must already be suitable for us to process. This is controlled 3667 * by dsl_scan_enqueue(). 3668 */ 3669 static void 3670 scan_io_queue_insert(dsl_scan_io_queue_t *queue, const blkptr_t *bp, int dva_i, 3671 int zio_flags, const zbookmark_phys_t *zb) 3672 { 3673 dsl_scan_t *scn = queue->q_scn; 3674 scan_io_t *sio = sio_alloc(BP_GET_NDVAS(bp)); 3675 3676 ASSERT0(BP_IS_GANG(bp)); 3677 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock)); 3678 3679 bp2sio(bp, sio, dva_i); 3680 sio->sio_flags = zio_flags; 3681 sio->sio_zb = *zb; 3682 3683 /* 3684 * Increment the bytes pending counter now so that we can't 3685 * get an integer underflow in case the worker processes the 3686 * zio before we get to incrementing this counter. 3687 */ 3688 atomic_add_64(&scn->scn_bytes_pending, SIO_GET_ASIZE(sio)); 3689 3690 scan_io_queue_insert_impl(queue, sio); 3691 } 3692 3693 /* 3694 * Given a set of I/O parameters as discovered by the metadata traversal 3695 * process, attempts to place the I/O into the sorted queues (if allowed), 3696 * or immediately executes the I/O. 3697 */ 3698 static void 3699 dsl_scan_enqueue(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags, 3700 const zbookmark_phys_t *zb) 3701 { 3702 spa_t *spa = dp->dp_spa; 3703 3704 ASSERT(!BP_IS_EMBEDDED(bp)); 3705 3706 /* 3707 * Gang blocks are hard to issue sequentially, so we just issue them 3708 * here immediately instead of queuing them. 3709 */ 3710 if (!dp->dp_scan->scn_is_sorted || BP_IS_GANG(bp)) { 3711 scan_exec_io(dp, bp, zio_flags, zb, NULL); 3712 return; 3713 } 3714 for (int i = 0; i < BP_GET_NDVAS(bp); i++) { 3715 dva_t dva; 3716 vdev_t *vdev; 3717 3718 dva = bp->blk_dva[i]; 3719 vdev = vdev_lookup_top(spa, DVA_GET_VDEV(&dva)); 3720 ASSERT(vdev != NULL); 3721 3722 mutex_enter(&vdev->vdev_scan_io_queue_lock); 3723 if (vdev->vdev_scan_io_queue == NULL) 3724 vdev->vdev_scan_io_queue = scan_io_queue_create(vdev); 3725 ASSERT(dp->dp_scan != NULL); 3726 scan_io_queue_insert(vdev->vdev_scan_io_queue, bp, 3727 i, zio_flags, zb); 3728 mutex_exit(&vdev->vdev_scan_io_queue_lock); 3729 } 3730 } 3731 3732 static int 3733 dsl_scan_scrub_cb(dsl_pool_t *dp, 3734 const blkptr_t *bp, const zbookmark_phys_t *zb) 3735 { 3736 dsl_scan_t *scn = dp->dp_scan; 3737 spa_t *spa = dp->dp_spa; 3738 uint64_t phys_birth = BP_PHYSICAL_BIRTH(bp); 3739 size_t psize = BP_GET_PSIZE(bp); 3740 boolean_t needs_io; 3741 int zio_flags = ZIO_FLAG_SCAN_THREAD | ZIO_FLAG_RAW | ZIO_FLAG_CANFAIL; 3742 int d; 3743 3744 if (phys_birth <= scn->scn_phys.scn_min_txg || 3745 phys_birth >= scn->scn_phys.scn_max_txg) { 3746 count_block(scn, dp->dp_blkstats, bp); 3747 return (0); 3748 } 3749 3750 /* Embedded BP's have phys_birth==0, so we reject them above. */ 3751 ASSERT(!BP_IS_EMBEDDED(bp)); 3752 3753 ASSERT(DSL_SCAN_IS_SCRUB_RESILVER(scn)); 3754 if (scn->scn_phys.scn_func == POOL_SCAN_SCRUB) { 3755 zio_flags |= ZIO_FLAG_SCRUB; 3756 needs_io = B_TRUE; 3757 } else { 3758 ASSERT3U(scn->scn_phys.scn_func, ==, POOL_SCAN_RESILVER); 3759 zio_flags |= ZIO_FLAG_RESILVER; 3760 needs_io = B_FALSE; 3761 } 3762 3763 /* If it's an intent log block, failure is expected. */ 3764 if (zb->zb_level == ZB_ZIL_LEVEL) 3765 zio_flags |= ZIO_FLAG_SPECULATIVE; 3766 3767 for (d = 0; d < BP_GET_NDVAS(bp); d++) { 3768 const dva_t *dva = &bp->blk_dva[d]; 3769 3770 /* 3771 * Keep track of how much data we've examined so that 3772 * zpool(1M) status can make useful progress reports. 3773 */ 3774 scn->scn_phys.scn_examined += DVA_GET_ASIZE(dva); 3775 spa->spa_scan_pass_exam += DVA_GET_ASIZE(dva); 3776 3777 /* if it's a resilver, this may not be in the target range */ 3778 if (!needs_io) 3779 needs_io = dsl_scan_need_resilver(spa, dva, psize, 3780 phys_birth); 3781 } 3782 3783 if (needs_io && !zfs_no_scrub_io) { 3784 dsl_scan_enqueue(dp, bp, zio_flags, zb); 3785 } else { 3786 count_block(scn, dp->dp_blkstats, bp); 3787 } 3788 3789 /* do not relocate this block */ 3790 return (0); 3791 } 3792 3793 static void 3794 dsl_scan_scrub_done(zio_t *zio) 3795 { 3796 spa_t *spa = zio->io_spa; 3797 blkptr_t *bp = zio->io_bp; 3798 dsl_scan_io_queue_t *queue = zio->io_private; 3799 3800 abd_free(zio->io_abd); 3801 3802 if (queue == NULL) { 3803 mutex_enter(&spa->spa_scrub_lock); 3804 ASSERT3U(spa->spa_scrub_inflight, >=, BP_GET_PSIZE(bp)); 3805 spa->spa_scrub_inflight -= BP_GET_PSIZE(bp); 3806 cv_broadcast(&spa->spa_scrub_io_cv); 3807 mutex_exit(&spa->spa_scrub_lock); 3808 } else { 3809 mutex_enter(&queue->q_vd->vdev_scan_io_queue_lock); 3810 ASSERT3U(queue->q_inflight_bytes, >=, BP_GET_PSIZE(bp)); 3811 queue->q_inflight_bytes -= BP_GET_PSIZE(bp); 3812 cv_broadcast(&queue->q_zio_cv); 3813 mutex_exit(&queue->q_vd->vdev_scan_io_queue_lock); 3814 } 3815 3816 if (zio->io_error && (zio->io_error != ECKSUM || 3817 !(zio->io_flags & ZIO_FLAG_SPECULATIVE))) { 3818 atomic_inc_64(&spa->spa_dsl_pool->dp_scan->scn_phys.scn_errors); 3819 } 3820 } 3821 3822 /* 3823 * Given a scanning zio's information, executes the zio. The zio need 3824 * not necessarily be only sortable, this function simply executes the 3825 * zio, no matter what it is. The optional queue argument allows the 3826 * caller to specify that they want per top level vdev IO rate limiting 3827 * instead of the legacy global limiting. 3828 */ 3829 static void 3830 scan_exec_io(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags, 3831 const zbookmark_phys_t *zb, dsl_scan_io_queue_t *queue) 3832 { 3833 spa_t *spa = dp->dp_spa; 3834 dsl_scan_t *scn = dp->dp_scan; 3835 size_t size = BP_GET_PSIZE(bp); 3836 abd_t *data = abd_alloc_for_io(size, B_FALSE); 3837 3838 if (queue == NULL) { 3839 mutex_enter(&spa->spa_scrub_lock); 3840 while (spa->spa_scrub_inflight >= scn->scn_maxinflight_bytes) 3841 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock); 3842 spa->spa_scrub_inflight += BP_GET_PSIZE(bp); 3843 mutex_exit(&spa->spa_scrub_lock); 3844 } else { 3845 kmutex_t *q_lock = &queue->q_vd->vdev_scan_io_queue_lock; 3846 3847 mutex_enter(q_lock); 3848 while (queue->q_inflight_bytes >= queue->q_maxinflight_bytes) 3849 cv_wait(&queue->q_zio_cv, q_lock); 3850 queue->q_inflight_bytes += BP_GET_PSIZE(bp); 3851 mutex_exit(q_lock); 3852 } 3853 3854 count_block(dp->dp_scan, dp->dp_blkstats, bp); 3855 zio_nowait(zio_read(dp->dp_scan->scn_zio_root, spa, bp, data, size, 3856 dsl_scan_scrub_done, queue, ZIO_PRIORITY_SCRUB, zio_flags, zb)); 3857 } 3858 3859 /* 3860 * This is the primary extent sorting algorithm. We balance two parameters: 3861 * 1) how many bytes of I/O are in an extent 3862 * 2) how well the extent is filled with I/O (as a fraction of its total size) 3863 * Since we allow extents to have gaps between their constituent I/Os, it's 3864 * possible to have a fairly large extent that contains the same amount of 3865 * I/O bytes than a much smaller extent, which just packs the I/O more tightly. 3866 * The algorithm sorts based on a score calculated from the extent's size, 3867 * the relative fill volume (in %) and a "fill weight" parameter that controls 3868 * the split between whether we prefer larger extents or more well populated 3869 * extents: 3870 * 3871 * SCORE = FILL_IN_BYTES + (FILL_IN_PERCENT * FILL_IN_BYTES * FILL_WEIGHT) 3872 * 3873 * Example: 3874 * 1) assume extsz = 64 MiB 3875 * 2) assume fill = 32 MiB (extent is half full) 3876 * 3) assume fill_weight = 3 3877 * 4) SCORE = 32M + (((32M * 100) / 64M) * 3 * 32M) / 100 3878 * SCORE = 32M + (50 * 3 * 32M) / 100 3879 * SCORE = 32M + (4800M / 100) 3880 * SCORE = 32M + 48M 3881 * ^ ^ 3882 * | +--- final total relative fill-based score 3883 * +--------- final total fill-based score 3884 * SCORE = 80M 3885 * 3886 * As can be seen, at fill_ratio=3, the algorithm is slightly biased towards 3887 * extents that are more completely filled (in a 3:2 ratio) vs just larger. 3888 * Note that as an optimization, we replace multiplication and division by 3889 * 100 with bitshifting by 7 (which effecitvely multiplies and divides by 128). 3890 */ 3891 static int 3892 ext_size_compare(const void *x, const void *y) 3893 { 3894 const range_seg_t *rsa = x, *rsb = y; 3895 uint64_t sa = rsa->rs_end - rsa->rs_start, 3896 sb = rsb->rs_end - rsb->rs_start; 3897 uint64_t score_a, score_b; 3898 3899 score_a = rsa->rs_fill + ((((rsa->rs_fill << 7) / sa) * 3900 fill_weight * rsa->rs_fill) >> 7); 3901 score_b = rsb->rs_fill + ((((rsb->rs_fill << 7) / sb) * 3902 fill_weight * rsb->rs_fill) >> 7); 3903 3904 if (score_a > score_b) 3905 return (-1); 3906 if (score_a == score_b) { 3907 if (rsa->rs_start < rsb->rs_start) 3908 return (-1); 3909 if (rsa->rs_start == rsb->rs_start) 3910 return (0); 3911 return (1); 3912 } 3913 return (1); 3914 } 3915 3916 /* 3917 * Comparator for the q_sios_by_addr tree. Sorting is simply performed 3918 * based on LBA-order (from lowest to highest). 3919 */ 3920 static int 3921 sio_addr_compare(const void *x, const void *y) 3922 { 3923 const scan_io_t *a = x, *b = y; 3924 3925 return (AVL_CMP(SIO_GET_OFFSET(a), SIO_GET_OFFSET(b))); 3926 } 3927 3928 /* IO queues are created on demand when they are needed. */ 3929 static dsl_scan_io_queue_t * 3930 scan_io_queue_create(vdev_t *vd) 3931 { 3932 dsl_scan_t *scn = vd->vdev_spa->spa_dsl_pool->dp_scan; 3933 dsl_scan_io_queue_t *q = kmem_zalloc(sizeof (*q), KM_SLEEP); 3934 3935 q->q_scn = scn; 3936 q->q_vd = vd; 3937 q->q_sio_memused = 0; 3938 cv_init(&q->q_zio_cv, NULL, CV_DEFAULT, NULL); 3939 q->q_exts_by_addr = range_tree_create_impl(&rt_avl_ops, 3940 &q->q_exts_by_size, ext_size_compare, zfs_scan_max_ext_gap); 3941 avl_create(&q->q_sios_by_addr, sio_addr_compare, 3942 sizeof (scan_io_t), offsetof(scan_io_t, sio_nodes.sio_addr_node)); 3943 3944 return (q); 3945 } 3946 3947 /* 3948 * Destroys a scan queue and all segments and scan_io_t's contained in it. 3949 * No further execution of I/O occurs, anything pending in the queue is 3950 * simply freed without being executed. 3951 */ 3952 void 3953 dsl_scan_io_queue_destroy(dsl_scan_io_queue_t *queue) 3954 { 3955 dsl_scan_t *scn = queue->q_scn; 3956 scan_io_t *sio; 3957 void *cookie = NULL; 3958 int64_t bytes_dequeued = 0; 3959 3960 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock)); 3961 3962 while ((sio = avl_destroy_nodes(&queue->q_sios_by_addr, &cookie)) != 3963 NULL) { 3964 ASSERT(range_tree_contains(queue->q_exts_by_addr, 3965 SIO_GET_OFFSET(sio), SIO_GET_ASIZE(sio))); 3966 bytes_dequeued += SIO_GET_ASIZE(sio); 3967 queue->q_sio_memused -= SIO_GET_MUSED(sio); 3968 sio_free(sio); 3969 } 3970 3971 ASSERT0(queue->q_sio_memused); 3972 atomic_add_64(&scn->scn_bytes_pending, -bytes_dequeued); 3973 range_tree_vacate(queue->q_exts_by_addr, NULL, queue); 3974 range_tree_destroy(queue->q_exts_by_addr); 3975 avl_destroy(&queue->q_sios_by_addr); 3976 cv_destroy(&queue->q_zio_cv); 3977 3978 kmem_free(queue, sizeof (*queue)); 3979 } 3980 3981 /* 3982 * Properly transfers a dsl_scan_queue_t from `svd' to `tvd'. This is 3983 * called on behalf of vdev_top_transfer when creating or destroying 3984 * a mirror vdev due to zpool attach/detach. 3985 */ 3986 void 3987 dsl_scan_io_queue_vdev_xfer(vdev_t *svd, vdev_t *tvd) 3988 { 3989 mutex_enter(&svd->vdev_scan_io_queue_lock); 3990 mutex_enter(&tvd->vdev_scan_io_queue_lock); 3991 3992 VERIFY3P(tvd->vdev_scan_io_queue, ==, NULL); 3993 tvd->vdev_scan_io_queue = svd->vdev_scan_io_queue; 3994 svd->vdev_scan_io_queue = NULL; 3995 if (tvd->vdev_scan_io_queue != NULL) 3996 tvd->vdev_scan_io_queue->q_vd = tvd; 3997 3998 mutex_exit(&tvd->vdev_scan_io_queue_lock); 3999 mutex_exit(&svd->vdev_scan_io_queue_lock); 4000 } 4001 4002 static void 4003 scan_io_queues_destroy(dsl_scan_t *scn) 4004 { 4005 vdev_t *rvd = scn->scn_dp->dp_spa->spa_root_vdev; 4006 4007 for (uint64_t i = 0; i < rvd->vdev_children; i++) { 4008 vdev_t *tvd = rvd->vdev_child[i]; 4009 4010 mutex_enter(&tvd->vdev_scan_io_queue_lock); 4011 if (tvd->vdev_scan_io_queue != NULL) 4012 dsl_scan_io_queue_destroy(tvd->vdev_scan_io_queue); 4013 tvd->vdev_scan_io_queue = NULL; 4014 mutex_exit(&tvd->vdev_scan_io_queue_lock); 4015 } 4016 } 4017 4018 static void 4019 dsl_scan_freed_dva(spa_t *spa, const blkptr_t *bp, int dva_i) 4020 { 4021 dsl_pool_t *dp = spa->spa_dsl_pool; 4022 dsl_scan_t *scn = dp->dp_scan; 4023 vdev_t *vdev; 4024 kmutex_t *q_lock; 4025 dsl_scan_io_queue_t *queue; 4026 scan_io_t *srch_sio, *sio; 4027 avl_index_t idx; 4028 uint64_t start, size; 4029 4030 vdev = vdev_lookup_top(spa, DVA_GET_VDEV(&bp->blk_dva[dva_i])); 4031 ASSERT(vdev != NULL); 4032 q_lock = &vdev->vdev_scan_io_queue_lock; 4033 queue = vdev->vdev_scan_io_queue; 4034 4035 mutex_enter(q_lock); 4036 if (queue == NULL) { 4037 mutex_exit(q_lock); 4038 return; 4039 } 4040 4041 srch_sio = sio_alloc(BP_GET_NDVAS(bp)); 4042 bp2sio(bp, srch_sio, dva_i); 4043 start = SIO_GET_OFFSET(srch_sio); 4044 size = SIO_GET_ASIZE(srch_sio); 4045 4046 /* 4047 * We can find the zio in two states: 4048 * 1) Cold, just sitting in the queue of zio's to be issued at 4049 * some point in the future. In this case, all we do is 4050 * remove the zio from the q_sios_by_addr tree, decrement 4051 * its data volume from the containing range_seg_t and 4052 * resort the q_exts_by_size tree to reflect that the 4053 * range_seg_t has lost some of its 'fill'. We don't shorten 4054 * the range_seg_t - this is usually rare enough not to be 4055 * worth the extra hassle of trying keep track of precise 4056 * extent boundaries. 4057 * 2) Hot, where the zio is currently in-flight in 4058 * dsl_scan_issue_ios. In this case, we can't simply 4059 * reach in and stop the in-flight zio's, so we instead 4060 * block the caller. Eventually, dsl_scan_issue_ios will 4061 * be done with issuing the zio's it gathered and will 4062 * signal us. 4063 */ 4064 sio = avl_find(&queue->q_sios_by_addr, srch_sio, &idx); 4065 sio_free(srch_sio); 4066 4067 if (sio != NULL) { 4068 int64_t asize = SIO_GET_ASIZE(sio); 4069 blkptr_t tmpbp; 4070 4071 /* Got it while it was cold in the queue */ 4072 ASSERT3U(start, ==, SIO_GET_OFFSET(sio)); 4073 ASSERT3U(size, ==, asize); 4074 avl_remove(&queue->q_sios_by_addr, sio); 4075 queue->q_sio_memused -= SIO_GET_MUSED(sio); 4076 4077 ASSERT(range_tree_contains(queue->q_exts_by_addr, start, size)); 4078 range_tree_remove_fill(queue->q_exts_by_addr, start, size); 4079 4080 /* 4081 * We only update scn_bytes_pending in the cold path, 4082 * otherwise it will already have been accounted for as 4083 * part of the zio's execution. 4084 */ 4085 atomic_add_64(&scn->scn_bytes_pending, -asize); 4086 4087 /* count the block as though we issued it */ 4088 sio2bp(sio, &tmpbp); 4089 count_block(scn, dp->dp_blkstats, &tmpbp); 4090 4091 sio_free(sio); 4092 } 4093 mutex_exit(q_lock); 4094 } 4095 4096 /* 4097 * Callback invoked when a zio_free() zio is executing. This needs to be 4098 * intercepted to prevent the zio from deallocating a particular portion 4099 * of disk space and it then getting reallocated and written to, while we 4100 * still have it queued up for processing. 4101 */ 4102 void 4103 dsl_scan_freed(spa_t *spa, const blkptr_t *bp) 4104 { 4105 dsl_pool_t *dp = spa->spa_dsl_pool; 4106 dsl_scan_t *scn = dp->dp_scan; 4107 4108 ASSERT(!BP_IS_EMBEDDED(bp)); 4109 ASSERT(scn != NULL); 4110 if (!dsl_scan_is_running(scn)) 4111 return; 4112 4113 for (int i = 0; i < BP_GET_NDVAS(bp); i++) 4114 dsl_scan_freed_dva(spa, bp, i); 4115 } 4116