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