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