xref: /dpdk/drivers/net/nfp/nfpcore/nfp_crc.c (revision f842b01aa0889a0fd3f24f48a2ed0e10f5d2d093)
1c7e9729dSAlejandro Lucero /* SPDX-License-Identifier: BSD-3-Clause
2c7e9729dSAlejandro Lucero  * Copyright(c) 2018 Netronome Systems, Inc.
3c7e9729dSAlejandro Lucero  * All rights reserved.
4c7e9729dSAlejandro Lucero  */
5c7e9729dSAlejandro Lucero 
6c7e9729dSAlejandro Lucero #include <stdio.h>
7c7e9729dSAlejandro Lucero #include <inttypes.h>
8c7e9729dSAlejandro Lucero 
9c7e9729dSAlejandro Lucero #include "nfp_crc.h"
10c7e9729dSAlejandro Lucero 
11c7e9729dSAlejandro Lucero static inline uint32_t
nfp_crc32_be_generic(uint32_t crc,unsigned char const * p,size_t len,uint32_t polynomial)12d108b9e9SChaoyong He nfp_crc32_be_generic(uint32_t crc,
13d108b9e9SChaoyong He 		unsigned char const *p,
14d108b9e9SChaoyong He 		size_t len,
15c7e9729dSAlejandro Lucero 		uint32_t polynomial)
16c7e9729dSAlejandro Lucero {
17c69debceSChaoyong He 	uint32_t i;
18*f842b01aSChaoyong He 
19c7e9729dSAlejandro Lucero 	while (len--) {
20c7e9729dSAlejandro Lucero 		crc ^= *p++ << 24;
21c7e9729dSAlejandro Lucero 		for (i = 0; i < 8; i++)
22d108b9e9SChaoyong He 			crc = (crc << 1) ^ ((crc & 0x80000000) ? polynomial : 0);
23c7e9729dSAlejandro Lucero 	}
24*f842b01aSChaoyong He 
25c7e9729dSAlejandro Lucero 	return crc;
26c7e9729dSAlejandro Lucero }
27c7e9729dSAlejandro Lucero 
28c7e9729dSAlejandro Lucero static inline uint32_t
nfp_crc32_be(uint32_t crc,unsigned char const * p,size_t len)29d108b9e9SChaoyong He nfp_crc32_be(uint32_t crc,
30d108b9e9SChaoyong He 		unsigned char const *p,
31d108b9e9SChaoyong He 		size_t len)
32c7e9729dSAlejandro Lucero {
33c7e9729dSAlejandro Lucero 	return nfp_crc32_be_generic(crc, p, len, CRCPOLY_BE);
34c7e9729dSAlejandro Lucero }
35c7e9729dSAlejandro Lucero 
36c7e9729dSAlejandro Lucero static uint32_t
nfp_crc32_posix_end(uint32_t crc,size_t total_len)37d108b9e9SChaoyong He nfp_crc32_posix_end(uint32_t crc,
38d108b9e9SChaoyong He 		size_t total_len)
39c7e9729dSAlejandro Lucero {
40c7e9729dSAlejandro Lucero 	/* Extend with the length of the string. */
41c7e9729dSAlejandro Lucero 	while (total_len != 0) {
42c7e9729dSAlejandro Lucero 		uint8_t c = total_len & 0xff;
43c7e9729dSAlejandro Lucero 
44c7e9729dSAlejandro Lucero 		crc = nfp_crc32_be(crc, &c, 1);
45c7e9729dSAlejandro Lucero 		total_len >>= 8;
46c7e9729dSAlejandro Lucero 	}
47c7e9729dSAlejandro Lucero 
48c7e9729dSAlejandro Lucero 	return ~crc;
49c7e9729dSAlejandro Lucero }
50c7e9729dSAlejandro Lucero 
51c7e9729dSAlejandro Lucero uint32_t
nfp_crc32_posix(const void * buff,size_t len)52d108b9e9SChaoyong He nfp_crc32_posix(const void *buff,
53d108b9e9SChaoyong He 		size_t len)
54c7e9729dSAlejandro Lucero {
55c7e9729dSAlejandro Lucero 	return nfp_crc32_posix_end(nfp_crc32_be(0, buff, len), len);
56c7e9729dSAlejandro Lucero }
57