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