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