sbin/hammer: Add /* not reached */ (missing ones in 052fd72b)
[dragonfly.git] / sbin / hammer / cmd_dedup.c
blobe1b3a64d513faa868f8c11934d52e4b4f957903d
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);
205 /* not reached */
208 glob_fd = getpfs(&glob_pfs, av[0]);
211 * Collection passes (memory limited)
213 printf("Dedup-simulate running\n");
214 do {
215 DedupCrcStart = DedupCrcEnd;
216 DedupCrcEnd = 0;
217 MemoryUse = 0;
219 if (VerboseOpt) {
220 printf("B-Tree pass crc-range %08x-max\n",
221 DedupCrcStart);
222 fflush(stdout);
224 scan_pfs(av[0], collect_btree_elm, "simu-pass");
226 if (VerboseOpt >= 2)
227 dump_simulated_dedup();
230 * Calculate simulated dedup ratio and get rid of the tree
232 while ((sim_de = RB_ROOT(&sim_dedup_tree)) != NULL) {
233 assert(sim_de->ref_blks != 0);
234 dedup_ref_size += sim_de->ref_size;
235 dedup_alloc_size += sim_de->ref_size / sim_de->ref_blks;
237 RB_REMOVE(sim_dedup_entry_rb_tree, &sim_dedup_tree, sim_de);
238 free(sim_de);
240 if (DedupCrcEnd && VerboseOpt == 0)
241 printf(".");
242 } while (DedupCrcEnd);
244 printf("Dedup-simulate %s succeeded\n", av[0]);
245 relpfs(glob_fd, &glob_pfs);
247 printf("Simulated dedup ratio = %.2f\n",
248 (dedup_alloc_size != 0) ?
249 (double)dedup_ref_size / dedup_alloc_size : 0);
253 * dedup <filesystem>
255 void
256 hammer_cmd_dedup(char **av, int ac)
258 struct dedup_entry *de;
259 struct sha_dedup_entry *sha_de;
260 struct pass2_dedup_entry *pass2_de;
261 char *tmp;
262 char buf[8];
263 int needfree = 0;
265 if (TimeoutOpt > 0)
266 alarm(TimeoutOpt);
268 if (ac != 1) {
269 dedup_usage(1);
270 /* not reached */
273 STAILQ_INIT(&pass2_dedup_queue);
275 glob_fd = getpfs(&glob_pfs, av[0]);
278 * A cycle file is _required_ for resuming dedup after the timeout
279 * specified with -t has expired. If no -c option, then place a
280 * .dedup.cycle file either in the PFS snapshots directory or in
281 * the default snapshots directory.
283 if (!CyclePath) {
284 if (glob_pfs.ondisk->snapshots[0] != '/')
285 asprintf(&tmp, "%s/%s/.dedup.cycle",
286 SNAPSHOTS_BASE, av[0]);
287 else
288 asprintf(&tmp, "%s/.dedup.cycle",
289 glob_pfs.ondisk->snapshots);
290 CyclePath = tmp;
291 needfree = 1;
295 * Pre-pass to cache the btree
297 scan_pfs(av[0], count_btree_elm, "pre-pass ");
298 DedupTotalRecords = DedupCurrentRecords;
301 * Collection passes (memory limited)
303 printf("Dedup running\n");
304 do {
305 DedupCrcStart = DedupCrcEnd;
306 DedupCrcEnd = 0;
307 MemoryUse = 0;
309 if (VerboseOpt) {
310 printf("B-Tree pass crc-range %08x-max\n",
311 DedupCrcStart);
312 fflush(stdout);
314 scan_pfs(av[0], process_btree_elm, "main-pass");
316 while ((pass2_de = STAILQ_FIRST(&pass2_dedup_queue)) != NULL) {
317 if (process_btree_elm(&pass2_de->leaf, DEDUP_PASS2))
318 dedup_skipped_size -= pass2_de->leaf.data_len;
320 STAILQ_REMOVE_HEAD(&pass2_dedup_queue, sq_entry);
321 free(pass2_de);
323 assert(STAILQ_EMPTY(&pass2_dedup_queue));
325 if (VerboseOpt >= 2)
326 dump_real_dedup();
329 * Calculate dedup ratio and get rid of the trees
331 while ((de = RB_ROOT(&dedup_tree)) != NULL) {
332 if (de->flags & HAMMER_DEDUP_ENTRY_FICTITIOUS) {
333 while ((sha_de = RB_ROOT(&de->u.fict_root)) != NULL) {
334 assert(sha_de->ref_blks != 0);
335 dedup_ref_size += sha_de->ref_size;
336 dedup_alloc_size += sha_de->ref_size / sha_de->ref_blks;
338 RB_REMOVE(sha_dedup_entry_rb_tree,
339 &de->u.fict_root, sha_de);
340 free(sha_de);
342 assert(RB_EMPTY(&de->u.fict_root));
343 } else {
344 assert(de->u.de.ref_blks != 0);
345 dedup_ref_size += de->u.de.ref_size;
346 dedup_alloc_size += de->u.de.ref_size / de->u.de.ref_blks;
349 RB_REMOVE(dedup_entry_rb_tree, &dedup_tree, de);
350 free(de);
352 assert(RB_EMPTY(&dedup_tree));
353 if (DedupCrcEnd && VerboseOpt == 0)
354 printf(".");
355 } while (DedupCrcEnd);
357 printf("Dedup %s succeeded\n", av[0]);
358 relpfs(glob_fd, &glob_pfs);
360 humanize_unsigned(buf, sizeof(buf), dedup_ref_size, "B", 1024);
361 printf("Dedup ratio = %.2f (in this run)\n"
362 " %8s referenced\n",
363 ((dedup_alloc_size != 0) ?
364 (double)dedup_ref_size / dedup_alloc_size : 0),
367 humanize_unsigned(buf, sizeof(buf), dedup_alloc_size, "B", 1024);
368 printf(" %8s allocated\n", buf);
369 humanize_unsigned(buf, sizeof(buf), dedup_skipped_size, "B", 1024);
370 printf(" %8s skipped\n", buf);
371 printf(" %8jd CRC collisions\n"
372 " %8jd SHA collisions\n"
373 " %8jd big-block underflows\n"
374 " %8jd new dedup records\n"
375 " %8jd new dedup bytes\n",
376 (intmax_t)dedup_crc_failures,
377 (intmax_t)dedup_sha_failures,
378 (intmax_t)dedup_underflows,
379 (intmax_t)dedup_successes_count,
380 (intmax_t)dedup_successes_bytes
383 /* Once completed remove cycle file */
384 hammer_reset_cycle();
386 /* We don't want to mess up with other directives */
387 if (needfree) {
388 free(tmp);
389 CyclePath = NULL;
393 static int
394 count_btree_elm(hammer_btree_leaf_elm_t scan_leaf __unused, int flags __unused)
396 return(1);
399 static int
400 collect_btree_elm(hammer_btree_leaf_elm_t scan_leaf, int flags __unused)
402 struct sim_dedup_entry *sim_de;
405 * If we are using too much memory we have to clean some out, which
406 * will cause the run to use multiple passes. Be careful of integer
407 * overflows!
409 if (MemoryUse > MemoryLimit) {
410 DedupCrcEnd = DedupCrcStart +
411 (uint32_t)(DedupCrcEnd - DedupCrcStart - 1) / 2;
412 if (VerboseOpt) {
413 printf("memory limit crc-range %08x-%08x\n",
414 DedupCrcStart, DedupCrcEnd);
415 fflush(stdout);
417 for (;;) {
418 sim_de = RB_MAX(sim_dedup_entry_rb_tree,
419 &sim_dedup_tree);
420 if (sim_de == NULL || sim_de->crc < DedupCrcEnd)
421 break;
422 RB_REMOVE(sim_dedup_entry_rb_tree,
423 &sim_dedup_tree, sim_de);
424 MemoryUse -= sizeof(*sim_de);
425 free(sim_de);
430 * Collect statistics based on the CRC only, do not try to read
431 * any data blocks or run SHA hashes.
433 sim_de = RB_LOOKUP(sim_dedup_entry_rb_tree, &sim_dedup_tree,
434 scan_leaf->data_crc);
436 if (sim_de == NULL) {
437 sim_de = calloc(1, sizeof(*sim_de));
438 sim_de->crc = scan_leaf->data_crc;
439 RB_INSERT(sim_dedup_entry_rb_tree, &sim_dedup_tree, sim_de);
440 MemoryUse += sizeof(*sim_de);
443 sim_de->ref_blks += 1;
444 sim_de->ref_size += scan_leaf->data_len;
445 return (1);
448 static __inline int
449 validate_dedup_pair(hammer_btree_leaf_elm_t p, hammer_btree_leaf_elm_t q)
451 if (HAMMER_ZONE(p->data_offset) != HAMMER_ZONE(q->data_offset))
452 return (1);
453 if (p->data_len != q->data_len)
454 return (1);
456 return (0);
459 #define DEDUP_TECH_FAILURE 1
460 #define DEDUP_CMP_FAILURE 2
461 #define DEDUP_INVALID_ZONE 3
462 #define DEDUP_UNDERFLOW 4
463 #define DEDUP_VERS_FAILURE 5
465 static __inline int
466 deduplicate(hammer_btree_leaf_elm_t p, hammer_btree_leaf_elm_t q)
468 struct hammer_ioc_dedup dedup;
470 bzero(&dedup, sizeof(dedup));
473 * If data_offset fields are the same there is no need to run ioctl,
474 * candidate is already dedup'ed.
476 if (p->data_offset == q->data_offset)
477 return (0);
479 dedup.elm1 = p->base;
480 dedup.elm2 = q->base;
481 RunningIoctl = 1;
482 if (ioctl(glob_fd, HAMMERIOC_DEDUP, &dedup) < 0) {
483 if (errno == EOPNOTSUPP)
484 return (DEDUP_VERS_FAILURE); /* must be at least version 5 */
485 /* Technical failure - locking or w/e */
486 return (DEDUP_TECH_FAILURE);
488 if (dedup.head.flags & HAMMER_IOC_DEDUP_CMP_FAILURE)
489 return (DEDUP_CMP_FAILURE);
490 if (dedup.head.flags & HAMMER_IOC_DEDUP_INVALID_ZONE)
491 return (DEDUP_INVALID_ZONE);
492 if (dedup.head.flags & HAMMER_IOC_DEDUP_UNDERFLOW)
493 return (DEDUP_UNDERFLOW);
494 RunningIoctl = 0;
495 ++dedup_successes_count;
496 dedup_successes_bytes += p->data_len;
497 return (0);
500 static int
501 process_btree_elm(hammer_btree_leaf_elm_t scan_leaf, int flags)
503 struct dedup_entry *de;
504 struct sha_dedup_entry *sha_de, temp;
505 struct pass2_dedup_entry *pass2_de;
506 int error;
509 * If we are using too much memory we have to clean some out, which
510 * will cause the run to use multiple passes. Be careful of integer
511 * overflows!
513 while (MemoryUse > MemoryLimit) {
514 DedupCrcEnd = DedupCrcStart +
515 (uint32_t)(DedupCrcEnd - DedupCrcStart - 1) / 2;
516 if (VerboseOpt) {
517 printf("memory limit crc-range %08x-%08x\n",
518 DedupCrcStart, DedupCrcEnd);
519 fflush(stdout);
522 for (;;) {
523 de = RB_MAX(dedup_entry_rb_tree, &dedup_tree);
524 if (de == NULL || de->leaf.data_crc < DedupCrcEnd)
525 break;
526 if (de->flags & HAMMER_DEDUP_ENTRY_FICTITIOUS) {
527 while ((sha_de = RB_ROOT(&de->u.fict_root)) !=
528 NULL) {
529 RB_REMOVE(sha_dedup_entry_rb_tree,
530 &de->u.fict_root, sha_de);
531 MemoryUse -= sizeof(*sha_de);
532 free(sha_de);
535 RB_REMOVE(dedup_entry_rb_tree, &dedup_tree, de);
536 MemoryUse -= sizeof(*de);
537 free(de);
542 * Collect statistics based on the CRC. Colliding CRCs usually
543 * cause a SHA sub-tree to be created under the de.
545 * Trivial case if de not found.
547 de = RB_LOOKUP(dedup_entry_rb_tree, &dedup_tree, scan_leaf->data_crc);
548 if (de == NULL) {
549 de = calloc(1, sizeof(*de));
550 de->leaf = *scan_leaf;
551 RB_INSERT(dedup_entry_rb_tree, &dedup_tree, de);
552 MemoryUse += sizeof(*de);
553 goto upgrade_stats;
557 * Found entry in CRC tree
559 if (de->flags & HAMMER_DEDUP_ENTRY_FICTITIOUS) {
561 * Optimize the case where a CRC failure results in multiple
562 * SHA entries. If we unconditionally issue a data-read a
563 * degenerate situation where a colliding CRC's second SHA
564 * entry contains the lion's share of the deduplication
565 * candidates will result in excessive data block reads.
567 * Deal with the degenerate case by looking for a matching
568 * data_offset/data_len in the SHA elements we already have
569 * before reading the data block and generating a new SHA.
571 RB_FOREACH(sha_de, sha_dedup_entry_rb_tree, &de->u.fict_root) {
572 if (sha_de->leaf.data_offset ==
573 scan_leaf->data_offset &&
574 sha_de->leaf.data_len == scan_leaf->data_len) {
575 memcpy(temp.sha_hash, sha_de->sha_hash,
576 SHA256_DIGEST_LENGTH);
577 break;
582 * Entry in CRC tree is fictitious, so we already had problems
583 * with this CRC. Upgrade (compute SHA) the candidate and
584 * dive into SHA subtree. If upgrade fails insert the candidate
585 * into Pass2 list (it will be processed later).
587 if (sha_de == NULL) {
588 if (upgrade_chksum(scan_leaf, temp.sha_hash))
589 goto pass2_insert;
591 sha_de = RB_FIND(sha_dedup_entry_rb_tree,
592 &de->u.fict_root, &temp);
596 * Nothing in SHA subtree so far, so this is a new
597 * 'dataset'. Insert new entry into SHA subtree.
599 if (sha_de == NULL) {
600 sha_de = calloc(1, sizeof(*sha_de));
601 sha_de->leaf = *scan_leaf;
602 memcpy(sha_de->sha_hash, temp.sha_hash,
603 SHA256_DIGEST_LENGTH);
604 RB_INSERT(sha_dedup_entry_rb_tree, &de->u.fict_root,
605 sha_de);
606 MemoryUse += sizeof(*sha_de);
607 goto upgrade_stats_sha;
611 * Found entry in SHA subtree, it means we have a potential
612 * dedup pair. Validate it (zones have to match and data_len
613 * field have to be the same too. If validation fails, treat
614 * it as a SHA collision (jump to sha256_failure).
616 if (validate_dedup_pair(&sha_de->leaf, scan_leaf))
617 goto sha256_failure;
620 * We have a valid dedup pair (SHA match, validated).
622 * In case of technical failure (dedup pair was good, but
623 * ioctl failed anyways) insert the candidate into Pass2 list
624 * (we will try to dedup it after we are done with the rest of
625 * the tree).
627 * If ioctl fails because either of blocks is in the non-dedup
628 * zone (we can dedup only in LARGE_DATA and SMALL_DATA) don't
629 * bother with the candidate and terminate early.
631 * If ioctl fails because of big-block underflow replace the
632 * leaf node that found dedup entry represents with scan_leaf.
634 error = deduplicate(&sha_de->leaf, scan_leaf);
635 switch(error) {
636 case 0:
637 goto upgrade_stats_sha;
638 case DEDUP_TECH_FAILURE:
639 goto pass2_insert;
640 case DEDUP_CMP_FAILURE:
641 goto sha256_failure;
642 case DEDUP_INVALID_ZONE:
643 goto terminate_early;
644 case DEDUP_UNDERFLOW:
645 ++dedup_underflows;
646 sha_de->leaf = *scan_leaf;
647 memcpy(sha_de->sha_hash, temp.sha_hash,
648 SHA256_DIGEST_LENGTH);
649 goto upgrade_stats_sha;
650 case DEDUP_VERS_FAILURE:
651 errx(1, "HAMMER filesystem must be at least "
652 "version 5 to dedup");
653 /* not reached */
654 default:
655 fprintf(stderr, "Unknown error\n");
656 goto terminate_early;
660 * Ooh la la.. SHA-256 collision. Terminate early, there's
661 * nothing we can do here.
663 sha256_failure:
664 ++dedup_sha_failures;
665 goto terminate_early;
666 } else {
668 * Candidate CRC is good for now (we found an entry in CRC
669 * tree and it's not fictitious). This means we have a
670 * potential dedup pair.
672 if (validate_dedup_pair(&de->leaf, scan_leaf))
673 goto crc_failure;
676 * We have a valid dedup pair (CRC match, validated)
678 error = deduplicate(&de->leaf, scan_leaf);
679 switch(error) {
680 case 0:
681 goto upgrade_stats;
682 case DEDUP_TECH_FAILURE:
683 goto pass2_insert;
684 case DEDUP_CMP_FAILURE:
685 goto crc_failure;
686 case DEDUP_INVALID_ZONE:
687 goto terminate_early;
688 case DEDUP_UNDERFLOW:
689 ++dedup_underflows;
690 de->leaf = *scan_leaf;
691 goto upgrade_stats;
692 case DEDUP_VERS_FAILURE:
693 errx(1, "HAMMER filesystem must be at least "
694 "version 5 to dedup");
695 /* not reached */
696 default:
697 fprintf(stderr, "Unknown error\n");
698 goto terminate_early;
701 crc_failure:
703 * We got a CRC collision - either ioctl failed because of
704 * the comparison failure or validation of the potential
705 * dedup pair went bad. In all cases insert both blocks
706 * into SHA subtree (this requires checksum upgrade) and mark
707 * entry that corresponds to this CRC in the CRC tree
708 * fictitious, so that all futher operations with this CRC go
709 * through SHA subtree.
711 ++dedup_crc_failures;
714 * Insert block that was represented by now fictitious dedup
715 * entry (create a new SHA entry and preserve stats of the
716 * old CRC one). If checksum upgrade fails insert the
717 * candidate into Pass2 list and return - keep both trees
718 * unmodified.
720 sha_de = calloc(1, sizeof(*sha_de));
721 sha_de->leaf = de->leaf;
722 sha_de->ref_blks = de->u.de.ref_blks;
723 sha_de->ref_size = de->u.de.ref_size;
724 if (upgrade_chksum(&sha_de->leaf, sha_de->sha_hash)) {
725 free(sha_de);
726 goto pass2_insert;
728 MemoryUse += sizeof(*sha_de);
730 RB_INIT(&de->u.fict_root);
732 * Here we can insert without prior checking because the tree
733 * is empty at this point
735 RB_INSERT(sha_dedup_entry_rb_tree, &de->u.fict_root, sha_de);
738 * Mark entry in CRC tree fictitious
740 de->flags |= HAMMER_DEDUP_ENTRY_FICTITIOUS;
743 * Upgrade checksum of the candidate and insert it into
744 * SHA subtree. If upgrade fails insert the candidate into
745 * Pass2 list.
747 if (upgrade_chksum(scan_leaf, temp.sha_hash))
748 goto pass2_insert;
749 sha_de = RB_FIND(sha_dedup_entry_rb_tree, &de->u.fict_root,
750 &temp);
751 if (sha_de != NULL)
752 /* There is an entry with this SHA already, but the only
753 * RB-tree element at this point is that entry we just
754 * added. We know for sure these blocks are different
755 * (this is crc_failure branch) so treat it as SHA
756 * collision.
758 goto sha256_failure;
760 sha_de = calloc(1, sizeof(*sha_de));
761 sha_de->leaf = *scan_leaf;
762 memcpy(sha_de->sha_hash, temp.sha_hash, SHA256_DIGEST_LENGTH);
763 RB_INSERT(sha_dedup_entry_rb_tree, &de->u.fict_root, sha_de);
764 MemoryUse += sizeof(*sha_de);
765 goto upgrade_stats_sha;
768 upgrade_stats:
769 de->u.de.ref_blks += 1;
770 de->u.de.ref_size += scan_leaf->data_len;
771 return (1);
773 upgrade_stats_sha:
774 sha_de->ref_blks += 1;
775 sha_de->ref_size += scan_leaf->data_len;
776 return (1);
778 pass2_insert:
780 * If in pass2 mode don't insert anything, fall through to
781 * terminate_early
783 if ((flags & DEDUP_PASS2) == 0) {
784 pass2_de = calloc(1, sizeof(*pass2_de));
785 pass2_de->leaf = *scan_leaf;
786 STAILQ_INSERT_TAIL(&pass2_dedup_queue, pass2_de, sq_entry);
787 dedup_skipped_size += scan_leaf->data_len;
788 return (1);
791 terminate_early:
793 * Early termination path. Fixup stats.
795 dedup_alloc_size += scan_leaf->data_len;
796 dedup_ref_size += scan_leaf->data_len;
797 return (0);
800 static int
801 upgrade_chksum(hammer_btree_leaf_elm_t leaf, uint8_t *sha_hash)
803 struct hammer_ioc_data data;
804 char *buf = malloc(DEDUP_BUF);
805 SHA256_CTX ctx;
806 int error;
808 bzero(&data, sizeof(data));
809 data.elm = leaf->base;
810 data.ubuf = buf;
811 data.size = DEDUP_BUF;
813 error = 0;
814 if (ioctl(glob_fd, HAMMERIOC_GET_DATA, &data) < 0) {
815 fprintf(stderr, "Get-data failed: %s\n", strerror(errno));
816 error = 1;
817 goto done;
819 DedupDataReads += leaf->data_len;
821 if (data.leaf.data_len != leaf->data_len) {
822 error = 1;
823 goto done;
826 if (data.leaf.base.btype == HAMMER_BTREE_TYPE_RECORD &&
827 data.leaf.base.rec_type == HAMMER_RECTYPE_DATA) {
828 SHA256_Init(&ctx);
829 SHA256_Update(&ctx, (void *)buf, data.leaf.data_len);
830 SHA256_Final(sha_hash, &ctx);
833 done:
834 free(buf);
835 return (error);
838 static void
839 sigAlrm(int signo __unused)
841 SigAlrmFlag = 1;
844 static void
845 sigInfo(int signo __unused)
847 SigInfoFlag = 1;
850 static void
851 scan_pfs(char *filesystem, scan_pfs_cb_t func, const char *id)
853 struct hammer_ioc_mirror_rw mirror;
854 hammer_ioc_mrecord_any_t mrec;
855 struct hammer_btree_leaf_elm elm;
856 char *buf = malloc(DEDUP_BUF);
857 char buf1[8];
858 char buf2[8];
859 int offset, bytes;
861 SigInfoFlag = 0;
862 DedupDataReads = 0;
863 DedupCurrentRecords = 0;
864 signal(SIGINFO, sigInfo);
865 signal(SIGALRM, sigAlrm);
868 * Deduplication happens per element so hammer(8) is in full
869 * control of the ioctl()s to actually perform it. SIGALRM
870 * needs to be handled within hammer(8) but a checkpoint
871 * is needed for resuming. Use cycle file for that.
873 * Try to obtain the previous obj_id from the cycle file and
874 * if not available just start from the beginning.
876 bzero(&mirror, sizeof(mirror));
877 hammer_key_beg_init(&mirror.key_beg);
878 hammer_get_cycle(&mirror.key_beg, &mirror.tid_beg);
880 if (mirror.key_beg.obj_id != (int64_t)HAMMER_MIN_OBJID) {
881 if (VerboseOpt)
882 fprintf(stderr, "%s: mirror-read: Resuming at object %016jx\n",
883 id, (uintmax_t)mirror.key_beg.obj_id);
886 hammer_key_end_init(&mirror.key_end);
888 mirror.tid_beg = glob_pfs.ondisk->sync_beg_tid;
889 mirror.tid_end = glob_pfs.ondisk->sync_end_tid;
890 mirror.head.flags |= HAMMER_IOC_MIRROR_NODATA; /* we want only keys */
891 mirror.ubuf = buf;
892 mirror.size = DEDUP_BUF;
893 mirror.pfs_id = glob_pfs.pfs_id;
894 mirror.shared_uuid = glob_pfs.ondisk->shared_uuid;
896 if (VerboseOpt && DedupCrcStart == 0) {
897 printf("%s %s: objspace %016jx:%04x %016jx:%04x\n",
898 id, filesystem,
899 (uintmax_t)mirror.key_beg.obj_id,
900 mirror.key_beg.localization,
901 (uintmax_t)mirror.key_end.obj_id,
902 mirror.key_end.localization);
903 printf("%s %s: pfs_id %d\n",
904 id, filesystem, glob_pfs.pfs_id);
906 fflush(stdout);
907 fflush(stderr);
909 do {
910 mirror.count = 0;
911 mirror.pfs_id = glob_pfs.pfs_id;
912 mirror.shared_uuid = glob_pfs.ondisk->shared_uuid;
913 if (ioctl(glob_fd, HAMMERIOC_MIRROR_READ, &mirror) < 0) {
914 err(1, "Mirror-read %s failed", filesystem);
915 /* not reached */
917 if (mirror.head.flags & HAMMER_IOC_HEAD_ERROR) {
918 errx(1, "Mirror-read %s fatal error %d",
919 filesystem, mirror.head.error);
920 /* not reached */
922 if (mirror.count) {
923 offset = 0;
924 while (offset < mirror.count) {
925 mrec = (void *)((char *)buf + offset);
926 bytes = HAMMER_HEAD_DOALIGN(mrec->head.rec_size);
927 if (offset + bytes > mirror.count) {
928 errx(1, "Misaligned record");
929 /* not reached */
931 assert((mrec->head.type &
932 HAMMER_MRECF_TYPE_MASK) ==
933 HAMMER_MREC_TYPE_REC);
934 offset += bytes;
935 elm = mrec->rec.leaf;
936 if (elm.base.btype != HAMMER_BTREE_TYPE_RECORD)
937 continue;
938 if (elm.base.rec_type != HAMMER_RECTYPE_DATA)
939 continue;
940 ++DedupCurrentRecords;
941 if (DedupCrcStart != DedupCrcEnd) {
942 if (elm.data_crc < DedupCrcStart)
943 continue;
944 if (DedupCrcEnd &&
945 elm.data_crc >= DedupCrcEnd) {
946 continue;
949 func(&elm, 0);
952 mirror.key_beg = mirror.key_cur;
953 if (DidInterrupt || SigAlrmFlag) {
954 if (VerboseOpt)
955 fprintf(stderr, "%s\n",
956 (DidInterrupt ? "Interrupted" : "Timeout"));
957 hammer_set_cycle(&mirror.key_cur, mirror.tid_beg);
958 if (VerboseOpt)
959 fprintf(stderr, "Cyclefile %s updated for "
960 "continuation\n", CyclePath);
961 exit(1);
963 if (SigInfoFlag) {
964 if (DedupTotalRecords) {
965 humanize_unsigned(buf1, sizeof(buf1),
966 DedupDataReads,
967 "B", 1024);
968 humanize_unsigned(buf2, sizeof(buf2),
969 dedup_successes_bytes,
970 "B", 1024);
971 fprintf(stderr, "%s count %7jd/%jd "
972 "(%02d.%02d%%) "
973 "ioread %s newddup %s\n",
975 (intmax_t)DedupCurrentRecords,
976 (intmax_t)DedupTotalRecords,
977 (int)(DedupCurrentRecords * 100 /
978 DedupTotalRecords),
979 (int)(DedupCurrentRecords * 10000 /
980 DedupTotalRecords % 100),
981 buf1, buf2);
982 } else {
983 fprintf(stderr, "%s count %-7jd\n",
985 (intmax_t)DedupCurrentRecords);
987 SigInfoFlag = 0;
989 } while (mirror.count != 0);
991 signal(SIGINFO, SIG_IGN);
992 signal(SIGALRM, SIG_IGN);
994 free(buf);
997 static void
998 dump_simulated_dedup(void)
1000 struct sim_dedup_entry *sim_de;
1002 printf("=== Dumping simulated dedup entries:\n");
1003 RB_FOREACH(sim_de, sim_dedup_entry_rb_tree, &sim_dedup_tree) {
1004 printf("\tcrc=%08x cnt=%ju size=%ju\n",
1005 sim_de->crc,
1006 (intmax_t)sim_de->ref_blks,
1007 (intmax_t)sim_de->ref_size);
1009 printf("end of dump ===\n");
1012 static void
1013 dump_real_dedup(void)
1015 struct dedup_entry *de;
1016 struct sha_dedup_entry *sha_de;
1017 int i;
1019 printf("=== Dumping dedup entries:\n");
1020 RB_FOREACH(de, dedup_entry_rb_tree, &dedup_tree) {
1021 if (de->flags & HAMMER_DEDUP_ENTRY_FICTITIOUS) {
1022 printf("\tcrc=%08x fictitious\n", de->leaf.data_crc);
1024 RB_FOREACH(sha_de, sha_dedup_entry_rb_tree, &de->u.fict_root) {
1025 printf("\t\tcrc=%08x cnt=%ju size=%ju\n\t"
1026 "\t\tsha=",
1027 sha_de->leaf.data_crc,
1028 (intmax_t)sha_de->ref_blks,
1029 (intmax_t)sha_de->ref_size);
1030 for (i = 0; i < SHA256_DIGEST_LENGTH; ++i)
1031 printf("%02x", sha_de->sha_hash[i]);
1032 printf("\n");
1034 } else {
1035 printf("\tcrc=%08x cnt=%ju size=%ju\n",
1036 de->leaf.data_crc,
1037 (intmax_t)de->u.de.ref_blks,
1038 (intmax_t)de->u.de.ref_size);
1041 printf("end of dump ===\n");
1044 static void
1045 dedup_usage(int code)
1047 fprintf(stderr,
1048 "hammer dedup-simulate <filesystem>\n"
1049 "hammer dedup <filesystem>\n"
1051 exit(code);