net: Introduce Toeplitz hash calculator
[qemu.git] / include / net / checksum.h
blobdd8b4f6dc22e25c0b6cff0376539a3abbcd010be
1 /*
2 * IP checksumming functions.
3 * (c) 2008 Gerd Hoffmann <kraxel@redhat.com>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; under version 2 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, see <http://www.gnu.org/licenses/>.
18 #ifndef QEMU_NET_CHECKSUM_H
19 #define QEMU_NET_CHECKSUM_H
21 #include "qemu/bswap.h"
22 struct iovec;
24 uint32_t net_checksum_add_cont(int len, uint8_t *buf, int seq);
25 uint16_t net_checksum_finish(uint32_t sum);
26 uint16_t net_checksum_tcpudp(uint16_t length, uint16_t proto,
27 uint8_t *addrs, uint8_t *buf);
28 void net_checksum_calculate(uint8_t *data, int length);
30 static inline uint32_t
31 net_checksum_add(int len, uint8_t *buf)
33 return net_checksum_add_cont(len, buf, 0);
36 static inline uint16_t
37 net_raw_checksum(uint8_t *data, int length)
39 return net_checksum_finish(net_checksum_add(length, data));
42 /**
43 * net_checksum_add_iov: scatter-gather vector checksumming
45 * @iov: input scatter-gather array
46 * @iov_cnt: number of array elements
47 * @iov_off: starting iov offset for checksumming
48 * @size: length of data to be checksummed
50 uint32_t net_checksum_add_iov(const struct iovec *iov,
51 const unsigned int iov_cnt,
52 uint32_t iov_off, uint32_t size);
54 typedef struct toeplitz_key_st {
55 uint32_t leftmost_32_bits;
56 uint8_t *next_byte;
57 } net_toeplitz_key;
59 static inline
60 void net_toeplitz_key_init(net_toeplitz_key *key, uint8_t *key_bytes)
62 key->leftmost_32_bits = be32_to_cpu(*(uint32_t *)key_bytes);
63 key->next_byte = key_bytes + sizeof(uint32_t);
66 static inline
67 void net_toeplitz_add(uint32_t *result,
68 uint8_t *input,
69 uint32_t len,
70 net_toeplitz_key *key)
72 register uint32_t accumulator = *result;
73 register uint32_t leftmost_32_bits = key->leftmost_32_bits;
74 register uint32_t byte;
76 for (byte = 0; byte < len; byte++) {
77 register uint8_t input_byte = input[byte];
78 register uint8_t key_byte = *(key->next_byte++);
79 register uint8_t bit;
81 for (bit = 0; bit < 8; bit++) {
82 if (input_byte & (1 << 7)) {
83 accumulator ^= leftmost_32_bits;
86 leftmost_32_bits =
87 (leftmost_32_bits << 1) | ((key_byte & (1 << 7)) >> 7);
89 input_byte <<= 1;
90 key_byte <<= 1;
94 key->leftmost_32_bits = leftmost_32_bits;
95 *result = accumulator;
98 #endif /* QEMU_NET_CHECKSUM_H */