xref: /freebsd/sys/contrib/openzfs/module/zfs/ddt.c (revision 61145dc2b94f12f6a47344fb9aac702321880e43)
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_* tuneables 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
ddt_object_create(ddt_t * ddt,ddt_type_t type,ddt_class_t class,dmu_tx_t * tx)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
ddt_object_destroy(ddt_t * ddt,ddt_type_t type,ddt_class_t class,dmu_tx_t * tx)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
ddt_object_load(ddt_t * ddt,ddt_type_t type,ddt_class_t class)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
ddt_object_sync(ddt_t * ddt,ddt_type_t type,ddt_class_t class,dmu_tx_t * tx)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
ddt_object_exists(ddt_t * ddt,ddt_type_t type,ddt_class_t class)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
ddt_object_lookup(ddt_t * ddt,ddt_type_t type,ddt_class_t class,ddt_entry_t * dde)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
ddt_object_contains(ddt_t * ddt,ddt_type_t type,ddt_class_t class,const ddt_key_t * ddk)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
ddt_object_prefetch(ddt_t * ddt,ddt_type_t type,ddt_class_t class,const ddt_key_t * ddk)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
ddt_object_prefetch_all(ddt_t * ddt,ddt_type_t type,ddt_class_t class)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
ddt_object_update(ddt_t * ddt,ddt_type_t type,ddt_class_t class,const ddt_lightweight_entry_t * ddlwe,dmu_tx_t * tx)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
ddt_object_remove(ddt_t * ddt,ddt_type_t type,ddt_class_t class,const ddt_key_t * ddk,dmu_tx_t * tx)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
ddt_object_walk(ddt_t * ddt,ddt_type_t type,ddt_class_t class,uint64_t * walk,ddt_lightweight_entry_t * ddlwe)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
ddt_object_count(ddt_t * ddt,ddt_type_t type,ddt_class_t class,uint64_t * count)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
ddt_object_info(ddt_t * ddt,ddt_type_t type,ddt_class_t class,dmu_object_info_t * doi)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
ddt_object_name(ddt_t * ddt,ddt_type_t type,ddt_class_t class,char * name)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
ddt_bp_fill(const ddt_univ_phys_t * ddp,ddt_phys_variant_t v,blkptr_t * bp,uint64_t txg)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
ddt_bp_create(enum zio_checksum checksum,const ddt_key_t * ddk,const ddt_univ_phys_t * ddp,ddt_phys_variant_t v,blkptr_t * bp)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
ddt_key_fill(ddt_key_t * ddk,const blkptr_t * bp)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
ddt_phys_extend(ddt_univ_phys_t * ddp,ddt_phys_variant_t v,const blkptr_t * bp)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
ddt_phys_copy(ddt_univ_phys_t * dst,const ddt_univ_phys_t * src,ddt_phys_variant_t v)735 ddt_phys_copy(ddt_univ_phys_t *dst, const ddt_univ_phys_t *src,
736     ddt_phys_variant_t v)
737 {
738 	ASSERT3U(v, <, DDT_PHYS_NONE);
739 
740 	if (v == DDT_PHYS_FLAT)
741 		dst->ddp_flat = src->ddp_flat;
742 	else
743 		dst->ddp_trad[v] = src->ddp_trad[v];
744 }
745 
746 void
ddt_phys_clear(ddt_univ_phys_t * ddp,ddt_phys_variant_t v)747 ddt_phys_clear(ddt_univ_phys_t *ddp, ddt_phys_variant_t v)
748 {
749 	ASSERT3U(v, <, DDT_PHYS_NONE);
750 
751 	if (v == DDT_PHYS_FLAT)
752 		memset(&ddp->ddp_flat, 0, DDT_FLAT_PHYS_SIZE);
753 	else
754 		memset(&ddp->ddp_trad[v], 0, DDT_TRAD_PHYS_SIZE / DDT_PHYS_MAX);
755 }
756 
757 static uint64_t
ddt_class_start(void)758 ddt_class_start(void)
759 {
760 	uint64_t start = gethrestime_sec();
761 
762 	if (ddt_prune_artificial_age) {
763 		/*
764 		 * debug aide -- simulate a wider distribution
765 		 * so we don't have to wait for an aged DDT
766 		 * to test prune.
767 		 */
768 		int range = 1 << 21;
769 		int percent = random_in_range(100);
770 		if (percent < 50) {
771 			range = range >> 4;
772 		} else if (percent > 75) {
773 			range /= 2;
774 		}
775 		start -= random_in_range(range);
776 	}
777 
778 	return (start);
779 }
780 
781 void
ddt_phys_addref(ddt_univ_phys_t * ddp,ddt_phys_variant_t v)782 ddt_phys_addref(ddt_univ_phys_t *ddp, ddt_phys_variant_t v)
783 {
784 	ASSERT3U(v, <, DDT_PHYS_NONE);
785 
786 	if (v == DDT_PHYS_FLAT)
787 		ddp->ddp_flat.ddp_refcnt++;
788 	else
789 		ddp->ddp_trad[v].ddp_refcnt++;
790 }
791 
792 uint64_t
ddt_phys_decref(ddt_univ_phys_t * ddp,ddt_phys_variant_t v)793 ddt_phys_decref(ddt_univ_phys_t *ddp, ddt_phys_variant_t v)
794 {
795 	ASSERT3U(v, <, DDT_PHYS_NONE);
796 
797 	uint64_t *refcntp;
798 
799 	if (v == DDT_PHYS_FLAT)
800 		refcntp = &ddp->ddp_flat.ddp_refcnt;
801 	else
802 		refcntp = &ddp->ddp_trad[v].ddp_refcnt;
803 
804 	ASSERT3U(*refcntp, >, 0);
805 	(*refcntp)--;
806 	return (*refcntp);
807 }
808 
809 static void
ddt_phys_free(ddt_t * ddt,ddt_key_t * ddk,ddt_univ_phys_t * ddp,ddt_phys_variant_t v,uint64_t txg)810 ddt_phys_free(ddt_t *ddt, ddt_key_t *ddk, ddt_univ_phys_t *ddp,
811     ddt_phys_variant_t v, uint64_t txg)
812 {
813 	blkptr_t blk;
814 
815 	ddt_bp_create(ddt->ddt_checksum, ddk, ddp, v, &blk);
816 
817 	/*
818 	 * We clear the dedup bit so that zio_free() will actually free the
819 	 * space, rather than just decrementing the refcount in the DDT.
820 	 */
821 	BP_SET_DEDUP(&blk, 0);
822 
823 	ddt_phys_clear(ddp, v);
824 	zio_free(ddt->ddt_spa, txg, &blk);
825 }
826 
827 uint64_t
ddt_phys_birth(const ddt_univ_phys_t * ddp,ddt_phys_variant_t v)828 ddt_phys_birth(const ddt_univ_phys_t *ddp, ddt_phys_variant_t v)
829 {
830 	ASSERT3U(v, <, DDT_PHYS_NONE);
831 
832 	if (v == DDT_PHYS_FLAT)
833 		return (ddp->ddp_flat.ddp_phys_birth);
834 	else
835 		return (ddp->ddp_trad[v].ddp_phys_birth);
836 }
837 
838 int
ddt_phys_dva_count(const ddt_univ_phys_t * ddp,ddt_phys_variant_t v,boolean_t encrypted)839 ddt_phys_dva_count(const ddt_univ_phys_t *ddp, ddt_phys_variant_t v,
840     boolean_t encrypted)
841 {
842 	ASSERT3U(v, <, DDT_PHYS_NONE);
843 
844 	const dva_t *dvas = (v == DDT_PHYS_FLAT) ?
845 	    ddp->ddp_flat.ddp_dva : ddp->ddp_trad[v].ddp_dva;
846 
847 	return (DVA_IS_VALID(&dvas[0]) +
848 	    DVA_IS_VALID(&dvas[1]) +
849 	    DVA_IS_VALID(&dvas[2]) * !encrypted);
850 }
851 
852 ddt_phys_variant_t
ddt_phys_select(const ddt_t * ddt,const ddt_entry_t * dde,const blkptr_t * bp)853 ddt_phys_select(const ddt_t *ddt, const ddt_entry_t *dde, const blkptr_t *bp)
854 {
855 	if (dde == NULL)
856 		return (DDT_PHYS_NONE);
857 
858 	const ddt_univ_phys_t *ddp = dde->dde_phys;
859 
860 	if (ddt->ddt_flags & DDT_FLAG_FLAT) {
861 		if (DVA_EQUAL(BP_IDENTITY(bp), &ddp->ddp_flat.ddp_dva[0]) &&
862 		    BP_GET_BIRTH(bp) == ddp->ddp_flat.ddp_phys_birth) {
863 			return (DDT_PHYS_FLAT);
864 		}
865 	} else /* traditional phys */ {
866 		for (int p = 0; p < DDT_PHYS_MAX; p++) {
867 			if (DVA_EQUAL(BP_IDENTITY(bp),
868 			    &ddp->ddp_trad[p].ddp_dva[0]) &&
869 			    BP_GET_BIRTH(bp) ==
870 			    ddp->ddp_trad[p].ddp_phys_birth) {
871 				return (p);
872 			}
873 		}
874 	}
875 	return (DDT_PHYS_NONE);
876 }
877 
878 uint64_t
ddt_phys_refcnt(const ddt_univ_phys_t * ddp,ddt_phys_variant_t v)879 ddt_phys_refcnt(const ddt_univ_phys_t *ddp, ddt_phys_variant_t v)
880 {
881 	ASSERT3U(v, <, DDT_PHYS_NONE);
882 
883 	if (v == DDT_PHYS_FLAT)
884 		return (ddp->ddp_flat.ddp_refcnt);
885 	else
886 		return (ddp->ddp_trad[v].ddp_refcnt);
887 }
888 
889 uint64_t
ddt_phys_total_refcnt(const ddt_t * ddt,const ddt_univ_phys_t * ddp)890 ddt_phys_total_refcnt(const ddt_t *ddt, const ddt_univ_phys_t *ddp)
891 {
892 	uint64_t refcnt = 0;
893 
894 	if (ddt->ddt_flags & DDT_FLAG_FLAT)
895 		refcnt = ddp->ddp_flat.ddp_refcnt;
896 	else
897 		for (int v = DDT_PHYS_SINGLE; v <= DDT_PHYS_TRIPLE; v++)
898 			refcnt += ddp->ddp_trad[v].ddp_refcnt;
899 
900 	return (refcnt);
901 }
902 
903 ddt_t *
ddt_select(spa_t * spa,const blkptr_t * bp)904 ddt_select(spa_t *spa, const blkptr_t *bp)
905 {
906 	ASSERT(DDT_CHECKSUM_VALID(BP_GET_CHECKSUM(bp)));
907 	return (spa->spa_ddt[BP_GET_CHECKSUM(bp)]);
908 }
909 
910 void
ddt_enter(ddt_t * ddt)911 ddt_enter(ddt_t *ddt)
912 {
913 	mutex_enter(&ddt->ddt_lock);
914 }
915 
916 void
ddt_exit(ddt_t * ddt)917 ddt_exit(ddt_t *ddt)
918 {
919 	mutex_exit(&ddt->ddt_lock);
920 }
921 
922 void
ddt_init(void)923 ddt_init(void)
924 {
925 	ddt_cache = kmem_cache_create("ddt_cache",
926 	    sizeof (ddt_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
927 	ddt_entry_flat_cache = kmem_cache_create("ddt_entry_flat_cache",
928 	    DDT_ENTRY_FLAT_SIZE, 0, NULL, NULL, NULL, NULL, NULL, 0);
929 	ddt_entry_trad_cache = kmem_cache_create("ddt_entry_trad_cache",
930 	    DDT_ENTRY_TRAD_SIZE, 0, NULL, NULL, NULL, NULL, NULL, 0);
931 
932 	ddt_log_init();
933 }
934 
935 void
ddt_fini(void)936 ddt_fini(void)
937 {
938 	ddt_log_fini();
939 
940 	kmem_cache_destroy(ddt_entry_trad_cache);
941 	kmem_cache_destroy(ddt_entry_flat_cache);
942 	kmem_cache_destroy(ddt_cache);
943 }
944 
945 static ddt_entry_t *
ddt_alloc(const ddt_t * ddt,const ddt_key_t * ddk)946 ddt_alloc(const ddt_t *ddt, const ddt_key_t *ddk)
947 {
948 	ddt_entry_t *dde;
949 
950 	if (ddt->ddt_flags & DDT_FLAG_FLAT) {
951 		dde = kmem_cache_alloc(ddt_entry_flat_cache, KM_SLEEP);
952 		memset(dde, 0, DDT_ENTRY_FLAT_SIZE);
953 	} else {
954 		dde = kmem_cache_alloc(ddt_entry_trad_cache, KM_SLEEP);
955 		memset(dde, 0, DDT_ENTRY_TRAD_SIZE);
956 	}
957 
958 	cv_init(&dde->dde_cv, NULL, CV_DEFAULT, NULL);
959 
960 	dde->dde_key = *ddk;
961 
962 	return (dde);
963 }
964 
965 void
ddt_alloc_entry_io(ddt_entry_t * dde)966 ddt_alloc_entry_io(ddt_entry_t *dde)
967 {
968 	if (dde->dde_io != NULL)
969 		return;
970 
971 	dde->dde_io = kmem_zalloc(sizeof (ddt_entry_io_t), KM_SLEEP);
972 }
973 
974 static void
ddt_free(const ddt_t * ddt,ddt_entry_t * dde)975 ddt_free(const ddt_t *ddt, ddt_entry_t *dde)
976 {
977 	if (dde->dde_io != NULL) {
978 		for (int p = 0; p < DDT_NPHYS(ddt); p++)
979 			ASSERT3P(dde->dde_io->dde_lead_zio[p], ==, NULL);
980 
981 		if (dde->dde_io->dde_repair_abd != NULL)
982 			abd_free(dde->dde_io->dde_repair_abd);
983 
984 		kmem_free(dde->dde_io, sizeof (ddt_entry_io_t));
985 	}
986 
987 	cv_destroy(&dde->dde_cv);
988 	kmem_cache_free(ddt->ddt_flags & DDT_FLAG_FLAT ?
989 	    ddt_entry_flat_cache : ddt_entry_trad_cache, dde);
990 }
991 
992 void
ddt_remove(ddt_t * ddt,ddt_entry_t * dde)993 ddt_remove(ddt_t *ddt, ddt_entry_t *dde)
994 {
995 	ASSERT(MUTEX_HELD(&ddt->ddt_lock));
996 
997 	/* Entry is still in the log, so charge the entry back to it */
998 	if (dde->dde_flags & DDE_FLAG_LOGGED) {
999 		ddt_lightweight_entry_t ddlwe;
1000 		DDT_ENTRY_TO_LIGHTWEIGHT(ddt, dde, &ddlwe);
1001 		ddt_histogram_add_entry(ddt, &ddt->ddt_log_histogram, &ddlwe);
1002 	}
1003 
1004 	avl_remove(&ddt->ddt_tree, dde);
1005 	ddt_free(ddt, dde);
1006 }
1007 
1008 static boolean_t
ddt_special_over_quota(spa_t * spa,metaslab_class_t * mc)1009 ddt_special_over_quota(spa_t *spa, metaslab_class_t *mc)
1010 {
1011 	if (mc != NULL && metaslab_class_get_space(mc) > 0) {
1012 		/* Over quota if allocating outside of this special class */
1013 		if (spa_syncing_txg(spa) <= spa->spa_dedup_class_full_txg +
1014 		    dedup_class_wait_txgs) {
1015 			/* Waiting for some deferred frees to be processed */
1016 			return (B_TRUE);
1017 		}
1018 
1019 		/*
1020 		 * We're considered over quota when we hit 85% full, or for
1021 		 * larger drives, when there is less than 8GB free.
1022 		 */
1023 		uint64_t allocated = metaslab_class_get_alloc(mc);
1024 		uint64_t capacity = metaslab_class_get_space(mc);
1025 		uint64_t limit = MAX(capacity * 85 / 100,
1026 		    (capacity > (1LL<<33)) ? capacity - (1LL<<33) : 0);
1027 
1028 		return (allocated >= limit);
1029 	}
1030 	return (B_FALSE);
1031 }
1032 
1033 /*
1034  * Check if the DDT is over its quota.  This can be due to a few conditions:
1035  *   1. 'dedup_table_quota' property is not 0 (none) and the dedup dsize
1036  *       exceeds this limit
1037  *
1038  *   2. 'dedup_table_quota' property is set to automatic and
1039  *      a. the dedup or special allocation class could not satisfy a DDT
1040  *         allocation in a recent transaction
1041  *      b. the dedup or special allocation class has exceeded its 85% limit
1042  */
1043 static boolean_t
ddt_over_quota(spa_t * spa)1044 ddt_over_quota(spa_t *spa)
1045 {
1046 	if (spa->spa_dedup_table_quota == 0)
1047 		return (B_FALSE);
1048 
1049 	if (spa->spa_dedup_table_quota != UINT64_MAX)
1050 		return (ddt_get_ddt_dsize(spa) > spa->spa_dedup_table_quota);
1051 
1052 	/*
1053 	 * For automatic quota, table size is limited by dedup or special class
1054 	 */
1055 	if (ddt_special_over_quota(spa, spa_dedup_class(spa)))
1056 		return (B_TRUE);
1057 	else if (spa_special_has_ddt(spa) &&
1058 	    ddt_special_over_quota(spa, spa_special_class(spa)))
1059 		return (B_TRUE);
1060 
1061 	return (B_FALSE);
1062 }
1063 
1064 void
ddt_prefetch_all(spa_t * spa)1065 ddt_prefetch_all(spa_t *spa)
1066 {
1067 	/*
1068 	 * Load all DDT entries for each type/class combination. This is
1069 	 * indended to perform a prefetch on all such blocks. For the same
1070 	 * reason that ddt_prefetch isn't locked, this is also not locked.
1071 	 */
1072 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
1073 		ddt_t *ddt = spa->spa_ddt[c];
1074 		if (!ddt)
1075 			continue;
1076 
1077 		for (ddt_type_t type = 0; type < DDT_TYPES; type++) {
1078 			for (ddt_class_t class = 0; class < DDT_CLASSES;
1079 			    class++) {
1080 				ddt_object_prefetch_all(ddt, type, class);
1081 			}
1082 		}
1083 	}
1084 }
1085 
1086 static int ddt_configure(ddt_t *ddt, boolean_t new);
1087 
1088 /*
1089  * If the BP passed to ddt_lookup has valid DVAs, then we need to compare them
1090  * to the ones in the entry. If they're different, then the passed-in BP is
1091  * from a previous generation of this entry (ie was previously pruned) and we
1092  * have to act like the entry doesn't exist at all.
1093  *
1094  * This should only happen during a lookup to free the block (zio_ddt_free()).
1095  *
1096  * XXX this is similar in spirit to ddt_phys_select(), maybe can combine
1097  *       -- robn, 2024-02-09
1098  */
1099 static boolean_t
ddt_entry_lookup_is_valid(ddt_t * ddt,const blkptr_t * bp,ddt_entry_t * dde)1100 ddt_entry_lookup_is_valid(ddt_t *ddt, const blkptr_t *bp, ddt_entry_t *dde)
1101 {
1102 	/* If the BP has no DVAs, then this entry is good */
1103 	uint_t ndvas = BP_GET_NDVAS(bp);
1104 	if (ndvas == 0)
1105 		return (B_TRUE);
1106 
1107 	/*
1108 	 * Only checking the phys for the copies. For flat, there's only one;
1109 	 * for trad it'll be the one that has the matching set of DVAs.
1110 	 */
1111 	const dva_t *dvas = (ddt->ddt_flags & DDT_FLAG_FLAT) ?
1112 	    dde->dde_phys->ddp_flat.ddp_dva :
1113 	    dde->dde_phys->ddp_trad[ndvas].ddp_dva;
1114 
1115 	/*
1116 	 * Compare entry DVAs with the BP. They should all be there, but
1117 	 * there's not really anything we can do if its only partial anyway,
1118 	 * that's an error somewhere else, maybe long ago.
1119 	 */
1120 	uint_t d;
1121 	for (d = 0; d < ndvas; d++)
1122 		if (!DVA_EQUAL(&dvas[d], &bp->blk_dva[d]))
1123 			return (B_FALSE);
1124 	ASSERT3U(d, ==, ndvas);
1125 
1126 	return (B_TRUE);
1127 }
1128 
1129 ddt_entry_t *
ddt_lookup(ddt_t * ddt,const blkptr_t * bp,boolean_t verify)1130 ddt_lookup(ddt_t *ddt, const blkptr_t *bp, boolean_t verify)
1131 {
1132 	spa_t *spa = ddt->ddt_spa;
1133 	ddt_key_t search;
1134 	ddt_entry_t *dde;
1135 	ddt_type_t type;
1136 	ddt_class_t class;
1137 	avl_index_t where;
1138 	int error;
1139 
1140 	ASSERT(MUTEX_HELD(&ddt->ddt_lock));
1141 
1142 	if (ddt->ddt_version == DDT_VERSION_UNCONFIGURED) {
1143 		/*
1144 		 * This is the first use of this DDT since the pool was
1145 		 * created; finish getting it ready for use.
1146 		 */
1147 		VERIFY0(ddt_configure(ddt, B_TRUE));
1148 		ASSERT3U(ddt->ddt_version, !=, DDT_VERSION_UNCONFIGURED);
1149 	}
1150 
1151 	DDT_KSTAT_BUMP(ddt, dds_lookup);
1152 
1153 	ddt_key_fill(&search, bp);
1154 
1155 	/* Find an existing live entry */
1156 	dde = avl_find(&ddt->ddt_tree, &search, &where);
1157 	if (dde != NULL) {
1158 		/* If we went over quota, act like we didn't find it */
1159 		if (dde->dde_flags & DDE_FLAG_OVERQUOTA)
1160 			return (NULL);
1161 
1162 		/* If it's already loaded, we can just return it. */
1163 		DDT_KSTAT_BUMP(ddt, dds_lookup_live_hit);
1164 		if (dde->dde_flags & DDE_FLAG_LOADED) {
1165 			if (!verify || ddt_entry_lookup_is_valid(ddt, bp, dde))
1166 				return (dde);
1167 			return (NULL);
1168 		}
1169 
1170 		/* Someone else is loading it, wait for it. */
1171 		dde->dde_waiters++;
1172 		DDT_KSTAT_BUMP(ddt, dds_lookup_live_wait);
1173 		while (!(dde->dde_flags & DDE_FLAG_LOADED))
1174 			cv_wait(&dde->dde_cv, &ddt->ddt_lock);
1175 		dde->dde_waiters--;
1176 
1177 		/* Loaded but over quota, forget we were ever here */
1178 		if (dde->dde_flags & DDE_FLAG_OVERQUOTA) {
1179 			if (dde->dde_waiters == 0) {
1180 				avl_remove(&ddt->ddt_tree, dde);
1181 				ddt_free(ddt, dde);
1182 			}
1183 			return (NULL);
1184 		}
1185 
1186 		DDT_KSTAT_BUMP(ddt, dds_lookup_existing);
1187 
1188 		/* Make sure the loaded entry matches the BP */
1189 		if (!verify || ddt_entry_lookup_is_valid(ddt, bp, dde))
1190 			return (dde);
1191 		return (NULL);
1192 	} else
1193 		DDT_KSTAT_BUMP(ddt, dds_lookup_live_miss);
1194 
1195 	/* Time to make a new entry. */
1196 	dde = ddt_alloc(ddt, &search);
1197 
1198 	/* Record the time this class was created (used by ddt prune) */
1199 	if (ddt->ddt_flags & DDT_FLAG_FLAT)
1200 		dde->dde_phys->ddp_flat.ddp_class_start = ddt_class_start();
1201 
1202 	avl_insert(&ddt->ddt_tree, dde, where);
1203 
1204 	/* If its in the log tree, we can "load" it from there */
1205 	if (ddt->ddt_flags & DDT_FLAG_LOG) {
1206 		ddt_lightweight_entry_t ddlwe;
1207 
1208 		if (ddt_log_find_key(ddt, &search, &ddlwe)) {
1209 			/*
1210 			 * See if we have the key first, and if so, set up
1211 			 * the entry.
1212 			 */
1213 			dde->dde_type = ddlwe.ddlwe_type;
1214 			dde->dde_class = ddlwe.ddlwe_class;
1215 			memcpy(dde->dde_phys, &ddlwe.ddlwe_phys,
1216 			    DDT_PHYS_SIZE(ddt));
1217 			/* Whatever we found isn't valid for this BP, eject */
1218 			if (verify &&
1219 			    !ddt_entry_lookup_is_valid(ddt, bp, dde)) {
1220 				avl_remove(&ddt->ddt_tree, dde);
1221 				ddt_free(ddt, dde);
1222 				return (NULL);
1223 			}
1224 
1225 			/* Remove it and count it */
1226 			if (ddt_log_remove_key(ddt,
1227 			    ddt->ddt_log_active, &search)) {
1228 				DDT_KSTAT_BUMP(ddt, dds_lookup_log_active_hit);
1229 			} else {
1230 				VERIFY(ddt_log_remove_key(ddt,
1231 				    ddt->ddt_log_flushing, &search));
1232 				DDT_KSTAT_BUMP(ddt,
1233 				    dds_lookup_log_flushing_hit);
1234 			}
1235 
1236 			dde->dde_flags = DDE_FLAG_LOADED | DDE_FLAG_LOGGED;
1237 
1238 			DDT_KSTAT_BUMP(ddt, dds_lookup_log_hit);
1239 			DDT_KSTAT_BUMP(ddt, dds_lookup_existing);
1240 
1241 			return (dde);
1242 		}
1243 
1244 		DDT_KSTAT_BUMP(ddt, dds_lookup_log_miss);
1245 	}
1246 
1247 	/*
1248 	 * ddt_tree is now stable, so unlock and let everyone else keep moving.
1249 	 * Anyone landing on this entry will find it without DDE_FLAG_LOADED,
1250 	 * and go to sleep waiting for it above.
1251 	 */
1252 	ddt_exit(ddt);
1253 
1254 	/* Search all store objects for the entry. */
1255 	error = ENOENT;
1256 	for (type = 0; type < DDT_TYPES; type++) {
1257 		for (class = 0; class < DDT_CLASSES; class++) {
1258 			error = ddt_object_lookup(ddt, type, class, dde);
1259 			if (error != ENOENT) {
1260 				ASSERT0(error);
1261 				break;
1262 			}
1263 		}
1264 		if (error != ENOENT)
1265 			break;
1266 	}
1267 
1268 	ddt_enter(ddt);
1269 
1270 	ASSERT(!(dde->dde_flags & DDE_FLAG_LOADED));
1271 
1272 	dde->dde_type = type;	/* will be DDT_TYPES if no entry found */
1273 	dde->dde_class = class;	/* will be DDT_CLASSES if no entry found */
1274 
1275 	boolean_t valid = B_TRUE;
1276 
1277 	if (dde->dde_type == DDT_TYPES &&
1278 	    dde->dde_class == DDT_CLASSES &&
1279 	    ddt_over_quota(spa)) {
1280 		/* Over quota. If no one is waiting, clean up right now. */
1281 		if (dde->dde_waiters == 0) {
1282 			avl_remove(&ddt->ddt_tree, dde);
1283 			ddt_free(ddt, dde);
1284 			return (NULL);
1285 		}
1286 
1287 		/* Flag cleanup required */
1288 		dde->dde_flags |= DDE_FLAG_OVERQUOTA;
1289 	} else if (error == 0) {
1290 		/*
1291 		 * If what we loaded is no good for this BP and there's no one
1292 		 * waiting for it, we can just remove it and get out. If its no
1293 		 * good but there are waiters, we have to leave it, because we
1294 		 * don't know what they want. If its not needed we'll end up
1295 		 * taking an entry log/sync, but it can only happen if more
1296 		 * than one previous version of this block is being deleted at
1297 		 * the same time. This is extremely unlikely to happen and not
1298 		 * worth the effort to deal with without taking an entry
1299 		 * update.
1300 		 */
1301 		valid = !verify || ddt_entry_lookup_is_valid(ddt, bp, dde);
1302 		if (!valid && dde->dde_waiters == 0) {
1303 			avl_remove(&ddt->ddt_tree, dde);
1304 			ddt_free(ddt, dde);
1305 			return (NULL);
1306 		}
1307 
1308 		DDT_KSTAT_BUMP(ddt, dds_lookup_stored_hit);
1309 		DDT_KSTAT_BUMP(ddt, dds_lookup_existing);
1310 
1311 		/*
1312 		 * The histograms only track inactive (stored or logged) blocks.
1313 		 * We've just put an entry onto the live list, so we need to
1314 		 * remove its counts. When its synced back, it'll be re-added
1315 		 * to the right one.
1316 		 *
1317 		 * We only do this when we successfully found it in the store.
1318 		 * error == ENOENT means this is a new entry, and so its already
1319 		 * not counted.
1320 		 */
1321 		ddt_histogram_t *ddh =
1322 		    &ddt->ddt_histogram[dde->dde_type][dde->dde_class];
1323 
1324 		ddt_lightweight_entry_t ddlwe;
1325 		DDT_ENTRY_TO_LIGHTWEIGHT(ddt, dde, &ddlwe);
1326 		ddt_histogram_sub_entry(ddt, ddh, &ddlwe);
1327 	} else {
1328 		DDT_KSTAT_BUMP(ddt, dds_lookup_stored_miss);
1329 		DDT_KSTAT_BUMP(ddt, dds_lookup_new);
1330 	}
1331 
1332 	/* Entry loaded, everyone can proceed now */
1333 	dde->dde_flags |= DDE_FLAG_LOADED;
1334 	cv_broadcast(&dde->dde_cv);
1335 
1336 	if ((dde->dde_flags & DDE_FLAG_OVERQUOTA) || !valid)
1337 		return (NULL);
1338 
1339 	return (dde);
1340 }
1341 
1342 void
ddt_prefetch(spa_t * spa,const blkptr_t * bp)1343 ddt_prefetch(spa_t *spa, const blkptr_t *bp)
1344 {
1345 	ddt_t *ddt;
1346 	ddt_key_t ddk;
1347 
1348 	if (!zfs_dedup_prefetch || bp == NULL || !BP_GET_DEDUP(bp))
1349 		return;
1350 
1351 	/*
1352 	 * We only remove the DDT once all tables are empty and only
1353 	 * prefetch dedup blocks when there are entries in the DDT.
1354 	 * Thus no locking is required as the DDT can't disappear on us.
1355 	 */
1356 	ddt = ddt_select(spa, bp);
1357 	ddt_key_fill(&ddk, bp);
1358 
1359 	for (ddt_type_t type = 0; type < DDT_TYPES; type++) {
1360 		for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {
1361 			ddt_object_prefetch(ddt, type, class, &ddk);
1362 		}
1363 	}
1364 }
1365 
1366 /*
1367  * ddt_key_t comparison. Any struct wanting to make use of this function must
1368  * have the key as the first element. Casts it to N uint64_ts, and checks until
1369  * we find there's a difference. This is intended to match how ddt_zap.c drives
1370  * the ZAPs (first uint64_t as the key prehash), which will minimise the number
1371  * of ZAP blocks touched when flushing logged entries from an AVL walk. This is
1372  * not an invariant for this function though, should you wish to change it.
1373  */
1374 int
ddt_key_compare(const void * x1,const void * x2)1375 ddt_key_compare(const void *x1, const void *x2)
1376 {
1377 	const uint64_t *k1 = (const uint64_t *)x1;
1378 	const uint64_t *k2 = (const uint64_t *)x2;
1379 
1380 	int cmp;
1381 	for (int i = 0; i < (sizeof (ddt_key_t) / sizeof (uint64_t)); i++)
1382 		if (likely((cmp = TREE_CMP(k1[i], k2[i])) != 0))
1383 			return (cmp);
1384 
1385 	return (0);
1386 }
1387 
1388 /* Create the containing dir for this DDT and bump the feature count */
1389 static void
ddt_create_dir(ddt_t * ddt,dmu_tx_t * tx)1390 ddt_create_dir(ddt_t *ddt, dmu_tx_t *tx)
1391 {
1392 	ASSERT3U(ddt->ddt_dir_object, ==, 0);
1393 	ASSERT3U(ddt->ddt_version, ==, DDT_VERSION_FDT);
1394 
1395 	char name[DDT_NAMELEN];
1396 	snprintf(name, DDT_NAMELEN, DMU_POOL_DDT_DIR,
1397 	    zio_checksum_table[ddt->ddt_checksum].ci_name);
1398 
1399 	ddt->ddt_dir_object = zap_create_link(ddt->ddt_os,
1400 	    DMU_OTN_ZAP_METADATA, DMU_POOL_DIRECTORY_OBJECT, name, tx);
1401 
1402 	VERIFY0(zap_add(ddt->ddt_os, ddt->ddt_dir_object, DDT_DIR_VERSION,
1403 	    sizeof (uint64_t), 1, &ddt->ddt_version, tx));
1404 	VERIFY0(zap_add(ddt->ddt_os, ddt->ddt_dir_object, DDT_DIR_FLAGS,
1405 	    sizeof (uint64_t), 1, &ddt->ddt_flags, tx));
1406 
1407 	spa_feature_incr(ddt->ddt_spa, SPA_FEATURE_FAST_DEDUP, tx);
1408 }
1409 
1410 /* Destroy the containing dir and deactivate the feature */
1411 static void
ddt_destroy_dir(ddt_t * ddt,dmu_tx_t * tx)1412 ddt_destroy_dir(ddt_t *ddt, dmu_tx_t *tx)
1413 {
1414 	ASSERT3U(ddt->ddt_dir_object, !=, 0);
1415 	ASSERT3U(ddt->ddt_dir_object, !=, DMU_POOL_DIRECTORY_OBJECT);
1416 	ASSERT3U(ddt->ddt_version, ==, DDT_VERSION_FDT);
1417 
1418 	char name[DDT_NAMELEN];
1419 	snprintf(name, DDT_NAMELEN, DMU_POOL_DDT_DIR,
1420 	    zio_checksum_table[ddt->ddt_checksum].ci_name);
1421 
1422 	for (ddt_type_t type = 0; type < DDT_TYPES; type++) {
1423 		for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {
1424 			ASSERT(!ddt_object_exists(ddt, type, class));
1425 		}
1426 	}
1427 
1428 	ddt_log_destroy(ddt, tx);
1429 
1430 	uint64_t count;
1431 	ASSERT0(zap_count(ddt->ddt_os, ddt->ddt_dir_object, &count));
1432 	ASSERT0(zap_contains(ddt->ddt_os, ddt->ddt_dir_object,
1433 	    DDT_DIR_VERSION));
1434 	ASSERT0(zap_contains(ddt->ddt_os, ddt->ddt_dir_object, DDT_DIR_FLAGS));
1435 	ASSERT3U(count, ==, 2);
1436 
1437 	VERIFY0(zap_remove(ddt->ddt_os, DMU_POOL_DIRECTORY_OBJECT, name, tx));
1438 	VERIFY0(zap_destroy(ddt->ddt_os, ddt->ddt_dir_object, tx));
1439 
1440 	ddt->ddt_dir_object = 0;
1441 
1442 	spa_feature_decr(ddt->ddt_spa, SPA_FEATURE_FAST_DEDUP, tx);
1443 }
1444 
1445 /*
1446  * Determine, flags and on-disk layout from what's already stored. If there's
1447  * nothing stored, then if new is false, returns ENOENT, and if true, selects
1448  * based on pool config.
1449  */
1450 static int
ddt_configure(ddt_t * ddt,boolean_t new)1451 ddt_configure(ddt_t *ddt, boolean_t new)
1452 {
1453 	spa_t *spa = ddt->ddt_spa;
1454 	char name[DDT_NAMELEN];
1455 	int error;
1456 
1457 	ASSERT3U(spa_load_state(spa), !=, SPA_LOAD_CREATE);
1458 
1459 	boolean_t fdt_enabled =
1460 	    spa_feature_is_enabled(spa, SPA_FEATURE_FAST_DEDUP);
1461 	boolean_t fdt_active =
1462 	    spa_feature_is_active(spa, SPA_FEATURE_FAST_DEDUP);
1463 
1464 	/*
1465 	 * First, look for the global DDT stats object. If its not there, then
1466 	 * there's never been a DDT written before ever, and we know we're
1467 	 * starting from scratch.
1468 	 */
1469 	error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
1470 	    DMU_POOL_DDT_STATS, sizeof (uint64_t), 1,
1471 	    &spa->spa_ddt_stat_object);
1472 	if (error != 0) {
1473 		if (error != ENOENT)
1474 			return (error);
1475 		goto not_found;
1476 	}
1477 
1478 	if (fdt_active) {
1479 		/*
1480 		 * Now look for a DDT directory. If it exists, then it has
1481 		 * everything we need.
1482 		 */
1483 		snprintf(name, DDT_NAMELEN, DMU_POOL_DDT_DIR,
1484 		    zio_checksum_table[ddt->ddt_checksum].ci_name);
1485 
1486 		error = zap_lookup(spa->spa_meta_objset,
1487 		    DMU_POOL_DIRECTORY_OBJECT, name, sizeof (uint64_t), 1,
1488 		    &ddt->ddt_dir_object);
1489 		if (error == 0) {
1490 			ASSERT3U(spa->spa_meta_objset, ==, ddt->ddt_os);
1491 
1492 			error = zap_lookup(ddt->ddt_os, ddt->ddt_dir_object,
1493 			    DDT_DIR_VERSION, sizeof (uint64_t), 1,
1494 			    &ddt->ddt_version);
1495 			if (error != 0)
1496 				return (error);
1497 
1498 			error = zap_lookup(ddt->ddt_os, ddt->ddt_dir_object,
1499 			    DDT_DIR_FLAGS, sizeof (uint64_t), 1,
1500 			    &ddt->ddt_flags);
1501 			if (error != 0)
1502 				return (error);
1503 
1504 			if (ddt->ddt_version != DDT_VERSION_FDT) {
1505 				zfs_dbgmsg("ddt_configure: spa=%s ddt_dir=%s "
1506 				    "unknown version %llu", spa_name(spa),
1507 				    name, (u_longlong_t)ddt->ddt_version);
1508 				return (SET_ERROR(EINVAL));
1509 			}
1510 
1511 			if ((ddt->ddt_flags & ~DDT_FLAG_MASK) != 0) {
1512 				zfs_dbgmsg("ddt_configure: spa=%s ddt_dir=%s "
1513 				    "version=%llu unknown flags %llx",
1514 				    spa_name(spa), name,
1515 				    (u_longlong_t)ddt->ddt_flags,
1516 				    (u_longlong_t)ddt->ddt_version);
1517 				return (SET_ERROR(EINVAL));
1518 			}
1519 
1520 			return (0);
1521 		}
1522 		if (error != ENOENT)
1523 			return (error);
1524 	}
1525 
1526 	/* Any object in the root indicates a traditional setup. */
1527 	for (ddt_type_t type = 0; type < DDT_TYPES; type++) {
1528 		for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {
1529 			ddt_object_name(ddt, type, class, name);
1530 			uint64_t obj;
1531 			error = zap_lookup(spa->spa_meta_objset,
1532 			    DMU_POOL_DIRECTORY_OBJECT, name, sizeof (uint64_t),
1533 			    1, &obj);
1534 			if (error == ENOENT)
1535 				continue;
1536 			if (error != 0)
1537 				return (error);
1538 
1539 			ddt->ddt_version = DDT_VERSION_LEGACY;
1540 			ddt->ddt_flags = ddt_version_flags[ddt->ddt_version];
1541 			ddt->ddt_dir_object = DMU_POOL_DIRECTORY_OBJECT;
1542 
1543 			return (0);
1544 		}
1545 	}
1546 
1547 not_found:
1548 	if (!new)
1549 		return (SET_ERROR(ENOENT));
1550 
1551 	/* Nothing on disk, so set up for the best version we can */
1552 	if (fdt_enabled) {
1553 		ddt->ddt_version = DDT_VERSION_FDT;
1554 		ddt->ddt_flags = ddt_version_flags[ddt->ddt_version];
1555 		ddt->ddt_dir_object = 0; /* create on first use */
1556 	} else {
1557 		ddt->ddt_version = DDT_VERSION_LEGACY;
1558 		ddt->ddt_flags = ddt_version_flags[ddt->ddt_version];
1559 		ddt->ddt_dir_object = DMU_POOL_DIRECTORY_OBJECT;
1560 	}
1561 
1562 	return (0);
1563 }
1564 
1565 static void
ddt_table_alloc_kstats(ddt_t * ddt)1566 ddt_table_alloc_kstats(ddt_t *ddt)
1567 {
1568 	char *mod = kmem_asprintf("zfs/%s", spa_name(ddt->ddt_spa));
1569 	char *name = kmem_asprintf("ddt_stats_%s",
1570 	    zio_checksum_table[ddt->ddt_checksum].ci_name);
1571 
1572 	ddt->ddt_ksp = kstat_create(mod, 0, name, "misc", KSTAT_TYPE_NAMED,
1573 	    sizeof (ddt_kstats_t) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
1574 	if (ddt->ddt_ksp != NULL) {
1575 		ddt_kstats_t *dds = kmem_alloc(sizeof (ddt_kstats_t), KM_SLEEP);
1576 		memcpy(dds, &ddt_kstats_template, sizeof (ddt_kstats_t));
1577 		ddt->ddt_ksp->ks_data = dds;
1578 		kstat_install(ddt->ddt_ksp);
1579 	}
1580 
1581 	kmem_strfree(name);
1582 	kmem_strfree(mod);
1583 }
1584 
1585 static ddt_t *
ddt_table_alloc(spa_t * spa,enum zio_checksum c)1586 ddt_table_alloc(spa_t *spa, enum zio_checksum c)
1587 {
1588 	ddt_t *ddt;
1589 
1590 	ddt = kmem_cache_alloc(ddt_cache, KM_SLEEP);
1591 	memset(ddt, 0, sizeof (ddt_t));
1592 	mutex_init(&ddt->ddt_lock, NULL, MUTEX_DEFAULT, NULL);
1593 	avl_create(&ddt->ddt_tree, ddt_key_compare,
1594 	    sizeof (ddt_entry_t), offsetof(ddt_entry_t, dde_node));
1595 	avl_create(&ddt->ddt_repair_tree, ddt_key_compare,
1596 	    sizeof (ddt_entry_t), offsetof(ddt_entry_t, dde_node));
1597 
1598 	ddt->ddt_checksum = c;
1599 	ddt->ddt_spa = spa;
1600 	ddt->ddt_os = spa->spa_meta_objset;
1601 	ddt->ddt_version = DDT_VERSION_UNCONFIGURED;
1602 	ddt->ddt_log_flush_pressure = 10;
1603 
1604 	ddt_log_alloc(ddt);
1605 	ddt_table_alloc_kstats(ddt);
1606 
1607 	return (ddt);
1608 }
1609 
1610 static void
ddt_table_free(ddt_t * ddt)1611 ddt_table_free(ddt_t *ddt)
1612 {
1613 	if (ddt->ddt_ksp != NULL) {
1614 		kmem_free(ddt->ddt_ksp->ks_data, sizeof (ddt_kstats_t));
1615 		ddt->ddt_ksp->ks_data = NULL;
1616 		kstat_delete(ddt->ddt_ksp);
1617 	}
1618 
1619 	ddt_log_free(ddt);
1620 	ASSERT0(avl_numnodes(&ddt->ddt_tree));
1621 	ASSERT0(avl_numnodes(&ddt->ddt_repair_tree));
1622 	avl_destroy(&ddt->ddt_tree);
1623 	avl_destroy(&ddt->ddt_repair_tree);
1624 	mutex_destroy(&ddt->ddt_lock);
1625 	kmem_cache_free(ddt_cache, ddt);
1626 }
1627 
1628 void
ddt_create(spa_t * spa)1629 ddt_create(spa_t *spa)
1630 {
1631 	spa->spa_dedup_checksum = ZIO_DEDUPCHECKSUM;
1632 
1633 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
1634 		if (DDT_CHECKSUM_VALID(c))
1635 			spa->spa_ddt[c] = ddt_table_alloc(spa, c);
1636 	}
1637 }
1638 
1639 int
ddt_load(spa_t * spa)1640 ddt_load(spa_t *spa)
1641 {
1642 	int error;
1643 
1644 	ddt_create(spa);
1645 
1646 	error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
1647 	    DMU_POOL_DDT_STATS, sizeof (uint64_t), 1,
1648 	    &spa->spa_ddt_stat_object);
1649 	if (error)
1650 		return (error == ENOENT ? 0 : error);
1651 
1652 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
1653 		if (!DDT_CHECKSUM_VALID(c))
1654 			continue;
1655 
1656 		ddt_t *ddt = spa->spa_ddt[c];
1657 		error = ddt_configure(ddt, B_FALSE);
1658 		if (error == ENOENT)
1659 			continue;
1660 		if (error != 0)
1661 			return (error);
1662 
1663 		for (ddt_type_t type = 0; type < DDT_TYPES; type++) {
1664 			for (ddt_class_t class = 0; class < DDT_CLASSES;
1665 			    class++) {
1666 				error = ddt_object_load(ddt, type, class);
1667 				if (error != 0 && error != ENOENT)
1668 					return (error);
1669 			}
1670 		}
1671 
1672 		error = ddt_log_load(ddt);
1673 		if (error != 0 && error != ENOENT)
1674 			return (error);
1675 
1676 		DDT_KSTAT_SET(ddt, dds_log_active_entries,
1677 		    avl_numnodes(&ddt->ddt_log_active->ddl_tree));
1678 		DDT_KSTAT_SET(ddt, dds_log_flushing_entries,
1679 		    avl_numnodes(&ddt->ddt_log_flushing->ddl_tree));
1680 
1681 		/*
1682 		 * Seed the cached histograms.
1683 		 */
1684 		memcpy(&ddt->ddt_histogram_cache, ddt->ddt_histogram,
1685 		    sizeof (ddt->ddt_histogram));
1686 	}
1687 
1688 	spa->spa_dedup_dspace = ~0ULL;
1689 	spa->spa_dedup_dsize = ~0ULL;
1690 
1691 	return (0);
1692 }
1693 
1694 void
ddt_unload(spa_t * spa)1695 ddt_unload(spa_t *spa)
1696 {
1697 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
1698 		if (spa->spa_ddt[c]) {
1699 			ddt_table_free(spa->spa_ddt[c]);
1700 			spa->spa_ddt[c] = NULL;
1701 		}
1702 	}
1703 }
1704 
1705 boolean_t
ddt_class_contains(spa_t * spa,ddt_class_t max_class,const blkptr_t * bp)1706 ddt_class_contains(spa_t *spa, ddt_class_t max_class, const blkptr_t *bp)
1707 {
1708 	ddt_t *ddt;
1709 	ddt_key_t ddk;
1710 
1711 	if (!BP_GET_DEDUP(bp))
1712 		return (B_FALSE);
1713 
1714 	if (max_class == DDT_CLASS_UNIQUE)
1715 		return (B_TRUE);
1716 
1717 	ddt = spa->spa_ddt[BP_GET_CHECKSUM(bp)];
1718 
1719 	ddt_key_fill(&ddk, bp);
1720 
1721 	for (ddt_type_t type = 0; type < DDT_TYPES; type++) {
1722 		for (ddt_class_t class = 0; class <= max_class; class++) {
1723 			if (ddt_object_contains(ddt, type, class, &ddk) == 0)
1724 				return (B_TRUE);
1725 		}
1726 	}
1727 
1728 	return (B_FALSE);
1729 }
1730 
1731 ddt_entry_t *
ddt_repair_start(ddt_t * ddt,const blkptr_t * bp)1732 ddt_repair_start(ddt_t *ddt, const blkptr_t *bp)
1733 {
1734 	ddt_key_t ddk;
1735 	ddt_entry_t *dde;
1736 
1737 	ddt_key_fill(&ddk, bp);
1738 
1739 	dde = ddt_alloc(ddt, &ddk);
1740 	ddt_alloc_entry_io(dde);
1741 
1742 	for (ddt_type_t type = 0; type < DDT_TYPES; type++) {
1743 		for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {
1744 			/*
1745 			 * We can only do repair if there are multiple copies
1746 			 * of the block.  For anything in the UNIQUE class,
1747 			 * there's definitely only one copy, so don't even try.
1748 			 */
1749 			if (class != DDT_CLASS_UNIQUE &&
1750 			    ddt_object_lookup(ddt, type, class, dde) == 0)
1751 				return (dde);
1752 		}
1753 	}
1754 
1755 	memset(dde->dde_phys, 0, DDT_PHYS_SIZE(ddt));
1756 
1757 	return (dde);
1758 }
1759 
1760 void
ddt_repair_done(ddt_t * ddt,ddt_entry_t * dde)1761 ddt_repair_done(ddt_t *ddt, ddt_entry_t *dde)
1762 {
1763 	avl_index_t where;
1764 
1765 	ddt_enter(ddt);
1766 
1767 	if (dde->dde_io->dde_repair_abd != NULL &&
1768 	    spa_writeable(ddt->ddt_spa) &&
1769 	    avl_find(&ddt->ddt_repair_tree, dde, &where) == NULL)
1770 		avl_insert(&ddt->ddt_repair_tree, dde, where);
1771 	else
1772 		ddt_free(ddt, dde);
1773 
1774 	ddt_exit(ddt);
1775 }
1776 
1777 static void
ddt_repair_entry_done(zio_t * zio)1778 ddt_repair_entry_done(zio_t *zio)
1779 {
1780 	ddt_t *ddt = ddt_select(zio->io_spa, zio->io_bp);
1781 	ddt_entry_t *rdde = zio->io_private;
1782 
1783 	ddt_free(ddt, rdde);
1784 }
1785 
1786 static void
ddt_repair_entry(ddt_t * ddt,ddt_entry_t * dde,ddt_entry_t * rdde,zio_t * rio)1787 ddt_repair_entry(ddt_t *ddt, ddt_entry_t *dde, ddt_entry_t *rdde, zio_t *rio)
1788 {
1789 	ddt_key_t *ddk = &dde->dde_key;
1790 	ddt_key_t *rddk = &rdde->dde_key;
1791 	zio_t *zio;
1792 	blkptr_t blk;
1793 
1794 	zio = zio_null(rio, rio->io_spa, NULL,
1795 	    ddt_repair_entry_done, rdde, rio->io_flags);
1796 
1797 	for (int p = 0; p < DDT_NPHYS(ddt); p++) {
1798 		ddt_univ_phys_t *ddp = dde->dde_phys;
1799 		ddt_univ_phys_t *rddp = rdde->dde_phys;
1800 		ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);
1801 		uint64_t phys_birth = ddt_phys_birth(ddp, v);
1802 		const dva_t *dvas, *rdvas;
1803 
1804 		if (ddt->ddt_flags & DDT_FLAG_FLAT) {
1805 			dvas = ddp->ddp_flat.ddp_dva;
1806 			rdvas = rddp->ddp_flat.ddp_dva;
1807 		} else {
1808 			dvas = ddp->ddp_trad[p].ddp_dva;
1809 			rdvas = rddp->ddp_trad[p].ddp_dva;
1810 		}
1811 
1812 		if (phys_birth == 0 ||
1813 		    phys_birth != ddt_phys_birth(rddp, v) ||
1814 		    memcmp(dvas, rdvas, sizeof (dva_t) * SPA_DVAS_PER_BP))
1815 			continue;
1816 
1817 		ddt_bp_create(ddt->ddt_checksum, ddk, ddp, v, &blk);
1818 		zio_nowait(zio_rewrite(zio, zio->io_spa, 0, &blk,
1819 		    rdde->dde_io->dde_repair_abd, DDK_GET_PSIZE(rddk),
1820 		    NULL, NULL, ZIO_PRIORITY_SYNC_WRITE,
1821 		    ZIO_DDT_CHILD_FLAGS(zio), NULL));
1822 	}
1823 
1824 	zio_nowait(zio);
1825 }
1826 
1827 static void
ddt_repair_table(ddt_t * ddt,zio_t * rio)1828 ddt_repair_table(ddt_t *ddt, zio_t *rio)
1829 {
1830 	spa_t *spa = ddt->ddt_spa;
1831 	ddt_entry_t *dde, *rdde_next, *rdde;
1832 	avl_tree_t *t = &ddt->ddt_repair_tree;
1833 	blkptr_t blk;
1834 
1835 	if (spa_sync_pass(spa) > 1)
1836 		return;
1837 
1838 	ddt_enter(ddt);
1839 	for (rdde = avl_first(t); rdde != NULL; rdde = rdde_next) {
1840 		rdde_next = AVL_NEXT(t, rdde);
1841 		avl_remove(&ddt->ddt_repair_tree, rdde);
1842 		ddt_exit(ddt);
1843 		ddt_bp_create(ddt->ddt_checksum, &rdde->dde_key, NULL,
1844 		    DDT_PHYS_NONE, &blk);
1845 		dde = ddt_repair_start(ddt, &blk);
1846 		ddt_repair_entry(ddt, dde, rdde, rio);
1847 		ddt_repair_done(ddt, dde);
1848 		ddt_enter(ddt);
1849 	}
1850 	ddt_exit(ddt);
1851 }
1852 
1853 static void
ddt_sync_update_stats(ddt_t * ddt,dmu_tx_t * tx)1854 ddt_sync_update_stats(ddt_t *ddt, dmu_tx_t *tx)
1855 {
1856 	/*
1857 	 * Count all the entries stored for each type/class, and updates the
1858 	 * stats within (ddt_object_sync()). If there's no entries for the
1859 	 * type/class, the whole object is removed. If all objects for the DDT
1860 	 * are removed, its containing dir is removed, effectively resetting
1861 	 * the entire DDT to an empty slate.
1862 	 */
1863 	uint64_t count = 0;
1864 	for (ddt_type_t type = 0; type < DDT_TYPES; type++) {
1865 		uint64_t add, tcount = 0;
1866 		for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {
1867 			if (ddt_object_exists(ddt, type, class)) {
1868 				ddt_object_sync(ddt, type, class, tx);
1869 				VERIFY0(ddt_object_count(ddt, type, class,
1870 				    &add));
1871 				tcount += add;
1872 			}
1873 		}
1874 		for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {
1875 			if (tcount == 0 && ddt_object_exists(ddt, type, class))
1876 				ddt_object_destroy(ddt, type, class, tx);
1877 		}
1878 		count += tcount;
1879 	}
1880 
1881 	if (ddt->ddt_flags & DDT_FLAG_LOG) {
1882 		/* Include logged entries in the total count */
1883 		count += avl_numnodes(&ddt->ddt_log_active->ddl_tree);
1884 		count += avl_numnodes(&ddt->ddt_log_flushing->ddl_tree);
1885 	}
1886 
1887 	if (count == 0) {
1888 		/*
1889 		 * No entries left on the DDT, so reset the version for next
1890 		 * time. This allows us to handle the feature being changed
1891 		 * since the DDT was originally created. New entries should get
1892 		 * whatever the feature currently demands.
1893 		 */
1894 		if (ddt->ddt_version == DDT_VERSION_FDT)
1895 			ddt_destroy_dir(ddt, tx);
1896 
1897 		ddt->ddt_version = DDT_VERSION_UNCONFIGURED;
1898 		ddt->ddt_flags = 0;
1899 	}
1900 
1901 	memcpy(&ddt->ddt_histogram_cache, ddt->ddt_histogram,
1902 	    sizeof (ddt->ddt_histogram));
1903 	ddt->ddt_spa->spa_dedup_dspace = ~0ULL;
1904 	ddt->ddt_spa->spa_dedup_dsize = ~0ULL;
1905 }
1906 
1907 static void
ddt_sync_scan_entry(ddt_t * ddt,ddt_lightweight_entry_t * ddlwe,dmu_tx_t * tx)1908 ddt_sync_scan_entry(ddt_t *ddt, ddt_lightweight_entry_t *ddlwe, dmu_tx_t *tx)
1909 {
1910 	dsl_pool_t *dp = ddt->ddt_spa->spa_dsl_pool;
1911 
1912 	/*
1913 	 * Compute the target class, so we can decide whether or not to inform
1914 	 * the scrub traversal (below). Note that we don't store this in the
1915 	 * entry, as it might change multiple times before finally being
1916 	 * committed (if we're logging). Instead, we recompute it in
1917 	 * ddt_sync_entry().
1918 	 */
1919 	uint64_t refcnt = ddt_phys_total_refcnt(ddt, &ddlwe->ddlwe_phys);
1920 	ddt_class_t nclass =
1921 	    (refcnt > 1) ? DDT_CLASS_DUPLICATE : DDT_CLASS_UNIQUE;
1922 
1923 	/*
1924 	 * If the class changes, the order that we scan this bp changes. If it
1925 	 * decreases, we could miss it, so scan it right now. (This covers both
1926 	 * class changing while we are doing ddt_walk(), and when we are
1927 	 * traversing.)
1928 	 *
1929 	 * We also do this when the refcnt goes to zero, because that change is
1930 	 * only in the log so far; the blocks on disk won't be freed until
1931 	 * the log is flushed, and the refcnt might increase before that. If it
1932 	 * does, then we could miss it in the same way.
1933 	 */
1934 	if (refcnt == 0 || nclass < ddlwe->ddlwe_class)
1935 		dsl_scan_ddt_entry(dp->dp_scan, ddt->ddt_checksum, ddt,
1936 		    ddlwe, tx);
1937 }
1938 
1939 static void
ddt_sync_flush_entry(ddt_t * ddt,ddt_lightweight_entry_t * ddlwe,ddt_type_t otype,ddt_class_t oclass,dmu_tx_t * tx)1940 ddt_sync_flush_entry(ddt_t *ddt, ddt_lightweight_entry_t *ddlwe,
1941     ddt_type_t otype, ddt_class_t oclass, dmu_tx_t *tx)
1942 {
1943 	ddt_key_t *ddk = &ddlwe->ddlwe_key;
1944 	ddt_type_t ntype = DDT_TYPE_DEFAULT;
1945 	uint64_t refcnt = 0;
1946 
1947 	/*
1948 	 * Compute the total refcnt. Along the way, issue frees for any DVAs
1949 	 * we no longer want.
1950 	 */
1951 	for (int p = 0; p < DDT_NPHYS(ddt); p++) {
1952 		ddt_univ_phys_t *ddp = &ddlwe->ddlwe_phys;
1953 		ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);
1954 		uint64_t phys_refcnt = ddt_phys_refcnt(ddp, v);
1955 
1956 		if (ddt_phys_birth(ddp, v) == 0) {
1957 			ASSERT0(phys_refcnt);
1958 			continue;
1959 		}
1960 		if (DDT_PHYS_IS_DITTO(ddt, p)) {
1961 			/*
1962 			 * We don't want to keep any obsolete slots (eg ditto),
1963 			 * regardless of their refcount, but we don't want to
1964 			 * leak them either. So, free them.
1965 			 */
1966 			ddt_phys_free(ddt, ddk, ddp, v, tx->tx_txg);
1967 			continue;
1968 		}
1969 		if (phys_refcnt == 0)
1970 			/* No remaining references, free it! */
1971 			ddt_phys_free(ddt, ddk, ddp, v, tx->tx_txg);
1972 		refcnt += phys_refcnt;
1973 	}
1974 
1975 	/* Select the best class for the entry. */
1976 	ddt_class_t nclass =
1977 	    (refcnt > 1) ? DDT_CLASS_DUPLICATE : DDT_CLASS_UNIQUE;
1978 
1979 	/*
1980 	 * If an existing entry changed type or class, or its refcount reached
1981 	 * zero, delete it from the DDT object
1982 	 */
1983 	if (otype != DDT_TYPES &&
1984 	    (otype != ntype || oclass != nclass || refcnt == 0)) {
1985 		VERIFY0(ddt_object_remove(ddt, otype, oclass, ddk, tx));
1986 		ASSERT(ddt_object_contains(ddt, otype, oclass, ddk) == ENOENT);
1987 	}
1988 
1989 	/*
1990 	 * Add or update the entry
1991 	 */
1992 	if (refcnt != 0) {
1993 		ddt_histogram_t *ddh =
1994 		    &ddt->ddt_histogram[ntype][nclass];
1995 
1996 		ddt_histogram_add_entry(ddt, ddh, ddlwe);
1997 
1998 		if (!ddt_object_exists(ddt, ntype, nclass))
1999 			ddt_object_create(ddt, ntype, nclass, tx);
2000 		VERIFY0(ddt_object_update(ddt, ntype, nclass, ddlwe, tx));
2001 	}
2002 }
2003 
2004 /* Calculate an exponential weighted moving average, lower limited to zero */
2005 static inline int32_t
_ewma(int32_t val,int32_t prev,uint32_t weight)2006 _ewma(int32_t val, int32_t prev, uint32_t weight)
2007 {
2008 	ASSERT3U(val, >=, 0);
2009 	ASSERT3U(prev, >=, 0);
2010 	const int32_t new =
2011 	    MAX(0, prev + (val-prev) / (int32_t)MAX(weight, 1));
2012 	ASSERT3U(new, >=, 0);
2013 	return (new);
2014 }
2015 
2016 static inline void
ddt_flush_force_update_txg(ddt_t * ddt,uint64_t txg)2017 ddt_flush_force_update_txg(ddt_t *ddt, uint64_t txg)
2018 {
2019 	/*
2020 	 * If we're not forcing flush, and not being asked to start, then
2021 	 * there's nothing more to do.
2022 	 */
2023 	if (txg == 0) {
2024 		/* Update requested, are we currently forcing flush? */
2025 		if (ddt->ddt_flush_force_txg == 0)
2026 			return;
2027 		txg = ddt->ddt_flush_force_txg;
2028 	}
2029 
2030 	/*
2031 	 * If either of the logs have entries unflushed entries before
2032 	 * the wanted txg, set the force txg, otherwise clear it.
2033 	 */
2034 
2035 	if ((!avl_is_empty(&ddt->ddt_log_active->ddl_tree) &&
2036 	    ddt->ddt_log_active->ddl_first_txg <= txg) ||
2037 	    (!avl_is_empty(&ddt->ddt_log_flushing->ddl_tree) &&
2038 	    ddt->ddt_log_flushing->ddl_first_txg <= txg)) {
2039 		ddt->ddt_flush_force_txg = txg;
2040 		return;
2041 	}
2042 
2043 	/*
2044 	 * Nothing to flush behind the given txg, so we can clear force flush
2045 	 * state.
2046 	 */
2047 	ddt->ddt_flush_force_txg = 0;
2048 }
2049 
2050 static void
ddt_sync_flush_log(ddt_t * ddt,dmu_tx_t * tx)2051 ddt_sync_flush_log(ddt_t *ddt, dmu_tx_t *tx)
2052 {
2053 	spa_t *spa = ddt->ddt_spa;
2054 	ASSERT(avl_is_empty(&ddt->ddt_tree));
2055 
2056 	/*
2057 	 * Don't do any flushing when the pool is ready to shut down, or in
2058 	 * passes beyond the first.
2059 	 */
2060 	if (spa_sync_pass(spa) > 1 || tx->tx_txg > spa_final_dirty_txg(spa))
2061 		return;
2062 
2063 	hrtime_t flush_start = gethrtime();
2064 	uint32_t count = 0;
2065 
2066 	/*
2067 	 * How many entries we need to flush. We need to at
2068 	 * least match the ingest rate, and also consider the
2069 	 * current backlog of entries.
2070 	 */
2071 	uint64_t backlog = avl_numnodes(&ddt->ddt_log_flushing->ddl_tree) +
2072 	    avl_numnodes(&ddt->ddt_log_active->ddl_tree);
2073 
2074 	if (avl_is_empty(&ddt->ddt_log_flushing->ddl_tree))
2075 		goto housekeeping;
2076 
2077 	uint64_t txgs = MAX(1, zfs_dedup_log_flush_txgs);
2078 	uint64_t cap = MAX(1, zfs_dedup_log_cap);
2079 	uint64_t flush_min = MAX(backlog / txgs,
2080 	    zfs_dedup_log_flush_entries_min);
2081 
2082 	/*
2083 	 * The theory for this block is that if we increase the pressure while
2084 	 * we're growing above the cap, and remove it when we're significantly
2085 	 * below the cap, we'll stay near cap while not bouncing around too
2086 	 * much.
2087 	 *
2088 	 * The factor of 10 is to smooth the pressure effect by expressing it
2089 	 * in tenths. The addition of the cap to the backlog in the second
2090 	 * block is to round up, instead of down. We never let the pressure go
2091 	 * below 1 (10 tenths).
2092 	 */
2093 	if (cap != UINT_MAX && backlog > cap &&
2094 	    backlog > ddt->ddt_log_flush_prev_backlog) {
2095 		ddt->ddt_log_flush_pressure += 10 * backlog / cap;
2096 	} else if (cap != UINT_MAX && backlog < cap) {
2097 		ddt->ddt_log_flush_pressure -=
2098 		    11 - (((10 * backlog) + cap - 1) / cap);
2099 		ddt->ddt_log_flush_pressure =
2100 		    MAX(ddt->ddt_log_flush_pressure, 10);
2101 	}
2102 
2103 	if (zfs_dedup_log_hard_cap && cap != UINT_MAX)
2104 		flush_min = MAX(flush_min, MIN(backlog - cap,
2105 		    (flush_min * ddt->ddt_log_flush_pressure) / 10));
2106 
2107 	uint64_t flush_max;
2108 
2109 	/*
2110 	 * If we've been asked to flush everything in a hurry,
2111 	 * try to dump as much as possible on this txg. In
2112 	 * this case we're only limited by time, not amount.
2113 	 *
2114 	 * Otherwise, if we are over the cap, try to get back down to it.
2115 	 *
2116 	 * Finally if there is no cap (or no pressure), just set the max a
2117 	 * little higher than the min to help smooth out variations in flush
2118 	 * times.
2119 	 */
2120 	if (ddt->ddt_flush_force_txg > 0)
2121 		flush_max = avl_numnodes(&ddt->ddt_log_flushing->ddl_tree);
2122 	else if (cap != UINT32_MAX && !zfs_dedup_log_hard_cap)
2123 		flush_max = MAX(flush_min * 5 / 4, MIN(backlog - cap,
2124 		    (flush_min * ddt->ddt_log_flush_pressure) / 10));
2125 	else
2126 		flush_max = flush_min * 5 / 4;
2127 	flush_max = MIN(flush_max, zfs_dedup_log_flush_entries_max);
2128 
2129 	/*
2130 	 * When the pool is busy or someone is explicitly waiting for this txg
2131 	 * to complete, use the zfs_dedup_log_flush_min_time_ms.  Otherwise use
2132 	 * half of the time in the txg timeout.
2133 	 */
2134 	uint64_t target_time;
2135 
2136 	if (txg_sync_waiting(ddt->ddt_spa->spa_dsl_pool) ||
2137 	    vdev_queue_pool_busy(spa)) {
2138 		target_time = MIN(MSEC2NSEC(zfs_dedup_log_flush_min_time_ms),
2139 		    SEC2NSEC(zfs_txg_timeout) / 2);
2140 	} else {
2141 		target_time = SEC2NSEC(zfs_txg_timeout) / 2;
2142 	}
2143 
2144 	ddt_lightweight_entry_t ddlwe;
2145 	while (ddt_log_take_first(ddt, ddt->ddt_log_flushing, &ddlwe)) {
2146 		ddt_sync_flush_entry(ddt, &ddlwe,
2147 		    ddlwe.ddlwe_type, ddlwe.ddlwe_class, tx);
2148 
2149 		/* End if we've synced as much as we needed to. */
2150 		if (++count >= flush_max)
2151 			break;
2152 
2153 		/*
2154 		 * As long as we've flushed the absolute minimum,
2155 		 * stop if we're way over our target time.
2156 		 */
2157 		uint64_t diff = gethrtime() - flush_start;
2158 		if (count > zfs_dedup_log_flush_entries_min &&
2159 		    diff >= target_time * 2)
2160 			break;
2161 
2162 		/*
2163 		 * End if we've passed the minimum flush and we're out of time.
2164 		 */
2165 		if (count > flush_min && diff >= target_time)
2166 			break;
2167 	}
2168 
2169 	if (avl_is_empty(&ddt->ddt_log_flushing->ddl_tree)) {
2170 		/* We emptied it, so truncate on-disk */
2171 		DDT_KSTAT_ZERO(ddt, dds_log_flushing_entries);
2172 		ddt_log_truncate(ddt, tx);
2173 	} else {
2174 		/* More to do next time, save checkpoint */
2175 		DDT_KSTAT_SUB(ddt, dds_log_flushing_entries, count);
2176 		ddt_log_checkpoint(ddt, &ddlwe, tx);
2177 	}
2178 
2179 	ddt_sync_update_stats(ddt, tx);
2180 
2181 housekeeping:
2182 	if (avl_is_empty(&ddt->ddt_log_flushing->ddl_tree) &&
2183 	    !avl_is_empty(&ddt->ddt_log_active->ddl_tree)) {
2184 		/*
2185 		 * No more to flush, and the active list has stuff, so
2186 		 * try to swap the logs for next time.
2187 		 */
2188 		if (ddt_log_swap(ddt, tx)) {
2189 			DDT_KSTAT_ZERO(ddt, dds_log_active_entries);
2190 			DDT_KSTAT_SET(ddt, dds_log_flushing_entries,
2191 			    avl_numnodes(&ddt->ddt_log_flushing->ddl_tree));
2192 		}
2193 	}
2194 
2195 	/* If force flush is no longer necessary, turn it off. */
2196 	ddt_flush_force_update_txg(ddt, 0);
2197 
2198 	ddt->ddt_log_flush_prev_backlog = backlog;
2199 
2200 	/*
2201 	 * Update flush rate. This is an exponential weighted moving
2202 	 * average of the number of entries flushed over recent txgs.
2203 	 */
2204 	ddt->ddt_log_flush_rate = _ewma(count, ddt->ddt_log_flush_rate,
2205 	    zfs_dedup_log_flush_flow_rate_txgs);
2206 	DDT_KSTAT_SET(ddt, dds_log_flush_rate, ddt->ddt_log_flush_rate);
2207 
2208 	/*
2209 	 * Update flush time rate. This is an exponential weighted moving
2210 	 * average of the total time taken to flush over recent txgs.
2211 	 */
2212 	ddt->ddt_log_flush_time_rate = _ewma(ddt->ddt_log_flush_time_rate,
2213 	    (int32_t)NSEC2MSEC(gethrtime() - flush_start),
2214 	    zfs_dedup_log_flush_flow_rate_txgs);
2215 	DDT_KSTAT_SET(ddt, dds_log_flush_time_rate,
2216 	    ddt->ddt_log_flush_time_rate);
2217 	if (avl_numnodes(&ddt->ddt_log_flushing->ddl_tree) > 0 &&
2218 	    zfs_flags & ZFS_DEBUG_DDT) {
2219 		zfs_dbgmsg("%lu entries remain(%lu in active), flushed %u @ "
2220 		    "txg %llu, in %llu ms, flush rate %d, time rate %d",
2221 		    (ulong_t)avl_numnodes(&ddt->ddt_log_flushing->ddl_tree),
2222 		    (ulong_t)avl_numnodes(&ddt->ddt_log_active->ddl_tree),
2223 		    count, (u_longlong_t)tx->tx_txg,
2224 		    (u_longlong_t)NSEC2MSEC(gethrtime() - flush_start),
2225 		    ddt->ddt_log_flush_rate, ddt->ddt_log_flush_time_rate);
2226 	}
2227 }
2228 
2229 static void
ddt_sync_table_log(ddt_t * ddt,dmu_tx_t * tx)2230 ddt_sync_table_log(ddt_t *ddt, dmu_tx_t *tx)
2231 {
2232 	uint64_t count = avl_numnodes(&ddt->ddt_tree);
2233 
2234 	if (count > 0) {
2235 		ddt_log_update_t dlu = {0};
2236 		ddt_log_begin(ddt, count, tx, &dlu);
2237 
2238 		ddt_entry_t *dde;
2239 		void *cookie = NULL;
2240 		ddt_lightweight_entry_t ddlwe;
2241 		while ((dde =
2242 		    avl_destroy_nodes(&ddt->ddt_tree, &cookie)) != NULL) {
2243 			ASSERT(dde->dde_flags & DDE_FLAG_LOADED);
2244 			DDT_ENTRY_TO_LIGHTWEIGHT(ddt, dde, &ddlwe);
2245 			ddt_log_entry(ddt, &ddlwe, &dlu);
2246 			ddt_sync_scan_entry(ddt, &ddlwe, tx);
2247 			ddt_free(ddt, dde);
2248 		}
2249 
2250 		ddt_log_commit(ddt, &dlu);
2251 
2252 		DDT_KSTAT_SET(ddt, dds_log_active_entries,
2253 		    avl_numnodes(&ddt->ddt_log_active->ddl_tree));
2254 
2255 		/*
2256 		 * Sync the stats for the store objects. Even though we haven't
2257 		 * modified anything on those objects, they're no longer the
2258 		 * source of truth for entries that are now in the log, and we
2259 		 * need the on-disk counts to reflect that, otherwise we'll
2260 		 * miscount later when importing.
2261 		 */
2262 		for (ddt_type_t type = 0; type < DDT_TYPES; type++) {
2263 			for (ddt_class_t class = 0;
2264 			    class < DDT_CLASSES; class++) {
2265 				if (ddt_object_exists(ddt, type, class))
2266 					ddt_object_sync(ddt, type, class, tx);
2267 			}
2268 		}
2269 
2270 		memcpy(&ddt->ddt_histogram_cache, ddt->ddt_histogram,
2271 		    sizeof (ddt->ddt_histogram));
2272 		ddt->ddt_spa->spa_dedup_dspace = ~0ULL;
2273 		ddt->ddt_spa->spa_dedup_dsize = ~0ULL;
2274 	}
2275 
2276 	if (spa_sync_pass(ddt->ddt_spa) == 1) {
2277 		/*
2278 		 * Update ingest rate. This is an exponential weighted moving
2279 		 * average of the number of entries changed over recent txgs.
2280 		 * The ramp-up cost shouldn't matter too much because the
2281 		 * flusher will be trying to take at least the minimum anyway.
2282 		 */
2283 		ddt->ddt_log_ingest_rate = _ewma(
2284 		    count, ddt->ddt_log_ingest_rate,
2285 		    zfs_dedup_log_flush_flow_rate_txgs);
2286 		DDT_KSTAT_SET(ddt, dds_log_ingest_rate,
2287 		    ddt->ddt_log_ingest_rate);
2288 	}
2289 }
2290 
2291 static void
ddt_sync_table_flush(ddt_t * ddt,dmu_tx_t * tx)2292 ddt_sync_table_flush(ddt_t *ddt, dmu_tx_t *tx)
2293 {
2294 	if (avl_numnodes(&ddt->ddt_tree) == 0)
2295 		return;
2296 
2297 	ddt_entry_t *dde;
2298 	void *cookie = NULL;
2299 	while ((dde = avl_destroy_nodes(
2300 	    &ddt->ddt_tree, &cookie)) != NULL) {
2301 		ASSERT(dde->dde_flags & DDE_FLAG_LOADED);
2302 
2303 		ddt_lightweight_entry_t ddlwe;
2304 		DDT_ENTRY_TO_LIGHTWEIGHT(ddt, dde, &ddlwe);
2305 		ddt_sync_flush_entry(ddt, &ddlwe,
2306 		    dde->dde_type, dde->dde_class, tx);
2307 		ddt_sync_scan_entry(ddt, &ddlwe, tx);
2308 		ddt_free(ddt, dde);
2309 	}
2310 
2311 	memcpy(&ddt->ddt_histogram_cache, ddt->ddt_histogram,
2312 	    sizeof (ddt->ddt_histogram));
2313 	ddt->ddt_spa->spa_dedup_dspace = ~0ULL;
2314 	ddt->ddt_spa->spa_dedup_dsize = ~0ULL;
2315 	ddt_sync_update_stats(ddt, tx);
2316 }
2317 
2318 static void
ddt_sync_table(ddt_t * ddt,dmu_tx_t * tx)2319 ddt_sync_table(ddt_t *ddt, dmu_tx_t *tx)
2320 {
2321 	spa_t *spa = ddt->ddt_spa;
2322 
2323 	if (ddt->ddt_version == UINT64_MAX)
2324 		return;
2325 
2326 	if (spa->spa_uberblock.ub_version < SPA_VERSION_DEDUP) {
2327 		ASSERT0(avl_numnodes(&ddt->ddt_tree));
2328 		return;
2329 	}
2330 
2331 	if (spa->spa_ddt_stat_object == 0) {
2332 		spa->spa_ddt_stat_object = zap_create_link(ddt->ddt_os,
2333 		    DMU_OT_DDT_STATS, DMU_POOL_DIRECTORY_OBJECT,
2334 		    DMU_POOL_DDT_STATS, tx);
2335 	}
2336 
2337 	if (ddt->ddt_version == DDT_VERSION_FDT && ddt->ddt_dir_object == 0)
2338 		ddt_create_dir(ddt, tx);
2339 
2340 	if (ddt->ddt_flags & DDT_FLAG_LOG)
2341 		ddt_sync_table_log(ddt, tx);
2342 	else
2343 		ddt_sync_table_flush(ddt, tx);
2344 }
2345 
2346 void
ddt_sync(spa_t * spa,uint64_t txg)2347 ddt_sync(spa_t *spa, uint64_t txg)
2348 {
2349 	dsl_scan_t *scn = spa->spa_dsl_pool->dp_scan;
2350 	dmu_tx_t *tx;
2351 	zio_t *rio;
2352 
2353 	ASSERT3U(spa_syncing_txg(spa), ==, txg);
2354 
2355 	tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
2356 
2357 	rio = zio_root(spa, NULL, NULL,
2358 	    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE | ZIO_FLAG_SELF_HEAL);
2359 
2360 	/*
2361 	 * This function may cause an immediate scan of ddt blocks (see
2362 	 * the comment above dsl_scan_ddt() for details). We set the
2363 	 * scan's root zio here so that we can wait for any scan IOs in
2364 	 * addition to the regular ddt IOs.
2365 	 */
2366 	ASSERT3P(scn->scn_zio_root, ==, NULL);
2367 	scn->scn_zio_root = rio;
2368 
2369 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
2370 		ddt_t *ddt = spa->spa_ddt[c];
2371 		if (ddt == NULL)
2372 			continue;
2373 		ddt_sync_table(ddt, tx);
2374 		if (ddt->ddt_flags & DDT_FLAG_LOG)
2375 			ddt_sync_flush_log(ddt, tx);
2376 		ddt_repair_table(ddt, rio);
2377 	}
2378 
2379 	(void) zio_wait(rio);
2380 	scn->scn_zio_root = NULL;
2381 
2382 	dmu_tx_commit(tx);
2383 }
2384 
2385 void
ddt_walk_init(spa_t * spa,uint64_t txg)2386 ddt_walk_init(spa_t *spa, uint64_t txg)
2387 {
2388 	if (txg == 0)
2389 		txg = spa_syncing_txg(spa);
2390 
2391 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
2392 		ddt_t *ddt = spa->spa_ddt[c];
2393 		if (ddt == NULL || !(ddt->ddt_flags & DDT_FLAG_LOG))
2394 			continue;
2395 
2396 		ddt_enter(ddt);
2397 		ddt_flush_force_update_txg(ddt, txg);
2398 		ddt_exit(ddt);
2399 	}
2400 }
2401 
2402 boolean_t
ddt_walk_ready(spa_t * spa)2403 ddt_walk_ready(spa_t *spa)
2404 {
2405 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
2406 		ddt_t *ddt = spa->spa_ddt[c];
2407 		if (ddt == NULL || !(ddt->ddt_flags & DDT_FLAG_LOG))
2408 			continue;
2409 
2410 		if (ddt->ddt_flush_force_txg > 0)
2411 			return (B_FALSE);
2412 	}
2413 
2414 	return (B_TRUE);
2415 }
2416 
2417 static int
ddt_walk_impl(spa_t * spa,ddt_bookmark_t * ddb,ddt_lightweight_entry_t * ddlwe,uint64_t flags,boolean_t wait)2418 ddt_walk_impl(spa_t *spa, ddt_bookmark_t *ddb, ddt_lightweight_entry_t *ddlwe,
2419     uint64_t flags, boolean_t wait)
2420 {
2421 	do {
2422 		do {
2423 			do {
2424 				ddt_t *ddt = spa->spa_ddt[ddb->ddb_checksum];
2425 				if (ddt == NULL)
2426 					continue;
2427 
2428 				if (flags != 0 &&
2429 				    (ddt->ddt_flags & flags) != flags)
2430 					continue;
2431 
2432 				if (wait && ddt->ddt_flush_force_txg > 0)
2433 					return (EAGAIN);
2434 
2435 				int error = ENOENT;
2436 				if (ddt_object_exists(ddt, ddb->ddb_type,
2437 				    ddb->ddb_class)) {
2438 					error = ddt_object_walk(ddt,
2439 					    ddb->ddb_type, ddb->ddb_class,
2440 					    &ddb->ddb_cursor, ddlwe);
2441 				}
2442 				if (error == 0)
2443 					return (0);
2444 				if (error != ENOENT)
2445 					return (error);
2446 				ddb->ddb_cursor = 0;
2447 			} while (++ddb->ddb_checksum < ZIO_CHECKSUM_FUNCTIONS);
2448 			ddb->ddb_checksum = 0;
2449 		} while (++ddb->ddb_type < DDT_TYPES);
2450 		ddb->ddb_type = 0;
2451 	} while (++ddb->ddb_class < DDT_CLASSES);
2452 
2453 	return (SET_ERROR(ENOENT));
2454 }
2455 
2456 int
ddt_walk(spa_t * spa,ddt_bookmark_t * ddb,ddt_lightweight_entry_t * ddlwe)2457 ddt_walk(spa_t *spa, ddt_bookmark_t *ddb, ddt_lightweight_entry_t *ddlwe)
2458 {
2459 	return (ddt_walk_impl(spa, ddb, ddlwe, 0, B_TRUE));
2460 }
2461 
2462 /*
2463  * This function is used by Block Cloning (brt.c) to increase reference
2464  * counter for the DDT entry if the block is already in DDT.
2465  *
2466  * Return false if the block, despite having the D bit set, is not present
2467  * in the DDT. This is possible when the DDT has been pruned by an admin
2468  * or by the DDT quota mechanism.
2469  */
2470 boolean_t
ddt_addref(spa_t * spa,const blkptr_t * bp)2471 ddt_addref(spa_t *spa, const blkptr_t *bp)
2472 {
2473 	ddt_t *ddt;
2474 	ddt_entry_t *dde;
2475 	boolean_t result;
2476 
2477 	spa_config_enter(spa, SCL_ZIO, FTAG, RW_READER);
2478 	ddt = ddt_select(spa, bp);
2479 	ddt_enter(ddt);
2480 
2481 	dde = ddt_lookup(ddt, bp, B_TRUE);
2482 
2483 	/* Can be NULL if the entry for this block was pruned. */
2484 	if (dde == NULL) {
2485 		ddt_exit(ddt);
2486 		spa_config_exit(spa, SCL_ZIO, FTAG);
2487 		return (B_FALSE);
2488 	}
2489 
2490 	if ((dde->dde_type < DDT_TYPES) || (dde->dde_flags & DDE_FLAG_LOGGED)) {
2491 		/*
2492 		 * This entry was either synced to a store object (dde_type is
2493 		 * real) or was logged. It must be properly on disk at this
2494 		 * point, so we can just bump its refcount.
2495 		 */
2496 		int p = DDT_PHYS_FOR_COPIES(ddt, BP_GET_NDVAS(bp));
2497 		ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);
2498 
2499 		ddt_phys_addref(dde->dde_phys, v);
2500 		result = B_TRUE;
2501 	} else {
2502 		/*
2503 		 * If the block has the DEDUP flag set it still might not
2504 		 * exist in the DEDUP table due to DDT pruning of entries
2505 		 * where refcnt=1.
2506 		 */
2507 		ddt_remove(ddt, dde);
2508 		result = B_FALSE;
2509 	}
2510 
2511 	ddt_exit(ddt);
2512 	spa_config_exit(spa, SCL_ZIO, FTAG);
2513 
2514 	return (result);
2515 }
2516 
2517 typedef struct ddt_prune_entry {
2518 	ddt_t		*dpe_ddt;
2519 	ddt_key_t	dpe_key;
2520 	list_node_t	dpe_node;
2521 	ddt_univ_phys_t	dpe_phys[];
2522 } ddt_prune_entry_t;
2523 
2524 typedef struct ddt_prune_info {
2525 	spa_t		*dpi_spa;
2526 	uint64_t	dpi_txg_syncs;
2527 	uint64_t	dpi_pruned;
2528 	list_t		dpi_candidates;
2529 } ddt_prune_info_t;
2530 
2531 /*
2532  * Add prune candidates for ddt_sync during spa_sync
2533  */
2534 static void
prune_candidates_sync(void * arg,dmu_tx_t * tx)2535 prune_candidates_sync(void *arg, dmu_tx_t *tx)
2536 {
2537 	(void) tx;
2538 	ddt_prune_info_t *dpi = arg;
2539 	ddt_prune_entry_t *dpe;
2540 
2541 	spa_config_enter(dpi->dpi_spa, SCL_ZIO, FTAG, RW_READER);
2542 
2543 	/* Process the prune candidates collected so far */
2544 	while ((dpe = list_remove_head(&dpi->dpi_candidates)) != NULL) {
2545 		blkptr_t blk;
2546 		ddt_t *ddt = dpe->dpe_ddt;
2547 
2548 		ddt_enter(ddt);
2549 
2550 		/*
2551 		 * If it's on the live list, then it was loaded for update
2552 		 * this txg and is no longer stale; skip it.
2553 		 */
2554 		if (avl_find(&ddt->ddt_tree, &dpe->dpe_key, NULL)) {
2555 			ddt_exit(ddt);
2556 			kmem_free(dpe, sizeof (*dpe));
2557 			continue;
2558 		}
2559 
2560 		ddt_bp_create(ddt->ddt_checksum, &dpe->dpe_key,
2561 		    dpe->dpe_phys, DDT_PHYS_FLAT, &blk);
2562 
2563 		ddt_entry_t *dde = ddt_lookup(ddt, &blk, B_TRUE);
2564 		if (dde != NULL && !(dde->dde_flags & DDE_FLAG_LOGGED)) {
2565 			ASSERT(dde->dde_flags & DDE_FLAG_LOADED);
2566 			/*
2567 			 * Zero the physical, so we don't try to free DVAs
2568 			 * at flush nor try to reuse this entry.
2569 			 */
2570 			ddt_phys_clear(dde->dde_phys, DDT_PHYS_FLAT);
2571 
2572 			dpi->dpi_pruned++;
2573 		}
2574 
2575 		ddt_exit(ddt);
2576 		kmem_free(dpe, sizeof (*dpe));
2577 	}
2578 
2579 	spa_config_exit(dpi->dpi_spa, SCL_ZIO, FTAG);
2580 	dpi->dpi_txg_syncs++;
2581 }
2582 
2583 /*
2584  * Prune candidates are collected in open context and processed
2585  * in sync context as part of ddt_sync_table().
2586  */
2587 static void
ddt_prune_entry(list_t * list,ddt_t * ddt,const ddt_key_t * ddk,const ddt_univ_phys_t * ddp)2588 ddt_prune_entry(list_t *list, ddt_t *ddt, const ddt_key_t *ddk,
2589     const ddt_univ_phys_t *ddp)
2590 {
2591 	ASSERT(ddt->ddt_flags & DDT_FLAG_FLAT);
2592 
2593 	size_t dpe_size = sizeof (ddt_prune_entry_t) + DDT_FLAT_PHYS_SIZE;
2594 	ddt_prune_entry_t *dpe = kmem_alloc(dpe_size, KM_SLEEP);
2595 
2596 	dpe->dpe_ddt = ddt;
2597 	dpe->dpe_key = *ddk;
2598 	memcpy(dpe->dpe_phys, ddp, DDT_FLAT_PHYS_SIZE);
2599 	list_insert_head(list, dpe);
2600 }
2601 
2602 /*
2603  * Interate over all the entries in the DDT unique class.
2604  * The walk will perform one of the following operations:
2605  *  (a) build a histogram than can be used when pruning
2606  *  (b) prune entries older than the cutoff
2607  *
2608  *  Also called by zdb(8) to dump the age histogram
2609  */
2610 void
ddt_prune_walk(spa_t * spa,uint64_t cutoff,ddt_age_histo_t * histogram)2611 ddt_prune_walk(spa_t *spa, uint64_t cutoff, ddt_age_histo_t *histogram)
2612 {
2613 	ddt_bookmark_t ddb = {
2614 		.ddb_class = DDT_CLASS_UNIQUE,
2615 		.ddb_type = 0,
2616 		.ddb_checksum = 0,
2617 		.ddb_cursor = 0
2618 	};
2619 	ddt_lightweight_entry_t ddlwe = {0};
2620 	int error;
2621 	int valid = 0;
2622 	int candidates = 0;
2623 	uint64_t now = gethrestime_sec();
2624 	ddt_prune_info_t dpi;
2625 	boolean_t pruning = (cutoff != 0);
2626 
2627 	if (pruning) {
2628 		dpi.dpi_txg_syncs = 0;
2629 		dpi.dpi_pruned = 0;
2630 		dpi.dpi_spa = spa;
2631 		list_create(&dpi.dpi_candidates, sizeof (ddt_prune_entry_t),
2632 		    offsetof(ddt_prune_entry_t, dpe_node));
2633 	}
2634 
2635 	if (histogram != NULL)
2636 		memset(histogram, 0, sizeof (ddt_age_histo_t));
2637 
2638 	while ((error =
2639 	    ddt_walk_impl(spa, &ddb, &ddlwe, DDT_FLAG_FLAT, B_FALSE)) == 0) {
2640 		ddt_t *ddt = spa->spa_ddt[ddb.ddb_checksum];
2641 		VERIFY(ddt);
2642 
2643 		if (spa_shutting_down(spa) || issig())
2644 			break;
2645 
2646 		ASSERT(ddt->ddt_flags & DDT_FLAG_FLAT);
2647 		ASSERT3U(ddlwe.ddlwe_phys.ddp_flat.ddp_refcnt, <=, 1);
2648 
2649 		uint64_t class_start =
2650 		    ddlwe.ddlwe_phys.ddp_flat.ddp_class_start;
2651 
2652 		/*
2653 		 * If this entry is on the log, then the stored entry is stale
2654 		 * and we should skip it.
2655 		 */
2656 		if (ddt_log_find_key(ddt, &ddlwe.ddlwe_key, NULL))
2657 			continue;
2658 
2659 		/* prune older entries */
2660 		if (pruning && class_start < cutoff) {
2661 			if (candidates++ >= zfs_ddt_prunes_per_txg) {
2662 				/* sync prune candidates in batches */
2663 				VERIFY0(dsl_sync_task(spa_name(spa),
2664 				    NULL, prune_candidates_sync,
2665 				    &dpi, 0, ZFS_SPACE_CHECK_NONE));
2666 				candidates = 1;
2667 			}
2668 			ddt_prune_entry(&dpi.dpi_candidates, ddt,
2669 			    &ddlwe.ddlwe_key, &ddlwe.ddlwe_phys);
2670 		}
2671 
2672 		/* build a histogram */
2673 		if (histogram != NULL) {
2674 			uint64_t age = MAX(1, (now - class_start) / 3600);
2675 			int bin = MIN(highbit64(age) - 1, HIST_BINS - 1);
2676 			histogram->dah_entries++;
2677 			histogram->dah_age_histo[bin]++;
2678 		}
2679 
2680 		valid++;
2681 	}
2682 
2683 	if (pruning && valid > 0) {
2684 		if (!list_is_empty(&dpi.dpi_candidates)) {
2685 			/* sync out final batch of prune candidates */
2686 			VERIFY0(dsl_sync_task(spa_name(spa), NULL,
2687 			    prune_candidates_sync, &dpi, 0,
2688 			    ZFS_SPACE_CHECK_NONE));
2689 		}
2690 		list_destroy(&dpi.dpi_candidates);
2691 
2692 		zfs_dbgmsg("pruned %llu entries (%d%%) across %llu txg syncs",
2693 		    (u_longlong_t)dpi.dpi_pruned,
2694 		    (int)((dpi.dpi_pruned * 100) / valid),
2695 		    (u_longlong_t)dpi.dpi_txg_syncs);
2696 	}
2697 }
2698 
2699 static uint64_t
ddt_total_entries(spa_t * spa)2700 ddt_total_entries(spa_t *spa)
2701 {
2702 	ddt_object_t ddo;
2703 	ddt_get_dedup_object_stats(spa, &ddo);
2704 
2705 	return (ddo.ddo_count);
2706 }
2707 
2708 int
ddt_prune_unique_entries(spa_t * spa,zpool_ddt_prune_unit_t unit,uint64_t amount)2709 ddt_prune_unique_entries(spa_t *spa, zpool_ddt_prune_unit_t unit,
2710     uint64_t amount)
2711 {
2712 	uint64_t cutoff;
2713 	uint64_t start_time = gethrtime();
2714 
2715 	if (spa->spa_active_ddt_prune)
2716 		return (SET_ERROR(EALREADY));
2717 	if (ddt_total_entries(spa) == 0)
2718 		return (0);
2719 
2720 	spa->spa_active_ddt_prune = B_TRUE;
2721 
2722 	zfs_dbgmsg("prune %llu %s", (u_longlong_t)amount,
2723 	    unit == ZPOOL_DDT_PRUNE_PERCENTAGE ? "%" : "seconds old or older");
2724 
2725 	if (unit == ZPOOL_DDT_PRUNE_PERCENTAGE) {
2726 		ddt_age_histo_t histogram;
2727 		uint64_t oldest = 0;
2728 
2729 		/* Make a pass over DDT to build a histogram */
2730 		ddt_prune_walk(spa, 0, &histogram);
2731 
2732 		int target = (histogram.dah_entries * amount) / 100;
2733 
2734 		/*
2735 		 * Figure out our cutoff date
2736 		 * (i.e., which bins to prune from)
2737 		 */
2738 		for (int i = HIST_BINS - 1; i >= 0 && target > 0; i--) {
2739 			if (histogram.dah_age_histo[i] != 0) {
2740 				/* less than this bucket remaining */
2741 				if (target < histogram.dah_age_histo[i]) {
2742 					oldest = MAX(1, (1<<i) * 3600);
2743 					target = 0;
2744 				} else {
2745 					target -= histogram.dah_age_histo[i];
2746 				}
2747 			}
2748 		}
2749 		cutoff = gethrestime_sec() - oldest;
2750 
2751 		if (ddt_dump_prune_histogram)
2752 			ddt_dump_age_histogram(&histogram, cutoff);
2753 	} else if (unit == ZPOOL_DDT_PRUNE_AGE) {
2754 		cutoff = gethrestime_sec() - amount;
2755 	} else {
2756 		return (EINVAL);
2757 	}
2758 
2759 	if (cutoff > 0 && !spa_shutting_down(spa) && !issig()) {
2760 		/* Traverse DDT to prune entries older that our cuttoff */
2761 		ddt_prune_walk(spa, cutoff, NULL);
2762 	}
2763 
2764 	zfs_dbgmsg("%s: prune completed in %llu ms",
2765 	    spa_name(spa), (u_longlong_t)NSEC2MSEC(gethrtime() - start_time));
2766 
2767 	spa->spa_active_ddt_prune = B_FALSE;
2768 	return (0);
2769 }
2770 
2771 ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, prefetch, INT, ZMOD_RW,
2772 	"Enable prefetching dedup-ed blks");
2773 
2774 ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_flush_min_time_ms, UINT, ZMOD_RW,
2775 	"Min time to spend on incremental dedup log flush each transaction");
2776 
2777 ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_flush_entries_min, UINT, ZMOD_RW,
2778 	"Min number of log entries to flush each transaction");
2779 
2780 ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_flush_entries_max, UINT, ZMOD_RW,
2781 	"Max number of log entries to flush each transaction");
2782 
2783 ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_flush_txgs, UINT, ZMOD_RW,
2784 	"Number of TXGs to try to rotate the log in");
2785 
2786 ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_cap, UINT, ZMOD_RW,
2787 	"Soft cap for the size of the current dedup log");
2788 
2789 ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_hard_cap, UINT, ZMOD_RW,
2790 	"Whether to use the soft cap as a hard cap");
2791 
2792 ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_flush_flow_rate_txgs, UINT, ZMOD_RW,
2793 	"Number of txgs to average flow rates across");
2794