]> granicus.if.org Git - zfs/blob - module/zfs/dsl_scan.c
Fix for ARC sysctls ignored at runtime
[zfs] / 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, 2018 by Delphix. All rights reserved.
24  * Copyright 2016 Gary Mills
25  * Copyright (c) 2017 Datto Inc.
26  * Copyright 2019 Joyent, Inc.
27  */
28
29 #include <sys/dsl_scan.h>
30 #include <sys/dsl_pool.h>
31 #include <sys/dsl_dataset.h>
32 #include <sys/dsl_prop.h>
33 #include <sys/dsl_dir.h>
34 #include <sys/dsl_synctask.h>
35 #include <sys/dnode.h>
36 #include <sys/dmu_tx.h>
37 #include <sys/dmu_objset.h>
38 #include <sys/arc.h>
39 #include <sys/zap.h>
40 #include <sys/zio.h>
41 #include <sys/zfs_context.h>
42 #include <sys/fs/zfs.h>
43 #include <sys/zfs_znode.h>
44 #include <sys/spa_impl.h>
45 #include <sys/vdev_impl.h>
46 #include <sys/zil_impl.h>
47 #include <sys/zio_checksum.h>
48 #include <sys/ddt.h>
49 #include <sys/sa.h>
50 #include <sys/sa_impl.h>
51 #include <sys/zfeature.h>
52 #include <sys/abd.h>
53 #include <sys/range_tree.h>
54 #ifdef _KERNEL
55 #include <sys/zfs_vfsops.h>
56 #endif
57
58 /*
59  * Grand theory statement on scan queue sorting
60  *
61  * Scanning is implemented by recursively traversing all indirection levels
62  * in an object and reading all blocks referenced from said objects. This
63  * results in us approximately traversing the object from lowest logical
64  * offset to the highest. For best performance, we would want the logical
65  * blocks to be physically contiguous. However, this is frequently not the
66  * case with pools given the allocation patterns of copy-on-write filesystems.
67  * So instead, we put the I/Os into a reordering queue and issue them in a
68  * way that will most benefit physical disks (LBA-order).
69  *
70  * Queue management:
71  *
72  * Ideally, we would want to scan all metadata and queue up all block I/O
73  * prior to starting to issue it, because that allows us to do an optimal
74  * sorting job. This can however consume large amounts of memory. Therefore
75  * we continuously monitor the size of the queues and constrain them to 5%
76  * (zfs_scan_mem_lim_fact) of physmem. If the queues grow larger than this
77  * limit, we clear out a few of the largest extents at the head of the queues
78  * to make room for more scanning. Hopefully, these extents will be fairly
79  * large and contiguous, allowing us to approach sequential I/O throughput
80  * even without a fully sorted tree.
81  *
82  * Metadata scanning takes place in dsl_scan_visit(), which is called from
83  * dsl_scan_sync() every spa_sync(). If we have either fully scanned all
84  * metadata on the pool, or we need to make room in memory because our
85  * queues are too large, dsl_scan_visit() is postponed and
86  * scan_io_queues_run() is called from dsl_scan_sync() instead. This implies
87  * that metadata scanning and queued I/O issuing are mutually exclusive. This
88  * allows us to provide maximum sequential I/O throughput for the majority of
89  * I/O's issued since sequential I/O performance is significantly negatively
90  * impacted if it is interleaved with random I/O.
91  *
92  * Implementation Notes
93  *
94  * One side effect of the queued scanning algorithm is that the scanning code
95  * needs to be notified whenever a block is freed. This is needed to allow
96  * the scanning code to remove these I/Os from the issuing queue. Additionally,
97  * we do not attempt to queue gang blocks to be issued sequentially since this
98  * is very hard to do and would have an extremely limited performance benefit.
99  * Instead, we simply issue gang I/Os as soon as we find them using the legacy
100  * algorithm.
101  *
102  * Backwards compatibility
103  *
104  * This new algorithm is backwards compatible with the legacy on-disk data
105  * structures (and therefore does not require a new feature flag).
106  * Periodically during scanning (see zfs_scan_checkpoint_intval), the scan
107  * will stop scanning metadata (in logical order) and wait for all outstanding
108  * sorted I/O to complete. Once this is done, we write out a checkpoint
109  * bookmark, indicating that we have scanned everything logically before it.
110  * If the pool is imported on a machine without the new sorting algorithm,
111  * the scan simply resumes from the last checkpoint using the legacy algorithm.
112  */
113
114 typedef int (scan_cb_t)(dsl_pool_t *, const blkptr_t *,
115     const zbookmark_phys_t *);
116
117 static scan_cb_t dsl_scan_scrub_cb;
118
119 static int scan_ds_queue_compare(const void *a, const void *b);
120 static int scan_prefetch_queue_compare(const void *a, const void *b);
121 static void scan_ds_queue_clear(dsl_scan_t *scn);
122 static void scan_ds_prefetch_queue_clear(dsl_scan_t *scn);
123 static boolean_t scan_ds_queue_contains(dsl_scan_t *scn, uint64_t dsobj,
124     uint64_t *txg);
125 static void scan_ds_queue_insert(dsl_scan_t *scn, uint64_t dsobj, uint64_t txg);
126 static void scan_ds_queue_remove(dsl_scan_t *scn, uint64_t dsobj);
127 static void scan_ds_queue_sync(dsl_scan_t *scn, dmu_tx_t *tx);
128 static uint64_t dsl_scan_count_leaves(vdev_t *vd);
129
130 extern int zfs_vdev_async_write_active_min_dirty_percent;
131
132 /*
133  * By default zfs will check to ensure it is not over the hard memory
134  * limit before each txg. If finer-grained control of this is needed
135  * this value can be set to 1 to enable checking before scanning each
136  * block.
137  */
138 int zfs_scan_strict_mem_lim = B_FALSE;
139
140 /*
141  * Maximum number of parallelly executed bytes per leaf vdev. We attempt
142  * to strike a balance here between keeping the vdev queues full of I/Os
143  * at all times and not overflowing the queues to cause long latency,
144  * which would cause long txg sync times. No matter what, we will not
145  * overload the drives with I/O, since that is protected by
146  * zfs_vdev_scrub_max_active.
147  */
148 unsigned long zfs_scan_vdev_limit = 4 << 20;
149
150 int zfs_scan_issue_strategy = 0;
151 int zfs_scan_legacy = B_FALSE; /* don't queue & sort zios, go direct */
152 unsigned long zfs_scan_max_ext_gap = 2 << 20; /* in bytes */
153
154 /*
155  * fill_weight is non-tunable at runtime, so we copy it at module init from
156  * zfs_scan_fill_weight. Runtime adjustments to zfs_scan_fill_weight would
157  * break queue sorting.
158  */
159 int zfs_scan_fill_weight = 3;
160 static uint64_t fill_weight;
161
162 /* See dsl_scan_should_clear() for details on the memory limit tunables */
163 uint64_t zfs_scan_mem_lim_min = 16 << 20;       /* bytes */
164 uint64_t zfs_scan_mem_lim_soft_max = 128 << 20; /* bytes */
165 int zfs_scan_mem_lim_fact = 20;         /* fraction of physmem */
166 int zfs_scan_mem_lim_soft_fact = 20;    /* fraction of mem lim above */
167
168 int zfs_scrub_min_time_ms = 1000; /* min millisecs to scrub per txg */
169 int zfs_obsolete_min_time_ms = 500; /* min millisecs to obsolete per txg */
170 int zfs_free_min_time_ms = 1000; /* min millisecs to free per txg */
171 int zfs_resilver_min_time_ms = 3000; /* min millisecs to resilver per txg */
172 int zfs_scan_checkpoint_intval = 7200; /* in seconds */
173 int zfs_scan_suspend_progress = 0; /* set to prevent scans from progressing */
174 int zfs_no_scrub_io = B_FALSE; /* set to disable scrub i/o */
175 int zfs_no_scrub_prefetch = B_FALSE; /* set to disable scrub prefetch */
176 enum ddt_class zfs_scrub_ddt_class_max = DDT_CLASS_DUPLICATE;
177 /* max number of blocks to free in a single TXG */
178 unsigned long zfs_async_block_max_blocks = 100000;
179
180 int zfs_resilver_disable_defer = 0; /* set to disable resilver deferring */
181
182 /*
183  * We wait a few txgs after importing a pool to begin scanning so that
184  * the import / mounting code isn't held up by scrub / resilver IO.
185  * Unfortunately, it is a bit difficult to determine exactly how long
186  * this will take since userspace will trigger fs mounts asynchronously
187  * and the kernel will create zvol minors asynchronously. As a result,
188  * the value provided here is a bit arbitrary, but represents a
189  * reasonable estimate of how many txgs it will take to finish fully
190  * importing a pool
191  */
192 #define SCAN_IMPORT_WAIT_TXGS           5
193
194 #define DSL_SCAN_IS_SCRUB_RESILVER(scn) \
195         ((scn)->scn_phys.scn_func == POOL_SCAN_SCRUB || \
196         (scn)->scn_phys.scn_func == POOL_SCAN_RESILVER)
197
198 /*
199  * Enable/disable the processing of the free_bpobj object.
200  */
201 int zfs_free_bpobj_enabled = 1;
202
203 /* the order has to match pool_scan_type */
204 static scan_cb_t *scan_funcs[POOL_SCAN_FUNCS] = {
205         NULL,
206         dsl_scan_scrub_cb,      /* POOL_SCAN_SCRUB */
207         dsl_scan_scrub_cb,      /* POOL_SCAN_RESILVER */
208 };
209
210 /* In core node for the scn->scn_queue. Represents a dataset to be scanned */
211 typedef struct {
212         uint64_t        sds_dsobj;
213         uint64_t        sds_txg;
214         avl_node_t      sds_node;
215 } scan_ds_t;
216
217 /*
218  * This controls what conditions are placed on dsl_scan_sync_state():
219  * SYNC_OPTIONAL) write out scn_phys iff scn_bytes_pending == 0
220  * SYNC_MANDATORY) write out scn_phys always. scn_bytes_pending must be 0.
221  * SYNC_CACHED) if scn_bytes_pending == 0, write out scn_phys. Otherwise
222  *      write out the scn_phys_cached version.
223  * See dsl_scan_sync_state for details.
224  */
225 typedef enum {
226         SYNC_OPTIONAL,
227         SYNC_MANDATORY,
228         SYNC_CACHED
229 } state_sync_type_t;
230
231 /*
232  * This struct represents the minimum information needed to reconstruct a
233  * zio for sequential scanning. This is useful because many of these will
234  * accumulate in the sequential IO queues before being issued, so saving
235  * memory matters here.
236  */
237 typedef struct scan_io {
238         /* fields from blkptr_t */
239         uint64_t                sio_blk_prop;
240         uint64_t                sio_phys_birth;
241         uint64_t                sio_birth;
242         zio_cksum_t             sio_cksum;
243         uint32_t                sio_nr_dvas;
244
245         /* fields from zio_t */
246         uint32_t                sio_flags;
247         zbookmark_phys_t        sio_zb;
248
249         /* members for queue sorting */
250         union {
251                 avl_node_t      sio_addr_node; /* link into issuing queue */
252                 list_node_t     sio_list_node; /* link for issuing to disk */
253         } sio_nodes;
254
255         /*
256          * There may be up to SPA_DVAS_PER_BP DVAs here from the bp,
257          * depending on how many were in the original bp. Only the
258          * first DVA is really used for sorting and issuing purposes.
259          * The other DVAs (if provided) simply exist so that the zio
260          * layer can find additional copies to repair from in the
261          * event of an error. This array must go at the end of the
262          * struct to allow this for the variable number of elements.
263          */
264         dva_t                   sio_dva[0];
265 } scan_io_t;
266
267 #define SIO_SET_OFFSET(sio, x)          DVA_SET_OFFSET(&(sio)->sio_dva[0], x)
268 #define SIO_SET_ASIZE(sio, x)           DVA_SET_ASIZE(&(sio)->sio_dva[0], x)
269 #define SIO_GET_OFFSET(sio)             DVA_GET_OFFSET(&(sio)->sio_dva[0])
270 #define SIO_GET_ASIZE(sio)              DVA_GET_ASIZE(&(sio)->sio_dva[0])
271 #define SIO_GET_END_OFFSET(sio)         \
272         (SIO_GET_OFFSET(sio) + SIO_GET_ASIZE(sio))
273 #define SIO_GET_MUSED(sio)              \
274         (sizeof (scan_io_t) + ((sio)->sio_nr_dvas * sizeof (dva_t)))
275
276 struct dsl_scan_io_queue {
277         dsl_scan_t      *q_scn; /* associated dsl_scan_t */
278         vdev_t          *q_vd; /* top-level vdev that this queue represents */
279
280         /* trees used for sorting I/Os and extents of I/Os */
281         range_tree_t    *q_exts_by_addr;
282         zfs_btree_t             q_exts_by_size;
283         avl_tree_t      q_sios_by_addr;
284         uint64_t        q_sio_memused;
285
286         /* members for zio rate limiting */
287         uint64_t        q_maxinflight_bytes;
288         uint64_t        q_inflight_bytes;
289         kcondvar_t      q_zio_cv; /* used under vd->vdev_scan_io_queue_lock */
290
291         /* per txg statistics */
292         uint64_t        q_total_seg_size_this_txg;
293         uint64_t        q_segs_this_txg;
294         uint64_t        q_total_zio_size_this_txg;
295         uint64_t        q_zios_this_txg;
296 };
297
298 /* private data for dsl_scan_prefetch_cb() */
299 typedef struct scan_prefetch_ctx {
300         zfs_refcount_t spc_refcnt;      /* refcount for memory management */
301         dsl_scan_t *spc_scn;            /* dsl_scan_t for the pool */
302         boolean_t spc_root;             /* is this prefetch for an objset? */
303         uint8_t spc_indblkshift;        /* dn_indblkshift of current dnode */
304         uint16_t spc_datablkszsec;      /* dn_idatablkszsec of current dnode */
305 } scan_prefetch_ctx_t;
306
307 /* private data for dsl_scan_prefetch() */
308 typedef struct scan_prefetch_issue_ctx {
309         avl_node_t spic_avl_node;       /* link into scn->scn_prefetch_queue */
310         scan_prefetch_ctx_t *spic_spc;  /* spc for the callback */
311         blkptr_t spic_bp;               /* bp to prefetch */
312         zbookmark_phys_t spic_zb;       /* bookmark to prefetch */
313 } scan_prefetch_issue_ctx_t;
314
315 static void scan_exec_io(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags,
316     const zbookmark_phys_t *zb, dsl_scan_io_queue_t *queue);
317 static void scan_io_queue_insert_impl(dsl_scan_io_queue_t *queue,
318     scan_io_t *sio);
319
320 static dsl_scan_io_queue_t *scan_io_queue_create(vdev_t *vd);
321 static void scan_io_queues_destroy(dsl_scan_t *scn);
322
323 static kmem_cache_t *sio_cache[SPA_DVAS_PER_BP];
324
325 /* sio->sio_nr_dvas must be set so we know which cache to free from */
326 static void
327 sio_free(scan_io_t *sio)
328 {
329         ASSERT3U(sio->sio_nr_dvas, >, 0);
330         ASSERT3U(sio->sio_nr_dvas, <=, SPA_DVAS_PER_BP);
331
332         kmem_cache_free(sio_cache[sio->sio_nr_dvas - 1], sio);
333 }
334
335 /* It is up to the caller to set sio->sio_nr_dvas for freeing */
336 static scan_io_t *
337 sio_alloc(unsigned short nr_dvas)
338 {
339         ASSERT3U(nr_dvas, >, 0);
340         ASSERT3U(nr_dvas, <=, SPA_DVAS_PER_BP);
341
342         return (kmem_cache_alloc(sio_cache[nr_dvas - 1], KM_SLEEP));
343 }
344
345 void
346 scan_init(void)
347 {
348         /*
349          * This is used in ext_size_compare() to weight segments
350          * based on how sparse they are. This cannot be changed
351          * mid-scan and the tree comparison functions don't currently
352          * have a mechanism for passing additional context to the
353          * compare functions. Thus we store this value globally and
354          * we only allow it to be set at module initialization time
355          */
356         fill_weight = zfs_scan_fill_weight;
357
358         for (int i = 0; i < SPA_DVAS_PER_BP; i++) {
359                 char name[36];
360
361                 (void) sprintf(name, "sio_cache_%d", i);
362                 sio_cache[i] = kmem_cache_create(name,
363                     (sizeof (scan_io_t) + ((i + 1) * sizeof (dva_t))),
364                     0, NULL, NULL, NULL, NULL, NULL, 0);
365         }
366 }
367
368 void
369 scan_fini(void)
370 {
371         for (int i = 0; i < SPA_DVAS_PER_BP; i++) {
372                 kmem_cache_destroy(sio_cache[i]);
373         }
374 }
375
376 static inline boolean_t
377 dsl_scan_is_running(const dsl_scan_t *scn)
378 {
379         return (scn->scn_phys.scn_state == DSS_SCANNING);
380 }
381
382 boolean_t
383 dsl_scan_resilvering(dsl_pool_t *dp)
384 {
385         return (dsl_scan_is_running(dp->dp_scan) &&
386             dp->dp_scan->scn_phys.scn_func == POOL_SCAN_RESILVER);
387 }
388
389 static inline void
390 sio2bp(const scan_io_t *sio, blkptr_t *bp)
391 {
392         bzero(bp, sizeof (*bp));
393         bp->blk_prop = sio->sio_blk_prop;
394         bp->blk_phys_birth = sio->sio_phys_birth;
395         bp->blk_birth = sio->sio_birth;
396         bp->blk_fill = 1;       /* we always only work with data pointers */
397         bp->blk_cksum = sio->sio_cksum;
398
399         ASSERT3U(sio->sio_nr_dvas, >, 0);
400         ASSERT3U(sio->sio_nr_dvas, <=, SPA_DVAS_PER_BP);
401
402         bcopy(sio->sio_dva, bp->blk_dva, sio->sio_nr_dvas * sizeof (dva_t));
403 }
404
405 static inline void
406 bp2sio(const blkptr_t *bp, scan_io_t *sio, int dva_i)
407 {
408         sio->sio_blk_prop = bp->blk_prop;
409         sio->sio_phys_birth = bp->blk_phys_birth;
410         sio->sio_birth = bp->blk_birth;
411         sio->sio_cksum = bp->blk_cksum;
412         sio->sio_nr_dvas = BP_GET_NDVAS(bp);
413
414         /*
415          * Copy the DVAs to the sio. We need all copies of the block so
416          * that the self healing code can use the alternate copies if the
417          * first is corrupted. We want the DVA at index dva_i to be first
418          * in the sio since this is the primary one that we want to issue.
419          */
420         for (int i = 0, j = dva_i; i < sio->sio_nr_dvas; i++, j++) {
421                 sio->sio_dva[i] = bp->blk_dva[j % sio->sio_nr_dvas];
422         }
423 }
424
425 int
426 dsl_scan_init(dsl_pool_t *dp, uint64_t txg)
427 {
428         int err;
429         dsl_scan_t *scn;
430         spa_t *spa = dp->dp_spa;
431         uint64_t f;
432
433         scn = dp->dp_scan = kmem_zalloc(sizeof (dsl_scan_t), KM_SLEEP);
434         scn->scn_dp = dp;
435
436         /*
437          * It's possible that we're resuming a scan after a reboot so
438          * make sure that the scan_async_destroying flag is initialized
439          * appropriately.
440          */
441         ASSERT(!scn->scn_async_destroying);
442         scn->scn_async_destroying = spa_feature_is_active(dp->dp_spa,
443             SPA_FEATURE_ASYNC_DESTROY);
444
445         /*
446          * Calculate the max number of in-flight bytes for pool-wide
447          * scanning operations (minimum 1MB). Limits for the issuing
448          * phase are done per top-level vdev and are handled separately.
449          */
450         scn->scn_maxinflight_bytes = MAX(zfs_scan_vdev_limit *
451             dsl_scan_count_leaves(spa->spa_root_vdev), 1ULL << 20);
452
453         avl_create(&scn->scn_queue, scan_ds_queue_compare, sizeof (scan_ds_t),
454             offsetof(scan_ds_t, sds_node));
455         avl_create(&scn->scn_prefetch_queue, scan_prefetch_queue_compare,
456             sizeof (scan_prefetch_issue_ctx_t),
457             offsetof(scan_prefetch_issue_ctx_t, spic_avl_node));
458
459         err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
460             "scrub_func", sizeof (uint64_t), 1, &f);
461         if (err == 0) {
462                 /*
463                  * There was an old-style scrub in progress.  Restart a
464                  * new-style scrub from the beginning.
465                  */
466                 scn->scn_restart_txg = txg;
467                 zfs_dbgmsg("old-style scrub was in progress; "
468                     "restarting new-style scrub in txg %llu",
469                     (longlong_t)scn->scn_restart_txg);
470
471                 /*
472                  * Load the queue obj from the old location so that it
473                  * can be freed by dsl_scan_done().
474                  */
475                 (void) zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
476                     "scrub_queue", sizeof (uint64_t), 1,
477                     &scn->scn_phys.scn_queue_obj);
478         } else {
479                 err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
480                     DMU_POOL_SCAN, sizeof (uint64_t), SCAN_PHYS_NUMINTS,
481                     &scn->scn_phys);
482                 /*
483                  * Detect if the pool contains the signature of #2094.  If it
484                  * does properly update the scn->scn_phys structure and notify
485                  * the administrator by setting an errata for the pool.
486                  */
487                 if (err == EOVERFLOW) {
488                         uint64_t zaptmp[SCAN_PHYS_NUMINTS + 1];
489                         VERIFY3S(SCAN_PHYS_NUMINTS, ==, 24);
490                         VERIFY3S(offsetof(dsl_scan_phys_t, scn_flags), ==,
491                             (23 * sizeof (uint64_t)));
492
493                         err = zap_lookup(dp->dp_meta_objset,
494                             DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SCAN,
495                             sizeof (uint64_t), SCAN_PHYS_NUMINTS + 1, &zaptmp);
496                         if (err == 0) {
497                                 uint64_t overflow = zaptmp[SCAN_PHYS_NUMINTS];
498
499                                 if (overflow & ~DSL_SCAN_FLAGS_MASK ||
500                                     scn->scn_async_destroying) {
501                                         spa->spa_errata =
502                                             ZPOOL_ERRATA_ZOL_2094_ASYNC_DESTROY;
503                                         return (EOVERFLOW);
504                                 }
505
506                                 bcopy(zaptmp, &scn->scn_phys,
507                                     SCAN_PHYS_NUMINTS * sizeof (uint64_t));
508                                 scn->scn_phys.scn_flags = overflow;
509
510                                 /* Required scrub already in progress. */
511                                 if (scn->scn_phys.scn_state == DSS_FINISHED ||
512                                     scn->scn_phys.scn_state == DSS_CANCELED)
513                                         spa->spa_errata =
514                                             ZPOOL_ERRATA_ZOL_2094_SCRUB;
515                         }
516                 }
517
518                 if (err == ENOENT)
519                         return (0);
520                 else if (err)
521                         return (err);
522
523                 /*
524                  * We might be restarting after a reboot, so jump the issued
525                  * counter to how far we've scanned. We know we're consistent
526                  * up to here.
527                  */
528                 scn->scn_issued_before_pass = scn->scn_phys.scn_examined;
529
530                 if (dsl_scan_is_running(scn) &&
531                     spa_prev_software_version(dp->dp_spa) < SPA_VERSION_SCAN) {
532                         /*
533                          * A new-type scrub was in progress on an old
534                          * pool, and the pool was accessed by old
535                          * software.  Restart from the beginning, since
536                          * the old software may have changed the pool in
537                          * the meantime.
538                          */
539                         scn->scn_restart_txg = txg;
540                         zfs_dbgmsg("new-style scrub was modified "
541                             "by old software; restarting in txg %llu",
542                             (longlong_t)scn->scn_restart_txg);
543                 }
544         }
545
546         bcopy(&scn->scn_phys, &scn->scn_phys_cached, sizeof (scn->scn_phys));
547
548         /* reload the queue into the in-core state */
549         if (scn->scn_phys.scn_queue_obj != 0) {
550                 zap_cursor_t zc;
551                 zap_attribute_t za;
552
553                 for (zap_cursor_init(&zc, dp->dp_meta_objset,
554                     scn->scn_phys.scn_queue_obj);
555                     zap_cursor_retrieve(&zc, &za) == 0;
556                     (void) zap_cursor_advance(&zc)) {
557                         scan_ds_queue_insert(scn,
558                             zfs_strtonum(za.za_name, NULL),
559                             za.za_first_integer);
560                 }
561                 zap_cursor_fini(&zc);
562         }
563
564         spa_scan_stat_init(spa);
565         return (0);
566 }
567
568 void
569 dsl_scan_fini(dsl_pool_t *dp)
570 {
571         if (dp->dp_scan != NULL) {
572                 dsl_scan_t *scn = dp->dp_scan;
573
574                 if (scn->scn_taskq != NULL)
575                         taskq_destroy(scn->scn_taskq);
576
577                 scan_ds_queue_clear(scn);
578                 avl_destroy(&scn->scn_queue);
579                 scan_ds_prefetch_queue_clear(scn);
580                 avl_destroy(&scn->scn_prefetch_queue);
581
582                 kmem_free(dp->dp_scan, sizeof (dsl_scan_t));
583                 dp->dp_scan = NULL;
584         }
585 }
586
587 static boolean_t
588 dsl_scan_restarting(dsl_scan_t *scn, dmu_tx_t *tx)
589 {
590         return (scn->scn_restart_txg != 0 &&
591             scn->scn_restart_txg <= tx->tx_txg);
592 }
593
594 boolean_t
595 dsl_scan_scrubbing(const dsl_pool_t *dp)
596 {
597         dsl_scan_phys_t *scn_phys = &dp->dp_scan->scn_phys;
598
599         return (scn_phys->scn_state == DSS_SCANNING &&
600             scn_phys->scn_func == POOL_SCAN_SCRUB);
601 }
602
603 boolean_t
604 dsl_scan_is_paused_scrub(const dsl_scan_t *scn)
605 {
606         return (dsl_scan_scrubbing(scn->scn_dp) &&
607             scn->scn_phys.scn_flags & DSF_SCRUB_PAUSED);
608 }
609
610 /*
611  * Writes out a persistent dsl_scan_phys_t record to the pool directory.
612  * Because we can be running in the block sorting algorithm, we do not always
613  * want to write out the record, only when it is "safe" to do so. This safety
614  * condition is achieved by making sure that the sorting queues are empty
615  * (scn_bytes_pending == 0). When this condition is not true, the sync'd state
616  * is inconsistent with how much actual scanning progress has been made. The
617  * kind of sync to be performed is specified by the sync_type argument. If the
618  * sync is optional, we only sync if the queues are empty. If the sync is
619  * mandatory, we do a hard ASSERT to make sure that the queues are empty. The
620  * third possible state is a "cached" sync. This is done in response to:
621  * 1) The dataset that was in the last sync'd dsl_scan_phys_t having been
622  *      destroyed, so we wouldn't be able to restart scanning from it.
623  * 2) The snapshot that was in the last sync'd dsl_scan_phys_t having been
624  *      superseded by a newer snapshot.
625  * 3) The dataset that was in the last sync'd dsl_scan_phys_t having been
626  *      swapped with its clone.
627  * In all cases, a cached sync simply rewrites the last record we've written,
628  * just slightly modified. For the modifications that are performed to the
629  * last written dsl_scan_phys_t, see dsl_scan_ds_destroyed,
630  * dsl_scan_ds_snapshotted and dsl_scan_ds_clone_swapped.
631  */
632 static void
633 dsl_scan_sync_state(dsl_scan_t *scn, dmu_tx_t *tx, state_sync_type_t sync_type)
634 {
635         int i;
636         spa_t *spa = scn->scn_dp->dp_spa;
637
638         ASSERT(sync_type != SYNC_MANDATORY || scn->scn_bytes_pending == 0);
639         if (scn->scn_bytes_pending == 0) {
640                 for (i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
641                         vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
642                         dsl_scan_io_queue_t *q = vd->vdev_scan_io_queue;
643
644                         if (q == NULL)
645                                 continue;
646
647                         mutex_enter(&vd->vdev_scan_io_queue_lock);
648                         ASSERT3P(avl_first(&q->q_sios_by_addr), ==, NULL);
649                         ASSERT3P(zfs_btree_first(&q->q_exts_by_size, NULL), ==,
650                             NULL);
651                         ASSERT3P(range_tree_first(q->q_exts_by_addr), ==, NULL);
652                         mutex_exit(&vd->vdev_scan_io_queue_lock);
653                 }
654
655                 if (scn->scn_phys.scn_queue_obj != 0)
656                         scan_ds_queue_sync(scn, tx);
657                 VERIFY0(zap_update(scn->scn_dp->dp_meta_objset,
658                     DMU_POOL_DIRECTORY_OBJECT,
659                     DMU_POOL_SCAN, sizeof (uint64_t), SCAN_PHYS_NUMINTS,
660                     &scn->scn_phys, tx));
661                 bcopy(&scn->scn_phys, &scn->scn_phys_cached,
662                     sizeof (scn->scn_phys));
663
664                 if (scn->scn_checkpointing)
665                         zfs_dbgmsg("finish scan checkpoint");
666
667                 scn->scn_checkpointing = B_FALSE;
668                 scn->scn_last_checkpoint = ddi_get_lbolt();
669         } else if (sync_type == SYNC_CACHED) {
670                 VERIFY0(zap_update(scn->scn_dp->dp_meta_objset,
671                     DMU_POOL_DIRECTORY_OBJECT,
672                     DMU_POOL_SCAN, sizeof (uint64_t), SCAN_PHYS_NUMINTS,
673                     &scn->scn_phys_cached, tx));
674         }
675 }
676
677 /* ARGSUSED */
678 static int
679 dsl_scan_setup_check(void *arg, dmu_tx_t *tx)
680 {
681         dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
682
683         if (dsl_scan_is_running(scn))
684                 return (SET_ERROR(EBUSY));
685
686         return (0);
687 }
688
689 static void
690 dsl_scan_setup_sync(void *arg, dmu_tx_t *tx)
691 {
692         dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
693         pool_scan_func_t *funcp = arg;
694         dmu_object_type_t ot = 0;
695         dsl_pool_t *dp = scn->scn_dp;
696         spa_t *spa = dp->dp_spa;
697
698         ASSERT(!dsl_scan_is_running(scn));
699         ASSERT(*funcp > POOL_SCAN_NONE && *funcp < POOL_SCAN_FUNCS);
700         bzero(&scn->scn_phys, sizeof (scn->scn_phys));
701         scn->scn_phys.scn_func = *funcp;
702         scn->scn_phys.scn_state = DSS_SCANNING;
703         scn->scn_phys.scn_min_txg = 0;
704         scn->scn_phys.scn_max_txg = tx->tx_txg;
705         scn->scn_phys.scn_ddt_class_max = DDT_CLASSES - 1; /* the entire DDT */
706         scn->scn_phys.scn_start_time = gethrestime_sec();
707         scn->scn_phys.scn_errors = 0;
708         scn->scn_phys.scn_to_examine = spa->spa_root_vdev->vdev_stat.vs_alloc;
709         scn->scn_issued_before_pass = 0;
710         scn->scn_restart_txg = 0;
711         scn->scn_done_txg = 0;
712         scn->scn_last_checkpoint = 0;
713         scn->scn_checkpointing = B_FALSE;
714         spa_scan_stat_init(spa);
715
716         if (DSL_SCAN_IS_SCRUB_RESILVER(scn)) {
717                 scn->scn_phys.scn_ddt_class_max = zfs_scrub_ddt_class_max;
718
719                 /* rewrite all disk labels */
720                 vdev_config_dirty(spa->spa_root_vdev);
721
722                 if (vdev_resilver_needed(spa->spa_root_vdev,
723                     &scn->scn_phys.scn_min_txg, &scn->scn_phys.scn_max_txg)) {
724                         spa_event_notify(spa, NULL, NULL,
725                             ESC_ZFS_RESILVER_START);
726                 } else {
727                         spa_event_notify(spa, NULL, NULL, ESC_ZFS_SCRUB_START);
728                 }
729
730                 spa->spa_scrub_started = B_TRUE;
731                 /*
732                  * If this is an incremental scrub, limit the DDT scrub phase
733                  * to just the auto-ditto class (for correctness); the rest
734                  * of the scrub should go faster using top-down pruning.
735                  */
736                 if (scn->scn_phys.scn_min_txg > TXG_INITIAL)
737                         scn->scn_phys.scn_ddt_class_max = DDT_CLASS_DITTO;
738
739         }
740
741         /* back to the generic stuff */
742
743         if (dp->dp_blkstats == NULL) {
744                 dp->dp_blkstats =
745                     vmem_alloc(sizeof (zfs_all_blkstats_t), KM_SLEEP);
746                 mutex_init(&dp->dp_blkstats->zab_lock, NULL,
747                     MUTEX_DEFAULT, NULL);
748         }
749         bzero(&dp->dp_blkstats->zab_type, sizeof (dp->dp_blkstats->zab_type));
750
751         if (spa_version(spa) < SPA_VERSION_DSL_SCRUB)
752                 ot = DMU_OT_ZAP_OTHER;
753
754         scn->scn_phys.scn_queue_obj = zap_create(dp->dp_meta_objset,
755             ot ? ot : DMU_OT_SCAN_QUEUE, DMU_OT_NONE, 0, tx);
756
757         bcopy(&scn->scn_phys, &scn->scn_phys_cached, sizeof (scn->scn_phys));
758
759         dsl_scan_sync_state(scn, tx, SYNC_MANDATORY);
760
761         spa_history_log_internal(spa, "scan setup", tx,
762             "func=%u mintxg=%llu maxtxg=%llu",
763             *funcp, (u_longlong_t)scn->scn_phys.scn_min_txg,
764             (u_longlong_t)scn->scn_phys.scn_max_txg);
765 }
766
767 /*
768  * Called by the ZFS_IOC_POOL_SCAN ioctl to start a scrub or resilver.
769  * Can also be called to resume a paused scrub.
770  */
771 int
772 dsl_scan(dsl_pool_t *dp, pool_scan_func_t func)
773 {
774         spa_t *spa = dp->dp_spa;
775         dsl_scan_t *scn = dp->dp_scan;
776
777         /*
778          * Purge all vdev caches and probe all devices.  We do this here
779          * rather than in sync context because this requires a writer lock
780          * on the spa_config lock, which we can't do from sync context.  The
781          * spa_scrub_reopen flag indicates that vdev_open() should not
782          * attempt to start another scrub.
783          */
784         spa_vdev_state_enter(spa, SCL_NONE);
785         spa->spa_scrub_reopen = B_TRUE;
786         vdev_reopen(spa->spa_root_vdev);
787         spa->spa_scrub_reopen = B_FALSE;
788         (void) spa_vdev_state_exit(spa, NULL, 0);
789
790         if (func == POOL_SCAN_RESILVER) {
791                 dsl_resilver_restart(spa->spa_dsl_pool, 0);
792                 return (0);
793         }
794
795         if (func == POOL_SCAN_SCRUB && dsl_scan_is_paused_scrub(scn)) {
796                 /* got scrub start cmd, resume paused scrub */
797                 int err = dsl_scrub_set_pause_resume(scn->scn_dp,
798                     POOL_SCRUB_NORMAL);
799                 if (err == 0) {
800                         spa_event_notify(spa, NULL, NULL, ESC_ZFS_SCRUB_RESUME);
801                         return (ECANCELED);
802                 }
803
804                 return (SET_ERROR(err));
805         }
806
807         return (dsl_sync_task(spa_name(spa), dsl_scan_setup_check,
808             dsl_scan_setup_sync, &func, 0, ZFS_SPACE_CHECK_EXTRA_RESERVED));
809 }
810
811 /*
812  * Sets the resilver defer flag to B_FALSE on all leaf devs under vd. Returns
813  * B_TRUE if we have devices that need to be resilvered and are available to
814  * accept resilver I/Os.
815  */
816 static boolean_t
817 dsl_scan_clear_deferred(vdev_t *vd, dmu_tx_t *tx)
818 {
819         boolean_t resilver_needed = B_FALSE;
820         spa_t *spa = vd->vdev_spa;
821
822         for (int c = 0; c < vd->vdev_children; c++) {
823                 resilver_needed |=
824                     dsl_scan_clear_deferred(vd->vdev_child[c], tx);
825         }
826
827         if (vd == spa->spa_root_vdev &&
828             spa_feature_is_active(spa, SPA_FEATURE_RESILVER_DEFER)) {
829                 spa_feature_decr(spa, SPA_FEATURE_RESILVER_DEFER, tx);
830                 vdev_config_dirty(vd);
831                 spa->spa_resilver_deferred = B_FALSE;
832                 return (resilver_needed);
833         }
834
835         if (!vdev_is_concrete(vd) || vd->vdev_aux ||
836             !vd->vdev_ops->vdev_op_leaf)
837                 return (resilver_needed);
838
839         if (vd->vdev_resilver_deferred)
840                 vd->vdev_resilver_deferred = B_FALSE;
841
842         return (!vdev_is_dead(vd) && !vd->vdev_offline &&
843             vdev_resilver_needed(vd, NULL, NULL));
844 }
845
846 /* ARGSUSED */
847 static void
848 dsl_scan_done(dsl_scan_t *scn, boolean_t complete, dmu_tx_t *tx)
849 {
850         static const char *old_names[] = {
851                 "scrub_bookmark",
852                 "scrub_ddt_bookmark",
853                 "scrub_ddt_class_max",
854                 "scrub_queue",
855                 "scrub_min_txg",
856                 "scrub_max_txg",
857                 "scrub_func",
858                 "scrub_errors",
859                 NULL
860         };
861
862         dsl_pool_t *dp = scn->scn_dp;
863         spa_t *spa = dp->dp_spa;
864         int i;
865
866         /* Remove any remnants of an old-style scrub. */
867         for (i = 0; old_names[i]; i++) {
868                 (void) zap_remove(dp->dp_meta_objset,
869                     DMU_POOL_DIRECTORY_OBJECT, old_names[i], tx);
870         }
871
872         if (scn->scn_phys.scn_queue_obj != 0) {
873                 VERIFY0(dmu_object_free(dp->dp_meta_objset,
874                     scn->scn_phys.scn_queue_obj, tx));
875                 scn->scn_phys.scn_queue_obj = 0;
876         }
877         scan_ds_queue_clear(scn);
878         scan_ds_prefetch_queue_clear(scn);
879
880         scn->scn_phys.scn_flags &= ~DSF_SCRUB_PAUSED;
881
882         /*
883          * If we were "restarted" from a stopped state, don't bother
884          * with anything else.
885          */
886         if (!dsl_scan_is_running(scn)) {
887                 ASSERT(!scn->scn_is_sorted);
888                 return;
889         }
890
891         if (scn->scn_is_sorted) {
892                 scan_io_queues_destroy(scn);
893                 scn->scn_is_sorted = B_FALSE;
894
895                 if (scn->scn_taskq != NULL) {
896                         taskq_destroy(scn->scn_taskq);
897                         scn->scn_taskq = NULL;
898                 }
899         }
900
901         scn->scn_phys.scn_state = complete ? DSS_FINISHED : DSS_CANCELED;
902
903         spa_notify_waiters(spa);
904
905         if (dsl_scan_restarting(scn, tx))
906                 spa_history_log_internal(spa, "scan aborted, restarting", tx,
907                     "errors=%llu", (u_longlong_t)spa_get_errlog_size(spa));
908         else if (!complete)
909                 spa_history_log_internal(spa, "scan cancelled", tx,
910                     "errors=%llu", (u_longlong_t)spa_get_errlog_size(spa));
911         else
912                 spa_history_log_internal(spa, "scan done", tx,
913                     "errors=%llu", (u_longlong_t)spa_get_errlog_size(spa));
914
915         if (DSL_SCAN_IS_SCRUB_RESILVER(scn)) {
916                 spa->spa_scrub_started = B_FALSE;
917                 spa->spa_scrub_active = B_FALSE;
918
919                 /*
920                  * If the scrub/resilver completed, update all DTLs to
921                  * reflect this.  Whether it succeeded or not, vacate
922                  * all temporary scrub DTLs.
923                  *
924                  * As the scrub does not currently support traversing
925                  * data that have been freed but are part of a checkpoint,
926                  * we don't mark the scrub as done in the DTLs as faults
927                  * may still exist in those vdevs.
928                  */
929                 if (complete &&
930                     !spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
931                         vdev_dtl_reassess(spa->spa_root_vdev, tx->tx_txg,
932                             scn->scn_phys.scn_max_txg, B_TRUE);
933
934                         spa_event_notify(spa, NULL, NULL,
935                             scn->scn_phys.scn_min_txg ?
936                             ESC_ZFS_RESILVER_FINISH : ESC_ZFS_SCRUB_FINISH);
937                 } else {
938                         vdev_dtl_reassess(spa->spa_root_vdev, tx->tx_txg,
939                             0, B_TRUE);
940                 }
941                 spa_errlog_rotate(spa);
942
943                 /*
944                  * We may have finished replacing a device.
945                  * Let the async thread assess this and handle the detach.
946                  */
947                 spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
948
949                 /*
950                  * Clear any deferred_resilver flags in the config.
951                  * If there are drives that need resilvering, kick
952                  * off an asynchronous request to start resilver.
953                  * dsl_scan_clear_deferred() may update the config
954                  * before the resilver can restart. In the event of
955                  * a crash during this period, the spa loading code
956                  * will find the drives that need to be resilvered
957                  * when the machine reboots and start the resilver then.
958                  */
959                 if (spa_feature_is_enabled(spa, SPA_FEATURE_RESILVER_DEFER)) {
960                         boolean_t resilver_needed =
961                             dsl_scan_clear_deferred(spa->spa_root_vdev, tx);
962                         if (resilver_needed) {
963                                 spa_history_log_internal(spa,
964                                     "starting deferred resilver", tx,
965                                     "errors=%llu",
966                                     (u_longlong_t)spa_get_errlog_size(spa));
967                                 spa_async_request(spa, SPA_ASYNC_RESILVER);
968                         }
969                 }
970         }
971
972         scn->scn_phys.scn_end_time = gethrestime_sec();
973
974         if (spa->spa_errata == ZPOOL_ERRATA_ZOL_2094_SCRUB)
975                 spa->spa_errata = 0;
976
977         ASSERT(!dsl_scan_is_running(scn));
978 }
979
980 /* ARGSUSED */
981 static int
982 dsl_scan_cancel_check(void *arg, dmu_tx_t *tx)
983 {
984         dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
985
986         if (!dsl_scan_is_running(scn))
987                 return (SET_ERROR(ENOENT));
988         return (0);
989 }
990
991 /* ARGSUSED */
992 static void
993 dsl_scan_cancel_sync(void *arg, dmu_tx_t *tx)
994 {
995         dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
996
997         dsl_scan_done(scn, B_FALSE, tx);
998         dsl_scan_sync_state(scn, tx, SYNC_MANDATORY);
999         spa_event_notify(scn->scn_dp->dp_spa, NULL, NULL, ESC_ZFS_SCRUB_ABORT);
1000 }
1001
1002 int
1003 dsl_scan_cancel(dsl_pool_t *dp)
1004 {
1005         return (dsl_sync_task(spa_name(dp->dp_spa), dsl_scan_cancel_check,
1006             dsl_scan_cancel_sync, NULL, 3, ZFS_SPACE_CHECK_RESERVED));
1007 }
1008
1009 static int
1010 dsl_scrub_pause_resume_check(void *arg, dmu_tx_t *tx)
1011 {
1012         pool_scrub_cmd_t *cmd = arg;
1013         dsl_pool_t *dp = dmu_tx_pool(tx);
1014         dsl_scan_t *scn = dp->dp_scan;
1015
1016         if (*cmd == POOL_SCRUB_PAUSE) {
1017                 /* can't pause a scrub when there is no in-progress scrub */
1018                 if (!dsl_scan_scrubbing(dp))
1019                         return (SET_ERROR(ENOENT));
1020
1021                 /* can't pause a paused scrub */
1022                 if (dsl_scan_is_paused_scrub(scn))
1023                         return (SET_ERROR(EBUSY));
1024         } else if (*cmd != POOL_SCRUB_NORMAL) {
1025                 return (SET_ERROR(ENOTSUP));
1026         }
1027
1028         return (0);
1029 }
1030
1031 static void
1032 dsl_scrub_pause_resume_sync(void *arg, dmu_tx_t *tx)
1033 {
1034         pool_scrub_cmd_t *cmd = arg;
1035         dsl_pool_t *dp = dmu_tx_pool(tx);
1036         spa_t *spa = dp->dp_spa;
1037         dsl_scan_t *scn = dp->dp_scan;
1038
1039         if (*cmd == POOL_SCRUB_PAUSE) {
1040                 /* can't pause a scrub when there is no in-progress scrub */
1041                 spa->spa_scan_pass_scrub_pause = gethrestime_sec();
1042                 scn->scn_phys.scn_flags |= DSF_SCRUB_PAUSED;
1043                 scn->scn_phys_cached.scn_flags |= DSF_SCRUB_PAUSED;
1044                 dsl_scan_sync_state(scn, tx, SYNC_CACHED);
1045                 spa_event_notify(spa, NULL, NULL, ESC_ZFS_SCRUB_PAUSED);
1046                 spa_notify_waiters(spa);
1047         } else {
1048                 ASSERT3U(*cmd, ==, POOL_SCRUB_NORMAL);
1049                 if (dsl_scan_is_paused_scrub(scn)) {
1050                         /*
1051                          * We need to keep track of how much time we spend
1052                          * paused per pass so that we can adjust the scrub rate
1053                          * shown in the output of 'zpool status'
1054                          */
1055                         spa->spa_scan_pass_scrub_spent_paused +=
1056                             gethrestime_sec() - spa->spa_scan_pass_scrub_pause;
1057                         spa->spa_scan_pass_scrub_pause = 0;
1058                         scn->scn_phys.scn_flags &= ~DSF_SCRUB_PAUSED;
1059                         scn->scn_phys_cached.scn_flags &= ~DSF_SCRUB_PAUSED;
1060                         dsl_scan_sync_state(scn, tx, SYNC_CACHED);
1061                 }
1062         }
1063 }
1064
1065 /*
1066  * Set scrub pause/resume state if it makes sense to do so
1067  */
1068 int
1069 dsl_scrub_set_pause_resume(const dsl_pool_t *dp, pool_scrub_cmd_t cmd)
1070 {
1071         return (dsl_sync_task(spa_name(dp->dp_spa),
1072             dsl_scrub_pause_resume_check, dsl_scrub_pause_resume_sync, &cmd, 3,
1073             ZFS_SPACE_CHECK_RESERVED));
1074 }
1075
1076
1077 /* start a new scan, or restart an existing one. */
1078 void
1079 dsl_resilver_restart(dsl_pool_t *dp, uint64_t txg)
1080 {
1081         if (txg == 0) {
1082                 dmu_tx_t *tx;
1083                 tx = dmu_tx_create_dd(dp->dp_mos_dir);
1084                 VERIFY(0 == dmu_tx_assign(tx, TXG_WAIT));
1085
1086                 txg = dmu_tx_get_txg(tx);
1087                 dp->dp_scan->scn_restart_txg = txg;
1088                 dmu_tx_commit(tx);
1089         } else {
1090                 dp->dp_scan->scn_restart_txg = txg;
1091         }
1092         zfs_dbgmsg("restarting resilver txg=%llu", (longlong_t)txg);
1093 }
1094
1095 void
1096 dsl_free(dsl_pool_t *dp, uint64_t txg, const blkptr_t *bp)
1097 {
1098         zio_free(dp->dp_spa, txg, bp);
1099 }
1100
1101 void
1102 dsl_free_sync(zio_t *pio, dsl_pool_t *dp, uint64_t txg, const blkptr_t *bpp)
1103 {
1104         ASSERT(dsl_pool_sync_context(dp));
1105         zio_nowait(zio_free_sync(pio, dp->dp_spa, txg, bpp, pio->io_flags));
1106 }
1107
1108 static int
1109 scan_ds_queue_compare(const void *a, const void *b)
1110 {
1111         const scan_ds_t *sds_a = a, *sds_b = b;
1112
1113         if (sds_a->sds_dsobj < sds_b->sds_dsobj)
1114                 return (-1);
1115         if (sds_a->sds_dsobj == sds_b->sds_dsobj)
1116                 return (0);
1117         return (1);
1118 }
1119
1120 static void
1121 scan_ds_queue_clear(dsl_scan_t *scn)
1122 {
1123         void *cookie = NULL;
1124         scan_ds_t *sds;
1125         while ((sds = avl_destroy_nodes(&scn->scn_queue, &cookie)) != NULL) {
1126                 kmem_free(sds, sizeof (*sds));
1127         }
1128 }
1129
1130 static boolean_t
1131 scan_ds_queue_contains(dsl_scan_t *scn, uint64_t dsobj, uint64_t *txg)
1132 {
1133         scan_ds_t srch, *sds;
1134
1135         srch.sds_dsobj = dsobj;
1136         sds = avl_find(&scn->scn_queue, &srch, NULL);
1137         if (sds != NULL && txg != NULL)
1138                 *txg = sds->sds_txg;
1139         return (sds != NULL);
1140 }
1141
1142 static void
1143 scan_ds_queue_insert(dsl_scan_t *scn, uint64_t dsobj, uint64_t txg)
1144 {
1145         scan_ds_t *sds;
1146         avl_index_t where;
1147
1148         sds = kmem_zalloc(sizeof (*sds), KM_SLEEP);
1149         sds->sds_dsobj = dsobj;
1150         sds->sds_txg = txg;
1151
1152         VERIFY3P(avl_find(&scn->scn_queue, sds, &where), ==, NULL);
1153         avl_insert(&scn->scn_queue, sds, where);
1154 }
1155
1156 static void
1157 scan_ds_queue_remove(dsl_scan_t *scn, uint64_t dsobj)
1158 {
1159         scan_ds_t srch, *sds;
1160
1161         srch.sds_dsobj = dsobj;
1162
1163         sds = avl_find(&scn->scn_queue, &srch, NULL);
1164         VERIFY(sds != NULL);
1165         avl_remove(&scn->scn_queue, sds);
1166         kmem_free(sds, sizeof (*sds));
1167 }
1168
1169 static void
1170 scan_ds_queue_sync(dsl_scan_t *scn, dmu_tx_t *tx)
1171 {
1172         dsl_pool_t *dp = scn->scn_dp;
1173         spa_t *spa = dp->dp_spa;
1174         dmu_object_type_t ot = (spa_version(spa) >= SPA_VERSION_DSL_SCRUB) ?
1175             DMU_OT_SCAN_QUEUE : DMU_OT_ZAP_OTHER;
1176
1177         ASSERT0(scn->scn_bytes_pending);
1178         ASSERT(scn->scn_phys.scn_queue_obj != 0);
1179
1180         VERIFY0(dmu_object_free(dp->dp_meta_objset,
1181             scn->scn_phys.scn_queue_obj, tx));
1182         scn->scn_phys.scn_queue_obj = zap_create(dp->dp_meta_objset, ot,
1183             DMU_OT_NONE, 0, tx);
1184         for (scan_ds_t *sds = avl_first(&scn->scn_queue);
1185             sds != NULL; sds = AVL_NEXT(&scn->scn_queue, sds)) {
1186                 VERIFY0(zap_add_int_key(dp->dp_meta_objset,
1187                     scn->scn_phys.scn_queue_obj, sds->sds_dsobj,
1188                     sds->sds_txg, tx));
1189         }
1190 }
1191
1192 /*
1193  * Computes the memory limit state that we're currently in. A sorted scan
1194  * needs quite a bit of memory to hold the sorting queue, so we need to
1195  * reasonably constrain the size so it doesn't impact overall system
1196  * performance. We compute two limits:
1197  * 1) Hard memory limit: if the amount of memory used by the sorting
1198  *      queues on a pool gets above this value, we stop the metadata
1199  *      scanning portion and start issuing the queued up and sorted
1200  *      I/Os to reduce memory usage.
1201  *      This limit is calculated as a fraction of physmem (by default 5%).
1202  *      We constrain the lower bound of the hard limit to an absolute
1203  *      minimum of zfs_scan_mem_lim_min (default: 16 MiB). We also constrain
1204  *      the upper bound to 5% of the total pool size - no chance we'll
1205  *      ever need that much memory, but just to keep the value in check.
1206  * 2) Soft memory limit: once we hit the hard memory limit, we start
1207  *      issuing I/O to reduce queue memory usage, but we don't want to
1208  *      completely empty out the queues, since we might be able to find I/Os
1209  *      that will fill in the gaps of our non-sequential IOs at some point
1210  *      in the future. So we stop the issuing of I/Os once the amount of
1211  *      memory used drops below the soft limit (at which point we stop issuing
1212  *      I/O and start scanning metadata again).
1213  *
1214  *      This limit is calculated by subtracting a fraction of the hard
1215  *      limit from the hard limit. By default this fraction is 5%, so
1216  *      the soft limit is 95% of the hard limit. We cap the size of the
1217  *      difference between the hard and soft limits at an absolute
1218  *      maximum of zfs_scan_mem_lim_soft_max (default: 128 MiB) - this is
1219  *      sufficient to not cause too frequent switching between the
1220  *      metadata scan and I/O issue (even at 2k recordsize, 128 MiB's
1221  *      worth of queues is about 1.2 GiB of on-pool data, so scanning
1222  *      that should take at least a decent fraction of a second).
1223  */
1224 static boolean_t
1225 dsl_scan_should_clear(dsl_scan_t *scn)
1226 {
1227         vdev_t *rvd = scn->scn_dp->dp_spa->spa_root_vdev;
1228         uint64_t mlim_hard, mlim_soft, mused;
1229         uint64_t alloc = metaslab_class_get_alloc(spa_normal_class(
1230             scn->scn_dp->dp_spa));
1231
1232         mlim_hard = MAX((physmem / zfs_scan_mem_lim_fact) * PAGESIZE,
1233             zfs_scan_mem_lim_min);
1234         mlim_hard = MIN(mlim_hard, alloc / 20);
1235         mlim_soft = mlim_hard - MIN(mlim_hard / zfs_scan_mem_lim_soft_fact,
1236             zfs_scan_mem_lim_soft_max);
1237         mused = 0;
1238         for (uint64_t i = 0; i < rvd->vdev_children; i++) {
1239                 vdev_t *tvd = rvd->vdev_child[i];
1240                 dsl_scan_io_queue_t *queue;
1241
1242                 mutex_enter(&tvd->vdev_scan_io_queue_lock);
1243                 queue = tvd->vdev_scan_io_queue;
1244                 if (queue != NULL) {
1245                         /* # extents in exts_by_size = # in exts_by_addr */
1246                         mused += zfs_btree_numnodes(&queue->q_exts_by_size) *
1247                             sizeof (range_seg_gap_t) + queue->q_sio_memused;
1248                 }
1249                 mutex_exit(&tvd->vdev_scan_io_queue_lock);
1250         }
1251
1252         dprintf("current scan memory usage: %llu bytes\n", (longlong_t)mused);
1253
1254         if (mused == 0)
1255                 ASSERT0(scn->scn_bytes_pending);
1256
1257         /*
1258          * If we are above our hard limit, we need to clear out memory.
1259          * If we are below our soft limit, we need to accumulate sequential IOs.
1260          * Otherwise, we should keep doing whatever we are currently doing.
1261          */
1262         if (mused >= mlim_hard)
1263                 return (B_TRUE);
1264         else if (mused < mlim_soft)
1265                 return (B_FALSE);
1266         else
1267                 return (scn->scn_clearing);
1268 }
1269
1270 static boolean_t
1271 dsl_scan_check_suspend(dsl_scan_t *scn, const zbookmark_phys_t *zb)
1272 {
1273         /* we never skip user/group accounting objects */
1274         if (zb && (int64_t)zb->zb_object < 0)
1275                 return (B_FALSE);
1276
1277         if (scn->scn_suspending)
1278                 return (B_TRUE); /* we're already suspending */
1279
1280         if (!ZB_IS_ZERO(&scn->scn_phys.scn_bookmark))
1281                 return (B_FALSE); /* we're resuming */
1282
1283         /* We only know how to resume from level-0 and objset blocks. */
1284         if (zb && (zb->zb_level != 0 && zb->zb_level != ZB_ROOT_LEVEL))
1285                 return (B_FALSE);
1286
1287         /*
1288          * We suspend if:
1289          *  - we have scanned for at least the minimum time (default 1 sec
1290          *    for scrub, 3 sec for resilver), and either we have sufficient
1291          *    dirty data that we are starting to write more quickly
1292          *    (default 30%), someone is explicitly waiting for this txg
1293          *    to complete, or we have used up all of the time in the txg
1294          *    timeout (default 5 sec).
1295          *  or
1296          *  - the spa is shutting down because this pool is being exported
1297          *    or the machine is rebooting.
1298          *  or
1299          *  - the scan queue has reached its memory use limit
1300          */
1301         uint64_t curr_time_ns = gethrtime();
1302         uint64_t scan_time_ns = curr_time_ns - scn->scn_sync_start_time;
1303         uint64_t sync_time_ns = curr_time_ns -
1304             scn->scn_dp->dp_spa->spa_sync_starttime;
1305         int dirty_pct = scn->scn_dp->dp_dirty_total * 100 / zfs_dirty_data_max;
1306         int mintime = (scn->scn_phys.scn_func == POOL_SCAN_RESILVER) ?
1307             zfs_resilver_min_time_ms : zfs_scrub_min_time_ms;
1308
1309         if ((NSEC2MSEC(scan_time_ns) > mintime &&
1310             (dirty_pct >= zfs_vdev_async_write_active_min_dirty_percent ||
1311             txg_sync_waiting(scn->scn_dp) ||
1312             NSEC2SEC(sync_time_ns) >= zfs_txg_timeout)) ||
1313             spa_shutting_down(scn->scn_dp->dp_spa) ||
1314             (zfs_scan_strict_mem_lim && dsl_scan_should_clear(scn))) {
1315                 if (zb && zb->zb_level == ZB_ROOT_LEVEL) {
1316                         dprintf("suspending at first available bookmark "
1317                             "%llx/%llx/%llx/%llx\n",
1318                             (longlong_t)zb->zb_objset,
1319                             (longlong_t)zb->zb_object,
1320                             (longlong_t)zb->zb_level,
1321                             (longlong_t)zb->zb_blkid);
1322                         SET_BOOKMARK(&scn->scn_phys.scn_bookmark,
1323                             zb->zb_objset, 0, 0, 0);
1324                 } else if (zb != NULL) {
1325                         dprintf("suspending at bookmark %llx/%llx/%llx/%llx\n",
1326                             (longlong_t)zb->zb_objset,
1327                             (longlong_t)zb->zb_object,
1328                             (longlong_t)zb->zb_level,
1329                             (longlong_t)zb->zb_blkid);
1330                         scn->scn_phys.scn_bookmark = *zb;
1331                 } else {
1332 #ifdef ZFS_DEBUG
1333                         dsl_scan_phys_t *scnp = &scn->scn_phys;
1334                         dprintf("suspending at at DDT bookmark "
1335                             "%llx/%llx/%llx/%llx\n",
1336                             (longlong_t)scnp->scn_ddt_bookmark.ddb_class,
1337                             (longlong_t)scnp->scn_ddt_bookmark.ddb_type,
1338                             (longlong_t)scnp->scn_ddt_bookmark.ddb_checksum,
1339                             (longlong_t)scnp->scn_ddt_bookmark.ddb_cursor);
1340 #endif
1341                 }
1342                 scn->scn_suspending = B_TRUE;
1343                 return (B_TRUE);
1344         }
1345         return (B_FALSE);
1346 }
1347
1348 typedef struct zil_scan_arg {
1349         dsl_pool_t      *zsa_dp;
1350         zil_header_t    *zsa_zh;
1351 } zil_scan_arg_t;
1352
1353 /* ARGSUSED */
1354 static int
1355 dsl_scan_zil_block(zilog_t *zilog, blkptr_t *bp, void *arg, uint64_t claim_txg)
1356 {
1357         zil_scan_arg_t *zsa = arg;
1358         dsl_pool_t *dp = zsa->zsa_dp;
1359         dsl_scan_t *scn = dp->dp_scan;
1360         zil_header_t *zh = zsa->zsa_zh;
1361         zbookmark_phys_t zb;
1362
1363         ASSERT(!BP_IS_REDACTED(bp));
1364         if (BP_IS_HOLE(bp) || bp->blk_birth <= scn->scn_phys.scn_cur_min_txg)
1365                 return (0);
1366
1367         /*
1368          * One block ("stubby") can be allocated a long time ago; we
1369          * want to visit that one because it has been allocated
1370          * (on-disk) even if it hasn't been claimed (even though for
1371          * scrub there's nothing to do to it).
1372          */
1373         if (claim_txg == 0 && bp->blk_birth >= spa_min_claim_txg(dp->dp_spa))
1374                 return (0);
1375
1376         SET_BOOKMARK(&zb, zh->zh_log.blk_cksum.zc_word[ZIL_ZC_OBJSET],
1377             ZB_ZIL_OBJECT, ZB_ZIL_LEVEL, bp->blk_cksum.zc_word[ZIL_ZC_SEQ]);
1378
1379         VERIFY(0 == scan_funcs[scn->scn_phys.scn_func](dp, bp, &zb));
1380         return (0);
1381 }
1382
1383 /* ARGSUSED */
1384 static int
1385 dsl_scan_zil_record(zilog_t *zilog, lr_t *lrc, void *arg, uint64_t claim_txg)
1386 {
1387         if (lrc->lrc_txtype == TX_WRITE) {
1388                 zil_scan_arg_t *zsa = arg;
1389                 dsl_pool_t *dp = zsa->zsa_dp;
1390                 dsl_scan_t *scn = dp->dp_scan;
1391                 zil_header_t *zh = zsa->zsa_zh;
1392                 lr_write_t *lr = (lr_write_t *)lrc;
1393                 blkptr_t *bp = &lr->lr_blkptr;
1394                 zbookmark_phys_t zb;
1395
1396                 ASSERT(!BP_IS_REDACTED(bp));
1397                 if (BP_IS_HOLE(bp) ||
1398                     bp->blk_birth <= scn->scn_phys.scn_cur_min_txg)
1399                         return (0);
1400
1401                 /*
1402                  * birth can be < claim_txg if this record's txg is
1403                  * already txg sync'ed (but this log block contains
1404                  * other records that are not synced)
1405                  */
1406                 if (claim_txg == 0 || bp->blk_birth < claim_txg)
1407                         return (0);
1408
1409                 SET_BOOKMARK(&zb, zh->zh_log.blk_cksum.zc_word[ZIL_ZC_OBJSET],
1410                     lr->lr_foid, ZB_ZIL_LEVEL,
1411                     lr->lr_offset / BP_GET_LSIZE(bp));
1412
1413                 VERIFY(0 == scan_funcs[scn->scn_phys.scn_func](dp, bp, &zb));
1414         }
1415         return (0);
1416 }
1417
1418 static void
1419 dsl_scan_zil(dsl_pool_t *dp, zil_header_t *zh)
1420 {
1421         uint64_t claim_txg = zh->zh_claim_txg;
1422         zil_scan_arg_t zsa = { dp, zh };
1423         zilog_t *zilog;
1424
1425         ASSERT(spa_writeable(dp->dp_spa));
1426
1427         /*
1428          * We only want to visit blocks that have been claimed but not yet
1429          * replayed (or, in read-only mode, blocks that *would* be claimed).
1430          */
1431         if (claim_txg == 0)
1432                 return;
1433
1434         zilog = zil_alloc(dp->dp_meta_objset, zh);
1435
1436         (void) zil_parse(zilog, dsl_scan_zil_block, dsl_scan_zil_record, &zsa,
1437             claim_txg, B_FALSE);
1438
1439         zil_free(zilog);
1440 }
1441
1442 /*
1443  * We compare scan_prefetch_issue_ctx_t's based on their bookmarks. The idea
1444  * here is to sort the AVL tree by the order each block will be needed.
1445  */
1446 static int
1447 scan_prefetch_queue_compare(const void *a, const void *b)
1448 {
1449         const scan_prefetch_issue_ctx_t *spic_a = a, *spic_b = b;
1450         const scan_prefetch_ctx_t *spc_a = spic_a->spic_spc;
1451         const scan_prefetch_ctx_t *spc_b = spic_b->spic_spc;
1452
1453         return (zbookmark_compare(spc_a->spc_datablkszsec,
1454             spc_a->spc_indblkshift, spc_b->spc_datablkszsec,
1455             spc_b->spc_indblkshift, &spic_a->spic_zb, &spic_b->spic_zb));
1456 }
1457
1458 static void
1459 scan_prefetch_ctx_rele(scan_prefetch_ctx_t *spc, void *tag)
1460 {
1461         if (zfs_refcount_remove(&spc->spc_refcnt, tag) == 0) {
1462                 zfs_refcount_destroy(&spc->spc_refcnt);
1463                 kmem_free(spc, sizeof (scan_prefetch_ctx_t));
1464         }
1465 }
1466
1467 static scan_prefetch_ctx_t *
1468 scan_prefetch_ctx_create(dsl_scan_t *scn, dnode_phys_t *dnp, void *tag)
1469 {
1470         scan_prefetch_ctx_t *spc;
1471
1472         spc = kmem_alloc(sizeof (scan_prefetch_ctx_t), KM_SLEEP);
1473         zfs_refcount_create(&spc->spc_refcnt);
1474         zfs_refcount_add(&spc->spc_refcnt, tag);
1475         spc->spc_scn = scn;
1476         if (dnp != NULL) {
1477                 spc->spc_datablkszsec = dnp->dn_datablkszsec;
1478                 spc->spc_indblkshift = dnp->dn_indblkshift;
1479                 spc->spc_root = B_FALSE;
1480         } else {
1481                 spc->spc_datablkszsec = 0;
1482                 spc->spc_indblkshift = 0;
1483                 spc->spc_root = B_TRUE;
1484         }
1485
1486         return (spc);
1487 }
1488
1489 static void
1490 scan_prefetch_ctx_add_ref(scan_prefetch_ctx_t *spc, void *tag)
1491 {
1492         zfs_refcount_add(&spc->spc_refcnt, tag);
1493 }
1494
1495 static void
1496 scan_ds_prefetch_queue_clear(dsl_scan_t *scn)
1497 {
1498         spa_t *spa = scn->scn_dp->dp_spa;
1499         void *cookie = NULL;
1500         scan_prefetch_issue_ctx_t *spic = NULL;
1501
1502         mutex_enter(&spa->spa_scrub_lock);
1503         while ((spic = avl_destroy_nodes(&scn->scn_prefetch_queue,
1504             &cookie)) != NULL) {
1505                 scan_prefetch_ctx_rele(spic->spic_spc, scn);
1506                 kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));
1507         }
1508         mutex_exit(&spa->spa_scrub_lock);
1509 }
1510
1511 static boolean_t
1512 dsl_scan_check_prefetch_resume(scan_prefetch_ctx_t *spc,
1513     const zbookmark_phys_t *zb)
1514 {
1515         zbookmark_phys_t *last_zb = &spc->spc_scn->scn_prefetch_bookmark;
1516         dnode_phys_t tmp_dnp;
1517         dnode_phys_t *dnp = (spc->spc_root) ? NULL : &tmp_dnp;
1518
1519         if (zb->zb_objset != last_zb->zb_objset)
1520                 return (B_TRUE);
1521         if ((int64_t)zb->zb_object < 0)
1522                 return (B_FALSE);
1523
1524         tmp_dnp.dn_datablkszsec = spc->spc_datablkszsec;
1525         tmp_dnp.dn_indblkshift = spc->spc_indblkshift;
1526
1527         if (zbookmark_subtree_completed(dnp, zb, last_zb))
1528                 return (B_TRUE);
1529
1530         return (B_FALSE);
1531 }
1532
1533 static void
1534 dsl_scan_prefetch(scan_prefetch_ctx_t *spc, blkptr_t *bp, zbookmark_phys_t *zb)
1535 {
1536         avl_index_t idx;
1537         dsl_scan_t *scn = spc->spc_scn;
1538         spa_t *spa = scn->scn_dp->dp_spa;
1539         scan_prefetch_issue_ctx_t *spic;
1540
1541         if (zfs_no_scrub_prefetch || BP_IS_REDACTED(bp))
1542                 return;
1543
1544         if (BP_IS_HOLE(bp) || bp->blk_birth <= scn->scn_phys.scn_cur_min_txg ||
1545             (BP_GET_LEVEL(bp) == 0 && BP_GET_TYPE(bp) != DMU_OT_DNODE &&
1546             BP_GET_TYPE(bp) != DMU_OT_OBJSET))
1547                 return;
1548
1549         if (dsl_scan_check_prefetch_resume(spc, zb))
1550                 return;
1551
1552         scan_prefetch_ctx_add_ref(spc, scn);
1553         spic = kmem_alloc(sizeof (scan_prefetch_issue_ctx_t), KM_SLEEP);
1554         spic->spic_spc = spc;
1555         spic->spic_bp = *bp;
1556         spic->spic_zb = *zb;
1557
1558         /*
1559          * Add the IO to the queue of blocks to prefetch. This allows us to
1560          * prioritize blocks that we will need first for the main traversal
1561          * thread.
1562          */
1563         mutex_enter(&spa->spa_scrub_lock);
1564         if (avl_find(&scn->scn_prefetch_queue, spic, &idx) != NULL) {
1565                 /* this block is already queued for prefetch */
1566                 kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));
1567                 scan_prefetch_ctx_rele(spc, scn);
1568                 mutex_exit(&spa->spa_scrub_lock);
1569                 return;
1570         }
1571
1572         avl_insert(&scn->scn_prefetch_queue, spic, idx);
1573         cv_broadcast(&spa->spa_scrub_io_cv);
1574         mutex_exit(&spa->spa_scrub_lock);
1575 }
1576
1577 static void
1578 dsl_scan_prefetch_dnode(dsl_scan_t *scn, dnode_phys_t *dnp,
1579     uint64_t objset, uint64_t object)
1580 {
1581         int i;
1582         zbookmark_phys_t zb;
1583         scan_prefetch_ctx_t *spc;
1584
1585         if (dnp->dn_nblkptr == 0 && !(dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR))
1586                 return;
1587
1588         SET_BOOKMARK(&zb, objset, object, 0, 0);
1589
1590         spc = scan_prefetch_ctx_create(scn, dnp, FTAG);
1591
1592         for (i = 0; i < dnp->dn_nblkptr; i++) {
1593                 zb.zb_level = BP_GET_LEVEL(&dnp->dn_blkptr[i]);
1594                 zb.zb_blkid = i;
1595                 dsl_scan_prefetch(spc, &dnp->dn_blkptr[i], &zb);
1596         }
1597
1598         if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {
1599                 zb.zb_level = 0;
1600                 zb.zb_blkid = DMU_SPILL_BLKID;
1601                 dsl_scan_prefetch(spc, DN_SPILL_BLKPTR(dnp), &zb);
1602         }
1603
1604         scan_prefetch_ctx_rele(spc, FTAG);
1605 }
1606
1607 void
1608 dsl_scan_prefetch_cb(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
1609     arc_buf_t *buf, void *private)
1610 {
1611         scan_prefetch_ctx_t *spc = private;
1612         dsl_scan_t *scn = spc->spc_scn;
1613         spa_t *spa = scn->scn_dp->dp_spa;
1614
1615         /* broadcast that the IO has completed for rate limiting purposes */
1616         mutex_enter(&spa->spa_scrub_lock);
1617         ASSERT3U(spa->spa_scrub_inflight, >=, BP_GET_PSIZE(bp));
1618         spa->spa_scrub_inflight -= BP_GET_PSIZE(bp);
1619         cv_broadcast(&spa->spa_scrub_io_cv);
1620         mutex_exit(&spa->spa_scrub_lock);
1621
1622         /* if there was an error or we are done prefetching, just cleanup */
1623         if (buf == NULL || scn->scn_prefetch_stop)
1624                 goto out;
1625
1626         if (BP_GET_LEVEL(bp) > 0) {
1627                 int i;
1628                 blkptr_t *cbp;
1629                 int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
1630                 zbookmark_phys_t czb;
1631
1632                 for (i = 0, cbp = buf->b_data; i < epb; i++, cbp++) {
1633                         SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
1634                             zb->zb_level - 1, zb->zb_blkid * epb + i);
1635                         dsl_scan_prefetch(spc, cbp, &czb);
1636                 }
1637         } else if (BP_GET_TYPE(bp) == DMU_OT_DNODE) {
1638                 dnode_phys_t *cdnp;
1639                 int i;
1640                 int epb = BP_GET_LSIZE(bp) >> DNODE_SHIFT;
1641
1642                 for (i = 0, cdnp = buf->b_data; i < epb;
1643                     i += cdnp->dn_extra_slots + 1,
1644                     cdnp += cdnp->dn_extra_slots + 1) {
1645                         dsl_scan_prefetch_dnode(scn, cdnp,
1646                             zb->zb_objset, zb->zb_blkid * epb + i);
1647                 }
1648         } else if (BP_GET_TYPE(bp) == DMU_OT_OBJSET) {
1649                 objset_phys_t *osp = buf->b_data;
1650
1651                 dsl_scan_prefetch_dnode(scn, &osp->os_meta_dnode,
1652                     zb->zb_objset, DMU_META_DNODE_OBJECT);
1653
1654                 if (OBJSET_BUF_HAS_USERUSED(buf)) {
1655                         dsl_scan_prefetch_dnode(scn,
1656                             &osp->os_groupused_dnode, zb->zb_objset,
1657                             DMU_GROUPUSED_OBJECT);
1658                         dsl_scan_prefetch_dnode(scn,
1659                             &osp->os_userused_dnode, zb->zb_objset,
1660                             DMU_USERUSED_OBJECT);
1661                 }
1662         }
1663
1664 out:
1665         if (buf != NULL)
1666                 arc_buf_destroy(buf, private);
1667         scan_prefetch_ctx_rele(spc, scn);
1668 }
1669
1670 /* ARGSUSED */
1671 static void
1672 dsl_scan_prefetch_thread(void *arg)
1673 {
1674         dsl_scan_t *scn = arg;
1675         spa_t *spa = scn->scn_dp->dp_spa;
1676         scan_prefetch_issue_ctx_t *spic;
1677
1678         /* loop until we are told to stop */
1679         while (!scn->scn_prefetch_stop) {
1680                 arc_flags_t flags = ARC_FLAG_NOWAIT |
1681                     ARC_FLAG_PRESCIENT_PREFETCH | ARC_FLAG_PREFETCH;
1682                 int zio_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCAN_THREAD;
1683
1684                 mutex_enter(&spa->spa_scrub_lock);
1685
1686                 /*
1687                  * Wait until we have an IO to issue and are not above our
1688                  * maximum in flight limit.
1689                  */
1690                 while (!scn->scn_prefetch_stop &&
1691                     (avl_numnodes(&scn->scn_prefetch_queue) == 0 ||
1692                     spa->spa_scrub_inflight >= scn->scn_maxinflight_bytes)) {
1693                         cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
1694                 }
1695
1696                 /* recheck if we should stop since we waited for the cv */
1697                 if (scn->scn_prefetch_stop) {
1698                         mutex_exit(&spa->spa_scrub_lock);
1699                         break;
1700                 }
1701
1702                 /* remove the prefetch IO from the tree */
1703                 spic = avl_first(&scn->scn_prefetch_queue);
1704                 spa->spa_scrub_inflight += BP_GET_PSIZE(&spic->spic_bp);
1705                 avl_remove(&scn->scn_prefetch_queue, spic);
1706
1707                 mutex_exit(&spa->spa_scrub_lock);
1708
1709                 if (BP_IS_PROTECTED(&spic->spic_bp)) {
1710                         ASSERT(BP_GET_TYPE(&spic->spic_bp) == DMU_OT_DNODE ||
1711                             BP_GET_TYPE(&spic->spic_bp) == DMU_OT_OBJSET);
1712                         ASSERT3U(BP_GET_LEVEL(&spic->spic_bp), ==, 0);
1713                         zio_flags |= ZIO_FLAG_RAW;
1714                 }
1715
1716                 /* issue the prefetch asynchronously */
1717                 (void) arc_read(scn->scn_zio_root, scn->scn_dp->dp_spa,
1718                     &spic->spic_bp, dsl_scan_prefetch_cb, spic->spic_spc,
1719                     ZIO_PRIORITY_SCRUB, zio_flags, &flags, &spic->spic_zb);
1720
1721                 kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));
1722         }
1723
1724         ASSERT(scn->scn_prefetch_stop);
1725
1726         /* free any prefetches we didn't get to complete */
1727         mutex_enter(&spa->spa_scrub_lock);
1728         while ((spic = avl_first(&scn->scn_prefetch_queue)) != NULL) {
1729                 avl_remove(&scn->scn_prefetch_queue, spic);
1730                 scan_prefetch_ctx_rele(spic->spic_spc, scn);
1731                 kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));
1732         }
1733         ASSERT0(avl_numnodes(&scn->scn_prefetch_queue));
1734         mutex_exit(&spa->spa_scrub_lock);
1735 }
1736
1737 static boolean_t
1738 dsl_scan_check_resume(dsl_scan_t *scn, const dnode_phys_t *dnp,
1739     const zbookmark_phys_t *zb)
1740 {
1741         /*
1742          * We never skip over user/group accounting objects (obj<0)
1743          */
1744         if (!ZB_IS_ZERO(&scn->scn_phys.scn_bookmark) &&
1745             (int64_t)zb->zb_object >= 0) {
1746                 /*
1747                  * If we already visited this bp & everything below (in
1748                  * a prior txg sync), don't bother doing it again.
1749                  */
1750                 if (zbookmark_subtree_completed(dnp, zb,
1751                     &scn->scn_phys.scn_bookmark))
1752                         return (B_TRUE);
1753
1754                 /*
1755                  * If we found the block we're trying to resume from, or
1756                  * we went past it to a different object, zero it out to
1757                  * indicate that it's OK to start checking for suspending
1758                  * again.
1759                  */
1760                 if (bcmp(zb, &scn->scn_phys.scn_bookmark, sizeof (*zb)) == 0 ||
1761                     zb->zb_object > scn->scn_phys.scn_bookmark.zb_object) {
1762                         dprintf("resuming at %llx/%llx/%llx/%llx\n",
1763                             (longlong_t)zb->zb_objset,
1764                             (longlong_t)zb->zb_object,
1765                             (longlong_t)zb->zb_level,
1766                             (longlong_t)zb->zb_blkid);
1767                         bzero(&scn->scn_phys.scn_bookmark, sizeof (*zb));
1768                 }
1769         }
1770         return (B_FALSE);
1771 }
1772
1773 static void dsl_scan_visitbp(blkptr_t *bp, const zbookmark_phys_t *zb,
1774     dnode_phys_t *dnp, dsl_dataset_t *ds, dsl_scan_t *scn,
1775     dmu_objset_type_t ostype, dmu_tx_t *tx);
1776 inline __attribute__((always_inline)) static void dsl_scan_visitdnode(
1777     dsl_scan_t *, dsl_dataset_t *ds, dmu_objset_type_t ostype,
1778     dnode_phys_t *dnp, uint64_t object, dmu_tx_t *tx);
1779
1780 /*
1781  * Return nonzero on i/o error.
1782  * Return new buf to write out in *bufp.
1783  */
1784 inline __attribute__((always_inline)) static int
1785 dsl_scan_recurse(dsl_scan_t *scn, dsl_dataset_t *ds, dmu_objset_type_t ostype,
1786     dnode_phys_t *dnp, const blkptr_t *bp,
1787     const zbookmark_phys_t *zb, dmu_tx_t *tx)
1788 {
1789         dsl_pool_t *dp = scn->scn_dp;
1790         int zio_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCAN_THREAD;
1791         int err;
1792
1793         ASSERT(!BP_IS_REDACTED(bp));
1794
1795         if (BP_GET_LEVEL(bp) > 0) {
1796                 arc_flags_t flags = ARC_FLAG_WAIT;
1797                 int i;
1798                 blkptr_t *cbp;
1799                 int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
1800                 arc_buf_t *buf;
1801
1802                 err = arc_read(NULL, dp->dp_spa, bp, arc_getbuf_func, &buf,
1803                     ZIO_PRIORITY_SCRUB, zio_flags, &flags, zb);
1804                 if (err) {
1805                         scn->scn_phys.scn_errors++;
1806                         return (err);
1807                 }
1808                 for (i = 0, cbp = buf->b_data; i < epb; i++, cbp++) {
1809                         zbookmark_phys_t czb;
1810
1811                         SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
1812                             zb->zb_level - 1,
1813                             zb->zb_blkid * epb + i);
1814                         dsl_scan_visitbp(cbp, &czb, dnp,
1815                             ds, scn, ostype, tx);
1816                 }
1817                 arc_buf_destroy(buf, &buf);
1818         } else if (BP_GET_TYPE(bp) == DMU_OT_DNODE) {
1819                 arc_flags_t flags = ARC_FLAG_WAIT;
1820                 dnode_phys_t *cdnp;
1821                 int i;
1822                 int epb = BP_GET_LSIZE(bp) >> DNODE_SHIFT;
1823                 arc_buf_t *buf;
1824
1825                 if (BP_IS_PROTECTED(bp)) {
1826                         ASSERT3U(BP_GET_COMPRESS(bp), ==, ZIO_COMPRESS_OFF);
1827                         zio_flags |= ZIO_FLAG_RAW;
1828                 }
1829
1830                 err = arc_read(NULL, dp->dp_spa, bp, arc_getbuf_func, &buf,
1831                     ZIO_PRIORITY_SCRUB, zio_flags, &flags, zb);
1832                 if (err) {
1833                         scn->scn_phys.scn_errors++;
1834                         return (err);
1835                 }
1836                 for (i = 0, cdnp = buf->b_data; i < epb;
1837                     i += cdnp->dn_extra_slots + 1,
1838                     cdnp += cdnp->dn_extra_slots + 1) {
1839                         dsl_scan_visitdnode(scn, ds, ostype,
1840                             cdnp, zb->zb_blkid * epb + i, tx);
1841                 }
1842
1843                 arc_buf_destroy(buf, &buf);
1844         } else if (BP_GET_TYPE(bp) == DMU_OT_OBJSET) {
1845                 arc_flags_t flags = ARC_FLAG_WAIT;
1846                 objset_phys_t *osp;
1847                 arc_buf_t *buf;
1848
1849                 err = arc_read(NULL, dp->dp_spa, bp, arc_getbuf_func, &buf,
1850                     ZIO_PRIORITY_SCRUB, zio_flags, &flags, zb);
1851                 if (err) {
1852                         scn->scn_phys.scn_errors++;
1853                         return (err);
1854                 }
1855
1856                 osp = buf->b_data;
1857
1858                 dsl_scan_visitdnode(scn, ds, osp->os_type,
1859                     &osp->os_meta_dnode, DMU_META_DNODE_OBJECT, tx);
1860
1861                 if (OBJSET_BUF_HAS_USERUSED(buf)) {
1862                         /*
1863                          * We also always visit user/group/project accounting
1864                          * objects, and never skip them, even if we are
1865                          * suspending. This is necessary so that the
1866                          * space deltas from this txg get integrated.
1867                          */
1868                         if (OBJSET_BUF_HAS_PROJECTUSED(buf))
1869                                 dsl_scan_visitdnode(scn, ds, osp->os_type,
1870                                     &osp->os_projectused_dnode,
1871                                     DMU_PROJECTUSED_OBJECT, tx);
1872                         dsl_scan_visitdnode(scn, ds, osp->os_type,
1873                             &osp->os_groupused_dnode,
1874                             DMU_GROUPUSED_OBJECT, tx);
1875                         dsl_scan_visitdnode(scn, ds, osp->os_type,
1876                             &osp->os_userused_dnode,
1877                             DMU_USERUSED_OBJECT, tx);
1878                 }
1879                 arc_buf_destroy(buf, &buf);
1880         }
1881
1882         return (0);
1883 }
1884
1885 inline __attribute__((always_inline)) static void
1886 dsl_scan_visitdnode(dsl_scan_t *scn, dsl_dataset_t *ds,
1887     dmu_objset_type_t ostype, dnode_phys_t *dnp,
1888     uint64_t object, dmu_tx_t *tx)
1889 {
1890         int j;
1891
1892         for (j = 0; j < dnp->dn_nblkptr; j++) {
1893                 zbookmark_phys_t czb;
1894
1895                 SET_BOOKMARK(&czb, ds ? ds->ds_object : 0, object,
1896                     dnp->dn_nlevels - 1, j);
1897                 dsl_scan_visitbp(&dnp->dn_blkptr[j],
1898                     &czb, dnp, ds, scn, ostype, tx);
1899         }
1900
1901         if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {
1902                 zbookmark_phys_t czb;
1903                 SET_BOOKMARK(&czb, ds ? ds->ds_object : 0, object,
1904                     0, DMU_SPILL_BLKID);
1905                 dsl_scan_visitbp(DN_SPILL_BLKPTR(dnp),
1906                     &czb, dnp, ds, scn, ostype, tx);
1907         }
1908 }
1909
1910 /*
1911  * The arguments are in this order because mdb can only print the
1912  * first 5; we want them to be useful.
1913  */
1914 static void
1915 dsl_scan_visitbp(blkptr_t *bp, const zbookmark_phys_t *zb,
1916     dnode_phys_t *dnp, dsl_dataset_t *ds, dsl_scan_t *scn,
1917     dmu_objset_type_t ostype, dmu_tx_t *tx)
1918 {
1919         dsl_pool_t *dp = scn->scn_dp;
1920         blkptr_t *bp_toread = NULL;
1921
1922         if (dsl_scan_check_suspend(scn, zb))
1923                 return;
1924
1925         if (dsl_scan_check_resume(scn, dnp, zb))
1926                 return;
1927
1928         scn->scn_visited_this_txg++;
1929
1930         /*
1931          * This debugging is commented out to conserve stack space.  This
1932          * function is called recursively and the debugging adds several
1933          * bytes to the stack for each call.  It can be commented back in
1934          * if required to debug an issue in dsl_scan_visitbp().
1935          *
1936          * dprintf_bp(bp,
1937          *     "visiting ds=%p/%llu zb=%llx/%llx/%llx/%llx bp=%p",
1938          *     ds, ds ? ds->ds_object : 0,
1939          *     zb->zb_objset, zb->zb_object, zb->zb_level, zb->zb_blkid,
1940          *     bp);
1941          */
1942
1943         if (BP_IS_HOLE(bp)) {
1944                 scn->scn_holes_this_txg++;
1945                 return;
1946         }
1947
1948         if (BP_IS_REDACTED(bp)) {
1949                 ASSERT(dsl_dataset_feature_is_active(ds,
1950                     SPA_FEATURE_REDACTED_DATASETS));
1951                 return;
1952         }
1953
1954         if (bp->blk_birth <= scn->scn_phys.scn_cur_min_txg) {
1955                 scn->scn_lt_min_this_txg++;
1956                 return;
1957         }
1958
1959         bp_toread = kmem_alloc(sizeof (blkptr_t), KM_SLEEP);
1960         *bp_toread = *bp;
1961
1962         if (dsl_scan_recurse(scn, ds, ostype, dnp, bp_toread, zb, tx) != 0)
1963                 goto out;
1964
1965         /*
1966          * If dsl_scan_ddt() has already visited this block, it will have
1967          * already done any translations or scrubbing, so don't call the
1968          * callback again.
1969          */
1970         if (ddt_class_contains(dp->dp_spa,
1971             scn->scn_phys.scn_ddt_class_max, bp)) {
1972                 scn->scn_ddt_contained_this_txg++;
1973                 goto out;
1974         }
1975
1976         /*
1977          * If this block is from the future (after cur_max_txg), then we
1978          * are doing this on behalf of a deleted snapshot, and we will
1979          * revisit the future block on the next pass of this dataset.
1980          * Don't scan it now unless we need to because something
1981          * under it was modified.
1982          */
1983         if (BP_PHYSICAL_BIRTH(bp) > scn->scn_phys.scn_cur_max_txg) {
1984                 scn->scn_gt_max_this_txg++;
1985                 goto out;
1986         }
1987
1988         scan_funcs[scn->scn_phys.scn_func](dp, bp, zb);
1989
1990 out:
1991         kmem_free(bp_toread, sizeof (blkptr_t));
1992 }
1993
1994 static void
1995 dsl_scan_visit_rootbp(dsl_scan_t *scn, dsl_dataset_t *ds, blkptr_t *bp,
1996     dmu_tx_t *tx)
1997 {
1998         zbookmark_phys_t zb;
1999         scan_prefetch_ctx_t *spc;
2000
2001         SET_BOOKMARK(&zb, ds ? ds->ds_object : DMU_META_OBJSET,
2002             ZB_ROOT_OBJECT, ZB_ROOT_LEVEL, ZB_ROOT_BLKID);
2003
2004         if (ZB_IS_ZERO(&scn->scn_phys.scn_bookmark)) {
2005                 SET_BOOKMARK(&scn->scn_prefetch_bookmark,
2006                     zb.zb_objset, 0, 0, 0);
2007         } else {
2008                 scn->scn_prefetch_bookmark = scn->scn_phys.scn_bookmark;
2009         }
2010
2011         scn->scn_objsets_visited_this_txg++;
2012
2013         spc = scan_prefetch_ctx_create(scn, NULL, FTAG);
2014         dsl_scan_prefetch(spc, bp, &zb);
2015         scan_prefetch_ctx_rele(spc, FTAG);
2016
2017         dsl_scan_visitbp(bp, &zb, NULL, ds, scn, DMU_OST_NONE, tx);
2018
2019         dprintf_ds(ds, "finished scan%s", "");
2020 }
2021
2022 static void
2023 ds_destroyed_scn_phys(dsl_dataset_t *ds, dsl_scan_phys_t *scn_phys)
2024 {
2025         if (scn_phys->scn_bookmark.zb_objset == ds->ds_object) {
2026                 if (ds->ds_is_snapshot) {
2027                         /*
2028                          * Note:
2029                          *  - scn_cur_{min,max}_txg stays the same.
2030                          *  - Setting the flag is not really necessary if
2031                          *    scn_cur_max_txg == scn_max_txg, because there
2032                          *    is nothing after this snapshot that we care
2033                          *    about.  However, we set it anyway and then
2034                          *    ignore it when we retraverse it in
2035                          *    dsl_scan_visitds().
2036                          */
2037                         scn_phys->scn_bookmark.zb_objset =
2038                             dsl_dataset_phys(ds)->ds_next_snap_obj;
2039                         zfs_dbgmsg("destroying ds %llu; currently traversing; "
2040                             "reset zb_objset to %llu",
2041                             (u_longlong_t)ds->ds_object,
2042                             (u_longlong_t)dsl_dataset_phys(ds)->
2043                             ds_next_snap_obj);
2044                         scn_phys->scn_flags |= DSF_VISIT_DS_AGAIN;
2045                 } else {
2046                         SET_BOOKMARK(&scn_phys->scn_bookmark,
2047                             ZB_DESTROYED_OBJSET, 0, 0, 0);
2048                         zfs_dbgmsg("destroying ds %llu; currently traversing; "
2049                             "reset bookmark to -1,0,0,0",
2050                             (u_longlong_t)ds->ds_object);
2051                 }
2052         }
2053 }
2054
2055 /*
2056  * Invoked when a dataset is destroyed. We need to make sure that:
2057  *
2058  * 1) If it is the dataset that was currently being scanned, we write
2059  *      a new dsl_scan_phys_t and marking the objset reference in it
2060  *      as destroyed.
2061  * 2) Remove it from the work queue, if it was present.
2062  *
2063  * If the dataset was actually a snapshot, instead of marking the dataset
2064  * as destroyed, we instead substitute the next snapshot in line.
2065  */
2066 void
2067 dsl_scan_ds_destroyed(dsl_dataset_t *ds, dmu_tx_t *tx)
2068 {
2069         dsl_pool_t *dp = ds->ds_dir->dd_pool;
2070         dsl_scan_t *scn = dp->dp_scan;
2071         uint64_t mintxg;
2072
2073         if (!dsl_scan_is_running(scn))
2074                 return;
2075
2076         ds_destroyed_scn_phys(ds, &scn->scn_phys);
2077         ds_destroyed_scn_phys(ds, &scn->scn_phys_cached);
2078
2079         if (scan_ds_queue_contains(scn, ds->ds_object, &mintxg)) {
2080                 scan_ds_queue_remove(scn, ds->ds_object);
2081                 if (ds->ds_is_snapshot)
2082                         scan_ds_queue_insert(scn,
2083                             dsl_dataset_phys(ds)->ds_next_snap_obj, mintxg);
2084         }
2085
2086         if (zap_lookup_int_key(dp->dp_meta_objset, scn->scn_phys.scn_queue_obj,
2087             ds->ds_object, &mintxg) == 0) {
2088                 ASSERT3U(dsl_dataset_phys(ds)->ds_num_children, <=, 1);
2089                 VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
2090                     scn->scn_phys.scn_queue_obj, ds->ds_object, tx));
2091                 if (ds->ds_is_snapshot) {
2092                         /*
2093                          * We keep the same mintxg; it could be >
2094                          * ds_creation_txg if the previous snapshot was
2095                          * deleted too.
2096                          */
2097                         VERIFY(zap_add_int_key(dp->dp_meta_objset,
2098                             scn->scn_phys.scn_queue_obj,
2099                             dsl_dataset_phys(ds)->ds_next_snap_obj,
2100                             mintxg, tx) == 0);
2101                         zfs_dbgmsg("destroying ds %llu; in queue; "
2102                             "replacing with %llu",
2103                             (u_longlong_t)ds->ds_object,
2104                             (u_longlong_t)dsl_dataset_phys(ds)->
2105                             ds_next_snap_obj);
2106                 } else {
2107                         zfs_dbgmsg("destroying ds %llu; in queue; removing",
2108                             (u_longlong_t)ds->ds_object);
2109                 }
2110         }
2111
2112         /*
2113          * dsl_scan_sync() should be called after this, and should sync
2114          * out our changed state, but just to be safe, do it here.
2115          */
2116         dsl_scan_sync_state(scn, tx, SYNC_CACHED);
2117 }
2118
2119 static void
2120 ds_snapshotted_bookmark(dsl_dataset_t *ds, zbookmark_phys_t *scn_bookmark)
2121 {
2122         if (scn_bookmark->zb_objset == ds->ds_object) {
2123                 scn_bookmark->zb_objset =
2124                     dsl_dataset_phys(ds)->ds_prev_snap_obj;
2125                 zfs_dbgmsg("snapshotting ds %llu; currently traversing; "
2126                     "reset zb_objset to %llu",
2127                     (u_longlong_t)ds->ds_object,
2128                     (u_longlong_t)dsl_dataset_phys(ds)->ds_prev_snap_obj);
2129         }
2130 }
2131
2132 /*
2133  * Called when a dataset is snapshotted. If we were currently traversing
2134  * this snapshot, we reset our bookmark to point at the newly created
2135  * snapshot. We also modify our work queue to remove the old snapshot and
2136  * replace with the new one.
2137  */
2138 void
2139 dsl_scan_ds_snapshotted(dsl_dataset_t *ds, dmu_tx_t *tx)
2140 {
2141         dsl_pool_t *dp = ds->ds_dir->dd_pool;
2142         dsl_scan_t *scn = dp->dp_scan;
2143         uint64_t mintxg;
2144
2145         if (!dsl_scan_is_running(scn))
2146                 return;
2147
2148         ASSERT(dsl_dataset_phys(ds)->ds_prev_snap_obj != 0);
2149
2150         ds_snapshotted_bookmark(ds, &scn->scn_phys.scn_bookmark);
2151         ds_snapshotted_bookmark(ds, &scn->scn_phys_cached.scn_bookmark);
2152
2153         if (scan_ds_queue_contains(scn, ds->ds_object, &mintxg)) {
2154                 scan_ds_queue_remove(scn, ds->ds_object);
2155                 scan_ds_queue_insert(scn,
2156                     dsl_dataset_phys(ds)->ds_prev_snap_obj, mintxg);
2157         }
2158
2159         if (zap_lookup_int_key(dp->dp_meta_objset, scn->scn_phys.scn_queue_obj,
2160             ds->ds_object, &mintxg) == 0) {
2161                 VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
2162                     scn->scn_phys.scn_queue_obj, ds->ds_object, tx));
2163                 VERIFY(zap_add_int_key(dp->dp_meta_objset,
2164                     scn->scn_phys.scn_queue_obj,
2165                     dsl_dataset_phys(ds)->ds_prev_snap_obj, mintxg, tx) == 0);
2166                 zfs_dbgmsg("snapshotting ds %llu; in queue; "
2167                     "replacing with %llu",
2168                     (u_longlong_t)ds->ds_object,
2169                     (u_longlong_t)dsl_dataset_phys(ds)->ds_prev_snap_obj);
2170         }
2171
2172         dsl_scan_sync_state(scn, tx, SYNC_CACHED);
2173 }
2174
2175 static void
2176 ds_clone_swapped_bookmark(dsl_dataset_t *ds1, dsl_dataset_t *ds2,
2177     zbookmark_phys_t *scn_bookmark)
2178 {
2179         if (scn_bookmark->zb_objset == ds1->ds_object) {
2180                 scn_bookmark->zb_objset = ds2->ds_object;
2181                 zfs_dbgmsg("clone_swap ds %llu; currently traversing; "
2182                     "reset zb_objset to %llu",
2183                     (u_longlong_t)ds1->ds_object,
2184                     (u_longlong_t)ds2->ds_object);
2185         } else if (scn_bookmark->zb_objset == ds2->ds_object) {
2186                 scn_bookmark->zb_objset = ds1->ds_object;
2187                 zfs_dbgmsg("clone_swap ds %llu; currently traversing; "
2188                     "reset zb_objset to %llu",
2189                     (u_longlong_t)ds2->ds_object,
2190                     (u_longlong_t)ds1->ds_object);
2191         }
2192 }
2193
2194 /*
2195  * Called when an origin dataset and its clone are swapped.  If we were
2196  * currently traversing the dataset, we need to switch to traversing the
2197  * newly promoted clone.
2198  */
2199 void
2200 dsl_scan_ds_clone_swapped(dsl_dataset_t *ds1, dsl_dataset_t *ds2, dmu_tx_t *tx)
2201 {
2202         dsl_pool_t *dp = ds1->ds_dir->dd_pool;
2203         dsl_scan_t *scn = dp->dp_scan;
2204         uint64_t mintxg1, mintxg2;
2205         boolean_t ds1_queued, ds2_queued;
2206
2207         if (!dsl_scan_is_running(scn))
2208                 return;
2209
2210         ds_clone_swapped_bookmark(ds1, ds2, &scn->scn_phys.scn_bookmark);
2211         ds_clone_swapped_bookmark(ds1, ds2, &scn->scn_phys_cached.scn_bookmark);
2212
2213         /*
2214          * Handle the in-memory scan queue.
2215          */
2216         ds1_queued = scan_ds_queue_contains(scn, ds1->ds_object, &mintxg1);
2217         ds2_queued = scan_ds_queue_contains(scn, ds2->ds_object, &mintxg2);
2218
2219         /* Sanity checking. */
2220         if (ds1_queued) {
2221                 ASSERT3U(mintxg1, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);
2222                 ASSERT3U(mintxg1, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);
2223         }
2224         if (ds2_queued) {
2225                 ASSERT3U(mintxg2, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);
2226                 ASSERT3U(mintxg2, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);
2227         }
2228
2229         if (ds1_queued && ds2_queued) {
2230                 /*
2231                  * If both are queued, we don't need to do anything.
2232                  * The swapping code below would not handle this case correctly,
2233                  * since we can't insert ds2 if it is already there. That's
2234                  * because scan_ds_queue_insert() prohibits a duplicate insert
2235                  * and panics.
2236                  */
2237         } else if (ds1_queued) {
2238                 scan_ds_queue_remove(scn, ds1->ds_object);
2239                 scan_ds_queue_insert(scn, ds2->ds_object, mintxg1);
2240         } else if (ds2_queued) {
2241                 scan_ds_queue_remove(scn, ds2->ds_object);
2242                 scan_ds_queue_insert(scn, ds1->ds_object, mintxg2);
2243         }
2244
2245         /*
2246          * Handle the on-disk scan queue.
2247          * The on-disk state is an out-of-date version of the in-memory state,
2248          * so the in-memory and on-disk values for ds1_queued and ds2_queued may
2249          * be different. Therefore we need to apply the swap logic to the
2250          * on-disk state independently of the in-memory state.
2251          */
2252         ds1_queued = zap_lookup_int_key(dp->dp_meta_objset,
2253             scn->scn_phys.scn_queue_obj, ds1->ds_object, &mintxg1) == 0;
2254         ds2_queued = zap_lookup_int_key(dp->dp_meta_objset,
2255             scn->scn_phys.scn_queue_obj, ds2->ds_object, &mintxg2) == 0;
2256
2257         /* Sanity checking. */
2258         if (ds1_queued) {
2259                 ASSERT3U(mintxg1, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);
2260                 ASSERT3U(mintxg1, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);
2261         }
2262         if (ds2_queued) {
2263                 ASSERT3U(mintxg2, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);
2264                 ASSERT3U(mintxg2, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);
2265         }
2266
2267         if (ds1_queued && ds2_queued) {
2268                 /*
2269                  * If both are queued, we don't need to do anything.
2270                  * Alternatively, we could check for EEXIST from
2271                  * zap_add_int_key() and back out to the original state, but
2272                  * that would be more work than checking for this case upfront.
2273                  */
2274         } else if (ds1_queued) {
2275                 VERIFY3S(0, ==, zap_remove_int(dp->dp_meta_objset,
2276                     scn->scn_phys.scn_queue_obj, ds1->ds_object, tx));
2277                 VERIFY3S(0, ==, zap_add_int_key(dp->dp_meta_objset,
2278                     scn->scn_phys.scn_queue_obj, ds2->ds_object, mintxg1, tx));
2279                 zfs_dbgmsg("clone_swap ds %llu; in queue; "
2280                     "replacing with %llu",
2281                     (u_longlong_t)ds1->ds_object,
2282                     (u_longlong_t)ds2->ds_object);
2283         } else if (ds2_queued) {
2284                 VERIFY3S(0, ==, zap_remove_int(dp->dp_meta_objset,
2285                     scn->scn_phys.scn_queue_obj, ds2->ds_object, tx));
2286                 VERIFY3S(0, ==, zap_add_int_key(dp->dp_meta_objset,
2287                     scn->scn_phys.scn_queue_obj, ds1->ds_object, mintxg2, tx));
2288                 zfs_dbgmsg("clone_swap ds %llu; in queue; "
2289                     "replacing with %llu",
2290                     (u_longlong_t)ds2->ds_object,
2291                     (u_longlong_t)ds1->ds_object);
2292         }
2293
2294         dsl_scan_sync_state(scn, tx, SYNC_CACHED);
2295 }
2296
2297 /* ARGSUSED */
2298 static int
2299 enqueue_clones_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)
2300 {
2301         uint64_t originobj = *(uint64_t *)arg;
2302         dsl_dataset_t *ds;
2303         int err;
2304         dsl_scan_t *scn = dp->dp_scan;
2305
2306         if (dsl_dir_phys(hds->ds_dir)->dd_origin_obj != originobj)
2307                 return (0);
2308
2309         err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);
2310         if (err)
2311                 return (err);
2312
2313         while (dsl_dataset_phys(ds)->ds_prev_snap_obj != originobj) {
2314                 dsl_dataset_t *prev;
2315                 err = dsl_dataset_hold_obj(dp,
2316                     dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);
2317
2318                 dsl_dataset_rele(ds, FTAG);
2319                 if (err)
2320                         return (err);
2321                 ds = prev;
2322         }
2323         scan_ds_queue_insert(scn, ds->ds_object,
2324             dsl_dataset_phys(ds)->ds_prev_snap_txg);
2325         dsl_dataset_rele(ds, FTAG);
2326         return (0);
2327 }
2328
2329 static void
2330 dsl_scan_visitds(dsl_scan_t *scn, uint64_t dsobj, dmu_tx_t *tx)
2331 {
2332         dsl_pool_t *dp = scn->scn_dp;
2333         dsl_dataset_t *ds;
2334
2335         VERIFY3U(0, ==, dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
2336
2337         if (scn->scn_phys.scn_cur_min_txg >=
2338             scn->scn_phys.scn_max_txg) {
2339                 /*
2340                  * This can happen if this snapshot was created after the
2341                  * scan started, and we already completed a previous snapshot
2342                  * that was created after the scan started.  This snapshot
2343                  * only references blocks with:
2344                  *
2345                  *      birth < our ds_creation_txg
2346                  *      cur_min_txg is no less than ds_creation_txg.
2347                  *      We have already visited these blocks.
2348                  * or
2349                  *      birth > scn_max_txg
2350                  *      The scan requested not to visit these blocks.
2351                  *
2352                  * Subsequent snapshots (and clones) can reference our
2353                  * blocks, or blocks with even higher birth times.
2354                  * Therefore we do not need to visit them either,
2355                  * so we do not add them to the work queue.
2356                  *
2357                  * Note that checking for cur_min_txg >= cur_max_txg
2358                  * is not sufficient, because in that case we may need to
2359                  * visit subsequent snapshots.  This happens when min_txg > 0,
2360                  * which raises cur_min_txg.  In this case we will visit
2361                  * this dataset but skip all of its blocks, because the
2362                  * rootbp's birth time is < cur_min_txg.  Then we will
2363                  * add the next snapshots/clones to the work queue.
2364                  */
2365                 char *dsname = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
2366                 dsl_dataset_name(ds, dsname);
2367                 zfs_dbgmsg("scanning dataset %llu (%s) is unnecessary because "
2368                     "cur_min_txg (%llu) >= max_txg (%llu)",
2369                     (longlong_t)dsobj, dsname,
2370                     (longlong_t)scn->scn_phys.scn_cur_min_txg,
2371                     (longlong_t)scn->scn_phys.scn_max_txg);
2372                 kmem_free(dsname, MAXNAMELEN);
2373
2374                 goto out;
2375         }
2376
2377         /*
2378          * Only the ZIL in the head (non-snapshot) is valid. Even though
2379          * snapshots can have ZIL block pointers (which may be the same
2380          * BP as in the head), they must be ignored. In addition, $ORIGIN
2381          * doesn't have a objset (i.e. its ds_bp is a hole) so we don't
2382          * need to look for a ZIL in it either. So we traverse the ZIL here,
2383          * rather than in scan_recurse(), because the regular snapshot
2384          * block-sharing rules don't apply to it.
2385          */
2386         if (!dsl_dataset_is_snapshot(ds) &&
2387             (dp->dp_origin_snap == NULL ||
2388             ds->ds_dir != dp->dp_origin_snap->ds_dir)) {
2389                 objset_t *os;
2390                 if (dmu_objset_from_ds(ds, &os) != 0) {
2391                         goto out;
2392                 }
2393                 dsl_scan_zil(dp, &os->os_zil_header);
2394         }
2395
2396         /*
2397          * Iterate over the bps in this ds.
2398          */
2399         dmu_buf_will_dirty(ds->ds_dbuf, tx);
2400         rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
2401         dsl_scan_visit_rootbp(scn, ds, &dsl_dataset_phys(ds)->ds_bp, tx);
2402         rrw_exit(&ds->ds_bp_rwlock, FTAG);
2403
2404         char *dsname = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
2405         dsl_dataset_name(ds, dsname);
2406         zfs_dbgmsg("scanned dataset %llu (%s) with min=%llu max=%llu; "
2407             "suspending=%u",
2408             (longlong_t)dsobj, dsname,
2409             (longlong_t)scn->scn_phys.scn_cur_min_txg,
2410             (longlong_t)scn->scn_phys.scn_cur_max_txg,
2411             (int)scn->scn_suspending);
2412         kmem_free(dsname, ZFS_MAX_DATASET_NAME_LEN);
2413
2414         if (scn->scn_suspending)
2415                 goto out;
2416
2417         /*
2418          * We've finished this pass over this dataset.
2419          */
2420
2421         /*
2422          * If we did not completely visit this dataset, do another pass.
2423          */
2424         if (scn->scn_phys.scn_flags & DSF_VISIT_DS_AGAIN) {
2425                 zfs_dbgmsg("incomplete pass; visiting again");
2426                 scn->scn_phys.scn_flags &= ~DSF_VISIT_DS_AGAIN;
2427                 scan_ds_queue_insert(scn, ds->ds_object,
2428                     scn->scn_phys.scn_cur_max_txg);
2429                 goto out;
2430         }
2431
2432         /*
2433          * Add descendant datasets to work queue.
2434          */
2435         if (dsl_dataset_phys(ds)->ds_next_snap_obj != 0) {
2436                 scan_ds_queue_insert(scn,
2437                     dsl_dataset_phys(ds)->ds_next_snap_obj,
2438                     dsl_dataset_phys(ds)->ds_creation_txg);
2439         }
2440         if (dsl_dataset_phys(ds)->ds_num_children > 1) {
2441                 boolean_t usenext = B_FALSE;
2442                 if (dsl_dataset_phys(ds)->ds_next_clones_obj != 0) {
2443                         uint64_t count;
2444                         /*
2445                          * A bug in a previous version of the code could
2446                          * cause upgrade_clones_cb() to not set
2447                          * ds_next_snap_obj when it should, leading to a
2448                          * missing entry.  Therefore we can only use the
2449                          * next_clones_obj when its count is correct.
2450                          */
2451                         int err = zap_count(dp->dp_meta_objset,
2452                             dsl_dataset_phys(ds)->ds_next_clones_obj, &count);
2453                         if (err == 0 &&
2454                             count == dsl_dataset_phys(ds)->ds_num_children - 1)
2455                                 usenext = B_TRUE;
2456                 }
2457
2458                 if (usenext) {
2459                         zap_cursor_t zc;
2460                         zap_attribute_t za;
2461                         for (zap_cursor_init(&zc, dp->dp_meta_objset,
2462                             dsl_dataset_phys(ds)->ds_next_clones_obj);
2463                             zap_cursor_retrieve(&zc, &za) == 0;
2464                             (void) zap_cursor_advance(&zc)) {
2465                                 scan_ds_queue_insert(scn,
2466                                     zfs_strtonum(za.za_name, NULL),
2467                                     dsl_dataset_phys(ds)->ds_creation_txg);
2468                         }
2469                         zap_cursor_fini(&zc);
2470                 } else {
2471                         VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
2472                             enqueue_clones_cb, &ds->ds_object,
2473                             DS_FIND_CHILDREN));
2474                 }
2475         }
2476
2477 out:
2478         dsl_dataset_rele(ds, FTAG);
2479 }
2480
2481 /* ARGSUSED */
2482 static int
2483 enqueue_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)
2484 {
2485         dsl_dataset_t *ds;
2486         int err;
2487         dsl_scan_t *scn = dp->dp_scan;
2488
2489         err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);
2490         if (err)
2491                 return (err);
2492
2493         while (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) {
2494                 dsl_dataset_t *prev;
2495                 err = dsl_dataset_hold_obj(dp,
2496                     dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);
2497                 if (err) {
2498                         dsl_dataset_rele(ds, FTAG);
2499                         return (err);
2500                 }
2501
2502                 /*
2503                  * If this is a clone, we don't need to worry about it for now.
2504                  */
2505                 if (dsl_dataset_phys(prev)->ds_next_snap_obj != ds->ds_object) {
2506                         dsl_dataset_rele(ds, FTAG);
2507                         dsl_dataset_rele(prev, FTAG);
2508                         return (0);
2509                 }
2510                 dsl_dataset_rele(ds, FTAG);
2511                 ds = prev;
2512         }
2513
2514         scan_ds_queue_insert(scn, ds->ds_object,
2515             dsl_dataset_phys(ds)->ds_prev_snap_txg);
2516         dsl_dataset_rele(ds, FTAG);
2517         return (0);
2518 }
2519
2520 /* ARGSUSED */
2521 void
2522 dsl_scan_ddt_entry(dsl_scan_t *scn, enum zio_checksum checksum,
2523     ddt_entry_t *dde, dmu_tx_t *tx)
2524 {
2525         const ddt_key_t *ddk = &dde->dde_key;
2526         ddt_phys_t *ddp = dde->dde_phys;
2527         blkptr_t bp;
2528         zbookmark_phys_t zb = { 0 };
2529         int p;
2530
2531         if (!dsl_scan_is_running(scn))
2532                 return;
2533
2534         /*
2535          * This function is special because it is the only thing
2536          * that can add scan_io_t's to the vdev scan queues from
2537          * outside dsl_scan_sync(). For the most part this is ok
2538          * as long as it is called from within syncing context.
2539          * However, dsl_scan_sync() expects that no new sio's will
2540          * be added between when all the work for a scan is done
2541          * and the next txg when the scan is actually marked as
2542          * completed. This check ensures we do not issue new sio's
2543          * during this period.
2544          */
2545         if (scn->scn_done_txg != 0)
2546                 return;
2547
2548         for (p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
2549                 if (ddp->ddp_phys_birth == 0 ||
2550                     ddp->ddp_phys_birth > scn->scn_phys.scn_max_txg)
2551                         continue;
2552                 ddt_bp_create(checksum, ddk, ddp, &bp);
2553
2554                 scn->scn_visited_this_txg++;
2555                 scan_funcs[scn->scn_phys.scn_func](scn->scn_dp, &bp, &zb);
2556         }
2557 }
2558
2559 /*
2560  * Scrub/dedup interaction.
2561  *
2562  * If there are N references to a deduped block, we don't want to scrub it
2563  * N times -- ideally, we should scrub it exactly once.
2564  *
2565  * We leverage the fact that the dde's replication class (enum ddt_class)
2566  * is ordered from highest replication class (DDT_CLASS_DITTO) to lowest
2567  * (DDT_CLASS_UNIQUE) so that we may walk the DDT in that order.
2568  *
2569  * To prevent excess scrubbing, the scrub begins by walking the DDT
2570  * to find all blocks with refcnt > 1, and scrubs each of these once.
2571  * Since there are two replication classes which contain blocks with
2572  * refcnt > 1, we scrub the highest replication class (DDT_CLASS_DITTO) first.
2573  * Finally the top-down scrub begins, only visiting blocks with refcnt == 1.
2574  *
2575  * There would be nothing more to say if a block's refcnt couldn't change
2576  * during a scrub, but of course it can so we must account for changes
2577  * in a block's replication class.
2578  *
2579  * Here's an example of what can occur:
2580  *
2581  * If a block has refcnt > 1 during the DDT scrub phase, but has refcnt == 1
2582  * when visited during the top-down scrub phase, it will be scrubbed twice.
2583  * This negates our scrub optimization, but is otherwise harmless.
2584  *
2585  * If a block has refcnt == 1 during the DDT scrub phase, but has refcnt > 1
2586  * on each visit during the top-down scrub phase, it will never be scrubbed.
2587  * To catch this, ddt_sync_entry() notifies the scrub code whenever a block's
2588  * reference class transitions to a higher level (i.e DDT_CLASS_UNIQUE to
2589  * DDT_CLASS_DUPLICATE); if it transitions from refcnt == 1 to refcnt > 1
2590  * while a scrub is in progress, it scrubs the block right then.
2591  */
2592 static void
2593 dsl_scan_ddt(dsl_scan_t *scn, dmu_tx_t *tx)
2594 {
2595         ddt_bookmark_t *ddb = &scn->scn_phys.scn_ddt_bookmark;
2596         ddt_entry_t dde;
2597         int error;
2598         uint64_t n = 0;
2599
2600         bzero(&dde, sizeof (ddt_entry_t));
2601
2602         while ((error = ddt_walk(scn->scn_dp->dp_spa, ddb, &dde)) == 0) {
2603                 ddt_t *ddt;
2604
2605                 if (ddb->ddb_class > scn->scn_phys.scn_ddt_class_max)
2606                         break;
2607                 dprintf("visiting ddb=%llu/%llu/%llu/%llx\n",
2608                     (longlong_t)ddb->ddb_class,
2609                     (longlong_t)ddb->ddb_type,
2610                     (longlong_t)ddb->ddb_checksum,
2611                     (longlong_t)ddb->ddb_cursor);
2612
2613                 /* There should be no pending changes to the dedup table */
2614                 ddt = scn->scn_dp->dp_spa->spa_ddt[ddb->ddb_checksum];
2615                 ASSERT(avl_first(&ddt->ddt_tree) == NULL);
2616
2617                 dsl_scan_ddt_entry(scn, ddb->ddb_checksum, &dde, tx);
2618                 n++;
2619
2620                 if (dsl_scan_check_suspend(scn, NULL))
2621                         break;
2622         }
2623
2624         zfs_dbgmsg("scanned %llu ddt entries with class_max = %u; "
2625             "suspending=%u", (longlong_t)n,
2626             (int)scn->scn_phys.scn_ddt_class_max, (int)scn->scn_suspending);
2627
2628         ASSERT(error == 0 || error == ENOENT);
2629         ASSERT(error != ENOENT ||
2630             ddb->ddb_class > scn->scn_phys.scn_ddt_class_max);
2631 }
2632
2633 static uint64_t
2634 dsl_scan_ds_maxtxg(dsl_dataset_t *ds)
2635 {
2636         uint64_t smt = ds->ds_dir->dd_pool->dp_scan->scn_phys.scn_max_txg;
2637         if (ds->ds_is_snapshot)
2638                 return (MIN(smt, dsl_dataset_phys(ds)->ds_creation_txg));
2639         return (smt);
2640 }
2641
2642 static void
2643 dsl_scan_visit(dsl_scan_t *scn, dmu_tx_t *tx)
2644 {
2645         scan_ds_t *sds;
2646         dsl_pool_t *dp = scn->scn_dp;
2647
2648         if (scn->scn_phys.scn_ddt_bookmark.ddb_class <=
2649             scn->scn_phys.scn_ddt_class_max) {
2650                 scn->scn_phys.scn_cur_min_txg = scn->scn_phys.scn_min_txg;
2651                 scn->scn_phys.scn_cur_max_txg = scn->scn_phys.scn_max_txg;
2652                 dsl_scan_ddt(scn, tx);
2653                 if (scn->scn_suspending)
2654                         return;
2655         }
2656
2657         if (scn->scn_phys.scn_bookmark.zb_objset == DMU_META_OBJSET) {
2658                 /* First do the MOS & ORIGIN */
2659
2660                 scn->scn_phys.scn_cur_min_txg = scn->scn_phys.scn_min_txg;
2661                 scn->scn_phys.scn_cur_max_txg = scn->scn_phys.scn_max_txg;
2662                 dsl_scan_visit_rootbp(scn, NULL,
2663                     &dp->dp_meta_rootbp, tx);
2664                 spa_set_rootblkptr(dp->dp_spa, &dp->dp_meta_rootbp);
2665                 if (scn->scn_suspending)
2666                         return;
2667
2668                 if (spa_version(dp->dp_spa) < SPA_VERSION_DSL_SCRUB) {
2669                         VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
2670                             enqueue_cb, NULL, DS_FIND_CHILDREN));
2671                 } else {
2672                         dsl_scan_visitds(scn,
2673                             dp->dp_origin_snap->ds_object, tx);
2674                 }
2675                 ASSERT(!scn->scn_suspending);
2676         } else if (scn->scn_phys.scn_bookmark.zb_objset !=
2677             ZB_DESTROYED_OBJSET) {
2678                 uint64_t dsobj = scn->scn_phys.scn_bookmark.zb_objset;
2679                 /*
2680                  * If we were suspended, continue from here. Note if the
2681                  * ds we were suspended on was deleted, the zb_objset may
2682                  * be -1, so we will skip this and find a new objset
2683                  * below.
2684                  */
2685                 dsl_scan_visitds(scn, dsobj, tx);
2686                 if (scn->scn_suspending)
2687                         return;
2688         }
2689
2690         /*
2691          * In case we suspended right at the end of the ds, zero the
2692          * bookmark so we don't think that we're still trying to resume.
2693          */
2694         bzero(&scn->scn_phys.scn_bookmark, sizeof (zbookmark_phys_t));
2695
2696         /*
2697          * Keep pulling things out of the dataset avl queue. Updates to the
2698          * persistent zap-object-as-queue happen only at checkpoints.
2699          */
2700         while ((sds = avl_first(&scn->scn_queue)) != NULL) {
2701                 dsl_dataset_t *ds;
2702                 uint64_t dsobj = sds->sds_dsobj;
2703                 uint64_t txg = sds->sds_txg;
2704
2705                 /* dequeue and free the ds from the queue */
2706                 scan_ds_queue_remove(scn, dsobj);
2707                 sds = NULL;
2708
2709                 /* set up min / max txg */
2710                 VERIFY3U(0, ==, dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
2711                 if (txg != 0) {
2712                         scn->scn_phys.scn_cur_min_txg =
2713                             MAX(scn->scn_phys.scn_min_txg, txg);
2714                 } else {
2715                         scn->scn_phys.scn_cur_min_txg =
2716                             MAX(scn->scn_phys.scn_min_txg,
2717                             dsl_dataset_phys(ds)->ds_prev_snap_txg);
2718                 }
2719                 scn->scn_phys.scn_cur_max_txg = dsl_scan_ds_maxtxg(ds);
2720                 dsl_dataset_rele(ds, FTAG);
2721
2722                 dsl_scan_visitds(scn, dsobj, tx);
2723                 if (scn->scn_suspending)
2724                         return;
2725         }
2726
2727         /* No more objsets to fetch, we're done */
2728         scn->scn_phys.scn_bookmark.zb_objset = ZB_DESTROYED_OBJSET;
2729         ASSERT0(scn->scn_suspending);
2730 }
2731
2732 static uint64_t
2733 dsl_scan_count_leaves(vdev_t *vd)
2734 {
2735         uint64_t i, leaves = 0;
2736
2737         /* we only count leaves that belong to the main pool and are readable */
2738         if (vd->vdev_islog || vd->vdev_isspare ||
2739             vd->vdev_isl2cache || !vdev_readable(vd))
2740                 return (0);
2741
2742         if (vd->vdev_ops->vdev_op_leaf)
2743                 return (1);
2744
2745         for (i = 0; i < vd->vdev_children; i++) {
2746                 leaves += dsl_scan_count_leaves(vd->vdev_child[i]);
2747         }
2748
2749         return (leaves);
2750 }
2751
2752 static void
2753 scan_io_queues_update_zio_stats(dsl_scan_io_queue_t *q, const blkptr_t *bp)
2754 {
2755         int i;
2756         uint64_t cur_size = 0;
2757
2758         for (i = 0; i < BP_GET_NDVAS(bp); i++) {
2759                 cur_size += DVA_GET_ASIZE(&bp->blk_dva[i]);
2760         }
2761
2762         q->q_total_zio_size_this_txg += cur_size;
2763         q->q_zios_this_txg++;
2764 }
2765
2766 static void
2767 scan_io_queues_update_seg_stats(dsl_scan_io_queue_t *q, uint64_t start,
2768     uint64_t end)
2769 {
2770         q->q_total_seg_size_this_txg += end - start;
2771         q->q_segs_this_txg++;
2772 }
2773
2774 static boolean_t
2775 scan_io_queue_check_suspend(dsl_scan_t *scn)
2776 {
2777         /* See comment in dsl_scan_check_suspend() */
2778         uint64_t curr_time_ns = gethrtime();
2779         uint64_t scan_time_ns = curr_time_ns - scn->scn_sync_start_time;
2780         uint64_t sync_time_ns = curr_time_ns -
2781             scn->scn_dp->dp_spa->spa_sync_starttime;
2782         int dirty_pct = scn->scn_dp->dp_dirty_total * 100 / zfs_dirty_data_max;
2783         int mintime = (scn->scn_phys.scn_func == POOL_SCAN_RESILVER) ?
2784             zfs_resilver_min_time_ms : zfs_scrub_min_time_ms;
2785
2786         return ((NSEC2MSEC(scan_time_ns) > mintime &&
2787             (dirty_pct >= zfs_vdev_async_write_active_min_dirty_percent ||
2788             txg_sync_waiting(scn->scn_dp) ||
2789             NSEC2SEC(sync_time_ns) >= zfs_txg_timeout)) ||
2790             spa_shutting_down(scn->scn_dp->dp_spa));
2791 }
2792
2793 /*
2794  * Given a list of scan_io_t's in io_list, this issues the I/Os out to
2795  * disk. This consumes the io_list and frees the scan_io_t's. This is
2796  * called when emptying queues, either when we're up against the memory
2797  * limit or when we have finished scanning. Returns B_TRUE if we stopped
2798  * processing the list before we finished. Any sios that were not issued
2799  * will remain in the io_list.
2800  */
2801 static boolean_t
2802 scan_io_queue_issue(dsl_scan_io_queue_t *queue, list_t *io_list)
2803 {
2804         dsl_scan_t *scn = queue->q_scn;
2805         scan_io_t *sio;
2806         int64_t bytes_issued = 0;
2807         boolean_t suspended = B_FALSE;
2808
2809         while ((sio = list_head(io_list)) != NULL) {
2810                 blkptr_t bp;
2811
2812                 if (scan_io_queue_check_suspend(scn)) {
2813                         suspended = B_TRUE;
2814                         break;
2815                 }
2816
2817                 sio2bp(sio, &bp);
2818                 bytes_issued += SIO_GET_ASIZE(sio);
2819                 scan_exec_io(scn->scn_dp, &bp, sio->sio_flags,
2820                     &sio->sio_zb, queue);
2821                 (void) list_remove_head(io_list);
2822                 scan_io_queues_update_zio_stats(queue, &bp);
2823                 sio_free(sio);
2824         }
2825
2826         atomic_add_64(&scn->scn_bytes_pending, -bytes_issued);
2827
2828         return (suspended);
2829 }
2830
2831 /*
2832  * This function removes sios from an IO queue which reside within a given
2833  * range_seg_t and inserts them (in offset order) into a list. Note that
2834  * we only ever return a maximum of 32 sios at once. If there are more sios
2835  * to process within this segment that did not make it onto the list we
2836  * return B_TRUE and otherwise B_FALSE.
2837  */
2838 static boolean_t
2839 scan_io_queue_gather(dsl_scan_io_queue_t *queue, range_seg_t *rs, list_t *list)
2840 {
2841         scan_io_t *srch_sio, *sio, *next_sio;
2842         avl_index_t idx;
2843         uint_t num_sios = 0;
2844         int64_t bytes_issued = 0;
2845
2846         ASSERT(rs != NULL);
2847         ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
2848
2849         srch_sio = sio_alloc(1);
2850         srch_sio->sio_nr_dvas = 1;
2851         SIO_SET_OFFSET(srch_sio, rs_get_start(rs, queue->q_exts_by_addr));
2852
2853         /*
2854          * The exact start of the extent might not contain any matching zios,
2855          * so if that's the case, examine the next one in the tree.
2856          */
2857         sio = avl_find(&queue->q_sios_by_addr, srch_sio, &idx);
2858         sio_free(srch_sio);
2859
2860         if (sio == NULL)
2861                 sio = avl_nearest(&queue->q_sios_by_addr, idx, AVL_AFTER);
2862
2863         while (sio != NULL && SIO_GET_OFFSET(sio) < rs_get_end(rs,
2864             queue->q_exts_by_addr) && num_sios <= 32) {
2865                 ASSERT3U(SIO_GET_OFFSET(sio), >=, rs_get_start(rs,
2866                     queue->q_exts_by_addr));
2867                 ASSERT3U(SIO_GET_END_OFFSET(sio), <=, rs_get_end(rs,
2868                     queue->q_exts_by_addr));
2869
2870                 next_sio = AVL_NEXT(&queue->q_sios_by_addr, sio);
2871                 avl_remove(&queue->q_sios_by_addr, sio);
2872                 queue->q_sio_memused -= SIO_GET_MUSED(sio);
2873
2874                 bytes_issued += SIO_GET_ASIZE(sio);
2875                 num_sios++;
2876                 list_insert_tail(list, sio);
2877                 sio = next_sio;
2878         }
2879
2880         /*
2881          * We limit the number of sios we process at once to 32 to avoid
2882          * biting off more than we can chew. If we didn't take everything
2883          * in the segment we update it to reflect the work we were able to
2884          * complete. Otherwise, we remove it from the range tree entirely.
2885          */
2886         if (sio != NULL && SIO_GET_OFFSET(sio) < rs_get_end(rs,
2887             queue->q_exts_by_addr)) {
2888                 range_tree_adjust_fill(queue->q_exts_by_addr, rs,
2889                     -bytes_issued);
2890                 range_tree_resize_segment(queue->q_exts_by_addr, rs,
2891                     SIO_GET_OFFSET(sio), rs_get_end(rs,
2892                     queue->q_exts_by_addr) - SIO_GET_OFFSET(sio));
2893
2894                 return (B_TRUE);
2895         } else {
2896                 uint64_t rstart = rs_get_start(rs, queue->q_exts_by_addr);
2897                 uint64_t rend = rs_get_end(rs, queue->q_exts_by_addr);
2898                 range_tree_remove(queue->q_exts_by_addr, rstart, rend - rstart);
2899                 return (B_FALSE);
2900         }
2901 }
2902
2903 /*
2904  * This is called from the queue emptying thread and selects the next
2905  * extent from which we are to issue I/Os. The behavior of this function
2906  * depends on the state of the scan, the current memory consumption and
2907  * whether or not we are performing a scan shutdown.
2908  * 1) We select extents in an elevator algorithm (LBA-order) if the scan
2909  *      needs to perform a checkpoint
2910  * 2) We select the largest available extent if we are up against the
2911  *      memory limit.
2912  * 3) Otherwise we don't select any extents.
2913  */
2914 static range_seg_t *
2915 scan_io_queue_fetch_ext(dsl_scan_io_queue_t *queue)
2916 {
2917         dsl_scan_t *scn = queue->q_scn;
2918         range_tree_t *rt = queue->q_exts_by_addr;
2919
2920         ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
2921         ASSERT(scn->scn_is_sorted);
2922
2923         /* handle tunable overrides */
2924         if (scn->scn_checkpointing || scn->scn_clearing) {
2925                 if (zfs_scan_issue_strategy == 1) {
2926                         return (range_tree_first(rt));
2927                 } else if (zfs_scan_issue_strategy == 2) {
2928                         /*
2929                          * We need to get the original entry in the by_addr
2930                          * tree so we can modify it.
2931                          */
2932                         range_seg_t *size_rs =
2933                             zfs_btree_first(&queue->q_exts_by_size, NULL);
2934                         if (size_rs == NULL)
2935                                 return (NULL);
2936                         uint64_t start = rs_get_start(size_rs, rt);
2937                         uint64_t size = rs_get_end(size_rs, rt) - start;
2938                         range_seg_t *addr_rs = range_tree_find(rt, start,
2939                             size);
2940                         ASSERT3P(addr_rs, !=, NULL);
2941                         ASSERT3U(rs_get_start(size_rs, rt), ==,
2942                             rs_get_start(addr_rs, rt));
2943                         ASSERT3U(rs_get_end(size_rs, rt), ==,
2944                             rs_get_end(addr_rs, rt));
2945                         return (addr_rs);
2946                 }
2947         }
2948
2949         /*
2950          * During normal clearing, we want to issue our largest segments
2951          * first, keeping IO as sequential as possible, and leaving the
2952          * smaller extents for later with the hope that they might eventually
2953          * grow to larger sequential segments. However, when the scan is
2954          * checkpointing, no new extents will be added to the sorting queue,
2955          * so the way we are sorted now is as good as it will ever get.
2956          * In this case, we instead switch to issuing extents in LBA order.
2957          */
2958         if (scn->scn_checkpointing) {
2959                 return (range_tree_first(rt));
2960         } else if (scn->scn_clearing) {
2961                 /*
2962                  * We need to get the original entry in the by_addr
2963                  * tree so we can modify it.
2964                  */
2965                 range_seg_t *size_rs = zfs_btree_first(&queue->q_exts_by_size,
2966                     NULL);
2967                 if (size_rs == NULL)
2968                         return (NULL);
2969                 uint64_t start = rs_get_start(size_rs, rt);
2970                 uint64_t size = rs_get_end(size_rs, rt) - start;
2971                 range_seg_t *addr_rs = range_tree_find(rt, start, size);
2972                 ASSERT3P(addr_rs, !=, NULL);
2973                 ASSERT3U(rs_get_start(size_rs, rt), ==, rs_get_start(addr_rs,
2974                     rt));
2975                 ASSERT3U(rs_get_end(size_rs, rt), ==, rs_get_end(addr_rs, rt));
2976                 return (addr_rs);
2977         } else {
2978                 return (NULL);
2979         }
2980 }
2981
2982 static void
2983 scan_io_queues_run_one(void *arg)
2984 {
2985         dsl_scan_io_queue_t *queue = arg;
2986         kmutex_t *q_lock = &queue->q_vd->vdev_scan_io_queue_lock;
2987         boolean_t suspended = B_FALSE;
2988         range_seg_t *rs = NULL;
2989         scan_io_t *sio = NULL;
2990         list_t sio_list;
2991         uint64_t bytes_per_leaf = zfs_scan_vdev_limit;
2992         uint64_t nr_leaves = dsl_scan_count_leaves(queue->q_vd);
2993
2994         ASSERT(queue->q_scn->scn_is_sorted);
2995
2996         list_create(&sio_list, sizeof (scan_io_t),
2997             offsetof(scan_io_t, sio_nodes.sio_list_node));
2998         mutex_enter(q_lock);
2999
3000         /* calculate maximum in-flight bytes for this txg (min 1MB) */
3001         queue->q_maxinflight_bytes =
3002             MAX(nr_leaves * bytes_per_leaf, 1ULL << 20);
3003
3004         /* reset per-queue scan statistics for this txg */
3005         queue->q_total_seg_size_this_txg = 0;
3006         queue->q_segs_this_txg = 0;
3007         queue->q_total_zio_size_this_txg = 0;
3008         queue->q_zios_this_txg = 0;
3009
3010         /* loop until we run out of time or sios */
3011         while ((rs = scan_io_queue_fetch_ext(queue)) != NULL) {
3012                 uint64_t seg_start = 0, seg_end = 0;
3013                 boolean_t more_left = B_TRUE;
3014
3015                 ASSERT(list_is_empty(&sio_list));
3016
3017                 /* loop while we still have sios left to process in this rs */
3018                 while (more_left) {
3019                         scan_io_t *first_sio, *last_sio;
3020
3021                         /*
3022                          * We have selected which extent needs to be
3023                          * processed next. Gather up the corresponding sios.
3024                          */
3025                         more_left = scan_io_queue_gather(queue, rs, &sio_list);
3026                         ASSERT(!list_is_empty(&sio_list));
3027                         first_sio = list_head(&sio_list);
3028                         last_sio = list_tail(&sio_list);
3029
3030                         seg_end = SIO_GET_END_OFFSET(last_sio);
3031                         if (seg_start == 0)
3032                                 seg_start = SIO_GET_OFFSET(first_sio);
3033
3034                         /*
3035                          * Issuing sios can take a long time so drop the
3036                          * queue lock. The sio queue won't be updated by
3037                          * other threads since we're in syncing context so
3038                          * we can be sure that our trees will remain exactly
3039                          * as we left them.
3040                          */
3041                         mutex_exit(q_lock);
3042                         suspended = scan_io_queue_issue(queue, &sio_list);
3043                         mutex_enter(q_lock);
3044
3045                         if (suspended)
3046                                 break;
3047                 }
3048
3049                 /* update statistics for debugging purposes */
3050                 scan_io_queues_update_seg_stats(queue, seg_start, seg_end);
3051
3052                 if (suspended)
3053                         break;
3054         }
3055
3056         /*
3057          * If we were suspended in the middle of processing,
3058          * requeue any unfinished sios and exit.
3059          */
3060         while ((sio = list_head(&sio_list)) != NULL) {
3061                 list_remove(&sio_list, sio);
3062                 scan_io_queue_insert_impl(queue, sio);
3063         }
3064
3065         mutex_exit(q_lock);
3066         list_destroy(&sio_list);
3067 }
3068
3069 /*
3070  * Performs an emptying run on all scan queues in the pool. This just
3071  * punches out one thread per top-level vdev, each of which processes
3072  * only that vdev's scan queue. We can parallelize the I/O here because
3073  * we know that each queue's I/Os only affect its own top-level vdev.
3074  *
3075  * This function waits for the queue runs to complete, and must be
3076  * called from dsl_scan_sync (or in general, syncing context).
3077  */
3078 static void
3079 scan_io_queues_run(dsl_scan_t *scn)
3080 {
3081         spa_t *spa = scn->scn_dp->dp_spa;
3082
3083         ASSERT(scn->scn_is_sorted);
3084         ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
3085
3086         if (scn->scn_bytes_pending == 0)
3087                 return;
3088
3089         if (scn->scn_taskq == NULL) {
3090                 int nthreads = spa->spa_root_vdev->vdev_children;
3091
3092                 /*
3093                  * We need to make this taskq *always* execute as many
3094                  * threads in parallel as we have top-level vdevs and no
3095                  * less, otherwise strange serialization of the calls to
3096                  * scan_io_queues_run_one can occur during spa_sync runs
3097                  * and that significantly impacts performance.
3098                  */
3099                 scn->scn_taskq = taskq_create("dsl_scan_iss", nthreads,
3100                     minclsyspri, nthreads, nthreads, TASKQ_PREPOPULATE);
3101         }
3102
3103         for (uint64_t i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
3104                 vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
3105
3106                 mutex_enter(&vd->vdev_scan_io_queue_lock);
3107                 if (vd->vdev_scan_io_queue != NULL) {
3108                         VERIFY(taskq_dispatch(scn->scn_taskq,
3109                             scan_io_queues_run_one, vd->vdev_scan_io_queue,
3110                             TQ_SLEEP) != TASKQID_INVALID);
3111                 }
3112                 mutex_exit(&vd->vdev_scan_io_queue_lock);
3113         }
3114
3115         /*
3116          * Wait for the queues to finish issuing their IOs for this run
3117          * before we return. There may still be IOs in flight at this
3118          * point.
3119          */
3120         taskq_wait(scn->scn_taskq);
3121 }
3122
3123 static boolean_t
3124 dsl_scan_async_block_should_pause(dsl_scan_t *scn)
3125 {
3126         uint64_t elapsed_nanosecs;
3127
3128         if (zfs_recover)
3129                 return (B_FALSE);
3130
3131         if (zfs_async_block_max_blocks != 0 &&
3132             scn->scn_visited_this_txg >= zfs_async_block_max_blocks) {
3133                 return (B_TRUE);
3134         }
3135
3136         elapsed_nanosecs = gethrtime() - scn->scn_sync_start_time;
3137         return (elapsed_nanosecs / NANOSEC > zfs_txg_timeout ||
3138             (NSEC2MSEC(elapsed_nanosecs) > scn->scn_async_block_min_time_ms &&
3139             txg_sync_waiting(scn->scn_dp)) ||
3140             spa_shutting_down(scn->scn_dp->dp_spa));
3141 }
3142
3143 static int
3144 dsl_scan_free_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
3145 {
3146         dsl_scan_t *scn = arg;
3147
3148         if (!scn->scn_is_bptree ||
3149             (BP_GET_LEVEL(bp) == 0 && BP_GET_TYPE(bp) != DMU_OT_OBJSET)) {
3150                 if (dsl_scan_async_block_should_pause(scn))
3151                         return (SET_ERROR(ERESTART));
3152         }
3153
3154         zio_nowait(zio_free_sync(scn->scn_zio_root, scn->scn_dp->dp_spa,
3155             dmu_tx_get_txg(tx), bp, 0));
3156         dsl_dir_diduse_space(tx->tx_pool->dp_free_dir, DD_USED_HEAD,
3157             -bp_get_dsize_sync(scn->scn_dp->dp_spa, bp),
3158             -BP_GET_PSIZE(bp), -BP_GET_UCSIZE(bp), tx);
3159         scn->scn_visited_this_txg++;
3160         return (0);
3161 }
3162
3163 static void
3164 dsl_scan_update_stats(dsl_scan_t *scn)
3165 {
3166         spa_t *spa = scn->scn_dp->dp_spa;
3167         uint64_t i;
3168         uint64_t seg_size_total = 0, zio_size_total = 0;
3169         uint64_t seg_count_total = 0, zio_count_total = 0;
3170
3171         for (i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
3172                 vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
3173                 dsl_scan_io_queue_t *queue = vd->vdev_scan_io_queue;
3174
3175                 if (queue == NULL)
3176                         continue;
3177
3178                 seg_size_total += queue->q_total_seg_size_this_txg;
3179                 zio_size_total += queue->q_total_zio_size_this_txg;
3180                 seg_count_total += queue->q_segs_this_txg;
3181                 zio_count_total += queue->q_zios_this_txg;
3182         }
3183
3184         if (seg_count_total == 0 || zio_count_total == 0) {
3185                 scn->scn_avg_seg_size_this_txg = 0;
3186                 scn->scn_avg_zio_size_this_txg = 0;
3187                 scn->scn_segs_this_txg = 0;
3188                 scn->scn_zios_this_txg = 0;
3189                 return;
3190         }
3191
3192         scn->scn_avg_seg_size_this_txg = seg_size_total / seg_count_total;
3193         scn->scn_avg_zio_size_this_txg = zio_size_total / zio_count_total;
3194         scn->scn_segs_this_txg = seg_count_total;
3195         scn->scn_zios_this_txg = zio_count_total;
3196 }
3197
3198 static int
3199 bpobj_dsl_scan_free_block_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,
3200     dmu_tx_t *tx)
3201 {
3202         ASSERT(!bp_freed);
3203         return (dsl_scan_free_block_cb(arg, bp, tx));
3204 }
3205
3206 static int
3207 dsl_scan_obsolete_block_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,
3208     dmu_tx_t *tx)
3209 {
3210         ASSERT(!bp_freed);
3211         dsl_scan_t *scn = arg;
3212         const dva_t *dva = &bp->blk_dva[0];
3213
3214         if (dsl_scan_async_block_should_pause(scn))
3215                 return (SET_ERROR(ERESTART));
3216
3217         spa_vdev_indirect_mark_obsolete(scn->scn_dp->dp_spa,
3218             DVA_GET_VDEV(dva), DVA_GET_OFFSET(dva),
3219             DVA_GET_ASIZE(dva), tx);
3220         scn->scn_visited_this_txg++;
3221         return (0);
3222 }
3223
3224 boolean_t
3225 dsl_scan_active(dsl_scan_t *scn)
3226 {
3227         spa_t *spa = scn->scn_dp->dp_spa;
3228         uint64_t used = 0, comp, uncomp;
3229         boolean_t clones_left;
3230
3231         if (spa->spa_load_state != SPA_LOAD_NONE)
3232                 return (B_FALSE);
3233         if (spa_shutting_down(spa))
3234                 return (B_FALSE);
3235         if ((dsl_scan_is_running(scn) && !dsl_scan_is_paused_scrub(scn)) ||
3236             (scn->scn_async_destroying && !scn->scn_async_stalled))
3237                 return (B_TRUE);
3238
3239         if (spa_version(scn->scn_dp->dp_spa) >= SPA_VERSION_DEADLISTS) {
3240                 (void) bpobj_space(&scn->scn_dp->dp_free_bpobj,
3241                     &used, &comp, &uncomp);
3242         }
3243         clones_left = spa_livelist_delete_check(spa);
3244         return ((used != 0) || (clones_left));
3245 }
3246
3247 static boolean_t
3248 dsl_scan_check_deferred(vdev_t *vd)
3249 {
3250         boolean_t need_resilver = B_FALSE;
3251
3252         for (int c = 0; c < vd->vdev_children; c++) {
3253                 need_resilver |=
3254                     dsl_scan_check_deferred(vd->vdev_child[c]);
3255         }
3256
3257         if (!vdev_is_concrete(vd) || vd->vdev_aux ||
3258             !vd->vdev_ops->vdev_op_leaf)
3259                 return (need_resilver);
3260
3261         if (!vd->vdev_resilver_deferred)
3262                 need_resilver = B_TRUE;
3263
3264         return (need_resilver);
3265 }
3266
3267 static boolean_t
3268 dsl_scan_need_resilver(spa_t *spa, const dva_t *dva, size_t psize,
3269     uint64_t phys_birth)
3270 {
3271         vdev_t *vd;
3272
3273         vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));
3274
3275         if (vd->vdev_ops == &vdev_indirect_ops) {
3276                 /*
3277                  * The indirect vdev can point to multiple
3278                  * vdevs.  For simplicity, always create
3279                  * the resilver zio_t. zio_vdev_io_start()
3280                  * will bypass the child resilver i/o's if
3281                  * they are on vdevs that don't have DTL's.
3282                  */
3283                 return (B_TRUE);
3284         }
3285
3286         if (DVA_GET_GANG(dva)) {
3287                 /*
3288                  * Gang members may be spread across multiple
3289                  * vdevs, so the best estimate we have is the
3290                  * scrub range, which has already been checked.
3291                  * XXX -- it would be better to change our
3292                  * allocation policy to ensure that all
3293                  * gang members reside on the same vdev.
3294                  */
3295                 return (B_TRUE);
3296         }
3297
3298         /*
3299          * Check if the txg falls within the range which must be
3300          * resilvered.  DVAs outside this range can always be skipped.
3301          */
3302         if (!vdev_dtl_contains(vd, DTL_PARTIAL, phys_birth, 1))
3303                 return (B_FALSE);
3304
3305         /*
3306          * Check if the top-level vdev must resilver this offset.
3307          * When the offset does not intersect with a dirty leaf DTL
3308          * then it may be possible to skip the resilver IO.  The psize
3309          * is provided instead of asize to simplify the check for RAIDZ.
3310          */
3311         if (!vdev_dtl_need_resilver(vd, DVA_GET_OFFSET(dva), psize))
3312                 return (B_FALSE);
3313
3314         /*
3315          * Check that this top-level vdev has a device under it which
3316          * is resilvering and is not deferred.
3317          */
3318         if (!dsl_scan_check_deferred(vd))
3319                 return (B_FALSE);
3320
3321         return (B_TRUE);
3322 }
3323
3324 static int
3325 dsl_process_async_destroys(dsl_pool_t *dp, dmu_tx_t *tx)
3326 {
3327         dsl_scan_t *scn = dp->dp_scan;
3328         spa_t *spa = dp->dp_spa;
3329         int err = 0;
3330
3331         if (spa_suspend_async_destroy(spa))
3332                 return (0);
3333
3334         if (zfs_free_bpobj_enabled &&
3335             spa_version(spa) >= SPA_VERSION_DEADLISTS) {
3336                 scn->scn_is_bptree = B_FALSE;
3337                 scn->scn_async_block_min_time_ms = zfs_free_min_time_ms;
3338                 scn->scn_zio_root = zio_root(spa, NULL,
3339                     NULL, ZIO_FLAG_MUSTSUCCEED);
3340                 err = bpobj_iterate(&dp->dp_free_bpobj,
3341                     bpobj_dsl_scan_free_block_cb, scn, tx);
3342                 VERIFY0(zio_wait(scn->scn_zio_root));
3343                 scn->scn_zio_root = NULL;
3344
3345                 if (err != 0 && err != ERESTART)
3346                         zfs_panic_recover("error %u from bpobj_iterate()", err);
3347         }
3348
3349         if (err == 0 && spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) {
3350                 ASSERT(scn->scn_async_destroying);
3351                 scn->scn_is_bptree = B_TRUE;
3352                 scn->scn_zio_root = zio_root(spa, NULL,
3353                     NULL, ZIO_FLAG_MUSTSUCCEED);
3354                 err = bptree_iterate(dp->dp_meta_objset,
3355                     dp->dp_bptree_obj, B_TRUE, dsl_scan_free_block_cb, scn, tx);
3356                 VERIFY0(zio_wait(scn->scn_zio_root));
3357                 scn->scn_zio_root = NULL;
3358
3359                 if (err == EIO || err == ECKSUM) {
3360                         err = 0;
3361                 } else if (err != 0 && err != ERESTART) {
3362                         zfs_panic_recover("error %u from "
3363                             "traverse_dataset_destroyed()", err);
3364                 }
3365
3366                 if (bptree_is_empty(dp->dp_meta_objset, dp->dp_bptree_obj)) {
3367                         /* finished; deactivate async destroy feature */
3368                         spa_feature_decr(spa, SPA_FEATURE_ASYNC_DESTROY, tx);
3369                         ASSERT(!spa_feature_is_active(spa,
3370                             SPA_FEATURE_ASYNC_DESTROY));
3371                         VERIFY0(zap_remove(dp->dp_meta_objset,
3372                             DMU_POOL_DIRECTORY_OBJECT,
3373                             DMU_POOL_BPTREE_OBJ, tx));
3374                         VERIFY0(bptree_free(dp->dp_meta_objset,
3375                             dp->dp_bptree_obj, tx));
3376                         dp->dp_bptree_obj = 0;
3377                         scn->scn_async_destroying = B_FALSE;
3378                         scn->scn_async_stalled = B_FALSE;
3379                 } else {
3380                         /*
3381                          * If we didn't make progress, mark the async
3382                          * destroy as stalled, so that we will not initiate
3383                          * a spa_sync() on its behalf.  Note that we only
3384                          * check this if we are not finished, because if the
3385                          * bptree had no blocks for us to visit, we can
3386                          * finish without "making progress".
3387                          */
3388                         scn->scn_async_stalled =
3389                             (scn->scn_visited_this_txg == 0);
3390                 }
3391         }
3392         if (scn->scn_visited_this_txg) {
3393                 zfs_dbgmsg("freed %llu blocks in %llums from "
3394                     "free_bpobj/bptree txg %llu; err=%u",
3395                     (longlong_t)scn->scn_visited_this_txg,
3396                     (longlong_t)
3397                     NSEC2MSEC(gethrtime() - scn->scn_sync_start_time),
3398                     (longlong_t)tx->tx_txg, err);
3399                 scn->scn_visited_this_txg = 0;
3400
3401                 /*
3402                  * Write out changes to the DDT that may be required as a
3403                  * result of the blocks freed.  This ensures that the DDT
3404                  * is clean when a scrub/resilver runs.
3405                  */
3406                 ddt_sync(spa, tx->tx_txg);
3407         }
3408         if (err != 0)
3409                 return (err);
3410         if (dp->dp_free_dir != NULL && !scn->scn_async_destroying &&
3411             zfs_free_leak_on_eio &&
3412             (dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes != 0 ||
3413             dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes != 0 ||
3414             dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes != 0)) {
3415                 /*
3416                  * We have finished background destroying, but there is still
3417                  * some space left in the dp_free_dir. Transfer this leaked
3418                  * space to the dp_leak_dir.
3419                  */
3420                 if (dp->dp_leak_dir == NULL) {
3421                         rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
3422                         (void) dsl_dir_create_sync(dp, dp->dp_root_dir,
3423                             LEAK_DIR_NAME, tx);
3424                         VERIFY0(dsl_pool_open_special_dir(dp,
3425                             LEAK_DIR_NAME, &dp->dp_leak_dir));
3426                         rrw_exit(&dp->dp_config_rwlock, FTAG);
3427                 }
3428                 dsl_dir_diduse_space(dp->dp_leak_dir, DD_USED_HEAD,
3429                     dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes,
3430                     dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes,
3431                     dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes, tx);
3432                 dsl_dir_diduse_space(dp->dp_free_dir, DD_USED_HEAD,
3433                     -dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes,
3434                     -dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes,
3435                     -dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes, tx);
3436         }
3437
3438         if (dp->dp_free_dir != NULL && !scn->scn_async_destroying &&
3439             !spa_livelist_delete_check(spa)) {
3440                 /* finished; verify that space accounting went to zero */
3441                 ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes);
3442                 ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes);
3443                 ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes);
3444         }
3445
3446         spa_notify_waiters(spa);
3447
3448         EQUIV(bpobj_is_open(&dp->dp_obsolete_bpobj),
3449             0 == zap_contains(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3450             DMU_POOL_OBSOLETE_BPOBJ));
3451         if (err == 0 && bpobj_is_open(&dp->dp_obsolete_bpobj)) {
3452                 ASSERT(spa_feature_is_active(dp->dp_spa,
3453                     SPA_FEATURE_OBSOLETE_COUNTS));
3454
3455                 scn->scn_is_bptree = B_FALSE;
3456                 scn->scn_async_block_min_time_ms = zfs_obsolete_min_time_ms;
3457                 err = bpobj_iterate(&dp->dp_obsolete_bpobj,
3458                     dsl_scan_obsolete_block_cb, scn, tx);
3459                 if (err != 0 && err != ERESTART)
3460                         zfs_panic_recover("error %u from bpobj_iterate()", err);
3461
3462                 if (bpobj_is_empty(&dp->dp_obsolete_bpobj))
3463                         dsl_pool_destroy_obsolete_bpobj(dp, tx);
3464         }
3465         return (0);
3466 }
3467
3468 /*
3469  * This is the primary entry point for scans that is called from syncing
3470  * context. Scans must happen entirely during syncing context so that we
3471  * can guarantee that blocks we are currently scanning will not change out
3472  * from under us. While a scan is active, this function controls how quickly
3473  * transaction groups proceed, instead of the normal handling provided by
3474  * txg_sync_thread().
3475  */
3476 void
3477 dsl_scan_sync(dsl_pool_t *dp, dmu_tx_t *tx)
3478 {
3479         int err = 0;
3480         dsl_scan_t *scn = dp->dp_scan;
3481         spa_t *spa = dp->dp_spa;
3482         state_sync_type_t sync_type = SYNC_OPTIONAL;
3483
3484         if (spa->spa_resilver_deferred &&
3485             !spa_feature_is_active(dp->dp_spa, SPA_FEATURE_RESILVER_DEFER))
3486                 spa_feature_incr(spa, SPA_FEATURE_RESILVER_DEFER, tx);
3487
3488         /*
3489          * Check for scn_restart_txg before checking spa_load_state, so
3490          * that we can restart an old-style scan while the pool is being
3491          * imported (see dsl_scan_init). We also restart scans if there
3492          * is a deferred resilver and the user has manually disabled
3493          * deferred resilvers via the tunable.
3494          */
3495         if (dsl_scan_restarting(scn, tx) ||
3496             (spa->spa_resilver_deferred && zfs_resilver_disable_defer)) {
3497                 pool_scan_func_t func = POOL_SCAN_SCRUB;
3498                 dsl_scan_done(scn, B_FALSE, tx);
3499                 if (vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL))
3500                         func = POOL_SCAN_RESILVER;
3501                 zfs_dbgmsg("restarting scan func=%u txg=%llu",
3502                     func, (longlong_t)tx->tx_txg);
3503                 dsl_scan_setup_sync(&func, tx);
3504         }
3505
3506         /*
3507          * Only process scans in sync pass 1.
3508          */
3509         if (spa_sync_pass(spa) > 1)
3510                 return;
3511
3512         /*
3513          * If the spa is shutting down, then stop scanning. This will
3514          * ensure that the scan does not dirty any new data during the
3515          * shutdown phase.
3516          */
3517         if (spa_shutting_down(spa))
3518                 return;
3519
3520         /*
3521          * If the scan is inactive due to a stalled async destroy, try again.
3522          */
3523         if (!scn->scn_async_stalled && !dsl_scan_active(scn))
3524                 return;
3525
3526         /* reset scan statistics */
3527         scn->scn_visited_this_txg = 0;
3528         scn->scn_holes_this_txg = 0;
3529         scn->scn_lt_min_this_txg = 0;
3530         scn->scn_gt_max_this_txg = 0;
3531         scn->scn_ddt_contained_this_txg = 0;
3532         scn->scn_objsets_visited_this_txg = 0;
3533         scn->scn_avg_seg_size_this_txg = 0;
3534         scn->scn_segs_this_txg = 0;
3535         scn->scn_avg_zio_size_this_txg = 0;
3536         scn->scn_zios_this_txg = 0;
3537         scn->scn_suspending = B_FALSE;
3538         scn->scn_sync_start_time = gethrtime();
3539         spa->spa_scrub_active = B_TRUE;
3540
3541         /*
3542          * First process the async destroys.  If we suspend, don't do
3543          * any scrubbing or resilvering.  This ensures that there are no
3544          * async destroys while we are scanning, so the scan code doesn't
3545          * have to worry about traversing it.  It is also faster to free the
3546          * blocks than to scrub them.
3547          */
3548         err = dsl_process_async_destroys(dp, tx);
3549         if (err != 0)
3550                 return;
3551
3552         if (!dsl_scan_is_running(scn) || dsl_scan_is_paused_scrub(scn))
3553                 return;
3554
3555         /*
3556          * Wait a few txgs after importing to begin scanning so that
3557          * we can get the pool imported quickly.
3558          */
3559         if (spa->spa_syncing_txg < spa->spa_first_txg + SCAN_IMPORT_WAIT_TXGS)
3560                 return;
3561
3562         /*
3563          * zfs_scan_suspend_progress can be set to disable scan progress.
3564          * We don't want to spin the txg_sync thread, so we add a delay
3565          * here to simulate the time spent doing a scan. This is mostly
3566          * useful for testing and debugging.
3567          */
3568         if (zfs_scan_suspend_progress) {
3569                 uint64_t scan_time_ns = gethrtime() - scn->scn_sync_start_time;
3570                 int mintime = (scn->scn_phys.scn_func == POOL_SCAN_RESILVER) ?
3571                     zfs_resilver_min_time_ms : zfs_scrub_min_time_ms;
3572
3573                 while (zfs_scan_suspend_progress &&
3574                     !txg_sync_waiting(scn->scn_dp) &&
3575                     !spa_shutting_down(scn->scn_dp->dp_spa) &&
3576                     NSEC2MSEC(scan_time_ns) < mintime) {
3577                         delay(hz);
3578                         scan_time_ns = gethrtime() - scn->scn_sync_start_time;
3579                 }
3580                 return;
3581         }
3582
3583         /*
3584          * It is possible to switch from unsorted to sorted at any time,
3585          * but afterwards the scan will remain sorted unless reloaded from
3586          * a checkpoint after a reboot.
3587          */
3588         if (!zfs_scan_legacy) {
3589                 scn->scn_is_sorted = B_TRUE;
3590                 if (scn->scn_last_checkpoint == 0)
3591                         scn->scn_last_checkpoint = ddi_get_lbolt();
3592         }
3593
3594         /*
3595          * For sorted scans, determine what kind of work we will be doing
3596          * this txg based on our memory limitations and whether or not we
3597          * need to perform a checkpoint.
3598          */
3599         if (scn->scn_is_sorted) {
3600                 /*
3601                  * If we are over our checkpoint interval, set scn_clearing
3602                  * so that we can begin checkpointing immediately. The
3603                  * checkpoint allows us to save a consistent bookmark
3604                  * representing how much data we have scrubbed so far.
3605                  * Otherwise, use the memory limit to determine if we should
3606                  * scan for metadata or start issue scrub IOs. We accumulate
3607                  * metadata until we hit our hard memory limit at which point
3608                  * we issue scrub IOs until we are at our soft memory limit.
3609                  */
3610                 if (scn->scn_checkpointing ||
3611                     ddi_get_lbolt() - scn->scn_last_checkpoint >
3612                     SEC_TO_TICK(zfs_scan_checkpoint_intval)) {
3613                         if (!scn->scn_checkpointing)
3614                                 zfs_dbgmsg("begin scan checkpoint");
3615
3616                         scn->scn_checkpointing = B_TRUE;
3617                         scn->scn_clearing = B_TRUE;
3618                 } else {
3619                         boolean_t should_clear = dsl_scan_should_clear(scn);
3620                         if (should_clear && !scn->scn_clearing) {
3621                                 zfs_dbgmsg("begin scan clearing");
3622                                 scn->scn_clearing = B_TRUE;
3623                         } else if (!should_clear && scn->scn_clearing) {
3624                                 zfs_dbgmsg("finish scan clearing");
3625                                 scn->scn_clearing = B_FALSE;
3626                         }
3627                 }
3628         } else {
3629                 ASSERT0(scn->scn_checkpointing);
3630                 ASSERT0(scn->scn_clearing);
3631         }
3632
3633         if (!scn->scn_clearing && scn->scn_done_txg == 0) {
3634                 /* Need to scan metadata for more blocks to scrub */
3635                 dsl_scan_phys_t *scnp = &scn->scn_phys;
3636                 taskqid_t prefetch_tqid;
3637                 uint64_t bytes_per_leaf = zfs_scan_vdev_limit;
3638                 uint64_t nr_leaves = dsl_scan_count_leaves(spa->spa_root_vdev);
3639
3640                 /*
3641                  * Recalculate the max number of in-flight bytes for pool-wide
3642                  * scanning operations (minimum 1MB). Limits for the issuing
3643                  * phase are done per top-level vdev and are handled separately.
3644                  */
3645                 scn->scn_maxinflight_bytes =
3646                     MAX(nr_leaves * bytes_per_leaf, 1ULL << 20);
3647
3648                 if (scnp->scn_ddt_bookmark.ddb_class <=
3649                     scnp->scn_ddt_class_max) {
3650                         ASSERT(ZB_IS_ZERO(&scnp->scn_bookmark));
3651                         zfs_dbgmsg("doing scan sync txg %llu; "
3652                             "ddt bm=%llu/%llu/%llu/%llx",
3653                             (longlong_t)tx->tx_txg,
3654                             (longlong_t)scnp->scn_ddt_bookmark.ddb_class,
3655                             (longlong_t)scnp->scn_ddt_bookmark.ddb_type,
3656                             (longlong_t)scnp->scn_ddt_bookmark.ddb_checksum,
3657                             (longlong_t)scnp->scn_ddt_bookmark.ddb_cursor);
3658                 } else {
3659                         zfs_dbgmsg("doing scan sync txg %llu; "
3660                             "bm=%llu/%llu/%llu/%llu",
3661                             (longlong_t)tx->tx_txg,
3662                             (longlong_t)scnp->scn_bookmark.zb_objset,
3663                             (longlong_t)scnp->scn_bookmark.zb_object,
3664                             (longlong_t)scnp->scn_bookmark.zb_level,
3665                             (longlong_t)scnp->scn_bookmark.zb_blkid);
3666                 }
3667
3668                 scn->scn_zio_root = zio_root(dp->dp_spa, NULL,
3669                     NULL, ZIO_FLAG_CANFAIL);
3670
3671                 scn->scn_prefetch_stop = B_FALSE;
3672                 prefetch_tqid = taskq_dispatch(dp->dp_sync_taskq,
3673                     dsl_scan_prefetch_thread, scn, TQ_SLEEP);
3674                 ASSERT(prefetch_tqid != TASKQID_INVALID);
3675
3676                 dsl_pool_config_enter(dp, FTAG);
3677                 dsl_scan_visit(scn, tx);
3678                 dsl_pool_config_exit(dp, FTAG);
3679
3680                 mutex_enter(&dp->dp_spa->spa_scrub_lock);
3681                 scn->scn_prefetch_stop = B_TRUE;
3682                 cv_broadcast(&spa->spa_scrub_io_cv);
3683                 mutex_exit(&dp->dp_spa->spa_scrub_lock);
3684
3685                 taskq_wait_id(dp->dp_sync_taskq, prefetch_tqid);
3686                 (void) zio_wait(scn->scn_zio_root);
3687                 scn->scn_zio_root = NULL;
3688
3689                 zfs_dbgmsg("scan visited %llu blocks in %llums "
3690                     "(%llu os's, %llu holes, %llu < mintxg, "
3691                     "%llu in ddt, %llu > maxtxg)",
3692                     (longlong_t)scn->scn_visited_this_txg,
3693                     (longlong_t)NSEC2MSEC(gethrtime() -
3694                     scn->scn_sync_start_time),
3695                     (longlong_t)scn->scn_objsets_visited_this_txg,
3696                     (longlong_t)scn->scn_holes_this_txg,
3697                     (longlong_t)scn->scn_lt_min_this_txg,
3698                     (longlong_t)scn->scn_ddt_contained_this_txg,
3699                     (longlong_t)scn->scn_gt_max_this_txg);
3700
3701                 if (!scn->scn_suspending) {
3702                         ASSERT0(avl_numnodes(&scn->scn_queue));
3703                         scn->scn_done_txg = tx->tx_txg + 1;
3704                         if (scn->scn_is_sorted) {
3705                                 scn->scn_checkpointing = B_TRUE;
3706                                 scn->scn_clearing = B_TRUE;
3707                         }
3708                         zfs_dbgmsg("scan complete txg %llu",
3709                             (longlong_t)tx->tx_txg);
3710                 }
3711         } else if (scn->scn_is_sorted && scn->scn_bytes_pending != 0) {
3712                 ASSERT(scn->scn_clearing);
3713
3714                 /* need to issue scrubbing IOs from per-vdev queues */
3715                 scn->scn_zio_root = zio_root(dp->dp_spa, NULL,
3716                     NULL, ZIO_FLAG_CANFAIL);
3717                 scan_io_queues_run(scn);
3718                 (void) zio_wait(scn->scn_zio_root);
3719                 scn->scn_zio_root = NULL;
3720
3721                 /* calculate and dprintf the current memory usage */
3722                 (void) dsl_scan_should_clear(scn);
3723                 dsl_scan_update_stats(scn);
3724
3725                 zfs_dbgmsg("scan issued %llu blocks (%llu segs) in %llums "
3726                     "(avg_block_size = %llu, avg_seg_size = %llu)",
3727                     (longlong_t)scn->scn_zios_this_txg,
3728                     (longlong_t)scn->scn_segs_this_txg,
3729                     (longlong_t)NSEC2MSEC(gethrtime() -
3730                     scn->scn_sync_start_time),
3731                     (longlong_t)scn->scn_avg_zio_size_this_txg,
3732                     (longlong_t)scn->scn_avg_seg_size_this_txg);
3733         } else if (scn->scn_done_txg != 0 && scn->scn_done_txg <= tx->tx_txg) {
3734                 /* Finished with everything. Mark the scrub as complete */
3735                 zfs_dbgmsg("scan issuing complete txg %llu",
3736                     (longlong_t)tx->tx_txg);
3737                 ASSERT3U(scn->scn_done_txg, !=, 0);
3738                 ASSERT0(spa->spa_scrub_inflight);
3739                 ASSERT0(scn->scn_bytes_pending);
3740                 dsl_scan_done(scn, B_TRUE, tx);
3741                 sync_type = SYNC_MANDATORY;
3742         }
3743
3744         dsl_scan_sync_state(scn, tx, sync_type);
3745 }
3746
3747 static void
3748 count_block(dsl_scan_t *scn, zfs_all_blkstats_t *zab, const blkptr_t *bp)
3749 {
3750         int i;
3751
3752         /*
3753          * Don't count embedded bp's, since we already did the work of
3754          * scanning these when we scanned the containing block.
3755          */
3756         if (BP_IS_EMBEDDED(bp))
3757                 return;
3758
3759         /*
3760          * Update the spa's stats on how many bytes we have issued.
3761          * Sequential scrubs create a zio for each DVA of the bp. Each
3762          * of these will include all DVAs for repair purposes, but the
3763          * zio code will only try the first one unless there is an issue.
3764          * Therefore, we should only count the first DVA for these IOs.
3765          */
3766         if (scn->scn_is_sorted) {
3767                 atomic_add_64(&scn->scn_dp->dp_spa->spa_scan_pass_issued,
3768                     DVA_GET_ASIZE(&bp->blk_dva[0]));
3769         } else {
3770                 spa_t *spa = scn->scn_dp->dp_spa;
3771
3772                 for (i = 0; i < BP_GET_NDVAS(bp); i++) {
3773                         atomic_add_64(&spa->spa_scan_pass_issued,
3774                             DVA_GET_ASIZE(&bp->blk_dva[i]));
3775                 }
3776         }
3777
3778         /*
3779          * If we resume after a reboot, zab will be NULL; don't record
3780          * incomplete stats in that case.
3781          */
3782         if (zab == NULL)
3783                 return;
3784
3785         mutex_enter(&zab->zab_lock);
3786
3787         for (i = 0; i < 4; i++) {
3788                 int l = (i < 2) ? BP_GET_LEVEL(bp) : DN_MAX_LEVELS;
3789                 int t = (i & 1) ? BP_GET_TYPE(bp) : DMU_OT_TOTAL;
3790
3791                 if (t & DMU_OT_NEWTYPE)
3792                         t = DMU_OT_OTHER;
3793                 zfs_blkstat_t *zb = &zab->zab_type[l][t];
3794                 int equal;
3795
3796                 zb->zb_count++;
3797                 zb->zb_asize += BP_GET_ASIZE(bp);
3798                 zb->zb_lsize += BP_GET_LSIZE(bp);
3799                 zb->zb_psize += BP_GET_PSIZE(bp);
3800                 zb->zb_gangs += BP_COUNT_GANG(bp);
3801
3802                 switch (BP_GET_NDVAS(bp)) {
3803                 case 2:
3804                         if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3805                             DVA_GET_VDEV(&bp->blk_dva[1]))
3806                                 zb->zb_ditto_2_of_2_samevdev++;
3807                         break;
3808                 case 3:
3809                         equal = (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3810                             DVA_GET_VDEV(&bp->blk_dva[1])) +
3811                             (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3812                             DVA_GET_VDEV(&bp->blk_dva[2])) +
3813                             (DVA_GET_VDEV(&bp->blk_dva[1]) ==
3814                             DVA_GET_VDEV(&bp->blk_dva[2]));
3815                         if (equal == 1)
3816                                 zb->zb_ditto_2_of_3_samevdev++;
3817                         else if (equal == 3)
3818                                 zb->zb_ditto_3_of_3_samevdev++;
3819                         break;
3820                 }
3821         }
3822
3823         mutex_exit(&zab->zab_lock);
3824 }
3825
3826 static void
3827 scan_io_queue_insert_impl(dsl_scan_io_queue_t *queue, scan_io_t *sio)
3828 {
3829         avl_index_t idx;
3830         int64_t asize = SIO_GET_ASIZE(sio);
3831         dsl_scan_t *scn = queue->q_scn;
3832
3833         ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
3834
3835         if (avl_find(&queue->q_sios_by_addr, sio, &idx) != NULL) {
3836                 /* block is already scheduled for reading */
3837                 atomic_add_64(&scn->scn_bytes_pending, -asize);
3838                 sio_free(sio);
3839                 return;
3840         }
3841         avl_insert(&queue->q_sios_by_addr, sio, idx);
3842         queue->q_sio_memused += SIO_GET_MUSED(sio);
3843         range_tree_add(queue->q_exts_by_addr, SIO_GET_OFFSET(sio), asize);
3844 }
3845
3846 /*
3847  * Given all the info we got from our metadata scanning process, we
3848  * construct a scan_io_t and insert it into the scan sorting queue. The
3849  * I/O must already be suitable for us to process. This is controlled
3850  * by dsl_scan_enqueue().
3851  */
3852 static void
3853 scan_io_queue_insert(dsl_scan_io_queue_t *queue, const blkptr_t *bp, int dva_i,
3854     int zio_flags, const zbookmark_phys_t *zb)
3855 {
3856         dsl_scan_t *scn = queue->q_scn;
3857         scan_io_t *sio = sio_alloc(BP_GET_NDVAS(bp));
3858
3859         ASSERT0(BP_IS_GANG(bp));
3860         ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
3861
3862         bp2sio(bp, sio, dva_i);
3863         sio->sio_flags = zio_flags;
3864         sio->sio_zb = *zb;
3865
3866         /*
3867          * Increment the bytes pending counter now so that we can't
3868          * get an integer underflow in case the worker processes the
3869          * zio before we get to incrementing this counter.
3870          */
3871         atomic_add_64(&scn->scn_bytes_pending, SIO_GET_ASIZE(sio));
3872
3873         scan_io_queue_insert_impl(queue, sio);
3874 }
3875
3876 /*
3877  * Given a set of I/O parameters as discovered by the metadata traversal
3878  * process, attempts to place the I/O into the sorted queues (if allowed),
3879  * or immediately executes the I/O.
3880  */
3881 static void
3882 dsl_scan_enqueue(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags,
3883     const zbookmark_phys_t *zb)
3884 {
3885         spa_t *spa = dp->dp_spa;
3886
3887         ASSERT(!BP_IS_EMBEDDED(bp));
3888
3889         /*
3890          * Gang blocks are hard to issue sequentially, so we just issue them
3891          * here immediately instead of queuing them.
3892          */
3893         if (!dp->dp_scan->scn_is_sorted || BP_IS_GANG(bp)) {
3894                 scan_exec_io(dp, bp, zio_flags, zb, NULL);
3895                 return;
3896         }
3897
3898         for (int i = 0; i < BP_GET_NDVAS(bp); i++) {
3899                 dva_t dva;
3900                 vdev_t *vdev;
3901
3902                 dva = bp->blk_dva[i];
3903                 vdev = vdev_lookup_top(spa, DVA_GET_VDEV(&dva));
3904                 ASSERT(vdev != NULL);
3905
3906                 mutex_enter(&vdev->vdev_scan_io_queue_lock);
3907                 if (vdev->vdev_scan_io_queue == NULL)
3908                         vdev->vdev_scan_io_queue = scan_io_queue_create(vdev);
3909                 ASSERT(dp->dp_scan != NULL);
3910                 scan_io_queue_insert(vdev->vdev_scan_io_queue, bp,
3911                     i, zio_flags, zb);
3912                 mutex_exit(&vdev->vdev_scan_io_queue_lock);
3913         }
3914 }
3915
3916 static int
3917 dsl_scan_scrub_cb(dsl_pool_t *dp,
3918     const blkptr_t *bp, const zbookmark_phys_t *zb)
3919 {
3920         dsl_scan_t *scn = dp->dp_scan;
3921         spa_t *spa = dp->dp_spa;
3922         uint64_t phys_birth = BP_PHYSICAL_BIRTH(bp);
3923         size_t psize = BP_GET_PSIZE(bp);
3924         boolean_t needs_io = B_FALSE;
3925         int zio_flags = ZIO_FLAG_SCAN_THREAD | ZIO_FLAG_RAW | ZIO_FLAG_CANFAIL;
3926
3927
3928         if (phys_birth <= scn->scn_phys.scn_min_txg ||
3929             phys_birth >= scn->scn_phys.scn_max_txg) {
3930                 count_block(scn, dp->dp_blkstats, bp);
3931                 return (0);
3932         }
3933
3934         /* Embedded BP's have phys_birth==0, so we reject them above. */
3935         ASSERT(!BP_IS_EMBEDDED(bp));
3936
3937         ASSERT(DSL_SCAN_IS_SCRUB_RESILVER(scn));
3938         if (scn->scn_phys.scn_func == POOL_SCAN_SCRUB) {
3939                 zio_flags |= ZIO_FLAG_SCRUB;
3940                 needs_io = B_TRUE;
3941         } else {
3942                 ASSERT3U(scn->scn_phys.scn_func, ==, POOL_SCAN_RESILVER);
3943                 zio_flags |= ZIO_FLAG_RESILVER;
3944                 needs_io = B_FALSE;
3945         }
3946
3947         /* If it's an intent log block, failure is expected. */
3948         if (zb->zb_level == ZB_ZIL_LEVEL)
3949                 zio_flags |= ZIO_FLAG_SPECULATIVE;
3950
3951         for (int d = 0; d < BP_GET_NDVAS(bp); d++) {
3952                 const dva_t *dva = &bp->blk_dva[d];
3953
3954                 /*
3955                  * Keep track of how much data we've examined so that
3956                  * zpool(1M) status can make useful progress reports.
3957                  */
3958                 scn->scn_phys.scn_examined += DVA_GET_ASIZE(dva);
3959                 spa->spa_scan_pass_exam += DVA_GET_ASIZE(dva);
3960
3961                 /* if it's a resilver, this may not be in the target range */
3962                 if (!needs_io)
3963                         needs_io = dsl_scan_need_resilver(spa, dva, psize,
3964                             phys_birth);
3965         }
3966
3967         if (needs_io && !zfs_no_scrub_io) {
3968                 dsl_scan_enqueue(dp, bp, zio_flags, zb);
3969         } else {
3970                 count_block(scn, dp->dp_blkstats, bp);
3971         }
3972
3973         /* do not relocate this block */
3974         return (0);
3975 }
3976
3977 static void
3978 dsl_scan_scrub_done(zio_t *zio)
3979 {
3980         spa_t *spa = zio->io_spa;
3981         blkptr_t *bp = zio->io_bp;
3982         dsl_scan_io_queue_t *queue = zio->io_private;
3983
3984         abd_free(zio->io_abd);
3985
3986         if (queue == NULL) {
3987                 mutex_enter(&spa->spa_scrub_lock);
3988                 ASSERT3U(spa->spa_scrub_inflight, >=, BP_GET_PSIZE(bp));
3989                 spa->spa_scrub_inflight -= BP_GET_PSIZE(bp);
3990                 cv_broadcast(&spa->spa_scrub_io_cv);
3991                 mutex_exit(&spa->spa_scrub_lock);
3992         } else {
3993                 mutex_enter(&queue->q_vd->vdev_scan_io_queue_lock);
3994                 ASSERT3U(queue->q_inflight_bytes, >=, BP_GET_PSIZE(bp));
3995                 queue->q_inflight_bytes -= BP_GET_PSIZE(bp);
3996                 cv_broadcast(&queue->q_zio_cv);
3997                 mutex_exit(&queue->q_vd->vdev_scan_io_queue_lock);
3998         }
3999
4000         if (zio->io_error && (zio->io_error != ECKSUM ||
4001             !(zio->io_flags & ZIO_FLAG_SPECULATIVE))) {
4002                 atomic_inc_64(&spa->spa_dsl_pool->dp_scan->scn_phys.scn_errors);
4003         }
4004 }
4005
4006 /*
4007  * Given a scanning zio's information, executes the zio. The zio need
4008  * not necessarily be only sortable, this function simply executes the
4009  * zio, no matter what it is. The optional queue argument allows the
4010  * caller to specify that they want per top level vdev IO rate limiting
4011  * instead of the legacy global limiting.
4012  */
4013 static void
4014 scan_exec_io(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags,
4015     const zbookmark_phys_t *zb, dsl_scan_io_queue_t *queue)
4016 {
4017         spa_t *spa = dp->dp_spa;
4018         dsl_scan_t *scn = dp->dp_scan;
4019         size_t size = BP_GET_PSIZE(bp);
4020         abd_t *data = abd_alloc_for_io(size, B_FALSE);
4021
4022         ASSERT3U(scn->scn_maxinflight_bytes, >, 0);
4023
4024         if (queue == NULL) {
4025                 mutex_enter(&spa->spa_scrub_lock);
4026                 while (spa->spa_scrub_inflight >= scn->scn_maxinflight_bytes)
4027                         cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
4028                 spa->spa_scrub_inflight += BP_GET_PSIZE(bp);
4029                 mutex_exit(&spa->spa_scrub_lock);
4030         } else {
4031                 kmutex_t *q_lock = &queue->q_vd->vdev_scan_io_queue_lock;
4032
4033                 mutex_enter(q_lock);
4034                 while (queue->q_inflight_bytes >= queue->q_maxinflight_bytes)
4035                         cv_wait(&queue->q_zio_cv, q_lock);
4036                 queue->q_inflight_bytes += BP_GET_PSIZE(bp);
4037                 mutex_exit(q_lock);
4038         }
4039
4040         count_block(scn, dp->dp_blkstats, bp);
4041         zio_nowait(zio_read(scn->scn_zio_root, spa, bp, data, size,
4042             dsl_scan_scrub_done, queue, ZIO_PRIORITY_SCRUB, zio_flags, zb));
4043 }
4044
4045 /*
4046  * This is the primary extent sorting algorithm. We balance two parameters:
4047  * 1) how many bytes of I/O are in an extent
4048  * 2) how well the extent is filled with I/O (as a fraction of its total size)
4049  * Since we allow extents to have gaps between their constituent I/Os, it's
4050  * possible to have a fairly large extent that contains the same amount of
4051  * I/O bytes than a much smaller extent, which just packs the I/O more tightly.
4052  * The algorithm sorts based on a score calculated from the extent's size,
4053  * the relative fill volume (in %) and a "fill weight" parameter that controls
4054  * the split between whether we prefer larger extents or more well populated
4055  * extents:
4056  *
4057  * SCORE = FILL_IN_BYTES + (FILL_IN_PERCENT * FILL_IN_BYTES * FILL_WEIGHT)
4058  *
4059  * Example:
4060  * 1) assume extsz = 64 MiB
4061  * 2) assume fill = 32 MiB (extent is half full)
4062  * 3) assume fill_weight = 3
4063  * 4)   SCORE = 32M + (((32M * 100) / 64M) * 3 * 32M) / 100
4064  *      SCORE = 32M + (50 * 3 * 32M) / 100
4065  *      SCORE = 32M + (4800M / 100)
4066  *      SCORE = 32M + 48M
4067  *               ^     ^
4068  *               |     +--- final total relative fill-based score
4069  *               +--------- final total fill-based score
4070  *      SCORE = 80M
4071  *
4072  * As can be seen, at fill_ratio=3, the algorithm is slightly biased towards
4073  * extents that are more completely filled (in a 3:2 ratio) vs just larger.
4074  * Note that as an optimization, we replace multiplication and division by
4075  * 100 with bitshifting by 7 (which effectively multiplies and divides by 128).
4076  */
4077 static int
4078 ext_size_compare(const void *x, const void *y)
4079 {
4080         const range_seg_gap_t *rsa = x, *rsb = y;
4081
4082         uint64_t sa = rsa->rs_end - rsa->rs_start;
4083         uint64_t sb = rsb->rs_end - rsb->rs_start;
4084         uint64_t score_a, score_b;
4085
4086         score_a = rsa->rs_fill + ((((rsa->rs_fill << 7) / sa) *
4087             fill_weight * rsa->rs_fill) >> 7);
4088         score_b = rsb->rs_fill + ((((rsb->rs_fill << 7) / sb) *
4089             fill_weight * rsb->rs_fill) >> 7);
4090
4091         if (score_a > score_b)
4092                 return (-1);
4093         if (score_a == score_b) {
4094                 if (rsa->rs_start < rsb->rs_start)
4095                         return (-1);
4096                 if (rsa->rs_start == rsb->rs_start)
4097                         return (0);
4098                 return (1);
4099         }
4100         return (1);
4101 }
4102
4103 /*
4104  * Comparator for the q_sios_by_addr tree. Sorting is simply performed
4105  * based on LBA-order (from lowest to highest).
4106  */
4107 static int
4108 sio_addr_compare(const void *x, const void *y)
4109 {
4110         const scan_io_t *a = x, *b = y;
4111
4112         return (TREE_CMP(SIO_GET_OFFSET(a), SIO_GET_OFFSET(b)));
4113 }
4114
4115 /* IO queues are created on demand when they are needed. */
4116 static dsl_scan_io_queue_t *
4117 scan_io_queue_create(vdev_t *vd)
4118 {
4119         dsl_scan_t *scn = vd->vdev_spa->spa_dsl_pool->dp_scan;
4120         dsl_scan_io_queue_t *q = kmem_zalloc(sizeof (*q), KM_SLEEP);
4121
4122         q->q_scn = scn;
4123         q->q_vd = vd;
4124         q->q_sio_memused = 0;
4125         cv_init(&q->q_zio_cv, NULL, CV_DEFAULT, NULL);
4126         q->q_exts_by_addr = range_tree_create_impl(&rt_btree_ops, RANGE_SEG_GAP,
4127             &q->q_exts_by_size, 0, 0, ext_size_compare, zfs_scan_max_ext_gap);
4128         avl_create(&q->q_sios_by_addr, sio_addr_compare,
4129             sizeof (scan_io_t), offsetof(scan_io_t, sio_nodes.sio_addr_node));
4130
4131         return (q);
4132 }
4133
4134 /*
4135  * Destroys a scan queue and all segments and scan_io_t's contained in it.
4136  * No further execution of I/O occurs, anything pending in the queue is
4137  * simply freed without being executed.
4138  */
4139 void
4140 dsl_scan_io_queue_destroy(dsl_scan_io_queue_t *queue)
4141 {
4142         dsl_scan_t *scn = queue->q_scn;
4143         scan_io_t *sio;
4144         void *cookie = NULL;
4145         int64_t bytes_dequeued = 0;
4146
4147         ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
4148
4149         while ((sio = avl_destroy_nodes(&queue->q_sios_by_addr, &cookie)) !=
4150             NULL) {
4151                 ASSERT(range_tree_contains(queue->q_exts_by_addr,
4152                     SIO_GET_OFFSET(sio), SIO_GET_ASIZE(sio)));
4153                 bytes_dequeued += SIO_GET_ASIZE(sio);
4154                 queue->q_sio_memused -= SIO_GET_MUSED(sio);
4155                 sio_free(sio);
4156         }
4157
4158         ASSERT0(queue->q_sio_memused);
4159         atomic_add_64(&scn->scn_bytes_pending, -bytes_dequeued);
4160         range_tree_vacate(queue->q_exts_by_addr, NULL, queue);
4161         range_tree_destroy(queue->q_exts_by_addr);
4162         avl_destroy(&queue->q_sios_by_addr);
4163         cv_destroy(&queue->q_zio_cv);
4164
4165         kmem_free(queue, sizeof (*queue));
4166 }
4167
4168 /*
4169  * Properly transfers a dsl_scan_queue_t from `svd' to `tvd'. This is
4170  * called on behalf of vdev_top_transfer when creating or destroying
4171  * a mirror vdev due to zpool attach/detach.
4172  */
4173 void
4174 dsl_scan_io_queue_vdev_xfer(vdev_t *svd, vdev_t *tvd)
4175 {
4176         mutex_enter(&svd->vdev_scan_io_queue_lock);
4177         mutex_enter(&tvd->vdev_scan_io_queue_lock);
4178
4179         VERIFY3P(tvd->vdev_scan_io_queue, ==, NULL);
4180         tvd->vdev_scan_io_queue = svd->vdev_scan_io_queue;
4181         svd->vdev_scan_io_queue = NULL;
4182         if (tvd->vdev_scan_io_queue != NULL)
4183                 tvd->vdev_scan_io_queue->q_vd = tvd;
4184
4185         mutex_exit(&tvd->vdev_scan_io_queue_lock);
4186         mutex_exit(&svd->vdev_scan_io_queue_lock);
4187 }
4188
4189 static void
4190 scan_io_queues_destroy(dsl_scan_t *scn)
4191 {
4192         vdev_t *rvd = scn->scn_dp->dp_spa->spa_root_vdev;
4193
4194         for (uint64_t i = 0; i < rvd->vdev_children; i++) {
4195                 vdev_t *tvd = rvd->vdev_child[i];
4196
4197                 mutex_enter(&tvd->vdev_scan_io_queue_lock);
4198                 if (tvd->vdev_scan_io_queue != NULL)
4199                         dsl_scan_io_queue_destroy(tvd->vdev_scan_io_queue);
4200                 tvd->vdev_scan_io_queue = NULL;
4201                 mutex_exit(&tvd->vdev_scan_io_queue_lock);
4202         }
4203 }
4204
4205 static void
4206 dsl_scan_freed_dva(spa_t *spa, const blkptr_t *bp, int dva_i)
4207 {
4208         dsl_pool_t *dp = spa->spa_dsl_pool;
4209         dsl_scan_t *scn = dp->dp_scan;
4210         vdev_t *vdev;
4211         kmutex_t *q_lock;
4212         dsl_scan_io_queue_t *queue;
4213         scan_io_t *srch_sio, *sio;
4214         avl_index_t idx;
4215         uint64_t start, size;
4216
4217         vdev = vdev_lookup_top(spa, DVA_GET_VDEV(&bp->blk_dva[dva_i]));
4218         ASSERT(vdev != NULL);
4219         q_lock = &vdev->vdev_scan_io_queue_lock;
4220         queue = vdev->vdev_scan_io_queue;
4221
4222         mutex_enter(q_lock);
4223         if (queue == NULL) {
4224                 mutex_exit(q_lock);
4225                 return;
4226         }
4227
4228         srch_sio = sio_alloc(BP_GET_NDVAS(bp));
4229         bp2sio(bp, srch_sio, dva_i);
4230         start = SIO_GET_OFFSET(srch_sio);
4231         size = SIO_GET_ASIZE(srch_sio);
4232
4233         /*
4234          * We can find the zio in two states:
4235          * 1) Cold, just sitting in the queue of zio's to be issued at
4236          *      some point in the future. In this case, all we do is
4237          *      remove the zio from the q_sios_by_addr tree, decrement
4238          *      its data volume from the containing range_seg_t and
4239          *      resort the q_exts_by_size tree to reflect that the
4240          *      range_seg_t has lost some of its 'fill'. We don't shorten
4241          *      the range_seg_t - this is usually rare enough not to be
4242          *      worth the extra hassle of trying keep track of precise
4243          *      extent boundaries.
4244          * 2) Hot, where the zio is currently in-flight in
4245          *      dsl_scan_issue_ios. In this case, we can't simply
4246          *      reach in and stop the in-flight zio's, so we instead
4247          *      block the caller. Eventually, dsl_scan_issue_ios will
4248          *      be done with issuing the zio's it gathered and will
4249          *      signal us.
4250          */
4251         sio = avl_find(&queue->q_sios_by_addr, srch_sio, &idx);
4252         sio_free(srch_sio);
4253
4254         if (sio != NULL) {
4255                 int64_t asize = SIO_GET_ASIZE(sio);
4256                 blkptr_t tmpbp;
4257
4258                 /* Got it while it was cold in the queue */
4259                 ASSERT3U(start, ==, SIO_GET_OFFSET(sio));
4260                 ASSERT3U(size, ==, asize);
4261                 avl_remove(&queue->q_sios_by_addr, sio);
4262                 queue->q_sio_memused -= SIO_GET_MUSED(sio);
4263
4264                 ASSERT(range_tree_contains(queue->q_exts_by_addr, start, size));
4265                 range_tree_remove_fill(queue->q_exts_by_addr, start, size);
4266
4267                 /*
4268                  * We only update scn_bytes_pending in the cold path,
4269                  * otherwise it will already have been accounted for as
4270                  * part of the zio's execution.
4271                  */
4272                 atomic_add_64(&scn->scn_bytes_pending, -asize);
4273
4274                 /* count the block as though we issued it */
4275                 sio2bp(sio, &tmpbp);
4276                 count_block(scn, dp->dp_blkstats, &tmpbp);
4277
4278                 sio_free(sio);
4279         }
4280         mutex_exit(q_lock);
4281 }
4282
4283 /*
4284  * Callback invoked when a zio_free() zio is executing. This needs to be
4285  * intercepted to prevent the zio from deallocating a particular portion
4286  * of disk space and it then getting reallocated and written to, while we
4287  * still have it queued up for processing.
4288  */
4289 void
4290 dsl_scan_freed(spa_t *spa, const blkptr_t *bp)
4291 {
4292         dsl_pool_t *dp = spa->spa_dsl_pool;
4293         dsl_scan_t *scn = dp->dp_scan;
4294
4295         ASSERT(!BP_IS_EMBEDDED(bp));
4296         ASSERT(scn != NULL);
4297         if (!dsl_scan_is_running(scn))
4298                 return;
4299
4300         for (int i = 0; i < BP_GET_NDVAS(bp); i++)
4301                 dsl_scan_freed_dva(spa, bp, i);
4302 }
4303
4304 /* BEGIN CSTYLED */
4305 ZFS_MODULE_PARAM(zfs, zfs_, scan_vdev_limit, ULONG, ZMOD_RW,
4306         "Max bytes in flight per leaf vdev for scrubs and resilvers");
4307
4308 ZFS_MODULE_PARAM(zfs, zfs_, scrub_min_time_ms, INT, ZMOD_RW,
4309         "Min millisecs to scrub per txg");
4310
4311 ZFS_MODULE_PARAM(zfs, zfs_, obsolete_min_time_ms, INT, ZMOD_RW,
4312         "Min millisecs to obsolete per txg");
4313
4314 ZFS_MODULE_PARAM(zfs, zfs_, free_min_time_ms, INT, ZMOD_RW,
4315         "Min millisecs to free per txg");
4316
4317 ZFS_MODULE_PARAM(zfs, zfs_, resilver_min_time_ms, INT, ZMOD_RW,
4318         "Min millisecs to resilver per txg");
4319
4320 ZFS_MODULE_PARAM(zfs, zfs_, scan_suspend_progress, INT, ZMOD_RW,
4321         "Set to prevent scans from progressing");
4322
4323 ZFS_MODULE_PARAM(zfs, zfs_, no_scrub_io, INT, ZMOD_RW,
4324         "Set to disable scrub I/O");
4325
4326 ZFS_MODULE_PARAM(zfs, zfs_, no_scrub_prefetch, INT, ZMOD_RW,
4327         "Set to disable scrub prefetching");
4328
4329 ZFS_MODULE_PARAM(zfs, zfs_, async_block_max_blocks, ULONG, ZMOD_RW,
4330         "Max number of blocks freed in one txg");
4331
4332 ZFS_MODULE_PARAM(zfs, zfs_, free_bpobj_enabled, INT, ZMOD_RW,
4333         "Enable processing of the free_bpobj");
4334
4335 ZFS_MODULE_PARAM(zfs, zfs_, scan_mem_lim_fact, INT, ZMOD_RW,
4336         "Fraction of RAM for scan hard limit");
4337
4338 ZFS_MODULE_PARAM(zfs, zfs_, scan_issue_strategy, INT, ZMOD_RW,
4339         "IO issuing strategy during scrubbing. "
4340         "0 = default, 1 = LBA, 2 = size");
4341
4342 ZFS_MODULE_PARAM(zfs, zfs_, scan_legacy, INT, ZMOD_RW,
4343         "Scrub using legacy non-sequential method");
4344
4345 ZFS_MODULE_PARAM(zfs, zfs_, scan_checkpoint_intval, INT, ZMOD_RW,
4346         "Scan progress on-disk checkpointing interval");
4347
4348 ZFS_MODULE_PARAM(zfs, zfs_, scan_max_ext_gap, ULONG, ZMOD_RW,
4349         "Max gap in bytes between sequential scrub / resilver I/Os");
4350
4351 ZFS_MODULE_PARAM(zfs, zfs_, scan_mem_lim_soft_fact, INT, ZMOD_RW,
4352         "Fraction of hard limit used as soft limit");
4353
4354 ZFS_MODULE_PARAM(zfs, zfs_, scan_strict_mem_lim, INT, ZMOD_RW,
4355         "Tunable to attempt to reduce lock contention");
4356
4357 ZFS_MODULE_PARAM(zfs, zfs_, scan_fill_weight, INT, ZMOD_RW,
4358         "Tunable to adjust bias towards more filled segments during scans");
4359
4360 ZFS_MODULE_PARAM(zfs, zfs_, resilver_disable_defer, INT, ZMOD_RW,
4361         "Process all resilvers immediately");
4362 /* END CSTYLED */