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