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