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