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