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