1 /*
2 * Copyright (c) 2021 Workaround GmbH.
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <zephyr/sys/crc.h>
8
9 /* crc table generated from polynomial 0x1EDC6F41UL (Castagnoli) */
10 static const uint32_t crc32c_table[16] = {
11 0x00000000UL, 0x105EC76FUL, 0x20BD8EDEUL, 0x30E349B1UL,
12 0x417B1DBCUL, 0x5125DAD3UL, 0x61C69362UL, 0x7198540DUL,
13 0x82F63B78UL, 0x92A8FC17UL, 0xA24BB5A6UL, 0xB21572C9UL,
14 0xC38D26C4UL, 0xD3D3E1ABUL, 0xE330A81AUL, 0xF36E6F75UL
15 };
16
17 /* This value needs to be XORed with the final crc value once crc for
18 * the entire stream is calculated. This is a requirement of crc32c algo.
19 */
20 #define CRC32C_XOR_OUT 0xFFFFFFFFUL
21
22 /* The crc32c algorithm requires the below value as Init value at the
23 * beginning of the stream.
24 */
25 #define CRC32C_INIT 0xFFFFFFFFUL
26
crc32_c(uint32_t crc,const uint8_t * data,size_t len,bool first_pkt,bool last_pkt)27 uint32_t crc32_c(uint32_t crc, const uint8_t *data,
28 size_t len, bool first_pkt, bool last_pkt)
29 {
30 if (first_pkt) {
31 crc = CRC32C_INIT;
32 }
33
34 for (size_t i = 0; i < len; i++) {
35 crc = crc32c_table[(crc ^ data[i]) & 0x0F] ^ (crc >> 4);
36 crc = crc32c_table[(crc ^ ((uint32_t)data[i] >> 4)) & 0x0F] ^ (crc >> 4);
37 }
38
39 return last_pkt ? (crc ^ CRC32C_XOR_OUT) : crc;
40 }
41