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