xref: /freebsd/sys/contrib/openzfs/module/zfs/ddt.c (revision b670c9bafc0e31c7609969bf374b2e80bdc00211)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * CDDL HEADER START
4  *
5  * The contents of this file are subject to the terms of the
6  * Common Development and Distribution License (the "License").
7  * You may not use this file except in compliance with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or https://opensource.org/licenses/CDDL-1.0.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 
23 /*
24  * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
25  * Copyright (c) 2012, 2016 by Delphix. All rights reserved.
26  * Copyright (c) 2022 by Pawel Jakub Dawidek
27  * Copyright (c) 2019, 2023, Klara Inc.
28  */
29 
30 #include <sys/zfs_context.h>
31 #include <sys/spa.h>
32 #include <sys/spa_impl.h>
33 #include <sys/zio.h>
34 #include <sys/ddt.h>
35 #include <sys/ddt_impl.h>
36 #include <sys/zap.h>
37 #include <sys/dmu_tx.h>
38 #include <sys/arc.h>
39 #include <sys/dsl_pool.h>
40 #include <sys/zio_checksum.h>
41 #include <sys/dsl_scan.h>
42 #include <sys/abd.h>
43 #include <sys/zfeature.h>
44 
45 /*
46  * # DDT: Deduplication tables
47  *
48  * The dedup subsystem provides block-level deduplication. When enabled, blocks
49  * to be written will have the dedup (D) bit set, which causes them to be
50  * tracked in a "dedup table", or DDT. If a block has been seen before (exists
51  * in the DDT), instead of being written, it will instead be made to reference
52  * the existing on-disk data, and a refcount bumped in the DDT instead.
53  *
54  * ## Dedup tables and entries
55  *
56  * Conceptually, a DDT is a dictionary or map. Each entry has a "key"
57  * (ddt_key_t) made up a block's checksum and certian properties, and a "value"
58  * (one or more ddt_phys_t) containing valid DVAs for the block's data, birth
59  * time and refcount. Together these are enough to track references to a
60  * specific block, to build a valid block pointer to reference that block (for
61  * freeing, scrubbing, etc), and to fill a new block pointer with the missing
62  * pieces to make it seem like it was written.
63  *
64  * There's a single DDT (ddt_t) for each checksum type, held in spa_ddt[].
65  * Within each DDT, there can be multiple storage "types" (ddt_type_t, on-disk
66  * object data formats, each with their own implementations) and "classes"
67  * (ddt_class_t, instance of a storage type object, for entries with a specific
68  * characteristic). An entry (key) will only ever exist on one of these objects
69  * at any given time, but may be moved from one to another if their type or
70  * class changes.
71  *
72  * The DDT is driven by the write IO pipeline (zio_ddt_write()). When a block
73  * is to be written, before DVAs have been allocated, ddt_lookup() is called to
74  * see if the block has been seen before. If its not found, the write proceeds
75  * as normal, and after it succeeds, a new entry is created. If it is found, we
76  * fill the BP with the DVAs from the entry, increment the refcount and cause
77  * the write IO to return immediately.
78  *
79  * Traditionally, each ddt_phys_t slot in the entry represents a separate dedup
80  * block for the same content/checksum. The slot is selected based on the
81  * zp_copies parameter the block is written with, that is, the number of DVAs
82  * in the block. The "ditto" slot (DDT_PHYS_DITTO) used to be used for
83  * now-removed "dedupditto" feature. These are no longer written, and will be
84  * freed if encountered on old pools.
85  *
86  * If the "fast_dedup" feature is enabled, new dedup tables will be created
87  * with the "flat phys" option. In this mode, there is only one ddt_phys_t
88  * slot. If a write is issued for an entry that exists, but has fewer DVAs,
89  * then only as many new DVAs are allocated and written to make up the
90  * shortfall. The existing entry is then extended (ddt_phys_extend()) with the
91  * new DVAs.
92  *
93  * ## Lifetime of an entry
94  *
95  * A DDT can be enormous, and typically is not held in memory all at once.
96  * Instead, the changes to an entry are tracked in memory, and written down to
97  * disk at the end of each txg.
98  *
99  * A "live" in-memory entry (ddt_entry_t) is a node on the live tree
100  * (ddt_tree).  At the start of a txg, ddt_tree is empty. When an entry is
101  * required for IO, ddt_lookup() is called. If an entry already exists on
102  * ddt_tree, it is returned. Otherwise, a new one is created, and the
103  * type/class objects for the DDT are searched for that key. If its found, its
104  * value is copied into the live entry. If not, an empty entry is created.
105  *
106  * The live entry will be modified during the txg, usually by modifying the
107  * refcount, but sometimes by adding or updating DVAs. At the end of the txg
108  * (during spa_sync()), type and class are recalculated for entry (see
109  * ddt_sync_entry()), and the entry is written to the appropriate storage
110  * object and (if necessary), removed from an old one. ddt_tree is cleared and
111  * the next txg can start.
112  *
113  * ## Dedup quota
114  *
115  * A maximum size for all DDTs on the pool can be set with the
116  * dedup_table_quota property. This is determined in ddt_over_quota() and
117  * enforced during ddt_lookup(). If the pool is at or over its quota limit,
118  * ddt_lookup() will only return entries for existing blocks, as updates are
119  * still possible. New entries will not be created; instead, ddt_lookup() will
120  * return NULL. In response, the DDT write stage (zio_ddt_write()) will remove
121  * the D bit on the block and reissue the IO as a regular write. The block will
122  * not be deduplicated.
123  *
124  * Note that this is based on the on-disk size of the dedup store. Reclaiming
125  * this space after deleting entries relies on the ZAP "shrinking" behaviour,
126  * without which, no space would be recovered and the DDT would continue to be
127  * considered "over quota". See zap_shrink_enabled.
128  *
129  * ## Dedup table pruning
130  *
131  * As a complement to the dedup quota feature, ddtprune allows removal of older
132  * non-duplicate entries to make room for newer duplicate entries. The amount
133  * to prune can be based on a target percentage of the unique entries or based
134  * on the age (i.e., prune unique entry older than N days).
135  *
136  * ## Dedup log
137  *
138  * Historically, all entries modified on a txg were written back to dedup
139  * storage objects at the end of every txg. This could cause significant
140  * overheads, as each entry only takes up a tiny portion of a ZAP leaf node,
141  * and so required reading the whole node, updating the entry, and writing it
142  * back. On busy pools, this could add serious IO and memory overheads.
143  *
144  * To address this, the dedup log was added. If the "fast_dedup" feature is
145  * enabled, at the end of each txg, modified entries will be copied to an
146  * in-memory "log" object (ddt_log_t), and appended to an on-disk log. If the
147  * same block is requested again, the in-memory object will be checked first,
148  * and if its there, the entry inflated back onto the live tree without going
149  * to storage. The on-disk log is only read at pool import time, to reload the
150  * in-memory log.
151  *
152  * Each txg, some amount of the in-memory log will be flushed out to a DDT
153  * storage object (ie ZAP) as normal. OpenZFS will try hard to flush enough to
154  * keep up with the rate of change on dedup entries, but not so much that it
155  * would impact overall throughput, and not using too much memory. See the
156  * zfs_dedup_log_* tunables in zfs(4) for more details.
157  *
158  * ## Repair IO
159  *
160  * If a read on a dedup block fails, but there are other copies of the block in
161  * the other ddt_phys_t slots, reads will be issued for those instead
162  * (zio_ddt_read_start()). If one of those succeeds, the read is returned to
163  * the caller, and a copy is stashed on the entry's dde_repair_abd.
164  *
165  * During the end-of-txg sync, any entries with a dde_repair_abd get a
166  * "rewrite" write issued for the original block pointer, with the data read
167  * from the alternate block. If the block is actually damaged, this will invoke
168  * the pool's "self-healing" mechanism, and repair the block.
169  *
170  * If the "fast_dedup" feature is enabled, the "flat phys" option will be in
171  * use, so there is only ever one ddt_phys_t slot. The repair process will
172  * still happen in this case, though it is unlikely to succeed as there will
173  * usually be no other equivalent blocks to fall back on (though there might
174  * be, if this was an early version of a dedup'd block that has since been
175  * extended).
176  *
177  * Note that this repair mechanism is in addition to and separate from the
178  * regular OpenZFS scrub and self-healing mechanisms.
179  *
180  * ## Scanning (scrub/resilver)
181  *
182  * If dedup is active, the scrub machinery will walk the dedup table first, and
183  * scrub all blocks with refcnt > 1 first. After that it will move on to the
184  * regular top-down scrub, and exclude the refcnt > 1 blocks when it sees them.
185  * In this way, heavily deduplicated blocks are only scrubbed once. See the
186  * commentary on dsl_scan_ddt() for more details.
187  *
188  * Walking the DDT is done via ddt_walk(). The current position is stored in a
189  * ddt_bookmark_t, which represents a stable position in the storage object.
190  * This bookmark is stored by the scan machinery, and must reference the same
191  * position on the object even if the object changes, the pool is exported, or
192  * OpenZFS is upgraded.
193  *
194  * If the "fast_dedup" feature is enabled and the table has a log, the scan
195  * cannot begin until entries on the log are flushed, as the on-disk log has no
196  * concept of a "stable position". Instead, the log flushing process will enter
197  * a more aggressive mode, to flush out as much as is necesary as soon as
198  * possible, in order to begin the scan as soon as possible.
199  *
200  * ## Interaction with block cloning
201  *
202  * If block cloning and dedup are both enabled on a pool, BRT will look for the
203  * dedup bit on an incoming block pointer. If set, it will call into the DDT
204  * (ddt_addref()) to add a reference to the block, instead of adding a
205  * reference to the BRT. See brt_pending_apply().
206  */
207 
208 /*
209  * These are the only checksums valid for dedup. They must match the list
210  * from dedup_table in zfs_prop.c
211  */
212 #define	DDT_CHECKSUM_VALID(c)	\
213 	(c == ZIO_CHECKSUM_SHA256 || c == ZIO_CHECKSUM_SHA512 || \
214 	c == ZIO_CHECKSUM_SKEIN || c == ZIO_CHECKSUM_EDONR || \
215 	c == ZIO_CHECKSUM_BLAKE3)
216 
217 static kmem_cache_t *ddt_cache;
218 
219 static kmem_cache_t *ddt_entry_flat_cache;
220 static kmem_cache_t *ddt_entry_trad_cache;
221 
222 #define	DDT_ENTRY_FLAT_SIZE	(sizeof (ddt_entry_t) + DDT_FLAT_PHYS_SIZE)
223 #define	DDT_ENTRY_TRAD_SIZE	(sizeof (ddt_entry_t) + DDT_TRAD_PHYS_SIZE)
224 
225 #define	DDT_ENTRY_SIZE(ddt)	\
226 	_DDT_PHYS_SWITCH(ddt, DDT_ENTRY_FLAT_SIZE, DDT_ENTRY_TRAD_SIZE)
227 
228 /*
229  * Enable/disable prefetching of dedup-ed blocks which are going to be freed.
230  */
231 int zfs_dedup_prefetch = 0;
232 
233 /*
234  * If the dedup class cannot satisfy a DDT allocation, treat as over quota
235  * for this many TXGs.
236  */
237 uint_t dedup_class_wait_txgs = 5;
238 
239 /*
240  * How many DDT prune entries to add to the DDT sync AVL tree.
241  * Note these addtional entries have a memory footprint of a
242  * ddt_entry_t (216 bytes).
243  */
244 static uint32_t zfs_ddt_prunes_per_txg = 50000;
245 
246 /*
247  * For testing, synthesize aged DDT entries
248  * (in global scope for ztest)
249  */
250 boolean_t ddt_prune_artificial_age = B_FALSE;
251 boolean_t ddt_dump_prune_histogram = B_FALSE;
252 
253 /*
254  * Minimum time to flush per txg.
255  */
256 uint_t zfs_dedup_log_flush_min_time_ms = 1000;
257 
258 /*
259  * Minimum entries to flush per txg.
260  */
261 uint_t zfs_dedup_log_flush_entries_min = 200;
262 
263 /*
264  * Target number of TXGs until the whole dedup log has been flushed.
265  * The log size will float around this value times the ingest rate.
266  */
267 uint_t zfs_dedup_log_flush_txgs = 100;
268 
269 /*
270  * Maximum entries to flush per txg. Used for testing the dedup log.
271  */
272 uint_t zfs_dedup_log_flush_entries_max = UINT_MAX;
273 
274 /*
275  * Soft cap for the size of the current dedup log. If the log is larger
276  * than this size, we slightly increase the aggressiveness of the flushing to
277  * try to bring it back down to the soft cap.
278  */
279 uint_t zfs_dedup_log_cap = UINT_MAX;
280 
281 /*
282  * If this is set to B_TRUE, the cap above acts more like a hard cap:
283  * flushing is significantly more aggressive, increasing the minimum amount we
284  * flush per txg, as well as the maximum.
285  */
286 boolean_t zfs_dedup_log_hard_cap = B_FALSE;
287 
288 /*
289  * Number of txgs to average flow rates across.
290  */
291 uint_t zfs_dedup_log_flush_flow_rate_txgs = 10;
292 
293 static const ddt_ops_t *const ddt_ops[DDT_TYPES] = {
294 	&ddt_zap_ops,
295 };
296 
297 static const char *const ddt_class_name[DDT_CLASSES] = {
298 	"ditto",
299 	"duplicate",
300 	"unique",
301 };
302 
303 /*
304  * DDT feature flags automatically enabled for each on-disk version. Note that
305  * versions >0 cannot exist on disk without SPA_FEATURE_FAST_DEDUP enabled.
306  */
307 static const uint64_t ddt_version_flags[] = {
308 	[DDT_VERSION_LEGACY] = 0,
309 	[DDT_VERSION_FDT] = DDT_FLAG_FLAT | DDT_FLAG_LOG,
310 };
311 
312 /* per-DDT kstats */
313 typedef struct {
314 	/* total lookups and whether they returned new or existing entries */
315 	kstat_named_t dds_lookup;
316 	kstat_named_t dds_lookup_new;
317 	kstat_named_t dds_lookup_existing;
318 
319 	/* entries found on live tree, and if we had to wait for load */
320 	kstat_named_t dds_lookup_live_hit;
321 	kstat_named_t dds_lookup_live_wait;
322 	kstat_named_t dds_lookup_live_miss;
323 
324 	/* entries found on log trees */
325 	kstat_named_t dds_lookup_log_hit;
326 	kstat_named_t dds_lookup_log_active_hit;
327 	kstat_named_t dds_lookup_log_flushing_hit;
328 	kstat_named_t dds_lookup_log_miss;
329 
330 	/* entries found on store objects */
331 	kstat_named_t dds_lookup_stored_hit;
332 	kstat_named_t dds_lookup_stored_miss;
333 
334 	/* number of entries on log trees */
335 	kstat_named_t dds_log_active_entries;
336 	kstat_named_t dds_log_flushing_entries;
337 
338 	/* avg updated/flushed entries per txg */
339 	kstat_named_t dds_log_ingest_rate;
340 	kstat_named_t dds_log_flush_rate;
341 	kstat_named_t dds_log_flush_time_rate;
342 } ddt_kstats_t;
343 
344 static const ddt_kstats_t ddt_kstats_template = {
345 	{ "lookup",			KSTAT_DATA_UINT64 },
346 	{ "lookup_new",			KSTAT_DATA_UINT64 },
347 	{ "lookup_existing",		KSTAT_DATA_UINT64 },
348 	{ "lookup_live_hit",		KSTAT_DATA_UINT64 },
349 	{ "lookup_live_wait",		KSTAT_DATA_UINT64 },
350 	{ "lookup_live_miss",		KSTAT_DATA_UINT64 },
351 	{ "lookup_log_hit",		KSTAT_DATA_UINT64 },
352 	{ "lookup_log_active_hit",	KSTAT_DATA_UINT64 },
353 	{ "lookup_log_flushing_hit",	KSTAT_DATA_UINT64 },
354 	{ "lookup_log_miss",		KSTAT_DATA_UINT64 },
355 	{ "lookup_stored_hit",		KSTAT_DATA_UINT64 },
356 	{ "lookup_stored_miss",		KSTAT_DATA_UINT64 },
357 	{ "log_active_entries",		KSTAT_DATA_UINT64 },
358 	{ "log_flushing_entries",	KSTAT_DATA_UINT64 },
359 	{ "log_ingest_rate",		KSTAT_DATA_UINT32 },
360 	{ "log_flush_rate",		KSTAT_DATA_UINT32 },
361 	{ "log_flush_time_rate",	KSTAT_DATA_UINT32 },
362 };
363 
364 #ifdef _KERNEL
365 #define	_DDT_KSTAT_STAT(ddt, stat) \
366 	&((ddt_kstats_t *)(ddt)->ddt_ksp->ks_data)->stat.value.ui64
367 #define	DDT_KSTAT_BUMP(ddt, stat) \
368 	do { atomic_inc_64(_DDT_KSTAT_STAT(ddt, stat)); } while (0)
369 #define	DDT_KSTAT_ADD(ddt, stat, val) \
370 	do { atomic_add_64(_DDT_KSTAT_STAT(ddt, stat), val); } while (0)
371 #define	DDT_KSTAT_SUB(ddt, stat, val) \
372 	do { atomic_sub_64(_DDT_KSTAT_STAT(ddt, stat), val); } while (0)
373 #define	DDT_KSTAT_SET(ddt, stat, val) \
374 	do { atomic_store_64(_DDT_KSTAT_STAT(ddt, stat), val); } while (0)
375 #define	DDT_KSTAT_ZERO(ddt, stat) DDT_KSTAT_SET(ddt, stat, 0)
376 #else
377 #define	DDT_KSTAT_BUMP(ddt, stat) do {} while (0)
378 #define	DDT_KSTAT_ADD(ddt, stat, val) do {} while (0)
379 #define	DDT_KSTAT_SUB(ddt, stat, val) do {} while (0)
380 #define	DDT_KSTAT_SET(ddt, stat, val) do {} while (0)
381 #define	DDT_KSTAT_ZERO(ddt, stat) do {} while (0)
382 #endif /* _KERNEL */
383 
384 
385 static void
386 ddt_object_create(ddt_t *ddt, ddt_type_t type, ddt_class_t class,
387     dmu_tx_t *tx)
388 {
389 	spa_t *spa = ddt->ddt_spa;
390 	objset_t *os = ddt->ddt_os;
391 	uint64_t *objectp = &ddt->ddt_object[type][class];
392 	boolean_t prehash = zio_checksum_table[ddt->ddt_checksum].ci_flags &
393 	    ZCHECKSUM_FLAG_DEDUP;
394 	char name[DDT_NAMELEN];
395 
396 	ASSERT3U(ddt->ddt_dir_object, >, 0);
397 
398 	ddt_object_name(ddt, type, class, name);
399 
400 	ASSERT3U(*objectp, ==, 0);
401 	VERIFY0(ddt_ops[type]->ddt_op_create(os, objectp, tx, prehash));
402 	ASSERT3U(*objectp, !=, 0);
403 
404 	ASSERT3U(ddt->ddt_version, !=, DDT_VERSION_UNCONFIGURED);
405 
406 	VERIFY0(zap_add(os, ddt->ddt_dir_object, name, sizeof (uint64_t), 1,
407 	    objectp, tx));
408 
409 	VERIFY0(zap_add(os, spa->spa_ddt_stat_object, name,
410 	    sizeof (uint64_t), sizeof (ddt_histogram_t) / sizeof (uint64_t),
411 	    &ddt->ddt_histogram[type][class], tx));
412 }
413 
414 static void
415 ddt_object_destroy(ddt_t *ddt, ddt_type_t type, ddt_class_t class,
416     dmu_tx_t *tx)
417 {
418 	spa_t *spa = ddt->ddt_spa;
419 	objset_t *os = ddt->ddt_os;
420 	uint64_t *objectp = &ddt->ddt_object[type][class];
421 	uint64_t count;
422 	char name[DDT_NAMELEN];
423 
424 	ASSERT3U(ddt->ddt_dir_object, >, 0);
425 
426 	ddt_object_name(ddt, type, class, name);
427 
428 	ASSERT3U(*objectp, !=, 0);
429 	ASSERT(ddt_histogram_empty(&ddt->ddt_histogram[type][class]));
430 	VERIFY0(ddt_object_count(ddt, type, class, &count));
431 	VERIFY0(count);
432 	VERIFY0(zap_remove(os, ddt->ddt_dir_object, name, tx));
433 	VERIFY0(zap_remove(os, spa->spa_ddt_stat_object, name, tx));
434 	VERIFY0(ddt_ops[type]->ddt_op_destroy(os, *objectp, tx));
435 	memset(&ddt->ddt_object_stats[type][class], 0, sizeof (ddt_object_t));
436 
437 	*objectp = 0;
438 }
439 
440 static int
441 ddt_object_load(ddt_t *ddt, ddt_type_t type, ddt_class_t class)
442 {
443 	ddt_object_t *ddo = &ddt->ddt_object_stats[type][class];
444 	dmu_object_info_t doi;
445 	uint64_t count;
446 	char name[DDT_NAMELEN];
447 	int error;
448 
449 	if (ddt->ddt_dir_object == 0) {
450 		/*
451 		 * If we're configured but the containing dir doesn't exist
452 		 * yet, then this object can't possibly exist either.
453 		 */
454 		ASSERT3U(ddt->ddt_version, !=, DDT_VERSION_UNCONFIGURED);
455 		return (SET_ERROR(ENOENT));
456 	}
457 
458 	ddt_object_name(ddt, type, class, name);
459 
460 	error = zap_lookup(ddt->ddt_os, ddt->ddt_dir_object, name,
461 	    sizeof (uint64_t), 1, &ddt->ddt_object[type][class]);
462 	if (error != 0)
463 		return (error);
464 
465 	error = zap_lookup(ddt->ddt_os, ddt->ddt_spa->spa_ddt_stat_object, name,
466 	    sizeof (uint64_t), sizeof (ddt_histogram_t) / sizeof (uint64_t),
467 	    &ddt->ddt_histogram[type][class]);
468 	if (error != 0)
469 		return (error);
470 
471 	/*
472 	 * Seed the cached statistics.
473 	 */
474 	error = ddt_object_info(ddt, type, class, &doi);
475 	if (error)
476 		return (error);
477 
478 	error = ddt_object_count(ddt, type, class, &count);
479 	if (error)
480 		return (error);
481 
482 	ddo->ddo_count = count;
483 	ddo->ddo_dspace = doi.doi_physical_blocks_512 << 9;
484 	ddo->ddo_mspace = doi.doi_fill_count * doi.doi_data_block_size;
485 
486 	return (0);
487 }
488 
489 static void
490 ddt_object_sync(ddt_t *ddt, ddt_type_t type, ddt_class_t class,
491     dmu_tx_t *tx)
492 {
493 	ddt_object_t *ddo = &ddt->ddt_object_stats[type][class];
494 	dmu_object_info_t doi;
495 	uint64_t count;
496 	char name[DDT_NAMELEN];
497 
498 	ddt_object_name(ddt, type, class, name);
499 
500 	VERIFY0(zap_update(ddt->ddt_os, ddt->ddt_spa->spa_ddt_stat_object, name,
501 	    sizeof (uint64_t), sizeof (ddt_histogram_t) / sizeof (uint64_t),
502 	    &ddt->ddt_histogram[type][class], tx));
503 
504 	/*
505 	 * Cache DDT statistics; this is the only time they'll change.
506 	 */
507 	VERIFY0(ddt_object_info(ddt, type, class, &doi));
508 	VERIFY0(ddt_object_count(ddt, type, class, &count));
509 
510 	ddo->ddo_count = count;
511 	ddo->ddo_dspace = doi.doi_physical_blocks_512 << 9;
512 	ddo->ddo_mspace = doi.doi_fill_count * doi.doi_data_block_size;
513 }
514 
515 static boolean_t
516 ddt_object_exists(ddt_t *ddt, ddt_type_t type, ddt_class_t class)
517 {
518 	return (!!ddt->ddt_object[type][class]);
519 }
520 
521 static int
522 ddt_object_lookup(ddt_t *ddt, ddt_type_t type, ddt_class_t class,
523     ddt_entry_t *dde)
524 {
525 	if (!ddt_object_exists(ddt, type, class))
526 		return (SET_ERROR(ENOENT));
527 
528 	return (ddt_ops[type]->ddt_op_lookup(ddt->ddt_os,
529 	    ddt->ddt_object[type][class], &dde->dde_key,
530 	    dde->dde_phys, DDT_PHYS_SIZE(ddt)));
531 }
532 
533 static int
534 ddt_object_contains(ddt_t *ddt, ddt_type_t type, ddt_class_t class,
535     const ddt_key_t *ddk)
536 {
537 	if (!ddt_object_exists(ddt, type, class))
538 		return (SET_ERROR(ENOENT));
539 
540 	return (ddt_ops[type]->ddt_op_contains(ddt->ddt_os,
541 	    ddt->ddt_object[type][class], ddk));
542 }
543 
544 static void
545 ddt_object_prefetch(ddt_t *ddt, ddt_type_t type, ddt_class_t class,
546     const ddt_key_t *ddk)
547 {
548 	if (!ddt_object_exists(ddt, type, class))
549 		return;
550 
551 	ddt_ops[type]->ddt_op_prefetch(ddt->ddt_os,
552 	    ddt->ddt_object[type][class], ddk);
553 }
554 
555 static void
556 ddt_object_prefetch_all(ddt_t *ddt, ddt_type_t type, ddt_class_t class)
557 {
558 	if (!ddt_object_exists(ddt, type, class))
559 		return;
560 
561 	ddt_ops[type]->ddt_op_prefetch_all(ddt->ddt_os,
562 	    ddt->ddt_object[type][class]);
563 }
564 
565 static int
566 ddt_object_update(ddt_t *ddt, ddt_type_t type, ddt_class_t class,
567     const ddt_lightweight_entry_t *ddlwe, dmu_tx_t *tx)
568 {
569 	ASSERT(ddt_object_exists(ddt, type, class));
570 
571 	return (ddt_ops[type]->ddt_op_update(ddt->ddt_os,
572 	    ddt->ddt_object[type][class], &ddlwe->ddlwe_key,
573 	    &ddlwe->ddlwe_phys, DDT_PHYS_SIZE(ddt), tx));
574 }
575 
576 static int
577 ddt_object_remove(ddt_t *ddt, ddt_type_t type, ddt_class_t class,
578     const ddt_key_t *ddk, dmu_tx_t *tx)
579 {
580 	ASSERT(ddt_object_exists(ddt, type, class));
581 
582 	return (ddt_ops[type]->ddt_op_remove(ddt->ddt_os,
583 	    ddt->ddt_object[type][class], ddk, tx));
584 }
585 
586 int
587 ddt_object_walk(ddt_t *ddt, ddt_type_t type, ddt_class_t class,
588     uint64_t *walk, ddt_lightweight_entry_t *ddlwe)
589 {
590 	ASSERT(ddt_object_exists(ddt, type, class));
591 
592 	int error = ddt_ops[type]->ddt_op_walk(ddt->ddt_os,
593 	    ddt->ddt_object[type][class], walk, &ddlwe->ddlwe_key,
594 	    &ddlwe->ddlwe_phys, DDT_PHYS_SIZE(ddt));
595 	if (error == 0) {
596 		ddlwe->ddlwe_type = type;
597 		ddlwe->ddlwe_class = class;
598 		return (0);
599 	}
600 	return (error);
601 }
602 
603 int
604 ddt_object_count(ddt_t *ddt, ddt_type_t type, ddt_class_t class,
605     uint64_t *count)
606 {
607 	ASSERT(ddt_object_exists(ddt, type, class));
608 
609 	return (ddt_ops[type]->ddt_op_count(ddt->ddt_os,
610 	    ddt->ddt_object[type][class], count));
611 }
612 
613 int
614 ddt_object_info(ddt_t *ddt, ddt_type_t type, ddt_class_t class,
615     dmu_object_info_t *doi)
616 {
617 	if (!ddt_object_exists(ddt, type, class))
618 		return (SET_ERROR(ENOENT));
619 
620 	return (dmu_object_info(ddt->ddt_os, ddt->ddt_object[type][class],
621 	    doi));
622 }
623 
624 void
625 ddt_object_name(ddt_t *ddt, ddt_type_t type, ddt_class_t class,
626     char *name)
627 {
628 	(void) snprintf(name, DDT_NAMELEN, DMU_POOL_DDT,
629 	    zio_checksum_table[ddt->ddt_checksum].ci_name,
630 	    ddt_ops[type]->ddt_op_name, ddt_class_name[class]);
631 }
632 
633 void
634 ddt_bp_fill(const ddt_univ_phys_t *ddp, ddt_phys_variant_t v,
635     blkptr_t *bp, uint64_t txg)
636 {
637 	ASSERT3U(txg, !=, 0);
638 	ASSERT3U(v, <, DDT_PHYS_NONE);
639 	uint64_t phys_birth;
640 	const dva_t *dvap;
641 
642 	if (v == DDT_PHYS_FLAT) {
643 		phys_birth = ddp->ddp_flat.ddp_phys_birth;
644 		dvap = ddp->ddp_flat.ddp_dva;
645 	} else {
646 		phys_birth = ddp->ddp_trad[v].ddp_phys_birth;
647 		dvap = ddp->ddp_trad[v].ddp_dva;
648 	}
649 
650 	for (int d = 0; d < SPA_DVAS_PER_BP; d++)
651 		bp->blk_dva[d] = dvap[d];
652 	BP_SET_BIRTH(bp, txg, phys_birth);
653 }
654 
655 /*
656  * The bp created via this function may be used for repairs and scrub, but it
657  * will be missing the salt / IV required to do a full decrypting read.
658  */
659 void
660 ddt_bp_create(enum zio_checksum checksum, const ddt_key_t *ddk,
661     const ddt_univ_phys_t *ddp, ddt_phys_variant_t v, blkptr_t *bp)
662 {
663 	BP_ZERO(bp);
664 
665 	if (ddp != NULL)
666 		ddt_bp_fill(ddp, v, bp, ddt_phys_birth(ddp, v));
667 
668 	bp->blk_cksum = ddk->ddk_cksum;
669 
670 	BP_SET_LSIZE(bp, DDK_GET_LSIZE(ddk));
671 	BP_SET_PSIZE(bp, DDK_GET_PSIZE(ddk));
672 	BP_SET_COMPRESS(bp, DDK_GET_COMPRESS(ddk));
673 	BP_SET_CRYPT(bp, DDK_GET_CRYPT(ddk));
674 	BP_SET_FILL(bp, 1);
675 	BP_SET_CHECKSUM(bp, checksum);
676 	BP_SET_TYPE(bp, DMU_OT_DEDUP);
677 	BP_SET_LEVEL(bp, 0);
678 	BP_SET_DEDUP(bp, 1);
679 	BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
680 }
681 
682 void
683 ddt_key_fill(ddt_key_t *ddk, const blkptr_t *bp)
684 {
685 	ddk->ddk_cksum = bp->blk_cksum;
686 	ddk->ddk_prop = 0;
687 
688 	ASSERT(BP_IS_ENCRYPTED(bp) || !BP_USES_CRYPT(bp));
689 
690 	DDK_SET_LSIZE(ddk, BP_GET_LSIZE(bp));
691 	DDK_SET_PSIZE(ddk, BP_GET_PSIZE(bp));
692 	DDK_SET_COMPRESS(ddk, BP_GET_COMPRESS(bp));
693 	DDK_SET_CRYPT(ddk, BP_USES_CRYPT(bp));
694 }
695 
696 void
697 ddt_phys_extend(ddt_univ_phys_t *ddp, ddt_phys_variant_t v, const blkptr_t *bp)
698 {
699 	ASSERT3U(v, <, DDT_PHYS_NONE);
700 	int bp_ndvas = BP_GET_NDVAS(bp);
701 	int ddp_max_dvas = BP_IS_ENCRYPTED(bp) ?
702 	    SPA_DVAS_PER_BP - 1 : SPA_DVAS_PER_BP;
703 	dva_t *dvas = (v == DDT_PHYS_FLAT) ?
704 	    ddp->ddp_flat.ddp_dva : ddp->ddp_trad[v].ddp_dva;
705 
706 	int s = 0, d = 0;
707 	while (s < bp_ndvas && d < ddp_max_dvas) {
708 		if (DVA_IS_VALID(&dvas[d])) {
709 			d++;
710 			continue;
711 		}
712 		dvas[d] = bp->blk_dva[s];
713 		s++; d++;
714 	}
715 
716 	/*
717 	 * If the caller offered us more DVAs than we can fit, something has
718 	 * gone wrong in their accounting. zio_ddt_write() should never ask for
719 	 * more than we need.
720 	 */
721 	ASSERT3U(s, ==, bp_ndvas);
722 
723 	if (BP_IS_ENCRYPTED(bp))
724 		dvas[2] = bp->blk_dva[2];
725 
726 	if (ddt_phys_birth(ddp, v) == 0) {
727 		if (v == DDT_PHYS_FLAT)
728 			ddp->ddp_flat.ddp_phys_birth = BP_GET_BIRTH(bp);
729 		else
730 			ddp->ddp_trad[v].ddp_phys_birth = BP_GET_BIRTH(bp);
731 	}
732 }
733 
734 void
735 ddt_phys_unextend(ddt_univ_phys_t *cur, ddt_univ_phys_t *orig,
736     ddt_phys_variant_t v)
737 {
738 	ASSERT3U(v, <, DDT_PHYS_NONE);
739 	dva_t *cur_dvas = (v == DDT_PHYS_FLAT) ?
740 	    cur->ddp_flat.ddp_dva : cur->ddp_trad[v].ddp_dva;
741 	dva_t *orig_dvas = (v == DDT_PHYS_FLAT) ?
742 	    orig->ddp_flat.ddp_dva : orig->ddp_trad[v].ddp_dva;
743 
744 	for (int d = 0; d < SPA_DVAS_PER_BP; d++)
745 		cur_dvas[d] = orig_dvas[d];
746 
747 	if (ddt_phys_birth(orig, v) == 0) {
748 		if (v == DDT_PHYS_FLAT)
749 			cur->ddp_flat.ddp_phys_birth = 0;
750 		else
751 			cur->ddp_trad[v].ddp_phys_birth = 0;
752 	}
753 }
754 
755 void
756 ddt_phys_copy(ddt_univ_phys_t *dst, const ddt_univ_phys_t *src,
757     ddt_phys_variant_t v)
758 {
759 	ASSERT3U(v, <, DDT_PHYS_NONE);
760 
761 	if (v == DDT_PHYS_FLAT)
762 		dst->ddp_flat = src->ddp_flat;
763 	else
764 		dst->ddp_trad[v] = src->ddp_trad[v];
765 }
766 
767 void
768 ddt_phys_clear(ddt_univ_phys_t *ddp, ddt_phys_variant_t v)
769 {
770 	ASSERT3U(v, <, DDT_PHYS_NONE);
771 
772 	if (v == DDT_PHYS_FLAT)
773 		memset(&ddp->ddp_flat, 0, DDT_FLAT_PHYS_SIZE);
774 	else
775 		memset(&ddp->ddp_trad[v], 0, DDT_TRAD_PHYS_SIZE / DDT_PHYS_MAX);
776 }
777 
778 static uint64_t
779 ddt_class_start(void)
780 {
781 	uint64_t start = gethrestime_sec();
782 
783 	if (ddt_prune_artificial_age) {
784 		/*
785 		 * debug aide -- simulate a wider distribution
786 		 * so we don't have to wait for an aged DDT
787 		 * to test prune.
788 		 */
789 		int range = 1 << 21;
790 		int percent = random_in_range(100);
791 		if (percent < 50) {
792 			range = range >> 4;
793 		} else if (percent > 75) {
794 			range /= 2;
795 		}
796 		start -= random_in_range(range);
797 	}
798 
799 	return (start);
800 }
801 
802 void
803 ddt_phys_addref(ddt_univ_phys_t *ddp, ddt_phys_variant_t v)
804 {
805 	ASSERT3U(v, <, DDT_PHYS_NONE);
806 
807 	if (v == DDT_PHYS_FLAT)
808 		ddp->ddp_flat.ddp_refcnt++;
809 	else
810 		ddp->ddp_trad[v].ddp_refcnt++;
811 }
812 
813 uint64_t
814 ddt_phys_decref(ddt_univ_phys_t *ddp, ddt_phys_variant_t v)
815 {
816 	ASSERT3U(v, <, DDT_PHYS_NONE);
817 
818 	uint64_t *refcntp;
819 
820 	if (v == DDT_PHYS_FLAT)
821 		refcntp = &ddp->ddp_flat.ddp_refcnt;
822 	else
823 		refcntp = &ddp->ddp_trad[v].ddp_refcnt;
824 
825 	ASSERT3U(*refcntp, >, 0);
826 	(*refcntp)--;
827 	return (*refcntp);
828 }
829 
830 static void
831 ddt_phys_free(ddt_t *ddt, ddt_key_t *ddk, ddt_univ_phys_t *ddp,
832     ddt_phys_variant_t v, uint64_t txg)
833 {
834 	blkptr_t blk;
835 
836 	ddt_bp_create(ddt->ddt_checksum, ddk, ddp, v, &blk);
837 
838 	/*
839 	 * We clear the dedup bit so that zio_free() will actually free the
840 	 * space, rather than just decrementing the refcount in the DDT.
841 	 */
842 	BP_SET_DEDUP(&blk, 0);
843 
844 	ddt_phys_clear(ddp, v);
845 	zio_free(ddt->ddt_spa, txg, &blk);
846 }
847 
848 uint64_t
849 ddt_phys_birth(const ddt_univ_phys_t *ddp, ddt_phys_variant_t v)
850 {
851 	ASSERT3U(v, <, DDT_PHYS_NONE);
852 
853 	if (v == DDT_PHYS_FLAT)
854 		return (ddp->ddp_flat.ddp_phys_birth);
855 	else
856 		return (ddp->ddp_trad[v].ddp_phys_birth);
857 }
858 
859 int
860 ddt_phys_is_gang(const ddt_univ_phys_t *ddp, ddt_phys_variant_t v)
861 {
862 	ASSERT3U(v, <, DDT_PHYS_NONE);
863 
864 	const dva_t *dvas = (v == DDT_PHYS_FLAT) ?
865 	    ddp->ddp_flat.ddp_dva : ddp->ddp_trad[v].ddp_dva;
866 
867 	return (DVA_GET_GANG(&dvas[0]));
868 }
869 
870 int
871 ddt_phys_dva_count(const ddt_univ_phys_t *ddp, ddt_phys_variant_t v,
872     boolean_t encrypted)
873 {
874 	ASSERT3U(v, <, DDT_PHYS_NONE);
875 
876 	const dva_t *dvas = (v == DDT_PHYS_FLAT) ?
877 	    ddp->ddp_flat.ddp_dva : ddp->ddp_trad[v].ddp_dva;
878 
879 	return (DVA_IS_VALID(&dvas[0]) +
880 	    DVA_IS_VALID(&dvas[1]) +
881 	    DVA_IS_VALID(&dvas[2]) * !encrypted);
882 }
883 
884 ddt_phys_variant_t
885 ddt_phys_select(const ddt_t *ddt, const ddt_entry_t *dde, const blkptr_t *bp)
886 {
887 	if (dde == NULL)
888 		return (DDT_PHYS_NONE);
889 
890 	const ddt_univ_phys_t *ddp = dde->dde_phys;
891 
892 	if (ddt->ddt_flags & DDT_FLAG_FLAT) {
893 		if (DVA_EQUAL(BP_IDENTITY(bp), &ddp->ddp_flat.ddp_dva[0]) &&
894 		    BP_GET_BIRTH(bp) == ddp->ddp_flat.ddp_phys_birth) {
895 			return (DDT_PHYS_FLAT);
896 		}
897 	} else /* traditional phys */ {
898 		for (int p = 0; p < DDT_PHYS_MAX; p++) {
899 			if (DVA_EQUAL(BP_IDENTITY(bp),
900 			    &ddp->ddp_trad[p].ddp_dva[0]) &&
901 			    BP_GET_BIRTH(bp) ==
902 			    ddp->ddp_trad[p].ddp_phys_birth) {
903 				return (p);
904 			}
905 		}
906 	}
907 	return (DDT_PHYS_NONE);
908 }
909 
910 uint64_t
911 ddt_phys_refcnt(const ddt_univ_phys_t *ddp, ddt_phys_variant_t v)
912 {
913 	ASSERT3U(v, <, DDT_PHYS_NONE);
914 
915 	if (v == DDT_PHYS_FLAT)
916 		return (ddp->ddp_flat.ddp_refcnt);
917 	else
918 		return (ddp->ddp_trad[v].ddp_refcnt);
919 }
920 
921 uint64_t
922 ddt_phys_total_refcnt(const ddt_t *ddt, const ddt_univ_phys_t *ddp)
923 {
924 	uint64_t refcnt = 0;
925 
926 	if (ddt->ddt_flags & DDT_FLAG_FLAT)
927 		refcnt = ddp->ddp_flat.ddp_refcnt;
928 	else
929 		for (int v = DDT_PHYS_SINGLE; v <= DDT_PHYS_TRIPLE; v++)
930 			refcnt += ddp->ddp_trad[v].ddp_refcnt;
931 
932 	return (refcnt);
933 }
934 
935 ddt_t *
936 ddt_select(spa_t *spa, const blkptr_t *bp)
937 {
938 	ASSERT(DDT_CHECKSUM_VALID(BP_GET_CHECKSUM(bp)));
939 	return (spa->spa_ddt[BP_GET_CHECKSUM(bp)]);
940 }
941 
942 void
943 ddt_enter(ddt_t *ddt)
944 {
945 	mutex_enter(&ddt->ddt_lock);
946 }
947 
948 void
949 ddt_exit(ddt_t *ddt)
950 {
951 	mutex_exit(&ddt->ddt_lock);
952 }
953 
954 void
955 ddt_init(void)
956 {
957 	ddt_cache = kmem_cache_create("ddt_cache",
958 	    sizeof (ddt_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
959 	ddt_entry_flat_cache = kmem_cache_create("ddt_entry_flat_cache",
960 	    DDT_ENTRY_FLAT_SIZE, 0, NULL, NULL, NULL, NULL, NULL, 0);
961 	ddt_entry_trad_cache = kmem_cache_create("ddt_entry_trad_cache",
962 	    DDT_ENTRY_TRAD_SIZE, 0, NULL, NULL, NULL, NULL, NULL, 0);
963 
964 	ddt_log_init();
965 }
966 
967 void
968 ddt_fini(void)
969 {
970 	ddt_log_fini();
971 
972 	kmem_cache_destroy(ddt_entry_trad_cache);
973 	kmem_cache_destroy(ddt_entry_flat_cache);
974 	kmem_cache_destroy(ddt_cache);
975 }
976 
977 static ddt_entry_t *
978 ddt_alloc(const ddt_t *ddt, const ddt_key_t *ddk)
979 {
980 	ddt_entry_t *dde;
981 
982 	if (ddt->ddt_flags & DDT_FLAG_FLAT) {
983 		dde = kmem_cache_alloc(ddt_entry_flat_cache, KM_SLEEP);
984 		memset(dde, 0, DDT_ENTRY_FLAT_SIZE);
985 	} else {
986 		dde = kmem_cache_alloc(ddt_entry_trad_cache, KM_SLEEP);
987 		memset(dde, 0, DDT_ENTRY_TRAD_SIZE);
988 	}
989 
990 	cv_init(&dde->dde_cv, NULL, CV_DEFAULT, NULL);
991 
992 	dde->dde_key = *ddk;
993 
994 	return (dde);
995 }
996 
997 void
998 ddt_alloc_entry_io(ddt_entry_t *dde)
999 {
1000 	if (dde->dde_io != NULL)
1001 		return;
1002 
1003 	dde->dde_io = kmem_zalloc(sizeof (ddt_entry_io_t), KM_SLEEP);
1004 }
1005 
1006 static void
1007 ddt_free(const ddt_t *ddt, ddt_entry_t *dde)
1008 {
1009 	if (dde->dde_io != NULL) {
1010 		for (int p = 0; p < DDT_NPHYS(ddt); p++)
1011 			ASSERT3P(dde->dde_io->dde_lead_zio[p], ==, NULL);
1012 
1013 		if (dde->dde_io->dde_repair_abd != NULL)
1014 			abd_free(dde->dde_io->dde_repair_abd);
1015 
1016 		kmem_free(dde->dde_io, sizeof (ddt_entry_io_t));
1017 	}
1018 
1019 	cv_destroy(&dde->dde_cv);
1020 	kmem_cache_free(ddt->ddt_flags & DDT_FLAG_FLAT ?
1021 	    ddt_entry_flat_cache : ddt_entry_trad_cache, dde);
1022 }
1023 
1024 void
1025 ddt_remove(ddt_t *ddt, ddt_entry_t *dde)
1026 {
1027 	ASSERT(MUTEX_HELD(&ddt->ddt_lock));
1028 
1029 	/* Entry is still in the log, so charge the entry back to it */
1030 	if (dde->dde_flags & DDE_FLAG_LOGGED) {
1031 		ddt_lightweight_entry_t ddlwe;
1032 		DDT_ENTRY_TO_LIGHTWEIGHT(ddt, dde, &ddlwe);
1033 		ddt_histogram_add_entry(ddt, &ddt->ddt_log_histogram, &ddlwe);
1034 	}
1035 
1036 	avl_remove(&ddt->ddt_tree, dde);
1037 	ddt_free(ddt, dde);
1038 }
1039 
1040 static boolean_t
1041 ddt_special_over_quota(spa_t *spa, metaslab_class_t *mc)
1042 {
1043 	if (mc != NULL && metaslab_class_get_space(mc) > 0) {
1044 		/* Over quota if allocating outside of this special class */
1045 		if (spa_syncing_txg(spa) <= spa->spa_dedup_class_full_txg +
1046 		    dedup_class_wait_txgs) {
1047 			/* Waiting for some deferred frees to be processed */
1048 			return (B_TRUE);
1049 		}
1050 
1051 		/*
1052 		 * We're considered over quota when we hit 85% full, or for
1053 		 * larger drives, when there is less than 8GB free.
1054 		 */
1055 		uint64_t allocated = metaslab_class_get_alloc(mc);
1056 		uint64_t capacity = metaslab_class_get_space(mc);
1057 		uint64_t limit = MAX(capacity * 85 / 100,
1058 		    (capacity > (1LL<<33)) ? capacity - (1LL<<33) : 0);
1059 
1060 		return (allocated >= limit);
1061 	}
1062 	return (B_FALSE);
1063 }
1064 
1065 /*
1066  * Check if the DDT is over its quota.  This can be due to a few conditions:
1067  *   1. 'dedup_table_quota' property is not 0 (none) and the dedup dsize
1068  *       exceeds this limit
1069  *
1070  *   2. 'dedup_table_quota' property is set to automatic and
1071  *      a. the dedup or special allocation class could not satisfy a DDT
1072  *         allocation in a recent transaction
1073  *      b. the dedup or special allocation class has exceeded its 85% limit
1074  */
1075 static boolean_t
1076 ddt_over_quota(spa_t *spa)
1077 {
1078 	if (spa->spa_dedup_table_quota == 0)
1079 		return (B_FALSE);
1080 
1081 	if (spa->spa_dedup_table_quota != UINT64_MAX)
1082 		return (ddt_get_ddt_dsize(spa) > spa->spa_dedup_table_quota);
1083 
1084 	/*
1085 	 * For automatic quota, table size is limited by dedup or special class
1086 	 */
1087 	if (ddt_special_over_quota(spa, spa_dedup_class(spa)))
1088 		return (B_TRUE);
1089 	else if (spa_special_has_ddt(spa) &&
1090 	    ddt_special_over_quota(spa, spa_special_class(spa)))
1091 		return (B_TRUE);
1092 
1093 	return (B_FALSE);
1094 }
1095 
1096 void
1097 ddt_prefetch_all(spa_t *spa)
1098 {
1099 	/*
1100 	 * Load all DDT entries for each type/class combination. This is
1101 	 * indended to perform a prefetch on all such blocks. For the same
1102 	 * reason that ddt_prefetch isn't locked, this is also not locked.
1103 	 */
1104 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
1105 		ddt_t *ddt = spa->spa_ddt[c];
1106 		if (!ddt)
1107 			continue;
1108 
1109 		for (ddt_type_t type = 0; type < DDT_TYPES; type++) {
1110 			for (ddt_class_t class = 0; class < DDT_CLASSES;
1111 			    class++) {
1112 				ddt_object_prefetch_all(ddt, type, class);
1113 			}
1114 		}
1115 	}
1116 }
1117 
1118 static int ddt_configure(ddt_t *ddt, boolean_t new);
1119 
1120 /*
1121  * If the BP passed to ddt_lookup has valid DVAs, then we need to compare them
1122  * to the ones in the entry. If they're different, then the passed-in BP is
1123  * from a previous generation of this entry (ie was previously pruned) and we
1124  * have to act like the entry doesn't exist at all.
1125  *
1126  * This should only happen during a lookup to free the block (zio_ddt_free()).
1127  *
1128  * XXX this is similar in spirit to ddt_phys_select(), maybe can combine
1129  *       -- robn, 2024-02-09
1130  */
1131 static boolean_t
1132 ddt_entry_lookup_is_valid(ddt_t *ddt, const blkptr_t *bp, ddt_entry_t *dde)
1133 {
1134 	/* If the BP has no DVAs, then this entry is good */
1135 	uint_t ndvas = BP_GET_NDVAS(bp);
1136 	if (ndvas == 0)
1137 		return (B_TRUE);
1138 
1139 	/*
1140 	 * Only checking the phys for the copies. For flat, there's only one;
1141 	 * for trad it'll be the one that has the matching set of DVAs.
1142 	 */
1143 	const dva_t *dvas = (ddt->ddt_flags & DDT_FLAG_FLAT) ?
1144 	    dde->dde_phys->ddp_flat.ddp_dva :
1145 	    dde->dde_phys->ddp_trad[ndvas].ddp_dva;
1146 
1147 	/*
1148 	 * Compare entry DVAs with the BP. They should all be there, but
1149 	 * there's not really anything we can do if its only partial anyway,
1150 	 * that's an error somewhere else, maybe long ago.
1151 	 */
1152 	uint_t d;
1153 	for (d = 0; d < ndvas; d++)
1154 		if (!DVA_EQUAL(&dvas[d], &bp->blk_dva[d]))
1155 			return (B_FALSE);
1156 	ASSERT3U(d, ==, ndvas);
1157 
1158 	return (B_TRUE);
1159 }
1160 
1161 ddt_entry_t *
1162 ddt_lookup(ddt_t *ddt, const blkptr_t *bp, boolean_t verify)
1163 {
1164 	spa_t *spa = ddt->ddt_spa;
1165 	ddt_key_t search;
1166 	ddt_entry_t *dde;
1167 	ddt_type_t type;
1168 	ddt_class_t class;
1169 	avl_index_t where;
1170 	int error;
1171 
1172 	ASSERT(MUTEX_HELD(&ddt->ddt_lock));
1173 
1174 	if (ddt->ddt_version == DDT_VERSION_UNCONFIGURED) {
1175 		/*
1176 		 * This is the first use of this DDT since the pool was
1177 		 * created; finish getting it ready for use.
1178 		 */
1179 		VERIFY0(ddt_configure(ddt, B_TRUE));
1180 		ASSERT3U(ddt->ddt_version, !=, DDT_VERSION_UNCONFIGURED);
1181 	}
1182 
1183 	DDT_KSTAT_BUMP(ddt, dds_lookup);
1184 
1185 	ddt_key_fill(&search, bp);
1186 
1187 	/* Find an existing live entry */
1188 	dde = avl_find(&ddt->ddt_tree, &search, &where);
1189 	if (dde != NULL) {
1190 		/* If we went over quota, act like we didn't find it */
1191 		if (dde->dde_flags & DDE_FLAG_OVERQUOTA)
1192 			return (NULL);
1193 
1194 		/* If it's already loaded, we can just return it. */
1195 		DDT_KSTAT_BUMP(ddt, dds_lookup_live_hit);
1196 		if (dde->dde_flags & DDE_FLAG_LOADED) {
1197 			if (!verify || ddt_entry_lookup_is_valid(ddt, bp, dde))
1198 				return (dde);
1199 			return (NULL);
1200 		}
1201 
1202 		/* Someone else is loading it, wait for it. */
1203 		dde->dde_waiters++;
1204 		DDT_KSTAT_BUMP(ddt, dds_lookup_live_wait);
1205 		while (!(dde->dde_flags & DDE_FLAG_LOADED))
1206 			cv_wait(&dde->dde_cv, &ddt->ddt_lock);
1207 		dde->dde_waiters--;
1208 
1209 		/* Loaded but over quota, forget we were ever here */
1210 		if (dde->dde_flags & DDE_FLAG_OVERQUOTA) {
1211 			if (dde->dde_waiters == 0) {
1212 				avl_remove(&ddt->ddt_tree, dde);
1213 				ddt_free(ddt, dde);
1214 			}
1215 			return (NULL);
1216 		}
1217 
1218 		DDT_KSTAT_BUMP(ddt, dds_lookup_existing);
1219 
1220 		/* Make sure the loaded entry matches the BP */
1221 		if (!verify || ddt_entry_lookup_is_valid(ddt, bp, dde))
1222 			return (dde);
1223 		return (NULL);
1224 	} else
1225 		DDT_KSTAT_BUMP(ddt, dds_lookup_live_miss);
1226 
1227 	/* Time to make a new entry. */
1228 	dde = ddt_alloc(ddt, &search);
1229 
1230 	/* Record the time this class was created (used by ddt prune) */
1231 	if (ddt->ddt_flags & DDT_FLAG_FLAT)
1232 		dde->dde_phys->ddp_flat.ddp_class_start = ddt_class_start();
1233 
1234 	avl_insert(&ddt->ddt_tree, dde, where);
1235 
1236 	/* If its in the log tree, we can "load" it from there */
1237 	if (ddt->ddt_flags & DDT_FLAG_LOG) {
1238 		ddt_lightweight_entry_t ddlwe;
1239 
1240 		if (ddt_log_find_key(ddt, &search, &ddlwe)) {
1241 			/*
1242 			 * See if we have the key first, and if so, set up
1243 			 * the entry.
1244 			 */
1245 			dde->dde_type = ddlwe.ddlwe_type;
1246 			dde->dde_class = ddlwe.ddlwe_class;
1247 			memcpy(dde->dde_phys, &ddlwe.ddlwe_phys,
1248 			    DDT_PHYS_SIZE(ddt));
1249 			/* Whatever we found isn't valid for this BP, eject */
1250 			if (verify &&
1251 			    !ddt_entry_lookup_is_valid(ddt, bp, dde)) {
1252 				avl_remove(&ddt->ddt_tree, dde);
1253 				ddt_free(ddt, dde);
1254 				return (NULL);
1255 			}
1256 
1257 			/* Remove it and count it */
1258 			if (ddt_log_remove_key(ddt,
1259 			    ddt->ddt_log_active, &search)) {
1260 				DDT_KSTAT_BUMP(ddt, dds_lookup_log_active_hit);
1261 			} else {
1262 				VERIFY(ddt_log_remove_key(ddt,
1263 				    ddt->ddt_log_flushing, &search));
1264 				DDT_KSTAT_BUMP(ddt,
1265 				    dds_lookup_log_flushing_hit);
1266 			}
1267 
1268 			dde->dde_flags = DDE_FLAG_LOADED | DDE_FLAG_LOGGED;
1269 
1270 			DDT_KSTAT_BUMP(ddt, dds_lookup_log_hit);
1271 			DDT_KSTAT_BUMP(ddt, dds_lookup_existing);
1272 
1273 			return (dde);
1274 		}
1275 
1276 		DDT_KSTAT_BUMP(ddt, dds_lookup_log_miss);
1277 	}
1278 
1279 	/*
1280 	 * ddt_tree is now stable, so unlock and let everyone else keep moving.
1281 	 * Anyone landing on this entry will find it without DDE_FLAG_LOADED,
1282 	 * and go to sleep waiting for it above.
1283 	 */
1284 	ddt_exit(ddt);
1285 
1286 	/* Search all store objects for the entry. */
1287 	error = ENOENT;
1288 	for (type = 0; type < DDT_TYPES; type++) {
1289 		for (class = 0; class < DDT_CLASSES; class++) {
1290 			error = ddt_object_lookup(ddt, type, class, dde);
1291 			if (error != ENOENT) {
1292 				ASSERT0(error);
1293 				break;
1294 			}
1295 		}
1296 		if (error != ENOENT)
1297 			break;
1298 	}
1299 
1300 	ddt_enter(ddt);
1301 
1302 	ASSERT(!(dde->dde_flags & DDE_FLAG_LOADED));
1303 
1304 	dde->dde_type = type;	/* will be DDT_TYPES if no entry found */
1305 	dde->dde_class = class;	/* will be DDT_CLASSES if no entry found */
1306 
1307 	boolean_t valid = B_TRUE;
1308 
1309 	if (dde->dde_type == DDT_TYPES &&
1310 	    dde->dde_class == DDT_CLASSES &&
1311 	    ddt_over_quota(spa)) {
1312 		/* Over quota. If no one is waiting, clean up right now. */
1313 		if (dde->dde_waiters == 0) {
1314 			avl_remove(&ddt->ddt_tree, dde);
1315 			ddt_free(ddt, dde);
1316 			return (NULL);
1317 		}
1318 
1319 		/* Flag cleanup required */
1320 		dde->dde_flags |= DDE_FLAG_OVERQUOTA;
1321 	} else if (error == 0) {
1322 		/*
1323 		 * If what we loaded is no good for this BP and there's no one
1324 		 * waiting for it, we can just remove it and get out. If its no
1325 		 * good but there are waiters, we have to leave it, because we
1326 		 * don't know what they want. If its not needed we'll end up
1327 		 * taking an entry log/sync, but it can only happen if more
1328 		 * than one previous version of this block is being deleted at
1329 		 * the same time. This is extremely unlikely to happen and not
1330 		 * worth the effort to deal with without taking an entry
1331 		 * update.
1332 		 */
1333 		valid = !verify || ddt_entry_lookup_is_valid(ddt, bp, dde);
1334 		if (!valid && dde->dde_waiters == 0) {
1335 			avl_remove(&ddt->ddt_tree, dde);
1336 			ddt_free(ddt, dde);
1337 			return (NULL);
1338 		}
1339 
1340 		DDT_KSTAT_BUMP(ddt, dds_lookup_stored_hit);
1341 		DDT_KSTAT_BUMP(ddt, dds_lookup_existing);
1342 
1343 		/*
1344 		 * The histograms only track inactive (stored or logged) blocks.
1345 		 * We've just put an entry onto the live list, so we need to
1346 		 * remove its counts. When its synced back, it'll be re-added
1347 		 * to the right one.
1348 		 *
1349 		 * We only do this when we successfully found it in the store.
1350 		 * error == ENOENT means this is a new entry, and so its already
1351 		 * not counted.
1352 		 */
1353 		ddt_histogram_t *ddh =
1354 		    &ddt->ddt_histogram[dde->dde_type][dde->dde_class];
1355 
1356 		ddt_lightweight_entry_t ddlwe;
1357 		DDT_ENTRY_TO_LIGHTWEIGHT(ddt, dde, &ddlwe);
1358 		ddt_histogram_sub_entry(ddt, ddh, &ddlwe);
1359 	} else {
1360 		DDT_KSTAT_BUMP(ddt, dds_lookup_stored_miss);
1361 		DDT_KSTAT_BUMP(ddt, dds_lookup_new);
1362 	}
1363 
1364 	/* Entry loaded, everyone can proceed now */
1365 	dde->dde_flags |= DDE_FLAG_LOADED;
1366 	cv_broadcast(&dde->dde_cv);
1367 
1368 	if ((dde->dde_flags & DDE_FLAG_OVERQUOTA) || !valid)
1369 		return (NULL);
1370 
1371 	return (dde);
1372 }
1373 
1374 void
1375 ddt_prefetch(spa_t *spa, const blkptr_t *bp)
1376 {
1377 	ddt_t *ddt;
1378 	ddt_key_t ddk;
1379 
1380 	if (!zfs_dedup_prefetch || bp == NULL || !BP_GET_DEDUP(bp))
1381 		return;
1382 
1383 	/*
1384 	 * We only remove the DDT once all tables are empty and only
1385 	 * prefetch dedup blocks when there are entries in the DDT.
1386 	 * Thus no locking is required as the DDT can't disappear on us.
1387 	 */
1388 	ddt = ddt_select(spa, bp);
1389 	ddt_key_fill(&ddk, bp);
1390 
1391 	for (ddt_type_t type = 0; type < DDT_TYPES; type++) {
1392 		for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {
1393 			ddt_object_prefetch(ddt, type, class, &ddk);
1394 		}
1395 	}
1396 }
1397 
1398 /*
1399  * ddt_key_t comparison. Any struct wanting to make use of this function must
1400  * have the key as the first element. Casts it to N uint64_ts, and checks until
1401  * we find there's a difference. This is intended to match how ddt_zap.c drives
1402  * the ZAPs (first uint64_t as the key prehash), which will minimise the number
1403  * of ZAP blocks touched when flushing logged entries from an AVL walk. This is
1404  * not an invariant for this function though, should you wish to change it.
1405  */
1406 int
1407 ddt_key_compare(const void *x1, const void *x2)
1408 {
1409 	const uint64_t *k1 = (const uint64_t *)x1;
1410 	const uint64_t *k2 = (const uint64_t *)x2;
1411 
1412 	int cmp;
1413 	for (int i = 0; i < (sizeof (ddt_key_t) / sizeof (uint64_t)); i++)
1414 		if (likely((cmp = TREE_CMP(k1[i], k2[i])) != 0))
1415 			return (cmp);
1416 
1417 	return (0);
1418 }
1419 
1420 /* Create the containing dir for this DDT and bump the feature count */
1421 static void
1422 ddt_create_dir(ddt_t *ddt, dmu_tx_t *tx)
1423 {
1424 	ASSERT3U(ddt->ddt_dir_object, ==, 0);
1425 	ASSERT3U(ddt->ddt_version, ==, DDT_VERSION_FDT);
1426 
1427 	char name[DDT_NAMELEN];
1428 	snprintf(name, DDT_NAMELEN, DMU_POOL_DDT_DIR,
1429 	    zio_checksum_table[ddt->ddt_checksum].ci_name);
1430 
1431 	ddt->ddt_dir_object = zap_create_link(ddt->ddt_os,
1432 	    DMU_OTN_ZAP_METADATA, DMU_POOL_DIRECTORY_OBJECT, name, tx);
1433 
1434 	VERIFY0(zap_add(ddt->ddt_os, ddt->ddt_dir_object, DDT_DIR_VERSION,
1435 	    sizeof (uint64_t), 1, &ddt->ddt_version, tx));
1436 	VERIFY0(zap_add(ddt->ddt_os, ddt->ddt_dir_object, DDT_DIR_FLAGS,
1437 	    sizeof (uint64_t), 1, &ddt->ddt_flags, tx));
1438 
1439 	spa_feature_incr(ddt->ddt_spa, SPA_FEATURE_FAST_DEDUP, tx);
1440 }
1441 
1442 /* Destroy the containing dir and deactivate the feature */
1443 static void
1444 ddt_destroy_dir(ddt_t *ddt, dmu_tx_t *tx)
1445 {
1446 	ASSERT3U(ddt->ddt_dir_object, !=, 0);
1447 	ASSERT3U(ddt->ddt_dir_object, !=, DMU_POOL_DIRECTORY_OBJECT);
1448 	ASSERT3U(ddt->ddt_version, ==, DDT_VERSION_FDT);
1449 
1450 	char name[DDT_NAMELEN];
1451 	snprintf(name, DDT_NAMELEN, DMU_POOL_DDT_DIR,
1452 	    zio_checksum_table[ddt->ddt_checksum].ci_name);
1453 
1454 	for (ddt_type_t type = 0; type < DDT_TYPES; type++) {
1455 		for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {
1456 			ASSERT(!ddt_object_exists(ddt, type, class));
1457 		}
1458 	}
1459 
1460 	ddt_log_destroy(ddt, tx);
1461 
1462 	uint64_t count;
1463 	ASSERT0(zap_count(ddt->ddt_os, ddt->ddt_dir_object, &count));
1464 	ASSERT0(zap_contains(ddt->ddt_os, ddt->ddt_dir_object,
1465 	    DDT_DIR_VERSION));
1466 	ASSERT0(zap_contains(ddt->ddt_os, ddt->ddt_dir_object, DDT_DIR_FLAGS));
1467 	ASSERT3U(count, ==, 2);
1468 
1469 	VERIFY0(zap_remove(ddt->ddt_os, DMU_POOL_DIRECTORY_OBJECT, name, tx));
1470 	VERIFY0(zap_destroy(ddt->ddt_os, ddt->ddt_dir_object, tx));
1471 
1472 	ddt->ddt_dir_object = 0;
1473 
1474 	spa_feature_decr(ddt->ddt_spa, SPA_FEATURE_FAST_DEDUP, tx);
1475 }
1476 
1477 /*
1478  * Determine, flags and on-disk layout from what's already stored. If there's
1479  * nothing stored, then if new is false, returns ENOENT, and if true, selects
1480  * based on pool config.
1481  */
1482 static int
1483 ddt_configure(ddt_t *ddt, boolean_t new)
1484 {
1485 	spa_t *spa = ddt->ddt_spa;
1486 	char name[DDT_NAMELEN];
1487 	int error;
1488 
1489 	ASSERT3U(spa_load_state(spa), !=, SPA_LOAD_CREATE);
1490 
1491 	boolean_t fdt_enabled =
1492 	    spa_feature_is_enabled(spa, SPA_FEATURE_FAST_DEDUP);
1493 	boolean_t fdt_active =
1494 	    spa_feature_is_active(spa, SPA_FEATURE_FAST_DEDUP);
1495 
1496 	/*
1497 	 * First, look for the global DDT stats object. If its not there, then
1498 	 * there's never been a DDT written before ever, and we know we're
1499 	 * starting from scratch.
1500 	 */
1501 	error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
1502 	    DMU_POOL_DDT_STATS, sizeof (uint64_t), 1,
1503 	    &spa->spa_ddt_stat_object);
1504 	if (error != 0) {
1505 		if (error != ENOENT)
1506 			return (error);
1507 		goto not_found;
1508 	}
1509 
1510 	if (fdt_active) {
1511 		/*
1512 		 * Now look for a DDT directory. If it exists, then it has
1513 		 * everything we need.
1514 		 */
1515 		snprintf(name, DDT_NAMELEN, DMU_POOL_DDT_DIR,
1516 		    zio_checksum_table[ddt->ddt_checksum].ci_name);
1517 
1518 		error = zap_lookup(spa->spa_meta_objset,
1519 		    DMU_POOL_DIRECTORY_OBJECT, name, sizeof (uint64_t), 1,
1520 		    &ddt->ddt_dir_object);
1521 		if (error == 0) {
1522 			ASSERT3U(spa->spa_meta_objset, ==, ddt->ddt_os);
1523 
1524 			error = zap_lookup(ddt->ddt_os, ddt->ddt_dir_object,
1525 			    DDT_DIR_VERSION, sizeof (uint64_t), 1,
1526 			    &ddt->ddt_version);
1527 			if (error != 0)
1528 				return (error);
1529 
1530 			error = zap_lookup(ddt->ddt_os, ddt->ddt_dir_object,
1531 			    DDT_DIR_FLAGS, sizeof (uint64_t), 1,
1532 			    &ddt->ddt_flags);
1533 			if (error != 0)
1534 				return (error);
1535 
1536 			if (ddt->ddt_version != DDT_VERSION_FDT) {
1537 				zfs_dbgmsg("ddt_configure: spa=%s ddt_dir=%s "
1538 				    "unknown version %llu", spa_name(spa),
1539 				    name, (u_longlong_t)ddt->ddt_version);
1540 				return (SET_ERROR(EINVAL));
1541 			}
1542 
1543 			if ((ddt->ddt_flags & ~DDT_FLAG_MASK) != 0) {
1544 				zfs_dbgmsg("ddt_configure: spa=%s ddt_dir=%s "
1545 				    "version=%llu unknown flags %llx",
1546 				    spa_name(spa), name,
1547 				    (u_longlong_t)ddt->ddt_flags,
1548 				    (u_longlong_t)ddt->ddt_version);
1549 				return (SET_ERROR(EINVAL));
1550 			}
1551 
1552 			return (0);
1553 		}
1554 		if (error != ENOENT)
1555 			return (error);
1556 	}
1557 
1558 	/* Any object in the root indicates a traditional setup. */
1559 	for (ddt_type_t type = 0; type < DDT_TYPES; type++) {
1560 		for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {
1561 			ddt_object_name(ddt, type, class, name);
1562 			uint64_t obj;
1563 			error = zap_lookup(spa->spa_meta_objset,
1564 			    DMU_POOL_DIRECTORY_OBJECT, name, sizeof (uint64_t),
1565 			    1, &obj);
1566 			if (error == ENOENT)
1567 				continue;
1568 			if (error != 0)
1569 				return (error);
1570 
1571 			ddt->ddt_version = DDT_VERSION_LEGACY;
1572 			ddt->ddt_flags = ddt_version_flags[ddt->ddt_version];
1573 			ddt->ddt_dir_object = DMU_POOL_DIRECTORY_OBJECT;
1574 
1575 			return (0);
1576 		}
1577 	}
1578 
1579 not_found:
1580 	if (!new)
1581 		return (SET_ERROR(ENOENT));
1582 
1583 	/* Nothing on disk, so set up for the best version we can */
1584 	if (fdt_enabled) {
1585 		ddt->ddt_version = DDT_VERSION_FDT;
1586 		ddt->ddt_flags = ddt_version_flags[ddt->ddt_version];
1587 		ddt->ddt_dir_object = 0; /* create on first use */
1588 	} else {
1589 		ddt->ddt_version = DDT_VERSION_LEGACY;
1590 		ddt->ddt_flags = ddt_version_flags[ddt->ddt_version];
1591 		ddt->ddt_dir_object = DMU_POOL_DIRECTORY_OBJECT;
1592 	}
1593 
1594 	return (0);
1595 }
1596 
1597 static void
1598 ddt_table_alloc_kstats(ddt_t *ddt)
1599 {
1600 	char *mod = kmem_asprintf("zfs/%s", spa_name(ddt->ddt_spa));
1601 	char *name = kmem_asprintf("ddt_stats_%s",
1602 	    zio_checksum_table[ddt->ddt_checksum].ci_name);
1603 
1604 	ddt->ddt_ksp = kstat_create(mod, 0, name, "misc", KSTAT_TYPE_NAMED,
1605 	    sizeof (ddt_kstats_t) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
1606 	if (ddt->ddt_ksp != NULL) {
1607 		ddt_kstats_t *dds = kmem_alloc(sizeof (ddt_kstats_t), KM_SLEEP);
1608 		memcpy(dds, &ddt_kstats_template, sizeof (ddt_kstats_t));
1609 		ddt->ddt_ksp->ks_data = dds;
1610 		kstat_install(ddt->ddt_ksp);
1611 	}
1612 
1613 	kmem_strfree(name);
1614 	kmem_strfree(mod);
1615 }
1616 
1617 static ddt_t *
1618 ddt_table_alloc(spa_t *spa, enum zio_checksum c)
1619 {
1620 	ddt_t *ddt;
1621 
1622 	ddt = kmem_cache_alloc(ddt_cache, KM_SLEEP);
1623 	memset(ddt, 0, sizeof (ddt_t));
1624 	mutex_init(&ddt->ddt_lock, NULL, MUTEX_DEFAULT, NULL);
1625 	avl_create(&ddt->ddt_tree, ddt_key_compare,
1626 	    sizeof (ddt_entry_t), offsetof(ddt_entry_t, dde_node));
1627 	avl_create(&ddt->ddt_repair_tree, ddt_key_compare,
1628 	    sizeof (ddt_entry_t), offsetof(ddt_entry_t, dde_node));
1629 
1630 	ddt->ddt_checksum = c;
1631 	ddt->ddt_spa = spa;
1632 	ddt->ddt_os = spa->spa_meta_objset;
1633 	ddt->ddt_version = DDT_VERSION_UNCONFIGURED;
1634 	ddt->ddt_log_flush_pressure = 10;
1635 
1636 	ddt_log_alloc(ddt);
1637 	ddt_table_alloc_kstats(ddt);
1638 
1639 	return (ddt);
1640 }
1641 
1642 static void
1643 ddt_table_free(ddt_t *ddt)
1644 {
1645 	if (ddt->ddt_ksp != NULL) {
1646 		kmem_free(ddt->ddt_ksp->ks_data, sizeof (ddt_kstats_t));
1647 		ddt->ddt_ksp->ks_data = NULL;
1648 		kstat_delete(ddt->ddt_ksp);
1649 	}
1650 
1651 	ddt_log_free(ddt);
1652 	ASSERT0(avl_numnodes(&ddt->ddt_tree));
1653 	ASSERT0(avl_numnodes(&ddt->ddt_repair_tree));
1654 	avl_destroy(&ddt->ddt_tree);
1655 	avl_destroy(&ddt->ddt_repair_tree);
1656 	mutex_destroy(&ddt->ddt_lock);
1657 	kmem_cache_free(ddt_cache, ddt);
1658 }
1659 
1660 void
1661 ddt_create(spa_t *spa)
1662 {
1663 	spa->spa_dedup_checksum = ZIO_DEDUPCHECKSUM;
1664 
1665 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
1666 		if (DDT_CHECKSUM_VALID(c))
1667 			spa->spa_ddt[c] = ddt_table_alloc(spa, c);
1668 	}
1669 }
1670 
1671 int
1672 ddt_load(spa_t *spa)
1673 {
1674 	int error;
1675 
1676 	ddt_create(spa);
1677 
1678 	error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
1679 	    DMU_POOL_DDT_STATS, sizeof (uint64_t), 1,
1680 	    &spa->spa_ddt_stat_object);
1681 	if (error)
1682 		return (error == ENOENT ? 0 : error);
1683 
1684 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
1685 		if (!DDT_CHECKSUM_VALID(c))
1686 			continue;
1687 
1688 		ddt_t *ddt = spa->spa_ddt[c];
1689 		error = ddt_configure(ddt, B_FALSE);
1690 		if (error == ENOENT)
1691 			continue;
1692 		if (error != 0)
1693 			return (error);
1694 
1695 		for (ddt_type_t type = 0; type < DDT_TYPES; type++) {
1696 			for (ddt_class_t class = 0; class < DDT_CLASSES;
1697 			    class++) {
1698 				error = ddt_object_load(ddt, type, class);
1699 				if (error != 0 && error != ENOENT)
1700 					return (error);
1701 			}
1702 		}
1703 
1704 		error = ddt_log_load(ddt);
1705 		if (error != 0 && error != ENOENT)
1706 			return (error);
1707 
1708 		DDT_KSTAT_SET(ddt, dds_log_active_entries,
1709 		    avl_numnodes(&ddt->ddt_log_active->ddl_tree));
1710 		DDT_KSTAT_SET(ddt, dds_log_flushing_entries,
1711 		    avl_numnodes(&ddt->ddt_log_flushing->ddl_tree));
1712 
1713 		/*
1714 		 * Seed the cached histograms.
1715 		 */
1716 		memcpy(&ddt->ddt_histogram_cache, ddt->ddt_histogram,
1717 		    sizeof (ddt->ddt_histogram));
1718 	}
1719 
1720 	spa->spa_dedup_dspace = ~0ULL;
1721 	spa->spa_dedup_dsize = ~0ULL;
1722 
1723 	return (0);
1724 }
1725 
1726 void
1727 ddt_unload(spa_t *spa)
1728 {
1729 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
1730 		if (spa->spa_ddt[c]) {
1731 			ddt_table_free(spa->spa_ddt[c]);
1732 			spa->spa_ddt[c] = NULL;
1733 		}
1734 	}
1735 }
1736 
1737 boolean_t
1738 ddt_class_contains(spa_t *spa, ddt_class_t max_class, const blkptr_t *bp)
1739 {
1740 	ddt_t *ddt;
1741 	ddt_key_t ddk;
1742 
1743 	if (!BP_GET_DEDUP(bp))
1744 		return (B_FALSE);
1745 
1746 	if (max_class == DDT_CLASS_UNIQUE)
1747 		return (B_TRUE);
1748 
1749 	ddt = spa->spa_ddt[BP_GET_CHECKSUM(bp)];
1750 
1751 	ddt_key_fill(&ddk, bp);
1752 
1753 	for (ddt_type_t type = 0; type < DDT_TYPES; type++) {
1754 		for (ddt_class_t class = 0; class <= max_class; class++) {
1755 			if (ddt_object_contains(ddt, type, class, &ddk) == 0)
1756 				return (B_TRUE);
1757 		}
1758 	}
1759 
1760 	return (B_FALSE);
1761 }
1762 
1763 ddt_entry_t *
1764 ddt_repair_start(ddt_t *ddt, const blkptr_t *bp)
1765 {
1766 	ddt_key_t ddk;
1767 	ddt_entry_t *dde;
1768 
1769 	ddt_key_fill(&ddk, bp);
1770 
1771 	dde = ddt_alloc(ddt, &ddk);
1772 	ddt_alloc_entry_io(dde);
1773 
1774 	for (ddt_type_t type = 0; type < DDT_TYPES; type++) {
1775 		for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {
1776 			/*
1777 			 * We can only do repair if there are multiple copies
1778 			 * of the block.  For anything in the UNIQUE class,
1779 			 * there's definitely only one copy, so don't even try.
1780 			 */
1781 			if (class != DDT_CLASS_UNIQUE &&
1782 			    ddt_object_lookup(ddt, type, class, dde) == 0)
1783 				return (dde);
1784 		}
1785 	}
1786 
1787 	memset(dde->dde_phys, 0, DDT_PHYS_SIZE(ddt));
1788 
1789 	return (dde);
1790 }
1791 
1792 void
1793 ddt_repair_done(ddt_t *ddt, ddt_entry_t *dde)
1794 {
1795 	avl_index_t where;
1796 
1797 	ddt_enter(ddt);
1798 
1799 	if (dde->dde_io->dde_repair_abd != NULL &&
1800 	    spa_writeable(ddt->ddt_spa) &&
1801 	    avl_find(&ddt->ddt_repair_tree, dde, &where) == NULL)
1802 		avl_insert(&ddt->ddt_repair_tree, dde, where);
1803 	else
1804 		ddt_free(ddt, dde);
1805 
1806 	ddt_exit(ddt);
1807 }
1808 
1809 static void
1810 ddt_repair_entry_done(zio_t *zio)
1811 {
1812 	ddt_t *ddt = ddt_select(zio->io_spa, zio->io_bp);
1813 	ddt_entry_t *rdde = zio->io_private;
1814 
1815 	ddt_free(ddt, rdde);
1816 }
1817 
1818 static void
1819 ddt_repair_entry(ddt_t *ddt, ddt_entry_t *dde, ddt_entry_t *rdde, zio_t *rio)
1820 {
1821 	ddt_key_t *ddk = &dde->dde_key;
1822 	ddt_key_t *rddk = &rdde->dde_key;
1823 	zio_t *zio;
1824 	blkptr_t blk;
1825 
1826 	zio = zio_null(rio, rio->io_spa, NULL,
1827 	    ddt_repair_entry_done, rdde, rio->io_flags);
1828 
1829 	for (int p = 0; p < DDT_NPHYS(ddt); p++) {
1830 		ddt_univ_phys_t *ddp = dde->dde_phys;
1831 		ddt_univ_phys_t *rddp = rdde->dde_phys;
1832 		ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);
1833 		uint64_t phys_birth = ddt_phys_birth(ddp, v);
1834 		const dva_t *dvas, *rdvas;
1835 
1836 		if (ddt->ddt_flags & DDT_FLAG_FLAT) {
1837 			dvas = ddp->ddp_flat.ddp_dva;
1838 			rdvas = rddp->ddp_flat.ddp_dva;
1839 		} else {
1840 			dvas = ddp->ddp_trad[p].ddp_dva;
1841 			rdvas = rddp->ddp_trad[p].ddp_dva;
1842 		}
1843 
1844 		if (phys_birth == 0 ||
1845 		    phys_birth != ddt_phys_birth(rddp, v) ||
1846 		    memcmp(dvas, rdvas, sizeof (dva_t) * SPA_DVAS_PER_BP))
1847 			continue;
1848 
1849 		ddt_bp_create(ddt->ddt_checksum, ddk, ddp, v, &blk);
1850 		zio_nowait(zio_rewrite(zio, zio->io_spa, 0, &blk,
1851 		    rdde->dde_io->dde_repair_abd, DDK_GET_PSIZE(rddk),
1852 		    NULL, NULL, ZIO_PRIORITY_SYNC_WRITE,
1853 		    ZIO_DDT_CHILD_FLAGS(zio), NULL));
1854 	}
1855 
1856 	zio_nowait(zio);
1857 }
1858 
1859 static void
1860 ddt_repair_table(ddt_t *ddt, zio_t *rio)
1861 {
1862 	spa_t *spa = ddt->ddt_spa;
1863 	ddt_entry_t *dde, *rdde_next, *rdde;
1864 	avl_tree_t *t = &ddt->ddt_repair_tree;
1865 	blkptr_t blk;
1866 
1867 	if (spa_sync_pass(spa) > 1)
1868 		return;
1869 
1870 	ddt_enter(ddt);
1871 	for (rdde = avl_first(t); rdde != NULL; rdde = rdde_next) {
1872 		rdde_next = AVL_NEXT(t, rdde);
1873 		avl_remove(&ddt->ddt_repair_tree, rdde);
1874 		ddt_exit(ddt);
1875 		ddt_bp_create(ddt->ddt_checksum, &rdde->dde_key, NULL,
1876 		    DDT_PHYS_NONE, &blk);
1877 		dde = ddt_repair_start(ddt, &blk);
1878 		ddt_repair_entry(ddt, dde, rdde, rio);
1879 		ddt_repair_done(ddt, dde);
1880 		ddt_enter(ddt);
1881 	}
1882 	ddt_exit(ddt);
1883 }
1884 
1885 static void
1886 ddt_sync_update_stats(ddt_t *ddt, dmu_tx_t *tx)
1887 {
1888 	/*
1889 	 * Count all the entries stored for each type/class, and updates the
1890 	 * stats within (ddt_object_sync()). If there's no entries for the
1891 	 * type/class, the whole object is removed. If all objects for the DDT
1892 	 * are removed, its containing dir is removed, effectively resetting
1893 	 * the entire DDT to an empty slate.
1894 	 */
1895 	uint64_t count = 0;
1896 	for (ddt_type_t type = 0; type < DDT_TYPES; type++) {
1897 		uint64_t add, tcount = 0;
1898 		for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {
1899 			if (ddt_object_exists(ddt, type, class)) {
1900 				ddt_object_sync(ddt, type, class, tx);
1901 				VERIFY0(ddt_object_count(ddt, type, class,
1902 				    &add));
1903 				tcount += add;
1904 			}
1905 		}
1906 		for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {
1907 			if (tcount == 0 && ddt_object_exists(ddt, type, class))
1908 				ddt_object_destroy(ddt, type, class, tx);
1909 		}
1910 		count += tcount;
1911 	}
1912 
1913 	if (ddt->ddt_flags & DDT_FLAG_LOG) {
1914 		/* Include logged entries in the total count */
1915 		count += avl_numnodes(&ddt->ddt_log_active->ddl_tree);
1916 		count += avl_numnodes(&ddt->ddt_log_flushing->ddl_tree);
1917 	}
1918 
1919 	if (count == 0) {
1920 		/*
1921 		 * No entries left on the DDT, so reset the version for next
1922 		 * time. This allows us to handle the feature being changed
1923 		 * since the DDT was originally created. New entries should get
1924 		 * whatever the feature currently demands.
1925 		 */
1926 		if (ddt->ddt_version == DDT_VERSION_FDT)
1927 			ddt_destroy_dir(ddt, tx);
1928 
1929 		ddt->ddt_version = DDT_VERSION_UNCONFIGURED;
1930 		ddt->ddt_flags = 0;
1931 	}
1932 
1933 	memcpy(&ddt->ddt_histogram_cache, ddt->ddt_histogram,
1934 	    sizeof (ddt->ddt_histogram));
1935 	ddt->ddt_spa->spa_dedup_dspace = ~0ULL;
1936 	ddt->ddt_spa->spa_dedup_dsize = ~0ULL;
1937 }
1938 
1939 static void
1940 ddt_sync_scan_entry(ddt_t *ddt, ddt_lightweight_entry_t *ddlwe, dmu_tx_t *tx)
1941 {
1942 	dsl_pool_t *dp = ddt->ddt_spa->spa_dsl_pool;
1943 
1944 	/*
1945 	 * Compute the target class, so we can decide whether or not to inform
1946 	 * the scrub traversal (below). Note that we don't store this in the
1947 	 * entry, as it might change multiple times before finally being
1948 	 * committed (if we're logging). Instead, we recompute it in
1949 	 * ddt_sync_entry().
1950 	 */
1951 	uint64_t refcnt = ddt_phys_total_refcnt(ddt, &ddlwe->ddlwe_phys);
1952 	ddt_class_t nclass =
1953 	    (refcnt > 1) ? DDT_CLASS_DUPLICATE : DDT_CLASS_UNIQUE;
1954 
1955 	/*
1956 	 * If the class changes, the order that we scan this bp changes. If it
1957 	 * decreases, we could miss it, so scan it right now. (This covers both
1958 	 * class changing while we are doing ddt_walk(), and when we are
1959 	 * traversing.)
1960 	 *
1961 	 * We also do this when the refcnt goes to zero, because that change is
1962 	 * only in the log so far; the blocks on disk won't be freed until
1963 	 * the log is flushed, and the refcnt might increase before that. If it
1964 	 * does, then we could miss it in the same way.
1965 	 */
1966 	if (refcnt == 0 || nclass < ddlwe->ddlwe_class)
1967 		dsl_scan_ddt_entry(dp->dp_scan, ddt->ddt_checksum, ddt,
1968 		    ddlwe, tx);
1969 }
1970 
1971 static void
1972 ddt_sync_flush_entry(ddt_t *ddt, ddt_lightweight_entry_t *ddlwe,
1973     ddt_type_t otype, ddt_class_t oclass, dmu_tx_t *tx)
1974 {
1975 	ddt_key_t *ddk = &ddlwe->ddlwe_key;
1976 	ddt_type_t ntype = DDT_TYPE_DEFAULT;
1977 	uint64_t refcnt = 0;
1978 
1979 	/*
1980 	 * Compute the total refcnt. Along the way, issue frees for any DVAs
1981 	 * we no longer want.
1982 	 */
1983 	for (int p = 0; p < DDT_NPHYS(ddt); p++) {
1984 		ddt_univ_phys_t *ddp = &ddlwe->ddlwe_phys;
1985 		ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);
1986 		uint64_t phys_refcnt = ddt_phys_refcnt(ddp, v);
1987 
1988 		if (ddt_phys_birth(ddp, v) == 0) {
1989 			ASSERT0(phys_refcnt);
1990 			continue;
1991 		}
1992 		if (DDT_PHYS_IS_DITTO(ddt, p)) {
1993 			/*
1994 			 * We don't want to keep any obsolete slots (eg ditto),
1995 			 * regardless of their refcount, but we don't want to
1996 			 * leak them either. So, free them.
1997 			 */
1998 			ddt_phys_free(ddt, ddk, ddp, v, tx->tx_txg);
1999 			continue;
2000 		}
2001 		if (phys_refcnt == 0)
2002 			/* No remaining references, free it! */
2003 			ddt_phys_free(ddt, ddk, ddp, v, tx->tx_txg);
2004 		refcnt += phys_refcnt;
2005 	}
2006 
2007 	/* Select the best class for the entry. */
2008 	ddt_class_t nclass =
2009 	    (refcnt > 1) ? DDT_CLASS_DUPLICATE : DDT_CLASS_UNIQUE;
2010 
2011 	/*
2012 	 * If an existing entry changed type or class, or its refcount reached
2013 	 * zero, delete it from the DDT object
2014 	 */
2015 	if (otype != DDT_TYPES &&
2016 	    (otype != ntype || oclass != nclass || refcnt == 0)) {
2017 		VERIFY0(ddt_object_remove(ddt, otype, oclass, ddk, tx));
2018 		ASSERT(ddt_object_contains(ddt, otype, oclass, ddk) == ENOENT);
2019 	}
2020 
2021 	/*
2022 	 * Add or update the entry
2023 	 */
2024 	if (refcnt != 0) {
2025 		ddt_histogram_t *ddh =
2026 		    &ddt->ddt_histogram[ntype][nclass];
2027 
2028 		ddt_histogram_add_entry(ddt, ddh, ddlwe);
2029 
2030 		if (!ddt_object_exists(ddt, ntype, nclass))
2031 			ddt_object_create(ddt, ntype, nclass, tx);
2032 		VERIFY0(ddt_object_update(ddt, ntype, nclass, ddlwe, tx));
2033 	}
2034 }
2035 
2036 /* Calculate an exponential weighted moving average, lower limited to zero */
2037 static inline int32_t
2038 _ewma(int32_t val, int32_t prev, uint32_t weight)
2039 {
2040 	ASSERT3U(val, >=, 0);
2041 	ASSERT3U(prev, >=, 0);
2042 	const int32_t new =
2043 	    MAX(0, prev + (val-prev) / (int32_t)MAX(weight, 1));
2044 	ASSERT3U(new, >=, 0);
2045 	return (new);
2046 }
2047 
2048 static inline void
2049 ddt_flush_force_update_txg(ddt_t *ddt, uint64_t txg)
2050 {
2051 	/*
2052 	 * If we're not forcing flush, and not being asked to start, then
2053 	 * there's nothing more to do.
2054 	 */
2055 	if (txg == 0) {
2056 		/* Update requested, are we currently forcing flush? */
2057 		if (ddt->ddt_flush_force_txg == 0)
2058 			return;
2059 		txg = ddt->ddt_flush_force_txg;
2060 	}
2061 
2062 	/*
2063 	 * If either of the logs have entries unflushed entries before
2064 	 * the wanted txg, set the force txg, otherwise clear it.
2065 	 */
2066 
2067 	if ((!avl_is_empty(&ddt->ddt_log_active->ddl_tree) &&
2068 	    ddt->ddt_log_active->ddl_first_txg <= txg) ||
2069 	    (!avl_is_empty(&ddt->ddt_log_flushing->ddl_tree) &&
2070 	    ddt->ddt_log_flushing->ddl_first_txg <= txg)) {
2071 		ddt->ddt_flush_force_txg = txg;
2072 		return;
2073 	}
2074 
2075 	/*
2076 	 * Nothing to flush behind the given txg, so we can clear force flush
2077 	 * state.
2078 	 */
2079 	ddt->ddt_flush_force_txg = 0;
2080 }
2081 
2082 static void
2083 ddt_sync_flush_log(ddt_t *ddt, dmu_tx_t *tx)
2084 {
2085 	spa_t *spa = ddt->ddt_spa;
2086 	ASSERT(avl_is_empty(&ddt->ddt_tree));
2087 
2088 	/*
2089 	 * Don't do any flushing when the pool is ready to shut down, or in
2090 	 * passes beyond the first.
2091 	 */
2092 	if (spa_sync_pass(spa) > 1 || tx->tx_txg > spa_final_dirty_txg(spa))
2093 		return;
2094 
2095 	hrtime_t flush_start = gethrtime();
2096 	uint32_t count = 0;
2097 
2098 	/*
2099 	 * How many entries we need to flush. We need to at
2100 	 * least match the ingest rate, and also consider the
2101 	 * current backlog of entries.
2102 	 */
2103 	uint64_t backlog = avl_numnodes(&ddt->ddt_log_flushing->ddl_tree) +
2104 	    avl_numnodes(&ddt->ddt_log_active->ddl_tree);
2105 
2106 	if (avl_is_empty(&ddt->ddt_log_flushing->ddl_tree))
2107 		goto housekeeping;
2108 
2109 	uint64_t txgs = MAX(1, zfs_dedup_log_flush_txgs);
2110 	uint64_t cap = MAX(1, zfs_dedup_log_cap);
2111 	uint64_t flush_min = MAX(backlog / txgs,
2112 	    zfs_dedup_log_flush_entries_min);
2113 
2114 	/*
2115 	 * The theory for this block is that if we increase the pressure while
2116 	 * we're growing above the cap, and remove it when we're significantly
2117 	 * below the cap, we'll stay near cap while not bouncing around too
2118 	 * much.
2119 	 *
2120 	 * The factor of 10 is to smooth the pressure effect by expressing it
2121 	 * in tenths. The addition of the cap to the backlog in the second
2122 	 * block is to round up, instead of down. We never let the pressure go
2123 	 * below 1 (10 tenths).
2124 	 */
2125 	if (cap != UINT_MAX && backlog > cap &&
2126 	    backlog > ddt->ddt_log_flush_prev_backlog) {
2127 		ddt->ddt_log_flush_pressure += 10 * backlog / cap;
2128 	} else if (cap != UINT_MAX && backlog < cap) {
2129 		ddt->ddt_log_flush_pressure -=
2130 		    11 - (((10 * backlog) + cap - 1) / cap);
2131 		ddt->ddt_log_flush_pressure =
2132 		    MAX(ddt->ddt_log_flush_pressure, 10);
2133 	}
2134 
2135 	if (zfs_dedup_log_hard_cap && cap != UINT_MAX)
2136 		flush_min = MAX(flush_min, MIN(backlog - cap,
2137 		    (flush_min * ddt->ddt_log_flush_pressure) / 10));
2138 
2139 	uint64_t flush_max;
2140 
2141 	/*
2142 	 * If we've been asked to flush everything in a hurry,
2143 	 * try to dump as much as possible on this txg. In
2144 	 * this case we're only limited by time, not amount.
2145 	 *
2146 	 * Otherwise, if we are over the cap, try to get back down to it.
2147 	 *
2148 	 * Finally if there is no cap (or no pressure), just set the max a
2149 	 * little higher than the min to help smooth out variations in flush
2150 	 * times.
2151 	 */
2152 	if (ddt->ddt_flush_force_txg > 0)
2153 		flush_max = avl_numnodes(&ddt->ddt_log_flushing->ddl_tree);
2154 	else if (cap != UINT32_MAX && !zfs_dedup_log_hard_cap)
2155 		flush_max = MAX(flush_min * 5 / 4, MIN(backlog - cap,
2156 		    (flush_min * ddt->ddt_log_flush_pressure) / 10));
2157 	else
2158 		flush_max = flush_min * 5 / 4;
2159 	flush_max = MIN(flush_max, zfs_dedup_log_flush_entries_max);
2160 
2161 	/*
2162 	 * When the pool is busy or someone is explicitly waiting for this txg
2163 	 * to complete, use the zfs_dedup_log_flush_min_time_ms.  Otherwise use
2164 	 * half of the time in the txg timeout.
2165 	 */
2166 	uint64_t target_time;
2167 
2168 	if (txg_sync_waiting(ddt->ddt_spa->spa_dsl_pool) ||
2169 	    vdev_queue_pool_busy(spa)) {
2170 		target_time = MIN(MSEC2NSEC(zfs_dedup_log_flush_min_time_ms),
2171 		    SEC2NSEC(zfs_txg_timeout) / 2);
2172 	} else {
2173 		target_time = SEC2NSEC(zfs_txg_timeout) / 2;
2174 	}
2175 
2176 	ddt_lightweight_entry_t ddlwe;
2177 	while (ddt_log_take_first(ddt, ddt->ddt_log_flushing, &ddlwe)) {
2178 		ddt_sync_flush_entry(ddt, &ddlwe,
2179 		    ddlwe.ddlwe_type, ddlwe.ddlwe_class, tx);
2180 
2181 		/* End if we've synced as much as we needed to. */
2182 		if (++count >= flush_max)
2183 			break;
2184 
2185 		/*
2186 		 * As long as we've flushed the absolute minimum,
2187 		 * stop if we're way over our target time.
2188 		 */
2189 		uint64_t diff = gethrtime() - flush_start;
2190 		if (count > zfs_dedup_log_flush_entries_min &&
2191 		    diff >= target_time * 2)
2192 			break;
2193 
2194 		/*
2195 		 * End if we've passed the minimum flush and we're out of time.
2196 		 */
2197 		if (count > flush_min && diff >= target_time)
2198 			break;
2199 	}
2200 
2201 	if (avl_is_empty(&ddt->ddt_log_flushing->ddl_tree)) {
2202 		/* We emptied it, so truncate on-disk */
2203 		DDT_KSTAT_ZERO(ddt, dds_log_flushing_entries);
2204 		ddt_log_truncate(ddt, tx);
2205 	} else {
2206 		/* More to do next time, save checkpoint */
2207 		DDT_KSTAT_SUB(ddt, dds_log_flushing_entries, count);
2208 		ddt_log_checkpoint(ddt, &ddlwe, tx);
2209 	}
2210 
2211 	ddt_sync_update_stats(ddt, tx);
2212 
2213 housekeeping:
2214 	if (avl_is_empty(&ddt->ddt_log_flushing->ddl_tree) &&
2215 	    !avl_is_empty(&ddt->ddt_log_active->ddl_tree)) {
2216 		/*
2217 		 * No more to flush, and the active list has stuff, so
2218 		 * try to swap the logs for next time.
2219 		 */
2220 		if (ddt_log_swap(ddt, tx)) {
2221 			DDT_KSTAT_ZERO(ddt, dds_log_active_entries);
2222 			DDT_KSTAT_SET(ddt, dds_log_flushing_entries,
2223 			    avl_numnodes(&ddt->ddt_log_flushing->ddl_tree));
2224 		}
2225 	}
2226 
2227 	/* If force flush is no longer necessary, turn it off. */
2228 	ddt_flush_force_update_txg(ddt, 0);
2229 
2230 	ddt->ddt_log_flush_prev_backlog = backlog;
2231 
2232 	/*
2233 	 * Update flush rate. This is an exponential weighted moving
2234 	 * average of the number of entries flushed over recent txgs.
2235 	 */
2236 	ddt->ddt_log_flush_rate = _ewma(count, ddt->ddt_log_flush_rate,
2237 	    zfs_dedup_log_flush_flow_rate_txgs);
2238 	DDT_KSTAT_SET(ddt, dds_log_flush_rate, ddt->ddt_log_flush_rate);
2239 
2240 	/*
2241 	 * Update flush time rate. This is an exponential weighted moving
2242 	 * average of the total time taken to flush over recent txgs.
2243 	 */
2244 	ddt->ddt_log_flush_time_rate = _ewma(ddt->ddt_log_flush_time_rate,
2245 	    (int32_t)NSEC2MSEC(gethrtime() - flush_start),
2246 	    zfs_dedup_log_flush_flow_rate_txgs);
2247 	DDT_KSTAT_SET(ddt, dds_log_flush_time_rate,
2248 	    ddt->ddt_log_flush_time_rate);
2249 	if (avl_numnodes(&ddt->ddt_log_flushing->ddl_tree) > 0 &&
2250 	    zfs_flags & ZFS_DEBUG_DDT) {
2251 		zfs_dbgmsg("%lu entries remain(%lu in active), flushed %u @ "
2252 		    "txg %llu, in %llu ms, flush rate %d, time rate %d",
2253 		    (ulong_t)avl_numnodes(&ddt->ddt_log_flushing->ddl_tree),
2254 		    (ulong_t)avl_numnodes(&ddt->ddt_log_active->ddl_tree),
2255 		    count, (u_longlong_t)tx->tx_txg,
2256 		    (u_longlong_t)NSEC2MSEC(gethrtime() - flush_start),
2257 		    ddt->ddt_log_flush_rate, ddt->ddt_log_flush_time_rate);
2258 	}
2259 }
2260 
2261 static void
2262 ddt_sync_table_log(ddt_t *ddt, dmu_tx_t *tx)
2263 {
2264 	uint64_t count = avl_numnodes(&ddt->ddt_tree);
2265 
2266 	if (count > 0) {
2267 		ddt_log_update_t dlu = {0};
2268 		ddt_log_begin(ddt, count, tx, &dlu);
2269 
2270 		ddt_entry_t *dde;
2271 		void *cookie = NULL;
2272 		ddt_lightweight_entry_t ddlwe;
2273 		while ((dde =
2274 		    avl_destroy_nodes(&ddt->ddt_tree, &cookie)) != NULL) {
2275 			ASSERT(dde->dde_flags & DDE_FLAG_LOADED);
2276 			DDT_ENTRY_TO_LIGHTWEIGHT(ddt, dde, &ddlwe);
2277 			ddt_log_entry(ddt, &ddlwe, &dlu);
2278 			ddt_sync_scan_entry(ddt, &ddlwe, tx);
2279 			ddt_free(ddt, dde);
2280 		}
2281 
2282 		ddt_log_commit(ddt, &dlu);
2283 
2284 		DDT_KSTAT_SET(ddt, dds_log_active_entries,
2285 		    avl_numnodes(&ddt->ddt_log_active->ddl_tree));
2286 
2287 		/*
2288 		 * Sync the stats for the store objects. Even though we haven't
2289 		 * modified anything on those objects, they're no longer the
2290 		 * source of truth for entries that are now in the log, and we
2291 		 * need the on-disk counts to reflect that, otherwise we'll
2292 		 * miscount later when importing.
2293 		 */
2294 		for (ddt_type_t type = 0; type < DDT_TYPES; type++) {
2295 			for (ddt_class_t class = 0;
2296 			    class < DDT_CLASSES; class++) {
2297 				if (ddt_object_exists(ddt, type, class))
2298 					ddt_object_sync(ddt, type, class, tx);
2299 			}
2300 		}
2301 
2302 		memcpy(&ddt->ddt_histogram_cache, ddt->ddt_histogram,
2303 		    sizeof (ddt->ddt_histogram));
2304 		ddt->ddt_spa->spa_dedup_dspace = ~0ULL;
2305 		ddt->ddt_spa->spa_dedup_dsize = ~0ULL;
2306 	}
2307 
2308 	if (spa_sync_pass(ddt->ddt_spa) == 1) {
2309 		/*
2310 		 * Update ingest rate. This is an exponential weighted moving
2311 		 * average of the number of entries changed over recent txgs.
2312 		 * The ramp-up cost shouldn't matter too much because the
2313 		 * flusher will be trying to take at least the minimum anyway.
2314 		 */
2315 		ddt->ddt_log_ingest_rate = _ewma(
2316 		    count, ddt->ddt_log_ingest_rate,
2317 		    zfs_dedup_log_flush_flow_rate_txgs);
2318 		DDT_KSTAT_SET(ddt, dds_log_ingest_rate,
2319 		    ddt->ddt_log_ingest_rate);
2320 	}
2321 }
2322 
2323 static void
2324 ddt_sync_table_flush(ddt_t *ddt, dmu_tx_t *tx)
2325 {
2326 	if (avl_numnodes(&ddt->ddt_tree) == 0)
2327 		return;
2328 
2329 	ddt_entry_t *dde;
2330 	void *cookie = NULL;
2331 	while ((dde = avl_destroy_nodes(
2332 	    &ddt->ddt_tree, &cookie)) != NULL) {
2333 		ASSERT(dde->dde_flags & DDE_FLAG_LOADED);
2334 
2335 		ddt_lightweight_entry_t ddlwe;
2336 		DDT_ENTRY_TO_LIGHTWEIGHT(ddt, dde, &ddlwe);
2337 		ddt_sync_flush_entry(ddt, &ddlwe,
2338 		    dde->dde_type, dde->dde_class, tx);
2339 		ddt_sync_scan_entry(ddt, &ddlwe, tx);
2340 		ddt_free(ddt, dde);
2341 	}
2342 
2343 	memcpy(&ddt->ddt_histogram_cache, ddt->ddt_histogram,
2344 	    sizeof (ddt->ddt_histogram));
2345 	ddt->ddt_spa->spa_dedup_dspace = ~0ULL;
2346 	ddt->ddt_spa->spa_dedup_dsize = ~0ULL;
2347 	ddt_sync_update_stats(ddt, tx);
2348 }
2349 
2350 static void
2351 ddt_sync_table(ddt_t *ddt, dmu_tx_t *tx)
2352 {
2353 	spa_t *spa = ddt->ddt_spa;
2354 
2355 	if (ddt->ddt_version == UINT64_MAX)
2356 		return;
2357 
2358 	if (spa->spa_uberblock.ub_version < SPA_VERSION_DEDUP) {
2359 		ASSERT0(avl_numnodes(&ddt->ddt_tree));
2360 		return;
2361 	}
2362 
2363 	if (spa->spa_ddt_stat_object == 0) {
2364 		spa->spa_ddt_stat_object = zap_create_link(ddt->ddt_os,
2365 		    DMU_OT_DDT_STATS, DMU_POOL_DIRECTORY_OBJECT,
2366 		    DMU_POOL_DDT_STATS, tx);
2367 	}
2368 
2369 	if (ddt->ddt_version == DDT_VERSION_FDT && ddt->ddt_dir_object == 0)
2370 		ddt_create_dir(ddt, tx);
2371 
2372 	if (ddt->ddt_flags & DDT_FLAG_LOG)
2373 		ddt_sync_table_log(ddt, tx);
2374 	else
2375 		ddt_sync_table_flush(ddt, tx);
2376 }
2377 
2378 void
2379 ddt_sync(spa_t *spa, uint64_t txg)
2380 {
2381 	dsl_scan_t *scn = spa->spa_dsl_pool->dp_scan;
2382 	dmu_tx_t *tx;
2383 	zio_t *rio;
2384 
2385 	ASSERT3U(spa_syncing_txg(spa), ==, txg);
2386 
2387 	tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
2388 
2389 	rio = zio_root(spa, NULL, NULL,
2390 	    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE | ZIO_FLAG_SELF_HEAL);
2391 
2392 	/*
2393 	 * This function may cause an immediate scan of ddt blocks (see
2394 	 * the comment above dsl_scan_ddt() for details). We set the
2395 	 * scan's root zio here so that we can wait for any scan IOs in
2396 	 * addition to the regular ddt IOs.
2397 	 */
2398 	ASSERT3P(scn->scn_zio_root, ==, NULL);
2399 	scn->scn_zio_root = rio;
2400 
2401 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
2402 		ddt_t *ddt = spa->spa_ddt[c];
2403 		if (ddt == NULL)
2404 			continue;
2405 		ddt_sync_table(ddt, tx);
2406 		if (ddt->ddt_flags & DDT_FLAG_LOG)
2407 			ddt_sync_flush_log(ddt, tx);
2408 		ddt_repair_table(ddt, rio);
2409 	}
2410 
2411 	(void) zio_wait(rio);
2412 	scn->scn_zio_root = NULL;
2413 
2414 	dmu_tx_commit(tx);
2415 }
2416 
2417 void
2418 ddt_walk_init(spa_t *spa, uint64_t txg)
2419 {
2420 	if (txg == 0)
2421 		txg = spa_syncing_txg(spa);
2422 
2423 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
2424 		ddt_t *ddt = spa->spa_ddt[c];
2425 		if (ddt == NULL || !(ddt->ddt_flags & DDT_FLAG_LOG))
2426 			continue;
2427 
2428 		ddt_enter(ddt);
2429 		ddt_flush_force_update_txg(ddt, txg);
2430 		ddt_exit(ddt);
2431 	}
2432 }
2433 
2434 boolean_t
2435 ddt_walk_ready(spa_t *spa)
2436 {
2437 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
2438 		ddt_t *ddt = spa->spa_ddt[c];
2439 		if (ddt == NULL || !(ddt->ddt_flags & DDT_FLAG_LOG))
2440 			continue;
2441 
2442 		if (ddt->ddt_flush_force_txg > 0)
2443 			return (B_FALSE);
2444 	}
2445 
2446 	return (B_TRUE);
2447 }
2448 
2449 static int
2450 ddt_walk_impl(spa_t *spa, ddt_bookmark_t *ddb, ddt_lightweight_entry_t *ddlwe,
2451     uint64_t flags, boolean_t wait)
2452 {
2453 	do {
2454 		do {
2455 			do {
2456 				ddt_t *ddt = spa->spa_ddt[ddb->ddb_checksum];
2457 				if (ddt == NULL)
2458 					continue;
2459 
2460 				if (flags != 0 &&
2461 				    (ddt->ddt_flags & flags) != flags)
2462 					continue;
2463 
2464 				if (wait && ddt->ddt_flush_force_txg > 0)
2465 					return (EAGAIN);
2466 
2467 				int error = ENOENT;
2468 				if (ddt_object_exists(ddt, ddb->ddb_type,
2469 				    ddb->ddb_class)) {
2470 					error = ddt_object_walk(ddt,
2471 					    ddb->ddb_type, ddb->ddb_class,
2472 					    &ddb->ddb_cursor, ddlwe);
2473 				}
2474 				if (error == 0)
2475 					return (0);
2476 				if (error != ENOENT)
2477 					return (error);
2478 				ddb->ddb_cursor = 0;
2479 			} while (++ddb->ddb_checksum < ZIO_CHECKSUM_FUNCTIONS);
2480 			ddb->ddb_checksum = 0;
2481 		} while (++ddb->ddb_type < DDT_TYPES);
2482 		ddb->ddb_type = 0;
2483 	} while (++ddb->ddb_class < DDT_CLASSES);
2484 
2485 	return (SET_ERROR(ENOENT));
2486 }
2487 
2488 int
2489 ddt_walk(spa_t *spa, ddt_bookmark_t *ddb, ddt_lightweight_entry_t *ddlwe)
2490 {
2491 	return (ddt_walk_impl(spa, ddb, ddlwe, 0, B_TRUE));
2492 }
2493 
2494 /*
2495  * This function is used by Block Cloning (brt.c) to increase reference
2496  * counter for the DDT entry if the block is already in DDT.
2497  *
2498  * Return false if the block, despite having the D bit set, is not present
2499  * in the DDT. This is possible when the DDT has been pruned by an admin
2500  * or by the DDT quota mechanism.
2501  */
2502 boolean_t
2503 ddt_addref(spa_t *spa, const blkptr_t *bp)
2504 {
2505 	ddt_t *ddt;
2506 	ddt_entry_t *dde;
2507 	boolean_t result;
2508 
2509 	spa_config_enter(spa, SCL_ZIO, FTAG, RW_READER);
2510 	ddt = ddt_select(spa, bp);
2511 	ddt_enter(ddt);
2512 
2513 	dde = ddt_lookup(ddt, bp, B_TRUE);
2514 
2515 	/* Can be NULL if the entry for this block was pruned. */
2516 	if (dde == NULL) {
2517 		ddt_exit(ddt);
2518 		spa_config_exit(spa, SCL_ZIO, FTAG);
2519 		return (B_FALSE);
2520 	}
2521 
2522 	if ((dde->dde_type < DDT_TYPES) || (dde->dde_flags & DDE_FLAG_LOGGED)) {
2523 		/*
2524 		 * This entry was either synced to a store object (dde_type is
2525 		 * real) or was logged. It must be properly on disk at this
2526 		 * point, so we can just bump its refcount.
2527 		 */
2528 		int p = DDT_PHYS_FOR_COPIES(ddt, BP_GET_NDVAS(bp));
2529 		ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);
2530 
2531 		ddt_phys_addref(dde->dde_phys, v);
2532 		result = B_TRUE;
2533 	} else {
2534 		/*
2535 		 * If the block has the DEDUP flag set it still might not
2536 		 * exist in the DEDUP table due to DDT pruning of entries
2537 		 * where refcnt=1.
2538 		 */
2539 		ddt_remove(ddt, dde);
2540 		result = B_FALSE;
2541 	}
2542 
2543 	ddt_exit(ddt);
2544 	spa_config_exit(spa, SCL_ZIO, FTAG);
2545 
2546 	return (result);
2547 }
2548 
2549 typedef struct ddt_prune_entry {
2550 	ddt_t		*dpe_ddt;
2551 	ddt_key_t	dpe_key;
2552 	list_node_t	dpe_node;
2553 	ddt_univ_phys_t	dpe_phys[];
2554 } ddt_prune_entry_t;
2555 
2556 typedef struct ddt_prune_info {
2557 	spa_t		*dpi_spa;
2558 	uint64_t	dpi_txg_syncs;
2559 	uint64_t	dpi_pruned;
2560 	list_t		dpi_candidates;
2561 } ddt_prune_info_t;
2562 
2563 /*
2564  * Add prune candidates for ddt_sync during spa_sync
2565  */
2566 static void
2567 prune_candidates_sync(void *arg, dmu_tx_t *tx)
2568 {
2569 	(void) tx;
2570 	ddt_prune_info_t *dpi = arg;
2571 	ddt_prune_entry_t *dpe;
2572 
2573 	spa_config_enter(dpi->dpi_spa, SCL_ZIO, FTAG, RW_READER);
2574 
2575 	/* Process the prune candidates collected so far */
2576 	while ((dpe = list_remove_head(&dpi->dpi_candidates)) != NULL) {
2577 		blkptr_t blk;
2578 		ddt_t *ddt = dpe->dpe_ddt;
2579 
2580 		ddt_enter(ddt);
2581 
2582 		/*
2583 		 * If it's on the live list, then it was loaded for update
2584 		 * this txg and is no longer stale; skip it.
2585 		 */
2586 		if (avl_find(&ddt->ddt_tree, &dpe->dpe_key, NULL)) {
2587 			ddt_exit(ddt);
2588 			kmem_free(dpe, sizeof (*dpe));
2589 			continue;
2590 		}
2591 
2592 		ddt_bp_create(ddt->ddt_checksum, &dpe->dpe_key,
2593 		    dpe->dpe_phys, DDT_PHYS_FLAT, &blk);
2594 
2595 		ddt_entry_t *dde = ddt_lookup(ddt, &blk, B_TRUE);
2596 		if (dde != NULL && !(dde->dde_flags & DDE_FLAG_LOGGED)) {
2597 			ASSERT(dde->dde_flags & DDE_FLAG_LOADED);
2598 			/*
2599 			 * Zero the physical, so we don't try to free DVAs
2600 			 * at flush nor try to reuse this entry.
2601 			 */
2602 			ddt_phys_clear(dde->dde_phys, DDT_PHYS_FLAT);
2603 
2604 			dpi->dpi_pruned++;
2605 		}
2606 
2607 		ddt_exit(ddt);
2608 		kmem_free(dpe, sizeof (*dpe));
2609 	}
2610 
2611 	spa_config_exit(dpi->dpi_spa, SCL_ZIO, FTAG);
2612 	dpi->dpi_txg_syncs++;
2613 }
2614 
2615 /*
2616  * Prune candidates are collected in open context and processed
2617  * in sync context as part of ddt_sync_table().
2618  */
2619 static void
2620 ddt_prune_entry(list_t *list, ddt_t *ddt, const ddt_key_t *ddk,
2621     const ddt_univ_phys_t *ddp)
2622 {
2623 	ASSERT(ddt->ddt_flags & DDT_FLAG_FLAT);
2624 
2625 	size_t dpe_size = sizeof (ddt_prune_entry_t) + DDT_FLAT_PHYS_SIZE;
2626 	ddt_prune_entry_t *dpe = kmem_alloc(dpe_size, KM_SLEEP);
2627 
2628 	dpe->dpe_ddt = ddt;
2629 	dpe->dpe_key = *ddk;
2630 	memcpy(dpe->dpe_phys, ddp, DDT_FLAT_PHYS_SIZE);
2631 	list_insert_head(list, dpe);
2632 }
2633 
2634 /*
2635  * Interate over all the entries in the DDT unique class.
2636  * The walk will perform one of the following operations:
2637  *  (a) build a histogram than can be used when pruning
2638  *  (b) prune entries older than the cutoff
2639  *
2640  *  Also called by zdb(8) to dump the age histogram
2641  */
2642 void
2643 ddt_prune_walk(spa_t *spa, uint64_t cutoff, ddt_age_histo_t *histogram)
2644 {
2645 	ddt_bookmark_t ddb = {
2646 		.ddb_class = DDT_CLASS_UNIQUE,
2647 		.ddb_type = 0,
2648 		.ddb_checksum = 0,
2649 		.ddb_cursor = 0
2650 	};
2651 	ddt_lightweight_entry_t ddlwe = {0};
2652 	int error;
2653 	int valid = 0;
2654 	int candidates = 0;
2655 	uint64_t now = gethrestime_sec();
2656 	ddt_prune_info_t dpi;
2657 	boolean_t pruning = (cutoff != 0);
2658 
2659 	if (pruning) {
2660 		dpi.dpi_txg_syncs = 0;
2661 		dpi.dpi_pruned = 0;
2662 		dpi.dpi_spa = spa;
2663 		list_create(&dpi.dpi_candidates, sizeof (ddt_prune_entry_t),
2664 		    offsetof(ddt_prune_entry_t, dpe_node));
2665 	}
2666 
2667 	if (histogram != NULL)
2668 		memset(histogram, 0, sizeof (ddt_age_histo_t));
2669 
2670 	while ((error =
2671 	    ddt_walk_impl(spa, &ddb, &ddlwe, DDT_FLAG_FLAT, B_FALSE)) == 0) {
2672 		ddt_t *ddt = spa->spa_ddt[ddb.ddb_checksum];
2673 		VERIFY(ddt);
2674 
2675 		if (spa_shutting_down(spa) || issig())
2676 			break;
2677 
2678 		ASSERT(ddt->ddt_flags & DDT_FLAG_FLAT);
2679 		ASSERT3U(ddlwe.ddlwe_phys.ddp_flat.ddp_refcnt, <=, 1);
2680 
2681 		uint64_t class_start =
2682 		    ddlwe.ddlwe_phys.ddp_flat.ddp_class_start;
2683 
2684 		/*
2685 		 * If this entry is on the log, then the stored entry is stale
2686 		 * and we should skip it.
2687 		 */
2688 		if (ddt_log_find_key(ddt, &ddlwe.ddlwe_key, NULL))
2689 			continue;
2690 
2691 		/* prune older entries */
2692 		if (pruning && class_start < cutoff) {
2693 			if (candidates++ >= zfs_ddt_prunes_per_txg) {
2694 				/* sync prune candidates in batches */
2695 				VERIFY0(dsl_sync_task(spa_name(spa),
2696 				    NULL, prune_candidates_sync,
2697 				    &dpi, 0, ZFS_SPACE_CHECK_NONE));
2698 				candidates = 1;
2699 			}
2700 			ddt_prune_entry(&dpi.dpi_candidates, ddt,
2701 			    &ddlwe.ddlwe_key, &ddlwe.ddlwe_phys);
2702 		}
2703 
2704 		/* build a histogram */
2705 		if (histogram != NULL) {
2706 			uint64_t age = MAX(1, (now - class_start) / 3600);
2707 			int bin = MIN(highbit64(age) - 1, HIST_BINS - 1);
2708 			histogram->dah_entries++;
2709 			histogram->dah_age_histo[bin]++;
2710 		}
2711 
2712 		valid++;
2713 	}
2714 
2715 	if (pruning && valid > 0) {
2716 		if (!list_is_empty(&dpi.dpi_candidates)) {
2717 			/* sync out final batch of prune candidates */
2718 			VERIFY0(dsl_sync_task(spa_name(spa), NULL,
2719 			    prune_candidates_sync, &dpi, 0,
2720 			    ZFS_SPACE_CHECK_NONE));
2721 		}
2722 		list_destroy(&dpi.dpi_candidates);
2723 
2724 		zfs_dbgmsg("pruned %llu entries (%d%%) across %llu txg syncs",
2725 		    (u_longlong_t)dpi.dpi_pruned,
2726 		    (int)((dpi.dpi_pruned * 100) / valid),
2727 		    (u_longlong_t)dpi.dpi_txg_syncs);
2728 	}
2729 }
2730 
2731 static uint64_t
2732 ddt_total_entries(spa_t *spa)
2733 {
2734 	ddt_object_t ddo;
2735 	ddt_get_dedup_object_stats(spa, &ddo);
2736 
2737 	return (ddo.ddo_count);
2738 }
2739 
2740 int
2741 ddt_prune_unique_entries(spa_t *spa, zpool_ddt_prune_unit_t unit,
2742     uint64_t amount)
2743 {
2744 	uint64_t cutoff;
2745 	uint64_t start_time = gethrtime();
2746 
2747 	if (spa->spa_active_ddt_prune)
2748 		return (SET_ERROR(EALREADY));
2749 	if (ddt_total_entries(spa) == 0)
2750 		return (0);
2751 
2752 	spa->spa_active_ddt_prune = B_TRUE;
2753 
2754 	zfs_dbgmsg("prune %llu %s", (u_longlong_t)amount,
2755 	    unit == ZPOOL_DDT_PRUNE_PERCENTAGE ? "%" : "seconds old or older");
2756 
2757 	if (unit == ZPOOL_DDT_PRUNE_PERCENTAGE) {
2758 		ddt_age_histo_t histogram;
2759 		uint64_t oldest = 0;
2760 
2761 		/* Make a pass over DDT to build a histogram */
2762 		ddt_prune_walk(spa, 0, &histogram);
2763 
2764 		int target = (histogram.dah_entries * amount) / 100;
2765 
2766 		/*
2767 		 * Figure out our cutoff date
2768 		 * (i.e., which bins to prune from)
2769 		 */
2770 		for (int i = HIST_BINS - 1; i >= 0 && target > 0; i--) {
2771 			if (histogram.dah_age_histo[i] != 0) {
2772 				/* less than this bucket remaining */
2773 				if (target < histogram.dah_age_histo[i]) {
2774 					oldest = MAX(1, (1<<i) * 3600);
2775 					target = 0;
2776 				} else {
2777 					target -= histogram.dah_age_histo[i];
2778 				}
2779 			}
2780 		}
2781 		cutoff = gethrestime_sec() - oldest;
2782 
2783 		if (ddt_dump_prune_histogram)
2784 			ddt_dump_age_histogram(&histogram, cutoff);
2785 	} else if (unit == ZPOOL_DDT_PRUNE_AGE) {
2786 		cutoff = gethrestime_sec() - amount;
2787 	} else {
2788 		return (EINVAL);
2789 	}
2790 
2791 	if (cutoff > 0 && !spa_shutting_down(spa) && !issig()) {
2792 		/* Traverse DDT to prune entries older that our cuttoff */
2793 		ddt_prune_walk(spa, cutoff, NULL);
2794 	}
2795 
2796 	zfs_dbgmsg("%s: prune completed in %llu ms",
2797 	    spa_name(spa), (u_longlong_t)NSEC2MSEC(gethrtime() - start_time));
2798 
2799 	spa->spa_active_ddt_prune = B_FALSE;
2800 	return (0);
2801 }
2802 
2803 ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, prefetch, INT, ZMOD_RW,
2804 	"Enable prefetching dedup-ed blks");
2805 
2806 ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_flush_min_time_ms, UINT, ZMOD_RW,
2807 	"Min time to spend on incremental dedup log flush each transaction");
2808 
2809 ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_flush_entries_min, UINT, ZMOD_RW,
2810 	"Min number of log entries to flush each transaction");
2811 
2812 ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_flush_entries_max, UINT, ZMOD_RW,
2813 	"Max number of log entries to flush each transaction");
2814 
2815 ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_flush_txgs, UINT, ZMOD_RW,
2816 	"Number of TXGs to try to rotate the log in");
2817 
2818 ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_cap, UINT, ZMOD_RW,
2819 	"Soft cap for the size of the current dedup log");
2820 
2821 ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_hard_cap, UINT, ZMOD_RW,
2822 	"Whether to use the soft cap as a hard cap");
2823 
2824 ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_flush_flow_rate_txgs, UINT, ZMOD_RW,
2825 	"Number of txgs to average flow rates across");
2826