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