xref: /freebsd/sys/contrib/openzfs/module/zfs/ddt.c (revision c03c5b1c80914ec656fbee84539355d1fad68bf9)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2012, 2016 by Delphix. All rights reserved.
25  */
26 
27 #include <sys/zfs_context.h>
28 #include <sys/spa.h>
29 #include <sys/spa_impl.h>
30 #include <sys/zio.h>
31 #include <sys/ddt.h>
32 #include <sys/zap.h>
33 #include <sys/dmu_tx.h>
34 #include <sys/arc.h>
35 #include <sys/dsl_pool.h>
36 #include <sys/zio_checksum.h>
37 #include <sys/zio_compress.h>
38 #include <sys/dsl_scan.h>
39 #include <sys/abd.h>
40 
41 static kmem_cache_t *ddt_cache;
42 static kmem_cache_t *ddt_entry_cache;
43 
44 /*
45  * Enable/disable prefetching of dedup-ed blocks which are going to be freed.
46  */
47 int zfs_dedup_prefetch = 0;
48 
49 static const ddt_ops_t *ddt_ops[DDT_TYPES] = {
50 	&ddt_zap_ops,
51 };
52 
53 static const char *ddt_class_name[DDT_CLASSES] = {
54 	"ditto",
55 	"duplicate",
56 	"unique",
57 };
58 
59 static void
60 ddt_object_create(ddt_t *ddt, enum ddt_type type, enum ddt_class class,
61     dmu_tx_t *tx)
62 {
63 	spa_t *spa = ddt->ddt_spa;
64 	objset_t *os = ddt->ddt_os;
65 	uint64_t *objectp = &ddt->ddt_object[type][class];
66 	boolean_t prehash = zio_checksum_table[ddt->ddt_checksum].ci_flags &
67 	    ZCHECKSUM_FLAG_DEDUP;
68 	char name[DDT_NAMELEN];
69 
70 	ddt_object_name(ddt, type, class, name);
71 
72 	ASSERT(*objectp == 0);
73 	VERIFY(ddt_ops[type]->ddt_op_create(os, objectp, tx, prehash) == 0);
74 	ASSERT(*objectp != 0);
75 
76 	VERIFY(zap_add(os, DMU_POOL_DIRECTORY_OBJECT, name,
77 	    sizeof (uint64_t), 1, objectp, tx) == 0);
78 
79 	VERIFY(zap_add(os, spa->spa_ddt_stat_object, name,
80 	    sizeof (uint64_t), sizeof (ddt_histogram_t) / sizeof (uint64_t),
81 	    &ddt->ddt_histogram[type][class], tx) == 0);
82 }
83 
84 static void
85 ddt_object_destroy(ddt_t *ddt, enum ddt_type type, enum ddt_class class,
86     dmu_tx_t *tx)
87 {
88 	spa_t *spa = ddt->ddt_spa;
89 	objset_t *os = ddt->ddt_os;
90 	uint64_t *objectp = &ddt->ddt_object[type][class];
91 	uint64_t count;
92 	char name[DDT_NAMELEN];
93 
94 	ddt_object_name(ddt, type, class, name);
95 
96 	ASSERT(*objectp != 0);
97 	ASSERT(ddt_histogram_empty(&ddt->ddt_histogram[type][class]));
98 	VERIFY(ddt_object_count(ddt, type, class, &count) == 0 && count == 0);
99 	VERIFY(zap_remove(os, DMU_POOL_DIRECTORY_OBJECT, name, tx) == 0);
100 	VERIFY(zap_remove(os, spa->spa_ddt_stat_object, name, tx) == 0);
101 	VERIFY(ddt_ops[type]->ddt_op_destroy(os, *objectp, tx) == 0);
102 	bzero(&ddt->ddt_object_stats[type][class], sizeof (ddt_object_t));
103 
104 	*objectp = 0;
105 }
106 
107 static int
108 ddt_object_load(ddt_t *ddt, enum ddt_type type, enum ddt_class class)
109 {
110 	ddt_object_t *ddo = &ddt->ddt_object_stats[type][class];
111 	dmu_object_info_t doi;
112 	uint64_t count;
113 	char name[DDT_NAMELEN];
114 	int error;
115 
116 	ddt_object_name(ddt, type, class, name);
117 
118 	error = zap_lookup(ddt->ddt_os, DMU_POOL_DIRECTORY_OBJECT, name,
119 	    sizeof (uint64_t), 1, &ddt->ddt_object[type][class]);
120 	if (error != 0)
121 		return (error);
122 
123 	error = zap_lookup(ddt->ddt_os, ddt->ddt_spa->spa_ddt_stat_object, name,
124 	    sizeof (uint64_t), sizeof (ddt_histogram_t) / sizeof (uint64_t),
125 	    &ddt->ddt_histogram[type][class]);
126 	if (error != 0)
127 		return (error);
128 
129 	/*
130 	 * Seed the cached statistics.
131 	 */
132 	error = ddt_object_info(ddt, type, class, &doi);
133 	if (error)
134 		return (error);
135 
136 	error = ddt_object_count(ddt, type, class, &count);
137 	if (error)
138 		return (error);
139 
140 	ddo->ddo_count = count;
141 	ddo->ddo_dspace = doi.doi_physical_blocks_512 << 9;
142 	ddo->ddo_mspace = doi.doi_fill_count * doi.doi_data_block_size;
143 
144 	return (0);
145 }
146 
147 static void
148 ddt_object_sync(ddt_t *ddt, enum ddt_type type, enum ddt_class class,
149     dmu_tx_t *tx)
150 {
151 	ddt_object_t *ddo = &ddt->ddt_object_stats[type][class];
152 	dmu_object_info_t doi;
153 	uint64_t count;
154 	char name[DDT_NAMELEN];
155 
156 	ddt_object_name(ddt, type, class, name);
157 
158 	VERIFY(zap_update(ddt->ddt_os, ddt->ddt_spa->spa_ddt_stat_object, name,
159 	    sizeof (uint64_t), sizeof (ddt_histogram_t) / sizeof (uint64_t),
160 	    &ddt->ddt_histogram[type][class], tx) == 0);
161 
162 	/*
163 	 * Cache DDT statistics; this is the only time they'll change.
164 	 */
165 	VERIFY(ddt_object_info(ddt, type, class, &doi) == 0);
166 	VERIFY(ddt_object_count(ddt, type, class, &count) == 0);
167 
168 	ddo->ddo_count = count;
169 	ddo->ddo_dspace = doi.doi_physical_blocks_512 << 9;
170 	ddo->ddo_mspace = doi.doi_fill_count * doi.doi_data_block_size;
171 }
172 
173 static int
174 ddt_object_lookup(ddt_t *ddt, enum ddt_type type, enum ddt_class class,
175     ddt_entry_t *dde)
176 {
177 	if (!ddt_object_exists(ddt, type, class))
178 		return (SET_ERROR(ENOENT));
179 
180 	return (ddt_ops[type]->ddt_op_lookup(ddt->ddt_os,
181 	    ddt->ddt_object[type][class], dde));
182 }
183 
184 static void
185 ddt_object_prefetch(ddt_t *ddt, enum ddt_type type, enum ddt_class class,
186     ddt_entry_t *dde)
187 {
188 	if (!ddt_object_exists(ddt, type, class))
189 		return;
190 
191 	ddt_ops[type]->ddt_op_prefetch(ddt->ddt_os,
192 	    ddt->ddt_object[type][class], dde);
193 }
194 
195 int
196 ddt_object_update(ddt_t *ddt, enum ddt_type type, enum ddt_class class,
197     ddt_entry_t *dde, dmu_tx_t *tx)
198 {
199 	ASSERT(ddt_object_exists(ddt, type, class));
200 
201 	return (ddt_ops[type]->ddt_op_update(ddt->ddt_os,
202 	    ddt->ddt_object[type][class], dde, tx));
203 }
204 
205 static int
206 ddt_object_remove(ddt_t *ddt, enum ddt_type type, enum ddt_class class,
207     ddt_entry_t *dde, dmu_tx_t *tx)
208 {
209 	ASSERT(ddt_object_exists(ddt, type, class));
210 
211 	return (ddt_ops[type]->ddt_op_remove(ddt->ddt_os,
212 	    ddt->ddt_object[type][class], dde, tx));
213 }
214 
215 int
216 ddt_object_walk(ddt_t *ddt, enum ddt_type type, enum ddt_class class,
217     uint64_t *walk, ddt_entry_t *dde)
218 {
219 	ASSERT(ddt_object_exists(ddt, type, class));
220 
221 	return (ddt_ops[type]->ddt_op_walk(ddt->ddt_os,
222 	    ddt->ddt_object[type][class], dde, walk));
223 }
224 
225 int
226 ddt_object_count(ddt_t *ddt, enum ddt_type type, enum ddt_class class,
227     uint64_t *count)
228 {
229 	ASSERT(ddt_object_exists(ddt, type, class));
230 
231 	return (ddt_ops[type]->ddt_op_count(ddt->ddt_os,
232 	    ddt->ddt_object[type][class], count));
233 }
234 
235 int
236 ddt_object_info(ddt_t *ddt, enum ddt_type type, enum ddt_class class,
237     dmu_object_info_t *doi)
238 {
239 	if (!ddt_object_exists(ddt, type, class))
240 		return (SET_ERROR(ENOENT));
241 
242 	return (dmu_object_info(ddt->ddt_os, ddt->ddt_object[type][class],
243 	    doi));
244 }
245 
246 boolean_t
247 ddt_object_exists(ddt_t *ddt, enum ddt_type type, enum ddt_class class)
248 {
249 	return (!!ddt->ddt_object[type][class]);
250 }
251 
252 void
253 ddt_object_name(ddt_t *ddt, enum ddt_type type, enum ddt_class class,
254     char *name)
255 {
256 	(void) snprintf(name, DDT_NAMELEN, DMU_POOL_DDT,
257 	    zio_checksum_table[ddt->ddt_checksum].ci_name,
258 	    ddt_ops[type]->ddt_op_name, ddt_class_name[class]);
259 }
260 
261 void
262 ddt_bp_fill(const ddt_phys_t *ddp, blkptr_t *bp, uint64_t txg)
263 {
264 	ASSERT(txg != 0);
265 
266 	for (int d = 0; d < SPA_DVAS_PER_BP; d++)
267 		bp->blk_dva[d] = ddp->ddp_dva[d];
268 	BP_SET_BIRTH(bp, txg, ddp->ddp_phys_birth);
269 }
270 
271 /*
272  * The bp created via this function may be used for repairs and scrub, but it
273  * will be missing the salt / IV required to do a full decrypting read.
274  */
275 void
276 ddt_bp_create(enum zio_checksum checksum,
277     const ddt_key_t *ddk, const ddt_phys_t *ddp, blkptr_t *bp)
278 {
279 	BP_ZERO(bp);
280 
281 	if (ddp != NULL)
282 		ddt_bp_fill(ddp, bp, ddp->ddp_phys_birth);
283 
284 	bp->blk_cksum = ddk->ddk_cksum;
285 
286 	BP_SET_LSIZE(bp, DDK_GET_LSIZE(ddk));
287 	BP_SET_PSIZE(bp, DDK_GET_PSIZE(ddk));
288 	BP_SET_COMPRESS(bp, DDK_GET_COMPRESS(ddk));
289 	BP_SET_CRYPT(bp, DDK_GET_CRYPT(ddk));
290 	BP_SET_FILL(bp, 1);
291 	BP_SET_CHECKSUM(bp, checksum);
292 	BP_SET_TYPE(bp, DMU_OT_DEDUP);
293 	BP_SET_LEVEL(bp, 0);
294 	BP_SET_DEDUP(bp, 1);
295 	BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
296 }
297 
298 void
299 ddt_key_fill(ddt_key_t *ddk, const blkptr_t *bp)
300 {
301 	ddk->ddk_cksum = bp->blk_cksum;
302 	ddk->ddk_prop = 0;
303 
304 	ASSERT(BP_IS_ENCRYPTED(bp) || !BP_USES_CRYPT(bp));
305 
306 	DDK_SET_LSIZE(ddk, BP_GET_LSIZE(bp));
307 	DDK_SET_PSIZE(ddk, BP_GET_PSIZE(bp));
308 	DDK_SET_COMPRESS(ddk, BP_GET_COMPRESS(bp));
309 	DDK_SET_CRYPT(ddk, BP_USES_CRYPT(bp));
310 }
311 
312 void
313 ddt_phys_fill(ddt_phys_t *ddp, const blkptr_t *bp)
314 {
315 	ASSERT(ddp->ddp_phys_birth == 0);
316 
317 	for (int d = 0; d < SPA_DVAS_PER_BP; d++)
318 		ddp->ddp_dva[d] = bp->blk_dva[d];
319 	ddp->ddp_phys_birth = BP_PHYSICAL_BIRTH(bp);
320 }
321 
322 void
323 ddt_phys_clear(ddt_phys_t *ddp)
324 {
325 	bzero(ddp, sizeof (*ddp));
326 }
327 
328 void
329 ddt_phys_addref(ddt_phys_t *ddp)
330 {
331 	ddp->ddp_refcnt++;
332 }
333 
334 void
335 ddt_phys_decref(ddt_phys_t *ddp)
336 {
337 	if (ddp) {
338 		ASSERT(ddp->ddp_refcnt > 0);
339 		ddp->ddp_refcnt--;
340 	}
341 }
342 
343 void
344 ddt_phys_free(ddt_t *ddt, ddt_key_t *ddk, ddt_phys_t *ddp, uint64_t txg)
345 {
346 	blkptr_t blk;
347 
348 	ddt_bp_create(ddt->ddt_checksum, ddk, ddp, &blk);
349 
350 	/*
351 	 * We clear the dedup bit so that zio_free() will actually free the
352 	 * space, rather than just decrementing the refcount in the DDT.
353 	 */
354 	BP_SET_DEDUP(&blk, 0);
355 
356 	ddt_phys_clear(ddp);
357 	zio_free(ddt->ddt_spa, txg, &blk);
358 }
359 
360 ddt_phys_t *
361 ddt_phys_select(const ddt_entry_t *dde, const blkptr_t *bp)
362 {
363 	ddt_phys_t *ddp = (ddt_phys_t *)dde->dde_phys;
364 
365 	for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
366 		if (DVA_EQUAL(BP_IDENTITY(bp), &ddp->ddp_dva[0]) &&
367 		    BP_PHYSICAL_BIRTH(bp) == ddp->ddp_phys_birth)
368 			return (ddp);
369 	}
370 	return (NULL);
371 }
372 
373 uint64_t
374 ddt_phys_total_refcnt(const ddt_entry_t *dde)
375 {
376 	uint64_t refcnt = 0;
377 
378 	for (int p = DDT_PHYS_SINGLE; p <= DDT_PHYS_TRIPLE; p++)
379 		refcnt += dde->dde_phys[p].ddp_refcnt;
380 
381 	return (refcnt);
382 }
383 
384 static void
385 ddt_stat_generate(ddt_t *ddt, ddt_entry_t *dde, ddt_stat_t *dds)
386 {
387 	spa_t *spa = ddt->ddt_spa;
388 	ddt_phys_t *ddp = dde->dde_phys;
389 	ddt_key_t *ddk = &dde->dde_key;
390 	uint64_t lsize = DDK_GET_LSIZE(ddk);
391 	uint64_t psize = DDK_GET_PSIZE(ddk);
392 
393 	bzero(dds, sizeof (*dds));
394 
395 	for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
396 		uint64_t dsize = 0;
397 		uint64_t refcnt = ddp->ddp_refcnt;
398 
399 		if (ddp->ddp_phys_birth == 0)
400 			continue;
401 
402 		for (int d = 0; d < DDE_GET_NDVAS(dde); d++)
403 			dsize += dva_get_dsize_sync(spa, &ddp->ddp_dva[d]);
404 
405 		dds->dds_blocks += 1;
406 		dds->dds_lsize += lsize;
407 		dds->dds_psize += psize;
408 		dds->dds_dsize += dsize;
409 
410 		dds->dds_ref_blocks += refcnt;
411 		dds->dds_ref_lsize += lsize * refcnt;
412 		dds->dds_ref_psize += psize * refcnt;
413 		dds->dds_ref_dsize += dsize * refcnt;
414 	}
415 }
416 
417 void
418 ddt_stat_add(ddt_stat_t *dst, const ddt_stat_t *src, uint64_t neg)
419 {
420 	const uint64_t *s = (const uint64_t *)src;
421 	uint64_t *d = (uint64_t *)dst;
422 	uint64_t *d_end = (uint64_t *)(dst + 1);
423 
424 	ASSERT(neg == 0 || neg == -1ULL);	/* add or subtract */
425 
426 	for (int i = 0; i < d_end - d; i++)
427 		d[i] += (s[i] ^ neg) - neg;
428 }
429 
430 static void
431 ddt_stat_update(ddt_t *ddt, ddt_entry_t *dde, uint64_t neg)
432 {
433 	ddt_stat_t dds;
434 	ddt_histogram_t *ddh;
435 	int bucket;
436 
437 	ddt_stat_generate(ddt, dde, &dds);
438 
439 	bucket = highbit64(dds.dds_ref_blocks) - 1;
440 	ASSERT(bucket >= 0);
441 
442 	ddh = &ddt->ddt_histogram[dde->dde_type][dde->dde_class];
443 
444 	ddt_stat_add(&ddh->ddh_stat[bucket], &dds, neg);
445 }
446 
447 void
448 ddt_histogram_add(ddt_histogram_t *dst, const ddt_histogram_t *src)
449 {
450 	for (int h = 0; h < 64; h++)
451 		ddt_stat_add(&dst->ddh_stat[h], &src->ddh_stat[h], 0);
452 }
453 
454 void
455 ddt_histogram_stat(ddt_stat_t *dds, const ddt_histogram_t *ddh)
456 {
457 	bzero(dds, sizeof (*dds));
458 
459 	for (int h = 0; h < 64; h++)
460 		ddt_stat_add(dds, &ddh->ddh_stat[h], 0);
461 }
462 
463 boolean_t
464 ddt_histogram_empty(const ddt_histogram_t *ddh)
465 {
466 	const uint64_t *s = (const uint64_t *)ddh;
467 	const uint64_t *s_end = (const uint64_t *)(ddh + 1);
468 
469 	while (s < s_end)
470 		if (*s++ != 0)
471 			return (B_FALSE);
472 
473 	return (B_TRUE);
474 }
475 
476 void
477 ddt_get_dedup_object_stats(spa_t *spa, ddt_object_t *ddo_total)
478 {
479 	/* Sum the statistics we cached in ddt_object_sync(). */
480 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
481 		ddt_t *ddt = spa->spa_ddt[c];
482 		for (enum ddt_type type = 0; type < DDT_TYPES; type++) {
483 			for (enum ddt_class class = 0; class < DDT_CLASSES;
484 			    class++) {
485 				ddt_object_t *ddo =
486 				    &ddt->ddt_object_stats[type][class];
487 				ddo_total->ddo_count += ddo->ddo_count;
488 				ddo_total->ddo_dspace += ddo->ddo_dspace;
489 				ddo_total->ddo_mspace += ddo->ddo_mspace;
490 			}
491 		}
492 	}
493 
494 	/* ... and compute the averages. */
495 	if (ddo_total->ddo_count != 0) {
496 		ddo_total->ddo_dspace /= ddo_total->ddo_count;
497 		ddo_total->ddo_mspace /= ddo_total->ddo_count;
498 	}
499 }
500 
501 void
502 ddt_get_dedup_histogram(spa_t *spa, ddt_histogram_t *ddh)
503 {
504 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
505 		ddt_t *ddt = spa->spa_ddt[c];
506 		for (enum ddt_type type = 0; type < DDT_TYPES && ddt; type++) {
507 			for (enum ddt_class class = 0; class < DDT_CLASSES;
508 			    class++) {
509 				ddt_histogram_add(ddh,
510 				    &ddt->ddt_histogram_cache[type][class]);
511 			}
512 		}
513 	}
514 }
515 
516 void
517 ddt_get_dedup_stats(spa_t *spa, ddt_stat_t *dds_total)
518 {
519 	ddt_histogram_t *ddh_total;
520 
521 	ddh_total = kmem_zalloc(sizeof (ddt_histogram_t), KM_SLEEP);
522 	ddt_get_dedup_histogram(spa, ddh_total);
523 	ddt_histogram_stat(dds_total, ddh_total);
524 	kmem_free(ddh_total, sizeof (ddt_histogram_t));
525 }
526 
527 uint64_t
528 ddt_get_dedup_dspace(spa_t *spa)
529 {
530 	ddt_stat_t dds_total;
531 
532 	if (spa->spa_dedup_dspace != ~0ULL)
533 		return (spa->spa_dedup_dspace);
534 
535 	bzero(&dds_total, sizeof (ddt_stat_t));
536 
537 	/* Calculate and cache the stats */
538 	ddt_get_dedup_stats(spa, &dds_total);
539 	spa->spa_dedup_dspace = dds_total.dds_ref_dsize - dds_total.dds_dsize;
540 	return (spa->spa_dedup_dspace);
541 }
542 
543 uint64_t
544 ddt_get_pool_dedup_ratio(spa_t *spa)
545 {
546 	ddt_stat_t dds_total = { 0 };
547 
548 	ddt_get_dedup_stats(spa, &dds_total);
549 	if (dds_total.dds_dsize == 0)
550 		return (100);
551 
552 	return (dds_total.dds_ref_dsize * 100 / dds_total.dds_dsize);
553 }
554 
555 size_t
556 ddt_compress(void *src, uchar_t *dst, size_t s_len, size_t d_len)
557 {
558 	uchar_t *version = dst++;
559 	int cpfunc = ZIO_COMPRESS_ZLE;
560 	zio_compress_info_t *ci = &zio_compress_table[cpfunc];
561 	size_t c_len;
562 
563 	ASSERT(d_len >= s_len + 1);	/* no compression plus version byte */
564 
565 	c_len = ci->ci_compress(src, dst, s_len, d_len - 1, ci->ci_level);
566 
567 	if (c_len == s_len) {
568 		cpfunc = ZIO_COMPRESS_OFF;
569 		bcopy(src, dst, s_len);
570 	}
571 
572 	*version = cpfunc;
573 	if (ZFS_HOST_BYTEORDER)
574 		*version |= DDT_COMPRESS_BYTEORDER_MASK;
575 
576 	return (c_len + 1);
577 }
578 
579 void
580 ddt_decompress(uchar_t *src, void *dst, size_t s_len, size_t d_len)
581 {
582 	uchar_t version = *src++;
583 	int cpfunc = version & DDT_COMPRESS_FUNCTION_MASK;
584 	zio_compress_info_t *ci = &zio_compress_table[cpfunc];
585 
586 	if (ci->ci_decompress != NULL)
587 		(void) ci->ci_decompress(src, dst, s_len, d_len, ci->ci_level);
588 	else
589 		bcopy(src, dst, d_len);
590 
591 	if (((version & DDT_COMPRESS_BYTEORDER_MASK) != 0) !=
592 	    (ZFS_HOST_BYTEORDER != 0))
593 		byteswap_uint64_array(dst, d_len);
594 }
595 
596 ddt_t *
597 ddt_select(spa_t *spa, const blkptr_t *bp)
598 {
599 	return (spa->spa_ddt[BP_GET_CHECKSUM(bp)]);
600 }
601 
602 void
603 ddt_enter(ddt_t *ddt)
604 {
605 	mutex_enter(&ddt->ddt_lock);
606 }
607 
608 void
609 ddt_exit(ddt_t *ddt)
610 {
611 	mutex_exit(&ddt->ddt_lock);
612 }
613 
614 void
615 ddt_init(void)
616 {
617 	ddt_cache = kmem_cache_create("ddt_cache",
618 	    sizeof (ddt_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
619 	ddt_entry_cache = kmem_cache_create("ddt_entry_cache",
620 	    sizeof (ddt_entry_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
621 }
622 
623 void
624 ddt_fini(void)
625 {
626 	kmem_cache_destroy(ddt_entry_cache);
627 	kmem_cache_destroy(ddt_cache);
628 }
629 
630 static ddt_entry_t *
631 ddt_alloc(const ddt_key_t *ddk)
632 {
633 	ddt_entry_t *dde;
634 
635 	dde = kmem_cache_alloc(ddt_entry_cache, KM_SLEEP);
636 	bzero(dde, sizeof (ddt_entry_t));
637 	cv_init(&dde->dde_cv, NULL, CV_DEFAULT, NULL);
638 
639 	dde->dde_key = *ddk;
640 
641 	return (dde);
642 }
643 
644 static void
645 ddt_free(ddt_entry_t *dde)
646 {
647 	ASSERT(!dde->dde_loading);
648 
649 	for (int p = 0; p < DDT_PHYS_TYPES; p++)
650 		ASSERT(dde->dde_lead_zio[p] == NULL);
651 
652 	if (dde->dde_repair_abd != NULL)
653 		abd_free(dde->dde_repair_abd);
654 
655 	cv_destroy(&dde->dde_cv);
656 	kmem_cache_free(ddt_entry_cache, dde);
657 }
658 
659 void
660 ddt_remove(ddt_t *ddt, ddt_entry_t *dde)
661 {
662 	ASSERT(MUTEX_HELD(&ddt->ddt_lock));
663 
664 	avl_remove(&ddt->ddt_tree, dde);
665 	ddt_free(dde);
666 }
667 
668 ddt_entry_t *
669 ddt_lookup(ddt_t *ddt, const blkptr_t *bp, boolean_t add)
670 {
671 	ddt_entry_t *dde, dde_search;
672 	enum ddt_type type;
673 	enum ddt_class class;
674 	avl_index_t where;
675 	int error;
676 
677 	ASSERT(MUTEX_HELD(&ddt->ddt_lock));
678 
679 	ddt_key_fill(&dde_search.dde_key, bp);
680 
681 	dde = avl_find(&ddt->ddt_tree, &dde_search, &where);
682 	if (dde == NULL) {
683 		if (!add)
684 			return (NULL);
685 		dde = ddt_alloc(&dde_search.dde_key);
686 		avl_insert(&ddt->ddt_tree, dde, where);
687 	}
688 
689 	while (dde->dde_loading)
690 		cv_wait(&dde->dde_cv, &ddt->ddt_lock);
691 
692 	if (dde->dde_loaded)
693 		return (dde);
694 
695 	dde->dde_loading = B_TRUE;
696 
697 	ddt_exit(ddt);
698 
699 	error = ENOENT;
700 
701 	for (type = 0; type < DDT_TYPES; type++) {
702 		for (class = 0; class < DDT_CLASSES; class++) {
703 			error = ddt_object_lookup(ddt, type, class, dde);
704 			if (error != ENOENT) {
705 				ASSERT0(error);
706 				break;
707 			}
708 		}
709 		if (error != ENOENT)
710 			break;
711 	}
712 
713 	ddt_enter(ddt);
714 
715 	ASSERT(dde->dde_loaded == B_FALSE);
716 	ASSERT(dde->dde_loading == B_TRUE);
717 
718 	dde->dde_type = type;	/* will be DDT_TYPES if no entry found */
719 	dde->dde_class = class;	/* will be DDT_CLASSES if no entry found */
720 	dde->dde_loaded = B_TRUE;
721 	dde->dde_loading = B_FALSE;
722 
723 	if (error == 0)
724 		ddt_stat_update(ddt, dde, -1ULL);
725 
726 	cv_broadcast(&dde->dde_cv);
727 
728 	return (dde);
729 }
730 
731 void
732 ddt_prefetch(spa_t *spa, const blkptr_t *bp)
733 {
734 	ddt_t *ddt;
735 	ddt_entry_t dde;
736 
737 	if (!zfs_dedup_prefetch || bp == NULL || !BP_GET_DEDUP(bp))
738 		return;
739 
740 	/*
741 	 * We only remove the DDT once all tables are empty and only
742 	 * prefetch dedup blocks when there are entries in the DDT.
743 	 * Thus no locking is required as the DDT can't disappear on us.
744 	 */
745 	ddt = ddt_select(spa, bp);
746 	ddt_key_fill(&dde.dde_key, bp);
747 
748 	for (enum ddt_type type = 0; type < DDT_TYPES; type++) {
749 		for (enum ddt_class class = 0; class < DDT_CLASSES; class++) {
750 			ddt_object_prefetch(ddt, type, class, &dde);
751 		}
752 	}
753 }
754 
755 /*
756  * Opaque struct used for ddt_key comparison
757  */
758 #define	DDT_KEY_CMP_LEN	(sizeof (ddt_key_t) / sizeof (uint16_t))
759 
760 typedef struct ddt_key_cmp {
761 	uint16_t	u16[DDT_KEY_CMP_LEN];
762 } ddt_key_cmp_t;
763 
764 int
765 ddt_entry_compare(const void *x1, const void *x2)
766 {
767 	const ddt_entry_t *dde1 = x1;
768 	const ddt_entry_t *dde2 = x2;
769 	const ddt_key_cmp_t *k1 = (const ddt_key_cmp_t *)&dde1->dde_key;
770 	const ddt_key_cmp_t *k2 = (const ddt_key_cmp_t *)&dde2->dde_key;
771 	int32_t cmp = 0;
772 
773 	for (int i = 0; i < DDT_KEY_CMP_LEN; i++) {
774 		cmp = (int32_t)k1->u16[i] - (int32_t)k2->u16[i];
775 		if (likely(cmp))
776 			break;
777 	}
778 
779 	return (TREE_ISIGN(cmp));
780 }
781 
782 static ddt_t *
783 ddt_table_alloc(spa_t *spa, enum zio_checksum c)
784 {
785 	ddt_t *ddt;
786 
787 	ddt = kmem_cache_alloc(ddt_cache, KM_SLEEP);
788 	bzero(ddt, sizeof (ddt_t));
789 
790 	mutex_init(&ddt->ddt_lock, NULL, MUTEX_DEFAULT, NULL);
791 	avl_create(&ddt->ddt_tree, ddt_entry_compare,
792 	    sizeof (ddt_entry_t), offsetof(ddt_entry_t, dde_node));
793 	avl_create(&ddt->ddt_repair_tree, ddt_entry_compare,
794 	    sizeof (ddt_entry_t), offsetof(ddt_entry_t, dde_node));
795 	ddt->ddt_checksum = c;
796 	ddt->ddt_spa = spa;
797 	ddt->ddt_os = spa->spa_meta_objset;
798 
799 	return (ddt);
800 }
801 
802 static void
803 ddt_table_free(ddt_t *ddt)
804 {
805 	ASSERT(avl_numnodes(&ddt->ddt_tree) == 0);
806 	ASSERT(avl_numnodes(&ddt->ddt_repair_tree) == 0);
807 	avl_destroy(&ddt->ddt_tree);
808 	avl_destroy(&ddt->ddt_repair_tree);
809 	mutex_destroy(&ddt->ddt_lock);
810 	kmem_cache_free(ddt_cache, ddt);
811 }
812 
813 void
814 ddt_create(spa_t *spa)
815 {
816 	spa->spa_dedup_checksum = ZIO_DEDUPCHECKSUM;
817 
818 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++)
819 		spa->spa_ddt[c] = ddt_table_alloc(spa, c);
820 }
821 
822 int
823 ddt_load(spa_t *spa)
824 {
825 	int error;
826 
827 	ddt_create(spa);
828 
829 	error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
830 	    DMU_POOL_DDT_STATS, sizeof (uint64_t), 1,
831 	    &spa->spa_ddt_stat_object);
832 
833 	if (error)
834 		return (error == ENOENT ? 0 : error);
835 
836 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
837 		ddt_t *ddt = spa->spa_ddt[c];
838 		for (enum ddt_type type = 0; type < DDT_TYPES; type++) {
839 			for (enum ddt_class class = 0; class < DDT_CLASSES;
840 			    class++) {
841 				error = ddt_object_load(ddt, type, class);
842 				if (error != 0 && error != ENOENT)
843 					return (error);
844 			}
845 		}
846 
847 		/*
848 		 * Seed the cached histograms.
849 		 */
850 		bcopy(ddt->ddt_histogram, &ddt->ddt_histogram_cache,
851 		    sizeof (ddt->ddt_histogram));
852 		spa->spa_dedup_dspace = ~0ULL;
853 	}
854 
855 	return (0);
856 }
857 
858 void
859 ddt_unload(spa_t *spa)
860 {
861 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
862 		if (spa->spa_ddt[c]) {
863 			ddt_table_free(spa->spa_ddt[c]);
864 			spa->spa_ddt[c] = NULL;
865 		}
866 	}
867 }
868 
869 boolean_t
870 ddt_class_contains(spa_t *spa, enum ddt_class max_class, const blkptr_t *bp)
871 {
872 	ddt_t *ddt;
873 	ddt_entry_t *dde;
874 
875 	if (!BP_GET_DEDUP(bp))
876 		return (B_FALSE);
877 
878 	if (max_class == DDT_CLASS_UNIQUE)
879 		return (B_TRUE);
880 
881 	ddt = spa->spa_ddt[BP_GET_CHECKSUM(bp)];
882 	dde = kmem_cache_alloc(ddt_entry_cache, KM_SLEEP);
883 
884 	ddt_key_fill(&(dde->dde_key), bp);
885 
886 	for (enum ddt_type type = 0; type < DDT_TYPES; type++) {
887 		for (enum ddt_class class = 0; class <= max_class; class++) {
888 			if (ddt_object_lookup(ddt, type, class, dde) == 0) {
889 				kmem_cache_free(ddt_entry_cache, dde);
890 				return (B_TRUE);
891 			}
892 		}
893 	}
894 
895 	kmem_cache_free(ddt_entry_cache, dde);
896 	return (B_FALSE);
897 }
898 
899 ddt_entry_t *
900 ddt_repair_start(ddt_t *ddt, const blkptr_t *bp)
901 {
902 	ddt_key_t ddk;
903 	ddt_entry_t *dde;
904 
905 	ddt_key_fill(&ddk, bp);
906 
907 	dde = ddt_alloc(&ddk);
908 
909 	for (enum ddt_type type = 0; type < DDT_TYPES; type++) {
910 		for (enum ddt_class class = 0; class < DDT_CLASSES; class++) {
911 			/*
912 			 * We can only do repair if there are multiple copies
913 			 * of the block.  For anything in the UNIQUE class,
914 			 * there's definitely only one copy, so don't even try.
915 			 */
916 			if (class != DDT_CLASS_UNIQUE &&
917 			    ddt_object_lookup(ddt, type, class, dde) == 0)
918 				return (dde);
919 		}
920 	}
921 
922 	bzero(dde->dde_phys, sizeof (dde->dde_phys));
923 
924 	return (dde);
925 }
926 
927 void
928 ddt_repair_done(ddt_t *ddt, ddt_entry_t *dde)
929 {
930 	avl_index_t where;
931 
932 	ddt_enter(ddt);
933 
934 	if (dde->dde_repair_abd != NULL && spa_writeable(ddt->ddt_spa) &&
935 	    avl_find(&ddt->ddt_repair_tree, dde, &where) == NULL)
936 		avl_insert(&ddt->ddt_repair_tree, dde, where);
937 	else
938 		ddt_free(dde);
939 
940 	ddt_exit(ddt);
941 }
942 
943 static void
944 ddt_repair_entry_done(zio_t *zio)
945 {
946 	ddt_entry_t *rdde = zio->io_private;
947 
948 	ddt_free(rdde);
949 }
950 
951 static void
952 ddt_repair_entry(ddt_t *ddt, ddt_entry_t *dde, ddt_entry_t *rdde, zio_t *rio)
953 {
954 	ddt_phys_t *ddp = dde->dde_phys;
955 	ddt_phys_t *rddp = rdde->dde_phys;
956 	ddt_key_t *ddk = &dde->dde_key;
957 	ddt_key_t *rddk = &rdde->dde_key;
958 	zio_t *zio;
959 	blkptr_t blk;
960 
961 	zio = zio_null(rio, rio->io_spa, NULL,
962 	    ddt_repair_entry_done, rdde, rio->io_flags);
963 
964 	for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++, rddp++) {
965 		if (ddp->ddp_phys_birth == 0 ||
966 		    ddp->ddp_phys_birth != rddp->ddp_phys_birth ||
967 		    bcmp(ddp->ddp_dva, rddp->ddp_dva, sizeof (ddp->ddp_dva)))
968 			continue;
969 		ddt_bp_create(ddt->ddt_checksum, ddk, ddp, &blk);
970 		zio_nowait(zio_rewrite(zio, zio->io_spa, 0, &blk,
971 		    rdde->dde_repair_abd, DDK_GET_PSIZE(rddk), NULL, NULL,
972 		    ZIO_PRIORITY_SYNC_WRITE, ZIO_DDT_CHILD_FLAGS(zio), NULL));
973 	}
974 
975 	zio_nowait(zio);
976 }
977 
978 static void
979 ddt_repair_table(ddt_t *ddt, zio_t *rio)
980 {
981 	spa_t *spa = ddt->ddt_spa;
982 	ddt_entry_t *dde, *rdde_next, *rdde;
983 	avl_tree_t *t = &ddt->ddt_repair_tree;
984 	blkptr_t blk;
985 
986 	if (spa_sync_pass(spa) > 1)
987 		return;
988 
989 	ddt_enter(ddt);
990 	for (rdde = avl_first(t); rdde != NULL; rdde = rdde_next) {
991 		rdde_next = AVL_NEXT(t, rdde);
992 		avl_remove(&ddt->ddt_repair_tree, rdde);
993 		ddt_exit(ddt);
994 		ddt_bp_create(ddt->ddt_checksum, &rdde->dde_key, NULL, &blk);
995 		dde = ddt_repair_start(ddt, &blk);
996 		ddt_repair_entry(ddt, dde, rdde, rio);
997 		ddt_repair_done(ddt, dde);
998 		ddt_enter(ddt);
999 	}
1000 	ddt_exit(ddt);
1001 }
1002 
1003 static void
1004 ddt_sync_entry(ddt_t *ddt, ddt_entry_t *dde, dmu_tx_t *tx, uint64_t txg)
1005 {
1006 	dsl_pool_t *dp = ddt->ddt_spa->spa_dsl_pool;
1007 	ddt_phys_t *ddp = dde->dde_phys;
1008 	ddt_key_t *ddk = &dde->dde_key;
1009 	enum ddt_type otype = dde->dde_type;
1010 	enum ddt_type ntype = DDT_TYPE_CURRENT;
1011 	enum ddt_class oclass = dde->dde_class;
1012 	enum ddt_class nclass;
1013 	uint64_t total_refcnt = 0;
1014 
1015 	ASSERT(dde->dde_loaded);
1016 	ASSERT(!dde->dde_loading);
1017 
1018 	for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
1019 		ASSERT(dde->dde_lead_zio[p] == NULL);
1020 		if (ddp->ddp_phys_birth == 0) {
1021 			ASSERT(ddp->ddp_refcnt == 0);
1022 			continue;
1023 		}
1024 		if (p == DDT_PHYS_DITTO) {
1025 			/*
1026 			 * Note, we no longer create DDT-DITTO blocks, but we
1027 			 * don't want to leak any written by older software.
1028 			 */
1029 			ddt_phys_free(ddt, ddk, ddp, txg);
1030 			continue;
1031 		}
1032 		if (ddp->ddp_refcnt == 0)
1033 			ddt_phys_free(ddt, ddk, ddp, txg);
1034 		total_refcnt += ddp->ddp_refcnt;
1035 	}
1036 
1037 	/* We do not create new DDT-DITTO blocks. */
1038 	ASSERT0(dde->dde_phys[DDT_PHYS_DITTO].ddp_phys_birth);
1039 	if (total_refcnt > 1)
1040 		nclass = DDT_CLASS_DUPLICATE;
1041 	else
1042 		nclass = DDT_CLASS_UNIQUE;
1043 
1044 	if (otype != DDT_TYPES &&
1045 	    (otype != ntype || oclass != nclass || total_refcnt == 0)) {
1046 		VERIFY(ddt_object_remove(ddt, otype, oclass, dde, tx) == 0);
1047 		ASSERT(ddt_object_lookup(ddt, otype, oclass, dde) == ENOENT);
1048 	}
1049 
1050 	if (total_refcnt != 0) {
1051 		dde->dde_type = ntype;
1052 		dde->dde_class = nclass;
1053 		ddt_stat_update(ddt, dde, 0);
1054 		if (!ddt_object_exists(ddt, ntype, nclass))
1055 			ddt_object_create(ddt, ntype, nclass, tx);
1056 		VERIFY(ddt_object_update(ddt, ntype, nclass, dde, tx) == 0);
1057 
1058 		/*
1059 		 * If the class changes, the order that we scan this bp
1060 		 * changes.  If it decreases, we could miss it, so
1061 		 * scan it right now.  (This covers both class changing
1062 		 * while we are doing ddt_walk(), and when we are
1063 		 * traversing.)
1064 		 */
1065 		if (nclass < oclass) {
1066 			dsl_scan_ddt_entry(dp->dp_scan,
1067 			    ddt->ddt_checksum, dde, tx);
1068 		}
1069 	}
1070 }
1071 
1072 static void
1073 ddt_sync_table(ddt_t *ddt, dmu_tx_t *tx, uint64_t txg)
1074 {
1075 	spa_t *spa = ddt->ddt_spa;
1076 	ddt_entry_t *dde;
1077 	void *cookie = NULL;
1078 
1079 	if (avl_numnodes(&ddt->ddt_tree) == 0)
1080 		return;
1081 
1082 	ASSERT(spa->spa_uberblock.ub_version >= SPA_VERSION_DEDUP);
1083 
1084 	if (spa->spa_ddt_stat_object == 0) {
1085 		spa->spa_ddt_stat_object = zap_create_link(ddt->ddt_os,
1086 		    DMU_OT_DDT_STATS, DMU_POOL_DIRECTORY_OBJECT,
1087 		    DMU_POOL_DDT_STATS, tx);
1088 	}
1089 
1090 	while ((dde = avl_destroy_nodes(&ddt->ddt_tree, &cookie)) != NULL) {
1091 		ddt_sync_entry(ddt, dde, tx, txg);
1092 		ddt_free(dde);
1093 	}
1094 
1095 	for (enum ddt_type type = 0; type < DDT_TYPES; type++) {
1096 		uint64_t add, count = 0;
1097 		for (enum ddt_class class = 0; class < DDT_CLASSES; class++) {
1098 			if (ddt_object_exists(ddt, type, class)) {
1099 				ddt_object_sync(ddt, type, class, tx);
1100 				VERIFY(ddt_object_count(ddt, type, class,
1101 				    &add) == 0);
1102 				count += add;
1103 			}
1104 		}
1105 		for (enum ddt_class class = 0; class < DDT_CLASSES; class++) {
1106 			if (count == 0 && ddt_object_exists(ddt, type, class))
1107 				ddt_object_destroy(ddt, type, class, tx);
1108 		}
1109 	}
1110 
1111 	bcopy(ddt->ddt_histogram, &ddt->ddt_histogram_cache,
1112 	    sizeof (ddt->ddt_histogram));
1113 	spa->spa_dedup_dspace = ~0ULL;
1114 }
1115 
1116 void
1117 ddt_sync(spa_t *spa, uint64_t txg)
1118 {
1119 	dsl_scan_t *scn = spa->spa_dsl_pool->dp_scan;
1120 	dmu_tx_t *tx;
1121 	zio_t *rio;
1122 
1123 	ASSERT(spa_syncing_txg(spa) == txg);
1124 
1125 	tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
1126 
1127 	rio = zio_root(spa, NULL, NULL,
1128 	    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE | ZIO_FLAG_SELF_HEAL);
1129 
1130 	/*
1131 	 * This function may cause an immediate scan of ddt blocks (see
1132 	 * the comment above dsl_scan_ddt() for details). We set the
1133 	 * scan's root zio here so that we can wait for any scan IOs in
1134 	 * addition to the regular ddt IOs.
1135 	 */
1136 	ASSERT3P(scn->scn_zio_root, ==, NULL);
1137 	scn->scn_zio_root = rio;
1138 
1139 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
1140 		ddt_t *ddt = spa->spa_ddt[c];
1141 		if (ddt == NULL)
1142 			continue;
1143 		ddt_sync_table(ddt, tx, txg);
1144 		ddt_repair_table(ddt, rio);
1145 	}
1146 
1147 	(void) zio_wait(rio);
1148 	scn->scn_zio_root = NULL;
1149 
1150 	dmu_tx_commit(tx);
1151 }
1152 
1153 int
1154 ddt_walk(spa_t *spa, ddt_bookmark_t *ddb, ddt_entry_t *dde)
1155 {
1156 	do {
1157 		do {
1158 			do {
1159 				ddt_t *ddt = spa->spa_ddt[ddb->ddb_checksum];
1160 				int error = ENOENT;
1161 				if (ddt_object_exists(ddt, ddb->ddb_type,
1162 				    ddb->ddb_class)) {
1163 					error = ddt_object_walk(ddt,
1164 					    ddb->ddb_type, ddb->ddb_class,
1165 					    &ddb->ddb_cursor, dde);
1166 				}
1167 				dde->dde_type = ddb->ddb_type;
1168 				dde->dde_class = ddb->ddb_class;
1169 				if (error == 0)
1170 					return (0);
1171 				if (error != ENOENT)
1172 					return (error);
1173 				ddb->ddb_cursor = 0;
1174 			} while (++ddb->ddb_checksum < ZIO_CHECKSUM_FUNCTIONS);
1175 			ddb->ddb_checksum = 0;
1176 		} while (++ddb->ddb_type < DDT_TYPES);
1177 		ddb->ddb_type = 0;
1178 	} while (++ddb->ddb_class < DDT_CLASSES);
1179 
1180 	return (SET_ERROR(ENOENT));
1181 }
1182 
1183 ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, prefetch, INT, ZMOD_RW,
1184 	"Enable prefetching dedup-ed blks");
1185