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