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