2 * IP checksumming functions.
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 or later 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 #include "qemu/osdep.h"
19 #include "qemu-common.h"
20 #include "net/checksum.h"
23 uint32_t net_checksum_add_cont(int len, uint8_t *buf, int seq)
28 for (i = seq; i < seq + len; i++) {
30 sum += (uint32_t)buf[i - seq];
32 sum += (uint32_t)buf[i - seq] << 8;
38 uint16_t net_checksum_finish(uint32_t sum)
41 sum = (sum & 0xFFFF)+(sum >> 16);
45 uint16_t net_checksum_tcpudp(uint16_t length, uint16_t proto,
46 uint8_t *addrs, uint8_t *buf)
50 sum += net_checksum_add(length, buf); // payload
51 sum += net_checksum_add(8, addrs); // src + dst address
52 sum += proto + length; // protocol & length
53 return net_checksum_finish(sum);
56 void net_checksum_calculate(uint8_t *data, int length)
62 * Note: We cannot assume "data" is aligned, so the all code uses
63 * some macros that take care of possible unaligned access for
64 * struct members (just in case).
67 /* Ensure data has complete L2 & L3 headers. */
68 if (length < (sizeof(struct eth_header) + sizeof(struct ip_header))) {
72 ip = (struct ip_header *)(data + sizeof(struct eth_header));
74 if (IP_HEADER_VERSION(ip) != IP_HEADER_VERSION_4) {
75 return; /* not IPv4 */
78 ip_len = lduw_be_p(&ip->ip_len);
80 /* Last, check that we have enough data for the all IP frame */
81 if (length < ip_len) {
85 ip_len -= IP_HDR_GET_LEN(ip);
91 tcp_header *tcp = (tcp_header *)(ip + 1);
93 if (ip_len < sizeof(tcp_header)) {
98 stw_he_p(&tcp->th_sum, 0);
100 csum = net_checksum_tcpudp(ip_len, ip->ip_p,
101 (uint8_t *)&ip->ip_src,
104 /* Store computed csum */
105 stw_be_p(&tcp->th_sum, csum);
112 udp_header *udp = (udp_header *)(ip + 1);
114 if (ip_len < sizeof(udp_header)) {
119 stw_he_p(&udp->uh_sum, 0);
121 csum = net_checksum_tcpudp(ip_len, ip->ip_p,
122 (uint8_t *)&ip->ip_src,
125 /* Store computed csum */
126 stw_be_p(&udp->uh_sum, csum);
131 /* Can't handle any other protocol */
137 net_checksum_add_iov(const struct iovec *iov, const unsigned int iov_cnt,
138 uint32_t iov_off, uint32_t size, uint32_t csum_offset)
140 size_t iovec_off, buf_off;
146 for (i = 0; i < iov_cnt && size; i++) {
147 if (iov_off < (iovec_off + iov[i].iov_len)) {
148 size_t len = MIN((iovec_off + iov[i].iov_len) - iov_off , size);
149 void *chunk_buf = iov[i].iov_base + (iov_off - iovec_off);
151 res += net_checksum_add_cont(len, chunk_buf, csum_offset);
158 iovec_off += iov[i].iov_len;