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 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"
25 uint32_t net_checksum_add_cont(int len
, uint8_t *buf
, int seq
)
30 for (i
= seq
; i
< seq
+ len
; i
++) {
32 sum
+= (uint32_t)buf
[i
- seq
];
34 sum
+= (uint32_t)buf
[i
- seq
] << 8;
40 uint16_t net_checksum_finish(uint32_t sum
)
43 sum
= (sum
& 0xFFFF)+(sum
>> 16);
47 uint16_t net_checksum_tcpudp(uint16_t length
, uint16_t proto
,
48 uint8_t *addrs
, uint8_t *buf
)
52 sum
+= net_checksum_add(length
, buf
); // payload
53 sum
+= net_checksum_add(8, addrs
); // src + dst address
54 sum
+= proto
+ length
; // protocol & length
55 return net_checksum_finish(sum
);
58 void net_checksum_calculate(uint8_t *data
, int length
)
60 int hlen
, plen
, proto
, csum_offset
;
63 /* Ensure data has complete L2 & L3 headers. */
64 if (length
< 14 + 20) {
68 if ((data
[14] & 0xf0) != 0x40)
69 return; /* not IPv4 */
70 hlen
= (data
[14] & 0x0f) * 4;
71 plen
= (data
[16] << 8 | data
[17]) - hlen
;
85 if (plen
< csum_offset
+ 2 || 14 + hlen
+ plen
> length
) {
89 data
[14+hlen
+csum_offset
] = 0;
90 data
[14+hlen
+csum_offset
+1] = 0;
91 csum
= net_checksum_tcpudp(plen
, proto
, data
+14+12, data
+14+hlen
);
92 data
[14+hlen
+csum_offset
] = csum
>> 8;
93 data
[14+hlen
+csum_offset
+1] = csum
& 0xff;
97 net_checksum_add_iov(const struct iovec
*iov
, const unsigned int iov_cnt
,
98 uint32_t iov_off
, uint32_t size
)
100 size_t iovec_off
, buf_off
;
107 for (i
= 0; i
< iov_cnt
&& size
; i
++) {
108 if (iov_off
< (iovec_off
+ iov
[i
].iov_len
)) {
109 size_t len
= MIN((iovec_off
+ iov
[i
].iov_len
) - iov_off
, size
);
110 void *chunk_buf
= iov
[i
].iov_base
+ (iov_off
- iovec_off
);
112 res
+= net_checksum_add_cont(len
, chunk_buf
, seq
);
119 iovec_off
+= iov
[i
].iov_len
;