sbin/hammer: Cleanup blocks with a single statement
[dragonfly.git] / sbin / hammer / cmd_dedup.c
blob022f1b261f66610c540d07ccf3b66ab2704cf523
1 /*
2 * Copyright (c) 2010 The DragonFly Project. All rights reserved.
4 * This code is derived from software contributed to The DragonFly Project
5 * by Ilya Dryomov <idryomov@gmail.com>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in
15 * the documentation and/or other materials provided with the
16 * distribution.
17 * 3. Neither the name of The DragonFly Project nor the names of its
18 * contributors may be used to endorse or promote products derived
19 * from this software without specific, prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
35 #include <libutil.h>
36 #include <crypto/sha2/sha2.h>
38 #include "hammer.h"
40 #define DEDUP_BUF (64 * 1024)
42 /* Sorted list of block CRCs - light version for dedup-simulate */
43 struct sim_dedup_entry_rb_tree;
44 RB_HEAD(sim_dedup_entry_rb_tree, sim_dedup_entry) sim_dedup_tree =
45 RB_INITIALIZER(&sim_dedup_tree);
46 RB_PROTOTYPE2(sim_dedup_entry_rb_tree, sim_dedup_entry, rb_entry,
47 rb_sim_dedup_entry_compare, hammer_crc_t);
49 struct sim_dedup_entry {
50 hammer_crc_t crc;
51 uint64_t ref_blks; /* number of blocks referenced */
52 uint64_t ref_size; /* size of data referenced */
53 RB_ENTRY(sim_dedup_entry) rb_entry;
56 struct dedup_entry {
57 struct hammer_btree_leaf_elm leaf;
58 union {
59 struct {
60 uint64_t ref_blks;
61 uint64_t ref_size;
62 } de;
63 RB_HEAD(sha_dedup_entry_rb_tree, sha_dedup_entry) fict_root;
64 } u;
65 uint8_t flags;
66 RB_ENTRY(dedup_entry) rb_entry;
69 #define HAMMER_DEDUP_ENTRY_FICTITIOUS 0x0001
71 struct sha_dedup_entry {
72 struct hammer_btree_leaf_elm leaf;
73 uint64_t ref_blks;
74 uint64_t ref_size;
75 uint8_t sha_hash[SHA256_DIGEST_LENGTH];
76 RB_ENTRY(sha_dedup_entry) fict_entry;
79 /* Sorted list of HAMMER B-Tree keys */
80 struct dedup_entry_rb_tree;
81 struct sha_dedup_entry_rb_tree;
83 RB_HEAD(dedup_entry_rb_tree, dedup_entry) dedup_tree =
84 RB_INITIALIZER(&dedup_tree);
85 RB_PROTOTYPE2(dedup_entry_rb_tree, dedup_entry, rb_entry,
86 rb_dedup_entry_compare, hammer_crc_t);
88 RB_PROTOTYPE(sha_dedup_entry_rb_tree, sha_dedup_entry, fict_entry,
89 rb_sha_dedup_entry_compare);
92 * Pass2 list - contains entries that were not dedup'ed because ioctl failed
94 STAILQ_HEAD(, pass2_dedup_entry) pass2_dedup_queue =
95 STAILQ_HEAD_INITIALIZER(pass2_dedup_queue);
97 struct pass2_dedup_entry {
98 struct hammer_btree_leaf_elm leaf;
99 STAILQ_ENTRY(pass2_dedup_entry) sq_entry;
102 #define DEDUP_PASS2 0x0001 /* process_btree_elm() mode */
104 static int SigInfoFlag;
105 static int SigAlrmFlag;
106 static int64_t DedupDataReads;
107 static int64_t DedupCurrentRecords;
108 static int64_t DedupTotalRecords;
109 static uint32_t DedupCrcStart;
110 static uint32_t DedupCrcEnd;
111 static uint64_t MemoryUse;
113 /* PFS global ids - we deal with just one PFS at a run */
114 static int glob_fd;
115 static struct hammer_ioc_pseudofs_rw glob_pfs;
118 * Global accounting variables
120 * Last three don't have to be 64-bit, just to be safe..
122 static uint64_t dedup_alloc_size;
123 static uint64_t dedup_ref_size;
124 static uint64_t dedup_skipped_size;
125 static uint64_t dedup_crc_failures;
126 static uint64_t dedup_sha_failures;
127 static uint64_t dedup_underflows;
128 static uint64_t dedup_successes_count;
129 static uint64_t dedup_successes_bytes;
131 static int rb_sim_dedup_entry_compare(struct sim_dedup_entry *sim_de1,
132 struct sim_dedup_entry *sim_de2);
133 static int rb_dedup_entry_compare(struct dedup_entry *de1,
134 struct dedup_entry *de2);
135 static int rb_sha_dedup_entry_compare(struct sha_dedup_entry *sha_de1,
136 struct sha_dedup_entry *sha_de2);
137 typedef int (*scan_pfs_cb_t)(hammer_btree_leaf_elm_t scan_leaf, int flags);
138 static void scan_pfs(char *filesystem, scan_pfs_cb_t func, const char *id);
139 static int collect_btree_elm(hammer_btree_leaf_elm_t scan_leaf, int flags);
140 static int count_btree_elm(hammer_btree_leaf_elm_t scan_leaf, int flags);
141 static int process_btree_elm(hammer_btree_leaf_elm_t scan_leaf, int flags);
142 static int upgrade_chksum(hammer_btree_leaf_elm_t leaf, uint8_t *sha_hash);
143 static void dump_simulated_dedup(void);
144 static void dump_real_dedup(void);
145 static void dedup_usage(int code);
147 RB_GENERATE2(sim_dedup_entry_rb_tree, sim_dedup_entry, rb_entry,
148 rb_sim_dedup_entry_compare, hammer_crc_t, crc);
149 RB_GENERATE2(dedup_entry_rb_tree, dedup_entry, rb_entry,
150 rb_dedup_entry_compare, hammer_crc_t, leaf.data_crc);
151 RB_GENERATE(sha_dedup_entry_rb_tree, sha_dedup_entry, fict_entry,
152 rb_sha_dedup_entry_compare);
154 static int
155 rb_sim_dedup_entry_compare(struct sim_dedup_entry *sim_de1,
156 struct sim_dedup_entry *sim_de2)
158 if (sim_de1->crc < sim_de2->crc)
159 return (-1);
160 if (sim_de1->crc > sim_de2->crc)
161 return (1);
163 return (0);
166 static int
167 rb_dedup_entry_compare(struct dedup_entry *de1, struct dedup_entry *de2)
169 if (de1->leaf.data_crc < de2->leaf.data_crc)
170 return (-1);
171 if (de1->leaf.data_crc > de2->leaf.data_crc)
172 return (1);
174 return (0);
177 static int
178 rb_sha_dedup_entry_compare(struct sha_dedup_entry *sha_de1,
179 struct sha_dedup_entry *sha_de2)
181 unsigned long *h1 = (unsigned long *)&sha_de1->sha_hash;
182 unsigned long *h2 = (unsigned long *)&sha_de2->sha_hash;
183 int i;
185 for (i = 0; i < SHA256_DIGEST_LENGTH / (int)sizeof(unsigned long); ++i) {
186 if (h1[i] < h2[i])
187 return (-1);
188 if (h1[i] > h2[i])
189 return (1);
192 return (0);
196 * dedup-simulate <filesystem>
198 void
199 hammer_cmd_dedup_simulate(char **av, int ac)
201 struct sim_dedup_entry *sim_de;
203 if (ac != 1)
204 dedup_usage(1);
206 glob_fd = getpfs(&glob_pfs, av[0]);
209 * Collection passes (memory limited)
211 printf("Dedup-simulate running\n");
212 do {
213 DedupCrcStart = DedupCrcEnd;
214 DedupCrcEnd = 0;
215 MemoryUse = 0;
217 if (VerboseOpt) {
218 printf("B-Tree pass crc-range %08x-max\n",
219 DedupCrcStart);
220 fflush(stdout);
222 scan_pfs(av[0], collect_btree_elm, "simu-pass");
224 if (VerboseOpt >= 2)
225 dump_simulated_dedup();
228 * Calculate simulated dedup ratio and get rid of the tree
230 while ((sim_de = RB_ROOT(&sim_dedup_tree)) != NULL) {
231 assert(sim_de->ref_blks != 0);
232 dedup_ref_size += sim_de->ref_size;
233 dedup_alloc_size += sim_de->ref_size / sim_de->ref_blks;
235 RB_REMOVE(sim_dedup_entry_rb_tree, &sim_dedup_tree, sim_de);
236 free(sim_de);
238 if (DedupCrcEnd && VerboseOpt == 0)
239 printf(".");
240 } while (DedupCrcEnd);
242 printf("Dedup-simulate %s succeeded\n", av[0]);
243 relpfs(glob_fd, &glob_pfs);
245 printf("Simulated dedup ratio = %.2f\n",
246 (dedup_alloc_size != 0) ?
247 (double)dedup_ref_size / dedup_alloc_size : 0);
251 * dedup <filesystem>
253 void
254 hammer_cmd_dedup(char **av, int ac)
256 struct dedup_entry *de;
257 struct sha_dedup_entry *sha_de;
258 struct pass2_dedup_entry *pass2_de;
259 char *tmp;
260 char buf[8];
261 int needfree = 0;
263 if (TimeoutOpt > 0)
264 alarm(TimeoutOpt);
266 if (ac != 1)
267 dedup_usage(1);
269 STAILQ_INIT(&pass2_dedup_queue);
271 glob_fd = getpfs(&glob_pfs, av[0]);
274 * A cycle file is _required_ for resuming dedup after the timeout
275 * specified with -t has expired. If no -c option, then place a
276 * .dedup.cycle file either in the PFS snapshots directory or in
277 * the default snapshots directory.
279 if (!CyclePath) {
280 if (glob_pfs.ondisk->snapshots[0] != '/')
281 asprintf(&tmp, "%s/%s/.dedup.cycle",
282 SNAPSHOTS_BASE, av[0]);
283 else
284 asprintf(&tmp, "%s/.dedup.cycle",
285 glob_pfs.ondisk->snapshots);
286 CyclePath = tmp;
287 needfree = 1;
291 * Pre-pass to cache the btree
293 scan_pfs(av[0], count_btree_elm, "pre-pass ");
294 DedupTotalRecords = DedupCurrentRecords;
297 * Collection passes (memory limited)
299 printf("Dedup running\n");
300 do {
301 DedupCrcStart = DedupCrcEnd;
302 DedupCrcEnd = 0;
303 MemoryUse = 0;
305 if (VerboseOpt) {
306 printf("B-Tree pass crc-range %08x-max\n",
307 DedupCrcStart);
308 fflush(stdout);
310 scan_pfs(av[0], process_btree_elm, "main-pass");
312 while ((pass2_de = STAILQ_FIRST(&pass2_dedup_queue)) != NULL) {
313 if (process_btree_elm(&pass2_de->leaf, DEDUP_PASS2))
314 dedup_skipped_size -= pass2_de->leaf.data_len;
316 STAILQ_REMOVE_HEAD(&pass2_dedup_queue, sq_entry);
317 free(pass2_de);
319 assert(STAILQ_EMPTY(&pass2_dedup_queue));
321 if (VerboseOpt >= 2)
322 dump_real_dedup();
325 * Calculate dedup ratio and get rid of the trees
327 while ((de = RB_ROOT(&dedup_tree)) != NULL) {
328 if (de->flags & HAMMER_DEDUP_ENTRY_FICTITIOUS) {
329 while ((sha_de = RB_ROOT(&de->u.fict_root)) != NULL) {
330 assert(sha_de->ref_blks != 0);
331 dedup_ref_size += sha_de->ref_size;
332 dedup_alloc_size += sha_de->ref_size / sha_de->ref_blks;
334 RB_REMOVE(sha_dedup_entry_rb_tree,
335 &de->u.fict_root, sha_de);
336 free(sha_de);
338 assert(RB_EMPTY(&de->u.fict_root));
339 } else {
340 assert(de->u.de.ref_blks != 0);
341 dedup_ref_size += de->u.de.ref_size;
342 dedup_alloc_size += de->u.de.ref_size / de->u.de.ref_blks;
345 RB_REMOVE(dedup_entry_rb_tree, &dedup_tree, de);
346 free(de);
348 assert(RB_EMPTY(&dedup_tree));
349 if (DedupCrcEnd && VerboseOpt == 0)
350 printf(".");
351 } while (DedupCrcEnd);
353 printf("Dedup %s succeeded\n", av[0]);
354 relpfs(glob_fd, &glob_pfs);
356 humanize_unsigned(buf, sizeof(buf), dedup_ref_size, "B", 1024);
357 printf("Dedup ratio = %.2f (in this run)\n"
358 " %8s referenced\n",
359 ((dedup_alloc_size != 0) ?
360 (double)dedup_ref_size / dedup_alloc_size : 0),
363 humanize_unsigned(buf, sizeof(buf), dedup_alloc_size, "B", 1024);
364 printf(" %8s allocated\n", buf);
365 humanize_unsigned(buf, sizeof(buf), dedup_skipped_size, "B", 1024);
366 printf(" %8s skipped\n", buf);
367 printf(" %8jd CRC collisions\n"
368 " %8jd SHA collisions\n"
369 " %8jd big-block underflows\n"
370 " %8jd new dedup records\n"
371 " %8jd new dedup bytes\n",
372 (intmax_t)dedup_crc_failures,
373 (intmax_t)dedup_sha_failures,
374 (intmax_t)dedup_underflows,
375 (intmax_t)dedup_successes_count,
376 (intmax_t)dedup_successes_bytes
379 /* Once completed remove cycle file */
380 hammer_reset_cycle();
382 /* We don't want to mess up with other directives */
383 if (needfree) {
384 free(tmp);
385 CyclePath = NULL;
389 static int
390 count_btree_elm(hammer_btree_leaf_elm_t scan_leaf __unused, int flags __unused)
392 return(1);
395 static int
396 collect_btree_elm(hammer_btree_leaf_elm_t scan_leaf, int flags __unused)
398 struct sim_dedup_entry *sim_de;
401 * If we are using too much memory we have to clean some out, which
402 * will cause the run to use multiple passes. Be careful of integer
403 * overflows!
405 if (MemoryUse > MemoryLimit) {
406 DedupCrcEnd = DedupCrcStart +
407 (uint32_t)(DedupCrcEnd - DedupCrcStart - 1) / 2;
408 if (VerboseOpt) {
409 printf("memory limit crc-range %08x-%08x\n",
410 DedupCrcStart, DedupCrcEnd);
411 fflush(stdout);
413 for (;;) {
414 sim_de = RB_MAX(sim_dedup_entry_rb_tree,
415 &sim_dedup_tree);
416 if (sim_de == NULL || sim_de->crc < DedupCrcEnd)
417 break;
418 RB_REMOVE(sim_dedup_entry_rb_tree,
419 &sim_dedup_tree, sim_de);
420 MemoryUse -= sizeof(*sim_de);
421 free(sim_de);
426 * Collect statistics based on the CRC only, do not try to read
427 * any data blocks or run SHA hashes.
429 sim_de = RB_LOOKUP(sim_dedup_entry_rb_tree, &sim_dedup_tree,
430 scan_leaf->data_crc);
432 if (sim_de == NULL) {
433 sim_de = calloc(1, sizeof(*sim_de));
434 sim_de->crc = scan_leaf->data_crc;
435 RB_INSERT(sim_dedup_entry_rb_tree, &sim_dedup_tree, sim_de);
436 MemoryUse += sizeof(*sim_de);
439 sim_de->ref_blks += 1;
440 sim_de->ref_size += scan_leaf->data_len;
441 return (1);
444 static __inline int
445 validate_dedup_pair(hammer_btree_leaf_elm_t p, hammer_btree_leaf_elm_t q)
447 if (HAMMER_ZONE(p->data_offset) != HAMMER_ZONE(q->data_offset))
448 return (1);
449 if (p->data_len != q->data_len)
450 return (1);
452 return (0);
455 #define DEDUP_TECH_FAILURE 1
456 #define DEDUP_CMP_FAILURE 2
457 #define DEDUP_INVALID_ZONE 3
458 #define DEDUP_UNDERFLOW 4
459 #define DEDUP_VERS_FAILURE 5
461 static __inline int
462 deduplicate(hammer_btree_leaf_elm_t p, hammer_btree_leaf_elm_t q)
464 struct hammer_ioc_dedup dedup;
466 bzero(&dedup, sizeof(dedup));
469 * If data_offset fields are the same there is no need to run ioctl,
470 * candidate is already dedup'ed.
472 if (p->data_offset == q->data_offset)
473 return (0);
475 dedup.elm1 = p->base;
476 dedup.elm2 = q->base;
477 RunningIoctl = 1;
478 if (ioctl(glob_fd, HAMMERIOC_DEDUP, &dedup) < 0) {
479 if (errno == EOPNOTSUPP)
480 return (DEDUP_VERS_FAILURE); /* must be at least version 5 */
481 /* Technical failure - locking or w/e */
482 return (DEDUP_TECH_FAILURE);
484 if (dedup.head.flags & HAMMER_IOC_DEDUP_CMP_FAILURE)
485 return (DEDUP_CMP_FAILURE);
486 if (dedup.head.flags & HAMMER_IOC_DEDUP_INVALID_ZONE)
487 return (DEDUP_INVALID_ZONE);
488 if (dedup.head.flags & HAMMER_IOC_DEDUP_UNDERFLOW)
489 return (DEDUP_UNDERFLOW);
490 RunningIoctl = 0;
491 ++dedup_successes_count;
492 dedup_successes_bytes += p->data_len;
493 return (0);
496 static int
497 process_btree_elm(hammer_btree_leaf_elm_t scan_leaf, int flags)
499 struct dedup_entry *de;
500 struct sha_dedup_entry *sha_de, temp;
501 struct pass2_dedup_entry *pass2_de;
502 int error;
505 * If we are using too much memory we have to clean some out, which
506 * will cause the run to use multiple passes. Be careful of integer
507 * overflows!
509 while (MemoryUse > MemoryLimit) {
510 DedupCrcEnd = DedupCrcStart +
511 (uint32_t)(DedupCrcEnd - DedupCrcStart - 1) / 2;
512 if (VerboseOpt) {
513 printf("memory limit crc-range %08x-%08x\n",
514 DedupCrcStart, DedupCrcEnd);
515 fflush(stdout);
518 for (;;) {
519 de = RB_MAX(dedup_entry_rb_tree, &dedup_tree);
520 if (de == NULL || de->leaf.data_crc < DedupCrcEnd)
521 break;
522 if (de->flags & HAMMER_DEDUP_ENTRY_FICTITIOUS)
523 while ((sha_de = RB_ROOT(&de->u.fict_root)) !=
524 NULL) {
525 RB_REMOVE(sha_dedup_entry_rb_tree,
526 &de->u.fict_root, sha_de);
527 MemoryUse -= sizeof(*sha_de);
528 free(sha_de);
530 RB_REMOVE(dedup_entry_rb_tree, &dedup_tree, de);
531 MemoryUse -= sizeof(*de);
532 free(de);
537 * Collect statistics based on the CRC. Colliding CRCs usually
538 * cause a SHA sub-tree to be created under the de.
540 * Trivial case if de not found.
542 de = RB_LOOKUP(dedup_entry_rb_tree, &dedup_tree, scan_leaf->data_crc);
543 if (de == NULL) {
544 de = calloc(1, sizeof(*de));
545 de->leaf = *scan_leaf;
546 RB_INSERT(dedup_entry_rb_tree, &dedup_tree, de);
547 MemoryUse += sizeof(*de);
548 goto upgrade_stats;
552 * Found entry in CRC tree
554 if (de->flags & HAMMER_DEDUP_ENTRY_FICTITIOUS) {
556 * Optimize the case where a CRC failure results in multiple
557 * SHA entries. If we unconditionally issue a data-read a
558 * degenerate situation where a colliding CRC's second SHA
559 * entry contains the lion's share of the deduplication
560 * candidates will result in excessive data block reads.
562 * Deal with the degenerate case by looking for a matching
563 * data_offset/data_len in the SHA elements we already have
564 * before reading the data block and generating a new SHA.
566 RB_FOREACH(sha_de, sha_dedup_entry_rb_tree, &de->u.fict_root)
567 if (sha_de->leaf.data_offset ==
568 scan_leaf->data_offset &&
569 sha_de->leaf.data_len == scan_leaf->data_len) {
570 memcpy(temp.sha_hash, sha_de->sha_hash,
571 SHA256_DIGEST_LENGTH);
572 break;
576 * Entry in CRC tree is fictitious, so we already had problems
577 * with this CRC. Upgrade (compute SHA) the candidate and
578 * dive into SHA subtree. If upgrade fails insert the candidate
579 * into Pass2 list (it will be processed later).
581 if (sha_de == NULL) {
582 if (upgrade_chksum(scan_leaf, temp.sha_hash))
583 goto pass2_insert;
585 sha_de = RB_FIND(sha_dedup_entry_rb_tree,
586 &de->u.fict_root, &temp);
590 * Nothing in SHA subtree so far, so this is a new
591 * 'dataset'. Insert new entry into SHA subtree.
593 if (sha_de == NULL) {
594 sha_de = calloc(1, sizeof(*sha_de));
595 sha_de->leaf = *scan_leaf;
596 memcpy(sha_de->sha_hash, temp.sha_hash,
597 SHA256_DIGEST_LENGTH);
598 RB_INSERT(sha_dedup_entry_rb_tree, &de->u.fict_root,
599 sha_de);
600 MemoryUse += sizeof(*sha_de);
601 goto upgrade_stats_sha;
605 * Found entry in SHA subtree, it means we have a potential
606 * dedup pair. Validate it (zones have to match and data_len
607 * field have to be the same too. If validation fails, treat
608 * it as a SHA collision (jump to sha256_failure).
610 if (validate_dedup_pair(&sha_de->leaf, scan_leaf))
611 goto sha256_failure;
614 * We have a valid dedup pair (SHA match, validated).
616 * In case of technical failure (dedup pair was good, but
617 * ioctl failed anyways) insert the candidate into Pass2 list
618 * (we will try to dedup it after we are done with the rest of
619 * the tree).
621 * If ioctl fails because either of blocks is in the non-dedup
622 * zone (we can dedup only in LARGE_DATA and SMALL_DATA) don't
623 * bother with the candidate and terminate early.
625 * If ioctl fails because of big-block underflow replace the
626 * leaf node that found dedup entry represents with scan_leaf.
628 error = deduplicate(&sha_de->leaf, scan_leaf);
629 switch(error) {
630 case 0:
631 goto upgrade_stats_sha;
632 case DEDUP_TECH_FAILURE:
633 goto pass2_insert;
634 case DEDUP_CMP_FAILURE:
635 goto sha256_failure;
636 case DEDUP_INVALID_ZONE:
637 goto terminate_early;
638 case DEDUP_UNDERFLOW:
639 ++dedup_underflows;
640 sha_de->leaf = *scan_leaf;
641 memcpy(sha_de->sha_hash, temp.sha_hash,
642 SHA256_DIGEST_LENGTH);
643 goto upgrade_stats_sha;
644 case DEDUP_VERS_FAILURE:
645 errx(1, "HAMMER filesystem must be at least "
646 "version 5 to dedup");
647 default:
648 fprintf(stderr, "Unknown error\n");
649 goto terminate_early;
653 * Ooh la la.. SHA-256 collision. Terminate early, there's
654 * nothing we can do here.
656 sha256_failure:
657 ++dedup_sha_failures;
658 goto terminate_early;
659 } else {
661 * Candidate CRC is good for now (we found an entry in CRC
662 * tree and it's not fictitious). This means we have a
663 * potential dedup pair.
665 if (validate_dedup_pair(&de->leaf, scan_leaf))
666 goto crc_failure;
669 * We have a valid dedup pair (CRC match, validated)
671 error = deduplicate(&de->leaf, scan_leaf);
672 switch(error) {
673 case 0:
674 goto upgrade_stats;
675 case DEDUP_TECH_FAILURE:
676 goto pass2_insert;
677 case DEDUP_CMP_FAILURE:
678 goto crc_failure;
679 case DEDUP_INVALID_ZONE:
680 goto terminate_early;
681 case DEDUP_UNDERFLOW:
682 ++dedup_underflows;
683 de->leaf = *scan_leaf;
684 goto upgrade_stats;
685 case DEDUP_VERS_FAILURE:
686 errx(1, "HAMMER filesystem must be at least "
687 "version 5 to dedup");
688 default:
689 fprintf(stderr, "Unknown error\n");
690 goto terminate_early;
693 crc_failure:
695 * We got a CRC collision - either ioctl failed because of
696 * the comparison failure or validation of the potential
697 * dedup pair went bad. In all cases insert both blocks
698 * into SHA subtree (this requires checksum upgrade) and mark
699 * entry that corresponds to this CRC in the CRC tree
700 * fictitious, so that all futher operations with this CRC go
701 * through SHA subtree.
703 ++dedup_crc_failures;
706 * Insert block that was represented by now fictitious dedup
707 * entry (create a new SHA entry and preserve stats of the
708 * old CRC one). If checksum upgrade fails insert the
709 * candidate into Pass2 list and return - keep both trees
710 * unmodified.
712 sha_de = calloc(1, sizeof(*sha_de));
713 sha_de->leaf = de->leaf;
714 sha_de->ref_blks = de->u.de.ref_blks;
715 sha_de->ref_size = de->u.de.ref_size;
716 if (upgrade_chksum(&sha_de->leaf, sha_de->sha_hash)) {
717 free(sha_de);
718 goto pass2_insert;
720 MemoryUse += sizeof(*sha_de);
722 RB_INIT(&de->u.fict_root);
724 * Here we can insert without prior checking because the tree
725 * is empty at this point
727 RB_INSERT(sha_dedup_entry_rb_tree, &de->u.fict_root, sha_de);
730 * Mark entry in CRC tree fictitious
732 de->flags |= HAMMER_DEDUP_ENTRY_FICTITIOUS;
735 * Upgrade checksum of the candidate and insert it into
736 * SHA subtree. If upgrade fails insert the candidate into
737 * Pass2 list.
739 if (upgrade_chksum(scan_leaf, temp.sha_hash))
740 goto pass2_insert;
741 sha_de = RB_FIND(sha_dedup_entry_rb_tree, &de->u.fict_root,
742 &temp);
743 if (sha_de != NULL)
744 /* There is an entry with this SHA already, but the only
745 * RB-tree element at this point is that entry we just
746 * added. We know for sure these blocks are different
747 * (this is crc_failure branch) so treat it as SHA
748 * collision.
750 goto sha256_failure;
752 sha_de = calloc(1, sizeof(*sha_de));
753 sha_de->leaf = *scan_leaf;
754 memcpy(sha_de->sha_hash, temp.sha_hash, SHA256_DIGEST_LENGTH);
755 RB_INSERT(sha_dedup_entry_rb_tree, &de->u.fict_root, sha_de);
756 MemoryUse += sizeof(*sha_de);
757 goto upgrade_stats_sha;
760 upgrade_stats:
761 de->u.de.ref_blks += 1;
762 de->u.de.ref_size += scan_leaf->data_len;
763 return (1);
765 upgrade_stats_sha:
766 sha_de->ref_blks += 1;
767 sha_de->ref_size += scan_leaf->data_len;
768 return (1);
770 pass2_insert:
772 * If in pass2 mode don't insert anything, fall through to
773 * terminate_early
775 if ((flags & DEDUP_PASS2) == 0) {
776 pass2_de = calloc(1, sizeof(*pass2_de));
777 pass2_de->leaf = *scan_leaf;
778 STAILQ_INSERT_TAIL(&pass2_dedup_queue, pass2_de, sq_entry);
779 dedup_skipped_size += scan_leaf->data_len;
780 return (1);
783 terminate_early:
785 * Early termination path. Fixup stats.
787 dedup_alloc_size += scan_leaf->data_len;
788 dedup_ref_size += scan_leaf->data_len;
789 return (0);
792 static int
793 upgrade_chksum(hammer_btree_leaf_elm_t leaf, uint8_t *sha_hash)
795 struct hammer_ioc_data data;
796 char *buf = malloc(DEDUP_BUF);
797 SHA256_CTX ctx;
798 int error;
800 bzero(&data, sizeof(data));
801 data.elm = leaf->base;
802 data.ubuf = buf;
803 data.size = DEDUP_BUF;
805 error = 0;
806 if (ioctl(glob_fd, HAMMERIOC_GET_DATA, &data) < 0) {
807 fprintf(stderr, "Get-data failed: %s\n", strerror(errno));
808 error = 1;
809 goto done;
811 DedupDataReads += leaf->data_len;
813 if (data.leaf.data_len != leaf->data_len) {
814 error = 1;
815 goto done;
818 if (data.leaf.base.btype == HAMMER_BTREE_TYPE_RECORD &&
819 data.leaf.base.rec_type == HAMMER_RECTYPE_DATA) {
820 SHA256_Init(&ctx);
821 SHA256_Update(&ctx, (void *)buf, data.leaf.data_len);
822 SHA256_Final(sha_hash, &ctx);
825 done:
826 free(buf);
827 return (error);
830 static void
831 sigAlrm(int signo __unused)
833 SigAlrmFlag = 1;
836 static void
837 sigInfo(int signo __unused)
839 SigInfoFlag = 1;
842 static void
843 scan_pfs(char *filesystem, scan_pfs_cb_t func, const char *id)
845 struct hammer_ioc_mirror_rw mirror;
846 hammer_ioc_mrecord_any_t mrec;
847 struct hammer_btree_leaf_elm elm;
848 char *buf = malloc(DEDUP_BUF);
849 char buf1[8];
850 char buf2[8];
851 int offset, bytes;
853 SigInfoFlag = 0;
854 DedupDataReads = 0;
855 DedupCurrentRecords = 0;
856 signal(SIGINFO, sigInfo);
857 signal(SIGALRM, sigAlrm);
860 * Deduplication happens per element so hammer(8) is in full
861 * control of the ioctl()s to actually perform it. SIGALRM
862 * needs to be handled within hammer(8) but a checkpoint
863 * is needed for resuming. Use cycle file for that.
865 * Try to obtain the previous obj_id from the cycle file and
866 * if not available just start from the beginning.
868 bzero(&mirror, sizeof(mirror));
869 hammer_key_beg_init(&mirror.key_beg);
870 hammer_get_cycle(&mirror.key_beg, &mirror.tid_beg);
872 if (mirror.key_beg.obj_id != (int64_t)HAMMER_MIN_OBJID)
873 if (VerboseOpt)
874 fprintf(stderr, "%s: mirror-read: Resuming at object %016jx\n",
875 id, (uintmax_t)mirror.key_beg.obj_id);
877 hammer_key_end_init(&mirror.key_end);
879 mirror.tid_beg = glob_pfs.ondisk->sync_beg_tid;
880 mirror.tid_end = glob_pfs.ondisk->sync_end_tid;
881 mirror.head.flags |= HAMMER_IOC_MIRROR_NODATA; /* we want only keys */
882 mirror.ubuf = buf;
883 mirror.size = DEDUP_BUF;
884 mirror.pfs_id = glob_pfs.pfs_id;
885 mirror.shared_uuid = glob_pfs.ondisk->shared_uuid;
887 if (VerboseOpt && DedupCrcStart == 0) {
888 printf("%s %s: objspace %016jx:%04x %016jx:%04x\n",
889 id, filesystem,
890 (uintmax_t)mirror.key_beg.obj_id,
891 mirror.key_beg.localization,
892 (uintmax_t)mirror.key_end.obj_id,
893 mirror.key_end.localization);
894 printf("%s %s: pfs_id %d\n",
895 id, filesystem, glob_pfs.pfs_id);
897 fflush(stdout);
898 fflush(stderr);
900 do {
901 mirror.count = 0;
902 mirror.pfs_id = glob_pfs.pfs_id;
903 mirror.shared_uuid = glob_pfs.ondisk->shared_uuid;
904 if (ioctl(glob_fd, HAMMERIOC_MIRROR_READ, &mirror) < 0)
905 err(1, "Mirror-read %s failed", filesystem);
906 if (mirror.head.flags & HAMMER_IOC_HEAD_ERROR)
907 errx(1, "Mirror-read %s fatal error %d",
908 filesystem, mirror.head.error);
909 if (mirror.count) {
910 offset = 0;
911 while (offset < mirror.count) {
912 mrec = (void *)((char *)buf + offset);
913 bytes = HAMMER_HEAD_DOALIGN(mrec->head.rec_size);
914 if (offset + bytes > mirror.count)
915 errx(1, "Misaligned record");
916 assert((mrec->head.type &
917 HAMMER_MRECF_TYPE_MASK) ==
918 HAMMER_MREC_TYPE_REC);
919 offset += bytes;
920 elm = mrec->rec.leaf;
921 if (elm.base.btype != HAMMER_BTREE_TYPE_RECORD)
922 continue;
923 if (elm.base.rec_type != HAMMER_RECTYPE_DATA)
924 continue;
925 ++DedupCurrentRecords;
926 if (DedupCrcStart != DedupCrcEnd) {
927 if (elm.data_crc < DedupCrcStart)
928 continue;
929 if (DedupCrcEnd &&
930 elm.data_crc >= DedupCrcEnd)
931 continue;
933 func(&elm, 0);
936 mirror.key_beg = mirror.key_cur;
937 if (DidInterrupt || SigAlrmFlag) {
938 if (VerboseOpt)
939 fprintf(stderr, "%s\n",
940 (DidInterrupt ? "Interrupted" : "Timeout"));
941 hammer_set_cycle(&mirror.key_cur, mirror.tid_beg);
942 if (VerboseOpt)
943 fprintf(stderr, "Cyclefile %s updated for "
944 "continuation\n", CyclePath);
945 exit(1);
947 if (SigInfoFlag) {
948 if (DedupTotalRecords) {
949 humanize_unsigned(buf1, sizeof(buf1),
950 DedupDataReads,
951 "B", 1024);
952 humanize_unsigned(buf2, sizeof(buf2),
953 dedup_successes_bytes,
954 "B", 1024);
955 fprintf(stderr, "%s count %7jd/%jd "
956 "(%02d.%02d%%) "
957 "ioread %s newddup %s\n",
959 (intmax_t)DedupCurrentRecords,
960 (intmax_t)DedupTotalRecords,
961 (int)(DedupCurrentRecords * 100 /
962 DedupTotalRecords),
963 (int)(DedupCurrentRecords * 10000 /
964 DedupTotalRecords % 100),
965 buf1, buf2);
966 } else {
967 fprintf(stderr, "%s count %-7jd\n",
969 (intmax_t)DedupCurrentRecords);
971 SigInfoFlag = 0;
973 } while (mirror.count != 0);
975 signal(SIGINFO, SIG_IGN);
976 signal(SIGALRM, SIG_IGN);
978 free(buf);
981 static void
982 dump_simulated_dedup(void)
984 struct sim_dedup_entry *sim_de;
986 printf("=== Dumping simulated dedup entries:\n");
987 RB_FOREACH(sim_de, sim_dedup_entry_rb_tree, &sim_dedup_tree)
988 printf("\tcrc=%08x cnt=%ju size=%ju\n",
989 sim_de->crc,
990 (intmax_t)sim_de->ref_blks,
991 (intmax_t)sim_de->ref_size);
992 printf("end of dump ===\n");
995 static void
996 dump_real_dedup(void)
998 struct dedup_entry *de;
999 struct sha_dedup_entry *sha_de;
1000 int i;
1002 printf("=== Dumping dedup entries:\n");
1003 RB_FOREACH(de, dedup_entry_rb_tree, &dedup_tree) {
1004 if (de->flags & HAMMER_DEDUP_ENTRY_FICTITIOUS) {
1005 printf("\tcrc=%08x fictitious\n", de->leaf.data_crc);
1007 RB_FOREACH(sha_de, sha_dedup_entry_rb_tree, &de->u.fict_root) {
1008 printf("\t\tcrc=%08x cnt=%ju size=%ju\n\t"
1009 "\t\tsha=",
1010 sha_de->leaf.data_crc,
1011 (intmax_t)sha_de->ref_blks,
1012 (intmax_t)sha_de->ref_size);
1013 for (i = 0; i < SHA256_DIGEST_LENGTH; ++i)
1014 printf("%02x", sha_de->sha_hash[i]);
1015 printf("\n");
1017 } else {
1018 printf("\tcrc=%08x cnt=%ju size=%ju\n",
1019 de->leaf.data_crc,
1020 (intmax_t)de->u.de.ref_blks,
1021 (intmax_t)de->u.de.ref_size);
1024 printf("end of dump ===\n");
1027 static void
1028 dedup_usage(int code)
1030 fprintf(stderr,
1031 "hammer dedup-simulate <filesystem>\n"
1032 "hammer dedup <filesystem>\n"
1034 exit(code);