xref: /illumos-gate/usr/src/uts/common/fs/zfs/dsl_scan.c (revision 6f6a76adacda33b10633476dc6c5d66d7f17dd94)
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 (dsl_dataset_is_snapshot(ds))
379 		return (MIN(smt, ds->ds_phys->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 	uint32_t flags = ARC_NOWAIT | ARC_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_is_before(dnp, zb, &scn->scn_phys.scn_bookmark))
579 			return (B_TRUE);
580 
581 		/*
582 		 * If we found the block we're trying to resume from, or
583 		 * we went past it to a different object, zero it out to
584 		 * indicate that it's OK to start checking for pausing
585 		 * again.
586 		 */
587 		if (bcmp(zb, &scn->scn_phys.scn_bookmark, sizeof (*zb)) == 0 ||
588 		    zb->zb_object > scn->scn_phys.scn_bookmark.zb_object) {
589 			dprintf("resuming at %llx/%llx/%llx/%llx\n",
590 			    (longlong_t)zb->zb_objset,
591 			    (longlong_t)zb->zb_object,
592 			    (longlong_t)zb->zb_level,
593 			    (longlong_t)zb->zb_blkid);
594 			bzero(&scn->scn_phys.scn_bookmark, sizeof (*zb));
595 		}
596 	}
597 	return (B_FALSE);
598 }
599 
600 /*
601  * Return nonzero on i/o error.
602  * Return new buf to write out in *bufp.
603  */
604 static int
605 dsl_scan_recurse(dsl_scan_t *scn, dsl_dataset_t *ds, dmu_objset_type_t ostype,
606     dnode_phys_t *dnp, const blkptr_t *bp,
607     const zbookmark_phys_t *zb, dmu_tx_t *tx)
608 {
609 	dsl_pool_t *dp = scn->scn_dp;
610 	int zio_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCAN_THREAD;
611 	int err;
612 
613 	if (BP_GET_LEVEL(bp) > 0) {
614 		uint32_t flags = ARC_WAIT;
615 		int i;
616 		blkptr_t *cbp;
617 		int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
618 		arc_buf_t *buf;
619 
620 		err = arc_read(NULL, dp->dp_spa, bp, arc_getbuf_func, &buf,
621 		    ZIO_PRIORITY_ASYNC_READ, zio_flags, &flags, zb);
622 		if (err) {
623 			scn->scn_phys.scn_errors++;
624 			return (err);
625 		}
626 		for (i = 0, cbp = buf->b_data; i < epb; i++, cbp++) {
627 			dsl_scan_prefetch(scn, buf, cbp, zb->zb_objset,
628 			    zb->zb_object, zb->zb_blkid * epb + i);
629 		}
630 		for (i = 0, cbp = buf->b_data; i < epb; i++, cbp++) {
631 			zbookmark_phys_t czb;
632 
633 			SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
634 			    zb->zb_level - 1,
635 			    zb->zb_blkid * epb + i);
636 			dsl_scan_visitbp(cbp, &czb, dnp,
637 			    ds, scn, ostype, tx);
638 		}
639 		(void) arc_buf_remove_ref(buf, &buf);
640 	} else if (BP_GET_TYPE(bp) == DMU_OT_DNODE) {
641 		uint32_t flags = ARC_WAIT;
642 		dnode_phys_t *cdnp;
643 		int i, j;
644 		int epb = BP_GET_LSIZE(bp) >> DNODE_SHIFT;
645 		arc_buf_t *buf;
646 
647 		err = arc_read(NULL, dp->dp_spa, bp, arc_getbuf_func, &buf,
648 		    ZIO_PRIORITY_ASYNC_READ, zio_flags, &flags, zb);
649 		if (err) {
650 			scn->scn_phys.scn_errors++;
651 			return (err);
652 		}
653 		for (i = 0, cdnp = buf->b_data; i < epb; i++, cdnp++) {
654 			for (j = 0; j < cdnp->dn_nblkptr; j++) {
655 				blkptr_t *cbp = &cdnp->dn_blkptr[j];
656 				dsl_scan_prefetch(scn, buf, cbp,
657 				    zb->zb_objset, zb->zb_blkid * epb + i, j);
658 			}
659 		}
660 		for (i = 0, cdnp = buf->b_data; i < epb; i++, cdnp++) {
661 			dsl_scan_visitdnode(scn, ds, ostype,
662 			    cdnp, zb->zb_blkid * epb + i, tx);
663 		}
664 
665 		(void) arc_buf_remove_ref(buf, &buf);
666 	} else if (BP_GET_TYPE(bp) == DMU_OT_OBJSET) {
667 		uint32_t flags = ARC_WAIT;
668 		objset_phys_t *osp;
669 		arc_buf_t *buf;
670 
671 		err = arc_read(NULL, dp->dp_spa, bp, arc_getbuf_func, &buf,
672 		    ZIO_PRIORITY_ASYNC_READ, zio_flags, &flags, zb);
673 		if (err) {
674 			scn->scn_phys.scn_errors++;
675 			return (err);
676 		}
677 
678 		osp = buf->b_data;
679 
680 		dsl_scan_visitdnode(scn, ds, osp->os_type,
681 		    &osp->os_meta_dnode, DMU_META_DNODE_OBJECT, tx);
682 
683 		if (OBJSET_BUF_HAS_USERUSED(buf)) {
684 			/*
685 			 * We also always visit user/group accounting
686 			 * objects, and never skip them, even if we are
687 			 * pausing.  This is necessary so that the space
688 			 * deltas from this txg get integrated.
689 			 */
690 			dsl_scan_visitdnode(scn, ds, osp->os_type,
691 			    &osp->os_groupused_dnode,
692 			    DMU_GROUPUSED_OBJECT, tx);
693 			dsl_scan_visitdnode(scn, ds, osp->os_type,
694 			    &osp->os_userused_dnode,
695 			    DMU_USERUSED_OBJECT, tx);
696 		}
697 		(void) arc_buf_remove_ref(buf, &buf);
698 	}
699 
700 	return (0);
701 }
702 
703 static void
704 dsl_scan_visitdnode(dsl_scan_t *scn, dsl_dataset_t *ds,
705     dmu_objset_type_t ostype, dnode_phys_t *dnp,
706     uint64_t object, dmu_tx_t *tx)
707 {
708 	int j;
709 
710 	for (j = 0; j < dnp->dn_nblkptr; j++) {
711 		zbookmark_phys_t czb;
712 
713 		SET_BOOKMARK(&czb, ds ? ds->ds_object : 0, object,
714 		    dnp->dn_nlevels - 1, j);
715 		dsl_scan_visitbp(&dnp->dn_blkptr[j],
716 		    &czb, dnp, ds, scn, ostype, tx);
717 	}
718 
719 	if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {
720 		zbookmark_phys_t czb;
721 		SET_BOOKMARK(&czb, ds ? ds->ds_object : 0, object,
722 		    0, DMU_SPILL_BLKID);
723 		dsl_scan_visitbp(&dnp->dn_spill,
724 		    &czb, dnp, ds, scn, ostype, tx);
725 	}
726 }
727 
728 /*
729  * The arguments are in this order because mdb can only print the
730  * first 5; we want them to be useful.
731  */
732 static void
733 dsl_scan_visitbp(blkptr_t *bp, const zbookmark_phys_t *zb,
734     dnode_phys_t *dnp, dsl_dataset_t *ds, dsl_scan_t *scn,
735     dmu_objset_type_t ostype, dmu_tx_t *tx)
736 {
737 	dsl_pool_t *dp = scn->scn_dp;
738 	arc_buf_t *buf = NULL;
739 	blkptr_t bp_toread = *bp;
740 
741 	/* ASSERT(pbuf == NULL || arc_released(pbuf)); */
742 
743 	if (dsl_scan_check_pause(scn, zb))
744 		return;
745 
746 	if (dsl_scan_check_resume(scn, dnp, zb))
747 		return;
748 
749 	if (BP_IS_HOLE(bp))
750 		return;
751 
752 	scn->scn_visited_this_txg++;
753 
754 	dprintf_bp(bp,
755 	    "visiting ds=%p/%llu zb=%llx/%llx/%llx/%llx bp=%p",
756 	    ds, ds ? ds->ds_object : 0,
757 	    zb->zb_objset, zb->zb_object, zb->zb_level, zb->zb_blkid,
758 	    bp);
759 
760 	if (bp->blk_birth <= scn->scn_phys.scn_cur_min_txg)
761 		return;
762 
763 	if (dsl_scan_recurse(scn, ds, ostype, dnp, &bp_toread, zb, tx) != 0)
764 		return;
765 
766 	/*
767 	 * If dsl_scan_ddt() has aready visited this block, it will have
768 	 * already done any translations or scrubbing, so don't call the
769 	 * callback again.
770 	 */
771 	if (ddt_class_contains(dp->dp_spa,
772 	    scn->scn_phys.scn_ddt_class_max, bp)) {
773 		ASSERT(buf == NULL);
774 		return;
775 	}
776 
777 	/*
778 	 * If this block is from the future (after cur_max_txg), then we
779 	 * are doing this on behalf of a deleted snapshot, and we will
780 	 * revisit the future block on the next pass of this dataset.
781 	 * Don't scan it now unless we need to because something
782 	 * under it was modified.
783 	 */
784 	if (BP_PHYSICAL_BIRTH(bp) <= scn->scn_phys.scn_cur_max_txg) {
785 		scan_funcs[scn->scn_phys.scn_func](dp, bp, zb);
786 	}
787 }
788 
789 static void
790 dsl_scan_visit_rootbp(dsl_scan_t *scn, dsl_dataset_t *ds, blkptr_t *bp,
791     dmu_tx_t *tx)
792 {
793 	zbookmark_phys_t zb;
794 
795 	SET_BOOKMARK(&zb, ds ? ds->ds_object : DMU_META_OBJSET,
796 	    ZB_ROOT_OBJECT, ZB_ROOT_LEVEL, ZB_ROOT_BLKID);
797 	dsl_scan_visitbp(bp, &zb, NULL,
798 	    ds, scn, DMU_OST_NONE, tx);
799 
800 	dprintf_ds(ds, "finished scan%s", "");
801 }
802 
803 void
804 dsl_scan_ds_destroyed(dsl_dataset_t *ds, dmu_tx_t *tx)
805 {
806 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
807 	dsl_scan_t *scn = dp->dp_scan;
808 	uint64_t mintxg;
809 
810 	if (scn->scn_phys.scn_state != DSS_SCANNING)
811 		return;
812 
813 	if (scn->scn_phys.scn_bookmark.zb_objset == ds->ds_object) {
814 		if (dsl_dataset_is_snapshot(ds)) {
815 			/* Note, scn_cur_{min,max}_txg stays the same. */
816 			scn->scn_phys.scn_bookmark.zb_objset =
817 			    ds->ds_phys->ds_next_snap_obj;
818 			zfs_dbgmsg("destroying ds %llu; currently traversing; "
819 			    "reset zb_objset to %llu",
820 			    (u_longlong_t)ds->ds_object,
821 			    (u_longlong_t)ds->ds_phys->ds_next_snap_obj);
822 			scn->scn_phys.scn_flags |= DSF_VISIT_DS_AGAIN;
823 		} else {
824 			SET_BOOKMARK(&scn->scn_phys.scn_bookmark,
825 			    ZB_DESTROYED_OBJSET, 0, 0, 0);
826 			zfs_dbgmsg("destroying ds %llu; currently traversing; "
827 			    "reset bookmark to -1,0,0,0",
828 			    (u_longlong_t)ds->ds_object);
829 		}
830 	} else if (zap_lookup_int_key(dp->dp_meta_objset,
831 	    scn->scn_phys.scn_queue_obj, ds->ds_object, &mintxg) == 0) {
832 		ASSERT3U(ds->ds_phys->ds_num_children, <=, 1);
833 		VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
834 		    scn->scn_phys.scn_queue_obj, ds->ds_object, tx));
835 		if (dsl_dataset_is_snapshot(ds)) {
836 			/*
837 			 * We keep the same mintxg; it could be >
838 			 * ds_creation_txg if the previous snapshot was
839 			 * deleted too.
840 			 */
841 			VERIFY(zap_add_int_key(dp->dp_meta_objset,
842 			    scn->scn_phys.scn_queue_obj,
843 			    ds->ds_phys->ds_next_snap_obj, mintxg, tx) == 0);
844 			zfs_dbgmsg("destroying ds %llu; in queue; "
845 			    "replacing with %llu",
846 			    (u_longlong_t)ds->ds_object,
847 			    (u_longlong_t)ds->ds_phys->ds_next_snap_obj);
848 		} else {
849 			zfs_dbgmsg("destroying ds %llu; in queue; removing",
850 			    (u_longlong_t)ds->ds_object);
851 		}
852 	} else {
853 		zfs_dbgmsg("destroying ds %llu; ignoring",
854 		    (u_longlong_t)ds->ds_object);
855 	}
856 
857 	/*
858 	 * dsl_scan_sync() should be called after this, and should sync
859 	 * out our changed state, but just to be safe, do it here.
860 	 */
861 	dsl_scan_sync_state(scn, tx);
862 }
863 
864 void
865 dsl_scan_ds_snapshotted(dsl_dataset_t *ds, dmu_tx_t *tx)
866 {
867 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
868 	dsl_scan_t *scn = dp->dp_scan;
869 	uint64_t mintxg;
870 
871 	if (scn->scn_phys.scn_state != DSS_SCANNING)
872 		return;
873 
874 	ASSERT(ds->ds_phys->ds_prev_snap_obj != 0);
875 
876 	if (scn->scn_phys.scn_bookmark.zb_objset == ds->ds_object) {
877 		scn->scn_phys.scn_bookmark.zb_objset =
878 		    ds->ds_phys->ds_prev_snap_obj;
879 		zfs_dbgmsg("snapshotting ds %llu; currently traversing; "
880 		    "reset zb_objset to %llu",
881 		    (u_longlong_t)ds->ds_object,
882 		    (u_longlong_t)ds->ds_phys->ds_prev_snap_obj);
883 	} else if (zap_lookup_int_key(dp->dp_meta_objset,
884 	    scn->scn_phys.scn_queue_obj, ds->ds_object, &mintxg) == 0) {
885 		VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
886 		    scn->scn_phys.scn_queue_obj, ds->ds_object, tx));
887 		VERIFY(zap_add_int_key(dp->dp_meta_objset,
888 		    scn->scn_phys.scn_queue_obj,
889 		    ds->ds_phys->ds_prev_snap_obj, mintxg, tx) == 0);
890 		zfs_dbgmsg("snapshotting ds %llu; in queue; "
891 		    "replacing with %llu",
892 		    (u_longlong_t)ds->ds_object,
893 		    (u_longlong_t)ds->ds_phys->ds_prev_snap_obj);
894 	}
895 	dsl_scan_sync_state(scn, tx);
896 }
897 
898 void
899 dsl_scan_ds_clone_swapped(dsl_dataset_t *ds1, dsl_dataset_t *ds2, dmu_tx_t *tx)
900 {
901 	dsl_pool_t *dp = ds1->ds_dir->dd_pool;
902 	dsl_scan_t *scn = dp->dp_scan;
903 	uint64_t mintxg;
904 
905 	if (scn->scn_phys.scn_state != DSS_SCANNING)
906 		return;
907 
908 	if (scn->scn_phys.scn_bookmark.zb_objset == ds1->ds_object) {
909 		scn->scn_phys.scn_bookmark.zb_objset = ds2->ds_object;
910 		zfs_dbgmsg("clone_swap ds %llu; currently traversing; "
911 		    "reset zb_objset to %llu",
912 		    (u_longlong_t)ds1->ds_object,
913 		    (u_longlong_t)ds2->ds_object);
914 	} else if (scn->scn_phys.scn_bookmark.zb_objset == ds2->ds_object) {
915 		scn->scn_phys.scn_bookmark.zb_objset = ds1->ds_object;
916 		zfs_dbgmsg("clone_swap ds %llu; currently traversing; "
917 		    "reset zb_objset to %llu",
918 		    (u_longlong_t)ds2->ds_object,
919 		    (u_longlong_t)ds1->ds_object);
920 	}
921 
922 	if (zap_lookup_int_key(dp->dp_meta_objset, scn->scn_phys.scn_queue_obj,
923 	    ds1->ds_object, &mintxg) == 0) {
924 		int err;
925 
926 		ASSERT3U(mintxg, ==, ds1->ds_phys->ds_prev_snap_txg);
927 		ASSERT3U(mintxg, ==, ds2->ds_phys->ds_prev_snap_txg);
928 		VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
929 		    scn->scn_phys.scn_queue_obj, ds1->ds_object, tx));
930 		err = zap_add_int_key(dp->dp_meta_objset,
931 		    scn->scn_phys.scn_queue_obj, ds2->ds_object, mintxg, tx);
932 		VERIFY(err == 0 || err == EEXIST);
933 		if (err == EEXIST) {
934 			/* Both were there to begin with */
935 			VERIFY(0 == zap_add_int_key(dp->dp_meta_objset,
936 			    scn->scn_phys.scn_queue_obj,
937 			    ds1->ds_object, mintxg, tx));
938 		}
939 		zfs_dbgmsg("clone_swap ds %llu; in queue; "
940 		    "replacing with %llu",
941 		    (u_longlong_t)ds1->ds_object,
942 		    (u_longlong_t)ds2->ds_object);
943 	} else if (zap_lookup_int_key(dp->dp_meta_objset,
944 	    scn->scn_phys.scn_queue_obj, ds2->ds_object, &mintxg) == 0) {
945 		ASSERT3U(mintxg, ==, ds1->ds_phys->ds_prev_snap_txg);
946 		ASSERT3U(mintxg, ==, ds2->ds_phys->ds_prev_snap_txg);
947 		VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
948 		    scn->scn_phys.scn_queue_obj, ds2->ds_object, tx));
949 		VERIFY(0 == zap_add_int_key(dp->dp_meta_objset,
950 		    scn->scn_phys.scn_queue_obj, ds1->ds_object, mintxg, tx));
951 		zfs_dbgmsg("clone_swap ds %llu; in queue; "
952 		    "replacing with %llu",
953 		    (u_longlong_t)ds2->ds_object,
954 		    (u_longlong_t)ds1->ds_object);
955 	}
956 
957 	dsl_scan_sync_state(scn, tx);
958 }
959 
960 struct enqueue_clones_arg {
961 	dmu_tx_t *tx;
962 	uint64_t originobj;
963 };
964 
965 /* ARGSUSED */
966 static int
967 enqueue_clones_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)
968 {
969 	struct enqueue_clones_arg *eca = arg;
970 	dsl_dataset_t *ds;
971 	int err;
972 	dsl_scan_t *scn = dp->dp_scan;
973 
974 	if (hds->ds_dir->dd_phys->dd_origin_obj != eca->originobj)
975 		return (0);
976 
977 	err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);
978 	if (err)
979 		return (err);
980 
981 	while (ds->ds_phys->ds_prev_snap_obj != eca->originobj) {
982 		dsl_dataset_t *prev;
983 		err = dsl_dataset_hold_obj(dp,
984 		    ds->ds_phys->ds_prev_snap_obj, FTAG, &prev);
985 
986 		dsl_dataset_rele(ds, FTAG);
987 		if (err)
988 			return (err);
989 		ds = prev;
990 	}
991 	VERIFY(zap_add_int_key(dp->dp_meta_objset,
992 	    scn->scn_phys.scn_queue_obj, ds->ds_object,
993 	    ds->ds_phys->ds_prev_snap_txg, eca->tx) == 0);
994 	dsl_dataset_rele(ds, FTAG);
995 	return (0);
996 }
997 
998 static void
999 dsl_scan_visitds(dsl_scan_t *scn, uint64_t dsobj, dmu_tx_t *tx)
1000 {
1001 	dsl_pool_t *dp = scn->scn_dp;
1002 	dsl_dataset_t *ds;
1003 	objset_t *os;
1004 
1005 	VERIFY3U(0, ==, dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
1006 
1007 	if (dmu_objset_from_ds(ds, &os))
1008 		goto out;
1009 
1010 	/*
1011 	 * Only the ZIL in the head (non-snapshot) is valid.  Even though
1012 	 * snapshots can have ZIL block pointers (which may be the same
1013 	 * BP as in the head), they must be ignored.  So we traverse the
1014 	 * ZIL here, rather than in scan_recurse(), because the regular
1015 	 * snapshot block-sharing rules don't apply to it.
1016 	 */
1017 	if (DSL_SCAN_IS_SCRUB_RESILVER(scn) && !dsl_dataset_is_snapshot(ds))
1018 		dsl_scan_zil(dp, &os->os_zil_header);
1019 
1020 	/*
1021 	 * Iterate over the bps in this ds.
1022 	 */
1023 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
1024 	dsl_scan_visit_rootbp(scn, ds, &ds->ds_phys->ds_bp, tx);
1025 
1026 	char *dsname = kmem_alloc(ZFS_MAXNAMELEN, KM_SLEEP);
1027 	dsl_dataset_name(ds, dsname);
1028 	zfs_dbgmsg("scanned dataset %llu (%s) with min=%llu max=%llu; "
1029 	    "pausing=%u",
1030 	    (longlong_t)dsobj, dsname,
1031 	    (longlong_t)scn->scn_phys.scn_cur_min_txg,
1032 	    (longlong_t)scn->scn_phys.scn_cur_max_txg,
1033 	    (int)scn->scn_pausing);
1034 	kmem_free(dsname, ZFS_MAXNAMELEN);
1035 
1036 	if (scn->scn_pausing)
1037 		goto out;
1038 
1039 	/*
1040 	 * We've finished this pass over this dataset.
1041 	 */
1042 
1043 	/*
1044 	 * If we did not completely visit this dataset, do another pass.
1045 	 */
1046 	if (scn->scn_phys.scn_flags & DSF_VISIT_DS_AGAIN) {
1047 		zfs_dbgmsg("incomplete pass; visiting again");
1048 		scn->scn_phys.scn_flags &= ~DSF_VISIT_DS_AGAIN;
1049 		VERIFY(zap_add_int_key(dp->dp_meta_objset,
1050 		    scn->scn_phys.scn_queue_obj, ds->ds_object,
1051 		    scn->scn_phys.scn_cur_max_txg, tx) == 0);
1052 		goto out;
1053 	}
1054 
1055 	/*
1056 	 * Add descendent datasets to work queue.
1057 	 */
1058 	if (ds->ds_phys->ds_next_snap_obj != 0) {
1059 		VERIFY(zap_add_int_key(dp->dp_meta_objset,
1060 		    scn->scn_phys.scn_queue_obj, ds->ds_phys->ds_next_snap_obj,
1061 		    ds->ds_phys->ds_creation_txg, tx) == 0);
1062 	}
1063 	if (ds->ds_phys->ds_num_children > 1) {
1064 		boolean_t usenext = B_FALSE;
1065 		if (ds->ds_phys->ds_next_clones_obj != 0) {
1066 			uint64_t count;
1067 			/*
1068 			 * A bug in a previous version of the code could
1069 			 * cause upgrade_clones_cb() to not set
1070 			 * ds_next_snap_obj when it should, leading to a
1071 			 * missing entry.  Therefore we can only use the
1072 			 * next_clones_obj when its count is correct.
1073 			 */
1074 			int err = zap_count(dp->dp_meta_objset,
1075 			    ds->ds_phys->ds_next_clones_obj, &count);
1076 			if (err == 0 &&
1077 			    count == ds->ds_phys->ds_num_children - 1)
1078 				usenext = B_TRUE;
1079 		}
1080 
1081 		if (usenext) {
1082 			VERIFY0(zap_join_key(dp->dp_meta_objset,
1083 			    ds->ds_phys->ds_next_clones_obj,
1084 			    scn->scn_phys.scn_queue_obj,
1085 			    ds->ds_phys->ds_creation_txg, tx));
1086 		} else {
1087 			struct enqueue_clones_arg eca;
1088 			eca.tx = tx;
1089 			eca.originobj = ds->ds_object;
1090 
1091 			VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
1092 			    enqueue_clones_cb, &eca, DS_FIND_CHILDREN));
1093 		}
1094 	}
1095 
1096 out:
1097 	dsl_dataset_rele(ds, FTAG);
1098 }
1099 
1100 /* ARGSUSED */
1101 static int
1102 enqueue_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)
1103 {
1104 	dmu_tx_t *tx = arg;
1105 	dsl_dataset_t *ds;
1106 	int err;
1107 	dsl_scan_t *scn = dp->dp_scan;
1108 
1109 	err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);
1110 	if (err)
1111 		return (err);
1112 
1113 	while (ds->ds_phys->ds_prev_snap_obj != 0) {
1114 		dsl_dataset_t *prev;
1115 		err = dsl_dataset_hold_obj(dp, ds->ds_phys->ds_prev_snap_obj,
1116 		    FTAG, &prev);
1117 		if (err) {
1118 			dsl_dataset_rele(ds, FTAG);
1119 			return (err);
1120 		}
1121 
1122 		/*
1123 		 * If this is a clone, we don't need to worry about it for now.
1124 		 */
1125 		if (prev->ds_phys->ds_next_snap_obj != ds->ds_object) {
1126 			dsl_dataset_rele(ds, FTAG);
1127 			dsl_dataset_rele(prev, FTAG);
1128 			return (0);
1129 		}
1130 		dsl_dataset_rele(ds, FTAG);
1131 		ds = prev;
1132 	}
1133 
1134 	VERIFY(zap_add_int_key(dp->dp_meta_objset, scn->scn_phys.scn_queue_obj,
1135 	    ds->ds_object, ds->ds_phys->ds_prev_snap_txg, tx) == 0);
1136 	dsl_dataset_rele(ds, FTAG);
1137 	return (0);
1138 }
1139 
1140 /*
1141  * Scrub/dedup interaction.
1142  *
1143  * If there are N references to a deduped block, we don't want to scrub it
1144  * N times -- ideally, we should scrub it exactly once.
1145  *
1146  * We leverage the fact that the dde's replication class (enum ddt_class)
1147  * is ordered from highest replication class (DDT_CLASS_DITTO) to lowest
1148  * (DDT_CLASS_UNIQUE) so that we may walk the DDT in that order.
1149  *
1150  * To prevent excess scrubbing, the scrub begins by walking the DDT
1151  * to find all blocks with refcnt > 1, and scrubs each of these once.
1152  * Since there are two replication classes which contain blocks with
1153  * refcnt > 1, we scrub the highest replication class (DDT_CLASS_DITTO) first.
1154  * Finally the top-down scrub begins, only visiting blocks with refcnt == 1.
1155  *
1156  * There would be nothing more to say if a block's refcnt couldn't change
1157  * during a scrub, but of course it can so we must account for changes
1158  * in a block's replication class.
1159  *
1160  * Here's an example of what can occur:
1161  *
1162  * If a block has refcnt > 1 during the DDT scrub phase, but has refcnt == 1
1163  * when visited during the top-down scrub phase, it will be scrubbed twice.
1164  * This negates our scrub optimization, but is otherwise harmless.
1165  *
1166  * If a block has refcnt == 1 during the DDT scrub phase, but has refcnt > 1
1167  * on each visit during the top-down scrub phase, it will never be scrubbed.
1168  * To catch this, ddt_sync_entry() notifies the scrub code whenever a block's
1169  * reference class transitions to a higher level (i.e DDT_CLASS_UNIQUE to
1170  * DDT_CLASS_DUPLICATE); if it transitions from refcnt == 1 to refcnt > 1
1171  * while a scrub is in progress, it scrubs the block right then.
1172  */
1173 static void
1174 dsl_scan_ddt(dsl_scan_t *scn, dmu_tx_t *tx)
1175 {
1176 	ddt_bookmark_t *ddb = &scn->scn_phys.scn_ddt_bookmark;
1177 	ddt_entry_t dde = { 0 };
1178 	int error;
1179 	uint64_t n = 0;
1180 
1181 	while ((error = ddt_walk(scn->scn_dp->dp_spa, ddb, &dde)) == 0) {
1182 		ddt_t *ddt;
1183 
1184 		if (ddb->ddb_class > scn->scn_phys.scn_ddt_class_max)
1185 			break;
1186 		dprintf("visiting ddb=%llu/%llu/%llu/%llx\n",
1187 		    (longlong_t)ddb->ddb_class,
1188 		    (longlong_t)ddb->ddb_type,
1189 		    (longlong_t)ddb->ddb_checksum,
1190 		    (longlong_t)ddb->ddb_cursor);
1191 
1192 		/* There should be no pending changes to the dedup table */
1193 		ddt = scn->scn_dp->dp_spa->spa_ddt[ddb->ddb_checksum];
1194 		ASSERT(avl_first(&ddt->ddt_tree) == NULL);
1195 
1196 		dsl_scan_ddt_entry(scn, ddb->ddb_checksum, &dde, tx);
1197 		n++;
1198 
1199 		if (dsl_scan_check_pause(scn, NULL))
1200 			break;
1201 	}
1202 
1203 	zfs_dbgmsg("scanned %llu ddt entries with class_max = %u; pausing=%u",
1204 	    (longlong_t)n, (int)scn->scn_phys.scn_ddt_class_max,
1205 	    (int)scn->scn_pausing);
1206 
1207 	ASSERT(error == 0 || error == ENOENT);
1208 	ASSERT(error != ENOENT ||
1209 	    ddb->ddb_class > scn->scn_phys.scn_ddt_class_max);
1210 }
1211 
1212 /* ARGSUSED */
1213 void
1214 dsl_scan_ddt_entry(dsl_scan_t *scn, enum zio_checksum checksum,
1215     ddt_entry_t *dde, dmu_tx_t *tx)
1216 {
1217 	const ddt_key_t *ddk = &dde->dde_key;
1218 	ddt_phys_t *ddp = dde->dde_phys;
1219 	blkptr_t bp;
1220 	zbookmark_phys_t zb = { 0 };
1221 
1222 	if (scn->scn_phys.scn_state != DSS_SCANNING)
1223 		return;
1224 
1225 	for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
1226 		if (ddp->ddp_phys_birth == 0 ||
1227 		    ddp->ddp_phys_birth > scn->scn_phys.scn_max_txg)
1228 			continue;
1229 		ddt_bp_create(checksum, ddk, ddp, &bp);
1230 
1231 		scn->scn_visited_this_txg++;
1232 		scan_funcs[scn->scn_phys.scn_func](scn->scn_dp, &bp, &zb);
1233 	}
1234 }
1235 
1236 static void
1237 dsl_scan_visit(dsl_scan_t *scn, dmu_tx_t *tx)
1238 {
1239 	dsl_pool_t *dp = scn->scn_dp;
1240 	zap_cursor_t zc;
1241 	zap_attribute_t za;
1242 
1243 	if (scn->scn_phys.scn_ddt_bookmark.ddb_class <=
1244 	    scn->scn_phys.scn_ddt_class_max) {
1245 		scn->scn_phys.scn_cur_min_txg = scn->scn_phys.scn_min_txg;
1246 		scn->scn_phys.scn_cur_max_txg = scn->scn_phys.scn_max_txg;
1247 		dsl_scan_ddt(scn, tx);
1248 		if (scn->scn_pausing)
1249 			return;
1250 	}
1251 
1252 	if (scn->scn_phys.scn_bookmark.zb_objset == DMU_META_OBJSET) {
1253 		/* First do the MOS & ORIGIN */
1254 
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_visit_rootbp(scn, NULL,
1258 		    &dp->dp_meta_rootbp, tx);
1259 		spa_set_rootblkptr(dp->dp_spa, &dp->dp_meta_rootbp);
1260 		if (scn->scn_pausing)
1261 			return;
1262 
1263 		if (spa_version(dp->dp_spa) < SPA_VERSION_DSL_SCRUB) {
1264 			VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
1265 			    enqueue_cb, tx, DS_FIND_CHILDREN));
1266 		} else {
1267 			dsl_scan_visitds(scn,
1268 			    dp->dp_origin_snap->ds_object, tx);
1269 		}
1270 		ASSERT(!scn->scn_pausing);
1271 	} else if (scn->scn_phys.scn_bookmark.zb_objset !=
1272 	    ZB_DESTROYED_OBJSET) {
1273 		/*
1274 		 * If we were paused, continue from here.  Note if the
1275 		 * ds we were paused on was deleted, the zb_objset may
1276 		 * be -1, so we will skip this and find a new objset
1277 		 * below.
1278 		 */
1279 		dsl_scan_visitds(scn, scn->scn_phys.scn_bookmark.zb_objset, tx);
1280 		if (scn->scn_pausing)
1281 			return;
1282 	}
1283 
1284 	/*
1285 	 * In case we were paused right at the end of the ds, zero the
1286 	 * bookmark so we don't think that we're still trying to resume.
1287 	 */
1288 	bzero(&scn->scn_phys.scn_bookmark, sizeof (zbookmark_phys_t));
1289 
1290 	/* keep pulling things out of the zap-object-as-queue */
1291 	while (zap_cursor_init(&zc, dp->dp_meta_objset,
1292 	    scn->scn_phys.scn_queue_obj),
1293 	    zap_cursor_retrieve(&zc, &za) == 0) {
1294 		dsl_dataset_t *ds;
1295 		uint64_t dsobj;
1296 
1297 		dsobj = strtonum(za.za_name, NULL);
1298 		VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
1299 		    scn->scn_phys.scn_queue_obj, dsobj, tx));
1300 
1301 		/* Set up min/max txg */
1302 		VERIFY3U(0, ==, dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
1303 		if (za.za_first_integer != 0) {
1304 			scn->scn_phys.scn_cur_min_txg =
1305 			    MAX(scn->scn_phys.scn_min_txg,
1306 			    za.za_first_integer);
1307 		} else {
1308 			scn->scn_phys.scn_cur_min_txg =
1309 			    MAX(scn->scn_phys.scn_min_txg,
1310 			    ds->ds_phys->ds_prev_snap_txg);
1311 		}
1312 		scn->scn_phys.scn_cur_max_txg = dsl_scan_ds_maxtxg(ds);
1313 		dsl_dataset_rele(ds, FTAG);
1314 
1315 		dsl_scan_visitds(scn, dsobj, tx);
1316 		zap_cursor_fini(&zc);
1317 		if (scn->scn_pausing)
1318 			return;
1319 	}
1320 	zap_cursor_fini(&zc);
1321 }
1322 
1323 static boolean_t
1324 dsl_scan_free_should_pause(dsl_scan_t *scn)
1325 {
1326 	uint64_t elapsed_nanosecs;
1327 
1328 	if (zfs_recover)
1329 		return (B_FALSE);
1330 
1331 	if (scn->scn_visited_this_txg >= zfs_free_max_blocks)
1332 		return (B_TRUE);
1333 
1334 	elapsed_nanosecs = gethrtime() - scn->scn_sync_start_time;
1335 	return (elapsed_nanosecs / NANOSEC > zfs_txg_timeout ||
1336 	    (NSEC2MSEC(elapsed_nanosecs) > zfs_free_min_time_ms &&
1337 	    txg_sync_waiting(scn->scn_dp)) ||
1338 	    spa_shutting_down(scn->scn_dp->dp_spa));
1339 }
1340 
1341 static int
1342 dsl_scan_free_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1343 {
1344 	dsl_scan_t *scn = arg;
1345 
1346 	if (!scn->scn_is_bptree ||
1347 	    (BP_GET_LEVEL(bp) == 0 && BP_GET_TYPE(bp) != DMU_OT_OBJSET)) {
1348 		if (dsl_scan_free_should_pause(scn))
1349 			return (SET_ERROR(ERESTART));
1350 	}
1351 
1352 	zio_nowait(zio_free_sync(scn->scn_zio_root, scn->scn_dp->dp_spa,
1353 	    dmu_tx_get_txg(tx), bp, 0));
1354 	dsl_dir_diduse_space(tx->tx_pool->dp_free_dir, DD_USED_HEAD,
1355 	    -bp_get_dsize_sync(scn->scn_dp->dp_spa, bp),
1356 	    -BP_GET_PSIZE(bp), -BP_GET_UCSIZE(bp), tx);
1357 	scn->scn_visited_this_txg++;
1358 	return (0);
1359 }
1360 
1361 boolean_t
1362 dsl_scan_active(dsl_scan_t *scn)
1363 {
1364 	spa_t *spa = scn->scn_dp->dp_spa;
1365 	uint64_t used = 0, comp, uncomp;
1366 
1367 	if (spa->spa_load_state != SPA_LOAD_NONE)
1368 		return (B_FALSE);
1369 	if (spa_shutting_down(spa))
1370 		return (B_FALSE);
1371 	if (scn->scn_phys.scn_state == DSS_SCANNING ||
1372 	    (scn->scn_async_destroying && !scn->scn_async_stalled))
1373 		return (B_TRUE);
1374 
1375 	if (spa_version(scn->scn_dp->dp_spa) >= SPA_VERSION_DEADLISTS) {
1376 		(void) bpobj_space(&scn->scn_dp->dp_free_bpobj,
1377 		    &used, &comp, &uncomp);
1378 	}
1379 	return (used != 0);
1380 }
1381 
1382 void
1383 dsl_scan_sync(dsl_pool_t *dp, dmu_tx_t *tx)
1384 {
1385 	dsl_scan_t *scn = dp->dp_scan;
1386 	spa_t *spa = dp->dp_spa;
1387 	int err = 0;
1388 
1389 	/*
1390 	 * Check for scn_restart_txg before checking spa_load_state, so
1391 	 * that we can restart an old-style scan while the pool is being
1392 	 * imported (see dsl_scan_init).
1393 	 */
1394 	if (scn->scn_restart_txg != 0 &&
1395 	    scn->scn_restart_txg <= tx->tx_txg) {
1396 		pool_scan_func_t func = POOL_SCAN_SCRUB;
1397 		dsl_scan_done(scn, B_FALSE, tx);
1398 		if (vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL))
1399 			func = POOL_SCAN_RESILVER;
1400 		zfs_dbgmsg("restarting scan func=%u txg=%llu",
1401 		    func, tx->tx_txg);
1402 		dsl_scan_setup_sync(&func, tx);
1403 	}
1404 
1405 	/*
1406 	 * If the scan is inactive due to a stalled async destroy, try again.
1407 	 */
1408 	if ((!scn->scn_async_stalled && !dsl_scan_active(scn)) ||
1409 	    spa_sync_pass(dp->dp_spa) > 1)
1410 		return;
1411 
1412 	scn->scn_visited_this_txg = 0;
1413 	scn->scn_pausing = B_FALSE;
1414 	scn->scn_sync_start_time = gethrtime();
1415 	spa->spa_scrub_active = B_TRUE;
1416 
1417 	/*
1418 	 * First process the async destroys.  If we pause, don't do
1419 	 * any scrubbing or resilvering.  This ensures that there are no
1420 	 * async destroys while we are scanning, so the scan code doesn't
1421 	 * have to worry about traversing it.  It is also faster to free the
1422 	 * blocks than to scrub them.
1423 	 */
1424 	if (spa_version(dp->dp_spa) >= SPA_VERSION_DEADLISTS) {
1425 		scn->scn_is_bptree = B_FALSE;
1426 		scn->scn_zio_root = zio_root(dp->dp_spa, NULL,
1427 		    NULL, ZIO_FLAG_MUSTSUCCEED);
1428 		err = bpobj_iterate(&dp->dp_free_bpobj,
1429 		    dsl_scan_free_block_cb, scn, tx);
1430 		VERIFY3U(0, ==, zio_wait(scn->scn_zio_root));
1431 
1432 		if (err != 0 && err != ERESTART)
1433 			zfs_panic_recover("error %u from bpobj_iterate()", err);
1434 	}
1435 
1436 	if (err == 0 && spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) {
1437 		ASSERT(scn->scn_async_destroying);
1438 		scn->scn_is_bptree = B_TRUE;
1439 		scn->scn_zio_root = zio_root(dp->dp_spa, NULL,
1440 		    NULL, ZIO_FLAG_MUSTSUCCEED);
1441 		err = bptree_iterate(dp->dp_meta_objset,
1442 		    dp->dp_bptree_obj, B_TRUE, dsl_scan_free_block_cb, scn, tx);
1443 		VERIFY0(zio_wait(scn->scn_zio_root));
1444 
1445 		if (err == EIO || err == ECKSUM) {
1446 			err = 0;
1447 		} else if (err != 0 && err != ERESTART) {
1448 			zfs_panic_recover("error %u from "
1449 			    "traverse_dataset_destroyed()", err);
1450 		}
1451 
1452 		/*
1453 		 * If we didn't make progress, mark the async destroy as
1454 		 * stalled, so that we will not initiate a spa_sync() on
1455 		 * its behalf.
1456 		 */
1457 		scn->scn_async_stalled = (scn->scn_visited_this_txg == 0);
1458 
1459 		if (bptree_is_empty(dp->dp_meta_objset, dp->dp_bptree_obj)) {
1460 			/* finished; deactivate async destroy feature */
1461 			spa_feature_decr(spa, SPA_FEATURE_ASYNC_DESTROY, tx);
1462 			ASSERT(!spa_feature_is_active(spa,
1463 			    SPA_FEATURE_ASYNC_DESTROY));
1464 			VERIFY0(zap_remove(dp->dp_meta_objset,
1465 			    DMU_POOL_DIRECTORY_OBJECT,
1466 			    DMU_POOL_BPTREE_OBJ, tx));
1467 			VERIFY0(bptree_free(dp->dp_meta_objset,
1468 			    dp->dp_bptree_obj, tx));
1469 			dp->dp_bptree_obj = 0;
1470 			scn->scn_async_destroying = B_FALSE;
1471 		}
1472 	}
1473 	if (scn->scn_visited_this_txg) {
1474 		zfs_dbgmsg("freed %llu blocks in %llums from "
1475 		    "free_bpobj/bptree txg %llu; err=%u",
1476 		    (longlong_t)scn->scn_visited_this_txg,
1477 		    (longlong_t)
1478 		    NSEC2MSEC(gethrtime() - scn->scn_sync_start_time),
1479 		    (longlong_t)tx->tx_txg, err);
1480 		scn->scn_visited_this_txg = 0;
1481 
1482 		/*
1483 		 * Write out changes to the DDT that may be required as a
1484 		 * result of the blocks freed.  This ensures that the DDT
1485 		 * is clean when a scrub/resilver runs.
1486 		 */
1487 		ddt_sync(spa, tx->tx_txg);
1488 	}
1489 	if (err != 0)
1490 		return;
1491 	if (!scn->scn_async_destroying && zfs_free_leak_on_eio &&
1492 	    (dp->dp_free_dir->dd_phys->dd_used_bytes != 0 ||
1493 	    dp->dp_free_dir->dd_phys->dd_compressed_bytes != 0 ||
1494 	    dp->dp_free_dir->dd_phys->dd_uncompressed_bytes != 0)) {
1495 		/*
1496 		 * We have finished background destroying, but there is still
1497 		 * some space left in the dp_free_dir. Transfer this leaked
1498 		 * space to the dp_leak_dir.
1499 		 */
1500 		if (dp->dp_leak_dir == NULL) {
1501 			rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
1502 			(void) dsl_dir_create_sync(dp, dp->dp_root_dir,
1503 			    LEAK_DIR_NAME, tx);
1504 			VERIFY0(dsl_pool_open_special_dir(dp,
1505 			    LEAK_DIR_NAME, &dp->dp_leak_dir));
1506 			rrw_exit(&dp->dp_config_rwlock, FTAG);
1507 		}
1508 		dsl_dir_diduse_space(dp->dp_leak_dir, DD_USED_HEAD,
1509 		    dp->dp_free_dir->dd_phys->dd_used_bytes,
1510 		    dp->dp_free_dir->dd_phys->dd_compressed_bytes,
1511 		    dp->dp_free_dir->dd_phys->dd_uncompressed_bytes, tx);
1512 		dsl_dir_diduse_space(dp->dp_free_dir, DD_USED_HEAD,
1513 		    -dp->dp_free_dir->dd_phys->dd_used_bytes,
1514 		    -dp->dp_free_dir->dd_phys->dd_compressed_bytes,
1515 		    -dp->dp_free_dir->dd_phys->dd_uncompressed_bytes, tx);
1516 	}
1517 	if (!scn->scn_async_destroying) {
1518 		/* finished; verify that space accounting went to zero */
1519 		ASSERT0(dp->dp_free_dir->dd_phys->dd_used_bytes);
1520 		ASSERT0(dp->dp_free_dir->dd_phys->dd_compressed_bytes);
1521 		ASSERT0(dp->dp_free_dir->dd_phys->dd_uncompressed_bytes);
1522 	}
1523 
1524 	if (scn->scn_phys.scn_state != DSS_SCANNING)
1525 		return;
1526 
1527 	if (scn->scn_done_txg == tx->tx_txg) {
1528 		ASSERT(!scn->scn_pausing);
1529 		/* finished with scan. */
1530 		zfs_dbgmsg("txg %llu scan complete", tx->tx_txg);
1531 		dsl_scan_done(scn, B_TRUE, tx);
1532 		ASSERT3U(spa->spa_scrub_inflight, ==, 0);
1533 		dsl_scan_sync_state(scn, tx);
1534 		return;
1535 	}
1536 
1537 	if (scn->scn_phys.scn_ddt_bookmark.ddb_class <=
1538 	    scn->scn_phys.scn_ddt_class_max) {
1539 		zfs_dbgmsg("doing scan sync txg %llu; "
1540 		    "ddt bm=%llu/%llu/%llu/%llx",
1541 		    (longlong_t)tx->tx_txg,
1542 		    (longlong_t)scn->scn_phys.scn_ddt_bookmark.ddb_class,
1543 		    (longlong_t)scn->scn_phys.scn_ddt_bookmark.ddb_type,
1544 		    (longlong_t)scn->scn_phys.scn_ddt_bookmark.ddb_checksum,
1545 		    (longlong_t)scn->scn_phys.scn_ddt_bookmark.ddb_cursor);
1546 		ASSERT(scn->scn_phys.scn_bookmark.zb_objset == 0);
1547 		ASSERT(scn->scn_phys.scn_bookmark.zb_object == 0);
1548 		ASSERT(scn->scn_phys.scn_bookmark.zb_level == 0);
1549 		ASSERT(scn->scn_phys.scn_bookmark.zb_blkid == 0);
1550 	} else {
1551 		zfs_dbgmsg("doing scan sync txg %llu; bm=%llu/%llu/%llu/%llu",
1552 		    (longlong_t)tx->tx_txg,
1553 		    (longlong_t)scn->scn_phys.scn_bookmark.zb_objset,
1554 		    (longlong_t)scn->scn_phys.scn_bookmark.zb_object,
1555 		    (longlong_t)scn->scn_phys.scn_bookmark.zb_level,
1556 		    (longlong_t)scn->scn_phys.scn_bookmark.zb_blkid);
1557 	}
1558 
1559 	scn->scn_zio_root = zio_root(dp->dp_spa, NULL,
1560 	    NULL, ZIO_FLAG_CANFAIL);
1561 	dsl_pool_config_enter(dp, FTAG);
1562 	dsl_scan_visit(scn, tx);
1563 	dsl_pool_config_exit(dp, FTAG);
1564 	(void) zio_wait(scn->scn_zio_root);
1565 	scn->scn_zio_root = NULL;
1566 
1567 	zfs_dbgmsg("visited %llu blocks in %llums",
1568 	    (longlong_t)scn->scn_visited_this_txg,
1569 	    (longlong_t)NSEC2MSEC(gethrtime() - scn->scn_sync_start_time));
1570 
1571 	if (!scn->scn_pausing) {
1572 		scn->scn_done_txg = tx->tx_txg + 1;
1573 		zfs_dbgmsg("txg %llu traversal complete, waiting till txg %llu",
1574 		    tx->tx_txg, scn->scn_done_txg);
1575 	}
1576 
1577 	if (DSL_SCAN_IS_SCRUB_RESILVER(scn)) {
1578 		mutex_enter(&spa->spa_scrub_lock);
1579 		while (spa->spa_scrub_inflight > 0) {
1580 			cv_wait(&spa->spa_scrub_io_cv,
1581 			    &spa->spa_scrub_lock);
1582 		}
1583 		mutex_exit(&spa->spa_scrub_lock);
1584 	}
1585 
1586 	dsl_scan_sync_state(scn, tx);
1587 }
1588 
1589 /*
1590  * This will start a new scan, or restart an existing one.
1591  */
1592 void
1593 dsl_resilver_restart(dsl_pool_t *dp, uint64_t txg)
1594 {
1595 	if (txg == 0) {
1596 		dmu_tx_t *tx;
1597 		tx = dmu_tx_create_dd(dp->dp_mos_dir);
1598 		VERIFY(0 == dmu_tx_assign(tx, TXG_WAIT));
1599 
1600 		txg = dmu_tx_get_txg(tx);
1601 		dp->dp_scan->scn_restart_txg = txg;
1602 		dmu_tx_commit(tx);
1603 	} else {
1604 		dp->dp_scan->scn_restart_txg = txg;
1605 	}
1606 	zfs_dbgmsg("restarting resilver txg=%llu", txg);
1607 }
1608 
1609 boolean_t
1610 dsl_scan_resilvering(dsl_pool_t *dp)
1611 {
1612 	return (dp->dp_scan->scn_phys.scn_state == DSS_SCANNING &&
1613 	    dp->dp_scan->scn_phys.scn_func == POOL_SCAN_RESILVER);
1614 }
1615 
1616 /*
1617  * scrub consumers
1618  */
1619 
1620 static void
1621 count_block(zfs_all_blkstats_t *zab, const blkptr_t *bp)
1622 {
1623 	int i;
1624 
1625 	/*
1626 	 * If we resume after a reboot, zab will be NULL; don't record
1627 	 * incomplete stats in that case.
1628 	 */
1629 	if (zab == NULL)
1630 		return;
1631 
1632 	for (i = 0; i < 4; i++) {
1633 		int l = (i < 2) ? BP_GET_LEVEL(bp) : DN_MAX_LEVELS;
1634 		int t = (i & 1) ? BP_GET_TYPE(bp) : DMU_OT_TOTAL;
1635 		if (t & DMU_OT_NEWTYPE)
1636 			t = DMU_OT_OTHER;
1637 		zfs_blkstat_t *zb = &zab->zab_type[l][t];
1638 		int equal;
1639 
1640 		zb->zb_count++;
1641 		zb->zb_asize += BP_GET_ASIZE(bp);
1642 		zb->zb_lsize += BP_GET_LSIZE(bp);
1643 		zb->zb_psize += BP_GET_PSIZE(bp);
1644 		zb->zb_gangs += BP_COUNT_GANG(bp);
1645 
1646 		switch (BP_GET_NDVAS(bp)) {
1647 		case 2:
1648 			if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
1649 			    DVA_GET_VDEV(&bp->blk_dva[1]))
1650 				zb->zb_ditto_2_of_2_samevdev++;
1651 			break;
1652 		case 3:
1653 			equal = (DVA_GET_VDEV(&bp->blk_dva[0]) ==
1654 			    DVA_GET_VDEV(&bp->blk_dva[1])) +
1655 			    (DVA_GET_VDEV(&bp->blk_dva[0]) ==
1656 			    DVA_GET_VDEV(&bp->blk_dva[2])) +
1657 			    (DVA_GET_VDEV(&bp->blk_dva[1]) ==
1658 			    DVA_GET_VDEV(&bp->blk_dva[2]));
1659 			if (equal == 1)
1660 				zb->zb_ditto_2_of_3_samevdev++;
1661 			else if (equal == 3)
1662 				zb->zb_ditto_3_of_3_samevdev++;
1663 			break;
1664 		}
1665 	}
1666 }
1667 
1668 static void
1669 dsl_scan_scrub_done(zio_t *zio)
1670 {
1671 	spa_t *spa = zio->io_spa;
1672 
1673 	zio_data_buf_free(zio->io_data, zio->io_size);
1674 
1675 	mutex_enter(&spa->spa_scrub_lock);
1676 	spa->spa_scrub_inflight--;
1677 	cv_broadcast(&spa->spa_scrub_io_cv);
1678 
1679 	if (zio->io_error && (zio->io_error != ECKSUM ||
1680 	    !(zio->io_flags & ZIO_FLAG_SPECULATIVE))) {
1681 		spa->spa_dsl_pool->dp_scan->scn_phys.scn_errors++;
1682 	}
1683 	mutex_exit(&spa->spa_scrub_lock);
1684 }
1685 
1686 static int
1687 dsl_scan_scrub_cb(dsl_pool_t *dp,
1688     const blkptr_t *bp, const zbookmark_phys_t *zb)
1689 {
1690 	dsl_scan_t *scn = dp->dp_scan;
1691 	size_t size = BP_GET_PSIZE(bp);
1692 	spa_t *spa = dp->dp_spa;
1693 	uint64_t phys_birth = BP_PHYSICAL_BIRTH(bp);
1694 	boolean_t needs_io;
1695 	int zio_flags = ZIO_FLAG_SCAN_THREAD | ZIO_FLAG_RAW | ZIO_FLAG_CANFAIL;
1696 	int scan_delay = 0;
1697 
1698 	if (phys_birth <= scn->scn_phys.scn_min_txg ||
1699 	    phys_birth >= scn->scn_phys.scn_max_txg)
1700 		return (0);
1701 
1702 	count_block(dp->dp_blkstats, bp);
1703 
1704 	if (BP_IS_EMBEDDED(bp))
1705 		return (0);
1706 
1707 	ASSERT(DSL_SCAN_IS_SCRUB_RESILVER(scn));
1708 	if (scn->scn_phys.scn_func == POOL_SCAN_SCRUB) {
1709 		zio_flags |= ZIO_FLAG_SCRUB;
1710 		needs_io = B_TRUE;
1711 		scan_delay = zfs_scrub_delay;
1712 	} else {
1713 		ASSERT3U(scn->scn_phys.scn_func, ==, POOL_SCAN_RESILVER);
1714 		zio_flags |= ZIO_FLAG_RESILVER;
1715 		needs_io = B_FALSE;
1716 		scan_delay = zfs_resilver_delay;
1717 	}
1718 
1719 	/* If it's an intent log block, failure is expected. */
1720 	if (zb->zb_level == ZB_ZIL_LEVEL)
1721 		zio_flags |= ZIO_FLAG_SPECULATIVE;
1722 
1723 	for (int d = 0; d < BP_GET_NDVAS(bp); d++) {
1724 		vdev_t *vd = vdev_lookup_top(spa,
1725 		    DVA_GET_VDEV(&bp->blk_dva[d]));
1726 
1727 		/*
1728 		 * Keep track of how much data we've examined so that
1729 		 * zpool(1M) status can make useful progress reports.
1730 		 */
1731 		scn->scn_phys.scn_examined += DVA_GET_ASIZE(&bp->blk_dva[d]);
1732 		spa->spa_scan_pass_exam += DVA_GET_ASIZE(&bp->blk_dva[d]);
1733 
1734 		/* if it's a resilver, this may not be in the target range */
1735 		if (!needs_io) {
1736 			if (DVA_GET_GANG(&bp->blk_dva[d])) {
1737 				/*
1738 				 * Gang members may be spread across multiple
1739 				 * vdevs, so the best estimate we have is the
1740 				 * scrub range, which has already been checked.
1741 				 * XXX -- it would be better to change our
1742 				 * allocation policy to ensure that all
1743 				 * gang members reside on the same vdev.
1744 				 */
1745 				needs_io = B_TRUE;
1746 			} else {
1747 				needs_io = vdev_dtl_contains(vd, DTL_PARTIAL,
1748 				    phys_birth, 1);
1749 			}
1750 		}
1751 	}
1752 
1753 	if (needs_io && !zfs_no_scrub_io) {
1754 		vdev_t *rvd = spa->spa_root_vdev;
1755 		uint64_t maxinflight = rvd->vdev_children * zfs_top_maxinflight;
1756 		void *data = zio_data_buf_alloc(size);
1757 
1758 		mutex_enter(&spa->spa_scrub_lock);
1759 		while (spa->spa_scrub_inflight >= maxinflight)
1760 			cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
1761 		spa->spa_scrub_inflight++;
1762 		mutex_exit(&spa->spa_scrub_lock);
1763 
1764 		/*
1765 		 * If we're seeing recent (zfs_scan_idle) "important" I/Os
1766 		 * then throttle our workload to limit the impact of a scan.
1767 		 */
1768 		if (ddi_get_lbolt64() - spa->spa_last_io <= zfs_scan_idle)
1769 			delay(scan_delay);
1770 
1771 		zio_nowait(zio_read(NULL, spa, bp, data, size,
1772 		    dsl_scan_scrub_done, NULL, ZIO_PRIORITY_SCRUB,
1773 		    zio_flags, zb));
1774 	}
1775 
1776 	/* do not relocate this block */
1777 	return (0);
1778 }
1779 
1780 int
1781 dsl_scan(dsl_pool_t *dp, pool_scan_func_t func)
1782 {
1783 	spa_t *spa = dp->dp_spa;
1784 
1785 	/*
1786 	 * Purge all vdev caches and probe all devices.  We do this here
1787 	 * rather than in sync context because this requires a writer lock
1788 	 * on the spa_config lock, which we can't do from sync context.  The
1789 	 * spa_scrub_reopen flag indicates that vdev_open() should not
1790 	 * attempt to start another scrub.
1791 	 */
1792 	spa_vdev_state_enter(spa, SCL_NONE);
1793 	spa->spa_scrub_reopen = B_TRUE;
1794 	vdev_reopen(spa->spa_root_vdev);
1795 	spa->spa_scrub_reopen = B_FALSE;
1796 	(void) spa_vdev_state_exit(spa, NULL, 0);
1797 
1798 	return (dsl_sync_task(spa_name(spa), dsl_scan_setup_check,
1799 	    dsl_scan_setup_sync, &func, 0, ZFS_SPACE_CHECK_NONE));
1800 }
1801