1 /* 2 * Copyright (c) 1988, 1992, 1993 3 * The Regents of the University of California. All rights reserved. 4 * 5 * %sccs.include.redist.c% 6 * 7 * @(#)in_cksum.c 8.1 (Berkeley) 06/10/93 8 */ 9 10 #include <sys/param.h> 11 #include <sys/mbuf.h> 12 13 /* 14 * Checksum routine for Internet Protocol family headers (Portable Version). 15 * 16 * This routine is very heavily used in the network 17 * code and should be modified for each CPU to be as fast as possible. 18 */ 19 20 #define ADDCARRY(x) (x > 65535 ? x -= 65535 : x) 21 #define REDUCE {l_util.l = sum; sum = l_util.s[0] + l_util.s[1]; ADDCARRY(sum);} 22 23 int 24 in_cksum(m, len) 25 register struct mbuf *m; 26 register int len; 27 { 28 register u_short *w; 29 register int sum = 0; 30 register int mlen = 0; 31 int byte_swapped = 0; 32 33 union { 34 char c[2]; 35 u_short s; 36 } s_util; 37 union { 38 u_short s[2]; 39 long l; 40 } l_util; 41 42 for (;m && len; m = m->m_next) { 43 if (m->m_len == 0) 44 continue; 45 w = mtod(m, u_short *); 46 if (mlen == -1) { 47 /* 48 * The first byte of this mbuf is the continuation 49 * of a word spanning between this mbuf and the 50 * last mbuf. 51 * 52 * s_util.c[0] is already saved when scanning previous 53 * mbuf. 54 */ 55 s_util.c[1] = *(char *)w; 56 sum += s_util.s; 57 w = (u_short *)((char *)w + 1); 58 mlen = m->m_len - 1; 59 len--; 60 } else 61 mlen = m->m_len; 62 if (len < mlen) 63 mlen = len; 64 len -= mlen; 65 /* 66 * Force to even boundary. 67 */ 68 if ((1 & (int) w) && (mlen > 0)) { 69 REDUCE; 70 sum <<= 8; 71 s_util.c[0] = *(u_char *)w; 72 w = (u_short *)((char *)w + 1); 73 mlen--; 74 byte_swapped = 1; 75 } 76 /* 77 * Unroll the loop to make overhead from 78 * branches &c small. 79 */ 80 while ((mlen -= 32) >= 0) { 81 sum += w[0]; sum += w[1]; sum += w[2]; sum += w[3]; 82 sum += w[4]; sum += w[5]; sum += w[6]; sum += w[7]; 83 sum += w[8]; sum += w[9]; sum += w[10]; sum += w[11]; 84 sum += w[12]; sum += w[13]; sum += w[14]; sum += w[15]; 85 w += 16; 86 } 87 mlen += 32; 88 while ((mlen -= 8) >= 0) { 89 sum += w[0]; sum += w[1]; sum += w[2]; sum += w[3]; 90 w += 4; 91 } 92 mlen += 8; 93 if (mlen == 0 && byte_swapped == 0) 94 continue; 95 REDUCE; 96 while ((mlen -= 2) >= 0) { 97 sum += *w++; 98 } 99 if (byte_swapped) { 100 REDUCE; 101 sum <<= 8; 102 byte_swapped = 0; 103 if (mlen == -1) { 104 s_util.c[1] = *(char *)w; 105 sum += s_util.s; 106 mlen = 0; 107 } else 108 mlen = -1; 109 } else if (mlen == -1) 110 s_util.c[0] = *(char *)w; 111 } 112 if (len) 113 printf("cksum: out of data\n"); 114 if (mlen == -1) { 115 /* The last mbuf has odd # of bytes. Follow the 116 standard (the odd byte may be shifted left by 8 bits 117 or not as determined by endian-ness of the machine) */ 118 s_util.c[1] = 0; 119 sum += s_util.s; 120 } 121 REDUCE; 122 return (~sum & 0xffff); 123 } 124