hash.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // SPDX-License-Identifier: GPL-2.0+
  2. #include <asm/unaligned.h>
  3. #include <linux/xxhash.h>
  4. #include <linux/types.h>
  5. #include <u-boot/sha256.h>
  6. #include <u-boot/blake2.h>
  7. #include <u-boot/crc.h>
  8. static u32 btrfs_crc32c_table[256];
  9. void btrfs_hash_init(void)
  10. {
  11. static int inited = 0;
  12. if (!inited) {
  13. crc32c_init(btrfs_crc32c_table, 0x82F63B78);
  14. inited = 1;
  15. }
  16. }
  17. int hash_sha256(const u8 *buf, size_t length, u8 *out)
  18. {
  19. sha256_context ctx;
  20. sha256_starts(&ctx);
  21. sha256_update(&ctx, buf, length);
  22. sha256_finish(&ctx, out);
  23. return 0;
  24. }
  25. int hash_xxhash(const u8 *buf, size_t length, u8 *out)
  26. {
  27. u64 hash;
  28. hash = xxh64(buf, length, 0);
  29. put_unaligned_le64(hash, out);
  30. return 0;
  31. }
  32. /* We use the full CSUM_SIZE(32) for BLAKE2B */
  33. #define BTRFS_BLAKE2_HASH_SIZE 32
  34. int hash_blake2(const u8 *buf, size_t length, u8 *out)
  35. {
  36. blake2b_state S;
  37. blake2b_init(&S, BTRFS_BLAKE2_HASH_SIZE);
  38. blake2b_update(&S, buf, length);
  39. blake2b_final(&S, out, BTRFS_BLAKE2_HASH_SIZE);
  40. return 0;
  41. }
  42. int hash_crc32c(const u8 *buf, size_t length, u8 *out)
  43. {
  44. u32 crc;
  45. crc = crc32c_cal((u32)~0, (char *)buf, length, btrfs_crc32c_table);
  46. put_unaligned_le32(~crc, out);
  47. return 0;
  48. }
  49. u32 crc32c(u32 seed, const void * data, size_t len)
  50. {
  51. return crc32c_cal(seed, data, len, btrfs_crc32c_table);
  52. }