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