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