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