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