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