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