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