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