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