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