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