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