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