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