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