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