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