xref: /illumos-gate/usr/src/uts/common/fs/zfs/dsl_scan.c (revision 28e9047603953b20acb54306be7c48152a1b03e6)
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 2016 Gary Mills
24  * Copyright (c) 2011, 2017 by Delphix. All rights reserved.
25  * Copyright 2017 Joyent, Inc.
26  * Copyright (c) 2017 Datto Inc.
27  */
28 
29 #include <sys/dsl_scan.h>
30 #include <sys/dsl_pool.h>
31 #include <sys/dsl_dataset.h>
32 #include <sys/dsl_prop.h>
33 #include <sys/dsl_dir.h>
34 #include <sys/dsl_synctask.h>
35 #include <sys/dnode.h>
36 #include <sys/dmu_tx.h>
37 #include <sys/dmu_objset.h>
38 #include <sys/arc.h>
39 #include <sys/zap.h>
40 #include <sys/zio.h>
41 #include <sys/zfs_context.h>
42 #include <sys/fs/zfs.h>
43 #include <sys/zfs_znode.h>
44 #include <sys/spa_impl.h>
45 #include <sys/vdev_impl.h>
46 #include <sys/zil_impl.h>
47 #include <sys/zio_checksum.h>
48 #include <sys/ddt.h>
49 #include <sys/sa.h>
50 #include <sys/sa_impl.h>
51 #include <sys/zfeature.h>
52 #include <sys/abd.h>
53 #ifdef _KERNEL
54 #include <sys/zfs_vfsops.h>
55 #endif
56 
57 typedef int (scan_cb_t)(dsl_pool_t *, const blkptr_t *,
58     const zbookmark_phys_t *);
59 
60 static scan_cb_t dsl_scan_scrub_cb;
61 static void dsl_scan_cancel_sync(void *, dmu_tx_t *);
62 static void dsl_scan_sync_state(dsl_scan_t *, dmu_tx_t *);
63 static boolean_t dsl_scan_restarting(dsl_scan_t *, dmu_tx_t *);
64 
65 int zfs_top_maxinflight = 32;		/* maximum I/Os per top-level */
66 int zfs_resilver_delay = 2;		/* number of ticks to delay resilver */
67 int zfs_scrub_delay = 4;		/* number of ticks to delay scrub */
68 int zfs_scan_idle = 50;			/* idle window in clock ticks */
69 
70 int zfs_scan_min_time_ms = 1000; /* min millisecs to scrub per txg */
71 int zfs_free_min_time_ms = 1000; /* min millisecs to free per txg */
72 int zfs_obsolete_min_time_ms = 500; /* min millisecs to obsolete per txg */
73 int zfs_resilver_min_time_ms = 3000; /* min millisecs to resilver per txg */
74 boolean_t zfs_no_scrub_io = B_FALSE; /* set to disable scrub i/o */
75 boolean_t zfs_no_scrub_prefetch = B_FALSE; /* set to disable scrub prefetch */
76 enum ddt_class zfs_scrub_ddt_class_max = DDT_CLASS_DUPLICATE;
77 int dsl_scan_delay_completion = B_FALSE; /* set to delay scan completion */
78 /* max number of blocks to free in a single TXG */
79 uint64_t zfs_async_block_max_blocks = UINT64_MAX;
80 
81 #define	DSL_SCAN_IS_SCRUB_RESILVER(scn) \
82 	((scn)->scn_phys.scn_func == POOL_SCAN_SCRUB || \
83 	(scn)->scn_phys.scn_func == POOL_SCAN_RESILVER)
84 
85 extern int zfs_txg_timeout;
86 
87 /*
88  * Enable/disable the processing of the free_bpobj object.
89  */
90 boolean_t zfs_free_bpobj_enabled = B_TRUE;
91 
92 /* the order has to match pool_scan_type */
93 static scan_cb_t *scan_funcs[POOL_SCAN_FUNCS] = {
94 	NULL,
95 	dsl_scan_scrub_cb,	/* POOL_SCAN_SCRUB */
96 	dsl_scan_scrub_cb,	/* POOL_SCAN_RESILVER */
97 };
98 
99 int
100 dsl_scan_init(dsl_pool_t *dp, uint64_t txg)
101 {
102 	int err;
103 	dsl_scan_t *scn;
104 	spa_t *spa = dp->dp_spa;
105 	uint64_t f;
106 
107 	scn = dp->dp_scan = kmem_zalloc(sizeof (dsl_scan_t), KM_SLEEP);
108 	scn->scn_dp = dp;
109 
110 	/*
111 	 * It's possible that we're resuming a scan after a reboot so
112 	 * make sure that the scan_async_destroying flag is initialized
113 	 * appropriately.
114 	 */
115 	ASSERT(!scn->scn_async_destroying);
116 	scn->scn_async_destroying = spa_feature_is_active(dp->dp_spa,
117 	    SPA_FEATURE_ASYNC_DESTROY);
118 
119 	err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
120 	    "scrub_func", sizeof (uint64_t), 1, &f);
121 	if (err == 0) {
122 		/*
123 		 * There was an old-style scrub in progress.  Restart a
124 		 * new-style scrub from the beginning.
125 		 */
126 		scn->scn_restart_txg = txg;
127 		zfs_dbgmsg("old-style scrub was in progress; "
128 		    "restarting new-style scrub in txg %llu",
129 		    scn->scn_restart_txg);
130 
131 		/*
132 		 * Load the queue obj from the old location so that it
133 		 * can be freed by dsl_scan_done().
134 		 */
135 		(void) zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
136 		    "scrub_queue", sizeof (uint64_t), 1,
137 		    &scn->scn_phys.scn_queue_obj);
138 	} else {
139 		err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
140 		    DMU_POOL_SCAN, sizeof (uint64_t), SCAN_PHYS_NUMINTS,
141 		    &scn->scn_phys);
142 		if (err == ENOENT)
143 			return (0);
144 		else if (err)
145 			return (err);
146 
147 		if (scn->scn_phys.scn_state == DSS_SCANNING &&
148 		    spa_prev_software_version(dp->dp_spa) < SPA_VERSION_SCAN) {
149 			/*
150 			 * A new-type scrub was in progress on an old
151 			 * pool, and the pool was accessed by old
152 			 * software.  Restart from the beginning, since
153 			 * the old software may have changed the pool in
154 			 * the meantime.
155 			 */
156 			scn->scn_restart_txg = txg;
157 			zfs_dbgmsg("new-style scrub was modified "
158 			    "by old software; restarting in txg %llu",
159 			    scn->scn_restart_txg);
160 		}
161 	}
162 
163 	spa_scan_stat_init(spa);
164 	return (0);
165 }
166 
167 void
168 dsl_scan_fini(dsl_pool_t *dp)
169 {
170 	if (dp->dp_scan) {
171 		kmem_free(dp->dp_scan, sizeof (dsl_scan_t));
172 		dp->dp_scan = NULL;
173 	}
174 }
175 
176 /* ARGSUSED */
177 static int
178 dsl_scan_setup_check(void *arg, dmu_tx_t *tx)
179 {
180 	dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
181 
182 	if (scn->scn_phys.scn_state == DSS_SCANNING)
183 		return (SET_ERROR(EBUSY));
184 
185 	return (0);
186 }
187 
188 static void
189 dsl_scan_setup_sync(void *arg, dmu_tx_t *tx)
190 {
191 	dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
192 	pool_scan_func_t *funcp = arg;
193 	dmu_object_type_t ot = 0;
194 	dsl_pool_t *dp = scn->scn_dp;
195 	spa_t *spa = dp->dp_spa;
196 
197 	ASSERT(scn->scn_phys.scn_state != DSS_SCANNING);
198 	ASSERT(*funcp > POOL_SCAN_NONE && *funcp < POOL_SCAN_FUNCS);
199 	bzero(&scn->scn_phys, sizeof (scn->scn_phys));
200 	scn->scn_phys.scn_func = *funcp;
201 	scn->scn_phys.scn_state = DSS_SCANNING;
202 	scn->scn_phys.scn_min_txg = 0;
203 	scn->scn_phys.scn_max_txg = tx->tx_txg;
204 	scn->scn_phys.scn_ddt_class_max = DDT_CLASSES - 1; /* the entire DDT */
205 	scn->scn_phys.scn_start_time = gethrestime_sec();
206 	scn->scn_phys.scn_errors = 0;
207 	scn->scn_phys.scn_to_examine = spa->spa_root_vdev->vdev_stat.vs_alloc;
208 	scn->scn_restart_txg = 0;
209 	scn->scn_done_txg = 0;
210 	spa_scan_stat_init(spa);
211 
212 	if (DSL_SCAN_IS_SCRUB_RESILVER(scn)) {
213 		scn->scn_phys.scn_ddt_class_max = zfs_scrub_ddt_class_max;
214 
215 		/* rewrite all disk labels */
216 		vdev_config_dirty(spa->spa_root_vdev);
217 
218 		if (vdev_resilver_needed(spa->spa_root_vdev,
219 		    &scn->scn_phys.scn_min_txg, &scn->scn_phys.scn_max_txg)) {
220 			spa_event_notify(spa, NULL, NULL,
221 			    ESC_ZFS_RESILVER_START);
222 		} else {
223 			spa_event_notify(spa, NULL, NULL, ESC_ZFS_SCRUB_START);
224 		}
225 
226 		spa->spa_scrub_started = B_TRUE;
227 		/*
228 		 * If this is an incremental scrub, limit the DDT scrub phase
229 		 * to just the auto-ditto class (for correctness); the rest
230 		 * of the scrub should go faster using top-down pruning.
231 		 */
232 		if (scn->scn_phys.scn_min_txg > TXG_INITIAL)
233 			scn->scn_phys.scn_ddt_class_max = DDT_CLASS_DITTO;
234 
235 	}
236 
237 	/* back to the generic stuff */
238 
239 	if (dp->dp_blkstats == NULL) {
240 		dp->dp_blkstats =
241 		    kmem_alloc(sizeof (zfs_all_blkstats_t), KM_SLEEP);
242 	}
243 	bzero(dp->dp_blkstats, sizeof (zfs_all_blkstats_t));
244 
245 	if (spa_version(spa) < SPA_VERSION_DSL_SCRUB)
246 		ot = DMU_OT_ZAP_OTHER;
247 
248 	scn->scn_phys.scn_queue_obj = zap_create(dp->dp_meta_objset,
249 	    ot ? ot : DMU_OT_SCAN_QUEUE, DMU_OT_NONE, 0, tx);
250 
251 	dsl_scan_sync_state(scn, tx);
252 
253 	spa_history_log_internal(spa, "scan setup", tx,
254 	    "func=%u mintxg=%llu maxtxg=%llu",
255 	    *funcp, scn->scn_phys.scn_min_txg, scn->scn_phys.scn_max_txg);
256 }
257 
258 /* ARGSUSED */
259 static void
260 dsl_scan_done(dsl_scan_t *scn, boolean_t complete, dmu_tx_t *tx)
261 {
262 	static const char *old_names[] = {
263 		"scrub_bookmark",
264 		"scrub_ddt_bookmark",
265 		"scrub_ddt_class_max",
266 		"scrub_queue",
267 		"scrub_min_txg",
268 		"scrub_max_txg",
269 		"scrub_func",
270 		"scrub_errors",
271 		NULL
272 	};
273 
274 	dsl_pool_t *dp = scn->scn_dp;
275 	spa_t *spa = dp->dp_spa;
276 	int i;
277 
278 	/* Remove any remnants of an old-style scrub. */
279 	for (i = 0; old_names[i]; i++) {
280 		(void) zap_remove(dp->dp_meta_objset,
281 		    DMU_POOL_DIRECTORY_OBJECT, old_names[i], tx);
282 	}
283 
284 	if (scn->scn_phys.scn_queue_obj != 0) {
285 		VERIFY(0 == dmu_object_free(dp->dp_meta_objset,
286 		    scn->scn_phys.scn_queue_obj, tx));
287 		scn->scn_phys.scn_queue_obj = 0;
288 	}
289 
290 	scn->scn_phys.scn_flags &= ~DSF_SCRUB_PAUSED;
291 
292 	/*
293 	 * If we were "restarted" from a stopped state, don't bother
294 	 * with anything else.
295 	 */
296 	if (scn->scn_phys.scn_state != DSS_SCANNING)
297 		return;
298 
299 	if (complete)
300 		scn->scn_phys.scn_state = DSS_FINISHED;
301 	else
302 		scn->scn_phys.scn_state = DSS_CANCELED;
303 
304 	if (dsl_scan_restarting(scn, tx))
305 		spa_history_log_internal(spa, "scan aborted, restarting", tx,
306 		    "errors=%llu", spa_get_errlog_size(spa));
307 	else if (!complete)
308 		spa_history_log_internal(spa, "scan cancelled", tx,
309 		    "errors=%llu", spa_get_errlog_size(spa));
310 	else
311 		spa_history_log_internal(spa, "scan done", tx,
312 		    "errors=%llu", spa_get_errlog_size(spa));
313 
314 	if (DSL_SCAN_IS_SCRUB_RESILVER(scn)) {
315 		mutex_enter(&spa->spa_scrub_lock);
316 		while (spa->spa_scrub_inflight > 0) {
317 			cv_wait(&spa->spa_scrub_io_cv,
318 			    &spa->spa_scrub_lock);
319 		}
320 		mutex_exit(&spa->spa_scrub_lock);
321 		spa->spa_scrub_started = B_FALSE;
322 		spa->spa_scrub_active = B_FALSE;
323 
324 		/*
325 		 * If the scrub/resilver completed, update all DTLs to
326 		 * reflect this.  Whether it succeeded or not, vacate
327 		 * all temporary scrub DTLs.
328 		 */
329 		vdev_dtl_reassess(spa->spa_root_vdev, tx->tx_txg,
330 		    complete ? scn->scn_phys.scn_max_txg : 0, B_TRUE);
331 		if (complete) {
332 			spa_event_notify(spa, NULL, NULL,
333 			    scn->scn_phys.scn_min_txg ?
334 			    ESC_ZFS_RESILVER_FINISH : ESC_ZFS_SCRUB_FINISH);
335 		}
336 		spa_errlog_rotate(spa);
337 
338 		/*
339 		 * We may have finished replacing a device.
340 		 * Let the async thread assess this and handle the detach.
341 		 */
342 		spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
343 	}
344 
345 	scn->scn_phys.scn_end_time = gethrestime_sec();
346 }
347 
348 /* ARGSUSED */
349 static int
350 dsl_scan_cancel_check(void *arg, dmu_tx_t *tx)
351 {
352 	dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
353 
354 	if (scn->scn_phys.scn_state != DSS_SCANNING)
355 		return (SET_ERROR(ENOENT));
356 	return (0);
357 }
358 
359 /* ARGSUSED */
360 static void
361 dsl_scan_cancel_sync(void *arg, dmu_tx_t *tx)
362 {
363 	dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
364 
365 	dsl_scan_done(scn, B_FALSE, tx);
366 	dsl_scan_sync_state(scn, tx);
367 }
368 
369 int
370 dsl_scan_cancel(dsl_pool_t *dp)
371 {
372 	return (dsl_sync_task(spa_name(dp->dp_spa), dsl_scan_cancel_check,
373 	    dsl_scan_cancel_sync, NULL, 3, ZFS_SPACE_CHECK_RESERVED));
374 }
375 
376 boolean_t
377 dsl_scan_is_paused_scrub(const dsl_scan_t *scn)
378 {
379 	if (dsl_scan_scrubbing(scn->scn_dp) &&
380 	    scn->scn_phys.scn_flags & DSF_SCRUB_PAUSED)
381 		return (B_TRUE);
382 
383 	return (B_FALSE);
384 }
385 
386 static int
387 dsl_scrub_pause_resume_check(void *arg, dmu_tx_t *tx)
388 {
389 	pool_scrub_cmd_t *cmd = arg;
390 	dsl_pool_t *dp = dmu_tx_pool(tx);
391 	dsl_scan_t *scn = dp->dp_scan;
392 
393 	if (*cmd == POOL_SCRUB_PAUSE) {
394 		/* can't pause a scrub when there is no in-progress scrub */
395 		if (!dsl_scan_scrubbing(dp))
396 			return (SET_ERROR(ENOENT));
397 
398 		/* can't pause a paused scrub */
399 		if (dsl_scan_is_paused_scrub(scn))
400 			return (SET_ERROR(EBUSY));
401 	} else if (*cmd != POOL_SCRUB_NORMAL) {
402 		return (SET_ERROR(ENOTSUP));
403 	}
404 
405 	return (0);
406 }
407 
408 static void
409 dsl_scrub_pause_resume_sync(void *arg, dmu_tx_t *tx)
410 {
411 	pool_scrub_cmd_t *cmd = arg;
412 	dsl_pool_t *dp = dmu_tx_pool(tx);
413 	spa_t *spa = dp->dp_spa;
414 	dsl_scan_t *scn = dp->dp_scan;
415 
416 	if (*cmd == POOL_SCRUB_PAUSE) {
417 		/* can't pause a scrub when there is no in-progress scrub */
418 		spa->spa_scan_pass_scrub_pause = gethrestime_sec();
419 		scn->scn_phys.scn_flags |= DSF_SCRUB_PAUSED;
420 		dsl_scan_sync_state(scn, tx);
421 	} else {
422 		ASSERT3U(*cmd, ==, POOL_SCRUB_NORMAL);
423 		if (dsl_scan_is_paused_scrub(scn)) {
424 			/*
425 			 * We need to keep track of how much time we spend
426 			 * paused per pass so that we can adjust the scrub rate
427 			 * shown in the output of 'zpool status'
428 			 */
429 			spa->spa_scan_pass_scrub_spent_paused +=
430 			    gethrestime_sec() - spa->spa_scan_pass_scrub_pause;
431 			spa->spa_scan_pass_scrub_pause = 0;
432 			scn->scn_phys.scn_flags &= ~DSF_SCRUB_PAUSED;
433 			dsl_scan_sync_state(scn, tx);
434 		}
435 	}
436 }
437 
438 /*
439  * Set scrub pause/resume state if it makes sense to do so
440  */
441 int
442 dsl_scrub_set_pause_resume(const dsl_pool_t *dp, pool_scrub_cmd_t cmd)
443 {
444 	return (dsl_sync_task(spa_name(dp->dp_spa),
445 	    dsl_scrub_pause_resume_check, dsl_scrub_pause_resume_sync, &cmd, 3,
446 	    ZFS_SPACE_CHECK_RESERVED));
447 }
448 
449 boolean_t
450 dsl_scan_scrubbing(const dsl_pool_t *dp)
451 {
452 	dsl_scan_t *scn = dp->dp_scan;
453 
454 	if (scn->scn_phys.scn_state == DSS_SCANNING &&
455 	    scn->scn_phys.scn_func == POOL_SCAN_SCRUB)
456 		return (B_TRUE);
457 
458 	return (B_FALSE);
459 }
460 
461 static void dsl_scan_visitbp(blkptr_t *bp, const zbookmark_phys_t *zb,
462     dnode_phys_t *dnp, dsl_dataset_t *ds, dsl_scan_t *scn,
463     dmu_objset_type_t ostype, dmu_tx_t *tx);
464 static void dsl_scan_visitdnode(dsl_scan_t *, dsl_dataset_t *ds,
465     dmu_objset_type_t ostype,
466     dnode_phys_t *dnp, uint64_t object, dmu_tx_t *tx);
467 
468 void
469 dsl_free(dsl_pool_t *dp, uint64_t txg, const blkptr_t *bp)
470 {
471 	zio_free(dp->dp_spa, txg, bp);
472 }
473 
474 void
475 dsl_free_sync(zio_t *pio, dsl_pool_t *dp, uint64_t txg, const blkptr_t *bpp)
476 {
477 	ASSERT(dsl_pool_sync_context(dp));
478 	zio_nowait(zio_free_sync(pio, dp->dp_spa, txg, bpp, pio->io_flags));
479 }
480 
481 static uint64_t
482 dsl_scan_ds_maxtxg(dsl_dataset_t *ds)
483 {
484 	uint64_t smt = ds->ds_dir->dd_pool->dp_scan->scn_phys.scn_max_txg;
485 	if (ds->ds_is_snapshot)
486 		return (MIN(smt, dsl_dataset_phys(ds)->ds_creation_txg));
487 	return (smt);
488 }
489 
490 static void
491 dsl_scan_sync_state(dsl_scan_t *scn, dmu_tx_t *tx)
492 {
493 	VERIFY0(zap_update(scn->scn_dp->dp_meta_objset,
494 	    DMU_POOL_DIRECTORY_OBJECT,
495 	    DMU_POOL_SCAN, sizeof (uint64_t), SCAN_PHYS_NUMINTS,
496 	    &scn->scn_phys, tx));
497 }
498 
499 extern int zfs_vdev_async_write_active_min_dirty_percent;
500 
501 static boolean_t
502 dsl_scan_check_suspend(dsl_scan_t *scn, const zbookmark_phys_t *zb)
503 {
504 	/* we never skip user/group accounting objects */
505 	if (zb && (int64_t)zb->zb_object < 0)
506 		return (B_FALSE);
507 
508 	if (scn->scn_suspending)
509 		return (B_TRUE); /* we're already suspending */
510 
511 	if (!ZB_IS_ZERO(&scn->scn_phys.scn_bookmark))
512 		return (B_FALSE); /* we're resuming */
513 
514 	/* We only know how to resume from level-0 blocks. */
515 	if (zb && zb->zb_level != 0)
516 		return (B_FALSE);
517 
518 	/*
519 	 * We suspend if:
520 	 *  - we have scanned for the maximum time: an entire txg
521 	 *    timeout (default 5 sec)
522 	 *  or
523 	 *  - we have scanned for at least the minimum time (default 1 sec
524 	 *    for scrub, 3 sec for resilver), and either we have sufficient
525 	 *    dirty data that we are starting to write more quickly
526 	 *    (default 30%), or someone is explicitly waiting for this txg
527 	 *    to complete.
528 	 *  or
529 	 *  - the spa is shutting down because this pool is being exported
530 	 *    or the machine is rebooting.
531 	 */
532 	int mintime = (scn->scn_phys.scn_func == POOL_SCAN_RESILVER) ?
533 	    zfs_resilver_min_time_ms : zfs_scan_min_time_ms;
534 	uint64_t elapsed_nanosecs = gethrtime() - scn->scn_sync_start_time;
535 	int dirty_pct = scn->scn_dp->dp_dirty_total * 100 / zfs_dirty_data_max;
536 	if (elapsed_nanosecs / NANOSEC >= zfs_txg_timeout ||
537 	    (NSEC2MSEC(elapsed_nanosecs) > mintime &&
538 	    (txg_sync_waiting(scn->scn_dp) ||
539 	    dirty_pct >= zfs_vdev_async_write_active_min_dirty_percent)) ||
540 	    spa_shutting_down(scn->scn_dp->dp_spa)) {
541 		if (zb) {
542 			dprintf("suspending at bookmark %llx/%llx/%llx/%llx\n",
543 			    (longlong_t)zb->zb_objset,
544 			    (longlong_t)zb->zb_object,
545 			    (longlong_t)zb->zb_level,
546 			    (longlong_t)zb->zb_blkid);
547 			scn->scn_phys.scn_bookmark = *zb;
548 		}
549 		dprintf("suspending at DDT bookmark %llx/%llx/%llx/%llx\n",
550 		    (longlong_t)scn->scn_phys.scn_ddt_bookmark.ddb_class,
551 		    (longlong_t)scn->scn_phys.scn_ddt_bookmark.ddb_type,
552 		    (longlong_t)scn->scn_phys.scn_ddt_bookmark.ddb_checksum,
553 		    (longlong_t)scn->scn_phys.scn_ddt_bookmark.ddb_cursor);
554 		scn->scn_suspending = B_TRUE;
555 		return (B_TRUE);
556 	}
557 	return (B_FALSE);
558 }
559 
560 typedef struct zil_scan_arg {
561 	dsl_pool_t	*zsa_dp;
562 	zil_header_t	*zsa_zh;
563 } zil_scan_arg_t;
564 
565 /* ARGSUSED */
566 static int
567 dsl_scan_zil_block(zilog_t *zilog, blkptr_t *bp, void *arg, uint64_t claim_txg)
568 {
569 	zil_scan_arg_t *zsa = arg;
570 	dsl_pool_t *dp = zsa->zsa_dp;
571 	dsl_scan_t *scn = dp->dp_scan;
572 	zil_header_t *zh = zsa->zsa_zh;
573 	zbookmark_phys_t zb;
574 
575 	if (BP_IS_HOLE(bp) || bp->blk_birth <= scn->scn_phys.scn_cur_min_txg)
576 		return (0);
577 
578 	/*
579 	 * One block ("stubby") can be allocated a long time ago; we
580 	 * want to visit that one because it has been allocated
581 	 * (on-disk) even if it hasn't been claimed (even though for
582 	 * scrub there's nothing to do to it).
583 	 */
584 	if (claim_txg == 0 && bp->blk_birth >= spa_first_txg(dp->dp_spa))
585 		return (0);
586 
587 	SET_BOOKMARK(&zb, zh->zh_log.blk_cksum.zc_word[ZIL_ZC_OBJSET],
588 	    ZB_ZIL_OBJECT, ZB_ZIL_LEVEL, bp->blk_cksum.zc_word[ZIL_ZC_SEQ]);
589 
590 	VERIFY(0 == scan_funcs[scn->scn_phys.scn_func](dp, bp, &zb));
591 	return (0);
592 }
593 
594 /* ARGSUSED */
595 static int
596 dsl_scan_zil_record(zilog_t *zilog, lr_t *lrc, void *arg, uint64_t claim_txg)
597 {
598 	if (lrc->lrc_txtype == TX_WRITE) {
599 		zil_scan_arg_t *zsa = arg;
600 		dsl_pool_t *dp = zsa->zsa_dp;
601 		dsl_scan_t *scn = dp->dp_scan;
602 		zil_header_t *zh = zsa->zsa_zh;
603 		lr_write_t *lr = (lr_write_t *)lrc;
604 		blkptr_t *bp = &lr->lr_blkptr;
605 		zbookmark_phys_t zb;
606 
607 		if (BP_IS_HOLE(bp) ||
608 		    bp->blk_birth <= scn->scn_phys.scn_cur_min_txg)
609 			return (0);
610 
611 		/*
612 		 * birth can be < claim_txg if this record's txg is
613 		 * already txg sync'ed (but this log block contains
614 		 * other records that are not synced)
615 		 */
616 		if (claim_txg == 0 || bp->blk_birth < claim_txg)
617 			return (0);
618 
619 		SET_BOOKMARK(&zb, zh->zh_log.blk_cksum.zc_word[ZIL_ZC_OBJSET],
620 		    lr->lr_foid, ZB_ZIL_LEVEL,
621 		    lr->lr_offset / BP_GET_LSIZE(bp));
622 
623 		VERIFY(0 == scan_funcs[scn->scn_phys.scn_func](dp, bp, &zb));
624 	}
625 	return (0);
626 }
627 
628 static void
629 dsl_scan_zil(dsl_pool_t *dp, zil_header_t *zh)
630 {
631 	uint64_t claim_txg = zh->zh_claim_txg;
632 	zil_scan_arg_t zsa = { dp, zh };
633 	zilog_t *zilog;
634 
635 	/*
636 	 * We only want to visit blocks that have been claimed but not yet
637 	 * replayed (or, in read-only mode, blocks that *would* be claimed).
638 	 */
639 	if (claim_txg == 0 && spa_writeable(dp->dp_spa))
640 		return;
641 
642 	zilog = zil_alloc(dp->dp_meta_objset, zh);
643 
644 	(void) zil_parse(zilog, dsl_scan_zil_block, dsl_scan_zil_record, &zsa,
645 	    claim_txg);
646 
647 	zil_free(zilog);
648 }
649 
650 /* ARGSUSED */
651 static void
652 dsl_scan_prefetch(dsl_scan_t *scn, arc_buf_t *buf, blkptr_t *bp,
653     uint64_t objset, uint64_t object, uint64_t blkid)
654 {
655 	zbookmark_phys_t czb;
656 	arc_flags_t flags = ARC_FLAG_NOWAIT | ARC_FLAG_PREFETCH;
657 
658 	if (zfs_no_scrub_prefetch)
659 		return;
660 
661 	if (BP_IS_HOLE(bp) || bp->blk_birth <= scn->scn_phys.scn_min_txg ||
662 	    (BP_GET_LEVEL(bp) == 0 && BP_GET_TYPE(bp) != DMU_OT_DNODE))
663 		return;
664 
665 	SET_BOOKMARK(&czb, objset, object, BP_GET_LEVEL(bp), blkid);
666 
667 	(void) arc_read(scn->scn_zio_root, scn->scn_dp->dp_spa, bp,
668 	    NULL, NULL, ZIO_PRIORITY_ASYNC_READ,
669 	    ZIO_FLAG_CANFAIL | ZIO_FLAG_SCAN_THREAD, &flags, &czb);
670 }
671 
672 static boolean_t
673 dsl_scan_check_resume(dsl_scan_t *scn, const dnode_phys_t *dnp,
674     const zbookmark_phys_t *zb)
675 {
676 	/*
677 	 * We never skip over user/group accounting objects (obj<0)
678 	 */
679 	if (!ZB_IS_ZERO(&scn->scn_phys.scn_bookmark) &&
680 	    (int64_t)zb->zb_object >= 0) {
681 		/*
682 		 * If we already visited this bp & everything below (in
683 		 * a prior txg sync), don't bother doing it again.
684 		 */
685 		if (zbookmark_subtree_completed(dnp, zb,
686 		    &scn->scn_phys.scn_bookmark))
687 			return (B_TRUE);
688 
689 		/*
690 		 * If we found the block we're trying to resume from, or
691 		 * we went past it to a different object, zero it out to
692 		 * indicate that it's OK to start checking for suspending
693 		 * again.
694 		 */
695 		if (bcmp(zb, &scn->scn_phys.scn_bookmark, sizeof (*zb)) == 0 ||
696 		    zb->zb_object > scn->scn_phys.scn_bookmark.zb_object) {
697 			dprintf("resuming at %llx/%llx/%llx/%llx\n",
698 			    (longlong_t)zb->zb_objset,
699 			    (longlong_t)zb->zb_object,
700 			    (longlong_t)zb->zb_level,
701 			    (longlong_t)zb->zb_blkid);
702 			bzero(&scn->scn_phys.scn_bookmark, sizeof (*zb));
703 		}
704 	}
705 	return (B_FALSE);
706 }
707 
708 /*
709  * Return nonzero on i/o error.
710  * Return new buf to write out in *bufp.
711  */
712 static int
713 dsl_scan_recurse(dsl_scan_t *scn, dsl_dataset_t *ds, dmu_objset_type_t ostype,
714     dnode_phys_t *dnp, const blkptr_t *bp,
715     const zbookmark_phys_t *zb, dmu_tx_t *tx)
716 {
717 	dsl_pool_t *dp = scn->scn_dp;
718 	int zio_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCAN_THREAD;
719 	int err;
720 
721 	if (BP_GET_LEVEL(bp) > 0) {
722 		arc_flags_t flags = ARC_FLAG_WAIT;
723 		int i;
724 		blkptr_t *cbp;
725 		int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
726 		arc_buf_t *buf;
727 
728 		err = arc_read(NULL, dp->dp_spa, bp, arc_getbuf_func, &buf,
729 		    ZIO_PRIORITY_ASYNC_READ, zio_flags, &flags, zb);
730 		if (err) {
731 			scn->scn_phys.scn_errors++;
732 			return (err);
733 		}
734 		for (i = 0, cbp = buf->b_data; i < epb; i++, cbp++) {
735 			dsl_scan_prefetch(scn, buf, cbp, zb->zb_objset,
736 			    zb->zb_object, zb->zb_blkid * epb + i);
737 		}
738 		for (i = 0, cbp = buf->b_data; i < epb; i++, cbp++) {
739 			zbookmark_phys_t czb;
740 
741 			SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
742 			    zb->zb_level - 1,
743 			    zb->zb_blkid * epb + i);
744 			dsl_scan_visitbp(cbp, &czb, dnp,
745 			    ds, scn, ostype, tx);
746 		}
747 		arc_buf_destroy(buf, &buf);
748 	} else if (BP_GET_TYPE(bp) == DMU_OT_DNODE) {
749 		arc_flags_t flags = ARC_FLAG_WAIT;
750 		dnode_phys_t *cdnp;
751 		int i, j;
752 		int epb = BP_GET_LSIZE(bp) >> DNODE_SHIFT;
753 		arc_buf_t *buf;
754 
755 		err = arc_read(NULL, dp->dp_spa, bp, arc_getbuf_func, &buf,
756 		    ZIO_PRIORITY_ASYNC_READ, zio_flags, &flags, zb);
757 		if (err) {
758 			scn->scn_phys.scn_errors++;
759 			return (err);
760 		}
761 		for (i = 0, cdnp = buf->b_data; i < epb; i++, cdnp++) {
762 			for (j = 0; j < cdnp->dn_nblkptr; j++) {
763 				blkptr_t *cbp = &cdnp->dn_blkptr[j];
764 				dsl_scan_prefetch(scn, buf, cbp,
765 				    zb->zb_objset, zb->zb_blkid * epb + i, j);
766 			}
767 		}
768 		for (i = 0, cdnp = buf->b_data; i < epb; i++, cdnp++) {
769 			dsl_scan_visitdnode(scn, ds, ostype,
770 			    cdnp, zb->zb_blkid * epb + i, tx);
771 		}
772 
773 		arc_buf_destroy(buf, &buf);
774 	} else if (BP_GET_TYPE(bp) == DMU_OT_OBJSET) {
775 		arc_flags_t flags = ARC_FLAG_WAIT;
776 		objset_phys_t *osp;
777 		arc_buf_t *buf;
778 
779 		err = arc_read(NULL, dp->dp_spa, bp, arc_getbuf_func, &buf,
780 		    ZIO_PRIORITY_ASYNC_READ, zio_flags, &flags, zb);
781 		if (err) {
782 			scn->scn_phys.scn_errors++;
783 			return (err);
784 		}
785 
786 		osp = buf->b_data;
787 
788 		dsl_scan_visitdnode(scn, ds, osp->os_type,
789 		    &osp->os_meta_dnode, DMU_META_DNODE_OBJECT, tx);
790 
791 		if (OBJSET_BUF_HAS_USERUSED(buf)) {
792 			/*
793 			 * We also always visit user/group accounting
794 			 * objects, and never skip them, even if we are
795 			 * suspending.  This is necessary so that the space
796 			 * deltas from this txg get integrated.
797 			 */
798 			dsl_scan_visitdnode(scn, ds, osp->os_type,
799 			    &osp->os_groupused_dnode,
800 			    DMU_GROUPUSED_OBJECT, tx);
801 			dsl_scan_visitdnode(scn, ds, osp->os_type,
802 			    &osp->os_userused_dnode,
803 			    DMU_USERUSED_OBJECT, tx);
804 		}
805 		arc_buf_destroy(buf, &buf);
806 	}
807 
808 	return (0);
809 }
810 
811 static void
812 dsl_scan_visitdnode(dsl_scan_t *scn, dsl_dataset_t *ds,
813     dmu_objset_type_t ostype, dnode_phys_t *dnp,
814     uint64_t object, dmu_tx_t *tx)
815 {
816 	int j;
817 
818 	for (j = 0; j < dnp->dn_nblkptr; j++) {
819 		zbookmark_phys_t czb;
820 
821 		SET_BOOKMARK(&czb, ds ? ds->ds_object : 0, object,
822 		    dnp->dn_nlevels - 1, j);
823 		dsl_scan_visitbp(&dnp->dn_blkptr[j],
824 		    &czb, dnp, ds, scn, ostype, tx);
825 	}
826 
827 	if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {
828 		zbookmark_phys_t czb;
829 		SET_BOOKMARK(&czb, ds ? ds->ds_object : 0, object,
830 		    0, DMU_SPILL_BLKID);
831 		dsl_scan_visitbp(&dnp->dn_spill,
832 		    &czb, dnp, ds, scn, ostype, tx);
833 	}
834 }
835 
836 /*
837  * The arguments are in this order because mdb can only print the
838  * first 5; we want them to be useful.
839  */
840 static void
841 dsl_scan_visitbp(blkptr_t *bp, const zbookmark_phys_t *zb,
842     dnode_phys_t *dnp, dsl_dataset_t *ds, dsl_scan_t *scn,
843     dmu_objset_type_t ostype, dmu_tx_t *tx)
844 {
845 	dsl_pool_t *dp = scn->scn_dp;
846 	arc_buf_t *buf = NULL;
847 	blkptr_t bp_toread = *bp;
848 
849 	/* ASSERT(pbuf == NULL || arc_released(pbuf)); */
850 
851 	if (dsl_scan_check_suspend(scn, zb))
852 		return;
853 
854 	if (dsl_scan_check_resume(scn, dnp, zb))
855 		return;
856 
857 	if (BP_IS_HOLE(bp))
858 		return;
859 
860 	scn->scn_visited_this_txg++;
861 
862 	dprintf_bp(bp,
863 	    "visiting ds=%p/%llu zb=%llx/%llx/%llx/%llx bp=%p",
864 	    ds, ds ? ds->ds_object : 0,
865 	    zb->zb_objset, zb->zb_object, zb->zb_level, zb->zb_blkid,
866 	    bp);
867 
868 	if (bp->blk_birth <= scn->scn_phys.scn_cur_min_txg)
869 		return;
870 
871 	if (dsl_scan_recurse(scn, ds, ostype, dnp, &bp_toread, zb, tx) != 0)
872 		return;
873 
874 	/*
875 	 * If dsl_scan_ddt() has already visited this block, it will have
876 	 * already done any translations or scrubbing, so don't call the
877 	 * callback again.
878 	 */
879 	if (ddt_class_contains(dp->dp_spa,
880 	    scn->scn_phys.scn_ddt_class_max, bp)) {
881 		ASSERT(buf == NULL);
882 		return;
883 	}
884 
885 	/*
886 	 * If this block is from the future (after cur_max_txg), then we
887 	 * are doing this on behalf of a deleted snapshot, and we will
888 	 * revisit the future block on the next pass of this dataset.
889 	 * Don't scan it now unless we need to because something
890 	 * under it was modified.
891 	 */
892 	if (BP_PHYSICAL_BIRTH(bp) <= scn->scn_phys.scn_cur_max_txg) {
893 		scan_funcs[scn->scn_phys.scn_func](dp, bp, zb);
894 	}
895 }
896 
897 static void
898 dsl_scan_visit_rootbp(dsl_scan_t *scn, dsl_dataset_t *ds, blkptr_t *bp,
899     dmu_tx_t *tx)
900 {
901 	zbookmark_phys_t zb;
902 
903 	SET_BOOKMARK(&zb, ds ? ds->ds_object : DMU_META_OBJSET,
904 	    ZB_ROOT_OBJECT, ZB_ROOT_LEVEL, ZB_ROOT_BLKID);
905 	dsl_scan_visitbp(bp, &zb, NULL,
906 	    ds, scn, DMU_OST_NONE, tx);
907 
908 	dprintf_ds(ds, "finished scan%s", "");
909 }
910 
911 void
912 dsl_scan_ds_destroyed(dsl_dataset_t *ds, dmu_tx_t *tx)
913 {
914 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
915 	dsl_scan_t *scn = dp->dp_scan;
916 	uint64_t mintxg;
917 
918 	if (scn->scn_phys.scn_state != DSS_SCANNING)
919 		return;
920 
921 	if (scn->scn_phys.scn_bookmark.zb_objset == ds->ds_object) {
922 		if (ds->ds_is_snapshot) {
923 			/*
924 			 * Note:
925 			 *  - scn_cur_{min,max}_txg stays the same.
926 			 *  - Setting the flag is not really necessary if
927 			 *    scn_cur_max_txg == scn_max_txg, because there
928 			 *    is nothing after this snapshot that we care
929 			 *    about.  However, we set it anyway and then
930 			 *    ignore it when we retraverse it in
931 			 *    dsl_scan_visitds().
932 			 */
933 			scn->scn_phys.scn_bookmark.zb_objset =
934 			    dsl_dataset_phys(ds)->ds_next_snap_obj;
935 			zfs_dbgmsg("destroying ds %llu; currently traversing; "
936 			    "reset zb_objset to %llu",
937 			    (u_longlong_t)ds->ds_object,
938 			    (u_longlong_t)dsl_dataset_phys(ds)->
939 			    ds_next_snap_obj);
940 			scn->scn_phys.scn_flags |= DSF_VISIT_DS_AGAIN;
941 		} else {
942 			SET_BOOKMARK(&scn->scn_phys.scn_bookmark,
943 			    ZB_DESTROYED_OBJSET, 0, 0, 0);
944 			zfs_dbgmsg("destroying ds %llu; currently traversing; "
945 			    "reset bookmark to -1,0,0,0",
946 			    (u_longlong_t)ds->ds_object);
947 		}
948 	} else if (zap_lookup_int_key(dp->dp_meta_objset,
949 	    scn->scn_phys.scn_queue_obj, ds->ds_object, &mintxg) == 0) {
950 		ASSERT3U(dsl_dataset_phys(ds)->ds_num_children, <=, 1);
951 		VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
952 		    scn->scn_phys.scn_queue_obj, ds->ds_object, tx));
953 		if (ds->ds_is_snapshot) {
954 			/*
955 			 * We keep the same mintxg; it could be >
956 			 * ds_creation_txg if the previous snapshot was
957 			 * deleted too.
958 			 */
959 			VERIFY(zap_add_int_key(dp->dp_meta_objset,
960 			    scn->scn_phys.scn_queue_obj,
961 			    dsl_dataset_phys(ds)->ds_next_snap_obj,
962 			    mintxg, tx) == 0);
963 			zfs_dbgmsg("destroying ds %llu; in queue; "
964 			    "replacing with %llu",
965 			    (u_longlong_t)ds->ds_object,
966 			    (u_longlong_t)dsl_dataset_phys(ds)->
967 			    ds_next_snap_obj);
968 		} else {
969 			zfs_dbgmsg("destroying ds %llu; in queue; removing",
970 			    (u_longlong_t)ds->ds_object);
971 		}
972 	}
973 
974 	/*
975 	 * dsl_scan_sync() should be called after this, and should sync
976 	 * out our changed state, but just to be safe, do it here.
977 	 */
978 	dsl_scan_sync_state(scn, tx);
979 }
980 
981 void
982 dsl_scan_ds_snapshotted(dsl_dataset_t *ds, dmu_tx_t *tx)
983 {
984 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
985 	dsl_scan_t *scn = dp->dp_scan;
986 	uint64_t mintxg;
987 
988 	if (scn->scn_phys.scn_state != DSS_SCANNING)
989 		return;
990 
991 	ASSERT(dsl_dataset_phys(ds)->ds_prev_snap_obj != 0);
992 
993 	if (scn->scn_phys.scn_bookmark.zb_objset == ds->ds_object) {
994 		scn->scn_phys.scn_bookmark.zb_objset =
995 		    dsl_dataset_phys(ds)->ds_prev_snap_obj;
996 		zfs_dbgmsg("snapshotting ds %llu; currently traversing; "
997 		    "reset zb_objset to %llu",
998 		    (u_longlong_t)ds->ds_object,
999 		    (u_longlong_t)dsl_dataset_phys(ds)->ds_prev_snap_obj);
1000 	} else if (zap_lookup_int_key(dp->dp_meta_objset,
1001 	    scn->scn_phys.scn_queue_obj, ds->ds_object, &mintxg) == 0) {
1002 		VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
1003 		    scn->scn_phys.scn_queue_obj, ds->ds_object, tx));
1004 		VERIFY(zap_add_int_key(dp->dp_meta_objset,
1005 		    scn->scn_phys.scn_queue_obj,
1006 		    dsl_dataset_phys(ds)->ds_prev_snap_obj, mintxg, tx) == 0);
1007 		zfs_dbgmsg("snapshotting ds %llu; in queue; "
1008 		    "replacing with %llu",
1009 		    (u_longlong_t)ds->ds_object,
1010 		    (u_longlong_t)dsl_dataset_phys(ds)->ds_prev_snap_obj);
1011 	}
1012 	dsl_scan_sync_state(scn, tx);
1013 }
1014 
1015 void
1016 dsl_scan_ds_clone_swapped(dsl_dataset_t *ds1, dsl_dataset_t *ds2, dmu_tx_t *tx)
1017 {
1018 	dsl_pool_t *dp = ds1->ds_dir->dd_pool;
1019 	dsl_scan_t *scn = dp->dp_scan;
1020 	uint64_t mintxg;
1021 
1022 	if (scn->scn_phys.scn_state != DSS_SCANNING)
1023 		return;
1024 
1025 	if (scn->scn_phys.scn_bookmark.zb_objset == ds1->ds_object) {
1026 		scn->scn_phys.scn_bookmark.zb_objset = ds2->ds_object;
1027 		zfs_dbgmsg("clone_swap ds %llu; currently traversing; "
1028 		    "reset zb_objset to %llu",
1029 		    (u_longlong_t)ds1->ds_object,
1030 		    (u_longlong_t)ds2->ds_object);
1031 	} else if (scn->scn_phys.scn_bookmark.zb_objset == ds2->ds_object) {
1032 		scn->scn_phys.scn_bookmark.zb_objset = ds1->ds_object;
1033 		zfs_dbgmsg("clone_swap ds %llu; currently traversing; "
1034 		    "reset zb_objset to %llu",
1035 		    (u_longlong_t)ds2->ds_object,
1036 		    (u_longlong_t)ds1->ds_object);
1037 	}
1038 
1039 	if (zap_lookup_int_key(dp->dp_meta_objset, scn->scn_phys.scn_queue_obj,
1040 	    ds1->ds_object, &mintxg) == 0) {
1041 		int err;
1042 
1043 		ASSERT3U(mintxg, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);
1044 		ASSERT3U(mintxg, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);
1045 		VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
1046 		    scn->scn_phys.scn_queue_obj, ds1->ds_object, tx));
1047 		err = zap_add_int_key(dp->dp_meta_objset,
1048 		    scn->scn_phys.scn_queue_obj, ds2->ds_object, mintxg, tx);
1049 		VERIFY(err == 0 || err == EEXIST);
1050 		if (err == EEXIST) {
1051 			/* Both were there to begin with */
1052 			VERIFY(0 == zap_add_int_key(dp->dp_meta_objset,
1053 			    scn->scn_phys.scn_queue_obj,
1054 			    ds1->ds_object, mintxg, tx));
1055 		}
1056 		zfs_dbgmsg("clone_swap ds %llu; in queue; "
1057 		    "replacing with %llu",
1058 		    (u_longlong_t)ds1->ds_object,
1059 		    (u_longlong_t)ds2->ds_object);
1060 	} else if (zap_lookup_int_key(dp->dp_meta_objset,
1061 	    scn->scn_phys.scn_queue_obj, ds2->ds_object, &mintxg) == 0) {
1062 		ASSERT3U(mintxg, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);
1063 		ASSERT3U(mintxg, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);
1064 		VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
1065 		    scn->scn_phys.scn_queue_obj, ds2->ds_object, tx));
1066 		VERIFY(0 == zap_add_int_key(dp->dp_meta_objset,
1067 		    scn->scn_phys.scn_queue_obj, ds1->ds_object, mintxg, tx));
1068 		zfs_dbgmsg("clone_swap ds %llu; in queue; "
1069 		    "replacing with %llu",
1070 		    (u_longlong_t)ds2->ds_object,
1071 		    (u_longlong_t)ds1->ds_object);
1072 	}
1073 
1074 	dsl_scan_sync_state(scn, tx);
1075 }
1076 
1077 struct enqueue_clones_arg {
1078 	dmu_tx_t *tx;
1079 	uint64_t originobj;
1080 };
1081 
1082 /* ARGSUSED */
1083 static int
1084 enqueue_clones_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)
1085 {
1086 	struct enqueue_clones_arg *eca = arg;
1087 	dsl_dataset_t *ds;
1088 	int err;
1089 	dsl_scan_t *scn = dp->dp_scan;
1090 
1091 	if (dsl_dir_phys(hds->ds_dir)->dd_origin_obj != eca->originobj)
1092 		return (0);
1093 
1094 	err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);
1095 	if (err)
1096 		return (err);
1097 
1098 	while (dsl_dataset_phys(ds)->ds_prev_snap_obj != eca->originobj) {
1099 		dsl_dataset_t *prev;
1100 		err = dsl_dataset_hold_obj(dp,
1101 		    dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);
1102 
1103 		dsl_dataset_rele(ds, FTAG);
1104 		if (err)
1105 			return (err);
1106 		ds = prev;
1107 	}
1108 	VERIFY(zap_add_int_key(dp->dp_meta_objset,
1109 	    scn->scn_phys.scn_queue_obj, ds->ds_object,
1110 	    dsl_dataset_phys(ds)->ds_prev_snap_txg, eca->tx) == 0);
1111 	dsl_dataset_rele(ds, FTAG);
1112 	return (0);
1113 }
1114 
1115 static void
1116 dsl_scan_visitds(dsl_scan_t *scn, uint64_t dsobj, dmu_tx_t *tx)
1117 {
1118 	dsl_pool_t *dp = scn->scn_dp;
1119 	dsl_dataset_t *ds;
1120 
1121 	VERIFY3U(0, ==, dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
1122 
1123 	if (scn->scn_phys.scn_cur_min_txg >=
1124 	    scn->scn_phys.scn_max_txg) {
1125 		/*
1126 		 * This can happen if this snapshot was created after the
1127 		 * scan started, and we already completed a previous snapshot
1128 		 * that was created after the scan started.  This snapshot
1129 		 * only references blocks with:
1130 		 *
1131 		 *	birth < our ds_creation_txg
1132 		 *	cur_min_txg is no less than ds_creation_txg.
1133 		 *	We have already visited these blocks.
1134 		 * or
1135 		 *	birth > scn_max_txg
1136 		 *	The scan requested not to visit these blocks.
1137 		 *
1138 		 * Subsequent snapshots (and clones) can reference our
1139 		 * blocks, or blocks with even higher birth times.
1140 		 * Therefore we do not need to visit them either,
1141 		 * so we do not add them to the work queue.
1142 		 *
1143 		 * Note that checking for cur_min_txg >= cur_max_txg
1144 		 * is not sufficient, because in that case we may need to
1145 		 * visit subsequent snapshots.  This happens when min_txg > 0,
1146 		 * which raises cur_min_txg.  In this case we will visit
1147 		 * this dataset but skip all of its blocks, because the
1148 		 * rootbp's birth time is < cur_min_txg.  Then we will
1149 		 * add the next snapshots/clones to the work queue.
1150 		 */
1151 		char *dsname = kmem_alloc(MAXNAMELEN, KM_SLEEP);
1152 		dsl_dataset_name(ds, dsname);
1153 		zfs_dbgmsg("scanning dataset %llu (%s) is unnecessary because "
1154 		    "cur_min_txg (%llu) >= max_txg (%llu)",
1155 		    dsobj, dsname,
1156 		    scn->scn_phys.scn_cur_min_txg,
1157 		    scn->scn_phys.scn_max_txg);
1158 		kmem_free(dsname, MAXNAMELEN);
1159 
1160 		goto out;
1161 	}
1162 
1163 	/*
1164 	 * Only the ZIL in the head (non-snapshot) is valid. Even though
1165 	 * snapshots can have ZIL block pointers (which may be the same
1166 	 * BP as in the head), they must be ignored. In addition, $ORIGIN
1167 	 * doesn't have a objset (i.e. its ds_bp is a hole) so we don't
1168 	 * need to look for a ZIL in it either. So we traverse the ZIL here,
1169 	 * rather than in scan_recurse(), because the regular snapshot
1170 	 * block-sharing rules don't apply to it.
1171 	 */
1172 	if (DSL_SCAN_IS_SCRUB_RESILVER(scn) && !dsl_dataset_is_snapshot(ds) &&
1173 	    ds->ds_dir != dp->dp_origin_snap->ds_dir) {
1174 		objset_t *os;
1175 		if (dmu_objset_from_ds(ds, &os) != 0) {
1176 			goto out;
1177 		}
1178 		dsl_scan_zil(dp, &os->os_zil_header);
1179 	}
1180 
1181 	/*
1182 	 * Iterate over the bps in this ds.
1183 	 */
1184 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
1185 	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
1186 	dsl_scan_visit_rootbp(scn, ds, &dsl_dataset_phys(ds)->ds_bp, tx);
1187 	rrw_exit(&ds->ds_bp_rwlock, FTAG);
1188 
1189 	char *dsname = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
1190 	dsl_dataset_name(ds, dsname);
1191 	zfs_dbgmsg("scanned dataset %llu (%s) with min=%llu max=%llu; "
1192 	    "suspending=%u",
1193 	    (longlong_t)dsobj, dsname,
1194 	    (longlong_t)scn->scn_phys.scn_cur_min_txg,
1195 	    (longlong_t)scn->scn_phys.scn_cur_max_txg,
1196 	    (int)scn->scn_suspending);
1197 	kmem_free(dsname, ZFS_MAX_DATASET_NAME_LEN);
1198 
1199 	if (scn->scn_suspending)
1200 		goto out;
1201 
1202 	/*
1203 	 * We've finished this pass over this dataset.
1204 	 */
1205 
1206 	/*
1207 	 * If we did not completely visit this dataset, do another pass.
1208 	 */
1209 	if (scn->scn_phys.scn_flags & DSF_VISIT_DS_AGAIN) {
1210 		zfs_dbgmsg("incomplete pass; visiting again");
1211 		scn->scn_phys.scn_flags &= ~DSF_VISIT_DS_AGAIN;
1212 		VERIFY(zap_add_int_key(dp->dp_meta_objset,
1213 		    scn->scn_phys.scn_queue_obj, ds->ds_object,
1214 		    scn->scn_phys.scn_cur_max_txg, tx) == 0);
1215 		goto out;
1216 	}
1217 
1218 	/*
1219 	 * Add descendent datasets to work queue.
1220 	 */
1221 	if (dsl_dataset_phys(ds)->ds_next_snap_obj != 0) {
1222 		VERIFY(zap_add_int_key(dp->dp_meta_objset,
1223 		    scn->scn_phys.scn_queue_obj,
1224 		    dsl_dataset_phys(ds)->ds_next_snap_obj,
1225 		    dsl_dataset_phys(ds)->ds_creation_txg, tx) == 0);
1226 	}
1227 	if (dsl_dataset_phys(ds)->ds_num_children > 1) {
1228 		boolean_t usenext = B_FALSE;
1229 		if (dsl_dataset_phys(ds)->ds_next_clones_obj != 0) {
1230 			uint64_t count;
1231 			/*
1232 			 * A bug in a previous version of the code could
1233 			 * cause upgrade_clones_cb() to not set
1234 			 * ds_next_snap_obj when it should, leading to a
1235 			 * missing entry.  Therefore we can only use the
1236 			 * next_clones_obj when its count is correct.
1237 			 */
1238 			int err = zap_count(dp->dp_meta_objset,
1239 			    dsl_dataset_phys(ds)->ds_next_clones_obj, &count);
1240 			if (err == 0 &&
1241 			    count == dsl_dataset_phys(ds)->ds_num_children - 1)
1242 				usenext = B_TRUE;
1243 		}
1244 
1245 		if (usenext) {
1246 			VERIFY0(zap_join_key(dp->dp_meta_objset,
1247 			    dsl_dataset_phys(ds)->ds_next_clones_obj,
1248 			    scn->scn_phys.scn_queue_obj,
1249 			    dsl_dataset_phys(ds)->ds_creation_txg, tx));
1250 		} else {
1251 			struct enqueue_clones_arg eca;
1252 			eca.tx = tx;
1253 			eca.originobj = ds->ds_object;
1254 
1255 			VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
1256 			    enqueue_clones_cb, &eca, DS_FIND_CHILDREN));
1257 		}
1258 	}
1259 
1260 out:
1261 	dsl_dataset_rele(ds, FTAG);
1262 }
1263 
1264 /* ARGSUSED */
1265 static int
1266 enqueue_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)
1267 {
1268 	dmu_tx_t *tx = arg;
1269 	dsl_dataset_t *ds;
1270 	int err;
1271 	dsl_scan_t *scn = dp->dp_scan;
1272 
1273 	err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);
1274 	if (err)
1275 		return (err);
1276 
1277 	while (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) {
1278 		dsl_dataset_t *prev;
1279 		err = dsl_dataset_hold_obj(dp,
1280 		    dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);
1281 		if (err) {
1282 			dsl_dataset_rele(ds, FTAG);
1283 			return (err);
1284 		}
1285 
1286 		/*
1287 		 * If this is a clone, we don't need to worry about it for now.
1288 		 */
1289 		if (dsl_dataset_phys(prev)->ds_next_snap_obj != ds->ds_object) {
1290 			dsl_dataset_rele(ds, FTAG);
1291 			dsl_dataset_rele(prev, FTAG);
1292 			return (0);
1293 		}
1294 		dsl_dataset_rele(ds, FTAG);
1295 		ds = prev;
1296 	}
1297 
1298 	VERIFY(zap_add_int_key(dp->dp_meta_objset, scn->scn_phys.scn_queue_obj,
1299 	    ds->ds_object, dsl_dataset_phys(ds)->ds_prev_snap_txg, tx) == 0);
1300 	dsl_dataset_rele(ds, FTAG);
1301 	return (0);
1302 }
1303 
1304 /*
1305  * Scrub/dedup interaction.
1306  *
1307  * If there are N references to a deduped block, we don't want to scrub it
1308  * N times -- ideally, we should scrub it exactly once.
1309  *
1310  * We leverage the fact that the dde's replication class (enum ddt_class)
1311  * is ordered from highest replication class (DDT_CLASS_DITTO) to lowest
1312  * (DDT_CLASS_UNIQUE) so that we may walk the DDT in that order.
1313  *
1314  * To prevent excess scrubbing, the scrub begins by walking the DDT
1315  * to find all blocks with refcnt > 1, and scrubs each of these once.
1316  * Since there are two replication classes which contain blocks with
1317  * refcnt > 1, we scrub the highest replication class (DDT_CLASS_DITTO) first.
1318  * Finally the top-down scrub begins, only visiting blocks with refcnt == 1.
1319  *
1320  * There would be nothing more to say if a block's refcnt couldn't change
1321  * during a scrub, but of course it can so we must account for changes
1322  * in a block's replication class.
1323  *
1324  * Here's an example of what can occur:
1325  *
1326  * If a block has refcnt > 1 during the DDT scrub phase, but has refcnt == 1
1327  * when visited during the top-down scrub phase, it will be scrubbed twice.
1328  * This negates our scrub optimization, but is otherwise harmless.
1329  *
1330  * If a block has refcnt == 1 during the DDT scrub phase, but has refcnt > 1
1331  * on each visit during the top-down scrub phase, it will never be scrubbed.
1332  * To catch this, ddt_sync_entry() notifies the scrub code whenever a block's
1333  * reference class transitions to a higher level (i.e DDT_CLASS_UNIQUE to
1334  * DDT_CLASS_DUPLICATE); if it transitions from refcnt == 1 to refcnt > 1
1335  * while a scrub is in progress, it scrubs the block right then.
1336  */
1337 static void
1338 dsl_scan_ddt(dsl_scan_t *scn, dmu_tx_t *tx)
1339 {
1340 	ddt_bookmark_t *ddb = &scn->scn_phys.scn_ddt_bookmark;
1341 	ddt_entry_t dde = { 0 };
1342 	int error;
1343 	uint64_t n = 0;
1344 
1345 	while ((error = ddt_walk(scn->scn_dp->dp_spa, ddb, &dde)) == 0) {
1346 		ddt_t *ddt;
1347 
1348 		if (ddb->ddb_class > scn->scn_phys.scn_ddt_class_max)
1349 			break;
1350 		dprintf("visiting ddb=%llu/%llu/%llu/%llx\n",
1351 		    (longlong_t)ddb->ddb_class,
1352 		    (longlong_t)ddb->ddb_type,
1353 		    (longlong_t)ddb->ddb_checksum,
1354 		    (longlong_t)ddb->ddb_cursor);
1355 
1356 		/* There should be no pending changes to the dedup table */
1357 		ddt = scn->scn_dp->dp_spa->spa_ddt[ddb->ddb_checksum];
1358 		ASSERT(avl_first(&ddt->ddt_tree) == NULL);
1359 
1360 		dsl_scan_ddt_entry(scn, ddb->ddb_checksum, &dde, tx);
1361 		n++;
1362 
1363 		if (dsl_scan_check_suspend(scn, NULL))
1364 			break;
1365 	}
1366 
1367 	zfs_dbgmsg("scanned %llu ddt entries with class_max = %u; "
1368 	    "suspending=%u", (longlong_t)n,
1369 	    (int)scn->scn_phys.scn_ddt_class_max, (int)scn->scn_suspending);
1370 
1371 	ASSERT(error == 0 || error == ENOENT);
1372 	ASSERT(error != ENOENT ||
1373 	    ddb->ddb_class > scn->scn_phys.scn_ddt_class_max);
1374 }
1375 
1376 /* ARGSUSED */
1377 void
1378 dsl_scan_ddt_entry(dsl_scan_t *scn, enum zio_checksum checksum,
1379     ddt_entry_t *dde, dmu_tx_t *tx)
1380 {
1381 	const ddt_key_t *ddk = &dde->dde_key;
1382 	ddt_phys_t *ddp = dde->dde_phys;
1383 	blkptr_t bp;
1384 	zbookmark_phys_t zb = { 0 };
1385 
1386 	if (scn->scn_phys.scn_state != DSS_SCANNING)
1387 		return;
1388 
1389 	for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
1390 		if (ddp->ddp_phys_birth == 0 ||
1391 		    ddp->ddp_phys_birth > scn->scn_phys.scn_max_txg)
1392 			continue;
1393 		ddt_bp_create(checksum, ddk, ddp, &bp);
1394 
1395 		scn->scn_visited_this_txg++;
1396 		scan_funcs[scn->scn_phys.scn_func](scn->scn_dp, &bp, &zb);
1397 	}
1398 }
1399 
1400 static void
1401 dsl_scan_visit(dsl_scan_t *scn, dmu_tx_t *tx)
1402 {
1403 	dsl_pool_t *dp = scn->scn_dp;
1404 	zap_cursor_t zc;
1405 	zap_attribute_t za;
1406 
1407 	if (scn->scn_phys.scn_ddt_bookmark.ddb_class <=
1408 	    scn->scn_phys.scn_ddt_class_max) {
1409 		scn->scn_phys.scn_cur_min_txg = scn->scn_phys.scn_min_txg;
1410 		scn->scn_phys.scn_cur_max_txg = scn->scn_phys.scn_max_txg;
1411 		dsl_scan_ddt(scn, tx);
1412 		if (scn->scn_suspending)
1413 			return;
1414 	}
1415 
1416 	if (scn->scn_phys.scn_bookmark.zb_objset == DMU_META_OBJSET) {
1417 		/* First do the MOS & ORIGIN */
1418 
1419 		scn->scn_phys.scn_cur_min_txg = scn->scn_phys.scn_min_txg;
1420 		scn->scn_phys.scn_cur_max_txg = scn->scn_phys.scn_max_txg;
1421 		dsl_scan_visit_rootbp(scn, NULL,
1422 		    &dp->dp_meta_rootbp, tx);
1423 		spa_set_rootblkptr(dp->dp_spa, &dp->dp_meta_rootbp);
1424 		if (scn->scn_suspending)
1425 			return;
1426 
1427 		if (spa_version(dp->dp_spa) < SPA_VERSION_DSL_SCRUB) {
1428 			VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
1429 			    enqueue_cb, tx, DS_FIND_CHILDREN));
1430 		} else {
1431 			dsl_scan_visitds(scn,
1432 			    dp->dp_origin_snap->ds_object, tx);
1433 		}
1434 		ASSERT(!scn->scn_suspending);
1435 	} else if (scn->scn_phys.scn_bookmark.zb_objset !=
1436 	    ZB_DESTROYED_OBJSET) {
1437 		/*
1438 		 * If we were suspended, continue from here.  Note if the
1439 		 * ds we were suspended on was deleted, the zb_objset may
1440 		 * be -1, so we will skip this and find a new objset
1441 		 * below.
1442 		 */
1443 		dsl_scan_visitds(scn, scn->scn_phys.scn_bookmark.zb_objset, tx);
1444 		if (scn->scn_suspending)
1445 			return;
1446 	}
1447 
1448 	/*
1449 	 * In case we were suspended right at the end of the ds, zero the
1450 	 * bookmark so we don't think that we're still trying to resume.
1451 	 */
1452 	bzero(&scn->scn_phys.scn_bookmark, sizeof (zbookmark_phys_t));
1453 
1454 	/* keep pulling things out of the zap-object-as-queue */
1455 	while (zap_cursor_init(&zc, dp->dp_meta_objset,
1456 	    scn->scn_phys.scn_queue_obj),
1457 	    zap_cursor_retrieve(&zc, &za) == 0) {
1458 		dsl_dataset_t *ds;
1459 		uint64_t dsobj;
1460 
1461 		dsobj = zfs_strtonum(za.za_name, NULL);
1462 		VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
1463 		    scn->scn_phys.scn_queue_obj, dsobj, tx));
1464 
1465 		/* Set up min/max txg */
1466 		VERIFY3U(0, ==, dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
1467 		if (za.za_first_integer != 0) {
1468 			scn->scn_phys.scn_cur_min_txg =
1469 			    MAX(scn->scn_phys.scn_min_txg,
1470 			    za.za_first_integer);
1471 		} else {
1472 			scn->scn_phys.scn_cur_min_txg =
1473 			    MAX(scn->scn_phys.scn_min_txg,
1474 			    dsl_dataset_phys(ds)->ds_prev_snap_txg);
1475 		}
1476 		scn->scn_phys.scn_cur_max_txg = dsl_scan_ds_maxtxg(ds);
1477 		dsl_dataset_rele(ds, FTAG);
1478 
1479 		dsl_scan_visitds(scn, dsobj, tx);
1480 		zap_cursor_fini(&zc);
1481 		if (scn->scn_suspending)
1482 			return;
1483 	}
1484 	zap_cursor_fini(&zc);
1485 }
1486 
1487 static boolean_t
1488 dsl_scan_async_block_should_pause(dsl_scan_t *scn)
1489 {
1490 	uint64_t elapsed_nanosecs;
1491 
1492 	if (zfs_recover)
1493 		return (B_FALSE);
1494 
1495 	if (scn->scn_visited_this_txg >= zfs_async_block_max_blocks)
1496 		return (B_TRUE);
1497 
1498 	elapsed_nanosecs = gethrtime() - scn->scn_sync_start_time;
1499 	return (elapsed_nanosecs / NANOSEC > zfs_txg_timeout ||
1500 	    (NSEC2MSEC(elapsed_nanosecs) > scn->scn_async_block_min_time_ms &&
1501 	    txg_sync_waiting(scn->scn_dp)) ||
1502 	    spa_shutting_down(scn->scn_dp->dp_spa));
1503 }
1504 
1505 static int
1506 dsl_scan_free_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1507 {
1508 	dsl_scan_t *scn = arg;
1509 
1510 	if (!scn->scn_is_bptree ||
1511 	    (BP_GET_LEVEL(bp) == 0 && BP_GET_TYPE(bp) != DMU_OT_OBJSET)) {
1512 		if (dsl_scan_async_block_should_pause(scn))
1513 			return (SET_ERROR(ERESTART));
1514 	}
1515 
1516 	zio_nowait(zio_free_sync(scn->scn_zio_root, scn->scn_dp->dp_spa,
1517 	    dmu_tx_get_txg(tx), bp, 0));
1518 	dsl_dir_diduse_space(tx->tx_pool->dp_free_dir, DD_USED_HEAD,
1519 	    -bp_get_dsize_sync(scn->scn_dp->dp_spa, bp),
1520 	    -BP_GET_PSIZE(bp), -BP_GET_UCSIZE(bp), tx);
1521 	scn->scn_visited_this_txg++;
1522 	return (0);
1523 }
1524 
1525 static int
1526 dsl_scan_obsolete_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1527 {
1528 	dsl_scan_t *scn = arg;
1529 	const dva_t *dva = &bp->blk_dva[0];
1530 
1531 	if (dsl_scan_async_block_should_pause(scn))
1532 		return (SET_ERROR(ERESTART));
1533 
1534 	spa_vdev_indirect_mark_obsolete(scn->scn_dp->dp_spa,
1535 	    DVA_GET_VDEV(dva), DVA_GET_OFFSET(dva),
1536 	    DVA_GET_ASIZE(dva), tx);
1537 	scn->scn_visited_this_txg++;
1538 	return (0);
1539 }
1540 
1541 boolean_t
1542 dsl_scan_active(dsl_scan_t *scn)
1543 {
1544 	spa_t *spa = scn->scn_dp->dp_spa;
1545 	uint64_t used = 0, comp, uncomp;
1546 
1547 	if (spa->spa_load_state != SPA_LOAD_NONE)
1548 		return (B_FALSE);
1549 	if (spa_shutting_down(spa))
1550 		return (B_FALSE);
1551 	if ((scn->scn_phys.scn_state == DSS_SCANNING &&
1552 	    !dsl_scan_is_paused_scrub(scn)) ||
1553 	    (scn->scn_async_destroying && !scn->scn_async_stalled))
1554 		return (B_TRUE);
1555 
1556 	if (spa_version(scn->scn_dp->dp_spa) >= SPA_VERSION_DEADLISTS) {
1557 		(void) bpobj_space(&scn->scn_dp->dp_free_bpobj,
1558 		    &used, &comp, &uncomp);
1559 	}
1560 	return (used != 0);
1561 }
1562 
1563 /* Called whenever a txg syncs. */
1564 void
1565 dsl_scan_sync(dsl_pool_t *dp, dmu_tx_t *tx)
1566 {
1567 	dsl_scan_t *scn = dp->dp_scan;
1568 	spa_t *spa = dp->dp_spa;
1569 	int err = 0;
1570 
1571 	/*
1572 	 * Check for scn_restart_txg before checking spa_load_state, so
1573 	 * that we can restart an old-style scan while the pool is being
1574 	 * imported (see dsl_scan_init).
1575 	 */
1576 	if (dsl_scan_restarting(scn, tx)) {
1577 		pool_scan_func_t func = POOL_SCAN_SCRUB;
1578 		dsl_scan_done(scn, B_FALSE, tx);
1579 		if (vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL))
1580 			func = POOL_SCAN_RESILVER;
1581 		zfs_dbgmsg("restarting scan func=%u txg=%llu",
1582 		    func, tx->tx_txg);
1583 		dsl_scan_setup_sync(&func, tx);
1584 	}
1585 
1586 	/*
1587 	 * Only process scans in sync pass 1.
1588 	 */
1589 	if (spa_sync_pass(dp->dp_spa) > 1)
1590 		return;
1591 
1592 	/*
1593 	 * If the spa is shutting down, then stop scanning. This will
1594 	 * ensure that the scan does not dirty any new data during the
1595 	 * shutdown phase.
1596 	 */
1597 	if (spa_shutting_down(spa))
1598 		return;
1599 
1600 	/*
1601 	 * If the scan is inactive due to a stalled async destroy, try again.
1602 	 */
1603 	if (!scn->scn_async_stalled && !dsl_scan_active(scn))
1604 		return;
1605 
1606 	scn->scn_visited_this_txg = 0;
1607 	scn->scn_suspending = B_FALSE;
1608 	scn->scn_sync_start_time = gethrtime();
1609 	spa->spa_scrub_active = B_TRUE;
1610 
1611 	/*
1612 	 * First process the async destroys.  If we suspend, don't do
1613 	 * any scrubbing or resilvering.  This ensures that there are no
1614 	 * async destroys while we are scanning, so the scan code doesn't
1615 	 * have to worry about traversing it.  It is also faster to free the
1616 	 * blocks than to scrub them.
1617 	 */
1618 	if (zfs_free_bpobj_enabled &&
1619 	    spa_version(dp->dp_spa) >= SPA_VERSION_DEADLISTS) {
1620 		scn->scn_is_bptree = B_FALSE;
1621 		scn->scn_async_block_min_time_ms = zfs_free_min_time_ms;
1622 		scn->scn_zio_root = zio_root(dp->dp_spa, NULL,
1623 		    NULL, ZIO_FLAG_MUSTSUCCEED);
1624 		err = bpobj_iterate(&dp->dp_free_bpobj,
1625 		    dsl_scan_free_block_cb, scn, tx);
1626 		VERIFY3U(0, ==, zio_wait(scn->scn_zio_root));
1627 
1628 		if (err != 0 && err != ERESTART)
1629 			zfs_panic_recover("error %u from bpobj_iterate()", err);
1630 	}
1631 
1632 	if (err == 0 && spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) {
1633 		ASSERT(scn->scn_async_destroying);
1634 		scn->scn_is_bptree = B_TRUE;
1635 		scn->scn_zio_root = zio_root(dp->dp_spa, NULL,
1636 		    NULL, ZIO_FLAG_MUSTSUCCEED);
1637 		err = bptree_iterate(dp->dp_meta_objset,
1638 		    dp->dp_bptree_obj, B_TRUE, dsl_scan_free_block_cb, scn, tx);
1639 		VERIFY0(zio_wait(scn->scn_zio_root));
1640 
1641 		if (err == EIO || err == ECKSUM) {
1642 			err = 0;
1643 		} else if (err != 0 && err != ERESTART) {
1644 			zfs_panic_recover("error %u from "
1645 			    "traverse_dataset_destroyed()", err);
1646 		}
1647 
1648 		if (bptree_is_empty(dp->dp_meta_objset, dp->dp_bptree_obj)) {
1649 			/* finished; deactivate async destroy feature */
1650 			spa_feature_decr(spa, SPA_FEATURE_ASYNC_DESTROY, tx);
1651 			ASSERT(!spa_feature_is_active(spa,
1652 			    SPA_FEATURE_ASYNC_DESTROY));
1653 			VERIFY0(zap_remove(dp->dp_meta_objset,
1654 			    DMU_POOL_DIRECTORY_OBJECT,
1655 			    DMU_POOL_BPTREE_OBJ, tx));
1656 			VERIFY0(bptree_free(dp->dp_meta_objset,
1657 			    dp->dp_bptree_obj, tx));
1658 			dp->dp_bptree_obj = 0;
1659 			scn->scn_async_destroying = B_FALSE;
1660 			scn->scn_async_stalled = B_FALSE;
1661 		} else {
1662 			/*
1663 			 * If we didn't make progress, mark the async
1664 			 * destroy as stalled, so that we will not initiate
1665 			 * a spa_sync() on its behalf.  Note that we only
1666 			 * check this if we are not finished, because if the
1667 			 * bptree had no blocks for us to visit, we can
1668 			 * finish without "making progress".
1669 			 */
1670 			scn->scn_async_stalled =
1671 			    (scn->scn_visited_this_txg == 0);
1672 		}
1673 	}
1674 	if (scn->scn_visited_this_txg) {
1675 		zfs_dbgmsg("freed %llu blocks in %llums from "
1676 		    "free_bpobj/bptree txg %llu; err=%u",
1677 		    (longlong_t)scn->scn_visited_this_txg,
1678 		    (longlong_t)
1679 		    NSEC2MSEC(gethrtime() - scn->scn_sync_start_time),
1680 		    (longlong_t)tx->tx_txg, err);
1681 		scn->scn_visited_this_txg = 0;
1682 
1683 		/*
1684 		 * Write out changes to the DDT that may be required as a
1685 		 * result of the blocks freed.  This ensures that the DDT
1686 		 * is clean when a scrub/resilver runs.
1687 		 */
1688 		ddt_sync(spa, tx->tx_txg);
1689 	}
1690 	if (err != 0)
1691 		return;
1692 	if (dp->dp_free_dir != NULL && !scn->scn_async_destroying &&
1693 	    zfs_free_leak_on_eio &&
1694 	    (dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes != 0 ||
1695 	    dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes != 0 ||
1696 	    dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes != 0)) {
1697 		/*
1698 		 * We have finished background destroying, but there is still
1699 		 * some space left in the dp_free_dir. Transfer this leaked
1700 		 * space to the dp_leak_dir.
1701 		 */
1702 		if (dp->dp_leak_dir == NULL) {
1703 			rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
1704 			(void) dsl_dir_create_sync(dp, dp->dp_root_dir,
1705 			    LEAK_DIR_NAME, tx);
1706 			VERIFY0(dsl_pool_open_special_dir(dp,
1707 			    LEAK_DIR_NAME, &dp->dp_leak_dir));
1708 			rrw_exit(&dp->dp_config_rwlock, FTAG);
1709 		}
1710 		dsl_dir_diduse_space(dp->dp_leak_dir, DD_USED_HEAD,
1711 		    dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes,
1712 		    dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes,
1713 		    dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes, tx);
1714 		dsl_dir_diduse_space(dp->dp_free_dir, DD_USED_HEAD,
1715 		    -dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes,
1716 		    -dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes,
1717 		    -dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes, tx);
1718 	}
1719 
1720 	if (dp->dp_free_dir != NULL && !scn->scn_async_destroying) {
1721 		/* finished; verify that space accounting went to zero */
1722 		ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes);
1723 		ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes);
1724 		ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes);
1725 	}
1726 
1727 	EQUIV(bpobj_is_open(&dp->dp_obsolete_bpobj),
1728 	    0 == zap_contains(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
1729 	    DMU_POOL_OBSOLETE_BPOBJ));
1730 	if (err == 0 && bpobj_is_open(&dp->dp_obsolete_bpobj)) {
1731 		ASSERT(spa_feature_is_active(dp->dp_spa,
1732 		    SPA_FEATURE_OBSOLETE_COUNTS));
1733 
1734 		scn->scn_is_bptree = B_FALSE;
1735 		scn->scn_async_block_min_time_ms = zfs_obsolete_min_time_ms;
1736 		err = bpobj_iterate(&dp->dp_obsolete_bpobj,
1737 		    dsl_scan_obsolete_block_cb, scn, tx);
1738 		if (err != 0 && err != ERESTART)
1739 			zfs_panic_recover("error %u from bpobj_iterate()", err);
1740 
1741 		if (bpobj_is_empty(&dp->dp_obsolete_bpobj))
1742 			dsl_pool_destroy_obsolete_bpobj(dp, tx);
1743 	}
1744 
1745 	if (scn->scn_phys.scn_state != DSS_SCANNING)
1746 		return;
1747 
1748 	if (scn->scn_done_txg == tx->tx_txg) {
1749 		ASSERT(!scn->scn_suspending);
1750 		/* finished with scan. */
1751 		zfs_dbgmsg("txg %llu scan complete", tx->tx_txg);
1752 		dsl_scan_done(scn, B_TRUE, tx);
1753 		ASSERT3U(spa->spa_scrub_inflight, ==, 0);
1754 		dsl_scan_sync_state(scn, tx);
1755 		return;
1756 	}
1757 
1758 	if (dsl_scan_is_paused_scrub(scn))
1759 		return;
1760 
1761 	if (scn->scn_phys.scn_ddt_bookmark.ddb_class <=
1762 	    scn->scn_phys.scn_ddt_class_max) {
1763 		zfs_dbgmsg("doing scan sync txg %llu; "
1764 		    "ddt bm=%llu/%llu/%llu/%llx",
1765 		    (longlong_t)tx->tx_txg,
1766 		    (longlong_t)scn->scn_phys.scn_ddt_bookmark.ddb_class,
1767 		    (longlong_t)scn->scn_phys.scn_ddt_bookmark.ddb_type,
1768 		    (longlong_t)scn->scn_phys.scn_ddt_bookmark.ddb_checksum,
1769 		    (longlong_t)scn->scn_phys.scn_ddt_bookmark.ddb_cursor);
1770 		ASSERT(scn->scn_phys.scn_bookmark.zb_objset == 0);
1771 		ASSERT(scn->scn_phys.scn_bookmark.zb_object == 0);
1772 		ASSERT(scn->scn_phys.scn_bookmark.zb_level == 0);
1773 		ASSERT(scn->scn_phys.scn_bookmark.zb_blkid == 0);
1774 	} else {
1775 		zfs_dbgmsg("doing scan sync txg %llu; bm=%llu/%llu/%llu/%llu",
1776 		    (longlong_t)tx->tx_txg,
1777 		    (longlong_t)scn->scn_phys.scn_bookmark.zb_objset,
1778 		    (longlong_t)scn->scn_phys.scn_bookmark.zb_object,
1779 		    (longlong_t)scn->scn_phys.scn_bookmark.zb_level,
1780 		    (longlong_t)scn->scn_phys.scn_bookmark.zb_blkid);
1781 	}
1782 
1783 	scn->scn_zio_root = zio_root(dp->dp_spa, NULL,
1784 	    NULL, ZIO_FLAG_CANFAIL);
1785 	dsl_pool_config_enter(dp, FTAG);
1786 	dsl_scan_visit(scn, tx);
1787 	dsl_pool_config_exit(dp, FTAG);
1788 	(void) zio_wait(scn->scn_zio_root);
1789 	scn->scn_zio_root = NULL;
1790 
1791 	zfs_dbgmsg("visited %llu blocks in %llums",
1792 	    (longlong_t)scn->scn_visited_this_txg,
1793 	    (longlong_t)NSEC2MSEC(gethrtime() - scn->scn_sync_start_time));
1794 
1795 	if (!scn->scn_suspending) {
1796 		scn->scn_done_txg = tx->tx_txg + 1;
1797 		zfs_dbgmsg("txg %llu traversal complete, waiting till txg %llu",
1798 		    tx->tx_txg, scn->scn_done_txg);
1799 	}
1800 
1801 	if (DSL_SCAN_IS_SCRUB_RESILVER(scn)) {
1802 		mutex_enter(&spa->spa_scrub_lock);
1803 		while (spa->spa_scrub_inflight > 0) {
1804 			cv_wait(&spa->spa_scrub_io_cv,
1805 			    &spa->spa_scrub_lock);
1806 		}
1807 		mutex_exit(&spa->spa_scrub_lock);
1808 	}
1809 
1810 	dsl_scan_sync_state(scn, tx);
1811 }
1812 
1813 /*
1814  * This will start a new scan, or restart an existing one.
1815  */
1816 void
1817 dsl_resilver_restart(dsl_pool_t *dp, uint64_t txg)
1818 {
1819 	if (txg == 0) {
1820 		dmu_tx_t *tx;
1821 		tx = dmu_tx_create_dd(dp->dp_mos_dir);
1822 		VERIFY(0 == dmu_tx_assign(tx, TXG_WAIT));
1823 
1824 		txg = dmu_tx_get_txg(tx);
1825 		dp->dp_scan->scn_restart_txg = txg;
1826 		dmu_tx_commit(tx);
1827 	} else {
1828 		dp->dp_scan->scn_restart_txg = txg;
1829 	}
1830 	zfs_dbgmsg("restarting resilver txg=%llu", txg);
1831 }
1832 
1833 boolean_t
1834 dsl_scan_resilvering(dsl_pool_t *dp)
1835 {
1836 	return (dp->dp_scan->scn_phys.scn_state == DSS_SCANNING &&
1837 	    dp->dp_scan->scn_phys.scn_func == POOL_SCAN_RESILVER);
1838 }
1839 
1840 /*
1841  * scrub consumers
1842  */
1843 
1844 static void
1845 count_block(zfs_all_blkstats_t *zab, const blkptr_t *bp)
1846 {
1847 	int i;
1848 
1849 	/*
1850 	 * If we resume after a reboot, zab will be NULL; don't record
1851 	 * incomplete stats in that case.
1852 	 */
1853 	if (zab == NULL)
1854 		return;
1855 
1856 	for (i = 0; i < 4; i++) {
1857 		int l = (i < 2) ? BP_GET_LEVEL(bp) : DN_MAX_LEVELS;
1858 		int t = (i & 1) ? BP_GET_TYPE(bp) : DMU_OT_TOTAL;
1859 		if (t & DMU_OT_NEWTYPE)
1860 			t = DMU_OT_OTHER;
1861 		zfs_blkstat_t *zb = &zab->zab_type[l][t];
1862 		int equal;
1863 
1864 		zb->zb_count++;
1865 		zb->zb_asize += BP_GET_ASIZE(bp);
1866 		zb->zb_lsize += BP_GET_LSIZE(bp);
1867 		zb->zb_psize += BP_GET_PSIZE(bp);
1868 		zb->zb_gangs += BP_COUNT_GANG(bp);
1869 
1870 		switch (BP_GET_NDVAS(bp)) {
1871 		case 2:
1872 			if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
1873 			    DVA_GET_VDEV(&bp->blk_dva[1]))
1874 				zb->zb_ditto_2_of_2_samevdev++;
1875 			break;
1876 		case 3:
1877 			equal = (DVA_GET_VDEV(&bp->blk_dva[0]) ==
1878 			    DVA_GET_VDEV(&bp->blk_dva[1])) +
1879 			    (DVA_GET_VDEV(&bp->blk_dva[0]) ==
1880 			    DVA_GET_VDEV(&bp->blk_dva[2])) +
1881 			    (DVA_GET_VDEV(&bp->blk_dva[1]) ==
1882 			    DVA_GET_VDEV(&bp->blk_dva[2]));
1883 			if (equal == 1)
1884 				zb->zb_ditto_2_of_3_samevdev++;
1885 			else if (equal == 3)
1886 				zb->zb_ditto_3_of_3_samevdev++;
1887 			break;
1888 		}
1889 	}
1890 }
1891 
1892 static void
1893 dsl_scan_scrub_done(zio_t *zio)
1894 {
1895 	spa_t *spa = zio->io_spa;
1896 
1897 	abd_free(zio->io_abd);
1898 
1899 	mutex_enter(&spa->spa_scrub_lock);
1900 	spa->spa_scrub_inflight--;
1901 	cv_broadcast(&spa->spa_scrub_io_cv);
1902 
1903 	if (zio->io_error && (zio->io_error != ECKSUM ||
1904 	    !(zio->io_flags & ZIO_FLAG_SPECULATIVE))) {
1905 		spa->spa_dsl_pool->dp_scan->scn_phys.scn_errors++;
1906 	}
1907 	mutex_exit(&spa->spa_scrub_lock);
1908 }
1909 
1910 static int
1911 dsl_scan_scrub_cb(dsl_pool_t *dp,
1912     const blkptr_t *bp, const zbookmark_phys_t *zb)
1913 {
1914 	dsl_scan_t *scn = dp->dp_scan;
1915 	size_t size = BP_GET_PSIZE(bp);
1916 	spa_t *spa = dp->dp_spa;
1917 	uint64_t phys_birth = BP_PHYSICAL_BIRTH(bp);
1918 	boolean_t needs_io;
1919 	int zio_flags = ZIO_FLAG_SCAN_THREAD | ZIO_FLAG_RAW | ZIO_FLAG_CANFAIL;
1920 	int scan_delay = 0;
1921 
1922 	if (phys_birth <= scn->scn_phys.scn_min_txg ||
1923 	    phys_birth >= scn->scn_phys.scn_max_txg)
1924 		return (0);
1925 
1926 	count_block(dp->dp_blkstats, bp);
1927 
1928 	if (BP_IS_EMBEDDED(bp))
1929 		return (0);
1930 
1931 	ASSERT(DSL_SCAN_IS_SCRUB_RESILVER(scn));
1932 	if (scn->scn_phys.scn_func == POOL_SCAN_SCRUB) {
1933 		zio_flags |= ZIO_FLAG_SCRUB;
1934 		needs_io = B_TRUE;
1935 		scan_delay = zfs_scrub_delay;
1936 	} else {
1937 		ASSERT3U(scn->scn_phys.scn_func, ==, POOL_SCAN_RESILVER);
1938 		zio_flags |= ZIO_FLAG_RESILVER;
1939 		needs_io = B_FALSE;
1940 		scan_delay = zfs_resilver_delay;
1941 	}
1942 
1943 	/* If it's an intent log block, failure is expected. */
1944 	if (zb->zb_level == ZB_ZIL_LEVEL)
1945 		zio_flags |= ZIO_FLAG_SPECULATIVE;
1946 
1947 	for (int d = 0; d < BP_GET_NDVAS(bp); d++) {
1948 		vdev_t *vd = vdev_lookup_top(spa,
1949 		    DVA_GET_VDEV(&bp->blk_dva[d]));
1950 
1951 		/*
1952 		 * Keep track of how much data we've examined so that
1953 		 * zpool(1M) status can make useful progress reports.
1954 		 */
1955 		scn->scn_phys.scn_examined += DVA_GET_ASIZE(&bp->blk_dva[d]);
1956 		spa->spa_scan_pass_exam += DVA_GET_ASIZE(&bp->blk_dva[d]);
1957 
1958 		/* if it's a resilver, this may not be in the target range */
1959 		if (!needs_io) {
1960 			if (DVA_GET_GANG(&bp->blk_dva[d])) {
1961 				/*
1962 				 * Gang members may be spread across multiple
1963 				 * vdevs, so the best estimate we have is the
1964 				 * scrub range, which has already been checked.
1965 				 * XXX -- it would be better to change our
1966 				 * allocation policy to ensure that all
1967 				 * gang members reside on the same vdev.
1968 				 */
1969 				needs_io = B_TRUE;
1970 			} else {
1971 				needs_io = vdev_dtl_contains(vd, DTL_PARTIAL,
1972 				    phys_birth, 1);
1973 			}
1974 		}
1975 	}
1976 
1977 	if (needs_io && !zfs_no_scrub_io) {
1978 		vdev_t *rvd = spa->spa_root_vdev;
1979 		uint64_t maxinflight = rvd->vdev_children * zfs_top_maxinflight;
1980 
1981 		mutex_enter(&spa->spa_scrub_lock);
1982 		while (spa->spa_scrub_inflight >= maxinflight)
1983 			cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
1984 		spa->spa_scrub_inflight++;
1985 		mutex_exit(&spa->spa_scrub_lock);
1986 
1987 		/*
1988 		 * If we're seeing recent (zfs_scan_idle) "important" I/Os
1989 		 * then throttle our workload to limit the impact of a scan.
1990 		 */
1991 		if (ddi_get_lbolt64() - spa->spa_last_io <= zfs_scan_idle)
1992 			delay(scan_delay);
1993 
1994 		zio_nowait(zio_read(NULL, spa, bp,
1995 		    abd_alloc_for_io(size, B_FALSE), size, dsl_scan_scrub_done,
1996 		    NULL, ZIO_PRIORITY_SCRUB, zio_flags, zb));
1997 	}
1998 
1999 	/* do not relocate this block */
2000 	return (0);
2001 }
2002 
2003 /*
2004  * Called by the ZFS_IOC_POOL_SCAN ioctl to start a scrub or resilver.
2005  * Can also be called to resume a paused scrub.
2006  */
2007 int
2008 dsl_scan(dsl_pool_t *dp, pool_scan_func_t func)
2009 {
2010 	spa_t *spa = dp->dp_spa;
2011 	dsl_scan_t *scn = dp->dp_scan;
2012 
2013 	/*
2014 	 * Purge all vdev caches and probe all devices.  We do this here
2015 	 * rather than in sync context because this requires a writer lock
2016 	 * on the spa_config lock, which we can't do from sync context.  The
2017 	 * spa_scrub_reopen flag indicates that vdev_open() should not
2018 	 * attempt to start another scrub.
2019 	 */
2020 	spa_vdev_state_enter(spa, SCL_NONE);
2021 	spa->spa_scrub_reopen = B_TRUE;
2022 	vdev_reopen(spa->spa_root_vdev);
2023 	spa->spa_scrub_reopen = B_FALSE;
2024 	(void) spa_vdev_state_exit(spa, NULL, 0);
2025 
2026 	if (func == POOL_SCAN_SCRUB && dsl_scan_is_paused_scrub(scn)) {
2027 		/* got scrub start cmd, resume paused scrub */
2028 		int err = dsl_scrub_set_pause_resume(scn->scn_dp,
2029 		    POOL_SCRUB_NORMAL);
2030 		if (err == 0)
2031 			return (ECANCELED);
2032 
2033 		return (SET_ERROR(err));
2034 	}
2035 
2036 	return (dsl_sync_task(spa_name(spa), dsl_scan_setup_check,
2037 	    dsl_scan_setup_sync, &func, 0, ZFS_SPACE_CHECK_NONE));
2038 }
2039 
2040 static boolean_t
2041 dsl_scan_restarting(dsl_scan_t *scn, dmu_tx_t *tx)
2042 {
2043 	return (scn->scn_restart_txg != 0 &&
2044 	    scn->scn_restart_txg <= tx->tx_txg);
2045 }
2046