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