1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33#include "qemu/osdep.h"
34#include "slirp.h"
35
36
37
38
39
40
41
42
43
44
45#define ADDCARRY(x) (x > 65535 ? x -= 65535 : x)
46#define REDUCE {l_util.l = sum; sum = l_util.s[0] + l_util.s[1]; \
47 (void)ADDCARRY(sum);}
48
49int cksum(struct mbuf *m, int len)
50{
51 register uint16_t *w;
52 register int sum = 0;
53 register int mlen = 0;
54 int byte_swapped = 0;
55
56 union {
57 uint8_t c[2];
58 uint16_t s;
59 } s_util;
60 union {
61 uint16_t s[2];
62 uint32_t l;
63 } l_util;
64
65 if (m->m_len == 0)
66 goto cont;
67 w = mtod(m, uint16_t *);
68
69 mlen = m->m_len;
70
71 if (len < mlen)
72 mlen = len;
73#ifdef DEBUG
74 len -= mlen;
75#endif
76
77
78
79 if ((1 & (uintptr_t)w) && (mlen > 0)) {
80 REDUCE;
81 sum <<= 8;
82 s_util.c[0] = *(uint8_t *)w;
83 w = (uint16_t *)((int8_t *)w + 1);
84 mlen--;
85 byte_swapped = 1;
86 }
87
88
89
90
91 while ((mlen -= 32) >= 0) {
92 sum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];
93 sum += w[4]; sum += w[5]; sum += w[6]; sum += w[7];
94 sum += w[8]; sum += w[9]; sum += w[10]; sum += w[11];
95 sum += w[12]; sum += w[13]; sum += w[14]; sum += w[15];
96 w += 16;
97 }
98 mlen += 32;
99 while ((mlen -= 8) >= 0) {
100 sum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];
101 w += 4;
102 }
103 mlen += 8;
104 if (mlen == 0 && byte_swapped == 0)
105 goto cont;
106 REDUCE;
107 while ((mlen -= 2) >= 0) {
108 sum += *w++;
109 }
110
111 if (byte_swapped) {
112 REDUCE;
113 sum <<= 8;
114 if (mlen == -1) {
115 s_util.c[1] = *(uint8_t *)w;
116 sum += s_util.s;
117 mlen = 0;
118 } else
119
120 mlen = -1;
121 } else if (mlen == -1)
122 s_util.c[0] = *(uint8_t *)w;
123
124cont:
125#ifdef DEBUG
126 if (len) {
127 DEBUG_ERROR((dfd, "cksum: out of data\n"));
128 DEBUG_ERROR((dfd, " len = %d\n", len));
129 }
130#endif
131 if (mlen == -1) {
132
133
134
135 s_util.c[1] = 0;
136 sum += s_util.s;
137 }
138 REDUCE;
139 return (~sum & 0xffff);
140}
141
142int ip6_cksum(struct mbuf *m)
143{
144
145
146 struct ip6 save_ip, *ip = mtod(m, struct ip6 *);
147 struct ip6_pseudohdr *ih = mtod(m, struct ip6_pseudohdr *);
148 int sum;
149
150 save_ip = *ip;
151
152 ih->ih_src = save_ip.ip_src;
153 ih->ih_dst = save_ip.ip_dst;
154 ih->ih_pl = htonl((uint32_t)ntohs(save_ip.ip_pl));
155 ih->ih_zero_hi = 0;
156 ih->ih_zero_lo = 0;
157 ih->ih_nh = save_ip.ip_nh;
158
159 sum = cksum(m, ((int)sizeof(struct ip6_pseudohdr))
160 + ntohl(ih->ih_pl));
161
162 *ip = save_ip;
163
164 return sum;
165}
166