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