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