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