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